diff --git a/.gitattributes b/.gitattributes index c77a1d5e54b6c27b47ee17767d4872be4637eeb4..2178b18d0b7458941525d463c7ed2ceeb2685754 100644 --- a/.gitattributes +++ b/.gitattributes @@ -74,3 +74,5 @@ categorized_datasets_for_QwenCoder/BigVul_Sample/BigVul_Sample_512_to_1024.csv f categorized_datasets_for_QwenCoder/BigVul_Sample/BigVul_Sample_under_512.csv filter=lfs diff=lfs merge=lfs -text categorized_datasets_for_R1-Distill-Llama/BigVul_Sample/BigVul_Sample_512_to_1024.csv filter=lfs diff=lfs merge=lfs -text categorized_datasets_for_R1-Distill-Llama/BigVul_Sample/BigVul_Sample_under_512.csv filter=lfs diff=lfs merge=lfs -text +categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_512_to_1024.csv filter=lfs diff=lfs merge=lfs -text +categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_under_512.csv filter=lfs diff=lfs merge=lfs -text diff --git a/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_1024_to_2048.csv b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_1024_to_2048.csv new file mode 100644 index 0000000000000000000000000000000000000000..77242cae85af416e2f4bfa6bad66d14cb95ce876 --- /dev/null +++ b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_1024_to_2048.csv @@ -0,0 +1,195162 @@ +idx,func_before,vul,func_after,patch,code_token_length,total_token_length,max_tokens_setting +740," tt_face_get_kerning( TT_Face face, + FT_UInt left_glyph, + FT_UInt right_glyph ) + { + FT_Int result = 0; + FT_UInt count, mask; + FT_Byte* p = face->kern_table; + FT_Byte* p_limit = p + face->kern_table_size; + + + p += 4; + mask = 0x0001; + + for ( count = face->num_kern_tables; + count > 0 && p + 6 <= p_limit; + count--, mask <<= 1 ) + { + FT_Byte* base = p; + FT_Byte* next; + FT_UInt version = FT_NEXT_USHORT( p ); + FT_UInt length = FT_NEXT_USHORT( p ); + FT_UInt coverage = FT_NEXT_USHORT( p ); + FT_UInt num_pairs; + FT_Int value = 0; + + FT_UNUSED( version ); + + + next = base + length; + + if ( next > p_limit ) /* handle broken table */ + next = p_limit; + + if ( ( face->kern_avail_bits & mask ) == 0 ) + goto NextTable; + + if ( p + 8 > next ) + goto NextTable; + + num_pairs = FT_NEXT_USHORT( p ); + p += 6; + + if ( ( next - p ) < 6 * (int)num_pairs ) /* handle broken count */ + num_pairs = (FT_UInt)( ( next - p ) / 6 ); + + switch ( coverage >> 8 ) + { + case 0: + { + FT_ULong key0 = TT_KERN_INDEX( left_glyph, right_glyph ); + + + if ( face->kern_order_bits & mask ) /* binary search */ + { + FT_UInt min = 0; + FT_UInt max = num_pairs; + + + while ( min < max ) + { + FT_UInt mid = ( min + max ) >> 1; + FT_Byte* q = p + 6 * mid; + FT_ULong key; + + + key = FT_NEXT_ULONG( q ); + + if ( key == key0 ) + { + value = FT_PEEK_SHORT( q ); + goto Found; + } + if ( key < key0 ) + min = mid + 1; + else + max = mid; + } + } + else /* linear search */ + { + FT_UInt count2; + + + for ( count2 = num_pairs; count2 > 0; count2-- ) + { + FT_ULong key = FT_NEXT_ULONG( p ); + + + if ( key == key0 ) + { + value = FT_PEEK_SHORT( p ); + goto Found; + } + p += 2; + } + } + } + break; + + /* + * We don't support format 2 because we haven't seen a single font + * using it in real life... + */ + + default: + ; + } + + goto NextTable; + + Found: + if ( coverage & 8 ) /* override or add */ + result = value; + else + result += value; + + NextTable: + p = next; + } + + return result; + } +",0," tt_face_get_kerning( TT_Face face, + FT_UInt left_glyph, + FT_UInt right_glyph ) + { + FT_Int result = 0; + FT_UInt count, mask; + FT_Byte* p = face->kern_table; + FT_Byte* p_limit = p + face->kern_table_size; + + + p += 4; + mask = 0x0001; + + for ( count = face->num_kern_tables; + count > 0 && p + 6 <= p_limit; + count--, mask <<= 1 ) + { + FT_Byte* base = p; + FT_Byte* next; + FT_UInt version = FT_NEXT_USHORT( p ); + FT_UInt length = FT_NEXT_USHORT( p ); + FT_UInt coverage = FT_NEXT_USHORT( p ); + FT_UInt num_pairs; + FT_Int value = 0; + + FT_UNUSED( version ); + + + next = base + length; + + if ( next > p_limit ) /* handle broken table */ + next = p_limit; + + if ( ( face->kern_avail_bits & mask ) == 0 ) + goto NextTable; + + if ( p + 8 > next ) + goto NextTable; + + num_pairs = FT_NEXT_USHORT( p ); + p += 6; + + if ( ( next - p ) < 6 * (int)num_pairs ) /* handle broken count */ + num_pairs = (FT_UInt)( ( next - p ) / 6 ); + + switch ( coverage >> 8 ) + { + case 0: + { + FT_ULong key0 = TT_KERN_INDEX( left_glyph, right_glyph ); + + + if ( face->kern_order_bits & mask ) /* binary search */ + { + FT_UInt min = 0; + FT_UInt max = num_pairs; + + + while ( min < max ) + { + FT_UInt mid = ( min + max ) >> 1; + FT_Byte* q = p + 6 * mid; + FT_ULong key; + + + key = FT_NEXT_ULONG( q ); + + if ( key == key0 ) + { + value = FT_PEEK_SHORT( q ); + goto Found; + } + if ( key < key0 ) + min = mid + 1; + else + max = mid; + } + } + else /* linear search */ + { + FT_UInt count2; + + + for ( count2 = num_pairs; count2 > 0; count2-- ) + { + FT_ULong key = FT_NEXT_ULONG( p ); + + + if ( key == key0 ) + { + value = FT_PEEK_SHORT( p ); + goto Found; + } + p += 2; + } + } + } + break; + + /* + * We don't support format 2 because we haven't seen a single font + * using it in real life... + */ + + default: + ; + } + + goto NextTable; + + Found: + if ( coverage & 8 ) /* override or add */ + result = value; + else + result += value; + + NextTable: + p = next; + } + + return result; + } +","@@ -99,7 +99,7 @@ + length = FT_NEXT_USHORT( p ); + coverage = FT_NEXT_USHORT( p ); + +- if ( length <= 6 ) ++ if ( length <= 6 + 8 ) + break; + + p_next += length;",717,1048,2048 +7369,"parse_args(int argc, char *argv[]) +{ + int r; + + static struct option longOptions[] = + { + {""receive-cmd"", required_argument, 0, 'v'}, + {""send-cmd"", required_argument, 0, 's'}, + {""imap"", required_argument, 0, 'I' }, + {""omap"", required_argument, 0, 'O' }, + {""emap"", required_argument, 0, 'E' }, + {""escape"", required_argument, 0, 'e'}, + {""echo"", no_argument, 0, 'c'}, + {""noinit"", no_argument, 0, 'i'}, + {""noreset"", no_argument, 0, 'r'}, + {""nolock"", no_argument, 0, 'l'}, + {""flow"", required_argument, 0, 'f'}, + {""baud"", required_argument, 0, 'b'}, + {""parity"", required_argument, 0, 'p'}, + {""databits"", required_argument, 0, 'd'}, + {""help"", no_argument, 0, 'h'}, + {0, 0, 0, 0} + }; + + r = 0; + while (1) { + int optionIndex = 0; + int c; + int map; + + /* no default error messages printed. */ + opterr = 0; + + c = getopt_long(argc, argv, ""hirlcv:s:r:e:f:b:p:d:"", + longOptions, &optionIndex); + + if (c < 0) + break; + + switch (c) { + case 's': + strncpy(opts.send_cmd, optarg, sizeof(opts.send_cmd)); + opts.send_cmd[sizeof(opts.send_cmd) - 1] = '\0'; + break; + case 'v': + strncpy(opts.receive_cmd, optarg, sizeof(opts.receive_cmd)); + opts.receive_cmd[sizeof(opts.receive_cmd) - 1] = '\0'; + break; + case 'I': + map = parse_map(optarg); + if (map >= 0) opts.imap = map; + else { fprintf(stderr, ""Invalid --imap\n""); r = -1; } + break; + case 'O': + map = parse_map(optarg); + if (map >= 0) opts.omap = map; + else { fprintf(stderr, ""Invalid --omap\n""); r = -1; } + break; + case 'E': + map = parse_map(optarg); + if (map >= 0) opts.emap = map; + else { fprintf(stderr, ""Invalid --emap\n""); r = -1; } + break; + case 'c': + opts.lecho = 1; + break; + case 'i': + opts.noinit = 1; + break; + case 'r': + opts.noreset = 1; + break; + case 'l': +#if defined (UUCP_LOCK_DIR) || defined (USE_FLOCK) + opts.nolock = 1; +#endif + break; + case 'e': + opts.escape = optarg[0] & 0x1f; + break; + case 'f': + switch (optarg[0]) { + case 'X': + case 'x': + opts.flow = FC_XONXOFF; + break; + case 'H': + case 'h': + opts.flow = FC_RTSCTS; + break; + case 'N': + case 'n': + opts.flow = FC_NONE; + break; + default: + fprintf(stderr, ""Invalid --flow: %c\n"", optarg[0]); + r = -1; + break; + } + break; + case 'b': + opts.baud = atoi(optarg); + break; + case 'p': + switch (optarg[0]) { + case 'e': + opts.parity = P_EVEN; + break; + case 'o': + opts.parity = P_ODD; + break; + case 'n': + opts.parity = P_NONE; + break; + default: + fprintf(stderr, ""Invalid --parity: %c\n"", optarg[0]); + r = -1; + break; + } + break; + case 'd': + switch (optarg[0]) { + case '5': + opts.databits = 5; + break; + case '6': + opts.databits = 6; + break; + case '7': + opts.databits = 7; + break; + case '8': + opts.databits = 8; + break; + default: + fprintf(stderr, ""Invalid --databits: %c\n"", optarg[0]); + r = -1; + break; + } + break; + case 'h': + show_usage(argv[0]); + exit(EXIT_SUCCESS); + case '?': + default: + fprintf(stderr, ""Unrecognized option(s)\n""); + r = -1; + break; + } + if ( r < 0 ) { + fprintf(stderr, ""Run with '--help'.\n""); + exit(EXIT_FAILURE); + } + } /* while */ + + if ( (argc - optind) < 1) { + fprintf(stderr, ""No port given\n""); + fprintf(stderr, ""Run with '--help'.\n""); + exit(EXIT_FAILURE); + } + strncpy(opts.port, argv[optind], sizeof(opts.port) - 1); + opts.port[sizeof(opts.port) - 1] = '\0'; + + printf(""picocom v%s\n"", VERSION_STR); + printf(""\n""); + printf(""port is : %s\n"", opts.port); + printf(""flowcontrol : %s\n"", flow_str[opts.flow]); + printf(""baudrate is : %d\n"", opts.baud); + printf(""parity is : %s\n"", parity_str[opts.parity]); + printf(""databits are : %d\n"", opts.databits); + printf(""escape is : C-%c\n"", 'a' + opts.escape - 1); + printf(""local echo is : %s\n"", opts.lecho ? ""yes"" : ""no""); + printf(""noinit is : %s\n"", opts.noinit ? ""yes"" : ""no""); + printf(""noreset is : %s\n"", opts.noreset ? ""yes"" : ""no""); +#if defined (UUCP_LOCK_DIR) || defined (USE_FLOCK) + printf(""nolock is : %s\n"", opts.nolock ? ""yes"" : ""no""); +#endif + printf(""send_cmd is : %s\n"", + (opts.send_cmd[0] == '\0') ? ""disabled"" : opts.send_cmd); + printf(""receive_cmd is : %s\n"", + (opts.receive_cmd[0] == '\0') ? ""disabled"" : opts.receive_cmd); + printf(""imap is : ""); print_map(opts.imap); + printf(""omap is : ""); print_map(opts.omap); + printf(""emap is : ""); print_map(opts.emap); + printf(""\n""); +} +",0,"parse_args(int argc, char *argv[]) +{ + int r; + + static struct option longOptions[] = + { + {""receive-cmd"", required_argument, 0, 'v'}, + {""send-cmd"", required_argument, 0, 's'}, + {""imap"", required_argument, 0, 'I' }, + {""omap"", required_argument, 0, 'O' }, + {""emap"", required_argument, 0, 'E' }, + {""escape"", required_argument, 0, 'e'}, + {""echo"", no_argument, 0, 'c'}, + {""noinit"", no_argument, 0, 'i'}, + {""noreset"", no_argument, 0, 'r'}, + {""nolock"", no_argument, 0, 'l'}, + {""flow"", required_argument, 0, 'f'}, + {""baud"", required_argument, 0, 'b'}, + {""parity"", required_argument, 0, 'p'}, + {""databits"", required_argument, 0, 'd'}, + {""help"", no_argument, 0, 'h'}, + {0, 0, 0, 0} + }; + + r = 0; + while (1) { + int optionIndex = 0; + int c; + int map; + + /* no default error messages printed. */ + opterr = 0; + + c = getopt_long(argc, argv, ""hirlcv:s:r:e:f:b:p:d:"", + longOptions, &optionIndex); + + if (c < 0) + break; + + switch (c) { + case 's': + strncpy(opts.send_cmd, optarg, sizeof(opts.send_cmd)); + opts.send_cmd[sizeof(opts.send_cmd) - 1] = '\0'; + break; + case 'v': + strncpy(opts.receive_cmd, optarg, sizeof(opts.receive_cmd)); + opts.receive_cmd[sizeof(opts.receive_cmd) - 1] = '\0'; + break; + case 'I': + map = parse_map(optarg); + if (map >= 0) opts.imap = map; + else { fprintf(stderr, ""Invalid --imap\n""); r = -1; } + break; + case 'O': + map = parse_map(optarg); + if (map >= 0) opts.omap = map; + else { fprintf(stderr, ""Invalid --omap\n""); r = -1; } + break; + case 'E': + map = parse_map(optarg); + if (map >= 0) opts.emap = map; + else { fprintf(stderr, ""Invalid --emap\n""); r = -1; } + break; + case 'c': + opts.lecho = 1; + break; + case 'i': + opts.noinit = 1; + break; + case 'r': + opts.noreset = 1; + break; + case 'l': +#if defined (UUCP_LOCK_DIR) || defined (USE_FLOCK) + opts.nolock = 1; +#endif + break; + case 'e': + opts.escape = optarg[0] & 0x1f; + break; + case 'f': + switch (optarg[0]) { + case 'X': + case 'x': + opts.flow = FC_XONXOFF; + break; + case 'H': + case 'h': + opts.flow = FC_RTSCTS; + break; + case 'N': + case 'n': + opts.flow = FC_NONE; + break; + default: + fprintf(stderr, ""Invalid --flow: %c\n"", optarg[0]); + r = -1; + break; + } + break; + case 'b': + opts.baud = atoi(optarg); + break; + case 'p': + switch (optarg[0]) { + case 'e': + opts.parity = P_EVEN; + break; + case 'o': + opts.parity = P_ODD; + break; + case 'n': + opts.parity = P_NONE; + break; + default: + fprintf(stderr, ""Invalid --parity: %c\n"", optarg[0]); + r = -1; + break; + } + break; + case 'd': + switch (optarg[0]) { + case '5': + opts.databits = 5; + break; + case '6': + opts.databits = 6; + break; + case '7': + opts.databits = 7; + break; + case '8': + opts.databits = 8; + break; + default: + fprintf(stderr, ""Invalid --databits: %c\n"", optarg[0]); + r = -1; + break; + } + break; + case 'h': + show_usage(argv[0]); + exit(EXIT_SUCCESS); + case '?': + default: + fprintf(stderr, ""Unrecognized option(s)\n""); + r = -1; + break; + } + if ( r < 0 ) { + fprintf(stderr, ""Run with '--help'.\n""); + exit(EXIT_FAILURE); + } + } /* while */ + + if ( (argc - optind) < 1) { + fprintf(stderr, ""No port given\n""); + fprintf(stderr, ""Run with '--help'.\n""); + exit(EXIT_FAILURE); + } + strncpy(opts.port, argv[optind], sizeof(opts.port) - 1); + opts.port[sizeof(opts.port) - 1] = '\0'; + + printf(""picocom v%s\n"", VERSION_STR); + printf(""\n""); + printf(""port is : %s\n"", opts.port); + printf(""flowcontrol : %s\n"", flow_str[opts.flow]); + printf(""baudrate is : %d\n"", opts.baud); + printf(""parity is : %s\n"", parity_str[opts.parity]); + printf(""databits are : %d\n"", opts.databits); + printf(""escape is : C-%c\n"", 'a' + opts.escape - 1); + printf(""local echo is : %s\n"", opts.lecho ? ""yes"" : ""no""); + printf(""noinit is : %s\n"", opts.noinit ? ""yes"" : ""no""); + printf(""noreset is : %s\n"", opts.noreset ? ""yes"" : ""no""); +#if defined (UUCP_LOCK_DIR) || defined (USE_FLOCK) + printf(""nolock is : %s\n"", opts.nolock ? ""yes"" : ""no""); +#endif + printf(""send_cmd is : %s\n"", + (opts.send_cmd[0] == '\0') ? ""disabled"" : opts.send_cmd); + printf(""receive_cmd is : %s\n"", + (opts.receive_cmd[0] == '\0') ? ""disabled"" : opts.receive_cmd); + printf(""imap is : ""); print_map(opts.imap); + printf(""omap is : ""); print_map(opts.omap); + printf(""emap is : ""); print_map(opts.emap); + printf(""\n""); +} +","@@ -48,6 +48,7 @@ + #define _GNU_SOURCE + #include + ++#include ""split.h"" + #include ""term.h"" + #ifdef LINENOISE + #include ""linenoise-1.0/linenoise.h"" +@@ -721,6 +722,9 @@ show_status (int dtr_up) + + /**********************************************************************/ + ++#define RUNCMD_ARGS_MAX 32 ++#define RUNCMD_EXEC_FAIL 126 ++ + void + establish_child_signal_handlers (void) + { +@@ -735,10 +739,8 @@ establish_child_signal_handlers (void) + sigaction (SIGTERM, &dfl_action, NULL); + } + +-#define EXEC ""exec "" +- + int +-run_cmd(int fd, ...) ++run_cmd(int fd, const char *cmd, const char *args_extra) + { + pid_t pid; + sigset_t sigm, sigm_old; +@@ -781,8 +783,10 @@ run_cmd(int fd, ...) + } else { + /* child: external program */ + long fl; +- char cmd[512]; +- ++ int argc; ++ char *argv[RUNCMD_ARGS_MAX + 1]; ++ int r; ++ + /* unmanage terminal, and reset it to canonical mode */ + term_remove(STI); + /* unmanage serial port fd, without reset */ +@@ -796,37 +800,36 @@ run_cmd(int fd, ...) + close(STO); + dup2(fd, STI); + dup2(fd, STO); +- { +- /* build command-line */ +- char *c, *ce; +- const char *s; +- int n; +- va_list vls; +- +- strcpy(cmd, EXEC); +- c = &cmd[sizeof(EXEC)- 1]; +- ce = cmd + sizeof(cmd) - 1; +- va_start(vls, fd); +- while ( (s = va_arg(vls, const char *)) ) { +- n = strlen(s); +- if ( c + n + 1 >= ce ) break; +- memcpy(c, s, n); c += n; +- *c++ = ' '; +- } +- va_end(vls); +- *c = '\0'; ++ ++ /* build command arguments vector */ ++ argc = 0; ++ r = split_quoted(cmd, &argc, argv, RUNCMD_ARGS_MAX); ++ if ( r < 0 ) { ++ fd_printf(STDERR_FILENO, ""Cannot parse command\n""); ++ exit(RUNCMD_EXEC_FAIL); ++ } ++ r = split_quoted(args_extra, &argc, argv, RUNCMD_ARGS_MAX); ++ if ( r < 0 ) { ++ fd_printf(STDERR_FILENO, ""Cannot parse extra args\n""); ++ exit(RUNCMD_EXEC_FAIL); + } ++ if ( argc < 1 ) { ++ fd_printf(STDERR_FILENO, ""No command given\n""); ++ exit(RUNCMD_EXEC_FAIL); ++ } ++ argv[argc] = NULL; ++ + /* run extenral command */ +- fd_printf(STDERR_FILENO, ""%s\n"", &cmd[sizeof(EXEC) - 1]); ++ fd_printf(STDERR_FILENO, ""$ %s %s\n"", cmd, args_extra); + establish_child_signal_handlers(); + sigprocmask(SIG_SETMASK, &sigm_old, NULL); +- execl(""/bin/sh"", ""sh"", ""-c"", cmd, NULL); +- exit(42); ++ execvp(argv[0], argv); ++ ++ fd_printf(STDERR_FILENO, ""exec: %s\n"", strerror(errno)); ++ exit(RUNCMD_EXEC_FAIL); + } + } + +-#undef EXEC +- + /**********************************************************************/ + + /* Process command key. Returns non-zero if command results in picocom +@@ -944,7 +947,7 @@ do_command (unsigned char c) + fd_printf(STO, ""*** cannot read filename ***\r\n""); + break; + } +- run_cmd(tty_fd, xfr_cmd, fname, NULL); ++ run_cmd(tty_fd, xfr_cmd, fname); + free(fname); + break; + case KEY_BREAK:",1509,1840,2048 +17574,"void bta_av_sig_chg(tBTA_AV_DATA* p_data) { + uint16_t event = p_data->str_msg.hdr.layer_specific; + tBTA_AV_CB* p_cb = &bta_av_cb; + uint32_t xx; + uint8_t mask; + tBTA_AV_LCB* p_lcb = NULL; + + APPL_TRACE_DEBUG(""%s: event: %d"", __func__, event); + if (event == AVDT_CONNECT_IND_EVT) { + APPL_TRACE_DEBUG(""%s: AVDT_CONNECT_IND_EVT: peer %s"", __func__, + p_data->str_msg.bd_addr.ToString().c_str()); + + p_lcb = bta_av_find_lcb(p_data->str_msg.bd_addr, BTA_AV_LCB_FIND); + if (!p_lcb) { + /* if the address does not have an LCB yet, alloc one */ + xx = bta_av_find_lcb_index_by_scb_and_address(p_data->str_msg.bd_addr); + + /* check if we found something */ + if (xx >= BTA_AV_NUM_LINKS) { + /* We do not have scb for this avdt connection. */ + /* Silently close the connection. */ + APPL_TRACE_ERROR(""%s: av scb not available for avdt connection for %s"", + __func__, p_data->str_msg.bd_addr.ToString().c_str()); + AVDT_DisconnectReq(p_data->str_msg.bd_addr, NULL); + return; + } + LOG_INFO(LOG_TAG, + ""%s: AVDT_CONNECT_IND_EVT: peer %s selected lcb_index %d"", + __func__, p_data->str_msg.bd_addr.ToString().c_str(), xx); + + tBTA_AV_SCB* p_scb = p_cb->p_scb[xx]; + mask = 1 << xx; + p_lcb = &p_cb->lcb[xx]; + p_lcb->lidx = xx + 1; + p_lcb->addr = p_data->str_msg.bd_addr; + p_lcb->conn_msk = 0; /* clear the connect mask */ + /* start listening when the signal channel is open */ + if (p_cb->features & BTA_AV_FEAT_RCTG) { + bta_av_rc_create(p_cb, AVCT_ACP, 0, p_lcb->lidx); + } + /* this entry is not used yet. */ + p_cb->conn_lcb |= mask; /* mark it as used */ + APPL_TRACE_DEBUG(""%s: start sig timer %d"", __func__, p_data->hdr.offset); + if (p_data->hdr.offset == AVDT_ACP) { + APPL_TRACE_DEBUG(""%s: Incoming L2CAP acquired, set state as incoming"", + __func__); + p_scb->OnConnected(p_data->str_msg.bd_addr); + p_scb->use_rc = true; /* allowing RC for incoming connection */ + bta_av_ssm_execute(p_scb, BTA_AV_ACP_CONNECT_EVT, p_data); + + /* The Pending Event should be sent as soon as the L2CAP signalling + * channel + * is set up, which is NOW. Earlier this was done only after + * BTA_AV_SIGNALLING_TIMEOUT_MS. + * The following function shall send the event and start the + * recurring timer + */ + bta_av_signalling_timer(NULL); + + APPL_TRACE_DEBUG(""%s: Re-start timer for AVDTP service"", __func__); + bta_sys_conn_open(BTA_ID_AV, p_scb->app_id, p_scb->PeerAddress()); + /* Possible collision : need to avoid outgoing processing while the + * timer is running */ + p_scb->coll_mask = BTA_AV_COLL_INC_TMR; + alarm_set_on_mloop( + p_cb->accept_signalling_timer, BTA_AV_ACCEPT_SIGNALLING_TIMEOUT_MS, + bta_av_accept_signalling_timer_cback, UINT_TO_PTR(xx)); + } + } + } +#if (BTA_AR_INCLUDED == TRUE) + else if (event == BTA_AR_AVDT_CONN_EVT) { + alarm_cancel(bta_av_cb.link_signalling_timer); + } +#endif + else { + /* disconnected. */ + APPL_TRACE_DEBUG(""%s: bta_av_cb.conn_lcb is %d"", __func__, + bta_av_cb.conn_lcb); + + p_lcb = bta_av_find_lcb(p_data->str_msg.bd_addr, BTA_AV_LCB_FREE); + if (p_lcb && (p_lcb->conn_msk || bta_av_cb.conn_lcb)) { + APPL_TRACE_DEBUG(""%s: conn_msk: 0x%x"", __func__, p_lcb->conn_msk); + /* clean up ssm */ + for (xx = 0; xx < BTA_AV_NUM_STRS; xx++) { + if (p_cb->p_scb[xx] && + p_cb->p_scb[xx]->PeerAddress() == p_data->str_msg.bd_addr) { + APPL_TRACE_DEBUG(""%s: Closing timer for AVDTP service"", __func__); + bta_sys_conn_close(BTA_ID_AV, p_cb->p_scb[xx]->app_id, + p_cb->p_scb[xx]->PeerAddress()); + } + mask = 1 << (xx + 1); + if (((mask & p_lcb->conn_msk) || bta_av_cb.conn_lcb) && + p_cb->p_scb[xx] && + p_cb->p_scb[xx]->PeerAddress() == p_data->str_msg.bd_addr) { + APPL_TRACE_WARNING(""%s: Sending AVDT_DISCONNECT_EVT peer_addr=%s"", + __func__, + p_cb->p_scb[xx]->PeerAddress().ToString().c_str()); + bta_av_ssm_execute(p_cb->p_scb[xx], BTA_AV_AVDT_DISCONNECT_EVT, NULL); + } + } + } + } + APPL_TRACE_DEBUG(""%s: sig_chg conn_lcb: 0x%x"", __func__, p_cb->conn_lcb); +} +",0,"void bta_av_sig_chg(tBTA_AV_DATA* p_data) { + uint16_t event = p_data->str_msg.hdr.layer_specific; + tBTA_AV_CB* p_cb = &bta_av_cb; + uint32_t xx; + uint8_t mask; + tBTA_AV_LCB* p_lcb = NULL; + + APPL_TRACE_DEBUG(""%s: event: %d"", __func__, event); + if (event == AVDT_CONNECT_IND_EVT) { + APPL_TRACE_DEBUG(""%s: AVDT_CONNECT_IND_EVT: peer %s"", __func__, + p_data->str_msg.bd_addr.ToString().c_str()); + + p_lcb = bta_av_find_lcb(p_data->str_msg.bd_addr, BTA_AV_LCB_FIND); + if (!p_lcb) { + /* if the address does not have an LCB yet, alloc one */ + xx = bta_av_find_lcb_index_by_scb_and_address(p_data->str_msg.bd_addr); + + /* check if we found something */ + if (xx >= BTA_AV_NUM_LINKS) { + /* We do not have scb for this avdt connection. */ + /* Silently close the connection. */ + APPL_TRACE_ERROR(""%s: av scb not available for avdt connection for %s"", + __func__, p_data->str_msg.bd_addr.ToString().c_str()); + AVDT_DisconnectReq(p_data->str_msg.bd_addr, NULL); + return; + } + LOG_INFO(LOG_TAG, + ""%s: AVDT_CONNECT_IND_EVT: peer %s selected lcb_index %d"", + __func__, p_data->str_msg.bd_addr.ToString().c_str(), xx); + + tBTA_AV_SCB* p_scb = p_cb->p_scb[xx]; + mask = 1 << xx; + p_lcb = &p_cb->lcb[xx]; + p_lcb->lidx = xx + 1; + p_lcb->addr = p_data->str_msg.bd_addr; + p_lcb->conn_msk = 0; /* clear the connect mask */ + /* start listening when the signal channel is open */ + if (p_cb->features & BTA_AV_FEAT_RCTG) { + bta_av_rc_create(p_cb, AVCT_ACP, 0, p_lcb->lidx); + } + /* this entry is not used yet. */ + p_cb->conn_lcb |= mask; /* mark it as used */ + APPL_TRACE_DEBUG(""%s: start sig timer %d"", __func__, p_data->hdr.offset); + if (p_data->hdr.offset == AVDT_ACP) { + APPL_TRACE_DEBUG(""%s: Incoming L2CAP acquired, set state as incoming"", + __func__); + p_scb->OnConnected(p_data->str_msg.bd_addr); + p_scb->use_rc = true; /* allowing RC for incoming connection */ + bta_av_ssm_execute(p_scb, BTA_AV_ACP_CONNECT_EVT, p_data); + + /* The Pending Event should be sent as soon as the L2CAP signalling + * channel + * is set up, which is NOW. Earlier this was done only after + * BTA_AV_SIGNALLING_TIMEOUT_MS. + * The following function shall send the event and start the + * recurring timer + */ + bta_av_signalling_timer(NULL); + + APPL_TRACE_DEBUG(""%s: Re-start timer for AVDTP service"", __func__); + bta_sys_conn_open(BTA_ID_AV, p_scb->app_id, p_scb->PeerAddress()); + /* Possible collision : need to avoid outgoing processing while the + * timer is running */ + p_scb->coll_mask = BTA_AV_COLL_INC_TMR; + alarm_set_on_mloop( + p_cb->accept_signalling_timer, BTA_AV_ACCEPT_SIGNALLING_TIMEOUT_MS, + bta_av_accept_signalling_timer_cback, UINT_TO_PTR(xx)); + } + } + } +#if (BTA_AR_INCLUDED == TRUE) + else if (event == BTA_AR_AVDT_CONN_EVT) { + alarm_cancel(bta_av_cb.link_signalling_timer); + } +#endif + else { + /* disconnected. */ + APPL_TRACE_DEBUG(""%s: bta_av_cb.conn_lcb is %d"", __func__, + bta_av_cb.conn_lcb); + + p_lcb = bta_av_find_lcb(p_data->str_msg.bd_addr, BTA_AV_LCB_FREE); + if (p_lcb && (p_lcb->conn_msk || bta_av_cb.conn_lcb)) { + APPL_TRACE_DEBUG(""%s: conn_msk: 0x%x"", __func__, p_lcb->conn_msk); + /* clean up ssm */ + for (xx = 0; xx < BTA_AV_NUM_STRS; xx++) { + if (p_cb->p_scb[xx] && + p_cb->p_scb[xx]->PeerAddress() == p_data->str_msg.bd_addr) { + APPL_TRACE_DEBUG(""%s: Closing timer for AVDTP service"", __func__); + bta_sys_conn_close(BTA_ID_AV, p_cb->p_scb[xx]->app_id, + p_cb->p_scb[xx]->PeerAddress()); + } + mask = 1 << (xx + 1); + if (((mask & p_lcb->conn_msk) || bta_av_cb.conn_lcb) && + p_cb->p_scb[xx] && + p_cb->p_scb[xx]->PeerAddress() == p_data->str_msg.bd_addr) { + APPL_TRACE_WARNING(""%s: Sending AVDT_DISCONNECT_EVT peer_addr=%s"", + __func__, + p_cb->p_scb[xx]->PeerAddress().ToString().c_str()); + bta_av_ssm_execute(p_cb->p_scb[xx], BTA_AV_AVDT_DISCONNECT_EVT, NULL); + } + } + } + } + APPL_TRACE_DEBUG(""%s: sig_chg conn_lcb: 0x%x"", __func__, p_cb->conn_lcb); +} +","@@ -35,6 +35,7 @@ + + #include ""bta_av_api.h"" + #include ""bta_av_int.h"" + #include ""l2c_api.h"" ++#include ""log/log.h"" + #include ""osi/include/list.h"" + #include ""osi/include/log.h"" + #include ""osi/include/osi.h"" +@@ -784,11 +785,16 @@ + + case AVRC_PDU_GET_CAPABILITIES: + /* process GetCapabilities command without reporting the event to app */ + evt = 0; ++ if (p_vendor->vendor_len != 5) { ++ android_errorWriteLog(0x534e4554, ""111893951""); ++ p_rc_rsp->get_caps.status = AVRC_STS_INTERNAL_ERR; ++ break; ++ } + u8 = *(p_vendor->p_vendor_data + 4); + p = p_vendor->p_vendor_data + 2; + p_rc_rsp->get_caps.capability_id = u8; + BE_STREAM_TO_UINT16(u16, p); +- if ((u16 != 1) || (p_vendor->vendor_len != 5)) { ++ if (u16 != 1) { + p_rc_rsp->get_caps.status = AVRC_STS_INTERNAL_ERR; + } else { + p_rc_rsp->get_caps.status = AVRC_STS_NO_ERROR; +",1269,1600,2048 +18283,"ZSTD_encodeSequences_body( + void* dst, size_t dstCapacity, + FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable, + FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable, + FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable, + seqDef const* sequences, size_t nbSeq, int longOffsets) +{ + BIT_CStream_t blockStream; + FSE_CState_t stateMatchLength; + FSE_CState_t stateOffsetBits; + FSE_CState_t stateLitLength; + + CHECK_E(BIT_initCStream(&blockStream, dst, dstCapacity), dstSize_tooSmall); /* not enough space remaining */ + + /* first symbols */ + FSE_initCState2(&stateMatchLength, CTable_MatchLength, mlCodeTable[nbSeq-1]); + FSE_initCState2(&stateOffsetBits, CTable_OffsetBits, ofCodeTable[nbSeq-1]); + FSE_initCState2(&stateLitLength, CTable_LitLength, llCodeTable[nbSeq-1]); + BIT_addBits(&blockStream, sequences[nbSeq-1].litLength, LL_bits[llCodeTable[nbSeq-1]]); + if (MEM_32bits()) BIT_flushBits(&blockStream); + BIT_addBits(&blockStream, sequences[nbSeq-1].matchLength, ML_bits[mlCodeTable[nbSeq-1]]); + if (MEM_32bits()) BIT_flushBits(&blockStream); + if (longOffsets) { + U32 const ofBits = ofCodeTable[nbSeq-1]; + int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1); + if (extraBits) { + BIT_addBits(&blockStream, sequences[nbSeq-1].offset, extraBits); + BIT_flushBits(&blockStream); + } + BIT_addBits(&blockStream, sequences[nbSeq-1].offset >> extraBits, + ofBits - extraBits); + } else { + BIT_addBits(&blockStream, sequences[nbSeq-1].offset, ofCodeTable[nbSeq-1]); + } + BIT_flushBits(&blockStream); + + { size_t n; + for (n=nbSeq-2 ; n= 64-7-(LLFSELog+MLFSELog+OffFSELog))) + BIT_flushBits(&blockStream); /* (7)*/ + BIT_addBits(&blockStream, sequences[n].litLength, llBits); + if (MEM_32bits() && ((llBits+mlBits)>24)) BIT_flushBits(&blockStream); + BIT_addBits(&blockStream, sequences[n].matchLength, mlBits); + if (MEM_32bits() || (ofBits+mlBits+llBits > 56)) BIT_flushBits(&blockStream); + if (longOffsets) { + int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1); + if (extraBits) { + BIT_addBits(&blockStream, sequences[n].offset, extraBits); + BIT_flushBits(&blockStream); /* (7)*/ + } + BIT_addBits(&blockStream, sequences[n].offset >> extraBits, + ofBits - extraBits); /* 31 */ + } else { + BIT_addBits(&blockStream, sequences[n].offset, ofBits); /* 31 */ + } + BIT_flushBits(&blockStream); /* (7)*/ + } } + + DEBUGLOG(6, ""ZSTD_encodeSequences: flushing ML state with %u bits"", stateMatchLength.stateLog); + FSE_flushCState(&blockStream, &stateMatchLength); + DEBUGLOG(6, ""ZSTD_encodeSequences: flushing Off state with %u bits"", stateOffsetBits.stateLog); + FSE_flushCState(&blockStream, &stateOffsetBits); + DEBUGLOG(6, ""ZSTD_encodeSequences: flushing LL state with %u bits"", stateLitLength.stateLog); + FSE_flushCState(&blockStream, &stateLitLength); + + { size_t const streamSize = BIT_closeCStream(&blockStream); + if (streamSize==0) return ERROR(dstSize_tooSmall); /* not enough space */ + return streamSize; + } +} +",1,"ZSTD_encodeSequences_body( + void* dst, size_t dstCapacity, + FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable, + FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable, + FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable, + seqDef const* sequences, size_t nbSeq, int longOffsets) +{ + BIT_CStream_t blockStream; + FSE_CState_t stateMatchLength; + FSE_CState_t stateOffsetBits; + FSE_CState_t stateLitLength; + + CHECK_E(BIT_initCStream(&blockStream, dst, dstCapacity), dstSize_tooSmall); /* not enough space remaining */ + DEBUGLOG(6, ""available space for bitstream : %i (dstCapacity=%u)"", + (int)(blockStream.endPtr - blockStream.startPtr), + (unsigned)dstCapacity); + + /* first symbols */ + FSE_initCState2(&stateMatchLength, CTable_MatchLength, mlCodeTable[nbSeq-1]); + FSE_initCState2(&stateOffsetBits, CTable_OffsetBits, ofCodeTable[nbSeq-1]); + FSE_initCState2(&stateLitLength, CTable_LitLength, llCodeTable[nbSeq-1]); + BIT_addBits(&blockStream, sequences[nbSeq-1].litLength, LL_bits[llCodeTable[nbSeq-1]]); + if (MEM_32bits()) BIT_flushBits(&blockStream); + BIT_addBits(&blockStream, sequences[nbSeq-1].matchLength, ML_bits[mlCodeTable[nbSeq-1]]); + if (MEM_32bits()) BIT_flushBits(&blockStream); + if (longOffsets) { + U32 const ofBits = ofCodeTable[nbSeq-1]; + int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1); + if (extraBits) { + BIT_addBits(&blockStream, sequences[nbSeq-1].offset, extraBits); + BIT_flushBits(&blockStream); + } + BIT_addBits(&blockStream, sequences[nbSeq-1].offset >> extraBits, + ofBits - extraBits); + } else { + BIT_addBits(&blockStream, sequences[nbSeq-1].offset, ofCodeTable[nbSeq-1]); + } + BIT_flushBits(&blockStream); + + { size_t n; + for (n=nbSeq-2 ; n= 64-7-(LLFSELog+MLFSELog+OffFSELog))) + BIT_flushBits(&blockStream); /* (7)*/ + BIT_addBits(&blockStream, sequences[n].litLength, llBits); + if (MEM_32bits() && ((llBits+mlBits)>24)) BIT_flushBits(&blockStream); + BIT_addBits(&blockStream, sequences[n].matchLength, mlBits); + if (MEM_32bits() || (ofBits+mlBits+llBits > 56)) BIT_flushBits(&blockStream); + if (longOffsets) { + int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1); + if (extraBits) { + BIT_addBits(&blockStream, sequences[n].offset, extraBits); + BIT_flushBits(&blockStream); /* (7)*/ + } + BIT_addBits(&blockStream, sequences[n].offset >> extraBits, + ofBits - extraBits); /* 31 */ + } else { + BIT_addBits(&blockStream, sequences[n].offset, ofBits); /* 31 */ + } + BIT_flushBits(&blockStream); /* (7)*/ + DEBUGLOG(7, ""remaining space : %i"", (int)(blockStream.endPtr - blockStream.ptr)); + } } + + DEBUGLOG(6, ""ZSTD_encodeSequences: flushing ML state with %u bits"", stateMatchLength.stateLog); + FSE_flushCState(&blockStream, &stateMatchLength); + DEBUGLOG(6, ""ZSTD_encodeSequences: flushing Off state with %u bits"", stateOffsetBits.stateLog); + FSE_flushCState(&blockStream, &stateOffsetBits); + DEBUGLOG(6, ""ZSTD_encodeSequences: flushing LL state with %u bits"", stateLitLength.stateLog); + FSE_flushCState(&blockStream, &stateLitLength); + + { size_t const streamSize = BIT_closeCStream(&blockStream); + if (streamSize==0) return ERROR(dstSize_tooSmall); /* not enough space */ + return streamSize; + } +} +","@@ -2008,11 +2008,13 @@ ZSTD_buildCTable(void* dst, size_t dstCapacity, + { + BYTE* op = (BYTE*)dst; + const BYTE* const oend = op + dstCapacity; ++ DEBUGLOG(6, ""ZSTD_buildCTable (dstCapacity=%u)"", (unsigned)dstCapacity); + + switch (type) { + case set_rle: +- *op = codeTable[0]; + CHECK_F(FSE_buildCTable_rle(nextCTable, (BYTE)max)); ++ if (dstCapacity==0) return ERROR(dstSize_tooSmall); ++ *op = codeTable[0]; + return 1; + case set_repeat: + memcpy(nextCTable, prevCTable, prevCTableSize); +@@ -2054,6 +2056,9 @@ ZSTD_encodeSequences_body( + FSE_CState_t stateLitLength; + + CHECK_E(BIT_initCStream(&blockStream, dst, dstCapacity), dstSize_tooSmall); /* not enough space remaining */ ++ DEBUGLOG(6, ""available space for bitstream : %i (dstCapacity=%u)"", ++ (int)(blockStream.endPtr - blockStream.startPtr), ++ (unsigned)dstCapacity); + + /* first symbols */ + FSE_initCState2(&stateMatchLength, CTable_MatchLength, mlCodeTable[nbSeq-1]); +@@ -2113,6 +2118,7 @@ ZSTD_encodeSequences_body( + BIT_addBits(&blockStream, sequences[n].offset, ofBits); /* 31 */ + } + BIT_flushBits(&blockStream); /* (7)*/ ++ DEBUGLOG(7, ""remaining space : %i"", (int)(blockStream.endPtr - blockStream.ptr)); + } } + + DEBUGLOG(6, ""ZSTD_encodeSequences: flushing ML state with %u bits"", stateMatchLength.stateLog); +@@ -2170,6 +2176,7 @@ static size_t ZSTD_encodeSequences( + FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable, + seqDef const* sequences, size_t nbSeq, int longOffsets, int bmi2) + { ++ DEBUGLOG(5, ""ZSTD_encodeSequences: dstCapacity = %u"", (unsigned)dstCapacity); + #if DYNAMIC_BMI2 + if (bmi2) { + return ZSTD_encodeSequences_bmi2(dst, dstCapacity, +@@ -2290,7 +2297,7 @@ ZSTD_compressSequences_internal(seqStore_t* seqStorePtr, + /* build CTable for MatchLengths */ + { U32 max = MaxML; + size_t const mostFrequent = HIST_countFast_wksp(count, &max, mlCodeTable, nbSeq, workspace, wkspSize); /* can't fail */ +- DEBUGLOG(5, ""Building ML table""); ++ DEBUGLOG(5, ""Building ML table (remaining space : %i)"", (int)(oend-op)); + nextEntropy->fse.matchlength_repeatMode = prevEntropy->fse.matchlength_repeatMode; + MLtype = ZSTD_selectEncodingType(&nextEntropy->fse.matchlength_repeatMode, count, max, mostFrequent, nbSeq, MLFSELog, prevEntropy->fse.matchlengthCTable, ML_defaultNorm, ML_defaultNormLog, ZSTD_defaultAllowed, strategy); + assert(!(MLtype < set_compressed && nextEntropy->fse.matchlength_repeatMode != FSE_repeat_none)); /* We don't copy tables */",1245,1576,2048 +17869," int sfgets(void) + { + struct pollfd pfd; + int pollret; + ssize_t readnb; + signed char seen_r = 0; + static size_t scanned; + static size_t readnbd; + + if (scanned > (size_t) 0U) { /* support pipelining */ + readnbd -= scanned; + memmove(cmd, cmd + scanned, readnbd); /* safe */ + scanned = (size_t) 0U; + } + pfd.fd = clientfd; +#ifdef __APPLE_CC__ + pfd.events = POLLIN | POLLERR | POLLHUP; +#else + pfd.events = POLLIN | POLLPRI | POLLERR | POLLHUP; +#endif + while (scanned < cmdsize) { + if (scanned >= readnbd) { /* nothing left in the buffer */ + pfd.revents = 0; + while ((pollret = poll(&pfd, 1U, idletime * 1000UL)) < 0 && + errno == EINTR); + if (pollret == 0) { + return -1; + } + if (pollret <= 0 || + (pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) != 0) { + return -2; + } + if ((pfd.revents & (POLLIN | POLLPRI)) == 0) { + continue; + } + if (readnbd >= cmdsize) { + break; + } +#ifdef WITH_TLS + if (tls_cnx != NULL) { + while ((readnb = SSL_read + (tls_cnx, cmd + readnbd, cmdsize - readnbd)) + < (ssize_t) 0 && errno == EINTR); + } else +#endif + { + while ((readnb = read(clientfd, cmd + readnbd, + cmdsize - readnbd)) < (ssize_t) 0 && + errno == EINTR); + } + if (readnb <= (ssize_t) 0) { + return -2; + } + readnbd += readnb; + if (readnbd > cmdsize) { + return -2; + } + } +#ifdef RFC_CONFORMANT_LINES + if (seen_r != 0) { +#endif + if (cmd[scanned] == '\n') { +#ifndef RFC_CONFORMANT_LINES + if (seen_r != 0) { +#endif + cmd[scanned - 1U] = 0; +#ifndef RFC_CONFORMANT_LINES + } else { + cmd[scanned] = 0; + } +#endif + if (++scanned >= readnbd) { /* non-pipelined command */ + scanned = readnbd = (size_t) 0U; + } + return 0; + } + seen_r = 0; +#ifdef RFC_CONFORMANT_LINES + } +#endif + if (ISCTRLCODE(cmd[scanned])) { + if (cmd[scanned] == '\r') { + seen_r = 1; + } +#ifdef RFC_CONFORMANT_PARSER /* disabled by default, intentionnaly */ + else if (cmd[scanned] == 0) { + cmd[scanned] = '\n'; + } +#else + /* replace control chars with _ */ + cmd[scanned] = '_'; +#endif + } + scanned++; + } + die(421, LOG_WARNING, MSG_LINE_TOO_LONG); /* don't remove this */ + + return 0; /* to please GCC */ +} +",1," int sfgets(void) + { + struct pollfd pfd; + int pollret; + ssize_t readnb; + signed char seen_r = 0; + + if (scanned > (size_t) 0U) { /* support pipelining */ + readnbd -= scanned; + memmove(cmd, cmd + scanned, readnbd); /* safe */ + scanned = (size_t) 0U; + } + pfd.fd = clientfd; +#ifdef __APPLE_CC__ + pfd.events = POLLIN | POLLERR | POLLHUP; +#else + pfd.events = POLLIN | POLLPRI | POLLERR | POLLHUP; +#endif + while (scanned < cmdsize) { + if (scanned >= readnbd) { /* nothing left in the buffer */ + pfd.revents = 0; + while ((pollret = poll(&pfd, 1U, idletime * 1000UL)) < 0 && + errno == EINTR); + if (pollret == 0) { + return -1; + } + if (pollret <= 0 || + (pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) != 0) { + return -2; + } + if ((pfd.revents & (POLLIN | POLLPRI)) == 0) { + continue; + } + if (readnbd >= cmdsize) { + break; + } +#ifdef WITH_TLS + if (tls_cnx != NULL) { + while ((readnb = SSL_read + (tls_cnx, cmd + readnbd, cmdsize - readnbd)) + < (ssize_t) 0 && errno == EINTR); + } else +#endif + { + while ((readnb = read(clientfd, cmd + readnbd, + cmdsize - readnbd)) < (ssize_t) 0 && + errno == EINTR); + } + if (readnb <= (ssize_t) 0) { + return -2; + } + readnbd += readnb; + if (readnbd > cmdsize) { + return -2; + } + } +#ifdef RFC_CONFORMANT_LINES + if (seen_r != 0) { +#endif + if (cmd[scanned] == '\n') { +#ifndef RFC_CONFORMANT_LINES + if (seen_r != 0) { +#endif + cmd[scanned - 1U] = 0; +#ifndef RFC_CONFORMANT_LINES + } else { + cmd[scanned] = 0; + } +#endif + if (++scanned >= readnbd) { /* non-pipelined command */ + scanned = readnbd = (size_t) 0U; + } + return 0; + } + seen_r = 0; +#ifdef RFC_CONFORMANT_LINES + } +#endif + if (ISCTRLCODE(cmd[scanned])) { + if (cmd[scanned] == '\r') { + seen_r = 1; + } +#ifdef RFC_CONFORMANT_PARSER /* disabled by default, intentionnaly */ + else if (cmd[scanned] == 0) { + cmd[scanned] = '\n'; + } +#else + /* replace control chars with _ */ + cmd[scanned] = '_'; +#endif + } + scanned++; + } + die(421, LOG_WARNING, MSG_LINE_TOO_LONG); /* don't remove this */ + + return 0; /* to please GCC */ +} +","@@ -57,14 +57,20 @@ static void randomdelay(void) + * -Frank. + */ + ++static size_t scanned; ++static size_t readnbd; ++ ++static void flush_cmd(void) ++{ ++ scanned = readnbd = (size_t) 0U; ++} ++ + int sfgets(void) + { + struct pollfd pfd; + int pollret; + ssize_t readnb; + signed char seen_r = 0; +- static size_t scanned; +- static size_t readnbd; + + if (scanned > (size_t) 0U) { /* support pipelining */ + readnbd -= scanned; +@@ -362,6 +368,7 @@ void parser(void) + addreply_noformat(234, ""AUTH TLS OK.""); + doreply(); + if (tls_cnx == NULL) { ++ flush_cmd(); + (void) tls_init_new_session(); + } + goto wayout;",779,1110,2048 +17804,"xps_init_truetype_font(xps_context_t *ctx, xps_font_t *font) +{ + int code = 0; + + font->font = (void*) gs_alloc_struct(ctx->memory, gs_font_type42, &st_gs_font_type42, ""xps_font type42""); + if (!font->font) + return gs_throw(gs_error_VMerror, ""out of memory""); + + /* no shortage of things to initialize */ + { + gs_font_type42 *p42 = (gs_font_type42*) font->font; + + /* Common to all fonts: */ + + p42->next = 0; + p42->prev = 0; + p42->memory = ctx->memory; + + p42->dir = ctx->fontdir; /* NB also set by gs_definefont later */ + p42->base = font->font; /* NB also set by gs_definefont later */ + p42->is_resource = false; + gs_notify_init(&p42->notify_list, gs_memory_stable(ctx->memory)); + p42->id = gs_next_ids(ctx->memory, 1); + + p42->client_data = font; /* that's us */ + + /* this is overwritten in grid_fit() */ + gs_make_identity(&p42->FontMatrix); + gs_make_identity(&p42->orig_FontMatrix); /* NB ... original or zeroes? */ + + p42->FontType = ft_TrueType; + p42->BitmapWidths = false; + p42->ExactSize = fbit_use_outlines; + p42->InBetweenSize = fbit_use_outlines; + p42->TransformedChar = fbit_use_outlines; + p42->WMode = 0; + p42->PaintType = 0; + p42->StrokeWidth = 0; + p42->is_cached = 0; + + p42->procs.define_font = gs_no_define_font; + p42->procs.make_font = gs_no_make_font; + p42->procs.font_info = gs_type42_font_info; + p42->procs.same_font = gs_default_same_font; + p42->procs.encode_char = xps_true_callback_encode_char; + p42->procs.decode_glyph = xps_true_callback_decode_glyph; + p42->procs.enumerate_glyph = gs_type42_enumerate_glyph; + p42->procs.glyph_info = gs_type42_glyph_info; + p42->procs.glyph_outline = gs_type42_glyph_outline; + p42->procs.glyph_name = xps_true_callback_glyph_name; + p42->procs.init_fstack = gs_default_init_fstack; + p42->procs.next_char_glyph = gs_default_next_char_glyph; + p42->procs.build_char = xps_true_callback_build_char; + + memset(p42->font_name.chars, 0, sizeof(p42->font_name.chars)); + xps_load_sfnt_name(font, (char*)p42->font_name.chars); + p42->font_name.size = strlen((char*)p42->font_name.chars); + + memset(p42->key_name.chars, 0, sizeof(p42->key_name.chars)); + strcpy((char*)p42->key_name.chars, (char*)p42->font_name.chars); + p42->key_name.size = strlen((char*)p42->key_name.chars); + + /* Base font specific: */ + + p42->FontBBox.p.x = 0; + p42->FontBBox.p.y = 0; + p42->FontBBox.q.x = 0; + p42->FontBBox.q.y = 0; + + uid_set_UniqueID(&p42->UID, p42->id); + + p42->encoding_index = ENCODING_INDEX_UNKNOWN; + p42->nearest_encoding_index = ENCODING_INDEX_ISOLATIN1; + + p42->FAPI = 0; + p42->FAPI_font_data = 0; + + /* Type 42 specific: */ + + p42->data.string_proc = xps_true_callback_string_proc; + p42->data.proc_data = font; + + gs_type42_font_init(p42, font->subfontid); + p42->data.get_glyph_index = xps_true_get_glyph_index; + } + + if ((code = gs_definefont(ctx->fontdir, font->font)) < 0) { + return(code); + } + + code = xps_fapi_passfont (font->font, NULL, NULL, font->data, font->length); + return code; +} +",1,"xps_init_truetype_font(xps_context_t *ctx, xps_font_t *font) +{ + int code = 0; + + font->font = (void*) gs_alloc_struct(ctx->memory, gs_font_type42, &st_gs_font_type42, ""xps_font type42""); + if (!font->font) + return gs_throw(gs_error_VMerror, ""out of memory""); + + /* no shortage of things to initialize */ + { + gs_font_type42 *p42 = (gs_font_type42*) font->font; + + /* Common to all fonts: */ + + p42->next = 0; + p42->prev = 0; + p42->memory = ctx->memory; + + p42->dir = ctx->fontdir; /* NB also set by gs_definefont later */ + p42->base = font->font; /* NB also set by gs_definefont later */ + p42->is_resource = false; + gs_notify_init(&p42->notify_list, gs_memory_stable(ctx->memory)); + p42->id = gs_next_ids(ctx->memory, 1); + + p42->client_data = font; /* that's us */ + + /* this is overwritten in grid_fit() */ + gs_make_identity(&p42->FontMatrix); + gs_make_identity(&p42->orig_FontMatrix); /* NB ... original or zeroes? */ + + p42->FontType = ft_TrueType; + p42->BitmapWidths = false; + p42->ExactSize = fbit_use_outlines; + p42->InBetweenSize = fbit_use_outlines; + p42->TransformedChar = fbit_use_outlines; + p42->WMode = 0; + p42->PaintType = 0; + p42->StrokeWidth = 0; + p42->is_cached = 0; + + p42->procs.define_font = gs_no_define_font; + p42->procs.make_font = gs_no_make_font; + p42->procs.font_info = gs_type42_font_info; + p42->procs.same_font = gs_default_same_font; + p42->procs.encode_char = xps_true_callback_encode_char; + p42->procs.decode_glyph = xps_true_callback_decode_glyph; + p42->procs.enumerate_glyph = gs_type42_enumerate_glyph; + p42->procs.glyph_info = gs_type42_glyph_info; + p42->procs.glyph_outline = gs_type42_glyph_outline; + p42->procs.glyph_name = xps_true_callback_glyph_name; + p42->procs.init_fstack = gs_default_init_fstack; + p42->procs.next_char_glyph = gs_default_next_char_glyph; + p42->procs.build_char = xps_true_callback_build_char; + + memset(p42->font_name.chars, 0, sizeof(p42->font_name.chars)); + xps_load_sfnt_name(font, (char*)p42->font_name.chars, sizeof(p42->font_name.chars)); + p42->font_name.size = strlen((char*)p42->font_name.chars); + + memset(p42->key_name.chars, 0, sizeof(p42->key_name.chars)); + strcpy((char*)p42->key_name.chars, (char*)p42->font_name.chars); + p42->key_name.size = strlen((char*)p42->key_name.chars); + + /* Base font specific: */ + + p42->FontBBox.p.x = 0; + p42->FontBBox.p.y = 0; + p42->FontBBox.q.x = 0; + p42->FontBBox.q.y = 0; + + uid_set_UniqueID(&p42->UID, p42->id); + + p42->encoding_index = ENCODING_INDEX_UNKNOWN; + p42->nearest_encoding_index = ENCODING_INDEX_ISOLATIN1; + + p42->FAPI = 0; + p42->FAPI_font_data = 0; + + /* Type 42 specific: */ + + p42->data.string_proc = xps_true_callback_string_proc; + p42->data.proc_data = font; + + gs_type42_font_init(p42, font->subfontid); + p42->data.get_glyph_index = xps_true_get_glyph_index; + } + + if ((code = gs_definefont(ctx->fontdir, font->font)) < 0) { + return(code); + } + + code = xps_fapi_passfont (font->font, NULL, NULL, font->data, font->length); + return code; +} +","@@ -385,7 +385,7 @@ xps_init_truetype_font(xps_context_t *ctx, xps_font_t *font) + p42->procs.build_char = xps_true_callback_build_char; + + memset(p42->font_name.chars, 0, sizeof(p42->font_name.chars)); +- xps_load_sfnt_name(font, (char*)p42->font_name.chars); ++ xps_load_sfnt_name(font, (char*)p42->font_name.chars, sizeof(p42->font_name.chars)); + p42->font_name.size = strlen((char*)p42->font_name.chars); + + memset(p42->key_name.chars, 0, sizeof(p42->key_name.chars));",1028,1359,2048 +7918,"static void cmd_parse_status(struct ImapData *idata, char *s) +{ + char *value = NULL; + struct Buffy *inc = NULL; + struct ImapMbox mx; + struct ImapStatus *status = NULL; + unsigned int olduv, oldun; + unsigned int litlen; + short new = 0; + short new_msg_count = 0; + + char *mailbox = imap_next_word(s); + + /* We need a real tokenizer. */ + if (imap_get_literal_count(mailbox, &litlen) == 0) + { + if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE) + { + idata->status = IMAP_FATAL; + return; + } + mailbox = idata->buf; + s = mailbox + litlen; + *s = '\0'; + s++; + SKIPWS(s); + } + else + { + s = imap_next_word(mailbox); + *(s - 1) = '\0'; + imap_unmunge_mbox_name(idata, mailbox); + } + + status = imap_mboxcache_get(idata, mailbox, 1); + olduv = status->uidvalidity; + oldun = status->uidnext; + + if (*s++ != '(') + { + mutt_debug(1, ""Error parsing STATUS\n""); + return; + } + while (*s && *s != ')') + { + value = imap_next_word(s); + + errno = 0; + const unsigned long ulcount = strtoul(value, &value, 10); + if (((errno == ERANGE) && (ulcount == ULONG_MAX)) || ((unsigned int) ulcount != ulcount)) + { + mutt_debug(1, ""Error parsing STATUS number\n""); + return; + } + const unsigned int count = (unsigned int) ulcount; + + if (mutt_str_strncmp(""MESSAGES"", s, 8) == 0) + { + status->messages = count; + new_msg_count = 1; + } + else if (mutt_str_strncmp(""RECENT"", s, 6) == 0) + status->recent = count; + else if (mutt_str_strncmp(""UIDNEXT"", s, 7) == 0) + status->uidnext = count; + else if (mutt_str_strncmp(""UIDVALIDITY"", s, 11) == 0) + status->uidvalidity = count; + else if (mutt_str_strncmp(""UNSEEN"", s, 6) == 0) + status->unseen = count; + + s = value; + if (*s && *s != ')') + s = imap_next_word(s); + } + mutt_debug(3, ""%s (UIDVALIDITY: %u, UIDNEXT: %u) %d messages, %d recent, %d unseen\n"", + status->name, status->uidvalidity, status->uidnext, + status->messages, status->recent, status->unseen); + + /* caller is prepared to handle the result herself */ + if (idata->cmddata && idata->cmdtype == IMAP_CT_STATUS) + { + memcpy(idata->cmddata, status, sizeof(struct ImapStatus)); + return; + } + + mutt_debug(3, ""Running default STATUS handler\n""); + + /* should perhaps move this code back to imap_buffy_check */ + for (inc = Incoming; inc; inc = inc->next) + { + if (inc->magic != MUTT_IMAP) + continue; + + if (imap_parse_path(inc->path, &mx) < 0) + { + mutt_debug(1, ""Error parsing mailbox %s, skipping\n"", inc->path); + continue; + } + + if (imap_account_match(&idata->conn->account, &mx.account)) + { + if (mx.mbox) + { + value = mutt_str_strdup(mx.mbox); + imap_fix_path(idata, mx.mbox, value, mutt_str_strlen(value) + 1); + FREE(&mx.mbox); + } + else + value = mutt_str_strdup(""INBOX""); + + if (value && (imap_mxcmp(mailbox, value) == 0)) + { + mutt_debug(3, ""Found %s in buffy list (OV: %u ON: %u U: %d)\n"", mailbox, + olduv, oldun, status->unseen); + + if (MailCheckRecent) + { + if (olduv && olduv == status->uidvalidity) + { + if (oldun < status->uidnext) + new = (status->unseen > 0); + } + else if (!olduv && !oldun) + { + /* first check per session, use recent. might need a flag for this. */ + new = (status->recent > 0); + } + else + new = (status->unseen > 0); + } + else + new = (status->unseen > 0); + +#ifdef USE_SIDEBAR + if ((inc->new != new) || (inc->msg_count != status->messages) || + (inc->msg_unread != status->unseen)) + { + mutt_menu_set_current_redraw(REDRAW_SIDEBAR); + } +#endif + inc->new = new; + if (new_msg_count) + inc->msg_count = status->messages; + inc->msg_unread = status->unseen; + + if (inc->new) + { + /* force back to keep detecting new mail until the mailbox is + opened */ + status->uidnext = oldun; + } + + FREE(&value); + return; + } + + FREE(&value); + } + + FREE(&mx.mbox); + } +} +",0,"static void cmd_parse_status(struct ImapData *idata, char *s) +{ + char *value = NULL; + struct Buffy *inc = NULL; + struct ImapMbox mx; + struct ImapStatus *status = NULL; + unsigned int olduv, oldun; + unsigned int litlen; + short new = 0; + short new_msg_count = 0; + + char *mailbox = imap_next_word(s); + + /* We need a real tokenizer. */ + if (imap_get_literal_count(mailbox, &litlen) == 0) + { + if (imap_cmd_step(idata) != IMAP_CMD_CONTINUE) + { + idata->status = IMAP_FATAL; + return; + } + mailbox = idata->buf; + s = mailbox + litlen; + *s = '\0'; + s++; + SKIPWS(s); + } + else + { + s = imap_next_word(mailbox); + *(s - 1) = '\0'; + imap_unmunge_mbox_name(idata, mailbox); + } + + status = imap_mboxcache_get(idata, mailbox, 1); + olduv = status->uidvalidity; + oldun = status->uidnext; + + if (*s++ != '(') + { + mutt_debug(1, ""Error parsing STATUS\n""); + return; + } + while (*s && *s != ')') + { + value = imap_next_word(s); + + errno = 0; + const unsigned long ulcount = strtoul(value, &value, 10); + if (((errno == ERANGE) && (ulcount == ULONG_MAX)) || ((unsigned int) ulcount != ulcount)) + { + mutt_debug(1, ""Error parsing STATUS number\n""); + return; + } + const unsigned int count = (unsigned int) ulcount; + + if (mutt_str_strncmp(""MESSAGES"", s, 8) == 0) + { + status->messages = count; + new_msg_count = 1; + } + else if (mutt_str_strncmp(""RECENT"", s, 6) == 0) + status->recent = count; + else if (mutt_str_strncmp(""UIDNEXT"", s, 7) == 0) + status->uidnext = count; + else if (mutt_str_strncmp(""UIDVALIDITY"", s, 11) == 0) + status->uidvalidity = count; + else if (mutt_str_strncmp(""UNSEEN"", s, 6) == 0) + status->unseen = count; + + s = value; + if (*s && *s != ')') + s = imap_next_word(s); + } + mutt_debug(3, ""%s (UIDVALIDITY: %u, UIDNEXT: %u) %d messages, %d recent, %d unseen\n"", + status->name, status->uidvalidity, status->uidnext, + status->messages, status->recent, status->unseen); + + /* caller is prepared to handle the result herself */ + if (idata->cmddata && idata->cmdtype == IMAP_CT_STATUS) + { + memcpy(idata->cmddata, status, sizeof(struct ImapStatus)); + return; + } + + mutt_debug(3, ""Running default STATUS handler\n""); + + /* should perhaps move this code back to imap_buffy_check */ + for (inc = Incoming; inc; inc = inc->next) + { + if (inc->magic != MUTT_IMAP) + continue; + + if (imap_parse_path(inc->path, &mx) < 0) + { + mutt_debug(1, ""Error parsing mailbox %s, skipping\n"", inc->path); + continue; + } + + if (imap_account_match(&idata->conn->account, &mx.account)) + { + if (mx.mbox) + { + value = mutt_str_strdup(mx.mbox); + imap_fix_path(idata, mx.mbox, value, mutt_str_strlen(value) + 1); + FREE(&mx.mbox); + } + else + value = mutt_str_strdup(""INBOX""); + + if (value && (imap_mxcmp(mailbox, value) == 0)) + { + mutt_debug(3, ""Found %s in buffy list (OV: %u ON: %u U: %d)\n"", mailbox, + olduv, oldun, status->unseen); + + if (MailCheckRecent) + { + if (olduv && olduv == status->uidvalidity) + { + if (oldun < status->uidnext) + new = (status->unseen > 0); + } + else if (!olduv && !oldun) + { + /* first check per session, use recent. might need a flag for this. */ + new = (status->recent > 0); + } + else + new = (status->unseen > 0); + } + else + new = (status->unseen > 0); + +#ifdef USE_SIDEBAR + if ((inc->new != new) || (inc->msg_count != status->messages) || + (inc->msg_unread != status->unseen)) + { + mutt_menu_set_current_redraw(REDRAW_SIDEBAR); + } +#endif + inc->new = new; + if (new_msg_count) + inc->msg_count = status->messages; + inc->msg_unread = status->unseen; + + if (inc->new) + { + /* force back to keep detecting new mail until the mailbox is + opened */ + status->uidnext = oldun; + } + + FREE(&value); + return; + } + + FREE(&value); + } + + FREE(&mx.mbox); + } +} +","@@ -499,7 +499,7 @@ static void cmd_parse_lsub(struct ImapData *idata, char *s) + mutt_str_strfcpy(buf, ""mailboxes \"""", sizeof(buf)); + mutt_account_tourl(&idata->conn->account, &url); + /* escape \ and "" */ +- imap_quote_string(errstr, sizeof(errstr), list.name); ++ imap_quote_string(errstr, sizeof(errstr), list.name, true); + url.path = errstr + 1; + url.path[strlen(url.path) - 1] = '\0'; + if (mutt_str_strcmp(url.user, ImapUser) == 0)",1247,1578,2048 +11321,"xsltKeyFunction(xmlXPathParserContextPtr ctxt, int nargs){ + xmlXPathObjectPtr obj1, obj2; + + if (nargs != 2) { + xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, + ""key() : expects two arguments\n""); + ctxt->error = XPATH_INVALID_ARITY; + return; + } + + /* + * Get the key's value. + */ + obj2 = valuePop(ctxt); + xmlXPathStringFunction(ctxt, 1); + if ((obj2 == NULL) || + (ctxt->value == NULL) || (ctxt->value->type != XPATH_STRING)) { + xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, + ""key() : invalid arg expecting a string\n""); + ctxt->error = XPATH_INVALID_TYPE; + xmlXPathFreeObject(obj2); + + return; + } + /* + * Get the key's name. + */ + obj1 = valuePop(ctxt); + + if ((obj2->type == XPATH_NODESET) || (obj2->type == XPATH_XSLT_TREE)) { + int i; + xmlXPathObjectPtr newobj, ret; + + ret = xmlXPathNewNodeSet(NULL); + + if (obj2->nodesetval != NULL) { + for (i = 0; i < obj2->nodesetval->nodeNr; i++) { + valuePush(ctxt, xmlXPathObjectCopy(obj1)); + valuePush(ctxt, + xmlXPathNewNodeSet(obj2->nodesetval->nodeTab[i])); + xmlXPathStringFunction(ctxt, 1); + xsltKeyFunction(ctxt, 2); + newobj = valuePop(ctxt); + ret->nodesetval = xmlXPathNodeSetMerge(ret->nodesetval, + newobj->nodesetval); + xmlXPathFreeObject(newobj); + } + } + valuePush(ctxt, ret); + } else { + xmlNodeSetPtr nodelist = NULL; + xmlChar *key = NULL, *value; + const xmlChar *keyURI; + xsltTransformContextPtr tctxt; + xmlChar *qname, *prefix; + xmlXPathContextPtr xpctxt = ctxt->context; + xmlNodePtr tmpNode = NULL; + xsltDocumentPtr oldDocInfo; + + tctxt = xsltXPathGetTransformContext(ctxt); + + oldDocInfo = tctxt->document; + + if (xpctxt->node == NULL) { + xsltTransformError(tctxt, NULL, tctxt->inst, + ""Internal error in xsltKeyFunction(): "" + ""The context node is not set on the XPath context.\n""); + tctxt->state = XSLT_STATE_STOPPED; + goto error; + } + /* + * Get the associated namespace URI if qualified name + */ + qname = obj1->stringval; + key = xmlSplitQName2(qname, &prefix); + if (key == NULL) { + key = xmlStrdup(obj1->stringval); + keyURI = NULL; + if (prefix != NULL) + xmlFree(prefix); + } else { + if (prefix != NULL) { + keyURI = xmlXPathNsLookup(xpctxt, prefix); + if (keyURI == NULL) { + xsltTransformError(tctxt, NULL, tctxt->inst, + ""key() : prefix %s is not bound\n"", prefix); + /* + * TODO: Shouldn't we stop here? + */ + } + xmlFree(prefix); + } else { + keyURI = NULL; + } + } + + /* + * Force conversion of first arg to string + */ + valuePush(ctxt, obj2); + xmlXPathStringFunction(ctxt, 1); + if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_STRING)) { + xsltTransformError(tctxt, NULL, tctxt->inst, + ""key() : invalid arg expecting a string\n""); + ctxt->error = XPATH_INVALID_TYPE; + goto error; + } + obj2 = valuePop(ctxt); + value = obj2->stringval; + + /* + * We need to ensure that ctxt->document is available for + * xsltGetKey(). + * First find the relevant doc, which is the context node's + * owner doc; using context->doc is not safe, since + * the doc could have been acquired via the document() function, + * or the doc might be a Result Tree Fragment. + * FUTURE INFO: In XSLT 2.0 the key() function takes an additional + * argument indicating the doc to use. + */ + if (xpctxt->node->type == XML_NAMESPACE_DECL) { + /* + * REVISIT: This is a libxml hack! Check xpath.c for details. + * The XPath module sets the owner element of a ns-node on + * the ns->next field. + */ + if ((((xmlNsPtr) xpctxt->node)->next != NULL) && + (((xmlNsPtr) xpctxt->node)->next->type == XML_ELEMENT_NODE)) + { + tmpNode = (xmlNodePtr) ((xmlNsPtr) xpctxt->node)->next; + } + } else + tmpNode = xpctxt->node; + + if ((tmpNode == NULL) || (tmpNode->doc == NULL)) { + xsltTransformError(tctxt, NULL, tctxt->inst, + ""Internal error in xsltKeyFunction(): "" + ""Couldn't get the doc of the XPath context node.\n""); + goto error; + } + + if ((tctxt->document == NULL) || + (tctxt->document->doc != tmpNode->doc)) + { + if (tmpNode->doc->name && (tmpNode->doc->name[0] == ' ')) { + /* + * This is a Result Tree Fragment. + */ + if (tmpNode->doc->_private == NULL) { + tmpNode->doc->_private = xsltNewDocument(tctxt, tmpNode->doc); + if (tmpNode->doc->_private == NULL) + goto error; + } + tctxt->document = (xsltDocumentPtr) tmpNode->doc->_private; + } else { + /* + * May be the initial source doc or a doc acquired via the + * document() function. + */ + tctxt->document = xsltFindDocument(tctxt, tmpNode->doc); + } + if (tctxt->document == NULL) { + xsltTransformError(tctxt, NULL, tctxt->inst, + ""Internal error in xsltKeyFunction(): "" + ""Could not get the document info of a context doc.\n""); + tctxt->state = XSLT_STATE_STOPPED; + goto error; + } + } + /* + * Get/compute the key value. + */ + nodelist = xsltGetKey(tctxt, key, keyURI, value); + +error: + tctxt->document = oldDocInfo; + valuePush(ctxt, xmlXPathWrapNodeSet( + xmlXPathNodeSetMerge(NULL, nodelist))); + if (key != NULL) + xmlFree(key); + } + + if (obj1 != NULL) + xmlXPathFreeObject(obj1); + if (obj2 != NULL) + xmlXPathFreeObject(obj2); +} +",0,"xsltKeyFunction(xmlXPathParserContextPtr ctxt, int nargs){ + xmlXPathObjectPtr obj1, obj2; + + if (nargs != 2) { + xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, + ""key() : expects two arguments\n""); + ctxt->error = XPATH_INVALID_ARITY; + return; + } + + /* + * Get the key's value. + */ + obj2 = valuePop(ctxt); + xmlXPathStringFunction(ctxt, 1); + if ((obj2 == NULL) || + (ctxt->value == NULL) || (ctxt->value->type != XPATH_STRING)) { + xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, + ""key() : invalid arg expecting a string\n""); + ctxt->error = XPATH_INVALID_TYPE; + xmlXPathFreeObject(obj2); + + return; + } + /* + * Get the key's name. + */ + obj1 = valuePop(ctxt); + + if ((obj2->type == XPATH_NODESET) || (obj2->type == XPATH_XSLT_TREE)) { + int i; + xmlXPathObjectPtr newobj, ret; + + ret = xmlXPathNewNodeSet(NULL); + + if (obj2->nodesetval != NULL) { + for (i = 0; i < obj2->nodesetval->nodeNr; i++) { + valuePush(ctxt, xmlXPathObjectCopy(obj1)); + valuePush(ctxt, + xmlXPathNewNodeSet(obj2->nodesetval->nodeTab[i])); + xmlXPathStringFunction(ctxt, 1); + xsltKeyFunction(ctxt, 2); + newobj = valuePop(ctxt); + ret->nodesetval = xmlXPathNodeSetMerge(ret->nodesetval, + newobj->nodesetval); + xmlXPathFreeObject(newobj); + } + } + valuePush(ctxt, ret); + } else { + xmlNodeSetPtr nodelist = NULL; + xmlChar *key = NULL, *value; + const xmlChar *keyURI; + xsltTransformContextPtr tctxt; + xmlChar *qname, *prefix; + xmlXPathContextPtr xpctxt = ctxt->context; + xmlNodePtr tmpNode = NULL; + xsltDocumentPtr oldDocInfo; + + tctxt = xsltXPathGetTransformContext(ctxt); + + oldDocInfo = tctxt->document; + + if (xpctxt->node == NULL) { + xsltTransformError(tctxt, NULL, tctxt->inst, + ""Internal error in xsltKeyFunction(): "" + ""The context node is not set on the XPath context.\n""); + tctxt->state = XSLT_STATE_STOPPED; + goto error; + } + /* + * Get the associated namespace URI if qualified name + */ + qname = obj1->stringval; + key = xmlSplitQName2(qname, &prefix); + if (key == NULL) { + key = xmlStrdup(obj1->stringval); + keyURI = NULL; + if (prefix != NULL) + xmlFree(prefix); + } else { + if (prefix != NULL) { + keyURI = xmlXPathNsLookup(xpctxt, prefix); + if (keyURI == NULL) { + xsltTransformError(tctxt, NULL, tctxt->inst, + ""key() : prefix %s is not bound\n"", prefix); + /* + * TODO: Shouldn't we stop here? + */ + } + xmlFree(prefix); + } else { + keyURI = NULL; + } + } + + /* + * Force conversion of first arg to string + */ + valuePush(ctxt, obj2); + xmlXPathStringFunction(ctxt, 1); + if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_STRING)) { + xsltTransformError(tctxt, NULL, tctxt->inst, + ""key() : invalid arg expecting a string\n""); + ctxt->error = XPATH_INVALID_TYPE; + goto error; + } + obj2 = valuePop(ctxt); + value = obj2->stringval; + + /* + * We need to ensure that ctxt->document is available for + * xsltGetKey(). + * First find the relevant doc, which is the context node's + * owner doc; using context->doc is not safe, since + * the doc could have been acquired via the document() function, + * or the doc might be a Result Tree Fragment. + * FUTURE INFO: In XSLT 2.0 the key() function takes an additional + * argument indicating the doc to use. + */ + if (xpctxt->node->type == XML_NAMESPACE_DECL) { + /* + * REVISIT: This is a libxml hack! Check xpath.c for details. + * The XPath module sets the owner element of a ns-node on + * the ns->next field. + */ + if ((((xmlNsPtr) xpctxt->node)->next != NULL) && + (((xmlNsPtr) xpctxt->node)->next->type == XML_ELEMENT_NODE)) + { + tmpNode = (xmlNodePtr) ((xmlNsPtr) xpctxt->node)->next; + } + } else + tmpNode = xpctxt->node; + + if ((tmpNode == NULL) || (tmpNode->doc == NULL)) { + xsltTransformError(tctxt, NULL, tctxt->inst, + ""Internal error in xsltKeyFunction(): "" + ""Couldn't get the doc of the XPath context node.\n""); + goto error; + } + + if ((tctxt->document == NULL) || + (tctxt->document->doc != tmpNode->doc)) + { + if (tmpNode->doc->name && (tmpNode->doc->name[0] == ' ')) { + /* + * This is a Result Tree Fragment. + */ + if (tmpNode->doc->_private == NULL) { + tmpNode->doc->_private = xsltNewDocument(tctxt, tmpNode->doc); + if (tmpNode->doc->_private == NULL) + goto error; + } + tctxt->document = (xsltDocumentPtr) tmpNode->doc->_private; + } else { + /* + * May be the initial source doc or a doc acquired via the + * document() function. + */ + tctxt->document = xsltFindDocument(tctxt, tmpNode->doc); + } + if (tctxt->document == NULL) { + xsltTransformError(tctxt, NULL, tctxt->inst, + ""Internal error in xsltKeyFunction(): "" + ""Could not get the document info of a context doc.\n""); + tctxt->state = XSLT_STATE_STOPPED; + goto error; + } + } + /* + * Get/compute the key value. + */ + nodelist = xsltGetKey(tctxt, key, keyURI, value); + +error: + tctxt->document = oldDocInfo; + valuePush(ctxt, xmlXPathWrapNodeSet( + xmlXPathNodeSetMerge(NULL, nodelist))); + if (key != NULL) + xmlFree(key); + } + + if (obj1 != NULL) + xmlXPathFreeObject(obj1); + if (obj2 != NULL) + xmlXPathFreeObject(obj2); +} +","@@ -654,14 +654,14 @@ xsltFormatNumberFunction(xmlXPathParserContextPtr ctxt, int nargs) + void + xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs){ + xmlNodePtr cur = NULL; ++ xmlXPathObjectPtr obj = NULL; + long val; + xmlChar str[30]; + xmlDocPtr doc; + + if (nargs == 0) { + cur = ctxt->context->node; + } else if (nargs == 1) { +- xmlXPathObjectPtr obj; + xmlNodeSetPtr nodelist; + int i, ret; + +@@ -684,7 +684,6 @@ xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs){ + if (ret == -1) + cur = nodelist->nodeTab[i]; + } +- xmlXPathFreeObject(obj); + } else { + xsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL, + ""generate-id() : invalid number of args %d\n"", nargs); +@@ -707,6 +706,9 @@ xsltGenerateIdFunction(xmlXPathParserContextPtr ctxt, int nargs){ + + } + ++ if (obj) ++ xmlXPathFreeObject(obj); ++ + val = (long)((char *)cur - (char *)doc); + if (val >= 0) { + sprintf((char *)str, ""idp%ld"", val);",1562,1893,2048 +5045,"static void opj_get_encoding_parameters( const opj_image_t *p_image, + const opj_cp_t *p_cp, + OPJ_UINT32 p_tileno, + OPJ_INT32 * p_tx0, + OPJ_INT32 * p_tx1, + OPJ_INT32 * p_ty0, + OPJ_INT32 * p_ty1, + OPJ_UINT32 * p_dx_min, + OPJ_UINT32 * p_dy_min, + OPJ_UINT32 * p_max_prec, + OPJ_UINT32 * p_max_res ) +{ + /* loop */ + OPJ_UINT32 compno, resno; + /* pointers */ + const opj_tcp_t *l_tcp = 00; + const opj_tccp_t * l_tccp = 00; + const opj_image_comp_t * l_img_comp = 00; + + /* position in x and y of tile */ + OPJ_UINT32 p, q; + + /* preconditions */ + assert(p_cp != 00); + assert(p_image != 00); + assert(p_tileno < p_cp->tw * p_cp->th); + + /* initializations */ + l_tcp = &p_cp->tcps [p_tileno]; + l_img_comp = p_image->comps; + l_tccp = l_tcp->tccps; + + /* here calculation of tx0, tx1, ty0, ty1, maxprec, dx and dy */ + p = p_tileno % p_cp->tw; + q = p_tileno / p_cp->tw; + + /* find extent of tile */ + *p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx), (OPJ_INT32)p_image->x0); + *p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx), (OPJ_INT32)p_image->x1); + *p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy), (OPJ_INT32)p_image->y0); + *p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy), (OPJ_INT32)p_image->y1); + + /* max precision is 0 (can only grow) */ + *p_max_prec = 0; + *p_max_res = 0; + + /* take the largest value for dx_min and dy_min */ + *p_dx_min = 0x7fffffff; + *p_dy_min = 0x7fffffff; + + for (compno = 0; compno < p_image->numcomps; ++compno) { + /* arithmetic variables to calculate */ + OPJ_UINT32 l_level_no; + OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1; + OPJ_INT32 l_px0, l_py0, l_px1, py1; + OPJ_UINT32 l_pdx, l_pdy; + OPJ_UINT32 l_pw, l_ph; + OPJ_UINT32 l_product; + OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1; + + l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx); + l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy); + l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx); + l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy); + + if (l_tccp->numresolutions > *p_max_res) { + *p_max_res = l_tccp->numresolutions; + } + + /* use custom size for precincts */ + for (resno = 0; resno < l_tccp->numresolutions; ++resno) { + OPJ_UINT32 l_dx, l_dy; + + /* precinct width and height */ + l_pdx = l_tccp->prcw[resno]; + l_pdy = l_tccp->prch[resno]; + + l_dx = l_img_comp->dx * (1u << (l_pdx + l_tccp->numresolutions - 1 - resno)); + l_dy = l_img_comp->dy * (1u << (l_pdy + l_tccp->numresolutions - 1 - resno)); + + /* take the minimum size for dx for each comp and resolution */ + *p_dx_min = opj_uint_min(*p_dx_min, l_dx); + *p_dy_min = opj_uint_min(*p_dy_min, l_dy); + + /* various calculations of extents */ + l_level_no = l_tccp->numresolutions - 1 - resno; + + l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no); + l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no); + l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no); + l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no); + + l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx; + l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy; + l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx; + + py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy; + + l_pw = (l_rx0==l_rx1)?0:(OPJ_UINT32)((l_px1 - l_px0) >> l_pdx); + l_ph = (l_ry0==l_ry1)?0:(OPJ_UINT32)((py1 - l_py0) >> l_pdy); + + l_product = l_pw * l_ph; + + /* update precision */ + if (l_product > *p_max_prec) { + *p_max_prec = l_product; + } + } + ++l_img_comp; + ++l_tccp; + } +} +",0,"static void opj_get_encoding_parameters( const opj_image_t *p_image, + const opj_cp_t *p_cp, + OPJ_UINT32 p_tileno, + OPJ_INT32 * p_tx0, + OPJ_INT32 * p_tx1, + OPJ_INT32 * p_ty0, + OPJ_INT32 * p_ty1, + OPJ_UINT32 * p_dx_min, + OPJ_UINT32 * p_dy_min, + OPJ_UINT32 * p_max_prec, + OPJ_UINT32 * p_max_res ) +{ + /* loop */ + OPJ_UINT32 compno, resno; + /* pointers */ + const opj_tcp_t *l_tcp = 00; + const opj_tccp_t * l_tccp = 00; + const opj_image_comp_t * l_img_comp = 00; + + /* position in x and y of tile */ + OPJ_UINT32 p, q; + + /* preconditions */ + assert(p_cp != 00); + assert(p_image != 00); + assert(p_tileno < p_cp->tw * p_cp->th); + + /* initializations */ + l_tcp = &p_cp->tcps [p_tileno]; + l_img_comp = p_image->comps; + l_tccp = l_tcp->tccps; + + /* here calculation of tx0, tx1, ty0, ty1, maxprec, dx and dy */ + p = p_tileno % p_cp->tw; + q = p_tileno / p_cp->tw; + + /* find extent of tile */ + *p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx), (OPJ_INT32)p_image->x0); + *p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx), (OPJ_INT32)p_image->x1); + *p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy), (OPJ_INT32)p_image->y0); + *p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy), (OPJ_INT32)p_image->y1); + + /* max precision is 0 (can only grow) */ + *p_max_prec = 0; + *p_max_res = 0; + + /* take the largest value for dx_min and dy_min */ + *p_dx_min = 0x7fffffff; + *p_dy_min = 0x7fffffff; + + for (compno = 0; compno < p_image->numcomps; ++compno) { + /* arithmetic variables to calculate */ + OPJ_UINT32 l_level_no; + OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1; + OPJ_INT32 l_px0, l_py0, l_px1, py1; + OPJ_UINT32 l_pdx, l_pdy; + OPJ_UINT32 l_pw, l_ph; + OPJ_UINT32 l_product; + OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1; + + l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx); + l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy); + l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx); + l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy); + + if (l_tccp->numresolutions > *p_max_res) { + *p_max_res = l_tccp->numresolutions; + } + + /* use custom size for precincts */ + for (resno = 0; resno < l_tccp->numresolutions; ++resno) { + OPJ_UINT32 l_dx, l_dy; + + /* precinct width and height */ + l_pdx = l_tccp->prcw[resno]; + l_pdy = l_tccp->prch[resno]; + + l_dx = l_img_comp->dx * (1u << (l_pdx + l_tccp->numresolutions - 1 - resno)); + l_dy = l_img_comp->dy * (1u << (l_pdy + l_tccp->numresolutions - 1 - resno)); + + /* take the minimum size for dx for each comp and resolution */ + *p_dx_min = opj_uint_min(*p_dx_min, l_dx); + *p_dy_min = opj_uint_min(*p_dy_min, l_dy); + + /* various calculations of extents */ + l_level_no = l_tccp->numresolutions - 1 - resno; + + l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no); + l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no); + l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no); + l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no); + + l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx; + l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy; + l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx; + + py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy; + + l_pw = (l_rx0==l_rx1)?0:(OPJ_UINT32)((l_px1 - l_px0) >> l_pdx); + l_ph = (l_ry0==l_ry1)?0:(OPJ_UINT32)((py1 - l_py0) >> l_pdy); + + l_product = l_pw * l_ph; + + /* update precision */ + if (l_product > *p_max_prec) { + *p_max_prec = l_product; + } + } + ++l_img_comp; + ++l_tccp; + } +} +","@@ -1237,7 +1237,13 @@ opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image, + l_current_pi = l_pi; + + /* memory allocation for include */ +- l_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16)); ++ /* prevent an integer overflow issue */ ++ l_current_pi->include = 00; ++ if (l_step_l <= (SIZE_MAX / (l_tcp->numlayers + 1U))) ++ { ++ l_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16)); ++ } ++ + if + (!l_current_pi->include) + {",1522,1853,2048 +17865,"static int huft_build(const unsigned *b, const unsigned n, + const unsigned s, const unsigned short *d, + const unsigned char *e, huft_t **t, unsigned *m) +{ + unsigned a; /* counter for codes of length k */ + unsigned c[BMAX + 1]; /* bit length count table */ + unsigned eob_len; /* length of end-of-block code (value 256) */ + unsigned f; /* i repeats in table every f entries */ + int g; /* maximum code length */ + int htl; /* table level */ + unsigned i; /* counter, current code */ + unsigned j; /* counter */ + int k; /* number of bits in current code */ + unsigned *p; /* pointer into c[], b[], or v[] */ + huft_t *q; /* points to current table */ + huft_t r; /* table entry for structure assignment */ + huft_t *u[BMAX]; /* table stack */ + unsigned v[N_MAX]; /* values in order of bit length */ + int ws[BMAX + 1]; /* bits decoded stack */ + int w; /* bits decoded */ + unsigned x[BMAX + 1]; /* bit offsets, then code stack */ + int y; /* number of dummy codes added */ + unsigned z; /* number of entries in current table */ + + /* Length of EOB code, if any */ + eob_len = n > 256 ? b[256] : BMAX; + + *t = NULL; + + + /* Generate counts for each bit length */ + memset(c, 0, sizeof(c)); + p = (unsigned *) b; /* cast allows us to reuse p for pointing to b */ + i = n; + do { + c[*p]++; /* assume all entries <= BMAX */ + } while (--i); + if (c[0] == n) { /* null input - all zero length codes */ + *m = 0; + return 2; + } + + /* Find minimum and maximum length, bound *m by those */ + for (j = 1; (j <= BMAX) && (c[j] == 0); j++) + continue; + k = j; /* minimum code length */ + for (i = BMAX; (c[i] == 0) && i; i--) + continue; + g = i; /* maximum code length */ + *m = (*m < j) ? j : ((*m > i) ? i : *m); + + /* Adjust last length count to fill out codes, if needed */ + for (y = 1 << j; j < i; j++, y <<= 1) { + y -= c[j]; + if (y < 0) + return 2; /* bad input: more codes than bits */ + } + y -= c[i]; + if (y < 0) + return 2; + c[i] += y; + + /* Generate starting offsets into the value table for each length */ + x[1] = j = 0; + p = c + 1; + xp = x + 2; + while (--i) { /* note that i == g from above */ + j += *p++; + *xp++ = j; + } + } +",1,"static int huft_build(const unsigned *b, const unsigned n, + const unsigned s, const unsigned short *d, + const unsigned char *e, huft_t **t, unsigned *m) +{ + unsigned a; /* counter for codes of length k */ + unsigned c[BMAX + 1]; /* bit length count table */ + unsigned eob_len; /* length of end-of-block code (value 256) */ + unsigned f; /* i repeats in table every f entries */ + int g; /* maximum code length */ + int htl; /* table level */ + unsigned i; /* counter, current code */ + unsigned j; /* counter */ + int k; /* number of bits in current code */ + const unsigned *p; /* pointer into c[], b[], or v[] */ + huft_t *q; /* points to current table */ + huft_t r; /* table entry for structure assignment */ + huft_t *u[BMAX]; /* table stack */ + unsigned v[N_MAX]; /* values in order of bit length */ + unsigned v_end; + int ws[BMAX + 1]; /* bits decoded stack */ + int w; /* bits decoded */ + unsigned x[BMAX + 1]; /* bit offsets, then code stack */ + int y; /* number of dummy codes added */ + unsigned z; /* number of entries in current table */ + + /* Length of EOB code, if any */ + eob_len = n > 256 ? b[256] : BMAX; + + *t = NULL; + + + /* Generate counts for each bit length */ + memset(c, 0, sizeof(c)); + p = b; + i = n; + do { + c[*p]++; /* assume all entries <= BMAX */ + } while (--i); + if (c[0] == n) { /* null input - all zero length codes */ + *m = 0; + return 2; + } + + /* Find minimum and maximum length, bound *m by those */ + for (j = 1; (j <= BMAX) && (c[j] == 0); j++) + continue; + k = j; /* minimum code length */ + for (i = BMAX; (c[i] == 0) && i; i--) + continue; + g = i; /* maximum code length */ + *m = (*m < j) ? j : ((*m > i) ? i : *m); + + /* Adjust last length count to fill out codes, if needed */ + for (y = 1 << j; j < i; j++, y <<= 1) { + y -= c[j]; + if (y < 0) + return 2; /* bad input: more codes than bits */ + } + y -= c[i]; + if (y < 0) + return 2; + c[i] += y; + + /* Generate starting offsets into the value table for each length */ + x[1] = j = 0; + p = c + 1; + xp = x + 2; + while (--i) { /* note that i == g from above */ + j += *p++; + *xp++ = j; + } + } +","@@ -305,11 +305,12 @@ static int huft_build(const unsigned *b, const unsigned n, + unsigned i; /* counter, current code */ + unsigned j; /* counter */ + int k; /* number of bits in current code */ +- unsigned *p; /* pointer into c[], b[], or v[] */ ++ const unsigned *p; /* pointer into c[], b[], or v[] */ + huft_t *q; /* points to current table */ + huft_t r; /* table entry for structure assignment */ + huft_t *u[BMAX]; /* table stack */ + unsigned v[N_MAX]; /* values in order of bit length */ ++ unsigned v_end; + int ws[BMAX + 1]; /* bits decoded stack */ + int w; /* bits decoded */ + unsigned x[BMAX + 1]; /* bit offsets, then code stack */ +@@ -324,7 +325,7 @@ static int huft_build(const unsigned *b, const unsigned n, + + /* Generate counts for each bit length */ + memset(c, 0, sizeof(c)); +- p = (unsigned *) b; /* cast allows us to reuse p for pointing to b */ ++ p = b; + i = n; + do { + c[*p]++; /* assume all entries <= BMAX */ +@@ -365,12 +366,14 @@ static int huft_build(const unsigned *b, const unsigned n, + } + + /* Make a table of values in order of bit lengths */ +- p = (unsigned *) b; ++ p = b; + i = 0; ++ v_end = 0; + do { + j = *p++; + if (j != 0) { + v[x[j]++] = i; ++ v_end = x[j]; + } + } while (++i < n); + +@@ -432,7 +435,7 @@ static int huft_build(const unsigned *b, const unsigned n, + + /* set up table entry in r */ + r.b = (unsigned char) (k - w); +- if (p >= v + n) { ++ if (p >= v + v_end) { // Was ""if (p >= v + n)"" but v[] can be shorter! + r.e = 99; /* out of values--invalid code */ + } else if (*p < s) { + r.e = (unsigned char) (*p < 256 ? 16 : 15); /* 256 is EOB code */",695,1026,2048 +18161,"get_page_image(LoadContext *lc, ddjvu_page_t *page, int x, int y, int w, int h, const ImageInfo *image_info ) { + ddjvu_format_t + *format; + + ddjvu_page_type_t + type; + + Image + *image; + + int + ret, + stride; + + unsigned char + *q; + + ddjvu_rect_t rect; + rect.x = x; + rect.y = y; + rect.w = (unsigned int) w; /* /10 */ + rect.h = (unsigned int) h; /* /10 */ + + image = lc->image; + type = ddjvu_page_get_type(lc->page); + + /* stride of this temporary buffer: */ + stride = (type == DDJVU_PAGETYPE_BITONAL)? + (image->columns + 7)/8 : image->columns *3; + + q = (unsigned char *) AcquireQuantumMemory(image->rows,stride); + if (q == (unsigned char *) NULL) + return; + + format = ddjvu_format_create( + (type == DDJVU_PAGETYPE_BITONAL)?DDJVU_FORMAT_LSBTOMSB : DDJVU_FORMAT_RGB24, + /* DDJVU_FORMAT_RGB24 + * DDJVU_FORMAT_RGBMASK32*/ + /* DDJVU_FORMAT_RGBMASK32 */ + 0, NULL); + +#if 0 + /* fixme: ThrowReaderException is a macro, which uses `exception' variable */ + if (format == NULL) + { + abort(); + /* ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); */ + } + +#endif + ddjvu_format_set_row_order(format, 1); + ddjvu_format_set_y_direction(format, 1); + + ret = ddjvu_page_render(page, + DDJVU_RENDER_COLOR, /* ddjvu_render_mode_t */ + &rect, + &rect, /* mmc: ?? */ + format, + stride, /* ?? */ + (char*)q); + (void) ret; + ddjvu_format_release(format); + + + if (type == DDJVU_PAGETYPE_BITONAL) { + /* */ +#if DEBUG + printf(""%s: expanding BITONAL page/image\n"", __FUNCTION__); +#endif + register IndexPacket *indexes; + size_t bit, byte; + + for (y=0; y < (ssize_t) image->rows; y++) + { + PixelPacket * o = QueueAuthenticPixels(image,0,y,image->columns,1,&image->exception); + if (o == (PixelPacket *) NULL) + break; + indexes=GetAuthenticIndexQueue(image); + bit=0; + byte=0; + + /* fixme: the non-aligned, last =<7 bits ! that's ok!!!*/ + for (x= 0; x < (ssize_t) image->columns; x++) + { + if (bit == 0) byte= (size_t) q[(y * stride) + (x / 8)]; + + if (indexes != (IndexPacket *) NULL) + SetPixelIndex(indexes+x,(IndexPacket) (((byte & 0x01) != 0) ? 0x00 : 0x01)); + bit++; + if (bit == 8) + bit=0; + byte>>=1; + } + if (SyncAuthenticPixels(image,&image->exception) == MagickFalse) + break; + } + if (!image->ping) + SyncImage(image); + } else { + #if DEBUG + printf(""%s: expanding PHOTO page/image\n"", __FUNCTION__); +#endif + /* now transfer line-wise: */ + ssize_t i; +#if 0 + /* old: */ + char* r; +#else + register PixelPacket *r; + unsigned char *s; +#endif + s=q; + for (i = 0;i< (ssize_t) image->rows; i++) + { +#if DEBUG + if (i % 1000 == 0) printf(""%d\n"",i); +#endif + r = QueueAuthenticPixels(image,0,i,image->columns,1,&image->exception); + if (r == (PixelPacket *) NULL) + break; + for (x=0; x < (ssize_t) image->columns; x++) + { + SetPixelRed(r,ScaleCharToQuantum(*s++)); + SetPixelGreen(r,ScaleCharToQuantum(*s++)); + SetPixelBlue(r,ScaleCharToQuantum(*s++)); + r++; + } + + (void) SyncAuthenticPixels(image,&image->exception); + } + } + q=(unsigned char *) RelinquishMagickMemory(q); +} +",1,"get_page_image(LoadContext *lc, ddjvu_page_t *page, int x, int y, int w, int h, const ImageInfo *image_info ) { + ddjvu_format_t + *format; + + ddjvu_page_type_t + type; + + Image + *image; + + int + ret, + stride; + + unsigned char + *q; + + ddjvu_rect_t rect; + rect.x = x; + rect.y = y; + rect.w = (unsigned int) w; /* /10 */ + rect.h = (unsigned int) h; /* /10 */ + + image = lc->image; + type = ddjvu_page_get_type(lc->page); + + /* stride of this temporary buffer: */ + stride = (type == DDJVU_PAGETYPE_BITONAL)? + (image->columns + 7)/8 : image->columns *3; + + q = (unsigned char *) AcquireQuantumMemory(image->rows,stride); + if (q == (unsigned char *) NULL) + return; + + format = ddjvu_format_create( + (type == DDJVU_PAGETYPE_BITONAL)?DDJVU_FORMAT_LSBTOMSB : DDJVU_FORMAT_RGB24, + /* DDJVU_FORMAT_RGB24 + * DDJVU_FORMAT_RGBMASK32*/ + /* DDJVU_FORMAT_RGBMASK32 */ + 0, NULL); + +#if 0 + /* fixme: ThrowReaderException is a macro, which uses `exception' variable */ + if (format == NULL) + { + abort(); + /* ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); */ + } + +#endif + ddjvu_format_set_row_order(format, 1); + ddjvu_format_set_y_direction(format, 1); + + ret = ddjvu_page_render(page, + DDJVU_RENDER_COLOR, /* ddjvu_render_mode_t */ + &rect, + &rect, /* mmc: ?? */ + format, + stride, /* ?? */ + (char*)q); + (void) ret; + ddjvu_format_release(format); + + + if (type == DDJVU_PAGETYPE_BITONAL) { + /* */ +#if DEBUG + printf(""%s: expanding BITONAL page/image\n"", __FUNCTION__); +#endif + register IndexPacket *indexes; + size_t bit, byte; + + for (y=0; y < (ssize_t) image->rows; y++) + { + PixelPacket * o = QueueAuthenticPixels(image,0,y,image->columns,1,&image->exception); + if (o == (PixelPacket *) NULL) + break; + indexes=GetAuthenticIndexQueue(image); + bit=0; + byte=0; + + /* fixme: the non-aligned, last =<7 bits ! that's ok!!!*/ + for (x= 0; x < (ssize_t) image->columns; x++) + { + if (bit == 0) byte= (size_t) q[(y * stride) + (x / 8)]; + + if (indexes != (IndexPacket *) NULL) + SetPixelIndex(indexes+x,(IndexPacket) (((byte & 0x01) != 0) ? 0x00 : 0x01)); + bit++; + if (bit == 8) + bit=0; + byte>>=1; + } + if (SyncAuthenticPixels(image,&image->exception) == MagickFalse) + break; + } + if (image->ping == MagickFalse) + SyncImage(image); + } else { + #if DEBUG + printf(""%s: expanding PHOTO page/image\n"", __FUNCTION__); +#endif + /* now transfer line-wise: */ + ssize_t i; +#if 0 + /* old: */ + char* r; +#else + register PixelPacket *r; + unsigned char *s; +#endif + s=q; + for (i = 0;i< (ssize_t) image->rows; i++) + { +#if DEBUG + if (i % 1000 == 0) printf(""%d\n"",i); +#endif + r = QueueAuthenticPixels(image,0,i,image->columns,1,&image->exception); + if (r == (PixelPacket *) NULL) + break; + for (x=0; x < (ssize_t) image->columns; x++) + { + SetPixelRed(r,ScaleCharToQuantum(*s++)); + SetPixelGreen(r,ScaleCharToQuantum(*s++)); + SetPixelBlue(r,ScaleCharToQuantum(*s++)); + r++; + } + + (void) SyncAuthenticPixels(image,&image->exception); + } + } + q=(unsigned char *) RelinquishMagickMemory(q); +} +","@@ -418,7 +418,7 @@ get_page_image(LoadContext *lc, ddjvu_page_t *page, int x, int y, int w, int h, + if (SyncAuthenticPixels(image,&image->exception) == MagickFalse) + break; + } +- if (!image->ping) ++ if (image->ping == MagickFalse) + SyncImage(image); + } else { + #if DEBUG +@@ -577,6 +577,7 @@ static Image *ReadOneDJVUImage(LoadContext* lc,const int pagenum, + Image *image; + int logging; + int tag; ++ MagickBooleanType status; + + /* so, we know that the page is there! Get its dimension, and */ + +@@ -667,6 +668,12 @@ static Image *ReadOneDJVUImage(LoadContext* lc,const int pagenum, + image->matte = MagickTrue; + /* is this useful? */ + } ++ status=SetImageExtent(image,image->columns,image->rows); ++ if (status == MagickFalse) ++ { ++ InheritException(exception,&image->exception); ++ return(DestroyImageList(image)); ++ } + #if DEBUG + printf(""now filling %.20g x %.20g\n"",(double) image->columns,(double) + image->rows);",1026,1357,2048 +17300,"perform_gamma_test(png_modifier *pm, int summary) +{ + /*TODO: remove this*/ + /* Save certain values for the temporary overrides below. */ + unsigned int calculations_use_input_precision = + pm->calculations_use_input_precision; +# ifdef PNG_READ_BACKGROUND_SUPPORTED + double maxout8 = pm->maxout8; +# endif + + /* First some arbitrary no-transform tests: */ + if (!pm->this.speed && pm->test_gamma_threshold) + { + perform_gamma_threshold_tests(pm); + + if (fail(pm)) + return; + } + + /* Now some real transforms. */ + if (pm->test_gamma_transform) + { + if (summary) + { + fflush(stderr); + printf(""Gamma correction error summary\n\n""); + printf(""The printed value is the maximum error in the pixel values\n""); + printf(""calculated by the libpng gamma correction code. The error\n""); + printf(""is calculated as the difference between the output pixel\n""); + printf(""value (always an integer) and the ideal value from the\n""); + printf(""libpng specification (typically not an integer).\n\n""); + + printf(""Expect this value to be less than .5 for 8 bit formats,\n""); + printf(""less than 1 for formats with fewer than 8 bits and a small\n""); + printf(""number (typically less than 5) for the 16 bit formats.\n""); + printf(""For performance reasons the value for 16 bit formats\n""); + printf(""increases when the image file includes an sBIT chunk.\n""); + fflush(stdout); + } + + init_gamma_errors(pm); + /*TODO: remove this. Necessary because the current libpng + * implementation works in 8 bits: + */ + if (pm->test_gamma_expand16) + pm->calculations_use_input_precision = 1; + perform_gamma_transform_tests(pm); + if (!calculations_use_input_precision) + pm->calculations_use_input_precision = 0; + + if (summary) + summarize_gamma_errors(pm, 0/*who*/, 1/*low bit depth*/, 1/*indexed*/); + + if (fail(pm)) + return; + } + + /* The sbit tests produce much larger errors: */ + if (pm->test_gamma_sbit) + { + init_gamma_errors(pm); + perform_gamma_sbit_tests(pm); + + if (summary) + summarize_gamma_errors(pm, ""sBIT"", pm->sbitlow < 8U, 1/*indexed*/); + + if (fail(pm)) + return; + } + +#ifdef DO_16BIT /* Should be READ_16BIT_SUPPORTED */ + if (pm->test_gamma_scale16) + { + /* The 16 to 8 bit strip operations: */ + init_gamma_errors(pm); + perform_gamma_scale16_tests(pm); + + if (summary) + { + fflush(stderr); + printf(""\nGamma correction with 16 to 8 bit reduction:\n""); + printf("" 16 bit gray: %.5f\n"", pm->error_gray_16); + printf("" 16 bit color: %.5f\n"", pm->error_color_16); + fflush(stdout); + } + + if (fail(pm)) + return; + } +#endif + +#ifdef PNG_READ_BACKGROUND_SUPPORTED + if (pm->test_gamma_background) + { + init_gamma_errors(pm); + + /*TODO: remove this. Necessary because the current libpng + * implementation works in 8 bits: + */ + if (pm->test_gamma_expand16) + { + pm->calculations_use_input_precision = 1; + pm->maxout8 = .499; /* because the 16 bit background is smashed */ + } + perform_gamma_composition_tests(pm, PNG_BACKGROUND_GAMMA_UNIQUE, + pm->test_gamma_expand16); + if (!calculations_use_input_precision) + pm->calculations_use_input_precision = 0; + pm->maxout8 = maxout8; + + if (summary) + summarize_gamma_errors(pm, ""background"", 1, 0/*indexed*/); + + if (fail(pm)) + return; + } +#endif + +#ifdef PNG_READ_ALPHA_MODE_SUPPORTED + if (pm->test_gamma_alpha_mode) + { + int do_background; + + init_gamma_errors(pm); + + /*TODO: remove this. Necessary because the current libpng + * implementation works in 8 bits: + */ + if (pm->test_gamma_expand16) + pm->calculations_use_input_precision = 1; + for (do_background = ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD; + do_background <= ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN && !fail(pm); + ++do_background) + perform_gamma_composition_tests(pm, do_background, + pm->test_gamma_expand16); + if (!calculations_use_input_precision) + pm->calculations_use_input_precision = 0; + + if (summary) + summarize_gamma_errors(pm, ""alpha mode"", 1, 0/*indexed*/); + + if (fail(pm)) + return; + } +#endif +} +",0,"perform_gamma_test(png_modifier *pm, int summary) +{ + /*TODO: remove this*/ + /* Save certain values for the temporary overrides below. */ + unsigned int calculations_use_input_precision = + pm->calculations_use_input_precision; +# ifdef PNG_READ_BACKGROUND_SUPPORTED + double maxout8 = pm->maxout8; +# endif + + /* First some arbitrary no-transform tests: */ + if (!pm->this.speed && pm->test_gamma_threshold) + { + perform_gamma_threshold_tests(pm); + + if (fail(pm)) + return; + } + + /* Now some real transforms. */ + if (pm->test_gamma_transform) + { + if (summary) + { + fflush(stderr); + printf(""Gamma correction error summary\n\n""); + printf(""The printed value is the maximum error in the pixel values\n""); + printf(""calculated by the libpng gamma correction code. The error\n""); + printf(""is calculated as the difference between the output pixel\n""); + printf(""value (always an integer) and the ideal value from the\n""); + printf(""libpng specification (typically not an integer).\n\n""); + + printf(""Expect this value to be less than .5 for 8 bit formats,\n""); + printf(""less than 1 for formats with fewer than 8 bits and a small\n""); + printf(""number (typically less than 5) for the 16 bit formats.\n""); + printf(""For performance reasons the value for 16 bit formats\n""); + printf(""increases when the image file includes an sBIT chunk.\n""); + fflush(stdout); + } + + init_gamma_errors(pm); + /*TODO: remove this. Necessary because the current libpng + * implementation works in 8 bits: + */ + if (pm->test_gamma_expand16) + pm->calculations_use_input_precision = 1; + perform_gamma_transform_tests(pm); + if (!calculations_use_input_precision) + pm->calculations_use_input_precision = 0; + + if (summary) + summarize_gamma_errors(pm, 0/*who*/, 1/*low bit depth*/, 1/*indexed*/); + + if (fail(pm)) + return; + } + + /* The sbit tests produce much larger errors: */ + if (pm->test_gamma_sbit) + { + init_gamma_errors(pm); + perform_gamma_sbit_tests(pm); + + if (summary) + summarize_gamma_errors(pm, ""sBIT"", pm->sbitlow < 8U, 1/*indexed*/); + + if (fail(pm)) + return; + } + +#ifdef DO_16BIT /* Should be READ_16BIT_SUPPORTED */ + if (pm->test_gamma_scale16) + { + /* The 16 to 8 bit strip operations: */ + init_gamma_errors(pm); + perform_gamma_scale16_tests(pm); + + if (summary) + { + fflush(stderr); + printf(""\nGamma correction with 16 to 8 bit reduction:\n""); + printf("" 16 bit gray: %.5f\n"", pm->error_gray_16); + printf("" 16 bit color: %.5f\n"", pm->error_color_16); + fflush(stdout); + } + + if (fail(pm)) + return; + } +#endif + +#ifdef PNG_READ_BACKGROUND_SUPPORTED + if (pm->test_gamma_background) + { + init_gamma_errors(pm); + + /*TODO: remove this. Necessary because the current libpng + * implementation works in 8 bits: + */ + if (pm->test_gamma_expand16) + { + pm->calculations_use_input_precision = 1; + pm->maxout8 = .499; /* because the 16 bit background is smashed */ + } + perform_gamma_composition_tests(pm, PNG_BACKGROUND_GAMMA_UNIQUE, + pm->test_gamma_expand16); + if (!calculations_use_input_precision) + pm->calculations_use_input_precision = 0; + pm->maxout8 = maxout8; + + if (summary) + summarize_gamma_errors(pm, ""background"", 1, 0/*indexed*/); + + if (fail(pm)) + return; + } +#endif + +#ifdef PNG_READ_ALPHA_MODE_SUPPORTED + if (pm->test_gamma_alpha_mode) + { + int do_background; + + init_gamma_errors(pm); + + /*TODO: remove this. Necessary because the current libpng + * implementation works in 8 bits: + */ + if (pm->test_gamma_expand16) + pm->calculations_use_input_precision = 1; + for (do_background = ALPHA_MODE_OFFSET + PNG_ALPHA_STANDARD; + do_background <= ALPHA_MODE_OFFSET + PNG_ALPHA_BROKEN && !fail(pm); + ++do_background) + perform_gamma_composition_tests(pm, do_background, + pm->test_gamma_expand16); + if (!calculations_use_input_precision) + pm->calculations_use_input_precision = 0; + + if (summary) + summarize_gamma_errors(pm, ""alpha mode"", 1, 0/*indexed*/); + + if (fail(pm)) + return; + } +#endif +} +","@@ -1,8 +1,8 @@ + + + /* pngvalid.c - validate libpng by constructing then reading png files. + * +- * Last changed in libpng 1.6.10 [March 6, 2014] +- * Copyright (c) 2014 Glenn Randers-Pehrson ++ * Last changed in libpng 1.5.25 [December 3, 2015] ++ * Copyright (c) 2014-2015 Glenn Randers-Pehrson + * Written by John Cunningham Bowler + * + * This code is released under the libpng license. +@@ -34,6 +34,16 @@ + + # include + #endif + ++#ifndef FE_DIVBYZERO ++# define FE_DIVBYZERO 0 ++#endif ++#ifndef FE_INVALID ++# define FE_INVALID 0 ++#endif ++#ifndef FE_OVERFLOW ++# define FE_OVERFLOW 0 ++#endif ++ + /* Define the following to use this test against your installed libpng, rather + * than the one being built here: + */ +@@ -64,7 +74,7 @@ + + (defined(PNG_FIXED_POINT_SUPPORTED) || defined(PNG_FLOATING_POINT_SUPPORTED)) + + #if PNG_LIBPNG_VER < 10500 +-/* This deliberately lacks the PNG_CONST. */ ++/* This deliberately lacks the const. */ + typedef png_byte *png_const_bytep; + + /* This is copied from 1.5.1 png.h: */ +@@ -147,6 +157,31 @@ + + &(ps)->exception_context + #define context(ps,fault) anon_context(ps); png_store *fault + ++/* This macro returns the number of elements in an array as an (unsigned int), ++ * it is necessary to avoid the inability of certain versions of GCC to use ++ * the value of a compile-time constant when performing range checks. It must ++ * be passed an array name. ++ */ ++#define ARRAY_SIZE(a) ((unsigned int)((sizeof (a))/(sizeof (a)[0]))) ++ ++/* GCC BUG 66447 (https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66447) requires ++ * some broken GCC versions to be fixed up to avoid invalid whining about auto ++ * variables that are *not* changed within the scope of a setjmp being changed. ++ * ++ * Feel free to extend the list of broken versions. ++ */ ++#define is_gnu(major,minor)\ ++ (defined __GNUC__) && __GNUC__ == (major) && __GNUC_MINOR__ == (minor) ++#define is_gnu_patch(major,minor,patch)\ ++ is_gnu(major,minor) && __GNUC_PATCHLEVEL__ == 0 ++/* For the moment just do it always; all versions of GCC seem to be broken: */ ++#ifdef __GNUC__ ++ const void * volatile make_volatile_for_gnu; ++# define gnu_volatile(x) make_volatile_for_gnu = &x; ++#else /* !GNUC broken versions */ ++# define gnu_volatile(x) ++#endif /* !GNUC broken versions */ ++ + /******************************* UTILITIES ************************************/ + /* Error handling is particularly problematic in production code - error + * handlers often themselves have bugs which lead to programs that detect +@@ -155,7 +190,7 @@ + + * warning messages into buffers that are too small. + */ + static size_t safecat(char *buffer, size_t bufsize, size_t pos, +- PNG_CONST char *cat) ++ const char *cat) + { + while (pos < bufsize && cat != NULL && *cat != 0) + buffer[pos++] = *cat++; +@@ -184,16 +219,16 @@ + + } + #endif + +-static PNG_CONST char invalid[] = ""invalid""; +-static PNG_CONST char sep[] = "": ""; ++static const char invalid[] = ""invalid""; ++static const char sep[] = "": ""; + +-static PNG_CONST char *colour_types[8] = ++static const char *colour_types[8] = + { + ""grayscale"", invalid, ""truecolour"", ""indexed-colour"", + ""grayscale with alpha"", invalid, ""truecolour with alpha"", invalid + }; + +-#ifdef PNG_READ_SUPPORTED ++#ifdef PNG_READ_TRANSFORMS_SUPPORTED + /* Convert a double precision value to fixed point. */ + static png_fixed_point + fix(double d) +@@ -241,7 +276,7 @@ + + make_random_bytes(seed, bytes, 4); + } + +-#ifdef PNG_READ_SUPPORTED ++#if defined PNG_READ_SUPPORTED || defined PNG_WRITE_tRNS_SUPPORTED + static void + randomize(void *pv, size_t size) + { +@@ -250,7 +285,9 @@ + + } + + #define RANDOMIZE(this) randomize(&(this), sizeof (this)) ++#endif /* READ || WRITE_tRNS */ + ++#ifdef PNG_READ_TRANSFORMS_SUPPORTED + static unsigned int + random_mod(unsigned int max) + { +@@ -261,7 +298,8 @@ + + return x % max; /* 0 .. max-1 */ + } + +-#ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED ++#if (defined PNG_READ_RGB_TO_GRAY_SUPPORTED) ||\ ++ (defined PNG_READ_FILLER_SUPPORTED) + static int + random_choice(void) + { +@@ -277,7 +315,8 @@ + + /* A numeric ID based on PNG file characteristics. The 'do_interlace' field + * simply records whether pngvalid did the interlace itself or whether it + * was done by libpng. Width and height must be less than 256. 'palette' is an +- * index of the palette to use for formats with a palette (0 otherwise.) ++ * index of the palette to use for formats with a palette otherwise a boolean ++ * indicating if a tRNS chunk was generated. + */ + #define FILEID(col, depth, palette, interlace, width, height, do_interlace) \ + ((png_uint_32)((col) + ((depth)<<3) + ((palette)<<8) + ((interlace)<<13) + \ +@@ -286,7 +325,7 @@ + + #define COL_FROM_ID(id) ((png_byte)((id)& 0x7U)) + #define DEPTH_FROM_ID(id) ((png_byte)(((id) >> 3) & 0x1fU)) + #define PALETTE_FROM_ID(id) (((id) >> 8) & 0x1f) +-#define INTERLACE_FROM_ID(id) ((int)(((id) >> 13) & 0x3)) ++#define INTERLACE_FROM_ID(id) ((png_byte)(((id) >> 13) & 0x3)) + #define DO_INTERLACE_FROM_ID(id) ((int)(((id)>>15) & 1)) + #define WIDTH_FROM_ID(id) (((id)>>16) & 0xff) + #define HEIGHT_FROM_ID(id) (((id)>>24) & 0xff) +@@ -298,12 +337,16 @@ + + png_uint_32 w, png_uint_32 h, int do_interlace) + { + pos = safecat(buffer, bufsize, pos, colour_types[colour_type]); +- if (npalette > 0) ++ if (colour_type == 3) /* must have a palette */ + { + pos = safecat(buffer, bufsize, pos, ""[""); + pos = safecatn(buffer, bufsize, pos, npalette); + pos = safecat(buffer, bufsize, pos, ""]""); + } ++ ++ else if (npalette != 0) ++ pos = safecat(buffer, bufsize, pos, ""+tRNS""); ++ + pos = safecat(buffer, bufsize, pos, "" ""); + pos = safecatn(buffer, bufsize, pos, bit_depth); + pos = safecat(buffer, bufsize, pos, "" bit""); +@@ -360,25 +403,32 @@ + + + static int + next_format(png_bytep colour_type, png_bytep bit_depth, +- unsigned int* palette_number, int no_low_depth_gray) ++ unsigned int* palette_number, int low_depth_gray, int tRNS) + { + if (*bit_depth == 0) + { + *colour_type = 0; +- if (no_low_depth_gray) +- *bit_depth = 8; +- else ++ if (low_depth_gray) + *bit_depth = 1; ++ else ++ *bit_depth = 8; + *palette_number = 0; + return 1; + } + +- if (*colour_type == 3) ++ if (*colour_type < 4/*no alpha channel*/) + { +- /* Add multiple palettes for colour type 3. */ +- if (++*palette_number < PALETTE_COUNT(*bit_depth)) ++ /* Add multiple palettes for colour type 3, one image with tRNS ++ * and one without for other non-alpha formats: ++ */ ++ unsigned int pn = ++*palette_number; ++ png_byte ct = *colour_type; ++ ++ if (((ct == 0/*GRAY*/ || ct/*RGB*/ == 2) && tRNS && pn < 2) || ++ (ct == 3/*PALETTE*/ && pn < PALETTE_COUNT(*bit_depth))) + return 1; + ++ /* No: next bit depth */ + *palette_number = 0; + } + +@@ -386,9 +436,9 @@ + + + /* Palette images are restricted to 8 bit depth */ + if (*bit_depth <= 8 +-# ifdef DO_16BIT ++#ifdef DO_16BIT + || (*colour_type != 3 && *bit_depth <= 16) +-# endif ++#endif + ) + return 1; + +@@ -423,7 +473,7 @@ + + #ifdef PNG_READ_TRANSFORMS_SUPPORTED + static unsigned int + sample(png_const_bytep row, png_byte colour_type, png_byte bit_depth, +- png_uint_32 x, unsigned int sample_index) ++ png_uint_32 x, unsigned int sample_index, int swap16, int littleendian) + { + png_uint_32 bit_index, result; + +@@ -452,11 +502,23 @@ + + return result; + + else if (bit_depth > 8) +- return (result << 8) + *++row; ++ { ++ if (swap16) ++ return (*++row << 8) + result; ++ else ++ return (result << 8) + *++row; ++ } + +- /* Less than 8 bits per sample. */ ++ /* Less than 8 bits per sample. By default PNG has the big end of ++ * the egg on the left of the screen, but if littleendian is set ++ * then the big end is on the right. ++ */ + bit_index &= 7; +- return (result >> (8-bit_index-bit_depth)) & ((1U<> bit_index) & ((1U<> 3] & ~destMask; + unsigned int sourceByte = fromBuffer[fromIndex >> 3]; + + /* Don't rely on << or >> supporting '0' here, just in case: */ + fromIndex &= 7; +- if (fromIndex > 0) sourceByte <<= fromIndex; +- if ((toIndex & 7) > 0) sourceByte >>= toIndex & 7; ++ if (littleendian) ++ { ++ if (fromIndex > 0) sourceByte >>= fromIndex; ++ if ((toIndex & 7) > 0) sourceByte <<= toIndex & 7; ++ } ++ ++ else ++ { ++ if (fromIndex > 0) sourceByte <<= fromIndex; ++ if ((toIndex & 7) > 0) sourceByte >>= toIndex & 7; ++ } + + toBuffer[toIndex >> 3] = (png_byte)(destByte | (sourceByte & destMask)); + } +@@ -501,7 +574,8 @@ + + * bytes at the end. + */ + static void +-row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth) ++row_copy(png_bytep toBuffer, png_const_bytep fromBuffer, unsigned int bitWidth, ++ int littleendian) + { + memcpy(toBuffer, fromBuffer, bitWidth >> 3); + +@@ -511,10 +585,10 @@ + + + toBuffer += bitWidth >> 3; + fromBuffer += bitWidth >> 3; +- /* The remaining bits are in the top of the byte, the mask is the bits to +- * retain. +- */ +- mask = 0xff >> (bitWidth & 7); ++ if (littleendian) ++ mask = 0xff << (bitWidth & 7); ++ else ++ mask = 0xff >> (bitWidth & 7); + *toBuffer = (png_byte)((*toBuffer & mask) | (*fromBuffer & ~mask)); + } + } +@@ -678,7 +752,7 @@ + + make_four_random_bytes(store_seed, mark); + } + +-#ifdef PNG_READ_SUPPORTED ++#ifdef PNG_READ_TRANSFORMS_SUPPORTED + /* Use this for random 32 bit values; this function makes sure the result is + * non-zero. + */ +@@ -686,7 +760,7 @@ + + random_32(void) + { + +- for(;;) ++ for (;;) + { + png_byte mark[4]; + png_uint_32 result; +@@ -836,7 +910,7 @@ + + /* Generate an error message (in the given buffer) */ + static size_t + store_message(png_store *ps, png_const_structp pp, char *buffer, size_t bufsize, +- size_t pos, PNG_CONST char *msg) ++ size_t pos, const char *msg) + { + if (pp != NULL && pp == ps->pread) + { +@@ -954,7 +1028,7 @@ + + */ + /* Return a single row from the correct image. */ + static png_bytep +-store_image_row(PNG_CONST png_store* ps, png_const_structp pp, int nImage, ++store_image_row(const png_store* ps, png_const_structp pp, int nImage, + png_uint_32 y) + { + png_size_t coffset = (nImage * ps->image_h + y) * (ps->cb_row + 5) + 2; +@@ -1058,7 +1132,7 @@ + + + #ifdef PNG_READ_SUPPORTED + static void +-store_image_check(PNG_CONST png_store* ps, png_const_structp pp, int iImage) ++store_image_check(const png_store* ps, png_const_structp pp, int iImage) + { + png_const_bytep image = ps->image; + +@@ -1275,7 +1349,10 @@ + + * operation.) + */ + if (ps->current == NULL) ++ { + store_log(ps, ps->pread, ""no current stream for palette"", 1); ++ return NULL; ++ } + + /* The result may be null if there is no palette. */ + *npalette = ps->current->npalette; +@@ -1305,7 +1382,7 @@ + + * all the memory. + */ + static void +-store_pool_error(png_store *ps, png_const_structp pp, PNG_CONST char *msg) ++store_pool_error(png_store *ps, png_const_structp pp, const char *msg) + { + if (pp != NULL) + png_error(pp, msg); +@@ -1369,7 +1446,7 @@ + + next->next = NULL; + + fprintf(stderr, ""\t%lu bytes @ %p\n"", +- (unsigned long)next->size, (PNG_CONST void*)(next+1)); ++ (unsigned long)next->size, (const void*)(next+1)); + /* The NULL means this will always return, even if the memory is + * corrupted. + */ +@@ -1524,8 +1601,7 @@ + + * returned libpng structures as destroyed by store_write_reset above. + */ + static png_structp +-set_store_for_write(png_store *ps, png_infopp ppi, +- PNG_CONST char * volatile name) ++set_store_for_write(png_store *ps, png_infopp ppi, const char *name) + { + anon_context(ps); + +@@ -1645,7 +1721,7 @@ + + */ + static png_structp + set_store_for_read(png_store *ps, png_infopp ppi, png_uint_32 id, +- PNG_CONST char *name) ++ const char *name) + { + /* Set the name for png_error */ + safecat(ps->test, sizeof ps->test, 0, name); +@@ -1752,6 +1828,7 @@ + + } color_encoding; + + #ifdef PNG_READ_SUPPORTED ++#if defined PNG_READ_TRANSFORMS_SUPPORTED && defined PNG_READ_cHRM_SUPPORTED + static double + chromaticity_x(CIE_color c) + { +@@ -1765,7 +1842,7 @@ + + } + + static CIE_color +-white_point(PNG_CONST color_encoding *encoding) ++white_point(const color_encoding *encoding) + { + CIE_color white; + +@@ -1775,12 +1852,13 @@ + + + return white; + } ++#endif /* READ_TRANSFORMS && READ_cHRM */ + + #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED + static void + normalize_color_encoding(color_encoding *encoding) + { +- PNG_CONST double whiteY = encoding->red.Y + encoding->green.Y + ++ const double whiteY = encoding->red.Y + encoding->green.Y + + encoding->blue.Y; + + if (whiteY != 1) +@@ -1798,9 +1876,10 @@ + + } + #endif + ++#ifdef PNG_READ_TRANSFORMS_SUPPORTED + static size_t + safecat_color_encoding(char *buffer, size_t bufsize, size_t pos, +- PNG_CONST color_encoding *e, double encoding_gamma) ++ const color_encoding *e, double encoding_gamma) + { + if (e != 0) + { +@@ -1837,6 +1916,7 @@ + + + return pos; + } ++#endif /* READ_TRANSFORMS */ + #endif /* PNG_READ_SUPPORTED */ + + typedef struct png_modifier +@@ -1861,9 +1941,9 @@ + + unsigned int ngammas; + unsigned int ngamma_tests; /* Number of gamma tests to run*/ + double current_gamma; /* 0 if not set */ +- PNG_CONST color_encoding *encodings; ++ const color_encoding *encodings; + unsigned int nencodings; +- PNG_CONST color_encoding *current_encoding; /* If an encoding has been set */ ++ const color_encoding *current_encoding; /* If an encoding has been set */ + unsigned int encoding_counter; /* For iteration */ + int encoding_ignored; /* Something overwrote it */ + +@@ -1874,7 +1954,7 @@ + + unsigned int repeat :1; /* Repeat this transform test. */ + unsigned int test_uses_encoding :1; + +- /* Lowest sbit to test (libpng fails for sbit < 8) */ ++ /* Lowest sbit to test (pre-1.7 libpng fails for sbit < 8) */ + png_byte sbitlow; + + /* Error control - these are the limits on errors accepted by the gamma tests +@@ -1929,6 +2009,7 @@ + + + /* Run tests on reading with a combination of transforms, */ + unsigned int test_transform :1; ++ unsigned int test_tRNS :1; /* Includes tRNS images */ + + /* When to use the use_input_precision option, this controls the gamma + * validation code checks. If set any value that is within the transformed +@@ -1960,6 +2041,16 @@ + + unsigned int test_gamma_expand16 :1; + unsigned int test_exhaustive :1; + ++ /* Whether or not to run the low-bit-depth grayscale tests. This fails on ++ * gamma images in some cases because of gross inaccuracies in the grayscale ++ * gamma handling for low bit depth. ++ */ ++ unsigned int test_lbg :1; ++ unsigned int test_lbg_gamma_threshold :1; ++ unsigned int test_lbg_gamma_transform :1; ++ unsigned int test_lbg_gamma_sbit :1; ++ unsigned int test_lbg_gamma_composition :1; ++ + unsigned int log :1; /* Log max error */ + + /* Buffer information, the buffer size limits the size of the chunks that can +@@ -2012,6 +2103,11 @@ + + pm->test_standard = 0; + pm->test_size = 0; + pm->test_transform = 0; ++# ifdef PNG_WRITE_tRNS_SUPPORTED ++ pm->test_tRNS = 1; ++# else ++ pm->test_tRNS = 0; ++# endif + pm->use_input_precision = 0; + pm->use_input_precision_sbit = 0; + pm->use_input_precision_16to8 = 0; +@@ -2024,6 +2120,11 @@ + + pm->test_gamma_background = 0; + pm->test_gamma_alpha_mode = 0; + pm->test_gamma_expand16 = 0; ++ pm->test_lbg = 1; ++ pm->test_lbg_gamma_threshold = 1; ++ pm->test_lbg_gamma_transform = 1; ++ pm->test_lbg_gamma_sbit = 1; ++ pm->test_lbg_gamma_composition = 1; + pm->test_exhaustive = 0; + pm->log = 0; + +@@ -2057,7 +2158,7 @@ + + * rounding and 'do_round' should be 1, if it is 0 the digitized value will + * be truncated. + */ +- PNG_CONST unsigned int digitization_factor = (1U << depth) -1; ++ const unsigned int digitization_factor = (1U << depth) -1; + + /* Limiting the range is done as a convenience to the caller - it's easier to + * do it once here than every time at the call site. +@@ -2076,7 +2177,7 @@ + + #endif /* RGB_TO_GRAY */ + + #ifdef PNG_READ_GAMMA_SUPPORTED +-static double abserr(PNG_CONST png_modifier *pm, int in_depth, int out_depth) ++static double abserr(const png_modifier *pm, int in_depth, int out_depth) + { + /* Absolute error permitted in linear values - affected by the bit depth of + * the calculations. +@@ -2088,7 +2189,7 @@ + + return pm->maxabs8; + } + +-static double calcerr(PNG_CONST png_modifier *pm, int in_depth, int out_depth) ++static double calcerr(const png_modifier *pm, int in_depth, int out_depth) + { + /* Error in the linear composition arithmetic - only relevant when + * composition actually happens (0 < alpha < 1). +@@ -2101,7 +2202,7 @@ + + return pm->maxcalc8; + } + +-static double pcerr(PNG_CONST png_modifier *pm, int in_depth, int out_depth) ++static double pcerr(const png_modifier *pm, int in_depth, int out_depth) + { + /* Percentage error permitted in the linear values. Note that the specified + * value is a percentage but this routine returns a simple number. +@@ -2124,7 +2225,7 @@ + + * The specified parameter does *not* include the base .5 digitization error but + * it is added here. + */ +-static double outerr(PNG_CONST png_modifier *pm, int in_depth, int out_depth) ++static double outerr(const png_modifier *pm, int in_depth, int out_depth) + { + /* There is a serious error in the 2 and 4 bit grayscale transform because + * the gamma table value (8 bits) is simply shifted, not rounded, so the +@@ -2156,7 +2257,7 @@ + + * rather than raising a warning. This is useful for debugging to track down + * exactly what set of parameters cause high error values. + */ +-static double outlog(PNG_CONST png_modifier *pm, int in_depth, int out_depth) ++static double outlog(const png_modifier *pm, int in_depth, int out_depth) + { + /* The command line parameters are either 8 bit (0..255) or 16 bit (0..65535) + * and so must be adjusted for low bit depth grayscale: +@@ -2194,7 +2295,7 @@ + + * but in the 8 bit calculation case it's actually quantization to a multiple of + * 257! + */ +-static int output_quantization_factor(PNG_CONST png_modifier *pm, int in_depth, ++static int output_quantization_factor(const png_modifier *pm, int in_depth, + int out_depth) + { + if (out_depth == 16 && in_depth != 16 && +@@ -2258,7 +2359,7 @@ + + + #ifdef PNG_READ_RGB_TO_GRAY_SUPPORTED + static void +-modifier_current_encoding(PNG_CONST png_modifier *pm, color_encoding *ce) ++modifier_current_encoding(const png_modifier *pm, color_encoding *ce) + { + if (pm->current_encoding != 0) + *ce = *pm->current_encoding; +@@ -2270,9 +2371,10 @@ + + } + #endif + ++#ifdef PNG_READ_TRANSFORMS_SUPPORTED + static size_t + safecat_current_encoding(char *buffer, size_t bufsize, size_t pos, +- PNG_CONST png_modifier *pm) ++ const png_modifier *pm) + { + pos = safecat_color_encoding(buffer, bufsize, pos, pm->current_encoding, + pm->current_gamma); +@@ -2282,6 +2384,7 @@ + + + return pos; + } ++#endif + + /* Iterate through the usefully testable color encodings. An encoding is one + * of: +@@ -2301,7 +2404,7 @@ + + * caller of modifier_reset must reset it at the start of each run of the test! + */ + static unsigned int +-modifier_total_encodings(PNG_CONST png_modifier *pm) ++modifier_total_encodings(const png_modifier *pm) + { + return 1 + /* (1) nothing */ + pm->ngammas + /* (2) gamma values to test */ +@@ -2417,14 +2520,14 @@ + + * assumption below that the first encoding in the list is the one for sRGB. + */ + static int +-modifier_color_encoding_is_sRGB(PNG_CONST png_modifier *pm) ++modifier_color_encoding_is_sRGB(const png_modifier *pm) + { + return pm->current_encoding != 0 && pm->current_encoding == pm->encodings && + pm->current_encoding->gamma == pm->current_gamma; + } + + static int +-modifier_color_encoding_is_set(PNG_CONST png_modifier *pm) ++modifier_color_encoding_is_set(const png_modifier *pm) + { + return pm->current_gamma != 0; + } +@@ -2743,7 +2846,7 @@ + + /* Set up a modifier. */ + static png_structp + set_modifier_for_read(png_modifier *pm, png_infopp ppi, png_uint_32 id, +- PNG_CONST char *name) ++ const char *name) + { + /* Do this first so that the modifier fields are cleared even if an error + * happens allocating the png_struct. No allocation is done here so no +@@ -2803,7 +2906,7 @@ + + typedef struct chrm_modification + { + png_modification this; +- PNG_CONST color_encoding *encoding; ++ const color_encoding *encoding; + png_fixed_point wx, wy, rx, ry, gx, gy, bx, by; + } chrm_modification; + +@@ -2827,7 +2930,7 @@ + + + static void + chrm_modification_init(chrm_modification *me, png_modifier *pm, +- PNG_CONST color_encoding *encoding) ++ const color_encoding *encoding) + { + CIE_color white = white_point(encoding); + +@@ -3162,6 +3265,45 @@ + + } + } + ++#ifdef PNG_WRITE_tRNS_SUPPORTED ++static void ++set_random_tRNS(png_structp pp, png_infop pi, const png_byte colour_type, ++ const int bit_depth) ++{ ++ /* To make this useful the tRNS color needs to match at least one pixel. ++ * Random values are fine for gray, including the 16-bit case where we know ++ * that the test image contains all the gray values. For RGB we need more ++ * method as only 65536 different RGB values are generated. ++ */ ++ png_color_16 tRNS; ++ const png_uint_16 mask = (png_uint_16)((1U << bit_depth)-1); ++ ++ RANDOMIZE(tRNS); ++ ++ if (colour_type & 2/*RGB*/) ++ { ++ if (bit_depth == 8) ++ { ++ tRNS.blue = tRNS.red ^ tRNS.green; ++ tRNS.red &= mask; ++ tRNS.green &= mask; ++ tRNS.blue &= mask; ++ } ++ ++ else /* bit_depth == 16 */ ++ { ++ tRNS.green = (png_uint_16)(tRNS.red * 257); ++ tRNS.blue = (png_uint_16)(tRNS.green * 17); ++ } ++ } ++ ++ else ++ tRNS.gray &= mask; ++ ++ png_set_tRNS(pp, pi, NULL, 0, &tRNS); ++} ++#endif ++ + /* The number of passes is related to the interlace type. There was no libpng + * API to determine this prior to 1.5, so we need an inquiry function: + */ +@@ -3411,13 +3553,17 @@ + + #ifdef PNG_WRITE_INTERLACING_SUPPORTED + # define INTERLACE_LAST PNG_INTERLACE_LAST + # define check_interlace_type(type) ((void)(type)) +-#else +-# define INTERLACE_LAST (PNG_INTERLACE_NONE+1) +-# define png_set_interlace_handling(a) (1) +- ++# define set_write_interlace_handling(pp,type) png_set_interlace_handling(pp) ++# define do_own_interlace 0 ++#elif PNG_LIBPNG_VER < 10700 ++# define set_write_interlace_handling(pp,type) (1) + static void +-check_interlace_type(int PNG_CONST interlace_type) ++check_interlace_type(int const interlace_type) + { ++ /* Prior to 1.7.0 libpng does not support the write of an interlaced image ++ * unless PNG_WRITE_INTERLACING_SUPPORTED, even with do_interlace so the ++ * code here does the pixel interlace itself, so: ++ */ + if (interlace_type != PNG_INTERLACE_NONE) + { + /* This is an internal error - --interlace tests should be skipped, not +@@ -3427,17 +3573,85 @@ + + exit(99); + } + } +-#endif ++# define INTERLACE_LAST (PNG_INTERLACE_NONE+1) ++# define do_own_interlace 0 ++#else /* libpng 1.7+ */ ++# define set_write_interlace_handling(pp,type)\ ++ npasses_from_interlace_type(pp,type) ++# define check_interlace_type(type) ((void)(type)) ++# define INTERLACE_LAST PNG_INTERLACE_LAST ++# define do_own_interlace 1 ++#endif /* WRITE_INTERLACING tests */ + +-/* Make a standardized image given a an image colour type, bit depth and ++#define CAN_WRITE_INTERLACE\ ++ PNG_LIBPNG_VER >= 10700 || defined PNG_WRITE_INTERLACING_SUPPORTED ++ ++/* Do the same thing for read interlacing; this controls whether read tests do ++ * their own de-interlace or use libpng. ++ */ ++#ifdef PNG_READ_INTERLACING_SUPPORTED ++# define do_read_interlace 0 ++#else /* no libpng read interlace support */ ++# define do_read_interlace 1 ++#endif ++/* The following two routines use the PNG interlace support macros from ++ * png.h to interlace or deinterlace rows. ++ */ ++static void ++interlace_row(png_bytep buffer, png_const_bytep imageRow, ++ unsigned int pixel_size, png_uint_32 w, int pass, int littleendian) ++{ ++ png_uint_32 xin, xout, xstep; ++ ++ /* Note that this can, trivially, be optimized to a memcpy on pass 7, the ++ * code is presented this way to make it easier to understand. In practice ++ * consult the code in the libpng source to see other ways of doing this. ++ * ++ * It is OK for buffer and imageRow to be identical, because 'xin' moves ++ * faster than 'xout' and we copy up. ++ */ ++ xin = PNG_PASS_START_COL(pass); ++ xstep = 1U< 0) ++ interlace_row(buffer, buffer, ++ bit_size(pp, colour_type, bit_depth), w, pass, ++ 0/*data always bigendian*/); ++ else ++ continue; ++ } ++# endif /* do_own_interlace */ ++ + png_write_row(pp, buffer); + } + } +@@ -3568,19 +3813,20 @@ + + } + + static void +-make_transform_images(png_store *ps) ++make_transform_images(png_modifier *pm) + { + png_byte colour_type = 0; + png_byte bit_depth = 0; + unsigned int palette_number = 0; + + /* This is in case of errors. */ +- safecat(ps->test, sizeof ps->test, 0, ""make standard images""); ++ safecat(pm->this.test, sizeof pm->this.test, 0, ""make standard images""); + + /* Use next_format to enumerate all the combinations we test, including +- * generating multiple low bit depth palette images. ++ * generating multiple low bit depth palette images. Non-A images (palette ++ * and direct) are created with and without tRNS chunks. + */ +- while (next_format(&colour_type, &bit_depth, &palette_number, 0)) ++ while (next_format(&colour_type, &bit_depth, &palette_number, 1, 1)) + { + int interlace_type; + +@@ -3590,59 +3836,13 @@ + + char name[FILE_NAME_SIZE]; + + standard_name(name, sizeof name, 0, colour_type, bit_depth, +- palette_number, interlace_type, 0, 0, 0); +- make_transform_image(ps, colour_type, bit_depth, palette_number, ++ palette_number, interlace_type, 0, 0, do_own_interlace); ++ make_transform_image(&pm->this, colour_type, bit_depth, palette_number, + interlace_type, name); + } + } + } + +-/* The following two routines use the PNG interlace support macros from +- * png.h to interlace or deinterlace rows. +- */ +-static void +-interlace_row(png_bytep buffer, png_const_bytep imageRow, +- unsigned int pixel_size, png_uint_32 w, int pass) +-{ +- png_uint_32 xin, xout, xstep; +- +- /* Note that this can, trivially, be optimized to a memcpy on pass 7, the +- * code is presented this way to make it easier to understand. In practice +- * consult the code in the libpng source to see other ways of doing this. +- */ +- xin = PNG_PASS_START_COL(pass); +- xstep = 1U<expect_error = !error_test[test].warning; + ps->expect_warning = error_test[test].warning; +@@ -4029,7 +4238,8 @@ + + } + + Catch (fault) +- ps = fault; /* expected exit, make sure ps is not clobbered */ ++ { /* expected exit */ ++ } + #undef exception__prev + #undef exception__env + +@@ -4046,8 +4256,7 @@ + + + else + { +- png_uint_32 h = transform_height(pp, colour_type, bit_depth); +- int npasses = png_set_interlace_handling(pp); ++ int npasses = set_write_interlace_handling(pp, interlace_type); + int pass; + + if (npasses != npasses_from_interlace_type(pp, interlace_type)) +@@ -4062,6 +4271,29 @@ + + png_byte buffer[TRANSFORM_ROWMAX]; + + transform_row(pp, buffer, colour_type, bit_depth, y); ++ ++# if do_own_interlace ++ /* If do_own_interlace *and* the image is interlaced we need a ++ * reduced interlace row; this may be reduced to empty. ++ */ ++ if (interlace_type == PNG_INTERLACE_ADAM7) ++ { ++ /* The row must not be written if it doesn't exist, notice ++ * that there are two conditions here, either the row isn't ++ * ever in the pass or the row would be but isn't wide ++ * enough to contribute any pixels. In fact the wPass test ++ * can be used to skip the whole y loop in this case. ++ */ ++ if (PNG_ROW_IN_INTERLACE_PASS(y, pass) && ++ PNG_PASS_COLS(w, pass) > 0) ++ interlace_row(buffer, buffer, ++ bit_size(pp, colour_type, bit_depth), w, pass, ++ 0/*data always bigendian*/); ++ else ++ continue; ++ } ++# endif /* do_own_interlace */ ++ + png_write_row(pp, buffer); + } + } +@@ -4080,8 +4312,8 @@ + + } + + static int +-make_errors(png_modifier* PNG_CONST pm, png_byte PNG_CONST colour_type, +- int bdlo, int PNG_CONST bdhi) ++make_errors(png_modifier* const pm, png_byte const colour_type, ++ int bdlo, int const bdhi) + { + for (; bdlo <= bdhi; ++bdlo) + { +@@ -4094,9 +4326,9 @@ + + char name[FILE_NAME_SIZE]; + + standard_name(name, sizeof name, 0, colour_type, 1<this, colour_type, DEPTH(bdlo), interlace_type, + test, name); +@@ -4141,7 +4373,7 @@ + + * then the warning messages the library outputs will probably be garbage. + */ + static void +-perform_formatting_test(png_store *volatile ps) ++perform_formatting_test(png_store *ps) + { + #ifdef PNG_TIME_RFC1123_SUPPORTED + /* The handle into the formatting code is the RFC1123 support; this test does +@@ -4246,7 +4478,8 @@ + + png_byte green_sBIT; + png_byte blue_sBIT; + png_byte alpha_sBIT; +- int interlace_type; ++ png_byte interlace_type; ++ png_byte filler; /* Output has a filler */ + png_uint_32 id; /* Calculated file ID */ + png_uint_32 w; /* Width of image */ + png_uint_32 h; /* Height of image */ +@@ -4255,7 +4488,9 @@ + + png_uint_32 bit_width; /* Width of output row in bits */ + size_t cbRow; /* Bytes in a row of the output image */ + int do_interlace; /* Do interlacing internally */ ++ int littleendian; /* App (row) data is little endian */ + int is_transparent; /* Transparency information was present. */ ++ int has_tRNS; /* color type GRAY or RGB with a tRNS chunk. */ + int speed; /* Doing a speed test */ + int use_update_info;/* Call update_info, not start_image */ + struct +@@ -4296,6 +4531,7 @@ + + dp->bit_width = 0; + dp->cbRow = 0; + dp->do_interlace = do_interlace; ++ dp->littleendian = 0; + dp->is_transparent = 0; + dp->speed = ps->speed; + dp->use_update_info = use_update_info; +@@ -4588,14 +4824,14 @@ + + case 0: + dp->transparent.red = dp->transparent.green = dp->transparent.blue = + trans_color->gray; +- dp->is_transparent = 1; ++ dp->has_tRNS = 1; + break; + + case 2: + dp->transparent.red = trans_color->red; + dp->transparent.green = trans_color->green; + dp->transparent.blue = trans_color->blue; +- dp->is_transparent = 1; ++ dp->has_tRNS = 1; + break; + + case 3: +@@ -4616,8 +4852,19 @@ + + * turning on interlace handling (if do_interlace is not set.) + */ + dp->npasses = npasses_from_interlace_type(pp, dp->interlace_type); +- if (!dp->do_interlace && dp->npasses != png_set_interlace_handling(pp)) +- png_error(pp, ""validate: file changed interlace type""); ++ if (!dp->do_interlace) ++ { ++# ifdef PNG_READ_INTERLACING_SUPPORTED ++ if (dp->npasses != png_set_interlace_handling(pp)) ++ png_error(pp, ""validate: file changed interlace type""); ++# else /* !READ_INTERLACING */ ++ /* This should never happen: the relevant tests (!do_interlace) should ++ * not be run. ++ */ ++ if (dp->npasses > 1) ++ png_error(pp, ""validate: no libpng interlace support""); ++# endif /* !READ_INTERLACING */ ++ } + + /* Caller calls png_read_update_info or png_start_read_image now, then calls + * part2. +@@ -4633,8 +4880,16 @@ + + png_const_infop pi, int nImages) + { + /* Record cbRow now that it can be found. */ +- dp->pixel_size = bit_size(pp, png_get_color_type(pp, pi), +- png_get_bit_depth(pp, pi)); ++ { ++ png_byte ct = png_get_color_type(pp, pi); ++ png_byte bd = png_get_bit_depth(pp, pi); ++ ++ if (bd >= 8 && (ct == PNG_COLOR_TYPE_RGB || ct == PNG_COLOR_TYPE_GRAY) && ++ dp->filler) ++ ct |= 4; /* handle filler as faked alpha channel */ ++ ++ dp->pixel_size = bit_size(pp, ct, bd); ++ } + dp->bit_width = png_get_image_width(pp, pi) * dp->pixel_size; + dp->cbRow = png_get_rowbytes(pp, pi); + +@@ -4691,7 +4946,7 @@ + + progressive_row(png_structp ppIn, png_bytep new_row, png_uint_32 y, int pass) + { + png_const_structp pp = ppIn; +- PNG_CONST standard_display *dp = voidcast(standard_display*, ++ const standard_display *dp = voidcast(standard_display*, + png_get_progressive_ptr(pp)); + + /* When handling interlacing some rows will be absent in each pass, the +@@ -4715,7 +4970,7 @@ + + + if (pass != png_get_current_pass_number(pp)) + png_error(pp, ""png_get_current_pass_number is broken""); +-#endif ++#endif /* USER_TRANSFORM_INFO */ + + y = PNG_ROW_FROM_PASS_ROW(y, pass); + } +@@ -4726,38 +4981,39 @@ + + + row = store_image_row(dp->ps, pp, 0, y); + +-#ifdef PNG_READ_INTERLACING_SUPPORTED + /* Combine the new row into the old: */ ++#ifdef PNG_READ_INTERLACING_SUPPORTED + if (dp->do_interlace) ++#endif /* READ_INTERLACING */ + { + if (dp->interlace_type == PNG_INTERLACE_ADAM7) +- deinterlace_row(row, new_row, dp->pixel_size, dp->w, pass); ++ deinterlace_row(row, new_row, dp->pixel_size, dp->w, pass, ++ dp->littleendian); + else +- row_copy(row, new_row, dp->pixel_size * dp->w); ++ row_copy(row, new_row, dp->pixel_size * dp->w, dp->littleendian); + } ++#ifdef PNG_READ_INTERLACING_SUPPORTED + else + png_progressive_combine_row(pp, row, new_row); + #endif /* PNG_READ_INTERLACING_SUPPORTED */ + } + +-#ifdef PNG_READ_INTERLACING_SUPPORTED + else if (dp->interlace_type == PNG_INTERLACE_ADAM7 && + PNG_ROW_IN_INTERLACE_PASS(y, pass) && + PNG_PASS_COLS(dp->w, pass) > 0) + png_error(pp, ""missing row in progressive de-interlacing""); +-#endif /* PNG_READ_INTERLACING_SUPPORTED */ + } + + static void + sequential_row(standard_display *dp, png_structp pp, png_infop pi, +- PNG_CONST int iImage, PNG_CONST int iDisplay) ++ const int iImage, const int iDisplay) + { +- PNG_CONST int npasses = dp->npasses; +- PNG_CONST int do_interlace = dp->do_interlace && ++ const int npasses = dp->npasses; ++ const int do_interlace = dp->do_interlace && + dp->interlace_type == PNG_INTERLACE_ADAM7; +- PNG_CONST png_uint_32 height = standard_height(pp, dp->id); +- PNG_CONST png_uint_32 width = standard_width(pp, dp->id); +- PNG_CONST png_store* ps = dp->ps; ++ const png_uint_32 height = standard_height(pp, dp->id); ++ const png_uint_32 width = standard_width(pp, dp->id); ++ const png_store* ps = dp->ps; + int pass; + + for (pass=0; pass= 0) + deinterlace_row(store_image_row(ps, pp, iImage, y), row, +- dp->pixel_size, dp->w, pass); ++ dp->pixel_size, dp->w, pass, dp->littleendian); + + if (iDisplay >= 0) + deinterlace_row(store_image_row(ps, pp, iDisplay, y), display, +- dp->pixel_size, dp->w, pass); ++ dp->pixel_size, dp->w, pass, dp->littleendian); + } + } + else +@@ -4943,14 +5199,6 @@ + + * In earlier passes 'row' will be partially filled in, with only the pixels + * that have been read so far, but 'display' will have those pixels + * replicated to fill the unread pixels while reading an interlaced image. +-#if PNG_LIBPNG_VER < 10506 +- * The side effect inside the libpng sequential reader is that the 'row' +- * array retains the correct values for unwritten pixels within the row +- * bytes, while the 'display' array gets bits off the end of the image (in +- * the last byte) trashed. Unfortunately in the progressive reader the +- * row bytes are always trashed, so we always do a pixel_cmp here even though +- * a memcmp of all cbRow bytes will succeed for the sequential reader. +-#endif + */ + if (iImage >= 0 && + (where = pixel_cmp(std, store_image_row(dp->ps, pp, iImage, y), +@@ -4963,19 +5211,12 @@ + + png_error(pp, msg); + } + +-#if PNG_LIBPNG_VER < 10506 +- /* In this case use pixel_cmp because we need to compare a partial +- * byte at the end of the row if the row is not an exact multiple +- * of 8 bits wide. (This is fixed in libpng-1.5.6 and pixel_cmp is +- * changed to match!) +- */ +-#endif + if (iDisplay >= 0 && + (where = pixel_cmp(std, store_image_row(dp->ps, pp, iDisplay, y), + dp->bit_width)) != 0) + { + char msg[64]; +- sprintf(msg, ""display row[%lu][%d] changed from %.2x to %.2x"", ++ sprintf(msg, ""display row[%lu][%d] changed from %.2x to %.2x"", + (unsigned long)y, where-1, std[where-1], + store_image_row(dp->ps, pp, iDisplay, y)[where-1]); + png_error(pp, msg); +@@ -5020,7 +5261,7 @@ + + + /* A single test run checking the standard image to ensure it is not damaged. */ + static void +-standard_test(png_store* PNG_CONST psIn, png_uint_32 PNG_CONST id, ++standard_test(png_store* const psIn, png_uint_32 const id, + int do_interlace, int use_update_info) + { + standard_display d; +@@ -5108,8 +5349,8 @@ + + } + + static int +-test_standard(png_modifier* PNG_CONST pm, png_byte PNG_CONST colour_type, +- int bdlo, int PNG_CONST bdhi) ++test_standard(png_modifier* const pm, png_byte const colour_type, ++ int bdlo, int const bdhi) + { + for (; bdlo <= bdhi; ++bdlo) + { +@@ -5119,7 +5360,7 @@ + + interlace_type < INTERLACE_LAST; ++interlace_type) + { + standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, +- interlace_type, 0, 0, 0), 0/*do_interlace*/, pm->use_update_info); ++ interlace_type, 0, 0, 0), do_read_interlace, pm->use_update_info); + + if (fail(pm)) + return 0; +@@ -5154,8 +5395,8 @@ + + + /********************************** SIZE TESTS ********************************/ + static int +-test_size(png_modifier* PNG_CONST pm, png_byte PNG_CONST colour_type, +- int bdlo, int PNG_CONST bdhi) ++test_size(png_modifier* const pm, png_byte const colour_type, ++ int bdlo, int const bdhi) + { + /* Run the tests on each combination. + * +@@ -5164,8 +5405,10 @@ + + * width and height. This is a waste of time in practice, hence the + * hinc and winc stuff: + */ +- static PNG_CONST png_byte hinc[] = {1, 3, 11, 1, 5}; +- static PNG_CONST png_byte winc[] = {1, 9, 5, 7, 1}; ++ static const png_byte hinc[] = {1, 3, 11, 1, 5}; ++ static const png_byte winc[] = {1, 9, 5, 7, 1}; ++ const int save_bdlo = bdlo; ++ + for (; bdlo <= bdhi; ++bdlo) + { + png_uint_32 h, w; +@@ -5191,22 +5434,6 @@ + + if (fail(pm)) + return 0; + +-# ifdef PNG_WRITE_INTERLACING_SUPPORTED +- standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, +- PNG_INTERLACE_ADAM7, w, h, 0), 0/*do_interlace*/, +- pm->use_update_info); +- +- if (fail(pm)) +- return 0; +- +- standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, +- PNG_INTERLACE_ADAM7, w, h, 1), 0/*do_interlace*/, +- pm->use_update_info); +- +- if (fail(pm)) +- return 0; +-# endif +- + /* Now validate the interlaced read side - do_interlace true, + * in the progressive case this does actually make a difference + * to the code used in the non-interlaced case too. +@@ -5218,7 +5445,45 @@ + + if (fail(pm)) + return 0; + ++# if CAN_WRITE_INTERLACE ++ /* Validate the pngvalid code itself: */ ++ standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, ++ PNG_INTERLACE_ADAM7, w, h, 1), 1/*do_interlace*/, ++ pm->use_update_info); ++ ++ if (fail(pm)) ++ return 0; ++# endif ++ } ++ } ++ ++ /* Now do the tests of libpng interlace handling, after we have made sure ++ * that the pngvalid version works: ++ */ ++ for (bdlo = save_bdlo; bdlo <= bdhi; ++bdlo) ++ { ++ png_uint_32 h, w; ++ ++ for (h=1; h<=16; h+=hinc[bdlo]) for (w=1; w<=16; w+=winc[bdlo]) ++ { ++# ifdef PNG_READ_INTERLACING_SUPPORTED ++ /* Test with pngvalid generated interlaced images first; we have ++ * already verify these are ok (unless pngvalid has self-consistent ++ * read/write errors, which is unlikely), so this detects errors in the ++ * read side first: ++ */ ++# if CAN_WRITE_INTERLACE ++ standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, ++ PNG_INTERLACE_ADAM7, w, h, 1), 0/*do_interlace*/, ++ pm->use_update_info); ++ ++ if (fail(pm)) ++ return 0; ++# endif ++# endif /* READ_INTERLACING */ ++ + # ifdef PNG_WRITE_INTERLACING_SUPPORTED ++ /* Test the libpng write side against the pngvalid read side: */ + standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, + PNG_INTERLACE_ADAM7, w, h, 0), 1/*do_interlace*/, + pm->use_update_info); +@@ -5226,6 +5491,18 @@ + + if (fail(pm)) + return 0; + # endif ++ ++# ifdef PNG_READ_INTERLACING_SUPPORTED ++# ifdef PNG_WRITE_INTERLACING_SUPPORTED ++ /* Test both together: */ ++ standard_test(&pm->this, FILEID(colour_type, DEPTH(bdlo), 0/*palette*/, ++ PNG_INTERLACE_ADAM7, w, h, 0), 0/*do_interlace*/, ++ pm->use_update_info); ++ ++ if (fail(pm)) ++ return 0; ++# endif ++# endif /* READ_INTERLACING */ + } + } + +@@ -5274,10 +5551,17 @@ + + */ + unsigned int red, green, blue, alpha; /* For non-palette images. */ + unsigned int palette_index; /* For a palette image. */ +- png_byte colour_type; /* As in the spec. */ +- png_byte bit_depth; /* Defines bit size in row */ +- png_byte sample_depth; /* Scale of samples */ +- int have_tRNS; /* tRNS chunk may need processing */ ++ png_byte colour_type; /* As in the spec. */ ++ png_byte bit_depth; /* Defines bit size in row */ ++ png_byte sample_depth; /* Scale of samples */ ++ unsigned int have_tRNS :1; /* tRNS chunk may need processing */ ++ unsigned int swap_rgb :1; /* RGB swapped to BGR */ ++ unsigned int alpha_first :1; /* Alpha at start, not end */ ++ unsigned int alpha_inverted :1; /* Alpha channel inverted */ ++ unsigned int mono_inverted :1; /* Gray channel inverted */ ++ unsigned int swap16 :1; /* Byte swap 16-bit components */ ++ unsigned int littleendian :1; /* High bits on right */ ++ unsigned int sig_bits :1; /* Pixel shifted (sig bits only) */ + + /* For checking the code calculates double precision floating point values + * along with an error value, accumulated from the transforms. Because an +@@ -5285,6 +5569,9 @@ + + * up to just less than +/-1 in the scaled value) the *lowest* sBIT for each + * channel is stored. This sBIT value is folded in to the stored error value + * at the end of the application of the transforms to the pixel. ++ * ++ * If sig_bits is set above the red, green, blue and alpha values have been ++ * scaled so they only contain the significant bits of the component values. + */ + double redf, greenf, bluef, alphaf; + double rede, greene, bluee, alphae; +@@ -5293,26 +5580,27 @@ + + + /* Shared utility function, see below. */ + static void +-image_pixel_setf(image_pixel *this, unsigned int max) ++image_pixel_setf(image_pixel *this, unsigned int rMax, unsigned int gMax, ++ unsigned int bMax, unsigned int aMax) + { +- this->redf = this->red / (double)max; +- this->greenf = this->green / (double)max; +- this->bluef = this->blue / (double)max; +- this->alphaf = this->alpha / (double)max; ++ this->redf = this->red / (double)rMax; ++ this->greenf = this->green / (double)gMax; ++ this->bluef = this->blue / (double)bMax; ++ this->alphaf = this->alpha / (double)aMax; + +- if (this->red < max) ++ if (this->red < rMax) + this->rede = this->redf * DBL_EPSILON; + else + this->rede = 0; +- if (this->green < max) ++ if (this->green < gMax) + this->greene = this->greenf * DBL_EPSILON; + else + this->greene = 0; +- if (this->blue < max) ++ if (this->blue < bMax) + this->bluee = this->bluef * DBL_EPSILON; + else + this->bluee = 0; +- if (this->alpha < max) ++ if (this->alpha < aMax) + this->alphae = this->alphaf * DBL_EPSILON; + else + this->alphae = 0; +@@ -5324,18 +5612,22 @@ + + */ + static void + image_pixel_init(image_pixel *this, png_const_bytep row, png_byte colour_type, +- png_byte bit_depth, png_uint_32 x, store_palette palette) ++ png_byte bit_depth, png_uint_32 x, store_palette palette, ++ const image_pixel *format /*from pngvalid transform of input*/) + { +- PNG_CONST png_byte sample_depth = (png_byte)(colour_type == ++ const png_byte sample_depth = (png_byte)(colour_type == + PNG_COLOR_TYPE_PALETTE ? 8 : bit_depth); +- PNG_CONST unsigned int max = (1U<swap16); ++ const int littleendian = (format != 0 && format->littleendian); ++ const int sig_bits = (format != 0 && format->sig_bits); + + /* Initially just set everything to the same number and the alpha to opaque. + * Note that this currently assumes a simple palette where entry x has colour + * rgb(x,x,x)! + */ + this->palette_index = this->red = this->green = this->blue = +- sample(row, colour_type, bit_depth, x, 0); ++ sample(row, colour_type, bit_depth, x, 0, swap16, littleendian); + this->alpha = max; + this->red_sBIT = this->green_sBIT = this->blue_sBIT = this->alpha_sBIT = + sample_depth; +@@ -5346,7 +5638,7 @@ + + /* This permits the caller to default to the sample value. */ + if (palette != 0) + { +- PNG_CONST unsigned int i = this->palette_index; ++ const unsigned int i = this->palette_index; + + this->red = palette[i].red; + this->green = palette[i].green; +@@ -5359,21 +5651,52 @@ + + { + unsigned int i = 0; + ++ if ((colour_type & 4) != 0 && format != 0 && format->alpha_first) ++ { ++ this->alpha = this->red; ++ /* This handles the gray case for 'AG' pixels */ ++ this->palette_index = this->red = this->green = this->blue = ++ sample(row, colour_type, bit_depth, x, 1, swap16, littleendian); ++ i = 1; ++ } ++ + if (colour_type & 2) + { +- this->green = sample(row, colour_type, bit_depth, x, 1); +- this->blue = sample(row, colour_type, bit_depth, x, 2); +- i = 2; ++ /* Green is second for both BGR and RGB: */ ++ this->green = sample(row, colour_type, bit_depth, x, ++i, swap16, ++ littleendian); ++ ++ if (format != 0 && format->swap_rgb) /* BGR */ ++ this->red = sample(row, colour_type, bit_depth, x, ++i, swap16, ++ littleendian); ++ else ++ this->blue = sample(row, colour_type, bit_depth, x, ++i, swap16, ++ littleendian); + } +- if (colour_type & 4) +- this->alpha = sample(row, colour_type, bit_depth, x, ++i); ++ ++ else /* grayscale */ if (format != 0 && format->mono_inverted) ++ this->red = this->green = this->blue = this->red ^ max; ++ ++ if ((colour_type & 4) != 0) /* alpha */ ++ { ++ if (format == 0 || !format->alpha_first) ++ this->alpha = sample(row, colour_type, bit_depth, x, ++i, swap16, ++ littleendian); ++ ++ if (format != 0 && format->alpha_inverted) ++ this->alpha ^= max; ++ } + } + + /* Calculate the scaled values, these are simply the values divided by + * 'max' and the error is initialized to the double precision epsilon value + * from the header file. + */ +- image_pixel_setf(this, max); ++ image_pixel_setf(this, ++ sig_bits ? (1U << format->red_sBIT)-1 : max, ++ sig_bits ? (1U << format->green_sBIT)-1 : max, ++ sig_bits ? (1U << format->blue_sBIT)-1 : max, ++ sig_bits ? (1U << format->alpha_sBIT)-1 : max); + + /* Store the input information for use in the transforms - these will + * modify the information. +@@ -5382,8 +5705,18 @@ + + this->bit_depth = bit_depth; + this->sample_depth = sample_depth; + this->have_tRNS = 0; ++ this->swap_rgb = 0; ++ this->alpha_first = 0; ++ this->alpha_inverted = 0; ++ this->mono_inverted = 0; ++ this->swap16 = 0; ++ this->littleendian = 0; ++ this->sig_bits = 0; + } + ++#if defined PNG_READ_EXPAND_SUPPORTED || defined PNG_READ_GRAY_TO_RGB_SUPPORTED\ ++ || defined PNG_READ_EXPAND_SUPPORTED || defined PNG_READ_EXPAND_16_SUPPORTED\ ++ || defined PNG_READ_BACKGROUND_SUPPORTED + /* Convert a palette image to an rgb image. This necessarily converts the tRNS + * chunk at the same time, because the tRNS will be in palette form. The way + * palette validation works means that the original palette is never updated, +@@ -5413,10 +5746,14 @@ + + + /* Add an alpha channel; this will import the tRNS information because tRNS is + * not valid in an alpha image. The bit depth will invariably be set to at +- * least 8. Palette images will be converted to alpha (using the above API). ++ * least 8 prior to 1.7.0. Palette images will be converted to alpha (using ++ * the above API). With png_set_background the alpha channel is never expanded ++ * but this routine is used by pngvalid to simplify code; 'for_background' ++ * records this. + */ + static void +-image_pixel_add_alpha(image_pixel *this, PNG_CONST standard_display *display) ++image_pixel_add_alpha(image_pixel *this, const standard_display *display, ++ int for_background) + { + if (this->colour_type == PNG_COLOR_TYPE_PALETTE) + image_pixel_convert_PLTE(this); +@@ -5425,11 +5762,21 @@ + + { + if (this->colour_type == PNG_COLOR_TYPE_GRAY) + { +- if (this->bit_depth < 8) +- this->bit_depth = 8; ++# if PNG_LIBPNG_VER < 10700 ++ if (!for_background && this->bit_depth < 8) ++ this->bit_depth = this->sample_depth = 8; ++# endif + + if (this->have_tRNS) + { ++ /* After 1.7 the expansion of bit depth only happens if there is a ++ * tRNS chunk to expand at this point. ++ */ ++# if PNG_LIBPNG_VER >= 10700 ++ if (!for_background && this->bit_depth < 8) ++ this->bit_depth = this->sample_depth = 8; ++# endif ++ + this->have_tRNS = 0; + + /* Check the input, original, channel value here against the +@@ -5461,9 +5808,11 @@ + + this->alphaf = 0; + else + this->alphaf = 1; +- +- this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA; + } ++ else ++ this->alphaf = 1; ++ ++ this->colour_type = PNG_COLOR_TYPE_RGB_ALPHA; + } + + /* The error in the alpha is zero and the sBIT value comes from the +@@ -5473,18 +5822,19 @@ + + this->alpha_sBIT = display->alpha_sBIT; + } + } ++#endif /* transforms that need image_pixel_add_alpha */ + + struct transform_display; + typedef struct image_transform + { + /* The name of this transform: a string. */ +- PNG_CONST char *name; ++ const char *name; + + /* Each transform can be disabled from the command line: */ + int enable; + + /* The global list of transforms; read only. */ +- struct image_transform *PNG_CONST list; ++ struct image_transform *const list; + + /* The global count of the number of times this transform has been set on an + * image. +@@ -5497,7 +5847,7 @@ + + /* The next transform in the list, each transform must call its own next + * transform after it has processed the pixel successfully. + */ +- PNG_CONST struct image_transform *next; ++ const struct image_transform *next; + + /* A single transform for the image, expressed as a series of function + * callbacks and some space for values. +@@ -5505,12 +5855,12 @@ + + * First a callback to add any required modifications to the png_modifier; + * this gets called just before the modifier is set up for read. + */ +- void (*ini)(PNG_CONST struct image_transform *this, ++ void (*ini)(const struct image_transform *this, + struct transform_display *that); + + /* And a callback to set the transform on the current png_read_struct: + */ +- void (*set)(PNG_CONST struct image_transform *this, ++ void (*set)(const struct image_transform *this, + struct transform_display *that, png_structp pp, png_infop pi); + + /* Then a transform that takes an input pixel in one PNG format or another +@@ -5519,8 +5869,8 @@ + + * in the libpng implementation!) The png_structp is solely to allow error + * reporting via png_error and png_warning. + */ +- void (*mod)(PNG_CONST struct image_transform *this, image_pixel *that, +- png_const_structp pp, PNG_CONST struct transform_display *display); ++ void (*mod)(const struct image_transform *this, image_pixel *that, ++ png_const_structp pp, const struct transform_display *display); + + /* Add this transform to the list and return true if the transform is + * meaningful for this colour type and bit depth - if false then the +@@ -5528,7 +5878,7 @@ + + * point running it. + */ + int (*add)(struct image_transform *this, +- PNG_CONST struct image_transform **that, png_byte colour_type, ++ const struct image_transform **that, png_byte colour_type, + png_byte bit_depth); + } image_transform; + +@@ -5538,11 +5888,13 @@ + + + /* Parameters */ + png_modifier* pm; +- PNG_CONST image_transform* transform_list; ++ const image_transform* transform_list; ++ unsigned int max_gamma_8; + + /* Local variables */ + png_byte output_colour_type; + png_byte output_bit_depth; ++ png_byte unpacked; + + /* Modifications (not necessarily used.) */ + gama_modification gama_mod; +@@ -5579,7 +5931,7 @@ + + + /* Three functions to end the list: */ + static void +-image_transform_ini_end(PNG_CONST image_transform *this, ++image_transform_ini_end(const image_transform *this, + transform_display *that) + { + UNUSED(this) +@@ -5587,7 +5939,7 @@ + + } + + static void +-image_transform_set_end(PNG_CONST image_transform *this, ++image_transform_set_end(const image_transform *this, + transform_display *that, png_structp pp, png_infop pi) + { + UNUSED(this) +@@ -5614,10 +5966,11 @@ + + } + + static void +-image_transform_mod_end(PNG_CONST image_transform *this, image_pixel *that, +- png_const_structp pp, PNG_CONST transform_display *display) ++image_transform_mod_end(const image_transform *this, image_pixel *that, ++ png_const_structp pp, const transform_display *display) + { +- PNG_CONST unsigned int scale = (1U<sample_depth)-1; ++ const unsigned int scale = (1U<sample_depth)-1; ++ const int sig_bits = that->sig_bits; + + UNUSED(this) + UNUSED(pp) +@@ -5632,6 +5985,13 @@ + + */ + that->red = sample_scale(that->redf, scale); + ++ /* This is a bit bogus; really the above calculation should use the red_sBIT ++ * value, not sample_depth, but because libpng does png_set_shift by just ++ * shifting the bits we get errors if we don't do it the same way. ++ */ ++ if (sig_bits && that->red_sBIT < that->sample_depth) ++ that->red >>= that->sample_depth - that->red_sBIT; ++ + /* The error value is increased, at the end, according to the lowest sBIT + * value seen. Common sense tells us that the intermediate integer + * representations are no more accurate than +/- 0.5 in the integral values, +@@ -5647,7 +6007,13 @@ + + if (that->colour_type & PNG_COLOR_MASK_COLOR) + { + that->green = sample_scale(that->greenf, scale); ++ if (sig_bits && that->green_sBIT < that->sample_depth) ++ that->green >>= that->sample_depth - that->green_sBIT; ++ + that->blue = sample_scale(that->bluef, scale); ++ if (sig_bits && that->blue_sBIT < that->sample_depth) ++ that->blue >>= that->sample_depth - that->blue_sBIT; ++ + that->greene += 1./(2*((1U<green_sBIT)-1)); + that->bluee += 1./(2*((1U<blue_sBIT)-1)); + } +@@ -5667,9 +6033,12 @@ + + else + { + that->alpha = scale; /* opaque */ +- that->alpha = 1; /* Override this. */ ++ that->alphaf = 1; /* Override this. */ + that->alphae = 0; /* It's exact ;-) */ + } ++ ++ if (sig_bits && that->alpha_sBIT < that->sample_depth) ++ that->alpha >>= that->sample_depth - that->alpha_sBIT; + } + + /* Static 'end' structure: */ +@@ -5692,21 +6061,23 @@ + + */ + static void + transform_display_init(transform_display *dp, png_modifier *pm, png_uint_32 id, +- PNG_CONST image_transform *transform_list) ++ const image_transform *transform_list) + { + memset(dp, 0, sizeof *dp); + + /* Standard fields */ +- standard_display_init(&dp->this, &pm->this, id, 0/*do_interlace*/, ++ standard_display_init(&dp->this, &pm->this, id, do_read_interlace, + pm->use_update_info); + + /* Parameter fields */ + dp->pm = pm; + dp->transform_list = transform_list; ++ dp->max_gamma_8 = 16; + + /* Local variable fields */ + dp->output_colour_type = 255; /* invalid */ + dp->output_bit_depth = 255; /* invalid */ ++ dp->unpacked = 0; /* not unpacked */ + } + + static void +@@ -5734,6 +6105,14 @@ + + dp->output_colour_type = png_get_color_type(pp, pi); + dp->output_bit_depth = png_get_bit_depth(pp, pi); + ++ /* If png_set_filler is in action then fake the output color type to include ++ * an alpha channel where appropriate. ++ */ ++ if (dp->output_bit_depth >= 8 && ++ (dp->output_colour_type == PNG_COLOR_TYPE_RGB || ++ dp->output_colour_type == PNG_COLOR_TYPE_GRAY) && dp->this.filler) ++ dp->output_colour_type |= 4; ++ + /* Validate the combination of colour type and bit depth that we are getting + * out of libpng; the semantics of something not in the PNG spec are, at + * best, unclear. +@@ -5768,7 +6147,8 @@ + + } + + /* Use a test pixel to check that the output agrees with what we expect - +- * this avoids running the whole test if the output is unexpected. ++ * this avoids running the whole test if the output is unexpected. This also ++ * checks for internal errors. + */ + { + image_pixel test_pixel; +@@ -5783,7 +6163,7 @@ + + /* Don't need sBIT here, but it must be set to non-zero to avoid + * arithmetic overflows. + */ +- test_pixel.have_tRNS = dp->this.is_transparent; ++ test_pixel.have_tRNS = dp->this.is_transparent != 0; + test_pixel.red_sBIT = test_pixel.green_sBIT = test_pixel.blue_sBIT = + test_pixel.alpha_sBIT = test_pixel.sample_depth; + +@@ -5814,22 +6194,41 @@ + + } + + /* If both bit depth and colour type are correct check the sample depth. +- * I believe these are both internal errors. + */ +- if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE) +- { +- if (test_pixel.sample_depth != 8) /* oops - internal error! */ +- png_error(pp, ""pngvalid: internal: palette sample depth not 8""); +- } +- else if (test_pixel.sample_depth != dp->output_bit_depth) ++ if (test_pixel.colour_type == PNG_COLOR_TYPE_PALETTE && ++ test_pixel.sample_depth != 8) /* oops - internal error! */ ++ png_error(pp, ""pngvalid: internal: palette sample depth not 8""); ++ else if (dp->unpacked && test_pixel.bit_depth != 8) ++ png_error(pp, ""pngvalid: internal: bad unpacked pixel depth""); ++ else if (!dp->unpacked && test_pixel.colour_type != PNG_COLOR_TYPE_PALETTE ++ && test_pixel.bit_depth != test_pixel.sample_depth) + { + char message[128]; + size_t pos = safecat(message, sizeof message, 0, + ""internal: sample depth ""); + ++ /* Because unless something has set 'unpacked' or the image is palette ++ * mapped we expect the transform to keep sample depth and bit depth ++ * the same. ++ */ ++ pos = safecatn(message, sizeof message, pos, test_pixel.sample_depth); ++ pos = safecat(message, sizeof message, pos, "" expected ""); ++ pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth); ++ ++ png_error(pp, message); ++ } ++ else if (test_pixel.bit_depth != dp->output_bit_depth) ++ { ++ /* This could be a libpng error too; libpng has not produced what we ++ * expect for the output bit depth. ++ */ ++ char message[128]; ++ size_t pos = safecat(message, sizeof message, 0, ++ ""internal: bit depth ""); ++ + pos = safecatn(message, sizeof message, pos, dp->output_bit_depth); + pos = safecat(message, sizeof message, pos, "" expected ""); +- pos = safecatn(message, sizeof message, pos, test_pixel.sample_depth); ++ pos = safecatn(message, sizeof message, pos, test_pixel.bit_depth); + + png_error(pp, message); + } +@@ -5847,7 +6246,7 @@ + + transform_range_check(png_const_structp pp, unsigned int r, unsigned int g, + unsigned int b, unsigned int a, unsigned int in_digitized, double in, + unsigned int out, png_byte sample_depth, double err, double limit, +- PNG_CONST char *name, double digitization_error) ++ const char *name, double digitization_error) + { + /* Compare the scaled, digitzed, values of our local calculation (in+-err) + * with the digitized values libpng produced; 'sample_depth' is the actual +@@ -5891,20 +6290,20 @@ + + png_infop pi) + { + /* Constants for the loop below: */ +- PNG_CONST png_store* PNG_CONST ps = dp->this.ps; +- PNG_CONST png_byte in_ct = dp->this.colour_type; +- PNG_CONST png_byte in_bd = dp->this.bit_depth; +- PNG_CONST png_uint_32 w = dp->this.w; +- PNG_CONST png_uint_32 h = dp->this.h; +- PNG_CONST png_byte out_ct = dp->output_colour_type; +- PNG_CONST png_byte out_bd = dp->output_bit_depth; +- PNG_CONST png_byte sample_depth = (png_byte)(out_ct == ++ const png_store* const ps = dp->this.ps; ++ const png_byte in_ct = dp->this.colour_type; ++ const png_byte in_bd = dp->this.bit_depth; ++ const png_uint_32 w = dp->this.w; ++ const png_uint_32 h = dp->this.h; ++ const png_byte out_ct = dp->output_colour_type; ++ const png_byte out_bd = dp->output_bit_depth; ++ const png_byte sample_depth = (png_byte)(out_ct == + PNG_COLOR_TYPE_PALETTE ? 8 : out_bd); +- PNG_CONST png_byte red_sBIT = dp->this.red_sBIT; +- PNG_CONST png_byte green_sBIT = dp->this.green_sBIT; +- PNG_CONST png_byte blue_sBIT = dp->this.blue_sBIT; +- PNG_CONST png_byte alpha_sBIT = dp->this.alpha_sBIT; +- PNG_CONST int have_tRNS = dp->this.is_transparent; ++ const png_byte red_sBIT = dp->this.red_sBIT; ++ const png_byte green_sBIT = dp->this.green_sBIT; ++ const png_byte blue_sBIT = dp->this.blue_sBIT; ++ const png_byte alpha_sBIT = dp->this.alpha_sBIT; ++ const int have_tRNS = dp->this.is_transparent; + double digitization_error; + + store_palette out_palette; +@@ -5959,7 +6358,7 @@ + + + for (y=0; ythis.palette); ++ image_pixel_init(&in_pixel, std, in_ct, in_bd, x, dp->this.palette, ++ NULL); + + in_pixel.red_sBIT = red_sBIT; + in_pixel.green_sBIT = green_sBIT; + in_pixel.blue_sBIT = blue_sBIT; + in_pixel.alpha_sBIT = alpha_sBIT; +- in_pixel.have_tRNS = have_tRNS; ++ in_pixel.have_tRNS = have_tRNS != 0; + + /* For error detection, below. */ + r = in_pixel.red; +@@ -5990,12 +6390,18 @@ + + b = in_pixel.blue; + a = in_pixel.alpha; + ++ /* This applies the transforms to the input data, including output ++ * format operations which must be used when reading the output ++ * pixel that libpng produces. ++ */ + dp->transform_list->mod(dp->transform_list, &in_pixel, pp, dp); + + /* Read the output pixel and compare it to what we got, we don't +- * use the error field here, so no need to update sBIT. ++ * use the error field here, so no need to update sBIT. in_pixel ++ * says whether we expect libpng to change the output format. + */ +- image_pixel_init(&out_pixel, pRow, out_ct, out_bd, x, out_palette); ++ image_pixel_init(&out_pixel, pRow, out_ct, out_bd, x, out_palette, ++ &in_pixel); + + /* We don't expect changes to the index here even if the bit depth is + * changed. +@@ -6058,8 +6464,8 @@ + + + /* A single test run. */ + static void +-transform_test(png_modifier *pmIn, PNG_CONST png_uint_32 idIn, +- PNG_CONST image_transform* transform_listIn, PNG_CONST char * volatile name) ++transform_test(png_modifier *pmIn, const png_uint_32 idIn, ++ const image_transform* transform_listIn, const char * const name) + { + transform_display d; + context(&pmIn->this, fault); +@@ -6160,8 +6566,11 @@ + + #define PT ITSTRUCT(end) /* stores the previous transform */ + + /* To save code: */ +-static void +-image_transform_default_ini(PNG_CONST image_transform *this, ++extern void image_transform_default_ini(const image_transform *this, ++ transform_display *that); /* silence GCC warnings */ ++ ++void /* private, but almost always needed */ ++image_transform_default_ini(const image_transform *this, + transform_display *that) + { + this->next->ini(this->next, that); +@@ -6170,7 +6579,7 @@ + + #ifdef PNG_READ_BACKGROUND_SUPPORTED + static int + image_transform_default_add(image_transform *this, +- PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) ++ const image_transform **that, png_byte colour_type, png_byte bit_depth) + { + UNUSED(colour_type) + UNUSED(bit_depth) +@@ -6185,7 +6594,7 @@ + + #ifdef PNG_READ_EXPAND_SUPPORTED + /* png_set_palette_to_rgb */ + static void +-image_transform_png_set_palette_to_rgb_set(PNG_CONST image_transform *this, ++image_transform_png_set_palette_to_rgb_set(const image_transform *this, + transform_display *that, png_structp pp, png_infop pi) + { + png_set_palette_to_rgb(pp); +@@ -6193,9 +6602,9 @@ + + } + + static void +-image_transform_png_set_palette_to_rgb_mod(PNG_CONST image_transform *this, ++image_transform_png_set_palette_to_rgb_mod(const image_transform *this, + image_pixel *that, png_const_structp pp, +- PNG_CONST transform_display *display) ++ const transform_display *display) + { + if (that->colour_type == PNG_COLOR_TYPE_PALETTE) + image_pixel_convert_PLTE(that); +@@ -6205,7 +6614,7 @@ + + + static int + image_transform_png_set_palette_to_rgb_add(image_transform *this, +- PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) ++ const image_transform **that, png_byte colour_type, png_byte bit_depth) + { + UNUSED(bit_depth) + +@@ -6223,28 +6632,42 @@ + + #ifdef PNG_READ_EXPAND_SUPPORTED + /* png_set_tRNS_to_alpha */ + static void +-image_transform_png_set_tRNS_to_alpha_set(PNG_CONST image_transform *this, ++image_transform_png_set_tRNS_to_alpha_set(const image_transform *this, + transform_display *that, png_structp pp, png_infop pi) + { + png_set_tRNS_to_alpha(pp); ++ ++ /* If there was a tRNS chunk that would get expanded and add an alpha ++ * channel is_transparent must be updated: ++ */ ++ if (that->this.has_tRNS) ++ that->this.is_transparent = 1; ++ + this->next->set(this->next, that, pp, pi); + } + + static void +-image_transform_png_set_tRNS_to_alpha_mod(PNG_CONST image_transform *this, ++image_transform_png_set_tRNS_to_alpha_mod(const image_transform *this, + image_pixel *that, png_const_structp pp, +- PNG_CONST transform_display *display) ++ const transform_display *display) + { ++#if PNG_LIBPNG_VER < 10700 + /* LIBPNG BUG: this always forces palette images to RGB. */ + if (that->colour_type == PNG_COLOR_TYPE_PALETTE) + image_pixel_convert_PLTE(that); ++#endif + + /* This effectively does an 'expand' only if there is some transparency to + * convert to an alpha channel. + */ + if (that->have_tRNS) +- image_pixel_add_alpha(that, &display->this); ++# if PNG_LIBPNG_VER >= 10700 ++ if (that->colour_type != PNG_COLOR_TYPE_PALETTE && ++ (that->colour_type & PNG_COLOR_MASK_ALPHA) == 0) ++# endif ++ image_pixel_add_alpha(that, &display->this, 0/*!for background*/); + ++#if PNG_LIBPNG_VER < 10700 + /* LIBPNG BUG: otherwise libpng still expands to 8 bits! */ + else + { +@@ -6253,13 +6676,14 @@ + + if (that->sample_depth < 8) + that->sample_depth = 8; + } ++#endif + + this->next->mod(this->next, that, pp, display); + } + + static int + image_transform_png_set_tRNS_to_alpha_add(image_transform *this, +- PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) ++ const image_transform **that, png_byte colour_type, png_byte bit_depth) + { + UNUSED(bit_depth) + +@@ -6268,9 +6692,14 @@ + + + /* We don't know yet whether there will be a tRNS chunk, but we know that + * this transformation should do nothing if there already is an alpha +- * channel. ++ * channel. In addition, after the bug fix in 1.7.0, there is no longer ++ * any action on a palette image. + */ +- return (colour_type & PNG_COLOR_MASK_ALPHA) == 0; ++ return ++# if PNG_LIBPNG_VER >= 10700 ++ colour_type != PNG_COLOR_TYPE_PALETTE && ++# endif ++ (colour_type & PNG_COLOR_MASK_ALPHA) == 0; + } + + IT(tRNS_to_alpha); +@@ -6281,17 +6710,18 @@ + + #ifdef PNG_READ_GRAY_TO_RGB_SUPPORTED + /* png_set_gray_to_rgb */ + static void +-image_transform_png_set_gray_to_rgb_set(PNG_CONST image_transform *this, ++image_transform_png_set_gray_to_rgb_set(const image_transform *this, + transform_display *that, png_structp pp, png_infop pi) + { + png_set_gray_to_rgb(pp); ++ /* NOTE: this doesn't result in tRNS expansion. */ + this->next->set(this->next, that, pp, pi); + } + + static void +-image_transform_png_set_gray_to_rgb_mod(PNG_CONST image_transform *this, ++image_transform_png_set_gray_to_rgb_mod(const image_transform *this, + image_pixel *that, png_const_structp pp, +- PNG_CONST transform_display *display) ++ const transform_display *display) + { + /* NOTE: we can actually pend the tRNS processing at this point because we + * can correctly recognize the original pixel value even though we have +@@ -6299,7 +6729,7 @@ + + * doesn't do this, so we don't either. + */ + if ((that->colour_type & PNG_COLOR_MASK_COLOR) == 0 && that->have_tRNS) +- image_pixel_add_alpha(that, &display->this); ++ image_pixel_add_alpha(that, &display->this, 0/*!for background*/); + + /* Simply expand the bit depth and alter the colour type as required. */ + if (that->colour_type == PNG_COLOR_TYPE_GRAY) +@@ -6322,7 +6752,7 @@ + + + static int + image_transform_png_set_gray_to_rgb_add(image_transform *this, +- PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) ++ const image_transform **that, png_byte colour_type, png_byte bit_depth) + { + UNUSED(bit_depth) + +@@ -6340,17 +6770,21 @@ + + #ifdef PNG_READ_EXPAND_SUPPORTED + /* png_set_expand */ + static void +-image_transform_png_set_expand_set(PNG_CONST image_transform *this, ++image_transform_png_set_expand_set(const image_transform *this, + transform_display *that, png_structp pp, png_infop pi) + { + png_set_expand(pp); ++ ++ if (that->this.has_tRNS) ++ that->this.is_transparent = 1; ++ + this->next->set(this->next, that, pp, pi); + } + + static void +-image_transform_png_set_expand_mod(PNG_CONST image_transform *this, ++image_transform_png_set_expand_mod(const image_transform *this, + image_pixel *that, png_const_structp pp, +- PNG_CONST transform_display *display) ++ const transform_display *display) + { + /* The general expand case depends on what the colour type is: */ + if (that->colour_type == PNG_COLOR_TYPE_PALETTE) +@@ -6359,14 +6793,14 @@ + + that->sample_depth = that->bit_depth = 8; + + if (that->have_tRNS) +- image_pixel_add_alpha(that, &display->this); ++ image_pixel_add_alpha(that, &display->this, 0/*!for background*/); + + this->next->mod(this->next, that, pp, display); + } + + static int + image_transform_png_set_expand_add(image_transform *this, +- PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) ++ const image_transform **that, png_byte colour_type, png_byte bit_depth) + { + UNUSED(bit_depth) + +@@ -6386,31 +6820,53 @@ + + + #ifdef PNG_READ_EXPAND_SUPPORTED + /* png_set_expand_gray_1_2_4_to_8 +- * LIBPNG BUG: this just does an 'expand' ++ * Pre 1.7.0 LIBPNG BUG: this just does an 'expand' + */ + static void + image_transform_png_set_expand_gray_1_2_4_to_8_set( +- PNG_CONST image_transform *this, transform_display *that, png_structp pp, ++ const image_transform *this, transform_display *that, png_structp pp, + png_infop pi) + { + png_set_expand_gray_1_2_4_to_8(pp); ++ /* NOTE: don't expect this to expand tRNS */ + this->next->set(this->next, that, pp, pi); + } + + static void + image_transform_png_set_expand_gray_1_2_4_to_8_mod( +- PNG_CONST image_transform *this, image_pixel *that, png_const_structp pp, +- PNG_CONST transform_display *display) ++ const image_transform *this, image_pixel *that, png_const_structp pp, ++ const transform_display *display) + { ++#if PNG_LIBPNG_VER < 10700 + image_transform_png_set_expand_mod(this, that, pp, display); ++#else ++ /* Only expand grayscale of bit depth less than 8: */ ++ if (that->colour_type == PNG_COLOR_TYPE_GRAY && ++ that->bit_depth < 8) ++ that->sample_depth = that->bit_depth = 8; ++ ++ this->next->mod(this->next, that, pp, display); ++#endif /* 1.7 or later */ + } + + static int + image_transform_png_set_expand_gray_1_2_4_to_8_add(image_transform *this, +- PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) ++ const image_transform **that, png_byte colour_type, png_byte bit_depth) + { ++#if PNG_LIBPNG_VER < 10700 + return image_transform_png_set_expand_add(this, that, colour_type, + bit_depth); ++#else ++ UNUSED(bit_depth) ++ ++ this->next = *that; ++ *that = this; ++ ++ /* This should do nothing unless the color type is gray and the bit depth is ++ * less than 8: ++ */ ++ return colour_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8; ++#endif /* 1.7 or later */ + } + + IT(expand_gray_1_2_4_to_8); +@@ -6421,17 +6877,24 @@ + + #ifdef PNG_READ_EXPAND_16_SUPPORTED + /* png_set_expand_16 */ + static void +-image_transform_png_set_expand_16_set(PNG_CONST image_transform *this, ++image_transform_png_set_expand_16_set(const image_transform *this, + transform_display *that, png_structp pp, png_infop pi) + { + png_set_expand_16(pp); ++ ++ /* NOTE: prior to 1.7 libpng does SET_EXPAND as well, so tRNS is expanded. */ ++# if PNG_LIBPNG_VER < 10700 ++ if (that->this.has_tRNS) ++ that->this.is_transparent = 1; ++# endif ++ + this->next->set(this->next, that, pp, pi); + } + + static void +-image_transform_png_set_expand_16_mod(PNG_CONST image_transform *this, ++image_transform_png_set_expand_16_mod(const image_transform *this, + image_pixel *that, png_const_structp pp, +- PNG_CONST transform_display *display) ++ const transform_display *display) + { + /* Expect expand_16 to expand everything to 16 bits as a result of also + * causing 'expand' to happen. +@@ -6440,7 +6903,7 @@ + + image_pixel_convert_PLTE(that); + + if (that->have_tRNS) +- image_pixel_add_alpha(that, &display->this); ++ image_pixel_add_alpha(that, &display->this, 0/*!for background*/); + + if (that->bit_depth < 16) + that->sample_depth = that->bit_depth = 16; +@@ -6450,7 +6913,7 @@ + + + static int + image_transform_png_set_expand_16_add(image_transform *this, +- PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) ++ const image_transform **that, png_byte colour_type, png_byte bit_depth) + { + UNUSED(colour_type) + +@@ -6469,17 +6932,21 @@ + + #ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED /* API added in 1.5.4 */ + /* png_set_scale_16 */ + static void +-image_transform_png_set_scale_16_set(PNG_CONST image_transform *this, ++image_transform_png_set_scale_16_set(const image_transform *this, + transform_display *that, png_structp pp, png_infop pi) + { + png_set_scale_16(pp); ++# if PNG_LIBPNG_VER < 10700 ++ /* libpng will limit the gamma table size: */ ++ that->max_gamma_8 = PNG_MAX_GAMMA_8; ++# endif + this->next->set(this->next, that, pp, pi); + } + + static void +-image_transform_png_set_scale_16_mod(PNG_CONST image_transform *this, ++image_transform_png_set_scale_16_mod(const image_transform *this, + image_pixel *that, png_const_structp pp, +- PNG_CONST transform_display *display) ++ const transform_display *display) + { + if (that->bit_depth == 16) + { +@@ -6495,7 +6962,7 @@ + + + static int + image_transform_png_set_scale_16_add(image_transform *this, +- PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) ++ const image_transform **that, png_byte colour_type, png_byte bit_depth) + { + UNUSED(colour_type) + +@@ -6513,17 +6980,21 @@ + + #ifdef PNG_READ_16_TO_8_SUPPORTED /* the default before 1.5.4 */ + /* png_set_strip_16 */ + static void +-image_transform_png_set_strip_16_set(PNG_CONST image_transform *this, ++image_transform_png_set_strip_16_set(const image_transform *this, + transform_display *that, png_structp pp, png_infop pi) + { + png_set_strip_16(pp); ++# if PNG_LIBPNG_VER < 10700 ++ /* libpng will limit the gamma table size: */ ++ that->max_gamma_8 = PNG_MAX_GAMMA_8; ++# endif + this->next->set(this->next, that, pp, pi); + } + + static void +-image_transform_png_set_strip_16_mod(PNG_CONST image_transform *this, ++image_transform_png_set_strip_16_mod(const image_transform *this, + image_pixel *that, png_const_structp pp, +- PNG_CONST transform_display *display) ++ const transform_display *display) + { + if (that->bit_depth == 16) + { +@@ -6548,7 +7019,7 @@ + + * png_set_scale_16 API in 1.5.4 (but 1.5.4+ always defines the above!) + */ + { +- PNG_CONST double d = (255-128.5)/65535; ++ const double d = (255-128.5)/65535; + that->rede += d; + that->greene += d; + that->bluee += d; +@@ -6562,7 +7033,7 @@ + + + static int + image_transform_png_set_strip_16_add(image_transform *this, +- PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) ++ const image_transform **that, png_byte colour_type, png_byte bit_depth) + { + UNUSED(colour_type) + +@@ -6580,7 +7051,7 @@ + + #ifdef PNG_READ_STRIP_ALPHA_SUPPORTED + /* png_set_strip_alpha */ + static void +-image_transform_png_set_strip_alpha_set(PNG_CONST image_transform *this, ++image_transform_png_set_strip_alpha_set(const image_transform *this, + transform_display *that, png_structp pp, png_infop pi) + { + png_set_strip_alpha(pp); +@@ -6588,9 +7059,9 @@ + + } + + static void +-image_transform_png_set_strip_alpha_mod(PNG_CONST image_transform *this, ++image_transform_png_set_strip_alpha_mod(const image_transform *this, + image_pixel *that, png_const_structp pp, +- PNG_CONST transform_display *display) ++ const transform_display *display) + { + if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA) + that->colour_type = PNG_COLOR_TYPE_GRAY; +@@ -6605,7 +7076,7 @@ + + + static int + image_transform_png_set_strip_alpha_add(image_transform *this, +- PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) ++ const image_transform **that, png_byte colour_type, png_byte bit_depth) + { + UNUSED(bit_depth) + +@@ -6626,7 +7097,8 @@ + + * png_fixed_point green) + * png_get_rgb_to_gray_status + * +- * The 'default' test here uses values known to be used inside libpng: ++ * The 'default' test here uses values known to be used inside libpng prior to ++ * 1.7.0: + * + * red: 6968 + * green: 23434 +@@ -6663,11 +7135,11 @@ + + #undef image_transform_ini + #define image_transform_ini image_transform_png_set_rgb_to_gray_ini + static void +-image_transform_png_set_rgb_to_gray_ini(PNG_CONST image_transform *this, ++image_transform_png_set_rgb_to_gray_ini(const image_transform *this, + transform_display *that) + { + png_modifier *pm = that->pm; +- PNG_CONST color_encoding *e = pm->current_encoding; ++ const color_encoding *e = pm->current_encoding; + + UNUSED(this) + +@@ -6682,7 +7154,7 @@ + + /* Coefficients come from the encoding, but may need to be normalized to a + * white point Y of 1.0 + */ +- PNG_CONST double whiteY = e->red.Y + e->green.Y + e->blue.Y; ++ const double whiteY = e->red.Y + e->green.Y + e->blue.Y; + + data.red_coefficient = e->red.Y; + data.green_coefficient = e->green.Y; +@@ -6699,9 +7171,15 @@ + + else + { + /* The default (built in) coeffcients, as above: */ +- data.red_coefficient = 6968 / 32768.; +- data.green_coefficient = 23434 / 32768.; +- data.blue_coefficient = 2366 / 32768.; ++# if PNG_LIBPNG_VER < 10700 ++ data.red_coefficient = 6968 / 32768.; ++ data.green_coefficient = 23434 / 32768.; ++ data.blue_coefficient = 2366 / 32768.; ++# else ++ data.red_coefficient = .2126; ++ data.green_coefficient = .7152; ++ data.blue_coefficient = .0722; ++# endif + } + + data.gamma = pm->current_gamma; +@@ -6776,14 +7254,15 @@ + + * conversion adds another +/-2 in the 16-bit case and + * +/-(1<<(15-PNG_MAX_GAMMA_8)) in the 8-bit case. + */ ++# if PNG_LIBPNG_VER < 10700 ++ if (that->this.bit_depth < 16) ++ that->max_gamma_8 = PNG_MAX_GAMMA_8; ++# endif + that->pm->limit += pow( +-# if PNG_MAX_GAMMA_8 < 14 +- (that->this.bit_depth == 16 ? 8. : +- 6. + (1<<(15-PNG_MAX_GAMMA_8))) +-# else +- 8. +-# endif +- /65535, data.gamma); ++ (that->this.bit_depth == 16 || that->max_gamma_8 > 14 ? ++ 8. : ++ 6. + (1<<(15-that->max_gamma_8)) ++ )/65535, data.gamma); + } + + else +@@ -6795,19 +7274,18 @@ + + * When DIGITIZE is set because a pre-1.7 version of libpng is being + * tested allow a bigger slack. + * +- * NOTE: this magic number was determined by experiment to be 1.1 (when +- * using fixed point arithmetic). There's no great merit to the value +- * below, however it only affects the limit used for checking for +- * internal calculation errors, not the actual limit imposed by +- * pngvalid on the output errors. ++ * NOTE: this magic number was determined by experiment to be about ++ * 1.263. There's no great merit to the value below, however it only ++ * affects the limit used for checking for internal calculation errors, ++ * not the actual limit imposed by pngvalid on the output errors. + */ + that->pm->limit += pow( +-# if DIGITIZE +- 1.1 +-# else +- 1. +-# endif +- /255, data.gamma); ++# if DIGITIZE ++ 1.3 ++# else ++ 1.0 ++# endif ++ /255, data.gamma); + } + } + +@@ -6822,10 +7300,10 @@ + + } + + static void +-image_transform_png_set_rgb_to_gray_set(PNG_CONST image_transform *this, ++image_transform_png_set_rgb_to_gray_set(const image_transform *this, + transform_display *that, png_structp pp, png_infop pi) + { +- PNG_CONST int error_action = 1; /* no error, no defines in png.h */ ++ const int error_action = 1; /* no error, no defines in png.h */ + + # ifdef PNG_FLOATING_POINT_SUPPORTED + png_set_rgb_to_gray(pp, error_action, data.red_to_set, data.green_to_set); +@@ -6862,7 +7340,7 @@ + + & PNG_INFO_cHRM) != 0) + { + double maxe; +- PNG_CONST char *el; ++ const char *el; + color_encoding e, o; + + /* Expect libpng to return a normalized result, but the original +@@ -6949,26 +7427,32 @@ + + } + + static void +-image_transform_png_set_rgb_to_gray_mod(PNG_CONST image_transform *this, ++image_transform_png_set_rgb_to_gray_mod(const image_transform *this, + image_pixel *that, png_const_structp pp, +- PNG_CONST transform_display *display) ++ const transform_display *display) + { + if ((that->colour_type & PNG_COLOR_MASK_COLOR) != 0) + { + double gray, err; + +- if (that->colour_type == PNG_COLOR_TYPE_PALETTE) +- image_pixel_convert_PLTE(that); ++# if PNG_LIBPNG_VER < 10700 ++ if (that->colour_type == PNG_COLOR_TYPE_PALETTE) ++ image_pixel_convert_PLTE(that); ++# endif + + /* Image now has RGB channels... */ + # if DIGITIZE + { +- PNG_CONST png_modifier *pm = display->pm; ++ const png_modifier *pm = display->pm; + const unsigned int sample_depth = that->sample_depth; + const unsigned int calc_depth = (pm->assume_16_bit_calculations ? 16 : + sample_depth); +- const unsigned int gamma_depth = (sample_depth == 16 ? 16 : +- (pm->assume_16_bit_calculations ? PNG_MAX_GAMMA_8 : sample_depth)); ++ const unsigned int gamma_depth = ++ (sample_depth == 16 ? ++ display->max_gamma_8 : ++ (pm->assume_16_bit_calculations ? ++ display->max_gamma_8 : ++ sample_depth)); + int isgray; + double r, g, b; + double rlo, rhi, glo, ghi, blo, bhi, graylo, grayhi; +@@ -6981,56 +7465,73 @@ + + * will be identical after this operation if there is only one + * transform, feel free to delete the png_error checks on this below in + * the future (this is just me trying to ensure it works!) ++ * ++ * Interval arithmetic is exact, but to implement it it must be ++ * possible to control the floating point implementation rounding mode. ++ * This cannot be done in ANSI-C, so instead I reduce the 'lo' values ++ * by DBL_EPSILON and increase the 'hi' values by the same. + */ ++# define DD(v,d,r) (digitize(v*(1-DBL_EPSILON), d, r) * (1-DBL_EPSILON)) ++# define DU(v,d,r) (digitize(v*(1+DBL_EPSILON), d, r) * (1+DBL_EPSILON)) ++ + r = rlo = rhi = that->redf; + rlo -= that->rede; +- rlo = digitize(rlo, calc_depth, 1/*round*/); ++ rlo = DD(rlo, calc_depth, 1/*round*/); + rhi += that->rede; +- rhi = digitize(rhi, calc_depth, 1/*round*/); ++ rhi = DU(rhi, calc_depth, 1/*round*/); + + g = glo = ghi = that->greenf; + glo -= that->greene; +- glo = digitize(glo, calc_depth, 1/*round*/); ++ glo = DD(glo, calc_depth, 1/*round*/); + ghi += that->greene; +- ghi = digitize(ghi, calc_depth, 1/*round*/); ++ ghi = DU(ghi, calc_depth, 1/*round*/); + + b = blo = bhi = that->bluef; + blo -= that->bluee; +- blo = digitize(blo, calc_depth, 1/*round*/); +- bhi += that->greene; +- bhi = digitize(bhi, calc_depth, 1/*round*/); ++ blo = DD(blo, calc_depth, 1/*round*/); ++ bhi += that->bluee; ++ bhi = DU(bhi, calc_depth, 1/*round*/); + + isgray = r==g && g==b; + + if (data.gamma != 1) + { +- PNG_CONST double power = 1/data.gamma; +- PNG_CONST double abse = calc_depth == 16 ? .5/65535 : .5/255; ++ const double power = 1/data.gamma; ++ const double abse = .5/(sample_depth == 16 ? 65535 : 255); + +- /* 'abse' is the absolute error permitted in linear calculations. It +- * is used here to capture the error permitted in the handling +- * (undoing) of the gamma encoding. Once again digitization occurs +- * to handle the upper and lower bounds of the values. This is +- * where the real errors are introduced. ++ /* If a gamma calculation is done it is done using lookup tables of ++ * precision gamma_depth, so the already digitized value above may ++ * need to be further digitized here. + */ ++ if (gamma_depth != calc_depth) ++ { ++ rlo = DD(rlo, gamma_depth, 0/*truncate*/); ++ rhi = DU(rhi, gamma_depth, 0/*truncate*/); ++ glo = DD(glo, gamma_depth, 0/*truncate*/); ++ ghi = DU(ghi, gamma_depth, 0/*truncate*/); ++ blo = DD(blo, gamma_depth, 0/*truncate*/); ++ bhi = DU(bhi, gamma_depth, 0/*truncate*/); ++ } ++ ++ /* 'abse' is the error in the gamma table calculation itself. */ + r = pow(r, power); +- rlo = digitize(pow(rlo, power)-abse, calc_depth, 1); +- rhi = digitize(pow(rhi, power)+abse, calc_depth, 1); ++ rlo = DD(pow(rlo, power)-abse, calc_depth, 1); ++ rhi = DU(pow(rhi, power)+abse, calc_depth, 1); + + g = pow(g, power); +- glo = digitize(pow(glo, power)-abse, calc_depth, 1); +- ghi = digitize(pow(ghi, power)+abse, calc_depth, 1); ++ glo = DD(pow(glo, power)-abse, calc_depth, 1); ++ ghi = DU(pow(ghi, power)+abse, calc_depth, 1); + + b = pow(b, power); +- blo = digitize(pow(blo, power)-abse, calc_depth, 1); +- bhi = digitize(pow(bhi, power)+abse, calc_depth, 1); ++ blo = DD(pow(blo, power)-abse, calc_depth, 1); ++ bhi = DU(pow(bhi, power)+abse, calc_depth, 1); + } + + /* Now calculate the actual gray values. Although the error in the + * coefficients depends on whether they were specified on the command + * line (in which case truncation to 15 bits happened) or not (rounding + * was used) the maxium error in an individual coefficient is always +- * 1/32768, because even in the rounding case the requirement that ++ * 2/32768, because even in the rounding case the requirement that + * coefficients add up to 32768 can cause a larger rounding error. + * + * The only time when rounding doesn't occur in 1.5.5 and later is when +@@ -7040,32 +7541,46 @@ + + b * data.blue_coefficient; + + { +- PNG_CONST int do_round = data.gamma != 1 || calc_depth == 16; +- PNG_CONST double ce = 1. / 32768; ++ const int do_round = data.gamma != 1 || calc_depth == 16; ++ const double ce = 2. / 32768; + +- graylo = digitize(rlo * (data.red_coefficient-ce) + ++ graylo = DD(rlo * (data.red_coefficient-ce) + + glo * (data.green_coefficient-ce) + +- blo * (data.blue_coefficient-ce), gamma_depth, do_round); +- if (graylo <= 0) +- graylo = 0; ++ blo * (data.blue_coefficient-ce), calc_depth, do_round); ++ if (graylo > gray) /* always accept the right answer */ ++ graylo = gray; + +- grayhi = digitize(rhi * (data.red_coefficient+ce) + ++ grayhi = DU(rhi * (data.red_coefficient+ce) + + ghi * (data.green_coefficient+ce) + +- bhi * (data.blue_coefficient+ce), gamma_depth, do_round); +- if (grayhi >= 1) +- grayhi = 1; ++ bhi * (data.blue_coefficient+ce), calc_depth, do_round); ++ if (grayhi < gray) ++ grayhi = gray; + } + + /* And invert the gamma. */ + if (data.gamma != 1) + { +- PNG_CONST double power = data.gamma; ++ const double power = data.gamma; ++ ++ /* And this happens yet again, shifting the values once more. */ ++ if (gamma_depth != sample_depth) ++ { ++ rlo = DD(rlo, gamma_depth, 0/*truncate*/); ++ rhi = DU(rhi, gamma_depth, 0/*truncate*/); ++ glo = DD(glo, gamma_depth, 0/*truncate*/); ++ ghi = DU(ghi, gamma_depth, 0/*truncate*/); ++ blo = DD(blo, gamma_depth, 0/*truncate*/); ++ bhi = DU(bhi, gamma_depth, 0/*truncate*/); ++ } + + gray = pow(gray, power); +- graylo = digitize(pow(graylo, power), sample_depth, 1); +- grayhi = digitize(pow(grayhi, power), sample_depth, 1); ++ graylo = DD(pow(graylo, power), sample_depth, 1); ++ grayhi = DU(pow(grayhi, power), sample_depth, 1); + } + ++# undef DD ++# undef DU ++ + /* Now the error can be calculated. + * + * If r==g==b because there is no overall gamma correction libpng +@@ -7103,29 +7618,46 @@ + + double b = that->bluef; + double be = that->bluee; + +- /* The true gray case involves no math. */ +- if (r == g && r == b) +- { +- gray = r; +- err = re; +- if (err < ge) err = ge; +- if (err < be) err = be; +- } ++# if PNG_LIBPNG_VER < 10700 ++ /* The true gray case involves no math in earlier versions (not ++ * true, there was some if gamma correction was happening too.) ++ */ ++ if (r == g && r == b) ++ { ++ gray = r; ++ err = re; ++ if (err < ge) err = ge; ++ if (err < be) err = be; ++ } + +- else if (data.gamma == 1) ++ else ++# endif /* before 1.7 */ ++ if (data.gamma == 1) + { + /* There is no need to do the conversions to and from linear space, + * so the calculation should be a lot more accurate. There is a +- * built in 1/32768 error in the coefficients because they only have +- * 15 bits and are adjusted to make sure they add up to 32768, so +- * the result may have an additional error up to 1/32768. (Note +- * that adding the 1/32768 here avoids needing to increase the +- * global error limits to take this into account.) ++ * built in error in the coefficients because they only have 15 bits ++ * and are adjusted to make sure they add up to 32768. This ++ * involves a integer calculation with truncation of the form: ++ * ++ * ((int)(coefficient * 100000) * 32768)/100000 ++ * ++ * This is done to the red and green coefficients (the ones ++ * provided to the API) then blue is calculated from them so the ++ * result adds up to 32768. In the worst case this can result in ++ * a -1 error in red and green and a +2 error in blue. Consequently ++ * the worst case in the calculation below is 2/32768 error. ++ * ++ * TODO: consider fixing this in libpng by rounding the calculation ++ * limiting the error to 1/32768. ++ * ++ * Handling this by adding 2/32768 here avoids needing to increase ++ * the global error limits to take this into account.) + */ + gray = r * data.red_coefficient + g * data.green_coefficient + + b * data.blue_coefficient; + err = re * data.red_coefficient + ge * data.green_coefficient + +- be * data.blue_coefficient + 1./32768 + gray * 5 * DBL_EPSILON; ++ be * data.blue_coefficient + 2./32768 + gray * 5 * DBL_EPSILON; + } + + else +@@ -7136,10 +7668,10 @@ + + * lookups in the calculation and each introduces a quantization + * error defined by the table size. + */ +- PNG_CONST png_modifier *pm = display->pm; ++ const png_modifier *pm = display->pm; + double in_qe = (that->sample_depth > 8 ? .5/65535 : .5/255); + double out_qe = (that->sample_depth > 8 ? .5/65535 : +- (pm->assume_16_bit_calculations ? .5/(1<assume_16_bit_calculations ? .5/(1<max_gamma_8) : + .5/255)); + double rhi, ghi, bhi, grayhi; + double g1 = 1/data.gamma; +@@ -7160,7 +7692,7 @@ + + * previously added input quantization error at this point. + */ + gray = r * data.red_coefficient + g * data.green_coefficient + +- b * data.blue_coefficient - 1./32768 - out_qe; ++ b * data.blue_coefficient - 2./32768 - out_qe; + if (gray <= 0) + gray = 0; + else +@@ -7170,7 +7702,7 @@ + + } + + grayhi = rhi * data.red_coefficient + ghi * data.green_coefficient + +- bhi * data.blue_coefficient + 1./32768 + out_qe; ++ bhi * data.blue_coefficient + 2./32768 + out_qe; + grayhi *= (1 + 6 * DBL_EPSILON); + if (grayhi >= 1) + grayhi = 1; +@@ -7226,7 +7758,7 @@ + + + static int + image_transform_png_set_rgb_to_gray_add(image_transform *this, +- PNG_CONST image_transform **that, png_byte colour_type, png_byte bit_depth) ++ const image_transform **that, png_byte colour_type, png_byte bit_depth) + { + UNUSED(bit_depth) + +@@ -7257,7 +7789,7 @@ + + static image_pixel data; + + static void +-image_transform_png_set_background_set(PNG_CONST image_transform *this, ++image_transform_png_set_background_set(const image_transform *this, + transform_display *that, png_structp pp, png_infop pi) + { + png_byte colour_type, bit_depth; +@@ -7285,12 +7817,15 @@ + + + else + { ++ if (that->this.has_tRNS) ++ that->this.is_transparent = 1; ++ + bit_depth = that->this.bit_depth; + expand = 1; + } + + image_pixel_init(&data, random_bytes, colour_type, +- bit_depth, 0/*x*/, 0/*unused: palette*/); ++ bit_depth, 0/*x*/, 0/*unused: palette*/, NULL/*format*/); + + /* Extract the background colour from this image_pixel, but make sure the + * unused fields of 'back' are garbage. +@@ -7317,13 +7852,13 @@ + + } + + static void +-image_transform_png_set_background_mod(PNG_CONST image_transform *this, ++image_transform_png_set_background_mod(const image_transform *this, + image_pixel *that, png_const_structp pp, +- PNG_CONST transform_display *display) ++ const transform_display *display) + { + /* Check for tRNS first: */ + if (that->have_tRNS && that->colour_type != PNG_COLOR_TYPE_PALETTE) +- image_pixel_add_alpha(that, &display->this); ++ image_pixel_add_alpha(that, &display->this, 1/*for background*/); + + /* This is only necessary if the alpha value is less than 1. */ + if (that->alphaf < 1) +@@ -7362,14 +7897,14 @@ + + /* Remove the alpha type and set the alpha (not in that order.) */ + that->alphaf = 1; + that->alphae = 0; +- +- if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA) +- that->colour_type = PNG_COLOR_TYPE_RGB; +- else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA) +- that->colour_type = PNG_COLOR_TYPE_GRAY; +- /* PNG_COLOR_TYPE_PALETTE is not changed */ + } + ++ if (that->colour_type == PNG_COLOR_TYPE_RGB_ALPHA) ++ that->colour_type = PNG_COLOR_TYPE_RGB; ++ else if (that->colour_type == PNG_COLOR_TYPE_GRAY_ALPHA) ++ that->colour_type = PNG_COLOR_TYPE_GRAY; ++ /* PNG_COLOR_TYPE_PALETTE is not changed */ ++ + this->next->mod(this->next, that, pp, display); + } + +@@ -7381,11 +7916,604 @@ + + #define PT ITSTRUCT(background) + #endif /* PNG_READ_BACKGROUND_SUPPORTED */ + +-/* This may just be 'end' if all the transforms are disabled! */ +-static image_transform *PNG_CONST image_transform_first = &PT; ++/* png_set_quantize(png_structp, png_colorp palette, int num_palette, ++ * int maximum_colors, png_const_uint_16p histogram, int full_quantize) ++ * ++ * Very difficult to validate this! ++ */ ++/*NOTE: TBD NYI */ ++ ++/* The data layout transforms are handled by swapping our own channel data, ++ * necessarily these need to happen at the end of the transform list because the ++ * semantic of the channels changes after these are executed. Some of these, ++ * like set_shift and set_packing, can't be done at present because they change ++ * the layout of the data at the sub-sample level so sample() won't get the ++ * right answer. ++ */ ++/* png_set_invert_alpha */ ++#ifdef PNG_READ_INVERT_ALPHA_SUPPORTED ++/* Invert the alpha channel ++ * ++ * png_set_invert_alpha(png_structrp png_ptr) ++ */ ++static void ++image_transform_png_set_invert_alpha_set(const image_transform *this, ++ transform_display *that, png_structp pp, png_infop pi) ++{ ++ png_set_invert_alpha(pp); ++ this->next->set(this->next, that, pp, pi); ++} + + static void +-transform_enable(PNG_CONST char *name) ++image_transform_png_set_invert_alpha_mod(const image_transform *this, ++ image_pixel *that, png_const_structp pp, ++ const transform_display *display) ++{ ++ if (that->colour_type & 4) ++ that->alpha_inverted = 1; ++ ++ this->next->mod(this->next, that, pp, display); ++} ++ ++static int ++image_transform_png_set_invert_alpha_add(image_transform *this, ++ const image_transform **that, png_byte colour_type, png_byte bit_depth) ++{ ++ UNUSED(bit_depth) ++ ++ this->next = *that; ++ *that = this; ++ ++ /* Only has an effect on pixels with alpha: */ ++ return (colour_type & 4) != 0; ++} ++ ++IT(invert_alpha); ++#undef PT ++#define PT ITSTRUCT(invert_alpha) ++ ++#endif /* PNG_READ_INVERT_ALPHA_SUPPORTED */ ++ ++/* png_set_bgr */ ++#ifdef PNG_READ_BGR_SUPPORTED ++/* Swap R,G,B channels to order B,G,R. ++ * ++ * png_set_bgr(png_structrp png_ptr) ++ * ++ * This only has an effect on RGB and RGBA pixels. ++ */ ++static void ++image_transform_png_set_bgr_set(const image_transform *this, ++ transform_display *that, png_structp pp, png_infop pi) ++{ ++ png_set_bgr(pp); ++ this->next->set(this->next, that, pp, pi); ++} ++ ++static void ++image_transform_png_set_bgr_mod(const image_transform *this, ++ image_pixel *that, png_const_structp pp, ++ const transform_display *display) ++{ ++ if (that->colour_type == PNG_COLOR_TYPE_RGB || ++ that->colour_type == PNG_COLOR_TYPE_RGBA) ++ that->swap_rgb = 1; ++ ++ this->next->mod(this->next, that, pp, display); ++} ++ ++static int ++image_transform_png_set_bgr_add(image_transform *this, ++ const image_transform **that, png_byte colour_type, png_byte bit_depth) ++{ ++ UNUSED(bit_depth) ++ ++ this->next = *that; ++ *that = this; ++ ++ return colour_type == PNG_COLOR_TYPE_RGB || ++ colour_type == PNG_COLOR_TYPE_RGBA; ++} ++ ++IT(bgr); ++#undef PT ++#define PT ITSTRUCT(bgr) ++ ++#endif /* PNG_READ_BGR_SUPPORTED */ ++ ++/* png_set_swap_alpha */ ++#ifdef PNG_READ_SWAP_ALPHA_SUPPORTED ++/* Put the alpha channel first. ++ * ++ * png_set_swap_alpha(png_structrp png_ptr) ++ * ++ * This only has an effect on GA and RGBA pixels. ++ */ ++static void ++image_transform_png_set_swap_alpha_set(const image_transform *this, ++ transform_display *that, png_structp pp, png_infop pi) ++{ ++ png_set_swap_alpha(pp); ++ this->next->set(this->next, that, pp, pi); ++} ++ ++static void ++image_transform_png_set_swap_alpha_mod(const image_transform *this, ++ image_pixel *that, png_const_structp pp, ++ const transform_display *display) ++{ ++ if (that->colour_type == PNG_COLOR_TYPE_GA || ++ that->colour_type == PNG_COLOR_TYPE_RGBA) ++ that->alpha_first = 1; ++ ++ this->next->mod(this->next, that, pp, display); ++} ++ ++static int ++image_transform_png_set_swap_alpha_add(image_transform *this, ++ const image_transform **that, png_byte colour_type, png_byte bit_depth) ++{ ++ UNUSED(bit_depth) ++ ++ this->next = *that; ++ *that = this; ++ ++ return colour_type == PNG_COLOR_TYPE_GA || ++ colour_type == PNG_COLOR_TYPE_RGBA; ++} ++ ++IT(swap_alpha); ++#undef PT ++#define PT ITSTRUCT(swap_alpha) ++ ++#endif /* PNG_READ_SWAP_ALPHA_SUPPORTED */ ++ ++/* png_set_swap */ ++#ifdef PNG_READ_SWAP_SUPPORTED ++/* Byte swap 16-bit components. ++ * ++ * png_set_swap(png_structrp png_ptr) ++ */ ++static void ++image_transform_png_set_swap_set(const image_transform *this, ++ transform_display *that, png_structp pp, png_infop pi) ++{ ++ png_set_swap(pp); ++ this->next->set(this->next, that, pp, pi); ++} ++ ++static void ++image_transform_png_set_swap_mod(const image_transform *this, ++ image_pixel *that, png_const_structp pp, ++ const transform_display *display) ++{ ++ if (that->bit_depth == 16) ++ that->swap16 = 1; ++ ++ this->next->mod(this->next, that, pp, display); ++} ++ ++static int ++image_transform_png_set_swap_add(image_transform *this, ++ const image_transform **that, png_byte colour_type, png_byte bit_depth) ++{ ++ UNUSED(colour_type) ++ ++ this->next = *that; ++ *that = this; ++ ++ return bit_depth == 16; ++} ++ ++IT(swap); ++#undef PT ++#define PT ITSTRUCT(swap) ++ ++#endif /* PNG_READ_SWAP_SUPPORTED */ ++ ++#ifdef PNG_READ_FILLER_SUPPORTED ++/* Add a filler byte to 8-bit Gray or 24-bit RGB images. ++ * ++ * png_set_filler, (png_structp png_ptr, png_uint_32 filler, int flags)); ++ * ++ * Flags: ++ * ++ * PNG_FILLER_BEFORE ++ * PNG_FILLER_AFTER ++ */ ++#define data ITDATA(filler) ++static struct ++{ ++ png_uint_32 filler; ++ int flags; ++} data; ++ ++static void ++image_transform_png_set_filler_set(const image_transform *this, ++ transform_display *that, png_structp pp, png_infop pi) ++{ ++ /* Need a random choice for 'before' and 'after' as well as for the ++ * filler. The 'filler' value has all 32 bits set, but only bit_depth ++ * will be used. At this point we don't know bit_depth. ++ */ ++ RANDOMIZE(data.filler); ++ data.flags = random_choice(); ++ ++ png_set_filler(pp, data.filler, data.flags); ++ ++ /* The standard display handling stuff also needs to know that ++ * there is a filler, so set that here. ++ */ ++ that->this.filler = 1; ++ ++ this->next->set(this->next, that, pp, pi); ++} ++ ++static void ++image_transform_png_set_filler_mod(const image_transform *this, ++ image_pixel *that, png_const_structp pp, ++ const transform_display *display) ++{ ++ if (that->bit_depth >= 8 && ++ (that->colour_type == PNG_COLOR_TYPE_RGB || ++ that->colour_type == PNG_COLOR_TYPE_GRAY)) ++ { ++ const unsigned int max = (1U << that->bit_depth)-1; ++ that->alpha = data.filler & max; ++ that->alphaf = ((double)that->alpha) / max; ++ that->alphae = 0; ++ ++ /* The filler has been stored in the alpha channel, we must record ++ * that this has been done for the checking later on, the color ++ * type is faked to have an alpha channel, but libpng won't report ++ * this; the app has to know the extra channel is there and this ++ * was recording in standard_display::filler above. ++ */ ++ that->colour_type |= 4; /* alpha added */ ++ that->alpha_first = data.flags == PNG_FILLER_BEFORE; ++ } ++ ++ this->next->mod(this->next, that, pp, display); ++} ++ ++static int ++image_transform_png_set_filler_add(image_transform *this, ++ const image_transform **that, png_byte colour_type, png_byte bit_depth) ++{ ++ this->next = *that; ++ *that = this; ++ ++ return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB || ++ colour_type == PNG_COLOR_TYPE_GRAY); ++} ++ ++#undef data ++IT(filler); ++#undef PT ++#define PT ITSTRUCT(filler) ++ ++/* png_set_add_alpha, (png_structp png_ptr, png_uint_32 filler, int flags)); */ ++/* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */ ++#define data ITDATA(add_alpha) ++static struct ++{ ++ png_uint_32 filler; ++ int flags; ++} data; ++ ++static void ++image_transform_png_set_add_alpha_set(const image_transform *this, ++ transform_display *that, png_structp pp, png_infop pi) ++{ ++ /* Need a random choice for 'before' and 'after' as well as for the ++ * filler. The 'filler' value has all 32 bits set, but only bit_depth ++ * will be used. At this point we don't know bit_depth. ++ */ ++ RANDOMIZE(data.filler); ++ data.flags = random_choice(); ++ ++ png_set_add_alpha(pp, data.filler, data.flags); ++ this->next->set(this->next, that, pp, pi); ++} ++ ++static void ++image_transform_png_set_add_alpha_mod(const image_transform *this, ++ image_pixel *that, png_const_structp pp, ++ const transform_display *display) ++{ ++ if (that->bit_depth >= 8 && ++ (that->colour_type == PNG_COLOR_TYPE_RGB || ++ that->colour_type == PNG_COLOR_TYPE_GRAY)) ++ { ++ const unsigned int max = (1U << that->bit_depth)-1; ++ that->alpha = data.filler & max; ++ that->alphaf = ((double)that->alpha) / max; ++ that->alphae = 0; ++ ++ that->colour_type |= 4; /* alpha added */ ++ that->alpha_first = data.flags == PNG_FILLER_BEFORE; ++ } ++ ++ this->next->mod(this->next, that, pp, display); ++} ++ ++static int ++image_transform_png_set_add_alpha_add(image_transform *this, ++ const image_transform **that, png_byte colour_type, png_byte bit_depth) ++{ ++ this->next = *that; ++ *that = this; ++ ++ return bit_depth >= 8 && (colour_type == PNG_COLOR_TYPE_RGB || ++ colour_type == PNG_COLOR_TYPE_GRAY); ++} ++ ++#undef data ++IT(add_alpha); ++#undef PT ++#define PT ITSTRUCT(add_alpha) ++ ++#endif /* PNG_READ_FILLER_SUPPORTED */ ++ ++/* png_set_packing */ ++#ifdef PNG_READ_PACK_SUPPORTED ++/* Use 1 byte per pixel in 1, 2, or 4-bit depth files. ++ * ++ * png_set_packing(png_structrp png_ptr) ++ * ++ * This should only affect grayscale and palette images with less than 8 bits ++ * per pixel. ++ */ ++static void ++image_transform_png_set_packing_set(const image_transform *this, ++ transform_display *that, png_structp pp, png_infop pi) ++{ ++ png_set_packing(pp); ++ that->unpacked = 1; ++ this->next->set(this->next, that, pp, pi); ++} ++ ++static void ++image_transform_png_set_packing_mod(const image_transform *this, ++ image_pixel *that, png_const_structp pp, ++ const transform_display *display) ++{ ++ /* The general expand case depends on what the colour type is, ++ * low bit-depth pixel values are unpacked into bytes without ++ * scaling, so sample_depth is not changed. ++ */ ++ if (that->bit_depth < 8) /* grayscale or palette */ ++ that->bit_depth = 8; ++ ++ this->next->mod(this->next, that, pp, display); ++} ++ ++static int ++image_transform_png_set_packing_add(image_transform *this, ++ const image_transform **that, png_byte colour_type, png_byte bit_depth) ++{ ++ UNUSED(colour_type) ++ ++ this->next = *that; ++ *that = this; ++ ++ /* Nothing should happen unless the bit depth is less than 8: */ ++ return bit_depth < 8; ++} ++ ++IT(packing); ++#undef PT ++#define PT ITSTRUCT(packing) ++ ++#endif /* PNG_READ_PACK_SUPPORTED */ ++ ++/* png_set_packswap */ ++#ifdef PNG_READ_PACKSWAP_SUPPORTED ++/* Swap pixels packed into bytes; reverses the order on screen so that ++ * the high order bits correspond to the rightmost pixels. ++ * ++ * png_set_packswap(png_structrp png_ptr) ++ */ ++static void ++image_transform_png_set_packswap_set(const image_transform *this, ++ transform_display *that, png_structp pp, png_infop pi) ++{ ++ png_set_packswap(pp); ++ that->this.littleendian = 1; ++ this->next->set(this->next, that, pp, pi); ++} ++ ++static void ++image_transform_png_set_packswap_mod(const image_transform *this, ++ image_pixel *that, png_const_structp pp, ++ const transform_display *display) ++{ ++ if (that->bit_depth < 8) ++ that->littleendian = 1; ++ ++ this->next->mod(this->next, that, pp, display); ++} ++ ++static int ++image_transform_png_set_packswap_add(image_transform *this, ++ const image_transform **that, png_byte colour_type, png_byte bit_depth) ++{ ++ UNUSED(colour_type) ++ ++ this->next = *that; ++ *that = this; ++ ++ return bit_depth < 8; ++} ++ ++IT(packswap); ++#undef PT ++#define PT ITSTRUCT(packswap) ++ ++#endif /* PNG_READ_PACKSWAP_SUPPORTED */ ++ ++ ++/* png_set_invert_mono */ ++#ifdef PNG_READ_INVERT_MONO_SUPPORTED ++/* Invert the gray channel ++ * ++ * png_set_invert_mono(png_structrp png_ptr) ++ */ ++static void ++image_transform_png_set_invert_mono_set(const image_transform *this, ++ transform_display *that, png_structp pp, png_infop pi) ++{ ++ png_set_invert_mono(pp); ++ this->next->set(this->next, that, pp, pi); ++} ++ ++static void ++image_transform_png_set_invert_mono_mod(const image_transform *this, ++ image_pixel *that, png_const_structp pp, ++ const transform_display *display) ++{ ++ if (that->colour_type & 4) ++ that->mono_inverted = 1; ++ ++ this->next->mod(this->next, that, pp, display); ++} ++ ++static int ++image_transform_png_set_invert_mono_add(image_transform *this, ++ const image_transform **that, png_byte colour_type, png_byte bit_depth) ++{ ++ UNUSED(bit_depth) ++ ++ this->next = *that; ++ *that = this; ++ ++ /* Only has an effect on pixels with no colour: */ ++ return (colour_type & 2) == 0; ++} ++ ++IT(invert_mono); ++#undef PT ++#define PT ITSTRUCT(invert_mono) ++ ++#endif /* PNG_READ_INVERT_MONO_SUPPORTED */ ++ ++#ifdef PNG_READ_SHIFT_SUPPORTED ++/* png_set_shift(png_structp, png_const_color_8p true_bits) ++ * ++ * The output pixels will be shifted by the given true_bits ++ * values. ++ */ ++#define data ITDATA(shift) ++static png_color_8 data; ++ ++static void ++image_transform_png_set_shift_set(const image_transform *this, ++ transform_display *that, png_structp pp, png_infop pi) ++{ ++ /* Get a random set of shifts. The shifts need to do something ++ * to test the transform, so they are limited to the bit depth ++ * of the input image. Notice that in the following the 'gray' ++ * field is randomized independently. This acts as a check that ++ * libpng does use the correct field. ++ */ ++ const unsigned int depth = that->this.bit_depth; ++ ++ data.red = (png_byte)/*SAFE*/(random_mod(depth)+1); ++ data.green = (png_byte)/*SAFE*/(random_mod(depth)+1); ++ data.blue = (png_byte)/*SAFE*/(random_mod(depth)+1); ++ data.gray = (png_byte)/*SAFE*/(random_mod(depth)+1); ++ data.alpha = (png_byte)/*SAFE*/(random_mod(depth)+1); ++ ++ png_set_shift(pp, &data); ++ this->next->set(this->next, that, pp, pi); ++} ++ ++static void ++image_transform_png_set_shift_mod(const image_transform *this, ++ image_pixel *that, png_const_structp pp, ++ const transform_display *display) ++{ ++ /* Copy the correct values into the sBIT fields, libpng does not do ++ * anything to palette data: ++ */ ++ if (that->colour_type != PNG_COLOR_TYPE_PALETTE) ++ { ++ that->sig_bits = 1; ++ ++ /* The sBIT fields are reset to the values previously sent to ++ * png_set_shift according to the colour type. ++ * does. ++ */ ++ if (that->colour_type & 2) /* RGB channels */ ++ { ++ that->red_sBIT = data.red; ++ that->green_sBIT = data.green; ++ that->blue_sBIT = data.blue; ++ } ++ ++ else /* One grey channel */ ++ that->red_sBIT = that->green_sBIT = that->blue_sBIT = data.gray; ++ ++ that->alpha_sBIT = data.alpha; ++ } ++ ++ this->next->mod(this->next, that, pp, display); ++} ++ ++static int ++image_transform_png_set_shift_add(image_transform *this, ++ const image_transform **that, png_byte colour_type, png_byte bit_depth) ++{ ++ UNUSED(bit_depth) ++ ++ this->next = *that; ++ *that = this; ++ ++ return colour_type != PNG_COLOR_TYPE_PALETTE; ++} ++ ++IT(shift); ++#undef PT ++#define PT ITSTRUCT(shift) ++ ++#endif /* PNG_READ_SHIFT_SUPPORTED */ ++ ++#ifdef THIS_IS_THE_PROFORMA ++static void ++image_transform_png_set_@_set(const image_transform *this, ++ transform_display *that, png_structp pp, png_infop pi) ++{ ++ png_set_@(pp); ++ this->next->set(this->next, that, pp, pi); ++} ++ ++static void ++image_transform_png_set_@_mod(const image_transform *this, ++ image_pixel *that, png_const_structp pp, ++ const transform_display *display) ++{ ++ this->next->mod(this->next, that, pp, display); ++} ++ ++static int ++image_transform_png_set_@_add(image_transform *this, ++ const image_transform **that, png_byte colour_type, png_byte bit_depth) ++{ ++ this->next = *that; ++ *that = this; ++ ++ return 1; ++} ++ ++IT(@); ++#endif ++ ++ ++/* This may just be 'end' if all the transforms are disabled! */ ++static image_transform *const image_transform_first = &PT; ++ ++static void ++transform_enable(const char *name) + { + /* Everything starts out enabled, so if we see an 'enable' disabled + * everything else the first time round. +@@ -7418,7 +8546,7 @@ + + } + + static void +-transform_disable(PNG_CONST char *name) ++transform_disable(const char *name) + { + image_transform *list = image_transform_first; + +@@ -7481,7 +8609,7 @@ + + } + + static png_uint_32 +-image_transform_add(PNG_CONST image_transform **this, unsigned int max, ++image_transform_add(const image_transform **this, unsigned int max, + png_uint_32 counter, char *name, size_t sizeof_name, size_t *pos, + png_byte colour_type, png_byte bit_depth) + { +@@ -7558,83 +8686,6 @@ + + } + } + +-#ifdef THIS_IS_THE_PROFORMA +-static void +-image_transform_png_set_@_set(PNG_CONST image_transform *this, +- transform_display *that, png_structp pp, png_infop pi) +-{ +- png_set_@(pp); +- this->next->set(this->next, that, pp, pi); +-} +- +-static void +-image_transform_png_set_@_mod(PNG_CONST image_transform *this, +- image_pixel *that, png_const_structp pp, +- PNG_CONST transform_display *display) +-{ +- this->next->mod(this->next, that, pp, display); +-} +- +-static int +-image_transform_png_set_@_add(image_transform *this, +- PNG_CONST image_transform **that, char *name, size_t sizeof_name, +- size_t *pos, png_byte colour_type, png_byte bit_depth) +-{ +- this->next = *that; +- *that = this; +- +- *pos = safecat(name, sizeof_name, *pos, "" +@""); +- +- return 1; +-} +- +-IT(@); +-#endif +- +-/* png_set_quantize(png_structp, png_colorp palette, int num_palette, +- * int maximum_colors, png_const_uint_16p histogram, int full_quantize) +- * +- * Very difficult to validate this! +- */ +-/*NOTE: TBD NYI */ +- +-/* The data layout transforms are handled by swapping our own channel data, +- * necessarily these need to happen at the end of the transform list because the +- * semantic of the channels changes after these are executed. Some of these, +- * like set_shift and set_packing, can't be done at present because they change +- * the layout of the data at the sub-sample level so sample() won't get the +- * right answer. +- */ +-/* png_set_invert_alpha */ +-/*NOTE: TBD NYI */ +- +-/* png_set_bgr */ +-/*NOTE: TBD NYI */ +- +-/* png_set_swap_alpha */ +-/*NOTE: TBD NYI */ +- +-/* png_set_swap */ +-/*NOTE: TBD NYI */ +- +-/* png_set_filler, (png_structp png_ptr, png_uint_32 filler, int flags)); */ +-/*NOTE: TBD NYI */ +- +-/* png_set_add_alpha, (png_structp png_ptr, png_uint_32 filler, int flags)); */ +-/*NOTE: TBD NYI */ +- +-/* png_set_packing */ +-/*NOTE: TBD NYI */ +- +-/* png_set_packswap */ +-/*NOTE: TBD NYI */ +- +-/* png_set_invert_mono */ +-/*NOTE: TBD NYI */ +- +-/* png_set_shift(png_structp, png_const_color_8p true_bits) */ +-/*NOTE: TBD NYI */ +- + static void + perform_transform_test(png_modifier *pm) + { +@@ -7642,7 +8693,8 @@ + + png_byte bit_depth = 0; + unsigned int palette_number = 0; + +- while (next_format(&colour_type, &bit_depth, &palette_number, 0)) ++ while (next_format(&colour_type, &bit_depth, &palette_number, pm->test_lbg, ++ pm->test_tRNS)) + { + png_uint_32 counter = 0; + size_t base_pos; +@@ -7653,7 +8705,7 @@ + + for (;;) + { + size_t pos = base_pos; +- PNG_CONST image_transform *list = 0; ++ const image_transform *list = 0; + + /* 'max' is currently hardwired to '1'; this should be settable on the + * command line. +@@ -7714,11 +8766,11 @@ + + gamma_display_init(gamma_display *dp, png_modifier *pm, png_uint_32 id, + double file_gamma, double screen_gamma, png_byte sbit, int threshold_test, + int use_input_precision, int scale16, int expand16, +- int do_background, PNG_CONST png_color_16 *pointer_to_the_background_color, ++ int do_background, const png_color_16 *pointer_to_the_background_color, + double background_gamma) + { + /* Standard fields */ +- standard_display_init(&dp->this, &pm->this, id, 0/*do_interlace*/, ++ standard_display_init(&dp->this, &pm->this, id, do_read_interlace, + pm->use_update_info); + + /* Parameter fields */ +@@ -7750,7 +8802,7 @@ + + /* If requested strip 16 to 8 bits - this is handled automagically below + * because the output bit depth is read from the library. Note that there + * are interactions with sBIT but, internally, libpng makes sbit at most +- * PNG_MAX_GAMMA_8 when doing the following. ++ * PNG_MAX_GAMMA_8 prior to 1.7 when doing the following. + */ + if (dp->scale16) + # ifdef PNG_READ_SCALE_16_TO_8_SUPPORTED +@@ -7782,9 +8834,9 @@ + + * non-inverted, represenation. It provides a default for the PNG file + * gamma, but since the file has a gAMA chunk this does not matter. + */ +- PNG_CONST double sg = dp->screen_gamma; ++ const double sg = dp->screen_gamma; + # ifndef PNG_FLOATING_POINT_SUPPORTED +- PNG_CONST png_fixed_point g = fix(sg); ++ const png_fixed_point g = fix(sg); + # endif + + # ifdef PNG_FLOATING_POINT_SUPPORTED +@@ -7830,9 +8882,9 @@ + + # ifdef PNG_READ_BACKGROUND_SUPPORTED + /* NOTE: this assumes the caller provided the correct background gamma! + */ +- PNG_CONST double bg = dp->background_gamma; ++ const double bg = dp->background_gamma; + # ifndef PNG_FLOATING_POINT_SUPPORTED +- PNG_CONST png_fixed_point g = fix(bg); ++ const png_fixed_point g = fix(bg); + # endif + + # ifdef PNG_FLOATING_POINT_SUPPORTED +@@ -7906,7 +8958,7 @@ + + init_validate_info(validate_info *vi, gamma_display *dp, png_const_structp pp, + int in_depth, int out_depth) + { +- PNG_CONST unsigned int outmax = (1U<pp = pp; + vi->dp = dp; +@@ -7945,13 +8997,15 @@ + + vi->outlog = outlog(dp->pm, in_depth, out_depth); + + if ((dp->this.colour_type & PNG_COLOR_MASK_ALPHA) != 0 || +- (dp->this.colour_type == 3 && dp->this.is_transparent)) ++ (dp->this.colour_type == 3 && dp->this.is_transparent) || ++ ((dp->this.colour_type == 0 || dp->this.colour_type == 2) && ++ dp->this.has_tRNS)) + { + vi->do_background = dp->do_background; + + if (vi->do_background != 0) + { +- PNG_CONST double bg_inverse = 1/dp->background_gamma; ++ const double bg_inverse = 1/dp->background_gamma; + double r, g, b; + + /* Caller must at least put the gray value into the red channel */ +@@ -7975,7 +9029,7 @@ + + vi->background_blue = b; + } + } +- else ++ else /* Do not expect any background processing */ + vi->do_background = 0; + + if (vi->do_background == 0) +@@ -8065,15 +9119,15 @@ + + + /* This API returns the encoded *input* component, in the range 0..1 */ + static double +-gamma_component_validate(PNG_CONST char *name, PNG_CONST validate_info *vi, +- PNG_CONST unsigned int id, PNG_CONST unsigned int od, +- PNG_CONST double alpha /* <0 for the alpha channel itself */, +- PNG_CONST double background /* component background value */) ++gamma_component_validate(const char *name, const validate_info *vi, ++ const unsigned int id, const unsigned int od, ++ const double alpha /* <0 for the alpha channel itself */, ++ const double background /* component background value */) + { +- PNG_CONST unsigned int isbit = id >> vi->isbit_shift; +- PNG_CONST unsigned int sbit_max = vi->sbit_max; +- PNG_CONST unsigned int outmax = vi->outmax; +- PNG_CONST int do_background = vi->do_background; ++ const unsigned int isbit = id >> vi->isbit_shift; ++ const unsigned int sbit_max = vi->sbit_max; ++ const unsigned int outmax = vi->outmax; ++ const int do_background = vi->do_background; + + double i; + +@@ -8638,14 +9692,14 @@ + + png_infop pi) + { + /* Get some constants derived from the input and output file formats: */ +- PNG_CONST png_store* PNG_CONST ps = dp->this.ps; +- PNG_CONST png_byte in_ct = dp->this.colour_type; +- PNG_CONST png_byte in_bd = dp->this.bit_depth; +- PNG_CONST png_uint_32 w = dp->this.w; +- PNG_CONST png_uint_32 h = dp->this.h; +- PNG_CONST size_t cbRow = dp->this.cbRow; +- PNG_CONST png_byte out_ct = png_get_color_type(pp, pi); +- PNG_CONST png_byte out_bd = png_get_bit_depth(pp, pi); ++ const png_store* const ps = dp->this.ps; ++ const png_byte in_ct = dp->this.colour_type; ++ const png_byte in_bd = dp->this.bit_depth; ++ const png_uint_32 w = dp->this.w; ++ const png_uint_32 h = dp->this.h; ++ const size_t cbRow = dp->this.cbRow; ++ const png_byte out_ct = png_get_color_type(pp, pi); ++ const png_byte out_bd = png_get_bit_depth(pp, pi); + + /* There are three sources of error, firstly the quantization in the + * file encoding, determined by sbit and/or the file depth, secondly +@@ -8686,11 +9740,12 @@ + + * The basic tests below do not do this, however if 'use_input_precision' + * is set a subsequent test is performed above. + */ +- PNG_CONST unsigned int samples_per_pixel = (out_ct & 2U) ? 3U : 1U; ++ const unsigned int samples_per_pixel = (out_ct & 2U) ? 3U : 1U; + int processing; + png_uint_32 y; +- PNG_CONST store_palette_entry *in_palette = dp->this.palette; +- PNG_CONST int in_is_transparent = dp->this.is_transparent; ++ const store_palette_entry *in_palette = dp->this.palette; ++ const int in_is_transparent = dp->this.is_transparent; ++ int process_tRNS; + int out_npalette = -1; + int out_is_transparent = 0; /* Just refers to the palette case */ + store_palette out_palette; +@@ -8706,6 +9761,7 @@ + + + processing = (vi.gamma_correction > 0 && !dp->threshold_test) + || in_bd != out_bd || in_ct != out_ct || vi.do_background; ++ process_tRNS = dp->this.has_tRNS && vi.do_background; + + /* TODO: FIX THIS: MAJOR BUG! If the transformations all happen inside + * the palette there is no way of finding out, because libpng fails to +@@ -8736,20 +9792,20 @@ + + double alpha = 1; /* serves as a flag value */ + + /* Record the palette index for index images. */ +- PNG_CONST unsigned int in_index = +- in_ct == 3 ? sample(std, 3, in_bd, x, 0) : 256; +- PNG_CONST unsigned int out_index = +- out_ct == 3 ? sample(std, 3, out_bd, x, 0) : 256; ++ const unsigned int in_index = ++ in_ct == 3 ? sample(std, 3, in_bd, x, 0, 0, 0) : 256; ++ const unsigned int out_index = ++ out_ct == 3 ? sample(std, 3, out_bd, x, 0, 0, 0) : 256; + + /* Handle input alpha - png_set_background will cause the output + * alpha to disappear so there is nothing to check. + */ +- if ((in_ct & PNG_COLOR_MASK_ALPHA) != 0 || (in_ct == 3 && +- in_is_transparent)) ++ if ((in_ct & PNG_COLOR_MASK_ALPHA) != 0 || ++ (in_ct == 3 && in_is_transparent)) + { +- PNG_CONST unsigned int input_alpha = in_ct == 3 ? ++ const unsigned int input_alpha = in_ct == 3 ? + dp->this.palette[in_index].alpha : +- sample(std, in_ct, in_bd, x, samples_per_pixel); ++ sample(std, in_ct, in_bd, x, samples_per_pixel, 0, 0); + + unsigned int output_alpha = 65536 /* as a flag value */; + +@@ -8761,7 +9817,7 @@ + + + else if ((out_ct & PNG_COLOR_MASK_ALPHA) != 0) + output_alpha = sample(pRow, out_ct, out_bd, x, +- samples_per_pixel); ++ samples_per_pixel, 0, 0); + + if (output_alpha != 65536) + alpha = gamma_component_validate(""alpha"", &vi, input_alpha, +@@ -8777,33 +9833,62 @@ + + } + } + ++ else if (process_tRNS) ++ { ++ /* alpha needs to be set appropriately for this pixel, it is ++ * currently 1 and needs to be 0 for an input pixel which matches ++ * the values in tRNS. ++ */ ++ switch (in_ct) ++ { ++ case 0: /* gray */ ++ if (sample(std, in_ct, in_bd, x, 0, 0, 0) == ++ dp->this.transparent.red) ++ alpha = 0; ++ break; ++ ++ case 2: /* RGB */ ++ if (sample(std, in_ct, in_bd, x, 0, 0, 0) == ++ dp->this.transparent.red && ++ sample(std, in_ct, in_bd, x, 1, 0, 0) == ++ dp->this.transparent.green && ++ sample(std, in_ct, in_bd, x, 2, 0, 0) == ++ dp->this.transparent.blue) ++ alpha = 0; ++ break; ++ ++ default: ++ break; ++ } ++ } ++ + /* Handle grayscale or RGB components. */ + if ((in_ct & PNG_COLOR_MASK_COLOR) == 0) /* grayscale */ + (void)gamma_component_validate(""gray"", &vi, +- sample(std, in_ct, in_bd, x, 0), +- sample(pRow, out_ct, out_bd, x, 0), alpha/*component*/, +- vi.background_red); ++ sample(std, in_ct, in_bd, x, 0, 0, 0), ++ sample(pRow, out_ct, out_bd, x, 0, 0, 0), ++ alpha/*component*/, vi.background_red); + else /* RGB or palette */ + { + (void)gamma_component_validate(""red"", &vi, + in_ct == 3 ? in_palette[in_index].red : +- sample(std, in_ct, in_bd, x, 0), ++ sample(std, in_ct, in_bd, x, 0, 0, 0), + out_ct == 3 ? out_palette[out_index].red : +- sample(pRow, out_ct, out_bd, x, 0), ++ sample(pRow, out_ct, out_bd, x, 0, 0, 0), + alpha/*component*/, vi.background_red); + + (void)gamma_component_validate(""green"", &vi, + in_ct == 3 ? in_palette[in_index].green : +- sample(std, in_ct, in_bd, x, 1), ++ sample(std, in_ct, in_bd, x, 1, 0, 0), + out_ct == 3 ? out_palette[out_index].green : +- sample(pRow, out_ct, out_bd, x, 1), ++ sample(pRow, out_ct, out_bd, x, 1, 0, 0), + alpha/*component*/, vi.background_green); + + (void)gamma_component_validate(""blue"", &vi, + in_ct == 3 ? in_palette[in_index].blue : +- sample(std, in_ct, in_bd, x, 2), ++ sample(std, in_ct, in_bd, x, 2, 0, 0), + out_ct == 3 ? out_palette[out_index].blue : +- sample(pRow, out_ct, out_bd, x, 2), ++ sample(pRow, out_ct, out_bd, x, 2, 0, 0), + alpha/*component*/, vi.background_blue); + } + } +@@ -8843,15 +9928,15 @@ + + * maxpc: maximum percentage error (as a percentage) + */ + static void +-gamma_test(png_modifier *pmIn, PNG_CONST png_byte colour_typeIn, +- PNG_CONST png_byte bit_depthIn, PNG_CONST int palette_numberIn, +- PNG_CONST int interlace_typeIn, +- PNG_CONST double file_gammaIn, PNG_CONST double screen_gammaIn, +- PNG_CONST png_byte sbitIn, PNG_CONST int threshold_testIn, +- PNG_CONST char *name, +- PNG_CONST int use_input_precisionIn, PNG_CONST int scale16In, +- PNG_CONST int expand16In, PNG_CONST int do_backgroundIn, +- PNG_CONST png_color_16 *bkgd_colorIn, double bkgd_gammaIn) ++gamma_test(png_modifier *pmIn, const png_byte colour_typeIn, ++ const png_byte bit_depthIn, const int palette_numberIn, ++ const int interlace_typeIn, ++ const double file_gammaIn, const double screen_gammaIn, ++ const png_byte sbitIn, const int threshold_testIn, ++ const char *name, ++ const int use_input_precisionIn, const int scale16In, ++ const int expand16In, const int do_backgroundIn, ++ const png_color_16 *bkgd_colorIn, double bkgd_gammaIn) + { + gamma_display d; + context(&pmIn->this, fault); +@@ -8886,7 +9971,7 @@ + + + modification_reset(d.pm->modifications); + +- /* Get a png_struct for writing the image. */ ++ /* Get a png_struct for reading the image. */ + pp = set_modifier_for_read(d.pm, &pi, d.this.id, name); + standard_palette_init(&d.this); + +@@ -9025,9 +10110,13 @@ + + /* Don't test more than one instance of each palette - it's pointless, in + * fact this test is somewhat excessive since libpng doesn't make this + * decision based on colour type or bit depth! ++ * ++ * CHANGED: now test two palettes and, as a side effect, images with and ++ * without tRNS. + */ +- while (next_format(&colour_type, &bit_depth, &palette_number, 1/*gamma*/)) +- if (palette_number == 0) ++ while (next_format(&colour_type, &bit_depth, &palette_number, ++ pm->test_lbg_gamma_threshold, pm->test_tRNS)) ++ if (palette_number < 2) + { + double test_gamma = 1.0; + while (test_gamma >= .4) +@@ -9050,11 +10139,11 @@ + + } + + static void gamma_transform_test(png_modifier *pm, +- PNG_CONST png_byte colour_type, PNG_CONST png_byte bit_depth, +- PNG_CONST int palette_number, +- PNG_CONST int interlace_type, PNG_CONST double file_gamma, +- PNG_CONST double screen_gamma, PNG_CONST png_byte sbit, +- PNG_CONST int use_input_precision, PNG_CONST int scale16) ++ const png_byte colour_type, const png_byte bit_depth, ++ const int palette_number, ++ const int interlace_type, const double file_gamma, ++ const double screen_gamma, const png_byte sbit, ++ const int use_input_precision, const int scale16) + { + size_t pos = 0; + char name[64]; +@@ -9087,7 +10176,8 @@ + + png_byte bit_depth = 0; + unsigned int palette_number = 0; + +- while (next_format(&colour_type, &bit_depth, &palette_number, 1/*gamma*/)) ++ while (next_format(&colour_type, &bit_depth, &palette_number, ++ pm->test_lbg_gamma_transform, pm->test_tRNS)) + { + unsigned int i, j; + +@@ -9117,7 +10207,8 @@ + + png_byte colour_type = 0, bit_depth = 0; + unsigned int npalette = 0; + +- while (next_format(&colour_type, &bit_depth, &npalette, 1/*gamma*/)) ++ while (next_format(&colour_type, &bit_depth, &npalette, ++ pm->test_lbg_gamma_sbit, pm->test_tRNS)) + if ((colour_type & PNG_COLOR_MASK_ALPHA) == 0 && + ((colour_type == 3 && sbit < 8) || + (colour_type != 3 && sbit < bit_depth))) +@@ -9152,7 +10243,11 @@ + + # ifndef PNG_MAX_GAMMA_8 + # define PNG_MAX_GAMMA_8 11 + # endif +-# define SBIT_16_TO_8 PNG_MAX_GAMMA_8 ++# if defined PNG_MAX_GAMMA_8 || PNG_LIBPNG_VER < 10700 ++# define SBIT_16_TO_8 PNG_MAX_GAMMA_8 ++# else ++# define SBIT_16_TO_8 16 ++# endif + /* Include the alpha cases here. Note that sbit matches the internal value + * used by the library - otherwise we will get spurious errors from the + * internal sbit style approximation. +@@ -9205,12 +10300,12 @@ + + #if defined(PNG_READ_BACKGROUND_SUPPORTED) ||\ + defined(PNG_READ_ALPHA_MODE_SUPPORTED) + static void gamma_composition_test(png_modifier *pm, +- PNG_CONST png_byte colour_type, PNG_CONST png_byte bit_depth, +- PNG_CONST int palette_number, +- PNG_CONST int interlace_type, PNG_CONST double file_gamma, +- PNG_CONST double screen_gamma, +- PNG_CONST int use_input_precision, PNG_CONST int do_background, +- PNG_CONST int expand_16) ++ const png_byte colour_type, const png_byte bit_depth, ++ const int palette_number, ++ const int interlace_type, const double file_gamma, ++ const double screen_gamma, ++ const int use_input_precision, const int do_background, ++ const int expand_16) + { + size_t pos = 0; + png_const_charp base; +@@ -9308,8 +10403,17 @@ + + } + + background.index = 193; /* rgb(193,193,193) to detect errors */ ++ + if (!(colour_type & PNG_COLOR_MASK_COLOR)) + { ++ /* Because, currently, png_set_background is always called with ++ * 'need_expand' false in this case and because the gamma test itself ++ * doesn't cause an expand to 8-bit for lower bit depths the colour must ++ * be reduced to the correct range. ++ */ ++ if (bit_depth < 8) ++ background.gray &= (png_uint_16)((1U << bit_depth)-1); ++ + /* Grayscale input, we do not convert to RGB (TBD), so we must set the + * background to gray - else libpng seems to fail. + */ +@@ -9358,9 +10462,18 @@ + + + /* Skip the non-alpha cases - there is no setting of a transparency colour at + * present. ++ * ++ * TODO: incorrect; the palette case sets tRNS and, now RGB and gray do, ++ * however the palette case fails miserably so is commented out below. + */ +- while (next_format(&colour_type, &bit_depth, &palette_number, 1/*gamma*/)) +- if ((colour_type & PNG_COLOR_MASK_ALPHA) != 0) ++ while (next_format(&colour_type, &bit_depth, &palette_number, ++ pm->test_lbg_gamma_composition, pm->test_tRNS)) ++ if ((colour_type & PNG_COLOR_MASK_ALPHA) != 0 ++#if 0 /* TODO: FIXME */ ++ /*TODO: FIXME: this should work */ ++ || colour_type == 3 ++#endif ++ || (colour_type != 3 && palette_number != 0)) + { + unsigned int i, j; + +@@ -9579,7 +10692,7 @@ + + * be indexed adam7[y][x] and notice that the pass numbers are based at + * 1, not 0 - the base libpng uses. + */ +-static PNG_CONST ++static const + png_byte adam7[8][8] = + { + { 1,6,4,6,2,6,4,6 }, +@@ -9930,7 +11043,7 @@ + + * The png_modifier code assumes that encodings[0] is sRGB and treats it + * specially: do not change the first entry in this list! + */ +-static PNG_CONST color_encoding test_encodings[] = ++static const color_encoding test_encodings[] = + { + /* sRGB: must be first in this list! */ + /*gamma:*/ { 1/2.2, +@@ -9952,6 +11065,11 @@ + + /*red: */ { 0.716500716779386, 0.258728243040113, 0.000000000000000 }, + /*green:*/ { 0.101020574397477, 0.724682314948566, 0.051211818965388 }, + /*blue: */ { 0.146774385252705, 0.016589442011321, 0.773892783545073} }, ++/* Fake encoding which selects just the green channel */ ++/*gamma:*/ { 1.45/2.2, /* the 'Mac' gamma */ ++/*red: */ { 0.716500716779386, 0.000000000000000, 0.000000000000000 }, ++/*green:*/ { 0.101020574397477, 1.000000000000000, 0.051211818965388 }, ++/*blue: */ { 0.146774385252705, 0.000000000000000, 0.773892783545073} }, + }; + + /* signal handler +@@ -10023,11 +11141,11 @@ + + /* main program */ + int main(int argc, char **argv) + { +- volatile int summary = 1; /* Print the error summary at the end */ +- volatile int memstats = 0; /* Print memory statistics at the end */ ++ int summary = 1; /* Print the error summary at the end */ ++ int memstats = 0; /* Print memory statistics at the end */ + + /* Create the given output file on success: */ +- PNG_CONST char *volatile touch = NULL; ++ const char *touch = NULL; + + /* This is an array of standard gamma values (believe it or not I've seen + * every one of these mentioned somewhere.) +@@ -10043,6 +11161,10 @@ + + + anon_context(&pm.this); + ++ gnu_volatile(summary) ++ gnu_volatile(memstats) ++ gnu_volatile(touch) ++ + /* Add appropriate signal handlers, just the ANSI specified ones: */ + signal(SIGABRT, signal_handler); + signal(SIGFPE, signal_handler); +@@ -10089,14 +11211,30 @@ + + + /* Store the test gammas */ + pm.gammas = gammas; +- pm.ngammas = (sizeof gammas) / (sizeof gammas[0]); ++ pm.ngammas = ARRAY_SIZE(gammas); + pm.ngamma_tests = 0; /* default to off */ + ++ /* Low bit depth gray images don't do well in the gamma tests, until ++ * this is fixed turn them off for some gamma cases: ++ */ ++# ifdef PNG_WRITE_tRNS_SUPPORTED ++ pm.test_tRNS = 1; ++# endif ++ pm.test_lbg = PNG_LIBPNG_VER >= 10600; ++ pm.test_lbg_gamma_threshold = 1; ++ pm.test_lbg_gamma_transform = PNG_LIBPNG_VER >= 10600; ++ pm.test_lbg_gamma_sbit = 1; ++ pm.test_lbg_gamma_composition = PNG_LIBPNG_VER >= 10700; ++ + /* And the test encodings */ + pm.encodings = test_encodings; +- pm.nencodings = (sizeof test_encodings) / (sizeof test_encodings[0]); ++ pm.nencodings = ARRAY_SIZE(test_encodings); + +- pm.sbitlow = 8U; /* because libpng doesn't do sBIT below 8! */ ++# if PNG_LIBPNG_VER < 10700 ++ pm.sbitlow = 8U; /* because libpng doesn't do sBIT below 8! */ ++# else ++ pm.sbitlow = 1U; ++# endif + + /* The following allows results to pass if they correspond to anything in the + * transformed range [input-.5,input+.5]; this is is required because of the +@@ -10122,7 +11260,11 @@ + + pm.maxout16 = .499; /* Error in *encoded* value */ + pm.maxabs16 = .00005;/* 1/20000 */ + pm.maxcalc16 =1./65535;/* +/-1 in 16 bits for compose errors */ +- pm.maxcalcG = 1./((1<s3->tmp.new_cipher->algorithm_mkey; + alg_a = s->s3->tmp.new_cipher->algorithm_auth; + + /* we don't have a certificate */ + if ((alg_a & (SSL_aDH | SSL_aNULL | SSL_aKRB5)) || (alg_k & SSL_kPSK)) + return (1); + + sc = s->session->sess_cert; + if (sc == NULL) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR); + goto err; + } +#ifndef OPENSSL_NO_RSA + rsa = s->session->sess_cert->peer_rsa_tmp; +#endif +#ifndef OPENSSL_NO_DH + dh = s->session->sess_cert->peer_dh_tmp; +#endif + + /* This is the passed certificate */ + + idx = sc->peer_cert_type; +#ifndef OPENSSL_NO_ECDH + if (idx == SSL_PKEY_ECC) { + if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509, s) == 0) { + /* check failed */ + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_BAD_ECC_CERT); + goto f_err; + } else { + return 1; + } + } +#endif + pkey = X509_get_pubkey(sc->peer_pkeys[idx].x509); + pkey_bits = EVP_PKEY_bits(pkey); + i = X509_certificate_type(sc->peer_pkeys[idx].x509, pkey); + EVP_PKEY_free(pkey); + + /* Check that we have a certificate if we require one */ + if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA | EVP_PKT_SIGN)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_RSA_SIGNING_CERT); + goto f_err; + } +#ifndef OPENSSL_NO_DSA + else if ((alg_a & SSL_aDSS) && !has_bits(i, EVP_PK_DSA | EVP_PKT_SIGN)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_DSA_SIGNING_CERT); + goto f_err; + } +#endif +#ifndef OPENSSL_NO_RSA + if (alg_k & SSL_kRSA) { + if (!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && + !has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_RSA_ENCRYPTING_CERT); + goto f_err; + } else if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)) { + if (pkey_bits <= SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) { + if (!has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_RSA_ENCRYPTING_CERT); + goto f_err; + } + if (rsa != NULL) { + /* server key exchange is not allowed. */ + al = SSL_AD_INTERNAL_ERROR; + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR); + goto f_err; + } + } + } + } +#endif +#ifndef OPENSSL_NO_DH + if ((alg_k & SSL_kEDH) && dh == NULL) { + al = SSL_AD_INTERNAL_ERROR; + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR); + goto f_err; + } + if ((alg_k & SSL_kDHr) && !has_bits(i, EVP_PK_DH | EVP_PKS_RSA)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_DH_RSA_CERT); + goto f_err; + } +# ifndef OPENSSL_NO_DSA + if ((alg_k & SSL_kDHd) && !has_bits(i, EVP_PK_DH | EVP_PKS_DSA)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_DH_DSA_CERT); + goto f_err; + } +# endif + + /* Check DHE only: static DH not implemented. */ + if (alg_k & SSL_kEDH) { + int dh_size = BN_num_bits(dh->p); + if ((!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && dh_size < 1024) + || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && dh_size < 512)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_DH_KEY_TOO_SMALL); + goto f_err; + } + } +#endif /* !OPENSSL_NO_DH */ + + if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && + pkey_bits > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) { +#ifndef OPENSSL_NO_RSA + if (alg_k & SSL_kRSA) { + if (rsa == NULL) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_EXPORT_TMP_RSA_KEY); + goto f_err; + } else if (BN_num_bits(rsa->n) > + SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) { + /* We have a temporary RSA key but it's too large. */ + al = SSL_AD_EXPORT_RESTRICTION; + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_EXPORT_TMP_RSA_KEY); + goto f_err; + } + } else +#endif +#ifndef OPENSSL_NO_DH + if (alg_k & SSL_kEDH) { + if (BN_num_bits(dh->p) > + SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) { + /* We have a temporary DH key but it's too large. */ + al = SSL_AD_EXPORT_RESTRICTION; + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_EXPORT_TMP_DH_KEY); + goto f_err; + } + } else if (alg_k & (SSL_kDHr | SSL_kDHd)) { + /* The cert should have had an export DH key. */ + al = SSL_AD_EXPORT_RESTRICTION; + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_EXPORT_TMP_DH_KEY); + goto f_err; + } else +#endif + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE); + goto f_err; + } + } + return (1); + f_err: + ssl3_send_alert(s, SSL3_AL_FATAL, al); + err: + return (0); +} +",0,"int ssl3_check_cert_and_algorithm(SSL *s) +{ + int i, idx; + long alg_k, alg_a; + EVP_PKEY *pkey = NULL; + int pkey_bits; + SESS_CERT *sc; +#ifndef OPENSSL_NO_RSA + RSA *rsa; +#endif +#ifndef OPENSSL_NO_DH + DH *dh; +#endif + int al = SSL_AD_HANDSHAKE_FAILURE; + + alg_k = s->s3->tmp.new_cipher->algorithm_mkey; + alg_a = s->s3->tmp.new_cipher->algorithm_auth; + + /* we don't have a certificate */ + if ((alg_a & (SSL_aDH | SSL_aNULL | SSL_aKRB5)) || (alg_k & SSL_kPSK)) + return (1); + + sc = s->session->sess_cert; + if (sc == NULL) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR); + goto err; + } +#ifndef OPENSSL_NO_RSA + rsa = s->session->sess_cert->peer_rsa_tmp; +#endif +#ifndef OPENSSL_NO_DH + dh = s->session->sess_cert->peer_dh_tmp; +#endif + + /* This is the passed certificate */ + + idx = sc->peer_cert_type; +#ifndef OPENSSL_NO_ECDH + if (idx == SSL_PKEY_ECC) { + if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509, s) == 0) { + /* check failed */ + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_BAD_ECC_CERT); + goto f_err; + } else { + return 1; + } + } +#endif + pkey = X509_get_pubkey(sc->peer_pkeys[idx].x509); + pkey_bits = EVP_PKEY_bits(pkey); + i = X509_certificate_type(sc->peer_pkeys[idx].x509, pkey); + EVP_PKEY_free(pkey); + + /* Check that we have a certificate if we require one */ + if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA | EVP_PKT_SIGN)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_RSA_SIGNING_CERT); + goto f_err; + } +#ifndef OPENSSL_NO_DSA + else if ((alg_a & SSL_aDSS) && !has_bits(i, EVP_PK_DSA | EVP_PKT_SIGN)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_DSA_SIGNING_CERT); + goto f_err; + } +#endif +#ifndef OPENSSL_NO_RSA + if (alg_k & SSL_kRSA) { + if (!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && + !has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_RSA_ENCRYPTING_CERT); + goto f_err; + } else if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)) { + if (pkey_bits <= SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) { + if (!has_bits(i, EVP_PK_RSA | EVP_PKT_ENC)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_RSA_ENCRYPTING_CERT); + goto f_err; + } + if (rsa != NULL) { + /* server key exchange is not allowed. */ + al = SSL_AD_INTERNAL_ERROR; + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR); + goto f_err; + } + } + } + } +#endif +#ifndef OPENSSL_NO_DH + if ((alg_k & SSL_kEDH) && dh == NULL) { + al = SSL_AD_INTERNAL_ERROR; + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR); + goto f_err; + } + if ((alg_k & SSL_kDHr) && !has_bits(i, EVP_PK_DH | EVP_PKS_RSA)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_DH_RSA_CERT); + goto f_err; + } +# ifndef OPENSSL_NO_DSA + if ((alg_k & SSL_kDHd) && !has_bits(i, EVP_PK_DH | EVP_PKS_DSA)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_DH_DSA_CERT); + goto f_err; + } +# endif + + /* Check DHE only: static DH not implemented. */ + if (alg_k & SSL_kEDH) { + int dh_size = BN_num_bits(dh->p); + if ((!SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && dh_size < 1024) + || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && dh_size < 512)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_DH_KEY_TOO_SMALL); + goto f_err; + } + } +#endif /* !OPENSSL_NO_DH */ + + if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && + pkey_bits > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) { +#ifndef OPENSSL_NO_RSA + if (alg_k & SSL_kRSA) { + if (rsa == NULL) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_EXPORT_TMP_RSA_KEY); + goto f_err; + } else if (BN_num_bits(rsa->n) > + SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) { + /* We have a temporary RSA key but it's too large. */ + al = SSL_AD_EXPORT_RESTRICTION; + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_EXPORT_TMP_RSA_KEY); + goto f_err; + } + } else +#endif +#ifndef OPENSSL_NO_DH + if (alg_k & SSL_kEDH) { + if (BN_num_bits(dh->p) > + SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) { + /* We have a temporary DH key but it's too large. */ + al = SSL_AD_EXPORT_RESTRICTION; + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_EXPORT_TMP_DH_KEY); + goto f_err; + } + } else if (alg_k & (SSL_kDHr | SSL_kDHd)) { + /* The cert should have had an export DH key. */ + al = SSL_AD_EXPORT_RESTRICTION; + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_EXPORT_TMP_DH_KEY); + goto f_err; + } else +#endif + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE); + goto f_err; + } + } + return (1); + f_err: + ssl3_send_alert(s, SSL3_AL_FATAL, al); + err: + return (0); +} +","@@ -1143,6 +1143,12 @@ int ssl3_get_server_certificate(SSL *s) + goto f_err; + } + for (nc = 0; nc < llen;) { ++ if (nc + 3 > llen) { ++ al = SSL_AD_DECODE_ERROR; ++ SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, ++ SSL_R_CERT_LENGTH_MISMATCH); ++ goto f_err; ++ } + n2l3(p, l); + if ((l + nc + 3) > llen) { + al = SSL_AD_DECODE_ERROR; +@@ -2072,6 +2078,11 @@ int ssl3_get_certificate_request(SSL *s) + } + + for (nc = 0; nc < llen;) { ++ if (nc + 2 > llen) { ++ ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR); ++ SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_CA_DN_TOO_LONG); ++ goto err; ++ } + n2s(p, l); + if ((l + nc + 2) > llen) { + if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG))",1535,1866,2048 +18140,"IPV6DefragDoSturgesNovakTest(int policy, u_char *expected, size_t expected_len) +{ + int i; + int ret = 0; + + DefragInit(); + + /* + * Build the packets. + */ + + int id = 1; + Packet *packets[17]; + memset(packets, 0x00, sizeof(packets)); + + /* + * Original fragments. + */ + + /* A*24 at 0. */ + packets[0] = IPV6BuildTestPacket(id, 0, 1, 'A', 24); + + /* B*15 at 32. */ + packets[1] = IPV6BuildTestPacket(id, 32 >> 3, 1, 'B', 16); + + /* C*24 at 48. */ + packets[2] = IPV6BuildTestPacket(id, 48 >> 3, 1, 'C', 24); + + /* D*8 at 80. */ + packets[3] = IPV6BuildTestPacket(id, 80 >> 3, 1, 'D', 8); + + /* E*16 at 104. */ + packets[4] = IPV6BuildTestPacket(id, 104 >> 3, 1, 'E', 16); + + /* F*24 at 120. */ + packets[5] = IPV6BuildTestPacket(id, 120 >> 3, 1, 'F', 24); + + /* G*16 at 144. */ + packets[6] = IPV6BuildTestPacket(id, 144 >> 3, 1, 'G', 16); + + /* H*16 at 160. */ + packets[7] = IPV6BuildTestPacket(id, 160 >> 3, 1, 'H', 16); + + /* I*8 at 176. */ + packets[8] = IPV6BuildTestPacket(id, 176 >> 3, 1, 'I', 8); + + /* + * Overlapping subsequent fragments. + */ + + /* J*32 at 8. */ + packets[9] = IPV6BuildTestPacket(id, 8 >> 3, 1, 'J', 32); + + /* K*24 at 48. */ + packets[10] = IPV6BuildTestPacket(id, 48 >> 3, 1, 'K', 24); + + /* L*24 at 72. */ + packets[11] = IPV6BuildTestPacket(id, 72 >> 3, 1, 'L', 24); + + /* M*24 at 96. */ + packets[12] = IPV6BuildTestPacket(id, 96 >> 3, 1, 'M', 24); + + /* N*8 at 128. */ + packets[13] = IPV6BuildTestPacket(id, 128 >> 3, 1, 'N', 8); + + /* O*8 at 152. */ + packets[14] = IPV6BuildTestPacket(id, 152 >> 3, 1, 'O', 8); + + /* P*8 at 160. */ + packets[15] = IPV6BuildTestPacket(id, 160 >> 3, 1, 'P', 8); + + /* Q*16 at 176. */ + packets[16] = IPV6BuildTestPacket(id, 176 >> 3, 0, 'Q', 16); + + default_policy = policy; + + /* Send all but the last. */ + for (i = 0; i < 9; i++) { + Packet *tp = Defrag(NULL, NULL, packets[i], NULL); + if (tp != NULL) { + SCFree(tp); + goto end; + } + if (ENGINE_ISSET_EVENT(packets[i], IPV6_FRAG_OVERLAP)) { + goto end; + } + } + int overlap = 0; + for (; i < 16; i++) { + Packet *tp = Defrag(NULL, NULL, packets[i], NULL); + if (tp != NULL) { + SCFree(tp); + goto end; + } + if (ENGINE_ISSET_EVENT(packets[i], IPV6_FRAG_OVERLAP)) { + overlap++; + } + } + if (!overlap) + goto end; + + /* And now the last one. */ + Packet *reassembled = Defrag(NULL, NULL, packets[16], NULL); + if (reassembled == NULL) + goto end; + if (memcmp(GET_PKT_DATA(reassembled) + 40, expected, expected_len) != 0) + goto end; + + if (IPV6_GET_PLEN(reassembled) != 192) + goto end; + + SCFree(reassembled); + + /* Make sure all frags were returned to the pool. */ + if (defrag_context->frag_pool->outstanding != 0) { + printf(""defrag_context->frag_pool->outstanding %u: "", defrag_context->frag_pool->outstanding); + goto end; + } + + ret = 1; + +end: + for (i = 0; i < 17; i++) { + SCFree(packets[i]); + } + DefragDestroy(); + return ret; +} +",1,"IPV6DefragDoSturgesNovakTest(int policy, u_char *expected, size_t expected_len) +{ + int i; + int ret = 0; + + DefragInit(); + + /* + * Build the packets. + */ + + int id = 1; + Packet *packets[17]; + memset(packets, 0x00, sizeof(packets)); + + /* + * Original fragments. + */ + + /* A*24 at 0. */ + packets[0] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 0, 1, 'A', 24); + + /* B*15 at 32. */ + packets[1] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 32 >> 3, 1, 'B', 16); + + /* C*24 at 48. */ + packets[2] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 48 >> 3, 1, 'C', 24); + + /* D*8 at 80. */ + packets[3] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 80 >> 3, 1, 'D', 8); + + /* E*16 at 104. */ + packets[4] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 104 >> 3, 1, 'E', 16); + + /* F*24 at 120. */ + packets[5] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 120 >> 3, 1, 'F', 24); + + /* G*16 at 144. */ + packets[6] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 144 >> 3, 1, 'G', 16); + + /* H*16 at 160. */ + packets[7] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 160 >> 3, 1, 'H', 16); + + /* I*8 at 176. */ + packets[8] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 176 >> 3, 1, 'I', 8); + + /* + * Overlapping subsequent fragments. + */ + + /* J*32 at 8. */ + packets[9] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 8 >> 3, 1, 'J', 32); + + /* K*24 at 48. */ + packets[10] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 48 >> 3, 1, 'K', 24); + + /* L*24 at 72. */ + packets[11] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 72 >> 3, 1, 'L', 24); + + /* M*24 at 96. */ + packets[12] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 96 >> 3, 1, 'M', 24); + + /* N*8 at 128. */ + packets[13] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 128 >> 3, 1, 'N', 8); + + /* O*8 at 152. */ + packets[14] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 152 >> 3, 1, 'O', 8); + + /* P*8 at 160. */ + packets[15] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 160 >> 3, 1, 'P', 8); + + /* Q*16 at 176. */ + packets[16] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 176 >> 3, 0, 'Q', 16); + + default_policy = policy; + + /* Send all but the last. */ + for (i = 0; i < 9; i++) { + Packet *tp = Defrag(NULL, NULL, packets[i], NULL); + if (tp != NULL) { + SCFree(tp); + goto end; + } + if (ENGINE_ISSET_EVENT(packets[i], IPV6_FRAG_OVERLAP)) { + goto end; + } + } + int overlap = 0; + for (; i < 16; i++) { + Packet *tp = Defrag(NULL, NULL, packets[i], NULL); + if (tp != NULL) { + SCFree(tp); + goto end; + } + if (ENGINE_ISSET_EVENT(packets[i], IPV6_FRAG_OVERLAP)) { + overlap++; + } + } + if (!overlap) + goto end; + + /* And now the last one. */ + Packet *reassembled = Defrag(NULL, NULL, packets[16], NULL); + if (reassembled == NULL) + goto end; + if (memcmp(GET_PKT_DATA(reassembled) + 40, expected, expected_len) != 0) + goto end; + + if (IPV6_GET_PLEN(reassembled) != 192) + goto end; + + SCFree(reassembled); + + /* Make sure all frags were returned to the pool. */ + if (defrag_context->frag_pool->outstanding != 0) { + printf(""defrag_context->frag_pool->outstanding %u: "", defrag_context->frag_pool->outstanding); + goto end; + } + + ret = 1; + +end: + for (i = 0; i < 17; i++) { + SCFree(packets[i]); + } + DefragDestroy(); + return ret; +} +","@@ -996,8 +996,8 @@ void DefragDestroy(void) + * with some payload of no particular protocol. + */ + static Packet * +-BuildTestPacket(uint16_t id, uint16_t off, int mf, const char content, +- int content_len) ++BuildTestPacket(uint8_t proto, uint16_t id, uint16_t off, int mf, ++ const char content, int content_len) + { + Packet *p = NULL; + int hlen = 20; +@@ -1023,7 +1023,7 @@ BuildTestPacket(uint16_t id, uint16_t off, int mf, const char content, + else + ip4h.ip_off = htons(off); + ip4h.ip_ttl = ttl; +- ip4h.ip_proto = IPPROTO_ICMP; ++ ip4h.ip_proto = proto; + + ip4h.s_ip_src.s_addr = 0x01010101; /* 1.1.1.1 */ + ip4h.s_ip_dst.s_addr = 0x02020202; /* 2.2.2.2 */ +@@ -1059,7 +1059,7 @@ BuildTestPacket(uint16_t id, uint16_t off, int mf, const char content, + goto error; + if (IPV4_GET_IPTTL(p) != ttl) + goto error; +- if (IPV4_GET_IPPROTO(p) != IPPROTO_ICMP) ++ if (IPV4_GET_IPPROTO(p) != proto) + goto error; + + return p; +@@ -1074,8 +1074,8 @@ void DecodeIPV6FragHeader(Packet *p, uint8_t *pkt, + uint16_t prev_hdrextlen); + + static Packet * +-IPV6BuildTestPacket(uint32_t id, uint16_t off, int mf, const char content, +- int content_len) ++IPV6BuildTestPacket(uint8_t proto, uint32_t id, uint16_t off, int mf, ++ const char content, int content_len) + { + Packet *p = NULL; + uint8_t *pcontent; +@@ -1109,7 +1109,7 @@ IPV6BuildTestPacket(uint32_t id, uint16_t off, int mf, const char content, + IPV6_SET_RAW_VER(p->ip6h, 6); + /* Fragmentation header. */ + IPV6FragHdr *fh = (IPV6FragHdr *)(GET_PKT_DATA(p) + sizeof(IPV6Hdr)); +- fh->ip6fh_nxt = IPPROTO_ICMP; ++ fh->ip6fh_nxt = proto; + fh->ip6fh_ident = htonl(id); + fh->ip6fh_offlg = htons((off << 3) | mf); + +@@ -1159,13 +1159,13 @@ DefragInOrderSimpleTest(void) + + DefragInit(); + +- p1 = BuildTestPacket(id, 0, 1, 'A', 8); ++ p1 = BuildTestPacket(IPPROTO_ICMP, id, 0, 1, 'A', 8); + if (p1 == NULL) + goto end; +- p2 = BuildTestPacket(id, 1, 1, 'B', 8); ++ p2 = BuildTestPacket(IPPROTO_ICMP, id, 1, 1, 'B', 8); + if (p2 == NULL) + goto end; +- p3 = BuildTestPacket(id, 2, 0, 'C', 3); ++ p3 = BuildTestPacket(IPPROTO_ICMP, id, 2, 0, 'C', 3); + if (p3 == NULL) + goto end; + +@@ -1236,13 +1236,13 @@ DefragReverseSimpleTest(void) + + DefragInit(); + +- p1 = BuildTestPacket(id, 0, 1, 'A', 8); ++ p1 = BuildTestPacket(IPPROTO_ICMP, id, 0, 1, 'A', 8); + if (p1 == NULL) + goto end; +- p2 = BuildTestPacket(id, 1, 1, 'B', 8); ++ p2 = BuildTestPacket(IPPROTO_ICMP, id, 1, 1, 'B', 8); + if (p2 == NULL) + goto end; +- p3 = BuildTestPacket(id, 2, 0, 'C', 3); ++ p3 = BuildTestPacket(IPPROTO_ICMP, id, 2, 0, 'C', 3); + if (p3 == NULL) + goto end; + +@@ -1308,13 +1308,13 @@ IPV6DefragInOrderSimpleTest(void) + + DefragInit(); + +- p1 = IPV6BuildTestPacket(id, 0, 1, 'A', 8); ++ p1 = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 0, 1, 'A', 8); + if (p1 == NULL) + goto end; +- p2 = IPV6BuildTestPacket(id, 1, 1, 'B', 8); ++ p2 = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 1, 1, 'B', 8); + if (p2 == NULL) + goto end; +- p3 = IPV6BuildTestPacket(id, 2, 0, 'C', 3); ++ p3 = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 2, 0, 'C', 3); + if (p3 == NULL) + goto end; + +@@ -1378,13 +1378,13 @@ IPV6DefragReverseSimpleTest(void) + if (dc == NULL) + goto end; + +- p1 = IPV6BuildTestPacket(id, 0, 1, 'A', 8); ++ p1 = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 0, 1, 'A', 8); + if (p1 == NULL) + goto end; +- p2 = IPV6BuildTestPacket(id, 1, 1, 'B', 8); ++ p2 = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 1, 1, 'B', 8); + if (p2 == NULL) + goto end; +- p3 = IPV6BuildTestPacket(id, 2, 0, 'C', 3); ++ p3 = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 2, 0, 'C', 3); + if (p3 == NULL) + goto end; + +@@ -1452,59 +1452,59 @@ DefragDoSturgesNovakTest(int policy, u_char *expected, size_t expected_len) + */ + + /* A*24 at 0. */ +- packets[0] = BuildTestPacket(id, 0, 1, 'A', 24); ++ packets[0] = BuildTestPacket(IPPROTO_ICMP, id, 0, 1, 'A', 24); + + /* B*15 at 32. */ +- packets[1] = BuildTestPacket(id, 32 >> 3, 1, 'B', 16); ++ packets[1] = BuildTestPacket(IPPROTO_ICMP, id, 32 >> 3, 1, 'B', 16); + + /* C*24 at 48. */ +- packets[2] = BuildTestPacket(id, 48 >> 3, 1, 'C', 24); ++ packets[2] = BuildTestPacket(IPPROTO_ICMP, id, 48 >> 3, 1, 'C', 24); + + /* D*8 at 80. */ +- packets[3] = BuildTestPacket(id, 80 >> 3, 1, 'D', 8); ++ packets[3] = BuildTestPacket(IPPROTO_ICMP, id, 80 >> 3, 1, 'D', 8); + + /* E*16 at 104. */ +- packets[4] = BuildTestPacket(id, 104 >> 3, 1, 'E', 16); ++ packets[4] = BuildTestPacket(IPPROTO_ICMP, id, 104 >> 3, 1, 'E', 16); + + /* F*24 at 120. */ +- packets[5] = BuildTestPacket(id, 120 >> 3, 1, 'F', 24); ++ packets[5] = BuildTestPacket(IPPROTO_ICMP, id, 120 >> 3, 1, 'F', 24); + + /* G*16 at 144. */ +- packets[6] = BuildTestPacket(id, 144 >> 3, 1, 'G', 16); ++ packets[6] = BuildTestPacket(IPPROTO_ICMP, id, 144 >> 3, 1, 'G', 16); + + /* H*16 at 160. */ +- packets[7] = BuildTestPacket(id, 160 >> 3, 1, 'H', 16); ++ packets[7] = BuildTestPacket(IPPROTO_ICMP, id, 160 >> 3, 1, 'H', 16); + + /* I*8 at 176. */ +- packets[8] = BuildTestPacket(id, 176 >> 3, 1, 'I', 8); ++ packets[8] = BuildTestPacket(IPPROTO_ICMP, id, 176 >> 3, 1, 'I', 8); + + /* + * Overlapping subsequent fragments. + */ + + /* J*32 at 8. */ +- packets[9] = BuildTestPacket(id, 8 >> 3, 1, 'J', 32); ++ packets[9] = BuildTestPacket(IPPROTO_ICMP, id, 8 >> 3, 1, 'J', 32); + + /* K*24 at 48. */ +- packets[10] = BuildTestPacket(id, 48 >> 3, 1, 'K', 24); ++ packets[10] = BuildTestPacket(IPPROTO_ICMP, id, 48 >> 3, 1, 'K', 24); + + /* L*24 at 72. */ +- packets[11] = BuildTestPacket(id, 72 >> 3, 1, 'L', 24); ++ packets[11] = BuildTestPacket(IPPROTO_ICMP, id, 72 >> 3, 1, 'L', 24); + + /* M*24 at 96. */ +- packets[12] = BuildTestPacket(id, 96 >> 3, 1, 'M', 24); ++ packets[12] = BuildTestPacket(IPPROTO_ICMP, id, 96 >> 3, 1, 'M', 24); + + /* N*8 at 128. */ +- packets[13] = BuildTestPacket(id, 128 >> 3, 1, 'N', 8); ++ packets[13] = BuildTestPacket(IPPROTO_ICMP, id, 128 >> 3, 1, 'N', 8); + + /* O*8 at 152. */ +- packets[14] = BuildTestPacket(id, 152 >> 3, 1, 'O', 8); ++ packets[14] = BuildTestPacket(IPPROTO_ICMP, id, 152 >> 3, 1, 'O', 8); + + /* P*8 at 160. */ +- packets[15] = BuildTestPacket(id, 160 >> 3, 1, 'P', 8); ++ packets[15] = BuildTestPacket(IPPROTO_ICMP, id, 160 >> 3, 1, 'P', 8); + + /* Q*16 at 176. */ +- packets[16] = BuildTestPacket(id, 176 >> 3, 0, 'Q', 16); ++ packets[16] = BuildTestPacket(IPPROTO_ICMP, id, 176 >> 3, 0, 'Q', 16); + + default_policy = policy; + +@@ -1587,59 +1587,59 @@ IPV6DefragDoSturgesNovakTest(int policy, u_char *expected, size_t expected_len) + */ + + /* A*24 at 0. */ +- packets[0] = IPV6BuildTestPacket(id, 0, 1, 'A', 24); ++ packets[0] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 0, 1, 'A', 24); + + /* B*15 at 32. */ +- packets[1] = IPV6BuildTestPacket(id, 32 >> 3, 1, 'B', 16); ++ packets[1] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 32 >> 3, 1, 'B', 16); + + /* C*24 at 48. */ +- packets[2] = IPV6BuildTestPacket(id, 48 >> 3, 1, 'C', 24); ++ packets[2] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 48 >> 3, 1, 'C', 24); + + /* D*8 at 80. */ +- packets[3] = IPV6BuildTestPacket(id, 80 >> 3, 1, 'D', 8); ++ packets[3] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 80 >> 3, 1, 'D', 8); + + /* E*16 at 104. */ +- packets[4] = IPV6BuildTestPacket(id, 104 >> 3, 1, 'E', 16); ++ packets[4] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 104 >> 3, 1, 'E', 16); + + /* F*24 at 120. */ +- packets[5] = IPV6BuildTestPacket(id, 120 >> 3, 1, 'F', 24); ++ packets[5] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 120 >> 3, 1, 'F', 24); + + /* G*16 at 144. */ +- packets[6] = IPV6BuildTestPacket(id, 144 >> 3, 1, 'G', 16); ++ packets[6] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 144 >> 3, 1, 'G', 16); + + /* H*16 at 160. */ +- packets[7] = IPV6BuildTestPacket(id, 160 >> 3, 1, 'H', 16); ++ packets[7] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 160 >> 3, 1, 'H', 16); + + /* I*8 at 176. */ +- packets[8] = IPV6BuildTestPacket(id, 176 >> 3, 1, 'I', 8); ++ packets[8] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 176 >> 3, 1, 'I', 8); + + /* + * Overlapping subsequent fragments. + */ + + /* J*32 at 8. */ +- packets[9] = IPV6BuildTestPacket(id, 8 >> 3, 1, 'J', 32); ++ packets[9] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 8 >> 3, 1, 'J', 32); + + /* K*24 at 48. */ +- packets[10] = IPV6BuildTestPacket(id, 48 >> 3, 1, 'K', 24); ++ packets[10] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 48 >> 3, 1, 'K', 24); + + /* L*24 at 72. */ +- packets[11] = IPV6BuildTestPacket(id, 72 >> 3, 1, 'L', 24); ++ packets[11] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 72 >> 3, 1, 'L', 24); + + /* M*24 at 96. */ +- packets[12] = IPV6BuildTestPacket(id, 96 >> 3, 1, 'M', 24); ++ packets[12] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 96 >> 3, 1, 'M', 24); + + /* N*8 at 128. */ +- packets[13] = IPV6BuildTestPacket(id, 128 >> 3, 1, 'N', 8); ++ packets[13] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 128 >> 3, 1, 'N', 8); + + /* O*8 at 152. */ +- packets[14] = IPV6BuildTestPacket(id, 152 >> 3, 1, 'O', 8); ++ packets[14] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 152 >> 3, 1, 'O', 8); + + /* P*8 at 160. */ +- packets[15] = IPV6BuildTestPacket(id, 160 >> 3, 1, 'P', 8); ++ packets[15] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 160 >> 3, 1, 'P', 8); + + /* Q*16 at 176. */ +- packets[16] = IPV6BuildTestPacket(id, 176 >> 3, 0, 'Q', 16); ++ packets[16] = IPV6BuildTestPacket(IPPROTO_ICMPV6, id, 176 >> 3, 0, 'Q', 16); + + default_policy = policy; + +@@ -2125,7 +2125,7 @@ DefragTimeoutTest(void) + + /* Load in 16 packets. */ + for (i = 0; i < 16; i++) { +- Packet *p = BuildTestPacket(i, 0, 1, 'A' + i, 16); ++ Packet *p = BuildTestPacket(IPPROTO_ICMP,i, 0, 1, 'A' + i, 16); + if (p == NULL) + goto end; + +@@ -2141,7 +2141,7 @@ DefragTimeoutTest(void) + + /* Build a new packet but push the timestamp out by our timeout. + * This should force our previous fragments to be timed out. */ +- Packet *p = BuildTestPacket(99, 0, 1, 'A' + i, 16); ++ Packet *p = BuildTestPacket(IPPROTO_ICMP, 99, 0, 1, 'A' + i, 16); + if (p == NULL) + goto end; + +@@ -2189,7 +2189,7 @@ DefragIPv4NoDataTest(void) + goto end; + + /* This packet has an offset > 0, more frags set to 0 and no data. */ +- p = BuildTestPacket(id, 1, 0, 'A', 0); ++ p = BuildTestPacket(IPPROTO_ICMP, id, 1, 0, 'A', 0); + if (p == NULL) + goto end; + +@@ -2228,7 +2228,7 @@ DefragIPv4TooLargeTest(void) + + /* Create a fragment that would extend past the max allowable size + * for an IPv4 packet. */ +- p = BuildTestPacket(1, 8183, 0, 'A', 71); ++ p = BuildTestPacket(IPPROTO_ICMP, 1, 8183, 0, 'A', 71); + if (p == NULL) + goto end; + +@@ -2267,10 +2267,10 @@ DefragVlanTest(void) + + DefragInit(); + +- p1 = BuildTestPacket(1, 0, 1, 'A', 8); ++ p1 = BuildTestPacket(IPPROTO_ICMP, 1, 0, 1, 'A', 8); + if (p1 == NULL) + goto end; +- p2 = BuildTestPacket(1, 1, 0, 'B', 8); ++ p2 = BuildTestPacket(IPPROTO_ICMP, 1, 1, 0, 'B', 8); + if (p2 == NULL) + goto end; + +@@ -2313,10 +2313,10 @@ DefragVlanQinQTest(void) + + DefragInit(); + +- p1 = BuildTestPacket(1, 0, 1, 'A', 8); ++ p1 = BuildTestPacket(IPPROTO_ICMP, 1, 0, 1, 'A', 8); + if (p1 == NULL) + goto end; +- p2 = BuildTestPacket(1, 1, 0, 'B', 8); ++ p2 = BuildTestPacket(IPPROTO_ICMP, 1, 1, 0, 'B', 8); + if (p2 == NULL) + goto end; + +@@ -2361,7 +2361,7 @@ static int DefragTrackerReuseTest(void) + + /* Build a packet, its not a fragment but shouldn't matter for + * this test. */ +- p1 = BuildTestPacket(id, 0, 0, 'A', 8); ++ p1 = BuildTestPacket(IPPROTO_ICMP, id, 0, 0, 'A', 8); + if (p1 == NULL) { + goto end; + } +@@ -2431,9 +2431,9 @@ static int DefragMfIpv4Test(void) + + DefragInit(); + +- Packet *p1 = BuildTestPacket(ip_id, 2, 1, 'C', 8); +- Packet *p2 = BuildTestPacket(ip_id, 0, 1, 'A', 8); +- Packet *p3 = BuildTestPacket(ip_id, 1, 0, 'B', 8); ++ Packet *p1 = BuildTestPacket(IPPROTO_ICMP, ip_id, 2, 1, 'C', 8); ++ Packet *p2 = BuildTestPacket(IPPROTO_ICMP, ip_id, 0, 1, 'A', 8); ++ Packet *p3 = BuildTestPacket(IPPROTO_ICMP, ip_id, 1, 0, 'B', 8); + if (p1 == NULL || p2 == NULL || p3 == NULL) { + goto end; + } +@@ -2495,9 +2495,9 @@ static int DefragMfIpv6Test(void) + + DefragInit(); + +- Packet *p1 = IPV6BuildTestPacket(ip_id, 2, 1, 'C', 8); +- Packet *p2 = IPV6BuildTestPacket(ip_id, 0, 1, 'A', 8); +- Packet *p3 = IPV6BuildTestPacket(ip_id, 1, 0, 'B', 8); ++ Packet *p1 = IPV6BuildTestPacket(IPPROTO_ICMPV6, ip_id, 2, 1, 'C', 8); ++ Packet *p2 = IPV6BuildTestPacket(IPPROTO_ICMPV6, ip_id, 0, 1, 'A', 8); ++ Packet *p3 = IPV6BuildTestPacket(IPPROTO_ICMPV6, ip_id, 1, 0, 'B', 8); + if (p1 == NULL || p2 == NULL || p3 == NULL) { + goto end; + } +@@ -2542,6 +2542,39 @@ static int DefragMfIpv6Test(void) + return retval; + } + ++/** ++ * \brief Test that fragments that match other than the proto don't ++ * actually get matched. ++ */ ++static int DefragTestBadProto(void) ++{ ++ Packet *p1 = NULL, *p2 = NULL, *p3 = NULL; ++ int id = 12; ++ ++ DefragInit(); ++ ++ p1 = BuildTestPacket(IPPROTO_ICMP, id, 0, 1, 'A', 8); ++ FAIL_IF_NULL(p1); ++ p2 = BuildTestPacket(IPPROTO_UDP, id, 1, 1, 'B', 8); ++ FAIL_IF_NULL(p2); ++ p3 = BuildTestPacket(IPPROTO_ICMP, id, 2, 0, 'C', 3); ++ FAIL_IF_NULL(p3); ++ ++ FAIL_IF_NOT_NULL(Defrag(NULL, NULL, p1, NULL)); ++ FAIL_IF_NOT_NULL(Defrag(NULL, NULL, p2, NULL)); ++ FAIL_IF_NOT_NULL(Defrag(NULL, NULL, p3, NULL)); ++ ++ if (p1 != NULL) ++ SCFree(p1); ++ if (p2 != NULL) ++ SCFree(p2); ++ if (p3 != NULL) ++ SCFree(p3); ++ ++ DefragDestroy(); ++ PASS; ++} ++ + #endif /* UNITTESTS */ + + void +@@ -2583,6 +2616,7 @@ DefragRegisterTests(void) + UtRegisterTest(""DefragTimeoutTest"", DefragTimeoutTest); + UtRegisterTest(""DefragMfIpv4Test"", DefragMfIpv4Test); + UtRegisterTest(""DefragMfIpv6Test"", DefragMfIpv6Test); ++ UtRegisterTest(""DefragTestBadProto"", DefragTestBadProto); + #endif /* UNITTESTS */ + } + ",1235,1566,2048 +1115,"static int usb_xhci_initfn(struct PCIDevice *dev) +{ + int i, ret; + + XHCIState *xhci = XHCI(dev); + + dev->config[PCI_CLASS_PROG] = 0x30; /* xHCI */ + dev->config[PCI_INTERRUPT_PIN] = 0x01; /* interrupt pin 1 */ + dev->config[PCI_CACHE_LINE_SIZE] = 0x10; + dev->config[0x60] = 0x30; /* release number */ + + usb_xhci_init(xhci); + + if (xhci->numintrs > MAXINTRS) { + xhci->numintrs = MAXINTRS; + } + while (xhci->numintrs & (xhci->numintrs - 1)) { /* ! power of 2 */ + xhci->numintrs++; + } + if (xhci->numintrs < 1) { + xhci->numintrs = 1; + } + if (xhci->numslots > MAXSLOTS) { + xhci->numslots = MAXSLOTS; + } + if (xhci->numslots < 1) { + xhci->numslots = 1; + } + + xhci->mfwrap_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, xhci_mfwrap_timer, xhci); + + memory_region_init(&xhci->mem, OBJECT(xhci), ""xhci"", LEN_REGS); + memory_region_init_io(&xhci->mem_cap, OBJECT(xhci), &xhci_cap_ops, xhci, + ""capabilities"", LEN_CAP); + memory_region_init_io(&xhci->mem_oper, OBJECT(xhci), &xhci_oper_ops, xhci, + ""operational"", 0x400); + memory_region_init_io(&xhci->mem_runtime, OBJECT(xhci), &xhci_runtime_ops, xhci, + ""runtime"", LEN_RUNTIME); + memory_region_init_io(&xhci->mem_doorbell, OBJECT(xhci), &xhci_doorbell_ops, xhci, + ""doorbell"", LEN_DOORBELL); + + memory_region_add_subregion(&xhci->mem, 0, &xhci->mem_cap); + memory_region_add_subregion(&xhci->mem, OFF_OPER, &xhci->mem_oper); + memory_region_add_subregion(&xhci->mem, OFF_RUNTIME, &xhci->mem_runtime); + memory_region_add_subregion(&xhci->mem, OFF_DOORBELL, &xhci->mem_doorbell); + + for (i = 0; i < xhci->numports; i++) { + XHCIPort *port = &xhci->ports[i]; + uint32_t offset = OFF_OPER + 0x400 + 0x10 * i; + port->xhci = xhci; + memory_region_init_io(&port->mem, OBJECT(xhci), &xhci_port_ops, port, + port->name, 0x10); + memory_region_add_subregion(&xhci->mem, offset, &port->mem); + } + + pci_register_bar(dev, 0, + PCI_BASE_ADDRESS_SPACE_MEMORY|PCI_BASE_ADDRESS_MEM_TYPE_64, + &xhci->mem); + + if (pci_bus_is_express(dev->bus)) { + ret = pcie_endpoint_cap_init(dev, 0xa0); + assert(ret >= 0); + } + + if (xhci_get_flag(xhci, XHCI_FLAG_USE_MSI)) { + msi_init(dev, 0x70, xhci->numintrs, true, false); + } + if (xhci_get_flag(xhci, XHCI_FLAG_USE_MSI_X)) { + msix_init(dev, xhci->numintrs, + &xhci->mem, 0, OFF_MSIX_TABLE, + &xhci->mem, 0, OFF_MSIX_PBA, + 0x90); + } + + return 0; +} +",0,"static int usb_xhci_initfn(struct PCIDevice *dev) +{ + int i, ret; + + XHCIState *xhci = XHCI(dev); + + dev->config[PCI_CLASS_PROG] = 0x30; /* xHCI */ + dev->config[PCI_INTERRUPT_PIN] = 0x01; /* interrupt pin 1 */ + dev->config[PCI_CACHE_LINE_SIZE] = 0x10; + dev->config[0x60] = 0x30; /* release number */ + + usb_xhci_init(xhci); + + if (xhci->numintrs > MAXINTRS) { + xhci->numintrs = MAXINTRS; + } + while (xhci->numintrs & (xhci->numintrs - 1)) { /* ! power of 2 */ + xhci->numintrs++; + } + if (xhci->numintrs < 1) { + xhci->numintrs = 1; + } + if (xhci->numslots > MAXSLOTS) { + xhci->numslots = MAXSLOTS; + } + if (xhci->numslots < 1) { + xhci->numslots = 1; + } + + xhci->mfwrap_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, xhci_mfwrap_timer, xhci); + + memory_region_init(&xhci->mem, OBJECT(xhci), ""xhci"", LEN_REGS); + memory_region_init_io(&xhci->mem_cap, OBJECT(xhci), &xhci_cap_ops, xhci, + ""capabilities"", LEN_CAP); + memory_region_init_io(&xhci->mem_oper, OBJECT(xhci), &xhci_oper_ops, xhci, + ""operational"", 0x400); + memory_region_init_io(&xhci->mem_runtime, OBJECT(xhci), &xhci_runtime_ops, xhci, + ""runtime"", LEN_RUNTIME); + memory_region_init_io(&xhci->mem_doorbell, OBJECT(xhci), &xhci_doorbell_ops, xhci, + ""doorbell"", LEN_DOORBELL); + + memory_region_add_subregion(&xhci->mem, 0, &xhci->mem_cap); + memory_region_add_subregion(&xhci->mem, OFF_OPER, &xhci->mem_oper); + memory_region_add_subregion(&xhci->mem, OFF_RUNTIME, &xhci->mem_runtime); + memory_region_add_subregion(&xhci->mem, OFF_DOORBELL, &xhci->mem_doorbell); + + for (i = 0; i < xhci->numports; i++) { + XHCIPort *port = &xhci->ports[i]; + uint32_t offset = OFF_OPER + 0x400 + 0x10 * i; + port->xhci = xhci; + memory_region_init_io(&port->mem, OBJECT(xhci), &xhci_port_ops, port, + port->name, 0x10); + memory_region_add_subregion(&xhci->mem, offset, &port->mem); + } + + pci_register_bar(dev, 0, + PCI_BASE_ADDRESS_SPACE_MEMORY|PCI_BASE_ADDRESS_MEM_TYPE_64, + &xhci->mem); + + if (pci_bus_is_express(dev->bus)) { + ret = pcie_endpoint_cap_init(dev, 0xa0); + assert(ret >= 0); + } + + if (xhci_get_flag(xhci, XHCI_FLAG_USE_MSI)) { + msi_init(dev, 0x70, xhci->numintrs, true, false); + } + if (xhci_get_flag(xhci, XHCI_FLAG_USE_MSI_X)) { + msix_init(dev, xhci->numintrs, + &xhci->mem, 0, OFF_MSIX_TABLE, + &xhci->mem, 0, OFF_MSIX_PBA, + 0x90); + } + + return 0; +} +","@@ -3737,6 +3737,7 @@ static const VMStateDescription vmstate_xhci_event = { + VMSTATE_UINT32(flags, XHCIEvent), + VMSTATE_UINT8(slotid, XHCIEvent), + VMSTATE_UINT8(epid, XHCIEvent), ++ VMSTATE_END_OF_LIST() + } + };",863,1194,2048 +1362,"c_pdf14trans_clist_write_update(const gs_composite_t * pcte, gx_device * dev, + gx_device ** pcdev, gs_gstate * pgs, gs_memory_t * mem) +{ + gx_device_clist_writer * const cdev = &((gx_device_clist *)dev)->writer; + const gs_pdf14trans_t * pdf14pct = (const gs_pdf14trans_t *) pcte; + int code = 0; + + /* We only handle the push/pop operations */ + switch (pdf14pct->params.pdf14_op) { + case PDF14_PUSH_DEVICE: + return gs_pdf14_clist_device_push(mem, pgs, pcdev, dev, pdf14pct); + + case PDF14_POP_DEVICE: +# if 0 /* Disabled because pdf14_clist_create_compositor does so. */ + /* + * Ensure that the tranfer functions, etc. are current before we + * dump our transparency image to the output device. + */ + if (pgs->dev_ht) + code = cmd_put_halftone((gx_device_clist_writer *) + (((pdf14_clist_device *)dev)->target), pgs->dev_ht); +# else + code = 0; +# endif + code = clist_writer_check_empty_cropping_stack(cdev); + break; + + case PDF14_BEGIN_TRANS_GROUP: + { /* HACK: store mask_id into our params for subsequent + calls of c_pdf14trans_write. To do this we must + break const. */ + gs_pdf14trans_t * pdf14pct_noconst; + + pdf14pct_noconst = (gs_pdf14trans_t *) pcte; + /* What ever the current mask ID is, that is the + softmask group through which this transparency + group must be rendered. Store it now. */ + pdf14pct_noconst->params.mask_id = cdev->mask_id; + if_debug1m('v', pgs->memory, + ""[v]c_pdf14trans_clist_write_update group mask_id=%d \n"", + cdev->mask_id); + } + break; + case PDF14_END_TRANS_GROUP: + code = 0; /* A place for breakpoint. */ + break; + case PDF14_BEGIN_TRANS_MASK: + /* A new mask has been started */ + cdev->mask_id = ++cdev->mask_id_count; + /* replacing is set everytime that we + have a zpushtransparencymaskgroup */ + { /* HACK: store mask_id into our params for subsequent + calls of c_pdf14trans_write. To do this we must + break const. */ + gs_pdf14trans_t * pdf14pct_noconst; + + pdf14pct_noconst = (gs_pdf14trans_t *) pcte; + pdf14pct_noconst->params.mask_id = cdev->mask_id; + if_debug1m('v', pgs->memory, + ""[v]c_pdf14trans_clist_write_update mask mask_id=%d \n"", + cdev->mask_id); + } + break; + case PDF14_END_TRANS_MASK: + code = 0; /* A place for breakpoint. */ + break; + case PDF14_PUSH_TRANS_STATE: + code = 0; /* A place for breakpoint. */ + break; + case PDF14_POP_TRANS_STATE: + code = 0; /* A place for breakpoint. */ + break; + case PDF14_ABORT_DEVICE: + code = 0; + break; + case PDF14_PUSH_SMASK_COLOR: + return 0; + break; + case PDF14_POP_SMASK_COLOR: + return 0; + break; + default: + break; /* do nothing for remaining ops */ + } + *pcdev = dev; + if (code < 0) + return code; + /* See c_pdf14trans_write, c_pdf14trans_adjust_ctm, and + apply_create_compositor. */ + code = gs_gstate_setmatrix(&cdev->gs_gstate, &pdf14pct->params.ctm); + /* Wrote an extra ctm. */ + cmd_clear_known(cdev, ctm_known); + + return code; +} +",0,"c_pdf14trans_clist_write_update(const gs_composite_t * pcte, gx_device * dev, + gx_device ** pcdev, gs_gstate * pgs, gs_memory_t * mem) +{ + gx_device_clist_writer * const cdev = &((gx_device_clist *)dev)->writer; + const gs_pdf14trans_t * pdf14pct = (const gs_pdf14trans_t *) pcte; + int code = 0; + + /* We only handle the push/pop operations */ + switch (pdf14pct->params.pdf14_op) { + case PDF14_PUSH_DEVICE: + return gs_pdf14_clist_device_push(mem, pgs, pcdev, dev, pdf14pct); + + case PDF14_POP_DEVICE: +# if 0 /* Disabled because pdf14_clist_create_compositor does so. */ + /* + * Ensure that the tranfer functions, etc. are current before we + * dump our transparency image to the output device. + */ + if (pgs->dev_ht) + code = cmd_put_halftone((gx_device_clist_writer *) + (((pdf14_clist_device *)dev)->target), pgs->dev_ht); +# else + code = 0; +# endif + code = clist_writer_check_empty_cropping_stack(cdev); + break; + + case PDF14_BEGIN_TRANS_GROUP: + { /* HACK: store mask_id into our params for subsequent + calls of c_pdf14trans_write. To do this we must + break const. */ + gs_pdf14trans_t * pdf14pct_noconst; + + pdf14pct_noconst = (gs_pdf14trans_t *) pcte; + /* What ever the current mask ID is, that is the + softmask group through which this transparency + group must be rendered. Store it now. */ + pdf14pct_noconst->params.mask_id = cdev->mask_id; + if_debug1m('v', pgs->memory, + ""[v]c_pdf14trans_clist_write_update group mask_id=%d \n"", + cdev->mask_id); + } + break; + case PDF14_END_TRANS_GROUP: + code = 0; /* A place for breakpoint. */ + break; + case PDF14_BEGIN_TRANS_MASK: + /* A new mask has been started */ + cdev->mask_id = ++cdev->mask_id_count; + /* replacing is set everytime that we + have a zpushtransparencymaskgroup */ + { /* HACK: store mask_id into our params for subsequent + calls of c_pdf14trans_write. To do this we must + break const. */ + gs_pdf14trans_t * pdf14pct_noconst; + + pdf14pct_noconst = (gs_pdf14trans_t *) pcte; + pdf14pct_noconst->params.mask_id = cdev->mask_id; + if_debug1m('v', pgs->memory, + ""[v]c_pdf14trans_clist_write_update mask mask_id=%d \n"", + cdev->mask_id); + } + break; + case PDF14_END_TRANS_MASK: + code = 0; /* A place for breakpoint. */ + break; + case PDF14_PUSH_TRANS_STATE: + code = 0; /* A place for breakpoint. */ + break; + case PDF14_POP_TRANS_STATE: + code = 0; /* A place for breakpoint. */ + break; + case PDF14_ABORT_DEVICE: + code = 0; + break; + case PDF14_PUSH_SMASK_COLOR: + return 0; + break; + case PDF14_POP_SMASK_COLOR: + return 0; + break; + default: + break; /* do nothing for remaining ops */ + } + *pcdev = dev; + if (code < 0) + return code; + /* See c_pdf14trans_write, c_pdf14trans_adjust_ctm, and + apply_create_compositor. */ + code = gs_gstate_setmatrix(&cdev->gs_gstate, &pdf14pct->params.ctm); + /* Wrote an extra ctm. */ + cmd_clear_known(cdev, ctm_known); + + return code; +} +","@@ -1066,6 +1066,9 @@ pdf14_pop_transparency_group(gs_gstate *pgs, pdf14_ctx *ctx, + gx_color_index drawn_comps = pdev->drawn_comps; + bool nonicc_conversion = true; + ++ if (nos == NULL) ++ return_error(gs_error_unknownerror); /* Unmatched group pop */ ++ + nos_num_color_comp = nos->parent_color_info_procs->num_components - nos->num_spots; + tos_num_color_comp = tos_num_color_comp - tos->num_spots;",936,1267,2048 +18119,"int vmw_gb_surface_define_ioctl(struct drm_device *dev, void *data, + struct drm_file *file_priv) +{ + struct vmw_private *dev_priv = vmw_priv(dev); + struct vmw_user_surface *user_srf; + struct vmw_surface *srf; + struct vmw_resource *res; + struct vmw_resource *tmp; + union drm_vmw_gb_surface_create_arg *arg = + (union drm_vmw_gb_surface_create_arg *)data; + struct drm_vmw_gb_surface_create_req *req = &arg->req; + struct drm_vmw_gb_surface_create_rep *rep = &arg->rep; + struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile; + int ret; + uint32_t size; + uint32_t backup_handle; + + if (req->multisample_count != 0) + return -EINVAL; + + if (req->mip_levels > DRM_VMW_MAX_MIP_LEVELS) + return -EINVAL; + + if (unlikely(vmw_user_surface_size == 0)) + vmw_user_surface_size = ttm_round_pot(sizeof(*user_srf)) + + 128; + + size = vmw_user_surface_size + 128; + + /* Define a surface based on the parameters. */ + ret = vmw_surface_gb_priv_define(dev, + size, + req->svga3d_flags, + req->format, + req->drm_surface_flags & drm_vmw_surface_flag_scanout, + req->mip_levels, + req->multisample_count, + req->array_size, + req->base_size, + &srf); + if (unlikely(ret != 0)) + return ret; + + user_srf = container_of(srf, struct vmw_user_surface, srf); + if (drm_is_primary_client(file_priv)) + user_srf->master = drm_master_get(file_priv->master); + + ret = ttm_read_lock(&dev_priv->reservation_sem, true); + if (unlikely(ret != 0)) + return ret; + + res = &user_srf->srf.res; + + + if (req->buffer_handle != SVGA3D_INVALID_ID) { + ret = vmw_user_dmabuf_lookup(tfile, req->buffer_handle, + &res->backup, + &user_srf->backup_base); + if (ret == 0 && res->backup->base.num_pages * PAGE_SIZE < + res->backup_size) { + DRM_ERROR(""Surface backup buffer is too small.\n""); + vmw_dmabuf_unreference(&res->backup); + ret = -EINVAL; + goto out_unlock; + } + } else if (req->drm_surface_flags & drm_vmw_surface_flag_create_buffer) + ret = vmw_user_dmabuf_alloc(dev_priv, tfile, + res->backup_size, + req->drm_surface_flags & + drm_vmw_surface_flag_shareable, + &backup_handle, + &res->backup, + &user_srf->backup_base); + + if (unlikely(ret != 0)) { + vmw_resource_unreference(&res); + goto out_unlock; + } + + tmp = vmw_resource_reference(res); + ret = ttm_prime_object_init(tfile, res->backup_size, &user_srf->prime, + req->drm_surface_flags & + drm_vmw_surface_flag_shareable, + VMW_RES_SURFACE, + &vmw_user_surface_base_release, NULL); + + if (unlikely(ret != 0)) { + vmw_resource_unreference(&tmp); + vmw_resource_unreference(&res); + goto out_unlock; + } + + rep->handle = user_srf->prime.base.hash.key; + rep->backup_size = res->backup_size; + if (res->backup) { + rep->buffer_map_handle = + drm_vma_node_offset_addr(&res->backup->base.vma_node); + rep->buffer_size = res->backup->base.num_pages * PAGE_SIZE; + rep->buffer_handle = backup_handle; + } else { + rep->buffer_map_handle = 0; + rep->buffer_size = 0; + rep->buffer_handle = SVGA3D_INVALID_ID; + } + + vmw_resource_unreference(&res); + +out_unlock: + ttm_read_unlock(&dev_priv->reservation_sem); + return ret; +} +",1,"int vmw_gb_surface_define_ioctl(struct drm_device *dev, void *data, + struct drm_file *file_priv) +{ + struct vmw_private *dev_priv = vmw_priv(dev); + struct vmw_user_surface *user_srf; + struct vmw_surface *srf; + struct vmw_resource *res; + struct vmw_resource *tmp; + union drm_vmw_gb_surface_create_arg *arg = + (union drm_vmw_gb_surface_create_arg *)data; + struct drm_vmw_gb_surface_create_req *req = &arg->req; + struct drm_vmw_gb_surface_create_rep *rep = &arg->rep; + struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile; + int ret; + uint32_t size; + uint32_t backup_handle = 0; + + if (req->multisample_count != 0) + return -EINVAL; + + if (req->mip_levels > DRM_VMW_MAX_MIP_LEVELS) + return -EINVAL; + + if (unlikely(vmw_user_surface_size == 0)) + vmw_user_surface_size = ttm_round_pot(sizeof(*user_srf)) + + 128; + + size = vmw_user_surface_size + 128; + + /* Define a surface based on the parameters. */ + ret = vmw_surface_gb_priv_define(dev, + size, + req->svga3d_flags, + req->format, + req->drm_surface_flags & drm_vmw_surface_flag_scanout, + req->mip_levels, + req->multisample_count, + req->array_size, + req->base_size, + &srf); + if (unlikely(ret != 0)) + return ret; + + user_srf = container_of(srf, struct vmw_user_surface, srf); + if (drm_is_primary_client(file_priv)) + user_srf->master = drm_master_get(file_priv->master); + + ret = ttm_read_lock(&dev_priv->reservation_sem, true); + if (unlikely(ret != 0)) + return ret; + + res = &user_srf->srf.res; + + + if (req->buffer_handle != SVGA3D_INVALID_ID) { + ret = vmw_user_dmabuf_lookup(tfile, req->buffer_handle, + &res->backup, + &user_srf->backup_base); + if (ret == 0) { + if (res->backup->base.num_pages * PAGE_SIZE < + res->backup_size) { + DRM_ERROR(""Surface backup buffer is too small.\n""); + vmw_dmabuf_unreference(&res->backup); + ret = -EINVAL; + goto out_unlock; + } else { + backup_handle = req->buffer_handle; + } + } + } else if (req->drm_surface_flags & drm_vmw_surface_flag_create_buffer) + ret = vmw_user_dmabuf_alloc(dev_priv, tfile, + res->backup_size, + req->drm_surface_flags & + drm_vmw_surface_flag_shareable, + &backup_handle, + &res->backup, + &user_srf->backup_base); + + if (unlikely(ret != 0)) { + vmw_resource_unreference(&res); + goto out_unlock; + } + + tmp = vmw_resource_reference(res); + ret = ttm_prime_object_init(tfile, res->backup_size, &user_srf->prime, + req->drm_surface_flags & + drm_vmw_surface_flag_shareable, + VMW_RES_SURFACE, + &vmw_user_surface_base_release, NULL); + + if (unlikely(ret != 0)) { + vmw_resource_unreference(&tmp); + vmw_resource_unreference(&res); + goto out_unlock; + } + + rep->handle = user_srf->prime.base.hash.key; + rep->backup_size = res->backup_size; + if (res->backup) { + rep->buffer_map_handle = + drm_vma_node_offset_addr(&res->backup->base.vma_node); + rep->buffer_size = res->backup->base.num_pages * PAGE_SIZE; + rep->buffer_handle = backup_handle; + } else { + rep->buffer_map_handle = 0; + rep->buffer_size = 0; + rep->buffer_handle = SVGA3D_INVALID_ID; + } + + vmw_resource_unreference(&res); + +out_unlock: + ttm_read_unlock(&dev_priv->reservation_sem); + return ret; +} +","@@ -1274,7 +1274,7 @@ int vmw_gb_surface_define_ioctl(struct drm_device *dev, void *data, + struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile; + int ret; + uint32_t size; +- uint32_t backup_handle; ++ uint32_t backup_handle = 0; + + if (req->multisample_count != 0) + return -EINVAL; +@@ -1317,12 +1317,16 @@ int vmw_gb_surface_define_ioctl(struct drm_device *dev, void *data, + ret = vmw_user_dmabuf_lookup(tfile, req->buffer_handle, + &res->backup, + &user_srf->backup_base); +- if (ret == 0 && res->backup->base.num_pages * PAGE_SIZE < +- res->backup_size) { +- DRM_ERROR(""Surface backup buffer is too small.\n""); +- vmw_dmabuf_unreference(&res->backup); +- ret = -EINVAL; +- goto out_unlock; ++ if (ret == 0) { ++ if (res->backup->base.num_pages * PAGE_SIZE < ++ res->backup_size) { ++ DRM_ERROR(""Surface backup buffer is too small.\n""); ++ vmw_dmabuf_unreference(&res->backup); ++ ret = -EINVAL; ++ goto out_unlock; ++ } else { ++ backup_handle = req->buffer_handle; ++ } + } + } else if (req->drm_surface_flags & drm_vmw_surface_flag_create_buffer) + ret = vmw_user_dmabuf_alloc(dev_priv, tfile,",897,1228,2048 +17776,"static bool ldap_push_filter(struct asn1_data *data, struct ldb_parse_tree *tree) +{ + int i; + + switch (tree->operation) { + case LDB_OP_AND: + case LDB_OP_OR: + asn1_push_tag(data, ASN1_CONTEXT(tree->operation==LDB_OP_AND?0:1)); + for (i=0; iu.list.num_elements; i++) { + if (!ldap_push_filter(data, tree->u.list.elements[i])) { + return false; + } + } + asn1_pop_tag(data); + break; + + case LDB_OP_NOT: + asn1_push_tag(data, ASN1_CONTEXT(2)); + if (!ldap_push_filter(data, tree->u.isnot.child)) { + return false; + } + asn1_pop_tag(data); + break; + + case LDB_OP_EQUALITY: + /* equality test */ + asn1_push_tag(data, ASN1_CONTEXT(3)); + asn1_write_OctetString(data, tree->u.equality.attr, + strlen(tree->u.equality.attr)); + asn1_write_OctetString(data, tree->u.equality.value.data, + tree->u.equality.value.length); + asn1_pop_tag(data); + break; + + case LDB_OP_SUBSTRING: + /* + SubstringFilter ::= SEQUENCE { + type AttributeDescription, + -- at least one must be present + substrings SEQUENCE OF CHOICE { + initial [0] LDAPString, + any [1] LDAPString, + final [2] LDAPString } } + */ + asn1_push_tag(data, ASN1_CONTEXT(4)); + asn1_write_OctetString(data, tree->u.substring.attr, strlen(tree->u.substring.attr)); + asn1_push_tag(data, ASN1_SEQUENCE(0)); + + if (tree->u.substring.chunks && tree->u.substring.chunks[0]) { + i = 0; + if (!tree->u.substring.start_with_wildcard) { + asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0)); + asn1_write_DATA_BLOB_LDAPString(data, tree->u.substring.chunks[i]); + asn1_pop_tag(data); + i++; + } + while (tree->u.substring.chunks[i]) { + int ctx; + + if (( ! tree->u.substring.chunks[i + 1]) && + (tree->u.substring.end_with_wildcard == 0)) { + ctx = 2; + } else { + ctx = 1; + } + asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(ctx)); + asn1_write_DATA_BLOB_LDAPString(data, tree->u.substring.chunks[i]); + asn1_pop_tag(data); + i++; + } + } + asn1_pop_tag(data); + asn1_pop_tag(data); + break; + + case LDB_OP_GREATER: + /* greaterOrEqual test */ + asn1_push_tag(data, ASN1_CONTEXT(5)); + asn1_write_OctetString(data, tree->u.comparison.attr, + strlen(tree->u.comparison.attr)); + asn1_write_OctetString(data, tree->u.comparison.value.data, + tree->u.comparison.value.length); + asn1_pop_tag(data); + break; + + case LDB_OP_LESS: + /* lessOrEqual test */ + asn1_push_tag(data, ASN1_CONTEXT(6)); + asn1_write_OctetString(data, tree->u.comparison.attr, + strlen(tree->u.comparison.attr)); + asn1_write_OctetString(data, tree->u.comparison.value.data, + tree->u.comparison.value.length); + asn1_pop_tag(data); + break; + + case LDB_OP_PRESENT: + /* present test */ + asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(7)); + asn1_write_LDAPString(data, tree->u.present.attr); + asn1_pop_tag(data); + return !data->has_error; + + case LDB_OP_APPROX: + /* approx test */ + asn1_push_tag(data, ASN1_CONTEXT(8)); + asn1_write_OctetString(data, tree->u.comparison.attr, + strlen(tree->u.comparison.attr)); + asn1_write_OctetString(data, tree->u.comparison.value.data, + tree->u.comparison.value.length); + asn1_pop_tag(data); + break; + + case LDB_OP_EXTENDED: + /* + MatchingRuleAssertion ::= SEQUENCE { + matchingRule [1] MatchingRuleID OPTIONAL, + type [2] AttributeDescription OPTIONAL, + matchValue [3] AssertionValue, + dnAttributes [4] BOOLEAN DEFAULT FALSE + } + */ + asn1_push_tag(data, ASN1_CONTEXT(9)); + if (tree->u.extended.rule_id) { + asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(1)); + asn1_write_LDAPString(data, tree->u.extended.rule_id); + asn1_pop_tag(data); + } + if (tree->u.extended.attr) { + asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(2)); + asn1_write_LDAPString(data, tree->u.extended.attr); + asn1_pop_tag(data); + } + asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(3)); + asn1_write_DATA_BLOB_LDAPString(data, &tree->u.extended.value); + asn1_pop_tag(data); + asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(4)); + asn1_write_uint8(data, tree->u.extended.dnAttributes); + asn1_pop_tag(data); + asn1_pop_tag(data); + break; + + default: + return false; + } + return !data->has_error; + } +",1,"static bool ldap_push_filter(struct asn1_data *data, struct ldb_parse_tree *tree) +{ + int i; + + switch (tree->operation) { + case LDB_OP_AND: + case LDB_OP_OR: + if (!asn1_push_tag(data, ASN1_CONTEXT(tree->operation==LDB_OP_AND?0:1))) return false; + for (i=0; iu.list.num_elements; i++) { + if (!ldap_push_filter(data, tree->u.list.elements[i])) { + return false; + } + } + if (!asn1_pop_tag(data)) return false; + break; + + case LDB_OP_NOT: + if (!asn1_push_tag(data, ASN1_CONTEXT(2))) return false; + if (!ldap_push_filter(data, tree->u.isnot.child)) { + return false; + } + if (!asn1_pop_tag(data)) return false; + break; + + case LDB_OP_EQUALITY: + /* equality test */ + if (!asn1_push_tag(data, ASN1_CONTEXT(3))) return false; + if (!asn1_write_OctetString(data, tree->u.equality.attr, + strlen(tree->u.equality.attr))) return false; + if (!asn1_write_OctetString(data, tree->u.equality.value.data, + tree->u.equality.value.length)) return false; + if (!asn1_pop_tag(data)) return false; + break; + + case LDB_OP_SUBSTRING: + /* + SubstringFilter ::= SEQUENCE { + type AttributeDescription, + -- at least one must be present + substrings SEQUENCE OF CHOICE { + initial [0] LDAPString, + any [1] LDAPString, + final [2] LDAPString } } + */ + if (!asn1_push_tag(data, ASN1_CONTEXT(4))) return false; + if (!asn1_write_OctetString(data, tree->u.substring.attr, strlen(tree->u.substring.attr))) return false; + if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) return false; + + if (tree->u.substring.chunks && tree->u.substring.chunks[0]) { + i = 0; + if (!tree->u.substring.start_with_wildcard) { + if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0))) return false; + if (!asn1_write_DATA_BLOB_LDAPString(data, tree->u.substring.chunks[i])) return false; + if (!asn1_pop_tag(data)) return false; + i++; + } + while (tree->u.substring.chunks[i]) { + int ctx; + + if (( ! tree->u.substring.chunks[i + 1]) && + (tree->u.substring.end_with_wildcard == 0)) { + ctx = 2; + } else { + ctx = 1; + } + if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(ctx))) return false; + if (!asn1_write_DATA_BLOB_LDAPString(data, tree->u.substring.chunks[i])) return false; + if (!asn1_pop_tag(data)) return false; + i++; + } + } + if (!asn1_pop_tag(data)) return false; + if (!asn1_pop_tag(data)) return false; + break; + + case LDB_OP_GREATER: + /* greaterOrEqual test */ + if (!asn1_push_tag(data, ASN1_CONTEXT(5))) return false; + if (!asn1_write_OctetString(data, tree->u.comparison.attr, + strlen(tree->u.comparison.attr))) return false; + if (!asn1_write_OctetString(data, tree->u.comparison.value.data, + tree->u.comparison.value.length)) return false; + if (!asn1_pop_tag(data)) return false; + break; + + case LDB_OP_LESS: + /* lessOrEqual test */ + if (!asn1_push_tag(data, ASN1_CONTEXT(6))) return false; + if (!asn1_write_OctetString(data, tree->u.comparison.attr, + strlen(tree->u.comparison.attr))) return false; + if (!asn1_write_OctetString(data, tree->u.comparison.value.data, + tree->u.comparison.value.length)) return false; + if (!asn1_pop_tag(data)) return false; + break; + + case LDB_OP_PRESENT: + /* present test */ + if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(7))) return false; + if (!asn1_write_LDAPString(data, tree->u.present.attr)) return false; + if (!asn1_pop_tag(data)) return false; + return !data->has_error; + + case LDB_OP_APPROX: + /* approx test */ + if (!asn1_push_tag(data, ASN1_CONTEXT(8))) return false; + if (!asn1_write_OctetString(data, tree->u.comparison.attr, + strlen(tree->u.comparison.attr))) return false; + if (!asn1_write_OctetString(data, tree->u.comparison.value.data, + tree->u.comparison.value.length)) return false; + if (!asn1_pop_tag(data)) return false; + break; + + case LDB_OP_EXTENDED: + /* + MatchingRuleAssertion ::= SEQUENCE { + matchingRule [1] MatchingRuleID OPTIONAL, + type [2] AttributeDescription OPTIONAL, + matchValue [3] AssertionValue, + dnAttributes [4] BOOLEAN DEFAULT FALSE + } + */ + if (!asn1_push_tag(data, ASN1_CONTEXT(9))) return false; + if (tree->u.extended.rule_id) { + if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(1))) return false; + if (!asn1_write_LDAPString(data, tree->u.extended.rule_id)) return false; + if (!asn1_pop_tag(data)) return false; + } + if (tree->u.extended.attr) { + if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(2))) return false; + if (!asn1_write_LDAPString(data, tree->u.extended.attr)) return false; + if (!asn1_pop_tag(data)) return false; + } + if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(3))) return false; + if (!asn1_write_DATA_BLOB_LDAPString(data, &tree->u.extended.value)) return false; + if (!asn1_pop_tag(data)) return false; + if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(4))) return false; + if (!asn1_write_uint8(data, tree->u.extended.dnAttributes)) return false; + if (!asn1_pop_tag(data)) return false; + if (!asn1_pop_tag(data)) return false; + break; + + default: + return false; + } + return !data->has_error; + } +","@@ -229,31 +229,31 @@ static bool ldap_push_filter(struct asn1_data *data, struct ldb_parse_tree *tree + switch (tree->operation) { + case LDB_OP_AND: + case LDB_OP_OR: +- asn1_push_tag(data, ASN1_CONTEXT(tree->operation==LDB_OP_AND?0:1)); ++ if (!asn1_push_tag(data, ASN1_CONTEXT(tree->operation==LDB_OP_AND?0:1))) return false; + for (i=0; iu.list.num_elements; i++) { + if (!ldap_push_filter(data, tree->u.list.elements[i])) { + return false; + } + } +- asn1_pop_tag(data); ++ if (!asn1_pop_tag(data)) return false; + break; + + case LDB_OP_NOT: +- asn1_push_tag(data, ASN1_CONTEXT(2)); ++ if (!asn1_push_tag(data, ASN1_CONTEXT(2))) return false; + if (!ldap_push_filter(data, tree->u.isnot.child)) { + return false; + } +- asn1_pop_tag(data); ++ if (!asn1_pop_tag(data)) return false; + break; + + case LDB_OP_EQUALITY: + /* equality test */ +- asn1_push_tag(data, ASN1_CONTEXT(3)); +- asn1_write_OctetString(data, tree->u.equality.attr, +- strlen(tree->u.equality.attr)); +- asn1_write_OctetString(data, tree->u.equality.value.data, +- tree->u.equality.value.length); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_CONTEXT(3))) return false; ++ if (!asn1_write_OctetString(data, tree->u.equality.attr, ++ strlen(tree->u.equality.attr))) return false; ++ if (!asn1_write_OctetString(data, tree->u.equality.value.data, ++ tree->u.equality.value.length)) return false; ++ if (!asn1_pop_tag(data)) return false; + break; + + case LDB_OP_SUBSTRING: +@@ -266,16 +266,16 @@ static bool ldap_push_filter(struct asn1_data *data, struct ldb_parse_tree *tree + any [1] LDAPString, + final [2] LDAPString } } + */ +- asn1_push_tag(data, ASN1_CONTEXT(4)); +- asn1_write_OctetString(data, tree->u.substring.attr, strlen(tree->u.substring.attr)); +- asn1_push_tag(data, ASN1_SEQUENCE(0)); ++ if (!asn1_push_tag(data, ASN1_CONTEXT(4))) return false; ++ if (!asn1_write_OctetString(data, tree->u.substring.attr, strlen(tree->u.substring.attr))) return false; ++ if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) return false; + + if (tree->u.substring.chunks && tree->u.substring.chunks[0]) { + i = 0; + if (!tree->u.substring.start_with_wildcard) { +- asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0)); +- asn1_write_DATA_BLOB_LDAPString(data, tree->u.substring.chunks[i]); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0))) return false; ++ if (!asn1_write_DATA_BLOB_LDAPString(data, tree->u.substring.chunks[i])) return false; ++ if (!asn1_pop_tag(data)) return false; + i++; + } + while (tree->u.substring.chunks[i]) { +@@ -287,51 +287,51 @@ static bool ldap_push_filter(struct asn1_data *data, struct ldb_parse_tree *tree + } else { + ctx = 1; + } +- asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(ctx)); +- asn1_write_DATA_BLOB_LDAPString(data, tree->u.substring.chunks[i]); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(ctx))) return false; ++ if (!asn1_write_DATA_BLOB_LDAPString(data, tree->u.substring.chunks[i])) return false; ++ if (!asn1_pop_tag(data)) return false; + i++; + } + } +- asn1_pop_tag(data); +- asn1_pop_tag(data); ++ if (!asn1_pop_tag(data)) return false; ++ if (!asn1_pop_tag(data)) return false; + break; + + case LDB_OP_GREATER: + /* greaterOrEqual test */ +- asn1_push_tag(data, ASN1_CONTEXT(5)); +- asn1_write_OctetString(data, tree->u.comparison.attr, +- strlen(tree->u.comparison.attr)); +- asn1_write_OctetString(data, tree->u.comparison.value.data, +- tree->u.comparison.value.length); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_CONTEXT(5))) return false; ++ if (!asn1_write_OctetString(data, tree->u.comparison.attr, ++ strlen(tree->u.comparison.attr))) return false; ++ if (!asn1_write_OctetString(data, tree->u.comparison.value.data, ++ tree->u.comparison.value.length)) return false; ++ if (!asn1_pop_tag(data)) return false; + break; + + case LDB_OP_LESS: + /* lessOrEqual test */ +- asn1_push_tag(data, ASN1_CONTEXT(6)); +- asn1_write_OctetString(data, tree->u.comparison.attr, +- strlen(tree->u.comparison.attr)); +- asn1_write_OctetString(data, tree->u.comparison.value.data, +- tree->u.comparison.value.length); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_CONTEXT(6))) return false; ++ if (!asn1_write_OctetString(data, tree->u.comparison.attr, ++ strlen(tree->u.comparison.attr))) return false; ++ if (!asn1_write_OctetString(data, tree->u.comparison.value.data, ++ tree->u.comparison.value.length)) return false; ++ if (!asn1_pop_tag(data)) return false; + break; + + case LDB_OP_PRESENT: + /* present test */ +- asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(7)); +- asn1_write_LDAPString(data, tree->u.present.attr); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(7))) return false; ++ if (!asn1_write_LDAPString(data, tree->u.present.attr)) return false; ++ if (!asn1_pop_tag(data)) return false; + return !data->has_error; + + case LDB_OP_APPROX: + /* approx test */ +- asn1_push_tag(data, ASN1_CONTEXT(8)); +- asn1_write_OctetString(data, tree->u.comparison.attr, +- strlen(tree->u.comparison.attr)); +- asn1_write_OctetString(data, tree->u.comparison.value.data, +- tree->u.comparison.value.length); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_CONTEXT(8))) return false; ++ if (!asn1_write_OctetString(data, tree->u.comparison.attr, ++ strlen(tree->u.comparison.attr))) return false; ++ if (!asn1_write_OctetString(data, tree->u.comparison.value.data, ++ tree->u.comparison.value.length)) return false; ++ if (!asn1_pop_tag(data)) return false; + break; + + case LDB_OP_EXTENDED: +@@ -343,24 +343,24 @@ static bool ldap_push_filter(struct asn1_data *data, struct ldb_parse_tree *tree + dnAttributes [4] BOOLEAN DEFAULT FALSE + } + */ +- asn1_push_tag(data, ASN1_CONTEXT(9)); ++ if (!asn1_push_tag(data, ASN1_CONTEXT(9))) return false; + if (tree->u.extended.rule_id) { +- asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(1)); +- asn1_write_LDAPString(data, tree->u.extended.rule_id); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(1))) return false; ++ if (!asn1_write_LDAPString(data, tree->u.extended.rule_id)) return false; ++ if (!asn1_pop_tag(data)) return false; + } + if (tree->u.extended.attr) { +- asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(2)); +- asn1_write_LDAPString(data, tree->u.extended.attr); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(2))) return false; ++ if (!asn1_write_LDAPString(data, tree->u.extended.attr)) return false; ++ if (!asn1_pop_tag(data)) return false; + } +- asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(3)); +- asn1_write_DATA_BLOB_LDAPString(data, &tree->u.extended.value); +- asn1_pop_tag(data); +- asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(4)); +- asn1_write_uint8(data, tree->u.extended.dnAttributes); +- asn1_pop_tag(data); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(3))) return false; ++ if (!asn1_write_DATA_BLOB_LDAPString(data, &tree->u.extended.value)) return false; ++ if (!asn1_pop_tag(data)) return false; ++ if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(4))) return false; ++ if (!asn1_write_uint8(data, tree->u.extended.dnAttributes)) return false; ++ if (!asn1_pop_tag(data)) return false; ++ if (!asn1_pop_tag(data)) return false; + break; + + default: +@@ -369,20 +369,21 @@ static bool ldap_push_filter(struct asn1_data *data, struct ldb_parse_tree *tree + return !data->has_error; + } + +-static void ldap_encode_response(struct asn1_data *data, struct ldap_Result *result) ++static bool ldap_encode_response(struct asn1_data *data, struct ldap_Result *result) + { +- asn1_write_enumerated(data, result->resultcode); +- asn1_write_OctetString(data, result->dn, +- (result->dn) ? strlen(result->dn) : 0); +- asn1_write_OctetString(data, result->errormessage, ++ if (!asn1_write_enumerated(data, result->resultcode)) return false; ++ if (!asn1_write_OctetString(data, result->dn, ++ (result->dn) ? strlen(result->dn) : 0)) return false; ++ if (!asn1_write_OctetString(data, result->errormessage, + (result->errormessage) ? +- strlen(result->errormessage) : 0); ++ strlen(result->errormessage) : 0)) return false; + if (result->referral) { +- asn1_push_tag(data, ASN1_CONTEXT(3)); +- asn1_write_OctetString(data, result->referral, +- strlen(result->referral)); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_CONTEXT(3))) return false; ++ if (!asn1_write_OctetString(data, result->referral, ++ strlen(result->referral))) return false; ++ if (!asn1_pop_tag(data)) return false; + } ++ return true; + } + + _PUBLIC_ bool ldap_encode(struct ldap_message *msg, +@@ -394,286 +395,286 @@ _PUBLIC_ bool ldap_encode(struct ldap_message *msg, + + if (!data) return false; + +- asn1_push_tag(data, ASN1_SEQUENCE(0)); +- asn1_write_Integer(data, msg->messageid); ++ if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) goto err; ++ if (!asn1_write_Integer(data, msg->messageid)) goto err; + + switch (msg->type) { + case LDAP_TAG_BindRequest: { + struct ldap_BindRequest *r = &msg->r.BindRequest; +- asn1_push_tag(data, ASN1_APPLICATION(msg->type)); +- asn1_write_Integer(data, r->version); +- asn1_write_OctetString(data, r->dn, +- (r->dn != NULL) ? strlen(r->dn) : 0); ++ if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err; ++ if (!asn1_write_Integer(data, r->version)) goto err; ++ if (!asn1_write_OctetString(data, r->dn, ++ (r->dn != NULL) ? strlen(r->dn) : 0)) goto err; + + switch (r->mechanism) { + case LDAP_AUTH_MECH_SIMPLE: + /* context, primitive */ +- asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0)); +- asn1_write(data, r->creds.password, +- strlen(r->creds.password)); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0))) goto err; ++ if (!asn1_write(data, r->creds.password, ++ strlen(r->creds.password))) goto err; ++ if (!asn1_pop_tag(data)) goto err; + break; + case LDAP_AUTH_MECH_SASL: + /* context, constructed */ +- asn1_push_tag(data, ASN1_CONTEXT(3)); +- asn1_write_OctetString(data, r->creds.SASL.mechanism, +- strlen(r->creds.SASL.mechanism)); ++ if (!asn1_push_tag(data, ASN1_CONTEXT(3))) goto err; ++ if (!asn1_write_OctetString(data, r->creds.SASL.mechanism, ++ strlen(r->creds.SASL.mechanism))) goto err; + if (r->creds.SASL.secblob) { +- asn1_write_OctetString(data, r->creds.SASL.secblob->data, +- r->creds.SASL.secblob->length); ++ if (!asn1_write_OctetString(data, r->creds.SASL.secblob->data, ++ r->creds.SASL.secblob->length)) goto err; + } +- asn1_pop_tag(data); ++ if (!asn1_pop_tag(data)) goto err; + break; + default: +- return false; ++ goto err; + } + +- asn1_pop_tag(data); ++ if (!asn1_pop_tag(data)) goto err; + break; + } + case LDAP_TAG_BindResponse: { + struct ldap_BindResponse *r = &msg->r.BindResponse; +- asn1_push_tag(data, ASN1_APPLICATION(msg->type)); +- ldap_encode_response(data, &r->response); ++ if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err; ++ if (!ldap_encode_response(data, &r->response)) goto err; + if (r->SASL.secblob) { +- asn1_write_ContextSimple(data, 7, r->SASL.secblob); ++ if (!asn1_write_ContextSimple(data, 7, r->SASL.secblob)) goto err; + } +- asn1_pop_tag(data); ++ if (!asn1_pop_tag(data)) goto err; + break; + } + case LDAP_TAG_UnbindRequest: { + /* struct ldap_UnbindRequest *r = &msg->r.UnbindRequest; */ +- asn1_push_tag(data, ASN1_APPLICATION_SIMPLE(msg->type)); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_APPLICATION_SIMPLE(msg->type))) goto err; ++ if (!asn1_pop_tag(data)) goto err; + break; + } + case LDAP_TAG_SearchRequest: { + struct ldap_SearchRequest *r = &msg->r.SearchRequest; +- asn1_push_tag(data, ASN1_APPLICATION(msg->type)); +- asn1_write_OctetString(data, r->basedn, strlen(r->basedn)); +- asn1_write_enumerated(data, r->scope); +- asn1_write_enumerated(data, r->deref); +- asn1_write_Integer(data, r->sizelimit); +- asn1_write_Integer(data, r->timelimit); +- asn1_write_BOOLEAN(data, r->attributesonly); ++ if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err; ++ if (!asn1_write_OctetString(data, r->basedn, strlen(r->basedn))) goto err; ++ if (!asn1_write_enumerated(data, r->scope)) goto err; ++ if (!asn1_write_enumerated(data, r->deref)) goto err; ++ if (!asn1_write_Integer(data, r->sizelimit)) goto err; ++ if (!asn1_write_Integer(data, r->timelimit)) goto err; ++ if (!asn1_write_BOOLEAN(data, r->attributesonly)) goto err; + + if (!ldap_push_filter(data, r->tree)) { +- return false; ++ goto err; + } + +- asn1_push_tag(data, ASN1_SEQUENCE(0)); ++ if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) goto err; + for (i=0; inum_attributes; i++) { +- asn1_write_OctetString(data, r->attributes[i], +- strlen(r->attributes[i])); ++ if (!asn1_write_OctetString(data, r->attributes[i], ++ strlen(r->attributes[i]))) goto err; + } +- asn1_pop_tag(data); +- asn1_pop_tag(data); ++ if (!asn1_pop_tag(data)) goto err; ++ if (!asn1_pop_tag(data)) goto err; + break; + } + case LDAP_TAG_SearchResultEntry: { + struct ldap_SearchResEntry *r = &msg->r.SearchResultEntry; +- asn1_push_tag(data, ASN1_APPLICATION(msg->type)); +- asn1_write_OctetString(data, r->dn, strlen(r->dn)); +- asn1_push_tag(data, ASN1_SEQUENCE(0)); ++ if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err; ++ if (!asn1_write_OctetString(data, r->dn, strlen(r->dn))) goto err; ++ if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) goto err; + for (i=0; inum_attributes; i++) { + struct ldb_message_element *attr = &r->attributes[i]; +- asn1_push_tag(data, ASN1_SEQUENCE(0)); +- asn1_write_OctetString(data, attr->name, +- strlen(attr->name)); +- asn1_push_tag(data, ASN1_SEQUENCE(1)); ++ if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) goto err; ++ if (!asn1_write_OctetString(data, attr->name, ++ strlen(attr->name))) goto err; ++ if (!asn1_push_tag(data, ASN1_SEQUENCE(1))) goto err; + for (j=0; jnum_values; j++) { +- asn1_write_OctetString(data, ++ if (!asn1_write_OctetString(data, + attr->values[j].data, +- attr->values[j].length); ++ attr->values[j].length)) goto err; + } +- asn1_pop_tag(data); +- asn1_pop_tag(data); ++ if (!asn1_pop_tag(data)) goto err; ++ if (!asn1_pop_tag(data)) goto err; + } +- asn1_pop_tag(data); +- asn1_pop_tag(data); ++ if (!asn1_pop_tag(data)) goto err; ++ if (!asn1_pop_tag(data)) goto err; + break; + } + case LDAP_TAG_SearchResultDone: { + struct ldap_Result *r = &msg->r.SearchResultDone; +- asn1_push_tag(data, ASN1_APPLICATION(msg->type)); +- ldap_encode_response(data, r); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err; ++ if (!ldap_encode_response(data, r)) goto err; ++ if (!asn1_pop_tag(data)) goto err; + break; + } + case LDAP_TAG_ModifyRequest: { + struct ldap_ModifyRequest *r = &msg->r.ModifyRequest; +- asn1_push_tag(data, ASN1_APPLICATION(msg->type)); +- asn1_write_OctetString(data, r->dn, strlen(r->dn)); +- asn1_push_tag(data, ASN1_SEQUENCE(0)); ++ if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err; ++ if (!asn1_write_OctetString(data, r->dn, strlen(r->dn))) goto err; ++ if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) goto err; + + for (i=0; inum_mods; i++) { + struct ldb_message_element *attrib = &r->mods[i].attrib; +- asn1_push_tag(data, ASN1_SEQUENCE(0)); +- asn1_write_enumerated(data, r->mods[i].type); +- asn1_push_tag(data, ASN1_SEQUENCE(0)); +- asn1_write_OctetString(data, attrib->name, +- strlen(attrib->name)); +- asn1_push_tag(data, ASN1_SET); ++ if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) goto err; ++ if (!asn1_write_enumerated(data, r->mods[i].type)) goto err; ++ if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) goto err; ++ if (!asn1_write_OctetString(data, attrib->name, ++ strlen(attrib->name))) goto err; ++ if (!asn1_push_tag(data, ASN1_SET)) goto err; + for (j=0; jnum_values; j++) { +- asn1_write_OctetString(data, ++ if (!asn1_write_OctetString(data, + attrib->values[j].data, +- attrib->values[j].length); ++ attrib->values[j].length)) goto err; + + } +- asn1_pop_tag(data); +- asn1_pop_tag(data); +- asn1_pop_tag(data); ++ if (!asn1_pop_tag(data)) goto err; ++ if (!asn1_pop_tag(data)) goto err; ++ if (!asn1_pop_tag(data)) goto err; + } + +- asn1_pop_tag(data); +- asn1_pop_tag(data); ++ if (!asn1_pop_tag(data)) goto err; ++ if (!asn1_pop_tag(data)) goto err; + break; + } + case LDAP_TAG_ModifyResponse: { + struct ldap_Result *r = &msg->r.ModifyResponse; +- asn1_push_tag(data, ASN1_APPLICATION(msg->type)); +- ldap_encode_response(data, r); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err; ++ if (!ldap_encode_response(data, r)) goto err; ++ if (!asn1_pop_tag(data)) goto err; + break; + } + case LDAP_TAG_AddRequest: { + struct ldap_AddRequest *r = &msg->r.AddRequest; +- asn1_push_tag(data, ASN1_APPLICATION(msg->type)); +- asn1_write_OctetString(data, r->dn, strlen(r->dn)); +- asn1_push_tag(data, ASN1_SEQUENCE(0)); ++ if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err; ++ if (!asn1_write_OctetString(data, r->dn, strlen(r->dn))) goto err; ++ if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) goto err; + + for (i=0; inum_attributes; i++) { + struct ldb_message_element *attrib = &r->attributes[i]; +- asn1_push_tag(data, ASN1_SEQUENCE(0)); +- asn1_write_OctetString(data, attrib->name, +- strlen(attrib->name)); +- asn1_push_tag(data, ASN1_SET); ++ if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) goto err; ++ if (!asn1_write_OctetString(data, attrib->name, ++ strlen(attrib->name))) goto err; ++ if (!asn1_push_tag(data, ASN1_SET)) goto err; + for (j=0; jattributes[i].num_values; j++) { +- asn1_write_OctetString(data, ++ if (!asn1_write_OctetString(data, + attrib->values[j].data, +- attrib->values[j].length); ++ attrib->values[j].length)) goto err; + } +- asn1_pop_tag(data); +- asn1_pop_tag(data); ++ if (!asn1_pop_tag(data)) goto err; ++ if (!asn1_pop_tag(data)) goto err; + } +- asn1_pop_tag(data); +- asn1_pop_tag(data); ++ if (!asn1_pop_tag(data)) goto err; ++ if (!asn1_pop_tag(data)) goto err; + break; + } + case LDAP_TAG_AddResponse: { + struct ldap_Result *r = &msg->r.AddResponse; +- asn1_push_tag(data, ASN1_APPLICATION(msg->type)); +- ldap_encode_response(data, r); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err; ++ if (!ldap_encode_response(data, r)) goto err; ++ if (!asn1_pop_tag(data)) goto err; + break; + } + case LDAP_TAG_DelRequest: { + struct ldap_DelRequest *r = &msg->r.DelRequest; +- asn1_push_tag(data, ASN1_APPLICATION_SIMPLE(msg->type)); +- asn1_write(data, r->dn, strlen(r->dn)); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_APPLICATION_SIMPLE(msg->type))) goto err; ++ if (!asn1_write(data, r->dn, strlen(r->dn))) goto err; ++ if (!asn1_pop_tag(data)) goto err; + break; + } + case LDAP_TAG_DelResponse: { + struct ldap_Result *r = &msg->r.DelResponse; +- asn1_push_tag(data, ASN1_APPLICATION(msg->type)); +- ldap_encode_response(data, r); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err; ++ if (!ldap_encode_response(data, r)) goto err; ++ if (!asn1_pop_tag(data)) goto err; + break; + } + case LDAP_TAG_ModifyDNRequest: { + struct ldap_ModifyDNRequest *r = &msg->r.ModifyDNRequest; +- asn1_push_tag(data, ASN1_APPLICATION(msg->type)); +- asn1_write_OctetString(data, r->dn, strlen(r->dn)); +- asn1_write_OctetString(data, r->newrdn, strlen(r->newrdn)); +- asn1_write_BOOLEAN(data, r->deleteolddn); ++ if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err; ++ if (!asn1_write_OctetString(data, r->dn, strlen(r->dn))) goto err; ++ if (!asn1_write_OctetString(data, r->newrdn, strlen(r->newrdn))) goto err; ++ if (!asn1_write_BOOLEAN(data, r->deleteolddn)) goto err; + if (r->newsuperior) { +- asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0)); +- asn1_write(data, r->newsuperior, +- strlen(r->newsuperior)); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0))) goto err; ++ if (!asn1_write(data, r->newsuperior, ++ strlen(r->newsuperior))) goto err; ++ if (!asn1_pop_tag(data)) goto err; + } +- asn1_pop_tag(data); ++ if (!asn1_pop_tag(data)) goto err; + break; + } + case LDAP_TAG_ModifyDNResponse: { + struct ldap_Result *r = &msg->r.ModifyDNResponse; +- asn1_push_tag(data, ASN1_APPLICATION(msg->type)); +- ldap_encode_response(data, r); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err; ++ if (!ldap_encode_response(data, r)) goto err; ++ if (!asn1_pop_tag(data)) goto err; + break; + } + case LDAP_TAG_CompareRequest: { + struct ldap_CompareRequest *r = &msg->r.CompareRequest; +- asn1_push_tag(data, ASN1_APPLICATION(msg->type)); +- asn1_write_OctetString(data, r->dn, strlen(r->dn)); +- asn1_push_tag(data, ASN1_SEQUENCE(0)); +- asn1_write_OctetString(data, r->attribute, +- strlen(r->attribute)); +- asn1_write_OctetString(data, r->value.data, +- r->value.length); +- asn1_pop_tag(data); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err; ++ if (!asn1_write_OctetString(data, r->dn, strlen(r->dn))) goto err; ++ if (!asn1_push_tag(data, ASN1_SEQUENCE(0))) goto err; ++ if (!asn1_write_OctetString(data, r->attribute, ++ strlen(r->attribute))) goto err; ++ if (!asn1_write_OctetString(data, r->value.data, ++ r->value.length)) goto err; ++ if (!asn1_pop_tag(data)) goto err; ++ if (!asn1_pop_tag(data)) goto err; + break; + } + case LDAP_TAG_CompareResponse: { + struct ldap_Result *r = &msg->r.ModifyDNResponse; +- asn1_push_tag(data, ASN1_APPLICATION(msg->type)); +- ldap_encode_response(data, r); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err; ++ if (!ldap_encode_response(data, r)) goto err; ++ if (!asn1_pop_tag(data)) goto err; + break; + } + case LDAP_TAG_AbandonRequest: { + struct ldap_AbandonRequest *r = &msg->r.AbandonRequest; +- asn1_push_tag(data, ASN1_APPLICATION_SIMPLE(msg->type)); +- asn1_write_implicit_Integer(data, r->messageid); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_APPLICATION_SIMPLE(msg->type))) goto err; ++ if (!asn1_write_implicit_Integer(data, r->messageid)) goto err; ++ if (!asn1_pop_tag(data)) goto err; + break; + } + case LDAP_TAG_SearchResultReference: { + struct ldap_SearchResRef *r = &msg->r.SearchResultReference; +- asn1_push_tag(data, ASN1_APPLICATION(msg->type)); +- asn1_write_OctetString(data, r->referral, strlen(r->referral)); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err; ++ if (!asn1_write_OctetString(data, r->referral, strlen(r->referral))) goto err; ++ if (!asn1_pop_tag(data)) goto err; + break; + } + case LDAP_TAG_ExtendedRequest: { + struct ldap_ExtendedRequest *r = &msg->r.ExtendedRequest; +- asn1_push_tag(data, ASN1_APPLICATION(msg->type)); +- asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0)); +- asn1_write(data, r->oid, strlen(r->oid)); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err; ++ if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0))) goto err; ++ if (!asn1_write(data, r->oid, strlen(r->oid))) goto err; ++ if (!asn1_pop_tag(data)) goto err; + if (r->value) { +- asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(1)); +- asn1_write(data, r->value->data, r->value->length); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(1))) goto err; ++ if (!asn1_write(data, r->value->data, r->value->length)) goto err; ++ if (!asn1_pop_tag(data)) goto err; + } +- asn1_pop_tag(data); ++ if (!asn1_pop_tag(data)) goto err; + break; + } + case LDAP_TAG_ExtendedResponse: { + struct ldap_ExtendedResponse *r = &msg->r.ExtendedResponse; +- asn1_push_tag(data, ASN1_APPLICATION(msg->type)); +- ldap_encode_response(data, &r->response); ++ if (!asn1_push_tag(data, ASN1_APPLICATION(msg->type))) goto err; ++ if (!ldap_encode_response(data, &r->response)) goto err; + if (r->oid) { +- asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(10)); +- asn1_write(data, r->oid, strlen(r->oid)); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(10))) goto err; ++ if (!asn1_write(data, r->oid, strlen(r->oid))) goto err; ++ if (!asn1_pop_tag(data)) goto err; + } + if (r->value) { +- asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(11)); +- asn1_write(data, r->value->data, r->value->length); +- asn1_pop_tag(data); ++ if (!asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(11))) goto err; ++ if (!asn1_write(data, r->value->data, r->value->length)) goto err; ++ if (!asn1_pop_tag(data)) goto err; + } +- asn1_pop_tag(data); ++ if (!asn1_pop_tag(data)) goto err; + break; + } + default: +- return false; ++ goto err; + } + + if (msg->controls != NULL) { +- asn1_push_tag(data, ASN1_CONTEXT(0)); ++ if (!asn1_push_tag(data, ASN1_CONTEXT(0))) goto err; + + for (i = 0; msg->controls[i] != NULL; i++) { + if (!ldap_encode_control(mem_ctx, data, +@@ -681,23 +682,24 @@ _PUBLIC_ bool ldap_encode(struct ldap_message *msg, + msg->controls[i])) { + DEBUG(0,(""Unable to encode control %s\n"", + msg->controls[i]->oid)); +- return false; ++ goto err; + } + } + +- asn1_pop_tag(data); ++ if (!asn1_pop_tag(data)) goto err; + } + +- asn1_pop_tag(data); +- +- if (data->has_error) { +- asn1_free(data); +- return false; +- } ++ if (!asn1_pop_tag(data)) goto err; + + *result = data_blob_talloc(mem_ctx, data->data, data->length); + asn1_free(data); ++ + return true; ++ ++ err: ++ ++ asn1_free(data); ++ return false; + } + + static const char *blob2string_talloc(TALLOC_CTX *mem_ctx, +@@ -721,20 +723,21 @@ bool asn1_read_OctetString_talloc(TALLOC_CTX *mem_ctx, + return true; + } + +-static void ldap_decode_response(TALLOC_CTX *mem_ctx, ++static bool ldap_decode_response(TALLOC_CTX *mem_ctx, + struct asn1_data *data, + struct ldap_Result *result) + { +- asn1_read_enumerated(data, &result->resultcode); +- asn1_read_OctetString_talloc(mem_ctx, data, &result->dn); +- asn1_read_OctetString_talloc(mem_ctx, data, &result->errormessage); ++ if (!asn1_read_enumerated(data, &result->resultcode)) return false; ++ if (!asn1_read_OctetString_talloc(mem_ctx, data, &result->dn)) return false; ++ if (!asn1_read_OctetString_talloc(mem_ctx, data, &result->errormessage)) return false; + if (asn1_peek_tag(data, ASN1_CONTEXT(3))) { +- asn1_start_tag(data, ASN1_CONTEXT(3)); +- asn1_read_OctetString_talloc(mem_ctx, data, &result->referral); +- asn1_end_tag(data); ++ if (!asn1_start_tag(data, ASN1_CONTEXT(3))) return false; ++ if (!asn1_read_OctetString_talloc(mem_ctx, data, &result->referral)) return false; ++ if (!asn1_end_tag(data)) return false; + } else { + result->referral = NULL; + } ++ return true; + } + + static struct ldb_val **ldap_decode_substring(TALLOC_CTX *mem_ctx, struct ldb_val **chunks, int chunk_num, char *value) +@@ -835,10 +838,10 @@ static struct ldb_parse_tree *ldap_decode_filter_tree(TALLOC_CTX *mem_ctx, + const char *attrib; + DATA_BLOB value; + +- asn1_start_tag(data, ASN1_CONTEXT(filter_tag)); +- asn1_read_OctetString_talloc(mem_ctx, data, &attrib); +- asn1_read_OctetString(data, mem_ctx, &value); +- asn1_end_tag(data); ++ if (!asn1_start_tag(data, ASN1_CONTEXT(filter_tag))) goto failed; ++ if (!asn1_read_OctetString_talloc(mem_ctx, data, &attrib)) goto failed; ++ if (!asn1_read_OctetString(data, mem_ctx, &value)) goto failed; ++ if (!asn1_end_tag(data)) goto failed; + if ((data->has_error) || (attrib == NULL) || (value.data == NULL)) { + goto failed; + } +@@ -874,13 +877,13 @@ static struct ldb_parse_tree *ldap_decode_filter_tree(TALLOC_CTX *mem_ctx, + } + + while (asn1_tag_remaining(data)) { +- asn1_peek_uint8(data, &subs_tag); ++ if (!asn1_peek_uint8(data, &subs_tag)) goto failed; + subs_tag &= 0x1f; /* strip off the asn1 stuff */ + if (subs_tag > 2) goto failed; + +- asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(subs_tag)); +- asn1_read_LDAPString(data, mem_ctx, &value); +- asn1_end_tag(data); ++ if (!asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(subs_tag))) goto failed; ++ if (!asn1_read_LDAPString(data, mem_ctx, &value)) goto failed; ++ if (!asn1_end_tag(data)) goto failed; + + switch (subs_tag) { + case 0: +@@ -947,10 +950,10 @@ static struct ldb_parse_tree *ldap_decode_filter_tree(TALLOC_CTX *mem_ctx, + const char *attrib; + DATA_BLOB value; + +- asn1_start_tag(data, ASN1_CONTEXT(filter_tag)); +- asn1_read_OctetString_talloc(mem_ctx, data, &attrib); +- asn1_read_OctetString(data, mem_ctx, &value); +- asn1_end_tag(data); ++ if (!asn1_start_tag(data, ASN1_CONTEXT(filter_tag))) goto failed; ++ if (!asn1_read_OctetString_talloc(mem_ctx, data, &attrib)) goto failed; ++ if (!asn1_read_OctetString(data, mem_ctx, &value)) goto failed; ++ if (!asn1_end_tag(data)) goto failed; + if ((data->has_error) || (attrib == NULL) || (value.data == NULL)) { + goto failed; + } +@@ -966,10 +969,10 @@ static struct ldb_parse_tree *ldap_decode_filter_tree(TALLOC_CTX *mem_ctx, + const char *attrib; + DATA_BLOB value; + +- asn1_start_tag(data, ASN1_CONTEXT(filter_tag)); +- asn1_read_OctetString_talloc(mem_ctx, data, &attrib); +- asn1_read_OctetString(data, mem_ctx, &value); +- asn1_end_tag(data); ++ if (!asn1_start_tag(data, ASN1_CONTEXT(filter_tag))) goto failed; ++ if (!asn1_read_OctetString_talloc(mem_ctx, data, &attrib)) goto failed; ++ if (!asn1_read_OctetString(data, mem_ctx, &value)) goto failed; ++ if (!asn1_end_tag(data)) goto failed; + if ((data->has_error) || (attrib == NULL) || (value.data == NULL)) { + goto failed; + } +@@ -1004,10 +1007,10 @@ static struct ldb_parse_tree *ldap_decode_filter_tree(TALLOC_CTX *mem_ctx, + const char *attrib; + DATA_BLOB value; + +- asn1_start_tag(data, ASN1_CONTEXT(filter_tag)); +- asn1_read_OctetString_talloc(mem_ctx, data, &attrib); +- asn1_read_OctetString(data, mem_ctx, &value); +- asn1_end_tag(data); ++ if (!asn1_start_tag(data, ASN1_CONTEXT(filter_tag))) goto failed; ++ if (!asn1_read_OctetString_talloc(mem_ctx, data, &attrib)) goto failed; ++ if (!asn1_read_OctetString(data, mem_ctx, &value)) goto failed; ++ if (!asn1_end_tag(data)) goto failed; + if ((data->has_error) || (attrib == NULL) || (value.data == NULL)) { + goto failed; + } +@@ -1030,18 +1033,18 @@ static struct ldb_parse_tree *ldap_decode_filter_tree(TALLOC_CTX *mem_ctx, + we need to check we properly implement --SSS */ + /* either oid or type must be defined */ + if (asn1_peek_tag(data, ASN1_CONTEXT_SIMPLE(1))) { /* optional */ +- asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(1)); +- asn1_read_LDAPString(data, ret, &oid); +- asn1_end_tag(data); ++ if (!asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(1))) goto failed; ++ if (!asn1_read_LDAPString(data, ret, &oid)) goto failed; ++ if (!asn1_end_tag(data)) goto failed; + } + if (asn1_peek_tag(data, ASN1_CONTEXT_SIMPLE(2))) { /* optional */ +- asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(2)); +- asn1_read_LDAPString(data, ret, &attr); +- asn1_end_tag(data); ++ if (!asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(2))) goto failed; ++ if (!asn1_read_LDAPString(data, ret, &attr)) goto failed; ++ if (!asn1_end_tag(data)) goto failed; + } +- asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(3)); +- asn1_read_LDAPString(data, ret, &value); +- asn1_end_tag(data); ++ if (!asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(3))) goto failed; ++ if (!asn1_read_LDAPString(data, ret, &value)) goto failed; ++ if (!asn1_end_tag(data)) goto failed; + /* dnAttributes is marked as BOOLEAN DEFAULT FALSE + it is not marked as OPTIONAL but openldap tools + do not set this unless it is to be set as TRUE +@@ -1049,9 +1052,9 @@ static struct ldb_parse_tree *ldap_decode_filter_tree(TALLOC_CTX *mem_ctx, + seems that AD always requires the dnAttributes + boolean value to be set */ + if (asn1_peek_tag(data, ASN1_CONTEXT_SIMPLE(4))) { +- asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(4)); +- asn1_read_uint8(data, &dnAttributes); +- asn1_end_tag(data); ++ if (!asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(4))) goto failed; ++ if (!asn1_read_uint8(data, &dnAttributes)) goto failed; ++ if (!asn1_end_tag(data)) goto failed; + } else { + dnAttributes = 0; + } +@@ -1099,45 +1102,45 @@ failed: + } + + /* Decode a single LDAP attribute, possibly containing multiple values */ +-static void ldap_decode_attrib(TALLOC_CTX *mem_ctx, struct asn1_data *data, ++static bool ldap_decode_attrib(TALLOC_CTX *mem_ctx, struct asn1_data *data, + struct ldb_message_element *attrib) + { +- asn1_start_tag(data, ASN1_SEQUENCE(0)); +- asn1_read_OctetString_talloc(mem_ctx, data, &attrib->name); +- asn1_start_tag(data, ASN1_SET); ++ if (!asn1_start_tag(data, ASN1_SEQUENCE(0))) return false; ++ if (!asn1_read_OctetString_talloc(mem_ctx, data, &attrib->name)) return false; ++ if (!asn1_start_tag(data, ASN1_SET)) return false; + while (asn1_peek_tag(data, ASN1_OCTET_STRING)) { + DATA_BLOB blob; +- asn1_read_OctetString(data, mem_ctx, &blob); ++ if (!asn1_read_OctetString(data, mem_ctx, &blob)) return false; + add_value_to_attrib(mem_ctx, &blob, attrib); + } +- asn1_end_tag(data); +- asn1_end_tag(data); +- ++ if (!asn1_end_tag(data)) return false; ++ return asn1_end_tag(data); + } + + /* Decode a set of LDAP attributes, as found in the dereference control */ +-void ldap_decode_attribs_bare(TALLOC_CTX *mem_ctx, struct asn1_data *data, ++bool ldap_decode_attribs_bare(TALLOC_CTX *mem_ctx, struct asn1_data *data, + struct ldb_message_element **attributes, + int *num_attributes) + { + while (asn1_peek_tag(data, ASN1_SEQUENCE(0))) { + struct ldb_message_element attrib; + ZERO_STRUCT(attrib); +- ldap_decode_attrib(mem_ctx, data, &attrib); ++ if (!ldap_decode_attrib(mem_ctx, data, &attrib)) return false; + add_attrib_to_array_talloc(mem_ctx, &attrib, + attributes, num_attributes); + } ++ return true; + } + + /* Decode a set of LDAP attributes, as found in a search entry */ +-static void ldap_decode_attribs(TALLOC_CTX *mem_ctx, struct asn1_data *data, ++static bool ldap_decode_attribs(TALLOC_CTX *mem_ctx, struct asn1_data *data, + struct ldb_message_element **attributes, + int *num_attributes) + { +- asn1_start_tag(data, ASN1_SEQUENCE(0)); +- ldap_decode_attribs_bare(mem_ctx, data, +- attributes, num_attributes); +- asn1_end_tag(data); ++ if (!asn1_start_tag(data, ASN1_SEQUENCE(0))) return false; ++ if (!ldap_decode_attribs_bare(mem_ctx, data, ++ attributes, num_attributes)) return false; ++ return asn1_end_tag(data); + } + + /* This routine returns LDAP status codes */ +@@ -1148,46 +1151,45 @@ _PUBLIC_ NTSTATUS ldap_decode(struct asn1_data *data, + { + uint8_t tag; + +- asn1_start_tag(data, ASN1_SEQUENCE(0)); +- asn1_read_Integer(data, &msg->messageid); ++ if (!asn1_start_tag(data, ASN1_SEQUENCE(0))) goto prot_err; ++ if (!asn1_read_Integer(data, &msg->messageid)) goto prot_err; + +- if (!asn1_peek_uint8(data, &tag)) +- return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); ++ if (!asn1_peek_uint8(data, &tag)) goto prot_err; + + switch(tag) { + + case ASN1_APPLICATION(LDAP_TAG_BindRequest): { + struct ldap_BindRequest *r = &msg->r.BindRequest; + msg->type = LDAP_TAG_BindRequest; +- asn1_start_tag(data, tag); +- asn1_read_Integer(data, &r->version); +- asn1_read_OctetString_talloc(msg, data, &r->dn); ++ if (!asn1_start_tag(data, tag)) goto prot_err; ++ if (!asn1_read_Integer(data, &r->version)) goto prot_err; ++ if (!asn1_read_OctetString_talloc(msg, data, &r->dn)) goto prot_err; + if (asn1_peek_tag(data, ASN1_CONTEXT_SIMPLE(0))) { + int pwlen; + r->creds.password = """"; + r->mechanism = LDAP_AUTH_MECH_SIMPLE; +- asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(0)); ++ if (!asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(0))) goto prot_err; + pwlen = asn1_tag_remaining(data); + if (pwlen == -1) { +- return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); ++ goto prot_err; + } + if (pwlen != 0) { + char *pw = talloc_array(msg, char, pwlen+1); + if (!pw) { + return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); + } +- asn1_read(data, pw, pwlen); ++ if (!asn1_read(data, pw, pwlen)) goto prot_err; + pw[pwlen] = '\0'; + r->creds.password = pw; + } +- asn1_end_tag(data); ++ if (!asn1_end_tag(data)) goto prot_err; + } else if (asn1_peek_tag(data, ASN1_CONTEXT(3))){ +- asn1_start_tag(data, ASN1_CONTEXT(3)); ++ if (!asn1_start_tag(data, ASN1_CONTEXT(3))) goto prot_err; + r->mechanism = LDAP_AUTH_MECH_SASL; +- asn1_read_OctetString_talloc(msg, data, &r->creds.SASL.mechanism); ++ if (!asn1_read_OctetString_talloc(msg, data, &r->creds.SASL.mechanism)) goto prot_err; + if (asn1_peek_tag(data, ASN1_OCTET_STRING)) { /* optional */ + DATA_BLOB tmp_blob = data_blob(NULL, 0); +- asn1_read_OctetString(data, msg, &tmp_blob); ++ if (!asn1_read_OctetString(data, msg, &tmp_blob)) goto prot_err; + r->creds.SASL.secblob = talloc(msg, DATA_BLOB); + if (!r->creds.SASL.secblob) { + return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); +@@ -1198,23 +1200,23 @@ _PUBLIC_ NTSTATUS ldap_decode(struct asn1_data *data, + } else { + r->creds.SASL.secblob = NULL; + } +- asn1_end_tag(data); ++ if (!asn1_end_tag(data)) goto prot_err; + } else { + /* Neither Simple nor SASL bind */ +- return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); ++ goto prot_err; + } +- asn1_end_tag(data); ++ if (!asn1_end_tag(data)) goto prot_err; + break; + } + + case ASN1_APPLICATION(LDAP_TAG_BindResponse): { + struct ldap_BindResponse *r = &msg->r.BindResponse; + msg->type = LDAP_TAG_BindResponse; +- asn1_start_tag(data, tag); +- ldap_decode_response(msg, data, &r->response); ++ if (!asn1_start_tag(data, tag)) goto prot_err; ++ if (!ldap_decode_response(msg, data, &r->response)) goto prot_err; + if (asn1_peek_tag(data, ASN1_CONTEXT_SIMPLE(7))) { + DATA_BLOB tmp_blob = data_blob(NULL, 0); +- asn1_read_ContextSimple(data, 7, &tmp_blob); ++ if (!asn1_read_ContextSimple(data, 7, &tmp_blob)) goto prot_err; + r->SASL.secblob = talloc(msg, DATA_BLOB); + if (!r->SASL.secblob) { + return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); +@@ -1225,14 +1227,14 @@ _PUBLIC_ NTSTATUS ldap_decode(struct asn1_data *data, + } else { + r->SASL.secblob = NULL; + } +- asn1_end_tag(data); ++ if (!asn1_end_tag(data)) goto prot_err; + break; + } + + case ASN1_APPLICATION_SIMPLE(LDAP_TAG_UnbindRequest): { + msg->type = LDAP_TAG_UnbindRequest; +- asn1_start_tag(data, tag); +- asn1_end_tag(data); ++ if (!asn1_start_tag(data, tag)) goto prot_err; ++ if (!asn1_end_tag(data)) goto prot_err; + break; + } + +@@ -1241,41 +1243,41 @@ _PUBLIC_ NTSTATUS ldap_decode(struct asn1_data *data, + int sizelimit, timelimit; + const char **attrs = NULL; + msg->type = LDAP_TAG_SearchRequest; +- asn1_start_tag(data, tag); +- asn1_read_OctetString_talloc(msg, data, &r->basedn); +- asn1_read_enumerated(data, (int *)(void *)&(r->scope)); +- asn1_read_enumerated(data, (int *)(void *)&(r->deref)); +- asn1_read_Integer(data, &sizelimit); ++ if (!asn1_start_tag(data, tag)) goto prot_err; ++ if (!asn1_read_OctetString_talloc(msg, data, &r->basedn)) goto prot_err; ++ if (!asn1_read_enumerated(data, (int *)(void *)&(r->scope))) goto prot_err; ++ if (!asn1_read_enumerated(data, (int *)(void *)&(r->deref))) goto prot_err; ++ if (!asn1_read_Integer(data, &sizelimit)) goto prot_err; + r->sizelimit = sizelimit; +- asn1_read_Integer(data, &timelimit); ++ if (!asn1_read_Integer(data, &timelimit)) goto prot_err; + r->timelimit = timelimit; +- asn1_read_BOOLEAN(data, &r->attributesonly); ++ if (!asn1_read_BOOLEAN(data, &r->attributesonly)) goto prot_err; + + r->tree = ldap_decode_filter_tree(msg, data); + if (r->tree == NULL) { +- return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); ++ goto prot_err; + } + +- asn1_start_tag(data, ASN1_SEQUENCE(0)); ++ if (!asn1_start_tag(data, ASN1_SEQUENCE(0))) goto prot_err; + + r->num_attributes = 0; + r->attributes = NULL; + +- while (asn1_tag_remaining(data) > 0) { ++ while (asn1_tag_remaining(data) > 0) { + + const char *attr; + if (!asn1_read_OctetString_talloc(msg, data, + &attr)) +- return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); ++ goto prot_err; + if (!add_string_to_array(msg, attr, + &attrs, + &r->num_attributes)) +- return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); ++ goto prot_err; + } + r->attributes = attrs; + +- asn1_end_tag(data); +- asn1_end_tag(data); ++ if (!asn1_end_tag(data)) goto prot_err; ++ if (!asn1_end_tag(data)) goto prot_err; + break; + } + +@@ -1284,38 +1286,38 @@ _PUBLIC_ NTSTATUS ldap_decode(struct asn1_data *data, + msg->type = LDAP_TAG_SearchResultEntry; + r->attributes = NULL; + r->num_attributes = 0; +- asn1_start_tag(data, tag); +- asn1_read_OctetString_talloc(msg, data, &r->dn); +- ldap_decode_attribs(msg, data, &r->attributes, +- &r->num_attributes); +- asn1_end_tag(data); ++ if (!asn1_start_tag(data, tag)) goto prot_err; ++ if (!asn1_read_OctetString_talloc(msg, data, &r->dn)) goto prot_err; ++ if (!ldap_decode_attribs(msg, data, &r->attributes, ++ &r->num_attributes)) goto prot_err; ++ if (!asn1_end_tag(data)) goto prot_err; + break; + } + + case ASN1_APPLICATION(LDAP_TAG_SearchResultDone): { + struct ldap_Result *r = &msg->r.SearchResultDone; + msg->type = LDAP_TAG_SearchResultDone; +- asn1_start_tag(data, tag); +- ldap_decode_response(msg, data, r); +- asn1_end_tag(data); ++ if (!asn1_start_tag(data, tag)) goto prot_err; ++ if (!ldap_decode_response(msg, data, r)) goto prot_err; ++ if (!asn1_end_tag(data)) goto prot_err; + break; + } + + case ASN1_APPLICATION(LDAP_TAG_SearchResultReference): { + struct ldap_SearchResRef *r = &msg->r.SearchResultReference; + msg->type = LDAP_TAG_SearchResultReference; +- asn1_start_tag(data, tag); +- asn1_read_OctetString_talloc(msg, data, &r->referral); +- asn1_end_tag(data); ++ if (!asn1_start_tag(data, tag)) goto prot_err; ++ if (!asn1_read_OctetString_talloc(msg, data, &r->referral)) goto prot_err; ++ if (!asn1_end_tag(data)) goto prot_err; + break; + } + + case ASN1_APPLICATION(LDAP_TAG_ModifyRequest): { + struct ldap_ModifyRequest *r = &msg->r.ModifyRequest; + msg->type = LDAP_TAG_ModifyRequest; +- asn1_start_tag(data, ASN1_APPLICATION(LDAP_TAG_ModifyRequest)); +- asn1_read_OctetString_talloc(msg, data, &r->dn); +- asn1_start_tag(data, ASN1_SEQUENCE(0)); ++ if (!asn1_start_tag(data, ASN1_APPLICATION(LDAP_TAG_ModifyRequest))) goto prot_err; ++ if (!asn1_read_OctetString_talloc(msg, data, &r->dn)) goto prot_err; ++ if (!asn1_start_tag(data, ASN1_SEQUENCE(0))) goto prot_err; + + r->num_mods = 0; + r->mods = NULL; +@@ -1324,52 +1326,52 @@ _PUBLIC_ NTSTATUS ldap_decode(struct asn1_data *data, + struct ldap_mod mod; + int v; + ZERO_STRUCT(mod); +- asn1_start_tag(data, ASN1_SEQUENCE(0)); +- asn1_read_enumerated(data, &v); ++ if (!asn1_start_tag(data, ASN1_SEQUENCE(0))) goto prot_err; ++ if (!asn1_read_enumerated(data, &v)) goto prot_err; + mod.type = v; +- ldap_decode_attrib(msg, data, &mod.attrib); +- asn1_end_tag(data); ++ if (!ldap_decode_attrib(msg, data, &mod.attrib)) goto prot_err; ++ if (!asn1_end_tag(data)) goto prot_err; + if (!add_mod_to_array_talloc(msg, &mod, + &r->mods, &r->num_mods)) { + return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); + } + } + +- asn1_end_tag(data); +- asn1_end_tag(data); ++ if (!asn1_end_tag(data)) goto prot_err; ++ if (!asn1_end_tag(data)) goto prot_err; + break; + } + + case ASN1_APPLICATION(LDAP_TAG_ModifyResponse): { + struct ldap_Result *r = &msg->r.ModifyResponse; + msg->type = LDAP_TAG_ModifyResponse; +- asn1_start_tag(data, tag); +- ldap_decode_response(msg, data, r); +- asn1_end_tag(data); ++ if (!asn1_start_tag(data, tag)) goto prot_err; ++ if (!ldap_decode_response(msg, data, r)) goto prot_err; ++ if (!asn1_end_tag(data)) goto prot_err; + break; + } + + case ASN1_APPLICATION(LDAP_TAG_AddRequest): { + struct ldap_AddRequest *r = &msg->r.AddRequest; + msg->type = LDAP_TAG_AddRequest; +- asn1_start_tag(data, tag); +- asn1_read_OctetString_talloc(msg, data, &r->dn); ++ if (!asn1_start_tag(data, tag)) goto prot_err; ++ if (!asn1_read_OctetString_talloc(msg, data, &r->dn)) goto prot_err; + + r->attributes = NULL; + r->num_attributes = 0; +- ldap_decode_attribs(msg, data, &r->attributes, +- &r->num_attributes); ++ if (!ldap_decode_attribs(msg, data, &r->attributes, ++ &r->num_attributes)) goto prot_err; + +- asn1_end_tag(data); ++ if (!asn1_end_tag(data)) goto prot_err; + break; + } + + case ASN1_APPLICATION(LDAP_TAG_AddResponse): { + struct ldap_Result *r = &msg->r.AddResponse; + msg->type = LDAP_TAG_AddResponse; +- asn1_start_tag(data, tag); +- ldap_decode_response(msg, data, r); +- asn1_end_tag(data); ++ if (!asn1_start_tag(data, tag)) goto prot_err; ++ if (!ldap_decode_response(msg, data, r)) goto prot_err; ++ if (!asn1_end_tag(data)) goto prot_err; + break; + } + +@@ -1378,102 +1380,102 @@ _PUBLIC_ NTSTATUS ldap_decode(struct asn1_data *data, + int len; + char *dn; + msg->type = LDAP_TAG_DelRequest; +- asn1_start_tag(data, +- ASN1_APPLICATION_SIMPLE(LDAP_TAG_DelRequest)); ++ if (!asn1_start_tag(data, ++ ASN1_APPLICATION_SIMPLE(LDAP_TAG_DelRequest))) goto prot_err; + len = asn1_tag_remaining(data); + if (len == -1) { +- return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); ++ goto prot_err; + } + dn = talloc_array(msg, char, len+1); + if (dn == NULL) + break; +- asn1_read(data, dn, len); ++ if (!asn1_read(data, dn, len)) goto prot_err; + dn[len] = '\0'; + r->dn = dn; +- asn1_end_tag(data); ++ if (!asn1_end_tag(data)) goto prot_err; + break; + } + + case ASN1_APPLICATION(LDAP_TAG_DelResponse): { + struct ldap_Result *r = &msg->r.DelResponse; + msg->type = LDAP_TAG_DelResponse; +- asn1_start_tag(data, tag); +- ldap_decode_response(msg, data, r); +- asn1_end_tag(data); ++ if (!asn1_start_tag(data, tag)) goto prot_err; ++ if (!ldap_decode_response(msg, data, r)) goto prot_err; ++ if (!asn1_end_tag(data)) goto prot_err; + break; + } + + case ASN1_APPLICATION(LDAP_TAG_ModifyDNRequest): { + struct ldap_ModifyDNRequest *r = &msg->r.ModifyDNRequest; + msg->type = LDAP_TAG_ModifyDNRequest; +- asn1_start_tag(data, +- ASN1_APPLICATION(LDAP_TAG_ModifyDNRequest)); +- asn1_read_OctetString_talloc(msg, data, &r->dn); +- asn1_read_OctetString_talloc(msg, data, &r->newrdn); +- asn1_read_BOOLEAN(data, &r->deleteolddn); ++ if (!asn1_start_tag(data, ++ ASN1_APPLICATION(LDAP_TAG_ModifyDNRequest))) goto prot_err; ++ if (!asn1_read_OctetString_talloc(msg, data, &r->dn)) goto prot_err; ++ if (!asn1_read_OctetString_talloc(msg, data, &r->newrdn)) goto prot_err; ++ if (!asn1_read_BOOLEAN(data, &r->deleteolddn)) goto prot_err; + r->newsuperior = NULL; + if (asn1_tag_remaining(data) > 0) { + int len; + char *newsup; +- asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(0)); ++ if (!asn1_start_tag(data, ASN1_CONTEXT_SIMPLE(0))) goto prot_err; + len = asn1_tag_remaining(data); + if (len == -1) { +- return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); ++ goto prot_err; + } + newsup = talloc_array(msg, char, len+1); + if (newsup == NULL) { + return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); + } +- asn1_read(data, newsup, len); ++ if (!asn1_read(data, newsup, len)) goto prot_err; + newsup[len] = '\0'; + r->newsuperior = newsup; +- asn1_end_tag(data); ++ if (!asn1_end_tag(data)) goto prot_err; + } +- asn1_end_tag(data); ++ if (!asn1_end_tag(data)) goto prot_err; + break; + } + + case ASN1_APPLICATION(LDAP_TAG_ModifyDNResponse): { + struct ldap_Result *r = &msg->r.ModifyDNResponse; + msg->type = LDAP_TAG_ModifyDNResponse; +- asn1_start_tag(data, tag); +- ldap_decode_response(msg, data, r); +- asn1_end_tag(data); ++ if (!asn1_start_tag(data, tag)) goto prot_err; ++ if (!ldap_decode_response(msg, data, r)) goto prot_err; ++ if (!asn1_end_tag(data)) goto prot_err; + break; + } + + case ASN1_APPLICATION(LDAP_TAG_CompareRequest): { + struct ldap_CompareRequest *r = &msg->r.CompareRequest; + msg->type = LDAP_TAG_CompareRequest; +- asn1_start_tag(data, +- ASN1_APPLICATION(LDAP_TAG_CompareRequest)); +- asn1_read_OctetString_talloc(msg, data, &r->dn); +- asn1_start_tag(data, ASN1_SEQUENCE(0)); +- asn1_read_OctetString_talloc(msg, data, &r->attribute); +- asn1_read_OctetString(data, msg, &r->value); ++ if (!asn1_start_tag(data, ++ ASN1_APPLICATION(LDAP_TAG_CompareRequest))) goto prot_err; ++ if (!asn1_read_OctetString_talloc(msg, data, &r->dn)) goto prot_err; ++ if (!asn1_start_tag(data, ASN1_SEQUENCE(0))) goto prot_err; ++ if (!asn1_read_OctetString_talloc(msg, data, &r->attribute)) goto prot_err; ++ if (!asn1_read_OctetString(data, msg, &r->value)) goto prot_err; + if (r->value.data) { + talloc_steal(msg, r->value.data); + } +- asn1_end_tag(data); +- asn1_end_tag(data); ++ if (!asn1_end_tag(data)) goto prot_err; ++ if (!asn1_end_tag(data)) goto prot_err; + break; + } + + case ASN1_APPLICATION(LDAP_TAG_CompareResponse): { + struct ldap_Result *r = &msg->r.CompareResponse; + msg->type = LDAP_TAG_CompareResponse; +- asn1_start_tag(data, tag); +- ldap_decode_response(msg, data, r); +- asn1_end_tag(data); ++ if (!asn1_start_tag(data, tag)) goto prot_err; ++ if (!ldap_decode_response(msg, data, r)) goto prot_err; ++ if (!asn1_end_tag(data)) goto prot_err; + break; + } + + case ASN1_APPLICATION_SIMPLE(LDAP_TAG_AbandonRequest): { + struct ldap_AbandonRequest *r = &msg->r.AbandonRequest; + msg->type = LDAP_TAG_AbandonRequest; +- asn1_start_tag(data, tag); +- asn1_read_implicit_Integer(data, &r->messageid); +- asn1_end_tag(data); ++ if (!asn1_start_tag(data, tag)) goto prot_err; ++ if (!asn1_read_implicit_Integer(data, &r->messageid)) goto prot_err; ++ if (!asn1_end_tag(data)) goto prot_err; + break; + } + +@@ -1482,9 +1484,9 @@ _PUBLIC_ NTSTATUS ldap_decode(struct asn1_data *data, + DATA_BLOB tmp_blob = data_blob(NULL, 0); + + msg->type = LDAP_TAG_ExtendedRequest; +- asn1_start_tag(data,tag); ++ if (!asn1_start_tag(data,tag)) goto prot_err; + if (!asn1_read_ContextSimple(data, 0, &tmp_blob)) { +- return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); ++ goto prot_err; + } + r->oid = blob2string_talloc(msg, tmp_blob); + data_blob_free(&tmp_blob); +@@ -1493,7 +1495,7 @@ _PUBLIC_ NTSTATUS ldap_decode(struct asn1_data *data, + } + + if (asn1_peek_tag(data, ASN1_CONTEXT_SIMPLE(1))) { +- asn1_read_ContextSimple(data, 1, &tmp_blob); ++ if (!asn1_read_ContextSimple(data, 1, &tmp_blob)) goto prot_err; + r->value = talloc(msg, DATA_BLOB); + if (!r->value) { + return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); +@@ -1504,7 +1506,7 @@ _PUBLIC_ NTSTATUS ldap_decode(struct asn1_data *data, + r->value = NULL; + } + +- asn1_end_tag(data); ++ if (!asn1_end_tag(data)) goto prot_err; + break; + } + +@@ -1513,11 +1515,11 @@ _PUBLIC_ NTSTATUS ldap_decode(struct asn1_data *data, + DATA_BLOB tmp_blob = data_blob(NULL, 0); + + msg->type = LDAP_TAG_ExtendedResponse; +- asn1_start_tag(data, tag); +- ldap_decode_response(msg, data, &r->response); ++ if (!asn1_start_tag(data, tag)) goto prot_err; ++ if (!ldap_decode_response(msg, data, &r->response)) goto prot_err; + + if (asn1_peek_tag(data, ASN1_CONTEXT_SIMPLE(10))) { +- asn1_read_ContextSimple(data, 1, &tmp_blob); ++ if (!asn1_read_ContextSimple(data, 1, &tmp_blob)) goto prot_err; + r->oid = blob2string_talloc(msg, tmp_blob); + data_blob_free(&tmp_blob); + if (!r->oid) { +@@ -1528,7 +1530,7 @@ _PUBLIC_ NTSTATUS ldap_decode(struct asn1_data *data, + } + + if (asn1_peek_tag(data, ASN1_CONTEXT_SIMPLE(11))) { +- asn1_read_ContextSimple(data, 1, &tmp_blob); ++ if (!asn1_read_ContextSimple(data, 1, &tmp_blob)) goto prot_err; + r->value = talloc(msg, DATA_BLOB); + if (!r->value) { + return NT_STATUS_LDAP(LDAP_OPERATIONS_ERROR); +@@ -1539,11 +1541,11 @@ _PUBLIC_ NTSTATUS ldap_decode(struct asn1_data *data, + r->value = NULL; + } + +- asn1_end_tag(data); ++ if (!asn1_end_tag(data)) goto prot_err; + break; + } +- default: +- return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); ++ default: ++ goto prot_err; + } + + msg->controls = NULL; +@@ -1554,7 +1556,7 @@ _PUBLIC_ NTSTATUS ldap_decode(struct asn1_data *data, + struct ldb_control **ctrl = NULL; + bool *decoded = NULL; + +- asn1_start_tag(data, ASN1_CONTEXT(0)); ++ if (!asn1_start_tag(data, ASN1_CONTEXT(0))) goto prot_err; + + while (asn1_peek_tag(data, ASN1_SEQUENCE(0))) { + DATA_BLOB value; +@@ -1576,9 +1578,9 @@ _PUBLIC_ NTSTATUS ldap_decode(struct asn1_data *data, + } + + if (!ldap_decode_control_wrapper(ctrl[i], data, ctrl[i], &value)) { +- return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); ++ goto prot_err; + } +- ++ + if (!ldap_decode_control_value(ctrl[i], value, + control_handlers, + ctrl[i])) { +@@ -1603,14 +1605,18 @@ _PUBLIC_ NTSTATUS ldap_decode(struct asn1_data *data, + msg->controls = ctrl; + msg->controls_decoded = decoded; + +- asn1_end_tag(data); ++ if (!asn1_end_tag(data)) goto prot_err; + } + +- asn1_end_tag(data); ++ if (!asn1_end_tag(data)) goto prot_err; + if ((data->has_error) || (data->nesting != NULL)) { + return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); + } + return NT_STATUS_OK; ++ ++ prot_err: ++ ++ return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR); + }",1224,1555,2048 +15432,"error::Error GLES2DecoderImpl::HandleTexSubImage2D( + uint32_t immediate_data_size, const volatile void* cmd_data) { + const char* func_name = ""glTexSubImage2D""; + const volatile gles2::cmds::TexSubImage2D& c = + *static_cast(cmd_data); + TRACE_EVENT2(""gpu"", ""GLES2DecoderImpl::HandleTexSubImage2D"", + ""width"", c.width, ""height"", c.height); + GLboolean internal = static_cast(c.internal); + if (internal == GL_TRUE && texture_state_.tex_image_failed) + return error::kNoError; + + GLenum target = static_cast(c.target); + GLint level = static_cast(c.level); + GLint xoffset = static_cast(c.xoffset); + GLint yoffset = static_cast(c.yoffset); + GLsizei width = static_cast(c.width); + GLsizei height = static_cast(c.height); + GLenum format = static_cast(c.format); + GLenum type = static_cast(c.type); + uint32_t pixels_shm_id = static_cast(c.pixels_shm_id); + uint32_t pixels_shm_offset = static_cast(c.pixels_shm_offset); + + if (width < 0 || height < 0) { + LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, func_name, ""dimensions < 0""); + return error::kNoError; + } + + PixelStoreParams params; + Buffer* buffer = state_.bound_pixel_unpack_buffer.get(); + if (buffer) { + if (pixels_shm_id) + return error::kInvalidArguments; + if (buffer->GetMappedRange()) { + LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, func_name, + ""pixel unpack buffer should not be mapped to client memory""); + return error::kNoError; + } + params = state_.GetUnpackParams(ContextState::k2D); + } else { + if (!pixels_shm_id && pixels_shm_offset) + return error::kInvalidArguments; + params.alignment = state_.unpack_alignment; + } + uint32_t pixels_size; + uint32_t skip_size; + uint32_t padding; + if (!GLES2Util::ComputeImageDataSizesES3(width, height, 1, + format, type, + params, + &pixels_size, + nullptr, + nullptr, + &skip_size, + &padding)) { + return error::kOutOfBounds; + } + DCHECK_EQ(0u, skip_size); + + const void* pixels; + if (pixels_shm_id) { + pixels = GetSharedMemoryAs( + pixels_shm_id, pixels_shm_offset, pixels_size); + if (!pixels) + return error::kOutOfBounds; + } else { + DCHECK(buffer || !pixels_shm_offset); + pixels = reinterpret_cast(pixels_shm_offset); + } + + TextureManager::DoTexSubImageArguments args = { + target, level, xoffset, yoffset, 0, width, height, 1, + format, type, pixels, pixels_size, padding, + TextureManager::DoTexSubImageArguments::kTexSubImage2D}; + texture_manager()->ValidateAndDoTexSubImage( + this, &texture_state_, &state_, error_state_.get(), &framebuffer_state_, + func_name, args); + + ExitCommandProcessingEarly(); + return error::kNoError; +} +",0,"error::Error GLES2DecoderImpl::HandleTexSubImage2D( + uint32_t immediate_data_size, const volatile void* cmd_data) { + const char* func_name = ""glTexSubImage2D""; + const volatile gles2::cmds::TexSubImage2D& c = + *static_cast(cmd_data); + TRACE_EVENT2(""gpu"", ""GLES2DecoderImpl::HandleTexSubImage2D"", + ""width"", c.width, ""height"", c.height); + GLboolean internal = static_cast(c.internal); + if (internal == GL_TRUE && texture_state_.tex_image_failed) + return error::kNoError; + + GLenum target = static_cast(c.target); + GLint level = static_cast(c.level); + GLint xoffset = static_cast(c.xoffset); + GLint yoffset = static_cast(c.yoffset); + GLsizei width = static_cast(c.width); + GLsizei height = static_cast(c.height); + GLenum format = static_cast(c.format); + GLenum type = static_cast(c.type); + uint32_t pixels_shm_id = static_cast(c.pixels_shm_id); + uint32_t pixels_shm_offset = static_cast(c.pixels_shm_offset); + + if (width < 0 || height < 0) { + LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, func_name, ""dimensions < 0""); + return error::kNoError; + } + + PixelStoreParams params; + Buffer* buffer = state_.bound_pixel_unpack_buffer.get(); + if (buffer) { + if (pixels_shm_id) + return error::kInvalidArguments; + if (buffer->GetMappedRange()) { + LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, func_name, + ""pixel unpack buffer should not be mapped to client memory""); + return error::kNoError; + } + params = state_.GetUnpackParams(ContextState::k2D); + } else { + if (!pixels_shm_id && pixels_shm_offset) + return error::kInvalidArguments; + params.alignment = state_.unpack_alignment; + } + uint32_t pixels_size; + uint32_t skip_size; + uint32_t padding; + if (!GLES2Util::ComputeImageDataSizesES3(width, height, 1, + format, type, + params, + &pixels_size, + nullptr, + nullptr, + &skip_size, + &padding)) { + return error::kOutOfBounds; + } + DCHECK_EQ(0u, skip_size); + + const void* pixels; + if (pixels_shm_id) { + pixels = GetSharedMemoryAs( + pixels_shm_id, pixels_shm_offset, pixels_size); + if (!pixels) + return error::kOutOfBounds; + } else { + DCHECK(buffer || !pixels_shm_offset); + pixels = reinterpret_cast(pixels_shm_offset); + } + + TextureManager::DoTexSubImageArguments args = { + target, level, xoffset, yoffset, 0, width, height, 1, + format, type, pixels, pixels_size, padding, + TextureManager::DoTexSubImageArguments::kTexSubImage2D}; + texture_manager()->ValidateAndDoTexSubImage( + this, &texture_state_, &state_, error_state_.get(), &framebuffer_state_, + func_name, args); + + ExitCommandProcessingEarly(); + return error::kNoError; +} +","@@ -17209,6 +17209,13 @@ error::Error GLES2DecoderImpl::HandleBeginQueryEXT( + return error::kNoError; + } + break; ++ case GL_PROGRAM_COMPLETION_QUERY_CHROMIUM: ++ if (!features().chromium_completion_query) { ++ LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, ""glBeginQueryEXT"", ++ ""not enabled for program completion queries""); ++ return error::kNoError; ++ } ++ break; + case GL_SAMPLES_PASSED_ARB: + if (!features().occlusion_query) { + LOCAL_SET_GL_ERROR(",776,1107,2048 +2736,"static int tpacket_fill_skb(struct packet_sock *po, struct sk_buff *skb, + void *frame, struct net_device *dev, int size_max, + __be16 proto, unsigned char *addr) +{ + union { + struct tpacket_hdr *h1; + struct tpacket2_hdr *h2; + void *raw; + } ph; + int to_write, offset, len, tp_len, nr_frags, len_max; + struct socket *sock = po->sk.sk_socket; + struct page *page; + void *data; + int err; + + ph.raw = frame; + + skb->protocol = proto; + skb->dev = dev; + skb->priority = po->sk.sk_priority; + skb->mark = po->sk.sk_mark; + skb_shinfo(skb)->destructor_arg = ph.raw; + + switch (po->tp_version) { + 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; + } + + skb_reserve(skb, LL_RESERVED_SPACE(dev)); + skb_reset_network_header(skb); + + data = ph.raw + po->tp_hdrlen - sizeof(struct sockaddr_ll); + 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 (dev->hard_header_len) { + /* net device doesn't like empty head */ + if (unlikely(tp_len <= dev->hard_header_len)) { + pr_err(""packet size is too short (%d < %d)\n"", + tp_len, dev->hard_header_len); + return -EINVAL; + } + + skb_push(skb, dev->hard_header_len); + err = skb_store_bits(skb, 0, data, + dev->hard_header_len); + if (unlikely(err)) + return err; + + data += dev->hard_header_len; + to_write -= dev->hard_header_len; + } + + err = -EFAULT; + 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; + atomic_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); + } + + return tp_len; +} +",0,"static int tpacket_fill_skb(struct packet_sock *po, struct sk_buff *skb, + void *frame, struct net_device *dev, int size_max, + __be16 proto, unsigned char *addr) +{ + union { + struct tpacket_hdr *h1; + struct tpacket2_hdr *h2; + void *raw; + } ph; + int to_write, offset, len, tp_len, nr_frags, len_max; + struct socket *sock = po->sk.sk_socket; + struct page *page; + void *data; + int err; + + ph.raw = frame; + + skb->protocol = proto; + skb->dev = dev; + skb->priority = po->sk.sk_priority; + skb->mark = po->sk.sk_mark; + skb_shinfo(skb)->destructor_arg = ph.raw; + + switch (po->tp_version) { + 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; + } + + skb_reserve(skb, LL_RESERVED_SPACE(dev)); + skb_reset_network_header(skb); + + data = ph.raw + po->tp_hdrlen - sizeof(struct sockaddr_ll); + 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 (dev->hard_header_len) { + /* net device doesn't like empty head */ + if (unlikely(tp_len <= dev->hard_header_len)) { + pr_err(""packet size is too short (%d < %d)\n"", + tp_len, dev->hard_header_len); + return -EINVAL; + } + + skb_push(skb, dev->hard_header_len); + err = skb_store_bits(skb, 0, data, + dev->hard_header_len); + if (unlikely(err)) + return err; + + data += dev->hard_header_len; + to_write -= dev->hard_header_len; + } + + err = -EFAULT; + 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; + atomic_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); + } + + return tp_len; +} +","@@ -804,6 +804,7 @@ static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev, + } else { + h.h2->tp_vlan_tci = 0; + } ++ h.h2->tp_padding = 0; + hdrlen = sizeof(*h.h2); + break; + default: +@@ -1736,6 +1737,7 @@ static int packet_recvmsg(struct kiocb *iocb, struct socket *sock, + } else { + aux.tp_vlan_tci = 0; + } ++ aux.tp_padding = 0; + put_cmsg(msg, SOL_PACKET, PACKET_AUXDATA, sizeof(aux), &aux); + } + ",717,1048,2048 +6927,"int ssl3_read_n(SSL *s, int n, int max, int extend, int clearold) +{ + /* + * If extend == 0, obtain new n-byte packet; if extend == 1, increase + * packet by another n bytes. The packet will be in the sub-array of + * s->s3->rbuf.buf specified by s->packet and s->packet_length. (If + * s->rlayer.read_ahead is set, 'max' bytes may be stored in rbuf [plus + * s->packet_length bytes if extend == 1].) + * if clearold == 1, move the packet to the start of the buffer; if + * clearold == 0 then leave any old packets where they were + */ + int i, len, left; + size_t align = 0; + unsigned char *pkt; + SSL3_BUFFER *rb; + + if (n <= 0) + return n; + + rb = &s->rlayer.rbuf; + if (rb->buf == NULL) + if (!ssl3_setup_read_buffer(s)) + return -1; + + left = rb->left; +#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0 + align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH; + align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD); +#endif + + if (!extend) { + /* start with empty packet ... */ + if (left == 0) + rb->offset = align; + else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) { + /* + * check if next packet length is large enough to justify payload + * alignment... + */ + pkt = rb->buf + rb->offset; + if (pkt[0] == SSL3_RT_APPLICATION_DATA + && (pkt[3] << 8 | pkt[4]) >= 128) { + /* + * Note that even if packet is corrupted and its length field + * is insane, we can only be led to wrong decision about + * whether memmove will occur or not. Header values has no + * effect on memmove arguments and therefore no buffer + * overrun can be triggered. + */ + memmove(rb->buf + align, pkt, left); + rb->offset = align; + } + } + s->rlayer.packet = rb->buf + rb->offset; + s->rlayer.packet_length = 0; + /* ... now we can act as if 'extend' was set */ + } + + len = s->rlayer.packet_length; + pkt = rb->buf + align; + /* + * Move any available bytes to front of buffer: 'len' bytes already + * pointed to by 'packet', 'left' extra ones at the end + */ + if (s->rlayer.packet != pkt && clearold == 1) { + memmove(pkt, s->rlayer.packet, len + left); + s->rlayer.packet = pkt; + rb->offset = len + align; + } + + /* + * For DTLS/UDP reads should not span multiple packets because the read + * operation returns the whole packet at once (as long as it fits into + * the buffer). + */ + if (SSL_IS_DTLS(s)) { + if (left == 0 && extend) + return 0; + if (left > 0 && n > left) + n = left; + } + + /* if there is enough in the buffer from a previous read, take some */ + if (left >= n) { + s->rlayer.packet_length += n; + rb->left = left - n; + rb->offset += n; + return (n); + } + + /* else we need to read more data */ + + if (n > (int)(rb->len - rb->offset)) { /* does not happen */ + SSLerr(SSL_F_SSL3_READ_N, ERR_R_INTERNAL_ERROR); + return -1; + } + + /* We always act like read_ahead is set for DTLS */ + if (!s->rlayer.read_ahead && !SSL_IS_DTLS(s)) + /* ignore max parameter */ + max = n; + else { + if (max < n) + max = n; + if (max > (int)(rb->len - rb->offset)) + max = rb->len - rb->offset; + } + + while (left < n) { + /* + * Now we have len+left bytes at the front of s->s3->rbuf.buf and + * need to read in more until we have len+n (up to len+max if + * possible) + */ + + clear_sys_error(); + if (s->rbio != NULL) { + s->rwstate = SSL_READING; + i = BIO_read(s->rbio, pkt + len + left, max - left); + } else { + SSLerr(SSL_F_SSL3_READ_N, SSL_R_READ_BIO_NOT_SET); + i = -1; + } + + if (i <= 0) { + rb->left = left; + if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s)) + if (len + left == 0) + ssl3_release_read_buffer(s); + return i; + } + left += i; + /* + * reads should *never* span multiple packets for DTLS because the + * underlying transport protocol is message oriented as opposed to + * byte oriented as in the TLS case. + */ + if (SSL_IS_DTLS(s)) { + if (n > left) + n = left; /* makes the while condition false */ + } + } + + /* done reading, now the book-keeping */ + rb->offset += n; + rb->left = left - n; + s->rlayer.packet_length += n; + s->rwstate = SSL_NOTHING; + return (n); +} +",0,"int ssl3_read_n(SSL *s, int n, int max, int extend, int clearold) +{ + /* + * If extend == 0, obtain new n-byte packet; if extend == 1, increase + * packet by another n bytes. The packet will be in the sub-array of + * s->s3->rbuf.buf specified by s->packet and s->packet_length. (If + * s->rlayer.read_ahead is set, 'max' bytes may be stored in rbuf [plus + * s->packet_length bytes if extend == 1].) + * if clearold == 1, move the packet to the start of the buffer; if + * clearold == 0 then leave any old packets where they were + */ + int i, len, left; + size_t align = 0; + unsigned char *pkt; + SSL3_BUFFER *rb; + + if (n <= 0) + return n; + + rb = &s->rlayer.rbuf; + if (rb->buf == NULL) + if (!ssl3_setup_read_buffer(s)) + return -1; + + left = rb->left; +#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0 + align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH; + align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD); +#endif + + if (!extend) { + /* start with empty packet ... */ + if (left == 0) + rb->offset = align; + else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) { + /* + * check if next packet length is large enough to justify payload + * alignment... + */ + pkt = rb->buf + rb->offset; + if (pkt[0] == SSL3_RT_APPLICATION_DATA + && (pkt[3] << 8 | pkt[4]) >= 128) { + /* + * Note that even if packet is corrupted and its length field + * is insane, we can only be led to wrong decision about + * whether memmove will occur or not. Header values has no + * effect on memmove arguments and therefore no buffer + * overrun can be triggered. + */ + memmove(rb->buf + align, pkt, left); + rb->offset = align; + } + } + s->rlayer.packet = rb->buf + rb->offset; + s->rlayer.packet_length = 0; + /* ... now we can act as if 'extend' was set */ + } + + len = s->rlayer.packet_length; + pkt = rb->buf + align; + /* + * Move any available bytes to front of buffer: 'len' bytes already + * pointed to by 'packet', 'left' extra ones at the end + */ + if (s->rlayer.packet != pkt && clearold == 1) { + memmove(pkt, s->rlayer.packet, len + left); + s->rlayer.packet = pkt; + rb->offset = len + align; + } + + /* + * For DTLS/UDP reads should not span multiple packets because the read + * operation returns the whole packet at once (as long as it fits into + * the buffer). + */ + if (SSL_IS_DTLS(s)) { + if (left == 0 && extend) + return 0; + if (left > 0 && n > left) + n = left; + } + + /* if there is enough in the buffer from a previous read, take some */ + if (left >= n) { + s->rlayer.packet_length += n; + rb->left = left - n; + rb->offset += n; + return (n); + } + + /* else we need to read more data */ + + if (n > (int)(rb->len - rb->offset)) { /* does not happen */ + SSLerr(SSL_F_SSL3_READ_N, ERR_R_INTERNAL_ERROR); + return -1; + } + + /* We always act like read_ahead is set for DTLS */ + if (!s->rlayer.read_ahead && !SSL_IS_DTLS(s)) + /* ignore max parameter */ + max = n; + else { + if (max < n) + max = n; + if (max > (int)(rb->len - rb->offset)) + max = rb->len - rb->offset; + } + + while (left < n) { + /* + * Now we have len+left bytes at the front of s->s3->rbuf.buf and + * need to read in more until we have len+n (up to len+max if + * possible) + */ + + clear_sys_error(); + if (s->rbio != NULL) { + s->rwstate = SSL_READING; + i = BIO_read(s->rbio, pkt + len + left, max - left); + } else { + SSLerr(SSL_F_SSL3_READ_N, SSL_R_READ_BIO_NOT_SET); + i = -1; + } + + if (i <= 0) { + rb->left = left; + if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_IS_DTLS(s)) + if (len + left == 0) + ssl3_release_read_buffer(s); + return i; + } + left += i; + /* + * reads should *never* span multiple packets for DTLS because the + * underlying transport protocol is message oriented as opposed to + * byte oriented as in the TLS case. + */ + if (SSL_IS_DTLS(s)) { + if (n > left) + n = left; /* makes the while condition false */ + } + } + + /* done reading, now the book-keeping */ + rb->offset += n; + rb->left = left - n; + s->rlayer.packet_length += n; + s->rwstate = SSL_NOTHING; + return (n); +} +","@@ -395,7 +395,7 @@ int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len) + if (type == SSL3_RT_APPLICATION_DATA && + u_len >= 4 * (max_send_fragment = s->max_send_fragment) && + s->compress == NULL && s->msg_callback == NULL && +- !SSL_USE_ETM(s) && SSL_USE_EXPLICIT_IV(s) && ++ !SSL_WRITE_ETM(s) && SSL_USE_EXPLICIT_IV(s) && + EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_write_ctx)) & + EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) { + unsigned char aad[13]; +@@ -791,7 +791,7 @@ int do_ssl3_write(SSL *s, int type, const unsigned char *buf, + * wb->buf + */ + +- if (!SSL_USE_ETM(s) && mac_size != 0) { ++ if (!SSL_WRITE_ETM(s) && mac_size != 0) { + if (s->method->ssl3_enc->mac(s, &wr[j], + &(outbuf[j][wr[j].length + eivlen]), + 1) < 0) +@@ -814,7 +814,7 @@ int do_ssl3_write(SSL *s, int type, const unsigned char *buf, + goto err; + + for (j = 0; j < numpipes; j++) { +- if (SSL_USE_ETM(s) && mac_size != 0) { ++ if (SSL_WRITE_ETM(s) && mac_size != 0) { + if (s->method->ssl3_enc->mac(s, &wr[j], + outbuf[j] + wr[j].length, 1) < 0) + goto err;",1288,1619,2048 +4878,"tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t tile, T2P* t2p, TIFF* output){ + + tsize_t written=0; + char buffer[32]; + int buflen=0; + + if(t2p->pdf_compression==T2P_COMPRESS_NONE){ + return(written); + } + written += t2pWriteFile(output, (tdata_t) ""/Filter "", 8); + switch(t2p->pdf_compression){ +#ifdef CCITT_SUPPORT + case T2P_COMPRESS_G4: + written += t2pWriteFile(output, (tdata_t) ""/CCITTFaxDecode "", 16); + written += t2pWriteFile(output, (tdata_t) ""/DecodeParms "", 13); + written += t2pWriteFile(output, (tdata_t) ""<< /K -1 "", 9); + if(tile==0){ + written += t2pWriteFile(output, (tdata_t) ""/Columns "", 9); + buflen=snprintf(buffer, sizeof(buffer), ""%lu"", + (unsigned long)t2p->tiff_width); + check_snprintf_ret(t2p, buflen, buffer); + written += t2pWriteFile(output, (tdata_t) buffer, buflen); + written += t2pWriteFile(output, (tdata_t) "" /Rows "", 7); + buflen=snprintf(buffer, sizeof(buffer), ""%lu"", + (unsigned long)t2p->tiff_length); + check_snprintf_ret(t2p, buflen, buffer); + written += t2pWriteFile(output, (tdata_t) buffer, buflen); + } else { + if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){ + written += t2pWriteFile(output, (tdata_t) ""/Columns "", 9); + buflen=snprintf(buffer, sizeof(buffer), ""%lu"", + (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); + check_snprintf_ret(t2p, buflen, buffer); + written += t2pWriteFile(output, (tdata_t) buffer, buflen); + } else { + written += t2pWriteFile(output, (tdata_t) ""/Columns "", 9); + buflen=snprintf(buffer, sizeof(buffer), ""%lu"", + (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); + check_snprintf_ret(t2p, buflen, buffer); + written += t2pWriteFile(output, (tdata_t) buffer, buflen); + } + if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){ + written += t2pWriteFile(output, (tdata_t) "" /Rows "", 7); + buflen=snprintf(buffer, sizeof(buffer), ""%lu"", + (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); + check_snprintf_ret(t2p, buflen, buffer); + written += t2pWriteFile(output, (tdata_t) buffer, buflen); + } else { + written += t2pWriteFile(output, (tdata_t) "" /Rows "", 7); + buflen=snprintf(buffer, sizeof(buffer), ""%lu"", + (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); + check_snprintf_ret(t2p, buflen, buffer); + written += t2pWriteFile(output, (tdata_t) buffer, buflen); + } + } + if(t2p->pdf_switchdecode == 0){ + written += t2pWriteFile(output, (tdata_t) "" /BlackIs1 true "", 16); + } + written += t2pWriteFile(output, (tdata_t) "">>\n"", 3); + break; +#endif +#ifdef JPEG_SUPPORT + case T2P_COMPRESS_JPEG: + written += t2pWriteFile(output, (tdata_t) ""/DCTDecode "", 11); + + if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR) { + written += t2pWriteFile(output, (tdata_t) ""/DecodeParms "", 13); + written += t2pWriteFile(output, (tdata_t) ""<< /ColorTransform 1 >>\n"", 24); + } + break; +#endif +#ifdef ZIP_SUPPORT + case T2P_COMPRESS_ZIP: + written += t2pWriteFile(output, (tdata_t) ""/FlateDecode "", 13); + if(t2p->pdf_compressionquality%100){ + written += t2pWriteFile(output, (tdata_t) ""/DecodeParms "", 13); + written += t2pWriteFile(output, (tdata_t) ""<< /Predictor "", 14); + buflen=snprintf(buffer, sizeof(buffer), ""%u"", t2p->pdf_compressionquality%100); + check_snprintf_ret(t2p, buflen, buffer); + written += t2pWriteFile(output, (tdata_t) buffer, buflen); + written += t2pWriteFile(output, (tdata_t) "" /Columns "", 10); + buflen = snprintf(buffer, sizeof(buffer), ""%lu"", + (unsigned long)t2p->tiff_width); + check_snprintf_ret(t2p, buflen, buffer); + written += t2pWriteFile(output, (tdata_t) buffer, buflen); + written += t2pWriteFile(output, (tdata_t) "" /Colors "", 9); + buflen=snprintf(buffer, sizeof(buffer), ""%u"", t2p->tiff_samplesperpixel); + check_snprintf_ret(t2p, buflen, buffer); + written += t2pWriteFile(output, (tdata_t) buffer, buflen); + written += t2pWriteFile(output, (tdata_t) "" /BitsPerComponent "", 19); + buflen=snprintf(buffer, sizeof(buffer), ""%u"", t2p->tiff_bitspersample); + check_snprintf_ret(t2p, buflen, buffer); + written += t2pWriteFile(output, (tdata_t) buffer, buflen); + written += t2pWriteFile(output, (tdata_t) "">>\n"", 3); + } + break; +#endif + default: + break; + } + + return(written); +} +",0,"tsize_t t2p_write_pdf_xobject_stream_filter(ttile_t tile, T2P* t2p, TIFF* output){ + + tsize_t written=0; + char buffer[32]; + int buflen=0; + + if(t2p->pdf_compression==T2P_COMPRESS_NONE){ + return(written); + } + written += t2pWriteFile(output, (tdata_t) ""/Filter "", 8); + switch(t2p->pdf_compression){ +#ifdef CCITT_SUPPORT + case T2P_COMPRESS_G4: + written += t2pWriteFile(output, (tdata_t) ""/CCITTFaxDecode "", 16); + written += t2pWriteFile(output, (tdata_t) ""/DecodeParms "", 13); + written += t2pWriteFile(output, (tdata_t) ""<< /K -1 "", 9); + if(tile==0){ + written += t2pWriteFile(output, (tdata_t) ""/Columns "", 9); + buflen=snprintf(buffer, sizeof(buffer), ""%lu"", + (unsigned long)t2p->tiff_width); + check_snprintf_ret(t2p, buflen, buffer); + written += t2pWriteFile(output, (tdata_t) buffer, buflen); + written += t2pWriteFile(output, (tdata_t) "" /Rows "", 7); + buflen=snprintf(buffer, sizeof(buffer), ""%lu"", + (unsigned long)t2p->tiff_length); + check_snprintf_ret(t2p, buflen, buffer); + written += t2pWriteFile(output, (tdata_t) buffer, buflen); + } else { + if(t2p_tile_is_right_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){ + written += t2pWriteFile(output, (tdata_t) ""/Columns "", 9); + buflen=snprintf(buffer, sizeof(buffer), ""%lu"", + (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilewidth); + check_snprintf_ret(t2p, buflen, buffer); + written += t2pWriteFile(output, (tdata_t) buffer, buflen); + } else { + written += t2pWriteFile(output, (tdata_t) ""/Columns "", 9); + buflen=snprintf(buffer, sizeof(buffer), ""%lu"", + (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilewidth); + check_snprintf_ret(t2p, buflen, buffer); + written += t2pWriteFile(output, (tdata_t) buffer, buflen); + } + if(t2p_tile_is_bottom_edge(t2p->tiff_tiles[t2p->pdf_page], tile-1)==0){ + written += t2pWriteFile(output, (tdata_t) "" /Rows "", 7); + buflen=snprintf(buffer, sizeof(buffer), ""%lu"", + (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_tilelength); + check_snprintf_ret(t2p, buflen, buffer); + written += t2pWriteFile(output, (tdata_t) buffer, buflen); + } else { + written += t2pWriteFile(output, (tdata_t) "" /Rows "", 7); + buflen=snprintf(buffer, sizeof(buffer), ""%lu"", + (unsigned long)t2p->tiff_tiles[t2p->pdf_page].tiles_edgetilelength); + check_snprintf_ret(t2p, buflen, buffer); + written += t2pWriteFile(output, (tdata_t) buffer, buflen); + } + } + if(t2p->pdf_switchdecode == 0){ + written += t2pWriteFile(output, (tdata_t) "" /BlackIs1 true "", 16); + } + written += t2pWriteFile(output, (tdata_t) "">>\n"", 3); + break; +#endif +#ifdef JPEG_SUPPORT + case T2P_COMPRESS_JPEG: + written += t2pWriteFile(output, (tdata_t) ""/DCTDecode "", 11); + + if(t2p->tiff_photometric != PHOTOMETRIC_YCBCR) { + written += t2pWriteFile(output, (tdata_t) ""/DecodeParms "", 13); + written += t2pWriteFile(output, (tdata_t) ""<< /ColorTransform 1 >>\n"", 24); + } + break; +#endif +#ifdef ZIP_SUPPORT + case T2P_COMPRESS_ZIP: + written += t2pWriteFile(output, (tdata_t) ""/FlateDecode "", 13); + if(t2p->pdf_compressionquality%100){ + written += t2pWriteFile(output, (tdata_t) ""/DecodeParms "", 13); + written += t2pWriteFile(output, (tdata_t) ""<< /Predictor "", 14); + buflen=snprintf(buffer, sizeof(buffer), ""%u"", t2p->pdf_compressionquality%100); + check_snprintf_ret(t2p, buflen, buffer); + written += t2pWriteFile(output, (tdata_t) buffer, buflen); + written += t2pWriteFile(output, (tdata_t) "" /Columns "", 10); + buflen = snprintf(buffer, sizeof(buffer), ""%lu"", + (unsigned long)t2p->tiff_width); + check_snprintf_ret(t2p, buflen, buffer); + written += t2pWriteFile(output, (tdata_t) buffer, buflen); + written += t2pWriteFile(output, (tdata_t) "" /Colors "", 9); + buflen=snprintf(buffer, sizeof(buffer), ""%u"", t2p->tiff_samplesperpixel); + check_snprintf_ret(t2p, buflen, buffer); + written += t2pWriteFile(output, (tdata_t) buffer, buflen); + written += t2pWriteFile(output, (tdata_t) "" /BitsPerComponent "", 19); + buflen=snprintf(buffer, sizeof(buffer), ""%u"", t2p->tiff_bitspersample); + check_snprintf_ret(t2p, buflen, buffer); + written += t2pWriteFile(output, (tdata_t) buffer, buflen); + written += t2pWriteFile(output, (tdata_t) "">>\n"", 3); + } + break; +#endif + default: + break; + } + + return(written); +} +","@@ -286,7 +286,7 @@ tsize_t t2p_readwrite_pdf_image_tile(T2P*, TIFF*, TIFF*, ttile_t); + int t2p_process_ojpeg_tables(T2P*, TIFF*); + #endif + #ifdef JPEG_SUPPORT +-int t2p_process_jpeg_strip(unsigned char*, tsize_t*, unsigned char*, tsize_t*, tstrip_t, uint32); ++int t2p_process_jpeg_strip(unsigned char*, tsize_t*, unsigned char*, tsize_t, tsize_t*, tstrip_t, uint32); + #endif + void t2p_tile_collapse_left(tdata_t, tsize_t, uint32, uint32, uint32); + void t2p_write_advance_directory(T2P*, TIFF*); +@@ -2408,7 +2408,8 @@ tsize_t t2p_readwrite_pdf_image(T2P* t2p, TIFF* input, TIFF* output){ + if(!t2p_process_jpeg_strip( + stripbuffer, + &striplength, +- buffer, ++ buffer, ++ t2p->tiff_datasize, + &bufferoffset, + i, + t2p->tiff_length)){ +@@ -3439,6 +3440,7 @@ int t2p_process_jpeg_strip( + unsigned char* strip, + tsize_t* striplength, + unsigned char* buffer, ++ tsize_t buffersize, + tsize_t* bufferoffset, + tstrip_t no, + uint32 height){ +@@ -3473,6 +3475,8 @@ int t2p_process_jpeg_strip( + } + switch( strip[i] ){ + case 0xd8: /* SOI - start of image */ ++ if( *bufferoffset + 2 > buffersize ) ++ return(0); + _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), 2); + *bufferoffset+=2; + break; +@@ -3482,12 +3486,18 @@ int t2p_process_jpeg_strip( + case 0xc9: /* SOF9 */ + case 0xca: /* SOF10 */ + if(no==0){ ++ if( *bufferoffset + datalen + 2 + 6 > buffersize ) ++ return(0); + _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); ++ if( *bufferoffset + 9 >= buffersize ) ++ return(0); + ncomp = buffer[*bufferoffset+9]; + if (ncomp < 1 || ncomp > 4) + return(0); + v_samp=1; + h_samp=1; ++ if( *bufferoffset + 11 + 3*(ncomp-1) >= buffersize ) ++ return(0); + for(j=0;j>4) > h_samp) +@@ -3519,20 +3529,28 @@ int t2p_process_jpeg_strip( + break; + case 0xc4: /* DHT */ + case 0xdb: /* DQT */ ++ if( *bufferoffset + datalen + 2 > buffersize ) ++ return(0); + _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); + *bufferoffset+=datalen+2; + break; + case 0xda: /* SOS */ + if(no==0){ ++ if( *bufferoffset + datalen + 2 > buffersize ) ++ return(0); + _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); + *bufferoffset+=datalen+2; + } else { ++ if( *bufferoffset + 2 > buffersize ) ++ return(0); + buffer[(*bufferoffset)++]=0xff; + buffer[(*bufferoffset)++]= + (unsigned char)(0xd0 | ((no-1)%8)); + } + i += datalen + 1; + /* copy remainder of strip */ ++ if( *bufferoffset + *striplength - i > buffersize ) ++ return(0); + _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i]), *striplength - i); + *bufferoffset+= *striplength - i; + return(1);",1470,1801,2048 +5199,"tcp_collapse(struct sock *sk, struct sk_buff_head *list, + struct sk_buff *head, struct sk_buff *tail, + u32 start, u32 end) +{ + struct sk_buff *skb, *n; + bool end_of_skbs; + + /* First, check that queue is collapsible and find + * the point where collapsing can be useful. */ + skb = head; +restart: + end_of_skbs = true; + skb_queue_walk_from_safe(list, skb, n) { + if (skb == tail) + break; + /* No new bits? It is possible on ofo queue. */ + if (!before(start, TCP_SKB_CB(skb)->end_seq)) { + skb = tcp_collapse_one(sk, skb, list); + if (!skb) + break; + goto restart; + } + + /* The first skb to collapse is: + * - not SYN/FIN and + * - bloated or contains data before ""start"" or + * overlaps to the next one. + */ + if (!(TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN)) && + (tcp_win_from_space(skb->truesize) > skb->len || + before(TCP_SKB_CB(skb)->seq, start))) { + end_of_skbs = false; + break; + } + + if (!skb_queue_is_last(list, skb)) { + struct sk_buff *next = skb_queue_next(list, skb); + if (next != tail && + TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(next)->seq) { + end_of_skbs = false; + break; + } + } + + /* Decided to skip this, advance start seq. */ + start = TCP_SKB_CB(skb)->end_seq; + } + if (end_of_skbs || + (TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN))) + return; + + while (before(start, end)) { + int copy = min_t(int, SKB_MAX_ORDER(0, 0), end - start); + struct sk_buff *nskb; + + nskb = alloc_skb(copy, GFP_ATOMIC); + if (!nskb) + return; + + memcpy(nskb->cb, skb->cb, sizeof(skb->cb)); + TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(nskb)->end_seq = start; + __skb_queue_before(list, skb, nskb); + skb_set_owner_r(nskb, sk); + + /* Copy data, releasing collapsed skbs. */ + while (copy > 0) { + int offset = start - TCP_SKB_CB(skb)->seq; + int size = TCP_SKB_CB(skb)->end_seq - start; + + BUG_ON(offset < 0); + if (size > 0) { + size = min(copy, size); + if (skb_copy_bits(skb, offset, skb_put(nskb, size), size)) + BUG(); + TCP_SKB_CB(nskb)->end_seq += size; + copy -= size; + start += size; + } + if (!before(start, TCP_SKB_CB(skb)->end_seq)) { + skb = tcp_collapse_one(sk, skb, list); + if (!skb || + skb == tail || + (TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN))) + return; + } + } + } +} +",0,"tcp_collapse(struct sock *sk, struct sk_buff_head *list, + struct sk_buff *head, struct sk_buff *tail, + u32 start, u32 end) +{ + struct sk_buff *skb, *n; + bool end_of_skbs; + + /* First, check that queue is collapsible and find + * the point where collapsing can be useful. */ + skb = head; +restart: + end_of_skbs = true; + skb_queue_walk_from_safe(list, skb, n) { + if (skb == tail) + break; + /* No new bits? It is possible on ofo queue. */ + if (!before(start, TCP_SKB_CB(skb)->end_seq)) { + skb = tcp_collapse_one(sk, skb, list); + if (!skb) + break; + goto restart; + } + + /* The first skb to collapse is: + * - not SYN/FIN and + * - bloated or contains data before ""start"" or + * overlaps to the next one. + */ + if (!(TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN)) && + (tcp_win_from_space(skb->truesize) > skb->len || + before(TCP_SKB_CB(skb)->seq, start))) { + end_of_skbs = false; + break; + } + + if (!skb_queue_is_last(list, skb)) { + struct sk_buff *next = skb_queue_next(list, skb); + if (next != tail && + TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(next)->seq) { + end_of_skbs = false; + break; + } + } + + /* Decided to skip this, advance start seq. */ + start = TCP_SKB_CB(skb)->end_seq; + } + if (end_of_skbs || + (TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN))) + return; + + while (before(start, end)) { + int copy = min_t(int, SKB_MAX_ORDER(0, 0), end - start); + struct sk_buff *nskb; + + nskb = alloc_skb(copy, GFP_ATOMIC); + if (!nskb) + return; + + memcpy(nskb->cb, skb->cb, sizeof(skb->cb)); + TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(nskb)->end_seq = start; + __skb_queue_before(list, skb, nskb); + skb_set_owner_r(nskb, sk); + + /* Copy data, releasing collapsed skbs. */ + while (copy > 0) { + int offset = start - TCP_SKB_CB(skb)->seq; + int size = TCP_SKB_CB(skb)->end_seq - start; + + BUG_ON(offset < 0); + if (size > 0) { + size = min(copy, size); + if (skb_copy_bits(skb, offset, skb_put(nskb, size), size)) + BUG(); + TCP_SKB_CB(nskb)->end_seq += size; + copy -= size; + start += size; + } + if (!before(start, TCP_SKB_CB(skb)->end_seq)) { + skb = tcp_collapse_one(sk, skb, list); + if (!skb || + skb == tail || + (TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN))) + return; + } + } + } +} +","@@ -87,7 +87,7 @@ int sysctl_tcp_adv_win_scale __read_mostly = 1; + EXPORT_SYMBOL(sysctl_tcp_adv_win_scale); + + /* rfc5961 challenge ack rate limiting */ +-int sysctl_tcp_challenge_ack_limit = 100; ++int sysctl_tcp_challenge_ack_limit = 1000; + + int sysctl_tcp_stdurg __read_mostly; + int sysctl_tcp_rfc1337 __read_mostly; +@@ -3458,21 +3458,26 @@ static void tcp_send_challenge_ack(struct sock *sk, const struct sk_buff *skb) + static u32 challenge_timestamp; + static unsigned int challenge_count; + struct tcp_sock *tp = tcp_sk(sk); +- u32 now; ++ u32 count, now; + + /* First check our per-socket dupack rate limit. */ + if (tcp_oow_rate_limited(sock_net(sk), skb, + LINUX_MIB_TCPACKSKIPPEDCHALLENGE, + &tp->last_oow_ack_time)) + return; + +- /* Then check the check host-wide RFC 5961 rate limit. */ ++ /* Then check host-wide RFC 5961 rate limit. */ + now = jiffies / HZ; + if (now != challenge_timestamp) { ++ u32 half = (sysctl_tcp_challenge_ack_limit + 1) >> 1; ++ + challenge_timestamp = now; +- challenge_count = 0; ++ WRITE_ONCE(challenge_count, half + ++ prandom_u32_max(sysctl_tcp_challenge_ack_limit)); + } +- if (++challenge_count <= sysctl_tcp_challenge_ack_limit) { ++ count = READ_ONCE(challenge_count); ++ if (count > 0) { ++ WRITE_ONCE(challenge_count, count - 1); + NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPCHALLENGEACK); + tcp_send_ack(sk); + }",735,1066,2048 +736," cf2_glyphpath_computeIntersection( CF2_GlyphPath glyphpath, + const FT_Vector* u1, + const FT_Vector* u2, + const FT_Vector* v1, + const FT_Vector* v2, + FT_Vector* intersection ) + { + /* + * Let `u' be a zero-based vector from the first segment, `v' from the + * second segment. + * Let `w 'be the zero-based vector from `u1' to `v1'. + * `perp' is the `perpendicular dot product'; see + * http://mathworld.wolfram.com/PerpDotProduct.html. + * `s' is the parameter for the parametric line for the first segment + * (`u'). + * + * See notation in + * http://softsurfer.com/Archive/algorithm_0104/algorithm_0104B.htm. + * Calculations are done in 16.16, but must handle the squaring of + * line lengths in character space. We scale all vectors by 1/32 to + * avoid overflow. This allows values up to 4095 to be squared. The + * scale factor cancels in the divide. + * + * TODO: the scale factor could be computed from UnitsPerEm. + * + */ + +#define cf2_perp( a, b ) \ + ( FT_MulFix( a.x, b.y ) - FT_MulFix( a.y, b.x ) ) + + /* round and divide by 32 */ +#define CF2_CS_SCALE( x ) \ + ( ( (x) + 0x10 ) >> 5 ) + + FT_Vector u, v, w; /* scaled vectors */ + CF2_Fixed denominator, s; + + + u.x = CF2_CS_SCALE( u2->x - u1->x ); + u.y = CF2_CS_SCALE( u2->y - u1->y ); + v.x = CF2_CS_SCALE( v2->x - v1->x ); + v.y = CF2_CS_SCALE( v2->y - v1->y ); + w.x = CF2_CS_SCALE( v1->x - u1->x ); + w.y = CF2_CS_SCALE( v1->y - u1->y ); + + denominator = cf2_perp( u, v ); + + if ( denominator == 0 ) + return FALSE; /* parallel or coincident lines */ + + s = FT_DivFix( cf2_perp( w, v ), denominator ); + + intersection->x = u1->x + FT_MulFix( s, u2->x - u1->x ); + intersection->y = u1->y + FT_MulFix( s, u2->y - u1->y ); + + /* + * Special case snapping for horizontal and vertical lines. + * This cleans up intersections and reduces problems with winding + * order detection. + * Sample case is sbc cd KozGoPr6N-Medium.otf 20 16685. + * Note: these calculations are in character space. + * + */ + + if ( u1->x == u2->x && + cf2_fixedAbs( intersection->x - u1->x ) < glyphpath->snapThreshold ) + intersection->x = u1->x; + if ( u1->y == u2->y && + cf2_fixedAbs( intersection->y - u1->y ) < glyphpath->snapThreshold ) + intersection->y = u1->y; + + if ( v1->x == v2->x && + cf2_fixedAbs( intersection->x - v1->x ) < glyphpath->snapThreshold ) + intersection->x = v1->x; + if ( v1->y == v2->y && + cf2_fixedAbs( intersection->y - v1->y ) < glyphpath->snapThreshold ) + intersection->y = v1->y; + + /* limit the intersection distance from midpoint of u2 and v1 */ + if ( cf2_fixedAbs( intersection->x - ( u2->x + v1->x ) / 2 ) > + glyphpath->miterLimit || + cf2_fixedAbs( intersection->y - ( u2->y + v1->y ) / 2 ) > + glyphpath->miterLimit ) + return FALSE; + + return TRUE; + } +",0," cf2_glyphpath_computeIntersection( CF2_GlyphPath glyphpath, + const FT_Vector* u1, + const FT_Vector* u2, + const FT_Vector* v1, + const FT_Vector* v2, + FT_Vector* intersection ) + { + /* + * Let `u' be a zero-based vector from the first segment, `v' from the + * second segment. + * Let `w 'be the zero-based vector from `u1' to `v1'. + * `perp' is the `perpendicular dot product'; see + * http://mathworld.wolfram.com/PerpDotProduct.html. + * `s' is the parameter for the parametric line for the first segment + * (`u'). + * + * See notation in + * http://softsurfer.com/Archive/algorithm_0104/algorithm_0104B.htm. + * Calculations are done in 16.16, but must handle the squaring of + * line lengths in character space. We scale all vectors by 1/32 to + * avoid overflow. This allows values up to 4095 to be squared. The + * scale factor cancels in the divide. + * + * TODO: the scale factor could be computed from UnitsPerEm. + * + */ + +#define cf2_perp( a, b ) \ + ( FT_MulFix( a.x, b.y ) - FT_MulFix( a.y, b.x ) ) + + /* round and divide by 32 */ +#define CF2_CS_SCALE( x ) \ + ( ( (x) + 0x10 ) >> 5 ) + + FT_Vector u, v, w; /* scaled vectors */ + CF2_Fixed denominator, s; + + + u.x = CF2_CS_SCALE( u2->x - u1->x ); + u.y = CF2_CS_SCALE( u2->y - u1->y ); + v.x = CF2_CS_SCALE( v2->x - v1->x ); + v.y = CF2_CS_SCALE( v2->y - v1->y ); + w.x = CF2_CS_SCALE( v1->x - u1->x ); + w.y = CF2_CS_SCALE( v1->y - u1->y ); + + denominator = cf2_perp( u, v ); + + if ( denominator == 0 ) + return FALSE; /* parallel or coincident lines */ + + s = FT_DivFix( cf2_perp( w, v ), denominator ); + + intersection->x = u1->x + FT_MulFix( s, u2->x - u1->x ); + intersection->y = u1->y + FT_MulFix( s, u2->y - u1->y ); + + /* + * Special case snapping for horizontal and vertical lines. + * This cleans up intersections and reduces problems with winding + * order detection. + * Sample case is sbc cd KozGoPr6N-Medium.otf 20 16685. + * Note: these calculations are in character space. + * + */ + + if ( u1->x == u2->x && + cf2_fixedAbs( intersection->x - u1->x ) < glyphpath->snapThreshold ) + intersection->x = u1->x; + if ( u1->y == u2->y && + cf2_fixedAbs( intersection->y - u1->y ) < glyphpath->snapThreshold ) + intersection->y = u1->y; + + if ( v1->x == v2->x && + cf2_fixedAbs( intersection->x - v1->x ) < glyphpath->snapThreshold ) + intersection->x = v1->x; + if ( v1->y == v2->y && + cf2_fixedAbs( intersection->y - v1->y ) < glyphpath->snapThreshold ) + intersection->y = v1->y; + + /* limit the intersection distance from midpoint of u2 and v1 */ + if ( cf2_fixedAbs( intersection->x - ( u2->x + v1->x ) / 2 ) > + glyphpath->miterLimit || + cf2_fixedAbs( intersection->y - ( u2->y + v1->y ) / 2 ) > + glyphpath->miterLimit ) + return FALSE; + + return TRUE; + } +","@@ -794,9 +794,12 @@ + maskPtr = cf2_hintmask_getMaskPtr( &tempHintMask ); + + /* use the hStem hints only, which are first in the mask */ +- /* TODO: compare this to cffhintmaskGetBitCount */ + bitCount = cf2_arrstack_size( hStemHintArray ); + ++ /* Defense-in-depth. Should never return here. */ ++ if ( bitCount > hintMask->bitCount ) ++ return; ++ + /* synthetic embox hints get highest priority */ + if ( font->blues.doEmBoxHints ) + {",983,1314,2048 +2488,"static int mpi_map_card(struct airo_info *ai, struct pci_dev *pci) +{ + unsigned long mem_start, mem_len, aux_start, aux_len; + int rc = -1; + int i; + dma_addr_t busaddroff; + unsigned char *vpackoff; + unsigned char __iomem *pciaddroff; + + mem_start = pci_resource_start(pci, 1); + mem_len = pci_resource_len(pci, 1); + aux_start = pci_resource_start(pci, 2); + aux_len = AUXMEMSIZE; + + if (!request_mem_region(mem_start, mem_len, DRV_NAME)) { + airo_print_err("""", ""Couldn't get region %x[%x]"", + (int)mem_start, (int)mem_len); + goto out; + } + if (!request_mem_region(aux_start, aux_len, DRV_NAME)) { + airo_print_err("""", ""Couldn't get region %x[%x]"", + (int)aux_start, (int)aux_len); + goto free_region1; + } + + ai->pcimem = ioremap(mem_start, mem_len); + if (!ai->pcimem) { + airo_print_err("""", ""Couldn't map region %x[%x]"", + (int)mem_start, (int)mem_len); + goto free_region2; + } + ai->pciaux = ioremap(aux_start, aux_len); + if (!ai->pciaux) { + airo_print_err("""", ""Couldn't map region %x[%x]"", + (int)aux_start, (int)aux_len); + goto free_memmap; + } + + /* Reserve PKTSIZE for each fid and 2K for the Rids */ + ai->shared = pci_alloc_consistent(pci, PCI_SHARED_LEN, &ai->shared_dma); + if (!ai->shared) { + airo_print_err("""", ""Couldn't alloc_consistent %d"", + PCI_SHARED_LEN); + goto free_auxmap; + } + + /* + * Setup descriptor RX, TX, CONFIG + */ + busaddroff = ai->shared_dma; + pciaddroff = ai->pciaux + AUX_OFFSET; + vpackoff = ai->shared; + + /* RX descriptor setup */ + for(i = 0; i < MPI_MAX_FIDS; i++) { + ai->rxfids[i].pending = 0; + ai->rxfids[i].card_ram_off = pciaddroff; + ai->rxfids[i].virtual_host_addr = vpackoff; + ai->rxfids[i].rx_desc.host_addr = busaddroff; + ai->rxfids[i].rx_desc.valid = 1; + ai->rxfids[i].rx_desc.len = PKTSIZE; + ai->rxfids[i].rx_desc.rdy = 0; + + pciaddroff += sizeof(RxFid); + busaddroff += PKTSIZE; + vpackoff += PKTSIZE; + } + + /* TX descriptor setup */ + for(i = 0; i < MPI_MAX_FIDS; i++) { + ai->txfids[i].card_ram_off = pciaddroff; + ai->txfids[i].virtual_host_addr = vpackoff; + ai->txfids[i].tx_desc.valid = 1; + ai->txfids[i].tx_desc.host_addr = busaddroff; + memcpy(ai->txfids[i].virtual_host_addr, + &wifictlhdr8023, sizeof(wifictlhdr8023)); + + pciaddroff += sizeof(TxFid); + busaddroff += PKTSIZE; + vpackoff += PKTSIZE; + } + ai->txfids[i-1].tx_desc.eoc = 1; /* Last descriptor has EOC set */ + + /* Rid descriptor setup */ + ai->config_desc.card_ram_off = pciaddroff; + ai->config_desc.virtual_host_addr = vpackoff; + ai->config_desc.rid_desc.host_addr = busaddroff; + ai->ridbus = busaddroff; + ai->config_desc.rid_desc.rid = 0; + ai->config_desc.rid_desc.len = RIDSIZE; + ai->config_desc.rid_desc.valid = 1; + pciaddroff += sizeof(Rid); + busaddroff += RIDSIZE; + vpackoff += RIDSIZE; + + /* Tell card about descriptors */ + if (mpi_init_descriptors (ai) != SUCCESS) + goto free_shared; + + return 0; + free_shared: + pci_free_consistent(pci, PCI_SHARED_LEN, ai->shared, ai->shared_dma); + free_auxmap: + iounmap(ai->pciaux); + free_memmap: + iounmap(ai->pcimem); + free_region2: + release_mem_region(aux_start, aux_len); + free_region1: + release_mem_region(mem_start, mem_len); + out: + return rc; +} +",0,"static int mpi_map_card(struct airo_info *ai, struct pci_dev *pci) +{ + unsigned long mem_start, mem_len, aux_start, aux_len; + int rc = -1; + int i; + dma_addr_t busaddroff; + unsigned char *vpackoff; + unsigned char __iomem *pciaddroff; + + mem_start = pci_resource_start(pci, 1); + mem_len = pci_resource_len(pci, 1); + aux_start = pci_resource_start(pci, 2); + aux_len = AUXMEMSIZE; + + if (!request_mem_region(mem_start, mem_len, DRV_NAME)) { + airo_print_err("""", ""Couldn't get region %x[%x]"", + (int)mem_start, (int)mem_len); + goto out; + } + if (!request_mem_region(aux_start, aux_len, DRV_NAME)) { + airo_print_err("""", ""Couldn't get region %x[%x]"", + (int)aux_start, (int)aux_len); + goto free_region1; + } + + ai->pcimem = ioremap(mem_start, mem_len); + if (!ai->pcimem) { + airo_print_err("""", ""Couldn't map region %x[%x]"", + (int)mem_start, (int)mem_len); + goto free_region2; + } + ai->pciaux = ioremap(aux_start, aux_len); + if (!ai->pciaux) { + airo_print_err("""", ""Couldn't map region %x[%x]"", + (int)aux_start, (int)aux_len); + goto free_memmap; + } + + /* Reserve PKTSIZE for each fid and 2K for the Rids */ + ai->shared = pci_alloc_consistent(pci, PCI_SHARED_LEN, &ai->shared_dma); + if (!ai->shared) { + airo_print_err("""", ""Couldn't alloc_consistent %d"", + PCI_SHARED_LEN); + goto free_auxmap; + } + + /* + * Setup descriptor RX, TX, CONFIG + */ + busaddroff = ai->shared_dma; + pciaddroff = ai->pciaux + AUX_OFFSET; + vpackoff = ai->shared; + + /* RX descriptor setup */ + for(i = 0; i < MPI_MAX_FIDS; i++) { + ai->rxfids[i].pending = 0; + ai->rxfids[i].card_ram_off = pciaddroff; + ai->rxfids[i].virtual_host_addr = vpackoff; + ai->rxfids[i].rx_desc.host_addr = busaddroff; + ai->rxfids[i].rx_desc.valid = 1; + ai->rxfids[i].rx_desc.len = PKTSIZE; + ai->rxfids[i].rx_desc.rdy = 0; + + pciaddroff += sizeof(RxFid); + busaddroff += PKTSIZE; + vpackoff += PKTSIZE; + } + + /* TX descriptor setup */ + for(i = 0; i < MPI_MAX_FIDS; i++) { + ai->txfids[i].card_ram_off = pciaddroff; + ai->txfids[i].virtual_host_addr = vpackoff; + ai->txfids[i].tx_desc.valid = 1; + ai->txfids[i].tx_desc.host_addr = busaddroff; + memcpy(ai->txfids[i].virtual_host_addr, + &wifictlhdr8023, sizeof(wifictlhdr8023)); + + pciaddroff += sizeof(TxFid); + busaddroff += PKTSIZE; + vpackoff += PKTSIZE; + } + ai->txfids[i-1].tx_desc.eoc = 1; /* Last descriptor has EOC set */ + + /* Rid descriptor setup */ + ai->config_desc.card_ram_off = pciaddroff; + ai->config_desc.virtual_host_addr = vpackoff; + ai->config_desc.rid_desc.host_addr = busaddroff; + ai->ridbus = busaddroff; + ai->config_desc.rid_desc.rid = 0; + ai->config_desc.rid_desc.len = RIDSIZE; + ai->config_desc.rid_desc.valid = 1; + pciaddroff += sizeof(Rid); + busaddroff += RIDSIZE; + vpackoff += RIDSIZE; + + /* Tell card about descriptors */ + if (mpi_init_descriptors (ai) != SUCCESS) + goto free_shared; + + return 0; + free_shared: + pci_free_consistent(pci, PCI_SHARED_LEN, ai->shared, ai->shared_dma); + free_auxmap: + iounmap(ai->pciaux); + free_memmap: + iounmap(ai->pcimem); + free_region2: + release_mem_region(aux_start, aux_len); + free_region1: + release_mem_region(mem_start, mem_len); + out: + return rc; +} +","@@ -2823,6 +2823,7 @@ static struct net_device *_init_airo_card( unsigned short irq, int port, + dev->wireless_data = &ai->wireless_data; + dev->irq = irq; + dev->base_addr = port; ++ dev->priv_flags &= ~IFF_TX_SKB_SHARING; + + SET_NETDEV_DEV(dev, dmdev); + ",1059,1390,2048 +6145,"static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, + const ssize_t type,const PSDCompressionType compression, + const size_t compact_size,ExceptionInfo *exception) +{ + MagickBooleanType + status; + + register unsigned char + *p; + + size_t + count, + length, + packet_size, + row_size; + + ssize_t + y; + + unsigned char + *compact_pixels, + *pixels; + + z_stream + stream; + + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" layer data is ZIP compressed""); + + compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, + sizeof(*compact_pixels)); + if (compact_pixels == (unsigned char *) NULL) + ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", + image->filename); + + packet_size=GetPSDPacketSize(image); + row_size=image->columns*packet_size; + count=image->rows*row_size; + + pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); + if (pixels == (unsigned char *) NULL) + { + compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); + ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", + image->filename); + } + if (ReadBlob(image,compact_size,compact_pixels) != (ssize_t) compact_size) + { + compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); + ThrowBinaryException(CorruptImageError,""UnexpectedEndOfFile"", + image->filename); + } + + ResetMagickMemory(&stream,0,sizeof(stream)); + stream.data_type=Z_BINARY; + stream.next_in=(Bytef *)compact_pixels; + stream.avail_in=(uInt) compact_size; + stream.next_out=(Bytef *)pixels; + stream.avail_out=(uInt) count; + + if (inflateInit(&stream) == Z_OK) + { + int + ret; + + while (stream.avail_out > 0) + { + ret=inflate(&stream, Z_SYNC_FLUSH); + if ((ret != Z_OK) && (ret != Z_STREAM_END)) + { + (void) inflateEnd(&stream); + compact_pixels=(unsigned char *) RelinquishMagickMemory( + compact_pixels); + pixels=(unsigned char *) RelinquishMagickMemory(pixels); + return(MagickFalse); + } + } + (void) inflateEnd(&stream); + } + + if (compression == ZipWithPrediction) + { + p=pixels; + while (count > 0) + { + length=image->columns; + while (--length) + { + if (packet_size == 2) + { + p[2]+=p[0]+((p[1]+p[3]) >> 8); + p[3]+=p[1]; + } + else + *(p+1)+=*p; + p+=packet_size; + } + p+=packet_size; + count-=row_size; + } + } + + status=MagickTrue; + p=pixels; + for (y=0; y < (ssize_t) image->rows; y++) + { + status=ReadPSDChannelPixels(image,channels,y,type,p,exception); + if (status == MagickFalse) + break; + + p+=row_size; + } + + compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); + pixels=(unsigned char *) RelinquishMagickMemory(pixels); + return(status); +} +",0,"static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, + const ssize_t type,const PSDCompressionType compression, + const size_t compact_size,ExceptionInfo *exception) +{ + MagickBooleanType + status; + + register unsigned char + *p; + + size_t + count, + length, + packet_size, + row_size; + + ssize_t + y; + + unsigned char + *compact_pixels, + *pixels; + + z_stream + stream; + + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" layer data is ZIP compressed""); + + compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, + sizeof(*compact_pixels)); + if (compact_pixels == (unsigned char *) NULL) + ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", + image->filename); + + packet_size=GetPSDPacketSize(image); + row_size=image->columns*packet_size; + count=image->rows*row_size; + + pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); + if (pixels == (unsigned char *) NULL) + { + compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); + ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", + image->filename); + } + if (ReadBlob(image,compact_size,compact_pixels) != (ssize_t) compact_size) + { + compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); + ThrowBinaryException(CorruptImageError,""UnexpectedEndOfFile"", + image->filename); + } + + ResetMagickMemory(&stream,0,sizeof(stream)); + stream.data_type=Z_BINARY; + stream.next_in=(Bytef *)compact_pixels; + stream.avail_in=(uInt) compact_size; + stream.next_out=(Bytef *)pixels; + stream.avail_out=(uInt) count; + + if (inflateInit(&stream) == Z_OK) + { + int + ret; + + while (stream.avail_out > 0) + { + ret=inflate(&stream, Z_SYNC_FLUSH); + if ((ret != Z_OK) && (ret != Z_STREAM_END)) + { + (void) inflateEnd(&stream); + compact_pixels=(unsigned char *) RelinquishMagickMemory( + compact_pixels); + pixels=(unsigned char *) RelinquishMagickMemory(pixels); + return(MagickFalse); + } + } + (void) inflateEnd(&stream); + } + + if (compression == ZipWithPrediction) + { + p=pixels; + while (count > 0) + { + length=image->columns; + while (--length) + { + if (packet_size == 2) + { + p[2]+=p[0]+((p[1]+p[3]) >> 8); + p[3]+=p[1]; + } + else + *(p+1)+=*p; + p+=packet_size; + } + p+=packet_size; + count-=row_size; + } + } + + status=MagickTrue; + p=pixels; + for (y=0; y < (ssize_t) image->rows; y++) + { + status=ReadPSDChannelPixels(image,channels,y,type,p,exception); + if (status == MagickFalse) + break; + + p+=row_size; + } + + compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); + pixels=(unsigned char *) RelinquishMagickMemory(pixels); + return(status); +} +","@@ -1688,6 +1688,12 @@ static MagickBooleanType ReadPSDLayersInternal(Image *image, + { + size_t blend_source=ReadBlobLong(image); + size_t blend_dest=ReadBlobLong(image); ++ if (EOFBlob(image) != MagickFalse) ++ { ++ layer_info=DestroyLayerInfo(layer_info,number_layers); ++ ThrowBinaryException(CorruptImageError, ++ ""InsufficientImageDataInFile"",image->filename); ++ } + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" source(%x), dest(%x)"",(unsigned int)",758,1089,2048 +18316,"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); + if (n <= 0) return(n); /* error or non-blocking io */ + /* 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 && + *p == 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); + + } +",1,"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 && + *p == 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); + + } +","@@ -645,8 +645,6 @@ int dtls1_get_record(SSL *s) + /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */ + i=rr->length; + n=ssl3_read_n(s,i,i,1); +- if (n <= 0) return(n); /* error or non-blocking io */ +- + /* this packet contained a partial record, dump it */ + if ( n != i) + {",1354,1685,2048 +18122,"static void print_bpf_insn(struct bpf_insn *insn) + { + u8 class = BPF_CLASS(insn->code); + + if (class == BPF_ALU || class == BPF_ALU64) { + if (BPF_SRC(insn->code) == BPF_X) + verbose(""(%02x) %sr%d %s %sr%d\n"", + insn->code, class == BPF_ALU ? ""(u32) "" : """", + insn->dst_reg, + bpf_alu_string[BPF_OP(insn->code) >> 4], + class == BPF_ALU ? ""(u32) "" : """", + insn->src_reg); + else + verbose(""(%02x) %sr%d %s %s%d\n"", + insn->code, class == BPF_ALU ? ""(u32) "" : """", + insn->dst_reg, + bpf_alu_string[BPF_OP(insn->code) >> 4], + class == BPF_ALU ? ""(u32) "" : """", + insn->imm); + } else if (class == BPF_STX) { + if (BPF_MODE(insn->code) == BPF_MEM) + verbose(""(%02x) *(%s *)(r%d %+d) = r%d\n"", + insn->code, + bpf_ldst_string[BPF_SIZE(insn->code) >> 3], + insn->dst_reg, + insn->off, insn->src_reg); + else if (BPF_MODE(insn->code) == BPF_XADD) + verbose(""(%02x) lock *(%s *)(r%d %+d) += r%d\n"", + insn->code, + bpf_ldst_string[BPF_SIZE(insn->code) >> 3], + insn->dst_reg, insn->off, + insn->src_reg); + else + verbose(""BUG_%02x\n"", insn->code); + } else if (class == BPF_ST) { + if (BPF_MODE(insn->code) != BPF_MEM) { + verbose(""BUG_st_%02x\n"", insn->code); + return; + } + verbose(""(%02x) *(%s *)(r%d %+d) = %d\n"", + insn->code, + bpf_ldst_string[BPF_SIZE(insn->code) >> 3], + insn->dst_reg, + insn->off, insn->imm); + } else if (class == BPF_LDX) { + if (BPF_MODE(insn->code) != BPF_MEM) { + verbose(""BUG_ldx_%02x\n"", insn->code); + return; + } + verbose(""(%02x) r%d = *(%s *)(r%d %+d)\n"", + insn->code, insn->dst_reg, + bpf_ldst_string[BPF_SIZE(insn->code) >> 3], + insn->src_reg, insn->off); + } else if (class == BPF_LD) { + if (BPF_MODE(insn->code) == BPF_ABS) { + verbose(""(%02x) r0 = *(%s *)skb[%d]\n"", + insn->code, + bpf_ldst_string[BPF_SIZE(insn->code) >> 3], + insn->imm); + } else if (BPF_MODE(insn->code) == BPF_IND) { + verbose(""(%02x) r0 = *(%s *)skb[r%d + %d]\n"", + insn->code, + bpf_ldst_string[BPF_SIZE(insn->code) >> 3], + insn->src_reg, insn->imm); + } else if (BPF_MODE(insn->code) == BPF_IMM) { + verbose(""(%02x) r%d = 0x%x\n"", + insn->code, insn->dst_reg, insn->imm); + } else { + verbose(""BUG_ld_%02x\n"", insn->code); + return; + } + } else if (class == BPF_JMP) { + u8 opcode = BPF_OP(insn->code); + + if (opcode == BPF_CALL) { + verbose(""(%02x) call %s#%d\n"", insn->code, + func_id_name(insn->imm), insn->imm); + } else if (insn->code == (BPF_JMP | BPF_JA)) { + verbose(""(%02x) goto pc%+d\n"", + insn->code, insn->off); + } else if (insn->code == (BPF_JMP | BPF_EXIT)) { + verbose(""(%02x) exit\n"", insn->code); + } else if (BPF_SRC(insn->code) == BPF_X) { + verbose(""(%02x) if r%d %s r%d goto pc%+d\n"", + insn->code, insn->dst_reg, + bpf_jmp_string[BPF_OP(insn->code) >> 4], + insn->src_reg, insn->off); + } else { + verbose(""(%02x) if r%d %s 0x%x goto pc%+d\n"", + insn->code, insn->dst_reg, + bpf_jmp_string[BPF_OP(insn->code) >> 4], + insn->imm, insn->off); + } + } else { + verbose(""(%02x) %s\n"", insn->code, bpf_class_string[class]); + } +} +",1,"static void print_bpf_insn(struct bpf_insn *insn) +static void print_bpf_insn(const struct bpf_verifier_env *env, + const struct bpf_insn *insn) + { + u8 class = BPF_CLASS(insn->code); + + if (class == BPF_ALU || class == BPF_ALU64) { + if (BPF_SRC(insn->code) == BPF_X) + verbose(""(%02x) %sr%d %s %sr%d\n"", + insn->code, class == BPF_ALU ? ""(u32) "" : """", + insn->dst_reg, + bpf_alu_string[BPF_OP(insn->code) >> 4], + class == BPF_ALU ? ""(u32) "" : """", + insn->src_reg); + else + verbose(""(%02x) %sr%d %s %s%d\n"", + insn->code, class == BPF_ALU ? ""(u32) "" : """", + insn->dst_reg, + bpf_alu_string[BPF_OP(insn->code) >> 4], + class == BPF_ALU ? ""(u32) "" : """", + insn->imm); + } else if (class == BPF_STX) { + if (BPF_MODE(insn->code) == BPF_MEM) + verbose(""(%02x) *(%s *)(r%d %+d) = r%d\n"", + insn->code, + bpf_ldst_string[BPF_SIZE(insn->code) >> 3], + insn->dst_reg, + insn->off, insn->src_reg); + else if (BPF_MODE(insn->code) == BPF_XADD) + verbose(""(%02x) lock *(%s *)(r%d %+d) += r%d\n"", + insn->code, + bpf_ldst_string[BPF_SIZE(insn->code) >> 3], + insn->dst_reg, insn->off, + insn->src_reg); + else + verbose(""BUG_%02x\n"", insn->code); + } else if (class == BPF_ST) { + if (BPF_MODE(insn->code) != BPF_MEM) { + verbose(""BUG_st_%02x\n"", insn->code); + return; + } + verbose(""(%02x) *(%s *)(r%d %+d) = %d\n"", + insn->code, + bpf_ldst_string[BPF_SIZE(insn->code) >> 3], + insn->dst_reg, + insn->off, insn->imm); + } else if (class == BPF_LDX) { + if (BPF_MODE(insn->code) != BPF_MEM) { + verbose(""BUG_ldx_%02x\n"", insn->code); + return; + } + verbose(""(%02x) r%d = *(%s *)(r%d %+d)\n"", + insn->code, insn->dst_reg, + bpf_ldst_string[BPF_SIZE(insn->code) >> 3], + insn->src_reg, insn->off); + } else if (class == BPF_LD) { + if (BPF_MODE(insn->code) == BPF_ABS) { + verbose(""(%02x) r0 = *(%s *)skb[%d]\n"", + insn->code, + bpf_ldst_string[BPF_SIZE(insn->code) >> 3], + insn->imm); + } else if (BPF_MODE(insn->code) == BPF_IND) { + verbose(""(%02x) r0 = *(%s *)skb[r%d + %d]\n"", + insn->code, + bpf_ldst_string[BPF_SIZE(insn->code) >> 3], + insn->src_reg, insn->imm); + } else if (BPF_MODE(insn->code) == BPF_IMM && + BPF_SIZE(insn->code) == BPF_DW) { + /* At this point, we already made sure that the second + * part of the ldimm64 insn is accessible. + */ + u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; + bool map_ptr = insn->src_reg == BPF_PSEUDO_MAP_FD; + + if (map_ptr && !env->allow_ptr_leaks) + imm = 0; + + verbose(""(%02x) r%d = 0x%llx\n"", insn->code, + insn->dst_reg, (unsigned long long)imm); + } else { + verbose(""BUG_ld_%02x\n"", insn->code); + return; + } + } else if (class == BPF_JMP) { + u8 opcode = BPF_OP(insn->code); + + if (opcode == BPF_CALL) { + verbose(""(%02x) call %s#%d\n"", insn->code, + func_id_name(insn->imm), insn->imm); + } else if (insn->code == (BPF_JMP | BPF_JA)) { + verbose(""(%02x) goto pc%+d\n"", + insn->code, insn->off); + } else if (insn->code == (BPF_JMP | BPF_EXIT)) { + verbose(""(%02x) exit\n"", insn->code); + } else if (BPF_SRC(insn->code) == BPF_X) { + verbose(""(%02x) if r%d %s r%d goto pc%+d\n"", + insn->code, insn->dst_reg, + bpf_jmp_string[BPF_OP(insn->code) >> 4], + insn->src_reg, insn->off); + } else { + verbose(""(%02x) if r%d %s 0x%x goto pc%+d\n"", + insn->code, insn->dst_reg, + bpf_jmp_string[BPF_OP(insn->code) >> 4], + insn->imm, insn->off); + } + } else { + verbose(""(%02x) %s\n"", insn->code, bpf_class_string[class]); + } +} +","@@ -298,7 +298,8 @@ static const char *const bpf_jmp_string[16] = { + [BPF_EXIT >> 4] = ""exit"", + }; + +-static void print_bpf_insn(struct bpf_insn *insn) ++static void print_bpf_insn(const struct bpf_verifier_env *env, ++ const struct bpf_insn *insn) + { + u8 class = BPF_CLASS(insn->code); + +@@ -362,9 +363,19 @@ static void print_bpf_insn(struct bpf_insn *insn) + insn->code, + bpf_ldst_string[BPF_SIZE(insn->code) >> 3], + insn->src_reg, insn->imm); +- } else if (BPF_MODE(insn->code) == BPF_IMM) { +- verbose(""(%02x) r%d = 0x%x\n"", +- insn->code, insn->dst_reg, insn->imm); ++ } else if (BPF_MODE(insn->code) == BPF_IMM && ++ BPF_SIZE(insn->code) == BPF_DW) { ++ /* At this point, we already made sure that the second ++ * part of the ldimm64 insn is accessible. ++ */ ++ u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; ++ bool map_ptr = insn->src_reg == BPF_PSEUDO_MAP_FD; ++ ++ if (map_ptr && !env->allow_ptr_leaks) ++ imm = 0; ++ ++ verbose(""(%02x) r%d = 0x%llx\n"", insn->code, ++ insn->dst_reg, (unsigned long long)imm); + } else { + verbose(""BUG_ld_%02x\n"", insn->code); + return; +@@ -2853,7 +2864,7 @@ static int do_check(struct bpf_verifier_env *env) + + if (log_level) { + verbose(""%d: "", insn_idx); +- print_bpf_insn(insn); ++ print_bpf_insn(env, insn); + } + + err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx);",1235,1566,2048 +4077,"static int rawv6_sendmsg(struct kiocb *iocb, struct sock *sk, + struct msghdr *msg, size_t len) +{ + struct ipv6_txoptions opt_space; + struct sockaddr_in6 * sin6 = (struct sockaddr_in6 *) msg->msg_name; + struct in6_addr *daddr, *final_p, final; + struct inet_sock *inet = inet_sk(sk); + struct ipv6_pinfo *np = inet6_sk(sk); + struct raw6_sock *rp = raw6_sk(sk); + struct ipv6_txoptions *opt = NULL; + struct ip6_flowlabel *flowlabel = NULL; + struct dst_entry *dst = NULL; + struct flowi6 fl6; + int addr_len = msg->msg_namelen; + int hlimit = -1; + int tclass = -1; + int dontfrag = -1; + u16 proto; + int err; + + /* Rough check on arithmetic overflow, + better check is made in ip6_append_data(). + */ + if (len > INT_MAX) + return -EMSGSIZE; + + /* Mirror BSD error message compatibility */ + if (msg->msg_flags & MSG_OOB) + return -EOPNOTSUPP; + + /* + * Get and verify the address. + */ + memset(&fl6, 0, sizeof(fl6)); + + fl6.flowi6_mark = sk->sk_mark; + + if (sin6) { + if (addr_len < SIN6_LEN_RFC2133) + return -EINVAL; + + if (sin6->sin6_family && sin6->sin6_family != AF_INET6) + return -EAFNOSUPPORT; + + /* port is the proto value [0..255] carried in nexthdr */ + proto = ntohs(sin6->sin6_port); + + if (!proto) + proto = inet->inet_num; + else if (proto != inet->inet_num) + return -EINVAL; + + if (proto > 255) + return -EINVAL; + + daddr = &sin6->sin6_addr; + if (np->sndflow) { + fl6.flowlabel = sin6->sin6_flowinfo&IPV6_FLOWINFO_MASK; + if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) { + flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); + if (flowlabel == NULL) + return -EINVAL; + daddr = &flowlabel->dst; + } + } + + /* + * Otherwise it will be difficult to maintain + * sk->sk_dst_cache. + */ + if (sk->sk_state == TCP_ESTABLISHED && + ipv6_addr_equal(daddr, &sk->sk_v6_daddr)) + daddr = &sk->sk_v6_daddr; + + if (addr_len >= sizeof(struct sockaddr_in6) && + sin6->sin6_scope_id && + __ipv6_addr_needs_scope_id(__ipv6_addr_type(daddr))) + fl6.flowi6_oif = sin6->sin6_scope_id; + } else { + if (sk->sk_state != TCP_ESTABLISHED) + return -EDESTADDRREQ; + + proto = inet->inet_num; + daddr = &sk->sk_v6_daddr; + fl6.flowlabel = np->flow_label; + } + + if (fl6.flowi6_oif == 0) + fl6.flowi6_oif = sk->sk_bound_dev_if; + + if (msg->msg_controllen) { + opt = &opt_space; + memset(opt, 0, sizeof(struct ipv6_txoptions)); + opt->tot_len = sizeof(struct ipv6_txoptions); + + err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt, + &hlimit, &tclass, &dontfrag); + if (err < 0) { + fl6_sock_release(flowlabel); + return err; + } + if ((fl6.flowlabel&IPV6_FLOWLABEL_MASK) && !flowlabel) { + flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); + if (flowlabel == NULL) + return -EINVAL; + } + if (!(opt->opt_nflen|opt->opt_flen)) + opt = NULL; + } + if (opt == NULL) + opt = np->opt; + if (flowlabel) + opt = fl6_merge_options(&opt_space, flowlabel, opt); + opt = ipv6_fixup_options(&opt_space, opt); + + fl6.flowi6_proto = proto; + err = rawv6_probe_proto_opt(&fl6, msg); + if (err) + goto out; + + if (!ipv6_addr_any(daddr)) + fl6.daddr = *daddr; + else + fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */ + if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr)) + fl6.saddr = np->saddr; + + final_p = fl6_update_dst(&fl6, opt, &final); + + if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr)) + fl6.flowi6_oif = np->mcast_oif; + else if (!fl6.flowi6_oif) + fl6.flowi6_oif = np->ucast_oif; + security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); + + dst = ip6_dst_lookup_flow(sk, &fl6, final_p, true); + if (IS_ERR(dst)) { + err = PTR_ERR(dst); + goto out; + } + if (hlimit < 0) { + if (ipv6_addr_is_multicast(&fl6.daddr)) + hlimit = np->mcast_hops; + else + hlimit = np->hop_limit; + if (hlimit < 0) + hlimit = ip6_dst_hoplimit(dst); + } + + if (tclass < 0) + tclass = np->tclass; + + if (dontfrag < 0) + dontfrag = np->dontfrag; + + if (msg->msg_flags&MSG_CONFIRM) + goto do_confirm; + +back_from_confirm: + if (inet->hdrincl) + err = rawv6_send_hdrinc(sk, msg->msg_iov, len, &fl6, &dst, msg->msg_flags); + else { + lock_sock(sk); + err = ip6_append_data(sk, ip_generic_getfrag, msg->msg_iov, + len, 0, hlimit, tclass, opt, &fl6, (struct rt6_info*)dst, + msg->msg_flags, dontfrag); + + if (err) + ip6_flush_pending_frames(sk); + else if (!(msg->msg_flags & MSG_MORE)) + err = rawv6_push_pending_frames(sk, &fl6, rp); + release_sock(sk); + } +done: + dst_release(dst); +out: + fl6_sock_release(flowlabel); + return err<0?err:len; +do_confirm: + dst_confirm(dst); + if (!(msg->msg_flags & MSG_PROBE) || len) + goto back_from_confirm; + err = 0; + goto done; +} +",0,"static int rawv6_sendmsg(struct kiocb *iocb, struct sock *sk, + struct msghdr *msg, size_t len) +{ + struct ipv6_txoptions opt_space; + struct sockaddr_in6 * sin6 = (struct sockaddr_in6 *) msg->msg_name; + struct in6_addr *daddr, *final_p, final; + struct inet_sock *inet = inet_sk(sk); + struct ipv6_pinfo *np = inet6_sk(sk); + struct raw6_sock *rp = raw6_sk(sk); + struct ipv6_txoptions *opt = NULL; + struct ip6_flowlabel *flowlabel = NULL; + struct dst_entry *dst = NULL; + struct flowi6 fl6; + int addr_len = msg->msg_namelen; + int hlimit = -1; + int tclass = -1; + int dontfrag = -1; + u16 proto; + int err; + + /* Rough check on arithmetic overflow, + better check is made in ip6_append_data(). + */ + if (len > INT_MAX) + return -EMSGSIZE; + + /* Mirror BSD error message compatibility */ + if (msg->msg_flags & MSG_OOB) + return -EOPNOTSUPP; + + /* + * Get and verify the address. + */ + memset(&fl6, 0, sizeof(fl6)); + + fl6.flowi6_mark = sk->sk_mark; + + if (sin6) { + if (addr_len < SIN6_LEN_RFC2133) + return -EINVAL; + + if (sin6->sin6_family && sin6->sin6_family != AF_INET6) + return -EAFNOSUPPORT; + + /* port is the proto value [0..255] carried in nexthdr */ + proto = ntohs(sin6->sin6_port); + + if (!proto) + proto = inet->inet_num; + else if (proto != inet->inet_num) + return -EINVAL; + + if (proto > 255) + return -EINVAL; + + daddr = &sin6->sin6_addr; + if (np->sndflow) { + fl6.flowlabel = sin6->sin6_flowinfo&IPV6_FLOWINFO_MASK; + if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) { + flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); + if (flowlabel == NULL) + return -EINVAL; + daddr = &flowlabel->dst; + } + } + + /* + * Otherwise it will be difficult to maintain + * sk->sk_dst_cache. + */ + if (sk->sk_state == TCP_ESTABLISHED && + ipv6_addr_equal(daddr, &sk->sk_v6_daddr)) + daddr = &sk->sk_v6_daddr; + + if (addr_len >= sizeof(struct sockaddr_in6) && + sin6->sin6_scope_id && + __ipv6_addr_needs_scope_id(__ipv6_addr_type(daddr))) + fl6.flowi6_oif = sin6->sin6_scope_id; + } else { + if (sk->sk_state != TCP_ESTABLISHED) + return -EDESTADDRREQ; + + proto = inet->inet_num; + daddr = &sk->sk_v6_daddr; + fl6.flowlabel = np->flow_label; + } + + if (fl6.flowi6_oif == 0) + fl6.flowi6_oif = sk->sk_bound_dev_if; + + if (msg->msg_controllen) { + opt = &opt_space; + memset(opt, 0, sizeof(struct ipv6_txoptions)); + opt->tot_len = sizeof(struct ipv6_txoptions); + + err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt, + &hlimit, &tclass, &dontfrag); + if (err < 0) { + fl6_sock_release(flowlabel); + return err; + } + if ((fl6.flowlabel&IPV6_FLOWLABEL_MASK) && !flowlabel) { + flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); + if (flowlabel == NULL) + return -EINVAL; + } + if (!(opt->opt_nflen|opt->opt_flen)) + opt = NULL; + } + if (opt == NULL) + opt = np->opt; + if (flowlabel) + opt = fl6_merge_options(&opt_space, flowlabel, opt); + opt = ipv6_fixup_options(&opt_space, opt); + + fl6.flowi6_proto = proto; + err = rawv6_probe_proto_opt(&fl6, msg); + if (err) + goto out; + + if (!ipv6_addr_any(daddr)) + fl6.daddr = *daddr; + else + fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */ + if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr)) + fl6.saddr = np->saddr; + + final_p = fl6_update_dst(&fl6, opt, &final); + + if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr)) + fl6.flowi6_oif = np->mcast_oif; + else if (!fl6.flowi6_oif) + fl6.flowi6_oif = np->ucast_oif; + security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); + + dst = ip6_dst_lookup_flow(sk, &fl6, final_p, true); + if (IS_ERR(dst)) { + err = PTR_ERR(dst); + goto out; + } + if (hlimit < 0) { + if (ipv6_addr_is_multicast(&fl6.daddr)) + hlimit = np->mcast_hops; + else + hlimit = np->hop_limit; + if (hlimit < 0) + hlimit = ip6_dst_hoplimit(dst); + } + + if (tclass < 0) + tclass = np->tclass; + + if (dontfrag < 0) + dontfrag = np->dontfrag; + + if (msg->msg_flags&MSG_CONFIRM) + goto do_confirm; + +back_from_confirm: + if (inet->hdrincl) + err = rawv6_send_hdrinc(sk, msg->msg_iov, len, &fl6, &dst, msg->msg_flags); + else { + lock_sock(sk); + err = ip6_append_data(sk, ip_generic_getfrag, msg->msg_iov, + len, 0, hlimit, tclass, opt, &fl6, (struct rt6_info*)dst, + msg->msg_flags, dontfrag); + + if (err) + ip6_flush_pending_frames(sk); + else if (!(msg->msg_flags & MSG_MORE)) + err = rawv6_push_pending_frames(sk, &fl6, rp); + release_sock(sk); + } +done: + dst_release(dst); +out: + fl6_sock_release(flowlabel); + return err<0?err:len; +do_confirm: + dst_confirm(dst); + if (!(msg->msg_flags & MSG_PROBE) || len) + goto back_from_confirm; + err = 0; + goto done; +} +","@@ -465,9 +465,6 @@ static int rawv6_recvmsg(struct kiocb *iocb, struct sock *sk, + if (flags & MSG_OOB) + return -EOPNOTSUPP; + +- if (addr_len) +- *addr_len=sizeof(*sin6); +- + if (flags & MSG_ERRQUEUE) + return ipv6_recv_error(sk, msg, len); + +@@ -506,6 +503,7 @@ static int rawv6_recvmsg(struct kiocb *iocb, struct sock *sk, + sin6->sin6_flowinfo = 0; + sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr, + IP6CB(skb)->iif); ++ *addr_len = sizeof(*sin6); + } + + sock_recv_ts_and_drops(msg, sk, skb);",1558,1889,2048 +6808,"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; + + packet_pick_tx_queue(dev, skb); + + 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; +} +",0,"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; + + packet_pick_tx_queue(dev, skb); + + 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; +} +","@@ -1619,6 +1619,7 @@ static void fanout_release_data(struct packet_fanout *f) + + 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; +@@ -1641,23 +1642,28 @@ static int fanout_add(struct sock *sk, u16 id, u16 type_flags) + return -EINVAL; + } + ++ mutex_lock(&fanout_mutex); ++ ++ err = -EINVAL; + if (!po->running) +- return -EINVAL; ++ goto out; + ++ err = -EALREADY; + if (po->fanout) +- return -EALREADY; ++ goto out; + + if (type == PACKET_FANOUT_ROLLOVER || + (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)) { +- po->rollover = kzalloc(sizeof(*po->rollover), GFP_KERNEL); +- if (!po->rollover) +- return -ENOMEM; +- atomic_long_set(&po->rollover->num, 0); +- atomic_long_set(&po->rollover->num_huge, 0); +- atomic_long_set(&po->rollover->num_failed, 0); ++ 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; + } + +- mutex_lock(&fanout_mutex); + match = NULL; + list_for_each_entry(f, &fanout_list, list) { + if (f->id == id && +@@ -1704,11 +1710,11 @@ static int fanout_add(struct sock *sk, u16 id, u16 type_flags) + } + } + out: +- mutex_unlock(&fanout_mutex); +- if (err) { +- kfree(po->rollover); ++ if (err && rollover) { ++ kfree(rollover); + po->rollover = NULL; + } ++ mutex_unlock(&fanout_mutex); + return err; + } + +@@ -1717,23 +1723,22 @@ static void fanout_release(struct sock *sk) + struct packet_sock *po = pkt_sk(sk); + struct packet_fanout *f; + +- f = po->fanout; +- if (!f) +- return; +- + mutex_lock(&fanout_mutex); +- po->fanout = NULL; ++ f = po->fanout; ++ if (f) { ++ po->fanout = NULL; ++ ++ if (atomic_dec_and_test(&f->sk_ref)) { ++ list_del(&f->list); ++ dev_remove_pack(&f->prot_hook); ++ fanout_release_data(f); ++ kfree(f); ++ } + +- if (atomic_dec_and_test(&f->sk_ref)) { +- list_del(&f->list); +- dev_remove_pack(&f->prot_hook); +- fanout_release_data(f); +- kfree(f); ++ if (po->rollover) ++ kfree_rcu(po->rollover, rcu); + } + mutex_unlock(&fanout_mutex); +- +- if (po->rollover) +- kfree_rcu(po->rollover, rcu); + } + + static bool packet_extra_vlan_len_allowed(const struct net_device *dev,",1039,1370,2048 +8298,"SECURITY_STATUS ntlm_read_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer) +{ + wStream* s; + size_t length; + NTLM_NEGOTIATE_MESSAGE* message; + message = &context->NEGOTIATE_MESSAGE; + ZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE)); + s = Stream_New((BYTE*) buffer->pvBuffer, buffer->cbBuffer); + + if (!s) + return SEC_E_INTERNAL_ERROR; + + if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*) message) < 0) + { + Stream_Free(s, FALSE); + return SEC_E_INVALID_TOKEN; + } + + if (message->MessageType != MESSAGE_TYPE_NEGOTIATE) + { + Stream_Free(s, FALSE); + return SEC_E_INVALID_TOKEN; + } + + Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ + + if (!((message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) && + (message->NegotiateFlags & NTLMSSP_NEGOTIATE_NTLM) && + (message->NegotiateFlags & NTLMSSP_NEGOTIATE_UNICODE))) + { + Stream_Free(s, FALSE); + return SEC_E_INVALID_TOKEN; + } + + context->NegotiateFlags = message->NegotiateFlags; + + /* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */ + + if (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */ + { + Stream_Free(s, FALSE); + return SEC_E_INVALID_TOKEN; + } + + /* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */ + + if (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */ + { + Stream_Free(s, FALSE); + return SEC_E_INVALID_TOKEN; + } + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) + { + if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */ + { + Stream_Free(s, FALSE); + return SEC_E_INVALID_TOKEN; + } + } + + length = Stream_GetPosition(s); + buffer->cbBuffer = length; + + if (!sspi_SecBufferAlloc(&context->NegotiateMessage, length)) + { + Stream_Free(s, FALSE); + return SEC_E_INTERNAL_ERROR; + } + + CopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer); + context->NegotiateMessage.BufferType = buffer->BufferType; +#ifdef WITH_DEBUG_NTLM + WLog_DBG(TAG, ""NEGOTIATE_MESSAGE (length = %""PRIu32"")"", context->NegotiateMessage.cbBuffer); + winpr_HexDump(TAG, WLOG_DEBUG, context->NegotiateMessage.pvBuffer, + context->NegotiateMessage.cbBuffer); + ntlm_print_negotiate_flags(message->NegotiateFlags); + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) + ntlm_print_version_info(&(message->Version)); + +#endif + context->state = NTLM_STATE_CHALLENGE; + Stream_Free(s, FALSE); + return SEC_I_CONTINUE_NEEDED; +} +",0,"SECURITY_STATUS ntlm_read_NegotiateMessage(NTLM_CONTEXT* context, PSecBuffer buffer) +{ + wStream* s; + size_t length; + NTLM_NEGOTIATE_MESSAGE* message; + message = &context->NEGOTIATE_MESSAGE; + ZeroMemory(message, sizeof(NTLM_NEGOTIATE_MESSAGE)); + s = Stream_New((BYTE*) buffer->pvBuffer, buffer->cbBuffer); + + if (!s) + return SEC_E_INTERNAL_ERROR; + + if (ntlm_read_message_header(s, (NTLM_MESSAGE_HEADER*) message) < 0) + { + Stream_Free(s, FALSE); + return SEC_E_INVALID_TOKEN; + } + + if (message->MessageType != MESSAGE_TYPE_NEGOTIATE) + { + Stream_Free(s, FALSE); + return SEC_E_INVALID_TOKEN; + } + + Stream_Read_UINT32(s, message->NegotiateFlags); /* NegotiateFlags (4 bytes) */ + + if (!((message->NegotiateFlags & NTLMSSP_REQUEST_TARGET) && + (message->NegotiateFlags & NTLMSSP_NEGOTIATE_NTLM) && + (message->NegotiateFlags & NTLMSSP_NEGOTIATE_UNICODE))) + { + Stream_Free(s, FALSE); + return SEC_E_INVALID_TOKEN; + } + + context->NegotiateFlags = message->NegotiateFlags; + + /* only set if NTLMSSP_NEGOTIATE_DOMAIN_SUPPLIED is set */ + + if (ntlm_read_message_fields(s, &(message->DomainName)) < 0) /* DomainNameFields (8 bytes) */ + { + Stream_Free(s, FALSE); + return SEC_E_INVALID_TOKEN; + } + + /* only set if NTLMSSP_NEGOTIATE_WORKSTATION_SUPPLIED is set */ + + if (ntlm_read_message_fields(s, &(message->Workstation)) < 0) /* WorkstationFields (8 bytes) */ + { + Stream_Free(s, FALSE); + return SEC_E_INVALID_TOKEN; + } + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) + { + if (ntlm_read_version_info(s, &(message->Version)) < 0) /* Version (8 bytes) */ + { + Stream_Free(s, FALSE); + return SEC_E_INVALID_TOKEN; + } + } + + length = Stream_GetPosition(s); + buffer->cbBuffer = length; + + if (!sspi_SecBufferAlloc(&context->NegotiateMessage, length)) + { + Stream_Free(s, FALSE); + return SEC_E_INTERNAL_ERROR; + } + + CopyMemory(context->NegotiateMessage.pvBuffer, buffer->pvBuffer, buffer->cbBuffer); + context->NegotiateMessage.BufferType = buffer->BufferType; +#ifdef WITH_DEBUG_NTLM + WLog_DBG(TAG, ""NEGOTIATE_MESSAGE (length = %""PRIu32"")"", context->NegotiateMessage.cbBuffer); + winpr_HexDump(TAG, WLOG_DEBUG, context->NegotiateMessage.pvBuffer, + context->NegotiateMessage.cbBuffer); + ntlm_print_negotiate_flags(message->NegotiateFlags); + + if (message->NegotiateFlags & NTLMSSP_NEGOTIATE_VERSION) + ntlm_print_version_info(&(message->Version)); + +#endif + context->state = NTLM_STATE_CHALLENGE; + Stream_Free(s, FALSE); + return SEC_I_CONTINUE_NEEDED; +} +","@@ -74,7 +74,7 @@ static const char* const NTLM_NEGOTIATE_STRINGS[] = + ""NTLMSSP_NEGOTIATE_UNICODE"" + }; + +-void ntlm_print_negotiate_flags(UINT32 flags) ++static void ntlm_print_negotiate_flags(UINT32 flags) + { + int i; + const char* str; +@@ -90,7 +90,7 @@ void ntlm_print_negotiate_flags(UINT32 flags) + } + } + +-int ntlm_read_message_header(wStream* s, NTLM_MESSAGE_HEADER* header) ++static int ntlm_read_message_header(wStream* s, NTLM_MESSAGE_HEADER* header) + { + if (Stream_GetRemainingLength(s) < 12) + return -1; +@@ -104,19 +104,19 @@ int ntlm_read_message_header(wStream* s, NTLM_MESSAGE_HEADER* header) + return 1; + } + +-void ntlm_write_message_header(wStream* s, NTLM_MESSAGE_HEADER* header) ++static void ntlm_write_message_header(wStream* s, NTLM_MESSAGE_HEADER* header) + { + Stream_Write(s, header->Signature, sizeof(NTLM_SIGNATURE)); + Stream_Write_UINT32(s, header->MessageType); + } + +-void ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType) ++static void ntlm_populate_message_header(NTLM_MESSAGE_HEADER* header, UINT32 MessageType) + { + CopyMemory(header->Signature, NTLM_SIGNATURE, sizeof(NTLM_SIGNATURE)); + header->MessageType = MessageType; + } + +-int ntlm_read_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields) ++static int ntlm_read_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields) + { + if (Stream_GetRemainingLength(s) < 8) + return -1; +@@ -127,7 +127,7 @@ int ntlm_read_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields) + return 1; + } + +-void ntlm_write_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields) ++static void ntlm_write_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields) + { + if (fields->MaxLen < 1) + fields->MaxLen = fields->Len; +@@ -137,11 +137,13 @@ void ntlm_write_message_fields(wStream* s, NTLM_MESSAGE_FIELDS* fields) + Stream_Write_UINT32(s, fields->BufferOffset); /* BufferOffset (4 bytes) */ + } + +-int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) ++static int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) + { + if (fields->Len > 0) + { +- if ((fields->BufferOffset + fields->Len) > Stream_Length(s)) ++ const UINT64 offset = (UINT64)fields->BufferOffset + (UINT64)fields->Len; ++ ++ if (offset > Stream_Length(s)) + return -1; + + fields->Buffer = (PBYTE) malloc(fields->Len); +@@ -156,7 +158,7 @@ int ntlm_read_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) + return 1; + } + +-void ntlm_write_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) ++static void ntlm_write_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) + { + if (fields->Len > 0) + { +@@ -165,7 +167,7 @@ void ntlm_write_message_fields_buffer(wStream* s, NTLM_MESSAGE_FIELDS* fields) + } + } + +-void ntlm_free_message_fields_buffer(NTLM_MESSAGE_FIELDS* fields) ++static void ntlm_free_message_fields_buffer(NTLM_MESSAGE_FIELDS* fields) + { + if (fields) + { +@@ -180,7 +182,7 @@ void ntlm_free_message_fields_buffer(NTLM_MESSAGE_FIELDS* fields) + } + } + +-void ntlm_print_message_fields(NTLM_MESSAGE_FIELDS* fields, const char* name) ++static void ntlm_print_message_fields(NTLM_MESSAGE_FIELDS* fields, const char* name) + { + WLog_DBG(TAG, ""%s (Len: %""PRIu16"" MaxLen: %""PRIu16"" BufferOffset: %""PRIu32"")"", + name, fields->Len, fields->MaxLen, fields->BufferOffset);",718,1049,2048 +18340,"static Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ + Image + *image; + + MagickBooleanType + status, + cubemap = MagickFalse, + volume = MagickFalse, + matte; + + CompressionType + compression; + + DDSInfo + dds_info; + + DDSDecoder + *decoder; + + size_t + n, + num_images; + + /* + 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); + } + + /* + Initialize image structure. + */ + if (ReadDDSInfo(image, &dds_info) != MagickTrue) { + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + } + + if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP) + cubemap = MagickTrue; + + if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0) + volume = MagickTrue; + + (void) SeekBlob(image, 128, SEEK_SET); + + /* + Determine pixel format + */ + if (dds_info.pixelformat.flags & DDPF_RGB) + { + compression = NoCompression; + if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS) + { + matte = MagickTrue; + decoder = ReadUncompressedRGBA; + } + else + { + matte = MagickTrue; + decoder = ReadUncompressedRGB; + } + } + else if (dds_info.pixelformat.flags & DDPF_LUMINANCE) + { + compression = NoCompression; + if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS) + { + /* Not sure how to handle this */ + ThrowReaderException(CorruptImageError, ""ImageTypeNotSupported""); + } + else + { + matte = MagickFalse; + decoder = ReadUncompressedRGB; + } + } + else if (dds_info.pixelformat.flags & DDPF_FOURCC) + { + switch (dds_info.pixelformat.fourcc) + { + case FOURCC_DXT1: + { + matte = MagickFalse; + compression = DXT1Compression; + decoder = ReadDXT1; + break; + } + case FOURCC_DXT3: + { + matte = MagickTrue; + compression = DXT3Compression; + decoder = ReadDXT3; + break; + } + case FOURCC_DXT5: + { + matte = MagickTrue; + compression = DXT5Compression; + decoder = ReadDXT5; + break; + } + default: + { + /* Unknown FOURCC */ + ThrowReaderException(CorruptImageError, ""ImageTypeNotSupported""); + } + } + } + else + { + /* Neither compressed nor uncompressed... thus unsupported */ + ThrowReaderException(CorruptImageError, ""ImageTypeNotSupported""); + } + + num_images = 1; + if (cubemap) + { + /* + Determine number of faces defined in the cubemap + */ + num_images = 0; + if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++; + if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++; + if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++; + if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++; + if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++; + if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++; + } + + if (volume) + num_images = dds_info.depth; + + for (n = 0; n < num_images; n++) + { + if (n != 0) + { + /* Start a new image */ + AcquireNextImage(image_info,image); + if (GetNextImageInList(image) == (Image *) NULL) + return(DestroyImageList(image)); + image=SyncNextImageInList(image); + } + + image->matte = matte; + image->compression = compression; + image->columns = dds_info.width; + image->rows = dds_info.height; + image->storage_class = DirectClass; + image->endian = LSBEndian; + image->depth = 8; + 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)); + } + + if ((decoder)(image, &dds_info, exception) != MagickTrue) + { + (void) CloseBlob(image); + return(GetFirstImageInList(image)); + } + } + + if (EOFBlob(image) != MagickFalse) + ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", + image->filename); + + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +",1,"static Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ + Image + *image; + + MagickBooleanType + status, + cubemap = MagickFalse, + volume = MagickFalse, + matte; + + CompressionType + compression; + + DDSInfo + dds_info; + + DDSDecoder + *decoder; + + size_t + n, + num_images; + + /* + 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); + } + + /* + Initialize image structure. + */ + if (ReadDDSInfo(image, &dds_info) != MagickTrue) { + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + } + + if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP) + cubemap = MagickTrue; + + if (dds_info.ddscaps2 & DDSCAPS2_VOLUME && dds_info.depth > 0) + volume = MagickTrue; + + (void) SeekBlob(image, 128, SEEK_SET); + + /* + Determine pixel format + */ + if (dds_info.pixelformat.flags & DDPF_RGB) + { + compression = NoCompression; + if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS) + { + matte = MagickTrue; + decoder = ReadUncompressedRGBA; + } + else + { + matte = MagickTrue; + decoder = ReadUncompressedRGB; + } + } + else if (dds_info.pixelformat.flags & DDPF_LUMINANCE) + { + compression = NoCompression; + if (dds_info.pixelformat.flags & DDPF_ALPHAPIXELS) + { + /* Not sure how to handle this */ + ThrowReaderException(CorruptImageError, ""ImageTypeNotSupported""); + } + else + { + matte = MagickFalse; + decoder = ReadUncompressedRGB; + } + } + else if (dds_info.pixelformat.flags & DDPF_FOURCC) + { + switch (dds_info.pixelformat.fourcc) + { + case FOURCC_DXT1: + { + matte = MagickFalse; + compression = DXT1Compression; + decoder = ReadDXT1; + break; + } + case FOURCC_DXT3: + { + matte = MagickTrue; + compression = DXT3Compression; + decoder = ReadDXT3; + break; + } + case FOURCC_DXT5: + { + matte = MagickTrue; + compression = DXT5Compression; + decoder = ReadDXT5; + break; + } + default: + { + /* Unknown FOURCC */ + ThrowReaderException(CorruptImageError, ""ImageTypeNotSupported""); + } + } + } + else + { + /* Neither compressed nor uncompressed... thus unsupported */ + ThrowReaderException(CorruptImageError, ""ImageTypeNotSupported""); + } + + num_images = 1; + if (cubemap) + { + /* + Determine number of faces defined in the cubemap + */ + num_images = 0; + if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEX) num_images++; + if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEX) num_images++; + if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEY) num_images++; + if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEY) num_images++; + if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_POSITIVEZ) num_images++; + if (dds_info.ddscaps2 & DDSCAPS2_CUBEMAP_NEGATIVEZ) num_images++; + } + + if (volume) + num_images = dds_info.depth; + + for (n = 0; n < num_images; n++) + { + if (n != 0) + { + if (EOFBlob(image) != MagickFalse) + ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); + /* Start a new image */ + AcquireNextImage(image_info,image); + if (GetNextImageInList(image) == (Image *) NULL) + return(DestroyImageList(image)); + image=SyncNextImageInList(image); + } + + image->matte = matte; + image->compression = compression; + image->columns = dds_info.width; + image->rows = dds_info.height; + image->storage_class = DirectClass; + image->endian = LSBEndian; + image->depth = 8; + 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)); + } + + if ((decoder)(image, &dds_info, exception) != MagickTrue) + { + (void) CloseBlob(image); + return(GetFirstImageInList(image)); + } + } + + if (EOFBlob(image) != MagickFalse) + ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", + image->filename); + + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +","@@ -1836,6 +1836,8 @@ static Image *ReadDDSImage(const ImageInfo *image_info,ExceptionInfo *exception) + { + if (n != 0) + { ++ if (EOFBlob(image) != MagickFalse) ++ ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); + /* Start a new image */ + AcquireNextImage(image_info,image); + if (GetNextImageInList(image) == (Image *) NULL)",1260,1591,2048 +5950,"static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur, + struct idpair *idmap) +{ + if (!(rold->live & REG_LIVE_READ)) + /* explored state didn't use this */ + return true; + + if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, live)) == 0) + return true; + + if (rold->type == NOT_INIT) + /* explored state can't have used this */ + return true; + if (rcur->type == NOT_INIT) + return false; + switch (rold->type) { + case SCALAR_VALUE: + if (rcur->type == SCALAR_VALUE) { + /* new val must satisfy old val knowledge */ + return range_within(rold, rcur) && + tnum_in(rold->var_off, rcur->var_off); + } else { + /* We're trying to use a pointer in place of a scalar. + * Even if the scalar was unbounded, this could lead to + * pointer leaks because scalars are allowed to leak + * while pointers are not. We could make this safe in + * special cases if root is calling us, but it's + * probably not worth the hassle. + */ + return false; + } + case PTR_TO_MAP_VALUE: + /* If the new min/max/var_off satisfy the old ones and + * everything else matches, we are OK. + * We don't care about the 'id' value, because nothing + * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL) + */ + return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && + range_within(rold, rcur) && + tnum_in(rold->var_off, rcur->var_off); + case PTR_TO_MAP_VALUE_OR_NULL: + /* a PTR_TO_MAP_VALUE could be safe to use as a + * PTR_TO_MAP_VALUE_OR_NULL into the same map. + * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL- + * checked, doing so could have affected others with the same + * id, and we can't check for that because we lost the id when + * we converted to a PTR_TO_MAP_VALUE. + */ + if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL) + return false; + if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id))) + return false; + /* Check our ids match any regs they're supposed to */ + return check_ids(rold->id, rcur->id, idmap); + case PTR_TO_PACKET_META: + case PTR_TO_PACKET: + if (rcur->type != rold->type) + return false; + /* We must have at least as much range as the old ptr + * did, so that any accesses which were safe before are + * still safe. This is true even if old range < old off, + * since someone could have accessed through (ptr - k), or + * even done ptr -= k in a register, to get a safe access. + */ + if (rold->range > rcur->range) + return false; + /* If the offsets don't match, we can't trust our alignment; + * nor can we be sure that we won't fall out of range. + */ + if (rold->off != rcur->off) + return false; + /* id relations must be preserved */ + if (rold->id && !check_ids(rold->id, rcur->id, idmap)) + return false; + /* new val must satisfy old val knowledge */ + return range_within(rold, rcur) && + tnum_in(rold->var_off, rcur->var_off); + case PTR_TO_CTX: + case CONST_PTR_TO_MAP: + case PTR_TO_STACK: + case PTR_TO_PACKET_END: + /* Only valid matches are exact, which memcmp() above + * would have accepted + */ + default: + /* Don't know what's going on, just say it's not safe */ + return false; + } + + /* Shouldn't get here; if we do, say it's not safe */ + WARN_ON_ONCE(1); + return false; +} +",0,"static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur, + struct idpair *idmap) +{ + if (!(rold->live & REG_LIVE_READ)) + /* explored state didn't use this */ + return true; + + if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, live)) == 0) + return true; + + if (rold->type == NOT_INIT) + /* explored state can't have used this */ + return true; + if (rcur->type == NOT_INIT) + return false; + switch (rold->type) { + case SCALAR_VALUE: + if (rcur->type == SCALAR_VALUE) { + /* new val must satisfy old val knowledge */ + return range_within(rold, rcur) && + tnum_in(rold->var_off, rcur->var_off); + } else { + /* We're trying to use a pointer in place of a scalar. + * Even if the scalar was unbounded, this could lead to + * pointer leaks because scalars are allowed to leak + * while pointers are not. We could make this safe in + * special cases if root is calling us, but it's + * probably not worth the hassle. + */ + return false; + } + case PTR_TO_MAP_VALUE: + /* If the new min/max/var_off satisfy the old ones and + * everything else matches, we are OK. + * We don't care about the 'id' value, because nothing + * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL) + */ + return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && + range_within(rold, rcur) && + tnum_in(rold->var_off, rcur->var_off); + case PTR_TO_MAP_VALUE_OR_NULL: + /* a PTR_TO_MAP_VALUE could be safe to use as a + * PTR_TO_MAP_VALUE_OR_NULL into the same map. + * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL- + * checked, doing so could have affected others with the same + * id, and we can't check for that because we lost the id when + * we converted to a PTR_TO_MAP_VALUE. + */ + if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL) + return false; + if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id))) + return false; + /* Check our ids match any regs they're supposed to */ + return check_ids(rold->id, rcur->id, idmap); + case PTR_TO_PACKET_META: + case PTR_TO_PACKET: + if (rcur->type != rold->type) + return false; + /* We must have at least as much range as the old ptr + * did, so that any accesses which were safe before are + * still safe. This is true even if old range < old off, + * since someone could have accessed through (ptr - k), or + * even done ptr -= k in a register, to get a safe access. + */ + if (rold->range > rcur->range) + return false; + /* If the offsets don't match, we can't trust our alignment; + * nor can we be sure that we won't fall out of range. + */ + if (rold->off != rcur->off) + return false; + /* id relations must be preserved */ + if (rold->id && !check_ids(rold->id, rcur->id, idmap)) + return false; + /* new val must satisfy old val knowledge */ + return range_within(rold, rcur) && + tnum_in(rold->var_off, rcur->var_off); + case PTR_TO_CTX: + case CONST_PTR_TO_MAP: + case PTR_TO_STACK: + case PTR_TO_PACKET_END: + /* Only valid matches are exact, which memcmp() above + * would have accepted + */ + default: + /* Don't know what's going on, just say it's not safe */ + return false; + } + + /* Shouldn't get here; if we do, say it's not safe */ + WARN_ON_ONCE(1); + return false; +} +","@@ -1819,6 +1819,41 @@ static bool signed_sub_overflows(s64 a, s64 b) + return res > a; + } + ++static bool check_reg_sane_offset(struct bpf_verifier_env *env, ++ const struct bpf_reg_state *reg, ++ enum bpf_reg_type type) ++{ ++ bool known = tnum_is_const(reg->var_off); ++ s64 val = reg->var_off.value; ++ s64 smin = reg->smin_value; ++ ++ if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { ++ verbose(env, ""math between %s pointer and %lld is not allowed\n"", ++ reg_type_str[type], val); ++ return false; ++ } ++ ++ if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { ++ verbose(env, ""%s pointer offset %d is not allowed\n"", ++ reg_type_str[type], reg->off); ++ return false; ++ } ++ ++ if (smin == S64_MIN) { ++ verbose(env, ""math between %s pointer and register with unbounded min value is not allowed\n"", ++ reg_type_str[type]); ++ return false; ++ } ++ ++ if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { ++ verbose(env, ""value %lld makes %s pointer be out of bounds\n"", ++ smin, reg_type_str[type]); ++ return false; ++ } ++ ++ return true; ++} ++ + /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. + * Caller should also handle BPF_MOV case separately. + * If we return -EACCES, caller may want to try again treating pointer as a +@@ -1887,6 +1922,10 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, + dst_reg->type = ptr_reg->type; + dst_reg->id = ptr_reg->id; + ++ if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || ++ !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) ++ return -EINVAL; ++ + switch (opcode) { + case BPF_ADD: + /* We can take a fixed offset as long as it doesn't overflow +@@ -2017,6 +2056,9 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, + return -EACCES; + } + ++ if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) ++ return -EINVAL; ++ + __update_reg_bounds(dst_reg); + __reg_deduce_bounds(dst_reg); + __reg_bound_offset(dst_reg); +@@ -2046,6 +2088,12 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, + src_known = tnum_is_const(src_reg.var_off); + dst_known = tnum_is_const(dst_reg->var_off); + ++ if (!src_known && ++ opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { ++ __mark_reg_unknown(dst_reg); ++ return 0; ++ } ++ + switch (opcode) { + case BPF_ADD: + if (signed_add_overflows(dst_reg->smin_value, smin_val) ||",919,1250,2048 +5703,"static void ext4_put_super(struct super_block *sb) +{ + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_super_block *es = sbi->s_es; + int i, err; + + ext4_unregister_li_request(sb); + dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED); + + flush_workqueue(sbi->rsv_conversion_wq); + destroy_workqueue(sbi->rsv_conversion_wq); + + if (sbi->s_journal) { + err = jbd2_journal_destroy(sbi->s_journal); + sbi->s_journal = NULL; + if (err < 0) + ext4_abort(sb, ""Couldn't clean up the journal""); + } + + ext4_unregister_sysfs(sb); + ext4_es_unregister_shrinker(sbi); + del_timer_sync(&sbi->s_err_report); + ext4_release_system_zone(sb); + ext4_mb_release(sb); + ext4_ext_release(sb); + ext4_xattr_put_super(sb); + + if (!(sb->s_flags & MS_RDONLY)) { + ext4_clear_feature_journal_needs_recovery(sb); + es->s_state = cpu_to_le16(sbi->s_mount_state); + } + if (!(sb->s_flags & MS_RDONLY)) + ext4_commit_super(sb, 1); + + for (i = 0; i < sbi->s_gdb_count; i++) + brelse(sbi->s_group_desc[i]); + kvfree(sbi->s_group_desc); + kvfree(sbi->s_flex_groups); + percpu_counter_destroy(&sbi->s_freeclusters_counter); + percpu_counter_destroy(&sbi->s_freeinodes_counter); + percpu_counter_destroy(&sbi->s_dirs_counter); + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); + brelse(sbi->s_sbh); +#ifdef CONFIG_QUOTA + for (i = 0; i < EXT4_MAXQUOTAS; i++) + kfree(sbi->s_qf_names[i]); +#endif + + /* Debugging code just in case the in-memory inode orphan list + * isn't empty. The on-disk one can be non-empty if we've + * detected an error and taken the fs readonly, but the + * in-memory list had better be clean by this point. */ + if (!list_empty(&sbi->s_orphan)) + dump_orphan_list(sb, sbi); + J_ASSERT(list_empty(&sbi->s_orphan)); + + sync_blockdev(sb->s_bdev); + invalidate_bdev(sb->s_bdev); + if (sbi->journal_bdev && sbi->journal_bdev != sb->s_bdev) { + /* + * Invalidate the journal device's buffers. We don't want them + * floating about in memory - the physical journal device may + * hotswapped, and it breaks the `ro-after' testing code. + */ + sync_blockdev(sbi->journal_bdev); + invalidate_bdev(sbi->journal_bdev); + ext4_blkdev_remove(sbi); + } + if (sbi->s_mb_cache) { + ext4_xattr_destroy_cache(sbi->s_mb_cache); + sbi->s_mb_cache = NULL; + } + if (sbi->s_mmp_tsk) + kthread_stop(sbi->s_mmp_tsk); + sb->s_fs_info = NULL; + /* + * Now that we are completely done shutting down the + * superblock, we need to actually destroy the kobject. + */ + kobject_put(&sbi->s_kobj); + wait_for_completion(&sbi->s_kobj_unregister); + if (sbi->s_chksum_driver) + crypto_free_shash(sbi->s_chksum_driver); + kfree(sbi->s_blockgroup_lock); + kfree(sbi); +} +",0,"static void ext4_put_super(struct super_block *sb) +{ + struct ext4_sb_info *sbi = EXT4_SB(sb); + struct ext4_super_block *es = sbi->s_es; + int i, err; + + ext4_unregister_li_request(sb); + dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED); + + flush_workqueue(sbi->rsv_conversion_wq); + destroy_workqueue(sbi->rsv_conversion_wq); + + if (sbi->s_journal) { + err = jbd2_journal_destroy(sbi->s_journal); + sbi->s_journal = NULL; + if (err < 0) + ext4_abort(sb, ""Couldn't clean up the journal""); + } + + ext4_unregister_sysfs(sb); + ext4_es_unregister_shrinker(sbi); + del_timer_sync(&sbi->s_err_report); + ext4_release_system_zone(sb); + ext4_mb_release(sb); + ext4_ext_release(sb); + ext4_xattr_put_super(sb); + + if (!(sb->s_flags & MS_RDONLY)) { + ext4_clear_feature_journal_needs_recovery(sb); + es->s_state = cpu_to_le16(sbi->s_mount_state); + } + if (!(sb->s_flags & MS_RDONLY)) + ext4_commit_super(sb, 1); + + for (i = 0; i < sbi->s_gdb_count; i++) + brelse(sbi->s_group_desc[i]); + kvfree(sbi->s_group_desc); + kvfree(sbi->s_flex_groups); + percpu_counter_destroy(&sbi->s_freeclusters_counter); + percpu_counter_destroy(&sbi->s_freeinodes_counter); + percpu_counter_destroy(&sbi->s_dirs_counter); + percpu_counter_destroy(&sbi->s_dirtyclusters_counter); + brelse(sbi->s_sbh); +#ifdef CONFIG_QUOTA + for (i = 0; i < EXT4_MAXQUOTAS; i++) + kfree(sbi->s_qf_names[i]); +#endif + + /* Debugging code just in case the in-memory inode orphan list + * isn't empty. The on-disk one can be non-empty if we've + * detected an error and taken the fs readonly, but the + * in-memory list had better be clean by this point. */ + if (!list_empty(&sbi->s_orphan)) + dump_orphan_list(sb, sbi); + J_ASSERT(list_empty(&sbi->s_orphan)); + + sync_blockdev(sb->s_bdev); + invalidate_bdev(sb->s_bdev); + if (sbi->journal_bdev && sbi->journal_bdev != sb->s_bdev) { + /* + * Invalidate the journal device's buffers. We don't want them + * floating about in memory - the physical journal device may + * hotswapped, and it breaks the `ro-after' testing code. + */ + sync_blockdev(sbi->journal_bdev); + invalidate_bdev(sbi->journal_bdev); + ext4_blkdev_remove(sbi); + } + if (sbi->s_mb_cache) { + ext4_xattr_destroy_cache(sbi->s_mb_cache); + sbi->s_mb_cache = NULL; + } + if (sbi->s_mmp_tsk) + kthread_stop(sbi->s_mmp_tsk); + sb->s_fs_info = NULL; + /* + * Now that we are completely done shutting down the + * superblock, we need to actually destroy the kobject. + */ + kobject_put(&sbi->s_kobj); + wait_for_completion(&sbi->s_kobj_unregister); + if (sbi->s_chksum_driver) + crypto_free_shash(sbi->s_chksum_driver); + kfree(sbi->s_blockgroup_lock); + kfree(sbi); +} +","@@ -958,6 +958,7 @@ static void init_once(void *foo) + INIT_LIST_HEAD(&ei->i_orphan); + init_rwsem(&ei->xattr_sem); + init_rwsem(&ei->i_data_sem); ++ init_rwsem(&ei->i_mmap_sem); + inode_init_once(&ei->vfs_inode); + } + ",814,1145,2048 +5719,"static void process_mpa_reply(struct iwch_ep *ep, struct sk_buff *skb) +{ + struct mpa_message *mpa; + u16 plen; + struct iwch_qp_attributes attrs; + enum iwch_qp_attr_mask mask; + int err; + + PDBG(""%s ep %p\n"", __func__, ep); + + /* + * Stop mpa timer. If it expired, then the state has + * changed and we bail since ep_timeout already aborted + * the connection. + */ + stop_ep_timer(ep); + if (state_read(&ep->com) != MPA_REQ_SENT) + return; + + /* + * If we get more than the supported amount of private data + * then we must fail this connection. + */ + if (ep->mpa_pkt_len + skb->len > sizeof(ep->mpa_pkt)) { + err = -EINVAL; + goto err; + } + + /* + * copy the new data into our accumulation buffer. + */ + skb_copy_from_linear_data(skb, &(ep->mpa_pkt[ep->mpa_pkt_len]), + skb->len); + ep->mpa_pkt_len += skb->len; + + /* + * if we don't even have the mpa message, then bail. + */ + if (ep->mpa_pkt_len < sizeof(*mpa)) + return; + mpa = (struct mpa_message *) ep->mpa_pkt; + + /* Validate MPA header. */ + if (mpa->revision != mpa_rev) { + err = -EPROTO; + goto err; + } + if (memcmp(mpa->key, MPA_KEY_REP, sizeof(mpa->key))) { + err = -EPROTO; + goto err; + } + + plen = ntohs(mpa->private_data_size); + + /* + * Fail if there's too much private data. + */ + if (plen > MPA_MAX_PRIVATE_DATA) { + err = -EPROTO; + goto err; + } + + /* + * If plen does not account for pkt size + */ + if (ep->mpa_pkt_len > (sizeof(*mpa) + plen)) { + err = -EPROTO; + goto err; + } + + ep->plen = (u8) plen; + + /* + * If we don't have all the pdata yet, then bail. + * We'll continue process when more data arrives. + */ + if (ep->mpa_pkt_len < (sizeof(*mpa) + plen)) + return; + + if (mpa->flags & MPA_REJECT) { + err = -ECONNREFUSED; + goto err; + } + + /* + * If we get here we have accumulated the entire mpa + * start reply message including private data. And + * the MPA header is valid. + */ + state_set(&ep->com, FPDU_MODE); + ep->mpa_attr.initiator = 1; + ep->mpa_attr.crc_enabled = (mpa->flags & MPA_CRC) | crc_enabled ? 1 : 0; + ep->mpa_attr.recv_marker_enabled = markers_enabled; + ep->mpa_attr.xmit_marker_enabled = mpa->flags & MPA_MARKERS ? 1 : 0; + ep->mpa_attr.version = mpa_rev; + PDBG(""%s - crc_enabled=%d, recv_marker_enabled=%d, "" + ""xmit_marker_enabled=%d, version=%d\n"", __func__, + ep->mpa_attr.crc_enabled, ep->mpa_attr.recv_marker_enabled, + ep->mpa_attr.xmit_marker_enabled, ep->mpa_attr.version); + + attrs.mpa_attr = ep->mpa_attr; + attrs.max_ird = ep->ird; + attrs.max_ord = ep->ord; + attrs.llp_stream_handle = ep; + attrs.next_state = IWCH_QP_STATE_RTS; + + mask = IWCH_QP_ATTR_NEXT_STATE | + IWCH_QP_ATTR_LLP_STREAM_HANDLE | IWCH_QP_ATTR_MPA_ATTR | + IWCH_QP_ATTR_MAX_IRD | IWCH_QP_ATTR_MAX_ORD; + + /* bind QP and TID with INIT_WR */ + err = iwch_modify_qp(ep->com.qp->rhp, + ep->com.qp, mask, &attrs, 1); + if (err) + goto err; + + if (peer2peer && iwch_rqes_posted(ep->com.qp) == 0) { + iwch_post_zb_read(ep); + } + + goto out; +err: + abort_connection(ep, skb, GFP_KERNEL); +out: + connect_reply_upcall(ep, err); + return; +} +",0,"static void process_mpa_reply(struct iwch_ep *ep, struct sk_buff *skb) +{ + struct mpa_message *mpa; + u16 plen; + struct iwch_qp_attributes attrs; + enum iwch_qp_attr_mask mask; + int err; + + PDBG(""%s ep %p\n"", __func__, ep); + + /* + * Stop mpa timer. If it expired, then the state has + * changed and we bail since ep_timeout already aborted + * the connection. + */ + stop_ep_timer(ep); + if (state_read(&ep->com) != MPA_REQ_SENT) + return; + + /* + * If we get more than the supported amount of private data + * then we must fail this connection. + */ + if (ep->mpa_pkt_len + skb->len > sizeof(ep->mpa_pkt)) { + err = -EINVAL; + goto err; + } + + /* + * copy the new data into our accumulation buffer. + */ + skb_copy_from_linear_data(skb, &(ep->mpa_pkt[ep->mpa_pkt_len]), + skb->len); + ep->mpa_pkt_len += skb->len; + + /* + * if we don't even have the mpa message, then bail. + */ + if (ep->mpa_pkt_len < sizeof(*mpa)) + return; + mpa = (struct mpa_message *) ep->mpa_pkt; + + /* Validate MPA header. */ + if (mpa->revision != mpa_rev) { + err = -EPROTO; + goto err; + } + if (memcmp(mpa->key, MPA_KEY_REP, sizeof(mpa->key))) { + err = -EPROTO; + goto err; + } + + plen = ntohs(mpa->private_data_size); + + /* + * Fail if there's too much private data. + */ + if (plen > MPA_MAX_PRIVATE_DATA) { + err = -EPROTO; + goto err; + } + + /* + * If plen does not account for pkt size + */ + if (ep->mpa_pkt_len > (sizeof(*mpa) + plen)) { + err = -EPROTO; + goto err; + } + + ep->plen = (u8) plen; + + /* + * If we don't have all the pdata yet, then bail. + * We'll continue process when more data arrives. + */ + if (ep->mpa_pkt_len < (sizeof(*mpa) + plen)) + return; + + if (mpa->flags & MPA_REJECT) { + err = -ECONNREFUSED; + goto err; + } + + /* + * If we get here we have accumulated the entire mpa + * start reply message including private data. And + * the MPA header is valid. + */ + state_set(&ep->com, FPDU_MODE); + ep->mpa_attr.initiator = 1; + ep->mpa_attr.crc_enabled = (mpa->flags & MPA_CRC) | crc_enabled ? 1 : 0; + ep->mpa_attr.recv_marker_enabled = markers_enabled; + ep->mpa_attr.xmit_marker_enabled = mpa->flags & MPA_MARKERS ? 1 : 0; + ep->mpa_attr.version = mpa_rev; + PDBG(""%s - crc_enabled=%d, recv_marker_enabled=%d, "" + ""xmit_marker_enabled=%d, version=%d\n"", __func__, + ep->mpa_attr.crc_enabled, ep->mpa_attr.recv_marker_enabled, + ep->mpa_attr.xmit_marker_enabled, ep->mpa_attr.version); + + attrs.mpa_attr = ep->mpa_attr; + attrs.max_ird = ep->ird; + attrs.max_ord = ep->ord; + attrs.llp_stream_handle = ep; + attrs.next_state = IWCH_QP_STATE_RTS; + + mask = IWCH_QP_ATTR_NEXT_STATE | + IWCH_QP_ATTR_LLP_STREAM_HANDLE | IWCH_QP_ATTR_MPA_ATTR | + IWCH_QP_ATTR_MAX_IRD | IWCH_QP_ATTR_MAX_ORD; + + /* bind QP and TID with INIT_WR */ + err = iwch_modify_qp(ep->com.qp->rhp, + ep->com.qp, mask, &attrs, 1); + if (err) + goto err; + + if (peer2peer && iwch_rqes_posted(ep->com.qp) == 0) { + iwch_post_zb_read(ep); + } + + goto out; +err: + abort_connection(ep, skb, GFP_KERNEL); +out: + connect_reply_upcall(ep, err); + return; +} +","@@ -149,7 +149,7 @@ static int iwch_l2t_send(struct t3cdev *tdev, struct sk_buff *skb, struct l2t_en + error = l2t_send(tdev, skb, l2e); + if (error < 0) + kfree_skb(skb); +- return error; ++ return error < 0 ? error : 0; + } + + int iwch_cxgb3_ofld_send(struct t3cdev *tdev, struct sk_buff *skb) +@@ -165,7 +165,7 @@ int iwch_cxgb3_ofld_send(struct t3cdev *tdev, struct sk_buff *skb) + error = cxgb3_ofld_send(tdev, skb); + if (error < 0) + kfree_skb(skb); +- return error; ++ return error < 0 ? error : 0; + } + + static void release_tid(struct t3cdev *tdev, u32 hwtid, struct sk_buff *skb)",973,1304,2048 +8856,"static void InsertSampler(FlowSource_t *fs, exporter_ipfix_domain_t *exporter, int32_t id, uint16_t mode, uint32_t interval) { +generic_sampler_t *sampler; + + dbg_printf(""[%u] Insert Sampler: Exporter is 0x%llu\n"", exporter->info.id, (long long unsigned)exporter); + if ( !exporter->sampler ) { + sampler = (generic_sampler_t *)malloc(sizeof(generic_sampler_t)); + if ( !sampler ) { + LogError( ""Process_v9: Panic! malloc(): %s line %d: %s"", __FILE__, __LINE__, strerror (errno)); + return; + } + + sampler->info.header.type = SamplerInfoRecordype; + sampler->info.header.size = sizeof(sampler_info_record_t); + sampler->info.exporter_sysid = exporter->info.sysid; + sampler->info.id = id; + sampler->info.mode = mode; + sampler->info.interval = interval; + sampler->next = NULL; + exporter->sampler = sampler; + + FlushInfoSampler(fs, &(sampler->info)); + LogInfo( ""Add new sampler: ID: %i, mode: %u, interval: %u\n"", + id, mode, interval); + dbg_printf(""Add new sampler: ID: %i, mode: %u, interval: %u\n"", + id, mode, interval); + + } else { + sampler = exporter->sampler; + while ( sampler ) { + if ( sampler->info.id == id ) { + dbg_printf(""Update existing sampler id: %i, mode: %u, interval: %u\n"", + id, mode, interval); + + if ( mode != sampler->info.mode || interval != sampler->info.interval ) { + FlushInfoSampler(fs, &(sampler->info)); + sampler->info.mode = mode; + sampler->info.interval = interval; + LogInfo( ""Update existing sampler id: %i, mode: %u, interval: %u\n"", + id, mode, interval); + } else { + dbg_printf(""Sampler unchanged!\n""); + } + + break; + } + + if ( sampler->next == NULL ) { + sampler->next = (generic_sampler_t *)malloc(sizeof(generic_sampler_t)); + if ( !sampler->next ) { + LogError( ""Process_v9: Panic! malloc(): %s line %d: %s"", __FILE__, __LINE__, strerror (errno)); + return; + } + sampler = sampler->next; + + sampler->info.header.type = SamplerInfoRecordype; + sampler->info.header.size = sizeof(sampler_info_record_t); + sampler->info.exporter_sysid = exporter->info.sysid; + sampler->info.id = id; + sampler->info.mode = mode; + sampler->info.interval = interval; + sampler->next = NULL; + + FlushInfoSampler(fs, &(sampler->info)); + + LogInfo( ""Append new sampler: ID: %u, mode: %u, interval: %u\n"", + id, mode, interval); + dbg_printf(""Append new sampler: ID: %u, mode: %u, interval: %u\n"", + id, mode, interval); + break; + } + + sampler = sampler->next; + } + } + +} // End of InsertSampler +",0,"static void InsertSampler(FlowSource_t *fs, exporter_ipfix_domain_t *exporter, int32_t id, uint16_t mode, uint32_t interval) { +generic_sampler_t *sampler; + + dbg_printf(""[%u] Insert Sampler: Exporter is 0x%llu\n"", exporter->info.id, (long long unsigned)exporter); + if ( !exporter->sampler ) { + sampler = (generic_sampler_t *)malloc(sizeof(generic_sampler_t)); + if ( !sampler ) { + LogError( ""Process_v9: Panic! malloc(): %s line %d: %s"", __FILE__, __LINE__, strerror (errno)); + return; + } + + sampler->info.header.type = SamplerInfoRecordype; + sampler->info.header.size = sizeof(sampler_info_record_t); + sampler->info.exporter_sysid = exporter->info.sysid; + sampler->info.id = id; + sampler->info.mode = mode; + sampler->info.interval = interval; + sampler->next = NULL; + exporter->sampler = sampler; + + FlushInfoSampler(fs, &(sampler->info)); + LogInfo( ""Add new sampler: ID: %i, mode: %u, interval: %u\n"", + id, mode, interval); + dbg_printf(""Add new sampler: ID: %i, mode: %u, interval: %u\n"", + id, mode, interval); + + } else { + sampler = exporter->sampler; + while ( sampler ) { + if ( sampler->info.id == id ) { + dbg_printf(""Update existing sampler id: %i, mode: %u, interval: %u\n"", + id, mode, interval); + + if ( mode != sampler->info.mode || interval != sampler->info.interval ) { + FlushInfoSampler(fs, &(sampler->info)); + sampler->info.mode = mode; + sampler->info.interval = interval; + LogInfo( ""Update existing sampler id: %i, mode: %u, interval: %u\n"", + id, mode, interval); + } else { + dbg_printf(""Sampler unchanged!\n""); + } + + break; + } + + if ( sampler->next == NULL ) { + sampler->next = (generic_sampler_t *)malloc(sizeof(generic_sampler_t)); + if ( !sampler->next ) { + LogError( ""Process_v9: Panic! malloc(): %s line %d: %s"", __FILE__, __LINE__, strerror (errno)); + return; + } + sampler = sampler->next; + + sampler->info.header.type = SamplerInfoRecordype; + sampler->info.header.size = sizeof(sampler_info_record_t); + sampler->info.exporter_sysid = exporter->info.sysid; + sampler->info.id = id; + sampler->info.mode = mode; + sampler->info.interval = interval; + sampler->next = NULL; + + FlushInfoSampler(fs, &(sampler->info)); + + LogInfo( ""Append new sampler: ID: %u, mode: %u, interval: %u\n"", + id, mode, interval); + dbg_printf(""Append new sampler: ID: %u, mode: %u, interval: %u\n"", + id, mode, interval); + break; + } + + sampler = sampler->next; + } + } + +} // End of InsertSampler +","@@ -1247,7 +1247,7 @@ int i; + uint32_t table_id, count, size_required; + uint32_t num_extensions = 0; + +- if ( size_left && size_left < 4 ) { ++ if ( size_left < 4 ) { + LogError(""Process_ipfix [%u] Template size error at %s line %u"" , + exporter->info.id, __FILE__, __LINE__, strerror (errno)); + size_left = 0; +@@ -1426,6 +1426,14 @@ ipfix_template_record_t *ipfix_template_record; + while ( size_left ) { + uint32_t id; + ++ if ( size_left < 4 ) { ++ LogError(""Process_ipfix [%u] Template withdraw size error at %s line %u"" , ++ exporter->info.id, __FILE__, __LINE__, strerror (errno)); ++ size_left = 0; ++ continue; ++ } ++ ++ + // map next record. + ipfix_template_record = (ipfix_template_record_t *)DataPtr; + size_left -= 4;",767,1098,2048 +3946,"infix(INFIX *in, bool first) +{ + if (in->curpol->type == VAL) + { + char *op = in->op + in->curpol->distance; + + RESIZEBUF(in, in->curpol->length * 2 + 5); + while (*op) + { + *(in->cur) = *op; + op++; + in->cur++; + } + if (in->curpol->flag & LVAR_SUBLEXEME) + { + *(in->cur) = '%'; + in->cur++; + } + if (in->curpol->flag & LVAR_INCASE) + { + *(in->cur) = '@'; + in->cur++; + } + if (in->curpol->flag & LVAR_ANYEND) + { + *(in->cur) = '*'; + in->cur++; + } + *(in->cur) = '\0'; + in->curpol++; + } + else if (in->curpol->val == (int32) '!') + { + bool isopr = false; + + RESIZEBUF(in, 1); + *(in->cur) = '!'; + in->cur++; + *(in->cur) = '\0'; + in->curpol++; + if (in->curpol->type == OPR) + { + isopr = true; + RESIZEBUF(in, 2); + sprintf(in->cur, ""( ""); + in->cur = strchr(in->cur, '\0'); + } + infix(in, isopr); + if (isopr) + { + RESIZEBUF(in, 2); + sprintf(in->cur, "" )""); + in->cur = strchr(in->cur, '\0'); + } + } + else + { + int32 op = in->curpol->val; + INFIX nrm; + + in->curpol++; + if (op == (int32) '|' && !first) + { + RESIZEBUF(in, 2); + sprintf(in->cur, ""( ""); + in->cur = strchr(in->cur, '\0'); + } + + nrm.curpol = in->curpol; + nrm.op = in->op; + nrm.buflen = 16; + nrm.cur = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen); + + /* get right operand */ + infix(&nrm, false); + + /* get & print left operand */ + in->curpol = nrm.curpol; + infix(in, false); + + /* print operator & right operand */ + RESIZEBUF(in, 3 + (nrm.cur - nrm.buf)); + sprintf(in->cur, "" %c %s"", op, nrm.buf); + in->cur = strchr(in->cur, '\0'); + pfree(nrm.buf); + + if (op == (int32) '|' && !first) + { + RESIZEBUF(in, 2); + sprintf(in->cur, "" )""); + in->cur = strchr(in->cur, '\0'); + } + } +} +",0,"infix(INFIX *in, bool first) +{ + if (in->curpol->type == VAL) + { + char *op = in->op + in->curpol->distance; + + RESIZEBUF(in, in->curpol->length * 2 + 5); + while (*op) + { + *(in->cur) = *op; + op++; + in->cur++; + } + if (in->curpol->flag & LVAR_SUBLEXEME) + { + *(in->cur) = '%'; + in->cur++; + } + if (in->curpol->flag & LVAR_INCASE) + { + *(in->cur) = '@'; + in->cur++; + } + if (in->curpol->flag & LVAR_ANYEND) + { + *(in->cur) = '*'; + in->cur++; + } + *(in->cur) = '\0'; + in->curpol++; + } + else if (in->curpol->val == (int32) '!') + { + bool isopr = false; + + RESIZEBUF(in, 1); + *(in->cur) = '!'; + in->cur++; + *(in->cur) = '\0'; + in->curpol++; + if (in->curpol->type == OPR) + { + isopr = true; + RESIZEBUF(in, 2); + sprintf(in->cur, ""( ""); + in->cur = strchr(in->cur, '\0'); + } + infix(in, isopr); + if (isopr) + { + RESIZEBUF(in, 2); + sprintf(in->cur, "" )""); + in->cur = strchr(in->cur, '\0'); + } + } + else + { + int32 op = in->curpol->val; + INFIX nrm; + + in->curpol++; + if (op == (int32) '|' && !first) + { + RESIZEBUF(in, 2); + sprintf(in->cur, ""( ""); + in->cur = strchr(in->cur, '\0'); + } + + nrm.curpol = in->curpol; + nrm.op = in->op; + nrm.buflen = 16; + nrm.cur = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen); + + /* get right operand */ + infix(&nrm, false); + + /* get & print left operand */ + in->curpol = nrm.curpol; + infix(in, false); + + /* print operator & right operand */ + RESIZEBUF(in, 3 + (nrm.cur - nrm.buf)); + sprintf(in->cur, "" %c %s"", op, nrm.buf); + in->cur = strchr(in->cur, '\0'); + pfree(nrm.buf); + + if (op == (int32) '|' && !first) + { + RESIZEBUF(in, 2); + sprintf(in->cur, "" )""); + in->cur = strchr(in->cur, '\0'); + } + } +} +","@@ -9,6 +9,7 @@ + + #include ""crc32.h"" + #include ""ltree.h"" ++#include ""miscadmin.h"" + + PG_FUNCTION_INFO_V1(ltxtq_in); + Datum ltxtq_in(PG_FUNCTION_ARGS); +@@ -212,6 +213,9 @@ makepol(QPRS_STATE *state) + int32 lenstack = 0; + uint16 flag = 0; + ++ /* since this function recurses, it could be driven to stack overflow */ ++ check_stack_depth(); ++ + while ((type = gettoken_query(state, &val, &lenval, &strval, &flag)) != END) + { + switch (type) +@@ -276,6 +280,9 @@ makepol(QPRS_STATE *state) + static void + findoprnd(ITEM *ptr, int32 *pos) + { ++ /* since this function recurses, it could be driven to stack overflow. */ ++ check_stack_depth(); ++ + if (ptr[*pos].type == VAL || ptr[*pos].type == VALTRUE) + { + ptr[*pos].left = 0; +@@ -340,8 +347,12 @@ queryin(char *buf) + errmsg(""syntax error""), + errdetail(""Empty query.""))); + +- /* make finish struct */ ++ if (LTXTQUERY_TOO_BIG(state.num, state.sumlen)) ++ ereport(ERROR, ++ (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), ++ errmsg(""ltxtquery is too large""))); + commonlen = COMPUTESIZE(state.num, state.sumlen); ++ + query = (ltxtquery *) palloc(commonlen); + SET_VARSIZE(query, commonlen); + query->size = state.num;",704,1035,2048 +973,"int tls1_shared_curve(SSL *s, int nmatch) +{ + const unsigned char *pref, *supp; + size_t num_pref, num_supp, i, j; + int k; + /* Can't do anything on client side */ + if (s->server == 0) + return -1; + if (nmatch == -2) { + if (tls1_suiteb(s)) { + /* + * For Suite B ciphersuite determines curve: we already know + * these are acceptable due to previous checks. + */ + unsigned long cid = s->s3->tmp.new_cipher->id; + if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256) + return NID_X9_62_prime256v1; /* P-256 */ + if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384) + return NID_secp384r1; /* P-384 */ + /* Should never happen */ + return NID_undef; + } + /* If not Suite B just return first preference shared curve */ + nmatch = 0; + } + /* + * Avoid truncation. tls1_get_curvelist takes an int + * but s->options is a long... + */ + if (!tls1_get_curvelist + (s, (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) != 0, &supp, + &num_supp)) + /* In practice, NID_undef == 0 but let's be precise. */ + return nmatch == -1 ? 0 : NID_undef; + if (!tls1_get_curvelist + (s, !(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE), &pref, &num_pref)) + return nmatch == -1 ? 0 : NID_undef; + + /* + * If the client didn't send the elliptic_curves extension all of them + * are allowed. + */ + if (num_supp == 0 && (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) != 0) { + supp = eccurves_all; + num_supp = sizeof(eccurves_all) / 2; + } else if (num_pref == 0 && + (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) == 0) { + pref = eccurves_all; + num_pref = sizeof(eccurves_all) / 2; + } + + k = 0; + for (i = 0; i < num_pref; i++, pref += 2) { + const unsigned char *tsupp = supp; + for (j = 0; j < num_supp; j++, tsupp += 2) { + if (pref[0] == tsupp[0] && pref[1] == tsupp[1]) { + if (!tls_curve_allowed(s, pref, SSL_SECOP_CURVE_SHARED)) + continue; + if (nmatch == k) { + int id = (pref[0] << 8) | pref[1]; + return tls1_ec_curve_id2nid(id, NULL); + } + k++; + } + } + } + if (nmatch == -1) + return k; + /* Out of range (nmatch > k). */ + return NID_undef; +} +",0,"int tls1_shared_curve(SSL *s, int nmatch) +{ + const unsigned char *pref, *supp; + size_t num_pref, num_supp, i, j; + int k; + /* Can't do anything on client side */ + if (s->server == 0) + return -1; + if (nmatch == -2) { + if (tls1_suiteb(s)) { + /* + * For Suite B ciphersuite determines curve: we already know + * these are acceptable due to previous checks. + */ + unsigned long cid = s->s3->tmp.new_cipher->id; + if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256) + return NID_X9_62_prime256v1; /* P-256 */ + if (cid == TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384) + return NID_secp384r1; /* P-384 */ + /* Should never happen */ + return NID_undef; + } + /* If not Suite B just return first preference shared curve */ + nmatch = 0; + } + /* + * Avoid truncation. tls1_get_curvelist takes an int + * but s->options is a long... + */ + if (!tls1_get_curvelist + (s, (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) != 0, &supp, + &num_supp)) + /* In practice, NID_undef == 0 but let's be precise. */ + return nmatch == -1 ? 0 : NID_undef; + if (!tls1_get_curvelist + (s, !(s->options & SSL_OP_CIPHER_SERVER_PREFERENCE), &pref, &num_pref)) + return nmatch == -1 ? 0 : NID_undef; + + /* + * If the client didn't send the elliptic_curves extension all of them + * are allowed. + */ + if (num_supp == 0 && (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) != 0) { + supp = eccurves_all; + num_supp = sizeof(eccurves_all) / 2; + } else if (num_pref == 0 && + (s->options & SSL_OP_CIPHER_SERVER_PREFERENCE) == 0) { + pref = eccurves_all; + num_pref = sizeof(eccurves_all) / 2; + } + + k = 0; + for (i = 0; i < num_pref; i++, pref += 2) { + const unsigned char *tsupp = supp; + for (j = 0; j < num_supp; j++, tsupp += 2) { + if (pref[0] == tsupp[0] && pref[1] == tsupp[1]) { + if (!tls_curve_allowed(s, pref, SSL_SECOP_CURVE_SHARED)) + continue; + if (nmatch == k) { + int id = (pref[0] << 8) | pref[1]; + return tls1_ec_curve_id2nid(id, NULL); + } + k++; + } + } + } + if (nmatch == -1) + return k; + /* Out of range (nmatch > k). */ + return NID_undef; +} +","@@ -2969,9 +2969,7 @@ static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, + HMAC_CTX *hctx = NULL; + EVP_CIPHER_CTX *ctx; + SSL_CTX *tctx = s->initial_ctx; +- /* Need at least keyname + iv + some encrypted data */ +- if (eticklen < 48) +- return 2; ++ + /* Initialize session ticket encryption and HMAC contexts */ + hctx = HMAC_CTX_new(); + if (hctx == NULL) +@@ -3018,6 +3016,12 @@ static int tls_decrypt_ticket(SSL *s, const unsigned char *etick, + if (mlen < 0) { + goto err; + } ++ /* Sanity check ticket length: must exceed keyname + IV + HMAC */ ++ if (eticklen <= ++ TLSEXT_KEYNAME_LENGTH + EVP_CIPHER_CTX_iv_length(ctx) + mlen) { ++ ret = 2; ++ goto err; ++ } + eticklen -= mlen; + /* Check HMAC of encrypted ticket */ + if (HMAC_Update(hctx, etick, eticklen) <= 0",738,1069,2048 +10274,"void Browser::Observe(NotificationType type, + const NotificationSource& source, + const NotificationDetails& details) { + switch (type.value) { + case NotificationType::TAB_CONTENTS_DISCONNECTED: + if (is_attempting_to_close_browser_) { + ClearUnloadState(Source(source).ptr(), false); + } + break; + + case NotificationType::SSL_VISIBLE_STATE_CHANGED: + if (GetSelectedTabContents() && + &GetSelectedTabContents()->controller() == + Source(source).ptr()) + UpdateToolbar(false); + break; + + case NotificationType::EXTENSION_UPDATE_DISABLED: { + Profile* profile = Source(source).ptr(); + if (profile_->IsSameProfile(profile)) { + ExtensionService* service = profile->GetExtensionService(); + DCHECK(service); + const Extension* extension = Details(details).ptr(); + if (service->extension_prefs()->DidExtensionEscalatePermissions( + extension->id())) + ShowExtensionDisabledUI(service, profile_, extension); + } + break; + } + + case NotificationType::EXTENSION_UNLOADED: { + window()->GetLocationBar()->UpdatePageActions(); + + const Extension* extension = + Details(details)->extension; + TabStripModel* model = tab_handler_->GetTabStripModel(); + for (int i = model->count() - 1; i >= 0; --i) { + TabContents* tc = model->GetTabContentsAt(i)->tab_contents(); + if (tc->GetURL().SchemeIs(chrome::kExtensionScheme) && + tc->GetURL().host() == extension->id()) { + CloseTabContents(tc); + } + } + + break; + } + + case NotificationType::EXTENSION_PROCESS_TERMINATED: { + window()->GetLocationBar()->InvalidatePageActions(); + break; + } + + case NotificationType::EXTENSION_UNINSTALLED: + case NotificationType::EXTENSION_LOADED: + window()->GetLocationBar()->UpdatePageActions(); + break; + + case NotificationType::BROWSER_THEME_CHANGED: + window()->UserChangedTheme(); + break; + + case NotificationType::EXTENSION_READY_FOR_INSTALL: { + if (BrowserList::FindBrowserWithType(profile(), + Browser::TYPE_NORMAL, + true) != this) + break; + + GURL download_url = *(Details(details).ptr()); + if (ExtensionService::IsDownloadFromMiniGallery(download_url)) + window()->ShowThemeInstallBubble(); + break; + } + + case NotificationType::PREF_CHANGED: { + const std::string& pref_name = *Details(details).ptr(); + if (pref_name == prefs::kUseVerticalTabs) { + UseVerticalTabsChanged(); + } else if (pref_name == prefs::kPrintingEnabled) { + UpdatePrintingState(GetContentRestrictionsForSelectedTab()); + } else if (pref_name == prefs::kInstantEnabled) { + if (!InstantController::IsEnabled(profile())) { + if (instant()) { + instant()->DestroyPreviewContents(); + instant_.reset(); + instant_unload_handler_.reset(); + } + } else { + CreateInstantIfNecessary(); + } + } else if (pref_name == prefs::kDevToolsDisabled) { + UpdateCommandsForDevTools(); + if (dev_tools_disabled_.GetValue()) + g_browser_process->devtools_manager()->CloseAllClientHosts(); + } else if (pref_name == prefs::kIncognitoEnabled) { + break; // No further action is required. + } else if (pref_name == prefs::kEditBookmarksEnabled) { + UpdateCommandsForBookmarkEditing(); + } else { + NOTREACHED(); + } + break; + } + + default: + NOTREACHED() << ""Got a notification we didn't register for.""; + } +} +",0,"void Browser::Observe(NotificationType type, + const NotificationSource& source, + const NotificationDetails& details) { + switch (type.value) { + case NotificationType::TAB_CONTENTS_DISCONNECTED: + if (is_attempting_to_close_browser_) { + ClearUnloadState(Source(source).ptr(), false); + } + break; + + case NotificationType::SSL_VISIBLE_STATE_CHANGED: + if (GetSelectedTabContents() && + &GetSelectedTabContents()->controller() == + Source(source).ptr()) + UpdateToolbar(false); + break; + + case NotificationType::EXTENSION_UPDATE_DISABLED: { + Profile* profile = Source(source).ptr(); + if (profile_->IsSameProfile(profile)) { + ExtensionService* service = profile->GetExtensionService(); + DCHECK(service); + const Extension* extension = Details(details).ptr(); + if (service->extension_prefs()->DidExtensionEscalatePermissions( + extension->id())) + ShowExtensionDisabledUI(service, profile_, extension); + } + break; + } + + case NotificationType::EXTENSION_UNLOADED: { + window()->GetLocationBar()->UpdatePageActions(); + + const Extension* extension = + Details(details)->extension; + TabStripModel* model = tab_handler_->GetTabStripModel(); + for (int i = model->count() - 1; i >= 0; --i) { + TabContents* tc = model->GetTabContentsAt(i)->tab_contents(); + if (tc->GetURL().SchemeIs(chrome::kExtensionScheme) && + tc->GetURL().host() == extension->id()) { + CloseTabContents(tc); + } + } + + break; + } + + case NotificationType::EXTENSION_PROCESS_TERMINATED: { + window()->GetLocationBar()->InvalidatePageActions(); + break; + } + + case NotificationType::EXTENSION_UNINSTALLED: + case NotificationType::EXTENSION_LOADED: + window()->GetLocationBar()->UpdatePageActions(); + break; + + case NotificationType::BROWSER_THEME_CHANGED: + window()->UserChangedTheme(); + break; + + case NotificationType::EXTENSION_READY_FOR_INSTALL: { + if (BrowserList::FindBrowserWithType(profile(), + Browser::TYPE_NORMAL, + true) != this) + break; + + GURL download_url = *(Details(details).ptr()); + if (ExtensionService::IsDownloadFromMiniGallery(download_url)) + window()->ShowThemeInstallBubble(); + break; + } + + case NotificationType::PREF_CHANGED: { + const std::string& pref_name = *Details(details).ptr(); + if (pref_name == prefs::kUseVerticalTabs) { + UseVerticalTabsChanged(); + } else if (pref_name == prefs::kPrintingEnabled) { + UpdatePrintingState(GetContentRestrictionsForSelectedTab()); + } else if (pref_name == prefs::kInstantEnabled) { + if (!InstantController::IsEnabled(profile())) { + if (instant()) { + instant()->DestroyPreviewContents(); + instant_.reset(); + instant_unload_handler_.reset(); + } + } else { + CreateInstantIfNecessary(); + } + } else if (pref_name == prefs::kDevToolsDisabled) { + UpdateCommandsForDevTools(); + if (dev_tools_disabled_.GetValue()) + g_browser_process->devtools_manager()->CloseAllClientHosts(); + } else if (pref_name == prefs::kIncognitoEnabled) { + break; // No further action is required. + } else if (pref_name == prefs::kEditBookmarksEnabled) { + UpdateCommandsForBookmarkEditing(); + } else { + NOTREACHED(); + } + break; + } + + default: + NOTREACHED() << ""Got a notification we didn't register for.""; + } +} +","@@ -2635,16 +2635,25 @@ bool Browser::CanReloadContents(TabContents* source) const { + return type() != TYPE_DEVTOOLS; + } + +-bool Browser::CanCloseContentsAt(int index) { +- if (!CanCloseTab()) ++bool Browser::CanCloseContents(std::vector* indices) { ++ DCHECK(!indices->empty()); ++ TabCloseableStateWatcher* watcher = ++ g_browser_process->tab_closeable_state_watcher(); ++ bool can_close_all = !watcher || watcher->CanCloseTabs(this, indices); ++ if (indices->empty()) // Cannot close any tab. + return false; +- if (tab_handler_->GetTabStripModel()->count() > 1) +- return true; +- // We are closing the last tab for this browser. Make sure to check for ++ // Now, handle cases where at least one tab can be closed. ++ // If we are closing all the tabs for this browser, make sure to check for + // in-progress downloads. + // Note that the next call when it returns false will ask the user for + // confirmation before closing the browser if the user decides so. +- return CanCloseWithInProgressDownloads(); ++ if (tab_handler_->GetTabStripModel()->count() == ++ static_cast(indices->size()) && ++ !CanCloseWithInProgressDownloads()) { ++ indices->clear(); ++ can_close_all = false; ++ } ++ return can_close_all; + } + + bool Browser::CanBookmarkAllTabs() const {",808,1139,2048 +4872,"void t2p_read_tiff_size(T2P* t2p, TIFF* input){ + + uint64* sbc=NULL; +#if defined(JPEG_SUPPORT) || defined (OJPEG_SUPPORT) + unsigned char* jpt=NULL; + tstrip_t i=0; + tstrip_t stripcount=0; +#endif + uint64 k = 0; + + if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ +#ifdef CCITT_SUPPORT + if(t2p->pdf_compression == T2P_COMPRESS_G4 ){ + TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); + t2p->tiff_datasize=(tmsize_t)sbc[0]; + return; + } +#endif +#ifdef ZIP_SUPPORT + if(t2p->pdf_compression == T2P_COMPRESS_ZIP){ + TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); + t2p->tiff_datasize=(tmsize_t)sbc[0]; + return; + } +#endif +#ifdef OJPEG_SUPPORT + if(t2p->tiff_compression == COMPRESSION_OJPEG){ + if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){ + TIFFError(TIFF2PDF_MODULE, + ""Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS"", + TIFFFileName(input)); + t2p->t2p_error = T2P_ERR_ERROR; + return; + } + stripcount=TIFFNumberOfStrips(input); + for(i=0;itiff_dataoffset))){ + if(t2p->tiff_dataoffset != 0){ + if(TIFFGetField(input, TIFFTAG_JPEGIFBYTECOUNT, &(t2p->tiff_datasize))!=0){ + if((uint64)t2p->tiff_datasize < k) { + TIFFWarning(TIFF2PDF_MODULE, + ""Input file %s has short JPEG interchange file byte count"", + TIFFFileName(input)); + t2p->pdf_ojpegiflength=t2p->tiff_datasize; + k = checkAdd64(k, t2p->tiff_datasize, t2p); + k = checkAdd64(k, 6, t2p); + k = checkAdd64(k, stripcount, t2p); + k = checkAdd64(k, stripcount, t2p); + t2p->tiff_datasize = (tsize_t) k; + if ((uint64) t2p->tiff_datasize != k) { + TIFFError(TIFF2PDF_MODULE, ""Integer overflow""); + t2p->t2p_error = T2P_ERR_ERROR; + } + return; + } + return; + }else { + TIFFError(TIFF2PDF_MODULE, + ""Input file %s missing field: TIFFTAG_JPEGIFBYTECOUNT"", + TIFFFileName(input)); + t2p->t2p_error = T2P_ERR_ERROR; + return; + } + } + } + k = checkAdd64(k, stripcount, t2p); + k = checkAdd64(k, stripcount, t2p); + k = checkAdd64(k, 2048, t2p); + t2p->tiff_datasize = (tsize_t) k; + if ((uint64) t2p->tiff_datasize != k) { + TIFFError(TIFF2PDF_MODULE, ""Integer overflow""); + t2p->t2p_error = T2P_ERR_ERROR; + } + return; + } +#endif +#ifdef JPEG_SUPPORT + if(t2p->tiff_compression == COMPRESSION_JPEG) { + uint32 count = 0; + if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0 ){ + if(count > 4){ + k += count; + k -= 2; /* don't use EOI of header */ + } + } else { + k = 2; /* SOI for first strip */ + } + stripcount=TIFFNumberOfStrips(input); + if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){ + TIFFError(TIFF2PDF_MODULE, + ""Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS"", + TIFFFileName(input)); + t2p->t2p_error = T2P_ERR_ERROR; + return; + } + for(i=0;itiff_datasize = (tsize_t) k; + if ((uint64) t2p->tiff_datasize != k) { + TIFFError(TIFF2PDF_MODULE, ""Integer overflow""); + t2p->t2p_error = T2P_ERR_ERROR; + } + return; + } +#endif + (void) 0; + } + k = checkMultiply64(TIFFScanlineSize(input), t2p->tiff_length, t2p); + if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ + k = checkMultiply64(k, t2p->tiff_samplesperpixel, t2p); + } + if (k == 0) { + /* Assume we had overflow inside TIFFScanlineSize */ + t2p->t2p_error = T2P_ERR_ERROR; + } + + t2p->tiff_datasize = (tsize_t) k; + if ((uint64) t2p->tiff_datasize != k) { + TIFFError(TIFF2PDF_MODULE, ""Integer overflow""); + t2p->t2p_error = T2P_ERR_ERROR; + } + + return; +} +",0,"void t2p_read_tiff_size(T2P* t2p, TIFF* input){ + + uint64* sbc=NULL; +#if defined(JPEG_SUPPORT) || defined (OJPEG_SUPPORT) + unsigned char* jpt=NULL; + tstrip_t i=0; + tstrip_t stripcount=0; +#endif + uint64 k = 0; + + if(t2p->pdf_transcode == T2P_TRANSCODE_RAW){ +#ifdef CCITT_SUPPORT + if(t2p->pdf_compression == T2P_COMPRESS_G4 ){ + TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); + t2p->tiff_datasize=(tmsize_t)sbc[0]; + return; + } +#endif +#ifdef ZIP_SUPPORT + if(t2p->pdf_compression == T2P_COMPRESS_ZIP){ + TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc); + t2p->tiff_datasize=(tmsize_t)sbc[0]; + return; + } +#endif +#ifdef OJPEG_SUPPORT + if(t2p->tiff_compression == COMPRESSION_OJPEG){ + if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){ + TIFFError(TIFF2PDF_MODULE, + ""Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS"", + TIFFFileName(input)); + t2p->t2p_error = T2P_ERR_ERROR; + return; + } + stripcount=TIFFNumberOfStrips(input); + for(i=0;itiff_dataoffset))){ + if(t2p->tiff_dataoffset != 0){ + if(TIFFGetField(input, TIFFTAG_JPEGIFBYTECOUNT, &(t2p->tiff_datasize))!=0){ + if((uint64)t2p->tiff_datasize < k) { + TIFFWarning(TIFF2PDF_MODULE, + ""Input file %s has short JPEG interchange file byte count"", + TIFFFileName(input)); + t2p->pdf_ojpegiflength=t2p->tiff_datasize; + k = checkAdd64(k, t2p->tiff_datasize, t2p); + k = checkAdd64(k, 6, t2p); + k = checkAdd64(k, stripcount, t2p); + k = checkAdd64(k, stripcount, t2p); + t2p->tiff_datasize = (tsize_t) k; + if ((uint64) t2p->tiff_datasize != k) { + TIFFError(TIFF2PDF_MODULE, ""Integer overflow""); + t2p->t2p_error = T2P_ERR_ERROR; + } + return; + } + return; + }else { + TIFFError(TIFF2PDF_MODULE, + ""Input file %s missing field: TIFFTAG_JPEGIFBYTECOUNT"", + TIFFFileName(input)); + t2p->t2p_error = T2P_ERR_ERROR; + return; + } + } + } + k = checkAdd64(k, stripcount, t2p); + k = checkAdd64(k, stripcount, t2p); + k = checkAdd64(k, 2048, t2p); + t2p->tiff_datasize = (tsize_t) k; + if ((uint64) t2p->tiff_datasize != k) { + TIFFError(TIFF2PDF_MODULE, ""Integer overflow""); + t2p->t2p_error = T2P_ERR_ERROR; + } + return; + } +#endif +#ifdef JPEG_SUPPORT + if(t2p->tiff_compression == COMPRESSION_JPEG) { + uint32 count = 0; + if(TIFFGetField(input, TIFFTAG_JPEGTABLES, &count, &jpt) != 0 ){ + if(count > 4){ + k += count; + k -= 2; /* don't use EOI of header */ + } + } else { + k = 2; /* SOI for first strip */ + } + stripcount=TIFFNumberOfStrips(input); + if(!TIFFGetField(input, TIFFTAG_STRIPBYTECOUNTS, &sbc)){ + TIFFError(TIFF2PDF_MODULE, + ""Input file %s missing field: TIFFTAG_STRIPBYTECOUNTS"", + TIFFFileName(input)); + t2p->t2p_error = T2P_ERR_ERROR; + return; + } + for(i=0;itiff_datasize = (tsize_t) k; + if ((uint64) t2p->tiff_datasize != k) { + TIFFError(TIFF2PDF_MODULE, ""Integer overflow""); + t2p->t2p_error = T2P_ERR_ERROR; + } + return; + } +#endif + (void) 0; + } + k = checkMultiply64(TIFFScanlineSize(input), t2p->tiff_length, t2p); + if(t2p->tiff_planar==PLANARCONFIG_SEPARATE){ + k = checkMultiply64(k, t2p->tiff_samplesperpixel, t2p); + } + if (k == 0) { + /* Assume we had overflow inside TIFFScanlineSize */ + t2p->t2p_error = T2P_ERR_ERROR; + } + + t2p->tiff_datasize = (tsize_t) k; + if ((uint64) t2p->tiff_datasize != k) { + TIFFError(TIFF2PDF_MODULE, ""Integer overflow""); + t2p->t2p_error = T2P_ERR_ERROR; + } + + return; +} +","@@ -286,7 +286,7 @@ tsize_t t2p_readwrite_pdf_image_tile(T2P*, TIFF*, TIFF*, ttile_t); + int t2p_process_ojpeg_tables(T2P*, TIFF*); + #endif + #ifdef JPEG_SUPPORT +-int t2p_process_jpeg_strip(unsigned char*, tsize_t*, unsigned char*, tsize_t*, tstrip_t, uint32); ++int t2p_process_jpeg_strip(unsigned char*, tsize_t*, unsigned char*, tsize_t, tsize_t*, tstrip_t, uint32); + #endif + void t2p_tile_collapse_left(tdata_t, tsize_t, uint32, uint32, uint32); + void t2p_write_advance_directory(T2P*, TIFF*); +@@ -2408,7 +2408,8 @@ tsize_t t2p_readwrite_pdf_image(T2P* t2p, TIFF* input, TIFF* output){ + if(!t2p_process_jpeg_strip( + stripbuffer, + &striplength, +- buffer, ++ buffer, ++ t2p->tiff_datasize, + &bufferoffset, + i, + t2p->tiff_length)){ +@@ -3439,6 +3440,7 @@ int t2p_process_jpeg_strip( + unsigned char* strip, + tsize_t* striplength, + unsigned char* buffer, ++ tsize_t buffersize, + tsize_t* bufferoffset, + tstrip_t no, + uint32 height){ +@@ -3473,6 +3475,8 @@ int t2p_process_jpeg_strip( + } + switch( strip[i] ){ + case 0xd8: /* SOI - start of image */ ++ if( *bufferoffset + 2 > buffersize ) ++ return(0); + _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), 2); + *bufferoffset+=2; + break; +@@ -3482,12 +3486,18 @@ int t2p_process_jpeg_strip( + case 0xc9: /* SOF9 */ + case 0xca: /* SOF10 */ + if(no==0){ ++ if( *bufferoffset + datalen + 2 + 6 > buffersize ) ++ return(0); + _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); ++ if( *bufferoffset + 9 >= buffersize ) ++ return(0); + ncomp = buffer[*bufferoffset+9]; + if (ncomp < 1 || ncomp > 4) + return(0); + v_samp=1; + h_samp=1; ++ if( *bufferoffset + 11 + 3*(ncomp-1) >= buffersize ) ++ return(0); + for(j=0;j>4) > h_samp) +@@ -3519,20 +3529,28 @@ int t2p_process_jpeg_strip( + break; + case 0xc4: /* DHT */ + case 0xdb: /* DQT */ ++ if( *bufferoffset + datalen + 2 > buffersize ) ++ return(0); + _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); + *bufferoffset+=datalen+2; + break; + case 0xda: /* SOS */ + if(no==0){ ++ if( *bufferoffset + datalen + 2 > buffersize ) ++ return(0); + _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i-1]), datalen+2); + *bufferoffset+=datalen+2; + } else { ++ if( *bufferoffset + 2 > buffersize ) ++ return(0); + buffer[(*bufferoffset)++]=0xff; + buffer[(*bufferoffset)++]= + (unsigned char)(0xd0 | ((no-1)%8)); + } + i += datalen + 1; + /* copy remainder of strip */ ++ if( *bufferoffset + *striplength - i > buffersize ) ++ return(0); + _TIFFmemcpy(&(buffer[*bufferoffset]), &(strip[i]), *striplength - i); + *bufferoffset+= *striplength - i; + return(1);",1411,1742,2048 +5020,"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; +} +",0,"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; +} +","@@ -2388,7 +2388,8 @@ static int arcmsr_iop_message_xfer(struct AdapterControlBlock *acb, + } + case ARCMSR_MESSAGE_WRITE_WQBUFFER: { + unsigned char *ver_addr; +- int32_t user_len, cnt2end; ++ uint32_t user_len; ++ int32_t cnt2end; + uint8_t *pQbuffer, *ptmpuserbuffer; + ver_addr = kmalloc(ARCMSR_API_DATA_BUFLEN, GFP_ATOMIC); + if (!ver_addr) { +@@ -2397,6 +2398,11 @@ static int arcmsr_iop_message_xfer(struct AdapterControlBlock *acb, + } + 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);",1295,1626,2048 +265,"char *vfs_GetWd(TALLOC_CTX *ctx, connection_struct *conn) +{ + char *current_dir = NULL; + char *result = NULL; + DATA_BLOB cache_value; + struct file_id key; + struct smb_filename *smb_fname_dot = NULL; + struct smb_filename *smb_fname_full = NULL; + + if (!lp_getwd_cache()) { + goto nocache; + } + + smb_fname_dot = synthetic_smb_fname(ctx, ""."", NULL, NULL); + if (smb_fname_dot == NULL) { + errno = ENOMEM; + goto out; + } + + if (SMB_VFS_STAT(conn, smb_fname_dot) == -1) { + /* + * Known to fail for root: the directory may be NFS-mounted + * and exported with root_squash (so has no root access). + */ + DEBUG(1,(""vfs_GetWd: couldn't stat \"".\"" error %s "" + ""(NFS problem ?)\n"", strerror(errno) )); + goto nocache; + } + + key = vfs_file_id_from_sbuf(conn, &smb_fname_dot->st); + + if (!memcache_lookup(smbd_memcache(), GETWD_CACHE, + data_blob_const(&key, sizeof(key)), + &cache_value)) { + goto nocache; + } + + SMB_ASSERT((cache_value.length > 0) + && (cache_value.data[cache_value.length-1] == '\0')); + + smb_fname_full = synthetic_smb_fname(ctx, (char *)cache_value.data, + NULL, NULL); + if (smb_fname_full == NULL) { + errno = ENOMEM; + goto out; + } + + if ((SMB_VFS_STAT(conn, smb_fname_full) == 0) && + (smb_fname_dot->st.st_ex_dev == smb_fname_full->st.st_ex_dev) && + (smb_fname_dot->st.st_ex_ino == smb_fname_full->st.st_ex_ino) && + (S_ISDIR(smb_fname_dot->st.st_ex_mode))) { + /* + * Ok, we're done + */ + result = talloc_strdup(ctx, smb_fname_full->base_name); + if (result == NULL) { + errno = ENOMEM; + } + goto out; + } + + nocache: + + /* + * We don't have the information to hand so rely on traditional + * methods. The very slow getcwd, which spawns a process on some + * systems, or the not quite so bad getwd. + */ + + current_dir = SMB_VFS_GETWD(conn); + if (current_dir == NULL) { + DEBUG(0, (""vfs_GetWd: SMB_VFS_GETWD call failed: %s\n"", + strerror(errno))); + goto out; + } + + if (lp_getwd_cache() && VALID_STAT(smb_fname_dot->st)) { + key = vfs_file_id_from_sbuf(conn, &smb_fname_dot->st); + + memcache_add(smbd_memcache(), GETWD_CACHE, + data_blob_const(&key, sizeof(key)), + data_blob_const(current_dir, + strlen(current_dir)+1)); + } + + result = talloc_strdup(ctx, current_dir); + if (result == NULL) { + errno = ENOMEM; + } + + out: + TALLOC_FREE(smb_fname_dot); + TALLOC_FREE(smb_fname_full); + SAFE_FREE(current_dir); + return result; +} +",0,"char *vfs_GetWd(TALLOC_CTX *ctx, connection_struct *conn) +{ + char *current_dir = NULL; + char *result = NULL; + DATA_BLOB cache_value; + struct file_id key; + struct smb_filename *smb_fname_dot = NULL; + struct smb_filename *smb_fname_full = NULL; + + if (!lp_getwd_cache()) { + goto nocache; + } + + smb_fname_dot = synthetic_smb_fname(ctx, ""."", NULL, NULL); + if (smb_fname_dot == NULL) { + errno = ENOMEM; + goto out; + } + + if (SMB_VFS_STAT(conn, smb_fname_dot) == -1) { + /* + * Known to fail for root: the directory may be NFS-mounted + * and exported with root_squash (so has no root access). + */ + DEBUG(1,(""vfs_GetWd: couldn't stat \"".\"" error %s "" + ""(NFS problem ?)\n"", strerror(errno) )); + goto nocache; + } + + key = vfs_file_id_from_sbuf(conn, &smb_fname_dot->st); + + if (!memcache_lookup(smbd_memcache(), GETWD_CACHE, + data_blob_const(&key, sizeof(key)), + &cache_value)) { + goto nocache; + } + + SMB_ASSERT((cache_value.length > 0) + && (cache_value.data[cache_value.length-1] == '\0')); + + smb_fname_full = synthetic_smb_fname(ctx, (char *)cache_value.data, + NULL, NULL); + if (smb_fname_full == NULL) { + errno = ENOMEM; + goto out; + } + + if ((SMB_VFS_STAT(conn, smb_fname_full) == 0) && + (smb_fname_dot->st.st_ex_dev == smb_fname_full->st.st_ex_dev) && + (smb_fname_dot->st.st_ex_ino == smb_fname_full->st.st_ex_ino) && + (S_ISDIR(smb_fname_dot->st.st_ex_mode))) { + /* + * Ok, we're done + */ + result = talloc_strdup(ctx, smb_fname_full->base_name); + if (result == NULL) { + errno = ENOMEM; + } + goto out; + } + + nocache: + + /* + * We don't have the information to hand so rely on traditional + * methods. The very slow getcwd, which spawns a process on some + * systems, or the not quite so bad getwd. + */ + + current_dir = SMB_VFS_GETWD(conn); + if (current_dir == NULL) { + DEBUG(0, (""vfs_GetWd: SMB_VFS_GETWD call failed: %s\n"", + strerror(errno))); + goto out; + } + + if (lp_getwd_cache() && VALID_STAT(smb_fname_dot->st)) { + key = vfs_file_id_from_sbuf(conn, &smb_fname_dot->st); + + memcache_add(smbd_memcache(), GETWD_CACHE, + data_blob_const(&key, sizeof(key)), + data_blob_const(current_dir, + strlen(current_dir)+1)); + } + + result = talloc_strdup(ctx, current_dir); + if (result == NULL) { + errno = ENOMEM; + } + + out: + TALLOC_FREE(smb_fname_dot); + TALLOC_FREE(smb_fname_full); + SAFE_FREE(current_dir); + return result; +} +","@@ -982,6 +982,7 @@ NTSTATUS check_reduced_name_with_privilege(connection_struct *conn, + struct smb_filename *smb_fname_cwd = NULL; + struct privilege_paths *priv_paths = NULL; + int ret; ++ bool matched; + + DEBUG(3,(""check_reduced_name_with_privilege [%s] [%s]\n"", + fname, +@@ -1076,7 +1077,10 @@ NTSTATUS check_reduced_name_with_privilege(connection_struct *conn, + } + + rootdir_len = strlen(conn_rootdir); +- if (strncmp(conn_rootdir, resolved_name, rootdir_len) != 0) { ++ matched = (strncmp(conn_rootdir, resolved_name, rootdir_len) == 0); ++ ++ if (!matched || (resolved_name[rootdir_len] != '/' && ++ resolved_name[rootdir_len] != '\0')) { + DEBUG(2, (""check_reduced_name_with_privilege: Bad access "" + ""attempt: %s is a symlink outside the "" + ""share path\n"", +@@ -1216,6 +1220,7 @@ NTSTATUS check_reduced_name(connection_struct *conn, const char *fname) + if (!allow_widelinks || !allow_symlinks) { + const char *conn_rootdir; + size_t rootdir_len; ++ bool matched; + + conn_rootdir = SMB_VFS_CONNECTPATH(conn, fname); + if (conn_rootdir == NULL) { +@@ -1226,8 +1231,10 @@ NTSTATUS check_reduced_name(connection_struct *conn, const char *fname) + } + + rootdir_len = strlen(conn_rootdir); +- if (strncmp(conn_rootdir, resolved_name, +- rootdir_len) != 0) { ++ matched = (strncmp(conn_rootdir, resolved_name, ++ rootdir_len) == 0); ++ if (!matched || (resolved_name[rootdir_len] != '/' && ++ resolved_name[rootdir_len] != '\0')) { + DEBUG(2, (""check_reduced_name: Bad access "" + ""attempt: %s is a symlink outside the "" + ""share path\n"", fname));",713,1044,2048 +7713,"ofputil_encode_flow_stats_request(const struct ofputil_flow_stats_request *fsr, + enum ofputil_protocol protocol) +{ + struct ofpbuf *msg; + enum ofpraw raw; + + switch (protocol) { + case OFPUTIL_P_OF11_STD: + case OFPUTIL_P_OF12_OXM: + case OFPUTIL_P_OF13_OXM: + case OFPUTIL_P_OF14_OXM: + case OFPUTIL_P_OF15_OXM: + case OFPUTIL_P_OF16_OXM: { + struct ofp11_flow_stats_request *ofsr; + + raw = (fsr->aggregate + ? OFPRAW_OFPST11_AGGREGATE_REQUEST + : OFPRAW_OFPST11_FLOW_REQUEST); + msg = ofpraw_alloc(raw, ofputil_protocol_to_ofp_version(protocol), + ofputil_match_typical_len(protocol)); + ofsr = ofpbuf_put_zeros(msg, sizeof *ofsr); + ofsr->table_id = fsr->table_id; + ofsr->out_port = ofputil_port_to_ofp11(fsr->out_port); + ofsr->out_group = htonl(fsr->out_group); + ofsr->cookie = fsr->cookie; + ofsr->cookie_mask = fsr->cookie_mask; + ofputil_put_ofp11_match(msg, &fsr->match, protocol); + break; + } + + case OFPUTIL_P_OF10_STD: + case OFPUTIL_P_OF10_STD_TID: { + struct ofp10_flow_stats_request *ofsr; + + raw = (fsr->aggregate + ? OFPRAW_OFPST10_AGGREGATE_REQUEST + : OFPRAW_OFPST10_FLOW_REQUEST); + msg = ofpraw_alloc(raw, OFP10_VERSION, 0); + ofsr = ofpbuf_put_zeros(msg, sizeof *ofsr); + ofputil_match_to_ofp10_match(&fsr->match, &ofsr->match); + ofsr->table_id = fsr->table_id; + ofsr->out_port = htons(ofp_to_u16(fsr->out_port)); + break; + } + + case OFPUTIL_P_OF10_NXM: + case OFPUTIL_P_OF10_NXM_TID: { + struct nx_flow_stats_request *nfsr; + int match_len; + + raw = (fsr->aggregate + ? OFPRAW_NXST_AGGREGATE_REQUEST + : OFPRAW_NXST_FLOW_REQUEST); + msg = ofpraw_alloc(raw, OFP10_VERSION, NXM_TYPICAL_LEN); + ofpbuf_put_zeros(msg, sizeof *nfsr); + match_len = nx_put_match(msg, &fsr->match, + fsr->cookie, fsr->cookie_mask); + + nfsr = msg->msg; + nfsr->out_port = htons(ofp_to_u16(fsr->out_port)); + nfsr->match_len = htons(match_len); + nfsr->table_id = fsr->table_id; + break; + } + + default: + OVS_NOT_REACHED(); + } + + return msg; +} +",0,"ofputil_encode_flow_stats_request(const struct ofputil_flow_stats_request *fsr, + enum ofputil_protocol protocol) +{ + struct ofpbuf *msg; + enum ofpraw raw; + + switch (protocol) { + case OFPUTIL_P_OF11_STD: + case OFPUTIL_P_OF12_OXM: + case OFPUTIL_P_OF13_OXM: + case OFPUTIL_P_OF14_OXM: + case OFPUTIL_P_OF15_OXM: + case OFPUTIL_P_OF16_OXM: { + struct ofp11_flow_stats_request *ofsr; + + raw = (fsr->aggregate + ? OFPRAW_OFPST11_AGGREGATE_REQUEST + : OFPRAW_OFPST11_FLOW_REQUEST); + msg = ofpraw_alloc(raw, ofputil_protocol_to_ofp_version(protocol), + ofputil_match_typical_len(protocol)); + ofsr = ofpbuf_put_zeros(msg, sizeof *ofsr); + ofsr->table_id = fsr->table_id; + ofsr->out_port = ofputil_port_to_ofp11(fsr->out_port); + ofsr->out_group = htonl(fsr->out_group); + ofsr->cookie = fsr->cookie; + ofsr->cookie_mask = fsr->cookie_mask; + ofputil_put_ofp11_match(msg, &fsr->match, protocol); + break; + } + + case OFPUTIL_P_OF10_STD: + case OFPUTIL_P_OF10_STD_TID: { + struct ofp10_flow_stats_request *ofsr; + + raw = (fsr->aggregate + ? OFPRAW_OFPST10_AGGREGATE_REQUEST + : OFPRAW_OFPST10_FLOW_REQUEST); + msg = ofpraw_alloc(raw, OFP10_VERSION, 0); + ofsr = ofpbuf_put_zeros(msg, sizeof *ofsr); + ofputil_match_to_ofp10_match(&fsr->match, &ofsr->match); + ofsr->table_id = fsr->table_id; + ofsr->out_port = htons(ofp_to_u16(fsr->out_port)); + break; + } + + case OFPUTIL_P_OF10_NXM: + case OFPUTIL_P_OF10_NXM_TID: { + struct nx_flow_stats_request *nfsr; + int match_len; + + raw = (fsr->aggregate + ? OFPRAW_NXST_AGGREGATE_REQUEST + : OFPRAW_NXST_FLOW_REQUEST); + msg = ofpraw_alloc(raw, OFP10_VERSION, NXM_TYPICAL_LEN); + ofpbuf_put_zeros(msg, sizeof *nfsr); + match_len = nx_put_match(msg, &fsr->match, + fsr->cookie, fsr->cookie_mask); + + nfsr = msg->msg; + nfsr->out_port = htons(ofp_to_u16(fsr->out_port)); + nfsr->match_len = htons(match_len); + nfsr->table_id = fsr->table_id; + break; + } + + default: + OVS_NOT_REACHED(); + } + + return msg; +} +","@@ -8941,7 +8941,7 @@ parse_group_prop_ntr_selection_method(struct ofpbuf *payload, + ""only allowed for select groups""); + return OFPERR_OFPBPC_BAD_VALUE; + default: +- OVS_NOT_REACHED(); ++ return OFPERR_OFPGMFC_BAD_TYPE; + } + + switch (group_cmd) { +@@ -8956,7 +8956,7 @@ parse_group_prop_ntr_selection_method(struct ofpbuf *payload, + ""only allowed for add and delete group modifications""); + return OFPERR_OFPBPC_BAD_VALUE; + default: +- OVS_NOT_REACHED(); ++ return OFPERR_OFPGMFC_BAD_COMMAND; + } + + if (payload->size < sizeof *prop) {",700,1031,2048 +6847,"server_response(struct httpd *httpd, struct client *clt) +{ + char path[PATH_MAX]; + char hostname[HOST_NAME_MAX+1]; + struct http_descriptor *desc = clt->clt_descreq; + struct http_descriptor *resp = clt->clt_descresp; + struct server *srv = clt->clt_srv; + struct server_config *srv_conf = &srv->srv_conf; + struct kv *kv, key, *host; + struct str_find sm; + int portval = -1, ret; + char *hostval; + const char *errstr = NULL; + + /* Canonicalize the request path */ + if (desc->http_path == NULL || + url_decode(desc->http_path) == NULL || + canonicalize_path(desc->http_path, path, sizeof(path)) == NULL) + goto fail; + free(desc->http_path); + if ((desc->http_path = strdup(path)) == NULL) + goto fail; + + key.kv_key = ""Host""; + if ((host = kv_find(&desc->http_headers, &key)) != NULL && + host->kv_value == NULL) + host = NULL; + + if (strcmp(desc->http_version, ""HTTP/1.1"") == 0) { + /* Host header is mandatory */ + if (host == NULL) + goto fail; + + /* Is the connection persistent? */ + key.kv_key = ""Connection""; + if ((kv = kv_find(&desc->http_headers, &key)) != NULL && + strcasecmp(""close"", kv->kv_value) == 0) + clt->clt_persist = 0; + else + clt->clt_persist++; + } else { + /* Is the connection persistent? */ + key.kv_key = ""Connection""; + if ((kv = kv_find(&desc->http_headers, &key)) != NULL && + strcasecmp(""keep-alive"", kv->kv_value) == 0) + clt->clt_persist++; + else + clt->clt_persist = 0; + } + + if (clt->clt_persist >= srv_conf->maxrequests) + clt->clt_persist = 0; + + /* + * Do we have a Host header and matching configuration? + * XXX the Host can also appear in the URL path. + */ + if (host != NULL) { + if ((hostval = server_http_parsehost(host->kv_value, + hostname, sizeof(hostname), &portval)) == NULL) + goto fail; + + TAILQ_FOREACH(srv_conf, &srv->srv_hosts, entry) { +#ifdef DEBUG + if ((srv_conf->flags & SRVFLAG_LOCATION) == 0) { + DPRINTF(""%s: virtual host \""%s:%u\"""" + "" host \""%s\"" (\""%s\"")"", + __func__, srv_conf->name, + ntohs(srv_conf->port), host->kv_value, + hostname); + } +#endif + if (srv_conf->flags & SRVFLAG_LOCATION) + continue; + else if (srv_conf->flags & SRVFLAG_SERVER_MATCH) { + str_find(hostname, srv_conf->name, + &sm, 1, &errstr); + ret = errstr == NULL ? 0 : -1; + } else { + ret = fnmatch(srv_conf->name, + hostname, FNM_CASEFOLD); + } + if (ret == 0 && + (portval == -1 || + (portval != -1 && portval == srv_conf->port))) { + /* Replace host configuration */ + clt->clt_srv_conf = srv_conf; + srv_conf = NULL; + break; + } + } + } + + if (srv_conf != NULL) { + /* Use the actual server IP address */ + if (server_http_host(&clt->clt_srv_ss, hostname, + sizeof(hostname)) == NULL) + goto fail; + } else { + /* Host header was valid and found */ + if (strlcpy(hostname, host->kv_value, sizeof(hostname)) >= + sizeof(hostname)) + goto fail; + srv_conf = clt->clt_srv_conf; + } + + if ((desc->http_host = strdup(hostname)) == NULL) + goto fail; + + /* Now fill in the mandatory parts of the response descriptor */ + resp->http_method = desc->http_method; + if ((resp->http_version = strdup(desc->http_version)) == NULL) + goto fail; + + /* Now search for the location */ + srv_conf = server_getlocation(clt, desc->http_path); + + if (srv_conf->flags & SRVFLAG_BLOCK) { + server_abort_http(clt, srv_conf->return_code, + srv_conf->return_uri); + return (-1); + } else if (srv_conf->flags & SRVFLAG_AUTH && + server_http_authenticate(srv_conf, clt) == -1) { + server_abort_http(clt, 401, srv_conf->auth_realm); + return (-1); + } else + return (server_file(httpd, clt)); + fail: + server_abort_http(clt, 400, ""bad request""); + return (-1); +} +",0,"server_response(struct httpd *httpd, struct client *clt) +{ + char path[PATH_MAX]; + char hostname[HOST_NAME_MAX+1]; + struct http_descriptor *desc = clt->clt_descreq; + struct http_descriptor *resp = clt->clt_descresp; + struct server *srv = clt->clt_srv; + struct server_config *srv_conf = &srv->srv_conf; + struct kv *kv, key, *host; + struct str_find sm; + int portval = -1, ret; + char *hostval; + const char *errstr = NULL; + + /* Canonicalize the request path */ + if (desc->http_path == NULL || + url_decode(desc->http_path) == NULL || + canonicalize_path(desc->http_path, path, sizeof(path)) == NULL) + goto fail; + free(desc->http_path); + if ((desc->http_path = strdup(path)) == NULL) + goto fail; + + key.kv_key = ""Host""; + if ((host = kv_find(&desc->http_headers, &key)) != NULL && + host->kv_value == NULL) + host = NULL; + + if (strcmp(desc->http_version, ""HTTP/1.1"") == 0) { + /* Host header is mandatory */ + if (host == NULL) + goto fail; + + /* Is the connection persistent? */ + key.kv_key = ""Connection""; + if ((kv = kv_find(&desc->http_headers, &key)) != NULL && + strcasecmp(""close"", kv->kv_value) == 0) + clt->clt_persist = 0; + else + clt->clt_persist++; + } else { + /* Is the connection persistent? */ + key.kv_key = ""Connection""; + if ((kv = kv_find(&desc->http_headers, &key)) != NULL && + strcasecmp(""keep-alive"", kv->kv_value) == 0) + clt->clt_persist++; + else + clt->clt_persist = 0; + } + + if (clt->clt_persist >= srv_conf->maxrequests) + clt->clt_persist = 0; + + /* + * Do we have a Host header and matching configuration? + * XXX the Host can also appear in the URL path. + */ + if (host != NULL) { + if ((hostval = server_http_parsehost(host->kv_value, + hostname, sizeof(hostname), &portval)) == NULL) + goto fail; + + TAILQ_FOREACH(srv_conf, &srv->srv_hosts, entry) { +#ifdef DEBUG + if ((srv_conf->flags & SRVFLAG_LOCATION) == 0) { + DPRINTF(""%s: virtual host \""%s:%u\"""" + "" host \""%s\"" (\""%s\"")"", + __func__, srv_conf->name, + ntohs(srv_conf->port), host->kv_value, + hostname); + } +#endif + if (srv_conf->flags & SRVFLAG_LOCATION) + continue; + else if (srv_conf->flags & SRVFLAG_SERVER_MATCH) { + str_find(hostname, srv_conf->name, + &sm, 1, &errstr); + ret = errstr == NULL ? 0 : -1; + } else { + ret = fnmatch(srv_conf->name, + hostname, FNM_CASEFOLD); + } + if (ret == 0 && + (portval == -1 || + (portval != -1 && portval == srv_conf->port))) { + /* Replace host configuration */ + clt->clt_srv_conf = srv_conf; + srv_conf = NULL; + break; + } + } + } + + if (srv_conf != NULL) { + /* Use the actual server IP address */ + if (server_http_host(&clt->clt_srv_ss, hostname, + sizeof(hostname)) == NULL) + goto fail; + } else { + /* Host header was valid and found */ + if (strlcpy(hostname, host->kv_value, sizeof(hostname)) >= + sizeof(hostname)) + goto fail; + srv_conf = clt->clt_srv_conf; + } + + if ((desc->http_host = strdup(hostname)) == NULL) + goto fail; + + /* Now fill in the mandatory parts of the response descriptor */ + resp->http_method = desc->http_method; + if ((resp->http_version = strdup(desc->http_version)) == NULL) + goto fail; + + /* Now search for the location */ + srv_conf = server_getlocation(clt, desc->http_path); + + if (srv_conf->flags & SRVFLAG_BLOCK) { + server_abort_http(clt, srv_conf->return_code, + srv_conf->return_uri); + return (-1); + } else if (srv_conf->flags & SRVFLAG_AUTH && + server_http_authenticate(srv_conf, clt) == -1) { + server_abort_http(clt, 401, srv_conf->auth_realm); + return (-1); + } else + return (server_file(httpd, clt)); + fail: + server_abort_http(clt, 400, ""bad request""); + return (-1); +} +","@@ -1,7 +1,7 @@ +-/* $OpenBSD: server_http.c,v 1.111 2017/01/31 12:21:27 reyk Exp $ */ ++/* $OpenBSD: server_http.c,v 1.112 2017/01/31 14:39:47 reyk Exp $ */ + + /* +- * Copyright (c) 2006 - 2015 Reyk Floeter ++ * Copyright (c) 2006 - 2017 Reyk Floeter + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above +@@ -609,6 +609,101 @@ server_read_httpchunks(struct bufferevent *bev, void *arg) + server_close(clt, strerror(errno)); + } + ++void ++server_read_httprange(struct bufferevent *bev, void *arg) ++{ ++ struct client *clt = arg; ++ struct evbuffer *src = EVBUFFER_INPUT(bev); ++ size_t size; ++ struct media_type *media; ++ struct range_data *r = &clt->clt_ranges; ++ struct range *range; ++ ++ getmonotime(&clt->clt_tv_last); ++ ++ if (r->range_toread > 0) { ++ size = EVBUFFER_LENGTH(src); ++ if (!size) ++ return; ++ ++ /* Read chunk data */ ++ if ((off_t)size > r->range_toread) { ++ size = r->range_toread; ++ if (server_bufferevent_write_chunk(clt, src, size) ++ == -1) ++ goto fail; ++ r->range_toread = 0; ++ } else { ++ if (server_bufferevent_write_buffer(clt, src) == -1) ++ goto fail; ++ r->range_toread -= size; ++ } ++ if (r->range_toread < 1) ++ r->range_toread = TOREAD_HTTP_RANGE; ++ DPRINTF(""%s: done, size %lu, to read %lld"", __func__, ++ size, r->range_toread); ++ } ++ ++ switch (r->range_toread) { ++ case TOREAD_HTTP_RANGE: ++ if (r->range_index >= r->range_count) { ++ if (r->range_count > 1) { ++ /* Add end marker */ ++ if (server_bufferevent_printf(clt, ++ ""\r\n--%llu--\r\n"", ++ clt->clt_boundary) == -1) ++ goto fail; ++ } ++ r->range_toread = TOREAD_HTTP_NONE; ++ break; ++ } ++ ++ range = &r->range[r->range_index]; ++ ++ if (r->range_count > 1) { ++ media = r->range_media; ++ if (server_bufferevent_printf(clt, ++ ""\r\n--%llu\r\n"" ++ ""Content-Type: %s/%s\r\n"" ++ ""Content-Range: bytes %lld-%lld/%zu\r\n\r\n"", ++ clt->clt_boundary, ++ media->media_type, media->media_subtype, ++ range->start, range->end, r->range_total) == -1) ++ goto fail; ++ } ++ r->range_toread = range->end - range->start + 1; ++ ++ if (lseek(clt->clt_fd, range->start, SEEK_SET) == -1) ++ goto fail; ++ ++ /* Throw away bytes that are already in the input buffer */ ++ evbuffer_drain(src, EVBUFFER_LENGTH(src)); ++ ++ /* Increment for the next part */ ++ r->range_index++; ++ break; ++ case TOREAD_HTTP_NONE: ++ case 0: ++ break; ++ } ++ ++ if (clt->clt_done) ++ goto done; ++ ++ if (EVBUFFER_LENGTH(EVBUFFER_OUTPUT(clt->clt_bev)) > (size_t) ++ SERVER_MAX_PREFETCH * clt->clt_sndbufsiz) { ++ bufferevent_disable(clt->clt_srvbev, EV_READ); ++ clt->clt_srvbev_throttled = 1; ++ } ++ ++ return; ++ done: ++ (*bev->errorcb)(bev, EVBUFFER_READ, bev->cbarg); ++ return; ++ fail: ++ server_close(clt, strerror(errno)); ++} ++ + void + server_reset_http(struct client *clt) + {",1119,1450,2048 +17942,"static int try_to_unmap_cluster(unsigned long cursor, unsigned int *mapcount, + struct vm_area_struct *vma, struct page *check_page) +{ + struct mm_struct *mm = vma->vm_mm; + pmd_t *pmd; + pte_t *pte; + pte_t pteval; + spinlock_t *ptl; + struct page *page; + unsigned long address; + unsigned long mmun_start; /* For mmu_notifiers */ + unsigned long mmun_end; /* For mmu_notifiers */ + unsigned long end; + int ret = SWAP_AGAIN; + int locked_vma = 0; + + address = (vma->vm_start + cursor) & CLUSTER_MASK; + end = address + CLUSTER_SIZE; + if (address < vma->vm_start) + address = vma->vm_start; + if (end > vma->vm_end) + end = vma->vm_end; + + pmd = mm_find_pmd(mm, address); + if (!pmd) + return ret; + + mmun_start = address; + mmun_end = end; + mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end); + + /* + * If we can acquire the mmap_sem for read, and vma is VM_LOCKED, + * keep the sem while scanning the cluster for mlocking pages. + */ + if (down_read_trylock(&vma->vm_mm->mmap_sem)) { + locked_vma = (vma->vm_flags & VM_LOCKED); + if (!locked_vma) + up_read(&vma->vm_mm->mmap_sem); /* don't need it */ + } + + pte = pte_offset_map_lock(mm, pmd, address, &ptl); + + /* Update high watermark before we lower rss */ + update_hiwater_rss(mm); + + for (; address < end; pte++, address += PAGE_SIZE) { + if (!pte_present(*pte)) + continue; + page = vm_normal_page(vma, address, *pte); + BUG_ON(!page || PageAnon(page)); + + if (locked_vma) { + mlock_vma_page(page); /* no-op if already mlocked */ + if (page == check_page) + ret = SWAP_MLOCK; + continue; /* don't unmap */ + } + + if (ptep_clear_flush_young_notify(vma, address, pte)) + continue; + + /* Nuke the page table entry. */ + flush_cache_page(vma, address, pte_pfn(*pte)); + pteval = ptep_clear_flush(vma, address, pte); + + /* If nonlinear, store the file page offset in the pte. */ + if (page->index != linear_page_index(vma, address)) { + pte_t ptfile = pgoff_to_pte(page->index); + if (pte_soft_dirty(pteval)) + pte_file_mksoft_dirty(ptfile); + set_pte_at(mm, address, pte, ptfile); + } + + /* Move the dirty bit to the physical page now the pte is gone. */ + if (pte_dirty(pteval)) + set_page_dirty(page); + + page_remove_rmap(page); + page_cache_release(page); + dec_mm_counter(mm, MM_FILEPAGES); + (*mapcount)--; + } + pte_unmap_unlock(pte - 1, ptl); + mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); + if (locked_vma) + up_read(&vma->vm_mm->mmap_sem); + return ret; +} +",1,"static int try_to_unmap_cluster(unsigned long cursor, unsigned int *mapcount, + struct vm_area_struct *vma, struct page *check_page) +{ + struct mm_struct *mm = vma->vm_mm; + pmd_t *pmd; + pte_t *pte; + pte_t pteval; + spinlock_t *ptl; + struct page *page; + unsigned long address; + unsigned long mmun_start; /* For mmu_notifiers */ + unsigned long mmun_end; /* For mmu_notifiers */ + unsigned long end; + int ret = SWAP_AGAIN; + int locked_vma = 0; + + address = (vma->vm_start + cursor) & CLUSTER_MASK; + end = address + CLUSTER_SIZE; + if (address < vma->vm_start) + address = vma->vm_start; + if (end > vma->vm_end) + end = vma->vm_end; + + pmd = mm_find_pmd(mm, address); + if (!pmd) + return ret; + + mmun_start = address; + mmun_end = end; + mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end); + + /* + * If we can acquire the mmap_sem for read, and vma is VM_LOCKED, + * keep the sem while scanning the cluster for mlocking pages. + */ + if (down_read_trylock(&vma->vm_mm->mmap_sem)) { + locked_vma = (vma->vm_flags & VM_LOCKED); + if (!locked_vma) + up_read(&vma->vm_mm->mmap_sem); /* don't need it */ + } + + pte = pte_offset_map_lock(mm, pmd, address, &ptl); + + /* Update high watermark before we lower rss */ + update_hiwater_rss(mm); + + for (; address < end; pte++, address += PAGE_SIZE) { + if (!pte_present(*pte)) + continue; + page = vm_normal_page(vma, address, *pte); + BUG_ON(!page || PageAnon(page)); + + if (locked_vma) { + if (page == check_page) { + /* we know we have check_page locked */ + mlock_vma_page(page); + ret = SWAP_MLOCK; + } else if (trylock_page(page)) { + /* + * If we can lock the page, perform mlock. + * Otherwise leave the page alone, it will be + * eventually encountered again later. + */ + mlock_vma_page(page); + unlock_page(page); + } + continue; /* don't unmap */ + } + + if (ptep_clear_flush_young_notify(vma, address, pte)) + continue; + + /* Nuke the page table entry. */ + flush_cache_page(vma, address, pte_pfn(*pte)); + pteval = ptep_clear_flush(vma, address, pte); + + /* If nonlinear, store the file page offset in the pte. */ + if (page->index != linear_page_index(vma, address)) { + pte_t ptfile = pgoff_to_pte(page->index); + if (pte_soft_dirty(pteval)) + pte_file_mksoft_dirty(ptfile); + set_pte_at(mm, address, pte, ptfile); + } + + /* Move the dirty bit to the physical page now the pte is gone. */ + if (pte_dirty(pteval)) + set_page_dirty(page); + + page_remove_rmap(page); + page_cache_release(page); + dec_mm_counter(mm, MM_FILEPAGES); + (*mapcount)--; + } + pte_unmap_unlock(pte - 1, ptl); + mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); + if (locked_vma) + up_read(&vma->vm_mm->mmap_sem); + return ret; +} +","@@ -1332,9 +1332,19 @@ static int try_to_unmap_cluster(unsigned long cursor, unsigned int *mapcount, + BUG_ON(!page || PageAnon(page)); + + if (locked_vma) { +- mlock_vma_page(page); /* no-op if already mlocked */ +- if (page == check_page) ++ if (page == check_page) { ++ /* we know we have check_page locked */ ++ mlock_vma_page(page); + ret = SWAP_MLOCK; ++ } else if (trylock_page(page)) { ++ /* ++ * If we can lock the page, perform mlock. ++ * Otherwise leave the page alone, it will be ++ * eventually encountered again later. ++ */ ++ mlock_vma_page(page); ++ unlock_page(page); ++ } + continue; /* don't unmap */ + } + ",762,1093,2048 +247,"NTSTATUS smb1cli_req_chain_submit(struct tevent_req **reqs, int num_reqs) +{ + struct smbXcli_req_state *first_state = + tevent_req_data(reqs[0], + struct smbXcli_req_state); + struct smbXcli_req_state *state; + size_t wct_offset; + size_t chain_padding = 0; + int i, iovlen; + struct iovec *iov = NULL; + struct iovec *this_iov; + NTSTATUS status; + ssize_t nbt_len; + + if (num_reqs == 1) { + return smb1cli_req_writev_submit(reqs[0], first_state, + first_state->smb1.iov, + first_state->smb1.iov_count); + } + + iovlen = 0; + for (i=0; ismb1.iov_count < 4) { + return NT_STATUS_INVALID_PARAMETER_MIX; + } + + if (i == 0) { + /* + * The NBT and SMB header + */ + iovlen += 2; + } else { + /* + * Chain padding + */ + iovlen += 1; + } + + /* + * words and bytes + */ + iovlen += state->smb1.iov_count - 2; + } + + iov = talloc_zero_array(first_state, struct iovec, iovlen); + if (iov == NULL) { + return NT_STATUS_NO_MEMORY; + } + + first_state->smb1.chained_requests = (struct tevent_req **)talloc_memdup( + first_state, reqs, sizeof(*reqs) * num_reqs); + if (first_state->smb1.chained_requests == NULL) { + TALLOC_FREE(iov); + return NT_STATUS_NO_MEMORY; + } + + wct_offset = HDR_WCT; + this_iov = iov; + + for (i=0; ismb1.hdr, HDR_COM)) + || CVAL(state->smb1.hdr, HDR_WCT) < 2) { + TALLOC_FREE(iov); + TALLOC_FREE(first_state->smb1.chained_requests); + return NT_STATUS_INVALID_PARAMETER_MIX; + } + } + + wct_offset += smbXcli_iov_len(state->smb1.iov+2, + state->smb1.iov_count-2) + 1; + if ((wct_offset % 4) != 0) { + next_padding = 4 - (wct_offset % 4); + } + wct_offset += next_padding; + vwv = state->smb1.vwv; + + if (i < num_reqs-1) { + struct smbXcli_req_state *next_state = + tevent_req_data(reqs[i+1], + struct smbXcli_req_state); + SCVAL(vwv+0, 0, CVAL(next_state->smb1.hdr, HDR_COM)); + SCVAL(vwv+0, 1, 0); + SSVAL(vwv+1, 0, wct_offset); + } else if (smb1cli_is_andx_req(CVAL(state->smb1.hdr, HDR_COM))) { + /* properly end the chain */ + SCVAL(vwv+0, 0, 0xff); + SCVAL(vwv+0, 1, 0xff); + SSVAL(vwv+1, 0, 0); + } + + if (i == 0) { + /* + * The NBT and SMB header + */ + this_iov[0] = state->smb1.iov[0]; + this_iov[1] = state->smb1.iov[1]; + this_iov += 2; + } else { + /* + * This one is a bit subtle. We have to add + * chain_padding bytes between the requests, and we + * have to also include the wct field of the + * subsequent requests. We use the subsequent header + * for the padding, it contains the wct field in its + * last byte. + */ + this_iov[0].iov_len = chain_padding+1; + this_iov[0].iov_base = (void *)&state->smb1.hdr[ + sizeof(state->smb1.hdr) - this_iov[0].iov_len]; + memset(this_iov[0].iov_base, 0, this_iov[0].iov_len-1); + this_iov += 1; + } + + /* + * copy the words and bytes + */ + memcpy(this_iov, state->smb1.iov+2, + sizeof(struct iovec) * (state->smb1.iov_count-2)); + this_iov += state->smb1.iov_count - 2; + chain_padding = next_padding; + } + + nbt_len = iov_buflen(&iov[1], iovlen-1); + if ((nbt_len == -1) || (nbt_len > first_state->conn->smb1.max_xmit)) { + TALLOC_FREE(iov); + TALLOC_FREE(first_state->smb1.chained_requests); + return NT_STATUS_INVALID_PARAMETER_MIX; + } + + status = smb1cli_req_writev_submit(reqs[0], first_state, iov, iovlen); + if (!NT_STATUS_IS_OK(status)) { + TALLOC_FREE(iov); + TALLOC_FREE(first_state->smb1.chained_requests); + return status; + } + + return NT_STATUS_OK; +} +",0,"NTSTATUS smb1cli_req_chain_submit(struct tevent_req **reqs, int num_reqs) +{ + struct smbXcli_req_state *first_state = + tevent_req_data(reqs[0], + struct smbXcli_req_state); + struct smbXcli_req_state *state; + size_t wct_offset; + size_t chain_padding = 0; + int i, iovlen; + struct iovec *iov = NULL; + struct iovec *this_iov; + NTSTATUS status; + ssize_t nbt_len; + + if (num_reqs == 1) { + return smb1cli_req_writev_submit(reqs[0], first_state, + first_state->smb1.iov, + first_state->smb1.iov_count); + } + + iovlen = 0; + for (i=0; ismb1.iov_count < 4) { + return NT_STATUS_INVALID_PARAMETER_MIX; + } + + if (i == 0) { + /* + * The NBT and SMB header + */ + iovlen += 2; + } else { + /* + * Chain padding + */ + iovlen += 1; + } + + /* + * words and bytes + */ + iovlen += state->smb1.iov_count - 2; + } + + iov = talloc_zero_array(first_state, struct iovec, iovlen); + if (iov == NULL) { + return NT_STATUS_NO_MEMORY; + } + + first_state->smb1.chained_requests = (struct tevent_req **)talloc_memdup( + first_state, reqs, sizeof(*reqs) * num_reqs); + if (first_state->smb1.chained_requests == NULL) { + TALLOC_FREE(iov); + return NT_STATUS_NO_MEMORY; + } + + wct_offset = HDR_WCT; + this_iov = iov; + + for (i=0; ismb1.hdr, HDR_COM)) + || CVAL(state->smb1.hdr, HDR_WCT) < 2) { + TALLOC_FREE(iov); + TALLOC_FREE(first_state->smb1.chained_requests); + return NT_STATUS_INVALID_PARAMETER_MIX; + } + } + + wct_offset += smbXcli_iov_len(state->smb1.iov+2, + state->smb1.iov_count-2) + 1; + if ((wct_offset % 4) != 0) { + next_padding = 4 - (wct_offset % 4); + } + wct_offset += next_padding; + vwv = state->smb1.vwv; + + if (i < num_reqs-1) { + struct smbXcli_req_state *next_state = + tevent_req_data(reqs[i+1], + struct smbXcli_req_state); + SCVAL(vwv+0, 0, CVAL(next_state->smb1.hdr, HDR_COM)); + SCVAL(vwv+0, 1, 0); + SSVAL(vwv+1, 0, wct_offset); + } else if (smb1cli_is_andx_req(CVAL(state->smb1.hdr, HDR_COM))) { + /* properly end the chain */ + SCVAL(vwv+0, 0, 0xff); + SCVAL(vwv+0, 1, 0xff); + SSVAL(vwv+1, 0, 0); + } + + if (i == 0) { + /* + * The NBT and SMB header + */ + this_iov[0] = state->smb1.iov[0]; + this_iov[1] = state->smb1.iov[1]; + this_iov += 2; + } else { + /* + * This one is a bit subtle. We have to add + * chain_padding bytes between the requests, and we + * have to also include the wct field of the + * subsequent requests. We use the subsequent header + * for the padding, it contains the wct field in its + * last byte. + */ + this_iov[0].iov_len = chain_padding+1; + this_iov[0].iov_base = (void *)&state->smb1.hdr[ + sizeof(state->smb1.hdr) - this_iov[0].iov_len]; + memset(this_iov[0].iov_base, 0, this_iov[0].iov_len-1); + this_iov += 1; + } + + /* + * copy the words and bytes + */ + memcpy(this_iov, state->smb1.iov+2, + sizeof(struct iovec) * (state->smb1.iov_count-2)); + this_iov += state->smb1.iov_count - 2; + chain_padding = next_padding; + } + + nbt_len = iov_buflen(&iov[1], iovlen-1); + if ((nbt_len == -1) || (nbt_len > first_state->conn->smb1.max_xmit)) { + TALLOC_FREE(iov); + TALLOC_FREE(first_state->smb1.chained_requests); + return NT_STATUS_INVALID_PARAMETER_MIX; + } + + status = smb1cli_req_writev_submit(reqs[0], first_state, iov, iovlen); + if (!NT_STATUS_IS_OK(status)) { + TALLOC_FREE(iov); + TALLOC_FREE(first_state->smb1.chained_requests); + return status; + } + + return NT_STATUS_OK; +} +","@@ -5446,6 +5446,9 @@ uint8_t smb2cli_session_security_mode(struct smbXcli_session *session) + if (conn->mandatory_signing) { + security_mode |= SMB2_NEGOTIATE_SIGNING_REQUIRED; + } ++ if (session->smb2->should_sign) { ++ security_mode |= SMB2_NEGOTIATE_SIGNING_REQUIRED; ++ } + + return security_mode; + } +@@ -5877,6 +5880,14 @@ NTSTATUS smb2cli_session_set_channel_key(struct smbXcli_session *session, + + NTSTATUS smb2cli_session_encryption_on(struct smbXcli_session *session) + { ++ if (!session->smb2->should_sign) { ++ /* ++ * We need required signing on the session ++ * in order to prevent man in the middle attacks. ++ */ ++ return NT_STATUS_INVALID_PARAMETER_MIX; ++ } ++ + if (session->smb2->should_encrypt) { + return NT_STATUS_OK; + }",1331,1662,2048 +4110,"static int netlink_mmap_sendmsg(struct sock *sk, struct msghdr *msg, + u32 dst_portid, u32 dst_group, + struct sock_iocb *siocb) +{ + struct netlink_sock *nlk = nlk_sk(sk); + struct netlink_ring *ring; + struct nl_mmap_hdr *hdr; + struct sk_buff *skb; + unsigned int maxlen; + bool excl = true; + int err = 0, len = 0; + + /* Netlink messages are validated by the receiver before processing. + * In order to avoid userspace changing the contents of the message + * after validation, the socket and the ring may only be used by a + * single process, otherwise we fall back to copying. + */ + if (atomic_long_read(&sk->sk_socket->file->f_count) > 2 || + atomic_read(&nlk->mapped) > 1) + excl = false; + + mutex_lock(&nlk->pg_vec_lock); + + ring = &nlk->tx_ring; + maxlen = ring->frame_size - NL_MMAP_HDRLEN; + + do { + hdr = netlink_current_frame(ring, NL_MMAP_STATUS_VALID); + if (hdr == NULL) { + if (!(msg->msg_flags & MSG_DONTWAIT) && + atomic_read(&nlk->tx_ring.pending)) + schedule(); + continue; + } + if (hdr->nm_len > maxlen) { + err = -EINVAL; + goto out; + } + + netlink_frame_flush_dcache(hdr); + + if (likely(dst_portid == 0 && dst_group == 0 && excl)) { + skb = alloc_skb_head(GFP_KERNEL); + if (skb == NULL) { + err = -ENOBUFS; + goto out; + } + sock_hold(sk); + netlink_ring_setup_skb(skb, sk, ring, hdr); + NETLINK_CB(skb).flags |= NETLINK_SKB_TX; + __skb_put(skb, hdr->nm_len); + netlink_set_status(hdr, NL_MMAP_STATUS_RESERVED); + atomic_inc(&ring->pending); + } else { + skb = alloc_skb(hdr->nm_len, GFP_KERNEL); + if (skb == NULL) { + err = -ENOBUFS; + goto out; + } + __skb_put(skb, hdr->nm_len); + memcpy(skb->data, (void *)hdr + NL_MMAP_HDRLEN, hdr->nm_len); + netlink_set_status(hdr, NL_MMAP_STATUS_UNUSED); + } + + netlink_increment_head(ring); + + NETLINK_CB(skb).portid = nlk->portid; + NETLINK_CB(skb).dst_group = dst_group; + NETLINK_CB(skb).creds = siocb->scm->creds; + + err = security_netlink_send(sk, skb); + if (err) { + kfree_skb(skb); + goto out; + } + + if (unlikely(dst_group)) { + atomic_inc(&skb->users); + netlink_broadcast(sk, skb, dst_portid, dst_group, + GFP_KERNEL); + } + err = netlink_unicast(sk, skb, dst_portid, + msg->msg_flags & MSG_DONTWAIT); + if (err < 0) + goto out; + len += err; + + } while (hdr != NULL || + (!(msg->msg_flags & MSG_DONTWAIT) && + atomic_read(&nlk->tx_ring.pending))); + + if (len > 0) + err = len; +out: + mutex_unlock(&nlk->pg_vec_lock); + return err; +} +",0,"static int netlink_mmap_sendmsg(struct sock *sk, struct msghdr *msg, + u32 dst_portid, u32 dst_group, + struct sock_iocb *siocb) +{ + struct netlink_sock *nlk = nlk_sk(sk); + struct netlink_ring *ring; + struct nl_mmap_hdr *hdr; + struct sk_buff *skb; + unsigned int maxlen; + bool excl = true; + int err = 0, len = 0; + + /* Netlink messages are validated by the receiver before processing. + * In order to avoid userspace changing the contents of the message + * after validation, the socket and the ring may only be used by a + * single process, otherwise we fall back to copying. + */ + if (atomic_long_read(&sk->sk_socket->file->f_count) > 2 || + atomic_read(&nlk->mapped) > 1) + excl = false; + + mutex_lock(&nlk->pg_vec_lock); + + ring = &nlk->tx_ring; + maxlen = ring->frame_size - NL_MMAP_HDRLEN; + + do { + hdr = netlink_current_frame(ring, NL_MMAP_STATUS_VALID); + if (hdr == NULL) { + if (!(msg->msg_flags & MSG_DONTWAIT) && + atomic_read(&nlk->tx_ring.pending)) + schedule(); + continue; + } + if (hdr->nm_len > maxlen) { + err = -EINVAL; + goto out; + } + + netlink_frame_flush_dcache(hdr); + + if (likely(dst_portid == 0 && dst_group == 0 && excl)) { + skb = alloc_skb_head(GFP_KERNEL); + if (skb == NULL) { + err = -ENOBUFS; + goto out; + } + sock_hold(sk); + netlink_ring_setup_skb(skb, sk, ring, hdr); + NETLINK_CB(skb).flags |= NETLINK_SKB_TX; + __skb_put(skb, hdr->nm_len); + netlink_set_status(hdr, NL_MMAP_STATUS_RESERVED); + atomic_inc(&ring->pending); + } else { + skb = alloc_skb(hdr->nm_len, GFP_KERNEL); + if (skb == NULL) { + err = -ENOBUFS; + goto out; + } + __skb_put(skb, hdr->nm_len); + memcpy(skb->data, (void *)hdr + NL_MMAP_HDRLEN, hdr->nm_len); + netlink_set_status(hdr, NL_MMAP_STATUS_UNUSED); + } + + netlink_increment_head(ring); + + NETLINK_CB(skb).portid = nlk->portid; + NETLINK_CB(skb).dst_group = dst_group; + NETLINK_CB(skb).creds = siocb->scm->creds; + + err = security_netlink_send(sk, skb); + if (err) { + kfree_skb(skb); + goto out; + } + + if (unlikely(dst_group)) { + atomic_inc(&skb->users); + netlink_broadcast(sk, skb, dst_portid, dst_group, + GFP_KERNEL); + } + err = netlink_unicast(sk, skb, dst_portid, + msg->msg_flags & MSG_DONTWAIT); + if (err < 0) + goto out; + len += err; + + } while (hdr != NULL || + (!(msg->msg_flags & MSG_DONTWAIT) && + atomic_read(&nlk->tx_ring.pending))); + + if (len > 0) + err = len; +out: + mutex_unlock(&nlk->pg_vec_lock); + return err; +} +","@@ -2335,8 +2335,6 @@ static int netlink_recvmsg(struct kiocb *kiocb, struct socket *sock, + } + #endif + +- msg->msg_namelen = 0; +- + copied = data_skb->len; + if (len < copied) { + msg->msg_flags |= MSG_TRUNC;",770,1101,2048 +4313,"static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id) +{ + int err; + struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL); + int cpu; + + if (!vmx) + return ERR_PTR(-ENOMEM); + + vmx->vpid = allocate_vpid(); + + err = kvm_vcpu_init(&vmx->vcpu, kvm, id); + if (err) + goto free_vcpu; + + vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL); + BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0]) + > PAGE_SIZE); + + err = -ENOMEM; + if (!vmx->guest_msrs) { + goto uninit_vcpu; + } + + vmx->loaded_vmcs = &vmx->vmcs01; + vmx->loaded_vmcs->vmcs = alloc_vmcs(); + if (!vmx->loaded_vmcs->vmcs) + goto free_msrs; + if (!vmm_exclusive) + kvm_cpu_vmxon(__pa(per_cpu(vmxarea, raw_smp_processor_id()))); + loaded_vmcs_init(vmx->loaded_vmcs); + if (!vmm_exclusive) + kvm_cpu_vmxoff(); + + cpu = get_cpu(); + vmx_vcpu_load(&vmx->vcpu, cpu); + vmx->vcpu.cpu = cpu; + err = vmx_vcpu_setup(vmx); + vmx_vcpu_put(&vmx->vcpu); + put_cpu(); + if (err) + goto free_vmcs; + if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) { + err = alloc_apic_access_page(kvm); + if (err) + goto free_vmcs; + } + + if (enable_ept) { + if (!kvm->arch.ept_identity_map_addr) + kvm->arch.ept_identity_map_addr = + VMX_EPT_IDENTITY_PAGETABLE_ADDR; + err = init_rmode_identity_map(kvm); + if (err) + goto free_vmcs; + } + + if (nested) { + nested_vmx_setup_ctls_msrs(vmx); + vmx->nested.vpid02 = allocate_vpid(); + } + + vmx->nested.posted_intr_nv = -1; + vmx->nested.current_vmptr = -1ull; + vmx->nested.current_vmcs12 = NULL; + + /* + * If PML is turned on, failure on enabling PML just results in failure + * of creating the vcpu, therefore we can simplify PML logic (by + * avoiding dealing with cases, such as enabling PML partially on vcpus + * for the guest, etc. + */ + if (enable_pml) { + err = vmx_create_pml_buffer(vmx); + if (err) + goto free_vmcs; + } + + return &vmx->vcpu; + +free_vmcs: + free_vpid(vmx->nested.vpid02); + free_loaded_vmcs(vmx->loaded_vmcs); +free_msrs: + kfree(vmx->guest_msrs); +uninit_vcpu: + kvm_vcpu_uninit(&vmx->vcpu); +free_vcpu: + free_vpid(vmx->vpid); + kmem_cache_free(kvm_vcpu_cache, vmx); + return ERR_PTR(err); +} +",0,"static struct kvm_vcpu *vmx_create_vcpu(struct kvm *kvm, unsigned int id) +{ + int err; + struct vcpu_vmx *vmx = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL); + int cpu; + + if (!vmx) + return ERR_PTR(-ENOMEM); + + vmx->vpid = allocate_vpid(); + + err = kvm_vcpu_init(&vmx->vcpu, kvm, id); + if (err) + goto free_vcpu; + + vmx->guest_msrs = kmalloc(PAGE_SIZE, GFP_KERNEL); + BUILD_BUG_ON(ARRAY_SIZE(vmx_msr_index) * sizeof(vmx->guest_msrs[0]) + > PAGE_SIZE); + + err = -ENOMEM; + if (!vmx->guest_msrs) { + goto uninit_vcpu; + } + + vmx->loaded_vmcs = &vmx->vmcs01; + vmx->loaded_vmcs->vmcs = alloc_vmcs(); + if (!vmx->loaded_vmcs->vmcs) + goto free_msrs; + if (!vmm_exclusive) + kvm_cpu_vmxon(__pa(per_cpu(vmxarea, raw_smp_processor_id()))); + loaded_vmcs_init(vmx->loaded_vmcs); + if (!vmm_exclusive) + kvm_cpu_vmxoff(); + + cpu = get_cpu(); + vmx_vcpu_load(&vmx->vcpu, cpu); + vmx->vcpu.cpu = cpu; + err = vmx_vcpu_setup(vmx); + vmx_vcpu_put(&vmx->vcpu); + put_cpu(); + if (err) + goto free_vmcs; + if (cpu_need_virtualize_apic_accesses(&vmx->vcpu)) { + err = alloc_apic_access_page(kvm); + if (err) + goto free_vmcs; + } + + if (enable_ept) { + if (!kvm->arch.ept_identity_map_addr) + kvm->arch.ept_identity_map_addr = + VMX_EPT_IDENTITY_PAGETABLE_ADDR; + err = init_rmode_identity_map(kvm); + if (err) + goto free_vmcs; + } + + if (nested) { + nested_vmx_setup_ctls_msrs(vmx); + vmx->nested.vpid02 = allocate_vpid(); + } + + vmx->nested.posted_intr_nv = -1; + vmx->nested.current_vmptr = -1ull; + vmx->nested.current_vmcs12 = NULL; + + /* + * If PML is turned on, failure on enabling PML just results in failure + * of creating the vcpu, therefore we can simplify PML logic (by + * avoiding dealing with cases, such as enabling PML partially on vcpus + * for the guest, etc. + */ + if (enable_pml) { + err = vmx_create_pml_buffer(vmx); + if (err) + goto free_vmcs; + } + + return &vmx->vcpu; + +free_vmcs: + free_vpid(vmx->nested.vpid02); + free_loaded_vmcs(vmx->loaded_vmcs); +free_msrs: + kfree(vmx->guest_msrs); +uninit_vcpu: + kvm_vcpu_uninit(&vmx->vcpu); +free_vcpu: + free_vpid(vmx->vpid); + kmem_cache_free(kvm_vcpu_cache, vmx); + return ERR_PTR(err); +} +","@@ -1639,7 +1639,7 @@ static void update_exception_bitmap(struct kvm_vcpu *vcpu) + u32 eb; + + eb = (1u << PF_VECTOR) | (1u << UD_VECTOR) | (1u << MC_VECTOR) | +- (1u << NM_VECTOR) | (1u << DB_VECTOR); ++ (1u << NM_VECTOR) | (1u << DB_VECTOR) | (1u << AC_VECTOR); + if ((vcpu->guest_debug & + (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) == + (KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)) +@@ -5261,6 +5261,9 @@ static int handle_exception(struct kvm_vcpu *vcpu) + return handle_rmode_exception(vcpu, ex_no, error_code); + + switch (ex_no) { ++ case AC_VECTOR: ++ kvm_queue_exception_e(vcpu, AC_VECTOR, error_code); ++ return 1; + case DB_VECTOR: + dr6 = vmcs_readl(EXIT_QUALIFICATION); + if (!(vcpu->guest_debug &",715,1046,2048 +4580,"static noinline int __push_leaf_right(struct btrfs_trans_handle *trans, + struct btrfs_root *root, + struct btrfs_path *path, + int data_size, int empty, + struct extent_buffer *right, + int free_space, u32 left_nritems, + u32 min_slot) +{ + struct extent_buffer *left = path->nodes[0]; + struct extent_buffer *upper = path->nodes[1]; + struct btrfs_map_token token; + struct btrfs_disk_key disk_key; + int slot; + u32 i; + int push_space = 0; + int push_items = 0; + struct btrfs_item *item; + u32 nr; + u32 right_nritems; + u32 data_end; + u32 this_item_size; + + btrfs_init_map_token(&token); + + if (empty) + nr = 0; + else + nr = max_t(u32, 1, min_slot); + + if (path->slots[0] >= left_nritems) + push_space += data_size; + + slot = path->slots[1]; + i = left_nritems - 1; + while (i >= nr) { + item = btrfs_item_nr(i); + + if (!empty && push_items > 0) { + if (path->slots[0] > i) + break; + if (path->slots[0] == i) { + int space = btrfs_leaf_free_space(root, left); + if (space + push_space * 2 > free_space) + break; + } + } + + if (path->slots[0] == i) + push_space += data_size; + + this_item_size = btrfs_item_size(left, item); + if (this_item_size + sizeof(*item) + push_space > free_space) + break; + + push_items++; + push_space += this_item_size + sizeof(*item); + if (i == 0) + break; + i--; + } + + if (push_items == 0) + goto out_unlock; + + WARN_ON(!empty && push_items == left_nritems); + + /* push left to right */ + right_nritems = btrfs_header_nritems(right); + + push_space = btrfs_item_end_nr(left, left_nritems - push_items); + push_space -= leaf_data_end(root, left); + + /* make room in the right data area */ + data_end = leaf_data_end(root, right); + memmove_extent_buffer(right, + btrfs_leaf_data(right) + data_end - push_space, + btrfs_leaf_data(right) + data_end, + BTRFS_LEAF_DATA_SIZE(root) - data_end); + + /* copy from the left data area */ + copy_extent_buffer(right, left, btrfs_leaf_data(right) + + BTRFS_LEAF_DATA_SIZE(root) - push_space, + btrfs_leaf_data(left) + leaf_data_end(root, left), + push_space); + + memmove_extent_buffer(right, btrfs_item_nr_offset(push_items), + btrfs_item_nr_offset(0), + right_nritems * sizeof(struct btrfs_item)); + + /* copy the items from left to right */ + copy_extent_buffer(right, left, btrfs_item_nr_offset(0), + btrfs_item_nr_offset(left_nritems - push_items), + push_items * sizeof(struct btrfs_item)); + + /* update the item pointers */ + right_nritems += push_items; + btrfs_set_header_nritems(right, right_nritems); + push_space = BTRFS_LEAF_DATA_SIZE(root); + for (i = 0; i < right_nritems; i++) { + item = btrfs_item_nr(i); + push_space -= btrfs_token_item_size(right, item, &token); + btrfs_set_token_item_offset(right, item, push_space, &token); + } + + left_nritems -= push_items; + btrfs_set_header_nritems(left, left_nritems); + + if (left_nritems) + btrfs_mark_buffer_dirty(left); + else + clean_tree_block(trans, root, left); + + btrfs_mark_buffer_dirty(right); + + btrfs_item_key(right, &disk_key, 0); + btrfs_set_node_key(upper, &disk_key, slot + 1); + btrfs_mark_buffer_dirty(upper); + + /* then fixup the leaf pointer in the path */ + if (path->slots[0] >= left_nritems) { + path->slots[0] -= left_nritems; + if (btrfs_header_nritems(path->nodes[0]) == 0) + clean_tree_block(trans, root, path->nodes[0]); + btrfs_tree_unlock(path->nodes[0]); + free_extent_buffer(path->nodes[0]); + path->nodes[0] = right; + path->slots[1] += 1; + } else { + btrfs_tree_unlock(right); + free_extent_buffer(right); + } + return 0; + +out_unlock: + btrfs_tree_unlock(right); + free_extent_buffer(right); + return 1; +} +",0,"static noinline int __push_leaf_right(struct btrfs_trans_handle *trans, + struct btrfs_root *root, + struct btrfs_path *path, + int data_size, int empty, + struct extent_buffer *right, + int free_space, u32 left_nritems, + u32 min_slot) +{ + struct extent_buffer *left = path->nodes[0]; + struct extent_buffer *upper = path->nodes[1]; + struct btrfs_map_token token; + struct btrfs_disk_key disk_key; + int slot; + u32 i; + int push_space = 0; + int push_items = 0; + struct btrfs_item *item; + u32 nr; + u32 right_nritems; + u32 data_end; + u32 this_item_size; + + btrfs_init_map_token(&token); + + if (empty) + nr = 0; + else + nr = max_t(u32, 1, min_slot); + + if (path->slots[0] >= left_nritems) + push_space += data_size; + + slot = path->slots[1]; + i = left_nritems - 1; + while (i >= nr) { + item = btrfs_item_nr(i); + + if (!empty && push_items > 0) { + if (path->slots[0] > i) + break; + if (path->slots[0] == i) { + int space = btrfs_leaf_free_space(root, left); + if (space + push_space * 2 > free_space) + break; + } + } + + if (path->slots[0] == i) + push_space += data_size; + + this_item_size = btrfs_item_size(left, item); + if (this_item_size + sizeof(*item) + push_space > free_space) + break; + + push_items++; + push_space += this_item_size + sizeof(*item); + if (i == 0) + break; + i--; + } + + if (push_items == 0) + goto out_unlock; + + WARN_ON(!empty && push_items == left_nritems); + + /* push left to right */ + right_nritems = btrfs_header_nritems(right); + + push_space = btrfs_item_end_nr(left, left_nritems - push_items); + push_space -= leaf_data_end(root, left); + + /* make room in the right data area */ + data_end = leaf_data_end(root, right); + memmove_extent_buffer(right, + btrfs_leaf_data(right) + data_end - push_space, + btrfs_leaf_data(right) + data_end, + BTRFS_LEAF_DATA_SIZE(root) - data_end); + + /* copy from the left data area */ + copy_extent_buffer(right, left, btrfs_leaf_data(right) + + BTRFS_LEAF_DATA_SIZE(root) - push_space, + btrfs_leaf_data(left) + leaf_data_end(root, left), + push_space); + + memmove_extent_buffer(right, btrfs_item_nr_offset(push_items), + btrfs_item_nr_offset(0), + right_nritems * sizeof(struct btrfs_item)); + + /* copy the items from left to right */ + copy_extent_buffer(right, left, btrfs_item_nr_offset(0), + btrfs_item_nr_offset(left_nritems - push_items), + push_items * sizeof(struct btrfs_item)); + + /* update the item pointers */ + right_nritems += push_items; + btrfs_set_header_nritems(right, right_nritems); + push_space = BTRFS_LEAF_DATA_SIZE(root); + for (i = 0; i < right_nritems; i++) { + item = btrfs_item_nr(i); + push_space -= btrfs_token_item_size(right, item, &token); + btrfs_set_token_item_offset(right, item, push_space, &token); + } + + left_nritems -= push_items; + btrfs_set_header_nritems(left, left_nritems); + + if (left_nritems) + btrfs_mark_buffer_dirty(left); + else + clean_tree_block(trans, root, left); + + btrfs_mark_buffer_dirty(right); + + btrfs_item_key(right, &disk_key, 0); + btrfs_set_node_key(upper, &disk_key, slot + 1); + btrfs_mark_buffer_dirty(upper); + + /* then fixup the leaf pointer in the path */ + if (path->slots[0] >= left_nritems) { + path->slots[0] -= left_nritems; + if (btrfs_header_nritems(path->nodes[0]) == 0) + clean_tree_block(trans, root, path->nodes[0]); + btrfs_tree_unlock(path->nodes[0]); + free_extent_buffer(path->nodes[0]); + path->nodes[0] = right; + path->slots[1] += 1; + } else { + btrfs_tree_unlock(right); + free_extent_buffer(right); + } + return 0; + +out_unlock: + btrfs_tree_unlock(right); + free_extent_buffer(right); + return 1; +} +","@@ -2939,7 +2939,7 @@ int btrfs_search_slot(struct btrfs_trans_handle *trans, struct btrfs_root + */ + if (!p->leave_spinning) + btrfs_set_path_blocking(p); +- if (ret < 0) ++ if (ret < 0 && !p->skip_release_on_error) + btrfs_release_path(p); + return ret; + }",1051,1382,2048 +5684,"ext4_swap_extents(handle_t *handle, struct inode *inode1, + struct inode *inode2, ext4_lblk_t lblk1, ext4_lblk_t lblk2, + ext4_lblk_t count, int unwritten, int *erp) +{ + struct ext4_ext_path *path1 = NULL; + struct ext4_ext_path *path2 = NULL; + int replaced_count = 0; + + BUG_ON(!rwsem_is_locked(&EXT4_I(inode1)->i_data_sem)); + BUG_ON(!rwsem_is_locked(&EXT4_I(inode2)->i_data_sem)); + BUG_ON(!mutex_is_locked(&inode1->i_mutex)); + BUG_ON(!mutex_is_locked(&inode2->i_mutex)); + + *erp = ext4_es_remove_extent(inode1, lblk1, count); + if (unlikely(*erp)) + return 0; + *erp = ext4_es_remove_extent(inode2, lblk2, count); + if (unlikely(*erp)) + return 0; + + while (count) { + struct ext4_extent *ex1, *ex2, tmp_ex; + ext4_lblk_t e1_blk, e2_blk; + int e1_len, e2_len, len; + int split = 0; + + path1 = ext4_find_extent(inode1, lblk1, NULL, EXT4_EX_NOCACHE); + if (IS_ERR(path1)) { + *erp = PTR_ERR(path1); + path1 = NULL; + finish: + count = 0; + goto repeat; + } + path2 = ext4_find_extent(inode2, lblk2, NULL, EXT4_EX_NOCACHE); + if (IS_ERR(path2)) { + *erp = PTR_ERR(path2); + path2 = NULL; + goto finish; + } + ex1 = path1[path1->p_depth].p_ext; + ex2 = path2[path2->p_depth].p_ext; + /* Do we have somthing to swap ? */ + if (unlikely(!ex2 || !ex1)) + goto finish; + + e1_blk = le32_to_cpu(ex1->ee_block); + e2_blk = le32_to_cpu(ex2->ee_block); + e1_len = ext4_ext_get_actual_len(ex1); + e2_len = ext4_ext_get_actual_len(ex2); + + /* Hole handling */ + if (!in_range(lblk1, e1_blk, e1_len) || + !in_range(lblk2, e2_blk, e2_len)) { + ext4_lblk_t next1, next2; + + /* if hole after extent, then go to next extent */ + next1 = ext4_ext_next_allocated_block(path1); + next2 = ext4_ext_next_allocated_block(path2); + /* If hole before extent, then shift to that extent */ + if (e1_blk > lblk1) + next1 = e1_blk; + if (e2_blk > lblk2) + next2 = e1_blk; + /* Do we have something to swap */ + if (next1 == EXT_MAX_BLOCKS || next2 == EXT_MAX_BLOCKS) + goto finish; + /* Move to the rightest boundary */ + len = next1 - lblk1; + if (len < next2 - lblk2) + len = next2 - lblk2; + if (len > count) + len = count; + lblk1 += len; + lblk2 += len; + count -= len; + goto repeat; + } + + /* Prepare left boundary */ + if (e1_blk < lblk1) { + split = 1; + *erp = ext4_force_split_extent_at(handle, inode1, + &path1, lblk1, 0); + if (unlikely(*erp)) + goto finish; + } + if (e2_blk < lblk2) { + split = 1; + *erp = ext4_force_split_extent_at(handle, inode2, + &path2, lblk2, 0); + if (unlikely(*erp)) + goto finish; + } + /* ext4_split_extent_at() may result in leaf extent split, + * path must to be revalidated. */ + if (split) + goto repeat; + + /* Prepare right boundary */ + len = count; + if (len > e1_blk + e1_len - lblk1) + len = e1_blk + e1_len - lblk1; + if (len > e2_blk + e2_len - lblk2) + len = e2_blk + e2_len - lblk2; + + if (len != e1_len) { + split = 1; + *erp = ext4_force_split_extent_at(handle, inode1, + &path1, lblk1 + len, 0); + if (unlikely(*erp)) + goto finish; + } + if (len != e2_len) { + split = 1; + *erp = ext4_force_split_extent_at(handle, inode2, + &path2, lblk2 + len, 0); + if (*erp) + goto finish; + } + /* ext4_split_extent_at() may result in leaf extent split, + * path must to be revalidated. */ + if (split) + goto repeat; + + BUG_ON(e2_len != e1_len); + *erp = ext4_ext_get_access(handle, inode1, path1 + path1->p_depth); + if (unlikely(*erp)) + goto finish; + *erp = ext4_ext_get_access(handle, inode2, path2 + path2->p_depth); + if (unlikely(*erp)) + goto finish; + + /* Both extents are fully inside boundaries. Swap it now */ + tmp_ex = *ex1; + ext4_ext_store_pblock(ex1, ext4_ext_pblock(ex2)); + ext4_ext_store_pblock(ex2, ext4_ext_pblock(&tmp_ex)); + ex1->ee_len = cpu_to_le16(e2_len); + ex2->ee_len = cpu_to_le16(e1_len); + if (unwritten) + ext4_ext_mark_unwritten(ex2); + if (ext4_ext_is_unwritten(&tmp_ex)) + ext4_ext_mark_unwritten(ex1); + + ext4_ext_try_to_merge(handle, inode2, path2, ex2); + ext4_ext_try_to_merge(handle, inode1, path1, ex1); + *erp = ext4_ext_dirty(handle, inode2, path2 + + path2->p_depth); + if (unlikely(*erp)) + goto finish; + *erp = ext4_ext_dirty(handle, inode1, path1 + + path1->p_depth); + /* + * Looks scarry ah..? second inode already points to new blocks, + * and it was successfully dirtied. But luckily error may happen + * only due to journal error, so full transaction will be + * aborted anyway. + */ + if (unlikely(*erp)) + goto finish; + lblk1 += len; + lblk2 += len; + replaced_count += len; + count -= len; + + repeat: + ext4_ext_drop_refs(path1); + kfree(path1); + ext4_ext_drop_refs(path2); + kfree(path2); + path1 = path2 = NULL; + } + return replaced_count; +} +",0,"ext4_swap_extents(handle_t *handle, struct inode *inode1, + struct inode *inode2, ext4_lblk_t lblk1, ext4_lblk_t lblk2, + ext4_lblk_t count, int unwritten, int *erp) +{ + struct ext4_ext_path *path1 = NULL; + struct ext4_ext_path *path2 = NULL; + int replaced_count = 0; + + BUG_ON(!rwsem_is_locked(&EXT4_I(inode1)->i_data_sem)); + BUG_ON(!rwsem_is_locked(&EXT4_I(inode2)->i_data_sem)); + BUG_ON(!mutex_is_locked(&inode1->i_mutex)); + BUG_ON(!mutex_is_locked(&inode2->i_mutex)); + + *erp = ext4_es_remove_extent(inode1, lblk1, count); + if (unlikely(*erp)) + return 0; + *erp = ext4_es_remove_extent(inode2, lblk2, count); + if (unlikely(*erp)) + return 0; + + while (count) { + struct ext4_extent *ex1, *ex2, tmp_ex; + ext4_lblk_t e1_blk, e2_blk; + int e1_len, e2_len, len; + int split = 0; + + path1 = ext4_find_extent(inode1, lblk1, NULL, EXT4_EX_NOCACHE); + if (IS_ERR(path1)) { + *erp = PTR_ERR(path1); + path1 = NULL; + finish: + count = 0; + goto repeat; + } + path2 = ext4_find_extent(inode2, lblk2, NULL, EXT4_EX_NOCACHE); + if (IS_ERR(path2)) { + *erp = PTR_ERR(path2); + path2 = NULL; + goto finish; + } + ex1 = path1[path1->p_depth].p_ext; + ex2 = path2[path2->p_depth].p_ext; + /* Do we have somthing to swap ? */ + if (unlikely(!ex2 || !ex1)) + goto finish; + + e1_blk = le32_to_cpu(ex1->ee_block); + e2_blk = le32_to_cpu(ex2->ee_block); + e1_len = ext4_ext_get_actual_len(ex1); + e2_len = ext4_ext_get_actual_len(ex2); + + /* Hole handling */ + if (!in_range(lblk1, e1_blk, e1_len) || + !in_range(lblk2, e2_blk, e2_len)) { + ext4_lblk_t next1, next2; + + /* if hole after extent, then go to next extent */ + next1 = ext4_ext_next_allocated_block(path1); + next2 = ext4_ext_next_allocated_block(path2); + /* If hole before extent, then shift to that extent */ + if (e1_blk > lblk1) + next1 = e1_blk; + if (e2_blk > lblk2) + next2 = e1_blk; + /* Do we have something to swap */ + if (next1 == EXT_MAX_BLOCKS || next2 == EXT_MAX_BLOCKS) + goto finish; + /* Move to the rightest boundary */ + len = next1 - lblk1; + if (len < next2 - lblk2) + len = next2 - lblk2; + if (len > count) + len = count; + lblk1 += len; + lblk2 += len; + count -= len; + goto repeat; + } + + /* Prepare left boundary */ + if (e1_blk < lblk1) { + split = 1; + *erp = ext4_force_split_extent_at(handle, inode1, + &path1, lblk1, 0); + if (unlikely(*erp)) + goto finish; + } + if (e2_blk < lblk2) { + split = 1; + *erp = ext4_force_split_extent_at(handle, inode2, + &path2, lblk2, 0); + if (unlikely(*erp)) + goto finish; + } + /* ext4_split_extent_at() may result in leaf extent split, + * path must to be revalidated. */ + if (split) + goto repeat; + + /* Prepare right boundary */ + len = count; + if (len > e1_blk + e1_len - lblk1) + len = e1_blk + e1_len - lblk1; + if (len > e2_blk + e2_len - lblk2) + len = e2_blk + e2_len - lblk2; + + if (len != e1_len) { + split = 1; + *erp = ext4_force_split_extent_at(handle, inode1, + &path1, lblk1 + len, 0); + if (unlikely(*erp)) + goto finish; + } + if (len != e2_len) { + split = 1; + *erp = ext4_force_split_extent_at(handle, inode2, + &path2, lblk2 + len, 0); + if (*erp) + goto finish; + } + /* ext4_split_extent_at() may result in leaf extent split, + * path must to be revalidated. */ + if (split) + goto repeat; + + BUG_ON(e2_len != e1_len); + *erp = ext4_ext_get_access(handle, inode1, path1 + path1->p_depth); + if (unlikely(*erp)) + goto finish; + *erp = ext4_ext_get_access(handle, inode2, path2 + path2->p_depth); + if (unlikely(*erp)) + goto finish; + + /* Both extents are fully inside boundaries. Swap it now */ + tmp_ex = *ex1; + ext4_ext_store_pblock(ex1, ext4_ext_pblock(ex2)); + ext4_ext_store_pblock(ex2, ext4_ext_pblock(&tmp_ex)); + ex1->ee_len = cpu_to_le16(e2_len); + ex2->ee_len = cpu_to_le16(e1_len); + if (unwritten) + ext4_ext_mark_unwritten(ex2); + if (ext4_ext_is_unwritten(&tmp_ex)) + ext4_ext_mark_unwritten(ex1); + + ext4_ext_try_to_merge(handle, inode2, path2, ex2); + ext4_ext_try_to_merge(handle, inode1, path1, ex1); + *erp = ext4_ext_dirty(handle, inode2, path2 + + path2->p_depth); + if (unlikely(*erp)) + goto finish; + *erp = ext4_ext_dirty(handle, inode1, path1 + + path1->p_depth); + /* + * Looks scarry ah..? second inode already points to new blocks, + * and it was successfully dirtied. But luckily error may happen + * only due to journal error, so full transaction will be + * aborted anyway. + */ + if (unlikely(*erp)) + goto finish; + lblk1 += len; + lblk2 += len; + replaced_count += len; + count -= len; + + repeat: + ext4_ext_drop_refs(path1); + kfree(path1); + ext4_ext_drop_refs(path2); + kfree(path2); + path1 = path2 = NULL; + } + return replaced_count; +} +","@@ -4770,7 +4770,6 @@ static long ext4_zero_range(struct file *file, loff_t offset, + int partial_begin, partial_end; + loff_t start, end; + ext4_lblk_t lblk; +- struct address_space *mapping = inode->i_mapping; + unsigned int blkbits = inode->i_blkbits; + + trace_ext4_zero_range(inode, offset, len, mode); +@@ -4785,17 +4784,6 @@ static long ext4_zero_range(struct file *file, loff_t offset, + return ret; + } + +- /* +- * Write out all dirty pages to avoid race conditions +- * Then release them. +- */ +- if (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) { +- ret = filemap_write_and_wait_range(mapping, offset, +- offset + len - 1); +- if (ret) +- return ret; +- } +- + /* + * Round up offset. This is not fallocate, we neet to zero out + * blocks, so convert interior block aligned part of the range to +@@ -4856,16 +4844,22 @@ static long ext4_zero_range(struct file *file, loff_t offset, + flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN | + EXT4_EX_NOCACHE); + +- /* Now release the pages and zero block aligned part of pages*/ +- truncate_pagecache_range(inode, start, end - 1); +- inode->i_mtime = inode->i_ctime = ext4_current_time(inode); +- + /* Wait all existing dio workers, newcomers will block on i_mutex */ + ext4_inode_block_unlocked_dio(inode); + inode_dio_wait(inode); + ++ /* ++ * Prevent page faults from reinstantiating pages we have ++ * released from page cache. ++ */ ++ down_write(&EXT4_I(inode)->i_mmap_sem); ++ /* Now release the pages and zero block aligned part of pages */ ++ truncate_pagecache_range(inode, start, end - 1); ++ inode->i_mtime = inode->i_ctime = ext4_current_time(inode); ++ + ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size, + flags, mode); ++ up_write(&EXT4_I(inode)->i_mmap_sem); + if (ret) + goto out_dio; + } +@@ -5524,17 +5518,22 @@ int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len) + goto out_mutex; + } + +- truncate_pagecache(inode, ioffset); +- + /* Wait for existing dio to complete */ + ext4_inode_block_unlocked_dio(inode); + inode_dio_wait(inode); + ++ /* ++ * Prevent page faults from reinstantiating pages we have released from ++ * page cache. ++ */ ++ down_write(&EXT4_I(inode)->i_mmap_sem); ++ truncate_pagecache(inode, ioffset); ++ + credits = ext4_writepage_trans_blocks(inode); + handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits); + if (IS_ERR(handle)) { + ret = PTR_ERR(handle); +- goto out_dio; ++ goto out_mmap; + } + + down_write(&EXT4_I(inode)->i_data_sem); +@@ -5573,7 +5572,8 @@ int ext4_collapse_range(struct inode *inode, loff_t offset, loff_t len) + + out_stop: + ext4_journal_stop(handle); +-out_dio: ++out_mmap: ++ up_write(&EXT4_I(inode)->i_mmap_sem); + ext4_inode_resume_unlocked_dio(inode); + out_mutex: + mutex_unlock(&inode->i_mutex); +@@ -5660,17 +5660,22 @@ int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len) + goto out_mutex; + } + +- truncate_pagecache(inode, ioffset); +- + /* Wait for existing dio to complete */ + ext4_inode_block_unlocked_dio(inode); + inode_dio_wait(inode); + ++ /* ++ * Prevent page faults from reinstantiating pages we have released from ++ * page cache. ++ */ ++ down_write(&EXT4_I(inode)->i_mmap_sem); ++ truncate_pagecache(inode, ioffset); ++ + credits = ext4_writepage_trans_blocks(inode); + handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits); + if (IS_ERR(handle)) { + ret = PTR_ERR(handle); +- goto out_dio; ++ goto out_mmap; + } + + /* Expand file to avoid data loss if there is error while shifting */ +@@ -5741,7 +5746,8 @@ int ext4_insert_range(struct inode *inode, loff_t offset, loff_t len) + + out_stop: + ext4_journal_stop(handle); +-out_dio: ++out_mmap: ++ up_write(&EXT4_I(inode)->i_mmap_sem); + ext4_inode_resume_unlocked_dio(inode); + out_mutex: + mutex_unlock(&inode->i_mutex);",1608,1939,2048 +794,"static void cirrus_vga_write_sr(CirrusVGAState * s, uint32_t val) +{ + switch (s->vga.sr_index) { + case 0x00: // Standard VGA + case 0x01: // Standard VGA + case 0x02: // Standard VGA + case 0x03: // Standard VGA + case 0x04: // Standard VGA + s->vga.sr[s->vga.sr_index] = val & sr_mask[s->vga.sr_index]; + if (s->vga.sr_index == 1) + s->vga.update_retrace_info(&s->vga); + break; + case 0x06: // Unlock Cirrus extensions + val &= 0x17; + if (val == 0x12) { + s->vga.sr[s->vga.sr_index] = 0x12; + } else { + s->vga.sr[s->vga.sr_index] = 0x0f; + } + break; + case 0x10: + case 0x30: + case 0x50: + case 0x70: // Graphics Cursor X + case 0x90: + case 0xb0: + case 0xd0: + case 0xf0: // Graphics Cursor X + s->vga.sr[0x10] = val; + s->hw_cursor_x = (val << 3) | (s->vga.sr_index >> 5); + break; + case 0x11: + case 0x31: + case 0x51: + case 0x71: // Graphics Cursor Y + case 0x91: + case 0xb1: + case 0xd1: + case 0xf1: // Graphics Cursor Y + s->vga.sr[0x11] = val; + s->hw_cursor_y = (val << 3) | (s->vga.sr_index >> 5); + break; + case 0x07: // Extended Sequencer Mode + cirrus_update_memory_access(s); + case 0x08: // EEPROM Control + case 0x09: // Scratch Register 0 + case 0x0a: // Scratch Register 1 + case 0x0b: // VCLK 0 + case 0x0c: // VCLK 1 + case 0x0d: // VCLK 2 + case 0x0e: // VCLK 3 + case 0x0f: // DRAM Control + case 0x12: // Graphics Cursor Attribute + case 0x13: // Graphics Cursor Pattern Address + case 0x14: // Scratch Register 2 + case 0x15: // Scratch Register 3 + case 0x16: // Performance Tuning Register + case 0x18: // Signature Generator Control + case 0x19: // Signature Generator Result + case 0x1a: // Signature Generator Result + case 0x1b: // VCLK 0 Denominator & Post + case 0x1c: // VCLK 1 Denominator & Post + case 0x1d: // VCLK 2 Denominator & Post + case 0x1e: // VCLK 3 Denominator & Post + case 0x1f: // BIOS Write Enable and MCLK select + s->vga.sr[s->vga.sr_index] = val; +#ifdef DEBUG_CIRRUS + printf(""cirrus: handled outport sr_index %02x, sr_value %02x\n"", + s->vga.sr_index, val); +#endif + break; + case 0x17: // Configuration Readback and Extended Control + s->vga.sr[s->vga.sr_index] = (s->vga.sr[s->vga.sr_index] & 0x38) + | (val & 0xc7); + cirrus_update_memory_access(s); + break; + default: +#ifdef DEBUG_CIRRUS + printf(""cirrus: outport sr_index %02x, sr_value %02x\n"", + s->vga.sr_index, val); +#endif + break; + } +} +",0,"static void cirrus_vga_write_sr(CirrusVGAState * s, uint32_t val) +{ + switch (s->vga.sr_index) { + case 0x00: // Standard VGA + case 0x01: // Standard VGA + case 0x02: // Standard VGA + case 0x03: // Standard VGA + case 0x04: // Standard VGA + s->vga.sr[s->vga.sr_index] = val & sr_mask[s->vga.sr_index]; + if (s->vga.sr_index == 1) + s->vga.update_retrace_info(&s->vga); + break; + case 0x06: // Unlock Cirrus extensions + val &= 0x17; + if (val == 0x12) { + s->vga.sr[s->vga.sr_index] = 0x12; + } else { + s->vga.sr[s->vga.sr_index] = 0x0f; + } + break; + case 0x10: + case 0x30: + case 0x50: + case 0x70: // Graphics Cursor X + case 0x90: + case 0xb0: + case 0xd0: + case 0xf0: // Graphics Cursor X + s->vga.sr[0x10] = val; + s->hw_cursor_x = (val << 3) | (s->vga.sr_index >> 5); + break; + case 0x11: + case 0x31: + case 0x51: + case 0x71: // Graphics Cursor Y + case 0x91: + case 0xb1: + case 0xd1: + case 0xf1: // Graphics Cursor Y + s->vga.sr[0x11] = val; + s->hw_cursor_y = (val << 3) | (s->vga.sr_index >> 5); + break; + case 0x07: // Extended Sequencer Mode + cirrus_update_memory_access(s); + case 0x08: // EEPROM Control + case 0x09: // Scratch Register 0 + case 0x0a: // Scratch Register 1 + case 0x0b: // VCLK 0 + case 0x0c: // VCLK 1 + case 0x0d: // VCLK 2 + case 0x0e: // VCLK 3 + case 0x0f: // DRAM Control + case 0x12: // Graphics Cursor Attribute + case 0x13: // Graphics Cursor Pattern Address + case 0x14: // Scratch Register 2 + case 0x15: // Scratch Register 3 + case 0x16: // Performance Tuning Register + case 0x18: // Signature Generator Control + case 0x19: // Signature Generator Result + case 0x1a: // Signature Generator Result + case 0x1b: // VCLK 0 Denominator & Post + case 0x1c: // VCLK 1 Denominator & Post + case 0x1d: // VCLK 2 Denominator & Post + case 0x1e: // VCLK 3 Denominator & Post + case 0x1f: // BIOS Write Enable and MCLK select + s->vga.sr[s->vga.sr_index] = val; +#ifdef DEBUG_CIRRUS + printf(""cirrus: handled outport sr_index %02x, sr_value %02x\n"", + s->vga.sr_index, val); +#endif + break; + case 0x17: // Configuration Readback and Extended Control + s->vga.sr[s->vga.sr_index] = (s->vga.sr[s->vga.sr_index] & 0x38) + | (val & 0xc7); + cirrus_update_memory_access(s); + break; + default: +#ifdef DEBUG_CIRRUS + printf(""cirrus: outport sr_index %02x, sr_value %02x\n"", + s->vga.sr_index, val); +#endif + break; + } +} +","@@ -293,6 +293,10 @@ static bool blit_is_unsafe(struct CirrusVGAState *s) + assert(s->cirrus_blt_width > 0); + assert(s->cirrus_blt_height > 0); + ++ if (s->cirrus_blt_width > CIRRUS_BLTBUFSIZE) { ++ return true; ++ } ++ + if (blit_region_is_unsafe(s, s->cirrus_blt_dstpitch, + s->cirrus_blt_dstaddr & s->cirrus_addr_mask)) { + return true;",1044,1375,2048 +7477,"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; + } +} +",0,"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; + } +} +","@@ -3,9 +3,9 @@ + // + // Original version written by Sean Barrett in 2007. + // +-// Originally sponsored by RAD Game Tools. Seeking sponsored +-// by Phillip Bennefall, Marc Andersen, Aaron Baker, Elias Software, +-// Aras Pranckevicius, and Sean Barrett. ++// Originally sponsored by RAD Game Tools. Seeking implementation ++// sponsored by Phillip Bennefall, Marc Andersen, Aaron Baker, ++// Elias Software, Aras Pranckevicius, and Sean Barrett. + // + // LICENSE + // +@@ -32,6 +32,7 @@ + // 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 +@@ -2042,14 +2043,19 @@ static int residue_decode(vorb *f, Codebook *book, float *target, int offset, in + 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; +- int n_read = r->end - r->begin; ++ 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 +@@ -4077,7 +4083,10 @@ static int start_decoder(vorb *f) + int i,max_part_read=0; + for (i=0; i < f->residue_count; ++i) { + Residue *r = f->residue_config + i; +- int n_read = r->end - r->begin; ++ 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; +@@ -4088,6 +4097,8 @@ static int start_decoder(vorb *f) + 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; +@@ -5351,6 +5362,8 @@ int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, in + #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;",705,1036,2048 +16394,"xmlBufResize(xmlBufPtr buf, size_t size) +{ + unsigned int newSize; + xmlChar* rebuf = NULL; + size_t start_buf; + + if ((buf == NULL) || (buf->error)) + return(0); + CHECK_COMPAT(buf) + + if (buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) return(0); + if (buf->alloc == XML_BUFFER_ALLOC_BOUNDED) { + /* + * Used to provide parsing limits + */ + if (size >= XML_MAX_TEXT_LENGTH) { + xmlBufMemoryError(buf, ""buffer error: text too long\n""); + return(0); + } + } + + /* Don't resize if we don't have to */ + if (size < buf->size) + return 1; + + /* figure out new size */ + switch (buf->alloc){ + case XML_BUFFER_ALLOC_IO: + case XML_BUFFER_ALLOC_DOUBLEIT: + /*take care of empty case*/ + newSize = (buf->size ? buf->size*2 : size + 10); + while (size > newSize) { + if (newSize > UINT_MAX / 2) { + xmlBufMemoryError(buf, ""growing buffer""); + return 0; + } + newSize *= 2; + } + break; + case XML_BUFFER_ALLOC_EXACT: + newSize = size+10; + break; + case XML_BUFFER_ALLOC_HYBRID: + if (buf->use < BASE_BUFFER_SIZE) + newSize = size; + else { + newSize = buf->size * 2; + while (size > newSize) { + if (newSize > UINT_MAX / 2) { + xmlBufMemoryError(buf, ""growing buffer""); + return 0; + } + newSize *= 2; + } + } + break; + + default: + newSize = size+10; + break; + } + + if ((buf->alloc == XML_BUFFER_ALLOC_IO) && (buf->contentIO != NULL)) { + start_buf = buf->content - buf->contentIO; + + if (start_buf > newSize) { + /* move data back to start */ + memmove(buf->contentIO, buf->content, buf->use); + buf->content = buf->contentIO; + buf->content[buf->use] = 0; + buf->size += start_buf; + } else { + rebuf = (xmlChar *) xmlRealloc(buf->contentIO, start_buf + newSize); + if (rebuf == NULL) { + xmlBufMemoryError(buf, ""growing buffer""); + return 0; + } + buf->contentIO = rebuf; + buf->content = rebuf + start_buf; + } + } else { + if (buf->content == NULL) { + rebuf = (xmlChar *) xmlMallocAtomic(newSize); + } else if (buf->size - buf->use < 100) { + rebuf = (xmlChar *) xmlRealloc(buf->content, newSize); + } else { + /* + * if we are reallocating a buffer far from being full, it's + * better to make a new allocation and copy only the used range + * and free the old one. + */ + rebuf = (xmlChar *) xmlMallocAtomic(newSize); + if (rebuf != NULL) { + memcpy(rebuf, buf->content, buf->use); + xmlFree(buf->content); + rebuf[buf->use] = 0; + } + } + if (rebuf == NULL) { + xmlBufMemoryError(buf, ""growing buffer""); + return 0; + } + buf->content = rebuf; + } + buf->size = newSize; + UPDATE_COMPAT(buf) + + return 1; +} +",0,"xmlBufResize(xmlBufPtr buf, size_t size) +{ + unsigned int newSize; + xmlChar* rebuf = NULL; + size_t start_buf; + + if ((buf == NULL) || (buf->error)) + return(0); + CHECK_COMPAT(buf) + + if (buf->alloc == XML_BUFFER_ALLOC_IMMUTABLE) return(0); + if (buf->alloc == XML_BUFFER_ALLOC_BOUNDED) { + /* + * Used to provide parsing limits + */ + if (size >= XML_MAX_TEXT_LENGTH) { + xmlBufMemoryError(buf, ""buffer error: text too long\n""); + return(0); + } + } + + /* Don't resize if we don't have to */ + if (size < buf->size) + return 1; + + /* figure out new size */ + switch (buf->alloc){ + case XML_BUFFER_ALLOC_IO: + case XML_BUFFER_ALLOC_DOUBLEIT: + /*take care of empty case*/ + newSize = (buf->size ? buf->size*2 : size + 10); + while (size > newSize) { + if (newSize > UINT_MAX / 2) { + xmlBufMemoryError(buf, ""growing buffer""); + return 0; + } + newSize *= 2; + } + break; + case XML_BUFFER_ALLOC_EXACT: + newSize = size+10; + break; + case XML_BUFFER_ALLOC_HYBRID: + if (buf->use < BASE_BUFFER_SIZE) + newSize = size; + else { + newSize = buf->size * 2; + while (size > newSize) { + if (newSize > UINT_MAX / 2) { + xmlBufMemoryError(buf, ""growing buffer""); + return 0; + } + newSize *= 2; + } + } + break; + + default: + newSize = size+10; + break; + } + + if ((buf->alloc == XML_BUFFER_ALLOC_IO) && (buf->contentIO != NULL)) { + start_buf = buf->content - buf->contentIO; + + if (start_buf > newSize) { + /* move data back to start */ + memmove(buf->contentIO, buf->content, buf->use); + buf->content = buf->contentIO; + buf->content[buf->use] = 0; + buf->size += start_buf; + } else { + rebuf = (xmlChar *) xmlRealloc(buf->contentIO, start_buf + newSize); + if (rebuf == NULL) { + xmlBufMemoryError(buf, ""growing buffer""); + return 0; + } + buf->contentIO = rebuf; + buf->content = rebuf + start_buf; + } + } else { + if (buf->content == NULL) { + rebuf = (xmlChar *) xmlMallocAtomic(newSize); + } else if (buf->size - buf->use < 100) { + rebuf = (xmlChar *) xmlRealloc(buf->content, newSize); + } else { + /* + * if we are reallocating a buffer far from being full, it's + * better to make a new allocation and copy only the used range + * and free the old one. + */ + rebuf = (xmlChar *) xmlMallocAtomic(newSize); + if (rebuf != NULL) { + memcpy(rebuf, buf->content, buf->use); + xmlFree(buf->content); + rebuf[buf->use] = 0; + } + } + if (rebuf == NULL) { + xmlBufMemoryError(buf, ""growing buffer""); + return 0; + } + buf->content = rebuf; + } + buf->size = newSize; + UPDATE_COMPAT(buf) + + return 1; +} +","@@ -231,7 +231,7 @@ xmlBufPtr + xmlBufCreateStatic(void *mem, size_t size) { + xmlBufPtr ret; + +- if ((mem == NULL) || (size == 0)) ++ if (mem == NULL) + return(NULL); + + ret = (xmlBufPtr) xmlMalloc(sizeof(xmlBuf));",793,1124,2048 +17551,"WORD32 ih264d_get_buf_info(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op) +{ + + dec_struct_t * ps_dec; + UWORD8 i = 0; // Default for 420P format + UWORD16 pic_wd, pic_ht; + ivd_ctl_getbufinfo_op_t *ps_ctl_op = + (ivd_ctl_getbufinfo_op_t*)pv_api_op; + UNUSED(pv_api_ip); + ps_ctl_op->u4_error_code = 0; + + ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle); + + ps_ctl_op->u4_min_num_in_bufs = MIN_IN_BUFS; + if(ps_dec->u1_chroma_format == IV_YUV_420P) + ps_ctl_op->u4_min_num_out_bufs = MIN_OUT_BUFS_420; + else if(ps_dec->u1_chroma_format == IV_YUV_422ILE) + ps_ctl_op->u4_min_num_out_bufs = MIN_OUT_BUFS_422ILE; + else if(ps_dec->u1_chroma_format == IV_RGB_565) + ps_ctl_op->u4_min_num_out_bufs = MIN_OUT_BUFS_RGB565; + else if((ps_dec->u1_chroma_format == IV_YUV_420SP_UV) + || (ps_dec->u1_chroma_format == IV_YUV_420SP_VU)) + ps_ctl_op->u4_min_num_out_bufs = MIN_OUT_BUFS_420SP; + + else + { + return IV_FAIL; + } + + ps_ctl_op->u4_num_disp_bufs = 1; + + for(i = 0; i < ps_ctl_op->u4_min_num_in_bufs; i++) + { + ps_ctl_op->u4_min_in_buf_size[i] = MIN_IN_BUF_SIZE; + } + + pic_wd = ps_dec->u4_width_at_init; + pic_ht = ps_dec->u4_height_at_init; + + if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) + { + + if(0 == ps_dec->u4_share_disp_buf) + { + pic_wd = ps_dec->u2_disp_width; + pic_ht = ps_dec->u2_disp_height; + + } + else + { + pic_wd = ps_dec->u2_frm_wd_y; + pic_ht = ps_dec->u2_frm_ht_y; + } + + } + else + { + if(1 == ps_dec->u4_share_disp_buf) + { + pic_wd += (PAD_LEN_Y_H << 1); + pic_ht += (PAD_LEN_Y_V << 2); + + } + } + + if((WORD32)ps_dec->u4_app_disp_width > pic_wd) + pic_wd = ps_dec->u4_app_disp_width; + + if(0 == ps_dec->u4_share_disp_buf) + ps_ctl_op->u4_num_disp_bufs = 1; + else + { + if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) + { + UWORD32 level, width_mbs, height_mbs; + + level = ps_dec->u4_level_at_init; + width_mbs = ps_dec->u2_frm_wd_in_mbs; + height_mbs = ps_dec->u2_frm_ht_in_mbs; + + if((ps_dec->ps_cur_sps->u1_vui_parameters_present_flag == 1) + && (ps_dec->ps_cur_sps->s_vui.u4_num_reorder_frames + != 64)) + { + ps_ctl_op->u4_num_disp_bufs = + ps_dec->ps_cur_sps->s_vui.u4_num_reorder_frames + 2; + } + else + { + /*if VUI is not present assume maximum possible refrence frames for the level, + * as max reorder frames*/ + ps_ctl_op->u4_num_disp_bufs = ih264d_get_dpb_size_new( + level, width_mbs, height_mbs); + } + + ps_ctl_op->u4_num_disp_bufs += + ps_dec->ps_cur_sps->u1_num_ref_frames + 1; + + } + else + { + ps_ctl_op->u4_num_disp_bufs = ih264d_get_dpb_size_new( + ps_dec->u4_level_at_init, + (ps_dec->u4_width_at_init >> 4), + (ps_dec->u4_height_at_init >> 4)); + + ps_ctl_op->u4_num_disp_bufs += + ps_ctl_op->u4_num_disp_bufs; + + ps_ctl_op->u4_num_disp_bufs = + MIN(ps_ctl_op->u4_num_disp_bufs, + (ps_dec->u4_num_ref_frames_at_init + + ps_dec->u4_num_reorder_frames_at_init)); + + } + + ps_ctl_op->u4_num_disp_bufs = MAX( + ps_ctl_op->u4_num_disp_bufs, 6); + ps_ctl_op->u4_num_disp_bufs = MIN( + ps_ctl_op->u4_num_disp_bufs, 32); + } + + /*!*/ + if(ps_dec->u1_chroma_format == IV_YUV_420P) + { + ps_ctl_op->u4_min_out_buf_size[0] = (pic_wd * pic_ht); + ps_ctl_op->u4_min_out_buf_size[1] = (pic_wd * pic_ht) + >> 2; + ps_ctl_op->u4_min_out_buf_size[2] = (pic_wd * pic_ht) + >> 2; + } + else if(ps_dec->u1_chroma_format == IV_YUV_422ILE) + { + ps_ctl_op->u4_min_out_buf_size[0] = (pic_wd * pic_ht) + * 2; + ps_ctl_op->u4_min_out_buf_size[1] = + ps_ctl_op->u4_min_out_buf_size[2] = 0; + } + else if(ps_dec->u1_chroma_format == IV_RGB_565) + { + ps_ctl_op->u4_min_out_buf_size[0] = (pic_wd * pic_ht) + * 2; + ps_ctl_op->u4_min_out_buf_size[1] = + ps_ctl_op->u4_min_out_buf_size[2] = 0; + } + else if((ps_dec->u1_chroma_format == IV_YUV_420SP_UV) + || (ps_dec->u1_chroma_format == IV_YUV_420SP_VU)) + { + ps_ctl_op->u4_min_out_buf_size[0] = (pic_wd * pic_ht); + ps_ctl_op->u4_min_out_buf_size[1] = (pic_wd * pic_ht) + >> 1; + ps_ctl_op->u4_min_out_buf_size[2] = 0; + } + ps_dec->u4_num_disp_bufs_requested = ps_ctl_op->u4_num_disp_bufs; + + return IV_SUCCESS; +} +",0,"WORD32 ih264d_get_buf_info(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op) +{ + + dec_struct_t * ps_dec; + UWORD8 i = 0; // Default for 420P format + UWORD16 pic_wd, pic_ht; + ivd_ctl_getbufinfo_op_t *ps_ctl_op = + (ivd_ctl_getbufinfo_op_t*)pv_api_op; + UNUSED(pv_api_ip); + ps_ctl_op->u4_error_code = 0; + + ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle); + + ps_ctl_op->u4_min_num_in_bufs = MIN_IN_BUFS; + if(ps_dec->u1_chroma_format == IV_YUV_420P) + ps_ctl_op->u4_min_num_out_bufs = MIN_OUT_BUFS_420; + else if(ps_dec->u1_chroma_format == IV_YUV_422ILE) + ps_ctl_op->u4_min_num_out_bufs = MIN_OUT_BUFS_422ILE; + else if(ps_dec->u1_chroma_format == IV_RGB_565) + ps_ctl_op->u4_min_num_out_bufs = MIN_OUT_BUFS_RGB565; + else if((ps_dec->u1_chroma_format == IV_YUV_420SP_UV) + || (ps_dec->u1_chroma_format == IV_YUV_420SP_VU)) + ps_ctl_op->u4_min_num_out_bufs = MIN_OUT_BUFS_420SP; + + else + { + return IV_FAIL; + } + + ps_ctl_op->u4_num_disp_bufs = 1; + + for(i = 0; i < ps_ctl_op->u4_min_num_in_bufs; i++) + { + ps_ctl_op->u4_min_in_buf_size[i] = MIN_IN_BUF_SIZE; + } + + pic_wd = ps_dec->u4_width_at_init; + pic_ht = ps_dec->u4_height_at_init; + + if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) + { + + if(0 == ps_dec->u4_share_disp_buf) + { + pic_wd = ps_dec->u2_disp_width; + pic_ht = ps_dec->u2_disp_height; + + } + else + { + pic_wd = ps_dec->u2_frm_wd_y; + pic_ht = ps_dec->u2_frm_ht_y; + } + + } + else + { + if(1 == ps_dec->u4_share_disp_buf) + { + pic_wd += (PAD_LEN_Y_H << 1); + pic_ht += (PAD_LEN_Y_V << 2); + + } + } + + if((WORD32)ps_dec->u4_app_disp_width > pic_wd) + pic_wd = ps_dec->u4_app_disp_width; + + if(0 == ps_dec->u4_share_disp_buf) + ps_ctl_op->u4_num_disp_bufs = 1; + else + { + if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) + { + UWORD32 level, width_mbs, height_mbs; + + level = ps_dec->u4_level_at_init; + width_mbs = ps_dec->u2_frm_wd_in_mbs; + height_mbs = ps_dec->u2_frm_ht_in_mbs; + + if((ps_dec->ps_cur_sps->u1_vui_parameters_present_flag == 1) + && (ps_dec->ps_cur_sps->s_vui.u4_num_reorder_frames + != 64)) + { + ps_ctl_op->u4_num_disp_bufs = + ps_dec->ps_cur_sps->s_vui.u4_num_reorder_frames + 2; + } + else + { + /*if VUI is not present assume maximum possible refrence frames for the level, + * as max reorder frames*/ + ps_ctl_op->u4_num_disp_bufs = ih264d_get_dpb_size_new( + level, width_mbs, height_mbs); + } + + ps_ctl_op->u4_num_disp_bufs += + ps_dec->ps_cur_sps->u1_num_ref_frames + 1; + + } + else + { + ps_ctl_op->u4_num_disp_bufs = ih264d_get_dpb_size_new( + ps_dec->u4_level_at_init, + (ps_dec->u4_width_at_init >> 4), + (ps_dec->u4_height_at_init >> 4)); + + ps_ctl_op->u4_num_disp_bufs += + ps_ctl_op->u4_num_disp_bufs; + + ps_ctl_op->u4_num_disp_bufs = + MIN(ps_ctl_op->u4_num_disp_bufs, + (ps_dec->u4_num_ref_frames_at_init + + ps_dec->u4_num_reorder_frames_at_init)); + + } + + ps_ctl_op->u4_num_disp_bufs = MAX( + ps_ctl_op->u4_num_disp_bufs, 6); + ps_ctl_op->u4_num_disp_bufs = MIN( + ps_ctl_op->u4_num_disp_bufs, 32); + } + + /*!*/ + if(ps_dec->u1_chroma_format == IV_YUV_420P) + { + ps_ctl_op->u4_min_out_buf_size[0] = (pic_wd * pic_ht); + ps_ctl_op->u4_min_out_buf_size[1] = (pic_wd * pic_ht) + >> 2; + ps_ctl_op->u4_min_out_buf_size[2] = (pic_wd * pic_ht) + >> 2; + } + else if(ps_dec->u1_chroma_format == IV_YUV_422ILE) + { + ps_ctl_op->u4_min_out_buf_size[0] = (pic_wd * pic_ht) + * 2; + ps_ctl_op->u4_min_out_buf_size[1] = + ps_ctl_op->u4_min_out_buf_size[2] = 0; + } + else if(ps_dec->u1_chroma_format == IV_RGB_565) + { + ps_ctl_op->u4_min_out_buf_size[0] = (pic_wd * pic_ht) + * 2; + ps_ctl_op->u4_min_out_buf_size[1] = + ps_ctl_op->u4_min_out_buf_size[2] = 0; + } + else if((ps_dec->u1_chroma_format == IV_YUV_420SP_UV) + || (ps_dec->u1_chroma_format == IV_YUV_420SP_VU)) + { + ps_ctl_op->u4_min_out_buf_size[0] = (pic_wd * pic_ht); + ps_ctl_op->u4_min_out_buf_size[1] = (pic_wd * pic_ht) + >> 1; + ps_ctl_op->u4_min_out_buf_size[2] = 0; + } + ps_dec->u4_num_disp_bufs_requested = ps_ctl_op->u4_num_disp_bufs; + + return IV_SUCCESS; +} +","@@ -2870,7 +2870,7 @@ + + ps_dec->u2_cur_slice_num = 0; + ps_dec->cur_dec_mb_num = 0; + ps_dec->cur_recon_mb_num = 0; +- ps_dec->u4_first_slice_in_pic = 2; ++ ps_dec->u4_first_slice_in_pic = 1; + ps_dec->u1_first_pb_nal_in_pic = 1; + ps_dec->u1_slice_header_done = 0; + ps_dec->u1_dangling_field = 0; +",1510,1841,2048 +9492,"static int parse_options(char *options, struct super_block *sb) +{ + char *p; + struct ext2_sb_info *sbi = EXT2_SB(sb); + substring_t args[MAX_OPT_ARGS]; + int option; + kuid_t uid; + kgid_t gid; + + if (!options) + return 1; + + while ((p = strsep (&options, "","")) != NULL) { + int token; + if (!*p) + continue; + + token = match_token(p, tokens, args); + switch (token) { + case Opt_bsd_df: + clear_opt (sbi->s_mount_opt, MINIX_DF); + break; + case Opt_minix_df: + set_opt (sbi->s_mount_opt, MINIX_DF); + break; + case Opt_grpid: + set_opt (sbi->s_mount_opt, GRPID); + break; + case Opt_nogrpid: + clear_opt (sbi->s_mount_opt, GRPID); + break; + case Opt_resuid: + if (match_int(&args[0], &option)) + return 0; + uid = make_kuid(current_user_ns(), option); + if (!uid_valid(uid)) { + ext2_msg(sb, KERN_ERR, ""Invalid uid value %d"", option); + return 0; + + } + sbi->s_resuid = uid; + break; + case Opt_resgid: + if (match_int(&args[0], &option)) + return 0; + gid = make_kgid(current_user_ns(), option); + if (!gid_valid(gid)) { + ext2_msg(sb, KERN_ERR, ""Invalid gid value %d"", option); + return 0; + } + sbi->s_resgid = gid; + break; + case Opt_sb: + /* handled by get_sb_block() instead of here */ + /* *sb_block = match_int(&args[0]); */ + break; + case Opt_err_panic: + clear_opt (sbi->s_mount_opt, ERRORS_CONT); + clear_opt (sbi->s_mount_opt, ERRORS_RO); + set_opt (sbi->s_mount_opt, ERRORS_PANIC); + break; + case Opt_err_ro: + clear_opt (sbi->s_mount_opt, ERRORS_CONT); + clear_opt (sbi->s_mount_opt, ERRORS_PANIC); + set_opt (sbi->s_mount_opt, ERRORS_RO); + break; + case Opt_err_cont: + clear_opt (sbi->s_mount_opt, ERRORS_RO); + clear_opt (sbi->s_mount_opt, ERRORS_PANIC); + set_opt (sbi->s_mount_opt, ERRORS_CONT); + break; + case Opt_nouid32: + set_opt (sbi->s_mount_opt, NO_UID32); + break; + case Opt_nocheck: + clear_opt (sbi->s_mount_opt, CHECK); + break; + case Opt_debug: + set_opt (sbi->s_mount_opt, DEBUG); + break; + case Opt_oldalloc: + set_opt (sbi->s_mount_opt, OLDALLOC); + break; + case Opt_orlov: + clear_opt (sbi->s_mount_opt, OLDALLOC); + break; + case Opt_nobh: + set_opt (sbi->s_mount_opt, NOBH); + break; +#ifdef CONFIG_EXT2_FS_XATTR + case Opt_user_xattr: + set_opt (sbi->s_mount_opt, XATTR_USER); + break; + case Opt_nouser_xattr: + clear_opt (sbi->s_mount_opt, XATTR_USER); + break; +#else + case Opt_user_xattr: + case Opt_nouser_xattr: + ext2_msg(sb, KERN_INFO, ""(no)user_xattr options"" + ""not supported""); + break; +#endif +#ifdef CONFIG_EXT2_FS_POSIX_ACL + case Opt_acl: + set_opt(sbi->s_mount_opt, POSIX_ACL); + break; + case Opt_noacl: + clear_opt(sbi->s_mount_opt, POSIX_ACL); + break; +#else + case Opt_acl: + case Opt_noacl: + ext2_msg(sb, KERN_INFO, + ""(no)acl options not supported""); + break; +#endif + case Opt_xip: + ext2_msg(sb, KERN_INFO, ""use dax instead of xip""); + set_opt(sbi->s_mount_opt, XIP); + /* Fall through */ + case Opt_dax: +#ifdef CONFIG_FS_DAX + ext2_msg(sb, KERN_WARNING, + ""DAX enabled. Warning: EXPERIMENTAL, use at your own risk""); + set_opt(sbi->s_mount_opt, DAX); +#else + ext2_msg(sb, KERN_INFO, ""dax option not supported""); +#endif + break; + +#if defined(CONFIG_QUOTA) + case Opt_quota: + case Opt_usrquota: + set_opt(sbi->s_mount_opt, USRQUOTA); + break; + + case Opt_grpquota: + set_opt(sbi->s_mount_opt, GRPQUOTA); + break; +#else + case Opt_quota: + case Opt_usrquota: + case Opt_grpquota: + ext2_msg(sb, KERN_INFO, + ""quota operations not supported""); + break; +#endif + + case Opt_reservation: + set_opt(sbi->s_mount_opt, RESERVATION); + ext2_msg(sb, KERN_INFO, ""reservations ON""); + break; + case Opt_noreservation: + clear_opt(sbi->s_mount_opt, RESERVATION); + ext2_msg(sb, KERN_INFO, ""reservations OFF""); + break; + case Opt_ignore: + break; + default: + return 0; + } + } + return 1; +} +",0,"static int parse_options(char *options, struct super_block *sb) +{ + char *p; + struct ext2_sb_info *sbi = EXT2_SB(sb); + substring_t args[MAX_OPT_ARGS]; + int option; + kuid_t uid; + kgid_t gid; + + if (!options) + return 1; + + while ((p = strsep (&options, "","")) != NULL) { + int token; + if (!*p) + continue; + + token = match_token(p, tokens, args); + switch (token) { + case Opt_bsd_df: + clear_opt (sbi->s_mount_opt, MINIX_DF); + break; + case Opt_minix_df: + set_opt (sbi->s_mount_opt, MINIX_DF); + break; + case Opt_grpid: + set_opt (sbi->s_mount_opt, GRPID); + break; + case Opt_nogrpid: + clear_opt (sbi->s_mount_opt, GRPID); + break; + case Opt_resuid: + if (match_int(&args[0], &option)) + return 0; + uid = make_kuid(current_user_ns(), option); + if (!uid_valid(uid)) { + ext2_msg(sb, KERN_ERR, ""Invalid uid value %d"", option); + return 0; + + } + sbi->s_resuid = uid; + break; + case Opt_resgid: + if (match_int(&args[0], &option)) + return 0; + gid = make_kgid(current_user_ns(), option); + if (!gid_valid(gid)) { + ext2_msg(sb, KERN_ERR, ""Invalid gid value %d"", option); + return 0; + } + sbi->s_resgid = gid; + break; + case Opt_sb: + /* handled by get_sb_block() instead of here */ + /* *sb_block = match_int(&args[0]); */ + break; + case Opt_err_panic: + clear_opt (sbi->s_mount_opt, ERRORS_CONT); + clear_opt (sbi->s_mount_opt, ERRORS_RO); + set_opt (sbi->s_mount_opt, ERRORS_PANIC); + break; + case Opt_err_ro: + clear_opt (sbi->s_mount_opt, ERRORS_CONT); + clear_opt (sbi->s_mount_opt, ERRORS_PANIC); + set_opt (sbi->s_mount_opt, ERRORS_RO); + break; + case Opt_err_cont: + clear_opt (sbi->s_mount_opt, ERRORS_RO); + clear_opt (sbi->s_mount_opt, ERRORS_PANIC); + set_opt (sbi->s_mount_opt, ERRORS_CONT); + break; + case Opt_nouid32: + set_opt (sbi->s_mount_opt, NO_UID32); + break; + case Opt_nocheck: + clear_opt (sbi->s_mount_opt, CHECK); + break; + case Opt_debug: + set_opt (sbi->s_mount_opt, DEBUG); + break; + case Opt_oldalloc: + set_opt (sbi->s_mount_opt, OLDALLOC); + break; + case Opt_orlov: + clear_opt (sbi->s_mount_opt, OLDALLOC); + break; + case Opt_nobh: + set_opt (sbi->s_mount_opt, NOBH); + break; +#ifdef CONFIG_EXT2_FS_XATTR + case Opt_user_xattr: + set_opt (sbi->s_mount_opt, XATTR_USER); + break; + case Opt_nouser_xattr: + clear_opt (sbi->s_mount_opt, XATTR_USER); + break; +#else + case Opt_user_xattr: + case Opt_nouser_xattr: + ext2_msg(sb, KERN_INFO, ""(no)user_xattr options"" + ""not supported""); + break; +#endif +#ifdef CONFIG_EXT2_FS_POSIX_ACL + case Opt_acl: + set_opt(sbi->s_mount_opt, POSIX_ACL); + break; + case Opt_noacl: + clear_opt(sbi->s_mount_opt, POSIX_ACL); + break; +#else + case Opt_acl: + case Opt_noacl: + ext2_msg(sb, KERN_INFO, + ""(no)acl options not supported""); + break; +#endif + case Opt_xip: + ext2_msg(sb, KERN_INFO, ""use dax instead of xip""); + set_opt(sbi->s_mount_opt, XIP); + /* Fall through */ + case Opt_dax: +#ifdef CONFIG_FS_DAX + ext2_msg(sb, KERN_WARNING, + ""DAX enabled. Warning: EXPERIMENTAL, use at your own risk""); + set_opt(sbi->s_mount_opt, DAX); +#else + ext2_msg(sb, KERN_INFO, ""dax option not supported""); +#endif + break; + +#if defined(CONFIG_QUOTA) + case Opt_quota: + case Opt_usrquota: + set_opt(sbi->s_mount_opt, USRQUOTA); + break; + + case Opt_grpquota: + set_opt(sbi->s_mount_opt, GRPQUOTA); + break; +#else + case Opt_quota: + case Opt_usrquota: + case Opt_grpquota: + ext2_msg(sb, KERN_INFO, + ""quota operations not supported""); + break; +#endif + + case Opt_reservation: + set_opt(sbi->s_mount_opt, RESERVATION); + ext2_msg(sb, KERN_INFO, ""reservations ON""); + break; + case Opt_noreservation: + clear_opt(sbi->s_mount_opt, RESERVATION); + ext2_msg(sb, KERN_INFO, ""reservations OFF""); + break; + case Opt_ignore: + break; + default: + return 0; + } + } + return 1; +} +","@@ -131,7 +131,10 @@ static void ext2_put_super (struct super_block * sb) + + dquot_disable(sb, -1, DQUOT_USAGE_ENABLED | DQUOT_LIMITS_ENABLED); + +- ext2_xattr_put_super(sb); ++ if (sbi->s_mb_cache) { ++ ext2_xattr_destroy_cache(sbi->s_mb_cache); ++ sbi->s_mb_cache = NULL; ++ } + if (!(sb->s_flags & MS_RDONLY)) { + struct ext2_super_block *es = sbi->s_es; + +@@ -1104,6 +1107,14 @@ static int ext2_fill_super(struct super_block *sb, void *data, int silent) + ext2_msg(sb, KERN_ERR, ""error: insufficient memory""); + goto failed_mount3; + } ++ ++#ifdef CONFIG_EXT2_FS_XATTR ++ sbi->s_mb_cache = ext2_xattr_create_cache(); ++ if (!sbi->s_mb_cache) { ++ ext2_msg(sb, KERN_ERR, ""Failed to create an mb_cache""); ++ goto failed_mount3; ++ } ++#endif + /* + * set up enough so that it can read an inode + */ +@@ -1149,6 +1160,8 @@ static int ext2_fill_super(struct super_block *sb, void *data, int silent) + sb->s_id); + goto failed_mount; + failed_mount3: ++ if (sbi->s_mb_cache) ++ ext2_xattr_destroy_cache(sbi->s_mb_cache); + percpu_counter_destroy(&sbi->s_freeblocks_counter); + percpu_counter_destroy(&sbi->s_freeinodes_counter); + percpu_counter_destroy(&sbi->s_dirs_counter); +@@ -1555,28 +1568,24 @@ MODULE_ALIAS_FS(""ext2""); + + static int __init init_ext2_fs(void) + { +- int err = init_ext2_xattr(); +- if (err) +- return err; ++ int err; ++ + err = init_inodecache(); + if (err) +- goto out1; ++ return err; + err = register_filesystem(&ext2_fs_type); + if (err) + goto out; + return 0; + out: + destroy_inodecache(); +-out1: +- exit_ext2_xattr(); + return err; + } + + static void __exit exit_ext2_fs(void) + { + unregister_filesystem(&ext2_fs_type); + destroy_inodecache(); +- exit_ext2_xattr(); + } + + MODULE_AUTHOR(""Remy Card and others"");",1243,1574,2048 +13657,"void HTMLInputElement::UpdateType() { + DCHECK(input_type_); + DCHECK(input_type_view_); + + const AtomicString& new_type_name = + InputType::NormalizeTypeName(FastGetAttribute(typeAttr)); + if (input_type_->FormControlType() == new_type_name) + return; + + InputType* new_type = InputType::Create(*this, new_type_name); + RemoveFromRadioButtonGroup(); + + ValueMode old_value_mode = input_type_->GetValueMode(); + bool did_respect_height_and_width = + input_type_->ShouldRespectHeightAndWidthAttributes(); + bool could_be_successful_submit_button = CanBeSuccessfulSubmitButton(); + + input_type_view_->DestroyShadowSubtree(); + DropInnerEditorElement(); + LazyReattachIfAttached(); + + if (input_type_->SupportsRequired() != new_type->SupportsRequired() && + IsRequired()) { + PseudoStateChanged(CSSSelector::kPseudoRequired); + PseudoStateChanged(CSSSelector::kPseudoOptional); + } + if (input_type_->SupportsReadOnly() != new_type->SupportsReadOnly()) { + PseudoStateChanged(CSSSelector::kPseudoReadOnly); + PseudoStateChanged(CSSSelector::kPseudoReadWrite); + } + if (input_type_->IsCheckable() != new_type->IsCheckable()) { + PseudoStateChanged(CSSSelector::kPseudoChecked); + } + PseudoStateChanged(CSSSelector::kPseudoIndeterminate); + if (input_type_->IsSteppable() || new_type->IsSteppable()) { + PseudoStateChanged(CSSSelector::kPseudoInRange); + PseudoStateChanged(CSSSelector::kPseudoOutOfRange); + } + + bool placeholder_changed = + input_type_->SupportsPlaceholder() != new_type->SupportsPlaceholder(); + + has_been_password_field_ |= new_type_name == InputTypeNames::password; + + input_type_ = new_type; + input_type_view_ = input_type_->CreateView(); + if (input_type_view_->NeedsShadowSubtree()) { + EnsureUserAgentShadowRoot(); + CreateShadowSubtree(); + } + + SetNeedsWillValidateCheck(); + + if (placeholder_changed) { + UpdatePlaceholderText(); + UpdatePlaceholderVisibility(); + PseudoStateChanged(CSSSelector::kPseudoPlaceholderShown); + } + + ValueMode new_value_mode = input_type_->GetValueMode(); + + if (old_value_mode == ValueMode::kValue && + (new_value_mode == ValueMode::kDefault || + new_value_mode == ValueMode::kDefaultOn)) { + if (HasDirtyValue()) + setAttribute(valueAttr, AtomicString(non_attribute_value_)); + non_attribute_value_ = String(); + has_dirty_value_ = false; + } + else if (old_value_mode != ValueMode::kValue && + new_value_mode == ValueMode::kValue) { + AtomicString value_string = FastGetAttribute(valueAttr); + input_type_->WarnIfValueIsInvalid(value_string); + non_attribute_value_ = SanitizeValue(value_string); + has_dirty_value_ = false; + } + else if (old_value_mode != ValueMode::kFilename && + new_value_mode == ValueMode::kFilename) { + non_attribute_value_ = String(); + has_dirty_value_ = false; + + } else { + if (!HasDirtyValue()) { + String default_value = FastGetAttribute(valueAttr); + if (!default_value.IsNull()) + input_type_->WarnIfValueIsInvalid(default_value); + } + + if (new_value_mode == ValueMode::kValue) { + String new_value = SanitizeValue(non_attribute_value_); + if (!EqualIgnoringNullity(new_value, non_attribute_value_)) { + if (HasDirtyValue()) + setValue(new_value); + else + SetNonDirtyValue(new_value); + } + } + } + + needs_to_update_view_value_ = true; + input_type_view_->UpdateView(); + + if (did_respect_height_and_width != + input_type_->ShouldRespectHeightAndWidthAttributes()) { + DCHECK(GetElementData()); + AttributeCollection attributes = AttributesWithoutUpdate(); + if (const Attribute* height = attributes.Find(heightAttr)) { + TextControlElement::AttributeChanged(AttributeModificationParams( + heightAttr, height->Value(), height->Value(), + AttributeModificationReason::kDirectly)); + } + if (const Attribute* width = attributes.Find(widthAttr)) { + TextControlElement::AttributeChanged( + AttributeModificationParams(widthAttr, width->Value(), width->Value(), + AttributeModificationReason::kDirectly)); + } + if (const Attribute* align = attributes.Find(alignAttr)) { + TextControlElement::AttributeChanged( + AttributeModificationParams(alignAttr, align->Value(), align->Value(), + AttributeModificationReason::kDirectly)); + } + } + + if (GetDocument().FocusedElement() == this) + GetDocument().UpdateFocusAppearanceLater(); + + ClearValueBeforeFirstUserEdit(); + + AddToRadioButtonGroup(); + + SetNeedsValidityCheck(); + if ((could_be_successful_submit_button || CanBeSuccessfulSubmitButton()) && + formOwner() && isConnected()) + formOwner()->InvalidateDefaultButtonStyle(); + NotifyFormStateChanged(); +} +",0,"void HTMLInputElement::UpdateType() { + DCHECK(input_type_); + DCHECK(input_type_view_); + + const AtomicString& new_type_name = + InputType::NormalizeTypeName(FastGetAttribute(typeAttr)); + if (input_type_->FormControlType() == new_type_name) + return; + + InputType* new_type = InputType::Create(*this, new_type_name); + RemoveFromRadioButtonGroup(); + + ValueMode old_value_mode = input_type_->GetValueMode(); + bool did_respect_height_and_width = + input_type_->ShouldRespectHeightAndWidthAttributes(); + bool could_be_successful_submit_button = CanBeSuccessfulSubmitButton(); + + input_type_view_->DestroyShadowSubtree(); + DropInnerEditorElement(); + LazyReattachIfAttached(); + + if (input_type_->SupportsRequired() != new_type->SupportsRequired() && + IsRequired()) { + PseudoStateChanged(CSSSelector::kPseudoRequired); + PseudoStateChanged(CSSSelector::kPseudoOptional); + } + if (input_type_->SupportsReadOnly() != new_type->SupportsReadOnly()) { + PseudoStateChanged(CSSSelector::kPseudoReadOnly); + PseudoStateChanged(CSSSelector::kPseudoReadWrite); + } + if (input_type_->IsCheckable() != new_type->IsCheckable()) { + PseudoStateChanged(CSSSelector::kPseudoChecked); + } + PseudoStateChanged(CSSSelector::kPseudoIndeterminate); + if (input_type_->IsSteppable() || new_type->IsSteppable()) { + PseudoStateChanged(CSSSelector::kPseudoInRange); + PseudoStateChanged(CSSSelector::kPseudoOutOfRange); + } + + bool placeholder_changed = + input_type_->SupportsPlaceholder() != new_type->SupportsPlaceholder(); + + has_been_password_field_ |= new_type_name == InputTypeNames::password; + + input_type_ = new_type; + input_type_view_ = input_type_->CreateView(); + if (input_type_view_->NeedsShadowSubtree()) { + EnsureUserAgentShadowRoot(); + CreateShadowSubtree(); + } + + SetNeedsWillValidateCheck(); + + if (placeholder_changed) { + UpdatePlaceholderText(); + UpdatePlaceholderVisibility(); + PseudoStateChanged(CSSSelector::kPseudoPlaceholderShown); + } + + ValueMode new_value_mode = input_type_->GetValueMode(); + + if (old_value_mode == ValueMode::kValue && + (new_value_mode == ValueMode::kDefault || + new_value_mode == ValueMode::kDefaultOn)) { + if (HasDirtyValue()) + setAttribute(valueAttr, AtomicString(non_attribute_value_)); + non_attribute_value_ = String(); + has_dirty_value_ = false; + } + else if (old_value_mode != ValueMode::kValue && + new_value_mode == ValueMode::kValue) { + AtomicString value_string = FastGetAttribute(valueAttr); + input_type_->WarnIfValueIsInvalid(value_string); + non_attribute_value_ = SanitizeValue(value_string); + has_dirty_value_ = false; + } + else if (old_value_mode != ValueMode::kFilename && + new_value_mode == ValueMode::kFilename) { + non_attribute_value_ = String(); + has_dirty_value_ = false; + + } else { + if (!HasDirtyValue()) { + String default_value = FastGetAttribute(valueAttr); + if (!default_value.IsNull()) + input_type_->WarnIfValueIsInvalid(default_value); + } + + if (new_value_mode == ValueMode::kValue) { + String new_value = SanitizeValue(non_attribute_value_); + if (!EqualIgnoringNullity(new_value, non_attribute_value_)) { + if (HasDirtyValue()) + setValue(new_value); + else + SetNonDirtyValue(new_value); + } + } + } + + needs_to_update_view_value_ = true; + input_type_view_->UpdateView(); + + if (did_respect_height_and_width != + input_type_->ShouldRespectHeightAndWidthAttributes()) { + DCHECK(GetElementData()); + AttributeCollection attributes = AttributesWithoutUpdate(); + if (const Attribute* height = attributes.Find(heightAttr)) { + TextControlElement::AttributeChanged(AttributeModificationParams( + heightAttr, height->Value(), height->Value(), + AttributeModificationReason::kDirectly)); + } + if (const Attribute* width = attributes.Find(widthAttr)) { + TextControlElement::AttributeChanged( + AttributeModificationParams(widthAttr, width->Value(), width->Value(), + AttributeModificationReason::kDirectly)); + } + if (const Attribute* align = attributes.Find(alignAttr)) { + TextControlElement::AttributeChanged( + AttributeModificationParams(alignAttr, align->Value(), align->Value(), + AttributeModificationReason::kDirectly)); + } + } + + if (GetDocument().FocusedElement() == this) + GetDocument().UpdateFocusAppearanceLater(); + + ClearValueBeforeFirstUserEdit(); + + AddToRadioButtonGroup(); + + SetNeedsValidityCheck(); + if ((could_be_successful_submit_button || CanBeSuccessfulSubmitButton()) && + formOwner() && isConnected()) + formOwner()->InvalidateDefaultButtonStyle(); + NotifyFormStateChanged(); +} +","@@ -342,11 +342,6 @@ void HTMLInputElement::EndEditing() { + frame->GetPage()->GetChromeClient().DidEndEditingOnTextField(*this); + } + +-void HTMLInputElement::HandleFocusEvent(Element* old_focused_element, +- WebFocusType type) { +- input_type_->EnableSecureTextInput(); +-} +- + void HTMLInputElement::DispatchFocusInEvent( + const AtomicString& event_type, + Element* old_focused_element, +@@ -359,7 +354,6 @@ void HTMLInputElement::DispatchFocusInEvent( + } + + void HTMLInputElement::HandleBlurEvent() { +- input_type_->DisableSecureTextInput(); + input_type_view_->HandleBlurEvent(); + } + ",1078,1409,2048 +17119,"void AudioFlinger::EffectModule::dump(int fd, const Vector& args __unused) +{ + const size_t SIZE = 256; + char buffer[SIZE]; + String8 result; + + snprintf(buffer, SIZE, ""\tEffect ID %d:\n"", mId); + result.append(buffer); + + bool locked = AudioFlinger::dumpTryLock(mLock); + if (!locked) { + result.append(""\t\tCould not lock Fx mutex:\n""); + } + + result.append(""\t\tSession Status State Engine:\n""); + snprintf(buffer, SIZE, ""\t\t%05d %03d %03d %p\n"", + mSessionId, mStatus, mState, mEffectInterface); + result.append(buffer); + + result.append(""\t\tDescriptor:\n""); + snprintf(buffer, SIZE, ""\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n"", + mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion, + mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1], + mDescriptor.uuid.node[2], + mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]); + result.append(buffer); + snprintf(buffer, SIZE, ""\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n"", + mDescriptor.type.timeLow, mDescriptor.type.timeMid, + mDescriptor.type.timeHiAndVersion, + mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1], + mDescriptor.type.node[2], + mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]); + result.append(buffer); + snprintf(buffer, SIZE, ""\t\t- apiVersion: %08X\n\t\t- flags: %08X (%s)\n"", + mDescriptor.apiVersion, + mDescriptor.flags, + effectFlagsToString(mDescriptor.flags).string()); + result.append(buffer); + snprintf(buffer, SIZE, ""\t\t- name: %s\n"", + mDescriptor.name); + result.append(buffer); + snprintf(buffer, SIZE, ""\t\t- implementor: %s\n"", + mDescriptor.implementor); + result.append(buffer); + + result.append(""\t\t- Input configuration:\n""); + result.append(""\t\t\tFrames Smp rate Channels Format Buffer\n""); + snprintf(buffer, SIZE, ""\t\t\t%05zu %05d %08x %6d (%s) %p\n"", + mConfig.inputCfg.buffer.frameCount, + mConfig.inputCfg.samplingRate, + mConfig.inputCfg.channels, + mConfig.inputCfg.format, + formatToString((audio_format_t)mConfig.inputCfg.format), + mConfig.inputCfg.buffer.raw); + result.append(buffer); + + result.append(""\t\t- Output configuration:\n""); + result.append(""\t\t\tBuffer Frames Smp rate Channels Format\n""); + snprintf(buffer, SIZE, ""\t\t\t%p %05zu %05d %08x %d (%s)\n"", + mConfig.outputCfg.buffer.raw, + mConfig.outputCfg.buffer.frameCount, + mConfig.outputCfg.samplingRate, + mConfig.outputCfg.channels, + mConfig.outputCfg.format, + formatToString((audio_format_t)mConfig.outputCfg.format)); + result.append(buffer); + + snprintf(buffer, SIZE, ""\t\t%zu Clients:\n"", mHandles.size()); + result.append(buffer); + result.append(""\t\t\t Pid Priority Ctrl Locked client server\n""); + for (size_t i = 0; i < mHandles.size(); ++i) { + EffectHandle *handle = mHandles[i]; + if (handle != NULL && !handle->destroyed_l()) { + handle->dumpToBuffer(buffer, SIZE); + result.append(buffer); + } + } + + write(fd, result.string(), result.length()); + + if (locked) { + mLock.unlock(); + } +} +",0,"void AudioFlinger::EffectModule::dump(int fd, const Vector& args __unused) +{ + const size_t SIZE = 256; + char buffer[SIZE]; + String8 result; + + snprintf(buffer, SIZE, ""\tEffect ID %d:\n"", mId); + result.append(buffer); + + bool locked = AudioFlinger::dumpTryLock(mLock); + if (!locked) { + result.append(""\t\tCould not lock Fx mutex:\n""); + } + + result.append(""\t\tSession Status State Engine:\n""); + snprintf(buffer, SIZE, ""\t\t%05d %03d %03d %p\n"", + mSessionId, mStatus, mState, mEffectInterface); + result.append(buffer); + + result.append(""\t\tDescriptor:\n""); + snprintf(buffer, SIZE, ""\t\t- UUID: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n"", + mDescriptor.uuid.timeLow, mDescriptor.uuid.timeMid, mDescriptor.uuid.timeHiAndVersion, + mDescriptor.uuid.clockSeq, mDescriptor.uuid.node[0], mDescriptor.uuid.node[1], + mDescriptor.uuid.node[2], + mDescriptor.uuid.node[3],mDescriptor.uuid.node[4],mDescriptor.uuid.node[5]); + result.append(buffer); + snprintf(buffer, SIZE, ""\t\t- TYPE: %08X-%04X-%04X-%04X-%02X%02X%02X%02X%02X%02X\n"", + mDescriptor.type.timeLow, mDescriptor.type.timeMid, + mDescriptor.type.timeHiAndVersion, + mDescriptor.type.clockSeq, mDescriptor.type.node[0], mDescriptor.type.node[1], + mDescriptor.type.node[2], + mDescriptor.type.node[3],mDescriptor.type.node[4],mDescriptor.type.node[5]); + result.append(buffer); + snprintf(buffer, SIZE, ""\t\t- apiVersion: %08X\n\t\t- flags: %08X (%s)\n"", + mDescriptor.apiVersion, + mDescriptor.flags, + effectFlagsToString(mDescriptor.flags).string()); + result.append(buffer); + snprintf(buffer, SIZE, ""\t\t- name: %s\n"", + mDescriptor.name); + result.append(buffer); + snprintf(buffer, SIZE, ""\t\t- implementor: %s\n"", + mDescriptor.implementor); + result.append(buffer); + + result.append(""\t\t- Input configuration:\n""); + result.append(""\t\t\tFrames Smp rate Channels Format Buffer\n""); + snprintf(buffer, SIZE, ""\t\t\t%05zu %05d %08x %6d (%s) %p\n"", + mConfig.inputCfg.buffer.frameCount, + mConfig.inputCfg.samplingRate, + mConfig.inputCfg.channels, + mConfig.inputCfg.format, + formatToString((audio_format_t)mConfig.inputCfg.format), + mConfig.inputCfg.buffer.raw); + result.append(buffer); + + result.append(""\t\t- Output configuration:\n""); + result.append(""\t\t\tBuffer Frames Smp rate Channels Format\n""); + snprintf(buffer, SIZE, ""\t\t\t%p %05zu %05d %08x %d (%s)\n"", + mConfig.outputCfg.buffer.raw, + mConfig.outputCfg.buffer.frameCount, + mConfig.outputCfg.samplingRate, + mConfig.outputCfg.channels, + mConfig.outputCfg.format, + formatToString((audio_format_t)mConfig.outputCfg.format)); + result.append(buffer); + + snprintf(buffer, SIZE, ""\t\t%zu Clients:\n"", mHandles.size()); + result.append(buffer); + result.append(""\t\t\t Pid Priority Ctrl Locked client server\n""); + for (size_t i = 0; i < mHandles.size(); ++i) { + EffectHandle *handle = mHandles[i]; + if (handle != NULL && !handle->destroyed_l()) { + handle->dumpToBuffer(buffer, SIZE); + result.append(buffer); + } + } + + write(fd, result.string(), result.length()); + + if (locked) { + mLock.unlock(); + } +} +","@@ -543,6 +543,13 @@ + + return NO_ERROR; + } + ++// round up delta valid if value and divisor are positive. ++template ++static T roundUpDelta(const T &value, const T &divisor) { ++ T remainder = value % divisor; ++ return remainder == 0 ? 0 : divisor - remainder; ++} ++ + status_t AudioFlinger::EffectModule::command(uint32_t cmdCode, + uint32_t cmdSize, + void *pCmdData, +@@ -564,6 +571,22 @@ + + android_errorWriteLog(0x534e4554, ""29251553""); + return -EINVAL; + } ++ if ((cmdCode == EFFECT_CMD_SET_PARAM ++ || cmdCode == EFFECT_CMD_SET_PARAM_DEFERRED) && // DEFERRED not generally used ++ (sizeof(effect_param_t) > cmdSize ++ || ((effect_param_t *)pCmdData)->psize > cmdSize ++ - sizeof(effect_param_t) ++ || ((effect_param_t *)pCmdData)->vsize > cmdSize ++ - sizeof(effect_param_t) ++ - ((effect_param_t *)pCmdData)->psize ++ || roundUpDelta(((effect_param_t *)pCmdData)->psize, (uint32_t)sizeof(int)) > ++ cmdSize ++ - sizeof(effect_param_t) ++ - ((effect_param_t *)pCmdData)->psize ++ - ((effect_param_t *)pCmdData)->vsize)) { ++ android_errorWriteLog(0x534e4554, ""30204301""); ++ return -EINVAL; ++ } + status_t status = (*mEffectInterface)->command(mEffectInterface, + cmdCode, + cmdSize, +",910,1241,2048 +2885,"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->tile) { + av_log(s->avctx, AV_LOG_ERROR, ""Missing SIZ\n""); + return AVERROR_INVALIDDATA; + } + 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: + bytestream2_skip(&s->g, len - 2); + break; + case JPEG2000_TLM: + 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; +} +",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->tile) { + av_log(s->avctx, AV_LOG_ERROR, ""Missing SIZ\n""); + return AVERROR_INVALIDDATA; + } + 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: + bytestream2_skip(&s->g, len - 2); + break; + case JPEG2000_TLM: + 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; +} +","@@ -1278,12 +1278,12 @@ static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile, + + + y = tile->comp[compno].coord[1][0] - s->image_offset_y; +- line = picture->data[plane] + y * picture->linesize[plane]; ++ line = picture->data[plane] + y / s->cdy[compno] * 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; ++ dst = line + x / s->cdx[compno] * pixelsize + compno*!planar; + + if (codsty->transform == FF_DWT97) { + for (; x < w; x += s->cdx[compno]) { +@@ -1324,12 +1324,12 @@ static int jpeg2000_decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile, + 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); ++ linel = (uint16_t *)picture->data[plane] + y / s->cdy[compno] * (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); ++ dst = linel + (x / s->cdx[compno] * pixelsize + compno*!planar); + if (codsty->transform == FF_DWT97) { + for (; x < w; x += s-> cdx[compno]) { + int val = lrintf(*datap) + (1 << (cbps - 1));",909,1240,2048 +5142,"zisofs_extract_init(struct archive_write *a, struct zisofs_extract *zisofs, + const unsigned char *p, size_t bytes) +{ + size_t avail = bytes; + size_t _ceil, xsize; + + /* Allocate block pointers buffer. */ + _ceil = (size_t)((zisofs->pz_uncompressed_size + + (((int64_t)1) << zisofs->pz_log2_bs) - 1) + >> zisofs->pz_log2_bs); + xsize = (_ceil + 1) * 4; + if (zisofs->block_pointers == NULL) { + size_t alloc = ((xsize >> 10) + 1) << 10; + zisofs->block_pointers = malloc(alloc); + if (zisofs->block_pointers == NULL) { + archive_set_error(&a->archive, ENOMEM, + ""No memory for zisofs decompression""); + return (ARCHIVE_FATAL); + } + } + zisofs->block_pointers_size = xsize; + + /* Allocate uncompressed data buffer. */ + zisofs->uncompressed_buffer_size = (size_t)1UL << zisofs->pz_log2_bs; + + /* + * Read the file header, and check the magic code of zisofs. + */ + if (!zisofs->header_passed) { + int err = 0; + if (avail < 16) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + ""Illegal zisofs file body""); + return (ARCHIVE_FATAL); + } + + if (memcmp(p, zisofs_magic, sizeof(zisofs_magic)) != 0) + err = 1; + else if (archive_le32dec(p + 8) != zisofs->pz_uncompressed_size) + err = 1; + else if (p[12] != 4 || p[13] != zisofs->pz_log2_bs) + err = 1; + if (err) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + ""Illegal zisofs file body""); + return (ARCHIVE_FATAL); + } + avail -= 16; + p += 16; + zisofs->header_passed = 1; + } + + /* + * Read block pointers. + */ + if (zisofs->header_passed && + zisofs->block_pointers_avail < zisofs->block_pointers_size) { + xsize = zisofs->block_pointers_size + - zisofs->block_pointers_avail; + if (avail < xsize) + xsize = avail; + memcpy(zisofs->block_pointers + + zisofs->block_pointers_avail, p, xsize); + zisofs->block_pointers_avail += xsize; + avail -= xsize; + if (zisofs->block_pointers_avail + == zisofs->block_pointers_size) { + /* We've got all block pointers and initialize + * related variables. */ + zisofs->block_off = 0; + zisofs->block_avail = 0; + /* Complete a initialization */ + zisofs->initialized = 1; + } + } + return ((ssize_t)avail); +} +",0,"zisofs_extract_init(struct archive_write *a, struct zisofs_extract *zisofs, + const unsigned char *p, size_t bytes) +{ + size_t avail = bytes; + size_t _ceil, xsize; + + /* Allocate block pointers buffer. */ + _ceil = (size_t)((zisofs->pz_uncompressed_size + + (((int64_t)1) << zisofs->pz_log2_bs) - 1) + >> zisofs->pz_log2_bs); + xsize = (_ceil + 1) * 4; + if (zisofs->block_pointers == NULL) { + size_t alloc = ((xsize >> 10) + 1) << 10; + zisofs->block_pointers = malloc(alloc); + if (zisofs->block_pointers == NULL) { + archive_set_error(&a->archive, ENOMEM, + ""No memory for zisofs decompression""); + return (ARCHIVE_FATAL); + } + } + zisofs->block_pointers_size = xsize; + + /* Allocate uncompressed data buffer. */ + zisofs->uncompressed_buffer_size = (size_t)1UL << zisofs->pz_log2_bs; + + /* + * Read the file header, and check the magic code of zisofs. + */ + if (!zisofs->header_passed) { + int err = 0; + if (avail < 16) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + ""Illegal zisofs file body""); + return (ARCHIVE_FATAL); + } + + if (memcmp(p, zisofs_magic, sizeof(zisofs_magic)) != 0) + err = 1; + else if (archive_le32dec(p + 8) != zisofs->pz_uncompressed_size) + err = 1; + else if (p[12] != 4 || p[13] != zisofs->pz_log2_bs) + err = 1; + if (err) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + ""Illegal zisofs file body""); + return (ARCHIVE_FATAL); + } + avail -= 16; + p += 16; + zisofs->header_passed = 1; + } + + /* + * Read block pointers. + */ + if (zisofs->header_passed && + zisofs->block_pointers_avail < zisofs->block_pointers_size) { + xsize = zisofs->block_pointers_size + - zisofs->block_pointers_avail; + if (avail < xsize) + xsize = avail; + memcpy(zisofs->block_pointers + + zisofs->block_pointers_avail, p, xsize); + zisofs->block_pointers_avail += xsize; + avail -= xsize; + if (zisofs->block_pointers_avail + == zisofs->block_pointers_size) { + /* We've got all block pointers and initialize + * related variables. */ + zisofs->block_off = 0; + zisofs->block_avail = 0; + /* Complete a initialization */ + zisofs->initialized = 1; + } + } + return ((ssize_t)avail); +} +","@@ -6225,7 +6225,7 @@ isoent_gen_joliet_identifier(struct archive_write *a, struct isoent *isoent, + unsigned char *p; + size_t l; + int r; +- int ffmax, parent_len; ++ size_t ffmax, parent_len; + static const struct archive_rb_tree_ops rb_ops = { + isoent_cmp_node_joliet, isoent_cmp_key_joliet + }; +@@ -6239,7 +6239,7 @@ isoent_gen_joliet_identifier(struct archive_write *a, struct isoent *isoent, + else + ffmax = 128; + +- r = idr_start(a, idr, isoent->children.cnt, ffmax, 6, 2, &rb_ops); ++ r = idr_start(a, idr, isoent->children.cnt, (int)ffmax, 6, 2, &rb_ops); + if (r < 0) + return (r); + +@@ -6252,7 +6252,7 @@ isoent_gen_joliet_identifier(struct archive_write *a, struct isoent *isoent, + int ext_off, noff, weight; + size_t lt; + +- if ((int)(l = np->file->basename_utf16.length) > ffmax) ++ if ((l = np->file->basename_utf16.length) > ffmax) + l = ffmax; + + p = malloc((l+1)*2); +@@ -6285,7 +6285,7 @@ isoent_gen_joliet_identifier(struct archive_write *a, struct isoent *isoent, + /* + * Get a length of MBS of a full-pathname. + */ +- if ((int)np->file->basename_utf16.length > ffmax) { ++ if (np->file->basename_utf16.length > ffmax) { + if (archive_strncpy_l(&iso9660->mbs, + (const char *)np->identifier, l, + iso9660->sconv_from_utf16be) != 0 && +@@ -6302,7 +6302,9 @@ isoent_gen_joliet_identifier(struct archive_write *a, struct isoent *isoent, + + /* If a length of full-pathname is longer than 240 bytes, + * it violates Joliet extensions regulation. */ +- if (parent_len + np->mb_len > 240) { ++ if (parent_len > 240 ++ || np->mb_len > 240 ++ || parent_len + np->mb_len > 240) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + ""The regulation of Joliet extensions;"" + "" A length of a full-pathname of `%s' is "" +@@ -6314,11 +6316,11 @@ isoent_gen_joliet_identifier(struct archive_write *a, struct isoent *isoent, + + /* Make an offset of the number which is used to be set + * hexadecimal number to avoid duplicate identifier. */ +- if ((int)l == ffmax) ++ if (l == ffmax) + noff = ext_off - 6; +- else if ((int)l == ffmax-2) ++ else if (l == ffmax-2) + noff = ext_off - 4; +- else if ((int)l == ffmax-4) ++ else if (l == ffmax-4) + noff = ext_off - 2; + else + noff = ext_off;",730,1061,2048 +6804,"static int sctp_setsockopt(struct sock *sk, int level, int optname, + char __user *optval, unsigned int optlen) +{ + int retval = 0; + + pr_debug(""%s: sk:%p, optname:%d\n"", __func__, sk, optname); + + /* I can hardly begin to describe how wrong this is. This is + * so broken as to be worse than useless. The API draft + * REALLY is NOT helpful here... I am not convinced that the + * semantics of setsockopt() with a level OTHER THAN SOL_SCTP + * are at all well-founded. + */ + if (level != SOL_SCTP) { + struct sctp_af *af = sctp_sk(sk)->pf->af; + retval = af->setsockopt(sk, level, optname, optval, optlen); + goto out_nounlock; + } + + lock_sock(sk); + + switch (optname) { + case SCTP_SOCKOPT_BINDX_ADD: + /* 'optlen' is the size of the addresses buffer. */ + retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval, + optlen, SCTP_BINDX_ADD_ADDR); + break; + + case SCTP_SOCKOPT_BINDX_REM: + /* 'optlen' is the size of the addresses buffer. */ + retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval, + optlen, SCTP_BINDX_REM_ADDR); + break; + + case SCTP_SOCKOPT_CONNECTX_OLD: + /* 'optlen' is the size of the addresses buffer. */ + retval = sctp_setsockopt_connectx_old(sk, + (struct sockaddr __user *)optval, + optlen); + break; + + case SCTP_SOCKOPT_CONNECTX: + /* 'optlen' is the size of the addresses buffer. */ + retval = sctp_setsockopt_connectx(sk, + (struct sockaddr __user *)optval, + optlen); + break; + + case SCTP_DISABLE_FRAGMENTS: + retval = sctp_setsockopt_disable_fragments(sk, optval, optlen); + break; + + case SCTP_EVENTS: + retval = sctp_setsockopt_events(sk, optval, optlen); + break; + + case SCTP_AUTOCLOSE: + retval = sctp_setsockopt_autoclose(sk, optval, optlen); + break; + + case SCTP_PEER_ADDR_PARAMS: + retval = sctp_setsockopt_peer_addr_params(sk, optval, optlen); + break; + + case SCTP_DELAYED_SACK: + retval = sctp_setsockopt_delayed_ack(sk, optval, optlen); + break; + case SCTP_PARTIAL_DELIVERY_POINT: + retval = sctp_setsockopt_partial_delivery_point(sk, optval, optlen); + break; + + case SCTP_INITMSG: + retval = sctp_setsockopt_initmsg(sk, optval, optlen); + break; + case SCTP_DEFAULT_SEND_PARAM: + retval = sctp_setsockopt_default_send_param(sk, optval, + optlen); + break; + case SCTP_DEFAULT_SNDINFO: + retval = sctp_setsockopt_default_sndinfo(sk, optval, optlen); + break; + case SCTP_PRIMARY_ADDR: + retval = sctp_setsockopt_primary_addr(sk, optval, optlen); + break; + case SCTP_SET_PEER_PRIMARY_ADDR: + retval = sctp_setsockopt_peer_primary_addr(sk, optval, optlen); + break; + case SCTP_NODELAY: + retval = sctp_setsockopt_nodelay(sk, optval, optlen); + break; + case SCTP_RTOINFO: + retval = sctp_setsockopt_rtoinfo(sk, optval, optlen); + break; + case SCTP_ASSOCINFO: + retval = sctp_setsockopt_associnfo(sk, optval, optlen); + break; + case SCTP_I_WANT_MAPPED_V4_ADDR: + retval = sctp_setsockopt_mappedv4(sk, optval, optlen); + break; + case SCTP_MAXSEG: + retval = sctp_setsockopt_maxseg(sk, optval, optlen); + break; + case SCTP_ADAPTATION_LAYER: + retval = sctp_setsockopt_adaptation_layer(sk, optval, optlen); + break; + case SCTP_CONTEXT: + retval = sctp_setsockopt_context(sk, optval, optlen); + break; + case SCTP_FRAGMENT_INTERLEAVE: + retval = sctp_setsockopt_fragment_interleave(sk, optval, optlen); + break; + case SCTP_MAX_BURST: + retval = sctp_setsockopt_maxburst(sk, optval, optlen); + break; + case SCTP_AUTH_CHUNK: + retval = sctp_setsockopt_auth_chunk(sk, optval, optlen); + break; + case SCTP_HMAC_IDENT: + retval = sctp_setsockopt_hmac_ident(sk, optval, optlen); + break; + case SCTP_AUTH_KEY: + retval = sctp_setsockopt_auth_key(sk, optval, optlen); + break; + case SCTP_AUTH_ACTIVE_KEY: + retval = sctp_setsockopt_active_key(sk, optval, optlen); + break; + case SCTP_AUTH_DELETE_KEY: + retval = sctp_setsockopt_del_key(sk, optval, optlen); + break; + case SCTP_AUTO_ASCONF: + retval = sctp_setsockopt_auto_asconf(sk, optval, optlen); + break; + case SCTP_PEER_ADDR_THLDS: + retval = sctp_setsockopt_paddr_thresholds(sk, optval, optlen); + break; + case SCTP_RECVRCVINFO: + retval = sctp_setsockopt_recvrcvinfo(sk, optval, optlen); + break; + case SCTP_RECVNXTINFO: + retval = sctp_setsockopt_recvnxtinfo(sk, optval, optlen); + break; + case SCTP_PR_SUPPORTED: + retval = sctp_setsockopt_pr_supported(sk, optval, optlen); + break; + case SCTP_DEFAULT_PRINFO: + retval = sctp_setsockopt_default_prinfo(sk, optval, optlen); + break; + case SCTP_ENABLE_STREAM_RESET: + retval = sctp_setsockopt_enable_strreset(sk, optval, optlen); + break; + case SCTP_RESET_STREAMS: + retval = sctp_setsockopt_reset_streams(sk, optval, optlen); + break; + case SCTP_RESET_ASSOC: + retval = sctp_setsockopt_reset_assoc(sk, optval, optlen); + break; + case SCTP_ADD_STREAMS: + retval = sctp_setsockopt_add_streams(sk, optval, optlen); + break; + default: + retval = -ENOPROTOOPT; + break; + } + + release_sock(sk); + +out_nounlock: + return retval; +} +",0,"static int sctp_setsockopt(struct sock *sk, int level, int optname, + char __user *optval, unsigned int optlen) +{ + int retval = 0; + + pr_debug(""%s: sk:%p, optname:%d\n"", __func__, sk, optname); + + /* I can hardly begin to describe how wrong this is. This is + * so broken as to be worse than useless. The API draft + * REALLY is NOT helpful here... I am not convinced that the + * semantics of setsockopt() with a level OTHER THAN SOL_SCTP + * are at all well-founded. + */ + if (level != SOL_SCTP) { + struct sctp_af *af = sctp_sk(sk)->pf->af; + retval = af->setsockopt(sk, level, optname, optval, optlen); + goto out_nounlock; + } + + lock_sock(sk); + + switch (optname) { + case SCTP_SOCKOPT_BINDX_ADD: + /* 'optlen' is the size of the addresses buffer. */ + retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval, + optlen, SCTP_BINDX_ADD_ADDR); + break; + + case SCTP_SOCKOPT_BINDX_REM: + /* 'optlen' is the size of the addresses buffer. */ + retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval, + optlen, SCTP_BINDX_REM_ADDR); + break; + + case SCTP_SOCKOPT_CONNECTX_OLD: + /* 'optlen' is the size of the addresses buffer. */ + retval = sctp_setsockopt_connectx_old(sk, + (struct sockaddr __user *)optval, + optlen); + break; + + case SCTP_SOCKOPT_CONNECTX: + /* 'optlen' is the size of the addresses buffer. */ + retval = sctp_setsockopt_connectx(sk, + (struct sockaddr __user *)optval, + optlen); + break; + + case SCTP_DISABLE_FRAGMENTS: + retval = sctp_setsockopt_disable_fragments(sk, optval, optlen); + break; + + case SCTP_EVENTS: + retval = sctp_setsockopt_events(sk, optval, optlen); + break; + + case SCTP_AUTOCLOSE: + retval = sctp_setsockopt_autoclose(sk, optval, optlen); + break; + + case SCTP_PEER_ADDR_PARAMS: + retval = sctp_setsockopt_peer_addr_params(sk, optval, optlen); + break; + + case SCTP_DELAYED_SACK: + retval = sctp_setsockopt_delayed_ack(sk, optval, optlen); + break; + case SCTP_PARTIAL_DELIVERY_POINT: + retval = sctp_setsockopt_partial_delivery_point(sk, optval, optlen); + break; + + case SCTP_INITMSG: + retval = sctp_setsockopt_initmsg(sk, optval, optlen); + break; + case SCTP_DEFAULT_SEND_PARAM: + retval = sctp_setsockopt_default_send_param(sk, optval, + optlen); + break; + case SCTP_DEFAULT_SNDINFO: + retval = sctp_setsockopt_default_sndinfo(sk, optval, optlen); + break; + case SCTP_PRIMARY_ADDR: + retval = sctp_setsockopt_primary_addr(sk, optval, optlen); + break; + case SCTP_SET_PEER_PRIMARY_ADDR: + retval = sctp_setsockopt_peer_primary_addr(sk, optval, optlen); + break; + case SCTP_NODELAY: + retval = sctp_setsockopt_nodelay(sk, optval, optlen); + break; + case SCTP_RTOINFO: + retval = sctp_setsockopt_rtoinfo(sk, optval, optlen); + break; + case SCTP_ASSOCINFO: + retval = sctp_setsockopt_associnfo(sk, optval, optlen); + break; + case SCTP_I_WANT_MAPPED_V4_ADDR: + retval = sctp_setsockopt_mappedv4(sk, optval, optlen); + break; + case SCTP_MAXSEG: + retval = sctp_setsockopt_maxseg(sk, optval, optlen); + break; + case SCTP_ADAPTATION_LAYER: + retval = sctp_setsockopt_adaptation_layer(sk, optval, optlen); + break; + case SCTP_CONTEXT: + retval = sctp_setsockopt_context(sk, optval, optlen); + break; + case SCTP_FRAGMENT_INTERLEAVE: + retval = sctp_setsockopt_fragment_interleave(sk, optval, optlen); + break; + case SCTP_MAX_BURST: + retval = sctp_setsockopt_maxburst(sk, optval, optlen); + break; + case SCTP_AUTH_CHUNK: + retval = sctp_setsockopt_auth_chunk(sk, optval, optlen); + break; + case SCTP_HMAC_IDENT: + retval = sctp_setsockopt_hmac_ident(sk, optval, optlen); + break; + case SCTP_AUTH_KEY: + retval = sctp_setsockopt_auth_key(sk, optval, optlen); + break; + case SCTP_AUTH_ACTIVE_KEY: + retval = sctp_setsockopt_active_key(sk, optval, optlen); + break; + case SCTP_AUTH_DELETE_KEY: + retval = sctp_setsockopt_del_key(sk, optval, optlen); + break; + case SCTP_AUTO_ASCONF: + retval = sctp_setsockopt_auto_asconf(sk, optval, optlen); + break; + case SCTP_PEER_ADDR_THLDS: + retval = sctp_setsockopt_paddr_thresholds(sk, optval, optlen); + break; + case SCTP_RECVRCVINFO: + retval = sctp_setsockopt_recvrcvinfo(sk, optval, optlen); + break; + case SCTP_RECVNXTINFO: + retval = sctp_setsockopt_recvnxtinfo(sk, optval, optlen); + break; + case SCTP_PR_SUPPORTED: + retval = sctp_setsockopt_pr_supported(sk, optval, optlen); + break; + case SCTP_DEFAULT_PRINFO: + retval = sctp_setsockopt_default_prinfo(sk, optval, optlen); + break; + case SCTP_ENABLE_STREAM_RESET: + retval = sctp_setsockopt_enable_strreset(sk, optval, optlen); + break; + case SCTP_RESET_STREAMS: + retval = sctp_setsockopt_reset_streams(sk, optval, optlen); + break; + case SCTP_RESET_ASSOC: + retval = sctp_setsockopt_reset_assoc(sk, optval, optlen); + break; + case SCTP_ADD_STREAMS: + retval = sctp_setsockopt_add_streams(sk, optval, optlen); + break; + default: + retval = -ENOPROTOOPT; + break; + } + + release_sock(sk); + +out_nounlock: + return retval; +} +","@@ -4862,6 +4862,12 @@ int sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp) + if (!asoc) + return -EINVAL; + ++ /* If there is a thread waiting on more sndbuf space for ++ * sending on this asoc, it cannot be peeled. ++ */ ++ if (waitqueue_active(&asoc->wait)) ++ return -EBUSY; ++ + /* An association cannot be branched off from an already peeled-off + * socket, nor is this supported for tcp style sockets. + */ +@@ -7599,8 +7605,6 @@ static int sctp_wait_for_sndbuf(struct sctp_association *asoc, long *timeo_p, + */ + release_sock(sk); + current_timeo = schedule_timeout(current_timeo); +- if (sk != asoc->base.sk) +- goto do_error; + lock_sock(sk); + + *timeo_p = current_timeo;",1438,1769,2048 +7593,"static int check_cond_jmp_op(struct bpf_verifier_env *env, + struct bpf_insn *insn, int *insn_idx) +{ + struct bpf_verifier_state *this_branch = env->cur_state; + struct bpf_verifier_state *other_branch; + struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; + struct bpf_reg_state *dst_reg, *other_branch_regs; + u8 opcode = BPF_OP(insn->code); + int err; + + if (opcode > BPF_JSLE) { + verbose(env, ""invalid BPF_JMP opcode %x\n"", opcode); + return -EINVAL; + } + + if (BPF_SRC(insn->code) == BPF_X) { + if (insn->imm != 0) { + verbose(env, ""BPF_JMP uses reserved fields\n""); + return -EINVAL; + } + + /* check src1 operand */ + err = check_reg_arg(env, insn->src_reg, SRC_OP); + if (err) + return err; + + if (is_pointer_value(env, insn->src_reg)) { + verbose(env, ""R%d pointer comparison prohibited\n"", + insn->src_reg); + return -EACCES; + } + } else { + if (insn->src_reg != BPF_REG_0) { + verbose(env, ""BPF_JMP uses reserved fields\n""); + return -EINVAL; + } + } + + /* check src2 operand */ + err = check_reg_arg(env, insn->dst_reg, SRC_OP); + if (err) + return err; + + dst_reg = ®s[insn->dst_reg]; + + /* detect if R == 0 where R was initialized to zero earlier */ + if (BPF_SRC(insn->code) == BPF_K && + (opcode == BPF_JEQ || opcode == BPF_JNE) && + dst_reg->type == SCALAR_VALUE && + tnum_is_const(dst_reg->var_off)) { + if ((opcode == BPF_JEQ && dst_reg->var_off.value == insn->imm) || + (opcode == BPF_JNE && dst_reg->var_off.value != insn->imm)) { + /* if (imm == imm) goto pc+off; + * only follow the goto, ignore fall-through + */ + *insn_idx += insn->off; + return 0; + } else { + /* if (imm != imm) goto pc+off; + * only follow fall-through branch, since + * that's where the program will go + */ + return 0; + } + } + + other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx); + if (!other_branch) + return -EFAULT; + other_branch_regs = other_branch->frame[other_branch->curframe]->regs; + + /* detect if we are comparing against a constant value so we can adjust + * our min/max values for our dst register. + * this is only legit if both are scalars (or pointers to the same + * object, I suppose, but we don't support that right now), because + * otherwise the different base pointers mean the offsets aren't + * comparable. + */ + if (BPF_SRC(insn->code) == BPF_X) { + if (dst_reg->type == SCALAR_VALUE && + regs[insn->src_reg].type == SCALAR_VALUE) { + if (tnum_is_const(regs[insn->src_reg].var_off)) + reg_set_min_max(&other_branch_regs[insn->dst_reg], + dst_reg, regs[insn->src_reg].var_off.value, + opcode); + else if (tnum_is_const(dst_reg->var_off)) + reg_set_min_max_inv(&other_branch_regs[insn->src_reg], + ®s[insn->src_reg], + dst_reg->var_off.value, opcode); + else if (opcode == BPF_JEQ || opcode == BPF_JNE) + /* Comparing for equality, we can combine knowledge */ + reg_combine_min_max(&other_branch_regs[insn->src_reg], + &other_branch_regs[insn->dst_reg], + ®s[insn->src_reg], + ®s[insn->dst_reg], opcode); + } + } else if (dst_reg->type == SCALAR_VALUE) { + reg_set_min_max(&other_branch_regs[insn->dst_reg], + dst_reg, insn->imm, opcode); + } + + /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */ + if (BPF_SRC(insn->code) == BPF_K && + insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && + dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) { + /* Mark all identical map registers in each branch as either + * safe or unknown depending R == 0 or R != 0 conditional. + */ + mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE); + mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ); + } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], + this_branch, other_branch) && + is_pointer_value(env, insn->dst_reg)) { + verbose(env, ""R%d pointer comparison prohibited\n"", + insn->dst_reg); + return -EACCES; + } + if (env->log.level) + print_verifier_state(env, this_branch->frame[this_branch->curframe]); + return 0; +} +",0,"static int check_cond_jmp_op(struct bpf_verifier_env *env, + struct bpf_insn *insn, int *insn_idx) +{ + struct bpf_verifier_state *this_branch = env->cur_state; + struct bpf_verifier_state *other_branch; + struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; + struct bpf_reg_state *dst_reg, *other_branch_regs; + u8 opcode = BPF_OP(insn->code); + int err; + + if (opcode > BPF_JSLE) { + verbose(env, ""invalid BPF_JMP opcode %x\n"", opcode); + return -EINVAL; + } + + if (BPF_SRC(insn->code) == BPF_X) { + if (insn->imm != 0) { + verbose(env, ""BPF_JMP uses reserved fields\n""); + return -EINVAL; + } + + /* check src1 operand */ + err = check_reg_arg(env, insn->src_reg, SRC_OP); + if (err) + return err; + + if (is_pointer_value(env, insn->src_reg)) { + verbose(env, ""R%d pointer comparison prohibited\n"", + insn->src_reg); + return -EACCES; + } + } else { + if (insn->src_reg != BPF_REG_0) { + verbose(env, ""BPF_JMP uses reserved fields\n""); + return -EINVAL; + } + } + + /* check src2 operand */ + err = check_reg_arg(env, insn->dst_reg, SRC_OP); + if (err) + return err; + + dst_reg = ®s[insn->dst_reg]; + + /* detect if R == 0 where R was initialized to zero earlier */ + if (BPF_SRC(insn->code) == BPF_K && + (opcode == BPF_JEQ || opcode == BPF_JNE) && + dst_reg->type == SCALAR_VALUE && + tnum_is_const(dst_reg->var_off)) { + if ((opcode == BPF_JEQ && dst_reg->var_off.value == insn->imm) || + (opcode == BPF_JNE && dst_reg->var_off.value != insn->imm)) { + /* if (imm == imm) goto pc+off; + * only follow the goto, ignore fall-through + */ + *insn_idx += insn->off; + return 0; + } else { + /* if (imm != imm) goto pc+off; + * only follow fall-through branch, since + * that's where the program will go + */ + return 0; + } + } + + other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx); + if (!other_branch) + return -EFAULT; + other_branch_regs = other_branch->frame[other_branch->curframe]->regs; + + /* detect if we are comparing against a constant value so we can adjust + * our min/max values for our dst register. + * this is only legit if both are scalars (or pointers to the same + * object, I suppose, but we don't support that right now), because + * otherwise the different base pointers mean the offsets aren't + * comparable. + */ + if (BPF_SRC(insn->code) == BPF_X) { + if (dst_reg->type == SCALAR_VALUE && + regs[insn->src_reg].type == SCALAR_VALUE) { + if (tnum_is_const(regs[insn->src_reg].var_off)) + reg_set_min_max(&other_branch_regs[insn->dst_reg], + dst_reg, regs[insn->src_reg].var_off.value, + opcode); + else if (tnum_is_const(dst_reg->var_off)) + reg_set_min_max_inv(&other_branch_regs[insn->src_reg], + ®s[insn->src_reg], + dst_reg->var_off.value, opcode); + else if (opcode == BPF_JEQ || opcode == BPF_JNE) + /* Comparing for equality, we can combine knowledge */ + reg_combine_min_max(&other_branch_regs[insn->src_reg], + &other_branch_regs[insn->dst_reg], + ®s[insn->src_reg], + ®s[insn->dst_reg], opcode); + } + } else if (dst_reg->type == SCALAR_VALUE) { + reg_set_min_max(&other_branch_regs[insn->dst_reg], + dst_reg, insn->imm, opcode); + } + + /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */ + if (BPF_SRC(insn->code) == BPF_K && + insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && + dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) { + /* Mark all identical map registers in each branch as either + * safe or unknown depending R == 0 or R != 0 conditional. + */ + mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JNE); + mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ); + } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], + this_branch, other_branch) && + is_pointer_value(env, insn->dst_reg)) { + verbose(env, ""R%d pointer comparison prohibited\n"", + insn->dst_reg); + return -EACCES; + } + if (env->log.level) + print_verifier_state(env, this_branch->frame[this_branch->curframe]); + return 0; +} +","@@ -2896,6 +2896,15 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, + u64 umin_val, umax_val; + u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; + ++ if (insn_bitness == 32) { ++ /* Relevant for 32-bit RSH: Information can propagate towards ++ * LSB, so it isn't sufficient to only truncate the output to ++ * 32 bits. ++ */ ++ coerce_reg_to_size(dst_reg, 4); ++ coerce_reg_to_size(&src_reg, 4); ++ } ++ + smin_val = src_reg.smin_value; + smax_val = src_reg.smax_value; + umin_val = src_reg.umin_value; +@@ -3131,7 +3140,6 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, + if (BPF_CLASS(insn->code) != BPF_ALU64) { + /* 32-bit ALU ops are (32,32)->32 */ + coerce_reg_to_size(dst_reg, 4); +- coerce_reg_to_size(&src_reg, 4); + } + + __reg_deduce_bounds(dst_reg);",1205,1536,2048 +3931,"static void ath_buf_set_rate(struct ath_softc *sc, struct ath_buf *bf, + struct ath_tx_info *info, int len, bool rts) +{ + struct ath_hw *ah = sc->sc_ah; + struct sk_buff *skb; + struct ieee80211_tx_info *tx_info; + struct ieee80211_tx_rate *rates; + const struct ieee80211_rate *rate; + struct ieee80211_hdr *hdr; + struct ath_frame_info *fi = get_frame_info(bf->bf_mpdu); + u32 rts_thresh = sc->hw->wiphy->rts_threshold; + int i; + u8 rix = 0; + + skb = bf->bf_mpdu; + tx_info = IEEE80211_SKB_CB(skb); + rates = bf->rates; + hdr = (struct ieee80211_hdr *)skb->data; + + /* set dur_update_en for l-sig computation except for PS-Poll frames */ + info->dur_update = !ieee80211_is_pspoll(hdr->frame_control); + info->rtscts_rate = fi->rtscts_rate; + + for (i = 0; i < ARRAY_SIZE(bf->rates); i++) { + bool is_40, is_sgi, is_sp; + int phy; + + if (!rates[i].count || (rates[i].idx < 0)) + continue; + + rix = rates[i].idx; + info->rates[i].Tries = rates[i].count; + + /* + * Handle RTS threshold for unaggregated HT frames. + */ + if (bf_isampdu(bf) && !bf_isaggr(bf) && + (rates[i].flags & IEEE80211_TX_RC_MCS) && + unlikely(rts_thresh != (u32) -1)) { + if (!rts_thresh || (len > rts_thresh)) + rts = true; + } + + if (rts || rates[i].flags & IEEE80211_TX_RC_USE_RTS_CTS) { + info->rates[i].RateFlags |= ATH9K_RATESERIES_RTS_CTS; + info->flags |= ATH9K_TXDESC_RTSENA; + } else if (rates[i].flags & IEEE80211_TX_RC_USE_CTS_PROTECT) { + info->rates[i].RateFlags |= ATH9K_RATESERIES_RTS_CTS; + info->flags |= ATH9K_TXDESC_CTSENA; + } + + if (rates[i].flags & IEEE80211_TX_RC_40_MHZ_WIDTH) + info->rates[i].RateFlags |= ATH9K_RATESERIES_2040; + if (rates[i].flags & IEEE80211_TX_RC_SHORT_GI) + info->rates[i].RateFlags |= ATH9K_RATESERIES_HALFGI; + + is_sgi = !!(rates[i].flags & IEEE80211_TX_RC_SHORT_GI); + is_40 = !!(rates[i].flags & IEEE80211_TX_RC_40_MHZ_WIDTH); + is_sp = !!(rates[i].flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE); + + if (rates[i].flags & IEEE80211_TX_RC_MCS) { + /* MCS rates */ + info->rates[i].Rate = rix | 0x80; + info->rates[i].ChSel = ath_txchainmask_reduction(sc, + ah->txchainmask, info->rates[i].Rate); + info->rates[i].PktDuration = ath_pkt_duration(sc, rix, len, + is_40, is_sgi, is_sp); + if (rix < 8 && (tx_info->flags & IEEE80211_TX_CTL_STBC)) + info->rates[i].RateFlags |= ATH9K_RATESERIES_STBC; + continue; + } + + /* legacy rates */ + rate = &sc->sbands[tx_info->band].bitrates[rates[i].idx]; + if ((tx_info->band == IEEE80211_BAND_2GHZ) && + !(rate->flags & IEEE80211_RATE_ERP_G)) + phy = WLAN_RC_PHY_CCK; + else + phy = WLAN_RC_PHY_OFDM; + + info->rates[i].Rate = rate->hw_value; + if (rate->hw_value_short) { + if (rates[i].flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE) + info->rates[i].Rate |= rate->hw_value_short; + } else { + is_sp = false; + } + + if (bf->bf_state.bfs_paprd) + info->rates[i].ChSel = ah->txchainmask; + else + info->rates[i].ChSel = ath_txchainmask_reduction(sc, + ah->txchainmask, info->rates[i].Rate); + + info->rates[i].PktDuration = ath9k_hw_computetxtime(sc->sc_ah, + phy, rate->bitrate * 100, len, rix, is_sp); + } + + /* For AR5416 - RTS cannot be followed by a frame larger than 8K */ + if (bf_isaggr(bf) && (len > sc->sc_ah->caps.rts_aggr_limit)) + info->flags &= ~ATH9K_TXDESC_RTSENA; + + /* ATH9K_TXDESC_RTSENA and ATH9K_TXDESC_CTSENA are mutually exclusive. */ + if (info->flags & ATH9K_TXDESC_RTSENA) + info->flags &= ~ATH9K_TXDESC_CTSENA; +} +",0,"static void ath_buf_set_rate(struct ath_softc *sc, struct ath_buf *bf, + struct ath_tx_info *info, int len, bool rts) +{ + struct ath_hw *ah = sc->sc_ah; + struct sk_buff *skb; + struct ieee80211_tx_info *tx_info; + struct ieee80211_tx_rate *rates; + const struct ieee80211_rate *rate; + struct ieee80211_hdr *hdr; + struct ath_frame_info *fi = get_frame_info(bf->bf_mpdu); + u32 rts_thresh = sc->hw->wiphy->rts_threshold; + int i; + u8 rix = 0; + + skb = bf->bf_mpdu; + tx_info = IEEE80211_SKB_CB(skb); + rates = bf->rates; + hdr = (struct ieee80211_hdr *)skb->data; + + /* set dur_update_en for l-sig computation except for PS-Poll frames */ + info->dur_update = !ieee80211_is_pspoll(hdr->frame_control); + info->rtscts_rate = fi->rtscts_rate; + + for (i = 0; i < ARRAY_SIZE(bf->rates); i++) { + bool is_40, is_sgi, is_sp; + int phy; + + if (!rates[i].count || (rates[i].idx < 0)) + continue; + + rix = rates[i].idx; + info->rates[i].Tries = rates[i].count; + + /* + * Handle RTS threshold for unaggregated HT frames. + */ + if (bf_isampdu(bf) && !bf_isaggr(bf) && + (rates[i].flags & IEEE80211_TX_RC_MCS) && + unlikely(rts_thresh != (u32) -1)) { + if (!rts_thresh || (len > rts_thresh)) + rts = true; + } + + if (rts || rates[i].flags & IEEE80211_TX_RC_USE_RTS_CTS) { + info->rates[i].RateFlags |= ATH9K_RATESERIES_RTS_CTS; + info->flags |= ATH9K_TXDESC_RTSENA; + } else if (rates[i].flags & IEEE80211_TX_RC_USE_CTS_PROTECT) { + info->rates[i].RateFlags |= ATH9K_RATESERIES_RTS_CTS; + info->flags |= ATH9K_TXDESC_CTSENA; + } + + if (rates[i].flags & IEEE80211_TX_RC_40_MHZ_WIDTH) + info->rates[i].RateFlags |= ATH9K_RATESERIES_2040; + if (rates[i].flags & IEEE80211_TX_RC_SHORT_GI) + info->rates[i].RateFlags |= ATH9K_RATESERIES_HALFGI; + + is_sgi = !!(rates[i].flags & IEEE80211_TX_RC_SHORT_GI); + is_40 = !!(rates[i].flags & IEEE80211_TX_RC_40_MHZ_WIDTH); + is_sp = !!(rates[i].flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE); + + if (rates[i].flags & IEEE80211_TX_RC_MCS) { + /* MCS rates */ + info->rates[i].Rate = rix | 0x80; + info->rates[i].ChSel = ath_txchainmask_reduction(sc, + ah->txchainmask, info->rates[i].Rate); + info->rates[i].PktDuration = ath_pkt_duration(sc, rix, len, + is_40, is_sgi, is_sp); + if (rix < 8 && (tx_info->flags & IEEE80211_TX_CTL_STBC)) + info->rates[i].RateFlags |= ATH9K_RATESERIES_STBC; + continue; + } + + /* legacy rates */ + rate = &sc->sbands[tx_info->band].bitrates[rates[i].idx]; + if ((tx_info->band == IEEE80211_BAND_2GHZ) && + !(rate->flags & IEEE80211_RATE_ERP_G)) + phy = WLAN_RC_PHY_CCK; + else + phy = WLAN_RC_PHY_OFDM; + + info->rates[i].Rate = rate->hw_value; + if (rate->hw_value_short) { + if (rates[i].flags & IEEE80211_TX_RC_USE_SHORT_PREAMBLE) + info->rates[i].Rate |= rate->hw_value_short; + } else { + is_sp = false; + } + + if (bf->bf_state.bfs_paprd) + info->rates[i].ChSel = ah->txchainmask; + else + info->rates[i].ChSel = ath_txchainmask_reduction(sc, + ah->txchainmask, info->rates[i].Rate); + + info->rates[i].PktDuration = ath9k_hw_computetxtime(sc->sc_ah, + phy, rate->bitrate * 100, len, rix, is_sp); + } + + /* For AR5416 - RTS cannot be followed by a frame larger than 8K */ + if (bf_isaggr(bf) && (len > sc->sc_ah->caps.rts_aggr_limit)) + info->flags &= ~ATH9K_TXDESC_RTSENA; + + /* ATH9K_TXDESC_RTSENA and ATH9K_TXDESC_CTSENA are mutually exclusive. */ + if (info->flags & ATH9K_TXDESC_RTSENA) + info->flags &= ~ATH9K_TXDESC_CTSENA; +} +","@@ -1444,14 +1444,16 @@ void ath_tx_aggr_sleep(struct ieee80211_sta *sta, struct ath_softc *sc, + for (tidno = 0, tid = &an->tid[tidno]; + tidno < IEEE80211_NUM_TIDS; tidno++, tid++) { + +- if (!tid->sched) +- continue; +- + ac = tid->ac; + txq = ac->txq; + + ath_txq_lock(sc, txq); + ++ if (!tid->sched) { ++ ath_txq_unlock(sc, txq); ++ continue; ++ } ++ + buffered = ath_tid_has_buffered(tid); + + tid->sched = false;",1252,1583,2048 +6321,"static int dnxhd_decode_frame(AVCodecContext *avctx, void *data, + int *got_frame, AVPacket *avpkt) +{ + const uint8_t *buf = avpkt->data; + int buf_size = avpkt->size; + DNXHDContext *ctx = avctx->priv_data; + ThreadFrame frame = { .f = data }; + AVFrame *picture = data; + int first_field = 1; + int ret, i; + + ff_dlog(avctx, ""frame size %d\n"", buf_size); + + for (i = 0; i < avctx->thread_count; i++) + ctx->rows[i].format = -1; + +decode_coding_unit: + if ((ret = dnxhd_decode_header(ctx, picture, buf, buf_size, first_field)) < 0) + return ret; + + if ((avctx->width || avctx->height) && + (ctx->width != avctx->width || ctx->height != avctx->height)) { + av_log(avctx, AV_LOG_WARNING, ""frame size changed: %dx%d -> %ux%u\n"", + avctx->width, avctx->height, ctx->width, ctx->height); + first_field = 1; + } + if (avctx->pix_fmt != AV_PIX_FMT_NONE && avctx->pix_fmt != ctx->pix_fmt) { + av_log(avctx, AV_LOG_WARNING, ""pix_fmt changed: %s -> %s\n"", + av_get_pix_fmt_name(avctx->pix_fmt), av_get_pix_fmt_name(ctx->pix_fmt)); + first_field = 1; + } + + avctx->pix_fmt = ctx->pix_fmt; + ret = ff_set_dimensions(avctx, ctx->width, ctx->height); + if (ret < 0) + return ret; + + if (first_field) { + if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) + return ret; + picture->pict_type = AV_PICTURE_TYPE_I; + picture->key_frame = 1; + } + + ctx->buf_size = buf_size - ctx->data_offset; + ctx->buf = buf + ctx->data_offset; + avctx->execute2(avctx, dnxhd_decode_row, picture, NULL, ctx->mb_height); + + if (first_field && picture->interlaced_frame) { + buf += ctx->cid_table->coding_unit_size; + buf_size -= ctx->cid_table->coding_unit_size; + first_field = 0; + goto decode_coding_unit; + } + + ret = 0; + for (i = 0; i < avctx->thread_count; i++) { + ret += ctx->rows[i].errors; + ctx->rows[i].errors = 0; + } + + if (ctx->act) { + static int act_warned; + int format = ctx->rows[0].format; + for (i = 1; i < avctx->thread_count; i++) { + if (ctx->rows[i].format != format && + ctx->rows[i].format != -1 /* not run */) { + format = 2; + break; + } + } + switch (format) { + case -1: + case 2: + if (!act_warned) { + act_warned = 1; + av_log(ctx->avctx, AV_LOG_ERROR, + ""Unsupported: variable ACT flag.\n""); + } + break; + case 0: + ctx->pix_fmt = ctx->bit_depth==10 + ? AV_PIX_FMT_GBRP10 : AV_PIX_FMT_GBRP12; + break; + case 1: + ctx->pix_fmt = ctx->bit_depth==10 + ? AV_PIX_FMT_YUV444P10 : AV_PIX_FMT_YUV444P12; + break; + } + } + avctx->pix_fmt = ctx->pix_fmt; + if (ret) { + av_log(ctx->avctx, AV_LOG_ERROR, ""%d lines with errors\n"", ret); + return AVERROR_INVALIDDATA; + } + + *got_frame = 1; + return avpkt->size; +} +",0,"static int dnxhd_decode_frame(AVCodecContext *avctx, void *data, + int *got_frame, AVPacket *avpkt) +{ + const uint8_t *buf = avpkt->data; + int buf_size = avpkt->size; + DNXHDContext *ctx = avctx->priv_data; + ThreadFrame frame = { .f = data }; + AVFrame *picture = data; + int first_field = 1; + int ret, i; + + ff_dlog(avctx, ""frame size %d\n"", buf_size); + + for (i = 0; i < avctx->thread_count; i++) + ctx->rows[i].format = -1; + +decode_coding_unit: + if ((ret = dnxhd_decode_header(ctx, picture, buf, buf_size, first_field)) < 0) + return ret; + + if ((avctx->width || avctx->height) && + (ctx->width != avctx->width || ctx->height != avctx->height)) { + av_log(avctx, AV_LOG_WARNING, ""frame size changed: %dx%d -> %ux%u\n"", + avctx->width, avctx->height, ctx->width, ctx->height); + first_field = 1; + } + if (avctx->pix_fmt != AV_PIX_FMT_NONE && avctx->pix_fmt != ctx->pix_fmt) { + av_log(avctx, AV_LOG_WARNING, ""pix_fmt changed: %s -> %s\n"", + av_get_pix_fmt_name(avctx->pix_fmt), av_get_pix_fmt_name(ctx->pix_fmt)); + first_field = 1; + } + + avctx->pix_fmt = ctx->pix_fmt; + ret = ff_set_dimensions(avctx, ctx->width, ctx->height); + if (ret < 0) + return ret; + + if (first_field) { + if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0) + return ret; + picture->pict_type = AV_PICTURE_TYPE_I; + picture->key_frame = 1; + } + + ctx->buf_size = buf_size - ctx->data_offset; + ctx->buf = buf + ctx->data_offset; + avctx->execute2(avctx, dnxhd_decode_row, picture, NULL, ctx->mb_height); + + if (first_field && picture->interlaced_frame) { + buf += ctx->cid_table->coding_unit_size; + buf_size -= ctx->cid_table->coding_unit_size; + first_field = 0; + goto decode_coding_unit; + } + + ret = 0; + for (i = 0; i < avctx->thread_count; i++) { + ret += ctx->rows[i].errors; + ctx->rows[i].errors = 0; + } + + if (ctx->act) { + static int act_warned; + int format = ctx->rows[0].format; + for (i = 1; i < avctx->thread_count; i++) { + if (ctx->rows[i].format != format && + ctx->rows[i].format != -1 /* not run */) { + format = 2; + break; + } + } + switch (format) { + case -1: + case 2: + if (!act_warned) { + act_warned = 1; + av_log(ctx->avctx, AV_LOG_ERROR, + ""Unsupported: variable ACT flag.\n""); + } + break; + case 0: + ctx->pix_fmt = ctx->bit_depth==10 + ? AV_PIX_FMT_GBRP10 : AV_PIX_FMT_GBRP12; + break; + case 1: + ctx->pix_fmt = ctx->bit_depth==10 + ? AV_PIX_FMT_YUV444P10 : AV_PIX_FMT_YUV444P12; + break; + } + } + avctx->pix_fmt = ctx->pix_fmt; + if (ret) { + av_log(ctx->avctx, AV_LOG_ERROR, ""%d lines with errors\n"", ret); + return AVERROR_INVALIDDATA; + } + + *got_frame = 1; + return avpkt->size; +} +","@@ -298,14 +298,18 @@ static int dnxhd_decode_header(DNXHDContext *ctx, AVFrame *frame, + if (ctx->mb_height > 68 && ff_dnxhd_check_header_prefix_hr(header_prefix)) { + ctx->data_offset = 0x170 + (ctx->mb_height << 2); + } else { +- if (ctx->mb_height > 68 || +- (ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) { ++ if (ctx->mb_height > 68) { + av_log(ctx->avctx, AV_LOG_ERROR, + ""mb height too big: %d\n"", ctx->mb_height); + return AVERROR_INVALIDDATA; + } + ctx->data_offset = 0x280; + } ++ if ((ctx->mb_height << frame->interlaced_frame) > (ctx->height + 15) >> 4) { ++ av_log(ctx->avctx, AV_LOG_ERROR, ++ ""mb height too big: %d\n"", ctx->mb_height); ++ return AVERROR_INVALIDDATA; ++ } + + if (buf_size < ctx->data_offset) { + av_log(ctx->avctx, AV_LOG_ERROR,",903,1234,2048 +1710,"pdf_load_obj_stm(fz_context *ctx, pdf_document *doc, int num, pdf_lexbuf *buf, int target) +{ + fz_stream *stm = NULL; + pdf_obj *objstm = NULL; + int *numbuf = NULL; + int64_t *ofsbuf = NULL; + + pdf_obj *obj; + int64_t first; + int count; + int i; + pdf_token tok; + pdf_xref_entry *ret_entry = NULL; + + fz_var(numbuf); + fz_var(ofsbuf); + fz_var(objstm); + fz_var(stm); + + fz_try(ctx) + { + objstm = pdf_load_object(ctx, doc, num); + + count = pdf_to_int(ctx, pdf_dict_get(ctx, objstm, PDF_NAME_N)); + first = pdf_to_int(ctx, pdf_dict_get(ctx, objstm, PDF_NAME_First)); + + if (count < 0) + fz_throw(ctx, FZ_ERROR_GENERIC, ""negative number of objects in object stream""); + if (first < 0) + fz_throw(ctx, FZ_ERROR_GENERIC, ""first object in object stream resides outside stream""); + + numbuf = fz_calloc(ctx, count, sizeof(*numbuf)); + ofsbuf = fz_calloc(ctx, count, sizeof(*ofsbuf)); + + stm = pdf_open_stream_number(ctx, doc, num); + for (i = 0; i < count; i++) + { + tok = pdf_lex(ctx, stm, buf); + if (tok != PDF_TOK_INT) + fz_throw(ctx, FZ_ERROR_GENERIC, ""corrupt object stream (%d 0 R)"", num); + numbuf[i] = buf->i; + + tok = pdf_lex(ctx, stm, buf); + if (tok != PDF_TOK_INT) + fz_throw(ctx, FZ_ERROR_GENERIC, ""corrupt object stream (%d 0 R)"", num); + ofsbuf[i] = buf->i; + } + + fz_seek(ctx, stm, first, SEEK_SET); + + for (i = 0; i < count; i++) + { + int xref_len = pdf_xref_len(ctx, doc); + pdf_xref_entry *entry; + fz_seek(ctx, stm, first + ofsbuf[i], SEEK_SET); + + obj = pdf_parse_stm_obj(ctx, doc, stm, buf); + + if (numbuf[i] <= 0 || numbuf[i] >= xref_len) + { + pdf_drop_obj(ctx, obj); + fz_throw(ctx, FZ_ERROR_GENERIC, ""object id (%d 0 R) out of range (0..%d)"", numbuf[i], xref_len - 1); + } + + entry = pdf_get_xref_entry(ctx, doc, numbuf[i]); + + pdf_set_obj_parent(ctx, obj, numbuf[i]); + + if (entry->type == 'o' && entry->ofs == num) + { + /* If we already have an entry for this object, + * we'd like to drop it and use the new one - + * but this means that anyone currently holding + * a pointer to the old one will be left with a + * stale pointer. Instead, we drop the new one + * and trust that the old one is correct. */ + if (entry->obj) + { + if (pdf_objcmp(ctx, entry->obj, obj)) + fz_warn(ctx, ""Encountered new definition for object %d - keeping the original one"", numbuf[i]); + pdf_drop_obj(ctx, obj); + } + else + { + entry->obj = obj; + fz_drop_buffer(ctx, entry->stm_buf); + entry->stm_buf = NULL; + } + if (numbuf[i] == target) + ret_entry = entry; + } + else + { + pdf_drop_obj(ctx, obj); + } + } + } + fz_always(ctx) + { + fz_drop_stream(ctx, stm); + fz_free(ctx, ofsbuf); + fz_free(ctx, numbuf); + pdf_drop_obj(ctx, objstm); + } + fz_catch(ctx) + { + fz_rethrow(ctx); + } + return ret_entry; +} +",0,"pdf_load_obj_stm(fz_context *ctx, pdf_document *doc, int num, pdf_lexbuf *buf, int target) +{ + fz_stream *stm = NULL; + pdf_obj *objstm = NULL; + int *numbuf = NULL; + int64_t *ofsbuf = NULL; + + pdf_obj *obj; + int64_t first; + int count; + int i; + pdf_token tok; + pdf_xref_entry *ret_entry = NULL; + + fz_var(numbuf); + fz_var(ofsbuf); + fz_var(objstm); + fz_var(stm); + + fz_try(ctx) + { + objstm = pdf_load_object(ctx, doc, num); + + count = pdf_to_int(ctx, pdf_dict_get(ctx, objstm, PDF_NAME_N)); + first = pdf_to_int(ctx, pdf_dict_get(ctx, objstm, PDF_NAME_First)); + + if (count < 0) + fz_throw(ctx, FZ_ERROR_GENERIC, ""negative number of objects in object stream""); + if (first < 0) + fz_throw(ctx, FZ_ERROR_GENERIC, ""first object in object stream resides outside stream""); + + numbuf = fz_calloc(ctx, count, sizeof(*numbuf)); + ofsbuf = fz_calloc(ctx, count, sizeof(*ofsbuf)); + + stm = pdf_open_stream_number(ctx, doc, num); + for (i = 0; i < count; i++) + { + tok = pdf_lex(ctx, stm, buf); + if (tok != PDF_TOK_INT) + fz_throw(ctx, FZ_ERROR_GENERIC, ""corrupt object stream (%d 0 R)"", num); + numbuf[i] = buf->i; + + tok = pdf_lex(ctx, stm, buf); + if (tok != PDF_TOK_INT) + fz_throw(ctx, FZ_ERROR_GENERIC, ""corrupt object stream (%d 0 R)"", num); + ofsbuf[i] = buf->i; + } + + fz_seek(ctx, stm, first, SEEK_SET); + + for (i = 0; i < count; i++) + { + int xref_len = pdf_xref_len(ctx, doc); + pdf_xref_entry *entry; + fz_seek(ctx, stm, first + ofsbuf[i], SEEK_SET); + + obj = pdf_parse_stm_obj(ctx, doc, stm, buf); + + if (numbuf[i] <= 0 || numbuf[i] >= xref_len) + { + pdf_drop_obj(ctx, obj); + fz_throw(ctx, FZ_ERROR_GENERIC, ""object id (%d 0 R) out of range (0..%d)"", numbuf[i], xref_len - 1); + } + + entry = pdf_get_xref_entry(ctx, doc, numbuf[i]); + + pdf_set_obj_parent(ctx, obj, numbuf[i]); + + if (entry->type == 'o' && entry->ofs == num) + { + /* If we already have an entry for this object, + * we'd like to drop it and use the new one - + * but this means that anyone currently holding + * a pointer to the old one will be left with a + * stale pointer. Instead, we drop the new one + * and trust that the old one is correct. */ + if (entry->obj) + { + if (pdf_objcmp(ctx, entry->obj, obj)) + fz_warn(ctx, ""Encountered new definition for object %d - keeping the original one"", numbuf[i]); + pdf_drop_obj(ctx, obj); + } + else + { + entry->obj = obj; + fz_drop_buffer(ctx, entry->stm_buf); + entry->stm_buf = NULL; + } + if (numbuf[i] == target) + ret_entry = entry; + } + else + { + pdf_drop_obj(ctx, obj); + } + } + } + fz_always(ctx) + { + fz_drop_stream(ctx, stm); + fz_free(ctx, ofsbuf); + fz_free(ctx, numbuf); + pdf_drop_obj(ctx, objstm); + } + fz_catch(ctx) + { + fz_rethrow(ctx); + } + return ret_entry; +} +","@@ -868,11 +868,12 @@ pdf_read_old_xref(fz_context *ctx, pdf_document *doc, pdf_lexbuf *buf) + fz_seek(ctx, file, -(2 + (int)strlen(s)), SEEK_CUR); + } + +- if (ofs < 0) +- fz_throw(ctx, FZ_ERROR_GENERIC, ""out of range object num in xref: %d"", (int)ofs); +- if (ofs > INT64_MAX - len) +- fz_throw(ctx, FZ_ERROR_GENERIC, ""xref section object numbers too big""); +- ++ if (ofs < 0 || ofs > PDF_MAX_OBJECT_NUMBER ++ || len < 0 || len > PDF_MAX_OBJECT_NUMBER ++ || ofs + len - 1 > PDF_MAX_OBJECT_NUMBER) ++ { ++ fz_throw(ctx, FZ_ERROR_GENERIC, ""xref subsection object numbers are out of range""); ++ } + /* broken pdfs where size in trailer undershoots entries in xref sections */ + if (ofs + len > xref_len) + { +@@ -933,10 +934,8 @@ pdf_read_new_xref_section(fz_context *ctx, pdf_document *doc, fz_stream *stm, in + pdf_xref_entry *table; + int i, n; + +- if (i0 < 0 || i1 < 0 || i0 > INT_MAX - i1) +- fz_throw(ctx, FZ_ERROR_GENERIC, ""negative xref stream entry index""); +- //if (i0 + i1 > pdf_xref_len(ctx, doc)) +- // fz_throw(ctx, FZ_ERROR_GENERIC, ""xref stream has too many entries""); ++ if (i0 < 0 || i0 > PDF_MAX_OBJECT_NUMBER || i1 < 0 || i1 > PDF_MAX_OBJECT_NUMBER || i0 + i1 - 1 > PDF_MAX_OBJECT_NUMBER) ++ fz_throw(ctx, FZ_ERROR_GENERIC, ""xref subsection object numbers are out of range""); + + table = pdf_xref_find_subsection(ctx, doc, i0, i1); + for (i = i0; i < i0 + i1; i++) +@@ -2086,6 +2085,10 @@ pdf_create_object(fz_context *ctx, pdf_document *doc) + /* TODO: reuse free object slots by properly linking free object chains in the ofs field */ + pdf_xref_entry *entry; + int num = pdf_xref_len(ctx, doc); ++ ++ if (num > PDF_MAX_OBJECT_NUMBER) ++ fz_throw(ctx, FZ_ERROR_GENERIC, ""too many objects stored in pdf""); ++ + entry = pdf_get_incremental_xref_entry(ctx, doc, num); + entry->type = 'f'; + entry->ofs = -1;",917,1248,2048 +18166,"static Image *ReadMONOImage(const ImageInfo *image_info, + ExceptionInfo *exception) +{ + Image + *image; + + MagickBooleanType + status; + + register IndexPacket + *indexes; + + register PixelPacket + *q; + + register ssize_t + x; + + size_t + bit, + byte; + + ssize_t + y; + + /* + 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); + } + if (DiscardBlobBytes(image,image->offset) == MagickFalse) + ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", + image->filename); + /* + Initialize image colormap. + */ + image->depth=1; + if (AcquireImageColormap(image,2) == MagickFalse) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + if (image_info->ping != MagickFalse) + { + (void) CloseBlob(image); + return(GetFirstImageInList(image)); + } + /* + Convert bi-level image to pixel packets. + */ + 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); + bit=0; + byte=0; + for (x=0; x < (ssize_t) image->columns; x++) + { + if (bit == 0) + byte=(size_t) ReadBlobByte(image); + if (image_info->endian == LSBEndian) + SetPixelIndex(indexes+x,((byte & 0x01) != 0) ? 0x00 : 0x01) + else + SetPixelIndex(indexes+x,((byte & 0x01) != 0) ? 0x01 : 0x00) + bit++; + if (bit == 8) + bit=0; + byte>>=1; + } + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + (void) SyncImage(image); + if (EOFBlob(image) != MagickFalse) + ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", + image->filename); + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +",1,"static Image *ReadMONOImage(const ImageInfo *image_info, + ExceptionInfo *exception) +{ + Image + *image; + + MagickBooleanType + status; + + register IndexPacket + *indexes; + + register PixelPacket + *q; + + register ssize_t + x; + + size_t + bit, + byte; + + ssize_t + y; + + /* + 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); + } + if (DiscardBlobBytes(image,image->offset) == MagickFalse) + ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", + image->filename); + /* + Initialize image colormap. + */ + image->depth=1; + if (AcquireImageColormap(image,2) == MagickFalse) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + 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)); + } + /* + Convert bi-level image to pixel packets. + */ + 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); + bit=0; + byte=0; + for (x=0; x < (ssize_t) image->columns; x++) + { + if (bit == 0) + byte=(size_t) ReadBlobByte(image); + if (image_info->endian == LSBEndian) + SetPixelIndex(indexes+x,((byte & 0x01) != 0) ? 0x00 : 0x01) + else + SetPixelIndex(indexes+x,((byte & 0x01) != 0) ? 0x01 : 0x00) + bit++; + if (bit == 8) + bit=0; + byte>>=1; + } + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + (void) SyncImage(image); + if (EOFBlob(image) != MagickFalse) + ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", + image->filename); + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +","@@ -154,6 +154,12 @@ static Image *ReadMONOImage(const ImageInfo *image_info, + (void) CloseBlob(image); + return(GetFirstImageInList(image)); + } ++ status=SetImageExtent(image,image->columns,image->rows); ++ if (status == MagickFalse) ++ { ++ InheritException(exception,&image->exception); ++ return(DestroyImageList(image)); ++ } + /* + Convert bi-level image to pixel packets. + */",710,1041,2048 +6220,"char* FileDialog(BOOL save, char* path, const ext_t* ext, DWORD options) +{ + DWORD tmp; + OPENFILENAMEA ofn; + char selected_name[MAX_PATH]; + char *ext_string = NULL, *all_files = NULL; + size_t i, j, ext_strlen; + BOOL r; + char* filepath = NULL; + HRESULT hr = FALSE; + IFileDialog *pfd = NULL; + IShellItem *psiResult; + COMDLG_FILTERSPEC* filter_spec = NULL; + wchar_t *wpath = NULL, *wfilename = NULL; + IShellItem *si_path = NULL; // Automatically freed + + if ((ext == NULL) || (ext->count == 0) || (ext->extension == NULL) || (ext->description == NULL)) + return NULL; + dialog_showing++; + + if (nWindowsVersion >= WINDOWS_VISTA) { + INIT_VISTA_SHELL32; + filter_spec = (COMDLG_FILTERSPEC*)calloc(ext->count + 1, sizeof(COMDLG_FILTERSPEC)); + if ((IS_VISTA_SHELL32_AVAILABLE) && (filter_spec != NULL)) { + for (i = 0; i < ext->count; i++) { + filter_spec[i].pszSpec = utf8_to_wchar(ext->extension[i]); + filter_spec[i].pszName = utf8_to_wchar(ext->description[i]); + } + filter_spec[i].pszSpec = L""*.*""; + filter_spec[i].pszName = utf8_to_wchar(lmprintf(MSG_107)); + + hr = CoCreateInstance(save ? &CLSID_FileSaveDialog : &CLSID_FileOpenDialog, NULL, CLSCTX_INPROC, + &IID_IFileDialog, (LPVOID)&pfd); + + if (FAILED(hr)) { + SetLastError(hr); + uprintf(""CoCreateInstance for FileOpenDialog failed: %s\n"", WindowsErrorString()); + pfd = NULL; // Just in case + goto fallback; + } + + pfd->lpVtbl->SetFileTypes(pfd, (UINT)ext->count + 1, filter_spec); + + wpath = utf8_to_wchar(path); + hr = (*pfSHCreateItemFromParsingName)(wpath, NULL, &IID_IShellItem, (LPVOID)&si_path); + if (SUCCEEDED(hr)) { + pfd->lpVtbl->SetFolder(pfd, si_path); + } + safe_free(wpath); + + wfilename = utf8_to_wchar((ext->filename == NULL) ? """" : ext->filename); + if (wfilename != NULL) { + pfd->lpVtbl->SetFileName(pfd, wfilename); + } + + hr = pfd->lpVtbl->Show(pfd, hMainDialog); + + safe_free(wfilename); + for (i = 0; i < ext->count; i++) { + safe_free(filter_spec[i].pszSpec); + safe_free(filter_spec[i].pszName); + } + safe_free(filter_spec[i].pszName); + safe_free(filter_spec); + + if (SUCCEEDED(hr)) { + hr = pfd->lpVtbl->GetResult(pfd, &psiResult); + if (SUCCEEDED(hr)) { + hr = psiResult->lpVtbl->GetDisplayName(psiResult, SIGDN_FILESYSPATH, &wpath); + if (SUCCEEDED(hr)) { + filepath = wchar_to_utf8(wpath); + CoTaskMemFree(wpath); + } else { + SetLastError(hr); + uprintf(""Unable to access file path: %s\n"", WindowsErrorString()); + } + psiResult->lpVtbl->Release(psiResult); + } + } else if ((hr & 0xFFFF) != ERROR_CANCELLED) { + SetLastError(hr); + uprintf(""Could not show FileOpenDialog: %s\n"", WindowsErrorString()); + goto fallback; + } + pfd->lpVtbl->Release(pfd); + dialog_showing--; + return filepath; + } + fallback: + safe_free(filter_spec); + if (pfd != NULL) { + pfd->lpVtbl->Release(pfd); + } + } + + memset(&ofn, 0, sizeof(ofn)); + ofn.lStructSize = sizeof(ofn); + ofn.hwndOwner = hMainDialog; + static_sprintf(selected_name, ""%s"", (ext->filename == NULL)?"""":ext->filename); + ofn.lpstrFile = selected_name; + ofn.nMaxFile = MAX_PATH; + all_files = lmprintf(MSG_107); + ext_strlen = 0; + for (i=0; icount; i++) { + ext_strlen += safe_strlen(ext->description[i]) + 2*safe_strlen(ext->extension[i]) + sizeof("" ()\r\r""); + } + ext_strlen += safe_strlen(all_files) + sizeof("" (*.*)\r*.*\r""); + ext_string = (char*)malloc(ext_strlen+1); + if (ext_string == NULL) + return NULL; + ext_string[0] = 0; + for (i=0, j=0; icount; i++) { + j += _snprintf(&ext_string[j], ext_strlen-j, ""%s (%s)\r%s\r"", ext->description[i], ext->extension[i], ext->extension[i]); + } + j = _snprintf(&ext_string[j], ext_strlen-j, ""%s (*.*)\r*.*\r"", all_files); + for (i=0; icount == 0) || (ext->extension == NULL) || (ext->description == NULL)) + return NULL; + dialog_showing++; + + if (nWindowsVersion >= WINDOWS_VISTA) { + INIT_VISTA_SHELL32; + filter_spec = (COMDLG_FILTERSPEC*)calloc(ext->count + 1, sizeof(COMDLG_FILTERSPEC)); + if ((IS_VISTA_SHELL32_AVAILABLE) && (filter_spec != NULL)) { + for (i = 0; i < ext->count; i++) { + filter_spec[i].pszSpec = utf8_to_wchar(ext->extension[i]); + filter_spec[i].pszName = utf8_to_wchar(ext->description[i]); + } + filter_spec[i].pszSpec = L""*.*""; + filter_spec[i].pszName = utf8_to_wchar(lmprintf(MSG_107)); + + hr = CoCreateInstance(save ? &CLSID_FileSaveDialog : &CLSID_FileOpenDialog, NULL, CLSCTX_INPROC, + &IID_IFileDialog, (LPVOID)&pfd); + + if (FAILED(hr)) { + SetLastError(hr); + uprintf(""CoCreateInstance for FileOpenDialog failed: %s\n"", WindowsErrorString()); + pfd = NULL; // Just in case + goto fallback; + } + + pfd->lpVtbl->SetFileTypes(pfd, (UINT)ext->count + 1, filter_spec); + + wpath = utf8_to_wchar(path); + hr = (*pfSHCreateItemFromParsingName)(wpath, NULL, &IID_IShellItem, (LPVOID)&si_path); + if (SUCCEEDED(hr)) { + pfd->lpVtbl->SetFolder(pfd, si_path); + } + safe_free(wpath); + + wfilename = utf8_to_wchar((ext->filename == NULL) ? """" : ext->filename); + if (wfilename != NULL) { + pfd->lpVtbl->SetFileName(pfd, wfilename); + } + + hr = pfd->lpVtbl->Show(pfd, hMainDialog); + + safe_free(wfilename); + for (i = 0; i < ext->count; i++) { + safe_free(filter_spec[i].pszSpec); + safe_free(filter_spec[i].pszName); + } + safe_free(filter_spec[i].pszName); + safe_free(filter_spec); + + if (SUCCEEDED(hr)) { + hr = pfd->lpVtbl->GetResult(pfd, &psiResult); + if (SUCCEEDED(hr)) { + hr = psiResult->lpVtbl->GetDisplayName(psiResult, SIGDN_FILESYSPATH, &wpath); + if (SUCCEEDED(hr)) { + filepath = wchar_to_utf8(wpath); + CoTaskMemFree(wpath); + } else { + SetLastError(hr); + uprintf(""Unable to access file path: %s\n"", WindowsErrorString()); + } + psiResult->lpVtbl->Release(psiResult); + } + } else if ((hr & 0xFFFF) != ERROR_CANCELLED) { + SetLastError(hr); + uprintf(""Could not show FileOpenDialog: %s\n"", WindowsErrorString()); + goto fallback; + } + pfd->lpVtbl->Release(pfd); + dialog_showing--; + return filepath; + } + fallback: + safe_free(filter_spec); + if (pfd != NULL) { + pfd->lpVtbl->Release(pfd); + } + } + + memset(&ofn, 0, sizeof(ofn)); + ofn.lStructSize = sizeof(ofn); + ofn.hwndOwner = hMainDialog; + static_sprintf(selected_name, ""%s"", (ext->filename == NULL)?"""":ext->filename); + ofn.lpstrFile = selected_name; + ofn.nMaxFile = MAX_PATH; + all_files = lmprintf(MSG_107); + ext_strlen = 0; + for (i=0; icount; i++) { + ext_strlen += safe_strlen(ext->description[i]) + 2*safe_strlen(ext->extension[i]) + sizeof("" ()\r\r""); + } + ext_strlen += safe_strlen(all_files) + sizeof("" (*.*)\r*.*\r""); + ext_string = (char*)malloc(ext_strlen+1); + if (ext_string == NULL) + return NULL; + ext_string[0] = 0; + for (i=0, j=0; icount; i++) { + j += _snprintf(&ext_string[j], ext_strlen-j, ""%s (%s)\r%s\r"", ext->description[i], ext->extension[i], ext->extension[i]); + } + j = _snprintf(&ext_string[j], ext_strlen-j, ""%s (*.*)\r*.*\r"", all_files); + for (i=0; ips_bitstrm; + dpb_commands_t *ps_dpb_cmds = ps_dec->ps_dpb_cmds; + dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice; + WORD32 j; + UWORD8 u1_buf_mode; + struct MMCParams *ps_mmc_params; + UWORD32 *pu4_bitstrm_buf = ps_dec->ps_bitstrm->pu4_buffer; + UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; + UWORD32 u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst; + + ps_slice->u1_mmco_equalto5 = 0; + { + if(ps_dec->u1_nal_unit_type == IDR_SLICE_NAL) + { + ps_slice->u1_no_output_of_prior_pics_flag = + ih264d_get_bit_h264(ps_bitstrm); + COPYTHECONTEXT(""SH: no_output_of_prior_pics_flag"", + ps_slice->u1_no_output_of_prior_pics_flag); + ps_slice->u1_long_term_reference_flag = ih264d_get_bit_h264( + ps_bitstrm); + COPYTHECONTEXT(""SH: long_term_reference_flag"", + ps_slice->u1_long_term_reference_flag); + ps_dpb_cmds->u1_idr_pic = 1; + ps_dpb_cmds->u1_no_output_of_prior_pics_flag = + ps_slice->u1_no_output_of_prior_pics_flag; + ps_dpb_cmds->u1_long_term_reference_flag = + ps_slice->u1_long_term_reference_flag; + } + else + { + u1_buf_mode = ih264d_get_bit_h264(ps_bitstrm); //0 - sliding window; 1 - arbitrary + COPYTHECONTEXT(""SH: adaptive_ref_pic_buffering_flag"", u1_buf_mode); + ps_dpb_cmds->u1_buf_mode = u1_buf_mode; + j = 0; + + if(u1_buf_mode == 1) + { + UWORD32 u4_mmco; + UWORD32 u4_diff_pic_num; + UWORD32 u4_lt_idx, u4_max_lt_idx; + + u4_mmco = ih264d_uev(pu4_bitstrm_ofst, + + pu4_bitstrm_buf); + while(u4_mmco != END_OF_MMCO) + { + ps_mmc_params = &ps_dpb_cmds->as_mmc_params[j]; + ps_mmc_params->u4_mmco = u4_mmco; + switch(u4_mmco) + { + case MARK_ST_PICNUM_AS_NONREF: + u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst, + pu4_bitstrm_buf); + ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num; + break; + + case MARK_LT_INDEX_AS_NONREF: + u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst, + pu4_bitstrm_buf); + ps_mmc_params->u4_lt_idx = u4_lt_idx; + break; + + case MARK_ST_PICNUM_AS_LT_INDEX: + u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst, + pu4_bitstrm_buf); + ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num; + u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst, + pu4_bitstrm_buf); + ps_mmc_params->u4_lt_idx = u4_lt_idx; + break; + + case SET_MAX_LT_INDEX: + { + u4_max_lt_idx = ih264d_uev(pu4_bitstrm_ofst, + pu4_bitstrm_buf); + ps_mmc_params->u4_max_lt_idx_plus1 = u4_max_lt_idx; + break; + } + case RESET_REF_PICTURES: + { + ps_slice->u1_mmco_equalto5 = 1; + break; + } + + case SET_LT_INDEX: + u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst, + pu4_bitstrm_buf); + ps_mmc_params->u4_lt_idx = u4_lt_idx; + break; + + default: + break; + } + u4_mmco = ih264d_uev(pu4_bitstrm_ofst, + pu4_bitstrm_buf); + + j++; + } + ps_dpb_cmds->u1_num_of_commands = j; + + } + } + ps_dpb_cmds->u1_dpb_commands_read = 1; + ps_dpb_cmds->u1_dpb_commands_read_slc = 1; + + } + u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst - u4_bit_ofst; + return u4_bit_ofst; +} +",1,"WORD32 ih264d_read_mmco_commands(struct _DecStruct * ps_dec) +{ + dec_bit_stream_t *ps_bitstrm = ps_dec->ps_bitstrm; + dpb_commands_t *ps_dpb_cmds = ps_dec->ps_dpb_cmds; + dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice; + WORD32 j; + UWORD8 u1_buf_mode; + struct MMCParams *ps_mmc_params; + UWORD32 *pu4_bitstrm_buf = ps_dec->ps_bitstrm->pu4_buffer; + UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; + UWORD32 u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst; + + ps_slice->u1_mmco_equalto5 = 0; + { + if(ps_dec->u1_nal_unit_type == IDR_SLICE_NAL) + { + ps_slice->u1_no_output_of_prior_pics_flag = + ih264d_get_bit_h264(ps_bitstrm); + COPYTHECONTEXT(""SH: no_output_of_prior_pics_flag"", + ps_slice->u1_no_output_of_prior_pics_flag); + ps_slice->u1_long_term_reference_flag = ih264d_get_bit_h264( + ps_bitstrm); + COPYTHECONTEXT(""SH: long_term_reference_flag"", + ps_slice->u1_long_term_reference_flag); + ps_dpb_cmds->u1_idr_pic = 1; + ps_dpb_cmds->u1_no_output_of_prior_pics_flag = + ps_slice->u1_no_output_of_prior_pics_flag; + ps_dpb_cmds->u1_long_term_reference_flag = + ps_slice->u1_long_term_reference_flag; + } + else + { + u1_buf_mode = ih264d_get_bit_h264(ps_bitstrm); //0 - sliding window; 1 - arbitrary + COPYTHECONTEXT(""SH: adaptive_ref_pic_buffering_flag"", u1_buf_mode); + ps_dpb_cmds->u1_buf_mode = u1_buf_mode; + j = 0; + + if(u1_buf_mode == 1) + { + UWORD32 u4_mmco; + UWORD32 u4_diff_pic_num; + UWORD32 u4_lt_idx, u4_max_lt_idx; + + u4_mmco = ih264d_uev(pu4_bitstrm_ofst, + + pu4_bitstrm_buf); + while(u4_mmco != END_OF_MMCO) + { + if (j >= MAX_REF_BUFS) + { + ALOGE(""b/25818142""); + android_errorWriteLog(0x534e4554, ""25818142""); + ps_dpb_cmds->u1_num_of_commands = 0; + return -1; + } + ps_mmc_params = &ps_dpb_cmds->as_mmc_params[j]; + ps_mmc_params->u4_mmco = u4_mmco; + switch(u4_mmco) + { + case MARK_ST_PICNUM_AS_NONREF: + u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst, + pu4_bitstrm_buf); + ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num; + break; + + case MARK_LT_INDEX_AS_NONREF: + u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst, + pu4_bitstrm_buf); + ps_mmc_params->u4_lt_idx = u4_lt_idx; + break; + + case MARK_ST_PICNUM_AS_LT_INDEX: + u4_diff_pic_num = ih264d_uev(pu4_bitstrm_ofst, + pu4_bitstrm_buf); + ps_mmc_params->u4_diff_pic_num = u4_diff_pic_num; + u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst, + pu4_bitstrm_buf); + ps_mmc_params->u4_lt_idx = u4_lt_idx; + break; + + case SET_MAX_LT_INDEX: + { + u4_max_lt_idx = ih264d_uev(pu4_bitstrm_ofst, + pu4_bitstrm_buf); + ps_mmc_params->u4_max_lt_idx_plus1 = u4_max_lt_idx; + break; + } + case RESET_REF_PICTURES: + { + ps_slice->u1_mmco_equalto5 = 1; + break; + } + + case SET_LT_INDEX: + u4_lt_idx = ih264d_uev(pu4_bitstrm_ofst, + pu4_bitstrm_buf); + ps_mmc_params->u4_lt_idx = u4_lt_idx; + break; + + default: + break; + } + u4_mmco = ih264d_uev(pu4_bitstrm_ofst, + pu4_bitstrm_buf); + + j++; + } + ps_dpb_cmds->u1_num_of_commands = j; + + } + } + ps_dpb_cmds->u1_dpb_commands_read = 1; + ps_dpb_cmds->u1_dpb_commands_read_slc = 1; + + } + u4_bit_ofst = ps_dec->ps_bitstrm->u4_ofst - u4_bit_ofst; + return u4_bit_ofst; +} +","@@ -17,6 +17,9 @@ + + ***************************************************************************** + * Originally developed and contributed by Ittiam Systems Pvt. Ltd, Bangalore + */ ++#include ""log/log.h"" ++#include ++ + #include ""ih264_typedefs.h"" + #include ""ih264_macros.h"" + #include ""ih264_platform_macros.h"" +@@ -872,6 +875,13 @@ + + pu4_bitstrm_buf); + while(u4_mmco != END_OF_MMCO) + { ++ if (j >= MAX_REF_BUFS) ++ { ++ ALOGE(""b/25818142""); ++ android_errorWriteLog(0x534e4554, ""25818142""); ++ ps_dpb_cmds->u1_num_of_commands = 0; ++ return -1; ++ } + ps_mmc_params = &ps_dpb_cmds->as_mmc_params[j]; + ps_mmc_params->u4_mmco = u4_mmco; + switch(u4_mmco) +",1085,1416,2048 +640,"int ssl2_accept(SSL *s) +{ + unsigned long l = (unsigned long)time(NULL); + BUF_MEM *buf = NULL; + int ret = -1; + long num1; + void (*cb) (const SSL *ssl, int type, int val) = NULL; + int new_state, state; + + RAND_add(&l, sizeof(l), 0); + ERR_clear_error(); + clear_sys_error(); + + if (s->info_callback != NULL) + cb = s->info_callback; + else if (s->ctx->info_callback != NULL) + cb = s->ctx->info_callback; + + /* init things to blank */ + s->in_handshake++; + if (!SSL_in_init(s) || SSL_in_before(s)) + SSL_clear(s); + + if (s->cert == NULL) { + SSLerr(SSL_F_SSL2_ACCEPT, SSL_R_NO_CERTIFICATE_SET); + return (-1); + } + + clear_sys_error(); + for (;;) { + state = s->state; + + switch (s->state) { + case SSL_ST_BEFORE: + case SSL_ST_ACCEPT: + case SSL_ST_BEFORE | SSL_ST_ACCEPT: + case SSL_ST_OK | SSL_ST_ACCEPT: + + s->server = 1; + if (cb != NULL) + cb(s, SSL_CB_HANDSHAKE_START, 1); + + s->version = SSL2_VERSION; + s->type = SSL_ST_ACCEPT; + + if (s->init_buf == NULL) { + if ((buf = BUF_MEM_new()) == NULL) { + ret = -1; + goto end; + } + if (!BUF_MEM_grow + (buf, (int)SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)) { + BUF_MEM_free(buf); + ret = -1; + goto end; + } + s->init_buf = buf; + } + s->init_num = 0; + s->ctx->stats.sess_accept++; + s->handshake_func = ssl2_accept; + s->state = SSL2_ST_GET_CLIENT_HELLO_A; + BREAK; + + case SSL2_ST_GET_CLIENT_HELLO_A: + case SSL2_ST_GET_CLIENT_HELLO_B: + case SSL2_ST_GET_CLIENT_HELLO_C: + s->shutdown = 0; + ret = get_client_hello(s); + if (ret <= 0) + goto end; + s->init_num = 0; + s->state = SSL2_ST_SEND_SERVER_HELLO_A; + BREAK; + + case SSL2_ST_SEND_SERVER_HELLO_A: + case SSL2_ST_SEND_SERVER_HELLO_B: + ret = server_hello(s); + if (ret <= 0) + goto end; + s->init_num = 0; + if (!s->hit) { + s->state = SSL2_ST_GET_CLIENT_MASTER_KEY_A; + BREAK; + } else { + s->state = SSL2_ST_SERVER_START_ENCRYPTION; + BREAK; + } + case SSL2_ST_GET_CLIENT_MASTER_KEY_A: + case SSL2_ST_GET_CLIENT_MASTER_KEY_B: + ret = get_client_master_key(s); + if (ret <= 0) + goto end; + s->init_num = 0; + s->state = SSL2_ST_SERVER_START_ENCRYPTION; + BREAK; + + case SSL2_ST_SERVER_START_ENCRYPTION: + /* + * Ok we how have sent all the stuff needed to start encrypting, + * the next packet back will be encrypted. + */ + if (!ssl2_enc_init(s, 0)) { + ret = -1; + goto end; + } + s->s2->clear_text = 0; + s->state = SSL2_ST_SEND_SERVER_VERIFY_A; + BREAK; + + case SSL2_ST_SEND_SERVER_VERIFY_A: + case SSL2_ST_SEND_SERVER_VERIFY_B: + ret = server_verify(s); + if (ret <= 0) + goto end; + s->init_num = 0; + if (s->hit) { + /* + * If we are in here, we have been buffering the output, so + * we need to flush it and remove buffering from future + * traffic + */ + s->state = SSL2_ST_SEND_SERVER_VERIFY_C; + BREAK; + } else { + s->state = SSL2_ST_GET_CLIENT_FINISHED_A; + break; + } + + case SSL2_ST_SEND_SERVER_VERIFY_C: + /* get the number of bytes to write */ + num1 = BIO_ctrl(s->wbio, BIO_CTRL_INFO, 0, NULL); + if (num1 > 0) { + s->rwstate = SSL_WRITING; + num1 = BIO_flush(s->wbio); + if (num1 <= 0) { + ret = -1; + goto end; + } + s->rwstate = SSL_NOTHING; + } + + /* flushed and now remove buffering */ + s->wbio = BIO_pop(s->wbio); + + s->state = SSL2_ST_GET_CLIENT_FINISHED_A; + BREAK; + + case SSL2_ST_GET_CLIENT_FINISHED_A: + case SSL2_ST_GET_CLIENT_FINISHED_B: + ret = get_client_finished(s); + if (ret <= 0) + goto end; + s->init_num = 0; + s->state = SSL2_ST_SEND_REQUEST_CERTIFICATE_A; + BREAK; + + case SSL2_ST_SEND_REQUEST_CERTIFICATE_A: + case SSL2_ST_SEND_REQUEST_CERTIFICATE_B: + case SSL2_ST_SEND_REQUEST_CERTIFICATE_C: + case SSL2_ST_SEND_REQUEST_CERTIFICATE_D: + /* + * don't do a 'request certificate' if we don't want to, or we + * already have one, and we only want to do it once. + */ + if (!(s->verify_mode & SSL_VERIFY_PEER) || + ((s->session->peer != NULL) && + (s->verify_mode & SSL_VERIFY_CLIENT_ONCE))) { + s->state = SSL2_ST_SEND_SERVER_FINISHED_A; + break; + } else { + ret = request_certificate(s); + if (ret <= 0) + goto end; + s->init_num = 0; + s->state = SSL2_ST_SEND_SERVER_FINISHED_A; + } + BREAK; + + case SSL2_ST_SEND_SERVER_FINISHED_A: + case SSL2_ST_SEND_SERVER_FINISHED_B: + ret = server_finish(s); + if (ret <= 0) + goto end; + s->init_num = 0; + s->state = SSL_ST_OK; + break; + + case SSL_ST_OK: + BUF_MEM_free(s->init_buf); + ssl_free_wbio_buffer(s); + s->init_buf = NULL; + s->init_num = 0; + /* ERR_clear_error(); */ + + ssl_update_cache(s, SSL_SESS_CACHE_SERVER); + + s->ctx->stats.sess_accept_good++; + /* s->server=1; */ + ret = 1; + + if (cb != NULL) + cb(s, SSL_CB_HANDSHAKE_DONE, 1); + + goto end; + /* BREAK; */ + + default: + SSLerr(SSL_F_SSL2_ACCEPT, SSL_R_UNKNOWN_STATE); + ret = -1; + goto end; + /* BREAK; */ + } + + if ((cb != NULL) && (s->state != state)) { + new_state = s->state; + s->state = state; + cb(s, SSL_CB_ACCEPT_LOOP, 1); + s->state = new_state; + } + } + end: + s->in_handshake--; + if (cb != NULL) + cb(s, SSL_CB_ACCEPT_EXIT, ret); + return (ret); +} +",0,"int ssl2_accept(SSL *s) +{ + unsigned long l = (unsigned long)time(NULL); + BUF_MEM *buf = NULL; + int ret = -1; + long num1; + void (*cb) (const SSL *ssl, int type, int val) = NULL; + int new_state, state; + + RAND_add(&l, sizeof(l), 0); + ERR_clear_error(); + clear_sys_error(); + + if (s->info_callback != NULL) + cb = s->info_callback; + else if (s->ctx->info_callback != NULL) + cb = s->ctx->info_callback; + + /* init things to blank */ + s->in_handshake++; + if (!SSL_in_init(s) || SSL_in_before(s)) + SSL_clear(s); + + if (s->cert == NULL) { + SSLerr(SSL_F_SSL2_ACCEPT, SSL_R_NO_CERTIFICATE_SET); + return (-1); + } + + clear_sys_error(); + for (;;) { + state = s->state; + + switch (s->state) { + case SSL_ST_BEFORE: + case SSL_ST_ACCEPT: + case SSL_ST_BEFORE | SSL_ST_ACCEPT: + case SSL_ST_OK | SSL_ST_ACCEPT: + + s->server = 1; + if (cb != NULL) + cb(s, SSL_CB_HANDSHAKE_START, 1); + + s->version = SSL2_VERSION; + s->type = SSL_ST_ACCEPT; + + if (s->init_buf == NULL) { + if ((buf = BUF_MEM_new()) == NULL) { + ret = -1; + goto end; + } + if (!BUF_MEM_grow + (buf, (int)SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)) { + BUF_MEM_free(buf); + ret = -1; + goto end; + } + s->init_buf = buf; + } + s->init_num = 0; + s->ctx->stats.sess_accept++; + s->handshake_func = ssl2_accept; + s->state = SSL2_ST_GET_CLIENT_HELLO_A; + BREAK; + + case SSL2_ST_GET_CLIENT_HELLO_A: + case SSL2_ST_GET_CLIENT_HELLO_B: + case SSL2_ST_GET_CLIENT_HELLO_C: + s->shutdown = 0; + ret = get_client_hello(s); + if (ret <= 0) + goto end; + s->init_num = 0; + s->state = SSL2_ST_SEND_SERVER_HELLO_A; + BREAK; + + case SSL2_ST_SEND_SERVER_HELLO_A: + case SSL2_ST_SEND_SERVER_HELLO_B: + ret = server_hello(s); + if (ret <= 0) + goto end; + s->init_num = 0; + if (!s->hit) { + s->state = SSL2_ST_GET_CLIENT_MASTER_KEY_A; + BREAK; + } else { + s->state = SSL2_ST_SERVER_START_ENCRYPTION; + BREAK; + } + case SSL2_ST_GET_CLIENT_MASTER_KEY_A: + case SSL2_ST_GET_CLIENT_MASTER_KEY_B: + ret = get_client_master_key(s); + if (ret <= 0) + goto end; + s->init_num = 0; + s->state = SSL2_ST_SERVER_START_ENCRYPTION; + BREAK; + + case SSL2_ST_SERVER_START_ENCRYPTION: + /* + * Ok we how have sent all the stuff needed to start encrypting, + * the next packet back will be encrypted. + */ + if (!ssl2_enc_init(s, 0)) { + ret = -1; + goto end; + } + s->s2->clear_text = 0; + s->state = SSL2_ST_SEND_SERVER_VERIFY_A; + BREAK; + + case SSL2_ST_SEND_SERVER_VERIFY_A: + case SSL2_ST_SEND_SERVER_VERIFY_B: + ret = server_verify(s); + if (ret <= 0) + goto end; + s->init_num = 0; + if (s->hit) { + /* + * If we are in here, we have been buffering the output, so + * we need to flush it and remove buffering from future + * traffic + */ + s->state = SSL2_ST_SEND_SERVER_VERIFY_C; + BREAK; + } else { + s->state = SSL2_ST_GET_CLIENT_FINISHED_A; + break; + } + + case SSL2_ST_SEND_SERVER_VERIFY_C: + /* get the number of bytes to write */ + num1 = BIO_ctrl(s->wbio, BIO_CTRL_INFO, 0, NULL); + if (num1 > 0) { + s->rwstate = SSL_WRITING; + num1 = BIO_flush(s->wbio); + if (num1 <= 0) { + ret = -1; + goto end; + } + s->rwstate = SSL_NOTHING; + } + + /* flushed and now remove buffering */ + s->wbio = BIO_pop(s->wbio); + + s->state = SSL2_ST_GET_CLIENT_FINISHED_A; + BREAK; + + case SSL2_ST_GET_CLIENT_FINISHED_A: + case SSL2_ST_GET_CLIENT_FINISHED_B: + ret = get_client_finished(s); + if (ret <= 0) + goto end; + s->init_num = 0; + s->state = SSL2_ST_SEND_REQUEST_CERTIFICATE_A; + BREAK; + + case SSL2_ST_SEND_REQUEST_CERTIFICATE_A: + case SSL2_ST_SEND_REQUEST_CERTIFICATE_B: + case SSL2_ST_SEND_REQUEST_CERTIFICATE_C: + case SSL2_ST_SEND_REQUEST_CERTIFICATE_D: + /* + * don't do a 'request certificate' if we don't want to, or we + * already have one, and we only want to do it once. + */ + if (!(s->verify_mode & SSL_VERIFY_PEER) || + ((s->session->peer != NULL) && + (s->verify_mode & SSL_VERIFY_CLIENT_ONCE))) { + s->state = SSL2_ST_SEND_SERVER_FINISHED_A; + break; + } else { + ret = request_certificate(s); + if (ret <= 0) + goto end; + s->init_num = 0; + s->state = SSL2_ST_SEND_SERVER_FINISHED_A; + } + BREAK; + + case SSL2_ST_SEND_SERVER_FINISHED_A: + case SSL2_ST_SEND_SERVER_FINISHED_B: + ret = server_finish(s); + if (ret <= 0) + goto end; + s->init_num = 0; + s->state = SSL_ST_OK; + break; + + case SSL_ST_OK: + BUF_MEM_free(s->init_buf); + ssl_free_wbio_buffer(s); + s->init_buf = NULL; + s->init_num = 0; + /* ERR_clear_error(); */ + + ssl_update_cache(s, SSL_SESS_CACHE_SERVER); + + s->ctx->stats.sess_accept_good++; + /* s->server=1; */ + ret = 1; + + if (cb != NULL) + cb(s, SSL_CB_HANDSHAKE_DONE, 1); + + goto end; + /* BREAK; */ + + default: + SSLerr(SSL_F_SSL2_ACCEPT, SSL_R_UNKNOWN_STATE); + ret = -1; + goto end; + /* BREAK; */ + } + + if ((cb != NULL) && (s->state != state)) { + new_state = s->state; + s->state = state; + cb(s, SSL_CB_ACCEPT_LOOP, 1); + s->state = new_state; + } + } + end: + s->in_handshake--; + if (cb != NULL) + cb(s, SSL_CB_ACCEPT_EXIT, ret); + return (ret); +} +","@@ -454,11 +454,6 @@ static int get_client_master_key(SSL *s) + SSLerr(SSL_F_GET_CLIENT_MASTER_KEY, SSL_R_NO_PRIVATEKEY); + return (-1); + } +- i = ssl_rsa_private_decrypt(s->cert, s->s2->tmp.enc, +- &(p[s->s2->tmp.clear]), +- &(p[s->s2->tmp.clear]), +- (s->s2->ssl2_rollback) ? RSA_SSLV23_PADDING : +- RSA_PKCS1_PADDING); + + is_export = SSL_C_IS_EXPORT(s->session->cipher); + +@@ -475,23 +470,61 @@ static int get_client_master_key(SSL *s) + } else + ek = 5; + ++ /* ++ * The format of the CLIENT-MASTER-KEY message is ++ * 1 byte message type ++ * 3 bytes cipher ++ * 2-byte clear key length (stored in s->s2->tmp.clear) ++ * 2-byte encrypted key length (stored in s->s2->tmp.enc) ++ * 2-byte key args length (IV etc) ++ * clear key ++ * encrypted key ++ * key args ++ * ++ * If the cipher is an export cipher, then the encrypted key bytes ++ * are a fixed portion of the total key (5 or 8 bytes). The size of ++ * this portion is in |ek|. If the cipher is not an export cipher, ++ * then the entire key material is encrypted (i.e., clear key length ++ * must be zero). ++ */ ++ if ((!is_export && s->s2->tmp.clear != 0) || ++ (is_export && s->s2->tmp.clear + ek != EVP_CIPHER_key_length(c))) { ++ ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR); ++ SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_BAD_LENGTH); ++ return -1; ++ } ++ /* ++ * The encrypted blob must decrypt to the encrypted portion of the key. ++ * Decryption can't be expanding, so if we don't have enough encrypted ++ * bytes to fit the key in the buffer, stop now. ++ */ ++ if ((is_export && s->s2->tmp.enc < ek) || ++ (!is_export && s->s2->tmp.enc < EVP_CIPHER_key_length(c))) { ++ ssl2_return_error(s,SSL2_PE_UNDEFINED_ERROR); ++ SSLerr(SSL_F_GET_CLIENT_MASTER_KEY,SSL_R_LENGTH_TOO_SHORT); ++ return -1; ++ } ++ ++ i = ssl_rsa_private_decrypt(s->cert, s->s2->tmp.enc, ++ &(p[s->s2->tmp.clear]), ++ &(p[s->s2->tmp.clear]), ++ (s->s2->ssl2_rollback) ? RSA_SSLV23_PADDING : ++ RSA_PKCS1_PADDING); ++ + /* bad decrypt */ + # if 1 + /* + * If a bad decrypt, continue with protocol but with a random master + * secret (Bleichenbacher attack) + */ +- if ((i < 0) || ((!is_export && (i != EVP_CIPHER_key_length(c))) +- || (is_export && ((i != ek) +- || (s->s2->tmp.clear + +- (unsigned int)i != (unsigned int) +- EVP_CIPHER_key_length(c)))))) { ++ if ((i < 0) || ((!is_export && i != EVP_CIPHER_key_length(c)) ++ || (is_export && i != ek))) { + ERR_clear_error(); + if (is_export) + i = ek; + else + i = EVP_CIPHER_key_length(c); +- if (RAND_pseudo_bytes(p, i) <= 0) ++ if (RAND_pseudo_bytes(&p[s->s2->tmp.clear], i) <= 0) + return 0; + } + # else +@@ -513,7 +546,7 @@ static int get_client_master_key(SSL *s) + # endif + + if (is_export) +- i += s->s2->tmp.clear; ++ i = EVP_CIPHER_key_length(c); + + if (i > SSL_MAX_MASTER_KEY_LENGTH) { + ssl2_return_error(s, SSL2_PE_UNDEFINED_ERROR);",1620,1951,2048 +1264,"_gnutls_server_select_suite (gnutls_session_t session, opaque * data, + int datalen) +{ + int x, i, j; + cipher_suite_st *ciphers, cs; + int retval, err; + gnutls_pk_algorithm_t pk_algo; /* will hold the pk algorithms + * supported by the peer. + */ + + pk_algo = _gnutls_server_find_pk_algos_in_ciphersuites (data, datalen); + + x = _gnutls_supported_ciphersuites (session, &ciphers); + if (x < 0) + { /* the case x==0 is handled within the function. */ + gnutls_assert (); + return x; + } + + /* Here we remove any ciphersuite that does not conform + * the certificate requested, or to the + * authentication requested (e.g. SRP). + */ + x = _gnutls_remove_unwanted_ciphersuites (session, &ciphers, x, pk_algo); + if (x <= 0) + { + gnutls_assert (); + gnutls_free (ciphers); + if (x < 0) + return x; + else + return GNUTLS_E_UNKNOWN_CIPHER_SUITE; + } + + /* Data length should be zero mod 2 since + * every ciphersuite is 2 bytes. (this check is needed + * see below). + */ + if (datalen % 2 != 0) + { + gnutls_assert (); + return GNUTLS_E_UNEXPECTED_PACKET_LENGTH; + } +#ifdef HANDSHAKE_DEBUG + + _gnutls_handshake_log (""HSK[%x]: Requested cipher suites: \n"", session); + for (j = 0; j < datalen; j += 2) + { + memcpy (&cs.suite, &data[j], 2); + _gnutls_handshake_log (""\t%s\n"", _gnutls_cipher_suite_get_name (&cs)); + } + _gnutls_handshake_log (""HSK[%x]: Supported cipher suites: \n"", session); + for (j = 0; j < x; j++) + _gnutls_handshake_log (""\t%s\n"", + _gnutls_cipher_suite_get_name (&ciphers[j])); +#endif + memset (session->security_parameters.current_cipher_suite.suite, '\0', 2); + + retval = GNUTLS_E_UNKNOWN_CIPHER_SUITE; + + for (j = 0; j < datalen; j += 2) + { + for (i = 0; i < x; i++) + { + if (memcmp (ciphers[i].suite, &data[j], 2) == 0) + { + memcpy (&cs.suite, &data[j], 2); + + _gnutls_handshake_log + (""HSK[%x]: Selected cipher suite: %s\n"", session, + _gnutls_cipher_suite_get_name (&cs)); + memcpy (session->security_parameters.current_cipher_suite. + suite, ciphers[i].suite, 2); + retval = 0; + goto finish; + } + } + } + +finish: + gnutls_free (ciphers); + + if (retval != 0) + { + gnutls_assert (); + return retval; + } + + /* check if the credentials (username, public key etc.) are ok + */ + if (_gnutls_get_kx_cred + (session, + _gnutls_cipher_suite_get_kx_algo (&session->security_parameters. + current_cipher_suite), + &err) == NULL && err != 0) + { + gnutls_assert (); + return GNUTLS_E_INSUFFICIENT_CREDENTIALS; + } + + + /* set the mod_auth_st to the appropriate struct + * according to the KX algorithm. This is needed since all the + * handshake functions are read from there; + */ + session->internals.auth_struct = + _gnutls_kx_auth_struct (_gnutls_cipher_suite_get_kx_algo + (&session->security_parameters. + current_cipher_suite)); + if (session->internals.auth_struct == NULL) + { + + _gnutls_handshake_log + (""HSK[%x]: Cannot find the appropriate handler for the KX algorithm\n"", + session); + gnutls_assert (); + return GNUTLS_E_INTERNAL_ERROR; + } + + return 0; + +} +",0,"_gnutls_server_select_suite (gnutls_session_t session, opaque * data, + int datalen) +{ + int x, i, j; + cipher_suite_st *ciphers, cs; + int retval, err; + gnutls_pk_algorithm_t pk_algo; /* will hold the pk algorithms + * supported by the peer. + */ + + pk_algo = _gnutls_server_find_pk_algos_in_ciphersuites (data, datalen); + + x = _gnutls_supported_ciphersuites (session, &ciphers); + if (x < 0) + { /* the case x==0 is handled within the function. */ + gnutls_assert (); + return x; + } + + /* Here we remove any ciphersuite that does not conform + * the certificate requested, or to the + * authentication requested (e.g. SRP). + */ + x = _gnutls_remove_unwanted_ciphersuites (session, &ciphers, x, pk_algo); + if (x <= 0) + { + gnutls_assert (); + gnutls_free (ciphers); + if (x < 0) + return x; + else + return GNUTLS_E_UNKNOWN_CIPHER_SUITE; + } + + /* Data length should be zero mod 2 since + * every ciphersuite is 2 bytes. (this check is needed + * see below). + */ + if (datalen % 2 != 0) + { + gnutls_assert (); + return GNUTLS_E_UNEXPECTED_PACKET_LENGTH; + } +#ifdef HANDSHAKE_DEBUG + + _gnutls_handshake_log (""HSK[%x]: Requested cipher suites: \n"", session); + for (j = 0; j < datalen; j += 2) + { + memcpy (&cs.suite, &data[j], 2); + _gnutls_handshake_log (""\t%s\n"", _gnutls_cipher_suite_get_name (&cs)); + } + _gnutls_handshake_log (""HSK[%x]: Supported cipher suites: \n"", session); + for (j = 0; j < x; j++) + _gnutls_handshake_log (""\t%s\n"", + _gnutls_cipher_suite_get_name (&ciphers[j])); +#endif + memset (session->security_parameters.current_cipher_suite.suite, '\0', 2); + + retval = GNUTLS_E_UNKNOWN_CIPHER_SUITE; + + for (j = 0; j < datalen; j += 2) + { + for (i = 0; i < x; i++) + { + if (memcmp (ciphers[i].suite, &data[j], 2) == 0) + { + memcpy (&cs.suite, &data[j], 2); + + _gnutls_handshake_log + (""HSK[%x]: Selected cipher suite: %s\n"", session, + _gnutls_cipher_suite_get_name (&cs)); + memcpy (session->security_parameters.current_cipher_suite. + suite, ciphers[i].suite, 2); + retval = 0; + goto finish; + } + } + } + +finish: + gnutls_free (ciphers); + + if (retval != 0) + { + gnutls_assert (); + return retval; + } + + /* check if the credentials (username, public key etc.) are ok + */ + if (_gnutls_get_kx_cred + (session, + _gnutls_cipher_suite_get_kx_algo (&session->security_parameters. + current_cipher_suite), + &err) == NULL && err != 0) + { + gnutls_assert (); + return GNUTLS_E_INSUFFICIENT_CREDENTIALS; + } + + + /* set the mod_auth_st to the appropriate struct + * according to the KX algorithm. This is needed since all the + * handshake functions are read from there; + */ + session->internals.auth_struct = + _gnutls_kx_auth_struct (_gnutls_cipher_suite_get_kx_algo + (&session->security_parameters. + current_cipher_suite)); + if (session->internals.auth_struct == NULL) + { + + _gnutls_handshake_log + (""HSK[%x]: Cannot find the appropriate handler for the KX algorithm\n"", + session); + gnutls_assert (); + return GNUTLS_E_INTERNAL_ERROR; + } + + return 0; + +} +","@@ -1003,6 +1003,14 @@ _gnutls_recv_handshake_header (gnutls_session_t session, + + *recv_type = session->internals.handshake_header_buffer.recv_type; + ++ if (*recv_type != type) ++ { ++ gnutls_assert (); ++ _gnutls_handshake_log ++ (""HSK[%x]: Handshake type mismatch (under attack?)\n"", session); ++ return GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET; ++ } ++ + return session->internals.handshake_header_buffer.packet_length; + }",946,1277,2048 +4189,"static int ax25_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) +{ + struct sock *sk = sock->sk; + void __user *argp = (void __user *)arg; + int res = 0; + + lock_sock(sk); + switch (cmd) { + case TIOCOUTQ: { + long amount; + + amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk); + if (amount < 0) + amount = 0; + res = put_user(amount, (int __user *)argp); + break; + } + + case TIOCINQ: { + struct sk_buff *skb; + long amount = 0L; + /* These two are safe on a single CPU system as only user tasks fiddle here */ + if ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) + amount = skb->len; + res = put_user(amount, (int __user *) argp); + break; + } + + case SIOCGSTAMP: + res = sock_get_timestamp(sk, argp); + break; + + case SIOCGSTAMPNS: + res = sock_get_timestampns(sk, argp); + break; + + case SIOCAX25ADDUID: /* Add a uid to the uid/call map table */ + case SIOCAX25DELUID: /* Delete a uid from the uid/call map table */ + case SIOCAX25GETUID: { + struct sockaddr_ax25 sax25; + if (copy_from_user(&sax25, argp, sizeof(sax25))) { + res = -EFAULT; + break; + } + res = ax25_uid_ioctl(cmd, &sax25); + break; + } + + case SIOCAX25NOUID: { /* Set the default policy (default/bar) */ + long amount; + if (!capable(CAP_NET_ADMIN)) { + res = -EPERM; + break; + } + if (get_user(amount, (long __user *)argp)) { + res = -EFAULT; + break; + } + if (amount < 0 || amount > AX25_NOUID_BLOCK) { + res = -EINVAL; + break; + } + ax25_uid_policy = amount; + res = 0; + break; + } + + case SIOCADDRT: + case SIOCDELRT: + case SIOCAX25OPTRT: + if (!capable(CAP_NET_ADMIN)) { + res = -EPERM; + break; + } + res = ax25_rt_ioctl(cmd, argp); + break; + + case SIOCAX25CTLCON: + if (!capable(CAP_NET_ADMIN)) { + res = -EPERM; + break; + } + res = ax25_ctl_ioctl(cmd, argp); + break; + + case SIOCAX25GETINFO: + case SIOCAX25GETINFOOLD: { + ax25_cb *ax25 = sk_to_ax25(sk); + struct ax25_info_struct ax25_info; + + ax25_info.t1 = ax25->t1 / HZ; + ax25_info.t2 = ax25->t2 / HZ; + ax25_info.t3 = ax25->t3 / HZ; + ax25_info.idle = ax25->idle / (60 * HZ); + ax25_info.n2 = ax25->n2; + ax25_info.t1timer = ax25_display_timer(&ax25->t1timer) / HZ; + ax25_info.t2timer = ax25_display_timer(&ax25->t2timer) / HZ; + ax25_info.t3timer = ax25_display_timer(&ax25->t3timer) / HZ; + ax25_info.idletimer = ax25_display_timer(&ax25->idletimer) / (60 * HZ); + ax25_info.n2count = ax25->n2count; + ax25_info.state = ax25->state; + ax25_info.rcv_q = sk_rmem_alloc_get(sk); + ax25_info.snd_q = sk_wmem_alloc_get(sk); + ax25_info.vs = ax25->vs; + ax25_info.vr = ax25->vr; + ax25_info.va = ax25->va; + ax25_info.vs_max = ax25->vs; /* reserved */ + ax25_info.paclen = ax25->paclen; + ax25_info.window = ax25->window; + + /* old structure? */ + if (cmd == SIOCAX25GETINFOOLD) { + static int warned = 0; + if (!warned) { + printk(KERN_INFO ""%s uses old SIOCAX25GETINFO\n"", + current->comm); + warned=1; + } + + if (copy_to_user(argp, &ax25_info, sizeof(struct ax25_info_struct_deprecated))) { + res = -EFAULT; + break; + } + } else { + if (copy_to_user(argp, &ax25_info, sizeof(struct ax25_info_struct))) { + res = -EINVAL; + break; + } + } + res = 0; + break; + } + + case SIOCAX25ADDFWD: + case SIOCAX25DELFWD: { + struct ax25_fwd_struct ax25_fwd; + if (!capable(CAP_NET_ADMIN)) { + res = -EPERM; + break; + } + if (copy_from_user(&ax25_fwd, argp, sizeof(ax25_fwd))) { + res = -EFAULT; + break; + } + res = ax25_fwd_ioctl(cmd, &ax25_fwd); + break; + } + + case SIOCGIFADDR: + case SIOCSIFADDR: + case SIOCGIFDSTADDR: + case SIOCSIFDSTADDR: + case SIOCGIFBRDADDR: + case SIOCSIFBRDADDR: + case SIOCGIFNETMASK: + case SIOCSIFNETMASK: + case SIOCGIFMETRIC: + case SIOCSIFMETRIC: + res = -EINVAL; + break; + + default: + res = -ENOIOCTLCMD; + break; + } + release_sock(sk); + + return res; +} +",0,"static int ax25_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) +{ + struct sock *sk = sock->sk; + void __user *argp = (void __user *)arg; + int res = 0; + + lock_sock(sk); + switch (cmd) { + case TIOCOUTQ: { + long amount; + + amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk); + if (amount < 0) + amount = 0; + res = put_user(amount, (int __user *)argp); + break; + } + + case TIOCINQ: { + struct sk_buff *skb; + long amount = 0L; + /* These two are safe on a single CPU system as only user tasks fiddle here */ + if ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) + amount = skb->len; + res = put_user(amount, (int __user *) argp); + break; + } + + case SIOCGSTAMP: + res = sock_get_timestamp(sk, argp); + break; + + case SIOCGSTAMPNS: + res = sock_get_timestampns(sk, argp); + break; + + case SIOCAX25ADDUID: /* Add a uid to the uid/call map table */ + case SIOCAX25DELUID: /* Delete a uid from the uid/call map table */ + case SIOCAX25GETUID: { + struct sockaddr_ax25 sax25; + if (copy_from_user(&sax25, argp, sizeof(sax25))) { + res = -EFAULT; + break; + } + res = ax25_uid_ioctl(cmd, &sax25); + break; + } + + case SIOCAX25NOUID: { /* Set the default policy (default/bar) */ + long amount; + if (!capable(CAP_NET_ADMIN)) { + res = -EPERM; + break; + } + if (get_user(amount, (long __user *)argp)) { + res = -EFAULT; + break; + } + if (amount < 0 || amount > AX25_NOUID_BLOCK) { + res = -EINVAL; + break; + } + ax25_uid_policy = amount; + res = 0; + break; + } + + case SIOCADDRT: + case SIOCDELRT: + case SIOCAX25OPTRT: + if (!capable(CAP_NET_ADMIN)) { + res = -EPERM; + break; + } + res = ax25_rt_ioctl(cmd, argp); + break; + + case SIOCAX25CTLCON: + if (!capable(CAP_NET_ADMIN)) { + res = -EPERM; + break; + } + res = ax25_ctl_ioctl(cmd, argp); + break; + + case SIOCAX25GETINFO: + case SIOCAX25GETINFOOLD: { + ax25_cb *ax25 = sk_to_ax25(sk); + struct ax25_info_struct ax25_info; + + ax25_info.t1 = ax25->t1 / HZ; + ax25_info.t2 = ax25->t2 / HZ; + ax25_info.t3 = ax25->t3 / HZ; + ax25_info.idle = ax25->idle / (60 * HZ); + ax25_info.n2 = ax25->n2; + ax25_info.t1timer = ax25_display_timer(&ax25->t1timer) / HZ; + ax25_info.t2timer = ax25_display_timer(&ax25->t2timer) / HZ; + ax25_info.t3timer = ax25_display_timer(&ax25->t3timer) / HZ; + ax25_info.idletimer = ax25_display_timer(&ax25->idletimer) / (60 * HZ); + ax25_info.n2count = ax25->n2count; + ax25_info.state = ax25->state; + ax25_info.rcv_q = sk_rmem_alloc_get(sk); + ax25_info.snd_q = sk_wmem_alloc_get(sk); + ax25_info.vs = ax25->vs; + ax25_info.vr = ax25->vr; + ax25_info.va = ax25->va; + ax25_info.vs_max = ax25->vs; /* reserved */ + ax25_info.paclen = ax25->paclen; + ax25_info.window = ax25->window; + + /* old structure? */ + if (cmd == SIOCAX25GETINFOOLD) { + static int warned = 0; + if (!warned) { + printk(KERN_INFO ""%s uses old SIOCAX25GETINFO\n"", + current->comm); + warned=1; + } + + if (copy_to_user(argp, &ax25_info, sizeof(struct ax25_info_struct_deprecated))) { + res = -EFAULT; + break; + } + } else { + if (copy_to_user(argp, &ax25_info, sizeof(struct ax25_info_struct))) { + res = -EINVAL; + break; + } + } + res = 0; + break; + } + + case SIOCAX25ADDFWD: + case SIOCAX25DELFWD: { + struct ax25_fwd_struct ax25_fwd; + if (!capable(CAP_NET_ADMIN)) { + res = -EPERM; + break; + } + if (copy_from_user(&ax25_fwd, argp, sizeof(ax25_fwd))) { + res = -EFAULT; + break; + } + res = ax25_fwd_ioctl(cmd, &ax25_fwd); + break; + } + + case SIOCGIFADDR: + case SIOCSIFADDR: + case SIOCGIFDSTADDR: + case SIOCSIFDSTADDR: + case SIOCGIFBRDADDR: + case SIOCSIFBRDADDR: + case SIOCGIFNETMASK: + case SIOCSIFNETMASK: + case SIOCGIFMETRIC: + case SIOCSIFMETRIC: + res = -EINVAL; + break; + + default: + res = -ENOIOCTLCMD; + break; + } + release_sock(sk); + + return res; +} +","@@ -805,6 +805,9 @@ static int ax25_create(struct net *net, struct socket *sock, int protocol, + struct sock *sk; + ax25_cb *ax25; + ++ if (protocol < 0 || protocol > SK_PROTOCOL_MAX) ++ return -EINVAL; ++ + if (!net_eq(net, &init_net)) + return -EAFNOSUPPORT; + ",1426,1757,2048 +18783,"status_t BnGraphicBufferProducer::onTransact( + uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) +{ + switch(code) { + case REQUEST_BUFFER: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + int bufferIdx = data.readInt32(); + sp buffer; + int result = requestBuffer(bufferIdx, &buffer); + reply->writeInt32(buffer != 0); + if (buffer != 0) { + reply->write(*buffer); + } + reply->writeInt32(result); + return NO_ERROR; + } + case SET_BUFFER_COUNT: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + int bufferCount = data.readInt32(); + int result = setBufferCount(bufferCount); + reply->writeInt32(result); + return NO_ERROR; + } + case DEQUEUE_BUFFER: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + bool async = static_cast(data.readInt32()); + uint32_t width = data.readUint32(); + uint32_t height = data.readUint32(); + PixelFormat format = static_cast(data.readInt32()); + uint32_t usage = data.readUint32(); + int buf = 0; + sp fence; + int result = dequeueBuffer(&buf, &fence, async, width, height, + format, usage); + reply->writeInt32(buf); + reply->writeInt32(fence != NULL); + if (fence != NULL) { + reply->write(*fence); + } + reply->writeInt32(result); + return NO_ERROR; + } + case DETACH_BUFFER: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + int slot = data.readInt32(); + int result = detachBuffer(slot); + reply->writeInt32(result); + return NO_ERROR; + } + case DETACH_NEXT_BUFFER: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + sp buffer; + sp fence; + int32_t result = detachNextBuffer(&buffer, &fence); + reply->writeInt32(result); + if (result == NO_ERROR) { + reply->writeInt32(buffer != NULL); + if (buffer != NULL) { + reply->write(*buffer); + } + reply->writeInt32(fence != NULL); + if (fence != NULL) { + reply->write(*fence); + } + } + return NO_ERROR; + } + case ATTACH_BUFFER: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + sp buffer = new GraphicBuffer(); + data.read(*buffer.get()); + int slot = 0; + int result = attachBuffer(&slot, buffer); + reply->writeInt32(slot); + reply->writeInt32(result); + return NO_ERROR; + } + case QUEUE_BUFFER: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + int buf = data.readInt32(); + QueueBufferInput input(data); + QueueBufferOutput* const output = + reinterpret_cast( + reply->writeInplace(sizeof(QueueBufferOutput))); + memset(output, 0, sizeof(QueueBufferOutput)); + status_t result = queueBuffer(buf, input, output); + reply->writeInt32(result); + return NO_ERROR; + } + case CANCEL_BUFFER: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + int buf = data.readInt32(); + sp fence = new Fence(); + data.read(*fence.get()); + cancelBuffer(buf, fence); + return NO_ERROR; + } + case QUERY: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + int value = 0; + int what = data.readInt32(); + int res = query(what, &value); + reply->writeInt32(value); + reply->writeInt32(res); + return NO_ERROR; + } + case CONNECT: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + sp listener; + if (data.readInt32() == 1) { + listener = IProducerListener::asInterface(data.readStrongBinder()); + } + int api = data.readInt32(); + bool producerControlledByApp = data.readInt32(); + + QueueBufferOutput* const output = + reinterpret_cast( + reply->writeInplace(sizeof(QueueBufferOutput))); + status_t res = connect(listener, api, producerControlledByApp, output); + reply->writeInt32(res); + return NO_ERROR; + } + case DISCONNECT: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + int api = data.readInt32(); + status_t res = disconnect(api); + reply->writeInt32(res); + return NO_ERROR; + } + case SET_SIDEBAND_STREAM: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + sp stream; + if (data.readInt32()) { + stream = NativeHandle::create(data.readNativeHandle(), true); + } + status_t result = setSidebandStream(stream); + reply->writeInt32(result); + return NO_ERROR; + } + case ALLOCATE_BUFFERS: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + bool async = static_cast(data.readInt32()); + uint32_t width = data.readUint32(); + uint32_t height = data.readUint32(); + PixelFormat format = static_cast(data.readInt32()); + uint32_t usage = data.readUint32(); + allocateBuffers(async, width, height, format, usage); + return NO_ERROR; + } + case ALLOW_ALLOCATION: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + bool allow = static_cast(data.readInt32()); + status_t result = allowAllocation(allow); + reply->writeInt32(result); + return NO_ERROR; + } + case SET_GENERATION_NUMBER: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + uint32_t generationNumber = data.readUint32(); + status_t result = setGenerationNumber(generationNumber); + reply->writeInt32(result); + return NO_ERROR; + } + case GET_CONSUMER_NAME: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + reply->writeString8(getConsumerName()); + return NO_ERROR; + } + } + return BBinder::onTransact(code, data, reply, flags); +} +",1,"status_t BnGraphicBufferProducer::onTransact( + uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) +{ + switch(code) { + case REQUEST_BUFFER: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + int bufferIdx = data.readInt32(); + sp buffer; + int result = requestBuffer(bufferIdx, &buffer); + reply->writeInt32(buffer != 0); + if (buffer != 0) { + reply->write(*buffer); + } + reply->writeInt32(result); + return NO_ERROR; + } + case SET_BUFFER_COUNT: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + int bufferCount = data.readInt32(); + int result = setBufferCount(bufferCount); + reply->writeInt32(result); + return NO_ERROR; + } + case DEQUEUE_BUFFER: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + bool async = static_cast(data.readInt32()); + uint32_t width = data.readUint32(); + uint32_t height = data.readUint32(); + PixelFormat format = static_cast(data.readInt32()); + uint32_t usage = data.readUint32(); + int buf = 0; + sp fence; + int result = dequeueBuffer(&buf, &fence, async, width, height, + format, usage); + reply->writeInt32(buf); + reply->writeInt32(fence != NULL); + if (fence != NULL) { + reply->write(*fence); + } + reply->writeInt32(result); + return NO_ERROR; + } + case DETACH_BUFFER: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + int slot = data.readInt32(); + int result = detachBuffer(slot); + reply->writeInt32(result); + return NO_ERROR; + } + case DETACH_NEXT_BUFFER: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + sp buffer; + sp fence; + int32_t result = detachNextBuffer(&buffer, &fence); + reply->writeInt32(result); + if (result == NO_ERROR) { + reply->writeInt32(buffer != NULL); + if (buffer != NULL) { + reply->write(*buffer); + } + reply->writeInt32(fence != NULL); + if (fence != NULL) { + reply->write(*fence); + } + } + return NO_ERROR; + } + case ATTACH_BUFFER: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + sp buffer = new GraphicBuffer(); + data.read(*buffer.get()); + int slot = 0; + int result = attachBuffer(&slot, buffer); + reply->writeInt32(slot); + reply->writeInt32(result); + return NO_ERROR; + } + case QUEUE_BUFFER: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + int buf = data.readInt32(); + QueueBufferInput input(data); + QueueBufferOutput* const output = + reinterpret_cast( + reply->writeInplace(sizeof(QueueBufferOutput))); + memset(output, 0, sizeof(QueueBufferOutput)); + status_t result = queueBuffer(buf, input, output); + reply->writeInt32(result); + return NO_ERROR; + } + case CANCEL_BUFFER: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + int buf = data.readInt32(); + sp fence = new Fence(); + data.read(*fence.get()); + cancelBuffer(buf, fence); + return NO_ERROR; + } + case QUERY: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + int value = 0; + int what = data.readInt32(); + int res = query(what, &value); + reply->writeInt32(value); + reply->writeInt32(res); + return NO_ERROR; + } + case CONNECT: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + sp listener; + if (data.readInt32() == 1) { + listener = IProducerListener::asInterface(data.readStrongBinder()); + } + int api = data.readInt32(); + bool producerControlledByApp = data.readInt32(); + + QueueBufferOutput* const output = + reinterpret_cast( + reply->writeInplace(sizeof(QueueBufferOutput))); + memset(output, 0, sizeof(QueueBufferOutput)); + status_t res = connect(listener, api, producerControlledByApp, output); + reply->writeInt32(res); + return NO_ERROR; + } + case DISCONNECT: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + int api = data.readInt32(); + status_t res = disconnect(api); + reply->writeInt32(res); + return NO_ERROR; + } + case SET_SIDEBAND_STREAM: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + sp stream; + if (data.readInt32()) { + stream = NativeHandle::create(data.readNativeHandle(), true); + } + status_t result = setSidebandStream(stream); + reply->writeInt32(result); + return NO_ERROR; + } + case ALLOCATE_BUFFERS: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + bool async = static_cast(data.readInt32()); + uint32_t width = data.readUint32(); + uint32_t height = data.readUint32(); + PixelFormat format = static_cast(data.readInt32()); + uint32_t usage = data.readUint32(); + allocateBuffers(async, width, height, format, usage); + return NO_ERROR; + } + case ALLOW_ALLOCATION: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + bool allow = static_cast(data.readInt32()); + status_t result = allowAllocation(allow); + reply->writeInt32(result); + return NO_ERROR; + } + case SET_GENERATION_NUMBER: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + uint32_t generationNumber = data.readUint32(); + status_t result = setGenerationNumber(generationNumber); + reply->writeInt32(result); + return NO_ERROR; + } + case GET_CONSUMER_NAME: { + CHECK_INTERFACE(IGraphicBufferProducer, data, reply); + reply->writeString8(getConsumerName()); + return NO_ERROR; + } + } + return BBinder::onTransact(code, data, reply, flags); +} +","@@ -435,6 +435,7 @@ + + QueueBufferOutput* const output = + reinterpret_cast( + reply->writeInplace(sizeof(QueueBufferOutput))); ++ memset(output, 0, sizeof(QueueBufferOutput)); + status_t res = connect(listener, api, producerControlledByApp, output); + reply->writeInt32(res); + return NO_ERROR; +",1343,1674,2048 +18096,"isis_print_is_reach_subtlv(netdissect_options *ndo, + const uint8_t *tptr, u_int subt, u_int subl, + const char *ident) +{ + u_int te_class,priority_level,gmpls_switch_cap; + union { /* int to float conversion buffer for several subTLVs */ + float f; + uint32_t i; + } bw; + + /* first lets see if we know the subTLVs name*/ + ND_PRINT((ndo, ""%s%s subTLV #%u, length: %u"", + ident, tok2str(isis_ext_is_reach_subtlv_values, ""unknown"", subt), + subt, subl)); + + ND_TCHECK2(*tptr, subl); + + switch(subt) { + case ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP: + case ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID: + case ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID: + if (subl >= 4) { + ND_PRINT((ndo, "", 0x%08x"", EXTRACT_32BITS(tptr))); + if (subl == 8) /* rfc4205 */ + ND_PRINT((ndo, "", 0x%08x"", EXTRACT_32BITS(tptr+4))); + } + break; + case ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR: + case ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR: + if (subl >= sizeof(struct in_addr)) + ND_PRINT((ndo, "", %s"", ipaddr_string(ndo, tptr))); + break; + case ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW : + case ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW: + if (subl >= 4) { + bw.i = EXTRACT_32BITS(tptr); + ND_PRINT((ndo, "", %.3f Mbps"", bw.f * 8 / 1000000)); + } + break; + case ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW : + if (subl >= 32) { + for (te_class = 0; te_class < 8; te_class++) { + bw.i = EXTRACT_32BITS(tptr); + ND_PRINT((ndo, ""%s TE-Class %u: %.3f Mbps"", + ident, + te_class, + bw.f * 8 / 1000000)); + tptr+=4; + } + } + break; + case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */ + case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD: + ND_PRINT((ndo, ""%sBandwidth Constraints Model ID: %s (%u)"", + ident, + tok2str(diffserv_te_bc_values, ""unknown"", *tptr), + *tptr)); + tptr++; + /* decode BCs until the subTLV ends */ + for (te_class = 0; te_class < (subl-1)/4; te_class++) { + ND_TCHECK2(*tptr, 4); + bw.i = EXTRACT_32BITS(tptr); + ND_PRINT((ndo, ""%s Bandwidth constraint CT%u: %.3f Mbps"", + ident, + te_class, + bw.f * 8 / 1000000)); + tptr+=4; + } + break; + case ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC: + if (subl >= 3) + ND_PRINT((ndo, "", %u"", EXTRACT_24BITS(tptr))); + break; + case ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE: + if (subl == 2) { + ND_PRINT((ndo, "", [ %s ] (0x%04x)"", + bittok2str(isis_subtlv_link_attribute_values, + ""Unknown"", + EXTRACT_16BITS(tptr)), + EXTRACT_16BITS(tptr))); + } + break; + case ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE: + if (subl >= 2) { + ND_PRINT((ndo, "", %s, Priority %u"", + bittok2str(gmpls_link_prot_values, ""none"", *tptr), + *(tptr+1))); + } + break; + case ISIS_SUBTLV_SPB_METRIC: + if (subl >= 6) { + ND_PRINT((ndo, "", LM: %u"", EXTRACT_24BITS(tptr))); + tptr=tptr+3; + ND_PRINT((ndo, "", P: %u"", *(tptr))); + tptr++; + ND_PRINT((ndo, "", P-ID: %u"", EXTRACT_16BITS(tptr))); + } + break; + case ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR: + if (subl >= 36) { + gmpls_switch_cap = *tptr; + ND_PRINT((ndo, ""%s Interface Switching Capability:%s"", + ident, + tok2str(gmpls_switch_cap_values, ""Unknown"", gmpls_switch_cap))); + ND_PRINT((ndo, "", LSP Encoding: %s"", + tok2str(gmpls_encoding_values, ""Unknown"", *(tptr + 1)))); + tptr+=4; + ND_PRINT((ndo, ""%s Max LSP Bandwidth:"", ident)); + for (priority_level = 0; priority_level < 8; priority_level++) { + bw.i = EXTRACT_32BITS(tptr); + ND_PRINT((ndo, ""%s priority level %d: %.3f Mbps"", + ident, + priority_level, + bw.f * 8 / 1000000)); + tptr+=4; + } + subl-=36; + switch (gmpls_switch_cap) { + case GMPLS_PSC1: + case GMPLS_PSC2: + case GMPLS_PSC3: + case GMPLS_PSC4: + ND_TCHECK2(*tptr, 6); + bw.i = EXTRACT_32BITS(tptr); + ND_PRINT((ndo, ""%s Min LSP Bandwidth: %.3f Mbps"", ident, bw.f * 8 / 1000000)); + ND_PRINT((ndo, ""%s Interface MTU: %u"", ident, EXTRACT_16BITS(tptr + 4))); + break; + case GMPLS_TSC: + ND_TCHECK2(*tptr, 8); + bw.i = EXTRACT_32BITS(tptr); + ND_PRINT((ndo, ""%s Min LSP Bandwidth: %.3f Mbps"", ident, bw.f * 8 / 1000000)); + ND_PRINT((ndo, ""%s Indication %s"", ident, + tok2str(gmpls_switch_cap_tsc_indication_values, ""Unknown (%u)"", *(tptr + 4)))); + break; + default: + /* there is some optional stuff left to decode but this is as of yet + not specified so just lets hexdump what is left */ + if(subl>0){ + if (!print_unknown_data(ndo, tptr, ""\n\t\t "", subl)) + return(0); + } + } + } + break; + default: + if (!print_unknown_data(ndo, tptr, ""\n\t\t "", subl)) + return(0); + break; + } + return(1); + +trunc: + return(0); +} +",1,"isis_print_is_reach_subtlv(netdissect_options *ndo, + const uint8_t *tptr, u_int subt, u_int subl, + const char *ident) +{ + u_int te_class,priority_level,gmpls_switch_cap; + union { /* int to float conversion buffer for several subTLVs */ + float f; + uint32_t i; + } bw; + + /* first lets see if we know the subTLVs name*/ + ND_PRINT((ndo, ""%s%s subTLV #%u, length: %u"", + ident, tok2str(isis_ext_is_reach_subtlv_values, ""unknown"", subt), + subt, subl)); + + ND_TCHECK2(*tptr, subl); + + switch(subt) { + case ISIS_SUBTLV_EXT_IS_REACH_ADMIN_GROUP: + case ISIS_SUBTLV_EXT_IS_REACH_LINK_LOCAL_REMOTE_ID: + case ISIS_SUBTLV_EXT_IS_REACH_LINK_REMOTE_ID: + if (subl >= 4) { + ND_PRINT((ndo, "", 0x%08x"", EXTRACT_32BITS(tptr))); + if (subl == 8) /* rfc4205 */ + ND_PRINT((ndo, "", 0x%08x"", EXTRACT_32BITS(tptr+4))); + } + break; + case ISIS_SUBTLV_EXT_IS_REACH_IPV4_INTF_ADDR: + case ISIS_SUBTLV_EXT_IS_REACH_IPV4_NEIGHBOR_ADDR: + if (subl >= sizeof(struct in_addr)) + ND_PRINT((ndo, "", %s"", ipaddr_string(ndo, tptr))); + break; + case ISIS_SUBTLV_EXT_IS_REACH_MAX_LINK_BW : + case ISIS_SUBTLV_EXT_IS_REACH_RESERVABLE_BW: + if (subl >= 4) { + bw.i = EXTRACT_32BITS(tptr); + ND_PRINT((ndo, "", %.3f Mbps"", bw.f * 8 / 1000000)); + } + break; + case ISIS_SUBTLV_EXT_IS_REACH_UNRESERVED_BW : + if (subl >= 32) { + for (te_class = 0; te_class < 8; te_class++) { + bw.i = EXTRACT_32BITS(tptr); + ND_PRINT((ndo, ""%s TE-Class %u: %.3f Mbps"", + ident, + te_class, + bw.f * 8 / 1000000)); + tptr+=4; + } + } + break; + case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */ + case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD: + if (subl == 0) + break; + ND_PRINT((ndo, ""%sBandwidth Constraints Model ID: %s (%u)"", + ident, + tok2str(diffserv_te_bc_values, ""unknown"", *tptr), + *tptr)); + tptr++; + /* decode BCs until the subTLV ends */ + for (te_class = 0; te_class < (subl-1)/4; te_class++) { + bw.i = EXTRACT_32BITS(tptr); + ND_PRINT((ndo, ""%s Bandwidth constraint CT%u: %.3f Mbps"", + ident, + te_class, + bw.f * 8 / 1000000)); + tptr+=4; + } + break; + case ISIS_SUBTLV_EXT_IS_REACH_TE_METRIC: + if (subl >= 3) + ND_PRINT((ndo, "", %u"", EXTRACT_24BITS(tptr))); + break; + case ISIS_SUBTLV_EXT_IS_REACH_LINK_ATTRIBUTE: + if (subl == 2) { + ND_PRINT((ndo, "", [ %s ] (0x%04x)"", + bittok2str(isis_subtlv_link_attribute_values, + ""Unknown"", + EXTRACT_16BITS(tptr)), + EXTRACT_16BITS(tptr))); + } + break; + case ISIS_SUBTLV_EXT_IS_REACH_LINK_PROTECTION_TYPE: + if (subl >= 2) { + ND_PRINT((ndo, "", %s, Priority %u"", + bittok2str(gmpls_link_prot_values, ""none"", *tptr), + *(tptr+1))); + } + break; + case ISIS_SUBTLV_SPB_METRIC: + if (subl >= 6) { + ND_PRINT((ndo, "", LM: %u"", EXTRACT_24BITS(tptr))); + tptr=tptr+3; + ND_PRINT((ndo, "", P: %u"", *(tptr))); + tptr++; + ND_PRINT((ndo, "", P-ID: %u"", EXTRACT_16BITS(tptr))); + } + break; + case ISIS_SUBTLV_EXT_IS_REACH_INTF_SW_CAP_DESCR: + if (subl >= 36) { + gmpls_switch_cap = *tptr; + ND_PRINT((ndo, ""%s Interface Switching Capability:%s"", + ident, + tok2str(gmpls_switch_cap_values, ""Unknown"", gmpls_switch_cap))); + ND_PRINT((ndo, "", LSP Encoding: %s"", + tok2str(gmpls_encoding_values, ""Unknown"", *(tptr + 1)))); + tptr+=4; + ND_PRINT((ndo, ""%s Max LSP Bandwidth:"", ident)); + for (priority_level = 0; priority_level < 8; priority_level++) { + bw.i = EXTRACT_32BITS(tptr); + ND_PRINT((ndo, ""%s priority level %d: %.3f Mbps"", + ident, + priority_level, + bw.f * 8 / 1000000)); + tptr+=4; + } + subl-=36; + switch (gmpls_switch_cap) { + case GMPLS_PSC1: + case GMPLS_PSC2: + case GMPLS_PSC3: + case GMPLS_PSC4: + ND_TCHECK2(*tptr, 6); + bw.i = EXTRACT_32BITS(tptr); + ND_PRINT((ndo, ""%s Min LSP Bandwidth: %.3f Mbps"", ident, bw.f * 8 / 1000000)); + ND_PRINT((ndo, ""%s Interface MTU: %u"", ident, EXTRACT_16BITS(tptr + 4))); + break; + case GMPLS_TSC: + ND_TCHECK2(*tptr, 8); + bw.i = EXTRACT_32BITS(tptr); + ND_PRINT((ndo, ""%s Min LSP Bandwidth: %.3f Mbps"", ident, bw.f * 8 / 1000000)); + ND_PRINT((ndo, ""%s Indication %s"", ident, + tok2str(gmpls_switch_cap_tsc_indication_values, ""Unknown (%u)"", *(tptr + 4)))); + break; + default: + /* there is some optional stuff left to decode but this is as of yet + not specified so just lets hexdump what is left */ + if(subl>0){ + if (!print_unknown_data(ndo, tptr, ""\n\t\t "", subl)) + return(0); + } + } + } + break; + default: + if (!print_unknown_data(ndo, tptr, ""\n\t\t "", subl)) + return(0); + break; + } + return(1); + +trunc: + return(0); +} +","@@ -1861,14 +1861,15 @@ isis_print_is_reach_subtlv(netdissect_options *ndo, + break; + case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS: /* fall through */ + case ISIS_SUBTLV_EXT_IS_REACH_BW_CONSTRAINTS_OLD: ++ if (subl == 0) ++ break; + ND_PRINT((ndo, ""%sBandwidth Constraints Model ID: %s (%u)"", + ident, + tok2str(diffserv_te_bc_values, ""unknown"", *tptr), + *tptr)); + tptr++; + /* decode BCs until the subTLV ends */ + for (te_class = 0; te_class < (subl-1)/4; te_class++) { +- ND_TCHECK2(*tptr, 4); + bw.i = EXTRACT_32BITS(tptr); + ND_PRINT((ndo, ""%s Bandwidth constraint CT%u: %.3f Mbps"", + ident,",1656,1987,2048 +18006,"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; +} +",1,"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) { + /* check validity, server sends exactly 16 bytes */ + if (cpkt.length != 16) { + fprintf(stderr, _(""Invalid salt length: %d (instead of 16) received from server %s\n""), cpkt.length, ether_ntoa((struct ether_addr *)dstmac)); + } + memcpy(pass_salt, cpkt.data, 16); + 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; +} +","@@ -96,7 +96,7 @@ static char autologin_path[255]; + + static int keepalive_counter = 0; + +-static unsigned char pass_salt[17]; ++static unsigned char pass_salt[16]; + 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]; +@@ -212,23 +212,26 @@ static void send_auth(char *username, char *password) { + char *terminal = getenv(""TERM""); + char md5data[100]; + unsigned char md5sum[17]; +- int plen; ++ int plen, act_pass_len; + md5_state_t state; + + #if defined(__linux__) && defined(_POSIX_MEMLOCK_RANGE) + mlock(md5data, sizeof(md5data)); + mlock(md5sum, sizeof(md5data)); + #endif + ++ /* calculate the actual password's length */ ++ act_pass_len = strnlen(password, 82); ++ + /* 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); ++ memcpy(md5data + 1, password, act_pass_len); ++ /* in case that password is long, calculate only using the used-up parts */ ++ memcpy(md5data + 1 + act_pass_len, 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_append(&state, (const md5_byte_t *)md5data, 1 + act_pass_len + 16); + md5_finish(&state, (md5_byte_t *)md5sum + 1); + md5sum[0] = 0; + +@@ -312,7 +315,11 @@ static int handle_packet(unsigned char *data, int data_len) { + + /* If we receive pass_salt, transmit auth data back */ + if (cpkt.cptype == MT_CPTYPE_PASSSALT) { +- memcpy(pass_salt, cpkt.data, cpkt.length); ++ /* check validity, server sends exactly 16 bytes */ ++ if (cpkt.length != 16) { ++ fprintf(stderr, _(""Invalid salt length: %d (instead of 16) received from server %s\n""), cpkt.length, ether_ntoa((struct ether_addr *)dstmac)); ++ } ++ memcpy(pass_salt, cpkt.data, 16); + send_auth(username, password); + } + ",833,1164,2048 +2481,"static int airo_set_encodeext(struct net_device *dev, + struct iw_request_info *info, + union iwreq_data *wrqu, + char *extra) +{ + struct airo_info *local = dev->ml_priv; + struct iw_point *encoding = &wrqu->encoding; + struct iw_encode_ext *ext = (struct iw_encode_ext *)extra; + int perm = ( encoding->flags & IW_ENCODE_TEMP ? 0 : 1 ); + __le16 currentAuthType = local->config.authType; + int idx, key_len, alg = ext->alg, set_key = 1, rc; + wep_key_t key; + + if (!local->wep_capable) + return -EOPNOTSUPP; + + readConfigRid(local, 1); + + /* Determine and validate the key index */ + idx = encoding->flags & IW_ENCODE_INDEX; + if (idx) { + if (!valid_index(local, idx - 1)) + return -EINVAL; + idx--; + } else { + idx = get_wep_tx_idx(local); + if (idx < 0) + idx = 0; + } + + if (encoding->flags & IW_ENCODE_DISABLED) + alg = IW_ENCODE_ALG_NONE; + + if (ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY) { + /* Only set transmit key index here, actual + * key is set below if needed. + */ + rc = set_wep_tx_idx(local, idx, perm, 1); + if (rc < 0) { + airo_print_err(local->dev->name, ""failed to set "" + ""WEP transmit index to %d: %d."", + idx, rc); + return rc; + } + set_key = ext->key_len > 0 ? 1 : 0; + } + + if (set_key) { + /* Set the requested key first */ + memset(key.key, 0, MAX_KEY_SIZE); + switch (alg) { + case IW_ENCODE_ALG_NONE: + key.len = 0; + break; + case IW_ENCODE_ALG_WEP: + if (ext->key_len > MIN_KEY_SIZE) { + key.len = MAX_KEY_SIZE; + } else if (ext->key_len > 0) { + key.len = MIN_KEY_SIZE; + } else { + return -EINVAL; + } + key_len = min (ext->key_len, key.len); + memcpy(key.key, ext->key, key_len); + break; + default: + return -EINVAL; + } + if (key.len == 0) { + rc = set_wep_tx_idx(local, idx, perm, 1); + if (rc < 0) { + airo_print_err(local->dev->name, + ""failed to set WEP transmit index to %d: %d."", + idx, rc); + return rc; + } + } else { + rc = set_wep_key(local, idx, key.key, key.len, perm, 1); + if (rc < 0) { + airo_print_err(local->dev->name, + ""failed to set WEP key at index %d: %d."", + idx, rc); + return rc; + } + } + } + + /* Read the flags */ + if(encoding->flags & IW_ENCODE_DISABLED) + local->config.authType = AUTH_OPEN; // disable encryption + if(encoding->flags & IW_ENCODE_RESTRICTED) + local->config.authType = AUTH_SHAREDKEY; // Only Both + if(encoding->flags & IW_ENCODE_OPEN) + local->config.authType = AUTH_ENCRYPT; // Only Wep + /* Commit the changes to flags if needed */ + if (local->config.authType != currentAuthType) + set_bit (FLAG_COMMIT, &local->flags); + + return -EINPROGRESS; +} +",0,"static int airo_set_encodeext(struct net_device *dev, + struct iw_request_info *info, + union iwreq_data *wrqu, + char *extra) +{ + struct airo_info *local = dev->ml_priv; + struct iw_point *encoding = &wrqu->encoding; + struct iw_encode_ext *ext = (struct iw_encode_ext *)extra; + int perm = ( encoding->flags & IW_ENCODE_TEMP ? 0 : 1 ); + __le16 currentAuthType = local->config.authType; + int idx, key_len, alg = ext->alg, set_key = 1, rc; + wep_key_t key; + + if (!local->wep_capable) + return -EOPNOTSUPP; + + readConfigRid(local, 1); + + /* Determine and validate the key index */ + idx = encoding->flags & IW_ENCODE_INDEX; + if (idx) { + if (!valid_index(local, idx - 1)) + return -EINVAL; + idx--; + } else { + idx = get_wep_tx_idx(local); + if (idx < 0) + idx = 0; + } + + if (encoding->flags & IW_ENCODE_DISABLED) + alg = IW_ENCODE_ALG_NONE; + + if (ext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY) { + /* Only set transmit key index here, actual + * key is set below if needed. + */ + rc = set_wep_tx_idx(local, idx, perm, 1); + if (rc < 0) { + airo_print_err(local->dev->name, ""failed to set "" + ""WEP transmit index to %d: %d."", + idx, rc); + return rc; + } + set_key = ext->key_len > 0 ? 1 : 0; + } + + if (set_key) { + /* Set the requested key first */ + memset(key.key, 0, MAX_KEY_SIZE); + switch (alg) { + case IW_ENCODE_ALG_NONE: + key.len = 0; + break; + case IW_ENCODE_ALG_WEP: + if (ext->key_len > MIN_KEY_SIZE) { + key.len = MAX_KEY_SIZE; + } else if (ext->key_len > 0) { + key.len = MIN_KEY_SIZE; + } else { + return -EINVAL; + } + key_len = min (ext->key_len, key.len); + memcpy(key.key, ext->key, key_len); + break; + default: + return -EINVAL; + } + if (key.len == 0) { + rc = set_wep_tx_idx(local, idx, perm, 1); + if (rc < 0) { + airo_print_err(local->dev->name, + ""failed to set WEP transmit index to %d: %d."", + idx, rc); + return rc; + } + } else { + rc = set_wep_key(local, idx, key.key, key.len, perm, 1); + if (rc < 0) { + airo_print_err(local->dev->name, + ""failed to set WEP key at index %d: %d."", + idx, rc); + return rc; + } + } + } + + /* Read the flags */ + if(encoding->flags & IW_ENCODE_DISABLED) + local->config.authType = AUTH_OPEN; // disable encryption + if(encoding->flags & IW_ENCODE_RESTRICTED) + local->config.authType = AUTH_SHAREDKEY; // Only Both + if(encoding->flags & IW_ENCODE_OPEN) + local->config.authType = AUTH_ENCRYPT; // Only Wep + /* Commit the changes to flags if needed */ + if (local->config.authType != currentAuthType) + set_bit (FLAG_COMMIT, &local->flags); + + return -EINPROGRESS; +} +","@@ -2823,6 +2823,7 @@ static struct net_device *_init_airo_card( unsigned short irq, int port, + dev->wireless_data = &ai->wireless_data; + dev->irq = irq; + dev->base_addr = port; ++ dev->priv_flags &= ~IFF_TX_SKB_SHARING; + + SET_NETDEV_DEV(dev, dmdev); + ",820,1151,2048 +1457,"session_setup_x11fwd(Session *s) +{ + struct stat st; + char display[512], auth_display[512]; + char hostname[NI_MAXHOST]; + u_int i; + + if (no_x11_forwarding_flag) { + packet_send_debug(""X11 forwarding disabled in user configuration file.""); + return 0; + } + if (!options.x11_forwarding) { + debug(""X11 forwarding disabled in server configuration file.""); + return 0; + } + if (options.xauth_location == NULL || + (stat(options.xauth_location, &st) == -1)) { + packet_send_debug(""No xauth program; cannot forward with spoofing.""); + return 0; + } + if (options.use_login) { + packet_send_debug(""X11 forwarding disabled; "" + ""not compatible with UseLogin=yes.""); + return 0; + } + if (s->display != NULL) { + debug(""X11 display already set.""); + return 0; + } + if (x11_create_display_inet(options.x11_display_offset, + options.x11_use_localhost, s->single_connection, + &s->display_number, &s->x11_chanids) == -1) { + debug(""x11_create_display_inet failed.""); + return 0; + } + for (i = 0; s->x11_chanids[i] != -1; i++) { + channel_register_cleanup(s->x11_chanids[i], + session_close_single_x11, 0); + } + + /* Set up a suitable value for the DISPLAY variable. */ + if (gethostname(hostname, sizeof(hostname)) < 0) + fatal(""gethostname: %.100s"", strerror(errno)); + /* + * auth_display must be used as the displayname when the + * authorization entry is added with xauth(1). This will be + * different than the DISPLAY string for localhost displays. + */ + if (options.x11_use_localhost) { + snprintf(display, sizeof display, ""localhost:%u.%u"", + s->display_number, s->screen); + snprintf(auth_display, sizeof auth_display, ""unix:%u.%u"", + s->display_number, s->screen); + s->display = xstrdup(display); + s->auth_display = xstrdup(auth_display); + } else { +#ifdef IPADDR_IN_DISPLAY + struct hostent *he; + struct in_addr my_addr; + + he = gethostbyname(hostname); + if (he == NULL) { + error(""Can't get IP address for X11 DISPLAY.""); + packet_send_debug(""Can't get IP address for X11 DISPLAY.""); + return 0; + } + memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr)); + snprintf(display, sizeof display, ""%.50s:%u.%u"", inet_ntoa(my_addr), + s->display_number, s->screen); +#else + snprintf(display, sizeof display, ""%.400s:%u.%u"", hostname, + s->display_number, s->screen); +#endif + s->display = xstrdup(display); + s->auth_display = xstrdup(display); + } + + return 1; +} +",0,"session_setup_x11fwd(Session *s) +{ + struct stat st; + char display[512], auth_display[512]; + char hostname[NI_MAXHOST]; + u_int i; + + if (no_x11_forwarding_flag) { + packet_send_debug(""X11 forwarding disabled in user configuration file.""); + return 0; + } + if (!options.x11_forwarding) { + debug(""X11 forwarding disabled in server configuration file.""); + return 0; + } + if (options.xauth_location == NULL || + (stat(options.xauth_location, &st) == -1)) { + packet_send_debug(""No xauth program; cannot forward with spoofing.""); + return 0; + } + if (options.use_login) { + packet_send_debug(""X11 forwarding disabled; "" + ""not compatible with UseLogin=yes.""); + return 0; + } + if (s->display != NULL) { + debug(""X11 display already set.""); + return 0; + } + if (x11_create_display_inet(options.x11_display_offset, + options.x11_use_localhost, s->single_connection, + &s->display_number, &s->x11_chanids) == -1) { + debug(""x11_create_display_inet failed.""); + return 0; + } + for (i = 0; s->x11_chanids[i] != -1; i++) { + channel_register_cleanup(s->x11_chanids[i], + session_close_single_x11, 0); + } + + /* Set up a suitable value for the DISPLAY variable. */ + if (gethostname(hostname, sizeof(hostname)) < 0) + fatal(""gethostname: %.100s"", strerror(errno)); + /* + * auth_display must be used as the displayname when the + * authorization entry is added with xauth(1). This will be + * different than the DISPLAY string for localhost displays. + */ + if (options.x11_use_localhost) { + snprintf(display, sizeof display, ""localhost:%u.%u"", + s->display_number, s->screen); + snprintf(auth_display, sizeof auth_display, ""unix:%u.%u"", + s->display_number, s->screen); + s->display = xstrdup(display); + s->auth_display = xstrdup(auth_display); + } else { +#ifdef IPADDR_IN_DISPLAY + struct hostent *he; + struct in_addr my_addr; + + he = gethostbyname(hostname); + if (he == NULL) { + error(""Can't get IP address for X11 DISPLAY.""); + packet_send_debug(""Can't get IP address for X11 DISPLAY.""); + return 0; + } + memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr)); + snprintf(display, sizeof display, ""%.50s:%u.%u"", inet_ntoa(my_addr), + s->display_number, s->screen); +#else + snprintf(display, sizeof display, ""%.400s:%u.%u"", hostname, + s->display_number, s->screen); +#endif + s->display = xstrdup(display); + s->auth_display = xstrdup(display); + } + + return 1; +} +","@@ -1322,7 +1322,7 @@ do_setup_env(Session *s, const char *shell) + * Pull in any environment variables that may have + * been set by PAM. + */ +- if (options.use_pam) { ++ if (options.use_pam && !options.use_login) { + char **p; + + p = fetch_pam_child_environment();",695,1026,2048 +9214,"XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) +{ + if ((parser == NULL) || (len < 0) || ((s == NULL) && (len != 0))) { + if (parser != NULL) + parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT; + return XML_STATUS_ERROR; + } + switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + parser->m_errorCode = XML_ERROR_SUSPENDED; + return XML_STATUS_ERROR; + case XML_FINISHED: + parser->m_errorCode = XML_ERROR_FINISHED; + return XML_STATUS_ERROR; + case XML_INITIALIZED: + if (parser->m_parentParser == NULL && !startParsing(parser)) { + parser->m_errorCode = XML_ERROR_NO_MEMORY; + return XML_STATUS_ERROR; + } + /* fall through */ + default: + parser->m_parsingStatus.parsing = XML_PARSING; + } + + if (len == 0) { + parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal; + if (!isFinal) + return XML_STATUS_OK; + parser->m_positionPtr = parser->m_bufferPtr; + parser->m_parseEndPtr = parser->m_bufferEnd; + + /* If data are left over from last buffer, and we now know that these + data are the final chunk of input, then we have to check them again + to detect errors based on that fact. + */ + parser->m_errorCode = parser->m_processor(parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr); + + if (parser->m_errorCode == XML_ERROR_NONE) { + switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + /* It is hard to be certain, but it seems that this case + * cannot occur. This code is cleaning up a previous parse + * with no new data (since len == 0). Changing the parsing + * state requires getting to execute a handler function, and + * there doesn't seem to be an opportunity for that while in + * this circumstance. + * + * Given the uncertainty, we retain the code but exclude it + * from coverage tests. + * + * LCOV_EXCL_START + */ + XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_bufferPtr, &parser->m_position); + parser->m_positionPtr = parser->m_bufferPtr; + return XML_STATUS_SUSPENDED; + /* LCOV_EXCL_STOP */ + case XML_INITIALIZED: + case XML_PARSING: + parser->m_parsingStatus.parsing = XML_FINISHED; + /* fall through */ + default: + return XML_STATUS_OK; + } + } + parser->m_eventEndPtr = parser->m_eventPtr; + parser->m_processor = errorProcessor; + return XML_STATUS_ERROR; + } +#ifndef XML_CONTEXT_BYTES + else if (parser->m_bufferPtr == parser->m_bufferEnd) { + const char *end; + int nLeftOver; + enum XML_Status result; + /* Detect overflow (a+b > MAX <==> b > MAX-a) */ + if (len > ((XML_Size)-1) / 2 - parser->m_parseEndByteIndex) { + parser->m_errorCode = XML_ERROR_NO_MEMORY; + parser->m_eventPtr = parser->m_eventEndPtr = NULL; + parser->m_processor = errorProcessor; + return XML_STATUS_ERROR; + } + parser->m_parseEndByteIndex += len; + parser->m_positionPtr = s; + parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal; + + parser->m_errorCode = parser->m_processor(parser, s, parser->m_parseEndPtr = s + len, &end); + + if (parser->m_errorCode != XML_ERROR_NONE) { + parser->m_eventEndPtr = parser->m_eventPtr; + parser->m_processor = errorProcessor; + return XML_STATUS_ERROR; + } + else { + switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + result = XML_STATUS_SUSPENDED; + break; + case XML_INITIALIZED: + case XML_PARSING: + if (isFinal) { + parser->m_parsingStatus.parsing = XML_FINISHED; + return XML_STATUS_OK; + } + /* fall through */ + default: + result = XML_STATUS_OK; + } + } + + XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, end, &parser->m_position); + nLeftOver = s + len - end; + if (nLeftOver) { + if (parser->m_buffer == NULL || nLeftOver > parser->m_bufferLim - parser->m_buffer) { + /* avoid _signed_ integer overflow */ + char *temp = NULL; + const int bytesToAllocate = (int)((unsigned)len * 2U); + if (bytesToAllocate > 0) { + temp = (char *)REALLOC(parser, parser->m_buffer, bytesToAllocate); + } + if (temp == NULL) { + parser->m_errorCode = XML_ERROR_NO_MEMORY; + parser->m_eventPtr = parser->m_eventEndPtr = NULL; + parser->m_processor = errorProcessor; + return XML_STATUS_ERROR; + } + parser->m_buffer = temp; + parser->m_bufferLim = parser->m_buffer + bytesToAllocate; + } + memcpy(parser->m_buffer, end, nLeftOver); + } + parser->m_bufferPtr = parser->m_buffer; + parser->m_bufferEnd = parser->m_buffer + nLeftOver; + parser->m_positionPtr = parser->m_bufferPtr; + parser->m_parseEndPtr = parser->m_bufferEnd; + parser->m_eventPtr = parser->m_bufferPtr; + parser->m_eventEndPtr = parser->m_bufferPtr; + return result; + } +#endif /* not defined XML_CONTEXT_BYTES */ + else { + void *buff = XML_GetBuffer(parser, len); + if (buff == NULL) + return XML_STATUS_ERROR; + else { + memcpy(buff, s, len); + return XML_ParseBuffer(parser, len, isFinal); + } + } +} +",0,"XML_Parse(XML_Parser parser, const char *s, int len, int isFinal) +{ + if ((parser == NULL) || (len < 0) || ((s == NULL) && (len != 0))) { + if (parser != NULL) + parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT; + return XML_STATUS_ERROR; + } + switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + parser->m_errorCode = XML_ERROR_SUSPENDED; + return XML_STATUS_ERROR; + case XML_FINISHED: + parser->m_errorCode = XML_ERROR_FINISHED; + return XML_STATUS_ERROR; + case XML_INITIALIZED: + if (parser->m_parentParser == NULL && !startParsing(parser)) { + parser->m_errorCode = XML_ERROR_NO_MEMORY; + return XML_STATUS_ERROR; + } + /* fall through */ + default: + parser->m_parsingStatus.parsing = XML_PARSING; + } + + if (len == 0) { + parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal; + if (!isFinal) + return XML_STATUS_OK; + parser->m_positionPtr = parser->m_bufferPtr; + parser->m_parseEndPtr = parser->m_bufferEnd; + + /* If data are left over from last buffer, and we now know that these + data are the final chunk of input, then we have to check them again + to detect errors based on that fact. + */ + parser->m_errorCode = parser->m_processor(parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr); + + if (parser->m_errorCode == XML_ERROR_NONE) { + switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + /* It is hard to be certain, but it seems that this case + * cannot occur. This code is cleaning up a previous parse + * with no new data (since len == 0). Changing the parsing + * state requires getting to execute a handler function, and + * there doesn't seem to be an opportunity for that while in + * this circumstance. + * + * Given the uncertainty, we retain the code but exclude it + * from coverage tests. + * + * LCOV_EXCL_START + */ + XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_bufferPtr, &parser->m_position); + parser->m_positionPtr = parser->m_bufferPtr; + return XML_STATUS_SUSPENDED; + /* LCOV_EXCL_STOP */ + case XML_INITIALIZED: + case XML_PARSING: + parser->m_parsingStatus.parsing = XML_FINISHED; + /* fall through */ + default: + return XML_STATUS_OK; + } + } + parser->m_eventEndPtr = parser->m_eventPtr; + parser->m_processor = errorProcessor; + return XML_STATUS_ERROR; + } +#ifndef XML_CONTEXT_BYTES + else if (parser->m_bufferPtr == parser->m_bufferEnd) { + const char *end; + int nLeftOver; + enum XML_Status result; + /* Detect overflow (a+b > MAX <==> b > MAX-a) */ + if (len > ((XML_Size)-1) / 2 - parser->m_parseEndByteIndex) { + parser->m_errorCode = XML_ERROR_NO_MEMORY; + parser->m_eventPtr = parser->m_eventEndPtr = NULL; + parser->m_processor = errorProcessor; + return XML_STATUS_ERROR; + } + parser->m_parseEndByteIndex += len; + parser->m_positionPtr = s; + parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal; + + parser->m_errorCode = parser->m_processor(parser, s, parser->m_parseEndPtr = s + len, &end); + + if (parser->m_errorCode != XML_ERROR_NONE) { + parser->m_eventEndPtr = parser->m_eventPtr; + parser->m_processor = errorProcessor; + return XML_STATUS_ERROR; + } + else { + switch (parser->m_parsingStatus.parsing) { + case XML_SUSPENDED: + result = XML_STATUS_SUSPENDED; + break; + case XML_INITIALIZED: + case XML_PARSING: + if (isFinal) { + parser->m_parsingStatus.parsing = XML_FINISHED; + return XML_STATUS_OK; + } + /* fall through */ + default: + result = XML_STATUS_OK; + } + } + + XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, end, &parser->m_position); + nLeftOver = s + len - end; + if (nLeftOver) { + if (parser->m_buffer == NULL || nLeftOver > parser->m_bufferLim - parser->m_buffer) { + /* avoid _signed_ integer overflow */ + char *temp = NULL; + const int bytesToAllocate = (int)((unsigned)len * 2U); + if (bytesToAllocate > 0) { + temp = (char *)REALLOC(parser, parser->m_buffer, bytesToAllocate); + } + if (temp == NULL) { + parser->m_errorCode = XML_ERROR_NO_MEMORY; + parser->m_eventPtr = parser->m_eventEndPtr = NULL; + parser->m_processor = errorProcessor; + return XML_STATUS_ERROR; + } + parser->m_buffer = temp; + parser->m_bufferLim = parser->m_buffer + bytesToAllocate; + } + memcpy(parser->m_buffer, end, nLeftOver); + } + parser->m_bufferPtr = parser->m_buffer; + parser->m_bufferEnd = parser->m_buffer + nLeftOver; + parser->m_positionPtr = parser->m_bufferPtr; + parser->m_parseEndPtr = parser->m_bufferEnd; + parser->m_eventPtr = parser->m_bufferPtr; + parser->m_eventEndPtr = parser->m_bufferPtr; + return result; + } +#endif /* not defined XML_CONTEXT_BYTES */ + else { + void *buff = XML_GetBuffer(parser, len); + if (buff == NULL) + return XML_STATUS_ERROR; + else { + memcpy(buff, s, len); + return XML_ParseBuffer(parser, len, isFinal); + } + } +} +","@@ -6071,7 +6071,7 @@ setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType) + else + poolDiscard(&dtd->pool); + elementType->prefix = prefix; +- ++ break; + } + } + return 1;",1349,1680,2048 +8981,"fast_unwrap_as_rep(krb5_context context, int32_t nonce, + krb5_data *chksumdata, + struct fast_state *state, AS_REP *rep) +{ + PA_FX_FAST_REPLY fxfastrep; + KrbFastResponse fastrep; + krb5_error_code ret; + PA_DATA *pa = NULL; + int idx = 0; + + if (state->armor_crypto == NULL || rep->padata == NULL) + return check_fast(context, state); + + /* find PA_FX_FAST_REPLY */ + + pa = krb5_find_padata(rep->padata->val, rep->padata->len, + KRB5_PADATA_FX_FAST, &idx); + if (pa == NULL) + return check_fast(context, state); + + memset(&fxfastrep, 0, sizeof(fxfastrep)); + memset(&fastrep, 0, sizeof(fastrep)); + + ret = decode_PA_FX_FAST_REPLY(pa->padata_value.data, pa->padata_value.length, &fxfastrep, NULL); + if (ret) + return ret; + + if (fxfastrep.element == choice_PA_FX_FAST_REPLY_armored_data) { + krb5_data data; + ret = krb5_decrypt_EncryptedData(context, + state->armor_crypto, + KRB5_KU_FAST_REP, + &fxfastrep.u.armored_data.enc_fast_rep, + &data); + if (ret) + goto out; + + ret = decode_KrbFastResponse(data.data, data.length, &fastrep, NULL); + krb5_data_free(&data); + if (ret) + goto out; + + } else { + ret = KRB5KDC_ERR_PREAUTH_FAILED; + goto out; + } + + free_METHOD_DATA(rep->padata); + ret = copy_METHOD_DATA(&fastrep.padata, rep->padata); + if (ret) + goto out; + + if (fastrep.strengthen_key) { + if (state->strengthen_key) + krb5_free_keyblock(context, state->strengthen_key); + + ret = krb5_copy_keyblock(context, fastrep.strengthen_key, &state->strengthen_key); + if (ret) + goto out; + } + + if (nonce != fastrep.nonce) { + ret = KRB5KDC_ERR_PREAUTH_FAILED; + goto out; + } + if (fastrep.finished) { + PrincipalName cname; + krb5_realm crealm = NULL; + + if (chksumdata == NULL) { + ret = KRB5KDC_ERR_PREAUTH_FAILED; + goto out; + } + + ret = krb5_verify_checksum(context, state->armor_crypto, + KRB5_KU_FAST_FINISHED, + chksumdata->data, chksumdata->length, + &fastrep.finished->ticket_checksum); + if (ret) + goto out; + + /* update */ + ret = copy_Realm(&fastrep.finished->crealm, &crealm); + if (ret) + goto out; + free_Realm(&rep->crealm); + rep->crealm = crealm; + + ret = copy_PrincipalName(&fastrep.finished->cname, &cname); + if (ret) + goto out; + free_PrincipalName(&rep->cname); + rep->cname = cname; + +#if 0 /* store authenticated checksum as kdc-offset */ + fastrep->finished.timestamp; + fastrep->finished.usec = 0; +#endif + + } else if (chksumdata) { + /* expected fastrep.finish but didn't get it */ + ret = KRB5KDC_ERR_PREAUTH_FAILED; + } + + out: + free_PA_FX_FAST_REPLY(&fxfastrep); + + return ret; +} +",0,"fast_unwrap_as_rep(krb5_context context, int32_t nonce, + krb5_data *chksumdata, + struct fast_state *state, AS_REP *rep) +{ + PA_FX_FAST_REPLY fxfastrep; + KrbFastResponse fastrep; + krb5_error_code ret; + PA_DATA *pa = NULL; + int idx = 0; + + if (state->armor_crypto == NULL || rep->padata == NULL) + return check_fast(context, state); + + /* find PA_FX_FAST_REPLY */ + + pa = krb5_find_padata(rep->padata->val, rep->padata->len, + KRB5_PADATA_FX_FAST, &idx); + if (pa == NULL) + return check_fast(context, state); + + memset(&fxfastrep, 0, sizeof(fxfastrep)); + memset(&fastrep, 0, sizeof(fastrep)); + + ret = decode_PA_FX_FAST_REPLY(pa->padata_value.data, pa->padata_value.length, &fxfastrep, NULL); + if (ret) + return ret; + + if (fxfastrep.element == choice_PA_FX_FAST_REPLY_armored_data) { + krb5_data data; + ret = krb5_decrypt_EncryptedData(context, + state->armor_crypto, + KRB5_KU_FAST_REP, + &fxfastrep.u.armored_data.enc_fast_rep, + &data); + if (ret) + goto out; + + ret = decode_KrbFastResponse(data.data, data.length, &fastrep, NULL); + krb5_data_free(&data); + if (ret) + goto out; + + } else { + ret = KRB5KDC_ERR_PREAUTH_FAILED; + goto out; + } + + free_METHOD_DATA(rep->padata); + ret = copy_METHOD_DATA(&fastrep.padata, rep->padata); + if (ret) + goto out; + + if (fastrep.strengthen_key) { + if (state->strengthen_key) + krb5_free_keyblock(context, state->strengthen_key); + + ret = krb5_copy_keyblock(context, fastrep.strengthen_key, &state->strengthen_key); + if (ret) + goto out; + } + + if (nonce != fastrep.nonce) { + ret = KRB5KDC_ERR_PREAUTH_FAILED; + goto out; + } + if (fastrep.finished) { + PrincipalName cname; + krb5_realm crealm = NULL; + + if (chksumdata == NULL) { + ret = KRB5KDC_ERR_PREAUTH_FAILED; + goto out; + } + + ret = krb5_verify_checksum(context, state->armor_crypto, + KRB5_KU_FAST_FINISHED, + chksumdata->data, chksumdata->length, + &fastrep.finished->ticket_checksum); + if (ret) + goto out; + + /* update */ + ret = copy_Realm(&fastrep.finished->crealm, &crealm); + if (ret) + goto out; + free_Realm(&rep->crealm); + rep->crealm = crealm; + + ret = copy_PrincipalName(&fastrep.finished->cname, &cname); + if (ret) + goto out; + free_PrincipalName(&rep->cname); + rep->cname = cname; + +#if 0 /* store authenticated checksum as kdc-offset */ + fastrep->finished.timestamp; + fastrep->finished.usec = 0; +#endif + + } else if (chksumdata) { + /* expected fastrep.finish but didn't get it */ + ret = KRB5KDC_ERR_PREAUTH_FAILED; + } + + out: + free_PA_FX_FAST_REPLY(&fxfastrep); + + return ret; +} +","@@ -2267,6 +2267,26 @@ krb5_init_creds_step(krb5_context context, + &ctx->req_buffer, + NULL, + NULL); ++ if (ret == 0 && ctx->pk_init_ctx) { ++ PA_DATA *pa_pkinit_kx; ++ int idx = 0; ++ ++ pa_pkinit_kx = ++ krb5_find_padata(rep.kdc_rep.padata->val, ++ rep.kdc_rep.padata->len, ++ KRB5_PADATA_PKINIT_KX, ++ &idx); ++ ++ ret = _krb5_pk_kx_confirm(context, ctx->pk_init_ctx, ++ ctx->fast_state.reply_key, ++ &ctx->cred.session, ++ pa_pkinit_kx); ++ if (ret) ++ krb5_set_error_message(context, ret, ++ N_(""Failed to confirm PA-PKINIT-KX"", """")); ++ else if (pa_pkinit_kx != NULL) ++ ctx->ic_flags |= KRB5_INIT_CREDS_PKINIT_KX_VALID; ++ } + if (ret == 0) + ret = copy_EncKDCRepPart(&rep.enc_part, &ctx->enc_part); + ",777,1108,2048 +4680,"static int __blkdev_get(struct block_device *bdev, fmode_t mode, int for_part) +{ + struct gendisk *disk; + struct module *owner; + int ret; + int partno; + int perm = 0; + + if (mode & FMODE_READ) + perm |= MAY_READ; + if (mode & FMODE_WRITE) + perm |= MAY_WRITE; + /* + * hooks: /n/, see ""layering violations"". + */ + if (!for_part) { + ret = devcgroup_inode_permission(bdev->bd_inode, perm); + if (ret != 0) { + bdput(bdev); + return ret; + } + } + + restart: + + ret = -ENXIO; + disk = get_gendisk(bdev->bd_dev, &partno); + if (!disk) + goto out; + owner = disk->fops->owner; + + disk_block_events(disk); + mutex_lock_nested(&bdev->bd_mutex, for_part); + if (!bdev->bd_openers) { + bdev->bd_disk = disk; + bdev->bd_queue = disk->queue; + bdev->bd_contains = bdev; + if (!partno) { + struct backing_dev_info *bdi; + + ret = -ENXIO; + bdev->bd_part = disk_get_part(disk, partno); + if (!bdev->bd_part) + goto out_clear; + + ret = 0; + if (disk->fops->open) { + ret = disk->fops->open(bdev, mode); + if (ret == -ERESTARTSYS) { + /* Lost a race with 'disk' being + * deleted, try again. + * See md.c + */ + disk_put_part(bdev->bd_part); + bdev->bd_part = NULL; + bdev->bd_disk = NULL; + bdev->bd_queue = NULL; + mutex_unlock(&bdev->bd_mutex); + disk_unblock_events(disk); + put_disk(disk); + module_put(owner); + goto restart; + } + } + + if (!ret) { + bd_set_size(bdev,(loff_t)get_capacity(disk)<<9); + bdi = blk_get_backing_dev_info(bdev); + if (bdi == NULL) + bdi = &default_backing_dev_info; + bdev_inode_switch_bdi(bdev->bd_inode, bdi); + } + + /* + * If the device is invalidated, rescan partition + * if open succeeded or failed with -ENOMEDIUM. + * The latter is necessary to prevent ghost + * partitions on a removed medium. + */ + if (bdev->bd_invalidated) { + if (!ret) + rescan_partitions(disk, bdev); + else if (ret == -ENOMEDIUM) + invalidate_partitions(disk, bdev); + } + if (ret) + goto out_clear; + } else { + struct block_device *whole; + whole = bdget_disk(disk, 0); + ret = -ENOMEM; + if (!whole) + goto out_clear; + BUG_ON(for_part); + ret = __blkdev_get(whole, mode, 1); + if (ret) + goto out_clear; + bdev->bd_contains = whole; + bdev_inode_switch_bdi(bdev->bd_inode, + whole->bd_inode->i_data.backing_dev_info); + bdev->bd_part = disk_get_part(disk, partno); + if (!(disk->flags & GENHD_FL_UP) || + !bdev->bd_part || !bdev->bd_part->nr_sects) { + ret = -ENXIO; + goto out_clear; + } + bd_set_size(bdev, (loff_t)bdev->bd_part->nr_sects << 9); + } + } else { + if (bdev->bd_contains == bdev) { + ret = 0; + if (bdev->bd_disk->fops->open) + ret = bdev->bd_disk->fops->open(bdev, mode); + /* the same as first opener case, read comment there */ + if (bdev->bd_invalidated) { + if (!ret) + rescan_partitions(bdev->bd_disk, bdev); + else if (ret == -ENOMEDIUM) + invalidate_partitions(bdev->bd_disk, bdev); + } + if (ret) + goto out_unlock_bdev; + } + /* only one opener holds refs to the module and disk */ + put_disk(disk); + module_put(owner); + } + bdev->bd_openers++; + if (for_part) + bdev->bd_part_count++; + mutex_unlock(&bdev->bd_mutex); + disk_unblock_events(disk); + return 0; + + out_clear: + disk_put_part(bdev->bd_part); + bdev->bd_disk = NULL; + bdev->bd_part = NULL; + bdev->bd_queue = NULL; + bdev_inode_switch_bdi(bdev->bd_inode, &default_backing_dev_info); + if (bdev != bdev->bd_contains) + __blkdev_put(bdev->bd_contains, mode, 1); + bdev->bd_contains = NULL; + out_unlock_bdev: + mutex_unlock(&bdev->bd_mutex); + disk_unblock_events(disk); + put_disk(disk); + module_put(owner); + out: + bdput(bdev); + + return ret; +} +",0,"static int __blkdev_get(struct block_device *bdev, fmode_t mode, int for_part) +{ + struct gendisk *disk; + struct module *owner; + int ret; + int partno; + int perm = 0; + + if (mode & FMODE_READ) + perm |= MAY_READ; + if (mode & FMODE_WRITE) + perm |= MAY_WRITE; + /* + * hooks: /n/, see ""layering violations"". + */ + if (!for_part) { + ret = devcgroup_inode_permission(bdev->bd_inode, perm); + if (ret != 0) { + bdput(bdev); + return ret; + } + } + + restart: + + ret = -ENXIO; + disk = get_gendisk(bdev->bd_dev, &partno); + if (!disk) + goto out; + owner = disk->fops->owner; + + disk_block_events(disk); + mutex_lock_nested(&bdev->bd_mutex, for_part); + if (!bdev->bd_openers) { + bdev->bd_disk = disk; + bdev->bd_queue = disk->queue; + bdev->bd_contains = bdev; + if (!partno) { + struct backing_dev_info *bdi; + + ret = -ENXIO; + bdev->bd_part = disk_get_part(disk, partno); + if (!bdev->bd_part) + goto out_clear; + + ret = 0; + if (disk->fops->open) { + ret = disk->fops->open(bdev, mode); + if (ret == -ERESTARTSYS) { + /* Lost a race with 'disk' being + * deleted, try again. + * See md.c + */ + disk_put_part(bdev->bd_part); + bdev->bd_part = NULL; + bdev->bd_disk = NULL; + bdev->bd_queue = NULL; + mutex_unlock(&bdev->bd_mutex); + disk_unblock_events(disk); + put_disk(disk); + module_put(owner); + goto restart; + } + } + + if (!ret) { + bd_set_size(bdev,(loff_t)get_capacity(disk)<<9); + bdi = blk_get_backing_dev_info(bdev); + if (bdi == NULL) + bdi = &default_backing_dev_info; + bdev_inode_switch_bdi(bdev->bd_inode, bdi); + } + + /* + * If the device is invalidated, rescan partition + * if open succeeded or failed with -ENOMEDIUM. + * The latter is necessary to prevent ghost + * partitions on a removed medium. + */ + if (bdev->bd_invalidated) { + if (!ret) + rescan_partitions(disk, bdev); + else if (ret == -ENOMEDIUM) + invalidate_partitions(disk, bdev); + } + if (ret) + goto out_clear; + } else { + struct block_device *whole; + whole = bdget_disk(disk, 0); + ret = -ENOMEM; + if (!whole) + goto out_clear; + BUG_ON(for_part); + ret = __blkdev_get(whole, mode, 1); + if (ret) + goto out_clear; + bdev->bd_contains = whole; + bdev_inode_switch_bdi(bdev->bd_inode, + whole->bd_inode->i_data.backing_dev_info); + bdev->bd_part = disk_get_part(disk, partno); + if (!(disk->flags & GENHD_FL_UP) || + !bdev->bd_part || !bdev->bd_part->nr_sects) { + ret = -ENXIO; + goto out_clear; + } + bd_set_size(bdev, (loff_t)bdev->bd_part->nr_sects << 9); + } + } else { + if (bdev->bd_contains == bdev) { + ret = 0; + if (bdev->bd_disk->fops->open) + ret = bdev->bd_disk->fops->open(bdev, mode); + /* the same as first opener case, read comment there */ + if (bdev->bd_invalidated) { + if (!ret) + rescan_partitions(bdev->bd_disk, bdev); + else if (ret == -ENOMEDIUM) + invalidate_partitions(bdev->bd_disk, bdev); + } + if (ret) + goto out_unlock_bdev; + } + /* only one opener holds refs to the module and disk */ + put_disk(disk); + module_put(owner); + } + bdev->bd_openers++; + if (for_part) + bdev->bd_part_count++; + mutex_unlock(&bdev->bd_mutex); + disk_unblock_events(disk); + return 0; + + out_clear: + disk_put_part(bdev->bd_part); + bdev->bd_disk = NULL; + bdev->bd_part = NULL; + bdev->bd_queue = NULL; + bdev_inode_switch_bdi(bdev->bd_inode, &default_backing_dev_info); + if (bdev != bdev->bd_contains) + __blkdev_put(bdev->bd_contains, mode, 1); + bdev->bd_contains = NULL; + out_unlock_bdev: + mutex_unlock(&bdev->bd_mutex); + disk_unblock_events(disk); + put_disk(disk); + module_put(owner); + out: + bdput(bdev); + + return ret; +} +","@@ -1583,7 +1583,7 @@ const struct file_operations def_blk_fops = { + .compat_ioctl = compat_blkdev_ioctl, + #endif + .splice_read = generic_file_splice_read, +- .splice_write = generic_file_splice_write, ++ .splice_write = iter_file_splice_write, + }; + + int ioctl_by_bdev(struct block_device *bdev, unsigned cmd, unsigned long arg)",1175,1506,2048 +4416,"AP_CORE_DECLARE_NONSTD(apr_status_t) ap_http_header_filter(ap_filter_t *f, + apr_bucket_brigade *b) +{ + request_rec *r = f->r; + conn_rec *c = r->connection; + const char *protocol = NULL; + apr_bucket *e; + apr_bucket_brigade *b2; + header_struct h; + header_filter_ctx *ctx = f->ctx; + const char *ctype; + ap_bucket_error *eb = NULL; + core_server_config *conf; + + AP_DEBUG_ASSERT(!r->main); + + if (r->header_only) { + if (!ctx) { + ctx = f->ctx = apr_pcalloc(r->pool, sizeof(header_filter_ctx)); + } + else if (ctx->headers_sent) { + apr_brigade_cleanup(b); + return OK; + } + } + + for (e = APR_BRIGADE_FIRST(b); + e != APR_BRIGADE_SENTINEL(b); + e = APR_BUCKET_NEXT(e)) + { + if (AP_BUCKET_IS_ERROR(e) && !eb) { + eb = e->data; + continue; + } + /* + * If we see an EOC bucket it is a signal that we should get out + * of the way doing nothing. + */ + if (AP_BUCKET_IS_EOC(e)) { + ap_remove_output_filter(f); + return ap_pass_brigade(f->next, b); + } + } + if (eb) { + int status; + + status = eb->status; + apr_brigade_cleanup(b); + ap_die(status, r); + return AP_FILTER_ERROR; + } + + if (r->assbackwards) { + r->sent_bodyct = 1; + ap_remove_output_filter(f); + return ap_pass_brigade(f->next, b); + } + + /* + * Now that we are ready to send a response, we need to combine the two + * header field tables into a single table. If we don't do this, our + * later attempts to set or unset a given fieldname might be bypassed. + */ + if (!apr_is_empty_table(r->err_headers_out)) { + r->headers_out = apr_table_overlay(r->pool, r->err_headers_out, + r->headers_out); + } + + conf = ap_get_core_module_config(r->server->module_config); + if (conf->http_conformance & AP_HTTP_CONFORMANCE_STRICT) { + int ok = check_headers(r); + if (!ok && !(conf->http_conformance & AP_HTTP_CONFORMANCE_LOGONLY)) { + ap_die(HTTP_INTERNAL_SERVER_ERROR, r); + return AP_FILTER_ERROR; + } + } + + /* + * Remove the 'Vary' header field if the client can't handle it. + * Since this will have nasty effects on HTTP/1.1 caches, force + * the response into HTTP/1.0 mode. + * + * Note: the force-response-1.0 should come before the call to + * basic_http_header_check() + */ + if (apr_table_get(r->subprocess_env, ""force-no-vary"") != NULL) { + apr_table_unset(r->headers_out, ""Vary""); + r->proto_num = HTTP_VERSION(1,0); + apr_table_setn(r->subprocess_env, ""force-response-1.0"", ""1""); + } + else { + fixup_vary(r); + } + + /* + * Now remove any ETag response header field if earlier processing + * says so (such as a 'FileETag None' directive). + */ + if (apr_table_get(r->notes, ""no-etag"") != NULL) { + apr_table_unset(r->headers_out, ""ETag""); + } + + /* determine the protocol and whether we should use keepalives. */ + basic_http_header_check(r, &protocol); + ap_set_keepalive(r); + + if (r->chunked) { + apr_table_mergen(r->headers_out, ""Transfer-Encoding"", ""chunked""); + apr_table_unset(r->headers_out, ""Content-Length""); + } + + ctype = ap_make_content_type(r, r->content_type); + if (ctype) { + apr_table_setn(r->headers_out, ""Content-Type"", ctype); + } + + if (r->content_encoding) { + apr_table_setn(r->headers_out, ""Content-Encoding"", + r->content_encoding); + } + + if (!apr_is_empty_array(r->content_languages)) { + int i; + char *token; + char **languages = (char **)(r->content_languages->elts); + const char *field = apr_table_get(r->headers_out, ""Content-Language""); + + while (field && (token = ap_get_list_item(r->pool, &field)) != NULL) { + for (i = 0; i < r->content_languages->nelts; ++i) { + if (!strcasecmp(token, languages[i])) + break; + } + if (i == r->content_languages->nelts) { + *((char **) apr_array_push(r->content_languages)) = token; + } + } + + field = apr_array_pstrcat(r->pool, r->content_languages, ','); + apr_table_setn(r->headers_out, ""Content-Language"", field); + } + + /* + * Control cachability for non-cachable responses if not already set by + * some other part of the server configuration. + */ + if (r->no_cache && !apr_table_get(r->headers_out, ""Expires"")) { + char *date = apr_palloc(r->pool, APR_RFC822_DATE_LEN); + ap_recent_rfc822_date(date, r->request_time); + apr_table_addn(r->headers_out, ""Expires"", date); + } + + b2 = apr_brigade_create(r->pool, c->bucket_alloc); + basic_http_header(r, b2, protocol); + + h.pool = r->pool; + h.bb = b2; + + if (r->status == HTTP_NOT_MODIFIED) { + apr_table_do((int (*)(void *, const char *, const char *)) form_header_field, + (void *) &h, r->headers_out, + ""Connection"", + ""Keep-Alive"", + ""ETag"", + ""Content-Location"", + ""Expires"", + ""Cache-Control"", + ""Vary"", + ""Warning"", + ""WWW-Authenticate"", + ""Proxy-Authenticate"", + ""Set-Cookie"", + ""Set-Cookie2"", + NULL); + } + else { + send_all_header_fields(&h, r); + } + + terminate_header(b2); + + ap_pass_brigade(f->next, b2); + + if (r->header_only) { + apr_brigade_cleanup(b); + ctx->headers_sent = 1; + return OK; + } + + r->sent_bodyct = 1; /* Whatever follows is real body stuff... */ + + if (r->chunked) { + /* We can't add this filter until we have already sent the headers. + * If we add it before this point, then the headers will be chunked + * as well, and that is just wrong. + */ + ap_add_output_filter(""CHUNK"", NULL, r, r->connection); + } + + /* Don't remove this filter until after we have added the CHUNK filter. + * Otherwise, f->next won't be the CHUNK filter and thus the first + * brigade won't be chunked properly. + */ + ap_remove_output_filter(f); + return ap_pass_brigade(f->next, b); +} +",0,"AP_CORE_DECLARE_NONSTD(apr_status_t) ap_http_header_filter(ap_filter_t *f, + apr_bucket_brigade *b) +{ + request_rec *r = f->r; + conn_rec *c = r->connection; + const char *protocol = NULL; + apr_bucket *e; + apr_bucket_brigade *b2; + header_struct h; + header_filter_ctx *ctx = f->ctx; + const char *ctype; + ap_bucket_error *eb = NULL; + core_server_config *conf; + + AP_DEBUG_ASSERT(!r->main); + + if (r->header_only) { + if (!ctx) { + ctx = f->ctx = apr_pcalloc(r->pool, sizeof(header_filter_ctx)); + } + else if (ctx->headers_sent) { + apr_brigade_cleanup(b); + return OK; + } + } + + for (e = APR_BRIGADE_FIRST(b); + e != APR_BRIGADE_SENTINEL(b); + e = APR_BUCKET_NEXT(e)) + { + if (AP_BUCKET_IS_ERROR(e) && !eb) { + eb = e->data; + continue; + } + /* + * If we see an EOC bucket it is a signal that we should get out + * of the way doing nothing. + */ + if (AP_BUCKET_IS_EOC(e)) { + ap_remove_output_filter(f); + return ap_pass_brigade(f->next, b); + } + } + if (eb) { + int status; + + status = eb->status; + apr_brigade_cleanup(b); + ap_die(status, r); + return AP_FILTER_ERROR; + } + + if (r->assbackwards) { + r->sent_bodyct = 1; + ap_remove_output_filter(f); + return ap_pass_brigade(f->next, b); + } + + /* + * Now that we are ready to send a response, we need to combine the two + * header field tables into a single table. If we don't do this, our + * later attempts to set or unset a given fieldname might be bypassed. + */ + if (!apr_is_empty_table(r->err_headers_out)) { + r->headers_out = apr_table_overlay(r->pool, r->err_headers_out, + r->headers_out); + } + + conf = ap_get_core_module_config(r->server->module_config); + if (conf->http_conformance & AP_HTTP_CONFORMANCE_STRICT) { + int ok = check_headers(r); + if (!ok && !(conf->http_conformance & AP_HTTP_CONFORMANCE_LOGONLY)) { + ap_die(HTTP_INTERNAL_SERVER_ERROR, r); + return AP_FILTER_ERROR; + } + } + + /* + * Remove the 'Vary' header field if the client can't handle it. + * Since this will have nasty effects on HTTP/1.1 caches, force + * the response into HTTP/1.0 mode. + * + * Note: the force-response-1.0 should come before the call to + * basic_http_header_check() + */ + if (apr_table_get(r->subprocess_env, ""force-no-vary"") != NULL) { + apr_table_unset(r->headers_out, ""Vary""); + r->proto_num = HTTP_VERSION(1,0); + apr_table_setn(r->subprocess_env, ""force-response-1.0"", ""1""); + } + else { + fixup_vary(r); + } + + /* + * Now remove any ETag response header field if earlier processing + * says so (such as a 'FileETag None' directive). + */ + if (apr_table_get(r->notes, ""no-etag"") != NULL) { + apr_table_unset(r->headers_out, ""ETag""); + } + + /* determine the protocol and whether we should use keepalives. */ + basic_http_header_check(r, &protocol); + ap_set_keepalive(r); + + if (r->chunked) { + apr_table_mergen(r->headers_out, ""Transfer-Encoding"", ""chunked""); + apr_table_unset(r->headers_out, ""Content-Length""); + } + + ctype = ap_make_content_type(r, r->content_type); + if (ctype) { + apr_table_setn(r->headers_out, ""Content-Type"", ctype); + } + + if (r->content_encoding) { + apr_table_setn(r->headers_out, ""Content-Encoding"", + r->content_encoding); + } + + if (!apr_is_empty_array(r->content_languages)) { + int i; + char *token; + char **languages = (char **)(r->content_languages->elts); + const char *field = apr_table_get(r->headers_out, ""Content-Language""); + + while (field && (token = ap_get_list_item(r->pool, &field)) != NULL) { + for (i = 0; i < r->content_languages->nelts; ++i) { + if (!strcasecmp(token, languages[i])) + break; + } + if (i == r->content_languages->nelts) { + *((char **) apr_array_push(r->content_languages)) = token; + } + } + + field = apr_array_pstrcat(r->pool, r->content_languages, ','); + apr_table_setn(r->headers_out, ""Content-Language"", field); + } + + /* + * Control cachability for non-cachable responses if not already set by + * some other part of the server configuration. + */ + if (r->no_cache && !apr_table_get(r->headers_out, ""Expires"")) { + char *date = apr_palloc(r->pool, APR_RFC822_DATE_LEN); + ap_recent_rfc822_date(date, r->request_time); + apr_table_addn(r->headers_out, ""Expires"", date); + } + + b2 = apr_brigade_create(r->pool, c->bucket_alloc); + basic_http_header(r, b2, protocol); + + h.pool = r->pool; + h.bb = b2; + + if (r->status == HTTP_NOT_MODIFIED) { + apr_table_do((int (*)(void *, const char *, const char *)) form_header_field, + (void *) &h, r->headers_out, + ""Connection"", + ""Keep-Alive"", + ""ETag"", + ""Content-Location"", + ""Expires"", + ""Cache-Control"", + ""Vary"", + ""Warning"", + ""WWW-Authenticate"", + ""Proxy-Authenticate"", + ""Set-Cookie"", + ""Set-Cookie2"", + NULL); + } + else { + send_all_header_fields(&h, r); + } + + terminate_header(b2); + + ap_pass_brigade(f->next, b2); + + if (r->header_only) { + apr_brigade_cleanup(b); + ctx->headers_sent = 1; + return OK; + } + + r->sent_bodyct = 1; /* Whatever follows is real body stuff... */ + + if (r->chunked) { + /* We can't add this filter until we have already sent the headers. + * If we add it before this point, then the headers will be chunked + * as well, and that is just wrong. + */ + ap_add_output_filter(""CHUNK"", NULL, r, r->connection); + } + + /* Don't remove this filter until after we have added the CHUNK filter. + * Otherwise, f->next won't be the CHUNK filter and thus the first + * brigade won't be chunked properly. + */ + ap_remove_output_filter(f); + return ap_pass_brigade(f->next, b); +} +","@@ -57,24 +57,24 @@ + + APLOG_USE_MODULE(http); + +-#define INVALID_CHAR -2 +- + typedef struct http_filter_ctx + { + apr_off_t remaining; + apr_off_t limit; + apr_off_t limit_used; + apr_int32_t chunk_used; +- apr_int16_t chunkbits; ++ apr_int32_t chunkbits; + enum + { + BODY_NONE, /* streamed data */ + BODY_LENGTH, /* data constrained by content length */ + BODY_CHUNK, /* chunk expected */ + BODY_CHUNK_PART, /* chunk digits */ + BODY_CHUNK_EXT, /* chunk extension */ ++ BODY_CHUNK_LF, /* got CR, expect LF after digits/extension */ + BODY_CHUNK_DATA, /* data constrained by chunked encoding */ +- BODY_CHUNK_END, /* chunk terminating CRLF */ ++ BODY_CHUNK_END, /* chunked data terminating CRLF */ ++ BODY_CHUNK_END_LF, /* got CR, expect LF after data */ + BODY_CHUNK_TRAILER /* trailers */ + } state; + unsigned int eos_sent :1; +@@ -89,7 +89,7 @@ typedef struct http_filter_ctx + * In general, any negative number can be considered an overflow error. + */ + static apr_status_t parse_chunk_size(http_ctx_t *ctx, const char *buffer, +- apr_size_t len, int linelimit) ++ apr_size_t len, int linelimit) + { + apr_size_t i = 0; + +@@ -99,10 +99,20 @@ static apr_status_t parse_chunk_size(http_ctx_t *ctx, const char *buffer, + ap_xlate_proto_from_ascii(&c, 1); + + /* handle CRLF after the chunk */ +- if (ctx->state == BODY_CHUNK_END) { ++ if (ctx->state == BODY_CHUNK_END ++ || ctx->state == BODY_CHUNK_END_LF) { + if (c == LF) { + ctx->state = BODY_CHUNK; + } ++ else if (c == CR && ctx->state == BODY_CHUNK_END) { ++ ctx->state = BODY_CHUNK_END_LF; ++ } ++ else { ++ /* ++ * LF expected. ++ */ ++ return APR_EINVAL; ++ } + i++; + continue; + } +@@ -111,44 +121,62 @@ static apr_status_t parse_chunk_size(http_ctx_t *ctx, const char *buffer, + if (ctx->state == BODY_CHUNK) { + if (!apr_isxdigit(c)) { + /* +- * Detect invalid character at beginning. This also works for empty +- * chunk size lines. ++ * Detect invalid character at beginning. This also works for ++ * empty chunk size lines. + */ +- return APR_EGENERAL; ++ return APR_EINVAL; + } + else { + ctx->state = BODY_CHUNK_PART; + } + ctx->remaining = 0; +- ctx->chunkbits = sizeof(long) * 8; ++ ctx->chunkbits = sizeof(apr_off_t) * 8; + ctx->chunk_used = 0; + } + +- /* handle a chunk part, or a chunk extension */ +- /* +- * In theory, we are supposed to expect CRLF only, but our +- * test suite sends LF only. Tolerate a missing CR. +- */ +- if (c == ';' || c == CR) { +- ctx->state = BODY_CHUNK_EXT; +- } +- else if (c == LF) { ++ if (c == LF) { + if (ctx->remaining) { + ctx->state = BODY_CHUNK_DATA; + } + else { + ctx->state = BODY_CHUNK_TRAILER; + } + } +- else if (ctx->state != BODY_CHUNK_EXT) { +- int xvalue = 0; ++ else if (ctx->state == BODY_CHUNK_LF) { ++ /* ++ * LF expected. ++ */ ++ return APR_EINVAL; ++ } ++ else if (c == CR) { ++ ctx->state = BODY_CHUNK_LF; ++ } ++ else if (c == ';') { ++ ctx->state = BODY_CHUNK_EXT; ++ } ++ else if (ctx->state == BODY_CHUNK_EXT) { ++ /* ++ * Control chars (but tabs) are invalid. ++ */ ++ if (c != '\t' && apr_iscntrl(c)) { ++ return APR_EINVAL; ++ } ++ } ++ else if (ctx->state == BODY_CHUNK_PART) { ++ int xvalue; + + /* ignore leading zeros */ + if (!ctx->remaining && c == '0') { + i++; + continue; + } + ++ ctx->chunkbits -= 4; ++ if (ctx->chunkbits < 0) { ++ /* overflow */ ++ return APR_ENOSPC; ++ } ++ + if (c >= '0' && c <= '9') { + xvalue = c - '0'; + } +@@ -160,16 +188,18 @@ static apr_status_t parse_chunk_size(http_ctx_t *ctx, const char *buffer, + } + else { + /* bogus character */ +- return APR_EGENERAL; ++ return APR_EINVAL; + } + + ctx->remaining = (ctx->remaining << 4) | xvalue; +- ctx->chunkbits -= 4; +- if (ctx->chunkbits <= 0 || ctx->remaining < 0) { ++ if (ctx->remaining < 0) { + /* overflow */ + return APR_ENOSPC; + } +- ++ } ++ else { ++ /* Should not happen */ ++ return APR_EGENERAL; + } + + i++; +@@ -232,7 +262,8 @@ static apr_status_t read_chunked_trailers(http_ctx_t *ctx, ap_filter_t *f, + * are successfully parsed. + */ + apr_status_t ap_http_filter(ap_filter_t *f, apr_bucket_brigade *b, +- ap_input_mode_t mode, apr_read_type_e block, apr_off_t readbytes) ++ ap_input_mode_t mode, apr_read_type_e block, ++ apr_off_t readbytes) + { + core_server_config *conf; + apr_bucket *e; +@@ -282,8 +313,8 @@ apr_status_t ap_http_filter(ap_filter_t *f, apr_bucket_brigade *b, + * reading the connection until it is closed by the server."" + */ + ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(02555) +- ""Unknown Transfer-Encoding: %s;"" +- "" using read-until-close"", tenc); ++ ""Unknown Transfer-Encoding: %s; "" ++ ""using read-until-close"", tenc); + tenc = NULL; + } + else { +@@ -308,22 +339,20 @@ apr_status_t ap_http_filter(ap_filter_t *f, apr_bucket_brigade *b, + || endstr == lenp || *endstr || ctx->remaining < 0) { + + ctx->remaining = 0; +- ap_log_rerror( +- APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(01587) +- ""Invalid Content-Length""); ++ ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(01587) ++ ""Invalid Content-Length""); + +- return APR_ENOSPC; ++ return APR_EINVAL; + } + + /* If we have a limit in effect and we know the C-L ahead of + * time, stop it here if it is invalid. + */ + if (ctx->limit && ctx->limit < ctx->remaining) { +- ap_log_rerror( +- APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(01588) +- ""Requested content-length of %"" APR_OFF_T_FMT +- "" is larger than the configured limit"" +- "" of %"" APR_OFF_T_FMT, ctx->remaining, ctx->limit); ++ ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(01588) ++ ""Requested content-length of %"" APR_OFF_T_FMT ++ "" is larger than the configured limit"" ++ "" of %"" APR_OFF_T_FMT, ctx->remaining, ctx->limit); + return APR_ENOSPC; + } + } +@@ -378,6 +407,7 @@ apr_status_t ap_http_filter(ap_filter_t *f, apr_bucket_brigade *b, + APR_BRIGADE_INSERT_TAIL(bb, e); + + rv = ap_pass_brigade(f->c->output_filters, bb); ++ apr_brigade_cleanup(bb); + if (rv != APR_SUCCESS) { + return AP_FILTER_ERROR; + } +@@ -401,7 +431,9 @@ apr_status_t ap_http_filter(ap_filter_t *f, apr_bucket_brigade *b, + case BODY_CHUNK: + case BODY_CHUNK_PART: + case BODY_CHUNK_EXT: +- case BODY_CHUNK_END: { ++ case BODY_CHUNK_LF: ++ case BODY_CHUNK_END: ++ case BODY_CHUNK_END_LF: { + + rv = ap_get_brigade(f->next, b, AP_MODE_GETLINE, block, 0); + +@@ -433,8 +465,9 @@ apr_status_t ap_http_filter(ap_filter_t *f, apr_bucket_brigade *b, + f->r->server->limit_req_fieldsize); + } + if (rv != APR_SUCCESS) { +- ap_log_rerror( +- APLOG_MARK, APLOG_INFO, rv, f->r, APLOGNO(01590) ""Error reading chunk %s "", (APR_ENOSPC == rv) ? ""(overflow)"" : """"); ++ ap_log_rerror(APLOG_MARK, APLOG_INFO, rv, f->r, APLOGNO(01590) ++ ""Error reading chunk %s "", ++ (APR_ENOSPC == rv) ? ""(overflow)"" : """"); + return rv; + } + } +@@ -446,9 +479,8 @@ apr_status_t ap_http_filter(ap_filter_t *f, apr_bucket_brigade *b, + + if (ctx->state == BODY_CHUNK_TRAILER) { + /* Treat UNSET as DISABLE - trailers aren't merged by default */ +- int merge_trailers = +- conf->merge_trailers == AP_MERGE_TRAILERS_ENABLE; +- return read_chunked_trailers(ctx, f, b, merge_trailers); ++ return read_chunked_trailers(ctx, f, b, ++ conf->merge_trailers == AP_MERGE_TRAILERS_ENABLE); + } + + break; +@@ -522,9 +554,10 @@ apr_status_t ap_http_filter(ap_filter_t *f, apr_bucket_brigade *b, + * really count. This seems to be up for interpretation. */ + ctx->limit_used += totalread; + if (ctx->limit < ctx->limit_used) { +- ap_log_rerror( +- APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(01591) ""Read content-length of %"" APR_OFF_T_FMT "" is larger than the configured limit"" +- "" of %"" APR_OFF_T_FMT, ctx->limit_used, ctx->limit); ++ ap_log_rerror(APLOG_MARK, APLOG_INFO, 0, f->r, APLOGNO(01591) ++ ""Read content-length of %"" APR_OFF_T_FMT ++ "" is larger than the configured limit"" ++ "" of %"" APR_OFF_T_FMT, ctx->limit_used, ctx->limit); + return APR_ENOSPC; + } + } +@@ -549,7 +582,10 @@ apr_status_t ap_http_filter(ap_filter_t *f, apr_bucket_brigade *b, + break; + } + default: { +- break; ++ /* Should not happen */ ++ ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, f->r, APLOGNO(02901) ++ ""Unexpected body state (%i)"", (int)ctx->state); ++ return APR_EGENERAL; + } + } + ",1623,1954,2048 +9618,"NDIS_STATUS ParaNdis_FinishSpecificInitialization(PARANDIS_ADAPTER *pContext) +{ + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + NET_BUFFER_LIST_POOL_PARAMETERS PoolParams; + NDIS_MINIPORT_INTERRUPT_CHARACTERISTICS mic; + DEBUG_ENTRY(0); + + NdisZeroMemory(&mic, sizeof(mic)); + mic.Header.Type = NDIS_OBJECT_TYPE_MINIPORT_INTERRUPT; + mic.Header.Revision = NDIS_MINIPORT_INTERRUPT_REVISION_1; + mic.Header.Size = NDIS_SIZEOF_MINIPORT_INTERRUPT_CHARACTERISTICS_REVISION_1; + mic.DisableInterruptHandler = MiniportDisableInterruptEx; + mic.EnableInterruptHandler = MiniportEnableInterruptEx; + mic.InterruptDpcHandler = MiniportInterruptDPC; + mic.InterruptHandler = MiniportInterrupt; + if (pContext->bUsingMSIX) + { + mic.MsiSupported = TRUE; + mic.MsiSyncWithAllMessages = TRUE; + mic.EnableMessageInterruptHandler = MiniportEnableMSIInterrupt; + mic.DisableMessageInterruptHandler = MiniportDisableMSIInterrupt; + mic.MessageInterruptHandler = MiniportMSIInterrupt; + mic.MessageInterruptDpcHandler = MiniportMSIInterruptDpc; + } + PoolParams.Header.Type = NDIS_OBJECT_TYPE_DEFAULT; + PoolParams.Header.Size = sizeof(PoolParams); + PoolParams.Header.Revision = NET_BUFFER_LIST_POOL_PARAMETERS_REVISION_1; + PoolParams.ProtocolId = NDIS_PROTOCOL_ID_DEFAULT; + PoolParams.fAllocateNetBuffer = TRUE; + PoolParams.ContextSize = 0; + PoolParams.PoolTag = PARANDIS_MEMORY_TAG; + PoolParams.DataSize = 0; + + pContext->BufferListsPool = NdisAllocateNetBufferListPool(pContext->MiniportHandle, &PoolParams); + if (!pContext->BufferListsPool) + { + status = NDIS_STATUS_RESOURCES; + } + + if (status == NDIS_STATUS_SUCCESS) + { + status = NdisMRegisterInterruptEx(pContext->MiniportHandle, pContext, &mic, &pContext->InterruptHandle); + } + +#ifdef DBG + if (pContext->bUsingMSIX) + { + DPrintf(0, (""[%s] MSIX message table %savailable, count = %u\n"", __FUNCTION__, (mic.MessageInfoTable == nullptr ? ""not "" : """"), + (mic.MessageInfoTable == nullptr ? 0 : mic.MessageInfoTable->MessageCount))); + } + else + { + DPrintf(0, (""[%s] Not using MSIX\n"", __FUNCTION__)); + } +#endif + + if (status == NDIS_STATUS_SUCCESS) + { + NDIS_SG_DMA_DESCRIPTION sgDesc; + sgDesc.Header.Type = NDIS_OBJECT_TYPE_SG_DMA_DESCRIPTION; + sgDesc.Header.Revision = NDIS_SG_DMA_DESCRIPTION_REVISION_1; + sgDesc.Header.Size = sizeof(sgDesc); + sgDesc.Flags = NDIS_SG_DMA_64_BIT_ADDRESS; + sgDesc.MaximumPhysicalMapping = 0x10000; // 64K + sgDesc.ProcessSGListHandler = ProcessSGListHandler; + sgDesc.SharedMemAllocateCompleteHandler = SharedMemAllocateCompleteHandler; + sgDesc.ScatterGatherListSize = 0; // OUT value + status = NdisMRegisterScatterGatherDma(pContext->MiniportHandle, &sgDesc, &pContext->DmaHandle); + if (status != NDIS_STATUS_SUCCESS) + { + DPrintf(0, (""[%s] ERROR: NdisMRegisterScatterGatherDma failed (%X)!\n"", __FUNCTION__, status)); + } + else + { + DPrintf(0, (""[%s] SG recommended size %d\n"", __FUNCTION__, sgDesc.ScatterGatherListSize)); + } + } + + if (status == NDIS_STATUS_SUCCESS) + { + if (NDIS_CONNECT_MESSAGE_BASED == mic.InterruptType) + { + pContext->pMSIXInfoTable = mic.MessageInfoTable; + } + else if (pContext->bUsingMSIX) + { + DPrintf(0, (""[%s] ERROR: Interrupt type %d, message table %p\n"", + __FUNCTION__, mic.InterruptType, mic.MessageInfoTable)); + status = NDIS_STATUS_RESOURCE_CONFLICT; + } + ParaNdis6_ApplyOffloadPersistentConfiguration(pContext); + DebugParseOffloadBits(); + } + DEBUG_EXIT_STATUS(0, status); + return status; +} +",0,"NDIS_STATUS ParaNdis_FinishSpecificInitialization(PARANDIS_ADAPTER *pContext) +{ + NDIS_STATUS status = NDIS_STATUS_SUCCESS; + NET_BUFFER_LIST_POOL_PARAMETERS PoolParams; + NDIS_MINIPORT_INTERRUPT_CHARACTERISTICS mic; + DEBUG_ENTRY(0); + + NdisZeroMemory(&mic, sizeof(mic)); + mic.Header.Type = NDIS_OBJECT_TYPE_MINIPORT_INTERRUPT; + mic.Header.Revision = NDIS_MINIPORT_INTERRUPT_REVISION_1; + mic.Header.Size = NDIS_SIZEOF_MINIPORT_INTERRUPT_CHARACTERISTICS_REVISION_1; + mic.DisableInterruptHandler = MiniportDisableInterruptEx; + mic.EnableInterruptHandler = MiniportEnableInterruptEx; + mic.InterruptDpcHandler = MiniportInterruptDPC; + mic.InterruptHandler = MiniportInterrupt; + if (pContext->bUsingMSIX) + { + mic.MsiSupported = TRUE; + mic.MsiSyncWithAllMessages = TRUE; + mic.EnableMessageInterruptHandler = MiniportEnableMSIInterrupt; + mic.DisableMessageInterruptHandler = MiniportDisableMSIInterrupt; + mic.MessageInterruptHandler = MiniportMSIInterrupt; + mic.MessageInterruptDpcHandler = MiniportMSIInterruptDpc; + } + PoolParams.Header.Type = NDIS_OBJECT_TYPE_DEFAULT; + PoolParams.Header.Size = sizeof(PoolParams); + PoolParams.Header.Revision = NET_BUFFER_LIST_POOL_PARAMETERS_REVISION_1; + PoolParams.ProtocolId = NDIS_PROTOCOL_ID_DEFAULT; + PoolParams.fAllocateNetBuffer = TRUE; + PoolParams.ContextSize = 0; + PoolParams.PoolTag = PARANDIS_MEMORY_TAG; + PoolParams.DataSize = 0; + + pContext->BufferListsPool = NdisAllocateNetBufferListPool(pContext->MiniportHandle, &PoolParams); + if (!pContext->BufferListsPool) + { + status = NDIS_STATUS_RESOURCES; + } + + if (status == NDIS_STATUS_SUCCESS) + { + status = NdisMRegisterInterruptEx(pContext->MiniportHandle, pContext, &mic, &pContext->InterruptHandle); + } + +#ifdef DBG + if (pContext->bUsingMSIX) + { + DPrintf(0, (""[%s] MSIX message table %savailable, count = %u\n"", __FUNCTION__, (mic.MessageInfoTable == nullptr ? ""not "" : """"), + (mic.MessageInfoTable == nullptr ? 0 : mic.MessageInfoTable->MessageCount))); + } + else + { + DPrintf(0, (""[%s] Not using MSIX\n"", __FUNCTION__)); + } +#endif + + if (status == NDIS_STATUS_SUCCESS) + { + NDIS_SG_DMA_DESCRIPTION sgDesc; + sgDesc.Header.Type = NDIS_OBJECT_TYPE_SG_DMA_DESCRIPTION; + sgDesc.Header.Revision = NDIS_SG_DMA_DESCRIPTION_REVISION_1; + sgDesc.Header.Size = sizeof(sgDesc); + sgDesc.Flags = NDIS_SG_DMA_64_BIT_ADDRESS; + sgDesc.MaximumPhysicalMapping = 0x10000; // 64K + sgDesc.ProcessSGListHandler = ProcessSGListHandler; + sgDesc.SharedMemAllocateCompleteHandler = SharedMemAllocateCompleteHandler; + sgDesc.ScatterGatherListSize = 0; // OUT value + status = NdisMRegisterScatterGatherDma(pContext->MiniportHandle, &sgDesc, &pContext->DmaHandle); + if (status != NDIS_STATUS_SUCCESS) + { + DPrintf(0, (""[%s] ERROR: NdisMRegisterScatterGatherDma failed (%X)!\n"", __FUNCTION__, status)); + } + else + { + DPrintf(0, (""[%s] SG recommended size %d\n"", __FUNCTION__, sgDesc.ScatterGatherListSize)); + } + } + + if (status == NDIS_STATUS_SUCCESS) + { + if (NDIS_CONNECT_MESSAGE_BASED == mic.InterruptType) + { + pContext->pMSIXInfoTable = mic.MessageInfoTable; + } + else if (pContext->bUsingMSIX) + { + DPrintf(0, (""[%s] ERROR: Interrupt type %d, message table %p\n"", + __FUNCTION__, mic.InterruptType, mic.MessageInfoTable)); + status = NDIS_STATUS_RESOURCE_CONFLICT; + } + ParaNdis6_ApplyOffloadPersistentConfiguration(pContext); + DebugParseOffloadBits(); + } + DEBUG_EXIT_STATUS(0, status); + return status; +} +","@@ -866,7 +866,7 @@ tPacketIndicationType ParaNdis_PrepareReceivedPacket( + pHeader->flags, + &pBuffersDesc->PhysicalPages[PARANDIS_FIRST_RX_DATA_PAGE], + pPacketInfo->dataLength, +- nBytesStripped); ++ nBytesStripped, TRUE); + if (csRes.value) + { + NDIS_TCP_IP_CHECKSUM_NET_BUFFER_LIST_INFO qCSInfo;",964,1295,2048 +17009,"xsltCopy(xsltTransformContextPtr ctxt, xmlNodePtr node, + xmlNodePtr inst, xsltStylePreCompPtr castedComp) +{ +#ifdef XSLT_REFACTORED + xsltStyleItemCopyPtr comp = (xsltStyleItemCopyPtr) castedComp; +#else + xsltStylePreCompPtr comp = castedComp; +#endif + xmlNodePtr copy, oldInsert; + + oldInsert = ctxt->insert; + if (ctxt->insert != NULL) { + switch (node->type) { + case XML_TEXT_NODE: + case XML_CDATA_SECTION_NODE: + /* + * This text comes from the stylesheet + * For stylesheets, the set of whitespace-preserving + * element names consists of just xsl:text. + */ +#ifdef WITH_XSLT_DEBUG_PROCESS + if (node->type == XML_CDATA_SECTION_NODE) { + XSLT_TRACE(ctxt,XSLT_TRACE_COPY,xsltGenericDebug(xsltGenericDebugContext, + ""xsltCopy: CDATA text %s\n"", node->content)); + } else { + XSLT_TRACE(ctxt,XSLT_TRACE_COPY,xsltGenericDebug(xsltGenericDebugContext, + ""xsltCopy: text %s\n"", node->content)); + } +#endif + xsltCopyText(ctxt, ctxt->insert, node, 0); + break; + case XML_DOCUMENT_NODE: + case XML_HTML_DOCUMENT_NODE: + break; + case XML_ELEMENT_NODE: + /* + * REVISIT NOTE: The ""fake"" is a doc-node, not an element node. + * REMOVED: + * if (xmlStrEqual(node->name, BAD_CAST "" fake node libxslt"")) + * return; + */ + +#ifdef WITH_XSLT_DEBUG_PROCESS + XSLT_TRACE(ctxt,XSLT_TRACE_COPY,xsltGenericDebug(xsltGenericDebugContext, + ""xsltCopy: node %s\n"", node->name)); +#endif + copy = xsltShallowCopyElem(ctxt, node, ctxt->insert, 0); + ctxt->insert = copy; + if (comp->use != NULL) { + xsltApplyAttributeSet(ctxt, node, inst, comp->use); + } + break; + case XML_ATTRIBUTE_NODE: { +#ifdef WITH_XSLT_DEBUG_PROCESS + XSLT_TRACE(ctxt,XSLT_TRACE_COPY,xsltGenericDebug(xsltGenericDebugContext, + ""xsltCopy: attribute %s\n"", node->name)); +#endif + /* + * REVISIT: We could also raise an error if the parent is not + * an element node. + * OPTIMIZE TODO: Can we set the value/children of the + * attribute without an intermediate copy of the string value? + */ + xsltShallowCopyAttr(ctxt, inst, ctxt->insert, (xmlAttrPtr) node); + break; + } + case XML_PI_NODE: +#ifdef WITH_XSLT_DEBUG_PROCESS + XSLT_TRACE(ctxt,XSLT_TRACE_COPY,xsltGenericDebug(xsltGenericDebugContext, + ""xsltCopy: PI %s\n"", node->name)); +#endif + copy = xmlNewDocPI(ctxt->insert->doc, node->name, + node->content); + copy = xsltAddChild(ctxt->insert, copy); + break; + case XML_COMMENT_NODE: +#ifdef WITH_XSLT_DEBUG_PROCESS + XSLT_TRACE(ctxt,XSLT_TRACE_COPY,xsltGenericDebug(xsltGenericDebugContext, + ""xsltCopy: comment\n"")); +#endif + copy = xmlNewComment(node->content); + copy = xsltAddChild(ctxt->insert, copy); + break; + case XML_NAMESPACE_DECL: +#ifdef WITH_XSLT_DEBUG_PROCESS + XSLT_TRACE(ctxt,XSLT_TRACE_COPY,xsltGenericDebug(xsltGenericDebugContext, + ""xsltCopy: namespace declaration\n"")); +#endif + xsltShallowCopyNsNode(ctxt, inst, ctxt->insert, (xmlNsPtr)node); + break; + default: + break; + + } + } + + switch (node->type) { + case XML_DOCUMENT_NODE: + case XML_HTML_DOCUMENT_NODE: + case XML_ELEMENT_NODE: + xsltApplySequenceConstructor(ctxt, ctxt->node, inst->children, + NULL); + break; + default: + break; + } + ctxt->insert = oldInsert; +} +",0,"xsltCopy(xsltTransformContextPtr ctxt, xmlNodePtr node, + xmlNodePtr inst, xsltStylePreCompPtr castedComp) +{ +#ifdef XSLT_REFACTORED + xsltStyleItemCopyPtr comp = (xsltStyleItemCopyPtr) castedComp; +#else + xsltStylePreCompPtr comp = castedComp; +#endif + xmlNodePtr copy, oldInsert; + + oldInsert = ctxt->insert; + if (ctxt->insert != NULL) { + switch (node->type) { + case XML_TEXT_NODE: + case XML_CDATA_SECTION_NODE: + /* + * This text comes from the stylesheet + * For stylesheets, the set of whitespace-preserving + * element names consists of just xsl:text. + */ +#ifdef WITH_XSLT_DEBUG_PROCESS + if (node->type == XML_CDATA_SECTION_NODE) { + XSLT_TRACE(ctxt,XSLT_TRACE_COPY,xsltGenericDebug(xsltGenericDebugContext, + ""xsltCopy: CDATA text %s\n"", node->content)); + } else { + XSLT_TRACE(ctxt,XSLT_TRACE_COPY,xsltGenericDebug(xsltGenericDebugContext, + ""xsltCopy: text %s\n"", node->content)); + } +#endif + xsltCopyText(ctxt, ctxt->insert, node, 0); + break; + case XML_DOCUMENT_NODE: + case XML_HTML_DOCUMENT_NODE: + break; + case XML_ELEMENT_NODE: + /* + * REVISIT NOTE: The ""fake"" is a doc-node, not an element node. + * REMOVED: + * if (xmlStrEqual(node->name, BAD_CAST "" fake node libxslt"")) + * return; + */ + +#ifdef WITH_XSLT_DEBUG_PROCESS + XSLT_TRACE(ctxt,XSLT_TRACE_COPY,xsltGenericDebug(xsltGenericDebugContext, + ""xsltCopy: node %s\n"", node->name)); +#endif + copy = xsltShallowCopyElem(ctxt, node, ctxt->insert, 0); + ctxt->insert = copy; + if (comp->use != NULL) { + xsltApplyAttributeSet(ctxt, node, inst, comp->use); + } + break; + case XML_ATTRIBUTE_NODE: { +#ifdef WITH_XSLT_DEBUG_PROCESS + XSLT_TRACE(ctxt,XSLT_TRACE_COPY,xsltGenericDebug(xsltGenericDebugContext, + ""xsltCopy: attribute %s\n"", node->name)); +#endif + /* + * REVISIT: We could also raise an error if the parent is not + * an element node. + * OPTIMIZE TODO: Can we set the value/children of the + * attribute without an intermediate copy of the string value? + */ + xsltShallowCopyAttr(ctxt, inst, ctxt->insert, (xmlAttrPtr) node); + break; + } + case XML_PI_NODE: +#ifdef WITH_XSLT_DEBUG_PROCESS + XSLT_TRACE(ctxt,XSLT_TRACE_COPY,xsltGenericDebug(xsltGenericDebugContext, + ""xsltCopy: PI %s\n"", node->name)); +#endif + copy = xmlNewDocPI(ctxt->insert->doc, node->name, + node->content); + copy = xsltAddChild(ctxt->insert, copy); + break; + case XML_COMMENT_NODE: +#ifdef WITH_XSLT_DEBUG_PROCESS + XSLT_TRACE(ctxt,XSLT_TRACE_COPY,xsltGenericDebug(xsltGenericDebugContext, + ""xsltCopy: comment\n"")); +#endif + copy = xmlNewComment(node->content); + copy = xsltAddChild(ctxt->insert, copy); + break; + case XML_NAMESPACE_DECL: +#ifdef WITH_XSLT_DEBUG_PROCESS + XSLT_TRACE(ctxt,XSLT_TRACE_COPY,xsltGenericDebug(xsltGenericDebugContext, + ""xsltCopy: namespace declaration\n"")); +#endif + xsltShallowCopyNsNode(ctxt, inst, ctxt->insert, (xmlNsPtr)node); + break; + default: + break; + + } + } + + switch (node->type) { + case XML_DOCUMENT_NODE: + case XML_HTML_DOCUMENT_NODE: + case XML_ELEMENT_NODE: + xsltApplySequenceConstructor(ctxt, ctxt->node, inst->children, + NULL); + break; + default: + break; + } + ctxt->insert = oldInsert; +} +","@@ -338,6 +338,104 @@ profCallgraphAdd(xsltTemplatePtr templ, xsltTemplatePtr parent) + } + } + ++/** ++ * xsltPreCompEval: ++ * @ctxt: transform context ++ * @node: context node ++ * @comp: precompiled expression ++ * ++ * Evaluate a precompiled XPath expression. ++ */ ++static xmlXPathObjectPtr ++xsltPreCompEval(xsltTransformContextPtr ctxt, xmlNodePtr node, ++ xsltStylePreCompPtr comp) { ++ xmlXPathObjectPtr res; ++ xmlXPathContextPtr xpctxt; ++ xmlNodePtr oldXPContextNode; ++ xmlNsPtr *oldXPNamespaces; ++ int oldXPProximityPosition, oldXPContextSize, oldXPNsNr; ++ ++ xpctxt = ctxt->xpathCtxt; ++ oldXPContextNode = xpctxt->node; ++ oldXPProximityPosition = xpctxt->proximityPosition; ++ oldXPContextSize = xpctxt->contextSize; ++ oldXPNsNr = xpctxt->nsNr; ++ oldXPNamespaces = xpctxt->namespaces; ++ ++ xpctxt->node = node; ++#ifdef XSLT_REFACTORED ++ if (comp->inScopeNs != NULL) { ++ xpctxt->namespaces = comp->inScopeNs->list; ++ xpctxt->nsNr = comp->inScopeNs->xpathNumber; ++ } else { ++ xpctxt->namespaces = NULL; ++ xpctxt->nsNr = 0; ++ } ++#else ++ xpctxt->namespaces = comp->nsList; ++ xpctxt->nsNr = comp->nsNr; ++#endif ++ ++ res = xmlXPathCompiledEval(comp->comp, xpctxt); ++ ++ xpctxt->node = oldXPContextNode; ++ xpctxt->proximityPosition = oldXPProximityPosition; ++ xpctxt->contextSize = oldXPContextSize; ++ xpctxt->nsNr = oldXPNsNr; ++ xpctxt->namespaces = oldXPNamespaces; ++ ++ return(res); ++} ++ ++/** ++ * xsltPreCompEvalToBoolean: ++ * @ctxt: transform context ++ * @node: context node ++ * @comp: precompiled expression ++ * ++ * Evaluate a precompiled XPath expression as boolean. ++ */ ++static int ++xsltPreCompEvalToBoolean(xsltTransformContextPtr ctxt, xmlNodePtr node, ++ xsltStylePreCompPtr comp) { ++ int res; ++ xmlXPathContextPtr xpctxt; ++ xmlNodePtr oldXPContextNode; ++ xmlNsPtr *oldXPNamespaces; ++ int oldXPProximityPosition, oldXPContextSize, oldXPNsNr; ++ ++ xpctxt = ctxt->xpathCtxt; ++ oldXPContextNode = xpctxt->node; ++ oldXPProximityPosition = xpctxt->proximityPosition; ++ oldXPContextSize = xpctxt->contextSize; ++ oldXPNsNr = xpctxt->nsNr; ++ oldXPNamespaces = xpctxt->namespaces; ++ ++ xpctxt->node = node; ++#ifdef XSLT_REFACTORED ++ if (comp->inScopeNs != NULL) { ++ xpctxt->namespaces = comp->inScopeNs->list; ++ xpctxt->nsNr = comp->inScopeNs->xpathNumber; ++ } else { ++ xpctxt->namespaces = NULL; ++ xpctxt->nsNr = 0; ++ } ++#else ++ xpctxt->namespaces = comp->nsList; ++ xpctxt->nsNr = comp->nsNr; ++#endif ++ ++ res = xmlXPathCompiledEvalToBoolean(comp->comp, xpctxt); ++ ++ xpctxt->node = oldXPContextNode; ++ xpctxt->proximityPosition = oldXPProximityPosition; ++ xpctxt->contextSize = oldXPContextSize; ++ xpctxt->nsNr = oldXPNsNr; ++ xpctxt->namespaces = oldXPNamespaces; ++ ++ return(res); ++} ++ + /************************************************************************ + * * + * XInclude default settings * +@@ -831,9 +929,9 @@ xsltCopyTextString(xsltTransformContextPtr ctxt, xmlNodePtr target, + } + copy = xmlNewTextLen(string, len); + } ++ if (copy != NULL && target != NULL) ++ copy = xsltAddChild(target, copy); + if (copy != NULL) { +- if (target != NULL) +- copy = xsltAddChild(target, copy); + ctxt->lasttext = copy->content; + ctxt->lasttsize = len; + ctxt->lasttuse = len; +@@ -1222,6 +1320,11 @@ xsltShallowCopyElem(xsltTransformContextPtr ctxt, xmlNodePtr node, + if (copy != NULL) { + copy->doc = ctxt->output; + copy = xsltAddChild(insert, copy); ++ if (copy == NULL) { ++ xsltTransformError(ctxt, NULL, node, ++ ""xsltShallowCopyElem: copy failed\n""); ++ return (copy); ++ } + + if (node->type == XML_ELEMENT_NODE) { + /* +@@ -1555,6 +1658,11 @@ xsltCopyTreeInternal(xsltTransformContextPtr ctxt, + if (copy != NULL) { + copy->doc = ctxt->output; + copy = xsltAddChild(insert, copy); ++ if (copy == NULL) { ++ xsltTransformError(ctxt, NULL, invocNode, ++ ""xsltCopyTreeInternal: Copying of '%s' failed.\n"", node->name); ++ return (copy); ++ } + /* + * The node may have been coalesced into another text node. + */ +@@ -3606,8 +3714,7 @@ xsltDocumentElem(xsltTransformContextPtr ctxt, xmlNodePtr node, + xmlDictReference(res->dict); + } else if (xmlStrEqual(method, (const xmlChar *) ""xhtml"")) { + xsltTransformError(ctxt, NULL, inst, +- ""xsltDocumentElem: unsupported method xhtml\n"", +- style->method); ++ ""xsltDocumentElem: unsupported method xhtml\n""); + ctxt->type = XSLT_OUTPUT_HTML; + res = htmlNewDocNoDtD(doctypeSystem, doctypePublic); + if (res == NULL) +@@ -3627,8 +3734,8 @@ xsltDocumentElem(xsltTransformContextPtr ctxt, xmlNodePtr node, + #endif + } else { + xsltTransformError(ctxt, NULL, inst, +- ""xsltDocumentElem: unsupported method %s\n"", +- style->method); ++ ""xsltDocumentElem: unsupported method (%s)\n"", ++ method); + goto error; + } + } else { +@@ -4034,6 +4141,11 @@ xsltElement(xsltTransformContextPtr ctxt, xmlNodePtr node, + return; + } + copy = xsltAddChild(ctxt->insert, copy); ++ if (copy == NULL) { ++ xsltTransformError(ctxt, NULL, inst, ++ ""xsl:element : xsltAddChild failed\n""); ++ return; ++ } + + /* + * Namespace +@@ -4287,11 +4399,6 @@ xsltCopyOf(xsltTransformContextPtr ctxt, xmlNodePtr node, + xmlXPathObjectPtr res = NULL; + xmlNodeSetPtr list = NULL; + int i; +- xmlDocPtr oldXPContextDoc; +- xmlNsPtr *oldXPNamespaces; +- xmlNodePtr oldXPContextNode; +- int oldXPProximityPosition, oldXPContextSize, oldXPNsNr; +- xmlXPathContextPtr xpctxt; + + if ((ctxt == NULL) || (node == NULL) || (inst == NULL)) + return; +@@ -4327,42 +4434,7 @@ xsltCopyOf(xsltTransformContextPtr ctxt, xmlNodePtr node, + /* + * Evaluate the ""select"" expression. + */ +- xpctxt = ctxt->xpathCtxt; +- oldXPContextDoc = xpctxt->doc; +- oldXPContextNode = xpctxt->node; +- oldXPProximityPosition = xpctxt->proximityPosition; +- oldXPContextSize = xpctxt->contextSize; +- oldXPNsNr = xpctxt->nsNr; +- oldXPNamespaces = xpctxt->namespaces; +- +- xpctxt->node = node; +- if (comp != NULL) { +- +-#ifdef XSLT_REFACTORED +- if (comp->inScopeNs != NULL) { +- xpctxt->namespaces = comp->inScopeNs->list; +- xpctxt->nsNr = comp->inScopeNs->xpathNumber; +- } else { +- xpctxt->namespaces = NULL; +- xpctxt->nsNr = 0; +- } +-#else +- xpctxt->namespaces = comp->nsList; +- xpctxt->nsNr = comp->nsNr; +-#endif +- } else { +- xpctxt->namespaces = NULL; +- xpctxt->nsNr = 0; +- } +- +- res = xmlXPathCompiledEval(comp->comp, xpctxt); +- +- xpctxt->doc = oldXPContextDoc; +- xpctxt->node = oldXPContextNode; +- xpctxt->contextSize = oldXPContextSize; +- xpctxt->proximityPosition = oldXPProximityPosition; +- xpctxt->nsNr = oldXPNsNr; +- xpctxt->namespaces = oldXPNamespaces; ++ res = xsltPreCompEval(ctxt, node, comp); + + if (res != NULL) { + if (res->type == XPATH_NODESET) { +@@ -4472,11 +4544,6 @@ xsltValueOf(xsltTransformContextPtr ctxt, xmlNodePtr node, + #endif + xmlXPathObjectPtr res = NULL; + xmlChar *value = NULL; +- xmlDocPtr oldXPContextDoc; +- xmlNsPtr *oldXPNamespaces; +- xmlNodePtr oldXPContextNode; +- int oldXPProximityPosition, oldXPContextSize, oldXPNsNr; +- xmlXPathContextPtr xpctxt; + + if ((ctxt == NULL) || (node == NULL) || (inst == NULL)) + return; +@@ -4493,42 +4560,7 @@ xsltValueOf(xsltTransformContextPtr ctxt, xmlNodePtr node, + ""xsltValueOf: select %s\n"", comp->select)); + #endif + +- xpctxt = ctxt->xpathCtxt; +- oldXPContextDoc = xpctxt->doc; +- oldXPContextNode = xpctxt->node; +- oldXPProximityPosition = xpctxt->proximityPosition; +- oldXPContextSize = xpctxt->contextSize; +- oldXPNsNr = xpctxt->nsNr; +- oldXPNamespaces = xpctxt->namespaces; +- +- xpctxt->node = node; +- if (comp != NULL) { +- +-#ifdef XSLT_REFACTORED +- if (comp->inScopeNs != NULL) { +- xpctxt->namespaces = comp->inScopeNs->list; +- xpctxt->nsNr = comp->inScopeNs->xpathNumber; +- } else { +- xpctxt->namespaces = NULL; +- xpctxt->nsNr = 0; +- } +-#else +- xpctxt->namespaces = comp->nsList; +- xpctxt->nsNr = comp->nsNr; +-#endif +- } else { +- xpctxt->namespaces = NULL; +- xpctxt->nsNr = 0; +- } +- +- res = xmlXPathCompiledEval(comp->comp, xpctxt); +- +- xpctxt->doc = oldXPContextDoc; +- xpctxt->node = oldXPContextNode; +- xpctxt->contextSize = oldXPContextSize; +- xpctxt->proximityPosition = oldXPProximityPosition; +- xpctxt->nsNr = oldXPNsNr; +- xpctxt->namespaces = oldXPNamespaces; ++ res = xsltPreCompEval(ctxt, node, comp); + + /* + * Cast the XPath object to string. +@@ -4584,6 +4616,10 @@ xsltNumber(xsltTransformContextPtr ctxt, xmlNodePtr node, + #else + xsltStylePreCompPtr comp = castedComp; + #endif ++ xmlXPathContextPtr xpctxt; ++ xmlNsPtr *oldXPNamespaces; ++ int oldXPNsNr; ++ + if (comp == NULL) { + xsltTransformError(ctxt, NULL, inst, + ""xsl:number : compilation failed\n""); +@@ -4596,7 +4632,27 @@ xsltNumber(xsltTransformContextPtr ctxt, xmlNodePtr node, + comp->numdata.doc = inst->doc; + comp->numdata.node = inst; + ++ xpctxt = ctxt->xpathCtxt; ++ oldXPNsNr = xpctxt->nsNr; ++ oldXPNamespaces = xpctxt->namespaces; ++ ++#ifdef XSLT_REFACTORED ++ if (comp->inScopeNs != NULL) { ++ xpctxt->namespaces = comp->inScopeNs->list; ++ xpctxt->nsNr = comp->inScopeNs->xpathNumber; ++ } else { ++ xpctxt->namespaces = NULL; ++ xpctxt->nsNr = 0; ++ } ++#else ++ xpctxt->namespaces = comp->nsList; ++ xpctxt->nsNr = comp->nsNr; ++#endif ++ + xsltNumberFormat(ctxt, &comp->numdata, node); ++ ++ xpctxt->nsNr = oldXPNsNr; ++ xpctxt->namespaces = oldXPNamespaces; + } + + /** +@@ -4790,12 +4846,11 @@ xsltApplyTemplates(xsltTransformContextPtr ctxt, xmlNodePtr node, + xmlNodePtr cur, delNode = NULL, oldContextNode; + xmlNodeSetPtr list = NULL, oldList; + xsltStackElemPtr withParams = NULL; +- int oldXPProximityPosition, oldXPContextSize, oldXPNsNr; ++ int oldXPProximityPosition, oldXPContextSize; + const xmlChar *oldMode, *oldModeURI; + xmlDocPtr oldXPDoc; + xsltDocumentPtr oldDocInfo; + xmlXPathContextPtr xpctxt; +- xmlNsPtr *oldXPNamespaces; + + if (comp == NULL) { + xsltTransformError(ctxt, NULL, inst, +@@ -4829,8 +4884,6 @@ xsltApplyTemplates(xsltTransformContextPtr ctxt, xmlNodePtr node, + oldXPContextSize = xpctxt->contextSize; + oldXPProximityPosition = xpctxt->proximityPosition; + oldXPDoc = xpctxt->doc; +- oldXPNsNr = xpctxt->nsNr; +- oldXPNamespaces = xpctxt->namespaces; + + /* + * Set up contexts. +@@ -4851,26 +4904,8 @@ xsltApplyTemplates(xsltTransformContextPtr ctxt, xmlNodePtr node, + ""xsltApplyTemplates: select %s\n"", comp->select)); + #endif + +- /* +- * Set up XPath. +- */ +- xpctxt->node = node; /* Set the ""context node"" */ +-#ifdef XSLT_REFACTORED +- if (comp->inScopeNs != NULL) { +- xpctxt->namespaces = comp->inScopeNs->list; +- xpctxt->nsNr = comp->inScopeNs->xpathNumber; +- } else { +- xpctxt->namespaces = NULL; +- xpctxt->nsNr = 0; +- } +-#else +- xpctxt->namespaces = comp->nsList; +- xpctxt->nsNr = comp->nsNr; +-#endif +- res = xmlXPathCompiledEval(comp->comp, xpctxt); ++ res = xsltPreCompEval(ctxt, node, comp); + +- xpctxt->contextSize = oldXPContextSize; +- xpctxt->proximityPosition = oldXPProximityPosition; + if (res != NULL) { + if (res->type == XPATH_NODESET) { + list = res->nodesetval; /* consume the node set */ +@@ -5153,8 +5188,6 @@ xsltApplyTemplates(xsltTransformContextPtr ctxt, xmlNodePtr node, + /* + * Restore context states. + */ +- xpctxt->nsNr = oldXPNsNr; +- xpctxt->namespaces = oldXPNamespaces; + xpctxt->doc = oldXPDoc; + xpctxt->contextSize = oldXPContextSize; + xpctxt->proximityPosition = oldXPProximityPosition; +@@ -5210,12 +5243,6 @@ xsltChoose(xsltTransformContextPtr ctxt, xmlNodePtr contextNode, + + { + int testRes = 0, res = 0; +- xmlXPathContextPtr xpctxt = ctxt->xpathCtxt; +- xmlDocPtr oldXPContextDoc = xpctxt->doc; +- int oldXPProximityPosition = xpctxt->proximityPosition; +- int oldXPContextSize = xpctxt->contextSize; +- xmlNsPtr *oldXPNamespaces = xpctxt->namespaces; +- int oldXPNsNr = xpctxt->nsNr; + + #ifdef XSLT_REFACTORED + xsltStyleItemWhenPtr wcomp = NULL; +@@ -5252,27 +5279,8 @@ xsltChoose(xsltTransformContextPtr ctxt, xmlNodePtr contextNode, + ""xsltChoose: test %s\n"", wcomp->test)); + #endif + +- xpctxt->node = contextNode; +- xpctxt->doc = oldXPContextDoc; +- xpctxt->proximityPosition = oldXPProximityPosition; +- xpctxt->contextSize = oldXPContextSize; +- +-#ifdef XSLT_REFACTORED +- if (wcomp->inScopeNs != NULL) { +- xpctxt->namespaces = wcomp->inScopeNs->list; +- xpctxt->nsNr = wcomp->inScopeNs->xpathNumber; +- } else { +- xpctxt->namespaces = NULL; +- xpctxt->nsNr = 0; +- } +-#else +- xpctxt->namespaces = wcomp->nsList; +- xpctxt->nsNr = wcomp->nsNr; +-#endif +- +- + #ifdef XSLT_FAST_IF +- res = xmlXPathCompiledEvalToBoolean(wcomp->comp, xpctxt); ++ res = xsltPreCompEvalToBoolean(ctxt, contextNode, wcomp); + + if (res == -1) { + ctxt->state = XSLT_STATE_STOPPED; +@@ -5282,7 +5290,7 @@ xsltChoose(xsltTransformContextPtr ctxt, xmlNodePtr contextNode, + + #else /* XSLT_FAST_IF */ + +- res = xmlXPathCompiledEval(wcomp->comp, xpctxt); ++ res = xsltPreCompEval(ctxt, cotextNode, wcomp); + + if (res != NULL) { + if (res->type != XPATH_BOOLEAN) +@@ -5331,22 +5339,10 @@ xsltChoose(xsltTransformContextPtr ctxt, xmlNodePtr contextNode, + #endif + goto test_is_true; + } +- xpctxt->node = contextNode; +- xpctxt->doc = oldXPContextDoc; +- xpctxt->proximityPosition = oldXPProximityPosition; +- xpctxt->contextSize = oldXPContextSize; +- xpctxt->namespaces = oldXPNamespaces; +- xpctxt->nsNr = oldXPNsNr; + goto exit; + + test_is_true: + +- xpctxt->node = contextNode; +- xpctxt->doc = oldXPContextDoc; +- xpctxt->proximityPosition = oldXPProximityPosition; +- xpctxt->contextSize = oldXPContextSize; +- xpctxt->namespaces = oldXPNamespaces; +- xpctxt->nsNr = oldXPNsNr; + goto process_sequence; + } + +@@ -5400,52 +5396,16 @@ xsltIf(xsltTransformContextPtr ctxt, xmlNodePtr contextNode, + + #ifdef XSLT_FAST_IF + { +- xmlXPathContextPtr xpctxt = ctxt->xpathCtxt; +- xmlDocPtr oldXPContextDoc = xpctxt->doc; +- xmlNsPtr *oldXPNamespaces = xpctxt->namespaces; +- xmlNodePtr oldXPContextNode = xpctxt->node; +- int oldXPProximityPosition = xpctxt->proximityPosition; +- int oldXPContextSize = xpctxt->contextSize; +- int oldXPNsNr = xpctxt->nsNr; + xmlDocPtr oldLocalFragmentTop = ctxt->localRVT; + +- xpctxt->node = contextNode; +- if (comp != NULL) { +- +-#ifdef XSLT_REFACTORED +- if (comp->inScopeNs != NULL) { +- xpctxt->namespaces = comp->inScopeNs->list; +- xpctxt->nsNr = comp->inScopeNs->xpathNumber; +- } else { +- xpctxt->namespaces = NULL; +- xpctxt->nsNr = 0; +- } +-#else +- xpctxt->namespaces = comp->nsList; +- xpctxt->nsNr = comp->nsNr; +-#endif +- } else { +- xpctxt->namespaces = NULL; +- xpctxt->nsNr = 0; +- } +- /* +- * This XPath function is optimized for boolean results. +- */ +- res = xmlXPathCompiledEvalToBoolean(comp->comp, xpctxt); ++ res = xsltPreCompEvalToBoolean(ctxt, contextNode, comp); + + /* + * Cleanup fragments created during evaluation of the + * ""select"" expression. + */ + if (oldLocalFragmentTop != ctxt->localRVT) + xsltReleaseLocalRVTs(ctxt, oldLocalFragmentTop); +- +- xpctxt->doc = oldXPContextDoc; +- xpctxt->node = oldXPContextNode; +- xpctxt->contextSize = oldXPContextSize; +- xpctxt->proximityPosition = oldXPProximityPosition; +- xpctxt->nsNr = oldXPNsNr; +- xpctxt->namespaces = oldXPNamespaces; + } + + #ifdef WITH_XSLT_DEBUG_PROCESS +@@ -5467,51 +5427,10 @@ xsltIf(xsltTransformContextPtr ctxt, xmlNodePtr contextNode, + + #else /* XSLT_FAST_IF */ + { +- xmlXPathObjectPtr xpobj = NULL; + /* + * OLD CODE: + */ +- { +- xmlXPathContextPtr xpctxt = ctxt->xpathCtxt; +- xmlDocPtr oldXPContextDoc = xpctxt->doc; +- xmlNsPtr *oldXPNamespaces = xpctxt->namespaces; +- xmlNodePtr oldXPContextNode = xpctxt->node; +- int oldXPProximityPosition = xpctxt->proximityPosition; +- int oldXPContextSize = xpctxt->contextSize; +- int oldXPNsNr = xpctxt->nsNr; +- +- xpctxt->node = contextNode; +- if (comp != NULL) { +- +-#ifdef XSLT_REFACTORED +- if (comp->inScopeNs != NULL) { +- xpctxt->namespaces = comp->inScopeNs->list; +- xpctxt->nsNr = comp->inScopeNs->xpathNumber; +- } else { +- xpctxt->namespaces = NULL; +- xpctxt->nsNr = 0; +- } +-#else +- xpctxt->namespaces = comp->nsList; +- xpctxt->nsNr = comp->nsNr; +-#endif +- } else { +- xpctxt->namespaces = NULL; +- xpctxt->nsNr = 0; +- } +- +- /* +- * This XPath function is optimized for boolean results. +- */ +- xpobj = xmlXPathCompiledEval(comp->comp, xpctxt); +- +- xpctxt->doc = oldXPContextDoc; +- xpctxt->node = oldXPContextNode; +- xpctxt->contextSize = oldXPContextSize; +- xpctxt->proximityPosition = oldXPProximityPosition; +- xpctxt->nsNr = oldXPNsNr; +- xpctxt->namespaces = oldXPNamespaces; +- } ++ xmlXPathObjectPtr xpobj = xsltPreCompEval(ctxt, contextNode, comp); + if (xpobj != NULL) { + if (xpobj->type != XPATH_BOOLEAN) + xpobj = xmlXPathConvertBoolean(xpobj); +@@ -5618,27 +5537,11 @@ xsltForEach(xsltTransformContextPtr ctxt, xmlNodePtr contextNode, + oldXPDoc = xpctxt->doc; + oldXPProximityPosition = xpctxt->proximityPosition; + oldXPContextSize = xpctxt->contextSize; +- /* +- * Set up XPath. +- */ +- xpctxt->node = contextNode; +-#ifdef XSLT_REFACTORED +- if (comp->inScopeNs != NULL) { +- xpctxt->namespaces = comp->inScopeNs->list; +- xpctxt->nsNr = comp->inScopeNs->xpathNumber; +- } else { +- xpctxt->namespaces = NULL; +- xpctxt->nsNr = 0; +- } +-#else +- xpctxt->namespaces = comp->nsList; +- xpctxt->nsNr = comp->nsNr; +-#endif + + /* + * Evaluate the 'select' expression. + */ +- res = xmlXPathCompiledEval(comp->comp, ctxt->xpathCtxt); ++ res = xsltPreCompEval(ctxt, contextNode, comp); + + if (res != NULL) { + if (res->type == XPATH_NODESET) +@@ -5668,13 +5571,6 @@ xsltForEach(xsltTransformContextPtr ctxt, xmlNodePtr contextNode, + ""xsltForEach: select evaluates to %d nodes\n"", list->nodeNr)); + #endif + +- /* +- * Restore XPath states for the ""current node"". +- */ +- xpctxt->contextSize = oldXPContextSize; +- xpctxt->proximityPosition = oldXPProximityPosition; +- xpctxt->node = contextNode; +- + /* + * Set the list; this has to be done already here for xsltDoSortFunction(). + */ +@@ -6076,8 +5972,7 @@ xsltApplyStylesheetInternal(xsltStylesheetPtr style, xmlDocPtr doc, + #endif + } else if (xmlStrEqual(method, (const xmlChar *) ""xhtml"")) { + xsltTransformError(ctxt, NULL, (xmlNodePtr) doc, +- ""xsltApplyStylesheetInternal: unsupported method xhtml, using html\n"", +- style->method); ++ ""xsltApplyStylesheetInternal: unsupported method xhtml, using html\n""); + ctxt->type = XSLT_OUTPUT_HTML; + res = htmlNewDoc(doctypeSystem, doctypePublic); + if (res == NULL) +@@ -6103,8 +5998,8 @@ xsltApplyStylesheetInternal(xsltStylesheetPtr style, xmlDocPtr doc, + #endif + } else { + xsltTransformError(ctxt, NULL, (xmlNodePtr) doc, +- ""xsltApplyStylesheetInternal: unsupported method %s\n"", +- style->method); ++ ""xsltApplyStylesheetInternal: unsupported method (%s)\n"", ++ method); + goto error; + } + } else {",946,1277,2048 +18167,"static Image *ReadMVGImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ +#define BoundingBox ""viewbox"" + + DrawInfo + *draw_info; + + Image + *image; + + MagickBooleanType + status; + + /* + 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); + } + if ((image->columns == 0) || (image->rows == 0)) + { + char + primitive[MaxTextExtent]; + + register char + *p; + + SegmentInfo + bounds; + + /* + Determine size of image canvas. + */ + while (ReadBlobString(image,primitive) != (char *) NULL) + { + for (p=primitive; (*p == ' ') || (*p == '\t'); p++) ; + if (LocaleNCompare(BoundingBox,p,strlen(BoundingBox)) != 0) + continue; + (void) sscanf(p,""viewbox %lf %lf %lf %lf"",&bounds.x1,&bounds.y1, + &bounds.x2,&bounds.y2); + image->columns=(size_t) floor((bounds.x2-bounds.x1)+0.5); + image->rows=(size_t) floor((bounds.y2-bounds.y1)+0.5); + break; + } + } + if ((image->columns == 0) || (image->rows == 0)) + ThrowReaderException(OptionError,""MustSpecifyImageSize""); + draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); + draw_info->affine.sx=image->x_resolution == 0.0 ? 1.0 : image->x_resolution/ + DefaultResolution; + draw_info->affine.sy=image->y_resolution == 0.0 ? 1.0 : image->y_resolution/ + DefaultResolution; + image->columns=(size_t) (draw_info->affine.sx*image->columns); + image->rows=(size_t) (draw_info->affine.sy*image->rows); + if (SetImageBackgroundColor(image) == MagickFalse) + { + InheritException(exception,&image->exception); + image=DestroyImageList(image); + return((Image *) NULL); + } + /* + Render drawing. + */ + if (GetBlobStreamData(image) == (unsigned char *) NULL) + draw_info->primitive=FileToString(image->filename,~0UL,exception); + else + { + draw_info->primitive=(char *) AcquireMagickMemory(GetBlobSize(image)+1); + if (draw_info->primitive != (char *) NULL) + { + CopyMagickMemory(draw_info->primitive,GetBlobStreamData(image), + GetBlobSize(image)); + draw_info->primitive[GetBlobSize(image)]='\0'; + } + } + (void) DrawImage(image,draw_info); + draw_info=DestroyDrawInfo(draw_info); + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +",1,"static Image *ReadMVGImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ +#define BoundingBox ""viewbox"" + + DrawInfo + *draw_info; + + Image + *image; + + MagickBooleanType + status; + + /* + 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); + } + if ((image->columns == 0) || (image->rows == 0)) + { + char + primitive[MaxTextExtent]; + + register char + *p; + + SegmentInfo + bounds; + + /* + Determine size of image canvas. + */ + while (ReadBlobString(image,primitive) != (char *) NULL) + { + for (p=primitive; (*p == ' ') || (*p == '\t'); p++) ; + if (LocaleNCompare(BoundingBox,p,strlen(BoundingBox)) != 0) + continue; + (void) sscanf(p,""viewbox %lf %lf %lf %lf"",&bounds.x1,&bounds.y1, + &bounds.x2,&bounds.y2); + image->columns=(size_t) floor((bounds.x2-bounds.x1)+0.5); + image->rows=(size_t) floor((bounds.y2-bounds.y1)+0.5); + break; + } + } + if ((image->columns == 0) || (image->rows == 0)) + ThrowReaderException(OptionError,""MustSpecifyImageSize""); + draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); + draw_info->affine.sx=image->x_resolution == 0.0 ? 1.0 : image->x_resolution/ + DefaultResolution; + draw_info->affine.sy=image->y_resolution == 0.0 ? 1.0 : image->y_resolution/ + DefaultResolution; + image->columns=(size_t) (draw_info->affine.sx*image->columns); + image->rows=(size_t) (draw_info->affine.sy*image->rows); + status=SetImageExtent(image,image->columns,image->rows); + if (status == MagickFalse) + { + InheritException(exception,&image->exception); + return(DestroyImageList(image)); + } + if (SetImageBackgroundColor(image) == MagickFalse) + { + InheritException(exception,&image->exception); + image=DestroyImageList(image); + return((Image *) NULL); + } + /* + Render drawing. + */ + if (GetBlobStreamData(image) == (unsigned char *) NULL) + draw_info->primitive=FileToString(image->filename,~0UL,exception); + else + { + draw_info->primitive=(char *) AcquireMagickMemory(GetBlobSize(image)+1); + if (draw_info->primitive != (char *) NULL) + { + CopyMagickMemory(draw_info->primitive,GetBlobStreamData(image), + GetBlobSize(image)); + draw_info->primitive[GetBlobSize(image)]='\0'; + } + } + (void) DrawImage(image,draw_info); + draw_info=DestroyDrawInfo(draw_info); + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +","@@ -190,6 +190,12 @@ static Image *ReadMVGImage(const ImageInfo *image_info,ExceptionInfo *exception) + DefaultResolution; + image->columns=(size_t) (draw_info->affine.sx*image->columns); + image->rows=(size_t) (draw_info->affine.sy*image->rows); ++ status=SetImageExtent(image,image->columns,image->rows); ++ if (status == MagickFalse) ++ { ++ InheritException(exception,&image->exception); ++ return(DestroyImageList(image)); ++ } + if (SetImageBackgroundColor(image) == MagickFalse) + { + InheritException(exception,&image->exception);",748,1079,2048 +14614,"void WebGLRenderingContextBase::TexImageHelperImageBitmap( + TexImageFunctionID function_id, + GLenum target, + GLint level, + GLint internalformat, + GLenum format, + GLenum type, + GLint xoffset, + GLint yoffset, + GLint zoffset, + ImageBitmap* bitmap, + const IntRect& source_sub_rect, + GLsizei depth, + GLint unpack_image_height, + ExceptionState& exception_state) { + const char* func_name = GetTexImageFunctionName(function_id); + if (isContextLost()) + return; + if (!ValidateImageBitmap(func_name, bitmap, exception_state)) + return; + WebGLTexture* texture = + ValidateTexImageBinding(func_name, function_id, target); + if (!texture) + return; + + bool selecting_sub_rectangle = false; + if (!ValidateTexImageSubRectangle(func_name, function_id, bitmap, + source_sub_rect, depth, unpack_image_height, + &selecting_sub_rectangle)) { + return; + } + + TexImageFunctionType function_type; + if (function_id == kTexImage2D) + function_type = kTexImage; + else + function_type = kTexSubImage; + + GLsizei width = source_sub_rect.Width(); + GLsizei height = source_sub_rect.Height(); + if (!ValidateTexFunc(func_name, function_type, kSourceImageBitmap, target, + level, internalformat, width, height, depth, 0, format, + type, xoffset, yoffset, zoffset)) + return; + DCHECK(bitmap->BitmapImage()); + + if (function_id != kTexSubImage3D && function_id != kTexImage3D && + bitmap->IsAccelerated() && CanUseTexImageByGPU(format, type) && + !selecting_sub_rectangle) { + if (function_id == kTexImage2D) { + TexImage2DBase(target, level, internalformat, width, height, 0, format, + type, 0); + TexImageByGPU(function_id, texture, target, level, 0, 0, 0, bitmap, + source_sub_rect); + } else if (function_id == kTexSubImage2D) { + TexImageByGPU(function_id, texture, target, level, xoffset, yoffset, 0, + bitmap, source_sub_rect); + } + return; + } + sk_sp sk_image = bitmap->BitmapImage()->ImageForCurrentFrame(); + SkPixmap pixmap; + uint8_t* pixel_data_ptr = nullptr; + RefPtr pixel_data; + bool peek_succeed = sk_image->peekPixels(&pixmap); + if (peek_succeed) { + pixel_data_ptr = static_cast(pixmap.writable_addr()); + } else { + pixel_data = bitmap->CopyBitmapData( + bitmap->IsPremultiplied() ? kPremultiplyAlpha : kDontPremultiplyAlpha); + pixel_data_ptr = pixel_data->Data(); + } + Vector data; + bool need_conversion = true; + bool have_peekable_rgba = + (peek_succeed && + pixmap.colorType() == SkColorType::kRGBA_8888_SkColorType); + bool is_pixel_data_rgba = (have_peekable_rgba || !peek_succeed); + if (is_pixel_data_rgba && format == GL_RGBA && type == GL_UNSIGNED_BYTE && + !selecting_sub_rectangle && depth == 1) { + need_conversion = false; + } else { + if (type == GL_UNSIGNED_INT_10F_11F_11F_REV) { + type = GL_FLOAT; + } + bool is_pixel_data_bgra = + pixmap.colorType() == SkColorType::kBGRA_8888_SkColorType; + if ((is_pixel_data_bgra && + !WebGLImageConversion::ExtractImageData( + pixel_data_ptr, WebGLImageConversion::DataFormat::kDataFormatBGRA8, + bitmap->Size(), source_sub_rect, depth, unpack_image_height, + format, type, false, false, data)) || + (is_pixel_data_rgba && + !WebGLImageConversion::ExtractImageData( + pixel_data_ptr, WebGLImageConversion::DataFormat::kDataFormatRGBA8, + bitmap->Size(), source_sub_rect, depth, unpack_image_height, + format, type, false, false, data))) { + SynthesizeGLError(GL_INVALID_VALUE, func_name, ""bad image data""); + return; + } + } + ScopedUnpackParametersResetRestore temporary_reset_unpack(this); + if (function_id == kTexImage2D) { + TexImage2DBase(target, level, internalformat, width, height, 0, format, + type, need_conversion ? data.data() : pixel_data_ptr); + } else if (function_id == kTexSubImage2D) { + ContextGL()->TexSubImage2D(target, level, xoffset, yoffset, width, height, + format, type, + need_conversion ? data.data() : pixel_data_ptr); + } else if (function_id == kTexImage3D) { + ContextGL()->TexImage3D(target, level, internalformat, width, height, depth, + 0, format, type, + need_conversion ? data.data() : pixel_data_ptr); + } else { + DCHECK_EQ(function_id, kTexSubImage3D); + ContextGL()->TexSubImage3D(target, level, xoffset, yoffset, zoffset, width, + height, depth, format, type, + need_conversion ? data.data() : pixel_data_ptr); + } +} +",0,"void WebGLRenderingContextBase::TexImageHelperImageBitmap( + TexImageFunctionID function_id, + GLenum target, + GLint level, + GLint internalformat, + GLenum format, + GLenum type, + GLint xoffset, + GLint yoffset, + GLint zoffset, + ImageBitmap* bitmap, + const IntRect& source_sub_rect, + GLsizei depth, + GLint unpack_image_height, + ExceptionState& exception_state) { + const char* func_name = GetTexImageFunctionName(function_id); + if (isContextLost()) + return; + if (!ValidateImageBitmap(func_name, bitmap, exception_state)) + return; + WebGLTexture* texture = + ValidateTexImageBinding(func_name, function_id, target); + if (!texture) + return; + + bool selecting_sub_rectangle = false; + if (!ValidateTexImageSubRectangle(func_name, function_id, bitmap, + source_sub_rect, depth, unpack_image_height, + &selecting_sub_rectangle)) { + return; + } + + TexImageFunctionType function_type; + if (function_id == kTexImage2D) + function_type = kTexImage; + else + function_type = kTexSubImage; + + GLsizei width = source_sub_rect.Width(); + GLsizei height = source_sub_rect.Height(); + if (!ValidateTexFunc(func_name, function_type, kSourceImageBitmap, target, + level, internalformat, width, height, depth, 0, format, + type, xoffset, yoffset, zoffset)) + return; + DCHECK(bitmap->BitmapImage()); + + if (function_id != kTexSubImage3D && function_id != kTexImage3D && + bitmap->IsAccelerated() && CanUseTexImageByGPU(format, type) && + !selecting_sub_rectangle) { + if (function_id == kTexImage2D) { + TexImage2DBase(target, level, internalformat, width, height, 0, format, + type, 0); + TexImageByGPU(function_id, texture, target, level, 0, 0, 0, bitmap, + source_sub_rect); + } else if (function_id == kTexSubImage2D) { + TexImageByGPU(function_id, texture, target, level, xoffset, yoffset, 0, + bitmap, source_sub_rect); + } + return; + } + sk_sp sk_image = bitmap->BitmapImage()->ImageForCurrentFrame(); + SkPixmap pixmap; + uint8_t* pixel_data_ptr = nullptr; + RefPtr pixel_data; + bool peek_succeed = sk_image->peekPixels(&pixmap); + if (peek_succeed) { + pixel_data_ptr = static_cast(pixmap.writable_addr()); + } else { + pixel_data = bitmap->CopyBitmapData( + bitmap->IsPremultiplied() ? kPremultiplyAlpha : kDontPremultiplyAlpha); + pixel_data_ptr = pixel_data->Data(); + } + Vector data; + bool need_conversion = true; + bool have_peekable_rgba = + (peek_succeed && + pixmap.colorType() == SkColorType::kRGBA_8888_SkColorType); + bool is_pixel_data_rgba = (have_peekable_rgba || !peek_succeed); + if (is_pixel_data_rgba && format == GL_RGBA && type == GL_UNSIGNED_BYTE && + !selecting_sub_rectangle && depth == 1) { + need_conversion = false; + } else { + if (type == GL_UNSIGNED_INT_10F_11F_11F_REV) { + type = GL_FLOAT; + } + bool is_pixel_data_bgra = + pixmap.colorType() == SkColorType::kBGRA_8888_SkColorType; + if ((is_pixel_data_bgra && + !WebGLImageConversion::ExtractImageData( + pixel_data_ptr, WebGLImageConversion::DataFormat::kDataFormatBGRA8, + bitmap->Size(), source_sub_rect, depth, unpack_image_height, + format, type, false, false, data)) || + (is_pixel_data_rgba && + !WebGLImageConversion::ExtractImageData( + pixel_data_ptr, WebGLImageConversion::DataFormat::kDataFormatRGBA8, + bitmap->Size(), source_sub_rect, depth, unpack_image_height, + format, type, false, false, data))) { + SynthesizeGLError(GL_INVALID_VALUE, func_name, ""bad image data""); + return; + } + } + ScopedUnpackParametersResetRestore temporary_reset_unpack(this); + if (function_id == kTexImage2D) { + TexImage2DBase(target, level, internalformat, width, height, 0, format, + type, need_conversion ? data.data() : pixel_data_ptr); + } else if (function_id == kTexSubImage2D) { + ContextGL()->TexSubImage2D(target, level, xoffset, yoffset, width, height, + format, type, + need_conversion ? data.data() : pixel_data_ptr); + } else if (function_id == kTexImage3D) { + ContextGL()->TexImage3D(target, level, internalformat, width, height, depth, + 0, format, type, + need_conversion ? data.data() : pixel_data_ptr); + } else { + DCHECK_EQ(function_id, kTexSubImage3D); + ContextGL()->TexSubImage3D(target, level, xoffset, yoffset, zoffset, width, + height, depth, format, type, + need_conversion ? data.data() : pixel_data_ptr); + } +} +","@@ -6344,7 +6344,8 @@ void WebGLRenderingContextBase::DrawingBufferClientRestoreMaskAndClearValues() { + ContextGL()->ClearStencil(clear_stencil_); + } + +-void WebGLRenderingContextBase::DrawingBufferClientRestorePixelPackAlignment() { ++void WebGLRenderingContextBase:: ++ DrawingBufferClientRestorePixelPackParameters() { + if (!ContextGL()) + return; + ContextGL()->PixelStorei(GL_PACK_ALIGNMENT, pack_alignment_); +@@ -6372,6 +6373,8 @@ void WebGLRenderingContextBase::DrawingBufferClientRestoreFramebufferBinding() { + + void WebGLRenderingContextBase:: + DrawingBufferClientRestorePixelUnpackBufferBinding() {} ++void WebGLRenderingContextBase:: ++ DrawingBufferClientRestorePixelPackBufferBinding() {} + + ScriptValue WebGLRenderingContextBase::GetBooleanParameter( + ScriptState* script_state,",1180,1511,2048 +3573,"int copy_siginfo_to_user(siginfo_t __user *to, siginfo_t *from) +{ + int err; + + if (!access_ok (VERIFY_WRITE, to, sizeof(siginfo_t))) + return -EFAULT; + if (from->si_code < 0) + return __copy_to_user(to, from, sizeof(siginfo_t)) + ? -EFAULT : 0; + /* + * If you change siginfo_t structure, please be sure + * this code is fixed accordingly. + * Please remember to update the signalfd_copyinfo() function + * inside fs/signalfd.c too, in case siginfo_t changes. + * It should never copy any pad contained in the structure + * to avoid security leaks, but must copy the generic + * 3 ints plus the relevant union member. + */ + err = __put_user(from->si_signo, &to->si_signo); + err |= __put_user(from->si_errno, &to->si_errno); + err |= __put_user((short)from->si_code, &to->si_code); + switch (from->si_code & __SI_MASK) { + case __SI_KILL: + err |= __put_user(from->si_pid, &to->si_pid); + err |= __put_user(from->si_uid, &to->si_uid); + break; + case __SI_TIMER: + err |= __put_user(from->si_tid, &to->si_tid); + err |= __put_user(from->si_overrun, &to->si_overrun); + err |= __put_user(from->si_ptr, &to->si_ptr); + break; + case __SI_POLL: + err |= __put_user(from->si_band, &to->si_band); + err |= __put_user(from->si_fd, &to->si_fd); + break; + case __SI_FAULT: + err |= __put_user(from->si_addr, &to->si_addr); +#ifdef __ARCH_SI_TRAPNO + err |= __put_user(from->si_trapno, &to->si_trapno); +#endif +#ifdef BUS_MCEERR_AO + /* + * Other callers might not initialize the si_lsb field, + * so check explicitely for the right codes here. + */ + if (from->si_code == BUS_MCEERR_AR || from->si_code == BUS_MCEERR_AO) + err |= __put_user(from->si_addr_lsb, &to->si_addr_lsb); +#endif + break; + case __SI_CHLD: + err |= __put_user(from->si_pid, &to->si_pid); + err |= __put_user(from->si_uid, &to->si_uid); + err |= __put_user(from->si_status, &to->si_status); + err |= __put_user(from->si_utime, &to->si_utime); + err |= __put_user(from->si_stime, &to->si_stime); + break; + case __SI_RT: /* This is not generated by the kernel as of now. */ + case __SI_MESGQ: /* But this is */ + err |= __put_user(from->si_pid, &to->si_pid); + err |= __put_user(from->si_uid, &to->si_uid); + err |= __put_user(from->si_ptr, &to->si_ptr); + break; + default: /* this is just in case for now ... */ + err |= __put_user(from->si_pid, &to->si_pid); + err |= __put_user(from->si_uid, &to->si_uid); + break; + } + return err; +} +",0,"int copy_siginfo_to_user(siginfo_t __user *to, siginfo_t *from) +{ + int err; + + if (!access_ok (VERIFY_WRITE, to, sizeof(siginfo_t))) + return -EFAULT; + if (from->si_code < 0) + return __copy_to_user(to, from, sizeof(siginfo_t)) + ? -EFAULT : 0; + /* + * If you change siginfo_t structure, please be sure + * this code is fixed accordingly. + * Please remember to update the signalfd_copyinfo() function + * inside fs/signalfd.c too, in case siginfo_t changes. + * It should never copy any pad contained in the structure + * to avoid security leaks, but must copy the generic + * 3 ints plus the relevant union member. + */ + err = __put_user(from->si_signo, &to->si_signo); + err |= __put_user(from->si_errno, &to->si_errno); + err |= __put_user((short)from->si_code, &to->si_code); + switch (from->si_code & __SI_MASK) { + case __SI_KILL: + err |= __put_user(from->si_pid, &to->si_pid); + err |= __put_user(from->si_uid, &to->si_uid); + break; + case __SI_TIMER: + err |= __put_user(from->si_tid, &to->si_tid); + err |= __put_user(from->si_overrun, &to->si_overrun); + err |= __put_user(from->si_ptr, &to->si_ptr); + break; + case __SI_POLL: + err |= __put_user(from->si_band, &to->si_band); + err |= __put_user(from->si_fd, &to->si_fd); + break; + case __SI_FAULT: + err |= __put_user(from->si_addr, &to->si_addr); +#ifdef __ARCH_SI_TRAPNO + err |= __put_user(from->si_trapno, &to->si_trapno); +#endif +#ifdef BUS_MCEERR_AO + /* + * Other callers might not initialize the si_lsb field, + * so check explicitely for the right codes here. + */ + if (from->si_code == BUS_MCEERR_AR || from->si_code == BUS_MCEERR_AO) + err |= __put_user(from->si_addr_lsb, &to->si_addr_lsb); +#endif + break; + case __SI_CHLD: + err |= __put_user(from->si_pid, &to->si_pid); + err |= __put_user(from->si_uid, &to->si_uid); + err |= __put_user(from->si_status, &to->si_status); + err |= __put_user(from->si_utime, &to->si_utime); + err |= __put_user(from->si_stime, &to->si_stime); + break; + case __SI_RT: /* This is not generated by the kernel as of now. */ + case __SI_MESGQ: /* But this is */ + err |= __put_user(from->si_pid, &to->si_pid); + err |= __put_user(from->si_uid, &to->si_uid); + err |= __put_user(from->si_ptr, &to->si_ptr); + break; + default: /* this is just in case for now ... */ + err |= __put_user(from->si_pid, &to->si_pid); + err |= __put_user(from->si_uid, &to->si_uid); + break; + } + return err; +} +","@@ -2421,9 +2421,13 @@ SYSCALL_DEFINE3(rt_sigqueueinfo, pid_t, pid, int, sig, + return -EFAULT; + + /* Not even root can pretend to send signals from the kernel. +- Nor can they impersonate a kill(), which adds source info. */ +- if (info.si_code >= 0) ++ * Nor can they impersonate a kill()/tgkill(), which adds source info. ++ */ ++ if (info.si_code != SI_QUEUE) { ++ /* We used to allow any < 0 si_code */ ++ WARN_ON_ONCE(info.si_code < 0); + return -EPERM; ++ } + info.si_signo = sig; + + /* POSIX.1b doesn't mention process groups. */ +@@ -2437,9 +2441,13 @@ long do_rt_tgsigqueueinfo(pid_t tgid, pid_t pid, int sig, siginfo_t *info) + return -EINVAL; + + /* Not even root can pretend to send signals from the kernel. +- Nor can they impersonate a kill(), which adds source info. */ +- if (info->si_code >= 0) ++ * Nor can they impersonate a kill()/tgkill(), which adds source info. ++ */ ++ if (info->si_code != SI_QUEUE) { ++ /* We used to allow any < 0 si_code */ ++ WARN_ON_ONCE(info->si_code < 0); + return -EPERM; ++ } + info->si_signo = sig; + + return do_send_specific(tgid, pid, sig, info);",765,1096,2048 +11480,"bool OmniboxViewWin::OnKeyDownOnlyWritable(TCHAR key, + UINT repeat_count, + UINT flags) { + + int count = repeat_count; + switch (key) { + case VK_RIGHT: + if (base::i18n::IsRTL()) + return false; + { + CHARRANGE selection; + GetSel(selection); + return (selection.cpMin == selection.cpMax) && + (selection.cpMin == GetTextLength()) && + model_->CommitSuggestedText(true); + } + + case VK_RETURN: + model_->AcceptInput((flags & KF_ALTDOWN) ? + NEW_FOREGROUND_TAB : CURRENT_TAB, false); + return true; + + case VK_PRIOR: + case VK_NEXT: + count = model_->result().size(); + case VK_UP: + case VK_DOWN: + if ((flags & KF_ALTDOWN) && !(flags & KF_EXTENDED)) + return false; + + model_->OnUpOrDownKeyPressed(((key == VK_PRIOR) || (key == VK_UP)) ? + -count : count); + return true; + + + case VK_DELETE: + if (flags & KF_ALTDOWN) + return false; + if (GetKeyState(VK_SHIFT) >= 0) { + if (GetKeyState(VK_CONTROL) >= 0) { + CHARRANGE selection; + GetSel(selection); + delete_at_end_pressed_ = ((selection.cpMin == selection.cpMax) && + (selection.cpMin == GetTextLength())); + } + return false; + } + if (GetKeyState(VK_CONTROL) >= 0) { + CHARRANGE selection; + GetSel(selection); + if (selection.cpMin != selection.cpMax) { + ScopedFreeze freeze(this, GetTextObjectModel()); + OnBeforePossibleChange(); + Cut(); + OnAfterPossibleChange(); + } else { + if (model_->popup_model()->IsOpen()) { + model_->popup_model()->TryDeletingCurrentItem(); + } + } + } + return true; + + case 'X': + if ((flags & KF_ALTDOWN) || (GetKeyState(VK_CONTROL) >= 0)) + return false; + if (GetKeyState(VK_SHIFT) >= 0) { + ScopedFreeze freeze(this, GetTextObjectModel()); + OnBeforePossibleChange(); + Cut(); + OnAfterPossibleChange(); + } + return true; + + case VK_INSERT: + if (!(flags & KF_ALTDOWN) && (GetKeyState(VK_SHIFT) >= 0) && + (GetKeyState(VK_CONTROL) >= 0)) + return true; + case 'V': + if ((flags & KF_ALTDOWN) || + (GetKeyState((key == 'V') ? VK_CONTROL : VK_SHIFT) >= 0)) + return false; + if (GetKeyState((key == 'V') ? VK_SHIFT : VK_CONTROL) >= 0) { + ScopedFreeze freeze(this, GetTextObjectModel()); + OnBeforePossibleChange(); + Paste(); + OnAfterPossibleChange(); + } + return true; + + case VK_BACK: { + if ((flags & KF_ALTDOWN) || model_->is_keyword_hint() || + model_->keyword().empty()) + return false; + + { + CHARRANGE selection; + GetSel(selection); + if ((selection.cpMin != selection.cpMax) || (selection.cpMin != 0)) + return false; + } + + ScopedFreeze freeze(this, GetTextObjectModel()); + model_->ClearKeyword(GetText()); + return true; + } + + case VK_TAB: { + if (model_->is_keyword_hint()) { + ScopedFreeze freeze(this, GetTextObjectModel()); + model_->AcceptKeyword(); + } else if (!IsCaretAtEnd()) { + ScopedFreeze freeze(this, GetTextObjectModel()); + OnBeforePossibleChange(); + PlaceCaretAt(GetTextLength()); + OnAfterPossibleChange(); + } else { + model_->CommitSuggestedText(true); + } + return true; + } + + case 0xbb: // Ctrl-'='. Triggers subscripting (even in plain text mode). + return true; + + default: + return false; + } +} +",0,"bool OmniboxViewWin::OnKeyDownOnlyWritable(TCHAR key, + UINT repeat_count, + UINT flags) { + + int count = repeat_count; + switch (key) { + case VK_RIGHT: + if (base::i18n::IsRTL()) + return false; + { + CHARRANGE selection; + GetSel(selection); + return (selection.cpMin == selection.cpMax) && + (selection.cpMin == GetTextLength()) && + model_->CommitSuggestedText(true); + } + + case VK_RETURN: + model_->AcceptInput((flags & KF_ALTDOWN) ? + NEW_FOREGROUND_TAB : CURRENT_TAB, false); + return true; + + case VK_PRIOR: + case VK_NEXT: + count = model_->result().size(); + case VK_UP: + case VK_DOWN: + if ((flags & KF_ALTDOWN) && !(flags & KF_EXTENDED)) + return false; + + model_->OnUpOrDownKeyPressed(((key == VK_PRIOR) || (key == VK_UP)) ? + -count : count); + return true; + + + case VK_DELETE: + if (flags & KF_ALTDOWN) + return false; + if (GetKeyState(VK_SHIFT) >= 0) { + if (GetKeyState(VK_CONTROL) >= 0) { + CHARRANGE selection; + GetSel(selection); + delete_at_end_pressed_ = ((selection.cpMin == selection.cpMax) && + (selection.cpMin == GetTextLength())); + } + return false; + } + if (GetKeyState(VK_CONTROL) >= 0) { + CHARRANGE selection; + GetSel(selection); + if (selection.cpMin != selection.cpMax) { + ScopedFreeze freeze(this, GetTextObjectModel()); + OnBeforePossibleChange(); + Cut(); + OnAfterPossibleChange(); + } else { + if (model_->popup_model()->IsOpen()) { + model_->popup_model()->TryDeletingCurrentItem(); + } + } + } + return true; + + case 'X': + if ((flags & KF_ALTDOWN) || (GetKeyState(VK_CONTROL) >= 0)) + return false; + if (GetKeyState(VK_SHIFT) >= 0) { + ScopedFreeze freeze(this, GetTextObjectModel()); + OnBeforePossibleChange(); + Cut(); + OnAfterPossibleChange(); + } + return true; + + case VK_INSERT: + if (!(flags & KF_ALTDOWN) && (GetKeyState(VK_SHIFT) >= 0) && + (GetKeyState(VK_CONTROL) >= 0)) + return true; + case 'V': + if ((flags & KF_ALTDOWN) || + (GetKeyState((key == 'V') ? VK_CONTROL : VK_SHIFT) >= 0)) + return false; + if (GetKeyState((key == 'V') ? VK_SHIFT : VK_CONTROL) >= 0) { + ScopedFreeze freeze(this, GetTextObjectModel()); + OnBeforePossibleChange(); + Paste(); + OnAfterPossibleChange(); + } + return true; + + case VK_BACK: { + if ((flags & KF_ALTDOWN) || model_->is_keyword_hint() || + model_->keyword().empty()) + return false; + + { + CHARRANGE selection; + GetSel(selection); + if ((selection.cpMin != selection.cpMax) || (selection.cpMin != 0)) + return false; + } + + ScopedFreeze freeze(this, GetTextObjectModel()); + model_->ClearKeyword(GetText()); + return true; + } + + case VK_TAB: { + if (model_->is_keyword_hint()) { + ScopedFreeze freeze(this, GetTextObjectModel()); + model_->AcceptKeyword(); + } else if (!IsCaretAtEnd()) { + ScopedFreeze freeze(this, GetTextObjectModel()); + OnBeforePossibleChange(); + PlaceCaretAt(GetTextLength()); + OnAfterPossibleChange(); + } else { + model_->CommitSuggestedText(true); + } + return true; + } + + case 0xbb: // Ctrl-'='. Triggers subscripting (even in plain text mode). + return true; + + default: + return false; + } +} +","@@ -1003,8 +1003,7 @@ int OmniboxViewWin::OnPerformDropImpl(const views::DropTargetEvent& event, + if (data.GetURLAndTitle(&url, &title)) { + string16 text(StripJavascriptSchemas(UTF8ToUTF16(url.spec()))); + SetUserText(text); +- if (url.spec().length() == text.length()) +- model()->AcceptInput(CURRENT_TAB, true); ++ model()->AcceptInput(CURRENT_TAB, true); + return CopyOrLinkDragOperation(event.source_operations()); + } + } else if (data.HasString()) {",892,1223,2048 +6627,"irc_ctcp_display_reply_from_nick (struct t_irc_server *server, time_t date, + const char *command, const char *nick, + const char *address, char *arguments) +{ + char *pos_end, *pos_space, *pos_args, *pos_usec; + struct timeval tv; + long sec1, usec1, sec2, usec2, difftime; + + while (arguments && arguments[0]) + { + pos_end = strrchr (arguments + 1, '\01'); + if (pos_end) + pos_end[0] = '\0'; + + pos_space = strchr (arguments + 1, ' '); + if (pos_space) + { + pos_space[0] = '\0'; + pos_args = pos_space + 1; + while (pos_args[0] == ' ') + { + pos_args++; + } + if (strcmp (arguments + 1, ""PING"") == 0) + { + pos_usec = strchr (pos_args, ' '); + if (pos_usec) + { + pos_usec[0] = '\0'; + + gettimeofday (&tv, NULL); + sec1 = atol (pos_args); + usec1 = atol (pos_usec + 1); + sec2 = tv.tv_sec; + usec2 = tv.tv_usec; + + difftime = ((sec2 * 1000000) + usec2) - + ((sec1 * 1000000) + usec1); + weechat_printf_date_tags ( + irc_msgbuffer_get_target_buffer ( + server, nick, NULL, ""ctcp"", NULL), + date, + irc_protocol_tags (command, ""irc_ctcp"", NULL, NULL), + /* TRANSLATORS: %.3fs is a float number + ""s"" (""seconds"") */ + _(""%sCTCP reply from %s%s%s: %s%s%s %.3fs""), + weechat_prefix (""network""), + irc_nick_color_for_msg (server, 0, NULL, nick), + nick, + IRC_COLOR_RESET, + IRC_COLOR_CHAT_CHANNEL, + arguments + 1, + IRC_COLOR_RESET, + (float)difftime / 1000000.0); + + pos_usec[0] = ' '; + } + } + else + { + weechat_printf_date_tags ( + irc_msgbuffer_get_target_buffer ( + server, nick, NULL, ""ctcp"", NULL), + date, + irc_protocol_tags (command, ""irc_ctcp"", NULL, address), + _(""%sCTCP reply from %s%s%s: %s%s%s%s%s""), + weechat_prefix (""network""), + irc_nick_color_for_msg (server, 0, NULL, nick), + nick, + IRC_COLOR_RESET, + IRC_COLOR_CHAT_CHANNEL, + arguments + 1, + IRC_COLOR_RESET, + "" "", + pos_args); + } + pos_space[0] = ' '; + } + else + { + weechat_printf_date_tags ( + irc_msgbuffer_get_target_buffer ( + server, nick, NULL, ""ctcp"", NULL), + date, + irc_protocol_tags (command, NULL, NULL, address), + _(""%sCTCP reply from %s%s%s: %s%s%s%s%s""), + weechat_prefix (""network""), + irc_nick_color_for_msg (server, 0, NULL, nick), + nick, + IRC_COLOR_RESET, + IRC_COLOR_CHAT_CHANNEL, + arguments + 1, + """", + """", + """"); + } + + if (pos_end) + pos_end[0] = '\01'; + + arguments = (pos_end) ? pos_end + 1 : NULL; + } +} +",0,"irc_ctcp_display_reply_from_nick (struct t_irc_server *server, time_t date, + const char *command, const char *nick, + const char *address, char *arguments) +{ + char *pos_end, *pos_space, *pos_args, *pos_usec; + struct timeval tv; + long sec1, usec1, sec2, usec2, difftime; + + while (arguments && arguments[0]) + { + pos_end = strrchr (arguments + 1, '\01'); + if (pos_end) + pos_end[0] = '\0'; + + pos_space = strchr (arguments + 1, ' '); + if (pos_space) + { + pos_space[0] = '\0'; + pos_args = pos_space + 1; + while (pos_args[0] == ' ') + { + pos_args++; + } + if (strcmp (arguments + 1, ""PING"") == 0) + { + pos_usec = strchr (pos_args, ' '); + if (pos_usec) + { + pos_usec[0] = '\0'; + + gettimeofday (&tv, NULL); + sec1 = atol (pos_args); + usec1 = atol (pos_usec + 1); + sec2 = tv.tv_sec; + usec2 = tv.tv_usec; + + difftime = ((sec2 * 1000000) + usec2) - + ((sec1 * 1000000) + usec1); + weechat_printf_date_tags ( + irc_msgbuffer_get_target_buffer ( + server, nick, NULL, ""ctcp"", NULL), + date, + irc_protocol_tags (command, ""irc_ctcp"", NULL, NULL), + /* TRANSLATORS: %.3fs is a float number + ""s"" (""seconds"") */ + _(""%sCTCP reply from %s%s%s: %s%s%s %.3fs""), + weechat_prefix (""network""), + irc_nick_color_for_msg (server, 0, NULL, nick), + nick, + IRC_COLOR_RESET, + IRC_COLOR_CHAT_CHANNEL, + arguments + 1, + IRC_COLOR_RESET, + (float)difftime / 1000000.0); + + pos_usec[0] = ' '; + } + } + else + { + weechat_printf_date_tags ( + irc_msgbuffer_get_target_buffer ( + server, nick, NULL, ""ctcp"", NULL), + date, + irc_protocol_tags (command, ""irc_ctcp"", NULL, address), + _(""%sCTCP reply from %s%s%s: %s%s%s%s%s""), + weechat_prefix (""network""), + irc_nick_color_for_msg (server, 0, NULL, nick), + nick, + IRC_COLOR_RESET, + IRC_COLOR_CHAT_CHANNEL, + arguments + 1, + IRC_COLOR_RESET, + "" "", + pos_args); + } + pos_space[0] = ' '; + } + else + { + weechat_printf_date_tags ( + irc_msgbuffer_get_target_buffer ( + server, nick, NULL, ""ctcp"", NULL), + date, + irc_protocol_tags (command, NULL, NULL, address), + _(""%sCTCP reply from %s%s%s: %s%s%s%s%s""), + weechat_prefix (""network""), + irc_nick_color_for_msg (server, 0, NULL, nick), + nick, + IRC_COLOR_RESET, + IRC_COLOR_CHAT_CHANNEL, + arguments + 1, + """", + """", + """"); + } + + if (pos_end) + pos_end[0] = '\01'; + + arguments = (pos_end) ? pos_end + 1 : NULL; + } +} +","@@ -512,7 +512,7 @@ irc_ctcp_dcc_filename_without_quotes (const char *filename) + int length; + + length = strlen (filename); +- if (length > 0) ++ if (length > 1) + { + if ((filename[0] == '\""') && (filename[length - 1] == '\""')) + return weechat_strndup (filename + 1, length - 2);",794,1125,2048 +18601,"png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr, + int num_text) +{ + int i; + + png_debug1(1, ""in %s storage function"", ((png_ptr == NULL || + png_ptr->chunk_name[0] == '\0') ? + ""text"" : (png_const_charp)png_ptr->chunk_name)); + + if (png_ptr == NULL || info_ptr == NULL || num_text == 0) + return(0); + + /* Make sure we have enough space in the ""text"" array in info_struct + * to hold all of the incoming text_ptr objects. + */ + if (info_ptr->num_text + num_text > info_ptr->max_text) + { + int old_max_text = info_ptr->max_text; + int old_num_text = info_ptr->num_text; + + if (info_ptr->text != NULL) + { + png_textp old_text; + + info_ptr->max_text = info_ptr->num_text + num_text + 8; + old_text = info_ptr->text; + + info_ptr->text = (png_textp)png_malloc_warn(png_ptr, + (png_uint_32)(info_ptr->max_text * png_sizeof(png_text))); + if (info_ptr->text == NULL) + { + /* Restore to previous condition */ + info_ptr->max_text = old_max_text; + info_ptr->text = old_text; + return(1); + } + png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max_text * + png_sizeof(png_text))); + png_free(png_ptr, old_text); + } + else + { + info_ptr->max_text = num_text + 8; + info_ptr->num_text = 0; + info_ptr->text = (png_textp)png_malloc_warn(png_ptr, + (png_uint_32)(info_ptr->max_text * png_sizeof(png_text))); + if (info_ptr->text == NULL) + { + /* Restore to previous condition */ + info_ptr->num_text = old_num_text; + info_ptr->max_text = old_max_text; + return(1); + } +#ifdef PNG_FREE_ME_SUPPORTED + info_ptr->free_me |= PNG_FREE_TEXT; +#endif + } + png_debug1(3, ""allocated %d entries for info_ptr->text"", + info_ptr->max_text); + } + + for (i = 0; i < num_text; i++) + { + png_size_t text_length, key_len; + png_size_t lang_len, lang_key_len; + png_textp textp = &(info_ptr->text[info_ptr->num_text]); + + if (text_ptr[i].key == NULL) + continue; + + key_len = png_strlen(text_ptr[i].key); + + if (text_ptr[i].compression <= 0) + { + lang_len = 0; + lang_key_len = 0; + } + + else +#ifdef PNG_iTXt_SUPPORTED + { + /* Set iTXt data */ + + if (text_ptr[i].lang != NULL) + lang_len = png_strlen(text_ptr[i].lang); + else + lang_len = 0; + if (text_ptr[i].lang_key != NULL) + lang_key_len = png_strlen(text_ptr[i].lang_key); + else + lang_key_len = 0; + } +#else /* PNG_iTXt_SUPPORTED */ + { + png_warning(png_ptr, ""iTXt chunk not supported.""); + continue; + } +#endif + + if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0') + { + text_length = 0; +#ifdef PNG_iTXt_SUPPORTED + if (text_ptr[i].compression > 0) + textp->compression = PNG_ITXT_COMPRESSION_NONE; + else +#endif + textp->compression = PNG_TEXT_COMPRESSION_NONE; + } + + else + { + text_length = png_strlen(text_ptr[i].text); + textp->compression = text_ptr[i].compression; + } + + textp->key = (png_charp)png_malloc_warn(png_ptr, + (png_uint_32) + (key_len + text_length + lang_len + lang_key_len + 4)); + if (textp->key == NULL) + return(1); + png_debug2(2, ""Allocated %lu bytes at %x in png_set_text"", + (png_uint_32) + (key_len + lang_len + lang_key_len + text_length + 4), + (int)textp->key); + + png_memcpy(textp->key, text_ptr[i].key,(png_size_t)(key_len)); + *(textp->key + key_len) = '\0'; +#ifdef PNG_iTXt_SUPPORTED + if (text_ptr[i].compression > 0) + { + textp->lang = textp->key + key_len + 1; + png_memcpy(textp->lang, text_ptr[i].lang, lang_len); + *(textp->lang + lang_len) = '\0'; + textp->lang_key = textp->lang + lang_len + 1; + png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len); + *(textp->lang_key + lang_key_len) = '\0'; + textp->text = textp->lang_key + lang_key_len + 1; + } + else +#endif + { +#ifdef PNG_iTXt_SUPPORTED + textp->lang=NULL; + textp->lang_key=NULL; +#endif + textp->text = textp->key + key_len + 1; + } + if (text_length) + png_memcpy(textp->text, text_ptr[i].text, + (png_size_t)(text_length)); + *(textp->text + text_length) = '\0'; + +#ifdef PNG_iTXt_SUPPORTED + if (textp->compression > 0) + { + textp->text_length = 0; + textp->itxt_length = text_length; + } + else +#endif + + { + textp->text_length = text_length; +#ifdef PNG_iTXt_SUPPORTED + textp->itxt_length = 0; +#endif + } + info_ptr->num_text++; + png_debug1(3, ""transferred text chunk %d"", info_ptr->num_text); + } + return(0); +} +",1,"png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr, + int num_text) +{ + int i; + + png_debug1(1, ""in %s storage function"", ((png_ptr == NULL || + png_ptr->chunk_name[0] == '\0') ? + ""text"" : (png_const_charp)png_ptr->chunk_name)); + + if (png_ptr == NULL || info_ptr == NULL || num_text == 0) + return(0); + + /* Make sure we have enough space in the ""text"" array in info_struct + * to hold all of the incoming text_ptr objects. + */ + if (info_ptr->num_text + num_text > info_ptr->max_text) + { + int old_max_text = info_ptr->max_text; + int old_num_text = info_ptr->num_text; + + if (info_ptr->text != NULL) + { + png_textp old_text; + + info_ptr->max_text = info_ptr->num_text + num_text + 8; + old_text = info_ptr->text; + + info_ptr->text = (png_textp)png_malloc_warn(png_ptr, + (png_uint_32)(info_ptr->max_text * png_sizeof(png_text))); + if (info_ptr->text == NULL) + { + /* Restore to previous condition */ + info_ptr->max_text = old_max_text; + info_ptr->text = old_text; + return(1); + } + png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max_text * + png_sizeof(png_text))); + png_free(png_ptr, old_text); + } + else + { + info_ptr->max_text = num_text + 8; + info_ptr->num_text = 0; + info_ptr->text = (png_textp)png_malloc_warn(png_ptr, + (png_uint_32)(info_ptr->max_text * png_sizeof(png_text))); + if (info_ptr->text == NULL) + { + /* Restore to previous condition */ + info_ptr->num_text = old_num_text; + info_ptr->max_text = old_max_text; + return(1); + } +#ifdef PNG_FREE_ME_SUPPORTED + info_ptr->free_me |= PNG_FREE_TEXT; +#endif + } + png_debug1(3, ""allocated %d entries for info_ptr->text"", + info_ptr->max_text); + } + + for (i = 0; i < num_text; i++) + { + png_size_t text_length, key_len; + png_size_t lang_len, lang_key_len; + png_textp textp = &(info_ptr->text[info_ptr->num_text]); + + if (text_ptr[i].key == NULL) + continue; + + key_len = png_strlen(text_ptr[i].key); + + if (text_ptr[i].compression <= 0) + { + lang_len = 0; + lang_key_len = 0; + } + + else +#ifdef PNG_iTXt_SUPPORTED + { + /* Set iTXt data */ + + if (text_ptr[i].lang != NULL) + lang_len = png_strlen(text_ptr[i].lang); + else + lang_len = 0; + if (text_ptr[i].lang_key != NULL) + lang_key_len = png_strlen(text_ptr[i].lang_key); + else + lang_key_len = 0; + } +#else /* PNG_iTXt_SUPPORTED */ + { + png_warning(png_ptr, ""iTXt chunk not supported.""); + continue; + } +#endif + + if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0') + { + text_length = 0; +#ifdef PNG_iTXt_SUPPORTED + if (text_ptr[i].compression > 0) + textp->compression = PNG_ITXT_COMPRESSION_NONE; + else +#endif + textp->compression = PNG_TEXT_COMPRESSION_NONE; + } + + else + { + text_length = png_strlen(text_ptr[i].text); + textp->compression = text_ptr[i].compression; + } + + textp->key = (png_charp)png_malloc_warn(png_ptr, + (png_uint_32) + (key_len + text_length + lang_len + lang_key_len + 4)); + if (textp->key == NULL) + return(1); + png_debug2(2, ""Allocated %lu bytes at %p in png_set_text"", + (png_uint_32) + (key_len + lang_len + lang_key_len + text_length + 4), + textp->key); + + png_memcpy(textp->key, text_ptr[i].key,(png_size_t)(key_len)); + *(textp->key + key_len) = '\0'; +#ifdef PNG_iTXt_SUPPORTED + if (text_ptr[i].compression > 0) + { + textp->lang = textp->key + key_len + 1; + png_memcpy(textp->lang, text_ptr[i].lang, lang_len); + *(textp->lang + lang_len) = '\0'; + textp->lang_key = textp->lang + lang_len + 1; + png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len); + *(textp->lang_key + lang_key_len) = '\0'; + textp->text = textp->lang_key + lang_key_len + 1; + } + else +#endif + { +#ifdef PNG_iTXt_SUPPORTED + textp->lang=NULL; + textp->lang_key=NULL; +#endif + textp->text = textp->key + key_len + 1; + } + if (text_length) + png_memcpy(textp->text, text_ptr[i].text, + (png_size_t)(text_length)); + *(textp->text + text_length) = '\0'; + +#ifdef PNG_iTXt_SUPPORTED + if (textp->compression > 0) + { + textp->text_length = 0; + textp->itxt_length = text_length; + } + else +#endif + + { + textp->text_length = text_length; +#ifdef PNG_iTXt_SUPPORTED + textp->itxt_length = 0; +#endif + } + info_ptr->num_text++; + png_debug1(3, ""transferred text chunk %d"", info_ptr->num_text); + } + return(0); +} +","@@ -1,8 +1,8 @@ + + /* pngset.c - storage of image information into info struct + * +- * Last changed in libpng 1.2.51 [February 6, 2014] +- * Copyright (c) 1998-2014 Glenn Randers-Pehrson ++ * Last changed in libpng 1.2.54 [November 12, 2015] ++ * Copyright (c) 1998-2015 Glenn Randers-Pehrson + * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger) + * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.) + * +@@ -263,7 +263,10 @@ png_set_IHDR(png_structp png_ptr, png_infop info_ptr, + - 1 /* filter byte */ + - 7*8 /* rounding of width to multiple of 8 pixels */ + - 8) /* extra max_pixel_depth pad */ ++ { + info_ptr->rowbytes = (png_size_t)0; ++ png_error(png_ptr, ""Image width is too large for this architecture""); ++ } + else + info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth, width); + } +@@ -446,12 +449,17 @@ png_set_PLTE(png_structp png_ptr, png_infop info_ptr, + png_colorp palette, int num_palette) + { + ++ png_uint_32 max_palette_length; ++ + png_debug1(1, ""in %s storage function"", ""PLTE""); + + if (png_ptr == NULL || info_ptr == NULL) + return; + +- if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH) ++ max_palette_length = (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ? ++ (1 << png_ptr->bit_depth) : PNG_MAX_PALETTE_LENGTH; ++ ++ if (num_palette < 0 || num_palette > (int) max_palette_length) + { + if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE) + png_error(png_ptr, ""Invalid palette length""); +@@ -471,8 +479,8 @@ png_set_PLTE(png_structp png_ptr, png_infop info_ptr, + #endif + + /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead +- * of num_palette entries, in case of an invalid PNG file that has +- * too-large sample values. ++ * of num_palette entries, in case of an invalid PNG file or incorrect ++ * call to png_set_PLTE() with too-large sample values. + */ + png_ptr->palette = (png_colorp)png_calloc(png_ptr, + PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color)); +@@ -770,10 +778,10 @@ png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr, + (key_len + text_length + lang_len + lang_key_len + 4)); + if (textp->key == NULL) + return(1); +- png_debug2(2, ""Allocated %lu bytes at %x in png_set_text"", ++ png_debug2(2, ""Allocated %lu bytes at %p in png_set_text"", + (png_uint_32) + (key_len + lang_len + lang_key_len + text_length + 4), +- (int)textp->key); ++ textp->key); + + png_memcpy(textp->key, text_ptr[i].key,(png_size_t)(key_len)); + *(textp->key + key_len) = '\0'; +@@ -834,6 +842,15 @@ png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time) + (png_ptr->mode & PNG_WROTE_tIME)) + return; + ++ if (mod_time->month == 0 || mod_time->month > 12 || ++ mod_time->day == 0 || mod_time->day > 31 || ++ mod_time->hour > 23 || mod_time->minute > 59 || ++ mod_time->second > 60) ++ { ++ png_warning(png_ptr, ""Ignoring invalid time value""); ++ return; ++ } ++ + png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof(png_time)); + info_ptr->valid |= PNG_INFO_tIME; + }",1370,1701,2048 +4139,"char *msPostGISBuildSQLItems(layerObj *layer) +{ + + char *strEndian = NULL; + char *strGeom = NULL; + char *strItems = NULL; + msPostGISLayerInfo *layerinfo = NULL; + + if (layer->debug) { + msDebug(""msPostGISBuildSQLItems called.\n""); + } + + assert( layer->layerinfo != NULL); + + layerinfo = (msPostGISLayerInfo *)layer->layerinfo; + + if ( ! layerinfo->geomcolumn ) { + msSetError(MS_MISCERR, ""layerinfo->geomcolumn is not initialized."", ""msPostGISBuildSQLItems()""); + return NULL; + } + + /* + ** Get the server to transform the geometry into our + ** native endian before transmitting it to us.. + */ + if (layerinfo->endian == LITTLE_ENDIAN) { + strEndian = ""NDR""; + } else { + strEndian = ""XDR""; + } + + { + /* + ** We transfer the geometry from server to client as a + ** hex or base64 encoded WKB byte-array. We will have to decode this + ** data once we get it. Forcing to 2D (via the AsBinary function + ** which includes a 2D force in it) removes ordinates we don't + ** need, saving transfer and encode/decode time. + */ +#if TRANSFER_ENCODING == 64 + static char *strGeomTemplate = ""encode(ST_AsBinary(ST_Force_2D(\""%s\""),'%s'),'base64') as geom,\""%s\""""; +#else + static char *strGeomTemplate = ""encode(ST_AsBinary(ST_Force_2D(\""%s\""),'%s'),'hex') as geom,\""%s\""""; +#endif + strGeom = (char*)msSmallMalloc(strlen(strGeomTemplate) + strlen(strEndian) + strlen(layerinfo->geomcolumn) + strlen(layerinfo->uid)); + sprintf(strGeom, strGeomTemplate, layerinfo->geomcolumn, strEndian, layerinfo->uid); + } + + if( layer->debug > 1 ) { + msDebug(""msPostGISBuildSQLItems: %d items requested.\n"",layer->numitems); + } + + /* + ** Not requesting items? We just need geometry and unique id. + */ + if (layer->numitems == 0) { + strItems = msStrdup(strGeom); + } + /* + ** Build SQL to pull all the items. + */ + else { + int length = strlen(strGeom) + 2; + int t; + for ( t = 0; t < layer->numitems; t++ ) { + length += strlen(layer->items[t]) + 3; /* itemname + """", */ + } + strItems = (char*)msSmallMalloc(length); + strItems[0] = '\0'; + for ( t = 0; t < layer->numitems; t++ ) { + strlcat(strItems, ""\"""", length); + strlcat(strItems, layer->items[t], length); + strlcat(strItems, ""\"","", length); + } + strlcat(strItems, strGeom, length); + } + + free(strGeom); + return strItems; +} +",0,"char *msPostGISBuildSQLItems(layerObj *layer) +{ + + char *strEndian = NULL; + char *strGeom = NULL; + char *strItems = NULL; + msPostGISLayerInfo *layerinfo = NULL; + + if (layer->debug) { + msDebug(""msPostGISBuildSQLItems called.\n""); + } + + assert( layer->layerinfo != NULL); + + layerinfo = (msPostGISLayerInfo *)layer->layerinfo; + + if ( ! layerinfo->geomcolumn ) { + msSetError(MS_MISCERR, ""layerinfo->geomcolumn is not initialized."", ""msPostGISBuildSQLItems()""); + return NULL; + } + + /* + ** Get the server to transform the geometry into our + ** native endian before transmitting it to us.. + */ + if (layerinfo->endian == LITTLE_ENDIAN) { + strEndian = ""NDR""; + } else { + strEndian = ""XDR""; + } + + { + /* + ** We transfer the geometry from server to client as a + ** hex or base64 encoded WKB byte-array. We will have to decode this + ** data once we get it. Forcing to 2D (via the AsBinary function + ** which includes a 2D force in it) removes ordinates we don't + ** need, saving transfer and encode/decode time. + */ +#if TRANSFER_ENCODING == 64 + static char *strGeomTemplate = ""encode(ST_AsBinary(ST_Force_2D(\""%s\""),'%s'),'base64') as geom,\""%s\""""; +#else + static char *strGeomTemplate = ""encode(ST_AsBinary(ST_Force_2D(\""%s\""),'%s'),'hex') as geom,\""%s\""""; +#endif + strGeom = (char*)msSmallMalloc(strlen(strGeomTemplate) + strlen(strEndian) + strlen(layerinfo->geomcolumn) + strlen(layerinfo->uid)); + sprintf(strGeom, strGeomTemplate, layerinfo->geomcolumn, strEndian, layerinfo->uid); + } + + if( layer->debug > 1 ) { + msDebug(""msPostGISBuildSQLItems: %d items requested.\n"",layer->numitems); + } + + /* + ** Not requesting items? We just need geometry and unique id. + */ + if (layer->numitems == 0) { + strItems = msStrdup(strGeom); + } + /* + ** Build SQL to pull all the items. + */ + else { + int length = strlen(strGeom) + 2; + int t; + for ( t = 0; t < layer->numitems; t++ ) { + length += strlen(layer->items[t]) + 3; /* itemname + """", */ + } + strItems = (char*)msSmallMalloc(length); + strItems[0] = '\0'; + for ( t = 0; t < layer->numitems; t++ ) { + strlcat(strItems, ""\"""", length); + strlcat(strItems, layer->items[t], length); + strlcat(strItems, ""\"","", length); + } + strlcat(strItems, strGeom, length); + } + + free(strGeom); + return strItems; +} +","@@ -3212,6 +3212,11 @@ int msPostGISLayerSetTimeFilter(layerObj *lp, const char *timestring, const char + if (!lp || !timestring || !timefield) + return MS_FALSE; + ++ if( strchr(timestring,'\'') || strchr(timestring, '\\') ) { ++ msSetError(MS_MISCERR, ""Invalid time filter."", ""msPostGISLayerSetTimeFilter()""); ++ return MS_FALSE; ++ } ++ + /* discrete time */ + if (strstr(timestring, "","") == NULL && + strstr(timestring, ""/"") == NULL) { /* discrete time */",698,1029,2048 +1566,"persistent_available_p (const char *host, int port, bool ssl, + bool *host_lookup_failed) +{ + /* First, check whether a persistent connection is active at all. */ + if (!pconn_active) + return false; + + /* If we want SSL and the last connection wasn't or vice versa, + don't use it. Checking for host and port is not enough because + HTTP and HTTPS can apparently coexist on the same port. */ + if (ssl != pconn.ssl) + return false; + + /* If we're not connecting to the same port, we're not interested. */ + if (port != pconn.port) + return false; + + /* If the host is the same, we're in business. If not, there is + still hope -- read below. */ + if (0 != strcasecmp (host, pconn.host)) + { + /* Check if pconn.socket is talking to HOST under another name. + This happens often when both sites are virtual hosts + distinguished only by name and served by the same network + interface, and hence the same web server (possibly set up by + the ISP and serving many different web sites). This + admittedly unconventional optimization does not contradict + HTTP and works well with popular server software. */ + + bool found; + ip_address ip; + struct address_list *al; + + if (ssl) + /* Don't try to talk to two different SSL sites over the same + secure connection! (Besides, it's not clear that + name-based virtual hosting is even possible with SSL.) */ + return false; + + /* If pconn.socket's peer is one of the IP addresses HOST + resolves to, pconn.socket is for all intents and purposes + already talking to HOST. */ + + if (!socket_ip_address (pconn.socket, &ip, ENDPOINT_PEER)) + { + /* Can't get the peer's address -- something must be very + wrong with the connection. */ + invalidate_persistent (); + return false; + } + al = lookup_host (host, 0); + if (!al) + { + *host_lookup_failed = true; + return false; + } + + found = address_list_contains (al, &ip); + address_list_release (al); + + if (!found) + return false; + + /* The persistent connection's peer address was found among the + addresses HOST resolved to; therefore, pconn.sock is in fact + already talking to HOST -- no need to reconnect. */ + } + + /* Finally, check whether the connection is still open. This is + important because most servers implement liberal (short) timeout + on persistent connections. Wget can of course always reconnect + if the connection doesn't work out, but it's nicer to know in + advance. This test is a logical followup of the first test, but + is ""expensive"" and therefore placed at the end of the list. + + (Current implementation of test_socket_open has a nice side + effect that it treats sockets with pending data as ""closed"". + This is exactly what we want: if a broken server sends message + body in response to HEAD, or if it sends more than conent-length + data, we won't reuse the corrupted connection.) */ + + if (!test_socket_open (pconn.socket)) + { + /* Oops, the socket is no longer open. Now that we know that, + let's invalidate the persistent connection before returning + 0. */ + invalidate_persistent (); + return false; + } + + return true; +} +",0,"persistent_available_p (const char *host, int port, bool ssl, + bool *host_lookup_failed) +{ + /* First, check whether a persistent connection is active at all. */ + if (!pconn_active) + return false; + + /* If we want SSL and the last connection wasn't or vice versa, + don't use it. Checking for host and port is not enough because + HTTP and HTTPS can apparently coexist on the same port. */ + if (ssl != pconn.ssl) + return false; + + /* If we're not connecting to the same port, we're not interested. */ + if (port != pconn.port) + return false; + + /* If the host is the same, we're in business. If not, there is + still hope -- read below. */ + if (0 != strcasecmp (host, pconn.host)) + { + /* Check if pconn.socket is talking to HOST under another name. + This happens often when both sites are virtual hosts + distinguished only by name and served by the same network + interface, and hence the same web server (possibly set up by + the ISP and serving many different web sites). This + admittedly unconventional optimization does not contradict + HTTP and works well with popular server software. */ + + bool found; + ip_address ip; + struct address_list *al; + + if (ssl) + /* Don't try to talk to two different SSL sites over the same + secure connection! (Besides, it's not clear that + name-based virtual hosting is even possible with SSL.) */ + return false; + + /* If pconn.socket's peer is one of the IP addresses HOST + resolves to, pconn.socket is for all intents and purposes + already talking to HOST. */ + + if (!socket_ip_address (pconn.socket, &ip, ENDPOINT_PEER)) + { + /* Can't get the peer's address -- something must be very + wrong with the connection. */ + invalidate_persistent (); + return false; + } + al = lookup_host (host, 0); + if (!al) + { + *host_lookup_failed = true; + return false; + } + + found = address_list_contains (al, &ip); + address_list_release (al); + + if (!found) + return false; + + /* The persistent connection's peer address was found among the + addresses HOST resolved to; therefore, pconn.sock is in fact + already talking to HOST -- no need to reconnect. */ + } + + /* Finally, check whether the connection is still open. This is + important because most servers implement liberal (short) timeout + on persistent connections. Wget can of course always reconnect + if the connection doesn't work out, but it's nicer to know in + advance. This test is a logical followup of the first test, but + is ""expensive"" and therefore placed at the end of the list. + + (Current implementation of test_socket_open has a nice side + effect that it treats sockets with pending data as ""closed"". + This is exactly what we want: if a broken server sends message + body in response to HEAD, or if it sends more than conent-length + data, we won't reuse the corrupted connection.) */ + + if (!test_socket_open (pconn.socket)) + { + /* Oops, the socket is no longer open. Now that we know that, + let's invalidate the persistent connection before returning + 0. */ + invalidate_persistent (); + return false; + } + + return true; +} +","@@ -613,9 +613,9 @@ struct response { + resp_header_*. */ + + static struct response * +-resp_new (const char *head) ++resp_new (char *head) + { +- const char *hdr; ++ char *hdr; + int count, size; + + struct response *resp = xnew0 (struct response); +@@ -644,15 +644,23 @@ resp_new (const char *head) + break; + + /* Find the end of HDR, including continuations. */ +- do ++ for (;;) + { +- const char *end = strchr (hdr, '\n'); ++ char *end = strchr (hdr, '\n'); ++ + if (end) + hdr = end + 1; + else + hdr += strlen (hdr); ++ ++ if (*hdr != ' ' && *hdr != '\t') ++ break; ++ ++ // continuation, transform \r and \n into spaces ++ *end = ' '; ++ if (end > head && end[-1] == '\r') ++ end[-1] = ' '; + } +- while (*hdr == ' ' || *hdr == '\t'); + } + DO_REALLOC (resp->headers, size, count + 1, const char *); + resp->headers[count] = NULL;",765,1096,2048 +17958,"static int x25_recvmsg(struct kiocb *iocb, struct socket *sock, + struct msghdr *msg, size_t size, + int flags) +{ + struct sock *sk = sock->sk; + struct x25_sock *x25 = x25_sk(sk); + struct sockaddr_x25 *sx25 = (struct sockaddr_x25 *)msg->msg_name; + size_t copied; + int qbit, header_len; + struct sk_buff *skb; + unsigned char *asmptr; + int rc = -ENOTCONN; + + lock_sock(sk); + + if (x25->neighbour == NULL) + goto out; + + header_len = x25->neighbour->extended ? + X25_EXT_MIN_LEN : X25_STD_MIN_LEN; + + /* + * This works for seqpacket too. The receiver has ordered the queue for + * us! We do one quick check first though + */ + if (sk->sk_state != TCP_ESTABLISHED) + goto out; + + if (flags & MSG_OOB) { + rc = -EINVAL; + if (sock_flag(sk, SOCK_URGINLINE) || + !skb_peek(&x25->interrupt_in_queue)) + goto out; + + skb = skb_dequeue(&x25->interrupt_in_queue); + + if (!pskb_may_pull(skb, X25_STD_MIN_LEN)) + goto out_free_dgram; + + skb_pull(skb, X25_STD_MIN_LEN); + + /* + * No Q bit information on Interrupt data. + */ + if (test_bit(X25_Q_BIT_FLAG, &x25->flags)) { + asmptr = skb_push(skb, 1); + *asmptr = 0x00; + } + + msg->msg_flags |= MSG_OOB; + } else { + /* Now we can treat all alike */ + release_sock(sk); + skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, + flags & MSG_DONTWAIT, &rc); + lock_sock(sk); + if (!skb) + goto out; + + if (!pskb_may_pull(skb, header_len)) + goto out_free_dgram; + + qbit = (skb->data[0] & X25_Q_BIT) == X25_Q_BIT; + + skb_pull(skb, header_len); + + if (test_bit(X25_Q_BIT_FLAG, &x25->flags)) { + asmptr = skb_push(skb, 1); + *asmptr = qbit; + } + } + + skb_reset_transport_header(skb); + copied = skb->len; + + if (copied > size) { + copied = size; + msg->msg_flags |= MSG_TRUNC; + } + + /* Currently, each datagram always contains a complete record */ + msg->msg_flags |= MSG_EOR; + + rc = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); + if (rc) + goto out_free_dgram; + + if (sx25) { + sx25->sx25_family = AF_X25; + sx25->sx25_addr = x25->dest_addr; + } + + msg->msg_namelen = sizeof(struct sockaddr_x25); + x25_check_rbuf(sk); + rc = copied; + out_free_dgram: + skb_free_datagram(sk, skb); +out: + release_sock(sk); + return rc; +} +",1,"static int x25_recvmsg(struct kiocb *iocb, struct socket *sock, + struct msghdr *msg, size_t size, + int flags) +{ + struct sock *sk = sock->sk; + struct x25_sock *x25 = x25_sk(sk); + struct sockaddr_x25 *sx25 = (struct sockaddr_x25 *)msg->msg_name; + size_t copied; + int qbit, header_len; + struct sk_buff *skb; + unsigned char *asmptr; + int rc = -ENOTCONN; + + lock_sock(sk); + + if (x25->neighbour == NULL) + goto out; + + header_len = x25->neighbour->extended ? + X25_EXT_MIN_LEN : X25_STD_MIN_LEN; + + /* + * This works for seqpacket too. The receiver has ordered the queue for + * us! We do one quick check first though + */ + if (sk->sk_state != TCP_ESTABLISHED) + goto out; + + if (flags & MSG_OOB) { + rc = -EINVAL; + if (sock_flag(sk, SOCK_URGINLINE) || + !skb_peek(&x25->interrupt_in_queue)) + goto out; + + skb = skb_dequeue(&x25->interrupt_in_queue); + + if (!pskb_may_pull(skb, X25_STD_MIN_LEN)) + goto out_free_dgram; + + skb_pull(skb, X25_STD_MIN_LEN); + + /* + * No Q bit information on Interrupt data. + */ + if (test_bit(X25_Q_BIT_FLAG, &x25->flags)) { + asmptr = skb_push(skb, 1); + *asmptr = 0x00; + } + + msg->msg_flags |= MSG_OOB; + } else { + /* Now we can treat all alike */ + release_sock(sk); + skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, + flags & MSG_DONTWAIT, &rc); + lock_sock(sk); + if (!skb) + goto out; + + if (!pskb_may_pull(skb, header_len)) + goto out_free_dgram; + + qbit = (skb->data[0] & X25_Q_BIT) == X25_Q_BIT; + + skb_pull(skb, header_len); + + if (test_bit(X25_Q_BIT_FLAG, &x25->flags)) { + asmptr = skb_push(skb, 1); + *asmptr = qbit; + } + } + + skb_reset_transport_header(skb); + copied = skb->len; + + if (copied > size) { + copied = size; + msg->msg_flags |= MSG_TRUNC; + } + + /* Currently, each datagram always contains a complete record */ + msg->msg_flags |= MSG_EOR; + + rc = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); + if (rc) + goto out_free_dgram; + + if (sx25) { + sx25->sx25_family = AF_X25; + sx25->sx25_addr = x25->dest_addr; + msg->msg_namelen = sizeof(*sx25); + } + + x25_check_rbuf(sk); + rc = copied; + out_free_dgram: + skb_free_datagram(sk, skb); +out: + release_sock(sk); + return rc; +} +","@@ -1340,10 +1340,9 @@ static int x25_recvmsg(struct kiocb *iocb, struct socket *sock, + if (sx25) { + sx25->sx25_family = AF_X25; + sx25->sx25_addr = x25->dest_addr; ++ msg->msg_namelen = sizeof(*sx25); + } + +- msg->msg_namelen = sizeof(struct sockaddr_x25); +- + x25_check_rbuf(sk); + rc = copied; + out_free_dgram:",747,1078,2048 +18782,"int main(int argc, char **argv) +{ + + u8 *byteStrmStart; + u8 *byteStrm; + u32 strmLen; + u32 picSize; + H264SwDecInst decInst; + H264SwDecRet ret; + H264SwDecInput decInput; + H264SwDecOutput decOutput; + H264SwDecPicture decPicture; + H264SwDecInfo decInfo; + u32 picNumber; + + FILE *finput; + FILE *foutput; + + /* Check that enough command line arguments given, if not -> print usage + * information out */ + if (argc < 2) + { + printf( ""Usage: %s file.h264\n"", argv[0]); + return -1; + } + + /* open output file for writing, output file named out.yuv. If file open + * fails -> exit */ + foutput = fopen(""out.yuv"", ""wb""); + if (foutput == NULL) + { + printf(""UNABLE TO OPEN OUTPUT FILE\n""); + return -1; + } + + /* open input file for reading, file name given by user. If file open + * fails -> exit */ + finput = fopen(argv[argc-1], ""rb""); + if (finput == NULL) + { + printf(""UNABLE TO OPEN INPUT FILE\n""); + return -1; + } + + /* check size of the input file -> length of the stream in bytes */ + fseek(finput, 0L, SEEK_END); + strmLen = (u32)ftell(finput); + + rewind(finput); + + /* allocate memory for stream buffer, exit if unsuccessful */ + byteStrm = byteStrmStart = (u8 *)H264SwDecMalloc(sizeof(u8)*strmLen); + if (byteStrm == NULL) + { + printf(""UNABLE TO ALLOCATE MEMORY\n""); + return -1; + } + + /* read input stream from file to buffer and close input file */ + fread(byteStrm, sizeof(u8), strmLen, finput); + fclose(finput); + + /* initialize decoder. If unsuccessful -> exit */ + ret = H264SwDecInit(&decInst, 0); + if (ret != H264SWDEC_OK) + { + printf(""DECODER INITIALIZATION FAILED\n""); + return -1; + } + + /* initialize H264SwDecDecode() input structure */ + decInput.pStream = byteStrmStart; + decInput.dataLen = strmLen; + decInput.intraConcealmentMethod = 0; + + picNumber = 0; + + /* For performance measurements, read the start time (in seconds) here. + * The decoding time should be measured over several frames and after + * that average fps (frames/second) can be calculated. + * + * startTime = GetTime(); + * + * To prevent calculating file I/O latensies as a decoding time, + * comment out WriteOutput function call. Also prints to stdout might + * consume considerable amount of cycles during measurement */ + + /* main decoding loop */ + do + { + /* call API function to perform decoding */ + ret = H264SwDecDecode(decInst, &decInput, &decOutput); + + switch(ret) + { + + case H264SWDEC_HDRS_RDY_BUFF_NOT_EMPTY: + + /* picture dimensions are available for query now */ + ret = H264SwDecGetInfo(decInst, &decInfo); + if (ret != H264SWDEC_OK) + return -1; + + /* picture size in pixels */ + picSize = decInfo.picWidth * decInfo.picHeight; + /* memory needed for YCbCr 4:2:0 picture in bytes */ + picSize = (3 * picSize)/2; + /* memory needed for 16-bit RGB picture in bytes + * picSize = (decInfo.picWidth * decInfo.picHeight) * 2; */ + + printf(""Width %d Height %d\n"", + decInfo.picWidth, decInfo.picHeight); + + /* update H264SwDecDecode() input structure, number of bytes + * ""consumed"" is computed as difference between the new stream + * pointer and old stream pointer */ + decInput.dataLen -= + (u32)(decOutput.pStrmCurrPos - decInput.pStream); + decInput.pStream = decOutput.pStrmCurrPos; + break; + + case H264SWDEC_PIC_RDY_BUFF_NOT_EMPTY: + case H264SWDEC_PIC_RDY: + + /* update H264SwDecDecode() input structure, number of bytes + * ""consumed"" is computed as difference between the new stream + * pointer and old stream pointer */ + decInput.dataLen -= + (u32)(decOutput.pStrmCurrPos - decInput.pStream); + decInput.pStream = decOutput.pStrmCurrPos; + + /* use function H264SwDecNextPicture() to obtain next picture + * in display order. Function is called until no more images + * are ready for display */ + while (H264SwDecNextPicture(decInst, &decPicture, 0) == + H264SWDEC_PIC_RDY) { picNumber++; + + printf(""PIC %d, type %s, concealed %d\n"", picNumber, + decPicture.isIdrPicture ? ""IDR"" : ""NON-IDR"", + decPicture.nbrOfErrMBs); + fflush(stdout); + + /* Do color conversion if needed to get display image + * in RGB-format + * + * YuvToRgb( decPicture.pOutputPicture, pRgbPicture ); */ + + /* write next display image to output file */ + WriteOutput(foutput, (u8*)decPicture.pOutputPicture, + picSize); + } + + break; + + case H264SWDEC_EVALUATION_LIMIT_EXCEEDED: + /* evaluation version of the decoder has limited decoding + * capabilities */ + printf(""EVALUATION LIMIT REACHED\n""); + goto end; + + default: + printf(""UNRECOVERABLE ERROR\n""); + return -1; + } + /* keep decoding until all data from input stream buffer consumed */ + } while (decInput.dataLen > 0); + +end: + + /* if output in display order is preferred, the decoder shall be forced + * to output pictures remaining in decoded picture buffer. Use function + * H264SwDecNextPicture() to obtain next picture in display order. Function + * is called until no more images are ready for display. Second parameter + * for the function is set to '1' to indicate that this is end of the + * stream and all pictures shall be output */ + while (H264SwDecNextPicture(decInst, &decPicture, 1) == + H264SWDEC_PIC_RDY) { + + picNumber++; + + printf(""PIC %d, type %s, concealed %d\n"", picNumber, + decPicture.isIdrPicture ? ""IDR"" : ""NON-IDR"", + decPicture.nbrOfErrMBs); + fflush(stdout); + + /* Do color conversion if needed to get display image + * in RGB-format + * + * YuvToRgb( decPicture.pOutputPicture, pRgbPicture ); */ + + /* write next display image to output file */ + WriteOutput(foutput, (u8*)decPicture.pOutputPicture, picSize); + } + + /* For performance measurements, read the end time (in seconds) here. + * + * endTime = GetTime(); + * + * Now the performance can be calculated as frames per second: + * fps = picNumber / (endTime - startTime); */ + + + /* release decoder instance */ + H264SwDecRelease(decInst); + + /* close output file */ + fclose(foutput); + + /* free byte stream buffer */ + free(byteStrmStart); + + return 0; + +} +",1,"int main(int argc, char **argv) +{ + + u8 *byteStrmStart; + u8 *byteStrm; + u32 strmLen; + u32 picSize; + H264SwDecInst decInst; + H264SwDecRet ret; + H264SwDecInput decInput; + H264SwDecOutput decOutput; + H264SwDecPicture decPicture; + H264SwDecInfo decInfo; + u32 picNumber; + + FILE *finput; + FILE *foutput; + + /* Check that enough command line arguments given, if not -> print usage + * information out */ + if (argc < 2) + { + printf( ""Usage: %s file.h264\n"", argv[0]); + return -1; + } + + /* open output file for writing, output file named out.yuv. If file open + * fails -> exit */ + foutput = fopen(""out.yuv"", ""wb""); + if (foutput == NULL) + { + printf(""UNABLE TO OPEN OUTPUT FILE\n""); + return -1; + } + + /* open input file for reading, file name given by user. If file open + * fails -> exit */ + finput = fopen(argv[argc-1], ""rb""); + if (finput == NULL) + { + printf(""UNABLE TO OPEN INPUT FILE\n""); + return -1; + } + + /* check size of the input file -> length of the stream in bytes */ + fseek(finput, 0L, SEEK_END); + strmLen = (u32)ftell(finput); + + rewind(finput); + + /* allocate memory for stream buffer, exit if unsuccessful */ + byteStrm = byteStrmStart = (u8 *)H264SwDecMalloc(sizeof(u8), strmLen); + if (byteStrm == NULL) + { + printf(""UNABLE TO ALLOCATE MEMORY\n""); + return -1; + } + + /* read input stream from file to buffer and close input file */ + fread(byteStrm, sizeof(u8), strmLen, finput); + fclose(finput); + + /* initialize decoder. If unsuccessful -> exit */ + ret = H264SwDecInit(&decInst, 0); + if (ret != H264SWDEC_OK) + { + printf(""DECODER INITIALIZATION FAILED\n""); + return -1; + } + + /* initialize H264SwDecDecode() input structure */ + decInput.pStream = byteStrmStart; + decInput.dataLen = strmLen; + decInput.intraConcealmentMethod = 0; + + picNumber = 0; + + /* For performance measurements, read the start time (in seconds) here. + * The decoding time should be measured over several frames and after + * that average fps (frames/second) can be calculated. + * + * startTime = GetTime(); + * + * To prevent calculating file I/O latensies as a decoding time, + * comment out WriteOutput function call. Also prints to stdout might + * consume considerable amount of cycles during measurement */ + + /* main decoding loop */ + do + { + /* call API function to perform decoding */ + ret = H264SwDecDecode(decInst, &decInput, &decOutput); + + switch(ret) + { + + case H264SWDEC_HDRS_RDY_BUFF_NOT_EMPTY: + + /* picture dimensions are available for query now */ + ret = H264SwDecGetInfo(decInst, &decInfo); + if (ret != H264SWDEC_OK) + return -1; + + /* picture size in pixels */ + picSize = decInfo.picWidth * decInfo.picHeight; + /* memory needed for YCbCr 4:2:0 picture in bytes */ + picSize = (3 * picSize)/2; + /* memory needed for 16-bit RGB picture in bytes + * picSize = (decInfo.picWidth * decInfo.picHeight) * 2; */ + + printf(""Width %d Height %d\n"", + decInfo.picWidth, decInfo.picHeight); + + /* update H264SwDecDecode() input structure, number of bytes + * ""consumed"" is computed as difference between the new stream + * pointer and old stream pointer */ + decInput.dataLen -= + (u32)(decOutput.pStrmCurrPos - decInput.pStream); + decInput.pStream = decOutput.pStrmCurrPos; + break; + + case H264SWDEC_PIC_RDY_BUFF_NOT_EMPTY: + case H264SWDEC_PIC_RDY: + + /* update H264SwDecDecode() input structure, number of bytes + * ""consumed"" is computed as difference between the new stream + * pointer and old stream pointer */ + decInput.dataLen -= + (u32)(decOutput.pStrmCurrPos - decInput.pStream); + decInput.pStream = decOutput.pStrmCurrPos; + + /* use function H264SwDecNextPicture() to obtain next picture + * in display order. Function is called until no more images + * are ready for display */ + while (H264SwDecNextPicture(decInst, &decPicture, 0) == + H264SWDEC_PIC_RDY) { picNumber++; + + printf(""PIC %d, type %s, concealed %d\n"", picNumber, + decPicture.isIdrPicture ? ""IDR"" : ""NON-IDR"", + decPicture.nbrOfErrMBs); + fflush(stdout); + + /* Do color conversion if needed to get display image + * in RGB-format + * + * YuvToRgb( decPicture.pOutputPicture, pRgbPicture ); */ + + /* write next display image to output file */ + WriteOutput(foutput, (u8*)decPicture.pOutputPicture, + picSize); + } + + break; + + case H264SWDEC_EVALUATION_LIMIT_EXCEEDED: + /* evaluation version of the decoder has limited decoding + * capabilities */ + printf(""EVALUATION LIMIT REACHED\n""); + goto end; + + default: + printf(""UNRECOVERABLE ERROR\n""); + return -1; + } + /* keep decoding until all data from input stream buffer consumed */ + } while (decInput.dataLen > 0); + +end: + + /* if output in display order is preferred, the decoder shall be forced + * to output pictures remaining in decoded picture buffer. Use function + * H264SwDecNextPicture() to obtain next picture in display order. Function + * is called until no more images are ready for display. Second parameter + * for the function is set to '1' to indicate that this is end of the + * stream and all pictures shall be output */ + while (H264SwDecNextPicture(decInst, &decPicture, 1) == + H264SWDEC_PIC_RDY) { + + picNumber++; + + printf(""PIC %d, type %s, concealed %d\n"", picNumber, + decPicture.isIdrPicture ? ""IDR"" : ""NON-IDR"", + decPicture.nbrOfErrMBs); + fflush(stdout); + + /* Do color conversion if needed to get display image + * in RGB-format + * + * YuvToRgb( decPicture.pOutputPicture, pRgbPicture ); */ + + /* write next display image to output file */ + WriteOutput(foutput, (u8*)decPicture.pOutputPicture, picSize); + } + + /* For performance measurements, read the end time (in seconds) here. + * + * endTime = GetTime(); + * + * Now the performance can be calculated as frames per second: + * fps = picNumber / (endTime - startTime); */ + + + /* release decoder instance */ + H264SwDecRelease(decInst); + + /* close output file */ + fclose(foutput); + + /* free byte stream buffer */ + free(byteStrmStart); + + return 0; + +} +","@@ -85,7 +85,7 @@ + + rewind(finput); + + /* allocate memory for stream buffer, exit if unsuccessful */ +- byteStrm = byteStrmStart = (u8 *)H264SwDecMalloc(sizeof(u8)*strmLen); ++ byteStrm = byteStrmStart = (u8 *)H264SwDecMalloc(sizeof(u8), strmLen); + if (byteStrm == NULL) + { + printf(""UNABLE TO ALLOCATE MEMORY\n""); +@@ -298,9 +298,12 @@ + + library function malloc for allocation of memory. + + ------------------------------------------------------------------------------*/ +-void* H264SwDecMalloc(u32 size) ++void* H264SwDecMalloc(u32 size, u32 num) + { +- return malloc(size); ++ if (size > UINT32_MAX / num) { ++ return NULL; ++ } ++ return malloc(size * num); + } + + /*------------------------------------------------------------------------------ +",1669,2000,2048 +7441,"static int ivr_read_header(AVFormatContext *s) +{ + unsigned tag, type, len, tlen, value; + int i, j, n, count, nb_streams = 0, ret; + uint8_t key[256], val[256]; + AVIOContext *pb = s->pb; + AVStream *st; + int64_t pos, offset, temp; + + pos = avio_tell(pb); + tag = avio_rl32(pb); + if (tag == MKTAG('.','R','1','M')) { + if (avio_rb16(pb) != 1) + return AVERROR_INVALIDDATA; + if (avio_r8(pb) != 1) + return AVERROR_INVALIDDATA; + len = avio_rb32(pb); + avio_skip(pb, len); + avio_skip(pb, 5); + temp = avio_rb64(pb); + while (!avio_feof(pb) && temp) { + offset = temp; + temp = avio_rb64(pb); + } + avio_skip(pb, offset - avio_tell(pb)); + if (avio_r8(pb) != 1) + return AVERROR_INVALIDDATA; + len = avio_rb32(pb); + avio_skip(pb, len); + if (avio_r8(pb) != 2) + return AVERROR_INVALIDDATA; + avio_skip(pb, 16); + pos = avio_tell(pb); + tag = avio_rl32(pb); + } + + if (tag != MKTAG('.','R','E','C')) + return AVERROR_INVALIDDATA; + + if (avio_r8(pb) != 0) + return AVERROR_INVALIDDATA; + count = avio_rb32(pb); + for (i = 0; i < count; i++) { + if (avio_feof(pb)) + return AVERROR_INVALIDDATA; + + type = avio_r8(pb); + tlen = avio_rb32(pb); + avio_get_str(pb, tlen, key, sizeof(key)); + len = avio_rb32(pb); + if (type == 5) { + avio_get_str(pb, len, val, sizeof(val)); + av_log(s, AV_LOG_DEBUG, ""%s = '%s'\n"", key, val); + } else if (type == 4) { + av_log(s, AV_LOG_DEBUG, ""%s = '0x"", key); + for (j = 0; j < len; j++) { + if (avio_feof(pb)) + return AVERROR_INVALIDDATA; + av_log(s, AV_LOG_DEBUG, ""%X"", avio_r8(pb)); + } + av_log(s, AV_LOG_DEBUG, ""'\n""); + } else if (len == 4 && type == 3 && !strncmp(key, ""StreamCount"", tlen)) { + nb_streams = value = avio_rb32(pb); + } else if (len == 4 && type == 3) { + value = avio_rb32(pb); + av_log(s, AV_LOG_DEBUG, ""%s = %d\n"", key, value); + } else { + av_log(s, AV_LOG_DEBUG, ""Skipping unsupported key: %s\n"", key); + avio_skip(pb, len); + } + } + + for (n = 0; n < nb_streams; n++) { + st = avformat_new_stream(s, NULL); + if (!st) + return AVERROR(ENOMEM); + st->priv_data = ff_rm_alloc_rmstream(); + if (!st->priv_data) + return AVERROR(ENOMEM); + + if (avio_r8(pb) != 1) + return AVERROR_INVALIDDATA; + + count = avio_rb32(pb); + for (i = 0; i < count; i++) { + if (avio_feof(pb)) + return AVERROR_INVALIDDATA; + + type = avio_r8(pb); + tlen = avio_rb32(pb); + avio_get_str(pb, tlen, key, sizeof(key)); + len = avio_rb32(pb); + if (type == 5) { + avio_get_str(pb, len, val, sizeof(val)); + av_log(s, AV_LOG_DEBUG, ""%s = '%s'\n"", key, val); + } else if (type == 4 && !strncmp(key, ""OpaqueData"", tlen)) { + ret = ffio_ensure_seekback(pb, 4); + if (ret < 0) + return ret; + if (avio_rb32(pb) == MKBETAG('M', 'L', 'T', 'I')) { + ret = rm_read_multi(s, pb, st, NULL); + } else { + avio_seek(pb, -4, SEEK_CUR); + ret = ff_rm_read_mdpr_codecdata(s, pb, st, st->priv_data, len, NULL); + } + + if (ret < 0) + return ret; + } else if (type == 4) { + int j; + + av_log(s, AV_LOG_DEBUG, ""%s = '0x"", key); + for (j = 0; j < len; j++) + av_log(s, AV_LOG_DEBUG, ""%X"", avio_r8(pb)); + av_log(s, AV_LOG_DEBUG, ""'\n""); + } else if (len == 4 && type == 3 && !strncmp(key, ""Duration"", tlen)) { + st->duration = avio_rb32(pb); + } else if (len == 4 && type == 3) { + value = avio_rb32(pb); + av_log(s, AV_LOG_DEBUG, ""%s = %d\n"", key, value); + } else { + av_log(s, AV_LOG_DEBUG, ""Skipping unsupported key: %s\n"", key); + avio_skip(pb, len); + } + } + } + + if (avio_r8(pb) != 6) + return AVERROR_INVALIDDATA; + avio_skip(pb, 12); + avio_skip(pb, avio_rb64(pb) + pos - avio_tell(s->pb)); + if (avio_r8(pb) != 8) + return AVERROR_INVALIDDATA; + avio_skip(pb, 8); + + return 0; +} +",0,"static int ivr_read_header(AVFormatContext *s) +{ + unsigned tag, type, len, tlen, value; + int i, j, n, count, nb_streams = 0, ret; + uint8_t key[256], val[256]; + AVIOContext *pb = s->pb; + AVStream *st; + int64_t pos, offset, temp; + + pos = avio_tell(pb); + tag = avio_rl32(pb); + if (tag == MKTAG('.','R','1','M')) { + if (avio_rb16(pb) != 1) + return AVERROR_INVALIDDATA; + if (avio_r8(pb) != 1) + return AVERROR_INVALIDDATA; + len = avio_rb32(pb); + avio_skip(pb, len); + avio_skip(pb, 5); + temp = avio_rb64(pb); + while (!avio_feof(pb) && temp) { + offset = temp; + temp = avio_rb64(pb); + } + avio_skip(pb, offset - avio_tell(pb)); + if (avio_r8(pb) != 1) + return AVERROR_INVALIDDATA; + len = avio_rb32(pb); + avio_skip(pb, len); + if (avio_r8(pb) != 2) + return AVERROR_INVALIDDATA; + avio_skip(pb, 16); + pos = avio_tell(pb); + tag = avio_rl32(pb); + } + + if (tag != MKTAG('.','R','E','C')) + return AVERROR_INVALIDDATA; + + if (avio_r8(pb) != 0) + return AVERROR_INVALIDDATA; + count = avio_rb32(pb); + for (i = 0; i < count; i++) { + if (avio_feof(pb)) + return AVERROR_INVALIDDATA; + + type = avio_r8(pb); + tlen = avio_rb32(pb); + avio_get_str(pb, tlen, key, sizeof(key)); + len = avio_rb32(pb); + if (type == 5) { + avio_get_str(pb, len, val, sizeof(val)); + av_log(s, AV_LOG_DEBUG, ""%s = '%s'\n"", key, val); + } else if (type == 4) { + av_log(s, AV_LOG_DEBUG, ""%s = '0x"", key); + for (j = 0; j < len; j++) { + if (avio_feof(pb)) + return AVERROR_INVALIDDATA; + av_log(s, AV_LOG_DEBUG, ""%X"", avio_r8(pb)); + } + av_log(s, AV_LOG_DEBUG, ""'\n""); + } else if (len == 4 && type == 3 && !strncmp(key, ""StreamCount"", tlen)) { + nb_streams = value = avio_rb32(pb); + } else if (len == 4 && type == 3) { + value = avio_rb32(pb); + av_log(s, AV_LOG_DEBUG, ""%s = %d\n"", key, value); + } else { + av_log(s, AV_LOG_DEBUG, ""Skipping unsupported key: %s\n"", key); + avio_skip(pb, len); + } + } + + for (n = 0; n < nb_streams; n++) { + st = avformat_new_stream(s, NULL); + if (!st) + return AVERROR(ENOMEM); + st->priv_data = ff_rm_alloc_rmstream(); + if (!st->priv_data) + return AVERROR(ENOMEM); + + if (avio_r8(pb) != 1) + return AVERROR_INVALIDDATA; + + count = avio_rb32(pb); + for (i = 0; i < count; i++) { + if (avio_feof(pb)) + return AVERROR_INVALIDDATA; + + type = avio_r8(pb); + tlen = avio_rb32(pb); + avio_get_str(pb, tlen, key, sizeof(key)); + len = avio_rb32(pb); + if (type == 5) { + avio_get_str(pb, len, val, sizeof(val)); + av_log(s, AV_LOG_DEBUG, ""%s = '%s'\n"", key, val); + } else if (type == 4 && !strncmp(key, ""OpaqueData"", tlen)) { + ret = ffio_ensure_seekback(pb, 4); + if (ret < 0) + return ret; + if (avio_rb32(pb) == MKBETAG('M', 'L', 'T', 'I')) { + ret = rm_read_multi(s, pb, st, NULL); + } else { + avio_seek(pb, -4, SEEK_CUR); + ret = ff_rm_read_mdpr_codecdata(s, pb, st, st->priv_data, len, NULL); + } + + if (ret < 0) + return ret; + } else if (type == 4) { + int j; + + av_log(s, AV_LOG_DEBUG, ""%s = '0x"", key); + for (j = 0; j < len; j++) + av_log(s, AV_LOG_DEBUG, ""%X"", avio_r8(pb)); + av_log(s, AV_LOG_DEBUG, ""'\n""); + } else if (len == 4 && type == 3 && !strncmp(key, ""Duration"", tlen)) { + st->duration = avio_rb32(pb); + } else if (len == 4 && type == 3) { + value = avio_rb32(pb); + av_log(s, AV_LOG_DEBUG, ""%s = %d\n"", key, value); + } else { + av_log(s, AV_LOG_DEBUG, ""Skipping unsupported key: %s\n"", key); + avio_skip(pb, len); + } + } + } + + if (avio_r8(pb) != 6) + return AVERROR_INVALIDDATA; + avio_skip(pb, 12); + avio_skip(pb, avio_rb64(pb) + pos - avio_tell(s->pb)); + if (avio_r8(pb) != 8) + return AVERROR_INVALIDDATA; + avio_skip(pb, 8); + + return 0; +} +","@@ -522,7 +522,7 @@ static int rm_read_multi(AVFormatContext *s, AVIOContext *pb, + + size2 = avio_rb32(pb); + ret = ff_rm_read_mdpr_codecdata(s, s->pb, st2, st2->priv_data, +- size2, mime); ++ size2, NULL); + if (ret < 0) + return ret; + }",1375,1706,2048 +17650,"xmlParserHandlePEReference(xmlParserCtxtPtr ctxt) { + const xmlChar *name; + xmlEntityPtr entity = NULL; + xmlParserInputPtr input; + + if (RAW != '%') return; + switch(ctxt->instate) { + case XML_PARSER_CDATA_SECTION: + return; + case XML_PARSER_COMMENT: + return; + case XML_PARSER_START_TAG: + return; + case XML_PARSER_END_TAG: + return; + case XML_PARSER_EOF: + xmlFatalErr(ctxt, XML_ERR_PEREF_AT_EOF, NULL); + return; + case XML_PARSER_PROLOG: + case XML_PARSER_START: + case XML_PARSER_MISC: + xmlFatalErr(ctxt, XML_ERR_PEREF_IN_PROLOG, NULL); + return; + case XML_PARSER_ENTITY_DECL: + case XML_PARSER_CONTENT: + case XML_PARSER_ATTRIBUTE_VALUE: + case XML_PARSER_PI: + case XML_PARSER_SYSTEM_LITERAL: + case XML_PARSER_PUBLIC_LITERAL: + /* we just ignore it there */ + return; + case XML_PARSER_EPILOG: + xmlFatalErr(ctxt, XML_ERR_PEREF_IN_EPILOG, NULL); + return; + case XML_PARSER_ENTITY_VALUE: + /* + * NOTE: in the case of entity values, we don't do the + * substitution here since we need the literal + * entity value to be able to save the internal + * subset of the document. + * This will be handled by xmlStringDecodeEntities + */ + return; + case XML_PARSER_DTD: + /* + * [WFC: Well-Formedness Constraint: PEs in Internal Subset] + * In the internal DTD subset, parameter-entity references + * can occur only where markup declarations can occur, not + * within markup declarations. + * In that case this is handled in xmlParseMarkupDecl + */ + if ((ctxt->external == 0) && (ctxt->inputNr == 1)) + return; + if (IS_BLANK_CH(NXT(1)) || NXT(1) == 0) + return; + break; + case XML_PARSER_IGNORE: + return; + } + + NEXT; + name = xmlParseName(ctxt); + if (xmlParserDebugEntities) + xmlGenericError(xmlGenericErrorContext, + ""PEReference: %s\n"", name); + if (name == NULL) { + xmlFatalErr(ctxt, XML_ERR_PEREF_NO_NAME, NULL); + } else { + if (RAW == ';') { + NEXT; + if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL)) + entity = ctxt->sax->getParameterEntity(ctxt->userData, name); + if (ctxt->instate == XML_PARSER_EOF) + return; + if (entity == NULL) { + + /* + * [ WFC: Entity Declared ] + * In a document without any DTD, a document with only an + * internal DTD subset which contains no parameter entity + * references, or a document with ""standalone='yes'"", ... + * ... The declaration of a parameter entity must precede + * any reference to it... + */ + if ((ctxt->standalone == 1) || + ((ctxt->hasExternalSubset == 0) && + (ctxt->hasPErefs == 0))) { + xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY, + ""PEReference: %%%s; not found\n"", name); + } else { + /* + * [ VC: Entity Declared ] + * In a document with an external subset or external + * parameter entities with ""standalone='no'"", ... + * ... The declaration of a parameter entity must precede + * any reference to it... + */ + if ((ctxt->validate) && (ctxt->vctxt.error != NULL)) { + xmlValidityError(ctxt, XML_WAR_UNDECLARED_ENTITY, + ""PEReference: %%%s; not found\n"", + name, NULL); + } else + xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, + ""PEReference: %%%s; not found\n"", + name, NULL); + ctxt->valid = 0; + } + xmlParserEntityCheck(ctxt, 0, NULL, 0); + } else if (ctxt->input->free != deallocblankswrapper) { + input = xmlNewBlanksWrapperInputStream(ctxt, entity); + if (xmlPushInput(ctxt, input) < 0) + return; + } else { + if ((entity->etype == XML_INTERNAL_PARAMETER_ENTITY) || + (entity->etype == XML_EXTERNAL_PARAMETER_ENTITY)) { + xmlChar start[4]; + xmlCharEncoding enc; + + /* + * Note: external parameter entities will not be loaded, it + * is not required for a non-validating parser, unless the + * option of validating, or substituting entities were + * given. Doing so is far more secure as the parser will + * only process data coming from the document entity by + * default. + */ + if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) && + ((ctxt->options & XML_PARSE_NOENT) == 0) && + ((ctxt->options & XML_PARSE_DTDVALID) == 0) && + ((ctxt->options & XML_PARSE_DTDLOAD) == 0) && + ((ctxt->options & XML_PARSE_DTDATTR) == 0) && + (ctxt->replaceEntities == 0) && + (ctxt->validate == 0)) + return; + + /* + * handle the extra spaces added before and after + * c.f. http://www.w3.org/TR/REC-xml#as-PE + * this is done independently. + */ + input = xmlNewEntityInputStream(ctxt, entity); + if (xmlPushInput(ctxt, input) < 0) + return; + + /* + * Get the 4 first bytes and decode the charset + * if enc != XML_CHAR_ENCODING_NONE + * plug some encoding conversion routines. + * Note that, since we may have some non-UTF8 + * encoding (like UTF16, bug 135229), the 'length' + * is not known, but we can calculate based upon + * the amount of data in the buffer. + */ + GROW + if (ctxt->instate == XML_PARSER_EOF) + return; + if ((ctxt->input->end - ctxt->input->cur)>=4) { + start[0] = RAW; + start[1] = NXT(1); + start[2] = NXT(2); + start[3] = NXT(3); + enc = xmlDetectCharEncoding(start, 4); + if (enc != XML_CHAR_ENCODING_NONE) { + xmlSwitchEncoding(ctxt, enc); + } + } + + if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) && + (CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l' )) && + (IS_BLANK_CH(NXT(5)))) { + xmlParseTextDecl(ctxt); + } + } else { + xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER, + ""PEReference: %s is not a parameter entity\n"", + name); + } + } + } else { + xmlFatalErr(ctxt, XML_ERR_PEREF_SEMICOL_MISSING, NULL); + } + } +} +",0,"xmlParserHandlePEReference(xmlParserCtxtPtr ctxt) { + const xmlChar *name; + xmlEntityPtr entity = NULL; + xmlParserInputPtr input; + + if (RAW != '%') return; + switch(ctxt->instate) { + case XML_PARSER_CDATA_SECTION: + return; + case XML_PARSER_COMMENT: + return; + case XML_PARSER_START_TAG: + return; + case XML_PARSER_END_TAG: + return; + case XML_PARSER_EOF: + xmlFatalErr(ctxt, XML_ERR_PEREF_AT_EOF, NULL); + return; + case XML_PARSER_PROLOG: + case XML_PARSER_START: + case XML_PARSER_MISC: + xmlFatalErr(ctxt, XML_ERR_PEREF_IN_PROLOG, NULL); + return; + case XML_PARSER_ENTITY_DECL: + case XML_PARSER_CONTENT: + case XML_PARSER_ATTRIBUTE_VALUE: + case XML_PARSER_PI: + case XML_PARSER_SYSTEM_LITERAL: + case XML_PARSER_PUBLIC_LITERAL: + /* we just ignore it there */ + return; + case XML_PARSER_EPILOG: + xmlFatalErr(ctxt, XML_ERR_PEREF_IN_EPILOG, NULL); + return; + case XML_PARSER_ENTITY_VALUE: + /* + * NOTE: in the case of entity values, we don't do the + * substitution here since we need the literal + * entity value to be able to save the internal + * subset of the document. + * This will be handled by xmlStringDecodeEntities + */ + return; + case XML_PARSER_DTD: + /* + * [WFC: Well-Formedness Constraint: PEs in Internal Subset] + * In the internal DTD subset, parameter-entity references + * can occur only where markup declarations can occur, not + * within markup declarations. + * In that case this is handled in xmlParseMarkupDecl + */ + if ((ctxt->external == 0) && (ctxt->inputNr == 1)) + return; + if (IS_BLANK_CH(NXT(1)) || NXT(1) == 0) + return; + break; + case XML_PARSER_IGNORE: + return; + } + + NEXT; + name = xmlParseName(ctxt); + if (xmlParserDebugEntities) + xmlGenericError(xmlGenericErrorContext, + ""PEReference: %s\n"", name); + if (name == NULL) { + xmlFatalErr(ctxt, XML_ERR_PEREF_NO_NAME, NULL); + } else { + if (RAW == ';') { + NEXT; + if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL)) + entity = ctxt->sax->getParameterEntity(ctxt->userData, name); + if (ctxt->instate == XML_PARSER_EOF) + return; + if (entity == NULL) { + + /* + * [ WFC: Entity Declared ] + * In a document without any DTD, a document with only an + * internal DTD subset which contains no parameter entity + * references, or a document with ""standalone='yes'"", ... + * ... The declaration of a parameter entity must precede + * any reference to it... + */ + if ((ctxt->standalone == 1) || + ((ctxt->hasExternalSubset == 0) && + (ctxt->hasPErefs == 0))) { + xmlFatalErrMsgStr(ctxt, XML_ERR_UNDECLARED_ENTITY, + ""PEReference: %%%s; not found\n"", name); + } else { + /* + * [ VC: Entity Declared ] + * In a document with an external subset or external + * parameter entities with ""standalone='no'"", ... + * ... The declaration of a parameter entity must precede + * any reference to it... + */ + if ((ctxt->validate) && (ctxt->vctxt.error != NULL)) { + xmlValidityError(ctxt, XML_WAR_UNDECLARED_ENTITY, + ""PEReference: %%%s; not found\n"", + name, NULL); + } else + xmlWarningMsg(ctxt, XML_WAR_UNDECLARED_ENTITY, + ""PEReference: %%%s; not found\n"", + name, NULL); + ctxt->valid = 0; + } + xmlParserEntityCheck(ctxt, 0, NULL, 0); + } else if (ctxt->input->free != deallocblankswrapper) { + input = xmlNewBlanksWrapperInputStream(ctxt, entity); + if (xmlPushInput(ctxt, input) < 0) + return; + } else { + if ((entity->etype == XML_INTERNAL_PARAMETER_ENTITY) || + (entity->etype == XML_EXTERNAL_PARAMETER_ENTITY)) { + xmlChar start[4]; + xmlCharEncoding enc; + + /* + * Note: external parameter entities will not be loaded, it + * is not required for a non-validating parser, unless the + * option of validating, or substituting entities were + * given. Doing so is far more secure as the parser will + * only process data coming from the document entity by + * default. + */ + if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) && + ((ctxt->options & XML_PARSE_NOENT) == 0) && + ((ctxt->options & XML_PARSE_DTDVALID) == 0) && + ((ctxt->options & XML_PARSE_DTDLOAD) == 0) && + ((ctxt->options & XML_PARSE_DTDATTR) == 0) && + (ctxt->replaceEntities == 0) && + (ctxt->validate == 0)) + return; + + /* + * handle the extra spaces added before and after + * c.f. http://www.w3.org/TR/REC-xml#as-PE + * this is done independently. + */ + input = xmlNewEntityInputStream(ctxt, entity); + if (xmlPushInput(ctxt, input) < 0) + return; + + /* + * Get the 4 first bytes and decode the charset + * if enc != XML_CHAR_ENCODING_NONE + * plug some encoding conversion routines. + * Note that, since we may have some non-UTF8 + * encoding (like UTF16, bug 135229), the 'length' + * is not known, but we can calculate based upon + * the amount of data in the buffer. + */ + GROW + if (ctxt->instate == XML_PARSER_EOF) + return; + if ((ctxt->input->end - ctxt->input->cur)>=4) { + start[0] = RAW; + start[1] = NXT(1); + start[2] = NXT(2); + start[3] = NXT(3); + enc = xmlDetectCharEncoding(start, 4); + if (enc != XML_CHAR_ENCODING_NONE) { + xmlSwitchEncoding(ctxt, enc); + } + } + + if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) && + (CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l' )) && + (IS_BLANK_CH(NXT(5)))) { + xmlParseTextDecl(ctxt); + } + } else { + xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_IS_PARAMETER, + ""PEReference: %s is not a parameter entity\n"", + name); + } + } + } else { + xmlFatalErr(ctxt, XML_ERR_PEREF_SEMICOL_MISSING, NULL); + } + } +} +","@@ -8130,6 +8130,14 @@ + + if (xmlPushInput(ctxt, input) < 0) + return; + } else { ++ if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) && ++ ((ctxt->options & XML_PARSE_NOENT) == 0) && ++ ((ctxt->options & XML_PARSE_DTDVALID) == 0) && ++ ((ctxt->options & XML_PARSE_DTDLOAD) == 0) && ++ ((ctxt->options & XML_PARSE_DTDATTR) == 0) && ++ (ctxt->replaceEntities == 0) && ++ (ctxt->validate == 0)) ++ return; + /* + * TODO !!! + * handle the extra spaces added before and after +",1492,1823,2048 +17330,"OMX_ERRORTYPE omx_vdec::component_role_enum(OMX_IN OMX_HANDLETYPE hComp, + OMX_OUT OMX_U8* role, + OMX_IN OMX_U32 index) +{ + (void) hComp; + OMX_ERRORTYPE eRet = OMX_ErrorNone; + + if (!strncmp(drv_ctx.kind, ""OMX.qcom.video.decoder.mpeg4"",OMX_MAX_STRINGNAME_SIZE)) { + if ((0 == index) && role) { + strlcpy((char *)role, ""video_decoder.mpeg4"",OMX_MAX_STRINGNAME_SIZE); + DEBUG_PRINT_LOW(""component_role_enum: role %s"",role); + } else { + eRet = OMX_ErrorNoMore; + } + } + if (!strncmp(drv_ctx.kind, ""OMX.qcom.video.decoder.mpeg2"",OMX_MAX_STRINGNAME_SIZE)) { + if ((0 == index) && role) { + strlcpy((char *)role, ""video_decoder.mpeg2"",OMX_MAX_STRINGNAME_SIZE); + DEBUG_PRINT_LOW(""component_role_enum: role %s"",role); + } else { + eRet = OMX_ErrorNoMore; + } + } else if (!strncmp(drv_ctx.kind, ""OMX.qcom.video.decoder.h263"",OMX_MAX_STRINGNAME_SIZE)) { + if ((0 == index) && role) { + strlcpy((char *)role, ""video_decoder.h263"",OMX_MAX_STRINGNAME_SIZE); + DEBUG_PRINT_LOW(""component_role_enum: role %s"",role); + } else { + DEBUG_PRINT_LOW(""No more roles""); + eRet = OMX_ErrorNoMore; + } + } + + else if ((!strncmp(drv_ctx.kind, ""OMX.qcom.video.decoder.divx"",OMX_MAX_STRINGNAME_SIZE)) || + (!strncmp(drv_ctx.kind, ""OMX.qcom.video.decoder.divx311"",OMX_MAX_STRINGNAME_SIZE))) { + if ((0 == index) && role) { + strlcpy((char *)role, ""video_decoder.divx"",OMX_MAX_STRINGNAME_SIZE); + DEBUG_PRINT_LOW(""component_role_enum: role %s"",role); + } else { + DEBUG_PRINT_LOW(""No more roles""); + eRet = OMX_ErrorNoMore; + } + } else if (!strncmp(drv_ctx.kind, ""OMX.qcom.video.decoder.avc"",OMX_MAX_STRINGNAME_SIZE)) { + if ((0 == index) && role) { + strlcpy((char *)role, ""video_decoder.avc"",OMX_MAX_STRINGNAME_SIZE); + DEBUG_PRINT_LOW(""component_role_enum: role %s"",role); + } else { + DEBUG_PRINT_LOW(""No more roles""); + eRet = OMX_ErrorNoMore; + } + } else if (!strncmp(drv_ctx.kind, ""OMX.qcom.video.decoder.mvc"", OMX_MAX_STRINGNAME_SIZE)) { + if ((0 == index) && role) { + strlcpy((char *)role, ""video_decoder.mvc"", OMX_MAX_STRINGNAME_SIZE); + DEBUG_PRINT_LOW(""component_role_enum: role %s"",role); + } else { + DEBUG_PRINT_LOW(""No more roles""); + eRet = OMX_ErrorNoMore; + } + } else if (!strncmp(drv_ctx.kind, ""OMX.qcom.video.decoder.hevc"", OMX_MAX_STRINGNAME_SIZE)) { + if ((0 == index) && role) { + strlcpy((char *)role, ""video_decoder.hevc"", OMX_MAX_STRINGNAME_SIZE); + DEBUG_PRINT_LOW(""component_role_enum: role %s"", role); + } else { + DEBUG_PRINT_LOW(""No more roles""); + eRet = OMX_ErrorNoMore; + } + } else if ( (!strncmp(drv_ctx.kind, ""OMX.qcom.video.decoder.vc1"",OMX_MAX_STRINGNAME_SIZE)) || + (!strncmp(drv_ctx.kind, ""OMX.qcom.video.decoder.wmv"",OMX_MAX_STRINGNAME_SIZE)) + ) { + if ((0 == index) && role) { + strlcpy((char *)role, ""video_decoder.vc1"",OMX_MAX_STRINGNAME_SIZE); + DEBUG_PRINT_LOW(""component_role_enum: role %s"",role); + } else { + DEBUG_PRINT_LOW(""No more roles""); + eRet = OMX_ErrorNoMore; + } + } else if (!strncmp(drv_ctx.kind, ""OMX.qcom.video.decoder.vp8"",OMX_MAX_STRINGNAME_SIZE)) { + if ((0 == index) && role) { + strlcpy((char *)role, ""video_decoder.vp8"",OMX_MAX_STRINGNAME_SIZE); + DEBUG_PRINT_LOW(""component_role_enum: role %s"",role); + } else { + DEBUG_PRINT_LOW(""No more roles""); + eRet = OMX_ErrorNoMore; + } + } else { + DEBUG_PRINT_ERROR(""ERROR:Querying Role on Unknown Component""); + eRet = OMX_ErrorInvalidComponentName; + } + return eRet; +} +",0,"OMX_ERRORTYPE omx_vdec::component_role_enum(OMX_IN OMX_HANDLETYPE hComp, + OMX_OUT OMX_U8* role, + OMX_IN OMX_U32 index) +{ + (void) hComp; + OMX_ERRORTYPE eRet = OMX_ErrorNone; + + if (!strncmp(drv_ctx.kind, ""OMX.qcom.video.decoder.mpeg4"",OMX_MAX_STRINGNAME_SIZE)) { + if ((0 == index) && role) { + strlcpy((char *)role, ""video_decoder.mpeg4"",OMX_MAX_STRINGNAME_SIZE); + DEBUG_PRINT_LOW(""component_role_enum: role %s"",role); + } else { + eRet = OMX_ErrorNoMore; + } + } + if (!strncmp(drv_ctx.kind, ""OMX.qcom.video.decoder.mpeg2"",OMX_MAX_STRINGNAME_SIZE)) { + if ((0 == index) && role) { + strlcpy((char *)role, ""video_decoder.mpeg2"",OMX_MAX_STRINGNAME_SIZE); + DEBUG_PRINT_LOW(""component_role_enum: role %s"",role); + } else { + eRet = OMX_ErrorNoMore; + } + } else if (!strncmp(drv_ctx.kind, ""OMX.qcom.video.decoder.h263"",OMX_MAX_STRINGNAME_SIZE)) { + if ((0 == index) && role) { + strlcpy((char *)role, ""video_decoder.h263"",OMX_MAX_STRINGNAME_SIZE); + DEBUG_PRINT_LOW(""component_role_enum: role %s"",role); + } else { + DEBUG_PRINT_LOW(""No more roles""); + eRet = OMX_ErrorNoMore; + } + } + + else if ((!strncmp(drv_ctx.kind, ""OMX.qcom.video.decoder.divx"",OMX_MAX_STRINGNAME_SIZE)) || + (!strncmp(drv_ctx.kind, ""OMX.qcom.video.decoder.divx311"",OMX_MAX_STRINGNAME_SIZE))) { + if ((0 == index) && role) { + strlcpy((char *)role, ""video_decoder.divx"",OMX_MAX_STRINGNAME_SIZE); + DEBUG_PRINT_LOW(""component_role_enum: role %s"",role); + } else { + DEBUG_PRINT_LOW(""No more roles""); + eRet = OMX_ErrorNoMore; + } + } else if (!strncmp(drv_ctx.kind, ""OMX.qcom.video.decoder.avc"",OMX_MAX_STRINGNAME_SIZE)) { + if ((0 == index) && role) { + strlcpy((char *)role, ""video_decoder.avc"",OMX_MAX_STRINGNAME_SIZE); + DEBUG_PRINT_LOW(""component_role_enum: role %s"",role); + } else { + DEBUG_PRINT_LOW(""No more roles""); + eRet = OMX_ErrorNoMore; + } + } else if (!strncmp(drv_ctx.kind, ""OMX.qcom.video.decoder.mvc"", OMX_MAX_STRINGNAME_SIZE)) { + if ((0 == index) && role) { + strlcpy((char *)role, ""video_decoder.mvc"", OMX_MAX_STRINGNAME_SIZE); + DEBUG_PRINT_LOW(""component_role_enum: role %s"",role); + } else { + DEBUG_PRINT_LOW(""No more roles""); + eRet = OMX_ErrorNoMore; + } + } else if (!strncmp(drv_ctx.kind, ""OMX.qcom.video.decoder.hevc"", OMX_MAX_STRINGNAME_SIZE)) { + if ((0 == index) && role) { + strlcpy((char *)role, ""video_decoder.hevc"", OMX_MAX_STRINGNAME_SIZE); + DEBUG_PRINT_LOW(""component_role_enum: role %s"", role); + } else { + DEBUG_PRINT_LOW(""No more roles""); + eRet = OMX_ErrorNoMore; + } + } else if ( (!strncmp(drv_ctx.kind, ""OMX.qcom.video.decoder.vc1"",OMX_MAX_STRINGNAME_SIZE)) || + (!strncmp(drv_ctx.kind, ""OMX.qcom.video.decoder.wmv"",OMX_MAX_STRINGNAME_SIZE)) + ) { + if ((0 == index) && role) { + strlcpy((char *)role, ""video_decoder.vc1"",OMX_MAX_STRINGNAME_SIZE); + DEBUG_PRINT_LOW(""component_role_enum: role %s"",role); + } else { + DEBUG_PRINT_LOW(""No more roles""); + eRet = OMX_ErrorNoMore; + } + } else if (!strncmp(drv_ctx.kind, ""OMX.qcom.video.decoder.vp8"",OMX_MAX_STRINGNAME_SIZE)) { + if ((0 == index) && role) { + strlcpy((char *)role, ""video_decoder.vp8"",OMX_MAX_STRINGNAME_SIZE); + DEBUG_PRINT_LOW(""component_role_enum: role %s"",role); + } else { + DEBUG_PRINT_LOW(""No more roles""); + eRet = OMX_ErrorNoMore; + } + } else { + DEBUG_PRINT_ERROR(""ERROR:Querying Role on Unknown Component""); + eRet = OMX_ErrorInvalidComponentName; + } + return eRet; +} +","@@ -690,6 +690,7 @@ + + m_vendor_config.pData = NULL; + pthread_mutex_init(&m_lock, NULL); + pthread_mutex_init(&c_lock, NULL); ++ pthread_mutex_init(&buf_lock, NULL); + sem_init(&m_cmd_lock,0,0); + sem_init(&m_safe_flush, 0, 0); + streaming[CAPTURE_PORT] = +@@ -817,6 +818,7 @@ + + close(drv_ctx.video_driver_fd); + pthread_mutex_destroy(&m_lock); + pthread_mutex_destroy(&c_lock); ++ pthread_mutex_destroy(&buf_lock); + sem_destroy(&m_cmd_lock); + if (perf_flag) { + DEBUG_PRINT_HIGH(""--> TOTAL PROCESSING TIME""); +@@ -5074,6 +5076,9 @@ + + index = bufferHdr - m_inp_mem_ptr; + DEBUG_PRINT_LOW(""Free Input Buffer index = %d"",index); + ++ auto_lock l(buf_lock); ++ bufferHdr->pInputPortPrivate = NULL; ++ + if (index < drv_ctx.ip_buf.actualcount && drv_ctx.ptr_inputbuffer) { + DEBUG_PRINT_LOW(""Free Input Buffer index = %d"",index); + if (drv_ctx.ptr_inputbuffer[index].pmem_fd > 0) { +@@ -6022,7 +6027,9 @@ + + OMX_ERRORTYPE ret1 = OMX_ErrorNone; + unsigned int nBufferIndex = drv_ctx.ip_buf.actualcount; + +- if (m_state == OMX_StateInvalid) { ++ if (m_state != OMX_StateExecuting && ++ m_state != OMX_StatePause && ++ m_state != OMX_StateIdle) { + DEBUG_PRINT_ERROR(""Empty this buffer in Invalid State""); + return OMX_ErrorInvalidState; + } +@@ -6156,9 +6163,10 @@ + + return OMX_ErrorNone; + } + ++ auto_lock l(buf_lock); + temp_buffer = (struct vdec_bufferpayload *)buffer->pInputPortPrivate; + +- if ((temp_buffer - drv_ctx.ptr_inputbuffer) > (int)drv_ctx.ip_buf.actualcount) { ++ if (!temp_buffer || (temp_buffer - drv_ctx.ptr_inputbuffer) > (int)drv_ctx.ip_buf.actualcount) { + return OMX_ErrorBadParameter; + } + /* If its first frame, H264 codec and reject is true, then parse the nal +@@ -6184,7 +6192,7 @@ + + /*for use buffer we need to memcpy the data*/ + temp_buffer->buffer_len = buffer->nFilledLen; + +- if (input_use_buffer) { ++ if (input_use_buffer && temp_buffer->bufferaddr) { + if (buffer->nFilledLen <= temp_buffer->buffer_len) { + if (arbitrary_bytes) { + memcpy (temp_buffer->bufferaddr, (buffer->pBuffer + buffer->nOffset),buffer->nFilledLen); +@@ -6352,6 +6360,18 @@ + + OMX_ERRORTYPE omx_vdec::fill_this_buffer(OMX_IN OMX_HANDLETYPE hComp, + OMX_IN OMX_BUFFERHEADERTYPE* buffer) + { ++ if (m_state != OMX_StateExecuting && ++ m_state != OMX_StatePause && ++ m_state != OMX_StateIdle) { ++ DEBUG_PRINT_ERROR(""FTB in Invalid State""); ++ return OMX_ErrorInvalidState; ++ } ++ ++ if (!m_out_bEnabled) { ++ DEBUG_PRINT_ERROR(""ERROR:FTB incorrect state operation, output port is disabled.""); ++ return OMX_ErrorIncorrectStateOperation; ++ } ++ + unsigned nPortIndex = 0; + if (dynamic_buf_mode) { + private_handle_t *handle = NULL; +@@ -6389,17 +6409,6 @@ + + buffer->nAllocLen = handle->size; + } + +- +- if (m_state == OMX_StateInvalid) { +- DEBUG_PRINT_ERROR(""FTB in Invalid State""); +- return OMX_ErrorInvalidState; +- } +- +- if (!m_out_bEnabled) { +- DEBUG_PRINT_ERROR(""ERROR:FTB incorrect state operation, output port is disabled.""); +- return OMX_ErrorIncorrectStateOperation; +- } +- + nPortIndex = buffer - client_buffers.get_il_buf_hdr(); + if (buffer == NULL || + (nPortIndex >= drv_ctx.op_buf.actualcount)) { +",1010,1341,2048 +17420,"FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode) +{ + FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc; + FLAC__int32 i32; + FLAC__uint32 u32; + unsigned u; + + decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC; + + subframe->residual = decoder->private_->residual[channel]; + subframe->order = order; + + /* read warm-up samples */ + for(u = 0; u < order; u++) { + if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps)) + return false; /* read_callback_ sets the state for us */ + subframe->warmup[u] = i32; + } + + /* read qlp coeff precision */ + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN)) + return false; /* read_callback_ sets the state for us */ + if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) { + send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC); + decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; + return true; + } + subframe->qlp_coeff_precision = u32+1; + + /* read qlp shift */ + if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN)) + return false; /* read_callback_ sets the state for us */ + subframe->quantization_level = i32; + + /* read quantized lp coefficiencts */ + for(u = 0; u < order; u++) { + if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision)) + return false; /* read_callback_ sets the state for us */ + subframe->qlp_coeff[u] = i32; + } + + /* read entropy coding method info */ + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN)) + return false; /* read_callback_ sets the state for us */ + subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32; + switch(subframe->entropy_coding_method.type) { + case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE: + case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2: + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN)) + return false; /* read_callback_ sets the state for us */ + subframe->entropy_coding_method.data.partitioned_rice.order = u32; + subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel]; + break; + default: + send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM); + decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; + return true; + } + + /* read residual */ + switch(subframe->entropy_coding_method.type) { + case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE: + case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2: + if(!read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, &decoder->private_->partitioned_rice_contents[channel], decoder->private_->residual[channel], /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2)) + return false; + break; + default: + FLAC__ASSERT(0); + } + + /* decode the subframe */ + if(do_full_decode) { + memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order); + /*@@@@@@ technically not pessimistic enough, should be more like + if( (FLAC__uint64)order * ((((FLAC__uint64)1)<qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) ) + */ + if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32) + if(bps <= 16 && subframe->qlp_coeff_precision <= 16) + decoder->private_->local_lpc_restore_signal_16bit(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order); + else + decoder->private_->local_lpc_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order); + else + decoder->private_->local_lpc_restore_signal_64bit(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order); + } + + return true; +} +",0,"FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode) +{ + FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc; + FLAC__int32 i32; + FLAC__uint32 u32; + unsigned u; + + decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC; + + subframe->residual = decoder->private_->residual[channel]; + subframe->order = order; + + /* read warm-up samples */ + for(u = 0; u < order; u++) { + if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps)) + return false; /* read_callback_ sets the state for us */ + subframe->warmup[u] = i32; + } + + /* read qlp coeff precision */ + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN)) + return false; /* read_callback_ sets the state for us */ + if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) { + send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC); + decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; + return true; + } + subframe->qlp_coeff_precision = u32+1; + + /* read qlp shift */ + if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN)) + return false; /* read_callback_ sets the state for us */ + subframe->quantization_level = i32; + + /* read quantized lp coefficiencts */ + for(u = 0; u < order; u++) { + if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision)) + return false; /* read_callback_ sets the state for us */ + subframe->qlp_coeff[u] = i32; + } + + /* read entropy coding method info */ + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN)) + return false; /* read_callback_ sets the state for us */ + subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32; + switch(subframe->entropy_coding_method.type) { + case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE: + case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2: + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN)) + return false; /* read_callback_ sets the state for us */ + subframe->entropy_coding_method.data.partitioned_rice.order = u32; + subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel]; + break; + default: + send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM); + decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC; + return true; + } + + /* read residual */ + switch(subframe->entropy_coding_method.type) { + case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE: + case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2: + if(!read_residual_partitioned_rice_(decoder, order, subframe->entropy_coding_method.data.partitioned_rice.order, &decoder->private_->partitioned_rice_contents[channel], decoder->private_->residual[channel], /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2)) + return false; + break; + default: + FLAC__ASSERT(0); + } + + /* decode the subframe */ + if(do_full_decode) { + memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order); + /*@@@@@@ technically not pessimistic enough, should be more like + if( (FLAC__uint64)order * ((((FLAC__uint64)1)<qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) ) + */ + if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32) + if(bps <= 16 && subframe->qlp_coeff_precision <= 16) + decoder->private_->local_lpc_restore_signal_16bit(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order); + else + decoder->private_->local_lpc_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order); + else + decoder->private_->local_lpc_restore_signal_64bit(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, subframe->qlp_coeff, order, subframe->quantization_level, decoder->private_->output[channel]+order); + } + + return true; +} +","@@ -1739,6 +1739,7 @@ + + if (obj->num_comments > 0) { + if (0 == (obj->comments = safe_malloc_mul_2op_p(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; ++ obj->num_comments = 0; + return false; + } + for (i = 0; i < obj->num_comments; i++) { +",1238,1569,2048 +8510,"static int ocfs2_write_cluster(struct address_space *mapping, + u32 *phys, unsigned int new, + unsigned int clear_unwritten, + unsigned int should_zero, + struct ocfs2_alloc_context *data_ac, + struct ocfs2_alloc_context *meta_ac, + struct ocfs2_write_ctxt *wc, u32 cpos, + loff_t user_pos, unsigned user_len) +{ + int ret, i; + u64 p_blkno; + struct inode *inode = mapping->host; + struct ocfs2_extent_tree et; + int bpc = ocfs2_clusters_to_blocks(inode->i_sb, 1); + + if (new) { + u32 tmp_pos; + + /* + * This is safe to call with the page locks - it won't take + * any additional semaphores or cluster locks. + */ + tmp_pos = cpos; + ret = ocfs2_add_inode_data(OCFS2_SB(inode->i_sb), inode, + &tmp_pos, 1, !clear_unwritten, + wc->w_di_bh, wc->w_handle, + data_ac, meta_ac, NULL); + /* + * This shouldn't happen because we must have already + * calculated the correct meta data allocation required. The + * internal tree allocation code should know how to increase + * transaction credits itself. + * + * If need be, we could handle -EAGAIN for a + * RESTART_TRANS here. + */ + mlog_bug_on_msg(ret == -EAGAIN, + ""Inode %llu: EAGAIN return during allocation.\n"", + (unsigned long long)OCFS2_I(inode)->ip_blkno); + if (ret < 0) { + mlog_errno(ret); + goto out; + } + } else if (clear_unwritten) { + ocfs2_init_dinode_extent_tree(&et, INODE_CACHE(inode), + wc->w_di_bh); + ret = ocfs2_mark_extent_written(inode, &et, + wc->w_handle, cpos, 1, *phys, + meta_ac, &wc->w_dealloc); + if (ret < 0) { + mlog_errno(ret); + goto out; + } + } + + /* + * The only reason this should fail is due to an inability to + * find the extent added. + */ + ret = ocfs2_get_clusters(inode, cpos, phys, NULL, NULL); + if (ret < 0) { + mlog(ML_ERROR, ""Get physical blkno failed for inode %llu, "" + ""at logical cluster %u"", + (unsigned long long)OCFS2_I(inode)->ip_blkno, cpos); + goto out; + } + + BUG_ON(*phys == 0); + + p_blkno = ocfs2_clusters_to_blocks(inode->i_sb, *phys); + if (!should_zero) + p_blkno += (user_pos >> inode->i_sb->s_blocksize_bits) & (u64)(bpc - 1); + + for(i = 0; i < wc->w_num_pages; i++) { + int tmpret; + + /* This is the direct io target page. */ + if (wc->w_pages[i] == NULL) { + p_blkno++; + continue; + } + + tmpret = ocfs2_prepare_page_for_write(inode, &p_blkno, wc, + wc->w_pages[i], cpos, + user_pos, user_len, + should_zero); + if (tmpret) { + mlog_errno(tmpret); + if (ret == 0) + ret = tmpret; + } + } + + /* + * We only have cleanup to do in case of allocating write. + */ + if (ret && new) + ocfs2_write_failure(inode, wc, user_pos, user_len); + +out: + + return ret; +} +",0,"static int ocfs2_write_cluster(struct address_space *mapping, + u32 *phys, unsigned int new, + unsigned int clear_unwritten, + unsigned int should_zero, + struct ocfs2_alloc_context *data_ac, + struct ocfs2_alloc_context *meta_ac, + struct ocfs2_write_ctxt *wc, u32 cpos, + loff_t user_pos, unsigned user_len) +{ + int ret, i; + u64 p_blkno; + struct inode *inode = mapping->host; + struct ocfs2_extent_tree et; + int bpc = ocfs2_clusters_to_blocks(inode->i_sb, 1); + + if (new) { + u32 tmp_pos; + + /* + * This is safe to call with the page locks - it won't take + * any additional semaphores or cluster locks. + */ + tmp_pos = cpos; + ret = ocfs2_add_inode_data(OCFS2_SB(inode->i_sb), inode, + &tmp_pos, 1, !clear_unwritten, + wc->w_di_bh, wc->w_handle, + data_ac, meta_ac, NULL); + /* + * This shouldn't happen because we must have already + * calculated the correct meta data allocation required. The + * internal tree allocation code should know how to increase + * transaction credits itself. + * + * If need be, we could handle -EAGAIN for a + * RESTART_TRANS here. + */ + mlog_bug_on_msg(ret == -EAGAIN, + ""Inode %llu: EAGAIN return during allocation.\n"", + (unsigned long long)OCFS2_I(inode)->ip_blkno); + if (ret < 0) { + mlog_errno(ret); + goto out; + } + } else if (clear_unwritten) { + ocfs2_init_dinode_extent_tree(&et, INODE_CACHE(inode), + wc->w_di_bh); + ret = ocfs2_mark_extent_written(inode, &et, + wc->w_handle, cpos, 1, *phys, + meta_ac, &wc->w_dealloc); + if (ret < 0) { + mlog_errno(ret); + goto out; + } + } + + /* + * The only reason this should fail is due to an inability to + * find the extent added. + */ + ret = ocfs2_get_clusters(inode, cpos, phys, NULL, NULL); + if (ret < 0) { + mlog(ML_ERROR, ""Get physical blkno failed for inode %llu, "" + ""at logical cluster %u"", + (unsigned long long)OCFS2_I(inode)->ip_blkno, cpos); + goto out; + } + + BUG_ON(*phys == 0); + + p_blkno = ocfs2_clusters_to_blocks(inode->i_sb, *phys); + if (!should_zero) + p_blkno += (user_pos >> inode->i_sb->s_blocksize_bits) & (u64)(bpc - 1); + + for(i = 0; i < wc->w_num_pages; i++) { + int tmpret; + + /* This is the direct io target page. */ + if (wc->w_pages[i] == NULL) { + p_blkno++; + continue; + } + + tmpret = ocfs2_prepare_page_for_write(inode, &p_blkno, wc, + wc->w_pages[i], cpos, + user_pos, user_len, + should_zero); + if (tmpret) { + mlog_errno(tmpret); + if (ret == 0) + ret = tmpret; + } + } + + /* + * We only have cleanup to do in case of allocating write. + */ + if (ret && new) + ocfs2_write_failure(inode, wc, user_pos, user_len); + +out: + + return ret; +} +","@@ -134,6 +134,19 @@ static int ocfs2_symlink_get_block(struct inode *inode, sector_t iblock, + return err; + } + ++static int ocfs2_lock_get_block(struct inode *inode, sector_t iblock, ++ struct buffer_head *bh_result, int create) ++{ ++ int ret = 0; ++ struct ocfs2_inode_info *oi = OCFS2_I(inode); ++ ++ down_read(&oi->ip_alloc_sem); ++ ret = ocfs2_get_block(inode, iblock, bh_result, create); ++ up_read(&oi->ip_alloc_sem); ++ ++ return ret; ++} ++ + int ocfs2_get_block(struct inode *inode, sector_t iblock, + struct buffer_head *bh_result, int create) + { +@@ -2128,7 +2141,7 @@ static void ocfs2_dio_free_write_ctx(struct inode *inode, + * called like this: dio->get_blocks(dio->inode, fs_startblk, + * fs_count, map_bh, dio->rw == WRITE); + */ +-static int ocfs2_dio_get_block(struct inode *inode, sector_t iblock, ++static int ocfs2_dio_wr_get_block(struct inode *inode, sector_t iblock, + struct buffer_head *bh_result, int create) + { + struct ocfs2_super *osb = OCFS2_SB(inode->i_sb); +@@ -2154,12 +2167,9 @@ static int ocfs2_dio_get_block(struct inode *inode, sector_t iblock, + * while file size will be changed. + */ + if (pos + total_len <= i_size_read(inode)) { +- down_read(&oi->ip_alloc_sem); +- /* This is the fast path for re-write. */ +- ret = ocfs2_get_block(inode, iblock, bh_result, create); +- +- up_read(&oi->ip_alloc_sem); + ++ /* This is the fast path for re-write. */ ++ ret = ocfs2_lock_get_block(inode, iblock, bh_result, create); + if (buffer_mapped(bh_result) && + !buffer_new(bh_result) && + ret == 0) +@@ -2424,9 +2434,9 @@ static ssize_t ocfs2_direct_IO(struct kiocb *iocb, struct iov_iter *iter) + return 0; + + if (iov_iter_rw(iter) == READ) +- get_block = ocfs2_get_block; ++ get_block = ocfs2_lock_get_block; + else +- get_block = ocfs2_dio_get_block; ++ get_block = ocfs2_dio_wr_get_block; + + return __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev, + iter, get_block,",826,1157,2048 +16107,"void RenderFrameImpl::CommitNavigation( + const network::ResourceResponseHead& head, + const GURL& body_url, + const CommonNavigationParams& common_params, + const RequestNavigationParams& request_params, + network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints, + std::unique_ptr subresource_loader_factories, + mojom::ControllerServiceWorkerInfoPtr controller_service_worker_info, + const base::UnguessableToken& devtools_navigation_token) { + DCHECK(!IsRendererDebugURL(common_params.url)); + if (!browser_side_navigation_pending_ && + !browser_side_navigation_pending_url_.is_empty() && + browser_side_navigation_pending_url_ == request_params.original_url && + request_params.nav_entry_id == 0) { + browser_side_navigation_pending_url_ = GURL(); + return; + } + + controller_service_worker_info_ = std::move(controller_service_worker_info); + + std::unique_ptr gesture( + common_params.has_user_gesture ? new blink::WebScopedUserGesture(frame_) + : nullptr); + + browser_side_navigation_pending_ = false; + browser_side_navigation_pending_url_ = GURL(); + + pending_navigation_info_.reset(nullptr); + + base::TimeTicks renderer_navigation_start = base::TimeTicks::Now(); + + bool is_reload = + FrameMsg_Navigate_Type::IsReload(common_params.navigation_type); + bool is_history_navigation = request_params.page_state.IsValid(); + auto cache_mode = blink::mojom::FetchCacheMode::kDefault; + RenderFrameImpl::PrepareRenderViewForNavigation(common_params.url, + request_params); + + GetContentClient()->SetActiveURL( + common_params.url, frame_->Top()->GetSecurityOrigin().ToString().Utf8()); + + if (is_reload && current_history_item_.IsNull()) { + is_reload = false; + cache_mode = blink::mojom::FetchCacheMode::kValidateCache; + } + + if (request_params.is_view_source) + frame_->EnableViewSourceMode(true); + + pending_navigation_params_.reset( + new NavigationParams(common_params, request_params)); + + pending_navigation_params_->common_params.navigation_start = + SanitizeNavigationTiming(common_params.navigation_start, + renderer_navigation_start); + + blink::WebFrameLoadType load_type = + common_params.should_replace_current_entry + ? blink::WebFrameLoadType::kReplaceCurrentItem + : blink::WebFrameLoadType::kStandard; + blink::WebHistoryLoadType history_load_type = + blink::kWebHistoryDifferentDocumentLoad; + bool should_load_request = false; + WebHistoryItem item_for_history_navigation; + bool is_same_document = + FrameMsg_Navigate_Type::IsSameDocument(common_params.navigation_type); + + DCHECK(is_same_document || + common_params.url.SchemeIs(url::kJavaScriptScheme) || + !base::FeatureList::IsEnabled(network::features::kNetworkService) || + subresource_loader_factories); + + SetupLoaderFactoryBundle(std::move(subresource_loader_factories)); + + bool has_history_navigation_in_frame = false; + + if (is_reload) { + load_type = ReloadFrameLoadTypeFor(common_params.navigation_type); + should_load_request = true; + } else if (is_history_navigation) { + DCHECK_NE(0, request_params.nav_entry_id); + std::unique_ptr entry = + PageStateToHistoryEntry(request_params.page_state); + if (entry) { + item_for_history_navigation = entry->root(); + switch (common_params.navigation_type) { + case FrameMsg_Navigate_Type::RELOAD: + case FrameMsg_Navigate_Type::RELOAD_BYPASSING_CACHE: + case FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL: + case FrameMsg_Navigate_Type::RESTORE: + case FrameMsg_Navigate_Type::RESTORE_WITH_POST: + case FrameMsg_Navigate_Type::HISTORY_DIFFERENT_DOCUMENT: + history_load_type = blink::kWebHistoryDifferentDocumentLoad; + break; + case FrameMsg_Navigate_Type::HISTORY_SAME_DOCUMENT: + history_load_type = blink::kWebHistorySameDocumentLoad; + break; + default: + NOTREACHED(); + history_load_type = blink::kWebHistoryDifferentDocumentLoad; + } + load_type = request_params.is_history_navigation_in_new_child + ? blink::WebFrameLoadType::kInitialHistoryLoad + : blink::WebFrameLoadType::kBackForward; + should_load_request = true; + + history_subframe_unique_names_ = request_params.subframe_unique_names; + + if (history_load_type == blink::kWebHistorySameDocumentLoad) { + if (current_history_item_.IsNull()) { + history_load_type = blink::kWebHistoryDifferentDocumentLoad; + NOTREACHED(); + } else { + if (current_history_item_.DocumentSequenceNumber() != + item_for_history_navigation.DocumentSequenceNumber()) { + history_load_type = blink::kWebHistoryDifferentDocumentLoad; + } + } + } + + bool interrupted_by_client_redirect = + frame_->IsNavigationScheduledWithin(0) || + frame_->GetProvisionalDocumentLoader() || + !current_history_item_.IsNull(); + if (request_params.is_history_navigation_in_new_child && + interrupted_by_client_redirect) { + should_load_request = false; + has_history_navigation_in_frame = false; + } + } + } else { + should_load_request = true; + } + + if (should_load_request) { + base::WeakPtr weak_this = weak_factory_.GetWeakPtr(); + bool is_client_redirect = + !!(common_params.transition & ui::PAGE_TRANSITION_CLIENT_REDIRECT); + + bool should_load_data_url = !common_params.base_url_for_data_url.is_empty(); +#if defined(OS_ANDROID) + should_load_data_url |= !request_params.data_url_as_string.empty(); +#endif + if (is_main_frame_ && should_load_data_url) { + LoadDataURL(common_params, request_params, frame_, load_type, + item_for_history_navigation, history_load_type, + is_client_redirect); + } else { + WebURLRequest request = CreateURLRequestForCommit( + common_params, request_params, std::move(url_loader_client_endpoints), + head, body_url, is_same_document); + + frame_->Load(request, load_type, item_for_history_navigation, + history_load_type, is_client_redirect, + devtools_navigation_token); + + if (!weak_this) + return; + } + } else { + if (frame_ && !frame_->IsLoading() && !has_history_navigation_in_frame) + Send(new FrameHostMsg_DidStopLoading(routing_id_)); + } + + pending_navigation_params_.reset(); + + frame_->GetDocumentLoader()->ResetSourceLocation(); + if (frame_->GetProvisionalDocumentLoader()) + frame_->GetProvisionalDocumentLoader()->ResetSourceLocation(); +} +",0,"void RenderFrameImpl::CommitNavigation( + const network::ResourceResponseHead& head, + const GURL& body_url, + const CommonNavigationParams& common_params, + const RequestNavigationParams& request_params, + network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints, + std::unique_ptr subresource_loader_factories, + mojom::ControllerServiceWorkerInfoPtr controller_service_worker_info, + const base::UnguessableToken& devtools_navigation_token) { + DCHECK(!IsRendererDebugURL(common_params.url)); + if (!browser_side_navigation_pending_ && + !browser_side_navigation_pending_url_.is_empty() && + browser_side_navigation_pending_url_ == request_params.original_url && + request_params.nav_entry_id == 0) { + browser_side_navigation_pending_url_ = GURL(); + return; + } + + controller_service_worker_info_ = std::move(controller_service_worker_info); + + std::unique_ptr gesture( + common_params.has_user_gesture ? new blink::WebScopedUserGesture(frame_) + : nullptr); + + browser_side_navigation_pending_ = false; + browser_side_navigation_pending_url_ = GURL(); + + pending_navigation_info_.reset(nullptr); + + base::TimeTicks renderer_navigation_start = base::TimeTicks::Now(); + + bool is_reload = + FrameMsg_Navigate_Type::IsReload(common_params.navigation_type); + bool is_history_navigation = request_params.page_state.IsValid(); + auto cache_mode = blink::mojom::FetchCacheMode::kDefault; + RenderFrameImpl::PrepareRenderViewForNavigation(common_params.url, + request_params); + + GetContentClient()->SetActiveURL( + common_params.url, frame_->Top()->GetSecurityOrigin().ToString().Utf8()); + + if (is_reload && current_history_item_.IsNull()) { + is_reload = false; + cache_mode = blink::mojom::FetchCacheMode::kValidateCache; + } + + if (request_params.is_view_source) + frame_->EnableViewSourceMode(true); + + pending_navigation_params_.reset( + new NavigationParams(common_params, request_params)); + + pending_navigation_params_->common_params.navigation_start = + SanitizeNavigationTiming(common_params.navigation_start, + renderer_navigation_start); + + blink::WebFrameLoadType load_type = + common_params.should_replace_current_entry + ? blink::WebFrameLoadType::kReplaceCurrentItem + : blink::WebFrameLoadType::kStandard; + blink::WebHistoryLoadType history_load_type = + blink::kWebHistoryDifferentDocumentLoad; + bool should_load_request = false; + WebHistoryItem item_for_history_navigation; + bool is_same_document = + FrameMsg_Navigate_Type::IsSameDocument(common_params.navigation_type); + + DCHECK(is_same_document || + common_params.url.SchemeIs(url::kJavaScriptScheme) || + !base::FeatureList::IsEnabled(network::features::kNetworkService) || + subresource_loader_factories); + + SetupLoaderFactoryBundle(std::move(subresource_loader_factories)); + + bool has_history_navigation_in_frame = false; + + if (is_reload) { + load_type = ReloadFrameLoadTypeFor(common_params.navigation_type); + should_load_request = true; + } else if (is_history_navigation) { + DCHECK_NE(0, request_params.nav_entry_id); + std::unique_ptr entry = + PageStateToHistoryEntry(request_params.page_state); + if (entry) { + item_for_history_navigation = entry->root(); + switch (common_params.navigation_type) { + case FrameMsg_Navigate_Type::RELOAD: + case FrameMsg_Navigate_Type::RELOAD_BYPASSING_CACHE: + case FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL: + case FrameMsg_Navigate_Type::RESTORE: + case FrameMsg_Navigate_Type::RESTORE_WITH_POST: + case FrameMsg_Navigate_Type::HISTORY_DIFFERENT_DOCUMENT: + history_load_type = blink::kWebHistoryDifferentDocumentLoad; + break; + case FrameMsg_Navigate_Type::HISTORY_SAME_DOCUMENT: + history_load_type = blink::kWebHistorySameDocumentLoad; + break; + default: + NOTREACHED(); + history_load_type = blink::kWebHistoryDifferentDocumentLoad; + } + load_type = request_params.is_history_navigation_in_new_child + ? blink::WebFrameLoadType::kInitialHistoryLoad + : blink::WebFrameLoadType::kBackForward; + should_load_request = true; + + history_subframe_unique_names_ = request_params.subframe_unique_names; + + if (history_load_type == blink::kWebHistorySameDocumentLoad) { + if (current_history_item_.IsNull()) { + history_load_type = blink::kWebHistoryDifferentDocumentLoad; + NOTREACHED(); + } else { + if (current_history_item_.DocumentSequenceNumber() != + item_for_history_navigation.DocumentSequenceNumber()) { + history_load_type = blink::kWebHistoryDifferentDocumentLoad; + } + } + } + + bool interrupted_by_client_redirect = + frame_->IsNavigationScheduledWithin(0) || + frame_->GetProvisionalDocumentLoader() || + !current_history_item_.IsNull(); + if (request_params.is_history_navigation_in_new_child && + interrupted_by_client_redirect) { + should_load_request = false; + has_history_navigation_in_frame = false; + } + } + } else { + should_load_request = true; + } + + if (should_load_request) { + base::WeakPtr weak_this = weak_factory_.GetWeakPtr(); + bool is_client_redirect = + !!(common_params.transition & ui::PAGE_TRANSITION_CLIENT_REDIRECT); + + bool should_load_data_url = !common_params.base_url_for_data_url.is_empty(); +#if defined(OS_ANDROID) + should_load_data_url |= !request_params.data_url_as_string.empty(); +#endif + if (is_main_frame_ && should_load_data_url) { + LoadDataURL(common_params, request_params, frame_, load_type, + item_for_history_navigation, history_load_type, + is_client_redirect); + } else { + WebURLRequest request = CreateURLRequestForCommit( + common_params, request_params, std::move(url_loader_client_endpoints), + head, body_url, is_same_document); + + frame_->Load(request, load_type, item_for_history_navigation, + history_load_type, is_client_redirect, + devtools_navigation_token); + + if (!weak_this) + return; + } + } else { + if (frame_ && !frame_->IsLoading() && !has_history_navigation_in_frame) + Send(new FrameHostMsg_DidStopLoading(routing_id_)); + } + + pending_navigation_params_.reset(); + + frame_->GetDocumentLoader()->ResetSourceLocation(); + if (frame_->GetProvisionalDocumentLoader()) + frame_->GetProvisionalDocumentLoader()->ResetSourceLocation(); +} +","@@ -7046,6 +7046,10 @@ int RenderFrameImpl::GetEnabledBindings() const { + return enabled_bindings_; + } + ++void RenderFrameImpl::FrameDidCallFocus() { ++ Send(new FrameHostMsg_FrameDidCallFocus(routing_id_)); ++} ++ + void RenderFrameImpl::SetAccessibilityModeForTest(ui::AXMode new_mode) { + OnSetAccessibilityMode(new_mode); + }",1422,1753,2048 +4467,"int ssl3_check_cert_and_algorithm(SSL *s) +{ + int i, idx; + long alg_k, alg_a; + EVP_PKEY *pkey = NULL; + int pkey_bits; + SESS_CERT *sc; +#ifndef OPENSSL_NO_RSA + RSA *rsa; +#endif +#ifndef OPENSSL_NO_DH + DH *dh; +#endif + + alg_k = s->s3->tmp.new_cipher->algorithm_mkey; + alg_a = s->s3->tmp.new_cipher->algorithm_auth; + + /* we don't have a certificate */ + if ((alg_a & SSL_aNULL) || (alg_k & SSL_kPSK)) + return (1); + + sc = s->session->sess_cert; + if (sc == NULL) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR); + goto err; + } +#ifndef OPENSSL_NO_RSA + rsa = s->session->sess_cert->peer_rsa_tmp; +#endif +#ifndef OPENSSL_NO_DH + dh = s->session->sess_cert->peer_dh_tmp; +#endif + + /* This is the passed certificate */ + + idx = sc->peer_cert_type; +#ifndef OPENSSL_NO_EC + if (idx == SSL_PKEY_ECC) { + if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509, s) == 0) { + /* check failed */ + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_BAD_ECC_CERT); + goto f_err; + } else { + return 1; + } + } else if (alg_a & SSL_aECDSA) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_ECDSA_SIGNING_CERT); + goto f_err; + } else if (alg_k & (SSL_kECDHr | SSL_kECDHe)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_MISSING_ECDH_CERT); + goto f_err; + } +#endif + pkey = X509_get_pubkey(sc->peer_pkeys[idx].x509); + pkey_bits = EVP_PKEY_bits(pkey); + i = X509_certificate_type(sc->peer_pkeys[idx].x509, pkey); + EVP_PKEY_free(pkey); + + /* Check that we have a certificate if we require one */ + if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA | EVP_PKT_SIGN)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_RSA_SIGNING_CERT); + goto f_err; + } +#ifndef OPENSSL_NO_DSA + else if ((alg_a & SSL_aDSS) && !has_bits(i, EVP_PK_DSA | EVP_PKT_SIGN)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_DSA_SIGNING_CERT); + goto f_err; + } +#endif +#ifndef OPENSSL_NO_RSA + if ((alg_k & SSL_kRSA) && + !(has_bits(i, EVP_PK_RSA | EVP_PKT_ENC) || (rsa != NULL))) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_RSA_ENCRYPTING_CERT); + goto f_err; + } +#endif +#ifndef OPENSSL_NO_DH + if ((alg_k & SSL_kDHE) && + !(has_bits(i, EVP_PK_DH | EVP_PKT_EXCH) || (dh != NULL))) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_MISSING_DH_KEY); + goto f_err; + } else if ((alg_k & SSL_kDHr) && !SSL_USE_SIGALGS(s) && + !has_bits(i, EVP_PK_DH | EVP_PKS_RSA)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_DH_RSA_CERT); + goto f_err; + } +# ifndef OPENSSL_NO_DSA + else if ((alg_k & SSL_kDHd) && !SSL_USE_SIGALGS(s) && + !has_bits(i, EVP_PK_DH | EVP_PKS_DSA)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_DH_DSA_CERT); + goto f_err; + } +# endif +#endif + + if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && + pkey_bits > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) { +#ifndef OPENSSL_NO_RSA + if (alg_k & SSL_kRSA) { + if (rsa == NULL + || RSA_size(rsa) * 8 > + SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_EXPORT_TMP_RSA_KEY); + goto f_err; + } + } else +#endif +#ifndef OPENSSL_NO_DH + if (alg_k & (SSL_kDHE | SSL_kDHr | SSL_kDHd)) { + if (dh == NULL + || DH_size(dh) * 8 > + SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_EXPORT_TMP_DH_KEY); + goto f_err; + } + } else +#endif + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE); + goto f_err; + } + } + return (1); + f_err: + ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); + err: + return (0); +} +",0,"int ssl3_check_cert_and_algorithm(SSL *s) +{ + int i, idx; + long alg_k, alg_a; + EVP_PKEY *pkey = NULL; + int pkey_bits; + SESS_CERT *sc; +#ifndef OPENSSL_NO_RSA + RSA *rsa; +#endif +#ifndef OPENSSL_NO_DH + DH *dh; +#endif + + alg_k = s->s3->tmp.new_cipher->algorithm_mkey; + alg_a = s->s3->tmp.new_cipher->algorithm_auth; + + /* we don't have a certificate */ + if ((alg_a & SSL_aNULL) || (alg_k & SSL_kPSK)) + return (1); + + sc = s->session->sess_cert; + if (sc == NULL) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, ERR_R_INTERNAL_ERROR); + goto err; + } +#ifndef OPENSSL_NO_RSA + rsa = s->session->sess_cert->peer_rsa_tmp; +#endif +#ifndef OPENSSL_NO_DH + dh = s->session->sess_cert->peer_dh_tmp; +#endif + + /* This is the passed certificate */ + + idx = sc->peer_cert_type; +#ifndef OPENSSL_NO_EC + if (idx == SSL_PKEY_ECC) { + if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509, s) == 0) { + /* check failed */ + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_BAD_ECC_CERT); + goto f_err; + } else { + return 1; + } + } else if (alg_a & SSL_aECDSA) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_ECDSA_SIGNING_CERT); + goto f_err; + } else if (alg_k & (SSL_kECDHr | SSL_kECDHe)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_MISSING_ECDH_CERT); + goto f_err; + } +#endif + pkey = X509_get_pubkey(sc->peer_pkeys[idx].x509); + pkey_bits = EVP_PKEY_bits(pkey); + i = X509_certificate_type(sc->peer_pkeys[idx].x509, pkey); + EVP_PKEY_free(pkey); + + /* Check that we have a certificate if we require one */ + if ((alg_a & SSL_aRSA) && !has_bits(i, EVP_PK_RSA | EVP_PKT_SIGN)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_RSA_SIGNING_CERT); + goto f_err; + } +#ifndef OPENSSL_NO_DSA + else if ((alg_a & SSL_aDSS) && !has_bits(i, EVP_PK_DSA | EVP_PKT_SIGN)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_DSA_SIGNING_CERT); + goto f_err; + } +#endif +#ifndef OPENSSL_NO_RSA + if ((alg_k & SSL_kRSA) && + !(has_bits(i, EVP_PK_RSA | EVP_PKT_ENC) || (rsa != NULL))) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_RSA_ENCRYPTING_CERT); + goto f_err; + } +#endif +#ifndef OPENSSL_NO_DH + if ((alg_k & SSL_kDHE) && + !(has_bits(i, EVP_PK_DH | EVP_PKT_EXCH) || (dh != NULL))) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, SSL_R_MISSING_DH_KEY); + goto f_err; + } else if ((alg_k & SSL_kDHr) && !SSL_USE_SIGALGS(s) && + !has_bits(i, EVP_PK_DH | EVP_PKS_RSA)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_DH_RSA_CERT); + goto f_err; + } +# ifndef OPENSSL_NO_DSA + else if ((alg_k & SSL_kDHd) && !SSL_USE_SIGALGS(s) && + !has_bits(i, EVP_PK_DH | EVP_PKS_DSA)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_DH_DSA_CERT); + goto f_err; + } +# endif +#endif + + if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && + pkey_bits > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) { +#ifndef OPENSSL_NO_RSA + if (alg_k & SSL_kRSA) { + if (rsa == NULL + || RSA_size(rsa) * 8 > + SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_EXPORT_TMP_RSA_KEY); + goto f_err; + } + } else +#endif +#ifndef OPENSSL_NO_DH + if (alg_k & (SSL_kDHE | SSL_kDHr | SSL_kDHd)) { + if (dh == NULL + || DH_size(dh) * 8 > + SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_MISSING_EXPORT_TMP_DH_KEY); + goto f_err; + } + } else +#endif + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM, + SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE); + goto f_err; + } + } + return (1); + f_err: + ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); + err: + return (0); +} +","@@ -2238,6 +2238,38 @@ int ssl3_get_new_session_ticket(SSL *s) + } + + p = d = (unsigned char *)s->init_msg; ++ ++ if (s->session->session_id_length > 0) { ++ int i = s->session_ctx->session_cache_mode; ++ SSL_SESSION *new_sess; ++ /* ++ * We reused an existing session, so we need to replace it with a new ++ * one ++ */ ++ if (i & SSL_SESS_CACHE_CLIENT) { ++ /* ++ * Remove the old session from the cache ++ */ ++ if (i & SSL_SESS_CACHE_NO_INTERNAL_STORE) { ++ if (s->session_ctx->remove_session_cb != NULL) ++ s->session_ctx->remove_session_cb(s->session_ctx, ++ s->session); ++ } else { ++ /* We carry on if this fails */ ++ SSL_CTX_remove_session(s->session_ctx, s->session); ++ } ++ } ++ ++ if ((new_sess = ssl_session_dup(s->session, 0)) == 0) { ++ al = SSL_AD_INTERNAL_ERROR; ++ SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE); ++ goto f_err; ++ } ++ ++ SSL_SESSION_free(s->session); ++ s->session = new_sess; ++ } ++ + n2l(p, s->session->tlsext_tick_lifetime_hint); + n2s(p, ticklen); + /* ticket_lifetime_hint + ticket_length + ticket */",1221,1552,2048 +13166,"void RenderFrameImpl::willSendRequest( + blink::WebLocalFrame* frame, + unsigned identifier, + blink::WebURLRequest& request, + const blink::WebURLResponse& redirect_response) { + DCHECK(!frame_ || frame_ == frame); + if (request.url().isEmpty()) + return; + + if (request.firstPartyForCookies().isEmpty()) { + if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel) { + request.setFirstPartyForCookies(request.url()); + } else { + WebFrame* top = frame->top(); + if (top->isWebLocalFrame()) { + request.setFirstPartyForCookies( + frame->top()->document().firstPartyForCookies()); + } + } + } + + WebDataSource* provisional_data_source = frame->provisionalDataSource(); + WebDataSource* data_source = + provisional_data_source ? provisional_data_source : frame->dataSource(); + + DocumentState* document_state = DocumentState::FromDataSource(data_source); + DCHECK(document_state); + InternalDocumentStateData* internal_data = + InternalDocumentStateData::FromDocumentState(document_state); + NavigationStateImpl* navigation_state = + static_cast(document_state->navigation_state()); + ui::PageTransition transition_type = navigation_state->GetTransitionType(); + if (provisional_data_source && provisional_data_source->isClientRedirect()) { + transition_type = ui::PageTransitionFromInt( + transition_type | ui::PAGE_TRANSITION_CLIENT_REDIRECT); + } + + GURL request_url(request.url()); + GURL new_url; + if (GetContentClient()->renderer()->WillSendRequest( + frame, + transition_type, + request_url, + request.firstPartyForCookies(), + &new_url)) { + request.setURL(WebURL(new_url)); + } + + if (internal_data->is_cache_policy_override_set()) + request.setCachePolicy(internal_data->cache_policy_override()); + + WebString custom_user_agent; + WebString requested_with; + scoped_ptr stream_override; + if (request.extraData()) { + RequestExtraData* old_extra_data = + static_cast(request.extraData()); + + custom_user_agent = old_extra_data->custom_user_agent(); + if (!custom_user_agent.isNull()) { + if (custom_user_agent.isEmpty()) + request.clearHTTPHeaderField(""User-Agent""); + else + request.setHTTPHeaderField(""User-Agent"", custom_user_agent); + } + + requested_with = old_extra_data->requested_with(); + if (!requested_with.isNull()) { + if (requested_with.isEmpty()) + request.clearHTTPHeaderField(""X-Requested-With""); + else + request.setHTTPHeaderField(""X-Requested-With"", requested_with); + } + stream_override = old_extra_data->TakeStreamOverrideOwnership(); + } + + if ((request.frameType() == blink::WebURLRequest::FrameTypeTopLevel || + request.frameType() == blink::WebURLRequest::FrameTypeNested) && + request.httpHeaderField(WebString::fromUTF8(kAcceptHeader)).isEmpty()) { + request.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader), + WebString::fromUTF8(kDefaultAcceptHeader)); + } + + request.addHTTPOriginIfNeeded(WebString()); + + bool should_replace_current_entry = false; + if (navigation_state->IsContentInitiated()) { + should_replace_current_entry = data_source->replacesCurrentHistoryItem(); + } else { + should_replace_current_entry = + navigation_state->common_params().should_replace_current_entry; + } + + int provider_id = kInvalidServiceWorkerProviderId; + if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel || + request.frameType() == blink::WebURLRequest::FrameTypeNested) { + if (frame->provisionalDataSource()) { + ServiceWorkerNetworkProvider* provider = + ServiceWorkerNetworkProvider::FromDocumentState( + DocumentState::FromDataSource(frame->provisionalDataSource())); + provider_id = provider->provider_id(); + } + } else if (frame->dataSource()) { + ServiceWorkerNetworkProvider* provider = + ServiceWorkerNetworkProvider::FromDocumentState( + DocumentState::FromDataSource(frame->dataSource())); + provider_id = provider->provider_id(); + } + + WebFrame* parent = frame->parent(); + int parent_routing_id = MSG_ROUTING_NONE; + if (!parent) { + parent_routing_id = -1; + } else if (parent->isWebLocalFrame()) { + parent_routing_id = FromWebFrame(parent)->GetRoutingID(); + } else { + parent_routing_id = RenderFrameProxy::FromWebFrame(parent)->routing_id(); + } + + RequestExtraData* extra_data = new RequestExtraData(); + extra_data->set_visibility_state(render_view_->visibilityState()); + extra_data->set_custom_user_agent(custom_user_agent); + extra_data->set_requested_with(requested_with); + extra_data->set_render_frame_id(routing_id_); + extra_data->set_is_main_frame(!parent); + extra_data->set_frame_origin( + GURL(frame->document().securityOrigin().toString())); + extra_data->set_parent_is_main_frame(parent && !parent->parent()); + extra_data->set_parent_render_frame_id(parent_routing_id); + extra_data->set_allow_download( + navigation_state->common_params().allow_download); + extra_data->set_transition_type(transition_type); + extra_data->set_should_replace_current_entry(should_replace_current_entry); + extra_data->set_transferred_request_child_id( + navigation_state->start_params().transferred_request_child_id); + extra_data->set_transferred_request_request_id( + navigation_state->start_params().transferred_request_request_id); + extra_data->set_service_worker_provider_id(provider_id); + extra_data->set_stream_override(stream_override.Pass()); + request.setExtraData(extra_data); + + WebFrame* top_frame = frame->top(); + if (top_frame && top_frame->isWebLocalFrame()) { + DocumentState* top_document_state = + DocumentState::FromDataSource(top_frame->dataSource()); + if (top_document_state) { + if (request.requestContext() == WebURLRequest::RequestContextPrefetch) + top_document_state->set_was_prefetcher(true); + } + } + + request.setRequestorID(render_view_->GetRoutingID()); + request.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture()); + + if (!navigation_state->start_params().extra_headers.empty()) { + for (net::HttpUtil::HeadersIterator i( + navigation_state->start_params().extra_headers.begin(), + navigation_state->start_params().extra_headers.end(), ""\n""); + i.GetNext();) { + if (base::LowerCaseEqualsASCII(i.name(), ""referer"")) { + WebString referrer = WebSecurityPolicy::generateReferrerHeader( + blink::WebReferrerPolicyDefault, + request.url(), + WebString::fromUTF8(i.values())); + request.setHTTPReferrer(referrer, blink::WebReferrerPolicyDefault); + } else { + request.setHTTPHeaderField(WebString::fromUTF8(i.name()), + WebString::fromUTF8(i.values())); + } + } + } + + if (!render_view_->renderer_preferences_.enable_referrers) + request.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault); +} +",0,"void RenderFrameImpl::willSendRequest( + blink::WebLocalFrame* frame, + unsigned identifier, + blink::WebURLRequest& request, + const blink::WebURLResponse& redirect_response) { + DCHECK(!frame_ || frame_ == frame); + if (request.url().isEmpty()) + return; + + if (request.firstPartyForCookies().isEmpty()) { + if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel) { + request.setFirstPartyForCookies(request.url()); + } else { + WebFrame* top = frame->top(); + if (top->isWebLocalFrame()) { + request.setFirstPartyForCookies( + frame->top()->document().firstPartyForCookies()); + } + } + } + + WebDataSource* provisional_data_source = frame->provisionalDataSource(); + WebDataSource* data_source = + provisional_data_source ? provisional_data_source : frame->dataSource(); + + DocumentState* document_state = DocumentState::FromDataSource(data_source); + DCHECK(document_state); + InternalDocumentStateData* internal_data = + InternalDocumentStateData::FromDocumentState(document_state); + NavigationStateImpl* navigation_state = + static_cast(document_state->navigation_state()); + ui::PageTransition transition_type = navigation_state->GetTransitionType(); + if (provisional_data_source && provisional_data_source->isClientRedirect()) { + transition_type = ui::PageTransitionFromInt( + transition_type | ui::PAGE_TRANSITION_CLIENT_REDIRECT); + } + + GURL request_url(request.url()); + GURL new_url; + if (GetContentClient()->renderer()->WillSendRequest( + frame, + transition_type, + request_url, + request.firstPartyForCookies(), + &new_url)) { + request.setURL(WebURL(new_url)); + } + + if (internal_data->is_cache_policy_override_set()) + request.setCachePolicy(internal_data->cache_policy_override()); + + WebString custom_user_agent; + WebString requested_with; + scoped_ptr stream_override; + if (request.extraData()) { + RequestExtraData* old_extra_data = + static_cast(request.extraData()); + + custom_user_agent = old_extra_data->custom_user_agent(); + if (!custom_user_agent.isNull()) { + if (custom_user_agent.isEmpty()) + request.clearHTTPHeaderField(""User-Agent""); + else + request.setHTTPHeaderField(""User-Agent"", custom_user_agent); + } + + requested_with = old_extra_data->requested_with(); + if (!requested_with.isNull()) { + if (requested_with.isEmpty()) + request.clearHTTPHeaderField(""X-Requested-With""); + else + request.setHTTPHeaderField(""X-Requested-With"", requested_with); + } + stream_override = old_extra_data->TakeStreamOverrideOwnership(); + } + + if ((request.frameType() == blink::WebURLRequest::FrameTypeTopLevel || + request.frameType() == blink::WebURLRequest::FrameTypeNested) && + request.httpHeaderField(WebString::fromUTF8(kAcceptHeader)).isEmpty()) { + request.setHTTPHeaderField(WebString::fromUTF8(kAcceptHeader), + WebString::fromUTF8(kDefaultAcceptHeader)); + } + + request.addHTTPOriginIfNeeded(WebString()); + + bool should_replace_current_entry = false; + if (navigation_state->IsContentInitiated()) { + should_replace_current_entry = data_source->replacesCurrentHistoryItem(); + } else { + should_replace_current_entry = + navigation_state->common_params().should_replace_current_entry; + } + + int provider_id = kInvalidServiceWorkerProviderId; + if (request.frameType() == blink::WebURLRequest::FrameTypeTopLevel || + request.frameType() == blink::WebURLRequest::FrameTypeNested) { + if (frame->provisionalDataSource()) { + ServiceWorkerNetworkProvider* provider = + ServiceWorkerNetworkProvider::FromDocumentState( + DocumentState::FromDataSource(frame->provisionalDataSource())); + provider_id = provider->provider_id(); + } + } else if (frame->dataSource()) { + ServiceWorkerNetworkProvider* provider = + ServiceWorkerNetworkProvider::FromDocumentState( + DocumentState::FromDataSource(frame->dataSource())); + provider_id = provider->provider_id(); + } + + WebFrame* parent = frame->parent(); + int parent_routing_id = MSG_ROUTING_NONE; + if (!parent) { + parent_routing_id = -1; + } else if (parent->isWebLocalFrame()) { + parent_routing_id = FromWebFrame(parent)->GetRoutingID(); + } else { + parent_routing_id = RenderFrameProxy::FromWebFrame(parent)->routing_id(); + } + + RequestExtraData* extra_data = new RequestExtraData(); + extra_data->set_visibility_state(render_view_->visibilityState()); + extra_data->set_custom_user_agent(custom_user_agent); + extra_data->set_requested_with(requested_with); + extra_data->set_render_frame_id(routing_id_); + extra_data->set_is_main_frame(!parent); + extra_data->set_frame_origin( + GURL(frame->document().securityOrigin().toString())); + extra_data->set_parent_is_main_frame(parent && !parent->parent()); + extra_data->set_parent_render_frame_id(parent_routing_id); + extra_data->set_allow_download( + navigation_state->common_params().allow_download); + extra_data->set_transition_type(transition_type); + extra_data->set_should_replace_current_entry(should_replace_current_entry); + extra_data->set_transferred_request_child_id( + navigation_state->start_params().transferred_request_child_id); + extra_data->set_transferred_request_request_id( + navigation_state->start_params().transferred_request_request_id); + extra_data->set_service_worker_provider_id(provider_id); + extra_data->set_stream_override(stream_override.Pass()); + request.setExtraData(extra_data); + + WebFrame* top_frame = frame->top(); + if (top_frame && top_frame->isWebLocalFrame()) { + DocumentState* top_document_state = + DocumentState::FromDataSource(top_frame->dataSource()); + if (top_document_state) { + if (request.requestContext() == WebURLRequest::RequestContextPrefetch) + top_document_state->set_was_prefetcher(true); + } + } + + request.setRequestorID(render_view_->GetRoutingID()); + request.setHasUserGesture(WebUserGestureIndicator::isProcessingUserGesture()); + + if (!navigation_state->start_params().extra_headers.empty()) { + for (net::HttpUtil::HeadersIterator i( + navigation_state->start_params().extra_headers.begin(), + navigation_state->start_params().extra_headers.end(), ""\n""); + i.GetNext();) { + if (base::LowerCaseEqualsASCII(i.name(), ""referer"")) { + WebString referrer = WebSecurityPolicy::generateReferrerHeader( + blink::WebReferrerPolicyDefault, + request.url(), + WebString::fromUTF8(i.values())); + request.setHTTPReferrer(referrer, blink::WebReferrerPolicyDefault); + } else { + request.setHTTPHeaderField(WebString::fromUTF8(i.name()), + WebString::fromUTF8(i.values())); + } + } + } + + if (!render_view_->renderer_preferences_.enable_referrers) + request.setHTTPReferrer(WebString(), blink::WebReferrerPolicyDefault); +} +","@@ -115,6 +115,7 @@ + #include ""media/blink/webmediaplayer_impl.h"" + #include ""media/blink/webmediaplayer_params.h"" + #include ""media/renderers/gpu_video_accelerator_factories.h"" ++#include ""mojo/common/url_type_converters.h"" + #include ""net/base/data_url.h"" + #include ""net/base/net_errors.h"" + #include ""net/base/registry_controlled_domains/registry_controlled_domain.h"" +@@ -125,6 +126,7 @@ + #include ""third_party/WebKit/public/platform/WebURLError.h"" + #include ""third_party/WebKit/public/platform/WebURLResponse.h"" + #include ""third_party/WebKit/public/platform/WebVector.h"" ++#include ""third_party/WebKit/public/platform/modules/webusb/WebUSBClient.h"" + #include ""third_party/WebKit/public/web/WebColorSuggestion.h"" + #include ""third_party/WebKit/public/web/WebDocument.h"" + #include ""third_party/WebKit/public/web/WebFrameWidget.h"" +@@ -174,6 +176,8 @@ + #include ""content/renderer/media/android/webmediaplayer_android.h"" + #else + #include ""cc/blink/context_provider_web_context.h"" ++#include ""content/renderer/usb/web_usb_client_impl.h"" ++#include ""device/devices_app/public/cpp/constants.h"" + #endif + + #if defined(ENABLE_PEPPER_CDMS) +@@ -705,6 +709,8 @@ RenderFrameImpl::RenderFrameImpl(const CreateParams& params) + #endif + + manifest_manager_ = new ManifestManager(this); ++ ++ GetServiceRegistry()->ConnectToRemoteService(mojo::GetProxy(&mojo_shell_)); + } + + RenderFrameImpl::~RenderFrameImpl() { +@@ -3812,6 +3818,17 @@ blink::WebBluetooth* RenderFrameImpl::bluetooth() { + return bluetooth_.get(); + } + ++blink::WebUSBClient* RenderFrameImpl::usbClient() { ++#if !defined(OS_ANDROID) ++ if (!usb_client_) { ++ mojo::ServiceProviderPtr device_services = ++ ConnectToApplication(GURL(device::kDevicesMojoAppUrl)); ++ usb_client_.reset(new WebUSBClientImpl(device_services.Pass())); ++ } ++#endif ++ return usb_client_.get(); ++} ++ + #if defined(ENABLE_WEBVR) + blink::WebVRClient* RenderFrameImpl::webVRClient() { + if (!vr_dispatcher_) +@@ -5003,17 +5020,9 @@ media::MediaPermission* RenderFrameImpl::GetMediaPermission() { + #if defined(ENABLE_MOJO_MEDIA) + media::interfaces::ServiceFactory* RenderFrameImpl::GetMediaServiceFactory() { + if (!media_service_factory_) { +- mojo::InterfacePtr shell_ptr; +- GetServiceRegistry()->ConnectToRemoteService(mojo::GetProxy(&shell_ptr)); +- +- mojo::ServiceProviderPtr service_provider; +- mojo::URLRequestPtr request(mojo::URLRequest::New()); +- request->url = mojo::String::From(""mojo:media""); +- shell_ptr->ConnectToApplication(request.Pass(), GetProxy(&service_provider), +- nullptr, nullptr); +- ++ mojo::ServiceProviderPtr service_provider = ++ ConnectToApplication(GURL(""mojo:media"")); + mojo::ConnectToService(service_provider.get(), &media_service_factory_); +- + media_service_factory_.set_connection_error_handler( + base::Bind(&RenderFrameImpl::OnMediaServiceFactoryConnectionError, + base::Unretained(this))); +@@ -5075,4 +5084,15 @@ void RenderFrameImpl::RegisterMojoServices() { + } + } + ++mojo::ServiceProviderPtr RenderFrameImpl::ConnectToApplication( ++ const GURL& url) { ++ DCHECK(mojo_shell_); ++ mojo::ServiceProviderPtr service_provider; ++ mojo::URLRequestPtr request(mojo::URLRequest::New()); ++ request->url = mojo::String::From(url); ++ mojo_shell_->ConnectToApplication(request.Pass(), GetProxy(&service_provider), ++ nullptr, nullptr); ++ return service_provider.Pass(); ++} ++ + } // namespace content",1511,1842,2048 +17282,"int main(int argc, const char **argv) +{ + /* This program uses the default, based, libpng error handling + * mechanism, therefore any local variable that exists before the call to + * setjmp and is changed after the call to setjmp returns successfully must + * be declared with 'volatile' to ensure that their values don't get + * destroyed by longjmp: + */ + volatile int result = 1/*fail*/; + + if (argc == 4) + { + long x = atol(argv[1]); + long y = atol(argv[2]); + FILE *f = fopen(argv[3], ""rb""); + volatile png_bytep row = NULL; + + if (f != NULL) + { + /* libpng requires a callback function for handling errors; this + * callback must not return. The default callback function uses a + * stored style jmp_buf which is held in a png_struct and + * writes error messages to stderr. Creating the png_struct is a + * little tricky; just copy the following code. + */ + png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, + NULL, NULL, NULL); + + if (png_ptr != NULL) + { + png_infop info_ptr = png_create_info_struct(png_ptr); + + if (info_ptr != NULL) + { + /* Declare stack variables to hold pointers to locally allocated + * data. + */ + + /* Initialize the error control buffer: */ + if (setjmp(png_jmpbuf(png_ptr)) == 0) + { + png_uint_32 width, height; + int bit_depth, color_type, interlace_method, + compression_method, filter_method; + png_bytep row_tmp; + + /* Now associate the recently opened (FILE*) with the default + * libpng initialization functions. Sometimes libpng is + * compiled without stdio support (it can be difficult to do + * in some environments); in that case you will have to write + * your own read callback to read data from the (FILE*). + */ + png_init_io(png_ptr, f); + + /* And read the first part of the PNG file - the header and + * all the information up to the first pixel. + */ + png_read_info(png_ptr, info_ptr); + + /* This fills in enough information to tell us the width of + * each row in bytes, allocate the appropriate amount of + * space. In this case png_malloc is used - it will not + * return if memory isn't available. + */ + row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, + info_ptr)); + + /* To avoid the overhead of using a volatile auto copy row_tmp + * to a local here - just use row for the png_free below. + */ + row_tmp = row; + + /* All the information we need is in the header is returned by + * png_get_IHDR, if this fails we can now use 'png_error' to + * signal the error and return control to the setjmp above. + */ + if (png_get_IHDR(png_ptr, info_ptr, &width, &height, + &bit_depth, &color_type, &interlace_method, + &compression_method, &filter_method)) + { + int passes, pass; + + /* png_set_interlace_handling returns the number of + * passes required as well as turning on libpng's + * handling, but since we do it ourselves this is + * necessary: + */ + switch (interlace_method) + { + case PNG_INTERLACE_NONE: + passes = 1; + break; + + case PNG_INTERLACE_ADAM7: + passes = PNG_INTERLACE_ADAM7_PASSES; + break; + + default: + png_error(png_ptr, ""pngpixel: unknown interlace""); + } + + /* Now read the pixels, pass-by-pass, row-by-row: */ + png_start_read_image(png_ptr); + + for (pass=0; pass based, libpng error handling + * mechanism, therefore any local variable that exists before the call to + * setjmp and is changed after the call to setjmp returns successfully must + * be declared with 'volatile' to ensure that their values don't get + * destroyed by longjmp: + */ + volatile int result = 1/*fail*/; + + if (argc == 4) + { + long x = atol(argv[1]); + long y = atol(argv[2]); + FILE *f = fopen(argv[3], ""rb""); + volatile png_bytep row = NULL; + + if (f != NULL) + { + /* libpng requires a callback function for handling errors; this + * callback must not return. The default callback function uses a + * stored style jmp_buf which is held in a png_struct and + * writes error messages to stderr. Creating the png_struct is a + * little tricky; just copy the following code. + */ + png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, + NULL, NULL, NULL); + + if (png_ptr != NULL) + { + png_infop info_ptr = png_create_info_struct(png_ptr); + + if (info_ptr != NULL) + { + /* Declare stack variables to hold pointers to locally allocated + * data. + */ + + /* Initialize the error control buffer: */ + if (setjmp(png_jmpbuf(png_ptr)) == 0) + { + png_uint_32 width, height; + int bit_depth, color_type, interlace_method, + compression_method, filter_method; + png_bytep row_tmp; + + /* Now associate the recently opened (FILE*) with the default + * libpng initialization functions. Sometimes libpng is + * compiled without stdio support (it can be difficult to do + * in some environments); in that case you will have to write + * your own read callback to read data from the (FILE*). + */ + png_init_io(png_ptr, f); + + /* And read the first part of the PNG file - the header and + * all the information up to the first pixel. + */ + png_read_info(png_ptr, info_ptr); + + /* This fills in enough information to tell us the width of + * each row in bytes, allocate the appropriate amount of + * space. In this case png_malloc is used - it will not + * return if memory isn't available. + */ + row = png_malloc(png_ptr, png_get_rowbytes(png_ptr, + info_ptr)); + + /* To avoid the overhead of using a volatile auto copy row_tmp + * to a local here - just use row for the png_free below. + */ + row_tmp = row; + + /* All the information we need is in the header is returned by + * png_get_IHDR, if this fails we can now use 'png_error' to + * signal the error and return control to the setjmp above. + */ + if (png_get_IHDR(png_ptr, info_ptr, &width, &height, + &bit_depth, &color_type, &interlace_method, + &compression_method, &filter_method)) + { + int passes, pass; + + /* png_set_interlace_handling returns the number of + * passes required as well as turning on libpng's + * handling, but since we do it ourselves this is + * necessary: + */ + switch (interlace_method) + { + case PNG_INTERLACE_NONE: + passes = 1; + break; + + case PNG_INTERLACE_ADAM7: + passes = PNG_INTERLACE_ADAM7_PASSES; + break; + + default: + png_error(png_ptr, ""pngpixel: unknown interlace""); + } + + /* Now read the pixels, pass-by-pass, row-by-row: */ + png_start_read_image(png_ptr); + + for (pass=0; passcurpol->type == QI_VAL) + { + QueryOperand *curpol = &in->curpol->qoperand; + char *op = in->op + curpol->distance; + int clen; + + RESIZEBUF(in, curpol->length * (pg_database_encoding_max_length() + 1) + 2 + 6); + *(in->cur) = '\''; + in->cur++; + while (*op) + { + if (t_iseq(op, '\'')) + { + *(in->cur) = '\''; + in->cur++; + } + else if (t_iseq(op, '\\')) + { + *(in->cur) = '\\'; + in->cur++; + } + COPYCHAR(in->cur, op); + + clen = pg_mblen(op); + op += clen; + in->cur += clen; + } + *(in->cur) = '\''; + in->cur++; + if (curpol->weight || curpol->prefix) + { + *(in->cur) = ':'; + in->cur++; + if (curpol->prefix) + { + *(in->cur) = '*'; + in->cur++; + } + if (curpol->weight & (1 << 3)) + { + *(in->cur) = 'A'; + in->cur++; + } + if (curpol->weight & (1 << 2)) + { + *(in->cur) = 'B'; + in->cur++; + } + if (curpol->weight & (1 << 1)) + { + *(in->cur) = 'C'; + in->cur++; + } + if (curpol->weight & 1) + { + *(in->cur) = 'D'; + in->cur++; + } + } + *(in->cur) = '\0'; + in->curpol++; + } + else if (in->curpol->qoperator.oper == OP_NOT) + { + bool isopr = false; + + RESIZEBUF(in, 1); + *(in->cur) = '!'; + in->cur++; + *(in->cur) = '\0'; + in->curpol++; + + if (in->curpol->type == QI_OPR) + { + isopr = true; + RESIZEBUF(in, 2); + sprintf(in->cur, ""( ""); + in->cur = strchr(in->cur, '\0'); + } + + infix(in, isopr); + if (isopr) + { + RESIZEBUF(in, 2); + sprintf(in->cur, "" )""); + in->cur = strchr(in->cur, '\0'); + } + } + else + { + int8 op = in->curpol->qoperator.oper; + INFIX nrm; + + in->curpol++; + if (op == OP_OR && !first) + { + RESIZEBUF(in, 2); + sprintf(in->cur, ""( ""); + in->cur = strchr(in->cur, '\0'); + } + + nrm.curpol = in->curpol; + nrm.op = in->op; + nrm.buflen = 16; + nrm.cur = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen); + + /* get right operand */ + infix(&nrm, false); + + /* get & print left operand */ + in->curpol = nrm.curpol; + infix(in, false); + + /* print operator & right operand */ + RESIZEBUF(in, 3 + (nrm.cur - nrm.buf)); + switch (op) + { + case OP_OR: + sprintf(in->cur, "" | %s"", nrm.buf); + break; + case OP_AND: + sprintf(in->cur, "" & %s"", nrm.buf); + break; + default: + /* OP_NOT is handled in above if-branch */ + elog(ERROR, ""unrecognized operator type: %d"", op); + } + in->cur = strchr(in->cur, '\0'); + pfree(nrm.buf); + + if (op == OP_OR && !first) + { + RESIZEBUF(in, 2); + sprintf(in->cur, "" )""); + in->cur = strchr(in->cur, '\0'); + } + } +} +",0,"infix(INFIX *in, bool first) +{ + /* since this function recurses, it could be driven to stack overflow. */ + check_stack_depth(); + + if (in->curpol->type == QI_VAL) + { + QueryOperand *curpol = &in->curpol->qoperand; + char *op = in->op + curpol->distance; + int clen; + + RESIZEBUF(in, curpol->length * (pg_database_encoding_max_length() + 1) + 2 + 6); + *(in->cur) = '\''; + in->cur++; + while (*op) + { + if (t_iseq(op, '\'')) + { + *(in->cur) = '\''; + in->cur++; + } + else if (t_iseq(op, '\\')) + { + *(in->cur) = '\\'; + in->cur++; + } + COPYCHAR(in->cur, op); + + clen = pg_mblen(op); + op += clen; + in->cur += clen; + } + *(in->cur) = '\''; + in->cur++; + if (curpol->weight || curpol->prefix) + { + *(in->cur) = ':'; + in->cur++; + if (curpol->prefix) + { + *(in->cur) = '*'; + in->cur++; + } + if (curpol->weight & (1 << 3)) + { + *(in->cur) = 'A'; + in->cur++; + } + if (curpol->weight & (1 << 2)) + { + *(in->cur) = 'B'; + in->cur++; + } + if (curpol->weight & (1 << 1)) + { + *(in->cur) = 'C'; + in->cur++; + } + if (curpol->weight & 1) + { + *(in->cur) = 'D'; + in->cur++; + } + } + *(in->cur) = '\0'; + in->curpol++; + } + else if (in->curpol->qoperator.oper == OP_NOT) + { + bool isopr = false; + + RESIZEBUF(in, 1); + *(in->cur) = '!'; + in->cur++; + *(in->cur) = '\0'; + in->curpol++; + + if (in->curpol->type == QI_OPR) + { + isopr = true; + RESIZEBUF(in, 2); + sprintf(in->cur, ""( ""); + in->cur = strchr(in->cur, '\0'); + } + + infix(in, isopr); + if (isopr) + { + RESIZEBUF(in, 2); + sprintf(in->cur, "" )""); + in->cur = strchr(in->cur, '\0'); + } + } + else + { + int8 op = in->curpol->qoperator.oper; + INFIX nrm; + + in->curpol++; + if (op == OP_OR && !first) + { + RESIZEBUF(in, 2); + sprintf(in->cur, ""( ""); + in->cur = strchr(in->cur, '\0'); + } + + nrm.curpol = in->curpol; + nrm.op = in->op; + nrm.buflen = 16; + nrm.cur = nrm.buf = (char *) palloc(sizeof(char) * nrm.buflen); + + /* get right operand */ + infix(&nrm, false); + + /* get & print left operand */ + in->curpol = nrm.curpol; + infix(in, false); + + /* print operator & right operand */ + RESIZEBUF(in, 3 + (nrm.cur - nrm.buf)); + switch (op) + { + case OP_OR: + sprintf(in->cur, "" | %s"", nrm.buf); + break; + case OP_AND: + sprintf(in->cur, "" & %s"", nrm.buf); + break; + default: + /* OP_NOT is handled in above if-branch */ + elog(ERROR, ""unrecognized operator type: %d"", op); + } + in->cur = strchr(in->cur, '\0'); + pfree(nrm.buf); + + if (op == OP_OR && !first) + { + RESIZEBUF(in, 2); + sprintf(in->cur, "" )""); + in->cur = strchr(in->cur, '\0'); + } + } +} +","@@ -514,8 +514,13 @@ parse_tsquery(char *buf, + return query; + } + +- /* Pack the QueryItems in the final TSQuery struct to return to caller */ ++ if (TSQUERY_TOO_BIG(list_length(state.polstr), state.sumlen)) ++ ereport(ERROR, ++ (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED), ++ errmsg(""tsquery is too large""))); + commonlen = COMPUTESIZE(list_length(state.polstr), state.sumlen); ++ ++ /* Pack the QueryItems in the final TSQuery struct to return to caller */ + query = (TSQuery) palloc0(commonlen); + SET_VARSIZE(query, commonlen); + query->size = list_length(state.polstr);",1023,1354,2048 +18614,"bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label, + bool is_tld_ascii) { + UErrorCode status = U_ZERO_ERROR; + int32_t result = + uspoof_check(checker_, label.data(), + base::checked_cast(label.size()), NULL, &status); + if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS)) + return false; + + icu::UnicodeString label_string(FALSE, label.data(), + base::checked_cast(label.size())); + + if (deviation_characters_.containsSome(label_string)) + return false; + + result &= USPOOF_RESTRICTION_LEVEL_MASK; + if (result == USPOOF_ASCII) + return true; + if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE && + kana_letters_exceptions_.containsNone(label_string) && + combining_diacritics_exceptions_.containsNone(label_string)) { + return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string); + } + + if (non_ascii_latin_letters_.containsSome(label_string) && + !lgc_letters_n_ascii_.containsAll(label_string)) + return false; + + if (!tls_index.initialized()) + tls_index.Initialize(&OnThreadTermination); + icu::RegexMatcher* dangerous_pattern = + reinterpret_cast(tls_index.Get()); + if (!dangerous_pattern) { + dangerous_pattern = new icu::RegexMatcher( + icu::UnicodeString( + R""([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"" + R""([\u30ce\u30f3\u30bd\u30be])"" + R""([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"" + R""([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"" + R""([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"" + R""(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"" + R""(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"" + R""([a-z]\u30fb|\u30fb[a-z]|)"" + R""(^[\u0585\u0581]+[a-z]|[a-z][\u0585\u0581]+$|)"" + R""([a-z][\u0585\u0581]+[a-z]|)"" + R""(^[og]+[\p{scx=armn}]|[\p{scx=armn}][og]+$|)"" + R""([\p{scx=armn}][og]+[\p{scx=armn}]|)"" + R""([\p{sc=cans}].*[a-z]|[a-z].*[\p{sc=cans}]|)"" + R""([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339])"", + -1, US_INV), + 0, status); + tls_index.Set(dangerous_pattern); + } + dangerous_pattern->reset(label_string); + return !dangerous_pattern->find(); +} +",1,"bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label, + bool is_tld_ascii) { + UErrorCode status = U_ZERO_ERROR; + int32_t result = + uspoof_check(checker_, label.data(), + base::checked_cast(label.size()), NULL, &status); + if (U_FAILURE(status) || (result & USPOOF_ALL_CHECKS)) + return false; + + icu::UnicodeString label_string(FALSE, label.data(), + base::checked_cast(label.size())); + + if (deviation_characters_.containsSome(label_string)) + return false; + + result &= USPOOF_RESTRICTION_LEVEL_MASK; + if (result == USPOOF_ASCII) + return true; + if (result == USPOOF_SINGLE_SCRIPT_RESTRICTIVE && + kana_letters_exceptions_.containsNone(label_string) && + combining_diacritics_exceptions_.containsNone(label_string)) { + return !is_tld_ascii || !IsMadeOfLatinAlikeCyrillic(label_string); + } + + if (non_ascii_latin_letters_.containsSome(label_string) && + !lgc_letters_n_ascii_.containsAll(label_string)) + return false; + + if (!tls_index.initialized()) + tls_index.Initialize(&OnThreadTermination); + icu::RegexMatcher* dangerous_pattern = + reinterpret_cast(tls_index.Get()); + if (!dangerous_pattern) { + // - Disalow mixing of Latin and Tifinagh. + dangerous_pattern = new icu::RegexMatcher( + icu::UnicodeString( + R""([^\p{scx=kana}\p{scx=hira}\p{scx=hani}])"" + R""([\u30ce\u30f3\u30bd\u30be])"" + R""([^\p{scx=kana}\p{scx=hira}\p{scx=hani}]|)"" + R""([^\p{scx=kana}\p{scx=hira}]\u30fc|^\u30fc|)"" + R""([^\p{scx=kana}][\u30fd\u30fe]|^[\u30fd\u30fe]|)"" + R""(^[\p{scx=kana}]+[\u3078-\u307a][\p{scx=kana}]+$|)"" + R""(^[\p{scx=hira}]+[\u30d8-\u30da][\p{scx=hira}]+$|)"" + R""([a-z]\u30fb|\u30fb[a-z]|)"" + R""(^[\u0585\u0581]+[a-z]|[a-z][\u0585\u0581]+$|)"" + R""([a-z][\u0585\u0581]+[a-z]|)"" + R""(^[og]+[\p{scx=armn}]|[\p{scx=armn}][og]+$|)"" + R""([\p{scx=armn}][og]+[\p{scx=armn}]|)"" + R""([\p{sc=cans}].*[a-z]|[a-z].*[\p{sc=cans}]|)"" + R""([\p{sc=tfng}].*[a-z]|[a-z].*[\p{sc=tfng}]|)"" + R""([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339])"", + -1, US_INV), + 0, status); + tls_index.Set(dangerous_pattern); + } + dangerous_pattern->reset(label_string); + return !dangerous_pattern->find(); +} +","@@ -236,6 +236,7 @@ bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label, + // Letter Co) to be next to Latin. + // - Disallow Latin 'o' and 'g' next to Armenian. + // - Disalow mixing of Latin and Canadian Syllabary. ++ // - Disalow mixing of Latin and Tifinagh. + // - Disallow combining diacritical mark (U+0300-U+0339) after a non-LGC + // character. Other combining diacritical marks are not in the allowed + // character set. +@@ -254,6 +255,7 @@ bool IDNSpoofChecker::SafeToDisplayAsUnicode(base::StringPiece16 label, + R""(^[og]+[\p{scx=armn}]|[\p{scx=armn}][og]+$|)"" + R""([\p{scx=armn}][og]+[\p{scx=armn}]|)"" + R""([\p{sc=cans}].*[a-z]|[a-z].*[\p{sc=cans}]|)"" ++ R""([\p{sc=tfng}].*[a-z]|[a-z].*[\p{sc=tfng}]|)"" + R""([^\p{scx=latn}\p{scx=grek}\p{scx=cyrl}][\u0300-\u0339])"", + -1, US_INV), + 0, status);",798,1129,2048 +7887,"static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track) +{ + int tag = track->par->codec_tag; + int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE; + AVStream *st = track->st; + int rate = defined_frame_rate(s, st); + + if (!tag) + tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag + + if (track->par->format == AV_PIX_FMT_YUV420P10) { + if (track->par->width == 960 && track->par->height == 720) { + if (!interlaced) { + if (rate == 24) tag = MKTAG('a','i','5','p'); + else if (rate == 25) tag = MKTAG('a','i','5','q'); + else if (rate == 30) tag = MKTAG('a','i','5','p'); + else if (rate == 50) tag = MKTAG('a','i','5','q'); + else if (rate == 60) tag = MKTAG('a','i','5','p'); + } + } else if (track->par->width == 1440 && track->par->height == 1080) { + if (!interlaced) { + if (rate == 24) tag = MKTAG('a','i','5','3'); + else if (rate == 25) tag = MKTAG('a','i','5','2'); + else if (rate == 30) tag = MKTAG('a','i','5','3'); + } else { + if (rate == 50) tag = MKTAG('a','i','5','5'); + else if (rate == 60) tag = MKTAG('a','i','5','6'); + } + } + } else if (track->par->format == AV_PIX_FMT_YUV422P10) { + if (track->par->width == 1280 && track->par->height == 720) { + if (!interlaced) { + if (rate == 24) tag = MKTAG('a','i','1','p'); + else if (rate == 25) tag = MKTAG('a','i','1','q'); + else if (rate == 30) tag = MKTAG('a','i','1','p'); + else if (rate == 50) tag = MKTAG('a','i','1','q'); + else if (rate == 60) tag = MKTAG('a','i','1','p'); + } + } else if (track->par->width == 1920 && track->par->height == 1080) { + if (!interlaced) { + if (rate == 24) tag = MKTAG('a','i','1','3'); + else if (rate == 25) tag = MKTAG('a','i','1','2'); + else if (rate == 30) tag = MKTAG('a','i','1','3'); + } else { + if (rate == 25) tag = MKTAG('a','i','1','5'); + else if (rate == 50) tag = MKTAG('a','i','1','5'); + else if (rate == 60) tag = MKTAG('a','i','1','6'); + } + } else if ( track->par->width == 4096 && track->par->height == 2160 + || track->par->width == 3840 && track->par->height == 2160 + || track->par->width == 2048 && track->par->height == 1080) { + tag = MKTAG('a','i','v','x'); + } + } + + return tag; +} +",0,"static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track) +{ + int tag = track->par->codec_tag; + int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE; + AVStream *st = track->st; + int rate = defined_frame_rate(s, st); + + if (!tag) + tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag + + if (track->par->format == AV_PIX_FMT_YUV420P10) { + if (track->par->width == 960 && track->par->height == 720) { + if (!interlaced) { + if (rate == 24) tag = MKTAG('a','i','5','p'); + else if (rate == 25) tag = MKTAG('a','i','5','q'); + else if (rate == 30) tag = MKTAG('a','i','5','p'); + else if (rate == 50) tag = MKTAG('a','i','5','q'); + else if (rate == 60) tag = MKTAG('a','i','5','p'); + } + } else if (track->par->width == 1440 && track->par->height == 1080) { + if (!interlaced) { + if (rate == 24) tag = MKTAG('a','i','5','3'); + else if (rate == 25) tag = MKTAG('a','i','5','2'); + else if (rate == 30) tag = MKTAG('a','i','5','3'); + } else { + if (rate == 50) tag = MKTAG('a','i','5','5'); + else if (rate == 60) tag = MKTAG('a','i','5','6'); + } + } + } else if (track->par->format == AV_PIX_FMT_YUV422P10) { + if (track->par->width == 1280 && track->par->height == 720) { + if (!interlaced) { + if (rate == 24) tag = MKTAG('a','i','1','p'); + else if (rate == 25) tag = MKTAG('a','i','1','q'); + else if (rate == 30) tag = MKTAG('a','i','1','p'); + else if (rate == 50) tag = MKTAG('a','i','1','q'); + else if (rate == 60) tag = MKTAG('a','i','1','p'); + } + } else if (track->par->width == 1920 && track->par->height == 1080) { + if (!interlaced) { + if (rate == 24) tag = MKTAG('a','i','1','3'); + else if (rate == 25) tag = MKTAG('a','i','1','2'); + else if (rate == 30) tag = MKTAG('a','i','1','3'); + } else { + if (rate == 25) tag = MKTAG('a','i','1','5'); + else if (rate == 50) tag = MKTAG('a','i','1','5'); + else if (rate == 60) tag = MKTAG('a','i','1','6'); + } + } else if ( track->par->width == 4096 && track->par->height == 2160 + || track->par->width == 3840 && track->par->height == 2160 + || track->par->width == 2048 && track->par->height == 1080) { + tag = MKTAG('a','i','v','x'); + } + } + + return tag; +} +","@@ -1022,7 +1022,7 @@ static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContex + uint32_t tag = track->tag; + + if (track->mode == MODE_MOV) { +- if (track->timescale > UINT16_MAX) { ++ if (track->timescale > UINT16_MAX || !track->par->channels) { + if (mov_get_lpcm_flags(track->par->codec_id)) + tag = AV_RL32(""lpcm""); + version = 2;",896,1227,2048 +2614,"static inline void parity_protection_init(void) +{ + switch (current_cpu_type()) { + case CPU_24K: + case CPU_34K: + case CPU_74K: + case CPU_1004K: + { +#define ERRCTL_PE 0x80000000 +#define ERRCTL_L2P 0x00800000 + unsigned long errctl; + unsigned int l1parity_present, l2parity_present; + + errctl = read_c0_ecc(); + errctl &= ~(ERRCTL_PE|ERRCTL_L2P); + + /* probe L1 parity support */ + write_c0_ecc(errctl | ERRCTL_PE); + back_to_back_c0_hazard(); + l1parity_present = (read_c0_ecc() & ERRCTL_PE); + + /* probe L2 parity support */ + write_c0_ecc(errctl|ERRCTL_L2P); + back_to_back_c0_hazard(); + l2parity_present = (read_c0_ecc() & ERRCTL_L2P); + + if (l1parity_present && l2parity_present) { + if (l1parity) + errctl |= ERRCTL_PE; + if (l1parity ^ l2parity) + errctl |= ERRCTL_L2P; + } else if (l1parity_present) { + if (l1parity) + errctl |= ERRCTL_PE; + } else if (l2parity_present) { + if (l2parity) + errctl |= ERRCTL_L2P; + } else { + /* No parity available */ + } + + printk(KERN_INFO ""Writing ErrCtl register=%08lx\n"", errctl); + + write_c0_ecc(errctl); + back_to_back_c0_hazard(); + errctl = read_c0_ecc(); + printk(KERN_INFO ""Readback ErrCtl register=%08lx\n"", errctl); + + if (l1parity_present) + printk(KERN_INFO ""Cache parity protection %sabled\n"", + (errctl & ERRCTL_PE) ? ""en"" : ""dis""); + + if (l2parity_present) { + if (l1parity_present && l1parity) + errctl ^= ERRCTL_L2P; + printk(KERN_INFO ""L2 cache parity protection %sabled\n"", + (errctl & ERRCTL_L2P) ? ""en"" : ""dis""); + } + } + break; + + case CPU_5KC: + write_c0_ecc(0x80000000); + back_to_back_c0_hazard(); + /* Set the PE bit (bit 31) in the c0_errctl register. */ + printk(KERN_INFO ""Cache parity protection %sabled\n"", + (read_c0_ecc() & 0x80000000) ? ""en"" : ""dis""); + break; + case CPU_20KC: + case CPU_25KF: + /* Clear the DE bit (bit 16) in the c0_status register. */ + printk(KERN_INFO ""Enable cache parity protection for "" + ""MIPS 20KC/25KF CPUs.\n""); + clear_c0_status(ST0_DE); + break; + default: + break; + } +} +",0,"static inline void parity_protection_init(void) +{ + switch (current_cpu_type()) { + case CPU_24K: + case CPU_34K: + case CPU_74K: + case CPU_1004K: + { +#define ERRCTL_PE 0x80000000 +#define ERRCTL_L2P 0x00800000 + unsigned long errctl; + unsigned int l1parity_present, l2parity_present; + + errctl = read_c0_ecc(); + errctl &= ~(ERRCTL_PE|ERRCTL_L2P); + + /* probe L1 parity support */ + write_c0_ecc(errctl | ERRCTL_PE); + back_to_back_c0_hazard(); + l1parity_present = (read_c0_ecc() & ERRCTL_PE); + + /* probe L2 parity support */ + write_c0_ecc(errctl|ERRCTL_L2P); + back_to_back_c0_hazard(); + l2parity_present = (read_c0_ecc() & ERRCTL_L2P); + + if (l1parity_present && l2parity_present) { + if (l1parity) + errctl |= ERRCTL_PE; + if (l1parity ^ l2parity) + errctl |= ERRCTL_L2P; + } else if (l1parity_present) { + if (l1parity) + errctl |= ERRCTL_PE; + } else if (l2parity_present) { + if (l2parity) + errctl |= ERRCTL_L2P; + } else { + /* No parity available */ + } + + printk(KERN_INFO ""Writing ErrCtl register=%08lx\n"", errctl); + + write_c0_ecc(errctl); + back_to_back_c0_hazard(); + errctl = read_c0_ecc(); + printk(KERN_INFO ""Readback ErrCtl register=%08lx\n"", errctl); + + if (l1parity_present) + printk(KERN_INFO ""Cache parity protection %sabled\n"", + (errctl & ERRCTL_PE) ? ""en"" : ""dis""); + + if (l2parity_present) { + if (l1parity_present && l1parity) + errctl ^= ERRCTL_L2P; + printk(KERN_INFO ""L2 cache parity protection %sabled\n"", + (errctl & ERRCTL_L2P) ? ""en"" : ""dis""); + } + } + break; + + case CPU_5KC: + write_c0_ecc(0x80000000); + back_to_back_c0_hazard(); + /* Set the PE bit (bit 31) in the c0_errctl register. */ + printk(KERN_INFO ""Cache parity protection %sabled\n"", + (read_c0_ecc() & 0x80000000) ? ""en"" : ""dis""); + break; + case CPU_20KC: + case CPU_25KF: + /* Clear the DE bit (bit 16) in the c0_status register. */ + printk(KERN_INFO ""Enable cache parity protection for "" + ""MIPS 20KC/25KF CPUs.\n""); + clear_c0_status(ST0_DE); + break; + default: + break; + } +} +","@@ -578,12 +578,12 @@ static int simulate_llsc(struct pt_regs *regs, unsigned int opcode) + { + if ((opcode & OPCODE) == LL) { + perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, +- 1, 0, regs, 0); ++ 1, regs, 0); + return simulate_ll(regs, opcode); + } + if ((opcode & OPCODE) == SC) { + perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, +- 1, 0, regs, 0); ++ 1, regs, 0); + return simulate_sc(regs, opcode); + } + +@@ -602,7 +602,7 @@ static int simulate_rdhwr(struct pt_regs *regs, unsigned int opcode) + int rd = (opcode & RD) >> 11; + int rt = (opcode & RT) >> 16; + perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, +- 1, 0, regs, 0); ++ 1, regs, 0); + switch (rd) { + case 0: /* CPU number */ + regs->regs[rt] = smp_processor_id(); +@@ -640,7 +640,7 @@ static int simulate_sync(struct pt_regs *regs, unsigned int opcode) + { + if ((opcode & OPCODE) == SPEC0 && (opcode & FUNC) == SYNC) { + perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, +- 1, 0, regs, 0); ++ 1, regs, 0); + return 0; + } + ",711,1042,2048 +17905,"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; +} +",1,"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; + } + + if (c->log2_cblk_width > 6 || c->log2_cblk_height > 6) { + avpriv_request_sample(s->avctx, ""cblk size > 64""); + return AVERROR_PATCHWELCOME; + } + + 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; +} +","@@ -384,6 +384,11 @@ static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c) + return AVERROR_INVALIDDATA; + } + ++ if (c->log2_cblk_width > 6 || c->log2_cblk_height > 6) { ++ avpriv_request_sample(s->avctx, ""cblk size > 64""); ++ return AVERROR_PATCHWELCOME; ++ } ++ + 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); +@@ -1025,6 +1030,9 @@ static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty, + int bpass_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_BYPASS; + int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC; + ++ av_assert0(width <= JPEG2000_MAX_CBLKW); ++ av_assert0(height <= JPEG2000_MAX_CBLKH); ++ + for (y = 0; y < height; y++) + memset(t1->data[y], 0, width * sizeof(**t1->data)); + ",697,1028,2048 +8882,"WandExport void CLIOption(MagickCLI *cli_wand,const char *option,...) +{ + const char /* extracted option args from args */ + *arg1, + *arg2; + + CommandOptionFlags + option_type; + + assert(cli_wand != (MagickCLI *) NULL); + assert(cli_wand->signature == MagickWandSignature); + assert(cli_wand->wand.signature == MagickWandSignature); + + do { /* Break Code Block for error handling */ + + /* get information about option */ + if ( cli_wand->command == (const OptionInfo *) NULL ) + cli_wand->command = GetCommandOptionInfo(option); +#if 0 + (void) FormatLocaleFile(stderr, ""CLIOption \""%s\"" matched \""%s\""\n"", + option, cli_wand->command->mnemonic ); +#endif + option_type=(CommandOptionFlags) cli_wand->command->flags; + + if ( option_type == UndefinedOptionFlag ) + CLIWandExceptionReturn(OptionFatalError,""UnrecognizedOption"",option); + + assert( LocaleCompare(cli_wand->command->mnemonic,option) == 0 ); + + /* deprecated options */ + if ( (option_type & DeprecateOptionFlag) != 0 ) + CLIWandExceptionBreak(OptionError,""DeprecatedOptionNoCode"",option); + + /* options that this module does not handle */ + if ((option_type & (SpecialOptionFlag|GenesisOptionFlag)) != 0 ) + CLIWandExceptionBreak(OptionFatalError,""InvalidUseOfOption"",option); + + /* Get argument strings from VarArgs + How can you determine if enough arguments was supplied? + What happens if not enough arguments were supplied? + */ + { size_t + count = (size_t) cli_wand->command->type; + + va_list + operands; + + va_start(operands,option); + + arg1=arg2=NULL; + if ( count >= 1 ) + arg1=(const char *) va_arg(operands, const char *); + if ( count >= 2 ) + arg2=(const char *) va_arg(operands, const char *); + + va_end(operands); +#if 0 + (void) FormatLocaleFile(stderr, + ""CLIOption: \""%s\"" Count: %ld Flags: %04x Args: \""%s\"" \""%s\""\n"", + option,(long) count,option_type,arg1,arg2); +#endif + } + + /* + Call the appropriate option handler + */ + + /* FUTURE: this is temporary - get 'settings' to handle distribution of + settings to images attributes,proprieties,artifacts */ + if ( cli_wand->wand.images != (Image *) NULL ) + (void) SyncImagesSettings(cli_wand->wand.image_info,cli_wand->wand.images, + cli_wand->wand.exception); + + if ( (option_type & SettingOptionFlags) != 0 ) { + CLISettingOptionInfo(cli_wand, option, arg1, arg2); + /* + FUTURE: Sync Specific Settings into Image Properities (not global) + */ + } + + /* Operators that do not need images - read, write, stack, clone */ + if ((option_type & NoImageOperatorFlag) != 0) + CLINoImageOperator(cli_wand, option, arg1, arg2); + + /* FUTURE: The not a setting part below is a temporary hack due to + * some options being both a Setting and a Simple operator. + * Specifically -monitor, -depth, and -colorspace */ + if ( cli_wand->wand.images == (Image *) NULL ) + if ( ((option_type & (SimpleOperatorFlag|ListOperatorFlag)) != 0 ) && + ((option_type & SettingOptionFlags) == 0 )) /* temp hack */ + CLIWandExceptionBreak(OptionError,""NoImagesFound"",option); + + /* Operators which loop of individual images, simply */ + if ( (option_type & SimpleOperatorFlag) != 0 && + cli_wand->wand.images != (Image *) NULL) /* temp hack */ + { + ExceptionInfo *exception=AcquireExceptionInfo(); + (void) CLISimpleOperatorImages(cli_wand, option, arg1, arg2,exception); + exception=DestroyExceptionInfo(exception); + } + + /* Operators that work on the image list as a whole */ + if ( (option_type & ListOperatorFlag) != 0 ) + (void) CLIListOperatorImages(cli_wand, option, arg1, arg2); + +DisableMSCWarning(4127) + } while (0); /* end Break code block */ +RestoreMSCWarning + + cli_wand->command = (const OptionInfo *) NULL; /* prevent re-use later */ +} +",0,"WandExport void CLIOption(MagickCLI *cli_wand,const char *option,...) +{ + const char /* extracted option args from args */ + *arg1, + *arg2; + + CommandOptionFlags + option_type; + + assert(cli_wand != (MagickCLI *) NULL); + assert(cli_wand->signature == MagickWandSignature); + assert(cli_wand->wand.signature == MagickWandSignature); + + do { /* Break Code Block for error handling */ + + /* get information about option */ + if ( cli_wand->command == (const OptionInfo *) NULL ) + cli_wand->command = GetCommandOptionInfo(option); +#if 0 + (void) FormatLocaleFile(stderr, ""CLIOption \""%s\"" matched \""%s\""\n"", + option, cli_wand->command->mnemonic ); +#endif + option_type=(CommandOptionFlags) cli_wand->command->flags; + + if ( option_type == UndefinedOptionFlag ) + CLIWandExceptionReturn(OptionFatalError,""UnrecognizedOption"",option); + + assert( LocaleCompare(cli_wand->command->mnemonic,option) == 0 ); + + /* deprecated options */ + if ( (option_type & DeprecateOptionFlag) != 0 ) + CLIWandExceptionBreak(OptionError,""DeprecatedOptionNoCode"",option); + + /* options that this module does not handle */ + if ((option_type & (SpecialOptionFlag|GenesisOptionFlag)) != 0 ) + CLIWandExceptionBreak(OptionFatalError,""InvalidUseOfOption"",option); + + /* Get argument strings from VarArgs + How can you determine if enough arguments was supplied? + What happens if not enough arguments were supplied? + */ + { size_t + count = (size_t) cli_wand->command->type; + + va_list + operands; + + va_start(operands,option); + + arg1=arg2=NULL; + if ( count >= 1 ) + arg1=(const char *) va_arg(operands, const char *); + if ( count >= 2 ) + arg2=(const char *) va_arg(operands, const char *); + + va_end(operands); +#if 0 + (void) FormatLocaleFile(stderr, + ""CLIOption: \""%s\"" Count: %ld Flags: %04x Args: \""%s\"" \""%s\""\n"", + option,(long) count,option_type,arg1,arg2); +#endif + } + + /* + Call the appropriate option handler + */ + + /* FUTURE: this is temporary - get 'settings' to handle distribution of + settings to images attributes,proprieties,artifacts */ + if ( cli_wand->wand.images != (Image *) NULL ) + (void) SyncImagesSettings(cli_wand->wand.image_info,cli_wand->wand.images, + cli_wand->wand.exception); + + if ( (option_type & SettingOptionFlags) != 0 ) { + CLISettingOptionInfo(cli_wand, option, arg1, arg2); + /* + FUTURE: Sync Specific Settings into Image Properities (not global) + */ + } + + /* Operators that do not need images - read, write, stack, clone */ + if ((option_type & NoImageOperatorFlag) != 0) + CLINoImageOperator(cli_wand, option, arg1, arg2); + + /* FUTURE: The not a setting part below is a temporary hack due to + * some options being both a Setting and a Simple operator. + * Specifically -monitor, -depth, and -colorspace */ + if ( cli_wand->wand.images == (Image *) NULL ) + if ( ((option_type & (SimpleOperatorFlag|ListOperatorFlag)) != 0 ) && + ((option_type & SettingOptionFlags) == 0 )) /* temp hack */ + CLIWandExceptionBreak(OptionError,""NoImagesFound"",option); + + /* Operators which loop of individual images, simply */ + if ( (option_type & SimpleOperatorFlag) != 0 && + cli_wand->wand.images != (Image *) NULL) /* temp hack */ + { + ExceptionInfo *exception=AcquireExceptionInfo(); + (void) CLISimpleOperatorImages(cli_wand, option, arg1, arg2,exception); + exception=DestroyExceptionInfo(exception); + } + + /* Operators that work on the image list as a whole */ + if ( (option_type & ListOperatorFlag) != 0 ) + (void) CLIListOperatorImages(cli_wand, option, arg1, arg2); + +DisableMSCWarning(4127) + } while (0); /* end Break code block */ +RestoreMSCWarning + + cli_wand->command = (const OptionInfo *) NULL; /* prevent re-use later */ +} +","@@ -3868,7 +3868,10 @@ WandPrivate MagickBooleanType CLIListOperatorImages(MagickCLI *cli_wand, + reconstruct_image=RemoveFirstImageFromList(&_images); + /* FUTURE - produce Exception, rather than silent fail */ + if (reconstruct_image == (Image *) NULL) +- break; ++ { ++ image=DestroyImage(image); ++ break; ++ } + metric=UndefinedErrorMetric; + option=GetImageOption(_image_info,""metric""); + if (option != (const char *) NULL)",1010,1341,2048 +8886,"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"", "", map \""%s\"""",map_id); + thresholds=DestroyXMLTree(thresholds); + return(map); + } + levels=GetXMLTreeChild(threshold,""levels""); + if (levels == (XMLTreeInfo *) NULL) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""XmlMissingElement"", "", map \""%s\"""", map_id); + thresholds=DestroyXMLTree(thresholds); + return(map); + } + map=(ThresholdMap *) AcquireCriticalMemory(sizeof(*map)); + 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"", "", 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"", "", 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"", "", 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"", "", 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"", "", 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"", "", 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"", "", 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"", "" 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"", "" %.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"", "" too many values, map \""%s\"""",map_id); + thresholds=DestroyXMLTree(thresholds); + map=DestroyThresholdMap(map); + return(map); + } + thresholds=DestroyXMLTree(thresholds); + return(map); +} +",0,"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"", "", map \""%s\"""",map_id); + thresholds=DestroyXMLTree(thresholds); + return(map); + } + levels=GetXMLTreeChild(threshold,""levels""); + if (levels == (XMLTreeInfo *) NULL) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""XmlMissingElement"", "", map \""%s\"""", map_id); + thresholds=DestroyXMLTree(thresholds); + return(map); + } + map=(ThresholdMap *) AcquireCriticalMemory(sizeof(*map)); + 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"", "", 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"", "", 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"", "", 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"", "", 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"", "", 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"", "", 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"", "", 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"", "" 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"", "" %.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"", "" too many values, map \""%s\"""",map_id); + thresholds=DestroyXMLTree(thresholds); + map=DestroyThresholdMap(map); + return(map); + } + thresholds=DestroyXMLTree(thresholds); + return(map); +} +","@@ -212,6 +212,8 @@ MagickExport Image *AdaptiveThresholdImage(const Image *image, + threshold_image=CloneImage(image,0,0,MagickTrue,exception); + if (threshold_image == (Image *) NULL) + return((Image *) NULL); ++ if (width == 0) ++ return(threshold_image); + status=SetImageStorageClass(threshold_image,DirectClass,exception); + if (status == MagickFalse) + {",1523,1854,2048 +6133,"static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb, + AVStream *st, MOVStreamContext *sc) +{ + if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && + !st->codecpar->sample_rate && sc->time_scale > 1) + st->codecpar->sample_rate = sc->time_scale; + + /* special codec parameters handling */ + switch (st->codecpar->codec_id) { +#if CONFIG_DV_DEMUXER + case AV_CODEC_ID_DVAUDIO: + c->dv_fctx = avformat_alloc_context(); + if (!c->dv_fctx) { + av_log(c->fc, AV_LOG_ERROR, ""dv demux context alloc error\n""); + return AVERROR(ENOMEM); + } + 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->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE; + break; +#endif + /* no ifdef since parameters are always those */ + case AV_CODEC_ID_QCELP: + st->codecpar->channels = 1; + if (st->codecpar->codec_tag != MKTAG('Q','c','l','p')) + st->codecpar->sample_rate = 8000; + sc->samples_per_frame = 160; + if (!sc->bytes_per_frame) + sc->bytes_per_frame = 35; + break; + case AV_CODEC_ID_AMR_NB: + st->codecpar->channels = 1; + /* force sample rate for amr, stsd in 3gp does not store sample rate */ + st->codecpar->sample_rate = 8000; + break; + case AV_CODEC_ID_AMR_WB: + st->codecpar->channels = 1; + st->codecpar->sample_rate = 16000; + break; + case AV_CODEC_ID_MP2: + case AV_CODEC_ID_MP3: + /* force type after stsd for m1a hdlr */ + st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; + break; + case AV_CODEC_ID_GSM: + case AV_CODEC_ID_ADPCM_MS: + case AV_CODEC_ID_ADPCM_IMA_WAV: + case AV_CODEC_ID_ILBC: + case AV_CODEC_ID_MACE3: + case AV_CODEC_ID_MACE6: + case AV_CODEC_ID_QDM2: + st->codecpar->block_align = sc->bytes_per_frame; + break; + case AV_CODEC_ID_ALAC: + if (st->codecpar->extradata_size == 36) { + st->codecpar->channels = AV_RB8 (st->codecpar->extradata + 21); + st->codecpar->sample_rate = AV_RB32(st->codecpar->extradata + 32); + } + break; + case AV_CODEC_ID_AC3: + case AV_CODEC_ID_EAC3: + case AV_CODEC_ID_MPEG1VIDEO: + case AV_CODEC_ID_VC1: + case AV_CODEC_ID_VP9: + st->need_parsing = AVSTREAM_PARSE_FULL; + break; + default: + break; + } + return 0; +} +",0,"static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb, + AVStream *st, MOVStreamContext *sc) +{ + if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && + !st->codecpar->sample_rate && sc->time_scale > 1) + st->codecpar->sample_rate = sc->time_scale; + + /* special codec parameters handling */ + switch (st->codecpar->codec_id) { +#if CONFIG_DV_DEMUXER + case AV_CODEC_ID_DVAUDIO: + c->dv_fctx = avformat_alloc_context(); + if (!c->dv_fctx) { + av_log(c->fc, AV_LOG_ERROR, ""dv demux context alloc error\n""); + return AVERROR(ENOMEM); + } + 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->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE; + break; +#endif + /* no ifdef since parameters are always those */ + case AV_CODEC_ID_QCELP: + st->codecpar->channels = 1; + if (st->codecpar->codec_tag != MKTAG('Q','c','l','p')) + st->codecpar->sample_rate = 8000; + sc->samples_per_frame = 160; + if (!sc->bytes_per_frame) + sc->bytes_per_frame = 35; + break; + case AV_CODEC_ID_AMR_NB: + st->codecpar->channels = 1; + /* force sample rate for amr, stsd in 3gp does not store sample rate */ + st->codecpar->sample_rate = 8000; + break; + case AV_CODEC_ID_AMR_WB: + st->codecpar->channels = 1; + st->codecpar->sample_rate = 16000; + break; + case AV_CODEC_ID_MP2: + case AV_CODEC_ID_MP3: + /* force type after stsd for m1a hdlr */ + st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; + break; + case AV_CODEC_ID_GSM: + case AV_CODEC_ID_ADPCM_MS: + case AV_CODEC_ID_ADPCM_IMA_WAV: + case AV_CODEC_ID_ILBC: + case AV_CODEC_ID_MACE3: + case AV_CODEC_ID_MACE6: + case AV_CODEC_ID_QDM2: + st->codecpar->block_align = sc->bytes_per_frame; + break; + case AV_CODEC_ID_ALAC: + if (st->codecpar->extradata_size == 36) { + st->codecpar->channels = AV_RB8 (st->codecpar->extradata + 21); + st->codecpar->sample_rate = AV_RB32(st->codecpar->extradata + 32); + } + break; + case AV_CODEC_ID_AC3: + case AV_CODEC_ID_EAC3: + case AV_CODEC_ID_MPEG1VIDEO: + case AV_CODEC_ID_VC1: + case AV_CODEC_ID_VP9: + st->need_parsing = AVSTREAM_PARSE_FULL; + break; + default: + break; + } + return 0; +} +","@@ -6094,6 +6094,13 @@ static int read_tfra(MOVContext *mov, AVIOContext *f) + } + for (i = 0; i < index->item_count; i++) { + int64_t time, offset; ++ ++ if (avio_feof(f)) { ++ index->item_count = 0; ++ av_freep(&index->items); ++ return AVERROR_INVALIDDATA; ++ } ++ + if (version == 1) { + time = avio_rb64(f); + offset = avio_rb64(f);",749,1080,2048 +17619,"WORD32 ih264d_insert_lt_node(dpb_manager_t *ps_dpb_mgr, + struct dpb_info_t *ps_mov_node, + UWORD32 u4_lt_idx, + UWORD8 u1_fld_pic_flag) +{ + UWORD8 u1_mark_top_field_long_term = 0; + UWORD8 u1_mark_bot_field_long_term = 0; + + { + if(u1_fld_pic_flag) + { + /* Assign corresponding field (top or bottom) long_term_frame_idx */ + + if((ps_mov_node->s_top_field.u1_reference_info == IS_LONG_TERM) + && (ps_mov_node->s_bot_field.u1_reference_info + == IS_LONG_TERM)) + { + if(ps_mov_node->u1_lt_idx == u4_lt_idx) + u1_mark_bot_field_long_term = 1; + else + { + + UWORD32 i4_error_code; + i4_error_code = ERROR_DBP_MANAGER_T; + + return i4_error_code; + + } + } + else if(ps_mov_node->s_top_field.u1_reference_info == IS_LONG_TERM) + { + u1_mark_top_field_long_term = 1; + } + + if(!(u1_mark_top_field_long_term || u1_mark_bot_field_long_term)) + { + UWORD32 i4_error_code; + i4_error_code = ERROR_DBP_MANAGER_T; + return i4_error_code; + } + } + else + { + ps_mov_node->s_top_field.u1_reference_info = IS_LONG_TERM; + ps_mov_node->s_bot_field.u1_reference_info = IS_LONG_TERM; + ps_mov_node->s_top_field.u1_long_term_frame_idx = u4_lt_idx; + ps_mov_node->s_bot_field.u1_long_term_frame_idx = u4_lt_idx; + u1_mark_bot_field_long_term = 1; + u1_mark_top_field_long_term = 1; + } + + ps_mov_node->u1_lt_idx = u4_lt_idx; //Assign the LT index to the node + ps_mov_node->ps_pic_buf->u1_long_term_frm_idx = u4_lt_idx; + ps_mov_node->u1_used_as_ref = IS_LONG_TERM; + + /* Insert the new long term in the LT list with u4_lt_idx */ + /* in ascending order. */ + if(ps_dpb_mgr->u1_num_lt_ref_bufs > 0) + { + struct dpb_info_t *ps_next_dpb = ps_dpb_mgr->ps_dpb_ht_head; + if(u4_lt_idx < ps_next_dpb->u1_lt_idx) + { + ps_mov_node->ps_prev_long = ps_next_dpb; + ps_dpb_mgr->ps_dpb_ht_head = ps_mov_node; + } + else + { + WORD32 i; + struct dpb_info_t *ps_nxtDPB = ps_next_dpb; + ps_next_dpb = ps_next_dpb->ps_prev_long; + for(i = 1; i < ps_dpb_mgr->u1_num_lt_ref_bufs; i++) + { + if(ps_next_dpb->u1_lt_idx > u4_lt_idx) + break; + ps_nxtDPB = ps_next_dpb; + ps_next_dpb = ps_next_dpb->ps_prev_long; + } + + ps_nxtDPB->ps_prev_long = ps_mov_node; + ps_mov_node->ps_prev_long = ps_next_dpb; + } + } + else + { + ps_dpb_mgr->ps_dpb_ht_head = ps_mov_node; + ps_mov_node->ps_prev_long = NULL; + } + /* Identify the picture buffer as a long term picture buffer */ + ps_mov_node->ps_pic_buf->u1_is_short = 0; + + /* Increment LT buf count only if new LT node inserted */ + /* If Increment during top_field is done, don't increment */ + /* for bottom field, as both them are part of same pic. */ + if(u1_mark_bot_field_long_term) + ps_dpb_mgr->u1_num_lt_ref_bufs++; + + } + return OK; +} +",0,"WORD32 ih264d_insert_lt_node(dpb_manager_t *ps_dpb_mgr, + struct dpb_info_t *ps_mov_node, + UWORD32 u4_lt_idx, + UWORD8 u1_fld_pic_flag) +{ + UWORD8 u1_mark_top_field_long_term = 0; + UWORD8 u1_mark_bot_field_long_term = 0; + + { + if(u1_fld_pic_flag) + { + /* Assign corresponding field (top or bottom) long_term_frame_idx */ + + if((ps_mov_node->s_top_field.u1_reference_info == IS_LONG_TERM) + && (ps_mov_node->s_bot_field.u1_reference_info + == IS_LONG_TERM)) + { + if(ps_mov_node->u1_lt_idx == u4_lt_idx) + u1_mark_bot_field_long_term = 1; + else + { + + UWORD32 i4_error_code; + i4_error_code = ERROR_DBP_MANAGER_T; + + return i4_error_code; + + } + } + else if(ps_mov_node->s_top_field.u1_reference_info == IS_LONG_TERM) + { + u1_mark_top_field_long_term = 1; + } + + if(!(u1_mark_top_field_long_term || u1_mark_bot_field_long_term)) + { + UWORD32 i4_error_code; + i4_error_code = ERROR_DBP_MANAGER_T; + return i4_error_code; + } + } + else + { + ps_mov_node->s_top_field.u1_reference_info = IS_LONG_TERM; + ps_mov_node->s_bot_field.u1_reference_info = IS_LONG_TERM; + ps_mov_node->s_top_field.u1_long_term_frame_idx = u4_lt_idx; + ps_mov_node->s_bot_field.u1_long_term_frame_idx = u4_lt_idx; + u1_mark_bot_field_long_term = 1; + u1_mark_top_field_long_term = 1; + } + + ps_mov_node->u1_lt_idx = u4_lt_idx; //Assign the LT index to the node + ps_mov_node->ps_pic_buf->u1_long_term_frm_idx = u4_lt_idx; + ps_mov_node->u1_used_as_ref = IS_LONG_TERM; + + /* Insert the new long term in the LT list with u4_lt_idx */ + /* in ascending order. */ + if(ps_dpb_mgr->u1_num_lt_ref_bufs > 0) + { + struct dpb_info_t *ps_next_dpb = ps_dpb_mgr->ps_dpb_ht_head; + if(u4_lt_idx < ps_next_dpb->u1_lt_idx) + { + ps_mov_node->ps_prev_long = ps_next_dpb; + ps_dpb_mgr->ps_dpb_ht_head = ps_mov_node; + } + else + { + WORD32 i; + struct dpb_info_t *ps_nxtDPB = ps_next_dpb; + ps_next_dpb = ps_next_dpb->ps_prev_long; + for(i = 1; i < ps_dpb_mgr->u1_num_lt_ref_bufs; i++) + { + if(ps_next_dpb->u1_lt_idx > u4_lt_idx) + break; + ps_nxtDPB = ps_next_dpb; + ps_next_dpb = ps_next_dpb->ps_prev_long; + } + + ps_nxtDPB->ps_prev_long = ps_mov_node; + ps_mov_node->ps_prev_long = ps_next_dpb; + } + } + else + { + ps_dpb_mgr->ps_dpb_ht_head = ps_mov_node; + ps_mov_node->ps_prev_long = NULL; + } + /* Identify the picture buffer as a long term picture buffer */ + ps_mov_node->ps_pic_buf->u1_is_short = 0; + + /* Increment LT buf count only if new LT node inserted */ + /* If Increment during top_field is done, don't increment */ + /* for bottom field, as both them are part of same pic. */ + if(u1_mark_bot_field_long_term) + ps_dpb_mgr->u1_num_lt_ref_bufs++; + + } + return OK; +} +","@@ -843,7 +843,7 @@ + + WORD32 ih264d_read_mmco_commands(struct _DecStruct * ps_dec) + { + dec_bit_stream_t *ps_bitstrm = ps_dec->ps_bitstrm; +- dpb_commands_t *ps_dpb_cmds = ps_dec->ps_dpb_cmds; ++ dpb_commands_t *ps_dpb_cmds = &(ps_dec->s_dpb_cmds_scratch); + dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice; + WORD32 j; + UWORD8 u1_buf_mode; +",834,1165,2048 +8471,"static int f2fs_write_cache_pages(struct address_space *mapping, + struct writeback_control *wbc) +{ + int ret = 0; + int done = 0; + struct pagevec pvec; + int nr_pages; + pgoff_t uninitialized_var(writeback_index); + pgoff_t index; + pgoff_t end; /* Inclusive */ + pgoff_t done_index; + int cycled; + int range_whole = 0; + int tag; + int nwritten = 0; + + pagevec_init(&pvec, 0); + + if (wbc->range_cyclic) { + writeback_index = mapping->writeback_index; /* prev offset */ + index = writeback_index; + if (index == 0) + cycled = 1; + else + cycled = 0; + end = -1; + } else { + index = wbc->range_start >> PAGE_SHIFT; + end = wbc->range_end >> PAGE_SHIFT; + if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX) + range_whole = 1; + cycled = 1; /* ignore range_cyclic tests */ + } + if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages) + tag = PAGECACHE_TAG_TOWRITE; + else + tag = PAGECACHE_TAG_DIRTY; +retry: + if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages) + tag_pages_for_writeback(mapping, index, end); + done_index = index; + while (!done && (index <= end)) { + int i; + + nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag, + min(end - index, (pgoff_t)PAGEVEC_SIZE - 1) + 1); + if (nr_pages == 0) + break; + + for (i = 0; i < nr_pages; i++) { + struct page *page = pvec.pages[i]; + + if (page->index > end) { + done = 1; + break; + } + + done_index = page->index; + + lock_page(page); + + if (unlikely(page->mapping != mapping)) { +continue_unlock: + unlock_page(page); + continue; + } + + if (!PageDirty(page)) { + /* someone wrote it for us */ + goto continue_unlock; + } + + if (PageWriteback(page)) { + if (wbc->sync_mode != WB_SYNC_NONE) + f2fs_wait_on_page_writeback(page, + DATA, true); + else + goto continue_unlock; + } + + BUG_ON(PageWriteback(page)); + if (!clear_page_dirty_for_io(page)) + goto continue_unlock; + + ret = mapping->a_ops->writepage(page, wbc); + if (unlikely(ret)) { + /* + * keep nr_to_write, since vfs uses this to + * get # of written pages. + */ + if (ret == AOP_WRITEPAGE_ACTIVATE) { + unlock_page(page); + ret = 0; + continue; + } + done_index = page->index + 1; + done = 1; + break; + } else { + nwritten++; + } + + if (--wbc->nr_to_write <= 0 && + wbc->sync_mode == WB_SYNC_NONE) { + done = 1; + break; + } + } + pagevec_release(&pvec); + cond_resched(); + } + + if (!cycled && !done) { + cycled = 1; + index = 0; + end = writeback_index - 1; + goto retry; + } + if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0)) + mapping->writeback_index = done_index; + + if (nwritten) + f2fs_submit_merged_bio_cond(F2FS_M_SB(mapping), mapping->host, + NULL, 0, DATA, WRITE); + + return ret; +} +",0,"static int f2fs_write_cache_pages(struct address_space *mapping, + struct writeback_control *wbc) +{ + int ret = 0; + int done = 0; + struct pagevec pvec; + int nr_pages; + pgoff_t uninitialized_var(writeback_index); + pgoff_t index; + pgoff_t end; /* Inclusive */ + pgoff_t done_index; + int cycled; + int range_whole = 0; + int tag; + int nwritten = 0; + + pagevec_init(&pvec, 0); + + if (wbc->range_cyclic) { + writeback_index = mapping->writeback_index; /* prev offset */ + index = writeback_index; + if (index == 0) + cycled = 1; + else + cycled = 0; + end = -1; + } else { + index = wbc->range_start >> PAGE_SHIFT; + end = wbc->range_end >> PAGE_SHIFT; + if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX) + range_whole = 1; + cycled = 1; /* ignore range_cyclic tests */ + } + if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages) + tag = PAGECACHE_TAG_TOWRITE; + else + tag = PAGECACHE_TAG_DIRTY; +retry: + if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages) + tag_pages_for_writeback(mapping, index, end); + done_index = index; + while (!done && (index <= end)) { + int i; + + nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag, + min(end - index, (pgoff_t)PAGEVEC_SIZE - 1) + 1); + if (nr_pages == 0) + break; + + for (i = 0; i < nr_pages; i++) { + struct page *page = pvec.pages[i]; + + if (page->index > end) { + done = 1; + break; + } + + done_index = page->index; + + lock_page(page); + + if (unlikely(page->mapping != mapping)) { +continue_unlock: + unlock_page(page); + continue; + } + + if (!PageDirty(page)) { + /* someone wrote it for us */ + goto continue_unlock; + } + + if (PageWriteback(page)) { + if (wbc->sync_mode != WB_SYNC_NONE) + f2fs_wait_on_page_writeback(page, + DATA, true); + else + goto continue_unlock; + } + + BUG_ON(PageWriteback(page)); + if (!clear_page_dirty_for_io(page)) + goto continue_unlock; + + ret = mapping->a_ops->writepage(page, wbc); + if (unlikely(ret)) { + /* + * keep nr_to_write, since vfs uses this to + * get # of written pages. + */ + if (ret == AOP_WRITEPAGE_ACTIVATE) { + unlock_page(page); + ret = 0; + continue; + } + done_index = page->index + 1; + done = 1; + break; + } else { + nwritten++; + } + + if (--wbc->nr_to_write <= 0 && + wbc->sync_mode == WB_SYNC_NONE) { + done = 1; + break; + } + } + pagevec_release(&pvec); + cond_resched(); + } + + if (!cycled && !done) { + cycled = 1; + index = 0; + end = writeback_index - 1; + goto retry; + } + if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0)) + mapping->writeback_index = done_index; + + if (nwritten) + f2fs_submit_merged_bio_cond(F2FS_M_SB(mapping), mapping->host, + NULL, 0, DATA, WRITE); + + return ret; +} +","@@ -964,7 +964,7 @@ static int __get_data_block(struct inode *inode, sector_t iblock, + if (!err) { + map_bh(bh, inode->i_sb, map.m_pblk); + bh->b_state = (bh->b_state & ~F2FS_MAP_FLAGS) | map.m_flags; +- bh->b_size = map.m_len << inode->i_blkbits; ++ bh->b_size = (u64)map.m_len << inode->i_blkbits; + } + return err; + }",864,1195,2048 +4069,"stf_status ikev2parent_outI1(int whack_sock, + struct connection *c, + struct state *predecessor, + lset_t policy, + unsigned long try, + enum crypto_importance importance +#ifdef HAVE_LABELED_IPSEC + , struct xfrm_user_sec_ctx_ike * uctx +#endif + ) +{ + struct state *st = new_state(); + struct db_sa *sadb; + int groupnum; + int policy_index = POLICY_ISAKMP(policy, + c->spd.this.xauth_server, + c->spd.this.xauth_client); + + /* set up new state */ + get_cookie(TRUE, st->st_icookie, COOKIE_SIZE, &c->spd.that.host_addr); + initialize_new_state(st, c, policy, try, whack_sock, importance); + st->st_ikev2 = TRUE; + change_state(st, STATE_PARENT_I1); + st->st_msgid_lastack = INVALID_MSGID; + st->st_msgid_nextuse = 0; + st->st_try = try; + + if (HAS_IPSEC_POLICY(policy)) { +#ifdef HAVE_LABELED_IPSEC + st->sec_ctx = NULL; + if ( uctx != NULL) + libreswan_log( + ""Labeled ipsec is not supported with ikev2 yet""); + + +#endif + + add_pending(dup_any( + whack_sock), st, c, policy, 1, + predecessor == NULL ? SOS_NOBODY : predecessor->st_serialno +#ifdef HAVE_LABELED_IPSEC + , st->sec_ctx +#endif + ); + } + + if (predecessor == NULL) + libreswan_log(""initiating v2 parent SA""); + else + libreswan_log(""initiating v2 parent SA to replace #%lu"", + predecessor->st_serialno); + + if (predecessor != NULL) { + update_pending(predecessor, st); + whack_log(RC_NEW_STATE + STATE_PARENT_I1, + ""%s: initiate, replacing #%lu"", + enum_name(&state_names, st->st_state), + predecessor->st_serialno); + } else { + whack_log(RC_NEW_STATE + STATE_PARENT_I1, + ""%s: initiate"", + enum_name(&state_names, st->st_state)); + } + + /* + * now, we need to initialize st->st_oakley, specifically, the group + * number needs to be initialized. + */ + groupnum = 0; + + st->st_sadb = &oakley_sadb[policy_index]; + sadb = oakley_alg_makedb(st->st_connection->alg_info_ike, + st->st_sadb, 0); + if (sadb != NULL) + st->st_sadb = sadb; + sadb = st->st_sadb = sa_v2_convert(st->st_sadb); + { + unsigned int pc_cnt; + + /* look at all the proposals */ + if (st->st_sadb->prop_disj != NULL) { + for (pc_cnt = 0; + pc_cnt < st->st_sadb->prop_disj_cnt && groupnum == + 0; + pc_cnt++) { + struct db_v2_prop *vp = + &st->st_sadb->prop_disj[pc_cnt]; + unsigned int pr_cnt; + + /* look at all the proposals */ + if (vp->props != NULL) { + for (pr_cnt = 0; + pr_cnt < vp->prop_cnt && + groupnum == 0; + pr_cnt++) { + unsigned int ts_cnt; + struct db_v2_prop_conj *vpc = + &vp->props[pr_cnt]; + + for (ts_cnt = 0; + ts_cnt < vpc->trans_cnt && + groupnum == 0; ts_cnt++) { + struct db_v2_trans *tr + = + &vpc-> + trans[ + ts_cnt + ]; + if (tr != NULL && + tr->transform_type + == + IKEv2_TRANS_TYPE_DH) + { + groupnum = + tr-> + transid; + } + } + } + } + } + } + } + if (groupnum == 0) + groupnum = OAKLEY_GROUP_MODP2048; + st->st_oakley.group = lookup_group(groupnum); + st->st_oakley.groupnum = groupnum; + + /* now. we need to go calculate the nonce, and the KE */ + { + struct ke_continuation *ke = alloc_thing( + struct ke_continuation, + ""ikev2_outI1 KE""); + stf_status e; + + ke->md = alloc_md(); + ke->md->from_state = STATE_IKEv2_BASE; + ke->md->svm = ikev2_parent_firststate(); + ke->md->st = st; + set_suspended(st, ke->md); + + if (!st->st_sec_in_use) { + pcrc_init(&ke->ke_pcrc); + ke->ke_pcrc.pcrc_func = ikev2_parent_outI1_continue; + e = build_ke(&ke->ke_pcrc, st, st->st_oakley.group, + importance); + if ( (e != STF_SUSPEND && + e != STF_INLINE) || (e == STF_TOOMUCHCRYPTO)) { + loglog(RC_CRYPTOFAILED, + ""system too busy - Enabling dcookies [TODO]""); + delete_state(st); + } + } else { + e = + ikev2_parent_outI1_tail( + (struct pluto_crypto_req_cont *)ke, + NULL); + } + + reset_globals(); + + return e; + } +} +",0,"stf_status ikev2parent_outI1(int whack_sock, + struct connection *c, + struct state *predecessor, + lset_t policy, + unsigned long try, + enum crypto_importance importance +#ifdef HAVE_LABELED_IPSEC + , struct xfrm_user_sec_ctx_ike * uctx +#endif + ) +{ + struct state *st = new_state(); + struct db_sa *sadb; + int groupnum; + int policy_index = POLICY_ISAKMP(policy, + c->spd.this.xauth_server, + c->spd.this.xauth_client); + + /* set up new state */ + get_cookie(TRUE, st->st_icookie, COOKIE_SIZE, &c->spd.that.host_addr); + initialize_new_state(st, c, policy, try, whack_sock, importance); + st->st_ikev2 = TRUE; + change_state(st, STATE_PARENT_I1); + st->st_msgid_lastack = INVALID_MSGID; + st->st_msgid_nextuse = 0; + st->st_try = try; + + if (HAS_IPSEC_POLICY(policy)) { +#ifdef HAVE_LABELED_IPSEC + st->sec_ctx = NULL; + if ( uctx != NULL) + libreswan_log( + ""Labeled ipsec is not supported with ikev2 yet""); + + +#endif + + add_pending(dup_any( + whack_sock), st, c, policy, 1, + predecessor == NULL ? SOS_NOBODY : predecessor->st_serialno +#ifdef HAVE_LABELED_IPSEC + , st->sec_ctx +#endif + ); + } + + if (predecessor == NULL) + libreswan_log(""initiating v2 parent SA""); + else + libreswan_log(""initiating v2 parent SA to replace #%lu"", + predecessor->st_serialno); + + if (predecessor != NULL) { + update_pending(predecessor, st); + whack_log(RC_NEW_STATE + STATE_PARENT_I1, + ""%s: initiate, replacing #%lu"", + enum_name(&state_names, st->st_state), + predecessor->st_serialno); + } else { + whack_log(RC_NEW_STATE + STATE_PARENT_I1, + ""%s: initiate"", + enum_name(&state_names, st->st_state)); + } + + /* + * now, we need to initialize st->st_oakley, specifically, the group + * number needs to be initialized. + */ + groupnum = 0; + + st->st_sadb = &oakley_sadb[policy_index]; + sadb = oakley_alg_makedb(st->st_connection->alg_info_ike, + st->st_sadb, 0); + if (sadb != NULL) + st->st_sadb = sadb; + sadb = st->st_sadb = sa_v2_convert(st->st_sadb); + { + unsigned int pc_cnt; + + /* look at all the proposals */ + if (st->st_sadb->prop_disj != NULL) { + for (pc_cnt = 0; + pc_cnt < st->st_sadb->prop_disj_cnt && groupnum == + 0; + pc_cnt++) { + struct db_v2_prop *vp = + &st->st_sadb->prop_disj[pc_cnt]; + unsigned int pr_cnt; + + /* look at all the proposals */ + if (vp->props != NULL) { + for (pr_cnt = 0; + pr_cnt < vp->prop_cnt && + groupnum == 0; + pr_cnt++) { + unsigned int ts_cnt; + struct db_v2_prop_conj *vpc = + &vp->props[pr_cnt]; + + for (ts_cnt = 0; + ts_cnt < vpc->trans_cnt && + groupnum == 0; ts_cnt++) { + struct db_v2_trans *tr + = + &vpc-> + trans[ + ts_cnt + ]; + if (tr != NULL && + tr->transform_type + == + IKEv2_TRANS_TYPE_DH) + { + groupnum = + tr-> + transid; + } + } + } + } + } + } + } + if (groupnum == 0) + groupnum = OAKLEY_GROUP_MODP2048; + st->st_oakley.group = lookup_group(groupnum); + st->st_oakley.groupnum = groupnum; + + /* now. we need to go calculate the nonce, and the KE */ + { + struct ke_continuation *ke = alloc_thing( + struct ke_continuation, + ""ikev2_outI1 KE""); + stf_status e; + + ke->md = alloc_md(); + ke->md->from_state = STATE_IKEv2_BASE; + ke->md->svm = ikev2_parent_firststate(); + ke->md->st = st; + set_suspended(st, ke->md); + + if (!st->st_sec_in_use) { + pcrc_init(&ke->ke_pcrc); + ke->ke_pcrc.pcrc_func = ikev2_parent_outI1_continue; + e = build_ke(&ke->ke_pcrc, st, st->st_oakley.group, + importance); + if ( (e != STF_SUSPEND && + e != STF_INLINE) || (e == STF_TOOMUCHCRYPTO)) { + loglog(RC_CRYPTOFAILED, + ""system too busy - Enabling dcookies [TODO]""); + delete_state(st); + } + } else { + e = + ikev2_parent_outI1_tail( + (struct pluto_crypto_req_cont *)ke, + NULL); + } + + reset_globals(); + + return e; + } +} +","@@ -306,8 +306,6 @@ static void ikev2_parent_outI1_continue(struct pluto_crypto_req_cont *pcrc, + } + reset_cur_state(); + reset_globals(); +- +- passert(GLOBALS_ARE_RESET()); + } + + /* +@@ -729,18 +727,31 @@ stf_status ikev2parent_inI1outR1(struct msg_digest *md) + */ + { + struct ikev2_ke *ke; ++ char fromname[ADDRTOT_BUF]; ++ addrtot(&md->sender, 0, fromname, ADDRTOT_BUF); ++ ++ if (!md->chain[ISAKMP_NEXT_v2KE]) { ++ /* is this a notify? If so, log it */ ++ if(md->chain[ISAKMP_NEXT_v2N]) { ++ libreswan_log(""Received Notify(%d): %s"", ++ md->chain[ISAKMP_NEXT_v2N]->payload.v2n.isan_type, ++ enum_name(&ikev2_notify_names, ++ md->chain[ISAKMP_NEXT_v2N]->payload.v2n.isan_type)); ++ } ++ libreswan_log( ++ ""rejecting I1 from %s:%u, no KE payload present"", ++ fromname, md->sender_port); ++ return STF_FAIL + v2N_INVALID_KE_PAYLOAD; ++ } + ke = &md->chain[ISAKMP_NEXT_v2KE]->payload.v2ke; + + st->st_oakley.group = lookup_group(ke->isak_group); + if (st->st_oakley.group == NULL) { +- char fromname[ADDRTOT_BUF]; +- +- addrtot(&md->sender, 0, fromname, ADDRTOT_BUF); + libreswan_log( + ""rejecting I1 from %s:%u, invalid DH group=%u"", + fromname, md->sender_port, + ke->isak_group); +- return v2N_INVALID_KE_PAYLOAD; ++ return STF_FAIL + v2N_INVALID_KE_PAYLOAD; + } + } + +@@ -819,8 +830,6 @@ static void ikev2_parent_inI1outR1_continue(struct pluto_crypto_req_cont *pcrc, + release_md(ke->md); + } + reset_globals(); +- +- passert(GLOBALS_ARE_RESET()); + } + + static stf_status ikev2_parent_inI1outR1_tail( +@@ -1145,8 +1154,6 @@ static void ikev2_parent_inR1outI2_continue(struct pluto_crypto_req_cont *pcrc, + release_md(dh->md); + } + reset_globals(); +- +- passert(GLOBALS_ARE_RESET()); + } + + static void ikev2_padup_pre_encrypt(struct msg_digest *md, +@@ -1714,7 +1721,7 @@ stf_status ikev2parent_inI2outR2(struct msg_digest *md) + /* verify that there is in fact an encrypted payload */ + if (!md->chain[ISAKMP_NEXT_v2E]) { + libreswan_log(""R2 state should receive an encrypted payload""); +- reset_globals(); ++ reset_globals(); /* XXX suspicious - why was this deemed neccessary? */ + return STF_FATAL; + } + +@@ -1794,8 +1801,6 @@ static void ikev2_parent_inI2outR2_continue(struct pluto_crypto_req_cont *pcrc, + release_md(dh->md); + } + reset_globals(); +- +- passert(GLOBALS_ARE_RESET()); + } + + static stf_status ikev2_parent_inI2outR2_tail(",1233,1564,2048 +4237,"static int call_sbin_request_key(struct key_construction *cons, + const char *op, + void *aux) +{ + const struct cred *cred = current_cred(); + key_serial_t prkey, sskey; + struct key *key = cons->key, *authkey = cons->authkey, *keyring, + *session; + char *argv[9], *envp[3], uid_str[12], gid_str[12]; + char key_str[12], keyring_str[3][12]; + char desc[20]; + int ret, i; + + kenter(""{%d},{%d},%s"", key->serial, authkey->serial, op); + + ret = install_user_keyrings(); + if (ret < 0) + goto error_alloc; + + /* allocate a new session keyring */ + sprintf(desc, ""_req.%u"", key->serial); + + cred = get_current_cred(); + keyring = keyring_alloc(desc, cred->fsuid, cred->fsgid, cred, + KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ, + KEY_ALLOC_QUOTA_OVERRUN, NULL); + put_cred(cred); + if (IS_ERR(keyring)) { + ret = PTR_ERR(keyring); + goto error_alloc; + } + + /* attach the auth key to the session keyring */ + ret = key_link(keyring, authkey); + if (ret < 0) + goto error_link; + + /* record the UID and GID */ + sprintf(uid_str, ""%d"", from_kuid(&init_user_ns, cred->fsuid)); + sprintf(gid_str, ""%d"", from_kgid(&init_user_ns, cred->fsgid)); + + /* we say which key is under construction */ + sprintf(key_str, ""%d"", key->serial); + + /* we specify the process's default keyrings */ + sprintf(keyring_str[0], ""%d"", + cred->thread_keyring ? cred->thread_keyring->serial : 0); + + prkey = 0; + if (cred->process_keyring) + prkey = cred->process_keyring->serial; + sprintf(keyring_str[1], ""%d"", prkey); + + rcu_read_lock(); + session = rcu_dereference(cred->session_keyring); + if (!session) + session = cred->user->session_keyring; + sskey = session->serial; + rcu_read_unlock(); + + sprintf(keyring_str[2], ""%d"", sskey); + + /* set up a minimal environment */ + i = 0; + envp[i++] = ""HOME=/""; + envp[i++] = ""PATH=/sbin:/bin:/usr/sbin:/usr/bin""; + envp[i] = NULL; + + /* set up the argument list */ + i = 0; + argv[i++] = ""/sbin/request-key""; + argv[i++] = (char *) op; + argv[i++] = key_str; + argv[i++] = uid_str; + argv[i++] = gid_str; + argv[i++] = keyring_str[0]; + argv[i++] = keyring_str[1]; + argv[i++] = keyring_str[2]; + argv[i] = NULL; + + /* do it */ + ret = call_usermodehelper_keys(argv[0], argv, envp, keyring, + UMH_WAIT_PROC); + kdebug(""usermode -> 0x%x"", ret); + if (ret >= 0) { + /* ret is the exit/wait code */ + if (test_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags) || + key_validate(key) < 0) + ret = -ENOKEY; + else + /* ignore any errors from userspace if the key was + * instantiated */ + ret = 0; + } + +error_link: + key_put(keyring); + +error_alloc: + complete_request_key(cons, ret); + kleave("" = %d"", ret); + return ret; +} +",0,"static int call_sbin_request_key(struct key_construction *cons, + const char *op, + void *aux) +{ + const struct cred *cred = current_cred(); + key_serial_t prkey, sskey; + struct key *key = cons->key, *authkey = cons->authkey, *keyring, + *session; + char *argv[9], *envp[3], uid_str[12], gid_str[12]; + char key_str[12], keyring_str[3][12]; + char desc[20]; + int ret, i; + + kenter(""{%d},{%d},%s"", key->serial, authkey->serial, op); + + ret = install_user_keyrings(); + if (ret < 0) + goto error_alloc; + + /* allocate a new session keyring */ + sprintf(desc, ""_req.%u"", key->serial); + + cred = get_current_cred(); + keyring = keyring_alloc(desc, cred->fsuid, cred->fsgid, cred, + KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ, + KEY_ALLOC_QUOTA_OVERRUN, NULL); + put_cred(cred); + if (IS_ERR(keyring)) { + ret = PTR_ERR(keyring); + goto error_alloc; + } + + /* attach the auth key to the session keyring */ + ret = key_link(keyring, authkey); + if (ret < 0) + goto error_link; + + /* record the UID and GID */ + sprintf(uid_str, ""%d"", from_kuid(&init_user_ns, cred->fsuid)); + sprintf(gid_str, ""%d"", from_kgid(&init_user_ns, cred->fsgid)); + + /* we say which key is under construction */ + sprintf(key_str, ""%d"", key->serial); + + /* we specify the process's default keyrings */ + sprintf(keyring_str[0], ""%d"", + cred->thread_keyring ? cred->thread_keyring->serial : 0); + + prkey = 0; + if (cred->process_keyring) + prkey = cred->process_keyring->serial; + sprintf(keyring_str[1], ""%d"", prkey); + + rcu_read_lock(); + session = rcu_dereference(cred->session_keyring); + if (!session) + session = cred->user->session_keyring; + sskey = session->serial; + rcu_read_unlock(); + + sprintf(keyring_str[2], ""%d"", sskey); + + /* set up a minimal environment */ + i = 0; + envp[i++] = ""HOME=/""; + envp[i++] = ""PATH=/sbin:/bin:/usr/sbin:/usr/bin""; + envp[i] = NULL; + + /* set up the argument list */ + i = 0; + argv[i++] = ""/sbin/request-key""; + argv[i++] = (char *) op; + argv[i++] = key_str; + argv[i++] = uid_str; + argv[i++] = gid_str; + argv[i++] = keyring_str[0]; + argv[i++] = keyring_str[1]; + argv[i++] = keyring_str[2]; + argv[i] = NULL; + + /* do it */ + ret = call_usermodehelper_keys(argv[0], argv, envp, keyring, + UMH_WAIT_PROC); + kdebug(""usermode -> 0x%x"", ret); + if (ret >= 0) { + /* ret is the exit/wait code */ + if (test_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags) || + key_validate(key) < 0) + ret = -ENOKEY; + else + /* ignore any errors from userspace if the key was + * instantiated */ + ret = 0; + } + +error_link: + key_put(keyring); + +error_alloc: + complete_request_key(cons, ret); + kleave("" = %d"", ret); + return ret; +} +","@@ -440,6 +440,9 @@ static struct key *construct_key_and_link(struct keyring_search_context *ctx, + + kenter(""""); + ++ if (ctx->index_key.type == &key_type_keyring) ++ return ERR_PTR(-EPERM); ++ + user = key_user_lookup(current_fsuid()); + if (!user) + return ERR_PTR(-ENOMEM);",814,1145,2048 +17872,"void icmp_send(struct sk_buff *skb_in, int type, int code, __be32 info) +{ + struct iphdr *iph; + int room; + struct icmp_bxm icmp_param; + struct rtable *rt = skb_rtable(skb_in); + struct ipcm_cookie ipc; + __be32 saddr; + u8 tos; + struct net *net; + struct sock *sk; + + if (!rt) + goto out; + net = dev_net(rt->dst.dev); + + /* + * Find the original header. It is expected to be valid, of course. + * Check this, icmp_send is called from the most obscure devices + * sometimes. + */ + iph = ip_hdr(skb_in); + + if ((u8 *)iph < skb_in->head || + (skb_in->network_header + sizeof(*iph)) > skb_in->tail) + goto out; + + /* + * No replies to physical multicast/broadcast + */ + if (skb_in->pkt_type != PACKET_HOST) + goto out; + + /* + * Now check at the protocol level + */ + if (rt->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST)) + goto out; + + /* + * Only reply to fragment 0. We byte re-order the constant + * mask for efficiency. + */ + if (iph->frag_off & htons(IP_OFFSET)) + goto out; + + /* + * If we send an ICMP error to an ICMP error a mess would result.. + */ + if (icmp_pointers[type].error) { + /* + * We are an error, check if we are replying to an + * ICMP error + */ + if (iph->protocol == IPPROTO_ICMP) { + u8 _inner_type, *itp; + + itp = skb_header_pointer(skb_in, + skb_network_header(skb_in) + + (iph->ihl << 2) + + offsetof(struct icmphdr, + type) - + skb_in->data, + sizeof(_inner_type), + &_inner_type); + if (itp == NULL) + goto out; + + /* + * Assume any unknown ICMP type is an error. This + * isn't specified by the RFC, but think about it.. + */ + if (*itp > NR_ICMP_TYPES || + icmp_pointers[*itp].error) + goto out; + } + } + + sk = icmp_xmit_lock(net); + if (sk == NULL) + return; + + /* + * Construct source address and options. + */ + + saddr = iph->daddr; + if (!(rt->rt_flags & RTCF_LOCAL)) { + struct net_device *dev = NULL; + + rcu_read_lock(); + if (rt_is_input_route(rt) && + net->ipv4.sysctl_icmp_errors_use_inbound_ifaddr) + dev = dev_get_by_index_rcu(net, rt->rt_iif); + + if (dev) + saddr = inet_select_addr(dev, 0, RT_SCOPE_LINK); + else + saddr = 0; + rcu_read_unlock(); + } + + tos = icmp_pointers[type].error ? ((iph->tos & IPTOS_TOS_MASK) | + IPTOS_PREC_INTERNETCONTROL) : + iph->tos; + + if (ip_options_echo(&icmp_param.replyopts, skb_in)) + goto out_unlock; + + + /* + * Prepare data for ICMP header. + */ + + icmp_param.data.icmph.type = type; + icmp_param.data.icmph.code = code; + icmp_param.data.icmph.un.gateway = info; + icmp_param.data.icmph.checksum = 0; + icmp_param.skb = skb_in; + icmp_param.offset = skb_network_offset(skb_in); + inet_sk(sk)->tos = tos; + ipc.addr = iph->saddr; + ipc.opt = &icmp_param.replyopts; + ipc.tx_flags = 0; + + rt = icmp_route_lookup(net, skb_in, iph, saddr, tos, + type, code, &icmp_param); + if (IS_ERR(rt)) + goto out_unlock; + + if (!icmpv4_xrlim_allow(net, rt, type, code)) + goto ende; + + /* RFC says return as much as we can without exceeding 576 bytes. */ + + room = dst_mtu(&rt->dst); + if (room > 576) + room = 576; + room -= sizeof(struct iphdr) + icmp_param.replyopts.optlen; + room -= sizeof(struct icmphdr); + + icmp_param.data_len = skb_in->len - icmp_param.offset; + if (icmp_param.data_len > room) + icmp_param.data_len = room; + icmp_param.head_len = sizeof(struct icmphdr); + + icmp_push_reply(&icmp_param, &ipc, &rt); +ende: + ip_rt_put(rt); +out_unlock: + icmp_xmit_unlock(sk); +out:; +} +",1,"void icmp_send(struct sk_buff *skb_in, int type, int code, __be32 info) +{ + struct iphdr *iph; + int room; + struct icmp_bxm icmp_param; + struct rtable *rt = skb_rtable(skb_in); + struct ipcm_cookie ipc; + __be32 saddr; + u8 tos; + struct net *net; + struct sock *sk; + + if (!rt) + goto out; + net = dev_net(rt->dst.dev); + + /* + * Find the original header. It is expected to be valid, of course. + * Check this, icmp_send is called from the most obscure devices + * sometimes. + */ + iph = ip_hdr(skb_in); + + if ((u8 *)iph < skb_in->head || + (skb_in->network_header + sizeof(*iph)) > skb_in->tail) + goto out; + + /* + * No replies to physical multicast/broadcast + */ + if (skb_in->pkt_type != PACKET_HOST) + goto out; + + /* + * Now check at the protocol level + */ + if (rt->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST)) + goto out; + + /* + * Only reply to fragment 0. We byte re-order the constant + * mask for efficiency. + */ + if (iph->frag_off & htons(IP_OFFSET)) + goto out; + + /* + * If we send an ICMP error to an ICMP error a mess would result.. + */ + if (icmp_pointers[type].error) { + /* + * We are an error, check if we are replying to an + * ICMP error + */ + if (iph->protocol == IPPROTO_ICMP) { + u8 _inner_type, *itp; + + itp = skb_header_pointer(skb_in, + skb_network_header(skb_in) + + (iph->ihl << 2) + + offsetof(struct icmphdr, + type) - + skb_in->data, + sizeof(_inner_type), + &_inner_type); + if (itp == NULL) + goto out; + + /* + * Assume any unknown ICMP type is an error. This + * isn't specified by the RFC, but think about it.. + */ + if (*itp > NR_ICMP_TYPES || + icmp_pointers[*itp].error) + goto out; + } + } + + sk = icmp_xmit_lock(net); + if (sk == NULL) + return; + + /* + * Construct source address and options. + */ + + saddr = iph->daddr; + if (!(rt->rt_flags & RTCF_LOCAL)) { + struct net_device *dev = NULL; + + rcu_read_lock(); + if (rt_is_input_route(rt) && + net->ipv4.sysctl_icmp_errors_use_inbound_ifaddr) + dev = dev_get_by_index_rcu(net, rt->rt_iif); + + if (dev) + saddr = inet_select_addr(dev, 0, RT_SCOPE_LINK); + else + saddr = 0; + rcu_read_unlock(); + } + + tos = icmp_pointers[type].error ? ((iph->tos & IPTOS_TOS_MASK) | + IPTOS_PREC_INTERNETCONTROL) : + iph->tos; + + if (ip_options_echo(&icmp_param.replyopts.opt.opt, skb_in)) + goto out_unlock; + + + /* + * Prepare data for ICMP header. + */ + + icmp_param.data.icmph.type = type; + icmp_param.data.icmph.code = code; + icmp_param.data.icmph.un.gateway = info; + icmp_param.data.icmph.checksum = 0; + icmp_param.skb = skb_in; + icmp_param.offset = skb_network_offset(skb_in); + inet_sk(sk)->tos = tos; + ipc.addr = iph->saddr; + ipc.opt = &icmp_param.replyopts.opt; + ipc.tx_flags = 0; + + rt = icmp_route_lookup(net, skb_in, iph, saddr, tos, + type, code, &icmp_param); + if (IS_ERR(rt)) + goto out_unlock; + + if (!icmpv4_xrlim_allow(net, rt, type, code)) + goto ende; + + /* RFC says return as much as we can without exceeding 576 bytes. */ + + room = dst_mtu(&rt->dst); + if (room > 576) + room = 576; + room -= sizeof(struct iphdr) + icmp_param.replyopts.opt.opt.optlen; + room -= sizeof(struct icmphdr); + + icmp_param.data_len = skb_in->len - icmp_param.offset; + if (icmp_param.data_len > room) + icmp_param.data_len = room; + icmp_param.head_len = sizeof(struct icmphdr); + + icmp_push_reply(&icmp_param, &ipc, &rt); +ende: + ip_rt_put(rt); +out_unlock: + icmp_xmit_unlock(sk); +out:; +} +","@@ -108,8 +108,7 @@ struct icmp_bxm { + __be32 times[3]; + } data; + int head_len; +- struct ip_options replyopts; +- unsigned char optbuf[40]; ++ struct ip_options_data replyopts; + }; + + /* An array of errno for error messages from dest unreach. */ +@@ -333,7 +332,7 @@ static void icmp_reply(struct icmp_bxm *icmp_param, struct sk_buff *skb) + struct inet_sock *inet; + __be32 daddr; + +- if (ip_options_echo(&icmp_param->replyopts, skb)) ++ if (ip_options_echo(&icmp_param->replyopts.opt.opt, skb)) + return; + + sk = icmp_xmit_lock(net); +@@ -347,10 +346,10 @@ static void icmp_reply(struct icmp_bxm *icmp_param, struct sk_buff *skb) + daddr = ipc.addr = rt->rt_src; + ipc.opt = NULL; + ipc.tx_flags = 0; +- if (icmp_param->replyopts.optlen) { +- ipc.opt = &icmp_param->replyopts; +- if (ipc.opt->srr) +- daddr = icmp_param->replyopts.faddr; ++ if (icmp_param->replyopts.opt.opt.optlen) { ++ ipc.opt = &icmp_param->replyopts.opt; ++ if (ipc.opt->opt.srr) ++ daddr = icmp_param->replyopts.opt.opt.faddr; + } + { + struct flowi4 fl4 = { +@@ -379,8 +378,8 @@ static struct rtable *icmp_route_lookup(struct net *net, struct sk_buff *skb_in, + struct icmp_bxm *param) + { + struct flowi4 fl4 = { +- .daddr = (param->replyopts.srr ? +- param->replyopts.faddr : iph->saddr), ++ .daddr = (param->replyopts.opt.opt.srr ? ++ param->replyopts.opt.opt.faddr : iph->saddr), + .saddr = saddr, + .flowi4_tos = RT_TOS(tos), + .flowi4_proto = IPPROTO_ICMP, +@@ -581,7 +580,7 @@ void icmp_send(struct sk_buff *skb_in, int type, int code, __be32 info) + IPTOS_PREC_INTERNETCONTROL) : + iph->tos; + +- if (ip_options_echo(&icmp_param.replyopts, skb_in)) ++ if (ip_options_echo(&icmp_param.replyopts.opt.opt, skb_in)) + goto out_unlock; + + +@@ -597,7 +596,7 @@ void icmp_send(struct sk_buff *skb_in, int type, int code, __be32 info) + icmp_param.offset = skb_network_offset(skb_in); + inet_sk(sk)->tos = tos; + ipc.addr = iph->saddr; +- ipc.opt = &icmp_param.replyopts; ++ ipc.opt = &icmp_param.replyopts.opt; + ipc.tx_flags = 0; + + rt = icmp_route_lookup(net, skb_in, iph, saddr, tos, +@@ -613,7 +612,7 @@ void icmp_send(struct sk_buff *skb_in, int type, int code, __be32 info) + room = dst_mtu(&rt->dst); + if (room > 576) + room = 576; +- room -= sizeof(struct iphdr) + icmp_param.replyopts.optlen; ++ room -= sizeof(struct iphdr) + icmp_param.replyopts.opt.opt.optlen; + room -= sizeof(struct icmphdr); + + icmp_param.data_len = skb_in->len - icmp_param.offset;",1060,1391,2048 +9102,"u2fh_devs_discover (u2fh_devs * devs, unsigned *max_index) +{ + struct hid_device_info *di, *cur_dev; + u2fh_rc res = U2FH_NO_U2F_DEVICE; + struct u2fdevice *dev; + + di = hid_enumerate (0, 0); + for (cur_dev = di; cur_dev; cur_dev = cur_dev->next) + { + int found = 0; + unsigned short usage_page = 0, usage = 0; + + /* check if we already opened this device */ + for (dev = devs->first; dev != NULL; dev = dev->next) + { + if (strcmp (dev->device_path, cur_dev->path) == 0) + { + if (ping_device (devs, dev->id) == U2FH_OK) + { + found = 1; + res = U2FH_OK; + } + else + { + if (debug) + { + fprintf (stderr, ""Device %s failed ping, dead.\n"", + dev->device_path); + } + close_device (devs, dev); + } + break; + } + } + if (found) + { + continue; + } + + get_usages (cur_dev, &usage_page, &usage); + if (usage_page == FIDO_USAGE_PAGE && usage == FIDO_USAGE_U2FHID) + { + dev = new_device (devs); + dev->devh = hid_open_path (cur_dev->path); + if (dev->devh != NULL) + { + dev->device_path = strdup (cur_dev->path); + if (dev->device_path == NULL) + { + close_device (devs, dev); + goto out; + } + if (init_device (devs, dev) == U2FH_OK) + { + if (cur_dev->product_string) + { + size_t len = + wcstombs (NULL, cur_dev->product_string, 0); + dev->device_string = malloc (len + 1); + if (dev->device_string == NULL) + { + close_device (devs, dev); + goto out; + } + memset (dev->device_string, 0, len + 1); + wcstombs (dev->device_string, cur_dev->product_string, + len); + if (debug) + { + fprintf (stderr, ""device %s discovered as '%s'\n"", + dev->device_path, dev->device_string); + fprintf (stderr, + "" version (Interface, Major, "" + ""Minor, Build): %d, %d, "" + ""%d, %d capFlags: %d\n"", + dev->versionInterface, + dev->versionMajor, + dev->versionMinor, + dev->versionBuild, dev->capFlags); + } + } + res = U2FH_OK; + continue; + } + } + close_device (devs, dev); + } + } + + + /* loop through all open devices and make sure we find them in the enumeration */ + dev = devs->first; + while (dev) + { + int found = 0; + + for (cur_dev = di; cur_dev; cur_dev = cur_dev->next) + { + if (strcmp (cur_dev->path, dev->device_path) == 0) + { + found = 1; + dev = dev->next; + break; + } + } + if (!found) + { + if (debug) + { + fprintf (stderr, ""device %s looks dead.\n"", dev->device_path); + } + dev = close_device (devs, dev); + } + } + +out: + hid_free_enumeration (di); + if (res == U2FH_OK && max_index) + *max_index = devs->max_id - 1; + + return res; +} +",0,"u2fh_devs_discover (u2fh_devs * devs, unsigned *max_index) +{ + struct hid_device_info *di, *cur_dev; + u2fh_rc res = U2FH_NO_U2F_DEVICE; + struct u2fdevice *dev; + + di = hid_enumerate (0, 0); + for (cur_dev = di; cur_dev; cur_dev = cur_dev->next) + { + int found = 0; + unsigned short usage_page = 0, usage = 0; + + /* check if we already opened this device */ + for (dev = devs->first; dev != NULL; dev = dev->next) + { + if (strcmp (dev->device_path, cur_dev->path) == 0) + { + if (ping_device (devs, dev->id) == U2FH_OK) + { + found = 1; + res = U2FH_OK; + } + else + { + if (debug) + { + fprintf (stderr, ""Device %s failed ping, dead.\n"", + dev->device_path); + } + close_device (devs, dev); + } + break; + } + } + if (found) + { + continue; + } + + get_usages (cur_dev, &usage_page, &usage); + if (usage_page == FIDO_USAGE_PAGE && usage == FIDO_USAGE_U2FHID) + { + dev = new_device (devs); + dev->devh = hid_open_path (cur_dev->path); + if (dev->devh != NULL) + { + dev->device_path = strdup (cur_dev->path); + if (dev->device_path == NULL) + { + close_device (devs, dev); + goto out; + } + if (init_device (devs, dev) == U2FH_OK) + { + if (cur_dev->product_string) + { + size_t len = + wcstombs (NULL, cur_dev->product_string, 0); + dev->device_string = malloc (len + 1); + if (dev->device_string == NULL) + { + close_device (devs, dev); + goto out; + } + memset (dev->device_string, 0, len + 1); + wcstombs (dev->device_string, cur_dev->product_string, + len); + if (debug) + { + fprintf (stderr, ""device %s discovered as '%s'\n"", + dev->device_path, dev->device_string); + fprintf (stderr, + "" version (Interface, Major, "" + ""Minor, Build): %d, %d, "" + ""%d, %d capFlags: %d\n"", + dev->versionInterface, + dev->versionMajor, + dev->versionMinor, + dev->versionBuild, dev->capFlags); + } + } + res = U2FH_OK; + continue; + } + } + close_device (devs, dev); + } + } + + + /* loop through all open devices and make sure we find them in the enumeration */ + dev = devs->first; + while (dev) + { + int found = 0; + + for (cur_dev = di; cur_dev; cur_dev = cur_dev->next) + { + if (strcmp (cur_dev->path, dev->device_path) == 0) + { + found = 1; + dev = dev->next; + break; + } + } + if (!found) + { + if (debug) + { + fprintf (stderr, ""device %s looks dead.\n"", dev->device_path); + } + dev = close_device (devs, dev); + } + } + +out: + hid_free_enumeration (di); + if (res == U2FH_OK && max_index) + *max_index = devs->max_id - 1; + + return res; +} +","@@ -302,17 +302,29 @@ init_device (u2fh_devs * devs, struct u2fdevice *dev) + (devs, dev->id, U2FHID_INIT, nonce, sizeof (nonce), resp, + &resplen) == U2FH_OK) + { +- U2FHID_INIT_RESP initresp; +- if (resplen > sizeof (initresp)) ++ int offs = sizeof (nonce); ++ /* the response has to be atleast 17 bytes, if it's more we discard that */ ++ if (resplen < 17) + { +- return U2FH_MEMORY_ERROR; ++ return U2FH_SIZE_ERROR; + } +- memcpy (&initresp, resp, resplen); +- dev->cid = initresp.cid; +- dev->versionInterface = initresp.versionInterface; +- dev->versionMajor = initresp.versionMajor; +- dev->versionMinor = initresp.versionMinor; +- dev->capFlags = initresp.capFlags; ++ ++ /* incoming and outgoing nonce has to match */ ++ if (memcmp (nonce, resp, sizeof (nonce)) != 0) ++ { ++ return U2FH_TRANSPORT_ERROR; ++ } ++ ++ dev->cid = ++ resp[offs] << 24 | resp[offs + 1] << 16 | resp[offs + ++ 2] << 8 | resp[offs + ++ 3]; ++ offs += 4; ++ dev->versionInterface = resp[offs++]; ++ dev->versionMajor = resp[offs++]; ++ dev->versionMinor = resp[offs++]; ++ dev->versionBuild = resp[offs++]; ++ dev->capFlags = resp[offs++]; + } + else + {",851,1182,2048 +18817,"void SoftMPEG4::onQueueFilled(OMX_U32 /* portIndex */) { + if (mSignalledError || mOutputPortSettingsChange != NONE) { + return; + } + + List &inQueue = getPortQueue(0); + List &outQueue = getPortQueue(1); + + while (!inQueue.empty() && outQueue.size() == kNumOutputBuffers) { + BufferInfo *inInfo = *inQueue.begin(); + OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; + if (inHeader == NULL) { + inQueue.erase(inQueue.begin()); + inInfo->mOwnedByUs = false; + continue; + } + + PortInfo *port = editPortInfo(1); + + OMX_BUFFERHEADERTYPE *outHeader = + port->mBuffers.editItemAt(mNumSamplesOutput & 1).mHeader; + + if (inHeader->nFilledLen == 0) { + inQueue.erase(inQueue.begin()); + inInfo->mOwnedByUs = false; + notifyEmptyBufferDone(inHeader); + + ++mInputBufferCount; + + if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { + outHeader->nFilledLen = 0; + outHeader->nFlags = OMX_BUFFERFLAG_EOS; + + List::iterator it = outQueue.begin(); + while ((*it)->mHeader != outHeader) { + ++it; + } + + BufferInfo *outInfo = *it; + outInfo->mOwnedByUs = false; + outQueue.erase(it); + outInfo = NULL; + + notifyFillBufferDone(outHeader); + outHeader = NULL; + } + return; + } + + uint8_t *bitstream = inHeader->pBuffer + inHeader->nOffset; + uint32_t *start_code = (uint32_t *)bitstream; + bool volHeader = *start_code == 0xB0010000; + if (volHeader) { + PVCleanUpVideoDecoder(mHandle); + mInitialized = false; + } + + if (!mInitialized) { + uint8_t *vol_data[1]; + int32_t vol_size = 0; + + vol_data[0] = NULL; + + if ((inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) || volHeader) { + vol_data[0] = bitstream; + vol_size = inHeader->nFilledLen; + } + + MP4DecodingMode mode = + (mMode == MODE_MPEG4) ? MPEG4_MODE : H263_MODE; + + Bool success = PVInitVideoDecoder( + mHandle, vol_data, &vol_size, 1, + outputBufferWidth(), outputBufferHeight(), mode); + + if (!success) { + ALOGW(""PVInitVideoDecoder failed. Unsupported content?""); + + notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); + mSignalledError = true; + return; + } + + MP4DecodingMode actualMode = PVGetDecBitstreamMode(mHandle); + if (mode != actualMode) { + notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); + mSignalledError = true; + return; + } + + PVSetPostProcType((VideoDecControls *) mHandle, 0); + + bool hasFrameData = false; + if (inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) { + inInfo->mOwnedByUs = false; + inQueue.erase(inQueue.begin()); + inInfo = NULL; + notifyEmptyBufferDone(inHeader); + inHeader = NULL; + } else if (volHeader) { + hasFrameData = true; + } + + mInitialized = true; + + if (mode == MPEG4_MODE && handlePortSettingsChange()) { + return; + } + + if (!hasFrameData) { + continue; + } + } + + if (!mFramesConfigured) { + PortInfo *port = editPortInfo(1); + OMX_BUFFERHEADERTYPE *outHeader = port->mBuffers.editItemAt(1).mHeader; + + PVSetReferenceYUV(mHandle, outHeader->pBuffer); + + mFramesConfigured = true; + } + + uint32_t useExtTimestamp = (inHeader->nOffset == 0); + + uint32_t timestamp = 0xFFFFFFFF; + if (useExtTimestamp) { + mPvToOmxTimeMap.add(mPvTime, inHeader->nTimeStamp); + timestamp = mPvTime; + mPvTime++; + } + + + int32_t bufferSize = inHeader->nFilledLen; + int32_t tmp = bufferSize; + + if (PVDecodeVideoFrame( + mHandle, &bitstream, ×tamp, &tmp, + &useExtTimestamp, + outHeader->pBuffer) != PV_TRUE) { + ALOGE(""failed to decode video frame.""); + + notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); + mSignalledError = true; + return; + } + + if (handlePortSettingsChange()) { + return; + } + + outHeader->nTimeStamp = mPvToOmxTimeMap.valueFor(timestamp); + mPvToOmxTimeMap.removeItem(timestamp); + + inHeader->nOffset += bufferSize; + inHeader->nFilledLen = 0; + if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { + outHeader->nFlags = OMX_BUFFERFLAG_EOS; + } else { + outHeader->nFlags = 0; + } + + if (inHeader->nFilledLen == 0) { + inInfo->mOwnedByUs = false; + inQueue.erase(inQueue.begin()); + inInfo = NULL; + notifyEmptyBufferDone(inHeader); + inHeader = NULL; + } + + + ++mInputBufferCount; + + outHeader->nOffset = 0; + outHeader->nFilledLen = (mWidth * mHeight * 3) / 2; + + List::iterator it = outQueue.begin(); + while ((*it)->mHeader != outHeader) { + ++it; + } + + BufferInfo *outInfo = *it; + outInfo->mOwnedByUs = false; + outQueue.erase(it); + outInfo = NULL; + + notifyFillBufferDone(outHeader); + outHeader = NULL; + + ++mNumSamplesOutput; + } +} +",1,"void SoftMPEG4::onQueueFilled(OMX_U32 /* portIndex */) { + if (mSignalledError || mOutputPortSettingsChange != NONE) { + return; + } + + List &inQueue = getPortQueue(0); + List &outQueue = getPortQueue(1); + + while (!inQueue.empty() && outQueue.size() == kNumOutputBuffers) { + BufferInfo *inInfo = *inQueue.begin(); + OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; + if (inHeader == NULL) { + inQueue.erase(inQueue.begin()); + inInfo->mOwnedByUs = false; + continue; + } + + PortInfo *port = editPortInfo(1); + + OMX_BUFFERHEADERTYPE *outHeader = + port->mBuffers.editItemAt(mNumSamplesOutput & 1).mHeader; + + if (inHeader->nFilledLen == 0) { + inQueue.erase(inQueue.begin()); + inInfo->mOwnedByUs = false; + notifyEmptyBufferDone(inHeader); + + ++mInputBufferCount; + + if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { + outHeader->nFilledLen = 0; + outHeader->nFlags = OMX_BUFFERFLAG_EOS; + + List::iterator it = outQueue.begin(); + while ((*it)->mHeader != outHeader) { + ++it; + } + + BufferInfo *outInfo = *it; + outInfo->mOwnedByUs = false; + outQueue.erase(it); + outInfo = NULL; + + notifyFillBufferDone(outHeader); + outHeader = NULL; + } + return; + } + + uint8_t *bitstream = inHeader->pBuffer + inHeader->nOffset; + uint32_t *start_code = (uint32_t *)bitstream; + bool volHeader = *start_code == 0xB0010000; + if (volHeader) { + PVCleanUpVideoDecoder(mHandle); + mInitialized = false; + } + + if (!mInitialized) { + uint8_t *vol_data[1]; + int32_t vol_size = 0; + + vol_data[0] = NULL; + + if ((inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) || volHeader) { + vol_data[0] = bitstream; + vol_size = inHeader->nFilledLen; + } + + MP4DecodingMode mode = + (mMode == MODE_MPEG4) ? MPEG4_MODE : H263_MODE; + + Bool success = PVInitVideoDecoder( + mHandle, vol_data, &vol_size, 1, + outputBufferWidth(), outputBufferHeight(), mode); + + if (!success) { + ALOGW(""PVInitVideoDecoder failed. Unsupported content?""); + + notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); + mSignalledError = true; + return; + } + + MP4DecodingMode actualMode = PVGetDecBitstreamMode(mHandle); + if (mode != actualMode) { + notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); + mSignalledError = true; + return; + } + + PVSetPostProcType((VideoDecControls *) mHandle, 0); + + bool hasFrameData = false; + if (inHeader->nFlags & OMX_BUFFERFLAG_CODECCONFIG) { + inInfo->mOwnedByUs = false; + inQueue.erase(inQueue.begin()); + inInfo = NULL; + notifyEmptyBufferDone(inHeader); + inHeader = NULL; + } else if (volHeader) { + hasFrameData = true; + } + + mInitialized = true; + + if (mode == MPEG4_MODE && handlePortSettingsChange()) { + return; + } + + if (!hasFrameData) { + continue; + } + } + + if (!mFramesConfigured) { + PortInfo *port = editPortInfo(1); + OMX_BUFFERHEADERTYPE *outHeader = port->mBuffers.editItemAt(1).mHeader; + + PVSetReferenceYUV(mHandle, outHeader->pBuffer); + + mFramesConfigured = true; + } + + uint32_t useExtTimestamp = (inHeader->nOffset == 0); + + uint32_t timestamp = 0xFFFFFFFF; + if (useExtTimestamp) { + mPvToOmxTimeMap.add(mPvTime, inHeader->nTimeStamp); + timestamp = mPvTime; + mPvTime++; + } + + + int32_t bufferSize = inHeader->nFilledLen; + int32_t tmp = bufferSize; + + OMX_U32 frameSize = (mWidth * mHeight * 3) / 2; + if (outHeader->nAllocLen < frameSize) { + android_errorWriteLog(0x534e4554, ""27833616""); + ALOGE(""Insufficient output buffer size""); + notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); + mSignalledError = true; + return; + } + if (PVDecodeVideoFrame( + mHandle, &bitstream, ×tamp, &tmp, + &useExtTimestamp, + outHeader->pBuffer) != PV_TRUE) { + ALOGE(""failed to decode video frame.""); + + notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); + mSignalledError = true; + return; + } + + if (handlePortSettingsChange()) { + return; + } + + outHeader->nTimeStamp = mPvToOmxTimeMap.valueFor(timestamp); + mPvToOmxTimeMap.removeItem(timestamp); + + inHeader->nOffset += bufferSize; + inHeader->nFilledLen = 0; + if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { + outHeader->nFlags = OMX_BUFFERFLAG_EOS; + } else { + outHeader->nFlags = 0; + } + + if (inHeader->nFilledLen == 0) { + inInfo->mOwnedByUs = false; + inQueue.erase(inQueue.begin()); + inInfo = NULL; + notifyEmptyBufferDone(inHeader); + inHeader = NULL; + } + + + ++mInputBufferCount; + + outHeader->nOffset = 0; + outHeader->nFilledLen = frameSize; + + List::iterator it = outQueue.begin(); + while ((*it)->mHeader != outHeader) { + ++it; + } + + BufferInfo *outInfo = *it; + outInfo->mOwnedByUs = false; + outQueue.erase(it); + outInfo = NULL; + + notifyFillBufferDone(outHeader); + outHeader = NULL; + + ++mNumSamplesOutput; + } +} +","@@ -229,6 +229,14 @@ + + int32_t bufferSize = inHeader->nFilledLen; + int32_t tmp = bufferSize; + ++ OMX_U32 frameSize = (mWidth * mHeight * 3) / 2; ++ if (outHeader->nAllocLen < frameSize) { ++ android_errorWriteLog(0x534e4554, ""27833616""); ++ ALOGE(""Insufficient output buffer size""); ++ notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); ++ mSignalledError = true; ++ return; ++ } + // The PV decoder is lying to us, sometimes it'll claim to only have + // consumed a subset of the buffer when it clearly consumed all of it. + // ignore whatever it says... +@@ -272,7 +280,7 @@ + + ++mInputBufferCount; + + outHeader->nOffset = 0; +- outHeader->nFilledLen = (mWidth * mHeight * 3) / 2; ++ outHeader->nFilledLen = frameSize; + + List::iterator it = outQueue.begin(); + while ((*it)->mHeader != outHeader) { +",1308,1639,2048 +16533,"void NavigationRequest::OnWillProcessResponseChecksComplete( + NavigationThrottle::ThrottleCheckResult result) { + DCHECK(result.action() != NavigationThrottle::DEFER); + + if (result.action() == NavigationThrottle::PROCEED) { + bool served_via_resource_dispatcher_host = + !base::FeatureList::IsEnabled(network::features::kNetworkService); + served_via_resource_dispatcher_host = + served_via_resource_dispatcher_host && + !(blink::ServiceWorkerUtils::IsServicificationEnabled() && + response_->head.was_fetched_via_service_worker); + + if (is_download_ && !served_via_resource_dispatcher_host) { + auto resource_request = std::make_unique(); + resource_request->url = common_params_.url; + resource_request->method = common_params_.method; + resource_request->request_initiator = common_params_.initiator_origin; + resource_request->referrer = common_params_.referrer.url; + resource_request->has_user_gesture = common_params_.has_user_gesture; + + BrowserContext* browser_context = + frame_tree_node_->navigator()->GetController()->GetBrowserContext(); + DownloadManagerImpl* download_manager = static_cast( + BrowserContext::GetDownloadManager(browser_context)); + download_manager->InterceptNavigation( + std::move(resource_request), navigation_handle_->GetRedirectChain(), + response_, std::move(url_loader_client_endpoints_), + ssl_info_.has_value() ? ssl_info_->cert_status : 0, + frame_tree_node_->frame_tree_node_id()); + + OnRequestFailedInternal( + network::URLLoaderCompletionStatus(net::ERR_ABORTED), + false /*skip_throttles*/, base::nullopt /*error_page_content*/, + false /*collapse_frame*/); + return; + } + + if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) { + if (url_loader_client_endpoints_) { + network::mojom::URLLoaderPtr url_loader( + std::move(url_loader_client_endpoints_->url_loader)); + url_loader->ProceedWithResponse(); + url_loader_client_endpoints_->url_loader = url_loader.PassInterface(); + } else { + loader_->ProceedWithResponse(); + } + } + } + + if (result.action() == NavigationThrottle::CANCEL_AND_IGNORE || + result.action() == NavigationThrottle::CANCEL || + !response_should_be_rendered_) { + render_frame_host_ = nullptr; + + if (!response_should_be_rendered_) { + OnRequestFailedInternal( + network::URLLoaderCompletionStatus(net::ERR_ABORTED), + true /* skip_throttles */, base::nullopt /* error_page_content */, + false /* collapse_frame */); + return; + } + + DCHECK(result.action() == NavigationThrottle::CANCEL || + result.net_error_code() == net::ERR_ABORTED); + OnRequestFailedInternal( + network::URLLoaderCompletionStatus(result.net_error_code()), + true /* skip_throttles */, result.error_page_content(), + false /* collapse_frame */); + + return; + } + + if (result.action() == NavigationThrottle::BLOCK_RESPONSE) { + DCHECK_EQ(net::ERR_BLOCKED_BY_RESPONSE, result.net_error_code()); + render_frame_host_ = nullptr; + OnRequestFailedInternal( + network::URLLoaderCompletionStatus(result.net_error_code()), + true /* skip_throttles */, result.error_page_content(), + false /* collapse_frame */); + return; + } + + CommitNavigation(); + +} +",0,"void NavigationRequest::OnWillProcessResponseChecksComplete( + NavigationThrottle::ThrottleCheckResult result) { + DCHECK(result.action() != NavigationThrottle::DEFER); + + if (result.action() == NavigationThrottle::PROCEED) { + bool served_via_resource_dispatcher_host = + !base::FeatureList::IsEnabled(network::features::kNetworkService); + served_via_resource_dispatcher_host = + served_via_resource_dispatcher_host && + !(blink::ServiceWorkerUtils::IsServicificationEnabled() && + response_->head.was_fetched_via_service_worker); + + if (is_download_ && !served_via_resource_dispatcher_host) { + auto resource_request = std::make_unique(); + resource_request->url = common_params_.url; + resource_request->method = common_params_.method; + resource_request->request_initiator = common_params_.initiator_origin; + resource_request->referrer = common_params_.referrer.url; + resource_request->has_user_gesture = common_params_.has_user_gesture; + + BrowserContext* browser_context = + frame_tree_node_->navigator()->GetController()->GetBrowserContext(); + DownloadManagerImpl* download_manager = static_cast( + BrowserContext::GetDownloadManager(browser_context)); + download_manager->InterceptNavigation( + std::move(resource_request), navigation_handle_->GetRedirectChain(), + response_, std::move(url_loader_client_endpoints_), + ssl_info_.has_value() ? ssl_info_->cert_status : 0, + frame_tree_node_->frame_tree_node_id()); + + OnRequestFailedInternal( + network::URLLoaderCompletionStatus(net::ERR_ABORTED), + false /*skip_throttles*/, base::nullopt /*error_page_content*/, + false /*collapse_frame*/); + return; + } + + if (!base::FeatureList::IsEnabled(network::features::kNetworkService)) { + if (url_loader_client_endpoints_) { + network::mojom::URLLoaderPtr url_loader( + std::move(url_loader_client_endpoints_->url_loader)); + url_loader->ProceedWithResponse(); + url_loader_client_endpoints_->url_loader = url_loader.PassInterface(); + } else { + loader_->ProceedWithResponse(); + } + } + } + + if (result.action() == NavigationThrottle::CANCEL_AND_IGNORE || + result.action() == NavigationThrottle::CANCEL || + !response_should_be_rendered_) { + render_frame_host_ = nullptr; + + if (!response_should_be_rendered_) { + OnRequestFailedInternal( + network::URLLoaderCompletionStatus(net::ERR_ABORTED), + true /* skip_throttles */, base::nullopt /* error_page_content */, + false /* collapse_frame */); + return; + } + + DCHECK(result.action() == NavigationThrottle::CANCEL || + result.net_error_code() == net::ERR_ABORTED); + OnRequestFailedInternal( + network::URLLoaderCompletionStatus(result.net_error_code()), + true /* skip_throttles */, result.error_page_content(), + false /* collapse_frame */); + + return; + } + + if (result.action() == NavigationThrottle::BLOCK_RESPONSE) { + DCHECK_EQ(net::ERR_BLOCKED_BY_RESPONSE, result.net_error_code()); + render_frame_host_ = nullptr; + OnRequestFailedInternal( + network::URLLoaderCompletionStatus(result.net_error_code()), + true /* skip_throttles */, result.error_page_content(), + false /* collapse_frame */); + return; + } + + CommitNavigation(); + +} +","@@ -894,8 +894,13 @@ void NavigationRequest::OnRequestRedirected( + redirect_info.new_url)) { + DVLOG(1) << ""Denied redirect for "" + << redirect_info.new_url.possibly_invalid_spec(); +- navigation_handle_->set_net_error_code(net::ERR_UNSAFE_REDIRECT); +- frame_tree_node_->ResetNavigationRequest(false, true); ++ // Show an error page rather than leaving the previous page in place. ++ OnRequestFailedInternal( ++ network::URLLoaderCompletionStatus(net::ERR_UNSAFE_REDIRECT), ++ false /* skip_throttles */, base::nullopt /* error_page_content */, ++ false /* collapse_frame */); ++ // DO NOT ADD CODE after this. The previous call to OnRequestFailedInternal ++ // has destroyed the NavigationRequest. + return; + } + +@@ -908,8 +913,13 @@ void NavigationRequest::OnRequestRedirected( + redirect_info.new_url)) { + DVLOG(1) << ""Denied unauthorized redirect for "" + << redirect_info.new_url.possibly_invalid_spec(); +- navigation_handle_->set_net_error_code(net::ERR_UNSAFE_REDIRECT); +- frame_tree_node_->ResetNavigationRequest(false, true); ++ // Show an error page rather than leaving the previous page in place. ++ OnRequestFailedInternal( ++ network::URLLoaderCompletionStatus(net::ERR_UNSAFE_REDIRECT), ++ false /* skip_throttles */, base::nullopt /* error_page_content */, ++ false /* collapse_frame */); ++ // DO NOT ADD CODE after this. The previous call to OnRequestFailedInternal ++ // has destroyed the NavigationRequest. + return; + } + ",723,1054,2048 +6341,"gssint_wrap_aead_iov_shim(gss_mechanism mech, + OM_uint32 *minor_status, + gss_ctx_id_t context_handle, + int conf_req_flag, + gss_qop_t qop_req, + gss_buffer_t input_assoc_buffer, + gss_buffer_t input_payload_buffer, + int *conf_state, + gss_buffer_t output_message_buffer) +{ + gss_iov_buffer_desc iov[5]; + OM_uint32 status; + size_t offset; + int i = 0, iov_count; + + /* HEADER | SIGN_ONLY_DATA | DATA | PADDING | TRAILER */ + + iov[i].type = GSS_IOV_BUFFER_TYPE_HEADER; + iov[i].buffer.value = NULL; + iov[i].buffer.length = 0; + i++; + + if (input_assoc_buffer != GSS_C_NO_BUFFER) { + iov[i].type = GSS_IOV_BUFFER_TYPE_SIGN_ONLY; + iov[i].buffer = *input_assoc_buffer; + i++; + } + + iov[i].type = GSS_IOV_BUFFER_TYPE_DATA; + iov[i].buffer = *input_payload_buffer; + i++; + + iov[i].type = GSS_IOV_BUFFER_TYPE_PADDING; + iov[i].buffer.value = NULL; + iov[i].buffer.length = 0; + i++; + + iov[i].type = GSS_IOV_BUFFER_TYPE_TRAILER; + iov[i].buffer.value = NULL; + iov[i].buffer.length = 0; + i++; + + iov_count = i; + + assert(mech->gss_wrap_iov_length); + + status = mech->gss_wrap_iov_length(minor_status, context_handle, + conf_req_flag, qop_req, + NULL, iov, iov_count); + if (status != GSS_S_COMPLETE) { + map_error(minor_status, mech); + return status; + } + + /* Format output token (does not include associated data) */ + for (i = 0, output_message_buffer->length = 0; i < iov_count; i++) { + if (GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_SIGN_ONLY) + continue; + + output_message_buffer->length += iov[i].buffer.length; + } + + output_message_buffer->value = gssalloc_malloc(output_message_buffer->length); + if (output_message_buffer->value == NULL) { + *minor_status = ENOMEM; + return GSS_S_FAILURE; + } + + i = 0, offset = 0; + + /* HEADER */ + iov[i].buffer.value = (unsigned char *)output_message_buffer->value + offset; + offset += iov[i].buffer.length; + i++; + + /* SIGN_ONLY_DATA */ + if (input_assoc_buffer != GSS_C_NO_BUFFER) + i++; + + /* DATA */ + iov[i].buffer.value = (unsigned char *)output_message_buffer->value + offset; + offset += iov[i].buffer.length; + + memcpy(iov[i].buffer.value, input_payload_buffer->value, iov[i].buffer.length); + i++; + + /* PADDING */ + iov[i].buffer.value = (unsigned char *)output_message_buffer->value + offset; + offset += iov[i].buffer.length; + i++; + + /* TRAILER */ + iov[i].buffer.value = (unsigned char *)output_message_buffer->value + offset; + offset += iov[i].buffer.length; + i++; + + assert(offset == output_message_buffer->length); + + assert(mech->gss_wrap_iov); + + status = mech->gss_wrap_iov(minor_status, context_handle, + conf_req_flag, qop_req, + conf_state, iov, iov_count); + if (status != GSS_S_COMPLETE) { + OM_uint32 minor; + + map_error(minor_status, mech); + gss_release_buffer(&minor, output_message_buffer); + } + + return status; +} +",0,"gssint_wrap_aead_iov_shim(gss_mechanism mech, + OM_uint32 *minor_status, + gss_ctx_id_t context_handle, + int conf_req_flag, + gss_qop_t qop_req, + gss_buffer_t input_assoc_buffer, + gss_buffer_t input_payload_buffer, + int *conf_state, + gss_buffer_t output_message_buffer) +{ + gss_iov_buffer_desc iov[5]; + OM_uint32 status; + size_t offset; + int i = 0, iov_count; + + /* HEADER | SIGN_ONLY_DATA | DATA | PADDING | TRAILER */ + + iov[i].type = GSS_IOV_BUFFER_TYPE_HEADER; + iov[i].buffer.value = NULL; + iov[i].buffer.length = 0; + i++; + + if (input_assoc_buffer != GSS_C_NO_BUFFER) { + iov[i].type = GSS_IOV_BUFFER_TYPE_SIGN_ONLY; + iov[i].buffer = *input_assoc_buffer; + i++; + } + + iov[i].type = GSS_IOV_BUFFER_TYPE_DATA; + iov[i].buffer = *input_payload_buffer; + i++; + + iov[i].type = GSS_IOV_BUFFER_TYPE_PADDING; + iov[i].buffer.value = NULL; + iov[i].buffer.length = 0; + i++; + + iov[i].type = GSS_IOV_BUFFER_TYPE_TRAILER; + iov[i].buffer.value = NULL; + iov[i].buffer.length = 0; + i++; + + iov_count = i; + + assert(mech->gss_wrap_iov_length); + + status = mech->gss_wrap_iov_length(minor_status, context_handle, + conf_req_flag, qop_req, + NULL, iov, iov_count); + if (status != GSS_S_COMPLETE) { + map_error(minor_status, mech); + return status; + } + + /* Format output token (does not include associated data) */ + for (i = 0, output_message_buffer->length = 0; i < iov_count; i++) { + if (GSS_IOV_BUFFER_TYPE(iov[i].type) == GSS_IOV_BUFFER_TYPE_SIGN_ONLY) + continue; + + output_message_buffer->length += iov[i].buffer.length; + } + + output_message_buffer->value = gssalloc_malloc(output_message_buffer->length); + if (output_message_buffer->value == NULL) { + *minor_status = ENOMEM; + return GSS_S_FAILURE; + } + + i = 0, offset = 0; + + /* HEADER */ + iov[i].buffer.value = (unsigned char *)output_message_buffer->value + offset; + offset += iov[i].buffer.length; + i++; + + /* SIGN_ONLY_DATA */ + if (input_assoc_buffer != GSS_C_NO_BUFFER) + i++; + + /* DATA */ + iov[i].buffer.value = (unsigned char *)output_message_buffer->value + offset; + offset += iov[i].buffer.length; + + memcpy(iov[i].buffer.value, input_payload_buffer->value, iov[i].buffer.length); + i++; + + /* PADDING */ + iov[i].buffer.value = (unsigned char *)output_message_buffer->value + offset; + offset += iov[i].buffer.length; + i++; + + /* TRAILER */ + iov[i].buffer.value = (unsigned char *)output_message_buffer->value + offset; + offset += iov[i].buffer.length; + i++; + + assert(offset == output_message_buffer->length); + + assert(mech->gss_wrap_iov); + + status = mech->gss_wrap_iov(minor_status, context_handle, + conf_req_flag, qop_req, + conf_state, iov, iov_count); + if (status != GSS_S_COMPLETE) { + OM_uint32 minor; + + map_error(minor_status, mech); + gss_release_buffer(&minor, output_message_buffer); + } + + return status; +} +","@@ -256,6 +256,8 @@ gss_buffer_t output_message_buffer; + * call it. + */ + ctx = (gss_union_ctx_id_t)context_handle; ++ if (ctx->internal_ctx_id == GSS_C_NO_CONTEXT) ++ return (GSS_S_NO_CONTEXT); + mech = gssint_get_mechanism (ctx->mech_type); + if (!mech) + return (GSS_S_BAD_MECH);",818,1149,2048 +15912,"void GLES2DecoderImpl::DoSwapBuffers(uint64_t swap_id, GLbitfield flags) { + bool is_offscreen = !!offscreen_target_frame_buffer_.get(); + + int this_frame_number = frame_number_++; + TRACE_EVENT_INSTANT2( + ""test_gpu"", ""SwapBuffersLatency"", TRACE_EVENT_SCOPE_THREAD, ""GLImpl"", + static_cast(gl::GetGLImplementation()), ""width"", + (is_offscreen ? offscreen_size_.width() : surface_->GetSize().width())); + TRACE_EVENT2(""gpu"", ""GLES2DecoderImpl::DoSwapBuffers"", + ""offscreen"", is_offscreen, + ""frame"", this_frame_number); + + ScopedGPUTrace scoped_gpu_trace(gpu_tracer_.get(), kTraceDecoder, + ""GLES2Decoder"", ""SwapBuffer""); + + bool is_tracing; + TRACE_EVENT_CATEGORY_GROUP_ENABLED(TRACE_DISABLED_BY_DEFAULT(""gpu.debug""), + &is_tracing); + if (is_tracing) { + ScopedFramebufferBinder binder(this, GetBoundDrawFramebufferServiceId()); + gpu_state_tracer_->TakeSnapshotWithCurrentFramebuffer( + is_offscreen ? offscreen_size_ : surface_->GetSize()); + } + + ClearScheduleCALayerState(); + ClearScheduleDCLayerState(); + + if (is_offscreen) { + TRACE_EVENT2(""gpu"", ""Offscreen"", + ""width"", offscreen_size_.width(), ""height"", offscreen_size_.height()); + + if (offscreen_single_buffer_) + return; + + if (offscreen_size_ != offscreen_saved_color_texture_->size()) { + if (workarounds().needs_offscreen_buffer_workaround) { + offscreen_saved_frame_buffer_->Create(); + api()->glFinishFn(); + } + + ReleaseNotInUseBackTextures(); + + DCHECK(offscreen_saved_color_format_); + offscreen_saved_color_texture_->AllocateStorage( + offscreen_size_, offscreen_saved_color_format_, false); + + offscreen_saved_frame_buffer_->AttachRenderTexture( + offscreen_saved_color_texture_.get()); + if (offscreen_size_.width() != 0 && offscreen_size_.height() != 0) { + if (offscreen_saved_frame_buffer_->CheckStatus() != + GL_FRAMEBUFFER_COMPLETE) { + LOG(ERROR) << ""GLES2DecoderImpl::ResizeOffscreenFramebuffer failed "" + << ""because offscreen saved FBO was incomplete.""; + MarkContextLost(error::kUnknown); + group_->LoseContexts(error::kUnknown); + return; + } + + { + ScopedFramebufferBinder binder(this, + offscreen_saved_frame_buffer_->id()); + api()->glClearColorFn(0, 0, 0, BackBufferAlphaClearColor()); + state_.SetDeviceColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + state_.SetDeviceCapabilityState(GL_SCISSOR_TEST, false); + ClearDeviceWindowRectangles(); + api()->glClearFn(GL_COLOR_BUFFER_BIT); + RestoreClearState(); + } + } + } + + if (offscreen_size_.width() == 0 || offscreen_size_.height() == 0) + return; + ScopedGLErrorSuppressor suppressor( + ""GLES2DecoderImpl::DoSwapBuffers"", GetErrorState()); + + if (IsOffscreenBufferMultisampled()) { + ScopedResolvedFramebufferBinder binder(this, true, false); + } else { + ScopedFramebufferBinder binder(this, + offscreen_target_frame_buffer_->id()); + + if (offscreen_target_buffer_preserved_) { + offscreen_saved_color_texture_->Copy(); + } else { + offscreen_saved_color_texture_.swap(offscreen_target_color_texture_); + offscreen_target_frame_buffer_->AttachRenderTexture( + offscreen_target_color_texture_.get()); + offscreen_saved_frame_buffer_->AttachRenderTexture( + offscreen_saved_color_texture_.get()); + } + + if (!gl_version_info().is_angle) + api()->glFlushFn(); + } + } else if (supports_async_swap_) { + TRACE_EVENT_ASYNC_BEGIN0(""gpu"", ""AsyncSwapBuffers"", swap_id); + + client_->OnSwapBuffers(swap_id, flags); + surface_->SwapBuffersAsync( + base::Bind(&GLES2DecoderImpl::FinishAsyncSwapBuffers, + weak_ptr_factory_.GetWeakPtr(), swap_id), + base::DoNothing()); + } else { + client_->OnSwapBuffers(swap_id, flags); + FinishSwapBuffers(surface_->SwapBuffers(base::DoNothing())); + } + + ExitCommandProcessingEarly(); +} +",0,"void GLES2DecoderImpl::DoSwapBuffers(uint64_t swap_id, GLbitfield flags) { + bool is_offscreen = !!offscreen_target_frame_buffer_.get(); + + int this_frame_number = frame_number_++; + TRACE_EVENT_INSTANT2( + ""test_gpu"", ""SwapBuffersLatency"", TRACE_EVENT_SCOPE_THREAD, ""GLImpl"", + static_cast(gl::GetGLImplementation()), ""width"", + (is_offscreen ? offscreen_size_.width() : surface_->GetSize().width())); + TRACE_EVENT2(""gpu"", ""GLES2DecoderImpl::DoSwapBuffers"", + ""offscreen"", is_offscreen, + ""frame"", this_frame_number); + + ScopedGPUTrace scoped_gpu_trace(gpu_tracer_.get(), kTraceDecoder, + ""GLES2Decoder"", ""SwapBuffer""); + + bool is_tracing; + TRACE_EVENT_CATEGORY_GROUP_ENABLED(TRACE_DISABLED_BY_DEFAULT(""gpu.debug""), + &is_tracing); + if (is_tracing) { + ScopedFramebufferBinder binder(this, GetBoundDrawFramebufferServiceId()); + gpu_state_tracer_->TakeSnapshotWithCurrentFramebuffer( + is_offscreen ? offscreen_size_ : surface_->GetSize()); + } + + ClearScheduleCALayerState(); + ClearScheduleDCLayerState(); + + if (is_offscreen) { + TRACE_EVENT2(""gpu"", ""Offscreen"", + ""width"", offscreen_size_.width(), ""height"", offscreen_size_.height()); + + if (offscreen_single_buffer_) + return; + + if (offscreen_size_ != offscreen_saved_color_texture_->size()) { + if (workarounds().needs_offscreen_buffer_workaround) { + offscreen_saved_frame_buffer_->Create(); + api()->glFinishFn(); + } + + ReleaseNotInUseBackTextures(); + + DCHECK(offscreen_saved_color_format_); + offscreen_saved_color_texture_->AllocateStorage( + offscreen_size_, offscreen_saved_color_format_, false); + + offscreen_saved_frame_buffer_->AttachRenderTexture( + offscreen_saved_color_texture_.get()); + if (offscreen_size_.width() != 0 && offscreen_size_.height() != 0) { + if (offscreen_saved_frame_buffer_->CheckStatus() != + GL_FRAMEBUFFER_COMPLETE) { + LOG(ERROR) << ""GLES2DecoderImpl::ResizeOffscreenFramebuffer failed "" + << ""because offscreen saved FBO was incomplete.""; + MarkContextLost(error::kUnknown); + group_->LoseContexts(error::kUnknown); + return; + } + + { + ScopedFramebufferBinder binder(this, + offscreen_saved_frame_buffer_->id()); + api()->glClearColorFn(0, 0, 0, BackBufferAlphaClearColor()); + state_.SetDeviceColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + state_.SetDeviceCapabilityState(GL_SCISSOR_TEST, false); + ClearDeviceWindowRectangles(); + api()->glClearFn(GL_COLOR_BUFFER_BIT); + RestoreClearState(); + } + } + } + + if (offscreen_size_.width() == 0 || offscreen_size_.height() == 0) + return; + ScopedGLErrorSuppressor suppressor( + ""GLES2DecoderImpl::DoSwapBuffers"", GetErrorState()); + + if (IsOffscreenBufferMultisampled()) { + ScopedResolvedFramebufferBinder binder(this, true, false); + } else { + ScopedFramebufferBinder binder(this, + offscreen_target_frame_buffer_->id()); + + if (offscreen_target_buffer_preserved_) { + offscreen_saved_color_texture_->Copy(); + } else { + offscreen_saved_color_texture_.swap(offscreen_target_color_texture_); + offscreen_target_frame_buffer_->AttachRenderTexture( + offscreen_target_color_texture_.get()); + offscreen_saved_frame_buffer_->AttachRenderTexture( + offscreen_saved_color_texture_.get()); + } + + if (!gl_version_info().is_angle) + api()->glFlushFn(); + } + } else if (supports_async_swap_) { + TRACE_EVENT_ASYNC_BEGIN0(""gpu"", ""AsyncSwapBuffers"", swap_id); + + client_->OnSwapBuffers(swap_id, flags); + surface_->SwapBuffersAsync( + base::Bind(&GLES2DecoderImpl::FinishAsyncSwapBuffers, + weak_ptr_factory_.GetWeakPtr(), swap_id), + base::DoNothing()); + } else { + client_->OnSwapBuffers(swap_id, flags); + FinishSwapBuffers(surface_->SwapBuffers(base::DoNothing())); + } + + ExitCommandProcessingEarly(); +} +","@@ -11384,29 +11384,24 @@ void GLES2DecoderImpl::GetTexParameterImpl( + return; + } + break; +- // Get the level information from the texture to avoid a Mac driver +- // bug where they store the levels in int16_t, making values bigger +- // than 2^15-1 overflow in the negative range. + case GL_TEXTURE_BASE_LEVEL: +- if (workarounds().use_shadowed_tex_level_params) { +- if (fparams) { +- fparams[0] = static_cast(texture->base_level()); +- } else { +- iparams[0] = texture->base_level(); +- } +- return; ++ // Use shadowed value in case it's clamped; also because older MacOSX ++ // stores the value on int16_t (see https://crbug.com/610153). ++ if (fparams) { ++ fparams[0] = static_cast(texture->unclamped_base_level()); ++ } else { ++ iparams[0] = texture->unclamped_base_level(); + } +- break; ++ return; + case GL_TEXTURE_MAX_LEVEL: +- if (workarounds().use_shadowed_tex_level_params) { +- if (fparams) { +- fparams[0] = static_cast(texture->max_level()); +- } else { +- iparams[0] = texture->max_level(); +- } +- return; ++ // Use shadowed value in case it's clamped; also because older MacOSX ++ // stores the value on int16_t (see https://crbug.com/610153). ++ if (fparams) { ++ fparams[0] = static_cast(texture->unclamped_max_level()); ++ } else { ++ iparams[0] = texture->unclamped_max_level(); + } +- break; ++ return; + case GL_TEXTURE_SWIZZLE_R: + if (fparams) { + fparams[0] = static_cast(texture->swizzle_r()); +@@ -17573,25 +17568,6 @@ void GLES2DecoderImpl::TexStorageImpl(GLenum target, + compatibility_internal_format = format_info->decompressed_internal_format; + } + +- if (workarounds().reset_base_mipmap_level_before_texstorage && +- texture->base_level() > 0) +- api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, 0); +- +- // TODO(zmo): We might need to emulate TexStorage using TexImage or +- // CompressedTexImage on Mac OSX where we expose ES3 APIs when the underlying +- // driver is lower than 4.2 and ARB_texture_storage extension doesn't exist. +- if (dimension == ContextState::k2D) { +- api()->glTexStorage2DEXTFn(target, levels, compatibility_internal_format, +- width, height); +- } else { +- api()->glTexStorage3DFn(target, levels, compatibility_internal_format, +- width, height, depth); +- } +- if (workarounds().reset_base_mipmap_level_before_texstorage && +- texture->base_level() > 0) +- api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, +- texture->base_level()); +- + { + GLsizei level_width = width; + GLsizei level_height = height; +@@ -17620,6 +17596,29 @@ void GLES2DecoderImpl::TexStorageImpl(GLenum target, + texture->ApplyFormatWorkarounds(feature_info_.get()); + texture->SetImmutable(true); + } ++ ++ if (workarounds().reset_base_mipmap_level_before_texstorage && ++ texture->base_level() > 0) ++ api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, 0); ++ ++ // TODO(zmo): We might need to emulate TexStorage using TexImage or ++ // CompressedTexImage on Mac OSX where we expose ES3 APIs when the underlying ++ // driver is lower than 4.2 and ARB_texture_storage extension doesn't exist. ++ if (dimension == ContextState::k2D) { ++ api()->glTexStorage2DEXTFn(target, levels, compatibility_internal_format, ++ width, height); ++ } else { ++ api()->glTexStorage3DFn(target, levels, compatibility_internal_format, ++ width, height, depth); ++ } ++ if (workarounds().reset_base_mipmap_level_before_texstorage && ++ texture->base_level() > 0) { ++ // Note base_level is already clamped due to texture->SetImmutable(true). ++ // This is necessary for certain NVidia Linux drivers; otherwise they ++ // may trigger segmentation fault. See https://crbug.com/877874. ++ api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, ++ texture->base_level()); ++ } + } + + void GLES2DecoderImpl::DoTexStorage2DEXT(GLenum target,",935,1266,2048 +18184,"static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, + jas_stream_t *in) +{ + jpc_siz_t *siz = &ms->parms.siz; + unsigned int i; + uint_fast8_t tmp; + + /* Eliminate compiler warning about unused variables. */ + cstate = 0; + + if (jpc_getuint16(in, &siz->caps) || + jpc_getuint32(in, &siz->width) || + jpc_getuint32(in, &siz->height) || + jpc_getuint32(in, &siz->xoff) || + jpc_getuint32(in, &siz->yoff) || + jpc_getuint32(in, &siz->tilewidth) || + jpc_getuint32(in, &siz->tileheight) || + jpc_getuint32(in, &siz->tilexoff) || + jpc_getuint32(in, &siz->tileyoff) || + jpc_getuint16(in, &siz->numcomps)) { + return -1; + } + if (!siz->width || !siz->height || !siz->tilewidth || + !siz->tileheight || !siz->numcomps || siz->numcomps > 16384) { + return -1; + } + if (siz->tilexoff >= siz->width || siz->tileyoff >= siz->height) { + jas_eprintf(""all tiles are outside the image area\n""); + return -1; + } + if (!(siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)))) { + return -1; + } + for (i = 0; i < siz->numcomps; ++i) { + if (jpc_getuint8(in, &tmp) || + jpc_getuint8(in, &siz->comps[i].hsamp) || + jpc_getuint8(in, &siz->comps[i].vsamp)) { + jas_free(siz->comps); + return -1; + } + if (siz->comps[i].hsamp == 0 || siz->comps[i].hsamp > 255) { + jas_eprintf(""invalid XRsiz value %d\n"", siz->comps[i].hsamp); + jas_free(siz->comps); + return -1; + } + if (siz->comps[i].vsamp == 0 || siz->comps[i].vsamp > 255) { + jas_eprintf(""invalid YRsiz value %d\n"", siz->comps[i].vsamp); + jas_free(siz->comps); + return -1; + } + siz->comps[i].sgnd = (tmp >> 7) & 1; + siz->comps[i].prec = (tmp & 0x7f) + 1; + } + if (jas_stream_eof(in)) { + jas_free(siz->comps); + return -1; + } + return 0; + } +",1,"static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, + jas_stream_t *in) +{ + jpc_siz_t *siz = &ms->parms.siz; + unsigned int i; + uint_fast8_t tmp; + + siz->comps = 0; + + /* Eliminate compiler warning about unused variables. */ + cstate = 0; + + if (jpc_getuint16(in, &siz->caps) || + jpc_getuint32(in, &siz->width) || + jpc_getuint32(in, &siz->height) || + jpc_getuint32(in, &siz->xoff) || + jpc_getuint32(in, &siz->yoff) || + jpc_getuint32(in, &siz->tilewidth) || + jpc_getuint32(in, &siz->tileheight) || + jpc_getuint32(in, &siz->tilexoff) || + jpc_getuint32(in, &siz->tileyoff) || + jpc_getuint16(in, &siz->numcomps)) { + goto error; + } + if (!siz->width || !siz->height) { + jas_eprintf(""reference grid cannot have zero area\n""); + goto error; + } + if (!siz->tilewidth || !siz->tileheight) { + jas_eprintf(""tile cannot have zero area\n""); + goto error; + } + if (!siz->numcomps || siz->numcomps > 16384) { + jas_eprintf(""number of components not in permissible range\n""); + goto error; + } + if (siz->xoff >= siz->width) { + jas_eprintf(""XOsiz not in permissible range\n""); + goto error; + } + if (siz->yoff >= siz->height) { + jas_eprintf(""YOsiz not in permissible range\n""); + goto error; + } + if (siz->tilexoff > siz->xoff || siz->tilexoff + siz->tilewidth <= siz->xoff) { + jas_eprintf(""XTOsiz not in permissible range\n""); + goto error; + } + if (siz->tileyoff > siz->yoff || siz->tileyoff + siz->tileheight <= siz->yoff) { + jas_eprintf(""YTOsiz not in permissible range\n""); + goto error; + } + + if (!(siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)))) { + goto error; + } + for (i = 0; i < siz->numcomps; ++i) { + if (jpc_getuint8(in, &tmp) || + jpc_getuint8(in, &siz->comps[i].hsamp) || + jpc_getuint8(in, &siz->comps[i].vsamp)) { + goto error; + } + if (siz->comps[i].hsamp == 0 || siz->comps[i].hsamp > 255) { + jas_eprintf(""invalid XRsiz value %d\n"", siz->comps[i].hsamp); + goto error; + } + if (siz->comps[i].vsamp == 0 || siz->comps[i].vsamp > 255) { + jas_eprintf(""invalid YRsiz value %d\n"", siz->comps[i].vsamp); + goto error; + } + siz->comps[i].sgnd = (tmp >> 7) & 1; + siz->comps[i].prec = (tmp & 0x7f) + 1; + } + if (jas_stream_eof(in)) { + goto error; + } + return 0; + +error: + if (siz->comps) { + jas_free(siz->comps); + } + return -1; + } +","@@ -489,6 +489,8 @@ static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, + unsigned int i; + uint_fast8_t tmp; + ++ siz->comps = 0; ++ + /* Eliminate compiler warning about unused variables. */ + cstate = 0; + +@@ -502,44 +504,67 @@ static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, + jpc_getuint32(in, &siz->tilexoff) || + jpc_getuint32(in, &siz->tileyoff) || + jpc_getuint16(in, &siz->numcomps)) { +- return -1; ++ goto error; + } +- if (!siz->width || !siz->height || !siz->tilewidth || +- !siz->tileheight || !siz->numcomps || siz->numcomps > 16384) { +- return -1; ++ if (!siz->width || !siz->height) { ++ jas_eprintf(""reference grid cannot have zero area\n""); ++ goto error; + } +- if (siz->tilexoff >= siz->width || siz->tileyoff >= siz->height) { +- jas_eprintf(""all tiles are outside the image area\n""); +- return -1; ++ if (!siz->tilewidth || !siz->tileheight) { ++ jas_eprintf(""tile cannot have zero area\n""); ++ goto error; ++ } ++ if (!siz->numcomps || siz->numcomps > 16384) { ++ jas_eprintf(""number of components not in permissible range\n""); ++ goto error; + } ++ if (siz->xoff >= siz->width) { ++ jas_eprintf(""XOsiz not in permissible range\n""); ++ goto error; ++ } ++ if (siz->yoff >= siz->height) { ++ jas_eprintf(""YOsiz not in permissible range\n""); ++ goto error; ++ } ++ if (siz->tilexoff > siz->xoff || siz->tilexoff + siz->tilewidth <= siz->xoff) { ++ jas_eprintf(""XTOsiz not in permissible range\n""); ++ goto error; ++ } ++ if (siz->tileyoff > siz->yoff || siz->tileyoff + siz->tileheight <= siz->yoff) { ++ jas_eprintf(""YTOsiz not in permissible range\n""); ++ goto error; ++ } ++ + if (!(siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)))) { +- return -1; ++ goto error; + } + for (i = 0; i < siz->numcomps; ++i) { + if (jpc_getuint8(in, &tmp) || + jpc_getuint8(in, &siz->comps[i].hsamp) || + jpc_getuint8(in, &siz->comps[i].vsamp)) { +- jas_free(siz->comps); +- return -1; ++ goto error; + } + if (siz->comps[i].hsamp == 0 || siz->comps[i].hsamp > 255) { + jas_eprintf(""invalid XRsiz value %d\n"", siz->comps[i].hsamp); +- jas_free(siz->comps); +- return -1; ++ goto error; + } + if (siz->comps[i].vsamp == 0 || siz->comps[i].vsamp > 255) { + jas_eprintf(""invalid YRsiz value %d\n"", siz->comps[i].vsamp); +- jas_free(siz->comps); +- return -1; ++ goto error; + } + siz->comps[i].sgnd = (tmp >> 7) & 1; + siz->comps[i].prec = (tmp & 0x7f) + 1; + } + if (jas_stream_eof(in)) { +- jas_free(siz->comps); +- return -1; ++ goto error; + } + return 0; ++ ++error: ++ if (siz->comps) { ++ jas_free(siz->comps); ++ } ++ return -1; + } + + static int jpc_siz_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)",724,1055,2048 +5943,"static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, + struct bpf_insn *insn) +{ + struct bpf_reg_state *regs = cur_regs(env), *dst_reg, *src_reg; + struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; + u8 opcode = BPF_OP(insn->code); + int rc; + + dst_reg = ®s[insn->dst_reg]; + src_reg = NULL; + if (dst_reg->type != SCALAR_VALUE) + ptr_reg = dst_reg; + if (BPF_SRC(insn->code) == BPF_X) { + src_reg = ®s[insn->src_reg]; + if (src_reg->type != SCALAR_VALUE) { + if (dst_reg->type != SCALAR_VALUE) { + /* Combining two pointers by any ALU op yields + * an arbitrary scalar. + */ + if (!env->allow_ptr_leaks) { + verbose(env, ""R%d pointer %s pointer prohibited\n"", + insn->dst_reg, + bpf_alu_string[opcode >> 4]); + return -EACCES; + } + mark_reg_unknown(env, regs, insn->dst_reg); + return 0; + } else { + /* scalar += pointer + * This is legal, but we have to reverse our + * src/dest handling in computing the range + */ + rc = adjust_ptr_min_max_vals(env, insn, + src_reg, dst_reg); + if (rc == -EACCES && env->allow_ptr_leaks) { + /* scalar += unknown scalar */ + __mark_reg_unknown(&off_reg); + return adjust_scalar_min_max_vals( + env, insn, + dst_reg, off_reg); + } + return rc; + } + } else if (ptr_reg) { + /* pointer += scalar */ + rc = adjust_ptr_min_max_vals(env, insn, + dst_reg, src_reg); + if (rc == -EACCES && env->allow_ptr_leaks) { + /* unknown scalar += scalar */ + __mark_reg_unknown(dst_reg); + return adjust_scalar_min_max_vals( + env, insn, dst_reg, *src_reg); + } + return rc; + } + } else { + /* Pretend the src is a reg with a known value, since we only + * need to be able to read from this state. + */ + off_reg.type = SCALAR_VALUE; + __mark_reg_known(&off_reg, insn->imm); + src_reg = &off_reg; + if (ptr_reg) { /* pointer += K */ + rc = adjust_ptr_min_max_vals(env, insn, + ptr_reg, src_reg); + if (rc == -EACCES && env->allow_ptr_leaks) { + /* unknown scalar += K */ + __mark_reg_unknown(dst_reg); + return adjust_scalar_min_max_vals( + env, insn, dst_reg, off_reg); + } + return rc; + } + } + + /* Got here implies adding two SCALAR_VALUEs */ + if (WARN_ON_ONCE(ptr_reg)) { + print_verifier_state(env, env->cur_state); + verbose(env, ""verifier internal error: unexpected ptr_reg\n""); + return -EINVAL; + } + if (WARN_ON(!src_reg)) { + print_verifier_state(env, env->cur_state); + verbose(env, ""verifier internal error: no src_reg\n""); + return -EINVAL; + } + return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); +} +",0,"static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, + struct bpf_insn *insn) +{ + struct bpf_reg_state *regs = cur_regs(env), *dst_reg, *src_reg; + struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; + u8 opcode = BPF_OP(insn->code); + int rc; + + dst_reg = ®s[insn->dst_reg]; + src_reg = NULL; + if (dst_reg->type != SCALAR_VALUE) + ptr_reg = dst_reg; + if (BPF_SRC(insn->code) == BPF_X) { + src_reg = ®s[insn->src_reg]; + if (src_reg->type != SCALAR_VALUE) { + if (dst_reg->type != SCALAR_VALUE) { + /* Combining two pointers by any ALU op yields + * an arbitrary scalar. + */ + if (!env->allow_ptr_leaks) { + verbose(env, ""R%d pointer %s pointer prohibited\n"", + insn->dst_reg, + bpf_alu_string[opcode >> 4]); + return -EACCES; + } + mark_reg_unknown(env, regs, insn->dst_reg); + return 0; + } else { + /* scalar += pointer + * This is legal, but we have to reverse our + * src/dest handling in computing the range + */ + rc = adjust_ptr_min_max_vals(env, insn, + src_reg, dst_reg); + if (rc == -EACCES && env->allow_ptr_leaks) { + /* scalar += unknown scalar */ + __mark_reg_unknown(&off_reg); + return adjust_scalar_min_max_vals( + env, insn, + dst_reg, off_reg); + } + return rc; + } + } else if (ptr_reg) { + /* pointer += scalar */ + rc = adjust_ptr_min_max_vals(env, insn, + dst_reg, src_reg); + if (rc == -EACCES && env->allow_ptr_leaks) { + /* unknown scalar += scalar */ + __mark_reg_unknown(dst_reg); + return adjust_scalar_min_max_vals( + env, insn, dst_reg, *src_reg); + } + return rc; + } + } else { + /* Pretend the src is a reg with a known value, since we only + * need to be able to read from this state. + */ + off_reg.type = SCALAR_VALUE; + __mark_reg_known(&off_reg, insn->imm); + src_reg = &off_reg; + if (ptr_reg) { /* pointer += K */ + rc = adjust_ptr_min_max_vals(env, insn, + ptr_reg, src_reg); + if (rc == -EACCES && env->allow_ptr_leaks) { + /* unknown scalar += K */ + __mark_reg_unknown(dst_reg); + return adjust_scalar_min_max_vals( + env, insn, dst_reg, off_reg); + } + return rc; + } + } + + /* Got here implies adding two SCALAR_VALUEs */ + if (WARN_ON_ONCE(ptr_reg)) { + print_verifier_state(env, env->cur_state); + verbose(env, ""verifier internal error: unexpected ptr_reg\n""); + return -EINVAL; + } + if (WARN_ON(!src_reg)) { + print_verifier_state(env, env->cur_state); + verbose(env, ""verifier internal error: no src_reg\n""); + return -EINVAL; + } + return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); +} +","@@ -3827,6 +3827,7 @@ static int do_check(struct bpf_verifier_env *env) + return err; + + regs = cur_regs(env); ++ env->insn_aux_data[insn_idx].seen = true; + if (class == BPF_ALU || class == BPF_ALU64) { + err = check_alu_op(env, insn); + if (err) +@@ -4022,6 +4023,7 @@ static int do_check(struct bpf_verifier_env *env) + return err; + + insn_idx++; ++ env->insn_aux_data[insn_idx].seen = true; + } else { + verbose(env, ""invalid BPF_LD mode\n""); + return -EINVAL; +@@ -4204,6 +4206,7 @@ static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len, + u32 off, u32 cnt) + { + struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data; ++ int i; + + if (cnt == 1) + return 0; +@@ -4213,6 +4216,8 @@ static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len, + memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); + memcpy(new_data + off + cnt - 1, old_data + off, + sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); ++ for (i = off; i < off + cnt - 1; i++) ++ new_data[i].seen = true; + env->insn_aux_data = new_data; + vfree(old_data); + return 0; +@@ -4231,6 +4236,25 @@ static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 of + return new_prog; + } + ++/* The verifier does more data flow analysis than llvm and will not explore ++ * branches that are dead at run time. Malicious programs can have dead code ++ * too. Therefore replace all dead at-run-time code with nops. ++ */ ++static void sanitize_dead_code(struct bpf_verifier_env *env) ++{ ++ struct bpf_insn_aux_data *aux_data = env->insn_aux_data; ++ struct bpf_insn nop = BPF_MOV64_REG(BPF_REG_0, BPF_REG_0); ++ struct bpf_insn *insn = env->prog->insnsi; ++ const int insn_cnt = env->prog->len; ++ int i; ++ ++ for (i = 0; i < insn_cnt; i++) { ++ if (aux_data[i].seen) ++ continue; ++ memcpy(insn + i, &nop, sizeof(nop)); ++ } ++} ++ + /* convert load instructions that access fields of 'struct __sk_buff' + * into sequence of instructions that access fields of 'struct sk_buff' + */ +@@ -4557,6 +4581,9 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr) + while (!pop_stack(env, NULL, NULL)); + free_states(env); + ++ if (ret == 0) ++ sanitize_dead_code(env); ++ + if (ret == 0) + /* program is valid, convert *(u32*)(ctx + off) accesses */ + ret = convert_ctx_accesses(env);",771,1102,2048 +17197,"void handle_rc_metamsg_cmd (tBTA_AV_META_MSG *pmeta_msg) +{ + /* Parse the metamsg command and pass it on to BTL-IFS */ + UINT8 scratch_buf[512] = {0}; + tAVRC_COMMAND avrc_command = {0}; + tAVRC_STS status; + + BTIF_TRACE_EVENT(""+ %s"", __FUNCTION__); + + if (pmeta_msg->p_msg->hdr.opcode != AVRC_OP_VENDOR) + { + BTIF_TRACE_WARNING(""Invalid opcode: %x"", pmeta_msg->p_msg->hdr.opcode); + return; + } + if (pmeta_msg->len < 3) + { + BTIF_TRACE_WARNING(""Invalid length.Opcode: 0x%x, len: 0x%x"", pmeta_msg->p_msg->hdr.opcode, + pmeta_msg->len); + return; + } + + if (pmeta_msg->code >= AVRC_RSP_NOT_IMPL) + { +#if (AVRC_ADV_CTRL_INCLUDED == TRUE) +{ + rc_transaction_t *transaction=NULL; + transaction=get_transaction_by_lbl(pmeta_msg->label); + if(NULL!=transaction) + { + handle_rc_metamsg_rsp(pmeta_msg); + } + else + { + BTIF_TRACE_DEBUG(""%s:Discard vendor dependent rsp. code: %d label:%d."", + __FUNCTION__, pmeta_msg->code, pmeta_msg->label); + } + return; +} +#else +{ + BTIF_TRACE_DEBUG(""%s:Received vendor dependent rsp. code: %d len: %d. Not processing it."", + __FUNCTION__, pmeta_msg->code, pmeta_msg->len); + return; +} +#endif + } + + status=AVRC_ParsCommand(pmeta_msg->p_msg, &avrc_command, scratch_buf, sizeof(scratch_buf)); + BTIF_TRACE_DEBUG(""Received vendor command.code,PDU and label: %d, %d,%d"",pmeta_msg->code, + avrc_command.cmd.pdu, pmeta_msg->label); + + if (status != AVRC_STS_NO_ERROR) + { + /* return error */ + BTIF_TRACE_WARNING(""%s: Error in parsing received metamsg command. status: 0x%02x"", + __FUNCTION__, status); + send_reject_response(pmeta_msg->rc_handle, pmeta_msg->label, avrc_command.pdu, status); + } + else + { + /* if RegisterNotification, add it to our registered queue */ + + if (avrc_command.cmd.pdu == AVRC_PDU_REGISTER_NOTIFICATION) + { + UINT8 event_id = avrc_command.reg_notif.event_id; + BTIF_TRACE_EVENT(""%s:New register notification received.event_id:%s,label:0x%x,code:%x"", + __FUNCTION__,dump_rc_notification_event_id(event_id), pmeta_msg->label,pmeta_msg->code); + btif_rc_cb.rc_notif[event_id-1].bNotify = TRUE; + btif_rc_cb.rc_notif[event_id-1].label = pmeta_msg->label; + + if(event_id == AVRC_EVT_UIDS_CHANGE) + { + handle_uid_changed_notification(pmeta_msg, &avrc_command); + return; + } + + } + + BTIF_TRACE_EVENT(""%s: Passing received metamsg command to app. pdu: %s"", + __FUNCTION__, dump_rc_pdu(avrc_command.cmd.pdu)); + + /* Since handle_rc_metamsg_cmd() itself is called from + *btif context, no context switching is required. Invoke + * btif_rc_upstreams_evt directly from here. */ + btif_rc_upstreams_evt((uint16_t)avrc_command.cmd.pdu, &avrc_command, pmeta_msg->code, + pmeta_msg->label); + } +} +",0,"void handle_rc_metamsg_cmd (tBTA_AV_META_MSG *pmeta_msg) +{ + /* Parse the metamsg command and pass it on to BTL-IFS */ + UINT8 scratch_buf[512] = {0}; + tAVRC_COMMAND avrc_command = {0}; + tAVRC_STS status; + + BTIF_TRACE_EVENT(""+ %s"", __FUNCTION__); + + if (pmeta_msg->p_msg->hdr.opcode != AVRC_OP_VENDOR) + { + BTIF_TRACE_WARNING(""Invalid opcode: %x"", pmeta_msg->p_msg->hdr.opcode); + return; + } + if (pmeta_msg->len < 3) + { + BTIF_TRACE_WARNING(""Invalid length.Opcode: 0x%x, len: 0x%x"", pmeta_msg->p_msg->hdr.opcode, + pmeta_msg->len); + return; + } + + if (pmeta_msg->code >= AVRC_RSP_NOT_IMPL) + { +#if (AVRC_ADV_CTRL_INCLUDED == TRUE) +{ + rc_transaction_t *transaction=NULL; + transaction=get_transaction_by_lbl(pmeta_msg->label); + if(NULL!=transaction) + { + handle_rc_metamsg_rsp(pmeta_msg); + } + else + { + BTIF_TRACE_DEBUG(""%s:Discard vendor dependent rsp. code: %d label:%d."", + __FUNCTION__, pmeta_msg->code, pmeta_msg->label); + } + return; +} +#else +{ + BTIF_TRACE_DEBUG(""%s:Received vendor dependent rsp. code: %d len: %d. Not processing it."", + __FUNCTION__, pmeta_msg->code, pmeta_msg->len); + return; +} +#endif + } + + status=AVRC_ParsCommand(pmeta_msg->p_msg, &avrc_command, scratch_buf, sizeof(scratch_buf)); + BTIF_TRACE_DEBUG(""Received vendor command.code,PDU and label: %d, %d,%d"",pmeta_msg->code, + avrc_command.cmd.pdu, pmeta_msg->label); + + if (status != AVRC_STS_NO_ERROR) + { + /* return error */ + BTIF_TRACE_WARNING(""%s: Error in parsing received metamsg command. status: 0x%02x"", + __FUNCTION__, status); + send_reject_response(pmeta_msg->rc_handle, pmeta_msg->label, avrc_command.pdu, status); + } + else + { + /* if RegisterNotification, add it to our registered queue */ + + if (avrc_command.cmd.pdu == AVRC_PDU_REGISTER_NOTIFICATION) + { + UINT8 event_id = avrc_command.reg_notif.event_id; + BTIF_TRACE_EVENT(""%s:New register notification received.event_id:%s,label:0x%x,code:%x"", + __FUNCTION__,dump_rc_notification_event_id(event_id), pmeta_msg->label,pmeta_msg->code); + btif_rc_cb.rc_notif[event_id-1].bNotify = TRUE; + btif_rc_cb.rc_notif[event_id-1].label = pmeta_msg->label; + + if(event_id == AVRC_EVT_UIDS_CHANGE) + { + handle_uid_changed_notification(pmeta_msg, &avrc_command); + return; + } + + } + + BTIF_TRACE_EVENT(""%s: Passing received metamsg command to app. pdu: %s"", + __FUNCTION__, dump_rc_pdu(avrc_command.cmd.pdu)); + + /* Since handle_rc_metamsg_cmd() itself is called from + *btif context, no context switching is required. Invoke + * btif_rc_upstreams_evt directly from here. */ + btif_rc_upstreams_evt((uint16_t)avrc_command.cmd.pdu, &avrc_command, pmeta_msg->code, + pmeta_msg->label); + } +} +","@@ -24,6 +24,7 @@ + + * Description: Bluetooth AVRC implementation + * + *****************************************************************************/ ++#include + #include + #include + #include +@@ -213,7 +214,7 @@ + + event.code = code; + event.value = value; + +- return write(fd, &event, sizeof(event)); ++ return TEMP_FAILURE_RETRY(write(fd, &event, sizeof(event))); + } + + void send_key (int fd, uint16_t key, int pressed) +@@ -252,7 +253,7 @@ + + + for(x=0; x < MAX_UINPUT_PATHS; x++) + { +- fd = open(uinput_dev_path[x], O_RDWR); ++ fd = TEMP_FAILURE_RETRY(open(uinput_dev_path[x], O_RDWR)); + if (fd < 0) + continue; + break; +@@ -270,20 +271,20 @@ + + dev.id.product = 0x0000; + dev.id.version = 0x0000; + +- if (write(fd, &dev, sizeof(dev)) < 0) { ++ if (TEMP_FAILURE_RETRY(write(fd, &dev, sizeof(dev))) < 0) { + BTIF_TRACE_ERROR(""%s Unable to write device information"", __FUNCTION__); + close(fd); + return -1; + } + +- ioctl(fd, UI_SET_EVBIT, EV_KEY); +- ioctl(fd, UI_SET_EVBIT, EV_REL); +- ioctl(fd, UI_SET_EVBIT, EV_SYN); ++ TEMP_FAILURE_RETRY(ioctl(fd, UI_SET_EVBIT, EV_KEY)); ++ TEMP_FAILURE_RETRY(ioctl(fd, UI_SET_EVBIT, EV_REL)); ++ TEMP_FAILURE_RETRY(ioctl(fd, UI_SET_EVBIT, EV_SYN)); + + for (x = 0; key_map[x].name != NULL; x++) +- ioctl(fd, UI_SET_KEYBIT, key_map[x].mapped_id); ++ TEMP_FAILURE_RETRY(ioctl(fd, UI_SET_KEYBIT, key_map[x].mapped_id)); + +- if (ioctl(fd, UI_DEV_CREATE, NULL) < 0) { ++ if (TEMP_FAILURE_RETRY(ioctl(fd, UI_DEV_CREATE, NULL)) < 0) { + BTIF_TRACE_ERROR(""%s Unable to create uinput device"", __FUNCTION__); + close(fd); + return -1; +@@ -311,7 +312,7 @@ + + { + BTIF_TRACE_DEBUG(""%s"", __FUNCTION__); + if (uinput_fd > 0) { +- ioctl(uinput_fd, UI_DEV_DESTROY); ++ TEMP_FAILURE_RETRY(ioctl(uinput_fd, UI_DEV_DESTROY)); + + close(uinput_fd); + uinput_fd = -1; +",771,1102,2048 +17982,"sd2_parse_rsrc_fork (SF_PRIVATE *psf) +{ SD2_RSRC rsrc ; + int k, marker, error = 0 ; + + psf_use_rsrc (psf, SF_TRUE) ; + + memset (&rsrc, 0, sizeof (rsrc)) ; + + rsrc.rsrc_len = psf_get_filelen (psf) ; + psf_log_printf (psf, ""Resource length : %d (0x%04X)\n"", rsrc.rsrc_len, rsrc.rsrc_len) ; + + if (rsrc.rsrc_len > SIGNED_SIZEOF (psf->header)) + { rsrc.rsrc_data = calloc (1, rsrc.rsrc_len) ; + rsrc.need_to_free_rsrc_data = SF_TRUE ; + } + else + { + rsrc.rsrc_data = psf->header ; + rsrc.need_to_free_rsrc_data = SF_FALSE ; + } ; + + /* Read in the whole lot. */ + psf_fread (rsrc.rsrc_data, rsrc.rsrc_len, 1, psf) ; + + /* Reset the header storage because we have changed to the rsrcdes. */ + psf->headindex = psf->headend = rsrc.rsrc_len ; + + rsrc.data_offset = read_rsrc_int (&rsrc, 0) ; + rsrc.map_offset = read_rsrc_int (&rsrc, 4) ; + rsrc.data_length = read_rsrc_int (&rsrc, 8) ; + rsrc.map_length = read_rsrc_int (&rsrc, 12) ; + + if (rsrc.data_offset == 0x51607 && rsrc.map_offset == 0x20000) + { psf_log_printf (psf, ""Trying offset of 0x52 bytes.\n"") ; + rsrc.data_offset = read_rsrc_int (&rsrc, 0x52 + 0) + 0x52 ; + rsrc.map_offset = read_rsrc_int (&rsrc, 0x52 + 4) + 0x52 ; + rsrc.data_length = read_rsrc_int (&rsrc, 0x52 + 8) ; + rsrc.map_length = read_rsrc_int (&rsrc, 0x52 + 12) ; + } ; + + psf_log_printf (psf, "" data offset : 0x%04X\n map offset : 0x%04X\n"" + "" data length : 0x%04X\n map length : 0x%04X\n"", + rsrc.data_offset, rsrc.map_offset, rsrc.data_length, rsrc.map_length) ; + + if (rsrc.data_offset > rsrc.rsrc_len) + { psf_log_printf (psf, ""Error : rsrc.data_offset (%d, 0x%x) > len\n"", rsrc.data_offset, rsrc.data_offset) ; + error = SFE_SD2_BAD_DATA_OFFSET ; + goto parse_rsrc_fork_cleanup ; + } ; + + if (rsrc.map_offset > rsrc.rsrc_len) + { psf_log_printf (psf, ""Error : rsrc.map_offset > len\n"") ; + error = SFE_SD2_BAD_MAP_OFFSET ; + goto parse_rsrc_fork_cleanup ; + } ; + + if (rsrc.data_length > rsrc.rsrc_len) + { psf_log_printf (psf, ""Error : rsrc.data_length > len\n"") ; + error = SFE_SD2_BAD_DATA_LENGTH ; + goto parse_rsrc_fork_cleanup ; + } ; + + if (rsrc.map_length > rsrc.rsrc_len) + { psf_log_printf (psf, ""Error : rsrc.map_length > len\n"") ; + error = SFE_SD2_BAD_MAP_LENGTH ; + goto parse_rsrc_fork_cleanup ; + } ; + + if (rsrc.data_offset + rsrc.data_length != rsrc.map_offset || rsrc.map_offset + rsrc.map_length != rsrc.rsrc_len) + { psf_log_printf (psf, ""Error : This does not look like a MacOSX resource fork.\n"") ; + error = SFE_SD2_BAD_RSRC ; + goto parse_rsrc_fork_cleanup ; + } ; + + if (rsrc.map_offset + 28 >= rsrc.rsrc_len) + { psf_log_printf (psf, ""Bad map offset (%d + 28 > %d).\n"", rsrc.map_offset, rsrc.rsrc_len) ; + error = SFE_SD2_BAD_RSRC ; + goto parse_rsrc_fork_cleanup ; + } ; + + rsrc.string_offset = rsrc.map_offset + read_rsrc_short (&rsrc, rsrc.map_offset + 26) ; + if (rsrc.string_offset > rsrc.rsrc_len) + { psf_log_printf (psf, ""Bad string offset (%d).\n"", rsrc.string_offset) ; + error = SFE_SD2_BAD_RSRC ; + goto parse_rsrc_fork_cleanup ; + } ; + + rsrc.type_offset = rsrc.map_offset + 30 ; + + rsrc.type_count = read_rsrc_short (&rsrc, rsrc.map_offset + 28) + 1 ; + if (rsrc.type_count < 1) + { psf_log_printf (psf, ""Bad type count.\n"") ; + error = SFE_SD2_BAD_RSRC ; + goto parse_rsrc_fork_cleanup ; + } ; + + rsrc.item_offset = rsrc.type_offset + rsrc.type_count * 8 ; + if (rsrc.item_offset < 0 || rsrc.item_offset > rsrc.rsrc_len) + { psf_log_printf (psf, ""Bad item offset (%d).\n"", rsrc.item_offset) ; + error = SFE_SD2_BAD_RSRC ; + goto parse_rsrc_fork_cleanup ; + } ; + + rsrc.str_index = -1 ; + for (k = 0 ; k < rsrc.type_count ; k ++) + { marker = read_rsrc_marker (&rsrc, rsrc.type_offset + k * 8) ; + + if (marker == STR_MARKER) + { rsrc.str_index = k ; + rsrc.str_count = read_rsrc_short (&rsrc, rsrc.type_offset + k * 8 + 4) + 1 ; + error = parse_str_rsrc (psf, &rsrc) ; + goto parse_rsrc_fork_cleanup ; + } ; + } ; + + psf_log_printf (psf, ""No 'STR ' resource.\n"") ; + error = SFE_SD2_BAD_RSRC ; + +parse_rsrc_fork_cleanup : + + psf_use_rsrc (psf, SF_FALSE) ; + + if (rsrc.need_to_free_rsrc_data) + free (rsrc.rsrc_data) ; + + return error ; +} /* sd2_parse_rsrc_fork */ +",1,"sd2_parse_rsrc_fork (SF_PRIVATE *psf) +{ SD2_RSRC rsrc ; + int k, marker, error = 0 ; + + psf_use_rsrc (psf, SF_TRUE) ; + + memset (&rsrc, 0, sizeof (rsrc)) ; + + rsrc.rsrc_len = psf_get_filelen (psf) ; + psf_log_printf (psf, ""Resource length : %d (0x%04X)\n"", rsrc.rsrc_len, rsrc.rsrc_len) ; + + if (rsrc.rsrc_len > SIGNED_SIZEOF (psf->header)) + { rsrc.rsrc_data = calloc (1, rsrc.rsrc_len) ; + rsrc.need_to_free_rsrc_data = SF_TRUE ; + } + else + { + rsrc.rsrc_data = psf->header ; + rsrc.need_to_free_rsrc_data = SF_FALSE ; + } ; + + /* Read in the whole lot. */ + psf_fread (rsrc.rsrc_data, rsrc.rsrc_len, 1, psf) ; + + /* Reset the header storage because we have changed to the rsrcdes. */ + psf->headindex = psf->headend = rsrc.rsrc_len ; + + rsrc.data_offset = read_rsrc_int (&rsrc, 0) ; + rsrc.map_offset = read_rsrc_int (&rsrc, 4) ; + rsrc.data_length = read_rsrc_int (&rsrc, 8) ; + rsrc.map_length = read_rsrc_int (&rsrc, 12) ; + + if (rsrc.data_offset == 0x51607 && rsrc.map_offset == 0x20000) + { psf_log_printf (psf, ""Trying offset of 0x52 bytes.\n"") ; + rsrc.data_offset = read_rsrc_int (&rsrc, 0x52 + 0) + 0x52 ; + rsrc.map_offset = read_rsrc_int (&rsrc, 0x52 + 4) + 0x52 ; + rsrc.data_length = read_rsrc_int (&rsrc, 0x52 + 8) ; + rsrc.map_length = read_rsrc_int (&rsrc, 0x52 + 12) ; + } ; + + psf_log_printf (psf, "" data offset : 0x%04X\n map offset : 0x%04X\n"" + "" data length : 0x%04X\n map length : 0x%04X\n"", + rsrc.data_offset, rsrc.map_offset, rsrc.data_length, rsrc.map_length) ; + + if (rsrc.data_offset > rsrc.rsrc_len) + { psf_log_printf (psf, ""Error : rsrc.data_offset (%d, 0x%x) > len\n"", rsrc.data_offset, rsrc.data_offset) ; + error = SFE_SD2_BAD_DATA_OFFSET ; + goto parse_rsrc_fork_cleanup ; + } ; + + if (rsrc.map_offset > rsrc.rsrc_len) + { psf_log_printf (psf, ""Error : rsrc.map_offset > len\n"") ; + error = SFE_SD2_BAD_MAP_OFFSET ; + goto parse_rsrc_fork_cleanup ; + } ; + + if (rsrc.data_length > rsrc.rsrc_len) + { psf_log_printf (psf, ""Error : rsrc.data_length > len\n"") ; + error = SFE_SD2_BAD_DATA_LENGTH ; + goto parse_rsrc_fork_cleanup ; + } ; + + if (rsrc.map_length > rsrc.rsrc_len) + { psf_log_printf (psf, ""Error : rsrc.map_length > len\n"") ; + error = SFE_SD2_BAD_MAP_LENGTH ; + goto parse_rsrc_fork_cleanup ; + } ; + + if (rsrc.data_offset + rsrc.data_length != rsrc.map_offset || rsrc.map_offset + rsrc.map_length != rsrc.rsrc_len) + { psf_log_printf (psf, ""Error : This does not look like a MacOSX resource fork.\n"") ; + error = SFE_SD2_BAD_RSRC ; + goto parse_rsrc_fork_cleanup ; + } ; + + if (rsrc.map_offset + 28 >= rsrc.rsrc_len) + { psf_log_printf (psf, ""Bad map offset (%d + 28 > %d).\n"", rsrc.map_offset, rsrc.rsrc_len) ; + error = SFE_SD2_BAD_RSRC ; + goto parse_rsrc_fork_cleanup ; + } ; + + rsrc.string_offset = rsrc.map_offset + read_rsrc_short (&rsrc, rsrc.map_offset + 26) ; + if (rsrc.string_offset > rsrc.rsrc_len) + { psf_log_printf (psf, ""Bad string offset (%d).\n"", rsrc.string_offset) ; + error = SFE_SD2_BAD_RSRC ; + goto parse_rsrc_fork_cleanup ; + } ; + + rsrc.type_offset = rsrc.map_offset + 30 ; + + if (rsrc.map_offset + 28 > rsrc.rsrc_len) + { psf_log_printf (psf, ""Bad map offset.\n"") ; + goto parse_rsrc_fork_cleanup ; + } ; + + rsrc.type_count = read_rsrc_short (&rsrc, rsrc.map_offset + 28) + 1 ; + if (rsrc.type_count < 1) + { psf_log_printf (psf, ""Bad type count.\n"") ; + error = SFE_SD2_BAD_RSRC ; + goto parse_rsrc_fork_cleanup ; + } ; + + rsrc.item_offset = rsrc.type_offset + rsrc.type_count * 8 ; + if (rsrc.item_offset < 0 || rsrc.item_offset > rsrc.rsrc_len) + { psf_log_printf (psf, ""Bad item offset (%d).\n"", rsrc.item_offset) ; + error = SFE_SD2_BAD_RSRC ; + goto parse_rsrc_fork_cleanup ; + } ; + + rsrc.str_index = -1 ; + for (k = 0 ; k < rsrc.type_count ; k ++) + { if (rsrc.type_offset + k * 8 > rsrc.rsrc_len) + { psf_log_printf (psf, ""Bad rsrc marker.\n"") ; + goto parse_rsrc_fork_cleanup ; + } ; + + marker = read_rsrc_marker (&rsrc, rsrc.type_offset + k * 8) ; + + if (marker == STR_MARKER) + { rsrc.str_index = k ; + rsrc.str_count = read_rsrc_short (&rsrc, rsrc.type_offset + k * 8 + 4) + 1 ; + error = parse_str_rsrc (psf, &rsrc) ; + goto parse_rsrc_fork_cleanup ; + } ; + } ; + + psf_log_printf (psf, ""No 'STR ' resource.\n"") ; + error = SFE_SD2_BAD_RSRC ; + +parse_rsrc_fork_cleanup : + + psf_use_rsrc (psf, SF_FALSE) ; + + if (rsrc.need_to_free_rsrc_data) + free (rsrc.rsrc_data) ; + + return error ; +} /* sd2_parse_rsrc_fork */ +","@@ -517,6 +517,11 @@ sd2_parse_rsrc_fork (SF_PRIVATE *psf) + + rsrc.type_offset = rsrc.map_offset + 30 ; + ++ if (rsrc.map_offset + 28 > rsrc.rsrc_len) ++ { psf_log_printf (psf, ""Bad map offset.\n"") ; ++ goto parse_rsrc_fork_cleanup ; ++ } ; ++ + rsrc.type_count = read_rsrc_short (&rsrc, rsrc.map_offset + 28) + 1 ; + if (rsrc.type_count < 1) + { psf_log_printf (psf, ""Bad type count.\n"") ; +@@ -533,7 +538,12 @@ sd2_parse_rsrc_fork (SF_PRIVATE *psf) + + rsrc.str_index = -1 ; + for (k = 0 ; k < rsrc.type_count ; k ++) +- { marker = read_rsrc_marker (&rsrc, rsrc.type_offset + k * 8) ; ++ { if (rsrc.type_offset + k * 8 > rsrc.rsrc_len) ++ { psf_log_printf (psf, ""Bad rsrc marker.\n"") ; ++ goto parse_rsrc_fork_cleanup ; ++ } ; ++ ++ marker = read_rsrc_marker (&rsrc, rsrc.type_offset + k * 8) ; + + if (marker == STR_MARKER) + { rsrc.str_index = k ;",1502,1833,2048 +7034,"static int jpc_pi_nextrpcl(register jpc_pi_t *pi) +{ + int rlvlno; + jpc_pirlvl_t *pirlvl; + jpc_pchg_t *pchg; + int prchind; + int prcvind; + int *prclyrno; + int compno; + jpc_picomp_t *picomp; + int xstep; + int ystep; + uint_fast32_t r; + uint_fast32_t rpx; + uint_fast32_t rpy; + uint_fast32_t trx0; + uint_fast32_t try0; + + pchg = pi->pchg; + if (!pi->prgvolfirst) { + goto skip; + } else { + pi->xstep = 0; + pi->ystep = 0; + for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; + ++compno, ++picomp) { + for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < + picomp->numrlvls; ++rlvlno, ++pirlvl) { + xstep = picomp->hsamp * (1 << (pirlvl->prcwidthexpn + + picomp->numrlvls - rlvlno - 1)); + ystep = picomp->vsamp * (1 << (pirlvl->prcheightexpn + + picomp->numrlvls - rlvlno - 1)); + pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); + pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); + } + } + pi->prgvolfirst = 0; + } + + for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend && + pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) { + for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += + pi->ystep - (pi->y % pi->ystep)) { + for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += + pi->xstep - (pi->x % pi->xstep)) { + for (pi->compno = pchg->compnostart, + pi->picomp = &pi->picomps[pi->compno]; + pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < + pi->numcomps; ++pi->compno, ++pi->picomp) { + if (pi->rlvlno >= pi->picomp->numrlvls) { + continue; + } + pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; + if (pi->pirlvl->numprcs == 0) { + continue; + } + r = pi->picomp->numrlvls - 1 - pi->rlvlno; + rpx = r + pi->pirlvl->prcwidthexpn; + rpy = r + pi->pirlvl->prcheightexpn; + trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); + try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); + if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) + || !(pi->x % (1 << rpx))) && + ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) + || !(pi->y % (1 << rpy)))) { + prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp + << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, + pi->pirlvl->prcwidthexpn); + prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp + << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, + pi->pirlvl->prcheightexpn); + pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; + + assert(pi->prcno < pi->pirlvl->numprcs); + for (pi->lyrno = 0; pi->lyrno < + pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { + prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; + if (pi->lyrno >= *prclyrno) { + ++(*prclyrno); + return 0; + } +skip: + ; + } + } + } + } + } + } + return 1; +} +",0,"static int jpc_pi_nextrpcl(register jpc_pi_t *pi) +{ + int rlvlno; + jpc_pirlvl_t *pirlvl; + jpc_pchg_t *pchg; + int prchind; + int prcvind; + int *prclyrno; + int compno; + jpc_picomp_t *picomp; + int xstep; + int ystep; + uint_fast32_t r; + uint_fast32_t rpx; + uint_fast32_t rpy; + uint_fast32_t trx0; + uint_fast32_t try0; + + pchg = pi->pchg; + if (!pi->prgvolfirst) { + goto skip; + } else { + pi->xstep = 0; + pi->ystep = 0; + for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; + ++compno, ++picomp) { + for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < + picomp->numrlvls; ++rlvlno, ++pirlvl) { + xstep = picomp->hsamp * (1 << (pirlvl->prcwidthexpn + + picomp->numrlvls - rlvlno - 1)); + ystep = picomp->vsamp * (1 << (pirlvl->prcheightexpn + + picomp->numrlvls - rlvlno - 1)); + pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); + pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); + } + } + pi->prgvolfirst = 0; + } + + for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend && + pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) { + for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += + pi->ystep - (pi->y % pi->ystep)) { + for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += + pi->xstep - (pi->x % pi->xstep)) { + for (pi->compno = pchg->compnostart, + pi->picomp = &pi->picomps[pi->compno]; + pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < + pi->numcomps; ++pi->compno, ++pi->picomp) { + if (pi->rlvlno >= pi->picomp->numrlvls) { + continue; + } + pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; + if (pi->pirlvl->numprcs == 0) { + continue; + } + r = pi->picomp->numrlvls - 1 - pi->rlvlno; + rpx = r + pi->pirlvl->prcwidthexpn; + rpy = r + pi->pirlvl->prcheightexpn; + trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); + try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); + if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) + || !(pi->x % (1 << rpx))) && + ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) + || !(pi->y % (1 << rpy)))) { + prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp + << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, + pi->pirlvl->prcwidthexpn); + prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp + << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, + pi->pirlvl->prcheightexpn); + pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; + + assert(pi->prcno < pi->pirlvl->numprcs); + for (pi->lyrno = 0; pi->lyrno < + pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { + prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; + if (pi->lyrno >= *prclyrno) { + ++(*prclyrno); + return 0; + } +skip: + ; + } + } + } + } + } + } + return 1; +} +","@@ -432,18 +432,18 @@ static int jpc_pi_nextcprl(register jpc_pi_t *pi) + &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno, + ++pi->picomp) { + pirlvl = pi->picomp->pirlvls; +- pi->xstep = pi->picomp->hsamp * (1 << (pirlvl->prcwidthexpn + +- pi->picomp->numrlvls - 1)); +- pi->ystep = pi->picomp->vsamp * (1 << (pirlvl->prcheightexpn + +- pi->picomp->numrlvls - 1)); ++ pi->xstep = pi->picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << ++ (pirlvl->prcwidthexpn + pi->picomp->numrlvls - 1)); ++ pi->ystep = pi->picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << ++ (pirlvl->prcheightexpn + pi->picomp->numrlvls - 1)); + for (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1]; + rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) { +- pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp * (1 << +- (pirlvl->prcwidthexpn + pi->picomp->numrlvls - +- rlvlno - 1))); +- pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp * (1 << +- (pirlvl->prcheightexpn + pi->picomp->numrlvls - +- rlvlno - 1))); ++ pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp * ++ (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn + ++ pi->picomp->numrlvls - rlvlno - 1))); ++ pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp * ++ (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn + ++ pi->picomp->numrlvls - rlvlno - 1))); + } + for (pi->y = pi->ystart; pi->y < pi->yend; + pi->y += pi->ystep - (pi->y % pi->ystep)) {",1207,1538,2048 +7198,"pubkey_prepare(Authctxt *authctxt) +{ + struct identity *id, *id2, *tmp; + struct idlist agent, files, *preferred; + struct sshkey *key; + int agent_fd = -1, i, r, found; + size_t j; + struct ssh_identitylist *idlist; + + TAILQ_INIT(&agent); /* keys from the agent */ + TAILQ_INIT(&files); /* keys from the config file */ + preferred = &authctxt->keys; + TAILQ_INIT(preferred); /* preferred order of keys */ + + /* list of keys stored in the filesystem and PKCS#11 */ + for (i = 0; i < options.num_identity_files; i++) { + key = options.identity_keys[i]; + if (key && key->type == KEY_RSA1) + continue; + if (key && key->cert && key->cert->type != SSH2_CERT_TYPE_USER) + continue; + options.identity_keys[i] = NULL; + id = xcalloc(1, sizeof(*id)); + id->agent_fd = -1; + id->key = key; + id->filename = xstrdup(options.identity_files[i]); + id->userprovided = options.identity_file_userprovided[i]; + TAILQ_INSERT_TAIL(&files, id, next); + } + /* list of certificates specified by user */ + for (i = 0; i < options.num_certificate_files; i++) { + key = options.certificates[i]; + if (!key_is_cert(key) || key->cert == NULL || + key->cert->type != SSH2_CERT_TYPE_USER) + continue; + id = xcalloc(1, sizeof(*id)); + id->agent_fd = -1; + id->key = key; + id->filename = xstrdup(options.certificate_files[i]); + id->userprovided = options.certificate_file_userprovided[i]; + TAILQ_INSERT_TAIL(preferred, id, next); + } + /* list of keys supported by the agent */ + if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) { + if (r != SSH_ERR_AGENT_NOT_PRESENT) + debug(""%s: ssh_get_authentication_socket: %s"", + __func__, ssh_err(r)); + } else if ((r = ssh_fetch_identitylist(agent_fd, 2, &idlist)) != 0) { + if (r != SSH_ERR_AGENT_NO_IDENTITIES) + debug(""%s: ssh_fetch_identitylist: %s"", + __func__, ssh_err(r)); + close(agent_fd); + } else { + for (j = 0; j < idlist->nkeys; j++) { + found = 0; + TAILQ_FOREACH(id, &files, next) { + /* + * agent keys from the config file are + * preferred + */ + if (sshkey_equal(idlist->keys[j], id->key)) { + TAILQ_REMOVE(&files, id, next); + TAILQ_INSERT_TAIL(preferred, id, next); + id->agent_fd = agent_fd; + found = 1; + break; + } + } + if (!found && !options.identities_only) { + id = xcalloc(1, sizeof(*id)); + /* XXX ""steals"" key/comment from idlist */ + id->key = idlist->keys[j]; + id->filename = idlist->comments[j]; + idlist->keys[j] = NULL; + idlist->comments[j] = NULL; + id->agent_fd = agent_fd; + TAILQ_INSERT_TAIL(&agent, id, next); + } + } + ssh_free_identitylist(idlist); + /* append remaining agent keys */ + for (id = TAILQ_FIRST(&agent); id; id = TAILQ_FIRST(&agent)) { + TAILQ_REMOVE(&agent, id, next); + TAILQ_INSERT_TAIL(preferred, id, next); + } + authctxt->agent_fd = agent_fd; + } + /* Prefer PKCS11 keys that are explicitly listed */ + TAILQ_FOREACH_SAFE(id, &files, next, tmp) { + if (id->key == NULL || (id->key->flags & SSHKEY_FLAG_EXT) == 0) + continue; + found = 0; + TAILQ_FOREACH(id2, &files, next) { + if (id2->key == NULL || + (id2->key->flags & SSHKEY_FLAG_EXT) == 0) + continue; + if (sshkey_equal(id->key, id2->key)) { + TAILQ_REMOVE(&files, id, next); + TAILQ_INSERT_TAIL(preferred, id, next); + found = 1; + break; + } + } + /* If IdentitiesOnly set and key not found then don't use it */ + if (!found && options.identities_only) { + TAILQ_REMOVE(&files, id, next); + explicit_bzero(id, sizeof(*id)); + free(id); + } + } + /* append remaining keys from the config file */ + for (id = TAILQ_FIRST(&files); id; id = TAILQ_FIRST(&files)) { + TAILQ_REMOVE(&files, id, next); + TAILQ_INSERT_TAIL(preferred, id, next); + } + /* finally, filter by PubkeyAcceptedKeyTypes */ + TAILQ_FOREACH_SAFE(id, preferred, next, id2) { + if (id->key != NULL && + match_pattern_list(sshkey_ssh_name(id->key), + options.pubkey_key_types, 0) != 1) { + debug(""Skipping %s key %s - "" + ""not in PubkeyAcceptedKeyTypes"", + sshkey_ssh_name(id->key), id->filename); + TAILQ_REMOVE(preferred, id, next); + sshkey_free(id->key); + free(id->filename); + memset(id, 0, sizeof(*id)); + continue; + } + debug2(""key: %s (%p)%s%s"", id->filename, id->key, + id->userprovided ? "", explicit"" : """", + id->agent_fd != -1 ? "", agent"" : """"); + } +} +",0,"pubkey_prepare(Authctxt *authctxt) +{ + struct identity *id, *id2, *tmp; + struct idlist agent, files, *preferred; + struct sshkey *key; + int agent_fd = -1, i, r, found; + size_t j; + struct ssh_identitylist *idlist; + + TAILQ_INIT(&agent); /* keys from the agent */ + TAILQ_INIT(&files); /* keys from the config file */ + preferred = &authctxt->keys; + TAILQ_INIT(preferred); /* preferred order of keys */ + + /* list of keys stored in the filesystem and PKCS#11 */ + for (i = 0; i < options.num_identity_files; i++) { + key = options.identity_keys[i]; + if (key && key->type == KEY_RSA1) + continue; + if (key && key->cert && key->cert->type != SSH2_CERT_TYPE_USER) + continue; + options.identity_keys[i] = NULL; + id = xcalloc(1, sizeof(*id)); + id->agent_fd = -1; + id->key = key; + id->filename = xstrdup(options.identity_files[i]); + id->userprovided = options.identity_file_userprovided[i]; + TAILQ_INSERT_TAIL(&files, id, next); + } + /* list of certificates specified by user */ + for (i = 0; i < options.num_certificate_files; i++) { + key = options.certificates[i]; + if (!key_is_cert(key) || key->cert == NULL || + key->cert->type != SSH2_CERT_TYPE_USER) + continue; + id = xcalloc(1, sizeof(*id)); + id->agent_fd = -1; + id->key = key; + id->filename = xstrdup(options.certificate_files[i]); + id->userprovided = options.certificate_file_userprovided[i]; + TAILQ_INSERT_TAIL(preferred, id, next); + } + /* list of keys supported by the agent */ + if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) { + if (r != SSH_ERR_AGENT_NOT_PRESENT) + debug(""%s: ssh_get_authentication_socket: %s"", + __func__, ssh_err(r)); + } else if ((r = ssh_fetch_identitylist(agent_fd, 2, &idlist)) != 0) { + if (r != SSH_ERR_AGENT_NO_IDENTITIES) + debug(""%s: ssh_fetch_identitylist: %s"", + __func__, ssh_err(r)); + close(agent_fd); + } else { + for (j = 0; j < idlist->nkeys; j++) { + found = 0; + TAILQ_FOREACH(id, &files, next) { + /* + * agent keys from the config file are + * preferred + */ + if (sshkey_equal(idlist->keys[j], id->key)) { + TAILQ_REMOVE(&files, id, next); + TAILQ_INSERT_TAIL(preferred, id, next); + id->agent_fd = agent_fd; + found = 1; + break; + } + } + if (!found && !options.identities_only) { + id = xcalloc(1, sizeof(*id)); + /* XXX ""steals"" key/comment from idlist */ + id->key = idlist->keys[j]; + id->filename = idlist->comments[j]; + idlist->keys[j] = NULL; + idlist->comments[j] = NULL; + id->agent_fd = agent_fd; + TAILQ_INSERT_TAIL(&agent, id, next); + } + } + ssh_free_identitylist(idlist); + /* append remaining agent keys */ + for (id = TAILQ_FIRST(&agent); id; id = TAILQ_FIRST(&agent)) { + TAILQ_REMOVE(&agent, id, next); + TAILQ_INSERT_TAIL(preferred, id, next); + } + authctxt->agent_fd = agent_fd; + } + /* Prefer PKCS11 keys that are explicitly listed */ + TAILQ_FOREACH_SAFE(id, &files, next, tmp) { + if (id->key == NULL || (id->key->flags & SSHKEY_FLAG_EXT) == 0) + continue; + found = 0; + TAILQ_FOREACH(id2, &files, next) { + if (id2->key == NULL || + (id2->key->flags & SSHKEY_FLAG_EXT) == 0) + continue; + if (sshkey_equal(id->key, id2->key)) { + TAILQ_REMOVE(&files, id, next); + TAILQ_INSERT_TAIL(preferred, id, next); + found = 1; + break; + } + } + /* If IdentitiesOnly set and key not found then don't use it */ + if (!found && options.identities_only) { + TAILQ_REMOVE(&files, id, next); + explicit_bzero(id, sizeof(*id)); + free(id); + } + } + /* append remaining keys from the config file */ + for (id = TAILQ_FIRST(&files); id; id = TAILQ_FIRST(&files)) { + TAILQ_REMOVE(&files, id, next); + TAILQ_INSERT_TAIL(preferred, id, next); + } + /* finally, filter by PubkeyAcceptedKeyTypes */ + TAILQ_FOREACH_SAFE(id, preferred, next, id2) { + if (id->key != NULL && + match_pattern_list(sshkey_ssh_name(id->key), + options.pubkey_key_types, 0) != 1) { + debug(""Skipping %s key %s - "" + ""not in PubkeyAcceptedKeyTypes"", + sshkey_ssh_name(id->key), id->filename); + TAILQ_REMOVE(preferred, id, next); + sshkey_free(id->key); + free(id->filename); + memset(id, 0, sizeof(*id)); + continue; + } + debug2(""key: %s (%p)%s%s"", id->filename, id->key, + id->userprovided ? "", explicit"" : """", + id->agent_fd != -1 ? "", agent"" : """"); + } +} +","@@ -1,4 +1,4 @@ +-/* $OpenBSD: sshconnect2.c,v 1.248 2016/09/22 02:29:57 dtucker Exp $ */ ++/* $OpenBSD: sshconnect2.c,v 1.249 2016/09/28 16:33:07 djm Exp $ */ + /* + * Copyright (c) 2000 Markus Friedl. All rights reserved. + * Copyright (c) 2008 Damien Miller. All rights reserved. +@@ -168,7 +168,7 @@ ssh_kex2(char *host, struct sockaddr *hostaddr, u_short port) + compat_cipher_proposal(options.ciphers); + myproposal[PROPOSAL_COMP_ALGS_CTOS] = + myproposal[PROPOSAL_COMP_ALGS_STOC] = options.compression ? +- ""zlib@openssh.com,zlib,none"" : ""none,zlib@openssh.com,zlib""; ++ ""zlib@openssh.com,none"" : ""none,zlib@openssh.com""; + myproposal[PROPOSAL_MAC_ALGS_CTOS] = + myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs; + if (options.hostkeyalgorithms != NULL) {",1332,1663,2048 +4949,"brcmf_set_key_mgmt(struct net_device *ndev, struct cfg80211_connect_params *sme) +{ + struct brcmf_if *ifp = netdev_priv(ndev); + s32 val; + s32 err; + const struct brcmf_tlv *rsn_ie; + const u8 *ie; + u32 ie_len; + u32 offset; + u16 rsn_cap; + u32 mfp; + u16 count; + + if (!sme->crypto.n_akm_suites) + return 0; + + err = brcmf_fil_bsscfg_int_get(netdev_priv(ndev), ""wpa_auth"", &val); + if (err) { + brcmf_err(""could not get wpa_auth (%d)\n"", err); + return err; + } + if (val & (WPA_AUTH_PSK | WPA_AUTH_UNSPECIFIED)) { + switch (sme->crypto.akm_suites[0]) { + case WLAN_AKM_SUITE_8021X: + val = WPA_AUTH_UNSPECIFIED; + break; + case WLAN_AKM_SUITE_PSK: + val = WPA_AUTH_PSK; + break; + default: + brcmf_err(""invalid cipher group (%d)\n"", + sme->crypto.cipher_group); + return -EINVAL; + } + } else if (val & (WPA2_AUTH_PSK | WPA2_AUTH_UNSPECIFIED)) { + switch (sme->crypto.akm_suites[0]) { + case WLAN_AKM_SUITE_8021X: + val = WPA2_AUTH_UNSPECIFIED; + break; + case WLAN_AKM_SUITE_8021X_SHA256: + val = WPA2_AUTH_1X_SHA256; + break; + case WLAN_AKM_SUITE_PSK_SHA256: + val = WPA2_AUTH_PSK_SHA256; + break; + case WLAN_AKM_SUITE_PSK: + val = WPA2_AUTH_PSK; + break; + default: + brcmf_err(""invalid cipher group (%d)\n"", + sme->crypto.cipher_group); + return -EINVAL; + } + } + + if (!brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MFP)) + goto skip_mfp_config; + /* The MFP mode (1 or 2) needs to be determined, parse IEs. The + * IE will not be verified, just a quick search for MFP config + */ + rsn_ie = brcmf_parse_tlvs((const u8 *)sme->ie, sme->ie_len, + WLAN_EID_RSN); + if (!rsn_ie) + goto skip_mfp_config; + ie = (const u8 *)rsn_ie; + ie_len = rsn_ie->len + TLV_HDR_LEN; + /* Skip unicast suite */ + offset = TLV_HDR_LEN + WPA_IE_VERSION_LEN + WPA_IE_MIN_OUI_LEN; + if (offset + WPA_IE_SUITE_COUNT_LEN >= ie_len) + goto skip_mfp_config; + /* Skip multicast suite */ + count = ie[offset] + (ie[offset + 1] << 8); + offset += WPA_IE_SUITE_COUNT_LEN + (count * WPA_IE_MIN_OUI_LEN); + if (offset + WPA_IE_SUITE_COUNT_LEN >= ie_len) + goto skip_mfp_config; + /* Skip auth key management suite(s) */ + count = ie[offset] + (ie[offset + 1] << 8); + offset += WPA_IE_SUITE_COUNT_LEN + (count * WPA_IE_MIN_OUI_LEN); + if (offset + WPA_IE_SUITE_COUNT_LEN > ie_len) + goto skip_mfp_config; + /* Ready to read capabilities */ + mfp = BRCMF_MFP_NONE; + rsn_cap = ie[offset] + (ie[offset + 1] << 8); + if (rsn_cap & RSN_CAP_MFPR_MASK) + mfp = BRCMF_MFP_REQUIRED; + else if (rsn_cap & RSN_CAP_MFPC_MASK) + mfp = BRCMF_MFP_CAPABLE; + brcmf_fil_bsscfg_int_set(netdev_priv(ndev), ""mfp"", mfp); + +skip_mfp_config: + brcmf_dbg(CONN, ""setting wpa_auth to %d\n"", val); + err = brcmf_fil_bsscfg_int_set(netdev_priv(ndev), ""wpa_auth"", val); + if (err) { + brcmf_err(""could not set wpa_auth (%d)\n"", err); + return err; + } + + return err; +} +",0,"brcmf_set_key_mgmt(struct net_device *ndev, struct cfg80211_connect_params *sme) +{ + struct brcmf_if *ifp = netdev_priv(ndev); + s32 val; + s32 err; + const struct brcmf_tlv *rsn_ie; + const u8 *ie; + u32 ie_len; + u32 offset; + u16 rsn_cap; + u32 mfp; + u16 count; + + if (!sme->crypto.n_akm_suites) + return 0; + + err = brcmf_fil_bsscfg_int_get(netdev_priv(ndev), ""wpa_auth"", &val); + if (err) { + brcmf_err(""could not get wpa_auth (%d)\n"", err); + return err; + } + if (val & (WPA_AUTH_PSK | WPA_AUTH_UNSPECIFIED)) { + switch (sme->crypto.akm_suites[0]) { + case WLAN_AKM_SUITE_8021X: + val = WPA_AUTH_UNSPECIFIED; + break; + case WLAN_AKM_SUITE_PSK: + val = WPA_AUTH_PSK; + break; + default: + brcmf_err(""invalid cipher group (%d)\n"", + sme->crypto.cipher_group); + return -EINVAL; + } + } else if (val & (WPA2_AUTH_PSK | WPA2_AUTH_UNSPECIFIED)) { + switch (sme->crypto.akm_suites[0]) { + case WLAN_AKM_SUITE_8021X: + val = WPA2_AUTH_UNSPECIFIED; + break; + case WLAN_AKM_SUITE_8021X_SHA256: + val = WPA2_AUTH_1X_SHA256; + break; + case WLAN_AKM_SUITE_PSK_SHA256: + val = WPA2_AUTH_PSK_SHA256; + break; + case WLAN_AKM_SUITE_PSK: + val = WPA2_AUTH_PSK; + break; + default: + brcmf_err(""invalid cipher group (%d)\n"", + sme->crypto.cipher_group); + return -EINVAL; + } + } + + if (!brcmf_feat_is_enabled(ifp, BRCMF_FEAT_MFP)) + goto skip_mfp_config; + /* The MFP mode (1 or 2) needs to be determined, parse IEs. The + * IE will not be verified, just a quick search for MFP config + */ + rsn_ie = brcmf_parse_tlvs((const u8 *)sme->ie, sme->ie_len, + WLAN_EID_RSN); + if (!rsn_ie) + goto skip_mfp_config; + ie = (const u8 *)rsn_ie; + ie_len = rsn_ie->len + TLV_HDR_LEN; + /* Skip unicast suite */ + offset = TLV_HDR_LEN + WPA_IE_VERSION_LEN + WPA_IE_MIN_OUI_LEN; + if (offset + WPA_IE_SUITE_COUNT_LEN >= ie_len) + goto skip_mfp_config; + /* Skip multicast suite */ + count = ie[offset] + (ie[offset + 1] << 8); + offset += WPA_IE_SUITE_COUNT_LEN + (count * WPA_IE_MIN_OUI_LEN); + if (offset + WPA_IE_SUITE_COUNT_LEN >= ie_len) + goto skip_mfp_config; + /* Skip auth key management suite(s) */ + count = ie[offset] + (ie[offset + 1] << 8); + offset += WPA_IE_SUITE_COUNT_LEN + (count * WPA_IE_MIN_OUI_LEN); + if (offset + WPA_IE_SUITE_COUNT_LEN > ie_len) + goto skip_mfp_config; + /* Ready to read capabilities */ + mfp = BRCMF_MFP_NONE; + rsn_cap = ie[offset] + (ie[offset + 1] << 8); + if (rsn_cap & RSN_CAP_MFPR_MASK) + mfp = BRCMF_MFP_REQUIRED; + else if (rsn_cap & RSN_CAP_MFPC_MASK) + mfp = BRCMF_MFP_CAPABLE; + brcmf_fil_bsscfg_int_set(netdev_priv(ndev), ""mfp"", mfp); + +skip_mfp_config: + brcmf_dbg(CONN, ""setting wpa_auth to %d\n"", val); + err = brcmf_fil_bsscfg_int_set(netdev_priv(ndev), ""wpa_auth"", val); + if (err) { + brcmf_err(""could not set wpa_auth (%d)\n"", err); + return err; + } + + return err; +} +","@@ -4527,7 +4527,7 @@ brcmf_cfg80211_start_ap(struct wiphy *wiphy, struct net_device *ndev, + (u8 *)&settings->beacon.head[ie_offset], + settings->beacon.head_len - ie_offset, + WLAN_EID_SSID); +- if (!ssid_ie) ++ if (!ssid_ie || ssid_ie->len > IEEE80211_MAX_SSID_LEN) + return -EINVAL; + + memcpy(ssid_le.SSID, ssid_ie->data, ssid_ie->len);",990,1321,2048 +18594," static void GetLoadTimes(const v8::FunctionCallbackInfo& args) { + WebLocalFrame* frame = WebLocalFrame::frameForCurrentContext(); + if (!frame) { + args.GetReturnValue().SetNull(); + return; + } + WebDataSource* data_source = frame->dataSource(); + if (!data_source) { + args.GetReturnValue().SetNull(); + return; + } + DocumentState* document_state = DocumentState::FromDataSource(data_source); + if (!document_state) { + args.GetReturnValue().SetNull(); + return; + } + double request_time = document_state->request_time().ToDoubleT(); + double start_load_time = document_state->start_load_time().ToDoubleT(); + double commit_load_time = document_state->commit_load_time().ToDoubleT(); + double finish_document_load_time = + document_state->finish_document_load_time().ToDoubleT(); + double finish_load_time = document_state->finish_load_time().ToDoubleT(); + double first_paint_time = document_state->first_paint_time().ToDoubleT(); + double first_paint_after_load_time = + document_state->first_paint_after_load_time().ToDoubleT(); + std::string navigation_type = + GetNavigationType(data_source->navigationType()); + bool was_fetched_via_spdy = document_state->was_fetched_via_spdy(); + bool was_npn_negotiated = document_state->was_npn_negotiated(); + std::string npn_negotiated_protocol = + document_state->npn_negotiated_protocol(); + bool was_alternate_protocol_available = + document_state->was_alternate_protocol_available(); + std::string connection_info = net::HttpResponseInfo::ConnectionInfoToString( + document_state->connection_info()); + v8::Isolate* isolate = args.GetIsolate(); + v8::Local load_times = v8::Object::New(isolate); + load_times->Set(v8::String::NewFromUtf8(isolate, ""requestTime""), + v8::Number::New(isolate, request_time)); + load_times->Set(v8::String::NewFromUtf8(isolate, ""startLoadTime""), + v8::Number::New(isolate, start_load_time)); + load_times->Set(v8::String::NewFromUtf8(isolate, ""commitLoadTime""), + v8::Number::New(isolate, commit_load_time)); + load_times->Set(v8::String::NewFromUtf8(isolate, ""finishDocumentLoadTime""), + v8::Number::New(isolate, finish_document_load_time)); + load_times->Set(v8::String::NewFromUtf8(isolate, ""finishLoadTime""), + v8::Number::New(isolate, finish_load_time)); + load_times->Set(v8::String::NewFromUtf8(isolate, ""firstPaintTime""), + v8::Number::New(isolate, first_paint_time)); + load_times->Set(v8::String::NewFromUtf8(isolate, ""firstPaintAfterLoadTime""), + v8::Number::New(isolate, first_paint_after_load_time)); + load_times->Set(v8::String::NewFromUtf8(isolate, ""navigationType""), + v8::String::NewFromUtf8(isolate, navigation_type.c_str())); + load_times->Set(v8::String::NewFromUtf8(isolate, ""wasFetchedViaSpdy""), + v8::Boolean::New(isolate, was_fetched_via_spdy)); + load_times->Set(v8::String::NewFromUtf8(isolate, ""wasNpnNegotiated""), + v8::Boolean::New(isolate, was_npn_negotiated)); + load_times->Set( + v8::String::NewFromUtf8(isolate, ""npnNegotiatedProtocol""), + v8::String::NewFromUtf8(isolate, npn_negotiated_protocol.c_str())); + load_times->Set( + v8::String::NewFromUtf8(isolate, ""wasAlternateProtocolAvailable""), + v8::Boolean::New(isolate, was_alternate_protocol_available)); + load_times->Set(v8::String::NewFromUtf8(isolate, ""connectionInfo""), + v8::String::NewFromUtf8(isolate, connection_info.c_str())); + args.GetReturnValue().Set(load_times); + } +",1," static void GetLoadTimes(const v8::FunctionCallbackInfo& args) { + args.GetReturnValue().SetNull(); + WebLocalFrame* frame = WebLocalFrame::frameForCurrentContext(); + if (!frame) { + return; + } + WebDataSource* data_source = frame->dataSource(); + if (!data_source) { + return; + } + DocumentState* document_state = DocumentState::FromDataSource(data_source); + if (!document_state) { + return; + } + double request_time = document_state->request_time().ToDoubleT(); + double start_load_time = document_state->start_load_time().ToDoubleT(); + double commit_load_time = document_state->commit_load_time().ToDoubleT(); + double finish_document_load_time = + document_state->finish_document_load_time().ToDoubleT(); + double finish_load_time = document_state->finish_load_time().ToDoubleT(); + double first_paint_time = document_state->first_paint_time().ToDoubleT(); + double first_paint_after_load_time = + document_state->first_paint_after_load_time().ToDoubleT(); + std::string navigation_type = + GetNavigationType(data_source->navigationType()); + bool was_fetched_via_spdy = document_state->was_fetched_via_spdy(); + bool was_npn_negotiated = document_state->was_npn_negotiated(); + std::string npn_negotiated_protocol = + document_state->npn_negotiated_protocol(); + bool was_alternate_protocol_available = + document_state->was_alternate_protocol_available(); + std::string connection_info = net::HttpResponseInfo::ConnectionInfoToString( + document_state->connection_info()); + v8::Isolate* isolate = args.GetIsolate(); + v8::Local ctx = isolate->GetCurrentContext(); + v8::Local load_times = v8::Object::New(isolate); + if (!load_times + ->Set(ctx, v8::String::NewFromUtf8(isolate, ""requestTime"", + v8::NewStringType::kNormal) + .ToLocalChecked(), + v8::Number::New(isolate, request_time)) + .FromMaybe(false)) { + return; + } + + if (!load_times + ->Set(ctx, v8::String::NewFromUtf8(isolate, ""startLoadTime"", + v8::NewStringType::kNormal) + .ToLocalChecked(), + v8::Number::New(isolate, start_load_time)) + .FromMaybe(false)) { + return; + } + if (!load_times + ->Set(ctx, v8::String::NewFromUtf8(isolate, ""commitLoadTime"", + v8::NewStringType::kNormal) + .ToLocalChecked(), + v8::Number::New(isolate, commit_load_time)) + .FromMaybe(false)) { + return; + } + if (!load_times + ->Set(ctx, + v8::String::NewFromUtf8(isolate, ""finishDocumentLoadTime"", + v8::NewStringType::kNormal) + .ToLocalChecked(), + v8::Number::New(isolate, finish_document_load_time)) + .FromMaybe(false)) { + return; + } + if (!load_times + ->Set(ctx, v8::String::NewFromUtf8(isolate, ""finishLoadTime"", + v8::NewStringType::kNormal) + .ToLocalChecked(), + v8::Number::New(isolate, finish_load_time)) + .FromMaybe(false)) { + return; + } + if (!load_times + ->Set(ctx, v8::String::NewFromUtf8(isolate, ""firstPaintTime"", + v8::NewStringType::kNormal) + .ToLocalChecked(), + v8::Number::New(isolate, first_paint_time)) + .FromMaybe(false)) { + return; + } + if (!load_times + ->Set(ctx, + v8::String::NewFromUtf8(isolate, ""firstPaintAfterLoadTime"", + v8::NewStringType::kNormal) + .ToLocalChecked(), + v8::Number::New(isolate, first_paint_after_load_time)) + .FromMaybe(false)) { + return; + } + if (!load_times + ->Set(ctx, v8::String::NewFromUtf8(isolate, ""navigationType"", + v8::NewStringType::kNormal) + .ToLocalChecked(), + v8::String::NewFromUtf8(isolate, navigation_type.c_str(), + v8::NewStringType::kNormal) + .ToLocalChecked()) + .FromMaybe(false)) { + return; + } + if (!load_times + ->Set(ctx, v8::String::NewFromUtf8(isolate, ""wasFetchedViaSpdy"", + v8::NewStringType::kNormal) + .ToLocalChecked(), + v8::Boolean::New(isolate, was_fetched_via_spdy)) + .FromMaybe(false)) { + return; + } + if (!load_times + ->Set(ctx, v8::String::NewFromUtf8(isolate, ""wasNpnNegotiated"", + v8::NewStringType::kNormal) + .ToLocalChecked(), + v8::Boolean::New(isolate, was_npn_negotiated)) + .FromMaybe(false)) { + return; + } + if (!load_times + ->Set(ctx, + v8::String::NewFromUtf8(isolate, ""npnNegotiatedProtocol"", + v8::NewStringType::kNormal) + .ToLocalChecked(), + v8::String::NewFromUtf8(isolate, + npn_negotiated_protocol.c_str(), + v8::NewStringType::kNormal) + .ToLocalChecked()) + .FromMaybe(false)) { + return; + } + if (!load_times + ->Set(ctx, v8::String::NewFromUtf8(isolate, + ""wasAlternateProtocolAvailable"", + v8::NewStringType::kNormal) + .ToLocalChecked(), + v8::Boolean::New(isolate, was_alternate_protocol_available)) + .FromMaybe(false)) { + return; + } + if (!load_times + ->Set(ctx, v8::String::NewFromUtf8(isolate, ""connectionInfo"", + v8::NewStringType::kNormal) + .ToLocalChecked(), + v8::String::NewFromUtf8(isolate, connection_info.c_str(), + v8::NewStringType::kNormal) + .ToLocalChecked()) + .FromMaybe(false)) { + return; + } + args.GetReturnValue().Set(load_times); + } +","@@ -98,19 +98,17 @@ class LoadTimesExtensionWrapper : public v8::Extension { + } + + static void GetLoadTimes(const v8::FunctionCallbackInfo& args) { ++ args.GetReturnValue().SetNull(); + WebLocalFrame* frame = WebLocalFrame::frameForCurrentContext(); + if (!frame) { +- args.GetReturnValue().SetNull(); + return; + } + WebDataSource* data_source = frame->dataSource(); + if (!data_source) { +- args.GetReturnValue().SetNull(); + return; + } + DocumentState* document_state = DocumentState::FromDataSource(data_source); + if (!document_state) { +- args.GetReturnValue().SetNull(); + return; + } + double request_time = document_state->request_time().ToDoubleT(); +@@ -136,70 +134,183 @@ class LoadTimesExtensionWrapper : public v8::Extension { + // referred to below this line, as JS setters below can invalidate these + // pointers. + v8::Isolate* isolate = args.GetIsolate(); ++ v8::Local ctx = isolate->GetCurrentContext(); + v8::Local load_times = v8::Object::New(isolate); +- load_times->Set(v8::String::NewFromUtf8(isolate, ""requestTime""), +- v8::Number::New(isolate, request_time)); +- load_times->Set(v8::String::NewFromUtf8(isolate, ""startLoadTime""), +- v8::Number::New(isolate, start_load_time)); +- load_times->Set(v8::String::NewFromUtf8(isolate, ""commitLoadTime""), +- v8::Number::New(isolate, commit_load_time)); +- load_times->Set(v8::String::NewFromUtf8(isolate, ""finishDocumentLoadTime""), +- v8::Number::New(isolate, finish_document_load_time)); +- load_times->Set(v8::String::NewFromUtf8(isolate, ""finishLoadTime""), +- v8::Number::New(isolate, finish_load_time)); +- load_times->Set(v8::String::NewFromUtf8(isolate, ""firstPaintTime""), +- v8::Number::New(isolate, first_paint_time)); +- load_times->Set(v8::String::NewFromUtf8(isolate, ""firstPaintAfterLoadTime""), +- v8::Number::New(isolate, first_paint_after_load_time)); +- load_times->Set(v8::String::NewFromUtf8(isolate, ""navigationType""), +- v8::String::NewFromUtf8(isolate, navigation_type.c_str())); +- load_times->Set(v8::String::NewFromUtf8(isolate, ""wasFetchedViaSpdy""), +- v8::Boolean::New(isolate, was_fetched_via_spdy)); +- load_times->Set(v8::String::NewFromUtf8(isolate, ""wasNpnNegotiated""), +- v8::Boolean::New(isolate, was_npn_negotiated)); +- load_times->Set( +- v8::String::NewFromUtf8(isolate, ""npnNegotiatedProtocol""), +- v8::String::NewFromUtf8(isolate, npn_negotiated_protocol.c_str())); +- load_times->Set( +- v8::String::NewFromUtf8(isolate, ""wasAlternateProtocolAvailable""), +- v8::Boolean::New(isolate, was_alternate_protocol_available)); +- load_times->Set(v8::String::NewFromUtf8(isolate, ""connectionInfo""), +- v8::String::NewFromUtf8(isolate, connection_info.c_str())); ++ if (!load_times ++ ->Set(ctx, v8::String::NewFromUtf8(isolate, ""requestTime"", ++ v8::NewStringType::kNormal) ++ .ToLocalChecked(), ++ v8::Number::New(isolate, request_time)) ++ .FromMaybe(false)) { ++ return; ++ } ++ ++ if (!load_times ++ ->Set(ctx, v8::String::NewFromUtf8(isolate, ""startLoadTime"", ++ v8::NewStringType::kNormal) ++ .ToLocalChecked(), ++ v8::Number::New(isolate, start_load_time)) ++ .FromMaybe(false)) { ++ return; ++ } ++ if (!load_times ++ ->Set(ctx, v8::String::NewFromUtf8(isolate, ""commitLoadTime"", ++ v8::NewStringType::kNormal) ++ .ToLocalChecked(), ++ v8::Number::New(isolate, commit_load_time)) ++ .FromMaybe(false)) { ++ return; ++ } ++ if (!load_times ++ ->Set(ctx, ++ v8::String::NewFromUtf8(isolate, ""finishDocumentLoadTime"", ++ v8::NewStringType::kNormal) ++ .ToLocalChecked(), ++ v8::Number::New(isolate, finish_document_load_time)) ++ .FromMaybe(false)) { ++ return; ++ } ++ if (!load_times ++ ->Set(ctx, v8::String::NewFromUtf8(isolate, ""finishLoadTime"", ++ v8::NewStringType::kNormal) ++ .ToLocalChecked(), ++ v8::Number::New(isolate, finish_load_time)) ++ .FromMaybe(false)) { ++ return; ++ } ++ if (!load_times ++ ->Set(ctx, v8::String::NewFromUtf8(isolate, ""firstPaintTime"", ++ v8::NewStringType::kNormal) ++ .ToLocalChecked(), ++ v8::Number::New(isolate, first_paint_time)) ++ .FromMaybe(false)) { ++ return; ++ } ++ if (!load_times ++ ->Set(ctx, ++ v8::String::NewFromUtf8(isolate, ""firstPaintAfterLoadTime"", ++ v8::NewStringType::kNormal) ++ .ToLocalChecked(), ++ v8::Number::New(isolate, first_paint_after_load_time)) ++ .FromMaybe(false)) { ++ return; ++ } ++ if (!load_times ++ ->Set(ctx, v8::String::NewFromUtf8(isolate, ""navigationType"", ++ v8::NewStringType::kNormal) ++ .ToLocalChecked(), ++ v8::String::NewFromUtf8(isolate, navigation_type.c_str(), ++ v8::NewStringType::kNormal) ++ .ToLocalChecked()) ++ .FromMaybe(false)) { ++ return; ++ } ++ if (!load_times ++ ->Set(ctx, v8::String::NewFromUtf8(isolate, ""wasFetchedViaSpdy"", ++ v8::NewStringType::kNormal) ++ .ToLocalChecked(), ++ v8::Boolean::New(isolate, was_fetched_via_spdy)) ++ .FromMaybe(false)) { ++ return; ++ } ++ if (!load_times ++ ->Set(ctx, v8::String::NewFromUtf8(isolate, ""wasNpnNegotiated"", ++ v8::NewStringType::kNormal) ++ .ToLocalChecked(), ++ v8::Boolean::New(isolate, was_npn_negotiated)) ++ .FromMaybe(false)) { ++ return; ++ } ++ if (!load_times ++ ->Set(ctx, ++ v8::String::NewFromUtf8(isolate, ""npnNegotiatedProtocol"", ++ v8::NewStringType::kNormal) ++ .ToLocalChecked(), ++ v8::String::NewFromUtf8(isolate, ++ npn_negotiated_protocol.c_str(), ++ v8::NewStringType::kNormal) ++ .ToLocalChecked()) ++ .FromMaybe(false)) { ++ return; ++ } ++ if (!load_times ++ ->Set(ctx, v8::String::NewFromUtf8(isolate, ++ ""wasAlternateProtocolAvailable"", ++ v8::NewStringType::kNormal) ++ .ToLocalChecked(), ++ v8::Boolean::New(isolate, was_alternate_protocol_available)) ++ .FromMaybe(false)) { ++ return; ++ } ++ if (!load_times ++ ->Set(ctx, v8::String::NewFromUtf8(isolate, ""connectionInfo"", ++ v8::NewStringType::kNormal) ++ .ToLocalChecked(), ++ v8::String::NewFromUtf8(isolate, connection_info.c_str(), ++ v8::NewStringType::kNormal) ++ .ToLocalChecked()) ++ .FromMaybe(false)) { ++ return; ++ } + args.GetReturnValue().Set(load_times); + } + + static void GetCSI(const v8::FunctionCallbackInfo& args) { ++ args.GetReturnValue().SetNull(); + WebLocalFrame* frame = WebLocalFrame::frameForCurrentContext(); +- if (frame) { +- WebDataSource* data_source = frame->dataSource(); +- if (data_source) { +- DocumentState* document_state = +- DocumentState::FromDataSource(data_source); +- v8::Isolate* isolate = args.GetIsolate(); +- v8::Local csi = v8::Object::New(isolate); +- base::Time now = base::Time::Now(); +- base::Time start = document_state->request_time().is_null() ? +- document_state->start_load_time() : +- document_state->request_time(); +- base::Time onload = document_state->finish_document_load_time(); +- base::TimeDelta page = now - start; +- csi->Set(v8::String::NewFromUtf8(isolate, ""startE""), +- v8::Number::New(isolate, floor(start.ToDoubleT() * 1000))); +- csi->Set(v8::String::NewFromUtf8(isolate, ""onloadT""), +- v8::Number::New(isolate, floor(onload.ToDoubleT() * 1000))); +- csi->Set(v8::String::NewFromUtf8(isolate, ""pageT""), +- v8::Number::New(isolate, page.InMillisecondsF())); +- csi->Set( +- v8::String::NewFromUtf8(isolate, ""tran""), +- v8::Number::New( +- isolate, GetCSITransitionType(data_source->navigationType()))); +- +- args.GetReturnValue().Set(csi); +- return; +- } ++ if (!frame) { ++ return; + } +- args.GetReturnValue().SetNull(); +- return; ++ WebDataSource* data_source = frame->dataSource(); ++ if (!data_source) { ++ return; ++ } ++ DocumentState* document_state = DocumentState::FromDataSource(data_source); ++ if (!document_state) { ++ return; ++ } ++ base::Time now = base::Time::Now(); ++ base::Time start = document_state->request_time().is_null() ++ ? document_state->start_load_time() ++ : document_state->request_time(); ++ base::Time onload = document_state->finish_document_load_time(); ++ base::TimeDelta page = now - start; ++ int navigation_type = GetCSITransitionType(data_source->navigationType()); ++ // Important: |frame|, |data_source| and |document_state| should not be ++ // referred to below this line, as JS setters below can invalidate these ++ // pointers. ++ v8::Isolate* isolate = args.GetIsolate(); ++ v8::Local ctx = isolate->GetCurrentContext(); ++ v8::Local csi = v8::Object::New(isolate); ++ if (!csi->Set(ctx, v8::String::NewFromUtf8(isolate, ""startE"", ++ v8::NewStringType::kNormal) ++ .ToLocalChecked(), ++ v8::Number::New(isolate, floor(start.ToDoubleT() * 1000))) ++ .FromMaybe(false)) { ++ return; ++ } ++ if (!csi->Set(ctx, v8::String::NewFromUtf8(isolate, ""onloadT"", ++ v8::NewStringType::kNormal) ++ .ToLocalChecked(), ++ v8::Number::New(isolate, floor(onload.ToDoubleT() * 1000))) ++ .FromMaybe(false)) { ++ return; ++ } ++ if (!csi->Set(ctx, v8::String::NewFromUtf8(isolate, ""pageT"", ++ v8::NewStringType::kNormal) ++ .ToLocalChecked(), ++ v8::Number::New(isolate, page.InMillisecondsF())) ++ .FromMaybe(false)) { ++ return; ++ } ++ if (!csi->Set(ctx, v8::String::NewFromUtf8(isolate, ""tran"", ++ v8::NewStringType::kNormal) ++ .ToLocalChecked(), ++ v8::Number::New(isolate, navigation_type)) ++ .FromMaybe(false)) { ++ return; ++ } ++ args.GetReturnValue().Set(csi); + } + }; + ",894,1225,2048 +17945,"static int dccp_packet(struct nf_conn *ct, const struct sk_buff *skb, + unsigned int dataoff, enum ip_conntrack_info ctinfo, + u_int8_t pf, unsigned int hooknum, + unsigned int *timeouts) +{ + struct net *net = nf_ct_net(ct); + enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo); + struct dccp_hdr _dh, *dh; + u_int8_t type, old_state, new_state; + enum ct_dccp_roles role; + + dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &dh); + BUG_ON(dh == NULL); + type = dh->dccph_type; + + if (type == DCCP_PKT_RESET && + !test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) { + /* Tear down connection immediately if only reply is a RESET */ + nf_ct_kill_acct(ct, ctinfo, skb); + return NF_ACCEPT; + } + + spin_lock_bh(&ct->lock); + + role = ct->proto.dccp.role[dir]; + old_state = ct->proto.dccp.state; + new_state = dccp_state_table[role][type][old_state]; + + switch (new_state) { + case CT_DCCP_REQUEST: + if (old_state == CT_DCCP_TIMEWAIT && + role == CT_DCCP_ROLE_SERVER) { + /* Reincarnation in the reverse direction: reopen and + * reverse client/server roles. */ + ct->proto.dccp.role[dir] = CT_DCCP_ROLE_CLIENT; + ct->proto.dccp.role[!dir] = CT_DCCP_ROLE_SERVER; + } + break; + case CT_DCCP_RESPOND: + if (old_state == CT_DCCP_REQUEST) + ct->proto.dccp.handshake_seq = dccp_hdr_seq(dh); + break; + case CT_DCCP_PARTOPEN: + if (old_state == CT_DCCP_RESPOND && + type == DCCP_PKT_ACK && + dccp_ack_seq(dh) == ct->proto.dccp.handshake_seq) + set_bit(IPS_ASSURED_BIT, &ct->status); + break; + case CT_DCCP_IGNORE: + /* + * Connection tracking might be out of sync, so we ignore + * packets that might establish a new connection and resync + * if the server responds with a valid Response. + */ + if (ct->proto.dccp.last_dir == !dir && + ct->proto.dccp.last_pkt == DCCP_PKT_REQUEST && + type == DCCP_PKT_RESPONSE) { + ct->proto.dccp.role[!dir] = CT_DCCP_ROLE_CLIENT; + ct->proto.dccp.role[dir] = CT_DCCP_ROLE_SERVER; + ct->proto.dccp.handshake_seq = dccp_hdr_seq(dh); + new_state = CT_DCCP_RESPOND; + break; + } + ct->proto.dccp.last_dir = dir; + ct->proto.dccp.last_pkt = type; + + spin_unlock_bh(&ct->lock); + if (LOG_INVALID(net, IPPROTO_DCCP)) + nf_log_packet(net, pf, 0, skb, NULL, NULL, NULL, + ""nf_ct_dccp: invalid packet ignored ""); + return NF_ACCEPT; + case CT_DCCP_INVALID: + spin_unlock_bh(&ct->lock); + if (LOG_INVALID(net, IPPROTO_DCCP)) + nf_log_packet(net, pf, 0, skb, NULL, NULL, NULL, + ""nf_ct_dccp: invalid state transition ""); + return -NF_ACCEPT; + } + + ct->proto.dccp.last_dir = dir; + ct->proto.dccp.last_pkt = type; + ct->proto.dccp.state = new_state; + spin_unlock_bh(&ct->lock); + + if (new_state != old_state) + nf_conntrack_event_cache(IPCT_PROTOINFO, ct); + + nf_ct_refresh_acct(ct, ctinfo, skb, timeouts[new_state]); + + return NF_ACCEPT; +} +",1,"static int dccp_packet(struct nf_conn *ct, const struct sk_buff *skb, + unsigned int dataoff, enum ip_conntrack_info ctinfo, + u_int8_t pf, unsigned int hooknum, + unsigned int *timeouts) +{ + struct net *net = nf_ct_net(ct); + enum ip_conntrack_dir dir = CTINFO2DIR(ctinfo); + struct dccp_hdr _dh, *dh; + u_int8_t type, old_state, new_state; + enum ct_dccp_roles role; + + dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &_dh); + BUG_ON(dh == NULL); + type = dh->dccph_type; + + if (type == DCCP_PKT_RESET && + !test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) { + /* Tear down connection immediately if only reply is a RESET */ + nf_ct_kill_acct(ct, ctinfo, skb); + return NF_ACCEPT; + } + + spin_lock_bh(&ct->lock); + + role = ct->proto.dccp.role[dir]; + old_state = ct->proto.dccp.state; + new_state = dccp_state_table[role][type][old_state]; + + switch (new_state) { + case CT_DCCP_REQUEST: + if (old_state == CT_DCCP_TIMEWAIT && + role == CT_DCCP_ROLE_SERVER) { + /* Reincarnation in the reverse direction: reopen and + * reverse client/server roles. */ + ct->proto.dccp.role[dir] = CT_DCCP_ROLE_CLIENT; + ct->proto.dccp.role[!dir] = CT_DCCP_ROLE_SERVER; + } + break; + case CT_DCCP_RESPOND: + if (old_state == CT_DCCP_REQUEST) + ct->proto.dccp.handshake_seq = dccp_hdr_seq(dh); + break; + case CT_DCCP_PARTOPEN: + if (old_state == CT_DCCP_RESPOND && + type == DCCP_PKT_ACK && + dccp_ack_seq(dh) == ct->proto.dccp.handshake_seq) + set_bit(IPS_ASSURED_BIT, &ct->status); + break; + case CT_DCCP_IGNORE: + /* + * Connection tracking might be out of sync, so we ignore + * packets that might establish a new connection and resync + * if the server responds with a valid Response. + */ + if (ct->proto.dccp.last_dir == !dir && + ct->proto.dccp.last_pkt == DCCP_PKT_REQUEST && + type == DCCP_PKT_RESPONSE) { + ct->proto.dccp.role[!dir] = CT_DCCP_ROLE_CLIENT; + ct->proto.dccp.role[dir] = CT_DCCP_ROLE_SERVER; + ct->proto.dccp.handshake_seq = dccp_hdr_seq(dh); + new_state = CT_DCCP_RESPOND; + break; + } + ct->proto.dccp.last_dir = dir; + ct->proto.dccp.last_pkt = type; + + spin_unlock_bh(&ct->lock); + if (LOG_INVALID(net, IPPROTO_DCCP)) + nf_log_packet(net, pf, 0, skb, NULL, NULL, NULL, + ""nf_ct_dccp: invalid packet ignored ""); + return NF_ACCEPT; + case CT_DCCP_INVALID: + spin_unlock_bh(&ct->lock); + if (LOG_INVALID(net, IPPROTO_DCCP)) + nf_log_packet(net, pf, 0, skb, NULL, NULL, NULL, + ""nf_ct_dccp: invalid state transition ""); + return -NF_ACCEPT; + } + + ct->proto.dccp.last_dir = dir; + ct->proto.dccp.last_pkt = type; + ct->proto.dccp.state = new_state; + spin_unlock_bh(&ct->lock); + + if (new_state != old_state) + nf_conntrack_event_cache(IPCT_PROTOINFO, ct); + + nf_ct_refresh_acct(ct, ctinfo, skb, timeouts[new_state]); + + return NF_ACCEPT; +} +","@@ -428,7 +428,7 @@ static bool dccp_new(struct nf_conn *ct, const struct sk_buff *skb, + const char *msg; + u_int8_t state; + +- dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &dh); ++ dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &_dh); + BUG_ON(dh == NULL); + + state = dccp_state_table[CT_DCCP_ROLE_CLIENT][dh->dccph_type][CT_DCCP_NONE]; +@@ -486,7 +486,7 @@ static int dccp_packet(struct nf_conn *ct, const struct sk_buff *skb, + u_int8_t type, old_state, new_state; + enum ct_dccp_roles role; + +- dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &dh); ++ dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &_dh); + BUG_ON(dh == NULL); + type = dh->dccph_type; + +@@ -577,7 +577,7 @@ static int dccp_error(struct net *net, struct nf_conn *tmpl, + unsigned int cscov; + const char *msg; + +- dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &dh); ++ dh = skb_header_pointer(skb, dataoff, sizeof(_dh), &_dh); + if (dh == NULL) { + msg = ""nf_ct_dccp: short packet ""; + goto out_invalid;",864,1195,2048 +484,"static time_t asn1_time_to_time_t(ASN1_UTCTIME * timestr TSRMLS_DC) /* {{{ */ +{ +/* + This is how the time string is formatted: + + snprintf(p, sizeof(p), ""%02d%02d%02d%02d%02d%02dZ"",ts->tm_year%100, + ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec); +*/ + + time_t ret; + struct tm thetime; + char * strbuf; + char * thestr; + long gmadjust = 0; + + if (ASN1_STRING_type(timestr) != V_ASN1_UTCTIME && ASN1_STRING_type(timestr) != V_ASN1_GENERALIZEDTIME) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""illegal ASN1 data type for timestamp""); + return (time_t)-1; + } + + if (ASN1_STRING_length(timestr) != strlen((const char*)ASN1_STRING_data(timestr))) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""illegal length in timestamp""); + return (time_t)-1; + } + + if (ASN1_STRING_length(timestr) < 13) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""unable to parse time string %s correctly"", timestr->data); + return (time_t)-1; + } + + if (ASN1_STRING_type(timestr) == V_ASN1_GENERALIZEDTIME && ASN1_STRING_length(timestr) < 15) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""unable to parse time string %s correctly"", timestr->data); + return (time_t)-1; + } + + strbuf = estrdup((char *)ASN1_STRING_data(timestr)); + + memset(&thetime, 0, sizeof(thetime)); + + /* we work backwards so that we can use atoi more easily */ + + thestr = strbuf + ASN1_STRING_length(timestr) - 3; + + thetime.tm_sec = atoi(thestr); + *thestr = '\0'; + thestr -= 2; + thetime.tm_min = atoi(thestr); + *thestr = '\0'; + thestr -= 2; + thetime.tm_hour = atoi(thestr); + *thestr = '\0'; + thestr -= 2; + thetime.tm_mday = atoi(thestr); + *thestr = '\0'; + thestr -= 2; + thetime.tm_mon = atoi(thestr)-1; + + *thestr = '\0'; + if( ASN1_STRING_type(timestr) == V_ASN1_UTCTIME ) { + thestr -= 2; + thetime.tm_year = atoi(thestr); + + if (thetime.tm_year < 68) { + thetime.tm_year += 100; + } + } else if( ASN1_STRING_type(timestr) == V_ASN1_GENERALIZEDTIME ) { + thestr -= 4; + thetime.tm_year = atoi(thestr) - 1900; + } + + + thetime.tm_isdst = -1; + ret = mktime(&thetime); + +#if HAVE_TM_GMTOFF + gmadjust = thetime.tm_gmtoff; +#else + /* + ** If correcting for daylight savings time, we set the adjustment to + ** the value of timezone - 3600 seconds. Otherwise, we need to overcorrect and + ** set the adjustment to the main timezone + 3600 seconds. + */ + gmadjust = -(thetime.tm_isdst ? (long)timezone - 3600 : (long)timezone + 3600); +#endif + ret += gmadjust; + + efree(strbuf); + + return ret; +} +/* }}} */ +",0,"static time_t asn1_time_to_time_t(ASN1_UTCTIME * timestr TSRMLS_DC) /* {{{ */ +{ +/* + This is how the time string is formatted: + + snprintf(p, sizeof(p), ""%02d%02d%02d%02d%02d%02dZ"",ts->tm_year%100, + ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec); +*/ + + time_t ret; + struct tm thetime; + char * strbuf; + char * thestr; + long gmadjust = 0; + + if (ASN1_STRING_type(timestr) != V_ASN1_UTCTIME && ASN1_STRING_type(timestr) != V_ASN1_GENERALIZEDTIME) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""illegal ASN1 data type for timestamp""); + return (time_t)-1; + } + + if (ASN1_STRING_length(timestr) != strlen((const char*)ASN1_STRING_data(timestr))) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""illegal length in timestamp""); + return (time_t)-1; + } + + if (ASN1_STRING_length(timestr) < 13) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""unable to parse time string %s correctly"", timestr->data); + return (time_t)-1; + } + + if (ASN1_STRING_type(timestr) == V_ASN1_GENERALIZEDTIME && ASN1_STRING_length(timestr) < 15) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""unable to parse time string %s correctly"", timestr->data); + return (time_t)-1; + } + + strbuf = estrdup((char *)ASN1_STRING_data(timestr)); + + memset(&thetime, 0, sizeof(thetime)); + + /* we work backwards so that we can use atoi more easily */ + + thestr = strbuf + ASN1_STRING_length(timestr) - 3; + + thetime.tm_sec = atoi(thestr); + *thestr = '\0'; + thestr -= 2; + thetime.tm_min = atoi(thestr); + *thestr = '\0'; + thestr -= 2; + thetime.tm_hour = atoi(thestr); + *thestr = '\0'; + thestr -= 2; + thetime.tm_mday = atoi(thestr); + *thestr = '\0'; + thestr -= 2; + thetime.tm_mon = atoi(thestr)-1; + + *thestr = '\0'; + if( ASN1_STRING_type(timestr) == V_ASN1_UTCTIME ) { + thestr -= 2; + thetime.tm_year = atoi(thestr); + + if (thetime.tm_year < 68) { + thetime.tm_year += 100; + } + } else if( ASN1_STRING_type(timestr) == V_ASN1_GENERALIZEDTIME ) { + thestr -= 4; + thetime.tm_year = atoi(thestr) - 1900; + } + + + thetime.tm_isdst = -1; + ret = mktime(&thetime); + +#if HAVE_TM_GMTOFF + gmadjust = thetime.tm_gmtoff; +#else + /* + ** If correcting for daylight savings time, we set the adjustment to + ** the value of timezone - 3600 seconds. Otherwise, we need to overcorrect and + ** set the adjustment to the main timezone + 3600 seconds. + */ + gmadjust = -(thetime.tm_isdst ? (long)timezone - 3600 : (long)timezone + 3600); +#endif + ret += gmadjust; + + efree(strbuf); + + return ret; +} +/* }}} */ +","@@ -4982,15 +4982,15 @@ PHP_FUNCTION(openssl_seal) + buf = emalloc(data_len + EVP_CIPHER_CTX_block_size(&ctx)); + EVP_CIPHER_CTX_cleanup(&ctx); + +- if (!EVP_SealInit(&ctx, cipher, eks, eksl, NULL, pkeys, nkeys) || !EVP_SealUpdate(&ctx, buf, &len1, (unsigned char *)data, data_len)) { ++ if (EVP_SealInit(&ctx, cipher, eks, eksl, NULL, pkeys, nkeys) <= 0 || ++ !EVP_SealUpdate(&ctx, buf, &len1, (unsigned char *)data, data_len) || ++ !EVP_SealFinal(&ctx, buf + len1, &len2)) { + RETVAL_FALSE; + efree(buf); + EVP_CIPHER_CTX_cleanup(&ctx); + goto clean_exit; + } + +- EVP_SealFinal(&ctx, buf + len1, &len2); +- + if (len1 + len2 > 0) { + zval_dtor(sealdata); + buf[len1 + len2] = '\0';",822,1153,2048 +7588,"xfs_attr_node_removename(xfs_da_args_t *args) +{ + xfs_da_state_t *state; + xfs_da_state_blk_t *blk; + xfs_inode_t *dp; + struct xfs_buf *bp; + int retval, error, forkoff; + + trace_xfs_attr_node_removename(args); + + /* + * Tie a string around our finger to remind us where we are. + */ + dp = args->dp; + state = xfs_da_state_alloc(); + state->args = args; + state->mp = dp->i_mount; + + /* + * Search to see if name exists, and get back a pointer to it. + */ + error = xfs_da3_node_lookup_int(state, &retval); + if (error || (retval != -EEXIST)) { + if (error == 0) + error = retval; + goto out; + } + + /* + * If there is an out-of-line value, de-allocate the blocks. + * This is done before we remove the attribute so that we don't + * overflow the maximum size of a transaction and/or hit a deadlock. + */ + blk = &state->path.blk[ state->path.active-1 ]; + ASSERT(blk->bp != NULL); + ASSERT(blk->magic == XFS_ATTR_LEAF_MAGIC); + if (args->rmtblkno > 0) { + /* + * Fill in disk block numbers in the state structure + * so that we can get the buffers back after we commit + * several transactions in the following calls. + */ + error = xfs_attr_fillstate(state); + if (error) + goto out; + + /* + * Mark the attribute as INCOMPLETE, then bunmapi() the + * remote value. + */ + error = xfs_attr3_leaf_setflag(args); + if (error) + goto out; + error = xfs_attr_rmtval_remove(args); + if (error) + goto out; + + /* + * Refill the state structure with buffers, the prior calls + * released our buffers. + */ + error = xfs_attr_refillstate(state); + if (error) + goto out; + } + + /* + * Remove the name and update the hashvals in the tree. + */ + blk = &state->path.blk[ state->path.active-1 ]; + ASSERT(blk->magic == XFS_ATTR_LEAF_MAGIC); + retval = xfs_attr3_leaf_remove(blk->bp, args); + xfs_da3_fixhashpath(state, &state->path); + + /* + * Check to see if the tree needs to be collapsed. + */ + if (retval && (state->path.active > 1)) { + xfs_defer_init(args->dfops, args->firstblock); + error = xfs_da3_join(state); + if (error) + goto out_defer_cancel; + xfs_defer_ijoin(args->dfops, dp); + error = xfs_defer_finish(&args->trans, args->dfops); + if (error) + goto out_defer_cancel; + /* + * Commit the Btree join operation and start a new trans. + */ + error = xfs_trans_roll_inode(&args->trans, dp); + if (error) + goto out; + } + + /* + * If the result is small enough, push it all into the inode. + */ + if (xfs_bmap_one_block(dp, XFS_ATTR_FORK)) { + /* + * Have to get rid of the copy of this dabuf in the state. + */ + ASSERT(state->path.active == 1); + ASSERT(state->path.blk[0].bp); + state->path.blk[0].bp = NULL; + + error = xfs_attr3_leaf_read(args->trans, args->dp, 0, -1, &bp); + if (error) + goto out; + + if ((forkoff = xfs_attr_shortform_allfit(bp, dp))) { + xfs_defer_init(args->dfops, args->firstblock); + error = xfs_attr3_leaf_to_shortform(bp, args, forkoff); + /* bp is gone due to xfs_da_shrink_inode */ + if (error) + goto out_defer_cancel; + xfs_defer_ijoin(args->dfops, dp); + error = xfs_defer_finish(&args->trans, args->dfops); + if (error) + goto out_defer_cancel; + } else + xfs_trans_brelse(args->trans, bp); + } + error = 0; + +out: + xfs_da_state_free(state); + return error; +out_defer_cancel: + xfs_defer_cancel(args->dfops); + goto out; +} +",0,"xfs_attr_node_removename(xfs_da_args_t *args) +{ + xfs_da_state_t *state; + xfs_da_state_blk_t *blk; + xfs_inode_t *dp; + struct xfs_buf *bp; + int retval, error, forkoff; + + trace_xfs_attr_node_removename(args); + + /* + * Tie a string around our finger to remind us where we are. + */ + dp = args->dp; + state = xfs_da_state_alloc(); + state->args = args; + state->mp = dp->i_mount; + + /* + * Search to see if name exists, and get back a pointer to it. + */ + error = xfs_da3_node_lookup_int(state, &retval); + if (error || (retval != -EEXIST)) { + if (error == 0) + error = retval; + goto out; + } + + /* + * If there is an out-of-line value, de-allocate the blocks. + * This is done before we remove the attribute so that we don't + * overflow the maximum size of a transaction and/or hit a deadlock. + */ + blk = &state->path.blk[ state->path.active-1 ]; + ASSERT(blk->bp != NULL); + ASSERT(blk->magic == XFS_ATTR_LEAF_MAGIC); + if (args->rmtblkno > 0) { + /* + * Fill in disk block numbers in the state structure + * so that we can get the buffers back after we commit + * several transactions in the following calls. + */ + error = xfs_attr_fillstate(state); + if (error) + goto out; + + /* + * Mark the attribute as INCOMPLETE, then bunmapi() the + * remote value. + */ + error = xfs_attr3_leaf_setflag(args); + if (error) + goto out; + error = xfs_attr_rmtval_remove(args); + if (error) + goto out; + + /* + * Refill the state structure with buffers, the prior calls + * released our buffers. + */ + error = xfs_attr_refillstate(state); + if (error) + goto out; + } + + /* + * Remove the name and update the hashvals in the tree. + */ + blk = &state->path.blk[ state->path.active-1 ]; + ASSERT(blk->magic == XFS_ATTR_LEAF_MAGIC); + retval = xfs_attr3_leaf_remove(blk->bp, args); + xfs_da3_fixhashpath(state, &state->path); + + /* + * Check to see if the tree needs to be collapsed. + */ + if (retval && (state->path.active > 1)) { + xfs_defer_init(args->dfops, args->firstblock); + error = xfs_da3_join(state); + if (error) + goto out_defer_cancel; + xfs_defer_ijoin(args->dfops, dp); + error = xfs_defer_finish(&args->trans, args->dfops); + if (error) + goto out_defer_cancel; + /* + * Commit the Btree join operation and start a new trans. + */ + error = xfs_trans_roll_inode(&args->trans, dp); + if (error) + goto out; + } + + /* + * If the result is small enough, push it all into the inode. + */ + if (xfs_bmap_one_block(dp, XFS_ATTR_FORK)) { + /* + * Have to get rid of the copy of this dabuf in the state. + */ + ASSERT(state->path.active == 1); + ASSERT(state->path.blk[0].bp); + state->path.blk[0].bp = NULL; + + error = xfs_attr3_leaf_read(args->trans, args->dp, 0, -1, &bp); + if (error) + goto out; + + if ((forkoff = xfs_attr_shortform_allfit(bp, dp))) { + xfs_defer_init(args->dfops, args->firstblock); + error = xfs_attr3_leaf_to_shortform(bp, args, forkoff); + /* bp is gone due to xfs_da_shrink_inode */ + if (error) + goto out_defer_cancel; + xfs_defer_ijoin(args->dfops, dp); + error = xfs_defer_finish(&args->trans, args->dfops); + if (error) + goto out_defer_cancel; + } else + xfs_trans_brelse(args->trans, bp); + } + error = 0; + +out: + xfs_da_state_free(state); + return error; +out_defer_cancel: + xfs_defer_cancel(args->dfops); + goto out; +} +","@@ -511,7 +511,14 @@ xfs_attr_shortform_addname(xfs_da_args_t *args) + if (args->flags & ATTR_CREATE) + return retval; + retval = xfs_attr_shortform_remove(args); +- ASSERT(retval == 0); ++ if (retval) ++ return retval; ++ /* ++ * Since we have removed the old attr, clear ATTR_REPLACE so ++ * that the leaf format add routine won't trip over the attr ++ * not being around. ++ */ ++ args->flags &= ~ATTR_REPLACE; + } + + if (args->namelen >= XFS_ATTR_SF_ENTSIZE_MAX ||",1000,1331,2048 +18607,"void NavigationRequest::OnStartChecksComplete( + NavigationThrottle::ThrottleCheckResult result) { + DCHECK(result.action() != NavigationThrottle::DEFER); + DCHECK(result.action() != NavigationThrottle::BLOCK_RESPONSE); + + if (on_start_checks_complete_closure_) + on_start_checks_complete_closure_.Run(); + if (result.action() == NavigationThrottle::CANCEL_AND_IGNORE || + result.action() == NavigationThrottle::CANCEL || + result.action() == NavigationThrottle::BLOCK_REQUEST || + result.action() == NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE) { +#if DCHECK_IS_ON() + if (result.action() == NavigationThrottle::BLOCK_REQUEST) { + DCHECK(result.net_error_code() == net::ERR_BLOCKED_BY_CLIENT || + result.net_error_code() == net::ERR_BLOCKED_BY_ADMINISTRATOR); + } + else if (result.action() == NavigationThrottle::CANCEL_AND_IGNORE) { + DCHECK_EQ(result.net_error_code(), net::ERR_ABORTED); + } +#endif + + bool collapse_frame = + result.action() == NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE; + + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + base::BindOnce( + &NavigationRequest::OnRequestFailedInternal, + weak_factory_.GetWeakPtr(), + network::URLLoaderCompletionStatus(result.net_error_code()), + true /* skip_throttles */, result.error_page_content(), + collapse_frame)); + + return; + } + + DCHECK_NE(AssociatedSiteInstanceType::NONE, associated_site_instance_type_); + RenderFrameHostImpl* navigating_frame_host = + associated_site_instance_type_ == AssociatedSiteInstanceType::SPECULATIVE + ? frame_tree_node_->render_manager()->speculative_frame_host() + : frame_tree_node_->current_frame_host(); + DCHECK(navigating_frame_host); + + navigation_handle_->SetExpectedProcess(navigating_frame_host->GetProcess()); + + BrowserContext* browser_context = + frame_tree_node_->navigator()->GetController()->GetBrowserContext(); + StoragePartition* partition = BrowserContext::GetStoragePartition( + browser_context, navigating_frame_host->GetSiteInstance()); + DCHECK(partition); + + DCHECK(!loader_); + + bool can_create_service_worker = + (frame_tree_node_->pending_frame_policy().sandbox_flags & + blink::WebSandboxFlags::kOrigin) != blink::WebSandboxFlags::kOrigin; + request_params_.should_create_service_worker = can_create_service_worker; + if (can_create_service_worker) { + ServiceWorkerContextWrapper* service_worker_context = + static_cast( + partition->GetServiceWorkerContext()); + navigation_handle_->InitServiceWorkerHandle(service_worker_context); + } + + if (IsSchemeSupportedForAppCache(common_params_.url)) { + if (navigating_frame_host->GetRenderViewHost() + ->GetWebkitPreferences() + .application_cache_enabled) { + navigation_handle_->InitAppCacheHandle( + static_cast(partition->GetAppCacheService())); + } + } + + request_params_.navigation_timing.fetch_start = base::TimeTicks::Now(); + + GURL base_url; +#if defined(OS_ANDROID) + NavigationEntry* last_committed_entry = + frame_tree_node_->navigator()->GetController()->GetLastCommittedEntry(); + if (last_committed_entry) + base_url = last_committed_entry->GetBaseURLForDataURL(); +#endif + const GURL& top_document_url = + !base_url.is_empty() + ? base_url + : frame_tree_node_->frame_tree()->root()->current_url(); + + const FrameTreeNode* current = frame_tree_node_->parent(); + bool ancestors_are_same_site = true; + while (current && ancestors_are_same_site) { + if (!net::registry_controlled_domains::SameDomainOrHost( + top_document_url, current->current_url(), + net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)) { + ancestors_are_same_site = false; + } + current = current->parent(); + } + const GURL& site_for_cookies = + ancestors_are_same_site + ? (frame_tree_node_->IsMainFrame() ? common_params_.url + : top_document_url) + : GURL::EmptyGURL(); + bool parent_is_main_frame = !frame_tree_node_->parent() + ? false + : frame_tree_node_->parent()->IsMainFrame(); + + std::unique_ptr navigation_ui_data; + if (navigation_handle_->GetNavigationUIData()) + navigation_ui_data = navigation_handle_->GetNavigationUIData()->Clone(); + + bool is_for_guests_only = + navigation_handle_->GetStartingSiteInstance()->GetSiteURL(). + SchemeIs(kGuestScheme); + + bool report_raw_headers = false; + RenderFrameDevToolsAgentHost::ApplyOverrides( + frame_tree_node_, begin_params_.get(), &report_raw_headers); + RenderFrameDevToolsAgentHost::OnNavigationRequestWillBeSent(*this); + + loader_ = NavigationURLLoader::Create( + browser_context->GetResourceContext(), partition, + std::make_unique( + common_params_, begin_params_.Clone(), site_for_cookies, + frame_tree_node_->IsMainFrame(), parent_is_main_frame, + IsSecureFrame(frame_tree_node_->parent()), + frame_tree_node_->frame_tree_node_id(), is_for_guests_only, + report_raw_headers, + navigating_frame_host->GetVisibilityState() == + blink::mojom::PageVisibilityState::kPrerender, + upgrade_if_insecure_, + blob_url_loader_factory_ ? blob_url_loader_factory_->Clone() + : nullptr, + devtools_navigation_token(), + frame_tree_node_->devtools_frame_token()), + std::move(navigation_ui_data), + navigation_handle_->service_worker_handle(), + navigation_handle_->appcache_handle(), this); +} +",1,"void NavigationRequest::OnStartChecksComplete( + NavigationThrottle::ThrottleCheckResult result) { + DCHECK(result.action() != NavigationThrottle::DEFER); + DCHECK(result.action() != NavigationThrottle::BLOCK_RESPONSE); + + if (on_start_checks_complete_closure_) + on_start_checks_complete_closure_.Run(); + if (result.action() == NavigationThrottle::CANCEL_AND_IGNORE || + result.action() == NavigationThrottle::CANCEL || + result.action() == NavigationThrottle::BLOCK_REQUEST || + result.action() == NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE) { +#if DCHECK_IS_ON() + if (result.action() == NavigationThrottle::BLOCK_REQUEST) { + DCHECK(result.net_error_code() == net::ERR_BLOCKED_BY_CLIENT || + result.net_error_code() == net::ERR_BLOCKED_BY_ADMINISTRATOR); + } + else if (result.action() == NavigationThrottle::CANCEL_AND_IGNORE) { + DCHECK_EQ(result.net_error_code(), net::ERR_ABORTED); + } +#endif + + bool collapse_frame = + result.action() == NavigationThrottle::BLOCK_REQUEST_AND_COLLAPSE; + + BrowserThread::PostTask( + BrowserThread::UI, FROM_HERE, + base::BindOnce( + &NavigationRequest::OnRequestFailedInternal, + weak_factory_.GetWeakPtr(), + network::URLLoaderCompletionStatus(result.net_error_code()), + true /* skip_throttles */, result.error_page_content(), + collapse_frame)); + + return; + } + + DCHECK_NE(AssociatedSiteInstanceType::NONE, associated_site_instance_type_); + RenderFrameHostImpl* navigating_frame_host = + associated_site_instance_type_ == AssociatedSiteInstanceType::SPECULATIVE + ? frame_tree_node_->render_manager()->speculative_frame_host() + : frame_tree_node_->current_frame_host(); + DCHECK(navigating_frame_host); + + navigation_handle_->SetExpectedProcess(navigating_frame_host->GetProcess()); + + BrowserContext* browser_context = + frame_tree_node_->navigator()->GetController()->GetBrowserContext(); + StoragePartition* partition = BrowserContext::GetStoragePartition( + browser_context, navigating_frame_host->GetSiteInstance()); + DCHECK(partition); + + DCHECK(!loader_); + + bool can_create_service_worker = + (frame_tree_node_->pending_frame_policy().sandbox_flags & + blink::WebSandboxFlags::kOrigin) != blink::WebSandboxFlags::kOrigin; + request_params_.should_create_service_worker = can_create_service_worker; + if (can_create_service_worker) { + ServiceWorkerContextWrapper* service_worker_context = + static_cast( + partition->GetServiceWorkerContext()); + navigation_handle_->InitServiceWorkerHandle(service_worker_context); + } + + if (IsSchemeSupportedForAppCache(common_params_.url)) { + if (navigating_frame_host->GetRenderViewHost() + ->GetWebkitPreferences() + .application_cache_enabled) { + navigation_handle_->InitAppCacheHandle( + static_cast(partition->GetAppCacheService())); + } + } + + request_params_.navigation_timing.fetch_start = base::TimeTicks::Now(); + + GURL base_url; +#if defined(OS_ANDROID) + NavigationEntry* last_committed_entry = + frame_tree_node_->navigator()->GetController()->GetLastCommittedEntry(); + if (last_committed_entry) + base_url = last_committed_entry->GetBaseURLForDataURL(); +#endif + const GURL& top_document_url = + !base_url.is_empty() + ? base_url + : frame_tree_node_->frame_tree()->root()->current_url(); + + // not, the |site_for_cookies| is set to an opaque URL. + const FrameTreeNode* current = frame_tree_node_->parent(); + bool ancestors_are_same_site = true; + while (current && ancestors_are_same_site) { + if (!net::registry_controlled_domains::SameDomainOrHost( + top_document_url, current->current_url(), + net::registry_controlled_domains::INCLUDE_PRIVATE_REGISTRIES)) { + ancestors_are_same_site = false; + } + current = current->parent(); + } + + const GURL& site_for_cookies = + (ancestors_are_same_site || !base_url.is_empty()) + ? (frame_tree_node_->IsMainFrame() ? common_params_.url + : top_document_url) + : GURL(""data:,""); + bool parent_is_main_frame = !frame_tree_node_->parent() + ? false + : frame_tree_node_->parent()->IsMainFrame(); + + std::unique_ptr navigation_ui_data; + if (navigation_handle_->GetNavigationUIData()) + navigation_ui_data = navigation_handle_->GetNavigationUIData()->Clone(); + + bool is_for_guests_only = + navigation_handle_->GetStartingSiteInstance()->GetSiteURL(). + SchemeIs(kGuestScheme); + + bool report_raw_headers = false; + RenderFrameDevToolsAgentHost::ApplyOverrides( + frame_tree_node_, begin_params_.get(), &report_raw_headers); + RenderFrameDevToolsAgentHost::OnNavigationRequestWillBeSent(*this); + + loader_ = NavigationURLLoader::Create( + browser_context->GetResourceContext(), partition, + std::make_unique( + common_params_, begin_params_.Clone(), site_for_cookies, + frame_tree_node_->IsMainFrame(), parent_is_main_frame, + IsSecureFrame(frame_tree_node_->parent()), + frame_tree_node_->frame_tree_node_id(), is_for_guests_only, + report_raw_headers, + navigating_frame_host->GetVisibilityState() == + blink::mojom::PageVisibilityState::kPrerender, + upgrade_if_insecure_, + blob_url_loader_factory_ ? blob_url_loader_factory_->Clone() + : nullptr, + devtools_navigation_token(), + frame_tree_node_->devtools_frame_token()), + std::move(navigation_ui_data), + navigation_handle_->service_worker_handle(), + navigation_handle_->appcache_handle(), this); +} +","@@ -1345,7 +1345,7 @@ void NavigationRequest::OnStartChecksComplete( + : frame_tree_node_->frame_tree()->root()->current_url(); + + // Walk the ancestor chain to determine whether all frames are same-site. If +- // not, the |site_for_cookies| is set to an empty URL. ++ // not, the |site_for_cookies| is set to an opaque URL. + // + // TODO(mkwst): This is incorrect. It ought to use the definition from + // 'Document::SiteForCookies()' in Blink, which special-cases extension +@@ -1360,11 +1360,12 @@ void NavigationRequest::OnStartChecksComplete( + } + current = current->parent(); + } ++ + const GURL& site_for_cookies = +- ancestors_are_same_site ++ (ancestors_are_same_site || !base_url.is_empty()) + ? (frame_tree_node_->IsMainFrame() ? common_params_.url + : top_document_url) +- : GURL::EmptyGURL(); ++ : GURL(""data:,""); + bool parent_is_main_frame = !frame_tree_node_->parent() + ? false + : frame_tree_node_->parent()->IsMainFrame();",1206,1537,2048 +16346,"void NavigationControllerImpl::LoadURLWithParams(const LoadURLParams& params) { + TRACE_EVENT1(""browser,navigation"", + ""NavigationControllerImpl::LoadURLWithParams"", + ""url"", params.url.possibly_invalid_spec()); + if (HandleDebugURL(params.url, params.transition_type)) { + if (!base::CommandLine::ForCurrentProcess()->HasSwitch( + cc::switches::kEnableGpuBenchmarking)) + return; + } + + switch (params.load_type) { + case LOAD_TYPE_DEFAULT: + case LOAD_TYPE_HTTP_POST: + break; + case LOAD_TYPE_DATA: + if (!params.url.SchemeIs(url::kDataScheme)) { + NOTREACHED() << ""Data load must use data scheme.""; + return; + } + break; + default: + NOTREACHED(); + break; + }; + + needs_reload_ = false; + + bool override = false; + switch (params.override_user_agent) { + case UA_OVERRIDE_INHERIT: + override = ShouldKeepOverride(GetLastCommittedEntry()); + break; + case UA_OVERRIDE_TRUE: + override = true; + break; + case UA_OVERRIDE_FALSE: + override = false; + break; + default: + NOTREACHED(); + break; + } + + std::unique_ptr entry; + + int frame_tree_node_id = params.frame_tree_node_id; + if (frame_tree_node_id != -1 || !params.frame_name.empty()) { + FrameTreeNode* node = + params.frame_tree_node_id != -1 + ? delegate_->GetFrameTree()->FindByID(params.frame_tree_node_id) + : delegate_->GetFrameTree()->FindByName(params.frame_name); + if (node && !node->IsMainFrame()) { + DCHECK(GetLastCommittedEntry()); + + frame_tree_node_id = node->frame_tree_node_id(); + + entry = GetLastCommittedEntry()->Clone(); + entry->AddOrUpdateFrameEntry( + node, -1, -1, nullptr, + static_cast(params.source_site_instance.get()), + params.url, params.referrer, params.redirect_chain, PageState(), + ""GET"", -1); + } + } + + if (!entry) { + std::string extra_headers_crlf; + base::ReplaceChars(params.extra_headers, ""\n"", ""\r\n"", &extra_headers_crlf); + entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry( + params.url, params.referrer, params.transition_type, + params.is_renderer_initiated, extra_headers_crlf, browser_context_)); + entry->set_source_site_instance( + static_cast(params.source_site_instance.get())); + entry->SetRedirectChain(params.redirect_chain); + } + + entry->set_frame_tree_node_id(frame_tree_node_id); + if (params.should_replace_current_entry && entries_.size() > 0) + entry->set_should_replace_entry(true); + entry->set_should_clear_history_list(params.should_clear_history_list); + entry->SetIsOverridingUserAgent(override); + entry->set_transferred_global_request_id( + params.transferred_global_request_id); + +#if defined(OS_ANDROID) + if (params.intent_received_timestamp > 0) { + entry->set_intent_received_timestamp( + base::TimeTicks() + + base::TimeDelta::FromMilliseconds(params.intent_received_timestamp)); + } + entry->set_has_user_gesture(params.has_user_gesture); +#endif + + switch (params.load_type) { + case LOAD_TYPE_DEFAULT: + break; + case LOAD_TYPE_HTTP_POST: + entry->SetHasPostData(true); + entry->SetPostData(params.post_data); + break; + case LOAD_TYPE_DATA: + entry->SetBaseURLForDataURL(params.base_url_for_data_url); + entry->SetVirtualURL(params.virtual_url_for_data_url); +#if defined(OS_ANDROID) + entry->SetDataURLAsString(params.data_url_as_string); +#endif + entry->SetCanLoadLocalResources(params.can_load_local_resources); + break; + default: + NOTREACHED(); + break; + }; + + entry->set_started_from_context_menu(params.started_from_context_menu); + LoadEntry(std::move(entry)); +} +",0,"void NavigationControllerImpl::LoadURLWithParams(const LoadURLParams& params) { + TRACE_EVENT1(""browser,navigation"", + ""NavigationControllerImpl::LoadURLWithParams"", + ""url"", params.url.possibly_invalid_spec()); + if (HandleDebugURL(params.url, params.transition_type)) { + if (!base::CommandLine::ForCurrentProcess()->HasSwitch( + cc::switches::kEnableGpuBenchmarking)) + return; + } + + switch (params.load_type) { + case LOAD_TYPE_DEFAULT: + case LOAD_TYPE_HTTP_POST: + break; + case LOAD_TYPE_DATA: + if (!params.url.SchemeIs(url::kDataScheme)) { + NOTREACHED() << ""Data load must use data scheme.""; + return; + } + break; + default: + NOTREACHED(); + break; + }; + + needs_reload_ = false; + + bool override = false; + switch (params.override_user_agent) { + case UA_OVERRIDE_INHERIT: + override = ShouldKeepOverride(GetLastCommittedEntry()); + break; + case UA_OVERRIDE_TRUE: + override = true; + break; + case UA_OVERRIDE_FALSE: + override = false; + break; + default: + NOTREACHED(); + break; + } + + std::unique_ptr entry; + + int frame_tree_node_id = params.frame_tree_node_id; + if (frame_tree_node_id != -1 || !params.frame_name.empty()) { + FrameTreeNode* node = + params.frame_tree_node_id != -1 + ? delegate_->GetFrameTree()->FindByID(params.frame_tree_node_id) + : delegate_->GetFrameTree()->FindByName(params.frame_name); + if (node && !node->IsMainFrame()) { + DCHECK(GetLastCommittedEntry()); + + frame_tree_node_id = node->frame_tree_node_id(); + + entry = GetLastCommittedEntry()->Clone(); + entry->AddOrUpdateFrameEntry( + node, -1, -1, nullptr, + static_cast(params.source_site_instance.get()), + params.url, params.referrer, params.redirect_chain, PageState(), + ""GET"", -1); + } + } + + if (!entry) { + std::string extra_headers_crlf; + base::ReplaceChars(params.extra_headers, ""\n"", ""\r\n"", &extra_headers_crlf); + entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry( + params.url, params.referrer, params.transition_type, + params.is_renderer_initiated, extra_headers_crlf, browser_context_)); + entry->set_source_site_instance( + static_cast(params.source_site_instance.get())); + entry->SetRedirectChain(params.redirect_chain); + } + + entry->set_frame_tree_node_id(frame_tree_node_id); + if (params.should_replace_current_entry && entries_.size() > 0) + entry->set_should_replace_entry(true); + entry->set_should_clear_history_list(params.should_clear_history_list); + entry->SetIsOverridingUserAgent(override); + entry->set_transferred_global_request_id( + params.transferred_global_request_id); + +#if defined(OS_ANDROID) + if (params.intent_received_timestamp > 0) { + entry->set_intent_received_timestamp( + base::TimeTicks() + + base::TimeDelta::FromMilliseconds(params.intent_received_timestamp)); + } + entry->set_has_user_gesture(params.has_user_gesture); +#endif + + switch (params.load_type) { + case LOAD_TYPE_DEFAULT: + break; + case LOAD_TYPE_HTTP_POST: + entry->SetHasPostData(true); + entry->SetPostData(params.post_data); + break; + case LOAD_TYPE_DATA: + entry->SetBaseURLForDataURL(params.base_url_for_data_url); + entry->SetVirtualURL(params.virtual_url_for_data_url); +#if defined(OS_ANDROID) + entry->SetDataURLAsString(params.data_url_as_string); +#endif + entry->SetCanLoadLocalResources(params.can_load_local_resources); + break; + default: + NOTREACHED(); + break; + }; + + entry->set_started_from_context_menu(params.started_from_context_menu); + LoadEntry(std::move(entry)); +} +","@@ -159,26 +159,6 @@ bool ShouldTreatNavigationAsReload(const NavigationEntry* entry) { + return false; + } + +-// Returns true if the error code indicates an error condition that is not +-// recoverable or navigation is blocked. In such cases, session history +-// navigations to the same NavigationEntry should not attempt to load the +-// original URL. +-// TODO(nasko): Find a better way to distinguish blocked vs failed navigations, +-// as this is a very hacky way of accomplishing this. For now, a handful of +-// error codes are considered, which are more or less known to be cases of +-// blocked navigations. +-bool IsBlockedNavigation(net::Error error_code) { +- switch (error_code) { +- case net::ERR_BLOCKED_BY_CLIENT: +- case net::ERR_BLOCKED_BY_RESPONSE: +- case net::ERR_BLOCKED_BY_XSS_AUDITOR: +- case net::ERR_UNSAFE_REDIRECT: +- return true; +- default: +- return false; +- } +-} +- + } // namespace + + // NavigationControllerImpl ---------------------------------------------------- +@@ -950,24 +930,6 @@ bool NavigationControllerImpl::RendererDidNavigate( + DCHECK(params.page_state == frame_entry->page_state()); + } + +- // When a navigation in the main frame is blocked, it will display an error +- // page. To avoid loading the blocked URL on back/forward navigations, +- // do not store it in the FrameNavigationEntry's URL or PageState. Instead, +- // make it visible to the user as the virtual URL. Store a safe URL +- // (about:blank) as the one to load if the entry is revisited. +- // TODO(nasko): Consider supporting similar behavior for subframe +- // navigations, including AUTO_SUBFRAME. +- if (!rfh->GetParent() && +- IsBlockedNavigation(navigation_handle->GetNetErrorCode())) { +- DCHECK(params.url_is_unreachable); +- active_entry->SetURL(GURL(url::kAboutBlankURL)); +- active_entry->SetVirtualURL(params.url); +- if (frame_entry) { +- frame_entry->SetPageState( +- PageState::CreateFromURL(active_entry->GetURL())); +- } +- } +- + // Use histogram to track memory impact of redirect chain because it's now + // not cleared for committed entries. + size_t redirect_chain_size = 0;",866,1197,2048 +17846,"polkit_backend_interactive_authority_check_authorization (PolkitBackendAuthority *authority, + PolkitSubject *caller, + PolkitSubject *subject, + const gchar *action_id, + PolkitDetails *details, + PolkitCheckAuthorizationFlags flags, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + PolkitBackendInteractiveAuthority *interactive_authority; + PolkitBackendInteractiveAuthorityPrivate *priv; + gchar *caller_str; + gchar *subject_str; + PolkitIdentity *user_of_caller; + PolkitIdentity *user_of_subject; + gchar *user_of_caller_str; + gchar *user_of_subject_str; + PolkitAuthorizationResult *result; + GError *error; + GSimpleAsyncResult *simple; + gboolean has_details; + gchar **detail_keys; + + interactive_authority = POLKIT_BACKEND_INTERACTIVE_AUTHORITY (authority); + priv = POLKIT_BACKEND_INTERACTIVE_AUTHORITY_GET_PRIVATE (interactive_authority); + + error = NULL; + caller_str = NULL; + subject_str = NULL; + user_of_caller = NULL; + user_of_subject = NULL; + user_of_caller_str = NULL; + user_of_subject_str = NULL; + result = NULL; + + simple = g_simple_async_result_new (G_OBJECT (authority), + callback, + user_data, + polkit_backend_interactive_authority_check_authorization); + + /* handle being called from ourselves */ + if (caller == NULL) + { + /* TODO: this is kind of a hack */ + GDBusConnection *system_bus; + system_bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, NULL); + caller = polkit_system_bus_name_new (g_dbus_connection_get_unique_name (system_bus)); + g_object_unref (system_bus); + } + + caller_str = polkit_subject_to_string (caller); + subject_str = polkit_subject_to_string (subject); + + g_debug (""%s is inquiring whether %s is authorized for %s"", + caller_str, + subject_str, + action_id); + action_id); + + user_of_caller = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor, + caller, + &error); + if (error != NULL) + { + g_simple_async_result_complete (simple); + g_object_unref (simple); + g_error_free (error); + goto out; + } + + user_of_caller_str = polkit_identity_to_string (user_of_caller); + g_debug ("" user of caller is %s"", user_of_caller_str); + g_debug ("" user of caller is %s"", user_of_caller_str); + + user_of_subject = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor, + subject, + &error); + if (error != NULL) + { + g_simple_async_result_complete (simple); + g_object_unref (simple); + g_error_free (error); + goto out; + } + + user_of_subject_str = polkit_identity_to_string (user_of_subject); + g_debug ("" user of subject is %s"", user_of_subject_str); + + has_details = FALSE; + if (details != NULL) + { + detail_keys = polkit_details_get_keys (details); + if (detail_keys != NULL) + { + if (g_strv_length (detail_keys) > 0) + has_details = TRUE; + g_strfreev (detail_keys); + } + } + + /* Not anyone is allowed to check that process XYZ is allowed to do ABC. + * We only allow this if, and only if, + * We only allow this if, and only if, + * + * - processes may check for another process owned by the *same* user but not + * if details are passed (otherwise you'd be able to spoof the dialog) + * + * - processes running as uid 0 may check anything and pass any details + * + if (!polkit_identity_equal (user_of_caller, user_of_subject) || has_details) + * then any uid referenced by that annotation is also allowed to check + * to check anything and pass any details + */ + if (!polkit_identity_equal (user_of_caller, user_of_subject) || has_details) + { + if (!may_identity_check_authorization (interactive_authority, action_id, user_of_caller)) + { + ""pass details""); + } + else + { + g_simple_async_result_set_error (simple, + POLKIT_ERROR, + POLKIT_ERROR_NOT_AUTHORIZED, + ""Only trusted callers (e.g. uid 0 or an action owner) can use CheckAuthorization() for "" + ""subjects belonging to other identities""); + } + g_simple_async_result_complete (simple); + g_object_unref (simple); + goto out; + } + } +",1,"polkit_backend_interactive_authority_check_authorization (PolkitBackendAuthority *authority, + PolkitSubject *caller, + PolkitSubject *subject, + const gchar *action_id, + PolkitDetails *details, + PolkitCheckAuthorizationFlags flags, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + PolkitBackendInteractiveAuthority *interactive_authority; + PolkitBackendInteractiveAuthorityPrivate *priv; + gchar *caller_str; + gchar *subject_str; + PolkitIdentity *user_of_caller; + PolkitIdentity *user_of_subject; + gboolean user_of_subject_matches; + gchar *user_of_caller_str; + gchar *user_of_subject_str; + PolkitAuthorizationResult *result; + GError *error; + GSimpleAsyncResult *simple; + gboolean has_details; + gchar **detail_keys; + + interactive_authority = POLKIT_BACKEND_INTERACTIVE_AUTHORITY (authority); + priv = POLKIT_BACKEND_INTERACTIVE_AUTHORITY_GET_PRIVATE (interactive_authority); + + error = NULL; + caller_str = NULL; + subject_str = NULL; + user_of_caller = NULL; + user_of_subject = NULL; + user_of_caller_str = NULL; + user_of_subject_str = NULL; + result = NULL; + + simple = g_simple_async_result_new (G_OBJECT (authority), + callback, + user_data, + polkit_backend_interactive_authority_check_authorization); + + /* handle being called from ourselves */ + if (caller == NULL) + { + /* TODO: this is kind of a hack */ + GDBusConnection *system_bus; + system_bus = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, NULL); + caller = polkit_system_bus_name_new (g_dbus_connection_get_unique_name (system_bus)); + g_object_unref (system_bus); + } + + caller_str = polkit_subject_to_string (caller); + subject_str = polkit_subject_to_string (subject); + + g_debug (""%s is inquiring whether %s is authorized for %s"", + caller_str, + subject_str, + action_id); + action_id); + + user_of_caller = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor, + caller, NULL, + &error); + if (error != NULL) + { + g_simple_async_result_complete (simple); + g_object_unref (simple); + g_error_free (error); + goto out; + } + + user_of_caller_str = polkit_identity_to_string (user_of_caller); + g_debug ("" user of caller is %s"", user_of_caller_str); + g_debug ("" user of caller is %s"", user_of_caller_str); + + user_of_subject = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor, + subject, &user_of_subject_matches, + &error); + if (error != NULL) + { + g_simple_async_result_complete (simple); + g_object_unref (simple); + g_error_free (error); + goto out; + } + + user_of_subject_str = polkit_identity_to_string (user_of_subject); + g_debug ("" user of subject is %s"", user_of_subject_str); + + has_details = FALSE; + if (details != NULL) + { + detail_keys = polkit_details_get_keys (details); + if (detail_keys != NULL) + { + if (g_strv_length (detail_keys) > 0) + has_details = TRUE; + g_strfreev (detail_keys); + } + } + + /* Not anyone is allowed to check that process XYZ is allowed to do ABC. + * We only allow this if, and only if, + * We only allow this if, and only if, + * + * - processes may check for another process owned by the *same* user but not + * if details are passed (otherwise you'd be able to spoof the dialog); + * the caller supplies the user_of_subject value, so we additionally + * require it to match at least at one point in time (via + * user_of_subject_matches). + * + * - processes running as uid 0 may check anything and pass any details + * + if (!polkit_identity_equal (user_of_caller, user_of_subject) || has_details) + * then any uid referenced by that annotation is also allowed to check + * to check anything and pass any details + */ + if (!user_of_subject_matches + || !polkit_identity_equal (user_of_caller, user_of_subject) + || has_details) + { + if (!may_identity_check_authorization (interactive_authority, action_id, user_of_caller)) + { + ""pass details""); + } + else + { + g_simple_async_result_set_error (simple, + POLKIT_ERROR, + POLKIT_ERROR_NOT_AUTHORIZED, + ""Only trusted callers (e.g. uid 0 or an action owner) can use CheckAuthorization() for "" + ""subjects belonging to other identities""); + } + g_simple_async_result_complete (simple); + g_object_unref (simple); + goto out; + } + } +","@@ -575,7 +575,7 @@ log_result (PolkitBackendInteractiveAuthority *authority, + if (polkit_authorization_result_get_is_authorized (result)) + log_result_str = ""ALLOWING""; + +- user_of_subject = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor, subject, NULL); ++ user_of_subject = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor, subject, NULL, NULL); + + subject_str = polkit_subject_to_string (subject); + +@@ -847,6 +847,7 @@ polkit_backend_interactive_authority_check_authorization (PolkitBackendAuthority + gchar *subject_str; + PolkitIdentity *user_of_caller; + PolkitIdentity *user_of_subject; ++ gboolean user_of_subject_matches; + gchar *user_of_caller_str; + gchar *user_of_subject_str; + PolkitAuthorizationResult *result; +@@ -892,7 +893,7 @@ polkit_backend_interactive_authority_check_authorization (PolkitBackendAuthority + action_id); + + user_of_caller = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor, +- caller, ++ caller, NULL, + &error); + if (error != NULL) + { +@@ -907,7 +908,7 @@ polkit_backend_interactive_authority_check_authorization (PolkitBackendAuthority + g_debug ("" user of caller is %s"", user_of_caller_str); + + user_of_subject = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor, +- subject, ++ subject, &user_of_subject_matches, + &error); + if (error != NULL) + { +@@ -937,7 +938,10 @@ polkit_backend_interactive_authority_check_authorization (PolkitBackendAuthority + * We only allow this if, and only if, + * + * - processes may check for another process owned by the *same* user but not +- * if details are passed (otherwise you'd be able to spoof the dialog) ++ * if details are passed (otherwise you'd be able to spoof the dialog); ++ * the caller supplies the user_of_subject value, so we additionally ++ * require it to match at least at one point in time (via ++ * user_of_subject_matches). + * + * - processes running as uid 0 may check anything and pass any details + * +@@ -945,7 +949,9 @@ polkit_backend_interactive_authority_check_authorization (PolkitBackendAuthority + * then any uid referenced by that annotation is also allowed to check + * to check anything and pass any details + */ +- if (!polkit_identity_equal (user_of_caller, user_of_subject) || has_details) ++ if (!user_of_subject_matches ++ || !polkit_identity_equal (user_of_caller, user_of_subject) ++ || has_details) + { + if (!may_identity_check_authorization (interactive_authority, action_id, user_of_caller)) + { +@@ -1110,9 +1116,10 @@ check_authorization_sync (PolkitBackendAuthority *authority, + goto out; + } + +- /* every subject has a user */ ++ /* every subject has a user; this is supplied by the client, so we rely ++ * on the caller to validate its acceptability. */ + user_of_subject = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor, +- subject, ++ subject, NULL, + error); + if (user_of_subject == NULL) + goto out; +@@ -2480,6 +2487,7 @@ polkit_backend_interactive_authority_register_authentication_agent (PolkitBacken + PolkitSubject *session_for_caller; + PolkitIdentity *user_of_caller; + PolkitIdentity *user_of_subject; ++ gboolean user_of_subject_matches; + AuthenticationAgent *agent; + gboolean ret; + gchar *caller_cmdline; +@@ -2532,7 +2540,7 @@ polkit_backend_interactive_authority_register_authentication_agent (PolkitBacken + goto out; + } + +- user_of_caller = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor, caller, NULL); ++ user_of_caller = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor, caller, NULL, NULL); + if (user_of_caller == NULL) + { + g_set_error (error, +@@ -2541,7 +2549,7 @@ polkit_backend_interactive_authority_register_authentication_agent (PolkitBacken + ""Cannot determine user of caller""); + goto out; + } +- user_of_subject = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor, subject, NULL); ++ user_of_subject = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor, subject, &user_of_subject_matches, NULL); + if (user_of_subject == NULL) + { + g_set_error (error, +@@ -2550,7 +2558,8 @@ polkit_backend_interactive_authority_register_authentication_agent (PolkitBacken + ""Cannot determine user of subject""); + goto out; + } +- if (!polkit_identity_equal (user_of_caller, user_of_subject)) ++ if (!user_of_subject_matches ++ || !polkit_identity_equal (user_of_caller, user_of_subject)) + { + if (identity_is_root_user (user_of_caller)) + { +@@ -2643,6 +2652,7 @@ polkit_backend_interactive_authority_unregister_authentication_agent (PolkitBack + PolkitSubject *session_for_caller; + PolkitIdentity *user_of_caller; + PolkitIdentity *user_of_subject; ++ gboolean user_of_subject_matches; + AuthenticationAgent *agent; + gboolean ret; + gchar *scope_str; +@@ -2691,7 +2701,7 @@ polkit_backend_interactive_authority_unregister_authentication_agent (PolkitBack + goto out; + } + +- user_of_caller = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor, caller, NULL); ++ user_of_caller = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor, caller, NULL, NULL); + if (user_of_caller == NULL) + { + g_set_error (error, +@@ -2700,7 +2710,7 @@ polkit_backend_interactive_authority_unregister_authentication_agent (PolkitBack + ""Cannot determine user of caller""); + goto out; + } +- user_of_subject = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor, subject, NULL); ++ user_of_subject = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor, subject, &user_of_subject_matches, NULL); + if (user_of_subject == NULL) + { + g_set_error (error, +@@ -2709,7 +2719,8 @@ polkit_backend_interactive_authority_unregister_authentication_agent (PolkitBack + ""Cannot determine user of subject""); + goto out; + } +- if (!polkit_identity_equal (user_of_caller, user_of_subject)) ++ if (!user_of_subject_matches ++ || !polkit_identity_equal (user_of_caller, user_of_subject)) + { + if (identity_is_root_user (user_of_caller)) + { +@@ -2819,7 +2830,7 @@ polkit_backend_interactive_authority_authentication_agent_response (PolkitBacken + identity_str); + + user_of_caller = polkit_backend_session_monitor_get_user_for_subject (priv->session_monitor, +- caller, ++ caller, NULL, + error); + if (user_of_caller == NULL) + goto out;",1026,1357,2048 +8877,"MagickExport MagickBooleanType ClutImage(Image *image,const Image *clut_image, + const PixelInterpolateMethod method,ExceptionInfo *exception) +{ +#define ClutImageTag ""Clut/Image"" + + CacheView + *clut_view, + *image_view; + + MagickBooleanType + status; + + MagickOffsetType + progress; + + PixelInfo + *clut_map; + + register ssize_t + i; + + ssize_t adjust, + y; + + assert(image != (Image *) NULL); + assert(image->signature == MagickCoreSignature); + if (image->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); + assert(clut_image != (Image *) NULL); + assert(clut_image->signature == MagickCoreSignature); + if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) + return(MagickFalse); + if ((IsGrayColorspace(image->colorspace) != MagickFalse) && + (IsGrayColorspace(clut_image->colorspace) == MagickFalse)) + (void) SetImageColorspace(image,sRGBColorspace,exception); + clut_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*clut_map)); + if (clut_map == (PixelInfo *) NULL) + ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", + image->filename); + /* + Clut image. + */ + status=MagickTrue; + progress=0; + adjust=(ssize_t) (clut_image->interpolate == IntegerInterpolatePixel ? 0 : 1); + clut_view=AcquireVirtualCacheView(clut_image,exception); + for (i=0; i <= (ssize_t) MaxMap; i++) + { + GetPixelInfo(clut_image,clut_map+i); + status=InterpolatePixelInfo(clut_image,clut_view,method, + (double) i*(clut_image->columns-adjust)/MaxMap,(double) i* + (clut_image->rows-adjust)/MaxMap,clut_map+i,exception); + if (status == MagickFalse) + break; + } + clut_view=DestroyCacheView(clut_view); + image_view=AcquireAuthenticCacheView(image,exception); +#if defined(MAGICKCORE_OPENMP_SUPPORT) + #pragma omp parallel for schedule(static) shared(progress,status) \ + magick_number_threads(image,image,image->rows,1) +#endif + for (y=0; y < (ssize_t) image->rows; y++) + { + PixelInfo + pixel; + + 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; + } + GetPixelInfo(image,&pixel); + for (x=0; x < (ssize_t) image->columns; x++) + { + PixelTrait + traits; + + GetPixelInfoPixel(image,q,&pixel); + traits=GetPixelChannelTraits(image,RedPixelChannel); + if ((traits & UpdatePixelTrait) != 0) + pixel.red=clut_map[ScaleQuantumToMap(ClampToQuantum( + pixel.red))].red; + traits=GetPixelChannelTraits(image,GreenPixelChannel); + if ((traits & UpdatePixelTrait) != 0) + pixel.green=clut_map[ScaleQuantumToMap(ClampToQuantum( + pixel.green))].green; + traits=GetPixelChannelTraits(image,BluePixelChannel); + if ((traits & UpdatePixelTrait) != 0) + pixel.blue=clut_map[ScaleQuantumToMap(ClampToQuantum( + pixel.blue))].blue; + traits=GetPixelChannelTraits(image,BlackPixelChannel); + if ((traits & UpdatePixelTrait) != 0) + pixel.black=clut_map[ScaleQuantumToMap(ClampToQuantum( + pixel.black))].black; + traits=GetPixelChannelTraits(image,AlphaPixelChannel); + if ((traits & UpdatePixelTrait) != 0) + pixel.alpha=clut_map[ScaleQuantumToMap(ClampToQuantum( + pixel.alpha))].alpha; + SetPixelViaPixelInfo(image,&pixel,q); + 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 atomic +#endif + progress++; + proceed=SetImageProgress(image,ClutImageTag,progress,image->rows); + if (proceed == MagickFalse) + status=MagickFalse; + } + } + image_view=DestroyCacheView(image_view); + clut_map=(PixelInfo *) RelinquishMagickMemory(clut_map); + if ((clut_image->alpha_trait != UndefinedPixelTrait) && + ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)) + (void) SetImageAlphaChannel(image,ActivateAlphaChannel,exception); + return(status); +} +",0,"MagickExport MagickBooleanType ClutImage(Image *image,const Image *clut_image, + const PixelInterpolateMethod method,ExceptionInfo *exception) +{ +#define ClutImageTag ""Clut/Image"" + + CacheView + *clut_view, + *image_view; + + MagickBooleanType + status; + + MagickOffsetType + progress; + + PixelInfo + *clut_map; + + register ssize_t + i; + + ssize_t adjust, + y; + + assert(image != (Image *) NULL); + assert(image->signature == MagickCoreSignature); + if (image->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); + assert(clut_image != (Image *) NULL); + assert(clut_image->signature == MagickCoreSignature); + if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) + return(MagickFalse); + if ((IsGrayColorspace(image->colorspace) != MagickFalse) && + (IsGrayColorspace(clut_image->colorspace) == MagickFalse)) + (void) SetImageColorspace(image,sRGBColorspace,exception); + clut_map=(PixelInfo *) AcquireQuantumMemory(MaxMap+1UL,sizeof(*clut_map)); + if (clut_map == (PixelInfo *) NULL) + ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", + image->filename); + /* + Clut image. + */ + status=MagickTrue; + progress=0; + adjust=(ssize_t) (clut_image->interpolate == IntegerInterpolatePixel ? 0 : 1); + clut_view=AcquireVirtualCacheView(clut_image,exception); + for (i=0; i <= (ssize_t) MaxMap; i++) + { + GetPixelInfo(clut_image,clut_map+i); + status=InterpolatePixelInfo(clut_image,clut_view,method, + (double) i*(clut_image->columns-adjust)/MaxMap,(double) i* + (clut_image->rows-adjust)/MaxMap,clut_map+i,exception); + if (status == MagickFalse) + break; + } + clut_view=DestroyCacheView(clut_view); + image_view=AcquireAuthenticCacheView(image,exception); +#if defined(MAGICKCORE_OPENMP_SUPPORT) + #pragma omp parallel for schedule(static) shared(progress,status) \ + magick_number_threads(image,image,image->rows,1) +#endif + for (y=0; y < (ssize_t) image->rows; y++) + { + PixelInfo + pixel; + + 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; + } + GetPixelInfo(image,&pixel); + for (x=0; x < (ssize_t) image->columns; x++) + { + PixelTrait + traits; + + GetPixelInfoPixel(image,q,&pixel); + traits=GetPixelChannelTraits(image,RedPixelChannel); + if ((traits & UpdatePixelTrait) != 0) + pixel.red=clut_map[ScaleQuantumToMap(ClampToQuantum( + pixel.red))].red; + traits=GetPixelChannelTraits(image,GreenPixelChannel); + if ((traits & UpdatePixelTrait) != 0) + pixel.green=clut_map[ScaleQuantumToMap(ClampToQuantum( + pixel.green))].green; + traits=GetPixelChannelTraits(image,BluePixelChannel); + if ((traits & UpdatePixelTrait) != 0) + pixel.blue=clut_map[ScaleQuantumToMap(ClampToQuantum( + pixel.blue))].blue; + traits=GetPixelChannelTraits(image,BlackPixelChannel); + if ((traits & UpdatePixelTrait) != 0) + pixel.black=clut_map[ScaleQuantumToMap(ClampToQuantum( + pixel.black))].black; + traits=GetPixelChannelTraits(image,AlphaPixelChannel); + if ((traits & UpdatePixelTrait) != 0) + pixel.alpha=clut_map[ScaleQuantumToMap(ClampToQuantum( + pixel.alpha))].alpha; + SetPixelViaPixelInfo(image,&pixel,q); + 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 atomic +#endif + progress++; + proceed=SetImageProgress(image,ClutImageTag,progress,image->rows); + if (proceed == MagickFalse) + status=MagickFalse; + } + } + image_view=DestroyCacheView(image_view); + clut_map=(PixelInfo *) RelinquishMagickMemory(clut_map); + if ((clut_image->alpha_trait != UndefinedPixelTrait) && + ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)) + (void) SetImageAlphaChannel(image,ActivateAlphaChannel,exception); + return(status); +} +","@@ -1973,7 +1973,7 @@ MagickExport Image *EnhanceImage(const Image *image,ExceptionInfo *exception) + pixel.black=((aggregate.black+total_weight/2.0)/total_weight); + pixel.alpha=((aggregate.alpha+total_weight/2.0)/total_weight); + } +- SetPixelViaPixelInfo(image,&pixel,q); ++ SetPixelViaPixelInfo(enhance_image,&pixel,q); + p+=GetPixelChannels(image); + q+=GetPixelChannels(enhance_image); + }",1159,1490,2048 +17950,"cifs_iovec_write(struct file *file, const struct iovec *iov, + unsigned long nr_segs, loff_t *poffset) + { + unsigned long nr_pages, i; + size_t copied, len, cur_len; + ssize_t total_written = 0; + loff_t offset; + struct iov_iter it; + struct cifsFileInfo *open_file; + struct cifs_tcon *tcon; + struct cifs_sb_info *cifs_sb; + struct cifs_writedata *wdata, *tmp; + struct list_head wdata_list; + int rc; + pid_t pid; + + len = iov_length(iov, nr_segs); + if (!len) + return 0; + + rc = generic_write_checks(file, poffset, &len, 0); + if (rc) + return rc; + + INIT_LIST_HEAD(&wdata_list); + cifs_sb = CIFS_SB(file->f_path.dentry->d_sb); + open_file = file->private_data; + tcon = tlink_tcon(open_file->tlink); + + if (!tcon->ses->server->ops->async_writev) + return -ENOSYS; + + offset = *poffset; + + if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_RWPIDFORWARD) + pid = open_file->pid; + else + pid = current->tgid; + + iov_iter_init(&it, iov, nr_segs, len, 0); + do { + size_t save_len; + + nr_pages = get_numpages(cifs_sb->wsize, len, &cur_len); + wdata = cifs_writedata_alloc(nr_pages, + cifs_uncached_writev_complete); + if (!wdata) { + rc = -ENOMEM; + break; + } + + rc = cifs_write_allocate_pages(wdata->pages, nr_pages); + if (rc) { + kfree(wdata); + break; + } + + save_len = cur_len; + for (i = 0; i < nr_pages; i++) { + copied = min_t(const size_t, cur_len, PAGE_SIZE); + copied = iov_iter_copy_from_user(wdata->pages[i], &it, + 0, copied); + cur_len -= copied; + iov_iter_advance(&it, copied); + } + cur_len = save_len - cur_len; + + wdata->sync_mode = WB_SYNC_ALL; + wdata->nr_pages = nr_pages; + wdata->offset = (__u64)offset; + wdata->cfile = cifsFileInfo_get(open_file); + wdata->pid = pid; + wdata->bytes = cur_len; + wdata->pagesz = PAGE_SIZE; + wdata->tailsz = cur_len - ((nr_pages - 1) * PAGE_SIZE); + rc = cifs_uncached_retry_writev(wdata); + if (rc) { + kref_put(&wdata->refcount, + cifs_uncached_writedata_release); + break; + } + + list_add_tail(&wdata->list, &wdata_list); + offset += cur_len; + len -= cur_len; + } while (len > 0); + + /* + * If at least one write was successfully sent, then discard any rc + * value from the later writes. If the other write succeeds, then + * we'll end up returning whatever was written. If it fails, then + * we'll get a new rc value from that. + */ + if (!list_empty(&wdata_list)) + rc = 0; + + /* + * Wait for and collect replies for any successful sends in order of + * increasing offset. Once an error is hit or we get a fatal signal + * while waiting, then return without waiting for any more replies. + */ +restart_loop: + list_for_each_entry_safe(wdata, tmp, &wdata_list, list) { + if (!rc) { + /* FIXME: freezable too? */ + rc = wait_for_completion_killable(&wdata->done); + if (rc) + rc = -EINTR; + else if (wdata->result) + rc = wdata->result; + else + total_written += wdata->bytes; + + /* resend call if it's a retryable error */ + if (rc == -EAGAIN) { + rc = cifs_uncached_retry_writev(wdata); + goto restart_loop; + } + } + list_del_init(&wdata->list); + kref_put(&wdata->refcount, cifs_uncached_writedata_release); + } + + if (total_written > 0) + *poffset += total_written; + + cifs_stats_bytes_written(tcon, total_written); + return total_written ? total_written : (ssize_t)rc; +} +",1,"cifs_iovec_write(struct file *file, const struct iovec *iov, + unsigned long nr_segs, loff_t *poffset) + { + unsigned long nr_pages, i; + size_t bytes, copied, len, cur_len; + ssize_t total_written = 0; + loff_t offset; + struct iov_iter it; + struct cifsFileInfo *open_file; + struct cifs_tcon *tcon; + struct cifs_sb_info *cifs_sb; + struct cifs_writedata *wdata, *tmp; + struct list_head wdata_list; + int rc; + pid_t pid; + + len = iov_length(iov, nr_segs); + if (!len) + return 0; + + rc = generic_write_checks(file, poffset, &len, 0); + if (rc) + return rc; + + INIT_LIST_HEAD(&wdata_list); + cifs_sb = CIFS_SB(file->f_path.dentry->d_sb); + open_file = file->private_data; + tcon = tlink_tcon(open_file->tlink); + + if (!tcon->ses->server->ops->async_writev) + return -ENOSYS; + + offset = *poffset; + + if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_RWPIDFORWARD) + pid = open_file->pid; + else + pid = current->tgid; + + iov_iter_init(&it, iov, nr_segs, len, 0); + do { + size_t save_len; + + nr_pages = get_numpages(cifs_sb->wsize, len, &cur_len); + wdata = cifs_writedata_alloc(nr_pages, + cifs_uncached_writev_complete); + if (!wdata) { + rc = -ENOMEM; + break; + } + + rc = cifs_write_allocate_pages(wdata->pages, nr_pages); + if (rc) { + kfree(wdata); + break; + } + + save_len = cur_len; + for (i = 0; i < nr_pages; i++) { + bytes = min_t(const size_t, cur_len, PAGE_SIZE); + copied = iov_iter_copy_from_user(wdata->pages[i], &it, + 0, bytes); + cur_len -= copied; + iov_iter_advance(&it, copied); + /* + * If we didn't copy as much as we expected, then that + * may mean we trod into an unmapped area. Stop copying + * at that point. On the next pass through the big + * loop, we'll likely end up getting a zero-length + * write and bailing out of it. + */ + if (copied < bytes) + break; + } + cur_len = save_len - cur_len; + + /* + * If we have no data to send, then that probably means that + * the copy above failed altogether. That's most likely because + * the address in the iovec was bogus. Set the rc to -EFAULT, + * free anything we allocated and bail out. + */ + if (!cur_len) { + for (i = 0; i < nr_pages; i++) + put_page(wdata->pages[i]); + kfree(wdata); + rc = -EFAULT; + break; + } + + /* + * i + 1 now represents the number of pages we actually used in + * the copy phase above. Bring nr_pages down to that, and free + * any pages that we didn't use. + */ + for ( ; nr_pages > i + 1; nr_pages--) + put_page(wdata->pages[nr_pages - 1]); + + wdata->sync_mode = WB_SYNC_ALL; + wdata->nr_pages = nr_pages; + wdata->offset = (__u64)offset; + wdata->cfile = cifsFileInfo_get(open_file); + wdata->pid = pid; + wdata->bytes = cur_len; + wdata->pagesz = PAGE_SIZE; + wdata->tailsz = cur_len - ((nr_pages - 1) * PAGE_SIZE); + rc = cifs_uncached_retry_writev(wdata); + if (rc) { + kref_put(&wdata->refcount, + cifs_uncached_writedata_release); + break; + } + + list_add_tail(&wdata->list, &wdata_list); + offset += cur_len; + len -= cur_len; + } while (len > 0); + + /* + * If at least one write was successfully sent, then discard any rc + * value from the later writes. If the other write succeeds, then + * we'll end up returning whatever was written. If it fails, then + * we'll get a new rc value from that. + */ + if (!list_empty(&wdata_list)) + rc = 0; + + /* + * Wait for and collect replies for any successful sends in order of + * increasing offset. Once an error is hit or we get a fatal signal + * while waiting, then return without waiting for any more replies. + */ +restart_loop: + list_for_each_entry_safe(wdata, tmp, &wdata_list, list) { + if (!rc) { + /* FIXME: freezable too? */ + rc = wait_for_completion_killable(&wdata->done); + if (rc) + rc = -EINTR; + else if (wdata->result) + rc = wdata->result; + else + total_written += wdata->bytes; + + /* resend call if it's a retryable error */ + if (rc == -EAGAIN) { + rc = cifs_uncached_retry_writev(wdata); + goto restart_loop; + } + } + list_del_init(&wdata->list); + kref_put(&wdata->refcount, cifs_uncached_writedata_release); + } + + if (total_written > 0) + *poffset += total_written; + + cifs_stats_bytes_written(tcon, total_written); + return total_written ? total_written : (ssize_t)rc; +} +","@@ -2389,7 +2389,7 @@ cifs_iovec_write(struct file *file, const struct iovec *iov, + unsigned long nr_segs, loff_t *poffset) + { + unsigned long nr_pages, i; +- size_t copied, len, cur_len; ++ size_t bytes, copied, len, cur_len; + ssize_t total_written = 0; + loff_t offset; + struct iov_iter it; +@@ -2444,14 +2444,45 @@ cifs_iovec_write(struct file *file, const struct iovec *iov, + + save_len = cur_len; + for (i = 0; i < nr_pages; i++) { +- copied = min_t(const size_t, cur_len, PAGE_SIZE); ++ bytes = min_t(const size_t, cur_len, PAGE_SIZE); + copied = iov_iter_copy_from_user(wdata->pages[i], &it, +- 0, copied); ++ 0, bytes); + cur_len -= copied; + iov_iter_advance(&it, copied); ++ /* ++ * If we didn't copy as much as we expected, then that ++ * may mean we trod into an unmapped area. Stop copying ++ * at that point. On the next pass through the big ++ * loop, we'll likely end up getting a zero-length ++ * write and bailing out of it. ++ */ ++ if (copied < bytes) ++ break; + } + cur_len = save_len - cur_len; + ++ /* ++ * If we have no data to send, then that probably means that ++ * the copy above failed altogether. That's most likely because ++ * the address in the iovec was bogus. Set the rc to -EFAULT, ++ * free anything we allocated and bail out. ++ */ ++ if (!cur_len) { ++ for (i = 0; i < nr_pages; i++) ++ put_page(wdata->pages[i]); ++ kfree(wdata); ++ rc = -EFAULT; ++ break; ++ } ++ ++ /* ++ * i + 1 now represents the number of pages we actually used in ++ * the copy phase above. Bring nr_pages down to that, and free ++ * any pages that we didn't use. ++ */ ++ for ( ; nr_pages > i + 1; nr_pages--) ++ put_page(wdata->pages[nr_pages - 1]); ++ + wdata->sync_mode = WB_SYNC_ALL; + wdata->nr_pages = nr_pages; + wdata->offset = (__u64)offset;",1023,1354,2048 +18730,"static vpx_codec_err_t vp8_decode(vpx_codec_alg_priv_t *ctx, + const uint8_t *data, + unsigned int data_sz, + void *user_priv, + long deadline) +{ + vpx_codec_err_t res = VPX_CODEC_OK; + unsigned int resolution_change = 0; + unsigned int w, h; + + if (!ctx->fragments.enabled && (data == NULL && data_sz == 0)) + { + return 0; + } + + /* Update the input fragment data */ + if(update_fragments(ctx, data, data_sz, &res) <= 0) + return res; + + /* Determine the stream parameters. Note that we rely on peek_si to + * validate that we have a buffer that does not wrap around the top + * of the heap. + */ + w = ctx->si.w; + h = ctx->si.h; + + res = vp8_peek_si_internal(ctx->fragments.ptrs[0], ctx->fragments.sizes[0], + &ctx->si, ctx->decrypt_cb, ctx->decrypt_state); + + if((res == VPX_CODEC_UNSUP_BITSTREAM) && !ctx->si.is_kf) + { + /* the peek function returns an error for non keyframes, however for + * this case, it is not an error */ + res = VPX_CODEC_OK; + } + + if(!ctx->decoder_init && !ctx->si.is_kf) + res = VPX_CODEC_UNSUP_BITSTREAM; + + if ((ctx->si.h != h) || (ctx->si.w != w)) + resolution_change = 1; + + /* Initialize the decoder instance on the first frame*/ + if (!res && !ctx->decoder_init) + { + VP8D_CONFIG oxcf; + + oxcf.Width = ctx->si.w; + oxcf.Height = ctx->si.h; + oxcf.Version = 9; + oxcf.postprocess = 0; + oxcf.max_threads = ctx->cfg.threads; + oxcf.error_concealment = + (ctx->base.init_flags & VPX_CODEC_USE_ERROR_CONCEALMENT); + + /* If postprocessing was enabled by the application and a + * configuration has not been provided, default it. + */ + if (!ctx->postproc_cfg_set + && (ctx->base.init_flags & VPX_CODEC_USE_POSTPROC)) { + ctx->postproc_cfg.post_proc_flag = + VP8_DEBLOCK | VP8_DEMACROBLOCK | VP8_MFQE; + ctx->postproc_cfg.deblocking_level = 4; + ctx->postproc_cfg.noise_level = 0; + } + + res = vp8_create_decoder_instances(&ctx->yv12_frame_buffers, &oxcf); + ctx->decoder_init = 1; + } + + /* Set these even if already initialized. The caller may have changed the + * decrypt config between frames. + */ + if (ctx->decoder_init) { + ctx->yv12_frame_buffers.pbi[0]->decrypt_cb = ctx->decrypt_cb; + ctx->yv12_frame_buffers.pbi[0]->decrypt_state = ctx->decrypt_state; + } + + if (!res) + { + VP8D_COMP *pbi = ctx->yv12_frame_buffers.pbi[0]; + if (resolution_change) + { + VP8_COMMON *const pc = & pbi->common; + MACROBLOCKD *const xd = & pbi->mb; +#if CONFIG_MULTITHREAD + int i; +#endif + pc->Width = ctx->si.w; + pc->Height = ctx->si.h; + { + int prev_mb_rows = pc->mb_rows; + + + if (setjmp(pbi->common.error.jmp)) + { + pbi->common.error.setjmp = 0; + vp8_clear_system_state(); + /* same return value as used in vp8dx_receive_compressed_data */ + return -1; + } + + pbi->common.error.setjmp = 1; + + if (pc->Width <= 0) + { + pc->Width = w; + vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME, + ""Invalid frame width""); + } + + if (pc->Height <= 0) + { + pc->Height = h; + vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME, + ""Invalid frame height""); + } + + if (vp8_alloc_frame_buffers(pc, pc->Width, pc->Height)) + vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR, + ""Failed to allocate frame buffers""); + + xd->pre = pc->yv12_fb[pc->lst_fb_idx]; + xd->dst = pc->yv12_fb[pc->new_fb_idx]; + +#if CONFIG_MULTITHREAD + for (i = 0; i < pbi->allocated_decoding_thread_count; i++) + { + pbi->mb_row_di[i].mbd.dst = pc->yv12_fb[pc->new_fb_idx]; + vp8_build_block_doffsets(&pbi->mb_row_di[i].mbd); + } +#endif + vp8_build_block_doffsets(&pbi->mb); + + /* allocate memory for last frame MODE_INFO array */ +#if CONFIG_ERROR_CONCEALMENT + + if (pbi->ec_enabled) + { + /* old prev_mip was released by vp8_de_alloc_frame_buffers() + * called in vp8_alloc_frame_buffers() */ + pc->prev_mip = vpx_calloc( + (pc->mb_cols + 1) * (pc->mb_rows + 1), + sizeof(MODE_INFO)); + + if (!pc->prev_mip) + { + vp8_de_alloc_frame_buffers(pc); + vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR, + ""Failed to allocate"" + ""last frame MODE_INFO array""); + } + + pc->prev_mi = pc->prev_mip + pc->mode_info_stride + 1; + + if (vp8_alloc_overlap_lists(pbi)) + vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR, + ""Failed to allocate overlap lists "" + ""for error concealment""); + } + +#endif + +#if CONFIG_MULTITHREAD + if (pbi->b_multithreaded_rd) + vp8mt_alloc_temp_buffers(pbi, pc->Width, prev_mb_rows); +#else + (void)prev_mb_rows; +#endif + } + + pbi->common.error.setjmp = 0; + + /* required to get past the first get_free_fb() call */ + pbi->common.fb_idx_ref_cnt[0] = 0; + } + + /* update the pbi fragment data */ + pbi->fragments = ctx->fragments; + + ctx->user_priv = user_priv; + if (vp8dx_receive_compressed_data(pbi, data_sz, data, deadline)) + { + res = update_error_state(ctx, &pbi->common.error); + } + + /* get ready for the next series of fragments */ + ctx->fragments.count = 0; + } + + return res; +} +",1,"static vpx_codec_err_t vp8_decode(vpx_codec_alg_priv_t *ctx, + const uint8_t *data, + unsigned int data_sz, + void *user_priv, + long deadline) +{ + vpx_codec_err_t res = VPX_CODEC_OK; + unsigned int resolution_change = 0; + unsigned int w, h; + + if (!ctx->fragments.enabled && (data == NULL && data_sz == 0)) + { + return 0; + } + + /* Update the input fragment data */ + if(update_fragments(ctx, data, data_sz, &res) <= 0) + return res; + + /* Determine the stream parameters. Note that we rely on peek_si to + * validate that we have a buffer that does not wrap around the top + * of the heap. + */ + w = ctx->si.w; + h = ctx->si.h; + + res = vp8_peek_si_internal(ctx->fragments.ptrs[0], ctx->fragments.sizes[0], + &ctx->si, ctx->decrypt_cb, ctx->decrypt_state); + + if((res == VPX_CODEC_UNSUP_BITSTREAM) && !ctx->si.is_kf) + { + /* the peek function returns an error for non keyframes, however for + * this case, it is not an error */ + res = VPX_CODEC_OK; + } + + if(!ctx->decoder_init && !ctx->si.is_kf) + res = VPX_CODEC_UNSUP_BITSTREAM; + + if ((ctx->si.h != h) || (ctx->si.w != w)) + resolution_change = 1; + + /* Initialize the decoder instance on the first frame*/ + if (!res && !ctx->decoder_init) + { + VP8D_CONFIG oxcf; + + oxcf.Width = ctx->si.w; + oxcf.Height = ctx->si.h; + oxcf.Version = 9; + oxcf.postprocess = 0; + oxcf.max_threads = ctx->cfg.threads; + oxcf.error_concealment = + (ctx->base.init_flags & VPX_CODEC_USE_ERROR_CONCEALMENT); + + /* If postprocessing was enabled by the application and a + * configuration has not been provided, default it. + */ + if (!ctx->postproc_cfg_set + && (ctx->base.init_flags & VPX_CODEC_USE_POSTPROC)) { + ctx->postproc_cfg.post_proc_flag = + VP8_DEBLOCK | VP8_DEMACROBLOCK | VP8_MFQE; + ctx->postproc_cfg.deblocking_level = 4; + ctx->postproc_cfg.noise_level = 0; + } + + res = vp8_create_decoder_instances(&ctx->yv12_frame_buffers, &oxcf); + ctx->decoder_init = 1; + } + + /* Set these even if already initialized. The caller may have changed the + * decrypt config between frames. + */ + if (ctx->decoder_init) { + ctx->yv12_frame_buffers.pbi[0]->decrypt_cb = ctx->decrypt_cb; + ctx->yv12_frame_buffers.pbi[0]->decrypt_state = ctx->decrypt_state; + } + + if (!res) + { + VP8D_COMP *pbi = ctx->yv12_frame_buffers.pbi[0]; + if (resolution_change) + { + VP8_COMMON *const pc = & pbi->common; + MACROBLOCKD *const xd = & pbi->mb; +#if CONFIG_MULTITHREAD + int i; +#endif + pc->Width = ctx->si.w; + pc->Height = ctx->si.h; + { + int prev_mb_rows = pc->mb_rows; + + + if (setjmp(pbi->common.error.jmp)) + { + pbi->common.error.setjmp = 0; + /* on failure clear the cached resolution to ensure a full + * reallocation is attempted on resync. */ + ctx->si.w = 0; + ctx->si.h = 0; + vp8_clear_system_state(); + /* same return value as used in vp8dx_receive_compressed_data */ + return -1; + } + + pbi->common.error.setjmp = 1; + + if (pc->Width <= 0) + { + pc->Width = w; + vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME, + ""Invalid frame width""); + } + + if (pc->Height <= 0) + { + pc->Height = h; + vpx_internal_error(&pc->error, VPX_CODEC_CORRUPT_FRAME, + ""Invalid frame height""); + } + + if (vp8_alloc_frame_buffers(pc, pc->Width, pc->Height)) + vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR, + ""Failed to allocate frame buffers""); + + xd->pre = pc->yv12_fb[pc->lst_fb_idx]; + xd->dst = pc->yv12_fb[pc->new_fb_idx]; + +#if CONFIG_MULTITHREAD + for (i = 0; i < pbi->allocated_decoding_thread_count; i++) + { + pbi->mb_row_di[i].mbd.dst = pc->yv12_fb[pc->new_fb_idx]; + vp8_build_block_doffsets(&pbi->mb_row_di[i].mbd); + } +#endif + vp8_build_block_doffsets(&pbi->mb); + + /* allocate memory for last frame MODE_INFO array */ +#if CONFIG_ERROR_CONCEALMENT + + if (pbi->ec_enabled) + { + /* old prev_mip was released by vp8_de_alloc_frame_buffers() + * called in vp8_alloc_frame_buffers() */ + pc->prev_mip = vpx_calloc( + (pc->mb_cols + 1) * (pc->mb_rows + 1), + sizeof(MODE_INFO)); + + if (!pc->prev_mip) + { + vp8_de_alloc_frame_buffers(pc); + vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR, + ""Failed to allocate"" + ""last frame MODE_INFO array""); + } + + pc->prev_mi = pc->prev_mip + pc->mode_info_stride + 1; + + if (vp8_alloc_overlap_lists(pbi)) + vpx_internal_error(&pc->error, VPX_CODEC_MEM_ERROR, + ""Failed to allocate overlap lists "" + ""for error concealment""); + } + +#endif + +#if CONFIG_MULTITHREAD + if (pbi->b_multithreaded_rd) + vp8mt_alloc_temp_buffers(pbi, pc->Width, prev_mb_rows); +#else + (void)prev_mb_rows; +#endif + } + + pbi->common.error.setjmp = 0; + + /* required to get past the first get_free_fb() call */ + pbi->common.fb_idx_ref_cnt[0] = 0; + } + + /* update the pbi fragment data */ + pbi->fragments = ctx->fragments; + + ctx->user_priv = user_priv; + if (vp8dx_receive_compressed_data(pbi, data_sz, data, deadline)) + { + res = update_error_state(ctx, &pbi->common.error); + } + + /* get ready for the next series of fragments */ + ctx->fragments.count = 0; + } + + return res; +} +","@@ -198,8 +198,8 @@ + + si->h = (clear[8] | (clear[9] << 8)) & 0x3fff; + + /*printf(""w=%d, h=%d\n"", si->w, si->h);*/ +- if (!(si->h | si->w)) +- res = VPX_CODEC_UNSUP_BITSTREAM; ++ if (!(si->h && si->w)) ++ res = VPX_CODEC_CORRUPT_FRAME; + } + else + { +@@ -421,6 +421,10 @@ + + if (setjmp(pbi->common.error.jmp)) + { + pbi->common.error.setjmp = 0; ++ /* on failure clear the cached resolution to ensure a full ++ * reallocation is attempted on resync. */ ++ ctx->si.w = 0; ++ ctx->si.h = 0; + vp8_clear_system_state(); + /* same return value as used in vp8dx_receive_compressed_data */ + return -1; +",1449,1780,2048 +18301,"bgp_capabilities_print(netdissect_options *ndo, + const u_char *opt, int caps_len) +{ + int cap_type, cap_len, tcap_len, cap_offset; + int i = 0; + + while (i < caps_len) { + ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE); + cap_type=opt[i]; + cap_len=opt[i+1]; + tcap_len=cap_len; + ND_PRINT((ndo, ""\n\t %s (%u), length: %u"", + tok2str(bgp_capcode_values, ""Unknown"", + cap_type), + cap_type, + cap_len)); + ND_TCHECK2(opt[i+2], cap_len); + switch (cap_type) { + case BGP_CAPCODE_MP: + ND_PRINT((ndo, ""\n\t\tAFI %s (%u), SAFI %s (%u)"", + tok2str(af_values, ""Unknown"", + EXTRACT_16BITS(opt+i+2)), + EXTRACT_16BITS(opt+i+2), + tok2str(bgp_safi_values, ""Unknown"", + opt[i+5]), + opt[i+5])); + break; + case BGP_CAPCODE_RESTART: + /* Restart Flags (4 bits), Restart Time in seconds (12 bits) */ + ND_TCHECK_16BITS(opt + i + 2); + ND_PRINT((ndo, ""\n\t\tRestart Flags: [%s], Restart Time %us"", + ((opt[i+2])&0x80) ? ""R"" : ""none"", + EXTRACT_16BITS(opt+i+2)&0xfff)); + tcap_len-=2; + cap_offset=4; + while(tcap_len>=4) { + ND_PRINT((ndo, ""\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s"", + tok2str(af_values,""Unknown"", + EXTRACT_16BITS(opt+i+cap_offset)), + EXTRACT_16BITS(opt+i+cap_offset), + tok2str(bgp_safi_values,""Unknown"", + opt[i+cap_offset+2]), + opt[i+cap_offset+2], + ((opt[i+cap_offset+3])&0x80) ? ""yes"" : ""no"" )); + tcap_len-=4; + cap_offset+=4; + } + break; + case BGP_CAPCODE_RR: + case BGP_CAPCODE_RR_CISCO: + break; + case BGP_CAPCODE_AS_NEW: + + /* + * Extract the 4 byte AS number encoded. + */ + if (cap_len == 4) { + ND_PRINT((ndo, ""\n\t\t 4 Byte AS %s"", + as_printf(ndo, astostr, sizeof(astostr), + EXTRACT_32BITS(opt + i + 2)))); + } + break; + case BGP_CAPCODE_ADD_PATH: + cap_offset=2; + if (tcap_len == 0) { + ND_PRINT((ndo, "" (bogus)"")); /* length */ + break; + } + while (tcap_len > 0) { + if (tcap_len < 4) { + ND_PRINT((ndo, ""\n\t\t(invalid)"")); + break; + } + ND_PRINT((ndo, ""\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s"", + tok2str(af_values,""Unknown"",EXTRACT_16BITS(opt+i+cap_offset)), + EXTRACT_16BITS(opt+i+cap_offset), + tok2str(bgp_safi_values,""Unknown"",opt[i+cap_offset+2]), + opt[i+cap_offset+2], + tok2str(bgp_add_path_recvsend,""Bogus (0x%02x)"",opt[i+cap_offset+3]) + )); + tcap_len-=4; + cap_offset+=4; + } + break; + default: + ND_PRINT((ndo, ""\n\t\tno decoder for Capability %u"", + cap_type)); + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, &opt[i+2], ""\n\t\t"", cap_len); + break; + } + if (ndo->ndo_vflag > 1 && cap_len > 0) { + print_unknown_data(ndo, &opt[i+2], ""\n\t\t"", cap_len); + } + i += BGP_CAP_HEADER_SIZE + cap_len; + } + return; + +trunc: + ND_PRINT((ndo, ""[|BGP]"")); +} +",1,"bgp_capabilities_print(netdissect_options *ndo, + const u_char *opt, int caps_len) +{ + int cap_type, cap_len, tcap_len, cap_offset; + int i = 0; + + while (i < caps_len) { + ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE); + cap_type=opt[i]; + cap_len=opt[i+1]; + tcap_len=cap_len; + ND_PRINT((ndo, ""\n\t %s (%u), length: %u"", + tok2str(bgp_capcode_values, ""Unknown"", + cap_type), + cap_type, + cap_len)); + ND_TCHECK2(opt[i+2], cap_len); + switch (cap_type) { + case BGP_CAPCODE_MP: + /* AFI (16 bits), Reserved (8 bits), SAFI (8 bits) */ + ND_TCHECK_8BITS(opt + i + 5); + ND_PRINT((ndo, ""\n\t\tAFI %s (%u), SAFI %s (%u)"", + tok2str(af_values, ""Unknown"", + EXTRACT_16BITS(opt+i+2)), + EXTRACT_16BITS(opt+i+2), + tok2str(bgp_safi_values, ""Unknown"", + opt[i+5]), + opt[i+5])); + break; + case BGP_CAPCODE_RESTART: + /* Restart Flags (4 bits), Restart Time in seconds (12 bits) */ + ND_TCHECK_16BITS(opt + i + 2); + ND_PRINT((ndo, ""\n\t\tRestart Flags: [%s], Restart Time %us"", + ((opt[i+2])&0x80) ? ""R"" : ""none"", + EXTRACT_16BITS(opt+i+2)&0xfff)); + tcap_len-=2; + cap_offset=4; + while(tcap_len>=4) { + ND_PRINT((ndo, ""\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s"", + tok2str(af_values,""Unknown"", + EXTRACT_16BITS(opt+i+cap_offset)), + EXTRACT_16BITS(opt+i+cap_offset), + tok2str(bgp_safi_values,""Unknown"", + opt[i+cap_offset+2]), + opt[i+cap_offset+2], + ((opt[i+cap_offset+3])&0x80) ? ""yes"" : ""no"" )); + tcap_len-=4; + cap_offset+=4; + } + break; + case BGP_CAPCODE_RR: + case BGP_CAPCODE_RR_CISCO: + break; + case BGP_CAPCODE_AS_NEW: + + /* + * Extract the 4 byte AS number encoded. + */ + if (cap_len == 4) { + ND_PRINT((ndo, ""\n\t\t 4 Byte AS %s"", + as_printf(ndo, astostr, sizeof(astostr), + EXTRACT_32BITS(opt + i + 2)))); + } + break; + case BGP_CAPCODE_ADD_PATH: + cap_offset=2; + if (tcap_len == 0) { + ND_PRINT((ndo, "" (bogus)"")); /* length */ + break; + } + while (tcap_len > 0) { + if (tcap_len < 4) { + ND_PRINT((ndo, ""\n\t\t(invalid)"")); + break; + } + ND_PRINT((ndo, ""\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s"", + tok2str(af_values,""Unknown"",EXTRACT_16BITS(opt+i+cap_offset)), + EXTRACT_16BITS(opt+i+cap_offset), + tok2str(bgp_safi_values,""Unknown"",opt[i+cap_offset+2]), + opt[i+cap_offset+2], + tok2str(bgp_add_path_recvsend,""Bogus (0x%02x)"",opt[i+cap_offset+3]) + )); + tcap_len-=4; + cap_offset+=4; + } + break; + default: + ND_PRINT((ndo, ""\n\t\tno decoder for Capability %u"", + cap_type)); + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, &opt[i+2], ""\n\t\t"", cap_len); + break; + } + if (ndo->ndo_vflag > 1 && cap_len > 0) { + print_unknown_data(ndo, &opt[i+2], ""\n\t\t"", cap_len); + } + i += BGP_CAP_HEADER_SIZE + cap_len; + } + return; + +trunc: + ND_PRINT((ndo, ""[|BGP]"")); +} +","@@ -2342,6 +2342,8 @@ bgp_capabilities_print(netdissect_options *ndo, + ND_TCHECK2(opt[i+2], cap_len); + switch (cap_type) { + case BGP_CAPCODE_MP: ++ /* AFI (16 bits), Reserved (8 bits), SAFI (8 bits) */ ++ ND_TCHECK_8BITS(opt + i + 5); + ND_PRINT((ndo, ""\n\t\tAFI %s (%u), SAFI %s (%u)"", + tok2str(af_values, ""Unknown"", + EXTRACT_16BITS(opt+i+2)),",994,1325,2048 +5681,"static long setup_sigcontext(struct sigcontext __user *sc, struct pt_regs *regs, + int signr, sigset_t *set, unsigned long handler, + int ctx_has_vsx_region) +{ + /* When CONFIG_ALTIVEC is set, we _always_ setup v_regs even if the + * process never used altivec yet (MSR_VEC is zero in pt_regs of + * the context). This is very important because we must ensure we + * don't lose the VRSAVE content that may have been set prior to + * the process doing its first vector operation + * Userland shall check AT_HWCAP to know whether it can rely on the + * v_regs pointer or not + */ +#ifdef CONFIG_ALTIVEC + elf_vrreg_t __user *v_regs = sigcontext_vmx_regs(sc); +#endif + unsigned long msr = regs->msr; + long err = 0; + +#ifdef CONFIG_ALTIVEC + err |= __put_user(v_regs, &sc->v_regs); + + /* save altivec registers */ + if (current->thread.used_vr) { + flush_altivec_to_thread(current); + /* Copy 33 vec registers (vr0..31 and vscr) to the stack */ + err |= __copy_to_user(v_regs, ¤t->thread.vr_state, + 33 * sizeof(vector128)); + /* set MSR_VEC in the MSR value in the frame to indicate that sc->v_reg) + * contains valid data. + */ + msr |= MSR_VEC; + } + /* We always copy to/from vrsave, it's 0 if we don't have or don't + * use altivec. + */ + if (cpu_has_feature(CPU_FTR_ALTIVEC)) + current->thread.vrsave = mfspr(SPRN_VRSAVE); + err |= __put_user(current->thread.vrsave, (u32 __user *)&v_regs[33]); +#else /* CONFIG_ALTIVEC */ + err |= __put_user(0, &sc->v_regs); +#endif /* CONFIG_ALTIVEC */ + flush_fp_to_thread(current); + /* copy fpr regs and fpscr */ + err |= copy_fpr_to_user(&sc->fp_regs, current); + + /* + * Clear the MSR VSX bit to indicate there is no valid state attached + * to this context, except in the specific case below where we set it. + */ + msr &= ~MSR_VSX; +#ifdef CONFIG_VSX + /* + * Copy VSX low doubleword to local buffer for formatting, + * then out to userspace. Update v_regs to point after the + * VMX data. + */ + if (current->thread.used_vsr && ctx_has_vsx_region) { + __giveup_vsx(current); + v_regs += ELF_NVRREG; + err |= copy_vsx_to_user(v_regs, current); + /* set MSR_VSX in the MSR value in the frame to + * indicate that sc->vs_reg) contains valid data. + */ + msr |= MSR_VSX; + } +#endif /* CONFIG_VSX */ + err |= __put_user(&sc->gp_regs, &sc->regs); + WARN_ON(!FULL_REGS(regs)); + err |= __copy_to_user(&sc->gp_regs, regs, GP_REGS_SIZE); + err |= __put_user(msr, &sc->gp_regs[PT_MSR]); + err |= __put_user(signr, &sc->signal); + err |= __put_user(handler, &sc->handler); + if (set != NULL) + err |= __put_user(set->sig[0], &sc->oldmask); + + return err; +} +",0,"static long setup_sigcontext(struct sigcontext __user *sc, struct pt_regs *regs, + int signr, sigset_t *set, unsigned long handler, + int ctx_has_vsx_region) +{ + /* When CONFIG_ALTIVEC is set, we _always_ setup v_regs even if the + * process never used altivec yet (MSR_VEC is zero in pt_regs of + * the context). This is very important because we must ensure we + * don't lose the VRSAVE content that may have been set prior to + * the process doing its first vector operation + * Userland shall check AT_HWCAP to know whether it can rely on the + * v_regs pointer or not + */ +#ifdef CONFIG_ALTIVEC + elf_vrreg_t __user *v_regs = sigcontext_vmx_regs(sc); +#endif + unsigned long msr = regs->msr; + long err = 0; + +#ifdef CONFIG_ALTIVEC + err |= __put_user(v_regs, &sc->v_regs); + + /* save altivec registers */ + if (current->thread.used_vr) { + flush_altivec_to_thread(current); + /* Copy 33 vec registers (vr0..31 and vscr) to the stack */ + err |= __copy_to_user(v_regs, ¤t->thread.vr_state, + 33 * sizeof(vector128)); + /* set MSR_VEC in the MSR value in the frame to indicate that sc->v_reg) + * contains valid data. + */ + msr |= MSR_VEC; + } + /* We always copy to/from vrsave, it's 0 if we don't have or don't + * use altivec. + */ + if (cpu_has_feature(CPU_FTR_ALTIVEC)) + current->thread.vrsave = mfspr(SPRN_VRSAVE); + err |= __put_user(current->thread.vrsave, (u32 __user *)&v_regs[33]); +#else /* CONFIG_ALTIVEC */ + err |= __put_user(0, &sc->v_regs); +#endif /* CONFIG_ALTIVEC */ + flush_fp_to_thread(current); + /* copy fpr regs and fpscr */ + err |= copy_fpr_to_user(&sc->fp_regs, current); + + /* + * Clear the MSR VSX bit to indicate there is no valid state attached + * to this context, except in the specific case below where we set it. + */ + msr &= ~MSR_VSX; +#ifdef CONFIG_VSX + /* + * Copy VSX low doubleword to local buffer for formatting, + * then out to userspace. Update v_regs to point after the + * VMX data. + */ + if (current->thread.used_vsr && ctx_has_vsx_region) { + __giveup_vsx(current); + v_regs += ELF_NVRREG; + err |= copy_vsx_to_user(v_regs, current); + /* set MSR_VSX in the MSR value in the frame to + * indicate that sc->vs_reg) contains valid data. + */ + msr |= MSR_VSX; + } +#endif /* CONFIG_VSX */ + err |= __put_user(&sc->gp_regs, &sc->regs); + WARN_ON(!FULL_REGS(regs)); + err |= __copy_to_user(&sc->gp_regs, regs, GP_REGS_SIZE); + err |= __put_user(msr, &sc->gp_regs[PT_MSR]); + err |= __put_user(signr, &sc->signal); + err |= __put_user(handler, &sc->handler); + if (set != NULL) + err |= __put_user(set->sig[0], &sc->oldmask); + + return err; +} +","@@ -438,6 +438,10 @@ static long restore_tm_sigcontexts(struct pt_regs *regs, + + /* get MSR separately, transfer the LE bit if doing signal return */ + err |= __get_user(msr, &sc->gp_regs[PT_MSR]); ++ /* Don't allow reserved mode. */ ++ if (MSR_TM_RESV(msr)) ++ return -EINVAL; ++ + /* pull in MSR TM from user context */ + regs->msr = (regs->msr & ~MSR_TS_MASK) | (msr & MSR_TS_MASK); + ",784,1115,2048 +1675,"CStarter::Init( JobInfoCommunicator* my_jic, const char* original_cwd, + bool is_gsh, int stdin_fd, int stdout_fd, + int stderr_fd ) +{ + if( ! my_jic ) { + EXCEPT( ""CStarter::Init() called with no JobInfoCommunicator!"" ); + } + if( jic ) { + delete( jic ); + } + jic = my_jic; + + if( original_cwd ) { + this->orig_cwd = strdup( original_cwd ); + } + this->is_gridshell = is_gsh; + starter_stdin_fd = stdin_fd; + starter_stdout_fd = stdout_fd; + starter_stderr_fd = stderr_fd; + + Config(); + + + if( is_gridshell ) { + WorkingDir = Execute; + } else { + WorkingDir.sprintf( ""%s%cdir_%ld"", Execute, DIR_DELIM_CHAR, + (long)daemonCore->getpid() ); + } + + daemonCore->Register_Signal(DC_SIGSUSPEND, ""DC_SIGSUSPEND"", + (SignalHandlercpp)&CStarter::RemoteSuspend, ""RemoteSuspend"", + this); + daemonCore->Register_Signal(DC_SIGCONTINUE, ""DC_SIGCONTINUE"", + (SignalHandlercpp)&CStarter::RemoteContinue, ""RemoteContinue"", + this); + daemonCore->Register_Signal(DC_SIGHARDKILL, ""DC_SIGHARDKILL"", + (SignalHandlercpp)&CStarter::RemoteShutdownFast, ""RemoteShutdownFast"", + this); + daemonCore->Register_Signal(DC_SIGSOFTKILL, ""DC_SIGSOFTKILL"", + (SignalHandlercpp)&CStarter::RemoteShutdownGraceful, ""RemoteShutdownGraceful"", + this); + daemonCore->Register_Signal(DC_SIGPCKPT, ""DC_SIGPCKPT"", + (SignalHandlercpp)&CStarter::RemotePeriodicCkpt, ""RemotePeriodicCkpt"", + this); + daemonCore->Register_Signal(DC_SIGREMOVE, ""DC_SIGREMOVE"", + (SignalHandlercpp)&CStarter::RemoteRemove, ""RemoteRemove"", + this); + daemonCore->Register_Signal(SIGUSR1, ""SIGUSR1"", + (SignalHandlercpp)&CStarter::RemoteRemove, ""RemoteRemove"", + this); + daemonCore->Register_Signal(DC_SIGHOLD, ""DC_SIGHOLD"", + (SignalHandlercpp)&CStarter::RemoteHold, ""RemoteHold"", + this); + daemonCore->Register_Reaper(""Reaper"", (ReaperHandlercpp)&CStarter::Reaper, + ""Reaper"", this); + + daemonCore-> + Register_Command( CA_CMD, ""CA_CMD"", + (CommandHandlercpp)&CStarter::classadCommand, + ""CStarter::classadCommand"", this, WRITE ); + daemonCore-> + Register_Command( UPDATE_GSI_CRED, ""UPDATE_GSI_CRED"", + (CommandHandlercpp)&CStarter::updateX509Proxy, + ""CStarter::updateX509Proxy"", this, WRITE ); + daemonCore-> + Register_Command( DELEGATE_GSI_CRED_STARTER, + ""DELEGATE_GSI_CRED_STARTER"", + (CommandHandlercpp)&CStarter::updateX509Proxy, + ""CStarter::updateX509Proxy"", this, WRITE ); + daemonCore-> + Register_Command( STARTER_HOLD_JOB, + ""STARTER_HOLD_JOB"", + (CommandHandlercpp)&CStarter::remoteHoldCommand, + ""CStarter::remoteHoldCommand"", this, DAEMON ); + daemonCore-> + Register_Command( CREATE_JOB_OWNER_SEC_SESSION, + ""CREATE_JOB_OWNER_SEC_SESSION"", + (CommandHandlercpp)&CStarter::createJobOwnerSecSession, + ""CStarter::createJobOwnerSecSession"", this, DAEMON ); + + daemonCore-> + Register_Command( START_SSHD, + ""START_SSHD"", + (CommandHandlercpp)&CStarter::startSSHD, + ""CStarter::startSSHD"", this, READ ); + if( ! jic->init() ) { + dprintf( D_ALWAYS, + ""Failed to initialize JobInfoCommunicator, aborting\n"" ); + return false; + } + sysapi_set_resource_limits(jic->getStackSize()); + + jic->setupJobEnvironment(); + return true; +} +",0,"CStarter::Init( JobInfoCommunicator* my_jic, const char* original_cwd, + bool is_gsh, int stdin_fd, int stdout_fd, + int stderr_fd ) +{ + if( ! my_jic ) { + EXCEPT( ""CStarter::Init() called with no JobInfoCommunicator!"" ); + } + if( jic ) { + delete( jic ); + } + jic = my_jic; + + if( original_cwd ) { + this->orig_cwd = strdup( original_cwd ); + } + this->is_gridshell = is_gsh; + starter_stdin_fd = stdin_fd; + starter_stdout_fd = stdout_fd; + starter_stderr_fd = stderr_fd; + + Config(); + + + if( is_gridshell ) { + WorkingDir = Execute; + } else { + WorkingDir.sprintf( ""%s%cdir_%ld"", Execute, DIR_DELIM_CHAR, + (long)daemonCore->getpid() ); + } + + daemonCore->Register_Signal(DC_SIGSUSPEND, ""DC_SIGSUSPEND"", + (SignalHandlercpp)&CStarter::RemoteSuspend, ""RemoteSuspend"", + this); + daemonCore->Register_Signal(DC_SIGCONTINUE, ""DC_SIGCONTINUE"", + (SignalHandlercpp)&CStarter::RemoteContinue, ""RemoteContinue"", + this); + daemonCore->Register_Signal(DC_SIGHARDKILL, ""DC_SIGHARDKILL"", + (SignalHandlercpp)&CStarter::RemoteShutdownFast, ""RemoteShutdownFast"", + this); + daemonCore->Register_Signal(DC_SIGSOFTKILL, ""DC_SIGSOFTKILL"", + (SignalHandlercpp)&CStarter::RemoteShutdownGraceful, ""RemoteShutdownGraceful"", + this); + daemonCore->Register_Signal(DC_SIGPCKPT, ""DC_SIGPCKPT"", + (SignalHandlercpp)&CStarter::RemotePeriodicCkpt, ""RemotePeriodicCkpt"", + this); + daemonCore->Register_Signal(DC_SIGREMOVE, ""DC_SIGREMOVE"", + (SignalHandlercpp)&CStarter::RemoteRemove, ""RemoteRemove"", + this); + daemonCore->Register_Signal(SIGUSR1, ""SIGUSR1"", + (SignalHandlercpp)&CStarter::RemoteRemove, ""RemoteRemove"", + this); + daemonCore->Register_Signal(DC_SIGHOLD, ""DC_SIGHOLD"", + (SignalHandlercpp)&CStarter::RemoteHold, ""RemoteHold"", + this); + daemonCore->Register_Reaper(""Reaper"", (ReaperHandlercpp)&CStarter::Reaper, + ""Reaper"", this); + + daemonCore-> + Register_Command( CA_CMD, ""CA_CMD"", + (CommandHandlercpp)&CStarter::classadCommand, + ""CStarter::classadCommand"", this, WRITE ); + daemonCore-> + Register_Command( UPDATE_GSI_CRED, ""UPDATE_GSI_CRED"", + (CommandHandlercpp)&CStarter::updateX509Proxy, + ""CStarter::updateX509Proxy"", this, WRITE ); + daemonCore-> + Register_Command( DELEGATE_GSI_CRED_STARTER, + ""DELEGATE_GSI_CRED_STARTER"", + (CommandHandlercpp)&CStarter::updateX509Proxy, + ""CStarter::updateX509Proxy"", this, WRITE ); + daemonCore-> + Register_Command( STARTER_HOLD_JOB, + ""STARTER_HOLD_JOB"", + (CommandHandlercpp)&CStarter::remoteHoldCommand, + ""CStarter::remoteHoldCommand"", this, DAEMON ); + daemonCore-> + Register_Command( CREATE_JOB_OWNER_SEC_SESSION, + ""CREATE_JOB_OWNER_SEC_SESSION"", + (CommandHandlercpp)&CStarter::createJobOwnerSecSession, + ""CStarter::createJobOwnerSecSession"", this, DAEMON ); + + daemonCore-> + Register_Command( START_SSHD, + ""START_SSHD"", + (CommandHandlercpp)&CStarter::startSSHD, + ""CStarter::startSSHD"", this, READ ); + if( ! jic->init() ) { + dprintf( D_ALWAYS, + ""Failed to initialize JobInfoCommunicator, aborting\n"" ); + return false; + } + sysapi_set_resource_limits(jic->getStackSize()); + + jic->setupJobEnvironment(); + return true; +} +","@@ -1800,7 +1800,7 @@ CStarter::removeDeferredJobs() { + error += this->jic->jobCluster(); + error += "".""; + error += this->jic->jobProc(); +- EXCEPT( error.Value() ); ++ EXCEPT( ""%s"", error.Value() ); + ret = false; + } + return ( ret );",975,1306,2048 +8816,"addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId, + const XML_Char *uri, BINDING **bindingsPtr) { + static const XML_Char xmlNamespace[] + = {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, + ASCII_SLASH, ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, + ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o, + ASCII_r, ASCII_g, ASCII_SLASH, ASCII_X, ASCII_M, + ASCII_L, ASCII_SLASH, ASCII_1, ASCII_9, ASCII_9, + ASCII_8, ASCII_SLASH, ASCII_n, ASCII_a, ASCII_m, + ASCII_e, ASCII_s, ASCII_p, ASCII_a, ASCII_c, + ASCII_e, '\0'}; + static const int xmlLen = (int)sizeof(xmlNamespace) / sizeof(XML_Char) - 1; + static const XML_Char xmlnsNamespace[] + = {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH, + ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w, + ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH, + ASCII_2, ASCII_0, ASCII_0, ASCII_0, ASCII_SLASH, ASCII_x, + ASCII_m, ASCII_l, ASCII_n, ASCII_s, ASCII_SLASH, '\0'}; + static const int xmlnsLen + = (int)sizeof(xmlnsNamespace) / sizeof(XML_Char) - 1; + + XML_Bool mustBeXML = XML_FALSE; + XML_Bool isXML = XML_TRUE; + XML_Bool isXMLNS = XML_TRUE; + + BINDING *b; + int len; + + /* empty URI is only valid for default namespace per XML NS 1.0 (not 1.1) */ + if (*uri == XML_T('\0') && prefix->name) + return XML_ERROR_UNDECLARING_PREFIX; + + if (prefix->name && prefix->name[0] == XML_T(ASCII_x) + && prefix->name[1] == XML_T(ASCII_m) + && prefix->name[2] == XML_T(ASCII_l)) { + /* Not allowed to bind xmlns */ + if (prefix->name[3] == XML_T(ASCII_n) && prefix->name[4] == XML_T(ASCII_s) + && prefix->name[5] == XML_T('\0')) + return XML_ERROR_RESERVED_PREFIX_XMLNS; + + if (prefix->name[3] == XML_T('\0')) + mustBeXML = XML_TRUE; + } + + for (len = 0; uri[len]; len++) { + if (isXML && (len > xmlLen || uri[len] != xmlNamespace[len])) + isXML = XML_FALSE; + + if (! mustBeXML && isXMLNS + && (len > xmlnsLen || uri[len] != xmlnsNamespace[len])) + isXMLNS = XML_FALSE; + } + isXML = isXML && len == xmlLen; + isXMLNS = isXMLNS && len == xmlnsLen; + + if (mustBeXML != isXML) + return mustBeXML ? XML_ERROR_RESERVED_PREFIX_XML + : XML_ERROR_RESERVED_NAMESPACE_URI; + + if (isXMLNS) + return XML_ERROR_RESERVED_NAMESPACE_URI; + + if (parser->m_namespaceSeparator) + len++; + if (parser->m_freeBindingList) { + b = parser->m_freeBindingList; + if (len > b->uriAlloc) { + XML_Char *temp = (XML_Char *)REALLOC( + parser, b->uri, sizeof(XML_Char) * (len + EXPAND_SPARE)); + if (temp == NULL) + return XML_ERROR_NO_MEMORY; + b->uri = temp; + b->uriAlloc = len + EXPAND_SPARE; + } + parser->m_freeBindingList = b->nextTagBinding; + } else { + b = (BINDING *)MALLOC(parser, sizeof(BINDING)); + if (! b) + return XML_ERROR_NO_MEMORY; + b->uri + = (XML_Char *)MALLOC(parser, sizeof(XML_Char) * (len + EXPAND_SPARE)); + if (! b->uri) { + FREE(parser, b); + return XML_ERROR_NO_MEMORY; + } + b->uriAlloc = len + EXPAND_SPARE; + } + b->uriLen = len; + memcpy(b->uri, uri, len * sizeof(XML_Char)); + if (parser->m_namespaceSeparator) + b->uri[len - 1] = parser->m_namespaceSeparator; + b->prefix = prefix; + b->attId = attId; + b->prevPrefixBinding = prefix->binding; + /* NULL binding when default namespace undeclared */ + if (*uri == XML_T('\0') && prefix == &parser->m_dtd->defaultPrefix) + prefix->binding = NULL; + else + prefix->binding = b; + b->nextTagBinding = *bindingsPtr; + *bindingsPtr = b; + /* if attId == NULL then we are not starting a namespace scope */ + if (attId && parser->m_startNamespaceDeclHandler) + parser->m_startNamespaceDeclHandler(parser->m_handlerArg, prefix->name, + prefix->binding ? uri : 0); + return XML_ERROR_NONE; +} +",0,"addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId, + const XML_Char *uri, BINDING **bindingsPtr) { + static const XML_Char xmlNamespace[] + = {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, + ASCII_SLASH, ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, + ASCII_PERIOD, ASCII_w, ASCII_3, ASCII_PERIOD, ASCII_o, + ASCII_r, ASCII_g, ASCII_SLASH, ASCII_X, ASCII_M, + ASCII_L, ASCII_SLASH, ASCII_1, ASCII_9, ASCII_9, + ASCII_8, ASCII_SLASH, ASCII_n, ASCII_a, ASCII_m, + ASCII_e, ASCII_s, ASCII_p, ASCII_a, ASCII_c, + ASCII_e, '\0'}; + static const int xmlLen = (int)sizeof(xmlNamespace) / sizeof(XML_Char) - 1; + static const XML_Char xmlnsNamespace[] + = {ASCII_h, ASCII_t, ASCII_t, ASCII_p, ASCII_COLON, ASCII_SLASH, + ASCII_SLASH, ASCII_w, ASCII_w, ASCII_w, ASCII_PERIOD, ASCII_w, + ASCII_3, ASCII_PERIOD, ASCII_o, ASCII_r, ASCII_g, ASCII_SLASH, + ASCII_2, ASCII_0, ASCII_0, ASCII_0, ASCII_SLASH, ASCII_x, + ASCII_m, ASCII_l, ASCII_n, ASCII_s, ASCII_SLASH, '\0'}; + static const int xmlnsLen + = (int)sizeof(xmlnsNamespace) / sizeof(XML_Char) - 1; + + XML_Bool mustBeXML = XML_FALSE; + XML_Bool isXML = XML_TRUE; + XML_Bool isXMLNS = XML_TRUE; + + BINDING *b; + int len; + + /* empty URI is only valid for default namespace per XML NS 1.0 (not 1.1) */ + if (*uri == XML_T('\0') && prefix->name) + return XML_ERROR_UNDECLARING_PREFIX; + + if (prefix->name && prefix->name[0] == XML_T(ASCII_x) + && prefix->name[1] == XML_T(ASCII_m) + && prefix->name[2] == XML_T(ASCII_l)) { + /* Not allowed to bind xmlns */ + if (prefix->name[3] == XML_T(ASCII_n) && prefix->name[4] == XML_T(ASCII_s) + && prefix->name[5] == XML_T('\0')) + return XML_ERROR_RESERVED_PREFIX_XMLNS; + + if (prefix->name[3] == XML_T('\0')) + mustBeXML = XML_TRUE; + } + + for (len = 0; uri[len]; len++) { + if (isXML && (len > xmlLen || uri[len] != xmlNamespace[len])) + isXML = XML_FALSE; + + if (! mustBeXML && isXMLNS + && (len > xmlnsLen || uri[len] != xmlnsNamespace[len])) + isXMLNS = XML_FALSE; + } + isXML = isXML && len == xmlLen; + isXMLNS = isXMLNS && len == xmlnsLen; + + if (mustBeXML != isXML) + return mustBeXML ? XML_ERROR_RESERVED_PREFIX_XML + : XML_ERROR_RESERVED_NAMESPACE_URI; + + if (isXMLNS) + return XML_ERROR_RESERVED_NAMESPACE_URI; + + if (parser->m_namespaceSeparator) + len++; + if (parser->m_freeBindingList) { + b = parser->m_freeBindingList; + if (len > b->uriAlloc) { + XML_Char *temp = (XML_Char *)REALLOC( + parser, b->uri, sizeof(XML_Char) * (len + EXPAND_SPARE)); + if (temp == NULL) + return XML_ERROR_NO_MEMORY; + b->uri = temp; + b->uriAlloc = len + EXPAND_SPARE; + } + parser->m_freeBindingList = b->nextTagBinding; + } else { + b = (BINDING *)MALLOC(parser, sizeof(BINDING)); + if (! b) + return XML_ERROR_NO_MEMORY; + b->uri + = (XML_Char *)MALLOC(parser, sizeof(XML_Char) * (len + EXPAND_SPARE)); + if (! b->uri) { + FREE(parser, b); + return XML_ERROR_NO_MEMORY; + } + b->uriAlloc = len + EXPAND_SPARE; + } + b->uriLen = len; + memcpy(b->uri, uri, len * sizeof(XML_Char)); + if (parser->m_namespaceSeparator) + b->uri[len - 1] = parser->m_namespaceSeparator; + b->prefix = prefix; + b->attId = attId; + b->prevPrefixBinding = prefix->binding; + /* NULL binding when default namespace undeclared */ + if (*uri == XML_T('\0') && prefix == &parser->m_dtd->defaultPrefix) + prefix->binding = NULL; + else + prefix->binding = b; + b->nextTagBinding = *bindingsPtr; + *bindingsPtr = b; + /* if attId == NULL then we are not starting a namespace scope */ + if (attId && parser->m_startNamespaceDeclHandler) + parser->m_startNamespaceDeclHandler(parser->m_handlerArg, prefix->name, + prefix->binding ? uri : 0); + return XML_ERROR_NONE; +} +","@@ -401,7 +401,7 @@ static enum XML_Error initializeEncoding(XML_Parser parser); + static enum XML_Error doProlog(XML_Parser parser, const ENCODING *enc, + const char *s, const char *end, int tok, + const char *next, const char **nextPtr, +- XML_Bool haveMore); ++ XML_Bool haveMore, XML_Bool allowClosingDoctype); + static enum XML_Error processInternalEntity(XML_Parser parser, ENTITY *entity, + XML_Bool betweenDecl); + static enum XML_Error doContent(XML_Parser parser, int startTagLevel, +@@ -4046,7 +4046,7 @@ externalParEntProcessor(XML_Parser parser, const char *s, const char *end, + + parser->m_processor = prologProcessor; + return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr, +- (XML_Bool)! parser->m_parsingStatus.finalBuffer); ++ (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE); + } + + static enum XML_Error PTRCALL +@@ -4090,12 +4090,13 @@ prologProcessor(XML_Parser parser, const char *s, const char *end, + const char *next = s; + int tok = XmlPrologTok(parser->m_encoding, s, end, &next); + return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr, +- (XML_Bool)! parser->m_parsingStatus.finalBuffer); ++ (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE); + } + + static enum XML_Error + doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, +- int tok, const char *next, const char **nextPtr, XML_Bool haveMore) { ++ int tok, const char *next, const char **nextPtr, XML_Bool haveMore, ++ XML_Bool allowClosingDoctype) { + #ifdef XML_DTD + static const XML_Char externalSubsetName[] = {ASCII_HASH, '\0'}; + #endif /* XML_DTD */ +@@ -4271,6 +4272,11 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end, + } + break; + case XML_ROLE_DOCTYPE_CLOSE: ++ if (allowClosingDoctype != XML_TRUE) { ++ /* Must not close doctype from within expanded parameter entities */ ++ return XML_ERROR_INVALID_TOKEN; ++ } ++ + if (parser->m_doctypeName) { + parser->m_startDoctypeDeclHandler( + parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid, +@@ -5174,7 +5180,7 @@ processInternalEntity(XML_Parser parser, ENTITY *entity, XML_Bool betweenDecl) { + int tok + = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next); + result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd, +- tok, next, &next, XML_FALSE); ++ tok, next, &next, XML_FALSE, XML_FALSE); + } else + #endif /* XML_DTD */ + result = doContent(parser, parser->m_tagLevel, parser->m_internalEncoding, +@@ -5217,7 +5223,7 @@ internalEntityProcessor(XML_Parser parser, const char *s, const char *end, + int tok + = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next); + result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd, +- tok, next, &next, XML_FALSE); ++ tok, next, &next, XML_FALSE, XML_TRUE); + } else + #endif /* XML_DTD */ + result = doContent(parser, openEntity->startTagLevel, +@@ -5244,7 +5250,7 @@ internalEntityProcessor(XML_Parser parser, const char *s, const char *end, + parser->m_processor = prologProcessor; + tok = XmlPrologTok(parser->m_encoding, s, end, &next); + return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr, +- (XML_Bool)! parser->m_parsingStatus.finalBuffer); ++ (XML_Bool)! parser->m_parsingStatus.finalBuffer, XML_TRUE); + } else + #endif /* XML_DTD */ + {",1179,1510,2048 +17329,"OMX_ERRORTYPE omx_vdec::component_deinit(OMX_IN OMX_HANDLETYPE hComp) +{ + (void) hComp; +#ifdef _ANDROID_ + if (iDivXDrmDecrypt) { + delete iDivXDrmDecrypt; + iDivXDrmDecrypt=NULL; + } +#endif //_ANDROID_ + + unsigned i = 0; + if (OMX_StateLoaded != m_state) { + DEBUG_PRINT_ERROR(""WARNING:Rxd DeInit,OMX not in LOADED state %d"",\ + m_state); + DEBUG_PRINT_ERROR(""Playback Ended - FAILED""); + } else { + DEBUG_PRINT_HIGH(""Playback Ended - PASSED""); + } + + /*Check if the output buffers have to be cleaned up*/ + if (m_out_mem_ptr) { + DEBUG_PRINT_LOW(""Freeing the Output Memory""); + for (i = 0; i < drv_ctx.op_buf.actualcount; i++ ) { + if (BITMASK_PRESENT(&m_out_bm_count, i)) { + BITMASK_CLEAR(&m_out_bm_count, i); + client_buffers.free_output_buffer (&m_out_mem_ptr[i]); + } + + if (release_output_done()) { + break; + } + } +#ifdef _ANDROID_ICS_ + memset(&native_buffer, 0, (sizeof(nativebuffer) * MAX_NUM_INPUT_OUTPUT_BUFFERS)); +#endif + } + + /*Check if the input buffers have to be cleaned up*/ + if (m_inp_mem_ptr || m_inp_heap_ptr) { + DEBUG_PRINT_LOW(""Freeing the Input Memory""); + for (i = 0; i TOTAL PROCESSING TIME""); +@@ -5074,6 +5076,9 @@ + + index = bufferHdr - m_inp_mem_ptr; + DEBUG_PRINT_LOW(""Free Input Buffer index = %d"",index); + ++ auto_lock l(buf_lock); ++ bufferHdr->pInputPortPrivate = NULL; ++ + if (index < drv_ctx.ip_buf.actualcount && drv_ctx.ptr_inputbuffer) { + DEBUG_PRINT_LOW(""Free Input Buffer index = %d"",index); + if (drv_ctx.ptr_inputbuffer[index].pmem_fd > 0) { +@@ -6022,7 +6027,9 @@ + + OMX_ERRORTYPE ret1 = OMX_ErrorNone; + unsigned int nBufferIndex = drv_ctx.ip_buf.actualcount; + +- if (m_state == OMX_StateInvalid) { ++ if (m_state != OMX_StateExecuting && ++ m_state != OMX_StatePause && ++ m_state != OMX_StateIdle) { + DEBUG_PRINT_ERROR(""Empty this buffer in Invalid State""); + return OMX_ErrorInvalidState; + } +@@ -6156,9 +6163,10 @@ + + return OMX_ErrorNone; + } + ++ auto_lock l(buf_lock); + temp_buffer = (struct vdec_bufferpayload *)buffer->pInputPortPrivate; + +- if ((temp_buffer - drv_ctx.ptr_inputbuffer) > (int)drv_ctx.ip_buf.actualcount) { ++ if (!temp_buffer || (temp_buffer - drv_ctx.ptr_inputbuffer) > (int)drv_ctx.ip_buf.actualcount) { + return OMX_ErrorBadParameter; + } + /* If its first frame, H264 codec and reject is true, then parse the nal +@@ -6184,7 +6192,7 @@ + + /*for use buffer we need to memcpy the data*/ + temp_buffer->buffer_len = buffer->nFilledLen; + +- if (input_use_buffer) { ++ if (input_use_buffer && temp_buffer->bufferaddr) { + if (buffer->nFilledLen <= temp_buffer->buffer_len) { + if (arbitrary_bytes) { + memcpy (temp_buffer->bufferaddr, (buffer->pBuffer + buffer->nOffset),buffer->nFilledLen); +@@ -6352,6 +6360,18 @@ + + OMX_ERRORTYPE omx_vdec::fill_this_buffer(OMX_IN OMX_HANDLETYPE hComp, + OMX_IN OMX_BUFFERHEADERTYPE* buffer) + { ++ if (m_state != OMX_StateExecuting && ++ m_state != OMX_StatePause && ++ m_state != OMX_StateIdle) { ++ DEBUG_PRINT_ERROR(""FTB in Invalid State""); ++ return OMX_ErrorInvalidState; ++ } ++ ++ if (!m_out_bEnabled) { ++ DEBUG_PRINT_ERROR(""ERROR:FTB incorrect state operation, output port is disabled.""); ++ return OMX_ErrorIncorrectStateOperation; ++ } ++ + unsigned nPortIndex = 0; + if (dynamic_buf_mode) { + private_handle_t *handle = NULL; +@@ -6389,17 +6409,6 @@ + + buffer->nAllocLen = handle->size; + } + +- +- if (m_state == OMX_StateInvalid) { +- DEBUG_PRINT_ERROR(""FTB in Invalid State""); +- return OMX_ErrorInvalidState; +- } +- +- if (!m_out_bEnabled) { +- DEBUG_PRINT_ERROR(""ERROR:FTB incorrect state operation, output port is disabled.""); +- return OMX_ErrorIncorrectStateOperation; +- } +- + nPortIndex = buffer - client_buffers.get_il_buf_hdr(); + if (buffer == NULL || + (nPortIndex >= drv_ctx.op_buf.actualcount)) { +",768,1099,2048 +6369,"httpd_initialize( + char* hostname, httpd_sockaddr* sa4P, httpd_sockaddr* sa6P, + unsigned short port, char* cgi_pattern, int cgi_limit, char* charset, + char* p3p, int max_age, char* cwd, int no_log, FILE* logfp, + int no_symlink_check, int vhost, int global_passwd, char* url_pattern, + char* local_pattern, int no_empty_referers ) + { + httpd_server* hs; + static char ghnbuf[256]; + char* cp; + + check_options(); + + hs = NEW( httpd_server, 1 ); + if ( hs == (httpd_server*) 0 ) + { + syslog( LOG_CRIT, ""out of memory allocating an httpd_server"" ); + return (httpd_server*) 0; + } + + if ( hostname != (char*) 0 ) + { + hs->binding_hostname = strdup( hostname ); + if ( hs->binding_hostname == (char*) 0 ) + { + syslog( LOG_CRIT, ""out of memory copying hostname"" ); + return (httpd_server*) 0; + } + hs->server_hostname = hs->binding_hostname; + } + else + { + hs->binding_hostname = (char*) 0; + hs->server_hostname = (char*) 0; + if ( gethostname( ghnbuf, sizeof(ghnbuf) ) < 0 ) + ghnbuf[0] = '\0'; +#ifdef SERVER_NAME_LIST + if ( ghnbuf[0] != '\0' ) + hs->server_hostname = hostname_map( ghnbuf ); +#endif /* SERVER_NAME_LIST */ + if ( hs->server_hostname == (char*) 0 ) + { +#ifdef SERVER_NAME + hs->server_hostname = SERVER_NAME; +#else /* SERVER_NAME */ + if ( ghnbuf[0] != '\0' ) + hs->server_hostname = ghnbuf; +#endif /* SERVER_NAME */ + } + } + + hs->port = port; + if ( cgi_pattern == (char*) 0 ) + hs->cgi_pattern = (char*) 0; + else + { + /* Nuke any leading slashes. */ + if ( cgi_pattern[0] == '/' ) + ++cgi_pattern; + hs->cgi_pattern = strdup( cgi_pattern ); + if ( hs->cgi_pattern == (char*) 0 ) + { + syslog( LOG_CRIT, ""out of memory copying cgi_pattern"" ); + return (httpd_server*) 0; + } + /* Nuke any leading slashes in the cgi pattern. */ + while ( ( cp = strstr( hs->cgi_pattern, ""|/"" ) ) != (char*) 0 ) + /* -2 for the offset, +1 for the '\0' */ + (void) memmove( cp + 1, cp + 2, strlen( cp ) - 1 ); + } + hs->cgi_limit = cgi_limit; + hs->cgi_count = 0; + hs->charset = strdup( charset ); + hs->p3p = strdup( p3p ); + hs->max_age = max_age; + hs->cwd = strdup( cwd ); + if ( hs->cwd == (char*) 0 ) + { + syslog( LOG_CRIT, ""out of memory copying cwd"" ); + return (httpd_server*) 0; + } + if ( url_pattern == (char*) 0 ) + hs->url_pattern = (char*) 0; + else + { + hs->url_pattern = strdup( url_pattern ); + if ( hs->url_pattern == (char*) 0 ) + { + syslog( LOG_CRIT, ""out of memory copying url_pattern"" ); + return (httpd_server*) 0; + } + } + if ( local_pattern == (char*) 0 ) + hs->local_pattern = (char*) 0; + else + { + hs->local_pattern = strdup( local_pattern ); + if ( hs->local_pattern == (char*) 0 ) + { + syslog( LOG_CRIT, ""out of memory copying local_pattern"" ); + return (httpd_server*) 0; + } + } + hs->no_log = no_log; + hs->logfp = (FILE*) 0; + httpd_set_logfp( hs, logfp ); + hs->no_symlink_check = no_symlink_check; + hs->vhost = vhost; + hs->global_passwd = global_passwd; + hs->no_empty_referers = no_empty_referers; + + /* Initialize listen sockets. Try v6 first because of a Linux peculiarity; + ** like some other systems, it has magical v6 sockets that also listen for + ** v4, but in Linux if you bind a v4 socket first then the v6 bind fails. + */ + if ( sa6P == (httpd_sockaddr*) 0 ) + hs->listen6_fd = -1; + else + hs->listen6_fd = initialize_listen_socket( sa6P ); + if ( sa4P == (httpd_sockaddr*) 0 ) + hs->listen4_fd = -1; + else + hs->listen4_fd = initialize_listen_socket( sa4P ); + /* If we didn't get any valid sockets, fail. */ + if ( hs->listen4_fd == -1 && hs->listen6_fd == -1 ) + { + free_httpd_server( hs ); + return (httpd_server*) 0; + } + + init_mime(); + + /* Done initializing. */ + if ( hs->binding_hostname == (char*) 0 ) + syslog( + LOG_NOTICE, ""%.80s starting on port %d"", SERVER_SOFTWARE, + (int) hs->port ); + else + syslog( + LOG_NOTICE, ""%.80s starting on %.80s, port %d"", SERVER_SOFTWARE, + httpd_ntoa( hs->listen4_fd != -1 ? sa4P : sa6P ), + (int) hs->port ); + return hs; + } +",0,"httpd_initialize( + char* hostname, httpd_sockaddr* sa4P, httpd_sockaddr* sa6P, + unsigned short port, char* cgi_pattern, int cgi_limit, char* charset, + char* p3p, int max_age, char* cwd, int no_log, FILE* logfp, + int no_symlink_check, int vhost, int global_passwd, char* url_pattern, + char* local_pattern, int no_empty_referers ) + { + httpd_server* hs; + static char ghnbuf[256]; + char* cp; + + check_options(); + + hs = NEW( httpd_server, 1 ); + if ( hs == (httpd_server*) 0 ) + { + syslog( LOG_CRIT, ""out of memory allocating an httpd_server"" ); + return (httpd_server*) 0; + } + + if ( hostname != (char*) 0 ) + { + hs->binding_hostname = strdup( hostname ); + if ( hs->binding_hostname == (char*) 0 ) + { + syslog( LOG_CRIT, ""out of memory copying hostname"" ); + return (httpd_server*) 0; + } + hs->server_hostname = hs->binding_hostname; + } + else + { + hs->binding_hostname = (char*) 0; + hs->server_hostname = (char*) 0; + if ( gethostname( ghnbuf, sizeof(ghnbuf) ) < 0 ) + ghnbuf[0] = '\0'; +#ifdef SERVER_NAME_LIST + if ( ghnbuf[0] != '\0' ) + hs->server_hostname = hostname_map( ghnbuf ); +#endif /* SERVER_NAME_LIST */ + if ( hs->server_hostname == (char*) 0 ) + { +#ifdef SERVER_NAME + hs->server_hostname = SERVER_NAME; +#else /* SERVER_NAME */ + if ( ghnbuf[0] != '\0' ) + hs->server_hostname = ghnbuf; +#endif /* SERVER_NAME */ + } + } + + hs->port = port; + if ( cgi_pattern == (char*) 0 ) + hs->cgi_pattern = (char*) 0; + else + { + /* Nuke any leading slashes. */ + if ( cgi_pattern[0] == '/' ) + ++cgi_pattern; + hs->cgi_pattern = strdup( cgi_pattern ); + if ( hs->cgi_pattern == (char*) 0 ) + { + syslog( LOG_CRIT, ""out of memory copying cgi_pattern"" ); + return (httpd_server*) 0; + } + /* Nuke any leading slashes in the cgi pattern. */ + while ( ( cp = strstr( hs->cgi_pattern, ""|/"" ) ) != (char*) 0 ) + /* -2 for the offset, +1 for the '\0' */ + (void) memmove( cp + 1, cp + 2, strlen( cp ) - 1 ); + } + hs->cgi_limit = cgi_limit; + hs->cgi_count = 0; + hs->charset = strdup( charset ); + hs->p3p = strdup( p3p ); + hs->max_age = max_age; + hs->cwd = strdup( cwd ); + if ( hs->cwd == (char*) 0 ) + { + syslog( LOG_CRIT, ""out of memory copying cwd"" ); + return (httpd_server*) 0; + } + if ( url_pattern == (char*) 0 ) + hs->url_pattern = (char*) 0; + else + { + hs->url_pattern = strdup( url_pattern ); + if ( hs->url_pattern == (char*) 0 ) + { + syslog( LOG_CRIT, ""out of memory copying url_pattern"" ); + return (httpd_server*) 0; + } + } + if ( local_pattern == (char*) 0 ) + hs->local_pattern = (char*) 0; + else + { + hs->local_pattern = strdup( local_pattern ); + if ( hs->local_pattern == (char*) 0 ) + { + syslog( LOG_CRIT, ""out of memory copying local_pattern"" ); + return (httpd_server*) 0; + } + } + hs->no_log = no_log; + hs->logfp = (FILE*) 0; + httpd_set_logfp( hs, logfp ); + hs->no_symlink_check = no_symlink_check; + hs->vhost = vhost; + hs->global_passwd = global_passwd; + hs->no_empty_referers = no_empty_referers; + + /* Initialize listen sockets. Try v6 first because of a Linux peculiarity; + ** like some other systems, it has magical v6 sockets that also listen for + ** v4, but in Linux if you bind a v4 socket first then the v6 bind fails. + */ + if ( sa6P == (httpd_sockaddr*) 0 ) + hs->listen6_fd = -1; + else + hs->listen6_fd = initialize_listen_socket( sa6P ); + if ( sa4P == (httpd_sockaddr*) 0 ) + hs->listen4_fd = -1; + else + hs->listen4_fd = initialize_listen_socket( sa4P ); + /* If we didn't get any valid sockets, fail. */ + if ( hs->listen4_fd == -1 && hs->listen6_fd == -1 ) + { + free_httpd_server( hs ); + return (httpd_server*) 0; + } + + init_mime(); + + /* Done initializing. */ + if ( hs->binding_hostname == (char*) 0 ) + syslog( + LOG_NOTICE, ""%.80s starting on port %d"", SERVER_SOFTWARE, + (int) hs->port ); + else + syslog( + LOG_NOTICE, ""%.80s starting on %.80s, port %d"", SERVER_SOFTWARE, + httpd_ntoa( hs->listen4_fd != -1 ? sa4P : sa6P ), + (int) hs->port ); + return hs; + } +","@@ -2410,7 +2410,7 @@ de_dotdot( char* file ) + while ( strncmp( file, ""./"", 2 ) == 0 ) + (void) memmove( file, file + 2, strlen( file ) - 1 ); + while ( ( cp = strstr( file, ""/./"") ) != (char*) 0 ) +- (void) memmove( cp, cp + 2, strlen( file ) - 1 ); ++ (void) memmove( cp, cp + 2, strlen( cp ) - 1 ); + + /* Alternate between removing leading ../ and removing xxx/../ */ + for (;;)",1277,1608,2048 +18324,"static int x509_crt_verify_child( + mbedtls_x509_crt *child, mbedtls_x509_crt *parent, + mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl, + const mbedtls_x509_crt_profile *profile, + int path_cnt, int self_cnt, uint32_t *flags, + int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), + void *p_vrfy ) +{ + int ret; + uint32_t parent_flags = 0; + unsigned char hash[MBEDTLS_MD_MAX_SIZE]; + mbedtls_x509_crt *grandparent; + const mbedtls_md_info_t *md_info; + + /* Counting intermediate self signed certificates */ + if( ( path_cnt != 0 ) && x509_name_cmp( &child->issuer, &child->subject ) == 0 ) + self_cnt++; + + /* path_cnt is 0 for the first intermediate CA */ + if( 1 + path_cnt > MBEDTLS_X509_MAX_INTERMEDIATE_CA ) + { + *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; + return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ); + } + + if( mbedtls_x509_time_is_past( &child->valid_to ) ) + *flags |= MBEDTLS_X509_BADCERT_EXPIRED; + + if( mbedtls_x509_time_is_future( &child->valid_from ) ) + *flags |= MBEDTLS_X509_BADCERT_FUTURE; + + if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 ) + *flags |= MBEDTLS_X509_BADCERT_BAD_MD; + + if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 ) + *flags |= MBEDTLS_X509_BADCERT_BAD_PK; + + md_info = mbedtls_md_info_from_type( child->sig_md ); + if( md_info == NULL ) + { + /* + * Cannot check 'unknown' hash + */ + *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; + } + else + { + mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash ); + + if( x509_profile_check_key( profile, child->sig_pk, &parent->pk ) != 0 ) + *flags |= MBEDTLS_X509_BADCERT_BAD_KEY; + + if( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk, + child->sig_md, hash, mbedtls_md_get_size( md_info ), + child->sig.p, child->sig.len ) != 0 ) + { + *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; + } + } + +#if defined(MBEDTLS_X509_CRL_PARSE_C) + /* Check trusted CA's CRL for the given crt */ + *flags |= x509_crt_verifycrl(child, parent, ca_crl, profile ); +#endif + + /* Look for a grandparent in trusted CAs */ + for( grandparent = trust_ca; + grandparent != NULL; + grandparent = grandparent->next ) + { + if( x509_crt_check_parent( parent, grandparent, + 0, path_cnt == 0 ) == 0 ) + break; + } + + if( grandparent != NULL ) + { + ret = x509_crt_verify_top( parent, grandparent, ca_crl, profile, + path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy ); + if( ret != 0 ) + return( ret ); + } + else + { + /* Look for a grandparent upwards the chain */ + for( grandparent = parent->next; + grandparent != NULL; + grandparent = grandparent->next ) + { + /* +2 because the current step is not yet accounted for + * and because max_pathlen is one higher than it should be. + * Also self signed certificates do not count to the limit. */ + if( grandparent->max_pathlen > 0 && + grandparent->max_pathlen < 2 + path_cnt - self_cnt ) + { + continue; + } + + if( x509_crt_check_parent( parent, grandparent, + 0, path_cnt == 0 ) == 0 ) + break; + } + + /* Is our parent part of the chain or at the top? */ + if( grandparent != NULL ) + { + ret = x509_crt_verify_child( parent, grandparent, trust_ca, ca_crl, + profile, path_cnt + 1, self_cnt, &parent_flags, + f_vrfy, p_vrfy ); + if( ret != 0 ) + return( ret ); + } + else + { + ret = x509_crt_verify_top( parent, trust_ca, ca_crl, profile, + path_cnt + 1, self_cnt, &parent_flags, + f_vrfy, p_vrfy ); + if( ret != 0 ) + return( ret ); + } + } + + /* child is verified to be a child of the parent, call verify callback */ + if( NULL != f_vrfy ) + if( ( ret = f_vrfy( p_vrfy, child, path_cnt, flags ) ) != 0 ) + return( ret ); + + *flags |= parent_flags; + + return( 0 ); +} +",1,"static int x509_crt_verify_child( + mbedtls_x509_crt *child, mbedtls_x509_crt *parent, + mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl, + const mbedtls_x509_crt_profile *profile, + int path_cnt, int self_cnt, uint32_t *flags, + int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *), + void *p_vrfy ) +{ + int ret; + uint32_t parent_flags = 0; + unsigned char hash[MBEDTLS_MD_MAX_SIZE]; + mbedtls_x509_crt *grandparent; + const mbedtls_md_info_t *md_info; + + /* Counting intermediate self signed certificates */ + if( ( path_cnt != 0 ) && x509_name_cmp( &child->issuer, &child->subject ) == 0 ) + self_cnt++; + + /* path_cnt is 0 for the first intermediate CA */ + if( 1 + path_cnt > MBEDTLS_X509_MAX_INTERMEDIATE_CA ) + { + /* return immediately as the goal is to avoid unbounded recursion */ + return( MBEDTLS_ERR_X509_FATAL_ERROR ); + } + + if( mbedtls_x509_time_is_past( &child->valid_to ) ) + *flags |= MBEDTLS_X509_BADCERT_EXPIRED; + + if( mbedtls_x509_time_is_future( &child->valid_from ) ) + *flags |= MBEDTLS_X509_BADCERT_FUTURE; + + if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 ) + *flags |= MBEDTLS_X509_BADCERT_BAD_MD; + + if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 ) + *flags |= MBEDTLS_X509_BADCERT_BAD_PK; + + md_info = mbedtls_md_info_from_type( child->sig_md ); + if( md_info == NULL ) + { + /* + * Cannot check 'unknown' hash + */ + *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; + } + else + { + mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash ); + + if( x509_profile_check_key( profile, child->sig_pk, &parent->pk ) != 0 ) + *flags |= MBEDTLS_X509_BADCERT_BAD_KEY; + + if( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk, + child->sig_md, hash, mbedtls_md_get_size( md_info ), + child->sig.p, child->sig.len ) != 0 ) + { + *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; + } + } + +#if defined(MBEDTLS_X509_CRL_PARSE_C) + /* Check trusted CA's CRL for the given crt */ + *flags |= x509_crt_verifycrl(child, parent, ca_crl, profile ); +#endif + + /* Look for a grandparent in trusted CAs */ + for( grandparent = trust_ca; + grandparent != NULL; + grandparent = grandparent->next ) + { + if( x509_crt_check_parent( parent, grandparent, + 0, path_cnt == 0 ) == 0 ) + break; + } + + if( grandparent != NULL ) + { + ret = x509_crt_verify_top( parent, grandparent, ca_crl, profile, + path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy ); + if( ret != 0 ) + return( ret ); + } + else + { + /* Look for a grandparent upwards the chain */ + for( grandparent = parent->next; + grandparent != NULL; + grandparent = grandparent->next ) + { + /* +2 because the current step is not yet accounted for + * and because max_pathlen is one higher than it should be. + * Also self signed certificates do not count to the limit. */ + if( grandparent->max_pathlen > 0 && + grandparent->max_pathlen < 2 + path_cnt - self_cnt ) + { + continue; + } + + if( x509_crt_check_parent( parent, grandparent, + 0, path_cnt == 0 ) == 0 ) + break; + } + + /* Is our parent part of the chain or at the top? */ + if( grandparent != NULL ) + { + ret = x509_crt_verify_child( parent, grandparent, trust_ca, ca_crl, + profile, path_cnt + 1, self_cnt, &parent_flags, + f_vrfy, p_vrfy ); + if( ret != 0 ) + return( ret ); + } + else + { + ret = x509_crt_verify_top( parent, trust_ca, ca_crl, profile, + path_cnt + 1, self_cnt, &parent_flags, + f_vrfy, p_vrfy ); + if( ret != 0 ) + return( ret ); + } + } + + /* child is verified to be a child of the parent, call verify callback */ + if( NULL != f_vrfy ) + if( ( ret = f_vrfy( p_vrfy, child, path_cnt, flags ) ) != 0 ) + return( ret ); + + *flags |= parent_flags; + + return( 0 ); +} +","@@ -2057,8 +2057,8 @@ static int x509_crt_verify_child( + /* path_cnt is 0 for the first intermediate CA */ + if( 1 + path_cnt > MBEDTLS_X509_MAX_INTERMEDIATE_CA ) + { +- *flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED; +- return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ); ++ /* return immediately as the goal is to avoid unbounded recursion */ ++ return( MBEDTLS_ERR_X509_FATAL_ERROR ); + } + + if( mbedtls_x509_time_is_past( &child->valid_to ) ) +@@ -2310,6 +2310,10 @@ int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt, + } + + exit: ++ /* prevent misuse of the vrfy callback */ ++ if( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ) ++ ret = MBEDTLS_ERR_X509_FATAL_ERROR; ++ + if( ret != 0 ) + { + *flags = (uint32_t) -1;",1232,1563,2048 +1554,"static DSA_SIG *dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa) +{ + BIGNUM *kinv = NULL; + BIGNUM *m, *blind, *blindm, *tmp; + BN_CTX *ctx = NULL; + int reason = ERR_R_BN_LIB; + DSA_SIG *ret = NULL; + int rv = 0; + + if (dsa->p == NULL || dsa->q == NULL || dsa->g == NULL) { + reason = DSA_R_MISSING_PARAMETERS; + goto err; + } + + ret = DSA_SIG_new(); + if (ret == NULL) + goto err; + ret->r = BN_new(); + ret->s = BN_new(); + if (ret->r == NULL || ret->s == NULL) + goto err; + + ctx = BN_CTX_new(); + if (ctx == NULL) + goto err; + m = BN_CTX_get(ctx); + blind = BN_CTX_get(ctx); + blindm = BN_CTX_get(ctx); + tmp = BN_CTX_get(ctx); + if (tmp == NULL) + goto err; + + redo: + if (!dsa_sign_setup(dsa, ctx, &kinv, &ret->r, dgst, dlen)) + goto err; + + if (dlen > BN_num_bytes(dsa->q)) + /* + * if the digest length is greater than the size of q use the + * BN_num_bits(dsa->q) leftmost bits of the digest, see fips 186-3, + * 4.2 + */ + dlen = BN_num_bytes(dsa->q); + if (BN_bin2bn(dgst, dlen, m) == NULL) + goto err; + + /* + * The normal signature calculation is: + * + * s := k^-1 * (m + r * priv_key) mod q + * + * We will blind this to protect against side channel attacks + * + * s := blind^-1 * k^-1 * (blind * m + blind * r * priv_key) mod q + */ + + /* Generate a blinding value */ + do { + if (!BN_priv_rand(blind, BN_num_bits(dsa->q) - 1, + BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY)) + goto err; + } while (BN_is_zero(blind)); + BN_set_flags(blind, BN_FLG_CONSTTIME); + BN_set_flags(blindm, BN_FLG_CONSTTIME); + BN_set_flags(tmp, BN_FLG_CONSTTIME); + + /* tmp := blind * priv_key * r mod q */ + if (!BN_mod_mul(tmp, blind, dsa->priv_key, dsa->q, ctx)) + goto err; + if (!BN_mod_mul(tmp, tmp, ret->r, dsa->q, ctx)) + goto err; + + /* blindm := blind * m mod q */ + if (!BN_mod_mul(blindm, blind, m, dsa->q, ctx)) + goto err; + + /* s : = (blind * priv_key * r) + (blind * m) mod q */ + if (!BN_mod_add_quick(ret->s, tmp, blindm, dsa->q)) + goto err; + + /* s := s * k^-1 mod q */ + if (!BN_mod_mul(ret->s, ret->s, kinv, dsa->q, ctx)) + goto err; + + /* s:= s * blind^-1 mod q */ + if (BN_mod_inverse(blind, blind, dsa->q, ctx) == NULL) + goto err; + if (!BN_mod_mul(ret->s, ret->s, blind, dsa->q, ctx)) + goto err; + + /* + * Redo if r or s is zero as required by FIPS 186-3: this is very + * unlikely. + */ + if (BN_is_zero(ret->r) || BN_is_zero(ret->s)) + goto redo; + + rv = 1; + + err: + if (rv == 0) { + DSAerr(DSA_F_DSA_DO_SIGN, reason); + DSA_SIG_free(ret); + ret = NULL; + } + BN_CTX_free(ctx); + BN_clear_free(kinv); + return ret; +} +",0,"static DSA_SIG *dsa_do_sign(const unsigned char *dgst, int dlen, DSA *dsa) +{ + BIGNUM *kinv = NULL; + BIGNUM *m, *blind, *blindm, *tmp; + BN_CTX *ctx = NULL; + int reason = ERR_R_BN_LIB; + DSA_SIG *ret = NULL; + int rv = 0; + + if (dsa->p == NULL || dsa->q == NULL || dsa->g == NULL) { + reason = DSA_R_MISSING_PARAMETERS; + goto err; + } + + ret = DSA_SIG_new(); + if (ret == NULL) + goto err; + ret->r = BN_new(); + ret->s = BN_new(); + if (ret->r == NULL || ret->s == NULL) + goto err; + + ctx = BN_CTX_new(); + if (ctx == NULL) + goto err; + m = BN_CTX_get(ctx); + blind = BN_CTX_get(ctx); + blindm = BN_CTX_get(ctx); + tmp = BN_CTX_get(ctx); + if (tmp == NULL) + goto err; + + redo: + if (!dsa_sign_setup(dsa, ctx, &kinv, &ret->r, dgst, dlen)) + goto err; + + if (dlen > BN_num_bytes(dsa->q)) + /* + * if the digest length is greater than the size of q use the + * BN_num_bits(dsa->q) leftmost bits of the digest, see fips 186-3, + * 4.2 + */ + dlen = BN_num_bytes(dsa->q); + if (BN_bin2bn(dgst, dlen, m) == NULL) + goto err; + + /* + * The normal signature calculation is: + * + * s := k^-1 * (m + r * priv_key) mod q + * + * We will blind this to protect against side channel attacks + * + * s := blind^-1 * k^-1 * (blind * m + blind * r * priv_key) mod q + */ + + /* Generate a blinding value */ + do { + if (!BN_priv_rand(blind, BN_num_bits(dsa->q) - 1, + BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY)) + goto err; + } while (BN_is_zero(blind)); + BN_set_flags(blind, BN_FLG_CONSTTIME); + BN_set_flags(blindm, BN_FLG_CONSTTIME); + BN_set_flags(tmp, BN_FLG_CONSTTIME); + + /* tmp := blind * priv_key * r mod q */ + if (!BN_mod_mul(tmp, blind, dsa->priv_key, dsa->q, ctx)) + goto err; + if (!BN_mod_mul(tmp, tmp, ret->r, dsa->q, ctx)) + goto err; + + /* blindm := blind * m mod q */ + if (!BN_mod_mul(blindm, blind, m, dsa->q, ctx)) + goto err; + + /* s : = (blind * priv_key * r) + (blind * m) mod q */ + if (!BN_mod_add_quick(ret->s, tmp, blindm, dsa->q)) + goto err; + + /* s := s * k^-1 mod q */ + if (!BN_mod_mul(ret->s, ret->s, kinv, dsa->q, ctx)) + goto err; + + /* s:= s * blind^-1 mod q */ + if (BN_mod_inverse(blind, blind, dsa->q, ctx) == NULL) + goto err; + if (!BN_mod_mul(ret->s, ret->s, blind, dsa->q, ctx)) + goto err; + + /* + * Redo if r or s is zero as required by FIPS 186-3: this is very + * unlikely. + */ + if (BN_is_zero(ret->r) || BN_is_zero(ret->s)) + goto redo; + + rv = 1; + + err: + if (rv == 0) { + DSAerr(DSA_F_DSA_DO_SIGN, reason); + DSA_SIG_free(ret); + ret = NULL; + } + BN_CTX_free(ctx); + BN_clear_free(kinv); + return ret; +} +","@@ -9,6 +9,7 @@ + + #include + #include ""internal/cryptlib.h"" ++#include ""internal/bn_int.h"" + #include + #include + #include ""dsa_locl.h"" +@@ -180,9 +181,9 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, + { + BN_CTX *ctx = NULL; + BIGNUM *k, *kinv = NULL, *r = *rp; +- BIGNUM *l, *m; ++ BIGNUM *l; + int ret = 0; +- int q_bits; ++ int q_bits, q_words; + + if (!dsa->p || !dsa->q || !dsa->g) { + DSAerr(DSA_F_DSA_SIGN_SETUP, DSA_R_MISSING_PARAMETERS); +@@ -191,8 +192,7 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, + + k = BN_new(); + l = BN_new(); +- m = BN_new(); +- if (k == NULL || l == NULL || m == NULL) ++ if (k == NULL || l == NULL) + goto err; + + if (ctx_in == NULL) { +@@ -203,9 +203,9 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, + + /* Preallocate space */ + q_bits = BN_num_bits(dsa->q); +- if (!BN_set_bit(k, q_bits) +- || !BN_set_bit(l, q_bits) +- || !BN_set_bit(m, q_bits)) ++ q_words = bn_get_top(dsa->q); ++ if (!bn_wexpand(k, q_words + 2) ++ || !bn_wexpand(l, q_words + 2)) + goto err; + + /* Get random k */ +@@ -240,14 +240,17 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, + * small timing information leakage. We then choose the sum that is + * one bit longer than the modulus. + * +- * TODO: revisit the BN_copy aiming for a memory access agnostic +- * conditional copy. ++ * There are some concerns about the efficacy of doing this. More ++ * specificly refer to the discussion starting with: ++ * https://github.com/openssl/openssl/pull/7486#discussion_r228323705 ++ * The fix is to rework BN so these gymnastics aren't required. + */ + if (!BN_add(l, k, dsa->q) +- || !BN_add(m, l, dsa->q) +- || !BN_copy(k, BN_num_bits(l) > q_bits ? l : m)) ++ || !BN_add(k, l, dsa->q)) + goto err; + ++ BN_consttime_swap(BN_is_bit_set(l, q_bits), k, l, q_words + 2); ++ + if ((dsa)->meth->bn_mod_exp != NULL) { + if (!dsa->meth->bn_mod_exp(dsa, r, dsa->g, k, dsa->p, ctx, + dsa->method_mont_p)) +@@ -260,7 +263,7 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, + if (!BN_mod(r, r, dsa->q, ctx)) + goto err; + +- /* Compute part of 's = inv(k) (m + xr) mod q' */ ++ /* Compute part of 's = inv(k) (m + xr) mod q' */ + if ((kinv = dsa_mod_inverse_fermat(k, dsa->q, ctx)) == NULL) + goto err; + +@@ -275,7 +278,6 @@ static int dsa_sign_setup(DSA *dsa, BN_CTX *ctx_in, + BN_CTX_free(ctx); + BN_clear_free(k); + BN_clear_free(l); +- BN_clear_free(m); + return ret; + }",924,1255,2048 +17039,"status_t MPEG4Source::parseChunk(off64_t *offset) { + uint32_t hdr[2]; + if (mDataSource->readAt(*offset, hdr, 8) < 8) { + return ERROR_IO; + } + uint64_t chunk_size = ntohl(hdr[0]); + uint32_t chunk_type = ntohl(hdr[1]); + off64_t data_offset = *offset + 8; + + if (chunk_size == 1) { + if (mDataSource->readAt(*offset + 8, &chunk_size, 8) < 8) { + return ERROR_IO; + } + chunk_size = ntoh64(chunk_size); + data_offset += 8; + + if (chunk_size < 16) { + return ERROR_MALFORMED; + } + } else if (chunk_size < 8) { + return ERROR_MALFORMED; + } + + char chunk[5]; + MakeFourCCString(chunk_type, chunk); + ALOGV(""MPEG4Source chunk %s @ %llx"", chunk, *offset); + + off64_t chunk_data_size = *offset + chunk_size - data_offset; + + switch(chunk_type) { + + case FOURCC('t', 'r', 'a', 'f'): + case FOURCC('m', 'o', 'o', 'f'): { + off64_t stop_offset = *offset + chunk_size; + *offset = data_offset; + while (*offset < stop_offset) { + status_t err = parseChunk(offset); + if (err != OK) { + return err; + } + } + if (chunk_type == FOURCC('m', 'o', 'o', 'f')) { + + while (true) { + if (mDataSource->readAt(*offset, hdr, 8) < 8) { + return ERROR_END_OF_STREAM; + } + chunk_size = ntohl(hdr[0]); + chunk_type = ntohl(hdr[1]); + if (chunk_type == FOURCC('m', 'o', 'o', 'f')) { + mNextMoofOffset = *offset; + break; + } + *offset += chunk_size; + } + } + break; + } + + case FOURCC('t', 'f', 'h', 'd'): { + status_t err; + if ((err = parseTrackFragmentHeader(data_offset, chunk_data_size)) != OK) { + return err; + } + *offset += chunk_size; + break; + } + + case FOURCC('t', 'r', 'u', 'n'): { + status_t err; + if (mLastParsedTrackId == mTrackId) { + if ((err = parseTrackFragmentRun(data_offset, chunk_data_size)) != OK) { + return err; + } + } + + *offset += chunk_size; + break; + } + + case FOURCC('s', 'a', 'i', 'z'): { + status_t err; + if ((err = parseSampleAuxiliaryInformationSizes(data_offset, chunk_data_size)) != OK) { + return err; + } + *offset += chunk_size; + break; + } + case FOURCC('s', 'a', 'i', 'o'): { + status_t err; + if ((err = parseSampleAuxiliaryInformationOffsets(data_offset, chunk_data_size)) != OK) { + return err; + } + *offset += chunk_size; + break; + } + + case FOURCC('m', 'd', 'a', 't'): { + ALOGV(""MPEG4Source::parseChunk mdat""); + *offset += chunk_size; + break; + } + + default: { + *offset += chunk_size; + break; + } + } + return OK; +} +",0,"status_t MPEG4Source::parseChunk(off64_t *offset) { + uint32_t hdr[2]; + if (mDataSource->readAt(*offset, hdr, 8) < 8) { + return ERROR_IO; + } + uint64_t chunk_size = ntohl(hdr[0]); + uint32_t chunk_type = ntohl(hdr[1]); + off64_t data_offset = *offset + 8; + + if (chunk_size == 1) { + if (mDataSource->readAt(*offset + 8, &chunk_size, 8) < 8) { + return ERROR_IO; + } + chunk_size = ntoh64(chunk_size); + data_offset += 8; + + if (chunk_size < 16) { + return ERROR_MALFORMED; + } + } else if (chunk_size < 8) { + return ERROR_MALFORMED; + } + + char chunk[5]; + MakeFourCCString(chunk_type, chunk); + ALOGV(""MPEG4Source chunk %s @ %llx"", chunk, *offset); + + off64_t chunk_data_size = *offset + chunk_size - data_offset; + + switch(chunk_type) { + + case FOURCC('t', 'r', 'a', 'f'): + case FOURCC('m', 'o', 'o', 'f'): { + off64_t stop_offset = *offset + chunk_size; + *offset = data_offset; + while (*offset < stop_offset) { + status_t err = parseChunk(offset); + if (err != OK) { + return err; + } + } + if (chunk_type == FOURCC('m', 'o', 'o', 'f')) { + + while (true) { + if (mDataSource->readAt(*offset, hdr, 8) < 8) { + return ERROR_END_OF_STREAM; + } + chunk_size = ntohl(hdr[0]); + chunk_type = ntohl(hdr[1]); + if (chunk_type == FOURCC('m', 'o', 'o', 'f')) { + mNextMoofOffset = *offset; + break; + } + *offset += chunk_size; + } + } + break; + } + + case FOURCC('t', 'f', 'h', 'd'): { + status_t err; + if ((err = parseTrackFragmentHeader(data_offset, chunk_data_size)) != OK) { + return err; + } + *offset += chunk_size; + break; + } + + case FOURCC('t', 'r', 'u', 'n'): { + status_t err; + if (mLastParsedTrackId == mTrackId) { + if ((err = parseTrackFragmentRun(data_offset, chunk_data_size)) != OK) { + return err; + } + } + + *offset += chunk_size; + break; + } + + case FOURCC('s', 'a', 'i', 'z'): { + status_t err; + if ((err = parseSampleAuxiliaryInformationSizes(data_offset, chunk_data_size)) != OK) { + return err; + } + *offset += chunk_size; + break; + } + case FOURCC('s', 'a', 'i', 'o'): { + status_t err; + if ((err = parseSampleAuxiliaryInformationOffsets(data_offset, chunk_data_size)) != OK) { + return err; + } + *offset += chunk_size; + break; + } + + case FOURCC('m', 'd', 'a', 't'): { + ALOGV(""MPEG4Source::parseChunk mdat""); + *offset += chunk_size; + break; + } + + default: { + *offset += chunk_size; + break; + } + } + return OK; +} +","@@ -1893,7 +1893,7 @@ + + size = 0; + } + +- if (SIZE_MAX - chunk_size <= size) { ++ if ((chunk_size > SIZE_MAX) || (SIZE_MAX - chunk_size <= size)) { + return ERROR_MALFORMED; + } + +",715,1046,2048 +6872,"static void klsi_105_set_termios(struct tty_struct *tty, + struct usb_serial_port *port, + struct ktermios *old_termios) +{ + struct klsi_105_private *priv = usb_get_serial_port_data(port); + struct device *dev = &port->dev; + unsigned int iflag = tty->termios.c_iflag; + unsigned int old_iflag = old_termios->c_iflag; + unsigned int cflag = tty->termios.c_cflag; + unsigned int old_cflag = old_termios->c_cflag; + struct klsi_105_port_settings *cfg; + unsigned long flags; + speed_t baud; + + cfg = kmalloc(sizeof(*cfg), GFP_KERNEL); + if (!cfg) + return; + + /* lock while we are modifying the settings */ + spin_lock_irqsave(&priv->lock, flags); + + /* + * Update baud rate + */ + baud = tty_get_baud_rate(tty); + + if ((cflag & CBAUD) != (old_cflag & CBAUD)) { + /* reassert DTR and (maybe) RTS on transition from B0 */ + if ((old_cflag & CBAUD) == B0) { + dev_dbg(dev, ""%s: baud was B0\n"", __func__); +#if 0 + priv->control_state |= TIOCM_DTR; + /* don't set RTS if using hardware flow control */ + if (!(old_cflag & CRTSCTS)) + priv->control_state |= TIOCM_RTS; + mct_u232_set_modem_ctrl(serial, priv->control_state); +#endif + } + } + switch (baud) { + case 0: /* handled below */ + break; + case 1200: + priv->cfg.baudrate = kl5kusb105a_sio_b1200; + break; + case 2400: + priv->cfg.baudrate = kl5kusb105a_sio_b2400; + break; + case 4800: + priv->cfg.baudrate = kl5kusb105a_sio_b4800; + break; + case 9600: + priv->cfg.baudrate = kl5kusb105a_sio_b9600; + break; + case 19200: + priv->cfg.baudrate = kl5kusb105a_sio_b19200; + break; + case 38400: + priv->cfg.baudrate = kl5kusb105a_sio_b38400; + break; + case 57600: + priv->cfg.baudrate = kl5kusb105a_sio_b57600; + break; + case 115200: + priv->cfg.baudrate = kl5kusb105a_sio_b115200; + break; + default: + dev_dbg(dev, ""unsupported baudrate, using 9600\n""); + priv->cfg.baudrate = kl5kusb105a_sio_b9600; + baud = 9600; + break; + } + if ((cflag & CBAUD) == B0) { + dev_dbg(dev, ""%s: baud is B0\n"", __func__); + /* Drop RTS and DTR */ + /* maybe this should be simulated by sending read + * disable and read enable messages? + */ +#if 0 + priv->control_state &= ~(TIOCM_DTR | TIOCM_RTS); + mct_u232_set_modem_ctrl(serial, priv->control_state); +#endif + } + tty_encode_baud_rate(tty, baud, baud); + + if ((cflag & CSIZE) != (old_cflag & CSIZE)) { + /* set the number of data bits */ + switch (cflag & CSIZE) { + case CS5: + dev_dbg(dev, ""%s - 5 bits/byte not supported\n"", __func__); + spin_unlock_irqrestore(&priv->lock, flags); + goto err; + case CS6: + dev_dbg(dev, ""%s - 6 bits/byte not supported\n"", __func__); + spin_unlock_irqrestore(&priv->lock, flags); + goto err; + case CS7: + priv->cfg.databits = kl5kusb105a_dtb_7; + break; + case CS8: + priv->cfg.databits = kl5kusb105a_dtb_8; + break; + default: + dev_err(dev, ""CSIZE was not CS5-CS8, using default of 8\n""); + priv->cfg.databits = kl5kusb105a_dtb_8; + break; + } + } + + /* + * Update line control register (LCR) + */ + if ((cflag & (PARENB|PARODD)) != (old_cflag & (PARENB|PARODD)) + || (cflag & CSTOPB) != (old_cflag & CSTOPB)) { + /* Not currently supported */ + tty->termios.c_cflag &= ~(PARENB|PARODD|CSTOPB); +#if 0 + priv->last_lcr = 0; + + /* set the parity */ + if (cflag & PARENB) + priv->last_lcr |= (cflag & PARODD) ? + MCT_U232_PARITY_ODD : MCT_U232_PARITY_EVEN; + else + priv->last_lcr |= MCT_U232_PARITY_NONE; + + /* set the number of stop bits */ + priv->last_lcr |= (cflag & CSTOPB) ? + MCT_U232_STOP_BITS_2 : MCT_U232_STOP_BITS_1; + + mct_u232_set_line_ctrl(serial, priv->last_lcr); +#endif + } + /* + * Set flow control: well, I do not really now how to handle DTR/RTS. + * Just do what we have seen with SniffUSB on Win98. + */ + if ((iflag & IXOFF) != (old_iflag & IXOFF) + || (iflag & IXON) != (old_iflag & IXON) + || (cflag & CRTSCTS) != (old_cflag & CRTSCTS)) { + /* Not currently supported */ + tty->termios.c_cflag &= ~CRTSCTS; + /* Drop DTR/RTS if no flow control otherwise assert */ +#if 0 + if ((iflag & IXOFF) || (iflag & IXON) || (cflag & CRTSCTS)) + priv->control_state |= TIOCM_DTR | TIOCM_RTS; + else + priv->control_state &= ~(TIOCM_DTR | TIOCM_RTS); + mct_u232_set_modem_ctrl(serial, priv->control_state); +#endif + } + memcpy(cfg, &priv->cfg, sizeof(*cfg)); + spin_unlock_irqrestore(&priv->lock, flags); + + /* now commit changes to device */ + klsi_105_chg_port_settings(port, cfg); +err: + kfree(cfg); +} +",0,"static void klsi_105_set_termios(struct tty_struct *tty, + struct usb_serial_port *port, + struct ktermios *old_termios) +{ + struct klsi_105_private *priv = usb_get_serial_port_data(port); + struct device *dev = &port->dev; + unsigned int iflag = tty->termios.c_iflag; + unsigned int old_iflag = old_termios->c_iflag; + unsigned int cflag = tty->termios.c_cflag; + unsigned int old_cflag = old_termios->c_cflag; + struct klsi_105_port_settings *cfg; + unsigned long flags; + speed_t baud; + + cfg = kmalloc(sizeof(*cfg), GFP_KERNEL); + if (!cfg) + return; + + /* lock while we are modifying the settings */ + spin_lock_irqsave(&priv->lock, flags); + + /* + * Update baud rate + */ + baud = tty_get_baud_rate(tty); + + if ((cflag & CBAUD) != (old_cflag & CBAUD)) { + /* reassert DTR and (maybe) RTS on transition from B0 */ + if ((old_cflag & CBAUD) == B0) { + dev_dbg(dev, ""%s: baud was B0\n"", __func__); +#if 0 + priv->control_state |= TIOCM_DTR; + /* don't set RTS if using hardware flow control */ + if (!(old_cflag & CRTSCTS)) + priv->control_state |= TIOCM_RTS; + mct_u232_set_modem_ctrl(serial, priv->control_state); +#endif + } + } + switch (baud) { + case 0: /* handled below */ + break; + case 1200: + priv->cfg.baudrate = kl5kusb105a_sio_b1200; + break; + case 2400: + priv->cfg.baudrate = kl5kusb105a_sio_b2400; + break; + case 4800: + priv->cfg.baudrate = kl5kusb105a_sio_b4800; + break; + case 9600: + priv->cfg.baudrate = kl5kusb105a_sio_b9600; + break; + case 19200: + priv->cfg.baudrate = kl5kusb105a_sio_b19200; + break; + case 38400: + priv->cfg.baudrate = kl5kusb105a_sio_b38400; + break; + case 57600: + priv->cfg.baudrate = kl5kusb105a_sio_b57600; + break; + case 115200: + priv->cfg.baudrate = kl5kusb105a_sio_b115200; + break; + default: + dev_dbg(dev, ""unsupported baudrate, using 9600\n""); + priv->cfg.baudrate = kl5kusb105a_sio_b9600; + baud = 9600; + break; + } + if ((cflag & CBAUD) == B0) { + dev_dbg(dev, ""%s: baud is B0\n"", __func__); + /* Drop RTS and DTR */ + /* maybe this should be simulated by sending read + * disable and read enable messages? + */ +#if 0 + priv->control_state &= ~(TIOCM_DTR | TIOCM_RTS); + mct_u232_set_modem_ctrl(serial, priv->control_state); +#endif + } + tty_encode_baud_rate(tty, baud, baud); + + if ((cflag & CSIZE) != (old_cflag & CSIZE)) { + /* set the number of data bits */ + switch (cflag & CSIZE) { + case CS5: + dev_dbg(dev, ""%s - 5 bits/byte not supported\n"", __func__); + spin_unlock_irqrestore(&priv->lock, flags); + goto err; + case CS6: + dev_dbg(dev, ""%s - 6 bits/byte not supported\n"", __func__); + spin_unlock_irqrestore(&priv->lock, flags); + goto err; + case CS7: + priv->cfg.databits = kl5kusb105a_dtb_7; + break; + case CS8: + priv->cfg.databits = kl5kusb105a_dtb_8; + break; + default: + dev_err(dev, ""CSIZE was not CS5-CS8, using default of 8\n""); + priv->cfg.databits = kl5kusb105a_dtb_8; + break; + } + } + + /* + * Update line control register (LCR) + */ + if ((cflag & (PARENB|PARODD)) != (old_cflag & (PARENB|PARODD)) + || (cflag & CSTOPB) != (old_cflag & CSTOPB)) { + /* Not currently supported */ + tty->termios.c_cflag &= ~(PARENB|PARODD|CSTOPB); +#if 0 + priv->last_lcr = 0; + + /* set the parity */ + if (cflag & PARENB) + priv->last_lcr |= (cflag & PARODD) ? + MCT_U232_PARITY_ODD : MCT_U232_PARITY_EVEN; + else + priv->last_lcr |= MCT_U232_PARITY_NONE; + + /* set the number of stop bits */ + priv->last_lcr |= (cflag & CSTOPB) ? + MCT_U232_STOP_BITS_2 : MCT_U232_STOP_BITS_1; + + mct_u232_set_line_ctrl(serial, priv->last_lcr); +#endif + } + /* + * Set flow control: well, I do not really now how to handle DTR/RTS. + * Just do what we have seen with SniffUSB on Win98. + */ + if ((iflag & IXOFF) != (old_iflag & IXOFF) + || (iflag & IXON) != (old_iflag & IXON) + || (cflag & CRTSCTS) != (old_cflag & CRTSCTS)) { + /* Not currently supported */ + tty->termios.c_cflag &= ~CRTSCTS; + /* Drop DTR/RTS if no flow control otherwise assert */ +#if 0 + if ((iflag & IXOFF) || (iflag & IXON) || (cflag & CRTSCTS)) + priv->control_state |= TIOCM_DTR | TIOCM_RTS; + else + priv->control_state &= ~(TIOCM_DTR | TIOCM_RTS); + mct_u232_set_modem_ctrl(serial, priv->control_state); +#endif + } + memcpy(cfg, &priv->cfg, sizeof(*cfg)); + spin_unlock_irqrestore(&priv->lock, flags); + + /* now commit changes to device */ + klsi_105_chg_port_settings(port, cfg); +err: + kfree(cfg); +} +","@@ -192,10 +192,11 @@ static int klsi_105_get_line_state(struct usb_serial_port *port, + status_buf, KLSI_STATUSBUF_LEN, + 10000 + ); +- if (rc < 0) +- dev_err(&port->dev, ""Reading line status failed (error = %d)\n"", +- rc); +- else { ++ if (rc != KLSI_STATUSBUF_LEN) { ++ dev_err(&port->dev, ""reading line status failed: %d\n"", rc); ++ if (rc >= 0) ++ rc = -EIO; ++ } else { + status = get_unaligned_le16(status_buf); + + dev_info(&port->serial->dev->dev, ""read status %x %x\n"",",1589,1920,2048 +17841,"xps_parse_gradient_stops(xps_document *doc, char *base_uri, fz_xml *node, + struct stop *stops, int maxcount) + { + fz_colorspace *colorspace; + float sample[8]; + float rgb[3]; + int before, after; + int count; + int i; + + /* We may have to insert 2 extra stops when postprocessing */ + maxcount -= 2; + + count = 0; + while (node && count < maxcount) + { + if (!strcmp(fz_xml_tag(node), ""GradientStop"")) + { + char *offset = fz_xml_att(node, ""Offset""); + char *color = fz_xml_att(node, ""Color""); + if (offset && color) + { + stops[count].offset = fz_atof(offset); + stops[count].index = count; + + xps_parse_color(doc, base_uri, color, &colorspace, sample); + + fz_convert_color(doc->ctx, fz_device_rgb(doc->ctx), rgb, colorspace, sample + 1); + + stops[count].r = rgb[0]; + stops[count].g = rgb[1]; + stops[count].b = rgb[2]; + stops[count].a = sample[0]; + + count ++; + } + } + node = fz_xml_next(node); + } + + if (count == 0) + { + fz_warn(doc->ctx, ""gradient brush has no gradient stops""); + stops[0].offset = 0; + stops[0].r = 0; + stops[0].g = 0; + stops[0].b = 0; + stops[0].a = 1; + stops[1].offset = 1; + stops[1].r = 1; + stops[1].g = 1; + stops[1].b = 1; + stops[1].a = 1; + return 2; + } + + if (count == maxcount) + fz_warn(doc->ctx, ""gradient brush exceeded maximum number of gradient stops""); + + /* Postprocess to make sure the range of offsets is 0.0 to 1.0 */ + + qsort(stops, count, sizeof(struct stop), cmp_stop); + + before = -1; + after = -1; + + for (i = 0; i < count; i++) + { + if (stops[i].offset < 0) + before = i; + if (stops[i].offset > 1) + { + after = i; + break; + } + } + + /* Remove all stops < 0 except the largest one */ + if (before > 0) + { + memmove(stops, stops + before, (count - before) * sizeof(struct stop)); + count -= before; + } + + /* Remove all stops > 1 except the smallest one */ + if (after >= 0) + count = after + 1; + + /* Expand single stop to 0 .. 1 */ + if (count == 1) + { + stops[1] = stops[0]; + stops[0].offset = 0; + stops[1].offset = 1; + return 2; + } + + /* First stop < 0 -- interpolate value to 0 */ + if (stops[0].offset < 0) + { + float d = -stops[0].offset / (stops[1].offset - stops[0].offset); + stops[0].offset = 0; + stops[0].r = lerp(stops[0].r, stops[1].r, d); + stops[0].g = lerp(stops[0].g, stops[1].g, d); + stops[0].b = lerp(stops[0].b, stops[1].b, d); + stops[0].a = lerp(stops[0].a, stops[1].a, d); + } + + /* Last stop > 1 -- interpolate value to 1 */ + if (stops[count-1].offset > 1) + { + float d = (1 - stops[count-2].offset) / (stops[count-1].offset - stops[count-2].offset); + stops[count-1].offset = 1; + stops[count-1].r = lerp(stops[count-2].r, stops[count-1].r, d); + stops[count-1].g = lerp(stops[count-2].g, stops[count-1].g, d); + stops[count-1].b = lerp(stops[count-2].b, stops[count-1].b, d); + stops[count-1].a = lerp(stops[count-2].a, stops[count-1].a, d); + } + + /* First stop > 0 -- insert a duplicate at 0 */ + if (stops[0].offset > 0) + { + memmove(stops + 1, stops, count * sizeof(struct stop)); + stops[0] = stops[1]; + stops[0].offset = 0; + count++; + } + + /* Last stop < 1 -- insert a duplicate at 1 */ + if (stops[count-1].offset < 1) + { + stops[count] = stops[count-1]; + stops[count].offset = 1; + count++; + } + + return count; +} +",1,"xps_parse_gradient_stops(xps_document *doc, char *base_uri, fz_xml *node, + struct stop *stops, int maxcount) + { + fz_colorspace *colorspace; + float sample[FZ_MAX_COLORS]; + float rgb[3]; + int before, after; + int count; + int i; + + /* We may have to insert 2 extra stops when postprocessing */ + maxcount -= 2; + + count = 0; + while (node && count < maxcount) + { + if (!strcmp(fz_xml_tag(node), ""GradientStop"")) + { + char *offset = fz_xml_att(node, ""Offset""); + char *color = fz_xml_att(node, ""Color""); + if (offset && color) + { + stops[count].offset = fz_atof(offset); + stops[count].index = count; + + xps_parse_color(doc, base_uri, color, &colorspace, sample); + + fz_convert_color(doc->ctx, fz_device_rgb(doc->ctx), rgb, colorspace, sample + 1); + + stops[count].r = rgb[0]; + stops[count].g = rgb[1]; + stops[count].b = rgb[2]; + stops[count].a = sample[0]; + + count ++; + } + } + node = fz_xml_next(node); + } + + if (count == 0) + { + fz_warn(doc->ctx, ""gradient brush has no gradient stops""); + stops[0].offset = 0; + stops[0].r = 0; + stops[0].g = 0; + stops[0].b = 0; + stops[0].a = 1; + stops[1].offset = 1; + stops[1].r = 1; + stops[1].g = 1; + stops[1].b = 1; + stops[1].a = 1; + return 2; + } + + if (count == maxcount) + fz_warn(doc->ctx, ""gradient brush exceeded maximum number of gradient stops""); + + /* Postprocess to make sure the range of offsets is 0.0 to 1.0 */ + + qsort(stops, count, sizeof(struct stop), cmp_stop); + + before = -1; + after = -1; + + for (i = 0; i < count; i++) + { + if (stops[i].offset < 0) + before = i; + if (stops[i].offset > 1) + { + after = i; + break; + } + } + + /* Remove all stops < 0 except the largest one */ + if (before > 0) + { + memmove(stops, stops + before, (count - before) * sizeof(struct stop)); + count -= before; + } + + /* Remove all stops > 1 except the smallest one */ + if (after >= 0) + count = after + 1; + + /* Expand single stop to 0 .. 1 */ + if (count == 1) + { + stops[1] = stops[0]; + stops[0].offset = 0; + stops[1].offset = 1; + return 2; + } + + /* First stop < 0 -- interpolate value to 0 */ + if (stops[0].offset < 0) + { + float d = -stops[0].offset / (stops[1].offset - stops[0].offset); + stops[0].offset = 0; + stops[0].r = lerp(stops[0].r, stops[1].r, d); + stops[0].g = lerp(stops[0].g, stops[1].g, d); + stops[0].b = lerp(stops[0].b, stops[1].b, d); + stops[0].a = lerp(stops[0].a, stops[1].a, d); + } + + /* Last stop > 1 -- interpolate value to 1 */ + if (stops[count-1].offset > 1) + { + float d = (1 - stops[count-2].offset) / (stops[count-1].offset - stops[count-2].offset); + stops[count-1].offset = 1; + stops[count-1].r = lerp(stops[count-2].r, stops[count-1].r, d); + stops[count-1].g = lerp(stops[count-2].g, stops[count-1].g, d); + stops[count-1].b = lerp(stops[count-2].b, stops[count-1].b, d); + stops[count-1].a = lerp(stops[count-2].a, stops[count-1].a, d); + } + + /* First stop > 0 -- insert a duplicate at 0 */ + if (stops[0].offset > 0) + { + memmove(stops + 1, stops, count * sizeof(struct stop)); + stops[0] = stops[1]; + stops[0].offset = 0; + count++; + } + + /* Last stop < 1 -- insert a duplicate at 1 */ + if (stops[count-1].offset < 1) + { + stops[count] = stops[count-1]; + stops[count].offset = 1; + count++; + } + + return count; +} +","@@ -39,7 +39,7 @@ xps_parse_gradient_stops(xps_document *doc, char *base_uri, fz_xml *node, + struct stop *stops, int maxcount) + { + fz_colorspace *colorspace; +- float sample[8]; ++ float sample[FZ_MAX_COLORS]; + float rgb[3]; + int before, after; + int count;",1175,1506,2048 +3111,"vmci_transport_recv_connecting_server(struct sock *listener, + struct sock *pending, + struct vmci_transport_packet *pkt) +{ + struct vsock_sock *vpending; + struct vmci_handle handle; + struct vmci_qp *qpair; + bool is_local; + u32 flags; + u32 detach_sub_id; + int err; + int skerr; + + vpending = vsock_sk(pending); + detach_sub_id = VMCI_INVALID_ID; + + switch (pkt->type) { + case VMCI_TRANSPORT_PACKET_TYPE_OFFER: + if (vmci_handle_is_invalid(pkt->u.handle)) { + vmci_transport_send_reset(pending, pkt); + skerr = EPROTO; + err = -EINVAL; + goto destroy; + } + break; + default: + /* Close and cleanup the connection. */ + vmci_transport_send_reset(pending, pkt); + skerr = EPROTO; + err = pkt->type == VMCI_TRANSPORT_PACKET_TYPE_RST ? 0 : -EINVAL; + goto destroy; + } + + /* In order to complete the connection we need to attach to the offered + * queue pair and send an attach notification. We also subscribe to the + * detach event so we know when our peer goes away, and we do that + * before attaching so we don't miss an event. If all this succeeds, + * we update our state and wakeup anything waiting in accept() for a + * connection. + */ + + /* We don't care about attach since we ensure the other side has + * attached by specifying the ATTACH_ONLY flag below. + */ + err = vmci_event_subscribe(VMCI_EVENT_QP_PEER_DETACH, + vmci_transport_peer_detach_cb, + pending, &detach_sub_id); + if (err < VMCI_SUCCESS) { + vmci_transport_send_reset(pending, pkt); + err = vmci_transport_error_to_vsock_error(err); + skerr = -err; + goto destroy; + } + + vmci_trans(vpending)->detach_sub_id = detach_sub_id; + + /* Now attach to the queue pair the client created. */ + handle = pkt->u.handle; + + /* vpending->local_addr always has a context id so we do not need to + * worry about VMADDR_CID_ANY in this case. + */ + is_local = + vpending->remote_addr.svm_cid == vpending->local_addr.svm_cid; + flags = VMCI_QPFLAG_ATTACH_ONLY; + flags |= is_local ? VMCI_QPFLAG_LOCAL : 0; + + err = vmci_transport_queue_pair_alloc( + &qpair, + &handle, + vmci_trans(vpending)->produce_size, + vmci_trans(vpending)->consume_size, + pkt->dg.src.context, + flags, + vmci_transport_is_trusted( + vpending, + vpending->remote_addr.svm_cid)); + if (err < 0) { + vmci_transport_send_reset(pending, pkt); + skerr = -err; + goto destroy; + } + + vmci_trans(vpending)->qp_handle = handle; + vmci_trans(vpending)->qpair = qpair; + + /* When we send the attach message, we must be ready to handle incoming + * control messages on the newly connected socket. So we move the + * pending socket to the connected state before sending the attach + * message. Otherwise, an incoming packet triggered by the attach being + * received by the peer may be processed concurrently with what happens + * below after sending the attach message, and that incoming packet + * will find the listening socket instead of the (currently) pending + * socket. Note that enqueueing the socket increments the reference + * count, so even if a reset comes before the connection is accepted, + * the socket will be valid until it is removed from the queue. + * + * If we fail sending the attach below, we remove the socket from the + * connected list and move the socket to SS_UNCONNECTED before + * releasing the lock, so a pending slow path processing of an incoming + * packet will not see the socket in the connected state in that case. + */ + pending->sk_state = SS_CONNECTED; + + vsock_insert_connected(vpending); + + /* Notify our peer of our attach. */ + err = vmci_transport_send_attach(pending, handle); + if (err < 0) { + vsock_remove_connected(vpending); + pr_err(""Could not send attach\n""); + vmci_transport_send_reset(pending, pkt); + err = vmci_transport_error_to_vsock_error(err); + skerr = -err; + goto destroy; + } + + /* We have a connection. Move the now connected socket from the + * listener's pending list to the accept queue so callers of accept() + * can find it. + */ + vsock_remove_pending(listener, pending); + vsock_enqueue_accept(listener, pending); + + /* Callers of accept() will be be waiting on the listening socket, not + * the pending socket. + */ + listener->sk_state_change(listener); + + return 0; + +destroy: + pending->sk_err = skerr; + pending->sk_state = SS_UNCONNECTED; + /* As long as we drop our reference, all necessary cleanup will handle + * when the cleanup function drops its reference and our destruct + * implementation is called. Note that since the listen handler will + * remove pending from the pending list upon our failure, the cleanup + * function won't drop the additional reference, which is why we do it + * here. + */ + sock_put(pending); + + return err; +} +",0,"vmci_transport_recv_connecting_server(struct sock *listener, + struct sock *pending, + struct vmci_transport_packet *pkt) +{ + struct vsock_sock *vpending; + struct vmci_handle handle; + struct vmci_qp *qpair; + bool is_local; + u32 flags; + u32 detach_sub_id; + int err; + int skerr; + + vpending = vsock_sk(pending); + detach_sub_id = VMCI_INVALID_ID; + + switch (pkt->type) { + case VMCI_TRANSPORT_PACKET_TYPE_OFFER: + if (vmci_handle_is_invalid(pkt->u.handle)) { + vmci_transport_send_reset(pending, pkt); + skerr = EPROTO; + err = -EINVAL; + goto destroy; + } + break; + default: + /* Close and cleanup the connection. */ + vmci_transport_send_reset(pending, pkt); + skerr = EPROTO; + err = pkt->type == VMCI_TRANSPORT_PACKET_TYPE_RST ? 0 : -EINVAL; + goto destroy; + } + + /* In order to complete the connection we need to attach to the offered + * queue pair and send an attach notification. We also subscribe to the + * detach event so we know when our peer goes away, and we do that + * before attaching so we don't miss an event. If all this succeeds, + * we update our state and wakeup anything waiting in accept() for a + * connection. + */ + + /* We don't care about attach since we ensure the other side has + * attached by specifying the ATTACH_ONLY flag below. + */ + err = vmci_event_subscribe(VMCI_EVENT_QP_PEER_DETACH, + vmci_transport_peer_detach_cb, + pending, &detach_sub_id); + if (err < VMCI_SUCCESS) { + vmci_transport_send_reset(pending, pkt); + err = vmci_transport_error_to_vsock_error(err); + skerr = -err; + goto destroy; + } + + vmci_trans(vpending)->detach_sub_id = detach_sub_id; + + /* Now attach to the queue pair the client created. */ + handle = pkt->u.handle; + + /* vpending->local_addr always has a context id so we do not need to + * worry about VMADDR_CID_ANY in this case. + */ + is_local = + vpending->remote_addr.svm_cid == vpending->local_addr.svm_cid; + flags = VMCI_QPFLAG_ATTACH_ONLY; + flags |= is_local ? VMCI_QPFLAG_LOCAL : 0; + + err = vmci_transport_queue_pair_alloc( + &qpair, + &handle, + vmci_trans(vpending)->produce_size, + vmci_trans(vpending)->consume_size, + pkt->dg.src.context, + flags, + vmci_transport_is_trusted( + vpending, + vpending->remote_addr.svm_cid)); + if (err < 0) { + vmci_transport_send_reset(pending, pkt); + skerr = -err; + goto destroy; + } + + vmci_trans(vpending)->qp_handle = handle; + vmci_trans(vpending)->qpair = qpair; + + /* When we send the attach message, we must be ready to handle incoming + * control messages on the newly connected socket. So we move the + * pending socket to the connected state before sending the attach + * message. Otherwise, an incoming packet triggered by the attach being + * received by the peer may be processed concurrently with what happens + * below after sending the attach message, and that incoming packet + * will find the listening socket instead of the (currently) pending + * socket. Note that enqueueing the socket increments the reference + * count, so even if a reset comes before the connection is accepted, + * the socket will be valid until it is removed from the queue. + * + * If we fail sending the attach below, we remove the socket from the + * connected list and move the socket to SS_UNCONNECTED before + * releasing the lock, so a pending slow path processing of an incoming + * packet will not see the socket in the connected state in that case. + */ + pending->sk_state = SS_CONNECTED; + + vsock_insert_connected(vpending); + + /* Notify our peer of our attach. */ + err = vmci_transport_send_attach(pending, handle); + if (err < 0) { + vsock_remove_connected(vpending); + pr_err(""Could not send attach\n""); + vmci_transport_send_reset(pending, pkt); + err = vmci_transport_error_to_vsock_error(err); + skerr = -err; + goto destroy; + } + + /* We have a connection. Move the now connected socket from the + * listener's pending list to the accept queue so callers of accept() + * can find it. + */ + vsock_remove_pending(listener, pending); + vsock_enqueue_accept(listener, pending); + + /* Callers of accept() will be be waiting on the listening socket, not + * the pending socket. + */ + listener->sk_state_change(listener); + + return 0; + +destroy: + pending->sk_err = skerr; + pending->sk_state = SS_UNCONNECTED; + /* As long as we drop our reference, all necessary cleanup will handle + * when the cleanup function drops its reference and our destruct + * implementation is called. Note that since the listen handler will + * remove pending from the pending list upon our failure, the cleanup + * function won't drop the additional reference, which is why we do it + * here. + */ + sock_put(pending); + + return err; +} +","@@ -1736,6 +1736,8 @@ static int vmci_transport_dgram_dequeue(struct kiocb *kiocb, + if (flags & MSG_OOB || flags & MSG_ERRQUEUE) + return -EOPNOTSUPP; + ++ msg->msg_namelen = 0; ++ + /* Retrieve the head sk_buff from the socket's receive queue. */ + err = 0; + skb = skb_recv_datagram(&vsk->sk, flags, noblock, &err); +@@ -1768,7 +1770,6 @@ static int vmci_transport_dgram_dequeue(struct kiocb *kiocb, + if (err) + goto out; + +- msg->msg_namelen = 0; + if (msg->msg_name) { + struct sockaddr_vm *vm_addr; + ",1183,1514,2048 +18003,"SPL_METHOD(Array, unserialize) +{ + spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC); + + char *buf; + int buf_len; + const unsigned char *p, *s; + php_unserialize_data_t var_hash; + zval *pmembers, *pflags = NULL; + HashTable *aht; + long flags; + + if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""s"", &buf, &buf_len) == FAILURE) { + return; + } + + if (buf_len == 0) { + return; + } + + aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); + if (aht->nApplyCount > 0) { + zend_error(E_WARNING, ""Modification of ArrayObject during sorting is prohibited""); + return; + } + + /* storage */ + s = p = (const unsigned char*)buf; + PHP_VAR_UNSERIALIZE_INIT(var_hash); + + if (*p!= 'x' || *++p != ':') { + goto outexcept; + } + ++p; + + ALLOC_INIT_ZVAL(pflags); + if (!php_var_unserialize(&pflags, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pflags) != IS_LONG) { + goto outexcept; + } + + var_push_dtor(&var_hash, &pflags); + --p; /* for ';' */ + flags = Z_LVAL_P(pflags); + /* flags needs to be verified and we also need to verify whether the next + * thing we get is ';'. After that we require an 'm' or somethign else + * where 'm' stands for members and anything else should be an array. If + * neither 'a' or 'm' follows we have an error. */ + + if (*p != ';') { + goto outexcept; + } + ++p; + + if (*p!='m') { + if (*p!='a' && *p!='O' && *p!='C' && *p!='r') { + goto outexcept; + } + intern->ar_flags &= ~SPL_ARRAY_CLONE_MASK; + intern->ar_flags |= flags & SPL_ARRAY_CLONE_MASK; + zval_ptr_dtor(&intern->array); + ALLOC_INIT_ZVAL(intern->array); + if (!php_var_unserialize(&intern->array, &p, s + buf_len, &var_hash TSRMLS_CC)) { + goto outexcept; + } + var_push_dtor(&var_hash, &intern->array); + } + if (*p != ';') { + goto outexcept; + } + ++p; + + /* members */ + if (*p!= 'm' || *++p != ':') { + goto outexcept; + } + ++p; + + ALLOC_INIT_ZVAL(pmembers); + if (!php_var_unserialize(&pmembers, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pmembers) != IS_ARRAY) { + zval_ptr_dtor(&pmembers); + goto outexcept; + } + + var_push_dtor(&var_hash, &pmembers); + /* copy members */ + if (!intern->std.properties) { + rebuild_object_properties(&intern->std); + } + zend_hash_copy(intern->std.properties, Z_ARRVAL_P(pmembers), (copy_ctor_func_t) zval_add_ref, (void *) NULL, sizeof(zval *)); + zval_ptr_dtor(&pmembers); + + /* done reading $serialized */ + + PHP_VAR_UNSERIALIZE_DESTROY(var_hash); + if (pflags) { + zval_ptr_dtor(&pflags); + } + return; + +outexcept: + PHP_VAR_UNSERIALIZE_DESTROY(var_hash); + if (pflags) { + zval_ptr_dtor(&pflags); + } + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Error at offset %ld of %d bytes"", (long)((char*)p - buf), buf_len); + return; + +} /* }}} */ + +/* {{{ arginfo and function table */ +",1,"SPL_METHOD(Array, unserialize) +{ + spl_array_object *intern = (spl_array_object*)zend_object_store_get_object(getThis() TSRMLS_CC); + + char *buf; + int buf_len; + const unsigned char *p, *s; + php_unserialize_data_t var_hash; + zval *pmembers, *pflags = NULL; + HashTable *aht; + long flags; + + if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""s"", &buf, &buf_len) == FAILURE) { + return; + } + + if (buf_len == 0) { + return; + } + + aht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); + if (aht->nApplyCount > 0) { + zend_error(E_WARNING, ""Modification of ArrayObject during sorting is prohibited""); + return; + } + + /* storage */ + s = p = (const unsigned char*)buf; + PHP_VAR_UNSERIALIZE_INIT(var_hash); + + if (*p!= 'x' || *++p != ':') { + goto outexcept; + } + ++p; + + ALLOC_INIT_ZVAL(pflags); + if (!php_var_unserialize(&pflags, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pflags) != IS_LONG) { + goto outexcept; + } + + var_push_dtor(&var_hash, &pflags); + --p; /* for ';' */ + flags = Z_LVAL_P(pflags); + /* flags needs to be verified and we also need to verify whether the next + * thing we get is ';'. After that we require an 'm' or somethign else + * where 'm' stands for members and anything else should be an array. If + * neither 'a' or 'm' follows we have an error. */ + + if (*p != ';') { + goto outexcept; + } + ++p; + + if (*p!='m') { + if (*p!='a' && *p!='O' && *p!='C' && *p!='r') { + goto outexcept; + } + intern->ar_flags &= ~SPL_ARRAY_CLONE_MASK; + intern->ar_flags |= flags & SPL_ARRAY_CLONE_MASK; + zval_ptr_dtor(&intern->array); + ALLOC_INIT_ZVAL(intern->array); + if (!php_var_unserialize(&intern->array, &p, s + buf_len, &var_hash TSRMLS_CC) + || (Z_TYPE_P(intern->array) != IS_ARRAY && Z_TYPE_P(intern->array) != IS_OBJECT)) { + zval_ptr_dtor(&intern->array); + goto outexcept; + } + var_push_dtor(&var_hash, &intern->array); + } + if (*p != ';') { + goto outexcept; + } + ++p; + + /* members */ + if (*p!= 'm' || *++p != ':') { + goto outexcept; + } + ++p; + + ALLOC_INIT_ZVAL(pmembers); + if (!php_var_unserialize(&pmembers, &p, s + buf_len, &var_hash TSRMLS_CC) || Z_TYPE_P(pmembers) != IS_ARRAY) { + zval_ptr_dtor(&pmembers); + goto outexcept; + } + + var_push_dtor(&var_hash, &pmembers); + /* copy members */ + if (!intern->std.properties) { + rebuild_object_properties(&intern->std); + } + zend_hash_copy(intern->std.properties, Z_ARRVAL_P(pmembers), (copy_ctor_func_t) zval_add_ref, (void *) NULL, sizeof(zval *)); + zval_ptr_dtor(&pmembers); + + /* done reading $serialized */ + + PHP_VAR_UNSERIALIZE_DESTROY(var_hash); + if (pflags) { + zval_ptr_dtor(&pflags); + } + return; + +outexcept: + PHP_VAR_UNSERIALIZE_DESTROY(var_hash); + if (pflags) { + zval_ptr_dtor(&pflags); + } + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Error at offset %ld of %d bytes"", (long)((char*)p - buf), buf_len); + return; + +} /* }}} */ + +/* {{{ arginfo and function table */ +","@@ -308,7 +308,7 @@ static zval **spl_array_get_dimension_ptr_ptr(int check_inherited, zval *object, + long index; + HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); + +- if (!offset) { ++ if (!offset || !ht) { + return &EG(uninitialized_zval_ptr); + } + +@@ -626,7 +626,7 @@ static int spl_array_has_dimension_ex(int check_inherited, zval *object, zval *o + HashTable *ht = spl_array_get_hash_table(intern, 0 TSRMLS_CC); + + switch(Z_TYPE_P(offset)) { +- case IS_STRING: ++ case IS_STRING: + if (zend_symtable_find(ht, Z_STRVAL_P(offset), Z_STRLEN_P(offset)+1, (void **) &tmp) != FAILURE) { + if (check_empty == 2) { + return 1; +@@ -638,7 +638,7 @@ static int spl_array_has_dimension_ex(int check_inherited, zval *object, zval *o + + case IS_DOUBLE: + case IS_RESOURCE: +- case IS_BOOL: ++ case IS_BOOL: + case IS_LONG: + if (offset->type == IS_DOUBLE) { + index = (long)Z_DVAL_P(offset); +@@ -1810,7 +1810,9 @@ SPL_METHOD(Array, unserialize) + intern->ar_flags |= flags & SPL_ARRAY_CLONE_MASK; + zval_ptr_dtor(&intern->array); + ALLOC_INIT_ZVAL(intern->array); +- if (!php_var_unserialize(&intern->array, &p, s + buf_len, &var_hash TSRMLS_CC)) { ++ if (!php_var_unserialize(&intern->array, &p, s + buf_len, &var_hash TSRMLS_CC) ++ || (Z_TYPE_P(intern->array) != IS_ARRAY && Z_TYPE_P(intern->array) != IS_OBJECT)) { ++ zval_ptr_dtor(&intern->array); + goto outexcept; + } + var_push_dtor(&var_hash, &intern->array);",862,1193,2048 +17814,"int v9fs_device_realize_common(V9fsState *s, Error **errp) +{ + V9fsVirtioState *v = container_of(s, V9fsVirtioState, state); + int i, len; + struct stat stat; + FsDriverEntry *fse; + V9fsPath path; + int rc = 1; + + /* initialize pdu allocator */ + QLIST_INIT(&s->free_list); + QLIST_INIT(&s->active_list); + for (i = 0; i < (MAX_REQ - 1); i++) { + QLIST_INSERT_HEAD(&s->free_list, &v->pdus[i], next); + v->pdus[i].s = s; + v->pdus[i].idx = i; + } + + v9fs_path_init(&path); + + fse = get_fsdev_fsentry(s->fsconf.fsdev_id); + + if (!fse) { + /* We don't have a fsdev identified by fsdev_id */ + error_setg(errp, ""9pfs device couldn't find fsdev with the "" + ""id = %s"", + s->fsconf.fsdev_id ? s->fsconf.fsdev_id : ""NULL""); + goto out; + } + + if (!s->fsconf.tag) { + /* we haven't specified a mount_tag */ + error_setg(errp, ""fsdev with id %s needs mount_tag arguments"", + s->fsconf.fsdev_id); + goto out; + } + + s->ctx.export_flags = fse->export_flags; + s->ctx.fs_root = g_strdup(fse->path); + s->ctx.exops.get_st_gen = NULL; + len = strlen(s->fsconf.tag); + if (len > MAX_TAG_LEN - 1) { + error_setg(errp, ""mount tag '%s' (%d bytes) is longer than "" + ""maximum (%d bytes)"", s->fsconf.tag, len, MAX_TAG_LEN - 1); + goto out; + } + + s->tag = g_strdup(s->fsconf.tag); + s->ctx.uid = -1; + + s->ops = fse->ops; + + s->fid_list = NULL; + qemu_co_rwlock_init(&s->rename_lock); + + if (s->ops->init(&s->ctx) < 0) { + error_setg(errp, ""9pfs Failed to initialize fs-driver with id:%s"" + "" and export path:%s"", s->fsconf.fsdev_id, s->ctx.fs_root); + goto out; + } + + /* + * Check details of export path, We need to use fs driver + * call back to do that. Since we are in the init path, we don't + * use co-routines here. + */ + if (s->ops->name_to_path(&s->ctx, NULL, ""/"", &path) < 0) { + error_setg(errp, + ""error in converting name to path %s"", strerror(errno)); + goto out; + } + if (s->ops->lstat(&s->ctx, &path, &stat)) { + error_setg(errp, ""share path %s does not exist"", fse->path); + goto out; + } else if (!S_ISDIR(stat.st_mode)) { + error_setg(errp, ""share path %s is not a directory"", fse->path); + goto out; + } + v9fs_path_free(&path); + + rc = 0; + out: + if (rc) { + g_free(s->ctx.fs_root); + g_free(s->tag); + v9fs_path_free(&path); + } + return rc; +} +",1,"int v9fs_device_realize_common(V9fsState *s, Error **errp) +{ + V9fsVirtioState *v = container_of(s, V9fsVirtioState, state); + int i, len; + struct stat stat; + FsDriverEntry *fse; + V9fsPath path; + int rc = 1; + + /* initialize pdu allocator */ + QLIST_INIT(&s->free_list); + QLIST_INIT(&s->active_list); + for (i = 0; i < (MAX_REQ - 1); i++) { + QLIST_INSERT_HEAD(&s->free_list, &v->pdus[i], next); + v->pdus[i].s = s; + v->pdus[i].idx = i; + } + + v9fs_path_init(&path); + + fse = get_fsdev_fsentry(s->fsconf.fsdev_id); + + if (!fse) { + /* We don't have a fsdev identified by fsdev_id */ + error_setg(errp, ""9pfs device couldn't find fsdev with the "" + ""id = %s"", + s->fsconf.fsdev_id ? s->fsconf.fsdev_id : ""NULL""); + goto out; + } + + if (!s->fsconf.tag) { + /* we haven't specified a mount_tag */ + error_setg(errp, ""fsdev with id %s needs mount_tag arguments"", + s->fsconf.fsdev_id); + goto out; + } + + s->ctx.export_flags = fse->export_flags; + s->ctx.fs_root = g_strdup(fse->path); + s->ctx.exops.get_st_gen = NULL; + len = strlen(s->fsconf.tag); + if (len > MAX_TAG_LEN - 1) { + error_setg(errp, ""mount tag '%s' (%d bytes) is longer than "" + ""maximum (%d bytes)"", s->fsconf.tag, len, MAX_TAG_LEN - 1); + goto out; + } + + s->tag = g_strdup(s->fsconf.tag); + s->ctx.uid = -1; + + s->ops = fse->ops; + + s->fid_list = NULL; + qemu_co_rwlock_init(&s->rename_lock); + + if (s->ops->init(&s->ctx) < 0) { + error_setg(errp, ""9pfs Failed to initialize fs-driver with id:%s"" + "" and export path:%s"", s->fsconf.fsdev_id, s->ctx.fs_root); + goto out; + } + + /* + * Check details of export path, We need to use fs driver + * call back to do that. Since we are in the init path, we don't + * use co-routines here. + */ + if (s->ops->name_to_path(&s->ctx, NULL, ""/"", &path) < 0) { + error_setg(errp, + ""error in converting name to path %s"", strerror(errno)); + goto out; + } + if (s->ops->lstat(&s->ctx, &path, &stat)) { + error_setg(errp, ""share path %s does not exist"", fse->path); + goto out; + } else if (!S_ISDIR(stat.st_mode)) { + error_setg(errp, ""share path %s is not a directory"", fse->path); + goto out; + } + v9fs_path_free(&path); + + rc = 0; + out: + if (rc) { + g_free(s->tag); + g_free(s->ctx.fs_root); + v9fs_path_free(&path); + } + return rc; +} +","@@ -3521,8 +3521,8 @@ int v9fs_device_realize_common(V9fsState *s, Error **errp) + rc = 0; + out: + if (rc) { +- g_free(s->ctx.fs_root); + g_free(s->tag); ++ g_free(s->ctx.fs_root); + v9fs_path_free(&path); + } + return rc; +@@ -3530,8 +3530,8 @@ out: + + void v9fs_device_unrealize_common(V9fsState *s, Error **errp) + { +- g_free(s->ctx.fs_root); + g_free(s->tag); ++ g_free(s->ctx.fs_root); + } + + typedef struct VirtfsCoResetData {",796,1127,2048 +18550,"void CompositingLayerPropertyUpdater::Update(const LayoutObject& object) { + if (!RuntimeEnabledFeatures::SlimmingPaintV175Enabled() || + RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) + return; + + if (object.GetDocument().Printing() && + !RuntimeEnabledFeatures::PrintBrowserEnabled()) + return; + + if (!object.HasLayer()) + return; + const auto* paint_layer = ToLayoutBoxModelObject(object).Layer(); + const auto* mapping = paint_layer->GetCompositedLayerMapping(); + if (!mapping) + return; + + const FragmentData& fragment_data = object.FirstFragment(); + DCHECK(fragment_data.HasLocalBorderBoxProperties()); + DCHECK(!fragment_data.NextFragment()); + + LayoutPoint layout_snapped_paint_offset = + fragment_data.PaintOffset() - mapping->SubpixelAccumulation(); + IntPoint snapped_paint_offset = RoundedIntPoint(layout_snapped_paint_offset); + +#if 0 + bool subpixel_accumulation_may_be_bogus = paint_layer->SubtreeIsInvisible(); + DCHECK(layout_snapped_paint_offset == snapped_paint_offset || + subpixel_accumulation_may_be_bogus); +#endif + + base::Optional container_layer_state; + auto SetContainerLayerState = + [&fragment_data, &snapped_paint_offset, + &container_layer_state](GraphicsLayer* graphics_layer) { + if (graphics_layer) { + if (!container_layer_state) { + container_layer_state = fragment_data.LocalBorderBoxProperties(); + if (const auto* properties = fragment_data.PaintProperties()) { + if (const auto* css_clip = properties->CssClip()) + container_layer_state->SetClip(css_clip->Parent()); + } + } + graphics_layer->SetLayerState( + *container_layer_state, + snapped_paint_offset + graphics_layer->OffsetFromLayoutObject()); + } + }; + SetContainerLayerState(mapping->MainGraphicsLayer()); + SetContainerLayerState(mapping->DecorationOutlineLayer()); + SetContainerLayerState(mapping->ChildClippingMaskLayer()); + + base::Optional scrollbar_layer_state; + + auto SetContainerLayerStateForScrollbars = + [&fragment_data, &snapped_paint_offset, &container_layer_state, + &scrollbar_layer_state](GraphicsLayer* graphics_layer) { + if (graphics_layer) { + if (!scrollbar_layer_state) { + if (container_layer_state) { + scrollbar_layer_state = container_layer_state; + } else { + scrollbar_layer_state = fragment_data.LocalBorderBoxProperties(); + } + + if (const auto* properties = fragment_data.PaintProperties()) { + if (const auto* clip = properties->OverflowControlsClip()) { + scrollbar_layer_state->SetClip(clip); + } else if (const auto* css_clip = properties->CssClip()) { + scrollbar_layer_state->SetClip(css_clip->Parent()); + } + } + } + graphics_layer->SetLayerState( + *scrollbar_layer_state, + snapped_paint_offset + graphics_layer->OffsetFromLayoutObject()); + } + }; + + SetContainerLayerStateForScrollbars(mapping->LayerForHorizontalScrollbar()); + SetContainerLayerStateForScrollbars(mapping->LayerForVerticalScrollbar()); + SetContainerLayerStateForScrollbars(mapping->LayerForScrollCorner()); + + if (mapping->ScrollingContentsLayer()) { + auto paint_offset = snapped_paint_offset; + + if (object.IsBox() && object.HasFlippedBlocksWritingMode()) + paint_offset.Move(ToLayoutBox(object).VerticalScrollbarWidth(), 0); + + auto SetContentsLayerState = + [&fragment_data, &paint_offset](GraphicsLayer* graphics_layer) { + if (graphics_layer) { + graphics_layer->SetLayerState( + fragment_data.ContentsProperties(), + paint_offset + graphics_layer->OffsetFromLayoutObject()); + } + }; + SetContentsLayerState(mapping->ScrollingContentsLayer()); + SetContentsLayerState(mapping->ForegroundLayer()); + } else { + SetContainerLayerState(mapping->ForegroundLayer()); + } + + if (auto* squashing_layer = mapping->SquashingLayer()) { + auto state = fragment_data.PreEffectProperties(); + const auto* clipping_container = paint_layer->ClippingContainer(); + state.SetClip( + clipping_container + ? clipping_container->FirstFragment().ContentsProperties().Clip() + : ClipPaintPropertyNode::Root()); + squashing_layer->SetLayerState( + state, + snapped_paint_offset + mapping->SquashingLayerOffsetFromLayoutObject()); + } + + if (auto* mask_layer = mapping->MaskLayer()) { + auto state = fragment_data.LocalBorderBoxProperties(); + const auto* properties = fragment_data.PaintProperties(); + DCHECK(properties && properties->Mask()); + state.SetEffect(properties->Mask()); + state.SetClip(properties->MaskClip()); + + mask_layer->SetLayerState( + state, snapped_paint_offset + mask_layer->OffsetFromLayoutObject()); + } + + if (auto* ancestor_clipping_mask_layer = + mapping->AncestorClippingMaskLayer()) { + PropertyTreeState state( + fragment_data.PreTransform(), + mapping->ClipInheritanceAncestor() + ->GetLayoutObject() + .FirstFragment() + .PostOverflowClip(), + fragment_data.PreFilter()); + ancestor_clipping_mask_layer->SetLayerState( + state, snapped_paint_offset + + ancestor_clipping_mask_layer->OffsetFromLayoutObject()); + } + + if (auto* child_clipping_mask_layer = mapping->ChildClippingMaskLayer()) { + PropertyTreeState state = fragment_data.LocalBorderBoxProperties(); + state.SetEffect(fragment_data.PreFilter()); + child_clipping_mask_layer->SetLayerState( + state, snapped_paint_offset + + child_clipping_mask_layer->OffsetFromLayoutObject()); + } +} +",1,"void CompositingLayerPropertyUpdater::Update(const LayoutObject& object) { + if (!RuntimeEnabledFeatures::SlimmingPaintV175Enabled() || + RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) + return; + + if (object.GetDocument().Printing() && + !RuntimeEnabledFeatures::PrintBrowserEnabled()) + return; + + if (!object.HasLayer()) + return; + const auto* paint_layer = ToLayoutBoxModelObject(object).Layer(); + const auto* mapping = paint_layer->GetCompositedLayerMapping(); + if (!mapping) + return; + + const FragmentData& fragment_data = object.FirstFragment(); + DCHECK(fragment_data.HasLocalBorderBoxProperties()); + DCHECK(!fragment_data.NextFragment()); + + LayoutPoint layout_snapped_paint_offset = + fragment_data.PaintOffset() - mapping->SubpixelAccumulation(); + IntPoint snapped_paint_offset = RoundedIntPoint(layout_snapped_paint_offset); + +#if 0 + bool subpixel_accumulation_may_be_bogus = paint_layer->SubtreeIsInvisible(); + DCHECK(layout_snapped_paint_offset == snapped_paint_offset || + subpixel_accumulation_may_be_bogus); +#endif + + base::Optional container_layer_state; + auto SetContainerLayerState = + [&fragment_data, &snapped_paint_offset, + &container_layer_state](GraphicsLayer* graphics_layer) { + if (graphics_layer) { + if (!container_layer_state) { + container_layer_state = fragment_data.LocalBorderBoxProperties(); + if (const auto* properties = fragment_data.PaintProperties()) { + if (const auto* css_clip = properties->CssClip()) + container_layer_state->SetClip(css_clip->Parent()); + } + } + graphics_layer->SetLayerState( + *container_layer_state, + snapped_paint_offset + graphics_layer->OffsetFromLayoutObject()); + } + }; + SetContainerLayerState(mapping->MainGraphicsLayer()); + SetContainerLayerState(mapping->DecorationOutlineLayer()); + SetContainerLayerState(mapping->ChildClippingMaskLayer()); + + base::Optional scrollbar_layer_state; + + auto SetContainerLayerStateForScrollbars = + [&fragment_data, &snapped_paint_offset, &container_layer_state, + &scrollbar_layer_state](GraphicsLayer* graphics_layer) { + if (graphics_layer) { + if (!scrollbar_layer_state) { + if (container_layer_state) { + scrollbar_layer_state = container_layer_state; + } else { + scrollbar_layer_state = fragment_data.LocalBorderBoxProperties(); + } + + if (const auto* properties = fragment_data.PaintProperties()) { + if (const auto* clip = properties->OverflowControlsClip()) { + scrollbar_layer_state->SetClip(clip); + } else if (const auto* css_clip = properties->CssClip()) { + scrollbar_layer_state->SetClip(css_clip->Parent()); + } + } + } + graphics_layer->SetLayerState( + *scrollbar_layer_state, + snapped_paint_offset + graphics_layer->OffsetFromLayoutObject()); + } + }; + + SetContainerLayerStateForScrollbars(mapping->LayerForHorizontalScrollbar()); + SetContainerLayerStateForScrollbars(mapping->LayerForVerticalScrollbar()); + SetContainerLayerStateForScrollbars(mapping->LayerForScrollCorner()); + + if (mapping->ScrollingContentsLayer()) { + auto paint_offset = snapped_paint_offset; + + if (object.IsBox() && object.HasFlippedBlocksWritingMode()) + paint_offset.Move(ToLayoutBox(object).VerticalScrollbarWidth(), 0); + + auto SetContentsLayerState = + [&fragment_data, &paint_offset](GraphicsLayer* graphics_layer) { + if (graphics_layer) { + graphics_layer->SetLayerState( + fragment_data.ContentsProperties(), + paint_offset + graphics_layer->OffsetFromLayoutObject()); + } + }; + SetContentsLayerState(mapping->ScrollingContentsLayer()); + SetContentsLayerState(mapping->ForegroundLayer()); + } else { + SetContainerLayerState(mapping->ForegroundLayer()); + } + + if (auto* squashing_layer = mapping->SquashingLayer()) { + auto state = fragment_data.PreEffectProperties(); + const auto* clipping_container = paint_layer->ClippingContainer(); + state.SetClip( + clipping_container + ? clipping_container->FirstFragment().ContentsProperties().Clip() + : &ClipPaintPropertyNode::Root()); + squashing_layer->SetLayerState( + state, + snapped_paint_offset + mapping->SquashingLayerOffsetFromLayoutObject()); + } + + if (auto* mask_layer = mapping->MaskLayer()) { + auto state = fragment_data.LocalBorderBoxProperties(); + const auto* properties = fragment_data.PaintProperties(); + DCHECK(properties && properties->Mask()); + state.SetEffect(properties->Mask()); + state.SetClip(properties->MaskClip()); + + mask_layer->SetLayerState( + state, snapped_paint_offset + mask_layer->OffsetFromLayoutObject()); + } + + if (auto* ancestor_clipping_mask_layer = + mapping->AncestorClippingMaskLayer()) { + PropertyTreeState state( + fragment_data.PreTransform(), + mapping->ClipInheritanceAncestor() + ->GetLayoutObject() + .FirstFragment() + .PostOverflowClip(), + fragment_data.PreFilter()); + ancestor_clipping_mask_layer->SetLayerState( + state, snapped_paint_offset + + ancestor_clipping_mask_layer->OffsetFromLayoutObject()); + } + + if (auto* child_clipping_mask_layer = mapping->ChildClippingMaskLayer()) { + PropertyTreeState state = fragment_data.LocalBorderBoxProperties(); + state.SetEffect(fragment_data.PreFilter()); + child_clipping_mask_layer->SetLayerState( + state, snapped_paint_offset + + child_clipping_mask_layer->OffsetFromLayoutObject()); + } +} +","@@ -139,7 +139,7 @@ void CompositingLayerPropertyUpdater::Update(const LayoutObject& object) { + state.SetClip( + clipping_container + ? clipping_container->FirstFragment().ContentsProperties().Clip() +- : ClipPaintPropertyNode::Root()); ++ : &ClipPaintPropertyNode::Root()); + squashing_layer->SetLayerState( + state, + snapped_paint_offset + mapping->SquashingLayerOffsetFromLayoutObject());",1193,1524,2048 +4454,"crm_xml_dump(xmlNode * data, int options, char **buffer, int *offset, int *max, int depth) +{ +#if 0 + if (is_not_set(options, xml_log_option_filtered)) { + /* Turning this code on also changes the PE tests for some reason + * (not just newlines). Figure out why before considering to + * enable this permanently. + * + * It exists to help debug slowness in xmlNodeDump() and + * potentially if we ever want to go back to it. + * + * In theory its a good idea (reuse) but our custom version does + * better for the filtered case and avoids the final strdup() for + * everything + */ + + time_t now, next; + xmlDoc *doc = NULL; + xmlBuffer *xml_buffer = NULL; + + *buffer = NULL; + doc = getDocPtr(data); + /* doc will only be NULL if data is */ + CRM_CHECK(doc != NULL, return); + + now = time(NULL); + xml_buffer = xmlBufferCreate(); + CRM_ASSERT(xml_buffer != NULL); + + /* The default allocator XML_BUFFER_ALLOC_EXACT does far too many + * realloc()s and it can take upwards of 18 seconds (yes, seconds) + * to dump a 28kb tree which XML_BUFFER_ALLOC_DOUBLEIT can do in + * less than 1 second. + * + * We could also use xmlBufferCreateSize() to start with a + * sane-ish initial size and avoid the first few doubles. + */ + xmlBufferSetAllocationScheme(xml_buffer, XML_BUFFER_ALLOC_DOUBLEIT); + + *max = xmlNodeDump(xml_buffer, doc, data, 0, (options & xml_log_option_formatted)); + if (*max > 0) { + *buffer = strdup((char *)xml_buffer->content); + } + + next = time(NULL); + if ((now + 1) < next) { + crm_log_xml_trace(data, ""Long time""); + crm_err(""xmlNodeDump() -> %dbytes took %ds"", *max, next - now); + } + + xmlBufferFree(xml_buffer); + return; + } +#endif + + switch(data->type) { + case XML_ELEMENT_NODE: + /* Handle below */ + dump_xml_element(data, options, buffer, offset, max, depth); + break; + case XML_TEXT_NODE: + /* Ignore */ + return; + case XML_COMMENT_NODE: + dump_xml_comment(data, options, buffer, offset, max, depth); + break; + default: + crm_warn(""Unhandled type: %d"", data->type); + return; + + /* + XML_ATTRIBUTE_NODE = 2 + XML_CDATA_SECTION_NODE = 4 + XML_ENTITY_REF_NODE = 5 + XML_ENTITY_NODE = 6 + XML_PI_NODE = 7 + XML_DOCUMENT_NODE = 9 + XML_DOCUMENT_TYPE_NODE = 10 + XML_DOCUMENT_FRAG_NODE = 11 + XML_NOTATION_NODE = 12 + XML_HTML_DOCUMENT_NODE = 13 + XML_DTD_NODE = 14 + XML_ELEMENT_DECL = 15 + XML_ATTRIBUTE_DECL = 16 + XML_ENTITY_DECL = 17 + XML_NAMESPACE_DECL = 18 + XML_XINCLUDE_START = 19 + XML_XINCLUDE_END = 20 + XML_DOCB_DOCUMENT_NODE = 21 + */ + } + +} +",0,"crm_xml_dump(xmlNode * data, int options, char **buffer, int *offset, int *max, int depth) +{ +#if 0 + if (is_not_set(options, xml_log_option_filtered)) { + /* Turning this code on also changes the PE tests for some reason + * (not just newlines). Figure out why before considering to + * enable this permanently. + * + * It exists to help debug slowness in xmlNodeDump() and + * potentially if we ever want to go back to it. + * + * In theory its a good idea (reuse) but our custom version does + * better for the filtered case and avoids the final strdup() for + * everything + */ + + time_t now, next; + xmlDoc *doc = NULL; + xmlBuffer *xml_buffer = NULL; + + *buffer = NULL; + doc = getDocPtr(data); + /* doc will only be NULL if data is */ + CRM_CHECK(doc != NULL, return); + + now = time(NULL); + xml_buffer = xmlBufferCreate(); + CRM_ASSERT(xml_buffer != NULL); + + /* The default allocator XML_BUFFER_ALLOC_EXACT does far too many + * realloc()s and it can take upwards of 18 seconds (yes, seconds) + * to dump a 28kb tree which XML_BUFFER_ALLOC_DOUBLEIT can do in + * less than 1 second. + * + * We could also use xmlBufferCreateSize() to start with a + * sane-ish initial size and avoid the first few doubles. + */ + xmlBufferSetAllocationScheme(xml_buffer, XML_BUFFER_ALLOC_DOUBLEIT); + + *max = xmlNodeDump(xml_buffer, doc, data, 0, (options & xml_log_option_formatted)); + if (*max > 0) { + *buffer = strdup((char *)xml_buffer->content); + } + + next = time(NULL); + if ((now + 1) < next) { + crm_log_xml_trace(data, ""Long time""); + crm_err(""xmlNodeDump() -> %dbytes took %ds"", *max, next - now); + } + + xmlBufferFree(xml_buffer); + return; + } +#endif + + switch(data->type) { + case XML_ELEMENT_NODE: + /* Handle below */ + dump_xml_element(data, options, buffer, offset, max, depth); + break; + case XML_TEXT_NODE: + /* Ignore */ + return; + case XML_COMMENT_NODE: + dump_xml_comment(data, options, buffer, offset, max, depth); + break; + default: + crm_warn(""Unhandled type: %d"", data->type); + return; + + /* + XML_ATTRIBUTE_NODE = 2 + XML_CDATA_SECTION_NODE = 4 + XML_ENTITY_REF_NODE = 5 + XML_ENTITY_NODE = 6 + XML_PI_NODE = 7 + XML_DOCUMENT_NODE = 9 + XML_DOCUMENT_TYPE_NODE = 10 + XML_DOCUMENT_FRAG_NODE = 11 + XML_NOTATION_NODE = 12 + XML_HTML_DOCUMENT_NODE = 13 + XML_DTD_NODE = 14 + XML_ELEMENT_DECL = 15 + XML_ATTRIBUTE_DECL = 16 + XML_ENTITY_DECL = 17 + XML_NAMESPACE_DECL = 18 + XML_XINCLUDE_START = 19 + XML_XINCLUDE_END = 20 + XML_DOCB_DOCUMENT_NODE = 21 + */ + } + +} +","@@ -1020,13 +1020,16 @@ __xml_acl_post_process(xmlNode * xml) + + if(is_set(p->flags, xpf_created)) { + xmlAttr *xIter = NULL; ++ char *path = xml_get_path(xml); + +- /* Always allow new scaffolding, ie. node with no attributes or only an 'id' */ ++ /* Always allow new scaffolding, ie. node with no attributes or only an 'id' ++ * Except in the ACLs section ++ */ + + for (xIter = crm_first_attr(xml); xIter != NULL; xIter = xIter->next) { + const char *prop_name = (const char *)xIter->name; + +- if (strcmp(prop_name, XML_ATTR_ID) == 0) { ++ if (strcmp(prop_name, XML_ATTR_ID) == 0 && strstr(path, ""/""XML_CIB_TAG_ACLS""/"") == NULL) { + /* Delay the acl check */ + continue; + +@@ -1035,7 +1038,6 @@ __xml_acl_post_process(xmlNode * xml) + break; + + } else { +- char *path = xml_get_path(xml); + crm_trace(""Cannot add new node %s at %s"", crm_element_name(xml), path); + + if(xml != xmlDocGetRootElement(xml->doc)) { +@@ -1046,6 +1048,7 @@ __xml_acl_post_process(xmlNode * xml) + return; + } + } ++ free(path); + } + + while (cIter != NULL) {",736,1067,2048 +6649,"static void gs_usb_receive_bulk_callback(struct urb *urb) +{ + struct gs_usb *usbcan = urb->context; + struct gs_can *dev; + struct net_device *netdev; + int rc; + struct net_device_stats *stats; + struct gs_host_frame *hf = urb->transfer_buffer; + struct gs_tx_context *txc; + struct can_frame *cf; + struct sk_buff *skb; + + BUG_ON(!usbcan); + + switch (urb->status) { + case 0: /* success */ + break; + case -ENOENT: + case -ESHUTDOWN: + return; + default: + /* do not resubmit aborted urbs. eg: when device goes down */ + return; + } + + /* device reports out of range channel id */ + if (hf->channel >= GS_MAX_INTF) + goto resubmit_urb; + + dev = usbcan->canch[hf->channel]; + + netdev = dev->netdev; + stats = &netdev->stats; + + if (!netif_device_present(netdev)) + return; + + if (hf->echo_id == -1) { /* normal rx */ + skb = alloc_can_skb(dev->netdev, &cf); + if (!skb) + return; + + cf->can_id = hf->can_id; + + cf->can_dlc = get_can_dlc(hf->can_dlc); + memcpy(cf->data, hf->data, 8); + + /* ERROR frames tell us information about the controller */ + if (hf->can_id & CAN_ERR_FLAG) + gs_update_state(dev, cf); + + netdev->stats.rx_packets++; + netdev->stats.rx_bytes += hf->can_dlc; + + netif_rx(skb); + } else { /* echo_id == hf->echo_id */ + if (hf->echo_id >= GS_MAX_TX_URBS) { + netdev_err(netdev, + ""Unexpected out of range echo id %d\n"", + hf->echo_id); + goto resubmit_urb; + } + + netdev->stats.tx_packets++; + netdev->stats.tx_bytes += hf->can_dlc; + + txc = gs_get_tx_context(dev, hf->echo_id); + + /* bad devices send bad echo_ids. */ + if (!txc) { + netdev_err(netdev, + ""Unexpected unused echo id %d\n"", + hf->echo_id); + goto resubmit_urb; + } + + can_get_echo_skb(netdev, hf->echo_id); + + gs_free_tx_context(txc); + + netif_wake_queue(netdev); + } + + if (hf->flags & GS_CAN_FLAG_OVERFLOW) { + skb = alloc_can_err_skb(netdev, &cf); + if (!skb) + goto resubmit_urb; + + cf->can_id |= CAN_ERR_CRTL; + cf->can_dlc = CAN_ERR_DLC; + cf->data[1] = CAN_ERR_CRTL_RX_OVERFLOW; + stats->rx_over_errors++; + stats->rx_errors++; + netif_rx(skb); + } + + resubmit_urb: + usb_fill_bulk_urb(urb, + usbcan->udev, + usb_rcvbulkpipe(usbcan->udev, GSUSB_ENDPOINT_IN), + hf, + sizeof(struct gs_host_frame), + gs_usb_receive_bulk_callback, + usbcan + ); + + rc = usb_submit_urb(urb, GFP_ATOMIC); + + /* USB failure take down all interfaces */ + if (rc == -ENODEV) { + for (rc = 0; rc < GS_MAX_INTF; rc++) { + if (usbcan->canch[rc]) + netif_device_detach(usbcan->canch[rc]->netdev); + } + } +} +",0,"static void gs_usb_receive_bulk_callback(struct urb *urb) +{ + struct gs_usb *usbcan = urb->context; + struct gs_can *dev; + struct net_device *netdev; + int rc; + struct net_device_stats *stats; + struct gs_host_frame *hf = urb->transfer_buffer; + struct gs_tx_context *txc; + struct can_frame *cf; + struct sk_buff *skb; + + BUG_ON(!usbcan); + + switch (urb->status) { + case 0: /* success */ + break; + case -ENOENT: + case -ESHUTDOWN: + return; + default: + /* do not resubmit aborted urbs. eg: when device goes down */ + return; + } + + /* device reports out of range channel id */ + if (hf->channel >= GS_MAX_INTF) + goto resubmit_urb; + + dev = usbcan->canch[hf->channel]; + + netdev = dev->netdev; + stats = &netdev->stats; + + if (!netif_device_present(netdev)) + return; + + if (hf->echo_id == -1) { /* normal rx */ + skb = alloc_can_skb(dev->netdev, &cf); + if (!skb) + return; + + cf->can_id = hf->can_id; + + cf->can_dlc = get_can_dlc(hf->can_dlc); + memcpy(cf->data, hf->data, 8); + + /* ERROR frames tell us information about the controller */ + if (hf->can_id & CAN_ERR_FLAG) + gs_update_state(dev, cf); + + netdev->stats.rx_packets++; + netdev->stats.rx_bytes += hf->can_dlc; + + netif_rx(skb); + } else { /* echo_id == hf->echo_id */ + if (hf->echo_id >= GS_MAX_TX_URBS) { + netdev_err(netdev, + ""Unexpected out of range echo id %d\n"", + hf->echo_id); + goto resubmit_urb; + } + + netdev->stats.tx_packets++; + netdev->stats.tx_bytes += hf->can_dlc; + + txc = gs_get_tx_context(dev, hf->echo_id); + + /* bad devices send bad echo_ids. */ + if (!txc) { + netdev_err(netdev, + ""Unexpected unused echo id %d\n"", + hf->echo_id); + goto resubmit_urb; + } + + can_get_echo_skb(netdev, hf->echo_id); + + gs_free_tx_context(txc); + + netif_wake_queue(netdev); + } + + if (hf->flags & GS_CAN_FLAG_OVERFLOW) { + skb = alloc_can_err_skb(netdev, &cf); + if (!skb) + goto resubmit_urb; + + cf->can_id |= CAN_ERR_CRTL; + cf->can_dlc = CAN_ERR_DLC; + cf->data[1] = CAN_ERR_CRTL_RX_OVERFLOW; + stats->rx_over_errors++; + stats->rx_errors++; + netif_rx(skb); + } + + resubmit_urb: + usb_fill_bulk_urb(urb, + usbcan->udev, + usb_rcvbulkpipe(usbcan->udev, GSUSB_ENDPOINT_IN), + hf, + sizeof(struct gs_host_frame), + gs_usb_receive_bulk_callback, + usbcan + ); + + rc = usb_submit_urb(urb, GFP_ATOMIC); + + /* USB failure take down all interfaces */ + if (rc == -ENODEV) { + for (rc = 0; rc < GS_MAX_INTF; rc++) { + if (usbcan->canch[rc]) + netif_device_detach(usbcan->canch[rc]->netdev); + } + } +} +","@@ -908,10 +908,14 @@ static int gs_usb_probe(struct usb_interface *intf, + struct gs_usb *dev; + int rc = -ENOMEM; + unsigned int icount, i; +- struct gs_host_config hconf = { +- .byte_order = 0x0000beef, +- }; +- struct gs_device_config dconf; ++ struct gs_host_config *hconf; ++ struct gs_device_config *dconf; ++ ++ hconf = kmalloc(sizeof(*hconf), GFP_KERNEL); ++ if (!hconf) ++ return -ENOMEM; ++ ++ hconf->byte_order = 0x0000beef; + + /* send host config */ + rc = usb_control_msg(interface_to_usbdev(intf), +@@ -920,45 +924,56 @@ static int gs_usb_probe(struct usb_interface *intf, + USB_DIR_OUT|USB_TYPE_VENDOR|USB_RECIP_INTERFACE, + 1, + intf->altsetting[0].desc.bInterfaceNumber, +- &hconf, +- sizeof(hconf), ++ hconf, ++ sizeof(*hconf), + 1000); + ++ kfree(hconf); ++ + if (rc < 0) { + dev_err(&intf->dev, ""Couldn't send data format (err=%d)\n"", + rc); + return rc; + } + ++ dconf = kmalloc(sizeof(*dconf), GFP_KERNEL); ++ if (!dconf) ++ return -ENOMEM; ++ + /* read device config */ + rc = usb_control_msg(interface_to_usbdev(intf), + usb_rcvctrlpipe(interface_to_usbdev(intf), 0), + GS_USB_BREQ_DEVICE_CONFIG, + USB_DIR_IN|USB_TYPE_VENDOR|USB_RECIP_INTERFACE, + 1, + intf->altsetting[0].desc.bInterfaceNumber, +- &dconf, +- sizeof(dconf), ++ dconf, ++ sizeof(*dconf), + 1000); + if (rc < 0) { + dev_err(&intf->dev, ""Couldn't get device config: (err=%d)\n"", + rc); ++ kfree(dconf); + return rc; + } + +- icount = dconf.icount + 1; ++ icount = dconf->icount + 1; + dev_info(&intf->dev, ""Configuring for %d interfaces\n"", icount); + + if (icount > GS_MAX_INTF) { + dev_err(&intf->dev, + ""Driver cannot handle more that %d CAN interfaces\n"", + GS_MAX_INTF); ++ kfree(dconf); + return -EINVAL; + } + + dev = kzalloc(sizeof(*dev), GFP_KERNEL); +- if (!dev) ++ if (!dev) { ++ kfree(dconf); + return -ENOMEM; ++ } ++ + init_usb_anchor(&dev->rx_submitted); + + atomic_set(&dev->active_channels, 0); +@@ -967,7 +982,7 @@ static int gs_usb_probe(struct usb_interface *intf, + dev->udev = interface_to_usbdev(intf); + + for (i = 0; i < icount; i++) { +- dev->canch[i] = gs_make_candev(i, intf, &dconf); ++ dev->canch[i] = gs_make_candev(i, intf, dconf); + if (IS_ERR_OR_NULL(dev->canch[i])) { + /* save error code to return later */ + rc = PTR_ERR(dev->canch[i]); +@@ -978,12 +993,15 @@ static int gs_usb_probe(struct usb_interface *intf, + gs_destroy_candev(dev->canch[i]); + + usb_kill_anchored_urbs(&dev->rx_submitted); ++ kfree(dconf); + kfree(dev); + return rc; + } + dev->canch[i]->parent = dev; + } + ++ kfree(dconf); ++ + return 0; + } + ",781,1112,2048 +7379,"bool handle_auth_response(PgSocket *client, PktHdr *pkt) { + uint16_t columns; + uint32_t length; + const char *username, *password; + PgUser user; + PgSocket *server = client->link; + + switch(pkt->type) { + case 'T': /* RowDescription */ + if (!mbuf_get_uint16be(&pkt->data, &columns)) { + disconnect_server(server, false, ""bad packet""); + return false; + } + if (columns != 2u) { + disconnect_server(server, false, ""expected 1 column from login query, not %hu"", columns); + return false; + } + break; + case 'D': /* DataRow */ + memset(&user, 0, sizeof(user)); + if (!mbuf_get_uint16be(&pkt->data, &columns)) { + disconnect_server(server, false, ""bad packet""); + return false; + } + if (columns != 2u) { + disconnect_server(server, false, ""expected 1 column from login query, not %hu"", columns); + return false; + } + if (!mbuf_get_uint32be(&pkt->data, &length)) { + disconnect_server(server, false, ""bad packet""); + return false; + } + if (!mbuf_get_chars(&pkt->data, length, &username)) { + disconnect_server(server, false, ""bad packet""); + return false; + } + if (sizeof(user.name) - 1 < length) + length = sizeof(user.name) - 1; + memcpy(user.name, username, length); + if (!mbuf_get_uint32be(&pkt->data, &length)) { + disconnect_server(server, false, ""bad packet""); + return false; + } + if (length == (uint32_t)-1) { + /* + * NULL - set an md5 password with an impossible value, + * so that nothing will ever match + */ + password = ""md5""; + length = 3; + } else { + if (!mbuf_get_chars(&pkt->data, length, &password)) { + disconnect_server(server, false, ""bad packet""); + return false; + } + } + if (sizeof(user.passwd) - 1 < length) + length = sizeof(user.passwd) - 1; + memcpy(user.passwd, password, length); + + client->auth_user = add_db_user(client->db, user.name, user.passwd); + if (!client->auth_user) { + disconnect_server(server, false, ""unable to allocate new user for auth""); + return false; + } + break; + case 'N': /* NoticeResponse */ + break; + case 'C': /* CommandComplete */ + break; + case '1': /* ParseComplete */ + break; + case '2': /* BindComplete */ + break; + case 'Z': /* ReadyForQuery */ + sbuf_prepare_skip(&client->link->sbuf, pkt->len); + if (!client->auth_user) { + if (cf_log_connections) + slog_info(client, ""login failed: db=%s"", client->db->name); + disconnect_client(client, true, ""No such user""); + } else { + slog_noise(client, ""auth query complete""); + client->link->resetting = true; + sbuf_continue(&client->sbuf); + } + /* + * either sbuf_continue or disconnect_client could disconnect the server + * way down in their bowels of other callbacks. so check that, and + * return appropriately (similar to reuse_on_release) + */ + if (server->state == SV_FREE || server->state == SV_JUSTFREE) + return false; + return true; + default: + disconnect_server(server, false, ""unexpected response from login query""); + return false; + } + sbuf_prepare_skip(&server->sbuf, pkt->len); + return true; +} +",0,"bool handle_auth_response(PgSocket *client, PktHdr *pkt) { + uint16_t columns; + uint32_t length; + const char *username, *password; + PgUser user; + PgSocket *server = client->link; + + switch(pkt->type) { + case 'T': /* RowDescription */ + if (!mbuf_get_uint16be(&pkt->data, &columns)) { + disconnect_server(server, false, ""bad packet""); + return false; + } + if (columns != 2u) { + disconnect_server(server, false, ""expected 1 column from login query, not %hu"", columns); + return false; + } + break; + case 'D': /* DataRow */ + memset(&user, 0, sizeof(user)); + if (!mbuf_get_uint16be(&pkt->data, &columns)) { + disconnect_server(server, false, ""bad packet""); + return false; + } + if (columns != 2u) { + disconnect_server(server, false, ""expected 1 column from login query, not %hu"", columns); + return false; + } + if (!mbuf_get_uint32be(&pkt->data, &length)) { + disconnect_server(server, false, ""bad packet""); + return false; + } + if (!mbuf_get_chars(&pkt->data, length, &username)) { + disconnect_server(server, false, ""bad packet""); + return false; + } + if (sizeof(user.name) - 1 < length) + length = sizeof(user.name) - 1; + memcpy(user.name, username, length); + if (!mbuf_get_uint32be(&pkt->data, &length)) { + disconnect_server(server, false, ""bad packet""); + return false; + } + if (length == (uint32_t)-1) { + /* + * NULL - set an md5 password with an impossible value, + * so that nothing will ever match + */ + password = ""md5""; + length = 3; + } else { + if (!mbuf_get_chars(&pkt->data, length, &password)) { + disconnect_server(server, false, ""bad packet""); + return false; + } + } + if (sizeof(user.passwd) - 1 < length) + length = sizeof(user.passwd) - 1; + memcpy(user.passwd, password, length); + + client->auth_user = add_db_user(client->db, user.name, user.passwd); + if (!client->auth_user) { + disconnect_server(server, false, ""unable to allocate new user for auth""); + return false; + } + break; + case 'N': /* NoticeResponse */ + break; + case 'C': /* CommandComplete */ + break; + case '1': /* ParseComplete */ + break; + case '2': /* BindComplete */ + break; + case 'Z': /* ReadyForQuery */ + sbuf_prepare_skip(&client->link->sbuf, pkt->len); + if (!client->auth_user) { + if (cf_log_connections) + slog_info(client, ""login failed: db=%s"", client->db->name); + disconnect_client(client, true, ""No such user""); + } else { + slog_noise(client, ""auth query complete""); + client->link->resetting = true; + sbuf_continue(&client->sbuf); + } + /* + * either sbuf_continue or disconnect_client could disconnect the server + * way down in their bowels of other callbacks. so check that, and + * return appropriately (similar to reuse_on_release) + */ + if (server->state == SV_FREE || server->state == SV_JUSTFREE) + return false; + return true; + default: + disconnect_server(server, false, ""unexpected response from login query""); + return false; + } + sbuf_prepare_skip(&server->sbuf, pkt->len); + return true; +} +","@@ -83,7 +83,6 @@ static void start_auth_request(PgSocket *client, const char *username) + int res; + PktBuf *buf; + +- client->auth_user = client->db->auth_user; + /* have to fetch user info from db */ + client->pool = get_pool(client->db, client->db->auth_user); + if (!find_server(client)) {",864,1195,2048 +20,"static int php_openssl_parse_config(struct php_x509_request * req, zval * optional_args TSRMLS_DC) /* {{{ */ +{ + char * str; + zval ** item; + + SET_OPTIONAL_STRING_ARG(""config"", req->config_filename, default_ssl_conf_filename); + SET_OPTIONAL_STRING_ARG(""config_section_name"", req->section_name, ""req""); + req->global_config = CONF_load(NULL, default_ssl_conf_filename, NULL); + req->req_config = CONF_load(NULL, req->config_filename, NULL); + + if (req->req_config == NULL) { + return FAILURE; + } + + /* read in the oids */ + str = CONF_get_string(req->req_config, NULL, ""oid_file""); + if (str && !php_openssl_safe_mode_chk(str TSRMLS_CC)) { + BIO *oid_bio = BIO_new_file(str, ""r""); + if (oid_bio) { + OBJ_create_objects(oid_bio); + BIO_free(oid_bio); + } + } + if (add_oid_section(req TSRMLS_CC) == FAILURE) { + return FAILURE; + } + SET_OPTIONAL_STRING_ARG(""digest_alg"", req->digest_name, + CONF_get_string(req->req_config, req->section_name, ""default_md"")); + SET_OPTIONAL_STRING_ARG(""x509_extensions"", req->extensions_section, + CONF_get_string(req->req_config, req->section_name, ""x509_extensions"")); + SET_OPTIONAL_STRING_ARG(""req_extensions"", req->request_extensions_section, + CONF_get_string(req->req_config, req->section_name, ""req_extensions"")); + SET_OPTIONAL_LONG_ARG(""private_key_bits"", req->priv_key_bits, + CONF_get_number(req->req_config, req->section_name, ""default_bits"")); + + SET_OPTIONAL_LONG_ARG(""private_key_type"", req->priv_key_type, OPENSSL_KEYTYPE_DEFAULT); + + if (optional_args && zend_hash_find(Z_ARRVAL_P(optional_args), ""encrypt_key"", sizeof(""encrypt_key""), (void**)&item) == SUCCESS) { + req->priv_key_encrypt = Z_BVAL_PP(item); + } else { + str = CONF_get_string(req->req_config, req->section_name, ""encrypt_rsa_key""); + if (str == NULL) { + str = CONF_get_string(req->req_config, req->section_name, ""encrypt_key""); + } + if (str && strcmp(str, ""no"") == 0) { + req->priv_key_encrypt = 0; + } else { + req->priv_key_encrypt = 1; + } + } + + /* digest alg */ + if (req->digest_name == NULL) { + req->digest_name = CONF_get_string(req->req_config, req->section_name, ""default_md""); + } + if (req->digest_name) { + req->digest = req->md_alg = EVP_get_digestbyname(req->digest_name); + } + if (req->md_alg == NULL) { + req->md_alg = req->digest = EVP_md5(); + } + + PHP_SSL_CONFIG_SYNTAX_CHECK(extensions_section); + + /* set the string mask */ + str = CONF_get_string(req->req_config, req->section_name, ""string_mask""); + if (str && !ASN1_STRING_set_default_mask_asc(str)) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Invalid global string mask setting %s"", str); + return FAILURE; + } + + PHP_SSL_CONFIG_SYNTAX_CHECK(request_extensions_section); + + return SUCCESS; +} +/* }}} */ +",0,"static int php_openssl_parse_config(struct php_x509_request * req, zval * optional_args TSRMLS_DC) /* {{{ */ +{ + char * str; + zval ** item; + + SET_OPTIONAL_STRING_ARG(""config"", req->config_filename, default_ssl_conf_filename); + SET_OPTIONAL_STRING_ARG(""config_section_name"", req->section_name, ""req""); + req->global_config = CONF_load(NULL, default_ssl_conf_filename, NULL); + req->req_config = CONF_load(NULL, req->config_filename, NULL); + + if (req->req_config == NULL) { + return FAILURE; + } + + /* read in the oids */ + str = CONF_get_string(req->req_config, NULL, ""oid_file""); + if (str && !php_openssl_safe_mode_chk(str TSRMLS_CC)) { + BIO *oid_bio = BIO_new_file(str, ""r""); + if (oid_bio) { + OBJ_create_objects(oid_bio); + BIO_free(oid_bio); + } + } + if (add_oid_section(req TSRMLS_CC) == FAILURE) { + return FAILURE; + } + SET_OPTIONAL_STRING_ARG(""digest_alg"", req->digest_name, + CONF_get_string(req->req_config, req->section_name, ""default_md"")); + SET_OPTIONAL_STRING_ARG(""x509_extensions"", req->extensions_section, + CONF_get_string(req->req_config, req->section_name, ""x509_extensions"")); + SET_OPTIONAL_STRING_ARG(""req_extensions"", req->request_extensions_section, + CONF_get_string(req->req_config, req->section_name, ""req_extensions"")); + SET_OPTIONAL_LONG_ARG(""private_key_bits"", req->priv_key_bits, + CONF_get_number(req->req_config, req->section_name, ""default_bits"")); + + SET_OPTIONAL_LONG_ARG(""private_key_type"", req->priv_key_type, OPENSSL_KEYTYPE_DEFAULT); + + if (optional_args && zend_hash_find(Z_ARRVAL_P(optional_args), ""encrypt_key"", sizeof(""encrypt_key""), (void**)&item) == SUCCESS) { + req->priv_key_encrypt = Z_BVAL_PP(item); + } else { + str = CONF_get_string(req->req_config, req->section_name, ""encrypt_rsa_key""); + if (str == NULL) { + str = CONF_get_string(req->req_config, req->section_name, ""encrypt_key""); + } + if (str && strcmp(str, ""no"") == 0) { + req->priv_key_encrypt = 0; + } else { + req->priv_key_encrypt = 1; + } + } + + /* digest alg */ + if (req->digest_name == NULL) { + req->digest_name = CONF_get_string(req->req_config, req->section_name, ""default_md""); + } + if (req->digest_name) { + req->digest = req->md_alg = EVP_get_digestbyname(req->digest_name); + } + if (req->md_alg == NULL) { + req->md_alg = req->digest = EVP_md5(); + } + + PHP_SSL_CONFIG_SYNTAX_CHECK(extensions_section); + + /* set the string mask */ + str = CONF_get_string(req->req_config, req->section_name, ""string_mask""); + if (str && !ASN1_STRING_set_default_mask_asc(str)) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Invalid global string mask setting %s"", str); + return FAILURE; + } + + PHP_SSL_CONFIG_SYNTAX_CHECK(request_extensions_section); + + return SUCCESS; +} +/* }}} */ +","@@ -644,18 +644,28 @@ static time_t asn1_time_to_time_t(ASN1_UTCTIME * timestr TSRMLS_DC) /* {{{ */ + char * thestr; + long gmadjust = 0; + +- if (timestr->length < 13) { +- php_error_docref(NULL TSRMLS_CC, E_WARNING, ""extension author too lazy to parse %s correctly"", timestr->data); ++ if (ASN1_STRING_type(timestr) != V_ASN1_UTCTIME) { ++ php_error_docref(NULL TSRMLS_CC, E_WARNING, ""illegal ASN1 data type for timestamp""); + return (time_t)-1; + } + +- strbuf = estrdup((char *)timestr->data); ++ if (ASN1_STRING_length(timestr) != strlen(ASN1_STRING_data(timestr))) { ++ php_error_docref(NULL TSRMLS_CC, E_WARNING, ""illegal length in timestamp""); ++ return (time_t)-1; ++ } ++ ++ if (ASN1_STRING_length(timestr) < 13) { ++ php_error_docref(NULL TSRMLS_CC, E_WARNING, ""unable to parse time string %s correctly"", timestr->data); ++ return (time_t)-1; ++ } ++ ++ strbuf = estrdup((char *)ASN1_STRING_data(timestr)); + + memset(&thetime, 0, sizeof(thetime)); + + /* we work backwards so that we can use atoi more easily */ + +- thestr = strbuf + timestr->length - 3; ++ thestr = strbuf + ASN1_STRING_length(timestr) - 3; + + thetime.tm_sec = atoi(thestr); + *thestr = '\0';",736,1067,2048 +6062,"R_API void r_flag_list(RFlag *f, int rad, const char *pfx) { + bool in_range = false; + ut64 range_from = UT64_MAX; + ut64 range_to = UT64_MAX; + int fs = -1; + RListIter *iter; + RFlagItem *flag; + if (rad == 'i') { + char *sp, *arg = strdup (pfx + 1); + sp = strchr (arg, ' '); + if (sp) { + *sp++ = 0; + range_from = r_num_math (f->num, arg); + range_to = r_num_math (f->num, sp); + } else { + const int bsize = 4096; + range_from = r_num_math (f->num, arg); + range_to = range_from + bsize; + } + in_range = true; + free (arg); + rad = pfx[0]; + pfx = NULL; + } + + if (pfx && !*pfx) { + pfx = NULL; + } + + switch (rad) { + case 'j': { + int first = 1; + f->cb_printf (""[""); + r_list_foreach (f->flags, iter, flag) { + if (IS_IN_SPACE (f, flag)) { + continue; + } + if (in_range && (flag->offset < range_from || flag->offset >= range_to)) { + continue; + } + f->cb_printf (""%s{\""name\"":\""%s\"",\""size\"":%""PFMT64d"","", + first?"""":"","", flag->name, flag->size); + if (flag->alias) { + f->cb_printf (""\""alias\"":\""%s\"""", flag->alias); + } else { + f->cb_printf (""\""offset\"":%""PFMT64d, flag->offset); + } + if (flag->comment) + f->cb_printf ("",\""comment\"":\""}""); + else f->cb_printf (""}""); + first = 0; + } + f->cb_printf (""]\n""); + } + break; + case 1: + case '*': + r_list_foreach (f->flags, iter, flag) { + if (IS_IN_SPACE (f, flag)) { + continue; + } + if (in_range && (flag->offset < range_from || flag->offset >= range_to)) { + continue; + } + if (fs == -1 || flag->space != fs) { + const char *flagspace; + fs = flag->space; + flagspace = r_flag_space_get_i (f, fs); + if (!flagspace || !*flagspace) + flagspace = ""*""; + f->cb_printf (""fs %s\n"", flagspace); + } + if (flag->alias) { + f->cb_printf (""fa %s %s\n"", flag->name, flag->alias); + if (flag->comment && *flag->comment) + f->cb_printf (""\""fC %s %s\""\n"", + flag->name, flag->comment); + } else { + f->cb_printf (""f %s %""PFMT64d"" 0x%08""PFMT64x""%s%s %s\n"", + flag->name, flag->size, flag->offset, + pfx?""+"":"""", pfx?pfx:"""", + flag->comment? flag->comment:""""); + } + } + break; + case 'n': // show original name + r_list_foreach (f->flags, iter, flag) { + if (IS_IN_SPACE (f, flag)) { + continue; + } + if (in_range && (flag->offset < range_from || flag->offset >= range_to)) { + continue; + } + if (flag->alias) { + f->cb_printf (""%s %""PFMT64d"" %s\n"", + flag->alias, flag->size, flag->realname); + } else { + f->cb_printf (""0x%08""PFMT64x"" %""PFMT64d"" %s\n"", + flag->offset, flag->size, flag->realname); + } + } + break; + default: + r_list_foreach (f->flags, iter, flag) { + if (IS_IN_SPACE (f, flag)) { + continue; + } + if (in_range && (flag->offset < range_from || flag->offset >= range_to)) { + continue; + } + if (flag->alias) { + f->cb_printf (""%s %""PFMT64d"" %s\n"", + flag->alias, flag->size, flag->name); + } else { + f->cb_printf (""0x%08""PFMT64x"" %""PFMT64d"" %s\n"", + flag->offset, flag->size, flag->name); + } + } + break; + } +",0,"R_API void r_flag_list(RFlag *f, int rad, const char *pfx) { + bool in_range = false; + ut64 range_from = UT64_MAX; + ut64 range_to = UT64_MAX; + int fs = -1; + RListIter *iter; + RFlagItem *flag; + if (rad == 'i') { + char *sp, *arg = strdup (pfx + 1); + sp = strchr (arg, ' '); + if (sp) { + *sp++ = 0; + range_from = r_num_math (f->num, arg); + range_to = r_num_math (f->num, sp); + } else { + const int bsize = 4096; + range_from = r_num_math (f->num, arg); + range_to = range_from + bsize; + } + in_range = true; + free (arg); + rad = pfx[0]; + pfx = NULL; + } + + if (pfx && !*pfx) { + pfx = NULL; + } + + switch (rad) { + case 'j': { + int first = 1; + f->cb_printf (""[""); + r_list_foreach (f->flags, iter, flag) { + if (IS_IN_SPACE (f, flag)) { + continue; + } + if (in_range && (flag->offset < range_from || flag->offset >= range_to)) { + continue; + } + f->cb_printf (""%s{\""name\"":\""%s\"",\""size\"":%""PFMT64d"","", + first?"""":"","", flag->name, flag->size); + if (flag->alias) { + f->cb_printf (""\""alias\"":\""%s\"""", flag->alias); + } else { + f->cb_printf (""\""offset\"":%""PFMT64d, flag->offset); + } + if (flag->comment) + f->cb_printf ("",\""comment\"":\""}""); + else f->cb_printf (""}""); + first = 0; + } + f->cb_printf (""]\n""); + } + break; + case 1: + case '*': + r_list_foreach (f->flags, iter, flag) { + if (IS_IN_SPACE (f, flag)) { + continue; + } + if (in_range && (flag->offset < range_from || flag->offset >= range_to)) { + continue; + } + if (fs == -1 || flag->space != fs) { + const char *flagspace; + fs = flag->space; + flagspace = r_flag_space_get_i (f, fs); + if (!flagspace || !*flagspace) + flagspace = ""*""; + f->cb_printf (""fs %s\n"", flagspace); + } + if (flag->alias) { + f->cb_printf (""fa %s %s\n"", flag->name, flag->alias); + if (flag->comment && *flag->comment) + f->cb_printf (""\""fC %s %s\""\n"", + flag->name, flag->comment); + } else { + f->cb_printf (""f %s %""PFMT64d"" 0x%08""PFMT64x""%s%s %s\n"", + flag->name, flag->size, flag->offset, + pfx?""+"":"""", pfx?pfx:"""", + flag->comment? flag->comment:""""); + } + } + break; + case 'n': // show original name + r_list_foreach (f->flags, iter, flag) { + if (IS_IN_SPACE (f, flag)) { + continue; + } + if (in_range && (flag->offset < range_from || flag->offset >= range_to)) { + continue; + } + if (flag->alias) { + f->cb_printf (""%s %""PFMT64d"" %s\n"", + flag->alias, flag->size, flag->realname); + } else { + f->cb_printf (""0x%08""PFMT64x"" %""PFMT64d"" %s\n"", + flag->offset, flag->size, flag->realname); + } + } + break; + default: + r_list_foreach (f->flags, iter, flag) { + if (IS_IN_SPACE (f, flag)) { + continue; + } + if (in_range && (flag->offset < range_from || flag->offset >= range_to)) { + continue; + } + if (flag->alias) { + f->cb_printf (""%s %""PFMT64d"" %s\n"", + flag->alias, flag->size, flag->name); + } else { + f->cb_printf (""0x%08""PFMT64x"" %""PFMT64d"" %s\n"", + flag->offset, flag->size, flag->name); + } + } + break; + } +","@@ -74,7 +74,7 @@ static ut64 num_callback(RNum *user, const char *name, int *ok) { + dir == -1 -> result <= off + dir == 0 -> result == off + dir == 1 -> result >= off*/ +-static RFlagsAtOffset* r_flag_get_nearest_list(RFlag *f, ut64 off, int dir) { ++static RFlagsAtOffset* r_flag_get_nearest_list(RFlag *f, ut64 off, int dir) { + RFlagsAtOffset *flags = NULL; + RFlagsAtOffset key; + key.off = off;",1085,1416,2048 +17954,"static int llc_ui_recvmsg(struct kiocb *iocb, struct socket *sock, + struct msghdr *msg, size_t len, int flags) +{ + struct sockaddr_llc *uaddr = (struct sockaddr_llc *)msg->msg_name; + const int nonblock = flags & MSG_DONTWAIT; + struct sk_buff *skb = NULL; + struct sock *sk = sock->sk; + struct llc_sock *llc = llc_sk(sk); + unsigned long cpu_flags; + size_t copied = 0; + u32 peek_seq = 0; + u32 *seq; + unsigned long used; + int target; /* Read at least this many bytes */ + long timeo; + + msg->msg_namelen = 0; + lock_sock(sk); + copied = -ENOTCONN; + if (unlikely(sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_LISTEN)) + goto out; + + timeo = sock_rcvtimeo(sk, nonblock); + + seq = &llc->copied_seq; + if (flags & MSG_PEEK) { + peek_seq = llc->copied_seq; + seq = &peek_seq; + } + + target = sock_rcvlowat(sk, flags & MSG_WAITALL, len); + copied = 0; + + do { + u32 offset; + + /* + * We need to check signals first, to get correct SIGURG + * handling. FIXME: Need to check this doesn't impact 1003.1g + * and move it down to the bottom of the loop + */ + if (signal_pending(current)) { + if (copied) + break; + copied = timeo ? sock_intr_errno(timeo) : -EAGAIN; + break; + } + + /* Next get a buffer. */ + + skb = skb_peek(&sk->sk_receive_queue); + if (skb) { + offset = *seq; + goto found_ok_skb; + } + /* Well, if we have backlog, try to process it now yet. */ + + if (copied >= target && !sk->sk_backlog.tail) + break; + + if (copied) { + if (sk->sk_err || + sk->sk_state == TCP_CLOSE || + (sk->sk_shutdown & RCV_SHUTDOWN) || + !timeo || + (flags & MSG_PEEK)) + break; + } else { + if (sock_flag(sk, SOCK_DONE)) + break; + + if (sk->sk_err) { + copied = sock_error(sk); + break; + } + if (sk->sk_shutdown & RCV_SHUTDOWN) + break; + + if (sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_CLOSE) { + if (!sock_flag(sk, SOCK_DONE)) { + /* + * This occurs when user tries to read + * from never connected socket. + */ + copied = -ENOTCONN; + break; + } + break; + } + if (!timeo) { + copied = -EAGAIN; + break; + } + } + + if (copied >= target) { /* Do not sleep, just process backlog. */ + release_sock(sk); + lock_sock(sk); + } else + sk_wait_data(sk, &timeo); + + if ((flags & MSG_PEEK) && peek_seq != llc->copied_seq) { + net_dbg_ratelimited(""LLC(%s:%d): Application bug, race in MSG_PEEK\n"", + current->comm, + task_pid_nr(current)); + peek_seq = llc->copied_seq; + } + continue; + found_ok_skb: + /* Ok so how much can we use? */ + used = skb->len - offset; + if (len < used) + used = len; + + if (!(flags & MSG_TRUNC)) { + int rc = skb_copy_datagram_iovec(skb, offset, + msg->msg_iov, used); + if (rc) { + /* Exception. Bailout! */ + if (!copied) + copied = -EFAULT; + break; + } + } + + *seq += used; + copied += used; + len -= used; + + /* For non stream protcols we get one packet per recvmsg call */ + if (sk->sk_type != SOCK_STREAM) + goto copy_uaddr; + + if (!(flags & MSG_PEEK)) { + spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags); + sk_eat_skb(sk, skb, false); + spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags); + *seq = 0; + } + + /* Partial read */ + if (used + offset < skb->len) + continue; + } while (len > 0); + +out: + release_sock(sk); + return copied; +copy_uaddr: + if (uaddr != NULL && skb != NULL) { + memcpy(uaddr, llc_ui_skb_cb(skb), sizeof(*uaddr)); + msg->msg_namelen = sizeof(*uaddr); + } + if (llc_sk(sk)->cmsg_flags) + llc_cmsg_rcv(msg, skb); + + if (!(flags & MSG_PEEK)) { + spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags); + sk_eat_skb(sk, skb, false); + spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags); + *seq = 0; + } + + goto out; +} +",1,"static int llc_ui_recvmsg(struct kiocb *iocb, struct socket *sock, + struct msghdr *msg, size_t len, int flags) +{ + struct sockaddr_llc *uaddr = (struct sockaddr_llc *)msg->msg_name; + const int nonblock = flags & MSG_DONTWAIT; + struct sk_buff *skb = NULL; + struct sock *sk = sock->sk; + struct llc_sock *llc = llc_sk(sk); + unsigned long cpu_flags; + size_t copied = 0; + u32 peek_seq = 0; + u32 *seq; + unsigned long used; + int target; /* Read at least this many bytes */ + long timeo; + + lock_sock(sk); + copied = -ENOTCONN; + if (unlikely(sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_LISTEN)) + goto out; + + timeo = sock_rcvtimeo(sk, nonblock); + + seq = &llc->copied_seq; + if (flags & MSG_PEEK) { + peek_seq = llc->copied_seq; + seq = &peek_seq; + } + + target = sock_rcvlowat(sk, flags & MSG_WAITALL, len); + copied = 0; + + do { + u32 offset; + + /* + * We need to check signals first, to get correct SIGURG + * handling. FIXME: Need to check this doesn't impact 1003.1g + * and move it down to the bottom of the loop + */ + if (signal_pending(current)) { + if (copied) + break; + copied = timeo ? sock_intr_errno(timeo) : -EAGAIN; + break; + } + + /* Next get a buffer. */ + + skb = skb_peek(&sk->sk_receive_queue); + if (skb) { + offset = *seq; + goto found_ok_skb; + } + /* Well, if we have backlog, try to process it now yet. */ + + if (copied >= target && !sk->sk_backlog.tail) + break; + + if (copied) { + if (sk->sk_err || + sk->sk_state == TCP_CLOSE || + (sk->sk_shutdown & RCV_SHUTDOWN) || + !timeo || + (flags & MSG_PEEK)) + break; + } else { + if (sock_flag(sk, SOCK_DONE)) + break; + + if (sk->sk_err) { + copied = sock_error(sk); + break; + } + if (sk->sk_shutdown & RCV_SHUTDOWN) + break; + + if (sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_CLOSE) { + if (!sock_flag(sk, SOCK_DONE)) { + /* + * This occurs when user tries to read + * from never connected socket. + */ + copied = -ENOTCONN; + break; + } + break; + } + if (!timeo) { + copied = -EAGAIN; + break; + } + } + + if (copied >= target) { /* Do not sleep, just process backlog. */ + release_sock(sk); + lock_sock(sk); + } else + sk_wait_data(sk, &timeo); + + if ((flags & MSG_PEEK) && peek_seq != llc->copied_seq) { + net_dbg_ratelimited(""LLC(%s:%d): Application bug, race in MSG_PEEK\n"", + current->comm, + task_pid_nr(current)); + peek_seq = llc->copied_seq; + } + continue; + found_ok_skb: + /* Ok so how much can we use? */ + used = skb->len - offset; + if (len < used) + used = len; + + if (!(flags & MSG_TRUNC)) { + int rc = skb_copy_datagram_iovec(skb, offset, + msg->msg_iov, used); + if (rc) { + /* Exception. Bailout! */ + if (!copied) + copied = -EFAULT; + break; + } + } + + *seq += used; + copied += used; + len -= used; + + /* For non stream protcols we get one packet per recvmsg call */ + if (sk->sk_type != SOCK_STREAM) + goto copy_uaddr; + + if (!(flags & MSG_PEEK)) { + spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags); + sk_eat_skb(sk, skb, false); + spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags); + *seq = 0; + } + + /* Partial read */ + if (used + offset < skb->len) + continue; + } while (len > 0); + +out: + release_sock(sk); + return copied; +copy_uaddr: + if (uaddr != NULL && skb != NULL) { + memcpy(uaddr, llc_ui_skb_cb(skb), sizeof(*uaddr)); + msg->msg_namelen = sizeof(*uaddr); + } + if (llc_sk(sk)->cmsg_flags) + llc_cmsg_rcv(msg, skb); + + if (!(flags & MSG_PEEK)) { + spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags); + sk_eat_skb(sk, skb, false); + spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags); + *seq = 0; + } + + goto out; +} +","@@ -720,8 +720,6 @@ static int llc_ui_recvmsg(struct kiocb *iocb, struct socket *sock, + int target; /* Read at least this many bytes */ + long timeo; + +- msg->msg_namelen = 0; +- + lock_sock(sk); + copied = -ENOTCONN; + if (unlikely(sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_LISTEN))",1196,1527,2048 +5709,"static int hub_port_reset(struct usb_hub *hub, int port1, + struct usb_device *udev, unsigned int delay, bool warm) +{ + int i, status; + u16 portchange, portstatus; + struct usb_port *port_dev = hub->ports[port1 - 1]; + + if (!hub_is_superspeed(hub->hdev)) { + if (warm) { + dev_err(hub->intfdev, ""only USB3 hub support "" + ""warm reset\n""); + return -EINVAL; + } + /* Block EHCI CF initialization during the port reset. + * Some companion controllers don't like it when they mix. + */ + down_read(&ehci_cf_port_reset_rwsem); + } else if (!warm) { + /* + * If the caller hasn't explicitly requested a warm reset, + * double check and see if one is needed. + */ + if (hub_port_status(hub, port1, &portstatus, &portchange) == 0) + if (hub_port_warm_reset_required(hub, port1, + portstatus)) + warm = true; + } + clear_bit(port1, hub->warm_reset_bits); + + /* Reset the port */ + for (i = 0; i < PORT_RESET_TRIES; i++) { + status = set_port_feature(hub->hdev, port1, (warm ? + USB_PORT_FEAT_BH_PORT_RESET : + USB_PORT_FEAT_RESET)); + if (status == -ENODEV) { + ; /* The hub is gone */ + } else if (status) { + dev_err(&port_dev->dev, + ""cannot %sreset (err = %d)\n"", + warm ? ""warm "" : """", status); + } else { + status = hub_port_wait_reset(hub, port1, udev, delay, + warm); + if (status && status != -ENOTCONN && status != -ENODEV) + dev_dbg(hub->intfdev, + ""port_wait_reset: err = %d\n"", + status); + } + + /* Check for disconnect or reset */ + if (status == 0 || status == -ENOTCONN || status == -ENODEV) { + usb_clear_port_feature(hub->hdev, port1, + USB_PORT_FEAT_C_RESET); + + if (!hub_is_superspeed(hub->hdev)) + goto done; + + usb_clear_port_feature(hub->hdev, port1, + USB_PORT_FEAT_C_BH_PORT_RESET); + usb_clear_port_feature(hub->hdev, port1, + USB_PORT_FEAT_C_PORT_LINK_STATE); + usb_clear_port_feature(hub->hdev, port1, + USB_PORT_FEAT_C_CONNECTION); + + /* + * If a USB 3.0 device migrates from reset to an error + * state, re-issue the warm reset. + */ + if (hub_port_status(hub, port1, + &portstatus, &portchange) < 0) + goto done; + + if (!hub_port_warm_reset_required(hub, port1, + portstatus)) + goto done; + + /* + * If the port is in SS.Inactive or Compliance Mode, the + * hot or warm reset failed. Try another warm reset. + */ + if (!warm) { + dev_dbg(&port_dev->dev, + ""hot reset failed, warm reset\n""); + warm = true; + } + } + + dev_dbg(&port_dev->dev, + ""not enabled, trying %sreset again...\n"", + warm ? ""warm "" : """"); + delay = HUB_LONG_RESET_TIME; + } + + dev_err(&port_dev->dev, ""Cannot enable. Maybe the USB cable is bad?\n""); + +done: + if (status == 0) { + /* TRSTRCY = 10 ms; plus some extra */ + msleep(10 + 40); + if (udev) { + struct usb_hcd *hcd = bus_to_hcd(udev->bus); + + update_devnum(udev, 0); + /* The xHC may think the device is already reset, + * so ignore the status. + */ + if (hcd->driver->reset_device) + hcd->driver->reset_device(hcd, udev); + + usb_set_device_state(udev, USB_STATE_DEFAULT); + } + } else { + if (udev) + usb_set_device_state(udev, USB_STATE_NOTATTACHED); + } + + if (!hub_is_superspeed(hub->hdev)) + up_read(&ehci_cf_port_reset_rwsem); + + return status; +} +",0,"static int hub_port_reset(struct usb_hub *hub, int port1, + struct usb_device *udev, unsigned int delay, bool warm) +{ + int i, status; + u16 portchange, portstatus; + struct usb_port *port_dev = hub->ports[port1 - 1]; + + if (!hub_is_superspeed(hub->hdev)) { + if (warm) { + dev_err(hub->intfdev, ""only USB3 hub support "" + ""warm reset\n""); + return -EINVAL; + } + /* Block EHCI CF initialization during the port reset. + * Some companion controllers don't like it when they mix. + */ + down_read(&ehci_cf_port_reset_rwsem); + } else if (!warm) { + /* + * If the caller hasn't explicitly requested a warm reset, + * double check and see if one is needed. + */ + if (hub_port_status(hub, port1, &portstatus, &portchange) == 0) + if (hub_port_warm_reset_required(hub, port1, + portstatus)) + warm = true; + } + clear_bit(port1, hub->warm_reset_bits); + + /* Reset the port */ + for (i = 0; i < PORT_RESET_TRIES; i++) { + status = set_port_feature(hub->hdev, port1, (warm ? + USB_PORT_FEAT_BH_PORT_RESET : + USB_PORT_FEAT_RESET)); + if (status == -ENODEV) { + ; /* The hub is gone */ + } else if (status) { + dev_err(&port_dev->dev, + ""cannot %sreset (err = %d)\n"", + warm ? ""warm "" : """", status); + } else { + status = hub_port_wait_reset(hub, port1, udev, delay, + warm); + if (status && status != -ENOTCONN && status != -ENODEV) + dev_dbg(hub->intfdev, + ""port_wait_reset: err = %d\n"", + status); + } + + /* Check for disconnect or reset */ + if (status == 0 || status == -ENOTCONN || status == -ENODEV) { + usb_clear_port_feature(hub->hdev, port1, + USB_PORT_FEAT_C_RESET); + + if (!hub_is_superspeed(hub->hdev)) + goto done; + + usb_clear_port_feature(hub->hdev, port1, + USB_PORT_FEAT_C_BH_PORT_RESET); + usb_clear_port_feature(hub->hdev, port1, + USB_PORT_FEAT_C_PORT_LINK_STATE); + usb_clear_port_feature(hub->hdev, port1, + USB_PORT_FEAT_C_CONNECTION); + + /* + * If a USB 3.0 device migrates from reset to an error + * state, re-issue the warm reset. + */ + if (hub_port_status(hub, port1, + &portstatus, &portchange) < 0) + goto done; + + if (!hub_port_warm_reset_required(hub, port1, + portstatus)) + goto done; + + /* + * If the port is in SS.Inactive or Compliance Mode, the + * hot or warm reset failed. Try another warm reset. + */ + if (!warm) { + dev_dbg(&port_dev->dev, + ""hot reset failed, warm reset\n""); + warm = true; + } + } + + dev_dbg(&port_dev->dev, + ""not enabled, trying %sreset again...\n"", + warm ? ""warm "" : """"); + delay = HUB_LONG_RESET_TIME; + } + + dev_err(&port_dev->dev, ""Cannot enable. Maybe the USB cable is bad?\n""); + +done: + if (status == 0) { + /* TRSTRCY = 10 ms; plus some extra */ + msleep(10 + 40); + if (udev) { + struct usb_hcd *hcd = bus_to_hcd(udev->bus); + + update_devnum(udev, 0); + /* The xHC may think the device is already reset, + * so ignore the status. + */ + if (hcd->driver->reset_device) + hcd->driver->reset_device(hcd, udev); + + usb_set_device_state(udev, USB_STATE_DEFAULT); + } + } else { + if (udev) + usb_set_device_state(udev, USB_STATE_NOTATTACHED); + } + + if (!hub_is_superspeed(hub->hdev)) + up_read(&ehci_cf_port_reset_rwsem); + + return status; +} +","@@ -1035,10 +1035,20 @@ static void hub_activate(struct usb_hub *hub, enum hub_activation_type type) + unsigned delay; + + /* Continue a partial initialization */ +- if (type == HUB_INIT2) +- goto init2; +- if (type == HUB_INIT3) ++ if (type == HUB_INIT2 || type == HUB_INIT3) { ++ device_lock(hub->intfdev); ++ ++ /* Was the hub disconnected while we were waiting? */ ++ if (hub->disconnected) { ++ device_unlock(hub->intfdev); ++ kref_put(&hub->kref, hub_release); ++ return; ++ } ++ if (type == HUB_INIT2) ++ goto init2; + goto init3; ++ } ++ kref_get(&hub->kref); + + /* The superspeed hub except for root hub has to use Hub Depth + * value as an offset into the route string to locate the bits +@@ -1236,6 +1246,7 @@ static void hub_activate(struct usb_hub *hub, enum hub_activation_type type) + queue_delayed_work(system_power_efficient_wq, + &hub->init_work, + msecs_to_jiffies(delay)); ++ device_unlock(hub->intfdev); + return; /* Continues at init3: below */ + } else { + msleep(delay); +@@ -1257,6 +1268,11 @@ static void hub_activate(struct usb_hub *hub, enum hub_activation_type type) + /* Allow autosuspend if it was suppressed */ + if (type <= HUB_INIT3) + usb_autopm_put_interface_async(to_usb_interface(hub->intfdev)); ++ ++ if (type == HUB_INIT2 || type == HUB_INIT3) ++ device_unlock(hub->intfdev); ++ ++ kref_put(&hub->kref, hub_release); + } + + /* Implement the continuations for the delays above */",1014,1345,2048 +8410,"check_table_height(struct table *t) +{ + int i, j, k; + struct { + short *row; + short *rowspan; + short *indexarray; + short maxcell; + short size; + short *height; + } cell; + int space = 0; + + cell.size = 0; + cell.maxcell = -1; + + for (j = 0; j <= t->maxrow; j++) { + if (!t->tabattr[j]) + continue; + for (i = 0; i <= t->maxcol; i++) { + int t_dep, rowspan; + if (t->tabattr[j][i] & (HTT_X | HTT_Y)) + continue; + + if (t->tabdata[j][i] == NULL) + t_dep = 0; + else + t_dep = t->tabdata[j][i]->nitem; + + rowspan = table_rowspan(t, j, i); + if (rowspan > 1) { + int c = cell.maxcell + 1; + k = bsearch_2short(rowspan, cell.rowspan, + j, cell.row, t->maxrow + 1, cell.indexarray, + c); + if (k <= cell.maxcell) { + int idx = cell.indexarray[k]; + if (cell.row[idx] == j && cell.rowspan[idx] == rowspan) + c = idx; + } + if (c >= MAXROWCELL) + continue; + if (c >= cell.size) { + if (cell.size == 0) { + cell.size = max(MAXCELL, c + 1); + cell.row = NewAtom_N(short, cell.size); + cell.rowspan = NewAtom_N(short, cell.size); + cell.indexarray = NewAtom_N(short, cell.size); + cell.height = NewAtom_N(short, cell.size); + } + else { + cell.size = max(cell.size + MAXCELL, c + 1); + cell.row = New_Reuse(short, cell.row, cell.size); + cell.rowspan = New_Reuse(short, cell.rowspan, + cell.size); + cell.indexarray = New_Reuse(short, cell.indexarray, + cell.size); + cell.height = New_Reuse(short, cell.height, cell.size); + } + } + if (c > cell.maxcell) { + cell.maxcell++; + cell.row[cell.maxcell] = j; + cell.rowspan[cell.maxcell] = rowspan; + cell.height[cell.maxcell] = 0; + if (cell.maxcell > k) { + int ii; + for (ii = cell.maxcell; ii > k; ii--) + cell.indexarray[ii] = cell.indexarray[ii - 1]; + } + cell.indexarray[k] = cell.maxcell; + } + + if (cell.height[c] < t_dep) + cell.height[c] = t_dep; + continue; + } + if (t->tabheight[j] < t_dep) + t->tabheight[j] = t_dep; + } + } + + switch (t->border_mode) { + case BORDER_THIN: + case BORDER_THICK: + case BORDER_NOWIN: + space = 1; + break; + case BORDER_NONE: + space = 0; + } + check_cell_width(t->tabheight, cell.height, cell.row, cell.rowspan, + cell.maxcell, cell.indexarray, space, 1); +} +",0,"check_table_height(struct table *t) +{ + int i, j, k; + struct { + short *row; + short *rowspan; + short *indexarray; + short maxcell; + short size; + short *height; + } cell; + int space = 0; + + cell.size = 0; + cell.maxcell = -1; + + for (j = 0; j <= t->maxrow; j++) { + if (!t->tabattr[j]) + continue; + for (i = 0; i <= t->maxcol; i++) { + int t_dep, rowspan; + if (t->tabattr[j][i] & (HTT_X | HTT_Y)) + continue; + + if (t->tabdata[j][i] == NULL) + t_dep = 0; + else + t_dep = t->tabdata[j][i]->nitem; + + rowspan = table_rowspan(t, j, i); + if (rowspan > 1) { + int c = cell.maxcell + 1; + k = bsearch_2short(rowspan, cell.rowspan, + j, cell.row, t->maxrow + 1, cell.indexarray, + c); + if (k <= cell.maxcell) { + int idx = cell.indexarray[k]; + if (cell.row[idx] == j && cell.rowspan[idx] == rowspan) + c = idx; + } + if (c >= MAXROWCELL) + continue; + if (c >= cell.size) { + if (cell.size == 0) { + cell.size = max(MAXCELL, c + 1); + cell.row = NewAtom_N(short, cell.size); + cell.rowspan = NewAtom_N(short, cell.size); + cell.indexarray = NewAtom_N(short, cell.size); + cell.height = NewAtom_N(short, cell.size); + } + else { + cell.size = max(cell.size + MAXCELL, c + 1); + cell.row = New_Reuse(short, cell.row, cell.size); + cell.rowspan = New_Reuse(short, cell.rowspan, + cell.size); + cell.indexarray = New_Reuse(short, cell.indexarray, + cell.size); + cell.height = New_Reuse(short, cell.height, cell.size); + } + } + if (c > cell.maxcell) { + cell.maxcell++; + cell.row[cell.maxcell] = j; + cell.rowspan[cell.maxcell] = rowspan; + cell.height[cell.maxcell] = 0; + if (cell.maxcell > k) { + int ii; + for (ii = cell.maxcell; ii > k; ii--) + cell.indexarray[ii] = cell.indexarray[ii - 1]; + } + cell.indexarray[k] = cell.maxcell; + } + + if (cell.height[c] < t_dep) + cell.height[c] = t_dep; + continue; + } + if (t->tabheight[j] < t_dep) + t->tabheight[j] = t_dep; + } + } + + switch (t->border_mode) { + case BORDER_THIN: + case BORDER_THICK: + case BORDER_NOWIN: + space = 1; + break; + case BORDER_NONE: + space = 0; + } + check_cell_width(t->tabheight, cell.height, cell.row, cell.rowspan, + cell.maxcell, cell.indexarray, space, 1); +} +","@@ -2356,10 +2356,14 @@ feed_table_block_tag(struct table *tbl, + if (mode->indent_level < MAX_INDENT_LEVEL) + tbl->indent -= INDENT_INCR; + } ++ if (tbl->indent < 0) ++ tbl->indent = 0; + offset = tbl->indent; + if (cmd == HTML_DT) { + if (mode->indent_level > 0 && mode->indent_level <= MAX_INDENT_LEVEL) + offset -= INDENT_INCR; ++ if (offset < 0) ++ offset = 0; + } + if (tbl->indent > 0) { + check_minimum0(tbl, 0);",730,1061,2048 +3617,"static int emulator_do_task_switch(struct x86_emulate_ctxt *ctxt, + u16 tss_selector, int idt_index, int reason, + bool has_error_code, u32 error_code) +{ + const struct x86_emulate_ops *ops = ctxt->ops; + struct desc_struct curr_tss_desc, next_tss_desc; + int ret; + u16 old_tss_sel = get_segment_selector(ctxt, VCPU_SREG_TR); + ulong old_tss_base = + ops->get_cached_segment_base(ctxt, VCPU_SREG_TR); + u32 desc_limit; + ulong desc_addr; + + /* FIXME: old_tss_base == ~0 ? */ + + ret = read_segment_descriptor(ctxt, tss_selector, &next_tss_desc, &desc_addr); + if (ret != X86EMUL_CONTINUE) + return ret; + ret = read_segment_descriptor(ctxt, old_tss_sel, &curr_tss_desc, &desc_addr); + if (ret != X86EMUL_CONTINUE) + return ret; + + /* FIXME: check that next_tss_desc is tss */ + + /* + * Check privileges. The three cases are task switch caused by... + * + * 1. jmp/call/int to task gate: Check against DPL of the task gate + * 2. Exception/IRQ/iret: No check is performed + * 3. jmp/call to TSS: Check against DPL of the TSS + */ + if (reason == TASK_SWITCH_GATE) { + if (idt_index != -1) { + /* Software interrupts */ + struct desc_struct task_gate_desc; + int dpl; + + ret = read_interrupt_descriptor(ctxt, idt_index, + &task_gate_desc); + if (ret != X86EMUL_CONTINUE) + return ret; + + dpl = task_gate_desc.dpl; + if ((tss_selector & 3) > dpl || ops->cpl(ctxt) > dpl) + return emulate_gp(ctxt, (idt_index << 3) | 0x2); + } + } else if (reason != TASK_SWITCH_IRET) { + int dpl = next_tss_desc.dpl; + if ((tss_selector & 3) > dpl || ops->cpl(ctxt) > dpl) + return emulate_gp(ctxt, tss_selector); + } + + + desc_limit = desc_limit_scaled(&next_tss_desc); + if (!next_tss_desc.p || + ((desc_limit < 0x67 && (next_tss_desc.type & 8)) || + desc_limit < 0x2b)) { + return emulate_ts(ctxt, tss_selector & 0xfffc); + } + + if (reason == TASK_SWITCH_IRET || reason == TASK_SWITCH_JMP) { + curr_tss_desc.type &= ~(1 << 1); /* clear busy flag */ + write_segment_descriptor(ctxt, old_tss_sel, &curr_tss_desc); + } + + if (reason == TASK_SWITCH_IRET) + ctxt->eflags = ctxt->eflags & ~X86_EFLAGS_NT; + + /* set back link to prev task only if NT bit is set in eflags + note that old_tss_sel is not used after this point */ + if (reason != TASK_SWITCH_CALL && reason != TASK_SWITCH_GATE) + old_tss_sel = 0xffff; + + if (next_tss_desc.type & 8) + ret = task_switch_32(ctxt, tss_selector, old_tss_sel, + old_tss_base, &next_tss_desc); + else + ret = task_switch_16(ctxt, tss_selector, old_tss_sel, + old_tss_base, &next_tss_desc); + if (ret != X86EMUL_CONTINUE) + return ret; + + if (reason == TASK_SWITCH_CALL || reason == TASK_SWITCH_GATE) + ctxt->eflags = ctxt->eflags | X86_EFLAGS_NT; + + if (reason != TASK_SWITCH_IRET) { + next_tss_desc.type |= (1 << 1); /* set busy flag */ + write_segment_descriptor(ctxt, tss_selector, &next_tss_desc); + } + + ops->set_cr(ctxt, 0, ops->get_cr(ctxt, 0) | X86_CR0_TS); + ops->set_segment(ctxt, tss_selector, &next_tss_desc, 0, VCPU_SREG_TR); + + if (has_error_code) { + ctxt->op_bytes = ctxt->ad_bytes = (next_tss_desc.type & 8) ? 4 : 2; + ctxt->lock_prefix = 0; + ctxt->src.val = (unsigned long) error_code; + ret = em_push(ctxt); + } + + return ret; +} +",0,"static int emulator_do_task_switch(struct x86_emulate_ctxt *ctxt, + u16 tss_selector, int idt_index, int reason, + bool has_error_code, u32 error_code) +{ + const struct x86_emulate_ops *ops = ctxt->ops; + struct desc_struct curr_tss_desc, next_tss_desc; + int ret; + u16 old_tss_sel = get_segment_selector(ctxt, VCPU_SREG_TR); + ulong old_tss_base = + ops->get_cached_segment_base(ctxt, VCPU_SREG_TR); + u32 desc_limit; + ulong desc_addr; + + /* FIXME: old_tss_base == ~0 ? */ + + ret = read_segment_descriptor(ctxt, tss_selector, &next_tss_desc, &desc_addr); + if (ret != X86EMUL_CONTINUE) + return ret; + ret = read_segment_descriptor(ctxt, old_tss_sel, &curr_tss_desc, &desc_addr); + if (ret != X86EMUL_CONTINUE) + return ret; + + /* FIXME: check that next_tss_desc is tss */ + + /* + * Check privileges. The three cases are task switch caused by... + * + * 1. jmp/call/int to task gate: Check against DPL of the task gate + * 2. Exception/IRQ/iret: No check is performed + * 3. jmp/call to TSS: Check against DPL of the TSS + */ + if (reason == TASK_SWITCH_GATE) { + if (idt_index != -1) { + /* Software interrupts */ + struct desc_struct task_gate_desc; + int dpl; + + ret = read_interrupt_descriptor(ctxt, idt_index, + &task_gate_desc); + if (ret != X86EMUL_CONTINUE) + return ret; + + dpl = task_gate_desc.dpl; + if ((tss_selector & 3) > dpl || ops->cpl(ctxt) > dpl) + return emulate_gp(ctxt, (idt_index << 3) | 0x2); + } + } else if (reason != TASK_SWITCH_IRET) { + int dpl = next_tss_desc.dpl; + if ((tss_selector & 3) > dpl || ops->cpl(ctxt) > dpl) + return emulate_gp(ctxt, tss_selector); + } + + + desc_limit = desc_limit_scaled(&next_tss_desc); + if (!next_tss_desc.p || + ((desc_limit < 0x67 && (next_tss_desc.type & 8)) || + desc_limit < 0x2b)) { + return emulate_ts(ctxt, tss_selector & 0xfffc); + } + + if (reason == TASK_SWITCH_IRET || reason == TASK_SWITCH_JMP) { + curr_tss_desc.type &= ~(1 << 1); /* clear busy flag */ + write_segment_descriptor(ctxt, old_tss_sel, &curr_tss_desc); + } + + if (reason == TASK_SWITCH_IRET) + ctxt->eflags = ctxt->eflags & ~X86_EFLAGS_NT; + + /* set back link to prev task only if NT bit is set in eflags + note that old_tss_sel is not used after this point */ + if (reason != TASK_SWITCH_CALL && reason != TASK_SWITCH_GATE) + old_tss_sel = 0xffff; + + if (next_tss_desc.type & 8) + ret = task_switch_32(ctxt, tss_selector, old_tss_sel, + old_tss_base, &next_tss_desc); + else + ret = task_switch_16(ctxt, tss_selector, old_tss_sel, + old_tss_base, &next_tss_desc); + if (ret != X86EMUL_CONTINUE) + return ret; + + if (reason == TASK_SWITCH_CALL || reason == TASK_SWITCH_GATE) + ctxt->eflags = ctxt->eflags | X86_EFLAGS_NT; + + if (reason != TASK_SWITCH_IRET) { + next_tss_desc.type |= (1 << 1); /* set busy flag */ + write_segment_descriptor(ctxt, tss_selector, &next_tss_desc); + } + + ops->set_cr(ctxt, 0, ops->get_cr(ctxt, 0) | X86_CR0_TS); + ops->set_segment(ctxt, tss_selector, &next_tss_desc, 0, VCPU_SREG_TR); + + if (has_error_code) { + ctxt->op_bytes = ctxt->ad_bytes = (next_tss_desc.type & 8) ? 4 : 2; + ctxt->lock_prefix = 0; + ctxt->src.val = (unsigned long) error_code; + ret = em_push(ctxt); + } + + return ret; +} +","@@ -4580,10 +4580,10 @@ int x86_decode_insn(struct x86_emulate_ctxt *ctxt, void *insn, int insn_len) + /* Decode and fetch the destination operand: register or memory. */ + rc = decode_operand(ctxt, &ctxt->dst, (ctxt->d >> DstShift) & OpMask); + +-done: + if (ctxt->rip_relative) + ctxt->memopp->addr.mem.ea += ctxt->_eip; + ++done: + return (rc != X86EMUL_CONTINUE) ? EMULATION_FAILED : EMULATION_OK; + } + ",1029,1360,2048 +18188,"static void WriteTo8BimProfile(Image *image,const char *name, + const StringInfo *profile) +{ + + const unsigned char + *datum, + *q; + + register const unsigned char + *p; + + size_t + length; + + StringInfo + *profile_8bim; + + ssize_t + count; + + unsigned char + length_byte; + + unsigned int + value; + + unsigned short + id, + profile_id; + + if (LocaleCompare(name,""icc"") == 0) + profile_id=0x040f; + else + if (LocaleCompare(name,""iptc"") == 0) + profile_id=0x0404; + else + if (LocaleCompare(name,""xmp"") == 0) + profile_id=0x0424; + else + return; + profile_8bim=(StringInfo *) GetValueFromSplayTree((SplayTreeInfo *) + image->profiles,""8bim""); + if (profile_8bim == (StringInfo *) NULL) + return; + datum=GetStringInfoDatum(profile_8bim); + length=GetStringInfoLength(profile_8bim); + for (p=datum; p < (datum+length-16); ) + { + q=p; + if (LocaleNCompare((char *) p,""8BIM"",4) != 0) + break; + p+=4; + p=ReadResourceShort(p,&id); + p=ReadResourceByte(p,&length_byte); + p+=length_byte; + if (((length_byte+1) & 0x01) != 0) + p++; + if (p > (datum+length-4)) + break; + p=ReadResourceLong(p,&value); + count=(ssize_t) value; + if ((count & 0x01) != 0) + count++; + if ((p > (datum+length-count)) || (count > (ssize_t) length)) + break; + if (id != profile_id) + p+=count; + else + { + size_t + extent, + offset; + + ssize_t + extract_extent; + + StringInfo + *extract_profile; + + extract_extent=0; + extent=(datum+length)-(p+count); + if (profile == (StringInfo *) NULL) + { + offset=(q-datum); + extract_profile=AcquireStringInfo(offset+extent); + (void) CopyMagickMemory(extract_profile->datum,datum,offset); + } + else + { + offset=(p-datum); + extract_extent=profile->length; + if ((extract_extent & 0x01) != 0) + extract_extent++; + extract_profile=AcquireStringInfo(offset+extract_extent+extent); + (void) CopyMagickMemory(extract_profile->datum,datum,offset-4); + (void) WriteResourceLong(extract_profile->datum+offset-4, + (unsigned int) profile->length); + (void) CopyMagickMemory(extract_profile->datum+offset, + profile->datum,profile->length); + } + (void) CopyMagickMemory(extract_profile->datum+offset+extract_extent, + p+count,extent); + (void) AddValueToSplayTree((SplayTreeInfo *) image->profiles, + ConstantString(""8bim""),CloneStringInfo(extract_profile)); + extract_profile=DestroyStringInfo(extract_profile); + break; + } + } +} +",1,"static void WriteTo8BimProfile(Image *image,const char *name, + const StringInfo *profile) +{ + + const unsigned char + *datum, + *q; + + register const unsigned char + *p; + + size_t + length; + + StringInfo + *profile_8bim; + + ssize_t + count; + + unsigned char + length_byte; + + unsigned int + value; + + unsigned short + id, + profile_id; + + if (LocaleCompare(name,""icc"") == 0) + profile_id=0x040f; + else + if (LocaleCompare(name,""iptc"") == 0) + profile_id=0x0404; + else + if (LocaleCompare(name,""xmp"") == 0) + profile_id=0x0424; + else + return; + profile_8bim=(StringInfo *) GetValueFromSplayTree((SplayTreeInfo *) + image->profiles,""8bim""); + if (profile_8bim == (StringInfo *) NULL) + return; + datum=GetStringInfoDatum(profile_8bim); + length=GetStringInfoLength(profile_8bim); + for (p=datum; p < (datum+length-16); ) + { + q=p; + if (LocaleNCompare((char *) p,""8BIM"",4) != 0) + break; + p+=4; + p=ReadResourceShort(p,&id); + p=ReadResourceByte(p,&length_byte); + p+=length_byte; + if (((length_byte+1) & 0x01) != 0) + p++; + if (p > (datum+length-4)) + break; + p=ReadResourceLong(p,&value); + count=(ssize_t) value; + if ((count & 0x01) != 0) + count++; + if ((count < 0) || (p > (datum+length-count)) || + (count > (ssize_t) length)) + break; + if (id != profile_id) + p+=count; + else + { + size_t + extent, + offset; + + ssize_t + extract_extent; + + StringInfo + *extract_profile; + + extract_extent=0; + extent=(datum+length)-(p+count); + if (profile == (StringInfo *) NULL) + { + offset=(q-datum); + extract_profile=AcquireStringInfo(offset+extent); + (void) CopyMagickMemory(extract_profile->datum,datum,offset); + } + else + { + offset=(p-datum); + extract_extent=profile->length; + if ((extract_extent & 0x01) != 0) + extract_extent++; + extract_profile=AcquireStringInfo(offset+extract_extent+extent); + (void) CopyMagickMemory(extract_profile->datum,datum,offset-4); + (void) WriteResourceLong(extract_profile->datum+offset-4, + (unsigned int) profile->length); + (void) CopyMagickMemory(extract_profile->datum+offset, + profile->datum,profile->length); + } + (void) CopyMagickMemory(extract_profile->datum+offset+extract_extent, + p+count,extent); + (void) AddValueToSplayTree((SplayTreeInfo *) image->profiles, + ConstantString(""8bim""),CloneStringInfo(extract_profile)); + extract_profile=DestroyStringInfo(extract_profile); + break; + } + } +} +","@@ -1444,7 +1444,8 @@ static void WriteTo8BimProfile(Image *image,const char *name, + count=(ssize_t) value; + if ((count & 0x01) != 0) + count++; +- if ((p > (datum+length-count)) || (count > (ssize_t) length)) ++ if ((count < 0) || (p > (datum+length-count)) || ++ (count > (ssize_t) length)) + break; + if (id != profile_id) + p+=count;",754,1085,2048 +18249,"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 = READ_ONCE(table->private); /* Address dependency. */ + cpu = smp_processor_id(); + 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.state = state; + 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); + + if (verdict == XT_CONTINUE) { + /* Target might have changed stuff. */ + arp = arp_hdr(skb); + 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; +} +",1,"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 = READ_ONCE(table->private); /* Address dependency. */ + cpu = smp_processor_id(); + 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.state = state; + 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)) { + if (unlikely(stackidx >= private->stacksize)) { + verdict = NF_DROP; + break; + } + 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); + + if (verdict == XT_CONTINUE) { + /* Target might have changed stuff. */ + arp = arp_hdr(skb); + 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; +} +","@@ -252,6 +252,10 @@ unsigned int arpt_do_table(struct sk_buff *skb, + } + if (table_base + v + != arpt_next_entry(e)) { ++ if (unlikely(stackidx >= private->stacksize)) { ++ verdict = NF_DROP; ++ break; ++ } + jumpstack[stackidx++] = e; + } + ",742,1073,2048 +2616,"static int fpux_emu(struct pt_regs *xcp, struct mips_fpu_struct *ctx, + mips_instruction ir, void *__user *fault_addr) +{ + unsigned rcsr = 0; /* resulting csr */ + + MIPS_FPU_EMU_INC_STATS(cp1xops); + + switch (MIPSInst_FMA_FFMT(ir)) { + case s_fmt:{ /* 0 */ + + ieee754sp(*handler) (ieee754sp, ieee754sp, ieee754sp); + ieee754sp fd, fr, fs, ft; + u32 __user *va; + u32 val; + + switch (MIPSInst_FUNC(ir)) { + case lwxc1_op: + va = (void __user *) (xcp->regs[MIPSInst_FR(ir)] + + xcp->regs[MIPSInst_FT(ir)]); + + MIPS_FPU_EMU_INC_STATS(loads); + if (!access_ok(VERIFY_READ, va, sizeof(u32))) { + MIPS_FPU_EMU_INC_STATS(errors); + *fault_addr = va; + return SIGBUS; + } + if (__get_user(val, va)) { + MIPS_FPU_EMU_INC_STATS(errors); + *fault_addr = va; + return SIGSEGV; + } + SITOREG(val, MIPSInst_FD(ir)); + break; + + case swxc1_op: + va = (void __user *) (xcp->regs[MIPSInst_FR(ir)] + + xcp->regs[MIPSInst_FT(ir)]); + + MIPS_FPU_EMU_INC_STATS(stores); + + SIFROMREG(val, MIPSInst_FS(ir)); + if (!access_ok(VERIFY_WRITE, va, sizeof(u32))) { + MIPS_FPU_EMU_INC_STATS(errors); + *fault_addr = va; + return SIGBUS; + } + if (put_user(val, va)) { + MIPS_FPU_EMU_INC_STATS(errors); + *fault_addr = va; + return SIGSEGV; + } + break; + + case madd_s_op: + handler = fpemu_sp_madd; + goto scoptop; + case msub_s_op: + handler = fpemu_sp_msub; + goto scoptop; + case nmadd_s_op: + handler = fpemu_sp_nmadd; + goto scoptop; + case nmsub_s_op: + handler = fpemu_sp_nmsub; + goto scoptop; + + scoptop: + SPFROMREG(fr, MIPSInst_FR(ir)); + SPFROMREG(fs, MIPSInst_FS(ir)); + SPFROMREG(ft, MIPSInst_FT(ir)); + fd = (*handler) (fr, fs, ft); + SPTOREG(fd, MIPSInst_FD(ir)); + + copcsr: + if (ieee754_cxtest(IEEE754_INEXACT)) + rcsr |= FPU_CSR_INE_X | FPU_CSR_INE_S; + if (ieee754_cxtest(IEEE754_UNDERFLOW)) + rcsr |= FPU_CSR_UDF_X | FPU_CSR_UDF_S; + if (ieee754_cxtest(IEEE754_OVERFLOW)) + rcsr |= FPU_CSR_OVF_X | FPU_CSR_OVF_S; + if (ieee754_cxtest(IEEE754_INVALID_OPERATION)) + rcsr |= FPU_CSR_INV_X | FPU_CSR_INV_S; + + ctx->fcr31 = (ctx->fcr31 & ~FPU_CSR_ALL_X) | rcsr; + if ((ctx->fcr31 >> 5) & ctx->fcr31 & FPU_CSR_ALL_E) { + /*printk (""SIGFPE: fpu csr = %08x\n"", + ctx->fcr31); */ + return SIGFPE; + } + + break; + + default: + return SIGILL; + } + break; + } + + case d_fmt:{ /* 1 */ + ieee754dp(*handler) (ieee754dp, ieee754dp, ieee754dp); + ieee754dp fd, fr, fs, ft; + u64 __user *va; + u64 val; + + switch (MIPSInst_FUNC(ir)) { + case ldxc1_op: + va = (void __user *) (xcp->regs[MIPSInst_FR(ir)] + + xcp->regs[MIPSInst_FT(ir)]); + + MIPS_FPU_EMU_INC_STATS(loads); + if (!access_ok(VERIFY_READ, va, sizeof(u64))) { + MIPS_FPU_EMU_INC_STATS(errors); + *fault_addr = va; + return SIGBUS; + } + if (__get_user(val, va)) { + MIPS_FPU_EMU_INC_STATS(errors); + *fault_addr = va; + return SIGSEGV; + } + DITOREG(val, MIPSInst_FD(ir)); + break; + + case sdxc1_op: + va = (void __user *) (xcp->regs[MIPSInst_FR(ir)] + + xcp->regs[MIPSInst_FT(ir)]); + + MIPS_FPU_EMU_INC_STATS(stores); + DIFROMREG(val, MIPSInst_FS(ir)); + if (!access_ok(VERIFY_WRITE, va, sizeof(u64))) { + MIPS_FPU_EMU_INC_STATS(errors); + *fault_addr = va; + return SIGBUS; + } + if (__put_user(val, va)) { + MIPS_FPU_EMU_INC_STATS(errors); + *fault_addr = va; + return SIGSEGV; + } + break; + + case madd_d_op: + handler = fpemu_dp_madd; + goto dcoptop; + case msub_d_op: + handler = fpemu_dp_msub; + goto dcoptop; + case nmadd_d_op: + handler = fpemu_dp_nmadd; + goto dcoptop; + case nmsub_d_op: + handler = fpemu_dp_nmsub; + goto dcoptop; + + dcoptop: + DPFROMREG(fr, MIPSInst_FR(ir)); + DPFROMREG(fs, MIPSInst_FS(ir)); + DPFROMREG(ft, MIPSInst_FT(ir)); + fd = (*handler) (fr, fs, ft); + DPTOREG(fd, MIPSInst_FD(ir)); + goto copcsr; + + default: + return SIGILL; + } + break; + } + + case 0x7: /* 7 */ + if (MIPSInst_FUNC(ir) != pfetch_op) { + return SIGILL; + } + /* ignore prefx operation */ + break; + + default: + return SIGILL; + } + + return 0; +} +",0,"static int fpux_emu(struct pt_regs *xcp, struct mips_fpu_struct *ctx, + mips_instruction ir, void *__user *fault_addr) +{ + unsigned rcsr = 0; /* resulting csr */ + + MIPS_FPU_EMU_INC_STATS(cp1xops); + + switch (MIPSInst_FMA_FFMT(ir)) { + case s_fmt:{ /* 0 */ + + ieee754sp(*handler) (ieee754sp, ieee754sp, ieee754sp); + ieee754sp fd, fr, fs, ft; + u32 __user *va; + u32 val; + + switch (MIPSInst_FUNC(ir)) { + case lwxc1_op: + va = (void __user *) (xcp->regs[MIPSInst_FR(ir)] + + xcp->regs[MIPSInst_FT(ir)]); + + MIPS_FPU_EMU_INC_STATS(loads); + if (!access_ok(VERIFY_READ, va, sizeof(u32))) { + MIPS_FPU_EMU_INC_STATS(errors); + *fault_addr = va; + return SIGBUS; + } + if (__get_user(val, va)) { + MIPS_FPU_EMU_INC_STATS(errors); + *fault_addr = va; + return SIGSEGV; + } + SITOREG(val, MIPSInst_FD(ir)); + break; + + case swxc1_op: + va = (void __user *) (xcp->regs[MIPSInst_FR(ir)] + + xcp->regs[MIPSInst_FT(ir)]); + + MIPS_FPU_EMU_INC_STATS(stores); + + SIFROMREG(val, MIPSInst_FS(ir)); + if (!access_ok(VERIFY_WRITE, va, sizeof(u32))) { + MIPS_FPU_EMU_INC_STATS(errors); + *fault_addr = va; + return SIGBUS; + } + if (put_user(val, va)) { + MIPS_FPU_EMU_INC_STATS(errors); + *fault_addr = va; + return SIGSEGV; + } + break; + + case madd_s_op: + handler = fpemu_sp_madd; + goto scoptop; + case msub_s_op: + handler = fpemu_sp_msub; + goto scoptop; + case nmadd_s_op: + handler = fpemu_sp_nmadd; + goto scoptop; + case nmsub_s_op: + handler = fpemu_sp_nmsub; + goto scoptop; + + scoptop: + SPFROMREG(fr, MIPSInst_FR(ir)); + SPFROMREG(fs, MIPSInst_FS(ir)); + SPFROMREG(ft, MIPSInst_FT(ir)); + fd = (*handler) (fr, fs, ft); + SPTOREG(fd, MIPSInst_FD(ir)); + + copcsr: + if (ieee754_cxtest(IEEE754_INEXACT)) + rcsr |= FPU_CSR_INE_X | FPU_CSR_INE_S; + if (ieee754_cxtest(IEEE754_UNDERFLOW)) + rcsr |= FPU_CSR_UDF_X | FPU_CSR_UDF_S; + if (ieee754_cxtest(IEEE754_OVERFLOW)) + rcsr |= FPU_CSR_OVF_X | FPU_CSR_OVF_S; + if (ieee754_cxtest(IEEE754_INVALID_OPERATION)) + rcsr |= FPU_CSR_INV_X | FPU_CSR_INV_S; + + ctx->fcr31 = (ctx->fcr31 & ~FPU_CSR_ALL_X) | rcsr; + if ((ctx->fcr31 >> 5) & ctx->fcr31 & FPU_CSR_ALL_E) { + /*printk (""SIGFPE: fpu csr = %08x\n"", + ctx->fcr31); */ + return SIGFPE; + } + + break; + + default: + return SIGILL; + } + break; + } + + case d_fmt:{ /* 1 */ + ieee754dp(*handler) (ieee754dp, ieee754dp, ieee754dp); + ieee754dp fd, fr, fs, ft; + u64 __user *va; + u64 val; + + switch (MIPSInst_FUNC(ir)) { + case ldxc1_op: + va = (void __user *) (xcp->regs[MIPSInst_FR(ir)] + + xcp->regs[MIPSInst_FT(ir)]); + + MIPS_FPU_EMU_INC_STATS(loads); + if (!access_ok(VERIFY_READ, va, sizeof(u64))) { + MIPS_FPU_EMU_INC_STATS(errors); + *fault_addr = va; + return SIGBUS; + } + if (__get_user(val, va)) { + MIPS_FPU_EMU_INC_STATS(errors); + *fault_addr = va; + return SIGSEGV; + } + DITOREG(val, MIPSInst_FD(ir)); + break; + + case sdxc1_op: + va = (void __user *) (xcp->regs[MIPSInst_FR(ir)] + + xcp->regs[MIPSInst_FT(ir)]); + + MIPS_FPU_EMU_INC_STATS(stores); + DIFROMREG(val, MIPSInst_FS(ir)); + if (!access_ok(VERIFY_WRITE, va, sizeof(u64))) { + MIPS_FPU_EMU_INC_STATS(errors); + *fault_addr = va; + return SIGBUS; + } + if (__put_user(val, va)) { + MIPS_FPU_EMU_INC_STATS(errors); + *fault_addr = va; + return SIGSEGV; + } + break; + + case madd_d_op: + handler = fpemu_dp_madd; + goto dcoptop; + case msub_d_op: + handler = fpemu_dp_msub; + goto dcoptop; + case nmadd_d_op: + handler = fpemu_dp_nmadd; + goto dcoptop; + case nmsub_d_op: + handler = fpemu_dp_nmsub; + goto dcoptop; + + dcoptop: + DPFROMREG(fr, MIPSInst_FR(ir)); + DPFROMREG(fs, MIPSInst_FS(ir)); + DPFROMREG(ft, MIPSInst_FT(ir)); + fd = (*handler) (fr, fs, ft); + DPTOREG(fd, MIPSInst_FD(ir)); + goto copcsr; + + default: + return SIGILL; + } + break; + } + + case 0x7: /* 7 */ + if (MIPSInst_FUNC(ir) != pfetch_op) { + return SIGILL; + } + /* ignore prefx operation */ + break; + + default: + return SIGILL; + } + + return 0; +} +","@@ -272,8 +272,7 @@ static int cop1Emulate(struct pt_regs *xcp, struct mips_fpu_struct *ctx, + } + + emul: +- perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, +- 1, 0, xcp, 0); ++ perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, xcp, 0); + MIPS_FPU_EMU_INC_STATS(emulated); + switch (MIPSInst_OPCODE(ir)) { + case ldc1_op:{",1476,1807,2048 +17842,"XpmCreateDataFromXpmImage( + char ***data_return, + XpmImage *image, + XpmInfo *info) +{ + /* calculation variables */ + int ErrorStatus; + char buf[BUFSIZ]; + char **header = NULL, **data, **sptr, **sptr2, *s; + unsigned int header_size, header_nlines; + unsigned int data_size, data_nlines; + unsigned int extensions = 0, ext_size = 0, ext_nlines = 0; + unsigned int offset, l, n; + + *data_return = NULL; + + extensions = info && (info->valuemask & XpmExtensions) + && info->nextensions; + + /* compute the number of extensions lines and size */ + if (extensions) + CountExtensions(info->extensions, info->nextensions, + &ext_size, &ext_nlines); + + /* + * alloc a temporary array of char pointer for the header section which + */ + header_nlines = 1 + image->ncolors; /* this may wrap and/or become 0 */ + + /* 2nd check superfluous if we do not need header_nlines any further */ + if(header_nlines <= image->ncolors || + header_nlines >= UINT_MAX / sizeof(char *)) + return(XpmNoMemory); + + header_size = sizeof(char *) * header_nlines; + if (header_size >= UINT_MAX / sizeof(char *)) + return (XpmNoMemory); + header = (char **) XpmCalloc(header_size, sizeof(char *)); /* can we trust image->ncolors */ + if (!header) + return (XpmNoMemory); + + /* print the hints line */ + s = buf; +#ifndef VOID_SPRINTF + s += +#endif + sprintf(s, ""%d %d %d %d"", image->width, image->height, + image->ncolors, image->cpp); +#ifdef VOID_SPRINTF + s += strlen(s); +#endif + + if (info && (info->valuemask & XpmHotspot)) { +#ifndef VOID_SPRINTF + s += +#endif + sprintf(s, "" %d %d"", info->x_hotspot, info->y_hotspot); +#ifdef VOID_SPRINTF + s += strlen(s); +#endif + } + if (extensions) { + strcpy(s, "" XPMEXT""); + s += 7; + } + l = s - buf + 1; + *header = (char *) XpmMalloc(l); + if (!*header) + RETURN(XpmNoMemory); + header_size += l; + strcpy(*header, buf); + + /* print colors */ + ErrorStatus = CreateColors(header + 1, &header_size, + image->colorTable, image->ncolors, image->cpp); + + if (ErrorStatus != XpmSuccess) + RETURN(ErrorStatus); + + /* now we know the size needed, alloc the data and copy the header lines */ + offset = image->width * image->cpp + 1; + + if(offset <= image->width || offset <= image->cpp) + if(offset <= image->width || offset <= image->cpp) + RETURN(XpmNoMemory); + + if( (image->height + ext_nlines) >= UINT_MAX / sizeof(char *)) + RETURN(XpmNoMemory); + data_size = (image->height + ext_nlines) * sizeof(char *); + + RETURN(XpmNoMemory); + data_size += image->height * offset; + RETURN(XpmNoMemory); + data_size += image->height * offset; + + if( (header_size + ext_size) >= (UINT_MAX - data_size) ) + RETURN(XpmNoMemory); + data_size += header_size + ext_size; + + + data_nlines = header_nlines + image->height + ext_nlines; + *data = (char *) (data + data_nlines); + + /* can header have less elements then n suggests? */ + n = image->ncolors; + for (l = 0, sptr = data, sptr2 = header; l <= n && sptr && sptr2; l++, sptr++, sptr2++) { + strcpy(*sptr, *sptr2); + *(sptr + 1) = *sptr + strlen(*sptr2) + 1; + } + + /* print pixels */ + data[header_nlines] = (char *) data + header_size + + (image->height + ext_nlines) * sizeof(char *); + + CreatePixels(data + header_nlines, data_size-header_nlines, image->width, image->height, + image->cpp, image->data, image->colorTable); + + /* print extensions */ + if (extensions) + CreateExtensions(data + header_nlines + image->height - 1, + data_size - header_nlines - image->height + 1, offset, + info->extensions, info->nextensions, + ext_nlines); + + *data_return = data; + ErrorStatus = XpmSuccess; + +/* exit point, free only locally allocated variables */ +exit: + if (header) { + for (l = 0; l < header_nlines; l++) + if (header[l]) + XpmFree(header[l]); + XpmFree(header); + } + return(ErrorStatus); +} +",1,"XpmCreateDataFromXpmImage( + char ***data_return, + XpmImage *image, + XpmInfo *info) +{ + /* calculation variables */ + int ErrorStatus; + char buf[BUFSIZ]; + char **header = NULL, **data, **sptr, **sptr2, *s; + unsigned int header_size, header_nlines; + unsigned int data_size, data_nlines; + unsigned int extensions = 0, ext_size = 0, ext_nlines = 0; + unsigned int offset, l, n; + + *data_return = NULL; + + extensions = info && (info->valuemask & XpmExtensions) + && info->nextensions; + + /* compute the number of extensions lines and size */ + if (extensions) + if (CountExtensions(info->extensions, info->nextensions, + &ext_size, &ext_nlines)) + return(XpmNoMemory); + + /* + * alloc a temporary array of char pointer for the header section which + */ + header_nlines = 1 + image->ncolors; /* this may wrap and/or become 0 */ + + /* 2nd check superfluous if we do not need header_nlines any further */ + if(header_nlines <= image->ncolors || + header_nlines >= UINT_MAX / sizeof(char *)) + return(XpmNoMemory); + + header_size = sizeof(char *) * header_nlines; + if (header_size >= UINT_MAX / sizeof(char *)) + return (XpmNoMemory); + header = (char **) XpmCalloc(header_size, sizeof(char *)); /* can we trust image->ncolors */ + if (!header) + return (XpmNoMemory); + + /* print the hints line */ + s = buf; +#ifndef VOID_SPRINTF + s += +#endif + sprintf(s, ""%d %d %d %d"", image->width, image->height, + image->ncolors, image->cpp); +#ifdef VOID_SPRINTF + s += strlen(s); +#endif + + if (info && (info->valuemask & XpmHotspot)) { +#ifndef VOID_SPRINTF + s += +#endif + sprintf(s, "" %d %d"", info->x_hotspot, info->y_hotspot); +#ifdef VOID_SPRINTF + s += strlen(s); +#endif + } + if (extensions) { + strcpy(s, "" XPMEXT""); + s += 7; + } + l = s - buf + 1; + *header = (char *) XpmMalloc(l); + if (!*header) + RETURN(XpmNoMemory); + header_size += l; + strcpy(*header, buf); + + /* print colors */ + ErrorStatus = CreateColors(header + 1, &header_size, + image->colorTable, image->ncolors, image->cpp); + + if (ErrorStatus != XpmSuccess) + RETURN(ErrorStatus); + + /* now we know the size needed, alloc the data and copy the header lines */ + offset = image->width * image->cpp + 1; + + if(offset <= image->width || offset <= image->cpp) + if(offset <= image->width || offset <= image->cpp) + RETURN(XpmNoMemory); + + if (image->height > UINT_MAX - ext_nlines || + image->height + ext_nlines >= UINT_MAX / sizeof(char *)) + RETURN(XpmNoMemory); + data_size = (image->height + ext_nlines) * sizeof(char *); + + RETURN(XpmNoMemory); + data_size += image->height * offset; + RETURN(XpmNoMemory); + data_size += image->height * offset; + + if (header_size > UINT_MAX - ext_size || + header_size + ext_size >= (UINT_MAX - data_size) ) + RETURN(XpmNoMemory); + data_size += header_size + ext_size; + + + data_nlines = header_nlines + image->height + ext_nlines; + *data = (char *) (data + data_nlines); + + /* can header have less elements then n suggests? */ + n = image->ncolors; + for (l = 0, sptr = data, sptr2 = header; l <= n && sptr && sptr2; l++, sptr++, sptr2++) { + strcpy(*sptr, *sptr2); + *(sptr + 1) = *sptr + strlen(*sptr2) + 1; + } + + /* print pixels */ + data[header_nlines] = (char *) data + header_size + + (image->height + ext_nlines) * sizeof(char *); + + CreatePixels(data + header_nlines, data_size-header_nlines, image->width, image->height, + image->cpp, image->data, image->colorTable); + + /* print extensions */ + if (extensions) + CreateExtensions(data + header_nlines + image->height - 1, + data_size - header_nlines - image->height + 1, offset, + info->extensions, info->nextensions, + ext_nlines); + + *data_return = data; + ErrorStatus = XpmSuccess; + +/* exit point, free only locally allocated variables */ +exit: + if (header) { + for (l = 0; l < header_nlines; l++) + if (header[l]) + XpmFree(header[l]); + XpmFree(header); + } + return(ErrorStatus); +} +","@@ -48,7 +48,7 @@ LFUNC(CreatePixels, void, (char **dataptr, unsigned int data_size, + unsigned int height, unsigned int cpp, + unsigned int *pixels, XpmColor *colors)); + +-LFUNC(CountExtensions, void, (XpmExtension *ext, unsigned int num, ++LFUNC(CountExtensions, int, (XpmExtension *ext, unsigned int num, + unsigned int *ext_size, + unsigned int *ext_nlines)); + +@@ -122,8 +122,9 @@ XpmCreateDataFromXpmImage( + + /* compute the number of extensions lines and size */ + if (extensions) +- CountExtensions(info->extensions, info->nextensions, +- &ext_size, &ext_nlines); ++ if (CountExtensions(info->extensions, info->nextensions, ++ &ext_size, &ext_nlines)) ++ return(XpmNoMemory); + + /* + * alloc a temporary array of char pointer for the header section which +@@ -187,7 +188,8 @@ XpmCreateDataFromXpmImage( + if(offset <= image->width || offset <= image->cpp) + RETURN(XpmNoMemory); + +- if( (image->height + ext_nlines) >= UINT_MAX / sizeof(char *)) ++ if (image->height > UINT_MAX - ext_nlines || ++ image->height + ext_nlines >= UINT_MAX / sizeof(char *)) + RETURN(XpmNoMemory); + data_size = (image->height + ext_nlines) * sizeof(char *); + +@@ -196,7 +198,8 @@ XpmCreateDataFromXpmImage( + RETURN(XpmNoMemory); + data_size += image->height * offset; + +- if( (header_size + ext_size) >= (UINT_MAX - data_size) ) ++ if (header_size > UINT_MAX - ext_size || ++ header_size + ext_size >= (UINT_MAX - data_size) ) + RETURN(XpmNoMemory); + data_size += header_size + ext_size; + +@@ -343,13 +346,14 @@ CreatePixels( + *s = '\0'; + } + +-static void ++static int + CountExtensions( + XpmExtension *ext, + unsigned int num, + unsigned int *ext_size, + unsigned int *ext_nlines) + { ++ size_t len; + unsigned int x, y, a, size, nlines; + char **line; + +@@ -357,16 +361,28 @@ CountExtensions( + nlines = 0; + for (x = 0; x < num; x++, ext++) { + /* 1 for the name */ ++ if (ext->nlines == UINT_MAX || nlines > UINT_MAX - ext->nlines - 1) ++ return (1); + nlines += ext->nlines + 1; + /* 8 = 7 (for ""XPMEXT "") + 1 (for 0) */ +- size += strlen(ext->name) + 8; ++ len = strlen(ext->name) + 8; ++ if (len > UINT_MAX - size) ++ return (1); ++ size += len; + a = ext->nlines; +- for (y = 0, line = ext->lines; y < a; y++, line++) +- size += strlen(*line) + 1; ++ for (y = 0, line = ext->lines; y < a; y++, line++) { ++ len = strlen(*line) + 1; ++ if (len > UINT_MAX - size) ++ return (1); ++ size += len; ++ } + } ++ if (size > UINT_MAX - 10 || nlines > UINT_MAX - 1) ++ return (1); + /* 10 and 1 are for the ending ""XPMENDEXT"" */ + *ext_size = size + 10; + *ext_nlines = nlines + 1; ++ return (0); + } + + static void",1123,1454,2048 +7912,"int imap_msg_open(struct Context *ctx, struct Message *msg, int msgno) +{ + struct Envelope *newenv = NULL; + char buf[LONG_STRING]; + char path[PATH_MAX]; + char *pc = NULL; + unsigned int bytes; + struct Progress progressbar; + unsigned int uid; + int cacheno; + struct ImapCache *cache = NULL; + bool retried = false; + bool read; + int rc; + + /* Sam's weird courier server returns an OK response even when FETCH + * fails. Thanks Sam. */ + bool fetched = false; + int output_progress; + + struct ImapData *idata = ctx->data; + struct Header *h = ctx->hdrs[msgno]; + + msg->fp = msg_cache_get(idata, h); + if (msg->fp) + { + if (HEADER_DATA(h)->parsed) + return 0; + else + goto parsemsg; + } + + /* we still do some caching even if imap_cachedir is unset */ + /* see if we already have the message in our cache */ + cacheno = HEADER_DATA(h)->uid % IMAP_CACHE_LEN; + cache = &idata->cache[cacheno]; + + if (cache->path) + { + /* don't treat cache errors as fatal, just fall back. */ + if (cache->uid == HEADER_DATA(h)->uid && (msg->fp = fopen(cache->path, ""r""))) + return 0; + else + { + unlink(cache->path); + FREE(&cache->path); + } + } + + /* This function is called in a few places after endwin() + * e.g. mutt_pipe_message(). */ + output_progress = !isendwin(); + if (output_progress) + mutt_message(_(""Fetching message..."")); + + msg->fp = msg_cache_put(idata, h); + if (!msg->fp) + { + cache->uid = HEADER_DATA(h)->uid; + mutt_mktemp(path, sizeof(path)); + cache->path = mutt_str_strdup(path); + msg->fp = mutt_file_fopen(path, ""w+""); + if (!msg->fp) + { + FREE(&cache->path); + return -1; + } + } + + /* mark this header as currently inactive so the command handler won't + * also try to update it. HACK until all this code can be moved into the + * command handler */ + h->active = false; + + snprintf(buf, sizeof(buf), ""UID FETCH %u %s"", HEADER_DATA(h)->uid, + (mutt_bit_isset(idata->capabilities, IMAP4REV1) ? + (ImapPeek ? ""BODY.PEEK[]"" : ""BODY[]"") : + ""RFC822"")); + + imap_cmd_start(idata, buf); + do + { + rc = imap_cmd_step(idata); + if (rc != IMAP_CMD_CONTINUE) + break; + + pc = idata->buf; + pc = imap_next_word(pc); + pc = imap_next_word(pc); + + if (mutt_str_strncasecmp(""FETCH"", pc, 5) == 0) + { + while (*pc) + { + pc = imap_next_word(pc); + if (pc[0] == '(') + pc++; + if (mutt_str_strncasecmp(""UID"", pc, 3) == 0) + { + pc = imap_next_word(pc); + if (mutt_str_atoui(pc, &uid) < 0) + goto bail; + if (uid != HEADER_DATA(h)->uid) + { + mutt_error(_( + ""The message index is incorrect. Try reopening the mailbox."")); + } + } + else if ((mutt_str_strncasecmp(""RFC822"", pc, 6) == 0) || + (mutt_str_strncasecmp(""BODY[]"", pc, 6) == 0)) + { + pc = imap_next_word(pc); + if (imap_get_literal_count(pc, &bytes) < 0) + { + imap_error(""imap_msg_open()"", buf); + goto bail; + } + if (output_progress) + { + mutt_progress_init(&progressbar, _(""Fetching message...""), + MUTT_PROGRESS_SIZE, NetInc, bytes); + } + if (imap_read_literal(msg->fp, idata, bytes, + output_progress ? &progressbar : NULL) < 0) + { + goto bail; + } + /* pick up trailing line */ + rc = imap_cmd_step(idata); + if (rc != IMAP_CMD_CONTINUE) + goto bail; + pc = idata->buf; + + fetched = true; + } + /* UW-IMAP will provide a FLAGS update here if the FETCH causes a + * change (eg from \Unseen to \Seen). + * Uncommitted changes in neomutt take precedence. If we decide to + * incrementally update flags later, this won't stop us syncing */ + else if ((mutt_str_strncasecmp(""FLAGS"", pc, 5) == 0) && !h->changed) + { + pc = imap_set_flags(idata, h, pc, NULL); + if (!pc) + goto bail; + } + } + } + } while (rc == IMAP_CMD_CONTINUE); + + /* see comment before command start. */ + h->active = true; + + fflush(msg->fp); + if (ferror(msg->fp)) + { + mutt_perror(cache->path); + goto bail; + } + + if (rc != IMAP_CMD_OK) + goto bail; + + if (!fetched || !imap_code(idata->buf)) + goto bail; + + msg_cache_commit(idata, h); + +parsemsg: + /* Update the header information. Previously, we only downloaded a + * portion of the headers, those required for the main display. + */ + rewind(msg->fp); + /* It may be that the Status header indicates a message is read, but the + * IMAP server doesn't know the message has been \Seen. So we capture + * the server's notion of 'read' and if it differs from the message info + * picked up in mutt_rfc822_read_header, we mark the message (and context + * changed). Another possibility: ignore Status on IMAP? */ + read = h->read; + newenv = mutt_rfc822_read_header(msg->fp, h, 0, 0); + mutt_env_merge(h->env, &newenv); + + /* see above. We want the new status in h->read, so we unset it manually + * and let mutt_set_flag set it correctly, updating context. */ + if (read != h->read) + { + h->read = read; + mutt_set_flag(ctx, h, MUTT_NEW, read); + } + + h->lines = 0; + fgets(buf, sizeof(buf), msg->fp); + while (!feof(msg->fp)) + { + h->lines++; + fgets(buf, sizeof(buf), msg->fp); + } + + h->content->length = ftell(msg->fp) - h->content->offset; + + mutt_clear_error(); + rewind(msg->fp); + HEADER_DATA(h)->parsed = true; + + /* retry message parse if cached message is empty */ + if (!retried && ((h->lines == 0) || (h->content->length == 0))) + { + imap_cache_del(idata, h); + retried = true; + goto parsemsg; + } + + return 0; + +bail: + mutt_file_fclose(&msg->fp); + imap_cache_del(idata, h); + if (cache->path) + { + unlink(cache->path); + FREE(&cache->path); + } + + return -1; +} +",0,"int imap_msg_open(struct Context *ctx, struct Message *msg, int msgno) +{ + struct Envelope *newenv = NULL; + char buf[LONG_STRING]; + char path[PATH_MAX]; + char *pc = NULL; + unsigned int bytes; + struct Progress progressbar; + unsigned int uid; + int cacheno; + struct ImapCache *cache = NULL; + bool retried = false; + bool read; + int rc; + + /* Sam's weird courier server returns an OK response even when FETCH + * fails. Thanks Sam. */ + bool fetched = false; + int output_progress; + + struct ImapData *idata = ctx->data; + struct Header *h = ctx->hdrs[msgno]; + + msg->fp = msg_cache_get(idata, h); + if (msg->fp) + { + if (HEADER_DATA(h)->parsed) + return 0; + else + goto parsemsg; + } + + /* we still do some caching even if imap_cachedir is unset */ + /* see if we already have the message in our cache */ + cacheno = HEADER_DATA(h)->uid % IMAP_CACHE_LEN; + cache = &idata->cache[cacheno]; + + if (cache->path) + { + /* don't treat cache errors as fatal, just fall back. */ + if (cache->uid == HEADER_DATA(h)->uid && (msg->fp = fopen(cache->path, ""r""))) + return 0; + else + { + unlink(cache->path); + FREE(&cache->path); + } + } + + /* This function is called in a few places after endwin() + * e.g. mutt_pipe_message(). */ + output_progress = !isendwin(); + if (output_progress) + mutt_message(_(""Fetching message..."")); + + msg->fp = msg_cache_put(idata, h); + if (!msg->fp) + { + cache->uid = HEADER_DATA(h)->uid; + mutt_mktemp(path, sizeof(path)); + cache->path = mutt_str_strdup(path); + msg->fp = mutt_file_fopen(path, ""w+""); + if (!msg->fp) + { + FREE(&cache->path); + return -1; + } + } + + /* mark this header as currently inactive so the command handler won't + * also try to update it. HACK until all this code can be moved into the + * command handler */ + h->active = false; + + snprintf(buf, sizeof(buf), ""UID FETCH %u %s"", HEADER_DATA(h)->uid, + (mutt_bit_isset(idata->capabilities, IMAP4REV1) ? + (ImapPeek ? ""BODY.PEEK[]"" : ""BODY[]"") : + ""RFC822"")); + + imap_cmd_start(idata, buf); + do + { + rc = imap_cmd_step(idata); + if (rc != IMAP_CMD_CONTINUE) + break; + + pc = idata->buf; + pc = imap_next_word(pc); + pc = imap_next_word(pc); + + if (mutt_str_strncasecmp(""FETCH"", pc, 5) == 0) + { + while (*pc) + { + pc = imap_next_word(pc); + if (pc[0] == '(') + pc++; + if (mutt_str_strncasecmp(""UID"", pc, 3) == 0) + { + pc = imap_next_word(pc); + if (mutt_str_atoui(pc, &uid) < 0) + goto bail; + if (uid != HEADER_DATA(h)->uid) + { + mutt_error(_( + ""The message index is incorrect. Try reopening the mailbox."")); + } + } + else if ((mutt_str_strncasecmp(""RFC822"", pc, 6) == 0) || + (mutt_str_strncasecmp(""BODY[]"", pc, 6) == 0)) + { + pc = imap_next_word(pc); + if (imap_get_literal_count(pc, &bytes) < 0) + { + imap_error(""imap_msg_open()"", buf); + goto bail; + } + if (output_progress) + { + mutt_progress_init(&progressbar, _(""Fetching message...""), + MUTT_PROGRESS_SIZE, NetInc, bytes); + } + if (imap_read_literal(msg->fp, idata, bytes, + output_progress ? &progressbar : NULL) < 0) + { + goto bail; + } + /* pick up trailing line */ + rc = imap_cmd_step(idata); + if (rc != IMAP_CMD_CONTINUE) + goto bail; + pc = idata->buf; + + fetched = true; + } + /* UW-IMAP will provide a FLAGS update here if the FETCH causes a + * change (eg from \Unseen to \Seen). + * Uncommitted changes in neomutt take precedence. If we decide to + * incrementally update flags later, this won't stop us syncing */ + else if ((mutt_str_strncasecmp(""FLAGS"", pc, 5) == 0) && !h->changed) + { + pc = imap_set_flags(idata, h, pc, NULL); + if (!pc) + goto bail; + } + } + } + } while (rc == IMAP_CMD_CONTINUE); + + /* see comment before command start. */ + h->active = true; + + fflush(msg->fp); + if (ferror(msg->fp)) + { + mutt_perror(cache->path); + goto bail; + } + + if (rc != IMAP_CMD_OK) + goto bail; + + if (!fetched || !imap_code(idata->buf)) + goto bail; + + msg_cache_commit(idata, h); + +parsemsg: + /* Update the header information. Previously, we only downloaded a + * portion of the headers, those required for the main display. + */ + rewind(msg->fp); + /* It may be that the Status header indicates a message is read, but the + * IMAP server doesn't know the message has been \Seen. So we capture + * the server's notion of 'read' and if it differs from the message info + * picked up in mutt_rfc822_read_header, we mark the message (and context + * changed). Another possibility: ignore Status on IMAP? */ + read = h->read; + newenv = mutt_rfc822_read_header(msg->fp, h, 0, 0); + mutt_env_merge(h->env, &newenv); + + /* see above. We want the new status in h->read, so we unset it manually + * and let mutt_set_flag set it correctly, updating context. */ + if (read != h->read) + { + h->read = read; + mutt_set_flag(ctx, h, MUTT_NEW, read); + } + + h->lines = 0; + fgets(buf, sizeof(buf), msg->fp); + while (!feof(msg->fp)) + { + h->lines++; + fgets(buf, sizeof(buf), msg->fp); + } + + h->content->length = ftell(msg->fp) - h->content->offset; + + mutt_clear_error(); + rewind(msg->fp); + HEADER_DATA(h)->parsed = true; + + /* retry message parse if cached message is empty */ + if (!retried && ((h->lines == 0) || (h->content->length == 0))) + { + imap_cache_del(idata, h); + retried = true; + goto parsemsg; + } + + return 0; + +bail: + mutt_file_fclose(&msg->fp); + imap_cache_del(idata, h); + if (cache->path) + { + unlink(cache->path); + FREE(&cache->path); + } + + return -1; +} +","@@ -330,7 +330,7 @@ static int msg_parse_fetch(struct ImapHeader *h, char *s) + } + s++; + ptmp = tmp; +- while (*s && *s != '\""') ++ while (*s && (*s != '\""') && (ptmp != (tmp + sizeof(tmp) - 1))) + *ptmp++ = *s++; + if (*s != '\""') + return -1; +@@ -343,7 +343,7 @@ static int msg_parse_fetch(struct ImapHeader *h, char *s) + s += 11; + SKIPWS(s); + ptmp = tmp; +- while (isdigit((unsigned char) *s)) ++ while (isdigit((unsigned char) *s) && (ptmp != (tmp + sizeof(tmp) - 1))) + *ptmp++ = *s++; + *ptmp = '\0'; + if (mutt_str_atol(tmp, &h->content_length) < 0)",1677,2008,2048 +6300,"static __init int hardware_setup(void) +{ + int r = -ENOMEM, i, msr; + + rdmsrl_safe(MSR_EFER, &host_efer); + + for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) + kvm_define_shared_msr(i, vmx_msr_index[i]); + + for (i = 0; i < VMX_BITMAP_NR; i++) { + vmx_bitmap[i] = (unsigned long *)__get_free_page(GFP_KERNEL); + if (!vmx_bitmap[i]) + goto out; + } + + vmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL); + memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE); + memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE); + + /* + * Allow direct access to the PC debug port (it is often used for I/O + * delays, but the vmexits simply slow things down). + */ + memset(vmx_io_bitmap_a, 0xff, PAGE_SIZE); + clear_bit(0x80, vmx_io_bitmap_a); + + memset(vmx_io_bitmap_b, 0xff, PAGE_SIZE); + + memset(vmx_msr_bitmap_legacy, 0xff, PAGE_SIZE); + memset(vmx_msr_bitmap_longmode, 0xff, PAGE_SIZE); + + if (setup_vmcs_config(&vmcs_config) < 0) { + r = -EIO; + goto out; + } + + if (boot_cpu_has(X86_FEATURE_NX)) + kvm_enable_efer_bits(EFER_NX); + + if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() || + !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global())) + enable_vpid = 0; + + if (!cpu_has_vmx_shadow_vmcs()) + enable_shadow_vmcs = 0; + if (enable_shadow_vmcs) + init_vmcs_shadow_fields(); + + if (!cpu_has_vmx_ept() || + !cpu_has_vmx_ept_4levels() || + !cpu_has_vmx_ept_mt_wb()) { + enable_ept = 0; + enable_unrestricted_guest = 0; + enable_ept_ad_bits = 0; + } + + if (!cpu_has_vmx_ept_ad_bits() || !enable_ept) + enable_ept_ad_bits = 0; + + if (!cpu_has_vmx_unrestricted_guest()) + enable_unrestricted_guest = 0; + + if (!cpu_has_vmx_flexpriority()) + flexpriority_enabled = 0; + + /* + * set_apic_access_page_addr() is used to reload apic access + * page upon invalidation. No need to do anything if not + * using the APIC_ACCESS_ADDR VMCS field. + */ + if (!flexpriority_enabled) + kvm_x86_ops->set_apic_access_page_addr = NULL; + + if (!cpu_has_vmx_tpr_shadow()) + kvm_x86_ops->update_cr8_intercept = NULL; + + if (enable_ept && !cpu_has_vmx_ept_2m_page()) + kvm_disable_largepages(); + + if (!cpu_has_vmx_ple()) + ple_gap = 0; + + if (!cpu_has_vmx_apicv()) { + enable_apicv = 0; + kvm_x86_ops->sync_pir_to_irr = NULL; + } + + if (cpu_has_vmx_tsc_scaling()) { + kvm_has_tsc_control = true; + kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX; + kvm_tsc_scaling_ratio_frac_bits = 48; + } + + vmx_disable_intercept_for_msr(MSR_FS_BASE, false); + vmx_disable_intercept_for_msr(MSR_GS_BASE, false); + vmx_disable_intercept_for_msr(MSR_KERNEL_GS_BASE, true); + vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_CS, false); + vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_ESP, false); + vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_EIP, false); + + memcpy(vmx_msr_bitmap_legacy_x2apic_apicv, + vmx_msr_bitmap_legacy, PAGE_SIZE); + memcpy(vmx_msr_bitmap_longmode_x2apic_apicv, + vmx_msr_bitmap_longmode, PAGE_SIZE); + memcpy(vmx_msr_bitmap_legacy_x2apic, + vmx_msr_bitmap_legacy, PAGE_SIZE); + memcpy(vmx_msr_bitmap_longmode_x2apic, + vmx_msr_bitmap_longmode, PAGE_SIZE); + + set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */ + + for (msr = 0x800; msr <= 0x8ff; msr++) { + if (msr == 0x839 /* TMCCT */) + continue; + vmx_disable_intercept_msr_x2apic(msr, MSR_TYPE_R, true); + } + + /* + * TPR reads and writes can be virtualized even if virtual interrupt + * delivery is not in use. + */ + vmx_disable_intercept_msr_x2apic(0x808, MSR_TYPE_W, true); + vmx_disable_intercept_msr_x2apic(0x808, MSR_TYPE_R | MSR_TYPE_W, false); + + /* EOI */ + vmx_disable_intercept_msr_x2apic(0x80b, MSR_TYPE_W, true); + /* SELF-IPI */ + vmx_disable_intercept_msr_x2apic(0x83f, MSR_TYPE_W, true); + + if (enable_ept) + vmx_enable_tdp(); + else + kvm_disable_tdp(); + + update_ple_window_actual_max(); + + /* + * Only enable PML when hardware supports PML feature, and both EPT + * and EPT A/D bit features are enabled -- PML depends on them to work. + */ + if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml()) + enable_pml = 0; + + if (!enable_pml) { + kvm_x86_ops->slot_enable_log_dirty = NULL; + kvm_x86_ops->slot_disable_log_dirty = NULL; + kvm_x86_ops->flush_log_dirty = NULL; + kvm_x86_ops->enable_log_dirty_pt_masked = NULL; + } + + if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) { + u64 vmx_msr; + + rdmsrl(MSR_IA32_VMX_MISC, vmx_msr); + cpu_preemption_timer_multi = + vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK; + } else { + kvm_x86_ops->set_hv_timer = NULL; + kvm_x86_ops->cancel_hv_timer = NULL; + } + + kvm_set_posted_intr_wakeup_handler(wakeup_handler); + + kvm_mce_cap_supported |= MCG_LMCE_P; + + return alloc_kvm_area(); + +out: + for (i = 0; i < VMX_BITMAP_NR; i++) + free_page((unsigned long)vmx_bitmap[i]); + + return r; +} +",0,"static __init int hardware_setup(void) +{ + int r = -ENOMEM, i, msr; + + rdmsrl_safe(MSR_EFER, &host_efer); + + for (i = 0; i < ARRAY_SIZE(vmx_msr_index); ++i) + kvm_define_shared_msr(i, vmx_msr_index[i]); + + for (i = 0; i < VMX_BITMAP_NR; i++) { + vmx_bitmap[i] = (unsigned long *)__get_free_page(GFP_KERNEL); + if (!vmx_bitmap[i]) + goto out; + } + + vmx_io_bitmap_b = (unsigned long *)__get_free_page(GFP_KERNEL); + memset(vmx_vmread_bitmap, 0xff, PAGE_SIZE); + memset(vmx_vmwrite_bitmap, 0xff, PAGE_SIZE); + + /* + * Allow direct access to the PC debug port (it is often used for I/O + * delays, but the vmexits simply slow things down). + */ + memset(vmx_io_bitmap_a, 0xff, PAGE_SIZE); + clear_bit(0x80, vmx_io_bitmap_a); + + memset(vmx_io_bitmap_b, 0xff, PAGE_SIZE); + + memset(vmx_msr_bitmap_legacy, 0xff, PAGE_SIZE); + memset(vmx_msr_bitmap_longmode, 0xff, PAGE_SIZE); + + if (setup_vmcs_config(&vmcs_config) < 0) { + r = -EIO; + goto out; + } + + if (boot_cpu_has(X86_FEATURE_NX)) + kvm_enable_efer_bits(EFER_NX); + + if (!cpu_has_vmx_vpid() || !cpu_has_vmx_invvpid() || + !(cpu_has_vmx_invvpid_single() || cpu_has_vmx_invvpid_global())) + enable_vpid = 0; + + if (!cpu_has_vmx_shadow_vmcs()) + enable_shadow_vmcs = 0; + if (enable_shadow_vmcs) + init_vmcs_shadow_fields(); + + if (!cpu_has_vmx_ept() || + !cpu_has_vmx_ept_4levels() || + !cpu_has_vmx_ept_mt_wb()) { + enable_ept = 0; + enable_unrestricted_guest = 0; + enable_ept_ad_bits = 0; + } + + if (!cpu_has_vmx_ept_ad_bits() || !enable_ept) + enable_ept_ad_bits = 0; + + if (!cpu_has_vmx_unrestricted_guest()) + enable_unrestricted_guest = 0; + + if (!cpu_has_vmx_flexpriority()) + flexpriority_enabled = 0; + + /* + * set_apic_access_page_addr() is used to reload apic access + * page upon invalidation. No need to do anything if not + * using the APIC_ACCESS_ADDR VMCS field. + */ + if (!flexpriority_enabled) + kvm_x86_ops->set_apic_access_page_addr = NULL; + + if (!cpu_has_vmx_tpr_shadow()) + kvm_x86_ops->update_cr8_intercept = NULL; + + if (enable_ept && !cpu_has_vmx_ept_2m_page()) + kvm_disable_largepages(); + + if (!cpu_has_vmx_ple()) + ple_gap = 0; + + if (!cpu_has_vmx_apicv()) { + enable_apicv = 0; + kvm_x86_ops->sync_pir_to_irr = NULL; + } + + if (cpu_has_vmx_tsc_scaling()) { + kvm_has_tsc_control = true; + kvm_max_tsc_scaling_ratio = KVM_VMX_TSC_MULTIPLIER_MAX; + kvm_tsc_scaling_ratio_frac_bits = 48; + } + + vmx_disable_intercept_for_msr(MSR_FS_BASE, false); + vmx_disable_intercept_for_msr(MSR_GS_BASE, false); + vmx_disable_intercept_for_msr(MSR_KERNEL_GS_BASE, true); + vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_CS, false); + vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_ESP, false); + vmx_disable_intercept_for_msr(MSR_IA32_SYSENTER_EIP, false); + + memcpy(vmx_msr_bitmap_legacy_x2apic_apicv, + vmx_msr_bitmap_legacy, PAGE_SIZE); + memcpy(vmx_msr_bitmap_longmode_x2apic_apicv, + vmx_msr_bitmap_longmode, PAGE_SIZE); + memcpy(vmx_msr_bitmap_legacy_x2apic, + vmx_msr_bitmap_legacy, PAGE_SIZE); + memcpy(vmx_msr_bitmap_longmode_x2apic, + vmx_msr_bitmap_longmode, PAGE_SIZE); + + set_bit(0, vmx_vpid_bitmap); /* 0 is reserved for host */ + + for (msr = 0x800; msr <= 0x8ff; msr++) { + if (msr == 0x839 /* TMCCT */) + continue; + vmx_disable_intercept_msr_x2apic(msr, MSR_TYPE_R, true); + } + + /* + * TPR reads and writes can be virtualized even if virtual interrupt + * delivery is not in use. + */ + vmx_disable_intercept_msr_x2apic(0x808, MSR_TYPE_W, true); + vmx_disable_intercept_msr_x2apic(0x808, MSR_TYPE_R | MSR_TYPE_W, false); + + /* EOI */ + vmx_disable_intercept_msr_x2apic(0x80b, MSR_TYPE_W, true); + /* SELF-IPI */ + vmx_disable_intercept_msr_x2apic(0x83f, MSR_TYPE_W, true); + + if (enable_ept) + vmx_enable_tdp(); + else + kvm_disable_tdp(); + + update_ple_window_actual_max(); + + /* + * Only enable PML when hardware supports PML feature, and both EPT + * and EPT A/D bit features are enabled -- PML depends on them to work. + */ + if (!enable_ept || !enable_ept_ad_bits || !cpu_has_vmx_pml()) + enable_pml = 0; + + if (!enable_pml) { + kvm_x86_ops->slot_enable_log_dirty = NULL; + kvm_x86_ops->slot_disable_log_dirty = NULL; + kvm_x86_ops->flush_log_dirty = NULL; + kvm_x86_ops->enable_log_dirty_pt_masked = NULL; + } + + if (cpu_has_vmx_preemption_timer() && enable_preemption_timer) { + u64 vmx_msr; + + rdmsrl(MSR_IA32_VMX_MISC, vmx_msr); + cpu_preemption_timer_multi = + vmx_msr & VMX_MISC_PREEMPTION_TIMER_RATE_MASK; + } else { + kvm_x86_ops->set_hv_timer = NULL; + kvm_x86_ops->cancel_hv_timer = NULL; + } + + kvm_set_posted_intr_wakeup_handler(wakeup_handler); + + kvm_mce_cap_supported |= MCG_LMCE_P; + + return alloc_kvm_area(); + +out: + for (i = 0; i < VMX_BITMAP_NR; i++) + free_page((unsigned long)vmx_bitmap[i]); + + return r; +} +","@@ -10525,6 +10525,11 @@ static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12, + if (exec_control & CPU_BASED_TPR_SHADOW) { + vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull); + vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold); ++ } else { ++#ifdef CONFIG_X86_64 ++ exec_control |= CPU_BASED_CR8_LOAD_EXITING | ++ CPU_BASED_CR8_STORE_EXITING; ++#endif + } + + /*",1564,1895,2048 +9571,"static pack_t *FS_LoadZipFile(const char *zipfile, const char *basename) +{ + fileInPack_t *buildBuffer; + pack_t *pack; + unzFile uf; + int err; + unz_global_info gi; + char filename_inzip[MAX_ZPATH]; + unz_file_info file_info; + int i, len; + long hash; + int fs_numHeaderLongs; + int *fs_headerLongs; + char *namePtr; + + fs_numHeaderLongs = 0; + + uf = unzOpen( zipfile ); + err = unzGetGlobalInfo( uf,&gi ); + + if ( err != UNZ_OK ) { + return NULL; + } + + fs_packFiles += gi.number_entry; + + len = 0; + unzGoToFirstFile( uf ); + for ( i = 0; i < gi.number_entry; i++ ) + { + err = unzGetCurrentFileInfo( uf, &file_info, filename_inzip, sizeof( filename_inzip ), NULL, 0, NULL, 0 ); + if ( err != UNZ_OK ) { + break; + } + len += strlen( filename_inzip ) + 1; + unzGoToNextFile( uf ); + } + + buildBuffer = Z_Malloc( ( gi.number_entry * sizeof( fileInPack_t ) ) + len ); + namePtr = ( (char *) buildBuffer ) + gi.number_entry * sizeof( fileInPack_t ); + fs_headerLongs = Z_Malloc( ( gi.number_entry + 1 ) * sizeof(int) ); + fs_headerLongs[ fs_numHeaderLongs++ ] = LittleLong( fs_checksumFeed ); + + for ( i = 1; i <= MAX_FILEHASH_SIZE; i <<= 1 ) { + if ( i > gi.number_entry ) { + break; + } + } + + pack = Z_Malloc( sizeof( pack_t ) + i * sizeof( fileInPack_t * ) ); + pack->hashSize = i; + pack->hashTable = ( fileInPack_t ** )( ( (char *) pack ) + sizeof( pack_t ) ); + for ( i = 0; i < pack->hashSize; i++ ) { + pack->hashTable[i] = NULL; + } + + Q_strncpyz( pack->pakFilename, zipfile, sizeof( pack->pakFilename ) ); + Q_strncpyz( pack->pakBasename, basename, sizeof( pack->pakBasename ) ); + + if ( strlen( pack->pakBasename ) > 4 && !Q_stricmp( pack->pakBasename + strlen( pack->pakBasename ) - 4, "".pk3"" ) ) { + pack->pakBasename[strlen( pack->pakBasename ) - 4] = 0; + } + + pack->handle = uf; + pack->numfiles = gi.number_entry; + unzGoToFirstFile( uf ); + + for ( i = 0; i < gi.number_entry; i++ ) + { + err = unzGetCurrentFileInfo( uf, &file_info, filename_inzip, sizeof( filename_inzip ), NULL, 0, NULL, 0 ); + if ( err != UNZ_OK ) { + break; + } + if ( file_info.uncompressed_size > 0 ) { + fs_headerLongs[fs_numHeaderLongs++] = LittleLong( file_info.crc ); + } + Q_strlwr( filename_inzip ); + hash = FS_HashFileName( filename_inzip, pack->hashSize ); + buildBuffer[i].name = namePtr; + strcpy( buildBuffer[i].name, filename_inzip ); + namePtr += strlen( filename_inzip ) + 1; + buildBuffer[i].pos = unzGetOffset(uf); + buildBuffer[i].len = file_info.uncompressed_size; + buildBuffer[i].next = pack->hashTable[hash]; + pack->hashTable[hash] = &buildBuffer[i]; + unzGoToNextFile( uf ); + } + + pack->checksum = Com_BlockChecksum( &fs_headerLongs[ 1 ], sizeof(*fs_headerLongs) * ( fs_numHeaderLongs - 1 ) ); + pack->pure_checksum = Com_BlockChecksum( fs_headerLongs, sizeof(*fs_headerLongs) * fs_numHeaderLongs ); + pack->checksum = LittleLong( pack->checksum ); + pack->pure_checksum = LittleLong( pack->pure_checksum ); + + Z_Free( fs_headerLongs ); + + pack->buildBuffer = buildBuffer; + return pack; +} +",0,"static pack_t *FS_LoadZipFile(const char *zipfile, const char *basename) +{ + fileInPack_t *buildBuffer; + pack_t *pack; + unzFile uf; + int err; + unz_global_info gi; + char filename_inzip[MAX_ZPATH]; + unz_file_info file_info; + int i, len; + long hash; + int fs_numHeaderLongs; + int *fs_headerLongs; + char *namePtr; + + fs_numHeaderLongs = 0; + + uf = unzOpen( zipfile ); + err = unzGetGlobalInfo( uf,&gi ); + + if ( err != UNZ_OK ) { + return NULL; + } + + fs_packFiles += gi.number_entry; + + len = 0; + unzGoToFirstFile( uf ); + for ( i = 0; i < gi.number_entry; i++ ) + { + err = unzGetCurrentFileInfo( uf, &file_info, filename_inzip, sizeof( filename_inzip ), NULL, 0, NULL, 0 ); + if ( err != UNZ_OK ) { + break; + } + len += strlen( filename_inzip ) + 1; + unzGoToNextFile( uf ); + } + + buildBuffer = Z_Malloc( ( gi.number_entry * sizeof( fileInPack_t ) ) + len ); + namePtr = ( (char *) buildBuffer ) + gi.number_entry * sizeof( fileInPack_t ); + fs_headerLongs = Z_Malloc( ( gi.number_entry + 1 ) * sizeof(int) ); + fs_headerLongs[ fs_numHeaderLongs++ ] = LittleLong( fs_checksumFeed ); + + for ( i = 1; i <= MAX_FILEHASH_SIZE; i <<= 1 ) { + if ( i > gi.number_entry ) { + break; + } + } + + pack = Z_Malloc( sizeof( pack_t ) + i * sizeof( fileInPack_t * ) ); + pack->hashSize = i; + pack->hashTable = ( fileInPack_t ** )( ( (char *) pack ) + sizeof( pack_t ) ); + for ( i = 0; i < pack->hashSize; i++ ) { + pack->hashTable[i] = NULL; + } + + Q_strncpyz( pack->pakFilename, zipfile, sizeof( pack->pakFilename ) ); + Q_strncpyz( pack->pakBasename, basename, sizeof( pack->pakBasename ) ); + + if ( strlen( pack->pakBasename ) > 4 && !Q_stricmp( pack->pakBasename + strlen( pack->pakBasename ) - 4, "".pk3"" ) ) { + pack->pakBasename[strlen( pack->pakBasename ) - 4] = 0; + } + + pack->handle = uf; + pack->numfiles = gi.number_entry; + unzGoToFirstFile( uf ); + + for ( i = 0; i < gi.number_entry; i++ ) + { + err = unzGetCurrentFileInfo( uf, &file_info, filename_inzip, sizeof( filename_inzip ), NULL, 0, NULL, 0 ); + if ( err != UNZ_OK ) { + break; + } + if ( file_info.uncompressed_size > 0 ) { + fs_headerLongs[fs_numHeaderLongs++] = LittleLong( file_info.crc ); + } + Q_strlwr( filename_inzip ); + hash = FS_HashFileName( filename_inzip, pack->hashSize ); + buildBuffer[i].name = namePtr; + strcpy( buildBuffer[i].name, filename_inzip ); + namePtr += strlen( filename_inzip ) + 1; + buildBuffer[i].pos = unzGetOffset(uf); + buildBuffer[i].len = file_info.uncompressed_size; + buildBuffer[i].next = pack->hashTable[hash]; + pack->hashTable[hash] = &buildBuffer[i]; + unzGoToNextFile( uf ); + } + + pack->checksum = Com_BlockChecksum( &fs_headerLongs[ 1 ], sizeof(*fs_headerLongs) * ( fs_numHeaderLongs - 1 ) ); + pack->pure_checksum = Com_BlockChecksum( fs_headerLongs, sizeof(*fs_headerLongs) * fs_numHeaderLongs ); + pack->checksum = LittleLong( pack->checksum ); + pack->pure_checksum = LittleLong( pack->pure_checksum ); + + Z_Free( fs_headerLongs ); + + pack->buildBuffer = buildBuffer; + return pack; +} +","@@ -1591,12 +1591,18 @@ long FS_FOpenFileRead(const char *filename, fileHandle_t *file, qboolean uniqueF + { + searchpath_t *search; + long len; ++ qboolean isLocalConfig; + + if(!fs_searchpaths) + Com_Error(ERR_FATAL, ""Filesystem call made without initialization""); + ++ isLocalConfig = !strcmp(filename, ""autoexec.cfg"") || !strcmp(filename, Q3CONFIG_CFG); + for(search = fs_searchpaths; search; search = search->next) + { ++ // autoexec.cfg and wolfconfig.cfg can only be loaded outside of pk3 files. ++ if (isLocalConfig && search->pack) ++ continue; ++ + len = FS_FOpenFileReadDir(filename, search, file, uniqueFILE, qfalse); + + if(file == NULL)",954,1285,2048 +10992,"error::Error GLES2DecoderImpl::DoTexImage2D( + GLenum target, + GLint level, + GLenum internal_format, + GLsizei width, + GLsizei height, + GLint border, + GLenum format, + GLenum type, + const void* pixels, + uint32 pixels_size) { + if (!validators_->texture_target.IsValid(target)) { + SetGLErrorInvalidEnum(""glTexImage2D"", target, ""target""); + return error::kNoError; + } + if (!validators_->texture_format.IsValid(internal_format)) { + SetGLErrorInvalidEnum(""glTexImage2D"", internal_format, ""internal_format""); + return error::kNoError; + } + if (!validators_->texture_format.IsValid(format)) { + SetGLErrorInvalidEnum(""glTexImage2D"", format, ""format""); + return error::kNoError; + } + if (!validators_->pixel_type.IsValid(type)) { + SetGLErrorInvalidEnum(""glTexImage2D"", type, ""type""); + return error::kNoError; + } + if (format != internal_format) { + SetGLError(GL_INVALID_OPERATION, + ""glTexImage2D"", ""format != internalFormat""); + return error::kNoError; + } + if (!ValidateTextureParameters(""glTexImage2D"", target, format, type, level)) { + return error::kNoError; + } + if (!texture_manager()->ValidForTarget(target, level, width, height, 1) || + border != 0) { + SetGLError(GL_INVALID_VALUE, ""glTexImage2D"", ""dimensions out of range""); + return error::kNoError; + } + if ((GLES2Util::GetChannelsForFormat(format) & + (GLES2Util::kDepth | GLES2Util::kStencil)) != 0 && pixels) { + SetGLError( + GL_INVALID_OPERATION, + ""glTexImage2D"", ""can not supply data for depth or stencil textures""); + return error::kNoError; + } + TextureManager::TextureInfo* info = GetTextureInfoForTarget(target); + if (!info) { + SetGLError(GL_INVALID_OPERATION, + ""glTexImage2D"", ""unknown texture for target""); + return error::kNoError; + } + + if (info->IsImmutable()) { + SetGLError(GL_INVALID_OPERATION, + ""glTexImage2D"", ""texture is immutable""); + return error::kNoError; + } + + GLsizei tex_width = 0; + GLsizei tex_height = 0; + GLenum tex_type = 0; + GLenum tex_format = 0; + bool level_is_same = + info->GetLevelSize(target, level, &tex_width, &tex_height) && + info->GetLevelType(target, level, &tex_type, &tex_format) && + width == tex_width && height == tex_height && + type == tex_type && format == tex_format; + + if (level_is_same && !pixels) { + texture_manager()->SetLevelInfo( + info, + target, level, internal_format, width, height, 1, border, format, type, + false); + tex_image_2d_failed_ = false; + return error::kNoError; + } + + if (info->IsAttachedToFramebuffer()) { + state_dirty_ = true; + framebuffer_manager()->IncFramebufferStateChangeCount(); + } + + if (!teximage2d_faster_than_texsubimage2d_ && level_is_same && pixels) { + glTexSubImage2D(target, level, 0, 0, width, height, format, type, pixels); + texture_manager()->SetLevelCleared(info, target, level); + tex_image_2d_failed_ = false; + return error::kNoError; + } + + CopyRealGLErrorsToWrapper(); + WrappedTexImage2D( + target, level, internal_format, width, height, border, format, type, + pixels); + GLenum error = PeekGLError(); + if (error == GL_NO_ERROR) { + texture_manager()->SetLevelInfo( + info, + target, level, internal_format, width, height, 1, border, format, type, + pixels != NULL); + tex_image_2d_failed_ = false; + } + return error::kNoError; +} +",0,"error::Error GLES2DecoderImpl::DoTexImage2D( + GLenum target, + GLint level, + GLenum internal_format, + GLsizei width, + GLsizei height, + GLint border, + GLenum format, + GLenum type, + const void* pixels, + uint32 pixels_size) { + if (!validators_->texture_target.IsValid(target)) { + SetGLErrorInvalidEnum(""glTexImage2D"", target, ""target""); + return error::kNoError; + } + if (!validators_->texture_format.IsValid(internal_format)) { + SetGLErrorInvalidEnum(""glTexImage2D"", internal_format, ""internal_format""); + return error::kNoError; + } + if (!validators_->texture_format.IsValid(format)) { + SetGLErrorInvalidEnum(""glTexImage2D"", format, ""format""); + return error::kNoError; + } + if (!validators_->pixel_type.IsValid(type)) { + SetGLErrorInvalidEnum(""glTexImage2D"", type, ""type""); + return error::kNoError; + } + if (format != internal_format) { + SetGLError(GL_INVALID_OPERATION, + ""glTexImage2D"", ""format != internalFormat""); + return error::kNoError; + } + if (!ValidateTextureParameters(""glTexImage2D"", target, format, type, level)) { + return error::kNoError; + } + if (!texture_manager()->ValidForTarget(target, level, width, height, 1) || + border != 0) { + SetGLError(GL_INVALID_VALUE, ""glTexImage2D"", ""dimensions out of range""); + return error::kNoError; + } + if ((GLES2Util::GetChannelsForFormat(format) & + (GLES2Util::kDepth | GLES2Util::kStencil)) != 0 && pixels) { + SetGLError( + GL_INVALID_OPERATION, + ""glTexImage2D"", ""can not supply data for depth or stencil textures""); + return error::kNoError; + } + TextureManager::TextureInfo* info = GetTextureInfoForTarget(target); + if (!info) { + SetGLError(GL_INVALID_OPERATION, + ""glTexImage2D"", ""unknown texture for target""); + return error::kNoError; + } + + if (info->IsImmutable()) { + SetGLError(GL_INVALID_OPERATION, + ""glTexImage2D"", ""texture is immutable""); + return error::kNoError; + } + + GLsizei tex_width = 0; + GLsizei tex_height = 0; + GLenum tex_type = 0; + GLenum tex_format = 0; + bool level_is_same = + info->GetLevelSize(target, level, &tex_width, &tex_height) && + info->GetLevelType(target, level, &tex_type, &tex_format) && + width == tex_width && height == tex_height && + type == tex_type && format == tex_format; + + if (level_is_same && !pixels) { + texture_manager()->SetLevelInfo( + info, + target, level, internal_format, width, height, 1, border, format, type, + false); + tex_image_2d_failed_ = false; + return error::kNoError; + } + + if (info->IsAttachedToFramebuffer()) { + state_dirty_ = true; + framebuffer_manager()->IncFramebufferStateChangeCount(); + } + + if (!teximage2d_faster_than_texsubimage2d_ && level_is_same && pixels) { + glTexSubImage2D(target, level, 0, 0, width, height, format, type, pixels); + texture_manager()->SetLevelCleared(info, target, level); + tex_image_2d_failed_ = false; + return error::kNoError; + } + + CopyRealGLErrorsToWrapper(); + WrappedTexImage2D( + target, level, internal_format, width, height, border, format, type, + pixels); + GLenum error = PeekGLError(); + if (error == GL_NO_ERROR) { + texture_manager()->SetLevelInfo( + info, + target, level, internal_format, width, height, 1, border, format, type, + pixels != NULL); + tex_image_2d_failed_ = false; + } + return error::kNoError; +} +","@@ -5435,11 +5435,10 @@ bool GLES2DecoderImpl::SimulateAttrib0( + typedef VertexAttribManager::VertexAttribInfo::Vec4 Vec4; + + GLuint num_vertices = max_vertex_accessed + 1; +- GLuint size_needed = 0; ++ uint32 size_needed = 0; + + if (num_vertices == 0 || +- !SafeMultiply(num_vertices, static_cast(sizeof(Vec4)), +- &size_needed) || ++ !SafeMultiplyUint32(num_vertices, sizeof(Vec4), &size_needed) || + size_needed > 0x7FFFFFFFU) { + SetGLError(GL_OUT_OF_MEMORY, function_name, ""Simulating attrib 0""); + return false; +@@ -5549,20 +5548,19 @@ bool GLES2DecoderImpl::SimulateFixedAttribs( + if (attrib_info && + info->CanAccess(max_accessed) && + info->type() == GL_FIXED) { +- GLuint elements_used = 0; +- if (!SafeMultiply(num_vertices, +- static_cast(info->size()), &elements_used) || +- !SafeAdd(elements_needed, elements_used, &elements_needed)) { ++ uint32 elements_used = 0; ++ if (!SafeMultiplyUint32(num_vertices, info->size(), &elements_used) || ++ !SafeAddUint32(elements_needed, elements_used, &elements_needed)) { + SetGLError( + GL_OUT_OF_MEMORY, function_name, ""simulating GL_FIXED attribs""); + return false; + } + } + } + +- const GLuint kSizeOfFloat = sizeof(float); // NOLINT +- GLuint size_needed = 0; +- if (!SafeMultiply(elements_needed, kSizeOfFloat, &size_needed) || ++ const uint32 kSizeOfFloat = sizeof(float); // NOLINT ++ uint32 size_needed = 0; ++ if (!SafeMultiplyUint32(elements_needed, kSizeOfFloat, &size_needed) || + size_needed > 0x7FFFFFFFU) { + SetGLError(GL_OUT_OF_MEMORY, function_name, ""simulating GL_FIXED attribs""); + return false; +@@ -6481,9 +6479,9 @@ error::Error GLES2DecoderImpl::HandleReadPixels( + // Get the size of the current fbo or backbuffer. + gfx::Size max_size = GetBoundReadFrameBufferSize(); + +- GLint max_x; +- GLint max_y; +- if (!SafeAdd(x, width, &max_x) || !SafeAdd(y, height, &max_y)) { ++ int32 max_x; ++ int32 max_y; ++ if (!SafeAddInt32(x, width, &max_x) || !SafeAddInt32(y, height, &max_y)) { + SetGLError(GL_INVALID_VALUE, ""glReadPixels"", ""dimensions out of range""); + return error::kNoError; + } +@@ -8536,7 +8534,7 @@ error::Error GLES2DecoderImpl::HandleGetMultipleIntegervCHROMIUM( + } + // Num will never be more than 4. + DCHECK_LE(num, 4u); +- if (!SafeAdd(num_results, num, &num_results)) { ++ if (!SafeAddUint32(num_results, num, &num_results)) { + return error::kOutOfBounds; + } + }",908,1239,2048 +17225,"static void onRttResults(wifi_request_id id, unsigned num_results, wifi_rtt_result* results[]) { + + JNIHelper helper(mVM); + + ALOGD(""onRttResults called, vm = %p, obj = %p"", mVM, mCls); + + JNIObject rttResults = helper.newObjectArray( + num_results, ""android/net/wifi/RttManager$RttResult"", NULL); + if (rttResults == NULL) { + ALOGE(""Error in allocating array""); + return; + } + + for (unsigned i = 0; i < num_results; i++) { + + wifi_rtt_result *result = results[i]; + + JNIObject rttResult = helper.createObject(""android/net/wifi/RttManager$RttResult""); + if (rttResult == NULL) { + ALOGE(""Error in creating rtt result""); + return; + } + + char bssid[32]; + sprintf(bssid, ""%02x:%02x:%02x:%02x:%02x:%02x"", result->addr[0], result->addr[1], + result->addr[2], result->addr[3], result->addr[4], result->addr[5]); + + helper.setStringField(rttResult, ""bssid"", bssid); + helper.setIntField( rttResult, ""burstNumber"", result->burst_num); + helper.setIntField( rttResult, ""measurementFrameNumber"", result->measurement_number); + helper.setIntField( rttResult, ""successMeasurementFrameNumber"", result->success_number); + helper.setIntField(rttResult, ""frameNumberPerBurstPeer"", result->number_per_burst_peer); + helper.setIntField( rttResult, ""status"", result->status); + helper.setIntField( rttResult, ""measurementType"", result->type); + helper.setIntField(rttResult, ""retryAfterDuration"", result->retry_after_duration); + helper.setLongField(rttResult, ""ts"", result->ts); + helper.setIntField( rttResult, ""rssi"", result->rssi); + helper.setIntField( rttResult, ""rssiSpread"", result->rssi_spread); + helper.setIntField( rttResult, ""txRate"", result->tx_rate.bitrate); + helper.setIntField( rttResult, ""rxRate"", result->rx_rate.bitrate); + helper.setLongField(rttResult, ""rtt"", result->rtt); + helper.setLongField(rttResult, ""rttStandardDeviation"", result->rtt_sd); + helper.setIntField( rttResult, ""distance"", result->distance); + helper.setIntField( rttResult, ""distanceStandardDeviation"", result->distance_sd); + helper.setIntField( rttResult, ""distanceSpread"", result->distance_spread); + helper.setIntField( rttResult, ""burstDuration"", result->burst_duration); + helper.setIntField( rttResult, ""negotiatedBurstNum"", result->negotiated_burst_num); + + JNIObject LCI = helper.createObject( + ""android/net/wifi/RttManager$WifiInformationElement""); + if (result->LCI != NULL && result->LCI->len > 0) { + ALOGD(""Add LCI in result""); + helper.setByteField(LCI, ""id"", result->LCI->id); + JNIObject elements = helper.newByteArray(result->LCI->len); + jbyte *bytes = (jbyte *)&(result->LCI->data[0]); + helper.setByteArrayRegion(elements, 0, result->LCI->len, bytes); + helper.setObjectField(LCI, ""data"", ""[B"", elements); + } else { + ALOGD(""No LCI in result""); + helper.setByteField(LCI, ""id"", (byte)(0xff)); + } + helper.setObjectField(rttResult, ""LCI"", + ""Landroid/net/wifi/RttManager$WifiInformationElement;"", LCI); + + JNIObject LCR = helper.createObject( + ""android/net/wifi/RttManager$WifiInformationElement""); + if (result->LCR != NULL && result->LCR->len > 0) { + ALOGD(""Add LCR in result""); + helper.setByteField(LCR, ""id"", result->LCR->id); + JNIObject elements = helper.newByteArray(result->LCI->len); + jbyte *bytes = (jbyte *)&(result->LCR->data[0]); + helper.setByteArrayRegion(elements, 0, result->LCI->len, bytes); + helper.setObjectField(LCR, ""data"", ""[B"", elements); + } else { + ALOGD(""No LCR in result""); + helper.setByteField(LCR, ""id"", (byte)(0xff)); + } + helper.setObjectField(rttResult, ""LCR"", + ""Landroid/net/wifi/RttManager$WifiInformationElement;"", LCR); + + helper.setObjectArrayElement(rttResults, i, rttResult); + } + + helper.reportEvent(mCls, ""onRttResults"", ""(I[Landroid/net/wifi/RttManager$RttResult;)V"", + id, rttResults.get()); +} +",0,"static void onRttResults(wifi_request_id id, unsigned num_results, wifi_rtt_result* results[]) { + + JNIHelper helper(mVM); + + ALOGD(""onRttResults called, vm = %p, obj = %p"", mVM, mCls); + + JNIObject rttResults = helper.newObjectArray( + num_results, ""android/net/wifi/RttManager$RttResult"", NULL); + if (rttResults == NULL) { + ALOGE(""Error in allocating array""); + return; + } + + for (unsigned i = 0; i < num_results; i++) { + + wifi_rtt_result *result = results[i]; + + JNIObject rttResult = helper.createObject(""android/net/wifi/RttManager$RttResult""); + if (rttResult == NULL) { + ALOGE(""Error in creating rtt result""); + return; + } + + char bssid[32]; + sprintf(bssid, ""%02x:%02x:%02x:%02x:%02x:%02x"", result->addr[0], result->addr[1], + result->addr[2], result->addr[3], result->addr[4], result->addr[5]); + + helper.setStringField(rttResult, ""bssid"", bssid); + helper.setIntField( rttResult, ""burstNumber"", result->burst_num); + helper.setIntField( rttResult, ""measurementFrameNumber"", result->measurement_number); + helper.setIntField( rttResult, ""successMeasurementFrameNumber"", result->success_number); + helper.setIntField(rttResult, ""frameNumberPerBurstPeer"", result->number_per_burst_peer); + helper.setIntField( rttResult, ""status"", result->status); + helper.setIntField( rttResult, ""measurementType"", result->type); + helper.setIntField(rttResult, ""retryAfterDuration"", result->retry_after_duration); + helper.setLongField(rttResult, ""ts"", result->ts); + helper.setIntField( rttResult, ""rssi"", result->rssi); + helper.setIntField( rttResult, ""rssiSpread"", result->rssi_spread); + helper.setIntField( rttResult, ""txRate"", result->tx_rate.bitrate); + helper.setIntField( rttResult, ""rxRate"", result->rx_rate.bitrate); + helper.setLongField(rttResult, ""rtt"", result->rtt); + helper.setLongField(rttResult, ""rttStandardDeviation"", result->rtt_sd); + helper.setIntField( rttResult, ""distance"", result->distance); + helper.setIntField( rttResult, ""distanceStandardDeviation"", result->distance_sd); + helper.setIntField( rttResult, ""distanceSpread"", result->distance_spread); + helper.setIntField( rttResult, ""burstDuration"", result->burst_duration); + helper.setIntField( rttResult, ""negotiatedBurstNum"", result->negotiated_burst_num); + + JNIObject LCI = helper.createObject( + ""android/net/wifi/RttManager$WifiInformationElement""); + if (result->LCI != NULL && result->LCI->len > 0) { + ALOGD(""Add LCI in result""); + helper.setByteField(LCI, ""id"", result->LCI->id); + JNIObject elements = helper.newByteArray(result->LCI->len); + jbyte *bytes = (jbyte *)&(result->LCI->data[0]); + helper.setByteArrayRegion(elements, 0, result->LCI->len, bytes); + helper.setObjectField(LCI, ""data"", ""[B"", elements); + } else { + ALOGD(""No LCI in result""); + helper.setByteField(LCI, ""id"", (byte)(0xff)); + } + helper.setObjectField(rttResult, ""LCI"", + ""Landroid/net/wifi/RttManager$WifiInformationElement;"", LCI); + + JNIObject LCR = helper.createObject( + ""android/net/wifi/RttManager$WifiInformationElement""); + if (result->LCR != NULL && result->LCR->len > 0) { + ALOGD(""Add LCR in result""); + helper.setByteField(LCR, ""id"", result->LCR->id); + JNIObject elements = helper.newByteArray(result->LCI->len); + jbyte *bytes = (jbyte *)&(result->LCR->data[0]); + helper.setByteArrayRegion(elements, 0, result->LCI->len, bytes); + helper.setObjectField(LCR, ""data"", ""[B"", elements); + } else { + ALOGD(""No LCR in result""); + helper.setByteField(LCR, ""id"", (byte)(0xff)); + } + helper.setObjectField(rttResult, ""LCR"", + ""Landroid/net/wifi/RttManager$WifiInformationElement;"", LCR); + + helper.setObjectArrayElement(rttResults, i, rttResult); + } + + helper.reportEvent(mCls, ""onRttResults"", ""(I[Landroid/net/wifi/RttManager$RttResult;)V"", + id, rttResults.get()); +} +","@@ -697,15 +697,23 @@ + + } + + static byte parseHexByte(const char * &str) { ++ if (str[0] == '\0') { ++ ALOGE(""Passed an empty string""); ++ return 0; ++ } + byte b = parseHexChar(str[0]); +- if (str[1] == ':' || str[1] == '\0') { +- str += 2; +- return b; ++ if (str[1] == '\0' || str[1] == ':') { ++ str ++; + } else { + b = b << 4 | parseHexChar(str[1]); +- str += 3; +- return b; ++ str += 2; + } ++ ++ // Skip trailing delimiter if not at the end of the string. ++ if (str[0] != '\0') { ++ str++; ++ } ++ return b; + } + + static void parseMacAddress(const char *str, mac_addr addr) { +",1129,1460,2048 +3821,"static void load_vmcs12_host_state(struct kvm_vcpu *vcpu, + struct vmcs12 *vmcs12) +{ + struct kvm_segment seg; + + if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) + vcpu->arch.efer = vmcs12->host_ia32_efer; + else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE) + vcpu->arch.efer |= (EFER_LMA | EFER_LME); + else + vcpu->arch.efer &= ~(EFER_LMA | EFER_LME); + vmx_set_efer(vcpu, vcpu->arch.efer); + + kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp); + kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip); + vmx_set_rflags(vcpu, X86_EFLAGS_FIXED); + /* + * Note that calling vmx_set_cr0 is important, even if cr0 hasn't + * actually changed, because it depends on the current state of + * fpu_active (which may have changed). + * Note that vmx_set_cr0 refers to efer set above. + */ + kvm_set_cr0(vcpu, vmcs12->host_cr0); + /* + * If we did fpu_activate()/fpu_deactivate() during L2's run, we need + * to apply the same changes to L1's vmcs. We just set cr0 correctly, + * but we also need to update cr0_guest_host_mask and exception_bitmap. + */ + update_exception_bitmap(vcpu); + vcpu->arch.cr0_guest_owned_bits = (vcpu->fpu_active ? X86_CR0_TS : 0); + vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits); + + /* + * Note that CR4_GUEST_HOST_MASK is already set in the original vmcs01 + * (KVM doesn't change it)- no reason to call set_cr4_guest_host_mask(); + */ + vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK); + kvm_set_cr4(vcpu, vmcs12->host_cr4); + + if (nested_cpu_has_ept(vmcs12)) + nested_ept_uninit_mmu_context(vcpu); + + kvm_set_cr3(vcpu, vmcs12->host_cr3); + kvm_mmu_reset_context(vcpu); + + if (enable_vpid) { + /* + * Trivially support vpid by letting L2s share their parent + * L1's vpid. TODO: move to a more elaborate solution, giving + * each L2 its own vpid and exposing the vpid feature to L1. + */ + vmx_flush_tlb(vcpu); + } + + + vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs); + vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp); + vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip); + vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base); + vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base); + + if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) + vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat); + if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL) + vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL, + vmcs12->host_ia32_perf_global_ctrl); + + /* Set L1 segment info according to Intel SDM + 27.5.2 Loading Host Segment and Descriptor-Table Registers */ + seg = (struct kvm_segment) { + .base = 0, + .limit = 0xFFFFFFFF, + .selector = vmcs12->host_cs_selector, + .type = 11, + .present = 1, + .s = 1, + .g = 1 + }; + if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE) + seg.l = 1; + else + seg.db = 1; + vmx_set_segment(vcpu, &seg, VCPU_SREG_CS); + seg = (struct kvm_segment) { + .base = 0, + .limit = 0xFFFFFFFF, + .type = 3, + .present = 1, + .s = 1, + .db = 1, + .g = 1 + }; + seg.selector = vmcs12->host_ds_selector; + vmx_set_segment(vcpu, &seg, VCPU_SREG_DS); + seg.selector = vmcs12->host_es_selector; + vmx_set_segment(vcpu, &seg, VCPU_SREG_ES); + seg.selector = vmcs12->host_ss_selector; + vmx_set_segment(vcpu, &seg, VCPU_SREG_SS); + seg.selector = vmcs12->host_fs_selector; + seg.base = vmcs12->host_fs_base; + vmx_set_segment(vcpu, &seg, VCPU_SREG_FS); + seg.selector = vmcs12->host_gs_selector; + seg.base = vmcs12->host_gs_base; + vmx_set_segment(vcpu, &seg, VCPU_SREG_GS); + seg = (struct kvm_segment) { + .base = vmcs12->host_tr_base, + .limit = 0x67, + .selector = vmcs12->host_tr_selector, + .type = 11, + .present = 1 + }; + vmx_set_segment(vcpu, &seg, VCPU_SREG_TR); + + kvm_set_dr(vcpu, 7, 0x400); + vmcs_write64(GUEST_IA32_DEBUGCTL, 0); +} +",0,"static void load_vmcs12_host_state(struct kvm_vcpu *vcpu, + struct vmcs12 *vmcs12) +{ + struct kvm_segment seg; + + if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_EFER) + vcpu->arch.efer = vmcs12->host_ia32_efer; + else if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE) + vcpu->arch.efer |= (EFER_LMA | EFER_LME); + else + vcpu->arch.efer &= ~(EFER_LMA | EFER_LME); + vmx_set_efer(vcpu, vcpu->arch.efer); + + kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->host_rsp); + kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->host_rip); + vmx_set_rflags(vcpu, X86_EFLAGS_FIXED); + /* + * Note that calling vmx_set_cr0 is important, even if cr0 hasn't + * actually changed, because it depends on the current state of + * fpu_active (which may have changed). + * Note that vmx_set_cr0 refers to efer set above. + */ + kvm_set_cr0(vcpu, vmcs12->host_cr0); + /* + * If we did fpu_activate()/fpu_deactivate() during L2's run, we need + * to apply the same changes to L1's vmcs. We just set cr0 correctly, + * but we also need to update cr0_guest_host_mask and exception_bitmap. + */ + update_exception_bitmap(vcpu); + vcpu->arch.cr0_guest_owned_bits = (vcpu->fpu_active ? X86_CR0_TS : 0); + vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits); + + /* + * Note that CR4_GUEST_HOST_MASK is already set in the original vmcs01 + * (KVM doesn't change it)- no reason to call set_cr4_guest_host_mask(); + */ + vcpu->arch.cr4_guest_owned_bits = ~vmcs_readl(CR4_GUEST_HOST_MASK); + kvm_set_cr4(vcpu, vmcs12->host_cr4); + + if (nested_cpu_has_ept(vmcs12)) + nested_ept_uninit_mmu_context(vcpu); + + kvm_set_cr3(vcpu, vmcs12->host_cr3); + kvm_mmu_reset_context(vcpu); + + if (enable_vpid) { + /* + * Trivially support vpid by letting L2s share their parent + * L1's vpid. TODO: move to a more elaborate solution, giving + * each L2 its own vpid and exposing the vpid feature to L1. + */ + vmx_flush_tlb(vcpu); + } + + + vmcs_write32(GUEST_SYSENTER_CS, vmcs12->host_ia32_sysenter_cs); + vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->host_ia32_sysenter_esp); + vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->host_ia32_sysenter_eip); + vmcs_writel(GUEST_IDTR_BASE, vmcs12->host_idtr_base); + vmcs_writel(GUEST_GDTR_BASE, vmcs12->host_gdtr_base); + + if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PAT) + vmcs_write64(GUEST_IA32_PAT, vmcs12->host_ia32_pat); + if (vmcs12->vm_exit_controls & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL) + vmcs_write64(GUEST_IA32_PERF_GLOBAL_CTRL, + vmcs12->host_ia32_perf_global_ctrl); + + /* Set L1 segment info according to Intel SDM + 27.5.2 Loading Host Segment and Descriptor-Table Registers */ + seg = (struct kvm_segment) { + .base = 0, + .limit = 0xFFFFFFFF, + .selector = vmcs12->host_cs_selector, + .type = 11, + .present = 1, + .s = 1, + .g = 1 + }; + if (vmcs12->vm_exit_controls & VM_EXIT_HOST_ADDR_SPACE_SIZE) + seg.l = 1; + else + seg.db = 1; + vmx_set_segment(vcpu, &seg, VCPU_SREG_CS); + seg = (struct kvm_segment) { + .base = 0, + .limit = 0xFFFFFFFF, + .type = 3, + .present = 1, + .s = 1, + .db = 1, + .g = 1 + }; + seg.selector = vmcs12->host_ds_selector; + vmx_set_segment(vcpu, &seg, VCPU_SREG_DS); + seg.selector = vmcs12->host_es_selector; + vmx_set_segment(vcpu, &seg, VCPU_SREG_ES); + seg.selector = vmcs12->host_ss_selector; + vmx_set_segment(vcpu, &seg, VCPU_SREG_SS); + seg.selector = vmcs12->host_fs_selector; + seg.base = vmcs12->host_fs_base; + vmx_set_segment(vcpu, &seg, VCPU_SREG_FS); + seg.selector = vmcs12->host_gs_selector; + seg.base = vmcs12->host_gs_base; + vmx_set_segment(vcpu, &seg, VCPU_SREG_GS); + seg = (struct kvm_segment) { + .base = vmcs12->host_tr_base, + .limit = 0x67, + .selector = vmcs12->host_tr_selector, + .type = 11, + .present = 1 + }; + vmx_set_segment(vcpu, &seg, VCPU_SREG_TR); + + kvm_set_dr(vcpu, 7, 0x400); + vmcs_write64(GUEST_IA32_DEBUGCTL, 0); +} +","@@ -712,6 +712,7 @@ static void nested_release_page_clean(struct page *page) + kvm_release_page_clean(page); + } + ++static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu); + static u64 construct_eptp(unsigned long root_hpa); + static void kvm_cpu_vmxon(u64 addr); + static void kvm_cpu_vmxoff(void); +@@ -2161,6 +2162,7 @@ static u32 nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high; + static u32 nested_vmx_exit_ctls_low, nested_vmx_exit_ctls_high; + static u32 nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high; + static u32 nested_vmx_misc_low, nested_vmx_misc_high; ++static u32 nested_vmx_ept_caps; + static __init void nested_vmx_setup_ctls_msrs(void) + { + /* +@@ -6279,6 +6281,74 @@ static int handle_vmptrst(struct kvm_vcpu *vcpu) + return 1; + } + ++/* Emulate the INVEPT instruction */ ++static int handle_invept(struct kvm_vcpu *vcpu) ++{ ++ u32 vmx_instruction_info, types; ++ unsigned long type; ++ gva_t gva; ++ struct x86_exception e; ++ struct { ++ u64 eptp, gpa; ++ } operand; ++ u64 eptp_mask = ((1ull << 51) - 1) & PAGE_MASK; ++ ++ if (!(nested_vmx_secondary_ctls_high & SECONDARY_EXEC_ENABLE_EPT) || ++ !(nested_vmx_ept_caps & VMX_EPT_INVEPT_BIT)) { ++ kvm_queue_exception(vcpu, UD_VECTOR); ++ return 1; ++ } ++ ++ if (!nested_vmx_check_permission(vcpu)) ++ return 1; ++ ++ if (!kvm_read_cr0_bits(vcpu, X86_CR0_PE)) { ++ kvm_queue_exception(vcpu, UD_VECTOR); ++ return 1; ++ } ++ ++ vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO); ++ type = kvm_register_read(vcpu, (vmx_instruction_info >> 28) & 0xf); ++ ++ types = (nested_vmx_ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6; ++ ++ if (!(types & (1UL << type))) { ++ nested_vmx_failValid(vcpu, ++ VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID); ++ return 1; ++ } ++ ++ /* According to the Intel VMX instruction reference, the memory ++ * operand is read even if it isn't needed (e.g., for type==global) ++ */ ++ if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION), ++ vmx_instruction_info, &gva)) ++ return 1; ++ if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &operand, ++ sizeof(operand), &e)) { ++ kvm_inject_page_fault(vcpu, &e); ++ return 1; ++ } ++ ++ switch (type) { ++ case VMX_EPT_EXTENT_CONTEXT: ++ if ((operand.eptp & eptp_mask) != ++ (nested_ept_get_cr3(vcpu) & eptp_mask)) ++ break; ++ case VMX_EPT_EXTENT_GLOBAL: ++ kvm_mmu_sync_roots(vcpu); ++ kvm_mmu_flush_tlb(vcpu); ++ nested_vmx_succeed(vcpu); ++ break; ++ default: ++ BUG_ON(1); ++ break; ++ } ++ ++ skip_emulated_instruction(vcpu); ++ return 1; ++} ++ + /* + * The exit handlers return 1 if the exit was handled fully and guest execution + * may resume. Otherwise they set the kvm_run parameter to indicate what needs +@@ -6323,6 +6393,7 @@ static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = { + [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause, + [EXIT_REASON_MWAIT_INSTRUCTION] = handle_invalid_op, + [EXIT_REASON_MONITOR_INSTRUCTION] = handle_invalid_op, ++ [EXIT_REASON_INVEPT] = handle_invept, + }; + + static const int kvm_vmx_max_exit_handlers = +@@ -6549,6 +6620,7 @@ static bool nested_vmx_exit_handled(struct kvm_vcpu *vcpu) + case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD: + case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE: + case EXIT_REASON_VMOFF: case EXIT_REASON_VMON: ++ case EXIT_REASON_INVEPT: + /* + * VMX instructions trap unconditionally. This allows L1 to + * emulate them for its L2 guest, i.e., allows 3-level nesting!",1343,1674,2048 +5936,"int main(int argc, char **argv) +{ + darray(struct tcmulib_handler) handlers = darray_new(); + struct tcmulib_context *tcmulib_context; + struct tcmur_handler **tmp_r_handler; + GMainLoop *loop; + GIOChannel *libtcmu_gio; + guint reg_id; + int ret; + + tcmu_cfg = tcmu_config_new(); + if (!tcmu_cfg) + exit(1); + ret = tcmu_load_config(tcmu_cfg, NULL); + if (ret == -1) + goto err_out; + + while (1) { + int option_index = 0; + int c; + + c = getopt_long(argc, argv, ""dhlV"", + long_options, &option_index); + if (c == -1) + break; + + switch (c) { + case 0: + if (option_index == 1) + handler_path = strdup(optarg); + break; + case 'l': + if (strlen(optarg) > PATH_MAX - TCMU_LOG_FILENAME_MAX) { + tcmu_err(""--tcmu-log-dir='%s' cannot exceed %d characters\n"", + optarg, PATH_MAX - TCMU_LOG_FILENAME_MAX); + } + if (!tcmu_logdir_create(optarg)) { + goto err_out; + } + tcmu_log_dir = strdup(optarg); + break; + case 'd': + tcmu_set_log_level(TCMU_CONF_LOG_DEBUG_SCSI_CMD); + break; + case 'V': + printf(""tcmu-runner %s\n"", TCMUR_VERSION); + goto err_out; + default: + case 'h': + usage(); + goto err_out; + } + } + + tcmu_dbg(""handler path: %s\n"", handler_path); + + ret = load_our_module(); + if (ret < 0) { + tcmu_err(""couldn't load module\n""); + goto err_out; + } + + ret = open_handlers(); + if (ret < 0) { + tcmu_err(""couldn't open handlers\n""); + goto err_out; + } + tcmu_dbg(""%d runner handlers found\n"", ret); + + /* + * Convert from tcmu-runner's handler struct to libtcmu's + * handler struct, an array of which we pass in, below. + */ + darray_foreach(tmp_r_handler, g_runner_handlers) { + struct tcmulib_handler tmp_handler; + + tmp_handler.name = (*tmp_r_handler)->name; + tmp_handler.subtype = (*tmp_r_handler)->subtype; + tmp_handler.cfg_desc = (*tmp_r_handler)->cfg_desc; + tmp_handler.check_config = (*tmp_r_handler)->check_config; + tmp_handler.reconfig = (*tmp_r_handler)->reconfig; + tmp_handler.added = dev_added; + tmp_handler.removed = dev_removed; + + /* + * Can hand out a ref to an internal pointer to the + * darray b/c handlers will never be added or removed + * once open_handlers() is done. + */ + tmp_handler.hm_private = *tmp_r_handler; + + darray_append(handlers, tmp_handler); + } + + tcmulib_context = tcmulib_initialize(handlers.item, handlers.size); + if (!tcmulib_context) { + tcmu_err(""tcmulib_initialize failed\n""); + goto err_out; + } + + loop = g_main_loop_new(NULL, FALSE); + if (g_unix_signal_add(SIGINT, sighandler, loop) <= 0 || + g_unix_signal_add(SIGTERM, sighandler, loop) <= 0) { + tcmu_err(""couldn't setup signal handlers\n""); + goto err_tcmulib_close; + } + + /* Set up event for libtcmu */ + libtcmu_gio = g_io_channel_unix_new(tcmulib_get_master_fd(tcmulib_context)); + g_io_add_watch(libtcmu_gio, G_IO_IN, tcmulib_callback, tcmulib_context); + + /* Set up DBus name, see callback */ + reg_id = g_bus_own_name(G_BUS_TYPE_SYSTEM, + ""org.kernel.TCMUService1"", + G_BUS_NAME_OWNER_FLAGS_NONE, + dbus_bus_acquired, + dbus_name_acquired, // name acquired + dbus_name_lost, // name lost + NULL, // user data + NULL // user date free func + ); + + g_main_loop_run(loop); + + tcmu_dbg(""Exiting...\n""); + g_bus_unown_name(reg_id); + g_main_loop_unref(loop); + tcmulib_close(tcmulib_context); + tcmu_config_destroy(tcmu_cfg); + + return 0; + +err_tcmulib_close: + tcmulib_close(tcmulib_context); +err_out: + tcmu_config_destroy(tcmu_cfg); + exit(1); +} +",0,"int main(int argc, char **argv) +{ + darray(struct tcmulib_handler) handlers = darray_new(); + struct tcmulib_context *tcmulib_context; + struct tcmur_handler **tmp_r_handler; + GMainLoop *loop; + GIOChannel *libtcmu_gio; + guint reg_id; + int ret; + + tcmu_cfg = tcmu_config_new(); + if (!tcmu_cfg) + exit(1); + ret = tcmu_load_config(tcmu_cfg, NULL); + if (ret == -1) + goto err_out; + + while (1) { + int option_index = 0; + int c; + + c = getopt_long(argc, argv, ""dhlV"", + long_options, &option_index); + if (c == -1) + break; + + switch (c) { + case 0: + if (option_index == 1) + handler_path = strdup(optarg); + break; + case 'l': + if (strlen(optarg) > PATH_MAX - TCMU_LOG_FILENAME_MAX) { + tcmu_err(""--tcmu-log-dir='%s' cannot exceed %d characters\n"", + optarg, PATH_MAX - TCMU_LOG_FILENAME_MAX); + } + if (!tcmu_logdir_create(optarg)) { + goto err_out; + } + tcmu_log_dir = strdup(optarg); + break; + case 'd': + tcmu_set_log_level(TCMU_CONF_LOG_DEBUG_SCSI_CMD); + break; + case 'V': + printf(""tcmu-runner %s\n"", TCMUR_VERSION); + goto err_out; + default: + case 'h': + usage(); + goto err_out; + } + } + + tcmu_dbg(""handler path: %s\n"", handler_path); + + ret = load_our_module(); + if (ret < 0) { + tcmu_err(""couldn't load module\n""); + goto err_out; + } + + ret = open_handlers(); + if (ret < 0) { + tcmu_err(""couldn't open handlers\n""); + goto err_out; + } + tcmu_dbg(""%d runner handlers found\n"", ret); + + /* + * Convert from tcmu-runner's handler struct to libtcmu's + * handler struct, an array of which we pass in, below. + */ + darray_foreach(tmp_r_handler, g_runner_handlers) { + struct tcmulib_handler tmp_handler; + + tmp_handler.name = (*tmp_r_handler)->name; + tmp_handler.subtype = (*tmp_r_handler)->subtype; + tmp_handler.cfg_desc = (*tmp_r_handler)->cfg_desc; + tmp_handler.check_config = (*tmp_r_handler)->check_config; + tmp_handler.reconfig = (*tmp_r_handler)->reconfig; + tmp_handler.added = dev_added; + tmp_handler.removed = dev_removed; + + /* + * Can hand out a ref to an internal pointer to the + * darray b/c handlers will never be added or removed + * once open_handlers() is done. + */ + tmp_handler.hm_private = *tmp_r_handler; + + darray_append(handlers, tmp_handler); + } + + tcmulib_context = tcmulib_initialize(handlers.item, handlers.size); + if (!tcmulib_context) { + tcmu_err(""tcmulib_initialize failed\n""); + goto err_out; + } + + loop = g_main_loop_new(NULL, FALSE); + if (g_unix_signal_add(SIGINT, sighandler, loop) <= 0 || + g_unix_signal_add(SIGTERM, sighandler, loop) <= 0) { + tcmu_err(""couldn't setup signal handlers\n""); + goto err_tcmulib_close; + } + + /* Set up event for libtcmu */ + libtcmu_gio = g_io_channel_unix_new(tcmulib_get_master_fd(tcmulib_context)); + g_io_add_watch(libtcmu_gio, G_IO_IN, tcmulib_callback, tcmulib_context); + + /* Set up DBus name, see callback */ + reg_id = g_bus_own_name(G_BUS_TYPE_SYSTEM, + ""org.kernel.TCMUService1"", + G_BUS_NAME_OWNER_FLAGS_NONE, + dbus_bus_acquired, + dbus_name_acquired, // name acquired + dbus_name_lost, // name lost + NULL, // user data + NULL // user date free func + ); + + g_main_loop_run(loop); + + tcmu_dbg(""Exiting...\n""); + g_bus_unown_name(reg_id); + g_main_loop_unref(loop); + tcmulib_close(tcmulib_context); + tcmu_config_destroy(tcmu_cfg); + + return 0; + +err_tcmulib_close: + tcmulib_close(tcmulib_context); +err_out: + tcmu_config_destroy(tcmu_cfg); + exit(1); +} +","@@ -386,7 +386,7 @@ on_unregister_handler(TCMUService1HandlerManager1 *interface, + gpointer user_data) + { + struct tcmur_handler *handler = find_handler_by_subtype(subtype); +- struct dbus_info *info = handler->opaque; ++ struct dbus_info *info = handler ? handler->opaque : NULL; + + if (!handler) { + g_dbus_method_invocation_return_value(invocation,",1033,1364,2048 +1686,"condor_net_remap_config( bool force_param ) +{ + char *str = NULL; + if( ! force_param && getenv(""NET_REMAP_ENABLE"") ) { + /* + this stuff is already set. unless the caller is forcing + us to call param() again (e.g. the master is trying to + re-bind() if the GCB broker is down and it's got a list + to try) we should return immediately and leave our + environment alone. this way, the master can choose what + GCB broker to use for itself and all its children, even + if there's a list and we're using $RANDOM_CHOICE(). + */ + return; + } + + /* + this method is only called if we're enabling a network remap + service. if we do, we always need to force condor to bind() + to all interfaces (INADDR_ANY). since we don't want to rely + on users to set this themselves to get GCB working, we'll + set it automatically. the only harm of setting this is that + we need Condor to automatically handle hostallow stuff for + ""localhost"", or users need to add localhost to their + hostallow settings as appropriate. we can't rely on the + later, and the former only works on some platforms. + luckily, the automatic localhost stuff works on all + platforms where GCB works (linux, and we hope, solaris), so + it's safe to turn this on whenever we're using GCB + */ + insert( ""BIND_ALL_INTERFACES"", ""TRUE"", ConfigTab, TABLESIZE ); + extra_info->AddInternalParam(""BIND_ALL_INTERFACES""); + + SetEnv( ""NET_REMAP_ENABLE"", ""true""); + str = param(""NET_REMAP_SERVICE""); + if (str) { + if (!strcasecmp(str, ""GCB"")) { + SetEnv( ""GCB_ENABLE"", ""true"" ); + free(str); + str = NULL; + if( (str = param(""NET_REMAP_INAGENT"")) ) { + const char *next_broker; + StringList all_brokers( str ); + StringList working_brokers; + + all_brokers.rewind(); + while ( (next_broker = all_brokers.next()) ) { + int rc = 0; + +#if HAVE_EXT_GCB + int num_slots = 0; /* only used w/HAVE_EXT_GCB */ + rc = GCB_broker_query( next_broker, + GCB_DATA_QUERY_FREE_SOCKS, + &num_slots ); +#endif + if ( rc == 0 ) { + working_brokers.append( next_broker ); + } + } + + if ( working_brokers.number() > 0 ) { + int rand_entry = (get_random_int() % working_brokers.number()) + 1; + int i = 0; + working_brokers.rewind(); + while ( (i < rand_entry) && + (next_broker=working_brokers.next()) ) { + i++; + } + + dprintf( D_FULLDEBUG,""Using GCB broker %s\n"",next_broker ); + SetEnv( ""GCB_INAGENT"", next_broker ); + } else { + dprintf( D_ALWAYS,""No usable GCB brokers were found. "" + ""Setting GCB_INAGENT=%s\n"", + CONDOR_GCB_INVALID_BROKER ); + SetEnv( ""GCB_INAGENT"", CONDOR_GCB_INVALID_BROKER ); + } + free( str ); + str = NULL; + } + if( (str = param(""NET_REMAP_ROUTE"")) ) { + SetEnv( ""GCB_ROUTE"", str ); + free( str ); + str = NULL; + } + } else if (!strcasecmp(str, ""DPF"")) { + SetEnv( ""DPF_ENABLE"", ""true"" ); + free(str); + str = NULL; + if( (str = param(""NET_REMAP_INAGENT"")) ) { + SetEnv( ""DPF_INAGENT"", str ); + free(str); + str = NULL; + } + if( (str = param(""NET_REMAP_ROUTE"")) ) { + SetEnv( ""DPF_ROUTE"", str ); + free(str); + str = NULL; + } + } + } +} +",0,"condor_net_remap_config( bool force_param ) +{ + char *str = NULL; + if( ! force_param && getenv(""NET_REMAP_ENABLE"") ) { + /* + this stuff is already set. unless the caller is forcing + us to call param() again (e.g. the master is trying to + re-bind() if the GCB broker is down and it's got a list + to try) we should return immediately and leave our + environment alone. this way, the master can choose what + GCB broker to use for itself and all its children, even + if there's a list and we're using $RANDOM_CHOICE(). + */ + return; + } + + /* + this method is only called if we're enabling a network remap + service. if we do, we always need to force condor to bind() + to all interfaces (INADDR_ANY). since we don't want to rely + on users to set this themselves to get GCB working, we'll + set it automatically. the only harm of setting this is that + we need Condor to automatically handle hostallow stuff for + ""localhost"", or users need to add localhost to their + hostallow settings as appropriate. we can't rely on the + later, and the former only works on some platforms. + luckily, the automatic localhost stuff works on all + platforms where GCB works (linux, and we hope, solaris), so + it's safe to turn this on whenever we're using GCB + */ + insert( ""BIND_ALL_INTERFACES"", ""TRUE"", ConfigTab, TABLESIZE ); + extra_info->AddInternalParam(""BIND_ALL_INTERFACES""); + + SetEnv( ""NET_REMAP_ENABLE"", ""true""); + str = param(""NET_REMAP_SERVICE""); + if (str) { + if (!strcasecmp(str, ""GCB"")) { + SetEnv( ""GCB_ENABLE"", ""true"" ); + free(str); + str = NULL; + if( (str = param(""NET_REMAP_INAGENT"")) ) { + const char *next_broker; + StringList all_brokers( str ); + StringList working_brokers; + + all_brokers.rewind(); + while ( (next_broker = all_brokers.next()) ) { + int rc = 0; + +#if HAVE_EXT_GCB + int num_slots = 0; /* only used w/HAVE_EXT_GCB */ + rc = GCB_broker_query( next_broker, + GCB_DATA_QUERY_FREE_SOCKS, + &num_slots ); +#endif + if ( rc == 0 ) { + working_brokers.append( next_broker ); + } + } + + if ( working_brokers.number() > 0 ) { + int rand_entry = (get_random_int() % working_brokers.number()) + 1; + int i = 0; + working_brokers.rewind(); + while ( (i < rand_entry) && + (next_broker=working_brokers.next()) ) { + i++; + } + + dprintf( D_FULLDEBUG,""Using GCB broker %s\n"",next_broker ); + SetEnv( ""GCB_INAGENT"", next_broker ); + } else { + dprintf( D_ALWAYS,""No usable GCB brokers were found. "" + ""Setting GCB_INAGENT=%s\n"", + CONDOR_GCB_INVALID_BROKER ); + SetEnv( ""GCB_INAGENT"", CONDOR_GCB_INVALID_BROKER ); + } + free( str ); + str = NULL; + } + if( (str = param(""NET_REMAP_ROUTE"")) ) { + SetEnv( ""GCB_ROUTE"", str ); + free( str ); + str = NULL; + } + } else if (!strcasecmp(str, ""DPF"")) { + SetEnv( ""DPF_ENABLE"", ""true"" ); + free(str); + str = NULL; + if( (str = param(""NET_REMAP_INAGENT"")) ) { + SetEnv( ""DPF_INAGENT"", str ); + free(str); + str = NULL; + } + if( (str = param(""NET_REMAP_ROUTE"")) ) { + SetEnv( ""DPF_ROUTE"", str ); + free(str); + str = NULL; + } + } + } +} +","@@ -240,7 +240,7 @@ validate_entries( bool ignore_invalid_entry ) { + if(ignore_invalid_entry) { + dprintf(D_ALWAYS, ""%s"", output.Value()); + } else { +- EXCEPT(output.Value()); ++ EXCEPT(""%s"", output.Value()); + } + } + }",935,1266,2048 +18328,"void CL_InitRef( void ) { + refimport_t ri; + refexport_t *ret; +#ifdef USE_RENDERER_DLOPEN + GetRefAPI_t GetRefAPI; + char dllName[MAX_OSPATH]; +#endif + + Com_Printf( ""----- Initializing Renderer ----\n"" ); + + #ifdef USE_RENDERER_DLOPEN + cl_renderer = Cvar_Get(""cl_renderer"", ""opengl1"", CVAR_ARCHIVE | CVAR_LATCH); + + Com_sprintf(dllName, sizeof(dllName), ""renderer_mp_%s_"" ARCH_STRING DLL_EXT, cl_renderer->string); + + if(!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString)) + { + Com_Printf(""failed:\n\""%s\""\n"", Sys_LibraryError()); + Cvar_ForceReset(""cl_renderer""); + + Com_sprintf(dllName, sizeof(dllName), ""renderer_mp_opengl1_"" ARCH_STRING DLL_EXT); + rendererLib = Sys_LoadDll(dllName, qfalse); + } + + if(!rendererLib) + { + Com_Printf(""failed:\n\""%s\""\n"", Sys_LibraryError()); + Com_Error(ERR_FATAL, ""Failed to load renderer""); + } + + GetRefAPI = Sys_LoadFunction(rendererLib, ""GetRefAPI""); + if(!GetRefAPI) + { + Com_Error(ERR_FATAL, ""Can't load symbol GetRefAPI: '%s'"", Sys_LibraryError()); + } +#endif + + ri.Cmd_AddCommand = Cmd_AddCommand; + ri.Cmd_RemoveCommand = Cmd_RemoveCommand; + ri.Cmd_Argc = Cmd_Argc; + ri.Cmd_Argv = Cmd_Argv; + ri.Cmd_ExecuteText = Cbuf_ExecuteText; + ri.Printf = CL_RefPrintf; + ri.Error = Com_Error; + ri.Milliseconds = CL_ScaledMilliseconds; +#ifdef ZONE_DEBUG + ri.Z_MallocDebug = CL_RefMallocDebug; +#else + ri.Z_Malloc = CL_RefMalloc; +#endif + ri.Free = Z_Free; + ri.Tag_Free = CL_RefTagFree; + ri.Hunk_Clear = Hunk_ClearToMark; +#ifdef HUNK_DEBUG + ri.Hunk_AllocDebug = Hunk_AllocDebug; +#else + ri.Hunk_Alloc = Hunk_Alloc; +#endif + ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory; + ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory; + + ri.CM_ClusterPVS = CM_ClusterPVS; + ri.CM_DrawDebugSurface = CM_DrawDebugSurface; + ri.FS_ReadFile = FS_ReadFile; + ri.FS_FreeFile = FS_FreeFile; + ri.FS_WriteFile = FS_WriteFile; + ri.FS_FreeFileList = FS_FreeFileList; + ri.FS_ListFiles = FS_ListFiles; + ri.FS_FileIsInPAK = FS_FileIsInPAK; + ri.FS_FileExists = FS_FileExists; + ri.Cvar_Get = Cvar_Get; + ri.Cvar_Set = Cvar_Set; + ri.Cvar_SetValue = Cvar_SetValue; + ri.Cvar_CheckRange = Cvar_CheckRange; + ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue; + + + ri.CIN_UploadCinematic = CIN_UploadCinematic; + ri.CIN_PlayCinematic = CIN_PlayCinematic; + ri.CIN_RunCinematic = CIN_RunCinematic; + + ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame; + + ri.IN_Init = IN_Init; + ri.IN_Shutdown = IN_Shutdown; + ri.IN_Restart = IN_Restart; + + ri.ftol = Q_ftol; + + ri.Sys_SetEnv = Sys_SetEnv; + ri.Sys_GLimpSafeInit = Sys_GLimpSafeInit; + ri.Sys_GLimpInit = Sys_GLimpInit; + ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory; + + ret = GetRefAPI( REF_API_VERSION, &ri ); + + if ( !ret ) { + Com_Error( ERR_FATAL, ""Couldn't initialize refresh"" ); + } + + re = *ret; + + Com_Printf( ""---- Renderer Initialization Complete ----\n"" ); + + Cvar_Set( ""cl_paused"", ""0"" ); +} +",1,"void CL_InitRef( void ) { + refimport_t ri; + refexport_t *ret; +#ifdef USE_RENDERER_DLOPEN + GetRefAPI_t GetRefAPI; + char dllName[MAX_OSPATH]; +#endif + + Com_Printf( ""----- Initializing Renderer ----\n"" ); + + #ifdef USE_RENDERER_DLOPEN + cl_renderer = Cvar_Get(""cl_renderer"", ""opengl1"", CVAR_ARCHIVE | CVAR_LATCH | CVAR_PROTECTED); + + Com_sprintf(dllName, sizeof(dllName), ""renderer_mp_%s_"" ARCH_STRING DLL_EXT, cl_renderer->string); + + if(!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString)) + { + Com_Printf(""failed:\n\""%s\""\n"", Sys_LibraryError()); + Cvar_ForceReset(""cl_renderer""); + + Com_sprintf(dllName, sizeof(dllName), ""renderer_mp_opengl1_"" ARCH_STRING DLL_EXT); + rendererLib = Sys_LoadDll(dllName, qfalse); + } + + if(!rendererLib) + { + Com_Printf(""failed:\n\""%s\""\n"", Sys_LibraryError()); + Com_Error(ERR_FATAL, ""Failed to load renderer""); + } + + GetRefAPI = Sys_LoadFunction(rendererLib, ""GetRefAPI""); + if(!GetRefAPI) + { + Com_Error(ERR_FATAL, ""Can't load symbol GetRefAPI: '%s'"", Sys_LibraryError()); + } +#endif + + ri.Cmd_AddCommand = Cmd_AddCommand; + ri.Cmd_RemoveCommand = Cmd_RemoveCommand; + ri.Cmd_Argc = Cmd_Argc; + ri.Cmd_Argv = Cmd_Argv; + ri.Cmd_ExecuteText = Cbuf_ExecuteText; + ri.Printf = CL_RefPrintf; + ri.Error = Com_Error; + ri.Milliseconds = CL_ScaledMilliseconds; +#ifdef ZONE_DEBUG + ri.Z_MallocDebug = CL_RefMallocDebug; +#else + ri.Z_Malloc = CL_RefMalloc; +#endif + ri.Free = Z_Free; + ri.Tag_Free = CL_RefTagFree; + ri.Hunk_Clear = Hunk_ClearToMark; +#ifdef HUNK_DEBUG + ri.Hunk_AllocDebug = Hunk_AllocDebug; +#else + ri.Hunk_Alloc = Hunk_Alloc; +#endif + ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory; + ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory; + + ri.CM_ClusterPVS = CM_ClusterPVS; + ri.CM_DrawDebugSurface = CM_DrawDebugSurface; + ri.FS_ReadFile = FS_ReadFile; + ri.FS_FreeFile = FS_FreeFile; + ri.FS_WriteFile = FS_WriteFile; + ri.FS_FreeFileList = FS_FreeFileList; + ri.FS_ListFiles = FS_ListFiles; + ri.FS_FileIsInPAK = FS_FileIsInPAK; + ri.FS_FileExists = FS_FileExists; + ri.Cvar_Get = Cvar_Get; + ri.Cvar_Set = Cvar_Set; + ri.Cvar_SetValue = Cvar_SetValue; + ri.Cvar_CheckRange = Cvar_CheckRange; + ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue; + + + ri.CIN_UploadCinematic = CIN_UploadCinematic; + ri.CIN_PlayCinematic = CIN_PlayCinematic; + ri.CIN_RunCinematic = CIN_RunCinematic; + + ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame; + + ri.IN_Init = IN_Init; + ri.IN_Shutdown = IN_Shutdown; + ri.IN_Restart = IN_Restart; + + ri.ftol = Q_ftol; + + ri.Sys_SetEnv = Sys_SetEnv; + ri.Sys_GLimpSafeInit = Sys_GLimpSafeInit; + ri.Sys_GLimpInit = Sys_GLimpInit; + ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory; + + ret = GetRefAPI( REF_API_VERSION, &ri ); + + if ( !ret ) { + Com_Error( ERR_FATAL, ""Couldn't initialize refresh"" ); + } + + re = *ret; + + Com_Printf( ""---- Renderer Initialization Complete ----\n"" ); + + Cvar_Set( ""cl_paused"", ""0"" ); +} +","@@ -3674,7 +3674,7 @@ void CL_InitRef( void ) { + Com_Printf( ""----- Initializing Renderer ----\n"" ); + + #ifdef USE_RENDERER_DLOPEN +- cl_renderer = Cvar_Get(""cl_renderer"", ""opengl1"", CVAR_ARCHIVE | CVAR_LATCH); ++ cl_renderer = Cvar_Get(""cl_renderer"", ""opengl1"", CVAR_ARCHIVE | CVAR_LATCH | CVAR_PROTECTED); + + Com_sprintf(dllName, sizeof(dllName), ""renderer_mp_%s_"" ARCH_STRING DLL_EXT, cl_renderer->string); + +@@ -4014,7 +4014,7 @@ void CL_Init( void ) { + + cl_allowDownload = Cvar_Get( ""cl_allowDownload"", ""1"", CVAR_ARCHIVE ); + #ifdef USE_CURL_DLOPEN +- cl_cURLLib = Cvar_Get(""cl_cURLLib"", DEFAULT_CURL_LIB, CVAR_ARCHIVE); ++ cl_cURLLib = Cvar_Get(""cl_cURLLib"", DEFAULT_CURL_LIB, CVAR_ARCHIVE | CVAR_PROTECTED); + #endif + + // init autoswitch so the ui will have it correctly even",918,1249,2048 +7877,"static int StreamTcpTest02 (void) +{ + Packet *p = SCMalloc(SIZE_OF_PACKET); + FAIL_IF(unlikely(p == NULL)); + Flow f; + ThreadVars tv; + StreamTcpThread stt; + uint8_t payload[4]; + TCPHdr tcph; + PacketQueue pq; + memset(&pq,0,sizeof(PacketQueue)); + memset(p, 0, SIZE_OF_PACKET); + memset (&f, 0, sizeof(Flow)); + memset(&tv, 0, sizeof (ThreadVars)); + memset(&stt, 0, sizeof (StreamTcpThread)); + memset(&tcph, 0, sizeof (TCPHdr)); + + FLOW_INITIALIZE(&f); + p->flow = &f; + tcph.th_win = htons(5480); + tcph.th_flags = TH_SYN; + p->tcph = &tcph; + p->flowflags = FLOW_PKT_TOSERVER; + + StreamTcpUTInit(&stt.ra_ctx); + + FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1); + + p->tcph->th_ack = htonl(1); + p->tcph->th_flags = TH_SYN | TH_ACK; + p->flowflags = FLOW_PKT_TOCLIENT; + + FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1); + + p->tcph->th_ack = htonl(1); + p->tcph->th_seq = htonl(1); + p->tcph->th_flags = TH_ACK; + p->flowflags = FLOW_PKT_TOSERVER; + + FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1); + + p->tcph->th_ack = htonl(1); + p->tcph->th_seq = htonl(2); + p->tcph->th_flags = TH_PUSH | TH_ACK; + p->flowflags = FLOW_PKT_TOSERVER; + + StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/ + p->payload = payload; + p->payload_len = 3; + + FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1); + + p->flowflags = FLOW_PKT_TOCLIENT; + FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1); + + p->tcph->th_ack = htonl(1); + p->tcph->th_seq = htonl(6); + p->tcph->th_flags = TH_PUSH | TH_ACK; + p->flowflags = FLOW_PKT_TOSERVER; + + StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/ + p->payload = payload; + p->payload_len = 3; + + FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1); + + p->flowflags = FLOW_PKT_TOCLIENT; + FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1); + + StreamTcpSessionClear(p->flow->protoctx); + + SCFree(p); + FLOW_DESTROY(&f); + StreamTcpUTDeinit(stt.ra_ctx); + PASS; +} +",0,"static int StreamTcpTest02 (void) +{ + Packet *p = SCMalloc(SIZE_OF_PACKET); + FAIL_IF(unlikely(p == NULL)); + Flow f; + ThreadVars tv; + StreamTcpThread stt; + uint8_t payload[4]; + TCPHdr tcph; + PacketQueue pq; + memset(&pq,0,sizeof(PacketQueue)); + memset(p, 0, SIZE_OF_PACKET); + memset (&f, 0, sizeof(Flow)); + memset(&tv, 0, sizeof (ThreadVars)); + memset(&stt, 0, sizeof (StreamTcpThread)); + memset(&tcph, 0, sizeof (TCPHdr)); + + FLOW_INITIALIZE(&f); + p->flow = &f; + tcph.th_win = htons(5480); + tcph.th_flags = TH_SYN; + p->tcph = &tcph; + p->flowflags = FLOW_PKT_TOSERVER; + + StreamTcpUTInit(&stt.ra_ctx); + + FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1); + + p->tcph->th_ack = htonl(1); + p->tcph->th_flags = TH_SYN | TH_ACK; + p->flowflags = FLOW_PKT_TOCLIENT; + + FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1); + + p->tcph->th_ack = htonl(1); + p->tcph->th_seq = htonl(1); + p->tcph->th_flags = TH_ACK; + p->flowflags = FLOW_PKT_TOSERVER; + + FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1); + + p->tcph->th_ack = htonl(1); + p->tcph->th_seq = htonl(2); + p->tcph->th_flags = TH_PUSH | TH_ACK; + p->flowflags = FLOW_PKT_TOSERVER; + + StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/ + p->payload = payload; + p->payload_len = 3; + + FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1); + + p->flowflags = FLOW_PKT_TOCLIENT; + FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1); + + p->tcph->th_ack = htonl(1); + p->tcph->th_seq = htonl(6); + p->tcph->th_flags = TH_PUSH | TH_ACK; + p->flowflags = FLOW_PKT_TOSERVER; + + StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/ + p->payload = payload; + p->payload_len = 3; + + FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1); + + p->flowflags = FLOW_PKT_TOCLIENT; + FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1); + + StreamTcpSessionClear(p->flow->protoctx); + + SCFree(p); + FLOW_DESTROY(&f); + StreamTcpUTDeinit(stt.ra_ctx); + PASS; +} +","@@ -105,6 +105,9 @@ static int StreamTcpValidateTimestamp(TcpSession * , Packet *); + static int StreamTcpHandleTimestamp(TcpSession * , Packet *); + static int StreamTcpValidateRst(TcpSession * , Packet *); + static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *, Packet *); ++static int StreamTcpStateDispatch(ThreadVars *tv, Packet *p, ++ StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq, ++ uint8_t state); + + extern int g_detect_disabled; + +@@ -737,6 +740,7 @@ static void StreamTcpPacketSetState(Packet *p, TcpSession *ssn, + if (state == ssn->state || PKT_IS_PSEUDOPKT(p)) + return; + ++ ssn->pstate = ssn->state; + ssn->state = state; + + /* update the flow state */ +@@ -1375,11 +1379,16 @@ static int StreamTcpPacketStateSynSent(ThreadVars *tv, Packet *p, + SEQ_EQ(TCP_GET_WINDOW(p), 0) && + SEQ_EQ(TCP_GET_ACK(p), (ssn->client.isn + 1))) + { ++ SCLogDebug(""ssn->server.flags |= STREAMTCP_STREAM_FLAG_RST_RECV""); ++ ssn->server.flags |= STREAMTCP_STREAM_FLAG_RST_RECV; ++ + StreamTcpPacketSetState(p, ssn, TCP_CLOSED); + SCLogDebug(""ssn %p: Reset received and state changed to "" + ""TCP_CLOSED"", ssn); + } + } else { ++ ssn->client.flags |= STREAMTCP_STREAM_FLAG_RST_RECV; ++ SCLogDebug(""ssn->client.flags |= STREAMTCP_STREAM_FLAG_RST_RECV""); + StreamTcpPacketSetState(p, ssn, TCP_CLOSED); + SCLogDebug(""ssn %p: Reset received and state changed to "" + ""TCP_CLOSED"", ssn); +@@ -4231,6 +4240,68 @@ static int StreamTcpPacketStateTimeWait(ThreadVars *tv, Packet *p, + return 0; + } + ++static int StreamTcpPacketStateClosed(ThreadVars *tv, Packet *p, ++ StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq) ++{ ++ if (ssn == NULL) ++ return -1; ++ ++ if (p->tcph->th_flags & TH_RST) { ++ SCLogDebug(""RST on closed state""); ++ return 0; ++ } ++ ++ TcpStream *stream = NULL, *ostream = NULL; ++ if (PKT_IS_TOSERVER(p)) { ++ stream = &ssn->client; ++ ostream = &ssn->server; ++ } else { ++ stream = &ssn->server; ++ ostream = &ssn->client; ++ } ++ ++ SCLogDebug(""stream %s ostream %s"", ++ stream->flags & STREAMTCP_STREAM_FLAG_RST_RECV?""true"":""false"", ++ ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV ? ""true"":""false""); ++ ++ /* if we've seen a RST on our direction, but not on the other ++ * see if we perhaps need to continue processing anyway. */ ++ if ((stream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) == 0) { ++ if (ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) { ++ if (StreamTcpStateDispatch(tv, p, stt, ssn, &stt->pseudo_queue, ssn->pstate) < 0) ++ return -1; ++ } ++ } ++ return 0; ++} ++ ++static void StreamTcpPacketCheckPostRst(TcpSession *ssn, Packet *p) ++{ ++ if (p->flags & PKT_PSEUDO_STREAM_END) { ++ return; ++ } ++ /* more RSTs are not unusual */ ++ if ((p->tcph->th_flags & (TH_RST)) != 0) { ++ return; ++ } ++ ++ TcpStream *ostream = NULL; ++ if (PKT_IS_TOSERVER(p)) { ++ ostream = &ssn->server; ++ } else { ++ ostream = &ssn->client; ++ } ++ ++ if (ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) { ++ SCLogDebug(""regular packet %""PRIu64"" from same sender as "" ++ ""the previous RST. Looks like it injected!"", p->pcap_cnt); ++ ostream->flags &= ~STREAMTCP_STREAM_FLAG_RST_RECV; ++ StreamTcpSetEvent(p, STREAM_SUSPECTED_RST_INJECT); ++ return; ++ } ++ return; ++} ++ + /** + * \retval 1 packet is a keep alive pkt + * \retval 0 packet is not a keep alive pkt +@@ -4515,6 +4586,76 @@ static int StreamTcpPacketIsBadWindowUpdate(TcpSession *ssn, Packet *p) + return 0; + } + ++/** \internal ++ * \brief call packet handling function for 'state' ++ * \param state current TCP state ++ */ ++static inline int StreamTcpStateDispatch(ThreadVars *tv, Packet *p, ++ StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq, ++ const uint8_t state) ++{ ++ switch (state) { ++ case TCP_SYN_SENT: ++ if (StreamTcpPacketStateSynSent(tv, p, stt, ssn, pq)) { ++ return -1; ++ } ++ break; ++ case TCP_SYN_RECV: ++ if (StreamTcpPacketStateSynRecv(tv, p, stt, ssn, pq)) { ++ return -1; ++ } ++ break; ++ case TCP_ESTABLISHED: ++ if (StreamTcpPacketStateEstablished(tv, p, stt, ssn, pq)) { ++ return -1; ++ } ++ break; ++ case TCP_FIN_WAIT1: ++ if (StreamTcpPacketStateFinWait1(tv, p, stt, ssn, pq)) { ++ return -1; ++ } ++ break; ++ case TCP_FIN_WAIT2: ++ if (StreamTcpPacketStateFinWait2(tv, p, stt, ssn, pq)) { ++ return -1; ++ } ++ break; ++ case TCP_CLOSING: ++ if (StreamTcpPacketStateClosing(tv, p, stt, ssn, pq)) { ++ return -1; ++ } ++ break; ++ case TCP_CLOSE_WAIT: ++ if (StreamTcpPacketStateCloseWait(tv, p, stt, ssn, pq)) { ++ return -1; ++ } ++ break; ++ case TCP_LAST_ACK: ++ if (StreamTcpPacketStateLastAck(tv, p, stt, ssn, pq)) { ++ return -1; ++ } ++ break; ++ case TCP_TIME_WAIT: ++ if (StreamTcpPacketStateTimeWait(tv, p, stt, ssn, pq)) { ++ return -1; ++ } ++ break; ++ case TCP_CLOSED: ++ /* TCP session memory is not returned to pool until timeout. */ ++ SCLogDebug(""packet received on closed state""); ++ ++ if (StreamTcpPacketStateClosed(tv, p, stt, ssn, pq)) { ++ return -1; ++ } ++ ++ break; ++ default: ++ SCLogDebug(""packet received on default state""); ++ break; ++ } ++ return 0; ++} ++ + /* flow is and stays locked */ + int StreamTcpPacket (ThreadVars *tv, Packet *p, StreamTcpThread *stt, + PacketQueue *pq) +@@ -4630,61 +4771,12 @@ int StreamTcpPacket (ThreadVars *tv, Packet *p, StreamTcpThread *stt, + if (StreamTcpPacketIsBadWindowUpdate(ssn,p)) + goto skip; + +- switch (ssn->state) { +- case TCP_SYN_SENT: +- if(StreamTcpPacketStateSynSent(tv, p, stt, ssn, &stt->pseudo_queue)) { +- goto error; +- } +- break; +- case TCP_SYN_RECV: +- if(StreamTcpPacketStateSynRecv(tv, p, stt, ssn, &stt->pseudo_queue)) { +- goto error; +- } +- break; +- case TCP_ESTABLISHED: +- if(StreamTcpPacketStateEstablished(tv, p, stt, ssn, &stt->pseudo_queue)) { +- goto error; +- } +- break; +- case TCP_FIN_WAIT1: +- if(StreamTcpPacketStateFinWait1(tv, p, stt, ssn, &stt->pseudo_queue)) { +- goto error; +- } +- break; +- case TCP_FIN_WAIT2: +- if(StreamTcpPacketStateFinWait2(tv, p, stt, ssn, &stt->pseudo_queue)) { +- goto error; +- } +- break; +- case TCP_CLOSING: +- if(StreamTcpPacketStateClosing(tv, p, stt, ssn, &stt->pseudo_queue)) { +- goto error; +- } +- break; +- case TCP_CLOSE_WAIT: +- if(StreamTcpPacketStateCloseWait(tv, p, stt, ssn, &stt->pseudo_queue)) { +- goto error; +- } +- break; +- case TCP_LAST_ACK: +- if(StreamTcpPacketStateLastAck(tv, p, stt, ssn, &stt->pseudo_queue)) { +- goto error; +- } +- break; +- case TCP_TIME_WAIT: +- if(StreamTcpPacketStateTimeWait(tv, p, stt, ssn, &stt->pseudo_queue)) { +- goto error; +- } +- break; +- case TCP_CLOSED: +- /* TCP session memory is not returned to pool until timeout. */ +- SCLogDebug(""packet received on closed state""); +- break; +- default: +- SCLogDebug(""packet received on default state""); +- break; +- } ++ /* handle the per 'state' logic */ ++ if (StreamTcpStateDispatch(tv, p, stt, ssn, &stt->pseudo_queue, ssn->state) < 0) ++ goto error; ++ + skip: ++ StreamTcpPacketCheckPostRst(ssn, p); + + if (ssn->state >= TCP_ESTABLISHED) { + p->flags |= PKT_STREAM_EST;",710,1041,2048 +17522,"int start_input_stream(struct stream_in *in) +{ + /* Enable output device and stream routing controls */ + int ret = 0; + bool recreate_resampler = false; + struct audio_usecase *uc_info; + struct audio_device *adev = in->dev; + struct pcm_device_profile *pcm_profile; + struct pcm_device *pcm_device; + + ALOGV(""%s: enter: usecase(%d)"", __func__, in->usecase); + adev->active_input = in; + pcm_profile = get_pcm_device(in->usecase_type, in->devices); + if (pcm_profile == NULL) { + ALOGE(""%s: Could not find PCM device id for the usecase(%d)"", + __func__, in->usecase); + ret = -EINVAL; + goto error_config; + } + + if (in->input_flags & AUDIO_INPUT_FLAG_FAST) { + ALOGV(""%s: change capture period size to low latency size %d"", + __func__, CAPTURE_PERIOD_SIZE_LOW_LATENCY); + pcm_profile->config.period_size = CAPTURE_PERIOD_SIZE_LOW_LATENCY; + } + + uc_info = (struct audio_usecase *)calloc(1, sizeof(struct audio_usecase)); + uc_info->id = in->usecase; + uc_info->type = PCM_CAPTURE; + uc_info->stream = (struct audio_stream *)in; + uc_info->devices = in->devices; + uc_info->in_snd_device = SND_DEVICE_NONE; + uc_info->out_snd_device = SND_DEVICE_NONE; + + pcm_device = (struct pcm_device *)calloc(1, sizeof(struct pcm_device)); + pcm_device->pcm_profile = pcm_profile; + list_init(&in->pcm_dev_list); + list_add_tail(&in->pcm_dev_list, &pcm_device->stream_list_node); + + list_init(&uc_info->mixer_list); + list_add_tail(&uc_info->mixer_list, + &adev_get_mixer_for_card(adev, + pcm_device->pcm_profile->card)->uc_list_node[uc_info->id]); + + list_add_tail(&adev->usecase_list, &uc_info->adev_list_node); + + select_devices(adev, in->usecase); + + /* Config should be updated as profile can be changed between different calls + * to this function: + * - Trigger resampler creation + * - Config needs to be updated */ + if (in->config.rate != pcm_profile->config.rate) { + recreate_resampler = true; + } + in->config = pcm_profile->config; + +#ifdef PREPROCESSING_ENABLED + if (in->aux_channels_changed) { + in->config.channels = audio_channel_count_from_in_mask(in->aux_channels); + recreate_resampler = true; + } +#endif + + if (in->requested_rate != in->config.rate) { + recreate_resampler = true; + } + + if (recreate_resampler) { + if (in->resampler) { + release_resampler(in->resampler); + in->resampler = NULL; + } + in->buf_provider.get_next_buffer = get_next_buffer; + in->buf_provider.release_buffer = release_buffer; + ret = create_resampler(in->config.rate, + in->requested_rate, + in->config.channels, + RESAMPLER_QUALITY_DEFAULT, + &in->buf_provider, + &in->resampler); + } + + /* Open the PCM device. + * The HW is limited to support only the default pcm_profile settings. + * As such a change in aux_channels will not have an effect. + */ + ALOGV(""%s: Opening PCM device card_id(%d) device_id(%d), channels %d, smp rate %d format %d, \ + period_size %d"", __func__, pcm_device->pcm_profile->card, pcm_device->pcm_profile->device, + pcm_device->pcm_profile->config.channels,pcm_device->pcm_profile->config.rate, + pcm_device->pcm_profile->config.format, pcm_device->pcm_profile->config.period_size); + + if (pcm_profile->type == PCM_HOTWORD_STREAMING) { + if (!adev->sound_trigger_open_for_streaming) { + ALOGE(""%s: No handle to sound trigger HAL"", __func__); + ret = -EIO; + goto error_open; + } + pcm_device->pcm = NULL; + pcm_device->sound_trigger_handle = + adev->sound_trigger_open_for_streaming(); + if (pcm_device->sound_trigger_handle <= 0) { + ALOGE(""%s: Failed to open DSP for streaming"", __func__); + ret = -EIO; + goto error_open; + } + ALOGV(""Opened DSP successfully""); + } else { + pcm_device->sound_trigger_handle = 0; + pcm_device->pcm = pcm_open(pcm_device->pcm_profile->card, + pcm_device->pcm_profile->device, + PCM_IN | PCM_MONOTONIC, + &pcm_device->pcm_profile->config); + if (pcm_device->pcm && !pcm_is_ready(pcm_device->pcm)) { + ALOGE(""%s: %s"", __func__, pcm_get_error(pcm_device->pcm)); + pcm_close(pcm_device->pcm); + pcm_device->pcm = NULL; + ret = -EIO; + goto error_open; + } + } + + /* force read and proc buffer reallocation in case of frame size or + * channel count change */ +#ifdef PREPROCESSING_ENABLED + in->proc_buf_frames = 0; +#endif + in->proc_buf_size = 0; + in->read_buf_size = 0; + in->read_buf_frames = 0; + + /* if no supported sample rate is available, use the resampler */ + if (in->resampler) { + in->resampler->reset(in->resampler); + } + + ALOGV(""%s: exit"", __func__); + return ret; + +error_open: + if (in->resampler) { + release_resampler(in->resampler); + in->resampler = NULL; + } + stop_input_stream(in); + +error_config: + ALOGV(""%s: exit: status(%d)"", __func__, ret); + adev->active_input = NULL; + return ret; +} +",0,"int start_input_stream(struct stream_in *in) +{ + /* Enable output device and stream routing controls */ + int ret = 0; + bool recreate_resampler = false; + struct audio_usecase *uc_info; + struct audio_device *adev = in->dev; + struct pcm_device_profile *pcm_profile; + struct pcm_device *pcm_device; + + ALOGV(""%s: enter: usecase(%d)"", __func__, in->usecase); + adev->active_input = in; + pcm_profile = get_pcm_device(in->usecase_type, in->devices); + if (pcm_profile == NULL) { + ALOGE(""%s: Could not find PCM device id for the usecase(%d)"", + __func__, in->usecase); + ret = -EINVAL; + goto error_config; + } + + if (in->input_flags & AUDIO_INPUT_FLAG_FAST) { + ALOGV(""%s: change capture period size to low latency size %d"", + __func__, CAPTURE_PERIOD_SIZE_LOW_LATENCY); + pcm_profile->config.period_size = CAPTURE_PERIOD_SIZE_LOW_LATENCY; + } + + uc_info = (struct audio_usecase *)calloc(1, sizeof(struct audio_usecase)); + uc_info->id = in->usecase; + uc_info->type = PCM_CAPTURE; + uc_info->stream = (struct audio_stream *)in; + uc_info->devices = in->devices; + uc_info->in_snd_device = SND_DEVICE_NONE; + uc_info->out_snd_device = SND_DEVICE_NONE; + + pcm_device = (struct pcm_device *)calloc(1, sizeof(struct pcm_device)); + pcm_device->pcm_profile = pcm_profile; + list_init(&in->pcm_dev_list); + list_add_tail(&in->pcm_dev_list, &pcm_device->stream_list_node); + + list_init(&uc_info->mixer_list); + list_add_tail(&uc_info->mixer_list, + &adev_get_mixer_for_card(adev, + pcm_device->pcm_profile->card)->uc_list_node[uc_info->id]); + + list_add_tail(&adev->usecase_list, &uc_info->adev_list_node); + + select_devices(adev, in->usecase); + + /* Config should be updated as profile can be changed between different calls + * to this function: + * - Trigger resampler creation + * - Config needs to be updated */ + if (in->config.rate != pcm_profile->config.rate) { + recreate_resampler = true; + } + in->config = pcm_profile->config; + +#ifdef PREPROCESSING_ENABLED + if (in->aux_channels_changed) { + in->config.channels = audio_channel_count_from_in_mask(in->aux_channels); + recreate_resampler = true; + } +#endif + + if (in->requested_rate != in->config.rate) { + recreate_resampler = true; + } + + if (recreate_resampler) { + if (in->resampler) { + release_resampler(in->resampler); + in->resampler = NULL; + } + in->buf_provider.get_next_buffer = get_next_buffer; + in->buf_provider.release_buffer = release_buffer; + ret = create_resampler(in->config.rate, + in->requested_rate, + in->config.channels, + RESAMPLER_QUALITY_DEFAULT, + &in->buf_provider, + &in->resampler); + } + + /* Open the PCM device. + * The HW is limited to support only the default pcm_profile settings. + * As such a change in aux_channels will not have an effect. + */ + ALOGV(""%s: Opening PCM device card_id(%d) device_id(%d), channels %d, smp rate %d format %d, \ + period_size %d"", __func__, pcm_device->pcm_profile->card, pcm_device->pcm_profile->device, + pcm_device->pcm_profile->config.channels,pcm_device->pcm_profile->config.rate, + pcm_device->pcm_profile->config.format, pcm_device->pcm_profile->config.period_size); + + if (pcm_profile->type == PCM_HOTWORD_STREAMING) { + if (!adev->sound_trigger_open_for_streaming) { + ALOGE(""%s: No handle to sound trigger HAL"", __func__); + ret = -EIO; + goto error_open; + } + pcm_device->pcm = NULL; + pcm_device->sound_trigger_handle = + adev->sound_trigger_open_for_streaming(); + if (pcm_device->sound_trigger_handle <= 0) { + ALOGE(""%s: Failed to open DSP for streaming"", __func__); + ret = -EIO; + goto error_open; + } + ALOGV(""Opened DSP successfully""); + } else { + pcm_device->sound_trigger_handle = 0; + pcm_device->pcm = pcm_open(pcm_device->pcm_profile->card, + pcm_device->pcm_profile->device, + PCM_IN | PCM_MONOTONIC, + &pcm_device->pcm_profile->config); + if (pcm_device->pcm && !pcm_is_ready(pcm_device->pcm)) { + ALOGE(""%s: %s"", __func__, pcm_get_error(pcm_device->pcm)); + pcm_close(pcm_device->pcm); + pcm_device->pcm = NULL; + ret = -EIO; + goto error_open; + } + } + + /* force read and proc buffer reallocation in case of frame size or + * channel count change */ +#ifdef PREPROCESSING_ENABLED + in->proc_buf_frames = 0; +#endif + in->proc_buf_size = 0; + in->read_buf_size = 0; + in->read_buf_frames = 0; + + /* if no supported sample rate is available, use the resampler */ + if (in->resampler) { + in->resampler->reset(in->resampler); + } + + ALOGV(""%s: exit"", __func__); + return ret; + +error_open: + if (in->resampler) { + release_resampler(in->resampler); + in->resampler = NULL; + } + stop_input_stream(in); + +error_config: + ALOGV(""%s: exit: status(%d)"", __func__, ret); + adev->active_input = NULL; + return ret; +} +","@@ -1023,12 +1023,7 @@ + + ssize_t frames_wr = 0; /* Number of frames actually read */ + size_t bytes_per_sample = audio_bytes_per_sample(stream->common.get_format(&stream->common)); + void *proc_buf_out = buffer; +-#ifdef PREPROCESSING_ENABLED +- audio_buffer_t in_buf; +- audio_buffer_t out_buf; +- int i; +- bool has_processing = in->num_preprocessors != 0; +-#endif ++ + /* Additional channels might be added on top of main_channels: + * - aux_channels (by processing effects) + * - extra channels due to HW limitations +@@ -1037,7 +1032,34 @@ + + size_t src_channels = in->config.channels; + size_t dst_channels = audio_channel_count_from_in_mask(in->main_channels); + bool channel_remapping_needed = (dst_channels != src_channels); +- size_t src_buffer_size = frames_num * src_channels * bytes_per_sample; ++ const size_t src_frame_size = src_channels * bytes_per_sample; ++ ++#ifdef PREPROCESSING_ENABLED ++ const bool has_processing = in->num_preprocessors != 0; ++#else ++ const bool has_processing = false; ++#endif ++ ++ /* With additional channels or processing, we need intermediate buffers */ ++ if (channel_remapping_needed || has_processing) { ++ const size_t src_buffer_size = frames_num * src_frame_size; ++ ++ if (in->proc_buf_size < src_buffer_size) { ++ in->proc_buf_size = src_buffer_size; ++#ifdef PREPROCESSING_ENABLED ++ /* we always reallocate both buffers in case # of effects change dynamically. */ ++ in->proc_buf_in = realloc(in->proc_buf_in, src_buffer_size); ++ ALOG_ASSERT((in->proc_buf_in != NULL), ++ ""process_frames() failed to reallocate proc_buf_in""); ++#endif ++ in->proc_buf_out = realloc(in->proc_buf_out, src_buffer_size); ++ ALOG_ASSERT((in->proc_buf_out != NULL), ++ ""process_frames() failed to reallocate proc_buf_out""); ++ } ++ if (channel_remapping_needed) { ++ proc_buf_out = in->proc_buf_out; ++ } ++ } + + #ifdef PREPROCESSING_ENABLED + if (has_processing) { +@@ -1046,24 +1068,10 @@ + + while (frames_wr < frames_num) { + /* first reload enough frames at the end of process input buffer */ + if (in->proc_buf_frames < (size_t)frames_num) { +- ssize_t frames_rd; +- if (in->proc_buf_size < (size_t)frames_num) { +- in->proc_buf_size = (size_t)frames_num; +- in->proc_buf_in = realloc(in->proc_buf_in, src_buffer_size); +- ALOG_ASSERT((in->proc_buf_in != NULL), +- ""process_frames() failed to reallocate proc_buf_in""); +- if (channel_remapping_needed) { +- in->proc_buf_out = realloc(in->proc_buf_out, src_buffer_size); +- ALOG_ASSERT((in->proc_buf_out != NULL), +- ""process_frames() failed to reallocate proc_buf_out""); +- proc_buf_out = in->proc_buf_out; +- } +- } +- frames_rd = read_frames(in, +- in->proc_buf_in + +- in->proc_buf_frames * src_channels * bytes_per_sample, +- frames_num - in->proc_buf_frames); +- if (frames_rd < 0) { ++ ssize_t frames_rd = read_frames(in, ++ (char *)in->proc_buf_in + in->proc_buf_frames * src_frame_size, ++ frames_num - in->proc_buf_frames); ++ if (frames_rd < 0) { + /* Return error code */ + frames_wr = frames_rd; + break; +@@ -1073,17 +1081,20 @@ + + + /* in_buf.frameCount and out_buf.frameCount indicate respectively + * the maximum number of frames to be consumed and produced by process() */ ++ audio_buffer_t in_buf; ++ audio_buffer_t out_buf; ++ + in_buf.frameCount = in->proc_buf_frames; +- in_buf.s16 = in->proc_buf_in; ++ in_buf.s16 = in->proc_buf_in; /* currently assumes PCM 16 effects */ + out_buf.frameCount = frames_num - frames_wr; +- out_buf.s16 = (int16_t *)proc_buf_out + frames_wr * in->config.channels; ++ out_buf.s16 = (int16_t *)proc_buf_out + frames_wr * src_channels; + + /* FIXME: this works because of current pre processing library implementation that + * does the actual process only when the last enabled effect process is called. + * The generic solution is to have an output buffer for each effect and pass it as + * input to the next. + */ +- for (i = 0; i < in->num_preprocessors; i++) { ++ for (int i = 0; i < in->num_preprocessors; i++) { + (*in->preprocessors[i].effect_itfe)->process(in->preprocessors[i].effect_itfe, + &in_buf, + &out_buf); +@@ -1096,8 +1107,8 @@ + + + if (in->proc_buf_frames) { + memcpy(in->proc_buf_in, +- in->proc_buf_in + in_buf.frameCount * src_channels * bytes_per_sample, +- in->proc_buf_frames * in->config.channels * audio_bytes_per_sample(in_get_format(in))); ++ (char *)in->proc_buf_in + in_buf.frameCount * src_frame_size, ++ in->proc_buf_frames * src_frame_size); + } + + /* if not enough frames were passed to process(), read more and retry. */ +@@ -1120,23 +1131,14 @@ + + #endif //PREPROCESSING_ENABLED + { + /* No processing effects attached */ +- if (channel_remapping_needed) { +- /* With additional channels, we cannot use original buffer */ +- if (in->proc_buf_size < src_buffer_size) { +- in->proc_buf_size = src_buffer_size; +- in->proc_buf_out = realloc(in->proc_buf_out, src_buffer_size); +- ALOG_ASSERT((in->proc_buf_out != NULL), +- ""process_frames() failed to reallocate proc_buf_out""); +- } +- proc_buf_out = in->proc_buf_out; +- } + frames_wr = read_frames(in, proc_buf_out, frames_num); + ALOG_ASSERT(frames_wr <= frames_num, ""read more frames than requested""); + } + +- if (channel_remapping_needed) { ++ /* check negative frames_wr (error) before channel remapping to avoid overwriting memory. */ ++ if (channel_remapping_needed && frames_wr > 0) { + size_t ret = adjust_channels(proc_buf_out, src_channels, buffer, dst_channels, +- bytes_per_sample, frames_wr * src_channels * bytes_per_sample); ++ bytes_per_sample, frames_wr * src_frame_size); + ALOG_ASSERT(ret == (frames_wr * dst_channels * bytes_per_sample)); + } + +",1265,1596,2048 +17949,"struct sk_buff *skb_segment(struct sk_buff *head_skb, + netdev_features_t features) +{ + struct sk_buff *segs = NULL; + struct sk_buff *tail = NULL; + struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list; + skb_frag_t *frag = skb_shinfo(head_skb)->frags; + unsigned int mss = skb_shinfo(head_skb)->gso_size; + unsigned int doffset = head_skb->data - skb_mac_header(head_skb); + unsigned int offset = doffset; + unsigned int tnl_hlen = skb_tnl_header_len(head_skb); + unsigned int headroom; + unsigned int len; + __be16 proto; + bool csum; + int sg = !!(features & NETIF_F_SG); + int nfrags = skb_shinfo(head_skb)->nr_frags; + int err = -ENOMEM; + int i = 0; + int pos; + + proto = skb_network_protocol(head_skb); + if (unlikely(!proto)) + return ERR_PTR(-EINVAL); + + csum = !!can_checksum_protocol(features, proto); + __skb_push(head_skb, doffset); + headroom = skb_headroom(head_skb); + pos = skb_headlen(head_skb); + + do { + struct sk_buff *nskb; + skb_frag_t *nskb_frag; + int hsize; + int size; + + len = head_skb->len - offset; + if (len > mss) + len = mss; + + hsize = skb_headlen(head_skb) - offset; + if (hsize < 0) + hsize = 0; + if (hsize > len || !sg) + hsize = len; + + if (!hsize && i >= nfrags && skb_headlen(list_skb) && + (skb_headlen(list_skb) == len || sg)) { + BUG_ON(skb_headlen(list_skb) > len); + + i = 0; + nfrags = skb_shinfo(list_skb)->nr_frags; + frag = skb_shinfo(list_skb)->frags; + pos += skb_headlen(list_skb); + + while (pos < offset + len) { + BUG_ON(i >= nfrags); + + size = skb_frag_size(frag); + if (pos + size > offset + len) + break; + + i++; + pos += size; + frag++; + } + + nskb = skb_clone(list_skb, GFP_ATOMIC); + list_skb = list_skb->next; + + if (unlikely(!nskb)) + goto err; + + if (unlikely(pskb_trim(nskb, len))) { + kfree_skb(nskb); + goto err; + } + + hsize = skb_end_offset(nskb); + if (skb_cow_head(nskb, doffset + headroom)) { + kfree_skb(nskb); + goto err; + } + + nskb->truesize += skb_end_offset(nskb) - hsize; + skb_release_head_state(nskb); + __skb_push(nskb, doffset); + } else { + nskb = __alloc_skb(hsize + doffset + headroom, + GFP_ATOMIC, skb_alloc_rx_flag(head_skb), + NUMA_NO_NODE); + + if (unlikely(!nskb)) + goto err; + + skb_reserve(nskb, headroom); + __skb_put(nskb, doffset); + } + + if (segs) + tail->next = nskb; + else + segs = nskb; + tail = nskb; + + __copy_skb_header(nskb, head_skb); + nskb->mac_len = head_skb->mac_len; + + skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom); + + skb_copy_from_linear_data_offset(head_skb, -tnl_hlen, + nskb->data - tnl_hlen, + doffset + tnl_hlen); + + if (nskb->len == len + doffset) + goto perform_csum_check; + + if (!sg) { + nskb->ip_summed = CHECKSUM_NONE; + nskb->csum = skb_copy_and_csum_bits(head_skb, offset, + skb_put(nskb, len), + len, 0); + continue; + } + + nskb_frag = skb_shinfo(nskb)->frags; + + skb_copy_from_linear_data_offset(head_skb, offset, + skb_put(nskb, hsize), hsize); + + skb_shinfo(nskb)->tx_flags = skb_shinfo(head_skb)->tx_flags & + SKBTX_SHARED_FRAG; + + while (pos < offset + len) { + if (i >= nfrags) { + BUG_ON(skb_headlen(list_skb)); + + i = 0; + nfrags = skb_shinfo(list_skb)->nr_frags; + frag = skb_shinfo(list_skb)->frags; + + BUG_ON(!nfrags); + + list_skb = list_skb->next; + } + + if (unlikely(skb_shinfo(nskb)->nr_frags >= + MAX_SKB_FRAGS)) { + net_warn_ratelimited( + ""skb_segment: too many frags: %u %u\n"", + pos, mss); + goto err; + } + + *nskb_frag = *frag; + __skb_frag_ref(nskb_frag); + size = skb_frag_size(nskb_frag); + + if (pos < offset) { + nskb_frag->page_offset += offset - pos; + skb_frag_size_sub(nskb_frag, offset - pos); + } + + skb_shinfo(nskb)->nr_frags++; + + if (pos + size <= offset + len) { + i++; + frag++; + pos += size; + } else { + skb_frag_size_sub(nskb_frag, pos + size - (offset + len)); + goto skip_fraglist; + } + + nskb_frag++; + } + +skip_fraglist: + nskb->data_len = len - hsize; + nskb->len += nskb->data_len; + nskb->truesize += nskb->data_len; + +perform_csum_check: + if (!csum) { + nskb->csum = skb_checksum(nskb, doffset, + nskb->len - doffset, 0); + nskb->ip_summed = CHECKSUM_NONE; + } + } while ((offset += len) < head_skb->len); + + return segs; + +err: + kfree_skb_list(segs); + return ERR_PTR(err); +} +",1,"struct sk_buff *skb_segment(struct sk_buff *head_skb, + netdev_features_t features) +{ + struct sk_buff *segs = NULL; + struct sk_buff *tail = NULL; + struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list; + skb_frag_t *frag = skb_shinfo(head_skb)->frags; + unsigned int mss = skb_shinfo(head_skb)->gso_size; + unsigned int doffset = head_skb->data - skb_mac_header(head_skb); + struct sk_buff *frag_skb = head_skb; + unsigned int offset = doffset; + unsigned int tnl_hlen = skb_tnl_header_len(head_skb); + unsigned int headroom; + unsigned int len; + __be16 proto; + bool csum; + int sg = !!(features & NETIF_F_SG); + int nfrags = skb_shinfo(head_skb)->nr_frags; + int err = -ENOMEM; + int i = 0; + int pos; + + proto = skb_network_protocol(head_skb); + if (unlikely(!proto)) + return ERR_PTR(-EINVAL); + + csum = !!can_checksum_protocol(features, proto); + __skb_push(head_skb, doffset); + headroom = skb_headroom(head_skb); + pos = skb_headlen(head_skb); + + do { + struct sk_buff *nskb; + skb_frag_t *nskb_frag; + int hsize; + int size; + + len = head_skb->len - offset; + if (len > mss) + len = mss; + + hsize = skb_headlen(head_skb) - offset; + if (hsize < 0) + hsize = 0; + if (hsize > len || !sg) + hsize = len; + + if (!hsize && i >= nfrags && skb_headlen(list_skb) && + (skb_headlen(list_skb) == len || sg)) { + BUG_ON(skb_headlen(list_skb) > len); + + i = 0; + nfrags = skb_shinfo(list_skb)->nr_frags; + frag = skb_shinfo(list_skb)->frags; + frag_skb = list_skb; + pos += skb_headlen(list_skb); + + while (pos < offset + len) { + BUG_ON(i >= nfrags); + + size = skb_frag_size(frag); + if (pos + size > offset + len) + break; + + i++; + pos += size; + frag++; + } + + nskb = skb_clone(list_skb, GFP_ATOMIC); + list_skb = list_skb->next; + + if (unlikely(!nskb)) + goto err; + + if (unlikely(pskb_trim(nskb, len))) { + kfree_skb(nskb); + goto err; + } + + hsize = skb_end_offset(nskb); + if (skb_cow_head(nskb, doffset + headroom)) { + kfree_skb(nskb); + goto err; + } + + nskb->truesize += skb_end_offset(nskb) - hsize; + skb_release_head_state(nskb); + __skb_push(nskb, doffset); + } else { + nskb = __alloc_skb(hsize + doffset + headroom, + GFP_ATOMIC, skb_alloc_rx_flag(head_skb), + NUMA_NO_NODE); + + if (unlikely(!nskb)) + goto err; + + skb_reserve(nskb, headroom); + __skb_put(nskb, doffset); + } + + if (segs) + tail->next = nskb; + else + segs = nskb; + tail = nskb; + + __copy_skb_header(nskb, head_skb); + nskb->mac_len = head_skb->mac_len; + + skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom); + + skb_copy_from_linear_data_offset(head_skb, -tnl_hlen, + nskb->data - tnl_hlen, + doffset + tnl_hlen); + + if (nskb->len == len + doffset) + goto perform_csum_check; + + if (!sg) { + nskb->ip_summed = CHECKSUM_NONE; + nskb->csum = skb_copy_and_csum_bits(head_skb, offset, + skb_put(nskb, len), + len, 0); + continue; + } + + nskb_frag = skb_shinfo(nskb)->frags; + + skb_copy_from_linear_data_offset(head_skb, offset, + skb_put(nskb, hsize), hsize); + + skb_shinfo(nskb)->tx_flags = skb_shinfo(head_skb)->tx_flags & + SKBTX_SHARED_FRAG; + + while (pos < offset + len) { + if (i >= nfrags) { + BUG_ON(skb_headlen(list_skb)); + + i = 0; + nfrags = skb_shinfo(list_skb)->nr_frags; + frag = skb_shinfo(list_skb)->frags; + frag_skb = list_skb; + + BUG_ON(!nfrags); + + list_skb = list_skb->next; + } + + if (unlikely(skb_shinfo(nskb)->nr_frags >= + MAX_SKB_FRAGS)) { + net_warn_ratelimited( + ""skb_segment: too many frags: %u %u\n"", + pos, mss); + goto err; + } + + if (unlikely(skb_orphan_frags(frag_skb, GFP_ATOMIC))) + goto err; + + *nskb_frag = *frag; + __skb_frag_ref(nskb_frag); + size = skb_frag_size(nskb_frag); + + if (pos < offset) { + nskb_frag->page_offset += offset - pos; + skb_frag_size_sub(nskb_frag, offset - pos); + } + + skb_shinfo(nskb)->nr_frags++; + + if (pos + size <= offset + len) { + i++; + frag++; + pos += size; + } else { + skb_frag_size_sub(nskb_frag, pos + size - (offset + len)); + goto skip_fraglist; + } + + nskb_frag++; + } + +skip_fraglist: + nskb->data_len = len - hsize; + nskb->len += nskb->data_len; + nskb->truesize += nskb->data_len; + +perform_csum_check: + if (!csum) { + nskb->csum = skb_checksum(nskb, doffset, + nskb->len - doffset, 0); + nskb->ip_summed = CHECKSUM_NONE; + } + } while ((offset += len) < head_skb->len); + + return segs; + +err: + kfree_skb_list(segs); + return ERR_PTR(err); +} +","@@ -2854,6 +2854,7 @@ struct sk_buff *skb_segment(struct sk_buff *head_skb, + skb_frag_t *frag = skb_shinfo(head_skb)->frags; + unsigned int mss = skb_shinfo(head_skb)->gso_size; + unsigned int doffset = head_skb->data - skb_mac_header(head_skb); ++ struct sk_buff *frag_skb = head_skb; + unsigned int offset = doffset; + unsigned int tnl_hlen = skb_tnl_header_len(head_skb); + unsigned int headroom; +@@ -2898,6 +2899,7 @@ struct sk_buff *skb_segment(struct sk_buff *head_skb, + i = 0; + nfrags = skb_shinfo(list_skb)->nr_frags; + frag = skb_shinfo(list_skb)->frags; ++ frag_skb = list_skb; + pos += skb_headlen(list_skb); + + while (pos < offset + len) { +@@ -2985,6 +2987,7 @@ struct sk_buff *skb_segment(struct sk_buff *head_skb, + i = 0; + nfrags = skb_shinfo(list_skb)->nr_frags; + frag = skb_shinfo(list_skb)->frags; ++ frag_skb = list_skb; + + BUG_ON(!nfrags); + +@@ -2999,6 +3002,9 @@ struct sk_buff *skb_segment(struct sk_buff *head_skb, + goto err; + } + ++ if (unlikely(skb_orphan_frags(frag_skb, GFP_ATOMIC))) ++ goto err; ++ + *nskb_frag = *frag; + __skb_frag_ref(nskb_frag); + size = skb_frag_size(nskb_frag);",1388,1719,2048 +3873,"static int logi_dj_probe(struct hid_device *hdev, + const struct hid_device_id *id) +{ + struct usb_interface *intf = to_usb_interface(hdev->dev.parent); + struct dj_receiver_dev *djrcv_dev; + int retval; + + if (is_dj_device((struct dj_device *)hdev->driver_data)) + return -ENODEV; + + dbg_hid(""%s called for ifnum %d\n"", __func__, + intf->cur_altsetting->desc.bInterfaceNumber); + + /* Ignore interfaces 0 and 1, they will not carry any data, dont create + * any hid_device for them */ + if (intf->cur_altsetting->desc.bInterfaceNumber != + LOGITECH_DJ_INTERFACE_NUMBER) { + dbg_hid(""%s: ignoring ifnum %d\n"", __func__, + intf->cur_altsetting->desc.bInterfaceNumber); + return -ENODEV; + } + + /* Treat interface 2 */ + + djrcv_dev = kzalloc(sizeof(struct dj_receiver_dev), GFP_KERNEL); + if (!djrcv_dev) { + dev_err(&hdev->dev, + ""%s:failed allocating dj_receiver_dev\n"", __func__); + return -ENOMEM; + } + djrcv_dev->hdev = hdev; + INIT_WORK(&djrcv_dev->work, delayedwork_callback); + spin_lock_init(&djrcv_dev->lock); + if (kfifo_alloc(&djrcv_dev->notif_fifo, + DJ_MAX_NUMBER_NOTIFICATIONS * sizeof(struct dj_report), + GFP_KERNEL)) { + dev_err(&hdev->dev, + ""%s:failed allocating notif_fifo\n"", __func__); + kfree(djrcv_dev); + return -ENOMEM; + } + hid_set_drvdata(hdev, djrcv_dev); + + /* Call to usbhid to fetch the HID descriptors of interface 2 and + * subsequently call to the hid/hid-core to parse the fetched + * descriptors, this will in turn create the hidraw and hiddev nodes + * for interface 2 of the receiver */ + retval = hid_parse(hdev); + if (retval) { + dev_err(&hdev->dev, + ""%s:parse of interface 2 failed\n"", __func__); + goto hid_parse_fail; + } + + if (!hid_validate_values(hdev, HID_OUTPUT_REPORT, REPORT_ID_DJ_SHORT, + 0, DJREPORT_SHORT_LENGTH - 1)) { + retval = -ENODEV; + goto hid_parse_fail; + } + + /* Starts the usb device and connects to upper interfaces hiddev and + * hidraw */ + retval = hid_hw_start(hdev, HID_CONNECT_DEFAULT); + if (retval) { + dev_err(&hdev->dev, + ""%s:hid_hw_start returned error\n"", __func__); + goto hid_hw_start_fail; + } + + retval = logi_dj_recv_switch_to_dj_mode(djrcv_dev, 0); + if (retval < 0) { + dev_err(&hdev->dev, + ""%s:logi_dj_recv_switch_to_dj_mode returned error:%d\n"", + __func__, retval); + goto switch_to_dj_mode_fail; + } + + /* This is enabling the polling urb on the IN endpoint */ + retval = hid_hw_open(hdev); + if (retval < 0) { + dev_err(&hdev->dev, ""%s:hid_hw_open returned error:%d\n"", + __func__, retval); + goto llopen_failed; + } + + /* Allow incoming packets to arrive: */ + hid_device_io_start(hdev); + + retval = logi_dj_recv_query_paired_devices(djrcv_dev); + if (retval < 0) { + dev_err(&hdev->dev, ""%s:logi_dj_recv_query_paired_devices "" + ""error:%d\n"", __func__, retval); + goto logi_dj_recv_query_paired_devices_failed; + } + + return retval; + +logi_dj_recv_query_paired_devices_failed: + hid_hw_close(hdev); + +llopen_failed: +switch_to_dj_mode_fail: + hid_hw_stop(hdev); + +hid_hw_start_fail: +hid_parse_fail: + kfifo_free(&djrcv_dev->notif_fifo); + kfree(djrcv_dev); + hid_set_drvdata(hdev, NULL); + return retval; + +} +",0,"static int logi_dj_probe(struct hid_device *hdev, + const struct hid_device_id *id) +{ + struct usb_interface *intf = to_usb_interface(hdev->dev.parent); + struct dj_receiver_dev *djrcv_dev; + int retval; + + if (is_dj_device((struct dj_device *)hdev->driver_data)) + return -ENODEV; + + dbg_hid(""%s called for ifnum %d\n"", __func__, + intf->cur_altsetting->desc.bInterfaceNumber); + + /* Ignore interfaces 0 and 1, they will not carry any data, dont create + * any hid_device for them */ + if (intf->cur_altsetting->desc.bInterfaceNumber != + LOGITECH_DJ_INTERFACE_NUMBER) { + dbg_hid(""%s: ignoring ifnum %d\n"", __func__, + intf->cur_altsetting->desc.bInterfaceNumber); + return -ENODEV; + } + + /* Treat interface 2 */ + + djrcv_dev = kzalloc(sizeof(struct dj_receiver_dev), GFP_KERNEL); + if (!djrcv_dev) { + dev_err(&hdev->dev, + ""%s:failed allocating dj_receiver_dev\n"", __func__); + return -ENOMEM; + } + djrcv_dev->hdev = hdev; + INIT_WORK(&djrcv_dev->work, delayedwork_callback); + spin_lock_init(&djrcv_dev->lock); + if (kfifo_alloc(&djrcv_dev->notif_fifo, + DJ_MAX_NUMBER_NOTIFICATIONS * sizeof(struct dj_report), + GFP_KERNEL)) { + dev_err(&hdev->dev, + ""%s:failed allocating notif_fifo\n"", __func__); + kfree(djrcv_dev); + return -ENOMEM; + } + hid_set_drvdata(hdev, djrcv_dev); + + /* Call to usbhid to fetch the HID descriptors of interface 2 and + * subsequently call to the hid/hid-core to parse the fetched + * descriptors, this will in turn create the hidraw and hiddev nodes + * for interface 2 of the receiver */ + retval = hid_parse(hdev); + if (retval) { + dev_err(&hdev->dev, + ""%s:parse of interface 2 failed\n"", __func__); + goto hid_parse_fail; + } + + if (!hid_validate_values(hdev, HID_OUTPUT_REPORT, REPORT_ID_DJ_SHORT, + 0, DJREPORT_SHORT_LENGTH - 1)) { + retval = -ENODEV; + goto hid_parse_fail; + } + + /* Starts the usb device and connects to upper interfaces hiddev and + * hidraw */ + retval = hid_hw_start(hdev, HID_CONNECT_DEFAULT); + if (retval) { + dev_err(&hdev->dev, + ""%s:hid_hw_start returned error\n"", __func__); + goto hid_hw_start_fail; + } + + retval = logi_dj_recv_switch_to_dj_mode(djrcv_dev, 0); + if (retval < 0) { + dev_err(&hdev->dev, + ""%s:logi_dj_recv_switch_to_dj_mode returned error:%d\n"", + __func__, retval); + goto switch_to_dj_mode_fail; + } + + /* This is enabling the polling urb on the IN endpoint */ + retval = hid_hw_open(hdev); + if (retval < 0) { + dev_err(&hdev->dev, ""%s:hid_hw_open returned error:%d\n"", + __func__, retval); + goto llopen_failed; + } + + /* Allow incoming packets to arrive: */ + hid_device_io_start(hdev); + + retval = logi_dj_recv_query_paired_devices(djrcv_dev); + if (retval < 0) { + dev_err(&hdev->dev, ""%s:logi_dj_recv_query_paired_devices "" + ""error:%d\n"", __func__, retval); + goto logi_dj_recv_query_paired_devices_failed; + } + + return retval; + +logi_dj_recv_query_paired_devices_failed: + hid_hw_close(hdev); + +llopen_failed: +switch_to_dj_mode_fail: + hid_hw_stop(hdev); + +hid_hw_start_fail: +hid_parse_fail: + kfifo_free(&djrcv_dev->notif_fifo); + kfree(djrcv_dev); + hid_set_drvdata(hdev, NULL); + return retval; + +} +","@@ -557,7 +557,7 @@ static int logi_dj_ll_raw_request(struct hid_device *hid, + if (!out_buf) + return -ENOMEM; + +- if (count < DJREPORT_SHORT_LENGTH - 2) ++ if (count > DJREPORT_SHORT_LENGTH - 2) + count = DJREPORT_SHORT_LENGTH - 2; + + out_buf[0] = REPORT_ID_DJ_SHORT;",916,1247,2048 +17924,"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; +} +",1,"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 super_block *sb = sdp->sd_vfs; + 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 ret; + 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++); + if (buffer_zeronew(bh_map)) { + ret = sb_issue_zeroout(sb, dblock, dblks, + GFP_NOFS); + if (ret) { + fs_err(sdp, + ""Failed to zero data buffers\n""); + clear_buffer_zeronew(bh_map); + } + } + 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; +} +","@@ -10,6 +10,7 @@ + #include + #include + #include ++#include + #include + #include + +@@ -427,12 +428,14 @@ static int gfs2_bmap_alloc(struct inode *inode, const sector_t lblock, + { + struct gfs2_inode *ip = GFS2_I(inode); + struct gfs2_sbd *sdp = GFS2_SB(inode); ++ struct super_block *sb = sdp->sd_vfs; + 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 ret; + int eob = 0; + enum alloc_state state; + __be64 *ptr; +@@ -535,6 +538,15 @@ static int gfs2_bmap_alloc(struct inode *inode, const sector_t lblock, + dblock = bn; + while (n-- > 0) + *ptr++ = cpu_to_be64(bn++); ++ if (buffer_zeronew(bh_map)) { ++ ret = sb_issue_zeroout(sb, dblock, dblks, ++ GFP_NOFS); ++ if (ret) { ++ fs_err(sdp, ++ ""Failed to zero data buffers\n""); ++ clear_buffer_zeronew(bh_map); ++ } ++ } + break; + } + } while ((state != ALLOC_DATA) || !dblock);",1265,1596,2048 +17873,"int ip_options_echo(struct ip_options * dopt, struct sk_buff * skb) + { + struct ip_options *sopt; + unsigned char *sptr, *dptr; + int soffset, doffset; + int optlen; + __be32 daddr; + + memset(dopt, 0, sizeof(struct ip_options)); + + sopt = &(IPCB(skb)->opt); + + if (sopt->optlen == 0) { + dopt->optlen = 0; + return 0; + } + + sptr = skb_network_header(skb); + dptr = dopt->__data; + + daddr = skb_rtable(skb)->rt_spec_dst; + + if (sopt->rr) { + optlen = sptr[sopt->rr+1]; + soffset = sptr[sopt->rr+2]; + dopt->rr = dopt->optlen + sizeof(struct iphdr); + memcpy(dptr, sptr+sopt->rr, optlen); + if (sopt->rr_needaddr && soffset <= optlen) { + if (soffset + 3 > optlen) + return -EINVAL; + dptr[2] = soffset + 4; + dopt->rr_needaddr = 1; + } + dptr += optlen; + dopt->optlen += optlen; + } + if (sopt->ts) { + optlen = sptr[sopt->ts+1]; + soffset = sptr[sopt->ts+2]; + dopt->ts = dopt->optlen + sizeof(struct iphdr); + memcpy(dptr, sptr+sopt->ts, optlen); + if (soffset <= optlen) { + if (sopt->ts_needaddr) { + if (soffset + 3 > optlen) + return -EINVAL; + dopt->ts_needaddr = 1; + soffset += 4; + } + if (sopt->ts_needtime) { + if (soffset + 3 > optlen) + return -EINVAL; + if ((dptr[3]&0xF) != IPOPT_TS_PRESPEC) { + dopt->ts_needtime = 1; + soffset += 4; + } else { + dopt->ts_needtime = 0; + + if (soffset + 7 <= optlen) { + __be32 addr; + + memcpy(&addr, dptr+soffset-1, 4); + if (inet_addr_type(dev_net(skb_dst(skb)->dev), addr) != RTN_UNICAST) { + dopt->ts_needtime = 1; + soffset += 8; + } + } + } + } + dptr[2] = soffset; + } + dptr += optlen; + dopt->optlen += optlen; + } + if (sopt->srr) { + unsigned char * start = sptr+sopt->srr; + __be32 faddr; + + optlen = start[1]; + soffset = start[2]; + doffset = 0; + if (soffset > optlen) + soffset = optlen + 1; + soffset -= 4; + if (soffset > 3) { + memcpy(&faddr, &start[soffset-1], 4); + for (soffset-=4, doffset=4; soffset > 3; soffset-=4, doffset+=4) + memcpy(&dptr[doffset-1], &start[soffset-1], 4); + /* + * RFC1812 requires to fix illegal source routes. + */ + if (memcmp(&ip_hdr(skb)->saddr, + &start[soffset + 3], 4) == 0) + doffset -= 4; + } + if (doffset > 3) { + memcpy(&start[doffset-1], &daddr, 4); + dopt->faddr = faddr; + dptr[0] = start[0]; + dptr[1] = doffset+3; + dptr[2] = 4; + dptr += doffset+3; + dopt->srr = dopt->optlen + sizeof(struct iphdr); + dopt->optlen += doffset+3; + dopt->is_strictroute = sopt->is_strictroute; + } + } + if (sopt->cipso) { + optlen = sptr[sopt->cipso+1]; + dopt->cipso = dopt->optlen+sizeof(struct iphdr); + memcpy(dptr, sptr+sopt->cipso, optlen); + dptr += optlen; + dopt->optlen += optlen; + } + while (dopt->optlen & 3) { + *dptr++ = IPOPT_END; + dopt->optlen++; + } + return 0; +} +",1,"int ip_options_echo(struct ip_options * dopt, struct sk_buff * skb) +int ip_options_echo(struct ip_options *dopt, struct sk_buff *skb) + { + const struct ip_options *sopt; + unsigned char *sptr, *dptr; + int soffset, doffset; + int optlen; + __be32 daddr; + + memset(dopt, 0, sizeof(struct ip_options)); + + sopt = &(IPCB(skb)->opt); + + if (sopt->optlen == 0) + return 0; + + sptr = skb_network_header(skb); + dptr = dopt->__data; + + daddr = skb_rtable(skb)->rt_spec_dst; + + if (sopt->rr) { + optlen = sptr[sopt->rr+1]; + soffset = sptr[sopt->rr+2]; + dopt->rr = dopt->optlen + sizeof(struct iphdr); + memcpy(dptr, sptr+sopt->rr, optlen); + if (sopt->rr_needaddr && soffset <= optlen) { + if (soffset + 3 > optlen) + return -EINVAL; + dptr[2] = soffset + 4; + dopt->rr_needaddr = 1; + } + dptr += optlen; + dopt->optlen += optlen; + } + if (sopt->ts) { + optlen = sptr[sopt->ts+1]; + soffset = sptr[sopt->ts+2]; + dopt->ts = dopt->optlen + sizeof(struct iphdr); + memcpy(dptr, sptr+sopt->ts, optlen); + if (soffset <= optlen) { + if (sopt->ts_needaddr) { + if (soffset + 3 > optlen) + return -EINVAL; + dopt->ts_needaddr = 1; + soffset += 4; + } + if (sopt->ts_needtime) { + if (soffset + 3 > optlen) + return -EINVAL; + if ((dptr[3]&0xF) != IPOPT_TS_PRESPEC) { + dopt->ts_needtime = 1; + soffset += 4; + } else { + dopt->ts_needtime = 0; + + if (soffset + 7 <= optlen) { + __be32 addr; + + memcpy(&addr, dptr+soffset-1, 4); + if (inet_addr_type(dev_net(skb_dst(skb)->dev), addr) != RTN_UNICAST) { + dopt->ts_needtime = 1; + soffset += 8; + } + } + } + } + dptr[2] = soffset; + } + dptr += optlen; + dopt->optlen += optlen; + } + if (sopt->srr) { + unsigned char *start = sptr+sopt->srr; + __be32 faddr; + + optlen = start[1]; + soffset = start[2]; + doffset = 0; + if (soffset > optlen) + soffset = optlen + 1; + soffset -= 4; + if (soffset > 3) { + memcpy(&faddr, &start[soffset-1], 4); + for (soffset-=4, doffset=4; soffset > 3; soffset-=4, doffset+=4) + memcpy(&dptr[doffset-1], &start[soffset-1], 4); + /* + * RFC1812 requires to fix illegal source routes. + */ + if (memcmp(&ip_hdr(skb)->saddr, + &start[soffset + 3], 4) == 0) + doffset -= 4; + } + if (doffset > 3) { + memcpy(&start[doffset-1], &daddr, 4); + dopt->faddr = faddr; + dptr[0] = start[0]; + dptr[1] = doffset+3; + dptr[2] = 4; + dptr += doffset+3; + dopt->srr = dopt->optlen + sizeof(struct iphdr); + dopt->optlen += doffset+3; + dopt->is_strictroute = sopt->is_strictroute; + } + } + if (sopt->cipso) { + optlen = sptr[sopt->cipso+1]; + dopt->cipso = dopt->optlen+sizeof(struct iphdr); + memcpy(dptr, sptr+sopt->cipso, optlen); + dptr += optlen; + dopt->optlen += optlen; + } + while (dopt->optlen & 3) { + *dptr++ = IPOPT_END; + dopt->optlen++; + } + return 0; +} +","@@ -36,7 +36,7 @@ + * saddr is address of outgoing interface. + */ + +-void ip_options_build(struct sk_buff * skb, struct ip_options * opt, ++void ip_options_build(struct sk_buff *skb, struct ip_options *opt, + __be32 daddr, struct rtable *rt, int is_frag) + { + unsigned char *iph = skb_network_header(skb); +@@ -83,9 +83,9 @@ void ip_options_build(struct sk_buff * skb, struct ip_options * opt, + * NOTE: dopt cannot point to skb. + */ + +-int ip_options_echo(struct ip_options * dopt, struct sk_buff * skb) ++int ip_options_echo(struct ip_options *dopt, struct sk_buff *skb) + { +- struct ip_options *sopt; ++ const struct ip_options *sopt; + unsigned char *sptr, *dptr; + int soffset, doffset; + int optlen; +@@ -95,10 +95,8 @@ int ip_options_echo(struct ip_options * dopt, struct sk_buff * skb) + + sopt = &(IPCB(skb)->opt); + +- if (sopt->optlen == 0) { +- dopt->optlen = 0; ++ if (sopt->optlen == 0) + return 0; +- } + + sptr = skb_network_header(skb); + dptr = dopt->__data; +@@ -157,7 +155,7 @@ int ip_options_echo(struct ip_options * dopt, struct sk_buff * skb) + dopt->optlen += optlen; + } + if (sopt->srr) { +- unsigned char * start = sptr+sopt->srr; ++ unsigned char *start = sptr+sopt->srr; + __be32 faddr; + + optlen = start[1]; +@@ -499,19 +497,19 @@ void ip_options_undo(struct ip_options * opt) + } + } + +-static struct ip_options *ip_options_get_alloc(const int optlen) ++static struct ip_options_rcu *ip_options_get_alloc(const int optlen) + { +- return kzalloc(sizeof(struct ip_options) + ((optlen + 3) & ~3), ++ return kzalloc(sizeof(struct ip_options_rcu) + ((optlen + 3) & ~3), + GFP_KERNEL); + } + +-static int ip_options_get_finish(struct net *net, struct ip_options **optp, +- struct ip_options *opt, int optlen) ++static int ip_options_get_finish(struct net *net, struct ip_options_rcu **optp, ++ struct ip_options_rcu *opt, int optlen) + { + while (optlen & 3) +- opt->__data[optlen++] = IPOPT_END; +- opt->optlen = optlen; +- if (optlen && ip_options_compile(net, opt, NULL)) { ++ opt->opt.__data[optlen++] = IPOPT_END; ++ opt->opt.optlen = optlen; ++ if (optlen && ip_options_compile(net, &opt->opt, NULL)) { + kfree(opt); + return -EINVAL; + } +@@ -520,29 +518,29 @@ static int ip_options_get_finish(struct net *net, struct ip_options **optp, + return 0; + } + +-int ip_options_get_from_user(struct net *net, struct ip_options **optp, ++int ip_options_get_from_user(struct net *net, struct ip_options_rcu **optp, + unsigned char __user *data, int optlen) + { +- struct ip_options *opt = ip_options_get_alloc(optlen); ++ struct ip_options_rcu *opt = ip_options_get_alloc(optlen); + + if (!opt) + return -ENOMEM; +- if (optlen && copy_from_user(opt->__data, data, optlen)) { ++ if (optlen && copy_from_user(opt->opt.__data, data, optlen)) { + kfree(opt); + return -EFAULT; + } + return ip_options_get_finish(net, optp, opt, optlen); + } + +-int ip_options_get(struct net *net, struct ip_options **optp, ++int ip_options_get(struct net *net, struct ip_options_rcu **optp, + unsigned char *data, int optlen) + { +- struct ip_options *opt = ip_options_get_alloc(optlen); ++ struct ip_options_rcu *opt = ip_options_get_alloc(optlen); + + if (!opt) + return -ENOMEM; + if (optlen) +- memcpy(opt->__data, data, optlen); ++ memcpy(opt->opt.__data, data, optlen); + return ip_options_get_finish(net, optp, opt, optlen); + } + ",1102,1433,2048 +3468,"static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr) +{ + struct sock *sk; + struct tun_struct *tun; + struct net_device *dev; + int err; + + dev = __dev_get_by_name(net, ifr->ifr_name); + if (dev) { + const struct cred *cred = current_cred(); + + if (ifr->ifr_flags & IFF_TUN_EXCL) + return -EBUSY; + if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops) + tun = netdev_priv(dev); + else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops) + tun = netdev_priv(dev); + else + return -EINVAL; + + if (((tun->owner != -1 && cred->euid != tun->owner) || + (tun->group != -1 && !in_egroup_p(tun->group))) && + !capable(CAP_NET_ADMIN)) + return -EPERM; + err = security_tun_dev_attach(tun->socket.sk); + if (err < 0) + return err; + + err = tun_attach(tun, file); + if (err < 0) + return err; + } + else { + char *name; + unsigned long flags = 0; + + if (!capable(CAP_NET_ADMIN)) + return -EPERM; + err = security_tun_dev_create(); + if (err < 0) + return err; + + /* Set dev type */ + if (ifr->ifr_flags & IFF_TUN) { + /* TUN device */ + flags |= TUN_TUN_DEV; + name = ""tun%d""; + } else if (ifr->ifr_flags & IFF_TAP) { + /* TAP device */ + flags |= TUN_TAP_DEV; + name = ""tap%d""; + } else + return -EINVAL; + + if (*ifr->ifr_name) + name = ifr->ifr_name; + + dev = alloc_netdev(sizeof(struct tun_struct), name, + tun_setup); + if (!dev) + return -ENOMEM; + + dev_net_set(dev, net); + dev->rtnl_link_ops = &tun_link_ops; + + tun = netdev_priv(dev); + tun->dev = dev; + tun->flags = flags; + tun->txflt.count = 0; + tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr); + set_bit(SOCK_EXTERNALLY_ALLOCATED, &tun->socket.flags); + + err = -ENOMEM; + sk = sk_alloc(&init_net, AF_UNSPEC, GFP_KERNEL, &tun_proto); + if (!sk) + goto err_free_dev; + + sk_change_net(sk, net); + tun->socket.wq = &tun->wq; + init_waitqueue_head(&tun->wq.wait); + tun->socket.ops = &tun_socket_ops; + sock_init_data(&tun->socket, sk); + sk->sk_write_space = tun_sock_write_space; + sk->sk_sndbuf = INT_MAX; + sock_set_flag(sk, SOCK_ZEROCOPY); + + tun_sk(sk)->tun = tun; + + security_tun_dev_post_create(sk); + + tun_net_init(dev); + + dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST | + TUN_USER_FEATURES; + dev->features = dev->hw_features; + + err = register_netdevice(tun->dev); + if (err < 0) + goto err_free_sk; + + if (device_create_file(&tun->dev->dev, &dev_attr_tun_flags) || + device_create_file(&tun->dev->dev, &dev_attr_owner) || + device_create_file(&tun->dev->dev, &dev_attr_group)) + pr_err(""Failed to create tun sysfs files\n""); + + sk->sk_destruct = tun_sock_destruct; + + err = tun_attach(tun, file); + if (err < 0) + goto failed; + } + + tun_debug(KERN_INFO, tun, ""tun_set_iff\n""); + + if (ifr->ifr_flags & IFF_NO_PI) + tun->flags |= TUN_NO_PI; + else + tun->flags &= ~TUN_NO_PI; + + if (ifr->ifr_flags & IFF_ONE_QUEUE) + tun->flags |= TUN_ONE_QUEUE; + else + tun->flags &= ~TUN_ONE_QUEUE; + + if (ifr->ifr_flags & IFF_VNET_HDR) + tun->flags |= TUN_VNET_HDR; + else + tun->flags &= ~TUN_VNET_HDR; + + /* Make sure persistent devices do not get stuck in + * xoff state. + */ + if (netif_running(tun->dev)) + netif_wake_queue(tun->dev); + + strcpy(ifr->ifr_name, tun->dev->name); + return 0; + + err_free_sk: + tun_free_netdev(dev); + err_free_dev: + free_netdev(dev); + failed: + return err; +} +",0,"static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr) +{ + struct sock *sk; + struct tun_struct *tun; + struct net_device *dev; + int err; + + dev = __dev_get_by_name(net, ifr->ifr_name); + if (dev) { + const struct cred *cred = current_cred(); + + if (ifr->ifr_flags & IFF_TUN_EXCL) + return -EBUSY; + if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops) + tun = netdev_priv(dev); + else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops) + tun = netdev_priv(dev); + else + return -EINVAL; + + if (((tun->owner != -1 && cred->euid != tun->owner) || + (tun->group != -1 && !in_egroup_p(tun->group))) && + !capable(CAP_NET_ADMIN)) + return -EPERM; + err = security_tun_dev_attach(tun->socket.sk); + if (err < 0) + return err; + + err = tun_attach(tun, file); + if (err < 0) + return err; + } + else { + char *name; + unsigned long flags = 0; + + if (!capable(CAP_NET_ADMIN)) + return -EPERM; + err = security_tun_dev_create(); + if (err < 0) + return err; + + /* Set dev type */ + if (ifr->ifr_flags & IFF_TUN) { + /* TUN device */ + flags |= TUN_TUN_DEV; + name = ""tun%d""; + } else if (ifr->ifr_flags & IFF_TAP) { + /* TAP device */ + flags |= TUN_TAP_DEV; + name = ""tap%d""; + } else + return -EINVAL; + + if (*ifr->ifr_name) + name = ifr->ifr_name; + + dev = alloc_netdev(sizeof(struct tun_struct), name, + tun_setup); + if (!dev) + return -ENOMEM; + + dev_net_set(dev, net); + dev->rtnl_link_ops = &tun_link_ops; + + tun = netdev_priv(dev); + tun->dev = dev; + tun->flags = flags; + tun->txflt.count = 0; + tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr); + set_bit(SOCK_EXTERNALLY_ALLOCATED, &tun->socket.flags); + + err = -ENOMEM; + sk = sk_alloc(&init_net, AF_UNSPEC, GFP_KERNEL, &tun_proto); + if (!sk) + goto err_free_dev; + + sk_change_net(sk, net); + tun->socket.wq = &tun->wq; + init_waitqueue_head(&tun->wq.wait); + tun->socket.ops = &tun_socket_ops; + sock_init_data(&tun->socket, sk); + sk->sk_write_space = tun_sock_write_space; + sk->sk_sndbuf = INT_MAX; + sock_set_flag(sk, SOCK_ZEROCOPY); + + tun_sk(sk)->tun = tun; + + security_tun_dev_post_create(sk); + + tun_net_init(dev); + + dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST | + TUN_USER_FEATURES; + dev->features = dev->hw_features; + + err = register_netdevice(tun->dev); + if (err < 0) + goto err_free_sk; + + if (device_create_file(&tun->dev->dev, &dev_attr_tun_flags) || + device_create_file(&tun->dev->dev, &dev_attr_owner) || + device_create_file(&tun->dev->dev, &dev_attr_group)) + pr_err(""Failed to create tun sysfs files\n""); + + sk->sk_destruct = tun_sock_destruct; + + err = tun_attach(tun, file); + if (err < 0) + goto failed; + } + + tun_debug(KERN_INFO, tun, ""tun_set_iff\n""); + + if (ifr->ifr_flags & IFF_NO_PI) + tun->flags |= TUN_NO_PI; + else + tun->flags &= ~TUN_NO_PI; + + if (ifr->ifr_flags & IFF_ONE_QUEUE) + tun->flags |= TUN_ONE_QUEUE; + else + tun->flags &= ~TUN_ONE_QUEUE; + + if (ifr->ifr_flags & IFF_VNET_HDR) + tun->flags |= TUN_VNET_HDR; + else + tun->flags &= ~TUN_VNET_HDR; + + /* Make sure persistent devices do not get stuck in + * xoff state. + */ + if (netif_running(tun->dev)) + netif_wake_queue(tun->dev); + + strcpy(ifr->ifr_name, tun->dev->name); + return 0; + + err_free_sk: + tun_free_netdev(dev); + err_free_dev: + free_netdev(dev); + failed: + return err; +} +","@@ -1379,9 +1379,11 @@ static long __tun_chr_ioctl(struct file *file, unsigned int cmd, + int vnet_hdr_sz; + int ret; + +- if (cmd == TUNSETIFF || _IOC_TYPE(cmd) == 0x89) ++ if (cmd == TUNSETIFF || _IOC_TYPE(cmd) == 0x89) { + if (copy_from_user(&ifr, argp, ifreq_len)) + return -EFAULT; ++ } else ++ memset(&ifr, 0, sizeof(ifr)); + + if (cmd == TUNGETFEATURES) { + /* Currently this just means: ""what IFF flags are valid?"".",1108,1439,2048 +2570,"CIFSGetDFSRefer(const int xid, struct cifs_ses *ses, + const unsigned char *searchName, + struct dfs_info3_param **target_nodes, + unsigned int *num_of_nodes, + const struct nls_table *nls_codepage, int remap) +{ +/* TRANS2_GET_DFS_REFERRAL */ + TRANSACTION2_GET_DFS_REFER_REQ *pSMB = NULL; + TRANSACTION2_GET_DFS_REFER_RSP *pSMBr = NULL; + int rc = 0; + int bytes_returned; + int name_len; + __u16 params, byte_count; + *num_of_nodes = 0; + *target_nodes = NULL; + + cFYI(1, ""In GetDFSRefer the path %s"", searchName); + if (ses == NULL) + return -ENODEV; +getDFSRetry: + rc = smb_init(SMB_COM_TRANSACTION2, 15, NULL, (void **) &pSMB, + (void **) &pSMBr); + if (rc) + return rc; + + /* server pointer checked in called function, + but should never be null here anyway */ + pSMB->hdr.Mid = GetNextMid(ses->server); + pSMB->hdr.Tid = ses->ipc_tid; + pSMB->hdr.Uid = ses->Suid; + if (ses->capabilities & CAP_STATUS32) + pSMB->hdr.Flags2 |= SMBFLG2_ERR_STATUS; + if (ses->capabilities & CAP_DFS) + pSMB->hdr.Flags2 |= SMBFLG2_DFS; + + if (ses->capabilities & CAP_UNICODE) { + pSMB->hdr.Flags2 |= SMBFLG2_UNICODE; + name_len = + cifsConvertToUCS((__le16 *) pSMB->RequestFileName, + searchName, PATH_MAX, nls_codepage, remap); + name_len++; /* trailing null */ + name_len *= 2; + } else { /* BB improve the check for buffer overruns BB */ + name_len = strnlen(searchName, PATH_MAX); + name_len++; /* trailing null */ + strncpy(pSMB->RequestFileName, searchName, name_len); + } + + if (ses->server) { + if (ses->server->sec_mode & + (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED)) + pSMB->hdr.Flags2 |= SMBFLG2_SECURITY_SIGNATURE; + } + + pSMB->hdr.Uid = ses->Suid; + + params = 2 /* level */ + name_len /*includes null */ ; + pSMB->TotalDataCount = 0; + pSMB->DataCount = 0; + pSMB->DataOffset = 0; + pSMB->MaxParameterCount = 0; + /* BB find exact max SMB PDU from sess structure BB */ + pSMB->MaxDataCount = cpu_to_le16(4000); + pSMB->MaxSetupCount = 0; + pSMB->Reserved = 0; + pSMB->Flags = 0; + pSMB->Timeout = 0; + pSMB->Reserved2 = 0; + pSMB->ParameterOffset = cpu_to_le16(offsetof( + struct smb_com_transaction2_get_dfs_refer_req, MaxReferralLevel) - 4); + pSMB->SetupCount = 1; + pSMB->Reserved3 = 0; + pSMB->SubCommand = cpu_to_le16(TRANS2_GET_DFS_REFERRAL); + byte_count = params + 3 /* pad */ ; + pSMB->ParameterCount = cpu_to_le16(params); + pSMB->TotalParameterCount = pSMB->ParameterCount; + pSMB->MaxReferralLevel = cpu_to_le16(3); + inc_rfc1001_len(pSMB, byte_count); + pSMB->ByteCount = cpu_to_le16(byte_count); + + rc = SendReceive(xid, ses, (struct smb_hdr *) pSMB, + (struct smb_hdr *) pSMBr, &bytes_returned, 0); + if (rc) { + cFYI(1, ""Send error in GetDFSRefer = %d"", rc); + goto GetDFSRefExit; + } + rc = validate_t2((struct smb_t2_rsp *)pSMBr); + + /* BB Also check if enough total bytes returned? */ + if (rc || get_bcc(&pSMBr->hdr) < 17) { + rc = -EIO; /* bad smb */ + goto GetDFSRefExit; + } + + cFYI(1, ""Decoding GetDFSRefer response BCC: %d Offset %d"", + get_bcc(&pSMBr->hdr), + le16_to_cpu(pSMBr->t2.DataOffset)); + + /* parse returned result into more usable form */ + rc = parse_DFS_referrals(pSMBr, num_of_nodes, + target_nodes, nls_codepage, remap, + searchName); + +GetDFSRefExit: + cifs_buf_release(pSMB); + + if (rc == -EAGAIN) + goto getDFSRetry; + + return rc; +} +",0,"CIFSGetDFSRefer(const int xid, struct cifs_ses *ses, + const unsigned char *searchName, + struct dfs_info3_param **target_nodes, + unsigned int *num_of_nodes, + const struct nls_table *nls_codepage, int remap) +{ +/* TRANS2_GET_DFS_REFERRAL */ + TRANSACTION2_GET_DFS_REFER_REQ *pSMB = NULL; + TRANSACTION2_GET_DFS_REFER_RSP *pSMBr = NULL; + int rc = 0; + int bytes_returned; + int name_len; + __u16 params, byte_count; + *num_of_nodes = 0; + *target_nodes = NULL; + + cFYI(1, ""In GetDFSRefer the path %s"", searchName); + if (ses == NULL) + return -ENODEV; +getDFSRetry: + rc = smb_init(SMB_COM_TRANSACTION2, 15, NULL, (void **) &pSMB, + (void **) &pSMBr); + if (rc) + return rc; + + /* server pointer checked in called function, + but should never be null here anyway */ + pSMB->hdr.Mid = GetNextMid(ses->server); + pSMB->hdr.Tid = ses->ipc_tid; + pSMB->hdr.Uid = ses->Suid; + if (ses->capabilities & CAP_STATUS32) + pSMB->hdr.Flags2 |= SMBFLG2_ERR_STATUS; + if (ses->capabilities & CAP_DFS) + pSMB->hdr.Flags2 |= SMBFLG2_DFS; + + if (ses->capabilities & CAP_UNICODE) { + pSMB->hdr.Flags2 |= SMBFLG2_UNICODE; + name_len = + cifsConvertToUCS((__le16 *) pSMB->RequestFileName, + searchName, PATH_MAX, nls_codepage, remap); + name_len++; /* trailing null */ + name_len *= 2; + } else { /* BB improve the check for buffer overruns BB */ + name_len = strnlen(searchName, PATH_MAX); + name_len++; /* trailing null */ + strncpy(pSMB->RequestFileName, searchName, name_len); + } + + if (ses->server) { + if (ses->server->sec_mode & + (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED)) + pSMB->hdr.Flags2 |= SMBFLG2_SECURITY_SIGNATURE; + } + + pSMB->hdr.Uid = ses->Suid; + + params = 2 /* level */ + name_len /*includes null */ ; + pSMB->TotalDataCount = 0; + pSMB->DataCount = 0; + pSMB->DataOffset = 0; + pSMB->MaxParameterCount = 0; + /* BB find exact max SMB PDU from sess structure BB */ + pSMB->MaxDataCount = cpu_to_le16(4000); + pSMB->MaxSetupCount = 0; + pSMB->Reserved = 0; + pSMB->Flags = 0; + pSMB->Timeout = 0; + pSMB->Reserved2 = 0; + pSMB->ParameterOffset = cpu_to_le16(offsetof( + struct smb_com_transaction2_get_dfs_refer_req, MaxReferralLevel) - 4); + pSMB->SetupCount = 1; + pSMB->Reserved3 = 0; + pSMB->SubCommand = cpu_to_le16(TRANS2_GET_DFS_REFERRAL); + byte_count = params + 3 /* pad */ ; + pSMB->ParameterCount = cpu_to_le16(params); + pSMB->TotalParameterCount = pSMB->ParameterCount; + pSMB->MaxReferralLevel = cpu_to_le16(3); + inc_rfc1001_len(pSMB, byte_count); + pSMB->ByteCount = cpu_to_le16(byte_count); + + rc = SendReceive(xid, ses, (struct smb_hdr *) pSMB, + (struct smb_hdr *) pSMBr, &bytes_returned, 0); + if (rc) { + cFYI(1, ""Send error in GetDFSRefer = %d"", rc); + goto GetDFSRefExit; + } + rc = validate_t2((struct smb_t2_rsp *)pSMBr); + + /* BB Also check if enough total bytes returned? */ + if (rc || get_bcc(&pSMBr->hdr) < 17) { + rc = -EIO; /* bad smb */ + goto GetDFSRefExit; + } + + cFYI(1, ""Decoding GetDFSRefer response BCC: %d Offset %d"", + get_bcc(&pSMBr->hdr), + le16_to_cpu(pSMBr->t2.DataOffset)); + + /* parse returned result into more usable form */ + rc = parse_DFS_referrals(pSMBr, num_of_nodes, + target_nodes, nls_codepage, remap, + searchName); + +GetDFSRefExit: + cifs_buf_release(pSMB); + + if (rc == -EAGAIN) + goto getDFSRetry; + + return rc; +} +","@@ -4079,7 +4079,8 @@ int CIFSFindNext(const int xid, struct cifs_tcon *tcon, + T2_FNEXT_RSP_PARMS *parms; + char *response_data; + int rc = 0; +- int bytes_returned, name_len; ++ int bytes_returned; ++ unsigned int name_len; + __u16 params, byte_count; + + cFYI(1, ""In FindNext"");",1095,1426,2048 +2372,"static int encode_attrs(struct xdr_stream *xdr, const struct iattr *iap, const struct nfs_server *server) +{ + char owner_name[IDMAP_NAMESZ]; + char owner_group[IDMAP_NAMESZ]; + int owner_namelen = 0; + int owner_grouplen = 0; + __be32 *p; + __be32 *q; + int len; + uint32_t bmval0 = 0; + uint32_t bmval1 = 0; + int status; + + /* + * We reserve enough space to write the entire attribute buffer at once. + * In the worst-case, this would be + * 12(bitmap) + 4(attrlen) + 8(size) + 4(mode) + 4(atime) + 4(mtime) + * = 36 bytes, plus any contribution from variable-length fields + * such as owner/group. + */ + len = 16; + + /* Sigh */ + if (iap->ia_valid & ATTR_SIZE) + len += 8; + if (iap->ia_valid & ATTR_MODE) + len += 4; + if (iap->ia_valid & ATTR_UID) { + owner_namelen = nfs_map_uid_to_name(server->nfs_client, iap->ia_uid, owner_name); + if (owner_namelen < 0) { + dprintk(""nfs: couldn't resolve uid %d to string\n"", + iap->ia_uid); + /* XXX */ + strcpy(owner_name, ""nobody""); + owner_namelen = sizeof(""nobody"") - 1; + /* goto out; */ + } + len += 4 + (XDR_QUADLEN(owner_namelen) << 2); + } + if (iap->ia_valid & ATTR_GID) { + owner_grouplen = nfs_map_gid_to_group(server->nfs_client, iap->ia_gid, owner_group); + if (owner_grouplen < 0) { + dprintk(""nfs: couldn't resolve gid %d to string\n"", + iap->ia_gid); + strcpy(owner_group, ""nobody""); + owner_grouplen = sizeof(""nobody"") - 1; + /* goto out; */ + } + len += 4 + (XDR_QUADLEN(owner_grouplen) << 2); + } + if (iap->ia_valid & ATTR_ATIME_SET) + len += 16; + else if (iap->ia_valid & ATTR_ATIME) + len += 4; + if (iap->ia_valid & ATTR_MTIME_SET) + len += 16; + else if (iap->ia_valid & ATTR_MTIME) + len += 4; + RESERVE_SPACE(len); + + /* + * We write the bitmap length now, but leave the bitmap and the attribute + * buffer length to be backfilled at the end of this routine. + */ + WRITE32(2); + q = p; + p += 3; + + if (iap->ia_valid & ATTR_SIZE) { + bmval0 |= FATTR4_WORD0_SIZE; + WRITE64(iap->ia_size); + } + if (iap->ia_valid & ATTR_MODE) { + bmval1 |= FATTR4_WORD1_MODE; + WRITE32(iap->ia_mode & S_IALLUGO); + } + if (iap->ia_valid & ATTR_UID) { + bmval1 |= FATTR4_WORD1_OWNER; + WRITE32(owner_namelen); + WRITEMEM(owner_name, owner_namelen); + } + if (iap->ia_valid & ATTR_GID) { + bmval1 |= FATTR4_WORD1_OWNER_GROUP; + WRITE32(owner_grouplen); + WRITEMEM(owner_group, owner_grouplen); + } + if (iap->ia_valid & ATTR_ATIME_SET) { + bmval1 |= FATTR4_WORD1_TIME_ACCESS_SET; + WRITE32(NFS4_SET_TO_CLIENT_TIME); + WRITE32(0); + WRITE32(iap->ia_mtime.tv_sec); + WRITE32(iap->ia_mtime.tv_nsec); + } + else if (iap->ia_valid & ATTR_ATIME) { + bmval1 |= FATTR4_WORD1_TIME_ACCESS_SET; + WRITE32(NFS4_SET_TO_SERVER_TIME); + } + if (iap->ia_valid & ATTR_MTIME_SET) { + bmval1 |= FATTR4_WORD1_TIME_MODIFY_SET; + WRITE32(NFS4_SET_TO_CLIENT_TIME); + WRITE32(0); + WRITE32(iap->ia_mtime.tv_sec); + WRITE32(iap->ia_mtime.tv_nsec); + } + else if (iap->ia_valid & ATTR_MTIME) { + bmval1 |= FATTR4_WORD1_TIME_MODIFY_SET; + WRITE32(NFS4_SET_TO_SERVER_TIME); + } + + /* + * Now we backfill the bitmap and the attribute buffer length. + */ + if (len != ((char *)p - (char *)q) + 4) { + printk(KERN_ERR ""nfs: Attr length error, %u != %Zu\n"", + len, ((char *)p - (char *)q) + 4); + BUG(); + } + len = (char *)p - (char *)q - 12; + *q++ = htonl(bmval0); + *q++ = htonl(bmval1); + *q++ = htonl(len); + + status = 0; +/* out: */ + return status; +} +",0,"static int encode_attrs(struct xdr_stream *xdr, const struct iattr *iap, const struct nfs_server *server) +{ + char owner_name[IDMAP_NAMESZ]; + char owner_group[IDMAP_NAMESZ]; + int owner_namelen = 0; + int owner_grouplen = 0; + __be32 *p; + __be32 *q; + int len; + uint32_t bmval0 = 0; + uint32_t bmval1 = 0; + int status; + + /* + * We reserve enough space to write the entire attribute buffer at once. + * In the worst-case, this would be + * 12(bitmap) + 4(attrlen) + 8(size) + 4(mode) + 4(atime) + 4(mtime) + * = 36 bytes, plus any contribution from variable-length fields + * such as owner/group. + */ + len = 16; + + /* Sigh */ + if (iap->ia_valid & ATTR_SIZE) + len += 8; + if (iap->ia_valid & ATTR_MODE) + len += 4; + if (iap->ia_valid & ATTR_UID) { + owner_namelen = nfs_map_uid_to_name(server->nfs_client, iap->ia_uid, owner_name); + if (owner_namelen < 0) { + dprintk(""nfs: couldn't resolve uid %d to string\n"", + iap->ia_uid); + /* XXX */ + strcpy(owner_name, ""nobody""); + owner_namelen = sizeof(""nobody"") - 1; + /* goto out; */ + } + len += 4 + (XDR_QUADLEN(owner_namelen) << 2); + } + if (iap->ia_valid & ATTR_GID) { + owner_grouplen = nfs_map_gid_to_group(server->nfs_client, iap->ia_gid, owner_group); + if (owner_grouplen < 0) { + dprintk(""nfs: couldn't resolve gid %d to string\n"", + iap->ia_gid); + strcpy(owner_group, ""nobody""); + owner_grouplen = sizeof(""nobody"") - 1; + /* goto out; */ + } + len += 4 + (XDR_QUADLEN(owner_grouplen) << 2); + } + if (iap->ia_valid & ATTR_ATIME_SET) + len += 16; + else if (iap->ia_valid & ATTR_ATIME) + len += 4; + if (iap->ia_valid & ATTR_MTIME_SET) + len += 16; + else if (iap->ia_valid & ATTR_MTIME) + len += 4; + RESERVE_SPACE(len); + + /* + * We write the bitmap length now, but leave the bitmap and the attribute + * buffer length to be backfilled at the end of this routine. + */ + WRITE32(2); + q = p; + p += 3; + + if (iap->ia_valid & ATTR_SIZE) { + bmval0 |= FATTR4_WORD0_SIZE; + WRITE64(iap->ia_size); + } + if (iap->ia_valid & ATTR_MODE) { + bmval1 |= FATTR4_WORD1_MODE; + WRITE32(iap->ia_mode & S_IALLUGO); + } + if (iap->ia_valid & ATTR_UID) { + bmval1 |= FATTR4_WORD1_OWNER; + WRITE32(owner_namelen); + WRITEMEM(owner_name, owner_namelen); + } + if (iap->ia_valid & ATTR_GID) { + bmval1 |= FATTR4_WORD1_OWNER_GROUP; + WRITE32(owner_grouplen); + WRITEMEM(owner_group, owner_grouplen); + } + if (iap->ia_valid & ATTR_ATIME_SET) { + bmval1 |= FATTR4_WORD1_TIME_ACCESS_SET; + WRITE32(NFS4_SET_TO_CLIENT_TIME); + WRITE32(0); + WRITE32(iap->ia_mtime.tv_sec); + WRITE32(iap->ia_mtime.tv_nsec); + } + else if (iap->ia_valid & ATTR_ATIME) { + bmval1 |= FATTR4_WORD1_TIME_ACCESS_SET; + WRITE32(NFS4_SET_TO_SERVER_TIME); + } + if (iap->ia_valid & ATTR_MTIME_SET) { + bmval1 |= FATTR4_WORD1_TIME_MODIFY_SET; + WRITE32(NFS4_SET_TO_CLIENT_TIME); + WRITE32(0); + WRITE32(iap->ia_mtime.tv_sec); + WRITE32(iap->ia_mtime.tv_nsec); + } + else if (iap->ia_valid & ATTR_MTIME) { + bmval1 |= FATTR4_WORD1_TIME_MODIFY_SET; + WRITE32(NFS4_SET_TO_SERVER_TIME); + } + + /* + * Now we backfill the bitmap and the attribute buffer length. + */ + if (len != ((char *)p - (char *)q) + 4) { + printk(KERN_ERR ""nfs: Attr length error, %u != %Zu\n"", + len, ((char *)p - (char *)q) + 4); + BUG(); + } + len = (char *)p - (char *)q - 12; + *q++ = htonl(bmval0); + *q++ = htonl(bmval1); + *q++ = htonl(len); + + status = 0; +/* out: */ + return status; +} +","@@ -953,12 +953,12 @@ static int encode_lookup(struct xdr_stream *xdr, const struct qstr *name) + return 0; + } + +-static void encode_share_access(struct xdr_stream *xdr, int open_flags) ++static void encode_share_access(struct xdr_stream *xdr, fmode_t fmode) + { + __be32 *p; + + RESERVE_SPACE(8); +- switch (open_flags & (FMODE_READ|FMODE_WRITE)) { ++ switch (fmode & (FMODE_READ|FMODE_WRITE)) { + case FMODE_READ: + WRITE32(NFS4_SHARE_ACCESS_READ); + break; +@@ -969,7 +969,7 @@ static void encode_share_access(struct xdr_stream *xdr, int open_flags) + WRITE32(NFS4_SHARE_ACCESS_BOTH); + break; + default: +- BUG(); ++ WRITE32(0); + } + WRITE32(0); /* for linux, share_deny = 0 always */ + } +@@ -984,7 +984,7 @@ static inline void encode_openhdr(struct xdr_stream *xdr, const struct nfs_opena + RESERVE_SPACE(8); + WRITE32(OP_OPEN); + WRITE32(arg->seqid->sequence->counter); +- encode_share_access(xdr, arg->open_flags); ++ encode_share_access(xdr, arg->fmode); + RESERVE_SPACE(28); + WRITE64(arg->clientid); + WRITE32(16); +@@ -1112,7 +1112,7 @@ static int encode_open_downgrade(struct xdr_stream *xdr, const struct nfs_closea + WRITE32(OP_OPEN_DOWNGRADE); + WRITEMEM(arg->stateid->data, NFS4_STATEID_SIZE); + WRITE32(arg->seqid->sequence->counter); +- encode_share_access(xdr, arg->open_flags); ++ encode_share_access(xdr, arg->fmode); + return 0; + } + ",1203,1534,2048 +7911,"int imap_copy_messages(struct Context *ctx, struct Header *h, char *dest, int delete) +{ + struct Buffer cmd, sync_cmd; + char mbox[PATH_MAX]; + char mmbox[PATH_MAX]; + char prompt[PATH_MAX + 64]; + int rc; + struct ImapMbox mx; + int err_continue = MUTT_NO; + int triedcreate = 0; + + struct ImapData *idata = ctx->data; + + if (imap_parse_path(dest, &mx)) + { + mutt_debug(1, ""bad destination %s\n"", dest); + return -1; + } + + /* check that the save-to folder is in the same account */ + if (mutt_account_match(&(idata->conn->account), &(mx.account)) == 0) + { + mutt_debug(3, ""%s not same server as %s\n"", dest, ctx->path); + return 1; + } + + if (h && h->attach_del) + { + mutt_debug(3, ""#1 Message contains attachments to be deleted\n""); + return 1; + } + + imap_fix_path(idata, mx.mbox, mbox, sizeof(mbox)); + if (!*mbox) + mutt_str_strfcpy(mbox, ""INBOX"", sizeof(mbox)); + imap_munge_mbox_name(idata, mmbox, sizeof(mmbox), mbox); + + /* loop in case of TRYCREATE */ + do + { + mutt_buffer_init(&sync_cmd); + mutt_buffer_init(&cmd); + + /* Null Header* means copy tagged messages */ + if (!h) + { + /* if any messages have attachments to delete, fall through to FETCH + * and APPEND. TODO: Copy what we can with COPY, fall through for the + * remainder. */ + for (int i = 0; i < ctx->msgcount; i++) + { + if (!message_is_tagged(ctx, i)) + continue; + + if (ctx->hdrs[i]->attach_del) + { + mutt_debug(3, ""#2 Message contains attachments to be deleted\n""); + return 1; + } + + if (ctx->hdrs[i]->active && ctx->hdrs[i]->changed) + { + rc = imap_sync_message_for_copy(idata, ctx->hdrs[i], &sync_cmd, &err_continue); + if (rc < 0) + { + mutt_debug(1, ""#1 could not sync\n""); + goto out; + } + } + } + + rc = imap_exec_msgset(idata, ""UID COPY"", mmbox, MUTT_TAG, 0, 0); + if (!rc) + { + mutt_debug(1, ""No messages tagged\n""); + rc = -1; + goto out; + } + else if (rc < 0) + { + mutt_debug(1, ""#1 could not queue copy\n""); + goto out; + } + else + { + mutt_message(ngettext(""Copying %d message to %s..."", ""Copying %d messages to %s..."", rc), + rc, mbox); + } + } + else + { + mutt_message(_(""Copying message %d to %s...""), h->index + 1, mbox); + mutt_buffer_printf(&cmd, ""UID COPY %u %s"", HEADER_DATA(h)->uid, mmbox); + + if (h->active && h->changed) + { + rc = imap_sync_message_for_copy(idata, h, &sync_cmd, &err_continue); + if (rc < 0) + { + mutt_debug(1, ""#2 could not sync\n""); + goto out; + } + } + rc = imap_exec(idata, cmd.data, IMAP_CMD_QUEUE); + if (rc < 0) + { + mutt_debug(1, ""#2 could not queue copy\n""); + goto out; + } + } + + /* let's get it on */ + rc = imap_exec(idata, NULL, IMAP_CMD_FAIL_OK); + if (rc == -2) + { + if (triedcreate) + { + mutt_debug(1, ""Already tried to create mailbox %s\n"", mbox); + break; + } + /* bail out if command failed for reasons other than nonexistent target */ + if (mutt_str_strncasecmp(imap_get_qualifier(idata->buf), ""[TRYCREATE]"", 11) != 0) + break; + mutt_debug(3, ""server suggests TRYCREATE\n""); + snprintf(prompt, sizeof(prompt), _(""Create %s?""), mbox); + if (Confirmcreate && mutt_yesorno(prompt, 1) != MUTT_YES) + { + mutt_clear_error(); + goto out; + } + if (imap_create_mailbox(idata, mbox) < 0) + break; + triedcreate = 1; + } + } while (rc == -2); + + if (rc != 0) + { + imap_error(""imap_copy_messages"", idata->buf); + goto out; + } + + /* cleanup */ + if (delete) + { + if (!h) + { + for (int i = 0; i < ctx->msgcount; i++) + { + if (!message_is_tagged(ctx, i)) + continue; + + mutt_set_flag(ctx, ctx->hdrs[i], MUTT_DELETE, 1); + mutt_set_flag(ctx, ctx->hdrs[i], MUTT_PURGE, 1); + if (DeleteUntag) + mutt_set_flag(ctx, ctx->hdrs[i], MUTT_TAG, 0); + } + } + else + { + mutt_set_flag(ctx, h, MUTT_DELETE, 1); + mutt_set_flag(ctx, h, MUTT_PURGE, 1); + if (DeleteUntag) + mutt_set_flag(ctx, h, MUTT_TAG, 0); + } + } + + rc = 0; + +out: + if (cmd.data) + FREE(&cmd.data); + if (sync_cmd.data) + FREE(&sync_cmd.data); + FREE(&mx.mbox); + + return (rc < 0) ? -1 : rc; +} +",0,"int imap_copy_messages(struct Context *ctx, struct Header *h, char *dest, int delete) +{ + struct Buffer cmd, sync_cmd; + char mbox[PATH_MAX]; + char mmbox[PATH_MAX]; + char prompt[PATH_MAX + 64]; + int rc; + struct ImapMbox mx; + int err_continue = MUTT_NO; + int triedcreate = 0; + + struct ImapData *idata = ctx->data; + + if (imap_parse_path(dest, &mx)) + { + mutt_debug(1, ""bad destination %s\n"", dest); + return -1; + } + + /* check that the save-to folder is in the same account */ + if (mutt_account_match(&(idata->conn->account), &(mx.account)) == 0) + { + mutt_debug(3, ""%s not same server as %s\n"", dest, ctx->path); + return 1; + } + + if (h && h->attach_del) + { + mutt_debug(3, ""#1 Message contains attachments to be deleted\n""); + return 1; + } + + imap_fix_path(idata, mx.mbox, mbox, sizeof(mbox)); + if (!*mbox) + mutt_str_strfcpy(mbox, ""INBOX"", sizeof(mbox)); + imap_munge_mbox_name(idata, mmbox, sizeof(mmbox), mbox); + + /* loop in case of TRYCREATE */ + do + { + mutt_buffer_init(&sync_cmd); + mutt_buffer_init(&cmd); + + /* Null Header* means copy tagged messages */ + if (!h) + { + /* if any messages have attachments to delete, fall through to FETCH + * and APPEND. TODO: Copy what we can with COPY, fall through for the + * remainder. */ + for (int i = 0; i < ctx->msgcount; i++) + { + if (!message_is_tagged(ctx, i)) + continue; + + if (ctx->hdrs[i]->attach_del) + { + mutt_debug(3, ""#2 Message contains attachments to be deleted\n""); + return 1; + } + + if (ctx->hdrs[i]->active && ctx->hdrs[i]->changed) + { + rc = imap_sync_message_for_copy(idata, ctx->hdrs[i], &sync_cmd, &err_continue); + if (rc < 0) + { + mutt_debug(1, ""#1 could not sync\n""); + goto out; + } + } + } + + rc = imap_exec_msgset(idata, ""UID COPY"", mmbox, MUTT_TAG, 0, 0); + if (!rc) + { + mutt_debug(1, ""No messages tagged\n""); + rc = -1; + goto out; + } + else if (rc < 0) + { + mutt_debug(1, ""#1 could not queue copy\n""); + goto out; + } + else + { + mutt_message(ngettext(""Copying %d message to %s..."", ""Copying %d messages to %s..."", rc), + rc, mbox); + } + } + else + { + mutt_message(_(""Copying message %d to %s...""), h->index + 1, mbox); + mutt_buffer_printf(&cmd, ""UID COPY %u %s"", HEADER_DATA(h)->uid, mmbox); + + if (h->active && h->changed) + { + rc = imap_sync_message_for_copy(idata, h, &sync_cmd, &err_continue); + if (rc < 0) + { + mutt_debug(1, ""#2 could not sync\n""); + goto out; + } + } + rc = imap_exec(idata, cmd.data, IMAP_CMD_QUEUE); + if (rc < 0) + { + mutt_debug(1, ""#2 could not queue copy\n""); + goto out; + } + } + + /* let's get it on */ + rc = imap_exec(idata, NULL, IMAP_CMD_FAIL_OK); + if (rc == -2) + { + if (triedcreate) + { + mutt_debug(1, ""Already tried to create mailbox %s\n"", mbox); + break; + } + /* bail out if command failed for reasons other than nonexistent target */ + if (mutt_str_strncasecmp(imap_get_qualifier(idata->buf), ""[TRYCREATE]"", 11) != 0) + break; + mutt_debug(3, ""server suggests TRYCREATE\n""); + snprintf(prompt, sizeof(prompt), _(""Create %s?""), mbox); + if (Confirmcreate && mutt_yesorno(prompt, 1) != MUTT_YES) + { + mutt_clear_error(); + goto out; + } + if (imap_create_mailbox(idata, mbox) < 0) + break; + triedcreate = 1; + } + } while (rc == -2); + + if (rc != 0) + { + imap_error(""imap_copy_messages"", idata->buf); + goto out; + } + + /* cleanup */ + if (delete) + { + if (!h) + { + for (int i = 0; i < ctx->msgcount; i++) + { + if (!message_is_tagged(ctx, i)) + continue; + + mutt_set_flag(ctx, ctx->hdrs[i], MUTT_DELETE, 1); + mutt_set_flag(ctx, ctx->hdrs[i], MUTT_PURGE, 1); + if (DeleteUntag) + mutt_set_flag(ctx, ctx->hdrs[i], MUTT_TAG, 0); + } + } + else + { + mutt_set_flag(ctx, h, MUTT_DELETE, 1); + mutt_set_flag(ctx, h, MUTT_PURGE, 1); + if (DeleteUntag) + mutt_set_flag(ctx, h, MUTT_TAG, 0); + } + } + + rc = 0; + +out: + if (cmd.data) + FREE(&cmd.data); + if (sync_cmd.data) + FREE(&sync_cmd.data); + FREE(&mx.mbox); + + return (rc < 0) ? -1 : rc; +} +","@@ -330,7 +330,7 @@ static int msg_parse_fetch(struct ImapHeader *h, char *s) + } + s++; + ptmp = tmp; +- while (*s && *s != '\""') ++ while (*s && (*s != '\""') && (ptmp != (tmp + sizeof(tmp) - 1))) + *ptmp++ = *s++; + if (*s != '\""') + return -1; +@@ -343,7 +343,7 @@ static int msg_parse_fetch(struct ImapHeader *h, char *s) + s += 11; + SKIPWS(s); + ptmp = tmp; +- while (isdigit((unsigned char) *s)) ++ while (isdigit((unsigned char) *s) && (ptmp != (tmp + sizeof(tmp) - 1))) + *ptmp++ = *s++; + *ptmp = '\0'; + if (mutt_str_atol(tmp, &h->content_length) < 0)",1328,1659,2048 +9377,"xfs_do_writepage( + struct page *page, + struct writeback_control *wbc, + void *data) +{ + struct xfs_writepage_ctx *wpc = data; + struct inode *inode = page->mapping->host; + loff_t offset; + __uint64_t end_offset; + pgoff_t end_index; + + trace_xfs_writepage(inode, page, 0, 0); + + ASSERT(page_has_buffers(page)); + + /* + * Refuse to write the page out if we are called from reclaim context. + * + * This avoids stack overflows when called from deeply used stacks in + * random callers for direct reclaim or memcg reclaim. We explicitly + * allow reclaim from kswapd as the stack usage there is relatively low. + * + * This should never happen except in the case of a VM regression so + * warn about it. + */ + if (WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD)) == + PF_MEMALLOC)) + goto redirty; + + /* + * Given that we do not allow direct reclaim to call us, we should + * never be called while in a filesystem transaction. + */ + if (WARN_ON_ONCE(current->flags & PF_FSTRANS)) + goto redirty; + + /* + * Is this page beyond the end of the file? + * + * The page index is less than the end_index, adjust the end_offset + * to the highest offset that this page should represent. + * ----------------------------------------------------- + * | file mapping | | + * ----------------------------------------------------- + * | Page ... | Page N-2 | Page N-1 | Page N | | + * ^--------------------------------^----------|-------- + * | desired writeback range | see else | + * ---------------------------------^------------------| + */ + offset = i_size_read(inode); + end_index = offset >> PAGE_SHIFT; + if (page->index < end_index) + end_offset = (xfs_off_t)(page->index + 1) << PAGE_SHIFT; + else { + /* + * Check whether the page to write out is beyond or straddles + * i_size or not. + * ------------------------------------------------------- + * | file mapping | | + * ------------------------------------------------------- + * | Page ... | Page N-2 | Page N-1 | Page N | Beyond | + * ^--------------------------------^-----------|--------- + * | | Straddles | + * ---------------------------------^-----------|--------| + */ + unsigned offset_into_page = offset & (PAGE_SIZE - 1); + + /* + * Skip the page if it is fully outside i_size, e.g. due to a + * truncate operation that is in progress. We must redirty the + * page so that reclaim stops reclaiming it. Otherwise + * xfs_vm_releasepage() is called on it and gets confused. + * + * Note that the end_index is unsigned long, it would overflow + * if the given offset is greater than 16TB on 32-bit system + * and if we do check the page is fully outside i_size or not + * via ""if (page->index >= end_index + 1)"" as ""end_index + 1"" + * will be evaluated to 0. Hence this page will be redirtied + * and be written out repeatedly which would result in an + * infinite loop, the user program that perform this operation + * will hang. Instead, we can verify this situation by checking + * if the page to write is totally beyond the i_size or if it's + * offset is just equal to the EOF. + */ + if (page->index > end_index || + (page->index == end_index && offset_into_page == 0)) + goto redirty; + + /* + * The page straddles i_size. It must be zeroed out on each + * and every writepage invocation because it may be mmapped. + * ""A file is mapped in multiples of the page size. For a file + * that is not a multiple of the page size, the remaining + * memory is zeroed when mapped, and writes to that region are + * not written out to the file."" + */ + zero_user_segment(page, offset_into_page, PAGE_SIZE); + + /* Adjust the end_offset to the end of file */ + end_offset = offset; + } + + return xfs_writepage_map(wpc, wbc, inode, page, offset, end_offset); + +redirty: + redirty_page_for_writepage(wbc, page); + unlock_page(page); + return 0; +} +",0,"xfs_do_writepage( + struct page *page, + struct writeback_control *wbc, + void *data) +{ + struct xfs_writepage_ctx *wpc = data; + struct inode *inode = page->mapping->host; + loff_t offset; + __uint64_t end_offset; + pgoff_t end_index; + + trace_xfs_writepage(inode, page, 0, 0); + + ASSERT(page_has_buffers(page)); + + /* + * Refuse to write the page out if we are called from reclaim context. + * + * This avoids stack overflows when called from deeply used stacks in + * random callers for direct reclaim or memcg reclaim. We explicitly + * allow reclaim from kswapd as the stack usage there is relatively low. + * + * This should never happen except in the case of a VM regression so + * warn about it. + */ + if (WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD)) == + PF_MEMALLOC)) + goto redirty; + + /* + * Given that we do not allow direct reclaim to call us, we should + * never be called while in a filesystem transaction. + */ + if (WARN_ON_ONCE(current->flags & PF_FSTRANS)) + goto redirty; + + /* + * Is this page beyond the end of the file? + * + * The page index is less than the end_index, adjust the end_offset + * to the highest offset that this page should represent. + * ----------------------------------------------------- + * | file mapping | | + * ----------------------------------------------------- + * | Page ... | Page N-2 | Page N-1 | Page N | | + * ^--------------------------------^----------|-------- + * | desired writeback range | see else | + * ---------------------------------^------------------| + */ + offset = i_size_read(inode); + end_index = offset >> PAGE_SHIFT; + if (page->index < end_index) + end_offset = (xfs_off_t)(page->index + 1) << PAGE_SHIFT; + else { + /* + * Check whether the page to write out is beyond or straddles + * i_size or not. + * ------------------------------------------------------- + * | file mapping | | + * ------------------------------------------------------- + * | Page ... | Page N-2 | Page N-1 | Page N | Beyond | + * ^--------------------------------^-----------|--------- + * | | Straddles | + * ---------------------------------^-----------|--------| + */ + unsigned offset_into_page = offset & (PAGE_SIZE - 1); + + /* + * Skip the page if it is fully outside i_size, e.g. due to a + * truncate operation that is in progress. We must redirty the + * page so that reclaim stops reclaiming it. Otherwise + * xfs_vm_releasepage() is called on it and gets confused. + * + * Note that the end_index is unsigned long, it would overflow + * if the given offset is greater than 16TB on 32-bit system + * and if we do check the page is fully outside i_size or not + * via ""if (page->index >= end_index + 1)"" as ""end_index + 1"" + * will be evaluated to 0. Hence this page will be redirtied + * and be written out repeatedly which would result in an + * infinite loop, the user program that perform this operation + * will hang. Instead, we can verify this situation by checking + * if the page to write is totally beyond the i_size or if it's + * offset is just equal to the EOF. + */ + if (page->index > end_index || + (page->index == end_index && offset_into_page == 0)) + goto redirty; + + /* + * The page straddles i_size. It must be zeroed out on each + * and every writepage invocation because it may be mmapped. + * ""A file is mapped in multiples of the page size. For a file + * that is not a multiple of the page size, the remaining + * memory is zeroed when mapped, and writes to that region are + * not written out to the file."" + */ + zero_user_segment(page, offset_into_page, PAGE_SIZE); + + /* Adjust the end_offset to the end of file */ + end_offset = offset; + } + + return xfs_writepage_map(wpc, wbc, inode, page, offset, end_offset); + +redirty: + redirty_page_for_writepage(wbc, page); + unlock_page(page); + return 0; +} +","@@ -1361,6 +1361,26 @@ __xfs_get_blocks( + if (error) + goto out_unlock; + ++ /* ++ * The only time we can ever safely find delalloc blocks on direct I/O ++ * is a dio write to post-eof speculative preallocation. All other ++ * scenarios are indicative of a problem or misuse (such as mixing ++ * direct and mapped I/O). ++ * ++ * The file may be unmapped by the time we get here so we cannot ++ * reliably fail the I/O based on mapping. Instead, fail the I/O if this ++ * is a read or a write within eof. Otherwise, carry on but warn as a ++ * precuation if the file happens to be mapped. ++ */ ++ if (direct && imap.br_startblock == DELAYSTARTBLOCK) { ++ if (!create || offset < i_size_read(VFS_I(ip))) { ++ WARN_ON_ONCE(1); ++ error = -EIO; ++ goto out_unlock; ++ } ++ WARN_ON_ONCE(mapping_mapped(VFS_I(ip)->i_mapping)); ++ } ++ + /* for DAX, we convert unwritten extents directly */ + if (create && + (!nimaps || +@@ -1450,8 +1470,6 @@ __xfs_get_blocks( + (new || ISUNWRITTEN(&imap)))) + set_buffer_new(bh_result); + +- BUG_ON(direct && imap.br_startblock == DELAYSTARTBLOCK); +- + return 0; + + out_unlock:",1007,1338,2048 +2034,"i915_gem_execbuffer(struct drm_device *dev, void *data, + struct drm_file *file) +{ + struct drm_i915_gem_execbuffer *args = data; + struct drm_i915_gem_execbuffer2 exec2; + struct drm_i915_gem_exec_object *exec_list = NULL; + struct drm_i915_gem_exec_object2 *exec2_list = NULL; + int ret, i; + + if (args->buffer_count < 1) { + DRM_DEBUG(""execbuf with %d buffers\n"", args->buffer_count); + return -EINVAL; + } + + /* Copy in the exec list from userland */ + exec_list = drm_malloc_ab(sizeof(*exec_list), args->buffer_count); + exec2_list = drm_malloc_ab(sizeof(*exec2_list), args->buffer_count); + if (exec_list == NULL || exec2_list == NULL) { + DRM_DEBUG(""Failed to allocate exec list for %d buffers\n"", + args->buffer_count); + drm_free_large(exec_list); + drm_free_large(exec2_list); + return -ENOMEM; + } + ret = copy_from_user(exec_list, + (struct drm_i915_relocation_entry __user *) + (uintptr_t) args->buffers_ptr, + sizeof(*exec_list) * args->buffer_count); + if (ret != 0) { + DRM_DEBUG(""copy %d exec entries failed %d\n"", + args->buffer_count, ret); + drm_free_large(exec_list); + drm_free_large(exec2_list); + return -EFAULT; + } + + for (i = 0; i < args->buffer_count; i++) { + exec2_list[i].handle = exec_list[i].handle; + exec2_list[i].relocation_count = exec_list[i].relocation_count; + exec2_list[i].relocs_ptr = exec_list[i].relocs_ptr; + exec2_list[i].alignment = exec_list[i].alignment; + exec2_list[i].offset = exec_list[i].offset; + if (INTEL_INFO(dev)->gen < 4) + exec2_list[i].flags = EXEC_OBJECT_NEEDS_FENCE; + else + exec2_list[i].flags = 0; + } + + exec2.buffers_ptr = args->buffers_ptr; + exec2.buffer_count = args->buffer_count; + exec2.batch_start_offset = args->batch_start_offset; + exec2.batch_len = args->batch_len; + exec2.DR1 = args->DR1; + exec2.DR4 = args->DR4; + exec2.num_cliprects = args->num_cliprects; + exec2.cliprects_ptr = args->cliprects_ptr; + exec2.flags = I915_EXEC_RENDER; + + ret = i915_gem_do_execbuffer(dev, data, file, &exec2, exec2_list); + if (!ret) { + /* Copy the new buffer offsets back to the user's exec list. */ + for (i = 0; i < args->buffer_count; i++) + exec_list[i].offset = exec2_list[i].offset; + /* ... and back out to userspace */ + ret = copy_to_user((struct drm_i915_relocation_entry __user *) + (uintptr_t) args->buffers_ptr, + exec_list, + sizeof(*exec_list) * args->buffer_count); + if (ret) { + ret = -EFAULT; + DRM_DEBUG(""failed to copy %d exec entries "" + ""back to user (%d)\n"", + args->buffer_count, ret); + } + } + + drm_free_large(exec_list); + drm_free_large(exec2_list); + return ret; +} +",0,"i915_gem_execbuffer(struct drm_device *dev, void *data, + struct drm_file *file) +{ + struct drm_i915_gem_execbuffer *args = data; + struct drm_i915_gem_execbuffer2 exec2; + struct drm_i915_gem_exec_object *exec_list = NULL; + struct drm_i915_gem_exec_object2 *exec2_list = NULL; + int ret, i; + + if (args->buffer_count < 1) { + DRM_DEBUG(""execbuf with %d buffers\n"", args->buffer_count); + return -EINVAL; + } + + /* Copy in the exec list from userland */ + exec_list = drm_malloc_ab(sizeof(*exec_list), args->buffer_count); + exec2_list = drm_malloc_ab(sizeof(*exec2_list), args->buffer_count); + if (exec_list == NULL || exec2_list == NULL) { + DRM_DEBUG(""Failed to allocate exec list for %d buffers\n"", + args->buffer_count); + drm_free_large(exec_list); + drm_free_large(exec2_list); + return -ENOMEM; + } + ret = copy_from_user(exec_list, + (struct drm_i915_relocation_entry __user *) + (uintptr_t) args->buffers_ptr, + sizeof(*exec_list) * args->buffer_count); + if (ret != 0) { + DRM_DEBUG(""copy %d exec entries failed %d\n"", + args->buffer_count, ret); + drm_free_large(exec_list); + drm_free_large(exec2_list); + return -EFAULT; + } + + for (i = 0; i < args->buffer_count; i++) { + exec2_list[i].handle = exec_list[i].handle; + exec2_list[i].relocation_count = exec_list[i].relocation_count; + exec2_list[i].relocs_ptr = exec_list[i].relocs_ptr; + exec2_list[i].alignment = exec_list[i].alignment; + exec2_list[i].offset = exec_list[i].offset; + if (INTEL_INFO(dev)->gen < 4) + exec2_list[i].flags = EXEC_OBJECT_NEEDS_FENCE; + else + exec2_list[i].flags = 0; + } + + exec2.buffers_ptr = args->buffers_ptr; + exec2.buffer_count = args->buffer_count; + exec2.batch_start_offset = args->batch_start_offset; + exec2.batch_len = args->batch_len; + exec2.DR1 = args->DR1; + exec2.DR4 = args->DR4; + exec2.num_cliprects = args->num_cliprects; + exec2.cliprects_ptr = args->cliprects_ptr; + exec2.flags = I915_EXEC_RENDER; + + ret = i915_gem_do_execbuffer(dev, data, file, &exec2, exec2_list); + if (!ret) { + /* Copy the new buffer offsets back to the user's exec list. */ + for (i = 0; i < args->buffer_count; i++) + exec_list[i].offset = exec2_list[i].offset; + /* ... and back out to userspace */ + ret = copy_to_user((struct drm_i915_relocation_entry __user *) + (uintptr_t) args->buffers_ptr, + exec_list, + sizeof(*exec_list) * args->buffer_count); + if (ret) { + ret = -EFAULT; + DRM_DEBUG(""failed to copy %d exec entries "" + ""back to user (%d)\n"", + args->buffer_count, ret); + } + } + + drm_free_large(exec_list); + drm_free_large(exec2_list); + return ret; +} +","@@ -1133,6 +1133,11 @@ i915_gem_do_execbuffer(struct drm_device *dev, void *data, + return -EINVAL; + } + ++ if (args->num_cliprects > UINT_MAX / sizeof(*cliprects)) { ++ DRM_DEBUG(""execbuf with %u cliprects\n"", ++ args->num_cliprects); ++ return -EINVAL; ++ } + cliprects = kmalloc(args->num_cliprects * sizeof(*cliprects), + GFP_KERNEL); + if (cliprects == NULL) {",777,1108,2048 +493,"user_update_from_pwent (User *user, + struct passwd *pwent, + struct spwd *spent) +{ + g_autofree gchar *real_name = NULL; + gboolean is_system_account; + const gchar *passwd; + gboolean locked; + PasswordMode mode; + AccountType account_type; + + g_object_freeze_notify (G_OBJECT (user)); + + if (pwent->pw_gecos && pwent->pw_gecos[0] != '\0') { + gchar *first_comma = NULL; + gchar *valid_utf8_name = NULL; + + if (g_utf8_validate (pwent->pw_gecos, -1, NULL)) { + valid_utf8_name = pwent->pw_gecos; + first_comma = g_utf8_strchr (valid_utf8_name, -1, ','); + } + else { + g_warning (""User %s has invalid UTF-8 in GECOS field. "" + ""It would be a good thing to check /etc/passwd."", + pwent->pw_name ? pwent->pw_name : """"); + } + + if (first_comma) { + real_name = g_strndup (valid_utf8_name, + (first_comma - valid_utf8_name)); + } + else if (valid_utf8_name) { + real_name = g_strdup (valid_utf8_name); + } + else { + real_name = NULL; + } + + if (real_name && real_name[0] == '\0') { + g_clear_pointer (&real_name, g_free); + } + } + else { + real_name = NULL; + } + + accounts_user_set_real_name (ACCOUNTS_USER (user), real_name); + accounts_user_set_uid (ACCOUNTS_USER (user), pwent->pw_uid); + + user->gid = pwent->pw_gid; + + account_type = account_type_from_pwent (pwent); + accounts_user_set_account_type (ACCOUNTS_USER (user), account_type); + + accounts_user_set_user_name (ACCOUNTS_USER (user), pwent->pw_name); + accounts_user_set_home_directory (ACCOUNTS_USER (user), pwent->pw_dir); + user_reset_icon_file (user); + + accounts_user_set_shell (ACCOUNTS_USER (user), pwent->pw_shell); + + passwd = NULL; + if (spent) + passwd = spent->sp_pwdp; + + if (passwd && passwd[0] == '!') { + locked = TRUE; + } + else { + locked = FALSE; + } + + accounts_user_set_locked (ACCOUNTS_USER (user), locked); + + if (passwd == NULL || passwd[0] != 0) { + mode = PASSWORD_MODE_REGULAR; + } + else { + mode = PASSWORD_MODE_NONE; + } + + if (spent) { + if (spent->sp_lstchg == 0) { + mode = PASSWORD_MODE_SET_AT_LOGIN; + } + + user->expiration_time = spent->sp_expire; + user->last_change_time = spent->sp_lstchg; + user->min_days_between_changes = spent->sp_min; + user->max_days_between_changes = spent->sp_max; + user->days_to_warn = spent->sp_warn; + user->days_after_expiration_until_lock = spent->sp_inact; + user->account_expiration_policy_known = TRUE; + } + + accounts_user_set_password_mode (ACCOUNTS_USER (user), mode); + is_system_account = !user_classify_is_human (accounts_user_get_uid (ACCOUNTS_USER (user)), + accounts_user_get_user_name (ACCOUNTS_USER (user)), + accounts_user_get_shell (ACCOUNTS_USER (user)), + passwd); + accounts_user_set_system_account (ACCOUNTS_USER (user), is_system_account); + + g_object_thaw_notify (G_OBJECT (user)); +} +",0,"user_update_from_pwent (User *user, + struct passwd *pwent, + struct spwd *spent) +{ + g_autofree gchar *real_name = NULL; + gboolean is_system_account; + const gchar *passwd; + gboolean locked; + PasswordMode mode; + AccountType account_type; + + g_object_freeze_notify (G_OBJECT (user)); + + if (pwent->pw_gecos && pwent->pw_gecos[0] != '\0') { + gchar *first_comma = NULL; + gchar *valid_utf8_name = NULL; + + if (g_utf8_validate (pwent->pw_gecos, -1, NULL)) { + valid_utf8_name = pwent->pw_gecos; + first_comma = g_utf8_strchr (valid_utf8_name, -1, ','); + } + else { + g_warning (""User %s has invalid UTF-8 in GECOS field. "" + ""It would be a good thing to check /etc/passwd."", + pwent->pw_name ? pwent->pw_name : """"); + } + + if (first_comma) { + real_name = g_strndup (valid_utf8_name, + (first_comma - valid_utf8_name)); + } + else if (valid_utf8_name) { + real_name = g_strdup (valid_utf8_name); + } + else { + real_name = NULL; + } + + if (real_name && real_name[0] == '\0') { + g_clear_pointer (&real_name, g_free); + } + } + else { + real_name = NULL; + } + + accounts_user_set_real_name (ACCOUNTS_USER (user), real_name); + accounts_user_set_uid (ACCOUNTS_USER (user), pwent->pw_uid); + + user->gid = pwent->pw_gid; + + account_type = account_type_from_pwent (pwent); + accounts_user_set_account_type (ACCOUNTS_USER (user), account_type); + + accounts_user_set_user_name (ACCOUNTS_USER (user), pwent->pw_name); + accounts_user_set_home_directory (ACCOUNTS_USER (user), pwent->pw_dir); + user_reset_icon_file (user); + + accounts_user_set_shell (ACCOUNTS_USER (user), pwent->pw_shell); + + passwd = NULL; + if (spent) + passwd = spent->sp_pwdp; + + if (passwd && passwd[0] == '!') { + locked = TRUE; + } + else { + locked = FALSE; + } + + accounts_user_set_locked (ACCOUNTS_USER (user), locked); + + if (passwd == NULL || passwd[0] != 0) { + mode = PASSWORD_MODE_REGULAR; + } + else { + mode = PASSWORD_MODE_NONE; + } + + if (spent) { + if (spent->sp_lstchg == 0) { + mode = PASSWORD_MODE_SET_AT_LOGIN; + } + + user->expiration_time = spent->sp_expire; + user->last_change_time = spent->sp_lstchg; + user->min_days_between_changes = spent->sp_min; + user->max_days_between_changes = spent->sp_max; + user->days_to_warn = spent->sp_warn; + user->days_after_expiration_until_lock = spent->sp_inact; + user->account_expiration_policy_known = TRUE; + } + + accounts_user_set_password_mode (ACCOUNTS_USER (user), mode); + is_system_account = !user_classify_is_human (accounts_user_get_uid (ACCOUNTS_USER (user)), + accounts_user_get_user_name (ACCOUNTS_USER (user)), + accounts_user_get_shell (ACCOUNTS_USER (user)), + passwd); + accounts_user_set_system_account (ACCOUNTS_USER (user), is_system_account); + + g_object_thaw_notify (G_OBJECT (user)); +} +","@@ -1334,6 +1334,14 @@ user_change_icon_file_authorized_cb (Daemon *daemon, + } + + file = g_file_new_for_path (filename); ++ g_clear_pointer (&filename, g_free); ++ ++ /* Canonicalize path so we can call g_str_has_prefix on it ++ * below without concern for ../ path components moving outside ++ * the prefix ++ */ ++ filename = g_file_get_path (file); ++ + info = g_file_query_info (file, G_FILE_ATTRIBUTE_UNIX_MODE "","" + G_FILE_ATTRIBUTE_STANDARD_TYPE "","" + G_FILE_ATTRIBUTE_STANDARD_SIZE,",802,1133,2048 +7238,"static Image *ReadTEXTImage(const ImageInfo *image_info, + ExceptionInfo *exception) +{ + char + filename[MagickPathExtent], + geometry[MagickPathExtent], + *p, + text[MagickPathExtent]; + + DrawInfo + *draw_info; + + Image + *image, + *texture; + + MagickBooleanType + status; + + PointInfo + delta; + + RectangleInfo + page; + + ssize_t + offset; + + TypeMetric + metrics; + + /* + 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); + } + (void) ResetMagickMemory(text,0,sizeof(text)); + (void) ReadBlobString(image,text); + /* + Set the page geometry. + */ + delta.x=DefaultResolution; + delta.y=DefaultResolution; + if ((image->resolution.x == 0.0) || (image->resolution.y == 0.0)) + { + GeometryInfo + geometry_info; + + MagickStatusType + flags; + + flags=ParseGeometry(PSDensityGeometry,&geometry_info); + image->resolution.x=geometry_info.rho; + image->resolution.y=geometry_info.sigma; + if ((flags & SigmaValue) == 0) + image->resolution.y=image->resolution.x; + } + page.width=612; + page.height=792; + page.x=43; + page.y=43; + if (image_info->page != (char *) NULL) + (void) ParseAbsoluteGeometry(image_info->page,&page); + /* + Initialize Image structure. + */ + image->columns=(size_t) floor((((double) page.width*image->resolution.x)/ + delta.x)+0.5); + image->rows=(size_t) floor((((double) page.height*image->resolution.y)/ + delta.y)+0.5); + status=SetImageExtent(image,image->columns,image->rows,exception); + if (status == MagickFalse) + return(DestroyImageList(image)); + image->page.x=0; + image->page.y=0; + texture=(Image *) NULL; + if (image_info->texture != (char *) NULL) + { + ImageInfo + *read_info; + + read_info=CloneImageInfo(image_info); + SetImageInfoBlob(read_info,(void *) NULL,0); + (void) CopyMagickString(read_info->filename,image_info->texture, + MagickPathExtent); + texture=ReadImage(read_info,exception); + read_info=DestroyImageInfo(read_info); + } + /* + Annotate the text image. + */ + (void) SetImageBackgroundColor(image,exception); + draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); + (void) CloneString(&draw_info->text,image_info->filename); + (void) FormatLocaleString(geometry,MagickPathExtent,""%gx%g%+g%+g"",(double) + image->columns,(double) image->rows,(double) page.x,(double) page.y); + (void) CloneString(&draw_info->geometry,geometry); + status=GetTypeMetrics(image,draw_info,&metrics,exception); + if (status == MagickFalse) + ThrowReaderException(TypeError,""UnableToGetTypeMetrics""); + page.y=(ssize_t) ceil((double) page.y+metrics.ascent-0.5); + (void) FormatLocaleString(geometry,MagickPathExtent,""%gx%g%+g%+g"",(double) + image->columns,(double) image->rows,(double) page.x,(double) page.y); + (void) CloneString(&draw_info->geometry,geometry); + (void) CopyMagickString(filename,image_info->filename,MagickPathExtent); + if (*draw_info->text != '\0') + *draw_info->text='\0'; + p=text; + for (offset=2*page.y; p != (char *) NULL; ) + { + /* + Annotate image with text. + */ + (void) ConcatenateString(&draw_info->text,text); + (void) ConcatenateString(&draw_info->text,""\n""); + offset+=(ssize_t) (metrics.ascent-metrics.descent); + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) offset, + image->rows); + if (status == MagickFalse) + break; + } + p=ReadBlobString(image,text); + if ((offset < (ssize_t) image->rows) && (p != (char *) NULL)) + continue; + if (texture != (Image *) NULL) + { + MagickProgressMonitor + progress_monitor; + + progress_monitor=SetImageProgressMonitor(image, + (MagickProgressMonitor) NULL,image->client_data); + (void) TextureImage(image,texture,exception); + (void) SetImageProgressMonitor(image,progress_monitor, + image->client_data); + } + (void) AnnotateImage(image,draw_info,exception); + if (p == (char *) NULL) + break; + /* + Page is full-- allocate next image structure. + */ + *draw_info->text='\0'; + offset=2*page.y; + AcquireNextImage(image_info,image,exception); + if (GetNextImageInList(image) == (Image *) NULL) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + image->next->columns=image->columns; + image->next->rows=image->rows; + image=SyncNextImageInList(image); + (void) CopyMagickString(image->filename,filename,MagickPathExtent); + (void) SetImageBackgroundColor(image,exception); + status=SetImageProgress(image,LoadImagesTag,TellBlob(image), + GetBlobSize(image)); + if (status == MagickFalse) + break; + } + if (texture != (Image *) NULL) + { + MagickProgressMonitor + progress_monitor; + + progress_monitor=SetImageProgressMonitor(image, + (MagickProgressMonitor) NULL,image->client_data); + (void) TextureImage(image,texture,exception); + (void) SetImageProgressMonitor(image,progress_monitor,image->client_data); + } + (void) AnnotateImage(image,draw_info,exception); + if (texture != (Image *) NULL) + texture=DestroyImage(texture); + draw_info=DestroyDrawInfo(draw_info); + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +",0,"static Image *ReadTEXTImage(const ImageInfo *image_info, + ExceptionInfo *exception) +{ + char + filename[MagickPathExtent], + geometry[MagickPathExtent], + *p, + text[MagickPathExtent]; + + DrawInfo + *draw_info; + + Image + *image, + *texture; + + MagickBooleanType + status; + + PointInfo + delta; + + RectangleInfo + page; + + ssize_t + offset; + + TypeMetric + metrics; + + /* + 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); + } + (void) ResetMagickMemory(text,0,sizeof(text)); + (void) ReadBlobString(image,text); + /* + Set the page geometry. + */ + delta.x=DefaultResolution; + delta.y=DefaultResolution; + if ((image->resolution.x == 0.0) || (image->resolution.y == 0.0)) + { + GeometryInfo + geometry_info; + + MagickStatusType + flags; + + flags=ParseGeometry(PSDensityGeometry,&geometry_info); + image->resolution.x=geometry_info.rho; + image->resolution.y=geometry_info.sigma; + if ((flags & SigmaValue) == 0) + image->resolution.y=image->resolution.x; + } + page.width=612; + page.height=792; + page.x=43; + page.y=43; + if (image_info->page != (char *) NULL) + (void) ParseAbsoluteGeometry(image_info->page,&page); + /* + Initialize Image structure. + */ + image->columns=(size_t) floor((((double) page.width*image->resolution.x)/ + delta.x)+0.5); + image->rows=(size_t) floor((((double) page.height*image->resolution.y)/ + delta.y)+0.5); + status=SetImageExtent(image,image->columns,image->rows,exception); + if (status == MagickFalse) + return(DestroyImageList(image)); + image->page.x=0; + image->page.y=0; + texture=(Image *) NULL; + if (image_info->texture != (char *) NULL) + { + ImageInfo + *read_info; + + read_info=CloneImageInfo(image_info); + SetImageInfoBlob(read_info,(void *) NULL,0); + (void) CopyMagickString(read_info->filename,image_info->texture, + MagickPathExtent); + texture=ReadImage(read_info,exception); + read_info=DestroyImageInfo(read_info); + } + /* + Annotate the text image. + */ + (void) SetImageBackgroundColor(image,exception); + draw_info=CloneDrawInfo(image_info,(DrawInfo *) NULL); + (void) CloneString(&draw_info->text,image_info->filename); + (void) FormatLocaleString(geometry,MagickPathExtent,""%gx%g%+g%+g"",(double) + image->columns,(double) image->rows,(double) page.x,(double) page.y); + (void) CloneString(&draw_info->geometry,geometry); + status=GetTypeMetrics(image,draw_info,&metrics,exception); + if (status == MagickFalse) + ThrowReaderException(TypeError,""UnableToGetTypeMetrics""); + page.y=(ssize_t) ceil((double) page.y+metrics.ascent-0.5); + (void) FormatLocaleString(geometry,MagickPathExtent,""%gx%g%+g%+g"",(double) + image->columns,(double) image->rows,(double) page.x,(double) page.y); + (void) CloneString(&draw_info->geometry,geometry); + (void) CopyMagickString(filename,image_info->filename,MagickPathExtent); + if (*draw_info->text != '\0') + *draw_info->text='\0'; + p=text; + for (offset=2*page.y; p != (char *) NULL; ) + { + /* + Annotate image with text. + */ + (void) ConcatenateString(&draw_info->text,text); + (void) ConcatenateString(&draw_info->text,""\n""); + offset+=(ssize_t) (metrics.ascent-metrics.descent); + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) offset, + image->rows); + if (status == MagickFalse) + break; + } + p=ReadBlobString(image,text); + if ((offset < (ssize_t) image->rows) && (p != (char *) NULL)) + continue; + if (texture != (Image *) NULL) + { + MagickProgressMonitor + progress_monitor; + + progress_monitor=SetImageProgressMonitor(image, + (MagickProgressMonitor) NULL,image->client_data); + (void) TextureImage(image,texture,exception); + (void) SetImageProgressMonitor(image,progress_monitor, + image->client_data); + } + (void) AnnotateImage(image,draw_info,exception); + if (p == (char *) NULL) + break; + /* + Page is full-- allocate next image structure. + */ + *draw_info->text='\0'; + offset=2*page.y; + AcquireNextImage(image_info,image,exception); + if (GetNextImageInList(image) == (Image *) NULL) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + image->next->columns=image->columns; + image->next->rows=image->rows; + image=SyncNextImageInList(image); + (void) CopyMagickString(image->filename,filename,MagickPathExtent); + (void) SetImageBackgroundColor(image,exception); + status=SetImageProgress(image,LoadImagesTag,TellBlob(image), + GetBlobSize(image)); + if (status == MagickFalse) + break; + } + if (texture != (Image *) NULL) + { + MagickProgressMonitor + progress_monitor; + + progress_monitor=SetImageProgressMonitor(image, + (MagickProgressMonitor) NULL,image->client_data); + (void) TextureImage(image,texture,exception); + (void) SetImageProgressMonitor(image,progress_monitor,image->client_data); + } + (void) AnnotateImage(image,draw_info,exception); + if (texture != (Image *) NULL) + texture=DestroyImage(texture); + draw_info=DestroyDrawInfo(draw_info); + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +","@@ -793,8 +793,7 @@ static MagickBooleanType WriteTXTImage(const ImageInfo *image_info,Image *image, + (void) WriteBlobString(image,buffer); + (void) CopyMagickString(tuple,""("",MagickPathExtent); + if (pixel.colorspace == GRAYColorspace) +- ConcatenateColorComponent(&pixel,GrayPixelChannel,compliance, +- tuple); ++ ConcatenateColorComponent(&pixel,GrayPixelChannel,compliance,tuple); + else + { + ConcatenateColorComponent(&pixel,RedPixelChannel,compliance,tuple);",1517,1848,2048 +18099,"pimv1_join_prune_print(netdissect_options *ndo, + register const u_char *bp, register u_int len) +{ + int ngroups, njoin, nprune; + int njp; + + /* If it's a single group and a single source, use 1-line output. */ + if (ND_TTEST2(bp[0], 30) && bp[11] == 1 && + ((njoin = EXTRACT_16BITS(&bp[20])) + EXTRACT_16BITS(&bp[22])) == 1) { + int hold; + + ND_PRINT((ndo, "" RPF %s "", ipaddr_string(ndo, bp))); + hold = EXTRACT_16BITS(&bp[6]); + if (hold != 180) { + ND_PRINT((ndo, ""Hold "")); + unsigned_relts_print(ndo, hold); + } + ND_PRINT((ndo, ""%s (%s/%d, %s"", njoin ? ""Join"" : ""Prune"", + ipaddr_string(ndo, &bp[26]), bp[25] & 0x3f, + ipaddr_string(ndo, &bp[12]))); + if (EXTRACT_32BITS(&bp[16]) != 0xffffffff) + ND_PRINT((ndo, ""/%s"", ipaddr_string(ndo, &bp[16]))); + ND_PRINT((ndo, "") %s%s %s"", + (bp[24] & 0x01) ? ""Sparse"" : ""Dense"", + (bp[25] & 0x80) ? "" WC"" : """", + (bp[25] & 0x40) ? ""RP"" : ""SPT"")); + return; + } + + ND_TCHECK2(bp[0], sizeof(struct in_addr)); + if (ndo->ndo_vflag > 1) + ND_PRINT((ndo, ""\n"")); + ND_PRINT((ndo, "" Upstream Nbr: %s"", ipaddr_string(ndo, bp))); + ND_TCHECK2(bp[6], 2); + if (ndo->ndo_vflag > 1) + ND_PRINT((ndo, ""\n"")); + ND_PRINT((ndo, "" Hold time: "")); + unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[6])); + if (ndo->ndo_vflag < 2) + return; + bp += 8; + len -= 8; + + ND_TCHECK2(bp[0], 4); + ngroups = bp[3]; + bp += 4; + len -= 4; + while (ngroups--) { + /* + * XXX - does the address have length ""addrlen"" and the + * mask length ""maddrlen""? + */ + ND_TCHECK2(bp[0], sizeof(struct in_addr)); + ND_PRINT((ndo, ""\n\tGroup: %s"", ipaddr_string(ndo, bp))); + ND_TCHECK2(bp[4], sizeof(struct in_addr)); + if (EXTRACT_32BITS(&bp[4]) != 0xffffffff) + ND_PRINT((ndo, ""/%s"", ipaddr_string(ndo, &bp[4]))); + ND_TCHECK2(bp[8], 4); + njoin = EXTRACT_16BITS(&bp[8]); + nprune = EXTRACT_16BITS(&bp[10]); + ND_PRINT((ndo, "" joined: %d pruned: %d"", njoin, nprune)); + bp += 12; + len -= 12; + for (njp = 0; njp < (njoin + nprune); njp++) { + const char *type; + + if (njp < njoin) + type = ""Join ""; + else + type = ""Prune""; + ND_TCHECK2(bp[0], 6); + ND_PRINT((ndo, ""\n\t%s %s%s%s%s/%d"", type, + (bp[0] & 0x01) ? ""Sparse "" : ""Dense "", + (bp[1] & 0x80) ? ""WC "" : """", + (bp[1] & 0x40) ? ""RP "" : ""SPT "", + ipaddr_string(ndo, &bp[2]), bp[1] & 0x3f)); + bp += 6; + len -= 6; + } + } + return; +trunc: + ND_PRINT((ndo, ""[|pim]"")); + return; +} +",1,"pimv1_join_prune_print(netdissect_options *ndo, + register const u_char *bp, register u_int len) +{ + int ngroups, njoin, nprune; + int njp; + + /* If it's a single group and a single source, use 1-line output. */ + if (ND_TTEST2(bp[0], 30) && bp[11] == 1 && + ((njoin = EXTRACT_16BITS(&bp[20])) + EXTRACT_16BITS(&bp[22])) == 1) { + int hold; + + ND_PRINT((ndo, "" RPF %s "", ipaddr_string(ndo, bp))); + hold = EXTRACT_16BITS(&bp[6]); + if (hold != 180) { + ND_PRINT((ndo, ""Hold "")); + unsigned_relts_print(ndo, hold); + } + ND_PRINT((ndo, ""%s (%s/%d, %s"", njoin ? ""Join"" : ""Prune"", + ipaddr_string(ndo, &bp[26]), bp[25] & 0x3f, + ipaddr_string(ndo, &bp[12]))); + if (EXTRACT_32BITS(&bp[16]) != 0xffffffff) + ND_PRINT((ndo, ""/%s"", ipaddr_string(ndo, &bp[16]))); + ND_PRINT((ndo, "") %s%s %s"", + (bp[24] & 0x01) ? ""Sparse"" : ""Dense"", + (bp[25] & 0x80) ? "" WC"" : """", + (bp[25] & 0x40) ? ""RP"" : ""SPT"")); + return; + } + + if (len < sizeof(struct in_addr)) + goto trunc; + ND_TCHECK2(bp[0], sizeof(struct in_addr)); + if (ndo->ndo_vflag > 1) + ND_PRINT((ndo, ""\n"")); + ND_PRINT((ndo, "" Upstream Nbr: %s"", ipaddr_string(ndo, bp))); + bp += 4; + len -= 4; + if (len < 4) + goto trunc; + ND_TCHECK2(bp[2], 2); + if (ndo->ndo_vflag > 1) + ND_PRINT((ndo, ""\n"")); + ND_PRINT((ndo, "" Hold time: "")); + unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2])); + if (ndo->ndo_vflag < 2) + return; + bp += 4; + len -= 4; + + if (len < 4) + goto trunc; + ND_TCHECK2(bp[0], 4); + ngroups = bp[3]; + bp += 4; + len -= 4; + while (ngroups--) { + /* + * XXX - does the address have length ""addrlen"" and the + * mask length ""maddrlen""? + */ + if (len < 4) + goto trunc; + ND_TCHECK2(bp[0], sizeof(struct in_addr)); + ND_PRINT((ndo, ""\n\tGroup: %s"", ipaddr_string(ndo, bp))); + bp += 4; + len -= 4; + if (len < 4) + goto trunc; + ND_TCHECK2(bp[0], sizeof(struct in_addr)); + if (EXTRACT_32BITS(&bp[0]) != 0xffffffff) + ND_PRINT((ndo, ""/%s"", ipaddr_string(ndo, &bp[0]))); + bp += 4; + len -= 4; + if (len < 4) + goto trunc; + ND_TCHECK2(bp[0], 4); + njoin = EXTRACT_16BITS(&bp[0]); + nprune = EXTRACT_16BITS(&bp[2]); + ND_PRINT((ndo, "" joined: %d pruned: %d"", njoin, nprune)); + bp += 4; + len -= 4; + for (njp = 0; njp < (njoin + nprune); njp++) { + const char *type; + + if (njp < njoin) + type = ""Join ""; + else + type = ""Prune""; + if (len < 6) + goto trunc; + ND_TCHECK2(bp[0], 6); + ND_PRINT((ndo, ""\n\t%s %s%s%s%s/%d"", type, + (bp[0] & 0x01) ? ""Sparse "" : ""Dense "", + (bp[1] & 0x80) ? ""WC "" : """", + (bp[1] & 0x40) ? ""RP "" : ""SPT "", + ipaddr_string(ndo, &bp[2]), + bp[1] & 0x3f)); + bp += 6; + len -= 6; + } + } + return; +trunc: + ND_PRINT((ndo, ""[|pim]"")); + return; +} +","@@ -169,20 +169,28 @@ pimv1_join_prune_print(netdissect_options *ndo, + return; + } + ++ if (len < sizeof(struct in_addr)) ++ goto trunc; + ND_TCHECK2(bp[0], sizeof(struct in_addr)); + if (ndo->ndo_vflag > 1) + ND_PRINT((ndo, ""\n"")); + ND_PRINT((ndo, "" Upstream Nbr: %s"", ipaddr_string(ndo, bp))); +- ND_TCHECK2(bp[6], 2); ++ bp += 4; ++ len -= 4; ++ if (len < 4) ++ goto trunc; ++ ND_TCHECK2(bp[2], 2); + if (ndo->ndo_vflag > 1) + ND_PRINT((ndo, ""\n"")); + ND_PRINT((ndo, "" Hold time: "")); +- unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[6])); ++ unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2])); + if (ndo->ndo_vflag < 2) + return; +- bp += 8; +- len -= 8; ++ bp += 4; ++ len -= 4; + ++ if (len < 4) ++ goto trunc; + ND_TCHECK2(bp[0], 4); + ngroups = bp[3]; + bp += 4; +@@ -192,30 +200,43 @@ pimv1_join_prune_print(netdissect_options *ndo, + * XXX - does the address have length ""addrlen"" and the + * mask length ""maddrlen""? + */ ++ if (len < 4) ++ goto trunc; + ND_TCHECK2(bp[0], sizeof(struct in_addr)); + ND_PRINT((ndo, ""\n\tGroup: %s"", ipaddr_string(ndo, bp))); +- ND_TCHECK2(bp[4], sizeof(struct in_addr)); +- if (EXTRACT_32BITS(&bp[4]) != 0xffffffff) +- ND_PRINT((ndo, ""/%s"", ipaddr_string(ndo, &bp[4]))); +- ND_TCHECK2(bp[8], 4); +- njoin = EXTRACT_16BITS(&bp[8]); +- nprune = EXTRACT_16BITS(&bp[10]); ++ bp += 4; ++ len -= 4; ++ if (len < 4) ++ goto trunc; ++ ND_TCHECK2(bp[0], sizeof(struct in_addr)); ++ if (EXTRACT_32BITS(&bp[0]) != 0xffffffff) ++ ND_PRINT((ndo, ""/%s"", ipaddr_string(ndo, &bp[0]))); ++ bp += 4; ++ len -= 4; ++ if (len < 4) ++ goto trunc; ++ ND_TCHECK2(bp[0], 4); ++ njoin = EXTRACT_16BITS(&bp[0]); ++ nprune = EXTRACT_16BITS(&bp[2]); + ND_PRINT((ndo, "" joined: %d pruned: %d"", njoin, nprune)); +- bp += 12; +- len -= 12; ++ bp += 4; ++ len -= 4; + for (njp = 0; njp < (njoin + nprune); njp++) { + const char *type; + + if (njp < njoin) + type = ""Join ""; + else + type = ""Prune""; ++ if (len < 6) ++ goto trunc; + ND_TCHECK2(bp[0], 6); + ND_PRINT((ndo, ""\n\t%s %s%s%s%s/%d"", type, + (bp[0] & 0x01) ? ""Sparse "" : ""Dense "", + (bp[1] & 0x80) ? ""WC "" : """", + (bp[1] & 0x40) ? ""RP "" : ""SPT "", +- ipaddr_string(ndo, &bp[2]), bp[1] & 0x3f)); ++ ipaddr_string(ndo, &bp[2]), ++ bp[1] & 0x3f)); + bp += 6; + len -= 6; + } +@@ -230,13 +251,8 @@ void + pimv1_print(netdissect_options *ndo, + register const u_char *bp, register u_int len) + { +- register const u_char *ep; + register u_char type; + +- ep = (const u_char *)ndo->ndo_snapend; +- if (bp >= ep) +- return; +- + ND_TCHECK(bp[1]); + type = bp[1]; + +@@ -302,8 +318,11 @@ pimv1_print(netdissect_options *ndo, + case PIMV1_TYPE_JOIN_PRUNE: + case PIMV1_TYPE_GRAFT: + case PIMV1_TYPE_GRAFT_ACK: +- if (ndo->ndo_vflag) ++ if (ndo->ndo_vflag) { ++ if (len < 8) ++ goto trunc; + pimv1_join_prune_print(ndo, &bp[8], len - 8); ++ } + break; + } + ND_TCHECK(bp[4]); +@@ -330,6 +349,8 @@ cisco_autorp_print(netdissect_options *ndo, + int numrps; + int hold; + ++ if (len < 8) ++ goto trunc; + ND_TCHECK(bp[0]); + ND_PRINT((ndo, "" auto-rp "")); + type = bp[0]; +@@ -377,10 +398,16 @@ cisco_autorp_print(netdissect_options *ndo, + int nentries; + char s; + ++ if (len < 4) ++ goto trunc; + ND_TCHECK2(bp[0], 4); + ND_PRINT((ndo, "" RP %s"", ipaddr_string(ndo, bp))); +- ND_TCHECK(bp[4]); +- switch (bp[4] & 0x3) { ++ bp += 4; ++ len -= 4; ++ if (len < 1) ++ goto trunc; ++ ND_TCHECK(bp[0]); ++ switch (bp[0] & 0x3) { + case 0: ND_PRINT((ndo, "" PIMv?"")); + break; + case 1: ND_PRINT((ndo, "" PIMv1"")); +@@ -390,13 +417,20 @@ cisco_autorp_print(netdissect_options *ndo, + case 3: ND_PRINT((ndo, "" PIMv1+2"")); + break; + } +- if (bp[4] & 0xfc) +- ND_PRINT((ndo, "" [rsvd=0x%02x]"", bp[4] & 0xfc)); +- ND_TCHECK(bp[5]); +- nentries = bp[5]; +- bp += 6; len -= 6; ++ if (bp[0] & 0xfc) ++ ND_PRINT((ndo, "" [rsvd=0x%02x]"", bp[0] & 0xfc)); ++ bp += 1; ++ len -= 1; ++ if (len < 1) ++ goto trunc; ++ ND_TCHECK(bp[0]); ++ nentries = bp[0]; ++ bp += 1; ++ len -= 1; + s = ' '; + for (; nentries; nentries--) { ++ if (len < 6) ++ goto trunc; + ND_TCHECK2(bp[0], 6); + ND_PRINT((ndo, ""%c%s%s/%d"", s, bp[0] & 1 ? ""!"" : """", + ipaddr_string(ndo, &bp[2]), bp[1])); +@@ -421,16 +455,13 @@ void + pim_print(netdissect_options *ndo, + register const u_char *bp, register u_int len, const u_char *bp2) + { +- register const u_char *ep; + register const struct pim *pim = (const struct pim *)bp; + +- ep = (const u_char *)ndo->ndo_snapend; +- if (bp >= ep) +- return; + #ifdef notyet /* currently we see only version and type */ + ND_TCHECK(pim->pim_rsv); + #endif + ++ ND_TCHECK(pim->pim_typever); + switch (PIM_VER(pim->pim_typever)) { + case 2: + if (!ndo->ndo_vflag) { +@@ -454,6 +485,10 @@ pim_print(netdissect_options *ndo, + break; + } + return; ++ ++trunc: ++ ND_PRINT((ndo, ""[|pim]"")); ++ return; + } + + /* +@@ -496,8 +531,6 @@ pim_print(netdissect_options *ndo, + * + */ + +-static int pimv2_addr_len; +- + enum pimv2_addrtype { + pimv2_unicast, pimv2_group, pimv2_source + }; +@@ -524,23 +557,24 @@ enum pimv2_addrtype { + */ + static int + pimv2_addr_print(netdissect_options *ndo, +- const u_char *bp, enum pimv2_addrtype at, int silent) ++ const u_char *bp, u_int len, enum pimv2_addrtype at, ++ u_int addr_len, int silent) + { + int af; +- int len, hdrlen; ++ int hdrlen; + +- ND_TCHECK(bp[0]); +- +- if (pimv2_addr_len == 0) { ++ if (addr_len == 0) { ++ if (len < 2) ++ goto trunc; + ND_TCHECK(bp[1]); + switch (bp[0]) { + case 1: + af = AF_INET; +- len = sizeof(struct in_addr); ++ addr_len = (u_int)sizeof(struct in_addr); + break; + case 2: + af = AF_INET6; +- len = sizeof(struct in6_addr); ++ addr_len = (u_int)sizeof(struct in6_addr); + break; + default: + return -1; +@@ -549,7 +583,7 @@ pimv2_addr_print(netdissect_options *ndo, + return -1; + hdrlen = 2; + } else { +- switch (pimv2_addr_len) { ++ switch (addr_len) { + case sizeof(struct in_addr): + af = AF_INET; + break; +@@ -560,14 +594,16 @@ pimv2_addr_print(netdissect_options *ndo, + return -1; + break; + } +- len = pimv2_addr_len; + hdrlen = 0; + } + + bp += hdrlen; ++ len -= hdrlen; + switch (at) { + case pimv2_unicast: +- ND_TCHECK2(bp[0], len); ++ if (len < addr_len) ++ goto trunc; ++ ND_TCHECK2(bp[0], addr_len); + if (af == AF_INET) { + if (!silent) + ND_PRINT((ndo, ""%s"", ipaddr_string(ndo, bp))); +@@ -576,10 +612,12 @@ pimv2_addr_print(netdissect_options *ndo, + if (!silent) + ND_PRINT((ndo, ""%s"", ip6addr_string(ndo, bp))); + } +- return hdrlen + len; ++ return hdrlen + addr_len; + case pimv2_group: + case pimv2_source: +- ND_TCHECK2(bp[0], len + 2); ++ if (len < addr_len + 2) ++ goto trunc; ++ ND_TCHECK2(bp[0], addr_len + 2); + if (af == AF_INET) { + if (!silent) { + ND_PRINT((ndo, ""%s"", ipaddr_string(ndo, bp + 2))); +@@ -608,7 +646,7 @@ pimv2_addr_print(netdissect_options *ndo, + ND_PRINT((ndo, "")"")); + } + } +- return hdrlen + 2 + len; ++ return hdrlen + 2 + addr_len; + default: + return -1; + } +@@ -660,17 +698,23 @@ pimv2_print(netdissect_options *ndo, + register const struct pim *pim = (const struct pim *)bp; + int advance; + enum checksum_status cksum_status; ++ int pimv2_addr_len; + + ep = (const u_char *)ndo->ndo_snapend; + if (bp >= ep) + return; + if (ep > bp + len) + ep = bp + len; ++ if (len < 2) ++ goto trunc; + ND_TCHECK(pim->pim_rsv); + pimv2_addr_len = pim->pim_rsv; + if (pimv2_addr_len != 0) + ND_PRINT((ndo, "", RFC2117-encoding"")); + ++ if (len < 4) ++ goto trunc; ++ ND_TCHECK(pim->pim_cksum); + ND_PRINT((ndo, "", cksum 0x%04x "", EXTRACT_16BITS(&pim->pim_cksum))); + if (EXTRACT_16BITS(&pim->pim_cksum) == 0) { + ND_PRINT((ndo, ""(unverified)"")); +@@ -711,23 +755,29 @@ pimv2_print(netdissect_options *ndo, + break; + } + } ++ bp += 4; ++ len -= 4; + + switch (PIM_TYPE(pim->pim_typever)) { + case PIMV2_TYPE_HELLO: + { + uint16_t otype, olen; +- bp += 4; +- while (bp < ep) { ++ while (len > 0) { ++ if (len < 4) ++ goto trunc; + ND_TCHECK2(bp[0], 4); + otype = EXTRACT_16BITS(&bp[0]); + olen = EXTRACT_16BITS(&bp[2]); +- ND_TCHECK2(bp[0], 4 + olen); + ND_PRINT((ndo, ""\n\t %s Option (%u), length %u, Value: "", + tok2str(pimv2_hello_option_values, ""Unknown"", otype), + otype, + olen)); + bp += 4; ++ len -= 4; + ++ if (len < olen) ++ goto trunc; ++ ND_TCHECK2(bp[0], olen); + switch (otype) { + case PIMV2_HELLO_OPTION_HOLDTIME: + if (olen != 2) { +@@ -797,14 +847,14 @@ pimv2_print(netdissect_options *ndo, + case PIMV2_HELLO_OPTION_ADDRESS_LIST: + if (ndo->ndo_vflag > 1) { + const u_char *ptr = bp; ++ u_int plen = len; + while (ptr < (bp+olen)) { + ND_PRINT((ndo, ""\n\t "")); +- advance = pimv2_addr_print(ndo, ptr, pimv2_unicast, 0); +- if (advance < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ advance = pimv2_addr_print(ndo, ptr, plen, pimv2_unicast, pimv2_addr_len, 0); ++ if (advance < 0) ++ goto trunc; + ptr += advance; ++ plen -= advance; + } + } + break; +@@ -817,6 +867,7 @@ pimv2_print(netdissect_options *ndo, + if (ndo->ndo_vflag> 1) + print_unknown_data(ndo, bp, ""\n\t "", olen); + bp += olen; ++ len -= olen; + } + break; + } +@@ -825,18 +876,24 @@ pimv2_print(netdissect_options *ndo, + { + const struct ip *ip; + +- ND_TCHECK2(*(bp + 4), PIMV2_REGISTER_FLAG_LEN); ++ if (len < 4) ++ goto trunc; ++ ND_TCHECK2(*bp, PIMV2_REGISTER_FLAG_LEN); + + ND_PRINT((ndo, "", Flags [ %s ]\n\t"", + tok2str(pimv2_register_flag_values, + ""none"", +- EXTRACT_32BITS(bp+4)))); ++ EXTRACT_32BITS(bp)))); + +- bp += 8; len -= 8; ++ bp += 4; len -= 4; + /* encapsulated multicast packet */ ++ if (len == 0) ++ goto trunc; + ip = (const struct ip *)bp; ++ ND_TCHECK(ip->ip_vhl); + switch (IP_V(ip)) { + case 0: /* Null header */ ++ ND_TCHECK(ip->ip_dst); + ND_PRINT((ndo, ""IP-Null-header %s > %s"", + ipaddr_string(ndo, &ip->ip_src), + ipaddr_string(ndo, &ip->ip_dst))); +@@ -858,22 +915,13 @@ pimv2_print(netdissect_options *ndo, + } + + case PIMV2_TYPE_REGISTER_STOP: +- bp += 4; len -= 4; +- if (bp >= ep) +- break; + ND_PRINT((ndo, "" group="")); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_group, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; len -= advance; +- if (bp >= ep) +- break; + ND_PRINT((ndo, "" source="")); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_unicast, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; len -= advance; + break; + +@@ -924,19 +972,15 @@ pimv2_print(netdissect_options *ndo, + uint16_t nprune; + int i, j; + +- bp += 4; len -= 4; + if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/ +- if (bp >= ep) +- break; + ND_PRINT((ndo, "", upstream-neighbor: "")); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_unicast, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; len -= advance; + } +- if (bp + 4 > ep) +- break; ++ if (len < 4) ++ goto trunc; ++ ND_TCHECK2(*bp, 4); + ngroup = bp[1]; + holdtime = EXTRACT_16BITS(&bp[2]); + ND_PRINT((ndo, ""\n\t %u group(s)"", ngroup)); +@@ -949,139 +993,125 @@ pimv2_print(netdissect_options *ndo, + } + bp += 4; len -= 4; + for (i = 0; i < ngroup; i++) { +- if (bp >= ep) +- goto jp_done; + ND_PRINT((ndo, ""\n\t group #%u: "", i+1)); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { +- ND_PRINT((ndo, ""...)"")); +- goto jp_done; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_group, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; len -= advance; +- if (bp + 4 > ep) { +- ND_PRINT((ndo, ""...)"")); +- goto jp_done; +- } ++ if (len < 4) ++ goto trunc; ++ ND_TCHECK2(*bp, 4); + njoin = EXTRACT_16BITS(&bp[0]); + nprune = EXTRACT_16BITS(&bp[2]); + ND_PRINT((ndo, "", joined sources: %u, pruned sources: %u"", njoin, nprune)); + bp += 4; len -= 4; + for (j = 0; j < njoin; j++) { + ND_PRINT((ndo, ""\n\t joined source #%u: "", j+1)); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) { +- ND_PRINT((ndo, ""...)"")); +- goto jp_done; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_source, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; len -= advance; + } + for (j = 0; j < nprune; j++) { + ND_PRINT((ndo, ""\n\t pruned source #%u: "", j+1)); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) { +- ND_PRINT((ndo, ""...)"")); +- goto jp_done; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_source, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; len -= advance; + } + } +- jp_done: + break; + } + + case PIMV2_TYPE_BOOTSTRAP: + { + int i, j, frpcnt; +- bp += 4; + + /* Fragment Tag, Hash Mask len, and BSR-priority */ +- if (bp + sizeof(uint16_t) >= ep) break; ++ if (len < 2) ++ goto trunc; ++ ND_TCHECK_16BITS(bp); + ND_PRINT((ndo, "" tag=%x"", EXTRACT_16BITS(bp))); +- bp += sizeof(uint16_t); +- if (bp >= ep) break; ++ bp += 2; ++ len -= 2; ++ if (len < 1) ++ goto trunc; ++ ND_TCHECK(bp[0]); + ND_PRINT((ndo, "" hashmlen=%d"", bp[0])); +- if (bp + 1 >= ep) break; ++ if (len < 2) ++ goto trunc; ++ ND_TCHECK(bp[2]); + ND_PRINT((ndo, "" BSRprio=%d"", bp[1])); + bp += 2; ++ len -= 2; + + /* Encoded-Unicast-BSR-Address */ +- if (bp >= ep) break; + ND_PRINT((ndo, "" BSR="")); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_unicast, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; ++ len -= advance; + + for (i = 0; bp < ep; i++) { + /* Encoded-Group Address */ + ND_PRINT((ndo, "" (group%d: "", i)); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) +- < 0) { +- ND_PRINT((ndo, ""...)"")); +- goto bs_done; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_group, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; ++ len -= advance; + + /* RP-Count, Frag RP-Cnt, and rsvd */ +- if (bp >= ep) { +- ND_PRINT((ndo, ""...)"")); +- goto bs_done; +- } ++ if (len < 1) ++ goto trunc; ++ ND_TCHECK(bp[0]); + ND_PRINT((ndo, "" RPcnt=%d"", bp[0])); +- if (bp + 1 >= ep) { +- ND_PRINT((ndo, ""...)"")); +- goto bs_done; +- } ++ if (len < 2) ++ goto trunc; ++ ND_TCHECK(bp[1]); + ND_PRINT((ndo, "" FRPcnt=%d"", frpcnt = bp[1])); ++ if (len < 4) ++ goto trunc; + bp += 4; ++ len -= 4; + + for (j = 0; j < frpcnt && bp < ep; j++) { + /* each RP info */ + ND_PRINT((ndo, "" RP%d="", j)); +- if ((advance = pimv2_addr_print(ndo, bp, ++ if ((advance = pimv2_addr_print(ndo, bp, len, + pimv2_unicast, +- 0)) < 0) { +- ND_PRINT((ndo, ""...)"")); +- goto bs_done; +- } ++ pimv2_addr_len, ++ 0)) < 0) ++ goto trunc; + bp += advance; ++ len -= advance; + +- if (bp + 1 >= ep) { +- ND_PRINT((ndo, ""...)"")); +- goto bs_done; +- } ++ if (len < 2) ++ goto trunc; ++ ND_TCHECK_16BITS(bp); + ND_PRINT((ndo, "",holdtime="")); + unsigned_relts_print(ndo, EXTRACT_16BITS(bp)); +- if (bp + 2 >= ep) { +- ND_PRINT((ndo, ""...)"")); +- goto bs_done; +- } ++ if (len < 3) ++ goto trunc; ++ ND_TCHECK(bp[2]); + ND_PRINT((ndo, "",prio=%d"", bp[2])); ++ if (len < 4) ++ goto trunc; + bp += 4; ++ len -= 4; + } + ND_PRINT((ndo, "")"")); + } +- bs_done: + break; + } + case PIMV2_TYPE_ASSERT: +- bp += 4; len -= 4; +- if (bp >= ep) +- break; + ND_PRINT((ndo, "" group="")); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_group, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; len -= advance; +- if (bp >= ep) +- break; + ND_PRINT((ndo, "" src="")); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_unicast, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; len -= advance; +- if (bp + 8 > ep) +- break; ++ if (len < 8) ++ goto trunc; ++ ND_TCHECK2(*bp, 8); + if (bp[0] & 0x80) + ND_PRINT((ndo, "" RPT"")); + ND_PRINT((ndo, "" pref=%u"", EXTRACT_32BITS(&bp[0]) & 0x7fffffff)); +@@ -1091,61 +1121,62 @@ pimv2_print(netdissect_options *ndo, + case PIMV2_TYPE_CANDIDATE_RP: + { + int i, pfxcnt; +- bp += 4; + + /* Prefix-Cnt, Priority, and Holdtime */ +- if (bp >= ep) break; ++ if (len < 1) ++ goto trunc; ++ ND_TCHECK(bp[0]); + ND_PRINT((ndo, "" prefix-cnt=%d"", bp[0])); + pfxcnt = bp[0]; +- if (bp + 1 >= ep) break; ++ if (len < 2) ++ goto trunc; ++ ND_TCHECK(bp[1]); + ND_PRINT((ndo, "" prio=%d"", bp[1])); +- if (bp + 3 >= ep) break; ++ if (len < 4) ++ goto trunc; ++ ND_TCHECK_16BITS(&bp[2]); + ND_PRINT((ndo, "" holdtime="")); + unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2])); + bp += 4; ++ len -= 4; + + /* Encoded-Unicast-RP-Address */ +- if (bp >= ep) break; + ND_PRINT((ndo, "" RP="")); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_unicast, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; ++ len -= advance; + + /* Encoded-Group Addresses */ + for (i = 0; i < pfxcnt && bp < ep; i++) { + ND_PRINT((ndo, "" Group%d="", i)); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) +- < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_group, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; ++ len -= advance; + } + break; + } + + case PIMV2_TYPE_PRUNE_REFRESH: + ND_PRINT((ndo, "" src="")); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_unicast, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; ++ len -= advance; + ND_PRINT((ndo, "" grp="")); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_group, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; ++ len -= advance; + ND_PRINT((ndo, "" forwarder="")); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_unicast, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; +- ND_TCHECK2(bp[0], 2); ++ len -= advance; ++ if (len < 2) ++ goto trunc; ++ ND_TCHECK_16BITS(bp); + ND_PRINT((ndo, "" TUNR "")); + unsigned_relts_print(ndo, EXTRACT_16BITS(bp)); + break;",1013,1344,2048 +14619,"bool WebGLRenderingContextBase::ValidateTexFuncData( + const char* function_name, + TexImageDimension tex_dimension, + GLint level, + GLsizei width, + GLsizei height, + GLsizei depth, + GLenum format, + GLenum type, + DOMArrayBufferView* pixels, + NullDisposition disposition, + GLuint src_offset) { + if (!pixels) { + DCHECK_NE(disposition, kNullNotReachable); + if (disposition == kNullAllowed) + return true; + SynthesizeGLError(GL_INVALID_VALUE, function_name, ""no pixels""); + return false; + } + + if (!ValidateSettableTexFormat(function_name, format)) + return false; + + switch (type) { + case GL_BYTE: + if (pixels->GetType() != DOMArrayBufferView::kTypeInt8) { + SynthesizeGLError(GL_INVALID_OPERATION, function_name, + ""type BYTE but ArrayBufferView not Int8Array""); + return false; + } + break; + case GL_UNSIGNED_BYTE: + if (pixels->GetType() != DOMArrayBufferView::kTypeUint8) { + SynthesizeGLError( + GL_INVALID_OPERATION, function_name, + ""type UNSIGNED_BYTE but ArrayBufferView not Uint8Array""); + return false; + } + break; + case GL_SHORT: + if (pixels->GetType() != DOMArrayBufferView::kTypeInt16) { + SynthesizeGLError(GL_INVALID_OPERATION, function_name, + ""type SHORT but ArrayBufferView not Int16Array""); + return false; + } + break; + case GL_UNSIGNED_SHORT: + case GL_UNSIGNED_SHORT_5_6_5: + case GL_UNSIGNED_SHORT_4_4_4_4: + case GL_UNSIGNED_SHORT_5_5_5_1: + if (pixels->GetType() != DOMArrayBufferView::kTypeUint16) { + SynthesizeGLError( + GL_INVALID_OPERATION, function_name, + ""type UNSIGNED_SHORT but ArrayBufferView not Uint16Array""); + return false; + } + break; + case GL_INT: + if (pixels->GetType() != DOMArrayBufferView::kTypeInt32) { + SynthesizeGLError(GL_INVALID_OPERATION, function_name, + ""type INT but ArrayBufferView not Int32Array""); + return false; + } + break; + case GL_UNSIGNED_INT: + case GL_UNSIGNED_INT_2_10_10_10_REV: + case GL_UNSIGNED_INT_10F_11F_11F_REV: + case GL_UNSIGNED_INT_5_9_9_9_REV: + case GL_UNSIGNED_INT_24_8: + if (pixels->GetType() != DOMArrayBufferView::kTypeUint32) { + SynthesizeGLError( + GL_INVALID_OPERATION, function_name, + ""type UNSIGNED_INT but ArrayBufferView not Uint32Array""); + return false; + } + break; + case GL_FLOAT: // OES_texture_float + if (pixels->GetType() != DOMArrayBufferView::kTypeFloat32) { + SynthesizeGLError(GL_INVALID_OPERATION, function_name, + ""type FLOAT but ArrayBufferView not Float32Array""); + return false; + } + break; + case GL_HALF_FLOAT: + case GL_HALF_FLOAT_OES: // OES_texture_half_float + if (pixels->GetType() != DOMArrayBufferView::kTypeUint16) { + SynthesizeGLError(GL_INVALID_OPERATION, function_name, + ""type HALF_FLOAT_OES but ArrayBufferView is not NULL "" + ""and not Uint16Array""); + return false; + } + break; + case GL_FLOAT_32_UNSIGNED_INT_24_8_REV: + SynthesizeGLError(GL_INVALID_OPERATION, function_name, + ""type FLOAT_32_UNSIGNED_INT_24_8_REV but "" + ""ArrayBufferView is not NULL""); + return false; + default: + NOTREACHED(); + } + + unsigned total_bytes_required, skip_bytes; + GLenum error = WebGLImageConversion::ComputeImageSizeInBytes( + format, type, width, height, depth, + GetUnpackPixelStoreParams(tex_dimension), &total_bytes_required, 0, + &skip_bytes); + if (error != GL_NO_ERROR) { + SynthesizeGLError(error, function_name, ""invalid texture dimensions""); + return false; + } + CheckedNumeric total = src_offset; + total *= pixels->TypeSize(); + total += total_bytes_required; + total += skip_bytes; + if (!total.IsValid() || pixels->byteLength() < total.ValueOrDie()) { + SynthesizeGLError(GL_INVALID_OPERATION, function_name, + ""ArrayBufferView not big enough for request""); + return false; + } + return true; +} +",0,"bool WebGLRenderingContextBase::ValidateTexFuncData( + const char* function_name, + TexImageDimension tex_dimension, + GLint level, + GLsizei width, + GLsizei height, + GLsizei depth, + GLenum format, + GLenum type, + DOMArrayBufferView* pixels, + NullDisposition disposition, + GLuint src_offset) { + if (!pixels) { + DCHECK_NE(disposition, kNullNotReachable); + if (disposition == kNullAllowed) + return true; + SynthesizeGLError(GL_INVALID_VALUE, function_name, ""no pixels""); + return false; + } + + if (!ValidateSettableTexFormat(function_name, format)) + return false; + + switch (type) { + case GL_BYTE: + if (pixels->GetType() != DOMArrayBufferView::kTypeInt8) { + SynthesizeGLError(GL_INVALID_OPERATION, function_name, + ""type BYTE but ArrayBufferView not Int8Array""); + return false; + } + break; + case GL_UNSIGNED_BYTE: + if (pixels->GetType() != DOMArrayBufferView::kTypeUint8) { + SynthesizeGLError( + GL_INVALID_OPERATION, function_name, + ""type UNSIGNED_BYTE but ArrayBufferView not Uint8Array""); + return false; + } + break; + case GL_SHORT: + if (pixels->GetType() != DOMArrayBufferView::kTypeInt16) { + SynthesizeGLError(GL_INVALID_OPERATION, function_name, + ""type SHORT but ArrayBufferView not Int16Array""); + return false; + } + break; + case GL_UNSIGNED_SHORT: + case GL_UNSIGNED_SHORT_5_6_5: + case GL_UNSIGNED_SHORT_4_4_4_4: + case GL_UNSIGNED_SHORT_5_5_5_1: + if (pixels->GetType() != DOMArrayBufferView::kTypeUint16) { + SynthesizeGLError( + GL_INVALID_OPERATION, function_name, + ""type UNSIGNED_SHORT but ArrayBufferView not Uint16Array""); + return false; + } + break; + case GL_INT: + if (pixels->GetType() != DOMArrayBufferView::kTypeInt32) { + SynthesizeGLError(GL_INVALID_OPERATION, function_name, + ""type INT but ArrayBufferView not Int32Array""); + return false; + } + break; + case GL_UNSIGNED_INT: + case GL_UNSIGNED_INT_2_10_10_10_REV: + case GL_UNSIGNED_INT_10F_11F_11F_REV: + case GL_UNSIGNED_INT_5_9_9_9_REV: + case GL_UNSIGNED_INT_24_8: + if (pixels->GetType() != DOMArrayBufferView::kTypeUint32) { + SynthesizeGLError( + GL_INVALID_OPERATION, function_name, + ""type UNSIGNED_INT but ArrayBufferView not Uint32Array""); + return false; + } + break; + case GL_FLOAT: // OES_texture_float + if (pixels->GetType() != DOMArrayBufferView::kTypeFloat32) { + SynthesizeGLError(GL_INVALID_OPERATION, function_name, + ""type FLOAT but ArrayBufferView not Float32Array""); + return false; + } + break; + case GL_HALF_FLOAT: + case GL_HALF_FLOAT_OES: // OES_texture_half_float + if (pixels->GetType() != DOMArrayBufferView::kTypeUint16) { + SynthesizeGLError(GL_INVALID_OPERATION, function_name, + ""type HALF_FLOAT_OES but ArrayBufferView is not NULL "" + ""and not Uint16Array""); + return false; + } + break; + case GL_FLOAT_32_UNSIGNED_INT_24_8_REV: + SynthesizeGLError(GL_INVALID_OPERATION, function_name, + ""type FLOAT_32_UNSIGNED_INT_24_8_REV but "" + ""ArrayBufferView is not NULL""); + return false; + default: + NOTREACHED(); + } + + unsigned total_bytes_required, skip_bytes; + GLenum error = WebGLImageConversion::ComputeImageSizeInBytes( + format, type, width, height, depth, + GetUnpackPixelStoreParams(tex_dimension), &total_bytes_required, 0, + &skip_bytes); + if (error != GL_NO_ERROR) { + SynthesizeGLError(error, function_name, ""invalid texture dimensions""); + return false; + } + CheckedNumeric total = src_offset; + total *= pixels->TypeSize(); + total += total_bytes_required; + total += skip_bytes; + if (!total.IsValid() || pixels->byteLength() < total.ValueOrDie()) { + SynthesizeGLError(GL_INVALID_OPERATION, function_name, + ""ArrayBufferView not big enough for request""); + return false; + } + return true; +} +","@@ -6344,7 +6344,8 @@ void WebGLRenderingContextBase::DrawingBufferClientRestoreMaskAndClearValues() { + ContextGL()->ClearStencil(clear_stencil_); + } + +-void WebGLRenderingContextBase::DrawingBufferClientRestorePixelPackAlignment() { ++void WebGLRenderingContextBase:: ++ DrawingBufferClientRestorePixelPackParameters() { + if (!ContextGL()) + return; + ContextGL()->PixelStorei(GL_PACK_ALIGNMENT, pack_alignment_); +@@ -6372,6 +6373,8 @@ void WebGLRenderingContextBase::DrawingBufferClientRestoreFramebufferBinding() { + + void WebGLRenderingContextBase:: + DrawingBufferClientRestorePixelUnpackBufferBinding() {} ++void WebGLRenderingContextBase:: ++ DrawingBufferClientRestorePixelPackBufferBinding() {} + + ScriptValue WebGLRenderingContextBase::GetBooleanParameter( + ScriptState* script_state,",1005,1336,2048 +18307,"static int cx24116_send_diseqc_msg(struct dvb_frontend *fe, + struct dvb_diseqc_master_cmd *d) +{ + struct cx24116_state *state = fe->demodulator_priv; + int i, ret; + + /* Dump DiSEqC message */ + if (debug) { + printk(KERN_INFO ""cx24116: %s("", __func__); + for (i = 0 ; i < d->msg_len ;) { + printk(KERN_INFO ""0x%02x"", d->msg[i]); + if (++i < d->msg_len) + printk(KERN_INFO "", ""); + } + printk("") toneburst=%d\n"", toneburst); + } + + /* Validate length */ + if (d->msg_len > (CX24116_ARGLEN - CX24116_DISEQC_MSGOFS)) + return -EINVAL; + /* DiSEqC message */ + for (i = 0; i < d->msg_len; i++) + state->dsec_cmd.args[CX24116_DISEQC_MSGOFS + i] = d->msg[i]; + + /* DiSEqC message length */ + state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] = d->msg_len; + + /* Command length */ + state->dsec_cmd.len = CX24116_DISEQC_MSGOFS + + state->dsec_cmd.args[CX24116_DISEQC_MSGLEN]; + + /* DiSEqC toneburst */ + if (toneburst == CX24116_DISEQC_MESGCACHE) + /* Message is cached */ + return 0; + + else if (toneburst == CX24116_DISEQC_TONEOFF) + /* Message is sent without burst */ + state->dsec_cmd.args[CX24116_DISEQC_BURST] = 0; + + else if (toneburst == CX24116_DISEQC_TONECACHE) { + /* + * Message is sent with derived else cached burst + * + * WRITE PORT GROUP COMMAND 38 + * + * 0/A/A: E0 10 38 F0..F3 + * 1/B/B: E0 10 38 F4..F7 + * 2/C/A: E0 10 38 F8..FB + * 3/D/B: E0 10 38 FC..FF + * + * databyte[3]= 8421:8421 + * ABCD:WXYZ + * CLR :SET + * + * WX= PORT SELECT 0..3 (X=TONEBURST) + * Y = VOLTAGE (0=13V, 1=18V) + * Z = BAND (0=LOW, 1=HIGH(22K)) + */ + if (d->msg_len >= 4 && d->msg[2] == 0x38) + state->dsec_cmd.args[CX24116_DISEQC_BURST] = + ((d->msg[3] & 4) >> 2); + if (debug) + dprintk(""%s burst=%d\n"", __func__, + state->dsec_cmd.args[CX24116_DISEQC_BURST]); + } + + /* Wait for LNB ready */ + ret = cx24116_wait_for_lnb(fe); + if (ret != 0) + return ret; + + /* Wait for voltage/min repeat delay */ + msleep(100); + + /* Command */ + ret = cx24116_cmd_execute(fe, &state->dsec_cmd); + if (ret != 0) + return ret; + /* + * Wait for send + * + * Eutelsat spec: + * >15ms delay + (XXX determine if FW does this, see set_tone) + * 13.5ms per byte + + * >15ms delay + + * 12.5ms burst + + * >15ms delay (XXX determine if FW does this, see set_tone) + */ + msleep((state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] << 4) + + ((toneburst == CX24116_DISEQC_TONEOFF) ? 30 : 60)); + + return 0; +} +",1,"static int cx24116_send_diseqc_msg(struct dvb_frontend *fe, + struct dvb_diseqc_master_cmd *d) +{ + struct cx24116_state *state = fe->demodulator_priv; + int i, ret; + + /* Validate length */ + if (d->msg_len > sizeof(d->msg)) + return -EINVAL; + + /* Dump DiSEqC message */ + if (debug) { + printk(KERN_INFO ""cx24116: %s("", __func__); + for (i = 0 ; i < d->msg_len ;) { + printk(KERN_INFO ""0x%02x"", d->msg[i]); + if (++i < d->msg_len) + printk(KERN_INFO "", ""); + } + printk("") toneburst=%d\n"", toneburst); + } + + /* DiSEqC message */ + for (i = 0; i < d->msg_len; i++) + state->dsec_cmd.args[CX24116_DISEQC_MSGOFS + i] = d->msg[i]; + + /* DiSEqC message length */ + state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] = d->msg_len; + + /* Command length */ + state->dsec_cmd.len = CX24116_DISEQC_MSGOFS + + state->dsec_cmd.args[CX24116_DISEQC_MSGLEN]; + + /* DiSEqC toneburst */ + if (toneburst == CX24116_DISEQC_MESGCACHE) + /* Message is cached */ + return 0; + + else if (toneburst == CX24116_DISEQC_TONEOFF) + /* Message is sent without burst */ + state->dsec_cmd.args[CX24116_DISEQC_BURST] = 0; + + else if (toneburst == CX24116_DISEQC_TONECACHE) { + /* + * Message is sent with derived else cached burst + * + * WRITE PORT GROUP COMMAND 38 + * + * 0/A/A: E0 10 38 F0..F3 + * 1/B/B: E0 10 38 F4..F7 + * 2/C/A: E0 10 38 F8..FB + * 3/D/B: E0 10 38 FC..FF + * + * databyte[3]= 8421:8421 + * ABCD:WXYZ + * CLR :SET + * + * WX= PORT SELECT 0..3 (X=TONEBURST) + * Y = VOLTAGE (0=13V, 1=18V) + * Z = BAND (0=LOW, 1=HIGH(22K)) + */ + if (d->msg_len >= 4 && d->msg[2] == 0x38) + state->dsec_cmd.args[CX24116_DISEQC_BURST] = + ((d->msg[3] & 4) >> 2); + if (debug) + dprintk(""%s burst=%d\n"", __func__, + state->dsec_cmd.args[CX24116_DISEQC_BURST]); + } + + /* Wait for LNB ready */ + ret = cx24116_wait_for_lnb(fe); + if (ret != 0) + return ret; + + /* Wait for voltage/min repeat delay */ + msleep(100); + + /* Command */ + ret = cx24116_cmd_execute(fe, &state->dsec_cmd); + if (ret != 0) + return ret; + /* + * Wait for send + * + * Eutelsat spec: + * >15ms delay + (XXX determine if FW does this, see set_tone) + * 13.5ms per byte + + * >15ms delay + + * 12.5ms burst + + * >15ms delay (XXX determine if FW does this, see set_tone) + */ + msleep((state->dsec_cmd.args[CX24116_DISEQC_MSGLEN] << 4) + + ((toneburst == CX24116_DISEQC_TONEOFF) ? 30 : 60)); + + return 0; +} +","@@ -963,6 +963,10 @@ static int cx24116_send_diseqc_msg(struct dvb_frontend *fe, + struct cx24116_state *state = fe->demodulator_priv; + int i, ret; + ++ /* Validate length */ ++ if (d->msg_len > sizeof(d->msg)) ++ return -EINVAL; ++ + /* Dump DiSEqC message */ + if (debug) { + printk(KERN_INFO ""cx24116: %s("", __func__); +@@ -974,10 +978,6 @@ static int cx24116_send_diseqc_msg(struct dvb_frontend *fe, + printk("") toneburst=%d\n"", toneburst); + } + +- /* Validate length */ +- if (d->msg_len > (CX24116_ARGLEN - CX24116_DISEQC_MSGOFS)) +- return -EINVAL; +- + /* DiSEqC message */ + for (i = 0; i < d->msg_len; i++) + state->dsec_cmd.args[CX24116_DISEQC_MSGOFS + i] = d->msg[i];",1006,1337,2048 +1558,"__imlib_RenderGetPixel(Display * d, Drawable w, Visual * v, Colormap cm, + int depth, DATA8 r, DATA8 g, DATA8 b) +{ + Context *ct; + + ct = __imlib_GetContext(d, v, cm, depth); + + if (ct->palette) + { + switch (ct->palette_type) + { + case 0: /* 332 */ + return ct->palette[((r >> 0) & 0xe0) | + ((g >> 3) & 0x1b) | ((b >> 6) & 0x02)]; + break; + case 1: /* 232 */ + return ct->palette[((r >> 0) & 0xe0) | + ((g >> 3) & 0x1b) | ((b >> 6) & 0x02)]; + break; + case 2: /* 222 */ + return ct->palette[((r >> 0) & 0xe0) | + ((g >> 3) & 0x1b) | ((b >> 6) & 0x02)]; + break; + case 3: /* 221 */ + return ct->palette[((r >> 0) & 0xe0) | + ((g >> 3) & 0x1b) | ((b >> 6) & 0x02)]; + break; + case 4: /* 121 */ + return ct->palette[((r >> 0) & 0xe0) | + ((g >> 3) & 0x1b) | ((b >> 6) & 0x02)]; + break; + case 5: /* 111 */ + return ct->palette[((r >> 0) & 0xe0) | + ((g >> 3) & 0x1b) | ((b >> 6) & 0x02)]; + break; + case 6: /* 1 */ + return ct->palette[((r >> 0) & 0xe0) | + ((g >> 3) & 0x1b) | ((b >> 6) & 0x02)]; + break; + case 7: /* 666 */ + return ct->palette[((int)(((double)r / 255) * 5.0) * 36) + + ((int)(((double)g / 255) * 5.0) * 6) + + ((int)(((double)b / 255) * 5.0))]; + break; + default: + return 0; + } + } + else + { + unsigned int rm, gm, bm; + int i, rshift = 0, gshift = 0, bshift = 0; + DATA32 val; + + rm = v->red_mask; + gm = v->green_mask; + bm = v->blue_mask; + if ((rm == 0xf800) && (gm == 0x7e0) && (bm == 0x1f)) /* 565 */ + { + return (((r << 8) & 0xf800) | + ((g << 3) & 0x07e0) | ((b >> 3) & 0x001f)); + } + if ((rm == 0xff0000) && (gm == 0xff00) && (bm == 0xff)) /* 888 */ + { + return (((r << 16) & 0xff0000) | + ((g << 8) & 0x00ff00) | ((r) & 0x0000ff)); + } + if ((rm == 0x7c00) && (gm == 0x3e0) && (bm == 0x1f)) /* 555 */ + { + return (((r << 7) & 0x7c00) | + ((g << 2) & 0x03e0) | ((b >> 3) & 0x001f)); + } + for (i = 31; i >= 0; i--) + { + if (rm >= (1U << i)) + { + rshift = i - 7; + break; + } + } + for (i = 31; i >= 0; i--) + { + if (gm >= (1U << i)) + { + gshift = i - 7; + break; + } + } + for (i = 31; i >= 0; i--) + { + if (bm >= (1U << i)) + { + bshift = i - 7; + break; + } + } + if (rshift >= 0) + val = ((r << rshift) & rm); + else + val = ((r >> (-rshift)) & rm); + if (gshift >= 0) + val |= ((g << gshift) & gm); + else + val |= ((g >> (-gshift)) & gm); + if (bshift >= 0) + val |= ((b << bshift) & bm); + else + val |= ((b >> (-bshift)) & bm); + return val; + } + return 0; +} +",0,"__imlib_RenderGetPixel(Display * d, Drawable w, Visual * v, Colormap cm, + int depth, DATA8 r, DATA8 g, DATA8 b) +{ + Context *ct; + + ct = __imlib_GetContext(d, v, cm, depth); + + if (ct->palette) + { + switch (ct->palette_type) + { + case 0: /* 332 */ + return ct->palette[((r >> 0) & 0xe0) | + ((g >> 3) & 0x1b) | ((b >> 6) & 0x02)]; + break; + case 1: /* 232 */ + return ct->palette[((r >> 0) & 0xe0) | + ((g >> 3) & 0x1b) | ((b >> 6) & 0x02)]; + break; + case 2: /* 222 */ + return ct->palette[((r >> 0) & 0xe0) | + ((g >> 3) & 0x1b) | ((b >> 6) & 0x02)]; + break; + case 3: /* 221 */ + return ct->palette[((r >> 0) & 0xe0) | + ((g >> 3) & 0x1b) | ((b >> 6) & 0x02)]; + break; + case 4: /* 121 */ + return ct->palette[((r >> 0) & 0xe0) | + ((g >> 3) & 0x1b) | ((b >> 6) & 0x02)]; + break; + case 5: /* 111 */ + return ct->palette[((r >> 0) & 0xe0) | + ((g >> 3) & 0x1b) | ((b >> 6) & 0x02)]; + break; + case 6: /* 1 */ + return ct->palette[((r >> 0) & 0xe0) | + ((g >> 3) & 0x1b) | ((b >> 6) & 0x02)]; + break; + case 7: /* 666 */ + return ct->palette[((int)(((double)r / 255) * 5.0) * 36) + + ((int)(((double)g / 255) * 5.0) * 6) + + ((int)(((double)b / 255) * 5.0))]; + break; + default: + return 0; + } + } + else + { + unsigned int rm, gm, bm; + int i, rshift = 0, gshift = 0, bshift = 0; + DATA32 val; + + rm = v->red_mask; + gm = v->green_mask; + bm = v->blue_mask; + if ((rm == 0xf800) && (gm == 0x7e0) && (bm == 0x1f)) /* 565 */ + { + return (((r << 8) & 0xf800) | + ((g << 3) & 0x07e0) | ((b >> 3) & 0x001f)); + } + if ((rm == 0xff0000) && (gm == 0xff00) && (bm == 0xff)) /* 888 */ + { + return (((r << 16) & 0xff0000) | + ((g << 8) & 0x00ff00) | ((r) & 0x0000ff)); + } + if ((rm == 0x7c00) && (gm == 0x3e0) && (bm == 0x1f)) /* 555 */ + { + return (((r << 7) & 0x7c00) | + ((g << 2) & 0x03e0) | ((b >> 3) & 0x001f)); + } + for (i = 31; i >= 0; i--) + { + if (rm >= (1U << i)) + { + rshift = i - 7; + break; + } + } + for (i = 31; i >= 0; i--) + { + if (gm >= (1U << i)) + { + gshift = i - 7; + break; + } + } + for (i = 31; i >= 0; i--) + { + if (bm >= (1U << i)) + { + bshift = i - 7; + break; + } + } + if (rshift >= 0) + val = ((r << rshift) & rm); + else + val = ((r >> (-rshift)) & rm); + if (gshift >= 0) + val |= ((g << gshift) & gm); + else + val |= ((g >> (-gshift)) & gm); + if (bshift >= 0) + val |= ((b << bshift) & bm); + else + val |= ((b >> (-bshift)) & bm); + return val; + } + return 0; +} +","@@ -16,10 +16,6 @@ + #include ""scale.h"" + #include ""ximage.h"" + +-/* The maximum pixmap dimension is 65535. */ +-/* However, for now, use 46340 (46340^2 < 2^31) to avoid buffer overflow issues. */ +-#define X_MAX_DIM 46340 +- + /* size of the lines per segment we scale / render at a time */ + #define LINESIZE 16",1214,1545,2048 +4351,"static int xmit_skb(struct send_queue *sq, struct sk_buff *skb) +{ + struct virtio_net_hdr_mrg_rxbuf *hdr; + const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest; + struct virtnet_info *vi = sq->vq->vdev->priv; + unsigned num_sg; + unsigned hdr_len = vi->hdr_len; + bool can_push; + + pr_debug(""%s: xmit %p %pM\n"", vi->dev->name, skb, dest); + + can_push = vi->any_header_sg && + !((unsigned long)skb->data & (__alignof__(*hdr) - 1)) && + !skb_header_cloned(skb) && skb_headroom(skb) >= hdr_len; + /* Even if we can, don't push here yet as this would skew + * csum_start offset below. */ + if (can_push) + hdr = (struct virtio_net_hdr_mrg_rxbuf *)(skb->data - hdr_len); + else + hdr = skb_vnet_hdr(skb); + + if (skb->ip_summed == CHECKSUM_PARTIAL) { + hdr->hdr.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; + hdr->hdr.csum_start = cpu_to_virtio16(vi->vdev, + skb_checksum_start_offset(skb)); + hdr->hdr.csum_offset = cpu_to_virtio16(vi->vdev, + skb->csum_offset); + } else { + hdr->hdr.flags = 0; + hdr->hdr.csum_offset = hdr->hdr.csum_start = 0; + } + + if (skb_is_gso(skb)) { + hdr->hdr.hdr_len = cpu_to_virtio16(vi->vdev, skb_headlen(skb)); + hdr->hdr.gso_size = cpu_to_virtio16(vi->vdev, + skb_shinfo(skb)->gso_size); + if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) + hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV4; + else if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6) + hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV6; + else if (skb_shinfo(skb)->gso_type & SKB_GSO_UDP) + hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_UDP; + else + BUG(); + if (skb_shinfo(skb)->gso_type & SKB_GSO_TCP_ECN) + hdr->hdr.gso_type |= VIRTIO_NET_HDR_GSO_ECN; + } else { + hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE; + hdr->hdr.gso_size = hdr->hdr.hdr_len = 0; + } + + if (vi->mergeable_rx_bufs) + hdr->num_buffers = 0; + + sg_init_table(sq->sg, MAX_SKB_FRAGS + 2); + if (can_push) { + __skb_push(skb, hdr_len); + num_sg = skb_to_sgvec(skb, sq->sg, 0, skb->len); + /* Pull header back to avoid skew in tx bytes calculations. */ + __skb_pull(skb, hdr_len); + } else { + sg_set_buf(sq->sg, hdr, hdr_len); + num_sg = skb_to_sgvec(skb, sq->sg + 1, 0, skb->len) + 1; + } + return virtqueue_add_outbuf(sq->vq, sq->sg, num_sg, skb, GFP_ATOMIC); +} +",0,"static int xmit_skb(struct send_queue *sq, struct sk_buff *skb) +{ + struct virtio_net_hdr_mrg_rxbuf *hdr; + const unsigned char *dest = ((struct ethhdr *)skb->data)->h_dest; + struct virtnet_info *vi = sq->vq->vdev->priv; + unsigned num_sg; + unsigned hdr_len = vi->hdr_len; + bool can_push; + + pr_debug(""%s: xmit %p %pM\n"", vi->dev->name, skb, dest); + + can_push = vi->any_header_sg && + !((unsigned long)skb->data & (__alignof__(*hdr) - 1)) && + !skb_header_cloned(skb) && skb_headroom(skb) >= hdr_len; + /* Even if we can, don't push here yet as this would skew + * csum_start offset below. */ + if (can_push) + hdr = (struct virtio_net_hdr_mrg_rxbuf *)(skb->data - hdr_len); + else + hdr = skb_vnet_hdr(skb); + + if (skb->ip_summed == CHECKSUM_PARTIAL) { + hdr->hdr.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; + hdr->hdr.csum_start = cpu_to_virtio16(vi->vdev, + skb_checksum_start_offset(skb)); + hdr->hdr.csum_offset = cpu_to_virtio16(vi->vdev, + skb->csum_offset); + } else { + hdr->hdr.flags = 0; + hdr->hdr.csum_offset = hdr->hdr.csum_start = 0; + } + + if (skb_is_gso(skb)) { + hdr->hdr.hdr_len = cpu_to_virtio16(vi->vdev, skb_headlen(skb)); + hdr->hdr.gso_size = cpu_to_virtio16(vi->vdev, + skb_shinfo(skb)->gso_size); + if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV4) + hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV4; + else if (skb_shinfo(skb)->gso_type & SKB_GSO_TCPV6) + hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV6; + else if (skb_shinfo(skb)->gso_type & SKB_GSO_UDP) + hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_UDP; + else + BUG(); + if (skb_shinfo(skb)->gso_type & SKB_GSO_TCP_ECN) + hdr->hdr.gso_type |= VIRTIO_NET_HDR_GSO_ECN; + } else { + hdr->hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE; + hdr->hdr.gso_size = hdr->hdr.hdr_len = 0; + } + + if (vi->mergeable_rx_bufs) + hdr->num_buffers = 0; + + sg_init_table(sq->sg, MAX_SKB_FRAGS + 2); + if (can_push) { + __skb_push(skb, hdr_len); + num_sg = skb_to_sgvec(skb, sq->sg, 0, skb->len); + /* Pull header back to avoid skew in tx bytes calculations. */ + __skb_pull(skb, hdr_len); + } else { + sg_set_buf(sq->sg, hdr, hdr_len); + num_sg = skb_to_sgvec(skb, sq->sg + 1, 0, skb->len) + 1; + } + return virtqueue_add_outbuf(sq->vq, sq->sg, num_sg, skb, GFP_ATOMIC); +} +","@@ -1756,9 +1756,9 @@ static int virtnet_probe(struct virtio_device *vdev) + /* Do we support ""hardware"" checksums? */ + if (virtio_has_feature(vdev, VIRTIO_NET_F_CSUM)) { + /* This opens up the world of extra features. */ +- dev->hw_features |= NETIF_F_HW_CSUM|NETIF_F_SG|NETIF_F_FRAGLIST; ++ dev->hw_features |= NETIF_F_HW_CSUM | NETIF_F_SG; + if (csum) +- dev->features |= NETIF_F_HW_CSUM|NETIF_F_SG|NETIF_F_FRAGLIST; ++ dev->features |= NETIF_F_HW_CSUM | NETIF_F_SG; + + if (virtio_has_feature(vdev, VIRTIO_NET_F_GSO)) { + dev->hw_features |= NETIF_F_TSO | NETIF_F_UFO",796,1127,2048 +263,"make_row_from_rec_and_jsonb(Jsonb *element, PopulateRecordsetState *state) +{ + Datum *values; + bool *nulls; + int i; + RecordIOData *my_extra = state->my_extra; + int ncolumns = my_extra->ncolumns; + TupleDesc tupdesc = state->ret_tdesc; + HeapTupleHeader rec = state->rec; + HeapTuple rettuple; + + values = (Datum *) palloc(ncolumns * sizeof(Datum)); + nulls = (bool *) palloc(ncolumns * sizeof(bool)); + + if (state->rec) + { + HeapTupleData tuple; + + /* Build a temporary HeapTuple control structure */ + tuple.t_len = HeapTupleHeaderGetDatumLength(state->rec); + ItemPointerSetInvalid(&(tuple.t_self)); + tuple.t_tableOid = InvalidOid; + tuple.t_data = state->rec; + + /* Break down the tuple into fields */ + heap_deform_tuple(&tuple, tupdesc, values, nulls); + } + else + { + for (i = 0; i < ncolumns; ++i) + { + values[i] = (Datum) 0; + nulls[i] = true; + } + } + + for (i = 0; i < ncolumns; ++i) + { + ColumnIOData *column_info = &my_extra->columns[i]; + Oid column_type = tupdesc->attrs[i]->atttypid; + JsonbValue *v = NULL; + char *key; + + /* Ignore dropped columns in datatype */ + if (tupdesc->attrs[i]->attisdropped) + { + nulls[i] = true; + continue; + } + + key = NameStr(tupdesc->attrs[i]->attname); + + v = findJsonbValueFromContainerLen(&element->root, JB_FOBJECT, + key, strlen(key)); + + /* + * We can't just skip here if the key wasn't found since we might have + * a domain to deal with. If we were passed in a non-null record + * datum, we assume that the existing values are valid (if they're + * not, then it's not our fault), but if we were passed in a null, + * then every field which we don't populate needs to be run through + * the input function just in case it's a domain type. + */ + if (v == NULL && rec) + continue; + + /* + * Prepare to convert the column value from text + */ + if (column_info->column_type != column_type) + { + getTypeInputInfo(column_type, + &column_info->typiofunc, + &column_info->typioparam); + fmgr_info_cxt(column_info->typiofunc, &column_info->proc, + state->fn_mcxt); + column_info->column_type = column_type; + } + if (v == NULL || v->type == jbvNull) + { + /* + * Need InputFunctionCall to happen even for nulls, so that domain + * checks are done + */ + values[i] = InputFunctionCall(&column_info->proc, NULL, + column_info->typioparam, + tupdesc->attrs[i]->atttypmod); + nulls[i] = true; + } + else + { + char *s = NULL; + + if (v->type == jbvString) + s = pnstrdup(v->val.string.val, v->val.string.len); + else if (v->type == jbvBool) + s = pnstrdup((v->val.boolean) ? ""t"" : ""f"", 1); + else if (v->type == jbvNumeric) + s = DatumGetCString(DirectFunctionCall1(numeric_out, + PointerGetDatum(v->val.numeric))); + else if (v->type == jbvBinary) + s = JsonbToCString(NULL, (JsonbContainer *) v->val.binary.data, v->val.binary.len); + else + elog(ERROR, ""unrecognized jsonb type: %d"", (int) v->type); + + values[i] = InputFunctionCall(&column_info->proc, s, + column_info->typioparam, + tupdesc->attrs[i]->atttypmod); + nulls[i] = false; + } + } + + rettuple = heap_form_tuple(tupdesc, values, nulls); + + tuplestore_puttuple(state->tuple_store, rettuple); +} +",0,"make_row_from_rec_and_jsonb(Jsonb *element, PopulateRecordsetState *state) +{ + Datum *values; + bool *nulls; + int i; + RecordIOData *my_extra = state->my_extra; + int ncolumns = my_extra->ncolumns; + TupleDesc tupdesc = state->ret_tdesc; + HeapTupleHeader rec = state->rec; + HeapTuple rettuple; + + values = (Datum *) palloc(ncolumns * sizeof(Datum)); + nulls = (bool *) palloc(ncolumns * sizeof(bool)); + + if (state->rec) + { + HeapTupleData tuple; + + /* Build a temporary HeapTuple control structure */ + tuple.t_len = HeapTupleHeaderGetDatumLength(state->rec); + ItemPointerSetInvalid(&(tuple.t_self)); + tuple.t_tableOid = InvalidOid; + tuple.t_data = state->rec; + + /* Break down the tuple into fields */ + heap_deform_tuple(&tuple, tupdesc, values, nulls); + } + else + { + for (i = 0; i < ncolumns; ++i) + { + values[i] = (Datum) 0; + nulls[i] = true; + } + } + + for (i = 0; i < ncolumns; ++i) + { + ColumnIOData *column_info = &my_extra->columns[i]; + Oid column_type = tupdesc->attrs[i]->atttypid; + JsonbValue *v = NULL; + char *key; + + /* Ignore dropped columns in datatype */ + if (tupdesc->attrs[i]->attisdropped) + { + nulls[i] = true; + continue; + } + + key = NameStr(tupdesc->attrs[i]->attname); + + v = findJsonbValueFromContainerLen(&element->root, JB_FOBJECT, + key, strlen(key)); + + /* + * We can't just skip here if the key wasn't found since we might have + * a domain to deal with. If we were passed in a non-null record + * datum, we assume that the existing values are valid (if they're + * not, then it's not our fault), but if we were passed in a null, + * then every field which we don't populate needs to be run through + * the input function just in case it's a domain type. + */ + if (v == NULL && rec) + continue; + + /* + * Prepare to convert the column value from text + */ + if (column_info->column_type != column_type) + { + getTypeInputInfo(column_type, + &column_info->typiofunc, + &column_info->typioparam); + fmgr_info_cxt(column_info->typiofunc, &column_info->proc, + state->fn_mcxt); + column_info->column_type = column_type; + } + if (v == NULL || v->type == jbvNull) + { + /* + * Need InputFunctionCall to happen even for nulls, so that domain + * checks are done + */ + values[i] = InputFunctionCall(&column_info->proc, NULL, + column_info->typioparam, + tupdesc->attrs[i]->atttypmod); + nulls[i] = true; + } + else + { + char *s = NULL; + + if (v->type == jbvString) + s = pnstrdup(v->val.string.val, v->val.string.len); + else if (v->type == jbvBool) + s = pnstrdup((v->val.boolean) ? ""t"" : ""f"", 1); + else if (v->type == jbvNumeric) + s = DatumGetCString(DirectFunctionCall1(numeric_out, + PointerGetDatum(v->val.numeric))); + else if (v->type == jbvBinary) + s = JsonbToCString(NULL, (JsonbContainer *) v->val.binary.data, v->val.binary.len); + else + elog(ERROR, ""unrecognized jsonb type: %d"", (int) v->type); + + values[i] = InputFunctionCall(&column_info->proc, s, + column_info->typioparam, + tupdesc->attrs[i]->atttypmod); + nulls[i] = false; + } + } + + rettuple = heap_form_tuple(tupdesc, values, nulls); + + tuplestore_puttuple(state->tuple_store, rettuple); +} +","@@ -3724,6 +3724,8 @@ setPath(JsonbIterator **it, Datum *path_elems, + JsonbValue *res = NULL; + int r; + ++ check_stack_depth(); ++ + if (path_nulls[level]) + elog(ERROR, ""path element at the position %d is NULL"", level + 1);",987,1318,2048 +18308,"bool radeon_atom_get_tv_timings(struct radeon_device *rdev, int index, + struct drm_display_mode *mode) +{ + struct radeon_mode_info *mode_info = &rdev->mode_info; + ATOM_ANALOG_TV_INFO *tv_info; + ATOM_ANALOG_TV_INFO_V1_2 *tv_info_v1_2; + ATOM_DTD_FORMAT *dtd_timings; + int data_index = GetIndexIntoMasterTable(DATA, AnalogTV_Info); + u8 frev, crev; + u16 data_offset, misc; + + if (!atom_parse_data_header(mode_info->atom_context, data_index, NULL, + &frev, &crev, &data_offset)) + return false; + + switch (crev) { + case 1: + tv_info = (ATOM_ANALOG_TV_INFO *)(mode_info->atom_context->bios + data_offset); + if (index > MAX_SUPPORTED_TV_TIMING) + return false; + + mode->crtc_htotal = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_Total); + mode->crtc_hdisplay = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_Disp); + mode->crtc_hsync_start = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncStart); + mode->crtc_hsync_end = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncStart) + + le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncWidth); + + mode->crtc_vtotal = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_Total); + mode->crtc_vdisplay = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_Disp); + mode->crtc_vsync_start = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncStart); + mode->crtc_vsync_end = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncStart) + + le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncWidth); + + mode->flags = 0; + misc = le16_to_cpu(tv_info->aModeTimings[index].susModeMiscInfo.usAccess); + if (misc & ATOM_VSYNC_POLARITY) + mode->flags |= DRM_MODE_FLAG_NVSYNC; + if (misc & ATOM_HSYNC_POLARITY) + mode->flags |= DRM_MODE_FLAG_NHSYNC; + if (misc & ATOM_COMPOSITESYNC) + mode->flags |= DRM_MODE_FLAG_CSYNC; + if (misc & ATOM_INTERLACE) + mode->flags |= DRM_MODE_FLAG_INTERLACE; + if (misc & ATOM_DOUBLE_CLOCK_MODE) + mode->flags |= DRM_MODE_FLAG_DBLSCAN; + + mode->clock = le16_to_cpu(tv_info->aModeTimings[index].usPixelClock) * 10; + + if (index == 1) { + /* PAL timings appear to have wrong values for totals */ + mode->crtc_htotal -= 1; + mode->crtc_vtotal -= 1; + } + break; + case 2: + tv_info_v1_2 = (ATOM_ANALOG_TV_INFO_V1_2 *)(mode_info->atom_context->bios + data_offset); + if (index > MAX_SUPPORTED_TV_TIMING_V1_2) + return false; + + dtd_timings = &tv_info_v1_2->aModeTimings[index]; + mode->crtc_htotal = le16_to_cpu(dtd_timings->usHActive) + + le16_to_cpu(dtd_timings->usHBlanking_Time); + mode->crtc_hdisplay = le16_to_cpu(dtd_timings->usHActive); + mode->crtc_hsync_start = le16_to_cpu(dtd_timings->usHActive) + + le16_to_cpu(dtd_timings->usHSyncOffset); + mode->crtc_hsync_end = mode->crtc_hsync_start + + le16_to_cpu(dtd_timings->usHSyncWidth); + + mode->crtc_vtotal = le16_to_cpu(dtd_timings->usVActive) + + le16_to_cpu(dtd_timings->usVBlanking_Time); + mode->crtc_vdisplay = le16_to_cpu(dtd_timings->usVActive); + mode->crtc_vsync_start = le16_to_cpu(dtd_timings->usVActive) + + le16_to_cpu(dtd_timings->usVSyncOffset); + mode->crtc_vsync_end = mode->crtc_vsync_start + + le16_to_cpu(dtd_timings->usVSyncWidth); + + mode->flags = 0; + misc = le16_to_cpu(dtd_timings->susModeMiscInfo.usAccess); + if (misc & ATOM_VSYNC_POLARITY) + mode->flags |= DRM_MODE_FLAG_NVSYNC; + if (misc & ATOM_HSYNC_POLARITY) + mode->flags |= DRM_MODE_FLAG_NHSYNC; + if (misc & ATOM_COMPOSITESYNC) + mode->flags |= DRM_MODE_FLAG_CSYNC; + if (misc & ATOM_INTERLACE) + mode->flags |= DRM_MODE_FLAG_INTERLACE; + if (misc & ATOM_DOUBLE_CLOCK_MODE) + mode->flags |= DRM_MODE_FLAG_DBLSCAN; + + mode->clock = le16_to_cpu(dtd_timings->usPixClk) * 10; + break; + } + return true; +} +",1,"bool radeon_atom_get_tv_timings(struct radeon_device *rdev, int index, + struct drm_display_mode *mode) +{ + struct radeon_mode_info *mode_info = &rdev->mode_info; + ATOM_ANALOG_TV_INFO *tv_info; + ATOM_ANALOG_TV_INFO_V1_2 *tv_info_v1_2; + ATOM_DTD_FORMAT *dtd_timings; + int data_index = GetIndexIntoMasterTable(DATA, AnalogTV_Info); + u8 frev, crev; + u16 data_offset, misc; + + if (!atom_parse_data_header(mode_info->atom_context, data_index, NULL, + &frev, &crev, &data_offset)) + return false; + + switch (crev) { + case 1: + tv_info = (ATOM_ANALOG_TV_INFO *)(mode_info->atom_context->bios + data_offset); + if (index >= MAX_SUPPORTED_TV_TIMING) + return false; + + mode->crtc_htotal = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_Total); + mode->crtc_hdisplay = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_Disp); + mode->crtc_hsync_start = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncStart); + mode->crtc_hsync_end = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncStart) + + le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_SyncWidth); + + mode->crtc_vtotal = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_Total); + mode->crtc_vdisplay = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_Disp); + mode->crtc_vsync_start = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncStart); + mode->crtc_vsync_end = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncStart) + + le16_to_cpu(tv_info->aModeTimings[index].usCRTC_V_SyncWidth); + + mode->flags = 0; + misc = le16_to_cpu(tv_info->aModeTimings[index].susModeMiscInfo.usAccess); + if (misc & ATOM_VSYNC_POLARITY) + mode->flags |= DRM_MODE_FLAG_NVSYNC; + if (misc & ATOM_HSYNC_POLARITY) + mode->flags |= DRM_MODE_FLAG_NHSYNC; + if (misc & ATOM_COMPOSITESYNC) + mode->flags |= DRM_MODE_FLAG_CSYNC; + if (misc & ATOM_INTERLACE) + mode->flags |= DRM_MODE_FLAG_INTERLACE; + if (misc & ATOM_DOUBLE_CLOCK_MODE) + mode->flags |= DRM_MODE_FLAG_DBLSCAN; + + mode->clock = le16_to_cpu(tv_info->aModeTimings[index].usPixelClock) * 10; + + if (index == 1) { + /* PAL timings appear to have wrong values for totals */ + mode->crtc_htotal -= 1; + mode->crtc_vtotal -= 1; + } + break; + case 2: + tv_info_v1_2 = (ATOM_ANALOG_TV_INFO_V1_2 *)(mode_info->atom_context->bios + data_offset); + if (index >= MAX_SUPPORTED_TV_TIMING_V1_2) + return false; + + dtd_timings = &tv_info_v1_2->aModeTimings[index]; + mode->crtc_htotal = le16_to_cpu(dtd_timings->usHActive) + + le16_to_cpu(dtd_timings->usHBlanking_Time); + mode->crtc_hdisplay = le16_to_cpu(dtd_timings->usHActive); + mode->crtc_hsync_start = le16_to_cpu(dtd_timings->usHActive) + + le16_to_cpu(dtd_timings->usHSyncOffset); + mode->crtc_hsync_end = mode->crtc_hsync_start + + le16_to_cpu(dtd_timings->usHSyncWidth); + + mode->crtc_vtotal = le16_to_cpu(dtd_timings->usVActive) + + le16_to_cpu(dtd_timings->usVBlanking_Time); + mode->crtc_vdisplay = le16_to_cpu(dtd_timings->usVActive); + mode->crtc_vsync_start = le16_to_cpu(dtd_timings->usVActive) + + le16_to_cpu(dtd_timings->usVSyncOffset); + mode->crtc_vsync_end = mode->crtc_vsync_start + + le16_to_cpu(dtd_timings->usVSyncWidth); + + mode->flags = 0; + misc = le16_to_cpu(dtd_timings->susModeMiscInfo.usAccess); + if (misc & ATOM_VSYNC_POLARITY) + mode->flags |= DRM_MODE_FLAG_NVSYNC; + if (misc & ATOM_HSYNC_POLARITY) + mode->flags |= DRM_MODE_FLAG_NHSYNC; + if (misc & ATOM_COMPOSITESYNC) + mode->flags |= DRM_MODE_FLAG_CSYNC; + if (misc & ATOM_INTERLACE) + mode->flags |= DRM_MODE_FLAG_INTERLACE; + if (misc & ATOM_DOUBLE_CLOCK_MODE) + mode->flags |= DRM_MODE_FLAG_DBLSCAN; + + mode->clock = le16_to_cpu(dtd_timings->usPixClk) * 10; + break; + } + return true; +} +","@@ -1264,7 +1264,7 @@ bool radeon_atom_get_tv_timings(struct radeon_device *rdev, int index, + switch (crev) { + case 1: + tv_info = (ATOM_ANALOG_TV_INFO *)(mode_info->atom_context->bios + data_offset); +- if (index > MAX_SUPPORTED_TV_TIMING) ++ if (index >= MAX_SUPPORTED_TV_TIMING) + return false; + + mode->crtc_htotal = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_Total); +@@ -1302,7 +1302,7 @@ bool radeon_atom_get_tv_timings(struct radeon_device *rdev, int index, + break; + case 2: + tv_info_v1_2 = (ATOM_ANALOG_TV_INFO_V1_2 *)(mode_info->atom_context->bios + data_offset); +- if (index > MAX_SUPPORTED_TV_TIMING_V1_2) ++ if (index >= MAX_SUPPORTED_TV_TIMING_V1_2) + return false; + + dtd_timings = &tv_info_v1_2->aModeTimings[index];",1248,1579,2048 +1604,"void ctdb_tcp_node_connect(struct event_context *ev, struct timed_event *te, + struct timeval t, void *private_data) +{ + struct ctdb_node *node = talloc_get_type(private_data, + struct ctdb_node); + struct ctdb_tcp_node *tnode = talloc_get_type(node->private_data, + struct ctdb_tcp_node); + struct ctdb_context *ctdb = node->ctdb; + ctdb_sock_addr sock_in; + int sockin_size; + int sockout_size; + ctdb_sock_addr sock_out; + + ctdb_tcp_stop_connection(node); + + ZERO_STRUCT(sock_out); +#ifdef HAVE_SOCK_SIN_LEN + sock_out.ip.sin_len = sizeof(sock_out); +#endif + if (ctdb_tcp_get_address(ctdb, node->address.address, &sock_out) != 0) { + return; + } + switch (sock_out.sa.sa_family) { + case AF_INET: + sock_out.ip.sin_port = htons(node->address.port); + break; + case AF_INET6: + sock_out.ip6.sin6_port = htons(node->address.port); + break; + default: + DEBUG(DEBUG_ERR, (__location__ "" unknown family %u\n"", + sock_out.sa.sa_family)); + return; + } + + tnode->fd = socket(sock_out.sa.sa_family, SOCK_STREAM, IPPROTO_TCP); + if (tnode->fd == -1) { + DEBUG(DEBUG_ERR, (__location__ ""Failed to create socket\n"")); + return; + } + set_nonblocking(tnode->fd); + set_close_on_exec(tnode->fd); + + DEBUG(DEBUG_DEBUG, (__location__ "" Created TCP SOCKET FD:%d\n"", tnode->fd)); + + /* Bind our side of the socketpair to the same address we use to listen + * on incoming CTDB traffic. + * We must specify this address to make sure that the address we expose to + * the remote side is actually routable in case CTDB traffic will run on + * a dedicated non-routeable network. + */ + ZERO_STRUCT(sock_in); + if (ctdb_tcp_get_address(ctdb, ctdb->address.address, &sock_in) != 0) { + DEBUG(DEBUG_ERR, (__location__ "" Failed to find our address. Failing bind.\n"")); + close(tnode->fd); + return; + } + + /* AIX libs check to see if the socket address and length + arguments are consistent with each other on calls like + connect(). Can not get by with just sizeof(sock_in), + need sizeof(sock_in.ip). + */ + switch (sock_in.sa.sa_family) { + case AF_INET: + sockin_size = sizeof(sock_in.ip); + sockout_size = sizeof(sock_out.ip); + break; + case AF_INET6: + sockin_size = sizeof(sock_in.ip6); + sockout_size = sizeof(sock_out.ip6); + break; + default: + DEBUG(DEBUG_ERR, (__location__ "" unknown family %u\n"", + sock_in.sa.sa_family)); + close(tnode->fd); + return; + } +#ifdef HAVE_SOCK_SIN_LEN + sock_in.ip.sin_len = sockin_size; + sock_out.ip.sin_len = sockout_size; +#endif + if (bind(tnode->fd, (struct sockaddr *)&sock_in, sockin_size) == -1) { + DEBUG(DEBUG_ERR, (__location__ ""Failed to bind socket %s(%d)\n"", + strerror(errno), errno)); + close(tnode->fd); + return; + } + + if (connect(tnode->fd, (struct sockaddr *)&sock_out, sockout_size) != 0 && + errno != EINPROGRESS) { + ctdb_tcp_stop_connection(node); + tnode->connect_te = event_add_timed(ctdb->ev, tnode, + timeval_current_ofs(1, 0), + ctdb_tcp_node_connect, node); + return; + } + + /* non-blocking connect - wait for write event */ + tnode->connect_fde = event_add_fd(node->ctdb->ev, tnode, tnode->fd, + EVENT_FD_WRITE|EVENT_FD_READ, + ctdb_node_connect_write, node); + + /* don't give it long to connect - retry in one second. This ensures + that we find a node is up quickly (tcp normally backs off a syn reply + delay by quite a lot) */ + tnode->connect_te = event_add_timed(ctdb->ev, tnode, timeval_current_ofs(1, 0), + ctdb_tcp_node_connect, node); +} +",0,"void ctdb_tcp_node_connect(struct event_context *ev, struct timed_event *te, + struct timeval t, void *private_data) +{ + struct ctdb_node *node = talloc_get_type(private_data, + struct ctdb_node); + struct ctdb_tcp_node *tnode = talloc_get_type(node->private_data, + struct ctdb_tcp_node); + struct ctdb_context *ctdb = node->ctdb; + ctdb_sock_addr sock_in; + int sockin_size; + int sockout_size; + ctdb_sock_addr sock_out; + + ctdb_tcp_stop_connection(node); + + ZERO_STRUCT(sock_out); +#ifdef HAVE_SOCK_SIN_LEN + sock_out.ip.sin_len = sizeof(sock_out); +#endif + if (ctdb_tcp_get_address(ctdb, node->address.address, &sock_out) != 0) { + return; + } + switch (sock_out.sa.sa_family) { + case AF_INET: + sock_out.ip.sin_port = htons(node->address.port); + break; + case AF_INET6: + sock_out.ip6.sin6_port = htons(node->address.port); + break; + default: + DEBUG(DEBUG_ERR, (__location__ "" unknown family %u\n"", + sock_out.sa.sa_family)); + return; + } + + tnode->fd = socket(sock_out.sa.sa_family, SOCK_STREAM, IPPROTO_TCP); + if (tnode->fd == -1) { + DEBUG(DEBUG_ERR, (__location__ ""Failed to create socket\n"")); + return; + } + set_nonblocking(tnode->fd); + set_close_on_exec(tnode->fd); + + DEBUG(DEBUG_DEBUG, (__location__ "" Created TCP SOCKET FD:%d\n"", tnode->fd)); + + /* Bind our side of the socketpair to the same address we use to listen + * on incoming CTDB traffic. + * We must specify this address to make sure that the address we expose to + * the remote side is actually routable in case CTDB traffic will run on + * a dedicated non-routeable network. + */ + ZERO_STRUCT(sock_in); + if (ctdb_tcp_get_address(ctdb, ctdb->address.address, &sock_in) != 0) { + DEBUG(DEBUG_ERR, (__location__ "" Failed to find our address. Failing bind.\n"")); + close(tnode->fd); + return; + } + + /* AIX libs check to see if the socket address and length + arguments are consistent with each other on calls like + connect(). Can not get by with just sizeof(sock_in), + need sizeof(sock_in.ip). + */ + switch (sock_in.sa.sa_family) { + case AF_INET: + sockin_size = sizeof(sock_in.ip); + sockout_size = sizeof(sock_out.ip); + break; + case AF_INET6: + sockin_size = sizeof(sock_in.ip6); + sockout_size = sizeof(sock_out.ip6); + break; + default: + DEBUG(DEBUG_ERR, (__location__ "" unknown family %u\n"", + sock_in.sa.sa_family)); + close(tnode->fd); + return; + } +#ifdef HAVE_SOCK_SIN_LEN + sock_in.ip.sin_len = sockin_size; + sock_out.ip.sin_len = sockout_size; +#endif + if (bind(tnode->fd, (struct sockaddr *)&sock_in, sockin_size) == -1) { + DEBUG(DEBUG_ERR, (__location__ ""Failed to bind socket %s(%d)\n"", + strerror(errno), errno)); + close(tnode->fd); + return; + } + + if (connect(tnode->fd, (struct sockaddr *)&sock_out, sockout_size) != 0 && + errno != EINPROGRESS) { + ctdb_tcp_stop_connection(node); + tnode->connect_te = event_add_timed(ctdb->ev, tnode, + timeval_current_ofs(1, 0), + ctdb_tcp_node_connect, node); + return; + } + + /* non-blocking connect - wait for write event */ + tnode->connect_fde = event_add_fd(node->ctdb->ev, tnode, tnode->fd, + EVENT_FD_WRITE|EVENT_FD_READ, + ctdb_node_connect_write, node); + + /* don't give it long to connect - retry in one second. This ensures + that we find a node is up quickly (tcp normally backs off a syn reply + delay by quite a lot) */ + tnode->connect_te = event_add_timed(ctdb->ev, tnode, timeval_current_ofs(1, 0), + ctdb_tcp_node_connect, node); +} +","@@ -284,7 +284,7 @@ static int ctdb_tcp_listen_automatic(struct ctdb_context *ctdb) + struct ctdb_tcp); + ctdb_sock_addr sock; + int lock_fd, i; +- const char *lock_path = ""/tmp/.ctdb_socket_lock""; ++ const char *lock_path = VARDIR ""/run/ctdb/.socket_lock""; + struct flock lock; + int one = 1; + int sock_size;",966,1297,2048 +1158,"int phar_detect_phar_fname_ext(const char *filename, int filename_len, const char **ext_str, int *ext_len, int executable, int for_create, int is_complete) /* {{{ */ +{ + const char *pos, *slash; + + *ext_str = NULL; + *ext_len = 0; + + if (!filename_len || filename_len == 1) { + return FAILURE; + } + + phar_request_initialize(); + /* first check for alias in first segment */ + pos = memchr(filename, '/', filename_len); + + if (pos && pos != filename) { + /* check for url like http:// or phar:// */ + if (*(pos - 1) == ':' && (pos - filename) < filename_len - 1 && *(pos + 1) == '/') { + *ext_len = -2; + *ext_str = NULL; + return FAILURE; + } + if (zend_hash_str_exists(&(PHAR_G(phar_alias_map)), (char *) filename, pos - filename)) { + *ext_str = pos; + *ext_len = -1; + return FAILURE; + } + + if (PHAR_G(manifest_cached) && zend_hash_str_exists(&cached_alias, (char *) filename, pos - filename)) { + *ext_str = pos; + *ext_len = -1; + return FAILURE; + } + } + + if (zend_hash_num_elements(&(PHAR_G(phar_fname_map))) || PHAR_G(manifest_cached)) { + phar_archive_data *pphar; + + if (is_complete) { + if (NULL != (pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), (char *) filename, filename_len))) { + *ext_str = filename + (filename_len - pphar->ext_len); +woohoo: + *ext_len = pphar->ext_len; + + if (executable == 2) { + return SUCCESS; + } + + if (executable == 1 && !pphar->is_data) { + return SUCCESS; + } + + if (!executable && pphar->is_data) { + return SUCCESS; + } + + return FAILURE; + } + + if (PHAR_G(manifest_cached) && NULL != (pphar = zend_hash_str_find_ptr(&cached_phars, (char *) filename, filename_len))) { + *ext_str = filename + (filename_len - pphar->ext_len); + goto woohoo; + } + } else { + zend_string *str_key; + zend_ulong unused; + + for (zend_hash_internal_pointer_reset(&(PHAR_G(phar_fname_map))); + HASH_KEY_NON_EXISTENT != zend_hash_get_current_key(&(PHAR_G(phar_fname_map)), &str_key, &unused); + zend_hash_move_forward(&(PHAR_G(phar_fname_map))) + ) { + if (ZSTR_LEN(str_key) > (uint) filename_len) { + continue; + } + + if (!memcmp(filename, ZSTR_VAL(str_key), ZSTR_LEN(str_key)) && ((uint)filename_len == ZSTR_LEN(str_key) + || filename[ZSTR_LEN(str_key)] == '/' || filename[ZSTR_LEN(str_key)] == '\0')) { + if (NULL == (pphar = zend_hash_get_current_data_ptr(&(PHAR_G(phar_fname_map))))) { + break; + } + *ext_str = filename + (ZSTR_LEN(str_key) - pphar->ext_len); + goto woohoo; + } + } + + if (PHAR_G(manifest_cached)) { + for (zend_hash_internal_pointer_reset(&cached_phars); + HASH_KEY_NON_EXISTENT != zend_hash_get_current_key(&cached_phars, &str_key, &unused); + zend_hash_move_forward(&cached_phars) + ) { + if (ZSTR_LEN(str_key) > (uint) filename_len) { + continue; + } + + if (!memcmp(filename, ZSTR_VAL(str_key), ZSTR_LEN(str_key)) && ((uint)filename_len == ZSTR_LEN(str_key) + || filename[ZSTR_LEN(str_key)] == '/' || filename[ZSTR_LEN(str_key)] == '\0')) { + if (NULL == (pphar = zend_hash_get_current_data_ptr(&cached_phars))) { + break; + } + *ext_str = filename + (ZSTR_LEN(str_key) - pphar->ext_len); + goto woohoo; + } + } + } + } + } + + pos = memchr(filename + 1, '.', filename_len); +next_extension: + if (!pos) { + return FAILURE; + } + + while (pos != filename && (*(pos - 1) == '/' || *(pos - 1) == '\0')) { + pos = memchr(pos + 1, '.', filename_len - (pos - filename) + 1); + if (!pos) { + return FAILURE; + } + } + + slash = memchr(pos, '/', filename_len - (pos - filename)); + + if (!slash) { + /* this is a url like ""phar://blah.phar"" with no directory */ + *ext_str = pos; + *ext_len = strlen(pos); + + /* file extension must contain ""phar"" */ + switch (phar_check_str(filename, *ext_str, *ext_len, executable, for_create)) { + case SUCCESS: + return SUCCESS; + case FAILURE: + /* we are at the end of the string, so we fail */ + return FAILURE; + } + } + + /* we've found an extension that ends at a directory separator */ + *ext_str = pos; + *ext_len = slash - pos; + + switch (phar_check_str(filename, *ext_str, *ext_len, executable, for_create)) { + case SUCCESS: + return SUCCESS; + case FAILURE: + /* look for more extensions */ + pos = strchr(pos + 1, '.'); + if (pos) { + *ext_str = NULL; + *ext_len = 0; + } + goto next_extension; + } + + return FAILURE; +} +/* }}} */ +",0,"int phar_detect_phar_fname_ext(const char *filename, int filename_len, const char **ext_str, int *ext_len, int executable, int for_create, int is_complete) /* {{{ */ +{ + const char *pos, *slash; + + *ext_str = NULL; + *ext_len = 0; + + if (!filename_len || filename_len == 1) { + return FAILURE; + } + + phar_request_initialize(); + /* first check for alias in first segment */ + pos = memchr(filename, '/', filename_len); + + if (pos && pos != filename) { + /* check for url like http:// or phar:// */ + if (*(pos - 1) == ':' && (pos - filename) < filename_len - 1 && *(pos + 1) == '/') { + *ext_len = -2; + *ext_str = NULL; + return FAILURE; + } + if (zend_hash_str_exists(&(PHAR_G(phar_alias_map)), (char *) filename, pos - filename)) { + *ext_str = pos; + *ext_len = -1; + return FAILURE; + } + + if (PHAR_G(manifest_cached) && zend_hash_str_exists(&cached_alias, (char *) filename, pos - filename)) { + *ext_str = pos; + *ext_len = -1; + return FAILURE; + } + } + + if (zend_hash_num_elements(&(PHAR_G(phar_fname_map))) || PHAR_G(manifest_cached)) { + phar_archive_data *pphar; + + if (is_complete) { + if (NULL != (pphar = zend_hash_str_find_ptr(&(PHAR_G(phar_fname_map)), (char *) filename, filename_len))) { + *ext_str = filename + (filename_len - pphar->ext_len); +woohoo: + *ext_len = pphar->ext_len; + + if (executable == 2) { + return SUCCESS; + } + + if (executable == 1 && !pphar->is_data) { + return SUCCESS; + } + + if (!executable && pphar->is_data) { + return SUCCESS; + } + + return FAILURE; + } + + if (PHAR_G(manifest_cached) && NULL != (pphar = zend_hash_str_find_ptr(&cached_phars, (char *) filename, filename_len))) { + *ext_str = filename + (filename_len - pphar->ext_len); + goto woohoo; + } + } else { + zend_string *str_key; + zend_ulong unused; + + for (zend_hash_internal_pointer_reset(&(PHAR_G(phar_fname_map))); + HASH_KEY_NON_EXISTENT != zend_hash_get_current_key(&(PHAR_G(phar_fname_map)), &str_key, &unused); + zend_hash_move_forward(&(PHAR_G(phar_fname_map))) + ) { + if (ZSTR_LEN(str_key) > (uint) filename_len) { + continue; + } + + if (!memcmp(filename, ZSTR_VAL(str_key), ZSTR_LEN(str_key)) && ((uint)filename_len == ZSTR_LEN(str_key) + || filename[ZSTR_LEN(str_key)] == '/' || filename[ZSTR_LEN(str_key)] == '\0')) { + if (NULL == (pphar = zend_hash_get_current_data_ptr(&(PHAR_G(phar_fname_map))))) { + break; + } + *ext_str = filename + (ZSTR_LEN(str_key) - pphar->ext_len); + goto woohoo; + } + } + + if (PHAR_G(manifest_cached)) { + for (zend_hash_internal_pointer_reset(&cached_phars); + HASH_KEY_NON_EXISTENT != zend_hash_get_current_key(&cached_phars, &str_key, &unused); + zend_hash_move_forward(&cached_phars) + ) { + if (ZSTR_LEN(str_key) > (uint) filename_len) { + continue; + } + + if (!memcmp(filename, ZSTR_VAL(str_key), ZSTR_LEN(str_key)) && ((uint)filename_len == ZSTR_LEN(str_key) + || filename[ZSTR_LEN(str_key)] == '/' || filename[ZSTR_LEN(str_key)] == '\0')) { + if (NULL == (pphar = zend_hash_get_current_data_ptr(&cached_phars))) { + break; + } + *ext_str = filename + (ZSTR_LEN(str_key) - pphar->ext_len); + goto woohoo; + } + } + } + } + } + + pos = memchr(filename + 1, '.', filename_len); +next_extension: + if (!pos) { + return FAILURE; + } + + while (pos != filename && (*(pos - 1) == '/' || *(pos - 1) == '\0')) { + pos = memchr(pos + 1, '.', filename_len - (pos - filename) + 1); + if (!pos) { + return FAILURE; + } + } + + slash = memchr(pos, '/', filename_len - (pos - filename)); + + if (!slash) { + /* this is a url like ""phar://blah.phar"" with no directory */ + *ext_str = pos; + *ext_len = strlen(pos); + + /* file extension must contain ""phar"" */ + switch (phar_check_str(filename, *ext_str, *ext_len, executable, for_create)) { + case SUCCESS: + return SUCCESS; + case FAILURE: + /* we are at the end of the string, so we fail */ + return FAILURE; + } + } + + /* we've found an extension that ends at a directory separator */ + *ext_str = pos; + *ext_len = slash - pos; + + switch (phar_check_str(filename, *ext_str, *ext_len, executable, for_create)) { + case SUCCESS: + return SUCCESS; + case FAILURE: + /* look for more extensions */ + pos = strchr(pos + 1, '.'); + if (pos) { + *ext_str = NULL; + *ext_len = 0; + } + goto next_extension; + } + + return FAILURE; +} +/* }}} */ +","@@ -2196,6 +2196,10 @@ int phar_split_fname(const char *filename, int filename_len, char **arch, int *a + #endif + int ext_len; + ++ if (CHECK_NULL_PATH(filename, filename_len)) { ++ return FAILURE; ++ } ++ + if (!strncasecmp(filename, ""phar://"", 7)) { + filename += 7; + filename_len -= 7;",1321,1652,2048 +3301,"static long kvm_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; + struct kvm_fpu *fpu = NULL; + struct kvm_sregs *kvm_sregs = NULL; + + if (vcpu->kvm->mm != current->mm) + return -EIO; + +#if defined(CONFIG_S390) || defined(CONFIG_PPC) + /* + * Special cases: vcpu ioctls that are asynchronous to vcpu execution, + * so vcpu_load() would break it. + */ + if (ioctl == KVM_S390_INTERRUPT || ioctl == KVM_INTERRUPT) + return kvm_arch_vcpu_ioctl(filp, ioctl, arg); +#endif + + + vcpu_load(vcpu); + switch (ioctl) { + case KVM_RUN: + r = -EINVAL; + if (arg) + goto out; + r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run); + trace_kvm_userspace_exit(vcpu->run->exit_reason, r); + break; + case KVM_GET_REGS: { + struct kvm_regs *kvm_regs; + + r = -ENOMEM; + kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL); + if (!kvm_regs) + goto out; + r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs); + if (r) + goto out_free1; + r = -EFAULT; + if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs))) + goto out_free1; + r = 0; +out_free1: + kfree(kvm_regs); + break; + } + case KVM_SET_REGS: { + struct kvm_regs *kvm_regs; + + r = -ENOMEM; + kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL); + if (!kvm_regs) + goto out; + r = -EFAULT; + if (copy_from_user(kvm_regs, argp, sizeof(struct kvm_regs))) + goto out_free2; + r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs); + if (r) + goto out_free2; + r = 0; +out_free2: + kfree(kvm_regs); + break; + } + case KVM_GET_SREGS: { + kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL); + r = -ENOMEM; + if (!kvm_sregs) + goto out; + r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs); + if (r) + goto out; + r = -EFAULT; + if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs))) + goto out; + r = 0; + break; + } + case KVM_SET_SREGS: { + kvm_sregs = kmalloc(sizeof(struct kvm_sregs), GFP_KERNEL); + r = -ENOMEM; + if (!kvm_sregs) + goto out; + r = -EFAULT; + if (copy_from_user(kvm_sregs, argp, sizeof(struct kvm_sregs))) + goto out; + r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs); + if (r) + goto out; + r = 0; + break; + } + case KVM_GET_MP_STATE: { + struct kvm_mp_state mp_state; + + r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state); + if (r) + goto out; + r = -EFAULT; + if (copy_to_user(argp, &mp_state, sizeof mp_state)) + goto out; + r = 0; + break; + } + case KVM_SET_MP_STATE: { + struct kvm_mp_state mp_state; + + r = -EFAULT; + if (copy_from_user(&mp_state, argp, sizeof mp_state)) + goto out; + r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state); + if (r) + goto out; + r = 0; + break; + } + case KVM_TRANSLATE: { + struct kvm_translation tr; + + r = -EFAULT; + if (copy_from_user(&tr, argp, sizeof tr)) + goto out; + r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr); + if (r) + goto out; + r = -EFAULT; + if (copy_to_user(argp, &tr, sizeof tr)) + goto out; + r = 0; + break; + } + case KVM_SET_GUEST_DEBUG: { + struct kvm_guest_debug dbg; + + r = -EFAULT; + if (copy_from_user(&dbg, argp, sizeof dbg)) + goto out; + r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg); + if (r) + goto out; + r = 0; + break; + } + case KVM_SET_SIGNAL_MASK: { + struct kvm_signal_mask __user *sigmask_arg = argp; + struct kvm_signal_mask kvm_sigmask; + sigset_t sigset, *p; + + p = NULL; + if (argp) { + r = -EFAULT; + if (copy_from_user(&kvm_sigmask, argp, + sizeof kvm_sigmask)) + goto out; + r = -EINVAL; + if (kvm_sigmask.len != sizeof sigset) + goto out; + r = -EFAULT; + if (copy_from_user(&sigset, sigmask_arg->sigset, + sizeof sigset)) + goto out; + p = &sigset; + } + r = kvm_vcpu_ioctl_set_sigmask(vcpu, p); + break; + } + case KVM_GET_FPU: { + fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL); + r = -ENOMEM; + if (!fpu) + goto out; + r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu); + if (r) + goto out; + r = -EFAULT; + if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu))) + goto out; + r = 0; + break; + } + case KVM_SET_FPU: { + fpu = kmalloc(sizeof(struct kvm_fpu), GFP_KERNEL); + r = -ENOMEM; + if (!fpu) + goto out; + r = -EFAULT; + if (copy_from_user(fpu, argp, sizeof(struct kvm_fpu))) + goto out; + r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu); + if (r) + goto out; + r = 0; + break; + } + default: + r = kvm_arch_vcpu_ioctl(filp, ioctl, arg); + } +out: + vcpu_put(vcpu); + kfree(fpu); + kfree(kvm_sregs); + return r; +} +",0,"static long kvm_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; + struct kvm_fpu *fpu = NULL; + struct kvm_sregs *kvm_sregs = NULL; + + if (vcpu->kvm->mm != current->mm) + return -EIO; + +#if defined(CONFIG_S390) || defined(CONFIG_PPC) + /* + * Special cases: vcpu ioctls that are asynchronous to vcpu execution, + * so vcpu_load() would break it. + */ + if (ioctl == KVM_S390_INTERRUPT || ioctl == KVM_INTERRUPT) + return kvm_arch_vcpu_ioctl(filp, ioctl, arg); +#endif + + + vcpu_load(vcpu); + switch (ioctl) { + case KVM_RUN: + r = -EINVAL; + if (arg) + goto out; + r = kvm_arch_vcpu_ioctl_run(vcpu, vcpu->run); + trace_kvm_userspace_exit(vcpu->run->exit_reason, r); + break; + case KVM_GET_REGS: { + struct kvm_regs *kvm_regs; + + r = -ENOMEM; + kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL); + if (!kvm_regs) + goto out; + r = kvm_arch_vcpu_ioctl_get_regs(vcpu, kvm_regs); + if (r) + goto out_free1; + r = -EFAULT; + if (copy_to_user(argp, kvm_regs, sizeof(struct kvm_regs))) + goto out_free1; + r = 0; +out_free1: + kfree(kvm_regs); + break; + } + case KVM_SET_REGS: { + struct kvm_regs *kvm_regs; + + r = -ENOMEM; + kvm_regs = kzalloc(sizeof(struct kvm_regs), GFP_KERNEL); + if (!kvm_regs) + goto out; + r = -EFAULT; + if (copy_from_user(kvm_regs, argp, sizeof(struct kvm_regs))) + goto out_free2; + r = kvm_arch_vcpu_ioctl_set_regs(vcpu, kvm_regs); + if (r) + goto out_free2; + r = 0; +out_free2: + kfree(kvm_regs); + break; + } + case KVM_GET_SREGS: { + kvm_sregs = kzalloc(sizeof(struct kvm_sregs), GFP_KERNEL); + r = -ENOMEM; + if (!kvm_sregs) + goto out; + r = kvm_arch_vcpu_ioctl_get_sregs(vcpu, kvm_sregs); + if (r) + goto out; + r = -EFAULT; + if (copy_to_user(argp, kvm_sregs, sizeof(struct kvm_sregs))) + goto out; + r = 0; + break; + } + case KVM_SET_SREGS: { + kvm_sregs = kmalloc(sizeof(struct kvm_sregs), GFP_KERNEL); + r = -ENOMEM; + if (!kvm_sregs) + goto out; + r = -EFAULT; + if (copy_from_user(kvm_sregs, argp, sizeof(struct kvm_sregs))) + goto out; + r = kvm_arch_vcpu_ioctl_set_sregs(vcpu, kvm_sregs); + if (r) + goto out; + r = 0; + break; + } + case KVM_GET_MP_STATE: { + struct kvm_mp_state mp_state; + + r = kvm_arch_vcpu_ioctl_get_mpstate(vcpu, &mp_state); + if (r) + goto out; + r = -EFAULT; + if (copy_to_user(argp, &mp_state, sizeof mp_state)) + goto out; + r = 0; + break; + } + case KVM_SET_MP_STATE: { + struct kvm_mp_state mp_state; + + r = -EFAULT; + if (copy_from_user(&mp_state, argp, sizeof mp_state)) + goto out; + r = kvm_arch_vcpu_ioctl_set_mpstate(vcpu, &mp_state); + if (r) + goto out; + r = 0; + break; + } + case KVM_TRANSLATE: { + struct kvm_translation tr; + + r = -EFAULT; + if (copy_from_user(&tr, argp, sizeof tr)) + goto out; + r = kvm_arch_vcpu_ioctl_translate(vcpu, &tr); + if (r) + goto out; + r = -EFAULT; + if (copy_to_user(argp, &tr, sizeof tr)) + goto out; + r = 0; + break; + } + case KVM_SET_GUEST_DEBUG: { + struct kvm_guest_debug dbg; + + r = -EFAULT; + if (copy_from_user(&dbg, argp, sizeof dbg)) + goto out; + r = kvm_arch_vcpu_ioctl_set_guest_debug(vcpu, &dbg); + if (r) + goto out; + r = 0; + break; + } + case KVM_SET_SIGNAL_MASK: { + struct kvm_signal_mask __user *sigmask_arg = argp; + struct kvm_signal_mask kvm_sigmask; + sigset_t sigset, *p; + + p = NULL; + if (argp) { + r = -EFAULT; + if (copy_from_user(&kvm_sigmask, argp, + sizeof kvm_sigmask)) + goto out; + r = -EINVAL; + if (kvm_sigmask.len != sizeof sigset) + goto out; + r = -EFAULT; + if (copy_from_user(&sigset, sigmask_arg->sigset, + sizeof sigset)) + goto out; + p = &sigset; + } + r = kvm_vcpu_ioctl_set_sigmask(vcpu, p); + break; + } + case KVM_GET_FPU: { + fpu = kzalloc(sizeof(struct kvm_fpu), GFP_KERNEL); + r = -ENOMEM; + if (!fpu) + goto out; + r = kvm_arch_vcpu_ioctl_get_fpu(vcpu, fpu); + if (r) + goto out; + r = -EFAULT; + if (copy_to_user(argp, fpu, sizeof(struct kvm_fpu))) + goto out; + r = 0; + break; + } + case KVM_SET_FPU: { + fpu = kmalloc(sizeof(struct kvm_fpu), GFP_KERNEL); + r = -ENOMEM; + if (!fpu) + goto out; + r = -EFAULT; + if (copy_from_user(fpu, argp, sizeof(struct kvm_fpu))) + goto out; + r = kvm_arch_vcpu_ioctl_set_fpu(vcpu, fpu); + if (r) + goto out; + r = 0; + break; + } + default: + r = kvm_arch_vcpu_ioctl(filp, ioctl, arg); + } +out: + vcpu_put(vcpu); + kfree(fpu); + kfree(kvm_sregs); + return r; +} +","@@ -648,7 +648,10 @@ int __kvm_set_memory_region(struct kvm *kvm, + goto out; + if (mem->guest_phys_addr & (PAGE_SIZE - 1)) + goto out; +- if (user_alloc && (mem->userspace_addr & (PAGE_SIZE - 1))) ++ /* We can read the guest memory with __xxx_user() later on. */ ++ if (user_alloc && ++ ((mem->userspace_addr & (PAGE_SIZE - 1)) || ++ !access_ok(VERIFY_WRITE, mem->userspace_addr, mem->memory_size))) + goto out; + if (mem->slot >= KVM_MEMORY_SLOTS + KVM_PRIVATE_MEM_SLOTS) + goto out; +@@ -1283,7 +1286,7 @@ int kvm_read_guest_page(struct kvm *kvm, gfn_t gfn, void *data, int offset, + addr = gfn_to_hva(kvm, gfn); + if (kvm_is_error_hva(addr)) + return -EFAULT; +- r = copy_from_user(data, (void __user *)addr + offset, len); ++ r = __copy_from_user(data, (void __user *)addr + offset, len); + if (r) + return -EFAULT; + return 0;",1476,1807,2048 +18322,"int gdTransformAffineCopy(gdImagePtr dst, + int dst_x, int dst_y, + const gdImagePtr src, + gdRectPtr src_region, + const double affine[6]) +{ + int c1x,c1y,c2x,c2y; + int backclip = 0; + int backup_clipx1, backup_clipy1, backup_clipx2, backup_clipy2; + register int x, y, src_offset_x, src_offset_y; + double inv[6]; + int *dst_p; + gdPointF pt, src_pt; + gdRect bbox; + int end_x, end_y; + gdInterpolationMethod interpolation_id_bak = GD_DEFAULT; + interpolation_method interpolation_bak; + + /* These methods use special implementations */ + if (src->interpolation_id == GD_BILINEAR_FIXED || src->interpolation_id == GD_BICUBIC_FIXED || src->interpolation_id == GD_NEAREST_NEIGHBOUR) { + interpolation_id_bak = src->interpolation_id; + interpolation_bak = src->interpolation; + gdImageSetInterpolationMethod(src, GD_BICUBIC); + } + + + gdImageClipRectangle(src, src_region); + + if (src_region->x > 0 || src_region->y > 0 + || src_region->width < gdImageSX(src) + || src_region->height < gdImageSY(src)) { + backclip = 1; + + gdImageGetClip(src, &backup_clipx1, &backup_clipy1, + &backup_clipx2, &backup_clipy2); + + gdImageSetClip(src, src_region->x, src_region->y, + src_region->x + src_region->width - 1, + src_region->y + src_region->height - 1); + } + + if (!gdTransformAffineBoundingBox(src_region, affine, &bbox)) { + if (backclip) { + gdImageSetClip(src, backup_clipx1, backup_clipy1, + backup_clipx2, backup_clipy2); + } + gdImageSetInterpolationMethod(src, interpolation_id_bak); + return GD_FALSE; + } + + gdImageGetClip(dst, &c1x, &c1y, &c2x, &c2y); + + end_x = bbox.width + (int) fabs(bbox.x); + end_y = bbox.height + (int) fabs(bbox.y); + + /* Get inverse affine to let us work with destination -> source */ + gdAffineInvert(inv, affine); + + src_offset_x = src_region->x; + src_offset_y = src_region->y; + + if (dst->alphaBlendingFlag) { + for (y = bbox.y; y <= end_y; y++) { + pt.y = y + 0.5; + for (x = 0; x <= end_x; x++) { + pt.x = x + 0.5; + gdAffineApplyToPointF(&src_pt, &pt, inv); + gdImageSetPixel(dst, dst_x + x, dst_y + y, getPixelInterpolated(src, src_offset_x + src_pt.x, src_offset_y + src_pt.y, 0)); + } + } + } else { + for (y = 0; y <= end_y; y++) { + pt.y = y + 0.5 + bbox.y; + if ((dst_y + y) < 0 || ((dst_y + y) > gdImageSY(dst) -1)) { + continue; + } + dst_p = dst->tpixels[dst_y + y] + dst_x; + + for (x = 0; x <= end_x; x++) { + pt.x = x + 0.5 + bbox.x; + gdAffineApplyToPointF(&src_pt, &pt, inv); + + if ((dst_x + x) < 0 || (dst_x + x) > (gdImageSX(dst) - 1)) { + break; + } + *(dst_p++) = getPixelInterpolated(src, src_offset_x + src_pt.x, src_offset_y + src_pt.y, -1); + } + } + } + + /* Restore clip if required */ + if (backclip) { + gdImageSetClip(src, backup_clipx1, backup_clipy1, + backup_clipx2, backup_clipy2); + } + + gdImageSetInterpolationMethod(src, interpolation_id_bak); + return GD_TRUE; +} +",1,"int gdTransformAffineCopy(gdImagePtr dst, + int dst_x, int dst_y, + const gdImagePtr src, + gdRectPtr src_region, + const double affine[6]) +{ + int c1x,c1y,c2x,c2y; + int backclip = 0; + int backup_clipx1, backup_clipy1, backup_clipx2, backup_clipy2; + register int x, y, src_offset_x, src_offset_y; + double inv[6]; + int *dst_p; + gdPointF pt, src_pt; + gdRect bbox; + int end_x, end_y; + gdInterpolationMethod interpolation_id_bak = GD_DEFAULT; + interpolation_method interpolation_bak; + + /* These methods use special implementations */ + if (src->interpolation_id == GD_BILINEAR_FIXED || src->interpolation_id == GD_BICUBIC_FIXED || src->interpolation_id == GD_NEAREST_NEIGHBOUR) { + interpolation_id_bak = src->interpolation_id; + interpolation_bak = src->interpolation; + + gdImageSetInterpolationMethod(src, GD_BICUBIC); + } + + + gdImageClipRectangle(src, src_region); + + if (src_region->x > 0 || src_region->y > 0 + || src_region->width < gdImageSX(src) + || src_region->height < gdImageSY(src)) { + backclip = 1; + + gdImageGetClip(src, &backup_clipx1, &backup_clipy1, + &backup_clipx2, &backup_clipy2); + + gdImageSetClip(src, src_region->x, src_region->y, + src_region->x + src_region->width - 1, + src_region->y + src_region->height - 1); + } + + if (!gdTransformAffineBoundingBox(src_region, affine, &bbox)) { + if (backclip) { + gdImageSetClip(src, backup_clipx1, backup_clipy1, + backup_clipx2, backup_clipy2); + } + gdImageSetInterpolationMethod(src, interpolation_id_bak); + return GD_FALSE; + } + + gdImageGetClip(dst, &c1x, &c1y, &c2x, &c2y); + + end_x = bbox.width + (int) fabs(bbox.x); + end_y = bbox.height + (int) fabs(bbox.y); + + /* Get inverse affine to let us work with destination -> source */ + gdAffineInvert(inv, affine); + + src_offset_x = src_region->x; + src_offset_y = src_region->y; + + if (dst->alphaBlendingFlag) { + for (y = bbox.y; y <= end_y; y++) { + pt.y = y + 0.5; + for (x = 0; x <= end_x; x++) { + pt.x = x + 0.5; + gdAffineApplyToPointF(&src_pt, &pt, inv); + gdImageSetPixel(dst, dst_x + x, dst_y + y, getPixelInterpolated(src, src_offset_x + src_pt.x, src_offset_y + src_pt.y, 0)); + } + } + } else { + for (y = 0; y <= end_y; y++) { + pt.y = y + 0.5 + bbox.y; + if ((dst_y + y) < 0 || ((dst_y + y) > gdImageSY(dst) -1)) { + continue; + } + dst_p = dst->tpixels[dst_y + y] + dst_x; + + for (x = 0; x <= end_x; x++) { + pt.x = x + 0.5 + bbox.x; + gdAffineApplyToPointF(&src_pt, &pt, inv); + + if ((dst_x + x) < 0 || (dst_x + x) > (gdImageSX(dst) - 1)) { + break; + } + *(dst_p++) = getPixelInterpolated(src, src_offset_x + src_pt.x, src_offset_y + src_pt.y, -1); + } + } + } + + /* Restore clip if required */ + if (backclip) { + gdImageSetClip(src, backup_clipx1, backup_clipy1, + backup_clipx2, backup_clipy2); + } + + gdImageSetInterpolationMethod(src, interpolation_id_bak); + return GD_TRUE; +} +","@@ -39,8 +39,8 @@ + downscaling using the fixed point implementations are usually much faster + than the existing gdImageCopyResampled while having a similar or better + quality. +- +- For image rotations, the optimized versions have a lazy antialiasing for ++ ++ For image rotations, the optimized versions have a lazy antialiasing for + the edges of the images. For a much better antialiased result, the affine + function is recommended. + */ +@@ -633,7 +633,7 @@ static inline int _color_blend (const int dst, const int src) + } + } + +-static inline int _setEdgePixel(const gdImagePtr src, unsigned int x, unsigned int y, gdFixed coverage, const int bgColor) ++static inline int _setEdgePixel(const gdImagePtr src, unsigned int x, unsigned int y, gdFixed coverage, const int bgColor) + { + const gdFixed f_127 = gd_itofx(127); + register int c = src->tpixels[y][x]; +@@ -934,9 +934,6 @@ static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsi + double dTotalWeight = 0.0; + int iSrc; + +- res->ContribRow[u].Left = iLeft; +- res->ContribRow[u].Right = iRight; +- + /* Cut edge points to fit in filter window in case of spill-off */ + if (iRight - iLeft + 1 > windows_size) { + if (iLeft < ((int)src_size - 1 / 2)) { +@@ -946,6 +943,9 @@ static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsi + } + } + ++ res->ContribRow[u].Left = iLeft; ++ res->ContribRow[u].Right = iRight; ++ + for (iSrc = iLeft; iSrc <= iRight; iSrc++) { + dTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc))); + } +@@ -2273,7 +2273,7 @@ int gdTransformAffineGetImage(gdImagePtr *dst, + if (!src->trueColor) { + gdImagePaletteToTrueColor(src); + } +- ++ + /* Translate to dst origin (0,0) */ + gdAffineTranslate(m, -bbox.x, -bbox.y); + gdAffineConcat(m, affine, m); +@@ -2332,7 +2332,7 @@ int gdTransformAffineCopy(gdImagePtr dst, + if (src->interpolation_id == GD_BILINEAR_FIXED || src->interpolation_id == GD_BICUBIC_FIXED || src->interpolation_id == GD_NEAREST_NEIGHBOUR) { + interpolation_id_bak = src->interpolation_id; + interpolation_bak = src->interpolation; +- ++ + gdImageSetInterpolationMethod(src, GD_BICUBIC); + } + ",969,1300,2048 +440,"void Splash::scaleImageYuXuBilinear(SplashImageSource src, void *srcData, + SplashColorMode srcMode, int nComps, + GBool srcAlpha, int srcWidth, int srcHeight, + int scaledWidth, int scaledHeight, + SplashBitmap *dest) { + Guchar *srcBuf, *lineBuf1, *lineBuf2, *alphaSrcBuf, *alphaLineBuf1, *alphaLineBuf2; + Guint pix[splashMaxColorComps]; + Guchar *destPtr0, *destPtr, *destAlphaPtr0, *destAlphaPtr; + int i; + + srcBuf = (Guchar *)gmallocn(srcWidth+1, nComps); // + 1 pixel of padding + lineBuf1 = (Guchar *)gmallocn(scaledWidth, nComps); + lineBuf2 = (Guchar *)gmallocn(scaledWidth, nComps); + if (srcAlpha) { + alphaSrcBuf = (Guchar *)gmalloc(srcWidth+1); // + 1 pixel of padding + alphaLineBuf1 = (Guchar *)gmalloc(scaledWidth); + alphaLineBuf2 = (Guchar *)gmalloc(scaledWidth); + } else { + alphaSrcBuf = NULL; + alphaLineBuf1 = NULL; + alphaLineBuf2 = NULL; + } + + double ySrc = 0.0; + double yStep = (double)srcHeight/scaledHeight; + double yFrac, yInt; + int currentSrcRow = -1; + (*src)(srcData, srcBuf, alphaSrcBuf); + expandRow(srcBuf, lineBuf2, srcWidth, scaledWidth, nComps); + if (srcAlpha) + expandRow(alphaSrcBuf, alphaLineBuf2, srcWidth, scaledWidth, 1); + + destPtr0 = dest->data; + destAlphaPtr0 = dest->alpha; + for (int y = 0; y < scaledHeight; y++) { + yFrac = modf(ySrc, &yInt); + if ((int)yInt > currentSrcRow) { + currentSrcRow++; + memcpy(lineBuf1, lineBuf2, scaledWidth * nComps); + if (srcAlpha) + memcpy(alphaLineBuf1, alphaLineBuf2, scaledWidth); + if (currentSrcRow < srcHeight) { + (*src)(srcData, srcBuf, alphaSrcBuf); + expandRow(srcBuf, lineBuf2, srcWidth, scaledWidth, nComps); + if (srcAlpha) + expandRow(alphaSrcBuf, alphaLineBuf2, srcWidth, scaledWidth, 1); + } + } + + for (int x = 0; x < scaledWidth; ++x) { + for (i = 0; i < nComps; ++i) { + pix[i] = lineBuf1[x*nComps + i]*(1.0 - yFrac) + lineBuf2[x*nComps + i]*yFrac; + } + + destPtr = destPtr0 + (y * scaledWidth + x) * nComps; + switch (srcMode) { + case splashModeMono1: // mono1 is not allowed + break; + case splashModeMono8: + *destPtr++ = (Guchar)pix[0]; + break; + case splashModeRGB8: + *destPtr++ = (Guchar)pix[0]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[2]; + break; + case splashModeXBGR8: + *destPtr++ = (Guchar)pix[2]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[0]; + *destPtr++ = (Guchar)255; + break; + case splashModeBGR8: + *destPtr++ = (Guchar)pix[2]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[0]; + break; +#if SPLASH_CMYK + case splashModeCMYK8: + *destPtr++ = (Guchar)pix[0]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[2]; + *destPtr++ = (Guchar)pix[3]; + break; + case splashModeDeviceN8: + for (int cp = 0; cp < SPOT_NCOMPS+4; cp++) + *destPtr++ = (Guchar)pix[cp]; + break; +#endif + } + + if (srcAlpha) { + destAlphaPtr = destAlphaPtr0 + y*scaledWidth + x; + *destAlphaPtr = alphaLineBuf1[x]*(1.0 - yFrac) + alphaLineBuf2[x]*yFrac; + } + } + + ySrc += yStep; + } + + gfree(alphaSrcBuf); + gfree(alphaLineBuf1); + gfree(alphaLineBuf2); + gfree(srcBuf); + gfree(lineBuf1); + gfree(lineBuf2); +} +",0,"void Splash::scaleImageYuXuBilinear(SplashImageSource src, void *srcData, + SplashColorMode srcMode, int nComps, + GBool srcAlpha, int srcWidth, int srcHeight, + int scaledWidth, int scaledHeight, + SplashBitmap *dest) { + Guchar *srcBuf, *lineBuf1, *lineBuf2, *alphaSrcBuf, *alphaLineBuf1, *alphaLineBuf2; + Guint pix[splashMaxColorComps]; + Guchar *destPtr0, *destPtr, *destAlphaPtr0, *destAlphaPtr; + int i; + + srcBuf = (Guchar *)gmallocn(srcWidth+1, nComps); // + 1 pixel of padding + lineBuf1 = (Guchar *)gmallocn(scaledWidth, nComps); + lineBuf2 = (Guchar *)gmallocn(scaledWidth, nComps); + if (srcAlpha) { + alphaSrcBuf = (Guchar *)gmalloc(srcWidth+1); // + 1 pixel of padding + alphaLineBuf1 = (Guchar *)gmalloc(scaledWidth); + alphaLineBuf2 = (Guchar *)gmalloc(scaledWidth); + } else { + alphaSrcBuf = NULL; + alphaLineBuf1 = NULL; + alphaLineBuf2 = NULL; + } + + double ySrc = 0.0; + double yStep = (double)srcHeight/scaledHeight; + double yFrac, yInt; + int currentSrcRow = -1; + (*src)(srcData, srcBuf, alphaSrcBuf); + expandRow(srcBuf, lineBuf2, srcWidth, scaledWidth, nComps); + if (srcAlpha) + expandRow(alphaSrcBuf, alphaLineBuf2, srcWidth, scaledWidth, 1); + + destPtr0 = dest->data; + destAlphaPtr0 = dest->alpha; + for (int y = 0; y < scaledHeight; y++) { + yFrac = modf(ySrc, &yInt); + if ((int)yInt > currentSrcRow) { + currentSrcRow++; + memcpy(lineBuf1, lineBuf2, scaledWidth * nComps); + if (srcAlpha) + memcpy(alphaLineBuf1, alphaLineBuf2, scaledWidth); + if (currentSrcRow < srcHeight) { + (*src)(srcData, srcBuf, alphaSrcBuf); + expandRow(srcBuf, lineBuf2, srcWidth, scaledWidth, nComps); + if (srcAlpha) + expandRow(alphaSrcBuf, alphaLineBuf2, srcWidth, scaledWidth, 1); + } + } + + for (int x = 0; x < scaledWidth; ++x) { + for (i = 0; i < nComps; ++i) { + pix[i] = lineBuf1[x*nComps + i]*(1.0 - yFrac) + lineBuf2[x*nComps + i]*yFrac; + } + + destPtr = destPtr0 + (y * scaledWidth + x) * nComps; + switch (srcMode) { + case splashModeMono1: // mono1 is not allowed + break; + case splashModeMono8: + *destPtr++ = (Guchar)pix[0]; + break; + case splashModeRGB8: + *destPtr++ = (Guchar)pix[0]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[2]; + break; + case splashModeXBGR8: + *destPtr++ = (Guchar)pix[2]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[0]; + *destPtr++ = (Guchar)255; + break; + case splashModeBGR8: + *destPtr++ = (Guchar)pix[2]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[0]; + break; +#if SPLASH_CMYK + case splashModeCMYK8: + *destPtr++ = (Guchar)pix[0]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[2]; + *destPtr++ = (Guchar)pix[3]; + break; + case splashModeDeviceN8: + for (int cp = 0; cp < SPOT_NCOMPS+4; cp++) + *destPtr++ = (Guchar)pix[cp]; + break; +#endif + } + + if (srcAlpha) { + destAlphaPtr = destAlphaPtr0 + y*scaledWidth + x; + *destAlphaPtr = alphaLineBuf1[x]*(1.0 - yFrac) + alphaLineBuf2[x]*yFrac; + } + } + + ySrc += yStep; + } + + gfree(alphaSrcBuf); + gfree(alphaLineBuf1); + gfree(alphaLineBuf2); + gfree(srcBuf); + gfree(lineBuf1); + gfree(lineBuf2); +} +","@@ -2955,7 +2955,7 @@ void Splash::arbitraryTransformMask(SplashImageMaskSource src, void *srcData, + scaledMask = scaleMask(src, srcData, srcWidth, srcHeight, + scaledWidth, scaledHeight); + if (scaledMask->data == NULL) { +- error(errInternal, -1, ""scaledMask->data is NULL in Splash::scaleMaskYuXu""); ++ error(errInternal, -1, ""scaledMask->data is NULL in Splash::arbitraryTransformMask""); + delete scaledMask; + return; + } +@@ -3461,11 +3461,15 @@ void Splash::blitMask(SplashBitmap *src, int xDest, int yDest, + + w = src->getWidth(); + h = src->getHeight(); ++ p = src->getDataPtr(); ++ if (p == NULL) { ++ error(errInternal, -1, ""src->getDataPtr() is NULL in Splash::blitMask""); ++ return; ++ } + if (vectorAntialias && clipRes != splashClipAllInside) { + pipeInit(&pipe, xDest, yDest, state->fillPattern, NULL, + (Guchar)splashRound(state->fillAlpha * 255), gTrue, gFalse); + drawAAPixelInit(); +- p = src->getDataPtr(); + for (y = 0; y < h; ++y) { + for (x = 0; x < w; ++x) { + pipe.shape = *p++; +@@ -3475,7 +3479,6 @@ void Splash::blitMask(SplashBitmap *src, int xDest, int yDest, + } else { + pipeInit(&pipe, xDest, yDest, state->fillPattern, NULL, + (Guchar)splashRound(state->fillAlpha * 255), gTrue, gFalse); +- p = src->getDataPtr(); + if (clipRes == splashClipAllInside) { + for (y = 0; y < h; ++y) { + pipeSetXY(&pipe, xDest, yDest + y);",1134,1465,2048 +18334," static MagickBooleanType ReadPSDChannelPixels(Image *image, + const size_t channels,const size_t row,const ssize_t type, + const unsigned char *pixels,ExceptionInfo *exception) +{ + Quantum + pixel; + + register const unsigned char + *p; + + register Quantum + *q; + + register ssize_t + x; + + size_t + packet_size; + + unsigned short + nibble; + + p=pixels; + q=GetAuthenticPixels(image,0,row,image->columns,1,exception); + if (q == (Quantum *) NULL) + return MagickFalse; + packet_size=GetPSDPacketSize(image); + for (x=0; x < (ssize_t) image->columns; x++) + { + if (packet_size == 1) + pixel=ScaleCharToQuantum(*p++); + else + { + p=PushShortPixel(MSBEndian,p,&nibble); + pixel=ScaleShortToQuantum(nibble); + } + switch (type) + { + case -1: + { + SetPixelAlpha(image,pixel,q); + break; + } + case -2: + case 0: + { + SetPixelRed(image,pixel,q); + if (channels == 1 || type == -2) + SetPixelGray(image,pixel,q); + if (image->storage_class == PseudoClass) + { + if (packet_size == 1) + SetPixelIndex(image,ScaleQuantumToChar(pixel),q); + else + SetPixelIndex(image,ScaleQuantumToShort(pixel),q); + SetPixelViaPixelInfo(image,image->colormap+(ssize_t) + ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q); + if (image->depth == 1) + { + ssize_t + bit, + number_bits; + number_bits=image->columns-x; + if (number_bits > 8) + number_bits=8; + for (bit=0; bit < number_bits; bit++) + { + SetPixelIndex(image,(((unsigned char) pixel) & + (0x01 << (7-bit))) != 0 ? 0 : 255,q); + SetPixelViaPixelInfo(image,image->colormap+(ssize_t) + ConstrainColormapIndex(image,GetPixelIndex(image,q), + exception),q); + q+=GetPixelChannels(image); + x++; + } + x--; + continue; + } + } + break; + } + case 1: + { + if (image->storage_class == PseudoClass) + SetPixelAlpha(image,pixel,q); + else + SetPixelGreen(image,pixel,q); + break; + } + case 2: + { + if (image->storage_class == PseudoClass) + SetPixelAlpha(image,pixel,q); + else + SetPixelBlue(image,pixel,q); + break; + } + case 3: + { + if (image->colorspace == CMYKColorspace) + SetPixelBlack(image,pixel,q); + else + if (image->alpha_trait != UndefinedPixelTrait) + SetPixelAlpha(image,pixel,q); + break; + } + case 4: + { + if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && + (channels > 3)) + break; + if (image->alpha_trait != UndefinedPixelTrait) + SetPixelAlpha(image,pixel,q); + break; + } + default: + break; + } + q+=GetPixelChannels(image); + } + return(SyncAuthenticPixels(image,exception)); + } +",1," static MagickBooleanType ReadPSDChannelPixels(Image *image, + const size_t channels,const size_t row,const ssize_t type, + const unsigned char *pixels,ExceptionInfo *exception) +{ + Quantum + pixel; + + register const unsigned char + *p; + + register Quantum + *q; + + register ssize_t + x; + + size_t + packet_size; + + unsigned short + nibble; + + p=pixels; + q=GetAuthenticPixels(image,0,row,image->columns,1,exception); + if (q == (Quantum *) NULL) + return MagickFalse; + packet_size=GetPSDPacketSize(image); + for (x=0; x < (ssize_t) image->columns; x++) + { + if (packet_size == 1) + pixel=ScaleCharToQuantum(*p++); + else + { + p=PushShortPixel(MSBEndian,p,&nibble); + pixel=ScaleShortToQuantum(nibble); + } + if (image->depth > 1) + { + SetPSDPixel(image,channels,type,packet_size,pixel,q,exception); + q+=GetPixelChannels(image); + } + else + { + ssize_t + bit, + number_bits; + + number_bits=image->columns-x; + if (number_bits > 8) + number_bits=8; + for (bit = 0; bit < number_bits; bit++) + { + SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) + & (0x01 << (7-bit))) != 0 ? 0 : 255,q,exception); + q+=GetPixelChannels(image); + x++; + } + if (x != image->columns) + x--; + continue; + } + } + return(SyncAuthenticPixels(image,exception)); + } +","@@ -764,6 +764,72 @@ static inline void ReversePSDString(Image *image,char *p,size_t length) + } + } + ++static inline void SetPSDPixel(Image *image,const size_t channels, ++ const ssize_t type,const size_t packet_size,const Quantum pixel,Quantum *q, ++ ExceptionInfo *exception) ++{ ++ if (image->storage_class == PseudoClass) ++ { ++ if (packet_size == 1) ++ SetPixelIndex(image,ScaleQuantumToChar(pixel),q); ++ else ++ SetPixelIndex(image,ScaleQuantumToShort(pixel),q); ++ SetPixelViaPixelInfo(image,image->colormap+(ssize_t) ++ ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q); ++ return; ++ } ++ switch (type) ++ { ++ case -1: ++ { ++ SetPixelAlpha(image, pixel,q); ++ break; ++ } ++ case -2: ++ case 0: ++ { ++ SetPixelRed(image,pixel,q); ++ if (channels == 1 || type == -2) ++ SetPixelGray(image,pixel,q); ++ break; ++ } ++ case 1: ++ { ++ if (image->storage_class == PseudoClass) ++ SetPixelAlpha(image,pixel,q); ++ else ++ SetPixelGreen(image,pixel,q); ++ break; ++ } ++ case 2: ++ { ++ if (image->storage_class == PseudoClass) ++ SetPixelAlpha(image,pixel,q); ++ else ++ SetPixelBlue(image,pixel,q); ++ break; ++ } ++ case 3: ++ { ++ if (image->colorspace == CMYKColorspace) ++ SetPixelBlack(image,pixel,q); ++ else ++ if (image->alpha_trait != UndefinedPixelTrait) ++ SetPixelAlpha(image,pixel,q); ++ break; ++ } ++ case 4: ++ { ++ if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && ++ (channels > 3)) ++ break; ++ if (image->alpha_trait != UndefinedPixelTrait) ++ SetPixelAlpha(image,pixel,q); ++ break; ++ } ++ } ++} ++ + static MagickBooleanType ReadPSDChannelPixels(Image *image, + const size_t channels,const size_t row,const ssize_t type, + const unsigned char *pixels,ExceptionInfo *exception) +@@ -800,90 +866,31 @@ static MagickBooleanType ReadPSDChannelPixels(Image *image, + p=PushShortPixel(MSBEndian,p,&nibble); + pixel=ScaleShortToQuantum(nibble); + } +- switch (type) +- { +- case -1: ++ if (image->depth > 1) + { +- SetPixelAlpha(image,pixel,q); +- break; ++ SetPSDPixel(image,channels,type,packet_size,pixel,q,exception); ++ q+=GetPixelChannels(image); + } +- case -2: +- case 0: +- { +- SetPixelRed(image,pixel,q); +- if (channels == 1 || type == -2) +- SetPixelGray(image,pixel,q); +- if (image->storage_class == PseudoClass) +- { +- if (packet_size == 1) +- SetPixelIndex(image,ScaleQuantumToChar(pixel),q); +- else +- SetPixelIndex(image,ScaleQuantumToShort(pixel),q); +- SetPixelViaPixelInfo(image,image->colormap+(ssize_t) +- ConstrainColormapIndex(image,GetPixelIndex(image,q),exception),q); +- if (image->depth == 1) +- { +- ssize_t +- bit, +- number_bits; +- +- number_bits=image->columns-x; +- if (number_bits > 8) +- number_bits=8; +- for (bit=0; bit < number_bits; bit++) +- { +- SetPixelIndex(image,(((unsigned char) pixel) & +- (0x01 << (7-bit))) != 0 ? 0 : 255,q); +- SetPixelViaPixelInfo(image,image->colormap+(ssize_t) +- ConstrainColormapIndex(image,GetPixelIndex(image,q), +- exception),q); +- q+=GetPixelChannels(image); +- x++; +- } +- x--; +- continue; +- } +- } +- break; +- } +- case 1: +- { +- if (image->storage_class == PseudoClass) +- SetPixelAlpha(image,pixel,q); +- else +- SetPixelGreen(image,pixel,q); +- break; +- } +- case 2: +- { +- if (image->storage_class == PseudoClass) +- SetPixelAlpha(image,pixel,q); +- else +- SetPixelBlue(image,pixel,q); +- break; +- } +- case 3: +- { +- if (image->colorspace == CMYKColorspace) +- SetPixelBlack(image,pixel,q); +- else +- if (image->alpha_trait != UndefinedPixelTrait) +- SetPixelAlpha(image,pixel,q); +- break; +- } +- case 4: ++ else + { +- if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && +- (channels > 3)) +- break; +- if (image->alpha_trait != UndefinedPixelTrait) +- SetPixelAlpha(image,pixel,q); +- break; ++ ssize_t ++ bit, ++ number_bits; ++ ++ number_bits=image->columns-x; ++ if (number_bits > 8) ++ number_bits=8; ++ for (bit = 0; bit < number_bits; bit++) ++ { ++ SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) ++ & (0x01 << (7-bit))) != 0 ? 0 : 255,q,exception); ++ q+=GetPixelChannels(image); ++ x++; ++ } ++ if (x != image->columns) ++ x--; ++ continue; + } +- default: +- break; +- } +- q+=GetPixelChannels(image); + } + return(SyncAuthenticPixels(image,exception)); + }",774,1105,2048 +4288,"static int md_seq_show(struct seq_file *seq, void *v) +{ + struct mddev *mddev = v; + sector_t sectors; + struct md_rdev *rdev; + + if (v == (void*)1) { + struct md_personality *pers; + seq_printf(seq, ""Personalities : ""); + spin_lock(&pers_lock); + list_for_each_entry(pers, &pers_list, list) + seq_printf(seq, ""[%s] "", pers->name); + + spin_unlock(&pers_lock); + seq_printf(seq, ""\n""); + seq->poll_event = atomic_read(&md_event_count); + return 0; + } + if (v == (void*)2) { + status_unused(seq); + return 0; + } + + spin_lock(&mddev->lock); + if (mddev->pers || mddev->raid_disks || !list_empty(&mddev->disks)) { + seq_printf(seq, ""%s : %sactive"", mdname(mddev), + mddev->pers ? """" : ""in""); + if (mddev->pers) { + if (mddev->ro==1) + seq_printf(seq, "" (read-only)""); + if (mddev->ro==2) + seq_printf(seq, "" (auto-read-only)""); + seq_printf(seq, "" %s"", mddev->pers->name); + } + + sectors = 0; + rcu_read_lock(); + rdev_for_each_rcu(rdev, mddev) { + char b[BDEVNAME_SIZE]; + seq_printf(seq, "" %s[%d]"", + bdevname(rdev->bdev,b), rdev->desc_nr); + if (test_bit(WriteMostly, &rdev->flags)) + seq_printf(seq, ""(W)""); + if (test_bit(Faulty, &rdev->flags)) { + seq_printf(seq, ""(F)""); + continue; + } + if (rdev->raid_disk < 0) + seq_printf(seq, ""(S)""); /* spare */ + if (test_bit(Replacement, &rdev->flags)) + seq_printf(seq, ""(R)""); + sectors += rdev->sectors; + } + rcu_read_unlock(); + + if (!list_empty(&mddev->disks)) { + if (mddev->pers) + seq_printf(seq, ""\n %llu blocks"", + (unsigned long long) + mddev->array_sectors / 2); + else + seq_printf(seq, ""\n %llu blocks"", + (unsigned long long)sectors / 2); + } + if (mddev->persistent) { + if (mddev->major_version != 0 || + mddev->minor_version != 90) { + seq_printf(seq,"" super %d.%d"", + mddev->major_version, + mddev->minor_version); + } + } else if (mddev->external) + seq_printf(seq, "" super external:%s"", + mddev->metadata_type); + else + seq_printf(seq, "" super non-persistent""); + + if (mddev->pers) { + mddev->pers->status(seq, mddev); + seq_printf(seq, ""\n ""); + if (mddev->pers->sync_request) { + if (mddev->curr_resync > 2) { + status_resync(seq, mddev); + seq_printf(seq, ""\n ""); + } else if (mddev->curr_resync >= 1) + seq_printf(seq, ""\tresync=DELAYED\n ""); + else if (mddev->recovery_cp < MaxSector) + seq_printf(seq, ""\tresync=PENDING\n ""); + } + } else + seq_printf(seq, ""\n ""); + + bitmap_status(seq, mddev->bitmap); + + seq_printf(seq, ""\n""); + } + spin_unlock(&mddev->lock); + + return 0; +} +",0,"static int md_seq_show(struct seq_file *seq, void *v) +{ + struct mddev *mddev = v; + sector_t sectors; + struct md_rdev *rdev; + + if (v == (void*)1) { + struct md_personality *pers; + seq_printf(seq, ""Personalities : ""); + spin_lock(&pers_lock); + list_for_each_entry(pers, &pers_list, list) + seq_printf(seq, ""[%s] "", pers->name); + + spin_unlock(&pers_lock); + seq_printf(seq, ""\n""); + seq->poll_event = atomic_read(&md_event_count); + return 0; + } + if (v == (void*)2) { + status_unused(seq); + return 0; + } + + spin_lock(&mddev->lock); + if (mddev->pers || mddev->raid_disks || !list_empty(&mddev->disks)) { + seq_printf(seq, ""%s : %sactive"", mdname(mddev), + mddev->pers ? """" : ""in""); + if (mddev->pers) { + if (mddev->ro==1) + seq_printf(seq, "" (read-only)""); + if (mddev->ro==2) + seq_printf(seq, "" (auto-read-only)""); + seq_printf(seq, "" %s"", mddev->pers->name); + } + + sectors = 0; + rcu_read_lock(); + rdev_for_each_rcu(rdev, mddev) { + char b[BDEVNAME_SIZE]; + seq_printf(seq, "" %s[%d]"", + bdevname(rdev->bdev,b), rdev->desc_nr); + if (test_bit(WriteMostly, &rdev->flags)) + seq_printf(seq, ""(W)""); + if (test_bit(Faulty, &rdev->flags)) { + seq_printf(seq, ""(F)""); + continue; + } + if (rdev->raid_disk < 0) + seq_printf(seq, ""(S)""); /* spare */ + if (test_bit(Replacement, &rdev->flags)) + seq_printf(seq, ""(R)""); + sectors += rdev->sectors; + } + rcu_read_unlock(); + + if (!list_empty(&mddev->disks)) { + if (mddev->pers) + seq_printf(seq, ""\n %llu blocks"", + (unsigned long long) + mddev->array_sectors / 2); + else + seq_printf(seq, ""\n %llu blocks"", + (unsigned long long)sectors / 2); + } + if (mddev->persistent) { + if (mddev->major_version != 0 || + mddev->minor_version != 90) { + seq_printf(seq,"" super %d.%d"", + mddev->major_version, + mddev->minor_version); + } + } else if (mddev->external) + seq_printf(seq, "" super external:%s"", + mddev->metadata_type); + else + seq_printf(seq, "" super non-persistent""); + + if (mddev->pers) { + mddev->pers->status(seq, mddev); + seq_printf(seq, ""\n ""); + if (mddev->pers->sync_request) { + if (mddev->curr_resync > 2) { + status_resync(seq, mddev); + seq_printf(seq, ""\n ""); + } else if (mddev->curr_resync >= 1) + seq_printf(seq, ""\tresync=DELAYED\n ""); + else if (mddev->recovery_cp < MaxSector) + seq_printf(seq, ""\tresync=PENDING\n ""); + } + } else + seq_printf(seq, ""\n ""); + + bitmap_status(seq, mddev->bitmap); + + seq_printf(seq, ""\n""); + } + spin_unlock(&mddev->lock); + + return 0; +} +","@@ -5759,7 +5759,7 @@ static int get_bitmap_file(struct mddev *mddev, void __user * arg) + char *ptr; + int err; + +- file = kmalloc(sizeof(*file), GFP_NOIO); ++ file = kzalloc(sizeof(*file), GFP_NOIO); + if (!file) + return -ENOMEM; + ",838,1169,2048 +4104,"static int llc_ui_bind(struct socket *sock, struct sockaddr *uaddr, int addrlen) +{ + struct sockaddr_llc *addr = (struct sockaddr_llc *)uaddr; + struct sock *sk = sock->sk; + struct llc_sock *llc = llc_sk(sk); + struct llc_sap *sap; + int rc = -EINVAL; + + dprintk(""%s: binding %02X\n"", __func__, addr->sllc_sap); + if (unlikely(!sock_flag(sk, SOCK_ZAPPED) || addrlen != sizeof(*addr))) + goto out; + rc = -EAFNOSUPPORT; + if (unlikely(addr->sllc_family != AF_LLC)) + goto out; + rc = -ENODEV; + rcu_read_lock(); + if (sk->sk_bound_dev_if) { + llc->dev = dev_get_by_index_rcu(&init_net, sk->sk_bound_dev_if); + if (llc->dev) { + if (!addr->sllc_arphrd) + addr->sllc_arphrd = llc->dev->type; + if (is_zero_ether_addr(addr->sllc_mac)) + memcpy(addr->sllc_mac, llc->dev->dev_addr, + IFHWADDRLEN); + if (addr->sllc_arphrd != llc->dev->type || + !ether_addr_equal(addr->sllc_mac, + llc->dev->dev_addr)) { + rc = -EINVAL; + llc->dev = NULL; + } + } + } else + llc->dev = dev_getbyhwaddr_rcu(&init_net, addr->sllc_arphrd, + addr->sllc_mac); + if (llc->dev) + dev_hold(llc->dev); + rcu_read_unlock(); + if (!llc->dev) + goto out; + if (!addr->sllc_sap) { + rc = -EUSERS; + addr->sllc_sap = llc_ui_autoport(); + if (!addr->sllc_sap) + goto out; + } + sap = llc_sap_find(addr->sllc_sap); + if (!sap) { + sap = llc_sap_open(addr->sllc_sap, NULL); + rc = -EBUSY; /* some other network layer is using the sap */ + if (!sap) + goto out; + } else { + struct llc_addr laddr, daddr; + struct sock *ask; + + memset(&laddr, 0, sizeof(laddr)); + memset(&daddr, 0, sizeof(daddr)); + /* + * FIXME: check if the address is multicast, + * only SOCK_DGRAM can do this. + */ + memcpy(laddr.mac, addr->sllc_mac, IFHWADDRLEN); + laddr.lsap = addr->sllc_sap; + rc = -EADDRINUSE; /* mac + sap clash. */ + ask = llc_lookup_established(sap, &daddr, &laddr); + if (ask) { + sock_put(ask); + goto out_put; + } + } + llc->laddr.lsap = addr->sllc_sap; + memcpy(llc->laddr.mac, addr->sllc_mac, IFHWADDRLEN); + memcpy(&llc->addr, addr, sizeof(llc->addr)); + /* assign new connection to its SAP */ + llc_sap_add_socket(sap, sk); + sock_reset_flag(sk, SOCK_ZAPPED); + rc = 0; +out_put: + llc_sap_put(sap); +out: + return rc; +} +",0,"static int llc_ui_bind(struct socket *sock, struct sockaddr *uaddr, int addrlen) +{ + struct sockaddr_llc *addr = (struct sockaddr_llc *)uaddr; + struct sock *sk = sock->sk; + struct llc_sock *llc = llc_sk(sk); + struct llc_sap *sap; + int rc = -EINVAL; + + dprintk(""%s: binding %02X\n"", __func__, addr->sllc_sap); + if (unlikely(!sock_flag(sk, SOCK_ZAPPED) || addrlen != sizeof(*addr))) + goto out; + rc = -EAFNOSUPPORT; + if (unlikely(addr->sllc_family != AF_LLC)) + goto out; + rc = -ENODEV; + rcu_read_lock(); + if (sk->sk_bound_dev_if) { + llc->dev = dev_get_by_index_rcu(&init_net, sk->sk_bound_dev_if); + if (llc->dev) { + if (!addr->sllc_arphrd) + addr->sllc_arphrd = llc->dev->type; + if (is_zero_ether_addr(addr->sllc_mac)) + memcpy(addr->sllc_mac, llc->dev->dev_addr, + IFHWADDRLEN); + if (addr->sllc_arphrd != llc->dev->type || + !ether_addr_equal(addr->sllc_mac, + llc->dev->dev_addr)) { + rc = -EINVAL; + llc->dev = NULL; + } + } + } else + llc->dev = dev_getbyhwaddr_rcu(&init_net, addr->sllc_arphrd, + addr->sllc_mac); + if (llc->dev) + dev_hold(llc->dev); + rcu_read_unlock(); + if (!llc->dev) + goto out; + if (!addr->sllc_sap) { + rc = -EUSERS; + addr->sllc_sap = llc_ui_autoport(); + if (!addr->sllc_sap) + goto out; + } + sap = llc_sap_find(addr->sllc_sap); + if (!sap) { + sap = llc_sap_open(addr->sllc_sap, NULL); + rc = -EBUSY; /* some other network layer is using the sap */ + if (!sap) + goto out; + } else { + struct llc_addr laddr, daddr; + struct sock *ask; + + memset(&laddr, 0, sizeof(laddr)); + memset(&daddr, 0, sizeof(daddr)); + /* + * FIXME: check if the address is multicast, + * only SOCK_DGRAM can do this. + */ + memcpy(laddr.mac, addr->sllc_mac, IFHWADDRLEN); + laddr.lsap = addr->sllc_sap; + rc = -EADDRINUSE; /* mac + sap clash. */ + ask = llc_lookup_established(sap, &daddr, &laddr); + if (ask) { + sock_put(ask); + goto out_put; + } + } + llc->laddr.lsap = addr->sllc_sap; + memcpy(llc->laddr.mac, addr->sllc_mac, IFHWADDRLEN); + memcpy(&llc->addr, addr, sizeof(llc->addr)); + /* assign new connection to its SAP */ + llc_sap_add_socket(sap, sk); + sock_reset_flag(sk, SOCK_ZAPPED); + rc = 0; +out_put: + llc_sap_put(sap); +out: + return rc; +} +","@@ -720,8 +720,6 @@ static int llc_ui_recvmsg(struct kiocb *iocb, struct socket *sock, + int target; /* Read at least this many bytes */ + long timeo; + +- msg->msg_namelen = 0; +- + lock_sock(sk); + copied = -ENOTCONN; + if (unlikely(sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_LISTEN))",784,1115,2048 +18151,"vc4_get_bcl(struct drm_device *dev, struct vc4_exec_info *exec) +{ + struct drm_vc4_submit_cl *args = exec->args; + void *temp = NULL; + void *bin; + int ret = 0; + uint32_t bin_offset = 0; + uint32_t shader_rec_offset = roundup(bin_offset + args->bin_cl_size, + 16); + uint32_t uniforms_offset = shader_rec_offset + args->shader_rec_size; + uint32_t exec_size = uniforms_offset + args->uniforms_size; + uint32_t temp_size = exec_size + (sizeof(struct vc4_shader_state) * + args->shader_rec_count); + struct vc4_bo *bo; + + if (shader_rec_offset < args->bin_cl_size || + uniforms_offset < shader_rec_offset || + exec_size < uniforms_offset || + args->shader_rec_count >= (UINT_MAX / + sizeof(struct vc4_shader_state)) || + temp_size < exec_size) { + DRM_ERROR(""overflow in exec arguments\n""); + goto fail; + } + + /* Allocate space where we'll store the copied in user command lists + * and shader records. + * + * We don't just copy directly into the BOs because we need to + * read the contents back for validation, and I think the + * bo->vaddr is uncached access. + */ + temp = drm_malloc_ab(temp_size, 1); + if (!temp) { + DRM_ERROR(""Failed to allocate storage for copying "" + ""in bin/render CLs.\n""); + ret = -ENOMEM; + goto fail; + } + bin = temp + bin_offset; + exec->shader_rec_u = temp + shader_rec_offset; + exec->uniforms_u = temp + uniforms_offset; + exec->shader_state = temp + exec_size; + exec->shader_state_size = args->shader_rec_count; + + if (copy_from_user(bin, + (void __user *)(uintptr_t)args->bin_cl, + args->bin_cl_size)) { + ret = -EFAULT; + goto fail; + } + + if (copy_from_user(exec->shader_rec_u, + (void __user *)(uintptr_t)args->shader_rec, + args->shader_rec_size)) { + ret = -EFAULT; + goto fail; + } + + if (copy_from_user(exec->uniforms_u, + (void __user *)(uintptr_t)args->uniforms, + args->uniforms_size)) { + ret = -EFAULT; + goto fail; + } + + bo = vc4_bo_create(dev, exec_size, true); + if (IS_ERR(bo)) { + DRM_ERROR(""Couldn't allocate BO for binning\n""); + ret = PTR_ERR(bo); + goto fail; + } + exec->exec_bo = &bo->base; + + list_add_tail(&to_vc4_bo(&exec->exec_bo->base)->unref_head, + &exec->unref_list); + + exec->ct0ca = exec->exec_bo->paddr + bin_offset; + + exec->bin_u = bin; + + exec->shader_rec_v = exec->exec_bo->vaddr + shader_rec_offset; + exec->shader_rec_p = exec->exec_bo->paddr + shader_rec_offset; + exec->shader_rec_size = args->shader_rec_size; + + exec->uniforms_v = exec->exec_bo->vaddr + uniforms_offset; + exec->uniforms_p = exec->exec_bo->paddr + uniforms_offset; + exec->uniforms_size = args->uniforms_size; + + ret = vc4_validate_bin_cl(dev, + exec->exec_bo->vaddr + bin_offset, + bin, + exec); + if (ret) + goto fail; + + ret = vc4_validate_shader_recs(dev, exec); + if (ret) + goto fail; + + /* Block waiting on any previous rendering into the CS's VBO, + * IB, or textures, so that pixels are actually written by the + * time we try to read them. + */ + ret = vc4_wait_for_seqno(dev, exec->bin_dep_seqno, ~0ull, true); + +fail: + drm_free_large(temp); + return ret; +} +",1,"vc4_get_bcl(struct drm_device *dev, struct vc4_exec_info *exec) +{ + struct drm_vc4_submit_cl *args = exec->args; + void *temp = NULL; + void *bin; + int ret = 0; + uint32_t bin_offset = 0; + uint32_t shader_rec_offset = roundup(bin_offset + args->bin_cl_size, + 16); + uint32_t uniforms_offset = shader_rec_offset + args->shader_rec_size; + uint32_t exec_size = uniforms_offset + args->uniforms_size; + uint32_t temp_size = exec_size + (sizeof(struct vc4_shader_state) * + args->shader_rec_count); + struct vc4_bo *bo; + + if (shader_rec_offset < args->bin_cl_size || + uniforms_offset < shader_rec_offset || + exec_size < uniforms_offset || + args->shader_rec_count >= (UINT_MAX / + sizeof(struct vc4_shader_state)) || + temp_size < exec_size) { + DRM_ERROR(""overflow in exec arguments\n""); + ret = -EINVAL; + goto fail; + } + + /* Allocate space where we'll store the copied in user command lists + * and shader records. + * + * We don't just copy directly into the BOs because we need to + * read the contents back for validation, and I think the + * bo->vaddr is uncached access. + */ + temp = drm_malloc_ab(temp_size, 1); + if (!temp) { + DRM_ERROR(""Failed to allocate storage for copying "" + ""in bin/render CLs.\n""); + ret = -ENOMEM; + goto fail; + } + bin = temp + bin_offset; + exec->shader_rec_u = temp + shader_rec_offset; + exec->uniforms_u = temp + uniforms_offset; + exec->shader_state = temp + exec_size; + exec->shader_state_size = args->shader_rec_count; + + if (copy_from_user(bin, + (void __user *)(uintptr_t)args->bin_cl, + args->bin_cl_size)) { + ret = -EFAULT; + goto fail; + } + + if (copy_from_user(exec->shader_rec_u, + (void __user *)(uintptr_t)args->shader_rec, + args->shader_rec_size)) { + ret = -EFAULT; + goto fail; + } + + if (copy_from_user(exec->uniforms_u, + (void __user *)(uintptr_t)args->uniforms, + args->uniforms_size)) { + ret = -EFAULT; + goto fail; + } + + bo = vc4_bo_create(dev, exec_size, true); + if (IS_ERR(bo)) { + DRM_ERROR(""Couldn't allocate BO for binning\n""); + ret = PTR_ERR(bo); + goto fail; + } + exec->exec_bo = &bo->base; + + list_add_tail(&to_vc4_bo(&exec->exec_bo->base)->unref_head, + &exec->unref_list); + + exec->ct0ca = exec->exec_bo->paddr + bin_offset; + + exec->bin_u = bin; + + exec->shader_rec_v = exec->exec_bo->vaddr + shader_rec_offset; + exec->shader_rec_p = exec->exec_bo->paddr + shader_rec_offset; + exec->shader_rec_size = args->shader_rec_size; + + exec->uniforms_v = exec->exec_bo->vaddr + uniforms_offset; + exec->uniforms_p = exec->exec_bo->paddr + uniforms_offset; + exec->uniforms_size = args->uniforms_size; + + ret = vc4_validate_bin_cl(dev, + exec->exec_bo->vaddr + bin_offset, + bin, + exec); + if (ret) + goto fail; + + ret = vc4_validate_shader_recs(dev, exec); + if (ret) + goto fail; + + /* Block waiting on any previous rendering into the CS's VBO, + * IB, or textures, so that pixels are actually written by the + * time we try to read them. + */ + ret = vc4_wait_for_seqno(dev, exec->bin_dep_seqno, ~0ull, true); + +fail: + drm_free_large(temp); + return ret; +} +","@@ -601,6 +601,7 @@ vc4_get_bcl(struct drm_device *dev, struct vc4_exec_info *exec) + sizeof(struct vc4_shader_state)) || + temp_size < exec_size) { + DRM_ERROR(""overflow in exec arguments\n""); ++ ret = -EINVAL; + goto fail; + } + ",866,1197,2048 +18338,"tChecksumCheckResult ParaNdis_CheckRxChecksum( + PARANDIS_ADAPTER *pContext, + ULONG virtioFlags, + tCompletePhysicalAddress *pPacketPages, + ULONG ulPacketLength, + ULONG ulDataOffset) + { + tOffloadSettingsFlags f = pContext->Offload.flags; + tChecksumCheckResult res; + tTcpIpPacketParsingResult ppr; + ULONG flagsToCalculate = 0; + res.value = 0; + + + if (f.fRxIPChecksum) flagsToCalculate |= pcrIpChecksum; // check only + + if (!(virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID)) + { + if (virtioFlags & VIRTIO_NET_HDR_F_NEEDS_CSUM) + { + flagsToCalculate |= pcrFixXxpChecksum | pcrTcpChecksum | pcrUdpChecksum; + } + else + { + if (f.fRxTCPChecksum) flagsToCalculate |= pcrTcpV4Checksum; + if (f.fRxUDPChecksum) flagsToCalculate |= pcrUdpV4Checksum; + if (f.fRxTCPv6Checksum) flagsToCalculate |= pcrTcpV6Checksum; + if (f.fRxUDPv6Checksum) flagsToCalculate |= pcrUdpV6Checksum; + } + } + + ppr = ParaNdis_CheckSumVerify(pPacketPages, ulPacketLength - ETH_HEADER_SIZE, ulDataOffset + ETH_HEADER_SIZE, flagsToCalculate, __FUNCTION__); + + if (ppr.ipCheckSum == ppresIPTooShort || ppr.xxpStatus == ppresXxpIncomplete) + { + res.flags.IpOK = FALSE; + res.flags.IpFailed = TRUE; + return res; + } + + if (virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID) + { + pContext->extraStatistics.framesRxCSHwOK++; + ppr.xxpCheckSum = ppresCSOK; + } + + if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment) + { + if (f.fRxIPChecksum) + { + res.flags.IpOK = ppr.ipCheckSum == ppresCSOK; + res.flags.IpFailed = ppr.ipCheckSum == ppresCSBad; + } + if(ppr.xxpStatus == ppresXxpKnown) + { + if(ppr.TcpUdp == ppresIsTCP) /* TCP */ + { + if (f.fRxTCPChecksum) + { + res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; + res.flags.TcpFailed = !res.flags.TcpOK; + } + } + else /* UDP */ + { + if (f.fRxUDPChecksum) + { + res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; + res.flags.UdpFailed = !res.flags.UdpOK; + } + } + } + } + else if (ppr.ipStatus == ppresIPV6) + { + if(ppr.xxpStatus == ppresXxpKnown) + { + if(ppr.TcpUdp == ppresIsTCP) /* TCP */ + { + if (f.fRxTCPv6Checksum) + { + res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; + res.flags.TcpFailed = !res.flags.TcpOK; + } + } + else /* UDP */ + { + if (f.fRxUDPv6Checksum) + { + res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; + res.flags.UdpFailed = !res.flags.UdpOK; + } + } + } + } + + return res; +} +",1,"tChecksumCheckResult ParaNdis_CheckRxChecksum( + PARANDIS_ADAPTER *pContext, + ULONG virtioFlags, + tCompletePhysicalAddress *pPacketPages, + ULONG ulPacketLength, + ULONG ulDataOffset, + BOOLEAN verifyLength) + { + tOffloadSettingsFlags f = pContext->Offload.flags; + tChecksumCheckResult res; + tTcpIpPacketParsingResult ppr; + ULONG flagsToCalculate = 0; + res.value = 0; + + + if (f.fRxIPChecksum) flagsToCalculate |= pcrIpChecksum; // check only + + if (!(virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID)) + { + if (virtioFlags & VIRTIO_NET_HDR_F_NEEDS_CSUM) + { + flagsToCalculate |= pcrFixXxpChecksum | pcrTcpChecksum | pcrUdpChecksum; + } + else + { + if (f.fRxTCPChecksum) flagsToCalculate |= pcrTcpV4Checksum; + if (f.fRxUDPChecksum) flagsToCalculate |= pcrUdpV4Checksum; + if (f.fRxTCPv6Checksum) flagsToCalculate |= pcrTcpV6Checksum; + if (f.fRxUDPv6Checksum) flagsToCalculate |= pcrUdpV6Checksum; + } + } + + ppr = ParaNdis_CheckSumVerify(pPacketPages, ulPacketLength - ETH_HEADER_SIZE, ulDataOffset + ETH_HEADER_SIZE, flagsToCalculate, + verifyLength, __FUNCTION__); + + if (ppr.ipCheckSum == ppresIPTooShort || ppr.xxpStatus == ppresXxpIncomplete) + { + res.flags.IpOK = FALSE; + res.flags.IpFailed = TRUE; + return res; + } + + if (virtioFlags & VIRTIO_NET_HDR_F_DATA_VALID) + { + pContext->extraStatistics.framesRxCSHwOK++; + ppr.xxpCheckSum = ppresCSOK; + } + + if (ppr.ipStatus == ppresIPV4 && !ppr.IsFragment) + { + if (f.fRxIPChecksum) + { + res.flags.IpOK = ppr.ipCheckSum == ppresCSOK; + res.flags.IpFailed = ppr.ipCheckSum == ppresCSBad; + } + if(ppr.xxpStatus == ppresXxpKnown) + { + if(ppr.TcpUdp == ppresIsTCP) /* TCP */ + { + if (f.fRxTCPChecksum) + { + res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; + res.flags.TcpFailed = !res.flags.TcpOK; + } + } + else /* UDP */ + { + if (f.fRxUDPChecksum) + { + res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; + res.flags.UdpFailed = !res.flags.UdpOK; + } + } + } + } + else if (ppr.ipStatus == ppresIPV6) + { + if(ppr.xxpStatus == ppresXxpKnown) + { + if(ppr.TcpUdp == ppresIsTCP) /* TCP */ + { + if (f.fRxTCPv6Checksum) + { + res.flags.TcpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; + res.flags.TcpFailed = !res.flags.TcpOK; + } + } + else /* UDP */ + { + if (f.fRxUDPv6Checksum) + { + res.flags.UdpOK = ppr.xxpCheckSum == ppresCSOK || ppr.fixedXxpCS; + res.flags.UdpFailed = !res.flags.UdpOK; + } + } + } + } + + return res; +} +","@@ -2219,7 +2219,8 @@ tChecksumCheckResult ParaNdis_CheckRxChecksum( + ULONG virtioFlags, + tCompletePhysicalAddress *pPacketPages, + ULONG ulPacketLength, +- ULONG ulDataOffset) ++ ULONG ulDataOffset, ++ BOOLEAN verifyLength) + { + tOffloadSettingsFlags f = pContext->Offload.flags; + tChecksumCheckResult res; +@@ -2247,7 +2248,8 @@ tChecksumCheckResult ParaNdis_CheckRxChecksum( + } + } + +- ppr = ParaNdis_CheckSumVerify(pPacketPages, ulPacketLength - ETH_HEADER_SIZE, ulDataOffset + ETH_HEADER_SIZE, flagsToCalculate, __FUNCTION__); ++ ppr = ParaNdis_CheckSumVerify(pPacketPages, ulPacketLength - ETH_HEADER_SIZE, ulDataOffset + ETH_HEADER_SIZE, flagsToCalculate, ++ verifyLength, __FUNCTION__); + + if (ppr.ipCheckSum == ppresIPTooShort || ppr.xxpStatus == ppresXxpIncomplete) + {",826,1157,2048 +18803,"void SoftAACEncoder2::onQueueFilled(OMX_U32 /* portIndex */) { + if (mSignalledError) { + return; + } + + List &inQueue = getPortQueue(0); + List &outQueue = getPortQueue(1); + + if (!mSentCodecSpecificData) { + + if (outQueue.empty()) { + return; + } + + if (AACENC_OK != aacEncEncode(mAACEncoder, NULL, NULL, NULL, NULL)) { + ALOGE(""Unable to initialize encoder for profile / sample-rate / bit-rate / channels""); + notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); + mSignalledError = true; + return; + } + + OMX_U32 actualBitRate = aacEncoder_GetParam(mAACEncoder, AACENC_BITRATE); + if (mBitRate != actualBitRate) { + ALOGW(""Requested bitrate %u unsupported, using %u"", mBitRate, actualBitRate); + } + + AACENC_InfoStruct encInfo; + if (AACENC_OK != aacEncInfo(mAACEncoder, &encInfo)) { + ALOGE(""Failed to get AAC encoder info""); + notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); + mSignalledError = true; + return; + } + + + BufferInfo *outInfo = *outQueue.begin(); + OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; + outHeader->nFilledLen = encInfo.confSize; + outHeader->nFlags = OMX_BUFFERFLAG_CODECCONFIG; + + uint8_t *out = outHeader->pBuffer + outHeader->nOffset; + memcpy(out, encInfo.confBuf, encInfo.confSize); + + outQueue.erase(outQueue.begin()); + outInfo->mOwnedByUs = false; + notifyFillBufferDone(outHeader); + + mSentCodecSpecificData = true; + } + + size_t numBytesPerInputFrame = + mNumChannels * kNumSamplesPerFrame * sizeof(int16_t); + + if (mAACProfile == OMX_AUDIO_AACObjectELD && numBytesPerInputFrame > 512) { + numBytesPerInputFrame = 512; + } + + for (;;) { + + while (mInputSize < numBytesPerInputFrame) { + + if (mSawInputEOS || inQueue.empty()) { + return; + } + + BufferInfo *inInfo = *inQueue.begin(); + OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; + + const void *inData = inHeader->pBuffer + inHeader->nOffset; + + size_t copy = numBytesPerInputFrame - mInputSize; + if (copy > inHeader->nFilledLen) { + copy = inHeader->nFilledLen; + } + + if (mInputFrame == NULL) { + mInputFrame = new int16_t[numBytesPerInputFrame / sizeof(int16_t)]; + } + + if (mInputSize == 0) { + mInputTimeUs = inHeader->nTimeStamp; + } + + memcpy((uint8_t *)mInputFrame + mInputSize, inData, copy); + mInputSize += copy; + + inHeader->nOffset += copy; + inHeader->nFilledLen -= copy; + + inHeader->nTimeStamp += + (copy * 1000000ll / mSampleRate) + / (mNumChannels * sizeof(int16_t)); + + if (inHeader->nFilledLen == 0) { + if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { + mSawInputEOS = true; + + memset((uint8_t *)mInputFrame + mInputSize, + 0, + numBytesPerInputFrame - mInputSize); + + mInputSize = numBytesPerInputFrame; + } + + inQueue.erase(inQueue.begin()); + inInfo->mOwnedByUs = false; + notifyEmptyBufferDone(inHeader); + + inData = NULL; + inHeader = NULL; + inInfo = NULL; + } + } + + + if (outQueue.empty()) { + return; + } + + BufferInfo *outInfo = *outQueue.begin(); + OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; + + uint8_t *outPtr = (uint8_t *)outHeader->pBuffer + outHeader->nOffset; + size_t outAvailable = outHeader->nAllocLen - outHeader->nOffset; + + AACENC_InArgs inargs; + AACENC_OutArgs outargs; + memset(&inargs, 0, sizeof(inargs)); + memset(&outargs, 0, sizeof(outargs)); + inargs.numInSamples = numBytesPerInputFrame / sizeof(int16_t); + + void* inBuffer[] = { (unsigned char *)mInputFrame }; + INT inBufferIds[] = { IN_AUDIO_DATA }; + INT inBufferSize[] = { (INT)numBytesPerInputFrame }; + INT inBufferElSize[] = { sizeof(int16_t) }; + + AACENC_BufDesc inBufDesc; + inBufDesc.numBufs = sizeof(inBuffer) / sizeof(void*); + inBufDesc.bufs = (void**)&inBuffer; + inBufDesc.bufferIdentifiers = inBufferIds; + inBufDesc.bufSizes = inBufferSize; + inBufDesc.bufElSizes = inBufferElSize; + + void* outBuffer[] = { outPtr }; + INT outBufferIds[] = { OUT_BITSTREAM_DATA }; + INT outBufferSize[] = { 0 }; + INT outBufferElSize[] = { sizeof(UCHAR) }; + + AACENC_BufDesc outBufDesc; + outBufDesc.numBufs = sizeof(outBuffer) / sizeof(void*); + outBufDesc.bufs = (void**)&outBuffer; + outBufDesc.bufferIdentifiers = outBufferIds; + outBufDesc.bufSizes = outBufferSize; + outBufDesc.bufElSizes = outBufferElSize; + + AACENC_ERROR encoderErr = AACENC_OK; + size_t nOutputBytes = 0; + + do { + memset(&outargs, 0, sizeof(outargs)); + + outBuffer[0] = outPtr; + outBufferSize[0] = outAvailable - nOutputBytes; + + encoderErr = aacEncEncode(mAACEncoder, + &inBufDesc, + &outBufDesc, + &inargs, + &outargs); + + if (encoderErr == AACENC_OK) { + outPtr += outargs.numOutBytes; + nOutputBytes += outargs.numOutBytes; + + if (outargs.numInSamples > 0) { + int numRemainingSamples = inargs.numInSamples - outargs.numInSamples; + if (numRemainingSamples > 0) { + memmove(mInputFrame, + &mInputFrame[outargs.numInSamples], + sizeof(int16_t) * numRemainingSamples); + } + inargs.numInSamples -= outargs.numInSamples; + } + } + } while (encoderErr == AACENC_OK && inargs.numInSamples > 0); + + outHeader->nFilledLen = nOutputBytes; + + outHeader->nFlags = OMX_BUFFERFLAG_ENDOFFRAME; + + if (mSawInputEOS) { + outHeader->nFlags = OMX_BUFFERFLAG_EOS; + } + + outHeader->nTimeStamp = mInputTimeUs; + +#if 0 + ALOGI(""sending %d bytes of data (time = %lld us, flags = 0x%08lx)"", + nOutputBytes, mInputTimeUs, outHeader->nFlags); + + hexdump(outHeader->pBuffer + outHeader->nOffset, outHeader->nFilledLen); +#endif + + outQueue.erase(outQueue.begin()); + outInfo->mOwnedByUs = false; + notifyFillBufferDone(outHeader); + + outHeader = NULL; + outInfo = NULL; + + mInputSize = 0; + } +} +",1,"void SoftAACEncoder2::onQueueFilled(OMX_U32 /* portIndex */) { + if (mSignalledError) { + return; + } + + List &inQueue = getPortQueue(0); + List &outQueue = getPortQueue(1); + + if (!mSentCodecSpecificData) { + + if (outQueue.empty()) { + return; + } + + if (AACENC_OK != aacEncEncode(mAACEncoder, NULL, NULL, NULL, NULL)) { + ALOGE(""Unable to initialize encoder for profile / sample-rate / bit-rate / channels""); + notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); + mSignalledError = true; + return; + } + + OMX_U32 actualBitRate = aacEncoder_GetParam(mAACEncoder, AACENC_BITRATE); + if (mBitRate != actualBitRate) { + ALOGW(""Requested bitrate %u unsupported, using %u"", mBitRate, actualBitRate); + } + + AACENC_InfoStruct encInfo; + if (AACENC_OK != aacEncInfo(mAACEncoder, &encInfo)) { + ALOGE(""Failed to get AAC encoder info""); + notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); + mSignalledError = true; + return; + } + + + BufferInfo *outInfo = *outQueue.begin(); + OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; + + if (outHeader->nOffset + encInfo.confSize > outHeader->nAllocLen) { + ALOGE(""b/34617444""); + android_errorWriteLog(0x534e4554,""34617444""); + notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); + mSignalledError = true; + return; + } + + outHeader->nFilledLen = encInfo.confSize; + outHeader->nFlags = OMX_BUFFERFLAG_CODECCONFIG; + + uint8_t *out = outHeader->pBuffer + outHeader->nOffset; + memcpy(out, encInfo.confBuf, encInfo.confSize); + + outQueue.erase(outQueue.begin()); + outInfo->mOwnedByUs = false; + notifyFillBufferDone(outHeader); + + mSentCodecSpecificData = true; + } + + size_t numBytesPerInputFrame = + mNumChannels * kNumSamplesPerFrame * sizeof(int16_t); + + if (mAACProfile == OMX_AUDIO_AACObjectELD && numBytesPerInputFrame > 512) { + numBytesPerInputFrame = 512; + } + + for (;;) { + + while (mInputSize < numBytesPerInputFrame) { + + if (mSawInputEOS || inQueue.empty()) { + return; + } + + BufferInfo *inInfo = *inQueue.begin(); + OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; + + const void *inData = inHeader->pBuffer + inHeader->nOffset; + + size_t copy = numBytesPerInputFrame - mInputSize; + if (copy > inHeader->nFilledLen) { + copy = inHeader->nFilledLen; + } + + if (mInputFrame == NULL) { + mInputFrame = new int16_t[numBytesPerInputFrame / sizeof(int16_t)]; + } + + if (mInputSize == 0) { + mInputTimeUs = inHeader->nTimeStamp; + } + + memcpy((uint8_t *)mInputFrame + mInputSize, inData, copy); + mInputSize += copy; + + inHeader->nOffset += copy; + inHeader->nFilledLen -= copy; + + inHeader->nTimeStamp += + (copy * 1000000ll / mSampleRate) + / (mNumChannels * sizeof(int16_t)); + + if (inHeader->nFilledLen == 0) { + if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { + mSawInputEOS = true; + + memset((uint8_t *)mInputFrame + mInputSize, + 0, + numBytesPerInputFrame - mInputSize); + + mInputSize = numBytesPerInputFrame; + } + + inQueue.erase(inQueue.begin()); + inInfo->mOwnedByUs = false; + notifyEmptyBufferDone(inHeader); + + inData = NULL; + inHeader = NULL; + inInfo = NULL; + } + } + + + if (outQueue.empty()) { + return; + } + + BufferInfo *outInfo = *outQueue.begin(); + OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; + + uint8_t *outPtr = (uint8_t *)outHeader->pBuffer + outHeader->nOffset; + size_t outAvailable = outHeader->nAllocLen - outHeader->nOffset; + + AACENC_InArgs inargs; + AACENC_OutArgs outargs; + memset(&inargs, 0, sizeof(inargs)); + memset(&outargs, 0, sizeof(outargs)); + inargs.numInSamples = numBytesPerInputFrame / sizeof(int16_t); + + void* inBuffer[] = { (unsigned char *)mInputFrame }; + INT inBufferIds[] = { IN_AUDIO_DATA }; + INT inBufferSize[] = { (INT)numBytesPerInputFrame }; + INT inBufferElSize[] = { sizeof(int16_t) }; + + AACENC_BufDesc inBufDesc; + inBufDesc.numBufs = sizeof(inBuffer) / sizeof(void*); + inBufDesc.bufs = (void**)&inBuffer; + inBufDesc.bufferIdentifiers = inBufferIds; + inBufDesc.bufSizes = inBufferSize; + inBufDesc.bufElSizes = inBufferElSize; + + void* outBuffer[] = { outPtr }; + INT outBufferIds[] = { OUT_BITSTREAM_DATA }; + INT outBufferSize[] = { 0 }; + INT outBufferElSize[] = { sizeof(UCHAR) }; + + AACENC_BufDesc outBufDesc; + outBufDesc.numBufs = sizeof(outBuffer) / sizeof(void*); + outBufDesc.bufs = (void**)&outBuffer; + outBufDesc.bufferIdentifiers = outBufferIds; + outBufDesc.bufSizes = outBufferSize; + outBufDesc.bufElSizes = outBufferElSize; + + AACENC_ERROR encoderErr = AACENC_OK; + size_t nOutputBytes = 0; + + do { + memset(&outargs, 0, sizeof(outargs)); + + outBuffer[0] = outPtr; + outBufferSize[0] = outAvailable - nOutputBytes; + + encoderErr = aacEncEncode(mAACEncoder, + &inBufDesc, + &outBufDesc, + &inargs, + &outargs); + + if (encoderErr == AACENC_OK) { + outPtr += outargs.numOutBytes; + nOutputBytes += outargs.numOutBytes; + + if (outargs.numInSamples > 0) { + int numRemainingSamples = inargs.numInSamples - outargs.numInSamples; + if (numRemainingSamples > 0) { + memmove(mInputFrame, + &mInputFrame[outargs.numInSamples], + sizeof(int16_t) * numRemainingSamples); + } + inargs.numInSamples -= outargs.numInSamples; + } + } + } while (encoderErr == AACENC_OK && inargs.numInSamples > 0); + + outHeader->nFilledLen = nOutputBytes; + + outHeader->nFlags = OMX_BUFFERFLAG_ENDOFFRAME; + + if (mSawInputEOS) { + outHeader->nFlags = OMX_BUFFERFLAG_EOS; + } + + outHeader->nTimeStamp = mInputTimeUs; + +#if 0 + ALOGI(""sending %d bytes of data (time = %lld us, flags = 0x%08lx)"", + nOutputBytes, mInputTimeUs, outHeader->nFlags); + + hexdump(outHeader->pBuffer + outHeader->nOffset, outHeader->nFilledLen); +#endif + + outQueue.erase(outQueue.begin()); + outInfo->mOwnedByUs = false; + notifyFillBufferDone(outHeader); + + outHeader = NULL; + outInfo = NULL; + + mInputSize = 0; + } +} +","@@ -510,6 +510,15 @@ + + + BufferInfo *outInfo = *outQueue.begin(); + OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; ++ ++ if (outHeader->nOffset + encInfo.confSize > outHeader->nAllocLen) { ++ ALOGE(""b/34617444""); ++ android_errorWriteLog(0x534e4554,""34617444""); ++ notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); ++ mSignalledError = true; ++ return; ++ } ++ + outHeader->nFilledLen = encInfo.confSize; + outHeader->nFlags = OMX_BUFFERFLAG_CODECCONFIG; + +",1659,1990,2048 +6803,"static int __sctp_connect(struct sock *sk, + struct sockaddr *kaddrs, + int addrs_size, + sctp_assoc_t *assoc_id) +{ + struct net *net = sock_net(sk); + struct sctp_sock *sp; + struct sctp_endpoint *ep; + struct sctp_association *asoc = NULL; + struct sctp_association *asoc2; + struct sctp_transport *transport; + union sctp_addr to; + sctp_scope_t scope; + long timeo; + int err = 0; + int addrcnt = 0; + int walk_size = 0; + union sctp_addr *sa_addr = NULL; + void *addr_buf; + unsigned short port; + unsigned int f_flags = 0; + + sp = sctp_sk(sk); + ep = sp->ep; + + /* connect() cannot be done on a socket that is already in ESTABLISHED + * state - UDP-style peeled off socket or a TCP-style socket that + * is already connected. + * It cannot be done even on a TCP-style listening socket. + */ + if (sctp_sstate(sk, ESTABLISHED) || sctp_sstate(sk, CLOSING) || + (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))) { + err = -EISCONN; + goto out_free; + } + + /* Walk through the addrs buffer and count the number of addresses. */ + addr_buf = kaddrs; + while (walk_size < addrs_size) { + struct sctp_af *af; + + if (walk_size + sizeof(sa_family_t) > addrs_size) { + err = -EINVAL; + goto out_free; + } + + sa_addr = addr_buf; + af = sctp_get_af_specific(sa_addr->sa.sa_family); + + /* If the address family is not supported or if this address + * causes the address buffer to overflow return EINVAL. + */ + if (!af || (walk_size + af->sockaddr_len) > addrs_size) { + err = -EINVAL; + goto out_free; + } + + port = ntohs(sa_addr->v4.sin_port); + + /* Save current address so we can work with it */ + memcpy(&to, sa_addr, af->sockaddr_len); + + err = sctp_verify_addr(sk, &to, af->sockaddr_len); + if (err) + goto out_free; + + /* Make sure the destination port is correctly set + * in all addresses. + */ + if (asoc && asoc->peer.port && asoc->peer.port != port) { + err = -EINVAL; + goto out_free; + } + + /* Check if there already is a matching association on the + * endpoint (other than the one created here). + */ + asoc2 = sctp_endpoint_lookup_assoc(ep, &to, &transport); + if (asoc2 && asoc2 != asoc) { + if (asoc2->state >= SCTP_STATE_ESTABLISHED) + err = -EISCONN; + else + err = -EALREADY; + goto out_free; + } + + /* If we could not find a matching association on the endpoint, + * make sure that there is no peeled-off association matching + * the peer address even on another socket. + */ + if (sctp_endpoint_is_peeled_off(ep, &to)) { + err = -EADDRNOTAVAIL; + goto out_free; + } + + if (!asoc) { + /* If a bind() or sctp_bindx() is not called prior to + * an sctp_connectx() call, the system picks an + * ephemeral port and will choose an address set + * equivalent to binding with a wildcard address. + */ + if (!ep->base.bind_addr.port) { + if (sctp_autobind(sk)) { + err = -EAGAIN; + goto out_free; + } + } else { + /* + * If an unprivileged user inherits a 1-many + * style socket with open associations on a + * privileged port, it MAY be permitted to + * accept new associations, but it SHOULD NOT + * be permitted to open new associations. + */ + if (ep->base.bind_addr.port < + inet_prot_sock(net) && + !ns_capable(net->user_ns, + CAP_NET_BIND_SERVICE)) { + err = -EACCES; + goto out_free; + } + } + + scope = sctp_scope(&to); + asoc = sctp_association_new(ep, sk, scope, GFP_KERNEL); + if (!asoc) { + err = -ENOMEM; + goto out_free; + } + + err = sctp_assoc_set_bind_addr_from_ep(asoc, scope, + GFP_KERNEL); + if (err < 0) { + goto out_free; + } + + } + + /* Prime the peer's transport structures. */ + transport = sctp_assoc_add_peer(asoc, &to, GFP_KERNEL, + SCTP_UNKNOWN); + if (!transport) { + err = -ENOMEM; + goto out_free; + } + + addrcnt++; + addr_buf += af->sockaddr_len; + walk_size += af->sockaddr_len; + } + + /* In case the user of sctp_connectx() wants an association + * id back, assign one now. + */ + if (assoc_id) { + err = sctp_assoc_set_id(asoc, GFP_KERNEL); + if (err < 0) + goto out_free; + } + + err = sctp_primitive_ASSOCIATE(net, asoc, NULL); + if (err < 0) { + goto out_free; + } + + /* Initialize sk's dport and daddr for getpeername() */ + inet_sk(sk)->inet_dport = htons(asoc->peer.port); + sp->pf->to_sk_daddr(sa_addr, sk); + sk->sk_err = 0; + + /* in-kernel sockets don't generally have a file allocated to them + * if all they do is call sock_create_kern(). + */ + if (sk->sk_socket->file) + f_flags = sk->sk_socket->file->f_flags; + + timeo = sock_sndtimeo(sk, f_flags & O_NONBLOCK); + + if (assoc_id) + *assoc_id = asoc->assoc_id; + err = sctp_wait_for_connect(asoc, &timeo); + /* Note: the asoc may be freed after the return of + * sctp_wait_for_connect. + */ + + /* Don't free association on exit. */ + asoc = NULL; + +out_free: + pr_debug(""%s: took out_free path with asoc:%p kaddrs:%p err:%d\n"", + __func__, asoc, kaddrs, err); + + if (asoc) { + /* sctp_primitive_ASSOCIATE may have added this association + * To the hash table, try to unhash it, just in case, its a noop + * if it wasn't hashed so we're safe + */ + sctp_association_free(asoc); + } + return err; +} +",0,"static int __sctp_connect(struct sock *sk, + struct sockaddr *kaddrs, + int addrs_size, + sctp_assoc_t *assoc_id) +{ + struct net *net = sock_net(sk); + struct sctp_sock *sp; + struct sctp_endpoint *ep; + struct sctp_association *asoc = NULL; + struct sctp_association *asoc2; + struct sctp_transport *transport; + union sctp_addr to; + sctp_scope_t scope; + long timeo; + int err = 0; + int addrcnt = 0; + int walk_size = 0; + union sctp_addr *sa_addr = NULL; + void *addr_buf; + unsigned short port; + unsigned int f_flags = 0; + + sp = sctp_sk(sk); + ep = sp->ep; + + /* connect() cannot be done on a socket that is already in ESTABLISHED + * state - UDP-style peeled off socket or a TCP-style socket that + * is already connected. + * It cannot be done even on a TCP-style listening socket. + */ + if (sctp_sstate(sk, ESTABLISHED) || sctp_sstate(sk, CLOSING) || + (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))) { + err = -EISCONN; + goto out_free; + } + + /* Walk through the addrs buffer and count the number of addresses. */ + addr_buf = kaddrs; + while (walk_size < addrs_size) { + struct sctp_af *af; + + if (walk_size + sizeof(sa_family_t) > addrs_size) { + err = -EINVAL; + goto out_free; + } + + sa_addr = addr_buf; + af = sctp_get_af_specific(sa_addr->sa.sa_family); + + /* If the address family is not supported or if this address + * causes the address buffer to overflow return EINVAL. + */ + if (!af || (walk_size + af->sockaddr_len) > addrs_size) { + err = -EINVAL; + goto out_free; + } + + port = ntohs(sa_addr->v4.sin_port); + + /* Save current address so we can work with it */ + memcpy(&to, sa_addr, af->sockaddr_len); + + err = sctp_verify_addr(sk, &to, af->sockaddr_len); + if (err) + goto out_free; + + /* Make sure the destination port is correctly set + * in all addresses. + */ + if (asoc && asoc->peer.port && asoc->peer.port != port) { + err = -EINVAL; + goto out_free; + } + + /* Check if there already is a matching association on the + * endpoint (other than the one created here). + */ + asoc2 = sctp_endpoint_lookup_assoc(ep, &to, &transport); + if (asoc2 && asoc2 != asoc) { + if (asoc2->state >= SCTP_STATE_ESTABLISHED) + err = -EISCONN; + else + err = -EALREADY; + goto out_free; + } + + /* If we could not find a matching association on the endpoint, + * make sure that there is no peeled-off association matching + * the peer address even on another socket. + */ + if (sctp_endpoint_is_peeled_off(ep, &to)) { + err = -EADDRNOTAVAIL; + goto out_free; + } + + if (!asoc) { + /* If a bind() or sctp_bindx() is not called prior to + * an sctp_connectx() call, the system picks an + * ephemeral port and will choose an address set + * equivalent to binding with a wildcard address. + */ + if (!ep->base.bind_addr.port) { + if (sctp_autobind(sk)) { + err = -EAGAIN; + goto out_free; + } + } else { + /* + * If an unprivileged user inherits a 1-many + * style socket with open associations on a + * privileged port, it MAY be permitted to + * accept new associations, but it SHOULD NOT + * be permitted to open new associations. + */ + if (ep->base.bind_addr.port < + inet_prot_sock(net) && + !ns_capable(net->user_ns, + CAP_NET_BIND_SERVICE)) { + err = -EACCES; + goto out_free; + } + } + + scope = sctp_scope(&to); + asoc = sctp_association_new(ep, sk, scope, GFP_KERNEL); + if (!asoc) { + err = -ENOMEM; + goto out_free; + } + + err = sctp_assoc_set_bind_addr_from_ep(asoc, scope, + GFP_KERNEL); + if (err < 0) { + goto out_free; + } + + } + + /* Prime the peer's transport structures. */ + transport = sctp_assoc_add_peer(asoc, &to, GFP_KERNEL, + SCTP_UNKNOWN); + if (!transport) { + err = -ENOMEM; + goto out_free; + } + + addrcnt++; + addr_buf += af->sockaddr_len; + walk_size += af->sockaddr_len; + } + + /* In case the user of sctp_connectx() wants an association + * id back, assign one now. + */ + if (assoc_id) { + err = sctp_assoc_set_id(asoc, GFP_KERNEL); + if (err < 0) + goto out_free; + } + + err = sctp_primitive_ASSOCIATE(net, asoc, NULL); + if (err < 0) { + goto out_free; + } + + /* Initialize sk's dport and daddr for getpeername() */ + inet_sk(sk)->inet_dport = htons(asoc->peer.port); + sp->pf->to_sk_daddr(sa_addr, sk); + sk->sk_err = 0; + + /* in-kernel sockets don't generally have a file allocated to them + * if all they do is call sock_create_kern(). + */ + if (sk->sk_socket->file) + f_flags = sk->sk_socket->file->f_flags; + + timeo = sock_sndtimeo(sk, f_flags & O_NONBLOCK); + + if (assoc_id) + *assoc_id = asoc->assoc_id; + err = sctp_wait_for_connect(asoc, &timeo); + /* Note: the asoc may be freed after the return of + * sctp_wait_for_connect. + */ + + /* Don't free association on exit. */ + asoc = NULL; + +out_free: + pr_debug(""%s: took out_free path with asoc:%p kaddrs:%p err:%d\n"", + __func__, asoc, kaddrs, err); + + if (asoc) { + /* sctp_primitive_ASSOCIATE may have added this association + * To the hash table, try to unhash it, just in case, its a noop + * if it wasn't hashed so we're safe + */ + sctp_association_free(asoc); + } + return err; +} +","@@ -4862,6 +4862,12 @@ int sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp) + if (!asoc) + return -EINVAL; + ++ /* If there is a thread waiting on more sndbuf space for ++ * sending on this asoc, it cannot be peeled. ++ */ ++ if (waitqueue_active(&asoc->wait)) ++ return -EBUSY; ++ + /* An association cannot be branched off from an already peeled-off + * socket, nor is this supported for tcp style sockets. + */ +@@ -7599,8 +7605,6 @@ static int sctp_wait_for_sndbuf(struct sctp_association *asoc, long *timeo_p, + */ + release_sock(sk); + current_timeo = schedule_timeout(current_timeo); +- if (sk != asoc->base.sk) +- goto do_error; + lock_sock(sk); + + *timeo_p = current_timeo;",1528,1859,2048 +1437,"static EVP_PKEY * php_openssl_evp_from_zval(zval ** val, int public_key, char * passphrase, int makeresource, long * resourceval TSRMLS_DC) +{ + EVP_PKEY * key = NULL; + X509 * cert = NULL; + int free_cert = 0; + long cert_res = -1; + char * filename = NULL; + zval tmp; + + Z_TYPE(tmp) = IS_NULL; + +#define TMP_CLEAN \ + if (Z_TYPE(tmp) == IS_STRING) {\ + zval_dtor(&tmp); \ + } \ + return NULL; + + if (resourceval) { + *resourceval = -1; + } + if (Z_TYPE_PP(val) == IS_ARRAY) { + zval ** zphrase; + + /* get passphrase */ + + if (zend_hash_index_find(HASH_OF(*val), 1, (void **)&zphrase) == FAILURE) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""key array must be of the form array(0 => key, 1 => phrase)""); + return NULL; + } + + if (Z_TYPE_PP(zphrase) == IS_STRING) { + passphrase = Z_STRVAL_PP(zphrase); + } else { + tmp = **zphrase; + zval_copy_ctor(&tmp); + convert_to_string(&tmp); + passphrase = Z_STRVAL(tmp); + } + + /* now set val to be the key param and continue */ + if (zend_hash_index_find(HASH_OF(*val), 0, (void **)&val) == FAILURE) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""key array must be of the form array(0 => key, 1 => phrase)""); + TMP_CLEAN; + } + } + + if (Z_TYPE_PP(val) == IS_RESOURCE) { + void * what; + int type; + + what = zend_fetch_resource(val TSRMLS_CC, -1, ""OpenSSL X.509/key"", &type, 2, le_x509, le_key); + if (!what) { + TMP_CLEAN; + } + if (resourceval) { + *resourceval = Z_LVAL_PP(val); + } + if (type == le_x509) { + /* extract key from cert, depending on public_key param */ + cert = (X509*)what; + free_cert = 0; + } else if (type == le_key) { + int is_priv; + + is_priv = php_openssl_is_private_key((EVP_PKEY*)what TSRMLS_CC); + + /* check whether it is actually a private key if requested */ + if (!public_key && !is_priv) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""supplied key param is a public key""); + TMP_CLEAN; + } + + if (public_key && is_priv) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Don't know how to get public key from this private key""); + TMP_CLEAN; + } else { + if (Z_TYPE(tmp) == IS_STRING) { + zval_dtor(&tmp); + } + /* got the key - return it */ + return (EVP_PKEY*)what; + } + } else { + /* other types could be used here - eg: file pointers and read in the data from them */ + TMP_CLEAN; + } + } else { + /* force it to be a string and check if it refers to a file */ + /* passing non string values leaks, object uses toString, it returns NULL + * See bug38255.phpt + */ + if (!(Z_TYPE_PP(val) == IS_STRING || Z_TYPE_PP(val) == IS_OBJECT)) { + TMP_CLEAN; + } + convert_to_string_ex(val); + + if (Z_STRLEN_PP(val) > 7 && memcmp(Z_STRVAL_PP(val), ""file://"", sizeof(""file://"") - 1) == 0) { + filename = Z_STRVAL_PP(val) + (sizeof(""file://"") - 1); + } + /* it's an X509 file/cert of some kind, and we need to extract the data from that */ + if (public_key) { + cert = php_openssl_x509_from_zval(val, 0, &cert_res TSRMLS_CC); + free_cert = (cert_res == -1); + /* actual extraction done later */ + if (!cert) { + /* not a X509 certificate, try to retrieve public key */ + BIO* in; + if (filename) { + in = BIO_new_file(filename, ""r""); + } else { + in = BIO_new_mem_buf(Z_STRVAL_PP(val), Z_STRLEN_PP(val)); + } + if (in == NULL) { + TMP_CLEAN; + } + key = PEM_read_bio_PUBKEY(in, NULL,NULL, NULL); + BIO_free(in); + } + } else { + /* we want the private key */ + BIO *in; + + if (filename) { + if (php_openssl_open_base_dir_chk(filename TSRMLS_CC)) { + TMP_CLEAN; + } + in = BIO_new_file(filename, ""r""); + } else { + in = BIO_new_mem_buf(Z_STRVAL_PP(val), Z_STRLEN_PP(val)); + } + + if (in == NULL) { + TMP_CLEAN; + } + key = PEM_read_bio_PrivateKey(in, NULL,NULL, passphrase); + BIO_free(in); + } + } + + if (public_key && cert && key == NULL) { + /* extract public key from X509 cert */ + key = (EVP_PKEY *) X509_get_pubkey(cert); + } + + if (free_cert && cert) { + X509_free(cert); + } + if (key && makeresource && resourceval) { + *resourceval = ZEND_REGISTER_RESOURCE(NULL, key, le_key); + } + if (Z_TYPE(tmp) == IS_STRING) { + zval_dtor(&tmp); + } + return key; +} +",0,"static EVP_PKEY * php_openssl_evp_from_zval(zval ** val, int public_key, char * passphrase, int makeresource, long * resourceval TSRMLS_DC) +{ + EVP_PKEY * key = NULL; + X509 * cert = NULL; + int free_cert = 0; + long cert_res = -1; + char * filename = NULL; + zval tmp; + + Z_TYPE(tmp) = IS_NULL; + +#define TMP_CLEAN \ + if (Z_TYPE(tmp) == IS_STRING) {\ + zval_dtor(&tmp); \ + } \ + return NULL; + + if (resourceval) { + *resourceval = -1; + } + if (Z_TYPE_PP(val) == IS_ARRAY) { + zval ** zphrase; + + /* get passphrase */ + + if (zend_hash_index_find(HASH_OF(*val), 1, (void **)&zphrase) == FAILURE) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""key array must be of the form array(0 => key, 1 => phrase)""); + return NULL; + } + + if (Z_TYPE_PP(zphrase) == IS_STRING) { + passphrase = Z_STRVAL_PP(zphrase); + } else { + tmp = **zphrase; + zval_copy_ctor(&tmp); + convert_to_string(&tmp); + passphrase = Z_STRVAL(tmp); + } + + /* now set val to be the key param and continue */ + if (zend_hash_index_find(HASH_OF(*val), 0, (void **)&val) == FAILURE) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""key array must be of the form array(0 => key, 1 => phrase)""); + TMP_CLEAN; + } + } + + if (Z_TYPE_PP(val) == IS_RESOURCE) { + void * what; + int type; + + what = zend_fetch_resource(val TSRMLS_CC, -1, ""OpenSSL X.509/key"", &type, 2, le_x509, le_key); + if (!what) { + TMP_CLEAN; + } + if (resourceval) { + *resourceval = Z_LVAL_PP(val); + } + if (type == le_x509) { + /* extract key from cert, depending on public_key param */ + cert = (X509*)what; + free_cert = 0; + } else if (type == le_key) { + int is_priv; + + is_priv = php_openssl_is_private_key((EVP_PKEY*)what TSRMLS_CC); + + /* check whether it is actually a private key if requested */ + if (!public_key && !is_priv) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""supplied key param is a public key""); + TMP_CLEAN; + } + + if (public_key && is_priv) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Don't know how to get public key from this private key""); + TMP_CLEAN; + } else { + if (Z_TYPE(tmp) == IS_STRING) { + zval_dtor(&tmp); + } + /* got the key - return it */ + return (EVP_PKEY*)what; + } + } else { + /* other types could be used here - eg: file pointers and read in the data from them */ + TMP_CLEAN; + } + } else { + /* force it to be a string and check if it refers to a file */ + /* passing non string values leaks, object uses toString, it returns NULL + * See bug38255.phpt + */ + if (!(Z_TYPE_PP(val) == IS_STRING || Z_TYPE_PP(val) == IS_OBJECT)) { + TMP_CLEAN; + } + convert_to_string_ex(val); + + if (Z_STRLEN_PP(val) > 7 && memcmp(Z_STRVAL_PP(val), ""file://"", sizeof(""file://"") - 1) == 0) { + filename = Z_STRVAL_PP(val) + (sizeof(""file://"") - 1); + } + /* it's an X509 file/cert of some kind, and we need to extract the data from that */ + if (public_key) { + cert = php_openssl_x509_from_zval(val, 0, &cert_res TSRMLS_CC); + free_cert = (cert_res == -1); + /* actual extraction done later */ + if (!cert) { + /* not a X509 certificate, try to retrieve public key */ + BIO* in; + if (filename) { + in = BIO_new_file(filename, ""r""); + } else { + in = BIO_new_mem_buf(Z_STRVAL_PP(val), Z_STRLEN_PP(val)); + } + if (in == NULL) { + TMP_CLEAN; + } + key = PEM_read_bio_PUBKEY(in, NULL,NULL, NULL); + BIO_free(in); + } + } else { + /* we want the private key */ + BIO *in; + + if (filename) { + if (php_openssl_open_base_dir_chk(filename TSRMLS_CC)) { + TMP_CLEAN; + } + in = BIO_new_file(filename, ""r""); + } else { + in = BIO_new_mem_buf(Z_STRVAL_PP(val), Z_STRLEN_PP(val)); + } + + if (in == NULL) { + TMP_CLEAN; + } + key = PEM_read_bio_PrivateKey(in, NULL,NULL, passphrase); + BIO_free(in); + } + } + + if (public_key && cert && key == NULL) { + /* extract public key from X509 cert */ + key = (EVP_PKEY *) X509_get_pubkey(cert); + } + + if (free_cert && cert) { + X509_free(cert); + } + if (key && makeresource && resourceval) { + *resourceval = ZEND_REGISTER_RESOURCE(NULL, key, le_key); + } + if (Z_TYPE(tmp) == IS_STRING) { + zval_dtor(&tmp); + } + return key; +} +","@@ -5070,7 +5070,6 @@ PHP_FUNCTION(openssl_random_pseudo_bytes) + long buffer_length; + unsigned char *buffer = NULL; + zval *zstrong_result_returned = NULL; +- int strong_result = 0; + + if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""l|z"", &buffer_length, &zstrong_result_returned) == FAILURE) { + return; +@@ -5088,7 +5087,6 @@ PHP_FUNCTION(openssl_random_pseudo_bytes) + buffer = emalloc(buffer_length + 1); + + #ifdef PHP_WIN32 +- strong_result = 1; + /* random/urandom equivalent on Windows */ + if (php_win32_get_random_bytes(buffer, (size_t) buffer_length) == FAILURE) { + efree(buffer); +@@ -5098,7 +5096,7 @@ PHP_FUNCTION(openssl_random_pseudo_bytes) + RETURN_FALSE; + } + #else +- if ((strong_result = RAND_pseudo_bytes(buffer, buffer_length)) < 0) { ++ if (RAND_bytes(buffer, buffer_length) <= 0) { + efree(buffer); + if (zstrong_result_returned) { + ZVAL_BOOL(zstrong_result_returned, 0); +@@ -5111,7 +5109,7 @@ PHP_FUNCTION(openssl_random_pseudo_bytes) + RETVAL_STRINGL((char *)buffer, buffer_length, 0); + + if (zstrong_result_returned) { +- ZVAL_BOOL(zstrong_result_returned, strong_result); ++ ZVAL_BOOL(zstrong_result_returned, 1); + } + } + /* }}} */",1330,1661,2048 +17883,"NORET_TYPE void do_exit(long code) +{ + struct task_struct *tsk = current; + int group_dead; + + profile_task_exit(tsk); + + WARN_ON(atomic_read(&tsk->fs_excl)); + + if (unlikely(in_interrupt())) + panic(""Aiee, killing interrupt handler!""); + if (unlikely(!tsk->pid)) + panic(""Attempted to kill the idle task!""); + + tracehook_report_exit(&code); + + /* + * We're taking recursive faults here in do_exit. Safest is to just + * leave this task alone and wait for reboot. + */ + if (unlikely(tsk->flags & PF_EXITING)) { + printk(KERN_ALERT + ""Fixing recursive fault but reboot is needed!\n""); + /* + * We can do this unlocked here. The futex code uses + * this flag just to verify whether the pi state + * cleanup has been done or not. In the worst case it + * loops once more. We pretend that the cleanup was + * done as there is no way to return. Either the + * OWNER_DIED bit is set by now or we push the blocked + * task into the wait for ever nirwana as well. + */ + tsk->flags |= PF_EXITPIDONE; + if (tsk->io_context) + exit_io_context(); + set_current_state(TASK_UNINTERRUPTIBLE); + schedule(); + } + + exit_signals(tsk); /* sets PF_EXITING */ + /* + * tsk->flags are checked in the futex code to protect against + * an exiting task cleaning up the robust pi futexes. + */ + smp_mb(); + spin_unlock_wait(&tsk->pi_lock); + + if (unlikely(in_atomic())) + printk(KERN_INFO ""note: %s[%d] exited with preempt_count %d\n"", + current->comm, task_pid_nr(current), + preempt_count()); + + acct_update_integrals(tsk); + if (tsk->mm) { + update_hiwater_rss(tsk->mm); + update_hiwater_vm(tsk->mm); + } + group_dead = atomic_dec_and_test(&tsk->signal->live); + if (group_dead) { + hrtimer_cancel(&tsk->signal->real_timer); + exit_itimers(tsk->signal); + } + acct_collect(code, group_dead); +#ifdef CONFIG_FUTEX + if (unlikely(tsk->robust_list)) + exit_robust_list(tsk); +#ifdef CONFIG_COMPAT + if (unlikely(tsk->compat_robust_list)) + compat_exit_robust_list(tsk); +#endif +#endif + if (group_dead) + tty_audit_exit(); + if (unlikely(tsk->audit_context)) + audit_free(tsk); + + tsk->exit_code = code; + taskstats_exit(tsk, group_dead); + + exit_mm(tsk); + + if (group_dead) + acct_process(); + trace_sched_process_exit(tsk); + + exit_sem(tsk); + exit_files(tsk); + exit_fs(tsk); + check_stack_usage(); + exit_thread(); + cgroup_exit(tsk, 1); + exit_keys(tsk); + + if (group_dead && tsk->signal->leader) + disassociate_ctty(1); + + module_put(task_thread_info(tsk)->exec_domain->module); + if (tsk->binfmt) + module_put(tsk->binfmt->module); + + proc_exit_connector(tsk); + exit_notify(tsk, group_dead); +#ifdef CONFIG_NUMA + mpol_put(tsk->mempolicy); + tsk->mempolicy = NULL; +#endif +#ifdef CONFIG_FUTEX + /* + * This must happen late, after the PID is not + * hashed anymore: + */ + if (unlikely(!list_empty(&tsk->pi_state_list))) + exit_pi_state_list(tsk); + if (unlikely(current->pi_state_cache)) + kfree(current->pi_state_cache); +#endif + /* + * Make sure we are holding no locks: + */ + debug_check_no_locks_held(tsk); + /* + * We can do this unlocked here. The futex code uses this flag + * just to verify whether the pi state cleanup has been done + * or not. In the worst case it loops once more. + */ + tsk->flags |= PF_EXITPIDONE; + + if (tsk->io_context) + exit_io_context(); + + if (tsk->splice_pipe) + __free_pipe_info(tsk->splice_pipe); + + preempt_disable(); + /* causes final put_task_struct in finish_task_switch(). */ + tsk->state = TASK_DEAD; + + schedule(); + BUG(); + /* Avoid ""noreturn function does return"". */ + for (;;) + cpu_relax(); /* For when BUG is null */ +} +",1,"NORET_TYPE void do_exit(long code) +{ + struct task_struct *tsk = current; + int group_dead; + + profile_task_exit(tsk); + + WARN_ON(atomic_read(&tsk->fs_excl)); + + if (unlikely(in_interrupt())) + panic(""Aiee, killing interrupt handler!""); + if (unlikely(!tsk->pid)) + panic(""Attempted to kill the idle task!""); + + tracehook_report_exit(&code); + + /* + * We're taking recursive faults here in do_exit. Safest is to just + * leave this task alone and wait for reboot. + */ + if (unlikely(tsk->flags & PF_EXITING)) { + printk(KERN_ALERT + ""Fixing recursive fault but reboot is needed!\n""); + /* + * We can do this unlocked here. The futex code uses + * this flag just to verify whether the pi state + * cleanup has been done or not. In the worst case it + * loops once more. We pretend that the cleanup was + * done as there is no way to return. Either the + * OWNER_DIED bit is set by now or we push the blocked + * task into the wait for ever nirwana as well. + */ + tsk->flags |= PF_EXITPIDONE; + if (tsk->io_context) + exit_io_context(); + set_current_state(TASK_UNINTERRUPTIBLE); + schedule(); + } + + exit_signals(tsk); /* sets PF_EXITING */ + /* + * tsk->flags are checked in the futex code to protect against + * an exiting task cleaning up the robust pi futexes. + */ + smp_mb(); + spin_unlock_wait(&tsk->pi_lock); + + if (unlikely(in_atomic())) + printk(KERN_INFO ""note: %s[%d] exited with preempt_count %d\n"", + current->comm, task_pid_nr(current), + preempt_count()); + + acct_update_integrals(tsk); + if (tsk->mm) { + update_hiwater_rss(tsk->mm); + update_hiwater_vm(tsk->mm); + } + group_dead = atomic_dec_and_test(&tsk->signal->live); + if (group_dead) { + hrtimer_cancel(&tsk->signal->real_timer); + exit_itimers(tsk->signal); + } + acct_collect(code, group_dead); + if (group_dead) + tty_audit_exit(); + if (unlikely(tsk->audit_context)) + audit_free(tsk); + + tsk->exit_code = code; + taskstats_exit(tsk, group_dead); + + exit_mm(tsk); + + if (group_dead) + acct_process(); + trace_sched_process_exit(tsk); + + exit_sem(tsk); + exit_files(tsk); + exit_fs(tsk); + check_stack_usage(); + exit_thread(); + cgroup_exit(tsk, 1); + exit_keys(tsk); + + if (group_dead && tsk->signal->leader) + disassociate_ctty(1); + + module_put(task_thread_info(tsk)->exec_domain->module); + if (tsk->binfmt) + module_put(tsk->binfmt->module); + + proc_exit_connector(tsk); + exit_notify(tsk, group_dead); +#ifdef CONFIG_NUMA + mpol_put(tsk->mempolicy); + tsk->mempolicy = NULL; +#endif +#ifdef CONFIG_FUTEX + /* + * This must happen late, after the PID is not + * hashed anymore: + */ + if (unlikely(!list_empty(&tsk->pi_state_list))) + exit_pi_state_list(tsk); + if (unlikely(current->pi_state_cache)) + kfree(current->pi_state_cache); +#endif + /* + * Make sure we are holding no locks: + */ + debug_check_no_locks_held(tsk); + /* + * We can do this unlocked here. The futex code uses this flag + * just to verify whether the pi state cleanup has been done + * or not. In the worst case it loops once more. + */ + tsk->flags |= PF_EXITPIDONE; + + if (tsk->io_context) + exit_io_context(); + + if (tsk->splice_pipe) + __free_pipe_info(tsk->splice_pipe); + + preempt_disable(); + /* causes final put_task_struct in finish_task_switch(). */ + tsk->state = TASK_DEAD; + + schedule(); + BUG(); + /* Avoid ""noreturn function does return"". */ + for (;;) + cpu_relax(); /* For when BUG is null */ +} +","@@ -40,7 +40,6 @@ + #include + #include + #include +-#include + #include + #include /* for audit_free() */ + #include +@@ -1059,14 +1058,6 @@ NORET_TYPE void do_exit(long code) + exit_itimers(tsk->signal); + } + acct_collect(code, group_dead); +-#ifdef CONFIG_FUTEX +- if (unlikely(tsk->robust_list)) +- exit_robust_list(tsk); +-#ifdef CONFIG_COMPAT +- if (unlikely(tsk->compat_robust_list)) +- compat_exit_robust_list(tsk); +-#endif +-#endif + if (group_dead) + tty_audit_exit(); + if (unlikely(tsk->audit_context))",997,1328,2048 +18097,"decode_multicast_vpn(netdissect_options *ndo, + const u_char *pptr, char *buf, u_int buflen) +{ + uint8_t route_type, route_length, addr_length, sg_length; + u_int offset; + + ND_TCHECK2(pptr[0], 2); + route_type = *pptr++; + route_length = *pptr++; + + snprintf(buf, buflen, ""Route-Type: %s (%u), length: %u"", + tok2str(bgp_multicast_vpn_route_type_values, + ""Unknown"", route_type), + route_type, route_length); + + switch(route_type) { + case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI: + ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); + offset = strlen(buf); + snprintf(buf + offset, buflen - offset, "", RD: %s, Originator %s"", + bgp_vpn_rd_print(ndo, pptr), + bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN, + (route_length - BGP_VPN_RD_LEN) << 3)); + break; + case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI: + ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); + offset = strlen(buf); + snprintf(buf + offset, buflen - offset, "", RD: %s, Source-AS %s"", + bgp_vpn_rd_print(ndo, pptr), + as_printf(ndo, astostr, sizeof(astostr), + EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); + break; + + case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI: + ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); + offset = strlen(buf); + snprintf(buf + offset, buflen - offset, "", RD: %s"", + bgp_vpn_rd_print(ndo, pptr)); + pptr += BGP_VPN_RD_LEN; + + sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen); + addr_length = route_length - sg_length; + + ND_TCHECK2(pptr[0], addr_length); + offset = strlen(buf); + snprintf(buf + offset, buflen - offset, "", Originator %s"", + bgp_vpn_ip_print(ndo, pptr, addr_length << 3)); + break; + + case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE: + ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); + offset = strlen(buf); + snprintf(buf + offset, buflen - offset, "", RD: %s"", + bgp_vpn_rd_print(ndo, pptr)); + pptr += BGP_VPN_RD_LEN; + + bgp_vpn_sg_print(ndo, pptr, buf, buflen); + break; + + case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */ + case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN: + ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); + offset = strlen(buf); + snprintf(buf + offset, buflen - offset, "", RD: %s, Source-AS %s"", + bgp_vpn_rd_print(ndo, pptr), + as_printf(ndo, astostr, sizeof(astostr), + EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); + pptr += BGP_VPN_RD_LEN; + + bgp_vpn_sg_print(ndo, pptr, buf, buflen); + break; + + /* + * no per route-type printing yet. + */ + case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF: + default: + break; + } + + return route_length + 2; + +trunc: + return -2; +} +",1,"decode_multicast_vpn(netdissect_options *ndo, + const u_char *pptr, char *buf, u_int buflen) +{ + uint8_t route_type, route_length, addr_length, sg_length; + u_int offset; + + ND_TCHECK2(pptr[0], 2); + route_type = *pptr++; + route_length = *pptr++; + + snprintf(buf, buflen, ""Route-Type: %s (%u), length: %u"", + tok2str(bgp_multicast_vpn_route_type_values, + ""Unknown"", route_type), + route_type, route_length); + + switch(route_type) { + case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI: + ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); + offset = strlen(buf); + snprintf(buf + offset, buflen - offset, "", RD: %s, Originator %s"", + bgp_vpn_rd_print(ndo, pptr), + bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN, + (route_length - BGP_VPN_RD_LEN) << 3)); + break; + case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI: + ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); + offset = strlen(buf); + snprintf(buf + offset, buflen - offset, "", RD: %s, Source-AS %s"", + bgp_vpn_rd_print(ndo, pptr), + as_printf(ndo, astostr, sizeof(astostr), + EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); + break; + + case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI: + ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); + offset = strlen(buf); + snprintf(buf + offset, buflen - offset, "", RD: %s"", + bgp_vpn_rd_print(ndo, pptr)); + pptr += BGP_VPN_RD_LEN; + + sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen); + addr_length = route_length - sg_length; + + ND_TCHECK2(pptr[0], addr_length); + offset = strlen(buf); + snprintf(buf + offset, buflen - offset, "", Originator %s"", + bgp_vpn_ip_print(ndo, pptr, addr_length << 3)); + break; + + case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE: + ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); + offset = strlen(buf); + snprintf(buf + offset, buflen - offset, "", RD: %s"", + bgp_vpn_rd_print(ndo, pptr)); + pptr += BGP_VPN_RD_LEN; + + bgp_vpn_sg_print(ndo, pptr, buf, buflen); + break; + + case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */ + case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN: + ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); + offset = strlen(buf); + snprintf(buf + offset, buflen - offset, "", RD: %s, Source-AS %s"", + bgp_vpn_rd_print(ndo, pptr), + as_printf(ndo, astostr, sizeof(astostr), + EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); + pptr += BGP_VPN_RD_LEN + 4; + + bgp_vpn_sg_print(ndo, pptr, buf, buflen); + break; + + /* + * no per route-type printing yet. + */ + case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF: + default: + break; + } + + return route_length + 2; + +trunc: + return -2; +} +","@@ -965,13 +965,13 @@ decode_multicast_vpn(netdissect_options *ndo, + + case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */ + case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN: +- ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN); ++ ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4); + offset = strlen(buf); + snprintf(buf + offset, buflen - offset, "", RD: %s, Source-AS %s"", + bgp_vpn_rd_print(ndo, pptr), + as_printf(ndo, astostr, sizeof(astostr), + EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN))); +- pptr += BGP_VPN_RD_LEN; ++ pptr += BGP_VPN_RD_LEN + 4; + + bgp_vpn_sg_print(ndo, pptr, buf, buflen); + break;",834,1165,2048 +2334,"static int power_check_constraints(struct cpu_hw_events *cpuhw, + u64 event_id[], unsigned int cflags[], + int n_ev) +{ + unsigned long mask, value, nv; + unsigned long smasks[MAX_HWEVENTS], svalues[MAX_HWEVENTS]; + int n_alt[MAX_HWEVENTS], choice[MAX_HWEVENTS]; + int i, j; + unsigned long addf = ppmu->add_fields; + unsigned long tadd = ppmu->test_adder; + + if (n_ev > ppmu->n_counter) + return -1; + + /* First see if the events will go on as-is */ + for (i = 0; i < n_ev; ++i) { + if ((cflags[i] & PPMU_LIMITED_PMC_REQD) + && !ppmu->limited_pmc_event(event_id[i])) { + ppmu->get_alternatives(event_id[i], cflags[i], + cpuhw->alternatives[i]); + event_id[i] = cpuhw->alternatives[i][0]; + } + if (ppmu->get_constraint(event_id[i], &cpuhw->amasks[i][0], + &cpuhw->avalues[i][0])) + return -1; + } + value = mask = 0; + for (i = 0; i < n_ev; ++i) { + nv = (value | cpuhw->avalues[i][0]) + + (value & cpuhw->avalues[i][0] & addf); + if ((((nv + tadd) ^ value) & mask) != 0 || + (((nv + tadd) ^ cpuhw->avalues[i][0]) & + cpuhw->amasks[i][0]) != 0) + break; + value = nv; + mask |= cpuhw->amasks[i][0]; + } + if (i == n_ev) + return 0; /* all OK */ + + /* doesn't work, gather alternatives... */ + if (!ppmu->get_alternatives) + return -1; + for (i = 0; i < n_ev; ++i) { + choice[i] = 0; + n_alt[i] = ppmu->get_alternatives(event_id[i], cflags[i], + cpuhw->alternatives[i]); + for (j = 1; j < n_alt[i]; ++j) + ppmu->get_constraint(cpuhw->alternatives[i][j], + &cpuhw->amasks[i][j], + &cpuhw->avalues[i][j]); + } + + /* enumerate all possibilities and see if any will work */ + i = 0; + j = -1; + value = mask = nv = 0; + while (i < n_ev) { + if (j >= 0) { + /* we're backtracking, restore context */ + value = svalues[i]; + mask = smasks[i]; + j = choice[i]; + } + /* + * See if any alternative k for event_id i, + * where k > j, will satisfy the constraints. + */ + while (++j < n_alt[i]) { + nv = (value | cpuhw->avalues[i][j]) + + (value & cpuhw->avalues[i][j] & addf); + if ((((nv + tadd) ^ value) & mask) == 0 && + (((nv + tadd) ^ cpuhw->avalues[i][j]) + & cpuhw->amasks[i][j]) == 0) + break; + } + if (j >= n_alt[i]) { + /* + * No feasible alternative, backtrack + * to event_id i-1 and continue enumerating its + * alternatives from where we got up to. + */ + if (--i < 0) + return -1; + } else { + /* + * Found a feasible alternative for event_id i, + * remember where we got up to with this event_id, + * go on to the next event_id, and start with + * the first alternative for it. + */ + choice[i] = j; + svalues[i] = value; + smasks[i] = mask; + value = nv; + mask |= cpuhw->amasks[i][j]; + ++i; + j = -1; + } + } + + /* OK, we have a feasible combination, tell the caller the solution */ + for (i = 0; i < n_ev; ++i) + event_id[i] = cpuhw->alternatives[i][choice[i]]; + return 0; +} +",0,"static int power_check_constraints(struct cpu_hw_events *cpuhw, + u64 event_id[], unsigned int cflags[], + int n_ev) +{ + unsigned long mask, value, nv; + unsigned long smasks[MAX_HWEVENTS], svalues[MAX_HWEVENTS]; + int n_alt[MAX_HWEVENTS], choice[MAX_HWEVENTS]; + int i, j; + unsigned long addf = ppmu->add_fields; + unsigned long tadd = ppmu->test_adder; + + if (n_ev > ppmu->n_counter) + return -1; + + /* First see if the events will go on as-is */ + for (i = 0; i < n_ev; ++i) { + if ((cflags[i] & PPMU_LIMITED_PMC_REQD) + && !ppmu->limited_pmc_event(event_id[i])) { + ppmu->get_alternatives(event_id[i], cflags[i], + cpuhw->alternatives[i]); + event_id[i] = cpuhw->alternatives[i][0]; + } + if (ppmu->get_constraint(event_id[i], &cpuhw->amasks[i][0], + &cpuhw->avalues[i][0])) + return -1; + } + value = mask = 0; + for (i = 0; i < n_ev; ++i) { + nv = (value | cpuhw->avalues[i][0]) + + (value & cpuhw->avalues[i][0] & addf); + if ((((nv + tadd) ^ value) & mask) != 0 || + (((nv + tadd) ^ cpuhw->avalues[i][0]) & + cpuhw->amasks[i][0]) != 0) + break; + value = nv; + mask |= cpuhw->amasks[i][0]; + } + if (i == n_ev) + return 0; /* all OK */ + + /* doesn't work, gather alternatives... */ + if (!ppmu->get_alternatives) + return -1; + for (i = 0; i < n_ev; ++i) { + choice[i] = 0; + n_alt[i] = ppmu->get_alternatives(event_id[i], cflags[i], + cpuhw->alternatives[i]); + for (j = 1; j < n_alt[i]; ++j) + ppmu->get_constraint(cpuhw->alternatives[i][j], + &cpuhw->amasks[i][j], + &cpuhw->avalues[i][j]); + } + + /* enumerate all possibilities and see if any will work */ + i = 0; + j = -1; + value = mask = nv = 0; + while (i < n_ev) { + if (j >= 0) { + /* we're backtracking, restore context */ + value = svalues[i]; + mask = smasks[i]; + j = choice[i]; + } + /* + * See if any alternative k for event_id i, + * where k > j, will satisfy the constraints. + */ + while (++j < n_alt[i]) { + nv = (value | cpuhw->avalues[i][j]) + + (value & cpuhw->avalues[i][j] & addf); + if ((((nv + tadd) ^ value) & mask) == 0 && + (((nv + tadd) ^ cpuhw->avalues[i][j]) + & cpuhw->amasks[i][j]) == 0) + break; + } + if (j >= n_alt[i]) { + /* + * No feasible alternative, backtrack + * to event_id i-1 and continue enumerating its + * alternatives from where we got up to. + */ + if (--i < 0) + return -1; + } else { + /* + * Found a feasible alternative for event_id i, + * remember where we got up to with this event_id, + * go on to the next event_id, and start with + * the first alternative for it. + */ + choice[i] = j; + svalues[i] = value; + smasks[i] = mask; + value = nv; + mask |= cpuhw->amasks[i][j]; + ++i; + j = -1; + } + } + + /* OK, we have a feasible combination, tell the caller the solution */ + for (i = 0; i < n_ev; ++i) + event_id[i] = cpuhw->alternatives[i][choice[i]]; + return 0; +} +","@@ -1269,6 +1269,28 @@ unsigned long perf_instruction_pointer(struct pt_regs *regs) + return ip; + } + ++static bool pmc_overflow(unsigned long val) ++{ ++ if ((int)val < 0) ++ return true; ++ ++ /* ++ * Events on POWER7 can roll back if a speculative event doesn't ++ * eventually complete. Unfortunately in some rare cases they will ++ * raise a performance monitor exception. We need to catch this to ++ * ensure we reset the PMC. In all cases the PMC will be 256 or less ++ * cycles from overflow. ++ * ++ * We only do this if the first pass fails to find any overflowing ++ * PMCs because a user might set a period of less than 256 and we ++ * don't want to mistakenly reset them. ++ */ ++ if (__is_processor(PV_POWER7) && ((0x80000000 - val) <= 256)) ++ return true; ++ ++ return false; ++} ++ + /* + * Performance monitor interrupt stuff + */ +@@ -1316,7 +1338,7 @@ static void perf_event_interrupt(struct pt_regs *regs) + if (is_limited_pmc(i + 1)) + continue; + val = read_pmc(i + 1); +- if ((int)val < 0) ++ if (pmc_overflow(val)) + write_pmc(i + 1, 0); + } + }",981,1312,2048 +3996,"int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule, + struct audit_context *actx) +{ + struct context *ctxt; + struct mls_level *level; + struct selinux_audit_rule *rule = vrule; + int match = 0; + + if (!rule) { + audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR, + ""selinux_audit_rule_match: missing rule\n""); + return -ENOENT; + } + + read_lock(&policy_rwlock); + + if (rule->au_seqno < latest_granting) { + audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR, + ""selinux_audit_rule_match: stale rule\n""); + match = -ESTALE; + goto out; + } + + ctxt = sidtab_search(&sidtab, sid); + if (!ctxt) { + audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR, + ""selinux_audit_rule_match: unrecognized SID %d\n"", + sid); + match = -ENOENT; + goto out; + } + + /* a field/op pair that is not caught here will simply fall through + without a match */ + switch (field) { + case AUDIT_SUBJ_USER: + case AUDIT_OBJ_USER: + switch (op) { + case Audit_equal: + match = (ctxt->user == rule->au_ctxt.user); + break; + case Audit_not_equal: + match = (ctxt->user != rule->au_ctxt.user); + break; + } + break; + case AUDIT_SUBJ_ROLE: + case AUDIT_OBJ_ROLE: + switch (op) { + case Audit_equal: + match = (ctxt->role == rule->au_ctxt.role); + break; + case Audit_not_equal: + match = (ctxt->role != rule->au_ctxt.role); + break; + } + break; + case AUDIT_SUBJ_TYPE: + case AUDIT_OBJ_TYPE: + switch (op) { + case Audit_equal: + match = (ctxt->type == rule->au_ctxt.type); + break; + case Audit_not_equal: + match = (ctxt->type != rule->au_ctxt.type); + break; + } + break; + case AUDIT_SUBJ_SEN: + case AUDIT_SUBJ_CLR: + case AUDIT_OBJ_LEV_LOW: + case AUDIT_OBJ_LEV_HIGH: + level = ((field == AUDIT_SUBJ_SEN || + field == AUDIT_OBJ_LEV_LOW) ? + &ctxt->range.level[0] : &ctxt->range.level[1]); + switch (op) { + case Audit_equal: + match = mls_level_eq(&rule->au_ctxt.range.level[0], + level); + break; + case Audit_not_equal: + match = !mls_level_eq(&rule->au_ctxt.range.level[0], + level); + break; + case Audit_lt: + match = (mls_level_dom(&rule->au_ctxt.range.level[0], + level) && + !mls_level_eq(&rule->au_ctxt.range.level[0], + level)); + break; + case Audit_le: + match = mls_level_dom(&rule->au_ctxt.range.level[0], + level); + break; + case Audit_gt: + match = (mls_level_dom(level, + &rule->au_ctxt.range.level[0]) && + !mls_level_eq(level, + &rule->au_ctxt.range.level[0])); + break; + case Audit_ge: + match = mls_level_dom(level, + &rule->au_ctxt.range.level[0]); + break; + } + } + +out: + read_unlock(&policy_rwlock); + return match; +} +",0,"int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule, + struct audit_context *actx) +{ + struct context *ctxt; + struct mls_level *level; + struct selinux_audit_rule *rule = vrule; + int match = 0; + + if (!rule) { + audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR, + ""selinux_audit_rule_match: missing rule\n""); + return -ENOENT; + } + + read_lock(&policy_rwlock); + + if (rule->au_seqno < latest_granting) { + audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR, + ""selinux_audit_rule_match: stale rule\n""); + match = -ESTALE; + goto out; + } + + ctxt = sidtab_search(&sidtab, sid); + if (!ctxt) { + audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR, + ""selinux_audit_rule_match: unrecognized SID %d\n"", + sid); + match = -ENOENT; + goto out; + } + + /* a field/op pair that is not caught here will simply fall through + without a match */ + switch (field) { + case AUDIT_SUBJ_USER: + case AUDIT_OBJ_USER: + switch (op) { + case Audit_equal: + match = (ctxt->user == rule->au_ctxt.user); + break; + case Audit_not_equal: + match = (ctxt->user != rule->au_ctxt.user); + break; + } + break; + case AUDIT_SUBJ_ROLE: + case AUDIT_OBJ_ROLE: + switch (op) { + case Audit_equal: + match = (ctxt->role == rule->au_ctxt.role); + break; + case Audit_not_equal: + match = (ctxt->role != rule->au_ctxt.role); + break; + } + break; + case AUDIT_SUBJ_TYPE: + case AUDIT_OBJ_TYPE: + switch (op) { + case Audit_equal: + match = (ctxt->type == rule->au_ctxt.type); + break; + case Audit_not_equal: + match = (ctxt->type != rule->au_ctxt.type); + break; + } + break; + case AUDIT_SUBJ_SEN: + case AUDIT_SUBJ_CLR: + case AUDIT_OBJ_LEV_LOW: + case AUDIT_OBJ_LEV_HIGH: + level = ((field == AUDIT_SUBJ_SEN || + field == AUDIT_OBJ_LEV_LOW) ? + &ctxt->range.level[0] : &ctxt->range.level[1]); + switch (op) { + case Audit_equal: + match = mls_level_eq(&rule->au_ctxt.range.level[0], + level); + break; + case Audit_not_equal: + match = !mls_level_eq(&rule->au_ctxt.range.level[0], + level); + break; + case Audit_lt: + match = (mls_level_dom(&rule->au_ctxt.range.level[0], + level) && + !mls_level_eq(&rule->au_ctxt.range.level[0], + level)); + break; + case Audit_le: + match = mls_level_dom(&rule->au_ctxt.range.level[0], + level); + break; + case Audit_gt: + match = (mls_level_dom(level, + &rule->au_ctxt.range.level[0]) && + !mls_level_eq(level, + &rule->au_ctxt.range.level[0])); + break; + case Audit_ge: + match = mls_level_dom(level, + &rule->au_ctxt.range.level[0]); + break; + } + } + +out: + read_unlock(&policy_rwlock); + return match; +} +","@@ -1232,6 +1232,10 @@ static int security_context_to_sid_core(const char *scontext, u32 scontext_len, + struct context context; + int rc = 0; + ++ /* An empty security context is never valid. */ ++ if (!scontext_len) ++ return -EINVAL; ++ + if (!ss_initialized) { + int i; + ",774,1105,2048 +1901,"static int kvp_set_ip_info(char *if_name, struct hv_kvp_ipaddr_value *new_val) +{ + int error = 0; + char if_file[128]; + FILE *file; + char cmd[512]; + char *mac_addr; + + /* + * Set the configuration for the specified interface with + * the information provided. Since there is no standard + * way to configure an interface, we will have an external + * script that does the job of configuring the interface and + * flushing the configuration. + * + * The parameters passed to this external script are: + * 1. A configuration file that has the specified configuration. + * + * We will embed the name of the interface in the configuration + * file: ifcfg-ethx (where ethx is the interface name). + * + * The information provided here may be more than what is needed + * in a given distro to configure the interface and so are free + * ignore information that may not be relevant. + * + * Here is the format of the ip configuration file: + * + * HWADDR=macaddr + * IF_NAME=interface name + * DHCP=yes (This is optional; if yes, DHCP is configured) + * + * IPADDR=ipaddr1 + * IPADDR_1=ipaddr2 + * IPADDR_x=ipaddry (where y = x + 1) + * + * NETMASK=netmask1 + * NETMASK_x=netmasky (where y = x + 1) + * + * GATEWAY=ipaddr1 + * GATEWAY_x=ipaddry (where y = x + 1) + * + * DNSx=ipaddrx (where first DNS address is tagged as DNS1 etc) + * + * IPV6 addresses will be tagged as IPV6ADDR, IPV6 gateway will be + * tagged as IPV6_DEFAULTGW and IPV6 NETMASK will be tagged as + * IPV6NETMASK. + * + * The host can specify multiple ipv4 and ipv6 addresses to be + * configured for the interface. Furthermore, the configuration + * needs to be persistent. A subsequent GET call on the interface + * is expected to return the configuration that is set via the SET + * call. + */ + + snprintf(if_file, sizeof(if_file), ""%s%s%s"", KVP_CONFIG_LOC, + ""hyperv/ifcfg-"", if_name); + + file = fopen(if_file, ""w""); + + if (file == NULL) { + syslog(LOG_ERR, ""Failed to open config file""); + return HV_E_FAIL; + } + + /* + * First write out the MAC address. + */ + + mac_addr = kvp_if_name_to_mac(if_name); + if (mac_addr == NULL) { + error = HV_E_FAIL; + goto setval_error; + } + + error = kvp_write_file(file, ""HWADDR"", """", mac_addr); + if (error) + goto setval_error; + + error = kvp_write_file(file, ""IF_NAME"", """", if_name); + if (error) + goto setval_error; + + if (new_val->dhcp_enabled) { + error = kvp_write_file(file, ""DHCP"", """", ""yes""); + if (error) + goto setval_error; + + /* + * We are done!. + */ + goto setval_done; + } + + /* + * Write the configuration for ipaddress, netmask, gateway and + * name servers. + */ + + error = process_ip_string(file, (char *)new_val->ip_addr, IPADDR); + if (error) + goto setval_error; + + error = process_ip_string(file, (char *)new_val->sub_net, NETMASK); + if (error) + goto setval_error; + + error = process_ip_string(file, (char *)new_val->gate_way, GATEWAY); + if (error) + goto setval_error; + + error = process_ip_string(file, (char *)new_val->dns_addr, DNS); + if (error) + goto setval_error; + +setval_done: + free(mac_addr); + fclose(file); + + /* + * Now that we have populated the configuration file, + * invoke the external script to do its magic. + */ + + snprintf(cmd, sizeof(cmd), ""%s %s"", ""hv_set_ifconfig"", if_file); + system(cmd); + return 0; + +setval_error: + syslog(LOG_ERR, ""Failed to write config file""); + free(mac_addr); + fclose(file); + return error; +} +",0,"static int kvp_set_ip_info(char *if_name, struct hv_kvp_ipaddr_value *new_val) +{ + int error = 0; + char if_file[128]; + FILE *file; + char cmd[512]; + char *mac_addr; + + /* + * Set the configuration for the specified interface with + * the information provided. Since there is no standard + * way to configure an interface, we will have an external + * script that does the job of configuring the interface and + * flushing the configuration. + * + * The parameters passed to this external script are: + * 1. A configuration file that has the specified configuration. + * + * We will embed the name of the interface in the configuration + * file: ifcfg-ethx (where ethx is the interface name). + * + * The information provided here may be more than what is needed + * in a given distro to configure the interface and so are free + * ignore information that may not be relevant. + * + * Here is the format of the ip configuration file: + * + * HWADDR=macaddr + * IF_NAME=interface name + * DHCP=yes (This is optional; if yes, DHCP is configured) + * + * IPADDR=ipaddr1 + * IPADDR_1=ipaddr2 + * IPADDR_x=ipaddry (where y = x + 1) + * + * NETMASK=netmask1 + * NETMASK_x=netmasky (where y = x + 1) + * + * GATEWAY=ipaddr1 + * GATEWAY_x=ipaddry (where y = x + 1) + * + * DNSx=ipaddrx (where first DNS address is tagged as DNS1 etc) + * + * IPV6 addresses will be tagged as IPV6ADDR, IPV6 gateway will be + * tagged as IPV6_DEFAULTGW and IPV6 NETMASK will be tagged as + * IPV6NETMASK. + * + * The host can specify multiple ipv4 and ipv6 addresses to be + * configured for the interface. Furthermore, the configuration + * needs to be persistent. A subsequent GET call on the interface + * is expected to return the configuration that is set via the SET + * call. + */ + + snprintf(if_file, sizeof(if_file), ""%s%s%s"", KVP_CONFIG_LOC, + ""hyperv/ifcfg-"", if_name); + + file = fopen(if_file, ""w""); + + if (file == NULL) { + syslog(LOG_ERR, ""Failed to open config file""); + return HV_E_FAIL; + } + + /* + * First write out the MAC address. + */ + + mac_addr = kvp_if_name_to_mac(if_name); + if (mac_addr == NULL) { + error = HV_E_FAIL; + goto setval_error; + } + + error = kvp_write_file(file, ""HWADDR"", """", mac_addr); + if (error) + goto setval_error; + + error = kvp_write_file(file, ""IF_NAME"", """", if_name); + if (error) + goto setval_error; + + if (new_val->dhcp_enabled) { + error = kvp_write_file(file, ""DHCP"", """", ""yes""); + if (error) + goto setval_error; + + /* + * We are done!. + */ + goto setval_done; + } + + /* + * Write the configuration for ipaddress, netmask, gateway and + * name servers. + */ + + error = process_ip_string(file, (char *)new_val->ip_addr, IPADDR); + if (error) + goto setval_error; + + error = process_ip_string(file, (char *)new_val->sub_net, NETMASK); + if (error) + goto setval_error; + + error = process_ip_string(file, (char *)new_val->gate_way, GATEWAY); + if (error) + goto setval_error; + + error = process_ip_string(file, (char *)new_val->dns_addr, DNS); + if (error) + goto setval_error; + +setval_done: + free(mac_addr); + fclose(file); + + /* + * Now that we have populated the configuration file, + * invoke the external script to do its magic. + */ + + snprintf(cmd, sizeof(cmd), ""%s %s"", ""hv_set_ifconfig"", if_file); + system(cmd); + return 0; + +setval_error: + syslog(LOG_ERR, ""Failed to write config file""); + free(mac_addr); + fclose(file); + return error; +} +","@@ -1486,13 +1486,19 @@ int main(void) + len = recvfrom(fd, kvp_recv_buffer, sizeof(kvp_recv_buffer), 0, + addr_p, &addr_l); + +- if (len < 0 || addr.nl_pid) { ++ if (len < 0) { + syslog(LOG_ERR, ""recvfrom failed; pid:%u error:%d %s"", + addr.nl_pid, errno, strerror(errno)); + close(fd); + return -1; + } + ++ if (addr.nl_pid) { ++ syslog(LOG_WARNING, ""Received packet from untrusted pid:%u"", ++ addr.nl_pid); ++ continue; ++ } ++ + incoming_msg = (struct nlmsghdr *)kvp_recv_buffer; + incoming_cn_msg = (struct cn_msg *)NLMSG_DATA(incoming_msg); + hv_msg = (struct hv_kvp_msg *)incoming_cn_msg->data;",948,1279,2048 +17981," dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off, + int num, size_t size, off_t fsize, int *flags, int sh_num) + { + Elf32_Phdr ph32; + Elf64_Phdr ph64; + const char *linking_style = ""statically""; + const char *interp = """"; + unsigned char nbuf[BUFSIZ]; + char ibuf[BUFSIZ]; + ssize_t bufsize; + size_t offset, align, len; + + if (size != xph_sizeof) { + if (file_printf(ms, "", corrupted program header size"") == -1) + return -1; + return 0; + } + + for ( ; num; num--) { + if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) { + file_badread(ms); + return -1; + } + + off += size; + bufsize = 0; + align = 4; + + /* Things we can determine before we seek */ + switch (xph_type) { + case PT_DYNAMIC: + linking_style = ""dynamically""; + break; + case PT_NOTE: + if (sh_num) /* Did this through section headers */ + continue; + if (((align = xph_align) & 0x80000000UL) != 0 || + align < 4) { + if (file_printf(ms, + "", invalid note alignment 0x%lx"", + (unsigned long)align) == -1) + return -1; + align = 4; + } + /*FALLTHROUGH*/ + case PT_INTERP: + len = xph_filesz < sizeof(nbuf) ? xph_filesz + : sizeof(nbuf); + bufsize = pread(fd, nbuf, len, xph_offset); + if (bufsize == -1) { + file_badread(ms); + return -1; + } + break; + default: + if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { + /* Maybe warn here? */ + continue; + } + break; + } + + /* Things we can determine when we seek */ + switch (xph_type) { + case PT_INTERP: + if (bufsize && nbuf[0]) { + nbuf[bufsize - 1] = '\0'; + interp = (const char *)nbuf; + } else + interp = ""*empty*""; + break; + case PT_NOTE: + /* + * This is a PT_NOTE section; loop through all the notes + * in the section. + */ + offset = 0; + for (;;) { + if (offset >= (size_t)bufsize) + break; + offset = donote(ms, nbuf, offset, + (size_t)bufsize, clazz, swap, align, + flags); + if (offset == 0) + break; + } + break; + default: + break; + } + } + if (file_printf(ms, "", %s linked"", linking_style) + == -1) + return -1; + if (interp[0]) + if (file_printf(ms, "", interpreter %s"", + file_printable(ibuf, sizeof(ibuf), interp)) == -1) + return -1; + return 0; +} +",1," dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off, + int num, size_t size, off_t fsize, int sh_num, int *flags, + uint16_t *notecount) + { + Elf32_Phdr ph32; + Elf64_Phdr ph64; + const char *linking_style = ""statically""; + const char *interp = """"; + unsigned char nbuf[BUFSIZ]; + char ibuf[BUFSIZ]; + ssize_t bufsize; + size_t offset, align, len; + + if (size != xph_sizeof) { + if (file_printf(ms, "", corrupted program header size"") == -1) + return -1; + return 0; + } + + for ( ; num; num--) { + if (pread(fd, xph_addr, xph_sizeof, off) < (ssize_t)xph_sizeof) { + file_badread(ms); + return -1; + } + + off += size; + bufsize = 0; + align = 4; + + /* Things we can determine before we seek */ + switch (xph_type) { + case PT_DYNAMIC: + linking_style = ""dynamically""; + break; + case PT_NOTE: + if (sh_num) /* Did this through section headers */ + continue; + if (((align = xph_align) & 0x80000000UL) != 0 || + align < 4) { + if (file_printf(ms, + "", invalid note alignment 0x%lx"", + (unsigned long)align) == -1) + return -1; + align = 4; + } + /*FALLTHROUGH*/ + case PT_INTERP: + len = xph_filesz < sizeof(nbuf) ? xph_filesz + : sizeof(nbuf); + bufsize = pread(fd, nbuf, len, xph_offset); + if (bufsize == -1) { + file_badread(ms); + return -1; + } + break; + default: + if (fsize != SIZE_UNKNOWN && xph_offset > fsize) { + /* Maybe warn here? */ + continue; + } + break; + } + + /* Things we can determine when we seek */ + switch (xph_type) { + case PT_INTERP: + if (bufsize && nbuf[0]) { + nbuf[bufsize - 1] = '\0'; + interp = (const char *)nbuf; + } else + interp = ""*empty*""; + break; + case PT_NOTE: + /* + * This is a PT_NOTE section; loop through all the notes + * in the section. + */ + offset = 0; + for (;;) { + if (offset >= (size_t)bufsize) + break; + offset = donote(ms, nbuf, offset, + (size_t)bufsize, clazz, swap, align, + flags, notecount); + if (offset == 0) + break; + } + break; + default: + break; + } + } + if (file_printf(ms, "", %s linked"", linking_style) + == -1) + return -1; + if (interp[0]) + if (file_printf(ms, "", interpreter %s"", + file_printable(ibuf, sizeof(ibuf), interp)) == -1) + return -1; + return 0; +} +","@@ -27,7 +27,7 @@ + #include ""file.h"" + + #ifndef lint +-FILE_RCSID(""@(#)$File: readelf.c,v 1.114 2014/12/11 14:19:36 christos Exp $"") ++FILE_RCSID(""@(#)$File: readelf.c,v 1.115 2014/12/16 20:53:05 christos Exp $"") + #endif + + #ifdef BUILTIN_ELF +@@ -43,14 +43,14 @@ FILE_RCSID(""@(#)$File: readelf.c,v 1.114 2014/12/11 14:19:36 christos Exp $"") + + #ifdef ELFCORE + private int dophn_core(struct magic_set *, int, int, int, off_t, int, size_t, +- off_t, int *); ++ off_t, int *, uint16_t *); + #endif + private int dophn_exec(struct magic_set *, int, int, int, off_t, int, size_t, +- off_t, int *, int); ++ off_t, int, int *, uint16_t *); + private int doshn(struct magic_set *, int, int, int, off_t, int, size_t, +- off_t, int *, int, int); ++ off_t, int, int, int *, uint16_t *); + private size_t donote(struct magic_set *, void *, size_t, size_t, int, +- int, size_t, int *); ++ int, size_t, int *, uint16_t *); + + #define ELF_ALIGN(a) ((((a) + align - 1) / align) * align) + +@@ -67,7 +67,7 @@ private uint64_t getu64(int, uint64_t); + private int + toomany(struct magic_set *ms, const char *name, uint16_t num) + { +- if (file_printf(ms, "", too many %s header sections (%u)"", name, num ++ if (file_printf(ms, "", too many %s (%u)"", name, num + ) == -1) + return -1; + return 0; +@@ -293,15 +293,19 @@ private const char os_style_names[][8] = { + ""NetBSD"", + }; + +-#define FLAGS_DID_CORE 0x01 +-#define FLAGS_DID_NOTE 0x02 +-#define FLAGS_DID_BUILD_ID 0x04 +-#define FLAGS_DID_CORE_STYLE 0x08 +-#define FLAGS_IS_CORE 0x10 ++#define FLAGS_DID_CORE 0x001 ++#define FLAGS_DID_OS_NOTE 0x002 ++#define FLAGS_DID_BUILD_ID 0x004 ++#define FLAGS_DID_CORE_STYLE 0x008 ++#define FLAGS_DID_NETBSD_PAX 0x010 ++#define FLAGS_DID_NETBSD_MARCH 0x020 ++#define FLAGS_DID_NETBSD_CMODEL 0x040 ++#define FLAGS_DID_NETBSD_UNKNOWN 0x080 ++#define FLAGS_IS_CORE 0x100 + + private int + dophn_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off, +- int num, size_t size, off_t fsize, int *flags) ++ int num, size_t size, off_t fsize, int *flags, uint16_t *notecount) + { + Elf32_Phdr ph32; + Elf64_Phdr ph64; +@@ -347,7 +351,7 @@ dophn_core(struct magic_set *ms, int clazz, int swap, int fd, off_t off, + if (offset >= (size_t)bufsize) + break; + offset = donote(ms, nbuf, offset, (size_t)bufsize, +- clazz, swap, 4, flags); ++ clazz, swap, 4, flags, notecount); + if (offset == 0) + break; + +@@ -477,133 +481,127 @@ do_note_freebsd_version(struct magic_set *ms, int swap, void *v) + } + } + +-private size_t +-donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size, +- int clazz, int swap, size_t align, int *flags) ++private int ++do_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, ++ int swap __attribute__((__unused__)), uint32_t namesz, uint32_t descsz, ++ size_t noff, size_t doff, int *flags) + { +- Elf32_Nhdr nh32; +- Elf64_Nhdr nh64; +- size_t noff, doff; +-#ifdef ELFCORE +- int os_style = -1; +-#endif +- uint32_t namesz, descsz; +- unsigned char *nbuf = CAST(unsigned char *, vbuf); +- char sbuf[512]; +- +- if (xnh_sizeof + offset > size) { +- /* +- * We're out of note headers. +- */ +- return xnh_sizeof + offset; +- } +- +- (void)memcpy(xnh_addr, &nbuf[offset], xnh_sizeof); +- offset += xnh_sizeof; +- +- namesz = xnh_namesz; +- descsz = xnh_descsz; +- if ((namesz == 0) && (descsz == 0)) { +- /* +- * We're out of note headers. +- */ +- return (offset >= size) ? offset : size; +- } +- +- if (namesz & 0x80000000) { +- (void)file_printf(ms, "", bad note name size 0x%lx"", +- (unsigned long)namesz); +- return 0; +- } +- +- if (descsz & 0x80000000) { +- (void)file_printf(ms, "", bad note description size 0x%lx"", +- (unsigned long)descsz); +- return 0; +- } +- +- +- noff = offset; +- doff = ELF_ALIGN(offset + namesz); +- +- if (offset + namesz > size) { +- /* +- * We're past the end of the buffer. +- */ +- return doff; +- } +- +- offset = ELF_ALIGN(doff + descsz); +- if (doff + descsz > size) { +- /* +- * We're past the end of the buffer. +- */ +- return (offset >= size) ? offset : size; ++ if (namesz == 4 && strcmp((char *)&nbuf[noff], ""GNU"") == 0 && ++ type == NT_GNU_BUILD_ID && (descsz == 16 || descsz == 20)) { ++ uint8_t desc[20]; ++ uint32_t i; ++ *flags |= FLAGS_DID_BUILD_ID; ++ if (file_printf(ms, "", BuildID[%s]="", descsz == 16 ? ""md5/uuid"" : ++ ""sha1"") == -1) ++ return 1; ++ (void)memcpy(desc, &nbuf[doff], descsz); ++ for (i = 0; i < descsz; i++) ++ if (file_printf(ms, ""%02x"", desc[i]) == -1) ++ return 1; ++ return 1; + } ++ return 0; ++} + +- if ((*flags & (FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID)) == +- (FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID)) +- goto core; +- ++private int ++do_os_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, ++ int swap, uint32_t namesz, uint32_t descsz, ++ size_t noff, size_t doff, int *flags) ++{ + if (namesz == 5 && strcmp((char *)&nbuf[noff], ""SuSE"") == 0 && +- xnh_type == NT_GNU_VERSION && descsz == 2) { ++ type == NT_GNU_VERSION && descsz == 2) { ++ *flags |= FLAGS_DID_OS_NOTE; + file_printf(ms, "", for SuSE %d.%d"", nbuf[doff], nbuf[doff + 1]); ++ return 1; + } ++ + if (namesz == 4 && strcmp((char *)&nbuf[noff], ""GNU"") == 0 && +- xnh_type == NT_GNU_VERSION && descsz == 16) { ++ type == NT_GNU_VERSION && descsz == 16) { + uint32_t desc[4]; + (void)memcpy(desc, &nbuf[doff], sizeof(desc)); + ++ *flags |= FLAGS_DID_OS_NOTE; + if (file_printf(ms, "", for GNU/"") == -1) +- return size; ++ return 1; + switch (elf_getu32(swap, desc[0])) { + case GNU_OS_LINUX: + if (file_printf(ms, ""Linux"") == -1) +- return size; ++ return 1; + break; + case GNU_OS_HURD: + if (file_printf(ms, ""Hurd"") == -1) +- return size; ++ return 1; + break; + case GNU_OS_SOLARIS: + if (file_printf(ms, ""Solaris"") == -1) +- return size; ++ return 1; + break; + case GNU_OS_KFREEBSD: + if (file_printf(ms, ""kFreeBSD"") == -1) +- return size; ++ return 1; + break; + case GNU_OS_KNETBSD: + if (file_printf(ms, ""kNetBSD"") == -1) +- return size; ++ return 1; + break; + default: + if (file_printf(ms, """") == -1) +- return size; ++ return 1; + } + if (file_printf(ms, "" %d.%d.%d"", elf_getu32(swap, desc[1]), + elf_getu32(swap, desc[2]), elf_getu32(swap, desc[3])) == -1) +- return size; +- *flags |= FLAGS_DID_NOTE; +- return size; ++ return 1; ++ return 1; + } + +- if (namesz == 4 && strcmp((char *)&nbuf[noff], ""GNU"") == 0 && +- xnh_type == NT_GNU_BUILD_ID && (descsz == 16 || descsz == 20)) { +- uint8_t desc[20]; +- uint32_t i; +- if (file_printf(ms, "", BuildID[%s]="", descsz == 16 ? ""md5/uuid"" : +- ""sha1"") == -1) +- return size; +- (void)memcpy(desc, &nbuf[doff], descsz); +- for (i = 0; i < descsz; i++) +- if (file_printf(ms, ""%02x"", desc[i]) == -1) +- return size; +- *flags |= FLAGS_DID_BUILD_ID; ++ if (namesz == 7 && strcmp((char *)&nbuf[noff], ""NetBSD"") == 0) { ++ if (type == NT_NETBSD_VERSION && descsz == 4) { ++ *flags |= FLAGS_DID_OS_NOTE; ++ do_note_netbsd_version(ms, swap, &nbuf[doff]); ++ return 1; ++ } ++ } ++ ++ if (namesz == 8 && strcmp((char *)&nbuf[noff], ""FreeBSD"") == 0) { ++ if (type == NT_FREEBSD_VERSION && descsz == 4) { ++ *flags |= FLAGS_DID_OS_NOTE; ++ do_note_freebsd_version(ms, swap, &nbuf[doff]); ++ return 1; ++ } + } + ++ if (namesz == 8 && strcmp((char *)&nbuf[noff], ""OpenBSD"") == 0 && ++ type == NT_OPENBSD_VERSION && descsz == 4) { ++ *flags |= FLAGS_DID_OS_NOTE; ++ if (file_printf(ms, "", for OpenBSD"") == -1) ++ return 1; ++ /* Content of note is always 0 */ ++ return 1; ++ } ++ ++ if (namesz == 10 && strcmp((char *)&nbuf[noff], ""DragonFly"") == 0 && ++ type == NT_DRAGONFLY_VERSION && descsz == 4) { ++ uint32_t desc; ++ *flags |= FLAGS_DID_OS_NOTE; ++ if (file_printf(ms, "", for DragonFly"") == -1) ++ return 1; ++ (void)memcpy(&desc, &nbuf[doff], sizeof(desc)); ++ desc = elf_getu32(swap, desc); ++ if (file_printf(ms, "" %d.%d.%d"", desc / 100000, ++ desc / 10000 % 10, desc % 10000) == -1) ++ return 1; ++ return 1; ++ } ++ return 0; ++} ++ ++private int ++do_pax_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, ++ int swap, uint32_t namesz, uint32_t descsz, ++ size_t noff, size_t doff, int *flags) ++{ + if (namesz == 4 && strcmp((char *)&nbuf[noff], ""PaX"") == 0 && +- xnh_type == NT_NETBSD_PAX && descsz == 4) { ++ type == NT_NETBSD_PAX && descsz == 4) { + static const char *pax[] = { + ""+mprotect"", + ""-mprotect"", +@@ -616,80 +614,32 @@ donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size, + size_t i; + int did = 0; + ++ *flags |= FLAGS_DID_NETBSD_PAX; + (void)memcpy(&desc, &nbuf[doff], sizeof(desc)); + desc = elf_getu32(swap, desc); + + if (desc && file_printf(ms, "", PaX: "") == -1) +- return size; ++ return 1; + + for (i = 0; i < __arraycount(pax); i++) { + if (((1 << i) & desc) == 0) + continue; + if (file_printf(ms, ""%s%s"", did++ ? "","" : """", + pax[i]) == -1) +- return size; +- } +- } +- +- if (namesz == 7 && strcmp((char *)&nbuf[noff], ""NetBSD"") == 0) { +- switch (xnh_type) { +- case NT_NETBSD_VERSION: +- if (descsz == 4) { +- do_note_netbsd_version(ms, swap, &nbuf[doff]); +- *flags |= FLAGS_DID_NOTE; +- return size; +- } +- break; +- case NT_NETBSD_MARCH: +- if (file_printf(ms, "", compiled for: %.*s"", (int)descsz, +- (const char *)&nbuf[doff]) == -1) +- return size; +- break; +- case NT_NETBSD_CMODEL: +- if (file_printf(ms, "", compiler model: %.*s"", +- (int)descsz, (const char *)&nbuf[doff]) == -1) +- return size; +- break; +- default: +- if (file_printf(ms, "", note=%u"", xnh_type) == -1) +- return size; +- break; +- } +- return size; +- } +- +- if (namesz == 8 && strcmp((char *)&nbuf[noff], ""FreeBSD"") == 0) { +- if (xnh_type == NT_FREEBSD_VERSION && descsz == 4) { +- do_note_freebsd_version(ms, swap, &nbuf[doff]); +- *flags |= FLAGS_DID_NOTE; +- return size; ++ return 1; + } ++ return 1; + } ++ return 0; ++} + +- if (namesz == 8 && strcmp((char *)&nbuf[noff], ""OpenBSD"") == 0 && +- xnh_type == NT_OPENBSD_VERSION && descsz == 4) { +- if (file_printf(ms, "", for OpenBSD"") == -1) +- return size; +- /* Content of note is always 0 */ +- *flags |= FLAGS_DID_NOTE; +- return size; +- } +- +- if (namesz == 10 && strcmp((char *)&nbuf[noff], ""DragonFly"") == 0 && +- xnh_type == NT_DRAGONFLY_VERSION && descsz == 4) { +- uint32_t desc; +- if (file_printf(ms, "", for DragonFly"") == -1) +- return size; +- (void)memcpy(&desc, &nbuf[doff], sizeof(desc)); +- desc = elf_getu32(swap, desc); +- if (file_printf(ms, "" %d.%d.%d"", desc / 100000, +- desc / 10000 % 10, desc % 10000) == -1) +- return size; +- *flags |= FLAGS_DID_NOTE; +- return size; +- } +- +-core: ++private int ++do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, ++ int swap, uint32_t namesz, uint32_t descsz, ++ size_t noff, size_t doff, int *flags, size_t size, int clazz) ++{ ++#ifdef ELFCORE ++ int os_style = -1; + /* + * Sigh. The 2.0.36 kernel in Debian 2.1, at + * least, doesn't correctly implement name +@@ -718,20 +668,17 @@ donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size, + os_style = OS_STYLE_NETBSD; + } + +-#ifdef ELFCORE +- if ((*flags & FLAGS_DID_CORE) != 0) +- return size; +- + if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) { + if (file_printf(ms, "", %s-style"", os_style_names[os_style]) + == -1) +- return size; ++ return 1; + *flags |= FLAGS_DID_CORE_STYLE; + } + + switch (os_style) { + case OS_STYLE_NETBSD: +- if (xnh_type == NT_NETBSD_CORE_PROCINFO) { ++ if (type == NT_NETBSD_CORE_PROCINFO) { ++ char sbuf[512]; + uint32_t signo; + /* + * Extract the program name. It is at +@@ -741,7 +688,7 @@ donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size, + if (file_printf(ms, "", from '%.31s'"", + file_printable(sbuf, sizeof(sbuf), + (const char *)&nbuf[doff + 0x7c])) == -1) +- return size; ++ return 1; + + /* + * Extract the signal number. It is at +@@ -751,14 +698,14 @@ donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size, + sizeof(signo)); + if (file_printf(ms, "" (signal %u)"", + elf_getu32(swap, signo)) == -1) +- return size; ++ return 1; + *flags |= FLAGS_DID_CORE; +- return size; ++ return 1; + } + break; + + default: +- if (xnh_type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) { ++ if (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) { + size_t i, j; + unsigned char c; + /* +@@ -826,7 +773,7 @@ donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size, + * Try next offsets, in case this match is + * in the middle of a string. + */ +- for (k = i + 1 ; k < NOFFSETS ; k++) { ++ for (k = i + 1 ; k < NOFFSETS; k++) { + size_t no; + int adjust = 1; + if (prpsoffsets(k) >= prpsoffsets(i)) +@@ -851,9 +798,9 @@ donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size, + cp--; + if (file_printf(ms, "", from '%.*s'"", + (int)(cp - cname), cname) == -1) +- return size; ++ return 1; + *flags |= FLAGS_DID_CORE; +- return size; ++ return 1; + + tryanother: + ; +@@ -862,6 +809,124 @@ donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size, + break; + } + #endif ++ return 0; ++} ++ ++private size_t ++donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size, ++ int clazz, int swap, size_t align, int *flags, uint16_t *notecount) ++{ ++ Elf32_Nhdr nh32; ++ Elf64_Nhdr nh64; ++ size_t noff, doff; ++ uint32_t namesz, descsz; ++ unsigned char *nbuf = CAST(unsigned char *, vbuf); ++ ++ if (*notecount == 0) ++ return 0; ++ --*notecount; ++ ++ if (xnh_sizeof + offset > size) { ++ /* ++ * We're out of note headers. ++ */ ++ return xnh_sizeof + offset; ++ } ++ ++ (void)memcpy(xnh_addr, &nbuf[offset], xnh_sizeof); ++ offset += xnh_sizeof; ++ ++ namesz = xnh_namesz; ++ descsz = xnh_descsz; ++ if ((namesz == 0) && (descsz == 0)) { ++ /* ++ * We're out of note headers. ++ */ ++ return (offset >= size) ? offset : size; ++ } ++ ++ if (namesz & 0x80000000) { ++ (void)file_printf(ms, "", bad note name size 0x%lx"", ++ (unsigned long)namesz); ++ return 0; ++ } ++ ++ if (descsz & 0x80000000) { ++ (void)file_printf(ms, "", bad note description size 0x%lx"", ++ (unsigned long)descsz); ++ return 0; ++ } ++ ++ noff = offset; ++ doff = ELF_ALIGN(offset + namesz); ++ ++ if (offset + namesz > size) { ++ /* ++ * We're past the end of the buffer. ++ */ ++ return doff; ++ } ++ ++ offset = ELF_ALIGN(doff + descsz); ++ if (doff + descsz > size) { ++ /* ++ * We're past the end of the buffer. ++ */ ++ return (offset >= size) ? offset : size; ++ } ++ ++ if ((*flags & FLAGS_DID_OS_NOTE) == 0) { ++ if (do_os_note(ms, nbuf, xnh_type, swap, ++ namesz, descsz, noff, doff, flags)) ++ return size; ++ } ++ ++ if ((*flags & FLAGS_DID_BUILD_ID) == 0) { ++ if (do_bid_note(ms, nbuf, xnh_type, swap, ++ namesz, descsz, noff, doff, flags)) ++ return size; ++ } ++ ++ if ((*flags & FLAGS_DID_NETBSD_PAX) == 0) { ++ if (do_pax_note(ms, nbuf, xnh_type, swap, ++ namesz, descsz, noff, doff, flags)) ++ return size; ++ } ++ ++ if ((*flags & FLAGS_DID_CORE) == 0) { ++ if (do_core_note(ms, nbuf, xnh_type, swap, ++ namesz, descsz, noff, doff, flags, size, clazz)) ++ return size; ++ } ++ ++ if (namesz == 7 && strcmp((char *)&nbuf[noff], ""NetBSD"") == 0) { ++ switch (xnh_type) { ++ case NT_NETBSD_VERSION: ++ return size; ++ case NT_NETBSD_MARCH: ++ if (*flags & FLAGS_DID_NETBSD_MARCH) ++ return size; ++ if (file_printf(ms, "", compiled for: %.*s"", (int)descsz, ++ (const char *)&nbuf[doff]) == -1) ++ return size; ++ break; ++ case NT_NETBSD_CMODEL: ++ if (*flags & FLAGS_DID_NETBSD_CMODEL) ++ return size; ++ if (file_printf(ms, "", compiler model: %.*s"", ++ (int)descsz, (const char *)&nbuf[doff]) == -1) ++ return size; ++ break; ++ default: ++ if (*flags & FLAGS_DID_NETBSD_UNKNOWN) ++ return size; ++ if (file_printf(ms, "", note=%u"", xnh_type) == -1) ++ return size; ++ break; ++ } ++ return size; ++ } ++ + return offset; + } + +@@ -917,7 +982,8 @@ static const cap_desc_t cap_desc_386[] = { + + private int + doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, +- size_t size, off_t fsize, int *flags, int mach, int strtab) ++ size_t size, off_t fsize, int mach, int strtab, int *flags, ++ uint16_t *notecount) + { + Elf32_Shdr sh32; + Elf64_Shdr sh64; +@@ -994,7 +1060,7 @@ doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, + if (noff >= (off_t)xsh_size) + break; + noff = donote(ms, nbuf, (size_t)noff, +- xsh_size, clazz, swap, 4, flags); ++ xsh_size, clazz, swap, 4, flags, notecount); + if (noff == 0) + break; + } +@@ -1161,7 +1227,8 @@ doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, + */ + private int + dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off, +- int num, size_t size, off_t fsize, int *flags, int sh_num) ++ int num, size_t size, off_t fsize, int sh_num, int *flags, ++ uint16_t *notecount) + { + Elf32_Phdr ph32; + Elf64_Phdr ph64; +@@ -1242,7 +1309,7 @@ dophn_exec(struct magic_set *ms, int clazz, int swap, int fd, off_t off, + break; + offset = donote(ms, nbuf, offset, + (size_t)bufsize, clazz, swap, align, +- flags); ++ flags, notecount); + if (offset == 0) + break; + } +@@ -1277,7 +1344,7 @@ file_tryelf(struct magic_set *ms, int fd, const unsigned char *buf, + int flags = 0; + Elf32_Ehdr elf32hdr; + Elf64_Ehdr elf64hdr; +- uint16_t type, phnum, shnum; ++ uint16_t type, phnum, shnum, notecount; + + if (ms->flags & (MAGIC_MIME|MAGIC_APPLE)) + return 0;",744,1075,2048 +4450,"__xml_build_changes(xmlNode * xml, xmlNode *patchset) +{ + xmlNode *cIter = NULL; + xmlAttr *pIter = NULL; + xmlNode *change = NULL; + xml_private_t *p = xml->_private; + + if(patchset && is_set(p->flags, xpf_created)) { + int offset = 0; + char buffer[XML_BUFFER_SIZE]; + + if(__get_prefix(NULL, xml->parent, buffer, offset) > 0) { + int position = __xml_offset_no_deletions(xml); + + change = create_xml_node(patchset, XML_DIFF_CHANGE); + + crm_xml_add(change, XML_DIFF_OP, ""create""); + crm_xml_add(change, XML_DIFF_PATH, buffer); + crm_xml_add_int(change, XML_DIFF_POSITION, position); + add_node_copy(change, xml); + } + + return; + } + + for (pIter = crm_first_attr(xml); pIter != NULL; pIter = pIter->next) { + xmlNode *attr = NULL; + + p = pIter->_private; + if(is_not_set(p->flags, xpf_deleted) && is_not_set(p->flags, xpf_dirty)) { + continue; + } + + if(change == NULL) { + int offset = 0; + char buffer[XML_BUFFER_SIZE]; + + if(__get_prefix(NULL, xml, buffer, offset) > 0) { + change = create_xml_node(patchset, XML_DIFF_CHANGE); + + crm_xml_add(change, XML_DIFF_OP, ""modify""); + crm_xml_add(change, XML_DIFF_PATH, buffer); + + change = create_xml_node(change, XML_DIFF_LIST); + } + } + + attr = create_xml_node(change, XML_DIFF_ATTR); + + crm_xml_add(attr, XML_NVPAIR_ATTR_NAME, (const char *)pIter->name); + if(p->flags & xpf_deleted) { + crm_xml_add(attr, XML_DIFF_OP, ""unset""); + + } else { + const char *value = crm_element_value(xml, (const char *)pIter->name); + + crm_xml_add(attr, XML_DIFF_OP, ""set""); + crm_xml_add(attr, XML_NVPAIR_ATTR_VALUE, value); + } + } + + if(change) { + xmlNode *result = NULL; + + change = create_xml_node(change->parent, XML_DIFF_RESULT); + result = create_xml_node(change, (const char *)xml->name); + + for (pIter = crm_first_attr(xml); pIter != NULL; pIter = pIter->next) { + const char *value = crm_element_value(xml, (const char *)pIter->name); + + p = pIter->_private; + if (is_not_set(p->flags, xpf_deleted)) { + crm_xml_add(result, (const char *)pIter->name, value); + } + } + } + + for (cIter = __xml_first_child(xml); cIter != NULL; cIter = __xml_next(cIter)) { + __xml_build_changes(cIter, patchset); + } + + p = xml->_private; + if(patchset && is_set(p->flags, xpf_moved)) { + int offset = 0; + char buffer[XML_BUFFER_SIZE]; + + crm_trace(""%s.%s moved to position %d"", xml->name, ID(xml), __xml_offset(xml)); + if(__get_prefix(NULL, xml, buffer, offset) > 0) { + change = create_xml_node(patchset, XML_DIFF_CHANGE); + + crm_xml_add(change, XML_DIFF_OP, ""move""); + crm_xml_add(change, XML_DIFF_PATH, buffer); + crm_xml_add_int(change, XML_DIFF_POSITION, __xml_offset_no_deletions(xml)); + } + } +} +",0,"__xml_build_changes(xmlNode * xml, xmlNode *patchset) +{ + xmlNode *cIter = NULL; + xmlAttr *pIter = NULL; + xmlNode *change = NULL; + xml_private_t *p = xml->_private; + + if(patchset && is_set(p->flags, xpf_created)) { + int offset = 0; + char buffer[XML_BUFFER_SIZE]; + + if(__get_prefix(NULL, xml->parent, buffer, offset) > 0) { + int position = __xml_offset_no_deletions(xml); + + change = create_xml_node(patchset, XML_DIFF_CHANGE); + + crm_xml_add(change, XML_DIFF_OP, ""create""); + crm_xml_add(change, XML_DIFF_PATH, buffer); + crm_xml_add_int(change, XML_DIFF_POSITION, position); + add_node_copy(change, xml); + } + + return; + } + + for (pIter = crm_first_attr(xml); pIter != NULL; pIter = pIter->next) { + xmlNode *attr = NULL; + + p = pIter->_private; + if(is_not_set(p->flags, xpf_deleted) && is_not_set(p->flags, xpf_dirty)) { + continue; + } + + if(change == NULL) { + int offset = 0; + char buffer[XML_BUFFER_SIZE]; + + if(__get_prefix(NULL, xml, buffer, offset) > 0) { + change = create_xml_node(patchset, XML_DIFF_CHANGE); + + crm_xml_add(change, XML_DIFF_OP, ""modify""); + crm_xml_add(change, XML_DIFF_PATH, buffer); + + change = create_xml_node(change, XML_DIFF_LIST); + } + } + + attr = create_xml_node(change, XML_DIFF_ATTR); + + crm_xml_add(attr, XML_NVPAIR_ATTR_NAME, (const char *)pIter->name); + if(p->flags & xpf_deleted) { + crm_xml_add(attr, XML_DIFF_OP, ""unset""); + + } else { + const char *value = crm_element_value(xml, (const char *)pIter->name); + + crm_xml_add(attr, XML_DIFF_OP, ""set""); + crm_xml_add(attr, XML_NVPAIR_ATTR_VALUE, value); + } + } + + if(change) { + xmlNode *result = NULL; + + change = create_xml_node(change->parent, XML_DIFF_RESULT); + result = create_xml_node(change, (const char *)xml->name); + + for (pIter = crm_first_attr(xml); pIter != NULL; pIter = pIter->next) { + const char *value = crm_element_value(xml, (const char *)pIter->name); + + p = pIter->_private; + if (is_not_set(p->flags, xpf_deleted)) { + crm_xml_add(result, (const char *)pIter->name, value); + } + } + } + + for (cIter = __xml_first_child(xml); cIter != NULL; cIter = __xml_next(cIter)) { + __xml_build_changes(cIter, patchset); + } + + p = xml->_private; + if(patchset && is_set(p->flags, xpf_moved)) { + int offset = 0; + char buffer[XML_BUFFER_SIZE]; + + crm_trace(""%s.%s moved to position %d"", xml->name, ID(xml), __xml_offset(xml)); + if(__get_prefix(NULL, xml, buffer, offset) > 0) { + change = create_xml_node(patchset, XML_DIFF_CHANGE); + + crm_xml_add(change, XML_DIFF_OP, ""move""); + crm_xml_add(change, XML_DIFF_PATH, buffer); + crm_xml_add_int(change, XML_DIFF_POSITION, __xml_offset_no_deletions(xml)); + } + } +} +","@@ -1020,13 +1020,16 @@ __xml_acl_post_process(xmlNode * xml) + + if(is_set(p->flags, xpf_created)) { + xmlAttr *xIter = NULL; ++ char *path = xml_get_path(xml); + +- /* Always allow new scaffolding, ie. node with no attributes or only an 'id' */ ++ /* Always allow new scaffolding, ie. node with no attributes or only an 'id' ++ * Except in the ACLs section ++ */ + + for (xIter = crm_first_attr(xml); xIter != NULL; xIter = xIter->next) { + const char *prop_name = (const char *)xIter->name; + +- if (strcmp(prop_name, XML_ATTR_ID) == 0) { ++ if (strcmp(prop_name, XML_ATTR_ID) == 0 && strstr(path, ""/""XML_CIB_TAG_ACLS""/"") == NULL) { + /* Delay the acl check */ + continue; + +@@ -1035,7 +1038,6 @@ __xml_acl_post_process(xmlNode * xml) + break; + + } else { +- char *path = xml_get_path(xml); + crm_trace(""Cannot add new node %s at %s"", crm_element_name(xml), path); + + if(xml != xmlDocGetRootElement(xml->doc)) { +@@ -1046,6 +1048,7 @@ __xml_acl_post_process(xmlNode * xml) + return; + } + } ++ free(path); + } + + while (cIter != NULL) {",799,1130,2048 +18571,"ResourceFetcher::DetermineRevalidationPolicy(Resource::Type type, + const FetchRequest& fetch_request, + Resource* existing_resource, + bool is_static_data) const { + const ResourceRequest& request = fetch_request.GetResourceRequest(); + + if (!existing_resource) + return kLoad; + + if (existing_resource->Loader() && + existing_resource->Loader()->Fetcher() != this) { + return kReload; + } + + RecordSriResourceIntegrityMismatchEvent(kCheckingForIntegrityMismatch); + if (existing_resource->MustRefetchDueToIntegrityMetadata(fetch_request)) { + RecordSriResourceIntegrityMismatchEvent(kRefetchDueToIntegrityMismatch); + return kReload; + } + + if (existing_resource->GetResponse().WasFallbackRequiredByServiceWorker()) + return kReload; + + if (existing_resource->GetType() != type) { + RESOURCE_LOADING_DVLOG(1) << ""ResourceFetcher::determineRevalidationPolicy "" + ""reloading due to type mismatch.""; + return kReload; + } + + if (fetch_request.IsSpeculativePreload() && existing_resource->IsPreloaded()) + return kUse; + + if (existing_resource->IsImage() && + !Context().AllowImage(images_enabled_, existing_resource->Url())) { + return kReload; + } + + if (request.DownloadToFile() || request.UseStreamOnResponse()) + return kReload; + + if (existing_resource->GetResponse().WasFetchedViaServiceWorker() && + existing_resource->GetResponse().ServiceWorkerResponseType() == + kWebServiceWorkerResponseTypeOpaque && + request.GetFetchRequestMode() != WebURLRequest::kFetchRequestModeNoCORS) { + return kReload; + } + + if (is_static_data) + return kUse; + + if (!existing_resource->CanReuse(fetch_request)) + return kReload; + + if (request.IsConditional() || + existing_resource->GetResponse().HttpStatusCode() == 304) { + return kReload; + } + + if (allow_stale_resources_) + return kUse; + + if (!fetch_request.Options().CanReuseRequest(existing_resource->Options())) + return kReload; + + if (existing_resource->IsPreloaded()) + return kUse; + + if (request.GetCachePolicy() == WebCachePolicy::kReturnCacheDataElseLoad) + return kUse; + + if (existing_resource->HasCacheControlNoStoreHeader()) { + RESOURCE_LOADING_DVLOG(1) << ""ResourceFetcher::determineRevalidationPolicy "" + ""reloading due to Cache-control: no-store.""; + return kReload; + } + + if (existing_resource->GetResourceRequest().AllowStoredCredentials() != + request.AllowStoredCredentials()) { + RESOURCE_LOADING_DVLOG(1) << ""ResourceFetcher::determineRevalidationPolicy "" + ""reloading due to difference in credentials "" + ""settings.""; + return kReload; + } + + if (type != Resource::kRaw) { + if (!Context().IsLoadComplete() && + validated_ur_ls_.Contains(existing_resource->Url())) + return kUse; + if (existing_resource->IsLoading()) + return kUse; + } + + if (request.GetCachePolicy() == WebCachePolicy::kBypassingCache) { + RESOURCE_LOADING_DVLOG(1) << ""ResourceFetcher::determineRevalidationPolicy "" + ""reloading due to "" + ""WebCachePolicy::BypassingCache.""; + return kReload; + } + + if (existing_resource->ErrorOccurred()) { + RESOURCE_LOADING_DVLOG(1) << ""ResourceFetcher::determineRevalidationPolicy "" + ""reloading due to resource being in the error "" + ""state""; + return kReload; + } + + if (type == Resource::kImage && + existing_resource == CachedResource(request.Url())) { + return kUse; + } + + if (existing_resource->MustReloadDueToVaryHeader(request)) + return kReload; + + if (!existing_resource->CanReuseRedirectChain()) { + RESOURCE_LOADING_DVLOG(1) << ""ResourceFetcher::determineRevalidationPolicy "" + ""reloading due to an uncacheable redirect""; + return kReload; + } + + if (request.GetCachePolicy() == WebCachePolicy::kValidatingCacheData || + existing_resource->MustRevalidateDueToCacheHeaders() || + request.CacheControlContainsNoCache()) { + if (existing_resource->CanUseCacheValidator() && + !Context().IsControlledByServiceWorker()) { + if (existing_resource->IsCacheValidator()) { + DCHECK(existing_resource->StillNeedsLoad()); + return kUse; + } + return kRevalidate; + } + + RESOURCE_LOADING_DVLOG(1) << ""ResourceFetcher::determineRevalidationPolicy "" + ""reloading due to missing cache validators.""; + return kReload; + } + + return kUse; +} +",1,"ResourceFetcher::DetermineRevalidationPolicy(Resource::Type type, + const FetchRequest& fetch_request, + Resource* existing_resource, + bool is_static_data) const { + const ResourceRequest& request = fetch_request.GetResourceRequest(); + + if (!existing_resource) + return kLoad; + + if (existing_resource->Loader() && + existing_resource->Loader()->Fetcher() != this) { + return kReload; + } + + RecordSriResourceIntegrityMismatchEvent(kCheckingForIntegrityMismatch); + if (existing_resource->MustRefetchDueToIntegrityMetadata(fetch_request)) { + RecordSriResourceIntegrityMismatchEvent(kRefetchDueToIntegrityMismatch); + return kReload; + } + + if (existing_resource->GetResponse().WasFallbackRequiredByServiceWorker()) + return kReload; + + if (existing_resource->GetType() != type) { + RESOURCE_LOADING_DVLOG(1) << ""ResourceFetcher::determineRevalidationPolicy "" + ""reloading due to type mismatch.""; + return kReload; + } + + if (fetch_request.IsSpeculativePreload() && existing_resource->IsPreloaded()) + return kUse; + + if (existing_resource->IsImage() && + !Context().AllowImage(images_enabled_, existing_resource->Url())) { + return kReload; + } + + if (request.DownloadToFile() || request.UseStreamOnResponse()) + return kReload; + + if (existing_resource->GetResponse().WasFetchedViaServiceWorker() && + existing_resource->GetResponse().ServiceWorkerResponseType() == + kWebServiceWorkerResponseTypeOpaque && + request.GetFetchRequestMode() != WebURLRequest::kFetchRequestModeNoCORS) { + return kReload; + } + + if (is_static_data) + return kUse; + + if (!existing_resource->CanReuse(fetch_request)) + return kReload; + + if (request.IsConditional() || + existing_resource->GetResponse().HttpStatusCode() == 304) { + return kReload; + } + + if (allow_stale_resources_) + return kUse; + + if (!fetch_request.Options().CanReuseRequest(existing_resource->Options())) + return kReload; + + if (existing_resource->IsPreloaded()) + return kUse; + + if (request.GetCachePolicy() == WebCachePolicy::kReturnCacheDataElseLoad) + return kUse; + + if (existing_resource->HasCacheControlNoStoreHeader()) { + RESOURCE_LOADING_DVLOG(1) << ""ResourceFetcher::determineRevalidationPolicy "" + ""reloading due to Cache-control: no-store.""; + return kReload; + } + + if (existing_resource->GetResourceRequest().AllowStoredCredentials() != + request.AllowStoredCredentials()) { + RESOURCE_LOADING_DVLOG(1) << ""ResourceFetcher::determineRevalidationPolicy "" + ""reloading due to difference in credentials "" + ""settings.""; + return kReload; + } + + if (type != Resource::kRaw) { + if (!Context().IsLoadComplete() && + validated_urls_.Contains(existing_resource->Url())) + return kUse; + if (existing_resource->IsLoading()) + return kUse; + } + + if (request.GetCachePolicy() == WebCachePolicy::kBypassingCache) { + RESOURCE_LOADING_DVLOG(1) << ""ResourceFetcher::determineRevalidationPolicy "" + ""reloading due to "" + ""WebCachePolicy::BypassingCache.""; + return kReload; + } + + if (existing_resource->ErrorOccurred()) { + RESOURCE_LOADING_DVLOG(1) << ""ResourceFetcher::determineRevalidationPolicy "" + ""reloading due to resource being in the error "" + ""state""; + return kReload; + } + + if (type == Resource::kImage && + existing_resource == CachedResource(request.Url())) { + return kUse; + } + + if (existing_resource->MustReloadDueToVaryHeader(request)) + return kReload; + + if (!existing_resource->CanReuseRedirectChain()) { + RESOURCE_LOADING_DVLOG(1) << ""ResourceFetcher::determineRevalidationPolicy "" + ""reloading due to an uncacheable redirect""; + return kReload; + } + + if (request.GetCachePolicy() == WebCachePolicy::kValidatingCacheData || + existing_resource->MustRevalidateDueToCacheHeaders() || + request.CacheControlContainsNoCache()) { + if (existing_resource->CanUseCacheValidator() && + !Context().IsControlledByServiceWorker()) { + if (existing_resource->IsCacheValidator()) { + DCHECK(existing_resource->StillNeedsLoad()); + return kUse; + } + return kRevalidate; + } + + RESOURCE_LOADING_DVLOG(1) << ""ResourceFetcher::determineRevalidationPolicy "" + ""reloading due to missing cache validators.""; + return kReload; + } + + return kUse; +} +","@@ -305,7 +305,7 @@ void ResourceFetcher::RequestLoadStarted(unsigned long identifier, + RevalidationPolicy policy, + bool is_static_data) { + if (policy == kUse && resource->GetStatus() == ResourceStatus::kCached && +- !validated_ur_ls_.Contains(resource->Url())) { ++ !validated_urls_.Contains(resource->Url())) { + // Loaded from MemoryCache. + DidLoadResourceFromMemoryCache(identifier, resource, + request.GetResourceRequest()); +@@ -315,7 +315,7 @@ void ResourceFetcher::RequestLoadStarted(unsigned long identifier, + return; + + if (policy == kUse && !resource->StillNeedsLoad() && +- !validated_ur_ls_.Contains(request.GetResourceRequest().Url())) { ++ !validated_urls_.Contains(request.GetResourceRequest().Url())) { + // Resources loaded from memory cache should be reported the first time + // they're used. + RefPtr info = ResourceTimingInfo::Create( +@@ -329,10 +329,10 @@ void ResourceFetcher::RequestLoadStarted(unsigned long identifier, + resource_timing_report_timer_.StartOneShot(0, BLINK_FROM_HERE); + } + +- if (validated_ur_ls_.size() >= kMaxValidatedURLsSize) { +- validated_ur_ls_.Clear(); ++ if (validated_urls_.size() >= kMaxValidatedURLsSize) { ++ validated_urls_.Clear(); + } +- validated_ur_ls_.insert(request.GetResourceRequest().Url()); ++ validated_urls_.insert(request.GetResourceRequest().Url()); + } + + void ResourceFetcher::DidLoadResourceFromMemoryCache( +@@ -968,7 +968,7 @@ ResourceFetcher::DetermineRevalidationPolicy(Resource::Type type, + // or other factors that require separate requests. + if (type != Resource::kRaw) { + if (!Context().IsLoadComplete() && +- validated_ur_ls_.Contains(existing_resource->Url())) ++ validated_urls_.Contains(existing_resource->Url())) + return kUse; + if (existing_resource->IsLoading()) + return kUse; +@@ -1096,24 +1096,24 @@ void ResourceFetcher::PreloadStarted(Resource* resource) { + preloads_ = new HeapListHashSet>; + preloads_->insert(resource); + +- if (preloaded_ur_ls_for_test_) +- preloaded_ur_ls_for_test_->insert(resource->Url().GetString()); ++ if (preloaded_urls_for_test_) ++ preloaded_urls_for_test_->insert(resource->Url().GetString()); + } + + void ResourceFetcher::EnableIsPreloadedForTest() { +- if (preloaded_ur_ls_for_test_) ++ if (preloaded_urls_for_test_) + return; +- preloaded_ur_ls_for_test_ = WTF::WrapUnique(new HashSet); ++ preloaded_urls_for_test_ = WTF::WrapUnique(new HashSet); + + if (preloads_) { + for (const auto& resource : *preloads_) +- preloaded_ur_ls_for_test_->insert(resource->Url().GetString()); ++ preloaded_urls_for_test_->insert(resource->Url().GetString()); + } + } + + bool ResourceFetcher::IsPreloadedForTest(const KURL& url) const { +- DCHECK(preloaded_ur_ls_for_test_); +- return preloaded_ur_ls_for_test_->Contains(url.GetString()); ++ DCHECK(preloaded_urls_for_test_); ++ return preloaded_urls_for_test_->Contains(url.GetString()); + } + + void ResourceFetcher::ClearPreloads(ClearPreloadsPolicy policy) {",1010,1341,2048 +17971,"static int rt_fill_info(struct net *net, __be32 dst, __be32 src, + struct flowi4 *fl4, struct sk_buff *skb, u32 portid, + u32 seq, int event, int nowait, unsigned int flags) +{ + struct rtable *rt = skb_rtable(skb); + struct rtmsg *r; + struct nlmsghdr *nlh; + unsigned long expires = 0; + u32 error; + u32 metrics[RTAX_MAX]; + + nlh = nlmsg_put(skb, portid, seq, event, sizeof(*r), flags); + if (nlh == NULL) + return -EMSGSIZE; + + r = nlmsg_data(nlh); + r->rtm_family = AF_INET; + r->rtm_dst_len = 32; + r->rtm_src_len = 0; + r->rtm_tos = fl4->flowi4_tos; + r->rtm_table = RT_TABLE_MAIN; + if (nla_put_u32(skb, RTA_TABLE, RT_TABLE_MAIN)) + goto nla_put_failure; + r->rtm_type = rt->rt_type; + r->rtm_scope = RT_SCOPE_UNIVERSE; + r->rtm_protocol = RTPROT_UNSPEC; + r->rtm_flags = (rt->rt_flags & ~0xFFFF) | RTM_F_CLONED; + if (rt->rt_flags & RTCF_NOTIFY) + r->rtm_flags |= RTM_F_NOTIFY; + + if (nla_put_be32(skb, RTA_DST, dst)) + goto nla_put_failure; + if (src) { + r->rtm_src_len = 32; + if (nla_put_be32(skb, RTA_SRC, src)) + goto nla_put_failure; + } + if (rt->dst.dev && + nla_put_u32(skb, RTA_OIF, rt->dst.dev->ifindex)) + goto nla_put_failure; +#ifdef CONFIG_IP_ROUTE_CLASSID + if (rt->dst.tclassid && + nla_put_u32(skb, RTA_FLOW, rt->dst.tclassid)) + goto nla_put_failure; +#endif + if (!rt_is_input_route(rt) && + fl4->saddr != src) { + if (nla_put_be32(skb, RTA_PREFSRC, fl4->saddr)) + goto nla_put_failure; + } + if (rt->rt_uses_gateway && + nla_put_be32(skb, RTA_GATEWAY, rt->rt_gateway)) + goto nla_put_failure; + + expires = rt->dst.expires; + if (expires) { + unsigned long now = jiffies; + + if (time_before(now, expires)) + expires -= now; + else + expires = 0; + } + + memcpy(metrics, dst_metrics_ptr(&rt->dst), sizeof(metrics)); + if (rt->rt_pmtu && expires) + metrics[RTAX_MTU - 1] = rt->rt_pmtu; + if (rtnetlink_put_metrics(skb, metrics) < 0) + goto nla_put_failure; + + if (fl4->flowi4_mark && + nla_put_u32(skb, RTA_MARK, fl4->flowi4_mark)) + goto nla_put_failure; + + error = rt->dst.error; + + if (rt_is_input_route(rt)) { +#ifdef CONFIG_IP_MROUTE + if (ipv4_is_multicast(dst) && !ipv4_is_local_multicast(dst) && + IPV4_DEVCONF_ALL(net, MC_FORWARDING)) { + int err = ipmr_get_route(net, skb, + fl4->saddr, fl4->daddr, + r, nowait); + if (err <= 0) { + if (!nowait) { + if (err == 0) + return 0; + goto nla_put_failure; + } else { + if (err == -EMSGSIZE) + goto nla_put_failure; + error = err; + } + } + } else +#endif + if (nla_put_u32(skb, RTA_IIF, skb->dev->ifindex)) + goto nla_put_failure; + } + + if (rtnl_put_cacheinfo(skb, &rt->dst, 0, expires, error) < 0) + goto nla_put_failure; + + return nlmsg_end(skb, nlh); + +nla_put_failure: + nlmsg_cancel(skb, nlh); + return -EMSGSIZE; +} +",1,"static int rt_fill_info(struct net *net, __be32 dst, __be32 src, + struct flowi4 *fl4, struct sk_buff *skb, u32 portid, + u32 seq, int event, int nowait, unsigned int flags) +{ + struct rtable *rt = skb_rtable(skb); + struct rtmsg *r; + struct nlmsghdr *nlh; + unsigned long expires = 0; + u32 error; + u32 metrics[RTAX_MAX]; + + nlh = nlmsg_put(skb, portid, seq, event, sizeof(*r), flags); + if (nlh == NULL) + return -EMSGSIZE; + + r = nlmsg_data(nlh); + r->rtm_family = AF_INET; + r->rtm_dst_len = 32; + r->rtm_src_len = 0; + r->rtm_tos = fl4->flowi4_tos; + r->rtm_table = RT_TABLE_MAIN; + if (nla_put_u32(skb, RTA_TABLE, RT_TABLE_MAIN)) + goto nla_put_failure; + r->rtm_type = rt->rt_type; + r->rtm_scope = RT_SCOPE_UNIVERSE; + r->rtm_protocol = RTPROT_UNSPEC; + r->rtm_flags = (rt->rt_flags & ~0xFFFF) | RTM_F_CLONED; + if (rt->rt_flags & RTCF_NOTIFY) + r->rtm_flags |= RTM_F_NOTIFY; + if (IPCB(skb)->flags & IPSKB_DOREDIRECT) + r->rtm_flags |= RTCF_DOREDIRECT; + + if (nla_put_be32(skb, RTA_DST, dst)) + goto nla_put_failure; + if (src) { + r->rtm_src_len = 32; + if (nla_put_be32(skb, RTA_SRC, src)) + goto nla_put_failure; + } + if (rt->dst.dev && + nla_put_u32(skb, RTA_OIF, rt->dst.dev->ifindex)) + goto nla_put_failure; +#ifdef CONFIG_IP_ROUTE_CLASSID + if (rt->dst.tclassid && + nla_put_u32(skb, RTA_FLOW, rt->dst.tclassid)) + goto nla_put_failure; +#endif + if (!rt_is_input_route(rt) && + fl4->saddr != src) { + if (nla_put_be32(skb, RTA_PREFSRC, fl4->saddr)) + goto nla_put_failure; + } + if (rt->rt_uses_gateway && + nla_put_be32(skb, RTA_GATEWAY, rt->rt_gateway)) + goto nla_put_failure; + + expires = rt->dst.expires; + if (expires) { + unsigned long now = jiffies; + + if (time_before(now, expires)) + expires -= now; + else + expires = 0; + } + + memcpy(metrics, dst_metrics_ptr(&rt->dst), sizeof(metrics)); + if (rt->rt_pmtu && expires) + metrics[RTAX_MTU - 1] = rt->rt_pmtu; + if (rtnetlink_put_metrics(skb, metrics) < 0) + goto nla_put_failure; + + if (fl4->flowi4_mark && + nla_put_u32(skb, RTA_MARK, fl4->flowi4_mark)) + goto nla_put_failure; + + error = rt->dst.error; + + if (rt_is_input_route(rt)) { +#ifdef CONFIG_IP_MROUTE + if (ipv4_is_multicast(dst) && !ipv4_is_local_multicast(dst) && + IPV4_DEVCONF_ALL(net, MC_FORWARDING)) { + int err = ipmr_get_route(net, skb, + fl4->saddr, fl4->daddr, + r, nowait); + if (err <= 0) { + if (!nowait) { + if (err == 0) + return 0; + goto nla_put_failure; + } else { + if (err == -EMSGSIZE) + goto nla_put_failure; + error = err; + } + } + } else +#endif + if (nla_put_u32(skb, RTA_IIF, skb->dev->ifindex)) + goto nla_put_failure; + } + + if (rtnl_put_cacheinfo(skb, &rt->dst, 0, expires, error) < 0) + goto nla_put_failure; + + return nlmsg_end(skb, nlh); + +nla_put_failure: + nlmsg_cancel(skb, nlh); + return -EMSGSIZE; +} +","@@ -1554,11 +1554,10 @@ static int __mkroute_input(struct sk_buff *skb, + + do_cache = res->fi && !itag; + if (out_dev == in_dev && err && IN_DEV_TX_REDIRECTS(out_dev) && ++ skb->protocol == htons(ETH_P_IP) && + (IN_DEV_SHARED_MEDIA(out_dev) || +- inet_addr_onlink(out_dev, saddr, FIB_RES_GW(*res)))) { +- flags |= RTCF_DOREDIRECT; +- do_cache = false; +- } ++ inet_addr_onlink(out_dev, saddr, FIB_RES_GW(*res)))) ++ IPCB(skb)->flags |= IPSKB_DOREDIRECT; + + if (skb->protocol != htons(ETH_P_IP)) { + /* Not IP (i.e. ARP). Do not create route, if it is +@@ -2303,6 +2302,8 @@ static int rt_fill_info(struct net *net, __be32 dst, __be32 src, + r->rtm_flags = (rt->rt_flags & ~0xFFFF) | RTM_F_CLONED; + if (rt->rt_flags & RTCF_NOTIFY) + r->rtm_flags |= RTM_F_NOTIFY; ++ if (IPCB(skb)->flags & IPSKB_DOREDIRECT) ++ r->rtm_flags |= RTCF_DOREDIRECT; + + if (nla_put_be32(skb, RTA_DST, dst)) + goto nla_put_failure;",971,1302,2048 +18321,"ext2_xattr_set2(struct inode *inode, struct buffer_head *old_bh, + struct ext2_xattr_header *header) +{ + struct super_block *sb = inode->i_sb; + struct buffer_head *new_bh = NULL; + int error; + + if (header) { + new_bh = ext2_xattr_cache_find(inode, header); + if (new_bh) { + /* We found an identical block in the cache. */ + if (new_bh == old_bh) { + ea_bdebug(new_bh, ""keeping this block""); + } else { + /* The old block is released after updating + the inode. */ + ea_bdebug(new_bh, ""reusing block""); + + error = dquot_alloc_block(inode, 1); + if (error) { + unlock_buffer(new_bh); + goto cleanup; + } + le32_add_cpu(&HDR(new_bh)->h_refcount, 1); + ea_bdebug(new_bh, ""refcount now=%d"", + le32_to_cpu(HDR(new_bh)->h_refcount)); + } + unlock_buffer(new_bh); + } else if (old_bh && header == HDR(old_bh)) { + /* Keep this block. No need to lock the block as we + don't need to change the reference count. */ + new_bh = old_bh; + get_bh(new_bh); + ext2_xattr_cache_insert(new_bh); + } else { + /* We need to allocate a new block */ + ext2_fsblk_t goal = ext2_group_first_block_no(sb, + EXT2_I(inode)->i_block_group); + int block = ext2_new_block(inode, goal, &error); + if (error) + goto cleanup; + ea_idebug(inode, ""creating block %d"", block); + + new_bh = sb_getblk(sb, block); + if (unlikely(!new_bh)) { + ext2_free_blocks(inode, block, 1); + mark_inode_dirty(inode); + error = -ENOMEM; + goto cleanup; + } + lock_buffer(new_bh); + memcpy(new_bh->b_data, header, new_bh->b_size); + set_buffer_uptodate(new_bh); + unlock_buffer(new_bh); + ext2_xattr_cache_insert(new_bh); + + ext2_xattr_update_super_block(sb); + } + mark_buffer_dirty(new_bh); + if (IS_SYNC(inode)) { + sync_dirty_buffer(new_bh); + error = -EIO; + if (buffer_req(new_bh) && !buffer_uptodate(new_bh)) + goto cleanup; + } + } + + /* Update the inode. */ + EXT2_I(inode)->i_file_acl = new_bh ? new_bh->b_blocknr : 0; + inode->i_ctime = CURRENT_TIME_SEC; + if (IS_SYNC(inode)) { + error = sync_inode_metadata(inode, 1); + /* In case sync failed due to ENOSPC the inode was actually + * written (only some dirty data were not) so we just proceed + * as if nothing happened and cleanup the unused block */ + if (error && error != -ENOSPC) { + if (new_bh && new_bh != old_bh) { + dquot_free_block_nodirty(inode, 1); + mark_inode_dirty(inode); + } + goto cleanup; + } + } else + mark_inode_dirty(inode); + + error = 0; + if (old_bh && old_bh != new_bh) { + struct mb_cache_entry *ce; + /* + * If there was an old block and we are no longer using it, + * release the old block. + */ + ce = mb_cache_entry_get(ext2_xattr_cache, old_bh->b_bdev, + old_bh->b_blocknr); + lock_buffer(old_bh); + if (HDR(old_bh)->h_refcount == cpu_to_le32(1)) { + /* Free the old block. */ + if (ce) + mb_cache_entry_free(ce); + ea_bdebug(old_bh, ""freeing""); + ext2_free_blocks(inode, old_bh->b_blocknr, 1); + mark_inode_dirty(inode); + /* We let our caller release old_bh, so we + * need to duplicate the buffer before. */ + get_bh(old_bh); + bforget(old_bh); + } else { + /* Decrement the refcount only. */ + le32_add_cpu(&HDR(old_bh)->h_refcount, -1); + if (ce) + mb_cache_entry_release(ce); + dquot_free_block_nodirty(inode, 1); + mark_inode_dirty(inode); + mark_buffer_dirty(old_bh); + ea_bdebug(old_bh, ""refcount now=%d"", + le32_to_cpu(HDR(old_bh)->h_refcount)); + } + unlock_buffer(old_bh); + } + +cleanup: + brelse(new_bh); + + return error; +} +",1,"ext2_xattr_set2(struct inode *inode, struct buffer_head *old_bh, + struct ext2_xattr_header *header) +{ + struct super_block *sb = inode->i_sb; + struct buffer_head *new_bh = NULL; + int error; + struct mb2_cache *ext2_mb_cache = EXT2_SB(sb)->s_mb_cache; + + if (header) { + new_bh = ext2_xattr_cache_find(inode, header); + if (new_bh) { + /* We found an identical block in the cache. */ + if (new_bh == old_bh) { + ea_bdebug(new_bh, ""keeping this block""); + } else { + /* The old block is released after updating + the inode. */ + ea_bdebug(new_bh, ""reusing block""); + + error = dquot_alloc_block(inode, 1); + if (error) { + unlock_buffer(new_bh); + goto cleanup; + } + le32_add_cpu(&HDR(new_bh)->h_refcount, 1); + ea_bdebug(new_bh, ""refcount now=%d"", + le32_to_cpu(HDR(new_bh)->h_refcount)); + } + unlock_buffer(new_bh); + } else if (old_bh && header == HDR(old_bh)) { + /* Keep this block. No need to lock the block as we + don't need to change the reference count. */ + new_bh = old_bh; + get_bh(new_bh); + ext2_xattr_cache_insert(ext2_mb_cache, new_bh); + } else { + /* We need to allocate a new block */ + ext2_fsblk_t goal = ext2_group_first_block_no(sb, + EXT2_I(inode)->i_block_group); + int block = ext2_new_block(inode, goal, &error); + if (error) + goto cleanup; + ea_idebug(inode, ""creating block %d"", block); + + new_bh = sb_getblk(sb, block); + if (unlikely(!new_bh)) { + ext2_free_blocks(inode, block, 1); + mark_inode_dirty(inode); + error = -ENOMEM; + goto cleanup; + } + lock_buffer(new_bh); + memcpy(new_bh->b_data, header, new_bh->b_size); + set_buffer_uptodate(new_bh); + unlock_buffer(new_bh); + ext2_xattr_cache_insert(ext2_mb_cache, new_bh); + + ext2_xattr_update_super_block(sb); + } + mark_buffer_dirty(new_bh); + if (IS_SYNC(inode)) { + sync_dirty_buffer(new_bh); + error = -EIO; + if (buffer_req(new_bh) && !buffer_uptodate(new_bh)) + goto cleanup; + } + } + + /* Update the inode. */ + EXT2_I(inode)->i_file_acl = new_bh ? new_bh->b_blocknr : 0; + inode->i_ctime = CURRENT_TIME_SEC; + if (IS_SYNC(inode)) { + error = sync_inode_metadata(inode, 1); + /* In case sync failed due to ENOSPC the inode was actually + * written (only some dirty data were not) so we just proceed + * as if nothing happened and cleanup the unused block */ + if (error && error != -ENOSPC) { + if (new_bh && new_bh != old_bh) { + dquot_free_block_nodirty(inode, 1); + mark_inode_dirty(inode); + } + goto cleanup; + } + } else + mark_inode_dirty(inode); + + error = 0; + if (old_bh && old_bh != new_bh) { + /* + * If there was an old block and we are no longer using it, + * release the old block. + */ + lock_buffer(old_bh); + if (HDR(old_bh)->h_refcount == cpu_to_le32(1)) { + __u32 hash = le32_to_cpu(HDR(old_bh)->h_hash); + + /* + * This must happen under buffer lock for + * ext2_xattr_set2() to reliably detect freed block + */ + mb2_cache_entry_delete_block(ext2_mb_cache, + hash, old_bh->b_blocknr); + /* Free the old block. */ + ea_bdebug(old_bh, ""freeing""); + ext2_free_blocks(inode, old_bh->b_blocknr, 1); + mark_inode_dirty(inode); + /* We let our caller release old_bh, so we + * need to duplicate the buffer before. */ + get_bh(old_bh); + bforget(old_bh); + } else { + /* Decrement the refcount only. */ + le32_add_cpu(&HDR(old_bh)->h_refcount, -1); + dquot_free_block_nodirty(inode, 1); + mark_inode_dirty(inode); + mark_buffer_dirty(old_bh); + ea_bdebug(old_bh, ""refcount now=%d"", + le32_to_cpu(HDR(old_bh)->h_refcount)); + } + unlock_buffer(old_bh); + } + +cleanup: + brelse(new_bh); + + return error; +} +","@@ -56,7 +56,7 @@ + #include + #include + #include +-#include ++#include + #include + #include + #include +@@ -90,14 +90,12 @@ + static int ext2_xattr_set2(struct inode *, struct buffer_head *, + struct ext2_xattr_header *); + +-static int ext2_xattr_cache_insert(struct buffer_head *); ++static int ext2_xattr_cache_insert(struct mb2_cache *, struct buffer_head *); + static struct buffer_head *ext2_xattr_cache_find(struct inode *, + struct ext2_xattr_header *); + static void ext2_xattr_rehash(struct ext2_xattr_header *, + struct ext2_xattr_entry *); + +-static struct mb_cache *ext2_xattr_cache; +- + static const struct xattr_handler *ext2_xattr_handler_map[] = { + [EXT2_XATTR_INDEX_USER] = &ext2_xattr_user_handler, + #ifdef CONFIG_EXT2_FS_POSIX_ACL +@@ -152,6 +150,7 @@ ext2_xattr_get(struct inode *inode, int name_index, const char *name, + size_t name_len, size; + char *end; + int error; ++ struct mb2_cache *ext2_mb_cache = EXT2_SB(inode->i_sb)->s_mb_cache; + + ea_idebug(inode, ""name=%d.%s, buffer=%p, buffer_size=%ld"", + name_index, name, buffer, (long)buffer_size); +@@ -196,7 +195,7 @@ bad_block: ext2_error(inode->i_sb, ""ext2_xattr_get"", + goto found; + entry = next; + } +- if (ext2_xattr_cache_insert(bh)) ++ if (ext2_xattr_cache_insert(ext2_mb_cache, bh)) + ea_idebug(inode, ""cache insert failed""); + error = -ENODATA; + goto cleanup; +@@ -209,7 +208,7 @@ bad_block: ext2_error(inode->i_sb, ""ext2_xattr_get"", + le16_to_cpu(entry->e_value_offs) + size > inode->i_sb->s_blocksize) + goto bad_block; + +- if (ext2_xattr_cache_insert(bh)) ++ if (ext2_xattr_cache_insert(ext2_mb_cache, bh)) + ea_idebug(inode, ""cache insert failed""); + if (buffer) { + error = -ERANGE; +@@ -247,6 +246,7 @@ ext2_xattr_list(struct dentry *dentry, char *buffer, size_t buffer_size) + char *end; + size_t rest = buffer_size; + int error; ++ struct mb2_cache *ext2_mb_cache = EXT2_SB(inode->i_sb)->s_mb_cache; + + ea_idebug(inode, ""buffer=%p, buffer_size=%ld"", + buffer, (long)buffer_size); +@@ -281,7 +281,7 @@ bad_block: ext2_error(inode->i_sb, ""ext2_xattr_list"", + goto bad_block; + entry = next; + } +- if (ext2_xattr_cache_insert(bh)) ++ if (ext2_xattr_cache_insert(ext2_mb_cache, bh)) + ea_idebug(inode, ""cache insert failed""); + + /* list the attribute names */ +@@ -483,22 +483,23 @@ bad_block: ext2_error(sb, ""ext2_xattr_set"", + /* Here we know that we can set the new attribute. */ + + if (header) { +- struct mb_cache_entry *ce; +- + /* assert(header == HDR(bh)); */ +- ce = mb_cache_entry_get(ext2_xattr_cache, bh->b_bdev, +- bh->b_blocknr); + lock_buffer(bh); + if (header->h_refcount == cpu_to_le32(1)) { ++ __u32 hash = le32_to_cpu(header->h_hash); ++ + ea_bdebug(bh, ""modifying in-place""); +- if (ce) +- mb_cache_entry_free(ce); ++ /* ++ * This must happen under buffer lock for ++ * ext2_xattr_set2() to reliably detect modified block ++ */ ++ mb2_cache_entry_delete_block(EXT2_SB(sb)->s_mb_cache, ++ hash, bh->b_blocknr); ++ + /* keep the buffer locked while modifying it. */ + } else { + int offset; + +- if (ce) +- mb_cache_entry_release(ce); + unlock_buffer(bh); + ea_bdebug(bh, ""cloning""); + header = kmalloc(bh->b_size, GFP_KERNEL); +@@ -626,6 +627,7 @@ ext2_xattr_set2(struct inode *inode, struct buffer_head *old_bh, + struct super_block *sb = inode->i_sb; + struct buffer_head *new_bh = NULL; + int error; ++ struct mb2_cache *ext2_mb_cache = EXT2_SB(sb)->s_mb_cache; + + if (header) { + new_bh = ext2_xattr_cache_find(inode, header); +@@ -653,7 +655,7 @@ ext2_xattr_set2(struct inode *inode, struct buffer_head *old_bh, + don't need to change the reference count. */ + new_bh = old_bh; + get_bh(new_bh); +- ext2_xattr_cache_insert(new_bh); ++ ext2_xattr_cache_insert(ext2_mb_cache, new_bh); + } else { + /* We need to allocate a new block */ + ext2_fsblk_t goal = ext2_group_first_block_no(sb, +@@ -674,7 +676,7 @@ ext2_xattr_set2(struct inode *inode, struct buffer_head *old_bh, + memcpy(new_bh->b_data, header, new_bh->b_size); + set_buffer_uptodate(new_bh); + unlock_buffer(new_bh); +- ext2_xattr_cache_insert(new_bh); ++ ext2_xattr_cache_insert(ext2_mb_cache, new_bh); + + ext2_xattr_update_super_block(sb); + } +@@ -707,19 +709,21 @@ ext2_xattr_set2(struct inode *inode, struct buffer_head *old_bh, + + error = 0; + if (old_bh && old_bh != new_bh) { +- struct mb_cache_entry *ce; +- + /* + * If there was an old block and we are no longer using it, + * release the old block. + */ +- ce = mb_cache_entry_get(ext2_xattr_cache, old_bh->b_bdev, +- old_bh->b_blocknr); + lock_buffer(old_bh); + if (HDR(old_bh)->h_refcount == cpu_to_le32(1)) { ++ __u32 hash = le32_to_cpu(HDR(old_bh)->h_hash); ++ ++ /* ++ * This must happen under buffer lock for ++ * ext2_xattr_set2() to reliably detect freed block ++ */ ++ mb2_cache_entry_delete_block(ext2_mb_cache, ++ hash, old_bh->b_blocknr); + /* Free the old block. */ +- if (ce) +- mb_cache_entry_free(ce); + ea_bdebug(old_bh, ""freeing""); + ext2_free_blocks(inode, old_bh->b_blocknr, 1); + mark_inode_dirty(inode); +@@ -730,8 +734,6 @@ ext2_xattr_set2(struct inode *inode, struct buffer_head *old_bh, + } else { + /* Decrement the refcount only. */ + le32_add_cpu(&HDR(old_bh)->h_refcount, -1); +- if (ce) +- mb_cache_entry_release(ce); + dquot_free_block_nodirty(inode, 1); + mark_inode_dirty(inode); + mark_buffer_dirty(old_bh); +@@ -757,7 +759,6 @@ void + ext2_xattr_delete_inode(struct inode *inode) + { + struct buffer_head *bh = NULL; +- struct mb_cache_entry *ce; + + down_write(&EXT2_I(inode)->xattr_sem); + if (!EXT2_I(inode)->i_file_acl) +@@ -777,19 +778,22 @@ ext2_xattr_delete_inode(struct inode *inode) + EXT2_I(inode)->i_file_acl); + goto cleanup; + } +- ce = mb_cache_entry_get(ext2_xattr_cache, bh->b_bdev, bh->b_blocknr); + lock_buffer(bh); + if (HDR(bh)->h_refcount == cpu_to_le32(1)) { +- if (ce) +- mb_cache_entry_free(ce); ++ __u32 hash = le32_to_cpu(HDR(bh)->h_hash); ++ ++ /* ++ * This must happen under buffer lock for ext2_xattr_set2() to ++ * reliably detect freed block ++ */ ++ mb2_cache_entry_delete_block(EXT2_SB(inode->i_sb)->s_mb_cache, ++ hash, bh->b_blocknr); + ext2_free_blocks(inode, EXT2_I(inode)->i_file_acl, 1); + get_bh(bh); + bforget(bh); + unlock_buffer(bh); + } else { + le32_add_cpu(&HDR(bh)->h_refcount, -1); +- if (ce) +- mb_cache_entry_release(ce); + ea_bdebug(bh, ""refcount now=%d"", + le32_to_cpu(HDR(bh)->h_refcount)); + unlock_buffer(bh); +@@ -805,18 +809,6 @@ ext2_xattr_delete_inode(struct inode *inode) + up_write(&EXT2_I(inode)->xattr_sem); + } + +-/* +- * ext2_xattr_put_super() +- * +- * This is called when a file system is unmounted. +- */ +-void +-ext2_xattr_put_super(struct super_block *sb) +-{ +- mb_cache_shrink(sb->s_bdev); +-} +- +- + /* + * ext2_xattr_cache_insert() + * +@@ -826,28 +818,20 @@ ext2_xattr_put_super(struct super_block *sb) + * Returns 0, or a negative error number on failure. + */ + static int +-ext2_xattr_cache_insert(struct buffer_head *bh) ++ext2_xattr_cache_insert(struct mb2_cache *cache, struct buffer_head *bh) + { + __u32 hash = le32_to_cpu(HDR(bh)->h_hash); +- struct mb_cache_entry *ce; + int error; + +- ce = mb_cache_entry_alloc(ext2_xattr_cache, GFP_NOFS); +- if (!ce) +- return -ENOMEM; +- error = mb_cache_entry_insert(ce, bh->b_bdev, bh->b_blocknr, hash); ++ error = mb2_cache_entry_create(cache, GFP_NOFS, hash, bh->b_blocknr); + if (error) { +- mb_cache_entry_free(ce); + if (error == -EBUSY) { + ea_bdebug(bh, ""already in cache (%d cache entries)"", + atomic_read(&ext2_xattr_cache->c_entry_count)); + error = 0; + } +- } else { +- ea_bdebug(bh, ""inserting [%x] (%d cache entries)"", (int)hash, +- atomic_read(&ext2_xattr_cache->c_entry_count)); +- mb_cache_entry_release(ce); +- } ++ } else ++ ea_bdebug(bh, ""inserting [%x]"", (int)hash); + return error; + } + +@@ -903,31 +887,39 @@ static struct buffer_head * + ext2_xattr_cache_find(struct inode *inode, struct ext2_xattr_header *header) + { + __u32 hash = le32_to_cpu(header->h_hash); +- struct mb_cache_entry *ce; ++ struct mb2_cache_entry *ce; ++ struct mb2_cache *ext2_mb_cache = EXT2_SB(inode->i_sb)->s_mb_cache; + + if (!header->h_hash) + return NULL; /* never share */ + ea_idebug(inode, ""looking for cached blocks [%x]"", (int)hash); + again: +- ce = mb_cache_entry_find_first(ext2_xattr_cache, inode->i_sb->s_bdev, +- hash); ++ ce = mb2_cache_entry_find_first(ext2_mb_cache, hash); + while (ce) { + struct buffer_head *bh; + +- if (IS_ERR(ce)) { +- if (PTR_ERR(ce) == -EAGAIN) +- goto again; +- break; +- } +- + bh = sb_bread(inode->i_sb, ce->e_block); + if (!bh) { + ext2_error(inode->i_sb, ""ext2_xattr_cache_find"", + ""inode %ld: block %ld read error"", + inode->i_ino, (unsigned long) ce->e_block); + } else { + lock_buffer(bh); +- if (le32_to_cpu(HDR(bh)->h_refcount) > ++ /* ++ * We have to be careful about races with freeing or ++ * rehashing of xattr block. Once we hold buffer lock ++ * xattr block's state is stable so we can check ++ * whether the block got freed / rehashed or not. ++ * Since we unhash mbcache entry under buffer lock when ++ * freeing / rehashing xattr block, checking whether ++ * entry is still hashed is reliable. ++ */ ++ if (hlist_bl_unhashed(&ce->e_hash_list)) { ++ mb2_cache_entry_put(ext2_mb_cache, ce); ++ unlock_buffer(bh); ++ brelse(bh); ++ goto again; ++ } else if (le32_to_cpu(HDR(bh)->h_refcount) > + EXT2_XATTR_REFCOUNT_MAX) { + ea_idebug(inode, ""block %ld refcount %d>%d"", + (unsigned long) ce->e_block, +@@ -936,13 +928,14 @@ ext2_xattr_cache_find(struct inode *inode, struct ext2_xattr_header *header) + } else if (!ext2_xattr_cmp(header, HDR(bh))) { + ea_bdebug(bh, ""b_count=%d"", + atomic_read(&(bh->b_count))); +- mb_cache_entry_release(ce); ++ mb2_cache_entry_touch(ext2_mb_cache, ce); ++ mb2_cache_entry_put(ext2_mb_cache, ce); + return bh; + } + unlock_buffer(bh); + brelse(bh); + } +- ce = mb_cache_entry_find_next(ce, inode->i_sb->s_bdev, hash); ++ ce = mb2_cache_entry_find_next(ext2_mb_cache, ce); + } + return NULL; + } +@@ -1015,17 +1008,15 @@ static void ext2_xattr_rehash(struct ext2_xattr_header *header, + + #undef BLOCK_HASH_SHIFT + +-int __init +-init_ext2_xattr(void) ++#define HASH_BUCKET_BITS 10 ++ ++struct mb2_cache *ext2_xattr_create_cache(void) + { +- ext2_xattr_cache = mb_cache_create(""ext2_xattr"", 6); +- if (!ext2_xattr_cache) +- return -ENOMEM; +- return 0; ++ return mb2_cache_create(HASH_BUCKET_BITS); + } + +-void +-exit_ext2_xattr(void) ++void ext2_xattr_destroy_cache(struct mb2_cache *cache) + { +- mb_cache_destroy(ext2_xattr_cache); ++ if (cache) ++ mb2_cache_destroy(cache); + }",1078,1409,2048 +3,"int do_print(const char *path_p, const struct stat *st, int walk_flags, void *unused) +{ + const char *default_prefix = NULL; + acl_t acl = NULL, default_acl = NULL; + int error = 0; + + if (walk_flags & WALK_TREE_FAILED) { + fprintf(stderr, ""%s: %s: %s\n"", progname, xquote(path_p, ""\n\r""), + strerror(errno)); + return 1; + } + + /* + * Symlinks can never have ACLs, so when doing a physical walk, we + * skip symlinks altogether, and when doing a half-logical walk, we + * skip all non-toplevel symlinks. + */ + if ((walk_flags & WALK_TREE_SYMLINK) && + ((walk_flags & WALK_TREE_PHYSICAL) || + !(walk_flags & (WALK_TREE_TOPLEVEL | WALK_TREE_LOGICAL)))) + return 0; + + if (opt_print_acl) { + acl = acl_get_file(path_p, ACL_TYPE_ACCESS); + if (acl == NULL && (errno == ENOSYS || errno == ENOTSUP)) + acl = acl_get_file_mode(path_p); + if (acl == NULL) + goto fail; + } + + if (opt_print_default_acl && S_ISDIR(st->st_mode)) { + default_acl = acl_get_file(path_p, ACL_TYPE_DEFAULT); + if (default_acl == NULL) { + if (errno != ENOSYS && errno != ENOTSUP) + goto fail; + } else if (acl_entries(default_acl) == 0) { + acl_free(default_acl); + default_acl = NULL; + } + } + + if (opt_skip_base && + (!acl || acl_equiv_mode(acl, NULL) == 0) && !default_acl) + return 0; + + if (opt_print_acl && opt_print_default_acl) + default_prefix = ""default:""; + + if (opt_strip_leading_slash) { + if (*path_p == '/') { + if (!absolute_warning) { + fprintf(stderr, _(""%s: Removing leading "" + ""'/' from absolute path names\n""), + progname); + absolute_warning = 1; + } + while (*path_p == '/') + path_p++; + } else if (*path_p == '.' && *(path_p+1) == '/') + while (*++path_p == '/') + /* nothing */ ; + if (*path_p == '\0') + path_p = "".""; + } + + if (opt_tabular) { + if (do_show(stdout, path_p, st, acl, default_acl) != 0) + goto fail; + } else { + if (opt_comments) { + printf(""# file: %s\n"", xquote(path_p, ""\n\r"")); + printf(""# owner: %s\n"", + xquote(user_name(st->st_uid, opt_numeric), "" \t\n\r"")); + printf(""# group: %s\n"", + xquote(group_name(st->st_gid, opt_numeric), "" \t\n\r"")); + } + if (acl != NULL) { + char *acl_text = acl_to_any_text(acl, NULL, '\n', + print_options); + if (!acl_text) + goto fail; + if (puts(acl_text) < 0) { + acl_free(acl_text); + goto fail; + } + acl_free(acl_text); + } + if (default_acl != NULL) { + char *acl_text = acl_to_any_text(default_acl, + default_prefix, '\n', + print_options); + if (!acl_text) + goto fail; + if (puts(acl_text) < 0) { + acl_free(acl_text); + goto fail; + } + acl_free(acl_text); + } + } + if (acl || default_acl || opt_comments) + printf(""\n""); + +cleanup: + if (acl) + acl_free(acl); + if (default_acl) + acl_free(default_acl); + return error; + +fail: + fprintf(stderr, ""%s: %s: %s\n"", progname, xquote(path_p, ""\n\r""), + strerror(errno)); + error = -1; + goto cleanup; +} +",0,"int do_print(const char *path_p, const struct stat *st, int walk_flags, void *unused) +{ + const char *default_prefix = NULL; + acl_t acl = NULL, default_acl = NULL; + int error = 0; + + if (walk_flags & WALK_TREE_FAILED) { + fprintf(stderr, ""%s: %s: %s\n"", progname, xquote(path_p, ""\n\r""), + strerror(errno)); + return 1; + } + + /* + * Symlinks can never have ACLs, so when doing a physical walk, we + * skip symlinks altogether, and when doing a half-logical walk, we + * skip all non-toplevel symlinks. + */ + if ((walk_flags & WALK_TREE_SYMLINK) && + ((walk_flags & WALK_TREE_PHYSICAL) || + !(walk_flags & (WALK_TREE_TOPLEVEL | WALK_TREE_LOGICAL)))) + return 0; + + if (opt_print_acl) { + acl = acl_get_file(path_p, ACL_TYPE_ACCESS); + if (acl == NULL && (errno == ENOSYS || errno == ENOTSUP)) + acl = acl_get_file_mode(path_p); + if (acl == NULL) + goto fail; + } + + if (opt_print_default_acl && S_ISDIR(st->st_mode)) { + default_acl = acl_get_file(path_p, ACL_TYPE_DEFAULT); + if (default_acl == NULL) { + if (errno != ENOSYS && errno != ENOTSUP) + goto fail; + } else if (acl_entries(default_acl) == 0) { + acl_free(default_acl); + default_acl = NULL; + } + } + + if (opt_skip_base && + (!acl || acl_equiv_mode(acl, NULL) == 0) && !default_acl) + return 0; + + if (opt_print_acl && opt_print_default_acl) + default_prefix = ""default:""; + + if (opt_strip_leading_slash) { + if (*path_p == '/') { + if (!absolute_warning) { + fprintf(stderr, _(""%s: Removing leading "" + ""'/' from absolute path names\n""), + progname); + absolute_warning = 1; + } + while (*path_p == '/') + path_p++; + } else if (*path_p == '.' && *(path_p+1) == '/') + while (*++path_p == '/') + /* nothing */ ; + if (*path_p == '\0') + path_p = "".""; + } + + if (opt_tabular) { + if (do_show(stdout, path_p, st, acl, default_acl) != 0) + goto fail; + } else { + if (opt_comments) { + printf(""# file: %s\n"", xquote(path_p, ""\n\r"")); + printf(""# owner: %s\n"", + xquote(user_name(st->st_uid, opt_numeric), "" \t\n\r"")); + printf(""# group: %s\n"", + xquote(group_name(st->st_gid, opt_numeric), "" \t\n\r"")); + } + if (acl != NULL) { + char *acl_text = acl_to_any_text(acl, NULL, '\n', + print_options); + if (!acl_text) + goto fail; + if (puts(acl_text) < 0) { + acl_free(acl_text); + goto fail; + } + acl_free(acl_text); + } + if (default_acl != NULL) { + char *acl_text = acl_to_any_text(default_acl, + default_prefix, '\n', + print_options); + if (!acl_text) + goto fail; + if (puts(acl_text) < 0) { + acl_free(acl_text); + goto fail; + } + acl_free(acl_text); + } + } + if (acl || default_acl || opt_comments) + printf(""\n""); + +cleanup: + if (acl) + acl_free(acl); + if (default_acl) + acl_free(default_acl); + return error; + +fail: + fprintf(stderr, ""%s: %s: %s\n"", progname, xquote(path_p, ""\n\r""), + strerror(errno)); + error = -1; + goto cleanup; +} +","@@ -1,3 +1,6 @@+* Make sure that getfacl -R only calls stat(2) on symlinks when it needs to.+ This fixes http://oss.sgi.com/bugzilla/show_bug.cgi?id=790 ""getfacl follows+ symlinks, even without -L"". * Stop quoting nonprintable characters in the getfacl output: what is printable or not depends on the locale settings, and getfacl often gets it wrong. We still need to quote a few special characters like newlines so that setfacldiff --git a/getfacl/getfacl.c b/getfacl/getfacl.c +index fc650e3..b3e6200 100644 +--- a/getfacl/getfacl.c ++++ b/getfacl/getfacl.c@@ -70,7 +70,7 @@ struct option long_options[] = { const char *progname; const char *cmd_line_options; -int walk_flags = WALK_TREE_DEREFERENCE;+int walk_flags = WALK_TREE_DEREFERENCE_TOPLEVEL; int opt_print_acl; int opt_print_default_acl; int opt_strip_leading_slash = 1;@@ -642,7 +642,7 @@ int main(int argc, char *argv[]) case 'L': /* follow all symlinks */ if (posixly_correct) goto synopsis;- walk_flags |= WALK_TREE_LOGICAL;+ walk_flags |= WALK_TREE_LOGICAL | WALK_TREE_DEREFERENCE; walk_flags &= ~WALK_TREE_PHYSICAL; break; @@ -650,7 +650,8 @@ int main(int argc, char *argv[]) if (posixly_correct) goto synopsis; walk_flags |= WALK_TREE_PHYSICAL;- walk_flags &= ~WALK_TREE_LOGICAL;+ walk_flags &= ~(WALK_TREE_LOGICAL | WALK_TREE_DEREFERENCE |+ WALK_TREE_DEREFERENCE_TOPLEVEL); break; case 's': /* skip files with only base entries */",901,1232,2048 +18560," void PrintViewManagerBase::OnDidPrintPage( + const PrintHostMsg_DidPrintPage_Params& params) { + if (!OpportunisticallyCreatePrintJob(params.document_cookie)) + return; + + PrintedDocument* document = print_job_->document(); + if (!document || params.document_cookie != document->cookie()) { + return; + } + +#if defined(OS_MACOSX) + const bool metafile_must_be_valid = true; +#else + const bool metafile_must_be_valid = expecting_first_page_; + expecting_first_page_ = false; +#endif + + std::unique_ptr shared_buf; + if (metafile_must_be_valid) { + if (!base::SharedMemory::IsHandleValid(params.metafile_data_handle)) { + NOTREACHED() << ""invalid memory handle""; + web_contents()->Stop(); + return; + } + shared_buf = + base::MakeUnique(params.metafile_data_handle, true); + if (!shared_buf->Map(params.data_size)) { + NOTREACHED() << ""couldn't map""; + web_contents()->Stop(); + return; + } + } else { + if (base::SharedMemory::IsHandleValid(params.metafile_data_handle)) { + NOTREACHED() << ""unexpected valid memory handle""; + web_contents()->Stop(); + base::SharedMemory::CloseHandle(params.metafile_data_handle); + return; + } + } + + std::unique_ptr metafile( + new PdfMetafileSkia(SkiaDocumentType::PDF)); + if (metafile_must_be_valid) { + if (!metafile->InitFromData(shared_buf->memory(), params.data_size)) { + NOTREACHED() << ""Invalid metafile header""; + web_contents()->Stop(); + return; + } + } + + #if defined(OS_WIN) + print_job_->AppendPrintedPage(params.page_number); + if (metafile_must_be_valid) { + scoped_refptr bytes = new base::RefCountedBytes( + reinterpret_cast(shared_buf->memory()), + params.data_size); + document->DebugDumpData(bytes.get(), FILE_PATH_LITERAL("".pdf"")); + + const auto& settings = document->settings(); + if (settings.printer_is_textonly()) { + print_job_->StartPdfToTextConversion(bytes, params.page_size); + } else if ((settings.printer_is_ps2() || settings.printer_is_ps3()) && + !base::FeatureList::IsEnabled( + features::kDisablePostScriptPrinting)) { + print_job_->StartPdfToPostScriptConversion(bytes, params.content_area, + params.physical_offsets, + settings.printer_is_ps2()); + } else { + bool print_text_with_gdi = settings.print_text_with_gdi() && + !settings.printer_is_xps() && + base::FeatureList::IsEnabled( + features::kGdiTextPrinting); + print_job_->StartPdfToEmfConversion( + bytes, params.page_size, params.content_area, print_text_with_gdi); + } + } + #else + document->SetPage(params.page_number, + std::move(metafile), +#if defined(OS_WIN) + 0.0f /* dummy shrink_factor */, +#endif + params.page_size, + params.content_area); + + ShouldQuitFromInnerMessageLoop(); +#endif +} +",1," void PrintViewManagerBase::OnDidPrintPage( + const PrintHostMsg_DidPrintPage_Params& params) { + // Ready to composite. Starting a print job. + if (!OpportunisticallyCreatePrintJob(params.document_cookie)) + return; + + PrintedDocument* document = print_job_->document(); + if (!document || params.document_cookie != document->cookie()) { + return; + } + +#if defined(OS_MACOSX) + const bool metafile_must_be_valid = true; +#else + const bool metafile_must_be_valid = expecting_first_page_; + expecting_first_page_ = false; +#endif + + std::unique_ptr shared_buf; + if (metafile_must_be_valid) { + if (!base::SharedMemory::IsHandleValid(params.metafile_data_handle)) { + NOTREACHED() << ""invalid memory handle""; + web_contents()->Stop(); + return; + } + + auto* client = PrintCompositeClient::FromWebContents(web_contents()); + if (IsOopifEnabled() && !client->for_preview() && + !document->settings().is_modifiable()) { + client->DoComposite( + params.metafile_data_handle, params.data_size, + base::BindOnce(&PrintViewManagerBase::OnComposePdfDone, + weak_ptr_factory_.GetWeakPtr(), params)); + return; + } + shared_buf = + std::make_unique(params.metafile_data_handle, true); + if (!shared_buf->Map(params.data_size)) { + NOTREACHED() << ""couldn't map""; + web_contents()->Stop(); + return; + } + } else { + if (base::SharedMemory::IsHandleValid(params.metafile_data_handle)) { + NOTREACHED() << ""unexpected valid memory handle""; + web_contents()->Stop(); + base::SharedMemory::CloseHandle(params.metafile_data_handle); + return; + } + } + + UpdateForPrintedPage(params, metafile_must_be_valid, std::move(shared_buf)); +} + +void PrintViewManagerBase::UpdateForPrintedPage( + const PrintHostMsg_DidPrintPage_Params& params, + bool has_valid_page_data, + std::unique_ptr shared_buf) { + PrintedDocument* document = print_job_->document(); + if (!document) + return; + + #if defined(OS_WIN) + print_job_->AppendPrintedPage(params.page_number); + if (has_valid_page_data) { + scoped_refptr bytes(new base::RefCountedBytes( + reinterpret_cast(shared_buf->memory()), + shared_buf->mapped_size())); + + document->DebugDumpData(bytes.get(), FILE_PATH_LITERAL("".pdf"")); + + const auto& settings = document->settings(); + if (settings.printer_is_textonly()) { + print_job_->StartPdfToTextConversion(bytes, params.page_size); + } else if ((settings.printer_is_ps2() || settings.printer_is_ps3()) && + !base::FeatureList::IsEnabled( + features::kDisablePostScriptPrinting)) { + print_job_->StartPdfToPostScriptConversion(bytes, params.content_area, + params.physical_offsets, + settings.printer_is_ps2()); + } else { + bool print_text_with_gdi = + settings.print_text_with_gdi() && !settings.printer_is_xps() && + base::FeatureList::IsEnabled(features::kGdiTextPrinting); + print_job_->StartPdfToEmfConversion( + bytes, params.page_size, params.content_area, print_text_with_gdi); + } + } + #else + std::unique_ptr metafile = + std::make_unique(SkiaDocumentType::PDF); + if (has_valid_page_data) { + if (!metafile->InitFromData(shared_buf->memory(), + shared_buf->mapped_size())) { + NOTREACHED() << ""Invalid metafile header""; + web_contents()->Stop(); + return; + } + } + + document->SetPage(params.page_number, std::move(metafile), params.page_size, + params.content_area); + + ShouldQuitFromInnerMessageLoop(); +#endif +} +","@@ -11,6 +11,7 @@ + #include ""base/bind.h"" + #include ""base/location.h"" + #include ""base/memory/ptr_util.h"" ++#include ""base/memory/shared_memory.h"" + #include ""base/message_loop/message_loop.h"" + #include ""base/run_loop.h"" + #include ""base/single_thread_task_runner.h"" +@@ -28,6 +29,8 @@ + #include ""chrome/common/pref_names.h"" + #include ""chrome/grit/generated_resources.h"" + #include ""components/prefs/pref_service.h"" ++#include ""components/printing/browser/print_composite_client.h"" ++#include ""components/printing/browser/print_manager_utils.h"" + #include ""components/printing/common/print_messages.h"" + #include ""content/public/browser/browser_thread.h"" + #include ""content/public/browser/notification_details.h"" +@@ -36,8 +39,10 @@ + #include ""content/public/browser/render_frame_host.h"" + #include ""content/public/browser/render_view_host.h"" + #include ""content/public/browser/web_contents.h"" ++#include ""mojo/public/cpp/system/buffer.h"" + #include ""printing/features/features.h"" + #include ""printing/pdf_metafile_skia.h"" ++#include ""printing/print_settings.h"" + #include ""printing/printed_document.h"" + #include ""ui/base/l10n/l10n_util.h"" + +@@ -78,7 +83,8 @@ PrintViewManagerBase::PrintViewManagerBase(content::WebContents* web_contents) + #if !defined(OS_MACOSX) + expecting_first_page_(true), + #endif +- queue_(g_browser_process->print_job_manager()->queue()) { ++ queue_(g_browser_process->print_job_manager()->queue()), ++ weak_ptr_factory_(this) { + DCHECK(queue_.get()); + Profile* profile = + Profile::FromBrowserContext(web_contents->GetBrowserContext()); +@@ -127,8 +133,24 @@ void PrintViewManagerBase::OnDidGetPrintedPagesCount(int cookie, + OpportunisticallyCreatePrintJob(cookie); + } + ++void PrintViewManagerBase::OnComposePdfDone( ++ const PrintHostMsg_DidPrintPage_Params& params, ++ mojom::PdfCompositor::Status status, ++ mojo::ScopedSharedBufferHandle handle) { ++ DCHECK_CURRENTLY_ON(content::BrowserThread::UI); ++ if (status != mojom::PdfCompositor::Status::SUCCESS) { ++ DLOG(ERROR) << ""Compositing pdf failed with error "" << status; ++ return; ++ } ++ ++ UpdateForPrintedPage( ++ params, true, ++ PrintCompositeClient::GetShmFromMojoHandle(std::move(handle))); ++} ++ + void PrintViewManagerBase::OnDidPrintPage( +- const PrintHostMsg_DidPrintPage_Params& params) { ++ const PrintHostMsg_DidPrintPage_Params& params) { ++ // Ready to composite. Starting a print job. + if (!OpportunisticallyCreatePrintJob(params.document_cookie)) + return; + +@@ -154,8 +176,18 @@ void PrintViewManagerBase::OnDidPrintPage( + web_contents()->Stop(); + return; + } ++ ++ auto* client = PrintCompositeClient::FromWebContents(web_contents()); ++ if (IsOopifEnabled() && !client->for_preview() && ++ !document->settings().is_modifiable()) { ++ client->DoComposite( ++ params.metafile_data_handle, params.data_size, ++ base::BindOnce(&PrintViewManagerBase::OnComposePdfDone, ++ weak_ptr_factory_.GetWeakPtr(), params)); ++ return; ++ } + shared_buf = +- base::MakeUnique(params.metafile_data_handle, true); ++ std::make_unique(params.metafile_data_handle, true); + if (!shared_buf->Map(params.data_size)) { + NOTREACHED() << ""couldn't map""; + web_contents()->Stop(); +@@ -170,22 +202,24 @@ void PrintViewManagerBase::OnDidPrintPage( + } + } + +- std::unique_ptr metafile( +- new PdfMetafileSkia(SkiaDocumentType::PDF)); +- if (metafile_must_be_valid) { +- if (!metafile->InitFromData(shared_buf->memory(), params.data_size)) { +- NOTREACHED() << ""Invalid metafile header""; +- web_contents()->Stop(); +- return; +- } +- } ++ UpdateForPrintedPage(params, metafile_must_be_valid, std::move(shared_buf)); ++} ++ ++void PrintViewManagerBase::UpdateForPrintedPage( ++ const PrintHostMsg_DidPrintPage_Params& params, ++ bool has_valid_page_data, ++ std::unique_ptr shared_buf) { ++ PrintedDocument* document = print_job_->document(); ++ if (!document) ++ return; + + #if defined(OS_WIN) + print_job_->AppendPrintedPage(params.page_number); +- if (metafile_must_be_valid) { +- scoped_refptr bytes = new base::RefCountedBytes( ++ if (has_valid_page_data) { ++ scoped_refptr bytes(new base::RefCountedBytes( + reinterpret_cast(shared_buf->memory()), +- params.data_size); ++ shared_buf->mapped_size())); ++ + document->DebugDumpData(bytes.get(), FILE_PATH_LITERAL("".pdf"")); + + const auto& settings = document->settings(); +@@ -203,22 +237,27 @@ void PrintViewManagerBase::OnDidPrintPage( + // Update : The missing letters seem to have been caused by the same + // problem as https://crbug.com/659604 which was resolved. GDI printing + // seems to work with the fix for this bug applied. +- bool print_text_with_gdi = settings.print_text_with_gdi() && +- !settings.printer_is_xps() && +- base::FeatureList::IsEnabled( +- features::kGdiTextPrinting); ++ bool print_text_with_gdi = ++ settings.print_text_with_gdi() && !settings.printer_is_xps() && ++ base::FeatureList::IsEnabled(features::kGdiTextPrinting); + print_job_->StartPdfToEmfConversion( + bytes, params.page_size, params.content_area, print_text_with_gdi); + } + } + #else ++ std::unique_ptr metafile = ++ std::make_unique(SkiaDocumentType::PDF); ++ if (has_valid_page_data) { ++ if (!metafile->InitFromData(shared_buf->memory(), ++ shared_buf->mapped_size())) { ++ NOTREACHED() << ""Invalid metafile header""; ++ web_contents()->Stop(); ++ return; ++ } ++ } ++ + // Update the rendered document. It will send notifications to the listener. +- document->SetPage(params.page_number, +- std::move(metafile), +-#if defined(OS_WIN) +- 0.0f /* dummy shrink_factor */, +-#endif +- params.page_size, ++ document->SetPage(params.page_number, std::move(metafile), params.page_size, + params.content_area); + + ShouldQuitFromInnerMessageLoop();",716,1047,2048 +5920,"macros_trusted(BOOL opt_D_used) +{ +#ifdef WHITELIST_D_MACROS +macro_item *m; +uschar *whitelisted, *end, *p, **whites, **w; +int white_count, i, n; +size_t len; +BOOL prev_char_item, found; +#endif + +if (!opt_D_used) + return TRUE; +#ifndef WHITELIST_D_MACROS +return FALSE; +#else + +/* We only trust -D overrides for some invoking users: +root, the exim run-time user, the optional config owner user. +I don't know why config-owner would be needed, but since they can own the +config files anyway, there's no security risk to letting them override -D. */ +if ( ! ((real_uid == root_uid) + || (real_uid == exim_uid) +#ifdef CONFIGURE_OWNER + || (real_uid == config_uid) +#endif + )) + { + debug_printf(""macros_trusted rejecting macros for uid %d\n"", (int) real_uid); + return FALSE; + } + +/* Get a list of macros which are whitelisted */ +whitelisted = string_copy_malloc(US WHITELIST_D_MACROS); +prev_char_item = FALSE; +white_count = 0; +for (p = whitelisted; *p != '\0'; ++p) + { + if (*p == ':' || isspace(*p)) + { + *p = '\0'; + if (prev_char_item) + ++white_count; + prev_char_item = FALSE; + continue; + } + if (!prev_char_item) + prev_char_item = TRUE; + } +end = p; +if (prev_char_item) + ++white_count; +if (!white_count) + return FALSE; +whites = store_malloc(sizeof(uschar *) * (white_count+1)); +for (p = whitelisted, i = 0; (p != end) && (i < white_count); ++p) + { + if (*p != '\0') + { + whites[i++] = p; + if (i == white_count) + break; + while (*p != '\0' && p < end) + ++p; + } + } +whites[i] = NULL; + +/* The list of commandline macros should be very short. +Accept the N*M complexity. */ +for (m = macros; m; m = m->next) if (m->command_line) + { + found = FALSE; + for (w = whites; *w; ++w) + if (Ustrcmp(*w, m->name) == 0) + { + found = TRUE; + break; + } + if (!found) + return FALSE; + if (m->replacement == NULL) + continue; + len = Ustrlen(m->replacement); + if (len == 0) + continue; + n = pcre_exec(regex_whitelisted_macro, NULL, CS m->replacement, len, + 0, PCRE_EOPT, NULL, 0); + if (n < 0) + { + if (n != PCRE_ERROR_NOMATCH) + debug_printf(""macros_trusted checking %s returned %d\n"", m->name, n); + return FALSE; + } + } +DEBUG(D_any) debug_printf(""macros_trusted overridden to true by whitelisting\n""); +return TRUE; +#endif +} +",0,"macros_trusted(BOOL opt_D_used) +{ +#ifdef WHITELIST_D_MACROS +macro_item *m; +uschar *whitelisted, *end, *p, **whites, **w; +int white_count, i, n; +size_t len; +BOOL prev_char_item, found; +#endif + +if (!opt_D_used) + return TRUE; +#ifndef WHITELIST_D_MACROS +return FALSE; +#else + +/* We only trust -D overrides for some invoking users: +root, the exim run-time user, the optional config owner user. +I don't know why config-owner would be needed, but since they can own the +config files anyway, there's no security risk to letting them override -D. */ +if ( ! ((real_uid == root_uid) + || (real_uid == exim_uid) +#ifdef CONFIGURE_OWNER + || (real_uid == config_uid) +#endif + )) + { + debug_printf(""macros_trusted rejecting macros for uid %d\n"", (int) real_uid); + return FALSE; + } + +/* Get a list of macros which are whitelisted */ +whitelisted = string_copy_malloc(US WHITELIST_D_MACROS); +prev_char_item = FALSE; +white_count = 0; +for (p = whitelisted; *p != '\0'; ++p) + { + if (*p == ':' || isspace(*p)) + { + *p = '\0'; + if (prev_char_item) + ++white_count; + prev_char_item = FALSE; + continue; + } + if (!prev_char_item) + prev_char_item = TRUE; + } +end = p; +if (prev_char_item) + ++white_count; +if (!white_count) + return FALSE; +whites = store_malloc(sizeof(uschar *) * (white_count+1)); +for (p = whitelisted, i = 0; (p != end) && (i < white_count); ++p) + { + if (*p != '\0') + { + whites[i++] = p; + if (i == white_count) + break; + while (*p != '\0' && p < end) + ++p; + } + } +whites[i] = NULL; + +/* The list of commandline macros should be very short. +Accept the N*M complexity. */ +for (m = macros; m; m = m->next) if (m->command_line) + { + found = FALSE; + for (w = whites; *w; ++w) + if (Ustrcmp(*w, m->name) == 0) + { + found = TRUE; + break; + } + if (!found) + return FALSE; + if (m->replacement == NULL) + continue; + len = Ustrlen(m->replacement); + if (len == 0) + continue; + n = pcre_exec(regex_whitelisted_macro, NULL, CS m->replacement, len, + 0, PCRE_EOPT, NULL, 0); + if (n < 0) + { + if (n != PCRE_ERROR_NOMATCH) + debug_printf(""macros_trusted checking %s returned %d\n"", m->name, n); + return FALSE; + } + } +DEBUG(D_any) debug_printf(""macros_trusted overridden to true by whitelisting\n""); +return TRUE; +#endif +} +","@@ -3106,7 +3106,14 @@ for (i = 1; i < argc; i++) + + /* -oMr: Received protocol */ + +- else if (Ustrcmp(argrest, ""Mr"") == 0) received_protocol = argv[++i]; ++ else if (Ustrcmp(argrest, ""Mr"") == 0) ++ ++ if (received_protocol) ++ { ++ fprintf(stderr, ""received_protocol is set already\n""); ++ exit(EXIT_FAILURE); ++ } ++ else received_protocol = argv[++i]; + + /* -oMs: Set sender host name */ + +@@ -3202,7 +3209,15 @@ for (i = 1; i < argc; i++) + + if (*argrest != 0) + { +- uschar *hn = Ustrchr(argrest, ':'); ++ uschar *hn; ++ ++ if (received_protocol) ++ { ++ fprintf(stderr, ""received_protocol is set already\n""); ++ exit(EXIT_FAILURE); ++ } ++ ++ hn = Ustrchr(argrest, ':'); + if (hn == NULL) + { + received_protocol = argrest;",706,1037,2048 +16599,"void RenderFrameImpl::CommitNavigation( + const network::ResourceResponseHead& head, + const CommonNavigationParams& common_params, + const RequestNavigationParams& request_params, + network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints, + std::unique_ptr subresource_loader_factories, + base::Optional> + subresource_overrides, + blink::mojom::ControllerServiceWorkerInfoPtr controller_service_worker_info, + network::mojom::URLLoaderFactoryPtr prefetch_loader_factory, + const base::UnguessableToken& devtools_navigation_token, + CommitNavigationCallback callback) { + DCHECK(!IsRendererDebugURL(common_params.url)); + DCHECK( + !FrameMsg_Navigate_Type::IsSameDocument(common_params.navigation_type)); + if (!browser_side_navigation_pending_ && + !browser_side_navigation_pending_url_.is_empty() && + browser_side_navigation_pending_url_ == request_params.original_url && + request_params.nav_entry_id == 0) { + browser_side_navigation_pending_url_ = GURL(); + std::move(callback).Run(blink::mojom::CommitResult::Aborted); + return; + } + + DCHECK(common_params.url.SchemeIs(url::kJavaScriptScheme) || + !base::FeatureList::IsEnabled(network::features::kNetworkService) || + subresource_loader_factories); + + SetupLoaderFactoryBundle(std::move(subresource_loader_factories), + std::move(subresource_overrides), + std::move(prefetch_loader_factory)); + + if (request_params.is_view_source) + frame_->EnableViewSourceMode(true); + + PrepareFrameForCommit(common_params.url, request_params); + + const network::ResourceResponseHead* response_head = nullptr; + if (!frame_->Parent() && !frame_->IsViewSourceModeEnabled()) + response_head = &head; + std::unique_ptr document_state(BuildDocumentStateFromParams( + common_params, request_params, base::TimeTicks::Now(), + std::move(callback), response_head)); + + blink::WebFrameLoadType load_type = NavigationTypeToLoadType( + common_params.navigation_type, common_params.should_replace_current_entry, + request_params.page_state.IsValid()); + + WebHistoryItem item_for_history_navigation; + blink::mojom::CommitResult commit_status = blink::mojom::CommitResult::Ok; + + if (load_type == WebFrameLoadType::kBackForward) { + DCHECK_NE(0, request_params.nav_entry_id); + + commit_status = PrepareForHistoryNavigationCommit( + common_params.navigation_type, request_params, + &item_for_history_navigation, &load_type); + } + + if (commit_status != blink::mojom::CommitResult::Ok) { + if (frame_ && !frame_->IsLoading()) + Send(new FrameHostMsg_DidStopLoading(routing_id_)); + return; + } + + base::WeakPtr weak_this = weak_factory_.GetWeakPtr(); + bool is_client_redirect = + !!(common_params.transition & ui::PAGE_TRANSITION_CLIENT_REDIRECT); + + auto navigation_params = + std::make_unique(devtools_navigation_token); + navigation_params->frame_load_type = load_type; + navigation_params->history_item = item_for_history_navigation; + navigation_params->is_client_redirect = is_client_redirect; + navigation_params->service_worker_network_provider = + BuildServiceWorkerNetworkProviderForNavigation( + &request_params, std::move(controller_service_worker_info)); + FillNavigationParams(common_params, request_params, navigation_params.get()); + + bool should_load_data_url = !common_params.base_url_for_data_url.is_empty(); +#if defined(OS_ANDROID) + should_load_data_url |= !request_params.data_url_as_string.empty(); +#endif + if (is_main_frame_ && should_load_data_url) { + std::string mime_type, charset, data; + GURL base_url; + DecodeDataURL(common_params, request_params, &mime_type, &charset, &data, + &base_url); + navigation_params->request = WebURLRequest(base_url); + navigation_params->data = WebData(data.c_str(), data.length()); + navigation_params->mime_type = WebString::FromUTF8(mime_type); + navigation_params->text_encoding = WebString::FromUTF8(charset); + navigation_params->unreachable_url = common_params.history_url_for_data_url; + } else { + navigation_params->request = + CreateURLRequestForCommit(common_params, request_params, + std::move(url_loader_client_endpoints), head); + } + + committing_main_request_ = true; + frame_->CommitNavigation(std::move(navigation_params), + std::move(document_state)); + if (!weak_this) + return; + committing_main_request_ = false; +} +",0,"void RenderFrameImpl::CommitNavigation( + const network::ResourceResponseHead& head, + const CommonNavigationParams& common_params, + const RequestNavigationParams& request_params, + network::mojom::URLLoaderClientEndpointsPtr url_loader_client_endpoints, + std::unique_ptr subresource_loader_factories, + base::Optional> + subresource_overrides, + blink::mojom::ControllerServiceWorkerInfoPtr controller_service_worker_info, + network::mojom::URLLoaderFactoryPtr prefetch_loader_factory, + const base::UnguessableToken& devtools_navigation_token, + CommitNavigationCallback callback) { + DCHECK(!IsRendererDebugURL(common_params.url)); + DCHECK( + !FrameMsg_Navigate_Type::IsSameDocument(common_params.navigation_type)); + if (!browser_side_navigation_pending_ && + !browser_side_navigation_pending_url_.is_empty() && + browser_side_navigation_pending_url_ == request_params.original_url && + request_params.nav_entry_id == 0) { + browser_side_navigation_pending_url_ = GURL(); + std::move(callback).Run(blink::mojom::CommitResult::Aborted); + return; + } + + DCHECK(common_params.url.SchemeIs(url::kJavaScriptScheme) || + !base::FeatureList::IsEnabled(network::features::kNetworkService) || + subresource_loader_factories); + + SetupLoaderFactoryBundle(std::move(subresource_loader_factories), + std::move(subresource_overrides), + std::move(prefetch_loader_factory)); + + if (request_params.is_view_source) + frame_->EnableViewSourceMode(true); + + PrepareFrameForCommit(common_params.url, request_params); + + const network::ResourceResponseHead* response_head = nullptr; + if (!frame_->Parent() && !frame_->IsViewSourceModeEnabled()) + response_head = &head; + std::unique_ptr document_state(BuildDocumentStateFromParams( + common_params, request_params, base::TimeTicks::Now(), + std::move(callback), response_head)); + + blink::WebFrameLoadType load_type = NavigationTypeToLoadType( + common_params.navigation_type, common_params.should_replace_current_entry, + request_params.page_state.IsValid()); + + WebHistoryItem item_for_history_navigation; + blink::mojom::CommitResult commit_status = blink::mojom::CommitResult::Ok; + + if (load_type == WebFrameLoadType::kBackForward) { + DCHECK_NE(0, request_params.nav_entry_id); + + commit_status = PrepareForHistoryNavigationCommit( + common_params.navigation_type, request_params, + &item_for_history_navigation, &load_type); + } + + if (commit_status != blink::mojom::CommitResult::Ok) { + if (frame_ && !frame_->IsLoading()) + Send(new FrameHostMsg_DidStopLoading(routing_id_)); + return; + } + + base::WeakPtr weak_this = weak_factory_.GetWeakPtr(); + bool is_client_redirect = + !!(common_params.transition & ui::PAGE_TRANSITION_CLIENT_REDIRECT); + + auto navigation_params = + std::make_unique(devtools_navigation_token); + navigation_params->frame_load_type = load_type; + navigation_params->history_item = item_for_history_navigation; + navigation_params->is_client_redirect = is_client_redirect; + navigation_params->service_worker_network_provider = + BuildServiceWorkerNetworkProviderForNavigation( + &request_params, std::move(controller_service_worker_info)); + FillNavigationParams(common_params, request_params, navigation_params.get()); + + bool should_load_data_url = !common_params.base_url_for_data_url.is_empty(); +#if defined(OS_ANDROID) + should_load_data_url |= !request_params.data_url_as_string.empty(); +#endif + if (is_main_frame_ && should_load_data_url) { + std::string mime_type, charset, data; + GURL base_url; + DecodeDataURL(common_params, request_params, &mime_type, &charset, &data, + &base_url); + navigation_params->request = WebURLRequest(base_url); + navigation_params->data = WebData(data.c_str(), data.length()); + navigation_params->mime_type = WebString::FromUTF8(mime_type); + navigation_params->text_encoding = WebString::FromUTF8(charset); + navigation_params->unreachable_url = common_params.history_url_for_data_url; + } else { + navigation_params->request = + CreateURLRequestForCommit(common_params, request_params, + std::move(url_loader_client_endpoints), head); + } + + committing_main_request_ = true; + frame_->CommitNavigation(std::move(navigation_params), + std::move(document_state)); + if (!weak_this) + return; + committing_main_request_ = false; +} +","@@ -6378,8 +6378,12 @@ void RenderFrameImpl::OnSelectPopupMenuItem(int selected_index) { + return; + + blink::WebScopedUserGesture gesture(frame_); +- external_popup_menu_->DidSelectItem(selected_index); +- external_popup_menu_.reset(); ++ // We need to reset |external_popup_menu_| before calling DidSelectItem(), ++ // which might delete |this|. ++ // See ExternalPopupMenuRemoveTest.RemoveFrameOnChange ++ std::unique_ptr popup; ++ popup.swap(external_popup_menu_); ++ popup->DidSelectItem(selected_index); + } + #else + void RenderFrameImpl::OnSelectPopupMenuItems( +@@ -6393,8 +6397,12 @@ void RenderFrameImpl::OnSelectPopupMenuItems( + return; + + blink::WebScopedUserGesture gesture(frame_); +- external_popup_menu_->DidSelectItems(canceled, selected_indices); +- external_popup_menu_.reset(); ++ // We need to reset |external_popup_menu_| before calling DidSelectItems(), ++ // which might delete |this|. ++ // See ExternalPopupMenuRemoveTest.RemoveFrameOnChange ++ std::unique_ptr popup; ++ popup.swap(external_popup_menu_); ++ popup->DidSelectItems(canceled, selected_indices); + } + #endif + #endif",991,1322,2048 +14654,"void Document::InheritHtmlAndBodyElementStyles(StyleRecalcChange change) { + DCHECK(InStyleRecalc()); + DCHECK(documentElement()); + + bool did_recalc_document_element = false; + RefPtr document_element_style = + documentElement()->MutableComputedStyle(); + if (change == kForce) + documentElement()->ClearAnimationStyleChange(); + if (!document_element_style || documentElement()->NeedsStyleRecalc() || + change == kForce) { + document_element_style = + EnsureStyleResolver().StyleForElement(documentElement()); + did_recalc_document_element = true; + } + + WritingMode root_writing_mode = document_element_style->GetWritingMode(); + TextDirection root_direction = document_element_style->Direction(); + + HTMLElement* body = this->body(); + RefPtr body_style; + + if (body) { + body_style = body->MutableComputedStyle(); + if (did_recalc_document_element) + body->ClearAnimationStyleChange(); + if (!body_style || body->NeedsStyleRecalc() || + did_recalc_document_element) { + body_style = EnsureStyleResolver().StyleForElement( + body, document_element_style.Get(), document_element_style.Get()); + } + root_writing_mode = body_style->GetWritingMode(); + root_direction = body_style->Direction(); + } + + const ComputedStyle* background_style = document_element_style.Get(); + if (isHTMLHtmlElement(documentElement()) && isHTMLBodyElement(body) && + !background_style->HasBackground()) + background_style = body_style.Get(); + + Node& root_scroller = GetRootScrollerController().EffectiveRootScroller(); + RefPtr root_scroller_style; + if (this != &root_scroller) { + DCHECK(root_scroller.IsElementNode()); + Element* root_scroller_element = ToElement(&root_scroller); + root_scroller_style = root_scroller_element->MutableComputedStyle(); + + if (!root_scroller_style || root_scroller_element->NeedsStyleRecalc()) { + root_scroller_style = + EnsureStyleResolver().StyleForElement(root_scroller_element); + } + + background_style = root_scroller_style.Get(); + } + + Color background_color = + background_style->VisitedDependentColor(CSSPropertyBackgroundColor); + FillLayer background_layers = background_style->BackgroundLayers(); + for (auto current_layer = &background_layers; current_layer; + current_layer = current_layer->Next()) { + current_layer->SetClip(kBorderFillBox); + + if (current_layer->Attachment() == kScrollBackgroundAttachment) + current_layer->SetAttachment(kLocalBackgroundAttachment); + } + EImageRendering image_rendering = background_style->ImageRendering(); + + const ComputedStyle* overflow_style = nullptr; + if (Element* element = + ViewportDefiningElement(document_element_style.Get())) { + if (element == body) { + overflow_style = body_style.Get(); + } else { + DCHECK_EQ(element, documentElement()); + overflow_style = document_element_style.Get(); + + if (body_style && !body_style->IsOverflowVisible()) + UseCounter::Count(*this, WebFeature::kBodyScrollsInAdditionToViewport); + } + } + + if (GetStyleEngine().UsesRemUnits() && + (documentElement()->NeedsAttach() || + !documentElement()->GetComputedStyle() || + documentElement()->GetComputedStyle()->FontSize() != + document_element_style->FontSize())) { + EnsureStyleResolver().InvalidateMatchedPropertiesCache(); + documentElement()->SetNeedsStyleRecalc( + kSubtreeStyleChange, StyleChangeReasonForTracing::Create( + StyleChangeReason::kFontSizeChange)); + } + + EOverflowAnchor overflow_anchor = EOverflowAnchor::kAuto; + EOverflow overflow_x = EOverflow::kAuto; + EOverflow overflow_y = EOverflow::kAuto; + float column_gap = 0; + if (overflow_style) { + overflow_anchor = overflow_style->OverflowAnchor(); + overflow_x = overflow_style->OverflowX(); + overflow_y = overflow_style->OverflowY(); + if (overflow_x == EOverflow::kVisible) + overflow_x = EOverflow::kAuto; + if (overflow_y == EOverflow::kVisible) + overflow_y = EOverflow::kAuto; + if (overflow_anchor == EOverflowAnchor::kVisible) + overflow_anchor = EOverflowAnchor::kAuto; + column_gap = overflow_style->ColumnGap(); + } + + ScrollSnapType snap_type = overflow_style->GetScrollSnapType(); + + RefPtr viewport_style = GetLayoutViewItem().MutableStyle(); + if (viewport_style->GetWritingMode() != root_writing_mode || + viewport_style->Direction() != root_direction || + viewport_style->VisitedDependentColor(CSSPropertyBackgroundColor) != + background_color || + viewport_style->BackgroundLayers() != background_layers || + viewport_style->ImageRendering() != image_rendering || + viewport_style->OverflowAnchor() != overflow_anchor || + viewport_style->OverflowX() != overflow_x || + viewport_style->OverflowY() != overflow_y || + viewport_style->ColumnGap() != column_gap || + viewport_style->GetScrollSnapType() != snap_type) { + RefPtr new_style = ComputedStyle::Clone(*viewport_style); + new_style->SetWritingMode(root_writing_mode); + new_style->SetDirection(root_direction); + new_style->SetBackgroundColor(background_color); + new_style->AccessBackgroundLayers() = background_layers; + new_style->SetImageRendering(image_rendering); + new_style->SetOverflowAnchor(overflow_anchor); + new_style->SetOverflowX(overflow_x); + new_style->SetOverflowY(overflow_y); + new_style->SetColumnGap(column_gap); + new_style->SetScrollSnapType(snap_type); + GetLayoutViewItem().SetStyle(new_style); + SetupFontBuilder(*new_style); + } + + if (body) { + if (const ComputedStyle* style = body->GetComputedStyle()) { + if (style->Direction() != root_direction || + style->GetWritingMode() != root_writing_mode) + body->SetNeedsStyleRecalc(kSubtreeStyleChange, + StyleChangeReasonForTracing::Create( + StyleChangeReason::kWritingModeChange)); + } + } + + if (const ComputedStyle* style = documentElement()->GetComputedStyle()) { + if (style->Direction() != root_direction || + style->GetWritingMode() != root_writing_mode) + documentElement()->SetNeedsStyleRecalc( + kSubtreeStyleChange, StyleChangeReasonForTracing::Create( + StyleChangeReason::kWritingModeChange)); + } +} +",0,"void Document::InheritHtmlAndBodyElementStyles(StyleRecalcChange change) { + DCHECK(InStyleRecalc()); + DCHECK(documentElement()); + + bool did_recalc_document_element = false; + RefPtr document_element_style = + documentElement()->MutableComputedStyle(); + if (change == kForce) + documentElement()->ClearAnimationStyleChange(); + if (!document_element_style || documentElement()->NeedsStyleRecalc() || + change == kForce) { + document_element_style = + EnsureStyleResolver().StyleForElement(documentElement()); + did_recalc_document_element = true; + } + + WritingMode root_writing_mode = document_element_style->GetWritingMode(); + TextDirection root_direction = document_element_style->Direction(); + + HTMLElement* body = this->body(); + RefPtr body_style; + + if (body) { + body_style = body->MutableComputedStyle(); + if (did_recalc_document_element) + body->ClearAnimationStyleChange(); + if (!body_style || body->NeedsStyleRecalc() || + did_recalc_document_element) { + body_style = EnsureStyleResolver().StyleForElement( + body, document_element_style.Get(), document_element_style.Get()); + } + root_writing_mode = body_style->GetWritingMode(); + root_direction = body_style->Direction(); + } + + const ComputedStyle* background_style = document_element_style.Get(); + if (isHTMLHtmlElement(documentElement()) && isHTMLBodyElement(body) && + !background_style->HasBackground()) + background_style = body_style.Get(); + + Node& root_scroller = GetRootScrollerController().EffectiveRootScroller(); + RefPtr root_scroller_style; + if (this != &root_scroller) { + DCHECK(root_scroller.IsElementNode()); + Element* root_scroller_element = ToElement(&root_scroller); + root_scroller_style = root_scroller_element->MutableComputedStyle(); + + if (!root_scroller_style || root_scroller_element->NeedsStyleRecalc()) { + root_scroller_style = + EnsureStyleResolver().StyleForElement(root_scroller_element); + } + + background_style = root_scroller_style.Get(); + } + + Color background_color = + background_style->VisitedDependentColor(CSSPropertyBackgroundColor); + FillLayer background_layers = background_style->BackgroundLayers(); + for (auto current_layer = &background_layers; current_layer; + current_layer = current_layer->Next()) { + current_layer->SetClip(kBorderFillBox); + + if (current_layer->Attachment() == kScrollBackgroundAttachment) + current_layer->SetAttachment(kLocalBackgroundAttachment); + } + EImageRendering image_rendering = background_style->ImageRendering(); + + const ComputedStyle* overflow_style = nullptr; + if (Element* element = + ViewportDefiningElement(document_element_style.Get())) { + if (element == body) { + overflow_style = body_style.Get(); + } else { + DCHECK_EQ(element, documentElement()); + overflow_style = document_element_style.Get(); + + if (body_style && !body_style->IsOverflowVisible()) + UseCounter::Count(*this, WebFeature::kBodyScrollsInAdditionToViewport); + } + } + + if (GetStyleEngine().UsesRemUnits() && + (documentElement()->NeedsAttach() || + !documentElement()->GetComputedStyle() || + documentElement()->GetComputedStyle()->FontSize() != + document_element_style->FontSize())) { + EnsureStyleResolver().InvalidateMatchedPropertiesCache(); + documentElement()->SetNeedsStyleRecalc( + kSubtreeStyleChange, StyleChangeReasonForTracing::Create( + StyleChangeReason::kFontSizeChange)); + } + + EOverflowAnchor overflow_anchor = EOverflowAnchor::kAuto; + EOverflow overflow_x = EOverflow::kAuto; + EOverflow overflow_y = EOverflow::kAuto; + float column_gap = 0; + if (overflow_style) { + overflow_anchor = overflow_style->OverflowAnchor(); + overflow_x = overflow_style->OverflowX(); + overflow_y = overflow_style->OverflowY(); + if (overflow_x == EOverflow::kVisible) + overflow_x = EOverflow::kAuto; + if (overflow_y == EOverflow::kVisible) + overflow_y = EOverflow::kAuto; + if (overflow_anchor == EOverflowAnchor::kVisible) + overflow_anchor = EOverflowAnchor::kAuto; + column_gap = overflow_style->ColumnGap(); + } + + ScrollSnapType snap_type = overflow_style->GetScrollSnapType(); + + RefPtr viewport_style = GetLayoutViewItem().MutableStyle(); + if (viewport_style->GetWritingMode() != root_writing_mode || + viewport_style->Direction() != root_direction || + viewport_style->VisitedDependentColor(CSSPropertyBackgroundColor) != + background_color || + viewport_style->BackgroundLayers() != background_layers || + viewport_style->ImageRendering() != image_rendering || + viewport_style->OverflowAnchor() != overflow_anchor || + viewport_style->OverflowX() != overflow_x || + viewport_style->OverflowY() != overflow_y || + viewport_style->ColumnGap() != column_gap || + viewport_style->GetScrollSnapType() != snap_type) { + RefPtr new_style = ComputedStyle::Clone(*viewport_style); + new_style->SetWritingMode(root_writing_mode); + new_style->SetDirection(root_direction); + new_style->SetBackgroundColor(background_color); + new_style->AccessBackgroundLayers() = background_layers; + new_style->SetImageRendering(image_rendering); + new_style->SetOverflowAnchor(overflow_anchor); + new_style->SetOverflowX(overflow_x); + new_style->SetOverflowY(overflow_y); + new_style->SetColumnGap(column_gap); + new_style->SetScrollSnapType(snap_type); + GetLayoutViewItem().SetStyle(new_style); + SetupFontBuilder(*new_style); + } + + if (body) { + if (const ComputedStyle* style = body->GetComputedStyle()) { + if (style->Direction() != root_direction || + style->GetWritingMode() != root_writing_mode) + body->SetNeedsStyleRecalc(kSubtreeStyleChange, + StyleChangeReasonForTracing::Create( + StyleChangeReason::kWritingModeChange)); + } + } + + if (const ComputedStyle* style = documentElement()->GetComputedStyle()) { + if (style->Direction() != root_direction || + style->GetWritingMode() != root_writing_mode) + documentElement()->SetNeedsStyleRecalc( + kSubtreeStyleChange, StyleChangeReasonForTracing::Create( + StyleChangeReason::kWritingModeChange)); + } +} +","@@ -5839,6 +5839,8 @@ void Document::InitSecurityContext(const DocumentInit& initializer) { + AddInsecureNavigationUpgrade(to_upgrade); + } + ++ ContentSecurityPolicy* policy_to_inherit = nullptr; ++ + if (IsSandboxed(kSandboxOrigin)) { + cookie_url_ = url_; + SetSecurityOrigin(SecurityOrigin::CreateUnique()); +@@ -5854,12 +5856,14 @@ void Document::InitSecurityContext(const DocumentInit& initializer) { + GetSecurityOrigin()->SetUniqueOriginIsPotentiallyTrustworthy(true); + if (owner->GetSecurityOrigin()->CanLoadLocalResources()) + GetSecurityOrigin()->GrantLoadLocalResources(); ++ policy_to_inherit = owner->GetContentSecurityPolicy(); + } + } else if (Document* owner = initializer.OwnerDocument()) { + cookie_url_ = owner->CookieURL(); + // We alias the SecurityOrigins to match Firefox, see Bug 15313 + // https://bugs.webkit.org/show_bug.cgi?id=15313 + SetSecurityOrigin(owner->GetSecurityOrigin()); ++ policy_to_inherit = owner->GetContentSecurityPolicy(); + } else { + cookie_url_ = url_; + SetSecurityOrigin(SecurityOrigin::Create(url_)); +@@ -5891,7 +5895,7 @@ void Document::InitSecurityContext(const DocumentInit& initializer) { + SetContentSecurityPolicy( + ImportsController()->Master()->GetContentSecurityPolicy()); + } else { +- InitContentSecurityPolicy(); ++ InitContentSecurityPolicy(nullptr, policy_to_inherit); + } + + if (GetSecurityOrigin()->HasSuborigin()) +@@ -5926,7 +5930,13 @@ void Document::InitSecurityContext(const DocumentInit& initializer) { + SetFeaturePolicy(g_empty_string); + } + +-void Document::InitContentSecurityPolicy(ContentSecurityPolicy* csp) { ++// the first parameter specifies a policy to use as the document csp meaning ++// the document will take ownership of the policy ++// the second parameter specifies a policy to inherit meaning the document ++// will attempt to copy over the policy ++void Document::InitContentSecurityPolicy( ++ ContentSecurityPolicy* csp, ++ const ContentSecurityPolicy* policy_to_inherit) { + SetContentSecurityPolicy(csp ? csp : ContentSecurityPolicy::Create()); + + // We inherit the parent/opener's CSP for documents with ""local"" schemes: +@@ -5938,24 +5948,27 @@ void Document::InitContentSecurityPolicy(ContentSecurityPolicy* csp) { + // + // TODO(dcheng): This is similar enough to work we're doing in + // 'DocumentLoader::ensureWriter' that it might make sense to combine them. +- if (frame_) { ++ if (policy_to_inherit) { ++ GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit); ++ } else if (frame_) { + Frame* inherit_from = frame_->Tree().Parent() ? frame_->Tree().Parent() + : frame_->Client()->Opener(); + if (inherit_from && frame_ != inherit_from) { + DCHECK(inherit_from->GetSecurityContext() && + inherit_from->GetSecurityContext()->GetContentSecurityPolicy()); +- ContentSecurityPolicy* policy_to_inherit = ++ policy_to_inherit = + inherit_from->GetSecurityContext()->GetContentSecurityPolicy(); + if (url_.IsEmpty() || url_.ProtocolIsAbout() || url_.ProtocolIsData() || + url_.ProtocolIs(""blob"") || url_.ProtocolIs(""filesystem"")) { + GetContentSecurityPolicy()->CopyStateFrom(policy_to_inherit); + } +- // Plugin documents inherit their parent/opener's 'plugin-types' directive +- // regardless of URL. +- if (IsPluginDocument()) +- GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit); + } + } ++ // Plugin documents inherit their parent/opener's 'plugin-types' directive ++ // regardless of URL. ++ if (policy_to_inherit && IsPluginDocument()) ++ GetContentSecurityPolicy()->CopyPluginTypesFrom(policy_to_inherit); ++ + GetContentSecurityPolicy()->BindToExecutionContext(this); + } + ",1392,1723,2048 +18300,"ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, + const struct isakmp_gen *ext, u_int item_len, + const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_, + uint32_t proto0 _U_, int depth _U_) +{ + const struct ikev1_pl_n *p; + struct ikev1_pl_n n; + const u_char *cp; + const u_char *ep2; + uint32_t doi; + uint32_t proto; + static const char *notify_error_str[] = { + NULL, ""INVALID-PAYLOAD-TYPE"", + ""DOI-NOT-SUPPORTED"", ""SITUATION-NOT-SUPPORTED"", + ""INVALID-COOKIE"", ""INVALID-MAJOR-VERSION"", + ""INVALID-MINOR-VERSION"", ""INVALID-EXCHANGE-TYPE"", + ""INVALID-FLAGS"", ""INVALID-MESSAGE-ID"", + ""INVALID-PROTOCOL-ID"", ""INVALID-SPI"", + ""INVALID-TRANSFORM-ID"", ""ATTRIBUTES-NOT-SUPPORTED"", + ""NO-PROPOSAL-CHOSEN"", ""BAD-PROPOSAL-SYNTAX"", + ""PAYLOAD-MALFORMED"", ""INVALID-KEY-INFORMATION"", + ""INVALID-ID-INFORMATION"", ""INVALID-CERT-ENCODING"", + ""INVALID-CERTIFICATE"", ""CERT-TYPE-UNSUPPORTED"", + ""INVALID-CERT-AUTHORITY"", ""INVALID-HASH-INFORMATION"", + ""AUTHENTICATION-FAILED"", ""INVALID-SIGNATURE"", + ""ADDRESS-NOTIFICATION"", ""NOTIFY-SA-LIFETIME"", + ""CERTIFICATE-UNAVAILABLE"", ""UNSUPPORTED-EXCHANGE-TYPE"", + ""UNEQUAL-PAYLOAD-LENGTHS"", + }; + static const char *ipsec_notify_error_str[] = { + ""RESERVED"", + }; + static const char *notify_status_str[] = { + ""CONNECTED"", + }; + static const char *ipsec_notify_status_str[] = { + ""RESPONDER-LIFETIME"", ""REPLAY-STATUS"", + ""INITIAL-CONTACT"", + }; +/* NOTE: these macro must be called with x in proper range */ + +/* 0 - 8191 */ +#define NOTIFY_ERROR_STR(x) \ + STR_OR_ID((x), notify_error_str) + +/* 8192 - 16383 */ +#define IPSEC_NOTIFY_ERROR_STR(x) \ + STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str) + +/* 16384 - 24575 */ +#define NOTIFY_STATUS_STR(x) \ + STR_OR_ID((u_int)((x) - 16384), notify_status_str) + +/* 24576 - 32767 */ +#define IPSEC_NOTIFY_STATUS_STR(x) \ + STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str) + + ND_PRINT((ndo,""%s:"", NPSTR(ISAKMP_NPTYPE_N))); + + p = (const struct ikev1_pl_n *)ext; + ND_TCHECK(*p); + UNALIGNED_MEMCPY(&n, ext, sizeof(n)); + doi = ntohl(n.doi); + proto = n.prot_id; + if (doi != 1) { + ND_PRINT((ndo,"" doi=%d"", doi)); + ND_PRINT((ndo,"" proto=%d"", proto)); + if (ntohs(n.type) < 8192) + ND_PRINT((ndo,"" type=%s"", NOTIFY_ERROR_STR(ntohs(n.type)))); + else if (ntohs(n.type) < 16384) + ND_PRINT((ndo,"" type=%s"", numstr(ntohs(n.type)))); + else if (ntohs(n.type) < 24576) + ND_PRINT((ndo,"" type=%s"", NOTIFY_STATUS_STR(ntohs(n.type)))); + else + ND_PRINT((ndo,"" type=%s"", numstr(ntohs(n.type)))); + if (n.spi_size) { + ND_PRINT((ndo,"" spi="")); + if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) + goto trunc; + } + return (const u_char *)(p + 1) + n.spi_size; + } + + ND_PRINT((ndo,"" doi=ipsec"")); + ND_PRINT((ndo,"" proto=%s"", PROTOIDSTR(proto))); + if (ntohs(n.type) < 8192) + ND_PRINT((ndo,"" type=%s"", NOTIFY_ERROR_STR(ntohs(n.type)))); + else if (ntohs(n.type) < 16384) + ND_PRINT((ndo,"" type=%s"", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type)))); + else if (ntohs(n.type) < 24576) + ND_PRINT((ndo,"" type=%s"", NOTIFY_STATUS_STR(ntohs(n.type)))); + else if (ntohs(n.type) < 32768) + ND_PRINT((ndo,"" type=%s"", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type)))); + else + ND_PRINT((ndo,"" type=%s"", numstr(ntohs(n.type)))); + if (n.spi_size) { + ND_PRINT((ndo,"" spi="")); + if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) + goto trunc; + } + + cp = (const u_char *)(p + 1) + n.spi_size; + ep2 = (const u_char *)p + item_len; + + if (cp < ep) { + switch (ntohs(n.type)) { + case IPSECDOI_NTYPE_RESPONDER_LIFETIME: + { + const struct attrmap *map = oakley_t_map; + size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); + ND_PRINT((ndo,"" attrs=("")); + while (cp < ep && cp < ep2) { + cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); + if (cp == NULL) { + ND_PRINT((ndo,"")"")); + goto trunc; + } + } + ND_PRINT((ndo,"")"")); + break; + } + case IPSECDOI_NTYPE_REPLAY_STATUS: + ND_PRINT((ndo,"" status=("")); + ND_PRINT((ndo,""replay detection %sabled"", + EXTRACT_32BITS(cp) ? ""en"" : ""dis"")); + ND_PRINT((ndo,"")"")); + break; + default: + /* + * XXX - fill in more types here; see, for example, + * draft-ietf-ipsec-notifymsg-04. + */ + if (ndo->ndo_vflag > 3) { + ND_PRINT((ndo,"" data=("")); + if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) + goto trunc; + ND_PRINT((ndo,"")"")); + } else { + if (!ike_show_somedata(ndo, cp, ep)) + goto trunc; + } + break; + } + } + return (const u_char *)ext + item_len; +trunc: + ND_PRINT((ndo,"" [|%s]"", NPSTR(ISAKMP_NPTYPE_N))); + return NULL; +} +",1,"ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, + const struct isakmp_gen *ext, u_int item_len, + const u_char *ep, uint32_t phase _U_, uint32_t doi0 _U_, + uint32_t proto0 _U_, int depth _U_) +{ + const struct ikev1_pl_n *p; + struct ikev1_pl_n n; + const u_char *cp; + const u_char *ep2; + uint32_t doi; + uint32_t proto; + static const char *notify_error_str[] = { + NULL, ""INVALID-PAYLOAD-TYPE"", + ""DOI-NOT-SUPPORTED"", ""SITUATION-NOT-SUPPORTED"", + ""INVALID-COOKIE"", ""INVALID-MAJOR-VERSION"", + ""INVALID-MINOR-VERSION"", ""INVALID-EXCHANGE-TYPE"", + ""INVALID-FLAGS"", ""INVALID-MESSAGE-ID"", + ""INVALID-PROTOCOL-ID"", ""INVALID-SPI"", + ""INVALID-TRANSFORM-ID"", ""ATTRIBUTES-NOT-SUPPORTED"", + ""NO-PROPOSAL-CHOSEN"", ""BAD-PROPOSAL-SYNTAX"", + ""PAYLOAD-MALFORMED"", ""INVALID-KEY-INFORMATION"", + ""INVALID-ID-INFORMATION"", ""INVALID-CERT-ENCODING"", + ""INVALID-CERTIFICATE"", ""CERT-TYPE-UNSUPPORTED"", + ""INVALID-CERT-AUTHORITY"", ""INVALID-HASH-INFORMATION"", + ""AUTHENTICATION-FAILED"", ""INVALID-SIGNATURE"", + ""ADDRESS-NOTIFICATION"", ""NOTIFY-SA-LIFETIME"", + ""CERTIFICATE-UNAVAILABLE"", ""UNSUPPORTED-EXCHANGE-TYPE"", + ""UNEQUAL-PAYLOAD-LENGTHS"", + }; + static const char *ipsec_notify_error_str[] = { + ""RESERVED"", + }; + static const char *notify_status_str[] = { + ""CONNECTED"", + }; + static const char *ipsec_notify_status_str[] = { + ""RESPONDER-LIFETIME"", ""REPLAY-STATUS"", + ""INITIAL-CONTACT"", + }; +/* NOTE: these macro must be called with x in proper range */ + +/* 0 - 8191 */ +#define NOTIFY_ERROR_STR(x) \ + STR_OR_ID((x), notify_error_str) + +/* 8192 - 16383 */ +#define IPSEC_NOTIFY_ERROR_STR(x) \ + STR_OR_ID((u_int)((x) - 8192), ipsec_notify_error_str) + +/* 16384 - 24575 */ +#define NOTIFY_STATUS_STR(x) \ + STR_OR_ID((u_int)((x) - 16384), notify_status_str) + +/* 24576 - 32767 */ +#define IPSEC_NOTIFY_STATUS_STR(x) \ + STR_OR_ID((u_int)((x) - 24576), ipsec_notify_status_str) + + ND_PRINT((ndo,""%s:"", NPSTR(ISAKMP_NPTYPE_N))); + + p = (const struct ikev1_pl_n *)ext; + ND_TCHECK(*p); + UNALIGNED_MEMCPY(&n, ext, sizeof(n)); + doi = ntohl(n.doi); + proto = n.prot_id; + if (doi != 1) { + ND_PRINT((ndo,"" doi=%d"", doi)); + ND_PRINT((ndo,"" proto=%d"", proto)); + if (ntohs(n.type) < 8192) + ND_PRINT((ndo,"" type=%s"", NOTIFY_ERROR_STR(ntohs(n.type)))); + else if (ntohs(n.type) < 16384) + ND_PRINT((ndo,"" type=%s"", numstr(ntohs(n.type)))); + else if (ntohs(n.type) < 24576) + ND_PRINT((ndo,"" type=%s"", NOTIFY_STATUS_STR(ntohs(n.type)))); + else + ND_PRINT((ndo,"" type=%s"", numstr(ntohs(n.type)))); + if (n.spi_size) { + ND_PRINT((ndo,"" spi="")); + if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) + goto trunc; + } + return (const u_char *)(p + 1) + n.spi_size; + } + + ND_PRINT((ndo,"" doi=ipsec"")); + ND_PRINT((ndo,"" proto=%s"", PROTOIDSTR(proto))); + if (ntohs(n.type) < 8192) + ND_PRINT((ndo,"" type=%s"", NOTIFY_ERROR_STR(ntohs(n.type)))); + else if (ntohs(n.type) < 16384) + ND_PRINT((ndo,"" type=%s"", IPSEC_NOTIFY_ERROR_STR(ntohs(n.type)))); + else if (ntohs(n.type) < 24576) + ND_PRINT((ndo,"" type=%s"", NOTIFY_STATUS_STR(ntohs(n.type)))); + else if (ntohs(n.type) < 32768) + ND_PRINT((ndo,"" type=%s"", IPSEC_NOTIFY_STATUS_STR(ntohs(n.type)))); + else + ND_PRINT((ndo,"" type=%s"", numstr(ntohs(n.type)))); + if (n.spi_size) { + ND_PRINT((ndo,"" spi="")); + if (!rawprint(ndo, (const uint8_t *)(p + 1), n.spi_size)) + goto trunc; + } + + cp = (const u_char *)(p + 1) + n.spi_size; + ep2 = (const u_char *)p + item_len; + + if (cp < ep) { + switch (ntohs(n.type)) { + case IPSECDOI_NTYPE_RESPONDER_LIFETIME: + { + const struct attrmap *map = oakley_t_map; + size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); + ND_PRINT((ndo,"" attrs=("")); + while (cp < ep && cp < ep2) { + cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); + if (cp == NULL) { + ND_PRINT((ndo,"")"")); + goto trunc; + } + } + ND_PRINT((ndo,"")"")); + break; + } + case IPSECDOI_NTYPE_REPLAY_STATUS: + ND_PRINT((ndo,"" status=("")); + ND_TCHECK_32BITS(cp); + ND_PRINT((ndo,""replay detection %sabled"", + EXTRACT_32BITS(cp) ? ""en"" : ""dis"")); + ND_PRINT((ndo,"")"")); + break; + default: + /* + * XXX - fill in more types here; see, for example, + * draft-ietf-ipsec-notifymsg-04. + */ + if (ndo->ndo_vflag > 3) { + ND_PRINT((ndo,"" data=("")); + if (!rawprint(ndo, (const uint8_t *)(cp), ep - cp)) + goto trunc; + ND_PRINT((ndo,"")"")); + } else { + if (!ike_show_somedata(ndo, cp, ep)) + goto trunc; + } + break; + } + } + return (const u_char *)ext + item_len; +trunc: + ND_PRINT((ndo,"" [|%s]"", NPSTR(ISAKMP_NPTYPE_N))); + return NULL; +} +","@@ -1769,6 +1769,7 @@ ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, + } + case IPSECDOI_NTYPE_REPLAY_STATUS: + ND_PRINT((ndo,"" status=("")); ++ ND_TCHECK_32BITS(cp); + ND_PRINT((ndo,""replay detection %sabled"", + EXTRACT_32BITS(cp) ? ""en"" : ""dis"")); + ND_PRINT((ndo,"")""));",1634,1965,2048 +18495,"xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) { + xmlChar *buf = NULL; + int len = 0; + int size = XML_PARSER_BUFFER_SIZE; + int c, l; + xmlChar stop; + xmlChar *ret = NULL; + const xmlChar *cur = NULL; + xmlParserInputPtr input; + + if (RAW == '""') stop = '""'; + else if (RAW == '\'') stop = '\''; + else { + xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_STARTED, NULL); + return(NULL); + } + buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); + if (buf == NULL) { + xmlErrMemory(ctxt, NULL); + return(NULL); + } + + /* + * The content of the entity definition is copied in a buffer. + */ + + ctxt->instate = XML_PARSER_ENTITY_VALUE; + input = ctxt->input; + GROW; + NEXT; + c = CUR_CHAR(l); + /* + * NOTE: 4.4.5 Included in Literal + * When a parameter entity reference appears in a literal entity + * value, ... a single or double quote character in the replacement + * text is always treated as a normal data character and will not + * terminate the literal. + * In practice it means we stop the loop only when back at parsing + * the initial entity and the quote is found + */ + while ((IS_CHAR(c)) && ((c != stop) || /* checked */ + (ctxt->input != input))) { + if (len + 5 >= size) { + xmlChar *tmp; + + size *= 2; + tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); + if (tmp == NULL) { + xmlErrMemory(ctxt, NULL); + xmlFree(buf); + return(NULL); + } + buf = tmp; + } + COPY_BUF(l,buf,len,c); + NEXTL(l); + /* + * Pop-up of finished entities. + */ + while ((RAW == 0) && (ctxt->inputNr > 1)) /* non input consuming */ + xmlPopInput(ctxt); + + GROW; + c = CUR_CHAR(l); + if (c == 0) { + GROW; + c = CUR_CHAR(l); + } + } + buf[len] = 0; + + /* + * Raise problem w.r.t. '&' and '%' being used in non-entities + * reference constructs. Note Charref will be handled in + * xmlStringDecodeEntities() + */ + cur = buf; + while (*cur != 0) { /* non input consuming */ + if ((*cur == '%') || ((*cur == '&') && (cur[1] != '#'))) { + xmlChar *name; + xmlChar tmp = *cur; + + cur++; + name = xmlParseStringName(ctxt, &cur); + if ((name == NULL) || (*cur != ';')) { + xmlFatalErrMsgInt(ctxt, XML_ERR_ENTITY_CHAR_ERROR, + ""EntityValue: '%c' forbidden except for entities references\n"", + tmp); + } + if ((tmp == '%') && (ctxt->inSubset == 1) && + (ctxt->inputNr == 1)) { + xmlFatalErr(ctxt, XML_ERR_ENTITY_PE_INTERNAL, NULL); + } + if (name != NULL) + xmlFree(name); + if (*cur == 0) + break; + } + cur++; + } + + /* + * Then PEReference entities are substituted. + */ + if (c != stop) { + xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_FINISHED, NULL); + xmlFree(buf); + } else { + NEXT; + /* + * NOTE: 4.4.7 Bypassed + * When a general entity reference appears in the EntityValue in + * an entity declaration, it is bypassed and left as is. + * so XML_SUBSTITUTE_REF is not set here. + */ + ret = xmlStringDecodeEntities(ctxt, buf, XML_SUBSTITUTE_PEREF, + 0, 0, 0); + if (orig != NULL) + *orig = buf; + else + xmlFree(buf); + } + return(ret); + } +",1,"xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) { + xmlChar *buf = NULL; + int len = 0; + int size = XML_PARSER_BUFFER_SIZE; + int c, l; + xmlChar stop; + xmlChar *ret = NULL; + const xmlChar *cur = NULL; + xmlParserInputPtr input; + + if (RAW == '""') stop = '""'; + else if (RAW == '\'') stop = '\''; + else { + xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_STARTED, NULL); + return(NULL); + } + buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); + if (buf == NULL) { + xmlErrMemory(ctxt, NULL); + return(NULL); + } + + /* + * The content of the entity definition is copied in a buffer. + */ + + ctxt->instate = XML_PARSER_ENTITY_VALUE; + input = ctxt->input; + GROW; + if (ctxt->instate == XML_PARSER_EOF) { + xmlFree(buf); + return(NULL); + } + NEXT; + c = CUR_CHAR(l); + /* + * NOTE: 4.4.5 Included in Literal + * When a parameter entity reference appears in a literal entity + * value, ... a single or double quote character in the replacement + * text is always treated as a normal data character and will not + * terminate the literal. + * In practice it means we stop the loop only when back at parsing + * the initial entity and the quote is found + */ + while (((IS_CHAR(c)) && ((c != stop) || /* checked */ + (ctxt->input != input))) && (ctxt->instate != XML_PARSER_EOF)) { + if (len + 5 >= size) { + xmlChar *tmp; + + size *= 2; + tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); + if (tmp == NULL) { + xmlErrMemory(ctxt, NULL); + xmlFree(buf); + return(NULL); + } + buf = tmp; + } + COPY_BUF(l,buf,len,c); + NEXTL(l); + /* + * Pop-up of finished entities. + */ + while ((RAW == 0) && (ctxt->inputNr > 1)) /* non input consuming */ + xmlPopInput(ctxt); + + GROW; + c = CUR_CHAR(l); + if (c == 0) { + GROW; + c = CUR_CHAR(l); + } + } + buf[len] = 0; + if (ctxt->instate == XML_PARSER_EOF) { + xmlFree(buf); + return(NULL); + } + + /* + * Raise problem w.r.t. '&' and '%' being used in non-entities + * reference constructs. Note Charref will be handled in + * xmlStringDecodeEntities() + */ + cur = buf; + while (*cur != 0) { /* non input consuming */ + if ((*cur == '%') || ((*cur == '&') && (cur[1] != '#'))) { + xmlChar *name; + xmlChar tmp = *cur; + + cur++; + name = xmlParseStringName(ctxt, &cur); + if ((name == NULL) || (*cur != ';')) { + xmlFatalErrMsgInt(ctxt, XML_ERR_ENTITY_CHAR_ERROR, + ""EntityValue: '%c' forbidden except for entities references\n"", + tmp); + } + if ((tmp == '%') && (ctxt->inSubset == 1) && + (ctxt->inputNr == 1)) { + xmlFatalErr(ctxt, XML_ERR_ENTITY_PE_INTERNAL, NULL); + } + if (name != NULL) + xmlFree(name); + if (*cur == 0) + break; + } + cur++; + } + + /* + * Then PEReference entities are substituted. + */ + if (c != stop) { + xmlFatalErr(ctxt, XML_ERR_ENTITY_NOT_FINISHED, NULL); + xmlFree(buf); + } else { + NEXT; + /* + * NOTE: 4.4.7 Bypassed + * When a general entity reference appears in the EntityValue in + * an entity declaration, it is bypassed and left as is. + * so XML_SUBSTITUTE_REF is not set here. + */ + ret = xmlStringDecodeEntities(ctxt, buf, XML_SUBSTITUTE_PEREF, + 0, 0, 0); + if (orig != NULL) + *orig = buf; + else + xmlFree(buf); + } + + return(ret); + } +","@@ -2013,6 +2013,8 @@ xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) { + ""Pushing input %d : %.30s\n"", ctxt->inputNr+1, input->cur); + } + ret = inputPush(ctxt, input); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + GROW; + return(ret); + } +@@ -2049,6 +2051,8 @@ xmlParseCharRef(xmlParserCtxtPtr ctxt) { + if (count++ > 20) { + count = 0; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(0); + } + if ((RAW >= '0') && (RAW <= '9')) + val = val * 16 + (CUR - '0'); +@@ -2080,6 +2084,8 @@ xmlParseCharRef(xmlParserCtxtPtr ctxt) { + if (count++ > 20) { + count = 0; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(0); + } + if ((RAW >= '0') && (RAW <= '9')) + val = val * 10 + (CUR - '0'); +@@ -2366,6 +2372,8 @@ xmlParserHandlePEReference(xmlParserCtxtPtr ctxt) { + NEXT; + if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL)) + entity = ctxt->sax->getParameterEntity(ctxt->userData, name); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + if (entity == NULL) { + + /* +@@ -2428,6 +2436,8 @@ xmlParserHandlePEReference(xmlParserCtxtPtr ctxt) { + * the amount of data in the buffer. + */ + GROW ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + if ((ctxt->input->end - ctxt->input->cur)>=4) { + start[0] = RAW; + start[1] = NXT(1); +@@ -3046,6 +3056,8 @@ xmlParseNameComplex(xmlParserCtxtPtr ctxt) { + * Handler for more complex cases + */ + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + c = CUR_CHAR(l); + if ((ctxt->options & XML_PARSE_OLD10) == 0) { + /* +@@ -3097,6 +3109,8 @@ xmlParseNameComplex(xmlParserCtxtPtr ctxt) { + if (count++ > 100) { + count = 0; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + } + len += l; + NEXTL(l); +@@ -3121,6 +3135,8 @@ xmlParseNameComplex(xmlParserCtxtPtr ctxt) { + if (count++ > 100) { + count = 0; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + } + len += l; + NEXTL(l); +@@ -3214,6 +3230,8 @@ xmlParseNCNameComplex(xmlParserCtxtPtr ctxt) { + if (count++ > 100) { + count = 0; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + } + len += l; + NEXTL(l); +@@ -3294,6 +3312,8 @@ xmlParseNameAndCompare(xmlParserCtxtPtr ctxt, xmlChar const *other) { + const xmlChar *ret; + + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + + in = ctxt->input->cur; + while (*in != 0 && *in == *cmp) { +@@ -3421,6 +3441,8 @@ xmlParseNmtoken(xmlParserCtxtPtr ctxt) { + #endif + + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + c = CUR_CHAR(l); + + while (xmlIsNameChar(ctxt, c)) { +@@ -3449,6 +3471,10 @@ xmlParseNmtoken(xmlParserCtxtPtr ctxt) { + if (count++ > 100) { + count = 0; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buffer); ++ return(NULL); ++ } + } + if (len + 10 > max) { + xmlChar *tmp; +@@ -3519,6 +3545,10 @@ xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) { + ctxt->instate = XML_PARSER_ENTITY_VALUE; + input = ctxt->input; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return(NULL); ++ } + NEXT; + c = CUR_CHAR(l); + /* +@@ -3530,8 +3560,8 @@ xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) { + * In practice it means we stop the loop only when back at parsing + * the initial entity and the quote is found + */ +- while ((IS_CHAR(c)) && ((c != stop) || /* checked */ +- (ctxt->input != input))) { ++ while (((IS_CHAR(c)) && ((c != stop) || /* checked */ ++ (ctxt->input != input))) && (ctxt->instate != XML_PARSER_EOF)) { + if (len + 5 >= size) { + xmlChar *tmp; + +@@ -3560,6 +3590,10 @@ xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) { + } + } + buf[len] = 0; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return(NULL); ++ } + + /* + * Raise problem w.r.t. '&' and '%' being used in non-entities +@@ -3607,12 +3641,12 @@ xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) { + */ + ret = xmlStringDecodeEntities(ctxt, buf, XML_SUBSTITUTE_PEREF, + 0, 0, 0); +- if (orig != NULL) ++ if (orig != NULL) + *orig = buf; + else + xmlFree(buf); + } +- ++ + return(ret); + } + +@@ -3663,8 +3697,9 @@ xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) { + * OK loop until we reach one of the ending char or a size limit. + */ + c = CUR_CHAR(l); +- while ((NXT(0) != limit) && /* checked */ +- (IS_CHAR(c)) && (c != '<')) { ++ while (((NXT(0) != limit) && /* checked */ ++ (IS_CHAR(c)) && (c != '<')) && ++ (ctxt->instate != XML_PARSER_EOF)) { + if (c == 0) break; + if (c == '&') { + in_space = 0; +@@ -3799,6 +3834,9 @@ xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) { + GROW; + c = CUR_CHAR(l); + } ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto error; ++ + if ((in_space) && (normalize)) { + while ((len > 0) && (buf[len - 1] == 0x20)) len--; + } +@@ -3820,6 +3858,7 @@ xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) { + + mem_error: + xmlErrMemory(ctxt, NULL); ++error: + if (buf != NULL) + xmlFree(buf); + if (rep != NULL) +@@ -3925,6 +3964,10 @@ xmlParseSystemLiteral(xmlParserCtxtPtr ctxt) { + if (count > 50) { + GROW; + count = 0; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return(NULL); ++ } + } + COPY_BUF(l,buf,len,cur); + NEXTL(l); +@@ -4002,6 +4045,10 @@ xmlParsePubidLiteral(xmlParserCtxtPtr ctxt) { + if (count > 50) { + GROW; + count = 0; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return(NULL); ++ } + } + NEXT; + cur = CUR; +@@ -4208,6 +4255,8 @@ xmlParseCharData(xmlParserCtxtPtr ctxt, int cdata) { + } + SHRINK; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + in = ctxt->input->cur; + } while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09)); + nbchar = 0; +@@ -4276,6 +4325,8 @@ xmlParseCharDataComplex(xmlParserCtxtPtr ctxt, int cdata) { + if (count > 50) { + GROW; + count = 0; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + } + NEXTL(l); + cur = CUR_CHAR(l); +@@ -4476,6 +4527,10 @@ xmlParseCommentComplex(xmlParserCtxtPtr ctxt, xmlChar *buf, int len, int size) { + if (count > 50) { + GROW; + count = 0; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return; ++ } + } + NEXTL(l); + cur = CUR_CHAR(l); +@@ -4626,6 +4681,10 @@ xmlParseComment(xmlParserCtxtPtr ctxt) { + } + SHRINK; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return; ++ } + in = ctxt->input->cur; + if (*in == '-') { + if (in[1] == '-') { +@@ -4644,7 +4703,8 @@ xmlParseComment(xmlParserCtxtPtr ctxt) { + } + if (buf != NULL) + xmlFree(buf); +- ctxt->instate = state; ++ if (ctxt->instate != XML_PARSER_EOF) ++ ctxt->instate = state; + return; + } + if (buf != NULL) +@@ -4862,6 +4922,10 @@ xmlParsePI(xmlParserCtxtPtr ctxt) { + count++; + if (count > 50) { + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return; ++ } + count = 0; + } + COPY_BUF(l,buf,len,cur); +@@ -5211,6 +5275,8 @@ xmlParseEntityDecl(xmlParserCtxtPtr ctxt) { + } + } + } ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + SKIP_BLANKS; + if (RAW != '>') { + xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_NOT_FINISHED, +@@ -5602,7 +5668,7 @@ xmlParseAttributeListDecl(xmlParserCtxtPtr ctxt) { + } + SKIP_BLANKS; + GROW; +- while (RAW != '>') { ++ while ((RAW != '>') && (ctxt->instate != XML_PARSER_EOF)) { + const xmlChar *check = CUR_PTR; + int type; + int def; +@@ -5751,7 +5817,7 @@ xmlParseElementMixedContentDecl(xmlParserCtxtPtr ctxt, int inputchk) { + ret = cur = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_PCDATA); + if (ret == NULL) return(NULL); + } +- while (RAW == '|') { ++ while ((RAW == '|') && (ctxt->instate != XML_PARSER_EOF)) { + NEXT; + if (elem == NULL) { + ret = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR); +@@ -5895,7 +5961,7 @@ xmlParseElementChildrenContentDeclPriv(xmlParserCtxtPtr ctxt, int inputchk, + } + SKIP_BLANKS; + SHRINK; +- while (RAW != ')') { ++ while ((RAW != ')') && (ctxt->instate != XML_PARSER_EOF)) { + /* + * Each loop we parse one separator and one element. + */ +@@ -6174,6 +6240,8 @@ xmlParseElementContentDecl(xmlParserCtxtPtr ctxt, const xmlChar *name, + } + NEXT; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + SKIP_BLANKS; + if (CMP7(CUR_PTR, '#', 'P', 'C', 'D', 'A', 'T', 'A')) { + tree = xmlParseElementMixedContentDecl(ctxt, inputid); +@@ -6341,8 +6409,8 @@ xmlParseConditionalSections(xmlParserCtxtPtr ctxt) { + ""Entering INCLUDE Conditional Section\n""); + } + +- while ((RAW != 0) && ((RAW != ']') || (NXT(1) != ']') || +- (NXT(2) != '>'))) { ++ while (((RAW != 0) && ((RAW != ']') || (NXT(1) != ']') || ++ (NXT(2) != '>'))) && (ctxt->instate != XML_PARSER_EOF)) { + const xmlChar *check = CUR_PTR; + unsigned int cons = ctxt->input->consumed; + +@@ -6410,7 +6478,8 @@ xmlParseConditionalSections(xmlParserCtxtPtr ctxt) { + if (ctxt->recovery == 0) ctxt->disableSAX = 1; + ctxt->instate = XML_PARSER_IGNORE; + +- while ((depth >= 0) && (RAW != 0)) { ++ while (((depth >= 0) && (RAW != 0)) && ++ (ctxt->instate != XML_PARSER_EOF)) { + if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) { + depth++; + SKIP(3); +@@ -6681,7 +6750,7 @@ xmlParseExternalSubset(xmlParserCtxtPtr ctxt, const xmlChar *ExternalID, + break; + } + } +- ++ + if (RAW != 0) { + xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL); + } +@@ -7127,6 +7196,8 @@ xmlParseEntityRef(xmlParserCtxtPtr ctxt) { + xmlEntityPtr ent = NULL; + + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + + if (RAW != '&') + return(NULL); +@@ -7172,6 +7243,8 @@ xmlParseEntityRef(xmlParserCtxtPtr ctxt) { + ent = xmlSAX2GetEntity(ctxt, name); + } + } ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + /* + * [ WFC: Entity Declared ] + * In a document without any DTD, a document with only an +@@ -7362,6 +7435,10 @@ xmlParseStringEntityRef(xmlParserCtxtPtr ctxt, const xmlChar ** str) { + ent = xmlSAX2GetEntity(ctxt, name); + } + } ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(name); ++ return(NULL); ++ } + + /* + * [ WFC: Entity Declared ] +@@ -7523,8 +7600,9 @@ xmlParsePEReference(xmlParserCtxtPtr ctxt) + */ + if ((ctxt->sax != NULL) && + (ctxt->sax->getParameterEntity != NULL)) +- entity = ctxt->sax->getParameterEntity(ctxt->userData, +- name); ++ entity = ctxt->sax->getParameterEntity(ctxt->userData, name); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + if (entity == NULL) { + /* + * [ WFC: Entity Declared ] +@@ -7657,6 +7735,10 @@ xmlLoadEntityContent(xmlParserCtxtPtr ctxt, xmlEntityPtr entity) { + if (count++ > 100) { + count = 0; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlBufferFree(buf); ++ return(-1); ++ } + } + NEXTL(l); + c = CUR_CHAR(l); +@@ -7748,8 +7830,11 @@ xmlParseStringPEReference(xmlParserCtxtPtr ctxt, const xmlChar **str) { + */ + if ((ctxt->sax != NULL) && + (ctxt->sax->getParameterEntity != NULL)) +- entity = ctxt->sax->getParameterEntity(ctxt->userData, +- name); ++ entity = ctxt->sax->getParameterEntity(ctxt->userData, name); ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(name); ++ return(NULL); ++ } + if (entity == NULL) { + /* + * [ WFC: Entity Declared ] +@@ -7851,6 +7936,8 @@ xmlParseDocTypeDecl(xmlParserCtxtPtr ctxt) { + if ((ctxt->sax != NULL) && (ctxt->sax->internalSubset != NULL) && + (!ctxt->disableSAX)) + ctxt->sax->internalSubset(ctxt->userData, name, ExternalID, URI); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + + /* + * Is there any internal subset declarations ? +@@ -7890,7 +7977,7 @@ xmlParseInternalSubset(xmlParserCtxtPtr ctxt) { + * PEReferences. + * Subsequence (markupdecl | PEReference | S)* + */ +- while (RAW != ']') { ++ while ((RAW != ']') && (ctxt->instate != XML_PARSER_EOF)) { + const xmlChar *check = CUR_PTR; + unsigned int cons = ctxt->input->consumed; + +@@ -8076,9 +8163,9 @@ xmlParseStartTag(xmlParserCtxtPtr ctxt) { + SKIP_BLANKS; + GROW; + +- while ((RAW != '>') && ++ while (((RAW != '>') && + ((RAW != '/') || (NXT(1) != '>')) && +- (IS_BYTE_CHAR(RAW))) { ++ (IS_BYTE_CHAR(RAW))) && (ctxt->instate != XML_PARSER_EOF)) { + const xmlChar *q = CUR_PTR; + unsigned int cons = ctxt->input->consumed; + +@@ -8502,6 +8589,8 @@ xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc, + if (in >= end) { + const xmlChar *oldbase = ctxt->input->base; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + if (oldbase != ctxt->input->base) { + long delta = ctxt->input->base - oldbase; + start = start + delta; +@@ -8516,6 +8605,8 @@ xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc, + if (in >= end) { + const xmlChar *oldbase = ctxt->input->base; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + if (oldbase != ctxt->input->base) { + long delta = ctxt->input->base - oldbase; + start = start + delta; +@@ -8536,6 +8627,8 @@ xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc, + if (in >= end) { + const xmlChar *oldbase = ctxt->input->base; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + if (oldbase != ctxt->input->base) { + long delta = ctxt->input->base - oldbase; + start = start + delta; +@@ -8553,6 +8646,8 @@ xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc, + if (in >= end) { + const xmlChar *oldbase = ctxt->input->base; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + if (oldbase != ctxt->input->base) { + long delta = ctxt->input->base - oldbase; + start = start + delta; +@@ -8784,9 +8879,9 @@ xmlParseStartTag2(xmlParserCtxtPtr ctxt, const xmlChar **pref, + GROW; + if (ctxt->input->base != base) goto base_changed; + +- while ((RAW != '>') && ++ while (((RAW != '>') && + ((RAW != '/') || (NXT(1) != '>')) && +- (IS_BYTE_CHAR(RAW))) { ++ (IS_BYTE_CHAR(RAW))) && (ctxt->instate != XML_PARSER_EOF)) { + const xmlChar *q = CUR_PTR; + unsigned int cons = ctxt->input->consumed; + int len = -1, alloc = 0; +@@ -8957,6 +9052,8 @@ xmlParseStartTag2(xmlParserCtxtPtr ctxt, const xmlChar **pref, + failed: + + GROW ++ if (ctxt->instate == XML_PARSER_EOF) ++ break; + if (ctxt->input->base != base) goto base_changed; + if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>')))) + break; +@@ -9194,6 +9291,8 @@ xmlParseEndTag2(xmlParserCtxtPtr ctxt, const xmlChar *prefix, + * We should definitely be at the ending ""S? '>'"" part + */ + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + SKIP_BLANKS; + if ((!IS_BYTE_CHAR(RAW)) || (RAW != '>')) { + xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL); +@@ -9302,6 +9401,10 @@ xmlParseCDSect(xmlParserCtxtPtr ctxt) { + count++; + if (count > 50) { + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return; ++ } + count = 0; + } + NEXTL(l); +@@ -9550,6 +9653,8 @@ xmlParseElement(xmlParserCtxtPtr ctxt) { + * Parse the content of the element: + */ + xmlParseContent(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + if (!IS_BYTE_CHAR(RAW)) { + xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NOT_FINISHED, + ""Premature end of data in tag %s line %d\n"", +@@ -10065,9 +10170,10 @@ xmlParseXMLDecl(xmlParserCtxtPtr ctxt) { + + void + xmlParseMisc(xmlParserCtxtPtr ctxt) { +- while (((RAW == '<') && (NXT(1) == '?')) || +- (CMP4(CUR_PTR, '<', '!', '-', '-')) || +- IS_BLANK_CH(CUR)) { ++ while ((ctxt->instate != XML_PARSER_EOF) && ++ (((RAW == '<') && (NXT(1) == '?')) || ++ (CMP4(CUR_PTR, '<', '!', '-', '-')) || ++ IS_BLANK_CH(CUR))) { + if ((RAW == '<') && (NXT(1) == '?')) { + xmlParsePI(ctxt); + } else if (IS_BLANK_CH(CUR)) { +@@ -10114,6 +10220,8 @@ xmlParseDocument(xmlParserCtxtPtr ctxt) { + */ + if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) + ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + + if ((ctxt->encoding == (const xmlChar *)XML_CHAR_ENCODING_NONE) && + ((ctxt->input->end - ctxt->input->cur) >= 4)) { +@@ -10165,6 +10273,8 @@ xmlParseDocument(xmlParserCtxtPtr ctxt) { + } + if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) + ctxt->sax->startDocument(ctxt->userData); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + + /* + * The Misc part of the Prolog +@@ -10184,6 +10294,8 @@ xmlParseDocument(xmlParserCtxtPtr ctxt) { + if (RAW == '[') { + ctxt->instate = XML_PARSER_DTD; + xmlParseInternalSubset(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + } + + /* +@@ -10194,6 +10306,8 @@ xmlParseDocument(xmlParserCtxtPtr ctxt) { + (!ctxt->disableSAX)) + ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, + ctxt->extSubSystem, ctxt->extSubURI); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + ctxt->inSubset = 0; + + xmlCleanSpecialAttr(ctxt); +@@ -10334,6 +10448,8 @@ xmlParseExtParsedEnt(xmlParserCtxtPtr ctxt) { + } + if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) + ctxt->sax->startDocument(ctxt->userData); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + + /* + * Doing validity checking on chunk doesn't make sense +@@ -10344,6 +10460,8 @@ xmlParseExtParsedEnt(xmlParserCtxtPtr ctxt) { + ctxt->depth = 0; + + xmlParseContent(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + + if ((RAW == '<') && (NXT(1) == '/')) { + xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL); +@@ -10651,7 +10769,7 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + } + xmlParseGetLasts(ctxt, &lastlt, &lastgt); + +- while (1) { ++ while (ctxt->instate != XML_PARSER_EOF) { + if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) + return(0); + +@@ -10891,6 +11009,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ctxt->sax->endElement(ctxt->userData, name); + #endif /* LIBXML_SAX1_ENABLED */ + } ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + spacePop(ctxt); + if (ctxt->nameNr == 0) { + ctxt->instate = XML_PARSER_EPILOG; +@@ -11072,6 +11192,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ctxt->sax->characters(ctxt->userData, + ctxt->input->cur, tmp); + } ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + SKIPL(tmp); + ctxt->checkIndex = 0; + } +@@ -11107,6 +11229,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ctxt->sax->characters(ctxt->userData, + ctxt->input->cur, base); + } ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + SKIPL(base + 3); + ctxt->checkIndex = 0; + ctxt->instate = XML_PARSER_CONTENT; +@@ -11138,6 +11262,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ""PP: Parsing PI\n""); + #endif + xmlParsePI(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + ctxt->checkIndex = 0; + } else if ((cur == '<') && (next == '!') && + (ctxt->input->cur[2] == '-') && +@@ -11150,6 +11276,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ""PP: Parsing Comment\n""); + #endif + xmlParseComment(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + ctxt->instate = XML_PARSER_MISC; + ctxt->checkIndex = 0; + } else if ((cur == '<') && (next == '!') && +@@ -11169,6 +11297,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + #endif + ctxt->inSubset = 1; + xmlParseDocTypeDecl(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + if (RAW == '[') { + ctxt->instate = XML_PARSER_DTD; + #ifdef DEBUG_PUSH +@@ -11225,6 +11355,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ""PP: Parsing PI\n""); + #endif + xmlParsePI(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + } else if ((cur == '<') && (next == '!') && + (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { + if ((!terminate) && +@@ -11235,6 +11367,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ""PP: Parsing Comment\n""); + #endif + xmlParseComment(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + ctxt->instate = XML_PARSER_PROLOG; + } else if ((cur == '<') && (next == '!') && + (avail < 4)) { +@@ -11269,6 +11403,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ""PP: Parsing PI\n""); + #endif + xmlParsePI(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + ctxt->instate = XML_PARSER_EPILOG; + } else if ((cur == '<') && (next == '!') && + (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { +@@ -11280,6 +11416,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ""PP: Parsing Comment\n""); + #endif + xmlParseComment(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + ctxt->instate = XML_PARSER_EPILOG; + } else if ((cur == '<') && (next == '!') && + (avail < 4)) { +@@ -11408,13 +11546,17 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + + found_end_int_subset: + xmlParseInternalSubset(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + ctxt->inSubset = 2; + if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && + (ctxt->sax->externalSubset != NULL)) + ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, + ctxt->extSubSystem, ctxt->extSubURI); + ctxt->inSubset = 0; + xmlCleanSpecialAttr(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + ctxt->instate = XML_PARSER_PROLOG; + ctxt->checkIndex = 0; + #ifdef DEBUG_PUSH +@@ -11537,6 +11679,8 @@ xmlParseChunk(xmlParserCtxtPtr ctxt, const char *chunk, int size, + return(XML_ERR_INTERNAL_ERROR); + if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) + return(ctxt->errNo); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + if (ctxt->instate == XML_PARSER_START) + xmlDetectSAX2(ctxt); + if ((size > 0) && (chunk != NULL) && (!terminate) && +@@ -11623,6 +11767,8 @@ xmlParseChunk(xmlParserCtxtPtr ctxt, const char *chunk, int size, + xmlParseTryOrFinish(ctxt, 0); + else + xmlParseTryOrFinish(ctxt, terminate); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(ctxt->errNo); + if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) + return(ctxt->errNo); + +@@ -11816,6 +11962,7 @@ xmlStopParser(xmlParserCtxtPtr ctxt) { + if (ctxt == NULL) + return; + ctxt->instate = XML_PARSER_EOF; ++ ctxt->errNo = XML_ERR_USER_STOP; + ctxt->disableSAX = 1; + if (ctxt->input != NULL) { + ctxt->input->cur = BAD_CAST"""";",904,1235,2048 +18117,"static int cdxl_decode_frame(AVCodecContext *avctx, void *data, + int *got_frame, AVPacket *pkt) +{ + CDXLVideoContext *c = avctx->priv_data; + AVFrame * const p = data; + int ret, w, h, encoding, aligned_width, buf_size = pkt->size; + const uint8_t *buf = pkt->data; + + if (buf_size < 32) + return AVERROR_INVALIDDATA; + encoding = buf[1] & 7; + c->format = buf[1] & 0xE0; + w = AV_RB16(&buf[14]); + h = AV_RB16(&buf[16]); + c->bpp = buf[19]; + c->palette_size = AV_RB16(&buf[20]); + c->palette = buf + 32; + c->video = c->palette + c->palette_size; + c->video_size = buf_size - c->palette_size - 32; + + if (c->palette_size > 512) + return AVERROR_INVALIDDATA; + if (buf_size < c->palette_size + 32) + return AVERROR_INVALIDDATA; + if (c->bpp < 1) + return AVERROR_INVALIDDATA; + if (c->format != BIT_PLANAR && c->format != BIT_LINE && c->format != CHUNKY) { + avpriv_request_sample(avctx, ""Pixel format 0x%0x"", c->format); + return AVERROR_PATCHWELCOME; + } + + if ((ret = ff_set_dimensions(avctx, w, h)) < 0) + return ret; + + if (c->format == CHUNKY) + aligned_width = avctx->width; + else + aligned_width = FFALIGN(c->avctx->width, 16); + c->padded_bits = aligned_width - c->avctx->width; + if (c->video_size < aligned_width * avctx->height * (int64_t)c->bpp / 8) + return AVERROR_INVALIDDATA; + if (!encoding && c->palette_size && c->bpp <= 8 && c->format != CHUNKY) { + avctx->pix_fmt = AV_PIX_FMT_PAL8; + } else if (encoding == 1 && (c->bpp == 6 || c->bpp == 8)) { + if (c->palette_size != (1 << (c->bpp - 1))) + return AVERROR_INVALIDDATA; + avctx->pix_fmt = AV_PIX_FMT_BGR24; + } else if (!encoding && c->bpp == 24 && c->format == CHUNKY && + !c->palette_size) { + avctx->pix_fmt = AV_PIX_FMT_RGB24; + } else { + avpriv_request_sample(avctx, ""Encoding %d, bpp %d and format 0x%x"", + encoding, c->bpp, c->format); + return AVERROR_PATCHWELCOME; + } + + if ((ret = ff_get_buffer(avctx, p, 0)) < 0) + return ret; + p->pict_type = AV_PICTURE_TYPE_I; + + if (encoding) { + av_fast_padded_malloc(&c->new_video, &c->new_video_size, + h * w + AV_INPUT_BUFFER_PADDING_SIZE); + if (!c->new_video) + return AVERROR(ENOMEM); + if (c->bpp == 8) + cdxl_decode_ham8(c, p); + else + cdxl_decode_ham6(c, p); + } else if (avctx->pix_fmt == AV_PIX_FMT_PAL8) { + cdxl_decode_rgb(c, p); + } else { + cdxl_decode_raw(c, p); + } + *got_frame = 1; + + return buf_size; +} +",1,"static int cdxl_decode_frame(AVCodecContext *avctx, void *data, + int *got_frame, AVPacket *pkt) +{ + CDXLVideoContext *c = avctx->priv_data; + AVFrame * const p = data; + int ret, w, h, encoding, aligned_width, buf_size = pkt->size; + const uint8_t *buf = pkt->data; + + if (buf_size < 32) + return AVERROR_INVALIDDATA; + encoding = buf[1] & 7; + c->format = buf[1] & 0xE0; + w = AV_RB16(&buf[14]); + h = AV_RB16(&buf[16]); + c->bpp = buf[19]; + c->palette_size = AV_RB16(&buf[20]); + c->palette = buf + 32; + c->video = c->palette + c->palette_size; + c->video_size = buf_size - c->palette_size - 32; + + if (c->palette_size > 512) + return AVERROR_INVALIDDATA; + if (buf_size < c->palette_size + 32) + return AVERROR_INVALIDDATA; + if (c->bpp < 1) + return AVERROR_INVALIDDATA; + if (c->format != BIT_PLANAR && c->format != BIT_LINE && c->format != CHUNKY) { + avpriv_request_sample(avctx, ""Pixel format 0x%0x"", c->format); + return AVERROR_PATCHWELCOME; + } + + if ((ret = ff_set_dimensions(avctx, w, h)) < 0) + return ret; + + if (c->format == CHUNKY) + aligned_width = avctx->width; + else + aligned_width = FFALIGN(c->avctx->width, 16); + c->padded_bits = aligned_width - c->avctx->width; + if (c->video_size < aligned_width * avctx->height * (int64_t)c->bpp / 8) + return AVERROR_INVALIDDATA; + if (!encoding && c->palette_size && c->bpp <= 8 && c->format != CHUNKY) { + avctx->pix_fmt = AV_PIX_FMT_PAL8; + } else if (encoding == 1 && (c->bpp == 6 || c->bpp == 8) && c->format != CHUNKY) { + if (c->palette_size != (1 << (c->bpp - 1))) + return AVERROR_INVALIDDATA; + avctx->pix_fmt = AV_PIX_FMT_BGR24; + } else if (!encoding && c->bpp == 24 && c->format == CHUNKY && + !c->palette_size) { + avctx->pix_fmt = AV_PIX_FMT_RGB24; + } else { + avpriv_request_sample(avctx, ""Encoding %d, bpp %d and format 0x%x"", + encoding, c->bpp, c->format); + return AVERROR_PATCHWELCOME; + } + + if ((ret = ff_get_buffer(avctx, p, 0)) < 0) + return ret; + p->pict_type = AV_PICTURE_TYPE_I; + + if (encoding) { + av_fast_padded_malloc(&c->new_video, &c->new_video_size, + h * w + AV_INPUT_BUFFER_PADDING_SIZE); + if (!c->new_video) + return AVERROR(ENOMEM); + if (c->bpp == 8) + cdxl_decode_ham8(c, p); + else + cdxl_decode_ham6(c, p); + } else if (avctx->pix_fmt == AV_PIX_FMT_PAL8) { + cdxl_decode_rgb(c, p); + } else { + cdxl_decode_raw(c, p); + } + *got_frame = 1; + + return buf_size; +} +","@@ -279,7 +279,7 @@ static int cdxl_decode_frame(AVCodecContext *avctx, void *data, + return AVERROR_INVALIDDATA; + if (!encoding && c->palette_size && c->bpp <= 8 && c->format != CHUNKY) { + avctx->pix_fmt = AV_PIX_FMT_PAL8; +- } else if (encoding == 1 && (c->bpp == 6 || c->bpp == 8)) { ++ } else if (encoding == 1 && (c->bpp == 6 || c->bpp == 8) && c->format != CHUNKY) { + if (c->palette_size != (1 << (c->bpp - 1))) + return AVERROR_INVALIDDATA; + avctx->pix_fmt = AV_PIX_FMT_BGR24;",845,1176,2048 +18421,"bool ChromeRenderMessageFilter::OnMessageReceived(const IPC::Message& message, + bool* message_was_ok) { + bool handled = true; + IPC_BEGIN_MESSAGE_MAP_EX(ChromeRenderMessageFilter, message, *message_was_ok) +#if !defined(DISABLE_NACL) + IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_LaunchNaCl, OnLaunchNaCl) + IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_GetReadonlyPnaclFD, + OnGetReadonlyPnaclFd) + IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_NaClCreateTemporaryFile, + OnNaClCreateTemporaryFile) +#endif + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_DnsPrefetch, OnDnsPrefetch) + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_ResourceTypeStats, + OnResourceTypeStats) + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_UpdatedCacheStats, + OnUpdatedCacheStats) + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_FPS, OnFPS) + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_V8HeapStats, OnV8HeapStats) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_OpenChannelToExtension, + OnOpenChannelToExtension) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_OpenChannelToTab, OnOpenChannelToTab) + IPC_MESSAGE_HANDLER_DELAY_REPLY(ExtensionHostMsg_GetMessageBundle, + OnGetExtensionMessageBundle) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddListener, OnExtensionAddListener) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveListener, + OnExtensionRemoveListener) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddLazyListener, + OnExtensionAddLazyListener) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveLazyListener, + OnExtensionRemoveLazyListener) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddFilteredListener, + OnExtensionAddFilteredListener) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveFilteredListener, + OnExtensionRemoveFilteredListener) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_CloseChannel, OnExtensionCloseChannel) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_RequestForIOThread, + OnExtensionRequestForIOThread) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_ShouldUnloadAck, + OnExtensionShouldUnloadAck) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_GenerateUniqueID, + OnExtensionGenerateUniqueID) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_UnloadAck, OnExtensionUnloadAck) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_ResumeRequests, + OnExtensionResumeRequests); +#if defined(USE_TCMALLOC) + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_WriteTcmallocHeapProfile_ACK, + OnWriteTcmallocHeapProfile) +#endif + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowDatabase, OnAllowDatabase) + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowDOMStorage, OnAllowDOMStorage) + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowFileSystem, OnAllowFileSystem) + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowIndexedDB, OnAllowIndexedDB) + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_CanTriggerClipboardRead, + OnCanTriggerClipboardRead) + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_CanTriggerClipboardWrite, + OnCanTriggerClipboardWrite) + IPC_MESSAGE_UNHANDLED(handled = false) + IPC_END_MESSAGE_MAP() + +#if defined(ENABLE_AUTOMATION) + if ((message.type() == ChromeViewHostMsg_GetCookies::ID || + message.type() == ChromeViewHostMsg_SetCookie::ID) && + AutomationResourceMessageFilter::ShouldFilterCookieMessages( + render_process_id_, message.routing_id())) { + IPC_BEGIN_MESSAGE_MAP_EX(ChromeRenderMessageFilter, message, + *message_was_ok) + IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_GetCookies, + OnGetCookies) + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_SetCookie, OnSetCookie) + IPC_END_MESSAGE_MAP() + handled = true; + } +#endif + + return handled; +} +",1,"bool ChromeRenderMessageFilter::OnMessageReceived(const IPC::Message& message, + bool* message_was_ok) { + bool handled = true; + IPC_BEGIN_MESSAGE_MAP_EX(ChromeRenderMessageFilter, message, *message_was_ok) +#if !defined(DISABLE_NACL) + IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_LaunchNaCl, OnLaunchNaCl) + IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_GetReadonlyPnaclFD, + OnGetReadonlyPnaclFd) + IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_NaClCreateTemporaryFile, + OnNaClCreateTemporaryFile) +#endif + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_DnsPrefetch, OnDnsPrefetch) + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_ResourceTypeStats, + OnResourceTypeStats) + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_UpdatedCacheStats, + OnUpdatedCacheStats) + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_FPS, OnFPS) + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_V8HeapStats, OnV8HeapStats) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_OpenChannelToExtension, + OnOpenChannelToExtension) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_OpenChannelToTab, OnOpenChannelToTab) + IPC_MESSAGE_HANDLER_DELAY_REPLY(ExtensionHostMsg_GetMessageBundle, + OnGetExtensionMessageBundle) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddListener, OnExtensionAddListener) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveListener, + OnExtensionRemoveListener) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddLazyListener, + OnExtensionAddLazyListener) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveLazyListener, + OnExtensionRemoveLazyListener) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_AddFilteredListener, + OnExtensionAddFilteredListener) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_RemoveFilteredListener, + OnExtensionRemoveFilteredListener) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_CloseChannel, OnExtensionCloseChannel) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_RequestForIOThread, + OnExtensionRequestForIOThread) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_ShouldUnloadAck, + OnExtensionShouldUnloadAck) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_GenerateUniqueID, + OnExtensionGenerateUniqueID) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_UnloadAck, OnExtensionUnloadAck) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_ResumeRequests, + OnExtensionResumeRequests); + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowDatabase, OnAllowDatabase) + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowDOMStorage, OnAllowDOMStorage) + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowFileSystem, OnAllowFileSystem) + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowIndexedDB, OnAllowIndexedDB) + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_CanTriggerClipboardRead, + OnCanTriggerClipboardRead) + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_CanTriggerClipboardWrite, + OnCanTriggerClipboardWrite) + IPC_MESSAGE_UNHANDLED(handled = false) + IPC_END_MESSAGE_MAP() + +#if defined(ENABLE_AUTOMATION) + if ((message.type() == ChromeViewHostMsg_GetCookies::ID || + message.type() == ChromeViewHostMsg_SetCookie::ID) && + AutomationResourceMessageFilter::ShouldFilterCookieMessages( + render_process_id_, message.routing_id())) { + IPC_BEGIN_MESSAGE_MAP_EX(ChromeRenderMessageFilter, message, + *message_was_ok) + IPC_MESSAGE_HANDLER_DELAY_REPLY(ChromeViewHostMsg_GetCookies, + OnGetCookies) + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_SetCookie, OnSetCookie) + IPC_END_MESSAGE_MAP() + handled = true; + } +#endif + + return handled; +} +","@@ -112,10 +112,6 @@ bool ChromeRenderMessageFilter::OnMessageReceived(const IPC::Message& message, + IPC_MESSAGE_HANDLER(ExtensionHostMsg_UnloadAck, OnExtensionUnloadAck) + IPC_MESSAGE_HANDLER(ExtensionHostMsg_ResumeRequests, + OnExtensionResumeRequests); +-#if defined(USE_TCMALLOC) +- IPC_MESSAGE_HANDLER(ChromeViewHostMsg_WriteTcmallocHeapProfile_ACK, +- OnWriteTcmallocHeapProfile) +-#endif + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowDatabase, OnAllowDatabase) + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowDOMStorage, OnAllowDOMStorage) + IPC_MESSAGE_HANDLER(ChromeViewHostMsg_AllowFileSystem, OnAllowFileSystem) +@@ -473,15 +469,6 @@ void ChromeRenderMessageFilter::OnExtensionResumeRequests(int route_id) { + render_process_id_, route_id); + } + +-#if defined(USE_TCMALLOC) +-void ChromeRenderMessageFilter::OnWriteTcmallocHeapProfile( +- const FilePath::StringType& filepath, +- const std::string& output) { +- VLOG(0) << ""Writing renderer heap profile dump to: "" << filepath; +- file_util::WriteFile(FilePath(filepath), output.c_str(), output.size()); +-} +-#endif +- + void ChromeRenderMessageFilter::OnAllowDatabase(int render_view_id, + const GURL& origin_url, + const GURL& top_origin_url,",815,1146,2048 +5363,"static void lex_scan_string(lex_t *lex, json_error_t *error) +{ + int c; + const char *p; + char *t; + int i; + + lex->value.string.val = NULL; + lex->token = TOKEN_INVALID; + + c = lex_get_save(lex, error); + + while(c != '""') { + if(c == STREAM_STATE_ERROR) + goto out; + + else if(c == STREAM_STATE_EOF) { + error_set(error, lex, ""premature end of input""); + goto out; + } + + else if(0 <= c && c <= 0x1F) { + /* control character */ + lex_unget_unsave(lex, c); + if(c == '\n') + error_set(error, lex, ""unexpected newline"", c); + else + error_set(error, lex, ""control character 0x%x"", c); + goto out; + } + + else if(c == '\\') { + c = lex_get_save(lex, error); + if(c == 'u') { + c = lex_get_save(lex, error); + for(i = 0; i < 4; i++) { + if(!l_isxdigit(c)) { + error_set(error, lex, ""invalid escape""); + goto out; + } + c = lex_get_save(lex, error); + } + } + else if(c == '""' || c == '\\' || c == '/' || c == 'b' || + c == 'f' || c == 'n' || c == 'r' || c == 't') + c = lex_get_save(lex, error); + else { + error_set(error, lex, ""invalid escape""); + goto out; + } + } + else + c = lex_get_save(lex, error); + } + + /* the actual value is at most of the same length as the source + string, because: + - shortcut escapes (e.g. ""\t"") (length 2) are converted to 1 byte + - a single \uXXXX escape (length 6) is converted to at most 3 bytes + - two \uXXXX escapes (length 12) forming an UTF-16 surrogate pair + are converted to 4 bytes + */ + t = jsonp_malloc(lex->saved_text.length + 1); + if(!t) { + /* this is not very nice, since TOKEN_INVALID is returned */ + goto out; + } + lex->value.string.val = t; + + /* + 1 to skip the "" */ + p = strbuffer_value(&lex->saved_text) + 1; + + while(*p != '""') { + if(*p == '\\') { + p++; + if(*p == 'u') { + size_t length; + int32_t value; + + value = decode_unicode_escape(p); + if(value < 0) { + error_set(error, lex, ""invalid Unicode escape '%.6s'"", p - 1); + goto out; + } + p += 5; + + if(0xD800 <= value && value <= 0xDBFF) { + /* surrogate pair */ + if(*p == '\\' && *(p + 1) == 'u') { + int32_t value2 = decode_unicode_escape(++p); + if(value2 < 0) { + error_set(error, lex, ""invalid Unicode escape '%.6s'"", p - 1); + goto out; + } + p += 5; + + if(0xDC00 <= value2 && value2 <= 0xDFFF) { + /* valid second surrogate */ + value = + ((value - 0xD800) << 10) + + (value2 - 0xDC00) + + 0x10000; + } + else { + /* invalid second surrogate */ + error_set(error, lex, + ""invalid Unicode '\\u%04X\\u%04X'"", + value, value2); + goto out; + } + } + else { + /* no second surrogate */ + error_set(error, lex, ""invalid Unicode '\\u%04X'"", + value); + goto out; + } + } + else if(0xDC00 <= value && value <= 0xDFFF) { + error_set(error, lex, ""invalid Unicode '\\u%04X'"", value); + goto out; + } + + if(utf8_encode(value, t, &length)) + assert(0); + t += length; + } + else { + switch(*p) { + case '""': case '\\': case '/': + *t = *p; break; + case 'b': *t = '\b'; break; + case 'f': *t = '\f'; break; + case 'n': *t = '\n'; break; + case 'r': *t = '\r'; break; + case 't': *t = '\t'; break; + default: assert(0); + } + t++; + p++; + } + } + else + *(t++) = *(p++); + } + *t = '\0'; + lex->value.string.len = t - lex->value.string.val; + lex->token = TOKEN_STRING; + return; + +out: + lex_free_string(lex); +} +",0,"static void lex_scan_string(lex_t *lex, json_error_t *error) +{ + int c; + const char *p; + char *t; + int i; + + lex->value.string.val = NULL; + lex->token = TOKEN_INVALID; + + c = lex_get_save(lex, error); + + while(c != '""') { + if(c == STREAM_STATE_ERROR) + goto out; + + else if(c == STREAM_STATE_EOF) { + error_set(error, lex, ""premature end of input""); + goto out; + } + + else if(0 <= c && c <= 0x1F) { + /* control character */ + lex_unget_unsave(lex, c); + if(c == '\n') + error_set(error, lex, ""unexpected newline"", c); + else + error_set(error, lex, ""control character 0x%x"", c); + goto out; + } + + else if(c == '\\') { + c = lex_get_save(lex, error); + if(c == 'u') { + c = lex_get_save(lex, error); + for(i = 0; i < 4; i++) { + if(!l_isxdigit(c)) { + error_set(error, lex, ""invalid escape""); + goto out; + } + c = lex_get_save(lex, error); + } + } + else if(c == '""' || c == '\\' || c == '/' || c == 'b' || + c == 'f' || c == 'n' || c == 'r' || c == 't') + c = lex_get_save(lex, error); + else { + error_set(error, lex, ""invalid escape""); + goto out; + } + } + else + c = lex_get_save(lex, error); + } + + /* the actual value is at most of the same length as the source + string, because: + - shortcut escapes (e.g. ""\t"") (length 2) are converted to 1 byte + - a single \uXXXX escape (length 6) is converted to at most 3 bytes + - two \uXXXX escapes (length 12) forming an UTF-16 surrogate pair + are converted to 4 bytes + */ + t = jsonp_malloc(lex->saved_text.length + 1); + if(!t) { + /* this is not very nice, since TOKEN_INVALID is returned */ + goto out; + } + lex->value.string.val = t; + + /* + 1 to skip the "" */ + p = strbuffer_value(&lex->saved_text) + 1; + + while(*p != '""') { + if(*p == '\\') { + p++; + if(*p == 'u') { + size_t length; + int32_t value; + + value = decode_unicode_escape(p); + if(value < 0) { + error_set(error, lex, ""invalid Unicode escape '%.6s'"", p - 1); + goto out; + } + p += 5; + + if(0xD800 <= value && value <= 0xDBFF) { + /* surrogate pair */ + if(*p == '\\' && *(p + 1) == 'u') { + int32_t value2 = decode_unicode_escape(++p); + if(value2 < 0) { + error_set(error, lex, ""invalid Unicode escape '%.6s'"", p - 1); + goto out; + } + p += 5; + + if(0xDC00 <= value2 && value2 <= 0xDFFF) { + /* valid second surrogate */ + value = + ((value - 0xD800) << 10) + + (value2 - 0xDC00) + + 0x10000; + } + else { + /* invalid second surrogate */ + error_set(error, lex, + ""invalid Unicode '\\u%04X\\u%04X'"", + value, value2); + goto out; + } + } + else { + /* no second surrogate */ + error_set(error, lex, ""invalid Unicode '\\u%04X'"", + value); + goto out; + } + } + else if(0xDC00 <= value && value <= 0xDFFF) { + error_set(error, lex, ""invalid Unicode '\\u%04X'"", value); + goto out; + } + + if(utf8_encode(value, t, &length)) + assert(0); + t += length; + } + else { + switch(*p) { + case '""': case '\\': case '/': + *t = *p; break; + case 'b': *t = '\b'; break; + case 'f': *t = '\f'; break; + case 'n': *t = '\n'; break; + case 'r': *t = '\r'; break; + case 't': *t = '\t'; break; + default: assert(0); + } + t++; + p++; + } + } + else + *(t++) = *(p++); + } + *t = '\0'; + lex->value.string.len = t - lex->value.string.val; + lex->token = TOKEN_STRING; + return; + +out: + lex_free_string(lex); +} +","@@ -62,6 +62,7 @@ typedef struct { + stream_t stream; + strbuffer_t saved_text; + size_t flags; ++ size_t depth; + int token; + union { + struct { +@@ -803,6 +804,12 @@ static json_t *parse_value(lex_t *lex, size_t flags, json_error_t *error) + { + json_t *json; + ++ lex->depth++; ++ if(lex->depth > JSON_PARSER_MAX_DEPTH) { ++ error_set(error, lex, ""maximum parsing depth reached""); ++ return NULL; ++ } ++ + switch(lex->token) { + case TOKEN_STRING: { + const char *value = lex->value.string.val; +@@ -865,13 +872,16 @@ static json_t *parse_value(lex_t *lex, size_t flags, json_error_t *error) + if(!json) + return NULL; + ++ lex->depth--; + return json; + } + + static json_t *parse_json(lex_t *lex, size_t flags, json_error_t *error) + { + json_t *result; + ++ lex->depth = 0; ++ + lex_scan(lex, error); + if(!(flags & JSON_DECODE_ANY)) { + if(lex->token != '[' && lex->token != '{') {",1136,1467,2048 +18066,"static int tty_open(struct inode *inode, struct file *filp) +{ + struct tty_struct *tty = NULL; + int noctty, retval; + struct tty_driver *driver; + int index; + dev_t device = inode->i_rdev; + unsigned saved_flags = filp->f_flags; + + nonseekable_open(inode, filp); + +retry_open: + noctty = filp->f_flags & O_NOCTTY; + index = -1; + retval = 0; + + mutex_lock(&tty_mutex); + tty_lock(); + + if (device == MKDEV(TTYAUX_MAJOR, 0)) { + tty = get_current_tty(); + if (!tty) { + tty_unlock(); + mutex_unlock(&tty_mutex); + return -ENXIO; + } + driver = tty_driver_kref_get(tty->driver); + index = tty->index; + filp->f_flags |= O_NONBLOCK; /* Don't let /dev/tty block */ + /* noctty = 1; */ + /* FIXME: Should we take a driver reference ? */ + tty_kref_put(tty); + goto got_driver; + } +#ifdef CONFIG_VT + if (device == MKDEV(TTY_MAJOR, 0)) { + extern struct tty_driver *console_driver; + driver = tty_driver_kref_get(console_driver); + index = fg_console; + noctty = 1; + goto got_driver; + } +#endif + if (device == MKDEV(TTYAUX_MAJOR, 1)) { + struct tty_driver *console_driver = console_device(&index); + if (console_driver) { + driver = tty_driver_kref_get(console_driver); + if (driver) { + /* Don't let /dev/console block */ + filp->f_flags |= O_NONBLOCK; + noctty = 1; + goto got_driver; + } + } + tty_unlock(); + mutex_unlock(&tty_mutex); + return -ENODEV; + } + + driver = get_tty_driver(device, &index); + if (!driver) { + tty_unlock(); + mutex_unlock(&tty_mutex); + return -ENODEV; + } +got_driver: + if (!tty) { + /* check whether we're reopening an existing tty */ + tty = tty_driver_lookup_tty(driver, inode, index); + + if (IS_ERR(tty)) { + tty_unlock(); + mutex_unlock(&tty_mutex); + return PTR_ERR(tty); + } + } + + if (tty) { + retval = tty_reopen(tty); + if (retval) + tty = ERR_PTR(retval); + } else + tty = tty_init_dev(driver, index, 0); + + mutex_unlock(&tty_mutex); + tty_driver_kref_put(driver); + if (IS_ERR(tty)) { + tty_unlock(); + return PTR_ERR(tty); + } + + retval = tty_add_file(tty, filp); + if (retval) { + tty_unlock(); + tty_release(inode, filp); + return retval; + } + + check_tty_count(tty, ""tty_open""); + if (tty->driver->type == TTY_DRIVER_TYPE_PTY && + tty->driver->subtype == PTY_TYPE_MASTER) + noctty = 1; +#ifdef TTY_DEBUG_HANGUP + printk(KERN_DEBUG ""opening %s..."", tty->name); +#endif + if (tty->ops->open) + retval = tty->ops->open(tty, filp); + else + retval = -ENODEV; + filp->f_flags = saved_flags; + + if (!retval && test_bit(TTY_EXCLUSIVE, &tty->flags) && + !capable(CAP_SYS_ADMIN)) + retval = -EBUSY; + + if (retval) { +#ifdef TTY_DEBUG_HANGUP + printk(KERN_DEBUG ""error %d in opening %s..."", retval, + tty->name); +#endif + tty_unlock(); /* need to call tty_release without BTM */ + tty_release(inode, filp); + if (retval != -ERESTARTSYS) + return retval; + + if (signal_pending(current)) + return retval; + + schedule(); + /* + * Need to reset f_op in case a hangup happened. + */ + tty_lock(); + if (filp->f_op == &hung_up_tty_fops) + filp->f_op = &tty_fops; + tty_unlock(); + goto retry_open; + } + tty_unlock(); + + + mutex_lock(&tty_mutex); + tty_lock(); + spin_lock_irq(¤t->sighand->siglock); + if (!noctty && + current->signal->leader && + !current->signal->tty && + tty->session == NULL) + __proc_set_tty(current, tty); + spin_unlock_irq(¤t->sighand->siglock); + tty_unlock(); + mutex_unlock(&tty_mutex); + return 0; +} +",1,"static int tty_open(struct inode *inode, struct file *filp) +{ + struct tty_struct *tty = NULL; + int noctty, retval; + struct tty_driver *driver; + int index; + dev_t device = inode->i_rdev; + unsigned saved_flags = filp->f_flags; + + nonseekable_open(inode, filp); + +retry_open: + noctty = filp->f_flags & O_NOCTTY; + index = -1; + retval = 0; + + mutex_lock(&tty_mutex); + tty_lock(); + + if (device == MKDEV(TTYAUX_MAJOR, 0)) { + tty = get_current_tty(); + if (!tty) { + tty_unlock(); + mutex_unlock(&tty_mutex); + return -ENXIO; + } + driver = tty_driver_kref_get(tty->driver); + index = tty->index; + filp->f_flags |= O_NONBLOCK; /* Don't let /dev/tty block */ + /* noctty = 1; */ + /* FIXME: Should we take a driver reference ? */ + tty_kref_put(tty); + goto got_driver; + } +#ifdef CONFIG_VT + if (device == MKDEV(TTY_MAJOR, 0)) { + extern struct tty_driver *console_driver; + driver = tty_driver_kref_get(console_driver); + index = fg_console; + noctty = 1; + goto got_driver; + } +#endif + if (device == MKDEV(TTYAUX_MAJOR, 1)) { + struct tty_driver *console_driver = console_device(&index); + if (console_driver) { + driver = tty_driver_kref_get(console_driver); + if (driver) { + /* Don't let /dev/console block */ + filp->f_flags |= O_NONBLOCK; + noctty = 1; + goto got_driver; + } + } + tty_unlock(); + mutex_unlock(&tty_mutex); + return -ENODEV; + } + + driver = get_tty_driver(device, &index); + if (!driver) { + tty_unlock(); + mutex_unlock(&tty_mutex); + return -ENODEV; + } +got_driver: + if (!tty) { + /* check whether we're reopening an existing tty */ + tty = tty_driver_lookup_tty(driver, inode, index); + + if (IS_ERR(tty)) { + tty_unlock(); + mutex_unlock(&tty_mutex); + tty_driver_kref_put(driver); + return PTR_ERR(tty); + } + } + + if (tty) { + retval = tty_reopen(tty); + if (retval) + tty = ERR_PTR(retval); + } else + tty = tty_init_dev(driver, index, 0); + + mutex_unlock(&tty_mutex); + tty_driver_kref_put(driver); + if (IS_ERR(tty)) { + tty_unlock(); + return PTR_ERR(tty); + } + + retval = tty_add_file(tty, filp); + if (retval) { + tty_unlock(); + tty_release(inode, filp); + return retval; + } + + check_tty_count(tty, ""tty_open""); + if (tty->driver->type == TTY_DRIVER_TYPE_PTY && + tty->driver->subtype == PTY_TYPE_MASTER) + noctty = 1; +#ifdef TTY_DEBUG_HANGUP + printk(KERN_DEBUG ""opening %s..."", tty->name); +#endif + if (tty->ops->open) + retval = tty->ops->open(tty, filp); + else + retval = -ENODEV; + filp->f_flags = saved_flags; + + if (!retval && test_bit(TTY_EXCLUSIVE, &tty->flags) && + !capable(CAP_SYS_ADMIN)) + retval = -EBUSY; + + if (retval) { +#ifdef TTY_DEBUG_HANGUP + printk(KERN_DEBUG ""error %d in opening %s..."", retval, + tty->name); +#endif + tty_unlock(); /* need to call tty_release without BTM */ + tty_release(inode, filp); + if (retval != -ERESTARTSYS) + return retval; + + if (signal_pending(current)) + return retval; + + schedule(); + /* + * Need to reset f_op in case a hangup happened. + */ + tty_lock(); + if (filp->f_op == &hung_up_tty_fops) + filp->f_op = &tty_fops; + tty_unlock(); + goto retry_open; + } + tty_unlock(); + + + mutex_lock(&tty_mutex); + tty_lock(); + spin_lock_irq(¤t->sighand->siglock); + if (!noctty && + current->signal->leader && + !current->signal->tty && + tty->session == NULL) + __proc_set_tty(current, tty); + spin_unlock_irq(¤t->sighand->siglock); + tty_unlock(); + mutex_unlock(&tty_mutex); + return 0; +} +","@@ -1873,6 +1873,7 @@ static int tty_open(struct inode *inode, struct file *filp) + if (IS_ERR(tty)) { + tty_unlock(); + mutex_unlock(&tty_mutex); ++ tty_driver_kref_put(driver); + return PTR_ERR(tty); + } + }",1034,1365,2048 +17454,"IMPEG2D_ERROR_CODES_T impeg2d_vld_inv_quant_mpeg2( + void *pv_dec, /* Decoder State */ + WORD16 *pi2_out_addr, /*!< Address where decoded symbols will be stored */ + const UWORD8 *pu1_scan, /*!< Scan table to be used */ + UWORD16 u2_intra_flag, /*!< Intra Macroblock or not */ + UWORD16 u2_colr_comp, /*!< 0 - Luma,1 - U comp, 2 - V comp */ + UWORD16 u2_d_picture /*!< D Picture or not */ + ) +{ + UWORD8 *pu1_weighting_matrix; + WORD32 u4_sum_is_even; + dec_state_t *ps_dec = (dec_state_t *)pv_dec; + IMPEG2D_ERROR_CODES_T e_error = (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; + + WORD16 pi2_coeffs[NUM_COEFFS]; + UWORD8 pi4_pos[NUM_COEFFS]; + WORD32 i4_num_coeffs; + + /* Perform VLD on the stream to get the coefficients and their positions */ + e_error = impeg2d_vld_decode(ps_dec, pi2_coeffs, pu1_scan, pi4_pos, u2_intra_flag, + u2_colr_comp, u2_d_picture, ps_dec->u2_intra_vlc_format, + ps_dec->u2_is_mpeg2, &i4_num_coeffs); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + return e_error; + } + + /* For YUV420 format,Select the weighting matrix according to Table 7.5 */ + pu1_weighting_matrix = (u2_intra_flag == 1) ? ps_dec->au1_intra_quant_matrix: + ps_dec->au1_inter_quant_matrix; + + /*mismatch control for mpeg2*/ + /* Check if the block has only one non-zero coeff which is DC */ + ps_dec->i4_last_value_one = 0; + + IMPEG2D_IQNT_INP_STATISTICS(pi2_out_addr, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows); + + /* Inverse Quantize the Output of VLD */ + PROFILE_DISABLE_INVQUANT_IF0 + + { + /* Clear output matrix */ + PROFILE_DISABLE_MEMSET_RESBUF_IF0 + if (1 != (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows)) + { + ps_dec->pf_memset_16bit_8x8_linear_block (pi2_out_addr); + } + + u4_sum_is_even = impeg2d_inv_quant_mpeg2(pi2_out_addr, pu1_weighting_matrix, + ps_dec->u1_quant_scale, u2_intra_flag, + i4_num_coeffs, pi2_coeffs, + pi4_pos, pu1_scan, + &ps_dec->u2_def_dc_pred[u2_colr_comp], + ps_dec->u2_intra_dc_precision); + + if (0 != pi2_out_addr[0]) + { + /* The first coeff might've become non-zero due to intra_dc_decision + * value. So, check here after inverse quantization. + */ + ps_dec->u4_non_zero_cols |= 0x1; + ps_dec->u4_non_zero_rows |= 0x1; + } + + if (1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows)) + { + ps_dec->i4_last_value_one = 1 - (pi2_out_addr[0] & 1); + } + else + { + /*toggle last bit if sum is even ,else retain it as it is*/ + pi2_out_addr[63] ^= (u4_sum_is_even & 1); + + if (0 != pi2_out_addr[63]) + { + ps_dec->u4_non_zero_cols |= 0x80; + ps_dec->u4_non_zero_rows |= 0x80; + } + } + } + + return e_error; +} +",0,"IMPEG2D_ERROR_CODES_T impeg2d_vld_inv_quant_mpeg2( + void *pv_dec, /* Decoder State */ + WORD16 *pi2_out_addr, /*!< Address where decoded symbols will be stored */ + const UWORD8 *pu1_scan, /*!< Scan table to be used */ + UWORD16 u2_intra_flag, /*!< Intra Macroblock or not */ + UWORD16 u2_colr_comp, /*!< 0 - Luma,1 - U comp, 2 - V comp */ + UWORD16 u2_d_picture /*!< D Picture or not */ + ) +{ + UWORD8 *pu1_weighting_matrix; + WORD32 u4_sum_is_even; + dec_state_t *ps_dec = (dec_state_t *)pv_dec; + IMPEG2D_ERROR_CODES_T e_error = (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; + + WORD16 pi2_coeffs[NUM_COEFFS]; + UWORD8 pi4_pos[NUM_COEFFS]; + WORD32 i4_num_coeffs; + + /* Perform VLD on the stream to get the coefficients and their positions */ + e_error = impeg2d_vld_decode(ps_dec, pi2_coeffs, pu1_scan, pi4_pos, u2_intra_flag, + u2_colr_comp, u2_d_picture, ps_dec->u2_intra_vlc_format, + ps_dec->u2_is_mpeg2, &i4_num_coeffs); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + return e_error; + } + + /* For YUV420 format,Select the weighting matrix according to Table 7.5 */ + pu1_weighting_matrix = (u2_intra_flag == 1) ? ps_dec->au1_intra_quant_matrix: + ps_dec->au1_inter_quant_matrix; + + /*mismatch control for mpeg2*/ + /* Check if the block has only one non-zero coeff which is DC */ + ps_dec->i4_last_value_one = 0; + + IMPEG2D_IQNT_INP_STATISTICS(pi2_out_addr, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows); + + /* Inverse Quantize the Output of VLD */ + PROFILE_DISABLE_INVQUANT_IF0 + + { + /* Clear output matrix */ + PROFILE_DISABLE_MEMSET_RESBUF_IF0 + if (1 != (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows)) + { + ps_dec->pf_memset_16bit_8x8_linear_block (pi2_out_addr); + } + + u4_sum_is_even = impeg2d_inv_quant_mpeg2(pi2_out_addr, pu1_weighting_matrix, + ps_dec->u1_quant_scale, u2_intra_flag, + i4_num_coeffs, pi2_coeffs, + pi4_pos, pu1_scan, + &ps_dec->u2_def_dc_pred[u2_colr_comp], + ps_dec->u2_intra_dc_precision); + + if (0 != pi2_out_addr[0]) + { + /* The first coeff might've become non-zero due to intra_dc_decision + * value. So, check here after inverse quantization. + */ + ps_dec->u4_non_zero_cols |= 0x1; + ps_dec->u4_non_zero_rows |= 0x1; + } + + if (1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows)) + { + ps_dec->i4_last_value_one = 1 - (pi2_out_addr[0] & 1); + } + else + { + /*toggle last bit if sum is even ,else retain it as it is*/ + pi2_out_addr[63] ^= (u4_sum_is_even & 1); + + if (0 != pi2_out_addr[63]) + { + ps_dec->u4_non_zero_cols |= 0x80; + ps_dec->u4_non_zero_rows |= 0x80; + } + } + } + + return e_error; +} +","@@ -789,13 +789,13 @@ + + u4_nz_cols |= 1 << (u4_pos & 0x7); + u4_nz_rows |= 1 << (u4_pos >> 0x3); + ++ if (u4_numCoeffs > 64) ++ { ++ return IMPEG2D_MB_TEX_DECODE_ERR; ++ } + + } + IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,u4_sym_len) +- if (u4_numCoeffs > 64) +- { +- return IMPEG2D_MB_TEX_DECODE_ERR; +- } + } + else + { +@@ -957,10 +957,11 @@ + + + u4_nz_cols |= 1 << (u4_pos & 0x7); + u4_nz_rows |= 1 << (u4_pos >> 0x3); +- } +- if (u4_numCoeffs > 64) +- { +- return IMPEG2D_MB_TEX_DECODE_ERR; ++ if (u4_numCoeffs > 64) ++ { ++ return IMPEG2D_MB_TEX_DECODE_ERR; ++ } ++ + } + + IBITS_GET(u4_buf,u4_buf_nxt,u4_offset,u4_bits,pu4_buf_aligned,u4_sym_len) +",866,1197,2048 +6556,"nfsd4_decode_fattr(struct nfsd4_compoundargs *argp, u32 *bmval, + struct iattr *iattr, struct nfs4_acl **acl, + struct xdr_netobj *label, int *umask) +{ + int expected_len, len = 0; + u32 dummy32; + char *buf; + + DECODE_HEAD; + iattr->ia_valid = 0; + if ((status = nfsd4_decode_bitmap(argp, bmval))) + return status; + + if (bmval[0] & ~NFSD_WRITEABLE_ATTRS_WORD0 + || bmval[1] & ~NFSD_WRITEABLE_ATTRS_WORD1 + || bmval[2] & ~NFSD_WRITEABLE_ATTRS_WORD2) { + if (nfsd_attrs_supported(argp->minorversion, bmval)) + return nfserr_inval; + return nfserr_attrnotsupp; + } + + READ_BUF(4); + expected_len = be32_to_cpup(p++); + + if (bmval[0] & FATTR4_WORD0_SIZE) { + READ_BUF(8); + len += 8; + p = xdr_decode_hyper(p, &iattr->ia_size); + iattr->ia_valid |= ATTR_SIZE; + } + if (bmval[0] & FATTR4_WORD0_ACL) { + u32 nace; + struct nfs4_ace *ace; + + READ_BUF(4); len += 4; + nace = be32_to_cpup(p++); + + if (nace > NFS4_ACL_MAX) + return nfserr_fbig; + + *acl = svcxdr_tmpalloc(argp, nfs4_acl_bytes(nace)); + if (*acl == NULL) + return nfserr_jukebox; + + (*acl)->naces = nace; + for (ace = (*acl)->aces; ace < (*acl)->aces + nace; ace++) { + READ_BUF(16); len += 16; + ace->type = be32_to_cpup(p++); + ace->flag = be32_to_cpup(p++); + ace->access_mask = be32_to_cpup(p++); + dummy32 = be32_to_cpup(p++); + READ_BUF(dummy32); + len += XDR_QUADLEN(dummy32) << 2; + READMEM(buf, dummy32); + ace->whotype = nfs4_acl_get_whotype(buf, dummy32); + status = nfs_ok; + if (ace->whotype != NFS4_ACL_WHO_NAMED) + ; + else if (ace->flag & NFS4_ACE_IDENTIFIER_GROUP) + status = nfsd_map_name_to_gid(argp->rqstp, + buf, dummy32, &ace->who_gid); + else + status = nfsd_map_name_to_uid(argp->rqstp, + buf, dummy32, &ace->who_uid); + if (status) + return status; + } + } else + *acl = NULL; + if (bmval[1] & FATTR4_WORD1_MODE) { + READ_BUF(4); + len += 4; + iattr->ia_mode = be32_to_cpup(p++); + iattr->ia_mode &= (S_IFMT | S_IALLUGO); + iattr->ia_valid |= ATTR_MODE; + } + if (bmval[1] & FATTR4_WORD1_OWNER) { + READ_BUF(4); + len += 4; + dummy32 = be32_to_cpup(p++); + READ_BUF(dummy32); + len += (XDR_QUADLEN(dummy32) << 2); + READMEM(buf, dummy32); + if ((status = nfsd_map_name_to_uid(argp->rqstp, buf, dummy32, &iattr->ia_uid))) + return status; + iattr->ia_valid |= ATTR_UID; + } + if (bmval[1] & FATTR4_WORD1_OWNER_GROUP) { + READ_BUF(4); + len += 4; + dummy32 = be32_to_cpup(p++); + READ_BUF(dummy32); + len += (XDR_QUADLEN(dummy32) << 2); + READMEM(buf, dummy32); + if ((status = nfsd_map_name_to_gid(argp->rqstp, buf, dummy32, &iattr->ia_gid))) + return status; + iattr->ia_valid |= ATTR_GID; + } + if (bmval[1] & FATTR4_WORD1_TIME_ACCESS_SET) { + READ_BUF(4); + len += 4; + dummy32 = be32_to_cpup(p++); + switch (dummy32) { + case NFS4_SET_TO_CLIENT_TIME: + len += 12; + status = nfsd4_decode_time(argp, &iattr->ia_atime); + if (status) + return status; + iattr->ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET); + break; + case NFS4_SET_TO_SERVER_TIME: + iattr->ia_valid |= ATTR_ATIME; + break; + default: + goto xdr_error; + } + } + if (bmval[1] & FATTR4_WORD1_TIME_MODIFY_SET) { + READ_BUF(4); + len += 4; + dummy32 = be32_to_cpup(p++); + switch (dummy32) { + case NFS4_SET_TO_CLIENT_TIME: + len += 12; + status = nfsd4_decode_time(argp, &iattr->ia_mtime); + if (status) + return status; + iattr->ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET); + break; + case NFS4_SET_TO_SERVER_TIME: + iattr->ia_valid |= ATTR_MTIME; + break; + default: + goto xdr_error; + } + } + + label->len = 0; +#ifdef CONFIG_NFSD_V4_SECURITY_LABEL + if (bmval[2] & FATTR4_WORD2_SECURITY_LABEL) { + READ_BUF(4); + len += 4; + dummy32 = be32_to_cpup(p++); /* lfs: we don't use it */ + READ_BUF(4); + len += 4; + dummy32 = be32_to_cpup(p++); /* pi: we don't use it either */ + READ_BUF(4); + len += 4; + dummy32 = be32_to_cpup(p++); + READ_BUF(dummy32); + if (dummy32 > NFS4_MAXLABELLEN) + return nfserr_badlabel; + len += (XDR_QUADLEN(dummy32) << 2); + READMEM(buf, dummy32); + label->len = dummy32; + label->data = svcxdr_dupstr(argp, buf, dummy32); + if (!label->data) + return nfserr_jukebox; + } +#endif + if (bmval[2] & FATTR4_WORD2_MODE_UMASK) { + if (!umask) + goto xdr_error; + READ_BUF(8); + len += 8; + dummy32 = be32_to_cpup(p++); + iattr->ia_mode = dummy32 & (S_IFMT | S_IALLUGO); + dummy32 = be32_to_cpup(p++); + *umask = dummy32 & S_IRWXUGO; + iattr->ia_valid |= ATTR_MODE; + } + if (len != expected_len) + goto xdr_error; + + DECODE_TAIL; +} +",0,"nfsd4_decode_fattr(struct nfsd4_compoundargs *argp, u32 *bmval, + struct iattr *iattr, struct nfs4_acl **acl, + struct xdr_netobj *label, int *umask) +{ + int expected_len, len = 0; + u32 dummy32; + char *buf; + + DECODE_HEAD; + iattr->ia_valid = 0; + if ((status = nfsd4_decode_bitmap(argp, bmval))) + return status; + + if (bmval[0] & ~NFSD_WRITEABLE_ATTRS_WORD0 + || bmval[1] & ~NFSD_WRITEABLE_ATTRS_WORD1 + || bmval[2] & ~NFSD_WRITEABLE_ATTRS_WORD2) { + if (nfsd_attrs_supported(argp->minorversion, bmval)) + return nfserr_inval; + return nfserr_attrnotsupp; + } + + READ_BUF(4); + expected_len = be32_to_cpup(p++); + + if (bmval[0] & FATTR4_WORD0_SIZE) { + READ_BUF(8); + len += 8; + p = xdr_decode_hyper(p, &iattr->ia_size); + iattr->ia_valid |= ATTR_SIZE; + } + if (bmval[0] & FATTR4_WORD0_ACL) { + u32 nace; + struct nfs4_ace *ace; + + READ_BUF(4); len += 4; + nace = be32_to_cpup(p++); + + if (nace > NFS4_ACL_MAX) + return nfserr_fbig; + + *acl = svcxdr_tmpalloc(argp, nfs4_acl_bytes(nace)); + if (*acl == NULL) + return nfserr_jukebox; + + (*acl)->naces = nace; + for (ace = (*acl)->aces; ace < (*acl)->aces + nace; ace++) { + READ_BUF(16); len += 16; + ace->type = be32_to_cpup(p++); + ace->flag = be32_to_cpup(p++); + ace->access_mask = be32_to_cpup(p++); + dummy32 = be32_to_cpup(p++); + READ_BUF(dummy32); + len += XDR_QUADLEN(dummy32) << 2; + READMEM(buf, dummy32); + ace->whotype = nfs4_acl_get_whotype(buf, dummy32); + status = nfs_ok; + if (ace->whotype != NFS4_ACL_WHO_NAMED) + ; + else if (ace->flag & NFS4_ACE_IDENTIFIER_GROUP) + status = nfsd_map_name_to_gid(argp->rqstp, + buf, dummy32, &ace->who_gid); + else + status = nfsd_map_name_to_uid(argp->rqstp, + buf, dummy32, &ace->who_uid); + if (status) + return status; + } + } else + *acl = NULL; + if (bmval[1] & FATTR4_WORD1_MODE) { + READ_BUF(4); + len += 4; + iattr->ia_mode = be32_to_cpup(p++); + iattr->ia_mode &= (S_IFMT | S_IALLUGO); + iattr->ia_valid |= ATTR_MODE; + } + if (bmval[1] & FATTR4_WORD1_OWNER) { + READ_BUF(4); + len += 4; + dummy32 = be32_to_cpup(p++); + READ_BUF(dummy32); + len += (XDR_QUADLEN(dummy32) << 2); + READMEM(buf, dummy32); + if ((status = nfsd_map_name_to_uid(argp->rqstp, buf, dummy32, &iattr->ia_uid))) + return status; + iattr->ia_valid |= ATTR_UID; + } + if (bmval[1] & FATTR4_WORD1_OWNER_GROUP) { + READ_BUF(4); + len += 4; + dummy32 = be32_to_cpup(p++); + READ_BUF(dummy32); + len += (XDR_QUADLEN(dummy32) << 2); + READMEM(buf, dummy32); + if ((status = nfsd_map_name_to_gid(argp->rqstp, buf, dummy32, &iattr->ia_gid))) + return status; + iattr->ia_valid |= ATTR_GID; + } + if (bmval[1] & FATTR4_WORD1_TIME_ACCESS_SET) { + READ_BUF(4); + len += 4; + dummy32 = be32_to_cpup(p++); + switch (dummy32) { + case NFS4_SET_TO_CLIENT_TIME: + len += 12; + status = nfsd4_decode_time(argp, &iattr->ia_atime); + if (status) + return status; + iattr->ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET); + break; + case NFS4_SET_TO_SERVER_TIME: + iattr->ia_valid |= ATTR_ATIME; + break; + default: + goto xdr_error; + } + } + if (bmval[1] & FATTR4_WORD1_TIME_MODIFY_SET) { + READ_BUF(4); + len += 4; + dummy32 = be32_to_cpup(p++); + switch (dummy32) { + case NFS4_SET_TO_CLIENT_TIME: + len += 12; + status = nfsd4_decode_time(argp, &iattr->ia_mtime); + if (status) + return status; + iattr->ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET); + break; + case NFS4_SET_TO_SERVER_TIME: + iattr->ia_valid |= ATTR_MTIME; + break; + default: + goto xdr_error; + } + } + + label->len = 0; +#ifdef CONFIG_NFSD_V4_SECURITY_LABEL + if (bmval[2] & FATTR4_WORD2_SECURITY_LABEL) { + READ_BUF(4); + len += 4; + dummy32 = be32_to_cpup(p++); /* lfs: we don't use it */ + READ_BUF(4); + len += 4; + dummy32 = be32_to_cpup(p++); /* pi: we don't use it either */ + READ_BUF(4); + len += 4; + dummy32 = be32_to_cpup(p++); + READ_BUF(dummy32); + if (dummy32 > NFS4_MAXLABELLEN) + return nfserr_badlabel; + len += (XDR_QUADLEN(dummy32) << 2); + READMEM(buf, dummy32); + label->len = dummy32; + label->data = svcxdr_dupstr(argp, buf, dummy32); + if (!label->data) + return nfserr_jukebox; + } +#endif + if (bmval[2] & FATTR4_WORD2_MODE_UMASK) { + if (!umask) + goto xdr_error; + READ_BUF(8); + len += 8; + dummy32 = be32_to_cpup(p++); + iattr->ia_mode = dummy32 & (S_IFMT | S_IALLUGO); + dummy32 = be32_to_cpup(p++); + *umask = dummy32 & S_IRWXUGO; + iattr->ia_valid |= ATTR_MODE; + } + if (len != expected_len) + goto xdr_error; + + DECODE_TAIL; +} +","@@ -2831,9 +2831,14 @@ nfsd4_encode_fattr(struct xdr_stream *xdr, struct svc_fh *fhp, + } + #endif /* CONFIG_NFSD_PNFS */ + if (bmval2 & FATTR4_WORD2_SUPPATTR_EXCLCREAT) { +- status = nfsd4_encode_bitmap(xdr, NFSD_SUPPATTR_EXCLCREAT_WORD0, +- NFSD_SUPPATTR_EXCLCREAT_WORD1, +- NFSD_SUPPATTR_EXCLCREAT_WORD2); ++ u32 supp[3]; ++ ++ memcpy(supp, nfsd_suppattrs[minorversion], sizeof(supp)); ++ supp[0] &= NFSD_SUPPATTR_EXCLCREAT_WORD0; ++ supp[1] &= NFSD_SUPPATTR_EXCLCREAT_WORD1; ++ supp[2] &= NFSD_SUPPATTR_EXCLCREAT_WORD2; ++ ++ status = nfsd4_encode_bitmap(xdr, supp[0], supp[1], supp[2]); + if (status) + goto out; + } +@@ -4119,8 +4124,7 @@ nfsd4_encode_getdeviceinfo(struct nfsd4_compoundres *resp, __be32 nfserr, + struct nfsd4_getdeviceinfo *gdev) + { + struct xdr_stream *xdr = &resp->xdr; +- const struct nfsd4_layout_ops *ops = +- nfsd4_layout_ops[gdev->gd_layout_type]; ++ const struct nfsd4_layout_ops *ops; + u32 starting_len = xdr->buf->len, needed_len; + __be32 *p; + +@@ -4137,6 +4141,7 @@ nfsd4_encode_getdeviceinfo(struct nfsd4_compoundres *resp, __be32 nfserr, + + /* If maxcount is 0 then just update notifications */ + if (gdev->gd_maxcount != 0) { ++ ops = nfsd4_layout_ops[gdev->gd_layout_type]; + nfserr = ops->encode_getdeviceinfo(xdr, gdev); + if (nfserr) { + /* +@@ -4189,8 +4194,7 @@ nfsd4_encode_layoutget(struct nfsd4_compoundres *resp, __be32 nfserr, + struct nfsd4_layoutget *lgp) + { + struct xdr_stream *xdr = &resp->xdr; +- const struct nfsd4_layout_ops *ops = +- nfsd4_layout_ops[lgp->lg_layout_type]; ++ const struct nfsd4_layout_ops *ops; + __be32 *p; + + dprintk(""%s: err %d\n"", __func__, nfserr); +@@ -4213,6 +4217,7 @@ nfsd4_encode_layoutget(struct nfsd4_compoundres *resp, __be32 nfserr, + *p++ = cpu_to_be32(lgp->lg_seg.iomode); + *p++ = cpu_to_be32(lgp->lg_layout_type); + ++ ops = nfsd4_layout_ops[lgp->lg_layout_type]; + nfserr = ops->encode_layoutget(xdr, lgp); + out: + kfree(lgp->lg_content);",1677,2008,2048 +16815,"void AutofillManager::FillOrPreviewDataModelForm( + AutofillDriver::RendererFormDataAction action, + int query_id, + const FormData& form, + const FormFieldData& field, + const AutofillDataModel& data_model, + bool is_credit_card, + const base::string16& cvc, + FormStructure* form_structure, + AutofillField* autofill_field, + bool is_refill) { + DCHECK(form_structure); + DCHECK(autofill_field); + + FormData result = form; + + if (base::FeatureList::IsEnabled(kAutofillRationalizeFieldTypePredictions)) { + form_structure->RationalizePhoneNumbersInSection(autofill_field->section); + } + + DCHECK_EQ(form_structure->field_count(), form.fields.size()); + + FillingContext* filling_context = nullptr; + auto itr = + filling_contexts_map_.find(form_structure->GetIdentifierForRefill()); + if (itr != filling_contexts_map_.end()) + filling_context = itr->second.get(); + bool could_attempt_refill = + base::FeatureList::IsEnabled(features::kAutofillDynamicForms) && + filling_context != nullptr && !filling_context->attempted_refill && + !is_refill && !is_credit_card; + + for (size_t i = 0; i < form_structure->field_count(); ++i) { + if (form_structure->field(i)->section != autofill_field->section) + continue; + + if (form_structure->field(i)->only_fill_when_focused() && + !form_structure->field(i)->SameFieldAs(field)) { + continue; + } + + DCHECK(form_structure->field(i)->SameFieldAs(result.fields[i])); + + AutofillField* cached_field = form_structure->field(i); + FieldTypeGroup field_group_type = cached_field->Type().group(); + + if (!cached_field->IsVisible()) { + bool skip = result.fields[i].form_control_type != ""select-one""; + form_interactions_ukm_logger_->LogHiddenRepresentationalFieldSkipDecision( + *form_structure, *cached_field, skip); + if (skip) + continue; + } + + if (result.fields[i].is_autofilled && !cached_field->SameFieldAs(field) && + !is_refill) { + continue; + } + + if (field_group_type == NO_GROUP) + continue; + + if (is_refill && + !base::ContainsKey(filling_context->type_groups_originally_filled, + field_group_type)) { + continue; + } + + if (IsCreditCardExpirationType(cached_field->Type().GetStorableType()) && + static_cast(&data_model) + ->IsExpired(AutofillClock::Now())) { + continue; + } + + if (could_attempt_refill) + filling_context->type_groups_originally_filled.insert(field_group_type); + + bool should_notify = !is_credit_card && + (result.fields[i].SameFieldAs(field) || + result.fields[i].form_control_type == ""select-one"" || + result.fields[i].value.empty()); + + FillFieldWithValue(cached_field, data_model, &result.fields[i], + should_notify, cvc); + if (result.fields[i].is_autofilled) + result.fields[i].section = form_structure->field(i)->section; + + if (!cached_field->IsVisible() && result.fields[i].is_autofilled) { + AutofillMetrics::LogHiddenOrPresentationalSelectFieldsFilled(); + } + } + + autofilled_form_signatures_.push_front(form_structure->FormSignatureAsStr()); + if (autofilled_form_signatures_.size() > kMaxRecentFormSignaturesToRemember) + autofilled_form_signatures_.pop_back(); + + if (action == AutofillDriver::FORM_DATA_ACTION_FILL && !is_refill) + personal_data_->RecordUseOf(data_model); + + driver()->SendFormDataToRenderer(query_id, action, result); +} +",0,"void AutofillManager::FillOrPreviewDataModelForm( + AutofillDriver::RendererFormDataAction action, + int query_id, + const FormData& form, + const FormFieldData& field, + const AutofillDataModel& data_model, + bool is_credit_card, + const base::string16& cvc, + FormStructure* form_structure, + AutofillField* autofill_field, + bool is_refill) { + DCHECK(form_structure); + DCHECK(autofill_field); + + FormData result = form; + + if (base::FeatureList::IsEnabled(kAutofillRationalizeFieldTypePredictions)) { + form_structure->RationalizePhoneNumbersInSection(autofill_field->section); + } + + DCHECK_EQ(form_structure->field_count(), form.fields.size()); + + FillingContext* filling_context = nullptr; + auto itr = + filling_contexts_map_.find(form_structure->GetIdentifierForRefill()); + if (itr != filling_contexts_map_.end()) + filling_context = itr->second.get(); + bool could_attempt_refill = + base::FeatureList::IsEnabled(features::kAutofillDynamicForms) && + filling_context != nullptr && !filling_context->attempted_refill && + !is_refill && !is_credit_card; + + for (size_t i = 0; i < form_structure->field_count(); ++i) { + if (form_structure->field(i)->section != autofill_field->section) + continue; + + if (form_structure->field(i)->only_fill_when_focused() && + !form_structure->field(i)->SameFieldAs(field)) { + continue; + } + + DCHECK(form_structure->field(i)->SameFieldAs(result.fields[i])); + + AutofillField* cached_field = form_structure->field(i); + FieldTypeGroup field_group_type = cached_field->Type().group(); + + if (!cached_field->IsVisible()) { + bool skip = result.fields[i].form_control_type != ""select-one""; + form_interactions_ukm_logger_->LogHiddenRepresentationalFieldSkipDecision( + *form_structure, *cached_field, skip); + if (skip) + continue; + } + + if (result.fields[i].is_autofilled && !cached_field->SameFieldAs(field) && + !is_refill) { + continue; + } + + if (field_group_type == NO_GROUP) + continue; + + if (is_refill && + !base::ContainsKey(filling_context->type_groups_originally_filled, + field_group_type)) { + continue; + } + + if (IsCreditCardExpirationType(cached_field->Type().GetStorableType()) && + static_cast(&data_model) + ->IsExpired(AutofillClock::Now())) { + continue; + } + + if (could_attempt_refill) + filling_context->type_groups_originally_filled.insert(field_group_type); + + bool should_notify = !is_credit_card && + (result.fields[i].SameFieldAs(field) || + result.fields[i].form_control_type == ""select-one"" || + result.fields[i].value.empty()); + + FillFieldWithValue(cached_field, data_model, &result.fields[i], + should_notify, cvc); + if (result.fields[i].is_autofilled) + result.fields[i].section = form_structure->field(i)->section; + + if (!cached_field->IsVisible() && result.fields[i].is_autofilled) { + AutofillMetrics::LogHiddenOrPresentationalSelectFieldsFilled(); + } + } + + autofilled_form_signatures_.push_front(form_structure->FormSignatureAsStr()); + if (autofilled_form_signatures_.size() > kMaxRecentFormSignaturesToRemember) + autofilled_form_signatures_.pop_back(); + + if (action == AutofillDriver::FORM_DATA_ACTION_FILL && !is_refill) + personal_data_->RecordUseOf(data_model); + + driver()->SendFormDataToRenderer(query_id, action, result); +} +","@@ -96,23 +96,6 @@ const size_t kWaitTimeForDynamicFormsMs = 200; + // The time limit, in ms, between a fill and when a refill can happen. + const int kLimitBeforeRefillMs = 1000; + +-// Precondition: |form_structure| and |form| should correspond to the same +-// logical form. Returns true if any field in the given |section| within |form| +-// is auto-filled. +-bool SectionHasAutofilledField(const FormStructure& form_structure, +- const FormData& form, +- const std::string& section) { +- DCHECK_EQ(form_structure.field_count(), form.fields.size()); +- for (size_t i = 0; i < form_structure.field_count(); ++i) { +- if (form_structure.field(i)->section == section && +- form.fields[i].is_autofilled) { +- return true; +- } +- } +- +- return false; +-} +- + // Returns the credit card field |value| trimmed from whitespace and with stop + // characters removed. + base::string16 SanitizeCreditCardFieldValue(const base::string16& value) { +@@ -562,8 +545,7 @@ void AutofillManager::OnQueryFormFieldAutofillImpl( + // suggestions available. + // TODO(mathp): Differentiate between number of suggestions available + // (current metric) and number shown to the user. +- if (!has_logged_address_suggestions_count_ && +- !context.section_has_autofilled_field) { ++ if (!has_logged_address_suggestions_count_) { + AutofillMetrics::LogAddressSuggestionsCount(suggestions.size()); + has_logged_address_suggestions_count_ = true; + } +@@ -2079,27 +2061,6 @@ void AutofillManager::GetAvailableSuggestions( + warning_suggestion.frontend_id = + POPUP_ITEM_ID_INSECURE_CONTEXT_PAYMENT_DISABLED_MESSAGE; + suggestions->assign(1, warning_suggestion); +- } else { +- context->section_has_autofilled_field = SectionHasAutofilledField( +- *context->form_structure, form, context->focused_field->section); +- if (context->section_has_autofilled_field) { +- // If the relevant section has auto-filled fields and the renderer is +- // querying for suggestions, then for some fields, the user is editing +- // the value of a field. In this case, mimic autocomplete: don't +- // display labels or icons, as that information is redundant. +- // Moreover, filter out duplicate suggestions. +- std::set seen_values; +- for (auto iter = suggestions->begin(); iter != suggestions->end();) { +- if (!seen_values.insert(iter->value).second) { +- // If we've seen this suggestion value before, remove it. +- iter = suggestions->erase(iter); +- } else { +- iter->label.clear(); +- iter->icon.clear(); +- ++iter; +- } +- } +- } + } + } + ",829,1160,2048 +18622,"bool ResourceLoader::WillFollowRedirect( + const WebURL& new_url, + const WebURL& new_site_for_cookies, + const WebString& new_referrer, + WebReferrerPolicy new_referrer_policy, + const WebString& new_method, + const WebURLResponse& passed_redirect_response, + bool& report_raw_headers) { + DCHECK(!passed_redirect_response.IsNull()); + + if (is_cache_aware_loading_activated_) { + HandleError( + ResourceError::CacheMissError(resource_->LastResourceRequest().Url())); + return false; + } + + const ResourceRequest& last_request = resource_->LastResourceRequest(); + ResourceRequest new_request(new_url); + new_request.SetSiteForCookies(new_site_for_cookies); + new_request.SetDownloadToFile(last_request.DownloadToFile()); + new_request.SetUseStreamOnResponse(last_request.UseStreamOnResponse()); + new_request.SetRequestContext(last_request.GetRequestContext()); + new_request.SetFrameType(last_request.GetFrameType()); + new_request.SetServiceWorkerMode( + passed_redirect_response.WasFetchedViaServiceWorker() + ? WebURLRequest::ServiceWorkerMode::kAll + : WebURLRequest::ServiceWorkerMode::kNone); + new_request.SetShouldResetAppCache(last_request.ShouldResetAppCache()); + new_request.SetFetchRequestMode(last_request.GetFetchRequestMode()); + new_request.SetFetchCredentialsMode(last_request.GetFetchCredentialsMode()); + new_request.SetKeepalive(last_request.GetKeepalive()); + String referrer = + new_referrer.IsEmpty() ? Referrer::NoReferrer() : String(new_referrer); + new_request.SetHTTPReferrer( + Referrer(referrer, static_cast(new_referrer_policy))); + new_request.SetPriority(last_request.Priority()); + new_request.SetHTTPMethod(new_method); + if (new_request.HttpMethod() == last_request.HttpMethod()) + new_request.SetHTTPBody(last_request.HttpBody()); + new_request.SetCheckForBrowserSideNavigation( + last_request.CheckForBrowserSideNavigation()); + + Resource::Type resource_type = resource_->GetType(); + + const ResourceRequest& initial_request = resource_->GetResourceRequest(); + WebURLRequest::RequestContext request_context = + initial_request.GetRequestContext(); + WebURLRequest::FrameType frame_type = initial_request.GetFrameType(); + WebURLRequest::FetchRequestMode fetch_request_mode = + initial_request.GetFetchRequestMode(); + WebURLRequest::FetchCredentialsMode fetch_credentials_mode = + initial_request.GetFetchCredentialsMode(); + + const ResourceLoaderOptions& options = resource_->Options(); + + const ResourceResponse& redirect_response( + passed_redirect_response.ToResourceResponse()); + + new_request.SetRedirectStatus( + ResourceRequest::RedirectStatus::kFollowedRedirect); + + if (!IsManualRedirectFetchRequest(initial_request)) { + bool unused_preload = resource_->IsUnusedPreload(); + + SecurityViolationReportingPolicy reporting_policy = + unused_preload ? SecurityViolationReportingPolicy::kSuppressReporting + : SecurityViolationReportingPolicy::kReport; + + Context().CheckCSPForRequest( + request_context, new_url, options, reporting_policy, + ResourceRequest::RedirectStatus::kFollowedRedirect); + + ResourceRequestBlockedReason blocked_reason = Context().CanRequest( + resource_type, new_request, new_url, options, reporting_policy, + FetchParameters::kUseDefaultOriginRestrictionForType, + ResourceRequest::RedirectStatus::kFollowedRedirect); + if (blocked_reason != ResourceRequestBlockedReason::kNone) { + CancelForRedirectAccessCheckError(new_url, blocked_reason); + return false; + } + + if (options.cors_handling_by_resource_fetcher == + kEnableCORSHandlingByResourceFetcher && + fetch_request_mode == WebURLRequest::kFetchRequestModeCORS) { + RefPtr source_origin = options.security_origin; + if (!source_origin.get()) + source_origin = Context().GetSecurityOrigin(); + WebSecurityOrigin source_web_origin(source_origin.get()); + WrappedResourceRequest new_request_wrapper(new_request); + WebString cors_error_msg; + if (!WebCORS::HandleRedirect( + source_web_origin, new_request_wrapper, redirect_response.Url(), + redirect_response.HttpStatusCode(), + redirect_response.HttpHeaderFields(), fetch_credentials_mode, + resource_->MutableOptions(), cors_error_msg)) { + resource_->SetCORSStatus(CORSStatus::kFailed); + + if (!unused_preload) { + Context().AddErrorConsoleMessage(cors_error_msg, + FetchContext::kJSSource); + } + + CancelForRedirectAccessCheckError(new_url, + ResourceRequestBlockedReason::kOther); + return false; + } + + source_origin = source_web_origin; + } + if (resource_type == Resource::kImage && + fetcher_->ShouldDeferImageLoad(new_url)) { + CancelForRedirectAccessCheckError(new_url, + ResourceRequestBlockedReason::kOther); + return false; + } + } + + bool cross_origin = + !SecurityOrigin::AreSameSchemeHostPort(redirect_response.Url(), new_url); + fetcher_->RecordResourceTimingOnRedirect(resource_.Get(), redirect_response, + cross_origin); + + if (options.cors_handling_by_resource_fetcher == + kEnableCORSHandlingByResourceFetcher && + fetch_request_mode == WebURLRequest::kFetchRequestModeCORS) { + bool allow_stored_credentials = false; + switch (fetch_credentials_mode) { + case WebURLRequest::kFetchCredentialsModeOmit: + break; + case WebURLRequest::kFetchCredentialsModeSameOrigin: + allow_stored_credentials = !options.cors_flag; + break; + case WebURLRequest::kFetchCredentialsModeInclude: + case WebURLRequest::kFetchCredentialsModePassword: + allow_stored_credentials = true; + break; + } + new_request.SetAllowStoredCredentials(allow_stored_credentials); + } + + + Context().PrepareRequest(new_request, + FetchContext::RedirectType::kForRedirect); + Context().DispatchWillSendRequest(resource_->Identifier(), new_request, + redirect_response, options.initiator_info); + + DCHECK(KURL(new_site_for_cookies) == new_request.SiteForCookies()); + + DCHECK_EQ(new_request.GetRequestContext(), request_context); + DCHECK_EQ(new_request.GetFrameType(), frame_type); + DCHECK_EQ(new_request.GetFetchRequestMode(), fetch_request_mode); + DCHECK_EQ(new_request.GetFetchCredentialsMode(), fetch_credentials_mode); + + if (new_request.Url() != KURL(new_url)) { + CancelForRedirectAccessCheckError(new_request.Url(), + ResourceRequestBlockedReason::kOther); + return false; + } + + if (!resource_->WillFollowRedirect(new_request, redirect_response)) { + CancelForRedirectAccessCheckError(new_request.Url(), + ResourceRequestBlockedReason::kOther); + return false; + } + + report_raw_headers = new_request.ReportRawHeaders(); + + return true; +} +",1,"bool ResourceLoader::WillFollowRedirect( + const WebURL& new_url, + const WebURL& new_site_for_cookies, + const WebString& new_referrer, + WebReferrerPolicy new_referrer_policy, + const WebString& new_method, + const WebURLResponse& passed_redirect_response, + bool& report_raw_headers) { + DCHECK(!passed_redirect_response.IsNull()); + + if (is_cache_aware_loading_activated_) { + HandleError( + ResourceError::CacheMissError(resource_->LastResourceRequest().Url())); + return false; + } + + const ResourceRequest& last_request = resource_->LastResourceRequest(); + ResourceRequest new_request(new_url); + new_request.SetSiteForCookies(new_site_for_cookies); + new_request.SetDownloadToFile(last_request.DownloadToFile()); + new_request.SetUseStreamOnResponse(last_request.UseStreamOnResponse()); + new_request.SetRequestContext(last_request.GetRequestContext()); + new_request.SetFrameType(last_request.GetFrameType()); + new_request.SetServiceWorkerMode( + passed_redirect_response.WasFetchedViaServiceWorker() + ? WebURLRequest::ServiceWorkerMode::kAll + : WebURLRequest::ServiceWorkerMode::kNone); + new_request.SetShouldResetAppCache(last_request.ShouldResetAppCache()); + new_request.SetFetchRequestMode(last_request.GetFetchRequestMode()); + new_request.SetFetchCredentialsMode(last_request.GetFetchCredentialsMode()); + new_request.SetKeepalive(last_request.GetKeepalive()); + String referrer = + new_referrer.IsEmpty() ? Referrer::NoReferrer() : String(new_referrer); + new_request.SetHTTPReferrer( + Referrer(referrer, static_cast(new_referrer_policy))); + new_request.SetPriority(last_request.Priority()); + new_request.SetHTTPMethod(new_method); + if (new_request.HttpMethod() == last_request.HttpMethod()) + new_request.SetHTTPBody(last_request.HttpBody()); + new_request.SetCheckForBrowserSideNavigation( + last_request.CheckForBrowserSideNavigation()); + + Resource::Type resource_type = resource_->GetType(); + + const ResourceRequest& initial_request = resource_->GetResourceRequest(); + WebURLRequest::RequestContext request_context = + initial_request.GetRequestContext(); + WebURLRequest::FrameType frame_type = initial_request.GetFrameType(); + WebURLRequest::FetchRequestMode fetch_request_mode = + initial_request.GetFetchRequestMode(); + WebURLRequest::FetchCredentialsMode fetch_credentials_mode = + initial_request.GetFetchCredentialsMode(); + + const ResourceLoaderOptions& options = resource_->Options(); + + const ResourceResponse& redirect_response( + passed_redirect_response.ToResourceResponse()); + + new_request.SetRedirectStatus( + ResourceRequest::RedirectStatus::kFollowedRedirect); + + if (!IsManualRedirectFetchRequest(initial_request)) { + bool unused_preload = resource_->IsUnusedPreload(); + + SecurityViolationReportingPolicy reporting_policy = + unused_preload ? SecurityViolationReportingPolicy::kSuppressReporting + : SecurityViolationReportingPolicy::kReport; + + Context().CheckCSPForRequest( + request_context, new_url, options, reporting_policy, + ResourceRequest::RedirectStatus::kFollowedRedirect); + + ResourceRequestBlockedReason blocked_reason = Context().CanRequest( + resource_type, new_request, new_url, options, reporting_policy, + FetchParameters::kUseDefaultOriginRestrictionForType, + ResourceRequest::RedirectStatus::kFollowedRedirect); + if (blocked_reason != ResourceRequestBlockedReason::kNone) { + CancelForRedirectAccessCheckError(new_url, blocked_reason); + return false; + } + + if (options.cors_handling_by_resource_fetcher == + kEnableCORSHandlingByResourceFetcher && + fetch_request_mode == WebURLRequest::kFetchRequestModeCORS) { + RefPtr source_origin = options.security_origin; + if (!source_origin.get()) + source_origin = Context().GetSecurityOrigin(); + WebSecurityOrigin source_web_origin(source_origin.get()); + WrappedResourceRequest new_request_wrapper(new_request); + WebString cors_error_msg; + if (!WebCORS::HandleRedirect( + source_web_origin, new_request_wrapper, redirect_response.Url(), + redirect_response.HttpStatusCode(), + redirect_response.HttpHeaderFields(), fetch_credentials_mode, + resource_->MutableOptions(), cors_error_msg)) { + resource_->SetCORSStatus(CORSStatus::kFailed); + + if (!unused_preload) { + Context().AddErrorConsoleMessage(cors_error_msg, + FetchContext::kJSSource); + } + + CancelForRedirectAccessCheckError(new_url, + ResourceRequestBlockedReason::kOther); + return false; + } + + source_origin = source_web_origin; + } + if (resource_type == Resource::kImage && + fetcher_->ShouldDeferImageLoad(new_url)) { + CancelForRedirectAccessCheckError(new_url, + ResourceRequestBlockedReason::kOther); + return false; + } + } + + bool cross_origin = + !SecurityOrigin::AreSameSchemeHostPort(redirect_response.Url(), new_url); + fetcher_->RecordResourceTimingOnRedirect(resource_.Get(), redirect_response, + cross_origin); + + if (options.cors_handling_by_resource_fetcher == + kEnableCORSHandlingByResourceFetcher && + fetch_request_mode == WebURLRequest::kFetchRequestModeCORS) { + bool allow_stored_credentials = false; + switch (fetch_credentials_mode) { + case WebURLRequest::kFetchCredentialsModeOmit: + break; + case WebURLRequest::kFetchCredentialsModeSameOrigin: + allow_stored_credentials = !options.cors_flag; + break; + case WebURLRequest::kFetchCredentialsModeInclude: + case WebURLRequest::kFetchCredentialsModePassword: + allow_stored_credentials = true; + break; + } + new_request.SetAllowStoredCredentials(allow_stored_credentials); + } + + + Context().PrepareRequest(new_request, + FetchContext::RedirectType::kForRedirect); + Context().DispatchWillSendRequest(resource_->Identifier(), new_request, + redirect_response, resource_->GetType(), + options.initiator_info); + + DCHECK(KURL(new_site_for_cookies) == new_request.SiteForCookies()); + + DCHECK_EQ(new_request.GetRequestContext(), request_context); + DCHECK_EQ(new_request.GetFrameType(), frame_type); + DCHECK_EQ(new_request.GetFetchRequestMode(), fetch_request_mode); + DCHECK_EQ(new_request.GetFetchCredentialsMode(), fetch_credentials_mode); + + if (new_request.Url() != KURL(new_url)) { + CancelForRedirectAccessCheckError(new_request.Url(), + ResourceRequestBlockedReason::kOther); + return false; + } + + if (!resource_->WillFollowRedirect(new_request, redirect_response)) { + CancelForRedirectAccessCheckError(new_request.Url(), + ResourceRequestBlockedReason::kOther); + return false; + } + + report_raw_headers = new_request.ReportRawHeaders(); + + return true; +} +","@@ -364,7 +364,8 @@ bool ResourceLoader::WillFollowRedirect( + Context().PrepareRequest(new_request, + FetchContext::RedirectType::kForRedirect); + Context().DispatchWillSendRequest(resource_->Identifier(), new_request, +- redirect_response, options.initiator_info); ++ redirect_response, resource_->GetType(), ++ options.initiator_info); + + // First-party cookie logic moved from DocumentLoader in Blink to + // net::URLRequest in the browser. Assert that Blink didn't try to change it",1398,1729,2048 +9015,"static void megasas_detach_one(struct pci_dev *pdev) +{ + int i; + struct Scsi_Host *host; + struct megasas_instance *instance; + struct fusion_context *fusion; + u32 pd_seq_map_sz; + + instance = pci_get_drvdata(pdev); + host = instance->host; + fusion = instance->ctrl_context; + + /* Shutdown SR-IOV heartbeat timer */ + if (instance->requestorId && !instance->skip_heartbeat_timer_del) + del_timer_sync(&instance->sriov_heartbeat_timer); + + /* Stop the FW fault detection watchdog */ + if (instance->adapter_type != MFI_SERIES) + megasas_fusion_stop_watchdog(instance); + + if (instance->fw_crash_state != UNAVAILABLE) + megasas_free_host_crash_buffer(instance); + scsi_remove_host(instance->host); + instance->unload = 1; + + if (megasas_wait_for_adapter_operational(instance)) + goto skip_firing_dcmds; + + megasas_flush_cache(instance); + megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN); + +skip_firing_dcmds: + /* cancel the delayed work if this work still in queue*/ + if (instance->ev != NULL) { + struct megasas_aen_event *ev = instance->ev; + cancel_delayed_work_sync(&ev->hotplug_work); + instance->ev = NULL; + } + + /* cancel all wait events */ + wake_up_all(&instance->int_cmd_wait_q); + + tasklet_kill(&instance->isr_tasklet); + + /* + * Take the instance off the instance array. Note that we will not + * decrement the max_index. We let this array be sparse array + */ + for (i = 0; i < megasas_mgmt_info.max_index; i++) { + if (megasas_mgmt_info.instance[i] == instance) { + megasas_mgmt_info.count--; + megasas_mgmt_info.instance[i] = NULL; + + break; + } + } + + instance->instancet->disable_intr(instance); + + megasas_destroy_irqs(instance); + + if (instance->msix_vectors) + pci_free_irq_vectors(instance->pdev); + + if (instance->adapter_type >= VENTURA_SERIES) { + for (i = 0; i < MAX_LOGICAL_DRIVES_EXT; ++i) + kfree(fusion->stream_detect_by_ld[i]); + kfree(fusion->stream_detect_by_ld); + fusion->stream_detect_by_ld = NULL; + } + + + if (instance->adapter_type != MFI_SERIES) { + megasas_release_fusion(instance); + pd_seq_map_sz = sizeof(struct MR_PD_CFG_SEQ_NUM_SYNC) + + (sizeof(struct MR_PD_CFG_SEQ) * + (MAX_PHYSICAL_DEVICES - 1)); + for (i = 0; i < 2 ; i++) { + if (fusion->ld_map[i]) + dma_free_coherent(&instance->pdev->dev, + fusion->max_map_sz, + fusion->ld_map[i], + fusion->ld_map_phys[i]); + if (fusion->ld_drv_map[i]) { + if (is_vmalloc_addr(fusion->ld_drv_map[i])) + vfree(fusion->ld_drv_map[i]); + else + free_pages((ulong)fusion->ld_drv_map[i], + fusion->drv_map_pages); + } + + if (fusion->pd_seq_sync[i]) + dma_free_coherent(&instance->pdev->dev, + pd_seq_map_sz, + fusion->pd_seq_sync[i], + fusion->pd_seq_phys[i]); + } + } else { + megasas_release_mfi(instance); + } + + if (instance->vf_affiliation) + dma_free_coherent(&pdev->dev, (MAX_LOGICAL_DRIVES + 1) * + sizeof(struct MR_LD_VF_AFFILIATION), + instance->vf_affiliation, + instance->vf_affiliation_h); + + if (instance->vf_affiliation_111) + dma_free_coherent(&pdev->dev, + sizeof(struct MR_LD_VF_AFFILIATION_111), + instance->vf_affiliation_111, + instance->vf_affiliation_111_h); + + if (instance->hb_host_mem) + dma_free_coherent(&pdev->dev, sizeof(struct MR_CTRL_HB_HOST_MEM), + instance->hb_host_mem, + instance->hb_host_mem_h); + + megasas_free_ctrl_dma_buffers(instance); + + megasas_free_ctrl_mem(instance); + + scsi_host_put(host); + + pci_disable_device(pdev); +} +",0,"static void megasas_detach_one(struct pci_dev *pdev) +{ + int i; + struct Scsi_Host *host; + struct megasas_instance *instance; + struct fusion_context *fusion; + u32 pd_seq_map_sz; + + instance = pci_get_drvdata(pdev); + host = instance->host; + fusion = instance->ctrl_context; + + /* Shutdown SR-IOV heartbeat timer */ + if (instance->requestorId && !instance->skip_heartbeat_timer_del) + del_timer_sync(&instance->sriov_heartbeat_timer); + + /* Stop the FW fault detection watchdog */ + if (instance->adapter_type != MFI_SERIES) + megasas_fusion_stop_watchdog(instance); + + if (instance->fw_crash_state != UNAVAILABLE) + megasas_free_host_crash_buffer(instance); + scsi_remove_host(instance->host); + instance->unload = 1; + + if (megasas_wait_for_adapter_operational(instance)) + goto skip_firing_dcmds; + + megasas_flush_cache(instance); + megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN); + +skip_firing_dcmds: + /* cancel the delayed work if this work still in queue*/ + if (instance->ev != NULL) { + struct megasas_aen_event *ev = instance->ev; + cancel_delayed_work_sync(&ev->hotplug_work); + instance->ev = NULL; + } + + /* cancel all wait events */ + wake_up_all(&instance->int_cmd_wait_q); + + tasklet_kill(&instance->isr_tasklet); + + /* + * Take the instance off the instance array. Note that we will not + * decrement the max_index. We let this array be sparse array + */ + for (i = 0; i < megasas_mgmt_info.max_index; i++) { + if (megasas_mgmt_info.instance[i] == instance) { + megasas_mgmt_info.count--; + megasas_mgmt_info.instance[i] = NULL; + + break; + } + } + + instance->instancet->disable_intr(instance); + + megasas_destroy_irqs(instance); + + if (instance->msix_vectors) + pci_free_irq_vectors(instance->pdev); + + if (instance->adapter_type >= VENTURA_SERIES) { + for (i = 0; i < MAX_LOGICAL_DRIVES_EXT; ++i) + kfree(fusion->stream_detect_by_ld[i]); + kfree(fusion->stream_detect_by_ld); + fusion->stream_detect_by_ld = NULL; + } + + + if (instance->adapter_type != MFI_SERIES) { + megasas_release_fusion(instance); + pd_seq_map_sz = sizeof(struct MR_PD_CFG_SEQ_NUM_SYNC) + + (sizeof(struct MR_PD_CFG_SEQ) * + (MAX_PHYSICAL_DEVICES - 1)); + for (i = 0; i < 2 ; i++) { + if (fusion->ld_map[i]) + dma_free_coherent(&instance->pdev->dev, + fusion->max_map_sz, + fusion->ld_map[i], + fusion->ld_map_phys[i]); + if (fusion->ld_drv_map[i]) { + if (is_vmalloc_addr(fusion->ld_drv_map[i])) + vfree(fusion->ld_drv_map[i]); + else + free_pages((ulong)fusion->ld_drv_map[i], + fusion->drv_map_pages); + } + + if (fusion->pd_seq_sync[i]) + dma_free_coherent(&instance->pdev->dev, + pd_seq_map_sz, + fusion->pd_seq_sync[i], + fusion->pd_seq_phys[i]); + } + } else { + megasas_release_mfi(instance); + } + + if (instance->vf_affiliation) + dma_free_coherent(&pdev->dev, (MAX_LOGICAL_DRIVES + 1) * + sizeof(struct MR_LD_VF_AFFILIATION), + instance->vf_affiliation, + instance->vf_affiliation_h); + + if (instance->vf_affiliation_111) + dma_free_coherent(&pdev->dev, + sizeof(struct MR_LD_VF_AFFILIATION_111), + instance->vf_affiliation_111, + instance->vf_affiliation_111_h); + + if (instance->hb_host_mem) + dma_free_coherent(&pdev->dev, sizeof(struct MR_CTRL_HB_HOST_MEM), + instance->hb_host_mem, + instance->hb_host_mem_h); + + megasas_free_ctrl_dma_buffers(instance); + + megasas_free_ctrl_mem(instance); + + scsi_host_put(host); + + pci_disable_device(pdev); +} +","@@ -4188,6 +4188,7 @@ int megasas_alloc_cmds(struct megasas_instance *instance) + if (megasas_create_frame_pool(instance)) { + dev_printk(KERN_DEBUG, &instance->pdev->dev, ""Error creating frame DMA pool\n""); + megasas_free_cmds(instance); ++ return -ENOMEM; + } + + return 0;",955,1286,2048 +1043," main( int argc, + char* argv[] ) + { + grEvent event; + + + parse_cmdline( &argc, &argv ); + +#if FREETYPE_MAJOR == 2 && FREETYPE_MINOR == 0 && FREETYPE_PATCH <= 8 + if ( status.debug ) + { +#ifdef FT_DEBUG_LEVEL_TRACE + FT_SetTraceLevel( trace_any, (FT_Byte)status.trace_level ); +#else + status.trace_level = 0; +#endif + } +#elif 0 + /* `setenv' and `putenv' is not ANSI and I don't want to mess */ + /* with this portability issue right now... */ + if ( status.debug ) + { + char temp[32]; + + sprintf( temp, ""any=%d"", status.trace_level ); + setenv( ""FT2_DEBUG"", temp ); + } +#endif + + /* Initialize engine */ + handle = FTDemo_New( status.encoding ); + + FT_Library_SetLcdFilter( handle->library, FT_LCD_FILTER_DEFAULT ); + + if ( status.preload ) + FTDemo_Set_Preload( handle, 1 ); + + for ( ; argc > 0; argc--, argv++ ) + FTDemo_Install_Font( handle, argv[0] ); + + if ( handle->num_fonts == 0 ) + Fatal( ""could not find/open any font file"" ); + + display = FTDemo_Display_New( gr_pixel_mode_rgb24 ); + if ( !display ) + Fatal( ""could not allocate display surface"" ); + + memset( display->fore_color.chroma, 0, 4 ); + memset( display->back_color.chroma, 0xff, 4 ); + grSetTitle( display->surface, + ""FreeType Glyph Viewer - press F1 for help"" ); + + status.Fail = 0; + + event_font_change( 0 ); + + if ( status.lcd_mode >= 0 ) + handle->lcd_mode = status.lcd_mode; + + FTDemo_Update_Current_Flags( handle ); + + for ( ;; ) + { + FTDemo_Display_Clear( display ); + + switch ( status.render_mode ) + { + case RENDER_MODE_ALL: + error = Render_All( handle->current_font->num_indices, + status.Num ); + break; + + case RENDER_MODE_EMBOLDEN: + error = Render_Embolden( handle->current_font->num_indices, + status.Num ); + break; + + case RENDER_MODE_SLANTED: + error = Render_Slanted( handle->current_font->num_indices, + status.Num ); + break; + + case RENDER_MODE_STROKE: + error = Render_Stroke( handle->current_font->num_indices, + status.Num ); + break; + + case RENDER_MODE_TEXT: + error = Render_Text( -1, status.Num ); + break; + + case RENDER_MODE_WATERFALL: + error = Render_Waterfall( status.ptsize ); + break; + } + + write_header( error ); + +#if FREETYPE_MAJOR == 2 && FREETYPE_MINOR < 2 + if ( status.dump_cache_stats ) + { + /* dump simple cache manager statistics */ + fprintf( stderr, ""cache manager [ nodes, bytes, average ] = "" + "" [ %d, %ld, %f ]\n"", + handle->cache_manager->num_nodes, + handle->cache_manager->cur_weight, + handle->cache_manager->num_nodes > 0 + ? handle->cache_manager->cur_weight * 1.0 / + handle->cache_manager->num_nodes + : 0.0 ); + } +#endif + + status.header = 0; + grListenSurface( display->surface, 0, &event ); + if ( Process_Event( &event ) ) + break; + } + + printf( ""Execution completed successfully.\n"" ); + printf( ""Fails = %d\n"", status.Fail ); + + FTDemo_Display_Done( display ); + FTDemo_Done( handle ); + exit( 0 ); /* for safety reasons */ + + return 0; /* never reached */ + } +",0," main( int argc, + char* argv[] ) + { + grEvent event; + + + parse_cmdline( &argc, &argv ); + +#if FREETYPE_MAJOR == 2 && FREETYPE_MINOR == 0 && FREETYPE_PATCH <= 8 + if ( status.debug ) + { +#ifdef FT_DEBUG_LEVEL_TRACE + FT_SetTraceLevel( trace_any, (FT_Byte)status.trace_level ); +#else + status.trace_level = 0; +#endif + } +#elif 0 + /* `setenv' and `putenv' is not ANSI and I don't want to mess */ + /* with this portability issue right now... */ + if ( status.debug ) + { + char temp[32]; + + sprintf( temp, ""any=%d"", status.trace_level ); + setenv( ""FT2_DEBUG"", temp ); + } +#endif + + /* Initialize engine */ + handle = FTDemo_New( status.encoding ); + + FT_Library_SetLcdFilter( handle->library, FT_LCD_FILTER_DEFAULT ); + + if ( status.preload ) + FTDemo_Set_Preload( handle, 1 ); + + for ( ; argc > 0; argc--, argv++ ) + FTDemo_Install_Font( handle, argv[0] ); + + if ( handle->num_fonts == 0 ) + Fatal( ""could not find/open any font file"" ); + + display = FTDemo_Display_New( gr_pixel_mode_rgb24 ); + if ( !display ) + Fatal( ""could not allocate display surface"" ); + + memset( display->fore_color.chroma, 0, 4 ); + memset( display->back_color.chroma, 0xff, 4 ); + grSetTitle( display->surface, + ""FreeType Glyph Viewer - press F1 for help"" ); + + status.Fail = 0; + + event_font_change( 0 ); + + if ( status.lcd_mode >= 0 ) + handle->lcd_mode = status.lcd_mode; + + FTDemo_Update_Current_Flags( handle ); + + for ( ;; ) + { + FTDemo_Display_Clear( display ); + + switch ( status.render_mode ) + { + case RENDER_MODE_ALL: + error = Render_All( handle->current_font->num_indices, + status.Num ); + break; + + case RENDER_MODE_EMBOLDEN: + error = Render_Embolden( handle->current_font->num_indices, + status.Num ); + break; + + case RENDER_MODE_SLANTED: + error = Render_Slanted( handle->current_font->num_indices, + status.Num ); + break; + + case RENDER_MODE_STROKE: + error = Render_Stroke( handle->current_font->num_indices, + status.Num ); + break; + + case RENDER_MODE_TEXT: + error = Render_Text( -1, status.Num ); + break; + + case RENDER_MODE_WATERFALL: + error = Render_Waterfall( status.ptsize ); + break; + } + + write_header( error ); + +#if FREETYPE_MAJOR == 2 && FREETYPE_MINOR < 2 + if ( status.dump_cache_stats ) + { + /* dump simple cache manager statistics */ + fprintf( stderr, ""cache manager [ nodes, bytes, average ] = "" + "" [ %d, %ld, %f ]\n"", + handle->cache_manager->num_nodes, + handle->cache_manager->cur_weight, + handle->cache_manager->num_nodes > 0 + ? handle->cache_manager->cur_weight * 1.0 / + handle->cache_manager->num_nodes + : 0.0 ); + } +#endif + + status.header = 0; + grListenSurface( display->surface, 0, &event ); + if ( Process_Event( &event ) ) + break; + } + + printf( ""Execution completed successfully.\n"" ); + printf( ""Fails = %d\n"", status.Fail ); + + FTDemo_Display_Done( display ); + FTDemo_Done( handle ); + exit( 0 ); /* for safety reasons */ + + return 0; /* never reached */ + } +","@@ -1145,19 +1145,19 @@ + switch ( error_code ) + { + case FT_Err_Ok: +- sprintf( status.header_buffer, ""%s %s (file `%s')"", ++ sprintf( status.header_buffer, ""%.50s %.50s (file `%.100s')"", + face->family_name, face->style_name, basename ); + break; + case FT_Err_Invalid_Pixel_Size: +- sprintf( status.header_buffer, ""Invalid pixel size (file `%s')"", ++ sprintf( status.header_buffer, ""Invalid pixel size (file `%.100s')"", + basename ); + break; + case FT_Err_Invalid_PPem: +- sprintf( status.header_buffer, ""Invalid ppem value (file `%s')"", ++ sprintf( status.header_buffer, ""Invalid ppem value (file `%.100s')"", + basename ); + break; + default: +- sprintf( status.header_buffer, ""File `%s': error 0x%04x"", ++ sprintf( status.header_buffer, ""File `%.100s': error 0x%04x"", + basename, (FT_UShort)error_code ); + break; + }",864,1195,2048 +6485,"static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env) +{ + struct bpf_insn *insn = env->prog->insnsi; + int insn_cnt = env->prog->len; + int i, j, err; + + err = bpf_prog_calc_tag(env->prog); + if (err) + return err; + + for (i = 0; i < insn_cnt; i++, insn++) { + if (BPF_CLASS(insn->code) == BPF_LDX && + (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { + verbose(""BPF_LDX uses reserved fields\n""); + return -EINVAL; + } + + if (BPF_CLASS(insn->code) == BPF_STX && + ((BPF_MODE(insn->code) != BPF_MEM && + BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) { + verbose(""BPF_STX uses reserved fields\n""); + return -EINVAL; + } + + if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { + struct bpf_map *map; + struct fd f; + + if (i == insn_cnt - 1 || insn[1].code != 0 || + insn[1].dst_reg != 0 || insn[1].src_reg != 0 || + insn[1].off != 0) { + verbose(""invalid bpf_ld_imm64 insn\n""); + return -EINVAL; + } + + if (insn->src_reg == 0) + /* valid generic load 64-bit imm */ + goto next_insn; + + if (insn->src_reg != BPF_PSEUDO_MAP_FD) { + verbose(""unrecognized bpf_ld_imm64 insn\n""); + return -EINVAL; + } + + f = fdget(insn->imm); + map = __bpf_map_get(f); + if (IS_ERR(map)) { + verbose(""fd %d is not pointing to valid bpf_map\n"", + insn->imm); + return PTR_ERR(map); + } + + err = check_map_prog_compatibility(map, env->prog); + if (err) { + fdput(f); + return err; + } + + /* store map pointer inside BPF_LD_IMM64 instruction */ + insn[0].imm = (u32) (unsigned long) map; + insn[1].imm = ((u64) (unsigned long) map) >> 32; + + /* check whether we recorded this map already */ + for (j = 0; j < env->used_map_cnt; j++) + if (env->used_maps[j] == map) { + fdput(f); + goto next_insn; + } + + if (env->used_map_cnt >= MAX_USED_MAPS) { + fdput(f); + return -E2BIG; + } + + /* hold the map. If the program is rejected by verifier, + * the map will be released by release_maps() or it + * will be used by the valid program until it's unloaded + * and all maps are released in free_bpf_prog_info() + */ + map = bpf_map_inc(map, false); + if (IS_ERR(map)) { + fdput(f); + return PTR_ERR(map); + } + env->used_maps[env->used_map_cnt++] = map; + + fdput(f); +next_insn: + insn++; + i++; + } + } + + /* now all pseudo BPF_LD_IMM64 instructions load valid + * 'struct bpf_map *' into a register instead of user map_fd. + * These pointers will be used later by verifier to validate map access. + */ + return 0; +} +",0,"static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env) +{ + struct bpf_insn *insn = env->prog->insnsi; + int insn_cnt = env->prog->len; + int i, j, err; + + err = bpf_prog_calc_tag(env->prog); + if (err) + return err; + + for (i = 0; i < insn_cnt; i++, insn++) { + if (BPF_CLASS(insn->code) == BPF_LDX && + (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { + verbose(""BPF_LDX uses reserved fields\n""); + return -EINVAL; + } + + if (BPF_CLASS(insn->code) == BPF_STX && + ((BPF_MODE(insn->code) != BPF_MEM && + BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) { + verbose(""BPF_STX uses reserved fields\n""); + return -EINVAL; + } + + if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { + struct bpf_map *map; + struct fd f; + + if (i == insn_cnt - 1 || insn[1].code != 0 || + insn[1].dst_reg != 0 || insn[1].src_reg != 0 || + insn[1].off != 0) { + verbose(""invalid bpf_ld_imm64 insn\n""); + return -EINVAL; + } + + if (insn->src_reg == 0) + /* valid generic load 64-bit imm */ + goto next_insn; + + if (insn->src_reg != BPF_PSEUDO_MAP_FD) { + verbose(""unrecognized bpf_ld_imm64 insn\n""); + return -EINVAL; + } + + f = fdget(insn->imm); + map = __bpf_map_get(f); + if (IS_ERR(map)) { + verbose(""fd %d is not pointing to valid bpf_map\n"", + insn->imm); + return PTR_ERR(map); + } + + err = check_map_prog_compatibility(map, env->prog); + if (err) { + fdput(f); + return err; + } + + /* store map pointer inside BPF_LD_IMM64 instruction */ + insn[0].imm = (u32) (unsigned long) map; + insn[1].imm = ((u64) (unsigned long) map) >> 32; + + /* check whether we recorded this map already */ + for (j = 0; j < env->used_map_cnt; j++) + if (env->used_maps[j] == map) { + fdput(f); + goto next_insn; + } + + if (env->used_map_cnt >= MAX_USED_MAPS) { + fdput(f); + return -E2BIG; + } + + /* hold the map. If the program is rejected by verifier, + * the map will be released by release_maps() or it + * will be used by the valid program until it's unloaded + * and all maps are released in free_bpf_prog_info() + */ + map = bpf_map_inc(map, false); + if (IS_ERR(map)) { + fdput(f); + return PTR_ERR(map); + } + env->used_maps[env->used_map_cnt++] = map; + + fdput(f); +next_insn: + insn++; + i++; + } + } + + /* now all pseudo BPF_LD_IMM64 instructions load valid + * 'struct bpf_map *' into a register instead of user map_fd. + * These pointers will be used later by verifier to validate map access. + */ + return 0; +} +","@@ -298,7 +298,8 @@ static const char *const bpf_jmp_string[16] = { + [BPF_EXIT >> 4] = ""exit"", + }; + +-static void print_bpf_insn(struct bpf_insn *insn) ++static void print_bpf_insn(const struct bpf_verifier_env *env, ++ const struct bpf_insn *insn) + { + u8 class = BPF_CLASS(insn->code); + +@@ -362,9 +363,19 @@ static void print_bpf_insn(struct bpf_insn *insn) + insn->code, + bpf_ldst_string[BPF_SIZE(insn->code) >> 3], + insn->src_reg, insn->imm); +- } else if (BPF_MODE(insn->code) == BPF_IMM) { +- verbose(""(%02x) r%d = 0x%x\n"", +- insn->code, insn->dst_reg, insn->imm); ++ } else if (BPF_MODE(insn->code) == BPF_IMM && ++ BPF_SIZE(insn->code) == BPF_DW) { ++ /* At this point, we already made sure that the second ++ * part of the ldimm64 insn is accessible. ++ */ ++ u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; ++ bool map_ptr = insn->src_reg == BPF_PSEUDO_MAP_FD; ++ ++ if (map_ptr && !env->allow_ptr_leaks) ++ imm = 0; ++ ++ verbose(""(%02x) r%d = 0x%llx\n"", insn->code, ++ insn->dst_reg, (unsigned long long)imm); + } else { + verbose(""BUG_ld_%02x\n"", insn->code); + return; +@@ -2853,7 +2864,7 @@ static int do_check(struct bpf_verifier_env *env) + + if (log_level) { + verbose(""%d: "", insn_idx); +- print_bpf_insn(insn); ++ print_bpf_insn(env, insn); + } + + err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx);",821,1152,2048 +889,"X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer, + EVP_PKEY *skey, const EVP_MD *md, unsigned int flags) +{ + X509_CRL *crl = NULL; + int i; + STACK_OF(X509_REVOKED) *revs = NULL; + /* CRLs can't be delta already */ + if (base->base_crl_number || newer->base_crl_number) { + X509err(X509_F_X509_CRL_DIFF, X509_R_CRL_ALREADY_DELTA); + return NULL; + } + /* Base and new CRL must have a CRL number */ + if (!base->crl_number || !newer->crl_number) { + X509err(X509_F_X509_CRL_DIFF, X509_R_NO_CRL_NUMBER); + return NULL; + } + /* Issuer names must match */ + if (X509_NAME_cmp(X509_CRL_get_issuer(base), X509_CRL_get_issuer(newer))) { + X509err(X509_F_X509_CRL_DIFF, X509_R_ISSUER_MISMATCH); + return NULL; + } + /* AKID and IDP must match */ + if (!crl_extension_match(base, newer, NID_authority_key_identifier)) { + X509err(X509_F_X509_CRL_DIFF, X509_R_AKID_MISMATCH); + return NULL; + } + if (!crl_extension_match(base, newer, NID_issuing_distribution_point)) { + X509err(X509_F_X509_CRL_DIFF, X509_R_IDP_MISMATCH); + return NULL; + } + /* Newer CRL number must exceed full CRL number */ + if (ASN1_INTEGER_cmp(newer->crl_number, base->crl_number) <= 0) { + X509err(X509_F_X509_CRL_DIFF, X509_R_NEWER_CRL_NOT_NEWER); + return NULL; + } + /* CRLs must verify */ + if (skey && (X509_CRL_verify(base, skey) <= 0 || + X509_CRL_verify(newer, skey) <= 0)) { + X509err(X509_F_X509_CRL_DIFF, X509_R_CRL_VERIFY_FAILURE); + return NULL; + } + /* Create new CRL */ + crl = X509_CRL_new(); + if (!crl || !X509_CRL_set_version(crl, 1)) + goto memerr; + /* Set issuer name */ + if (!X509_CRL_set_issuer_name(crl, X509_CRL_get_issuer(newer))) + goto memerr; + + if (!X509_CRL_set_lastUpdate(crl, X509_CRL_get_lastUpdate(newer))) + goto memerr; + if (!X509_CRL_set_nextUpdate(crl, X509_CRL_get_nextUpdate(newer))) + goto memerr; + + /* Set base CRL number: must be critical */ + + if (!X509_CRL_add1_ext_i2d(crl, NID_delta_crl, base->crl_number, 1, 0)) + goto memerr; + + /* + * Copy extensions across from newest CRL to delta: this will set CRL + * number to correct value too. + */ + + for (i = 0; i < X509_CRL_get_ext_count(newer); i++) { + X509_EXTENSION *ext; + ext = X509_CRL_get_ext(newer, i); + if (!X509_CRL_add_ext(crl, ext, -1)) + goto memerr; + } + + /* Go through revoked entries, copying as needed */ + + revs = X509_CRL_get_REVOKED(newer); + + for (i = 0; i < sk_X509_REVOKED_num(revs); i++) { + X509_REVOKED *rvn, *rvtmp; + rvn = sk_X509_REVOKED_value(revs, i); + /* + * Add only if not also in base. TODO: need something cleverer here + * for some more complex CRLs covering multiple CAs. + */ + if (!X509_CRL_get0_by_serial(base, &rvtmp, rvn->serialNumber)) { + rvtmp = X509_REVOKED_dup(rvn); + if (!rvtmp) + goto memerr; + if (!X509_CRL_add0_revoked(crl, rvtmp)) { + X509_REVOKED_free(rvtmp); + goto memerr; + } + } + } + /* TODO: optionally prune deleted entries */ + + if (skey && md && !X509_CRL_sign(crl, skey, md)) + goto memerr; + + return crl; + + memerr: + X509err(X509_F_X509_CRL_DIFF, ERR_R_MALLOC_FAILURE); + if (crl) + X509_CRL_free(crl); + return NULL; +} +",0,"X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer, + EVP_PKEY *skey, const EVP_MD *md, unsigned int flags) +{ + X509_CRL *crl = NULL; + int i; + STACK_OF(X509_REVOKED) *revs = NULL; + /* CRLs can't be delta already */ + if (base->base_crl_number || newer->base_crl_number) { + X509err(X509_F_X509_CRL_DIFF, X509_R_CRL_ALREADY_DELTA); + return NULL; + } + /* Base and new CRL must have a CRL number */ + if (!base->crl_number || !newer->crl_number) { + X509err(X509_F_X509_CRL_DIFF, X509_R_NO_CRL_NUMBER); + return NULL; + } + /* Issuer names must match */ + if (X509_NAME_cmp(X509_CRL_get_issuer(base), X509_CRL_get_issuer(newer))) { + X509err(X509_F_X509_CRL_DIFF, X509_R_ISSUER_MISMATCH); + return NULL; + } + /* AKID and IDP must match */ + if (!crl_extension_match(base, newer, NID_authority_key_identifier)) { + X509err(X509_F_X509_CRL_DIFF, X509_R_AKID_MISMATCH); + return NULL; + } + if (!crl_extension_match(base, newer, NID_issuing_distribution_point)) { + X509err(X509_F_X509_CRL_DIFF, X509_R_IDP_MISMATCH); + return NULL; + } + /* Newer CRL number must exceed full CRL number */ + if (ASN1_INTEGER_cmp(newer->crl_number, base->crl_number) <= 0) { + X509err(X509_F_X509_CRL_DIFF, X509_R_NEWER_CRL_NOT_NEWER); + return NULL; + } + /* CRLs must verify */ + if (skey && (X509_CRL_verify(base, skey) <= 0 || + X509_CRL_verify(newer, skey) <= 0)) { + X509err(X509_F_X509_CRL_DIFF, X509_R_CRL_VERIFY_FAILURE); + return NULL; + } + /* Create new CRL */ + crl = X509_CRL_new(); + if (!crl || !X509_CRL_set_version(crl, 1)) + goto memerr; + /* Set issuer name */ + if (!X509_CRL_set_issuer_name(crl, X509_CRL_get_issuer(newer))) + goto memerr; + + if (!X509_CRL_set_lastUpdate(crl, X509_CRL_get_lastUpdate(newer))) + goto memerr; + if (!X509_CRL_set_nextUpdate(crl, X509_CRL_get_nextUpdate(newer))) + goto memerr; + + /* Set base CRL number: must be critical */ + + if (!X509_CRL_add1_ext_i2d(crl, NID_delta_crl, base->crl_number, 1, 0)) + goto memerr; + + /* + * Copy extensions across from newest CRL to delta: this will set CRL + * number to correct value too. + */ + + for (i = 0; i < X509_CRL_get_ext_count(newer); i++) { + X509_EXTENSION *ext; + ext = X509_CRL_get_ext(newer, i); + if (!X509_CRL_add_ext(crl, ext, -1)) + goto memerr; + } + + /* Go through revoked entries, copying as needed */ + + revs = X509_CRL_get_REVOKED(newer); + + for (i = 0; i < sk_X509_REVOKED_num(revs); i++) { + X509_REVOKED *rvn, *rvtmp; + rvn = sk_X509_REVOKED_value(revs, i); + /* + * Add only if not also in base. TODO: need something cleverer here + * for some more complex CRLs covering multiple CAs. + */ + if (!X509_CRL_get0_by_serial(base, &rvtmp, rvn->serialNumber)) { + rvtmp = X509_REVOKED_dup(rvn); + if (!rvtmp) + goto memerr; + if (!X509_CRL_add0_revoked(crl, rvtmp)) { + X509_REVOKED_free(rvtmp); + goto memerr; + } + } + } + /* TODO: optionally prune deleted entries */ + + if (skey && md && !X509_CRL_sign(crl, skey, md)) + goto memerr; + + return crl; + + memerr: + X509err(X509_F_X509_CRL_DIFF, ERR_R_MALLOC_FAILURE); + if (crl) + X509_CRL_free(crl); + return NULL; +} +","@@ -1124,10 +1124,10 @@ static int get_crl_sk(X509_STORE_CTX *ctx, X509_CRL **pcrl, X509_CRL **pdcrl, + crl = sk_X509_CRL_value(crls, i); + reasons = *preasons; + crl_score = get_crl_score(ctx, &crl_issuer, &reasons, crl, x); +- if (crl_score < best_score) ++ if (crl_score < best_score || crl_score == 0) + continue; + /* If current CRL is equivalent use it if it is newer */ +- if (crl_score == best_score) { ++ if (crl_score == best_score && best_crl != NULL) { + int day, sec; + if (ASN1_TIME_diff(&day, &sec, X509_CRL_get_lastUpdate(best_crl), + X509_CRL_get_lastUpdate(crl)) == 0)",1194,1525,2048 +321,"static int validatedevicenspace(i_ctx_t * i_ctx_p, ref **space) +{ + int i, code = 0; + ref *devicenspace = *space, proc; + ref nameref, sref, altspace, namesarray, sname; + + /* Check enough arguments in the space */ + if (r_size(devicenspace) < 4) + return_error(gs_error_rangecheck); + /* Check the names parameter is an array */ + code = array_get(imemory, devicenspace, 1, &namesarray); + if (code < 0) + return code; + if (!r_is_array(&namesarray)) + return_error(gs_error_typecheck); + /* Ensure we have at least one ink */ + if (r_size(&namesarray) < 1) + return_error(gs_error_typecheck); + /* Make sure no more inks than we can cope with */ + if (r_size(&namesarray) > MAX_COMPONENTS_IN_DEVN) /* MUST match psi/icremap.h int_remap_color_info_s */ + return_error(gs_error_limitcheck); + /* Check the tint transform is a procedure */ + code = array_get(imemory, devicenspace, 3, &proc); + if (code < 0) + return code; + check_proc(proc); + + /* Check the array of ink names only contains names or strings */ + for (i = 0; i < r_size(&namesarray); ++i) { + array_get(imemory, &namesarray, (long)i, &sname); + switch (r_type(&sname)) { + case t_string: + case t_name: + break; + default: + return_error(gs_error_typecheck); + } + } + + /* Get the name of the alternate space */ + code = array_get(imemory, devicenspace, 2, &altspace); + if (code < 0) + return code; + if (r_has_type(&altspace, t_name)) + ref_assign(&nameref, &altspace); + else { + /* Make sure the alternate space is an array */ + if (!r_is_array(&altspace)) + return_error(gs_error_typecheck); + /* And has a name for its type */ + code = array_get(imemory, &altspace, 0, &nameref); + if (code < 0) + return code; + if (!r_has_type(&nameref, t_name)) + return_error(gs_error_typecheck); + } + /* Convert alternate space name to string */ + name_string_ref(imemory, &nameref, &sref); + /* Check its not /Indexed, /Pattern, /DeviceN */ + if (r_size(&sref) == 7) { + if (strncmp((const char *)sref.value.const_bytes, ""Indexed"", 7) == 0) + return_error(gs_error_typecheck); + if (strncmp((const char *)sref.value.const_bytes, ""Pattern"", 7) == 0) + return_error(gs_error_typecheck); + if (strncmp((const char *)sref.value.const_bytes, ""DeviceN"", 7) == 0) + return_error(gs_error_typecheck); + } + /* and also not /Separation */ + if (r_size(&sref) == 9 && strncmp((const char *)sref.value.const_bytes, ""Separation"", 9) == 0) + return_error(gs_error_typecheck); + + ref_assign(*space, &altspace); + return 0; +} +",0,"static int validatedevicenspace(i_ctx_t * i_ctx_p, ref **space) +{ + int i, code = 0; + ref *devicenspace = *space, proc; + ref nameref, sref, altspace, namesarray, sname; + + /* Check enough arguments in the space */ + if (r_size(devicenspace) < 4) + return_error(gs_error_rangecheck); + /* Check the names parameter is an array */ + code = array_get(imemory, devicenspace, 1, &namesarray); + if (code < 0) + return code; + if (!r_is_array(&namesarray)) + return_error(gs_error_typecheck); + /* Ensure we have at least one ink */ + if (r_size(&namesarray) < 1) + return_error(gs_error_typecheck); + /* Make sure no more inks than we can cope with */ + if (r_size(&namesarray) > MAX_COMPONENTS_IN_DEVN) /* MUST match psi/icremap.h int_remap_color_info_s */ + return_error(gs_error_limitcheck); + /* Check the tint transform is a procedure */ + code = array_get(imemory, devicenspace, 3, &proc); + if (code < 0) + return code; + check_proc(proc); + + /* Check the array of ink names only contains names or strings */ + for (i = 0; i < r_size(&namesarray); ++i) { + array_get(imemory, &namesarray, (long)i, &sname); + switch (r_type(&sname)) { + case t_string: + case t_name: + break; + default: + return_error(gs_error_typecheck); + } + } + + /* Get the name of the alternate space */ + code = array_get(imemory, devicenspace, 2, &altspace); + if (code < 0) + return code; + if (r_has_type(&altspace, t_name)) + ref_assign(&nameref, &altspace); + else { + /* Make sure the alternate space is an array */ + if (!r_is_array(&altspace)) + return_error(gs_error_typecheck); + /* And has a name for its type */ + code = array_get(imemory, &altspace, 0, &nameref); + if (code < 0) + return code; + if (!r_has_type(&nameref, t_name)) + return_error(gs_error_typecheck); + } + /* Convert alternate space name to string */ + name_string_ref(imemory, &nameref, &sref); + /* Check its not /Indexed, /Pattern, /DeviceN */ + if (r_size(&sref) == 7) { + if (strncmp((const char *)sref.value.const_bytes, ""Indexed"", 7) == 0) + return_error(gs_error_typecheck); + if (strncmp((const char *)sref.value.const_bytes, ""Pattern"", 7) == 0) + return_error(gs_error_typecheck); + if (strncmp((const char *)sref.value.const_bytes, ""DeviceN"", 7) == 0) + return_error(gs_error_typecheck); + } + /* and also not /Separation */ + if (r_size(&sref) == 9 && strncmp((const char *)sref.value.const_bytes, ""Separation"", 9) == 0) + return_error(gs_error_typecheck); + + ref_assign(*space, &altspace); + return 0; +} +","@@ -283,8 +283,9 @@ zsetcolor(i_ctx_t * i_ctx_p) + if (r_has_type(op, t_dictionary)) { + ref *pImpl, pPatInst; + +- code = dict_find_string(op, ""Implementation"", &pImpl); +- if (code != 0) { ++ if ((code = dict_find_string(op, ""Implementation"", &pImpl)) < 0) ++ return code; ++ if (code > 0) { + code = array_get(imemory, pImpl, 0, &pPatInst); + if (code < 0) + return code;",756,1087,2048 +1718,"int qcow2_snapshot_goto(BlockDriverState *bs, const char *snapshot_id) +{ + BDRVQcowState *s = bs->opaque; + QCowSnapshot *sn; + int i, snapshot_index; + int cur_l1_bytes, sn_l1_bytes; + int ret; + uint64_t *sn_l1_table = NULL; + + /* Search the snapshot */ + snapshot_index = find_snapshot_by_id_or_name(bs, snapshot_id); + if (snapshot_index < 0) { + return -ENOENT; + } + sn = &s->snapshots[snapshot_index]; + + if (sn->disk_size != bs->total_sectors * BDRV_SECTOR_SIZE) { + error_report(""qcow2: Loading snapshots with different disk "" + ""size is not implemented""); + ret = -ENOTSUP; + goto fail; + } + + /* + * Make sure that the current L1 table is big enough to contain the whole + * L1 table of the snapshot. If the snapshot L1 table is smaller, the + * current one must be padded with zeros. + */ + ret = qcow2_grow_l1_table(bs, sn->l1_size, true); + if (ret < 0) { + goto fail; + } + + cur_l1_bytes = s->l1_size * sizeof(uint64_t); + sn_l1_bytes = sn->l1_size * sizeof(uint64_t); + + /* + * Copy the snapshot L1 table to the current L1 table. + * + * Before overwriting the old current L1 table on disk, make sure to + * increase all refcounts for the clusters referenced by the new one. + * Decrease the refcount referenced by the old one only when the L1 + * table is overwritten. + */ + sn_l1_table = g_malloc0(cur_l1_bytes); + + ret = bdrv_pread(bs->file, sn->l1_table_offset, sn_l1_table, sn_l1_bytes); + if (ret < 0) { + goto fail; + } + + ret = qcow2_update_snapshot_refcount(bs, sn->l1_table_offset, + sn->l1_size, 1); + if (ret < 0) { + goto fail; + } + + ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_ACTIVE_L1, + s->l1_table_offset, cur_l1_bytes); + if (ret < 0) { + goto fail; + } + + ret = bdrv_pwrite_sync(bs->file, s->l1_table_offset, sn_l1_table, + cur_l1_bytes); + if (ret < 0) { + goto fail; + } + + /* + * Decrease refcount of clusters of current L1 table. + * + * At this point, the in-memory s->l1_table points to the old L1 table, + * whereas on disk we already have the new one. + * + * qcow2_update_snapshot_refcount special cases the current L1 table to use + * the in-memory data instead of really using the offset to load a new one, + * which is why this works. + */ + ret = qcow2_update_snapshot_refcount(bs, s->l1_table_offset, + s->l1_size, -1); + + /* + * Now update the in-memory L1 table to be in sync with the on-disk one. We + * need to do this even if updating refcounts failed. + */ + for(i = 0;i < s->l1_size; i++) { + s->l1_table[i] = be64_to_cpu(sn_l1_table[i]); + } + + if (ret < 0) { + goto fail; + } + + g_free(sn_l1_table); + sn_l1_table = NULL; + + /* + * Update QCOW_OFLAG_COPIED in the active L1 table (it may have changed + * when we decreased the refcount of the old snapshot. + */ + ret = qcow2_update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 0); + if (ret < 0) { + goto fail; + } + +#ifdef DEBUG_ALLOC + { + BdrvCheckResult result = {0}; + qcow2_check_refcounts(bs, &result, 0); + } +#endif + return 0; + +fail: + g_free(sn_l1_table); + return ret; +} +",0,"int qcow2_snapshot_goto(BlockDriverState *bs, const char *snapshot_id) +{ + BDRVQcowState *s = bs->opaque; + QCowSnapshot *sn; + int i, snapshot_index; + int cur_l1_bytes, sn_l1_bytes; + int ret; + uint64_t *sn_l1_table = NULL; + + /* Search the snapshot */ + snapshot_index = find_snapshot_by_id_or_name(bs, snapshot_id); + if (snapshot_index < 0) { + return -ENOENT; + } + sn = &s->snapshots[snapshot_index]; + + if (sn->disk_size != bs->total_sectors * BDRV_SECTOR_SIZE) { + error_report(""qcow2: Loading snapshots with different disk "" + ""size is not implemented""); + ret = -ENOTSUP; + goto fail; + } + + /* + * Make sure that the current L1 table is big enough to contain the whole + * L1 table of the snapshot. If the snapshot L1 table is smaller, the + * current one must be padded with zeros. + */ + ret = qcow2_grow_l1_table(bs, sn->l1_size, true); + if (ret < 0) { + goto fail; + } + + cur_l1_bytes = s->l1_size * sizeof(uint64_t); + sn_l1_bytes = sn->l1_size * sizeof(uint64_t); + + /* + * Copy the snapshot L1 table to the current L1 table. + * + * Before overwriting the old current L1 table on disk, make sure to + * increase all refcounts for the clusters referenced by the new one. + * Decrease the refcount referenced by the old one only when the L1 + * table is overwritten. + */ + sn_l1_table = g_malloc0(cur_l1_bytes); + + ret = bdrv_pread(bs->file, sn->l1_table_offset, sn_l1_table, sn_l1_bytes); + if (ret < 0) { + goto fail; + } + + ret = qcow2_update_snapshot_refcount(bs, sn->l1_table_offset, + sn->l1_size, 1); + if (ret < 0) { + goto fail; + } + + ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_ACTIVE_L1, + s->l1_table_offset, cur_l1_bytes); + if (ret < 0) { + goto fail; + } + + ret = bdrv_pwrite_sync(bs->file, s->l1_table_offset, sn_l1_table, + cur_l1_bytes); + if (ret < 0) { + goto fail; + } + + /* + * Decrease refcount of clusters of current L1 table. + * + * At this point, the in-memory s->l1_table points to the old L1 table, + * whereas on disk we already have the new one. + * + * qcow2_update_snapshot_refcount special cases the current L1 table to use + * the in-memory data instead of really using the offset to load a new one, + * which is why this works. + */ + ret = qcow2_update_snapshot_refcount(bs, s->l1_table_offset, + s->l1_size, -1); + + /* + * Now update the in-memory L1 table to be in sync with the on-disk one. We + * need to do this even if updating refcounts failed. + */ + for(i = 0;i < s->l1_size; i++) { + s->l1_table[i] = be64_to_cpu(sn_l1_table[i]); + } + + if (ret < 0) { + goto fail; + } + + g_free(sn_l1_table); + sn_l1_table = NULL; + + /* + * Update QCOW_OFLAG_COPIED in the active L1 table (it may have changed + * when we decreased the refcount of the old snapshot. + */ + ret = qcow2_update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 0); + if (ret < 0) { + goto fail; + } + +#ifdef DEBUG_ALLOC + { + BdrvCheckResult result = {0}; + qcow2_check_refcounts(bs, &result, 0); + } +#endif + return 0; + +fail: + g_free(sn_l1_table); + return ret; +} +","@@ -680,7 +680,7 @@ int qcow2_snapshot_load_tmp(BlockDriverState *bs, + sn = &s->snapshots[snapshot_index]; + + /* Allocate and read in the snapshot's L1 table */ +- new_l1_bytes = s->l1_size * sizeof(uint64_t); ++ new_l1_bytes = sn->l1_size * sizeof(uint64_t); + new_l1_table = g_malloc0(align_offset(new_l1_bytes, 512)); + + ret = bdrv_pread(bs->file, sn->l1_table_offset, new_l1_table, new_l1_bytes);",957,1288,2048 +9284,"sec_parse_crypt_info(STREAM s, uint32 * rc4_key_size, + uint8 ** server_random, uint8 * modulus, uint8 * exponent) +{ + uint32 crypt_level, random_len, rsa_info_len; + uint32 cacert_len, cert_len, flags; + RDSSL_CERT *cacert, *server_cert; + RDSSL_RKEY *server_public_key; + uint16 tag, length; + uint8 *next_tag, *end; + + logger(Protocol, Debug, ""%s()"", __func__); + + in_uint32_le(s, *rc4_key_size); /* 1 = 40-bit, 2 = 128-bit */ + in_uint32_le(s, crypt_level); /* 1 = low, 2 = medium, 3 = high */ + if (crypt_level == 0) + { + /* no encryption */ + logger(Protocol, Debug, ""sec_parse_crypt_info(), got ENCRYPTION_LEVEL_NONE""); + return False; + } + + in_uint32_le(s, random_len); + in_uint32_le(s, rsa_info_len); + + if (random_len != SEC_RANDOM_SIZE) + { + logger(Protocol, Error, ""sec_parse_crypt_info(), got random len %d, expected %d"", + random_len, SEC_RANDOM_SIZE); + return False; + } + + in_uint8p(s, *server_random, random_len); + + /* RSA info */ + end = s->p + rsa_info_len; + if (end > s->end) + { + logger(Protocol, Error, ""sec_parse_crypt_info(), end > s->end""); + return False; + } + + in_uint32_le(s, flags); /* 1 = RDP4-style, 0x80000002 = X.509 */ + if (flags & 1) + { + logger(Protocol, Debug, + ""sec_parse_crypt_info(), We're going for the RDP4-style encryption""); + in_uint8s(s, 8); /* unknown */ + + while (s->p < end) + { + in_uint16_le(s, tag); + in_uint16_le(s, length); + + next_tag = s->p + length; + + switch (tag) + { + case SEC_TAG_PUBKEY: + if (!sec_parse_public_key(s, modulus, exponent)) + { + logger(Protocol, Error, + ""sec_parse_crypt_info(), invalid public key""); + return False; + } + logger(Protocol, Debug, + ""sec_parse_crypt_info(), got public key""); + + break; + + case SEC_TAG_KEYSIG: + if (!sec_parse_public_sig(s, length, modulus, exponent)) + { + logger(Protocol, Error, + ""sec_parse_crypt_info(), invalid public sig""); + return False; + } + break; + + default: + logger(Protocol, Warning, + ""sec_parse_crypt_info(), unhandled crypt tag 0x%x"", + tag); + } + + s->p = next_tag; + } + } + else + { + uint32 certcount; + + logger(Protocol, Debug, + ""sec_parse_crypt_info(), We're going for the RDP5-style encryption""); + in_uint32_le(s, certcount); /* Number of certificates */ + if (certcount < 2) + { + logger(Protocol, Error, + ""sec_parse_crypt_info(), server didn't send enough x509 certificates""); + return False; + } + for (; certcount > 2; certcount--) + { /* ignore all the certificates between the root and the signing CA */ + uint32 ignorelen; + RDSSL_CERT *ignorecert; + + in_uint32_le(s, ignorelen); + ignorecert = rdssl_cert_read(s->p, ignorelen); + in_uint8s(s, ignorelen); + if (ignorecert == NULL) + { /* XXX: error out? */ + logger(Protocol, Error, + ""sec_parse_crypt_info(), got a bad cert: this will probably screw up the rest of the communication""); + } + } + /* Do da funky X.509 stuffy + + ""How did I find out about this? I looked up and saw a + bright light and when I came to I had a scar on my forehead + and knew about X.500"" + - Peter Gutman in a early version of + http://www.cs.auckland.ac.nz/~pgut001/pubs/x509guide.txt + */ + in_uint32_le(s, cacert_len); + logger(Protocol, Debug, + ""sec_parse_crypt_info(), server CA Certificate length is %d"", cacert_len); + cacert = rdssl_cert_read(s->p, cacert_len); + in_uint8s(s, cacert_len); + if (NULL == cacert) + { + logger(Protocol, Error, + ""sec_parse_crypt_info(), couldn't load CA Certificate from server""); + return False; + } + in_uint32_le(s, cert_len); + logger(Protocol, Debug, ""sec_parse_crypt_info(), certificate length is %d"", + cert_len); + server_cert = rdssl_cert_read(s->p, cert_len); + in_uint8s(s, cert_len); + if (NULL == server_cert) + { + rdssl_cert_free(cacert); + logger(Protocol, Error, + ""sec_parse_crypt_info(), couldn't load Certificate from server""); + return False; + } + if (!rdssl_certs_ok(server_cert, cacert)) + { + rdssl_cert_free(server_cert); + rdssl_cert_free(cacert); + logger(Protocol, Error, + ""sec_parse_crypt_info(), security error, CA Certificate invalid""); + return False; + } + rdssl_cert_free(cacert); + in_uint8s(s, 16); /* Padding */ + server_public_key = rdssl_cert_to_rkey(server_cert, &g_server_public_key_len); + if (NULL == server_public_key) + { + logger(Protocol, Debug, + ""sec_parse_crypt_info(). failed to parse X509 correctly""); + rdssl_cert_free(server_cert); + return False; + } + rdssl_cert_free(server_cert); + if ((g_server_public_key_len < SEC_MODULUS_SIZE) || + (g_server_public_key_len > SEC_MAX_MODULUS_SIZE)) + { + logger(Protocol, Error, + ""sec_parse_crypt_info(), bad server public key size (%u bits)"", + g_server_public_key_len * 8); + rdssl_rkey_free(server_public_key); + return False; + } + if (rdssl_rkey_get_exp_mod(server_public_key, exponent, SEC_EXPONENT_SIZE, + modulus, SEC_MAX_MODULUS_SIZE) != 0) + { + logger(Protocol, Error, + ""sec_parse_crypt_info(), problem extracting RSA exponent, modulus""); + rdssl_rkey_free(server_public_key); + return False; + } + rdssl_rkey_free(server_public_key); + return True; /* There's some garbage here we don't care about */ + } + return s_check_end(s); +} +",0,"sec_parse_crypt_info(STREAM s, uint32 * rc4_key_size, + uint8 ** server_random, uint8 * modulus, uint8 * exponent) +{ + uint32 crypt_level, random_len, rsa_info_len; + uint32 cacert_len, cert_len, flags; + RDSSL_CERT *cacert, *server_cert; + RDSSL_RKEY *server_public_key; + uint16 tag, length; + uint8 *next_tag, *end; + + logger(Protocol, Debug, ""%s()"", __func__); + + in_uint32_le(s, *rc4_key_size); /* 1 = 40-bit, 2 = 128-bit */ + in_uint32_le(s, crypt_level); /* 1 = low, 2 = medium, 3 = high */ + if (crypt_level == 0) + { + /* no encryption */ + logger(Protocol, Debug, ""sec_parse_crypt_info(), got ENCRYPTION_LEVEL_NONE""); + return False; + } + + in_uint32_le(s, random_len); + in_uint32_le(s, rsa_info_len); + + if (random_len != SEC_RANDOM_SIZE) + { + logger(Protocol, Error, ""sec_parse_crypt_info(), got random len %d, expected %d"", + random_len, SEC_RANDOM_SIZE); + return False; + } + + in_uint8p(s, *server_random, random_len); + + /* RSA info */ + end = s->p + rsa_info_len; + if (end > s->end) + { + logger(Protocol, Error, ""sec_parse_crypt_info(), end > s->end""); + return False; + } + + in_uint32_le(s, flags); /* 1 = RDP4-style, 0x80000002 = X.509 */ + if (flags & 1) + { + logger(Protocol, Debug, + ""sec_parse_crypt_info(), We're going for the RDP4-style encryption""); + in_uint8s(s, 8); /* unknown */ + + while (s->p < end) + { + in_uint16_le(s, tag); + in_uint16_le(s, length); + + next_tag = s->p + length; + + switch (tag) + { + case SEC_TAG_PUBKEY: + if (!sec_parse_public_key(s, modulus, exponent)) + { + logger(Protocol, Error, + ""sec_parse_crypt_info(), invalid public key""); + return False; + } + logger(Protocol, Debug, + ""sec_parse_crypt_info(), got public key""); + + break; + + case SEC_TAG_KEYSIG: + if (!sec_parse_public_sig(s, length, modulus, exponent)) + { + logger(Protocol, Error, + ""sec_parse_crypt_info(), invalid public sig""); + return False; + } + break; + + default: + logger(Protocol, Warning, + ""sec_parse_crypt_info(), unhandled crypt tag 0x%x"", + tag); + } + + s->p = next_tag; + } + } + else + { + uint32 certcount; + + logger(Protocol, Debug, + ""sec_parse_crypt_info(), We're going for the RDP5-style encryption""); + in_uint32_le(s, certcount); /* Number of certificates */ + if (certcount < 2) + { + logger(Protocol, Error, + ""sec_parse_crypt_info(), server didn't send enough x509 certificates""); + return False; + } + for (; certcount > 2; certcount--) + { /* ignore all the certificates between the root and the signing CA */ + uint32 ignorelen; + RDSSL_CERT *ignorecert; + + in_uint32_le(s, ignorelen); + ignorecert = rdssl_cert_read(s->p, ignorelen); + in_uint8s(s, ignorelen); + if (ignorecert == NULL) + { /* XXX: error out? */ + logger(Protocol, Error, + ""sec_parse_crypt_info(), got a bad cert: this will probably screw up the rest of the communication""); + } + } + /* Do da funky X.509 stuffy + + ""How did I find out about this? I looked up and saw a + bright light and when I came to I had a scar on my forehead + and knew about X.500"" + - Peter Gutman in a early version of + http://www.cs.auckland.ac.nz/~pgut001/pubs/x509guide.txt + */ + in_uint32_le(s, cacert_len); + logger(Protocol, Debug, + ""sec_parse_crypt_info(), server CA Certificate length is %d"", cacert_len); + cacert = rdssl_cert_read(s->p, cacert_len); + in_uint8s(s, cacert_len); + if (NULL == cacert) + { + logger(Protocol, Error, + ""sec_parse_crypt_info(), couldn't load CA Certificate from server""); + return False; + } + in_uint32_le(s, cert_len); + logger(Protocol, Debug, ""sec_parse_crypt_info(), certificate length is %d"", + cert_len); + server_cert = rdssl_cert_read(s->p, cert_len); + in_uint8s(s, cert_len); + if (NULL == server_cert) + { + rdssl_cert_free(cacert); + logger(Protocol, Error, + ""sec_parse_crypt_info(), couldn't load Certificate from server""); + return False; + } + if (!rdssl_certs_ok(server_cert, cacert)) + { + rdssl_cert_free(server_cert); + rdssl_cert_free(cacert); + logger(Protocol, Error, + ""sec_parse_crypt_info(), security error, CA Certificate invalid""); + return False; + } + rdssl_cert_free(cacert); + in_uint8s(s, 16); /* Padding */ + server_public_key = rdssl_cert_to_rkey(server_cert, &g_server_public_key_len); + if (NULL == server_public_key) + { + logger(Protocol, Debug, + ""sec_parse_crypt_info(). failed to parse X509 correctly""); + rdssl_cert_free(server_cert); + return False; + } + rdssl_cert_free(server_cert); + if ((g_server_public_key_len < SEC_MODULUS_SIZE) || + (g_server_public_key_len > SEC_MAX_MODULUS_SIZE)) + { + logger(Protocol, Error, + ""sec_parse_crypt_info(), bad server public key size (%u bits)"", + g_server_public_key_len * 8); + rdssl_rkey_free(server_public_key); + return False; + } + if (rdssl_rkey_get_exp_mod(server_public_key, exponent, SEC_EXPONENT_SIZE, + modulus, SEC_MAX_MODULUS_SIZE) != 0) + { + logger(Protocol, Error, + ""sec_parse_crypt_info(), problem extracting RSA exponent, modulus""); + rdssl_rkey_free(server_public_key); + return False; + } + rdssl_rkey_free(server_public_key); + return True; /* There's some garbage here we don't care about */ + } + return s_check_end(s); +} +","@@ -296,6 +296,9 @@ sec_encrypt(uint8 * data, int length) + void + sec_decrypt(uint8 * data, int length) + { ++ if (length <= 0) ++ return; ++ + if (g_sec_decrypt_use_count == 4096) + { + sec_update(g_sec_decrypt_key, g_sec_decrypt_update_key); +@@ -848,9 +851,11 @@ sec_recv(RD_BOOL * is_fastpath) + uint16 sec_flags; + uint16 channel; + STREAM s; ++ struct stream packet; + + while ((s = mcs_recv(&channel, is_fastpath, &fastpath_hdr)) != NULL) + { ++ packet = *s; + if (*is_fastpath == True) + { + /* If fastpath packet is encrypted, read data +@@ -859,6 +864,10 @@ sec_recv(RD_BOOL * is_fastpath) + fastpath_flags = (fastpath_hdr & 0xC0) >> 6; + if (fastpath_flags & FASTPATH_OUTPUT_ENCRYPTED) + { ++ if (!s_check_rem(s, 8)) { ++ rdp_protocol_error(""sec_recv(), consume fastpath signature from stream would overrun"", &packet); ++ } ++ + in_uint8s(s, 8); /* signature */ + sec_decrypt(s->p, s->end - s->p); + } +@@ -875,6 +884,10 @@ sec_recv(RD_BOOL * is_fastpath) + { + if (sec_flags & SEC_ENCRYPT) + { ++ if (!s_check_rem(s, 8)) { ++ rdp_protocol_error(""sec_recv(), consume encrypt signature from stream would overrun"", &packet); ++ } ++ + in_uint8s(s, 8); /* signature */ + sec_decrypt(s->p, s->end - s->p); + } +@@ -889,6 +902,10 @@ sec_recv(RD_BOOL * is_fastpath) + { + uint8 swapbyte; + ++ if (!s_check_rem(s, 8)) { ++ rdp_protocol_error(""sec_recv(), consume redirect signature from stream would overrun"", &packet); ++ } ++ + in_uint8s(s, 8); /* signature */ + sec_decrypt(s->p, s->end - s->p); + ",1573,1904,2048 +18278,"compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env) +{ + int r, len; + + switch (node->type) { + case BAG_MEMORY: + r = compile_bag_memory_node(node, reg, env); + break; + + case BAG_OPTION: + r = compile_option_node(node, reg, env); + break; + + case BAG_STOP_BACKTRACK: + if (NODE_IS_STOP_BT_SIMPLE_REPEAT(node)) { + QuantNode* qn = QUANT_(NODE_BAG_BODY(node)); + r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env); + if (r != 0) return r; + + len = compile_length_tree(NODE_QUANT_BODY(qn), reg); + if (len < 0) return len; + + r = add_op(reg, OP_PUSH); + if (r != 0) return r; + COP(reg)->push.addr = SIZE_INC_OP + len + SIZE_OP_POP_OUT + SIZE_OP_JUMP; + + r = compile_tree(NODE_QUANT_BODY(qn), reg, env); + if (r != 0) return r; + r = add_op(reg, OP_POP_OUT); + if (r != 0) return r; + + r = add_op(reg, OP_JUMP); + if (r != 0) return r; + COP(reg)->jump.addr = -((int )SIZE_OP_PUSH + len + (int )SIZE_OP_POP_OUT); + } + else { + r = add_op(reg, OP_ATOMIC_START); + if (r != 0) return r; + r = compile_tree(NODE_BAG_BODY(node), reg, env); + if (r != 0) return r; + r = add_op(reg, OP_ATOMIC_END); + } + break; + + case BAG_IF_ELSE: + { + int cond_len, then_len, jump_len; + Node* cond = NODE_BAG_BODY(node); + Node* Then = node->te.Then; + Node* Else = node->te.Else; + + r = add_op(reg, OP_ATOMIC_START); + if (r != 0) return r; + + cond_len = compile_length_tree(cond, reg); + if (cond_len < 0) return cond_len; + if (IS_NOT_NULL(Then)) { + then_len = compile_length_tree(Then, reg); + if (then_len < 0) return then_len; + } + else + then_len = 0; + + jump_len = cond_len + then_len + SIZE_OP_ATOMIC_END; + if (IS_NOT_NULL(Else)) jump_len += SIZE_OP_JUMP; + + r = add_op(reg, OP_PUSH); + if (r != 0) return r; + COP(reg)->push.addr = SIZE_INC_OP + jump_len; + + r = compile_tree(cond, reg, env); + if (r != 0) return r; + r = add_op(reg, OP_ATOMIC_END); + if (r != 0) return r; + + if (IS_NOT_NULL(Then)) { + r = compile_tree(Then, reg, env); + if (r != 0) return r; + } + + if (IS_NOT_NULL(Else)) { + int else_len = compile_length_tree(Else, reg); + r = add_op(reg, OP_JUMP); + if (r != 0) return r; + COP(reg)->jump.addr = else_len + SIZE_INC_OP; + + r = compile_tree(Else, reg, env); + } + } + break; + } + + return r; +} +",1,"compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env) +{ + int r, len; + + switch (node->type) { + case BAG_MEMORY: + r = compile_bag_memory_node(node, reg, env); + break; + + case BAG_OPTION: + r = compile_option_node(node, reg, env); + break; + + case BAG_STOP_BACKTRACK: + if (NODE_IS_STOP_BT_SIMPLE_REPEAT(node)) { + QuantNode* qn = QUANT_(NODE_BAG_BODY(node)); + r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env); + if (r != 0) return r; + + len = compile_length_tree(NODE_QUANT_BODY(qn), reg); + if (len < 0) return len; + + r = add_op(reg, OP_PUSH); + if (r != 0) return r; + COP(reg)->push.addr = SIZE_INC_OP + len + SIZE_OP_POP_OUT + SIZE_OP_JUMP; + + r = compile_tree(NODE_QUANT_BODY(qn), reg, env); + if (r != 0) return r; + r = add_op(reg, OP_POP_OUT); + if (r != 0) return r; + + r = add_op(reg, OP_JUMP); + if (r != 0) return r; + COP(reg)->jump.addr = -((int )SIZE_OP_PUSH + len + (int )SIZE_OP_POP_OUT); + } + else { + r = add_op(reg, OP_ATOMIC_START); + if (r != 0) return r; + r = compile_tree(NODE_BAG_BODY(node), reg, env); + if (r != 0) return r; + r = add_op(reg, OP_ATOMIC_END); + } + break; + + case BAG_IF_ELSE: + { + int cond_len, then_len, else_len, jump_len; + Node* cond = NODE_BAG_BODY(node); + Node* Then = node->te.Then; + Node* Else = node->te.Else; + + r = add_op(reg, OP_ATOMIC_START); + if (r != 0) return r; + + cond_len = compile_length_tree(cond, reg); + if (cond_len < 0) return cond_len; + if (IS_NOT_NULL(Then)) { + then_len = compile_length_tree(Then, reg); + if (then_len < 0) return then_len; + } + else + then_len = 0; + + jump_len = cond_len + then_len + SIZE_OP_ATOMIC_END + SIZE_OP_JUMP; + + r = add_op(reg, OP_PUSH); + if (r != 0) return r; + COP(reg)->push.addr = SIZE_INC_OP + jump_len; + + r = compile_tree(cond, reg, env); + if (r != 0) return r; + r = add_op(reg, OP_ATOMIC_END); + if (r != 0) return r; + + if (IS_NOT_NULL(Then)) { + r = compile_tree(Then, reg, env); + if (r != 0) return r; + } + + if (IS_NOT_NULL(Else)) { + else_len = compile_length_tree(Else, reg); + if (else_len < 0) return else_len; + } + else + else_len = 0; + + r = add_op(reg, OP_JUMP); + if (r != 0) return r; + COP(reg)->jump.addr = SIZE_OP_ATOMIC_END + else_len + SIZE_INC_OP; + + r = add_op(reg, OP_ATOMIC_END); + if (r != 0) return r; + + if (IS_NOT_NULL(Else)) { + r = compile_tree(Else, reg, env); + } + } + break; + } + + return r; +} +","@@ -1307,8 +1307,9 @@ compile_length_bag_node(BagNode* node, regex_t* reg) + len += tlen; + } + ++ len += SIZE_OP_JUMP + SIZE_OP_ATOMIC_END; ++ + if (IS_NOT_NULL(Else)) { +- len += SIZE_OP_JUMP; + tlen = compile_length_tree(Else, reg); + if (tlen < 0) return tlen; + len += tlen; +@@ -1455,7 +1456,7 @@ compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env) + + case BAG_IF_ELSE: + { +- int cond_len, then_len, jump_len; ++ int cond_len, then_len, else_len, jump_len; + Node* cond = NODE_BAG_BODY(node); + Node* Then = node->te.Then; + Node* Else = node->te.Else; +@@ -1472,8 +1473,7 @@ compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env) + else + then_len = 0; + +- jump_len = cond_len + then_len + SIZE_OP_ATOMIC_END; +- if (IS_NOT_NULL(Else)) jump_len += SIZE_OP_JUMP; ++ jump_len = cond_len + then_len + SIZE_OP_ATOMIC_END + SIZE_OP_JUMP; + + r = add_op(reg, OP_PUSH); + if (r != 0) return r; +@@ -1490,11 +1490,20 @@ compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env) + } + + if (IS_NOT_NULL(Else)) { +- int else_len = compile_length_tree(Else, reg); +- r = add_op(reg, OP_JUMP); +- if (r != 0) return r; +- COP(reg)->jump.addr = else_len + SIZE_INC_OP; ++ else_len = compile_length_tree(Else, reg); ++ if (else_len < 0) return else_len; ++ } ++ else ++ else_len = 0; + ++ r = add_op(reg, OP_JUMP); ++ if (r != 0) return r; ++ COP(reg)->jump.addr = SIZE_OP_ATOMIC_END + else_len + SIZE_INC_OP; ++ ++ r = add_op(reg, OP_ATOMIC_END); ++ if (r != 0) return r; ++ ++ if (IS_NOT_NULL(Else)) { + r = compile_tree(Else, reg, env); + } + }",765,1096,2048 +18279,"compile_length_bag_node(BagNode* node, regex_t* reg) +{ + int len; + int tlen; + + if (node->type == BAG_OPTION) + return compile_length_option_node(node, reg); + + if (NODE_BAG_BODY(node)) { + tlen = compile_length_tree(NODE_BAG_BODY(node), reg); + if (tlen < 0) return tlen; + } + else + tlen = 0; + + switch (node->type) { + case BAG_MEMORY: +#ifdef USE_CALL + + if (node->m.regnum == 0 && NODE_IS_CALLED(node)) { + len = tlen + SIZE_OP_CALL + SIZE_OP_JUMP + SIZE_OP_RETURN; + return len; + } + + if (NODE_IS_CALLED(node)) { + len = SIZE_OP_MEMORY_START_PUSH + tlen + + SIZE_OP_CALL + SIZE_OP_JUMP + SIZE_OP_RETURN; + if (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum)) + len += (NODE_IS_RECURSION(node) + ? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_PUSH); + else + len += (NODE_IS_RECURSION(node) + ? SIZE_OP_MEMORY_END_REC : SIZE_OP_MEMORY_END); + } + else if (NODE_IS_RECURSION(node)) { + len = SIZE_OP_MEMORY_START_PUSH; + len += tlen + (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum) + ? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_REC); + } + else +#endif + { + if (MEM_STATUS_AT0(reg->bt_mem_start, node->m.regnum)) + len = SIZE_OP_MEMORY_START_PUSH; + else + len = SIZE_OP_MEMORY_START; + + len += tlen + (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum) + ? SIZE_OP_MEMORY_END_PUSH : SIZE_OP_MEMORY_END); + } + break; + + case BAG_STOP_BACKTRACK: + if (NODE_IS_STOP_BT_SIMPLE_REPEAT(node)) { + int v; + QuantNode* qn; + + qn = QUANT_(NODE_BAG_BODY(node)); + tlen = compile_length_tree(NODE_QUANT_BODY(qn), reg); + if (tlen < 0) return tlen; + + v = onig_positive_int_multiply(qn->lower, tlen); + if (v < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; + len = v + SIZE_OP_PUSH + tlen + SIZE_OP_POP_OUT + SIZE_OP_JUMP; + } + else { + len = SIZE_OP_ATOMIC_START + tlen + SIZE_OP_ATOMIC_END; + } + break; + + case BAG_IF_ELSE: + { + Node* cond = NODE_BAG_BODY(node); + Node* Then = node->te.Then; + Node* Else = node->te.Else; + + len = compile_length_tree(cond, reg); + if (len < 0) return len; + len += SIZE_OP_PUSH; + len += SIZE_OP_ATOMIC_START + SIZE_OP_ATOMIC_END; + + if (IS_NOT_NULL(Then)) { + tlen = compile_length_tree(Then, reg); + if (tlen < 0) return tlen; + len += tlen; + } + + if (IS_NOT_NULL(Else)) { + len += SIZE_OP_JUMP; + tlen = compile_length_tree(Else, reg); + if (tlen < 0) return tlen; + len += tlen; + } + } + break; + + case BAG_OPTION: + /* never come here, but set for escape warning */ + len = 0; + break; + } + + return len; +} +",1,"compile_length_bag_node(BagNode* node, regex_t* reg) +{ + int len; + int tlen; + + if (node->type == BAG_OPTION) + return compile_length_option_node(node, reg); + + if (NODE_BAG_BODY(node)) { + tlen = compile_length_tree(NODE_BAG_BODY(node), reg); + if (tlen < 0) return tlen; + } + else + tlen = 0; + + switch (node->type) { + case BAG_MEMORY: +#ifdef USE_CALL + + if (node->m.regnum == 0 && NODE_IS_CALLED(node)) { + len = tlen + SIZE_OP_CALL + SIZE_OP_JUMP + SIZE_OP_RETURN; + return len; + } + + if (NODE_IS_CALLED(node)) { + len = SIZE_OP_MEMORY_START_PUSH + tlen + + SIZE_OP_CALL + SIZE_OP_JUMP + SIZE_OP_RETURN; + if (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum)) + len += (NODE_IS_RECURSION(node) + ? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_PUSH); + else + len += (NODE_IS_RECURSION(node) + ? SIZE_OP_MEMORY_END_REC : SIZE_OP_MEMORY_END); + } + else if (NODE_IS_RECURSION(node)) { + len = SIZE_OP_MEMORY_START_PUSH; + len += tlen + (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum) + ? SIZE_OP_MEMORY_END_PUSH_REC : SIZE_OP_MEMORY_END_REC); + } + else +#endif + { + if (MEM_STATUS_AT0(reg->bt_mem_start, node->m.regnum)) + len = SIZE_OP_MEMORY_START_PUSH; + else + len = SIZE_OP_MEMORY_START; + + len += tlen + (MEM_STATUS_AT0(reg->bt_mem_end, node->m.regnum) + ? SIZE_OP_MEMORY_END_PUSH : SIZE_OP_MEMORY_END); + } + break; + + case BAG_STOP_BACKTRACK: + if (NODE_IS_STOP_BT_SIMPLE_REPEAT(node)) { + int v; + QuantNode* qn; + + qn = QUANT_(NODE_BAG_BODY(node)); + tlen = compile_length_tree(NODE_QUANT_BODY(qn), reg); + if (tlen < 0) return tlen; + + v = onig_positive_int_multiply(qn->lower, tlen); + if (v < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; + len = v + SIZE_OP_PUSH + tlen + SIZE_OP_POP_OUT + SIZE_OP_JUMP; + } + else { + len = SIZE_OP_ATOMIC_START + tlen + SIZE_OP_ATOMIC_END; + } + break; + + case BAG_IF_ELSE: + { + Node* cond = NODE_BAG_BODY(node); + Node* Then = node->te.Then; + Node* Else = node->te.Else; + + len = compile_length_tree(cond, reg); + if (len < 0) return len; + len += SIZE_OP_PUSH; + len += SIZE_OP_ATOMIC_START + SIZE_OP_ATOMIC_END; + + if (IS_NOT_NULL(Then)) { + tlen = compile_length_tree(Then, reg); + if (tlen < 0) return tlen; + len += tlen; + } + + len += SIZE_OP_JUMP + SIZE_OP_ATOMIC_END; + + if (IS_NOT_NULL(Else)) { + tlen = compile_length_tree(Else, reg); + if (tlen < 0) return tlen; + len += tlen; + } + } + break; + + case BAG_OPTION: + /* never come here, but set for escape warning */ + len = 0; + break; + } + + return len; +} +","@@ -1307,8 +1307,9 @@ compile_length_bag_node(BagNode* node, regex_t* reg) + len += tlen; + } + ++ len += SIZE_OP_JUMP + SIZE_OP_ATOMIC_END; ++ + if (IS_NOT_NULL(Else)) { +- len += SIZE_OP_JUMP; + tlen = compile_length_tree(Else, reg); + if (tlen < 0) return tlen; + len += tlen; +@@ -1455,7 +1456,7 @@ compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env) + + case BAG_IF_ELSE: + { +- int cond_len, then_len, jump_len; ++ int cond_len, then_len, else_len, jump_len; + Node* cond = NODE_BAG_BODY(node); + Node* Then = node->te.Then; + Node* Else = node->te.Else; +@@ -1472,8 +1473,7 @@ compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env) + else + then_len = 0; + +- jump_len = cond_len + then_len + SIZE_OP_ATOMIC_END; +- if (IS_NOT_NULL(Else)) jump_len += SIZE_OP_JUMP; ++ jump_len = cond_len + then_len + SIZE_OP_ATOMIC_END + SIZE_OP_JUMP; + + r = add_op(reg, OP_PUSH); + if (r != 0) return r; +@@ -1490,11 +1490,20 @@ compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env) + } + + if (IS_NOT_NULL(Else)) { +- int else_len = compile_length_tree(Else, reg); +- r = add_op(reg, OP_JUMP); +- if (r != 0) return r; +- COP(reg)->jump.addr = else_len + SIZE_INC_OP; ++ else_len = compile_length_tree(Else, reg); ++ if (else_len < 0) return else_len; ++ } ++ else ++ else_len = 0; + ++ r = add_op(reg, OP_JUMP); ++ if (r != 0) return r; ++ COP(reg)->jump.addr = SIZE_OP_ATOMIC_END + else_len + SIZE_INC_OP; ++ ++ r = add_op(reg, OP_ATOMIC_END); ++ if (r != 0) return r; ++ ++ if (IS_NOT_NULL(Else)) { + r = compile_tree(Else, reg, env); + } + }",789,1120,2048 +16101,"RenderFrameHostImpl::RenderFrameHostImpl(SiteInstance* site_instance, + RenderViewHostImpl* render_view_host, + RenderFrameHostDelegate* delegate, + RenderWidgetHostDelegate* rwh_delegate, + FrameTree* frame_tree, + FrameTreeNode* frame_tree_node, + int32_t routing_id, + int32_t widget_routing_id, + bool hidden, + bool renderer_initiated_creation) + : render_view_host_(render_view_host), + delegate_(delegate), + site_instance_(static_cast(site_instance)), + process_(site_instance->GetProcess()), + frame_tree_(frame_tree), + frame_tree_node_(frame_tree_node), + parent_(nullptr), + render_widget_host_(nullptr), + routing_id_(routing_id), + is_waiting_for_swapout_ack_(false), + render_frame_created_(false), + is_waiting_for_beforeunload_ack_(false), + unload_ack_is_for_navigation_(false), + is_loading_(false), + pending_commit_(false), + nav_entry_id_(0), + accessibility_reset_token_(0), + accessibility_reset_count_(0), + browser_plugin_embedder_ax_tree_id_(ui::AXTreeIDRegistry::kNoAXTreeID), + no_create_browser_accessibility_manager_for_testing_(false), + web_ui_type_(WebUI::kNoWebUI), + pending_web_ui_type_(WebUI::kNoWebUI), + should_reuse_web_ui_(false), + has_selection_(false), + is_audible_(false), + last_navigation_previews_state_(PREVIEWS_UNSPECIFIED), + frame_host_associated_binding_(this), + waiting_for_init_(renderer_initiated_creation), + has_focused_editable_element_(false), + active_sandbox_flags_(blink::WebSandboxFlags::kNone), + document_scoped_interface_provider_binding_(this), + keep_alive_timeout_(base::TimeDelta::FromSeconds(30)), + weak_ptr_factory_(this) { + frame_tree_->AddRenderViewHostRef(render_view_host_); + GetProcess()->AddRoute(routing_id_, this); + g_routing_id_frame_map.Get().insert(std::make_pair( + RenderFrameHostID(GetProcess()->GetID(), routing_id_), + this)); + site_instance_->AddObserver(this); + GetSiteInstance()->IncrementActiveFrameCount(); + + if (frame_tree_node_->parent()) { + parent_ = frame_tree_node_->parent()->current_frame_host(); + + if (parent_->GetEnabledBindings()) + enabled_bindings_ = parent_->GetEnabledBindings(); + + set_nav_entry_id( + frame_tree_node_->parent()->current_frame_host()->nav_entry_id()); + } + + SetUpMojoIfNeeded(); + + swapout_event_monitor_timeout_.reset(new TimeoutMonitor(base::Bind( + &RenderFrameHostImpl::OnSwappedOut, weak_ptr_factory_.GetWeakPtr()))); + beforeunload_timeout_.reset( + new TimeoutMonitor(base::Bind(&RenderFrameHostImpl::BeforeUnloadTimeout, + weak_ptr_factory_.GetWeakPtr()))); + + if (widget_routing_id != MSG_ROUTING_NONE) { + mojom::WidgetPtr widget; + GetRemoteInterfaces()->GetInterface(&widget); + + render_widget_host_ = + RenderWidgetHostImpl::FromID(GetProcess()->GetID(), widget_routing_id); + + mojom::WidgetInputHandlerAssociatedPtr widget_handler; + mojom::WidgetInputHandlerHostRequest host_request; + if (frame_input_handler_) { + mojom::WidgetInputHandlerHostPtr host; + host_request = mojo::MakeRequest(&host); + frame_input_handler_->GetWidgetInputHandler( + mojo::MakeRequest(&widget_handler), std::move(host)); + } + if (!render_widget_host_) { + DCHECK(frame_tree_node->parent()); + render_widget_host_ = RenderWidgetHostFactory::Create( + rwh_delegate, GetProcess(), widget_routing_id, std::move(widget), + hidden); + render_widget_host_->set_owned_by_render_frame_host(true); + } else { + DCHECK(!render_widget_host_->owned_by_render_frame_host()); + render_widget_host_->SetWidget(std::move(widget)); + } + render_widget_host_->SetWidgetInputHandler(std::move(widget_handler), + std::move(host_request)); + render_widget_host_->input_router()->SetFrameTreeNodeId( + frame_tree_node_->frame_tree_node_id()); + } + ResetFeaturePolicy(); + + ax_tree_id_ = ui::AXTreeIDRegistry::GetInstance()->GetOrCreateAXTreeID( + GetProcess()->GetID(), routing_id_); +} +",0,"RenderFrameHostImpl::RenderFrameHostImpl(SiteInstance* site_instance, + RenderViewHostImpl* render_view_host, + RenderFrameHostDelegate* delegate, + RenderWidgetHostDelegate* rwh_delegate, + FrameTree* frame_tree, + FrameTreeNode* frame_tree_node, + int32_t routing_id, + int32_t widget_routing_id, + bool hidden, + bool renderer_initiated_creation) + : render_view_host_(render_view_host), + delegate_(delegate), + site_instance_(static_cast(site_instance)), + process_(site_instance->GetProcess()), + frame_tree_(frame_tree), + frame_tree_node_(frame_tree_node), + parent_(nullptr), + render_widget_host_(nullptr), + routing_id_(routing_id), + is_waiting_for_swapout_ack_(false), + render_frame_created_(false), + is_waiting_for_beforeunload_ack_(false), + unload_ack_is_for_navigation_(false), + is_loading_(false), + pending_commit_(false), + nav_entry_id_(0), + accessibility_reset_token_(0), + accessibility_reset_count_(0), + browser_plugin_embedder_ax_tree_id_(ui::AXTreeIDRegistry::kNoAXTreeID), + no_create_browser_accessibility_manager_for_testing_(false), + web_ui_type_(WebUI::kNoWebUI), + pending_web_ui_type_(WebUI::kNoWebUI), + should_reuse_web_ui_(false), + has_selection_(false), + is_audible_(false), + last_navigation_previews_state_(PREVIEWS_UNSPECIFIED), + frame_host_associated_binding_(this), + waiting_for_init_(renderer_initiated_creation), + has_focused_editable_element_(false), + active_sandbox_flags_(blink::WebSandboxFlags::kNone), + document_scoped_interface_provider_binding_(this), + keep_alive_timeout_(base::TimeDelta::FromSeconds(30)), + weak_ptr_factory_(this) { + frame_tree_->AddRenderViewHostRef(render_view_host_); + GetProcess()->AddRoute(routing_id_, this); + g_routing_id_frame_map.Get().insert(std::make_pair( + RenderFrameHostID(GetProcess()->GetID(), routing_id_), + this)); + site_instance_->AddObserver(this); + GetSiteInstance()->IncrementActiveFrameCount(); + + if (frame_tree_node_->parent()) { + parent_ = frame_tree_node_->parent()->current_frame_host(); + + if (parent_->GetEnabledBindings()) + enabled_bindings_ = parent_->GetEnabledBindings(); + + set_nav_entry_id( + frame_tree_node_->parent()->current_frame_host()->nav_entry_id()); + } + + SetUpMojoIfNeeded(); + + swapout_event_monitor_timeout_.reset(new TimeoutMonitor(base::Bind( + &RenderFrameHostImpl::OnSwappedOut, weak_ptr_factory_.GetWeakPtr()))); + beforeunload_timeout_.reset( + new TimeoutMonitor(base::Bind(&RenderFrameHostImpl::BeforeUnloadTimeout, + weak_ptr_factory_.GetWeakPtr()))); + + if (widget_routing_id != MSG_ROUTING_NONE) { + mojom::WidgetPtr widget; + GetRemoteInterfaces()->GetInterface(&widget); + + render_widget_host_ = + RenderWidgetHostImpl::FromID(GetProcess()->GetID(), widget_routing_id); + + mojom::WidgetInputHandlerAssociatedPtr widget_handler; + mojom::WidgetInputHandlerHostRequest host_request; + if (frame_input_handler_) { + mojom::WidgetInputHandlerHostPtr host; + host_request = mojo::MakeRequest(&host); + frame_input_handler_->GetWidgetInputHandler( + mojo::MakeRequest(&widget_handler), std::move(host)); + } + if (!render_widget_host_) { + DCHECK(frame_tree_node->parent()); + render_widget_host_ = RenderWidgetHostFactory::Create( + rwh_delegate, GetProcess(), widget_routing_id, std::move(widget), + hidden); + render_widget_host_->set_owned_by_render_frame_host(true); + } else { + DCHECK(!render_widget_host_->owned_by_render_frame_host()); + render_widget_host_->SetWidget(std::move(widget)); + } + render_widget_host_->SetWidgetInputHandler(std::move(widget_handler), + std::move(host_request)); + render_widget_host_->input_router()->SetFrameTreeNodeId( + frame_tree_node_->frame_tree_node_id()); + } + ResetFeaturePolicy(); + + ax_tree_id_ = ui::AXTreeIDRegistry::GetInstance()->GetOrCreateAXTreeID( + GetProcess()->GetID(), routing_id_); +} +","@@ -960,6 +960,7 @@ bool RenderFrameHostImpl::OnMessageReceived(const IPC::Message &msg) { + OnSetHasReceivedUserGestureBeforeNavigation) + IPC_MESSAGE_HANDLER(FrameHostMsg_ScrollRectToVisibleInParentFrame, + OnScrollRectToVisibleInParentFrame) ++ IPC_MESSAGE_HANDLER(FrameHostMsg_FrameDidCallFocus, OnFrameDidCallFocus) + #if BUILDFLAG(USE_EXTERNAL_POPUP_MENU) + IPC_MESSAGE_HANDLER(FrameHostMsg_ShowPopup, OnShowPopup) + IPC_MESSAGE_HANDLER(FrameHostMsg_HidePopup, OnHidePopup) +@@ -2824,6 +2825,10 @@ void RenderFrameHostImpl::OnScrollRectToVisibleInParentFrame( + proxy->ScrollRectToVisible(rect_to_scroll, params); + } + ++void RenderFrameHostImpl::OnFrameDidCallFocus() { ++ delegate_->DidCallFocus(); ++} ++ + #if BUILDFLAG(USE_EXTERNAL_POPUP_MENU) + void RenderFrameHostImpl::OnShowPopup( + const FrameHostMsg_ShowPopup_Params& params) {",936,1267,2048 +18085," construct_command_line(struct manager_ctx *manager, struct server *server) + { + static char cmd[BUF_SIZE]; + char *method = manager->method; + int i; + + build_config(working_dir, server); + + if (server->method) method = server->method; + memset(cmd, 0, BUF_SIZE); + snprintf(cmd, BUF_SIZE, + ""%s -m %s --manager-address %s -f %s/.shadowsocks_%s.pid -c %s/.shadowsocks_%s.conf"", + executable, method, manager->manager_address, + working_dir, server->port, working_dir, server->port); + + if (manager->acl != NULL) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" --acl %s"", manager->acl); + } + if (manager->timeout != NULL) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" -t %s"", manager->timeout); + } +#ifdef HAVE_SETRLIMIT + if (manager->nofile) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" -n %d"", manager->nofile); + } +#endif + if (manager->user != NULL) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" -a %s"", manager->user); + } + if (manager->verbose) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" -v""); + } + if (server->mode == NULL && manager->mode == UDP_ONLY) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" -U""); + } + if (server->mode == NULL && manager->mode == TCP_AND_UDP) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" -u""); + } + if (server->fast_open[0] == 0 && manager->fast_open) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" --fast-open""); + } + if (manager->ipv6first) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" -6""); + } + if (manager->mtu) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" --mtu %d"", manager->mtu); + } + if (server->plugin == NULL && manager->plugin) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" --plugin \""%s\"""", manager->plugin); + } + if (server->plugin_opts == NULL && manager->plugin_opts) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" --plugin-opts \""%s\"""", manager->plugin_opts); + } + for (i = 0; i < manager->nameserver_num; i++) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" -d %s"", manager->nameservers[i]); + } + for (i = 0; i < manager->host_num; i++) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" -s %s"", manager->hosts[i]); + } + { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" --reuse-port""); + } + + if (verbose) { + LOGI(""cmd: %s"", cmd); + } + + return cmd; +} +",1," construct_command_line(struct manager_ctx *manager, struct server *server) + { + static char cmd[BUF_SIZE]; + int i; + int port; + + port = atoi(server->port); + + build_config(working_dir, manager, server); + + memset(cmd, 0, BUF_SIZE); + snprintf(cmd, BUF_SIZE, + ""%s --manager-address %s -f %s/.shadowsocks_%d.pid -c %s/.shadowsocks_%d.conf"", + executable, manager->manager_address, working_dir, port, working_dir, port); + + if (manager->acl != NULL) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" --acl %s"", manager->acl); + } + if (manager->timeout != NULL) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" -t %s"", manager->timeout); + } +#ifdef HAVE_SETRLIMIT + if (manager->nofile) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" -n %d"", manager->nofile); + } +#endif + if (manager->user != NULL) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" -a %s"", manager->user); + } + if (manager->verbose) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" -v""); + } + if (server->mode == NULL && manager->mode == UDP_ONLY) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" -U""); + } + if (server->mode == NULL && manager->mode == TCP_AND_UDP) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" -u""); + } + if (server->fast_open[0] == 0 && manager->fast_open) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" --fast-open""); + } + if (manager->ipv6first) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" -6""); + } + if (manager->mtu) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" --mtu %d"", manager->mtu); + } + if (server->plugin == NULL && manager->plugin) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" --plugin \""%s\"""", manager->plugin); + } + if (server->plugin_opts == NULL && manager->plugin_opts) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" --plugin-opts \""%s\"""", manager->plugin_opts); + } + for (i = 0; i < manager->nameserver_num; i++) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" -d %s"", manager->nameservers[i]); + } + for (i = 0; i < manager->host_num; i++) { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" -s %s"", manager->hosts[i]); + } + { + int len = strlen(cmd); + snprintf(cmd + len, BUF_SIZE - len, "" --reuse-port""); + } + + if (verbose) { + LOGI(""cmd: %s"", cmd); + } + + return cmd; +} +","@@ -92,7 +92,7 @@ destroy_server(struct server *server) { + } + + static void +-build_config(char *prefix, struct server *server) ++build_config(char *prefix, struct manager_ctx *manager, struct server *server) + { + char *path = NULL; + int path_size = strlen(prefix) + strlen(server->port) + 20; +@@ -110,11 +110,18 @@ build_config(char *prefix, struct server *server) + fprintf(f, ""{\n""); + fprintf(f, ""\""server_port\"":%d,\n"", atoi(server->port)); + fprintf(f, ""\""password\"":\""%s\"""", server->password); +- if (server->fast_open[0]) fprintf(f, "",\n\""fast_open\"": %s"", server->fast_open); +- if (server->mode) fprintf(f, "",\n\""mode\"":\""%s\"""", server->mode); +- if (server->method) fprintf(f, "",\n\""method\"":\""%s\"""", server->method); +- if (server->plugin) fprintf(f, "",\n\""plugin\"":\""%s\"""", server->plugin); +- if (server->plugin_opts) fprintf(f, "",\n\""plugin_opts\"":\""%s\"""", server->plugin_opts); ++ if (server->method) ++ fprintf(f, "",\n\""method\"":\""%s\"""", server->method); ++ else if (manager->method) ++ fprintf(f, "",\n\""method\"":\""%s\"""", manager->method); ++ if (server->fast_open[0]) ++ fprintf(f, "",\n\""fast_open\"": %s"", server->fast_open); ++ if (server->mode) ++ fprintf(f, "",\n\""mode\"":\""%s\"""", server->mode); ++ if (server->plugin) ++ fprintf(f, "",\n\""plugin\"":\""%s\"""", server->plugin); ++ if (server->plugin_opts) ++ fprintf(f, "",\n\""plugin_opts\"":\""%s\"""", server->plugin_opts); + fprintf(f, ""\n}\n""); + fclose(f); + ss_free(path); +@@ -124,17 +131,17 @@ static char * + construct_command_line(struct manager_ctx *manager, struct server *server) + { + static char cmd[BUF_SIZE]; +- char *method = manager->method; + int i; ++ int port; + +- build_config(working_dir, server); ++ port = atoi(server->port); ++ ++ build_config(working_dir, manager, server); + +- if (server->method) method = server->method; + memset(cmd, 0, BUF_SIZE); + snprintf(cmd, BUF_SIZE, +- ""%s -m %s --manager-address %s -f %s/.shadowsocks_%s.pid -c %s/.shadowsocks_%s.conf"", +- executable, method, manager->manager_address, +- working_dir, server->port, working_dir, server->port); ++ ""%s --manager-address %s -f %s/.shadowsocks_%d.pid -c %s/.shadowsocks_%d.conf"", ++ executable, manager->manager_address, working_dir, port, working_dir, port); + + if (manager->acl != NULL) { + int len = strlen(cmd);",786,1117,2048 +18148,"mapi_attr_read (size_t len, unsigned char *buf) +{ + size_t idx = 0; + uint32 i,j; + assert(len > 4); + uint32 num_properties = GETINT32(buf+idx); + MAPI_Attr** attrs = CHECKED_XMALLOC (MAPI_Attr*, (num_properties + 1)); + + idx += 4; + + if (!attrs) return NULL; + for (i = 0; i < num_properties; i++) + { + MAPI_Attr* a = attrs[i] = CHECKED_XCALLOC(MAPI_Attr, 1); + MAPI_Value* v = NULL; + + CHECKINT16(idx, len); a->type = GETINT16(buf+idx); idx += 2; + CHECKINT16(idx, len); a->name = GETINT16(buf+idx); idx += 2; + + /* handle special case of GUID prefixed properties */ + if (a->name & GUID_EXISTS_FLAG) + { + /* copy GUID */ + a->guid = CHECKED_XMALLOC(GUID, 1); + copy_guid_from_buf(a->guid, buf+idx, len); + idx += sizeof (GUID); + + CHECKINT32(idx, len); a->num_names = GETINT32(buf+idx); idx += 4; + if (a->num_names > 0) + { + /* FIXME: do something useful here! */ + size_t i; + + a->names = CHECKED_XCALLOC(VarLenData, a->num_names); + + for (i = 0; i < a->num_names; i++) + { + size_t j; + + CHECKINT32(idx, len); a->names[i].len = GETINT32(buf+idx); idx += 4; + + /* read the data into a buffer */ + a->names[i].data + = CHECKED_XMALLOC(unsigned char, a->names[i].len); + for (j = 0; j < (a->names[i].len >> 1); j++) + a->names[i].data[j] = (buf+idx)[j*2]; + + /* But what are we going to do with it? */ + + idx += pad_to_4byte(a->names[i].len); + } + } + else + { + /* get the 'real' name */ + CHECKINT32(idx, len); a->name = GETINT32(buf+idx); idx+= 4; + } + } + + /* + * Multi-value types and string/object/binary types have + * multiple values + */ + if (a->type & MULTI_VALUE_FLAG || + a->type == szMAPI_STRING || + a->type == szMAPI_UNICODE_STRING || + a->type == szMAPI_OBJECT || + a->type == szMAPI_BINARY) + { + CHECKINT32(idx, len); a->num_values = GETINT32(buf+idx); + idx += 4; + } + else + { + a->num_values = 1; + } + + /* Amend the type in case of multi-value type */ + if (a->type & MULTI_VALUE_FLAG) + { + a->type -= MULTI_VALUE_FLAG; + } + + + v = alloc_mapi_values (a); + + for (j = 0; j < a->num_values; j++) + { + switch (a->type) + { + case szMAPI_SHORT: /* 2 bytes */ + v->len = 2; + CHECKINT16(idx, len); v->data.bytes2 = GETINT16(buf+idx); + idx += 4; /* assume padding of 2, advance by 4! */ + break; + + case szMAPI_INT: /* 4 bytes */ + v->len = 4; + CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); + idx += 4; + v++; + break; + + case szMAPI_FLOAT: /* 4 bytes */ + case szMAPI_BOOLEAN: /* this should be 2 bytes + 2 padding */ + v->len = 4; + CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); + idx += v->len; + break; + + case szMAPI_SYSTIME: /* 8 bytes */ + v->len = 8; + CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); + CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); + idx += 8; + v++; + break; + + case szMAPI_DOUBLE: /* 8 bytes */ + case szMAPI_APPTIME: + case szMAPI_CURRENCY: + case szMAPI_INT8BYTE: + v->len = 8; + CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); + CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); + idx += v->len; + break; + + case szMAPI_CLSID: + v->len = sizeof (GUID); + copy_guid_from_buf(&v->data.guid, buf+idx, len); + idx += v->len; + break; + + case szMAPI_STRING: + case szMAPI_UNICODE_STRING: + case szMAPI_OBJECT: + case szMAPI_BINARY: + CHECKINT32(idx, len); v->len = GETINT32(buf+idx); idx += 4; + + if (a->type == szMAPI_UNICODE_STRING) + { + v->data.buf = (unsigned char*)unicode_to_utf8(v->len, buf+idx); + } + else + { + v->data.buf = CHECKED_XMALLOC(unsigned char, v->len); + memmove (v->data.buf, buf+idx, v->len); + } + + idx += pad_to_4byte(v->len); + v++; + break; + + case szMAPI_NULL: /* illegal in input tnef streams */ + case szMAPI_ERROR: + case szMAPI_UNSPECIFIED: + fprintf (stderr, + ""Invalid attribute, input file may be corrupted\n""); + if (!ENCODE_SKIP) exit (1); + + return NULL; + + default: /* should never get here */ + fprintf (stderr, + ""Undefined attribute, input file may be corrupted\n""); + if (!ENCODE_SKIP) exit (1); + + return NULL; + + } + if (DEBUG_ON) mapi_attr_dump (attrs[i]); + } + } + attrs[i] = NULL; + + return attrs; +} +",1,"mapi_attr_read (size_t len, unsigned char *buf) +{ + size_t idx = 0; + uint32 i,j; + assert(len > 4); + uint32 num_properties = GETINT32(buf+idx); + assert((num_properties+1) != 0); + MAPI_Attr** attrs = CHECKED_XMALLOC (MAPI_Attr*, (num_properties + 1)); + + idx += 4; + + if (!attrs) return NULL; + for (i = 0; i < num_properties; i++) + { + MAPI_Attr* a = attrs[i] = CHECKED_XCALLOC(MAPI_Attr, 1); + MAPI_Value* v = NULL; + + CHECKINT16(idx, len); a->type = GETINT16(buf+idx); idx += 2; + CHECKINT16(idx, len); a->name = GETINT16(buf+idx); idx += 2; + + /* handle special case of GUID prefixed properties */ + if (a->name & GUID_EXISTS_FLAG) + { + /* copy GUID */ + a->guid = CHECKED_XMALLOC(GUID, 1); + copy_guid_from_buf(a->guid, buf+idx, len); + idx += sizeof (GUID); + + CHECKINT32(idx, len); a->num_names = GETINT32(buf+idx); idx += 4; + if (a->num_names > 0) + { + /* FIXME: do something useful here! */ + size_t i; + + a->names = CHECKED_XCALLOC(VarLenData, a->num_names); + + for (i = 0; i < a->num_names; i++) + { + size_t j; + + CHECKINT32(idx, len); a->names[i].len = GETINT32(buf+idx); idx += 4; + + /* read the data into a buffer */ + a->names[i].data + = CHECKED_XMALLOC(unsigned char, a->names[i].len); + assert((idx+(a->names[i].len*2)) <= len); + for (j = 0; j < (a->names[i].len >> 1); j++) + a->names[i].data[j] = (buf+idx)[j*2]; + + /* But what are we going to do with it? */ + + idx += pad_to_4byte(a->names[i].len); + } + } + else + { + /* get the 'real' name */ + CHECKINT32(idx, len); a->name = GETINT32(buf+idx); idx+= 4; + } + } + + /* + * Multi-value types and string/object/binary types have + * multiple values + */ + if (a->type & MULTI_VALUE_FLAG || + a->type == szMAPI_STRING || + a->type == szMAPI_UNICODE_STRING || + a->type == szMAPI_OBJECT || + a->type == szMAPI_BINARY) + { + CHECKINT32(idx, len); a->num_values = GETINT32(buf+idx); + idx += 4; + } + else + { + a->num_values = 1; + } + + /* Amend the type in case of multi-value type */ + if (a->type & MULTI_VALUE_FLAG) + { + a->type -= MULTI_VALUE_FLAG; + } + + + v = alloc_mapi_values (a); + + for (j = 0; j < a->num_values; j++) + { + switch (a->type) + { + case szMAPI_SHORT: /* 2 bytes */ + v->len = 2; + CHECKINT16(idx, len); v->data.bytes2 = GETINT16(buf+idx); + idx += 4; /* assume padding of 2, advance by 4! */ + break; + + case szMAPI_INT: /* 4 bytes */ + v->len = 4; + CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); + idx += 4; + v++; + break; + + case szMAPI_FLOAT: /* 4 bytes */ + case szMAPI_BOOLEAN: /* this should be 2 bytes + 2 padding */ + v->len = 4; + CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); + idx += v->len; + break; + + case szMAPI_SYSTIME: /* 8 bytes */ + v->len = 8; + CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); + CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); + idx += 8; + v++; + break; + + case szMAPI_DOUBLE: /* 8 bytes */ + case szMAPI_APPTIME: + case szMAPI_CURRENCY: + case szMAPI_INT8BYTE: + v->len = 8; + CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); + CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); + idx += v->len; + break; + + case szMAPI_CLSID: + v->len = sizeof (GUID); + copy_guid_from_buf(&v->data.guid, buf+idx, len); + idx += v->len; + break; + + case szMAPI_STRING: + case szMAPI_UNICODE_STRING: + case szMAPI_OBJECT: + case szMAPI_BINARY: + CHECKINT32(idx, len); v->len = GETINT32(buf+idx); idx += 4; + + assert(v->len + idx <= len); + + if (a->type == szMAPI_UNICODE_STRING) + { + assert(v->len != 0); + v->data.buf = (unsigned char*)unicode_to_utf8(v->len, buf+idx); + } + else + { + v->data.buf = CHECKED_XMALLOC(unsigned char, v->len); + memmove (v->data.buf, buf+idx, v->len); + } + + idx += pad_to_4byte(v->len); + v++; + break; + + case szMAPI_NULL: /* illegal in input tnef streams */ + case szMAPI_ERROR: + case szMAPI_UNSPECIFIED: + fprintf (stderr, + ""Invalid attribute, input file may be corrupted\n""); + if (!ENCODE_SKIP) exit (1); + + return NULL; + + default: /* should never get here */ + fprintf (stderr, + ""Undefined attribute, input file may be corrupted\n""); + if (!ENCODE_SKIP) exit (1); + + return NULL; + + } + if (DEBUG_ON) mapi_attr_dump (attrs[i]); + } + } + attrs[i] = NULL; + + return attrs; +} +","@@ -174,6 +174,7 @@ mapi_attr_read (size_t len, unsigned char *buf) + uint32 i,j; + assert(len > 4); + uint32 num_properties = GETINT32(buf+idx); ++ assert((num_properties+1) != 0); + MAPI_Attr** attrs = CHECKED_XMALLOC (MAPI_Attr*, (num_properties + 1)); + + idx += 4; +@@ -212,6 +213,7 @@ mapi_attr_read (size_t len, unsigned char *buf) + /* read the data into a buffer */ + a->names[i].data + = CHECKED_XMALLOC(unsigned char, a->names[i].len); ++ assert((idx+(a->names[i].len*2)) <= len); + for (j = 0; j < (a->names[i].len >> 1); j++) + a->names[i].data[j] = (buf+idx)[j*2]; + +@@ -308,8 +310,11 @@ mapi_attr_read (size_t len, unsigned char *buf) + case szMAPI_BINARY: + CHECKINT32(idx, len); v->len = GETINT32(buf+idx); idx += 4; + ++ assert(v->len + idx <= len); ++ + if (a->type == szMAPI_UNICODE_STRING) + { ++ assert(v->len != 0); + v->data.buf = (unsigned char*)unicode_to_utf8(v->len, buf+idx); + } + else",1487,1818,2048 +1287,"static int phar_zip_applysignature(phar_archive_data *phar, struct _phar_zip_pass *pass, + smart_str *metadata TSRMLS_DC) /* {{{ */ +{ + /* 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; + 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); + phar_stream_copy_to_stream(pass->filefp, newfile, tell, NULL); + tell = php_stream_tell(pass->centralfp); + php_stream_seek(pass->centralfp, 0, SEEK_SET); + phar_stream_copy_to_stream(pass->centralfp, newfile, tell, NULL); + if (metadata->c) { + php_stream_write(newfile, metadata->c, metadata->len); + } + + if (FAILURE == phar_create_signature(phar, newfile, &signature, &signature_length, pass->error TSRMLS_CC)) { + 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((void *)&entry, (void *)pass TSRMLS_CC); + php_stream_close(newfile); + + if (pass->error && *(pass->error)) { + /* error is set by writeheaders */ + php_stream_close(newfile); + return FAILURE; + } + } /* signature */ + return SUCCESS; +} +/* }}} */ +",0,"static int phar_zip_applysignature(phar_archive_data *phar, struct _phar_zip_pass *pass, + smart_str *metadata TSRMLS_DC) /* {{{ */ +{ + /* 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; + 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); + phar_stream_copy_to_stream(pass->filefp, newfile, tell, NULL); + tell = php_stream_tell(pass->centralfp); + php_stream_seek(pass->centralfp, 0, SEEK_SET); + phar_stream_copy_to_stream(pass->centralfp, newfile, tell, NULL); + if (metadata->c) { + php_stream_write(newfile, metadata->c, metadata->len); + } + + if (FAILURE == phar_create_signature(phar, newfile, &signature, &signature_length, pass->error TSRMLS_CC)) { + 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((void *)&entry, (void *)pass TSRMLS_CC); + php_stream_close(newfile); + + if (pass->error && *(pass->error)) { + /* error is set by writeheaders */ + php_stream_close(newfile); + return FAILURE; + } + } /* signature */ + return SUCCESS; +} +/* }}} */ +","@@ -159,7 +159,7 @@ static void phar_zip_u2d_time(time_t time, char *dtime, char *ddate) /* {{{ */ + * + * 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. + */ +@@ -199,7 +199,7 @@ int phar_parse_zipfile(php_stream *fp, char *fname, int fname_len, char *alias, + } + + while ((p=(char *) memchr(p + 1, 'P', (size_t) (size - (p + 1 - buf)))) != NULL) { +- if (!memcmp(p + 1, ""K\5\6"", 3)) { ++ 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 */ +@@ -1161,7 +1161,7 @@ int phar_zip_flush(phar_archive_data *phar, char *user_stub, long len, int defau + static const char newstub[] = ""sequence->structural_components_count; i++) { + sourceclip = mxf_resolve_strong_ref(mxf, &source_track->sequence->structural_components_refs[i], SourceClip); + if (!sourceclip) + continue; + + if (!(physical_package = mxf_resolve_source_package(mxf, sourceclip->source_package_uid))) + break; + + mxf_add_umid_metadata(&st->metadata, ""reel_umid"", physical_package); + + /* the name of physical source package is name of the reel or tape */ + if (physical_package->name && physical_package->name[0]) + av_dict_set(&st->metadata, ""reel_name"", physical_package->name, 0); + + /* the source timecode is calculated by adding the start_position of the sourceclip from the file source package track + * to the start_frame of the timecode component located on one of the tracks of the physical source package. + */ + for (j = 0; j < physical_package->tracks_count; j++) { + if (!(physical_track = mxf_resolve_strong_ref(mxf, &physical_package->tracks_refs[j], Track))) { + av_log(mxf->fc, AV_LOG_ERROR, ""could not resolve source track strong ref\n""); + continue; + } + + if (!(physical_track->sequence = mxf_resolve_strong_ref(mxf, &physical_track->sequence_ref, Sequence))) { + av_log(mxf->fc, AV_LOG_ERROR, ""could not resolve source track sequence strong ref\n""); + continue; + } + + if (physical_track->edit_rate.num <= 0 || + physical_track->edit_rate.den <= 0) { + av_log(mxf->fc, AV_LOG_WARNING, + ""Invalid edit rate (%d/%d) found on structural"" + "" component #%d, defaulting to 25/1\n"", + physical_track->edit_rate.num, + physical_track->edit_rate.den, i); + physical_track->edit_rate = (AVRational){25, 1}; + } + + for (k = 0; k < physical_track->sequence->structural_components_count; k++) { + if (!(mxf_tc = mxf_resolve_timecode_component(mxf, &physical_track->sequence->structural_components_refs[k]))) + continue; + + flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0; + /* scale sourceclip start_position to match physical track edit rate */ + start_position = av_rescale_q(sourceclip->start_position, + physical_track->edit_rate, + source_track->edit_rate); + + if (av_timecode_init(&tc, mxf_tc->rate, flags, start_position + mxf_tc->start_frame, mxf->fc) == 0) { + mxf_add_timecode_metadata(&st->metadata, ""timecode"", &tc); + return 0; + } + } + } + } + + return 0; +} +",0,"static int mxf_parse_physical_source_package(MXFContext *mxf, MXFTrack *source_track, AVStream *st) +{ + MXFPackage *physical_package = NULL; + MXFTrack *physical_track = NULL; + MXFStructuralComponent *sourceclip = NULL; + MXFTimecodeComponent *mxf_tc = NULL; + int i, j, k; + AVTimecode tc; + int flags; + int64_t start_position; + + for (i = 0; i < source_track->sequence->structural_components_count; i++) { + sourceclip = mxf_resolve_strong_ref(mxf, &source_track->sequence->structural_components_refs[i], SourceClip); + if (!sourceclip) + continue; + + if (!(physical_package = mxf_resolve_source_package(mxf, sourceclip->source_package_uid))) + break; + + mxf_add_umid_metadata(&st->metadata, ""reel_umid"", physical_package); + + /* the name of physical source package is name of the reel or tape */ + if (physical_package->name && physical_package->name[0]) + av_dict_set(&st->metadata, ""reel_name"", physical_package->name, 0); + + /* the source timecode is calculated by adding the start_position of the sourceclip from the file source package track + * to the start_frame of the timecode component located on one of the tracks of the physical source package. + */ + for (j = 0; j < physical_package->tracks_count; j++) { + if (!(physical_track = mxf_resolve_strong_ref(mxf, &physical_package->tracks_refs[j], Track))) { + av_log(mxf->fc, AV_LOG_ERROR, ""could not resolve source track strong ref\n""); + continue; + } + + if (!(physical_track->sequence = mxf_resolve_strong_ref(mxf, &physical_track->sequence_ref, Sequence))) { + av_log(mxf->fc, AV_LOG_ERROR, ""could not resolve source track sequence strong ref\n""); + continue; + } + + if (physical_track->edit_rate.num <= 0 || + physical_track->edit_rate.den <= 0) { + av_log(mxf->fc, AV_LOG_WARNING, + ""Invalid edit rate (%d/%d) found on structural"" + "" component #%d, defaulting to 25/1\n"", + physical_track->edit_rate.num, + physical_track->edit_rate.den, i); + physical_track->edit_rate = (AVRational){25, 1}; + } + + for (k = 0; k < physical_track->sequence->structural_components_count; k++) { + if (!(mxf_tc = mxf_resolve_timecode_component(mxf, &physical_track->sequence->structural_components_refs[k]))) + continue; + + flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0; + /* scale sourceclip start_position to match physical track edit rate */ + start_position = av_rescale_q(sourceclip->start_position, + physical_track->edit_rate, + source_track->edit_rate); + + if (av_timecode_init(&tc, mxf_tc->rate, flags, start_position + mxf_tc->start_frame, mxf->fc) == 0) { + mxf_add_timecode_metadata(&st->metadata, ""timecode"", &tc); + return 0; + } + } + } + } + + return 0; +} +","@@ -899,6 +899,8 @@ static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *seg + segment->nb_index_entries = avio_rb32(pb); + + length = avio_rb32(pb); ++ if(segment->nb_index_entries && length < 11) ++ return AVERROR_INVALIDDATA; + + if (!(segment->temporal_offset_entries=av_calloc(segment->nb_index_entries, sizeof(*segment->temporal_offset_entries))) || + !(segment->flag_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) || +@@ -909,6 +911,8 @@ static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *seg + } + + for (i = 0; i < segment->nb_index_entries; i++) { ++ if(avio_feof(pb)) ++ return AVERROR_INVALIDDATA; + segment->temporal_offset_entries[i] = avio_r8(pb); + avio_r8(pb); /* KeyFrameOffset */ + segment->flag_entries[i] = avio_r8(pb);",730,1061,2048 +9393,"static int tcm_loop_device_reset(struct scsi_cmnd *sc) +{ + struct se_cmd *se_cmd = NULL; + struct se_portal_group *se_tpg; + struct se_session *se_sess; + struct tcm_loop_cmd *tl_cmd = NULL; + struct tcm_loop_hba *tl_hba; + struct tcm_loop_nexus *tl_nexus; + struct tcm_loop_tmr *tl_tmr = NULL; + struct tcm_loop_tpg *tl_tpg; + int ret = FAILED; + /* + * Locate the tcm_loop_hba_t pointer + */ + tl_hba = *(struct tcm_loop_hba **)shost_priv(sc->device->host); + /* + * Locate the tl_nexus and se_sess pointers + */ + tl_nexus = tl_hba->tl_nexus; + if (!tl_nexus) { + printk(KERN_ERR ""Unable to perform device reset without"" + "" active I_T Nexus\n""); + return FAILED; + } + se_sess = tl_nexus->se_sess; + /* + * Locate the tl_tpg and se_tpg pointers from TargetID in sc->device->id + */ + tl_tpg = &tl_hba->tl_hba_tpgs[sc->device->id]; + se_tpg = &tl_tpg->tl_se_tpg; + + tl_cmd = kmem_cache_zalloc(tcm_loop_cmd_cache, GFP_KERNEL); + if (!tl_cmd) { + printk(KERN_ERR ""Unable to allocate memory for tl_cmd\n""); + return FAILED; + } + + tl_tmr = kzalloc(sizeof(struct tcm_loop_tmr), GFP_KERNEL); + if (!tl_tmr) { + printk(KERN_ERR ""Unable to allocate memory for tl_tmr\n""); + goto release; + } + init_waitqueue_head(&tl_tmr->tl_tmr_wait); + + se_cmd = &tl_cmd->tl_se_cmd; + /* + * Initialize struct se_cmd descriptor from target_core_mod infrastructure + */ + transport_init_se_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess, 0, + DMA_NONE, MSG_SIMPLE_TAG, + &tl_cmd->tl_sense_buf[0]); + /* + * Allocate the LUN_RESET TMR + */ + se_cmd->se_tmr_req = core_tmr_alloc_req(se_cmd, tl_tmr, + TMR_LUN_RESET); + if (IS_ERR(se_cmd->se_tmr_req)) + goto release; + /* + * Locate the underlying TCM struct se_lun from sc->device->lun + */ + if (transport_lookup_tmr_lun(se_cmd, sc->device->lun) < 0) + goto release; + /* + * Queue the TMR to TCM Core and sleep waiting for tcm_loop_queue_tm_rsp() + * to wake us up. + */ + transport_generic_handle_tmr(se_cmd); + wait_event(tl_tmr->tl_tmr_wait, atomic_read(&tl_tmr->tmr_complete)); + /* + * The TMR LUN_RESET has completed, check the response status and + * then release allocations. + */ + ret = (se_cmd->se_tmr_req->response == TMR_FUNCTION_COMPLETE) ? + SUCCESS : FAILED; +release: + if (se_cmd) + transport_generic_free_cmd(se_cmd, 1, 0); + else + kmem_cache_free(tcm_loop_cmd_cache, tl_cmd); + kfree(tl_tmr); + return ret; +} +",0,"static int tcm_loop_device_reset(struct scsi_cmnd *sc) +{ + struct se_cmd *se_cmd = NULL; + struct se_portal_group *se_tpg; + struct se_session *se_sess; + struct tcm_loop_cmd *tl_cmd = NULL; + struct tcm_loop_hba *tl_hba; + struct tcm_loop_nexus *tl_nexus; + struct tcm_loop_tmr *tl_tmr = NULL; + struct tcm_loop_tpg *tl_tpg; + int ret = FAILED; + /* + * Locate the tcm_loop_hba_t pointer + */ + tl_hba = *(struct tcm_loop_hba **)shost_priv(sc->device->host); + /* + * Locate the tl_nexus and se_sess pointers + */ + tl_nexus = tl_hba->tl_nexus; + if (!tl_nexus) { + printk(KERN_ERR ""Unable to perform device reset without"" + "" active I_T Nexus\n""); + return FAILED; + } + se_sess = tl_nexus->se_sess; + /* + * Locate the tl_tpg and se_tpg pointers from TargetID in sc->device->id + */ + tl_tpg = &tl_hba->tl_hba_tpgs[sc->device->id]; + se_tpg = &tl_tpg->tl_se_tpg; + + tl_cmd = kmem_cache_zalloc(tcm_loop_cmd_cache, GFP_KERNEL); + if (!tl_cmd) { + printk(KERN_ERR ""Unable to allocate memory for tl_cmd\n""); + return FAILED; + } + + tl_tmr = kzalloc(sizeof(struct tcm_loop_tmr), GFP_KERNEL); + if (!tl_tmr) { + printk(KERN_ERR ""Unable to allocate memory for tl_tmr\n""); + goto release; + } + init_waitqueue_head(&tl_tmr->tl_tmr_wait); + + se_cmd = &tl_cmd->tl_se_cmd; + /* + * Initialize struct se_cmd descriptor from target_core_mod infrastructure + */ + transport_init_se_cmd(se_cmd, se_tpg->se_tpg_tfo, se_sess, 0, + DMA_NONE, MSG_SIMPLE_TAG, + &tl_cmd->tl_sense_buf[0]); + /* + * Allocate the LUN_RESET TMR + */ + se_cmd->se_tmr_req = core_tmr_alloc_req(se_cmd, tl_tmr, + TMR_LUN_RESET); + if (IS_ERR(se_cmd->se_tmr_req)) + goto release; + /* + * Locate the underlying TCM struct se_lun from sc->device->lun + */ + if (transport_lookup_tmr_lun(se_cmd, sc->device->lun) < 0) + goto release; + /* + * Queue the TMR to TCM Core and sleep waiting for tcm_loop_queue_tm_rsp() + * to wake us up. + */ + transport_generic_handle_tmr(se_cmd); + wait_event(tl_tmr->tl_tmr_wait, atomic_read(&tl_tmr->tmr_complete)); + /* + * The TMR LUN_RESET has completed, check the response status and + * then release allocations. + */ + ret = (se_cmd->se_tmr_req->response == TMR_FUNCTION_COMPLETE) ? + SUCCESS : FAILED; +release: + if (se_cmd) + transport_generic_free_cmd(se_cmd, 1, 0); + else + kmem_cache_free(tcm_loop_cmd_cache, tl_cmd); + kfree(tl_tmr); + return ret; +} +","@@ -1205,7 +1205,7 @@ struct se_portal_group *tcm_loop_make_naa_tpg( + tpgt_str += 5; /* Skip ahead of ""tpgt_"" */ + tpgt = (unsigned short int) simple_strtoul(tpgt_str, &end_ptr, 0); + +- if (tpgt > TL_TPGS_PER_HBA) { ++ if (tpgt >= TL_TPGS_PER_HBA) { + printk(KERN_ERR ""Passed tpgt: %hu exceeds TL_TPGS_PER_HBA:"" + "" %u\n"", tpgt, TL_TPGS_PER_HBA); + return ERR_PTR(-EINVAL);",726,1057,2048 +17957,"vsock_stream_recvmsg(struct kiocb *kiocb, + struct socket *sock, + struct msghdr *msg, size_t len, int flags) +{ + struct sock *sk; + struct vsock_sock *vsk; + int err; + size_t target; + ssize_t copied; + long timeout; + struct vsock_transport_recv_notify_data recv_data; + + DEFINE_WAIT(wait); + + sk = sock->sk; + vsk = vsock_sk(sk); + err = 0; + + msg->msg_namelen = 0; + lock_sock(sk); + + if (sk->sk_state != SS_CONNECTED) { + /* Recvmsg is supposed to return 0 if a peer performs an + * orderly shutdown. Differentiate between that case and when a + * peer has not connected or a local shutdown occured with the + * SOCK_DONE flag. + */ + if (sock_flag(sk, SOCK_DONE)) + err = 0; + else + err = -ENOTCONN; + + goto out; + } + + if (flags & MSG_OOB) { + err = -EOPNOTSUPP; + goto out; + } + + /* We don't check peer_shutdown flag here since peer may actually shut + * down, but there can be data in the queue that a local socket can + * receive. + */ + if (sk->sk_shutdown & RCV_SHUTDOWN) { + err = 0; + goto out; + } + + /* It is valid on Linux to pass in a zero-length receive buffer. This + * is not an error. We may as well bail out now. + */ + if (!len) { + err = 0; + goto out; + } + + /* We must not copy less than target bytes into the user's buffer + * before returning successfully, so we wait for the consume queue to + * have that much data to consume before dequeueing. Note that this + * makes it impossible to handle cases where target is greater than the + * queue size. + */ + target = sock_rcvlowat(sk, flags & MSG_WAITALL, len); + if (target >= transport->stream_rcvhiwat(vsk)) { + err = -ENOMEM; + goto out; + } + timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT); + copied = 0; + + err = transport->notify_recv_init(vsk, target, &recv_data); + if (err < 0) + goto out; + + prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); + + while (1) { + s64 ready = vsock_stream_has_data(vsk); + + if (ready < 0) { + /* Invalid queue pair content. XXX This should be + * changed to a connection reset in a later change. + */ + + err = -ENOMEM; + goto out_wait; + } else if (ready > 0) { + ssize_t read; + + err = transport->notify_recv_pre_dequeue( + vsk, target, &recv_data); + if (err < 0) + break; + + read = transport->stream_dequeue( + vsk, msg->msg_iov, + len - copied, flags); + if (read < 0) { + err = -ENOMEM; + break; + } + + copied += read; + + err = transport->notify_recv_post_dequeue( + vsk, target, read, + !(flags & MSG_PEEK), &recv_data); + if (err < 0) + goto out_wait; + + if (read >= target || flags & MSG_PEEK) + break; + + target -= read; + } else { + if (sk->sk_err != 0 || (sk->sk_shutdown & RCV_SHUTDOWN) + || (vsk->peer_shutdown & SEND_SHUTDOWN)) { + break; + } + /* Don't wait for non-blocking sockets. */ + if (timeout == 0) { + err = -EAGAIN; + break; + } + + err = transport->notify_recv_pre_block( + vsk, target, &recv_data); + if (err < 0) + break; + + release_sock(sk); + timeout = schedule_timeout(timeout); + lock_sock(sk); + + if (signal_pending(current)) { + err = sock_intr_errno(timeout); + break; + } else if (timeout == 0) { + err = -EAGAIN; + break; + } + + prepare_to_wait(sk_sleep(sk), &wait, + TASK_INTERRUPTIBLE); + } + } + + if (sk->sk_err) + err = -sk->sk_err; + else if (sk->sk_shutdown & RCV_SHUTDOWN) + err = 0; + + if (copied > 0) { + /* We only do these additional bookkeeping/notification steps + * if we actually copied something out of the queue pair + * instead of just peeking ahead. + */ + + if (!(flags & MSG_PEEK)) { + /* If the other side has shutdown for sending and there + * is nothing more to read, then modify the socket + * state. + */ + if (vsk->peer_shutdown & SEND_SHUTDOWN) { + if (vsock_stream_has_data(vsk) <= 0) { + sk->sk_state = SS_UNCONNECTED; + sock_set_flag(sk, SOCK_DONE); + sk->sk_state_change(sk); + } + } + } + err = copied; + } + +out_wait: + finish_wait(sk_sleep(sk), &wait); +out: + release_sock(sk); + return err; +} +",1,"vsock_stream_recvmsg(struct kiocb *kiocb, + struct socket *sock, + struct msghdr *msg, size_t len, int flags) +{ + struct sock *sk; + struct vsock_sock *vsk; + int err; + size_t target; + ssize_t copied; + long timeout; + struct vsock_transport_recv_notify_data recv_data; + + DEFINE_WAIT(wait); + + sk = sock->sk; + vsk = vsock_sk(sk); + err = 0; + + lock_sock(sk); + + if (sk->sk_state != SS_CONNECTED) { + /* Recvmsg is supposed to return 0 if a peer performs an + * orderly shutdown. Differentiate between that case and when a + * peer has not connected or a local shutdown occured with the + * SOCK_DONE flag. + */ + if (sock_flag(sk, SOCK_DONE)) + err = 0; + else + err = -ENOTCONN; + + goto out; + } + + if (flags & MSG_OOB) { + err = -EOPNOTSUPP; + goto out; + } + + /* We don't check peer_shutdown flag here since peer may actually shut + * down, but there can be data in the queue that a local socket can + * receive. + */ + if (sk->sk_shutdown & RCV_SHUTDOWN) { + err = 0; + goto out; + } + + /* It is valid on Linux to pass in a zero-length receive buffer. This + * is not an error. We may as well bail out now. + */ + if (!len) { + err = 0; + goto out; + } + + /* We must not copy less than target bytes into the user's buffer + * before returning successfully, so we wait for the consume queue to + * have that much data to consume before dequeueing. Note that this + * makes it impossible to handle cases where target is greater than the + * queue size. + */ + target = sock_rcvlowat(sk, flags & MSG_WAITALL, len); + if (target >= transport->stream_rcvhiwat(vsk)) { + err = -ENOMEM; + goto out; + } + timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT); + copied = 0; + + err = transport->notify_recv_init(vsk, target, &recv_data); + if (err < 0) + goto out; + + prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); + + while (1) { + s64 ready = vsock_stream_has_data(vsk); + + if (ready < 0) { + /* Invalid queue pair content. XXX This should be + * changed to a connection reset in a later change. + */ + + err = -ENOMEM; + goto out_wait; + } else if (ready > 0) { + ssize_t read; + + err = transport->notify_recv_pre_dequeue( + vsk, target, &recv_data); + if (err < 0) + break; + + read = transport->stream_dequeue( + vsk, msg->msg_iov, + len - copied, flags); + if (read < 0) { + err = -ENOMEM; + break; + } + + copied += read; + + err = transport->notify_recv_post_dequeue( + vsk, target, read, + !(flags & MSG_PEEK), &recv_data); + if (err < 0) + goto out_wait; + + if (read >= target || flags & MSG_PEEK) + break; + + target -= read; + } else { + if (sk->sk_err != 0 || (sk->sk_shutdown & RCV_SHUTDOWN) + || (vsk->peer_shutdown & SEND_SHUTDOWN)) { + break; + } + /* Don't wait for non-blocking sockets. */ + if (timeout == 0) { + err = -EAGAIN; + break; + } + + err = transport->notify_recv_pre_block( + vsk, target, &recv_data); + if (err < 0) + break; + + release_sock(sk); + timeout = schedule_timeout(timeout); + lock_sock(sk); + + if (signal_pending(current)) { + err = sock_intr_errno(timeout); + break; + } else if (timeout == 0) { + err = -EAGAIN; + break; + } + + prepare_to_wait(sk_sleep(sk), &wait, + TASK_INTERRUPTIBLE); + } + } + + if (sk->sk_err) + err = -sk->sk_err; + else if (sk->sk_shutdown & RCV_SHUTDOWN) + err = 0; + + if (copied > 0) { + /* We only do these additional bookkeeping/notification steps + * if we actually copied something out of the queue pair + * instead of just peeking ahead. + */ + + if (!(flags & MSG_PEEK)) { + /* If the other side has shutdown for sending and there + * is nothing more to read, then modify the socket + * state. + */ + if (vsk->peer_shutdown & SEND_SHUTDOWN) { + if (vsock_stream_has_data(vsk) <= 0) { + sk->sk_state = SS_UNCONNECTED; + sock_set_flag(sk, SOCK_DONE); + sk->sk_state_change(sk); + } + } + } + err = copied; + } + +out_wait: + finish_wait(sk_sleep(sk), &wait); +out: + release_sock(sk); + return err; +} +","@@ -1662,8 +1662,6 @@ vsock_stream_recvmsg(struct kiocb *kiocb, + vsk = vsock_sk(sk); + err = 0; + +- msg->msg_namelen = 0; +- + lock_sock(sk); + + if (sk->sk_state != SS_CONNECTED) {",1198,1529,2048 +1426,"gs_main_finit(gs_main_instance * minst, int exit_status, int code) +{ + i_ctx_t *i_ctx_p = minst->i_ctx_p; + int exit_code; + ref error_object; + char *tempnames; + + /* NB: need to free gs_name_table + */ + + /* + * Previous versions of this code closed the devices in the + * device list here. Since these devices are now prototypes, + * they cannot be opened, so they do not need to be closed; + * alloc_restore_all will close dynamically allocated devices. + */ + tempnames = gs_main_tempnames(minst); + +#ifndef PSI_INCLUDED + /* We have to disable BGPrint before we call interp_reclaim() to prevent the + * parent rendering thread initialising for the next page, whilst we are + * removing objects it may want to access - for example, the I/O device table. + * We also have to mess with the BeginPage/EndPage procs so that we don't + * trigger a spurious extra page to be emitted. + */ + if (minst->init_done >= 1) { + gs_main_run_string(minst, + ""/systemdict .systemexec /begin .systemexec \ + /BGPrint /GetDeviceParam .special_op \ + {{ <> setpagedevice} if} if \ + serverdict /.jobsavelevel get 0 eq {/quit} {/stop} ifelse end \ + .systemvar exec"", + 0 , &exit_code, &error_object); + } +#endif + + /* + * Close the ""main"" device, because it may need to write out + * data before destruction. pdfwrite needs so. + */ + if (minst->init_done >= 1) { + int code = 0; + + if (idmemory->reclaim != 0) { + code = interp_reclaim(&minst->i_ctx_p, avm_global); + + if (code < 0) { + ref error_name; + if (tempnames) + free(tempnames); + + if (gs_errorname(i_ctx_p, code, &error_name) >= 0) { + char err_str[32] = {0}; + name_string_ref(imemory, &error_name, &error_name); + memcpy(err_str, error_name.value.const_bytes, r_size(&error_name)); + emprintf2(imemory, ""ERROR: %s (%d) reclaiming the memory while the interpreter finalization.\n"", err_str, code); + } + else { + emprintf1(imemory, ""UNKNOWN ERROR %d reclaiming the memory while the interpreter finalization.\n"", code); + } + return gs_error_Fatal; + } + i_ctx_p = minst->i_ctx_p; /* interp_reclaim could change it. */ + } +#ifndef PSI_INCLUDED + if (i_ctx_p->pgs != NULL && i_ctx_p->pgs->device != NULL) { + gx_device *pdev = i_ctx_p->pgs->device; + const char * dname = pdev->dname; + + /* make sure device doesn't isn't freed by .uninstalldevice */ + rc_adjust(pdev, 1, ""gs_main_finit""); + /* deactivate the device just before we close it for the last time */ + gs_main_run_string(minst, + /* we need to do the 'quit' so we don't loop for input (double quit) */ + "".uninstallpagedevice serverdict \ + /.jobsavelevel get 0 eq {/quit} {/stop} ifelse .systemvar exec"", + 0 , &exit_code, &error_object); + code = gs_closedevice(pdev); + if (code < 0) { + ref error_name; + if (gs_errorname(i_ctx_p, code, &error_name) >= 0) { + char err_str[32] = {0}; + name_string_ref(imemory, &error_name, &error_name); + memcpy(err_str, error_name.value.const_bytes, r_size(&error_name)); + emprintf3(imemory, ""ERROR: %s (%d) on closing %s device.\n"", err_str, code, dname); + } + else { + emprintf2(imemory, ""UNKNOWN ERROR %d closing %s device.\n"", code, dname); + } + } + rc_decrement(pdev, ""gs_main_finit""); /* device might be freed */ + if (exit_status == 0 || exit_status == gs_error_Quit) + exit_status = code; + } +#endif + } + /* Flush stdout and stderr */ + if (minst->init_done >= 2) + gs_main_run_string(minst, + ""(%stdout) (w) file closefile (%stderr) (w) file closefile \ + /systemdict .systemexec /begin .systemexec \ + serverdict /.jobsavelevel get 0 eq {/quit} {/stop} ifelse .systemexec \ + systemdict /savedinitialgstate .forceundef \ + end "", + 0 , &exit_code, &error_object); + gp_readline_finit(minst->readline_data); + i_ctx_p = minst->i_ctx_p; /* get current interp context */ + if (gs_debug_c(':')) { + print_resource_usage(minst, &gs_imemory, ""Final""); + dmprintf1(minst->heap, ""%% Exiting instance 0x%p\n"", minst); + } + /* Do the equivalent of a restore ""past the bottom"". */ + /* This will release all memory, close all open files, etc. */ + if (minst->init_done >= 1) { + gs_memory_t *mem_raw = i_ctx_p->memory.current->non_gc_memory; + i_plugin_holder *h = i_ctx_p->plugin_list; + code = alloc_restore_all(i_ctx_p); + if (code < 0) + emprintf1(mem_raw, + ""ERROR %d while the final restore. See gs/psi/ierrors.h for code explanation.\n"", + code); + i_plugin_finit(mem_raw, h); + } +#ifndef PSI_INCLUDED + /* clean up redirected stdout */ + if (minst->heap->gs_lib_ctx->fstdout2 + && (minst->heap->gs_lib_ctx->fstdout2 != minst->heap->gs_lib_ctx->fstdout) + && (minst->heap->gs_lib_ctx->fstdout2 != minst->heap->gs_lib_ctx->fstderr)) { + fclose(minst->heap->gs_lib_ctx->fstdout2); + minst->heap->gs_lib_ctx->fstdout2 = (FILE *)NULL; + } +#endif + minst->heap->gs_lib_ctx->stdout_is_redirected = 0; + minst->heap->gs_lib_ctx->stdout_to_stderr = 0; + /* remove any temporary files, after ghostscript has closed files */ + if (tempnames) { + char *p = tempnames; + while (*p) { + unlink(p); + p += strlen(p) + 1; + } + free(tempnames); + } +#ifndef PSI_INCLUDED + gs_lib_finit(exit_status, code, minst->heap); +#endif + return exit_status; +} +",0,"gs_main_finit(gs_main_instance * minst, int exit_status, int code) +{ + i_ctx_t *i_ctx_p = minst->i_ctx_p; + int exit_code; + ref error_object; + char *tempnames; + + /* NB: need to free gs_name_table + */ + + /* + * Previous versions of this code closed the devices in the + * device list here. Since these devices are now prototypes, + * they cannot be opened, so they do not need to be closed; + * alloc_restore_all will close dynamically allocated devices. + */ + tempnames = gs_main_tempnames(minst); + +#ifndef PSI_INCLUDED + /* We have to disable BGPrint before we call interp_reclaim() to prevent the + * parent rendering thread initialising for the next page, whilst we are + * removing objects it may want to access - for example, the I/O device table. + * We also have to mess with the BeginPage/EndPage procs so that we don't + * trigger a spurious extra page to be emitted. + */ + if (minst->init_done >= 1) { + gs_main_run_string(minst, + ""/systemdict .systemexec /begin .systemexec \ + /BGPrint /GetDeviceParam .special_op \ + {{ <> setpagedevice} if} if \ + serverdict /.jobsavelevel get 0 eq {/quit} {/stop} ifelse end \ + .systemvar exec"", + 0 , &exit_code, &error_object); + } +#endif + + /* + * Close the ""main"" device, because it may need to write out + * data before destruction. pdfwrite needs so. + */ + if (minst->init_done >= 1) { + int code = 0; + + if (idmemory->reclaim != 0) { + code = interp_reclaim(&minst->i_ctx_p, avm_global); + + if (code < 0) { + ref error_name; + if (tempnames) + free(tempnames); + + if (gs_errorname(i_ctx_p, code, &error_name) >= 0) { + char err_str[32] = {0}; + name_string_ref(imemory, &error_name, &error_name); + memcpy(err_str, error_name.value.const_bytes, r_size(&error_name)); + emprintf2(imemory, ""ERROR: %s (%d) reclaiming the memory while the interpreter finalization.\n"", err_str, code); + } + else { + emprintf1(imemory, ""UNKNOWN ERROR %d reclaiming the memory while the interpreter finalization.\n"", code); + } + return gs_error_Fatal; + } + i_ctx_p = minst->i_ctx_p; /* interp_reclaim could change it. */ + } +#ifndef PSI_INCLUDED + if (i_ctx_p->pgs != NULL && i_ctx_p->pgs->device != NULL) { + gx_device *pdev = i_ctx_p->pgs->device; + const char * dname = pdev->dname; + + /* make sure device doesn't isn't freed by .uninstalldevice */ + rc_adjust(pdev, 1, ""gs_main_finit""); + /* deactivate the device just before we close it for the last time */ + gs_main_run_string(minst, + /* we need to do the 'quit' so we don't loop for input (double quit) */ + "".uninstallpagedevice serverdict \ + /.jobsavelevel get 0 eq {/quit} {/stop} ifelse .systemvar exec"", + 0 , &exit_code, &error_object); + code = gs_closedevice(pdev); + if (code < 0) { + ref error_name; + if (gs_errorname(i_ctx_p, code, &error_name) >= 0) { + char err_str[32] = {0}; + name_string_ref(imemory, &error_name, &error_name); + memcpy(err_str, error_name.value.const_bytes, r_size(&error_name)); + emprintf3(imemory, ""ERROR: %s (%d) on closing %s device.\n"", err_str, code, dname); + } + else { + emprintf2(imemory, ""UNKNOWN ERROR %d closing %s device.\n"", code, dname); + } + } + rc_decrement(pdev, ""gs_main_finit""); /* device might be freed */ + if (exit_status == 0 || exit_status == gs_error_Quit) + exit_status = code; + } +#endif + } + /* Flush stdout and stderr */ + if (minst->init_done >= 2) + gs_main_run_string(minst, + ""(%stdout) (w) file closefile (%stderr) (w) file closefile \ + /systemdict .systemexec /begin .systemexec \ + serverdict /.jobsavelevel get 0 eq {/quit} {/stop} ifelse .systemexec \ + systemdict /savedinitialgstate .forceundef \ + end "", + 0 , &exit_code, &error_object); + gp_readline_finit(minst->readline_data); + i_ctx_p = minst->i_ctx_p; /* get current interp context */ + if (gs_debug_c(':')) { + print_resource_usage(minst, &gs_imemory, ""Final""); + dmprintf1(minst->heap, ""%% Exiting instance 0x%p\n"", minst); + } + /* Do the equivalent of a restore ""past the bottom"". */ + /* This will release all memory, close all open files, etc. */ + if (minst->init_done >= 1) { + gs_memory_t *mem_raw = i_ctx_p->memory.current->non_gc_memory; + i_plugin_holder *h = i_ctx_p->plugin_list; + code = alloc_restore_all(i_ctx_p); + if (code < 0) + emprintf1(mem_raw, + ""ERROR %d while the final restore. See gs/psi/ierrors.h for code explanation.\n"", + code); + i_plugin_finit(mem_raw, h); + } +#ifndef PSI_INCLUDED + /* clean up redirected stdout */ + if (minst->heap->gs_lib_ctx->fstdout2 + && (minst->heap->gs_lib_ctx->fstdout2 != minst->heap->gs_lib_ctx->fstdout) + && (minst->heap->gs_lib_ctx->fstdout2 != minst->heap->gs_lib_ctx->fstderr)) { + fclose(minst->heap->gs_lib_ctx->fstdout2); + minst->heap->gs_lib_ctx->fstdout2 = (FILE *)NULL; + } +#endif + minst->heap->gs_lib_ctx->stdout_is_redirected = 0; + minst->heap->gs_lib_ctx->stdout_to_stderr = 0; + /* remove any temporary files, after ghostscript has closed files */ + if (tempnames) { + char *p = tempnames; + while (*p) { + unlink(p); + p += strlen(p) + 1; + } + free(tempnames); + } +#ifndef PSI_INCLUDED + gs_lib_finit(exit_status, code, minst->heap); +#endif + return exit_status; +} +","@@ -57,6 +57,7 @@ + #include ""ivmspace.h"" + #include ""idisp.h"" /* for setting display device callback */ + #include ""iplugin.h"" ++#include ""zfile.h"" + + #ifdef PACIFY_VALGRIND + #include ""valgrind.h"" +@@ -212,6 +213,7 @@ gs_main_init1(gs_main_instance * minst) + ""the_gs_name_table""); + if (code < 0) + return code; ++ mem->gs_lib_ctx->client_check_file_permission = z_check_file_permissions; + } + code = obj_init(&minst->i_ctx_p, &idmem); /* requires name_init */ + if (code < 0)",1577,1908,2048 +2444,"isdn_net_log_skb(struct sk_buff * skb, isdn_net_local * lp) +{ + /* hopefully, this was set correctly */ + const u_char *p = skb_network_header(skb); + unsigned short proto = ntohs(skb->protocol); + int data_ofs; + ip_ports *ipp; + char addinfo[100]; + + addinfo[0] = '\0'; + /* This check stolen from 2.1.72 dev_queue_xmit_nit() */ + if (p < skb->data || skb->network_header >= skb->tail) { + /* fall back to old isdn_net_log_packet method() */ + char * buf = skb->data; + + printk(KERN_DEBUG ""isdn_net: protocol %04x is buggy, dev %s\n"", skb->protocol, lp->netdev->dev->name); + p = buf; + proto = ETH_P_IP; + switch (lp->p_encap) { + case ISDN_NET_ENCAP_IPTYP: + proto = ntohs(*(__be16 *)&buf[0]); + p = &buf[2]; + break; + case ISDN_NET_ENCAP_ETHER: + proto = ntohs(*(__be16 *)&buf[12]); + p = &buf[14]; + break; + case ISDN_NET_ENCAP_CISCOHDLC: + proto = ntohs(*(__be16 *)&buf[2]); + p = &buf[4]; + break; +#ifdef CONFIG_ISDN_PPP + case ISDN_NET_ENCAP_SYNCPPP: + proto = ntohs(skb->protocol); + p = &buf[IPPP_MAX_HEADER]; + break; +#endif + } + } + data_ofs = ((p[0] & 15) * 4); + switch (proto) { + case ETH_P_IP: + switch (p[9]) { + case 1: + strcpy(addinfo, "" ICMP""); + break; + case 2: + strcpy(addinfo, "" IGMP""); + break; + case 4: + strcpy(addinfo, "" IPIP""); + break; + case 6: + ipp = (ip_ports *) (&p[data_ofs]); + sprintf(addinfo, "" TCP, port: %d -> %d"", ntohs(ipp->source), + ntohs(ipp->dest)); + break; + case 8: + strcpy(addinfo, "" EGP""); + break; + case 12: + strcpy(addinfo, "" PUP""); + break; + case 17: + ipp = (ip_ports *) (&p[data_ofs]); + sprintf(addinfo, "" UDP, port: %d -> %d"", ntohs(ipp->source), + ntohs(ipp->dest)); + break; + case 22: + strcpy(addinfo, "" IDP""); + break; + } + printk(KERN_INFO ""OPEN: %pI4 -> %pI4%s\n"", + p + 12, p + 16, addinfo); + break; + case ETH_P_ARP: + printk(KERN_INFO ""OPEN: ARP %pI4 -> *.*.*.* ?%pI4\n"", + p + 14, p + 24); + break; + } +} +",0,"isdn_net_log_skb(struct sk_buff * skb, isdn_net_local * lp) +{ + /* hopefully, this was set correctly */ + const u_char *p = skb_network_header(skb); + unsigned short proto = ntohs(skb->protocol); + int data_ofs; + ip_ports *ipp; + char addinfo[100]; + + addinfo[0] = '\0'; + /* This check stolen from 2.1.72 dev_queue_xmit_nit() */ + if (p < skb->data || skb->network_header >= skb->tail) { + /* fall back to old isdn_net_log_packet method() */ + char * buf = skb->data; + + printk(KERN_DEBUG ""isdn_net: protocol %04x is buggy, dev %s\n"", skb->protocol, lp->netdev->dev->name); + p = buf; + proto = ETH_P_IP; + switch (lp->p_encap) { + case ISDN_NET_ENCAP_IPTYP: + proto = ntohs(*(__be16 *)&buf[0]); + p = &buf[2]; + break; + case ISDN_NET_ENCAP_ETHER: + proto = ntohs(*(__be16 *)&buf[12]); + p = &buf[14]; + break; + case ISDN_NET_ENCAP_CISCOHDLC: + proto = ntohs(*(__be16 *)&buf[2]); + p = &buf[4]; + break; +#ifdef CONFIG_ISDN_PPP + case ISDN_NET_ENCAP_SYNCPPP: + proto = ntohs(skb->protocol); + p = &buf[IPPP_MAX_HEADER]; + break; +#endif + } + } + data_ofs = ((p[0] & 15) * 4); + switch (proto) { + case ETH_P_IP: + switch (p[9]) { + case 1: + strcpy(addinfo, "" ICMP""); + break; + case 2: + strcpy(addinfo, "" IGMP""); + break; + case 4: + strcpy(addinfo, "" IPIP""); + break; + case 6: + ipp = (ip_ports *) (&p[data_ofs]); + sprintf(addinfo, "" TCP, port: %d -> %d"", ntohs(ipp->source), + ntohs(ipp->dest)); + break; + case 8: + strcpy(addinfo, "" EGP""); + break; + case 12: + strcpy(addinfo, "" PUP""); + break; + case 17: + ipp = (ip_ports *) (&p[data_ofs]); + sprintf(addinfo, "" UDP, port: %d -> %d"", ntohs(ipp->source), + ntohs(ipp->dest)); + break; + case 22: + strcpy(addinfo, "" IDP""); + break; + } + printk(KERN_INFO ""OPEN: %pI4 -> %pI4%s\n"", + p + 12, p + 16, addinfo); + break; + case ETH_P_ARP: + printk(KERN_INFO ""OPEN: ARP %pI4 -> *.*.*.* ?%pI4\n"", + p + 14, p + 24); + break; + } +} +","@@ -2532,6 +2532,9 @@ static void _isdn_setup(struct net_device *dev) + + /* Setup the generic properties */ + dev->flags = IFF_NOARP|IFF_POINTOPOINT; ++ ++ /* isdn prepends a header in the tx path, can't share skbs */ ++ dev->priv_flags &= ~IFF_TX_SKB_SHARING; + dev->header_ops = NULL; + dev->netdev_ops = &isdn_netdev_ops; + ",697,1028,2048 +5916,"static ssize_t generic_perform_write_2copy(struct file *file, + struct iov_iter *i, loff_t pos) +{ + struct address_space *mapping = file->f_mapping; + const struct address_space_operations *a_ops = mapping->a_ops; + struct inode *inode = mapping->host; + long status = 0; + ssize_t written = 0; + + do { + struct page *src_page; + struct page *page; + pgoff_t index; /* Pagecache index for current page */ + unsigned long offset; /* Offset into pagecache page */ + unsigned long bytes; /* Bytes to write to page */ + size_t copied; /* Bytes copied from user */ + + offset = (pos & (PAGE_CACHE_SIZE - 1)); + index = pos >> PAGE_CACHE_SHIFT; + bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset, + iov_iter_count(i)); + + /* + * a non-NULL src_page indicates that we're doing the + * copy via get_user_pages and kmap. + */ + src_page = NULL; + + /* + * Bring in the user page that we will copy from _first_. + * Otherwise there's a nasty deadlock on copying from the + * same page as we're writing to, without it being marked + * up-to-date. + * + * Not only is this an optimisation, but it is also required + * to check that the address is actually valid, when atomic + * usercopies are used, below. + */ + if (unlikely(iov_iter_fault_in_readable(i, bytes))) { + status = -EFAULT; + break; + } + + page = __grab_cache_page(mapping, index); + if (!page) { + status = -ENOMEM; + break; + } + + /* + * non-uptodate pages cannot cope with short copies, and we + * cannot take a pagefault with the destination page locked. + * So pin the source page to copy it. + */ + if (!PageUptodate(page) && !segment_eq(get_fs(), KERNEL_DS)) { + unlock_page(page); + + src_page = alloc_page(GFP_KERNEL); + if (!src_page) { + page_cache_release(page); + status = -ENOMEM; + break; + } + + /* + * Cannot get_user_pages with a page locked for the + * same reason as we can't take a page fault with a + * page locked (as explained below). + */ + copied = iov_iter_copy_from_user(src_page, i, + offset, bytes); + if (unlikely(copied == 0)) { + status = -EFAULT; + page_cache_release(page); + page_cache_release(src_page); + break; + } + bytes = copied; + + lock_page(page); + /* + * Can't handle the page going uptodate here, because + * that means we would use non-atomic usercopies, which + * zero out the tail of the page, which can cause + * zeroes to become transiently visible. We could just + * use a non-zeroing copy, but the APIs aren't too + * consistent. + */ + if (unlikely(!page->mapping || PageUptodate(page))) { + unlock_page(page); + page_cache_release(page); + page_cache_release(src_page); + continue; + } + } + + status = a_ops->prepare_write(file, page, offset, offset+bytes); + if (unlikely(status)) + goto fs_write_aop_error; + + if (!src_page) { + /* + * Must not enter the pagefault handler here, because + * we hold the page lock, so we might recursively + * deadlock on the same lock, or get an ABBA deadlock + * against a different lock, or against the mmap_sem + * (which nests outside the page lock). So increment + * preempt count, and use _atomic usercopies. + * + * The page is uptodate so we are OK to encounter a + * short copy: if unmodified parts of the page are + * marked dirty and written out to disk, it doesn't + * really matter. + */ + pagefault_disable(); + copied = iov_iter_copy_from_user_atomic(page, i, + offset, bytes); + pagefault_enable(); + } else { + void *src, *dst; + src = kmap_atomic(src_page, KM_USER0); + dst = kmap_atomic(page, KM_USER1); + memcpy(dst + offset, src + offset, bytes); + kunmap_atomic(dst, KM_USER1); + kunmap_atomic(src, KM_USER0); + copied = bytes; + } + flush_dcache_page(page); + + status = a_ops->commit_write(file, page, offset, offset+bytes); + if (unlikely(status < 0)) + goto fs_write_aop_error; + if (unlikely(status > 0)) /* filesystem did partial write */ + copied = min_t(size_t, copied, status); + + unlock_page(page); + mark_page_accessed(page); + page_cache_release(page); + if (src_page) + page_cache_release(src_page); + + iov_iter_advance(i, copied); + pos += copied; + written += copied; + + balance_dirty_pages_ratelimited(mapping); + cond_resched(); + continue; + +fs_write_aop_error: + unlock_page(page); + page_cache_release(page); + if (src_page) + page_cache_release(src_page); + + /* + * prepare_write() may have instantiated a few blocks + * outside i_size. Trim these off again. Don't need + * i_size_read because we hold i_mutex. + */ + if (pos + bytes > inode->i_size) + vmtruncate(inode, inode->i_size); + break; + } while (iov_iter_count(i)); + + return written ? written : status; +} +",0,"static ssize_t generic_perform_write_2copy(struct file *file, + struct iov_iter *i, loff_t pos) +{ + struct address_space *mapping = file->f_mapping; + const struct address_space_operations *a_ops = mapping->a_ops; + struct inode *inode = mapping->host; + long status = 0; + ssize_t written = 0; + + do { + struct page *src_page; + struct page *page; + pgoff_t index; /* Pagecache index for current page */ + unsigned long offset; /* Offset into pagecache page */ + unsigned long bytes; /* Bytes to write to page */ + size_t copied; /* Bytes copied from user */ + + offset = (pos & (PAGE_CACHE_SIZE - 1)); + index = pos >> PAGE_CACHE_SHIFT; + bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset, + iov_iter_count(i)); + + /* + * a non-NULL src_page indicates that we're doing the + * copy via get_user_pages and kmap. + */ + src_page = NULL; + + /* + * Bring in the user page that we will copy from _first_. + * Otherwise there's a nasty deadlock on copying from the + * same page as we're writing to, without it being marked + * up-to-date. + * + * Not only is this an optimisation, but it is also required + * to check that the address is actually valid, when atomic + * usercopies are used, below. + */ + if (unlikely(iov_iter_fault_in_readable(i, bytes))) { + status = -EFAULT; + break; + } + + page = __grab_cache_page(mapping, index); + if (!page) { + status = -ENOMEM; + break; + } + + /* + * non-uptodate pages cannot cope with short copies, and we + * cannot take a pagefault with the destination page locked. + * So pin the source page to copy it. + */ + if (!PageUptodate(page) && !segment_eq(get_fs(), KERNEL_DS)) { + unlock_page(page); + + src_page = alloc_page(GFP_KERNEL); + if (!src_page) { + page_cache_release(page); + status = -ENOMEM; + break; + } + + /* + * Cannot get_user_pages with a page locked for the + * same reason as we can't take a page fault with a + * page locked (as explained below). + */ + copied = iov_iter_copy_from_user(src_page, i, + offset, bytes); + if (unlikely(copied == 0)) { + status = -EFAULT; + page_cache_release(page); + page_cache_release(src_page); + break; + } + bytes = copied; + + lock_page(page); + /* + * Can't handle the page going uptodate here, because + * that means we would use non-atomic usercopies, which + * zero out the tail of the page, which can cause + * zeroes to become transiently visible. We could just + * use a non-zeroing copy, but the APIs aren't too + * consistent. + */ + if (unlikely(!page->mapping || PageUptodate(page))) { + unlock_page(page); + page_cache_release(page); + page_cache_release(src_page); + continue; + } + } + + status = a_ops->prepare_write(file, page, offset, offset+bytes); + if (unlikely(status)) + goto fs_write_aop_error; + + if (!src_page) { + /* + * Must not enter the pagefault handler here, because + * we hold the page lock, so we might recursively + * deadlock on the same lock, or get an ABBA deadlock + * against a different lock, or against the mmap_sem + * (which nests outside the page lock). So increment + * preempt count, and use _atomic usercopies. + * + * The page is uptodate so we are OK to encounter a + * short copy: if unmodified parts of the page are + * marked dirty and written out to disk, it doesn't + * really matter. + */ + pagefault_disable(); + copied = iov_iter_copy_from_user_atomic(page, i, + offset, bytes); + pagefault_enable(); + } else { + void *src, *dst; + src = kmap_atomic(src_page, KM_USER0); + dst = kmap_atomic(page, KM_USER1); + memcpy(dst + offset, src + offset, bytes); + kunmap_atomic(dst, KM_USER1); + kunmap_atomic(src, KM_USER0); + copied = bytes; + } + flush_dcache_page(page); + + status = a_ops->commit_write(file, page, offset, offset+bytes); + if (unlikely(status < 0)) + goto fs_write_aop_error; + if (unlikely(status > 0)) /* filesystem did partial write */ + copied = min_t(size_t, copied, status); + + unlock_page(page); + mark_page_accessed(page); + page_cache_release(page); + if (src_page) + page_cache_release(src_page); + + iov_iter_advance(i, copied); + pos += copied; + written += copied; + + balance_dirty_pages_ratelimited(mapping); + cond_resched(); + continue; + +fs_write_aop_error: + unlock_page(page); + page_cache_release(page); + if (src_page) + page_cache_release(src_page); + + /* + * prepare_write() may have instantiated a few blocks + * outside i_size. Trim these off again. Don't need + * i_size_read because we hold i_mutex. + */ + if (pos + bytes > inode->i_size) + vmtruncate(inode, inode->i_size); + break; + } while (iov_iter_count(i)); + + return written ? written : status; +} +","@@ -1750,7 +1750,11 @@ static void __iov_iter_advance_iov(struct iov_iter *i, size_t bytes) + const struct iovec *iov = i->iov; + size_t base = i->iov_offset; + +- while (bytes) { ++ /* ++ * The !iov->iov_len check ensures we skip over unlikely ++ * zero-length segments. ++ */ ++ while (bytes || !iov->iov_len) { + int copy = min(bytes, iov->iov_len - base); + + bytes -= copy; +@@ -2268,6 +2272,7 @@ static ssize_t generic_perform_write(struct file *file, + + cond_resched(); + ++ iov_iter_advance(i, copied); + if (unlikely(copied == 0)) { + /* + * If we were unable to copy any data at all, we must +@@ -2281,7 +2286,6 @@ static ssize_t generic_perform_write(struct file *file, + iov_iter_single_seg_count(i)); + goto again; + } +- iov_iter_advance(i, copied); + pos += copied; + written += copied; + ",1268,1599,2048 +17788,"datum_to_json(Datum val, bool is_null, StringInfo result, + JsonTypeCategory tcategory, Oid outfuncoid, + bool key_scalar) +{ + char *outputstr; + text *jsontext; + + /* callers are expected to ensure that null keys are not passed in */ + char *outputstr; + text *jsontext; + + /* callers are expected to ensure that null keys are not passed in */ + Assert(!(key_scalar && is_null)); + + if (key_scalar && + (tcategory == JSONTYPE_ARRAY || + tcategory == JSONTYPE_COMPOSITE || + tcategory == JSONTYPE_JSON || + tcategory == JSONTYPE_CAST)) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg(""key value must be scalar, not array, composite, or json""))); + + switch (tcategory) + { + case JSONTYPE_ARRAY: + array_to_json_internal(val, result, false); + break; + case JSONTYPE_COMPOSITE: + composite_to_json(val, result, false); + break; + case JSONTYPE_BOOL: + outputstr = DatumGetBool(val) ? ""true"" : ""false""; + if (key_scalar) + escape_json(result, outputstr); + else + appendStringInfoString(result, outputstr); + break; + case JSONTYPE_NUMERIC: + outputstr = OidOutputFunctionCall(outfuncoid, val); + + /* + * Don't call escape_json for a non-key if it's a valid JSON + * number. + */ + if (!key_scalar && IsValidJsonNumber(outputstr, strlen(outputstr))) + appendStringInfoString(result, outputstr); + else + escape_json(result, outputstr); + pfree(outputstr); + break; + case JSONTYPE_DATE: + { + DateADT date; + struct pg_tm tm; + char buf[MAXDATELEN + 1]; + + date = DatumGetDateADT(val); + + if (DATE_NOT_FINITE(date)) + { + /* we have to format infinity ourselves */ + appendStringInfoString(result, DT_INFINITY); + } + else + { + j2date(date + POSTGRES_EPOCH_JDATE, + &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday)); + EncodeDateOnly(&tm, USE_XSD_DATES, buf); + appendStringInfo(result, ""\""%s\"""", buf); + } + } + break; + case JSONTYPE_TIMESTAMP: + { + Timestamp timestamp; + struct pg_tm tm; + fsec_t fsec; + char buf[MAXDATELEN + 1]; + + timestamp = DatumGetTimestamp(val); + + if (TIMESTAMP_NOT_FINITE(timestamp)) + { + /* we have to format infinity ourselves */ + appendStringInfoString(result, DT_INFINITY); + } + else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0) + { + EncodeDateTime(&tm, fsec, false, 0, NULL, USE_XSD_DATES, buf); + appendStringInfo(result, ""\""%s\"""", buf); + } + else + ereport(ERROR, + (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE), + errmsg(""timestamp out of range""))); + } + break; + case JSONTYPE_TIMESTAMPTZ: + { + TimestampTz timestamp; + struct pg_tm tm; + int tz; + fsec_t fsec; + const char *tzn = NULL; + char buf[MAXDATELEN + 1]; + + timestamp = DatumGetTimestamp(val); + + if (TIMESTAMP_NOT_FINITE(timestamp)) + { + /* we have to format infinity ourselves */ + appendStringInfoString(result, DT_INFINITY); + } + else if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) == 0) + { + EncodeDateTime(&tm, fsec, true, tz, tzn, USE_XSD_DATES, buf); + appendStringInfo(result, ""\""%s\"""", buf); + } + else + ereport(ERROR, + (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE), + errmsg(""timestamp out of range""))); + } + break; + case JSONTYPE_JSON: + /* JSON and JSONB output will already be escaped */ + outputstr = OidOutputFunctionCall(outfuncoid, val); + appendStringInfoString(result, outputstr); + pfree(outputstr); + break; + case JSONTYPE_CAST: + /* outfuncoid refers to a cast function, not an output function */ + jsontext = DatumGetTextP(OidFunctionCall1(outfuncoid, val)); + outputstr = text_to_cstring(jsontext); + appendStringInfoString(result, outputstr); + pfree(outputstr); + pfree(jsontext); + break; + default: + outputstr = OidOutputFunctionCall(outfuncoid, val); + escape_json(result, outputstr); + pfree(outputstr); + break; + } +} +",1,"datum_to_json(Datum val, bool is_null, StringInfo result, + JsonTypeCategory tcategory, Oid outfuncoid, + bool key_scalar) +{ + char *outputstr; + text *jsontext; + + /* callers are expected to ensure that null keys are not passed in */ + char *outputstr; + text *jsontext; + + check_stack_depth(); + + /* callers are expected to ensure that null keys are not passed in */ + Assert(!(key_scalar && is_null)); + + if (key_scalar && + (tcategory == JSONTYPE_ARRAY || + tcategory == JSONTYPE_COMPOSITE || + tcategory == JSONTYPE_JSON || + tcategory == JSONTYPE_CAST)) + ereport(ERROR, + (errcode(ERRCODE_INVALID_PARAMETER_VALUE), + errmsg(""key value must be scalar, not array, composite, or json""))); + + switch (tcategory) + { + case JSONTYPE_ARRAY: + array_to_json_internal(val, result, false); + break; + case JSONTYPE_COMPOSITE: + composite_to_json(val, result, false); + break; + case JSONTYPE_BOOL: + outputstr = DatumGetBool(val) ? ""true"" : ""false""; + if (key_scalar) + escape_json(result, outputstr); + else + appendStringInfoString(result, outputstr); + break; + case JSONTYPE_NUMERIC: + outputstr = OidOutputFunctionCall(outfuncoid, val); + + /* + * Don't call escape_json for a non-key if it's a valid JSON + * number. + */ + if (!key_scalar && IsValidJsonNumber(outputstr, strlen(outputstr))) + appendStringInfoString(result, outputstr); + else + escape_json(result, outputstr); + pfree(outputstr); + break; + case JSONTYPE_DATE: + { + DateADT date; + struct pg_tm tm; + char buf[MAXDATELEN + 1]; + + date = DatumGetDateADT(val); + + if (DATE_NOT_FINITE(date)) + { + /* we have to format infinity ourselves */ + appendStringInfoString(result, DT_INFINITY); + } + else + { + j2date(date + POSTGRES_EPOCH_JDATE, + &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday)); + EncodeDateOnly(&tm, USE_XSD_DATES, buf); + appendStringInfo(result, ""\""%s\"""", buf); + } + } + break; + case JSONTYPE_TIMESTAMP: + { + Timestamp timestamp; + struct pg_tm tm; + fsec_t fsec; + char buf[MAXDATELEN + 1]; + + timestamp = DatumGetTimestamp(val); + + if (TIMESTAMP_NOT_FINITE(timestamp)) + { + /* we have to format infinity ourselves */ + appendStringInfoString(result, DT_INFINITY); + } + else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0) + { + EncodeDateTime(&tm, fsec, false, 0, NULL, USE_XSD_DATES, buf); + appendStringInfo(result, ""\""%s\"""", buf); + } + else + ereport(ERROR, + (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE), + errmsg(""timestamp out of range""))); + } + break; + case JSONTYPE_TIMESTAMPTZ: + { + TimestampTz timestamp; + struct pg_tm tm; + int tz; + fsec_t fsec; + const char *tzn = NULL; + char buf[MAXDATELEN + 1]; + + timestamp = DatumGetTimestamp(val); + + if (TIMESTAMP_NOT_FINITE(timestamp)) + { + /* we have to format infinity ourselves */ + appendStringInfoString(result, DT_INFINITY); + } + else if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) == 0) + { + EncodeDateTime(&tm, fsec, true, tz, tzn, USE_XSD_DATES, buf); + appendStringInfo(result, ""\""%s\"""", buf); + } + else + ereport(ERROR, + (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE), + errmsg(""timestamp out of range""))); + } + break; + case JSONTYPE_JSON: + /* JSON and JSONB output will already be escaped */ + outputstr = OidOutputFunctionCall(outfuncoid, val); + appendStringInfoString(result, outputstr); + pfree(outputstr); + break; + case JSONTYPE_CAST: + /* outfuncoid refers to a cast function, not an output function */ + jsontext = DatumGetTextP(OidFunctionCall1(outfuncoid, val)); + outputstr = text_to_cstring(jsontext); + appendStringInfoString(result, outputstr); + pfree(outputstr); + pfree(jsontext); + break; + default: + outputstr = OidOutputFunctionCall(outfuncoid, val); + escape_json(result, outputstr); + pfree(outputstr); + break; + } +} +","@@ -490,6 +490,8 @@ parse_object(JsonLexContext *lex, JsonSemAction *sem) + json_struct_action oend = sem->object_end; + JsonTokenType tok; + ++ check_stack_depth(); ++ + if (ostart != NULL) + (*ostart) (sem->semstate); + +@@ -568,6 +570,8 @@ parse_array(JsonLexContext *lex, JsonSemAction *sem) + json_struct_action astart = sem->array_start; + json_struct_action aend = sem->array_end; + ++ check_stack_depth(); ++ + if (astart != NULL) + (*astart) (sem->semstate); + +@@ -1433,6 +1437,8 @@ datum_to_json(Datum val, bool is_null, StringInfo result, + char *outputstr; + text *jsontext; + ++ check_stack_depth(); ++ + /* callers are expected to ensure that null keys are not passed in */ + Assert(!(key_scalar && is_null)); + ",1100,1431,2048 +8126,"void xinfoCommand(client *c) { + const char *help[] = { +""CONSUMERS -- Show consumer groups of group ."", +""GROUPS -- Show the stream consumer groups."", +""STREAM -- Show information about the stream."", +""HELP -- Print this help."", +NULL + }; + stream *s = NULL; + char *opt; + robj *key; + + /* HELP is special. Handle it ASAP. */ + if (!strcasecmp(c->argv[1]->ptr,""HELP"")) { + addReplyHelp(c, help); + return; + } else if (c->argc < 3) { + addReplyError(c,""syntax error, try 'XINFO HELP'""); + return; + } + + /* With the exception of HELP handled before any other sub commands, all + * the ones are in the form of "" "". */ + opt = c->argv[1]->ptr; + key = c->argv[2]; + + /* Lookup the key now, this is common for all the subcommands but HELP. */ + robj *o = lookupKeyWriteOrReply(c,key,shared.nokeyerr); + if (o == NULL) return; + s = o->ptr; + + /* Dispatch the different subcommands. */ + if (!strcasecmp(opt,""CONSUMERS"") && c->argc == 4) { + /* XINFO CONSUMERS . */ + streamCG *cg = streamLookupCG(s,c->argv[3]->ptr); + if (cg == NULL) { + addReplyErrorFormat(c, ""-NOGROUP No such consumer group '%s' "" + ""for key name '%s'"", + (char*)c->argv[3]->ptr, (char*)key->ptr); + return; + } + + addReplyMultiBulkLen(c,raxSize(cg->consumers)); + raxIterator ri; + raxStart(&ri,cg->consumers); + raxSeek(&ri,""^"",NULL,0); + mstime_t now = mstime(); + while(raxNext(&ri)) { + streamConsumer *consumer = ri.data; + mstime_t idle = now - consumer->seen_time; + if (idle < 0) idle = 0; + + addReplyMultiBulkLen(c,6); + addReplyStatus(c,""name""); + addReplyBulkCBuffer(c,consumer->name,sdslen(consumer->name)); + addReplyStatus(c,""pending""); + addReplyLongLong(c,raxSize(consumer->pel)); + addReplyStatus(c,""idle""); + addReplyLongLong(c,idle); + } + raxStop(&ri); + } else if (!strcasecmp(opt,""GROUPS"") && c->argc == 3) { + /* XINFO GROUPS . */ + if (s->cgroups == NULL) { + addReplyMultiBulkLen(c,0); + return; + } + + addReplyMultiBulkLen(c,raxSize(s->cgroups)); + raxIterator ri; + raxStart(&ri,s->cgroups); + raxSeek(&ri,""^"",NULL,0); + while(raxNext(&ri)) { + streamCG *cg = ri.data; + addReplyMultiBulkLen(c,6); + addReplyStatus(c,""name""); + addReplyBulkCBuffer(c,ri.key,ri.key_len); + addReplyStatus(c,""consumers""); + addReplyLongLong(c,raxSize(cg->consumers)); + addReplyStatus(c,""pending""); + addReplyLongLong(c,raxSize(cg->pel)); + } + raxStop(&ri); + } else if (!strcasecmp(opt,""STREAM"") && c->argc == 3) { + /* XINFO STREAM (or the alias XINFO ). */ + addReplyMultiBulkLen(c,12); + addReplyStatus(c,""length""); + addReplyLongLong(c,s->length); + addReplyStatus(c,""radix-tree-keys""); + addReplyLongLong(c,raxSize(s->rax)); + addReplyStatus(c,""radix-tree-nodes""); + addReplyLongLong(c,s->rax->numnodes); + addReplyStatus(c,""groups""); + addReplyLongLong(c,s->cgroups ? raxSize(s->cgroups) : 0); + + /* To emit the first/last entry we us the streamReplyWithRange() + * API. */ + int count; + streamID start, end; + start.ms = start.seq = 0; + end.ms = end.seq = UINT64_MAX; + addReplyStatus(c,""first-entry""); + count = streamReplyWithRange(c,s,&start,&end,1,0,NULL,NULL, + STREAM_RWR_RAWENTRIES,NULL); + if (!count) addReply(c,shared.nullbulk); + addReplyStatus(c,""last-entry""); + count = streamReplyWithRange(c,s,&start,&end,1,1,NULL,NULL, + STREAM_RWR_RAWENTRIES,NULL); + if (!count) addReply(c,shared.nullbulk); + } else { + addReplyError(c,""syntax error, try 'XINFO HELP'""); + } +} +",0,"void xinfoCommand(client *c) { + const char *help[] = { +""CONSUMERS -- Show consumer groups of group ."", +""GROUPS -- Show the stream consumer groups."", +""STREAM -- Show information about the stream."", +""HELP -- Print this help."", +NULL + }; + stream *s = NULL; + char *opt; + robj *key; + + /* HELP is special. Handle it ASAP. */ + if (!strcasecmp(c->argv[1]->ptr,""HELP"")) { + addReplyHelp(c, help); + return; + } else if (c->argc < 3) { + addReplyError(c,""syntax error, try 'XINFO HELP'""); + return; + } + + /* With the exception of HELP handled before any other sub commands, all + * the ones are in the form of "" "". */ + opt = c->argv[1]->ptr; + key = c->argv[2]; + + /* Lookup the key now, this is common for all the subcommands but HELP. */ + robj *o = lookupKeyWriteOrReply(c,key,shared.nokeyerr); + if (o == NULL) return; + s = o->ptr; + + /* Dispatch the different subcommands. */ + if (!strcasecmp(opt,""CONSUMERS"") && c->argc == 4) { + /* XINFO CONSUMERS . */ + streamCG *cg = streamLookupCG(s,c->argv[3]->ptr); + if (cg == NULL) { + addReplyErrorFormat(c, ""-NOGROUP No such consumer group '%s' "" + ""for key name '%s'"", + (char*)c->argv[3]->ptr, (char*)key->ptr); + return; + } + + addReplyMultiBulkLen(c,raxSize(cg->consumers)); + raxIterator ri; + raxStart(&ri,cg->consumers); + raxSeek(&ri,""^"",NULL,0); + mstime_t now = mstime(); + while(raxNext(&ri)) { + streamConsumer *consumer = ri.data; + mstime_t idle = now - consumer->seen_time; + if (idle < 0) idle = 0; + + addReplyMultiBulkLen(c,6); + addReplyStatus(c,""name""); + addReplyBulkCBuffer(c,consumer->name,sdslen(consumer->name)); + addReplyStatus(c,""pending""); + addReplyLongLong(c,raxSize(consumer->pel)); + addReplyStatus(c,""idle""); + addReplyLongLong(c,idle); + } + raxStop(&ri); + } else if (!strcasecmp(opt,""GROUPS"") && c->argc == 3) { + /* XINFO GROUPS . */ + if (s->cgroups == NULL) { + addReplyMultiBulkLen(c,0); + return; + } + + addReplyMultiBulkLen(c,raxSize(s->cgroups)); + raxIterator ri; + raxStart(&ri,s->cgroups); + raxSeek(&ri,""^"",NULL,0); + while(raxNext(&ri)) { + streamCG *cg = ri.data; + addReplyMultiBulkLen(c,6); + addReplyStatus(c,""name""); + addReplyBulkCBuffer(c,ri.key,ri.key_len); + addReplyStatus(c,""consumers""); + addReplyLongLong(c,raxSize(cg->consumers)); + addReplyStatus(c,""pending""); + addReplyLongLong(c,raxSize(cg->pel)); + } + raxStop(&ri); + } else if (!strcasecmp(opt,""STREAM"") && c->argc == 3) { + /* XINFO STREAM (or the alias XINFO ). */ + addReplyMultiBulkLen(c,12); + addReplyStatus(c,""length""); + addReplyLongLong(c,s->length); + addReplyStatus(c,""radix-tree-keys""); + addReplyLongLong(c,raxSize(s->rax)); + addReplyStatus(c,""radix-tree-nodes""); + addReplyLongLong(c,s->rax->numnodes); + addReplyStatus(c,""groups""); + addReplyLongLong(c,s->cgroups ? raxSize(s->cgroups) : 0); + + /* To emit the first/last entry we us the streamReplyWithRange() + * API. */ + int count; + streamID start, end; + start.ms = start.seq = 0; + end.ms = end.seq = UINT64_MAX; + addReplyStatus(c,""first-entry""); + count = streamReplyWithRange(c,s,&start,&end,1,0,NULL,NULL, + STREAM_RWR_RAWENTRIES,NULL); + if (!count) addReply(c,shared.nullbulk); + addReplyStatus(c,""last-entry""); + count = streamReplyWithRange(c,s,&start,&end,1,1,NULL,NULL, + STREAM_RWR_RAWENTRIES,NULL); + if (!count) addReply(c,shared.nullbulk); + } else { + addReplyError(c,""syntax error, try 'XINFO HELP'""); + } +} +","@@ -1576,7 +1576,7 @@ NULL + /* Lookup the key now, this is common for all the subcommands but HELP. */ + if (c->argc >= 4) { + robj *o = lookupKeyWriteOrReply(c,c->argv[2],shared.nokeyerr); +- if (o == NULL) return; ++ if (o == NULL || checkType(c,o,OBJ_STREAM)) return; + s = o->ptr; + grpname = c->argv[3]->ptr; + ",1110,1441,2048 +651,"PHP_MINIT_FUNCTION(date) +{ + REGISTER_INI_ENTRIES(); + date_register_classes(TSRMLS_C); +/* + * RFC4287, Section 3.3: http://www.ietf.org/rfc/rfc4287.txt + * A Date construct is an element whose content MUST conform to the + * ""date-time"" production in [RFC3339]. In addition, an uppercase ""T"" + * character MUST be used to separate date and time, and an uppercase + * ""Z"" character MUST be present in the absence of a numeric time zone offset. + */ + REGISTER_STRING_CONSTANT(""DATE_ATOM"", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); +/* + * Preliminary specification: http://wp.netscape.com/newsref/std/cookie_spec.html + * ""This is based on RFC 822, RFC 850, RFC 1036, and RFC 1123, + * with the variations that the only legal time zone is GMT + * and the separators between the elements of the date must be dashes."" + */ + REGISTER_STRING_CONSTANT(""DATE_COOKIE"", DATE_FORMAT_COOKIE, CONST_CS | CONST_PERSISTENT); + REGISTER_STRING_CONSTANT(""DATE_ISO8601"", DATE_FORMAT_ISO8601, CONST_CS | CONST_PERSISTENT); + REGISTER_STRING_CONSTANT(""DATE_RFC822"", DATE_FORMAT_RFC822, CONST_CS | CONST_PERSISTENT); + REGISTER_STRING_CONSTANT(""DATE_RFC850"", DATE_FORMAT_RFC850, CONST_CS | CONST_PERSISTENT); + REGISTER_STRING_CONSTANT(""DATE_RFC1036"", DATE_FORMAT_RFC1036, CONST_CS | CONST_PERSISTENT); + REGISTER_STRING_CONSTANT(""DATE_RFC1123"", DATE_FORMAT_RFC1123, CONST_CS | CONST_PERSISTENT); + REGISTER_STRING_CONSTANT(""DATE_RFC2822"", DATE_FORMAT_RFC2822, CONST_CS | CONST_PERSISTENT); + REGISTER_STRING_CONSTANT(""DATE_RFC3339"", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); +/* + * RSS 2.0 Specification: http://blogs.law.harvard.edu/tech/rss + * ""All date-times in RSS conform to the Date and Time Specification of RFC 822, + * with the exception that the year may be expressed with two characters or four characters (four preferred)"" + */ + REGISTER_STRING_CONSTANT(""DATE_RSS"", DATE_FORMAT_RFC1123, CONST_CS | CONST_PERSISTENT); + REGISTER_STRING_CONSTANT(""DATE_W3C"", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); + + REGISTER_LONG_CONSTANT(""SUNFUNCS_RET_TIMESTAMP"", SUNFUNCS_RET_TIMESTAMP, CONST_CS | CONST_PERSISTENT); + REGISTER_LONG_CONSTANT(""SUNFUNCS_RET_STRING"", SUNFUNCS_RET_STRING, CONST_CS | CONST_PERSISTENT); + REGISTER_LONG_CONSTANT(""SUNFUNCS_RET_DOUBLE"", SUNFUNCS_RET_DOUBLE, CONST_CS | CONST_PERSISTENT); + + php_date_global_timezone_db = NULL; + php_date_global_timezone_db_enabled = 0; + DATEG(last_errors) = NULL; + return SUCCESS; +} +",0,"PHP_MINIT_FUNCTION(date) +{ + REGISTER_INI_ENTRIES(); + date_register_classes(TSRMLS_C); +/* + * RFC4287, Section 3.3: http://www.ietf.org/rfc/rfc4287.txt + * A Date construct is an element whose content MUST conform to the + * ""date-time"" production in [RFC3339]. In addition, an uppercase ""T"" + * character MUST be used to separate date and time, and an uppercase + * ""Z"" character MUST be present in the absence of a numeric time zone offset. + */ + REGISTER_STRING_CONSTANT(""DATE_ATOM"", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); +/* + * Preliminary specification: http://wp.netscape.com/newsref/std/cookie_spec.html + * ""This is based on RFC 822, RFC 850, RFC 1036, and RFC 1123, + * with the variations that the only legal time zone is GMT + * and the separators between the elements of the date must be dashes."" + */ + REGISTER_STRING_CONSTANT(""DATE_COOKIE"", DATE_FORMAT_COOKIE, CONST_CS | CONST_PERSISTENT); + REGISTER_STRING_CONSTANT(""DATE_ISO8601"", DATE_FORMAT_ISO8601, CONST_CS | CONST_PERSISTENT); + REGISTER_STRING_CONSTANT(""DATE_RFC822"", DATE_FORMAT_RFC822, CONST_CS | CONST_PERSISTENT); + REGISTER_STRING_CONSTANT(""DATE_RFC850"", DATE_FORMAT_RFC850, CONST_CS | CONST_PERSISTENT); + REGISTER_STRING_CONSTANT(""DATE_RFC1036"", DATE_FORMAT_RFC1036, CONST_CS | CONST_PERSISTENT); + REGISTER_STRING_CONSTANT(""DATE_RFC1123"", DATE_FORMAT_RFC1123, CONST_CS | CONST_PERSISTENT); + REGISTER_STRING_CONSTANT(""DATE_RFC2822"", DATE_FORMAT_RFC2822, CONST_CS | CONST_PERSISTENT); + REGISTER_STRING_CONSTANT(""DATE_RFC3339"", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); +/* + * RSS 2.0 Specification: http://blogs.law.harvard.edu/tech/rss + * ""All date-times in RSS conform to the Date and Time Specification of RFC 822, + * with the exception that the year may be expressed with two characters or four characters (four preferred)"" + */ + REGISTER_STRING_CONSTANT(""DATE_RSS"", DATE_FORMAT_RFC1123, CONST_CS | CONST_PERSISTENT); + REGISTER_STRING_CONSTANT(""DATE_W3C"", DATE_FORMAT_RFC3339, CONST_CS | CONST_PERSISTENT); + + REGISTER_LONG_CONSTANT(""SUNFUNCS_RET_TIMESTAMP"", SUNFUNCS_RET_TIMESTAMP, CONST_CS | CONST_PERSISTENT); + REGISTER_LONG_CONSTANT(""SUNFUNCS_RET_STRING"", SUNFUNCS_RET_STRING, CONST_CS | CONST_PERSISTENT); + REGISTER_LONG_CONSTANT(""SUNFUNCS_RET_DOUBLE"", SUNFUNCS_RET_DOUBLE, CONST_CS | CONST_PERSISTENT); + + php_date_global_timezone_db = NULL; + php_date_global_timezone_db_enabled = 0; + DATEG(last_errors) = NULL; + return SUCCESS; +} +","@@ -2807,12 +2807,9 @@ static int php_date_initialize_from_hash(php_date_obj **dateobj, HashTable *myht + timelib_tzinfo *tzi; + php_timezone_obj *tzobj; + +- if (zend_hash_find(myht, ""date"", 5, (void**) &z_date) == SUCCESS) { +- convert_to_string(*z_date); +- if (zend_hash_find(myht, ""timezone_type"", 14, (void**) &z_timezone_type) == SUCCESS) { +- convert_to_long(*z_timezone_type); +- if (zend_hash_find(myht, ""timezone"", 9, (void**) &z_timezone) == SUCCESS) { +- convert_to_string(*z_timezone); ++ if (zend_hash_find(myht, ""date"", 5, (void**) &z_date) == SUCCESS && Z_TYPE_PP(z_date) == IS_STRING) { ++ if (zend_hash_find(myht, ""timezone_type"", 14, (void**) &z_timezone_type) == SUCCESS && Z_TYPE_PP(z_timezone_type) == IS_LONG) { ++ if (zend_hash_find(myht, ""timezone"", 9, (void**) &z_timezone) == SUCCESS && Z_TYPE_PP(z_timezone) == IS_STRING) { + + switch (Z_LVAL_PP(z_timezone_type)) { + case TIMELIB_ZONETYPE_OFFSET: +@@ -2827,7 +2824,6 @@ static int php_date_initialize_from_hash(php_date_obj **dateobj, HashTable *myht + + case TIMELIB_ZONETYPE_ID: { + int ret; +- convert_to_string(*z_timezone); + + tzi = php_date_parse_tzfile(Z_STRVAL_PP(z_timezone), DATE_TIMEZONEDB TSRMLS_CC); + +@@ -3744,9 +3740,8 @@ static int php_date_timezone_initialize_from_hash(zval **return_value, php_timez + zval **z_timezone = NULL; + zval **z_timezone_type = NULL; + +- if (zend_hash_find(myht, ""timezone_type"", 14, (void**) &z_timezone_type) == SUCCESS) { ++ if (zend_hash_find(myht, ""timezone_type"", 14, (void**) &z_timezone_type) == SUCCESS && Z_TYPE_PP(z_timezone_type) == IS_LONG) { + if (zend_hash_find(myht, ""timezone"", 9, (void**) &z_timezone) == SUCCESS) { +- convert_to_long(*z_timezone_type); + if (SUCCESS == timezone_initialize(*tzobj, Z_STRVAL_PP(z_timezone) TSRMLS_CC)) { + return SUCCESS; + } +@@ -3771,7 +3766,9 @@ PHP_METHOD(DateTimeZone, __set_state) + + php_date_instantiate(date_ce_timezone, return_value TSRMLS_CC); + tzobj = (php_timezone_obj *) zend_object_store_get_object(return_value TSRMLS_CC); +- php_date_timezone_initialize_from_hash(&return_value, &tzobj, myht TSRMLS_CC); ++ if(php_date_timezone_initialize_from_hash(&return_value, &tzobj, myht TSRMLS_CC) != SUCCESS) { ++ php_error_docref(NULL, E_ERROR, ""Timezone initialization failed""); ++ } + } + /* }}} */ + +@@ -3787,7 +3784,9 @@ PHP_METHOD(DateTimeZone, __wakeup) + + myht = Z_OBJPROP_P(object); + +- php_date_timezone_initialize_from_hash(&return_value, &tzobj, myht TSRMLS_CC); ++ if(php_date_timezone_initialize_from_hash(&return_value, &tzobj, myht TSRMLS_CC) != SUCCESS) { ++ php_error_docref(NULL, E_ERROR, ""Timezone initialization failed""); ++ } + } + /* }}} */",700,1031,2048 +978,"static NOINLINE void ntp_init(char **argv) +{ + unsigned opts; + llist_t *peers; + + srand(getpid()); + + if (getuid()) + bb_error_msg_and_die(bb_msg_you_must_be_root); + + /* Set some globals */ + G.discipline_jitter = G_precision_sec; + G.stratum = MAXSTRAT; + if (BURSTPOLL != 0) + G.poll_exp = BURSTPOLL; /* speeds up initial sync */ + G.last_script_run = G.reftime = G.last_update_recv_time = gettime1900d(); /* sets G.cur_time too */ + + /* Parse options */ + peers = NULL; + opt_complementary = ""dd:wn"" /* -d: counter; -p: list; -w implies -n */ + IF_FEATURE_NTPD_SERVER("":Il""); /* -I implies -l */ + opts = getopt32(argv, + ""nqNx"" /* compat */ + ""wp:*S:""IF_FEATURE_NTPD_SERVER(""l"") /* NOT compat */ + IF_FEATURE_NTPD_SERVER(""I:"") /* compat */ + ""d"" /* compat */ + ""46aAbgL"", /* compat, ignored */ + &peers,&G.script_name, +#if ENABLE_FEATURE_NTPD_SERVER + &G.if_name, +#endif + &G.verbose); + + +#if ENABLE_FEATURE_NTPD_SERVER + G_listen_fd = -1; + if (opts & OPT_l) { + G_listen_fd = create_and_bind_dgram_or_die(NULL, 123); + if (G.if_name) { + if (setsockopt_bindtodevice(G_listen_fd, G.if_name)) + xfunc_die(); + } + socket_want_pktinfo(G_listen_fd); + setsockopt_int(G_listen_fd, IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY); + } +#endif + /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */ + if (opts & OPT_N) + setpriority(PRIO_PROCESS, 0, -15); + + /* add_peers() calls can retry DNS resolution (possibly forever). + * Daemonize before them, or else boot can stall forever. + */ + if (!(opts & OPT_n)) { + bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv); + logmode = LOGMODE_NONE; + } + + if (peers) { + while (peers) + add_peers(llist_pop(&peers)); + } +#if ENABLE_FEATURE_NTPD_CONF + else { + parser_t *parser; + char *token[3]; + + parser = config_open(""/etc/ntp.conf""); + while (config_read(parser, token, 3, 1, ""# \t"", PARSE_NORMAL)) { + if (strcmp(token[0], ""server"") == 0 && token[1]) { + add_peers(token[1]); + continue; + } + bb_error_msg(""skipping %s:%u: unimplemented command '%s'"", + ""/etc/ntp.conf"", parser->lineno, token[0] + ); + } + config_close(parser); + } +#endif + if (G.peer_cnt == 0) { + if (!(opts & OPT_l)) + bb_show_usage(); + /* -l but no peers: ""stratum 1 server"" mode */ + G.stratum = 1; + } + /* If network is up, syncronization occurs in ~10 seconds. + * We give ""ntpd -q"" 10 seconds to get first reply, + * then another 50 seconds to finish syncing. + * + * I tested ntpd 4.2.6p1 and apparently it never exits + * (will try forever), but it does not feel right. + * The goal of -q is to act like ntpdate: set time + * after a reasonably small period of polling, or fail. + */ + if (opts & OPT_q) { + option_mask32 |= OPT_qq; + alarm(10); + } + + bb_signals(0 + | (1 << SIGTERM) + | (1 << SIGINT) + | (1 << SIGALRM) + , record_signo + ); + bb_signals(0 + | (1 << SIGPIPE) + | (1 << SIGCHLD) + , SIG_IGN + ); +} +",0,"static NOINLINE void ntp_init(char **argv) +{ + unsigned opts; + llist_t *peers; + + srand(getpid()); + + if (getuid()) + bb_error_msg_and_die(bb_msg_you_must_be_root); + + /* Set some globals */ + G.discipline_jitter = G_precision_sec; + G.stratum = MAXSTRAT; + if (BURSTPOLL != 0) + G.poll_exp = BURSTPOLL; /* speeds up initial sync */ + G.last_script_run = G.reftime = G.last_update_recv_time = gettime1900d(); /* sets G.cur_time too */ + + /* Parse options */ + peers = NULL; + opt_complementary = ""dd:wn"" /* -d: counter; -p: list; -w implies -n */ + IF_FEATURE_NTPD_SERVER("":Il""); /* -I implies -l */ + opts = getopt32(argv, + ""nqNx"" /* compat */ + ""wp:*S:""IF_FEATURE_NTPD_SERVER(""l"") /* NOT compat */ + IF_FEATURE_NTPD_SERVER(""I:"") /* compat */ + ""d"" /* compat */ + ""46aAbgL"", /* compat, ignored */ + &peers,&G.script_name, +#if ENABLE_FEATURE_NTPD_SERVER + &G.if_name, +#endif + &G.verbose); + + +#if ENABLE_FEATURE_NTPD_SERVER + G_listen_fd = -1; + if (opts & OPT_l) { + G_listen_fd = create_and_bind_dgram_or_die(NULL, 123); + if (G.if_name) { + if (setsockopt_bindtodevice(G_listen_fd, G.if_name)) + xfunc_die(); + } + socket_want_pktinfo(G_listen_fd); + setsockopt_int(G_listen_fd, IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY); + } +#endif + /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */ + if (opts & OPT_N) + setpriority(PRIO_PROCESS, 0, -15); + + /* add_peers() calls can retry DNS resolution (possibly forever). + * Daemonize before them, or else boot can stall forever. + */ + if (!(opts & OPT_n)) { + bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv); + logmode = LOGMODE_NONE; + } + + if (peers) { + while (peers) + add_peers(llist_pop(&peers)); + } +#if ENABLE_FEATURE_NTPD_CONF + else { + parser_t *parser; + char *token[3]; + + parser = config_open(""/etc/ntp.conf""); + while (config_read(parser, token, 3, 1, ""# \t"", PARSE_NORMAL)) { + if (strcmp(token[0], ""server"") == 0 && token[1]) { + add_peers(token[1]); + continue; + } + bb_error_msg(""skipping %s:%u: unimplemented command '%s'"", + ""/etc/ntp.conf"", parser->lineno, token[0] + ); + } + config_close(parser); + } +#endif + if (G.peer_cnt == 0) { + if (!(opts & OPT_l)) + bb_show_usage(); + /* -l but no peers: ""stratum 1 server"" mode */ + G.stratum = 1; + } + /* If network is up, syncronization occurs in ~10 seconds. + * We give ""ntpd -q"" 10 seconds to get first reply, + * then another 50 seconds to finish syncing. + * + * I tested ntpd 4.2.6p1 and apparently it never exits + * (will try forever), but it does not feel right. + * The goal of -q is to act like ntpdate: set time + * after a reasonably small period of polling, or fail. + */ + if (opts & OPT_q) { + option_mask32 |= OPT_qq; + alarm(10); + } + + bb_signals(0 + | (1 << SIGTERM) + | (1 << SIGINT) + | (1 << SIGALRM) + , record_signo + ); + bb_signals(0 + | (1 << SIGPIPE) + | (1 << SIGCHLD) + , SIG_IGN + ); +} +","@@ -2051,6 +2051,13 @@ recv_and_process_client_pkt(void /*int fd*/) + goto bail; + } + ++ /* Respond only to client and symmetric active packets */ ++ if ((msg.m_status & MODE_MASK) != MODE_CLIENT ++ && (msg.m_status & MODE_MASK) != MODE_SYM_ACT ++ ) { ++ goto bail; ++ } ++ + query_status = msg.m_status; + query_xmttime = msg.m_xmttime;",952,1283,2048 +16368,"void RenderThreadImpl::RequestNewLayerTreeFrameSink( + int routing_id, + scoped_refptr frame_swap_message_queue, + const GURL& url, + const LayerTreeFrameSinkCallback& callback) { + const base::CommandLine& command_line = + *base::CommandLine::ForCurrentProcess(); + + viz::ClientLayerTreeFrameSink::InitParams params; + params.enable_surface_synchronization = + command_line.HasSwitch(switches::kEnableSurfaceSynchronization); + params.local_surface_id_provider = + std::make_unique(); + + if (command_line.HasSwitch(switches::kDisableGpuVsync) && + command_line.GetSwitchValueASCII(switches::kDisableGpuVsync) != ""gpu"") { + params.synthetic_begin_frame_source = CreateSyntheticBeginFrameSource(); + } + +#if defined(USE_AURA) + if (IsRunningInMash()) { + if (!RendererWindowTreeClient::Get(routing_id)) { + callback.Run(nullptr); + return; + } + bool connection_error = false; + scoped_refptr channel = + EstablishGpuChannelSync(&connection_error); + if (connection_error) + return; + if (!channel) { + callback.Run(nullptr); + return; + } + RendererWindowTreeClient::Get(routing_id) + ->RequestLayerTreeFrameSink( + gpu_->CreateContextProvider(std::move(channel)), + GetGpuMemoryBufferManager(), callback); + return; + } +#endif + + viz::mojom::CompositorFrameSinkRequest sink_request = + mojo::MakeRequest(¶ms.pipes.compositor_frame_sink_info); + viz::mojom::CompositorFrameSinkClientPtr client; + params.pipes.client_request = mojo::MakeRequest(&client); + + if (command_line.HasSwitch(switches::kEnableVulkan)) { + scoped_refptr vulkan_context_provider = + viz::VulkanInProcessContextProvider::Create(); + if (vulkan_context_provider) { + DCHECK(!layout_test_mode()); + frame_sink_provider_->CreateForWidget(routing_id, std::move(sink_request), + std::move(client)); + callback.Run(std::make_unique( + std::move(vulkan_context_provider), ¶ms)); + return; + } + } + + if (is_gpu_compositing_disabled_) { + DCHECK(!layout_test_mode()); + frame_sink_provider_->CreateForWidget(routing_id, std::move(sink_request), + std::move(client)); + params.shared_bitmap_manager = shared_bitmap_manager(); + callback.Run(std::make_unique( + nullptr, nullptr, ¶ms)); + return; + } + + bool connection_error = false; + scoped_refptr gpu_channel_host = + EstablishGpuChannelSync(&connection_error); + if (connection_error) + return; + if (!gpu_channel_host) { + callback.Run(nullptr); + return; + } + + scoped_refptr worker_context_provider = + SharedCompositorWorkerContextProvider(); + if (!worker_context_provider) { + callback.Run(nullptr); + return; + } + + gpu::SharedMemoryLimits limits = gpu::SharedMemoryLimits::ForMailboxContext(); + + gpu::gles2::ContextCreationAttribHelper attributes; + attributes.alpha_size = -1; + attributes.depth_size = 0; + attributes.stencil_size = 0; + attributes.samples = 0; + attributes.sample_buffers = 0; + attributes.bind_generates_resource = false; + attributes.lose_context_when_out_of_memory = true; + + constexpr bool automatic_flushes = false; + constexpr bool support_locking = false; + + ui::ContextProviderCommandBuffer* share_context = + worker_context_provider.get(); + if (IsAsyncWorkerContextEnabled()) + share_context = nullptr; + + scoped_refptr context_provider( + new ui::ContextProviderCommandBuffer( + gpu_channel_host, kGpuStreamIdDefault, kGpuStreamPriorityDefault, + gpu::kNullSurfaceHandle, url, automatic_flushes, support_locking, + limits, attributes, share_context, + ui::command_buffer_metrics::RENDER_COMPOSITOR_CONTEXT)); + + if (layout_test_deps_) { + callback.Run(layout_test_deps_->CreateLayerTreeFrameSink( + routing_id, std::move(gpu_channel_host), std::move(context_provider), + std::move(worker_context_provider), GetGpuMemoryBufferManager(), this)); + return; + } + +#if defined(OS_ANDROID) + if (sync_compositor_message_filter_) { + std::unique_ptr begin_frame_source = + params.synthetic_begin_frame_source + ? std::move(params.synthetic_begin_frame_source) + : CreateExternalBeginFrameSource(routing_id); + callback.Run(std::make_unique( + std::move(context_provider), std::move(worker_context_provider), + GetGpuMemoryBufferManager(), shared_bitmap_manager(), routing_id, + g_next_layer_tree_frame_sink_id++, std::move(begin_frame_source), + sync_compositor_message_filter_.get(), + std::move(frame_swap_message_queue))); + return; + } +#endif + frame_sink_provider_->CreateForWidget(routing_id, std::move(sink_request), + std::move(client)); + params.gpu_memory_buffer_manager = GetGpuMemoryBufferManager(); + callback.Run(std::make_unique( + std::move(context_provider), std::move(worker_context_provider), + ¶ms)); +} +",0,"void RenderThreadImpl::RequestNewLayerTreeFrameSink( + int routing_id, + scoped_refptr frame_swap_message_queue, + const GURL& url, + const LayerTreeFrameSinkCallback& callback) { + const base::CommandLine& command_line = + *base::CommandLine::ForCurrentProcess(); + + viz::ClientLayerTreeFrameSink::InitParams params; + params.enable_surface_synchronization = + command_line.HasSwitch(switches::kEnableSurfaceSynchronization); + params.local_surface_id_provider = + std::make_unique(); + + if (command_line.HasSwitch(switches::kDisableGpuVsync) && + command_line.GetSwitchValueASCII(switches::kDisableGpuVsync) != ""gpu"") { + params.synthetic_begin_frame_source = CreateSyntheticBeginFrameSource(); + } + +#if defined(USE_AURA) + if (IsRunningInMash()) { + if (!RendererWindowTreeClient::Get(routing_id)) { + callback.Run(nullptr); + return; + } + bool connection_error = false; + scoped_refptr channel = + EstablishGpuChannelSync(&connection_error); + if (connection_error) + return; + if (!channel) { + callback.Run(nullptr); + return; + } + RendererWindowTreeClient::Get(routing_id) + ->RequestLayerTreeFrameSink( + gpu_->CreateContextProvider(std::move(channel)), + GetGpuMemoryBufferManager(), callback); + return; + } +#endif + + viz::mojom::CompositorFrameSinkRequest sink_request = + mojo::MakeRequest(¶ms.pipes.compositor_frame_sink_info); + viz::mojom::CompositorFrameSinkClientPtr client; + params.pipes.client_request = mojo::MakeRequest(&client); + + if (command_line.HasSwitch(switches::kEnableVulkan)) { + scoped_refptr vulkan_context_provider = + viz::VulkanInProcessContextProvider::Create(); + if (vulkan_context_provider) { + DCHECK(!layout_test_mode()); + frame_sink_provider_->CreateForWidget(routing_id, std::move(sink_request), + std::move(client)); + callback.Run(std::make_unique( + std::move(vulkan_context_provider), ¶ms)); + return; + } + } + + if (is_gpu_compositing_disabled_) { + DCHECK(!layout_test_mode()); + frame_sink_provider_->CreateForWidget(routing_id, std::move(sink_request), + std::move(client)); + params.shared_bitmap_manager = shared_bitmap_manager(); + callback.Run(std::make_unique( + nullptr, nullptr, ¶ms)); + return; + } + + bool connection_error = false; + scoped_refptr gpu_channel_host = + EstablishGpuChannelSync(&connection_error); + if (connection_error) + return; + if (!gpu_channel_host) { + callback.Run(nullptr); + return; + } + + scoped_refptr worker_context_provider = + SharedCompositorWorkerContextProvider(); + if (!worker_context_provider) { + callback.Run(nullptr); + return; + } + + gpu::SharedMemoryLimits limits = gpu::SharedMemoryLimits::ForMailboxContext(); + + gpu::gles2::ContextCreationAttribHelper attributes; + attributes.alpha_size = -1; + attributes.depth_size = 0; + attributes.stencil_size = 0; + attributes.samples = 0; + attributes.sample_buffers = 0; + attributes.bind_generates_resource = false; + attributes.lose_context_when_out_of_memory = true; + + constexpr bool automatic_flushes = false; + constexpr bool support_locking = false; + + ui::ContextProviderCommandBuffer* share_context = + worker_context_provider.get(); + if (IsAsyncWorkerContextEnabled()) + share_context = nullptr; + + scoped_refptr context_provider( + new ui::ContextProviderCommandBuffer( + gpu_channel_host, kGpuStreamIdDefault, kGpuStreamPriorityDefault, + gpu::kNullSurfaceHandle, url, automatic_flushes, support_locking, + limits, attributes, share_context, + ui::command_buffer_metrics::RENDER_COMPOSITOR_CONTEXT)); + + if (layout_test_deps_) { + callback.Run(layout_test_deps_->CreateLayerTreeFrameSink( + routing_id, std::move(gpu_channel_host), std::move(context_provider), + std::move(worker_context_provider), GetGpuMemoryBufferManager(), this)); + return; + } + +#if defined(OS_ANDROID) + if (sync_compositor_message_filter_) { + std::unique_ptr begin_frame_source = + params.synthetic_begin_frame_source + ? std::move(params.synthetic_begin_frame_source) + : CreateExternalBeginFrameSource(routing_id); + callback.Run(std::make_unique( + std::move(context_provider), std::move(worker_context_provider), + GetGpuMemoryBufferManager(), shared_bitmap_manager(), routing_id, + g_next_layer_tree_frame_sink_id++, std::move(begin_frame_source), + sync_compositor_message_filter_.get(), + std::move(frame_swap_message_queue))); + return; + } +#endif + frame_sink_provider_->CreateForWidget(routing_id, std::move(sink_request), + std::move(client)); + params.gpu_memory_buffer_manager = GetGpuMemoryBufferManager(); + callback.Run(std::make_unique( + std::move(context_provider), std::move(worker_context_provider), + ¶ms)); +} +","@@ -994,9 +994,6 @@ void RenderThreadImpl::Init( + if (!command_line.HasSwitch(switches::kSingleProcess)) + base::SequencedWorkerPool::EnableForProcess(); + +- EVP_set_buggy_rsa_parser( +- base::FeatureList::IsEnabled(features::kBuggyRSAParser)); +- + GetConnector()->BindInterface(mojom::kBrowserServiceName, + mojo::MakeRequest(&frame_sink_provider_)); + ",1182,1513,2048 +12128,"void IOThread::InitAsync() { + TRACE_EVENT0(""startup"", ""IOThread::InitAsync""); + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); + +#if defined(USE_NSS) || defined(OS_IOS) + net::SetMessageLoopForNSSHttpIO(); +#endif + + const CommandLine& command_line = *CommandLine::ForCurrentProcess(); + + DCHECK(!globals_); + globals_ = new Globals; + + network_change_observer_.reset( + new LoggingNetworkChangeObserver(net_log_)); + + net::NetworkChangeNotifier::InitHistogramWatcher(); + + globals_->extension_event_router_forwarder = + extension_event_router_forwarder_; + ChromeNetworkDelegate* network_delegate = + new ChromeNetworkDelegate(extension_event_router_forwarder_, + &system_enable_referrers_); + if (command_line.HasSwitch(switches::kEnableClientHints)) + network_delegate->SetEnableClientHints(); + if (command_line.HasSwitch(switches::kDisableExtensionsHttpThrottling)) + network_delegate->NeverThrottleRequests(); + globals_->system_network_delegate.reset(network_delegate); + globals_->host_resolver = CreateGlobalHostResolver(net_log_); + UpdateDnsClientEnabled(); + globals_->cert_verifier.reset(net::CertVerifier::CreateDefault()); + globals_->transport_security_state.reset(new net::TransportSecurityState()); +#if !defined(USE_OPENSSL) + net::MultiLogCTVerifier* ct_verifier = new net::MultiLogCTVerifier(); + globals_->cert_transparency_verifier.reset(ct_verifier); + + ct_verifier->AddLog(net::ct::CreateGooglePilotLogVerifier().Pass()); + ct_verifier->AddLog(net::ct::CreateGoogleAviatorLogVerifier().Pass()); + ct_verifier->AddLog(net::ct::CreateGoogleRocketeerLogVerifier().Pass()); + + if (command_line.HasSwitch(switches::kCertificateTransparencyLog)) { + std::string switch_value = command_line.GetSwitchValueASCII( + switches::kCertificateTransparencyLog); + size_t delim_pos = switch_value.find("":""); + CHECK(delim_pos != std::string::npos) + << ""CT log description not provided (switch format"" + "" is 'description:base64_key')""; + std::string log_description(switch_value.substr(0, delim_pos)); + std::string ct_public_key_data; + CHECK(base::Base64Decode( + switch_value.substr(delim_pos + 1), + &ct_public_key_data)) << ""Unable to decode CT public key.""; + scoped_ptr external_log_verifier( + net::CTLogVerifier::Create(ct_public_key_data, log_description)); + CHECK(external_log_verifier) << ""Unable to parse CT public key.""; + ct_verifier->AddLog(external_log_verifier.Pass()); + } +#else + if (command_line.HasSwitch(switches::kCertificateTransparencyLog)) { + LOG(DFATAL) << ""Certificate Transparency is not yet supported in Chrome "" + ""builds using OpenSSL.""; + } +#endif + globals_->ssl_config_service = GetSSLConfigService(); +#if defined(OS_ANDROID) || defined(OS_IOS) + if (DataReductionProxySettings::IsDataReductionProxyAllowed()) { + spdyproxy_auth_origins_ = + DataReductionProxySettings::GetDataReductionProxies(); + } +#endif // defined(OS_ANDROID) || defined(OS_IOS) + globals_->http_auth_handler_factory.reset(CreateDefaultAuthHandlerFactory( + globals_->host_resolver.get())); + globals_->http_server_properties.reset(new net::HttpServerPropertiesImpl()); + globals_->proxy_script_fetcher_proxy_service.reset( + net::ProxyService::CreateDirectWithNetLog(net_log_)); + globals_->system_cookie_store = new net::CookieMonster(NULL, NULL); + globals_->system_server_bound_cert_service.reset( + new net::ServerBoundCertService( + new net::DefaultServerBoundCertStore(NULL), + base::WorkerPool::GetTaskRunner(true))); + globals_->dns_probe_service.reset(new chrome_browser_net::DnsProbeService()); + globals_->load_time_stats.reset(new chrome_browser_net::LoadTimeStats()); + globals_->host_mapping_rules.reset(new net::HostMappingRules()); + globals_->http_user_agent_settings.reset( + new BasicHttpUserAgentSettings(std::string())); + if (command_line.HasSwitch(switches::kHostRules)) { + TRACE_EVENT_BEGIN0(""startup"", ""IOThread::InitAsync:SetRulesFromString""); + globals_->host_mapping_rules->SetRulesFromString( + command_line.GetSwitchValueASCII(switches::kHostRules)); + TRACE_EVENT_END0(""startup"", ""IOThread::InitAsync:SetRulesFromString""); + } + if (command_line.HasSwitch(switches::kIgnoreCertificateErrors)) + globals_->ignore_certificate_errors = true; + if (command_line.HasSwitch(switches::kTestingFixedHttpPort)) { + globals_->testing_fixed_http_port = + GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpPort); + } + if (command_line.HasSwitch(switches::kTestingFixedHttpsPort)) { + globals_->testing_fixed_https_port = + GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpsPort); + } + ConfigureQuic(command_line); + if (command_line.HasSwitch( + switches::kEnableUserAlternateProtocolPorts)) { + globals_->enable_user_alternate_protocol_ports = true; + } + InitializeNetworkOptions(command_line); + + net::HttpNetworkSession::Params session_params; + InitializeNetworkSessionParams(&session_params); + session_params.net_log = net_log_; + session_params.proxy_service = + globals_->proxy_script_fetcher_proxy_service.get(); + + TRACE_EVENT_BEGIN0(""startup"", ""IOThread::InitAsync:HttpNetworkSession""); + scoped_refptr network_session( + new net::HttpNetworkSession(session_params)); + globals_->proxy_script_fetcher_http_transaction_factory + .reset(new net::HttpNetworkLayer(network_session.get())); + TRACE_EVENT_END0(""startup"", ""IOThread::InitAsync:HttpNetworkSession""); + scoped_ptr job_factory( + new net::URLRequestJobFactoryImpl()); + job_factory->SetProtocolHandler(chrome::kDataScheme, + new net::DataProtocolHandler()); + job_factory->SetProtocolHandler( + chrome::kFileScheme, + new net::FileProtocolHandler( + content::BrowserThread::GetBlockingPool()-> + GetTaskRunnerWithShutdownBehavior( + base::SequencedWorkerPool::SKIP_ON_SHUTDOWN))); +#if !defined(DISABLE_FTP_SUPPORT) + globals_->proxy_script_fetcher_ftp_transaction_factory.reset( + new net::FtpNetworkLayer(globals_->host_resolver.get())); + job_factory->SetProtocolHandler( + content::kFtpScheme, + new net::FtpProtocolHandler( + globals_->proxy_script_fetcher_ftp_transaction_factory.get())); +#endif + globals_->proxy_script_fetcher_url_request_job_factory = + job_factory.PassAs(); + + globals_->throttler_manager.reset(new net::URLRequestThrottlerManager()); + globals_->throttler_manager->set_net_log(net_log_); + globals_->throttler_manager->set_enable_thread_checks(true); + + globals_->proxy_script_fetcher_context.reset( + ConstructProxyScriptFetcherContext(globals_, net_log_)); + + globals_->network_time_notifier.reset( + new net::NetworkTimeNotifier( + scoped_ptr(new base::DefaultTickClock()))); + + sdch_manager_ = new net::SdchManager(); + +#if defined(OS_MACOSX) && !defined(OS_IOS) + BrowserThread::PostTask(BrowserThread::UI, + FROM_HERE, + base::Bind(&ObserveKeychainEvents)); +#endif + + BrowserThread::PostTask(BrowserThread::UI, + FROM_HERE, + base::Bind(&IOThread::InitSystemRequestContext, + weak_factory_.GetWeakPtr())); +} +",0,"void IOThread::InitAsync() { + TRACE_EVENT0(""startup"", ""IOThread::InitAsync""); + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); + +#if defined(USE_NSS) || defined(OS_IOS) + net::SetMessageLoopForNSSHttpIO(); +#endif + + const CommandLine& command_line = *CommandLine::ForCurrentProcess(); + + DCHECK(!globals_); + globals_ = new Globals; + + network_change_observer_.reset( + new LoggingNetworkChangeObserver(net_log_)); + + net::NetworkChangeNotifier::InitHistogramWatcher(); + + globals_->extension_event_router_forwarder = + extension_event_router_forwarder_; + ChromeNetworkDelegate* network_delegate = + new ChromeNetworkDelegate(extension_event_router_forwarder_, + &system_enable_referrers_); + if (command_line.HasSwitch(switches::kEnableClientHints)) + network_delegate->SetEnableClientHints(); + if (command_line.HasSwitch(switches::kDisableExtensionsHttpThrottling)) + network_delegate->NeverThrottleRequests(); + globals_->system_network_delegate.reset(network_delegate); + globals_->host_resolver = CreateGlobalHostResolver(net_log_); + UpdateDnsClientEnabled(); + globals_->cert_verifier.reset(net::CertVerifier::CreateDefault()); + globals_->transport_security_state.reset(new net::TransportSecurityState()); +#if !defined(USE_OPENSSL) + net::MultiLogCTVerifier* ct_verifier = new net::MultiLogCTVerifier(); + globals_->cert_transparency_verifier.reset(ct_verifier); + + ct_verifier->AddLog(net::ct::CreateGooglePilotLogVerifier().Pass()); + ct_verifier->AddLog(net::ct::CreateGoogleAviatorLogVerifier().Pass()); + ct_verifier->AddLog(net::ct::CreateGoogleRocketeerLogVerifier().Pass()); + + if (command_line.HasSwitch(switches::kCertificateTransparencyLog)) { + std::string switch_value = command_line.GetSwitchValueASCII( + switches::kCertificateTransparencyLog); + size_t delim_pos = switch_value.find("":""); + CHECK(delim_pos != std::string::npos) + << ""CT log description not provided (switch format"" + "" is 'description:base64_key')""; + std::string log_description(switch_value.substr(0, delim_pos)); + std::string ct_public_key_data; + CHECK(base::Base64Decode( + switch_value.substr(delim_pos + 1), + &ct_public_key_data)) << ""Unable to decode CT public key.""; + scoped_ptr external_log_verifier( + net::CTLogVerifier::Create(ct_public_key_data, log_description)); + CHECK(external_log_verifier) << ""Unable to parse CT public key.""; + ct_verifier->AddLog(external_log_verifier.Pass()); + } +#else + if (command_line.HasSwitch(switches::kCertificateTransparencyLog)) { + LOG(DFATAL) << ""Certificate Transparency is not yet supported in Chrome "" + ""builds using OpenSSL.""; + } +#endif + globals_->ssl_config_service = GetSSLConfigService(); +#if defined(OS_ANDROID) || defined(OS_IOS) + if (DataReductionProxySettings::IsDataReductionProxyAllowed()) { + spdyproxy_auth_origins_ = + DataReductionProxySettings::GetDataReductionProxies(); + } +#endif // defined(OS_ANDROID) || defined(OS_IOS) + globals_->http_auth_handler_factory.reset(CreateDefaultAuthHandlerFactory( + globals_->host_resolver.get())); + globals_->http_server_properties.reset(new net::HttpServerPropertiesImpl()); + globals_->proxy_script_fetcher_proxy_service.reset( + net::ProxyService::CreateDirectWithNetLog(net_log_)); + globals_->system_cookie_store = new net::CookieMonster(NULL, NULL); + globals_->system_server_bound_cert_service.reset( + new net::ServerBoundCertService( + new net::DefaultServerBoundCertStore(NULL), + base::WorkerPool::GetTaskRunner(true))); + globals_->dns_probe_service.reset(new chrome_browser_net::DnsProbeService()); + globals_->load_time_stats.reset(new chrome_browser_net::LoadTimeStats()); + globals_->host_mapping_rules.reset(new net::HostMappingRules()); + globals_->http_user_agent_settings.reset( + new BasicHttpUserAgentSettings(std::string())); + if (command_line.HasSwitch(switches::kHostRules)) { + TRACE_EVENT_BEGIN0(""startup"", ""IOThread::InitAsync:SetRulesFromString""); + globals_->host_mapping_rules->SetRulesFromString( + command_line.GetSwitchValueASCII(switches::kHostRules)); + TRACE_EVENT_END0(""startup"", ""IOThread::InitAsync:SetRulesFromString""); + } + if (command_line.HasSwitch(switches::kIgnoreCertificateErrors)) + globals_->ignore_certificate_errors = true; + if (command_line.HasSwitch(switches::kTestingFixedHttpPort)) { + globals_->testing_fixed_http_port = + GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpPort); + } + if (command_line.HasSwitch(switches::kTestingFixedHttpsPort)) { + globals_->testing_fixed_https_port = + GetSwitchValueAsInt(command_line, switches::kTestingFixedHttpsPort); + } + ConfigureQuic(command_line); + if (command_line.HasSwitch( + switches::kEnableUserAlternateProtocolPorts)) { + globals_->enable_user_alternate_protocol_ports = true; + } + InitializeNetworkOptions(command_line); + + net::HttpNetworkSession::Params session_params; + InitializeNetworkSessionParams(&session_params); + session_params.net_log = net_log_; + session_params.proxy_service = + globals_->proxy_script_fetcher_proxy_service.get(); + + TRACE_EVENT_BEGIN0(""startup"", ""IOThread::InitAsync:HttpNetworkSession""); + scoped_refptr network_session( + new net::HttpNetworkSession(session_params)); + globals_->proxy_script_fetcher_http_transaction_factory + .reset(new net::HttpNetworkLayer(network_session.get())); + TRACE_EVENT_END0(""startup"", ""IOThread::InitAsync:HttpNetworkSession""); + scoped_ptr job_factory( + new net::URLRequestJobFactoryImpl()); + job_factory->SetProtocolHandler(chrome::kDataScheme, + new net::DataProtocolHandler()); + job_factory->SetProtocolHandler( + chrome::kFileScheme, + new net::FileProtocolHandler( + content::BrowserThread::GetBlockingPool()-> + GetTaskRunnerWithShutdownBehavior( + base::SequencedWorkerPool::SKIP_ON_SHUTDOWN))); +#if !defined(DISABLE_FTP_SUPPORT) + globals_->proxy_script_fetcher_ftp_transaction_factory.reset( + new net::FtpNetworkLayer(globals_->host_resolver.get())); + job_factory->SetProtocolHandler( + content::kFtpScheme, + new net::FtpProtocolHandler( + globals_->proxy_script_fetcher_ftp_transaction_factory.get())); +#endif + globals_->proxy_script_fetcher_url_request_job_factory = + job_factory.PassAs(); + + globals_->throttler_manager.reset(new net::URLRequestThrottlerManager()); + globals_->throttler_manager->set_net_log(net_log_); + globals_->throttler_manager->set_enable_thread_checks(true); + + globals_->proxy_script_fetcher_context.reset( + ConstructProxyScriptFetcherContext(globals_, net_log_)); + + globals_->network_time_notifier.reset( + new net::NetworkTimeNotifier( + scoped_ptr(new base::DefaultTickClock()))); + + sdch_manager_ = new net::SdchManager(); + +#if defined(OS_MACOSX) && !defined(OS_IOS) + BrowserThread::PostTask(BrowserThread::UI, + FROM_HERE, + base::Bind(&ObserveKeychainEvents)); +#endif + + BrowserThread::PostTask(BrowserThread::UI, + FROM_HERE, + base::Bind(&IOThread::InitSystemRequestContext, + weak_factory_.GetWeakPtr())); +} +","@@ -879,6 +879,14 @@ void IOThread::RegisterPrefs(PrefRegistrySimple* registry) { + prefs::kDailyOriginalContentLengthWithDataReductionProxyEnabled); + registry->RegisterListPref( + prefs::kDailyContentLengthWithDataReductionProxyEnabled); ++ registry->RegisterListPref( ++ prefs::kDailyContentLengthHttpsWithDataReductionProxyEnabled); ++ registry->RegisterListPref( ++ prefs::kDailyContentLengthShortBypassWithDataReductionProxyEnabled); ++ registry->RegisterListPref( ++ prefs::kDailyContentLengthLongBypassWithDataReductionProxyEnabled); ++ registry->RegisterListPref( ++ prefs::kDailyContentLengthUnknownWithDataReductionProxyEnabled); + registry->RegisterListPref( + prefs::kDailyOriginalContentLengthViaDataReductionProxy); + registry->RegisterListPref(",1662,1993,2048 +1339,"ssh_packet_read_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p) +{ + struct session_state *state = ssh->state; + int len, r, ms_remain, cont; + fd_set *setp; + char buf[8192]; + struct timeval timeout, start, *timeoutp = NULL; + + DBG(debug(""packet_read()"")); + + setp = calloc(howmany(state->connection_in + 1, + NFDBITS), sizeof(fd_mask)); + if (setp == NULL) + return SSH_ERR_ALLOC_FAIL; + + /* + * Since we are blocking, ensure that all written packets have + * been sent. + */ + if ((r = ssh_packet_write_wait(ssh)) != 0) + goto out; + + /* Stay in the loop until we have received a complete packet. */ + for (;;) { + /* Try to read a packet from the buffer. */ + r = ssh_packet_read_poll_seqnr(ssh, typep, seqnr_p); + if (r != 0) + break; + if (!compat20 && ( + *typep == SSH_SMSG_SUCCESS + || *typep == SSH_SMSG_FAILURE + || *typep == SSH_CMSG_EOF + || *typep == SSH_CMSG_EXIT_CONFIRMATION)) + if ((r = sshpkt_get_end(ssh)) != 0) + break; + /* If we got a packet, return it. */ + if (*typep != SSH_MSG_NONE) + break; + /* + * Otherwise, wait for some data to arrive, add it to the + * buffer, and try again. + */ + memset(setp, 0, howmany(state->connection_in + 1, + NFDBITS) * sizeof(fd_mask)); + FD_SET(state->connection_in, setp); + + if (state->packet_timeout_ms > 0) { + ms_remain = state->packet_timeout_ms; + timeoutp = &timeout; + } + /* Wait for some data to arrive. */ + for (;;) { + if (state->packet_timeout_ms != -1) { + ms_to_timeval(&timeout, ms_remain); + gettimeofday(&start, NULL); + } + if ((r = select(state->connection_in + 1, setp, + NULL, NULL, timeoutp)) >= 0) + break; + if (errno != EAGAIN && errno != EINTR && + errno != EWOULDBLOCK) + break; + if (state->packet_timeout_ms == -1) + continue; + ms_subtract_diff(&start, &ms_remain); + if (ms_remain <= 0) { + r = 0; + break; + } + } + if (r == 0) + return SSH_ERR_CONN_TIMEOUT; + /* Read data from the socket. */ + do { + cont = 0; + len = roaming_read(state->connection_in, buf, + sizeof(buf), &cont); + } while (len == 0 && cont); + if (len == 0) { + r = SSH_ERR_CONN_CLOSED; + goto out; + } + if (len < 0) { + r = SSH_ERR_SYSTEM_ERROR; + goto out; + } + + /* Append it to the buffer. */ + if ((r = ssh_packet_process_incoming(ssh, buf, len)) != 0) + goto out; + } + out: + free(setp); + return r; +} +",0,"ssh_packet_read_seqnr(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p) +{ + struct session_state *state = ssh->state; + int len, r, ms_remain, cont; + fd_set *setp; + char buf[8192]; + struct timeval timeout, start, *timeoutp = NULL; + + DBG(debug(""packet_read()"")); + + setp = calloc(howmany(state->connection_in + 1, + NFDBITS), sizeof(fd_mask)); + if (setp == NULL) + return SSH_ERR_ALLOC_FAIL; + + /* + * Since we are blocking, ensure that all written packets have + * been sent. + */ + if ((r = ssh_packet_write_wait(ssh)) != 0) + goto out; + + /* Stay in the loop until we have received a complete packet. */ + for (;;) { + /* Try to read a packet from the buffer. */ + r = ssh_packet_read_poll_seqnr(ssh, typep, seqnr_p); + if (r != 0) + break; + if (!compat20 && ( + *typep == SSH_SMSG_SUCCESS + || *typep == SSH_SMSG_FAILURE + || *typep == SSH_CMSG_EOF + || *typep == SSH_CMSG_EXIT_CONFIRMATION)) + if ((r = sshpkt_get_end(ssh)) != 0) + break; + /* If we got a packet, return it. */ + if (*typep != SSH_MSG_NONE) + break; + /* + * Otherwise, wait for some data to arrive, add it to the + * buffer, and try again. + */ + memset(setp, 0, howmany(state->connection_in + 1, + NFDBITS) * sizeof(fd_mask)); + FD_SET(state->connection_in, setp); + + if (state->packet_timeout_ms > 0) { + ms_remain = state->packet_timeout_ms; + timeoutp = &timeout; + } + /* Wait for some data to arrive. */ + for (;;) { + if (state->packet_timeout_ms != -1) { + ms_to_timeval(&timeout, ms_remain); + gettimeofday(&start, NULL); + } + if ((r = select(state->connection_in + 1, setp, + NULL, NULL, timeoutp)) >= 0) + break; + if (errno != EAGAIN && errno != EINTR && + errno != EWOULDBLOCK) + break; + if (state->packet_timeout_ms == -1) + continue; + ms_subtract_diff(&start, &ms_remain); + if (ms_remain <= 0) { + r = 0; + break; + } + } + if (r == 0) + return SSH_ERR_CONN_TIMEOUT; + /* Read data from the socket. */ + do { + cont = 0; + len = roaming_read(state->connection_in, buf, + sizeof(buf), &cont); + } while (len == 0 && cont); + if (len == 0) { + r = SSH_ERR_CONN_CLOSED; + goto out; + } + if (len < 0) { + r = SSH_ERR_SYSTEM_ERROR; + goto out; + } + + /* Append it to the buffer. */ + if ((r = ssh_packet_process_incoming(ssh, buf, len)) != 0) + goto out; + } + out: + free(setp); + return r; +} +","@@ -1,4 +1,4 @@ +-/* $OpenBSD: packet.c,v 1.216 2015/10/21 11:33:03 gsoares Exp $ */ ++/* $OpenBSD: packet.c,v 1.217 2015/11/08 21:59:11 djm Exp $ */ + /* + * Author: Tatu Ylonen + * Copyright (c) 1995 Tatu Ylonen , Espoo, Finland +@@ -1581,6 +1581,7 @@ ssh_packet_read_poll2(struct ssh *ssh, u_char *typep, u_int32_t *seqnr_p) + logit(""Bad packet length %u."", state->packlen); + if ((r = sshpkt_disconnect(ssh, ""Packet corrupt"")) != 0) + return r; ++ return SSH_ERR_CONN_CORRUPT; + } + sshbuf_reset(state->incoming_packet); + } else if (state->packlen == 0) {",741,1072,2048 +1921,"static int dccp_v4_rcv(struct sk_buff *skb) +{ + const struct dccp_hdr *dh; + const struct iphdr *iph; + struct sock *sk; + int min_cov; + + /* Step 1: Check header basics */ + + if (dccp_invalid_packet(skb)) + goto discard_it; + + iph = ip_hdr(skb); + /* Step 1: If header checksum is incorrect, drop packet and return */ + if (dccp_v4_csum_finish(skb, iph->saddr, iph->daddr)) { + DCCP_WARN(""dropped packet with invalid checksum\n""); + goto discard_it; + } + + dh = dccp_hdr(skb); + + DCCP_SKB_CB(skb)->dccpd_seq = dccp_hdr_seq(dh); + DCCP_SKB_CB(skb)->dccpd_type = dh->dccph_type; + + dccp_pr_debug(""%8.8s src=%pI4@%-5d dst=%pI4@%-5d seq=%llu"", + dccp_packet_name(dh->dccph_type), + &iph->saddr, ntohs(dh->dccph_sport), + &iph->daddr, ntohs(dh->dccph_dport), + (unsigned long long) DCCP_SKB_CB(skb)->dccpd_seq); + + if (dccp_packet_without_ack(skb)) { + DCCP_SKB_CB(skb)->dccpd_ack_seq = DCCP_PKT_WITHOUT_ACK_SEQ; + dccp_pr_debug_cat(""\n""); + } else { + DCCP_SKB_CB(skb)->dccpd_ack_seq = dccp_hdr_ack_seq(skb); + dccp_pr_debug_cat("", ack=%llu\n"", (unsigned long long) + DCCP_SKB_CB(skb)->dccpd_ack_seq); + } + + /* Step 2: + * Look up flow ID in table and get corresponding socket */ + sk = __inet_lookup_skb(&dccp_hashinfo, skb, + dh->dccph_sport, dh->dccph_dport); + /* + * Step 2: + * If no socket ... + */ + if (sk == NULL) { + dccp_pr_debug(""failed to look up flow ID in table and "" + ""get corresponding socket\n""); + goto no_dccp_socket; + } + + /* + * Step 2: + * ... or S.state == TIMEWAIT, + * Generate Reset(No Connection) unless P.type == Reset + * Drop packet and return + */ + if (sk->sk_state == DCCP_TIME_WAIT) { + dccp_pr_debug(""sk->sk_state == DCCP_TIME_WAIT: do_time_wait\n""); + inet_twsk_put(inet_twsk(sk)); + goto no_dccp_socket; + } + + /* + * RFC 4340, sec. 9.2.1: Minimum Checksum Coverage + * o if MinCsCov = 0, only packets with CsCov = 0 are accepted + * o if MinCsCov > 0, also accept packets with CsCov >= MinCsCov + */ + min_cov = dccp_sk(sk)->dccps_pcrlen; + if (dh->dccph_cscov && (min_cov == 0 || dh->dccph_cscov < min_cov)) { + dccp_pr_debug(""Packet CsCov %d does not satisfy MinCsCov %d\n"", + dh->dccph_cscov, min_cov); + /* FIXME: ""Such packets SHOULD be reported using Data Dropped + * options (Section 11.7) with Drop Code 0, Protocol + * Constraints."" */ + goto discard_and_relse; + } + + if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) + goto discard_and_relse; + nf_reset(skb); + + return sk_receive_skb(sk, skb, 1); + +no_dccp_socket: + if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) + goto discard_it; + /* + * Step 2: + * If no socket ... + * Generate Reset(No Connection) unless P.type == Reset + * Drop packet and return + */ + if (dh->dccph_type != DCCP_PKT_RESET) { + DCCP_SKB_CB(skb)->dccpd_reset_code = + DCCP_RESET_CODE_NO_CONNECTION; + dccp_v4_ctl_send_reset(sk, skb); + } + +discard_it: + kfree_skb(skb); + return 0; + +discard_and_relse: + sock_put(sk); + goto discard_it; +} +",0,"static int dccp_v4_rcv(struct sk_buff *skb) +{ + const struct dccp_hdr *dh; + const struct iphdr *iph; + struct sock *sk; + int min_cov; + + /* Step 1: Check header basics */ + + if (dccp_invalid_packet(skb)) + goto discard_it; + + iph = ip_hdr(skb); + /* Step 1: If header checksum is incorrect, drop packet and return */ + if (dccp_v4_csum_finish(skb, iph->saddr, iph->daddr)) { + DCCP_WARN(""dropped packet with invalid checksum\n""); + goto discard_it; + } + + dh = dccp_hdr(skb); + + DCCP_SKB_CB(skb)->dccpd_seq = dccp_hdr_seq(dh); + DCCP_SKB_CB(skb)->dccpd_type = dh->dccph_type; + + dccp_pr_debug(""%8.8s src=%pI4@%-5d dst=%pI4@%-5d seq=%llu"", + dccp_packet_name(dh->dccph_type), + &iph->saddr, ntohs(dh->dccph_sport), + &iph->daddr, ntohs(dh->dccph_dport), + (unsigned long long) DCCP_SKB_CB(skb)->dccpd_seq); + + if (dccp_packet_without_ack(skb)) { + DCCP_SKB_CB(skb)->dccpd_ack_seq = DCCP_PKT_WITHOUT_ACK_SEQ; + dccp_pr_debug_cat(""\n""); + } else { + DCCP_SKB_CB(skb)->dccpd_ack_seq = dccp_hdr_ack_seq(skb); + dccp_pr_debug_cat("", ack=%llu\n"", (unsigned long long) + DCCP_SKB_CB(skb)->dccpd_ack_seq); + } + + /* Step 2: + * Look up flow ID in table and get corresponding socket */ + sk = __inet_lookup_skb(&dccp_hashinfo, skb, + dh->dccph_sport, dh->dccph_dport); + /* + * Step 2: + * If no socket ... + */ + if (sk == NULL) { + dccp_pr_debug(""failed to look up flow ID in table and "" + ""get corresponding socket\n""); + goto no_dccp_socket; + } + + /* + * Step 2: + * ... or S.state == TIMEWAIT, + * Generate Reset(No Connection) unless P.type == Reset + * Drop packet and return + */ + if (sk->sk_state == DCCP_TIME_WAIT) { + dccp_pr_debug(""sk->sk_state == DCCP_TIME_WAIT: do_time_wait\n""); + inet_twsk_put(inet_twsk(sk)); + goto no_dccp_socket; + } + + /* + * RFC 4340, sec. 9.2.1: Minimum Checksum Coverage + * o if MinCsCov = 0, only packets with CsCov = 0 are accepted + * o if MinCsCov > 0, also accept packets with CsCov >= MinCsCov + */ + min_cov = dccp_sk(sk)->dccps_pcrlen; + if (dh->dccph_cscov && (min_cov == 0 || dh->dccph_cscov < min_cov)) { + dccp_pr_debug(""Packet CsCov %d does not satisfy MinCsCov %d\n"", + dh->dccph_cscov, min_cov); + /* FIXME: ""Such packets SHOULD be reported using Data Dropped + * options (Section 11.7) with Drop Code 0, Protocol + * Constraints."" */ + goto discard_and_relse; + } + + if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) + goto discard_and_relse; + nf_reset(skb); + + return sk_receive_skb(sk, skb, 1); + +no_dccp_socket: + if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) + goto discard_it; + /* + * Step 2: + * If no socket ... + * Generate Reset(No Connection) unless P.type == Reset + * Drop packet and return + */ + if (dh->dccph_type != DCCP_PKT_RESET) { + DCCP_SKB_CB(skb)->dccpd_reset_code = + DCCP_RESET_CODE_NO_CONNECTION; + dccp_v4_ctl_send_reset(sk, skb); + } + +discard_it: + kfree_skb(skb); + return 0; + +discard_and_relse: + sock_put(sk); + goto discard_it; +} +","@@ -48,6 +48,7 @@ int dccp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len) + struct flowi4 fl4; + struct rtable *rt; + int err; ++ struct ip_options_rcu *inet_opt; + + dp->dccps_role = DCCP_ROLE_CLIENT; + +@@ -58,10 +59,13 @@ int dccp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len) + return -EAFNOSUPPORT; + + nexthop = daddr = usin->sin_addr.s_addr; +- if (inet->opt != NULL && inet->opt->srr) { ++ ++ inet_opt = rcu_dereference_protected(inet->inet_opt, ++ sock_owned_by_user(sk)); ++ if (inet_opt != NULL && inet_opt->opt.srr) { + if (daddr == 0) + return -EINVAL; +- nexthop = inet->opt->faddr; ++ nexthop = inet_opt->opt.faddr; + } + + orig_sport = inet->inet_sport; +@@ -78,7 +82,7 @@ int dccp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len) + return -ENETUNREACH; + } + +- if (inet->opt == NULL || !inet->opt->srr) ++ if (inet_opt == NULL || !inet_opt->opt.srr) + daddr = rt->rt_dst; + + if (inet->inet_saddr == 0) +@@ -89,8 +93,8 @@ int dccp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len) + inet->inet_daddr = daddr; + + inet_csk(sk)->icsk_ext_hdr_len = 0; +- if (inet->opt != NULL) +- inet_csk(sk)->icsk_ext_hdr_len = inet->opt->optlen; ++ if (inet_opt) ++ inet_csk(sk)->icsk_ext_hdr_len = inet_opt->opt.optlen; + /* + * Socket identity is still unknown (sport may be zero). + * However we set state to DCCP_REQUESTING and not releasing socket +@@ -405,7 +409,7 @@ struct sock *dccp_v4_request_recv_sock(struct sock *sk, struct sk_buff *skb, + newinet->inet_daddr = ireq->rmt_addr; + newinet->inet_rcv_saddr = ireq->loc_addr; + newinet->inet_saddr = ireq->loc_addr; +- newinet->opt = ireq->opt; ++ newinet->inet_opt = ireq->opt; + ireq->opt = NULL; + newinet->mc_index = inet_iif(skb); + newinet->mc_ttl = ip_hdr(skb)->ttl;",980,1311,2048 +7317,"static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, + const ssize_t type,const PSDCompressionType compression, + const size_t compact_size,ExceptionInfo *exception) +{ + MagickBooleanType + status; + + register unsigned char + *p; + + size_t + count, + length, + packet_size, + row_size; + + ssize_t + y; + + unsigned char + *compact_pixels, + *pixels; + + z_stream + stream; + + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" layer data is ZIP compressed""); + + compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, + sizeof(*compact_pixels)); + if (compact_pixels == (unsigned char *) NULL) + ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", + image->filename); + + packet_size=GetPSDPacketSize(image); + row_size=image->columns*packet_size; + count=image->rows*row_size; + + pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); + if (pixels == (unsigned char *) NULL) + { + compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); + ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", + image->filename); + } + + ResetMagickMemory(&stream, 0, sizeof(z_stream)); + stream.data_type=Z_BINARY; + (void) ReadBlob(image,compact_size,compact_pixels); + + stream.next_in=(Bytef *)compact_pixels; + stream.avail_in=(unsigned int) compact_size; + stream.next_out=(Bytef *)pixels; + stream.avail_out=(unsigned int) count; + + if(inflateInit(&stream) == Z_OK) + { + int + ret; + + while (stream.avail_out > 0) + { + ret=inflate(&stream, Z_SYNC_FLUSH); + if (ret != Z_OK && ret != Z_STREAM_END) + { + compact_pixels=(unsigned char *) RelinquishMagickMemory( + compact_pixels); + pixels=(unsigned char *) RelinquishMagickMemory(pixels); + return(MagickFalse); + } + } + } + + if (compression == ZipWithPrediction) + { + p=pixels; + while(count > 0) + { + length=image->columns; + while(--length) + { + if (packet_size == 2) + { + p[2]+=p[0]+((p[1]+p[3]) >> 8); + p[3]+=p[1]; + } + else + *(p+1)+=*p; + p+=packet_size; + } + p+=packet_size; + count-=row_size; + } + } + + status=MagickTrue; + p=pixels; + for (y=0; y < (ssize_t) image->rows; y++) + { + status=ReadPSDChannelPixels(image,channels,y,type,p,exception); + if (status == MagickFalse) + break; + + p+=row_size; + } + + compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); + pixels=(unsigned char *) RelinquishMagickMemory(pixels); + return(status); +} +",0,"static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, + const ssize_t type,const PSDCompressionType compression, + const size_t compact_size,ExceptionInfo *exception) +{ + MagickBooleanType + status; + + register unsigned char + *p; + + size_t + count, + length, + packet_size, + row_size; + + ssize_t + y; + + unsigned char + *compact_pixels, + *pixels; + + z_stream + stream; + + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" layer data is ZIP compressed""); + + compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, + sizeof(*compact_pixels)); + if (compact_pixels == (unsigned char *) NULL) + ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", + image->filename); + + packet_size=GetPSDPacketSize(image); + row_size=image->columns*packet_size; + count=image->rows*row_size; + + pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); + if (pixels == (unsigned char *) NULL) + { + compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); + ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", + image->filename); + } + + ResetMagickMemory(&stream, 0, sizeof(z_stream)); + stream.data_type=Z_BINARY; + (void) ReadBlob(image,compact_size,compact_pixels); + + stream.next_in=(Bytef *)compact_pixels; + stream.avail_in=(unsigned int) compact_size; + stream.next_out=(Bytef *)pixels; + stream.avail_out=(unsigned int) count; + + if(inflateInit(&stream) == Z_OK) + { + int + ret; + + while (stream.avail_out > 0) + { + ret=inflate(&stream, Z_SYNC_FLUSH); + if (ret != Z_OK && ret != Z_STREAM_END) + { + compact_pixels=(unsigned char *) RelinquishMagickMemory( + compact_pixels); + pixels=(unsigned char *) RelinquishMagickMemory(pixels); + return(MagickFalse); + } + } + } + + if (compression == ZipWithPrediction) + { + p=pixels; + while(count > 0) + { + length=image->columns; + while(--length) + { + if (packet_size == 2) + { + p[2]+=p[0]+((p[1]+p[3]) >> 8); + p[3]+=p[1]; + } + else + *(p+1)+=*p; + p+=packet_size; + } + p+=packet_size; + count-=row_size; + } + } + + status=MagickTrue; + p=pixels; + for (y=0; y < (ssize_t) image->rows; y++) + { + status=ReadPSDChannelPixels(image,channels,y,type,p,exception); + if (status == MagickFalse) + break; + + p+=row_size; + } + + compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); + pixels=(unsigned char *) RelinquishMagickMemory(pixels); + return(status); +} +","@@ -2542,9 +2542,12 @@ static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) + p=PushLongPixel(MSBEndian,p,&count); + if (id == 0x0000040f) + { +- (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- +- (PSDQuantum(count)+12)-(q-datum)); +- SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); ++ if ((q+PSDQuantum(count)+12) < (datum+length-16)) ++ { ++ (void) CopyMagickMemory(q,q+PSDQuantum(count)+12,length- ++ (PSDQuantum(count)+12)-(q-datum)); ++ SetStringInfoLength(bim_profile,length-(PSDQuantum(count)+12)); ++ } + break; + } + p+=count;",694,1025,2048 +18203," UriSuite() { + TEST_ADD(UriSuite::testDistinction) + TEST_ADD(UriSuite::testIpFour) + TEST_ADD(UriSuite::testIpSixPass) + TEST_ADD(UriSuite::testIpSixFail) + TEST_ADD(UriSuite::testUri) + TEST_ADD(UriSuite::testUriUserInfoHostPort1) + TEST_ADD(UriSuite::testUriUserInfoHostPort2) + TEST_ADD(UriSuite::testUriUserInfoHostPort22_Bug1948038) + TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_1) + TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_2) + TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_3) + TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_4) + TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_related_1) + TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_related_12) + TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_related_2) + TEST_ADD(UriSuite::testUriUserInfoHostPort3) + TEST_ADD(UriSuite::testUriUserInfoHostPort4) + TEST_ADD(UriSuite::testUriUserInfoHostPort5) + TEST_ADD(UriSuite::testUriUserInfoHostPort6) + TEST_ADD(UriSuite::testUriHostRegname) + TEST_ADD(UriSuite::testUriHostIpFour1) + TEST_ADD(UriSuite::testUriHostIpFour2) + TEST_ADD(UriSuite::testUriHostIpSix1) + TEST_ADD(UriSuite::testUriHostIpSix2) + TEST_ADD(UriSuite::testUriHostIpFuture) + TEST_ADD(UriSuite::testUriHostEmpty) + TEST_ADD(UriSuite::testUriComponents) + TEST_ADD(UriSuite::testUriComponents_Bug20070701) + TEST_ADD(UriSuite::testEscaping) + TEST_ADD(UriSuite::testUnescaping) + TEST_ADD(UriSuite::testTrailingSlash) + TEST_ADD(UriSuite::testAddBase) + TEST_ADD(UriSuite::testToString) + TEST_ADD(UriSuite::testToString_Bug1950126) + TEST_ADD(UriSuite::testToStringCharsRequired) + TEST_ADD(UriSuite::testToStringCharsRequired) + TEST_ADD(UriSuite::testNormalizeSyntaxMaskRequired) + TEST_ADD(UriSuite::testNormalizeSyntax) + TEST_ADD(UriSuite::testNormalizeSyntaxComponents) + TEST_ADD(UriSuite::testNormalizeCrash_Bug20080224) + TEST_ADD(UriSuite::testFilenameUriConversion) + TEST_ADD(UriSuite::testCrash_FreeUriMembers_Bug20080116) + TEST_ADD(UriSuite::testCrash_Report2418192) + TEST_ADD(UriSuite::testPervertedQueryString); + TEST_ADD(UriSuite::testQueryStringEndingInEqualSign_NonBug32); + TEST_ADD(UriSuite::testCrash_MakeOwner_Bug20080207) + TEST_ADD(UriSuite::testQueryList) + TEST_ADD(UriSuite::testQueryListPair) + TEST_ADD(UriSuite::testQueryDissection_Bug3590761) + TEST_ADD(UriSuite::testFreeCrash_Bug20080827) + TEST_ADD(UriSuite::testParseInvalid_Bug16) + TEST_ADD(UriSuite::testRangeComparison) + TEST_ADD(UriSuite::testRangeComparison_RemoveBaseUri_Issue19) + TEST_ADD(UriSuite::testEquals) + TEST_ADD(UriSuite::testHostTextTermination_Issue15) + } +",1," UriSuite() { + TEST_ADD(UriSuite::testDistinction) + TEST_ADD(UriSuite::testIpFour) + TEST_ADD(UriSuite::testIpSixPass) + TEST_ADD(UriSuite::testIpSixFail) + TEST_ADD(UriSuite::testUri) + TEST_ADD(UriSuite::testUriUserInfoHostPort1) + TEST_ADD(UriSuite::testUriUserInfoHostPort2) + TEST_ADD(UriSuite::testUriUserInfoHostPort22_Bug1948038) + TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_1) + TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_2) + TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_3) + TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_4) + TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_related_1) + TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_related_12) + TEST_ADD(UriSuite::testUriUserInfoHostPort23_Bug3510198_related_2) + TEST_ADD(UriSuite::testUriUserInfoHostPort3) + TEST_ADD(UriSuite::testUriUserInfoHostPort4) + TEST_ADD(UriSuite::testUriUserInfoHostPort5) + TEST_ADD(UriSuite::testUriUserInfoHostPort6) + TEST_ADD(UriSuite::testUriHostRegname) + TEST_ADD(UriSuite::testUriHostIpFour1) + TEST_ADD(UriSuite::testUriHostIpFour2) + TEST_ADD(UriSuite::testUriHostIpSix1) + TEST_ADD(UriSuite::testUriHostIpSix2) + TEST_ADD(UriSuite::testUriHostIpFuture) + TEST_ADD(UriSuite::testUriHostEmpty) + TEST_ADD(UriSuite::testUriComponents) + TEST_ADD(UriSuite::testUriComponents_Bug20070701) + TEST_ADD(UriSuite::testEscaping) + TEST_ADD(UriSuite::testUnescaping) + TEST_ADD(UriSuite::testTrailingSlash) + TEST_ADD(UriSuite::testAddBase) + TEST_ADD(UriSuite::testToString) + TEST_ADD(UriSuite::testToString_Bug1950126) + TEST_ADD(UriSuite::testToStringCharsRequired) + TEST_ADD(UriSuite::testToStringCharsRequired) + TEST_ADD(UriSuite::testNormalizeSyntaxMaskRequired) + TEST_ADD(UriSuite::testNormalizeSyntax) + TEST_ADD(UriSuite::testNormalizeSyntaxComponents) + TEST_ADD(UriSuite::testNormalizeCrash_Bug20080224) + TEST_ADD(UriSuite::testFilenameUriConversion) + TEST_ADD(UriSuite::testCrash_FreeUriMembers_Bug20080116) + TEST_ADD(UriSuite::testCrash_Report2418192) + TEST_ADD(UriSuite::testPervertedQueryString); + TEST_ADD(UriSuite::testQueryStringEndingInEqualSign_NonBug32); + TEST_ADD(UriSuite::testCrash_MakeOwner_Bug20080207) + TEST_ADD(UriSuite::testQueryList) + TEST_ADD(UriSuite::testQueryListPair) + TEST_ADD(UriSuite::testQueryDissection_Bug3590761) + TEST_ADD(UriSuite::testQueryCompositionMathWrite_GoogleAutofuzz113244572) + TEST_ADD(UriSuite::testFreeCrash_Bug20080827) + TEST_ADD(UriSuite::testParseInvalid_Bug16) + TEST_ADD(UriSuite::testRangeComparison) + TEST_ADD(UriSuite::testRangeComparison_RemoveBaseUri_Issue19) + TEST_ADD(UriSuite::testEquals) + TEST_ADD(UriSuite::testHostTextTermination_Issue15) + } +","@@ -104,6 +104,7 @@ class UriSuite : public Suite { + TEST_ADD(UriSuite::testQueryList) + TEST_ADD(UriSuite::testQueryListPair) + TEST_ADD(UriSuite::testQueryDissection_Bug3590761) ++ TEST_ADD(UriSuite::testQueryCompositionMathWrite_GoogleAutofuzz113244572) + TEST_ADD(UriSuite::testFreeCrash_Bug20080827) + TEST_ADD(UriSuite::testParseInvalid_Bug16) + TEST_ADD(UriSuite::testRangeComparison) +@@ -1749,6 +1750,37 @@ Rule | Example | hostSet | absPath | emptySeg + uriFreeQueryListA(queryList); + } + ++ void testQueryCompositionMathWrite_GoogleAutofuzz113244572() { ++ UriQueryListA second = { .key = ""\x11"", .value = NULL, .next = NULL }; ++ UriQueryListA first = { .key = ""\x01"", .value = ""\x02"", .next = &second }; ++ ++ const UriBool spaceToPlus = URI_TRUE; ++ const UriBool normalizeBreaks = URI_FALSE; /* for factor 3 but 6 */ ++ ++ const int charsRequired = (3 + 1 + 3) + 1 + (3); ++ ++ { ++ // Minimum space to hold everything fine ++ const char * const expected = ""%01=%02"" ""&"" ""%11""; ++ char dest[charsRequired + 1]; ++ int charsWritten; ++ TEST_ASSERT(uriComposeQueryExA(dest, &first, sizeof(dest), ++ &charsWritten, spaceToPlus, normalizeBreaks) ++ == URI_SUCCESS); ++ TEST_ASSERT(! strcmp(dest, expected)); ++ TEST_ASSERT(charsWritten == strlen(expected) + 1); ++ } ++ ++ { ++ // Previous math failed to take ampersand into account ++ char dest[charsRequired + 1 - 1]; ++ int charsWritten; ++ TEST_ASSERT(uriComposeQueryExA(dest, &first, sizeof(dest), ++ &charsWritten, spaceToPlus, normalizeBreaks) ++ == URI_ERROR_OUTPUT_TOO_LARGE); ++ } ++ } ++ + void testFreeCrash_Bug20080827() { + char const * const sourceUri = ""abc""; + char const * const baseUri = ""http://www.example.org/"";",832,1163,2048 +17480,"WORD32 ih264d_parse_islice(dec_struct_t *ps_dec, + UWORD16 u2_first_mb_in_slice) +{ + dec_pic_params_t * ps_pps = ps_dec->ps_cur_pps; + dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice; + UWORD32 *pu4_bitstrm_buf = ps_dec->ps_bitstrm->pu4_buffer; + UWORD32 *pu4_bitstrm_ofst = &ps_dec->ps_bitstrm->u4_ofst; + UWORD32 u4_temp; + WORD32 i_temp; + WORD32 ret; + + /*--------------------------------------------------------------------*/ + /* Read remaining contents of the slice header */ + /*--------------------------------------------------------------------*/ + /* dec_ref_pic_marking function */ + /* G050 */ + if(ps_slice->u1_nal_ref_idc != 0) + { + if(!ps_dec->ps_dpb_cmds->u1_dpb_commands_read) + ps_dec->u4_bitoffset = ih264d_read_mmco_commands( + ps_dec); + else + ps_dec->ps_bitstrm->u4_ofst += ps_dec->u4_bitoffset; + } + /* G050 */ + + /* Read slice_qp_delta */ + i_temp = ps_pps->u1_pic_init_qp + + ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf); + if((i_temp < 0) || (i_temp > 51)) + return ERROR_INV_RANGE_QP_T; + ps_slice->u1_slice_qp = i_temp; + COPYTHECONTEXT(""SH: slice_qp_delta"", + ps_slice->u1_slice_qp - ps_pps->u1_pic_init_qp); + + if(ps_pps->u1_deblocking_filter_parameters_present_flag == 1) + { + u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); + COPYTHECONTEXT(""SH: disable_deblocking_filter_idc"", u4_temp); + + if(u4_temp > SLICE_BOUNDARY_DBLK_DISABLED) + { + return ERROR_INV_SLICE_HDR_T; + } + ps_slice->u1_disable_dblk_filter_idc = u4_temp; + if(u4_temp != 1) + { + i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf) + << 1; + if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF)) + { + return ERROR_INV_SLICE_HDR_T; + } + ps_slice->i1_slice_alpha_c0_offset = i_temp; + COPYTHECONTEXT(""SH: slice_alpha_c0_offset_div2"", + ps_slice->i1_slice_alpha_c0_offset >> 1); + + i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf) + << 1; + if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF)) + { + return ERROR_INV_SLICE_HDR_T; + } + ps_slice->i1_slice_beta_offset = i_temp; + COPYTHECONTEXT(""SH: slice_beta_offset_div2"", + ps_slice->i1_slice_beta_offset >> 1); + + } + else + { + ps_slice->i1_slice_alpha_c0_offset = 0; + ps_slice->i1_slice_beta_offset = 0; + } + } + else + { + ps_slice->u1_disable_dblk_filter_idc = 0; + ps_slice->i1_slice_alpha_c0_offset = 0; + ps_slice->i1_slice_beta_offset = 0; + } + + /* Initialization to check if number of motion vector per 2 Mbs */ + /* are exceeding the range or not */ + ps_dec->u2_mv_2mb[0] = 0; + ps_dec->u2_mv_2mb[1] = 0; + + + /*set slice header cone to 2 ,to indicate correct header*/ + ps_dec->u1_slice_header_done = 2; + + if(ps_pps->u1_entropy_coding_mode) + { + SWITCHOFFTRACE; SWITCHONTRACECABAC; + if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag) + { + ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_mbaff; + } + else + ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_nonmbaff; + + ret = ih264d_parse_islice_data_cabac(ps_dec, ps_slice, + u2_first_mb_in_slice); + if(ret != OK) + return ret; + SWITCHONTRACE; SWITCHOFFTRACECABAC; + } + else + { + if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag) + { + ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_mbaff; + } + else + ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_nonmbaff; + ret = ih264d_parse_islice_data_cavlc(ps_dec, ps_slice, + u2_first_mb_in_slice); + if(ret != OK) + return ret; + } + + return OK; +} +",0,"WORD32 ih264d_parse_islice(dec_struct_t *ps_dec, + UWORD16 u2_first_mb_in_slice) +{ + dec_pic_params_t * ps_pps = ps_dec->ps_cur_pps; + dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice; + UWORD32 *pu4_bitstrm_buf = ps_dec->ps_bitstrm->pu4_buffer; + UWORD32 *pu4_bitstrm_ofst = &ps_dec->ps_bitstrm->u4_ofst; + UWORD32 u4_temp; + WORD32 i_temp; + WORD32 ret; + + /*--------------------------------------------------------------------*/ + /* Read remaining contents of the slice header */ + /*--------------------------------------------------------------------*/ + /* dec_ref_pic_marking function */ + /* G050 */ + if(ps_slice->u1_nal_ref_idc != 0) + { + if(!ps_dec->ps_dpb_cmds->u1_dpb_commands_read) + ps_dec->u4_bitoffset = ih264d_read_mmco_commands( + ps_dec); + else + ps_dec->ps_bitstrm->u4_ofst += ps_dec->u4_bitoffset; + } + /* G050 */ + + /* Read slice_qp_delta */ + i_temp = ps_pps->u1_pic_init_qp + + ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf); + if((i_temp < 0) || (i_temp > 51)) + return ERROR_INV_RANGE_QP_T; + ps_slice->u1_slice_qp = i_temp; + COPYTHECONTEXT(""SH: slice_qp_delta"", + ps_slice->u1_slice_qp - ps_pps->u1_pic_init_qp); + + if(ps_pps->u1_deblocking_filter_parameters_present_flag == 1) + { + u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); + COPYTHECONTEXT(""SH: disable_deblocking_filter_idc"", u4_temp); + + if(u4_temp > SLICE_BOUNDARY_DBLK_DISABLED) + { + return ERROR_INV_SLICE_HDR_T; + } + ps_slice->u1_disable_dblk_filter_idc = u4_temp; + if(u4_temp != 1) + { + i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf) + << 1; + if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF)) + { + return ERROR_INV_SLICE_HDR_T; + } + ps_slice->i1_slice_alpha_c0_offset = i_temp; + COPYTHECONTEXT(""SH: slice_alpha_c0_offset_div2"", + ps_slice->i1_slice_alpha_c0_offset >> 1); + + i_temp = ih264d_sev(pu4_bitstrm_ofst, pu4_bitstrm_buf) + << 1; + if((MIN_DBLK_FIL_OFF > i_temp) || (i_temp > MAX_DBLK_FIL_OFF)) + { + return ERROR_INV_SLICE_HDR_T; + } + ps_slice->i1_slice_beta_offset = i_temp; + COPYTHECONTEXT(""SH: slice_beta_offset_div2"", + ps_slice->i1_slice_beta_offset >> 1); + + } + else + { + ps_slice->i1_slice_alpha_c0_offset = 0; + ps_slice->i1_slice_beta_offset = 0; + } + } + else + { + ps_slice->u1_disable_dblk_filter_idc = 0; + ps_slice->i1_slice_alpha_c0_offset = 0; + ps_slice->i1_slice_beta_offset = 0; + } + + /* Initialization to check if number of motion vector per 2 Mbs */ + /* are exceeding the range or not */ + ps_dec->u2_mv_2mb[0] = 0; + ps_dec->u2_mv_2mb[1] = 0; + + + /*set slice header cone to 2 ,to indicate correct header*/ + ps_dec->u1_slice_header_done = 2; + + if(ps_pps->u1_entropy_coding_mode) + { + SWITCHOFFTRACE; SWITCHONTRACECABAC; + if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag) + { + ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_mbaff; + } + else + ps_dec->pf_get_mb_info = ih264d_get_mb_info_cabac_nonmbaff; + + ret = ih264d_parse_islice_data_cabac(ps_dec, ps_slice, + u2_first_mb_in_slice); + if(ret != OK) + return ret; + SWITCHONTRACE; SWITCHOFFTRACECABAC; + } + else + { + if(ps_dec->ps_cur_slice->u1_mbaff_frame_flag) + { + ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_mbaff; + } + else + ps_dec->pf_get_mb_info = ih264d_get_mb_info_cavlc_nonmbaff; + ret = ih264d_parse_islice_data_cavlc(ps_dec, ps_slice, + u2_first_mb_in_slice); + if(ret != OK) + return ret; + } + + return OK; +} +","@@ -899,7 +899,6 @@ + + (UWORD16)(u1_num_mbs >> u1_mbaff)); + } + u1_num_mbs++; +- ps_dec->u2_total_mbs_coded++; + + /****************************************************************/ + /* Check for End Of Row */ +@@ -929,7 +928,7 @@ + + u1_num_mbs_next, u1_tfr_n_mb, + u1_end_of_row); + } +- ++ ps_dec->u2_total_mbs_coded += u1_num_mbs; + if(u1_tfr_n_mb) + u1_num_mbs = 0; + u1_mb_idx = u1_num_mbs; +@@ -1119,7 +1118,6 @@ + + (UWORD16)(u1_num_mbs >> u1_mbaff)); + } + u1_num_mbs++; +- ps_dec->u2_total_mbs_coded++; + + } + +@@ -1148,7 +1146,7 @@ + + u1_num_mbs_next, u1_tfr_n_mb, + u1_end_of_row); + } +- ++ ps_dec->u2_total_mbs_coded += u1_num_mbs; + if(u1_tfr_n_mb) + u1_num_mbs = 0; + u1_mb_idx = u1_num_mbs; +",1118,1449,2048 +17897,"int handle_ldf_stq(u32 insn, struct pt_regs *regs) +{ + unsigned long addr = compute_effective_address(regs, insn, 0); + int freg = ((insn >> 25) & 0x1e) | ((insn >> 20) & 0x20); + struct fpustate *f = FPUSTATE; + int asi = decode_asi(insn, regs); + int flag = (freg < 32) ? FPRS_DL : FPRS_DU; + + perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0); + + save_and_clear_fpu(); + current_thread_info()->xfsr[0] &= ~0x1c000; + if (freg & 3) { + current_thread_info()->xfsr[0] |= (6 << 14) /* invalid_fp_register */; + do_fpother(regs); + return 0; + } + if (insn & 0x200000) { + /* STQ */ + u64 first = 0, second = 0; + + if (current_thread_info()->fpsaved[0] & flag) { + first = *(u64 *)&f->regs[freg]; + second = *(u64 *)&f->regs[freg+2]; + } + if (asi < 0x80) { + do_privact(regs); + return 1; + } + switch (asi) { + case ASI_P: + case ASI_S: break; + case ASI_PL: + case ASI_SL: + { + /* Need to convert endians */ + u64 tmp = __swab64p(&first); + + first = __swab64p(&second); + second = tmp; + break; + } + default: + if (tlb_type == hypervisor) + sun4v_data_access_exception(regs, addr, 0); + else + spitfire_data_access_exception(regs, 0, addr); + return 1; + } + if (put_user (first >> 32, (u32 __user *)addr) || + __put_user ((u32)first, (u32 __user *)(addr + 4)) || + __put_user (second >> 32, (u32 __user *)(addr + 8)) || + __put_user ((u32)second, (u32 __user *)(addr + 12))) { + if (tlb_type == hypervisor) + sun4v_data_access_exception(regs, addr, 0); + else + spitfire_data_access_exception(regs, 0, addr); + return 1; + } + } else { + /* LDF, LDDF, LDQF */ + u32 data[4] __attribute__ ((aligned(8))); + int size, i; + int err; + + if (asi < 0x80) { + do_privact(regs); + return 1; + } else if (asi > ASI_SNFL) { + if (tlb_type == hypervisor) + sun4v_data_access_exception(regs, addr, 0); + else + spitfire_data_access_exception(regs, 0, addr); + return 1; + } + switch (insn & 0x180000) { + case 0x000000: size = 1; break; + case 0x100000: size = 4; break; + default: size = 2; break; + } + for (i = 0; i < size; i++) + data[i] = 0; + + err = get_user (data[0], (u32 __user *) addr); + if (!err) { + for (i = 1; i < size; i++) + err |= __get_user (data[i], (u32 __user *)(addr + 4*i)); + } + if (err && !(asi & 0x2 /* NF */)) { + if (tlb_type == hypervisor) + sun4v_data_access_exception(regs, addr, 0); + else + spitfire_data_access_exception(regs, 0, addr); + return 1; + } + if (asi & 0x8) /* Little */ { + u64 tmp; + + switch (size) { + case 1: data[0] = le32_to_cpup(data + 0); break; + default:*(u64 *)(data + 0) = le64_to_cpup((u64 *)(data + 0)); + break; + case 4: tmp = le64_to_cpup((u64 *)(data + 0)); + *(u64 *)(data + 0) = le64_to_cpup((u64 *)(data + 2)); + *(u64 *)(data + 2) = tmp; + break; + } + } + if (!(current_thread_info()->fpsaved[0] & FPRS_FEF)) { + current_thread_info()->fpsaved[0] = FPRS_FEF; + current_thread_info()->gsr[0] = 0; + } + if (!(current_thread_info()->fpsaved[0] & flag)) { + if (freg < 32) + memset(f->regs, 0, 32*sizeof(u32)); + else + memset(f->regs+32, 0, 32*sizeof(u32)); + } + memcpy(f->regs + freg, data, size * 4); + current_thread_info()->fpsaved[0] |= flag; + } + advance(regs); + return 1; +} +",1,"int handle_ldf_stq(u32 insn, struct pt_regs *regs) +{ + unsigned long addr = compute_effective_address(regs, insn, 0); + int freg = ((insn >> 25) & 0x1e) | ((insn >> 20) & 0x20); + struct fpustate *f = FPUSTATE; + int asi = decode_asi(insn, regs); + int flag = (freg < 32) ? FPRS_DL : FPRS_DU; + + perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, regs, 0); + + save_and_clear_fpu(); + current_thread_info()->xfsr[0] &= ~0x1c000; + if (freg & 3) { + current_thread_info()->xfsr[0] |= (6 << 14) /* invalid_fp_register */; + do_fpother(regs); + return 0; + } + if (insn & 0x200000) { + /* STQ */ + u64 first = 0, second = 0; + + if (current_thread_info()->fpsaved[0] & flag) { + first = *(u64 *)&f->regs[freg]; + second = *(u64 *)&f->regs[freg+2]; + } + if (asi < 0x80) { + do_privact(regs); + return 1; + } + switch (asi) { + case ASI_P: + case ASI_S: break; + case ASI_PL: + case ASI_SL: + { + /* Need to convert endians */ + u64 tmp = __swab64p(&first); + + first = __swab64p(&second); + second = tmp; + break; + } + default: + if (tlb_type == hypervisor) + sun4v_data_access_exception(regs, addr, 0); + else + spitfire_data_access_exception(regs, 0, addr); + return 1; + } + if (put_user (first >> 32, (u32 __user *)addr) || + __put_user ((u32)first, (u32 __user *)(addr + 4)) || + __put_user (second >> 32, (u32 __user *)(addr + 8)) || + __put_user ((u32)second, (u32 __user *)(addr + 12))) { + if (tlb_type == hypervisor) + sun4v_data_access_exception(regs, addr, 0); + else + spitfire_data_access_exception(regs, 0, addr); + return 1; + } + } else { + /* LDF, LDDF, LDQF */ + u32 data[4] __attribute__ ((aligned(8))); + int size, i; + int err; + + if (asi < 0x80) { + do_privact(regs); + return 1; + } else if (asi > ASI_SNFL) { + if (tlb_type == hypervisor) + sun4v_data_access_exception(regs, addr, 0); + else + spitfire_data_access_exception(regs, 0, addr); + return 1; + } + switch (insn & 0x180000) { + case 0x000000: size = 1; break; + case 0x100000: size = 4; break; + default: size = 2; break; + } + for (i = 0; i < size; i++) + data[i] = 0; + + err = get_user (data[0], (u32 __user *) addr); + if (!err) { + for (i = 1; i < size; i++) + err |= __get_user (data[i], (u32 __user *)(addr + 4*i)); + } + if (err && !(asi & 0x2 /* NF */)) { + if (tlb_type == hypervisor) + sun4v_data_access_exception(regs, addr, 0); + else + spitfire_data_access_exception(regs, 0, addr); + return 1; + } + if (asi & 0x8) /* Little */ { + u64 tmp; + + switch (size) { + case 1: data[0] = le32_to_cpup(data + 0); break; + default:*(u64 *)(data + 0) = le64_to_cpup((u64 *)(data + 0)); + break; + case 4: tmp = le64_to_cpup((u64 *)(data + 0)); + *(u64 *)(data + 0) = le64_to_cpup((u64 *)(data + 2)); + *(u64 *)(data + 2) = tmp; + break; + } + } + if (!(current_thread_info()->fpsaved[0] & FPRS_FEF)) { + current_thread_info()->fpsaved[0] = FPRS_FEF; + current_thread_info()->gsr[0] = 0; + } + if (!(current_thread_info()->fpsaved[0] & flag)) { + if (freg < 32) + memset(f->regs, 0, 32*sizeof(u32)); + else + memset(f->regs+32, 0, 32*sizeof(u32)); + } + memcpy(f->regs + freg, data, size * 4); + current_thread_info()->fpsaved[0] |= flag; + } + advance(regs); + return 1; +} +","@@ -317,7 +317,7 @@ asmlinkage void kernel_unaligned_trap(struct pt_regs *regs, unsigned int insn) + + addr = compute_effective_address(regs, insn, + ((insn >> 25) & 0x1f)); +- perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, addr); ++ perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, regs, addr); + switch (asi) { + case ASI_NL: + case ASI_AIUPL: +@@ -384,7 +384,7 @@ int handle_popc(u32 insn, struct pt_regs *regs) + int ret, i, rd = ((insn >> 25) & 0x1f); + int from_kernel = (regs->tstate & TSTATE_PRIV) != 0; + +- perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0); ++ perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, regs, 0); + if (insn & 0x2000) { + maybe_flush_windows(0, 0, rd, from_kernel); + value = sign_extend_imm13(insn); +@@ -431,7 +431,7 @@ int handle_ldf_stq(u32 insn, struct pt_regs *regs) + int asi = decode_asi(insn, regs); + int flag = (freg < 32) ? FPRS_DL : FPRS_DU; + +- perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0); ++ perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, regs, 0); + + save_and_clear_fpu(); + current_thread_info()->xfsr[0] &= ~0x1c000; +@@ -554,7 +554,7 @@ void handle_ld_nf(u32 insn, struct pt_regs *regs) + int from_kernel = (regs->tstate & TSTATE_PRIV) != 0; + unsigned long *reg; + +- perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0); ++ perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, regs, 0); + + maybe_flush_windows(0, 0, rd, from_kernel); + reg = fetch_reg_addr(rd, regs); +@@ -586,7 +586,7 @@ void handle_lddfmna(struct pt_regs *regs, unsigned long sfar, unsigned long sfsr + + if (tstate & TSTATE_PRIV) + die_if_kernel(""lddfmna from kernel"", regs); +- perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, sfar); ++ perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, regs, sfar); + if (test_thread_flag(TIF_32BIT)) + pc = (u32)pc; + if (get_user(insn, (u32 __user *) pc) != -EFAULT) { +@@ -647,7 +647,7 @@ void handle_stdfmna(struct pt_regs *regs, unsigned long sfar, unsigned long sfsr + + if (tstate & TSTATE_PRIV) + die_if_kernel(""stdfmna from kernel"", regs); +- perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, 0, regs, sfar); ++ perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, 1, regs, sfar); + if (test_thread_flag(TIF_32BIT)) + pc = (u32)pc; + if (get_user(insn, (u32 __user *) pc) != -EFAULT) {",1292,1623,2048 +7377,"enum nss_status _nss_mymachines_gethostbyname3_r( + const char *name, + int af, + struct hostent *result, + char *buffer, size_t buflen, + int *errnop, int *h_errnop, + int32_t *ttlp, + char **canonp) { + + _cleanup_bus_message_unref_ sd_bus_message* reply = NULL; + _cleanup_bus_flush_close_unref_ sd_bus *bus = NULL; + _cleanup_free_ char *class = NULL; + unsigned c = 0, i = 0; + char *r_name, *r_aliases, *r_addr, *r_addr_list; + size_t l, idx, ms, alen; + int r; + + assert(name); + assert(result); + assert(buffer); + assert(errnop); + assert(h_errnop); + + if (af == AF_UNSPEC) + af = AF_INET; + + if (af != AF_INET && af != AF_INET6) { + r = -EAFNOSUPPORT; + goto fail; + } + + r = sd_machine_get_class(name, &class); + if (r < 0) + goto fail; + if (!streq(class, ""container"")) { + r = -ENOTTY; + goto fail; + } + + r = sd_bus_open_system(&bus); + if (r < 0) + goto fail; + + r = sd_bus_call_method(bus, + ""org.freedesktop.machine1"", + ""/org/freedesktop/machine1"", + ""org.freedesktop.machine1.Manager"", + ""GetMachineAddresses"", + NULL, + &reply, + ""s"", name); + if (r < 0) + goto fail; + + r = sd_bus_message_enter_container(reply, 'a', ""(iay)""); + if (r < 0) + goto fail; + + r = count_addresses(reply, af, &c); + if (r < 0) + goto fail; + + if (c <= 0) { + *errnop = ENOENT; + *h_errnop = HOST_NOT_FOUND; + return NSS_STATUS_NOTFOUND; + } + + alen = FAMILY_ADDRESS_SIZE(af); + l = strlen(name); + + ms = ALIGN(l+1) + c * ALIGN(alen) + (c+2) * sizeof(char*); + + if (buflen < ms) { + *errnop = ENOMEM; + *h_errnop = NO_RECOVERY; + return NSS_STATUS_TRYAGAIN; + } + + /* First, append name */ + r_name = buffer; + memcpy(r_name, name, l+1); + idx = ALIGN(l+1); + + /* Second, create aliases array */ + r_aliases = buffer + idx; + ((char**) r_aliases)[0] = NULL; + idx += sizeof(char*); + + /* Third, append addresses */ + r_addr = buffer + idx; + while ((r = sd_bus_message_enter_container(reply, 'r', ""iay"")) > 0) { + int family; + const void *a; + size_t sz; + + r = sd_bus_message_read(reply, ""i"", &family); + if (r < 0) + goto fail; + + r = sd_bus_message_read_array(reply, 'y', &a, &sz); + if (r < 0) + goto fail; + + r = sd_bus_message_exit_container(reply); + if (r < 0) + goto fail; + + if (family != af) + continue; + + if (sz != alen) { + r = -EINVAL; + goto fail; + } + + memcpy(r_addr + i*ALIGN(alen), a, alen); + i++; + } + + assert(i == c); + idx += c * ALIGN(alen); + + r = sd_bus_message_exit_container(reply); + if (r < 0) + goto fail; + + /* Third, append address pointer array */ + r_addr_list = buffer + idx; + for (i = 0; i < c; i++) + ((char**) r_addr_list)[i] = r_addr + i*ALIGN(alen); + + ((char**) r_addr_list)[i] = NULL; + idx += (c+1) * sizeof(char*); + + assert(idx == ms); + + result->h_name = r_name; + result->h_aliases = (char**) r_aliases; + result->h_addrtype = af; + result->h_length = alen; + result->h_addr_list = (char**) r_addr_list; + + if (ttlp) + *ttlp = 0; + + if (canonp) + *canonp = r_name; + + /* Explicitly reset all error variables */ + *errnop = 0; + *h_errnop = NETDB_SUCCESS; + h_errno = 0; + + return NSS_STATUS_SUCCESS; + +fail: + *errnop = -r; + *h_errnop = NO_DATA; + return NSS_STATUS_UNAVAIL; +} +",0,"enum nss_status _nss_mymachines_gethostbyname3_r( + const char *name, + int af, + struct hostent *result, + char *buffer, size_t buflen, + int *errnop, int *h_errnop, + int32_t *ttlp, + char **canonp) { + + _cleanup_bus_message_unref_ sd_bus_message* reply = NULL; + _cleanup_bus_flush_close_unref_ sd_bus *bus = NULL; + _cleanup_free_ char *class = NULL; + unsigned c = 0, i = 0; + char *r_name, *r_aliases, *r_addr, *r_addr_list; + size_t l, idx, ms, alen; + int r; + + assert(name); + assert(result); + assert(buffer); + assert(errnop); + assert(h_errnop); + + if (af == AF_UNSPEC) + af = AF_INET; + + if (af != AF_INET && af != AF_INET6) { + r = -EAFNOSUPPORT; + goto fail; + } + + r = sd_machine_get_class(name, &class); + if (r < 0) + goto fail; + if (!streq(class, ""container"")) { + r = -ENOTTY; + goto fail; + } + + r = sd_bus_open_system(&bus); + if (r < 0) + goto fail; + + r = sd_bus_call_method(bus, + ""org.freedesktop.machine1"", + ""/org/freedesktop/machine1"", + ""org.freedesktop.machine1.Manager"", + ""GetMachineAddresses"", + NULL, + &reply, + ""s"", name); + if (r < 0) + goto fail; + + r = sd_bus_message_enter_container(reply, 'a', ""(iay)""); + if (r < 0) + goto fail; + + r = count_addresses(reply, af, &c); + if (r < 0) + goto fail; + + if (c <= 0) { + *errnop = ENOENT; + *h_errnop = HOST_NOT_FOUND; + return NSS_STATUS_NOTFOUND; + } + + alen = FAMILY_ADDRESS_SIZE(af); + l = strlen(name); + + ms = ALIGN(l+1) + c * ALIGN(alen) + (c+2) * sizeof(char*); + + if (buflen < ms) { + *errnop = ENOMEM; + *h_errnop = NO_RECOVERY; + return NSS_STATUS_TRYAGAIN; + } + + /* First, append name */ + r_name = buffer; + memcpy(r_name, name, l+1); + idx = ALIGN(l+1); + + /* Second, create aliases array */ + r_aliases = buffer + idx; + ((char**) r_aliases)[0] = NULL; + idx += sizeof(char*); + + /* Third, append addresses */ + r_addr = buffer + idx; + while ((r = sd_bus_message_enter_container(reply, 'r', ""iay"")) > 0) { + int family; + const void *a; + size_t sz; + + r = sd_bus_message_read(reply, ""i"", &family); + if (r < 0) + goto fail; + + r = sd_bus_message_read_array(reply, 'y', &a, &sz); + if (r < 0) + goto fail; + + r = sd_bus_message_exit_container(reply); + if (r < 0) + goto fail; + + if (family != af) + continue; + + if (sz != alen) { + r = -EINVAL; + goto fail; + } + + memcpy(r_addr + i*ALIGN(alen), a, alen); + i++; + } + + assert(i == c); + idx += c * ALIGN(alen); + + r = sd_bus_message_exit_container(reply); + if (r < 0) + goto fail; + + /* Third, append address pointer array */ + r_addr_list = buffer + idx; + for (i = 0; i < c; i++) + ((char**) r_addr_list)[i] = r_addr + i*ALIGN(alen); + + ((char**) r_addr_list)[i] = NULL; + idx += (c+1) * sizeof(char*); + + assert(idx == ms); + + result->h_name = r_name; + result->h_aliases = (char**) r_aliases; + result->h_addrtype = af; + result->h_length = alen; + result->h_addr_list = (char**) r_addr_list; + + if (ttlp) + *ttlp = 0; + + if (canonp) + *canonp = r_name; + + /* Explicitly reset all error variables */ + *errnop = 0; + *h_errnop = NETDB_SUCCESS; + h_errno = 0; + + return NSS_STATUS_SUCCESS; + +fail: + *errnop = -r; + *h_errnop = NO_DATA; + return NSS_STATUS_UNAVAIL; +} +","@@ -416,6 +416,9 @@ enum nss_status _nss_mymachines_getpwnam_r( + if (!e || e == p) + goto not_found; + ++ if (e - p > HOST_NAME_MAX - 1) /* -1 for the last dash */ ++ goto not_found; ++ + r = parse_uid(e + 1, &uid); + if (r < 0) + goto not_found; +@@ -573,6 +576,9 @@ enum nss_status _nss_mymachines_getgrnam_r( + if (!e || e == p) + goto not_found; + ++ if (e - p > HOST_NAME_MAX - 1) /* -1 for the last dash */ ++ goto not_found; ++ + r = parse_gid(e + 1, &gid); + if (r < 0) + goto not_found;",1059,1390,2048 +15218,"void RenderFrameImpl::BeginNavigationInternal( + std::unique_ptr info) { + std::unique_ptr document_state_owned = BuildDocumentState(); + DocumentState* document_state = document_state_owned.get(); + if (!frame_->CreatePlaceholderDocumentLoader( + *info, std::move(document_state_owned))) { + return; + } + + browser_side_navigation_pending_ = true; + browser_side_navigation_pending_url_ = info->url_request.Url(); + + blink::WebURLRequest& request = info->url_request; + + WebDocument frame_document = frame_->GetDocument(); + if (info->frame_type == network::mojom::RequestContextFrameType::kTopLevel) + request.SetSiteForCookies(request.Url()); + else + request.SetSiteForCookies(frame_document.SiteForCookies()); + + ui::PageTransition transition_type = GetTransitionType( + ui::PAGE_TRANSITION_LINK, + info->frame_load_type == WebFrameLoadType::kReplaceCurrentItem, + IsMainFrame(), info->navigation_type); + if (info->is_client_redirect) { + transition_type = ui::PageTransitionFromInt( + transition_type | ui::PAGE_TRANSITION_CLIENT_REDIRECT); + } + + WillSendRequestInternal( + request, + frame_->Parent() ? ResourceType::kSubFrame : ResourceType::kMainFrame, + document_state, transition_type); + + if (!info->url_request.GetExtraData()) + info->url_request.SetExtraData(std::make_unique()); + + DCHECK_EQ(network::mojom::FetchRequestMode::kNavigate, + info->url_request.GetFetchRequestMode()); + DCHECK_EQ(network::mojom::FetchCredentialsMode::kInclude, + info->url_request.GetFetchCredentialsMode()); + DCHECK_EQ(network::mojom::FetchRedirectMode::kManual, + info->url_request.GetFetchRedirectMode()); + DCHECK(frame_->Parent() || + info->frame_type == + network::mojom::RequestContextFrameType::kTopLevel); + DCHECK(!frame_->Parent() || + info->frame_type == network::mojom::RequestContextFrameType::kNested); + + bool is_form_submission = + info->navigation_type == blink::kWebNavigationTypeFormSubmitted || + info->navigation_type == blink::kWebNavigationTypeFormResubmitted; + + GURL searchable_form_url; + std::string searchable_form_encoding; + if (!info->form.IsNull()) { + WebSearchableFormData web_searchable_form_data(info->form); + searchable_form_url = web_searchable_form_data.Url(); + searchable_form_encoding = web_searchable_form_data.Encoding().Utf8(); + } + + GURL client_side_redirect_url; + if (info->is_client_redirect) + client_side_redirect_url = frame_->GetDocument().Url(); + + blink::mojom::BlobURLTokenPtr blob_url_token( + CloneBlobURLToken(info->blob_url_token.get())); + + int load_flags = info->url_request.GetLoadFlagsForWebUrlRequest(); + std::unique_ptr initiator = + GetDevToolsInitiator(info->devtools_initiator_info); + mojom::BeginNavigationParamsPtr begin_navigation_params = + mojom::BeginNavigationParams::New( + GetWebURLRequestHeadersAsString(info->url_request), load_flags, + info->url_request.GetSkipServiceWorker(), + GetRequestContextTypeForWebURLRequest(info->url_request), + GetMixedContentContextTypeForWebURLRequest(info->url_request), + is_form_submission, searchable_form_url, searchable_form_encoding, + client_side_redirect_url, + initiator ? base::make_optional(std::move(*initiator)) + : base::nullopt); + + mojom::NavigationClientAssociatedPtrInfo navigation_client_info; + if (IsPerNavigationMojoInterfaceEnabled()) { + BindNavigationClient(mojo::MakeRequest(&navigation_client_info)); + navigation_client_impl_->MarkWasInitiatedInThisFrame(); + } + + blink::mojom::NavigationInitiatorPtr initiator_ptr( + blink::mojom::NavigationInitiatorPtrInfo( + std::move(info->navigation_initiator_handle), 0)); + + bool current_frame_has_download_sandbox_flag = + !frame_->IsAllowedToDownloadWithoutUserActivation(); + bool has_download_sandbox_flag = + info->initiator_frame_has_download_sandbox_flag || + current_frame_has_download_sandbox_flag; + bool from_ad = info->initiator_frame_is_ad || frame_->IsAdSubframe(); + + GetFrameHost()->BeginNavigation( + MakeCommonNavigationParams(frame_->GetSecurityOrigin(), std::move(info), + load_flags, has_download_sandbox_flag, + from_ad), + std::move(begin_navigation_params), std::move(blob_url_token), + std::move(navigation_client_info), std::move(initiator_ptr)); +} +",0,"void RenderFrameImpl::BeginNavigationInternal( + std::unique_ptr info) { + std::unique_ptr document_state_owned = BuildDocumentState(); + DocumentState* document_state = document_state_owned.get(); + if (!frame_->CreatePlaceholderDocumentLoader( + *info, std::move(document_state_owned))) { + return; + } + + browser_side_navigation_pending_ = true; + browser_side_navigation_pending_url_ = info->url_request.Url(); + + blink::WebURLRequest& request = info->url_request; + + WebDocument frame_document = frame_->GetDocument(); + if (info->frame_type == network::mojom::RequestContextFrameType::kTopLevel) + request.SetSiteForCookies(request.Url()); + else + request.SetSiteForCookies(frame_document.SiteForCookies()); + + ui::PageTransition transition_type = GetTransitionType( + ui::PAGE_TRANSITION_LINK, + info->frame_load_type == WebFrameLoadType::kReplaceCurrentItem, + IsMainFrame(), info->navigation_type); + if (info->is_client_redirect) { + transition_type = ui::PageTransitionFromInt( + transition_type | ui::PAGE_TRANSITION_CLIENT_REDIRECT); + } + + WillSendRequestInternal( + request, + frame_->Parent() ? ResourceType::kSubFrame : ResourceType::kMainFrame, + document_state, transition_type); + + if (!info->url_request.GetExtraData()) + info->url_request.SetExtraData(std::make_unique()); + + DCHECK_EQ(network::mojom::FetchRequestMode::kNavigate, + info->url_request.GetFetchRequestMode()); + DCHECK_EQ(network::mojom::FetchCredentialsMode::kInclude, + info->url_request.GetFetchCredentialsMode()); + DCHECK_EQ(network::mojom::FetchRedirectMode::kManual, + info->url_request.GetFetchRedirectMode()); + DCHECK(frame_->Parent() || + info->frame_type == + network::mojom::RequestContextFrameType::kTopLevel); + DCHECK(!frame_->Parent() || + info->frame_type == network::mojom::RequestContextFrameType::kNested); + + bool is_form_submission = + info->navigation_type == blink::kWebNavigationTypeFormSubmitted || + info->navigation_type == blink::kWebNavigationTypeFormResubmitted; + + GURL searchable_form_url; + std::string searchable_form_encoding; + if (!info->form.IsNull()) { + WebSearchableFormData web_searchable_form_data(info->form); + searchable_form_url = web_searchable_form_data.Url(); + searchable_form_encoding = web_searchable_form_data.Encoding().Utf8(); + } + + GURL client_side_redirect_url; + if (info->is_client_redirect) + client_side_redirect_url = frame_->GetDocument().Url(); + + blink::mojom::BlobURLTokenPtr blob_url_token( + CloneBlobURLToken(info->blob_url_token.get())); + + int load_flags = info->url_request.GetLoadFlagsForWebUrlRequest(); + std::unique_ptr initiator = + GetDevToolsInitiator(info->devtools_initiator_info); + mojom::BeginNavigationParamsPtr begin_navigation_params = + mojom::BeginNavigationParams::New( + GetWebURLRequestHeadersAsString(info->url_request), load_flags, + info->url_request.GetSkipServiceWorker(), + GetRequestContextTypeForWebURLRequest(info->url_request), + GetMixedContentContextTypeForWebURLRequest(info->url_request), + is_form_submission, searchable_form_url, searchable_form_encoding, + client_side_redirect_url, + initiator ? base::make_optional(std::move(*initiator)) + : base::nullopt); + + mojom::NavigationClientAssociatedPtrInfo navigation_client_info; + if (IsPerNavigationMojoInterfaceEnabled()) { + BindNavigationClient(mojo::MakeRequest(&navigation_client_info)); + navigation_client_impl_->MarkWasInitiatedInThisFrame(); + } + + blink::mojom::NavigationInitiatorPtr initiator_ptr( + blink::mojom::NavigationInitiatorPtrInfo( + std::move(info->navigation_initiator_handle), 0)); + + bool current_frame_has_download_sandbox_flag = + !frame_->IsAllowedToDownloadWithoutUserActivation(); + bool has_download_sandbox_flag = + info->initiator_frame_has_download_sandbox_flag || + current_frame_has_download_sandbox_flag; + bool from_ad = info->initiator_frame_is_ad || frame_->IsAdSubframe(); + + GetFrameHost()->BeginNavigation( + MakeCommonNavigationParams(frame_->GetSecurityOrigin(), std::move(info), + load_flags, has_download_sandbox_flag, + from_ad), + std::move(begin_navigation_params), std::move(blob_url_token), + std::move(navigation_client_info), std::move(initiator_ptr)); +} +","@@ -4545,9 +4545,9 @@ void RenderFrameImpl::DidAddMessageToConsole( + } + } + +- Send(new FrameHostMsg_DidAddMessageToConsole( +- routing_id_, static_cast(log_severity), message.text.Utf16(), +- static_cast(source_line), source_name.Utf16())); ++ GetFrameHost()->DidAddMessageToConsole(message.level, message.text.Utf16(), ++ static_cast(source_line), ++ source_name.Utf16()); + } + + void RenderFrameImpl::DownloadURL(",991,1322,2048 +4739,"static int __driver_rfc4106_decrypt(struct aead_request *req) +{ + u8 one_entry_in_sg = 0; + u8 *src, *dst, *assoc; + unsigned long tempCipherLen = 0; + __be32 counter = cpu_to_be32(1); + int retval = 0; + struct crypto_aead *tfm = crypto_aead_reqtfm(req); + struct aesni_rfc4106_gcm_ctx *ctx = aesni_rfc4106_gcm_ctx_get(tfm); + void *aes_ctx = &(ctx->aes_key_expanded); + unsigned long auth_tag_len = crypto_aead_authsize(tfm); + u8 iv_and_authTag[32+AESNI_ALIGN]; + u8 *iv = (u8 *) PTR_ALIGN((u8 *)iv_and_authTag, AESNI_ALIGN); + u8 *authTag = iv + 16; + struct scatter_walk src_sg_walk; + struct scatter_walk assoc_sg_walk; + struct scatter_walk dst_sg_walk; + unsigned int i; + + if (unlikely((req->cryptlen < auth_tag_len) || + (req->assoclen != 8 && req->assoclen != 12))) + return -EINVAL; + /* Assuming we are supporting rfc4106 64-bit extended */ + /* sequence numbers We need to have the AAD length */ + /* equal to 8 or 12 bytes */ + + tempCipherLen = (unsigned long)(req->cryptlen - auth_tag_len); + /* IV below built */ + for (i = 0; i < 4; i++) + *(iv+i) = ctx->nonce[i]; + for (i = 0; i < 8; i++) + *(iv+4+i) = req->iv[i]; + *((__be32 *)(iv+12)) = counter; + + if ((sg_is_last(req->src)) && (sg_is_last(req->assoc))) { + one_entry_in_sg = 1; + scatterwalk_start(&src_sg_walk, req->src); + scatterwalk_start(&assoc_sg_walk, req->assoc); + src = scatterwalk_map(&src_sg_walk); + assoc = scatterwalk_map(&assoc_sg_walk); + dst = src; + if (unlikely(req->src != req->dst)) { + scatterwalk_start(&dst_sg_walk, req->dst); + dst = scatterwalk_map(&dst_sg_walk); + } + + } else { + /* Allocate memory for src, dst, assoc */ + src = kmalloc(req->cryptlen + req->assoclen, GFP_ATOMIC); + if (!src) + return -ENOMEM; + assoc = (src + req->cryptlen + auth_tag_len); + scatterwalk_map_and_copy(src, req->src, 0, req->cryptlen, 0); + scatterwalk_map_and_copy(assoc, req->assoc, 0, + req->assoclen, 0); + dst = src; + } + + aesni_gcm_dec_tfm(aes_ctx, dst, src, tempCipherLen, iv, + ctx->hash_subkey, assoc, (unsigned long)req->assoclen, + authTag, auth_tag_len); + + /* Compare generated tag with passed in tag. */ + retval = crypto_memneq(src + tempCipherLen, authTag, auth_tag_len) ? + -EBADMSG : 0; + + if (one_entry_in_sg) { + if (unlikely(req->src != req->dst)) { + scatterwalk_unmap(dst); + scatterwalk_done(&dst_sg_walk, 0, 0); + } + scatterwalk_unmap(src); + scatterwalk_unmap(assoc); + scatterwalk_done(&src_sg_walk, 0, 0); + scatterwalk_done(&assoc_sg_walk, 0, 0); + } else { + scatterwalk_map_and_copy(dst, req->dst, 0, req->cryptlen, 1); + kfree(src); + } + return retval; +} +",0,"static int __driver_rfc4106_decrypt(struct aead_request *req) +{ + u8 one_entry_in_sg = 0; + u8 *src, *dst, *assoc; + unsigned long tempCipherLen = 0; + __be32 counter = cpu_to_be32(1); + int retval = 0; + struct crypto_aead *tfm = crypto_aead_reqtfm(req); + struct aesni_rfc4106_gcm_ctx *ctx = aesni_rfc4106_gcm_ctx_get(tfm); + void *aes_ctx = &(ctx->aes_key_expanded); + unsigned long auth_tag_len = crypto_aead_authsize(tfm); + u8 iv_and_authTag[32+AESNI_ALIGN]; + u8 *iv = (u8 *) PTR_ALIGN((u8 *)iv_and_authTag, AESNI_ALIGN); + u8 *authTag = iv + 16; + struct scatter_walk src_sg_walk; + struct scatter_walk assoc_sg_walk; + struct scatter_walk dst_sg_walk; + unsigned int i; + + if (unlikely((req->cryptlen < auth_tag_len) || + (req->assoclen != 8 && req->assoclen != 12))) + return -EINVAL; + /* Assuming we are supporting rfc4106 64-bit extended */ + /* sequence numbers We need to have the AAD length */ + /* equal to 8 or 12 bytes */ + + tempCipherLen = (unsigned long)(req->cryptlen - auth_tag_len); + /* IV below built */ + for (i = 0; i < 4; i++) + *(iv+i) = ctx->nonce[i]; + for (i = 0; i < 8; i++) + *(iv+4+i) = req->iv[i]; + *((__be32 *)(iv+12)) = counter; + + if ((sg_is_last(req->src)) && (sg_is_last(req->assoc))) { + one_entry_in_sg = 1; + scatterwalk_start(&src_sg_walk, req->src); + scatterwalk_start(&assoc_sg_walk, req->assoc); + src = scatterwalk_map(&src_sg_walk); + assoc = scatterwalk_map(&assoc_sg_walk); + dst = src; + if (unlikely(req->src != req->dst)) { + scatterwalk_start(&dst_sg_walk, req->dst); + dst = scatterwalk_map(&dst_sg_walk); + } + + } else { + /* Allocate memory for src, dst, assoc */ + src = kmalloc(req->cryptlen + req->assoclen, GFP_ATOMIC); + if (!src) + return -ENOMEM; + assoc = (src + req->cryptlen + auth_tag_len); + scatterwalk_map_and_copy(src, req->src, 0, req->cryptlen, 0); + scatterwalk_map_and_copy(assoc, req->assoc, 0, + req->assoclen, 0); + dst = src; + } + + aesni_gcm_dec_tfm(aes_ctx, dst, src, tempCipherLen, iv, + ctx->hash_subkey, assoc, (unsigned long)req->assoclen, + authTag, auth_tag_len); + + /* Compare generated tag with passed in tag. */ + retval = crypto_memneq(src + tempCipherLen, authTag, auth_tag_len) ? + -EBADMSG : 0; + + if (one_entry_in_sg) { + if (unlikely(req->src != req->dst)) { + scatterwalk_unmap(dst); + scatterwalk_done(&dst_sg_walk, 0, 0); + } + scatterwalk_unmap(src); + scatterwalk_unmap(assoc); + scatterwalk_done(&src_sg_walk, 0, 0); + scatterwalk_done(&assoc_sg_walk, 0, 0); + } else { + scatterwalk_map_and_copy(dst, req->dst, 0, req->cryptlen, 1); + kfree(src); + } + return retval; +} +","@@ -1546,4 +1546,4 @@ module_exit(aesni_exit); + + MODULE_DESCRIPTION(""Rijndael (AES) Cipher Algorithm, Intel AES-NI instructions optimized""); + MODULE_LICENSE(""GPL""); +-MODULE_ALIAS(""aes""); ++MODULE_ALIAS_CRYPTO(""aes"");",859,1190,2048 +18060,"static int mpage_da_map_blocks(struct mpage_da_data *mpd) +{ + int err, blks, get_blocks_flags; + struct buffer_head new; + sector_t next = mpd->b_blocknr; + unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits; + loff_t disksize = EXT4_I(mpd->inode)->i_disksize; + handle_t *handle = NULL; + + /* + * We consider only non-mapped and non-allocated blocks + */ + if ((mpd->b_state & (1 << BH_Mapped)) && + !(mpd->b_state & (1 << BH_Delay)) && + !(mpd->b_state & (1 << BH_Unwritten))) + return 0; + + /* + * If we didn't accumulate anything to write simply return + */ + if (!mpd->b_size) + return 0; + + handle = ext4_journal_current_handle(); + BUG_ON(!handle); + + /* + * Call ext4_get_blocks() to allocate any delayed allocation + * blocks, or to convert an uninitialized extent to be + * initialized (in the case where we have written into + * one or more preallocated blocks). + * + * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to + * indicate that we are on the delayed allocation path. This + * affects functions in many different parts of the allocation + * call path. This flag exists primarily because we don't + * want to change *many* call functions, so ext4_get_blocks() + * will set the magic i_delalloc_reserved_flag once the + * inode's allocation semaphore is taken. + * + * If the blocks in questions were delalloc blocks, set + * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting + * variables are updated after the blocks have been allocated. + */ + new.b_state = 0; + get_blocks_flags = EXT4_GET_BLOCKS_CREATE; + if (mpd->b_state & (1 << BH_Delay)) + get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE; + + blks = ext4_get_blocks(handle, mpd->inode, next, max_blocks, + &new, get_blocks_flags); + if (blks < 0) { + err = blks; + /* + * If get block returns with error we simply + * return. Later writepage will redirty the page and + * writepages will find the dirty page again + */ + if (err == -EAGAIN) + return 0; + + if (err == -ENOSPC && + ext4_count_free_blocks(mpd->inode->i_sb)) { + mpd->retval = err; + return 0; + } + + /* + * get block failure will cause us to loop in + * writepages, because a_ops->writepage won't be able + * to make progress. The page will be redirtied by + * writepage and writepages will again try to write + * the same. + */ + ext4_msg(mpd->inode->i_sb, KERN_CRIT, + ""delayed block allocation failed for inode %lu at "" + ""logical offset %llu with max blocks %zd with "" + ""error %d\n"", mpd->inode->i_ino, + (unsigned long long) next, + mpd->b_size >> mpd->inode->i_blkbits, err); + printk(KERN_CRIT ""This should not happen!! "" + ""Data will be lost\n""); + if (err == -ENOSPC) { + ext4_print_free_blocks(mpd->inode); + } + /* invalidate all the pages */ + ext4_da_block_invalidatepages(mpd, next, + mpd->b_size >> mpd->inode->i_blkbits); + return err; + } + BUG_ON(blks == 0); + + new.b_size = (blks << mpd->inode->i_blkbits); + + if (buffer_new(&new)) + __unmap_underlying_blocks(mpd->inode, &new); + + /* + * If blocks are delayed marked, we need to + * put actual blocknr and drop delayed bit + */ + if ((mpd->b_state & (1 << BH_Delay)) || + (mpd->b_state & (1 << BH_Unwritten))) + mpage_put_bnr_to_bhs(mpd, next, &new); + + if (ext4_should_order_data(mpd->inode)) { + err = ext4_jbd2_file_inode(handle, mpd->inode); + if (err) + return err; + } + + /* + * Update on-disk size along with block allocation. + */ + disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits; + if (disksize > i_size_read(mpd->inode)) + disksize = i_size_read(mpd->inode); + if (disksize > EXT4_I(mpd->inode)->i_disksize) { + ext4_update_i_disksize(mpd->inode, disksize); + return ext4_mark_inode_dirty(handle, mpd->inode); + } + + return 0; +} +",1,"static int mpage_da_map_blocks(struct mpage_da_data *mpd) +{ + int err, blks, get_blocks_flags; + struct buffer_head new; + sector_t next = mpd->b_blocknr; + unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits; + loff_t disksize = EXT4_I(mpd->inode)->i_disksize; + handle_t *handle = NULL; + + /* + * We consider only non-mapped and non-allocated blocks + */ + if ((mpd->b_state & (1 << BH_Mapped)) && + !(mpd->b_state & (1 << BH_Delay)) && + !(mpd->b_state & (1 << BH_Unwritten))) + return 0; + + /* + * If we didn't accumulate anything to write simply return + */ + if (!mpd->b_size) + return 0; + + handle = ext4_journal_current_handle(); + BUG_ON(!handle); + + /* + * Call ext4_get_blocks() to allocate any delayed allocation + * blocks, or to convert an uninitialized extent to be + * initialized (in the case where we have written into + * one or more preallocated blocks). + * + * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to + * indicate that we are on the delayed allocation path. This + * affects functions in many different parts of the allocation + * call path. This flag exists primarily because we don't + * want to change *many* call functions, so ext4_get_blocks() + * will set the magic i_delalloc_reserved_flag once the + * inode's allocation semaphore is taken. + * + * If the blocks in questions were delalloc blocks, set + * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting + * variables are updated after the blocks have been allocated. + */ + new.b_state = 0; + get_blocks_flags = EXT4_GET_BLOCKS_CREATE; + if (ext4_should_dioread_nolock(mpd->inode)) + get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT; + if (mpd->b_state & (1 << BH_Delay)) + get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE; + + blks = ext4_get_blocks(handle, mpd->inode, next, max_blocks, + &new, get_blocks_flags); + if (blks < 0) { + err = blks; + /* + * If get block returns with error we simply + * return. Later writepage will redirty the page and + * writepages will find the dirty page again + */ + if (err == -EAGAIN) + return 0; + + if (err == -ENOSPC && + ext4_count_free_blocks(mpd->inode->i_sb)) { + mpd->retval = err; + return 0; + } + + /* + * get block failure will cause us to loop in + * writepages, because a_ops->writepage won't be able + * to make progress. The page will be redirtied by + * writepage and writepages will again try to write + * the same. + */ + ext4_msg(mpd->inode->i_sb, KERN_CRIT, + ""delayed block allocation failed for inode %lu at "" + ""logical offset %llu with max blocks %zd with "" + ""error %d\n"", mpd->inode->i_ino, + (unsigned long long) next, + mpd->b_size >> mpd->inode->i_blkbits, err); + printk(KERN_CRIT ""This should not happen!! "" + ""Data will be lost\n""); + if (err == -ENOSPC) { + ext4_print_free_blocks(mpd->inode); + } + /* invalidate all the pages */ + ext4_da_block_invalidatepages(mpd, next, + mpd->b_size >> mpd->inode->i_blkbits); + return err; + } + BUG_ON(blks == 0); + + new.b_size = (blks << mpd->inode->i_blkbits); + + if (buffer_new(&new)) + __unmap_underlying_blocks(mpd->inode, &new); + + /* + * If blocks are delayed marked, we need to + * put actual blocknr and drop delayed bit + */ + if ((mpd->b_state & (1 << BH_Delay)) || + (mpd->b_state & (1 << BH_Unwritten))) + mpage_put_bnr_to_bhs(mpd, next, &new); + + if (ext4_should_order_data(mpd->inode)) { + err = ext4_jbd2_file_inode(handle, mpd->inode); + if (err) + return err; + } + + /* + * Update on-disk size along with block allocation. + */ + disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits; + if (disksize > i_size_read(mpd->inode)) + disksize = i_size_read(mpd->inode); + if (disksize > EXT4_I(mpd->inode)->i_disksize) { + ext4_update_i_disksize(mpd->inode, disksize); + return ext4_mark_inode_dirty(handle, mpd->inode); + } + + return 0; +} +","@@ -38,6 +38,7 @@ + #include + #include + #include ++#include + + #include ""ext4_jbd2.h"" + #include ""xattr.h"" +@@ -1534,6 +1535,8 @@ static void ext4_truncate_failed_write(struct inode *inode) + ext4_truncate(inode); + } + ++static int ext4_get_block_write(struct inode *inode, sector_t iblock, ++ struct buffer_head *bh_result, int create); + static int ext4_write_begin(struct file *file, struct address_space *mapping, + loff_t pos, unsigned len, unsigned flags, + struct page **pagep, void **fsdata) +@@ -1575,8 +1578,12 @@ static int ext4_write_begin(struct file *file, struct address_space *mapping, + } + *pagep = page; + +- ret = block_write_begin(file, mapping, pos, len, flags, pagep, fsdata, +- ext4_get_block); ++ if (ext4_should_dioread_nolock(inode)) ++ ret = block_write_begin(file, mapping, pos, len, flags, pagep, ++ fsdata, ext4_get_block_write); ++ else ++ ret = block_write_begin(file, mapping, pos, len, flags, pagep, ++ fsdata, ext4_get_block); + + if (!ret && ext4_should_journal_data(inode)) { + ret = walk_page_buffers(handle, page_buffers(page), +@@ -2092,6 +2099,8 @@ static void mpage_put_bnr_to_bhs(struct mpage_da_data *mpd, sector_t logical, + } else if (buffer_mapped(bh)) + BUG_ON(bh->b_blocknr != pblock); + ++ if (buffer_uninit(exbh)) ++ set_buffer_uninit(bh); + cur_logical++; + pblock++; + } while ((bh = bh->b_this_page) != head); +@@ -2221,6 +2230,8 @@ static int mpage_da_map_blocks(struct mpage_da_data *mpd) + */ + new.b_state = 0; + get_blocks_flags = EXT4_GET_BLOCKS_CREATE; ++ if (ext4_should_dioread_nolock(mpd->inode)) ++ get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT; + if (mpd->b_state & (1 << BH_Delay)) + get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE; + +@@ -2636,6 +2647,9 @@ static int __ext4_journalled_writepage(struct page *page, + return ret; + } + ++static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode); ++static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate); ++ + /* + * Note that we don't need to start a transaction unless we're journaling data + * because we should have holes filled from ext4_page_mkwrite(). We even don't +@@ -2683,7 +2697,7 @@ static int ext4_writepage(struct page *page, + int ret = 0; + loff_t size; + unsigned int len; +- struct buffer_head *page_bufs; ++ struct buffer_head *page_bufs = NULL; + struct inode *inode = page->mapping->host; + + trace_ext4_writepage(inode, page); +@@ -2759,7 +2773,11 @@ static int ext4_writepage(struct page *page, + + if (test_opt(inode->i_sb, NOBH) && ext4_should_writeback_data(inode)) + ret = nobh_writepage(page, noalloc_get_block_write, wbc); +- else ++ else if (page_bufs && buffer_uninit(page_bufs)) { ++ ext4_set_bh_endio(page_bufs, inode); ++ ret = block_write_full_page_endio(page, noalloc_get_block_write, ++ wbc, ext4_end_io_buffer_write); ++ } else + ret = block_write_full_page(page, noalloc_get_block_write, + wbc); + +@@ -3347,10 +3365,44 @@ ext4_readpages(struct file *file, struct address_space *mapping, + return mpage_readpages(mapping, pages, nr_pages, ext4_get_block); + } + ++static void ext4_free_io_end(ext4_io_end_t *io) ++{ ++ BUG_ON(!io); ++ if (io->page) ++ put_page(io->page); ++ iput(io->inode); ++ kfree(io); ++} ++ ++static void ext4_invalidatepage_free_endio(struct page *page, unsigned long offset) ++{ ++ struct buffer_head *head, *bh; ++ unsigned int curr_off = 0; ++ ++ if (!page_has_buffers(page)) ++ return; ++ head = bh = page_buffers(page); ++ do { ++ if (offset <= curr_off && test_clear_buffer_uninit(bh) ++ && bh->b_private) { ++ ext4_free_io_end(bh->b_private); ++ bh->b_private = NULL; ++ bh->b_end_io = NULL; ++ } ++ curr_off = curr_off + bh->b_size; ++ bh = bh->b_this_page; ++ } while (bh != head); ++} ++ + static void ext4_invalidatepage(struct page *page, unsigned long offset) + { + journal_t *journal = EXT4_JOURNAL(page->mapping->host); + ++ /* ++ * free any io_end structure allocated for buffers to be discarded ++ */ ++ if (ext4_should_dioread_nolock(page->mapping->host)) ++ ext4_invalidatepage_free_endio(page, offset); + /* + * If it's a full truncate we just forget about the pending dirtying + */ +@@ -3471,10 +3523,11 @@ static ssize_t ext4_ind_direct_IO(int rw, struct kiocb *iocb, + static int ext4_get_block_write(struct inode *inode, sector_t iblock, + struct buffer_head *bh_result, int create) + { +- handle_t *handle = NULL; ++ handle_t *handle = ext4_journal_current_handle(); + int ret = 0; + unsigned max_blocks = bh_result->b_size >> inode->i_blkbits; + int dio_credits; ++ int started = 0; + + ext4_debug(""ext4_get_block_write: inode %lu, create flag %d\n"", + inode->i_ino, create); +@@ -3485,44 +3538,44 @@ static int ext4_get_block_write(struct inode *inode, sector_t iblock, + */ + create = EXT4_GET_BLOCKS_IO_CREATE_EXT; + +- if (max_blocks > DIO_MAX_BLOCKS) +- max_blocks = DIO_MAX_BLOCKS; +- dio_credits = ext4_chunk_trans_blocks(inode, max_blocks); +- handle = ext4_journal_start(inode, dio_credits); +- if (IS_ERR(handle)) { +- ret = PTR_ERR(handle); +- goto out; ++ if (!handle) { ++ if (max_blocks > DIO_MAX_BLOCKS) ++ max_blocks = DIO_MAX_BLOCKS; ++ dio_credits = ext4_chunk_trans_blocks(inode, max_blocks); ++ handle = ext4_journal_start(inode, dio_credits); ++ if (IS_ERR(handle)) { ++ ret = PTR_ERR(handle); ++ goto out; ++ } ++ started = 1; + } ++ + ret = ext4_get_blocks(handle, inode, iblock, max_blocks, bh_result, + create); + if (ret > 0) { + bh_result->b_size = (ret << inode->i_blkbits); + ret = 0; + } +- ext4_journal_stop(handle); ++ if (started) ++ ext4_journal_stop(handle); + out: + return ret; + } + +-static void ext4_free_io_end(ext4_io_end_t *io) +-{ +- BUG_ON(!io); +- iput(io->inode); +- kfree(io); +-} +- + static void dump_completed_IO(struct inode * inode) + { + #ifdef EXT4_DEBUG + struct list_head *cur, *before, *after; + ext4_io_end_t *io, *io0, *io1; ++ unsigned long flags; + + if (list_empty(&EXT4_I(inode)->i_completed_io_list)){ + ext4_debug(""inode %lu completed_io list is empty\n"", inode->i_ino); + return; + } + + ext4_debug(""Dump inode %lu completed_io list \n"", inode->i_ino); ++ spin_lock_irqsave(&EXT4_I(inode)->i_completed_io_lock, flags); + list_for_each_entry(io, &EXT4_I(inode)->i_completed_io_list, list){ + cur = &io->list; + before = cur->prev; +@@ -3533,6 +3586,7 @@ static void dump_completed_IO(struct inode * inode) + ext4_debug(""io 0x%p from inode %lu,prev 0x%p,next 0x%p\n"", + io, inode->i_ino, io0, io1); + } ++ spin_unlock_irqrestore(&EXT4_I(inode)->i_completed_io_lock, flags); + #endif + } + +@@ -3556,9 +3610,7 @@ static int ext4_end_io_nolock(ext4_io_end_t *io) + if (io->flag != EXT4_IO_UNWRITTEN) + return ret; + +- if (offset + size <= i_size_read(inode)) +- ret = ext4_convert_unwritten_extents(inode, offset, size); +- ++ ret = ext4_convert_unwritten_extents(inode, offset, size); + if (ret < 0) { + printk(KERN_EMERG ""%s: failed to convert unwritten"" + ""extents to written extents, error is %d"" +@@ -3577,18 +3629,25 @@ static int ext4_end_io_nolock(ext4_io_end_t *io) + */ + static void ext4_end_io_work(struct work_struct *work) + { +- ext4_io_end_t *io = container_of(work, ext4_io_end_t, work); +- struct inode *inode = io->inode; +- int ret = 0; ++ ext4_io_end_t *io = container_of(work, ext4_io_end_t, work); ++ struct inode *inode = io->inode; ++ struct ext4_inode_info *ei = EXT4_I(inode); ++ unsigned long flags; ++ int ret; + + mutex_lock(&inode->i_mutex); + ret = ext4_end_io_nolock(io); +- if (ret >= 0) { +- if (!list_empty(&io->list)) +- list_del_init(&io->list); +- ext4_free_io_end(io); ++ if (ret < 0) { ++ mutex_unlock(&inode->i_mutex); ++ return; + } ++ ++ spin_lock_irqsave(&ei->i_completed_io_lock, flags); ++ if (!list_empty(&io->list)) ++ list_del_init(&io->list); ++ spin_unlock_irqrestore(&ei->i_completed_io_lock, flags); + mutex_unlock(&inode->i_mutex); ++ ext4_free_io_end(io); + } + + /* +@@ -3607,15 +3666,18 @@ static void ext4_end_io_work(struct work_struct *work) + int flush_completed_IO(struct inode *inode) + { + ext4_io_end_t *io; ++ struct ext4_inode_info *ei = EXT4_I(inode); ++ unsigned long flags; + int ret = 0; + int ret2 = 0; + +- if (list_empty(&EXT4_I(inode)->i_completed_io_list)) ++ if (list_empty(&ei->i_completed_io_list)) + return ret; + + dump_completed_IO(inode); +- while (!list_empty(&EXT4_I(inode)->i_completed_io_list)){ +- io = list_entry(EXT4_I(inode)->i_completed_io_list.next, ++ spin_lock_irqsave(&ei->i_completed_io_lock, flags); ++ while (!list_empty(&ei->i_completed_io_list)){ ++ io = list_entry(ei->i_completed_io_list.next, + ext4_io_end_t, list); + /* + * Calling ext4_end_io_nolock() to convert completed +@@ -3631,28 +3693,31 @@ int flush_completed_IO(struct inode *inode) + * avoid double converting from both fsync and background work + * queue work. + */ ++ spin_unlock_irqrestore(&ei->i_completed_io_lock, flags); + ret = ext4_end_io_nolock(io); ++ spin_lock_irqsave(&ei->i_completed_io_lock, flags); + if (ret < 0) + ret2 = ret; + else + list_del_init(&io->list); + } ++ spin_unlock_irqrestore(&ei->i_completed_io_lock, flags); + return (ret2 < 0) ? ret2 : 0; + } + +-static ext4_io_end_t *ext4_init_io_end (struct inode *inode) ++static ext4_io_end_t *ext4_init_io_end (struct inode *inode, gfp_t flags) + { + ext4_io_end_t *io = NULL; + +- io = kmalloc(sizeof(*io), GFP_NOFS); ++ io = kmalloc(sizeof(*io), flags); + + if (io) { + igrab(inode); + io->inode = inode; + io->flag = 0; + io->offset = 0; + io->size = 0; +- io->error = 0; ++ io->page = NULL; + INIT_WORK(&io->work, ext4_end_io_work); + INIT_LIST_HEAD(&io->list); + } +@@ -3665,6 +3730,8 @@ static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset, + { + ext4_io_end_t *io_end = iocb->private; + struct workqueue_struct *wq; ++ unsigned long flags; ++ struct ext4_inode_info *ei; + + /* if not async direct IO or dio with 0 bytes write, just return */ + if (!io_end || !size) +@@ -3684,17 +3751,85 @@ static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset, + + io_end->offset = offset; + io_end->size = size; ++ io_end->flag = EXT4_IO_UNWRITTEN; + wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq; + + /* queue the work to convert unwritten extents to written */ + queue_work(wq, &io_end->work); + + /* Add the io_end to per-inode completed aio dio list*/ +- list_add_tail(&io_end->list, +- &EXT4_I(io_end->inode)->i_completed_io_list); ++ ei = EXT4_I(io_end->inode); ++ spin_lock_irqsave(&ei->i_completed_io_lock, flags); ++ list_add_tail(&io_end->list, &ei->i_completed_io_list); ++ spin_unlock_irqrestore(&ei->i_completed_io_lock, flags); + iocb->private = NULL; + } + ++static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate) ++{ ++ ext4_io_end_t *io_end = bh->b_private; ++ struct workqueue_struct *wq; ++ struct inode *inode; ++ unsigned long flags; ++ ++ if (!test_clear_buffer_uninit(bh) || !io_end) ++ goto out; ++ ++ if (!(io_end->inode->i_sb->s_flags & MS_ACTIVE)) { ++ printk(""sb umounted, discard end_io request for inode %lu\n"", ++ io_end->inode->i_ino); ++ ext4_free_io_end(io_end); ++ goto out; ++ } ++ ++ io_end->flag = EXT4_IO_UNWRITTEN; ++ inode = io_end->inode; ++ ++ /* Add the io_end to per-inode completed io list*/ ++ spin_lock_irqsave(&EXT4_I(inode)->i_completed_io_lock, flags); ++ list_add_tail(&io_end->list, &EXT4_I(inode)->i_completed_io_list); ++ spin_unlock_irqrestore(&EXT4_I(inode)->i_completed_io_lock, flags); ++ ++ wq = EXT4_SB(inode->i_sb)->dio_unwritten_wq; ++ /* queue the work to convert unwritten extents to written */ ++ queue_work(wq, &io_end->work); ++out: ++ bh->b_private = NULL; ++ bh->b_end_io = NULL; ++ clear_buffer_uninit(bh); ++ end_buffer_async_write(bh, uptodate); ++} ++ ++static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode) ++{ ++ ext4_io_end_t *io_end; ++ struct page *page = bh->b_page; ++ loff_t offset = (sector_t)page->index << PAGE_CACHE_SHIFT; ++ size_t size = bh->b_size; ++ ++retry: ++ io_end = ext4_init_io_end(inode, GFP_ATOMIC); ++ if (!io_end) { ++ if (printk_ratelimit()) ++ printk(KERN_WARNING ""%s: allocation fail\n"", __func__); ++ schedule(); ++ goto retry; ++ } ++ io_end->offset = offset; ++ io_end->size = size; ++ /* ++ * We need to hold a reference to the page to make sure it ++ * doesn't get evicted before ext4_end_io_work() has a chance ++ * to convert the extent from written to unwritten. ++ */ ++ io_end->page = page; ++ get_page(io_end->page); ++ ++ bh->b_private = io_end; ++ bh->b_end_io = ext4_end_io_buffer_write; ++ return 0; ++} ++ + /* + * For ext4 extent files, ext4 will do direct-io write to holes, + * preallocated extents, and those write extend the file, no need to +@@ -3748,7 +3883,7 @@ static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb, + iocb->private = NULL; + EXT4_I(inode)->cur_aio_dio = NULL; + if (!is_sync_kiocb(iocb)) { +- iocb->private = ext4_init_io_end(inode); ++ iocb->private = ext4_init_io_end(inode, GFP_NOFS); + if (!iocb->private) + return -ENOMEM; + /*",1113,1444,2048 +18734,"void SoftMP3::onQueueFilled(OMX_U32 /* portIndex */) { + if (mSignalledError || mOutputPortSettingsChange != NONE) { + return; + } + + List &inQueue = getPortQueue(0); + List &outQueue = getPortQueue(1); + + while ((!inQueue.empty() || (mSawInputEos && !mSignalledOutputEos)) && !outQueue.empty()) { + BufferInfo *inInfo = NULL; + OMX_BUFFERHEADERTYPE *inHeader = NULL; + if (!inQueue.empty()) { + inInfo = *inQueue.begin(); + inHeader = inInfo->mHeader; + } + + BufferInfo *outInfo = *outQueue.begin(); + OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; + outHeader->nFlags = 0; + + if (inHeader) { + if (inHeader->nOffset == 0 && inHeader->nFilledLen) { + mAnchorTimeUs = inHeader->nTimeStamp; + mNumFramesOutput = 0; + } + + if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { + mSawInputEos = true; + } + + mConfig->pInputBuffer = + inHeader->pBuffer + inHeader->nOffset; + + mConfig->inputBufferCurrentLength = inHeader->nFilledLen; + } else { + mConfig->pInputBuffer = NULL; + mConfig->inputBufferCurrentLength = 0; + } + mConfig->inputBufferMaxLength = 0; + mConfig->inputBufferUsedLength = 0; + + mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t); + if ((int32)outHeader->nAllocLen < mConfig->outputFrameSize) { + ALOGE(""input buffer too small: got %u, expected %u"", + outHeader->nAllocLen, mConfig->outputFrameSize); + android_errorWriteLog(0x534e4554, ""27793371""); + notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL); + mSignalledError = true; + return; + } + + mConfig->pOutputBuffer = + reinterpret_cast(outHeader->pBuffer); + + ERROR_CODE decoderErr; + if ((decoderErr = pvmp3_framedecoder(mConfig, mDecoderBuf)) + != NO_DECODING_ERROR) { + ALOGV(""mp3 decoder returned error %d"", decoderErr); + + if (decoderErr != NO_ENOUGH_MAIN_DATA_ERROR + && decoderErr != SIDE_INFO_ERROR) { + ALOGE(""mp3 decoder returned error %d"", decoderErr); + + notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL); + mSignalledError = true; + return; + } + + if (mConfig->outputFrameSize == 0) { + mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t); + } + + if (decoderErr == NO_ENOUGH_MAIN_DATA_ERROR && mSawInputEos) { + if (!mIsFirst) { + + outHeader->nOffset = 0; + outHeader->nFilledLen = kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t); + + memset(outHeader->pBuffer, 0, outHeader->nFilledLen); + } + outHeader->nFlags = OMX_BUFFERFLAG_EOS; + mSignalledOutputEos = true; + } else { + + + ALOGV_IF(mIsFirst, ""insufficient data for first frame, sending silence""); + memset(outHeader->pBuffer, + 0, + mConfig->outputFrameSize * sizeof(int16_t)); + + if (inHeader) { + mConfig->inputBufferUsedLength = inHeader->nFilledLen; + } + } + } else if (mConfig->samplingRate != mSamplingRate + || mConfig->num_channels != mNumChannels) { + mSamplingRate = mConfig->samplingRate; + mNumChannels = mConfig->num_channels; + + notify(OMX_EventPortSettingsChanged, 1, 0, NULL); + mOutputPortSettingsChange = AWAITING_DISABLED; + return; + } + + if (mIsFirst) { + mIsFirst = false; + outHeader->nOffset = + kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t); + + outHeader->nFilledLen = + mConfig->outputFrameSize * sizeof(int16_t) - outHeader->nOffset; + } else if (!mSignalledOutputEos) { + outHeader->nOffset = 0; + outHeader->nFilledLen = mConfig->outputFrameSize * sizeof(int16_t); + } + + outHeader->nTimeStamp = + mAnchorTimeUs + (mNumFramesOutput * 1000000ll) / mSamplingRate; + + if (inHeader) { + CHECK_GE(inHeader->nFilledLen, mConfig->inputBufferUsedLength); + + inHeader->nOffset += mConfig->inputBufferUsedLength; + inHeader->nFilledLen -= mConfig->inputBufferUsedLength; + + + if (inHeader->nFilledLen == 0) { + inInfo->mOwnedByUs = false; + inQueue.erase(inQueue.begin()); + inInfo = NULL; + notifyEmptyBufferDone(inHeader); + inHeader = NULL; + } + } + + mNumFramesOutput += mConfig->outputFrameSize / mNumChannels; + + outInfo->mOwnedByUs = false; + outQueue.erase(outQueue.begin()); + outInfo = NULL; + notifyFillBufferDone(outHeader); + outHeader = NULL; + } +} +",1,"void SoftMP3::onQueueFilled(OMX_U32 /* portIndex */) { + if (mSignalledError || mOutputPortSettingsChange != NONE) { + return; + } + + List &inQueue = getPortQueue(0); + List &outQueue = getPortQueue(1); + + while ((!inQueue.empty() || (mSawInputEos && !mSignalledOutputEos)) && !outQueue.empty()) { + BufferInfo *inInfo = NULL; + OMX_BUFFERHEADERTYPE *inHeader = NULL; + if (!inQueue.empty()) { + inInfo = *inQueue.begin(); + inHeader = inInfo->mHeader; + } + + BufferInfo *outInfo = *outQueue.begin(); + OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; + outHeader->nFlags = 0; + + if (inHeader) { + if (inHeader->nOffset == 0 && inHeader->nFilledLen) { + mAnchorTimeUs = inHeader->nTimeStamp; + mNumFramesOutput = 0; + } + + if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { + mSawInputEos = true; + } + + mConfig->pInputBuffer = + inHeader->pBuffer + inHeader->nOffset; + + mConfig->inputBufferCurrentLength = inHeader->nFilledLen; + } else { + mConfig->pInputBuffer = NULL; + mConfig->inputBufferCurrentLength = 0; + } + mConfig->inputBufferMaxLength = 0; + mConfig->inputBufferUsedLength = 0; + + mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t); + if ((int32)outHeader->nAllocLen < mConfig->outputFrameSize) { + ALOGE(""input buffer too small: got %u, expected %u"", + outHeader->nAllocLen, mConfig->outputFrameSize); + android_errorWriteLog(0x534e4554, ""27793371""); + notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL); + mSignalledError = true; + return; + } + + mConfig->pOutputBuffer = + reinterpret_cast(outHeader->pBuffer); + + ERROR_CODE decoderErr; + if ((decoderErr = pvmp3_framedecoder(mConfig, mDecoderBuf)) + != NO_DECODING_ERROR) { + ALOGV(""mp3 decoder returned error %d"", decoderErr); + + if (decoderErr != NO_ENOUGH_MAIN_DATA_ERROR + && decoderErr != SIDE_INFO_ERROR) { + ALOGE(""mp3 decoder returned error %d"", decoderErr); + + notify(OMX_EventError, OMX_ErrorUndefined, decoderErr, NULL); + mSignalledError = true; + return; + } + + if (mConfig->outputFrameSize == 0) { + mConfig->outputFrameSize = kOutputBufferSize / sizeof(int16_t); + } + + if (decoderErr == NO_ENOUGH_MAIN_DATA_ERROR && mSawInputEos) { + if (!mIsFirst) { + + outHeader->nOffset = 0; + outHeader->nFilledLen = kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t); + + if (!memsetSafe(outHeader, 0, outHeader->nFilledLen)) { + return; + } + + } + outHeader->nFlags = OMX_BUFFERFLAG_EOS; + mSignalledOutputEos = true; + } else { + + + ALOGV_IF(mIsFirst, ""insufficient data for first frame, sending silence""); + if (!memsetSafe(outHeader, 0, mConfig->outputFrameSize * sizeof(int16_t))) { + return; + } + + if (inHeader) { + mConfig->inputBufferUsedLength = inHeader->nFilledLen; + } + } + } else if (mConfig->samplingRate != mSamplingRate + || mConfig->num_channels != mNumChannels) { + mSamplingRate = mConfig->samplingRate; + mNumChannels = mConfig->num_channels; + + notify(OMX_EventPortSettingsChanged, 1, 0, NULL); + mOutputPortSettingsChange = AWAITING_DISABLED; + return; + } + + if (mIsFirst) { + mIsFirst = false; + outHeader->nOffset = + kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t); + + outHeader->nFilledLen = + mConfig->outputFrameSize * sizeof(int16_t) - outHeader->nOffset; + } else if (!mSignalledOutputEos) { + outHeader->nOffset = 0; + outHeader->nFilledLen = mConfig->outputFrameSize * sizeof(int16_t); + } + + outHeader->nTimeStamp = + mAnchorTimeUs + (mNumFramesOutput * 1000000ll) / mSamplingRate; + + if (inHeader) { + CHECK_GE(inHeader->nFilledLen, mConfig->inputBufferUsedLength); + + inHeader->nOffset += mConfig->inputBufferUsedLength; + inHeader->nFilledLen -= mConfig->inputBufferUsedLength; + + + if (inHeader->nFilledLen == 0) { + inInfo->mOwnedByUs = false; + inQueue.erase(inQueue.begin()); + inInfo = NULL; + notifyEmptyBufferDone(inHeader); + inHeader = NULL; + } + } + + mNumFramesOutput += mConfig->outputFrameSize / mNumChannels; + + outInfo->mOwnedByUs = false; + outQueue.erase(outQueue.begin()); + outInfo = NULL; + notifyFillBufferDone(outHeader); + outHeader = NULL; + } +} +","@@ -120,6 +120,17 @@ + + mIsFirst = true; + } + ++void *SoftMP3::memsetSafe(OMX_BUFFERHEADERTYPE *outHeader, int c, size_t len) { ++ if (len > outHeader->nAllocLen) { ++ ALOGE(""memset buffer too small: got %lu, expected %zu"", outHeader->nAllocLen, len); ++ android_errorWriteLog(0x534e4554, ""29422022""); ++ notify(OMX_EventError, OMX_ErrorUndefined, OUTPUT_BUFFER_TOO_SMALL, NULL); ++ mSignalledError = true; ++ return NULL; ++ } ++ return memset(outHeader->pBuffer, c, len); ++} ++ + OMX_ERRORTYPE SoftMP3::internalGetParameter( + OMX_INDEXTYPE index, OMX_PTR params) { + switch (index) { +@@ -300,7 +311,10 @@ + + outHeader->nOffset = 0; + outHeader->nFilledLen = kPVMP3DecoderDelay * mNumChannels * sizeof(int16_t); + +- memset(outHeader->pBuffer, 0, outHeader->nFilledLen); ++ if (!memsetSafe(outHeader, 0, outHeader->nFilledLen)) { ++ return; ++ } ++ + } + outHeader->nFlags = OMX_BUFFERFLAG_EOS; + mSignalledOutputEos = true; +@@ -312,9 +326,9 @@ + + // if mIsFirst is true as we may not have a valid + // mConfig->samplingRate and mConfig->num_channels? + ALOGV_IF(mIsFirst, ""insufficient data for first frame, sending silence""); +- memset(outHeader->pBuffer, +- 0, +- mConfig->outputFrameSize * sizeof(int16_t)); ++ if (!memsetSafe(outHeader, 0, mConfig->outputFrameSize * sizeof(int16_t))) { ++ return; ++ } + + if (inHeader) { + mConfig->inputBufferUsedLength = inHeader->nFilledLen; +",1210,1541,2048 +7471,"conn *conn_new(const int sfd, enum conn_states init_state, + const int event_flags, + const int read_buffer_size, enum network_transport transport, + struct event_base *base) { + conn *c; + + assert(sfd >= 0 && sfd < max_fds); + c = conns[sfd]; + + if (NULL == c) { + if (!(c = (conn *)calloc(1, sizeof(conn)))) { + STATS_LOCK(); + stats.malloc_fails++; + STATS_UNLOCK(); + fprintf(stderr, ""Failed to allocate connection object\n""); + return NULL; + } + MEMCACHED_CONN_CREATE(c); + + c->rbuf = c->wbuf = 0; + c->ilist = 0; + c->suffixlist = 0; + c->iov = 0; + c->msglist = 0; + c->hdrbuf = 0; + + c->rsize = read_buffer_size; + c->wsize = DATA_BUFFER_SIZE; + c->isize = ITEM_LIST_INITIAL; + c->suffixsize = SUFFIX_LIST_INITIAL; + c->iovsize = IOV_LIST_INITIAL; + c->msgsize = MSG_LIST_INITIAL; + c->hdrsize = 0; + + c->rbuf = (char *)malloc((size_t)c->rsize); + c->wbuf = (char *)malloc((size_t)c->wsize); + c->ilist = (item **)malloc(sizeof(item *) * c->isize); + c->suffixlist = (char **)malloc(sizeof(char *) * c->suffixsize); + c->iov = (struct iovec *)malloc(sizeof(struct iovec) * c->iovsize); + c->msglist = (struct msghdr *)malloc(sizeof(struct msghdr) * c->msgsize); + + if (c->rbuf == 0 || c->wbuf == 0 || c->ilist == 0 || c->iov == 0 || + c->msglist == 0 || c->suffixlist == 0) { + conn_free(c); + STATS_LOCK(); + stats.malloc_fails++; + STATS_UNLOCK(); + fprintf(stderr, ""Failed to allocate buffers for connection\n""); + return NULL; + } + + STATS_LOCK(); + stats_state.conn_structs++; + STATS_UNLOCK(); + + c->sfd = sfd; + conns[sfd] = c; + } + + c->transport = transport; + c->protocol = settings.binding_protocol; + + /* unix socket mode doesn't need this, so zeroed out. but why + * is this done for every command? presumably for UDP + * mode. */ + if (!settings.socketpath) { + c->request_addr_size = sizeof(c->request_addr); + } else { + c->request_addr_size = 0; + } + + if (transport == tcp_transport && init_state == conn_new_cmd) { + if (getpeername(sfd, (struct sockaddr *) &c->request_addr, + &c->request_addr_size)) { + perror(""getpeername""); + memset(&c->request_addr, 0, sizeof(c->request_addr)); + } + } + + if (settings.verbose > 1) { + if (init_state == conn_listening) { + fprintf(stderr, ""<%d server listening (%s)\n"", sfd, + prot_text(c->protocol)); + } else if (IS_UDP(transport)) { + fprintf(stderr, ""<%d server listening (udp)\n"", sfd); + } else if (c->protocol == negotiating_prot) { + fprintf(stderr, ""<%d new auto-negotiating client connection\n"", + sfd); + } else if (c->protocol == ascii_prot) { + fprintf(stderr, ""<%d new ascii client connection.\n"", sfd); + } else if (c->protocol == binary_prot) { + fprintf(stderr, ""<%d new binary client connection.\n"", sfd); + } else { + fprintf(stderr, ""<%d new unknown (%d) client connection\n"", + sfd, c->protocol); + assert(false); + } + } + + c->state = init_state; + c->rlbytes = 0; + c->cmd = -1; + c->rbytes = c->wbytes = 0; + c->wcurr = c->wbuf; + c->rcurr = c->rbuf; + c->ritem = 0; + c->icurr = c->ilist; + c->suffixcurr = c->suffixlist; + c->ileft = 0; + c->suffixleft = 0; + c->iovused = 0; + c->msgcurr = 0; + c->msgused = 0; + c->authenticated = false; + c->last_cmd_time = current_time; /* initialize for idle kicker */ + + c->write_and_go = init_state; + c->write_and_free = 0; + c->item = 0; + + c->noreply = false; + + event_set(&c->event, sfd, event_flags, event_handler, (void *)c); + event_base_set(base, &c->event); + c->ev_flags = event_flags; + + if (event_add(&c->event, 0) == -1) { + perror(""event_add""); + return NULL; + } + + STATS_LOCK(); + stats_state.curr_conns++; + stats.total_conns++; + STATS_UNLOCK(); + + MEMCACHED_CONN_ALLOCATE(c->sfd); + + return c; +} +",0,"conn *conn_new(const int sfd, enum conn_states init_state, + const int event_flags, + const int read_buffer_size, enum network_transport transport, + struct event_base *base) { + conn *c; + + assert(sfd >= 0 && sfd < max_fds); + c = conns[sfd]; + + if (NULL == c) { + if (!(c = (conn *)calloc(1, sizeof(conn)))) { + STATS_LOCK(); + stats.malloc_fails++; + STATS_UNLOCK(); + fprintf(stderr, ""Failed to allocate connection object\n""); + return NULL; + } + MEMCACHED_CONN_CREATE(c); + + c->rbuf = c->wbuf = 0; + c->ilist = 0; + c->suffixlist = 0; + c->iov = 0; + c->msglist = 0; + c->hdrbuf = 0; + + c->rsize = read_buffer_size; + c->wsize = DATA_BUFFER_SIZE; + c->isize = ITEM_LIST_INITIAL; + c->suffixsize = SUFFIX_LIST_INITIAL; + c->iovsize = IOV_LIST_INITIAL; + c->msgsize = MSG_LIST_INITIAL; + c->hdrsize = 0; + + c->rbuf = (char *)malloc((size_t)c->rsize); + c->wbuf = (char *)malloc((size_t)c->wsize); + c->ilist = (item **)malloc(sizeof(item *) * c->isize); + c->suffixlist = (char **)malloc(sizeof(char *) * c->suffixsize); + c->iov = (struct iovec *)malloc(sizeof(struct iovec) * c->iovsize); + c->msglist = (struct msghdr *)malloc(sizeof(struct msghdr) * c->msgsize); + + if (c->rbuf == 0 || c->wbuf == 0 || c->ilist == 0 || c->iov == 0 || + c->msglist == 0 || c->suffixlist == 0) { + conn_free(c); + STATS_LOCK(); + stats.malloc_fails++; + STATS_UNLOCK(); + fprintf(stderr, ""Failed to allocate buffers for connection\n""); + return NULL; + } + + STATS_LOCK(); + stats_state.conn_structs++; + STATS_UNLOCK(); + + c->sfd = sfd; + conns[sfd] = c; + } + + c->transport = transport; + c->protocol = settings.binding_protocol; + + /* unix socket mode doesn't need this, so zeroed out. but why + * is this done for every command? presumably for UDP + * mode. */ + if (!settings.socketpath) { + c->request_addr_size = sizeof(c->request_addr); + } else { + c->request_addr_size = 0; + } + + if (transport == tcp_transport && init_state == conn_new_cmd) { + if (getpeername(sfd, (struct sockaddr *) &c->request_addr, + &c->request_addr_size)) { + perror(""getpeername""); + memset(&c->request_addr, 0, sizeof(c->request_addr)); + } + } + + if (settings.verbose > 1) { + if (init_state == conn_listening) { + fprintf(stderr, ""<%d server listening (%s)\n"", sfd, + prot_text(c->protocol)); + } else if (IS_UDP(transport)) { + fprintf(stderr, ""<%d server listening (udp)\n"", sfd); + } else if (c->protocol == negotiating_prot) { + fprintf(stderr, ""<%d new auto-negotiating client connection\n"", + sfd); + } else if (c->protocol == ascii_prot) { + fprintf(stderr, ""<%d new ascii client connection.\n"", sfd); + } else if (c->protocol == binary_prot) { + fprintf(stderr, ""<%d new binary client connection.\n"", sfd); + } else { + fprintf(stderr, ""<%d new unknown (%d) client connection\n"", + sfd, c->protocol); + assert(false); + } + } + + c->state = init_state; + c->rlbytes = 0; + c->cmd = -1; + c->rbytes = c->wbytes = 0; + c->wcurr = c->wbuf; + c->rcurr = c->rbuf; + c->ritem = 0; + c->icurr = c->ilist; + c->suffixcurr = c->suffixlist; + c->ileft = 0; + c->suffixleft = 0; + c->iovused = 0; + c->msgcurr = 0; + c->msgused = 0; + c->authenticated = false; + c->last_cmd_time = current_time; /* initialize for idle kicker */ + + c->write_and_go = init_state; + c->write_and_free = 0; + c->item = 0; + + c->noreply = false; + + event_set(&c->event, sfd, event_flags, event_handler, (void *)c); + event_base_set(base, &c->event); + c->ev_flags = event_flags; + + if (event_add(&c->event, 0) == -1) { + perror(""event_add""); + return NULL; + } + + STATS_LOCK(); + stats_state.curr_conns++; + stats.total_conns++; + STATS_UNLOCK(); + + MEMCACHED_CONN_ALLOCATE(c->sfd); + + return c; +} +","@@ -3249,6 +3249,16 @@ static inline int make_ascii_get_suffix(char *suffix, item *it, bool return_cas) + return (p - suffix) + 2; + } + ++#define IT_REFCOUNT_LIMIT 60000 ++static inline item* limited_get(char *key, size_t nkey, conn *c) { ++ item *it = item_get(key, nkey, c, DO_UPDATE); ++ if (it && it->refcount > IT_REFCOUNT_LIMIT) { ++ item_remove(it); ++ it = NULL; ++ } ++ return it; ++} ++ + /* ntokens is overwritten here... shrug.. */ + static inline void process_get_command(conn *c, token_t *tokens, size_t ntokens, bool return_cas) { + char *key; +@@ -3273,7 +3283,7 @@ static inline void process_get_command(conn *c, token_t *tokens, size_t ntokens, + return; + } + +- it = item_get(key, nkey, c, DO_UPDATE); ++ it = limited_get(key, nkey, c); + if (settings.detail_enabled) { + stats_prefix_record_get(key, nkey, NULL != it); + }",1184,1515,2048 +12554,"Browser::Browser(const CreateParams& params) + : type_(params.type), + profile_(params.profile), + window_(NULL), + ALLOW_THIS_IN_INITIALIZER_LIST( + tab_strip_model_delegate_( + new chrome::BrowserTabStripModelDelegate(this))), + tab_strip_model_(new TabStripModel(tab_strip_model_delegate_.get(), + params.profile)), + app_name_(params.app_name), + app_type_(params.app_type), + chrome_updater_factory_(this), + cancel_download_confirmation_state_(NOT_PROMPTED), + override_bounds_(params.initial_bounds), + initial_show_state_(params.initial_show_state), + is_session_restore_(params.is_session_restore), + host_desktop_type_(params.host_desktop_type), + ALLOW_THIS_IN_INITIALIZER_LIST( + unload_controller_(new chrome::UnloadController(this))), + weak_factory_(this), + ALLOW_THIS_IN_INITIALIZER_LIST( + content_setting_bubble_model_delegate_( + new BrowserContentSettingBubbleModelDelegate(this))), + ALLOW_THIS_IN_INITIALIZER_LIST( + toolbar_model_delegate_( + new BrowserToolbarModelDelegate(this))), + ALLOW_THIS_IN_INITIALIZER_LIST( + tab_restore_service_delegate_( + new BrowserTabRestoreServiceDelegate(this))), + ALLOW_THIS_IN_INITIALIZER_LIST( + synced_window_delegate_( + new BrowserSyncedWindowDelegate(this))), + bookmark_bar_state_(BookmarkBar::HIDDEN), + ALLOW_THIS_IN_INITIALIZER_LIST( + command_controller_(new chrome::BrowserCommandController(this))), + window_has_shown_(false) { + if (!app_name_.empty()) + chrome::RegisterAppPrefs(app_name_, profile_); + tab_strip_model_->AddObserver(this); + + toolbar_model_.reset(new ToolbarModelImpl(toolbar_model_delegate_.get())); + search_model_.reset(new chrome::search::SearchModel(NULL)); + search_delegate_.reset( + new chrome::search::SearchDelegate(search_model_.get(), + toolbar_model_.get())); + + registrar_.Add(this, content::NOTIFICATION_SSL_VISIBLE_STATE_CHANGED, + content::NotificationService::AllSources()); + registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_LOADED, + content::Source(profile_->GetOriginalProfile())); + registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED, + content::Source(profile_->GetOriginalProfile())); + registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNINSTALLED, + content::Source(profile_->GetOriginalProfile())); + registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED, + content::NotificationService::AllSources()); +#if defined(ENABLE_THEMES) + registrar_.Add( + this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED, + content::Source( + ThemeServiceFactory::GetForProfile(profile_))); +#endif + registrar_.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED, + content::NotificationService::AllSources()); + + profile_pref_registrar_.Init(profile_->GetPrefs()); + profile_pref_registrar_.Add(prefs::kDevToolsDisabled, this); + profile_pref_registrar_.Add(prefs::kShowBookmarkBar, this); + profile_pref_registrar_.Add(prefs::kHomePage, this); + + BrowserList::AddBrowser(this); + + encoding_auto_detect_.Init(prefs::kWebKitUsesUniversalDetector, + profile_->GetPrefs(), NULL); + + instant_controller_.reset(new chrome::BrowserInstantController(this)); + +#if 0 + device_attached_intent_source_.reset( + new DeviceAttachedIntentSource(this, (this))); +#endif + + UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_INIT); + + FilePath profile_path = profile_->GetPath(); + ProfileMetrics::LogProfileLaunch(profile_path); + + window_ = params.window ? params.window : CreateBrowserWindow(this); + +#if defined(OS_WIN) && !defined(USE_AURA) + ui::win::SetAppIdForWindow( + is_app() && !is_type_panel() ? + ShellIntegration::GetAppModelIdForProfile(UTF8ToWide(app_name_), + profile_->GetPath()) : + ShellIntegration::GetChromiumModelIdForProfile(profile_->GetPath()), + window()->GetNativeWindow()); + + if (is_type_panel()) { + ui::win::SetAppIconForWindow(ShellIntegration::GetChromiumIconPath(), + window()->GetNativeWindow()); + } +#endif + + extension_window_controller_.reset( + new BrowserExtensionWindowController(this)); + + content::NotificationService::current()->Notify( + chrome::NOTIFICATION_BROWSER_WINDOW_READY, + content::Source(this), + content::NotificationService::NoDetails()); + + PrefService* local_state = g_browser_process->local_state(); + if (local_state && local_state->FindPreference( + prefs::kAutofillPersonalDataManagerFirstRun) && + local_state->GetBoolean(prefs::kAutofillPersonalDataManagerFirstRun)) { +#if defined(OS_WIN) + ImportAutofillDataWin(PersonalDataManagerFactory::GetForProfile(profile_)); +#endif // defined(OS_WIN) + local_state->ClearPref(prefs::kAutofillPersonalDataManagerFirstRun); + } + + fullscreen_controller_.reset(new FullscreenController(this)); + search_model_->AddObserver(this); +} +",0,"Browser::Browser(const CreateParams& params) + : type_(params.type), + profile_(params.profile), + window_(NULL), + ALLOW_THIS_IN_INITIALIZER_LIST( + tab_strip_model_delegate_( + new chrome::BrowserTabStripModelDelegate(this))), + tab_strip_model_(new TabStripModel(tab_strip_model_delegate_.get(), + params.profile)), + app_name_(params.app_name), + app_type_(params.app_type), + chrome_updater_factory_(this), + cancel_download_confirmation_state_(NOT_PROMPTED), + override_bounds_(params.initial_bounds), + initial_show_state_(params.initial_show_state), + is_session_restore_(params.is_session_restore), + host_desktop_type_(params.host_desktop_type), + ALLOW_THIS_IN_INITIALIZER_LIST( + unload_controller_(new chrome::UnloadController(this))), + weak_factory_(this), + ALLOW_THIS_IN_INITIALIZER_LIST( + content_setting_bubble_model_delegate_( + new BrowserContentSettingBubbleModelDelegate(this))), + ALLOW_THIS_IN_INITIALIZER_LIST( + toolbar_model_delegate_( + new BrowserToolbarModelDelegate(this))), + ALLOW_THIS_IN_INITIALIZER_LIST( + tab_restore_service_delegate_( + new BrowserTabRestoreServiceDelegate(this))), + ALLOW_THIS_IN_INITIALIZER_LIST( + synced_window_delegate_( + new BrowserSyncedWindowDelegate(this))), + bookmark_bar_state_(BookmarkBar::HIDDEN), + ALLOW_THIS_IN_INITIALIZER_LIST( + command_controller_(new chrome::BrowserCommandController(this))), + window_has_shown_(false) { + if (!app_name_.empty()) + chrome::RegisterAppPrefs(app_name_, profile_); + tab_strip_model_->AddObserver(this); + + toolbar_model_.reset(new ToolbarModelImpl(toolbar_model_delegate_.get())); + search_model_.reset(new chrome::search::SearchModel(NULL)); + search_delegate_.reset( + new chrome::search::SearchDelegate(search_model_.get(), + toolbar_model_.get())); + + registrar_.Add(this, content::NOTIFICATION_SSL_VISIBLE_STATE_CHANGED, + content::NotificationService::AllSources()); + registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_LOADED, + content::Source(profile_->GetOriginalProfile())); + registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED, + content::Source(profile_->GetOriginalProfile())); + registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNINSTALLED, + content::Source(profile_->GetOriginalProfile())); + registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED, + content::NotificationService::AllSources()); +#if defined(ENABLE_THEMES) + registrar_.Add( + this, chrome::NOTIFICATION_BROWSER_THEME_CHANGED, + content::Source( + ThemeServiceFactory::GetForProfile(profile_))); +#endif + registrar_.Add(this, chrome::NOTIFICATION_WEB_CONTENT_SETTINGS_CHANGED, + content::NotificationService::AllSources()); + + profile_pref_registrar_.Init(profile_->GetPrefs()); + profile_pref_registrar_.Add(prefs::kDevToolsDisabled, this); + profile_pref_registrar_.Add(prefs::kShowBookmarkBar, this); + profile_pref_registrar_.Add(prefs::kHomePage, this); + + BrowserList::AddBrowser(this); + + encoding_auto_detect_.Init(prefs::kWebKitUsesUniversalDetector, + profile_->GetPrefs(), NULL); + + instant_controller_.reset(new chrome::BrowserInstantController(this)); + +#if 0 + device_attached_intent_source_.reset( + new DeviceAttachedIntentSource(this, (this))); +#endif + + UpdateBookmarkBarState(BOOKMARK_BAR_STATE_CHANGE_INIT); + + FilePath profile_path = profile_->GetPath(); + ProfileMetrics::LogProfileLaunch(profile_path); + + window_ = params.window ? params.window : CreateBrowserWindow(this); + +#if defined(OS_WIN) && !defined(USE_AURA) + ui::win::SetAppIdForWindow( + is_app() && !is_type_panel() ? + ShellIntegration::GetAppModelIdForProfile(UTF8ToWide(app_name_), + profile_->GetPath()) : + ShellIntegration::GetChromiumModelIdForProfile(profile_->GetPath()), + window()->GetNativeWindow()); + + if (is_type_panel()) { + ui::win::SetAppIconForWindow(ShellIntegration::GetChromiumIconPath(), + window()->GetNativeWindow()); + } +#endif + + extension_window_controller_.reset( + new BrowserExtensionWindowController(this)); + + content::NotificationService::current()->Notify( + chrome::NOTIFICATION_BROWSER_WINDOW_READY, + content::Source(this), + content::NotificationService::NoDetails()); + + PrefService* local_state = g_browser_process->local_state(); + if (local_state && local_state->FindPreference( + prefs::kAutofillPersonalDataManagerFirstRun) && + local_state->GetBoolean(prefs::kAutofillPersonalDataManagerFirstRun)) { +#if defined(OS_WIN) + ImportAutofillDataWin(PersonalDataManagerFactory::GetForProfile(profile_)); +#endif // defined(OS_WIN) + local_state->ClearPref(prefs::kAutofillPersonalDataManagerFirstRun); + } + + fullscreen_controller_.reset(new FullscreenController(this)); + search_model_->AddObserver(this); +} +","@@ -1055,7 +1055,7 @@ void Browser::TabClosingAt(TabStripModel* tab_strip_model, + SetAsDelegate(contents, NULL); + } + +-void Browser::TabDetachedAt(TabContents* contents, int index) { ++void Browser::TabDetachedAt(WebContents* contents, int index) { + TabDetachedAtImpl(contents, index, DETACH_TYPE_DETACH); + } + +@@ -1149,7 +1149,7 @@ void Browser::TabReplacedAt(TabStripModel* tab_strip_model, + TabContents* old_contents, + TabContents* new_contents, + int index) { +- TabDetachedAtImpl(old_contents, index, DETACH_TYPE_REPLACE); ++ TabDetachedAtImpl(old_contents->web_contents(), index, DETACH_TYPE_REPLACE); + SessionService* session_service = + SessionServiceFactory::GetForProfile(profile_); + if (session_service) +@@ -2162,37 +2162,38 @@ void Browser::CloseFrame() { + window_->Close(); + } + +-void Browser::TabDetachedAtImpl(TabContents* contents, int index, ++void Browser::TabDetachedAtImpl(content::WebContents* contents, ++ int index, + DetachType type) { + if (type == DETACH_TYPE_DETACH) { + // Save the current location bar state, but only if the tab being detached + // is the selected tab. Because saving state can conditionally revert the + // location bar, saving the current tab's location bar state to a + // non-selected tab can corrupt both tabs. +- if (contents == chrome::GetActiveTabContents(this)) { ++ if (contents == chrome::GetActiveWebContents(this)) { + LocationBar* location_bar = window()->GetLocationBar(); + if (location_bar) +- location_bar->SaveStateToContents(contents->web_contents()); ++ location_bar->SaveStateToContents(contents); + } + + if (!tab_strip_model_->closing_all()) + SyncHistoryWithTabs(0); + } + +- SetAsDelegate(contents->web_contents(), NULL); +- RemoveScheduledUpdatesFor(contents->web_contents()); ++ SetAsDelegate(contents, NULL); ++ RemoveScheduledUpdatesFor(contents); + + if (find_bar_controller_.get() && index == active_index()) { + find_bar_controller_->ChangeWebContents(NULL); + } + + // Stop observing search model changes for this tab. +- search_delegate_->OnTabDetached(contents->web_contents()); ++ search_delegate_->OnTabDetached(contents); + + registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_ATTACHED, +- content::Source(contents->web_contents())); ++ content::Source(contents)); + registrar_.Remove(this, content::NOTIFICATION_INTERSTITIAL_DETACHED, +- content::Source(contents->web_contents())); ++ content::Source(contents)); + } + + bool Browser::SupportsWindowFeatureImpl(WindowFeature feature,",1062,1393,2048 +5064,"PHP_FUNCTION(imagepsbbox) +{ + zval *fnt; + long sz = 0, sp = 0, wd = 0; + char *str; + int i, space = 0, add_width = 0, char_width, amount_kern; + int cur_x, cur_y, dx, dy; + int x1, y1, x2, y2, x3, y3, x4, y4; + int *f_ind; + int str_len, per_char = 0; + int argc = ZEND_NUM_ARGS(); + double angle = 0, sin_a = 0, cos_a = 0; + BBox char_bbox, str_bbox = {0, 0, 0, 0}; + + if (argc != 3 && argc != 6) { + ZEND_WRONG_PARAM_COUNT(); + } + + if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""srl|lld"", &str, &str_len, &fnt, &sz, &sp, &wd, &angle) == FAILURE) { + return; + } + + if (argc == 6) { + space = sp; + add_width = wd; + angle = angle * M_PI / 180; + sin_a = sin(angle); + cos_a = cos(angle); + per_char = add_width || angle ? 1 : 0; + } + + ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, ""Type 1 font"", le_ps_font); + +#define max(a, b) (a > b ? a : b) +#define min(a, b) (a < b ? a : b) +#define new_x(a, b) (int) ((a) * cos_a - (b) * sin_a) +#define new_y(a, b) (int) ((a) * sin_a + (b) * cos_a) + + if (per_char) { + space += T1_GetCharWidth(*f_ind, ' '); + cur_x = cur_y = 0; + + for (i = 0; i < str_len; i++) { + if (str[i] == ' ') { + char_bbox.llx = char_bbox.lly = char_bbox.ury = 0; + char_bbox.urx = char_width = space; + } else { + char_bbox = T1_GetCharBBox(*f_ind, str[i]); + char_width = T1_GetCharWidth(*f_ind, str[i]); + } + amount_kern = i ? T1_GetKerning(*f_ind, str[i - 1], str[i]) : 0; + + /* Transfer character bounding box to right place */ + x1 = new_x(char_bbox.llx, char_bbox.lly) + cur_x; + y1 = new_y(char_bbox.llx, char_bbox.lly) + cur_y; + x2 = new_x(char_bbox.llx, char_bbox.ury) + cur_x; + y2 = new_y(char_bbox.llx, char_bbox.ury) + cur_y; + x3 = new_x(char_bbox.urx, char_bbox.ury) + cur_x; + y3 = new_y(char_bbox.urx, char_bbox.ury) + cur_y; + x4 = new_x(char_bbox.urx, char_bbox.lly) + cur_x; + y4 = new_y(char_bbox.urx, char_bbox.lly) + cur_y; + + /* Find min & max values and compare them with current bounding box */ + str_bbox.llx = min(str_bbox.llx, min(x1, min(x2, min(x3, x4)))); + str_bbox.lly = min(str_bbox.lly, min(y1, min(y2, min(y3, y4)))); + str_bbox.urx = max(str_bbox.urx, max(x1, max(x2, max(x3, x4)))); + str_bbox.ury = max(str_bbox.ury, max(y1, max(y2, max(y3, y4)))); + + /* Move to the next base point */ + dx = new_x(char_width + add_width + amount_kern, 0); + dy = new_y(char_width + add_width + amount_kern, 0); + cur_x += dx; + cur_y += dy; + /* + printf(""%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n"", x1, y1, x2, y2, x3, y3, x4, y4, char_bbox.llx, char_bbox.lly, char_bbox.urx, char_bbox.ury, char_width, amount_kern, cur_x, cur_y, dx, dy); + */ + } + + } else { + str_bbox = T1_GetStringBBox(*f_ind, str, str_len, space, T1_KERNING); + } + + if (T1_errno) { + RETURN_FALSE; + } + + array_init(return_value); + /* + printf(""%d %d %d %d\n"", str_bbox.llx, str_bbox.lly, str_bbox.urx, str_bbox.ury); + */ + add_next_index_long(return_value, (int) ceil(((double) str_bbox.llx)*sz/1000)); + add_next_index_long(return_value, (int) ceil(((double) str_bbox.lly)*sz/1000)); + add_next_index_long(return_value, (int) ceil(((double) str_bbox.urx)*sz/1000)); + add_next_index_long(return_value, (int) ceil(((double) str_bbox.ury)*sz/1000)); +} +",0,"PHP_FUNCTION(imagepsbbox) +{ + zval *fnt; + long sz = 0, sp = 0, wd = 0; + char *str; + int i, space = 0, add_width = 0, char_width, amount_kern; + int cur_x, cur_y, dx, dy; + int x1, y1, x2, y2, x3, y3, x4, y4; + int *f_ind; + int str_len, per_char = 0; + int argc = ZEND_NUM_ARGS(); + double angle = 0, sin_a = 0, cos_a = 0; + BBox char_bbox, str_bbox = {0, 0, 0, 0}; + + if (argc != 3 && argc != 6) { + ZEND_WRONG_PARAM_COUNT(); + } + + if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""srl|lld"", &str, &str_len, &fnt, &sz, &sp, &wd, &angle) == FAILURE) { + return; + } + + if (argc == 6) { + space = sp; + add_width = wd; + angle = angle * M_PI / 180; + sin_a = sin(angle); + cos_a = cos(angle); + per_char = add_width || angle ? 1 : 0; + } + + ZEND_FETCH_RESOURCE(f_ind, int *, &fnt, -1, ""Type 1 font"", le_ps_font); + +#define max(a, b) (a > b ? a : b) +#define min(a, b) (a < b ? a : b) +#define new_x(a, b) (int) ((a) * cos_a - (b) * sin_a) +#define new_y(a, b) (int) ((a) * sin_a + (b) * cos_a) + + if (per_char) { + space += T1_GetCharWidth(*f_ind, ' '); + cur_x = cur_y = 0; + + for (i = 0; i < str_len; i++) { + if (str[i] == ' ') { + char_bbox.llx = char_bbox.lly = char_bbox.ury = 0; + char_bbox.urx = char_width = space; + } else { + char_bbox = T1_GetCharBBox(*f_ind, str[i]); + char_width = T1_GetCharWidth(*f_ind, str[i]); + } + amount_kern = i ? T1_GetKerning(*f_ind, str[i - 1], str[i]) : 0; + + /* Transfer character bounding box to right place */ + x1 = new_x(char_bbox.llx, char_bbox.lly) + cur_x; + y1 = new_y(char_bbox.llx, char_bbox.lly) + cur_y; + x2 = new_x(char_bbox.llx, char_bbox.ury) + cur_x; + y2 = new_y(char_bbox.llx, char_bbox.ury) + cur_y; + x3 = new_x(char_bbox.urx, char_bbox.ury) + cur_x; + y3 = new_y(char_bbox.urx, char_bbox.ury) + cur_y; + x4 = new_x(char_bbox.urx, char_bbox.lly) + cur_x; + y4 = new_y(char_bbox.urx, char_bbox.lly) + cur_y; + + /* Find min & max values and compare them with current bounding box */ + str_bbox.llx = min(str_bbox.llx, min(x1, min(x2, min(x3, x4)))); + str_bbox.lly = min(str_bbox.lly, min(y1, min(y2, min(y3, y4)))); + str_bbox.urx = max(str_bbox.urx, max(x1, max(x2, max(x3, x4)))); + str_bbox.ury = max(str_bbox.ury, max(y1, max(y2, max(y3, y4)))); + + /* Move to the next base point */ + dx = new_x(char_width + add_width + amount_kern, 0); + dy = new_y(char_width + add_width + amount_kern, 0); + cur_x += dx; + cur_y += dy; + /* + printf(""%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n"", x1, y1, x2, y2, x3, y3, x4, y4, char_bbox.llx, char_bbox.lly, char_bbox.urx, char_bbox.ury, char_width, amount_kern, cur_x, cur_y, dx, dy); + */ + } + + } else { + str_bbox = T1_GetStringBBox(*f_ind, str, str_len, space, T1_KERNING); + } + + if (T1_errno) { + RETURN_FALSE; + } + + array_init(return_value); + /* + printf(""%d %d %d %d\n"", str_bbox.llx, str_bbox.lly, str_bbox.urx, str_bbox.ury); + */ + add_next_index_long(return_value, (int) ceil(((double) str_bbox.llx)*sz/1000)); + add_next_index_long(return_value, (int) ceil(((double) str_bbox.lly)*sz/1000)); + add_next_index_long(return_value, (int) ceil(((double) str_bbox.urx)*sz/1000)); + add_next_index_long(return_value, (int) ceil(((double) str_bbox.ury)*sz/1000)); +} +","@@ -3082,6 +3082,11 @@ PHP_FUNCTION(imagegammacorrect) + return; + } + ++ if ( input <= 0.0 || output <= 0.0 ) { ++ php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Gamma values should be positive""); ++ RETURN_FALSE; ++ } ++ + ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, ""Image"", le_gd); + + if (gdImageTrueColor(im)) {",1211,1542,2048 +8541,"static struct mapped_device *alloc_dev(int minor) +{ + int r, numa_node_id = dm_get_numa_node(); + struct dax_device *dax_dev; + struct mapped_device *md; + void *old_md; + + md = kvzalloc_node(sizeof(*md), GFP_KERNEL, numa_node_id); + if (!md) { + DMWARN(""unable to allocate device, out of memory.""); + return NULL; + } + + if (!try_module_get(THIS_MODULE)) + goto bad_module_get; + + /* get a minor number for the dev */ + if (minor == DM_ANY_MINOR) + r = next_free_minor(&minor); + else + r = specific_minor(minor); + if (r < 0) + goto bad_minor; + + r = init_srcu_struct(&md->io_barrier); + if (r < 0) + goto bad_io_barrier; + + md->numa_node_id = numa_node_id; + md->use_blk_mq = dm_use_blk_mq_default(); + md->init_tio_pdu = false; + md->type = DM_TYPE_NONE; + mutex_init(&md->suspend_lock); + mutex_init(&md->type_lock); + mutex_init(&md->table_devices_lock); + spin_lock_init(&md->deferred_lock); + atomic_set(&md->holders, 1); + atomic_set(&md->open_count, 0); + atomic_set(&md->event_nr, 0); + atomic_set(&md->uevent_seq, 0); + INIT_LIST_HEAD(&md->uevent_list); + INIT_LIST_HEAD(&md->table_devices); + spin_lock_init(&md->uevent_lock); + + md->queue = blk_alloc_queue_node(GFP_KERNEL, numa_node_id); + if (!md->queue) + goto bad; + + dm_init_md_queue(md); + + md->disk = alloc_disk_node(1, numa_node_id); + if (!md->disk) + goto bad; + + atomic_set(&md->pending[0], 0); + atomic_set(&md->pending[1], 0); + init_waitqueue_head(&md->wait); + INIT_WORK(&md->work, dm_wq_work); + init_waitqueue_head(&md->eventq); + init_completion(&md->kobj_holder.completion); + md->kworker_task = NULL; + + md->disk->major = _major; + md->disk->first_minor = minor; + md->disk->fops = &dm_blk_dops; + md->disk->queue = md->queue; + md->disk->private_data = md; + sprintf(md->disk->disk_name, ""dm-%d"", minor); + + dax_dev = alloc_dax(md, md->disk->disk_name, &dm_dax_ops); + if (!dax_dev) + goto bad; + md->dax_dev = dax_dev; + + add_disk(md->disk); + format_dev_t(md->name, MKDEV(_major, minor)); + + md->wq = alloc_workqueue(""kdmflush"", WQ_MEM_RECLAIM, 0); + if (!md->wq) + goto bad; + + md->bdev = bdget_disk(md->disk, 0); + if (!md->bdev) + goto bad; + + bio_init(&md->flush_bio, NULL, 0); + bio_set_dev(&md->flush_bio, md->bdev); + md->flush_bio.bi_opf = REQ_OP_WRITE | REQ_PREFLUSH | REQ_SYNC; + + dm_stats_init(&md->stats); + + /* Populate the mapping, nobody knows we exist yet */ + spin_lock(&_minor_lock); + old_md = idr_replace(&_minor_idr, md, minor); + spin_unlock(&_minor_lock); + + BUG_ON(old_md != MINOR_ALLOCED); + + return md; + +bad: + cleanup_mapped_device(md); +bad_io_barrier: + free_minor(minor); +bad_minor: + module_put(THIS_MODULE); +bad_module_get: + kvfree(md); + return NULL; +} +",0,"static struct mapped_device *alloc_dev(int minor) +{ + int r, numa_node_id = dm_get_numa_node(); + struct dax_device *dax_dev; + struct mapped_device *md; + void *old_md; + + md = kvzalloc_node(sizeof(*md), GFP_KERNEL, numa_node_id); + if (!md) { + DMWARN(""unable to allocate device, out of memory.""); + return NULL; + } + + if (!try_module_get(THIS_MODULE)) + goto bad_module_get; + + /* get a minor number for the dev */ + if (minor == DM_ANY_MINOR) + r = next_free_minor(&minor); + else + r = specific_minor(minor); + if (r < 0) + goto bad_minor; + + r = init_srcu_struct(&md->io_barrier); + if (r < 0) + goto bad_io_barrier; + + md->numa_node_id = numa_node_id; + md->use_blk_mq = dm_use_blk_mq_default(); + md->init_tio_pdu = false; + md->type = DM_TYPE_NONE; + mutex_init(&md->suspend_lock); + mutex_init(&md->type_lock); + mutex_init(&md->table_devices_lock); + spin_lock_init(&md->deferred_lock); + atomic_set(&md->holders, 1); + atomic_set(&md->open_count, 0); + atomic_set(&md->event_nr, 0); + atomic_set(&md->uevent_seq, 0); + INIT_LIST_HEAD(&md->uevent_list); + INIT_LIST_HEAD(&md->table_devices); + spin_lock_init(&md->uevent_lock); + + md->queue = blk_alloc_queue_node(GFP_KERNEL, numa_node_id); + if (!md->queue) + goto bad; + + dm_init_md_queue(md); + + md->disk = alloc_disk_node(1, numa_node_id); + if (!md->disk) + goto bad; + + atomic_set(&md->pending[0], 0); + atomic_set(&md->pending[1], 0); + init_waitqueue_head(&md->wait); + INIT_WORK(&md->work, dm_wq_work); + init_waitqueue_head(&md->eventq); + init_completion(&md->kobj_holder.completion); + md->kworker_task = NULL; + + md->disk->major = _major; + md->disk->first_minor = minor; + md->disk->fops = &dm_blk_dops; + md->disk->queue = md->queue; + md->disk->private_data = md; + sprintf(md->disk->disk_name, ""dm-%d"", minor); + + dax_dev = alloc_dax(md, md->disk->disk_name, &dm_dax_ops); + if (!dax_dev) + goto bad; + md->dax_dev = dax_dev; + + add_disk(md->disk); + format_dev_t(md->name, MKDEV(_major, minor)); + + md->wq = alloc_workqueue(""kdmflush"", WQ_MEM_RECLAIM, 0); + if (!md->wq) + goto bad; + + md->bdev = bdget_disk(md->disk, 0); + if (!md->bdev) + goto bad; + + bio_init(&md->flush_bio, NULL, 0); + bio_set_dev(&md->flush_bio, md->bdev); + md->flush_bio.bi_opf = REQ_OP_WRITE | REQ_PREFLUSH | REQ_SYNC; + + dm_stats_init(&md->stats); + + /* Populate the mapping, nobody knows we exist yet */ + spin_lock(&_minor_lock); + old_md = idr_replace(&_minor_idr, md, minor); + spin_unlock(&_minor_lock); + + BUG_ON(old_md != MINOR_ALLOCED); + + return md; + +bad: + cleanup_mapped_device(md); +bad_io_barrier: + free_minor(minor); +bad_minor: + module_put(THIS_MODULE); +bad_module_get: + kvfree(md); + return NULL; +} +","@@ -2711,11 +2711,15 @@ struct mapped_device *dm_get_from_kobject(struct kobject *kobj) + + md = container_of(kobj, struct mapped_device, kobj_holder.kobj); + +- if (test_bit(DMF_FREEING, &md->flags) || +- dm_deleting_md(md)) +- return NULL; +- ++ spin_lock(&_minor_lock); ++ if (test_bit(DMF_FREEING, &md->flags) || dm_deleting_md(md)) { ++ md = NULL; ++ goto out; ++ } + dm_get(md); ++out: ++ spin_unlock(&_minor_lock); ++ + return md; + } + ",796,1127,2048 +17317,"read_chunk(struct file *file) + /* On entry file::data_pos must be set to the position of the first byte + * of the chunk data *and* the input file must be at this position. This + * routine (via process_chunk) instantiates a chunk or IDAT control structure + * based on file::length and file::type and also resets these fields and + * file::data_pos for the chunk after this one. For an IDAT chunk the whole + * stream of IDATs will be read, until something other than an IDAT is + * encountered, and the file fields will be set for the chunk after the end + * of the stream of IDATs. + * + * For IEND the file::type field will be set to 0, and nothing beyond the end + * of the IEND chunk will have been read. + */ +{ + png_uint_32 length = file->length; + png_uint_32 type = file->type; + + /* After IEND file::type is set to 0, if libpng attempts to read + * more data at this point this is a bug in libpng. + */ + if (type == 0) + stop(file, UNEXPECTED_ERROR_CODE, ""read beyond IEND""); + + if (file->global->verbose > 2) + { + fputs("" "", stderr); + type_name(type, stderr); + fprintf(stderr, "" %lu\n"", (unsigned long)length); + } + + /* Start the read_crc calculation with the chunk type, then read to the end + * of the chunk data (without processing it in any way) to check that it is + * all there and calculate the CRC. + */ + file->crc = crc_init_4(type); + if (crc_read_many(file, length)) /* else it was truncated */ + { + png_uint_32 file_crc; /* CRC read from file */ + unsigned int nread = read_4(file, &file_crc); + + if (nread == 4) + { + if (type != png_IEND) /* do not read beyond IEND */ + { + png_uint_32 next_length; + + nread += read_4(file, &next_length); + if (nread == 8 && next_length <= 0x7fffffff) + { + png_uint_32 next_type; + + nread += read_4(file, &next_type); + + if (nread == 12 && chunk_type_valid(next_type)) + { + /* Adjust the read count back to the correct value for this + * chunk. + */ + file->read_count -= 8; + process_chunk(file, file_crc, next_length, next_type); + return; + } + } + } + + else /* IEND */ + { + process_chunk(file, file_crc, 0, 0); + return; + } + } + } + + /* Control gets to here if the the stream seems invalid or damaged in some + * way. Either there was a problem reading all the expected data (this + * chunk's data, its CRC and the length and type of the next chunk) or the + * next chunk length/type are invalid. Notice that the cases that end up + * here all correspond to cases that would otherwise terminate the read of + * the PNG file. + */ + sync_stream(file); +} +",0,"read_chunk(struct file *file) + /* On entry file::data_pos must be set to the position of the first byte + * of the chunk data *and* the input file must be at this position. This + * routine (via process_chunk) instantiates a chunk or IDAT control structure + * based on file::length and file::type and also resets these fields and + * file::data_pos for the chunk after this one. For an IDAT chunk the whole + * stream of IDATs will be read, until something other than an IDAT is + * encountered, and the file fields will be set for the chunk after the end + * of the stream of IDATs. + * + * For IEND the file::type field will be set to 0, and nothing beyond the end + * of the IEND chunk will have been read. + */ +{ + png_uint_32 length = file->length; + png_uint_32 type = file->type; + + /* After IEND file::type is set to 0, if libpng attempts to read + * more data at this point this is a bug in libpng. + */ + if (type == 0) + stop(file, UNEXPECTED_ERROR_CODE, ""read beyond IEND""); + + if (file->global->verbose > 2) + { + fputs("" "", stderr); + type_name(type, stderr); + fprintf(stderr, "" %lu\n"", (unsigned long)length); + } + + /* Start the read_crc calculation with the chunk type, then read to the end + * of the chunk data (without processing it in any way) to check that it is + * all there and calculate the CRC. + */ + file->crc = crc_init_4(type); + if (crc_read_many(file, length)) /* else it was truncated */ + { + png_uint_32 file_crc; /* CRC read from file */ + unsigned int nread = read_4(file, &file_crc); + + if (nread == 4) + { + if (type != png_IEND) /* do not read beyond IEND */ + { + png_uint_32 next_length; + + nread += read_4(file, &next_length); + if (nread == 8 && next_length <= 0x7fffffff) + { + png_uint_32 next_type; + + nread += read_4(file, &next_type); + + if (nread == 12 && chunk_type_valid(next_type)) + { + /* Adjust the read count back to the correct value for this + * chunk. + */ + file->read_count -= 8; + process_chunk(file, file_crc, next_length, next_type); + return; + } + } + } + + else /* IEND */ + { + process_chunk(file, file_crc, 0, 0); + return; + } + } + } + + /* Control gets to here if the the stream seems invalid or damaged in some + * way. Either there was a problem reading all the expected data (this + * chunk's data, its CRC and the length and type of the next chunk) or the + * next chunk length/type are invalid. Notice that the cases that end up + * here all correspond to cases that would otherwise terminate the read of + * the PNG file. + */ + sync_stream(file); +} +","@@ -1,15 +1,15 @@ + + /* pngfix.c + * +- * Copyright (c) 2014 John Cunningham Bowler ++ * Copyright (c) 2014-2015 John Cunningham Bowler + * +- * Last changed in libpng 1.6.10 [March 6, 2014] ++ * Last changed in libpng 1.6.20 [December 3, 2015] + * + * This code is released under the libpng license. + * For conditions of distribution and use, see the disclaimer + * and license in png.h + * +- * Tool to check and fix the zlib inflate 'too far back' problem, see the usage +- * message for more information. ++ * Tool to check and fix the zlib inflate 'too far back' problem. ++ * See the usage message for more information. + */ + #include + #include +@@ -49,7 +49,13 @@ + + # error ""pngfix will not work with libpng prior to 1.6.3"" + #endif + +-#if defined(PNG_READ_SUPPORTED) && defined(PNG_EASY_ACCESS_SUPPORTED) ++#ifdef PNG_SETJMP_SUPPORTED ++#include ++ ++#if defined(PNG_READ_SUPPORTED) && defined(PNG_EASY_ACCESS_SUPPORTED) &&\ ++ (defined(PNG_READ_DEINTERLACE_SUPPORTED) ||\ ++ defined(PNG_READ_INTERLACING_SUPPORTED)) ++ + /* zlib.h defines the structure z_stream, an instance of which is included + * in this structure and is required for decompressing the LZ compressed + * data in PNG files. +@@ -68,8 +74,8 @@ + + * with older builds. + */ + #if ZLIB_VERNUM < 0x1260 +-# define PNGZ_MSG_CAST(s) png_constcast(char*,s) +-# define PNGZ_INPUT_CAST(b) png_constcast(png_bytep,b) ++# define PNGZ_MSG_CAST(s) constcast(char*,s) ++# define PNGZ_INPUT_CAST(b) constcast(png_bytep,b) + #else + # define PNGZ_MSG_CAST(s) (s) + # define PNGZ_INPUT_CAST(b) (b) +@@ -79,21 +85,21 @@ + + # error ""pngfix not supported in this libpng version"" + #endif + +-#if PNG_ZLIB_VERNUM >= 0x1240 ++#if ZLIB_VERNUM >= 0x1240 + + /* Copied from pngpriv.h */ + #ifdef __cplusplus +-# define png_voidcast(type, value) static_cast(value) +-# define png_constcast(type, value) const_cast(value) +-# define png_aligncast(type, value) \ ++# define voidcast(type, value) static_cast(value) ++# define constcast(type, value) const_cast(value) ++# define aligncast(type, value) \ + static_cast(static_cast(value)) +-# define png_aligncastconst(type, value) \ ++# define aligncastconst(type, value) \ + static_cast(static_cast(value)) + #else +-# define png_voidcast(type, value) (value) +-# define png_constcast(type, value) ((type)(value)) +-# define png_aligncast(type, value) ((void*)(value)) +-# define png_aligncastconst(type, value) ((const void*)(value)) ++# define voidcast(type, value) (value) ++# define constcast(type, value) ((type)(value)) ++# define aligncast(type, value) ((void*)(value)) ++# define aligncastconst(type, value) ((const void*)(value)) + #endif /* __cplusplus */ + + #if PNG_LIBPNG_VER < 10700 +@@ -131,7 +137,7 @@ + + #define png_zTXt PNG_U32(122, 84, 88, 116) + #endif + +-/* The 8 byte signature as a pair of 32 bit quantities */ ++/* The 8-byte signature as a pair of 32-bit quantities */ + #define sig1 PNG_U32(137, 80, 78, 71) + #define sig2 PNG_U32( 13, 10, 26, 10) + +@@ -153,7 +159,7 @@ + + */ + #define UNREACHED 0 + +-/* 80-bit number handling - a PNG image can be up to (2^31-1)x(2^31-1) 8 byte ++/* 80-bit number handling - a PNG image can be up to (2^31-1)x(2^31-1) 8-byte + * (16-bit RGBA) pixels in size; that's less than 2^65 bytes or 2^68 bits, so + * arithmetic of 80-bit numbers is sufficient. This representation uses an + * arbitrary length array of png_uint_16 digits (0..65535). The representation +@@ -443,7 +449,7 @@ + + make_random_bytes(png_uint_32* seed, void* pv, size_t size) + { + png_uint_32 u0 = seed[0], u1 = seed[1]; +- png_bytep bytes = png_voidcast(png_bytep, pv); ++ png_bytep bytes = voidcast(png_bytep, pv); + + /* There are thirty-three bits; the next bit in the sequence is bit-33 XOR + * bit-20. The top 1 bit is in u1, the bottom 32 are in u0. +@@ -581,7 +587,7 @@ + + c &= ~PNG_U32(32,32,0,32); + t = (c & ~0x1f1f1f1f) ^ 0x40404040; + +- /* Subtract 65 for each 8 bit quantity, this must not overflow ++ /* Subtract 65 for each 8-bit quantity, this must not overflow + * and each byte must then be in the range 0-25. + */ + c -= PNG_U32(65,65,65,65); +@@ -664,8 +670,8 @@ + + + if (length < tail->length) /* arithmetic overflow */ + length = tail->length; +- +- next = png_voidcast(IDAT_list*, malloc(IDAT_list_size(NULL, length))); ++ ++ next = voidcast(IDAT_list*, malloc(IDAT_list_size(NULL, length))); + CLEAR(*next); + + /* The caller must handle this: */ +@@ -918,7 +924,7 @@ + + + else if (isspace(UCHAR_MAX & *str)) + putc('_', out); +- ++ + else + fprintf(out, ""\\%.3o"", *str); + } +@@ -1942,7 +1948,7 @@ + + list->count = 0; + file->idat->idat_list_tail = list; + } +- ++ + /* And fill in the next IDAT information buffer. */ + list->lengths[(list->count)++] = file->chunk->chunk_length; + +@@ -2135,7 +2141,7 @@ + + * + * z-rc is the zlib failure code; message is the error message with + * spaces replaced by '-'. The compressed byte count indicates where +- * in the zlib stream the error occured. ++ * in the zlib stream the error occurred. + */ + type_name(zlib->chunk->chunk_type, stdout); + printf("" SKP %s %d %s "", zlib_flevel(zlib), zlib->file_bits, +@@ -2215,7 +2221,7 @@ + + /* These values are sticky across reset (in addition to the stuff in the + * first block, which is actually constant.) + */ +- zlib->file_bits = 16; ++ zlib->file_bits = 24; + zlib->ok_bits = 16; /* unset */ + zlib->cksum = 0; /* set when a checksum error is detected */ + +@@ -2298,10 +2304,12 @@ + + zlib->file_bits = file_bits; + + /* Check against the existing value - it may not need to be +- * changed. ++ * changed. Note that a bogus file_bits is allowed through once, ++ * to see if it works, but the window_bits value is set to 15, ++ * the maximum. + */ + if (new_bits == 0) /* no change */ +- zlib->window_bits = file_bits; ++ zlib->window_bits = ((file_bits > 15) ? 15 : file_bits); + + else if (new_bits != file_bits) /* rewrite required */ + bIn = (png_byte)((bIn & 0xf) + ((new_bits-8) << 4)); +@@ -2322,8 +2330,7 @@ + + if (bIn != b2) + { + /* If the first byte wasn't changed this indicates an error in +- * the checksum calculation; signal this by setting file_bits +- * (not window_bits) to 0. ++ * the checksum calculation; signal this by setting 'cksum'. + */ + if (zlib->file_bits == zlib->window_bits) + zlib->cksum = 1; +@@ -2582,7 +2589,7 @@ + + { + struct chunk *chunk = zlib->chunk; + int rc; +- ++ + assert(zlib->rewrite_offset < chunk->chunk_length); + + rc = zlib_advance(zlib, chunk->chunk_length - zlib->rewrite_offset); +@@ -3532,7 +3539,7 @@ + + /* This just returns the (file*). The chunk and idat control structures + * don't always exist. + */ +- struct control *control = png_voidcast(struct control*, ++ struct control *control = voidcast(struct control*, + png_get_error_ptr(png_ptr)); + return &control->file; + } +@@ -3540,7 +3547,7 @@ + + static void + allocate(struct file *file, int allocate_idat) + { +- struct control *control = png_voidcast(struct control*, file->alloc_ptr); ++ struct control *control = voidcast(struct control*, file->alloc_ptr); + + if (allocate_idat) + { +@@ -3574,7 +3581,6 @@ + + { + png_structp png_ptr; + png_infop info_ptr = NULL; +- volatile png_bytep row = NULL, display = NULL; + volatile int rc; + + png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, control, +@@ -3591,6 +3597,16 @@ + + rc = setjmp(control->file.jmpbuf); + if (rc == 0) + { ++# ifdef PNG_SET_USER_LIMITS_SUPPORTED ++ /* Remove any limits on the size of PNG files that can be read, ++ * without this we may reject files based on built-in safety ++ * limits. ++ */ ++ png_set_user_limits(png_ptr, 0x7fffffff, 0x7fffffff); ++ png_set_chunk_cache_max(png_ptr, 0); ++ png_set_chunk_malloc_max(png_ptr, 0); ++# endif ++ + png_set_read_fn(png_ptr, control, read_callback); + + info_ptr = png_create_info_struct(png_ptr); +@@ -3603,32 +3619,22 @@ + + png_read_info(png_ptr, info_ptr); + + { +- png_size_t rowbytes = png_get_rowbytes(png_ptr, info_ptr); ++ png_uint_32 height = png_get_image_height(png_ptr, info_ptr); ++ int passes = png_set_interlace_handling(png_ptr); ++ int pass; + +- row = png_voidcast(png_byte*, malloc(rowbytes)); +- display = png_voidcast(png_byte*, malloc(rowbytes)); ++ png_start_read_image(png_ptr); + +- if (row == NULL || display == NULL) +- png_error(png_ptr, ""OOM allocating row buffers""); ++ for (pass = 0; pass < passes; ++pass) ++ { ++ png_uint_32 y = height; + +- { +- png_uint_32 height = png_get_image_height(png_ptr, info_ptr); +- int passes = png_set_interlace_handling(png_ptr); +- int pass; +- +- png_start_read_image(png_ptr); +- +- for (pass = 0; pass < passes; ++pass) +- { +- png_uint_32 y = height; +- +- /* NOTE: this trashes the row each time; interlace handling won't +- * work, but this avoids memory thrashing for speed testing. +- */ +- while (y-- > 0) +- png_read_row(png_ptr, row, display); +- } +- } ++ /* NOTE: this skips asking libpng to return either version of ++ * the image row, but libpng still reads the rows. ++ */ ++ while (y-- > 0) ++ png_read_row(png_ptr, NULL, NULL); ++ } + } + + if (control->file.global->verbose) +@@ -3639,8 +3645,6 @@ + + } + + png_destroy_read_struct(&png_ptr, &info_ptr, NULL); +- if (row != NULL) free(row); +- if (display != NULL) free(display); + return rc; + } + +@@ -3702,21 +3706,21 @@ + + "" gAMA, sRGB [all]: These specify the gamma encoding used for the pixel"", + "" values."", + "" cHRM, iCCP [color]: These specify how colors are encoded. iCCP also"", +-"" specifies the exact encoding of a pixel value however in practice"", +-"" most programs will ignore it."", ++"" specifies the exact encoding of a pixel value; however, in"", ++"" practice most programs will ignore it."", + "" bKGD [transform]: This is used by libpng transforms."" + "" --max=:"", + "" Use IDAT chunks sized . If no number is given the the IDAT"", + "" chunks will be the maximum size permitted; 2^31-1 bytes. If the option"", + "" is omitted the original chunk sizes will not be changed. When the"", +-"" option is given --strip=unsafe is set automatically, this may be"", ++"" option is given --strip=unsafe is set automatically. This may be"", + "" cancelled if you know that all unknown unsafe-to-copy chunks really are"", + "" safe to copy across an IDAT size change. This is true of all chunks"", + "" that have ever been formally proposed as PNG extensions."", + "" MESSAGES"", + "" By default the program only outputs summaries for each file."", + "" --quiet (-q):"", +-"" Do not output the summaries except for files which cannot be read. With"", ++"" Do not output the summaries except for files that cannot be read. With"", + "" two --quiets these are not output either."", + "" --errors (-e):"", + "" Output errors from libpng and the program (except too-far-back)."", +@@ -3749,7 +3753,7 @@ + + "" the following codes. Notice that the results for each file are combined"", + "" together - check one file at a time to get a meaningful error code!"", + "" 0x01: The zlib too-far-back error existed in at least one chunk."", +-"" 0x02: At least once chunk had a CRC error."", ++"" 0x02: At least one chunk had a CRC error."", + "" 0x04: A chunk length was incorrect."", + "" 0x08: The file was truncated."", + "" Errors less than 16 are potentially recoverable, for a single file if the"", +@@ -3757,7 +3761,7 @@ + + "" non-zero code is returned)."", + "" 0x10: The file could not be read, even with corrections."", + "" 0x20: The output file could not be written."", +-"" 0x40: An unexpected, potentially internal, error occured."", ++"" 0x40: An unexpected, potentially internal, error occurred."", + "" If the command line arguments are incorrect the program exits with exit"", + "" 255. Some older operating systems only support 7-bit exit codes, on those"", + "" systems it is suggested that this program is first tested by supplying"", +@@ -3817,7 +3821,7 @@ + + "" SKP: The chunk was skipped because of a zlib issue (zlib-rc) with"", + "" explanation 'message'"", + "" ERR: The read of the file was aborted. The parameters explain why."", +-""$3 status: For 'ERR' the accumulate status code from 'EXIT CODES' above."", ++""$3 status: For 'ERR' the accumulated status code from 'EXIT CODES' above."", + "" This is printed as a 2 digit hexadecimal value"", + "" comp-level: The recorded compression level (FLEVEL) of a zlib stream"", + "" expressed as a string {supfast,stdfast,default,maximum}"", +@@ -3853,6 +3857,7 @@ + + int + main(int argc, const char **argv) + { ++ char temp_name[FILENAME_MAX+1]; + const char * prog = *argv; + const char * outfile = NULL; + const char * suffix = NULL; +@@ -3955,7 +3960,6 @@ + + else + { + size_t outlen = strlen(*argv); +- char temp_name[FILENAME_MAX+1]; + + if (outfile == NULL) /* else this takes precedence */ + { +@@ -4014,23 +4018,32 @@ + + return global_end(&global); + } + +-#else /* PNG_ZLIB_VERNUM < 0x1240 */ ++#else /* ZLIB_VERNUM < 0x1240 */ + int + main(void) + { + fprintf(stderr, + ""pngfix needs libpng with a zlib >=1.2.4 (not 0x%x)\n"", +- PNG_ZLIB_VERNUM); ++ ZLIB_VERNUM); + return 77; + } +-#endif /* PNG_ZLIB_VERNUM */ ++#endif /* ZLIB_VERNUM */ + + #else /* No read support */ + + int + main(void) + { +- fprintf(stderr, ""pngfix does not work without read support\n""); ++ fprintf(stderr, ""pngfix does not work without read deinterlace support\n""); + return 77; + } + #endif /* PNG_READ_SUPPORTED && PNG_EASY_ACCESS_SUPPORTED */ ++#else /* No setjmp support */ ++int ++main(void) ++{ ++ fprintf(stderr, ""pngfix does not work without setjmp support\n""); ++ return 77; ++} ++#endif /* PNG_SETJMP_SUPPORTED */ ++ +",700,1031,2048 +2846,"static void seq_chn_common_event(unsigned char *event_rec) +{ + unsigned char dev = event_rec[1]; + unsigned char cmd = event_rec[2]; + unsigned char chn = event_rec[3]; + unsigned char p1 = event_rec[4]; + + /* unsigned char p2 = event_rec[5]; */ + unsigned short w14 = *(short *) &event_rec[6]; + + if ((int) dev > max_synthdev || synth_devs[dev] == NULL) + return; + if (!(synth_open_mask & (1 << dev))) + return; + if (!synth_devs[dev]) + return; + + switch (cmd) + { + case MIDI_PGM_CHANGE: + if (seq_mode == SEQ_2) + { + synth_devs[dev]->chn_info[chn].pgm_num = p1; + if ((int) dev >= num_synths) + synth_devs[dev]->set_instr(dev, chn, p1); + } + else + synth_devs[dev]->set_instr(dev, chn, p1); + + break; + + case MIDI_CTL_CHANGE: + if (seq_mode == SEQ_2) + { + if (chn > 15 || p1 > 127) + break; + + synth_devs[dev]->chn_info[chn].controllers[p1] = w14 & 0x7f; + + if (p1 < 32) /* Setting MSB should clear LSB to 0 */ + synth_devs[dev]->chn_info[chn].controllers[p1 + 32] = 0; + + if ((int) dev < num_synths) + { + int val = w14 & 0x7f; + int i, key; + + if (p1 < 64) /* Combine MSB and LSB */ + { + val = ((synth_devs[dev]-> + chn_info[chn].controllers[p1 & ~32] & 0x7f) << 7) + | (synth_devs[dev]-> + chn_info[chn].controllers[p1 | 32] & 0x7f); + p1 &= ~32; + } + /* Handle all playing notes on this channel */ + + key = ((int) chn << 8); + + for (i = 0; i < synth_devs[dev]->alloc.max_voice; i++) + if ((synth_devs[dev]->alloc.map[i] & 0xff00) == key) + synth_devs[dev]->controller(dev, i, p1, val); + } + else + synth_devs[dev]->controller(dev, chn, p1, w14); + } + else /* Mode 1 */ + synth_devs[dev]->controller(dev, chn, p1, w14); + break; + + case MIDI_PITCH_BEND: + if (seq_mode == SEQ_2) + { + synth_devs[dev]->chn_info[chn].bender_value = w14; + + if ((int) dev < num_synths) + { + /* Handle all playing notes on this channel */ + int i, key; + + key = (chn << 8); + + for (i = 0; i < synth_devs[dev]->alloc.max_voice; i++) + if ((synth_devs[dev]->alloc.map[i] & 0xff00) == key) + synth_devs[dev]->bender(dev, i, w14); + } + else + synth_devs[dev]->bender(dev, chn, w14); + } + else /* MODE 1 */ + synth_devs[dev]->bender(dev, chn, w14); + break; + + default:; + } +} +",0,"static void seq_chn_common_event(unsigned char *event_rec) +{ + unsigned char dev = event_rec[1]; + unsigned char cmd = event_rec[2]; + unsigned char chn = event_rec[3]; + unsigned char p1 = event_rec[4]; + + /* unsigned char p2 = event_rec[5]; */ + unsigned short w14 = *(short *) &event_rec[6]; + + if ((int) dev > max_synthdev || synth_devs[dev] == NULL) + return; + if (!(synth_open_mask & (1 << dev))) + return; + if (!synth_devs[dev]) + return; + + switch (cmd) + { + case MIDI_PGM_CHANGE: + if (seq_mode == SEQ_2) + { + synth_devs[dev]->chn_info[chn].pgm_num = p1; + if ((int) dev >= num_synths) + synth_devs[dev]->set_instr(dev, chn, p1); + } + else + synth_devs[dev]->set_instr(dev, chn, p1); + + break; + + case MIDI_CTL_CHANGE: + if (seq_mode == SEQ_2) + { + if (chn > 15 || p1 > 127) + break; + + synth_devs[dev]->chn_info[chn].controllers[p1] = w14 & 0x7f; + + if (p1 < 32) /* Setting MSB should clear LSB to 0 */ + synth_devs[dev]->chn_info[chn].controllers[p1 + 32] = 0; + + if ((int) dev < num_synths) + { + int val = w14 & 0x7f; + int i, key; + + if (p1 < 64) /* Combine MSB and LSB */ + { + val = ((synth_devs[dev]-> + chn_info[chn].controllers[p1 & ~32] & 0x7f) << 7) + | (synth_devs[dev]-> + chn_info[chn].controllers[p1 | 32] & 0x7f); + p1 &= ~32; + } + /* Handle all playing notes on this channel */ + + key = ((int) chn << 8); + + for (i = 0; i < synth_devs[dev]->alloc.max_voice; i++) + if ((synth_devs[dev]->alloc.map[i] & 0xff00) == key) + synth_devs[dev]->controller(dev, i, p1, val); + } + else + synth_devs[dev]->controller(dev, chn, p1, w14); + } + else /* Mode 1 */ + synth_devs[dev]->controller(dev, chn, p1, w14); + break; + + case MIDI_PITCH_BEND: + if (seq_mode == SEQ_2) + { + synth_devs[dev]->chn_info[chn].bender_value = w14; + + if ((int) dev < num_synths) + { + /* Handle all playing notes on this channel */ + int i, key; + + key = (chn << 8); + + for (i = 0; i < synth_devs[dev]->alloc.max_voice; i++) + if ((synth_devs[dev]->alloc.map[i] & 0xff00) == key) + synth_devs[dev]->bender(dev, i, w14); + } + else + synth_devs[dev]->bender(dev, chn, w14); + } + else /* MODE 1 */ + synth_devs[dev]->bender(dev, chn, w14); + break; + + default:; + } +} +","@@ -241,7 +241,7 @@ int sequencer_write(int dev, struct file *file, const char __user *buf, int coun + return -ENXIO; + + fmt = (*(short *) &event_rec[0]) & 0xffff; +- err = synth_devs[dev]->load_patch(dev, fmt, buf, p + 4, c, 0); ++ err = synth_devs[dev]->load_patch(dev, fmt, buf + p, c, 0); + if (err < 0) + return err; + ",844,1175,2048 +18083,"long keyctl_chown_key(key_serial_t id, uid_t user, gid_t group) +{ + struct key_user *newowner, *zapowner = NULL; + struct key *key; + key_ref_t key_ref; + long ret; + kuid_t uid; + kgid_t gid; + + uid = make_kuid(current_user_ns(), user); + gid = make_kgid(current_user_ns(), group); + ret = -EINVAL; + if ((user != (uid_t) -1) && !uid_valid(uid)) + goto error; + if ((group != (gid_t) -1) && !gid_valid(gid)) + goto error; + + ret = 0; + if (user == (uid_t) -1 && group == (gid_t) -1) + goto error; + + key_ref = lookup_user_key(id, KEY_LOOKUP_CREATE | KEY_LOOKUP_PARTIAL, + KEY_NEED_SETATTR); + if (IS_ERR(key_ref)) { + ret = PTR_ERR(key_ref); + goto error; + } + + key = key_ref_to_ptr(key_ref); + + /* make the changes with the locks held to prevent chown/chown races */ + ret = -EACCES; + down_write(&key->sem); + + if (!capable(CAP_SYS_ADMIN)) { + /* only the sysadmin can chown a key to some other UID */ + if (user != (uid_t) -1 && !uid_eq(key->uid, uid)) + goto error_put; + + /* only the sysadmin can set the key's GID to a group other + * than one of those that the current process subscribes to */ + if (group != (gid_t) -1 && !gid_eq(gid, key->gid) && !in_group_p(gid)) + goto error_put; + } + + /* change the UID */ + if (user != (uid_t) -1 && !uid_eq(uid, key->uid)) { + ret = -ENOMEM; + newowner = key_user_lookup(uid); + if (!newowner) + goto error_put; + + /* transfer the quota burden to the new user */ + if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) { + unsigned maxkeys = uid_eq(uid, GLOBAL_ROOT_UID) ? + key_quota_root_maxkeys : key_quota_maxkeys; + unsigned maxbytes = uid_eq(uid, GLOBAL_ROOT_UID) ? + key_quota_root_maxbytes : key_quota_maxbytes; + + spin_lock(&newowner->lock); + if (newowner->qnkeys + 1 >= maxkeys || + newowner->qnbytes + key->quotalen >= maxbytes || + newowner->qnbytes + key->quotalen < + newowner->qnbytes) + goto quota_overrun; + + newowner->qnkeys++; + newowner->qnbytes += key->quotalen; + spin_unlock(&newowner->lock); + + spin_lock(&key->user->lock); + key->user->qnkeys--; + key->user->qnbytes -= key->quotalen; + spin_unlock(&key->user->lock); + } + + atomic_dec(&key->user->nkeys); + atomic_inc(&newowner->nkeys); + + if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) { + atomic_dec(&key->user->nikeys); + atomic_inc(&newowner->nikeys); + } + + zapowner = key->user; + key->user = newowner; + key->uid = uid; + } + + /* change the GID */ + if (group != (gid_t) -1) + key->gid = gid; + + ret = 0; + +error_put: + up_write(&key->sem); + key_put(key); + if (zapowner) + key_user_put(zapowner); +error: + return ret; + +quota_overrun: + spin_unlock(&newowner->lock); + zapowner = newowner; + ret = -EDQUOT; + goto error_put; +} +",1,"long keyctl_chown_key(key_serial_t id, uid_t user, gid_t group) +{ + struct key_user *newowner, *zapowner = NULL; + struct key *key; + key_ref_t key_ref; + long ret; + kuid_t uid; + kgid_t gid; + + uid = make_kuid(current_user_ns(), user); + gid = make_kgid(current_user_ns(), group); + ret = -EINVAL; + if ((user != (uid_t) -1) && !uid_valid(uid)) + goto error; + if ((group != (gid_t) -1) && !gid_valid(gid)) + goto error; + + ret = 0; + if (user == (uid_t) -1 && group == (gid_t) -1) + goto error; + + key_ref = lookup_user_key(id, KEY_LOOKUP_CREATE | KEY_LOOKUP_PARTIAL, + KEY_NEED_SETATTR); + if (IS_ERR(key_ref)) { + ret = PTR_ERR(key_ref); + goto error; + } + + key = key_ref_to_ptr(key_ref); + + /* make the changes with the locks held to prevent chown/chown races */ + ret = -EACCES; + down_write(&key->sem); + + if (!capable(CAP_SYS_ADMIN)) { + /* only the sysadmin can chown a key to some other UID */ + if (user != (uid_t) -1 && !uid_eq(key->uid, uid)) + goto error_put; + + /* only the sysadmin can set the key's GID to a group other + * than one of those that the current process subscribes to */ + if (group != (gid_t) -1 && !gid_eq(gid, key->gid) && !in_group_p(gid)) + goto error_put; + } + + /* change the UID */ + if (user != (uid_t) -1 && !uid_eq(uid, key->uid)) { + ret = -ENOMEM; + newowner = key_user_lookup(uid); + if (!newowner) + goto error_put; + + /* transfer the quota burden to the new user */ + if (test_bit(KEY_FLAG_IN_QUOTA, &key->flags)) { + unsigned maxkeys = uid_eq(uid, GLOBAL_ROOT_UID) ? + key_quota_root_maxkeys : key_quota_maxkeys; + unsigned maxbytes = uid_eq(uid, GLOBAL_ROOT_UID) ? + key_quota_root_maxbytes : key_quota_maxbytes; + + spin_lock(&newowner->lock); + if (newowner->qnkeys + 1 >= maxkeys || + newowner->qnbytes + key->quotalen >= maxbytes || + newowner->qnbytes + key->quotalen < + newowner->qnbytes) + goto quota_overrun; + + newowner->qnkeys++; + newowner->qnbytes += key->quotalen; + spin_unlock(&newowner->lock); + + spin_lock(&key->user->lock); + key->user->qnkeys--; + key->user->qnbytes -= key->quotalen; + spin_unlock(&key->user->lock); + } + + atomic_dec(&key->user->nkeys); + atomic_inc(&newowner->nkeys); + + if (key->state != KEY_IS_UNINSTANTIATED) { + atomic_dec(&key->user->nikeys); + atomic_inc(&newowner->nikeys); + } + + zapowner = key->user; + key->user = newowner; + key->uid = uid; + } + + /* change the GID */ + if (group != (gid_t) -1) + key->gid = gid; + + ret = 0; + +error_put: + up_write(&key->sem); + key_put(key); + if (zapowner) + key_user_put(zapowner); +error: + return ret; + +quota_overrun: + spin_unlock(&newowner->lock); + zapowner = newowner; + ret = -EDQUOT; + goto error_put; +} +","@@ -766,10 +766,9 @@ long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen) + + key = key_ref_to_ptr(key_ref); + +- if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) { +- ret = -ENOKEY; +- goto error2; +- } ++ ret = key_read_state(key); ++ if (ret < 0) ++ goto error2; /* Negatively instantiated */ + + /* see if we can read it directly */ + ret = key_permission(key_ref, KEY_NEED_READ); +@@ -901,7 +900,7 @@ long keyctl_chown_key(key_serial_t id, uid_t user, gid_t group) + atomic_dec(&key->user->nkeys); + atomic_inc(&newowner->nkeys); + +- if (test_bit(KEY_FLAG_INSTANTIATED, &key->flags)) { ++ if (key->state != KEY_IS_UNINSTANTIATED) { + atomic_dec(&key->user->nikeys); + atomic_inc(&newowner->nikeys); + }",825,1156,2048 +4121,"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; + + 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)); + } + } + + if (skb->ip_summed == CHECKSUM_PARTIAL) + status |= TP_STATUS_CSUMNOTREADY; + + snaplen = skb->len; + + res = run_filter(skb, sk, snaplen); + if (!res) + goto drop_n_restore; + 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; + 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; + } + } + spin_lock(&sk->sk_receive_queue.lock); + h.raw = packet_current_rx_frame(po, skb, + TP_STATUS_KERNEL, (macoff+snaplen)); + if (!h.raw) + goto ring_is_full; + 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); + + 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 (vlan_tx_tag_present(skb)) { + h.h2->tp_vlan_tci = vlan_tx_tag_get(skb); + status |= TP_STATUS_VLAN_VALID; + } else { + h.h2->tp_vlan_tci = 0; + } + h.h2->tp_padding = 0; + 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; + 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 + { + u8 *start, *end; + + if (po->tp_version <= TPACKET_V2) { + 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); + else + prb_clear_blk_fill_status(&po->rx_ring); + + sk->sk_data_ready(sk, 0); + +drop_n_restore: + if (skb_head != skb->data && skb_shared(skb)) { + skb->data = skb_head; + skb->len = skb_len; + } +drop: + kfree_skb(skb); + return 0; + +ring_is_full: + po->stats.stats1.tp_drops++; + spin_unlock(&sk->sk_receive_queue.lock); + + sk->sk_data_ready(sk, 0); + kfree_skb(copy_skb); + goto drop_n_restore; +} +",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; + + 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)); + } + } + + if (skb->ip_summed == CHECKSUM_PARTIAL) + status |= TP_STATUS_CSUMNOTREADY; + + snaplen = skb->len; + + res = run_filter(skb, sk, snaplen); + if (!res) + goto drop_n_restore; + 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; + 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; + } + } + spin_lock(&sk->sk_receive_queue.lock); + h.raw = packet_current_rx_frame(po, skb, + TP_STATUS_KERNEL, (macoff+snaplen)); + if (!h.raw) + goto ring_is_full; + 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); + + 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 (vlan_tx_tag_present(skb)) { + h.h2->tp_vlan_tci = vlan_tx_tag_get(skb); + status |= TP_STATUS_VLAN_VALID; + } else { + h.h2->tp_vlan_tci = 0; + } + h.h2->tp_padding = 0; + 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; + 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 + { + u8 *start, *end; + + if (po->tp_version <= TPACKET_V2) { + 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); + else + prb_clear_blk_fill_status(&po->rx_ring); + + sk->sk_data_ready(sk, 0); + +drop_n_restore: + if (skb_head != skb->data && skb_shared(skb)) { + skb->data = skb_head; + skb->len = skb_len; + } +drop: + kfree_skb(skb); + return 0; + +ring_is_full: + po->stats.stats1.tp_drops++; + spin_unlock(&sk->sk_receive_queue.lock); + + sk->sk_data_ready(sk, 0); + kfree_skb(copy_skb); + goto drop_n_restore; +} +","@@ -2660,7 +2660,6 @@ static int packet_recvmsg(struct kiocb *iocb, struct socket *sock, + struct sock *sk = sock->sk; + struct sk_buff *skb; + int copied, err; +- struct sockaddr_ll *sll; + int vnet_hdr_len = 0; + + err = -EINVAL; +@@ -2744,22 +2743,10 @@ static int packet_recvmsg(struct kiocb *iocb, struct socket *sock, + goto out_free; + } + +- /* +- * If the address length field is there to be filled in, we fill +- * it in now. +- */ +- +- sll = &PACKET_SKB_CB(skb)->sa.ll; +- if (sock->type == SOCK_PACKET) +- msg->msg_namelen = sizeof(struct sockaddr_pkt); +- else +- msg->msg_namelen = sll->sll_halen + offsetof(struct sockaddr_ll, sll_addr); +- +- /* +- * You lose any data beyond the buffer you gave. If it worries a +- * user program they can ask the device for its MTU anyway. ++ /* 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; +@@ -2772,9 +2759,20 @@ static int packet_recvmsg(struct kiocb *iocb, struct socket *sock, + + sock_recv_ts_and_drops(msg, sk, skb); + +- if (msg->msg_name) ++ 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) { ++ 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;",1612,1943,2048 +17863,"jbig2_parse_segment_header(Jbig2Ctx *ctx, uint8_t *buf, size_t buf_size, size_t *p_header_size) +{ + Jbig2Segment *result; + uint8_t rtscarf; + uint32_t rtscarf_long; + uint32_t *referred_to_segments; + int referred_to_segment_count; + int referred_to_segment_size; + int pa_size; + int offset; + + /* minimum possible size of a jbig2 segment header */ + if (buf_size < 11) + return NULL; + + result = jbig2_new(ctx, Jbig2Segment, 1); + if (result == NULL) { + jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, ""failed to allocate segment in jbig2_parse_segment_header""); + return result; + } + + /* 7.2.2 */ + result->number = jbig2_get_uint32(buf); + + /* 7.2.3 */ + result->flags = buf[4]; + + /* 7.2.4 referred-to segments */ + rtscarf = buf[5]; + if ((rtscarf & 0xe0) == 0xe0) { + rtscarf_long = jbig2_get_uint32(buf + 5); + referred_to_segment_count = rtscarf_long & 0x1fffffff; + offset = 5 + 4 + (referred_to_segment_count + 1) / 8; + } else { + referred_to_segment_count = (rtscarf >> 5); + offset = 5 + 1; + } + result->referred_to_segment_count = referred_to_segment_count; + + /* we now have enough information to compute the full header length */ + referred_to_segment_size = result->number <= 256 ? 1 : result->number <= 65536 ? 2 : 4; /* 7.2.5 */ + pa_size = result->flags & 0x40 ? 4 : 1; /* 7.2.6 */ + if (offset + referred_to_segment_count * referred_to_segment_size + pa_size + 4 > buf_size) { + jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, result->number, ""jbig2_parse_segment_header() called with insufficient data"", -1); + jbig2_free(ctx->allocator, result); + return NULL; + } + + /* 7.2.5 */ + if (referred_to_segment_count) { + int i; + + referred_to_segments = jbig2_new(ctx, uint32_t, referred_to_segment_count * referred_to_segment_size); + if (referred_to_segments == NULL) { + jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, ""could not allocate referred_to_segments "" ""in jbig2_parse_segment_header""); + return NULL; + } + + for (i = 0; i < referred_to_segment_count; i++) { + referred_to_segments[i] = + (referred_to_segment_size == 1) ? buf[offset] : + (referred_to_segment_size == 2) ? jbig2_get_uint16(buf + offset) : jbig2_get_uint32(buf + offset); + offset += referred_to_segment_size; + jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, result->number, ""segment %d refers to segment %d"", result->number, referred_to_segments[i]); + } + result->referred_to_segments = referred_to_segments; + } else { /* no referred-to segments */ + + result->referred_to_segments = NULL; + } + + /* 7.2.6 */ + if (result->flags & 0x40) { + result->page_association = jbig2_get_uint32(buf + offset); + offset += 4; + } else { + result->page_association = buf[offset++]; + } + jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, result->number, ""segment %d is associated with page %d"", result->number, result->page_association); + + /* 7.2.7 */ + result->data_length = jbig2_get_uint32(buf + offset); + *p_header_size = offset + 4; + + /* no body parsing results yet */ + result->result = NULL; + + return result; +} +",1,"jbig2_parse_segment_header(Jbig2Ctx *ctx, uint8_t *buf, size_t buf_size, size_t *p_header_size) +{ + Jbig2Segment *result; + uint8_t rtscarf; + uint32_t rtscarf_long; + uint32_t *referred_to_segments; + uint32_t referred_to_segment_count; + uint32_t referred_to_segment_size; + uint32_t pa_size; + uint32_t offset; + + /* minimum possible size of a jbig2 segment header */ + if (buf_size < 11) + return NULL; + + result = jbig2_new(ctx, Jbig2Segment, 1); + if (result == NULL) { + jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, ""failed to allocate segment in jbig2_parse_segment_header""); + return result; + } + + /* 7.2.2 */ + result->number = jbig2_get_uint32(buf); + + /* 7.2.3 */ + result->flags = buf[4]; + + /* 7.2.4 referred-to segments */ + rtscarf = buf[5]; + if ((rtscarf & 0xe0) == 0xe0) { + rtscarf_long = jbig2_get_uint32(buf + 5); + referred_to_segment_count = rtscarf_long & 0x1fffffff; + offset = 5 + 4 + (referred_to_segment_count + 1) / 8; + } else { + referred_to_segment_count = (rtscarf >> 5); + offset = 5 + 1; + } + result->referred_to_segment_count = referred_to_segment_count; + + /* we now have enough information to compute the full header length */ + referred_to_segment_size = result->number <= 256 ? 1 : result->number <= 65536 ? 2 : 4; /* 7.2.5 */ + pa_size = result->flags & 0x40 ? 4 : 1; /* 7.2.6 */ + if (offset + referred_to_segment_count * referred_to_segment_size + pa_size + 4 > buf_size) { + jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, result->number, ""jbig2_parse_segment_header() called with insufficient data"", -1); + jbig2_free(ctx->allocator, result); + return NULL; + } + + /* 7.2.5 */ + if (referred_to_segment_count) { + uint32_t i; + + referred_to_segments = jbig2_new(ctx, uint32_t, referred_to_segment_count * referred_to_segment_size); + if (referred_to_segments == NULL) { + jbig2_error(ctx, JBIG2_SEVERITY_FATAL, -1, ""could not allocate referred_to_segments "" ""in jbig2_parse_segment_header""); + return NULL; + } + + for (i = 0; i < referred_to_segment_count; i++) { + referred_to_segments[i] = + (referred_to_segment_size == 1) ? buf[offset] : + (referred_to_segment_size == 2) ? jbig2_get_uint16(buf + offset) : jbig2_get_uint32(buf + offset); + offset += referred_to_segment_size; + jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, result->number, ""segment %d refers to segment %d"", result->number, referred_to_segments[i]); + } + result->referred_to_segments = referred_to_segments; + } else { /* no referred-to segments */ + + result->referred_to_segments = NULL; + } + + /* 7.2.6 */ + if (result->flags & 0x40) { + result->page_association = jbig2_get_uint32(buf + offset); + offset += 4; + } else { + result->page_association = buf[offset++]; + } + jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, result->number, ""segment %d is associated with page %d"", result->number, result->page_association); + + /* 7.2.7 */ + result->data_length = jbig2_get_uint32(buf + offset); + *p_header_size = offset + 4; + + /* no body parsing results yet */ + result->result = NULL; + + return result; +} +","@@ -39,10 +39,10 @@ jbig2_parse_segment_header(Jbig2Ctx *ctx, uint8_t *buf, size_t buf_size, size_t + uint8_t rtscarf; + uint32_t rtscarf_long; + uint32_t *referred_to_segments; +- int referred_to_segment_count; +- int referred_to_segment_size; +- int pa_size; +- int offset; ++ uint32_t referred_to_segment_count; ++ uint32_t referred_to_segment_size; ++ uint32_t pa_size; ++ uint32_t offset; + + /* minimum possible size of a jbig2 segment header */ + if (buf_size < 11) +@@ -83,7 +83,7 @@ jbig2_parse_segment_header(Jbig2Ctx *ctx, uint8_t *buf, size_t buf_size, size_t + + /* 7.2.5 */ + if (referred_to_segment_count) { +- int i; ++ uint32_t i; + + referred_to_segments = jbig2_new(ctx, uint32_t, referred_to_segment_count * referred_to_segment_size); + if (referred_to_segments == NULL) {",951,1282,2048 +4168,"static void tcp_rtt_estimator(struct sock *sk, const __u32 mrtt) +{ + struct tcp_sock *tp = tcp_sk(sk); + long m = mrtt; /* RTT */ + + /* The following amusing code comes from Jacobson's + * article in SIGCOMM '88. Note that rtt and mdev + * are scaled versions of rtt and mean deviation. + * This is designed to be as fast as possible + * m stands for ""measurement"". + * + * On a 1990 paper the rto value is changed to: + * RTO = rtt + 4 * mdev + * + * Funny. This algorithm seems to be very broken. + * These formulae increase RTO, when it should be decreased, increase + * too slowly, when it should be increased quickly, decrease too quickly + * etc. I guess in BSD RTO takes ONE value, so that it is absolutely + * does not matter how to _calculate_ it. Seems, it was trap + * that VJ failed to avoid. 8) + */ + if (m == 0) + m = 1; + if (tp->srtt != 0) { + m -= (tp->srtt >> 3); /* m is now error in rtt est */ + tp->srtt += m; /* rtt = 7/8 rtt + 1/8 new */ + if (m < 0) { + m = -m; /* m is now abs(error) */ + m -= (tp->mdev >> 2); /* similar update on mdev */ + /* This is similar to one of Eifel findings. + * Eifel blocks mdev updates when rtt decreases. + * This solution is a bit different: we use finer gain + * for mdev in this case (alpha*beta). + * Like Eifel it also prevents growth of rto, + * but also it limits too fast rto decreases, + * happening in pure Eifel. + */ + if (m > 0) + m >>= 3; + } else { + m -= (tp->mdev >> 2); /* similar update on mdev */ + } + tp->mdev += m; /* mdev = 3/4 mdev + 1/4 new */ + if (tp->mdev > tp->mdev_max) { + tp->mdev_max = tp->mdev; + if (tp->mdev_max > tp->rttvar) + tp->rttvar = tp->mdev_max; + } + if (after(tp->snd_una, tp->rtt_seq)) { + if (tp->mdev_max < tp->rttvar) + tp->rttvar -= (tp->rttvar - tp->mdev_max) >> 2; + tp->rtt_seq = tp->snd_nxt; + tp->mdev_max = tcp_rto_min(sk); + } + } else { + /* no previous measure. */ + tp->srtt = m << 3; /* take the measured time to be rtt */ + tp->mdev = m << 1; /* make sure rto = 3*rtt */ + tp->mdev_max = tp->rttvar = max(tp->mdev, tcp_rto_min(sk)); + tp->rtt_seq = tp->snd_nxt; + } +} +",0,"static void tcp_rtt_estimator(struct sock *sk, const __u32 mrtt) +{ + struct tcp_sock *tp = tcp_sk(sk); + long m = mrtt; /* RTT */ + + /* The following amusing code comes from Jacobson's + * article in SIGCOMM '88. Note that rtt and mdev + * are scaled versions of rtt and mean deviation. + * This is designed to be as fast as possible + * m stands for ""measurement"". + * + * On a 1990 paper the rto value is changed to: + * RTO = rtt + 4 * mdev + * + * Funny. This algorithm seems to be very broken. + * These formulae increase RTO, when it should be decreased, increase + * too slowly, when it should be increased quickly, decrease too quickly + * etc. I guess in BSD RTO takes ONE value, so that it is absolutely + * does not matter how to _calculate_ it. Seems, it was trap + * that VJ failed to avoid. 8) + */ + if (m == 0) + m = 1; + if (tp->srtt != 0) { + m -= (tp->srtt >> 3); /* m is now error in rtt est */ + tp->srtt += m; /* rtt = 7/8 rtt + 1/8 new */ + if (m < 0) { + m = -m; /* m is now abs(error) */ + m -= (tp->mdev >> 2); /* similar update on mdev */ + /* This is similar to one of Eifel findings. + * Eifel blocks mdev updates when rtt decreases. + * This solution is a bit different: we use finer gain + * for mdev in this case (alpha*beta). + * Like Eifel it also prevents growth of rto, + * but also it limits too fast rto decreases, + * happening in pure Eifel. + */ + if (m > 0) + m >>= 3; + } else { + m -= (tp->mdev >> 2); /* similar update on mdev */ + } + tp->mdev += m; /* mdev = 3/4 mdev + 1/4 new */ + if (tp->mdev > tp->mdev_max) { + tp->mdev_max = tp->mdev; + if (tp->mdev_max > tp->rttvar) + tp->rttvar = tp->mdev_max; + } + if (after(tp->snd_una, tp->rtt_seq)) { + if (tp->mdev_max < tp->rttvar) + tp->rttvar -= (tp->rttvar - tp->mdev_max) >> 2; + tp->rtt_seq = tp->snd_nxt; + tp->mdev_max = tcp_rto_min(sk); + } + } else { + /* no previous measure. */ + tp->srtt = m << 3; /* take the measured time to be rtt */ + tp->mdev = m << 1; /* make sure rto = 3*rtt */ + tp->mdev_max = tp->rttvar = max(tp->mdev, tcp_rto_min(sk)); + tp->rtt_seq = tp->snd_nxt; + } +} +","@@ -5811,6 +5811,8 @@ int tcp_rcv_state_process(struct sock *sk, struct sk_buff *skb, + goto discard; + + if (th->syn) { ++ if (th->fin) ++ goto discard; + if (icsk->icsk_af_ops->conn_request(sk, skb) < 0) + return 1; + ",767,1098,2048 +1261,"_gnutls_compressed2ciphertext (gnutls_session_t session, + opaque * cipher_data, int cipher_size, + gnutls_datum_t compressed, + content_type_t _type, int random_pad) +{ + uint8_t MAC[MAX_HASH_SIZE]; + uint16_t c_length; + uint8_t pad; + int length, ret; + digest_hd_st td; + uint8_t type = _type; + uint8_t major, minor; + int hash_size = + _gnutls_hash_get_algo_len (session->security_parameters. + write_mac_algorithm); + gnutls_protocol_t ver; + int blocksize = + _gnutls_cipher_get_block_size (session->security_parameters. + write_bulk_cipher_algorithm); + cipher_type_t block_algo = + _gnutls_cipher_is_block (session->security_parameters. + write_bulk_cipher_algorithm); + opaque *data_ptr; + + + ver = gnutls_protocol_get_version (session); + minor = _gnutls_version_get_minor (ver); + major = _gnutls_version_get_major (ver); + + + /* Initialize MAC */ + ret = mac_init (&td, session->security_parameters.write_mac_algorithm, + session->connection_state.write_mac_secret.data, + session->connection_state.write_mac_secret.size, ver); + + if (ret < 0 && session->security_parameters.write_mac_algorithm != GNUTLS_MAC_NULL) + { + gnutls_assert (); + return ret; + } + + c_length = _gnutls_conv_uint16 (compressed.size); + + if (session->security_parameters.write_mac_algorithm != GNUTLS_MAC_NULL) + { /* actually when the algorithm in not the NULL one */ + _gnutls_hmac (&td, + UINT64DATA (session->connection_state. + write_sequence_number), 8); + + _gnutls_hmac (&td, &type, 1); + if (ver >= GNUTLS_TLS1) + { /* TLS 1.0 or higher */ + _gnutls_hmac (&td, &major, 1); + _gnutls_hmac (&td, &minor, 1); + } + _gnutls_hmac (&td, &c_length, 2); + _gnutls_hmac (&td, compressed.data, compressed.size); + mac_deinit (&td, MAC, ver); + } + + + /* Calculate the encrypted length (padding etc.) + */ + length = + calc_enc_length (session, compressed.size, hash_size, &pad, + random_pad, block_algo, blocksize); + if (length < 0) + { + gnutls_assert (); + return length; + } + + /* copy the encrypted data to cipher_data. + */ + if (cipher_size < length) + { + gnutls_assert (); + return GNUTLS_E_MEMORY_ERROR; + } + + data_ptr = cipher_data; + if (block_algo == CIPHER_BLOCK && + session->security_parameters.version >= GNUTLS_TLS1_1) + { + /* copy the random IV. + */ + ret = _gnutls_rnd (RND_NONCE, data_ptr, blocksize); + if (ret < 0) + { + gnutls_assert (); + return ret; + } + + data_ptr += blocksize; + } + + memcpy (data_ptr, compressed.data, compressed.size); + data_ptr += compressed.size; + + if (hash_size > 0) + { + memcpy (data_ptr, MAC, hash_size); + data_ptr += hash_size; + } + if (block_algo == CIPHER_BLOCK && pad > 0) + { + memset (data_ptr, pad - 1, pad); + } + + + /* Actual encryption (inplace). + */ + ret = _gnutls_cipher_encrypt (&session->connection_state. + write_cipher_state, cipher_data, length); + if (ret < 0) + { + gnutls_assert (); + return ret; + } + + return length; +} +",0,"_gnutls_compressed2ciphertext (gnutls_session_t session, + opaque * cipher_data, int cipher_size, + gnutls_datum_t compressed, + content_type_t _type, int random_pad) +{ + uint8_t MAC[MAX_HASH_SIZE]; + uint16_t c_length; + uint8_t pad; + int length, ret; + digest_hd_st td; + uint8_t type = _type; + uint8_t major, minor; + int hash_size = + _gnutls_hash_get_algo_len (session->security_parameters. + write_mac_algorithm); + gnutls_protocol_t ver; + int blocksize = + _gnutls_cipher_get_block_size (session->security_parameters. + write_bulk_cipher_algorithm); + cipher_type_t block_algo = + _gnutls_cipher_is_block (session->security_parameters. + write_bulk_cipher_algorithm); + opaque *data_ptr; + + + ver = gnutls_protocol_get_version (session); + minor = _gnutls_version_get_minor (ver); + major = _gnutls_version_get_major (ver); + + + /* Initialize MAC */ + ret = mac_init (&td, session->security_parameters.write_mac_algorithm, + session->connection_state.write_mac_secret.data, + session->connection_state.write_mac_secret.size, ver); + + if (ret < 0 && session->security_parameters.write_mac_algorithm != GNUTLS_MAC_NULL) + { + gnutls_assert (); + return ret; + } + + c_length = _gnutls_conv_uint16 (compressed.size); + + if (session->security_parameters.write_mac_algorithm != GNUTLS_MAC_NULL) + { /* actually when the algorithm in not the NULL one */ + _gnutls_hmac (&td, + UINT64DATA (session->connection_state. + write_sequence_number), 8); + + _gnutls_hmac (&td, &type, 1); + if (ver >= GNUTLS_TLS1) + { /* TLS 1.0 or higher */ + _gnutls_hmac (&td, &major, 1); + _gnutls_hmac (&td, &minor, 1); + } + _gnutls_hmac (&td, &c_length, 2); + _gnutls_hmac (&td, compressed.data, compressed.size); + mac_deinit (&td, MAC, ver); + } + + + /* Calculate the encrypted length (padding etc.) + */ + length = + calc_enc_length (session, compressed.size, hash_size, &pad, + random_pad, block_algo, blocksize); + if (length < 0) + { + gnutls_assert (); + return length; + } + + /* copy the encrypted data to cipher_data. + */ + if (cipher_size < length) + { + gnutls_assert (); + return GNUTLS_E_MEMORY_ERROR; + } + + data_ptr = cipher_data; + if (block_algo == CIPHER_BLOCK && + session->security_parameters.version >= GNUTLS_TLS1_1) + { + /* copy the random IV. + */ + ret = _gnutls_rnd (RND_NONCE, data_ptr, blocksize); + if (ret < 0) + { + gnutls_assert (); + return ret; + } + + data_ptr += blocksize; + } + + memcpy (data_ptr, compressed.data, compressed.size); + data_ptr += compressed.size; + + if (hash_size > 0) + { + memcpy (data_ptr, MAC, hash_size); + data_ptr += hash_size; + } + if (block_algo == CIPHER_BLOCK && pad > 0) + { + memset (data_ptr, pad - 1, pad); + } + + + /* Actual encryption (inplace). + */ + ret = _gnutls_cipher_encrypt (&session->connection_state. + write_cipher_state, cipher_data, length); + if (ret < 0) + { + gnutls_assert (); + return ret; + } + + return length; +} +","@@ -459,6 +459,14 @@ _gnutls_ciphertext2compressed (gnutls_session_t session, + return GNUTLS_E_INTERNAL_ERROR; + } + ++ if (ciphertext.size < (unsigned) blocksize + hash_size) ++ { ++ _gnutls_record_log ++ (""REC[%x]: Short record length %d < %d + %d (under attack?)\n"", ++ session, ciphertext.size, blocksize, hash_size); ++ gnutls_assert (); ++ return GNUTLS_E_DECRYPTION_FAILED; ++ } + + /* actual decryption (inplace) + */ +@@ -510,9 +518,7 @@ _gnutls_ciphertext2compressed (gnutls_session_t session, + + pad = ciphertext.data[ciphertext.size - 1] + 1; /* pad */ + +- length = ciphertext.size - hash_size - pad; +- +- if (pad > ciphertext.size - hash_size) ++ if ((int)pad > (int)ciphertext.size - hash_size) + { + gnutls_assert (); + /* We do not fail here. We check below for the +@@ -521,6 +527,8 @@ _gnutls_ciphertext2compressed (gnutls_session_t session, + pad_failed = GNUTLS_E_DECRYPTION_FAILED; + } + ++ length = ciphertext.size - hash_size - pad; ++ + /* Check the pading bytes (TLS 1.x) + */ + if (ver >= GNUTLS_TLS1 && pad_failed == 0)",846,1177,2048 +17,"SSL *php_SSL_new_from_context(SSL_CTX *ctx, php_stream *stream TSRMLS_DC) /* {{{ */ +{ + zval **val = NULL; + char *cafile = NULL; + char *capath = NULL; + char *certfile = NULL; + char *cipherlist = NULL; + int ok = 1; + + ERR_clear_error(); + + /* look at context options in the stream and set appropriate verification flags */ + if (GET_VER_OPT(""verify_peer"") && zval_is_true(*val)) { + + /* turn on verification callback */ + SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verify_callback); + + /* CA stuff */ + GET_VER_OPT_STRING(""cafile"", cafile); + GET_VER_OPT_STRING(""capath"", capath); + + if (cafile || capath) { + if (!SSL_CTX_load_verify_locations(ctx, cafile, capath)) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to set verify locations `%s' `%s'"", cafile, capath); + return NULL; + } + } + + if (GET_VER_OPT(""verify_depth"")) { + convert_to_long_ex(val); + SSL_CTX_set_verify_depth(ctx, Z_LVAL_PP(val)); + } + } else { + SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL); + } + + /* callback for the passphrase (for localcert) */ + if (GET_VER_OPT(""passphrase"")) { + SSL_CTX_set_default_passwd_cb_userdata(ctx, stream); + SSL_CTX_set_default_passwd_cb(ctx, passwd_callback); + } + + GET_VER_OPT_STRING(""ciphers"", cipherlist); + if (!cipherlist) { + cipherlist = ""DEFAULT""; + } + if (SSL_CTX_set_cipher_list(ctx, cipherlist) != 1) { + return NULL; + } + + GET_VER_OPT_STRING(""local_cert"", certfile); + if (certfile) { + X509 *cert = NULL; + EVP_PKEY *key = NULL; + SSL *tmpssl; + char resolved_path_buff[MAXPATHLEN]; + const char * private_key = NULL; + + if (VCWD_REALPATH(certfile, resolved_path_buff)) { + /* a certificate to use for authentication */ + if (SSL_CTX_use_certificate_chain_file(ctx, resolved_path_buff) != 1) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to set local cert chain file `%s'; Check that your cafile/capath settings include details of your certificate and its issuer"", certfile); + return NULL; + } + GET_VER_OPT_STRING(""local_pk"", private_key); + + if (private_key) { + char resolved_path_buff_pk[MAXPATHLEN]; + if (VCWD_REALPATH(private_key, resolved_path_buff_pk)) { + if (SSL_CTX_use_PrivateKey_file(ctx, resolved_path_buff_pk, SSL_FILETYPE_PEM) != 1) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to set private key file `%s'"", resolved_path_buff_pk); + return NULL; + } + } + } else { + if (SSL_CTX_use_PrivateKey_file(ctx, resolved_path_buff, SSL_FILETYPE_PEM) != 1) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to set private key file `%s'"", resolved_path_buff); + return NULL; + } + } + + tmpssl = SSL_new(ctx); + cert = SSL_get_certificate(tmpssl); + + if (cert) { + key = X509_get_pubkey(cert); + EVP_PKEY_copy_parameters(key, SSL_get_privatekey(tmpssl)); + EVP_PKEY_free(key); + } + SSL_free(tmpssl); + + if (!SSL_CTX_check_private_key(ctx)) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Private key does not match certificate!""); + } + } + } + if (ok) { + SSL *ssl = SSL_new(ctx); + + if (ssl) { + /* map SSL => stream */ + SSL_set_ex_data(ssl, ssl_stream_data_index, stream); + } + return ssl; + } + + return NULL; +} +/* }}} */ +",0,"SSL *php_SSL_new_from_context(SSL_CTX *ctx, php_stream *stream TSRMLS_DC) /* {{{ */ +{ + zval **val = NULL; + char *cafile = NULL; + char *capath = NULL; + char *certfile = NULL; + char *cipherlist = NULL; + int ok = 1; + + ERR_clear_error(); + + /* look at context options in the stream and set appropriate verification flags */ + if (GET_VER_OPT(""verify_peer"") && zval_is_true(*val)) { + + /* turn on verification callback */ + SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verify_callback); + + /* CA stuff */ + GET_VER_OPT_STRING(""cafile"", cafile); + GET_VER_OPT_STRING(""capath"", capath); + + if (cafile || capath) { + if (!SSL_CTX_load_verify_locations(ctx, cafile, capath)) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to set verify locations `%s' `%s'"", cafile, capath); + return NULL; + } + } + + if (GET_VER_OPT(""verify_depth"")) { + convert_to_long_ex(val); + SSL_CTX_set_verify_depth(ctx, Z_LVAL_PP(val)); + } + } else { + SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL); + } + + /* callback for the passphrase (for localcert) */ + if (GET_VER_OPT(""passphrase"")) { + SSL_CTX_set_default_passwd_cb_userdata(ctx, stream); + SSL_CTX_set_default_passwd_cb(ctx, passwd_callback); + } + + GET_VER_OPT_STRING(""ciphers"", cipherlist); + if (!cipherlist) { + cipherlist = ""DEFAULT""; + } + if (SSL_CTX_set_cipher_list(ctx, cipherlist) != 1) { + return NULL; + } + + GET_VER_OPT_STRING(""local_cert"", certfile); + if (certfile) { + X509 *cert = NULL; + EVP_PKEY *key = NULL; + SSL *tmpssl; + char resolved_path_buff[MAXPATHLEN]; + const char * private_key = NULL; + + if (VCWD_REALPATH(certfile, resolved_path_buff)) { + /* a certificate to use for authentication */ + if (SSL_CTX_use_certificate_chain_file(ctx, resolved_path_buff) != 1) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to set local cert chain file `%s'; Check that your cafile/capath settings include details of your certificate and its issuer"", certfile); + return NULL; + } + GET_VER_OPT_STRING(""local_pk"", private_key); + + if (private_key) { + char resolved_path_buff_pk[MAXPATHLEN]; + if (VCWD_REALPATH(private_key, resolved_path_buff_pk)) { + if (SSL_CTX_use_PrivateKey_file(ctx, resolved_path_buff_pk, SSL_FILETYPE_PEM) != 1) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to set private key file `%s'"", resolved_path_buff_pk); + return NULL; + } + } + } else { + if (SSL_CTX_use_PrivateKey_file(ctx, resolved_path_buff, SSL_FILETYPE_PEM) != 1) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to set private key file `%s'"", resolved_path_buff); + return NULL; + } + } + + tmpssl = SSL_new(ctx); + cert = SSL_get_certificate(tmpssl); + + if (cert) { + key = X509_get_pubkey(cert); + EVP_PKEY_copy_parameters(key, SSL_get_privatekey(tmpssl)); + EVP_PKEY_free(key); + } + SSL_free(tmpssl); + + if (!SSL_CTX_check_private_key(ctx)) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Private key does not match certificate!""); + } + } + } + if (ok) { + SSL *ssl = SSL_new(ctx); + + if (ssl) { + /* map SSL => stream */ + SSL_set_ex_data(ssl, ssl_stream_data_index, stream); + } + return ssl; + } + + return NULL; +} +/* }}} */ +","@@ -644,18 +644,28 @@ static time_t asn1_time_to_time_t(ASN1_UTCTIME * timestr TSRMLS_DC) /* {{{ */ + char * thestr; + long gmadjust = 0; + +- if (timestr->length < 13) { +- php_error_docref(NULL TSRMLS_CC, E_WARNING, ""extension author too lazy to parse %s correctly"", timestr->data); ++ if (ASN1_STRING_type(timestr) != V_ASN1_UTCTIME) { ++ php_error_docref(NULL TSRMLS_CC, E_WARNING, ""illegal ASN1 data type for timestamp""); + return (time_t)-1; + } + +- strbuf = estrdup((char *)timestr->data); ++ if (ASN1_STRING_length(timestr) != strlen(ASN1_STRING_data(timestr))) { ++ php_error_docref(NULL TSRMLS_CC, E_WARNING, ""illegal length in timestamp""); ++ return (time_t)-1; ++ } ++ ++ if (ASN1_STRING_length(timestr) < 13) { ++ php_error_docref(NULL TSRMLS_CC, E_WARNING, ""unable to parse time string %s correctly"", timestr->data); ++ return (time_t)-1; ++ } ++ ++ strbuf = estrdup((char *)ASN1_STRING_data(timestr)); + + memset(&thetime, 0, sizeof(thetime)); + + /* we work backwards so that we can use atoi more easily */ + +- thestr = strbuf + timestr->length - 3; ++ thestr = strbuf + ASN1_STRING_length(timestr) - 3; + + thetime.tm_sec = atoi(thestr); + *thestr = '\0';",895,1226,2048 +15914,"void GLES2DecoderImpl::DoTexStorage2DImageCHROMIUM(GLenum target, + GLenum internal_format, + GLenum buffer_usage, + GLsizei width, + GLsizei height) { + TRACE_EVENT2(""gpu"", ""GLES2DecoderImpl::DoTexStorage2DImageCHROMIUM"", ""width"", + width, ""height"", height); + + ScopedGLErrorSuppressor suppressor( + ""GLES2CmdDecoder::DoTexStorage2DImageCHROMIUM"", state_.GetErrorState()); + + if (!texture_manager()->ValidForTarget(target, 0, width, height, 1)) { + LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, ""glTexStorage2DImageCHROMIUM"", + ""dimensions out of range""); + return; + } + + TextureRef* texture_ref = + texture_manager()->GetTextureInfoForTarget(&state_, target); + if (!texture_ref) { + LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, ""glTexStorage2DImageCHROMIUM"", + ""unknown texture for target""); + return; + } + + Texture* texture = texture_ref->texture(); + if (texture->IsImmutable()) { + LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, ""glTexStorage2DImageCHROMIUM"", + ""texture is immutable""); + return; + } + + gfx::BufferFormat buffer_format; + GLint untyped_format; + switch (internal_format) { + case GL_RGBA8_OES: + buffer_format = gfx::BufferFormat::RGBA_8888; + untyped_format = GL_RGBA; + break; + case GL_BGRA8_EXT: + buffer_format = gfx::BufferFormat::BGRA_8888; + untyped_format = GL_BGRA_EXT; + break; + case GL_RGBA16F_EXT: + buffer_format = gfx::BufferFormat::RGBA_F16; + untyped_format = GL_RGBA; + break; + case GL_R8_EXT: + buffer_format = gfx::BufferFormat::R_8; + untyped_format = GL_RED_EXT; + break; + default: + LOCAL_SET_GL_ERROR(GL_INVALID_ENUM, ""glTexStorage2DImageCHROMIUM"", + ""Invalid buffer format""); + return; + } + + DCHECK_EQ(buffer_usage, static_cast(GL_SCANOUT_CHROMIUM)); + + if (!GetContextGroup()->image_factory()) { + LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, ""glTexStorage2DImageCHROMIUM"", + ""Cannot create GL image""); + return; + } + + bool is_cleared = false; + scoped_refptr image = + GetContextGroup()->image_factory()->CreateAnonymousImage( + gfx::Size(width, height), buffer_format, gfx::BufferUsage::SCANOUT, + untyped_format, &is_cleared); + if (!image || !image->BindTexImage(target)) { + LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, ""glTexStorage2DImageCHROMIUM"", + ""Failed to create or bind GL Image""); + return; + } + + gfx::Rect cleared_rect; + if (is_cleared) + cleared_rect = gfx::Rect(width, height); + + texture_manager()->SetLevelInfo( + texture_ref, target, 0, image->GetInternalFormat(), width, height, 1, 0, + image->GetInternalFormat(), GL_UNSIGNED_BYTE, cleared_rect); + texture_manager()->SetLevelImage(texture_ref, target, 0, image.get(), + Texture::BOUND); + + if (texture->IsAttachedToFramebuffer()) + framebuffer_state_.clear_state_dirty = true; + + texture->SetImmutable(true); +} +",0,"void GLES2DecoderImpl::DoTexStorage2DImageCHROMIUM(GLenum target, + GLenum internal_format, + GLenum buffer_usage, + GLsizei width, + GLsizei height) { + TRACE_EVENT2(""gpu"", ""GLES2DecoderImpl::DoTexStorage2DImageCHROMIUM"", ""width"", + width, ""height"", height); + + ScopedGLErrorSuppressor suppressor( + ""GLES2CmdDecoder::DoTexStorage2DImageCHROMIUM"", state_.GetErrorState()); + + if (!texture_manager()->ValidForTarget(target, 0, width, height, 1)) { + LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, ""glTexStorage2DImageCHROMIUM"", + ""dimensions out of range""); + return; + } + + TextureRef* texture_ref = + texture_manager()->GetTextureInfoForTarget(&state_, target); + if (!texture_ref) { + LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, ""glTexStorage2DImageCHROMIUM"", + ""unknown texture for target""); + return; + } + + Texture* texture = texture_ref->texture(); + if (texture->IsImmutable()) { + LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, ""glTexStorage2DImageCHROMIUM"", + ""texture is immutable""); + return; + } + + gfx::BufferFormat buffer_format; + GLint untyped_format; + switch (internal_format) { + case GL_RGBA8_OES: + buffer_format = gfx::BufferFormat::RGBA_8888; + untyped_format = GL_RGBA; + break; + case GL_BGRA8_EXT: + buffer_format = gfx::BufferFormat::BGRA_8888; + untyped_format = GL_BGRA_EXT; + break; + case GL_RGBA16F_EXT: + buffer_format = gfx::BufferFormat::RGBA_F16; + untyped_format = GL_RGBA; + break; + case GL_R8_EXT: + buffer_format = gfx::BufferFormat::R_8; + untyped_format = GL_RED_EXT; + break; + default: + LOCAL_SET_GL_ERROR(GL_INVALID_ENUM, ""glTexStorage2DImageCHROMIUM"", + ""Invalid buffer format""); + return; + } + + DCHECK_EQ(buffer_usage, static_cast(GL_SCANOUT_CHROMIUM)); + + if (!GetContextGroup()->image_factory()) { + LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, ""glTexStorage2DImageCHROMIUM"", + ""Cannot create GL image""); + return; + } + + bool is_cleared = false; + scoped_refptr image = + GetContextGroup()->image_factory()->CreateAnonymousImage( + gfx::Size(width, height), buffer_format, gfx::BufferUsage::SCANOUT, + untyped_format, &is_cleared); + if (!image || !image->BindTexImage(target)) { + LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, ""glTexStorage2DImageCHROMIUM"", + ""Failed to create or bind GL Image""); + return; + } + + gfx::Rect cleared_rect; + if (is_cleared) + cleared_rect = gfx::Rect(width, height); + + texture_manager()->SetLevelInfo( + texture_ref, target, 0, image->GetInternalFormat(), width, height, 1, 0, + image->GetInternalFormat(), GL_UNSIGNED_BYTE, cleared_rect); + texture_manager()->SetLevelImage(texture_ref, target, 0, image.get(), + Texture::BOUND); + + if (texture->IsAttachedToFramebuffer()) + framebuffer_state_.clear_state_dirty = true; + + texture->SetImmutable(true); +} +","@@ -11384,29 +11384,24 @@ void GLES2DecoderImpl::GetTexParameterImpl( + return; + } + break; +- // Get the level information from the texture to avoid a Mac driver +- // bug where they store the levels in int16_t, making values bigger +- // than 2^15-1 overflow in the negative range. + case GL_TEXTURE_BASE_LEVEL: +- if (workarounds().use_shadowed_tex_level_params) { +- if (fparams) { +- fparams[0] = static_cast(texture->base_level()); +- } else { +- iparams[0] = texture->base_level(); +- } +- return; ++ // Use shadowed value in case it's clamped; also because older MacOSX ++ // stores the value on int16_t (see https://crbug.com/610153). ++ if (fparams) { ++ fparams[0] = static_cast(texture->unclamped_base_level()); ++ } else { ++ iparams[0] = texture->unclamped_base_level(); + } +- break; ++ return; + case GL_TEXTURE_MAX_LEVEL: +- if (workarounds().use_shadowed_tex_level_params) { +- if (fparams) { +- fparams[0] = static_cast(texture->max_level()); +- } else { +- iparams[0] = texture->max_level(); +- } +- return; ++ // Use shadowed value in case it's clamped; also because older MacOSX ++ // stores the value on int16_t (see https://crbug.com/610153). ++ if (fparams) { ++ fparams[0] = static_cast(texture->unclamped_max_level()); ++ } else { ++ iparams[0] = texture->unclamped_max_level(); + } +- break; ++ return; + case GL_TEXTURE_SWIZZLE_R: + if (fparams) { + fparams[0] = static_cast(texture->swizzle_r()); +@@ -17573,25 +17568,6 @@ void GLES2DecoderImpl::TexStorageImpl(GLenum target, + compatibility_internal_format = format_info->decompressed_internal_format; + } + +- if (workarounds().reset_base_mipmap_level_before_texstorage && +- texture->base_level() > 0) +- api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, 0); +- +- // TODO(zmo): We might need to emulate TexStorage using TexImage or +- // CompressedTexImage on Mac OSX where we expose ES3 APIs when the underlying +- // driver is lower than 4.2 and ARB_texture_storage extension doesn't exist. +- if (dimension == ContextState::k2D) { +- api()->glTexStorage2DEXTFn(target, levels, compatibility_internal_format, +- width, height); +- } else { +- api()->glTexStorage3DFn(target, levels, compatibility_internal_format, +- width, height, depth); +- } +- if (workarounds().reset_base_mipmap_level_before_texstorage && +- texture->base_level() > 0) +- api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, +- texture->base_level()); +- + { + GLsizei level_width = width; + GLsizei level_height = height; +@@ -17620,6 +17596,29 @@ void GLES2DecoderImpl::TexStorageImpl(GLenum target, + texture->ApplyFormatWorkarounds(feature_info_.get()); + texture->SetImmutable(true); + } ++ ++ if (workarounds().reset_base_mipmap_level_before_texstorage && ++ texture->base_level() > 0) ++ api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, 0); ++ ++ // TODO(zmo): We might need to emulate TexStorage using TexImage or ++ // CompressedTexImage on Mac OSX where we expose ES3 APIs when the underlying ++ // driver is lower than 4.2 and ARB_texture_storage extension doesn't exist. ++ if (dimension == ContextState::k2D) { ++ api()->glTexStorage2DEXTFn(target, levels, compatibility_internal_format, ++ width, height); ++ } else { ++ api()->glTexStorage3DFn(target, levels, compatibility_internal_format, ++ width, height, depth); ++ } ++ if (workarounds().reset_base_mipmap_level_before_texstorage && ++ texture->base_level() > 0) { ++ // Note base_level is already clamped due to texture->SetImmutable(true). ++ // This is necessary for certain NVidia Linux drivers; otherwise they ++ // may trigger segmentation fault. See https://crbug.com/877874. ++ api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, ++ texture->base_level()); ++ } + } + + void GLES2DecoderImpl::DoTexStorage2DEXT(GLenum target,",767,1098,2048 +4170,"static struct sk_buff *tcp_shift_skb_data(struct sock *sk, struct sk_buff *skb, + struct tcp_sacktag_state *state, + u32 start_seq, u32 end_seq, + int dup_sack) +{ + struct tcp_sock *tp = tcp_sk(sk); + struct sk_buff *prev; + int mss; + int pcount = 0; + int len; + int in_sack; + + if (!sk_can_gso(sk)) + goto fallback; + + /* Normally R but no L won't result in plain S */ + if (!dup_sack && + (TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_RETRANS)) == TCPCB_SACKED_RETRANS) + goto fallback; + if (!skb_can_shift(skb)) + goto fallback; + /* This frame is about to be dropped (was ACKed). */ + if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una)) + goto fallback; + + /* Can only happen with delayed DSACK + discard craziness */ + if (unlikely(skb == tcp_write_queue_head(sk))) + goto fallback; + prev = tcp_write_queue_prev(sk, skb); + + if ((TCP_SKB_CB(prev)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED) + goto fallback; + + in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) && + !before(end_seq, TCP_SKB_CB(skb)->end_seq); + + if (in_sack) { + len = skb->len; + pcount = tcp_skb_pcount(skb); + mss = tcp_skb_seglen(skb); + + /* TODO: Fix DSACKs to not fragment already SACKed and we can + * drop this restriction as unnecessary + */ + if (mss != tcp_skb_seglen(prev)) + goto fallback; + } else { + if (!after(TCP_SKB_CB(skb)->end_seq, start_seq)) + goto noop; + /* CHECKME: This is non-MSS split case only?, this will + * cause skipped skbs due to advancing loop btw, original + * has that feature too + */ + if (tcp_skb_pcount(skb) <= 1) + goto noop; + + in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq); + if (!in_sack) { + /* TODO: head merge to next could be attempted here + * if (!after(TCP_SKB_CB(skb)->end_seq, end_seq)), + * though it might not be worth of the additional hassle + * + * ...we can probably just fallback to what was done + * previously. We could try merging non-SACKed ones + * as well but it probably isn't going to buy off + * because later SACKs might again split them, and + * it would make skb timestamp tracking considerably + * harder problem. + */ + goto fallback; + } + + len = end_seq - TCP_SKB_CB(skb)->seq; + BUG_ON(len < 0); + BUG_ON(len > skb->len); + + /* MSS boundaries should be honoured or else pcount will + * severely break even though it makes things bit trickier. + * Optimize common case to avoid most of the divides + */ + mss = tcp_skb_mss(skb); + + /* TODO: Fix DSACKs to not fragment already SACKed and we can + * drop this restriction as unnecessary + */ + if (mss != tcp_skb_seglen(prev)) + goto fallback; + + if (len == mss) { + pcount = 1; + } else if (len < mss) { + goto noop; + } else { + pcount = len / mss; + len = pcount * mss; + } + } + + if (!skb_shift(prev, skb, len)) + goto fallback; + if (!tcp_shifted_skb(sk, skb, state, pcount, len, mss, dup_sack)) + goto out; + + /* Hole filled allows collapsing with the next as well, this is very + * useful when hole on every nth skb pattern happens + */ + if (prev == tcp_write_queue_tail(sk)) + goto out; + skb = tcp_write_queue_next(sk, prev); + + if (!skb_can_shift(skb) || + (skb == tcp_send_head(sk)) || + ((TCP_SKB_CB(skb)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED) || + (mss != tcp_skb_seglen(skb))) + goto out; + + len = skb->len; + if (skb_shift(prev, skb, len)) { + pcount += tcp_skb_pcount(skb); + tcp_shifted_skb(sk, skb, state, tcp_skb_pcount(skb), len, mss, 0); + } + +out: + state->fack_count += pcount; + return prev; + +noop: + return skb; + +fallback: + NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SACKSHIFTFALLBACK); + return NULL; +} +",0,"static struct sk_buff *tcp_shift_skb_data(struct sock *sk, struct sk_buff *skb, + struct tcp_sacktag_state *state, + u32 start_seq, u32 end_seq, + int dup_sack) +{ + struct tcp_sock *tp = tcp_sk(sk); + struct sk_buff *prev; + int mss; + int pcount = 0; + int len; + int in_sack; + + if (!sk_can_gso(sk)) + goto fallback; + + /* Normally R but no L won't result in plain S */ + if (!dup_sack && + (TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_RETRANS)) == TCPCB_SACKED_RETRANS) + goto fallback; + if (!skb_can_shift(skb)) + goto fallback; + /* This frame is about to be dropped (was ACKed). */ + if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una)) + goto fallback; + + /* Can only happen with delayed DSACK + discard craziness */ + if (unlikely(skb == tcp_write_queue_head(sk))) + goto fallback; + prev = tcp_write_queue_prev(sk, skb); + + if ((TCP_SKB_CB(prev)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED) + goto fallback; + + in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) && + !before(end_seq, TCP_SKB_CB(skb)->end_seq); + + if (in_sack) { + len = skb->len; + pcount = tcp_skb_pcount(skb); + mss = tcp_skb_seglen(skb); + + /* TODO: Fix DSACKs to not fragment already SACKed and we can + * drop this restriction as unnecessary + */ + if (mss != tcp_skb_seglen(prev)) + goto fallback; + } else { + if (!after(TCP_SKB_CB(skb)->end_seq, start_seq)) + goto noop; + /* CHECKME: This is non-MSS split case only?, this will + * cause skipped skbs due to advancing loop btw, original + * has that feature too + */ + if (tcp_skb_pcount(skb) <= 1) + goto noop; + + in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq); + if (!in_sack) { + /* TODO: head merge to next could be attempted here + * if (!after(TCP_SKB_CB(skb)->end_seq, end_seq)), + * though it might not be worth of the additional hassle + * + * ...we can probably just fallback to what was done + * previously. We could try merging non-SACKed ones + * as well but it probably isn't going to buy off + * because later SACKs might again split them, and + * it would make skb timestamp tracking considerably + * harder problem. + */ + goto fallback; + } + + len = end_seq - TCP_SKB_CB(skb)->seq; + BUG_ON(len < 0); + BUG_ON(len > skb->len); + + /* MSS boundaries should be honoured or else pcount will + * severely break even though it makes things bit trickier. + * Optimize common case to avoid most of the divides + */ + mss = tcp_skb_mss(skb); + + /* TODO: Fix DSACKs to not fragment already SACKed and we can + * drop this restriction as unnecessary + */ + if (mss != tcp_skb_seglen(prev)) + goto fallback; + + if (len == mss) { + pcount = 1; + } else if (len < mss) { + goto noop; + } else { + pcount = len / mss; + len = pcount * mss; + } + } + + if (!skb_shift(prev, skb, len)) + goto fallback; + if (!tcp_shifted_skb(sk, skb, state, pcount, len, mss, dup_sack)) + goto out; + + /* Hole filled allows collapsing with the next as well, this is very + * useful when hole on every nth skb pattern happens + */ + if (prev == tcp_write_queue_tail(sk)) + goto out; + skb = tcp_write_queue_next(sk, prev); + + if (!skb_can_shift(skb) || + (skb == tcp_send_head(sk)) || + ((TCP_SKB_CB(skb)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED) || + (mss != tcp_skb_seglen(skb))) + goto out; + + len = skb->len; + if (skb_shift(prev, skb, len)) { + pcount += tcp_skb_pcount(skb); + tcp_shifted_skb(sk, skb, state, tcp_skb_pcount(skb), len, mss, 0); + } + +out: + state->fack_count += pcount; + return prev; + +noop: + return skb; + +fallback: + NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SACKSHIFTFALLBACK); + return NULL; +} +","@@ -5811,6 +5811,8 @@ int tcp_rcv_state_process(struct sock *sk, struct sk_buff *skb, + goto discard; + + if (th->syn) { ++ if (th->fin) ++ goto discard; + if (icsk->icsk_af_ops->conn_request(sk, skb) < 0) + return 1; + ",1076,1407,2048 +8165,"SYSCALL_DEFINE2(socketcall, int, call, unsigned long __user *, args) +{ + unsigned long a[AUDITSC_ARGS]; + unsigned long a0, a1; + int err; + unsigned int len; + + if (call < 1 || call > SYS_SENDMMSG) + return -EINVAL; + + len = nargs[call]; + if (len > sizeof(a)) + return -EINVAL; + + /* copy_from_user should be SMP safe. */ + if (copy_from_user(a, args, len)) + return -EFAULT; + + err = audit_socketcall(nargs[call] / sizeof(unsigned long), a); + if (err) + return err; + + a0 = a[0]; + a1 = a[1]; + + switch (call) { + case SYS_SOCKET: + err = __sys_socket(a0, a1, a[2]); + break; + case SYS_BIND: + err = __sys_bind(a0, (struct sockaddr __user *)a1, a[2]); + break; + case SYS_CONNECT: + err = __sys_connect(a0, (struct sockaddr __user *)a1, a[2]); + break; + case SYS_LISTEN: + err = __sys_listen(a0, a1); + break; + case SYS_ACCEPT: + err = __sys_accept4(a0, (struct sockaddr __user *)a1, + (int __user *)a[2], 0); + break; + case SYS_GETSOCKNAME: + err = + __sys_getsockname(a0, (struct sockaddr __user *)a1, + (int __user *)a[2]); + break; + case SYS_GETPEERNAME: + err = + __sys_getpeername(a0, (struct sockaddr __user *)a1, + (int __user *)a[2]); + break; + case SYS_SOCKETPAIR: + err = __sys_socketpair(a0, a1, a[2], (int __user *)a[3]); + break; + case SYS_SEND: + err = __sys_sendto(a0, (void __user *)a1, a[2], a[3], + NULL, 0); + break; + case SYS_SENDTO: + err = __sys_sendto(a0, (void __user *)a1, a[2], a[3], + (struct sockaddr __user *)a[4], a[5]); + break; + case SYS_RECV: + err = __sys_recvfrom(a0, (void __user *)a1, a[2], a[3], + NULL, NULL); + break; + case SYS_RECVFROM: + err = __sys_recvfrom(a0, (void __user *)a1, a[2], a[3], + (struct sockaddr __user *)a[4], + (int __user *)a[5]); + break; + case SYS_SHUTDOWN: + err = __sys_shutdown(a0, a1); + break; + case SYS_SETSOCKOPT: + err = __sys_setsockopt(a0, a1, a[2], (char __user *)a[3], + a[4]); + break; + case SYS_GETSOCKOPT: + err = + __sys_getsockopt(a0, a1, a[2], (char __user *)a[3], + (int __user *)a[4]); + break; + case SYS_SENDMSG: + err = __sys_sendmsg(a0, (struct user_msghdr __user *)a1, + a[2], true); + break; + case SYS_SENDMMSG: + err = __sys_sendmmsg(a0, (struct mmsghdr __user *)a1, a[2], + a[3], true); + break; + case SYS_RECVMSG: + err = __sys_recvmsg(a0, (struct user_msghdr __user *)a1, + a[2], true); + break; + case SYS_RECVMMSG: + err = do_sys_recvmmsg(a0, (struct mmsghdr __user *)a1, a[2], + a[3], (struct timespec __user *)a[4]); + break; + case SYS_ACCEPT4: + err = __sys_accept4(a0, (struct sockaddr __user *)a1, + (int __user *)a[2], a[3]); + break; + default: + err = -EINVAL; + break; + } + return err; +} +",0,"SYSCALL_DEFINE2(socketcall, int, call, unsigned long __user *, args) +{ + unsigned long a[AUDITSC_ARGS]; + unsigned long a0, a1; + int err; + unsigned int len; + + if (call < 1 || call > SYS_SENDMMSG) + return -EINVAL; + + len = nargs[call]; + if (len > sizeof(a)) + return -EINVAL; + + /* copy_from_user should be SMP safe. */ + if (copy_from_user(a, args, len)) + return -EFAULT; + + err = audit_socketcall(nargs[call] / sizeof(unsigned long), a); + if (err) + return err; + + a0 = a[0]; + a1 = a[1]; + + switch (call) { + case SYS_SOCKET: + err = __sys_socket(a0, a1, a[2]); + break; + case SYS_BIND: + err = __sys_bind(a0, (struct sockaddr __user *)a1, a[2]); + break; + case SYS_CONNECT: + err = __sys_connect(a0, (struct sockaddr __user *)a1, a[2]); + break; + case SYS_LISTEN: + err = __sys_listen(a0, a1); + break; + case SYS_ACCEPT: + err = __sys_accept4(a0, (struct sockaddr __user *)a1, + (int __user *)a[2], 0); + break; + case SYS_GETSOCKNAME: + err = + __sys_getsockname(a0, (struct sockaddr __user *)a1, + (int __user *)a[2]); + break; + case SYS_GETPEERNAME: + err = + __sys_getpeername(a0, (struct sockaddr __user *)a1, + (int __user *)a[2]); + break; + case SYS_SOCKETPAIR: + err = __sys_socketpair(a0, a1, a[2], (int __user *)a[3]); + break; + case SYS_SEND: + err = __sys_sendto(a0, (void __user *)a1, a[2], a[3], + NULL, 0); + break; + case SYS_SENDTO: + err = __sys_sendto(a0, (void __user *)a1, a[2], a[3], + (struct sockaddr __user *)a[4], a[5]); + break; + case SYS_RECV: + err = __sys_recvfrom(a0, (void __user *)a1, a[2], a[3], + NULL, NULL); + break; + case SYS_RECVFROM: + err = __sys_recvfrom(a0, (void __user *)a1, a[2], a[3], + (struct sockaddr __user *)a[4], + (int __user *)a[5]); + break; + case SYS_SHUTDOWN: + err = __sys_shutdown(a0, a1); + break; + case SYS_SETSOCKOPT: + err = __sys_setsockopt(a0, a1, a[2], (char __user *)a[3], + a[4]); + break; + case SYS_GETSOCKOPT: + err = + __sys_getsockopt(a0, a1, a[2], (char __user *)a[3], + (int __user *)a[4]); + break; + case SYS_SENDMSG: + err = __sys_sendmsg(a0, (struct user_msghdr __user *)a1, + a[2], true); + break; + case SYS_SENDMMSG: + err = __sys_sendmmsg(a0, (struct mmsghdr __user *)a1, a[2], + a[3], true); + break; + case SYS_RECVMSG: + err = __sys_recvmsg(a0, (struct user_msghdr __user *)a1, + a[2], true); + break; + case SYS_RECVMMSG: + err = do_sys_recvmmsg(a0, (struct mmsghdr __user *)a1, a[2], + a[3], (struct timespec __user *)a[4]); + break; + case SYS_ACCEPT4: + err = __sys_accept4(a0, (struct sockaddr __user *)a1, + (int __user *)a[2], a[3]); + break; + default: + err = -EINVAL; + break; + } + return err; +} +","@@ -541,7 +541,10 @@ static int sockfs_setattr(struct dentry *dentry, struct iattr *iattr) + if (!err && (iattr->ia_valid & ATTR_UID)) { + struct socket *sock = SOCKET_I(d_inode(dentry)); + +- sock->sk->sk_uid = iattr->ia_uid; ++ if (sock->sk) ++ sock->sk->sk_uid = iattr->ia_uid; ++ else ++ err = -ENOENT; + } + + return err; +@@ -590,12 +593,16 @@ EXPORT_SYMBOL(sock_alloc); + * an inode not a file. + */ + +-void sock_release(struct socket *sock) ++static void __sock_release(struct socket *sock, struct inode *inode) + { + if (sock->ops) { + struct module *owner = sock->ops->owner; + ++ if (inode) ++ inode_lock(inode); + sock->ops->release(sock); ++ if (inode) ++ inode_unlock(inode); + sock->ops = NULL; + module_put(owner); + } +@@ -609,6 +616,11 @@ void sock_release(struct socket *sock) + } + sock->file = NULL; + } ++ ++void sock_release(struct socket *sock) ++{ ++ __sock_release(sock, NULL); ++} + EXPORT_SYMBOL(sock_release); + + void __sock_tx_timestamp(__u16 tsflags, __u8 *tx_flags) +@@ -1171,7 +1183,7 @@ static int sock_mmap(struct file *file, struct vm_area_struct *vma) + + static int sock_close(struct inode *inode, struct file *filp) + { +- sock_release(SOCKET_I(inode)); ++ __sock_release(SOCKET_I(inode), inode); + return 0; + } + ",923,1254,2048 +6187,"int ff_rm_read_mdpr_codecdata(AVFormatContext *s, AVIOContext *pb, + AVStream *st, RMStream *rst, + unsigned int codec_data_size, const uint8_t *mime) +{ + unsigned int v; + int size; + int64_t codec_pos; + int ret; + + if (codec_data_size > INT_MAX) + return AVERROR_INVALIDDATA; + if (codec_data_size == 0) + return 0; + + avpriv_set_pts_info(st, 64, 1, 1000); + codec_pos = avio_tell(pb); + v = avio_rb32(pb); + + if (v == MKTAG(0xfd, 'a', 'r', '.')) { + /* ra type header */ + if (rm_read_audio_stream_info(s, pb, st, rst, 0)) + return -1; + } else if (v == MKBETAG('L', 'S', 'D', ':')) { + avio_seek(pb, -4, SEEK_CUR); + if ((ret = rm_read_extradata(s, pb, st->codecpar, codec_data_size)) < 0) + return ret; + + st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; + st->codecpar->codec_tag = AV_RL32(st->codecpar->extradata); + st->codecpar->codec_id = ff_codec_get_id(ff_rm_codec_tags, + st->codecpar->codec_tag); + } else if(mime && !strcmp(mime, ""logical-fileinfo"")){ + int stream_count, rule_count, property_count, i; + ff_free_stream(s, st); + if (avio_rb16(pb) != 0) { + av_log(s, AV_LOG_WARNING, ""Unsupported version\n""); + goto skip; + } + stream_count = avio_rb16(pb); + avio_skip(pb, 6*stream_count); + rule_count = avio_rb16(pb); + avio_skip(pb, 2*rule_count); + property_count = avio_rb16(pb); + for(i=0; imetadata, name, val, 0); + break; + default: avio_skip(pb, avio_rb16(pb)); + } + } + } else { + int fps; + if (avio_rl32(pb) != MKTAG('V', 'I', 'D', 'O')) { + fail1: + av_log(s, AV_LOG_WARNING, ""Unsupported stream type %08x\n"", v); + goto skip; + } + st->codecpar->codec_tag = avio_rl32(pb); + st->codecpar->codec_id = ff_codec_get_id(ff_rm_codec_tags, + st->codecpar->codec_tag); + av_log(s, AV_LOG_TRACE, ""%""PRIX32"" %X\n"", + st->codecpar->codec_tag, MKTAG('R', 'V', '2', '0')); + if (st->codecpar->codec_id == AV_CODEC_ID_NONE) + goto fail1; + st->codecpar->width = avio_rb16(pb); + st->codecpar->height = avio_rb16(pb); + avio_skip(pb, 2); // looks like bits per sample + avio_skip(pb, 4); // always zero? + st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; + st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS; + fps = avio_rb32(pb); + + if ((ret = rm_read_extradata(s, pb, st->codecpar, codec_data_size - (avio_tell(pb) - codec_pos))) < 0) + return ret; + + if (fps > 0) { + av_reduce(&st->avg_frame_rate.den, &st->avg_frame_rate.num, + 0x10000, fps, (1 << 30) - 1); +#if FF_API_R_FRAME_RATE + st->r_frame_rate = st->avg_frame_rate; +#endif + } else if (s->error_recognition & AV_EF_EXPLODE) { + av_log(s, AV_LOG_ERROR, ""Invalid framerate\n""); + return AVERROR_INVALIDDATA; + } + } + +skip: + /* skip codec info */ + size = avio_tell(pb) - codec_pos; + if (codec_data_size >= size) { + avio_skip(pb, codec_data_size - size); + } else { + av_log(s, AV_LOG_WARNING, ""codec_data_size %u < size %d\n"", codec_data_size, size); + } + + return 0; +} +",0,"int ff_rm_read_mdpr_codecdata(AVFormatContext *s, AVIOContext *pb, + AVStream *st, RMStream *rst, + unsigned int codec_data_size, const uint8_t *mime) +{ + unsigned int v; + int size; + int64_t codec_pos; + int ret; + + if (codec_data_size > INT_MAX) + return AVERROR_INVALIDDATA; + if (codec_data_size == 0) + return 0; + + avpriv_set_pts_info(st, 64, 1, 1000); + codec_pos = avio_tell(pb); + v = avio_rb32(pb); + + if (v == MKTAG(0xfd, 'a', 'r', '.')) { + /* ra type header */ + if (rm_read_audio_stream_info(s, pb, st, rst, 0)) + return -1; + } else if (v == MKBETAG('L', 'S', 'D', ':')) { + avio_seek(pb, -4, SEEK_CUR); + if ((ret = rm_read_extradata(s, pb, st->codecpar, codec_data_size)) < 0) + return ret; + + st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; + st->codecpar->codec_tag = AV_RL32(st->codecpar->extradata); + st->codecpar->codec_id = ff_codec_get_id(ff_rm_codec_tags, + st->codecpar->codec_tag); + } else if(mime && !strcmp(mime, ""logical-fileinfo"")){ + int stream_count, rule_count, property_count, i; + ff_free_stream(s, st); + if (avio_rb16(pb) != 0) { + av_log(s, AV_LOG_WARNING, ""Unsupported version\n""); + goto skip; + } + stream_count = avio_rb16(pb); + avio_skip(pb, 6*stream_count); + rule_count = avio_rb16(pb); + avio_skip(pb, 2*rule_count); + property_count = avio_rb16(pb); + for(i=0; imetadata, name, val, 0); + break; + default: avio_skip(pb, avio_rb16(pb)); + } + } + } else { + int fps; + if (avio_rl32(pb) != MKTAG('V', 'I', 'D', 'O')) { + fail1: + av_log(s, AV_LOG_WARNING, ""Unsupported stream type %08x\n"", v); + goto skip; + } + st->codecpar->codec_tag = avio_rl32(pb); + st->codecpar->codec_id = ff_codec_get_id(ff_rm_codec_tags, + st->codecpar->codec_tag); + av_log(s, AV_LOG_TRACE, ""%""PRIX32"" %X\n"", + st->codecpar->codec_tag, MKTAG('R', 'V', '2', '0')); + if (st->codecpar->codec_id == AV_CODEC_ID_NONE) + goto fail1; + st->codecpar->width = avio_rb16(pb); + st->codecpar->height = avio_rb16(pb); + avio_skip(pb, 2); // looks like bits per sample + avio_skip(pb, 4); // always zero? + st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; + st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS; + fps = avio_rb32(pb); + + if ((ret = rm_read_extradata(s, pb, st->codecpar, codec_data_size - (avio_tell(pb) - codec_pos))) < 0) + return ret; + + if (fps > 0) { + av_reduce(&st->avg_frame_rate.den, &st->avg_frame_rate.num, + 0x10000, fps, (1 << 30) - 1); +#if FF_API_R_FRAME_RATE + st->r_frame_rate = st->avg_frame_rate; +#endif + } else if (s->error_recognition & AV_EF_EXPLODE) { + av_log(s, AV_LOG_ERROR, ""Invalid framerate\n""); + return AVERROR_INVALIDDATA; + } + } + +skip: + /* skip codec info */ + size = avio_tell(pb) - codec_pos; + if (codec_data_size >= size) { + avio_skip(pb, codec_data_size - size); + } else { + av_log(s, AV_LOG_WARNING, ""codec_data_size %u < size %d\n"", codec_data_size, size); + } + + return 0; +} +","@@ -1223,8 +1223,11 @@ static int ivr_read_header(AVFormatContext *s) + av_log(s, AV_LOG_DEBUG, ""%s = '%s'\n"", key, val); + } else if (type == 4) { + av_log(s, AV_LOG_DEBUG, ""%s = '0x"", key); +- for (j = 0; j < len; j++) ++ for (j = 0; j < len; j++) { ++ if (avio_feof(pb)) ++ return AVERROR_INVALIDDATA; + av_log(s, AV_LOG_DEBUG, ""%X"", avio_r8(pb)); ++ } + av_log(s, AV_LOG_DEBUG, ""'\n""); + } else if (len == 4 && type == 3 && !strncmp(key, ""StreamCount"", tlen)) { + nb_streams = value = avio_rb32(pb);",1130,1461,2048 +17915,"prep_reprocess_req(krb5_kdc_req *request, krb5_principal *krbtgt_princ) +{ + krb5_error_code retval = KRB5KRB_AP_ERR_BADMATCH; + char **realms, **cpp, *temp_buf=NULL; + krb5_data *comp1 = NULL, *comp2 = NULL; + char *comp1_str = NULL; + + /* By now we know that server principal name is unknown. + * If CANONICALIZE flag is set in the request + * If req is not U2U authn. req + * the requested server princ. has exactly two components + * either + * the name type is NT-SRV-HST + * or name type is NT-UNKNOWN and + * the 1st component is listed in conf file under host_based_services + * the 1st component is not in a list in conf under ""no_host_referral"" + * the 2d component looks like fully-qualified domain name (FQDN) + * If all of these conditions are satisfied - try mapping the FQDN and + * re-process the request as if client had asked for cross-realm TGT. + */ + if (isflagset(request->kdc_options, KDC_OPT_CANONICALIZE) && + !isflagset(request->kdc_options, KDC_OPT_ENC_TKT_IN_SKEY) && + krb5_princ_size(kdc_context, request->server) == 2) { + + comp1 = krb5_princ_component(kdc_context, request->server, 0); + comp2 = krb5_princ_component(kdc_context, request->server, 1); + + comp1_str = calloc(1,comp1->length+1); + if (!comp1_str) { + retval = ENOMEM; + goto cleanup; + } + strlcpy(comp1_str,comp1->data,comp1->length+1); + + if ((krb5_princ_type(kdc_context, request->server) == KRB5_NT_SRV_HST || + krb5_princ_type(kdc_context, request->server) == KRB5_NT_SRV_INST || + (krb5_princ_type(kdc_context, request->server) == KRB5_NT_UNKNOWN && + kdc_active_realm->realm_host_based_services != NULL && + (krb5_match_config_pattern(kdc_active_realm->realm_host_based_services, + comp1_str) == TRUE || + krb5_match_config_pattern(kdc_active_realm->realm_host_based_services, + KRB5_CONF_ASTERISK) == TRUE))) && + (kdc_active_realm->realm_no_host_referral == NULL || + (krb5_match_config_pattern(kdc_active_realm->realm_no_host_referral, + KRB5_CONF_ASTERISK) == FALSE && + krb5_match_config_pattern(kdc_active_realm->realm_no_host_referral, + comp1_str) == FALSE))) { + + if (memchr(comp2->data, '.', comp2->length) == NULL) + goto cleanup; + temp_buf = calloc(1, comp2->length+1); + if (!temp_buf) { + retval = ENOMEM; + goto cleanup; + } + strlcpy(temp_buf, comp2->data,comp2->length+1); + retval = krb5int_get_domain_realm_mapping(kdc_context, temp_buf, &realms); + free(temp_buf); + if (retval) { + /* no match found */ + kdc_err(kdc_context, retval, ""unable to find realm of host""); + goto cleanup; + } + if (realms == 0) { + retval = KRB5KRB_AP_ERR_BADMATCH; + goto cleanup; + } + /* Don't return a referral to the null realm or the service + * realm. */ + if (realms[0] == 0 || + data_eq_string(request->server->realm, realms[0])) { + free(realms[0]); + free(realms); + retval = KRB5KRB_AP_ERR_BADMATCH; + goto cleanup; + } + /* Modify request. + * Construct cross-realm tgt : krbtgt/REMOTE_REALM@LOCAL_REALM + * and use it as a principal in this req. + */ + retval = krb5_build_principal(kdc_context, krbtgt_princ, + (*request->server).realm.length, + (*request->server).realm.data, + ""krbtgt"", realms[0], (char *)0); + for (cpp = realms; *cpp; cpp++) + free(*cpp); + } + } +cleanup: + free(comp1_str); + + return retval; +} +",1,"prep_reprocess_req(krb5_kdc_req *request, krb5_principal *krbtgt_princ) +{ + krb5_error_code retval = KRB5KRB_AP_ERR_BADMATCH; + char **realms, **cpp, *temp_buf=NULL; + krb5_data *comp1 = NULL, *comp2 = NULL; + char *comp1_str = NULL; + + /* By now we know that server principal name is unknown. + * If CANONICALIZE flag is set in the request + * If req is not U2U authn. req + * the requested server princ. has exactly two components + * either + * the name type is NT-SRV-HST + * or name type is NT-UNKNOWN and + * the 1st component is listed in conf file under host_based_services + * the 1st component is not in a list in conf under ""no_host_referral"" + * the 2d component looks like fully-qualified domain name (FQDN) + * If all of these conditions are satisfied - try mapping the FQDN and + * re-process the request as if client had asked for cross-realm TGT. + */ + if (isflagset(request->kdc_options, KDC_OPT_CANONICALIZE) && + !isflagset(request->kdc_options, KDC_OPT_ENC_TKT_IN_SKEY) && + krb5_princ_size(kdc_context, request->server) == 2) { + + comp1 = krb5_princ_component(kdc_context, request->server, 0); + comp2 = krb5_princ_component(kdc_context, request->server, 1); + + comp1_str = calloc(1,comp1->length+1); + if (!comp1_str) { + retval = ENOMEM; + goto cleanup; + } + if (comp1->data != NULL) + memcpy(comp1_str, comp1->data, comp1->length); + + if ((krb5_princ_type(kdc_context, request->server) == KRB5_NT_SRV_HST || + krb5_princ_type(kdc_context, request->server) == KRB5_NT_SRV_INST || + (krb5_princ_type(kdc_context, request->server) == KRB5_NT_UNKNOWN && + kdc_active_realm->realm_host_based_services != NULL && + (krb5_match_config_pattern(kdc_active_realm->realm_host_based_services, + comp1_str) == TRUE || + krb5_match_config_pattern(kdc_active_realm->realm_host_based_services, + KRB5_CONF_ASTERISK) == TRUE))) && + (kdc_active_realm->realm_no_host_referral == NULL || + (krb5_match_config_pattern(kdc_active_realm->realm_no_host_referral, + KRB5_CONF_ASTERISK) == FALSE && + krb5_match_config_pattern(kdc_active_realm->realm_no_host_referral, + comp1_str) == FALSE))) { + + if (memchr(comp2->data, '.', comp2->length) == NULL) + goto cleanup; + temp_buf = calloc(1, comp2->length+1); + if (!temp_buf) { + retval = ENOMEM; + goto cleanup; + } + if (comp2->data != NULL) + memcpy(temp_buf, comp2->data, comp2->length); + retval = krb5int_get_domain_realm_mapping(kdc_context, temp_buf, &realms); + free(temp_buf); + if (retval) { + /* no match found */ + kdc_err(kdc_context, retval, ""unable to find realm of host""); + goto cleanup; + } + if (realms == 0) { + retval = KRB5KRB_AP_ERR_BADMATCH; + goto cleanup; + } + /* Don't return a referral to the null realm or the service + * realm. */ + if (realms[0] == 0 || + data_eq_string(request->server->realm, realms[0])) { + free(realms[0]); + free(realms); + retval = KRB5KRB_AP_ERR_BADMATCH; + goto cleanup; + } + /* Modify request. + * Construct cross-realm tgt : krbtgt/REMOTE_REALM@LOCAL_REALM + * and use it as a principal in this req. + */ + retval = krb5_build_principal(kdc_context, krbtgt_princ, + (*request->server).realm.length, + (*request->server).realm.data, + ""krbtgt"", realms[0], (char *)0); + for (cpp = realms; *cpp; cpp++) + free(*cpp); + } + } +cleanup: + free(comp1_str); + + return retval; +} +","@@ -1141,7 +1141,8 @@ prep_reprocess_req(krb5_kdc_req *request, krb5_principal *krbtgt_princ) + retval = ENOMEM; + goto cleanup; + } +- strlcpy(comp1_str,comp1->data,comp1->length+1); ++ if (comp1->data != NULL) ++ memcpy(comp1_str, comp1->data, comp1->length); + + if ((krb5_princ_type(kdc_context, request->server) == KRB5_NT_SRV_HST || + krb5_princ_type(kdc_context, request->server) == KRB5_NT_SRV_INST || +@@ -1164,7 +1165,8 @@ prep_reprocess_req(krb5_kdc_req *request, krb5_principal *krbtgt_princ) + retval = ENOMEM; + goto cleanup; + } +- strlcpy(temp_buf, comp2->data,comp2->length+1); ++ if (comp2->data != NULL) ++ memcpy(temp_buf, comp2->data, comp2->length); + retval = krb5int_get_domain_realm_mapping(kdc_context, temp_buf, &realms); + free(temp_buf); + if (retval) {",1003,1334,2048 +18659,"bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::SubmitSlice( + const H264PPS* pps, + const H264SliceHeader* slice_hdr, + const H264Picture::Vector& ref_pic_list0, + const H264Picture::Vector& ref_pic_list1, + const scoped_refptr& pic, + const uint8_t* data, + size_t size) { + VASliceParameterBufferH264 slice_param; + memset(&slice_param, 0, sizeof(slice_param)); + + slice_param.slice_data_size = slice_hdr->nalu_size; + slice_param.slice_data_offset = 0; + slice_param.slice_data_flag = VA_SLICE_DATA_FLAG_ALL; + slice_param.slice_data_bit_offset = slice_hdr->header_bit_size; + +#define SHDRToSP(a) slice_param.a = slice_hdr->a + SHDRToSP(first_mb_in_slice); + slice_param.slice_type = slice_hdr->slice_type % 5; + SHDRToSP(direct_spatial_mv_pred_flag); + + SHDRToSP(num_ref_idx_l0_active_minus1); + SHDRToSP(num_ref_idx_l1_active_minus1); + SHDRToSP(cabac_init_idc); + SHDRToSP(slice_qp_delta); + SHDRToSP(disable_deblocking_filter_idc); + SHDRToSP(slice_alpha_c0_offset_div2); + SHDRToSP(slice_beta_offset_div2); + + if (((slice_hdr->IsPSlice() || slice_hdr->IsSPSlice()) && + pps->weighted_pred_flag) || + (slice_hdr->IsBSlice() && pps->weighted_bipred_idc == 1)) { + SHDRToSP(luma_log2_weight_denom); + SHDRToSP(chroma_log2_weight_denom); + + SHDRToSP(luma_weight_l0_flag); + SHDRToSP(luma_weight_l1_flag); + + SHDRToSP(chroma_weight_l0_flag); + SHDRToSP(chroma_weight_l1_flag); + + for (int i = 0; i <= slice_param.num_ref_idx_l0_active_minus1; ++i) { + slice_param.luma_weight_l0[i] = + slice_hdr->pred_weight_table_l0.luma_weight[i]; + slice_param.luma_offset_l0[i] = + slice_hdr->pred_weight_table_l0.luma_offset[i]; + + for (int j = 0; j < 2; ++j) { + slice_param.chroma_weight_l0[i][j] = + slice_hdr->pred_weight_table_l0.chroma_weight[i][j]; + slice_param.chroma_offset_l0[i][j] = + slice_hdr->pred_weight_table_l0.chroma_offset[i][j]; + } + } + + if (slice_hdr->IsBSlice()) { + for (int i = 0; i <= slice_param.num_ref_idx_l1_active_minus1; ++i) { + slice_param.luma_weight_l1[i] = + slice_hdr->pred_weight_table_l1.luma_weight[i]; + slice_param.luma_offset_l1[i] = + slice_hdr->pred_weight_table_l1.luma_offset[i]; + + for (int j = 0; j < 2; ++j) { + slice_param.chroma_weight_l1[i][j] = + slice_hdr->pred_weight_table_l1.chroma_weight[i][j]; + slice_param.chroma_offset_l1[i][j] = + slice_hdr->pred_weight_table_l1.chroma_offset[i][j]; + } + } + } + } + + static_assert( + arraysize(slice_param.RefPicList0) == arraysize(slice_param.RefPicList1), + ""Invalid RefPicList sizes""); + + for (size_t i = 0; i < arraysize(slice_param.RefPicList0); ++i) { + InitVAPicture(&slice_param.RefPicList0[i]); + InitVAPicture(&slice_param.RefPicList1[i]); + } + + for (size_t i = 0; + i < ref_pic_list0.size() && i < arraysize(slice_param.RefPicList0); + ++i) { + if (ref_pic_list0[i]) + FillVAPicture(&slice_param.RefPicList0[i], ref_pic_list0[i]); + } + for (size_t i = 0; + i < ref_pic_list1.size() && i < arraysize(slice_param.RefPicList1); + ++i) { + if (ref_pic_list1[i]) + FillVAPicture(&slice_param.RefPicList1[i], ref_pic_list1[i]); + } + + if (!vaapi_wrapper_->SubmitBuffer(VASliceParameterBufferType, + sizeof(slice_param), &slice_param)) + return false; + + void* non_const_ptr = const_cast(data); + return vaapi_wrapper_->SubmitBuffer(VASliceDataBufferType, size, + non_const_ptr); +} +",1,"bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::SubmitSlice( + const H264PPS* pps, + const H264SliceHeader* slice_hdr, + const H264Picture::Vector& ref_pic_list0, + const H264Picture::Vector& ref_pic_list1, + const scoped_refptr& pic, + const uint8_t* data, + size_t size) { + DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + VASliceParameterBufferH264 slice_param; + memset(&slice_param, 0, sizeof(slice_param)); + + slice_param.slice_data_size = slice_hdr->nalu_size; + slice_param.slice_data_offset = 0; + slice_param.slice_data_flag = VA_SLICE_DATA_FLAG_ALL; + slice_param.slice_data_bit_offset = slice_hdr->header_bit_size; + +#define SHDRToSP(a) slice_param.a = slice_hdr->a + SHDRToSP(first_mb_in_slice); + slice_param.slice_type = slice_hdr->slice_type % 5; + SHDRToSP(direct_spatial_mv_pred_flag); + + SHDRToSP(num_ref_idx_l0_active_minus1); + SHDRToSP(num_ref_idx_l1_active_minus1); + SHDRToSP(cabac_init_idc); + SHDRToSP(slice_qp_delta); + SHDRToSP(disable_deblocking_filter_idc); + SHDRToSP(slice_alpha_c0_offset_div2); + SHDRToSP(slice_beta_offset_div2); + + if (((slice_hdr->IsPSlice() || slice_hdr->IsSPSlice()) && + pps->weighted_pred_flag) || + (slice_hdr->IsBSlice() && pps->weighted_bipred_idc == 1)) { + SHDRToSP(luma_log2_weight_denom); + SHDRToSP(chroma_log2_weight_denom); + + SHDRToSP(luma_weight_l0_flag); + SHDRToSP(luma_weight_l1_flag); + + SHDRToSP(chroma_weight_l0_flag); + SHDRToSP(chroma_weight_l1_flag); + + for (int i = 0; i <= slice_param.num_ref_idx_l0_active_minus1; ++i) { + slice_param.luma_weight_l0[i] = + slice_hdr->pred_weight_table_l0.luma_weight[i]; + slice_param.luma_offset_l0[i] = + slice_hdr->pred_weight_table_l0.luma_offset[i]; + + for (int j = 0; j < 2; ++j) { + slice_param.chroma_weight_l0[i][j] = + slice_hdr->pred_weight_table_l0.chroma_weight[i][j]; + slice_param.chroma_offset_l0[i][j] = + slice_hdr->pred_weight_table_l0.chroma_offset[i][j]; + } + } + + if (slice_hdr->IsBSlice()) { + for (int i = 0; i <= slice_param.num_ref_idx_l1_active_minus1; ++i) { + slice_param.luma_weight_l1[i] = + slice_hdr->pred_weight_table_l1.luma_weight[i]; + slice_param.luma_offset_l1[i] = + slice_hdr->pred_weight_table_l1.luma_offset[i]; + + for (int j = 0; j < 2; ++j) { + slice_param.chroma_weight_l1[i][j] = + slice_hdr->pred_weight_table_l1.chroma_weight[i][j]; + slice_param.chroma_offset_l1[i][j] = + slice_hdr->pred_weight_table_l1.chroma_offset[i][j]; + } + } + } + } + + static_assert( + arraysize(slice_param.RefPicList0) == arraysize(slice_param.RefPicList1), + ""Invalid RefPicList sizes""); + + for (size_t i = 0; i < arraysize(slice_param.RefPicList0); ++i) { + InitVAPicture(&slice_param.RefPicList0[i]); + InitVAPicture(&slice_param.RefPicList1[i]); + } + + for (size_t i = 0; + i < ref_pic_list0.size() && i < arraysize(slice_param.RefPicList0); + ++i) { + if (ref_pic_list0[i]) + FillVAPicture(&slice_param.RefPicList0[i], ref_pic_list0[i]); + } + for (size_t i = 0; + i < ref_pic_list1.size() && i < arraysize(slice_param.RefPicList1); + ++i) { + if (ref_pic_list1[i]) + FillVAPicture(&slice_param.RefPicList1[i], ref_pic_list1[i]); + } + + if (!vaapi_wrapper_->SubmitBuffer(VASliceParameterBufferType, + sizeof(slice_param), &slice_param)) + return false; + + void* non_const_ptr = const_cast(data); + return vaapi_wrapper_->SubmitBuffer(VASliceDataBufferType, size, + non_const_ptr); +} +","@@ -171,6 +171,8 @@ class VaapiVideoDecodeAccelerator::VaapiH264Accelerator + VaapiWrapper* vaapi_wrapper_; + VaapiVideoDecodeAccelerator* vaapi_dec_; + ++ SEQUENCE_CHECKER(sequence_checker_); ++ + DISALLOW_COPY_AND_ASSIGN(VaapiH264Accelerator); + }; + +@@ -218,6 +220,8 @@ class VaapiVideoDecodeAccelerator::VaapiVP8Accelerator + VaapiWrapper* vaapi_wrapper_; + VaapiVideoDecodeAccelerator* vaapi_dec_; + ++ SEQUENCE_CHECKER(sequence_checker_); ++ + DISALLOW_COPY_AND_ASSIGN(VaapiVP8Accelerator); + }; + +@@ -270,6 +274,8 @@ class VaapiVideoDecodeAccelerator::VaapiVP9Accelerator + VaapiWrapper* vaapi_wrapper_; + VaapiVideoDecodeAccelerator* vaapi_dec_; + ++ SEQUENCE_CHECKER(sequence_checker_); ++ + DISALLOW_COPY_AND_ASSIGN(VaapiVP9Accelerator); + }; + +@@ -1061,6 +1067,18 @@ void VaapiVideoDecodeAccelerator::Cleanup() { + client_ptr_factory_.reset(); + weak_this_factory_.InvalidateWeakPtrs(); + ++ decoder_thread_task_runner_->DeleteSoon(FROM_HERE, decoder_.release()); ++ if (h264_accelerator_) { ++ decoder_thread_task_runner_->DeleteSoon(FROM_HERE, ++ h264_accelerator_.release()); ++ } else if (vp8_accelerator_) { ++ decoder_thread_task_runner_->DeleteSoon(FROM_HERE, ++ vp8_accelerator_.release()); ++ } else if (vp9_accelerator_) { ++ decoder_thread_task_runner_->DeleteSoon(FROM_HERE, ++ vp9_accelerator_.release()); ++ } ++ + // Signal all potential waiters on the decoder_thread_, let them early-exit, + // as we've just moved to the kDestroying state, and wait for all tasks + // to finish. +@@ -1144,12 +1162,16 @@ VaapiVideoDecodeAccelerator::VaapiH264Accelerator::VaapiH264Accelerator( + : vaapi_wrapper_(vaapi_wrapper), vaapi_dec_(vaapi_dec) { + DCHECK(vaapi_wrapper_); + DCHECK(vaapi_dec_); ++ DETACH_FROM_SEQUENCE(sequence_checker_); + } + +-VaapiVideoDecodeAccelerator::VaapiH264Accelerator::~VaapiH264Accelerator() {} ++VaapiVideoDecodeAccelerator::VaapiH264Accelerator::~VaapiH264Accelerator() { ++ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); ++} + + scoped_refptr + VaapiVideoDecodeAccelerator::VaapiH264Accelerator::CreateH264Picture() { ++ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + scoped_refptr va_surface = vaapi_dec_->CreateSurface(); + if (!va_surface) + return nullptr; +@@ -1172,6 +1194,7 @@ bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::SubmitFrameMetadata( + const H264Picture::Vector& ref_pic_listb0, + const H264Picture::Vector& ref_pic_listb1, + const scoped_refptr& pic) { ++ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + VAPictureParameterBufferH264 pic_param; + memset(&pic_param, 0, sizeof(pic_param)); + +@@ -1286,6 +1309,7 @@ bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::SubmitSlice( + const scoped_refptr& pic, + const uint8_t* data, + size_t size) { ++ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + VASliceParameterBufferH264 slice_param; + memset(&slice_param, 0, sizeof(slice_param)); + +@@ -1387,6 +1411,7 @@ bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::SubmitSlice( + bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::SubmitDecode( + const scoped_refptr& pic) { + VLOGF(4) << ""Decoding POC "" << pic->pic_order_cnt; ++ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + scoped_refptr dec_surface = + H264PictureToVaapiDecodeSurface(pic); + +@@ -1395,6 +1420,7 @@ bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::SubmitDecode( + + bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::OutputPicture( + const scoped_refptr& pic) { ++ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + scoped_refptr dec_surface = + H264PictureToVaapiDecodeSurface(pic); + dec_surface->set_visible_rect(pic->visible_rect); +@@ -1404,12 +1430,14 @@ bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::OutputPicture( + } + + void VaapiVideoDecodeAccelerator::VaapiH264Accelerator::Reset() { ++ DETACH_FROM_SEQUENCE(sequence_checker_); + vaapi_wrapper_->DestroyPendingBuffers(); + } + + scoped_refptr + VaapiVideoDecodeAccelerator::VaapiH264Accelerator:: + H264PictureToVaapiDecodeSurface(const scoped_refptr& pic) { ++ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + VaapiH264Picture* vaapi_pic = pic->AsVaapiH264Picture(); + CHECK(vaapi_pic); + return vaapi_pic->dec_surface(); +@@ -1418,6 +1446,7 @@ VaapiVideoDecodeAccelerator::VaapiH264Accelerator:: + void VaapiVideoDecodeAccelerator::VaapiH264Accelerator::FillVAPicture( + VAPictureH264* va_pic, + scoped_refptr pic) { ++ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + VASurfaceID va_surface_id = VA_INVALID_SURFACE; + + if (!pic->nonexisting) { +@@ -1454,6 +1483,7 @@ int VaapiVideoDecodeAccelerator::VaapiH264Accelerator::FillVARefFramesFromDPB( + const H264DPB& dpb, + VAPictureH264* va_pics, + int num_pics) { ++ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + H264Picture::Vector::const_reverse_iterator rit; + int i; + +@@ -1474,12 +1504,16 @@ VaapiVideoDecodeAccelerator::VaapiVP8Accelerator::VaapiVP8Accelerator( + : vaapi_wrapper_(vaapi_wrapper), vaapi_dec_(vaapi_dec) { + DCHECK(vaapi_wrapper_); + DCHECK(vaapi_dec_); ++ DETACH_FROM_SEQUENCE(sequence_checker_); + } + +-VaapiVideoDecodeAccelerator::VaapiVP8Accelerator::~VaapiVP8Accelerator() {} ++VaapiVideoDecodeAccelerator::VaapiVP8Accelerator::~VaapiVP8Accelerator() { ++ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); ++} + + scoped_refptr + VaapiVideoDecodeAccelerator::VaapiVP8Accelerator::CreateVP8Picture() { ++ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + scoped_refptr va_surface = vaapi_dec_->CreateSurface(); + if (!va_surface) + return nullptr; +@@ -1500,6 +1534,7 @@ bool VaapiVideoDecodeAccelerator::VaapiVP8Accelerator::SubmitDecode( + const scoped_refptr& last_frame, + const scoped_refptr& golden_frame, + const scoped_refptr& alt_frame) { ++ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + VAIQMatrixBufferVP8 iq_matrix_buf; + memset(&iq_matrix_buf, 0, sizeof(VAIQMatrixBufferVP8)); + +@@ -1682,6 +1717,7 @@ bool VaapiVideoDecodeAccelerator::VaapiVP8Accelerator::SubmitDecode( + + bool VaapiVideoDecodeAccelerator::VaapiVP8Accelerator::OutputPicture( + const scoped_refptr& pic) { ++ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + scoped_refptr dec_surface = + VP8PictureToVaapiDecodeSurface(pic); + dec_surface->set_visible_rect(pic->visible_rect); +@@ -1692,6 +1728,7 @@ bool VaapiVideoDecodeAccelerator::VaapiVP8Accelerator::OutputPicture( + scoped_refptr + VaapiVideoDecodeAccelerator::VaapiVP8Accelerator:: + VP8PictureToVaapiDecodeSurface(const scoped_refptr& pic) { ++ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + VaapiVP8Picture* vaapi_pic = pic->AsVaapiVP8Picture(); + CHECK(vaapi_pic); + return vaapi_pic->dec_surface(); +@@ -1703,12 +1740,16 @@ VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::VaapiVP9Accelerator( + : vaapi_wrapper_(vaapi_wrapper), vaapi_dec_(vaapi_dec) { + DCHECK(vaapi_wrapper_); + DCHECK(vaapi_dec_); ++ DETACH_FROM_SEQUENCE(sequence_checker_); + } + +-VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::~VaapiVP9Accelerator() {} ++VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::~VaapiVP9Accelerator() { ++ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); ++} + + scoped_refptr + VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::CreateVP9Picture() { ++ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + scoped_refptr va_surface = vaapi_dec_->CreateSurface(); + if (!va_surface) + return nullptr; +@@ -1722,6 +1763,7 @@ bool VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::SubmitDecode( + const Vp9LoopFilterParams& lf, + const std::vector>& ref_pictures, + const base::Closure& done_cb) { ++ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + // |done_cb| should be null as we return false from IsFrameContextRequired(). + DCHECK(done_cb.is_null()); + +@@ -1844,6 +1886,7 @@ bool VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::SubmitDecode( + + bool VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::OutputPicture( + const scoped_refptr& pic) { ++ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + scoped_refptr dec_surface = + VP9PictureToVaapiDecodeSurface(pic); + dec_surface->set_visible_rect(pic->visible_rect); +@@ -1854,13 +1897,15 @@ bool VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::OutputPicture( + bool VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::GetFrameContext( + const scoped_refptr& pic, + Vp9FrameContext* frame_ctx) { ++ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + NOTIMPLEMENTED() << ""Frame context update not supported""; + return false; + } + + scoped_refptr + VaapiVideoDecodeAccelerator::VaapiVP9Accelerator:: + VP9PictureToVaapiDecodeSurface(const scoped_refptr& pic) { ++ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); + VaapiVP9Picture* vaapi_pic = pic->AsVaapiVP9Picture(); + CHECK(vaapi_pic); + return vaapi_pic->dec_surface();",1062,1393,2048 +18100," pimv2_addr_print(netdissect_options *ndo, + const u_char *bp, enum pimv2_addrtype at, int silent) + { + int af; + int len, hdrlen; + + ND_TCHECK(bp[0]); + if (pimv2_addr_len == 0) { + ND_TCHECK(bp[1]); + switch (bp[0]) { + case 1: + af = AF_INET; + len = sizeof(struct in_addr); + break; + case 2: + af = AF_INET6; + len = sizeof(struct in6_addr); + break; + default: + return -1; + } + if (bp[1] != 0) + return -1; + hdrlen = 2; + } else { + switch (pimv2_addr_len) { + case sizeof(struct in_addr): + af = AF_INET; + break; + case sizeof(struct in6_addr): + af = AF_INET6; + break; + default: + return -1; + break; + } + len = pimv2_addr_len; + hdrlen = 0; + } + + bp += hdrlen; + switch (at) { + case pimv2_unicast: + ND_TCHECK2(bp[0], len); + if (af == AF_INET) { + if (!silent) + ND_PRINT((ndo, ""%s"", ipaddr_string(ndo, bp))); + } + else if (af == AF_INET6) { + if (!silent) + ND_PRINT((ndo, ""%s"", ip6addr_string(ndo, bp))); + } + return hdrlen + len; + case pimv2_group: + case pimv2_source: + ND_TCHECK2(bp[0], len + 2); + if (af == AF_INET) { + if (!silent) { + ND_PRINT((ndo, ""%s"", ipaddr_string(ndo, bp + 2))); + if (bp[1] != 32) + ND_PRINT((ndo, ""/%u"", bp[1])); + } + } + else if (af == AF_INET6) { + if (!silent) { + ND_PRINT((ndo, ""%s"", ip6addr_string(ndo, bp + 2))); + if (bp[1] != 128) + ND_PRINT((ndo, ""/%u"", bp[1])); + } + } + if (bp[0] && !silent) { + if (at == pimv2_group) { + ND_PRINT((ndo, ""(0x%02x)"", bp[0])); + } else { + ND_PRINT((ndo, ""(%s%s%s"", + bp[0] & 0x04 ? ""S"" : """", + bp[0] & 0x02 ? ""W"" : """", + bp[0] & 0x01 ? ""R"" : """")); + if (bp[0] & 0xf8) { + ND_PRINT((ndo, ""+0x%02x"", bp[0] & 0xf8)); + } + ND_PRINT((ndo, "")"")); + } + } + return hdrlen + 2 + len; + default: + return -1; + } +trunc: + return -1; +} +",1," pimv2_addr_print(netdissect_options *ndo, + const u_char *bp, u_int len, enum pimv2_addrtype at, + u_int addr_len, int silent) + { + int af; + int hdrlen; + + if (addr_len == 0) { + if (len < 2) + goto trunc; + ND_TCHECK(bp[1]); + switch (bp[0]) { + case 1: + af = AF_INET; + addr_len = (u_int)sizeof(struct in_addr); + break; + case 2: + af = AF_INET6; + addr_len = (u_int)sizeof(struct in6_addr); + break; + default: + return -1; + } + if (bp[1] != 0) + return -1; + hdrlen = 2; + } else { + switch (addr_len) { + case sizeof(struct in_addr): + af = AF_INET; + break; + case sizeof(struct in6_addr): + af = AF_INET6; + break; + default: + return -1; + break; + } + hdrlen = 0; + } + + bp += hdrlen; + len -= hdrlen; + switch (at) { + case pimv2_unicast: + if (len < addr_len) + goto trunc; + ND_TCHECK2(bp[0], addr_len); + if (af == AF_INET) { + if (!silent) + ND_PRINT((ndo, ""%s"", ipaddr_string(ndo, bp))); + } + else if (af == AF_INET6) { + if (!silent) + ND_PRINT((ndo, ""%s"", ip6addr_string(ndo, bp))); + } + return hdrlen + addr_len; + case pimv2_group: + case pimv2_source: + if (len < addr_len + 2) + goto trunc; + ND_TCHECK2(bp[0], addr_len + 2); + if (af == AF_INET) { + if (!silent) { + ND_PRINT((ndo, ""%s"", ipaddr_string(ndo, bp + 2))); + if (bp[1] != 32) + ND_PRINT((ndo, ""/%u"", bp[1])); + } + } + else if (af == AF_INET6) { + if (!silent) { + ND_PRINT((ndo, ""%s"", ip6addr_string(ndo, bp + 2))); + if (bp[1] != 128) + ND_PRINT((ndo, ""/%u"", bp[1])); + } + } + if (bp[0] && !silent) { + if (at == pimv2_group) { + ND_PRINT((ndo, ""(0x%02x)"", bp[0])); + } else { + ND_PRINT((ndo, ""(%s%s%s"", + bp[0] & 0x04 ? ""S"" : """", + bp[0] & 0x02 ? ""W"" : """", + bp[0] & 0x01 ? ""R"" : """")); + if (bp[0] & 0xf8) { + ND_PRINT((ndo, ""+0x%02x"", bp[0] & 0xf8)); + } + ND_PRINT((ndo, "")"")); + } + } + return hdrlen + 2 + addr_len; + default: + return -1; + } +trunc: + return -1; +} +","@@ -169,20 +169,28 @@ pimv1_join_prune_print(netdissect_options *ndo, + return; + } + ++ if (len < sizeof(struct in_addr)) ++ goto trunc; + ND_TCHECK2(bp[0], sizeof(struct in_addr)); + if (ndo->ndo_vflag > 1) + ND_PRINT((ndo, ""\n"")); + ND_PRINT((ndo, "" Upstream Nbr: %s"", ipaddr_string(ndo, bp))); +- ND_TCHECK2(bp[6], 2); ++ bp += 4; ++ len -= 4; ++ if (len < 4) ++ goto trunc; ++ ND_TCHECK2(bp[2], 2); + if (ndo->ndo_vflag > 1) + ND_PRINT((ndo, ""\n"")); + ND_PRINT((ndo, "" Hold time: "")); +- unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[6])); ++ unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2])); + if (ndo->ndo_vflag < 2) + return; +- bp += 8; +- len -= 8; ++ bp += 4; ++ len -= 4; + ++ if (len < 4) ++ goto trunc; + ND_TCHECK2(bp[0], 4); + ngroups = bp[3]; + bp += 4; +@@ -192,30 +200,43 @@ pimv1_join_prune_print(netdissect_options *ndo, + * XXX - does the address have length ""addrlen"" and the + * mask length ""maddrlen""? + */ ++ if (len < 4) ++ goto trunc; + ND_TCHECK2(bp[0], sizeof(struct in_addr)); + ND_PRINT((ndo, ""\n\tGroup: %s"", ipaddr_string(ndo, bp))); +- ND_TCHECK2(bp[4], sizeof(struct in_addr)); +- if (EXTRACT_32BITS(&bp[4]) != 0xffffffff) +- ND_PRINT((ndo, ""/%s"", ipaddr_string(ndo, &bp[4]))); +- ND_TCHECK2(bp[8], 4); +- njoin = EXTRACT_16BITS(&bp[8]); +- nprune = EXTRACT_16BITS(&bp[10]); ++ bp += 4; ++ len -= 4; ++ if (len < 4) ++ goto trunc; ++ ND_TCHECK2(bp[0], sizeof(struct in_addr)); ++ if (EXTRACT_32BITS(&bp[0]) != 0xffffffff) ++ ND_PRINT((ndo, ""/%s"", ipaddr_string(ndo, &bp[0]))); ++ bp += 4; ++ len -= 4; ++ if (len < 4) ++ goto trunc; ++ ND_TCHECK2(bp[0], 4); ++ njoin = EXTRACT_16BITS(&bp[0]); ++ nprune = EXTRACT_16BITS(&bp[2]); + ND_PRINT((ndo, "" joined: %d pruned: %d"", njoin, nprune)); +- bp += 12; +- len -= 12; ++ bp += 4; ++ len -= 4; + for (njp = 0; njp < (njoin + nprune); njp++) { + const char *type; + + if (njp < njoin) + type = ""Join ""; + else + type = ""Prune""; ++ if (len < 6) ++ goto trunc; + ND_TCHECK2(bp[0], 6); + ND_PRINT((ndo, ""\n\t%s %s%s%s%s/%d"", type, + (bp[0] & 0x01) ? ""Sparse "" : ""Dense "", + (bp[1] & 0x80) ? ""WC "" : """", + (bp[1] & 0x40) ? ""RP "" : ""SPT "", +- ipaddr_string(ndo, &bp[2]), bp[1] & 0x3f)); ++ ipaddr_string(ndo, &bp[2]), ++ bp[1] & 0x3f)); + bp += 6; + len -= 6; + } +@@ -230,13 +251,8 @@ void + pimv1_print(netdissect_options *ndo, + register const u_char *bp, register u_int len) + { +- register const u_char *ep; + register u_char type; + +- ep = (const u_char *)ndo->ndo_snapend; +- if (bp >= ep) +- return; +- + ND_TCHECK(bp[1]); + type = bp[1]; + +@@ -302,8 +318,11 @@ pimv1_print(netdissect_options *ndo, + case PIMV1_TYPE_JOIN_PRUNE: + case PIMV1_TYPE_GRAFT: + case PIMV1_TYPE_GRAFT_ACK: +- if (ndo->ndo_vflag) ++ if (ndo->ndo_vflag) { ++ if (len < 8) ++ goto trunc; + pimv1_join_prune_print(ndo, &bp[8], len - 8); ++ } + break; + } + ND_TCHECK(bp[4]); +@@ -330,6 +349,8 @@ cisco_autorp_print(netdissect_options *ndo, + int numrps; + int hold; + ++ if (len < 8) ++ goto trunc; + ND_TCHECK(bp[0]); + ND_PRINT((ndo, "" auto-rp "")); + type = bp[0]; +@@ -377,10 +398,16 @@ cisco_autorp_print(netdissect_options *ndo, + int nentries; + char s; + ++ if (len < 4) ++ goto trunc; + ND_TCHECK2(bp[0], 4); + ND_PRINT((ndo, "" RP %s"", ipaddr_string(ndo, bp))); +- ND_TCHECK(bp[4]); +- switch (bp[4] & 0x3) { ++ bp += 4; ++ len -= 4; ++ if (len < 1) ++ goto trunc; ++ ND_TCHECK(bp[0]); ++ switch (bp[0] & 0x3) { + case 0: ND_PRINT((ndo, "" PIMv?"")); + break; + case 1: ND_PRINT((ndo, "" PIMv1"")); +@@ -390,13 +417,20 @@ cisco_autorp_print(netdissect_options *ndo, + case 3: ND_PRINT((ndo, "" PIMv1+2"")); + break; + } +- if (bp[4] & 0xfc) +- ND_PRINT((ndo, "" [rsvd=0x%02x]"", bp[4] & 0xfc)); +- ND_TCHECK(bp[5]); +- nentries = bp[5]; +- bp += 6; len -= 6; ++ if (bp[0] & 0xfc) ++ ND_PRINT((ndo, "" [rsvd=0x%02x]"", bp[0] & 0xfc)); ++ bp += 1; ++ len -= 1; ++ if (len < 1) ++ goto trunc; ++ ND_TCHECK(bp[0]); ++ nentries = bp[0]; ++ bp += 1; ++ len -= 1; + s = ' '; + for (; nentries; nentries--) { ++ if (len < 6) ++ goto trunc; + ND_TCHECK2(bp[0], 6); + ND_PRINT((ndo, ""%c%s%s/%d"", s, bp[0] & 1 ? ""!"" : """", + ipaddr_string(ndo, &bp[2]), bp[1])); +@@ -421,16 +455,13 @@ void + pim_print(netdissect_options *ndo, + register const u_char *bp, register u_int len, const u_char *bp2) + { +- register const u_char *ep; + register const struct pim *pim = (const struct pim *)bp; + +- ep = (const u_char *)ndo->ndo_snapend; +- if (bp >= ep) +- return; + #ifdef notyet /* currently we see only version and type */ + ND_TCHECK(pim->pim_rsv); + #endif + ++ ND_TCHECK(pim->pim_typever); + switch (PIM_VER(pim->pim_typever)) { + case 2: + if (!ndo->ndo_vflag) { +@@ -454,6 +485,10 @@ pim_print(netdissect_options *ndo, + break; + } + return; ++ ++trunc: ++ ND_PRINT((ndo, ""[|pim]"")); ++ return; + } + + /* +@@ -496,8 +531,6 @@ pim_print(netdissect_options *ndo, + * + */ + +-static int pimv2_addr_len; +- + enum pimv2_addrtype { + pimv2_unicast, pimv2_group, pimv2_source + }; +@@ -524,23 +557,24 @@ enum pimv2_addrtype { + */ + static int + pimv2_addr_print(netdissect_options *ndo, +- const u_char *bp, enum pimv2_addrtype at, int silent) ++ const u_char *bp, u_int len, enum pimv2_addrtype at, ++ u_int addr_len, int silent) + { + int af; +- int len, hdrlen; ++ int hdrlen; + +- ND_TCHECK(bp[0]); +- +- if (pimv2_addr_len == 0) { ++ if (addr_len == 0) { ++ if (len < 2) ++ goto trunc; + ND_TCHECK(bp[1]); + switch (bp[0]) { + case 1: + af = AF_INET; +- len = sizeof(struct in_addr); ++ addr_len = (u_int)sizeof(struct in_addr); + break; + case 2: + af = AF_INET6; +- len = sizeof(struct in6_addr); ++ addr_len = (u_int)sizeof(struct in6_addr); + break; + default: + return -1; +@@ -549,7 +583,7 @@ pimv2_addr_print(netdissect_options *ndo, + return -1; + hdrlen = 2; + } else { +- switch (pimv2_addr_len) { ++ switch (addr_len) { + case sizeof(struct in_addr): + af = AF_INET; + break; +@@ -560,14 +594,16 @@ pimv2_addr_print(netdissect_options *ndo, + return -1; + break; + } +- len = pimv2_addr_len; + hdrlen = 0; + } + + bp += hdrlen; ++ len -= hdrlen; + switch (at) { + case pimv2_unicast: +- ND_TCHECK2(bp[0], len); ++ if (len < addr_len) ++ goto trunc; ++ ND_TCHECK2(bp[0], addr_len); + if (af == AF_INET) { + if (!silent) + ND_PRINT((ndo, ""%s"", ipaddr_string(ndo, bp))); +@@ -576,10 +612,12 @@ pimv2_addr_print(netdissect_options *ndo, + if (!silent) + ND_PRINT((ndo, ""%s"", ip6addr_string(ndo, bp))); + } +- return hdrlen + len; ++ return hdrlen + addr_len; + case pimv2_group: + case pimv2_source: +- ND_TCHECK2(bp[0], len + 2); ++ if (len < addr_len + 2) ++ goto trunc; ++ ND_TCHECK2(bp[0], addr_len + 2); + if (af == AF_INET) { + if (!silent) { + ND_PRINT((ndo, ""%s"", ipaddr_string(ndo, bp + 2))); +@@ -608,7 +646,7 @@ pimv2_addr_print(netdissect_options *ndo, + ND_PRINT((ndo, "")"")); + } + } +- return hdrlen + 2 + len; ++ return hdrlen + 2 + addr_len; + default: + return -1; + } +@@ -660,17 +698,23 @@ pimv2_print(netdissect_options *ndo, + register const struct pim *pim = (const struct pim *)bp; + int advance; + enum checksum_status cksum_status; ++ int pimv2_addr_len; + + ep = (const u_char *)ndo->ndo_snapend; + if (bp >= ep) + return; + if (ep > bp + len) + ep = bp + len; ++ if (len < 2) ++ goto trunc; + ND_TCHECK(pim->pim_rsv); + pimv2_addr_len = pim->pim_rsv; + if (pimv2_addr_len != 0) + ND_PRINT((ndo, "", RFC2117-encoding"")); + ++ if (len < 4) ++ goto trunc; ++ ND_TCHECK(pim->pim_cksum); + ND_PRINT((ndo, "", cksum 0x%04x "", EXTRACT_16BITS(&pim->pim_cksum))); + if (EXTRACT_16BITS(&pim->pim_cksum) == 0) { + ND_PRINT((ndo, ""(unverified)"")); +@@ -711,23 +755,29 @@ pimv2_print(netdissect_options *ndo, + break; + } + } ++ bp += 4; ++ len -= 4; + + switch (PIM_TYPE(pim->pim_typever)) { + case PIMV2_TYPE_HELLO: + { + uint16_t otype, olen; +- bp += 4; +- while (bp < ep) { ++ while (len > 0) { ++ if (len < 4) ++ goto trunc; + ND_TCHECK2(bp[0], 4); + otype = EXTRACT_16BITS(&bp[0]); + olen = EXTRACT_16BITS(&bp[2]); +- ND_TCHECK2(bp[0], 4 + olen); + ND_PRINT((ndo, ""\n\t %s Option (%u), length %u, Value: "", + tok2str(pimv2_hello_option_values, ""Unknown"", otype), + otype, + olen)); + bp += 4; ++ len -= 4; + ++ if (len < olen) ++ goto trunc; ++ ND_TCHECK2(bp[0], olen); + switch (otype) { + case PIMV2_HELLO_OPTION_HOLDTIME: + if (olen != 2) { +@@ -797,14 +847,14 @@ pimv2_print(netdissect_options *ndo, + case PIMV2_HELLO_OPTION_ADDRESS_LIST: + if (ndo->ndo_vflag > 1) { + const u_char *ptr = bp; ++ u_int plen = len; + while (ptr < (bp+olen)) { + ND_PRINT((ndo, ""\n\t "")); +- advance = pimv2_addr_print(ndo, ptr, pimv2_unicast, 0); +- if (advance < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ advance = pimv2_addr_print(ndo, ptr, plen, pimv2_unicast, pimv2_addr_len, 0); ++ if (advance < 0) ++ goto trunc; + ptr += advance; ++ plen -= advance; + } + } + break; +@@ -817,6 +867,7 @@ pimv2_print(netdissect_options *ndo, + if (ndo->ndo_vflag> 1) + print_unknown_data(ndo, bp, ""\n\t "", olen); + bp += olen; ++ len -= olen; + } + break; + } +@@ -825,18 +876,24 @@ pimv2_print(netdissect_options *ndo, + { + const struct ip *ip; + +- ND_TCHECK2(*(bp + 4), PIMV2_REGISTER_FLAG_LEN); ++ if (len < 4) ++ goto trunc; ++ ND_TCHECK2(*bp, PIMV2_REGISTER_FLAG_LEN); + + ND_PRINT((ndo, "", Flags [ %s ]\n\t"", + tok2str(pimv2_register_flag_values, + ""none"", +- EXTRACT_32BITS(bp+4)))); ++ EXTRACT_32BITS(bp)))); + +- bp += 8; len -= 8; ++ bp += 4; len -= 4; + /* encapsulated multicast packet */ ++ if (len == 0) ++ goto trunc; + ip = (const struct ip *)bp; ++ ND_TCHECK(ip->ip_vhl); + switch (IP_V(ip)) { + case 0: /* Null header */ ++ ND_TCHECK(ip->ip_dst); + ND_PRINT((ndo, ""IP-Null-header %s > %s"", + ipaddr_string(ndo, &ip->ip_src), + ipaddr_string(ndo, &ip->ip_dst))); +@@ -858,22 +915,13 @@ pimv2_print(netdissect_options *ndo, + } + + case PIMV2_TYPE_REGISTER_STOP: +- bp += 4; len -= 4; +- if (bp >= ep) +- break; + ND_PRINT((ndo, "" group="")); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_group, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; len -= advance; +- if (bp >= ep) +- break; + ND_PRINT((ndo, "" source="")); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_unicast, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; len -= advance; + break; + +@@ -924,19 +972,15 @@ pimv2_print(netdissect_options *ndo, + uint16_t nprune; + int i, j; + +- bp += 4; len -= 4; + if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/ +- if (bp >= ep) +- break; + ND_PRINT((ndo, "", upstream-neighbor: "")); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_unicast, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; len -= advance; + } +- if (bp + 4 > ep) +- break; ++ if (len < 4) ++ goto trunc; ++ ND_TCHECK2(*bp, 4); + ngroup = bp[1]; + holdtime = EXTRACT_16BITS(&bp[2]); + ND_PRINT((ndo, ""\n\t %u group(s)"", ngroup)); +@@ -949,139 +993,125 @@ pimv2_print(netdissect_options *ndo, + } + bp += 4; len -= 4; + for (i = 0; i < ngroup; i++) { +- if (bp >= ep) +- goto jp_done; + ND_PRINT((ndo, ""\n\t group #%u: "", i+1)); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { +- ND_PRINT((ndo, ""...)"")); +- goto jp_done; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_group, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; len -= advance; +- if (bp + 4 > ep) { +- ND_PRINT((ndo, ""...)"")); +- goto jp_done; +- } ++ if (len < 4) ++ goto trunc; ++ ND_TCHECK2(*bp, 4); + njoin = EXTRACT_16BITS(&bp[0]); + nprune = EXTRACT_16BITS(&bp[2]); + ND_PRINT((ndo, "", joined sources: %u, pruned sources: %u"", njoin, nprune)); + bp += 4; len -= 4; + for (j = 0; j < njoin; j++) { + ND_PRINT((ndo, ""\n\t joined source #%u: "", j+1)); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) { +- ND_PRINT((ndo, ""...)"")); +- goto jp_done; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_source, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; len -= advance; + } + for (j = 0; j < nprune; j++) { + ND_PRINT((ndo, ""\n\t pruned source #%u: "", j+1)); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) { +- ND_PRINT((ndo, ""...)"")); +- goto jp_done; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_source, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; len -= advance; + } + } +- jp_done: + break; + } + + case PIMV2_TYPE_BOOTSTRAP: + { + int i, j, frpcnt; +- bp += 4; + + /* Fragment Tag, Hash Mask len, and BSR-priority */ +- if (bp + sizeof(uint16_t) >= ep) break; ++ if (len < 2) ++ goto trunc; ++ ND_TCHECK_16BITS(bp); + ND_PRINT((ndo, "" tag=%x"", EXTRACT_16BITS(bp))); +- bp += sizeof(uint16_t); +- if (bp >= ep) break; ++ bp += 2; ++ len -= 2; ++ if (len < 1) ++ goto trunc; ++ ND_TCHECK(bp[0]); + ND_PRINT((ndo, "" hashmlen=%d"", bp[0])); +- if (bp + 1 >= ep) break; ++ if (len < 2) ++ goto trunc; ++ ND_TCHECK(bp[2]); + ND_PRINT((ndo, "" BSRprio=%d"", bp[1])); + bp += 2; ++ len -= 2; + + /* Encoded-Unicast-BSR-Address */ +- if (bp >= ep) break; + ND_PRINT((ndo, "" BSR="")); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_unicast, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; ++ len -= advance; + + for (i = 0; bp < ep; i++) { + /* Encoded-Group Address */ + ND_PRINT((ndo, "" (group%d: "", i)); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) +- < 0) { +- ND_PRINT((ndo, ""...)"")); +- goto bs_done; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_group, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; ++ len -= advance; + + /* RP-Count, Frag RP-Cnt, and rsvd */ +- if (bp >= ep) { +- ND_PRINT((ndo, ""...)"")); +- goto bs_done; +- } ++ if (len < 1) ++ goto trunc; ++ ND_TCHECK(bp[0]); + ND_PRINT((ndo, "" RPcnt=%d"", bp[0])); +- if (bp + 1 >= ep) { +- ND_PRINT((ndo, ""...)"")); +- goto bs_done; +- } ++ if (len < 2) ++ goto trunc; ++ ND_TCHECK(bp[1]); + ND_PRINT((ndo, "" FRPcnt=%d"", frpcnt = bp[1])); ++ if (len < 4) ++ goto trunc; + bp += 4; ++ len -= 4; + + for (j = 0; j < frpcnt && bp < ep; j++) { + /* each RP info */ + ND_PRINT((ndo, "" RP%d="", j)); +- if ((advance = pimv2_addr_print(ndo, bp, ++ if ((advance = pimv2_addr_print(ndo, bp, len, + pimv2_unicast, +- 0)) < 0) { +- ND_PRINT((ndo, ""...)"")); +- goto bs_done; +- } ++ pimv2_addr_len, ++ 0)) < 0) ++ goto trunc; + bp += advance; ++ len -= advance; + +- if (bp + 1 >= ep) { +- ND_PRINT((ndo, ""...)"")); +- goto bs_done; +- } ++ if (len < 2) ++ goto trunc; ++ ND_TCHECK_16BITS(bp); + ND_PRINT((ndo, "",holdtime="")); + unsigned_relts_print(ndo, EXTRACT_16BITS(bp)); +- if (bp + 2 >= ep) { +- ND_PRINT((ndo, ""...)"")); +- goto bs_done; +- } ++ if (len < 3) ++ goto trunc; ++ ND_TCHECK(bp[2]); + ND_PRINT((ndo, "",prio=%d"", bp[2])); ++ if (len < 4) ++ goto trunc; + bp += 4; ++ len -= 4; + } + ND_PRINT((ndo, "")"")); + } +- bs_done: + break; + } + case PIMV2_TYPE_ASSERT: +- bp += 4; len -= 4; +- if (bp >= ep) +- break; + ND_PRINT((ndo, "" group="")); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_group, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; len -= advance; +- if (bp >= ep) +- break; + ND_PRINT((ndo, "" src="")); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_unicast, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; len -= advance; +- if (bp + 8 > ep) +- break; ++ if (len < 8) ++ goto trunc; ++ ND_TCHECK2(*bp, 8); + if (bp[0] & 0x80) + ND_PRINT((ndo, "" RPT"")); + ND_PRINT((ndo, "" pref=%u"", EXTRACT_32BITS(&bp[0]) & 0x7fffffff)); +@@ -1091,61 +1121,62 @@ pimv2_print(netdissect_options *ndo, + case PIMV2_TYPE_CANDIDATE_RP: + { + int i, pfxcnt; +- bp += 4; + + /* Prefix-Cnt, Priority, and Holdtime */ +- if (bp >= ep) break; ++ if (len < 1) ++ goto trunc; ++ ND_TCHECK(bp[0]); + ND_PRINT((ndo, "" prefix-cnt=%d"", bp[0])); + pfxcnt = bp[0]; +- if (bp + 1 >= ep) break; ++ if (len < 2) ++ goto trunc; ++ ND_TCHECK(bp[1]); + ND_PRINT((ndo, "" prio=%d"", bp[1])); +- if (bp + 3 >= ep) break; ++ if (len < 4) ++ goto trunc; ++ ND_TCHECK_16BITS(&bp[2]); + ND_PRINT((ndo, "" holdtime="")); + unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2])); + bp += 4; ++ len -= 4; + + /* Encoded-Unicast-RP-Address */ +- if (bp >= ep) break; + ND_PRINT((ndo, "" RP="")); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_unicast, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; ++ len -= advance; + + /* Encoded-Group Addresses */ + for (i = 0; i < pfxcnt && bp < ep; i++) { + ND_PRINT((ndo, "" Group%d="", i)); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) +- < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_group, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; ++ len -= advance; + } + break; + } + + case PIMV2_TYPE_PRUNE_REFRESH: + ND_PRINT((ndo, "" src="")); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_unicast, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; ++ len -= advance; + ND_PRINT((ndo, "" grp="")); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_group, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; ++ len -= advance; + ND_PRINT((ndo, "" forwarder="")); +- if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) { +- ND_PRINT((ndo, ""..."")); +- break; +- } ++ if ((advance = pimv2_addr_print(ndo, bp, len, pimv2_unicast, pimv2_addr_len, 0)) < 0) ++ goto trunc; + bp += advance; +- ND_TCHECK2(bp[0], 2); ++ len -= advance; ++ if (len < 2) ++ goto trunc; ++ ND_TCHECK_16BITS(bp); + ND_PRINT((ndo, "" TUNR "")); + unsigned_relts_print(ndo, EXTRACT_16BITS(bp)); + break;",743,1074,2048 +17118,"status_t AudioFlinger::EffectModule::configure() +{ + status_t status; + sp thread; + uint32_t size; + audio_channel_mask_t channelMask; + + if (mEffectInterface == NULL) { + status = NO_INIT; + goto exit; + } + + thread = mThread.promote(); + if (thread == 0) { + status = DEAD_OBJECT; + goto exit; + } + + channelMask = thread->channelMask(); + mConfig.outputCfg.channels = channelMask; + + if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { + mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO; + } else { + mConfig.inputCfg.channels = channelMask; + if (channelMask == AUDIO_CHANNEL_OUT_MONO) { + mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_STEREO; + mConfig.outputCfg.channels = AUDIO_CHANNEL_OUT_STEREO; + ALOGV(""Overriding effect input and output as STEREO""); + } + } + + mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT; + mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT; + mConfig.inputCfg.samplingRate = thread->sampleRate(); + mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate; + mConfig.inputCfg.bufferProvider.cookie = NULL; + mConfig.inputCfg.bufferProvider.getBuffer = NULL; + mConfig.inputCfg.bufferProvider.releaseBuffer = NULL; + mConfig.outputCfg.bufferProvider.cookie = NULL; + mConfig.outputCfg.bufferProvider.getBuffer = NULL; + mConfig.outputCfg.bufferProvider.releaseBuffer = NULL; + mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ; + if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) { + mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE; + } else { + mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE; + } + mConfig.inputCfg.mask = EFFECT_CONFIG_ALL; + mConfig.outputCfg.mask = EFFECT_CONFIG_ALL; + mConfig.inputCfg.buffer.frameCount = thread->frameCount(); + mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount; + + ALOGV(""configure() %p thread %p buffer %p framecount %zu"", + this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount); + + status_t cmdStatus; + size = sizeof(int); + status = (*mEffectInterface)->command(mEffectInterface, + EFFECT_CMD_SET_CONFIG, + sizeof(effect_config_t), + &mConfig, + &size, + &cmdStatus); + if (status == 0) { + status = cmdStatus; + } + + if (status == 0 && + (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) { + uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2]; + effect_param_t *p = (effect_param_t *)buf32; + + p->psize = sizeof(uint32_t); + p->vsize = sizeof(uint32_t); + size = sizeof(int); + *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY; + + uint32_t latency = 0; + PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId); + if (pbt != NULL) { + latency = pbt->latency_l(); + } + + *((int32_t *)p->data + 1)= latency; + (*mEffectInterface)->command(mEffectInterface, + EFFECT_CMD_SET_PARAM, + sizeof(effect_param_t) + 8, + &buf32, + &size, + &cmdStatus); + } + + mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) / + (1000 * mConfig.outputCfg.buffer.frameCount); + +exit: + mStatus = status; + return status; +} +",0,"status_t AudioFlinger::EffectModule::configure() +{ + status_t status; + sp thread; + uint32_t size; + audio_channel_mask_t channelMask; + + if (mEffectInterface == NULL) { + status = NO_INIT; + goto exit; + } + + thread = mThread.promote(); + if (thread == 0) { + status = DEAD_OBJECT; + goto exit; + } + + channelMask = thread->channelMask(); + mConfig.outputCfg.channels = channelMask; + + if ((mDescriptor.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) { + mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_MONO; + } else { + mConfig.inputCfg.channels = channelMask; + if (channelMask == AUDIO_CHANNEL_OUT_MONO) { + mConfig.inputCfg.channels = AUDIO_CHANNEL_OUT_STEREO; + mConfig.outputCfg.channels = AUDIO_CHANNEL_OUT_STEREO; + ALOGV(""Overriding effect input and output as STEREO""); + } + } + + mConfig.inputCfg.format = AUDIO_FORMAT_PCM_16_BIT; + mConfig.outputCfg.format = AUDIO_FORMAT_PCM_16_BIT; + mConfig.inputCfg.samplingRate = thread->sampleRate(); + mConfig.outputCfg.samplingRate = mConfig.inputCfg.samplingRate; + mConfig.inputCfg.bufferProvider.cookie = NULL; + mConfig.inputCfg.bufferProvider.getBuffer = NULL; + mConfig.inputCfg.bufferProvider.releaseBuffer = NULL; + mConfig.outputCfg.bufferProvider.cookie = NULL; + mConfig.outputCfg.bufferProvider.getBuffer = NULL; + mConfig.outputCfg.bufferProvider.releaseBuffer = NULL; + mConfig.inputCfg.accessMode = EFFECT_BUFFER_ACCESS_READ; + if (mConfig.inputCfg.buffer.raw != mConfig.outputCfg.buffer.raw) { + mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_ACCUMULATE; + } else { + mConfig.outputCfg.accessMode = EFFECT_BUFFER_ACCESS_WRITE; + } + mConfig.inputCfg.mask = EFFECT_CONFIG_ALL; + mConfig.outputCfg.mask = EFFECT_CONFIG_ALL; + mConfig.inputCfg.buffer.frameCount = thread->frameCount(); + mConfig.outputCfg.buffer.frameCount = mConfig.inputCfg.buffer.frameCount; + + ALOGV(""configure() %p thread %p buffer %p framecount %zu"", + this, thread.get(), mConfig.inputCfg.buffer.raw, mConfig.inputCfg.buffer.frameCount); + + status_t cmdStatus; + size = sizeof(int); + status = (*mEffectInterface)->command(mEffectInterface, + EFFECT_CMD_SET_CONFIG, + sizeof(effect_config_t), + &mConfig, + &size, + &cmdStatus); + if (status == 0) { + status = cmdStatus; + } + + if (status == 0 && + (memcmp(&mDescriptor.type, SL_IID_VISUALIZATION, sizeof(effect_uuid_t)) == 0)) { + uint32_t buf32[sizeof(effect_param_t) / sizeof(uint32_t) + 2]; + effect_param_t *p = (effect_param_t *)buf32; + + p->psize = sizeof(uint32_t); + p->vsize = sizeof(uint32_t); + size = sizeof(int); + *(int32_t *)p->data = VISUALIZER_PARAM_LATENCY; + + uint32_t latency = 0; + PlaybackThread *pbt = thread->mAudioFlinger->checkPlaybackThread_l(thread->mId); + if (pbt != NULL) { + latency = pbt->latency_l(); + } + + *((int32_t *)p->data + 1)= latency; + (*mEffectInterface)->command(mEffectInterface, + EFFECT_CMD_SET_PARAM, + sizeof(effect_param_t) + 8, + &buf32, + &size, + &cmdStatus); + } + + mMaxDisableWaitCnt = (MAX_DISABLE_TIME_MS * mConfig.outputCfg.samplingRate) / + (1000 * mConfig.outputCfg.buffer.frameCount); + +exit: + mStatus = status; + return status; +} +","@@ -543,6 +543,13 @@ + + return NO_ERROR; + } + ++// round up delta valid if value and divisor are positive. ++template ++static T roundUpDelta(const T &value, const T &divisor) { ++ T remainder = value % divisor; ++ return remainder == 0 ? 0 : divisor - remainder; ++} ++ + status_t AudioFlinger::EffectModule::command(uint32_t cmdCode, + uint32_t cmdSize, + void *pCmdData, +@@ -564,6 +571,22 @@ + + android_errorWriteLog(0x534e4554, ""29251553""); + return -EINVAL; + } ++ if ((cmdCode == EFFECT_CMD_SET_PARAM ++ || cmdCode == EFFECT_CMD_SET_PARAM_DEFERRED) && // DEFERRED not generally used ++ (sizeof(effect_param_t) > cmdSize ++ || ((effect_param_t *)pCmdData)->psize > cmdSize ++ - sizeof(effect_param_t) ++ || ((effect_param_t *)pCmdData)->vsize > cmdSize ++ - sizeof(effect_param_t) ++ - ((effect_param_t *)pCmdData)->psize ++ || roundUpDelta(((effect_param_t *)pCmdData)->psize, (uint32_t)sizeof(int)) > ++ cmdSize ++ - sizeof(effect_param_t) ++ - ((effect_param_t *)pCmdData)->psize ++ - ((effect_param_t *)pCmdData)->vsize)) { ++ android_errorWriteLog(0x534e4554, ""30204301""); ++ return -EINVAL; ++ } + status_t status = (*mEffectInterface)->command(mEffectInterface, + cmdCode, + cmdSize, +",818,1149,2048 +438,"void Splash::scaleImageYuXd(SplashImageSource src, void *srcData, + SplashColorMode srcMode, int nComps, + GBool srcAlpha, int srcWidth, int srcHeight, + int scaledWidth, int scaledHeight, + SplashBitmap *dest) { + Guchar *lineBuf, *alphaLineBuf; + Guint pix[splashMaxColorComps]; + Guint alpha; + Guchar *destPtr0, *destPtr, *destAlphaPtr0, *destAlphaPtr; + int yp, yq, xp, xq, yt, y, yStep, xt, x, xStep, xx, xxa, d, d0, d1; + int i, j; + + yp = scaledHeight / srcHeight; + yq = scaledHeight % srcHeight; + + xp = srcWidth / scaledWidth; + xq = srcWidth % scaledWidth; + + lineBuf = (Guchar *)gmallocn(srcWidth, nComps); + if (srcAlpha) { + alphaLineBuf = (Guchar *)gmalloc(srcWidth); + } else { + alphaLineBuf = NULL; + } + + yt = 0; + + destPtr0 = dest->data; + destAlphaPtr0 = dest->alpha; + for (y = 0; y < srcHeight; ++y) { + + if ((yt += yq) >= srcHeight) { + yt -= srcHeight; + yStep = yp + 1; + } else { + yStep = yp; + } + + (*src)(srcData, lineBuf, alphaLineBuf); + + xt = 0; + d0 = (1 << 23) / xp; + d1 = (1 << 23) / (xp + 1); + + xx = xxa = 0; + for (x = 0; x < scaledWidth; ++x) { + + if ((xt += xq) >= scaledWidth) { + xt -= scaledWidth; + xStep = xp + 1; + d = d1; + } else { + xStep = xp; + d = d0; + } + + for (i = 0; i < nComps; ++i) { + pix[i] = 0; + } + for (i = 0; i < xStep; ++i) { + for (j = 0; j < nComps; ++j, ++xx) { + pix[j] += lineBuf[xx]; + } + } + for (i = 0; i < nComps; ++i) { + pix[i] = (pix[i] * d) >> 23; + } + + switch (srcMode) { + case splashModeMono1: // mono1 is not allowed + break; + case splashModeMono8: + for (i = 0; i < yStep; ++i) { + destPtr = destPtr0 + (i * scaledWidth + x) * nComps; + *destPtr++ = (Guchar)pix[0]; + } + break; + case splashModeRGB8: + for (i = 0; i < yStep; ++i) { + destPtr = destPtr0 + (i * scaledWidth + x) * nComps; + *destPtr++ = (Guchar)pix[0]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[2]; + } + break; + case splashModeXBGR8: + for (i = 0; i < yStep; ++i) { + destPtr = destPtr0 + (i * scaledWidth + x) * nComps; + *destPtr++ = (Guchar)pix[2]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[0]; + *destPtr++ = (Guchar)255; + } + break; + case splashModeBGR8: + for (i = 0; i < yStep; ++i) { + destPtr = destPtr0 + (i * scaledWidth + x) * nComps; + *destPtr++ = (Guchar)pix[2]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[0]; + } + break; +#if SPLASH_CMYK + case splashModeCMYK8: + for (i = 0; i < yStep; ++i) { + destPtr = destPtr0 + (i * scaledWidth + x) * nComps; + *destPtr++ = (Guchar)pix[0]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[2]; + *destPtr++ = (Guchar)pix[3]; + } + break; + case splashModeDeviceN8: + for (i = 0; i < yStep; ++i) { + destPtr = destPtr0 + (i * scaledWidth + x) * nComps; + for (int cp = 0; cp < SPOT_NCOMPS+4; cp++) + *destPtr++ = (Guchar)pix[cp]; + } + break; +#endif + } + + if (srcAlpha) { + alpha = 0; + for (i = 0; i < xStep; ++i, ++xxa) { + alpha += alphaLineBuf[xxa]; + } + alpha = (alpha * d) >> 23; + for (i = 0; i < yStep; ++i) { + destAlphaPtr = destAlphaPtr0 + i * scaledWidth + x; + *destAlphaPtr = (Guchar)alpha; + } + } + } + + destPtr0 += yStep * scaledWidth * nComps; + if (srcAlpha) { + destAlphaPtr0 += yStep * scaledWidth; + } + } + + gfree(alphaLineBuf); + gfree(lineBuf); +} +",0,"void Splash::scaleImageYuXd(SplashImageSource src, void *srcData, + SplashColorMode srcMode, int nComps, + GBool srcAlpha, int srcWidth, int srcHeight, + int scaledWidth, int scaledHeight, + SplashBitmap *dest) { + Guchar *lineBuf, *alphaLineBuf; + Guint pix[splashMaxColorComps]; + Guint alpha; + Guchar *destPtr0, *destPtr, *destAlphaPtr0, *destAlphaPtr; + int yp, yq, xp, xq, yt, y, yStep, xt, x, xStep, xx, xxa, d, d0, d1; + int i, j; + + yp = scaledHeight / srcHeight; + yq = scaledHeight % srcHeight; + + xp = srcWidth / scaledWidth; + xq = srcWidth % scaledWidth; + + lineBuf = (Guchar *)gmallocn(srcWidth, nComps); + if (srcAlpha) { + alphaLineBuf = (Guchar *)gmalloc(srcWidth); + } else { + alphaLineBuf = NULL; + } + + yt = 0; + + destPtr0 = dest->data; + destAlphaPtr0 = dest->alpha; + for (y = 0; y < srcHeight; ++y) { + + if ((yt += yq) >= srcHeight) { + yt -= srcHeight; + yStep = yp + 1; + } else { + yStep = yp; + } + + (*src)(srcData, lineBuf, alphaLineBuf); + + xt = 0; + d0 = (1 << 23) / xp; + d1 = (1 << 23) / (xp + 1); + + xx = xxa = 0; + for (x = 0; x < scaledWidth; ++x) { + + if ((xt += xq) >= scaledWidth) { + xt -= scaledWidth; + xStep = xp + 1; + d = d1; + } else { + xStep = xp; + d = d0; + } + + for (i = 0; i < nComps; ++i) { + pix[i] = 0; + } + for (i = 0; i < xStep; ++i) { + for (j = 0; j < nComps; ++j, ++xx) { + pix[j] += lineBuf[xx]; + } + } + for (i = 0; i < nComps; ++i) { + pix[i] = (pix[i] * d) >> 23; + } + + switch (srcMode) { + case splashModeMono1: // mono1 is not allowed + break; + case splashModeMono8: + for (i = 0; i < yStep; ++i) { + destPtr = destPtr0 + (i * scaledWidth + x) * nComps; + *destPtr++ = (Guchar)pix[0]; + } + break; + case splashModeRGB8: + for (i = 0; i < yStep; ++i) { + destPtr = destPtr0 + (i * scaledWidth + x) * nComps; + *destPtr++ = (Guchar)pix[0]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[2]; + } + break; + case splashModeXBGR8: + for (i = 0; i < yStep; ++i) { + destPtr = destPtr0 + (i * scaledWidth + x) * nComps; + *destPtr++ = (Guchar)pix[2]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[0]; + *destPtr++ = (Guchar)255; + } + break; + case splashModeBGR8: + for (i = 0; i < yStep; ++i) { + destPtr = destPtr0 + (i * scaledWidth + x) * nComps; + *destPtr++ = (Guchar)pix[2]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[0]; + } + break; +#if SPLASH_CMYK + case splashModeCMYK8: + for (i = 0; i < yStep; ++i) { + destPtr = destPtr0 + (i * scaledWidth + x) * nComps; + *destPtr++ = (Guchar)pix[0]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[2]; + *destPtr++ = (Guchar)pix[3]; + } + break; + case splashModeDeviceN8: + for (i = 0; i < yStep; ++i) { + destPtr = destPtr0 + (i * scaledWidth + x) * nComps; + for (int cp = 0; cp < SPOT_NCOMPS+4; cp++) + *destPtr++ = (Guchar)pix[cp]; + } + break; +#endif + } + + if (srcAlpha) { + alpha = 0; + for (i = 0; i < xStep; ++i, ++xxa) { + alpha += alphaLineBuf[xxa]; + } + alpha = (alpha * d) >> 23; + for (i = 0; i < yStep; ++i) { + destAlphaPtr = destAlphaPtr0 + i * scaledWidth + x; + *destAlphaPtr = (Guchar)alpha; + } + } + } + + destPtr0 += yStep * scaledWidth * nComps; + if (srcAlpha) { + destAlphaPtr0 += yStep * scaledWidth; + } + } + + gfree(alphaLineBuf); + gfree(lineBuf); +} +","@@ -2955,7 +2955,7 @@ void Splash::arbitraryTransformMask(SplashImageMaskSource src, void *srcData, + scaledMask = scaleMask(src, srcData, srcWidth, srcHeight, + scaledWidth, scaledHeight); + if (scaledMask->data == NULL) { +- error(errInternal, -1, ""scaledMask->data is NULL in Splash::scaleMaskYuXu""); ++ error(errInternal, -1, ""scaledMask->data is NULL in Splash::arbitraryTransformMask""); + delete scaledMask; + return; + } +@@ -3461,11 +3461,15 @@ void Splash::blitMask(SplashBitmap *src, int xDest, int yDest, + + w = src->getWidth(); + h = src->getHeight(); ++ p = src->getDataPtr(); ++ if (p == NULL) { ++ error(errInternal, -1, ""src->getDataPtr() is NULL in Splash::blitMask""); ++ return; ++ } + if (vectorAntialias && clipRes != splashClipAllInside) { + pipeInit(&pipe, xDest, yDest, state->fillPattern, NULL, + (Guchar)splashRound(state->fillAlpha * 255), gTrue, gFalse); + drawAAPixelInit(); +- p = src->getDataPtr(); + for (y = 0; y < h; ++y) { + for (x = 0; x < w; ++x) { + pipe.shape = *p++; +@@ -3475,7 +3479,6 @@ void Splash::blitMask(SplashBitmap *src, int xDest, int yDest, + } else { + pipeInit(&pipe, xDest, yDest, state->fillPattern, NULL, + (Guchar)splashRound(state->fillAlpha * 255), gTrue, gFalse); +- p = src->getDataPtr(); + if (clipRes == splashClipAllInside) { + for (y = 0; y < h; ++y) { + pipeSetXY(&pipe, xDest, yDest + y);",1302,1633,2048 +6087,"cms_envelopeddata_verify(krb5_context context, + pkinit_plg_crypto_context plg_cryptoctx, + pkinit_req_crypto_context req_cryptoctx, + pkinit_identity_crypto_context id_cryptoctx, + krb5_preauthtype pa_type, + int require_crl_checking, + unsigned char *enveloped_data, + unsigned int enveloped_data_len, + unsigned char **data, + unsigned int *data_len) +{ + krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED; + PKCS7 *p7 = NULL; + BIO *out = NULL; + int i = 0; + unsigned int size = 0; + const unsigned char *p = enveloped_data; + unsigned int tmp_buf_len = 0, tmp_buf2_len = 0, vfy_buf_len = 0; + unsigned char *tmp_buf = NULL, *tmp_buf2 = NULL, *vfy_buf = NULL; + int msg_type = 0; + +#ifdef DEBUG_ASN1 + print_buffer_bin(enveloped_data, enveloped_data_len, + ""/tmp/client_envelopeddata""); +#endif + /* decode received PKCS7 message */ + if ((p7 = d2i_PKCS7(NULL, &p, (int)enveloped_data_len)) == NULL) { + retval = oerr(context, 0, _(""Failed to decode PKCS7"")); + goto cleanup; + } + + /* verify that the received message is PKCS7 EnvelopedData message */ + if (OBJ_obj2nid(p7->type) != NID_pkcs7_enveloped) { + pkiDebug(""Expected id-enveloped PKCS7 msg (received type = %d)\n"", + OBJ_obj2nid(p7->type)); + krb5_set_error_message(context, retval, ""wrong oid\n""); + goto cleanup; + } + + /* decrypt received PKCS7 message */ + out = BIO_new(BIO_s_mem()); + if (pkcs7_decrypt(context, id_cryptoctx, p7, out)) { + pkiDebug(""PKCS7 decryption successful\n""); + } else { + retval = oerr(context, 0, _(""Failed to decrypt PKCS7 message"")); + goto cleanup; + } + + /* transfer the decoded PKCS7 SignedData message into a separate buffer */ + for (;;) { + if ((tmp_buf = realloc(tmp_buf, size + 1024 * 10)) == NULL) + goto cleanup; + i = BIO_read(out, &(tmp_buf[size]), 1024 * 10); + if (i <= 0) + break; + else + size += i; + } + tmp_buf_len = size; + +#ifdef DEBUG_ASN1 + print_buffer_bin(tmp_buf, tmp_buf_len, ""/tmp/client_enc_keypack""); +#endif + /* verify PKCS7 SignedData message */ + switch (pa_type) { + case KRB5_PADATA_PK_AS_REP: + msg_type = CMS_ENVEL_SERVER; + + break; + case KRB5_PADATA_PK_AS_REP_OLD: + msg_type = CMS_SIGN_DRAFT9; + break; + default: + pkiDebug(""%s: unrecognized pa_type = %d\n"", __FUNCTION__, pa_type); + retval = KRB5KDC_ERR_PREAUTH_FAILED; + goto cleanup; + } + /* + * If this is the RFC style, wrap the signed data to make + * decoding easier in the verify routine. + * For draft9-compatible, we don't do anything because it + * is already wrapped. + */ + if (msg_type == CMS_ENVEL_SERVER) { + retval = wrap_signeddata(tmp_buf, tmp_buf_len, + &tmp_buf2, &tmp_buf2_len); + if (retval) { + pkiDebug(""failed to encode signeddata\n""); + goto cleanup; + } + vfy_buf = tmp_buf2; + vfy_buf_len = tmp_buf2_len; + + } else { + vfy_buf = tmp_buf; + vfy_buf_len = tmp_buf_len; + } + +#ifdef DEBUG_ASN1 + print_buffer_bin(vfy_buf, vfy_buf_len, ""/tmp/client_enc_keypack2""); +#endif + + retval = cms_signeddata_verify(context, plg_cryptoctx, req_cryptoctx, + id_cryptoctx, msg_type, + require_crl_checking, + vfy_buf, vfy_buf_len, + data, data_len, NULL, NULL, NULL); + + if (!retval) + pkiDebug(""PKCS7 Verification Success\n""); + else { + pkiDebug(""PKCS7 Verification Failure\n""); + goto cleanup; + } + + retval = 0; + +cleanup: + + if (p7 != NULL) + PKCS7_free(p7); + if (out != NULL) + BIO_free(out); + free(tmp_buf); + free(tmp_buf2); + + return retval; +} +",0,"cms_envelopeddata_verify(krb5_context context, + pkinit_plg_crypto_context plg_cryptoctx, + pkinit_req_crypto_context req_cryptoctx, + pkinit_identity_crypto_context id_cryptoctx, + krb5_preauthtype pa_type, + int require_crl_checking, + unsigned char *enveloped_data, + unsigned int enveloped_data_len, + unsigned char **data, + unsigned int *data_len) +{ + krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED; + PKCS7 *p7 = NULL; + BIO *out = NULL; + int i = 0; + unsigned int size = 0; + const unsigned char *p = enveloped_data; + unsigned int tmp_buf_len = 0, tmp_buf2_len = 0, vfy_buf_len = 0; + unsigned char *tmp_buf = NULL, *tmp_buf2 = NULL, *vfy_buf = NULL; + int msg_type = 0; + +#ifdef DEBUG_ASN1 + print_buffer_bin(enveloped_data, enveloped_data_len, + ""/tmp/client_envelopeddata""); +#endif + /* decode received PKCS7 message */ + if ((p7 = d2i_PKCS7(NULL, &p, (int)enveloped_data_len)) == NULL) { + retval = oerr(context, 0, _(""Failed to decode PKCS7"")); + goto cleanup; + } + + /* verify that the received message is PKCS7 EnvelopedData message */ + if (OBJ_obj2nid(p7->type) != NID_pkcs7_enveloped) { + pkiDebug(""Expected id-enveloped PKCS7 msg (received type = %d)\n"", + OBJ_obj2nid(p7->type)); + krb5_set_error_message(context, retval, ""wrong oid\n""); + goto cleanup; + } + + /* decrypt received PKCS7 message */ + out = BIO_new(BIO_s_mem()); + if (pkcs7_decrypt(context, id_cryptoctx, p7, out)) { + pkiDebug(""PKCS7 decryption successful\n""); + } else { + retval = oerr(context, 0, _(""Failed to decrypt PKCS7 message"")); + goto cleanup; + } + + /* transfer the decoded PKCS7 SignedData message into a separate buffer */ + for (;;) { + if ((tmp_buf = realloc(tmp_buf, size + 1024 * 10)) == NULL) + goto cleanup; + i = BIO_read(out, &(tmp_buf[size]), 1024 * 10); + if (i <= 0) + break; + else + size += i; + } + tmp_buf_len = size; + +#ifdef DEBUG_ASN1 + print_buffer_bin(tmp_buf, tmp_buf_len, ""/tmp/client_enc_keypack""); +#endif + /* verify PKCS7 SignedData message */ + switch (pa_type) { + case KRB5_PADATA_PK_AS_REP: + msg_type = CMS_ENVEL_SERVER; + + break; + case KRB5_PADATA_PK_AS_REP_OLD: + msg_type = CMS_SIGN_DRAFT9; + break; + default: + pkiDebug(""%s: unrecognized pa_type = %d\n"", __FUNCTION__, pa_type); + retval = KRB5KDC_ERR_PREAUTH_FAILED; + goto cleanup; + } + /* + * If this is the RFC style, wrap the signed data to make + * decoding easier in the verify routine. + * For draft9-compatible, we don't do anything because it + * is already wrapped. + */ + if (msg_type == CMS_ENVEL_SERVER) { + retval = wrap_signeddata(tmp_buf, tmp_buf_len, + &tmp_buf2, &tmp_buf2_len); + if (retval) { + pkiDebug(""failed to encode signeddata\n""); + goto cleanup; + } + vfy_buf = tmp_buf2; + vfy_buf_len = tmp_buf2_len; + + } else { + vfy_buf = tmp_buf; + vfy_buf_len = tmp_buf_len; + } + +#ifdef DEBUG_ASN1 + print_buffer_bin(vfy_buf, vfy_buf_len, ""/tmp/client_enc_keypack2""); +#endif + + retval = cms_signeddata_verify(context, plg_cryptoctx, req_cryptoctx, + id_cryptoctx, msg_type, + require_crl_checking, + vfy_buf, vfy_buf_len, + data, data_len, NULL, NULL, NULL); + + if (!retval) + pkiDebug(""PKCS7 Verification Success\n""); + else { + pkiDebug(""PKCS7 Verification Failure\n""); + goto cleanup; + } + + retval = 0; + +cleanup: + + if (p7 != NULL) + PKCS7_free(p7); + if (out != NULL) + BIO_free(out); + free(tmp_buf); + free(tmp_buf2); + + return retval; +} +","@@ -5002,33 +5002,29 @@ crypto_retrieve_X509_key_usage(krb5_context context, + return retval; + } + +-/* +- * Return a string format of an X509_NAME in buf where +- * size is an in/out parameter. On input it is the size +- * of the buffer, and on output it is the actual length +- * of the name. +- * If buf is NULL, returns the length req'd to hold name +- */ +-static char * +-X509_NAME_oneline_ex(X509_NAME * a, +- char *buf, +- unsigned int *size, +- unsigned long flag) ++static krb5_error_code ++rfc2253_name(X509_NAME *name, char **str_out) + { +- BIO *out = NULL; ++ BIO *b = NULL; ++ char *str; + +- out = BIO_new(BIO_s_mem ()); +- if (X509_NAME_print_ex(out, a, 0, flag) > 0) { +- if (buf != NULL && (*size) > (unsigned int) BIO_number_written(out)) { +- memset(buf, 0, *size); +- BIO_read(out, buf, (int) BIO_number_written(out)); +- } +- else { +- *size = BIO_number_written(out); +- } +- } +- BIO_free(out); +- return (buf); ++ *str_out = NULL; ++ b = BIO_new(BIO_s_mem()); ++ if (b == NULL) ++ return ENOMEM; ++ if (X509_NAME_print_ex(b, name, 0, XN_FLAG_SEP_COMMA_PLUS) < 0) ++ goto error; ++ str = calloc(BIO_number_written(b) + 1, 1); ++ if (str == NULL) ++ goto error; ++ BIO_read(b, str, BIO_number_written(b)); ++ BIO_free(b); ++ *str_out = str; ++ return 0; ++ ++error: ++ BIO_free(b); ++ return ENOMEM; + } + + /* +@@ -5094,32 +5090,19 @@ get_matching_data(krb5_context context, + pkinit_cert_matching_data *md = NULL; + krb5_principal *pkinit_sans = NULL, *upn_sans = NULL; + size_t i, j; +- char buf[DN_BUF_LEN]; +- unsigned int bufsize = sizeof(buf); + + *md_out = NULL; + + md = calloc(1, sizeof(*md)); + if (md == NULL) + goto cleanup; + +- /* Get the subject name (in rfc2253 format). */ +- X509_NAME_oneline_ex(X509_get_subject_name(cert), buf, &bufsize, +- XN_FLAG_SEP_COMMA_PLUS); +- md->subject_dn = strdup(buf); +- if (md->subject_dn == NULL) { +- ret = ENOMEM; ++ ret = rfc2253_name(X509_get_subject_name(cert), &md->subject_dn); ++ if (ret) + goto cleanup; +- } +- +- /* Get the issuer name (in rfc2253 format). */ +- X509_NAME_oneline_ex(X509_get_issuer_name(cert), buf, &bufsize, +- XN_FLAG_SEP_COMMA_PLUS); +- md->issuer_dn = strdup(buf); +- if (md->issuer_dn == NULL) { +- ret = ENOMEM; ++ ret = rfc2253_name(X509_get_issuer_name(cert), &md->issuer_dn); ++ if (ret) + goto cleanup; +- } + + /* Get the SAN data. */ + ret = crypto_retrieve_X509_sans(context, plg_cryptoctx, req_cryptoctx,",1042,1373,2048 +17844,"vmnc_handle_packet (GstVMncDec * dec, const guint8 * data, int len, + gboolean decode) +{ + int type; + int offset = 0; + + if (len < 4) { + GST_LOG_OBJECT (dec, ""Packet too short""); + return ERROR_INSUFFICIENT_DATA; + } + + type = data[0]; + + switch (type) { + case 0: + { + int numrect = RFB_GET_UINT16 (data + 2); + int i; + int read; + + offset = 4; + + for (i = 0; i < numrect; i++) { + struct RfbRectangle r; + rectangle_handler handler; + + if (len < offset + 12) { + GST_LOG_OBJECT (dec, + ""Packet too short for rectangle header: %d < %d"", + len, offset + 12); + return ERROR_INSUFFICIENT_DATA; + } + GST_LOG_OBJECT (dec, ""Reading rectangle %d"", i); + r.x = RFB_GET_UINT16 (data + offset); + r.y = RFB_GET_UINT16 (data + offset + 2); + r.width = RFB_GET_UINT16 (data + offset + 4); + r.height = RFB_GET_UINT16 (data + offset + 6); + r.type = RFB_GET_UINT32 (data + offset + 8); + + if (r.type != TYPE_WMVi) { + /* We must have a WMVi packet to initialise things before we can + * continue */ + if (!dec->have_format) { + GST_WARNING_OBJECT (dec, ""Received packet without WMVi: %d"", + r.type); + return ERROR_INVALID; + } + if (r.x + r.width > dec->format.width || + r.y + r.height > dec->format.height) { + GST_WARNING_OBJECT (dec, ""Rectangle out of range, type %d"", r.type); + return ERROR_INVALID; + } + } + + switch (r.type) { + handler = vmnc_handle_wmve_rectangle; + break; + case TYPE_WMVf: + handler = vmnc_handle_wmvf_rectangle; + break; + case TYPE_WMVg: + handler = vmnc_handle_wmvg_rectangle; + break; + case TYPE_WMVh: + handler = vmnc_handle_wmvh_rectangle; + break; + case TYPE_WMVi: + handler = vmnc_handle_wmvi_rectangle; + break; + case TYPE_WMVj: + handler = vmnc_handle_wmvj_rectangle; + break; + case TYPE_RAW: + handler = vmnc_handle_raw_rectangle; + break; + case TYPE_COPY: + handler = vmnc_handle_copy_rectangle; + break; + case TYPE_HEXTILE: + handler = vmnc_handle_hextile_rectangle; + break; + default: + GST_WARNING_OBJECT (dec, ""Unknown rectangle type""); + return ERROR_INVALID; + } + + read = handler (dec, &r, data + offset + 12, len - offset - 12, decode); + if (read < 0) { + GST_DEBUG_OBJECT (dec, ""Error calling rectangle handler\n""); + return read; + } + offset += 12 + read; + } + break; + } + default: + GST_WARNING_OBJECT (dec, ""Packet type unknown: %d"", type); + return ERROR_INVALID; + } + + return offset; +} +",1,"vmnc_handle_packet (GstVMncDec * dec, const guint8 * data, int len, + gboolean decode) +{ + int type; + int offset = 0; + + if (len < 4) { + GST_LOG_OBJECT (dec, ""Packet too short""); + return ERROR_INSUFFICIENT_DATA; + } + + type = data[0]; + + switch (type) { + case 0: + { + int numrect = RFB_GET_UINT16 (data + 2); + int i; + int read; + + offset = 4; + + for (i = 0; i < numrect; i++) { + struct RfbRectangle r; + rectangle_handler handler; + + if (len < offset + 12) { + GST_LOG_OBJECT (dec, + ""Packet too short for rectangle header: %d < %d"", + len, offset + 12); + return ERROR_INSUFFICIENT_DATA; + } + GST_LOG_OBJECT (dec, ""Reading rectangle %d"", i); + r.x = RFB_GET_UINT16 (data + offset); + r.y = RFB_GET_UINT16 (data + offset + 2); + r.width = RFB_GET_UINT16 (data + offset + 4); + r.height = RFB_GET_UINT16 (data + offset + 6); + r.type = RFB_GET_UINT32 (data + offset + 8); + + if (r.type != TYPE_WMVi) { + /* We must have a WMVi packet to initialise things before we can + * continue */ + if (!dec->have_format) { + GST_WARNING_OBJECT (dec, ""Received packet without WMVi: %d"", + r.type); + return ERROR_INVALID; + } + if (r.x + r.width > dec->format.width || + r.y + r.height > dec->format.height) { + GST_WARNING_OBJECT (dec, ""Rectangle out of range, type %d"", r.type); + return ERROR_INVALID; + } + } else if (r.width > 16384 || r.height > 16384) { + GST_WARNING_OBJECT (dec, ""Width or height too high: %ux%u"", r.width, + r.height); + return ERROR_INVALID; + } + + switch (r.type) { + handler = vmnc_handle_wmve_rectangle; + break; + case TYPE_WMVf: + handler = vmnc_handle_wmvf_rectangle; + break; + case TYPE_WMVg: + handler = vmnc_handle_wmvg_rectangle; + break; + case TYPE_WMVh: + handler = vmnc_handle_wmvh_rectangle; + break; + case TYPE_WMVi: + handler = vmnc_handle_wmvi_rectangle; + break; + case TYPE_WMVj: + handler = vmnc_handle_wmvj_rectangle; + break; + case TYPE_RAW: + handler = vmnc_handle_raw_rectangle; + break; + case TYPE_COPY: + handler = vmnc_handle_copy_rectangle; + break; + case TYPE_HEXTILE: + handler = vmnc_handle_hextile_rectangle; + break; + default: + GST_WARNING_OBJECT (dec, ""Unknown rectangle type""); + return ERROR_INVALID; + } + + read = handler (dec, &r, data + offset + 12, len - offset - 12, decode); + if (read < 0) { + GST_DEBUG_OBJECT (dec, ""Error calling rectangle handler\n""); + return read; + } + offset += 12 + read; + } + break; + } + default: + GST_WARNING_OBJECT (dec, ""Packet type unknown: %d"", type); + return ERROR_INVALID; + } + + return offset; +} +","@@ -260,7 +260,7 @@ vmnc_handle_wmvi_rectangle (GstVMncDec * dec, struct RfbRectangle *rect, + gst_video_codec_state_unref (state); + + g_free (dec->imagedata); +- dec->imagedata = g_malloc (dec->format.width * dec->format.height * ++ dec->imagedata = g_malloc0 (dec->format.width * dec->format.height * + dec->format.bytes_per_pixel); + GST_DEBUG_OBJECT (dec, ""Allocated image data at %p"", dec->imagedata); + +@@ -790,6 +790,10 @@ vmnc_handle_packet (GstVMncDec * dec, const guint8 * data, int len, + GST_WARNING_OBJECT (dec, ""Rectangle out of range, type %d"", r.type); + return ERROR_INVALID; + } ++ } else if (r.width > 16384 || r.height > 16384) { ++ GST_WARNING_OBJECT (dec, ""Width or height too high: %ux%u"", r.width, ++ r.height); ++ return ERROR_INVALID; + } + + switch (r.type) {",736,1067,2048 +7033,"TIFFSeek(TIFF* tif, uint32 row, uint16 sample ) +{ + register TIFFDirectory *td = &tif->tif_dir; + uint32 strip; + int whole_strip; + tmsize_t read_ahead = 0; + + /* + ** Establish what strip we are working from. + */ + if (row >= td->td_imagelength) { /* out of range */ + TIFFErrorExt(tif->tif_clientdata, tif->tif_name, + ""%lu: Row out of range, max %lu"", + (unsigned long) row, + (unsigned long) td->td_imagelength); + return (0); + } + if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { + if (sample >= td->td_samplesperpixel) { + TIFFErrorExt(tif->tif_clientdata, tif->tif_name, + ""%lu: Sample out of range, max %lu"", + (unsigned long) sample, (unsigned long) td->td_samplesperpixel); + return (0); + } + strip = (uint32)sample*td->td_stripsperimage + row/td->td_rowsperstrip; + } else + strip = row / td->td_rowsperstrip; + + /* + * Do we want to treat this strip as one whole chunk or + * read it a few lines at a time? + */ +#if defined(CHUNKY_STRIP_READ_SUPPORT) + if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount) + return 0; + whole_strip = tif->tif_dir.td_stripbytecount[strip] < 10 + || isMapped(tif); +#else + whole_strip = 1; +#endif + + if( !whole_strip ) + { + read_ahead = tif->tif_scanlinesize * 16 + 5000; + } + + /* + * If we haven't loaded this strip, do so now, possibly + * only reading the first part. + */ + if (strip != tif->tif_curstrip) { /* different strip, refill */ + + if( whole_strip ) + { + if (!TIFFFillStrip(tif, strip)) + return (0); + } + else + { + if( !TIFFFillStripPartial(tif,strip,read_ahead,1) ) + return 0; + } + } + + /* + ** If we already have some data loaded, do we need to read some more? + */ + else if( !whole_strip ) + { + if( ((tif->tif_rawdata + tif->tif_rawdataloaded) - tif->tif_rawcp) < read_ahead + && (uint64) tif->tif_rawdataoff+tif->tif_rawdataloaded < td->td_stripbytecount[strip] ) + { + if( !TIFFFillStripPartial(tif,strip,read_ahead,0) ) + return 0; + } + } + + if (row < tif->tif_row) { + /* + * Moving backwards within the same strip: backup + * to the start and then decode forward (below). + * + * NB: If you're planning on lots of random access within a + * strip, it's better to just read and decode the entire + * strip, and then access the decoded data in a random fashion. + */ + + if( tif->tif_rawdataoff != 0 ) + { + if( !TIFFFillStripPartial(tif,strip,read_ahead,1) ) + return 0; + } + else + { + if (!TIFFStartStrip(tif, strip)) + return (0); + } + } + + if (row != tif->tif_row) { + /* + * Seek forward to the desired row. + */ + + /* TODO: Will this really work with partial buffers? */ + + if (!(*tif->tif_seek)(tif, row - tif->tif_row)) + return (0); + tif->tif_row = row; + } + + return (1); +} +",0,"TIFFSeek(TIFF* tif, uint32 row, uint16 sample ) +{ + register TIFFDirectory *td = &tif->tif_dir; + uint32 strip; + int whole_strip; + tmsize_t read_ahead = 0; + + /* + ** Establish what strip we are working from. + */ + if (row >= td->td_imagelength) { /* out of range */ + TIFFErrorExt(tif->tif_clientdata, tif->tif_name, + ""%lu: Row out of range, max %lu"", + (unsigned long) row, + (unsigned long) td->td_imagelength); + return (0); + } + if (td->td_planarconfig == PLANARCONFIG_SEPARATE) { + if (sample >= td->td_samplesperpixel) { + TIFFErrorExt(tif->tif_clientdata, tif->tif_name, + ""%lu: Sample out of range, max %lu"", + (unsigned long) sample, (unsigned long) td->td_samplesperpixel); + return (0); + } + strip = (uint32)sample*td->td_stripsperimage + row/td->td_rowsperstrip; + } else + strip = row / td->td_rowsperstrip; + + /* + * Do we want to treat this strip as one whole chunk or + * read it a few lines at a time? + */ +#if defined(CHUNKY_STRIP_READ_SUPPORT) + if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount) + return 0; + whole_strip = tif->tif_dir.td_stripbytecount[strip] < 10 + || isMapped(tif); +#else + whole_strip = 1; +#endif + + if( !whole_strip ) + { + read_ahead = tif->tif_scanlinesize * 16 + 5000; + } + + /* + * If we haven't loaded this strip, do so now, possibly + * only reading the first part. + */ + if (strip != tif->tif_curstrip) { /* different strip, refill */ + + if( whole_strip ) + { + if (!TIFFFillStrip(tif, strip)) + return (0); + } + else + { + if( !TIFFFillStripPartial(tif,strip,read_ahead,1) ) + return 0; + } + } + + /* + ** If we already have some data loaded, do we need to read some more? + */ + else if( !whole_strip ) + { + if( ((tif->tif_rawdata + tif->tif_rawdataloaded) - tif->tif_rawcp) < read_ahead + && (uint64) tif->tif_rawdataoff+tif->tif_rawdataloaded < td->td_stripbytecount[strip] ) + { + if( !TIFFFillStripPartial(tif,strip,read_ahead,0) ) + return 0; + } + } + + if (row < tif->tif_row) { + /* + * Moving backwards within the same strip: backup + * to the start and then decode forward (below). + * + * NB: If you're planning on lots of random access within a + * strip, it's better to just read and decode the entire + * strip, and then access the decoded data in a random fashion. + */ + + if( tif->tif_rawdataoff != 0 ) + { + if( !TIFFFillStripPartial(tif,strip,read_ahead,1) ) + return 0; + } + else + { + if (!TIFFStartStrip(tif, strip)) + return (0); + } + } + + if (row != tif->tif_row) { + /* + * Seek forward to the desired row. + */ + + /* TODO: Will this really work with partial buffers? */ + + if (!(*tif->tif_seek)(tif, row - tif->tif_row)) + return (0); + tif->tif_row = row; + } + + return (1); +} +","@@ -346,7 +346,7 @@ TIFFReadEncodedStrip(TIFF* tif, uint32 strip, void* buf, tmsize_t size) + rowsperstrip=td->td_rowsperstrip; + if (rowsperstrip>td->td_imagelength) + rowsperstrip=td->td_imagelength; +- stripsperplane=((td->td_imagelength+rowsperstrip-1)/rowsperstrip); ++ stripsperplane= TIFFhowmany_32_maxuint_compat(td->td_imagelength, rowsperstrip); + stripinplane=(strip%stripsperplane); + plane=(uint16)(strip/stripsperplane); + rows=td->td_imagelength-stripinplane*rowsperstrip;",895,1226,2048 +17570,"void smp_proc_pair_cmd(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { + uint8_t* p = (uint8_t*)p_data; + uint8_t reason = SMP_ENC_KEY_SIZE; + tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(p_cb->pairing_bda); + + SMP_TRACE_DEBUG(""%s"", __func__); + /* erase all keys if it is slave proc pairing req */ + if (p_dev_rec && (p_cb->role == HCI_ROLE_SLAVE)) + btm_sec_clear_ble_keys(p_dev_rec); + + p_cb->flags |= SMP_PAIR_FLAG_ENC_AFTER_PAIR; + + STREAM_TO_UINT8(p_cb->peer_io_caps, p); + STREAM_TO_UINT8(p_cb->peer_oob_flag, p); + STREAM_TO_UINT8(p_cb->peer_auth_req, p); + STREAM_TO_UINT8(p_cb->peer_enc_size, p); + STREAM_TO_UINT8(p_cb->peer_i_key, p); + STREAM_TO_UINT8(p_cb->peer_r_key, p); + + if (smp_command_has_invalid_parameters(p_cb)) { + reason = SMP_INVALID_PARAMETERS; + smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &reason); + return; + } + + if (pts_test_send_authentication_complete_failure(p_cb)) return; + + if (p_cb->role == HCI_ROLE_SLAVE) { + if (!(p_cb->flags & SMP_PAIR_FLAGS_WE_STARTED_DD)) { + /* peer (master) started pairing sending Pairing Request */ + p_cb->local_i_key = p_cb->peer_i_key; + p_cb->local_r_key = p_cb->peer_r_key; + + p_cb->cb_evt = SMP_SEC_REQUEST_EVT; + } else /* update local i/r key according to pairing request */ + { + /* pairing started with this side (slave) sending Security Request */ + p_cb->local_i_key &= p_cb->peer_i_key; + p_cb->local_r_key &= p_cb->peer_r_key; + p_cb->selected_association_model = smp_select_association_model(p_cb); + + if (p_cb->secure_connections_only_mode_required && + (!(p_cb->le_secure_connections_mode_is_used) || + (p_cb->selected_association_model == + SMP_MODEL_SEC_CONN_JUSTWORKS))) { + SMP_TRACE_ERROR( + ""%s: pairing failed - slave requires secure connection only mode"", + __func__); + reason = SMP_PAIR_AUTH_FAIL; + smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &reason); + return; + } + + if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_OOB) { + if (smp_request_oob_data(p_cb)) return; + } else { + smp_send_pair_rsp(p_cb, NULL); + } + } + } else /* Master receives pairing response */ + { + p_cb->selected_association_model = smp_select_association_model(p_cb); + + if (p_cb->secure_connections_only_mode_required && + (!(p_cb->le_secure_connections_mode_is_used) || + (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_JUSTWORKS))) { + SMP_TRACE_ERROR( + ""Master requires secure connection only mode "" + ""but it can't be provided -> Master fails pairing""); + reason = SMP_PAIR_AUTH_FAIL; + smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &reason); + return; + } + + if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_OOB) { + if (smp_request_oob_data(p_cb)) return; + } else { + smp_decide_association_model(p_cb, NULL); + } + } +} +",0,"void smp_proc_pair_cmd(tSMP_CB* p_cb, tSMP_INT_DATA* p_data) { + uint8_t* p = (uint8_t*)p_data; + uint8_t reason = SMP_ENC_KEY_SIZE; + tBTM_SEC_DEV_REC* p_dev_rec = btm_find_dev(p_cb->pairing_bda); + + SMP_TRACE_DEBUG(""%s"", __func__); + /* erase all keys if it is slave proc pairing req */ + if (p_dev_rec && (p_cb->role == HCI_ROLE_SLAVE)) + btm_sec_clear_ble_keys(p_dev_rec); + + p_cb->flags |= SMP_PAIR_FLAG_ENC_AFTER_PAIR; + + STREAM_TO_UINT8(p_cb->peer_io_caps, p); + STREAM_TO_UINT8(p_cb->peer_oob_flag, p); + STREAM_TO_UINT8(p_cb->peer_auth_req, p); + STREAM_TO_UINT8(p_cb->peer_enc_size, p); + STREAM_TO_UINT8(p_cb->peer_i_key, p); + STREAM_TO_UINT8(p_cb->peer_r_key, p); + + if (smp_command_has_invalid_parameters(p_cb)) { + reason = SMP_INVALID_PARAMETERS; + smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &reason); + return; + } + + if (pts_test_send_authentication_complete_failure(p_cb)) return; + + if (p_cb->role == HCI_ROLE_SLAVE) { + if (!(p_cb->flags & SMP_PAIR_FLAGS_WE_STARTED_DD)) { + /* peer (master) started pairing sending Pairing Request */ + p_cb->local_i_key = p_cb->peer_i_key; + p_cb->local_r_key = p_cb->peer_r_key; + + p_cb->cb_evt = SMP_SEC_REQUEST_EVT; + } else /* update local i/r key according to pairing request */ + { + /* pairing started with this side (slave) sending Security Request */ + p_cb->local_i_key &= p_cb->peer_i_key; + p_cb->local_r_key &= p_cb->peer_r_key; + p_cb->selected_association_model = smp_select_association_model(p_cb); + + if (p_cb->secure_connections_only_mode_required && + (!(p_cb->le_secure_connections_mode_is_used) || + (p_cb->selected_association_model == + SMP_MODEL_SEC_CONN_JUSTWORKS))) { + SMP_TRACE_ERROR( + ""%s: pairing failed - slave requires secure connection only mode"", + __func__); + reason = SMP_PAIR_AUTH_FAIL; + smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &reason); + return; + } + + if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_OOB) { + if (smp_request_oob_data(p_cb)) return; + } else { + smp_send_pair_rsp(p_cb, NULL); + } + } + } else /* Master receives pairing response */ + { + p_cb->selected_association_model = smp_select_association_model(p_cb); + + if (p_cb->secure_connections_only_mode_required && + (!(p_cb->le_secure_connections_mode_is_used) || + (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_JUSTWORKS))) { + SMP_TRACE_ERROR( + ""Master requires secure connection only mode "" + ""but it can't be provided -> Master fails pairing""); + reason = SMP_PAIR_AUTH_FAIL; + smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &reason); + return; + } + + if (p_cb->selected_association_model == SMP_MODEL_SEC_CONN_OOB) { + if (smp_request_oob_data(p_cb)) return; + } else { + smp_decide_association_model(p_cb, NULL); + } + } +} +","@@ -725,13 +725,17 @@ + + uint8_t reason = SMP_INVALID_PARAMETERS; + + SMP_TRACE_DEBUG(""%s"", __func__); +- p_cb->status = *(uint8_t*)p_data; + + if (smp_command_has_invalid_parameters(p_cb)) { ++ if (p_cb->rcvd_cmd_len < 2) { // 1 (opcode) + 1 (Notif Type) bytes ++ android_errorWriteLog(0x534e4554, ""111936834""); ++ } + smp_sm_event(p_cb, SMP_AUTH_CMPL_EVT, &reason); + return; + } + ++ p_cb->status = *(uint8_t*)p_data; ++ + if (p != NULL) { + STREAM_TO_UINT8(p_cb->peer_keypress_notification, p); + } else { +",740,1071,2048 +127,"void JBIG2Stream::readSegments() { + Guint segNum, segFlags, segType, page, segLength; + Guint refFlags, nRefSegs; + Guint *refSegs; + int segDataPos; + int c1, c2, c3; + Guint i; + + while (readULong(&segNum)) { + + if (!readUByte(&segFlags)) { + goto eofError1; + } + segType = segFlags & 0x3f; + + if (!readUByte(&refFlags)) { + goto eofError1; + } + nRefSegs = refFlags >> 5; + if (nRefSegs == 7) { + if ((c1 = curStr->getChar()) == EOF || + (c2 = curStr->getChar()) == EOF || + (c3 = curStr->getChar()) == EOF) { + goto eofError1; + } + refFlags = (refFlags << 24) | (c1 << 16) | (c2 << 8) | c3; + nRefSegs = refFlags & 0x1fffffff; + for (i = 0; i < (nRefSegs + 9) >> 3; ++i) { + c1 = curStr->getChar(); + } + } + + refSegs = (Guint *)gmallocn(nRefSegs, sizeof(Guint)); + if (segNum <= 256) { + for (i = 0; i < nRefSegs; ++i) { + if (!readUByte(&refSegs[i])) { + goto eofError2; + } + } + } else if (segNum <= 65536) { + for (i = 0; i < nRefSegs; ++i) { + if (!readUWord(&refSegs[i])) { + goto eofError2; + } + } + } else { + for (i = 0; i < nRefSegs; ++i) { + if (!readULong(&refSegs[i])) { + goto eofError2; + } + } + } + + if (segFlags & 0x40) { + if (!readULong(&page)) { + goto eofError2; + } + } else { + if (!readUByte(&page)) { + goto eofError2; + } + } + + if (!readULong(&segLength)) { + goto eofError2; + } + + segDataPos = getPos(); + + switch (segType) { + case 0: + if (!readSymbolDictSeg(segNum, segLength, refSegs, nRefSegs)) { + goto syntaxError; + } + break; + case 4: + readTextRegionSeg(segNum, gFalse, gFalse, segLength, refSegs, nRefSegs); + break; + case 6: + readTextRegionSeg(segNum, gTrue, gFalse, segLength, refSegs, nRefSegs); + break; + case 7: + readTextRegionSeg(segNum, gTrue, gTrue, segLength, refSegs, nRefSegs); + break; + case 16: + readPatternDictSeg(segNum, segLength); + break; + case 20: + readHalftoneRegionSeg(segNum, gFalse, gFalse, segLength, + refSegs, nRefSegs); + break; + case 22: + readHalftoneRegionSeg(segNum, gTrue, gFalse, segLength, + refSegs, nRefSegs); + break; + case 23: + readHalftoneRegionSeg(segNum, gTrue, gTrue, segLength, + refSegs, nRefSegs); + break; + case 36: + readGenericRegionSeg(segNum, gFalse, gFalse, segLength); + break; + case 38: + readGenericRegionSeg(segNum, gTrue, gFalse, segLength); + break; + case 39: + readGenericRegionSeg(segNum, gTrue, gTrue, segLength); + break; + case 40: + readGenericRefinementRegionSeg(segNum, gFalse, gFalse, segLength, + refSegs, nRefSegs); + break; + case 42: + readGenericRefinementRegionSeg(segNum, gTrue, gFalse, segLength, + refSegs, nRefSegs); + break; + case 43: + readGenericRefinementRegionSeg(segNum, gTrue, gTrue, segLength, + refSegs, nRefSegs); + break; + case 48: + readPageInfoSeg(segLength); + break; + case 50: + readEndOfStripeSeg(segLength); + break; + case 52: + readProfilesSeg(segLength); + break; + case 53: + readCodeTableSeg(segNum, segLength); + break; + case 62: + readExtensionSeg(segLength); + break; + default: + error(getPos(), ""Unknown segment type in JBIG2 stream""); + for (i = 0; i < segLength; ++i) { + if ((c1 = curStr->getChar()) == EOF) { + goto eofError2; + } + } + break; + } + + + if (segLength != 0xffffffff) { + + int segExtraBytes = segDataPos + segLength - getPos(); + if (segExtraBytes > 0) { + + + + error(getPos(), ""%d extraneous byte%s after segment"", + segExtraBytes, (segExtraBytes > 1) ? ""s"" : """"); + + + int trash; + for (int i = segExtraBytes; i > 0; i--) { + readByte(&trash); + } + + } else if (segExtraBytes < 0) { + + + error(getPos(), ""Previous segment handler read too many bytes""); + + } + + } + + gfree(refSegs); + } + + return; + + syntaxError: + gfree(refSegs); + return; + + eofError2: + gfree(refSegs); + eofError1: + error(getPos(), ""Unexpected EOF in JBIG2 stream""); +} +",0,"void JBIG2Stream::readSegments() { + Guint segNum, segFlags, segType, page, segLength; + Guint refFlags, nRefSegs; + Guint *refSegs; + int segDataPos; + int c1, c2, c3; + Guint i; + + while (readULong(&segNum)) { + + if (!readUByte(&segFlags)) { + goto eofError1; + } + segType = segFlags & 0x3f; + + if (!readUByte(&refFlags)) { + goto eofError1; + } + nRefSegs = refFlags >> 5; + if (nRefSegs == 7) { + if ((c1 = curStr->getChar()) == EOF || + (c2 = curStr->getChar()) == EOF || + (c3 = curStr->getChar()) == EOF) { + goto eofError1; + } + refFlags = (refFlags << 24) | (c1 << 16) | (c2 << 8) | c3; + nRefSegs = refFlags & 0x1fffffff; + for (i = 0; i < (nRefSegs + 9) >> 3; ++i) { + c1 = curStr->getChar(); + } + } + + refSegs = (Guint *)gmallocn(nRefSegs, sizeof(Guint)); + if (segNum <= 256) { + for (i = 0; i < nRefSegs; ++i) { + if (!readUByte(&refSegs[i])) { + goto eofError2; + } + } + } else if (segNum <= 65536) { + for (i = 0; i < nRefSegs; ++i) { + if (!readUWord(&refSegs[i])) { + goto eofError2; + } + } + } else { + for (i = 0; i < nRefSegs; ++i) { + if (!readULong(&refSegs[i])) { + goto eofError2; + } + } + } + + if (segFlags & 0x40) { + if (!readULong(&page)) { + goto eofError2; + } + } else { + if (!readUByte(&page)) { + goto eofError2; + } + } + + if (!readULong(&segLength)) { + goto eofError2; + } + + segDataPos = getPos(); + + switch (segType) { + case 0: + if (!readSymbolDictSeg(segNum, segLength, refSegs, nRefSegs)) { + goto syntaxError; + } + break; + case 4: + readTextRegionSeg(segNum, gFalse, gFalse, segLength, refSegs, nRefSegs); + break; + case 6: + readTextRegionSeg(segNum, gTrue, gFalse, segLength, refSegs, nRefSegs); + break; + case 7: + readTextRegionSeg(segNum, gTrue, gTrue, segLength, refSegs, nRefSegs); + break; + case 16: + readPatternDictSeg(segNum, segLength); + break; + case 20: + readHalftoneRegionSeg(segNum, gFalse, gFalse, segLength, + refSegs, nRefSegs); + break; + case 22: + readHalftoneRegionSeg(segNum, gTrue, gFalse, segLength, + refSegs, nRefSegs); + break; + case 23: + readHalftoneRegionSeg(segNum, gTrue, gTrue, segLength, + refSegs, nRefSegs); + break; + case 36: + readGenericRegionSeg(segNum, gFalse, gFalse, segLength); + break; + case 38: + readGenericRegionSeg(segNum, gTrue, gFalse, segLength); + break; + case 39: + readGenericRegionSeg(segNum, gTrue, gTrue, segLength); + break; + case 40: + readGenericRefinementRegionSeg(segNum, gFalse, gFalse, segLength, + refSegs, nRefSegs); + break; + case 42: + readGenericRefinementRegionSeg(segNum, gTrue, gFalse, segLength, + refSegs, nRefSegs); + break; + case 43: + readGenericRefinementRegionSeg(segNum, gTrue, gTrue, segLength, + refSegs, nRefSegs); + break; + case 48: + readPageInfoSeg(segLength); + break; + case 50: + readEndOfStripeSeg(segLength); + break; + case 52: + readProfilesSeg(segLength); + break; + case 53: + readCodeTableSeg(segNum, segLength); + break; + case 62: + readExtensionSeg(segLength); + break; + default: + error(getPos(), ""Unknown segment type in JBIG2 stream""); + for (i = 0; i < segLength; ++i) { + if ((c1 = curStr->getChar()) == EOF) { + goto eofError2; + } + } + break; + } + + + if (segLength != 0xffffffff) { + + int segExtraBytes = segDataPos + segLength - getPos(); + if (segExtraBytes > 0) { + + + + error(getPos(), ""%d extraneous byte%s after segment"", + segExtraBytes, (segExtraBytes > 1) ? ""s"" : """"); + + + int trash; + for (int i = segExtraBytes; i > 0; i--) { + readByte(&trash); + } + + } else if (segExtraBytes < 0) { + + + error(getPos(), ""Previous segment handler read too many bytes""); + + } + + } + + gfree(refSegs); + } + + return; + + syntaxError: + gfree(refSegs); + return; + + eofError2: + gfree(refSegs); + eofError1: + error(getPos(), ""Unexpected EOF in JBIG2 stream""); +} +","@@ -707,7 +707,7 @@ JBIG2Bitmap::JBIG2Bitmap(Guint segNumA, int wA, int hA): + return; + } + // need to allocate one extra guard byte for use in combine() +- data = (Guchar *)gmalloc(h * line + 1); ++ data = (Guchar *)gmallocn(h, line + 1); + data[h * line] = 0; + } + +@@ -724,7 +724,7 @@ JBIG2Bitmap::JBIG2Bitmap(Guint segNumA, JBIG2Bitmap *bitmap): + return; + } + // need to allocate one extra guard byte for use in combine() +- data = (Guchar *)gmalloc(h * line + 1); ++ data = (Guchar *)gmallocn(h, line + 1); + memcpy(data, bitmap->data, h * line); + data[h * line] = 0; + }",1365,1696,2048 +4393,"void ping_err(struct sk_buff *skb, int offset, u32 info) +{ + int family; + struct icmphdr *icmph; + struct inet_sock *inet_sock; + int type; + int code; + struct net *net = dev_net(skb->dev); + struct sock *sk; + int harderr; + int err; + + if (skb->protocol == htons(ETH_P_IP)) { + family = AF_INET; + type = icmp_hdr(skb)->type; + code = icmp_hdr(skb)->code; + icmph = (struct icmphdr *)(skb->data + offset); + } else if (skb->protocol == htons(ETH_P_IPV6)) { + family = AF_INET6; + type = icmp6_hdr(skb)->icmp6_type; + code = icmp6_hdr(skb)->icmp6_code; + icmph = (struct icmphdr *) (skb->data + offset); + } else { + BUG(); + } + + /* We assume the packet has already been checked by icmp_unreach */ + + if (!ping_supported(family, icmph->type, icmph->code)) + return; + + pr_debug(""ping_err(proto=0x%x,type=%d,code=%d,id=%04x,seq=%04x)\n"", + skb->protocol, type, code, ntohs(icmph->un.echo.id), + ntohs(icmph->un.echo.sequence)); + + sk = ping_lookup(net, skb, ntohs(icmph->un.echo.id)); + if (!sk) { + pr_debug(""no socket, dropping\n""); + return; /* No socket for error */ + } + pr_debug(""err on socket %p\n"", sk); + + err = 0; + harderr = 0; + inet_sock = inet_sk(sk); + + if (skb->protocol == htons(ETH_P_IP)) { + switch (type) { + default: + case ICMP_TIME_EXCEEDED: + err = EHOSTUNREACH; + break; + case ICMP_SOURCE_QUENCH: + /* This is not a real error but ping wants to see it. + * Report it with some fake errno. + */ + err = EREMOTEIO; + break; + case ICMP_PARAMETERPROB: + err = EPROTO; + harderr = 1; + break; + case ICMP_DEST_UNREACH: + if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */ + ipv4_sk_update_pmtu(skb, sk, info); + if (inet_sock->pmtudisc != IP_PMTUDISC_DONT) { + err = EMSGSIZE; + harderr = 1; + break; + } + goto out; + } + err = EHOSTUNREACH; + if (code <= NR_ICMP_UNREACH) { + harderr = icmp_err_convert[code].fatal; + err = icmp_err_convert[code].errno; + } + break; + case ICMP_REDIRECT: + /* See ICMP_SOURCE_QUENCH */ + ipv4_sk_redirect(skb, sk); + err = EREMOTEIO; + break; + } +#if IS_ENABLED(CONFIG_IPV6) + } else if (skb->protocol == htons(ETH_P_IPV6)) { + harderr = pingv6_ops.icmpv6_err_convert(type, code, &err); +#endif + } + + /* + * RFC1122: OK. Passes ICMP errors back to application, as per + * 4.1.3.3. + */ + if ((family == AF_INET && !inet_sock->recverr) || + (family == AF_INET6 && !inet6_sk(sk)->recverr)) { + if (!harderr || sk->sk_state != TCP_ESTABLISHED) + goto out; + } else { + if (family == AF_INET) { + ip_icmp_error(sk, skb, err, 0 /* no remote port */, + info, (u8 *)icmph); +#if IS_ENABLED(CONFIG_IPV6) + } else if (family == AF_INET6) { + pingv6_ops.ipv6_icmp_error(sk, skb, err, 0, + info, (u8 *)icmph); +#endif + } + } + sk->sk_err = err; + sk->sk_error_report(sk); +out: + sock_put(sk); +} +",0,"void ping_err(struct sk_buff *skb, int offset, u32 info) +{ + int family; + struct icmphdr *icmph; + struct inet_sock *inet_sock; + int type; + int code; + struct net *net = dev_net(skb->dev); + struct sock *sk; + int harderr; + int err; + + if (skb->protocol == htons(ETH_P_IP)) { + family = AF_INET; + type = icmp_hdr(skb)->type; + code = icmp_hdr(skb)->code; + icmph = (struct icmphdr *)(skb->data + offset); + } else if (skb->protocol == htons(ETH_P_IPV6)) { + family = AF_INET6; + type = icmp6_hdr(skb)->icmp6_type; + code = icmp6_hdr(skb)->icmp6_code; + icmph = (struct icmphdr *) (skb->data + offset); + } else { + BUG(); + } + + /* We assume the packet has already been checked by icmp_unreach */ + + if (!ping_supported(family, icmph->type, icmph->code)) + return; + + pr_debug(""ping_err(proto=0x%x,type=%d,code=%d,id=%04x,seq=%04x)\n"", + skb->protocol, type, code, ntohs(icmph->un.echo.id), + ntohs(icmph->un.echo.sequence)); + + sk = ping_lookup(net, skb, ntohs(icmph->un.echo.id)); + if (!sk) { + pr_debug(""no socket, dropping\n""); + return; /* No socket for error */ + } + pr_debug(""err on socket %p\n"", sk); + + err = 0; + harderr = 0; + inet_sock = inet_sk(sk); + + if (skb->protocol == htons(ETH_P_IP)) { + switch (type) { + default: + case ICMP_TIME_EXCEEDED: + err = EHOSTUNREACH; + break; + case ICMP_SOURCE_QUENCH: + /* This is not a real error but ping wants to see it. + * Report it with some fake errno. + */ + err = EREMOTEIO; + break; + case ICMP_PARAMETERPROB: + err = EPROTO; + harderr = 1; + break; + case ICMP_DEST_UNREACH: + if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */ + ipv4_sk_update_pmtu(skb, sk, info); + if (inet_sock->pmtudisc != IP_PMTUDISC_DONT) { + err = EMSGSIZE; + harderr = 1; + break; + } + goto out; + } + err = EHOSTUNREACH; + if (code <= NR_ICMP_UNREACH) { + harderr = icmp_err_convert[code].fatal; + err = icmp_err_convert[code].errno; + } + break; + case ICMP_REDIRECT: + /* See ICMP_SOURCE_QUENCH */ + ipv4_sk_redirect(skb, sk); + err = EREMOTEIO; + break; + } +#if IS_ENABLED(CONFIG_IPV6) + } else if (skb->protocol == htons(ETH_P_IPV6)) { + harderr = pingv6_ops.icmpv6_err_convert(type, code, &err); +#endif + } + + /* + * RFC1122: OK. Passes ICMP errors back to application, as per + * 4.1.3.3. + */ + if ((family == AF_INET && !inet_sock->recverr) || + (family == AF_INET6 && !inet6_sk(sk)->recverr)) { + if (!harderr || sk->sk_state != TCP_ESTABLISHED) + goto out; + } else { + if (family == AF_INET) { + ip_icmp_error(sk, skb, err, 0 /* no remote port */, + info, (u8 *)icmph); +#if IS_ENABLED(CONFIG_IPV6) + } else if (family == AF_INET6) { + pingv6_ops.ipv6_icmp_error(sk, skb, err, 0, + info, (u8 *)icmph); +#endif + } + } + sk->sk_err = err; + sk->sk_error_report(sk); +out: + sock_put(sk); +} +","@@ -158,6 +158,7 @@ void ping_unhash(struct sock *sk) + if (sk_hashed(sk)) { + write_lock_bh(&ping_table.lock); + hlist_nulls_del(&sk->sk_nulls_node); ++ sk_nulls_node_init(&sk->sk_nulls_node); + sock_put(sk); + isk->inet_num = 0; + isk->inet_sport = 0;",915,1246,2048 +18809,"WORD32 ixheaacd_complex_anal_filt(ia_esbr_hbe_txposer_struct *ptr_hbe_txposer) { + WORD32 idx; + WORD32 anal_size = 2 * ptr_hbe_txposer->synth_size; + WORD32 N = (10 * anal_size); + + for (idx = 0; idx < (ptr_hbe_txposer->no_bins >> 1); idx++) { + WORD32 i, j, k, l; + FLOAT32 window_output[640]; + FLOAT32 u[128], u_in[256], u_out[256]; + FLOAT32 accu_r, accu_i; + const FLOAT32 *inp_signal; + FLOAT32 *anal_buf; + + FLOAT32 *analy_cos_sin_tab = ptr_hbe_txposer->analy_cos_sin_tab; + const FLOAT32 *interp_window_coeff = ptr_hbe_txposer->analy_wind_coeff; + FLOAT32 *x = ptr_hbe_txposer->analy_buf; + + memset(ptr_hbe_txposer->qmf_in_buf[idx + HBE_OPER_WIN_LEN - 1], 0, + TWICE_QMF_SYNTH_CHANNELS_NUM * sizeof(FLOAT32)); + + inp_signal = ptr_hbe_txposer->ptr_input_buf + + idx * 2 * ptr_hbe_txposer->synth_size + 1; + anal_buf = &ptr_hbe_txposer->qmf_in_buf[idx + HBE_OPER_WIN_LEN - 1] + [4 * ptr_hbe_txposer->k_start]; + + for (i = N - 1; i >= anal_size; i--) { + x[i] = x[i - anal_size]; + } + + for (i = anal_size - 1; i >= 0; i--) { + x[i] = inp_signal[anal_size - 1 - i]; + } + + for (i = 0; i < N; i++) { + window_output[i] = x[i] * interp_window_coeff[i]; + } + + for (i = 0; i < 2 * anal_size; i++) { + accu_r = 0.0; + for (j = 0; j < 5; j++) { + accu_r = accu_r + window_output[i + j * 2 * anal_size]; + } + u[i] = accu_r; + } + + if (anal_size == 40) { + for (i = 1; i < anal_size; i++) { + FLOAT32 temp1 = u[i] + u[2 * anal_size - i]; + FLOAT32 temp2 = u[i] - u[2 * anal_size - i]; + u[i] = temp1; + u[2 * anal_size - i] = temp2; + } + + for (k = 0; k < anal_size; k++) { + accu_r = u[anal_size]; + if (k & 1) + accu_i = u[0]; + else + accu_i = -u[0]; + for (l = 1; l < anal_size; l++) { + accu_r = accu_r + u[0 + l] * analy_cos_sin_tab[2 * l + 0]; + accu_i = accu_i + u[2 * anal_size - l] * analy_cos_sin_tab[2 * l + 1]; + } + analy_cos_sin_tab += (2 * anal_size); + *anal_buf++ = (FLOAT32)accu_r; + *anal_buf++ = (FLOAT32)accu_i; + } + } else { + FLOAT32 *ptr_u = u_in; + FLOAT32 *ptr_v = u_out; + for (k = 0; k < anal_size * 2; k++) { + + *ptr_u++ = ((*analy_cos_sin_tab++) * u[k]); + *ptr_u++ = ((*analy_cos_sin_tab++) * u[k]); + } + if (ixheaacd_cmplx_anal_fft != NULL) + (*ixheaacd_cmplx_anal_fft)(u_in, u_out, anal_size * 2); + else + return -1; + + for (k = 0; k < anal_size / 2; k++) { + *(anal_buf + 1) = -*ptr_v++; + *anal_buf = *ptr_v++; + + anal_buf += 2; + + *(anal_buf + 1) = *ptr_v++; + *anal_buf = -*ptr_v++; + + anal_buf += 2; + } + } + } + return 0; +} +",1,"WORD32 ixheaacd_complex_anal_filt(ia_esbr_hbe_txposer_struct *ptr_hbe_txposer) { + WORD32 idx; + WORD32 anal_size = 2 * ptr_hbe_txposer->synth_size; + WORD32 N = (10 * anal_size); + + for (idx = 0; idx < (ptr_hbe_txposer->no_bins >> 1); idx++) { + WORD32 i, j, k, l; + FLOAT32 window_output[640]; + FLOAT32 u[128], u_in[256], u_out[256]; + FLOAT32 accu_r, accu_i; + const FLOAT32 *inp_signal; + FLOAT32 *anal_buf; + + FLOAT32 *analy_cos_sin_tab = ptr_hbe_txposer->analy_cos_sin_tab; + const FLOAT32 *interp_window_coeff = ptr_hbe_txposer->analy_wind_coeff; + FLOAT32 *x = ptr_hbe_txposer->analy_buf; + + memset(ptr_hbe_txposer->qmf_in_buf[idx + HBE_OPER_WIN_LEN - 1], 0, + TWICE_QMF_SYNTH_CHANNELS_NUM * sizeof(FLOAT32)); + + inp_signal = ptr_hbe_txposer->ptr_input_buf + + idx * 2 * ptr_hbe_txposer->synth_size + 1; + anal_buf = &ptr_hbe_txposer->qmf_in_buf[idx + HBE_OPER_WIN_LEN - 1] + [4 * ptr_hbe_txposer->k_start]; + + for (i = N - 1; i >= anal_size; i--) { + x[i] = x[i - anal_size]; + } + + for (i = anal_size - 1; i >= 0; i--) { + x[i] = inp_signal[anal_size - 1 - i]; + } + + for (i = 0; i < N; i++) { + window_output[i] = x[i] * interp_window_coeff[i]; + } + + for (i = 0; i < 2 * anal_size; i++) { + accu_r = 0.0; + for (j = 0; j < 5; j++) { + accu_r = accu_r + window_output[i + j * 2 * anal_size]; + } + u[i] = accu_r; + } + + if (anal_size == 40) { + for (i = 1; i < anal_size; i++) { + FLOAT32 temp1 = u[i] + u[2 * anal_size - i]; + FLOAT32 temp2 = u[i] - u[2 * anal_size - i]; + u[i] = temp1; + u[2 * anal_size - i] = temp2; + } + + for (k = 0; k < anal_size; k++) { + accu_r = u[anal_size]; + if (k & 1) + accu_i = u[0]; + else + accu_i = -u[0]; + for (l = 1; l < anal_size; l++) { + accu_r = accu_r + u[0 + l] * analy_cos_sin_tab[2 * l + 0]; + accu_i = accu_i + u[2 * anal_size - l] * analy_cos_sin_tab[2 * l + 1]; + } + analy_cos_sin_tab += (2 * anal_size); + *anal_buf++ = (FLOAT32)accu_r; + *anal_buf++ = (FLOAT32)accu_i; + } + } else { + FLOAT32 *ptr_u = u_in; + FLOAT32 *ptr_v = u_out; + for (k = 0; k < anal_size * 2; k++) { + + *ptr_u++ = ((*analy_cos_sin_tab++) * u[k]); + *ptr_u++ = ((*analy_cos_sin_tab++) * u[k]); + } + if (ptr_hbe_txposer->ixheaacd_cmplx_anal_fft != NULL) + (*(ptr_hbe_txposer->ixheaacd_cmplx_anal_fft))(u_in, u_out, + anal_size * 2); + else + return -1; + + for (k = 0; k < anal_size / 2; k++) { + *(anal_buf + 1) = -*ptr_v++; + *anal_buf = *ptr_v++; + + anal_buf += 2; + + *(anal_buf + 1) = *ptr_v++; + *anal_buf = -*ptr_v++; + + anal_buf += 2; + } + } + } + return 0; +} +","@@ -120,8 +120,9 @@ + + *ptr_u++ = ((*analy_cos_sin_tab++) * u[k]); + *ptr_u++ = ((*analy_cos_sin_tab++) * u[k]); + } +- if (ixheaacd_cmplx_anal_fft != NULL) +- (*ixheaacd_cmplx_anal_fft)(u_in, u_out, anal_size * 2); ++ if (ptr_hbe_txposer->ixheaacd_cmplx_anal_fft != NULL) ++ (*(ptr_hbe_txposer->ixheaacd_cmplx_anal_fft))(u_in, u_out, ++ anal_size * 2); + else + return -1; + +@@ -209,8 +210,9 @@ + + FLOAT32 *syn_buf = &buffer[kmax]; + kmax += synth_size; + +- if (ixheaacd_real_synth_fft != NULL) +- (*ixheaacd_real_synth_fft)(synth_buf_r, synth_out, synth_size * 2); ++ if (ptr_hbe_txposer->ixheaacd_real_synth_fft != NULL) ++ (*(ptr_hbe_txposer->ixheaacd_real_synth_fft))(synth_buf_r, synth_out, ++ synth_size * 2); + else + return -1; + +",965,1296,2048 +18535,"void DisplayItemList::commitNewDisplayItems(GraphicsLayer* graphicsLayer) +{ + TRACE_EVENT2(""blink,benchmark"", ""DisplayItemList::commitNewDisplayItems"", ""current_display_list_size"", (int)m_currentDisplayItems.size(), + ""num_non_cached_new_items"", (int)m_newDisplayItems.size() - m_numCachedItems); + + if (RuntimeEnabledFeatures::slimmingPaintSynchronizedPaintingEnabled()) { + for (const auto& invalidation : m_invalidations) + graphicsLayer->setNeedsDisplayInRect(invalidation.rect, invalidation.invalidationReason); + m_invalidations.clear(); + } + + ASSERT(m_scopeStack.isEmpty()); + m_scopeStack.clear(); + m_nextScope = 1; + ASSERT(!skippingCache()); +#if ENABLE(ASSERT) + m_newDisplayItemIndicesByClient.clear(); +#endif + + if (m_currentDisplayItems.isEmpty()) { +#if ENABLE(ASSERT) + for (const auto& item : m_newDisplayItems) + ASSERT(!item.isCached()); + #endif + m_currentDisplayItems.swap(m_newDisplayItems); + m_validlyCachedClientsDirty = true; + m_numCachedItems = 0; + return; + } + + updateValidlyCachedClientsIfNeeded(); + + OutOfOrderIndexContext outOfOrderIndexContext(m_currentDisplayItems.begin()); + + DisplayItems updatedList(std::max(m_currentDisplayItems.usedCapacityInBytes(), m_newDisplayItems.usedCapacityInBytes())); + DisplayItems::iterator currentIt = m_currentDisplayItems.begin(); + DisplayItems::iterator currentEnd = m_currentDisplayItems.end(); + for (DisplayItems::iterator newIt = m_newDisplayItems.begin(); newIt != m_newDisplayItems.end(); ++newIt) { + const DisplayItem& newDisplayItem = *newIt; + const DisplayItem::Id newDisplayItemId = newDisplayItem.nonCachedId(); + bool newDisplayItemHasCachedType = newDisplayItem.type() != newDisplayItemId.type; + + bool isSynchronized = currentIt != currentEnd && newDisplayItemId.matches(*currentIt); + + if (newDisplayItemHasCachedType) { + ASSERT(newDisplayItem.isCached()); + ASSERT(clientCacheIsValid(newDisplayItem.client()) || (RuntimeEnabledFeatures::slimmingPaintOffsetCachingEnabled() && !paintOffsetWasInvalidated(newDisplayItem.client()))); + if (!isSynchronized) { + currentIt = findOutOfOrderCachedItem(newDisplayItemId, outOfOrderIndexContext); + + if (currentIt == currentEnd) { +#ifndef NDEBUG + showDebugData(); + WTFLogAlways(""%s not found in m_currentDisplayItems\n"", newDisplayItem.asDebugString().utf8().data()); +#endif + ASSERT_NOT_REACHED(); + continue; + } + } +#if ENABLE(ASSERT) + if (RuntimeEnabledFeatures::slimmingPaintUnderInvalidationCheckingEnabled()) { + DisplayItems::iterator temp = currentIt; + checkUnderInvalidation(newIt, temp); + } +#endif + if (newDisplayItem.isCachedDrawing()) { + updatedList.appendByMoving(*currentIt); + ++currentIt; + } else { + ASSERT(newDisplayItem.isCachedSubsequence()); + copyCachedSubsequence(currentIt, updatedList); + ASSERT(updatedList.last().isEndSubsequence()); + } + } else { + ASSERT(!newDisplayItem.isDrawing() + || newDisplayItem.skippedCache() + || !clientCacheIsValid(newDisplayItem.client()) + || (RuntimeEnabledFeatures::slimmingPaintOffsetCachingEnabled() && paintOffsetWasInvalidated(newDisplayItem.client()))); + + updatedList.appendByMoving(*newIt); + + if (isSynchronized) + ++currentIt; + } + if (currentIt - outOfOrderIndexContext.nextItemToIndex > 0) + outOfOrderIndexContext.nextItemToIndex = currentIt; + } + +#if ENABLE(ASSERT) + if (RuntimeEnabledFeatures::slimmingPaintUnderInvalidationCheckingEnabled()) + checkNoRemainingCachedDisplayItems(); + #endif // ENABLE(ASSERT) + + m_newDisplayItems.clear(); + m_validlyCachedClientsDirty = true; + m_currentDisplayItems.swap(updatedList); + m_numCachedItems = 0; + +#if ENABLE(ASSERT) + m_clientsWithPaintOffsetInvalidations.clear(); +#endif +} +",1,"void DisplayItemList::commitNewDisplayItems(GraphicsLayer* graphicsLayer) +{ + TRACE_EVENT2(""blink,benchmark"", ""DisplayItemList::commitNewDisplayItems"", ""current_display_list_size"", (int)m_currentDisplayItems.size(), + ""num_non_cached_new_items"", (int)m_newDisplayItems.size() - m_numCachedItems); + + if (RuntimeEnabledFeatures::slimmingPaintSynchronizedPaintingEnabled()) { + for (const auto& invalidation : m_invalidations) + graphicsLayer->setNeedsDisplayInRect(invalidation.rect, invalidation.invalidationReason); + m_invalidations.clear(); + } + + ASSERT(m_scopeStack.isEmpty()); + m_scopeStack.clear(); + m_nextScope = 1; + ASSERT(!skippingCache()); +#if ENABLE(ASSERT) + m_newDisplayItemIndicesByClient.clear(); +#endif + + if (m_currentDisplayItems.isEmpty()) { +#if ENABLE(ASSERT) + for (const auto& item : m_newDisplayItems) + ASSERT(!item.isCached()); + #endif + m_currentDisplayItems.swap(m_newDisplayItems); + m_currentPaintChunks = m_newPaintChunks.releasePaintChunks(); + m_validlyCachedClientsDirty = true; + m_numCachedItems = 0; + return; + } + + updateValidlyCachedClientsIfNeeded(); + + OutOfOrderIndexContext outOfOrderIndexContext(m_currentDisplayItems.begin()); + + DisplayItems updatedList(std::max(m_currentDisplayItems.usedCapacityInBytes(), m_newDisplayItems.usedCapacityInBytes())); + Vector updatedPaintChunks; + DisplayItems::iterator currentIt = m_currentDisplayItems.begin(); + DisplayItems::iterator currentEnd = m_currentDisplayItems.end(); + for (DisplayItems::iterator newIt = m_newDisplayItems.begin(); newIt != m_newDisplayItems.end(); ++newIt) { + const DisplayItem& newDisplayItem = *newIt; + const DisplayItem::Id newDisplayItemId = newDisplayItem.nonCachedId(); + bool newDisplayItemHasCachedType = newDisplayItem.type() != newDisplayItemId.type; + + bool isSynchronized = currentIt != currentEnd && newDisplayItemId.matches(*currentIt); + + if (newDisplayItemHasCachedType) { + ASSERT(newDisplayItem.isCached()); + ASSERT(clientCacheIsValid(newDisplayItem.client()) || (RuntimeEnabledFeatures::slimmingPaintOffsetCachingEnabled() && !paintOffsetWasInvalidated(newDisplayItem.client()))); + if (!isSynchronized) { + currentIt = findOutOfOrderCachedItem(newDisplayItemId, outOfOrderIndexContext); + + if (currentIt == currentEnd) { +#ifndef NDEBUG + showDebugData(); + WTFLogAlways(""%s not found in m_currentDisplayItems\n"", newDisplayItem.asDebugString().utf8().data()); +#endif + ASSERT_NOT_REACHED(); + continue; + } + } +#if ENABLE(ASSERT) + if (RuntimeEnabledFeatures::slimmingPaintUnderInvalidationCheckingEnabled()) { + DisplayItems::iterator temp = currentIt; + checkUnderInvalidation(newIt, temp); + } +#endif + if (newDisplayItem.isCachedDrawing()) { + updatedList.appendByMoving(*currentIt); + ++currentIt; + } else { + ASSERT(newDisplayItem.isCachedSubsequence()); + copyCachedSubsequence(currentIt, updatedList); + ASSERT(updatedList.last().isEndSubsequence()); + } + } else { + ASSERT(!newDisplayItem.isDrawing() + || newDisplayItem.skippedCache() + || !clientCacheIsValid(newDisplayItem.client()) + || (RuntimeEnabledFeatures::slimmingPaintOffsetCachingEnabled() && paintOffsetWasInvalidated(newDisplayItem.client()))); + + updatedList.appendByMoving(*newIt); + + if (isSynchronized) + ++currentIt; + } + if (currentIt - outOfOrderIndexContext.nextItemToIndex > 0) + outOfOrderIndexContext.nextItemToIndex = currentIt; + } + +#if ENABLE(ASSERT) + if (RuntimeEnabledFeatures::slimmingPaintUnderInvalidationCheckingEnabled()) + checkNoRemainingCachedDisplayItems(); + #endif // ENABLE(ASSERT) + + // TODO(jbroman): When subsequence caching applies to SPv2, we'll need to + // merge the paint chunks as well. + m_currentPaintChunks = m_newPaintChunks.releasePaintChunks(); + + m_newDisplayItems.clear(); + m_validlyCachedClientsDirty = true; + m_currentDisplayItems.swap(updatedList); + m_numCachedItems = 0; + +#if ENABLE(ASSERT) + m_clientsWithPaintOffsetInvalidations.clear(); +#endif +} +","@@ -24,6 +24,12 @@ const DisplayItems& DisplayItemList::displayItems() const + return m_currentDisplayItems; + } + ++const Vector& DisplayItemList::paintChunks() const ++{ ++ ASSERT(m_newPaintChunks.isInInitialState()); ++ return m_currentPaintChunks; ++} ++ + bool DisplayItemList::lastDisplayItemIsNoopBegin() const + { + if (m_newDisplayItems.isEmpty()) +@@ -48,6 +54,9 @@ void DisplayItemList::removeLastDisplayItem() + } + #endif + m_newDisplayItems.removeLast(); ++ ++ if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) ++ m_newPaintChunks.decrementDisplayItemIndex(); + } + + void DisplayItemList::processNewItem(DisplayItem& displayItem) +@@ -85,6 +94,14 @@ void DisplayItemList::processNewItem(DisplayItem& displayItem) + + if (skippingCache()) + displayItem.setSkippedCache(); ++ ++ if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) ++ m_newPaintChunks.incrementDisplayItemIndex(); ++} ++ ++void DisplayItemList::updateCurrentPaintProperties(const PaintProperties& newPaintProperties) ++{ ++ m_newPaintChunks.updateCurrentPaintProperties(newPaintProperties); + } + + void DisplayItemList::beginScope() +@@ -287,6 +304,7 @@ void DisplayItemList::commitNewDisplayItems(GraphicsLayer* graphicsLayer) + ASSERT(!item.isCached()); + #endif + m_currentDisplayItems.swap(m_newDisplayItems); ++ m_currentPaintChunks = m_newPaintChunks.releasePaintChunks(); + m_validlyCachedClientsDirty = true; + m_numCachedItems = 0; + return; +@@ -303,6 +321,7 @@ void DisplayItemList::commitNewDisplayItems(GraphicsLayer* graphicsLayer) + + // TODO(jbroman): Consider revisiting this heuristic. + DisplayItems updatedList(std::max(m_currentDisplayItems.usedCapacityInBytes(), m_newDisplayItems.usedCapacityInBytes())); ++ Vector updatedPaintChunks; + DisplayItems::iterator currentIt = m_currentDisplayItems.begin(); + DisplayItems::iterator currentEnd = m_currentDisplayItems.end(); + for (DisplayItems::iterator newIt = m_newDisplayItems.begin(); newIt != m_newDisplayItems.end(); ++newIt) { +@@ -365,6 +384,10 @@ void DisplayItemList::commitNewDisplayItems(GraphicsLayer* graphicsLayer) + checkNoRemainingCachedDisplayItems(); + #endif // ENABLE(ASSERT) + ++ // TODO(jbroman): When subsequence caching applies to SPv2, we'll need to ++ // merge the paint chunks as well. ++ m_currentPaintChunks = m_newPaintChunks.releasePaintChunks(); ++ + m_newDisplayItems.clear(); + m_validlyCachedClientsDirty = true; + m_currentDisplayItems.swap(updatedList);",886,1217,2048 +1049," Ins_MDRP( INS_ARG ) + { + FT_UShort point; + FT_F26Dot6 org_dist, distance; + + + point = (FT_UShort)args[0]; + + if ( BOUNDS( point, CUR.zp1.n_points ) || + BOUNDS( CUR.GS.rp0, CUR.zp0.n_points ) ) + { + if ( CUR.pedantic_hinting ) + CUR.error = TT_Err_Invalid_Reference; + return; + } + + /* XXX: Is there some undocumented feature while in the */ + /* twilight zone? */ + + /* XXX: UNDOCUMENTED: twilight zone special case */ + + if ( CUR.GS.gep0 == 0 || CUR.GS.gep1 == 0 ) + { + FT_Vector* vec1 = &CUR.zp1.org[point]; + FT_Vector* vec2 = &CUR.zp0.org[CUR.GS.rp0]; + + + org_dist = CUR_Func_dualproj( vec1, vec2 ); + } + else + { + FT_Vector* vec1 = &CUR.zp1.orus[point]; + FT_Vector* vec2 = &CUR.zp0.orus[CUR.GS.rp0]; + + + if ( CUR.metrics.x_scale == CUR.metrics.y_scale ) + { + /* this should be faster */ + org_dist = CUR_Func_dualproj( vec1, vec2 ); + org_dist = TT_MULFIX( org_dist, CUR.metrics.x_scale ); + } + else + { + FT_Vector vec; + + + vec.x = TT_MULFIX( vec1->x - vec2->x, CUR.metrics.x_scale ); + vec.y = TT_MULFIX( vec1->y - vec2->y, CUR.metrics.y_scale ); + + org_dist = CUR_fast_dualproj( &vec ); + } + } + + /* single width cut-in test */ + + if ( FT_ABS( org_dist - CUR.GS.single_width_value ) < + CUR.GS.single_width_cutin ) + { + if ( org_dist >= 0 ) + org_dist = CUR.GS.single_width_value; + else + org_dist = -CUR.GS.single_width_value; + } + + /* round flag */ + + if ( ( CUR.opcode & 4 ) != 0 ) + distance = CUR_Func_round( + org_dist, + CUR.tt_metrics.compensations[CUR.opcode & 3] ); + else + distance = ROUND_None( + org_dist, + CUR.tt_metrics.compensations[CUR.opcode & 3] ); + + /* minimum distance flag */ + + if ( ( CUR.opcode & 8 ) != 0 ) + { + if ( org_dist >= 0 ) + { + if ( distance < CUR.GS.minimum_distance ) + distance = CUR.GS.minimum_distance; + } + else + { + if ( distance > -CUR.GS.minimum_distance ) + distance = -CUR.GS.minimum_distance; + } + } + + /* now move the point */ + + org_dist = CUR_Func_project( CUR.zp1.cur + point, + CUR.zp0.cur + CUR.GS.rp0 ); + + CUR_Func_move( &CUR.zp1, point, distance - org_dist ); + + CUR.GS.rp1 = CUR.GS.rp0; + CUR.GS.rp2 = point; + + if ( ( CUR.opcode & 16 ) != 0 ) + CUR.GS.rp0 = point; + } +",0," Ins_MDRP( INS_ARG ) + { + FT_UShort point; + FT_F26Dot6 org_dist, distance; + + + point = (FT_UShort)args[0]; + + if ( BOUNDS( point, CUR.zp1.n_points ) || + BOUNDS( CUR.GS.rp0, CUR.zp0.n_points ) ) + { + if ( CUR.pedantic_hinting ) + CUR.error = TT_Err_Invalid_Reference; + return; + } + + /* XXX: Is there some undocumented feature while in the */ + /* twilight zone? */ + + /* XXX: UNDOCUMENTED: twilight zone special case */ + + if ( CUR.GS.gep0 == 0 || CUR.GS.gep1 == 0 ) + { + FT_Vector* vec1 = &CUR.zp1.org[point]; + FT_Vector* vec2 = &CUR.zp0.org[CUR.GS.rp0]; + + + org_dist = CUR_Func_dualproj( vec1, vec2 ); + } + else + { + FT_Vector* vec1 = &CUR.zp1.orus[point]; + FT_Vector* vec2 = &CUR.zp0.orus[CUR.GS.rp0]; + + + if ( CUR.metrics.x_scale == CUR.metrics.y_scale ) + { + /* this should be faster */ + org_dist = CUR_Func_dualproj( vec1, vec2 ); + org_dist = TT_MULFIX( org_dist, CUR.metrics.x_scale ); + } + else + { + FT_Vector vec; + + + vec.x = TT_MULFIX( vec1->x - vec2->x, CUR.metrics.x_scale ); + vec.y = TT_MULFIX( vec1->y - vec2->y, CUR.metrics.y_scale ); + + org_dist = CUR_fast_dualproj( &vec ); + } + } + + /* single width cut-in test */ + + if ( FT_ABS( org_dist - CUR.GS.single_width_value ) < + CUR.GS.single_width_cutin ) + { + if ( org_dist >= 0 ) + org_dist = CUR.GS.single_width_value; + else + org_dist = -CUR.GS.single_width_value; + } + + /* round flag */ + + if ( ( CUR.opcode & 4 ) != 0 ) + distance = CUR_Func_round( + org_dist, + CUR.tt_metrics.compensations[CUR.opcode & 3] ); + else + distance = ROUND_None( + org_dist, + CUR.tt_metrics.compensations[CUR.opcode & 3] ); + + /* minimum distance flag */ + + if ( ( CUR.opcode & 8 ) != 0 ) + { + if ( org_dist >= 0 ) + { + if ( distance < CUR.GS.minimum_distance ) + distance = CUR.GS.minimum_distance; + } + else + { + if ( distance > -CUR.GS.minimum_distance ) + distance = -CUR.GS.minimum_distance; + } + } + + /* now move the point */ + + org_dist = CUR_Func_project( CUR.zp1.cur + point, + CUR.zp0.cur + CUR.GS.rp0 ); + + CUR_Func_move( &CUR.zp1, point, distance - org_dist ); + + CUR.GS.rp1 = CUR.GS.rp0; + CUR.GS.rp2 = point; + + if ( ( CUR.opcode & 16 ) != 0 ) + CUR.GS.rp0 = point; + } +","@@ -6755,8 +6755,8 @@ + end_point = CUR.pts.contours[contour] - CUR.pts.first_point; + first_point = point; + +- if ( CUR.pts.n_points <= end_point ) +- end_point = CUR.pts.n_points; ++ if ( BOUNDS ( end_point, CUR.pts.n_points ) ) ++ end_point = CUR.pts.n_points - 1; + + while ( point <= end_point && ( CUR.pts.tags[point] & mask ) == 0 ) + point++;",745,1076,2048 +4209,"record_old_file_extents(struct inode *inode, + struct btrfs_ordered_extent *ordered) +{ + struct btrfs_root *root = BTRFS_I(inode)->root; + struct btrfs_path *path; + struct btrfs_key key; + struct old_sa_defrag_extent *old; + struct new_sa_defrag_extent *new; + int ret; + + new = kmalloc(sizeof(*new), GFP_NOFS); + if (!new) + return NULL; + + new->inode = inode; + new->file_pos = ordered->file_offset; + new->len = ordered->len; + new->bytenr = ordered->start; + new->disk_len = ordered->disk_len; + new->compress_type = ordered->compress_type; + new->root = RB_ROOT; + INIT_LIST_HEAD(&new->head); + + path = btrfs_alloc_path(); + if (!path) + goto out_kfree; + + key.objectid = btrfs_ino(inode); + key.type = BTRFS_EXTENT_DATA_KEY; + key.offset = new->file_pos; + + ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); + if (ret < 0) + goto out_free_path; + if (ret > 0 && path->slots[0] > 0) + path->slots[0]--; + + /* find out all the old extents for the file range */ + while (1) { + struct btrfs_file_extent_item *extent; + struct extent_buffer *l; + int slot; + u64 num_bytes; + u64 offset; + u64 end; + u64 disk_bytenr; + u64 extent_offset; + + l = path->nodes[0]; + slot = path->slots[0]; + + if (slot >= btrfs_header_nritems(l)) { + ret = btrfs_next_leaf(root, path); + if (ret < 0) + goto out_free_path; + else if (ret > 0) + break; + continue; + } + + btrfs_item_key_to_cpu(l, &key, slot); + + if (key.objectid != btrfs_ino(inode)) + break; + if (key.type != BTRFS_EXTENT_DATA_KEY) + break; + if (key.offset >= new->file_pos + new->len) + break; + + extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item); + + num_bytes = btrfs_file_extent_num_bytes(l, extent); + if (key.offset + num_bytes < new->file_pos) + goto next; + + disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent); + if (!disk_bytenr) + goto next; + + extent_offset = btrfs_file_extent_offset(l, extent); + + old = kmalloc(sizeof(*old), GFP_NOFS); + if (!old) + goto out_free_path; + + offset = max(new->file_pos, key.offset); + end = min(new->file_pos + new->len, key.offset + num_bytes); + + old->bytenr = disk_bytenr; + old->extent_offset = extent_offset; + old->offset = offset - key.offset; + old->len = end - offset; + old->new = new; + old->count = 0; + list_add_tail(&old->list, &new->head); +next: + path->slots[0]++; + cond_resched(); + } + + btrfs_free_path(path); + atomic_inc(&root->fs_info->defrag_running); + + return new; + +out_free_path: + btrfs_free_path(path); +out_kfree: + free_sa_defrag_extent(new); + return NULL; +} +",0,"record_old_file_extents(struct inode *inode, + struct btrfs_ordered_extent *ordered) +{ + struct btrfs_root *root = BTRFS_I(inode)->root; + struct btrfs_path *path; + struct btrfs_key key; + struct old_sa_defrag_extent *old; + struct new_sa_defrag_extent *new; + int ret; + + new = kmalloc(sizeof(*new), GFP_NOFS); + if (!new) + return NULL; + + new->inode = inode; + new->file_pos = ordered->file_offset; + new->len = ordered->len; + new->bytenr = ordered->start; + new->disk_len = ordered->disk_len; + new->compress_type = ordered->compress_type; + new->root = RB_ROOT; + INIT_LIST_HEAD(&new->head); + + path = btrfs_alloc_path(); + if (!path) + goto out_kfree; + + key.objectid = btrfs_ino(inode); + key.type = BTRFS_EXTENT_DATA_KEY; + key.offset = new->file_pos; + + ret = btrfs_search_slot(NULL, root, &key, path, 0, 0); + if (ret < 0) + goto out_free_path; + if (ret > 0 && path->slots[0] > 0) + path->slots[0]--; + + /* find out all the old extents for the file range */ + while (1) { + struct btrfs_file_extent_item *extent; + struct extent_buffer *l; + int slot; + u64 num_bytes; + u64 offset; + u64 end; + u64 disk_bytenr; + u64 extent_offset; + + l = path->nodes[0]; + slot = path->slots[0]; + + if (slot >= btrfs_header_nritems(l)) { + ret = btrfs_next_leaf(root, path); + if (ret < 0) + goto out_free_path; + else if (ret > 0) + break; + continue; + } + + btrfs_item_key_to_cpu(l, &key, slot); + + if (key.objectid != btrfs_ino(inode)) + break; + if (key.type != BTRFS_EXTENT_DATA_KEY) + break; + if (key.offset >= new->file_pos + new->len) + break; + + extent = btrfs_item_ptr(l, slot, struct btrfs_file_extent_item); + + num_bytes = btrfs_file_extent_num_bytes(l, extent); + if (key.offset + num_bytes < new->file_pos) + goto next; + + disk_bytenr = btrfs_file_extent_disk_bytenr(l, extent); + if (!disk_bytenr) + goto next; + + extent_offset = btrfs_file_extent_offset(l, extent); + + old = kmalloc(sizeof(*old), GFP_NOFS); + if (!old) + goto out_free_path; + + offset = max(new->file_pos, key.offset); + end = min(new->file_pos + new->len, key.offset + num_bytes); + + old->bytenr = disk_bytenr; + old->extent_offset = extent_offset; + old->offset = offset - key.offset; + old->len = end - offset; + old->new = new; + old->count = 0; + list_add_tail(&old->list, &new->head); +next: + path->slots[0]++; + cond_resched(); + } + + btrfs_free_path(path); + atomic_inc(&root->fs_info->defrag_running); + + return new; + +out_free_path: + btrfs_free_path(path); +out_kfree: + free_sa_defrag_extent(new); + return NULL; +} +","@@ -4217,6 +4217,47 @@ static int truncate_space_check(struct btrfs_trans_handle *trans, + + } + ++static int truncate_inline_extent(struct inode *inode, ++ struct btrfs_path *path, ++ struct btrfs_key *found_key, ++ const u64 item_end, ++ const u64 new_size) ++{ ++ struct extent_buffer *leaf = path->nodes[0]; ++ int slot = path->slots[0]; ++ struct btrfs_file_extent_item *fi; ++ u32 size = (u32)(new_size - found_key->offset); ++ struct btrfs_root *root = BTRFS_I(inode)->root; ++ ++ fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item); ++ ++ if (btrfs_file_extent_compression(leaf, fi) != BTRFS_COMPRESS_NONE) { ++ loff_t offset = new_size; ++ loff_t page_end = ALIGN(offset, PAGE_CACHE_SIZE); ++ ++ /* ++ * Zero out the remaining of the last page of our inline extent, ++ * instead of directly truncating our inline extent here - that ++ * would be much more complex (decompressing all the data, then ++ * compressing the truncated data, which might be bigger than ++ * the size of the inline extent, resize the extent, etc). ++ * We release the path because to get the page we might need to ++ * read the extent item from disk (data not in the page cache). ++ */ ++ btrfs_release_path(path); ++ return btrfs_truncate_page(inode, offset, page_end - offset, 0); ++ } ++ ++ btrfs_set_file_extent_ram_bytes(leaf, fi, size); ++ size = btrfs_file_extent_calc_inline_size(size); ++ btrfs_truncate_item(root, path, size, 1); ++ ++ if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) ++ inode_sub_bytes(inode, item_end + 1 - new_size); ++ ++ return 0; ++} ++ + /* + * this can truncate away extent items, csum items and directory items. + * It starts at a high offset and removes keys until it can't find +@@ -4411,27 +4452,40 @@ int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans, + * special encodings + */ + if (!del_item && +- btrfs_file_extent_compression(leaf, fi) == 0 && + btrfs_file_extent_encryption(leaf, fi) == 0 && + btrfs_file_extent_other_encoding(leaf, fi) == 0) { +- u32 size = new_size - found_key.offset; +- +- if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) +- inode_sub_bytes(inode, item_end + 1 - +- new_size); + + /* +- * update the ram bytes to properly reflect +- * the new size of our item ++ * Need to release path in order to truncate a ++ * compressed extent. So delete any accumulated ++ * extent items so far. + */ +- btrfs_set_file_extent_ram_bytes(leaf, fi, size); +- size = +- btrfs_file_extent_calc_inline_size(size); +- btrfs_truncate_item(root, path, size, 1); ++ if (btrfs_file_extent_compression(leaf, fi) != ++ BTRFS_COMPRESS_NONE && pending_del_nr) { ++ err = btrfs_del_items(trans, root, path, ++ pending_del_slot, ++ pending_del_nr); ++ if (err) { ++ btrfs_abort_transaction(trans, ++ root, ++ err); ++ goto error; ++ } ++ pending_del_nr = 0; ++ } ++ ++ err = truncate_inline_extent(inode, path, ++ &found_key, ++ item_end, ++ new_size); ++ if (err) { ++ btrfs_abort_transaction(trans, ++ root, err); ++ goto error; ++ } + } else if (test_bit(BTRFS_ROOT_REF_COWS, + &root->state)) { +- inode_sub_bytes(inode, item_end + 1 - +- found_key.offset); ++ inode_sub_bytes(inode, item_end + 1 - new_size); + } + } + delete:",762,1093,2048 +439,"void Splash::scaleImageYuXu(SplashImageSource src, void *srcData, + SplashColorMode srcMode, int nComps, + GBool srcAlpha, int srcWidth, int srcHeight, + int scaledWidth, int scaledHeight, + SplashBitmap *dest) { + Guchar *lineBuf, *alphaLineBuf; + Guint pix[splashMaxColorComps]; + Guint alpha; + Guchar *destPtr0, *destPtr, *destAlphaPtr0, *destAlphaPtr; + int yp, yq, xp, xq, yt, y, yStep, xt, x, xStep, xx; + int i, j; + + yp = scaledHeight / srcHeight; + yq = scaledHeight % srcHeight; + + xp = scaledWidth / srcWidth; + xq = scaledWidth % srcWidth; + + lineBuf = (Guchar *)gmallocn(srcWidth, nComps); + if (srcAlpha) { + alphaLineBuf = (Guchar *)gmalloc(srcWidth); + } else { + alphaLineBuf = NULL; + } + + yt = 0; + + destPtr0 = dest->data; + destAlphaPtr0 = dest->alpha; + for (y = 0; y < srcHeight; ++y) { + + if ((yt += yq) >= srcHeight) { + yt -= srcHeight; + yStep = yp + 1; + } else { + yStep = yp; + } + + (*src)(srcData, lineBuf, alphaLineBuf); + + xt = 0; + + xx = 0; + for (x = 0; x < srcWidth; ++x) { + + if ((xt += xq) >= srcWidth) { + xt -= srcWidth; + xStep = xp + 1; + } else { + xStep = xp; + } + + for (i = 0; i < nComps; ++i) { + pix[i] = lineBuf[x * nComps + i]; + } + + switch (srcMode) { + case splashModeMono1: // mono1 is not allowed + break; + case splashModeMono8: + for (i = 0; i < yStep; ++i) { + for (j = 0; j < xStep; ++j) { + destPtr = destPtr0 + (i * scaledWidth + xx + j) * nComps; + *destPtr++ = (Guchar)pix[0]; + } + } + break; + case splashModeRGB8: + for (i = 0; i < yStep; ++i) { + for (j = 0; j < xStep; ++j) { + destPtr = destPtr0 + (i * scaledWidth + xx + j) * nComps; + *destPtr++ = (Guchar)pix[0]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[2]; + } + } + break; + case splashModeXBGR8: + for (i = 0; i < yStep; ++i) { + for (j = 0; j < xStep; ++j) { + destPtr = destPtr0 + (i * scaledWidth + xx + j) * nComps; + *destPtr++ = (Guchar)pix[2]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[0]; + *destPtr++ = (Guchar)255; + } + } + break; + case splashModeBGR8: + for (i = 0; i < yStep; ++i) { + for (j = 0; j < xStep; ++j) { + destPtr = destPtr0 + (i * scaledWidth + xx + j) * nComps; + *destPtr++ = (Guchar)pix[2]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[0]; + } + } + break; +#if SPLASH_CMYK + case splashModeCMYK8: + for (i = 0; i < yStep; ++i) { + for (j = 0; j < xStep; ++j) { + destPtr = destPtr0 + (i * scaledWidth + xx + j) * nComps; + *destPtr++ = (Guchar)pix[0]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[2]; + *destPtr++ = (Guchar)pix[3]; + } + } + break; + case splashModeDeviceN8: + for (i = 0; i < yStep; ++i) { + for (j = 0; j < xStep; ++j) { + destPtr = destPtr0 + (i * scaledWidth + xx + j) * nComps; + for (int cp = 0; cp < SPOT_NCOMPS+4; cp++) + *destPtr++ = (Guchar)pix[cp]; + } + } + break; +#endif + } + + if (srcAlpha) { + alpha = alphaLineBuf[x]; + for (i = 0; i < yStep; ++i) { + for (j = 0; j < xStep; ++j) { + destAlphaPtr = destAlphaPtr0 + i * scaledWidth + xx + j; + *destAlphaPtr = (Guchar)alpha; + } + } + } + + xx += xStep; + } + + destPtr0 += yStep * scaledWidth * nComps; + if (srcAlpha) { + destAlphaPtr0 += yStep * scaledWidth; + } + } + + gfree(alphaLineBuf); + gfree(lineBuf); +} +",0,"void Splash::scaleImageYuXu(SplashImageSource src, void *srcData, + SplashColorMode srcMode, int nComps, + GBool srcAlpha, int srcWidth, int srcHeight, + int scaledWidth, int scaledHeight, + SplashBitmap *dest) { + Guchar *lineBuf, *alphaLineBuf; + Guint pix[splashMaxColorComps]; + Guint alpha; + Guchar *destPtr0, *destPtr, *destAlphaPtr0, *destAlphaPtr; + int yp, yq, xp, xq, yt, y, yStep, xt, x, xStep, xx; + int i, j; + + yp = scaledHeight / srcHeight; + yq = scaledHeight % srcHeight; + + xp = scaledWidth / srcWidth; + xq = scaledWidth % srcWidth; + + lineBuf = (Guchar *)gmallocn(srcWidth, nComps); + if (srcAlpha) { + alphaLineBuf = (Guchar *)gmalloc(srcWidth); + } else { + alphaLineBuf = NULL; + } + + yt = 0; + + destPtr0 = dest->data; + destAlphaPtr0 = dest->alpha; + for (y = 0; y < srcHeight; ++y) { + + if ((yt += yq) >= srcHeight) { + yt -= srcHeight; + yStep = yp + 1; + } else { + yStep = yp; + } + + (*src)(srcData, lineBuf, alphaLineBuf); + + xt = 0; + + xx = 0; + for (x = 0; x < srcWidth; ++x) { + + if ((xt += xq) >= srcWidth) { + xt -= srcWidth; + xStep = xp + 1; + } else { + xStep = xp; + } + + for (i = 0; i < nComps; ++i) { + pix[i] = lineBuf[x * nComps + i]; + } + + switch (srcMode) { + case splashModeMono1: // mono1 is not allowed + break; + case splashModeMono8: + for (i = 0; i < yStep; ++i) { + for (j = 0; j < xStep; ++j) { + destPtr = destPtr0 + (i * scaledWidth + xx + j) * nComps; + *destPtr++ = (Guchar)pix[0]; + } + } + break; + case splashModeRGB8: + for (i = 0; i < yStep; ++i) { + for (j = 0; j < xStep; ++j) { + destPtr = destPtr0 + (i * scaledWidth + xx + j) * nComps; + *destPtr++ = (Guchar)pix[0]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[2]; + } + } + break; + case splashModeXBGR8: + for (i = 0; i < yStep; ++i) { + for (j = 0; j < xStep; ++j) { + destPtr = destPtr0 + (i * scaledWidth + xx + j) * nComps; + *destPtr++ = (Guchar)pix[2]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[0]; + *destPtr++ = (Guchar)255; + } + } + break; + case splashModeBGR8: + for (i = 0; i < yStep; ++i) { + for (j = 0; j < xStep; ++j) { + destPtr = destPtr0 + (i * scaledWidth + xx + j) * nComps; + *destPtr++ = (Guchar)pix[2]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[0]; + } + } + break; +#if SPLASH_CMYK + case splashModeCMYK8: + for (i = 0; i < yStep; ++i) { + for (j = 0; j < xStep; ++j) { + destPtr = destPtr0 + (i * scaledWidth + xx + j) * nComps; + *destPtr++ = (Guchar)pix[0]; + *destPtr++ = (Guchar)pix[1]; + *destPtr++ = (Guchar)pix[2]; + *destPtr++ = (Guchar)pix[3]; + } + } + break; + case splashModeDeviceN8: + for (i = 0; i < yStep; ++i) { + for (j = 0; j < xStep; ++j) { + destPtr = destPtr0 + (i * scaledWidth + xx + j) * nComps; + for (int cp = 0; cp < SPOT_NCOMPS+4; cp++) + *destPtr++ = (Guchar)pix[cp]; + } + } + break; +#endif + } + + if (srcAlpha) { + alpha = alphaLineBuf[x]; + for (i = 0; i < yStep; ++i) { + for (j = 0; j < xStep; ++j) { + destAlphaPtr = destAlphaPtr0 + i * scaledWidth + xx + j; + *destAlphaPtr = (Guchar)alpha; + } + } + } + + xx += xStep; + } + + destPtr0 += yStep * scaledWidth * nComps; + if (srcAlpha) { + destAlphaPtr0 += yStep * scaledWidth; + } + } + + gfree(alphaLineBuf); + gfree(lineBuf); +} +","@@ -2955,7 +2955,7 @@ void Splash::arbitraryTransformMask(SplashImageMaskSource src, void *srcData, + scaledMask = scaleMask(src, srcData, srcWidth, srcHeight, + scaledWidth, scaledHeight); + if (scaledMask->data == NULL) { +- error(errInternal, -1, ""scaledMask->data is NULL in Splash::scaleMaskYuXu""); ++ error(errInternal, -1, ""scaledMask->data is NULL in Splash::arbitraryTransformMask""); + delete scaledMask; + return; + } +@@ -3461,11 +3461,15 @@ void Splash::blitMask(SplashBitmap *src, int xDest, int yDest, + + w = src->getWidth(); + h = src->getHeight(); ++ p = src->getDataPtr(); ++ if (p == NULL) { ++ error(errInternal, -1, ""src->getDataPtr() is NULL in Splash::blitMask""); ++ return; ++ } + if (vectorAntialias && clipRes != splashClipAllInside) { + pipeInit(&pipe, xDest, yDest, state->fillPattern, NULL, + (Guchar)splashRound(state->fillAlpha * 255), gTrue, gFalse); + drawAAPixelInit(); +- p = src->getDataPtr(); + for (y = 0; y < h; ++y) { + for (x = 0; x < w; ++x) { + pipe.shape = *p++; +@@ -3475,7 +3479,6 @@ void Splash::blitMask(SplashBitmap *src, int xDest, int yDest, + } else { + pipeInit(&pipe, xDest, yDest, state->fillPattern, NULL, + (Guchar)splashRound(state->fillAlpha * 255), gTrue, gFalse); +- p = src->getDataPtr(); + if (clipRes == splashClipAllInside) { + for (y = 0; y < h; ++y) { + pipeSetXY(&pipe, xDest, yDest + y);",1277,1608,2048 +5271,"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 +} +",0,"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 +} +","@@ -573,7 +573,8 @@ static inline int check_entry_size_and_hooks(struct arpt_entry *e, + int err; + + if ((unsigned long)e % __alignof__(struct arpt_entry) != 0 || +- (unsigned char *)e + sizeof(struct arpt_entry) >= limit) { ++ (unsigned char *)e + sizeof(struct arpt_entry) >= limit || ++ (unsigned char *)e + e->next_offset > limit) { + duprintf(""Bad offset %p\n"", e); + return -EINVAL; + } +@@ -1232,7 +1233,8 @@ check_compat_entry_size_and_hooks(struct compat_arpt_entry *e, + + 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) { ++ (unsigned char *)e + sizeof(struct compat_arpt_entry) >= limit || ++ (unsigned char *)e + e->next_offset > limit) { + duprintf(""Bad offset %p, limit = %p\n"", e, limit); + return -EINVAL; + }",1180,1511,2048 +18343,"MagickExport Image *MeanShiftImage(const Image *image,const size_t width, + const size_t height,const double color_distance,ExceptionInfo *exception) +{ +#define MaxMeanShiftIterations 100 +#define MeanShiftImageTag ""MeanShift/Image"" + + CacheView + *image_view, + *mean_view, + *pixel_view; + + Image + *mean_image; + + MagickBooleanType + status; + + MagickOffsetType + progress; + + ssize_t + y; + + assert(image != (const 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); + mean_image=CloneImage(image,0,0,MagickTrue,exception); + if (mean_image == (Image *) NULL) + return((Image *) NULL); + if (SetImageStorageClass(mean_image,DirectClass,exception) == MagickFalse) + { + mean_image=DestroyImage(mean_image); + return((Image *) NULL); + } + status=MagickTrue; + progress=0; + image_view=AcquireVirtualCacheView(image,exception); + pixel_view=AcquireVirtualCacheView(image,exception); + mean_view=AcquireAuthenticCacheView(mean_image,exception); +#if defined(MAGICKCORE_OPENMP_SUPPORT) + #pragma omp parallel for schedule(static) shared(status,progress) \ + magick_number_threads(mean_image,mean_image,mean_image->rows,1) +#endif + for (y=0; y < (ssize_t) mean_image->rows; y++) + { + register const Quantum + *magick_restrict p; + + register Quantum + *magick_restrict q; + + register ssize_t + x; + + if (status == MagickFalse) + continue; + p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); + q=GetCacheViewAuthenticPixels(mean_view,0,y,mean_image->columns,1, + exception); + if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) + { + status=MagickFalse; + continue; + } + for (x=0; x < (ssize_t) mean_image->columns; x++) + { + PixelInfo + mean_pixel, + previous_pixel; + + PointInfo + mean_location, + previous_location; + + register ssize_t + i; + + GetPixelInfo(image,&mean_pixel); + GetPixelInfoPixel(image,p,&mean_pixel); + mean_location.x=(double) x; + mean_location.y=(double) y; + for (i=0; i < MaxMeanShiftIterations; i++) + { + double + distance, + gamma; + + PixelInfo + sum_pixel; + + PointInfo + sum_location; + + ssize_t + count, + v; + + sum_location.x=0.0; + sum_location.y=0.0; + GetPixelInfo(image,&sum_pixel); + previous_location=mean_location; + previous_pixel=mean_pixel; + count=0; + for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++) + { + ssize_t + u; + + for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++) + { + if ((v*v+u*u) <= (ssize_t) ((width/2)*(height/2))) + { + PixelInfo + pixel; + + status=GetOneCacheViewVirtualPixelInfo(pixel_view,(ssize_t) + MagickRound(mean_location.x+u),(ssize_t) MagickRound( + mean_location.y+v),&pixel,exception); + distance=(mean_pixel.red-pixel.red)*(mean_pixel.red-pixel.red)+ + (mean_pixel.green-pixel.green)*(mean_pixel.green-pixel.green)+ + (mean_pixel.blue-pixel.blue)*(mean_pixel.blue-pixel.blue); + if (distance <= (color_distance*color_distance)) + { + sum_location.x+=mean_location.x+u; + sum_location.y+=mean_location.y+v; + sum_pixel.red+=pixel.red; + sum_pixel.green+=pixel.green; + sum_pixel.blue+=pixel.blue; + sum_pixel.alpha+=pixel.alpha; + count++; + } + } + } + } + gamma=1.0/count; + mean_location.x=gamma*sum_location.x; + mean_location.y=gamma*sum_location.y; + mean_pixel.red=gamma*sum_pixel.red; + mean_pixel.green=gamma*sum_pixel.green; + mean_pixel.blue=gamma*sum_pixel.blue; + mean_pixel.alpha=gamma*sum_pixel.alpha; + distance=(mean_location.x-previous_location.x)* + (mean_location.x-previous_location.x)+ + (mean_location.y-previous_location.y)* + (mean_location.y-previous_location.y)+ + 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)* + 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)+ + 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)* + 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)+ + 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue)* + 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue); + if (distance <= 3.0) + break; + } + SetPixelRed(mean_image,ClampToQuantum(mean_pixel.red),q); + SetPixelGreen(mean_image,ClampToQuantum(mean_pixel.green),q); + SetPixelBlue(mean_image,ClampToQuantum(mean_pixel.blue),q); + SetPixelAlpha(mean_image,ClampToQuantum(mean_pixel.alpha),q); + p+=GetPixelChannels(image); + q+=GetPixelChannels(mean_image); + } + if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse) + status=MagickFalse; + if (image->progress_monitor != (MagickProgressMonitor) NULL) + { + MagickBooleanType + proceed; + +#if defined(MAGICKCORE_OPENMP_SUPPORT) + #pragma omp atomic +#endif + progress++; + proceed=SetImageProgress(image,MeanShiftImageTag,progress,image->rows); + if (proceed == MagickFalse) + status=MagickFalse; + } + } + mean_view=DestroyCacheView(mean_view); + pixel_view=DestroyCacheView(pixel_view); + image_view=DestroyCacheView(image_view); + return(mean_image); +} +",1,"MagickExport Image *MeanShiftImage(const Image *image,const size_t width, + const size_t height,const double color_distance,ExceptionInfo *exception) +{ +#define MaxMeanShiftIterations 100 +#define MeanShiftImageTag ""MeanShift/Image"" + + CacheView + *image_view, + *mean_view, + *pixel_view; + + Image + *mean_image; + + MagickBooleanType + status; + + MagickOffsetType + progress; + + ssize_t + y; + + assert(image != (const 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); + mean_image=CloneImage(image,0,0,MagickTrue,exception); + if (mean_image == (Image *) NULL) + return((Image *) NULL); + if (SetImageStorageClass(mean_image,DirectClass,exception) == MagickFalse) + { + mean_image=DestroyImage(mean_image); + return((Image *) NULL); + } + status=MagickTrue; + progress=0; + image_view=AcquireVirtualCacheView(image,exception); + pixel_view=AcquireVirtualCacheView(image,exception); + mean_view=AcquireAuthenticCacheView(mean_image,exception); +#if defined(MAGICKCORE_OPENMP_SUPPORT) + #pragma omp parallel for schedule(static) shared(status,progress) \ + magick_number_threads(mean_image,mean_image,mean_image->rows,1) +#endif + for (y=0; y < (ssize_t) mean_image->rows; y++) + { + register const Quantum + *magick_restrict p; + + register Quantum + *magick_restrict q; + + register ssize_t + x; + + if (status == MagickFalse) + continue; + p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); + q=GetCacheViewAuthenticPixels(mean_view,0,y,mean_image->columns,1, + exception); + if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) + { + status=MagickFalse; + continue; + } + for (x=0; x < (ssize_t) mean_image->columns; x++) + { + PixelInfo + mean_pixel, + previous_pixel; + + PointInfo + mean_location, + previous_location; + + register ssize_t + i; + + GetPixelInfo(image,&mean_pixel); + GetPixelInfoPixel(image,p,&mean_pixel); + mean_location.x=(double) x; + mean_location.y=(double) y; + for (i=0; i < MaxMeanShiftIterations; i++) + { + double + distance, + gamma; + + PixelInfo + sum_pixel; + + PointInfo + sum_location; + + ssize_t + count, + v; + + sum_location.x=0.0; + sum_location.y=0.0; + GetPixelInfo(image,&sum_pixel); + previous_location=mean_location; + previous_pixel=mean_pixel; + count=0; + for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++) + { + ssize_t + u; + + for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++) + { + if ((v*v+u*u) <= (ssize_t) ((width/2)*(height/2))) + { + PixelInfo + pixel; + + status=GetOneCacheViewVirtualPixelInfo(pixel_view,(ssize_t) + MagickRound(mean_location.x+u),(ssize_t) MagickRound( + mean_location.y+v),&pixel,exception); + distance=(mean_pixel.red-pixel.red)*(mean_pixel.red-pixel.red)+ + (mean_pixel.green-pixel.green)*(mean_pixel.green-pixel.green)+ + (mean_pixel.blue-pixel.blue)*(mean_pixel.blue-pixel.blue); + if (distance <= (color_distance*color_distance)) + { + sum_location.x+=mean_location.x+u; + sum_location.y+=mean_location.y+v; + sum_pixel.red+=pixel.red; + sum_pixel.green+=pixel.green; + sum_pixel.blue+=pixel.blue; + sum_pixel.alpha+=pixel.alpha; + count++; + } + } + } + } + gamma=PerceptibleReciprocal(count); + mean_location.x=gamma*sum_location.x; + mean_location.y=gamma*sum_location.y; + mean_pixel.red=gamma*sum_pixel.red; + mean_pixel.green=gamma*sum_pixel.green; + mean_pixel.blue=gamma*sum_pixel.blue; + mean_pixel.alpha=gamma*sum_pixel.alpha; + distance=(mean_location.x-previous_location.x)* + (mean_location.x-previous_location.x)+ + (mean_location.y-previous_location.y)* + (mean_location.y-previous_location.y)+ + 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)* + 255.0*QuantumScale*(mean_pixel.red-previous_pixel.red)+ + 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)* + 255.0*QuantumScale*(mean_pixel.green-previous_pixel.green)+ + 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue)* + 255.0*QuantumScale*(mean_pixel.blue-previous_pixel.blue); + if (distance <= 3.0) + break; + } + SetPixelRed(mean_image,ClampToQuantum(mean_pixel.red),q); + SetPixelGreen(mean_image,ClampToQuantum(mean_pixel.green),q); + SetPixelBlue(mean_image,ClampToQuantum(mean_pixel.blue),q); + SetPixelAlpha(mean_image,ClampToQuantum(mean_pixel.alpha),q); + p+=GetPixelChannels(image); + q+=GetPixelChannels(mean_image); + } + if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse) + status=MagickFalse; + if (image->progress_monitor != (MagickProgressMonitor) NULL) + { + MagickBooleanType + proceed; + +#if defined(MAGICKCORE_OPENMP_SUPPORT) + #pragma omp atomic +#endif + progress++; + proceed=SetImageProgress(image,MeanShiftImageTag,progress,image->rows); + if (proceed == MagickFalse) + status=MagickFalse; + } + } + mean_view=DestroyCacheView(mean_view); + pixel_view=DestroyCacheView(pixel_view); + image_view=DestroyCacheView(image_view); + return(mean_image); +} +","@@ -2288,7 +2288,7 @@ MagickExport Image *MeanShiftImage(const Image *image,const size_t width, + } + } + } +- gamma=1.0/count; ++ gamma=PerceptibleReciprocal(count); + mean_location.x=gamma*sum_location.x; + mean_location.y=gamma*sum_location.y; + mean_pixel.red=gamma*sum_pixel.red;",1443,1774,2048 +17229,"OMX_ERRORTYPE omx_video::get_supported_profile_level(OMX_VIDEO_PARAM_PROFILELEVELTYPE *profileLevelType) +{ + OMX_ERRORTYPE eRet = OMX_ErrorNone; + if (!profileLevelType) + return OMX_ErrorBadParameter; + + if (profileLevelType->nPortIndex == 1) { + if (m_sOutPortDef.format.video.eCompressionFormat == OMX_VIDEO_CodingAVC) { +#if defined _MSM8974_ && !defined _MSM8226_ + if (profileLevelType->nProfileIndex == 0) { + profileLevelType->eProfile = OMX_VIDEO_AVCProfileBaseline; + profileLevelType->eLevel = OMX_VIDEO_AVCLevel52; + } else if (profileLevelType->nProfileIndex == 1) { + profileLevelType->eProfile = OMX_VIDEO_AVCProfileMain; + profileLevelType->eLevel = OMX_VIDEO_AVCLevel52; + } else if (profileLevelType->nProfileIndex == 2) { + profileLevelType->eProfile = OMX_VIDEO_AVCProfileHigh; + profileLevelType->eLevel = OMX_VIDEO_AVCLevel52; + } else if (profileLevelType->nProfileIndex == 3) { + profileLevelType->eProfile = QOMX_VIDEO_AVCProfileConstrainedBaseline; + profileLevelType->eLevel = OMX_VIDEO_AVCLevel52; + } else { + DEBUG_PRINT_LOW(""get_parameter: OMX_IndexParamVideoProfileLevelQuerySupported nProfileIndex ret NoMore %u"", + (unsigned int)profileLevelType->nProfileIndex); + eRet = OMX_ErrorNoMore; + } +#else + if (profileLevelType->nProfileIndex == 0) { + profileLevelType->eProfile = OMX_VIDEO_AVCProfileBaseline; + profileLevelType->eLevel = OMX_VIDEO_AVCLevel4; + + } else if (profileLevelType->nProfileIndex == 1) { + profileLevelType->eProfile = OMX_VIDEO_AVCProfileMain; + profileLevelType->eLevel = OMX_VIDEO_AVCLevel4; + } else if (profileLevelType->nProfileIndex == 2) { + profileLevelType->eProfile = OMX_VIDEO_AVCProfileHigh; + profileLevelType->eLevel = OMX_VIDEO_AVCLevel4; +#ifdef _MSM8226_ + } else if (profileLevelType->nProfileIndex == 3) { + profileLevelType->eProfile = QOMX_VIDEO_AVCProfileConstrainedBaseline; + profileLevelType->eLevel = OMX_VIDEO_AVCLevel4; +#endif + } else { + DEBUG_PRINT_LOW(""get_parameter: OMX_IndexParamVideoProfileLevelQuerySupported nProfileIndex ret NoMore %d"", + (int)profileLevelType->nProfileIndex); + eRet = OMX_ErrorNoMore; + } +#endif + } else if (m_sOutPortDef.format.video.eCompressionFormat == OMX_VIDEO_CodingH263) { + if (profileLevelType->nProfileIndex == 0) { + profileLevelType->eProfile = OMX_VIDEO_H263ProfileBaseline; + profileLevelType->eLevel = OMX_VIDEO_H263Level70; + } else { + DEBUG_PRINT_ERROR(""get_parameter: OMX_IndexParamVideoProfileLevelQuerySupported nProfileIndex ret NoMore %u"", (unsigned int)profileLevelType->nProfileIndex); + eRet = OMX_ErrorNoMore; + } + } else if (m_sOutPortDef.format.video.eCompressionFormat == OMX_VIDEO_CodingMPEG4) { + if (profileLevelType->nProfileIndex == 0) { + profileLevelType->eProfile = OMX_VIDEO_MPEG4ProfileSimple; + profileLevelType->eLevel = OMX_VIDEO_MPEG4Level5; + } else if (profileLevelType->nProfileIndex == 1) { + profileLevelType->eProfile = OMX_VIDEO_MPEG4ProfileAdvancedSimple; + profileLevelType->eLevel = OMX_VIDEO_MPEG4Level5; + } else { + DEBUG_PRINT_ERROR(""get_parameter: OMX_IndexParamVideoProfileLevelQuerySupported nProfileIndex ret NoMore %u"", (unsigned int)profileLevelType->nProfileIndex); + eRet = OMX_ErrorNoMore; + } + } else if (m_sOutPortDef.format.video.eCompressionFormat == OMX_VIDEO_CodingVP8) { + if (profileLevelType->nProfileIndex == 0) { + profileLevelType->eProfile = OMX_VIDEO_VP8ProfileMain; + profileLevelType->eLevel = OMX_VIDEO_VP8Level_Version0; + } else if (profileLevelType->nProfileIndex == 1) { + profileLevelType->eProfile = OMX_VIDEO_VP8ProfileMain; + profileLevelType->eLevel = OMX_VIDEO_VP8Level_Version1; + } else { + DEBUG_PRINT_LOW(""VP8: get_parameter: OMX_IndexParamVideoProfileLevelQuerySupported nProfileIndex ret NoMore %u"", + (unsigned int)profileLevelType->nProfileIndex); + eRet = OMX_ErrorNoMore; + } + } else if (m_sOutPortDef.format.video.eCompressionFormat == OMX_VIDEO_CodingHEVC) { + if (profileLevelType->nProfileIndex == 0) { + profileLevelType->eProfile = OMX_VIDEO_HEVCProfileMain; + profileLevelType->eLevel = OMX_VIDEO_HEVCMainTierLevel52; + } else if (profileLevelType->nProfileIndex == 1) { + profileLevelType->eProfile = OMX_VIDEO_HEVCProfileMain10; + profileLevelType->eLevel = OMX_VIDEO_HEVCMainTierLevel52; + } else { + DEBUG_PRINT_LOW(""HEVC: get_parameter: OMX_IndexParamVideoProfileLevelQuerySupported nProfileIndex ret NoMore %u"", + (unsigned int)profileLevelType->nProfileIndex); + eRet = OMX_ErrorNoMore; + } + } else { + DEBUG_PRINT_ERROR(""get_parameter: OMX_IndexParamVideoProfileLevelQuerySupported ret NoMore""); + eRet = OMX_ErrorNoMore; + } + } else { + DEBUG_PRINT_ERROR(""get_parameter: OMX_IndexParamVideoProfileLevelQuerySupported should be queried on Input port only %u"", (unsigned int)profileLevelType->nPortIndex); + eRet = OMX_ErrorBadPortIndex; + } + DEBUG_PRINT_LOW(""get_parameter: OMX_IndexParamVideoProfileLevelQuerySupported for Input port returned Profile:%u, Level:%u"", + (unsigned int)profileLevelType->eProfile, (unsigned int)profileLevelType->eLevel); + return eRet; +} +",0,"OMX_ERRORTYPE omx_video::get_supported_profile_level(OMX_VIDEO_PARAM_PROFILELEVELTYPE *profileLevelType) +{ + OMX_ERRORTYPE eRet = OMX_ErrorNone; + if (!profileLevelType) + return OMX_ErrorBadParameter; + + if (profileLevelType->nPortIndex == 1) { + if (m_sOutPortDef.format.video.eCompressionFormat == OMX_VIDEO_CodingAVC) { +#if defined _MSM8974_ && !defined _MSM8226_ + if (profileLevelType->nProfileIndex == 0) { + profileLevelType->eProfile = OMX_VIDEO_AVCProfileBaseline; + profileLevelType->eLevel = OMX_VIDEO_AVCLevel52; + } else if (profileLevelType->nProfileIndex == 1) { + profileLevelType->eProfile = OMX_VIDEO_AVCProfileMain; + profileLevelType->eLevel = OMX_VIDEO_AVCLevel52; + } else if (profileLevelType->nProfileIndex == 2) { + profileLevelType->eProfile = OMX_VIDEO_AVCProfileHigh; + profileLevelType->eLevel = OMX_VIDEO_AVCLevel52; + } else if (profileLevelType->nProfileIndex == 3) { + profileLevelType->eProfile = QOMX_VIDEO_AVCProfileConstrainedBaseline; + profileLevelType->eLevel = OMX_VIDEO_AVCLevel52; + } else { + DEBUG_PRINT_LOW(""get_parameter: OMX_IndexParamVideoProfileLevelQuerySupported nProfileIndex ret NoMore %u"", + (unsigned int)profileLevelType->nProfileIndex); + eRet = OMX_ErrorNoMore; + } +#else + if (profileLevelType->nProfileIndex == 0) { + profileLevelType->eProfile = OMX_VIDEO_AVCProfileBaseline; + profileLevelType->eLevel = OMX_VIDEO_AVCLevel4; + + } else if (profileLevelType->nProfileIndex == 1) { + profileLevelType->eProfile = OMX_VIDEO_AVCProfileMain; + profileLevelType->eLevel = OMX_VIDEO_AVCLevel4; + } else if (profileLevelType->nProfileIndex == 2) { + profileLevelType->eProfile = OMX_VIDEO_AVCProfileHigh; + profileLevelType->eLevel = OMX_VIDEO_AVCLevel4; +#ifdef _MSM8226_ + } else if (profileLevelType->nProfileIndex == 3) { + profileLevelType->eProfile = QOMX_VIDEO_AVCProfileConstrainedBaseline; + profileLevelType->eLevel = OMX_VIDEO_AVCLevel4; +#endif + } else { + DEBUG_PRINT_LOW(""get_parameter: OMX_IndexParamVideoProfileLevelQuerySupported nProfileIndex ret NoMore %d"", + (int)profileLevelType->nProfileIndex); + eRet = OMX_ErrorNoMore; + } +#endif + } else if (m_sOutPortDef.format.video.eCompressionFormat == OMX_VIDEO_CodingH263) { + if (profileLevelType->nProfileIndex == 0) { + profileLevelType->eProfile = OMX_VIDEO_H263ProfileBaseline; + profileLevelType->eLevel = OMX_VIDEO_H263Level70; + } else { + DEBUG_PRINT_ERROR(""get_parameter: OMX_IndexParamVideoProfileLevelQuerySupported nProfileIndex ret NoMore %u"", (unsigned int)profileLevelType->nProfileIndex); + eRet = OMX_ErrorNoMore; + } + } else if (m_sOutPortDef.format.video.eCompressionFormat == OMX_VIDEO_CodingMPEG4) { + if (profileLevelType->nProfileIndex == 0) { + profileLevelType->eProfile = OMX_VIDEO_MPEG4ProfileSimple; + profileLevelType->eLevel = OMX_VIDEO_MPEG4Level5; + } else if (profileLevelType->nProfileIndex == 1) { + profileLevelType->eProfile = OMX_VIDEO_MPEG4ProfileAdvancedSimple; + profileLevelType->eLevel = OMX_VIDEO_MPEG4Level5; + } else { + DEBUG_PRINT_ERROR(""get_parameter: OMX_IndexParamVideoProfileLevelQuerySupported nProfileIndex ret NoMore %u"", (unsigned int)profileLevelType->nProfileIndex); + eRet = OMX_ErrorNoMore; + } + } else if (m_sOutPortDef.format.video.eCompressionFormat == OMX_VIDEO_CodingVP8) { + if (profileLevelType->nProfileIndex == 0) { + profileLevelType->eProfile = OMX_VIDEO_VP8ProfileMain; + profileLevelType->eLevel = OMX_VIDEO_VP8Level_Version0; + } else if (profileLevelType->nProfileIndex == 1) { + profileLevelType->eProfile = OMX_VIDEO_VP8ProfileMain; + profileLevelType->eLevel = OMX_VIDEO_VP8Level_Version1; + } else { + DEBUG_PRINT_LOW(""VP8: get_parameter: OMX_IndexParamVideoProfileLevelQuerySupported nProfileIndex ret NoMore %u"", + (unsigned int)profileLevelType->nProfileIndex); + eRet = OMX_ErrorNoMore; + } + } else if (m_sOutPortDef.format.video.eCompressionFormat == OMX_VIDEO_CodingHEVC) { + if (profileLevelType->nProfileIndex == 0) { + profileLevelType->eProfile = OMX_VIDEO_HEVCProfileMain; + profileLevelType->eLevel = OMX_VIDEO_HEVCMainTierLevel52; + } else if (profileLevelType->nProfileIndex == 1) { + profileLevelType->eProfile = OMX_VIDEO_HEVCProfileMain10; + profileLevelType->eLevel = OMX_VIDEO_HEVCMainTierLevel52; + } else { + DEBUG_PRINT_LOW(""HEVC: get_parameter: OMX_IndexParamVideoProfileLevelQuerySupported nProfileIndex ret NoMore %u"", + (unsigned int)profileLevelType->nProfileIndex); + eRet = OMX_ErrorNoMore; + } + } else { + DEBUG_PRINT_ERROR(""get_parameter: OMX_IndexParamVideoProfileLevelQuerySupported ret NoMore""); + eRet = OMX_ErrorNoMore; + } + } else { + DEBUG_PRINT_ERROR(""get_parameter: OMX_IndexParamVideoProfileLevelQuerySupported should be queried on Input port only %u"", (unsigned int)profileLevelType->nPortIndex); + eRet = OMX_ErrorBadPortIndex; + } + DEBUG_PRINT_LOW(""get_parameter: OMX_IndexParamVideoProfileLevelQuerySupported for Input port returned Profile:%u, Level:%u"", + (unsigned int)profileLevelType->eProfile, (unsigned int)profileLevelType->eLevel); + return eRet; +} +","@@ -80,7 +80,6 @@ + + + #define SZ_4K 0x1000 + #define SZ_1M 0x100000 +-#define SECURE_BUFPTR 0xDEADBEEF + + typedef struct OMXComponentCapabilityFlagsType { + ////////////////// OMX COMPONENT CAPABILITY RELATED MEMBERS +@@ -2252,7 +2251,7 @@ + + m_pInput_pmem[i].size = m_sInPortDef.nBufferSize; + m_pInput_pmem[i].offset = 0; + +- m_pInput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR; ++ m_pInput_pmem[i].buffer = NULL; + if(!secure_session) { + m_pInput_pmem[i].buffer = (unsigned char *)mmap( + NULL,m_pInput_pmem[i].size,PROT_READ|PROT_WRITE, +@@ -2260,6 +2259,7 @@ + + + if (m_pInput_pmem[i].buffer == MAP_FAILED) { + DEBUG_PRINT_ERROR(""ERROR: mmap() Failed""); ++ m_pInput_pmem[i].buffer = NULL; + close(m_pInput_pmem[i].fd); + #ifdef USE_ION + free_ion_memory(&m_pInput_ion[i]); +@@ -2443,7 +2443,7 @@ + + m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize; + m_pOutput_pmem[i].offset = 0; + +- m_pOutput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR; ++ m_pOutput_pmem[i].buffer = NULL; + if(!secure_session) { + #ifdef _MSM8974_ + m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL, +@@ -2456,6 +2456,7 @@ + + #endif + if (m_pOutput_pmem[i].buffer == MAP_FAILED) { + DEBUG_PRINT_ERROR(""ERROR: mmap() Failed""); ++ m_pOutput_pmem[i].buffer = NULL; + close(m_pOutput_pmem[i].fd); + #ifdef USE_ION + free_ion_memory(&m_pOutput_ion[i]); +@@ -2854,13 +2855,14 @@ + + m_pInput_pmem[i].size = m_sInPortDef.nBufferSize; + m_pInput_pmem[i].offset = 0; + +- m_pInput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR; ++ m_pInput_pmem[i].buffer = NULL; + if(!secure_session) { + m_pInput_pmem[i].buffer = (unsigned char *)mmap(NULL, + m_pInput_pmem[i].size,PROT_READ|PROT_WRITE, + MAP_SHARED,m_pInput_pmem[i].fd,0); + if (m_pInput_pmem[i].buffer == MAP_FAILED) { + DEBUG_PRINT_ERROR(""ERROR: mmap FAILED= %d"", errno); ++ m_pInput_pmem[i].buffer = NULL; + close(m_pInput_pmem[i].fd); + #ifdef USE_ION + free_ion_memory(&m_pInput_ion[i]); +@@ -2871,6 +2873,10 @@ + + //This should only be used for passing reference to source type and + //secure handle fd struct native_handle_t* + m_pInput_pmem[i].buffer = malloc(sizeof(OMX_U32) + sizeof(native_handle_t*)); ++ if (m_pInput_pmem[i].buffer == NULL) { ++ DEBUG_PRINT_ERROR(""%s: failed to allocate native-handle"", __func__); ++ return OMX_ErrorInsufficientResources; ++ } + (*bufferHdr)->nAllocLen = sizeof(OMX_U32) + sizeof(native_handle_t*); + } + +@@ -3016,7 +3022,7 @@ + + m_pOutput_pmem[i].size = m_sOutPortDef.nBufferSize; + m_pOutput_pmem[i].offset = 0; + +- m_pOutput_pmem[i].buffer = (OMX_U8 *)SECURE_BUFPTR; ++ m_pOutput_pmem[i].buffer = NULL; + if(!secure_session) { + #ifdef _MSM8974_ + m_pOutput_pmem[i].buffer = (unsigned char *)mmap(NULL, +@@ -3029,6 +3035,7 @@ + + #endif + if (m_pOutput_pmem[i].buffer == MAP_FAILED) { + DEBUG_PRINT_ERROR(""ERROR: MMAP_FAILED in o/p alloc buffer""); ++ m_pOutput_pmem[i].buffer = NULL; + close (m_pOutput_pmem[i].fd); + #ifdef USE_ION + free_ion_memory(&m_pOutput_ion[i]); +@@ -3040,6 +3047,10 @@ + + //This should only be used for passing reference to source type and + //secure handle fd struct native_handle_t* + m_pOutput_pmem[i].buffer = malloc(sizeof(OMX_U32) + sizeof(native_handle_t*)); ++ if (m_pOutput_pmem[i].buffer == NULL) { ++ DEBUG_PRINT_ERROR(""%s: Failed to allocate native-handle"", __func__); ++ return OMX_ErrorInsufficientResources; ++ } + (*bufferHdr)->nAllocLen = sizeof(OMX_U32) + sizeof(native_handle_t*); + native_handle_t *handle = native_handle_create(1, 0); + handle->data[0] = m_pOutput_pmem[i].fd; +",1396,1727,2048 +1483,"void JBIG2Bitmap::combine(JBIG2Bitmap *bitmap, int x, int y, + Guint combOp) { + int x0, x1, y0, y1, xx, yy; + Guchar *srcPtr, *destPtr; + Guint src0, src1, src, dest, s1, s2, m1, m2, m3; + GBool oneByte; + + if (y < -0x7fffffff) { + return; + } + if (y < 0) { + y0 = -y; + } else { + y0 = 0; + } + if (y + bitmap->h > h) { + y1 = h - y; + } else { + y1 = bitmap->h; + } + if (y0 >= y1) { + return; + } + + if (x >= 0) { + x0 = x & ~7; + } else { + x0 = 0; + } + x1 = x + bitmap->w; + if (x1 > w) { + x1 = w; + } + if (x0 >= x1) { + return; + } + + s1 = x & 7; + s2 = 8 - s1; + m1 = 0xff >> (x1 & 7); + m2 = 0xff << (((x1 & 7) == 0) ? 0 : 8 - (x1 & 7)); + m3 = (0xff >> s1) & m2; + + oneByte = x0 == ((x1 - 1) & ~7); + + for (yy = y0; yy < y1; ++yy) { + + if (oneByte) { + if (x >= 0) { + destPtr = data + (y + yy) * line + (x >> 3); + srcPtr = bitmap->data + yy * bitmap->line; + dest = *destPtr; + src1 = *srcPtr; + switch (combOp) { + case 0: // or + dest |= (src1 >> s1) & m2; + break; + case 1: // and + dest &= ((0xff00 | src1) >> s1) | m1; + break; + case 2: // xor + dest ^= (src1 >> s1) & m2; + break; + case 3: // xnor + dest ^= ((src1 ^ 0xff) >> s1) & m2; + break; + case 4: // replace + dest = (dest & ~m3) | ((src1 >> s1) & m3); + break; + } + *destPtr = dest; + } else { + destPtr = data + (y + yy) * line; + srcPtr = bitmap->data + yy * bitmap->line + (-x >> 3); + dest = *destPtr; + src1 = *srcPtr; + switch (combOp) { + case 0: // or + dest |= src1 & m2; + break; + case 1: // and + dest &= src1 | m1; + break; + case 2: // xor + dest ^= src1 & m2; + break; + case 3: // xnor + dest ^= (src1 ^ 0xff) & m2; + break; + case 4: // replace + dest = (src1 & m2) | (dest & m1); + break; + } + *destPtr = dest; + } + + } else { + + if (x >= 0) { + destPtr = data + (y + yy) * line + (x >> 3); + srcPtr = bitmap->data + yy * bitmap->line; + src1 = *srcPtr++; + dest = *destPtr; + switch (combOp) { + case 0: // or + dest |= src1 >> s1; + break; + case 1: // and + dest &= (0xff00 | src1) >> s1; + break; + case 2: // xor + dest ^= src1 >> s1; + break; + case 3: // xnor + dest ^= (src1 ^ 0xff) >> s1; + break; + case 4: // replace + dest = (dest & (0xff << s2)) | (src1 >> s1); + break; + } + *destPtr++ = dest; + xx = x0 + 8; + } else { + destPtr = data + (y + yy) * line; + srcPtr = bitmap->data + yy * bitmap->line + (-x >> 3); + src1 = *srcPtr++; + xx = x0; + } + + for (; xx < x1 - 8; xx += 8) { + dest = *destPtr; + src0 = src1; + src1 = *srcPtr++; + src = (((src0 << 8) | src1) >> s1) & 0xff; + switch (combOp) { + case 0: // or + dest |= src; + break; + case 1: // and + dest &= src; + break; + case 2: // xor + dest ^= src; + break; + case 3: // xnor + dest ^= src ^ 0xff; + break; + case 4: // replace + dest = src; + break; + } + *destPtr++ = dest; + } + + dest = *destPtr; + src0 = src1; + src1 = *srcPtr++; + src = (((src0 << 8) | src1) >> s1) & 0xff; + switch (combOp) { + case 0: // or + dest |= src & m2; + break; + case 1: // and + dest &= src | m1; + break; + case 2: // xor + dest ^= src & m2; + break; + case 3: // xnor + dest ^= (src ^ 0xff) & m2; + break; + case 4: // replace + dest = (src & m2) | (dest & m1); + break; + } + *destPtr = dest; + } + } +} +",0,"void JBIG2Bitmap::combine(JBIG2Bitmap *bitmap, int x, int y, + Guint combOp) { + int x0, x1, y0, y1, xx, yy; + Guchar *srcPtr, *destPtr; + Guint src0, src1, src, dest, s1, s2, m1, m2, m3; + GBool oneByte; + + if (y < -0x7fffffff) { + return; + } + if (y < 0) { + y0 = -y; + } else { + y0 = 0; + } + if (y + bitmap->h > h) { + y1 = h - y; + } else { + y1 = bitmap->h; + } + if (y0 >= y1) { + return; + } + + if (x >= 0) { + x0 = x & ~7; + } else { + x0 = 0; + } + x1 = x + bitmap->w; + if (x1 > w) { + x1 = w; + } + if (x0 >= x1) { + return; + } + + s1 = x & 7; + s2 = 8 - s1; + m1 = 0xff >> (x1 & 7); + m2 = 0xff << (((x1 & 7) == 0) ? 0 : 8 - (x1 & 7)); + m3 = (0xff >> s1) & m2; + + oneByte = x0 == ((x1 - 1) & ~7); + + for (yy = y0; yy < y1; ++yy) { + + if (oneByte) { + if (x >= 0) { + destPtr = data + (y + yy) * line + (x >> 3); + srcPtr = bitmap->data + yy * bitmap->line; + dest = *destPtr; + src1 = *srcPtr; + switch (combOp) { + case 0: // or + dest |= (src1 >> s1) & m2; + break; + case 1: // and + dest &= ((0xff00 | src1) >> s1) | m1; + break; + case 2: // xor + dest ^= (src1 >> s1) & m2; + break; + case 3: // xnor + dest ^= ((src1 ^ 0xff) >> s1) & m2; + break; + case 4: // replace + dest = (dest & ~m3) | ((src1 >> s1) & m3); + break; + } + *destPtr = dest; + } else { + destPtr = data + (y + yy) * line; + srcPtr = bitmap->data + yy * bitmap->line + (-x >> 3); + dest = *destPtr; + src1 = *srcPtr; + switch (combOp) { + case 0: // or + dest |= src1 & m2; + break; + case 1: // and + dest &= src1 | m1; + break; + case 2: // xor + dest ^= src1 & m2; + break; + case 3: // xnor + dest ^= (src1 ^ 0xff) & m2; + break; + case 4: // replace + dest = (src1 & m2) | (dest & m1); + break; + } + *destPtr = dest; + } + + } else { + + if (x >= 0) { + destPtr = data + (y + yy) * line + (x >> 3); + srcPtr = bitmap->data + yy * bitmap->line; + src1 = *srcPtr++; + dest = *destPtr; + switch (combOp) { + case 0: // or + dest |= src1 >> s1; + break; + case 1: // and + dest &= (0xff00 | src1) >> s1; + break; + case 2: // xor + dest ^= src1 >> s1; + break; + case 3: // xnor + dest ^= (src1 ^ 0xff) >> s1; + break; + case 4: // replace + dest = (dest & (0xff << s2)) | (src1 >> s1); + break; + } + *destPtr++ = dest; + xx = x0 + 8; + } else { + destPtr = data + (y + yy) * line; + srcPtr = bitmap->data + yy * bitmap->line + (-x >> 3); + src1 = *srcPtr++; + xx = x0; + } + + for (; xx < x1 - 8; xx += 8) { + dest = *destPtr; + src0 = src1; + src1 = *srcPtr++; + src = (((src0 << 8) | src1) >> s1) & 0xff; + switch (combOp) { + case 0: // or + dest |= src; + break; + case 1: // and + dest &= src; + break; + case 2: // xor + dest ^= src; + break; + case 3: // xnor + dest ^= src ^ 0xff; + break; + case 4: // replace + dest = src; + break; + } + *destPtr++ = dest; + } + + dest = *destPtr; + src0 = src1; + src1 = *srcPtr++; + src = (((src0 << 8) | src1) >> s1) & 0xff; + switch (combOp) { + case 0: // or + dest |= src & m2; + break; + case 1: // and + dest &= src | m1; + break; + case 2: // xor + dest ^= src & m2; + break; + case 3: // xnor + dest ^= (src ^ 0xff) & m2; + break; + case 4: // replace + dest = (src & m2) | (dest & m1); + break; + } + *destPtr = dest; + } + } +} +","@@ -1495,7 +1495,7 @@ void JBIG2Stream::readSegments() { + // arithmetic-coded symbol dictionary segments when numNewSyms + // == 0. Segments like this often occur for blank pages. + +- error(errSyntaxError, curStr->getPos(), ""{0:d} extraneous byte{1:s} after segment"", ++ error(errSyntaxError, curStr->getPos(), ""{0:lld} extraneous byte{1:s} after segment"", + segExtraBytes, (segExtraBytes > 1) ? ""s"" : """"); + + // Burn through the remaining bytes -- inefficient, but",1345,1676,2048 +8487,"static void build_sit_entries(struct f2fs_sb_info *sbi) +{ + struct sit_info *sit_i = SIT_I(sbi); + struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA); + struct f2fs_journal *journal = curseg->journal; + struct seg_entry *se; + struct f2fs_sit_entry sit; + int sit_blk_cnt = SIT_BLK_CNT(sbi); + unsigned int i, start, end; + unsigned int readed, start_blk = 0; + + do { + readed = ra_meta_pages(sbi, start_blk, BIO_MAX_PAGES, + META_SIT, true); + + start = start_blk * sit_i->sents_per_block; + end = (start_blk + readed) * sit_i->sents_per_block; + + for (; start < end && start < MAIN_SEGS(sbi); start++) { + struct f2fs_sit_block *sit_blk; + struct page *page; + + se = &sit_i->sentries[start]; + page = get_current_sit_page(sbi, start); + sit_blk = (struct f2fs_sit_block *)page_address(page); + sit = sit_blk->entries[SIT_ENTRY_OFFSET(sit_i, start)]; + f2fs_put_page(page, 1); + + check_block_count(sbi, start, &sit); + seg_info_from_raw_sit(se, &sit); + + /* build discard map only one time */ + if (f2fs_discard_en(sbi)) { + if (is_set_ckpt_flags(sbi, CP_TRIMMED_FLAG)) { + memset(se->discard_map, 0xff, + SIT_VBLOCK_MAP_SIZE); + } else { + memcpy(se->discard_map, + se->cur_valid_map, + SIT_VBLOCK_MAP_SIZE); + sbi->discard_blks += + sbi->blocks_per_seg - + se->valid_blocks; + } + } + + if (sbi->segs_per_sec > 1) + get_sec_entry(sbi, start)->valid_blocks += + se->valid_blocks; + } + start_blk += readed; + } while (start_blk < sit_blk_cnt); + + down_read(&curseg->journal_rwsem); + for (i = 0; i < sits_in_cursum(journal); i++) { + unsigned int old_valid_blocks; + + start = le32_to_cpu(segno_in_journal(journal, i)); + se = &sit_i->sentries[start]; + sit = sit_in_journal(journal, i); + + old_valid_blocks = se->valid_blocks; + + check_block_count(sbi, start, &sit); + seg_info_from_raw_sit(se, &sit); + + if (f2fs_discard_en(sbi)) { + if (is_set_ckpt_flags(sbi, CP_TRIMMED_FLAG)) { + memset(se->discard_map, 0xff, + SIT_VBLOCK_MAP_SIZE); + } else { + memcpy(se->discard_map, se->cur_valid_map, + SIT_VBLOCK_MAP_SIZE); + sbi->discard_blks += old_valid_blocks - + se->valid_blocks; + } + } + + if (sbi->segs_per_sec > 1) + get_sec_entry(sbi, start)->valid_blocks += + se->valid_blocks - old_valid_blocks; + } + up_read(&curseg->journal_rwsem); +} +",0,"static void build_sit_entries(struct f2fs_sb_info *sbi) +{ + struct sit_info *sit_i = SIT_I(sbi); + struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_COLD_DATA); + struct f2fs_journal *journal = curseg->journal; + struct seg_entry *se; + struct f2fs_sit_entry sit; + int sit_blk_cnt = SIT_BLK_CNT(sbi); + unsigned int i, start, end; + unsigned int readed, start_blk = 0; + + do { + readed = ra_meta_pages(sbi, start_blk, BIO_MAX_PAGES, + META_SIT, true); + + start = start_blk * sit_i->sents_per_block; + end = (start_blk + readed) * sit_i->sents_per_block; + + for (; start < end && start < MAIN_SEGS(sbi); start++) { + struct f2fs_sit_block *sit_blk; + struct page *page; + + se = &sit_i->sentries[start]; + page = get_current_sit_page(sbi, start); + sit_blk = (struct f2fs_sit_block *)page_address(page); + sit = sit_blk->entries[SIT_ENTRY_OFFSET(sit_i, start)]; + f2fs_put_page(page, 1); + + check_block_count(sbi, start, &sit); + seg_info_from_raw_sit(se, &sit); + + /* build discard map only one time */ + if (f2fs_discard_en(sbi)) { + if (is_set_ckpt_flags(sbi, CP_TRIMMED_FLAG)) { + memset(se->discard_map, 0xff, + SIT_VBLOCK_MAP_SIZE); + } else { + memcpy(se->discard_map, + se->cur_valid_map, + SIT_VBLOCK_MAP_SIZE); + sbi->discard_blks += + sbi->blocks_per_seg - + se->valid_blocks; + } + } + + if (sbi->segs_per_sec > 1) + get_sec_entry(sbi, start)->valid_blocks += + se->valid_blocks; + } + start_blk += readed; + } while (start_blk < sit_blk_cnt); + + down_read(&curseg->journal_rwsem); + for (i = 0; i < sits_in_cursum(journal); i++) { + unsigned int old_valid_blocks; + + start = le32_to_cpu(segno_in_journal(journal, i)); + se = &sit_i->sentries[start]; + sit = sit_in_journal(journal, i); + + old_valid_blocks = se->valid_blocks; + + check_block_count(sbi, start, &sit); + seg_info_from_raw_sit(se, &sit); + + if (f2fs_discard_en(sbi)) { + if (is_set_ckpt_flags(sbi, CP_TRIMMED_FLAG)) { + memset(se->discard_map, 0xff, + SIT_VBLOCK_MAP_SIZE); + } else { + memcpy(se->discard_map, se->cur_valid_map, + SIT_VBLOCK_MAP_SIZE); + sbi->discard_blks += old_valid_blocks - + se->valid_blocks; + } + } + + if (sbi->segs_per_sec > 1) + get_sec_entry(sbi, start)->valid_blocks += + se->valid_blocks - old_valid_blocks; + } + up_read(&curseg->journal_rwsem); +} +","@@ -566,6 +566,9 @@ int create_flush_cmd_control(struct f2fs_sb_info *sbi) + init_waitqueue_head(&fcc->flush_wait_queue); + init_llist_head(&fcc->issue_list); + SM_I(sbi)->fcc_info = fcc; ++ if (!test_opt(sbi, FLUSH_MERGE)) ++ return err; ++ + init_thread: + fcc->f2fs_issue_flush = kthread_run(issue_flush_thread, sbi, + ""f2fs_flush-%u:%u"", MAJOR(dev), MINOR(dev)); +@@ -3240,7 +3243,7 @@ int build_segment_manager(struct f2fs_sb_info *sbi) + + INIT_LIST_HEAD(&sm_info->sit_entry_set); + +- if (test_opt(sbi, FLUSH_MERGE) && !f2fs_readonly(sbi->sb)) { ++ if (!f2fs_readonly(sbi->sb)) { + err = create_flush_cmd_control(sbi); + if (err) + return err;",731,1062,2048 +7324,"static MagickBooleanType ReadOneLayer(const ImageInfo *image_info,Image* image, + XCFDocInfo* inDocInfo,XCFLayerInfo *outLayer,const ssize_t layer, + ExceptionInfo *exception) +{ + MagickOffsetType + offset; + + unsigned int + foundPropEnd = 0; + + size_t + hierarchy_offset, + layer_mask_offset; + + /* clear the block! */ + (void) ResetMagickMemory( outLayer, 0, sizeof( XCFLayerInfo ) ); + /* read in the layer width, height, type and name */ + outLayer->width = ReadBlobMSBLong(image); + outLayer->height = ReadBlobMSBLong(image); + outLayer->type = ReadBlobMSBLong(image); + (void) ReadBlobStringWithLongSize(image, outLayer->name, + sizeof(outLayer->name),exception); + /* read the layer properties! */ + foundPropEnd = 0; + while ( (foundPropEnd == MagickFalse) && (EOFBlob(image) == MagickFalse) ) { + PropType prop_type = (PropType) ReadBlobMSBLong(image); + size_t prop_size = ReadBlobMSBLong(image); + switch (prop_type) + { + case PROP_END: + foundPropEnd = 1; + break; + case PROP_ACTIVE_LAYER: + outLayer->active = 1; + break; + case PROP_FLOATING_SELECTION: + outLayer->floating_offset = ReadBlobMSBLong(image); + break; + case PROP_OPACITY: + outLayer->alpha = ReadBlobMSBLong(image); + break; + case PROP_VISIBLE: + outLayer->visible = ReadBlobMSBLong(image); + break; + case PROP_LINKED: + outLayer->linked = ReadBlobMSBLong(image); + break; + case PROP_PRESERVE_TRANSPARENCY: + outLayer->preserve_trans = ReadBlobMSBLong(image); + break; + case PROP_APPLY_MASK: + outLayer->apply_mask = ReadBlobMSBLong(image); + break; + case PROP_EDIT_MASK: + outLayer->edit_mask = ReadBlobMSBLong(image); + break; + case PROP_SHOW_MASK: + outLayer->show_mask = ReadBlobMSBLong(image); + break; + case PROP_OFFSETS: + outLayer->offset_x = (int) ReadBlobMSBLong(image); + outLayer->offset_y = (int) ReadBlobMSBLong(image); + break; + case PROP_MODE: + outLayer->mode = ReadBlobMSBLong(image); + break; + case PROP_TATTOO: + outLayer->preserve_trans = ReadBlobMSBLong(image); + break; + case PROP_PARASITES: + { + if (DiscardBlobBytes(image,prop_size) == MagickFalse) + ThrowFileException(exception,CorruptImageError, + ""UnexpectedEndOfFile"",image->filename); + + /* + ssize_t base = info->cp; + GimpParasite *p; + while (info->cp - base < prop_size) + { + p = xcf_load_parasite(info); + gimp_drawable_parasite_attach(GIMP_DRAWABLE(layer), p); + gimp_parasite_free(p); + } + if (info->cp - base != prop_size) + g_message (""Error detected while loading a layer's parasites""); + */ + } + break; + default: + /* g_message (""unexpected/unknown layer property: %d (skipping)"", + prop_type); */ + + { + int buf[16]; + ssize_t amount; + + /* read over it... */ + while ((prop_size > 0) && (EOFBlob(image) == MagickFalse)) + { + amount = (ssize_t) MagickMin(16, prop_size); + amount = ReadBlob(image, (size_t) amount, (unsigned char *) &buf); + if (!amount) + ThrowBinaryException(CorruptImageError,""CorruptImage"", + image->filename); + prop_size -= (size_t) MagickMin(16, (size_t) amount); + } + } + break; + } + } + + if (foundPropEnd == MagickFalse) + return(MagickFalse); + /* allocate the image for this layer */ + if (image_info->number_scenes != 0) + { + ssize_t + scene; + + scene=inDocInfo->number_layers-layer-1; + if (scene > (ssize_t) (image_info->scene+image_info->number_scenes-1)) + { + outLayer->image=CloneImage(image,0,0,MagickTrue,exception); + if (outLayer->image == (Image *) NULL) + return(MagickFalse); + InitXCFImage(outLayer,exception); + return(MagickTrue); + } + } + outLayer->image=CloneImage(image,outLayer->width, outLayer->height,MagickTrue, + exception); + if (outLayer->image == (Image *) NULL) + return(MagickFalse); + /* clear the image based on the layer opacity */ + outLayer->image->background_color.alpha= + ScaleCharToQuantum((unsigned char) outLayer->alpha); + (void) SetImageBackgroundColor(outLayer->image,exception); + + InitXCFImage(outLayer,exception); + + /* set the compositing mode */ + outLayer->image->compose = GIMPBlendModeToCompositeOperator( outLayer->mode ); + if ( outLayer->visible == MagickFalse ) + { + /* BOGUS: should really be separate member var! */ + outLayer->image->compose = NoCompositeOp; + } + + /* read the hierarchy and layer mask offsets */ + hierarchy_offset = ReadBlobMSBLong(image); + layer_mask_offset = ReadBlobMSBLong(image); + + /* read in the hierarchy */ + offset=SeekBlob(image, (MagickOffsetType) hierarchy_offset, SEEK_SET); + if (offset < 0) + (void) ThrowMagickException(exception,GetMagickModule(), + CorruptImageError,""InvalidImageHeader"",""`%s'"",image->filename); + if (load_hierarchy (image, inDocInfo, outLayer, exception) == 0) + return(MagickFalse); + + /* read in the layer mask */ + if (layer_mask_offset != 0) + { + offset=SeekBlob(image, (MagickOffsetType) layer_mask_offset, SEEK_SET); + +#if 0 /* BOGUS: support layer masks! */ + layer_mask = xcf_load_layer_mask (info, gimage); + if (layer_mask == 0) + goto error; + + /* set the offsets of the layer_mask */ + GIMP_DRAWABLE (layer_mask)->offset_x = GIMP_DRAWABLE (layer)->offset_x; + GIMP_DRAWABLE (layer_mask)->offset_y = GIMP_DRAWABLE (layer)->offset_y; + + gimp_layer_add_mask (layer, layer_mask, MagickFalse); + + layer->mask->apply_mask = apply_mask; + layer->mask->edit_mask = edit_mask; + layer->mask->show_mask = show_mask; +#endif + } + + /* attach the floating selection... */ +#if 0 /* BOGUS: we may need to read this, even if we don't support it! */ + if (add_floating_sel) + { + GimpLayer *floating_sel; + + floating_sel = info->floating_sel; + floating_sel_attach (floating_sel, GIMP_DRAWABLE (layer)); + } +#endif + + return MagickTrue; +} +",0,"static MagickBooleanType ReadOneLayer(const ImageInfo *image_info,Image* image, + XCFDocInfo* inDocInfo,XCFLayerInfo *outLayer,const ssize_t layer, + ExceptionInfo *exception) +{ + MagickOffsetType + offset; + + unsigned int + foundPropEnd = 0; + + size_t + hierarchy_offset, + layer_mask_offset; + + /* clear the block! */ + (void) ResetMagickMemory( outLayer, 0, sizeof( XCFLayerInfo ) ); + /* read in the layer width, height, type and name */ + outLayer->width = ReadBlobMSBLong(image); + outLayer->height = ReadBlobMSBLong(image); + outLayer->type = ReadBlobMSBLong(image); + (void) ReadBlobStringWithLongSize(image, outLayer->name, + sizeof(outLayer->name),exception); + /* read the layer properties! */ + foundPropEnd = 0; + while ( (foundPropEnd == MagickFalse) && (EOFBlob(image) == MagickFalse) ) { + PropType prop_type = (PropType) ReadBlobMSBLong(image); + size_t prop_size = ReadBlobMSBLong(image); + switch (prop_type) + { + case PROP_END: + foundPropEnd = 1; + break; + case PROP_ACTIVE_LAYER: + outLayer->active = 1; + break; + case PROP_FLOATING_SELECTION: + outLayer->floating_offset = ReadBlobMSBLong(image); + break; + case PROP_OPACITY: + outLayer->alpha = ReadBlobMSBLong(image); + break; + case PROP_VISIBLE: + outLayer->visible = ReadBlobMSBLong(image); + break; + case PROP_LINKED: + outLayer->linked = ReadBlobMSBLong(image); + break; + case PROP_PRESERVE_TRANSPARENCY: + outLayer->preserve_trans = ReadBlobMSBLong(image); + break; + case PROP_APPLY_MASK: + outLayer->apply_mask = ReadBlobMSBLong(image); + break; + case PROP_EDIT_MASK: + outLayer->edit_mask = ReadBlobMSBLong(image); + break; + case PROP_SHOW_MASK: + outLayer->show_mask = ReadBlobMSBLong(image); + break; + case PROP_OFFSETS: + outLayer->offset_x = (int) ReadBlobMSBLong(image); + outLayer->offset_y = (int) ReadBlobMSBLong(image); + break; + case PROP_MODE: + outLayer->mode = ReadBlobMSBLong(image); + break; + case PROP_TATTOO: + outLayer->preserve_trans = ReadBlobMSBLong(image); + break; + case PROP_PARASITES: + { + if (DiscardBlobBytes(image,prop_size) == MagickFalse) + ThrowFileException(exception,CorruptImageError, + ""UnexpectedEndOfFile"",image->filename); + + /* + ssize_t base = info->cp; + GimpParasite *p; + while (info->cp - base < prop_size) + { + p = xcf_load_parasite(info); + gimp_drawable_parasite_attach(GIMP_DRAWABLE(layer), p); + gimp_parasite_free(p); + } + if (info->cp - base != prop_size) + g_message (""Error detected while loading a layer's parasites""); + */ + } + break; + default: + /* g_message (""unexpected/unknown layer property: %d (skipping)"", + prop_type); */ + + { + int buf[16]; + ssize_t amount; + + /* read over it... */ + while ((prop_size > 0) && (EOFBlob(image) == MagickFalse)) + { + amount = (ssize_t) MagickMin(16, prop_size); + amount = ReadBlob(image, (size_t) amount, (unsigned char *) &buf); + if (!amount) + ThrowBinaryException(CorruptImageError,""CorruptImage"", + image->filename); + prop_size -= (size_t) MagickMin(16, (size_t) amount); + } + } + break; + } + } + + if (foundPropEnd == MagickFalse) + return(MagickFalse); + /* allocate the image for this layer */ + if (image_info->number_scenes != 0) + { + ssize_t + scene; + + scene=inDocInfo->number_layers-layer-1; + if (scene > (ssize_t) (image_info->scene+image_info->number_scenes-1)) + { + outLayer->image=CloneImage(image,0,0,MagickTrue,exception); + if (outLayer->image == (Image *) NULL) + return(MagickFalse); + InitXCFImage(outLayer,exception); + return(MagickTrue); + } + } + outLayer->image=CloneImage(image,outLayer->width, outLayer->height,MagickTrue, + exception); + if (outLayer->image == (Image *) NULL) + return(MagickFalse); + /* clear the image based on the layer opacity */ + outLayer->image->background_color.alpha= + ScaleCharToQuantum((unsigned char) outLayer->alpha); + (void) SetImageBackgroundColor(outLayer->image,exception); + + InitXCFImage(outLayer,exception); + + /* set the compositing mode */ + outLayer->image->compose = GIMPBlendModeToCompositeOperator( outLayer->mode ); + if ( outLayer->visible == MagickFalse ) + { + /* BOGUS: should really be separate member var! */ + outLayer->image->compose = NoCompositeOp; + } + + /* read the hierarchy and layer mask offsets */ + hierarchy_offset = ReadBlobMSBLong(image); + layer_mask_offset = ReadBlobMSBLong(image); + + /* read in the hierarchy */ + offset=SeekBlob(image, (MagickOffsetType) hierarchy_offset, SEEK_SET); + if (offset < 0) + (void) ThrowMagickException(exception,GetMagickModule(), + CorruptImageError,""InvalidImageHeader"",""`%s'"",image->filename); + if (load_hierarchy (image, inDocInfo, outLayer, exception) == 0) + return(MagickFalse); + + /* read in the layer mask */ + if (layer_mask_offset != 0) + { + offset=SeekBlob(image, (MagickOffsetType) layer_mask_offset, SEEK_SET); + +#if 0 /* BOGUS: support layer masks! */ + layer_mask = xcf_load_layer_mask (info, gimage); + if (layer_mask == 0) + goto error; + + /* set the offsets of the layer_mask */ + GIMP_DRAWABLE (layer_mask)->offset_x = GIMP_DRAWABLE (layer)->offset_x; + GIMP_DRAWABLE (layer_mask)->offset_y = GIMP_DRAWABLE (layer)->offset_y; + + gimp_layer_add_mask (layer, layer_mask, MagickFalse); + + layer->mask->apply_mask = apply_mask; + layer->mask->edit_mask = edit_mask; + layer->mask->show_mask = show_mask; +#endif + } + + /* attach the floating selection... */ +#if 0 /* BOGUS: we may need to read this, even if we don't support it! */ + if (add_floating_sel) + { + GimpLayer *floating_sel; + + floating_sel = info->floating_sel; + floating_sel_attach (floating_sel, GIMP_DRAWABLE (layer)); + } +#endif + + return MagickTrue; +} +","@@ -347,7 +347,8 @@ static MagickBooleanType load_tile(Image *image,Image *tile_image, + *xcfdata, + *xcfodata; + +- xcfdata=(XCFPixelInfo *) AcquireQuantumMemory(data_length,sizeof(*xcfdata)); ++ xcfdata=(XCFPixelInfo *) AcquireQuantumMemory(MagickMax(data_length, ++ tile_image->columns*tile_image->rows),sizeof(*xcfdata)); + if (xcfdata == (XCFPixelInfo *) NULL) + ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", + image->filename);",1617,1948,2048 +7438,"static int mpeg4_decode_partitioned_mb(MpegEncContext *s, int16_t block[6][64]) +{ + Mpeg4DecContext *ctx = s->avctx->priv_data; + int cbp, mb_type; + const int xy = s->mb_x + s->mb_y * s->mb_stride; + + av_assert2(s == (void*)ctx); + + mb_type = s->current_picture.mb_type[xy]; + cbp = s->cbp_table[xy]; + + ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold; + + if (s->current_picture.qscale_table[xy] != s->qscale) + ff_set_qscale(s, s->current_picture.qscale_table[xy]); + + if (s->pict_type == AV_PICTURE_TYPE_P || + s->pict_type == AV_PICTURE_TYPE_S) { + int i; + for (i = 0; i < 4; i++) { + s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0]; + s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1]; + } + s->mb_intra = IS_INTRA(mb_type); + + if (IS_SKIP(mb_type)) { + /* skip mb */ + for (i = 0; i < 6; i++) + s->block_last_index[i] = -1; + s->mv_dir = MV_DIR_FORWARD; + s->mv_type = MV_TYPE_16X16; + if (s->pict_type == AV_PICTURE_TYPE_S + && ctx->vol_sprite_usage == GMC_SPRITE) { + s->mcsel = 1; + s->mb_skipped = 0; + } else { + s->mcsel = 0; + s->mb_skipped = 1; + } + } else if (s->mb_intra) { + s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]); + } else if (!s->mb_intra) { + + s->mv_dir = MV_DIR_FORWARD; + if (IS_8X8(mb_type)) { + s->mv_type = MV_TYPE_8X8; + } else { + s->mv_type = MV_TYPE_16X16; + } + } + } else { /* I-Frame */ + s->mb_intra = 1; + s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]); + } + + if (!IS_SKIP(mb_type)) { + int i; + s->bdsp.clear_blocks(s->block[0]); + /* decode each block */ + for (i = 0; i < 6; i++) { + if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, s->mb_intra, ctx->rvlc) < 0) { + av_log(s->avctx, AV_LOG_ERROR, + ""texture corrupted at %d %d %d\n"", + s->mb_x, s->mb_y, s->mb_intra); + return AVERROR_INVALIDDATA; + } + cbp += cbp; + } + } + + /* per-MB end of slice check */ + if (--s->mb_num_left <= 0) { + if (mpeg4_is_resync(ctx)) + return SLICE_END; + else + return SLICE_NOEND; + } else { + if (mpeg4_is_resync(ctx)) { + const int delta = s->mb_x + 1 == s->mb_width ? 2 : 1; + if (s->cbp_table[xy + delta]) + return SLICE_END; + } + return SLICE_OK; + } +} +",0,"static int mpeg4_decode_partitioned_mb(MpegEncContext *s, int16_t block[6][64]) +{ + Mpeg4DecContext *ctx = s->avctx->priv_data; + int cbp, mb_type; + const int xy = s->mb_x + s->mb_y * s->mb_stride; + + av_assert2(s == (void*)ctx); + + mb_type = s->current_picture.mb_type[xy]; + cbp = s->cbp_table[xy]; + + ctx->use_intra_dc_vlc = s->qscale < ctx->intra_dc_threshold; + + if (s->current_picture.qscale_table[xy] != s->qscale) + ff_set_qscale(s, s->current_picture.qscale_table[xy]); + + if (s->pict_type == AV_PICTURE_TYPE_P || + s->pict_type == AV_PICTURE_TYPE_S) { + int i; + for (i = 0; i < 4; i++) { + s->mv[0][i][0] = s->current_picture.motion_val[0][s->block_index[i]][0]; + s->mv[0][i][1] = s->current_picture.motion_val[0][s->block_index[i]][1]; + } + s->mb_intra = IS_INTRA(mb_type); + + if (IS_SKIP(mb_type)) { + /* skip mb */ + for (i = 0; i < 6; i++) + s->block_last_index[i] = -1; + s->mv_dir = MV_DIR_FORWARD; + s->mv_type = MV_TYPE_16X16; + if (s->pict_type == AV_PICTURE_TYPE_S + && ctx->vol_sprite_usage == GMC_SPRITE) { + s->mcsel = 1; + s->mb_skipped = 0; + } else { + s->mcsel = 0; + s->mb_skipped = 1; + } + } else if (s->mb_intra) { + s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]); + } else if (!s->mb_intra) { + + s->mv_dir = MV_DIR_FORWARD; + if (IS_8X8(mb_type)) { + s->mv_type = MV_TYPE_8X8; + } else { + s->mv_type = MV_TYPE_16X16; + } + } + } else { /* I-Frame */ + s->mb_intra = 1; + s->ac_pred = IS_ACPRED(s->current_picture.mb_type[xy]); + } + + if (!IS_SKIP(mb_type)) { + int i; + s->bdsp.clear_blocks(s->block[0]); + /* decode each block */ + for (i = 0; i < 6; i++) { + if (mpeg4_decode_block(ctx, block[i], i, cbp & 32, s->mb_intra, ctx->rvlc) < 0) { + av_log(s->avctx, AV_LOG_ERROR, + ""texture corrupted at %d %d %d\n"", + s->mb_x, s->mb_y, s->mb_intra); + return AVERROR_INVALIDDATA; + } + cbp += cbp; + } + } + + /* per-MB end of slice check */ + if (--s->mb_num_left <= 0) { + if (mpeg4_is_resync(ctx)) + return SLICE_END; + else + return SLICE_NOEND; + } else { + if (mpeg4_is_resync(ctx)) { + const int delta = s->mb_x + 1 == s->mb_width ? 2 : 1; + if (s->cbp_table[xy + delta]) + return SLICE_END; + } + return SLICE_OK; + } +} +","@@ -2867,11 +2867,13 @@ static int decode_vop_header(Mpeg4DecContext *ctx, GetBitContext *gb) + return 0; + } + +-static void read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb) ++static int read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb) + { + int i, j, v; + + if (get_bits1(gb)) { ++ if (get_bits_left(gb) < 64*8) ++ return AVERROR_INVALIDDATA; + /* intra_quantiser_matrix */ + for (i = 0; i < 64; i++) { + v = get_bits(gb, 8); +@@ -2882,13 +2884,17 @@ static void read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb) + } + + if (get_bits1(gb)) { ++ if (get_bits_left(gb) < 64*8) ++ return AVERROR_INVALIDDATA; + /* non_intra_quantiser_matrix */ + for (i = 0; i < 64; i++) { + get_bits(gb, 8); + } + } + + if (get_bits1(gb)) { ++ if (get_bits_left(gb) < 64*8) ++ return AVERROR_INVALIDDATA; + /* chroma_intra_quantiser_matrix */ + for (i = 0; i < 64; i++) { + v = get_bits(gb, 8); +@@ -2898,13 +2904,16 @@ static void read_quant_matrix_ext(MpegEncContext *s, GetBitContext *gb) + } + + if (get_bits1(gb)) { ++ if (get_bits_left(gb) < 64*8) ++ return AVERROR_INVALIDDATA; + /* chroma_non_intra_quantiser_matrix */ + for (i = 0; i < 64; i++) { + get_bits(gb, 8); + } + } + + next_start_code_studio(gb); ++ return 0; + } + + static void extension_and_user_data(MpegEncContext *s, GetBitContext *gb, int id)",838,1169,2048 +6011,"usbtest_probe(struct usb_interface *intf, const struct usb_device_id *id) +{ + struct usb_device *udev; + struct usbtest_dev *dev; + struct usbtest_info *info; + char *rtest, *wtest; + char *irtest, *iwtest; + char *intrtest, *intwtest; + + udev = interface_to_usbdev(intf); + +#ifdef GENERIC + /* specify devices by module parameters? */ + if (id->match_flags == 0) { + /* vendor match required, product match optional */ + if (!vendor || le16_to_cpu(udev->descriptor.idVendor) != (u16)vendor) + return -ENODEV; + if (product && le16_to_cpu(udev->descriptor.idProduct) != (u16)product) + return -ENODEV; + dev_info(&intf->dev, ""matched module params, "" + ""vend=0x%04x prod=0x%04x\n"", + le16_to_cpu(udev->descriptor.idVendor), + le16_to_cpu(udev->descriptor.idProduct)); + } +#endif + + dev = kzalloc(sizeof(*dev), GFP_KERNEL); + if (!dev) + return -ENOMEM; + info = (struct usbtest_info *) id->driver_info; + dev->info = info; + mutex_init(&dev->lock); + + dev->intf = intf; + + /* cacheline-aligned scratch for i/o */ + dev->buf = kmalloc(TBUF_SIZE, GFP_KERNEL); + if (dev->buf == NULL) { + kfree(dev); + return -ENOMEM; + } + + /* NOTE this doesn't yet test the handful of difference that are + * visible with high speed interrupts: bigger maxpacket (1K) and + * ""high bandwidth"" modes (up to 3 packets/uframe). + */ + rtest = wtest = """"; + irtest = iwtest = """"; + intrtest = intwtest = """"; + if (force_interrupt || udev->speed == USB_SPEED_LOW) { + if (info->ep_in) { + dev->in_pipe = usb_rcvintpipe(udev, info->ep_in); + rtest = "" intr-in""; + } + if (info->ep_out) { + dev->out_pipe = usb_sndintpipe(udev, info->ep_out); + wtest = "" intr-out""; + } + } else { + if (override_alt >= 0 || info->autoconf) { + int status; + + status = get_endpoints(dev, intf); + if (status < 0) { + WARNING(dev, ""couldn't get endpoints, %d\n"", + status); + kfree(dev->buf); + kfree(dev); + return status; + } + /* may find bulk or ISO pipes */ + } else { + if (info->ep_in) + dev->in_pipe = usb_rcvbulkpipe(udev, + info->ep_in); + if (info->ep_out) + dev->out_pipe = usb_sndbulkpipe(udev, + info->ep_out); + } + if (dev->in_pipe) + rtest = "" bulk-in""; + if (dev->out_pipe) + wtest = "" bulk-out""; + if (dev->in_iso_pipe) + irtest = "" iso-in""; + if (dev->out_iso_pipe) + iwtest = "" iso-out""; + if (dev->in_int_pipe) + intrtest = "" int-in""; + if (dev->out_int_pipe) + intwtest = "" int-out""; + } + + usb_set_intfdata(intf, dev); + dev_info(&intf->dev, ""%s\n"", info->name); + dev_info(&intf->dev, ""%s {control%s%s%s%s%s%s%s} tests%s\n"", + usb_speed_string(udev->speed), + info->ctrl_out ? "" in/out"" : """", + rtest, wtest, + irtest, iwtest, + intrtest, intwtest, + info->alt >= 0 ? "" (+alt)"" : """"); + return 0; +} +",0,"usbtest_probe(struct usb_interface *intf, const struct usb_device_id *id) +{ + struct usb_device *udev; + struct usbtest_dev *dev; + struct usbtest_info *info; + char *rtest, *wtest; + char *irtest, *iwtest; + char *intrtest, *intwtest; + + udev = interface_to_usbdev(intf); + +#ifdef GENERIC + /* specify devices by module parameters? */ + if (id->match_flags == 0) { + /* vendor match required, product match optional */ + if (!vendor || le16_to_cpu(udev->descriptor.idVendor) != (u16)vendor) + return -ENODEV; + if (product && le16_to_cpu(udev->descriptor.idProduct) != (u16)product) + return -ENODEV; + dev_info(&intf->dev, ""matched module params, "" + ""vend=0x%04x prod=0x%04x\n"", + le16_to_cpu(udev->descriptor.idVendor), + le16_to_cpu(udev->descriptor.idProduct)); + } +#endif + + dev = kzalloc(sizeof(*dev), GFP_KERNEL); + if (!dev) + return -ENOMEM; + info = (struct usbtest_info *) id->driver_info; + dev->info = info; + mutex_init(&dev->lock); + + dev->intf = intf; + + /* cacheline-aligned scratch for i/o */ + dev->buf = kmalloc(TBUF_SIZE, GFP_KERNEL); + if (dev->buf == NULL) { + kfree(dev); + return -ENOMEM; + } + + /* NOTE this doesn't yet test the handful of difference that are + * visible with high speed interrupts: bigger maxpacket (1K) and + * ""high bandwidth"" modes (up to 3 packets/uframe). + */ + rtest = wtest = """"; + irtest = iwtest = """"; + intrtest = intwtest = """"; + if (force_interrupt || udev->speed == USB_SPEED_LOW) { + if (info->ep_in) { + dev->in_pipe = usb_rcvintpipe(udev, info->ep_in); + rtest = "" intr-in""; + } + if (info->ep_out) { + dev->out_pipe = usb_sndintpipe(udev, info->ep_out); + wtest = "" intr-out""; + } + } else { + if (override_alt >= 0 || info->autoconf) { + int status; + + status = get_endpoints(dev, intf); + if (status < 0) { + WARNING(dev, ""couldn't get endpoints, %d\n"", + status); + kfree(dev->buf); + kfree(dev); + return status; + } + /* may find bulk or ISO pipes */ + } else { + if (info->ep_in) + dev->in_pipe = usb_rcvbulkpipe(udev, + info->ep_in); + if (info->ep_out) + dev->out_pipe = usb_sndbulkpipe(udev, + info->ep_out); + } + if (dev->in_pipe) + rtest = "" bulk-in""; + if (dev->out_pipe) + wtest = "" bulk-out""; + if (dev->in_iso_pipe) + irtest = "" iso-in""; + if (dev->out_iso_pipe) + iwtest = "" iso-out""; + if (dev->in_int_pipe) + intrtest = "" int-in""; + if (dev->out_int_pipe) + intwtest = "" int-out""; + } + + usb_set_intfdata(intf, dev); + dev_info(&intf->dev, ""%s\n"", info->name); + dev_info(&intf->dev, ""%s {control%s%s%s%s%s%s%s} tests%s\n"", + usb_speed_string(udev->speed), + info->ctrl_out ? "" in/out"" : """", + rtest, wtest, + irtest, iwtest, + intrtest, intwtest, + info->alt >= 0 ? "" (+alt)"" : """"); + return 0; +} +","@@ -202,12 +202,13 @@ get_endpoints(struct usbtest_dev *dev, struct usb_interface *intf) + return tmp; + } + +- if (in) { ++ if (in) + dev->in_pipe = usb_rcvbulkpipe(udev, + in->desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK); ++ if (out) + dev->out_pipe = usb_sndbulkpipe(udev, + out->desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK); +- } ++ + if (iso_in) { + dev->iso_in = &iso_in->desc; + dev->in_iso_pipe = usb_rcvisocpipe(udev,",887,1218,2048 +13229,"void PictureLayerImpl::RecalculateRasterScales() { + float old_raster_contents_scale = raster_contents_scale_; + float old_raster_page_scale = raster_page_scale_; + float old_raster_source_scale = raster_source_scale_; + + raster_device_scale_ = ideal_device_scale_; + raster_page_scale_ = ideal_page_scale_; + raster_source_scale_ = ideal_source_scale_; + raster_contents_scale_ = ideal_contents_scale_; + + if (old_raster_source_scale && + !draw_properties().screen_space_transform_is_animating && + !was_screen_space_transform_animating_ && + old_raster_source_scale != ideal_source_scale_) + raster_source_scale_is_fixed_ = true; + + if (raster_source_scale_is_fixed_) { + raster_contents_scale_ /= raster_source_scale_; + raster_source_scale_ = 1.f; + } + + bool is_pinching = layer_tree_impl()->PinchGestureActive(); + if (is_pinching && old_raster_contents_scale) { + bool zooming_out = old_raster_page_scale > ideal_page_scale_; + float desired_contents_scale = old_raster_contents_scale; + if (zooming_out) { + while (desired_contents_scale > ideal_contents_scale_) + desired_contents_scale /= kMaxScaleRatioDuringPinch; + } else { + while (desired_contents_scale < ideal_contents_scale_) + desired_contents_scale *= kMaxScaleRatioDuringPinch; + } + raster_contents_scale_ = tilings_->GetSnappedContentsScale( + desired_contents_scale, kSnapToExistingTilingRatio); + raster_page_scale_ = + raster_contents_scale_ / raster_device_scale_ / raster_source_scale_; + } + + if (draw_properties().screen_space_transform_is_animating && + !ShouldAdjustRasterScaleDuringScaleAnimations()) { + bool can_raster_at_maximum_scale = false; + float maximum_scale = draw_properties().maximum_animation_contents_scale; + if (maximum_scale) { + gfx::Size bounds_at_maximum_scale = gfx::ToCeiledSize( + gfx::ScaleSize(raster_source_->GetSize(), maximum_scale)); + int64 maximum_area = static_cast(bounds_at_maximum_scale.width()) * + static_cast(bounds_at_maximum_scale.height()); + gfx::Size viewport = layer_tree_impl()->device_viewport_size(); + int64 viewport_area = static_cast(viewport.width()) * + static_cast(viewport.height()); + if (maximum_area <= viewport_area) + can_raster_at_maximum_scale = true; + } + if (can_raster_at_maximum_scale) + raster_contents_scale_ = maximum_scale; + else + raster_contents_scale_ = 1.f * ideal_page_scale_ * ideal_device_scale_; + } + + raster_contents_scale_ = + std::max(raster_contents_scale_, MinimumContentsScale()); + + gfx::Size raster_bounds = gfx::ToCeiledSize( + gfx::ScaleSize(raster_source_->GetSize(), raster_contents_scale_)); + gfx::Size tile_size = CalculateTileSize(raster_bounds); + bool tile_covers_bounds = tile_size.width() >= raster_bounds.width() && + tile_size.height() >= raster_bounds.height(); + if (tile_size.IsEmpty() || tile_covers_bounds) { + low_res_raster_contents_scale_ = raster_contents_scale_; + return; + } + + float low_res_factor = + layer_tree_impl()->settings().low_res_contents_scale_factor; + low_res_raster_contents_scale_ = std::max( + raster_contents_scale_ * low_res_factor, + MinimumContentsScale()); + DCHECK_LE(low_res_raster_contents_scale_, raster_contents_scale_); + DCHECK_GE(low_res_raster_contents_scale_, MinimumContentsScale()); +} +",0,"void PictureLayerImpl::RecalculateRasterScales() { + float old_raster_contents_scale = raster_contents_scale_; + float old_raster_page_scale = raster_page_scale_; + float old_raster_source_scale = raster_source_scale_; + + raster_device_scale_ = ideal_device_scale_; + raster_page_scale_ = ideal_page_scale_; + raster_source_scale_ = ideal_source_scale_; + raster_contents_scale_ = ideal_contents_scale_; + + if (old_raster_source_scale && + !draw_properties().screen_space_transform_is_animating && + !was_screen_space_transform_animating_ && + old_raster_source_scale != ideal_source_scale_) + raster_source_scale_is_fixed_ = true; + + if (raster_source_scale_is_fixed_) { + raster_contents_scale_ /= raster_source_scale_; + raster_source_scale_ = 1.f; + } + + bool is_pinching = layer_tree_impl()->PinchGestureActive(); + if (is_pinching && old_raster_contents_scale) { + bool zooming_out = old_raster_page_scale > ideal_page_scale_; + float desired_contents_scale = old_raster_contents_scale; + if (zooming_out) { + while (desired_contents_scale > ideal_contents_scale_) + desired_contents_scale /= kMaxScaleRatioDuringPinch; + } else { + while (desired_contents_scale < ideal_contents_scale_) + desired_contents_scale *= kMaxScaleRatioDuringPinch; + } + raster_contents_scale_ = tilings_->GetSnappedContentsScale( + desired_contents_scale, kSnapToExistingTilingRatio); + raster_page_scale_ = + raster_contents_scale_ / raster_device_scale_ / raster_source_scale_; + } + + if (draw_properties().screen_space_transform_is_animating && + !ShouldAdjustRasterScaleDuringScaleAnimations()) { + bool can_raster_at_maximum_scale = false; + float maximum_scale = draw_properties().maximum_animation_contents_scale; + if (maximum_scale) { + gfx::Size bounds_at_maximum_scale = gfx::ToCeiledSize( + gfx::ScaleSize(raster_source_->GetSize(), maximum_scale)); + int64 maximum_area = static_cast(bounds_at_maximum_scale.width()) * + static_cast(bounds_at_maximum_scale.height()); + gfx::Size viewport = layer_tree_impl()->device_viewport_size(); + int64 viewport_area = static_cast(viewport.width()) * + static_cast(viewport.height()); + if (maximum_area <= viewport_area) + can_raster_at_maximum_scale = true; + } + if (can_raster_at_maximum_scale) + raster_contents_scale_ = maximum_scale; + else + raster_contents_scale_ = 1.f * ideal_page_scale_ * ideal_device_scale_; + } + + raster_contents_scale_ = + std::max(raster_contents_scale_, MinimumContentsScale()); + + gfx::Size raster_bounds = gfx::ToCeiledSize( + gfx::ScaleSize(raster_source_->GetSize(), raster_contents_scale_)); + gfx::Size tile_size = CalculateTileSize(raster_bounds); + bool tile_covers_bounds = tile_size.width() >= raster_bounds.width() && + tile_size.height() >= raster_bounds.height(); + if (tile_size.IsEmpty() || tile_covers_bounds) { + low_res_raster_contents_scale_ = raster_contents_scale_; + return; + } + + float low_res_factor = + layer_tree_impl()->settings().low_res_contents_scale_factor; + low_res_raster_contents_scale_ = std::max( + raster_contents_scale_ * low_res_factor, + MinimumContentsScale()); + DCHECK_LE(low_res_raster_contents_scale_, raster_contents_scale_); + DCHECK_GE(low_res_raster_contents_scale_, MinimumContentsScale()); +} +","@@ -69,8 +69,6 @@ PictureLayerImpl::PictureLayerImpl(LayerTreeImpl* tree_impl, + : LayerImpl(tree_impl, id), + twin_layer_(nullptr), + tilings_(CreatePictureLayerTilingSet()), +- // TODO(danakj): Can this be null to start? +- raster_source_(PicturePileImpl::Create()), + ideal_page_scale_(0.f), + ideal_device_scale_(0.f), + ideal_source_scale_(0.f), +@@ -585,7 +583,9 @@ void PictureLayerImpl::UpdateRasterSource( + << "" bounds "" << bounds().ToString() << "" pile "" + << raster_source->GetSize().ToString(); + +- bool could_have_tilings = CanHaveTilings(); ++ // The |raster_source_| is initially null, so have to check for that for the ++ // first frame. ++ bool could_have_tilings = raster_source_.get() && CanHaveTilings(); + raster_source_.swap(raster_source); + + // The |new_invalidation| must be cleared before updating tilings since they",765,1096,2048 +7740,"bson_iter_visit_all (bson_iter_t *iter, /* INOUT */ + const bson_visitor_t *visitor, /* IN */ + void *data) /* IN */ +{ + uint32_t bson_type; + const char *key; + bool unsupported; + + BSON_ASSERT (iter); + BSON_ASSERT (visitor); + + while (_bson_iter_next_internal (iter, 0, &key, &bson_type, &unsupported)) { + if (*key && !bson_utf8_validate (key, strlen (key), false)) { + iter->err_off = iter->off; + break; + } + + if (VISIT_BEFORE (iter, key, data)) { + return true; + } + + switch (bson_type) { + case BSON_TYPE_DOUBLE: + + if (VISIT_DOUBLE (iter, key, bson_iter_double (iter), data)) { + return true; + } + + break; + case BSON_TYPE_UTF8: { + uint32_t utf8_len; + const char *utf8; + + utf8 = bson_iter_utf8 (iter, &utf8_len); + + if (!bson_utf8_validate (utf8, utf8_len, true)) { + iter->err_off = iter->off; + return true; + } + + if (VISIT_UTF8 (iter, key, utf8_len, utf8, data)) { + return true; + } + } break; + case BSON_TYPE_DOCUMENT: { + const uint8_t *docbuf = NULL; + uint32_t doclen = 0; + bson_t b; + + bson_iter_document (iter, &doclen, &docbuf); + + if (bson_init_static (&b, docbuf, doclen) && + VISIT_DOCUMENT (iter, key, &b, data)) { + return true; + } + } break; + case BSON_TYPE_ARRAY: { + const uint8_t *docbuf = NULL; + uint32_t doclen = 0; + bson_t b; + + bson_iter_array (iter, &doclen, &docbuf); + + if (bson_init_static (&b, docbuf, doclen) && + VISIT_ARRAY (iter, key, &b, data)) { + return true; + } + } break; + case BSON_TYPE_BINARY: { + const uint8_t *binary = NULL; + bson_subtype_t subtype = BSON_SUBTYPE_BINARY; + uint32_t binary_len = 0; + + bson_iter_binary (iter, &subtype, &binary_len, &binary); + + if (VISIT_BINARY (iter, key, subtype, binary_len, binary, data)) { + return true; + } + } break; + case BSON_TYPE_UNDEFINED: + + if (VISIT_UNDEFINED (iter, key, data)) { + return true; + } + + break; + case BSON_TYPE_OID: + + if (VISIT_OID (iter, key, bson_iter_oid (iter), data)) { + return true; + } + + break; + case BSON_TYPE_BOOL: + + if (VISIT_BOOL (iter, key, bson_iter_bool (iter), data)) { + return true; + } + + break; + case BSON_TYPE_DATE_TIME: + + if (VISIT_DATE_TIME (iter, key, bson_iter_date_time (iter), data)) { + return true; + } + + break; + case BSON_TYPE_NULL: + + if (VISIT_NULL (iter, key, data)) { + return true; + } + + break; + case BSON_TYPE_REGEX: { + const char *regex = NULL; + const char *options = NULL; + regex = bson_iter_regex (iter, &options); + + if (!bson_utf8_validate (regex, strlen (regex), true)) { + iter->err_off = iter->off; + return true; + } + + if (VISIT_REGEX (iter, key, regex, options, data)) { + return true; + } + } break; + case BSON_TYPE_DBPOINTER: { + uint32_t collection_len = 0; + const char *collection = NULL; + const bson_oid_t *oid = NULL; + + bson_iter_dbpointer (iter, &collection_len, &collection, &oid); + + if (!bson_utf8_validate (collection, collection_len, true)) { + iter->err_off = iter->off; + return true; + } + + if (VISIT_DBPOINTER ( + iter, key, collection_len, collection, oid, data)) { + return true; + } + } break; + case BSON_TYPE_CODE: { + uint32_t code_len; + const char *code; + + code = bson_iter_code (iter, &code_len); + + if (!bson_utf8_validate (code, code_len, true)) { + iter->err_off = iter->off; + return true; + } + + if (VISIT_CODE (iter, key, code_len, code, data)) { + return true; + } + } break; + case BSON_TYPE_SYMBOL: { + uint32_t symbol_len; + const char *symbol; + + symbol = bson_iter_symbol (iter, &symbol_len); + + if (!bson_utf8_validate (symbol, symbol_len, true)) { + iter->err_off = iter->off; + return true; + } + + if (VISIT_SYMBOL (iter, key, symbol_len, symbol, data)) { + return true; + } + } break; + case BSON_TYPE_CODEWSCOPE: { + uint32_t length = 0; + const char *code; + const uint8_t *docbuf = NULL; + uint32_t doclen = 0; + bson_t b; + + code = bson_iter_codewscope (iter, &length, &doclen, &docbuf); + + if (!bson_utf8_validate (code, length, true)) { + iter->err_off = iter->off; + return true; + } + + if (bson_init_static (&b, docbuf, doclen) && + VISIT_CODEWSCOPE (iter, key, length, code, &b, data)) { + return true; + } + } break; + case BSON_TYPE_INT32: + + if (VISIT_INT32 (iter, key, bson_iter_int32 (iter), data)) { + return true; + } + + break; + case BSON_TYPE_TIMESTAMP: { + uint32_t timestamp; + uint32_t increment; + bson_iter_timestamp (iter, ×tamp, &increment); + + if (VISIT_TIMESTAMP (iter, key, timestamp, increment, data)) { + return true; + } + } break; + case BSON_TYPE_INT64: + + if (VISIT_INT64 (iter, key, bson_iter_int64 (iter), data)) { + return true; + } + + break; + case BSON_TYPE_DECIMAL128: { + bson_decimal128_t dec; + bson_iter_decimal128 (iter, &dec); + + if (VISIT_DECIMAL128 (iter, key, &dec, data)) { + return true; + } + } break; + case BSON_TYPE_MAXKEY: + + if (VISIT_MAXKEY (iter, bson_iter_key_unsafe (iter), data)) { + return true; + } + + break; + case BSON_TYPE_MINKEY: + + if (VISIT_MINKEY (iter, bson_iter_key_unsafe (iter), data)) { + return true; + } + + break; + case BSON_TYPE_EOD: + default: + break; + } + + if (VISIT_AFTER (iter, bson_iter_key_unsafe (iter), data)) { + return true; + } + } + + if (iter->err_off) { + if (unsupported && visitor->visit_unsupported_type && + bson_utf8_validate (key, strlen (key), false)) { + visitor->visit_unsupported_type (iter, key, bson_type, data); + return false; + } + + VISIT_CORRUPT (iter, data); + } + +#undef VISIT_FIELD + + return false; +} +",0,"bson_iter_visit_all (bson_iter_t *iter, /* INOUT */ + const bson_visitor_t *visitor, /* IN */ + void *data) /* IN */ +{ + uint32_t bson_type; + const char *key; + bool unsupported; + + BSON_ASSERT (iter); + BSON_ASSERT (visitor); + + while (_bson_iter_next_internal (iter, 0, &key, &bson_type, &unsupported)) { + if (*key && !bson_utf8_validate (key, strlen (key), false)) { + iter->err_off = iter->off; + break; + } + + if (VISIT_BEFORE (iter, key, data)) { + return true; + } + + switch (bson_type) { + case BSON_TYPE_DOUBLE: + + if (VISIT_DOUBLE (iter, key, bson_iter_double (iter), data)) { + return true; + } + + break; + case BSON_TYPE_UTF8: { + uint32_t utf8_len; + const char *utf8; + + utf8 = bson_iter_utf8 (iter, &utf8_len); + + if (!bson_utf8_validate (utf8, utf8_len, true)) { + iter->err_off = iter->off; + return true; + } + + if (VISIT_UTF8 (iter, key, utf8_len, utf8, data)) { + return true; + } + } break; + case BSON_TYPE_DOCUMENT: { + const uint8_t *docbuf = NULL; + uint32_t doclen = 0; + bson_t b; + + bson_iter_document (iter, &doclen, &docbuf); + + if (bson_init_static (&b, docbuf, doclen) && + VISIT_DOCUMENT (iter, key, &b, data)) { + return true; + } + } break; + case BSON_TYPE_ARRAY: { + const uint8_t *docbuf = NULL; + uint32_t doclen = 0; + bson_t b; + + bson_iter_array (iter, &doclen, &docbuf); + + if (bson_init_static (&b, docbuf, doclen) && + VISIT_ARRAY (iter, key, &b, data)) { + return true; + } + } break; + case BSON_TYPE_BINARY: { + const uint8_t *binary = NULL; + bson_subtype_t subtype = BSON_SUBTYPE_BINARY; + uint32_t binary_len = 0; + + bson_iter_binary (iter, &subtype, &binary_len, &binary); + + if (VISIT_BINARY (iter, key, subtype, binary_len, binary, data)) { + return true; + } + } break; + case BSON_TYPE_UNDEFINED: + + if (VISIT_UNDEFINED (iter, key, data)) { + return true; + } + + break; + case BSON_TYPE_OID: + + if (VISIT_OID (iter, key, bson_iter_oid (iter), data)) { + return true; + } + + break; + case BSON_TYPE_BOOL: + + if (VISIT_BOOL (iter, key, bson_iter_bool (iter), data)) { + return true; + } + + break; + case BSON_TYPE_DATE_TIME: + + if (VISIT_DATE_TIME (iter, key, bson_iter_date_time (iter), data)) { + return true; + } + + break; + case BSON_TYPE_NULL: + + if (VISIT_NULL (iter, key, data)) { + return true; + } + + break; + case BSON_TYPE_REGEX: { + const char *regex = NULL; + const char *options = NULL; + regex = bson_iter_regex (iter, &options); + + if (!bson_utf8_validate (regex, strlen (regex), true)) { + iter->err_off = iter->off; + return true; + } + + if (VISIT_REGEX (iter, key, regex, options, data)) { + return true; + } + } break; + case BSON_TYPE_DBPOINTER: { + uint32_t collection_len = 0; + const char *collection = NULL; + const bson_oid_t *oid = NULL; + + bson_iter_dbpointer (iter, &collection_len, &collection, &oid); + + if (!bson_utf8_validate (collection, collection_len, true)) { + iter->err_off = iter->off; + return true; + } + + if (VISIT_DBPOINTER ( + iter, key, collection_len, collection, oid, data)) { + return true; + } + } break; + case BSON_TYPE_CODE: { + uint32_t code_len; + const char *code; + + code = bson_iter_code (iter, &code_len); + + if (!bson_utf8_validate (code, code_len, true)) { + iter->err_off = iter->off; + return true; + } + + if (VISIT_CODE (iter, key, code_len, code, data)) { + return true; + } + } break; + case BSON_TYPE_SYMBOL: { + uint32_t symbol_len; + const char *symbol; + + symbol = bson_iter_symbol (iter, &symbol_len); + + if (!bson_utf8_validate (symbol, symbol_len, true)) { + iter->err_off = iter->off; + return true; + } + + if (VISIT_SYMBOL (iter, key, symbol_len, symbol, data)) { + return true; + } + } break; + case BSON_TYPE_CODEWSCOPE: { + uint32_t length = 0; + const char *code; + const uint8_t *docbuf = NULL; + uint32_t doclen = 0; + bson_t b; + + code = bson_iter_codewscope (iter, &length, &doclen, &docbuf); + + if (!bson_utf8_validate (code, length, true)) { + iter->err_off = iter->off; + return true; + } + + if (bson_init_static (&b, docbuf, doclen) && + VISIT_CODEWSCOPE (iter, key, length, code, &b, data)) { + return true; + } + } break; + case BSON_TYPE_INT32: + + if (VISIT_INT32 (iter, key, bson_iter_int32 (iter), data)) { + return true; + } + + break; + case BSON_TYPE_TIMESTAMP: { + uint32_t timestamp; + uint32_t increment; + bson_iter_timestamp (iter, ×tamp, &increment); + + if (VISIT_TIMESTAMP (iter, key, timestamp, increment, data)) { + return true; + } + } break; + case BSON_TYPE_INT64: + + if (VISIT_INT64 (iter, key, bson_iter_int64 (iter), data)) { + return true; + } + + break; + case BSON_TYPE_DECIMAL128: { + bson_decimal128_t dec; + bson_iter_decimal128 (iter, &dec); + + if (VISIT_DECIMAL128 (iter, key, &dec, data)) { + return true; + } + } break; + case BSON_TYPE_MAXKEY: + + if (VISIT_MAXKEY (iter, bson_iter_key_unsafe (iter), data)) { + return true; + } + + break; + case BSON_TYPE_MINKEY: + + if (VISIT_MINKEY (iter, bson_iter_key_unsafe (iter), data)) { + return true; + } + + break; + case BSON_TYPE_EOD: + default: + break; + } + + if (VISIT_AFTER (iter, bson_iter_key_unsafe (iter), data)) { + return true; + } + } + + if (iter->err_off) { + if (unsupported && visitor->visit_unsupported_type && + bson_utf8_validate (key, strlen (key), false)) { + visitor->visit_unsupported_type (iter, key, bson_type, data); + return false; + } + + VISIT_CORRUPT (iter, data); + } + +#undef VISIT_FIELD + + return false; +} +","@@ -618,7 +618,7 @@ _bson_iter_next_internal (bson_iter_t *iter, /* INOUT */ + memcpy (&l, iter->raw + iter->d1, sizeof (l)); + l = BSON_UINT32_FROM_LE (l); + +- if (l >= (len - o)) { ++ if (l >= (len - o - 4)) { + iter->err_off = o; + goto mark_invalid; + }",1697,2028,2048 +9098,"static MagickBooleanType WriteMETAImage(const ImageInfo *image_info, + Image *image,ExceptionInfo *exception) +{ + const StringInfo + *profile; + + MagickBooleanType + status; + + size_t + length; + + /* + Open 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); + length=0; + if (LocaleCompare(image_info->magick,""8BIM"") == 0) + { + /* + Write 8BIM image. + */ + profile=GetImageProfile(image,""8bim""); + if (profile == (StringInfo *) NULL) + ThrowWriterException(CoderError,""No8BIMDataIsAvailable""); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); + if (status == MagickFalse) + return(status); + (void) WriteBlob(image,GetStringInfoLength(profile), + GetStringInfoDatum(profile)); + (void) CloseBlob(image); + return(MagickTrue); + } + if (LocaleCompare(image_info->magick,""iptc"") == 0) + { + size_t + length; + + unsigned char + *info; + + profile=GetImageProfile(image,""iptc""); + if (profile == (StringInfo *) NULL) + profile=GetImageProfile(image,""8bim""); + if (profile == (StringInfo *) NULL) + ThrowWriterException(CoderError,""No8BIMDataIsAvailable""); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); + info=GetStringInfoDatum(profile); + length=GetStringInfoLength(profile); + length=GetIPTCStream(&info,length); + if (length == 0) + ThrowWriterException(CoderError,""NoIPTCProfileAvailable""); + (void) WriteBlob(image,length,info); + (void) CloseBlob(image); + return(MagickTrue); + } + if (LocaleCompare(image_info->magick,""8BIMTEXT"") == 0) + { + Image + *buff; + + profile=GetImageProfile(image,""8bim""); + if (profile == (StringInfo *) NULL) + ThrowWriterException(CoderError,""No8BIMDataIsAvailable""); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); + if (status == MagickFalse) + return(status); + buff=AcquireImage((ImageInfo *) NULL,exception); + if (buff == (Image *) NULL) + ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); + AttachBlob(buff->blob,GetStringInfoDatum(profile), + GetStringInfoLength(profile)); + format8BIM(buff,image); + (void) DetachBlob(buff->blob); + buff=DestroyImage(buff); + (void) CloseBlob(image); + return(MagickTrue); + } + if (LocaleCompare(image_info->magick,""8BIMWTEXT"") == 0) + return(MagickFalse); + if (LocaleCompare(image_info->magick,""IPTCTEXT"") == 0) + { + Image + *buff; + + unsigned char + *info; + + profile=GetImageProfile(image,""8bim""); + if (profile == (StringInfo *) NULL) + ThrowWriterException(CoderError,""No8BIMDataIsAvailable""); + info=GetStringInfoDatum(profile); + length=GetStringInfoLength(profile); + length=GetIPTCStream(&info,length); + if (length == 0) + ThrowWriterException(CoderError,""NoIPTCProfileAvailable""); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); + if (status == MagickFalse) + return(status); + buff=AcquireImage((ImageInfo *) NULL,exception); + if (buff == (Image *) NULL) + ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); + AttachBlob(buff->blob,info,length); + formatIPTC(buff,image); + (void) DetachBlob(buff->blob); + buff=DestroyImage(buff); + (void) CloseBlob(image); + return(MagickTrue); + } + if (LocaleCompare(image_info->magick,""IPTCWTEXT"") == 0) + return(MagickFalse); + if ((LocaleCompare(image_info->magick,""APP1"") == 0) || + (LocaleCompare(image_info->magick,""EXIF"") == 0) || + (LocaleCompare(image_info->magick,""XMP"") == 0)) + { + /* + (void) Write APP1 image. + */ + profile=GetImageProfile(image,image_info->magick); + if (profile == (StringInfo *) NULL) + ThrowWriterException(CoderError,""NoAPP1DataIsAvailable""); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); + if (status == MagickFalse) + return(status); + (void) WriteBlob(image,GetStringInfoLength(profile), + GetStringInfoDatum(profile)); + (void) CloseBlob(image); + return(MagickTrue); + } + if ((LocaleCompare(image_info->magick,""ICC"") == 0) || + (LocaleCompare(image_info->magick,""ICM"") == 0)) + { + /* + Write ICM image. + */ + profile=GetImageProfile(image,""icc""); + if (profile == (StringInfo *) NULL) + ThrowWriterException(CoderError,""NoColorProfileIsAvailable""); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); + if (status == MagickFalse) + return(status); + (void) WriteBlob(image,GetStringInfoLength(profile), + GetStringInfoDatum(profile)); + (void) CloseBlob(image); + return(MagickTrue); + } + return(MagickFalse); +} +",0,"static MagickBooleanType WriteMETAImage(const ImageInfo *image_info, + Image *image,ExceptionInfo *exception) +{ + const StringInfo + *profile; + + MagickBooleanType + status; + + size_t + length; + + /* + Open 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); + length=0; + if (LocaleCompare(image_info->magick,""8BIM"") == 0) + { + /* + Write 8BIM image. + */ + profile=GetImageProfile(image,""8bim""); + if (profile == (StringInfo *) NULL) + ThrowWriterException(CoderError,""No8BIMDataIsAvailable""); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); + if (status == MagickFalse) + return(status); + (void) WriteBlob(image,GetStringInfoLength(profile), + GetStringInfoDatum(profile)); + (void) CloseBlob(image); + return(MagickTrue); + } + if (LocaleCompare(image_info->magick,""iptc"") == 0) + { + size_t + length; + + unsigned char + *info; + + profile=GetImageProfile(image,""iptc""); + if (profile == (StringInfo *) NULL) + profile=GetImageProfile(image,""8bim""); + if (profile == (StringInfo *) NULL) + ThrowWriterException(CoderError,""No8BIMDataIsAvailable""); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); + info=GetStringInfoDatum(profile); + length=GetStringInfoLength(profile); + length=GetIPTCStream(&info,length); + if (length == 0) + ThrowWriterException(CoderError,""NoIPTCProfileAvailable""); + (void) WriteBlob(image,length,info); + (void) CloseBlob(image); + return(MagickTrue); + } + if (LocaleCompare(image_info->magick,""8BIMTEXT"") == 0) + { + Image + *buff; + + profile=GetImageProfile(image,""8bim""); + if (profile == (StringInfo *) NULL) + ThrowWriterException(CoderError,""No8BIMDataIsAvailable""); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); + if (status == MagickFalse) + return(status); + buff=AcquireImage((ImageInfo *) NULL,exception); + if (buff == (Image *) NULL) + ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); + AttachBlob(buff->blob,GetStringInfoDatum(profile), + GetStringInfoLength(profile)); + format8BIM(buff,image); + (void) DetachBlob(buff->blob); + buff=DestroyImage(buff); + (void) CloseBlob(image); + return(MagickTrue); + } + if (LocaleCompare(image_info->magick,""8BIMWTEXT"") == 0) + return(MagickFalse); + if (LocaleCompare(image_info->magick,""IPTCTEXT"") == 0) + { + Image + *buff; + + unsigned char + *info; + + profile=GetImageProfile(image,""8bim""); + if (profile == (StringInfo *) NULL) + ThrowWriterException(CoderError,""No8BIMDataIsAvailable""); + info=GetStringInfoDatum(profile); + length=GetStringInfoLength(profile); + length=GetIPTCStream(&info,length); + if (length == 0) + ThrowWriterException(CoderError,""NoIPTCProfileAvailable""); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); + if (status == MagickFalse) + return(status); + buff=AcquireImage((ImageInfo *) NULL,exception); + if (buff == (Image *) NULL) + ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); + AttachBlob(buff->blob,info,length); + formatIPTC(buff,image); + (void) DetachBlob(buff->blob); + buff=DestroyImage(buff); + (void) CloseBlob(image); + return(MagickTrue); + } + if (LocaleCompare(image_info->magick,""IPTCWTEXT"") == 0) + return(MagickFalse); + if ((LocaleCompare(image_info->magick,""APP1"") == 0) || + (LocaleCompare(image_info->magick,""EXIF"") == 0) || + (LocaleCompare(image_info->magick,""XMP"") == 0)) + { + /* + (void) Write APP1 image. + */ + profile=GetImageProfile(image,image_info->magick); + if (profile == (StringInfo *) NULL) + ThrowWriterException(CoderError,""NoAPP1DataIsAvailable""); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); + if (status == MagickFalse) + return(status); + (void) WriteBlob(image,GetStringInfoLength(profile), + GetStringInfoDatum(profile)); + (void) CloseBlob(image); + return(MagickTrue); + } + if ((LocaleCompare(image_info->magick,""ICC"") == 0) || + (LocaleCompare(image_info->magick,""ICM"") == 0)) + { + /* + Write ICM image. + */ + profile=GetImageProfile(image,""icc""); + if (profile == (StringInfo *) NULL) + ThrowWriterException(CoderError,""NoColorProfileIsAvailable""); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); + if (status == MagickFalse) + return(status); + (void) WriteBlob(image,GetStringInfoLength(profile), + GetStringInfoDatum(profile)); + (void) CloseBlob(image); + return(MagickTrue); + } + return(MagickFalse); +} +","@@ -2204,7 +2204,7 @@ static int format8BIM(Image *ifile, Image *ofile) + return -1; + } + /* make a buffer to hold the data and snag it from the input stream */ +- str=(unsigned char *) AcquireQuantumMemory((size_t) count,sizeof(*str)); ++ str=(unsigned char *) AcquireQuantumMemory((size_t) count+1,sizeof(*str)); + if (str == (unsigned char *) NULL) + { + PString=(unsigned char *) RelinquishMagickMemory(PString);",1405,1736,2048 +7919,"int imap_cmd_step(struct ImapData *idata) +{ + size_t len = 0; + int c; + int rc; + int stillrunning = 0; + struct ImapCommand *cmd = NULL; + + if (idata->status == IMAP_FATAL) + { + cmd_handle_fatal(idata); + return IMAP_CMD_BAD; + } + + /* read into buffer, expanding buffer as necessary until we have a full + * line */ + do + { + if (len == idata->blen) + { + mutt_mem_realloc(&idata->buf, idata->blen + IMAP_CMD_BUFSIZE); + idata->blen = idata->blen + IMAP_CMD_BUFSIZE; + mutt_debug(3, ""grew buffer to %u bytes\n"", idata->blen); + } + + /* back up over '\0' */ + if (len) + len--; + c = mutt_socket_readln(idata->buf + len, idata->blen - len, idata->conn); + if (c <= 0) + { + mutt_debug(1, ""Error reading server response.\n""); + cmd_handle_fatal(idata); + return IMAP_CMD_BAD; + } + + len += c; + } + /* if we've read all the way to the end of the buffer, we haven't read a + * full line (mutt_socket_readln strips the \r, so we always have at least + * one character free when we've read a full line) */ + while (len == idata->blen); + + /* don't let one large string make cmd->buf hog memory forever */ + if ((idata->blen > IMAP_CMD_BUFSIZE) && (len <= IMAP_CMD_BUFSIZE)) + { + mutt_mem_realloc(&idata->buf, IMAP_CMD_BUFSIZE); + idata->blen = IMAP_CMD_BUFSIZE; + mutt_debug(3, ""shrank buffer to %u bytes\n"", idata->blen); + } + + idata->lastread = time(NULL); + + /* handle untagged messages. The caller still gets its shot afterwards. */ + if (((mutt_str_strncmp(idata->buf, ""* "", 2) == 0) || + (mutt_str_strncmp(imap_next_word(idata->buf), ""OK ["", 4) == 0)) && + cmd_handle_untagged(idata)) + { + return IMAP_CMD_BAD; + } + + /* server demands a continuation response from us */ + if (idata->buf[0] == '+') + return IMAP_CMD_RESPOND; + + /* Look for tagged command completions. + * + * Some response handlers can end up recursively calling + * imap_cmd_step() and end up handling all tagged command + * completions. + * (e.g. FETCH->set_flag->set_header_color->~h pattern match.) + * + * Other callers don't even create an idata->cmds entry. + * + * For both these cases, we default to returning OK */ + rc = IMAP_CMD_OK; + c = idata->lastcmd; + do + { + cmd = &idata->cmds[c]; + if (cmd->state == IMAP_CMD_NEW) + { + if (mutt_str_strncmp(idata->buf, cmd->seq, SEQLEN) == 0) + { + if (!stillrunning) + { + /* first command in queue has finished - move queue pointer up */ + idata->lastcmd = (idata->lastcmd + 1) % idata->cmdslots; + } + cmd->state = cmd_status(idata->buf); + /* bogus - we don't know which command result to return here. Caller + * should provide a tag. */ + rc = cmd->state; + } + else + stillrunning++; + } + + c = (c + 1) % idata->cmdslots; + } while (c != idata->nextcmd); + + if (stillrunning) + rc = IMAP_CMD_CONTINUE; + else + { + mutt_debug(3, ""IMAP queue drained\n""); + imap_cmd_finish(idata); + } + + return rc; +} +",0,"int imap_cmd_step(struct ImapData *idata) +{ + size_t len = 0; + int c; + int rc; + int stillrunning = 0; + struct ImapCommand *cmd = NULL; + + if (idata->status == IMAP_FATAL) + { + cmd_handle_fatal(idata); + return IMAP_CMD_BAD; + } + + /* read into buffer, expanding buffer as necessary until we have a full + * line */ + do + { + if (len == idata->blen) + { + mutt_mem_realloc(&idata->buf, idata->blen + IMAP_CMD_BUFSIZE); + idata->blen = idata->blen + IMAP_CMD_BUFSIZE; + mutt_debug(3, ""grew buffer to %u bytes\n"", idata->blen); + } + + /* back up over '\0' */ + if (len) + len--; + c = mutt_socket_readln(idata->buf + len, idata->blen - len, idata->conn); + if (c <= 0) + { + mutt_debug(1, ""Error reading server response.\n""); + cmd_handle_fatal(idata); + return IMAP_CMD_BAD; + } + + len += c; + } + /* if we've read all the way to the end of the buffer, we haven't read a + * full line (mutt_socket_readln strips the \r, so we always have at least + * one character free when we've read a full line) */ + while (len == idata->blen); + + /* don't let one large string make cmd->buf hog memory forever */ + if ((idata->blen > IMAP_CMD_BUFSIZE) && (len <= IMAP_CMD_BUFSIZE)) + { + mutt_mem_realloc(&idata->buf, IMAP_CMD_BUFSIZE); + idata->blen = IMAP_CMD_BUFSIZE; + mutt_debug(3, ""shrank buffer to %u bytes\n"", idata->blen); + } + + idata->lastread = time(NULL); + + /* handle untagged messages. The caller still gets its shot afterwards. */ + if (((mutt_str_strncmp(idata->buf, ""* "", 2) == 0) || + (mutt_str_strncmp(imap_next_word(idata->buf), ""OK ["", 4) == 0)) && + cmd_handle_untagged(idata)) + { + return IMAP_CMD_BAD; + } + + /* server demands a continuation response from us */ + if (idata->buf[0] == '+') + return IMAP_CMD_RESPOND; + + /* Look for tagged command completions. + * + * Some response handlers can end up recursively calling + * imap_cmd_step() and end up handling all tagged command + * completions. + * (e.g. FETCH->set_flag->set_header_color->~h pattern match.) + * + * Other callers don't even create an idata->cmds entry. + * + * For both these cases, we default to returning OK */ + rc = IMAP_CMD_OK; + c = idata->lastcmd; + do + { + cmd = &idata->cmds[c]; + if (cmd->state == IMAP_CMD_NEW) + { + if (mutt_str_strncmp(idata->buf, cmd->seq, SEQLEN) == 0) + { + if (!stillrunning) + { + /* first command in queue has finished - move queue pointer up */ + idata->lastcmd = (idata->lastcmd + 1) % idata->cmdslots; + } + cmd->state = cmd_status(idata->buf); + /* bogus - we don't know which command result to return here. Caller + * should provide a tag. */ + rc = cmd->state; + } + else + stillrunning++; + } + + c = (c + 1) % idata->cmdslots; + } while (c != idata->nextcmd); + + if (stillrunning) + rc = IMAP_CMD_CONTINUE; + else + { + mutt_debug(3, ""IMAP queue drained\n""); + imap_cmd_finish(idata); + } + + return rc; +} +","@@ -499,7 +499,7 @@ static void cmd_parse_lsub(struct ImapData *idata, char *s) + mutt_str_strfcpy(buf, ""mailboxes \"""", sizeof(buf)); + mutt_account_tourl(&idata->conn->account, &url); + /* escape \ and "" */ +- imap_quote_string(errstr, sizeof(errstr), list.name); ++ imap_quote_string(errstr, sizeof(errstr), list.name, true); + url.path = errstr + 1; + url.path[strlen(url.path) - 1] = '\0'; + if (mutt_str_strcmp(url.user, ImapUser) == 0)",909,1240,2048 +879,"static uint32_t vmsvga_value_read(void *opaque, uint32_t address) +{ + uint32_t caps; + struct vmsvga_state_s *s = opaque; + DisplaySurface *surface = qemu_console_surface(s->vga.con); + PixelFormat pf; + uint32_t ret; + + switch (s->index) { + case SVGA_REG_ID: + ret = s->svgaid; + break; + + case SVGA_REG_ENABLE: + ret = s->enable; + break; + + case SVGA_REG_WIDTH: + ret = s->new_width ? s->new_width : surface_width(surface); + break; + + case SVGA_REG_HEIGHT: + ret = s->new_height ? s->new_height : surface_height(surface); + break; + + case SVGA_REG_MAX_WIDTH: + ret = SVGA_MAX_WIDTH; + break; + + case SVGA_REG_MAX_HEIGHT: + ret = SVGA_MAX_HEIGHT; + break; + + case SVGA_REG_DEPTH: + ret = (s->new_depth == 32) ? 24 : s->new_depth; + break; + + case SVGA_REG_BITS_PER_PIXEL: + case SVGA_REG_HOST_BITS_PER_PIXEL: + ret = s->new_depth; + break; + + case SVGA_REG_PSEUDOCOLOR: + ret = 0x0; + break; + + case SVGA_REG_RED_MASK: + pf = qemu_default_pixelformat(s->new_depth); + ret = pf.rmask; + break; + + case SVGA_REG_GREEN_MASK: + pf = qemu_default_pixelformat(s->new_depth); + ret = pf.gmask; + break; + + case SVGA_REG_BLUE_MASK: + pf = qemu_default_pixelformat(s->new_depth); + ret = pf.bmask; + break; + + case SVGA_REG_BYTES_PER_LINE: + if (s->new_width) { + ret = (s->new_depth * s->new_width) / 8; + } else { + ret = surface_stride(surface); + } + break; + + case SVGA_REG_FB_START: { + struct pci_vmsvga_state_s *pci_vmsvga + = container_of(s, struct pci_vmsvga_state_s, chip); + ret = pci_get_bar_addr(PCI_DEVICE(pci_vmsvga), 1); + break; + } + + case SVGA_REG_FB_OFFSET: + ret = 0x0; + break; + + case SVGA_REG_VRAM_SIZE: + ret = s->vga.vram_size; /* No physical VRAM besides the framebuffer */ + break; + + case SVGA_REG_FB_SIZE: + ret = s->vga.vram_size; + break; + + case SVGA_REG_CAPABILITIES: + caps = SVGA_CAP_NONE; +#ifdef HW_RECT_ACCEL + caps |= SVGA_CAP_RECT_COPY; +#endif +#ifdef HW_FILL_ACCEL + caps |= SVGA_CAP_RECT_FILL; +#endif +#ifdef HW_MOUSE_ACCEL + if (dpy_cursor_define_supported(s->vga.con)) { + caps |= SVGA_CAP_CURSOR | SVGA_CAP_CURSOR_BYPASS_2 | + SVGA_CAP_CURSOR_BYPASS; + } +#endif + ret = caps; + break; + + case SVGA_REG_MEM_START: { + struct pci_vmsvga_state_s *pci_vmsvga + = container_of(s, struct pci_vmsvga_state_s, chip); + ret = pci_get_bar_addr(PCI_DEVICE(pci_vmsvga), 2); + break; + } + + case SVGA_REG_MEM_SIZE: + ret = s->fifo_size; + break; + + case SVGA_REG_CONFIG_DONE: + ret = s->config; + break; + + case SVGA_REG_SYNC: + case SVGA_REG_BUSY: + ret = s->syncing; + break; + + case SVGA_REG_GUEST_ID: + ret = s->guest; + break; + + case SVGA_REG_CURSOR_ID: + ret = s->cursor.id; + break; + + case SVGA_REG_CURSOR_X: + ret = s->cursor.x; + break; + + case SVGA_REG_CURSOR_Y: + ret = s->cursor.y; + break; + + case SVGA_REG_CURSOR_ON: + ret = s->cursor.on; + break; + + case SVGA_REG_SCRATCH_SIZE: + ret = s->scratch_size; + break; + + case SVGA_REG_MEM_REGS: + case SVGA_REG_NUM_DISPLAYS: + case SVGA_REG_PITCHLOCK: + case SVGA_PALETTE_BASE ... SVGA_PALETTE_END: + ret = 0; + break; + + default: + if (s->index >= SVGA_SCRATCH_BASE && + s->index < SVGA_SCRATCH_BASE + s->scratch_size) { + ret = s->scratch[s->index - SVGA_SCRATCH_BASE]; + break; + } + printf(""%s: Bad register %02x\n"", __func__, s->index); + ret = 0; + break; + } + + if (s->index >= SVGA_SCRATCH_BASE) { + trace_vmware_scratch_read(s->index, ret); + } else if (s->index >= SVGA_PALETTE_BASE) { + trace_vmware_palette_read(s->index, ret); + } else { + trace_vmware_value_read(s->index, ret); + } + return ret; +} +",0,"static uint32_t vmsvga_value_read(void *opaque, uint32_t address) +{ + uint32_t caps; + struct vmsvga_state_s *s = opaque; + DisplaySurface *surface = qemu_console_surface(s->vga.con); + PixelFormat pf; + uint32_t ret; + + switch (s->index) { + case SVGA_REG_ID: + ret = s->svgaid; + break; + + case SVGA_REG_ENABLE: + ret = s->enable; + break; + + case SVGA_REG_WIDTH: + ret = s->new_width ? s->new_width : surface_width(surface); + break; + + case SVGA_REG_HEIGHT: + ret = s->new_height ? s->new_height : surface_height(surface); + break; + + case SVGA_REG_MAX_WIDTH: + ret = SVGA_MAX_WIDTH; + break; + + case SVGA_REG_MAX_HEIGHT: + ret = SVGA_MAX_HEIGHT; + break; + + case SVGA_REG_DEPTH: + ret = (s->new_depth == 32) ? 24 : s->new_depth; + break; + + case SVGA_REG_BITS_PER_PIXEL: + case SVGA_REG_HOST_BITS_PER_PIXEL: + ret = s->new_depth; + break; + + case SVGA_REG_PSEUDOCOLOR: + ret = 0x0; + break; + + case SVGA_REG_RED_MASK: + pf = qemu_default_pixelformat(s->new_depth); + ret = pf.rmask; + break; + + case SVGA_REG_GREEN_MASK: + pf = qemu_default_pixelformat(s->new_depth); + ret = pf.gmask; + break; + + case SVGA_REG_BLUE_MASK: + pf = qemu_default_pixelformat(s->new_depth); + ret = pf.bmask; + break; + + case SVGA_REG_BYTES_PER_LINE: + if (s->new_width) { + ret = (s->new_depth * s->new_width) / 8; + } else { + ret = surface_stride(surface); + } + break; + + case SVGA_REG_FB_START: { + struct pci_vmsvga_state_s *pci_vmsvga + = container_of(s, struct pci_vmsvga_state_s, chip); + ret = pci_get_bar_addr(PCI_DEVICE(pci_vmsvga), 1); + break; + } + + case SVGA_REG_FB_OFFSET: + ret = 0x0; + break; + + case SVGA_REG_VRAM_SIZE: + ret = s->vga.vram_size; /* No physical VRAM besides the framebuffer */ + break; + + case SVGA_REG_FB_SIZE: + ret = s->vga.vram_size; + break; + + case SVGA_REG_CAPABILITIES: + caps = SVGA_CAP_NONE; +#ifdef HW_RECT_ACCEL + caps |= SVGA_CAP_RECT_COPY; +#endif +#ifdef HW_FILL_ACCEL + caps |= SVGA_CAP_RECT_FILL; +#endif +#ifdef HW_MOUSE_ACCEL + if (dpy_cursor_define_supported(s->vga.con)) { + caps |= SVGA_CAP_CURSOR | SVGA_CAP_CURSOR_BYPASS_2 | + SVGA_CAP_CURSOR_BYPASS; + } +#endif + ret = caps; + break; + + case SVGA_REG_MEM_START: { + struct pci_vmsvga_state_s *pci_vmsvga + = container_of(s, struct pci_vmsvga_state_s, chip); + ret = pci_get_bar_addr(PCI_DEVICE(pci_vmsvga), 2); + break; + } + + case SVGA_REG_MEM_SIZE: + ret = s->fifo_size; + break; + + case SVGA_REG_CONFIG_DONE: + ret = s->config; + break; + + case SVGA_REG_SYNC: + case SVGA_REG_BUSY: + ret = s->syncing; + break; + + case SVGA_REG_GUEST_ID: + ret = s->guest; + break; + + case SVGA_REG_CURSOR_ID: + ret = s->cursor.id; + break; + + case SVGA_REG_CURSOR_X: + ret = s->cursor.x; + break; + + case SVGA_REG_CURSOR_Y: + ret = s->cursor.y; + break; + + case SVGA_REG_CURSOR_ON: + ret = s->cursor.on; + break; + + case SVGA_REG_SCRATCH_SIZE: + ret = s->scratch_size; + break; + + case SVGA_REG_MEM_REGS: + case SVGA_REG_NUM_DISPLAYS: + case SVGA_REG_PITCHLOCK: + case SVGA_PALETTE_BASE ... SVGA_PALETTE_END: + ret = 0; + break; + + default: + if (s->index >= SVGA_SCRATCH_BASE && + s->index < SVGA_SCRATCH_BASE + s->scratch_size) { + ret = s->scratch[s->index - SVGA_SCRATCH_BASE]; + break; + } + printf(""%s: Bad register %02x\n"", __func__, s->index); + ret = 0; + break; + } + + if (s->index >= SVGA_SCRATCH_BASE) { + trace_vmware_scratch_read(s->index, ret); + } else if (s->index >= SVGA_PALETTE_BASE) { + trace_vmware_palette_read(s->index, ret); + } else { + trace_vmware_value_read(s->index, ret); + } + return ret; +} +","@@ -676,11 +676,13 @@ static void vmsvga_fifo_run(struct vmsvga_state_s *s) + cursor.bpp = vmsvga_fifo_read(s); + + args = SVGA_BITMAP_SIZE(x, y) + SVGA_PIXMAP_SIZE(x, y, cursor.bpp); +- if (cursor.width > 256 || +- cursor.height > 256 || +- cursor.bpp > 32 || +- SVGA_BITMAP_SIZE(x, y) > sizeof cursor.mask || +- SVGA_PIXMAP_SIZE(x, y, cursor.bpp) > sizeof cursor.image) { ++ if (cursor.width > 256 ++ || cursor.height > 256 ++ || cursor.bpp > 32 ++ || SVGA_BITMAP_SIZE(x, y) ++ > sizeof(cursor.mask) / sizeof(cursor.mask[0]) ++ || SVGA_PIXMAP_SIZE(x, y, cursor.bpp) ++ > sizeof(cursor.image) / sizeof(cursor.image[0])) { + goto badcmd; + }",1145,1476,2048 +8380,"static inline int DetectRunInspectRuleHeader( + const Packet *p, + const Flow *f, + const Signature *s, + const uint32_t sflags, + const uint8_t s_proto_flags) +{ + /* check if this signature has a requirement for flowvars of some type + * and if so, if we actually have any in the flow. If not, the sig + * can't match and we skip it. */ + if ((p->flags & PKT_HAS_FLOW) && (sflags & SIG_FLAG_REQUIRE_FLOWVAR)) { + int m = f->flowvar ? 1 : 0; + + /* no flowvars? skip this sig */ + if (m == 0) { + SCLogDebug(""skipping sig as the flow has no flowvars and sig "" + ""has SIG_FLAG_REQUIRE_FLOWVAR flag set.""); + return 0; + } + } + + if ((s_proto_flags & DETECT_PROTO_IPV4) && !PKT_IS_IPV4(p)) { + SCLogDebug(""ip version didn't match""); + return 0; + } + if ((s_proto_flags & DETECT_PROTO_IPV6) && !PKT_IS_IPV6(p)) { + SCLogDebug(""ip version didn't match""); + return 0; + } + + if (DetectProtoContainsProto(&s->proto, IP_GET_IPPROTO(p)) == 0) { + SCLogDebug(""proto didn't match""); + return 0; + } + + /* check the source & dst port in the sig */ + if (p->proto == IPPROTO_TCP || p->proto == IPPROTO_UDP || p->proto == IPPROTO_SCTP) { + if (!(sflags & SIG_FLAG_DP_ANY)) { + if (p->flags & PKT_IS_FRAGMENT) + return 0; + DetectPort *dport = DetectPortLookupGroup(s->dp,p->dp); + if (dport == NULL) { + SCLogDebug(""dport didn't match.""); + return 0; + } + } + if (!(sflags & SIG_FLAG_SP_ANY)) { + if (p->flags & PKT_IS_FRAGMENT) + return 0; + DetectPort *sport = DetectPortLookupGroup(s->sp,p->sp); + if (sport == NULL) { + SCLogDebug(""sport didn't match.""); + return 0; + } + } + } else if ((sflags & (SIG_FLAG_DP_ANY|SIG_FLAG_SP_ANY)) != (SIG_FLAG_DP_ANY|SIG_FLAG_SP_ANY)) { + SCLogDebug(""port-less protocol and sig needs ports""); + return 0; + } + + /* check the destination address */ + if (!(sflags & SIG_FLAG_DST_ANY)) { + if (PKT_IS_IPV4(p)) { + if (DetectAddressMatchIPv4(s->addr_dst_match4, s->addr_dst_match4_cnt, &p->dst) == 0) + return 0; + } else if (PKT_IS_IPV6(p)) { + if (DetectAddressMatchIPv6(s->addr_dst_match6, s->addr_dst_match6_cnt, &p->dst) == 0) + return 0; + } + } + /* check the source address */ + if (!(sflags & SIG_FLAG_SRC_ANY)) { + if (PKT_IS_IPV4(p)) { + if (DetectAddressMatchIPv4(s->addr_src_match4, s->addr_src_match4_cnt, &p->src) == 0) + return 0; + } else if (PKT_IS_IPV6(p)) { + if (DetectAddressMatchIPv6(s->addr_src_match6, s->addr_src_match6_cnt, &p->src) == 0) + return 0; + } + } + + return 1; +} +",0,"static inline int DetectRunInspectRuleHeader( + const Packet *p, + const Flow *f, + const Signature *s, + const uint32_t sflags, + const uint8_t s_proto_flags) +{ + /* check if this signature has a requirement for flowvars of some type + * and if so, if we actually have any in the flow. If not, the sig + * can't match and we skip it. */ + if ((p->flags & PKT_HAS_FLOW) && (sflags & SIG_FLAG_REQUIRE_FLOWVAR)) { + int m = f->flowvar ? 1 : 0; + + /* no flowvars? skip this sig */ + if (m == 0) { + SCLogDebug(""skipping sig as the flow has no flowvars and sig "" + ""has SIG_FLAG_REQUIRE_FLOWVAR flag set.""); + return 0; + } + } + + if ((s_proto_flags & DETECT_PROTO_IPV4) && !PKT_IS_IPV4(p)) { + SCLogDebug(""ip version didn't match""); + return 0; + } + if ((s_proto_flags & DETECT_PROTO_IPV6) && !PKT_IS_IPV6(p)) { + SCLogDebug(""ip version didn't match""); + return 0; + } + + if (DetectProtoContainsProto(&s->proto, IP_GET_IPPROTO(p)) == 0) { + SCLogDebug(""proto didn't match""); + return 0; + } + + /* check the source & dst port in the sig */ + if (p->proto == IPPROTO_TCP || p->proto == IPPROTO_UDP || p->proto == IPPROTO_SCTP) { + if (!(sflags & SIG_FLAG_DP_ANY)) { + if (p->flags & PKT_IS_FRAGMENT) + return 0; + DetectPort *dport = DetectPortLookupGroup(s->dp,p->dp); + if (dport == NULL) { + SCLogDebug(""dport didn't match.""); + return 0; + } + } + if (!(sflags & SIG_FLAG_SP_ANY)) { + if (p->flags & PKT_IS_FRAGMENT) + return 0; + DetectPort *sport = DetectPortLookupGroup(s->sp,p->sp); + if (sport == NULL) { + SCLogDebug(""sport didn't match.""); + return 0; + } + } + } else if ((sflags & (SIG_FLAG_DP_ANY|SIG_FLAG_SP_ANY)) != (SIG_FLAG_DP_ANY|SIG_FLAG_SP_ANY)) { + SCLogDebug(""port-less protocol and sig needs ports""); + return 0; + } + + /* check the destination address */ + if (!(sflags & SIG_FLAG_DST_ANY)) { + if (PKT_IS_IPV4(p)) { + if (DetectAddressMatchIPv4(s->addr_dst_match4, s->addr_dst_match4_cnt, &p->dst) == 0) + return 0; + } else if (PKT_IS_IPV6(p)) { + if (DetectAddressMatchIPv6(s->addr_dst_match6, s->addr_dst_match6_cnt, &p->dst) == 0) + return 0; + } + } + /* check the source address */ + if (!(sflags & SIG_FLAG_SRC_ANY)) { + if (PKT_IS_IPV4(p)) { + if (DetectAddressMatchIPv4(s->addr_src_match4, s->addr_src_match4_cnt, &p->src) == 0) + return 0; + } else if (PKT_IS_IPV6(p)) { + if (DetectAddressMatchIPv6(s->addr_src_match6, s->addr_src_match6_cnt, &p->src) == 0) + return 0; + } + } + + return 1; +} +","@@ -1610,10 +1610,7 @@ static void DetectFlow(ThreadVars *tv, + DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, + Packet *p) + { +- /* No need to perform any detection on this packet, if the the given flag is set.*/ +- if ((p->flags & PKT_NOPACKET_INSPECTION) || +- (PACKET_TEST_ACTION(p, ACTION_DROP))) +- { ++ if (p->flags & PKT_NOPACKET_INSPECTION) { + /* hack: if we are in pass the entire flow mode, we need to still + * update the inspect_id forward. So test for the condition here, + * and call the update code if necessary. */ +@@ -1629,6 +1626,8 @@ static void DetectFlow(ThreadVars *tv, + flags = FlowGetDisruptionFlags(p->flow, flags); + DeStateUpdateInspectTransactionId(p->flow, flags, true); + } ++ SCLogDebug(""p->pcap %""PRIu64"": no detection on packet, "" ++ ""PKT_NOPACKET_INSPECTION is set"", p->pcap_cnt); + return; + } + ",802,1133,2048 +18304,"static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr) +{ + struct tun_struct *tun; + struct tun_file *tfile = file->private_data; + struct net_device *dev; + int err; + + if (tfile->detached) + return -EINVAL; + + dev = __dev_get_by_name(net, ifr->ifr_name); + if (dev) { + if (ifr->ifr_flags & IFF_TUN_EXCL) + return -EBUSY; + if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops) + tun = netdev_priv(dev); + else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops) + tun = netdev_priv(dev); + else + return -EINVAL; + + if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) != + !!(tun->flags & IFF_MULTI_QUEUE)) + return -EINVAL; + + if (tun_not_capable(tun)) + return -EPERM; + err = security_tun_dev_open(tun->security); + if (err < 0) + return err; + + err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER); + if (err < 0) + return err; + + if (tun->flags & IFF_MULTI_QUEUE && + (tun->numqueues + tun->numdisabled > 1)) { + /* One or more queue has already been attached, no need + * to initialize the device again. + */ + return 0; + } + } + else { + char *name; + unsigned long flags = 0; + int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ? + MAX_TAP_QUEUES : 1; + + if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) + return -EPERM; + err = security_tun_dev_create(); + if (err < 0) + return err; + + /* Set dev type */ + if (ifr->ifr_flags & IFF_TUN) { + /* TUN device */ + flags |= IFF_TUN; + name = ""tun%d""; + } else if (ifr->ifr_flags & IFF_TAP) { + /* TAP device */ + flags |= IFF_TAP; + name = ""tap%d""; + } else + return -EINVAL; + + if (*ifr->ifr_name) + name = ifr->ifr_name; + + dev = alloc_netdev_mqs(sizeof(struct tun_struct), name, + NET_NAME_UNKNOWN, tun_setup, queues, + queues); + + if (!dev) + return -ENOMEM; + + dev_net_set(dev, net); + dev->rtnl_link_ops = &tun_link_ops; + dev->ifindex = tfile->ifindex; + dev->sysfs_groups[0] = &tun_attr_group; + + tun = netdev_priv(dev); + tun->dev = dev; + tun->flags = flags; + tun->txflt.count = 0; + tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr); + + tun->align = NET_SKB_PAD; + tun->filter_attached = false; + tun->sndbuf = tfile->socket.sk->sk_sndbuf; + tun->rx_batched = 0; + + tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats); + if (!tun->pcpu_stats) { + err = -ENOMEM; + goto err_free_dev; + } + + spin_lock_init(&tun->lock); + + err = security_tun_dev_alloc_security(&tun->security); + if (err < 0) + goto err_free_stat; + + tun_net_init(dev); + tun_flow_init(tun); + + dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST | + TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX | + NETIF_F_HW_VLAN_STAG_TX; + dev->features = dev->hw_features | NETIF_F_LLTX; + dev->vlan_features = dev->features & + ~(NETIF_F_HW_VLAN_CTAG_TX | + NETIF_F_HW_VLAN_STAG_TX); + + INIT_LIST_HEAD(&tun->disabled); + err = tun_attach(tun, file, false); + if (err < 0) + goto err_free_flow; + + err = register_netdevice(tun->dev); + if (err < 0) + goto err_detach; + } + + netif_carrier_on(tun->dev); + + tun_debug(KERN_INFO, tun, ""tun_set_iff\n""); + + tun->flags = (tun->flags & ~TUN_FEATURES) | + (ifr->ifr_flags & TUN_FEATURES); + + /* Make sure persistent devices do not get stuck in + * xoff state. + */ + if (netif_running(tun->dev)) + netif_tx_wake_all_queues(tun->dev); + + strcpy(ifr->ifr_name, tun->dev->name); + return 0; + +err_detach: + tun_detach_all(dev); + /* register_netdevice() already called tun_free_netdev() */ + goto err_free_dev; + +err_free_flow: + tun_flow_uninit(tun); + security_tun_dev_free_security(tun->security); +err_free_stat: + free_percpu(tun->pcpu_stats); +err_free_dev: + free_netdev(dev); + return err; +} +",1,"static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr) +{ + struct tun_struct *tun; + struct tun_file *tfile = file->private_data; + struct net_device *dev; + int err; + + if (tfile->detached) + return -EINVAL; + + dev = __dev_get_by_name(net, ifr->ifr_name); + if (dev) { + if (ifr->ifr_flags & IFF_TUN_EXCL) + return -EBUSY; + if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops) + tun = netdev_priv(dev); + else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops) + tun = netdev_priv(dev); + else + return -EINVAL; + + if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) != + !!(tun->flags & IFF_MULTI_QUEUE)) + return -EINVAL; + + if (tun_not_capable(tun)) + return -EPERM; + err = security_tun_dev_open(tun->security); + if (err < 0) + return err; + + err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER); + if (err < 0) + return err; + + if (tun->flags & IFF_MULTI_QUEUE && + (tun->numqueues + tun->numdisabled > 1)) { + /* One or more queue has already been attached, no need + * to initialize the device again. + */ + return 0; + } + } + else { + char *name; + unsigned long flags = 0; + int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ? + MAX_TAP_QUEUES : 1; + + if (!ns_capable(net->user_ns, CAP_NET_ADMIN)) + return -EPERM; + err = security_tun_dev_create(); + if (err < 0) + return err; + + /* Set dev type */ + if (ifr->ifr_flags & IFF_TUN) { + /* TUN device */ + flags |= IFF_TUN; + name = ""tun%d""; + } else if (ifr->ifr_flags & IFF_TAP) { + /* TAP device */ + flags |= IFF_TAP; + name = ""tap%d""; + } else + return -EINVAL; + + if (*ifr->ifr_name) + name = ifr->ifr_name; + + dev = alloc_netdev_mqs(sizeof(struct tun_struct), name, + NET_NAME_UNKNOWN, tun_setup, queues, + queues); + + if (!dev) + return -ENOMEM; + err = dev_get_valid_name(net, dev, name); + if (err) + goto err_free_dev; + + dev_net_set(dev, net); + dev->rtnl_link_ops = &tun_link_ops; + dev->ifindex = tfile->ifindex; + dev->sysfs_groups[0] = &tun_attr_group; + + tun = netdev_priv(dev); + tun->dev = dev; + tun->flags = flags; + tun->txflt.count = 0; + tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr); + + tun->align = NET_SKB_PAD; + tun->filter_attached = false; + tun->sndbuf = tfile->socket.sk->sk_sndbuf; + tun->rx_batched = 0; + + tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats); + if (!tun->pcpu_stats) { + err = -ENOMEM; + goto err_free_dev; + } + + spin_lock_init(&tun->lock); + + err = security_tun_dev_alloc_security(&tun->security); + if (err < 0) + goto err_free_stat; + + tun_net_init(dev); + tun_flow_init(tun); + + dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST | + TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX | + NETIF_F_HW_VLAN_STAG_TX; + dev->features = dev->hw_features | NETIF_F_LLTX; + dev->vlan_features = dev->features & + ~(NETIF_F_HW_VLAN_CTAG_TX | + NETIF_F_HW_VLAN_STAG_TX); + + INIT_LIST_HEAD(&tun->disabled); + err = tun_attach(tun, file, false); + if (err < 0) + goto err_free_flow; + + err = register_netdevice(tun->dev); + if (err < 0) + goto err_detach; + } + + netif_carrier_on(tun->dev); + + tun_debug(KERN_INFO, tun, ""tun_set_iff\n""); + + tun->flags = (tun->flags & ~TUN_FEATURES) | + (ifr->ifr_flags & TUN_FEATURES); + + /* Make sure persistent devices do not get stuck in + * xoff state. + */ + if (netif_running(tun->dev)) + netif_tx_wake_all_queues(tun->dev); + + strcpy(ifr->ifr_name, tun->dev->name); + return 0; + +err_detach: + tun_detach_all(dev); + /* register_netdevice() already called tun_free_netdev() */ + goto err_free_dev; + +err_free_flow: + tun_flow_uninit(tun); + security_tun_dev_free_security(tun->security); +err_free_stat: + free_percpu(tun->pcpu_stats); +err_free_dev: + free_netdev(dev); + return err; +} +","@@ -2027,6 +2027,9 @@ static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr) + + if (!dev) + return -ENOMEM; ++ err = dev_get_valid_name(net, dev, name); ++ if (err) ++ goto err_free_dev; + + dev_net_set(dev, net); + dev->rtnl_link_ops = &tun_link_ops;",1189,1520,2048 +15542,"content::PreviewsState ChromeContentBrowserClient::DetermineAllowedPreviews( + content::PreviewsState initial_state, + content::NavigationHandle* navigation_handle, + const GURL& current_navigation_url) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + DCHECK(!navigation_handle->HasCommitted()); + + if (!navigation_handle->IsInMainFrame() || + navigation_handle->IsSameDocument()) { + return initial_state; + } + + if (!current_navigation_url.SchemeIsHTTPOrHTTPS()) + return content::PREVIEWS_OFF; + + if (navigation_handle->IsPost()) + return content::PREVIEWS_OFF; + + content::WebContents* web_contents = navigation_handle->GetWebContents(); + content::WebContentsDelegate* delegate = web_contents->GetDelegate(); + + auto* browser_context = web_contents->GetBrowserContext(); + + PreviewsService* previews_service = PreviewsServiceFactory::GetForProfile( + Profile::FromBrowserContext(browser_context)); + auto* data_reduction_proxy_settings = + DataReductionProxyChromeSettingsFactory::GetForBrowserContext( + browser_context); + if (!previews_service || !previews_service->previews_ui_service() || + !data_reduction_proxy_settings) { + return content::PREVIEWS_OFF; + } + + PreviewsUITabHelper* ui_tab_helper = + PreviewsUITabHelper::FromWebContents(web_contents); + if (!ui_tab_helper) + return content::PREVIEWS_OFF; + + DCHECK(!browser_context->IsOffTheRecord()); + + previews::PreviewsDeciderImpl* previews_decider_impl = + previews_service->previews_ui_service()->previews_decider_impl(); + DCHECK(previews_decider_impl); + + content::PreviewsState previews_state = content::PREVIEWS_UNSPECIFIED; + + previews::PreviewsUserData* previews_data = + ui_tab_helper->GetPreviewsUserData(navigation_handle); + + bool is_redirect = false; + if (previews_data) { + is_redirect = !previews_data->server_lite_page_info(); + } else { + previews_data = ui_tab_helper->CreatePreviewsUserDataForNavigationHandle( + navigation_handle, previews_decider_impl->GeneratePageId()); + } + + DCHECK(previews_data); + + bool is_reload = + navigation_handle->GetReloadType() != content::ReloadType::NONE; + + content::PreviewsState server_previews_enabled_state = + content::SERVER_LOFI_ON | content::SERVER_LITE_PAGE_ON; + + if (is_redirect) { + previews_state |= (previews_data->allowed_previews_state() & + server_previews_enabled_state); + } else { + if (previews_decider_impl->ShouldAllowPreviewAtNavigationStart( + previews_data, current_navigation_url, is_reload, + previews::PreviewsType::LITE_PAGE)) { + previews_state |= server_previews_enabled_state; + } + } + + previews_state |= previews::DetermineAllowedClientPreviewsState( + previews_data, current_navigation_url, is_reload, is_redirect, + data_reduction_proxy_settings->IsDataReductionProxyEnabled(), + previews_decider_impl, navigation_handle); + + if (previews_state & content::PREVIEWS_OFF) { + previews_data->set_allowed_previews_state(content::PREVIEWS_OFF); + return content::PREVIEWS_OFF; + } + + if (previews_state & content::PREVIEWS_NO_TRANSFORM) { + previews_data->set_allowed_previews_state(content::PREVIEWS_NO_TRANSFORM); + return content::PREVIEWS_NO_TRANSFORM; + } + + if (previews_state == content::PREVIEWS_UNSPECIFIED) { + previews_data->set_allowed_previews_state(content::PREVIEWS_OFF); + return content::PREVIEWS_OFF; + } + + content::PreviewsState embedder_state = content::PREVIEWS_UNSPECIFIED; + if (delegate) { + delegate->AdjustPreviewsStateForNavigation(web_contents, &embedder_state); + } + + if (embedder_state != content::PREVIEWS_UNSPECIFIED) { + previews_state = previews_state & embedder_state; + if (previews_state == content::PREVIEWS_UNSPECIFIED) + previews_state = content::PREVIEWS_OFF; + } + previews_data->set_allowed_previews_state(previews_state); + return previews_state; +} +",0,"content::PreviewsState ChromeContentBrowserClient::DetermineAllowedPreviews( + content::PreviewsState initial_state, + content::NavigationHandle* navigation_handle, + const GURL& current_navigation_url) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + DCHECK(!navigation_handle->HasCommitted()); + + if (!navigation_handle->IsInMainFrame() || + navigation_handle->IsSameDocument()) { + return initial_state; + } + + if (!current_navigation_url.SchemeIsHTTPOrHTTPS()) + return content::PREVIEWS_OFF; + + if (navigation_handle->IsPost()) + return content::PREVIEWS_OFF; + + content::WebContents* web_contents = navigation_handle->GetWebContents(); + content::WebContentsDelegate* delegate = web_contents->GetDelegate(); + + auto* browser_context = web_contents->GetBrowserContext(); + + PreviewsService* previews_service = PreviewsServiceFactory::GetForProfile( + Profile::FromBrowserContext(browser_context)); + auto* data_reduction_proxy_settings = + DataReductionProxyChromeSettingsFactory::GetForBrowserContext( + browser_context); + if (!previews_service || !previews_service->previews_ui_service() || + !data_reduction_proxy_settings) { + return content::PREVIEWS_OFF; + } + + PreviewsUITabHelper* ui_tab_helper = + PreviewsUITabHelper::FromWebContents(web_contents); + if (!ui_tab_helper) + return content::PREVIEWS_OFF; + + DCHECK(!browser_context->IsOffTheRecord()); + + previews::PreviewsDeciderImpl* previews_decider_impl = + previews_service->previews_ui_service()->previews_decider_impl(); + DCHECK(previews_decider_impl); + + content::PreviewsState previews_state = content::PREVIEWS_UNSPECIFIED; + + previews::PreviewsUserData* previews_data = + ui_tab_helper->GetPreviewsUserData(navigation_handle); + + bool is_redirect = false; + if (previews_data) { + is_redirect = !previews_data->server_lite_page_info(); + } else { + previews_data = ui_tab_helper->CreatePreviewsUserDataForNavigationHandle( + navigation_handle, previews_decider_impl->GeneratePageId()); + } + + DCHECK(previews_data); + + bool is_reload = + navigation_handle->GetReloadType() != content::ReloadType::NONE; + + content::PreviewsState server_previews_enabled_state = + content::SERVER_LOFI_ON | content::SERVER_LITE_PAGE_ON; + + if (is_redirect) { + previews_state |= (previews_data->allowed_previews_state() & + server_previews_enabled_state); + } else { + if (previews_decider_impl->ShouldAllowPreviewAtNavigationStart( + previews_data, current_navigation_url, is_reload, + previews::PreviewsType::LITE_PAGE)) { + previews_state |= server_previews_enabled_state; + } + } + + previews_state |= previews::DetermineAllowedClientPreviewsState( + previews_data, current_navigation_url, is_reload, is_redirect, + data_reduction_proxy_settings->IsDataReductionProxyEnabled(), + previews_decider_impl, navigation_handle); + + if (previews_state & content::PREVIEWS_OFF) { + previews_data->set_allowed_previews_state(content::PREVIEWS_OFF); + return content::PREVIEWS_OFF; + } + + if (previews_state & content::PREVIEWS_NO_TRANSFORM) { + previews_data->set_allowed_previews_state(content::PREVIEWS_NO_TRANSFORM); + return content::PREVIEWS_NO_TRANSFORM; + } + + if (previews_state == content::PREVIEWS_UNSPECIFIED) { + previews_data->set_allowed_previews_state(content::PREVIEWS_OFF); + return content::PREVIEWS_OFF; + } + + content::PreviewsState embedder_state = content::PREVIEWS_UNSPECIFIED; + if (delegate) { + delegate->AdjustPreviewsStateForNavigation(web_contents, &embedder_state); + } + + if (embedder_state != content::PREVIEWS_UNSPECIFIED) { + previews_state = previews_state & embedder_state; + if (previews_state == content::PREVIEWS_UNSPECIFIED) + previews_state = content::PREVIEWS_OFF; + } + previews_data->set_allowed_previews_state(previews_state); + return previews_state; +} +","@@ -2282,12 +2282,9 @@ const gfx::ImageSkia* ChromeContentBrowserClient::GetDefaultFavicon() { + + bool ChromeContentBrowserClient::IsDataSaverEnabled( + content::BrowserContext* browser_context) { +- data_reduction_proxy::DataReductionProxySettings* +- data_reduction_proxy_settings = +- DataReductionProxyChromeSettingsFactory::GetForBrowserContext( +- browser_context); +- return data_reduction_proxy_settings && +- data_reduction_proxy_settings->IsDataSaverEnabledByUser(); ++ Profile* profile = Profile::FromBrowserContext(browser_context); ++ return profile && data_reduction_proxy::DataReductionProxySettings:: ++ IsDataSaverEnabledByUser(profile->GetPrefs()); + } + + void ChromeContentBrowserClient::UpdateRendererPreferencesForWorker(",902,1233,2048 +15010,"void TabletModeWindowState::OnWMEvent(wm::WindowState* window_state, + const wm::WMEvent* event) { + if (ignore_wm_events_) { + return; + } + + switch (event->type()) { + case wm::WM_EVENT_TOGGLE_FULLSCREEN: + ToggleFullScreen(window_state, window_state->delegate()); + break; + case wm::WM_EVENT_FULLSCREEN: + UpdateWindow(window_state, WindowStateType::kFullscreen, + true /* animated */); + break; + case wm::WM_EVENT_PIN: + if (!Shell::Get()->screen_pinning_controller()->IsPinned()) + UpdateWindow(window_state, WindowStateType::kPinned, + true /* animated */); + break; + case wm::WM_EVENT_PIP: + if (!window_state->IsPip()) { + UpdateWindow(window_state, WindowStateType::kPip, true /* animated */); + } + break; + case wm::WM_EVENT_TRUSTED_PIN: + if (!Shell::Get()->screen_pinning_controller()->IsPinned()) + UpdateWindow(window_state, WindowStateType::kTrustedPinned, + true /* animated */); + break; + case wm::WM_EVENT_TOGGLE_MAXIMIZE_CAPTION: + case wm::WM_EVENT_TOGGLE_VERTICAL_MAXIMIZE: + case wm::WM_EVENT_TOGGLE_HORIZONTAL_MAXIMIZE: + case wm::WM_EVENT_TOGGLE_MAXIMIZE: + case wm::WM_EVENT_CYCLE_SNAP_LEFT: + case wm::WM_EVENT_CYCLE_SNAP_RIGHT: + case wm::WM_EVENT_CENTER: + case wm::WM_EVENT_NORMAL: + case wm::WM_EVENT_MAXIMIZE: + UpdateWindow(window_state, GetMaximizedOrCenteredWindowType(window_state), + true /* animated */); + return; + case wm::WM_EVENT_SNAP_LEFT: + window_state->set_bounds_changed_by_user(true); + UpdateWindow(window_state, + GetSnappedWindowStateType(window_state, + WindowStateType::kLeftSnapped), + false /* animated */); + return; + case wm::WM_EVENT_SNAP_RIGHT: + window_state->set_bounds_changed_by_user(true); + UpdateWindow(window_state, + GetSnappedWindowStateType(window_state, + WindowStateType::kRightSnapped), + false /* animated */); + return; + case wm::WM_EVENT_MINIMIZE: + UpdateWindow(window_state, WindowStateType::kMinimized, + true /* animated */); + return; + case wm::WM_EVENT_SHOW_INACTIVE: + case wm::WM_EVENT_SYSTEM_UI_AREA_CHANGED: + return; + case wm::WM_EVENT_SET_BOUNDS: { + gfx::Rect bounds_in_parent = + (static_cast(event))->requested_bounds(); + if (bounds_in_parent.IsEmpty()) + return; + + if (wm::IsDraggingTabs(window_state->window()) || + IsTabDraggingSourceWindow(window_state->window())) { + window_state->SetBoundsDirect(bounds_in_parent); + } else if (current_state_type_ == WindowStateType::kMaximized) { + window_state->SetRestoreBoundsInParent(bounds_in_parent); + } else if (current_state_type_ != WindowStateType::kMinimized && + current_state_type_ != WindowStateType::kFullscreen && + current_state_type_ != WindowStateType::kPinned && + current_state_type_ != WindowStateType::kTrustedPinned && + current_state_type_ != WindowStateType::kLeftSnapped && + current_state_type_ != WindowStateType::kRightSnapped) { + bounds_in_parent = GetCenteredBounds(bounds_in_parent, window_state); + if (bounds_in_parent != window_state->window()->bounds()) { + const wm::SetBoundsEvent* bounds_event = + static_cast(event); + if (window_state->window()->IsVisible() && bounds_event->animate()) + window_state->SetBoundsDirectAnimated(bounds_in_parent); + else + window_state->SetBoundsDirect(bounds_in_parent); + } + } + break; + } + case wm::WM_EVENT_ADDED_TO_WORKSPACE: + if (current_state_type_ != WindowStateType::kMaximized && + current_state_type_ != WindowStateType::kFullscreen && + current_state_type_ != WindowStateType::kMinimized) { + WindowStateType new_state = + GetMaximizedOrCenteredWindowType(window_state); + UpdateWindow(window_state, new_state, true /* animated */); + } + break; + case wm::WM_EVENT_WORKAREA_BOUNDS_CHANGED: + if (current_state_type_ != WindowStateType::kMinimized) + UpdateBounds(window_state, true /* animated */); + break; + case wm::WM_EVENT_DISPLAY_BOUNDS_CHANGED: + if (current_state_type_ != WindowStateType::kMinimized) + UpdateBounds(window_state, false /* animated */); + break; + } +} +",0,"void TabletModeWindowState::OnWMEvent(wm::WindowState* window_state, + const wm::WMEvent* event) { + if (ignore_wm_events_) { + return; + } + + switch (event->type()) { + case wm::WM_EVENT_TOGGLE_FULLSCREEN: + ToggleFullScreen(window_state, window_state->delegate()); + break; + case wm::WM_EVENT_FULLSCREEN: + UpdateWindow(window_state, WindowStateType::kFullscreen, + true /* animated */); + break; + case wm::WM_EVENT_PIN: + if (!Shell::Get()->screen_pinning_controller()->IsPinned()) + UpdateWindow(window_state, WindowStateType::kPinned, + true /* animated */); + break; + case wm::WM_EVENT_PIP: + if (!window_state->IsPip()) { + UpdateWindow(window_state, WindowStateType::kPip, true /* animated */); + } + break; + case wm::WM_EVENT_TRUSTED_PIN: + if (!Shell::Get()->screen_pinning_controller()->IsPinned()) + UpdateWindow(window_state, WindowStateType::kTrustedPinned, + true /* animated */); + break; + case wm::WM_EVENT_TOGGLE_MAXIMIZE_CAPTION: + case wm::WM_EVENT_TOGGLE_VERTICAL_MAXIMIZE: + case wm::WM_EVENT_TOGGLE_HORIZONTAL_MAXIMIZE: + case wm::WM_EVENT_TOGGLE_MAXIMIZE: + case wm::WM_EVENT_CYCLE_SNAP_LEFT: + case wm::WM_EVENT_CYCLE_SNAP_RIGHT: + case wm::WM_EVENT_CENTER: + case wm::WM_EVENT_NORMAL: + case wm::WM_EVENT_MAXIMIZE: + UpdateWindow(window_state, GetMaximizedOrCenteredWindowType(window_state), + true /* animated */); + return; + case wm::WM_EVENT_SNAP_LEFT: + window_state->set_bounds_changed_by_user(true); + UpdateWindow(window_state, + GetSnappedWindowStateType(window_state, + WindowStateType::kLeftSnapped), + false /* animated */); + return; + case wm::WM_EVENT_SNAP_RIGHT: + window_state->set_bounds_changed_by_user(true); + UpdateWindow(window_state, + GetSnappedWindowStateType(window_state, + WindowStateType::kRightSnapped), + false /* animated */); + return; + case wm::WM_EVENT_MINIMIZE: + UpdateWindow(window_state, WindowStateType::kMinimized, + true /* animated */); + return; + case wm::WM_EVENT_SHOW_INACTIVE: + case wm::WM_EVENT_SYSTEM_UI_AREA_CHANGED: + return; + case wm::WM_EVENT_SET_BOUNDS: { + gfx::Rect bounds_in_parent = + (static_cast(event))->requested_bounds(); + if (bounds_in_parent.IsEmpty()) + return; + + if (wm::IsDraggingTabs(window_state->window()) || + IsTabDraggingSourceWindow(window_state->window())) { + window_state->SetBoundsDirect(bounds_in_parent); + } else if (current_state_type_ == WindowStateType::kMaximized) { + window_state->SetRestoreBoundsInParent(bounds_in_parent); + } else if (current_state_type_ != WindowStateType::kMinimized && + current_state_type_ != WindowStateType::kFullscreen && + current_state_type_ != WindowStateType::kPinned && + current_state_type_ != WindowStateType::kTrustedPinned && + current_state_type_ != WindowStateType::kLeftSnapped && + current_state_type_ != WindowStateType::kRightSnapped) { + bounds_in_parent = GetCenteredBounds(bounds_in_parent, window_state); + if (bounds_in_parent != window_state->window()->bounds()) { + const wm::SetBoundsEvent* bounds_event = + static_cast(event); + if (window_state->window()->IsVisible() && bounds_event->animate()) + window_state->SetBoundsDirectAnimated(bounds_in_parent); + else + window_state->SetBoundsDirect(bounds_in_parent); + } + } + break; + } + case wm::WM_EVENT_ADDED_TO_WORKSPACE: + if (current_state_type_ != WindowStateType::kMaximized && + current_state_type_ != WindowStateType::kFullscreen && + current_state_type_ != WindowStateType::kMinimized) { + WindowStateType new_state = + GetMaximizedOrCenteredWindowType(window_state); + UpdateWindow(window_state, new_state, true /* animated */); + } + break; + case wm::WM_EVENT_WORKAREA_BOUNDS_CHANGED: + if (current_state_type_ != WindowStateType::kMinimized) + UpdateBounds(window_state, true /* animated */); + break; + case wm::WM_EVENT_DISPLAY_BOUNDS_CHANGED: + if (current_state_type_ != WindowStateType::kMinimized) + UpdateBounds(window_state, false /* animated */); + break; + } +} +","@@ -198,12 +198,15 @@ TabletModeWindowState::~TabletModeWindowState() { + creator_->WindowStateDestroyed(window_); + } + +-void TabletModeWindowState::LeaveTabletMode(wm::WindowState* window_state) { +- // Only do bounds change animation if the window is the top window or a window +- // showing in splitview, and the window has changed its state. Otherwise, +- // restore its bounds immediately. ++void TabletModeWindowState::LeaveTabletMode(wm::WindowState* window_state, ++ bool was_in_overview) { ++ // Only do bounds change animation if the window was showing in overview, ++ // or the top window or a window showing in splitview before leaving tablet ++ // mode, and the window has changed its state. Otherwise, restore its bounds ++ // immediately. + EnterAnimationType animation_type = +- window_state->IsSnapped() || IsTopWindow(window_state->window()) ++ was_in_overview || window_state->IsSnapped() || ++ IsTopWindow(window_state->window()) + ? DEFAULT + : IMMEDIATE; + if (old_state_->GetType() == window_state->GetStateType() &&",1018,1349,2048 +4299,"int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) +{ + struct udp_sock *up = udp_sk(sk); + int rc; + int is_udplite = IS_UDPLITE(sk); + + /* + * Charge it to the socket, dropping if the queue is full. + */ + if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) + goto drop; + nf_reset(skb); + + if (static_key_false(&udp_encap_needed) && up->encap_type) { + int (*encap_rcv)(struct sock *sk, struct sk_buff *skb); + + /* + * This is an encapsulation socket so pass the skb to + * the socket's udp_encap_rcv() hook. Otherwise, just + * fall through and pass this up the UDP socket. + * up->encap_rcv() returns the following value: + * =0 if skb was successfully passed to the encap + * handler or was discarded by it. + * >0 if skb should be passed on to UDP. + * <0 if skb should be resubmitted as proto -N + */ + + /* if we're overly short, let UDP handle it */ + encap_rcv = ACCESS_ONCE(up->encap_rcv); + if (skb->len > sizeof(struct udphdr) && encap_rcv) { + int ret; + + /* Verify checksum before giving to encap */ + if (udp_lib_checksum_complete(skb)) + goto csum_error; + + ret = encap_rcv(sk, skb); + if (ret <= 0) { + UDP_INC_STATS_BH(sock_net(sk), + UDP_MIB_INDATAGRAMS, + is_udplite); + return -ret; + } + } + + /* FALLTHROUGH -- it's a UDP Packet */ + } + + /* + * UDP-Lite specific tests, ignored on UDP sockets + */ + if ((is_udplite & UDPLITE_RECV_CC) && UDP_SKB_CB(skb)->partial_cov) { + + /* + * MIB statistics other than incrementing the error count are + * disabled for the following two types of errors: these depend + * on the application settings, not on the functioning of the + * protocol stack as such. + * + * RFC 3828 here recommends (sec 3.3): ""There should also be a + * way ... to ... at least let the receiving application block + * delivery of packets with coverage values less than a value + * provided by the application."" + */ + if (up->pcrlen == 0) { /* full coverage was set */ + net_dbg_ratelimited(""UDPLite: partial coverage %d while full coverage %d requested\n"", + UDP_SKB_CB(skb)->cscov, skb->len); + goto drop; + } + /* The next case involves violating the min. coverage requested + * by the receiver. This is subtle: if receiver wants x and x is + * greater than the buffersize/MTU then receiver will complain + * that it wants x while sender emits packets of smaller size y. + * Therefore the above ...()->partial_cov statement is essential. + */ + if (UDP_SKB_CB(skb)->cscov < up->pcrlen) { + net_dbg_ratelimited(""UDPLite: coverage %d too small, need min %d\n"", + UDP_SKB_CB(skb)->cscov, up->pcrlen); + goto drop; + } + } + + if (rcu_access_pointer(sk->sk_filter) && + udp_lib_checksum_complete(skb)) + goto csum_error; + + if (sk_rcvqueues_full(sk, sk->sk_rcvbuf)) { + UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_RCVBUFERRORS, + is_udplite); + goto drop; + } + + rc = 0; + + ipv4_pktinfo_prepare(sk, skb); + bh_lock_sock(sk); + if (!sock_owned_by_user(sk)) + rc = __udp_queue_rcv_skb(sk, skb); + else if (sk_add_backlog(sk, skb, sk->sk_rcvbuf)) { + bh_unlock_sock(sk); + goto drop; + } + bh_unlock_sock(sk); + + return rc; + +csum_error: + UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); +drop: + UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, is_udplite); + atomic_inc(&sk->sk_drops); + kfree_skb(skb); + return -1; +} +",0,"int udp_queue_rcv_skb(struct sock *sk, struct sk_buff *skb) +{ + struct udp_sock *up = udp_sk(sk); + int rc; + int is_udplite = IS_UDPLITE(sk); + + /* + * Charge it to the socket, dropping if the queue is full. + */ + if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) + goto drop; + nf_reset(skb); + + if (static_key_false(&udp_encap_needed) && up->encap_type) { + int (*encap_rcv)(struct sock *sk, struct sk_buff *skb); + + /* + * This is an encapsulation socket so pass the skb to + * the socket's udp_encap_rcv() hook. Otherwise, just + * fall through and pass this up the UDP socket. + * up->encap_rcv() returns the following value: + * =0 if skb was successfully passed to the encap + * handler or was discarded by it. + * >0 if skb should be passed on to UDP. + * <0 if skb should be resubmitted as proto -N + */ + + /* if we're overly short, let UDP handle it */ + encap_rcv = ACCESS_ONCE(up->encap_rcv); + if (skb->len > sizeof(struct udphdr) && encap_rcv) { + int ret; + + /* Verify checksum before giving to encap */ + if (udp_lib_checksum_complete(skb)) + goto csum_error; + + ret = encap_rcv(sk, skb); + if (ret <= 0) { + UDP_INC_STATS_BH(sock_net(sk), + UDP_MIB_INDATAGRAMS, + is_udplite); + return -ret; + } + } + + /* FALLTHROUGH -- it's a UDP Packet */ + } + + /* + * UDP-Lite specific tests, ignored on UDP sockets + */ + if ((is_udplite & UDPLITE_RECV_CC) && UDP_SKB_CB(skb)->partial_cov) { + + /* + * MIB statistics other than incrementing the error count are + * disabled for the following two types of errors: these depend + * on the application settings, not on the functioning of the + * protocol stack as such. + * + * RFC 3828 here recommends (sec 3.3): ""There should also be a + * way ... to ... at least let the receiving application block + * delivery of packets with coverage values less than a value + * provided by the application."" + */ + if (up->pcrlen == 0) { /* full coverage was set */ + net_dbg_ratelimited(""UDPLite: partial coverage %d while full coverage %d requested\n"", + UDP_SKB_CB(skb)->cscov, skb->len); + goto drop; + } + /* The next case involves violating the min. coverage requested + * by the receiver. This is subtle: if receiver wants x and x is + * greater than the buffersize/MTU then receiver will complain + * that it wants x while sender emits packets of smaller size y. + * Therefore the above ...()->partial_cov statement is essential. + */ + if (UDP_SKB_CB(skb)->cscov < up->pcrlen) { + net_dbg_ratelimited(""UDPLite: coverage %d too small, need min %d\n"", + UDP_SKB_CB(skb)->cscov, up->pcrlen); + goto drop; + } + } + + if (rcu_access_pointer(sk->sk_filter) && + udp_lib_checksum_complete(skb)) + goto csum_error; + + if (sk_rcvqueues_full(sk, sk->sk_rcvbuf)) { + UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_RCVBUFERRORS, + is_udplite); + goto drop; + } + + rc = 0; + + ipv4_pktinfo_prepare(sk, skb); + bh_lock_sock(sk); + if (!sock_owned_by_user(sk)) + rc = __udp_queue_rcv_skb(sk, skb); + else if (sk_add_backlog(sk, skb, sk->sk_rcvbuf)) { + bh_unlock_sock(sk); + goto drop; + } + bh_unlock_sock(sk); + + return rc; + +csum_error: + UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); +drop: + UDP_INC_STATS_BH(sock_net(sk), UDP_MIB_INERRORS, is_udplite); + atomic_inc(&sk->sk_drops); + kfree_skb(skb); + return -1; +} +","@@ -1345,10 +1345,8 @@ int udp_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int noblock, + } + unlock_sock_fast(sk, slow); + +- if (noblock) +- return -EAGAIN; +- +- /* starting over for a new packet */ ++ /* starting over for a new packet, but check if we need to yield */ ++ cond_resched(); + msg->msg_flags &= ~MSG_TRUNC; + goto try_again; + }",992,1323,2048 +11476,"void OmniboxViewWin::DrawSlashForInsecureScheme(HDC hdc, + const CRect& client_rect, + const CRect& paint_clip_rect) { + DCHECK(insecure_scheme_component_.is_nonempty()); + + const int font_top = client_rect.top + font_y_adjustment_; + const SkScalar kStrokeWidthPixels = SkIntToScalar(2); + const int kAdditionalSpaceOutsideFont = + static_cast(ceil(kStrokeWidthPixels * 1.5f)); + const CRect scheme_rect(PosFromChar(insecure_scheme_component_.begin).x, + font_top + font_.GetBaseline() - font_x_height_ - + kAdditionalSpaceOutsideFont, + PosFromChar(insecure_scheme_component_.end()).x, + font_top + font_.GetBaseline() + + kAdditionalSpaceOutsideFont); + + CRect canvas_clip_rect, canvas_paint_clip_rect; + canvas_clip_rect.IntersectRect(scheme_rect, client_rect); + canvas_paint_clip_rect.IntersectRect(canvas_clip_rect, paint_clip_rect); + if (canvas_paint_clip_rect.IsRectNull()) + return; // We don't need to paint any of this region, so just bail early. + canvas_clip_rect.OffsetRect(-scheme_rect.left, -scheme_rect.top); + canvas_paint_clip_rect.OffsetRect(-scheme_rect.left, -scheme_rect.top); + + SkPaint paint; + paint.setAntiAlias(true); + paint.setStrokeWidth(kStrokeWidthPixels); + paint.setStrokeCap(SkPaint::kRound_Cap); + + gfx::CanvasSkia canvas(gfx::Size(scheme_rect.Width(), scheme_rect.Height()), + false); + SkCanvas* sk_canvas = canvas.sk_canvas(); + sk_canvas->getDevice()->accessBitmap(true).eraseARGB(0, 0, 0, 0); + + const SkScalar kEndCapRadiusPixels = kStrokeWidthPixels / SkIntToScalar(2); + const SkPoint start_point = { + kEndCapRadiusPixels, + SkIntToScalar(scheme_rect.Height()) - kEndCapRadiusPixels }; + const SkPoint end_point = { + SkIntToScalar(scheme_rect.Width()) - kEndCapRadiusPixels, + kEndCapRadiusPixels }; + + CHARRANGE sel; + GetSel(sel); + const SkRect selection_rect = { + SkIntToScalar(PosFromChar(sel.cpMin).x - scheme_rect.left), + SkIntToScalar(0), + SkIntToScalar(PosFromChar(sel.cpMax).x - scheme_rect.left), + SkIntToScalar(scheme_rect.Height()) }; + + sk_canvas->save(); + if (selection_rect.isEmpty() || + sk_canvas->clipRect(selection_rect, SkRegion::kDifference_Op)) { + paint.setColor(LocationBarView::GetColor(security_level_, + LocationBarView::SECURITY_TEXT)); + sk_canvas->drawLine(start_point.fX, start_point.fY, + end_point.fX, end_point.fY, paint); + } + sk_canvas->restore(); + + if (!selection_rect.isEmpty() && sk_canvas->clipRect(selection_rect)) { + paint.setColor(LocationBarView::GetColor(security_level_, + LocationBarView::SELECTED_TEXT)); + sk_canvas->drawLine(start_point.fX, start_point.fY, + end_point.fX, end_point.fY, paint); + } + + skia::DrawToNativeContext(sk_canvas, hdc, + scheme_rect.left + canvas_paint_clip_rect.left - canvas_clip_rect.left, + std::max(scheme_rect.top, client_rect.top) + canvas_paint_clip_rect.top - + canvas_clip_rect.top, &canvas_paint_clip_rect); +} +",0,"void OmniboxViewWin::DrawSlashForInsecureScheme(HDC hdc, + const CRect& client_rect, + const CRect& paint_clip_rect) { + DCHECK(insecure_scheme_component_.is_nonempty()); + + const int font_top = client_rect.top + font_y_adjustment_; + const SkScalar kStrokeWidthPixels = SkIntToScalar(2); + const int kAdditionalSpaceOutsideFont = + static_cast(ceil(kStrokeWidthPixels * 1.5f)); + const CRect scheme_rect(PosFromChar(insecure_scheme_component_.begin).x, + font_top + font_.GetBaseline() - font_x_height_ - + kAdditionalSpaceOutsideFont, + PosFromChar(insecure_scheme_component_.end()).x, + font_top + font_.GetBaseline() + + kAdditionalSpaceOutsideFont); + + CRect canvas_clip_rect, canvas_paint_clip_rect; + canvas_clip_rect.IntersectRect(scheme_rect, client_rect); + canvas_paint_clip_rect.IntersectRect(canvas_clip_rect, paint_clip_rect); + if (canvas_paint_clip_rect.IsRectNull()) + return; // We don't need to paint any of this region, so just bail early. + canvas_clip_rect.OffsetRect(-scheme_rect.left, -scheme_rect.top); + canvas_paint_clip_rect.OffsetRect(-scheme_rect.left, -scheme_rect.top); + + SkPaint paint; + paint.setAntiAlias(true); + paint.setStrokeWidth(kStrokeWidthPixels); + paint.setStrokeCap(SkPaint::kRound_Cap); + + gfx::CanvasSkia canvas(gfx::Size(scheme_rect.Width(), scheme_rect.Height()), + false); + SkCanvas* sk_canvas = canvas.sk_canvas(); + sk_canvas->getDevice()->accessBitmap(true).eraseARGB(0, 0, 0, 0); + + const SkScalar kEndCapRadiusPixels = kStrokeWidthPixels / SkIntToScalar(2); + const SkPoint start_point = { + kEndCapRadiusPixels, + SkIntToScalar(scheme_rect.Height()) - kEndCapRadiusPixels }; + const SkPoint end_point = { + SkIntToScalar(scheme_rect.Width()) - kEndCapRadiusPixels, + kEndCapRadiusPixels }; + + CHARRANGE sel; + GetSel(sel); + const SkRect selection_rect = { + SkIntToScalar(PosFromChar(sel.cpMin).x - scheme_rect.left), + SkIntToScalar(0), + SkIntToScalar(PosFromChar(sel.cpMax).x - scheme_rect.left), + SkIntToScalar(scheme_rect.Height()) }; + + sk_canvas->save(); + if (selection_rect.isEmpty() || + sk_canvas->clipRect(selection_rect, SkRegion::kDifference_Op)) { + paint.setColor(LocationBarView::GetColor(security_level_, + LocationBarView::SECURITY_TEXT)); + sk_canvas->drawLine(start_point.fX, start_point.fY, + end_point.fX, end_point.fY, paint); + } + sk_canvas->restore(); + + if (!selection_rect.isEmpty() && sk_canvas->clipRect(selection_rect)) { + paint.setColor(LocationBarView::GetColor(security_level_, + LocationBarView::SELECTED_TEXT)); + sk_canvas->drawLine(start_point.fX, start_point.fY, + end_point.fX, end_point.fY, paint); + } + + skia::DrawToNativeContext(sk_canvas, hdc, + scheme_rect.left + canvas_paint_clip_rect.left - canvas_clip_rect.left, + std::max(scheme_rect.top, client_rect.top) + canvas_paint_clip_rect.top - + canvas_clip_rect.top, &canvas_paint_clip_rect); +} +","@@ -1003,8 +1003,7 @@ int OmniboxViewWin::OnPerformDropImpl(const views::DropTargetEvent& event, + if (data.GetURLAndTitle(&url, &title)) { + string16 text(StripJavascriptSchemas(UTF8ToUTF16(url.spec()))); + SetUserText(text); +- if (url.spec().length() == text.length()) +- model()->AcceptInput(CURRENT_TAB, true); ++ model()->AcceptInput(CURRENT_TAB, true); + return CopyOrLinkDragOperation(event.source_operations()); + } + } else if (data.HasString()) {",757,1088,2048 +17648,"xmlParsePI(xmlParserCtxtPtr ctxt) { + xmlChar *buf = NULL; + size_t len = 0; + size_t size = XML_PARSER_BUFFER_SIZE; + int cur, l; + const xmlChar *target; + xmlParserInputState state; + int count = 0; + + if ((RAW == '<') && (NXT(1) == '?')) { + xmlParserInputPtr input = ctxt->input; + state = ctxt->instate; + ctxt->instate = XML_PARSER_PI; + /* + * this is a Processing Instruction. + */ + SKIP(2); + SHRINK; + + /* + * Parse the target name and check for special support like + * namespace. + */ + target = xmlParsePITarget(ctxt); + if (target != NULL) { + if ((RAW == '?') && (NXT(1) == '>')) { + if (input != ctxt->input) { + xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY, + ""PI declaration doesn't start and stop in the same entity\n""); + } + SKIP(2); + + /* + * SAX: PI detected. + */ + if ((ctxt->sax) && (!ctxt->disableSAX) && + (ctxt->sax->processingInstruction != NULL)) + ctxt->sax->processingInstruction(ctxt->userData, + target, NULL); + if (ctxt->instate != XML_PARSER_EOF) + ctxt->instate = state; + return; + } + buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); + if (buf == NULL) { + xmlErrMemory(ctxt, NULL); + ctxt->instate = state; + return; + } + cur = CUR; + if (!IS_BLANK(cur)) { + xmlFatalErrMsgStr(ctxt, XML_ERR_SPACE_REQUIRED, + ""ParsePI: PI %s space expected\n"", target); + } + SKIP_BLANKS; + cur = CUR_CHAR(l); + while (IS_CHAR(cur) && /* checked */ + ((cur != '?') || (NXT(1) != '>'))) { + if (len + 5 >= size) { + xmlChar *tmp; + size_t new_size = size * 2; + tmp = (xmlChar *) xmlRealloc(buf, new_size); + if (tmp == NULL) { + xmlErrMemory(ctxt, NULL); + xmlFree(buf); + ctxt->instate = state; + return; + } + buf = tmp; + size = new_size; + } + count++; + if (count > 50) { + GROW; + if (ctxt->instate == XML_PARSER_EOF) { + xmlFree(buf); + return; + } + count = 0; + if ((len > XML_MAX_TEXT_LENGTH) && + ((ctxt->options & XML_PARSE_HUGE) == 0)) { + xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED, + ""PI %s too big found"", target); + xmlFree(buf); + ctxt->instate = state; + return; + } + } + COPY_BUF(l,buf,len,cur); + NEXTL(l); + cur = CUR_CHAR(l); + if (cur == 0) { + SHRINK; + GROW; + cur = CUR_CHAR(l); + } + } + if ((len > XML_MAX_TEXT_LENGTH) && + ((ctxt->options & XML_PARSE_HUGE) == 0)) { + xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED, + ""PI %s too big found"", target); + xmlFree(buf); + ctxt->instate = state; + return; + } + buf[len] = 0; + if (cur != '?') { + xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED, + ""ParsePI: PI %s never end ...\n"", target); + } else { + if (input != ctxt->input) { + xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, + ""PI declaration doesn't start and stop in the same entity\n""); + } + SKIP(2); + +#ifdef LIBXML_CATALOG_ENABLED + if (((state == XML_PARSER_MISC) || + (state == XML_PARSER_START)) && + (xmlStrEqual(target, XML_CATALOG_PI))) { + xmlCatalogAllow allow = xmlCatalogGetDefaults(); + if ((allow == XML_CATA_ALLOW_DOCUMENT) || + (allow == XML_CATA_ALLOW_ALL)) + xmlParseCatalogPI(ctxt, buf); + } +#endif + + + /* + * SAX: PI detected. + */ + if ((ctxt->sax) && (!ctxt->disableSAX) && + (ctxt->sax->processingInstruction != NULL)) + ctxt->sax->processingInstruction(ctxt->userData, + target, buf); + } + xmlFree(buf); + } else { + xmlFatalErr(ctxt, XML_ERR_PI_NOT_STARTED, NULL); + } + if (ctxt->instate != XML_PARSER_EOF) + ctxt->instate = state; + } +} +",0,"xmlParsePI(xmlParserCtxtPtr ctxt) { + xmlChar *buf = NULL; + size_t len = 0; + size_t size = XML_PARSER_BUFFER_SIZE; + int cur, l; + const xmlChar *target; + xmlParserInputState state; + int count = 0; + + if ((RAW == '<') && (NXT(1) == '?')) { + xmlParserInputPtr input = ctxt->input; + state = ctxt->instate; + ctxt->instate = XML_PARSER_PI; + /* + * this is a Processing Instruction. + */ + SKIP(2); + SHRINK; + + /* + * Parse the target name and check for special support like + * namespace. + */ + target = xmlParsePITarget(ctxt); + if (target != NULL) { + if ((RAW == '?') && (NXT(1) == '>')) { + if (input != ctxt->input) { + xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY, + ""PI declaration doesn't start and stop in the same entity\n""); + } + SKIP(2); + + /* + * SAX: PI detected. + */ + if ((ctxt->sax) && (!ctxt->disableSAX) && + (ctxt->sax->processingInstruction != NULL)) + ctxt->sax->processingInstruction(ctxt->userData, + target, NULL); + if (ctxt->instate != XML_PARSER_EOF) + ctxt->instate = state; + return; + } + buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); + if (buf == NULL) { + xmlErrMemory(ctxt, NULL); + ctxt->instate = state; + return; + } + cur = CUR; + if (!IS_BLANK(cur)) { + xmlFatalErrMsgStr(ctxt, XML_ERR_SPACE_REQUIRED, + ""ParsePI: PI %s space expected\n"", target); + } + SKIP_BLANKS; + cur = CUR_CHAR(l); + while (IS_CHAR(cur) && /* checked */ + ((cur != '?') || (NXT(1) != '>'))) { + if (len + 5 >= size) { + xmlChar *tmp; + size_t new_size = size * 2; + tmp = (xmlChar *) xmlRealloc(buf, new_size); + if (tmp == NULL) { + xmlErrMemory(ctxt, NULL); + xmlFree(buf); + ctxt->instate = state; + return; + } + buf = tmp; + size = new_size; + } + count++; + if (count > 50) { + GROW; + if (ctxt->instate == XML_PARSER_EOF) { + xmlFree(buf); + return; + } + count = 0; + if ((len > XML_MAX_TEXT_LENGTH) && + ((ctxt->options & XML_PARSE_HUGE) == 0)) { + xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED, + ""PI %s too big found"", target); + xmlFree(buf); + ctxt->instate = state; + return; + } + } + COPY_BUF(l,buf,len,cur); + NEXTL(l); + cur = CUR_CHAR(l); + if (cur == 0) { + SHRINK; + GROW; + cur = CUR_CHAR(l); + } + } + if ((len > XML_MAX_TEXT_LENGTH) && + ((ctxt->options & XML_PARSE_HUGE) == 0)) { + xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED, + ""PI %s too big found"", target); + xmlFree(buf); + ctxt->instate = state; + return; + } + buf[len] = 0; + if (cur != '?') { + xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED, + ""ParsePI: PI %s never end ...\n"", target); + } else { + if (input != ctxt->input) { + xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, + ""PI declaration doesn't start and stop in the same entity\n""); + } + SKIP(2); + +#ifdef LIBXML_CATALOG_ENABLED + if (((state == XML_PARSER_MISC) || + (state == XML_PARSER_START)) && + (xmlStrEqual(target, XML_CATALOG_PI))) { + xmlCatalogAllow allow = xmlCatalogGetDefaults(); + if ((allow == XML_CATA_ALLOW_DOCUMENT) || + (allow == XML_CATA_ALLOW_ALL)) + xmlParseCatalogPI(ctxt, buf); + } +#endif + + + /* + * SAX: PI detected. + */ + if ((ctxt->sax) && (!ctxt->disableSAX) && + (ctxt->sax->processingInstruction != NULL)) + ctxt->sax->processingInstruction(ctxt->userData, + target, buf); + } + xmlFree(buf); + } else { + xmlFatalErr(ctxt, XML_ERR_PI_NOT_STARTED, NULL); + } + if (ctxt->instate != XML_PARSER_EOF) + ctxt->instate = state; + } +} +","@@ -8130,6 +8130,14 @@ + + if (xmlPushInput(ctxt, input) < 0) + return; + } else { ++ if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) && ++ ((ctxt->options & XML_PARSE_NOENT) == 0) && ++ ((ctxt->options & XML_PARSE_DTDVALID) == 0) && ++ ((ctxt->options & XML_PARSE_DTDLOAD) == 0) && ++ ((ctxt->options & XML_PARSE_DTDATTR) == 0) && ++ (ctxt->replaceEntities == 0) && ++ (ctxt->validate == 0)) ++ return; + /* + * TODO !!! + * handle the extra spaces added before and after +",1006,1337,2048 +17965,"static void init_vmcb(struct vcpu_svm *svm) +{ + struct vmcb_control_area *control = &svm->vmcb->control; + struct vmcb_save_area *save = &svm->vmcb->save; + + svm->vcpu.fpu_active = 1; + svm->vcpu.arch.hflags = 0; + + set_cr_intercept(svm, INTERCEPT_CR0_READ); + set_cr_intercept(svm, INTERCEPT_CR3_READ); + set_cr_intercept(svm, INTERCEPT_CR4_READ); + set_cr_intercept(svm, INTERCEPT_CR0_WRITE); + set_cr_intercept(svm, INTERCEPT_CR3_WRITE); + set_cr_intercept(svm, INTERCEPT_CR4_WRITE); + set_cr_intercept(svm, INTERCEPT_CR8_WRITE); + + set_dr_intercepts(svm); + + set_exception_intercept(svm, PF_VECTOR); + set_exception_intercept(svm, UD_VECTOR); + set_exception_intercept(svm, MC_VECTOR); + + set_intercept(svm, INTERCEPT_INTR); + set_intercept(svm, INTERCEPT_NMI); + set_intercept(svm, INTERCEPT_SMI); + set_intercept(svm, INTERCEPT_SELECTIVE_CR0); + set_intercept(svm, INTERCEPT_RDPMC); + set_intercept(svm, INTERCEPT_CPUID); + set_intercept(svm, INTERCEPT_INVD); + set_intercept(svm, INTERCEPT_HLT); + set_intercept(svm, INTERCEPT_INVLPG); + set_intercept(svm, INTERCEPT_INVLPGA); + set_intercept(svm, INTERCEPT_IOIO_PROT); + set_intercept(svm, INTERCEPT_MSR_PROT); + set_intercept(svm, INTERCEPT_TASK_SWITCH); + set_intercept(svm, INTERCEPT_SHUTDOWN); + set_intercept(svm, INTERCEPT_VMRUN); + set_intercept(svm, INTERCEPT_VMMCALL); + set_intercept(svm, INTERCEPT_VMLOAD); + set_intercept(svm, INTERCEPT_VMSAVE); + set_intercept(svm, INTERCEPT_STGI); + set_intercept(svm, INTERCEPT_CLGI); + set_intercept(svm, INTERCEPT_SKINIT); + set_intercept(svm, INTERCEPT_WBINVD); + set_intercept(svm, INTERCEPT_MONITOR); + set_intercept(svm, INTERCEPT_MWAIT); + set_intercept(svm, INTERCEPT_XSETBV); + + control->iopm_base_pa = iopm_base; + control->msrpm_base_pa = __pa(svm->msrpm); + control->int_ctl = V_INTR_MASKING_MASK; + + init_seg(&save->es); + init_seg(&save->ss); + init_seg(&save->ds); + init_seg(&save->fs); + init_seg(&save->gs); + + save->cs.selector = 0xf000; + save->cs.base = 0xffff0000; + /* Executable/Readable Code Segment */ + save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK | + SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK; + save->cs.limit = 0xffff; + + save->gdtr.limit = 0xffff; + save->idtr.limit = 0xffff; + + init_sys_seg(&save->ldtr, SEG_TYPE_LDT); + init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16); + + svm_set_efer(&svm->vcpu, 0); + save->dr6 = 0xffff0ff0; + kvm_set_rflags(&svm->vcpu, 2); + save->rip = 0x0000fff0; + svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip; + + /* + * svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0. + * It also updates the guest-visible cr0 value. + */ + svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET); + kvm_mmu_reset_context(&svm->vcpu); + + save->cr4 = X86_CR4_PAE; + /* rdx = ?? */ + + if (npt_enabled) { + /* Setup VMCB for Nested Paging */ + control->nested_ctl = 1; + clr_intercept(svm, INTERCEPT_INVLPG); + clr_exception_intercept(svm, PF_VECTOR); + clr_cr_intercept(svm, INTERCEPT_CR3_READ); + clr_cr_intercept(svm, INTERCEPT_CR3_WRITE); + save->g_pat = svm->vcpu.arch.pat; + save->cr3 = 0; + save->cr4 = 0; + } + svm->asid_generation = 0; + + svm->nested.vmcb = 0; + svm->vcpu.arch.hflags = 0; + + if (boot_cpu_has(X86_FEATURE_PAUSEFILTER)) { + control->pause_filter_count = 3000; + set_intercept(svm, INTERCEPT_PAUSE); + } + + mark_all_dirty(svm->vmcb); + + enable_gif(svm); +} +",1,"static void init_vmcb(struct vcpu_svm *svm) +{ + struct vmcb_control_area *control = &svm->vmcb->control; + struct vmcb_save_area *save = &svm->vmcb->save; + + svm->vcpu.fpu_active = 1; + svm->vcpu.arch.hflags = 0; + + set_cr_intercept(svm, INTERCEPT_CR0_READ); + set_cr_intercept(svm, INTERCEPT_CR3_READ); + set_cr_intercept(svm, INTERCEPT_CR4_READ); + set_cr_intercept(svm, INTERCEPT_CR0_WRITE); + set_cr_intercept(svm, INTERCEPT_CR3_WRITE); + set_cr_intercept(svm, INTERCEPT_CR4_WRITE); + set_cr_intercept(svm, INTERCEPT_CR8_WRITE); + + set_dr_intercepts(svm); + + set_exception_intercept(svm, PF_VECTOR); + set_exception_intercept(svm, UD_VECTOR); + set_exception_intercept(svm, MC_VECTOR); + set_exception_intercept(svm, AC_VECTOR); + + set_intercept(svm, INTERCEPT_INTR); + set_intercept(svm, INTERCEPT_NMI); + set_intercept(svm, INTERCEPT_SMI); + set_intercept(svm, INTERCEPT_SELECTIVE_CR0); + set_intercept(svm, INTERCEPT_RDPMC); + set_intercept(svm, INTERCEPT_CPUID); + set_intercept(svm, INTERCEPT_INVD); + set_intercept(svm, INTERCEPT_HLT); + set_intercept(svm, INTERCEPT_INVLPG); + set_intercept(svm, INTERCEPT_INVLPGA); + set_intercept(svm, INTERCEPT_IOIO_PROT); + set_intercept(svm, INTERCEPT_MSR_PROT); + set_intercept(svm, INTERCEPT_TASK_SWITCH); + set_intercept(svm, INTERCEPT_SHUTDOWN); + set_intercept(svm, INTERCEPT_VMRUN); + set_intercept(svm, INTERCEPT_VMMCALL); + set_intercept(svm, INTERCEPT_VMLOAD); + set_intercept(svm, INTERCEPT_VMSAVE); + set_intercept(svm, INTERCEPT_STGI); + set_intercept(svm, INTERCEPT_CLGI); + set_intercept(svm, INTERCEPT_SKINIT); + set_intercept(svm, INTERCEPT_WBINVD); + set_intercept(svm, INTERCEPT_MONITOR); + set_intercept(svm, INTERCEPT_MWAIT); + set_intercept(svm, INTERCEPT_XSETBV); + + control->iopm_base_pa = iopm_base; + control->msrpm_base_pa = __pa(svm->msrpm); + control->int_ctl = V_INTR_MASKING_MASK; + + init_seg(&save->es); + init_seg(&save->ss); + init_seg(&save->ds); + init_seg(&save->fs); + init_seg(&save->gs); + + save->cs.selector = 0xf000; + save->cs.base = 0xffff0000; + /* Executable/Readable Code Segment */ + save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK | + SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK; + save->cs.limit = 0xffff; + + save->gdtr.limit = 0xffff; + save->idtr.limit = 0xffff; + + init_sys_seg(&save->ldtr, SEG_TYPE_LDT); + init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16); + + svm_set_efer(&svm->vcpu, 0); + save->dr6 = 0xffff0ff0; + kvm_set_rflags(&svm->vcpu, 2); + save->rip = 0x0000fff0; + svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip; + + /* + * svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0. + * It also updates the guest-visible cr0 value. + */ + svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET); + kvm_mmu_reset_context(&svm->vcpu); + + save->cr4 = X86_CR4_PAE; + /* rdx = ?? */ + + if (npt_enabled) { + /* Setup VMCB for Nested Paging */ + control->nested_ctl = 1; + clr_intercept(svm, INTERCEPT_INVLPG); + clr_exception_intercept(svm, PF_VECTOR); + clr_cr_intercept(svm, INTERCEPT_CR3_READ); + clr_cr_intercept(svm, INTERCEPT_CR3_WRITE); + save->g_pat = svm->vcpu.arch.pat; + save->cr3 = 0; + save->cr4 = 0; + } + svm->asid_generation = 0; + + svm->nested.vmcb = 0; + svm->vcpu.arch.hflags = 0; + + if (boot_cpu_has(X86_FEATURE_PAUSEFILTER)) { + control->pause_filter_count = 3000; + set_intercept(svm, INTERCEPT_PAUSE); + } + + mark_all_dirty(svm->vmcb); + + enable_gif(svm); +} +","@@ -1019,6 +1019,7 @@ static void init_vmcb(struct vcpu_svm *svm) + set_exception_intercept(svm, PF_VECTOR); + set_exception_intercept(svm, UD_VECTOR); + set_exception_intercept(svm, MC_VECTOR); ++ set_exception_intercept(svm, AC_VECTOR); + + set_intercept(svm, INTERCEPT_INTR); + set_intercept(svm, INTERCEPT_NMI); +@@ -1707,6 +1708,12 @@ static int ud_interception(struct vcpu_svm *svm) + return 1; + } + ++static int ac_interception(struct vcpu_svm *svm) ++{ ++ kvm_queue_exception_e(&svm->vcpu, AC_VECTOR, 0); ++ return 1; ++} ++ + static void svm_fpu_activate(struct kvm_vcpu *vcpu) + { + struct vcpu_svm *svm = to_svm(vcpu); +@@ -3270,6 +3277,7 @@ static int (*const svm_exit_handlers[])(struct vcpu_svm *svm) = { + [SVM_EXIT_EXCP_BASE + PF_VECTOR] = pf_interception, + [SVM_EXIT_EXCP_BASE + NM_VECTOR] = nm_interception, + [SVM_EXIT_EXCP_BASE + MC_VECTOR] = mc_interception, ++ [SVM_EXIT_EXCP_BASE + AC_VECTOR] = ac_interception, + [SVM_EXIT_INTR] = intr_interception, + [SVM_EXIT_NMI] = nmi_interception, + [SVM_EXIT_SMI] = nop_on_interception,",1067,1398,2048 +7827,"static int setcos_set_security_env2(sc_card_t *card, + const sc_security_env_t *env, int se_num) +{ + sc_apdu_t apdu; + u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; + u8 *p; + int r, locked = 0; + + assert(card != NULL && env != NULL); + + if (card->type == SC_CARD_TYPE_SETCOS_44 || + card->type == SC_CARD_TYPE_SETCOS_NIDEL || + SETCOS_IS_EID_APPLET(card)) { + if (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) { + sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, ""symmetric keyref not supported.\n""); + return SC_ERROR_NOT_SUPPORTED; + } + if (se_num > 0) { + sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, ""restore security environment not supported.\n""); + return SC_ERROR_NOT_SUPPORTED; + } + } + + sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0, 0); + switch (env->operation) { + case SC_SEC_OPERATION_DECIPHER: + /* Should be 0x81 */ + apdu.p1 = 0x41; + apdu.p2 = 0xB8; + break; + case SC_SEC_OPERATION_SIGN: + /* Should be 0x41 */ + apdu.p1 = ((card->type == SC_CARD_TYPE_SETCOS_FINEID_V2) || + (card->type == SC_CARD_TYPE_SETCOS_FINEID_V2_2048) || + (card->type == SC_CARD_TYPE_SETCOS_44) || + (card->type == SC_CARD_TYPE_SETCOS_NIDEL) || + SETCOS_IS_EID_APPLET(card)) ? 0x41 : 0x81; + apdu.p2 = 0xB6; + break; + default: + return SC_ERROR_INVALID_ARGUMENTS; + } + apdu.le = 0; + p = sbuf; + if (env->flags & SC_SEC_ENV_ALG_REF_PRESENT) { + *p++ = 0x80; /* algorithm reference */ + *p++ = 0x01; + *p++ = env->algorithm_ref & 0xFF; + } + if (env->flags & SC_SEC_ENV_FILE_REF_PRESENT) { + *p++ = 0x81; + *p++ = env->file_ref.len; + memcpy(p, env->file_ref.value, env->file_ref.len); + p += env->file_ref.len; + } + if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT && + !(card->type == SC_CARD_TYPE_SETCOS_NIDEL || + card->type == SC_CARD_TYPE_SETCOS_FINEID_V2_2048)) { + if (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) + *p++ = 0x83; + else + *p++ = 0x84; + *p++ = env->key_ref_len; + memcpy(p, env->key_ref, env->key_ref_len); + p += env->key_ref_len; + } + r = p - sbuf; + apdu.lc = r; + apdu.datalen = r; + apdu.data = sbuf; + apdu.resplen = 0; + if (se_num > 0) { + r = sc_lock(card); + SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, ""sc_lock() failed""); + locked = 1; + } + if (apdu.datalen != 0) { + r = sc_transmit_apdu(card, &apdu); + if (r) { + sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, + ""%s: APDU transmit failed"", sc_strerror(r)); + goto err; + } + r = sc_check_sw(card, apdu.sw1, apdu.sw2); + if (r) { + sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, + ""%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(card, &apdu); + sc_unlock(card); + SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, ""APDU transmit failed""); + return sc_check_sw(card, apdu.sw1, apdu.sw2); +err: + if (locked) + sc_unlock(card); + return r; +} +",0,"static int setcos_set_security_env2(sc_card_t *card, + const sc_security_env_t *env, int se_num) +{ + sc_apdu_t apdu; + u8 sbuf[SC_MAX_APDU_BUFFER_SIZE]; + u8 *p; + int r, locked = 0; + + assert(card != NULL && env != NULL); + + if (card->type == SC_CARD_TYPE_SETCOS_44 || + card->type == SC_CARD_TYPE_SETCOS_NIDEL || + SETCOS_IS_EID_APPLET(card)) { + if (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) { + sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, ""symmetric keyref not supported.\n""); + return SC_ERROR_NOT_SUPPORTED; + } + if (se_num > 0) { + sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, ""restore security environment not supported.\n""); + return SC_ERROR_NOT_SUPPORTED; + } + } + + sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0, 0); + switch (env->operation) { + case SC_SEC_OPERATION_DECIPHER: + /* Should be 0x81 */ + apdu.p1 = 0x41; + apdu.p2 = 0xB8; + break; + case SC_SEC_OPERATION_SIGN: + /* Should be 0x41 */ + apdu.p1 = ((card->type == SC_CARD_TYPE_SETCOS_FINEID_V2) || + (card->type == SC_CARD_TYPE_SETCOS_FINEID_V2_2048) || + (card->type == SC_CARD_TYPE_SETCOS_44) || + (card->type == SC_CARD_TYPE_SETCOS_NIDEL) || + SETCOS_IS_EID_APPLET(card)) ? 0x41 : 0x81; + apdu.p2 = 0xB6; + break; + default: + return SC_ERROR_INVALID_ARGUMENTS; + } + apdu.le = 0; + p = sbuf; + if (env->flags & SC_SEC_ENV_ALG_REF_PRESENT) { + *p++ = 0x80; /* algorithm reference */ + *p++ = 0x01; + *p++ = env->algorithm_ref & 0xFF; + } + if (env->flags & SC_SEC_ENV_FILE_REF_PRESENT) { + *p++ = 0x81; + *p++ = env->file_ref.len; + memcpy(p, env->file_ref.value, env->file_ref.len); + p += env->file_ref.len; + } + if (env->flags & SC_SEC_ENV_KEY_REF_PRESENT && + !(card->type == SC_CARD_TYPE_SETCOS_NIDEL || + card->type == SC_CARD_TYPE_SETCOS_FINEID_V2_2048)) { + if (env->flags & SC_SEC_ENV_KEY_REF_SYMMETRIC) + *p++ = 0x83; + else + *p++ = 0x84; + *p++ = env->key_ref_len; + memcpy(p, env->key_ref, env->key_ref_len); + p += env->key_ref_len; + } + r = p - sbuf; + apdu.lc = r; + apdu.datalen = r; + apdu.data = sbuf; + apdu.resplen = 0; + if (se_num > 0) { + r = sc_lock(card); + SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, ""sc_lock() failed""); + locked = 1; + } + if (apdu.datalen != 0) { + r = sc_transmit_apdu(card, &apdu); + if (r) { + sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, + ""%s: APDU transmit failed"", sc_strerror(r)); + goto err; + } + r = sc_check_sw(card, apdu.sw1, apdu.sw2); + if (r) { + sc_debug(card->ctx, SC_LOG_DEBUG_NORMAL, + ""%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(card, &apdu); + sc_unlock(card); + SC_TEST_RET(card->ctx, SC_LOG_DEBUG_NORMAL, r, ""APDU transmit failed""); + return sc_check_sw(card, apdu.sw1, apdu.sw2); +err: + if (locked) + sc_unlock(card); + return r; +} +","@@ -789,6 +789,8 @@ static void parse_sec_attr_44(sc_file_t *file, const u8 *buf, size_t len) + /* Check all sub-AC definitions within the total AC */ + while (len > 1) { /* minimum length = 2 */ + int iACLen = buf[iOffset] & 0x0F; ++ if ((size_t) iACLen > len) ++ break; + + iPinCount = -1; /* default no pin required */ + iMethod = SC_AC_NONE; /* default no authentication required */ +@@ -806,7 +808,10 @@ static void parse_sec_attr_44(sc_file_t *file, const u8 *buf, size_t len) + + /* Get KeyNumber if available */ + if(iKeyLen) { +- int iSC = buf[iOffset+iACLen]; ++ int iSC; ++ if (len < 1+iACLen) ++ break; ++ iSC = buf[iOffset+iACLen]; + + switch( (iSC>>5) & 0x03 ){ + case 0: +@@ -825,11 +830,15 @@ static void parse_sec_attr_44(sc_file_t *file, const u8 *buf, size_t len) + + /* Get PinNumber if available */ + if (iACLen > (1+iParmLen+iKeyLen)) { /* check via total length if pin is present */ ++ if (len < 1+1+1+iParmLen) ++ break; + iKeyRef = buf[iOffset+1+1+iParmLen]; /* PTL + AM-header + parameter-bytes */ + iMethod = SC_AC_CHV; + } + + /* Convert SETCOS command to OpenSC command group */ ++ if (len < 1+2) ++ break; + switch(buf[iOffset+2]){ + case 0x2A: /* crypto operation */ + iOperation = SC_AC_OP_CRYPTO; +@@ -863,7 +872,10 @@ static void parse_sec_attr_44(sc_file_t *file, const u8 *buf, size_t len) + iPinCount = iACLen - 1; + + if (buf[iOffset] & 0x20) { +- int iSC = buf[iOffset + iACLen]; ++ int iSC; ++ if (len < 1 + iACLen) ++ break; ++ iSC = buf[iOffset + iACLen]; + + switch( (iSC>>5) & 0x03 ) { + case 0: +@@ -884,6 +896,8 @@ static void parse_sec_attr_44(sc_file_t *file, const u8 *buf, size_t len) + + /* Pin present ? */ + if ( iPinCount > 0 ) { ++ if (len < 1 + 2) ++ break; + iKeyRef = buf[iOffset + 2]; /* pin ref */ + iMethod = SC_AC_CHV; + }",1019,1350,2048 +18271,"double GetGPMFSampleRate(size_t handle, uint32_t fourcc, uint32_t flags) + { + mp4object *mp4 = (mp4object *)handle; + if (mp4 == NULL) return 0.0; + + GPMF_stream metadata_stream, *ms = &metadata_stream; + uint32_t teststart = 0; + uint32_t testend = mp4->indexcount; + double rate = 0.0; + + if (mp4->indexcount < 1) + return 0.0; + + if (mp4->indexcount > 3) // samples after first and before last are statistically the best, avoiding camera start up or shutdown anomollies. + { + teststart++; + testend--; + } + uint32_t *payload = GetPayload(handle, NULL, teststart); // second payload + uint32_t payloadsize = GetPayloadSize(handle, teststart); + int32_t ret = GPMF_Init(ms, payload, payloadsize); + + if (ret != GPMF_OK) + goto cleanup; + + { + uint32_t startsamples = 0; + uint32_t endsamples = 0; + uint32_t missing_samples = 0; + + while (ret == GPMF_OK && GPMF_OK != GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS)) + { + missing_samples = 1; + teststart++; + payload = GetPayload(handle, payload, teststart); // second last payload + payloadsize = GetPayloadSize(handle, teststart); + ret = GPMF_Init(ms, payload, payloadsize); + } + + if (missing_samples) + { + teststart++; //samples after sensor start are statistically the best + payload = GetPayload(handle, payload, teststart); + payloadsize = GetPayloadSize(handle, teststart); + ret = GPMF_Init(ms, payload, payloadsize); + } + if (ret == GPMF_OK) + { + uint32_t samples = GPMF_Repeat(ms); + GPMF_stream find_stream; + GPMF_CopyState(ms, &find_stream); + + if (!(flags & GPMF_SAMPLE_RATE_PRECISE) && GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL)) + { + startsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream)) - samples; + + payload = GetPayload(handle, payload, testend); // second last payload + payloadsize = GetPayloadSize(handle, testend); + ret = GPMF_Init(ms, payload, payloadsize); + if (ret != GPMF_OK) + goto cleanup; + + if (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS)) + { + GPMF_CopyState(ms, &find_stream); + if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL)) + { + endsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream)); + rate = (double)(endsamples - startsamples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount); + goto cleanup; + } + } + rate = (double)(samples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount); + } + else // for increased precision, for older GPMF streams sometimes missing the total sample count + { + uint32_t payloadpos = 0, payloadcount = 0; + double slope, top = 0.0, bot = 0.0, meanX = 0, meanY = 0; + uint32_t *repeatarray = malloc(mp4->indexcount * 4 + 4); + memset(repeatarray, 0, mp4->indexcount * 4 + 4); + + samples = 0; + + for (payloadpos = teststart; payloadpos < testend; payloadcount++, payloadpos++) + { + payload = GetPayload(handle, payload, payloadpos); // second last payload + payloadsize = GetPayloadSize(handle, payloadpos); + ret = GPMF_Init(ms, payload, payloadsize); + + if (ret != GPMF_OK) + goto cleanup; + + if (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS)) + { + GPMF_stream find_stream2; + GPMF_CopyState(ms, &find_stream2); + + if (GPMF_OK == GPMF_FindNext(&find_stream2, fourcc, GPMF_CURRENT_LEVEL)) // Count the instances, not the repeats + { + if (repeatarray) + { + float in, out; + + do + { + samples++; + } while (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_CURRENT_LEVEL)); + + repeatarray[payloadpos] = samples; + meanY += (double)samples; + + GetPayloadTime(handle, payloadpos, &in, &out); + meanX += out; + } + } + else + { + uint32_t repeat = GPMF_Repeat(ms); + samples += repeat; + + if (repeatarray) + { + float in, out; + + repeatarray[payloadpos] = samples; + meanY += (double)samples; + + GetPayloadTime(handle, payloadpos, &in, &out); + meanX += out; + } + } + } + } + if (repeatarray) + { + meanY /= (double)payloadcount; + meanX /= (double)payloadcount; + + for (payloadpos = teststart; payloadpos < testend; payloadpos++) + { + float in, out; + GetPayloadTime(handle, payloadpos, &in, &out); + + top += ((double)out - meanX)*((double)repeatarray[payloadpos] - meanY); + bot += ((double)out - meanX)*((double)out - meanX); + } + + slope = top / bot; + + #if 0 + { + double intercept; + intercept = meanY - slope*meanX; + printf(""%c%c%c%c start offset = %f (%.3fms)\n"", PRINTF_4CC(fourcc), intercept, 1000.0 * intercept / slope); + } +#endif + rate = slope; + } + else + { + rate = (double)(samples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount); + } + free(repeatarray); + + goto cleanup; + } + } + } + +cleanup: + if (payload) + { + FreePayload(payload); + payload = NULL; + } + return rate; +} +",1,"double GetGPMFSampleRate(size_t handle, uint32_t fourcc, uint32_t flags) +double GetGPMFSampleRate(size_t handle, uint32_t fourcc, uint32_t flags, double *firstsampletime, double *lastsampletime) + { + mp4object *mp4 = (mp4object *)handle; + if (mp4 == NULL) return 0.0; + + GPMF_stream metadata_stream, *ms = &metadata_stream; + uint32_t teststart = 0; + uint32_t testend = mp4->indexcount; + double rate = 0.0; + + uint32_t *payload; + uint32_t payloadsize; + int32_t ret; + + if (mp4->indexcount < 1) + return 0.0; + + payload = GetPayload(handle, NULL, teststart); + payloadsize = GetPayloadSize(handle, teststart); + ret = GPMF_Init(ms, payload, payloadsize); + + if (ret != GPMF_OK) + goto cleanup; + + { + uint64_t minimumtimestamp = 0; + uint64_t starttimestamp = 0; + uint64_t endtimestamp = 0; + uint32_t startsamples = 0; + uint32_t endsamples = 0; + double intercept = 0.0; + + + + while (teststart < mp4->indexcount && ret == GPMF_OK && GPMF_OK != GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS)) + { + teststart++; + payload = GetPayload(handle, payload, teststart); // second last payload + payloadsize = GetPayloadSize(handle, teststart); + ret = GPMF_Init(ms, payload, payloadsize); + } + + if (ret == GPMF_OK && payload) + { + uint32_t samples = GPMF_PayloadSampleCount(ms); + GPMF_stream find_stream; + GPMF_CopyState(ms, &find_stream); + if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL)) + startsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream)) - samples; + + GPMF_CopyState(ms, &find_stream); + if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TIME_STAMP, GPMF_CURRENT_LEVEL)) + starttimestamp = BYTESWAP64(*(uint64_t *)GPMF_RawData(&find_stream)); + + if (starttimestamp) // is this earliest in the payload, examine the other streams in this early payload. + { + GPMF_stream any_stream; + GPMF_Init(&any_stream, payload, payloadsize); + + minimumtimestamp = starttimestamp; + while (GPMF_OK == GPMF_FindNext(&any_stream, GPMF_KEY_TIME_STAMP, GPMF_RECURSE_LEVELS)) + { + uint64_t timestamp = BYTESWAP64(*(uint64_t *)GPMF_RawData(&any_stream)); + if (timestamp < minimumtimestamp) + minimumtimestamp = timestamp; + } + } + + testend = mp4->indexcount; + do + { + testend--;// last payload with the fourcc needed + payload = GetPayload(handle, payload, testend); + payloadsize = GetPayloadSize(handle, testend); + ret = GPMF_Init(ms, payload, payloadsize); + } while (testend > 0 && GPMF_OK != GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS)); + + GPMF_CopyState(ms, &find_stream); + if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL)) + endsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream)); + else // If there is no TSMP we have to count the samples. + { + uint32_t i; + for (i = teststart; i <= testend; i++) + { + payload = GetPayload(handle,payload, i); // second last payload + payloadsize = GetPayloadSize(handle, i); + if (GPMF_OK == GPMF_Init(ms, payload, payloadsize)) + if (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS)) + endsamples += GPMF_PayloadSampleCount(ms); + } + } + + if (starttimestamp != 0) + { + uint32_t last_samples = GPMF_PayloadSampleCount(ms); + uint32_t totaltimestamped_samples = endsamples - last_samples - startsamples; + double time_stamp_scale = 1000000000.0; // scan for nanoseconds, microseconds to seconds, all base 10. + + GPMF_CopyState(ms, &find_stream); + if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TIME_STAMP, GPMF_CURRENT_LEVEL)) + endtimestamp = BYTESWAP64(*(uint64_t *)GPMF_RawData(&find_stream)); + + if (endtimestamp) + { + double approxrate = 0.0; + if (endsamples > startsamples) + approxrate = (double)(endsamples - startsamples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount); + + if (approxrate == 0.0) + approxrate = (double)(samples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount); + + + while (time_stamp_scale >= 1) + { + rate = (double)(totaltimestamped_samples) / ((double)(endtimestamp - starttimestamp) / time_stamp_scale); + if (rate*0.9 < approxrate && approxrate < rate*1.1) + break; + + time_stamp_scale *= 0.1; + } + if (time_stamp_scale < 1.0) rate = 0.0; + intercept = (((double)minimumtimestamp - (double)starttimestamp) / time_stamp_scale) * rate; + } + } + + if (rate == 0.0) //Timestamps didn't help weren't available + { + if (!(flags & GPMF_SAMPLE_RATE_PRECISE)) + { + if (endsamples > startsamples) + rate = (double)(endsamples - startsamples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount); + + if (rate == 0.0) + rate = (double)(samples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount); + + double in, out; + if (GPMF_OK == GetPayloadTime(handle, teststart, &in, &out)) + intercept = (double)-in * rate; + } + else // for increased precision, for older GPMF streams sometimes missing the total sample count + { + uint32_t payloadpos = 0, payloadcount = 0; + double slope, top = 0.0, bot = 0.0, meanX = 0, meanY = 0; + uint32_t *repeatarray = malloc(mp4->indexcount * 4 + 4); + memset(repeatarray, 0, mp4->indexcount * 4 + 4); + + samples = 0; + + for (payloadpos = teststart; payloadpos <= testend; payloadpos++) + { + payload = GetPayload(handle, payload, payloadpos); // second last payload + payloadsize = GetPayloadSize(handle, payloadpos); + ret = GPMF_Init(ms, payload, payloadsize); + + if (ret != GPMF_OK) + goto cleanup; + + if (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS)) + { + GPMF_stream find_stream2; + GPMF_CopyState(ms, &find_stream2); + + payloadcount++; + + if (GPMF_OK == GPMF_FindNext(&find_stream2, fourcc, GPMF_CURRENT_LEVEL)) // Count the instances, not the repeats + { + if (repeatarray) + { + double in, out; + + do + { + samples++; + } while (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_CURRENT_LEVEL)); + + repeatarray[payloadpos] = samples; + meanY += (double)samples; + + if (GPMF_OK == GetPayloadTime(handle, payloadpos, &in, &out)) + meanX += out; + } + } + else + { + uint32_t repeat = GPMF_PayloadSampleCount(ms); + samples += repeat; + + if (repeatarray) + { + double in, out; + + repeatarray[payloadpos] = samples; + meanY += (double)samples; + + if (GPMF_OK == GetPayloadTime(handle, payloadpos, &in, &out)) + meanX += out; + } + } + } + else + { + repeatarray[payloadpos] = 0; + } + } + + // Compute the line of best fit for a jitter removed sample rate. + // This does assume an unchanging clock, even though the IMU data can thermally impacted causing small clock changes. + // TODO: Next enhancement would be a low order polynominal fit the compensate for any thermal clock drift. + if (repeatarray) + { + meanY /= (double)payloadcount; + meanX /= (double)payloadcount; + + for (payloadpos = teststart; payloadpos <= testend; payloadpos++) + { + double in, out; + if (repeatarray[payloadpos] && GPMF_OK == GetPayloadTime(handle, payloadpos, &in, &out)) + { + top += ((double)out - meanX)*((double)repeatarray[payloadpos] - meanY); + bot += ((double)out - meanX)*((double)out - meanX); + } + } + + slope = top / bot; + rate = slope; + + // This sample code might be useful for compare data latency between channels. + intercept = meanY - slope * meanX; + #if 0 + printf(""%c%c%c%c start offset = %f (%.3fms) rate = %f\n"", PRINTF_4CC(fourcc), intercept, 1000.0 * intercept / slope, rate); + printf(""%c%c%c%c first sample at time %.3fms\n"", PRINTF_4CC(fourcc), -1000.0 * intercept / slope); +#endif + } + else + { + rate = (double)(samples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount); + } + + free(repeatarray); + } + } + +","@@ -2,15 +2,14 @@ + * + * @brief Way Too Crude MP4|MOV reader + * +-* @version 1.2.1 ++* @version 1.3.1 + * +-* (C) Copyright 2017 GoPro Inc (http://gopro.com/). ++* (C) Copyright 2017-2019 GoPro Inc (http://gopro.com/). + * +-* Licensed under the Apache License, Version 2.0 (the ""License""); +-* you may not use this file except in compliance with the License. +-* You may obtain a copy of the License at +-* +-* http://www.apache.org/licenses/LICENSE-2.0 ++* Licensed under either: ++* - Apache License, Version 2.0, http://www.apache.org/licenses/LICENSE-2.0 ++* - MIT license, http://opensource.org/licenses/MIT ++* at your option. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an ""AS IS"" BASIS, +@@ -20,21 +19,24 @@ + * + */ + +-/* This is not an elegant MP4 parser, only used to help demonstrate extraction of MP4 */ +- ++/* This is not an elegant MP4 parser, only used to help demonstrate extraction of GPMF */ + + #include + #include + #include + #include ++#include ++#include ++ + #include ""GPMF_mp4reader.h"" + + #define PRINT_MP4_STRUCTURE 0 + + #ifdef WIN32 +-#define LONGSEEK _fseeki64 ++#define LONGSEEK _fseeki64 ++#define stat64 _stat64 + #else +-#define LONGSEEK fseeko ++#define LONGSEEK fseeko + #endif + + +@@ -50,7 +52,6 @@ uint32_t GetNumberPayloads(size_t handle) + return 0; + } + +- + uint32_t *GetPayload(size_t handle, uint32_t *lastpayload, uint32_t index) + { + mp4object *mp4 = (mp4object *)handle; +@@ -63,31 +64,35 @@ uint32_t *GetPayload(size_t handle, uint32_t *lastpayload, uint32_t index) + + if (MP4buffer) + { +- LONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET); +- fread(MP4buffer, 1, mp4->metasizes[index], mp4->mediafp); +- return MP4buffer; ++ if (mp4->filesize > mp4->metaoffsets[index]+mp4->metasizes[index]) ++ { ++ LONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET); ++ fread(MP4buffer, 1, mp4->metasizes[index], mp4->mediafp); ++ mp4->filepos = mp4->metaoffsets[index] + mp4->metasizes[index]; ++ return MP4buffer; ++ } + } + } + return NULL; + } + + +-void SavePayload(size_t handle, uint32_t *payload, uint32_t index) ++void LongSeek(mp4object *mp4, int64_t offset) + { +- mp4object *mp4 = (mp4object *)handle; +- if (mp4 == NULL) return; +- +- uint32_t *MP4buffer = NULL; +- if (index < mp4->indexcount && mp4->mediafp && payload) ++ if (mp4 && offset) + { +- LONGSEEK(mp4->mediafp, mp4->metaoffsets[index], SEEK_SET); +- fwrite(payload, 1, mp4->metasizes[index], mp4->mediafp); ++ if (mp4->filepos + offset < mp4->filesize) ++ { ++ LONGSEEK(mp4->mediafp, offset, SEEK_CUR); ++ mp4->filepos += offset; ++ } ++ else ++ { ++ mp4->filepos = mp4->filesize; ++ } + } +- return; + } + +- +- + void FreePayload(uint32_t *lastpayload) + { + if (lastpayload) +@@ -106,6 +111,7 @@ uint32_t GetPayloadSize(size_t handle, uint32_t index) + return 0; + } + ++ + #define MAX_NEST_LEVEL 20 + + size_t OpenMP4Source(char *filename, uint32_t traktype, uint32_t traksubtype) //RAW or within MP4 +@@ -115,6 +121,12 @@ size_t OpenMP4Source(char *filename, uint32_t traktype, uint32_t traksubtype) / + + memset(mp4, 0, sizeof(mp4object)); + ++ struct stat64 mp4stat; ++ stat64(filename, &mp4stat); ++ mp4->filesize = mp4stat.st_size; ++ ++ if (mp4->filesize < 64) return 0; ++ + #ifdef _WINDOWS + fopen_s(&mp4->mediafp, filename, ""rb""); + #else +@@ -129,25 +141,27 @@ size_t OpenMP4Source(char *filename, uint32_t traktype, uint32_t traksubtype) / + uint64_t nestsize[MAX_NEST_LEVEL] = { 0 }; + uint64_t lastsize = 0, qtsize; + ++ + do + { + len = fread(&qtsize32, 1, 4, mp4->mediafp); + len += fread(&qttag, 1, 4, mp4->mediafp); +- if (len == 8) ++ mp4->filepos += len; ++ if (len == 8 && mp4->filepos < mp4->filesize) + { + if (!VALID_FOURCC(qttag)) + { +- LONGSEEK(mp4->mediafp, lastsize - 8 - 8, SEEK_CUR); +- +- NESTSIZE(lastsize - 8); +- continue; ++ CloseSource((size_t)mp4); ++ mp4 = NULL; ++ break; + } + + qtsize32 = BYTESWAP32(qtsize32); + + if (qtsize32 == 1) // 64-bit Atom + { +- fread(&qtsize, 1, 8, mp4->mediafp); ++ len = fread(&qtsize, 1, 8, mp4->mediafp); ++ mp4->filepos += len; + qtsize = BYTESWAP64(qtsize) - 8; + } + else +@@ -168,9 +182,10 @@ size_t OpenMP4Source(char *filename, uint32_t traktype, uint32_t traksubtype) / + + if (qttag == MAKEID('m', 'd', 'a', 't') || + qttag == MAKEID('f', 't', 'y', 'p') || +- qttag == MAKEID('u', 'd', 't', 'a')) ++ qttag == MAKEID('u', 'd', 't', 'a') || ++ qttag == MAKEID('f', 'r', 'e', 'e')) + { +- LONGSEEK(mediafp, qtsize - 8, SEEK_CUR); ++ LongSeek(mp4, qtsize - 8); + + NESTSIZE(qtsize); + +@@ -187,8 +202,6 @@ size_t OpenMP4Source(char *filename, uint32_t traktype, uint32_t traksubtype) / + qttag != MAKEID('d', 'i', 'n', 'f') && + qttag != MAKEID('a', 'l', 'i', 's') && + qttag != MAKEID('s', 't', 's', 'd') && +- qttag != MAKEID('a', 'l', 'i', 's') && +- qttag != MAKEID('a', 'l', 'i', 's') && + qttag != MAKEID('s', 't', 'b', 'l') && + qttag != MAKEID('s', 't', 't', 's') && + qttag != MAKEID('s', 't', 's', 'c') && +@@ -197,7 +210,7 @@ size_t OpenMP4Source(char *filename, uint32_t traktype, uint32_t traksubtype) / + qttag != MAKEID('c', 'o', '6', '4') && + qttag != MAKEID('h', 'd', 'l', 'r')) + { +- LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR); ++ LongSeek(mp4, qtsize - 8); + + NESTSIZE(qtsize); + } +@@ -210,7 +223,9 @@ size_t OpenMP4Source(char *filename, uint32_t traktype, uint32_t traksubtype) / + len += fread(&skip, 1, 4, mp4->mediafp); + len += fread(&mp4->clockdemon, 1, 4, mp4->mediafp); mp4->clockdemon = BYTESWAP32(mp4->clockdemon); + len += fread(&mp4->clockcount, 1, 4, mp4->mediafp); mp4->clockcount = BYTESWAP32(mp4->clockcount); +- LONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over mvhd ++ ++ mp4->filepos += len; ++ LongSeek(mp4, qtsize - 8 - len); // skip over mvhd + + NESTSIZE(qtsize); + } +@@ -233,7 +248,9 @@ size_t OpenMP4Source(char *filename, uint32_t traktype, uint32_t traksubtype) / + mp4->videolength = (float)((double)mp4->trak_clockcount / (double)mp4->trak_clockdemon); + } + } +- LONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over mvhd ++ ++ mp4->filepos += len; ++ LongSeek(mp4, qtsize - 8 - len); // skip over mvhd + + NESTSIZE(qtsize); + } +@@ -244,10 +261,11 @@ size_t OpenMP4Source(char *filename, uint32_t traktype, uint32_t traksubtype) / + len += fread(&skip, 1, 4, mp4->mediafp); + len += fread(&temp, 1, 4, mp4->mediafp); // type will be 'meta' for the correct trak. + +- if (temp != MAKEID('a', 'l', 'i', 's')) ++ if (temp != MAKEID('a', 'l', 'i', 's') && temp != MAKEID('u', 'r', 'l', ' ')) + type = temp; + +- LONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over hldr ++ mp4->filepos += len; ++ LongSeek(mp4, qtsize - 8 - len); // skip over hldr + + NESTSIZE(qtsize); + +@@ -267,10 +285,11 @@ size_t OpenMP4Source(char *filename, uint32_t traktype, uint32_t traksubtype) / + type = 0; // MP4 + } + } +- LONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over stsd ++ mp4->filepos += len; ++ LongSeek(mp4, qtsize - 8 - len); // skip over stsd + } + else +- LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR); ++ LongSeek(mp4, qtsize - 8); + + NESTSIZE(qtsize); + } +@@ -286,32 +305,35 @@ size_t OpenMP4Source(char *filename, uint32_t traktype, uint32_t traksubtype) / + { + mp4->metastsc_count = num; + if (mp4->metastsc) free(mp4->metastsc); +- mp4->metastsc = (SampleToChunk *)malloc(num * 12); +- if (mp4->metastsc) ++ if (num > 0) + { +- uint32_t total_stsc = num; +- len += fread(mp4->metastsc, 1, num * sizeof(SampleToChunk), mp4->mediafp); +- +- do ++ mp4->metastsc = (SampleToChunk *)malloc(num * sizeof(SampleToChunk)); ++ if (mp4->metastsc) + { +- num--; +- mp4->metastsc[num].chunk_num = BYTESWAP32(mp4->metastsc[num].chunk_num); +- mp4->metastsc[num].samples = BYTESWAP32(mp4->metastsc[num].samples); +- mp4->metastsc[num].id = BYTESWAP32(mp4->metastsc[num].id); +- } while (num > 0); +- } ++ len += fread(mp4->metastsc, 1, num * sizeof(SampleToChunk), mp4->mediafp); + +- if (mp4->metastsc_count == 1 && mp4->metastsc[0].samples == 1) // Simplify if the stsc is not reporting any grouped chunks. ++ do ++ { ++ num--; ++ mp4->metastsc[num].chunk_num = BYTESWAP32(mp4->metastsc[num].chunk_num); ++ mp4->metastsc[num].samples = BYTESWAP32(mp4->metastsc[num].samples); ++ mp4->metastsc[num].id = BYTESWAP32(mp4->metastsc[num].id); ++ } while (num > 0); ++ } ++ } ++ else + { +- if (mp4->metastsc) free(mp4->metastsc); +- mp4->metastsc = NULL; +- mp4->metastsc_count = 0; ++ //size of null ++ CloseSource((size_t)mp4); ++ mp4 = NULL; ++ break; + } + } +- LONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over stsx ++ mp4->filepos += len; ++ LongSeek(mp4, qtsize - 8 - len); // skip over stsx + } + else +- LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR); ++ LongSeek(mp4, qtsize - 8); + + NESTSIZE(qtsize); + } +@@ -330,33 +352,44 @@ size_t OpenMP4Source(char *filename, uint32_t traktype, uint32_t traksubtype) / + { + mp4->metasize_count = num; + if (mp4->metasizes) free(mp4->metasizes); +- mp4->metasizes = (uint32_t *)malloc(num * 4); +- if (mp4->metasizes) ++ if(num > 0) + { +- if (equalsamplesize == 0) ++ mp4->metasizes = (uint32_t *)malloc(num * 4); ++ if (mp4->metasizes) + { +- len += fread(mp4->metasizes, 1, num * 4, mp4->mediafp); +- do ++ if (equalsamplesize == 0) + { +- num--; +- mp4->metasizes[num] = BYTESWAP32(mp4->metasizes[num]); +- } while (num > 0); +- } +- else +- { +- equalsamplesize = BYTESWAP32(equalsamplesize); +- do ++ len += fread(mp4->metasizes, 1, num * 4, mp4->mediafp); ++ do ++ { ++ num--; ++ mp4->metasizes[num] = BYTESWAP32(mp4->metasizes[num]); ++ } while (num > 0); ++ } ++ else + { +- num--; +- mp4->metasizes[num] = equalsamplesize; +- } while (num > 0); ++ equalsamplesize = BYTESWAP32(equalsamplesize); ++ do ++ { ++ num--; ++ mp4->metasizes[num] = equalsamplesize; ++ } while (num > 0); ++ } + } + } ++ else ++ { ++ //size of null ++ CloseSource((size_t)mp4); ++ mp4 = NULL; ++ break; ++ } + } +- LONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over stsz ++ mp4->filepos += len; ++ LongSeek(mp4, qtsize - 8 - len); // skip over stsz + } + else +- LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR); ++ LongSeek(mp4, qtsize - 8); + + NESTSIZE(qtsize); + } +@@ -369,93 +402,121 @@ size_t OpenMP4Source(char *filename, uint32_t traktype, uint32_t traksubtype) / + num = BYTESWAP32(num); + if (num * 4 <= qtsize - 8 - len) + { ++ uint32_t metastco_count = num; ++ + if (mp4->metastsc_count > 0 && num != mp4->metasize_count) + { +- mp4->indexcount = mp4->metasize_count; ++ mp4->indexcount = num; + if (mp4->metaoffsets) free(mp4->metaoffsets); +- mp4->metaoffsets = (uint64_t *)malloc(mp4->metasize_count * 8); +- if (mp4->metaoffsets) ++ if(num > 0) + { +- uint32_t *metaoffsets32 = NULL; +- metaoffsets32 = (uint32_t *)malloc(num * 4); +- if (metaoffsets32) ++ mp4->metaoffsets = (uint64_t *)malloc(num * 8); ++ if (mp4->metaoffsets) + { +- uint64_t fileoffset = 0; +- int stsc_pos = 0; +- int stco_pos = 0; +- int repeat = 1; +- len += fread(metaoffsets32, 1, num * 4, mp4->mediafp); +- do +- { +- num--; +- metaoffsets32[num] = BYTESWAP32(metaoffsets32[num]); +- } while (num > 0); +- +- mp4->metaoffsets[0] = fileoffset = metaoffsets32[stco_pos]; +- num = 1; +- while (num < mp4->metasize_count) ++ uint32_t *metaoffsets32 = NULL; ++ metaoffsets32 = (uint32_t *)malloc(num * 4); ++ if (metaoffsets32) + { +- if (stsc_pos + 1 < (int)mp4->metastsc_count && num == stsc_pos) ++ uint64_t fileoffset = 0; ++ int stsc_pos = 0; ++ int stco_pos = 0; ++ int repeat = 1; ++ len += fread(metaoffsets32, 1, num * 4, mp4->mediafp); ++ do + { +- stco_pos++; stsc_pos++; +- fileoffset = (uint64_t)metaoffsets32[stco_pos]; +- repeat = 1; +- } +- else if (repeat == mp4->metastsc[stsc_pos].samples) +- { +- stco_pos++; +- fileoffset = (uint64_t)metaoffsets32[stco_pos]; +- repeat = 1; +- } +- else ++ num--; ++ metaoffsets32[num] = BYTESWAP32(metaoffsets32[num]); ++ } while (num > 0); ++ ++ mp4->metaoffsets[0] = fileoffset = metaoffsets32[stco_pos]; ++ num = 1; ++ while (num < mp4->indexcount) + { +- fileoffset += (uint64_t)mp4->metasizes[num - 1]; +- repeat++; ++ if ((uint32_t)repeat == mp4->metastsc[stsc_pos].samples) ++ { ++ if ((uint32_t)stco_pos + 1 < metastco_count) ++ { ++ stco_pos++; ++ fileoffset = (uint64_t)metaoffsets32[stco_pos]; ++ } ++ else ++ { ++ fileoffset += (uint64_t)mp4->metasizes[num - 1]; ++ } ++ if ((uint32_t)stsc_pos + 1 < mp4->metastsc_count) ++ if (mp4->metastsc[stsc_pos + 1].chunk_num == (uint32_t)stco_pos + 1) ++ stsc_pos++; ++ ++ repeat = 1; ++ } ++ else ++ { ++ fileoffset += (uint64_t)mp4->metasizes[num - 1]; ++ repeat++; ++ } ++ ++ mp4->metaoffsets[num] = fileoffset; ++ //int delta = metaoffsets[num] - metaoffsets[num - 1]; ++ //printf(""%3d:%08x, delta = %08x\n"", num, (int)fileoffset, delta); ++ ++ num++; + } + +- mp4->metaoffsets[num] = fileoffset; +- //int delta = metaoffsets[num] - metaoffsets[num - 1]; +- //printf(""%3d:%08x, delta = %08x\n"", num, (int)fileoffset, delta); ++ if (mp4->metastsc) free(mp4->metastsc); ++ mp4->metastsc = NULL; ++ mp4->metastsc_count = 0; + +- num++; ++ free(metaoffsets32); + } +- +- if (mp4->metastsc) free(mp4->metastsc); +- mp4->metastsc = NULL; +- mp4->metastsc_count = 0; +- +- free(metaoffsets32); + } + } ++ else ++ { ++ //size of null ++ CloseSource((size_t)mp4); ++ mp4 = NULL; ++ break; ++ } + } + else + { + mp4->indexcount = num; + if (mp4->metaoffsets) free(mp4->metaoffsets); +- mp4->metaoffsets = (uint64_t *)malloc(num * 8); +- if (mp4->metaoffsets) ++ if (num > 0) + { +- uint32_t *metaoffsets32 = NULL; +- metaoffsets32 = (uint32_t *)malloc(num * 4); +- if (metaoffsets32) ++ mp4->metaoffsets = (uint64_t *)malloc(num * 8); ++ if (mp4->metaoffsets) + { +- size_t readlen = fread(metaoffsets32, 1, num * 4, mp4->mediafp); +- len += readlen; +- do ++ uint32_t *metaoffsets32 = NULL; ++ metaoffsets32 = (uint32_t *)malloc(num * 4); ++ if (metaoffsets32) + { +- num--; +- mp4->metaoffsets[num] = BYTESWAP32(metaoffsets32[num]); +- } while (num > 0); ++ size_t readlen = fread(metaoffsets32, 1, num * 4, mp4->mediafp); ++ len += readlen; ++ do ++ { ++ num--; ++ mp4->metaoffsets[num] = BYTESWAP32(metaoffsets32[num]); ++ } while (num > 0); + +- free(metaoffsets32); ++ free(metaoffsets32); ++ } + } + } ++ else ++ { ++ //size of null ++ CloseSource((size_t)mp4); ++ mp4 = NULL; ++ break; ++ } + } + } +- LONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over stco ++ mp4->filepos += len; ++ LongSeek(mp4, qtsize - 8 - len); // skip over stco + } + else +- LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR); ++ LongSeek(mp4, qtsize - 8); + + NESTSIZE(qtsize); + } +@@ -467,60 +528,79 @@ size_t OpenMP4Source(char *filename, uint32_t traktype, uint32_t traksubtype) / + len = fread(&skip, 1, 4, mp4->mediafp); + len += fread(&num, 1, 4, mp4->mediafp); + num = BYTESWAP32(num); ++ ++ if(num == 0) ++ { ++ //size of null ++ CloseSource((size_t)mp4); ++ mp4 = NULL; ++ break; ++ } ++ + if (num * 8 <= qtsize - 8 - len) + { + if (mp4->metastsc_count > 0 && num != mp4->metasize_count) + { + mp4->indexcount = mp4->metasize_count; + if (mp4->metaoffsets) free(mp4->metaoffsets); +- mp4->metaoffsets = (uint64_t *)malloc(mp4->metasize_count * 8); +- if (mp4->metaoffsets) ++ if (mp4->metasize_count) + { +- uint64_t *metaoffsets64 = NULL; +- metaoffsets64 = (uint64_t *)malloc(num * 8); +- if (metaoffsets64) ++ mp4->metaoffsets = (uint64_t *)malloc(mp4->metasize_count * 8); ++ if (mp4->metaoffsets) + { +- uint64_t fileoffset = 0; +- int stsc_pos = 0; +- int stco_pos = 0; +- len += fread(metaoffsets64, 1, num * 8, mp4->mediafp); +- do ++ uint64_t *metaoffsets64 = NULL; ++ metaoffsets64 = (uint64_t *)malloc(num * 8); ++ if (metaoffsets64) + { +- num--; +- metaoffsets64[num] = BYTESWAP64(metaoffsets64[num]); +- } while (num > 0); ++ uint64_t fileoffset = 0; ++ int stsc_pos = 0; ++ int stco_pos = 0; ++ len += fread(metaoffsets64, 1, num * 8, mp4->mediafp); ++ do ++ { ++ num--; ++ metaoffsets64[num] = BYTESWAP64(metaoffsets64[num]); ++ } while (num > 0); + +- fileoffset = metaoffsets64[0]; +- mp4->metaoffsets[0] = fileoffset; +- //printf(""%3d:%08x, delta = %08x\n"", 0, (int)fileoffset, 0); ++ fileoffset = metaoffsets64[0]; ++ mp4->metaoffsets[0] = fileoffset; ++ //printf(""%3d:%08x, delta = %08x\n"", 0, (int)fileoffset, 0); + +- num = 1; +- while (num < mp4->metasize_count) +- { +- if (num != mp4->metastsc[stsc_pos].chunk_num - 1 && 0 == (num - (mp4->metastsc[stsc_pos].chunk_num - 1)) % mp4->metastsc[stsc_pos].samples) +- { +- stco_pos++; +- fileoffset = (uint64_t)metaoffsets64[stco_pos]; +- } +- else ++ num = 1; ++ while (num < mp4->metasize_count) + { +- fileoffset += (uint64_t)mp4->metasizes[num - 1]; ++ if (num != mp4->metastsc[stsc_pos].chunk_num - 1 && 0 == (num - (mp4->metastsc[stsc_pos].chunk_num - 1)) % mp4->metastsc[stsc_pos].samples) ++ { ++ stco_pos++; ++ fileoffset = (uint64_t)metaoffsets64[stco_pos]; ++ } ++ else ++ { ++ fileoffset += (uint64_t)mp4->metasizes[num - 1]; ++ } ++ ++ mp4->metaoffsets[num] = fileoffset; ++ //int delta = metaoffsets[num] - metaoffsets[num - 1]; ++ //printf(""%3d:%08x, delta = %08x\n"", num, (int)fileoffset, delta); ++ ++ num++; + } + +- mp4->metaoffsets[num] = fileoffset; +- //int delta = metaoffsets[num] - metaoffsets[num - 1]; +- //printf(""%3d:%08x, delta = %08x\n"", num, (int)fileoffset, delta); ++ if (mp4->metastsc) free(mp4->metastsc); ++ mp4->metastsc = NULL; ++ mp4->metastsc_count = 0; + +- num++; ++ free(metaoffsets64); + } +- +- if (mp4->metastsc) free(mp4->metastsc); +- mp4->metastsc = NULL; +- mp4->metastsc_count = 0; +- +- free(metaoffsets64); + } + } ++ else ++ { ++ //size of null ++ CloseSource((size_t)mp4); ++ mp4 = NULL; ++ break; ++ } + } + else + { +@@ -538,10 +618,11 @@ size_t OpenMP4Source(char *filename, uint32_t traktype, uint32_t traksubtype) / + } + } + } +- LONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over stco ++ mp4->filepos += len; ++ LongSeek(mp4, qtsize - 8 - len); // skip over stco + } + else +- LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR); ++ LongSeek(mp4, qtsize - 8); + + NESTSIZE(qtsize); + } +@@ -578,10 +659,11 @@ size_t OpenMP4Source(char *filename, uint32_t traktype, uint32_t traksubtype) / + } + mp4->basemetadataduration = mp4->metadatalength * (double)mp4->meta_clockdemon / (double)samples; + } +- LONGSEEK(mp4->mediafp, qtsize - 8 - len, SEEK_CUR); // skip over stco ++ mp4->filepos += len; ++ LongSeek(mp4, qtsize - 8 - len); // skip over stco + } + else +- LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR); ++ LongSeek(mp4, qtsize - 8); + + NESTSIZE(qtsize); + } +@@ -595,6 +677,15 @@ size_t OpenMP4Source(char *filename, uint32_t traktype, uint32_t traksubtype) / + break; + } + } while (len > 0); ++ ++ if (mp4) ++ { ++ if (mp4->metasizes == NULL || mp4->metaoffsets == NULL) ++ { ++ CloseSource((size_t)mp4); ++ mp4 = NULL; ++ } ++ } + } + else + { +@@ -631,20 +722,32 @@ void CloseSource(size_t handle) + } + + +-uint32_t GetPayloadTime(size_t handle, uint32_t index, float *in, float *out) ++uint32_t GetPayloadTime(size_t handle, uint32_t index, double *in, double *out) + { + mp4object *mp4 = (mp4object *)handle; +- if (mp4 == NULL) return 0; ++ if (mp4 == NULL) return GPMF_ERROR_MEMORY; + +- if (mp4->metaoffsets == 0 || mp4->basemetadataduration == 0 || mp4->meta_clockdemon == 0 || in == NULL || out == NULL) return 1; ++ if (mp4->metaoffsets == 0 || mp4->basemetadataduration == 0 || mp4->meta_clockdemon == 0 || in == NULL || out == NULL) return GPMF_ERROR_MEMORY; + +- *in = (float)((double)index * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon); +- *out = (float)((double)(index + 1) * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon); +- return 0; ++ *in = ((double)index * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon); ++ *out = ((double)(index + 1) * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon); ++ return GPMF_OK; + } + + +- ++uint32_t GetPayloadRationalTime(size_t handle, uint32_t index, uint32_t *in_numerator, uint32_t *out_numerator, uint32_t *denominator) ++{ ++ mp4object *mp4 = (mp4object *)handle; ++ if (mp4 == NULL) return GPMF_ERROR_MEMORY; ++ ++ if (mp4->metaoffsets == 0 || mp4->basemetadataduration == 0 || mp4->meta_clockdemon == 0 || in_numerator == NULL || out_numerator == NULL) return GPMF_ERROR_MEMORY; ++ ++ *in_numerator = (uint32_t)(index * mp4->basemetadataduration); ++ *out_numerator = (uint32_t)((index + 1) * mp4->basemetadataduration); ++ *denominator = (uint32_t)mp4->meta_clockdemon; ++ ++ return GPMF_OK; ++} + + size_t OpenMP4SourceUDTA(char *filename) + { +@@ -661,7 +764,8 @@ size_t OpenMP4SourceUDTA(char *filename) + + if (mp4->mediafp) + { +- uint32_t qttag, qtsize32, len; ++ uint32_t qttag, qtsize32; ++ size_t len; + int32_t nest = 0; + uint64_t nestsize[MAX_NEST_LEVEL] = { 0 }; + uint64_t lastsize = 0, qtsize; +@@ -674,7 +778,7 @@ size_t OpenMP4SourceUDTA(char *filename) + { + if (!GPMF_VALID_FOURCC(qttag)) + { +- LONGSEEK(mp4->mediafp, lastsize - 8 - 8, SEEK_CUR); ++ LongSeek(mp4, lastsize - 8 - 8); + + NESTSIZE(lastsize - 8); + continue; +@@ -701,7 +805,7 @@ size_t OpenMP4SourceUDTA(char *filename) + if (qttag == MAKEID('m', 'd', 'a', 't') || + qttag == MAKEID('f', 't', 'y', 'p')) + { +- LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR); ++ LongSeek(mp4, qtsize - 8); + NESTSIZE(qtsize); + continue; + } +@@ -725,7 +829,7 @@ size_t OpenMP4SourceUDTA(char *filename) + if (qttag != MAKEID('m', 'o', 'o', 'v') && //skip over all but these atoms + qttag != MAKEID('u', 'd', 't', 'a')) + { +- LONGSEEK(mp4->mediafp, qtsize - 8, SEEK_CUR); ++ LongSeek(mp4, qtsize - 8); + NESTSIZE(qtsize); + continue; + } +@@ -740,7 +844,7 @@ size_t OpenMP4SourceUDTA(char *filename) + } + + +-double GetGPMFSampleRate(size_t handle, uint32_t fourcc, uint32_t flags) ++double GetGPMFSampleRate(size_t handle, uint32_t fourcc, uint32_t flags, double *firstsampletime, double *lastsampletime) + { + mp4object *mp4 = (mp4object *)handle; + if (mp4 == NULL) return 0.0; +@@ -750,221 +854,278 @@ double GetGPMFSampleRate(size_t handle, uint32_t fourcc, uint32_t flags) + uint32_t testend = mp4->indexcount; + double rate = 0.0; + ++ uint32_t *payload; ++ uint32_t payloadsize; ++ int32_t ret; ++ + if (mp4->indexcount < 1) + return 0.0; + +- if (mp4->indexcount > 3) // samples after first and before last are statistically the best, avoiding camera start up or shutdown anomollies. +- { +- teststart++; +- testend--; +- } +- +- uint32_t *payload = GetPayload(handle, NULL, teststart); // second payload +- uint32_t payloadsize = GetPayloadSize(handle, teststart); +- int32_t ret = GPMF_Init(ms, payload, payloadsize); ++ payload = GetPayload(handle, NULL, teststart); ++ payloadsize = GetPayloadSize(handle, teststart); ++ ret = GPMF_Init(ms, payload, payloadsize); + + if (ret != GPMF_OK) + goto cleanup; + + { ++ uint64_t minimumtimestamp = 0; ++ uint64_t starttimestamp = 0; ++ uint64_t endtimestamp = 0; + uint32_t startsamples = 0; + uint32_t endsamples = 0; +- uint32_t missing_samples = 0; ++ double intercept = 0.0; ++ ++ + +- while (ret == GPMF_OK && GPMF_OK != GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS)) ++ while (teststart < mp4->indexcount && ret == GPMF_OK && GPMF_OK != GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS)) + { +- missing_samples = 1; + teststart++; + payload = GetPayload(handle, payload, teststart); // second last payload + payloadsize = GetPayloadSize(handle, teststart); + ret = GPMF_Init(ms, payload, payloadsize); + } + +- if (missing_samples) +- { +- teststart++; //samples after sensor start are statistically the best +- payload = GetPayload(handle, payload, teststart); +- payloadsize = GetPayloadSize(handle, teststart); +- ret = GPMF_Init(ms, payload, payloadsize); +- } +- +- if (ret == GPMF_OK) ++ if (ret == GPMF_OK && payload) + { +- uint32_t samples = GPMF_Repeat(ms); ++ uint32_t samples = GPMF_PayloadSampleCount(ms); + GPMF_stream find_stream; + GPMF_CopyState(ms, &find_stream); ++ if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL)) ++ startsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream)) - samples; + +- if (!(flags & GPMF_SAMPLE_RATE_PRECISE) && GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL)) ++ GPMF_CopyState(ms, &find_stream); ++ if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TIME_STAMP, GPMF_CURRENT_LEVEL)) ++ starttimestamp = BYTESWAP64(*(uint64_t *)GPMF_RawData(&find_stream)); ++ ++ if (starttimestamp) // is this earliest in the payload, examine the other streams in this early payload. + { +- startsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream)) - samples; ++ GPMF_stream any_stream; ++ GPMF_Init(&any_stream, payload, payloadsize); ++ ++ minimumtimestamp = starttimestamp; ++ while (GPMF_OK == GPMF_FindNext(&any_stream, GPMF_KEY_TIME_STAMP, GPMF_RECURSE_LEVELS)) ++ { ++ uint64_t timestamp = BYTESWAP64(*(uint64_t *)GPMF_RawData(&any_stream)); ++ if (timestamp < minimumtimestamp) ++ minimumtimestamp = timestamp; ++ } ++ } + +- payload = GetPayload(handle, payload, testend); // second last payload ++ testend = mp4->indexcount; ++ do ++ { ++ testend--;// last payload with the fourcc needed ++ payload = GetPayload(handle, payload, testend); + payloadsize = GetPayloadSize(handle, testend); + ret = GPMF_Init(ms, payload, payloadsize); +- if (ret != GPMF_OK) +- goto cleanup; ++ } while (testend > 0 && GPMF_OK != GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS)); + +- if (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS)) ++ GPMF_CopyState(ms, &find_stream); ++ if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL)) ++ endsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream)); ++ else // If there is no TSMP we have to count the samples. ++ { ++ uint32_t i; ++ for (i = teststart; i <= testend; i++) + { +- GPMF_CopyState(ms, &find_stream); +- if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL)) ++ payload = GetPayload(handle,payload, i); // second last payload ++ payloadsize = GetPayloadSize(handle, i); ++ if (GPMF_OK == GPMF_Init(ms, payload, payloadsize)) ++ if (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS)) ++ endsamples += GPMF_PayloadSampleCount(ms); ++ } ++ } ++ ++ if (starttimestamp != 0) ++ { ++ uint32_t last_samples = GPMF_PayloadSampleCount(ms); ++ uint32_t totaltimestamped_samples = endsamples - last_samples - startsamples; ++ double time_stamp_scale = 1000000000.0; // scan for nanoseconds, microseconds to seconds, all base 10. ++ ++ GPMF_CopyState(ms, &find_stream); ++ if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TIME_STAMP, GPMF_CURRENT_LEVEL)) ++ endtimestamp = BYTESWAP64(*(uint64_t *)GPMF_RawData(&find_stream)); ++ ++ if (endtimestamp) ++ { ++ double approxrate = 0.0; ++ if (endsamples > startsamples) ++ approxrate = (double)(endsamples - startsamples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount); ++ ++ if (approxrate == 0.0) ++ approxrate = (double)(samples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount); ++ ++ ++ while (time_stamp_scale >= 1) + { +- endsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream)); +- rate = (double)(endsamples - startsamples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount); +- goto cleanup; ++ rate = (double)(totaltimestamped_samples) / ((double)(endtimestamp - starttimestamp) / time_stamp_scale); ++ if (rate*0.9 < approxrate && approxrate < rate*1.1) ++ break; ++ ++ time_stamp_scale *= 0.1; + } ++ if (time_stamp_scale < 1.0) rate = 0.0; ++ intercept = (((double)minimumtimestamp - (double)starttimestamp) / time_stamp_scale) * rate; + } +- +- rate = (double)(samples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount); + } +- else // for increased precision, for older GPMF streams sometimes missing the total sample count ++ ++ if (rate == 0.0) //Timestamps didn't help weren't available + { +- uint32_t payloadpos = 0, payloadcount = 0; +- double slope, top = 0.0, bot = 0.0, meanX = 0, meanY = 0; +- uint32_t *repeatarray = malloc(mp4->indexcount * 4 + 4); +- memset(repeatarray, 0, mp4->indexcount * 4 + 4); ++ if (!(flags & GPMF_SAMPLE_RATE_PRECISE)) ++ { ++ if (endsamples > startsamples) ++ rate = (double)(endsamples - startsamples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount); + +- samples = 0; ++ if (rate == 0.0) ++ rate = (double)(samples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount); + +- for (payloadpos = teststart; payloadpos < testend; payloadcount++, payloadpos++) ++ double in, out; ++ if (GPMF_OK == GetPayloadTime(handle, teststart, &in, &out)) ++ intercept = (double)-in * rate; ++ } ++ else // for increased precision, for older GPMF streams sometimes missing the total sample count + { +- payload = GetPayload(handle, payload, payloadpos); // second last payload +- payloadsize = GetPayloadSize(handle, payloadpos); +- ret = GPMF_Init(ms, payload, payloadsize); ++ uint32_t payloadpos = 0, payloadcount = 0; ++ double slope, top = 0.0, bot = 0.0, meanX = 0, meanY = 0; ++ uint32_t *repeatarray = malloc(mp4->indexcount * 4 + 4); ++ memset(repeatarray, 0, mp4->indexcount * 4 + 4); + +- if (ret != GPMF_OK) +- goto cleanup; ++ samples = 0; + +- if (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS)) ++ for (payloadpos = teststart; payloadpos <= testend; payloadpos++) + { +- GPMF_stream find_stream2; +- GPMF_CopyState(ms, &find_stream2); ++ payload = GetPayload(handle, payload, payloadpos); // second last payload ++ payloadsize = GetPayloadSize(handle, payloadpos); ++ ret = GPMF_Init(ms, payload, payloadsize); + +- if (GPMF_OK == GPMF_FindNext(&find_stream2, fourcc, GPMF_CURRENT_LEVEL)) // Count the instances, not the repeats ++ if (ret != GPMF_OK) ++ goto cleanup; ++ ++ if (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS)) + { +- if (repeatarray) +- { +- float in, out; ++ GPMF_stream find_stream2; ++ GPMF_CopyState(ms, &find_stream2); ++ ++ payloadcount++; + +- do ++ if (GPMF_OK == GPMF_FindNext(&find_stream2, fourcc, GPMF_CURRENT_LEVEL)) // Count the instances, not the repeats ++ { ++ if (repeatarray) + { +- samples++; +- } while (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_CURRENT_LEVEL)); ++ double in, out; + +- repeatarray[payloadpos] = samples; +- meanY += (double)samples; ++ do ++ { ++ samples++; ++ } while (GPMF_OK == GPMF_FindNext(ms, fourcc, GPMF_CURRENT_LEVEL)); + +- GetPayloadTime(handle, payloadpos, &in, &out); +- meanX += out; +- } +- } +- else +- { +- uint32_t repeat = GPMF_Repeat(ms); +- samples += repeat; ++ repeatarray[payloadpos] = samples; ++ meanY += (double)samples; + +- if (repeatarray) ++ if (GPMF_OK == GetPayloadTime(handle, payloadpos, &in, &out)) ++ meanX += out; ++ } ++ } ++ else + { +- float in, out; ++ uint32_t repeat = GPMF_PayloadSampleCount(ms); ++ samples += repeat; ++ ++ if (repeatarray) ++ { ++ double in, out; + +- repeatarray[payloadpos] = samples; +- meanY += (double)samples; ++ repeatarray[payloadpos] = samples; ++ meanY += (double)samples; + +- GetPayloadTime(handle, payloadpos, &in, &out); +- meanX += out; ++ if (GPMF_OK == GetPayloadTime(handle, payloadpos, &in, &out)) ++ meanX += out; ++ } + } + } ++ else ++ { ++ repeatarray[payloadpos] = 0; ++ } + } +- } +- +- // Compute the line of best fit for a jitter removed sample rate. +- // This does assume an unchanging clock, even though the IMU data can thermally impacted causing small clock changes. +- // TODO: Next enhancement would be a low order polynominal fit the compensate for any thermal clock drift. +- if (repeatarray) +- { +- meanY /= (double)payloadcount; +- meanX /= (double)payloadcount; + +- for (payloadpos = teststart; payloadpos < testend; payloadpos++) ++ // Compute the line of best fit for a jitter removed sample rate. ++ // This does assume an unchanging clock, even though the IMU data can thermally impacted causing small clock changes. ++ // TODO: Next enhancement would be a low order polynominal fit the compensate for any thermal clock drift. ++ if (repeatarray) + { +- float in, out; +- GetPayloadTime(handle, payloadpos, &in, &out); ++ meanY /= (double)payloadcount; ++ meanX /= (double)payloadcount; + +- top += ((double)out - meanX)*((double)repeatarray[payloadpos] - meanY); +- bot += ((double)out - meanX)*((double)out - meanX); +- } ++ for (payloadpos = teststart; payloadpos <= testend; payloadpos++) ++ { ++ double in, out; ++ if (repeatarray[payloadpos] && GPMF_OK == GetPayloadTime(handle, payloadpos, &in, &out)) ++ { ++ top += ((double)out - meanX)*((double)repeatarray[payloadpos] - meanY); ++ bot += ((double)out - meanX)*((double)out - meanX); ++ } ++ } + +- slope = top / bot; ++ slope = top / bot; ++ rate = slope; + ++ // This sample code might be useful for compare data latency between channels. ++ intercept = meanY - slope * meanX; + #if 0 +- // This sample code might be useful for compare data latency between channels. ++ printf(""%c%c%c%c start offset = %f (%.3fms) rate = %f\n"", PRINTF_4CC(fourcc), intercept, 1000.0 * intercept / slope, rate); ++ printf(""%c%c%c%c first sample at time %.3fms\n"", PRINTF_4CC(fourcc), -1000.0 * intercept / slope); ++#endif ++ } ++ else + { +- double intercept; +- intercept = meanY - slope*meanX; +- printf(""%c%c%c%c start offset = %f (%.3fms)\n"", PRINTF_4CC(fourcc), intercept, 1000.0 * intercept / slope); ++ rate = (double)(samples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount); + } +-#endif +- rate = slope; +- } +- else +- { +- rate = (double)(samples) / (mp4->metadatalength * ((double)(testend - teststart + 1)) / (double)mp4->indexcount); +- } +- +- free(repeatarray); + +- goto cleanup; ++ free(repeatarray); ++ } + } +- } +- } + +-cleanup: +- if (payload) +- { +- FreePayload(payload); +- payload = NULL; +- } +- +- return rate; +-} ++ if (firstsampletime && lastsampletime) ++ { ++ uint32_t endpayload = mp4->indexcount; ++ do ++ { ++ endpayload--;// last payload with the fourcc needed ++ payload = GetPayload(handle, payload, endpayload); ++ payloadsize = GetPayloadSize(handle, endpayload); ++ ret = GPMF_Init(ms, payload, payloadsize); ++ } while (endpayload > 0 && GPMF_OK != GPMF_FindNext(ms, fourcc, GPMF_RECURSE_LEVELS)); + ++ if (endpayload > 0 && ret == GPMF_OK) ++ { ++ uint32_t totalsamples = endsamples - startsamples; ++ float timo = 0.0; + +-double GetGPMFSampleRateAndTimes(size_t handle, GPMF_stream *gs, double rate, uint32_t index, double *in, double *out) +-{ +- mp4object *mp4 = (mp4object *)handle; +- if (mp4 == NULL) return 0.0; ++ GPMF_CopyState(ms, &find_stream); ++ if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TIME_OFFSET, GPMF_CURRENT_LEVEL)) ++ GPMF_FormattedData(&find_stream, &timo, 4, 0, 1); + +- uint32_t key, insamples; +- uint32_t repeat, outsamples; +- GPMF_stream find_stream; ++ double first, last; ++ first = -intercept / rate - timo; ++ last = first + (double)totalsamples / rate; + +- if (gs == NULL || mp4->metaoffsets == 0 || mp4->indexcount == 0 || mp4->basemetadataduration == 0 || mp4->meta_clockdemon == 0 || in == NULL || out == NULL) return 0.0; ++ //printf(""%c%c%c%c first sample at time %.3fms, last at %.3fms\n"", PRINTF_4CC(fourcc), 1000.0*first, 1000.0*last); + +- key = GPMF_Key(gs); +- repeat = GPMF_Repeat(gs); +- if (rate == 0.0) +- rate = GetGPMFSampleRate(handle, key, GPMF_SAMPLE_RATE_FAST); ++ if (firstsampletime) *firstsampletime = first; + +- if (rate == 0.0) +- { +- *in = *out = 0.0; +- return 0.0; ++ if (lastsampletime) *lastsampletime = last; ++ } ++ } ++ } + } + +- GPMF_CopyState(gs, &find_stream); +- if (GPMF_OK == GPMF_FindPrev(&find_stream, GPMF_KEY_TOTAL_SAMPLES, GPMF_CURRENT_LEVEL)) +- { +- outsamples = BYTESWAP32(*(uint32_t *)GPMF_RawData(&find_stream)); +- insamples = outsamples - repeat; ++cleanup: ++ if (payload) ++ FreePayload(payload); ++ payload = NULL; + +- *in = ((double)insamples / (double)rate); +- *out = ((double)outsamples / (double)rate); +- } +- else +- { +- // might too costly in some applications read all the samples to determine the clock jitter, here I return the estimate from the MP4 track. +- *in = ((double)index * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon); +- *out = ((double)(index + 1) * (double)mp4->basemetadataduration / (double)mp4->meta_clockdemon); +- } + return rate; + } ++",1626,1957,2048 +18493,"xmlParseDocument(xmlParserCtxtPtr ctxt) { + xmlChar start[4]; + xmlCharEncoding enc; + + xmlInitParser(); + + if ((ctxt == NULL) || (ctxt->input == NULL)) + return(-1); + + GROW; + + /* + * SAX: detecting the level. + */ + xmlDetectSAX2(ctxt); + + /* + * SAX: beginning of the document processing. + */ + if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) + ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); + + if ((ctxt->encoding == (const xmlChar *)XML_CHAR_ENCODING_NONE) && + ((ctxt->input->end - ctxt->input->cur) >= 4)) { + /* + * Get the 4 first bytes and decode the charset + * if enc != XML_CHAR_ENCODING_NONE + * plug some encoding conversion routines. + */ + start[0] = RAW; + start[1] = NXT(1); + start[2] = NXT(2); + start[3] = NXT(3); + enc = xmlDetectCharEncoding(&start[0], 4); + if (enc != XML_CHAR_ENCODING_NONE) { + xmlSwitchEncoding(ctxt, enc); + } + } + + + if (CUR == 0) { + xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL); + } + + /* + * Check for the XMLDecl in the Prolog. + * do not GROW here to avoid the detected encoder to decode more + * than just the first line, unless the amount of data is really + * too small to hold ""input->end - ctxt->input->cur) < 35) { + GROW; + } + if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { + + /* + * Note that we will switch encoding on the fly. + */ + xmlParseXMLDecl(ctxt); + if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { + /* + * The XML REC instructs us to stop parsing right here + */ + return(-1); + } + ctxt->standalone = ctxt->input->standalone; + SKIP_BLANKS; + } else { + ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION); + } + if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) + ctxt->sax->startDocument(ctxt->userData); + + /* + * The Misc part of the Prolog + */ + GROW; + xmlParseMisc(ctxt); + + /* + * Then possibly doc type declaration(s) and more Misc + * (doctypedecl Misc*)? + */ + GROW; + if (CMP9(CUR_PTR, '<', '!', 'D', 'O', 'C', 'T', 'Y', 'P', 'E')) { + + ctxt->inSubset = 1; + xmlParseDocTypeDecl(ctxt); + if (RAW == '[') { + ctxt->instate = XML_PARSER_DTD; + xmlParseInternalSubset(ctxt); + } + + /* + * Create and update the external subset. + */ + ctxt->inSubset = 2; + if ((ctxt->sax != NULL) && (ctxt->sax->externalSubset != NULL) && + (!ctxt->disableSAX)) + ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, + ctxt->extSubSystem, ctxt->extSubURI); + ctxt->inSubset = 0; + + xmlCleanSpecialAttr(ctxt); + + ctxt->instate = XML_PARSER_PROLOG; + xmlParseMisc(ctxt); + } + + /* + * Time to start parsing the tree itself + */ + GROW; + if (RAW != '<') { + xmlFatalErrMsg(ctxt, XML_ERR_DOCUMENT_EMPTY, + ""Start tag expected, '<' not found\n""); + } else { + ctxt->instate = XML_PARSER_CONTENT; + xmlParseElement(ctxt); + ctxt->instate = XML_PARSER_EPILOG; + + + /* + * The Misc part at the end + */ + xmlParseMisc(ctxt); + + if (RAW != 0) { + xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); + } + ctxt->instate = XML_PARSER_EOF; + } + + /* + * SAX: end of the document processing. + */ + if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) + ctxt->sax->endDocument(ctxt->userData); + + /* + * Remove locally kept entity definitions if the tree was not built + */ + if ((ctxt->myDoc != NULL) && + (xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE))) { + xmlFreeDoc(ctxt->myDoc); + ctxt->myDoc = NULL; + } + + if ((ctxt->wellFormed) && (ctxt->myDoc != NULL)) { + ctxt->myDoc->properties |= XML_DOC_WELLFORMED; + if (ctxt->valid) + ctxt->myDoc->properties |= XML_DOC_DTDVALID; + if (ctxt->nsWellFormed) + ctxt->myDoc->properties |= XML_DOC_NSVALID; + if (ctxt->options & XML_PARSE_OLD10) + ctxt->myDoc->properties |= XML_DOC_OLD10; + } + if (! ctxt->wellFormed) { + ctxt->valid = 0; + return(-1); + } + return(0); +} +",1,"xmlParseDocument(xmlParserCtxtPtr ctxt) { + xmlChar start[4]; + xmlCharEncoding enc; + + xmlInitParser(); + + if ((ctxt == NULL) || (ctxt->input == NULL)) + return(-1); + + GROW; + + /* + * SAX: detecting the level. + */ + xmlDetectSAX2(ctxt); + + /* + * SAX: beginning of the document processing. + */ + if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) + ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); + if (ctxt->instate == XML_PARSER_EOF) + return(-1); + + if ((ctxt->encoding == (const xmlChar *)XML_CHAR_ENCODING_NONE) && + ((ctxt->input->end - ctxt->input->cur) >= 4)) { + /* + * Get the 4 first bytes and decode the charset + * if enc != XML_CHAR_ENCODING_NONE + * plug some encoding conversion routines. + */ + start[0] = RAW; + start[1] = NXT(1); + start[2] = NXT(2); + start[3] = NXT(3); + enc = xmlDetectCharEncoding(&start[0], 4); + if (enc != XML_CHAR_ENCODING_NONE) { + xmlSwitchEncoding(ctxt, enc); + } + } + + + if (CUR == 0) { + xmlFatalErr(ctxt, XML_ERR_DOCUMENT_EMPTY, NULL); + } + + /* + * Check for the XMLDecl in the Prolog. + * do not GROW here to avoid the detected encoder to decode more + * than just the first line, unless the amount of data is really + * too small to hold ""input->end - ctxt->input->cur) < 35) { + GROW; + } + if ((CMP5(CUR_PTR, '<', '?', 'x', 'm', 'l')) && (IS_BLANK_CH(NXT(5)))) { + + /* + * Note that we will switch encoding on the fly. + */ + xmlParseXMLDecl(ctxt); + if (ctxt->errNo == XML_ERR_UNSUPPORTED_ENCODING) { + /* + * The XML REC instructs us to stop parsing right here + */ + return(-1); + } + ctxt->standalone = ctxt->input->standalone; + SKIP_BLANKS; + } else { + ctxt->version = xmlCharStrdup(XML_DEFAULT_VERSION); + } + if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) + ctxt->sax->startDocument(ctxt->userData); + if (ctxt->instate == XML_PARSER_EOF) + return(-1); + + /* + * The Misc part of the Prolog + */ + GROW; + xmlParseMisc(ctxt); + + /* + * Then possibly doc type declaration(s) and more Misc + * (doctypedecl Misc*)? + */ + GROW; + if (CMP9(CUR_PTR, '<', '!', 'D', 'O', 'C', 'T', 'Y', 'P', 'E')) { + + ctxt->inSubset = 1; + xmlParseDocTypeDecl(ctxt); + if (RAW == '[') { + ctxt->instate = XML_PARSER_DTD; + xmlParseInternalSubset(ctxt); + if (ctxt->instate == XML_PARSER_EOF) + return(-1); + } + + /* + * Create and update the external subset. + */ + ctxt->inSubset = 2; + if ((ctxt->sax != NULL) && (ctxt->sax->externalSubset != NULL) && + (!ctxt->disableSAX)) + ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, + ctxt->extSubSystem, ctxt->extSubURI); + if (ctxt->instate == XML_PARSER_EOF) + return(-1); + ctxt->inSubset = 0; + + xmlCleanSpecialAttr(ctxt); + + ctxt->instate = XML_PARSER_PROLOG; + xmlParseMisc(ctxt); + } + + /* + * Time to start parsing the tree itself + */ + GROW; + if (RAW != '<') { + xmlFatalErrMsg(ctxt, XML_ERR_DOCUMENT_EMPTY, + ""Start tag expected, '<' not found\n""); + } else { + ctxt->instate = XML_PARSER_CONTENT; + xmlParseElement(ctxt); + ctxt->instate = XML_PARSER_EPILOG; + + + /* + * The Misc part at the end + */ + xmlParseMisc(ctxt); + + if (RAW != 0) { + xmlFatalErr(ctxt, XML_ERR_DOCUMENT_END, NULL); + } + ctxt->instate = XML_PARSER_EOF; + } + + /* + * SAX: end of the document processing. + */ + if ((ctxt->sax) && (ctxt->sax->endDocument != NULL)) + ctxt->sax->endDocument(ctxt->userData); + + /* + * Remove locally kept entity definitions if the tree was not built + */ + if ((ctxt->myDoc != NULL) && + (xmlStrEqual(ctxt->myDoc->version, SAX_COMPAT_MODE))) { + xmlFreeDoc(ctxt->myDoc); + ctxt->myDoc = NULL; + } + + if ((ctxt->wellFormed) && (ctxt->myDoc != NULL)) { + ctxt->myDoc->properties |= XML_DOC_WELLFORMED; + if (ctxt->valid) + ctxt->myDoc->properties |= XML_DOC_DTDVALID; + if (ctxt->nsWellFormed) + ctxt->myDoc->properties |= XML_DOC_NSVALID; + if (ctxt->options & XML_PARSE_OLD10) + ctxt->myDoc->properties |= XML_DOC_OLD10; + } + if (! ctxt->wellFormed) { + ctxt->valid = 0; + return(-1); + } + return(0); +} +","@@ -2013,6 +2013,8 @@ xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) { + ""Pushing input %d : %.30s\n"", ctxt->inputNr+1, input->cur); + } + ret = inputPush(ctxt, input); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + GROW; + return(ret); + } +@@ -2049,6 +2051,8 @@ xmlParseCharRef(xmlParserCtxtPtr ctxt) { + if (count++ > 20) { + count = 0; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(0); + } + if ((RAW >= '0') && (RAW <= '9')) + val = val * 16 + (CUR - '0'); +@@ -2080,6 +2084,8 @@ xmlParseCharRef(xmlParserCtxtPtr ctxt) { + if (count++ > 20) { + count = 0; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(0); + } + if ((RAW >= '0') && (RAW <= '9')) + val = val * 10 + (CUR - '0'); +@@ -2366,6 +2372,8 @@ xmlParserHandlePEReference(xmlParserCtxtPtr ctxt) { + NEXT; + if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL)) + entity = ctxt->sax->getParameterEntity(ctxt->userData, name); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + if (entity == NULL) { + + /* +@@ -2428,6 +2436,8 @@ xmlParserHandlePEReference(xmlParserCtxtPtr ctxt) { + * the amount of data in the buffer. + */ + GROW ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + if ((ctxt->input->end - ctxt->input->cur)>=4) { + start[0] = RAW; + start[1] = NXT(1); +@@ -3046,6 +3056,8 @@ xmlParseNameComplex(xmlParserCtxtPtr ctxt) { + * Handler for more complex cases + */ + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + c = CUR_CHAR(l); + if ((ctxt->options & XML_PARSE_OLD10) == 0) { + /* +@@ -3097,6 +3109,8 @@ xmlParseNameComplex(xmlParserCtxtPtr ctxt) { + if (count++ > 100) { + count = 0; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + } + len += l; + NEXTL(l); +@@ -3121,6 +3135,8 @@ xmlParseNameComplex(xmlParserCtxtPtr ctxt) { + if (count++ > 100) { + count = 0; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + } + len += l; + NEXTL(l); +@@ -3214,6 +3230,8 @@ xmlParseNCNameComplex(xmlParserCtxtPtr ctxt) { + if (count++ > 100) { + count = 0; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + } + len += l; + NEXTL(l); +@@ -3294,6 +3312,8 @@ xmlParseNameAndCompare(xmlParserCtxtPtr ctxt, xmlChar const *other) { + const xmlChar *ret; + + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + + in = ctxt->input->cur; + while (*in != 0 && *in == *cmp) { +@@ -3421,6 +3441,8 @@ xmlParseNmtoken(xmlParserCtxtPtr ctxt) { + #endif + + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + c = CUR_CHAR(l); + + while (xmlIsNameChar(ctxt, c)) { +@@ -3449,6 +3471,10 @@ xmlParseNmtoken(xmlParserCtxtPtr ctxt) { + if (count++ > 100) { + count = 0; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buffer); ++ return(NULL); ++ } + } + if (len + 10 > max) { + xmlChar *tmp; +@@ -3519,6 +3545,10 @@ xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) { + ctxt->instate = XML_PARSER_ENTITY_VALUE; + input = ctxt->input; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return(NULL); ++ } + NEXT; + c = CUR_CHAR(l); + /* +@@ -3530,8 +3560,8 @@ xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) { + * In practice it means we stop the loop only when back at parsing + * the initial entity and the quote is found + */ +- while ((IS_CHAR(c)) && ((c != stop) || /* checked */ +- (ctxt->input != input))) { ++ while (((IS_CHAR(c)) && ((c != stop) || /* checked */ ++ (ctxt->input != input))) && (ctxt->instate != XML_PARSER_EOF)) { + if (len + 5 >= size) { + xmlChar *tmp; + +@@ -3560,6 +3590,10 @@ xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) { + } + } + buf[len] = 0; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return(NULL); ++ } + + /* + * Raise problem w.r.t. '&' and '%' being used in non-entities +@@ -3607,12 +3641,12 @@ xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) { + */ + ret = xmlStringDecodeEntities(ctxt, buf, XML_SUBSTITUTE_PEREF, + 0, 0, 0); +- if (orig != NULL) ++ if (orig != NULL) + *orig = buf; + else + xmlFree(buf); + } +- ++ + return(ret); + } + +@@ -3663,8 +3697,9 @@ xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) { + * OK loop until we reach one of the ending char or a size limit. + */ + c = CUR_CHAR(l); +- while ((NXT(0) != limit) && /* checked */ +- (IS_CHAR(c)) && (c != '<')) { ++ while (((NXT(0) != limit) && /* checked */ ++ (IS_CHAR(c)) && (c != '<')) && ++ (ctxt->instate != XML_PARSER_EOF)) { + if (c == 0) break; + if (c == '&') { + in_space = 0; +@@ -3799,6 +3834,9 @@ xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) { + GROW; + c = CUR_CHAR(l); + } ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto error; ++ + if ((in_space) && (normalize)) { + while ((len > 0) && (buf[len - 1] == 0x20)) len--; + } +@@ -3820,6 +3858,7 @@ xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) { + + mem_error: + xmlErrMemory(ctxt, NULL); ++error: + if (buf != NULL) + xmlFree(buf); + if (rep != NULL) +@@ -3925,6 +3964,10 @@ xmlParseSystemLiteral(xmlParserCtxtPtr ctxt) { + if (count > 50) { + GROW; + count = 0; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return(NULL); ++ } + } + COPY_BUF(l,buf,len,cur); + NEXTL(l); +@@ -4002,6 +4045,10 @@ xmlParsePubidLiteral(xmlParserCtxtPtr ctxt) { + if (count > 50) { + GROW; + count = 0; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return(NULL); ++ } + } + NEXT; + cur = CUR; +@@ -4208,6 +4255,8 @@ xmlParseCharData(xmlParserCtxtPtr ctxt, int cdata) { + } + SHRINK; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + in = ctxt->input->cur; + } while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09)); + nbchar = 0; +@@ -4276,6 +4325,8 @@ xmlParseCharDataComplex(xmlParserCtxtPtr ctxt, int cdata) { + if (count > 50) { + GROW; + count = 0; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + } + NEXTL(l); + cur = CUR_CHAR(l); +@@ -4476,6 +4527,10 @@ xmlParseCommentComplex(xmlParserCtxtPtr ctxt, xmlChar *buf, int len, int size) { + if (count > 50) { + GROW; + count = 0; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return; ++ } + } + NEXTL(l); + cur = CUR_CHAR(l); +@@ -4626,6 +4681,10 @@ xmlParseComment(xmlParserCtxtPtr ctxt) { + } + SHRINK; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return; ++ } + in = ctxt->input->cur; + if (*in == '-') { + if (in[1] == '-') { +@@ -4644,7 +4703,8 @@ xmlParseComment(xmlParserCtxtPtr ctxt) { + } + if (buf != NULL) + xmlFree(buf); +- ctxt->instate = state; ++ if (ctxt->instate != XML_PARSER_EOF) ++ ctxt->instate = state; + return; + } + if (buf != NULL) +@@ -4862,6 +4922,10 @@ xmlParsePI(xmlParserCtxtPtr ctxt) { + count++; + if (count > 50) { + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return; ++ } + count = 0; + } + COPY_BUF(l,buf,len,cur); +@@ -5211,6 +5275,8 @@ xmlParseEntityDecl(xmlParserCtxtPtr ctxt) { + } + } + } ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + SKIP_BLANKS; + if (RAW != '>') { + xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_NOT_FINISHED, +@@ -5602,7 +5668,7 @@ xmlParseAttributeListDecl(xmlParserCtxtPtr ctxt) { + } + SKIP_BLANKS; + GROW; +- while (RAW != '>') { ++ while ((RAW != '>') && (ctxt->instate != XML_PARSER_EOF)) { + const xmlChar *check = CUR_PTR; + int type; + int def; +@@ -5751,7 +5817,7 @@ xmlParseElementMixedContentDecl(xmlParserCtxtPtr ctxt, int inputchk) { + ret = cur = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_PCDATA); + if (ret == NULL) return(NULL); + } +- while (RAW == '|') { ++ while ((RAW == '|') && (ctxt->instate != XML_PARSER_EOF)) { + NEXT; + if (elem == NULL) { + ret = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR); +@@ -5895,7 +5961,7 @@ xmlParseElementChildrenContentDeclPriv(xmlParserCtxtPtr ctxt, int inputchk, + } + SKIP_BLANKS; + SHRINK; +- while (RAW != ')') { ++ while ((RAW != ')') && (ctxt->instate != XML_PARSER_EOF)) { + /* + * Each loop we parse one separator and one element. + */ +@@ -6174,6 +6240,8 @@ xmlParseElementContentDecl(xmlParserCtxtPtr ctxt, const xmlChar *name, + } + NEXT; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + SKIP_BLANKS; + if (CMP7(CUR_PTR, '#', 'P', 'C', 'D', 'A', 'T', 'A')) { + tree = xmlParseElementMixedContentDecl(ctxt, inputid); +@@ -6341,8 +6409,8 @@ xmlParseConditionalSections(xmlParserCtxtPtr ctxt) { + ""Entering INCLUDE Conditional Section\n""); + } + +- while ((RAW != 0) && ((RAW != ']') || (NXT(1) != ']') || +- (NXT(2) != '>'))) { ++ while (((RAW != 0) && ((RAW != ']') || (NXT(1) != ']') || ++ (NXT(2) != '>'))) && (ctxt->instate != XML_PARSER_EOF)) { + const xmlChar *check = CUR_PTR; + unsigned int cons = ctxt->input->consumed; + +@@ -6410,7 +6478,8 @@ xmlParseConditionalSections(xmlParserCtxtPtr ctxt) { + if (ctxt->recovery == 0) ctxt->disableSAX = 1; + ctxt->instate = XML_PARSER_IGNORE; + +- while ((depth >= 0) && (RAW != 0)) { ++ while (((depth >= 0) && (RAW != 0)) && ++ (ctxt->instate != XML_PARSER_EOF)) { + if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) { + depth++; + SKIP(3); +@@ -6681,7 +6750,7 @@ xmlParseExternalSubset(xmlParserCtxtPtr ctxt, const xmlChar *ExternalID, + break; + } + } +- ++ + if (RAW != 0) { + xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL); + } +@@ -7127,6 +7196,8 @@ xmlParseEntityRef(xmlParserCtxtPtr ctxt) { + xmlEntityPtr ent = NULL; + + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + + if (RAW != '&') + return(NULL); +@@ -7172,6 +7243,8 @@ xmlParseEntityRef(xmlParserCtxtPtr ctxt) { + ent = xmlSAX2GetEntity(ctxt, name); + } + } ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + /* + * [ WFC: Entity Declared ] + * In a document without any DTD, a document with only an +@@ -7362,6 +7435,10 @@ xmlParseStringEntityRef(xmlParserCtxtPtr ctxt, const xmlChar ** str) { + ent = xmlSAX2GetEntity(ctxt, name); + } + } ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(name); ++ return(NULL); ++ } + + /* + * [ WFC: Entity Declared ] +@@ -7523,8 +7600,9 @@ xmlParsePEReference(xmlParserCtxtPtr ctxt) + */ + if ((ctxt->sax != NULL) && + (ctxt->sax->getParameterEntity != NULL)) +- entity = ctxt->sax->getParameterEntity(ctxt->userData, +- name); ++ entity = ctxt->sax->getParameterEntity(ctxt->userData, name); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + if (entity == NULL) { + /* + * [ WFC: Entity Declared ] +@@ -7657,6 +7735,10 @@ xmlLoadEntityContent(xmlParserCtxtPtr ctxt, xmlEntityPtr entity) { + if (count++ > 100) { + count = 0; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlBufferFree(buf); ++ return(-1); ++ } + } + NEXTL(l); + c = CUR_CHAR(l); +@@ -7748,8 +7830,11 @@ xmlParseStringPEReference(xmlParserCtxtPtr ctxt, const xmlChar **str) { + */ + if ((ctxt->sax != NULL) && + (ctxt->sax->getParameterEntity != NULL)) +- entity = ctxt->sax->getParameterEntity(ctxt->userData, +- name); ++ entity = ctxt->sax->getParameterEntity(ctxt->userData, name); ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(name); ++ return(NULL); ++ } + if (entity == NULL) { + /* + * [ WFC: Entity Declared ] +@@ -7851,6 +7936,8 @@ xmlParseDocTypeDecl(xmlParserCtxtPtr ctxt) { + if ((ctxt->sax != NULL) && (ctxt->sax->internalSubset != NULL) && + (!ctxt->disableSAX)) + ctxt->sax->internalSubset(ctxt->userData, name, ExternalID, URI); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + + /* + * Is there any internal subset declarations ? +@@ -7890,7 +7977,7 @@ xmlParseInternalSubset(xmlParserCtxtPtr ctxt) { + * PEReferences. + * Subsequence (markupdecl | PEReference | S)* + */ +- while (RAW != ']') { ++ while ((RAW != ']') && (ctxt->instate != XML_PARSER_EOF)) { + const xmlChar *check = CUR_PTR; + unsigned int cons = ctxt->input->consumed; + +@@ -8076,9 +8163,9 @@ xmlParseStartTag(xmlParserCtxtPtr ctxt) { + SKIP_BLANKS; + GROW; + +- while ((RAW != '>') && ++ while (((RAW != '>') && + ((RAW != '/') || (NXT(1) != '>')) && +- (IS_BYTE_CHAR(RAW))) { ++ (IS_BYTE_CHAR(RAW))) && (ctxt->instate != XML_PARSER_EOF)) { + const xmlChar *q = CUR_PTR; + unsigned int cons = ctxt->input->consumed; + +@@ -8502,6 +8589,8 @@ xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc, + if (in >= end) { + const xmlChar *oldbase = ctxt->input->base; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + if (oldbase != ctxt->input->base) { + long delta = ctxt->input->base - oldbase; + start = start + delta; +@@ -8516,6 +8605,8 @@ xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc, + if (in >= end) { + const xmlChar *oldbase = ctxt->input->base; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + if (oldbase != ctxt->input->base) { + long delta = ctxt->input->base - oldbase; + start = start + delta; +@@ -8536,6 +8627,8 @@ xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc, + if (in >= end) { + const xmlChar *oldbase = ctxt->input->base; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + if (oldbase != ctxt->input->base) { + long delta = ctxt->input->base - oldbase; + start = start + delta; +@@ -8553,6 +8646,8 @@ xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc, + if (in >= end) { + const xmlChar *oldbase = ctxt->input->base; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + if (oldbase != ctxt->input->base) { + long delta = ctxt->input->base - oldbase; + start = start + delta; +@@ -8784,9 +8879,9 @@ xmlParseStartTag2(xmlParserCtxtPtr ctxt, const xmlChar **pref, + GROW; + if (ctxt->input->base != base) goto base_changed; + +- while ((RAW != '>') && ++ while (((RAW != '>') && + ((RAW != '/') || (NXT(1) != '>')) && +- (IS_BYTE_CHAR(RAW))) { ++ (IS_BYTE_CHAR(RAW))) && (ctxt->instate != XML_PARSER_EOF)) { + const xmlChar *q = CUR_PTR; + unsigned int cons = ctxt->input->consumed; + int len = -1, alloc = 0; +@@ -8957,6 +9052,8 @@ xmlParseStartTag2(xmlParserCtxtPtr ctxt, const xmlChar **pref, + failed: + + GROW ++ if (ctxt->instate == XML_PARSER_EOF) ++ break; + if (ctxt->input->base != base) goto base_changed; + if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>')))) + break; +@@ -9194,6 +9291,8 @@ xmlParseEndTag2(xmlParserCtxtPtr ctxt, const xmlChar *prefix, + * We should definitely be at the ending ""S? '>'"" part + */ + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + SKIP_BLANKS; + if ((!IS_BYTE_CHAR(RAW)) || (RAW != '>')) { + xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL); +@@ -9302,6 +9401,10 @@ xmlParseCDSect(xmlParserCtxtPtr ctxt) { + count++; + if (count > 50) { + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return; ++ } + count = 0; + } + NEXTL(l); +@@ -9550,6 +9653,8 @@ xmlParseElement(xmlParserCtxtPtr ctxt) { + * Parse the content of the element: + */ + xmlParseContent(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + if (!IS_BYTE_CHAR(RAW)) { + xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NOT_FINISHED, + ""Premature end of data in tag %s line %d\n"", +@@ -10065,9 +10170,10 @@ xmlParseXMLDecl(xmlParserCtxtPtr ctxt) { + + void + xmlParseMisc(xmlParserCtxtPtr ctxt) { +- while (((RAW == '<') && (NXT(1) == '?')) || +- (CMP4(CUR_PTR, '<', '!', '-', '-')) || +- IS_BLANK_CH(CUR)) { ++ while ((ctxt->instate != XML_PARSER_EOF) && ++ (((RAW == '<') && (NXT(1) == '?')) || ++ (CMP4(CUR_PTR, '<', '!', '-', '-')) || ++ IS_BLANK_CH(CUR))) { + if ((RAW == '<') && (NXT(1) == '?')) { + xmlParsePI(ctxt); + } else if (IS_BLANK_CH(CUR)) { +@@ -10114,6 +10220,8 @@ xmlParseDocument(xmlParserCtxtPtr ctxt) { + */ + if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) + ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + + if ((ctxt->encoding == (const xmlChar *)XML_CHAR_ENCODING_NONE) && + ((ctxt->input->end - ctxt->input->cur) >= 4)) { +@@ -10165,6 +10273,8 @@ xmlParseDocument(xmlParserCtxtPtr ctxt) { + } + if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) + ctxt->sax->startDocument(ctxt->userData); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + + /* + * The Misc part of the Prolog +@@ -10184,6 +10294,8 @@ xmlParseDocument(xmlParserCtxtPtr ctxt) { + if (RAW == '[') { + ctxt->instate = XML_PARSER_DTD; + xmlParseInternalSubset(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + } + + /* +@@ -10194,6 +10306,8 @@ xmlParseDocument(xmlParserCtxtPtr ctxt) { + (!ctxt->disableSAX)) + ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, + ctxt->extSubSystem, ctxt->extSubURI); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + ctxt->inSubset = 0; + + xmlCleanSpecialAttr(ctxt); +@@ -10334,6 +10448,8 @@ xmlParseExtParsedEnt(xmlParserCtxtPtr ctxt) { + } + if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) + ctxt->sax->startDocument(ctxt->userData); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + + /* + * Doing validity checking on chunk doesn't make sense +@@ -10344,6 +10460,8 @@ xmlParseExtParsedEnt(xmlParserCtxtPtr ctxt) { + ctxt->depth = 0; + + xmlParseContent(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + + if ((RAW == '<') && (NXT(1) == '/')) { + xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL); +@@ -10651,7 +10769,7 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + } + xmlParseGetLasts(ctxt, &lastlt, &lastgt); + +- while (1) { ++ while (ctxt->instate != XML_PARSER_EOF) { + if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) + return(0); + +@@ -10891,6 +11009,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ctxt->sax->endElement(ctxt->userData, name); + #endif /* LIBXML_SAX1_ENABLED */ + } ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + spacePop(ctxt); + if (ctxt->nameNr == 0) { + ctxt->instate = XML_PARSER_EPILOG; +@@ -11072,6 +11192,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ctxt->sax->characters(ctxt->userData, + ctxt->input->cur, tmp); + } ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + SKIPL(tmp); + ctxt->checkIndex = 0; + } +@@ -11107,6 +11229,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ctxt->sax->characters(ctxt->userData, + ctxt->input->cur, base); + } ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + SKIPL(base + 3); + ctxt->checkIndex = 0; + ctxt->instate = XML_PARSER_CONTENT; +@@ -11138,6 +11262,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ""PP: Parsing PI\n""); + #endif + xmlParsePI(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + ctxt->checkIndex = 0; + } else if ((cur == '<') && (next == '!') && + (ctxt->input->cur[2] == '-') && +@@ -11150,6 +11276,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ""PP: Parsing Comment\n""); + #endif + xmlParseComment(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + ctxt->instate = XML_PARSER_MISC; + ctxt->checkIndex = 0; + } else if ((cur == '<') && (next == '!') && +@@ -11169,6 +11297,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + #endif + ctxt->inSubset = 1; + xmlParseDocTypeDecl(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + if (RAW == '[') { + ctxt->instate = XML_PARSER_DTD; + #ifdef DEBUG_PUSH +@@ -11225,6 +11355,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ""PP: Parsing PI\n""); + #endif + xmlParsePI(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + } else if ((cur == '<') && (next == '!') && + (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { + if ((!terminate) && +@@ -11235,6 +11367,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ""PP: Parsing Comment\n""); + #endif + xmlParseComment(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + ctxt->instate = XML_PARSER_PROLOG; + } else if ((cur == '<') && (next == '!') && + (avail < 4)) { +@@ -11269,6 +11403,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ""PP: Parsing PI\n""); + #endif + xmlParsePI(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + ctxt->instate = XML_PARSER_EPILOG; + } else if ((cur == '<') && (next == '!') && + (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { +@@ -11280,6 +11416,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ""PP: Parsing Comment\n""); + #endif + xmlParseComment(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + ctxt->instate = XML_PARSER_EPILOG; + } else if ((cur == '<') && (next == '!') && + (avail < 4)) { +@@ -11408,13 +11546,17 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + + found_end_int_subset: + xmlParseInternalSubset(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + ctxt->inSubset = 2; + if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && + (ctxt->sax->externalSubset != NULL)) + ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, + ctxt->extSubSystem, ctxt->extSubURI); + ctxt->inSubset = 0; + xmlCleanSpecialAttr(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + ctxt->instate = XML_PARSER_PROLOG; + ctxt->checkIndex = 0; + #ifdef DEBUG_PUSH +@@ -11537,6 +11679,8 @@ xmlParseChunk(xmlParserCtxtPtr ctxt, const char *chunk, int size, + return(XML_ERR_INTERNAL_ERROR); + if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) + return(ctxt->errNo); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + if (ctxt->instate == XML_PARSER_START) + xmlDetectSAX2(ctxt); + if ((size > 0) && (chunk != NULL) && (!terminate) && +@@ -11623,6 +11767,8 @@ xmlParseChunk(xmlParserCtxtPtr ctxt, const char *chunk, int size, + xmlParseTryOrFinish(ctxt, 0); + else + xmlParseTryOrFinish(ctxt, terminate); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(ctxt->errNo); + if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) + return(ctxt->errNo); + +@@ -11816,6 +11962,7 @@ xmlStopParser(xmlParserCtxtPtr ctxt) { + if (ctxt == NULL) + return; + ctxt->instate = XML_PARSER_EOF; ++ ctxt->errNo = XML_ERR_USER_STOP; + ctxt->disableSAX = 1; + if (ctxt->input != NULL) { + ctxt->input->cur = BAD_CAST"""";",1212,1543,2048 +2448,"void bond_change_active_slave(struct bonding *bond, struct slave *new_active) +{ + struct slave *old_active = bond->curr_active_slave; + + if (old_active == new_active) + return; + + if (new_active) { + new_active->jiffies = jiffies; + + if (new_active->link == BOND_LINK_BACK) { + if (USES_PRIMARY(bond->params.mode)) { + pr_info(""%s: making interface %s the new active one %d ms earlier.\n"", + bond->dev->name, new_active->dev->name, + (bond->params.updelay - new_active->delay) * bond->params.miimon); + } + + new_active->delay = 0; + new_active->link = BOND_LINK_UP; + + if (bond->params.mode == BOND_MODE_8023AD) + bond_3ad_handle_link_change(new_active, BOND_LINK_UP); + + if (bond_is_lb(bond)) + bond_alb_handle_link_change(bond, new_active, BOND_LINK_UP); + } else { + if (USES_PRIMARY(bond->params.mode)) { + pr_info(""%s: making interface %s the new active one.\n"", + bond->dev->name, new_active->dev->name); + } + } + } + + if (USES_PRIMARY(bond->params.mode)) + bond_mc_swap(bond, new_active, old_active); + + if (bond_is_lb(bond)) { + bond_alb_handle_active_change(bond, new_active); + if (old_active) + bond_set_slave_inactive_flags(old_active); + if (new_active) + bond_set_slave_active_flags(new_active); + } else { + bond->curr_active_slave = new_active; + } + + if (bond->params.mode == BOND_MODE_ACTIVEBACKUP) { + if (old_active) + bond_set_slave_inactive_flags(old_active); + + if (new_active) { + bool should_notify_peers = false; + + bond_set_slave_active_flags(new_active); + + if (bond->params.fail_over_mac) + bond_do_fail_over_mac(bond, new_active, + old_active); + + if (netif_running(bond->dev)) { + bond->send_peer_notif = + bond->params.num_peer_notif; + should_notify_peers = + bond_should_notify_peers(bond); + } + + write_unlock_bh(&bond->curr_slave_lock); + read_unlock(&bond->lock); + + netdev_bonding_change(bond->dev, NETDEV_BONDING_FAILOVER); + if (should_notify_peers) + netdev_bonding_change(bond->dev, + NETDEV_NOTIFY_PEERS); + + read_lock(&bond->lock); + write_lock_bh(&bond->curr_slave_lock); + } + } + + /* resend IGMP joins since active slave has changed or + * all were sent on curr_active_slave. + * resend only if bond is brought up with the affected + * bonding modes and the retransmission is enabled */ + if (netif_running(bond->dev) && (bond->params.resend_igmp > 0) && + ((USES_PRIMARY(bond->params.mode) && new_active) || + bond->params.mode == BOND_MODE_ROUNDROBIN)) { + bond->igmp_retrans = bond->params.resend_igmp; + queue_delayed_work(bond->wq, &bond->mcast_work, 0); + } +} +",0,"void bond_change_active_slave(struct bonding *bond, struct slave *new_active) +{ + struct slave *old_active = bond->curr_active_slave; + + if (old_active == new_active) + return; + + if (new_active) { + new_active->jiffies = jiffies; + + if (new_active->link == BOND_LINK_BACK) { + if (USES_PRIMARY(bond->params.mode)) { + pr_info(""%s: making interface %s the new active one %d ms earlier.\n"", + bond->dev->name, new_active->dev->name, + (bond->params.updelay - new_active->delay) * bond->params.miimon); + } + + new_active->delay = 0; + new_active->link = BOND_LINK_UP; + + if (bond->params.mode == BOND_MODE_8023AD) + bond_3ad_handle_link_change(new_active, BOND_LINK_UP); + + if (bond_is_lb(bond)) + bond_alb_handle_link_change(bond, new_active, BOND_LINK_UP); + } else { + if (USES_PRIMARY(bond->params.mode)) { + pr_info(""%s: making interface %s the new active one.\n"", + bond->dev->name, new_active->dev->name); + } + } + } + + if (USES_PRIMARY(bond->params.mode)) + bond_mc_swap(bond, new_active, old_active); + + if (bond_is_lb(bond)) { + bond_alb_handle_active_change(bond, new_active); + if (old_active) + bond_set_slave_inactive_flags(old_active); + if (new_active) + bond_set_slave_active_flags(new_active); + } else { + bond->curr_active_slave = new_active; + } + + if (bond->params.mode == BOND_MODE_ACTIVEBACKUP) { + if (old_active) + bond_set_slave_inactive_flags(old_active); + + if (new_active) { + bool should_notify_peers = false; + + bond_set_slave_active_flags(new_active); + + if (bond->params.fail_over_mac) + bond_do_fail_over_mac(bond, new_active, + old_active); + + if (netif_running(bond->dev)) { + bond->send_peer_notif = + bond->params.num_peer_notif; + should_notify_peers = + bond_should_notify_peers(bond); + } + + write_unlock_bh(&bond->curr_slave_lock); + read_unlock(&bond->lock); + + netdev_bonding_change(bond->dev, NETDEV_BONDING_FAILOVER); + if (should_notify_peers) + netdev_bonding_change(bond->dev, + NETDEV_NOTIFY_PEERS); + + read_lock(&bond->lock); + write_lock_bh(&bond->curr_slave_lock); + } + } + + /* resend IGMP joins since active slave has changed or + * all were sent on curr_active_slave. + * resend only if bond is brought up with the affected + * bonding modes and the retransmission is enabled */ + if (netif_running(bond->dev) && (bond->params.resend_igmp > 0) && + ((USES_PRIMARY(bond->params.mode) && new_active) || + bond->params.mode == BOND_MODE_ROUNDROBIN)) { + bond->igmp_retrans = bond->params.resend_igmp; + queue_delayed_work(bond->wq, &bond->mcast_work, 0); + } +} +","@@ -1557,8 +1557,10 @@ int bond_enslave(struct net_device *bond_dev, struct net_device *slave_dev) + + if (slave_dev->type != ARPHRD_ETHER) + bond_setup_by_slave(bond_dev, slave_dev); +- else ++ else { + ether_setup(bond_dev); ++ bond_dev->priv_flags &= ~IFF_TX_SKB_SHARING; ++ } + + netdev_bonding_change(bond_dev, + NETDEV_POST_TYPE_CHANGE); +@@ -4330,7 +4332,7 @@ static void bond_setup(struct net_device *bond_dev) + bond_dev->tx_queue_len = 0; + bond_dev->flags |= IFF_MASTER|IFF_MULTICAST; + bond_dev->priv_flags |= IFF_BONDING; +- bond_dev->priv_flags &= ~IFF_XMIT_DST_RELEASE; ++ bond_dev->priv_flags &= ~(IFF_XMIT_DST_RELEASE | IFF_TX_SKB_SHARING); + + /* At first, we block adding VLANs. That's the only way to + * prevent problems that occur when adding VLANs over an",752,1083,2048 +17859," static int zrle_send_framebuffer_update(VncState *vs, int x, int y, + int w, int h) + { + bool be = !!(vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG); + size_t bytes; + int zywrle_level; + + if (vs->zrle.type == VNC_ENCODING_ZYWRLE) { + if (!vs->vd->lossy || vs->tight.quality == (uint8_t)-1 + || vs->tight.quality == 9) { + zywrle_level = 0; + vs->zrle.type = VNC_ENCODING_ZRLE; + } else if (vs->tight.quality < 3) { + zywrle_level = 3; + } else if (vs->tight.quality < 6) { + zywrle_level = 2; + } else { + zywrle_level = 1; + } + } else { + zywrle_level = 0; + } + + vnc_zrle_start(vs); + + switch(vs->clientds.pf.bytes_per_pixel) { + case 1: + zrle_encode_8ne(vs, x, y, w, h, zywrle_level); + break; + + case 2: + if (vs->clientds.pf.gmax > 0x1F) { + if (be) { + zrle_encode_16be(vs, x, y, w, h, zywrle_level); + } else { + zrle_encode_16le(vs, x, y, w, h, zywrle_level); + } + } else { + if (be) { + zrle_encode_15be(vs, x, y, w, h, zywrle_level); + } else { + zrle_encode_15le(vs, x, y, w, h, zywrle_level); + } + } + break; + + case 4: + { + bool fits_in_ls3bytes; + bool fits_in_ms3bytes; + + fits_in_ls3bytes = + ((vs->clientds.pf.rmax << vs->clientds.pf.rshift) < (1 << 24) && + (vs->clientds.pf.gmax << vs->clientds.pf.gshift) < (1 << 24) && + (vs->clientds.pf.bmax << vs->clientds.pf.bshift) < (1 << 24)); + + fits_in_ms3bytes = (vs->clientds.pf.rshift > 7 && + vs->clientds.pf.gshift > 7 && + vs->clientds.pf.bshift > 7); + + if ((fits_in_ls3bytes && !be) || (fits_in_ms3bytes && be)) { + if (be) { + zrle_encode_24abe(vs, x, y, w, h, zywrle_level); + } else { + zrle_encode_24ale(vs, x, y, w, h, zywrle_level); + } + } else if ((fits_in_ls3bytes && be) || (fits_in_ms3bytes && !be)) { + if (be) { + zrle_encode_24bbe(vs, x, y, w, h, zywrle_level); + } else { + zrle_encode_24ble(vs, x, y, w, h, zywrle_level); + } + } else { + if (be) { + zrle_encode_32be(vs, x, y, w, h, zywrle_level); + } else { + zrle_encode_32le(vs, x, y, w, h, zywrle_level); + } + } + } + break; + } + + vnc_zrle_stop(vs); + bytes = zrle_compress_data(vs, Z_DEFAULT_COMPRESSION); + vnc_framebuffer_update(vs, x, y, w, h, vs->zrle.type); + vnc_write_u32(vs, bytes); + vnc_write(vs, vs->zrle.zlib.buffer, vs->zrle.zlib.offset); + return 1; +} +",1," static int zrle_send_framebuffer_update(VncState *vs, int x, int y, + int w, int h) + { + bool be = vs->client_be; + size_t bytes; + int zywrle_level; + + if (vs->zrle.type == VNC_ENCODING_ZYWRLE) { + if (!vs->vd->lossy || vs->tight.quality == (uint8_t)-1 + || vs->tight.quality == 9) { + zywrle_level = 0; + vs->zrle.type = VNC_ENCODING_ZRLE; + } else if (vs->tight.quality < 3) { + zywrle_level = 3; + } else if (vs->tight.quality < 6) { + zywrle_level = 2; + } else { + zywrle_level = 1; + } + } else { + zywrle_level = 0; + } + + vnc_zrle_start(vs); + + switch (vs->client_pf.bytes_per_pixel) { + case 1: + zrle_encode_8ne(vs, x, y, w, h, zywrle_level); + break; + + case 2: + if (vs->client_pf.gmax > 0x1F) { + if (be) { + zrle_encode_16be(vs, x, y, w, h, zywrle_level); + } else { + zrle_encode_16le(vs, x, y, w, h, zywrle_level); + } + } else { + if (be) { + zrle_encode_15be(vs, x, y, w, h, zywrle_level); + } else { + zrle_encode_15le(vs, x, y, w, h, zywrle_level); + } + } + break; + + case 4: + { + bool fits_in_ls3bytes; + bool fits_in_ms3bytes; + + fits_in_ls3bytes = + ((vs->client_pf.rmax << vs->client_pf.rshift) < (1 << 24) && + (vs->client_pf.gmax << vs->client_pf.gshift) < (1 << 24) && + (vs->client_pf.bmax << vs->client_pf.bshift) < (1 << 24)); + + fits_in_ms3bytes = (vs->client_pf.rshift > 7 && + vs->client_pf.gshift > 7 && + vs->client_pf.bshift > 7); + + if ((fits_in_ls3bytes && !be) || (fits_in_ms3bytes && be)) { + if (be) { + zrle_encode_24abe(vs, x, y, w, h, zywrle_level); + } else { + zrle_encode_24ale(vs, x, y, w, h, zywrle_level); + } + } else if ((fits_in_ls3bytes && be) || (fits_in_ms3bytes && !be)) { + if (be) { + zrle_encode_24bbe(vs, x, y, w, h, zywrle_level); + } else { + zrle_encode_24ble(vs, x, y, w, h, zywrle_level); + } + } else { + if (be) { + zrle_encode_32be(vs, x, y, w, h, zywrle_level); + } else { + zrle_encode_32le(vs, x, y, w, h, zywrle_level); + } + } + } + break; + } + + vnc_zrle_stop(vs); + bytes = zrle_compress_data(vs, Z_DEFAULT_COMPRESSION); + vnc_framebuffer_update(vs, x, y, w, h, vs->zrle.type); + vnc_write_u32(vs, bytes); + vnc_write(vs, vs->zrle.zlib.buffer, vs->zrle.zlib.offset); + return 1; +} +","@@ -255,7 +255,7 @@ static void zrle_write_u8(VncState *vs, uint8_t value) + static int zrle_send_framebuffer_update(VncState *vs, int x, int y, + int w, int h) + { +- bool be = !!(vs->clientds.flags & QEMU_BIG_ENDIAN_FLAG); ++ bool be = vs->client_be; + size_t bytes; + int zywrle_level; + +@@ -277,13 +277,13 @@ static int zrle_send_framebuffer_update(VncState *vs, int x, int y, + + vnc_zrle_start(vs); + +- switch(vs->clientds.pf.bytes_per_pixel) { ++ switch (vs->client_pf.bytes_per_pixel) { + case 1: + zrle_encode_8ne(vs, x, y, w, h, zywrle_level); + break; + + case 2: +- if (vs->clientds.pf.gmax > 0x1F) { ++ if (vs->client_pf.gmax > 0x1F) { + if (be) { + zrle_encode_16be(vs, x, y, w, h, zywrle_level); + } else { +@@ -304,13 +304,13 @@ static int zrle_send_framebuffer_update(VncState *vs, int x, int y, + bool fits_in_ms3bytes; + + fits_in_ls3bytes = +- ((vs->clientds.pf.rmax << vs->clientds.pf.rshift) < (1 << 24) && +- (vs->clientds.pf.gmax << vs->clientds.pf.gshift) < (1 << 24) && +- (vs->clientds.pf.bmax << vs->clientds.pf.bshift) < (1 << 24)); ++ ((vs->client_pf.rmax << vs->client_pf.rshift) < (1 << 24) && ++ (vs->client_pf.gmax << vs->client_pf.gshift) < (1 << 24) && ++ (vs->client_pf.bmax << vs->client_pf.bshift) < (1 << 24)); + +- fits_in_ms3bytes = (vs->clientds.pf.rshift > 7 && +- vs->clientds.pf.gshift > 7 && +- vs->clientds.pf.bshift > 7); ++ fits_in_ms3bytes = (vs->client_pf.rshift > 7 && ++ vs->client_pf.gshift > 7 && ++ vs->client_pf.bshift > 7); + + if ((fits_in_ls3bytes && !be) || (fits_in_ms3bytes && be)) { + if (be) {",933,1264,2048 +9676,"static struct rtable *__mkroute_output(const struct fib_result *res, + const struct flowi4 *fl4, int orig_oif, + struct net_device *dev_out, + unsigned int flags) +{ + struct fib_info *fi = res->fi; + struct fib_nh_exception *fnhe; + struct in_device *in_dev; + u16 type = res->type; + struct rtable *rth; + bool do_cache; + + in_dev = __in_dev_get_rcu(dev_out); + if (!in_dev) + return ERR_PTR(-EINVAL); + + if (likely(!IN_DEV_ROUTE_LOCALNET(in_dev))) + if (ipv4_is_loopback(fl4->saddr) && !(dev_out->flags & IFF_LOOPBACK)) + return ERR_PTR(-EINVAL); + + if (ipv4_is_lbcast(fl4->daddr)) + type = RTN_BROADCAST; + else if (ipv4_is_multicast(fl4->daddr)) + type = RTN_MULTICAST; + else if (ipv4_is_zeronet(fl4->daddr)) + return ERR_PTR(-EINVAL); + + if (dev_out->flags & IFF_LOOPBACK) + flags |= RTCF_LOCAL; + + do_cache = true; + if (type == RTN_BROADCAST) { + flags |= RTCF_BROADCAST | RTCF_LOCAL; + fi = NULL; + } else if (type == RTN_MULTICAST) { + flags |= RTCF_MULTICAST | RTCF_LOCAL; + if (!ip_check_mc_rcu(in_dev, fl4->daddr, fl4->saddr, + fl4->flowi4_proto)) + flags &= ~RTCF_LOCAL; + else + do_cache = false; + /* If multicast route do not exist use + * default one, but do not gateway in this case. + * Yes, it is hack. + */ + if (fi && res->prefixlen < 4) + fi = NULL; + } else if ((type == RTN_LOCAL) && (orig_oif != 0) && + (orig_oif != dev_out->ifindex)) { + /* For local routes that require a particular output interface + * we do not want to cache the result. Caching the result + * causes incorrect behaviour when there are multiple source + * addresses on the interface, the end result being that if the + * intended recipient is waiting on that interface for the + * packet he won't receive it because it will be delivered on + * the loopback interface and the IP_PKTINFO ipi_ifindex will + * be set to the loopback interface as well. + */ + fi = NULL; + } + + fnhe = NULL; + do_cache &= fi != NULL; + if (do_cache) { + struct rtable __rcu **prth; + struct fib_nh *nh = &FIB_RES_NH(*res); + + fnhe = find_exception(nh, fl4->daddr); + if (fnhe) + prth = &fnhe->fnhe_rth_output; + else { + if (unlikely(fl4->flowi4_flags & + FLOWI_FLAG_KNOWN_NH && + !(nh->nh_gw && + nh->nh_scope == RT_SCOPE_LINK))) { + do_cache = false; + goto add; + } + prth = raw_cpu_ptr(nh->nh_pcpu_rth_output); + } + rth = rcu_dereference(*prth); + if (rt_cache_valid(rth)) { + dst_hold(&rth->dst); + return rth; + } + } + +add: + rth = rt_dst_alloc(dev_out, + IN_DEV_CONF_GET(in_dev, NOPOLICY), + IN_DEV_CONF_GET(in_dev, NOXFRM), + do_cache); + if (!rth) + return ERR_PTR(-ENOBUFS); + + rth->dst.output = ip_output; + + rth->rt_genid = rt_genid_ipv4(dev_net(dev_out)); + rth->rt_flags = flags; + rth->rt_type = type; + rth->rt_is_input = 0; + rth->rt_iif = orig_oif ? : 0; + rth->rt_pmtu = 0; + rth->rt_gateway = 0; + rth->rt_uses_gateway = 0; + INIT_LIST_HEAD(&rth->rt_uncached); + + RT_CACHE_STAT_INC(out_slow_tot); + + if (flags & RTCF_LOCAL) + rth->dst.input = ip_local_deliver; + if (flags & (RTCF_BROADCAST | RTCF_MULTICAST)) { + if (flags & RTCF_LOCAL && + !(dev_out->flags & IFF_LOOPBACK)) { + rth->dst.output = ip_mc_output; + RT_CACHE_STAT_INC(out_slow_mc); + } +#ifdef CONFIG_IP_MROUTE + if (type == RTN_MULTICAST) { + if (IN_DEV_MFORWARD(in_dev) && + !ipv4_is_local_multicast(fl4->daddr)) { + rth->dst.input = ip_mr_input; + rth->dst.output = ip_mc_output; + } + } +#endif + } + + rt_set_nexthop(rth, fl4->daddr, res, fnhe, fi, type, 0); + + return rth; +} +",0,"static struct rtable *__mkroute_output(const struct fib_result *res, + const struct flowi4 *fl4, int orig_oif, + struct net_device *dev_out, + unsigned int flags) +{ + struct fib_info *fi = res->fi; + struct fib_nh_exception *fnhe; + struct in_device *in_dev; + u16 type = res->type; + struct rtable *rth; + bool do_cache; + + in_dev = __in_dev_get_rcu(dev_out); + if (!in_dev) + return ERR_PTR(-EINVAL); + + if (likely(!IN_DEV_ROUTE_LOCALNET(in_dev))) + if (ipv4_is_loopback(fl4->saddr) && !(dev_out->flags & IFF_LOOPBACK)) + return ERR_PTR(-EINVAL); + + if (ipv4_is_lbcast(fl4->daddr)) + type = RTN_BROADCAST; + else if (ipv4_is_multicast(fl4->daddr)) + type = RTN_MULTICAST; + else if (ipv4_is_zeronet(fl4->daddr)) + return ERR_PTR(-EINVAL); + + if (dev_out->flags & IFF_LOOPBACK) + flags |= RTCF_LOCAL; + + do_cache = true; + if (type == RTN_BROADCAST) { + flags |= RTCF_BROADCAST | RTCF_LOCAL; + fi = NULL; + } else if (type == RTN_MULTICAST) { + flags |= RTCF_MULTICAST | RTCF_LOCAL; + if (!ip_check_mc_rcu(in_dev, fl4->daddr, fl4->saddr, + fl4->flowi4_proto)) + flags &= ~RTCF_LOCAL; + else + do_cache = false; + /* If multicast route do not exist use + * default one, but do not gateway in this case. + * Yes, it is hack. + */ + if (fi && res->prefixlen < 4) + fi = NULL; + } else if ((type == RTN_LOCAL) && (orig_oif != 0) && + (orig_oif != dev_out->ifindex)) { + /* For local routes that require a particular output interface + * we do not want to cache the result. Caching the result + * causes incorrect behaviour when there are multiple source + * addresses on the interface, the end result being that if the + * intended recipient is waiting on that interface for the + * packet he won't receive it because it will be delivered on + * the loopback interface and the IP_PKTINFO ipi_ifindex will + * be set to the loopback interface as well. + */ + fi = NULL; + } + + fnhe = NULL; + do_cache &= fi != NULL; + if (do_cache) { + struct rtable __rcu **prth; + struct fib_nh *nh = &FIB_RES_NH(*res); + + fnhe = find_exception(nh, fl4->daddr); + if (fnhe) + prth = &fnhe->fnhe_rth_output; + else { + if (unlikely(fl4->flowi4_flags & + FLOWI_FLAG_KNOWN_NH && + !(nh->nh_gw && + nh->nh_scope == RT_SCOPE_LINK))) { + do_cache = false; + goto add; + } + prth = raw_cpu_ptr(nh->nh_pcpu_rth_output); + } + rth = rcu_dereference(*prth); + if (rt_cache_valid(rth)) { + dst_hold(&rth->dst); + return rth; + } + } + +add: + rth = rt_dst_alloc(dev_out, + IN_DEV_CONF_GET(in_dev, NOPOLICY), + IN_DEV_CONF_GET(in_dev, NOXFRM), + do_cache); + if (!rth) + return ERR_PTR(-ENOBUFS); + + rth->dst.output = ip_output; + + rth->rt_genid = rt_genid_ipv4(dev_net(dev_out)); + rth->rt_flags = flags; + rth->rt_type = type; + rth->rt_is_input = 0; + rth->rt_iif = orig_oif ? : 0; + rth->rt_pmtu = 0; + rth->rt_gateway = 0; + rth->rt_uses_gateway = 0; + INIT_LIST_HEAD(&rth->rt_uncached); + + RT_CACHE_STAT_INC(out_slow_tot); + + if (flags & RTCF_LOCAL) + rth->dst.input = ip_local_deliver; + if (flags & (RTCF_BROADCAST | RTCF_MULTICAST)) { + if (flags & RTCF_LOCAL && + !(dev_out->flags & IFF_LOOPBACK)) { + rth->dst.output = ip_mc_output; + RT_CACHE_STAT_INC(out_slow_mc); + } +#ifdef CONFIG_IP_MROUTE + if (type == RTN_MULTICAST) { + if (IN_DEV_MFORWARD(in_dev) && + !ipv4_is_local_multicast(fl4->daddr)) { + rth->dst.input = ip_mr_input; + rth->dst.output = ip_mc_output; + } + } +#endif + } + + rt_set_nexthop(rth, fl4->daddr, res, fnhe, fi, type, 0); + + return rth; +} +","@@ -488,13 +488,15 @@ EXPORT_SYMBOL(ip_idents_reserve); + void __ip_select_ident(struct iphdr *iph, int segs) + { + static u32 ip_idents_hashrnd __read_mostly; ++ static u32 ip_idents_hashrnd_extra __read_mostly; + u32 hash, id; + + net_get_random_once(&ip_idents_hashrnd, sizeof(ip_idents_hashrnd)); ++ net_get_random_once(&ip_idents_hashrnd_extra, sizeof(ip_idents_hashrnd_extra)); + + hash = jhash_3words((__force u32)iph->daddr, + (__force u32)iph->saddr, +- iph->protocol, ++ iph->protocol ^ ip_idents_hashrnd_extra, + ip_idents_hashrnd); + id = ip_idents_reserve(hash, segs); + iph->id = htons(id);",1121,1452,2048 +6066,"static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu, + struct kvm_enable_cap *cap) +{ + int r; + + if (cap->flags) + return -EINVAL; + + switch (cap->cap) { + case KVM_CAP_PPC_OSI: + r = 0; + vcpu->arch.osi_enabled = true; + break; + case KVM_CAP_PPC_PAPR: + r = 0; + vcpu->arch.papr_enabled = true; + break; + case KVM_CAP_PPC_EPR: + r = 0; + if (cap->args[0]) + vcpu->arch.epr_flags |= KVMPPC_EPR_USER; + else + vcpu->arch.epr_flags &= ~KVMPPC_EPR_USER; + break; +#ifdef CONFIG_BOOKE + case KVM_CAP_PPC_BOOKE_WATCHDOG: + r = 0; + vcpu->arch.watchdog_enabled = true; + break; +#endif +#if defined(CONFIG_KVM_E500V2) || defined(CONFIG_KVM_E500MC) + case KVM_CAP_SW_TLB: { + struct kvm_config_tlb cfg; + void __user *user_ptr = (void __user *)(uintptr_t)cap->args[0]; + + r = -EFAULT; + if (copy_from_user(&cfg, user_ptr, sizeof(cfg))) + break; + + r = kvm_vcpu_ioctl_config_tlb(vcpu, &cfg); + break; + } +#endif +#ifdef CONFIG_KVM_MPIC + case KVM_CAP_IRQ_MPIC: { + struct fd f; + struct kvm_device *dev; + + r = -EBADF; + f = fdget(cap->args[0]); + if (!f.file) + break; + + r = -EPERM; + dev = kvm_device_from_filp(f.file); + if (dev) + r = kvmppc_mpic_connect_vcpu(dev, vcpu, cap->args[1]); + + fdput(f); + break; + } +#endif +#ifdef CONFIG_KVM_XICS + case KVM_CAP_IRQ_XICS: { + struct fd f; + struct kvm_device *dev; + + r = -EBADF; + f = fdget(cap->args[0]); + if (!f.file) + break; + + r = -EPERM; + dev = kvm_device_from_filp(f.file); + if (dev) { + if (xive_enabled()) + r = kvmppc_xive_connect_vcpu(dev, vcpu, cap->args[1]); + else + r = kvmppc_xics_connect_vcpu(dev, vcpu, cap->args[1]); + } + + fdput(f); + break; + } +#endif /* CONFIG_KVM_XICS */ +#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE + case KVM_CAP_PPC_FWNMI: + r = -EINVAL; + if (!is_kvmppc_hv_enabled(vcpu->kvm)) + break; + r = 0; + vcpu->kvm->arch.fwnmi_enabled = true; + break; +#endif /* CONFIG_KVM_BOOK3S_HV_POSSIBLE */ + default: + r = -EINVAL; + break; + } + + if (!r) + r = kvmppc_sanity_check(vcpu); + + return r; +} +",0,"static int kvm_vcpu_ioctl_enable_cap(struct kvm_vcpu *vcpu, + struct kvm_enable_cap *cap) +{ + int r; + + if (cap->flags) + return -EINVAL; + + switch (cap->cap) { + case KVM_CAP_PPC_OSI: + r = 0; + vcpu->arch.osi_enabled = true; + break; + case KVM_CAP_PPC_PAPR: + r = 0; + vcpu->arch.papr_enabled = true; + break; + case KVM_CAP_PPC_EPR: + r = 0; + if (cap->args[0]) + vcpu->arch.epr_flags |= KVMPPC_EPR_USER; + else + vcpu->arch.epr_flags &= ~KVMPPC_EPR_USER; + break; +#ifdef CONFIG_BOOKE + case KVM_CAP_PPC_BOOKE_WATCHDOG: + r = 0; + vcpu->arch.watchdog_enabled = true; + break; +#endif +#if defined(CONFIG_KVM_E500V2) || defined(CONFIG_KVM_E500MC) + case KVM_CAP_SW_TLB: { + struct kvm_config_tlb cfg; + void __user *user_ptr = (void __user *)(uintptr_t)cap->args[0]; + + r = -EFAULT; + if (copy_from_user(&cfg, user_ptr, sizeof(cfg))) + break; + + r = kvm_vcpu_ioctl_config_tlb(vcpu, &cfg); + break; + } +#endif +#ifdef CONFIG_KVM_MPIC + case KVM_CAP_IRQ_MPIC: { + struct fd f; + struct kvm_device *dev; + + r = -EBADF; + f = fdget(cap->args[0]); + if (!f.file) + break; + + r = -EPERM; + dev = kvm_device_from_filp(f.file); + if (dev) + r = kvmppc_mpic_connect_vcpu(dev, vcpu, cap->args[1]); + + fdput(f); + break; + } +#endif +#ifdef CONFIG_KVM_XICS + case KVM_CAP_IRQ_XICS: { + struct fd f; + struct kvm_device *dev; + + r = -EBADF; + f = fdget(cap->args[0]); + if (!f.file) + break; + + r = -EPERM; + dev = kvm_device_from_filp(f.file); + if (dev) { + if (xive_enabled()) + r = kvmppc_xive_connect_vcpu(dev, vcpu, cap->args[1]); + else + r = kvmppc_xics_connect_vcpu(dev, vcpu, cap->args[1]); + } + + fdput(f); + break; + } +#endif /* CONFIG_KVM_XICS */ +#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE + case KVM_CAP_PPC_FWNMI: + r = -EINVAL; + if (!is_kvmppc_hv_enabled(vcpu->kvm)) + break; + r = 0; + vcpu->kvm->arch.fwnmi_enabled = true; + break; +#endif /* CONFIG_KVM_BOOK3S_HV_POSSIBLE */ + default: + r = -EINVAL; + break; + } + + if (!r) + r = kvmppc_sanity_check(vcpu); + + return r; +} +","@@ -644,8 +644,7 @@ int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext) + break; + #endif + case KVM_CAP_PPC_HTM: +- r = cpu_has_feature(CPU_FTR_TM_COMP) && +- is_kvmppc_hv_enabled(kvm); ++ r = cpu_has_feature(CPU_FTR_TM_COMP) && hv_enabled; + break; + default: + r = 0;",706,1037,2048 +979,"int ntpd_main(int argc UNUSED_PARAM, char **argv) +{ +#undef G + struct globals G; + struct pollfd *pfd; + peer_t **idx2peer; + unsigned cnt; + + memset(&G, 0, sizeof(G)); + SET_PTR_TO_GLOBALS(&G); + + ntp_init(argv); + + /* If ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */ + cnt = G.peer_cnt + ENABLE_FEATURE_NTPD_SERVER; + idx2peer = xzalloc(sizeof(idx2peer[0]) * cnt); + pfd = xzalloc(sizeof(pfd[0]) * cnt); + + /* Countdown: we never sync before we sent INITIAL_SAMPLES+1 + * packets to each peer. + * NB: if some peer is not responding, we may end up sending + * fewer packets to it and more to other peers. + * NB2: sync usually happens using INITIAL_SAMPLES packets, + * since last reply does not come back instantaneously. + */ + cnt = G.peer_cnt * (INITIAL_SAMPLES + 1); + + write_pidfile(CONFIG_PID_FILE_PATH ""/ntpd.pid""); + + while (!bb_got_signal) { + llist_t *item; + unsigned i, j; + int nfds, timeout; + double nextaction; + + /* Nothing between here and poll() blocks for any significant time */ + + nextaction = G.cur_time + 3600; + + i = 0; +#if ENABLE_FEATURE_NTPD_SERVER + if (G_listen_fd != -1) { + pfd[0].fd = G_listen_fd; + pfd[0].events = POLLIN; + i++; + } +#endif + /* Pass over peer list, send requests, time out on receives */ + for (item = G.ntp_peers; item != NULL; item = item->link) { + peer_t *p = (peer_t *) item->data; + + if (p->next_action_time <= G.cur_time) { + if (p->p_fd == -1) { + /* Time to send new req */ + if (--cnt == 0) { + VERB4 bb_error_msg(""disabling burst mode""); + G.polladj_count = 0; + G.poll_exp = MINPOLL; + } + send_query_to_peer(p); + } else { + /* Timed out waiting for reply */ + close(p->p_fd); + p->p_fd = -1; + /* If poll interval is small, increase it */ + if (G.poll_exp < BIGPOLL) + adjust_poll(MINPOLL); + timeout = poll_interval(NOREPLY_INTERVAL); + bb_error_msg(""timed out waiting for %s, reach 0x%02x, next query in %us"", + p->p_dotted, p->reachable_bits, timeout); + + /* What if don't see it because it changed its IP? */ + if (p->reachable_bits == 0) + resolve_peer_hostname(p, /*loop_on_fail=*/ 0); + + set_next(p, timeout); + } + } + + if (p->next_action_time < nextaction) + nextaction = p->next_action_time; + + if (p->p_fd >= 0) { + /* Wait for reply from this peer */ + pfd[i].fd = p->p_fd; + pfd[i].events = POLLIN; + idx2peer[i] = p; + i++; + } + } + + timeout = nextaction - G.cur_time; + if (timeout < 0) + timeout = 0; + timeout++; /* (nextaction - G.cur_time) rounds down, compensating */ + + /* Here we may block */ + VERB2 { + if (i > (ENABLE_FEATURE_NTPD_SERVER && G_listen_fd != -1)) { + /* We wait for at least one reply. + * Poll for it, without wasting time for message. + * Since replies often come under 1 second, this also + * reduces clutter in logs. + */ + nfds = poll(pfd, i, 1000); + if (nfds != 0) + goto did_poll; + if (--timeout <= 0) + goto did_poll; + } + bb_error_msg(""poll:%us sockets:%u interval:%us"", timeout, i, 1 << G.poll_exp); + } + nfds = poll(pfd, i, timeout * 1000); + did_poll: + gettime1900d(); /* sets G.cur_time */ + if (nfds <= 0) { + if (!bb_got_signal /* poll wasn't interrupted by a signal */ + && G.cur_time - G.last_script_run > 11*60 + ) { + /* Useful for updating battery-backed RTC and such */ + run_script(""periodic"", G.last_update_offset); + gettime1900d(); /* sets G.cur_time */ + } + goto check_unsync; + } + + /* Process any received packets */ + j = 0; +#if ENABLE_FEATURE_NTPD_SERVER + if (G.listen_fd != -1) { + if (pfd[0].revents /* & (POLLIN|POLLERR)*/) { + nfds--; + recv_and_process_client_pkt(/*G.listen_fd*/); + gettime1900d(); /* sets G.cur_time */ + } + j = 1; + } +#endif + for (; nfds != 0 && j < i; j++) { + if (pfd[j].revents /* & (POLLIN|POLLERR)*/) { + /* + * At init, alarm was set to 10 sec. + * Now we did get a reply. + * Increase timeout to 50 seconds to finish syncing. + */ + if (option_mask32 & OPT_qq) { + option_mask32 &= ~OPT_qq; + alarm(50); + } + nfds--; + recv_and_process_peer_pkt(idx2peer[j]); + gettime1900d(); /* sets G.cur_time */ + } + } + + check_unsync: + if (G.ntp_peers && G.stratum != MAXSTRAT) { + for (item = G.ntp_peers; item != NULL; item = item->link) { + peer_t *p = (peer_t *) item->data; + if (p->reachable_bits) + goto have_reachable_peer; + } + /* No peer responded for last 8 packets, panic */ + clamp_pollexp_and_set_MAXSTRAT(); + run_script(""unsync"", 0.0); + have_reachable_peer: ; + } + } /* while (!bb_got_signal) */ + + remove_pidfile(CONFIG_PID_FILE_PATH ""/ntpd.pid""); + kill_myself_with_sig(bb_got_signal); +} +",0,"int ntpd_main(int argc UNUSED_PARAM, char **argv) +{ +#undef G + struct globals G; + struct pollfd *pfd; + peer_t **idx2peer; + unsigned cnt; + + memset(&G, 0, sizeof(G)); + SET_PTR_TO_GLOBALS(&G); + + ntp_init(argv); + + /* If ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */ + cnt = G.peer_cnt + ENABLE_FEATURE_NTPD_SERVER; + idx2peer = xzalloc(sizeof(idx2peer[0]) * cnt); + pfd = xzalloc(sizeof(pfd[0]) * cnt); + + /* Countdown: we never sync before we sent INITIAL_SAMPLES+1 + * packets to each peer. + * NB: if some peer is not responding, we may end up sending + * fewer packets to it and more to other peers. + * NB2: sync usually happens using INITIAL_SAMPLES packets, + * since last reply does not come back instantaneously. + */ + cnt = G.peer_cnt * (INITIAL_SAMPLES + 1); + + write_pidfile(CONFIG_PID_FILE_PATH ""/ntpd.pid""); + + while (!bb_got_signal) { + llist_t *item; + unsigned i, j; + int nfds, timeout; + double nextaction; + + /* Nothing between here and poll() blocks for any significant time */ + + nextaction = G.cur_time + 3600; + + i = 0; +#if ENABLE_FEATURE_NTPD_SERVER + if (G_listen_fd != -1) { + pfd[0].fd = G_listen_fd; + pfd[0].events = POLLIN; + i++; + } +#endif + /* Pass over peer list, send requests, time out on receives */ + for (item = G.ntp_peers; item != NULL; item = item->link) { + peer_t *p = (peer_t *) item->data; + + if (p->next_action_time <= G.cur_time) { + if (p->p_fd == -1) { + /* Time to send new req */ + if (--cnt == 0) { + VERB4 bb_error_msg(""disabling burst mode""); + G.polladj_count = 0; + G.poll_exp = MINPOLL; + } + send_query_to_peer(p); + } else { + /* Timed out waiting for reply */ + close(p->p_fd); + p->p_fd = -1; + /* If poll interval is small, increase it */ + if (G.poll_exp < BIGPOLL) + adjust_poll(MINPOLL); + timeout = poll_interval(NOREPLY_INTERVAL); + bb_error_msg(""timed out waiting for %s, reach 0x%02x, next query in %us"", + p->p_dotted, p->reachable_bits, timeout); + + /* What if don't see it because it changed its IP? */ + if (p->reachable_bits == 0) + resolve_peer_hostname(p, /*loop_on_fail=*/ 0); + + set_next(p, timeout); + } + } + + if (p->next_action_time < nextaction) + nextaction = p->next_action_time; + + if (p->p_fd >= 0) { + /* Wait for reply from this peer */ + pfd[i].fd = p->p_fd; + pfd[i].events = POLLIN; + idx2peer[i] = p; + i++; + } + } + + timeout = nextaction - G.cur_time; + if (timeout < 0) + timeout = 0; + timeout++; /* (nextaction - G.cur_time) rounds down, compensating */ + + /* Here we may block */ + VERB2 { + if (i > (ENABLE_FEATURE_NTPD_SERVER && G_listen_fd != -1)) { + /* We wait for at least one reply. + * Poll for it, without wasting time for message. + * Since replies often come under 1 second, this also + * reduces clutter in logs. + */ + nfds = poll(pfd, i, 1000); + if (nfds != 0) + goto did_poll; + if (--timeout <= 0) + goto did_poll; + } + bb_error_msg(""poll:%us sockets:%u interval:%us"", timeout, i, 1 << G.poll_exp); + } + nfds = poll(pfd, i, timeout * 1000); + did_poll: + gettime1900d(); /* sets G.cur_time */ + if (nfds <= 0) { + if (!bb_got_signal /* poll wasn't interrupted by a signal */ + && G.cur_time - G.last_script_run > 11*60 + ) { + /* Useful for updating battery-backed RTC and such */ + run_script(""periodic"", G.last_update_offset); + gettime1900d(); /* sets G.cur_time */ + } + goto check_unsync; + } + + /* Process any received packets */ + j = 0; +#if ENABLE_FEATURE_NTPD_SERVER + if (G.listen_fd != -1) { + if (pfd[0].revents /* & (POLLIN|POLLERR)*/) { + nfds--; + recv_and_process_client_pkt(/*G.listen_fd*/); + gettime1900d(); /* sets G.cur_time */ + } + j = 1; + } +#endif + for (; nfds != 0 && j < i; j++) { + if (pfd[j].revents /* & (POLLIN|POLLERR)*/) { + /* + * At init, alarm was set to 10 sec. + * Now we did get a reply. + * Increase timeout to 50 seconds to finish syncing. + */ + if (option_mask32 & OPT_qq) { + option_mask32 &= ~OPT_qq; + alarm(50); + } + nfds--; + recv_and_process_peer_pkt(idx2peer[j]); + gettime1900d(); /* sets G.cur_time */ + } + } + + check_unsync: + if (G.ntp_peers && G.stratum != MAXSTRAT) { + for (item = G.ntp_peers; item != NULL; item = item->link) { + peer_t *p = (peer_t *) item->data; + if (p->reachable_bits) + goto have_reachable_peer; + } + /* No peer responded for last 8 packets, panic */ + clamp_pollexp_and_set_MAXSTRAT(); + run_script(""unsync"", 0.0); + have_reachable_peer: ; + } + } /* while (!bb_got_signal) */ + + remove_pidfile(CONFIG_PID_FILE_PATH ""/ntpd.pid""); + kill_myself_with_sig(bb_got_signal); +} +","@@ -2051,6 +2051,13 @@ recv_and_process_client_pkt(void /*int fd*/) + goto bail; + } + ++ /* Respond only to client and symmetric active packets */ ++ if ((msg.m_status & MODE_MASK) != MODE_CLIENT ++ && (msg.m_status & MODE_MASK) != MODE_SYM_ACT ++ ) { ++ goto bail; ++ } ++ + query_status = msg.m_status; + query_xmttime = msg.m_xmttime;",1487,1818,2048 +17968,"iakerb_gss_init_sec_context(OM_uint32 *minor_status, + gss_cred_id_t claimant_cred_handle, + gss_ctx_id_t *context_handle, + gss_name_t target_name, + gss_OID mech_type, + OM_uint32 req_flags, + OM_uint32 time_req, + gss_channel_bindings_t input_chan_bindings, + gss_buffer_t input_token, + gss_OID *actual_mech_type, + gss_buffer_t output_token, + OM_uint32 *ret_flags, + OM_uint32 *time_rec) +{ + OM_uint32 major_status = GSS_S_FAILURE; + krb5_error_code code; + iakerb_ctx_id_t ctx; + krb5_gss_cred_id_t kcred; + krb5_gss_name_t kname; + krb5_boolean cred_locked = FALSE; + int initialContextToken = (*context_handle == GSS_C_NO_CONTEXT); + + if (initialContextToken) { + code = iakerb_alloc_context(&ctx); + if (code != 0) { + *minor_status = code; + goto cleanup; + } + if (claimant_cred_handle == GSS_C_NO_CREDENTIAL) { + major_status = iakerb_gss_acquire_cred(minor_status, NULL, + GSS_C_INDEFINITE, + GSS_C_NULL_OID_SET, + GSS_C_INITIATE, + &ctx->defcred, NULL, NULL); + if (GSS_ERROR(major_status)) + goto cleanup; + claimant_cred_handle = ctx->defcred; + } + } else { + ctx = (iakerb_ctx_id_t)*context_handle; + if (claimant_cred_handle == GSS_C_NO_CREDENTIAL) + claimant_cred_handle = ctx->defcred; + } + + kname = (krb5_gss_name_t)target_name; + + major_status = kg_cred_resolve(minor_status, ctx->k5c, + claimant_cred_handle, target_name); + if (GSS_ERROR(major_status)) + goto cleanup; + cred_locked = TRUE; + kcred = (krb5_gss_cred_id_t)claimant_cred_handle; + + major_status = GSS_S_FAILURE; + + if (initialContextToken) { + code = iakerb_get_initial_state(ctx, kcred, kname, time_req, + &ctx->state); + if (code != 0) { + *minor_status = code; + goto cleanup; + } + *context_handle = (gss_ctx_id_t)ctx; + } + + if (ctx->state != IAKERB_AP_REQ) { + /* We need to do IAKERB. */ + code = iakerb_initiator_step(ctx, + kcred, + kname, + time_req, + input_token, + output_token); + if (code == KRB5_BAD_MSIZE) + major_status = GSS_S_DEFECTIVE_TOKEN; + if (code != 0) { + *minor_status = code; + goto cleanup; + } + } + + if (ctx->state == IAKERB_AP_REQ) { + krb5_gss_ctx_ext_rec exts; + + if (cred_locked) { + k5_mutex_unlock(&kcred->lock); + cred_locked = FALSE; + } + + iakerb_make_exts(ctx, &exts); + + if (ctx->gssc == GSS_C_NO_CONTEXT) + input_token = GSS_C_NO_BUFFER; + + /* IAKERB is finished, or we skipped to Kerberos directly. */ + major_status = krb5_gss_init_sec_context_ext(minor_status, + (gss_cred_id_t) kcred, + &ctx->gssc, + target_name, + (gss_OID)gss_mech_iakerb, + req_flags, + time_req, + input_chan_bindings, + input_token, + NULL, + output_token, + ret_flags, + time_rec, + &exts); + if (major_status == GSS_S_COMPLETE) { + *context_handle = ctx->gssc; + ctx->gssc = GSS_C_NO_CONTEXT; + iakerb_release_context(ctx); + } + if (actual_mech_type != NULL) + *actual_mech_type = (gss_OID)gss_mech_krb5; + } else { + if (actual_mech_type != NULL) + *actual_mech_type = (gss_OID)gss_mech_iakerb; + if (ret_flags != NULL) + *ret_flags = 0; + if (time_rec != NULL) + *time_rec = 0; + major_status = GSS_S_CONTINUE_NEEDED; + } + +cleanup: + if (cred_locked) + k5_mutex_unlock(&kcred->lock); + if (initialContextToken && GSS_ERROR(major_status)) { + iakerb_release_context(ctx); + *context_handle = GSS_C_NO_CONTEXT; + } + + return major_status; + } +",1,"iakerb_gss_init_sec_context(OM_uint32 *minor_status, + gss_cred_id_t claimant_cred_handle, + gss_ctx_id_t *context_handle, + gss_name_t target_name, + gss_OID mech_type, + OM_uint32 req_flags, + OM_uint32 time_req, + gss_channel_bindings_t input_chan_bindings, + gss_buffer_t input_token, + gss_OID *actual_mech_type, + gss_buffer_t output_token, + OM_uint32 *ret_flags, + OM_uint32 *time_rec) +{ + OM_uint32 major_status = GSS_S_FAILURE; + krb5_error_code code; + iakerb_ctx_id_t ctx; + krb5_gss_cred_id_t kcred; + krb5_gss_name_t kname; + krb5_boolean cred_locked = FALSE; + int initialContextToken = (*context_handle == GSS_C_NO_CONTEXT); + + if (initialContextToken) { + code = iakerb_alloc_context(&ctx, 1); + if (code != 0) { + *minor_status = code; + goto cleanup; + } + if (claimant_cred_handle == GSS_C_NO_CREDENTIAL) { + major_status = iakerb_gss_acquire_cred(minor_status, NULL, + GSS_C_INDEFINITE, + GSS_C_NULL_OID_SET, + GSS_C_INITIATE, + &ctx->defcred, NULL, NULL); + if (GSS_ERROR(major_status)) + goto cleanup; + claimant_cred_handle = ctx->defcred; + } + } else { + ctx = (iakerb_ctx_id_t)*context_handle; + if (claimant_cred_handle == GSS_C_NO_CREDENTIAL) + claimant_cred_handle = ctx->defcred; + } + + kname = (krb5_gss_name_t)target_name; + + major_status = kg_cred_resolve(minor_status, ctx->k5c, + claimant_cred_handle, target_name); + if (GSS_ERROR(major_status)) + goto cleanup; + cred_locked = TRUE; + kcred = (krb5_gss_cred_id_t)claimant_cred_handle; + + major_status = GSS_S_FAILURE; + + if (initialContextToken) { + code = iakerb_get_initial_state(ctx, kcred, kname, time_req, + &ctx->state); + if (code != 0) { + *minor_status = code; + goto cleanup; + } + *context_handle = (gss_ctx_id_t)ctx; + } + + if (ctx->state != IAKERB_AP_REQ) { + /* We need to do IAKERB. */ + code = iakerb_initiator_step(ctx, + kcred, + kname, + time_req, + input_token, + output_token); + if (code == KRB5_BAD_MSIZE) + major_status = GSS_S_DEFECTIVE_TOKEN; + if (code != 0) { + *minor_status = code; + goto cleanup; + } + } + + if (ctx->state == IAKERB_AP_REQ) { + krb5_gss_ctx_ext_rec exts; + + if (cred_locked) { + k5_mutex_unlock(&kcred->lock); + cred_locked = FALSE; + } + + iakerb_make_exts(ctx, &exts); + + if (ctx->gssc == GSS_C_NO_CONTEXT) + input_token = GSS_C_NO_BUFFER; + + /* IAKERB is finished, or we skipped to Kerberos directly. */ + major_status = krb5_gss_init_sec_context_ext(minor_status, + (gss_cred_id_t) kcred, + &ctx->gssc, + target_name, + (gss_OID)gss_mech_iakerb, + req_flags, + time_req, + input_chan_bindings, + input_token, + NULL, + output_token, + ret_flags, + time_rec, + &exts); + if (major_status == GSS_S_COMPLETE) + ctx->established = 1; + if (actual_mech_type != NULL) + *actual_mech_type = (gss_OID)gss_mech_krb5; + } else { + if (actual_mech_type != NULL) + *actual_mech_type = (gss_OID)gss_mech_iakerb; + if (ret_flags != NULL) + *ret_flags = 0; + if (time_rec != NULL) + *time_rec = 0; + major_status = GSS_S_CONTINUE_NEEDED; + } + +cleanup: + if (cred_locked) + k5_mutex_unlock(&kcred->lock); + if (initialContextToken && GSS_ERROR(major_status)) { + iakerb_release_context(ctx); + *context_handle = GSS_C_NO_CONTEXT; + } + + return major_status; + } +","@@ -47,6 +47,8 @@ struct _iakerb_ctx_id_rec { + gss_ctx_id_t gssc; + krb5_data conv; /* conversation for checksumming */ + unsigned int count; /* number of round trips */ ++ int initiate; ++ int established; + krb5_get_init_creds_opt *gic_opts; + }; + +@@ -695,7 +697,7 @@ iakerb_get_initial_state(iakerb_ctx_id_t ctx, + * Allocate and initialise an IAKERB context + */ + static krb5_error_code +-iakerb_alloc_context(iakerb_ctx_id_t *pctx) ++iakerb_alloc_context(iakerb_ctx_id_t *pctx, int initiate) + { + iakerb_ctx_id_t ctx; + krb5_error_code code; +@@ -709,6 +711,8 @@ iakerb_alloc_context(iakerb_ctx_id_t *pctx) + ctx->magic = KG_IAKERB_CONTEXT; + ctx->state = IAKERB_AS_REQ; + ctx->count = 0; ++ ctx->initiate = initiate; ++ ctx->established = 0; + + code = krb5_gss_init_context(&ctx->k5c); + if (code != 0) +@@ -732,31 +736,18 @@ iakerb_gss_delete_sec_context(OM_uint32 *minor_status, + gss_ctx_id_t *context_handle, + gss_buffer_t output_token) + { +- OM_uint32 major_status = GSS_S_COMPLETE; ++ iakerb_ctx_id_t iakerb_ctx = (iakerb_ctx_id_t)*context_handle; + + if (output_token != GSS_C_NO_BUFFER) { + output_token->length = 0; + output_token->value = NULL; + } + + *minor_status = 0; ++ *context_handle = GSS_C_NO_CONTEXT; ++ iakerb_release_context(iakerb_ctx); + +- if (*context_handle != GSS_C_NO_CONTEXT) { +- iakerb_ctx_id_t iakerb_ctx = (iakerb_ctx_id_t)*context_handle; +- +- if (iakerb_ctx->magic == KG_IAKERB_CONTEXT) { +- iakerb_release_context(iakerb_ctx); +- *context_handle = GSS_C_NO_CONTEXT; +- } else { +- assert(iakerb_ctx->magic == KG_CONTEXT); +- +- major_status = krb5_gss_delete_sec_context(minor_status, +- context_handle, +- output_token); +- } +- } +- +- return major_status; ++ return GSS_S_COMPLETE; + } + + static krb5_boolean +@@ -802,7 +793,7 @@ iakerb_gss_accept_sec_context(OM_uint32 *minor_status, + int initialContextToken = (*context_handle == GSS_C_NO_CONTEXT); + + if (initialContextToken) { +- code = iakerb_alloc_context(&ctx); ++ code = iakerb_alloc_context(&ctx, 0); + if (code != 0) + goto cleanup; + +@@ -854,11 +845,8 @@ iakerb_gss_accept_sec_context(OM_uint32 *minor_status, + time_rec, + delegated_cred_handle, + &exts); +- if (major_status == GSS_S_COMPLETE) { +- *context_handle = ctx->gssc; +- ctx->gssc = NULL; +- iakerb_release_context(ctx); +- } ++ if (major_status == GSS_S_COMPLETE) ++ ctx->established = 1; + if (mech_type != NULL) + *mech_type = (gss_OID)gss_mech_krb5; + } +@@ -897,7 +885,7 @@ iakerb_gss_init_sec_context(OM_uint32 *minor_status, + int initialContextToken = (*context_handle == GSS_C_NO_CONTEXT); + + if (initialContextToken) { +- code = iakerb_alloc_context(&ctx); ++ code = iakerb_alloc_context(&ctx, 1); + if (code != 0) { + *minor_status = code; + goto cleanup; +@@ -983,11 +971,8 @@ iakerb_gss_init_sec_context(OM_uint32 *minor_status, + ret_flags, + time_rec, + &exts); +- if (major_status == GSS_S_COMPLETE) { +- *context_handle = ctx->gssc; +- ctx->gssc = GSS_C_NO_CONTEXT; +- iakerb_release_context(ctx); +- } ++ if (major_status == GSS_S_COMPLETE) ++ ctx->established = 1; + if (actual_mech_type != NULL) + *actual_mech_type = (gss_OID)gss_mech_krb5; + } else { +@@ -1010,3 +995,309 @@ iakerb_gss_init_sec_context(OM_uint32 *minor_status, + + return major_status; + } ++ ++OM_uint32 KRB5_CALLCONV ++iakerb_gss_unwrap(OM_uint32 *minor_status, gss_ctx_id_t context_handle, ++ gss_buffer_t input_message_buffer, ++ gss_buffer_t output_message_buffer, int *conf_state, ++ gss_qop_t *qop_state) ++{ ++ iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; ++ ++ if (ctx->gssc == GSS_C_NO_CONTEXT) ++ return GSS_S_NO_CONTEXT; ++ ++ return krb5_gss_unwrap(minor_status, ctx->gssc, input_message_buffer, ++ output_message_buffer, conf_state, qop_state); ++} ++ ++OM_uint32 KRB5_CALLCONV ++iakerb_gss_wrap(OM_uint32 *minor_status, gss_ctx_id_t context_handle, ++ int conf_req_flag, gss_qop_t qop_req, ++ gss_buffer_t input_message_buffer, int *conf_state, ++ gss_buffer_t output_message_buffer) ++{ ++ iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; ++ ++ if (ctx->gssc == GSS_C_NO_CONTEXT) ++ return GSS_S_NO_CONTEXT; ++ ++ return krb5_gss_wrap(minor_status, ctx->gssc, conf_req_flag, qop_req, ++ input_message_buffer, conf_state, ++ output_message_buffer); ++} ++ ++OM_uint32 KRB5_CALLCONV ++iakerb_gss_process_context_token(OM_uint32 *minor_status, ++ const gss_ctx_id_t context_handle, ++ const gss_buffer_t token_buffer) ++{ ++ iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; ++ ++ if (ctx->gssc == GSS_C_NO_CONTEXT) ++ return GSS_S_DEFECTIVE_TOKEN; ++ ++ return krb5_gss_process_context_token(minor_status, ctx->gssc, ++ token_buffer); ++} ++ ++OM_uint32 KRB5_CALLCONV ++iakerb_gss_context_time(OM_uint32 *minor_status, gss_ctx_id_t context_handle, ++ OM_uint32 *time_rec) ++{ ++ iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; ++ ++ if (ctx->gssc == GSS_C_NO_CONTEXT) ++ return GSS_S_NO_CONTEXT; ++ ++ return krb5_gss_context_time(minor_status, ctx->gssc, time_rec); ++} ++ ++#ifndef LEAN_CLIENT ++ ++OM_uint32 KRB5_CALLCONV ++iakerb_gss_export_sec_context(OM_uint32 *minor_status, ++ gss_ctx_id_t *context_handle, ++ gss_buffer_t interprocess_token) ++{ ++ OM_uint32 maj; ++ iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; ++ ++ /* We don't currently support exporting partially established contexts. */ ++ if (!ctx->established) ++ return GSS_S_UNAVAILABLE; ++ ++ maj = krb5_gss_export_sec_context(minor_status, &ctx->gssc, ++ interprocess_token); ++ if (ctx->gssc == GSS_C_NO_CONTEXT) { ++ iakerb_release_context(ctx); ++ *context_handle = GSS_C_NO_CONTEXT; ++ } ++ return maj; ++} ++ ++/* ++ * Until we implement partial context exports, there are no SPNEGO exported ++ * context tokens, only tokens for the underlying krb5 context. So we do not ++ * need to implement an iakerb_gss_import_sec_context() yet; it would be ++ * unreachable except via a manually constructed token. ++ */ ++ ++#endif /* LEAN_CLIENT */ ++ ++OM_uint32 KRB5_CALLCONV ++iakerb_gss_inquire_context(OM_uint32 *minor_status, ++ gss_ctx_id_t context_handle, gss_name_t *src_name, ++ gss_name_t *targ_name, OM_uint32 *lifetime_rec, ++ gss_OID *mech_type, OM_uint32 *ctx_flags, ++ int *initiate, int *opened) ++{ ++ OM_uint32 ret; ++ iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; ++ ++ if (src_name != NULL) ++ *src_name = GSS_C_NO_NAME; ++ if (targ_name != NULL) ++ *targ_name = GSS_C_NO_NAME; ++ if (lifetime_rec != NULL) ++ *lifetime_rec = 0; ++ if (mech_type != NULL) ++ *mech_type = (gss_OID)gss_mech_iakerb; ++ if (ctx_flags != NULL) ++ *ctx_flags = 0; ++ if (initiate != NULL) ++ *initiate = ctx->initiate; ++ if (opened != NULL) ++ *opened = ctx->established; ++ ++ if (ctx->gssc == GSS_C_NO_CONTEXT) ++ return GSS_S_COMPLETE; ++ ++ ret = krb5_gss_inquire_context(minor_status, ctx->gssc, src_name, ++ targ_name, lifetime_rec, mech_type, ++ ctx_flags, initiate, opened); ++ ++ if (!ctx->established) { ++ /* Report IAKERB as the mech OID until the context is established. */ ++ if (mech_type != NULL) ++ *mech_type = (gss_OID)gss_mech_iakerb; ++ ++ /* We don't support exporting partially-established contexts. */ ++ if (ctx_flags != NULL) ++ *ctx_flags &= ~GSS_C_TRANS_FLAG; ++ } ++ ++ return ret; ++} ++ ++OM_uint32 KRB5_CALLCONV ++iakerb_gss_wrap_size_limit(OM_uint32 *minor_status, ++ gss_ctx_id_t context_handle, int conf_req_flag, ++ gss_qop_t qop_req, OM_uint32 req_output_size, ++ OM_uint32 *max_input_size) ++{ ++ iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; ++ ++ if (ctx->gssc == GSS_C_NO_CONTEXT) ++ return GSS_S_NO_CONTEXT; ++ ++ return krb5_gss_wrap_size_limit(minor_status, ctx->gssc, conf_req_flag, ++ qop_req, req_output_size, max_input_size); ++} ++ ++OM_uint32 KRB5_CALLCONV ++iakerb_gss_get_mic(OM_uint32 *minor_status, gss_ctx_id_t context_handle, ++ gss_qop_t qop_req, gss_buffer_t message_buffer, ++ gss_buffer_t message_token) ++{ ++ iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; ++ ++ if (ctx->gssc == GSS_C_NO_CONTEXT) ++ return GSS_S_NO_CONTEXT; ++ ++ return krb5_gss_get_mic(minor_status, ctx->gssc, qop_req, message_buffer, ++ message_token); ++} ++ ++OM_uint32 KRB5_CALLCONV ++iakerb_gss_verify_mic(OM_uint32 *minor_status, gss_ctx_id_t context_handle, ++ gss_buffer_t msg_buffer, gss_buffer_t token_buffer, ++ gss_qop_t *qop_state) ++{ ++ iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; ++ ++ if (ctx->gssc == GSS_C_NO_CONTEXT) ++ return GSS_S_NO_CONTEXT; ++ ++ return krb5_gss_verify_mic(minor_status, ctx->gssc, msg_buffer, ++ token_buffer, qop_state); ++} ++ ++OM_uint32 KRB5_CALLCONV ++iakerb_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) ++{ ++ iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; ++ ++ if (ctx->gssc == GSS_C_NO_CONTEXT) ++ return GSS_S_UNAVAILABLE; ++ ++ return krb5_gss_inquire_sec_context_by_oid(minor_status, ctx->gssc, ++ desired_object, data_set); ++} ++ ++OM_uint32 KRB5_CALLCONV ++iakerb_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) ++{ ++ iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)*context_handle; ++ ++ if (ctx == NULL || ctx->gssc == GSS_C_NO_CONTEXT) ++ return GSS_S_UNAVAILABLE; ++ ++ return krb5_gss_set_sec_context_option(minor_status, &ctx->gssc, ++ desired_object, value); ++} ++ ++OM_uint32 KRB5_CALLCONV ++iakerb_gss_wrap_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, ++ int conf_req_flag, gss_qop_t qop_req, int *conf_state, ++ gss_iov_buffer_desc *iov, int iov_count) ++{ ++ iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; ++ ++ if (ctx->gssc == GSS_C_NO_CONTEXT) ++ return GSS_S_NO_CONTEXT; ++ ++ return krb5_gss_wrap_iov(minor_status, ctx->gssc, conf_req_flag, qop_req, ++ conf_state, iov, iov_count); ++} ++ ++OM_uint32 KRB5_CALLCONV ++iakerb_gss_unwrap_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, ++ int *conf_state, gss_qop_t *qop_state, ++ gss_iov_buffer_desc *iov, int iov_count) ++{ ++ iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; ++ ++ if (ctx->gssc == GSS_C_NO_CONTEXT) ++ return GSS_S_NO_CONTEXT; ++ ++ return krb5_gss_unwrap_iov(minor_status, ctx->gssc, conf_state, qop_state, ++ iov, iov_count); ++} ++ ++OM_uint32 KRB5_CALLCONV ++iakerb_gss_wrap_iov_length(OM_uint32 *minor_status, ++ gss_ctx_id_t context_handle, int conf_req_flag, ++ gss_qop_t qop_req, int *conf_state, ++ gss_iov_buffer_desc *iov, int iov_count) ++{ ++ iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; ++ ++ if (ctx->gssc == GSS_C_NO_CONTEXT) ++ return GSS_S_NO_CONTEXT; ++ ++ return krb5_gss_wrap_iov_length(minor_status, ctx->gssc, conf_req_flag, ++ qop_req, conf_state, iov, iov_count); ++} ++ ++OM_uint32 KRB5_CALLCONV ++iakerb_gss_pseudo_random(OM_uint32 *minor_status, gss_ctx_id_t context_handle, ++ int prf_key, const gss_buffer_t prf_in, ++ ssize_t desired_output_len, gss_buffer_t prf_out) ++{ ++ iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; ++ ++ if (ctx->gssc == GSS_C_NO_CONTEXT) ++ return GSS_S_NO_CONTEXT; ++ ++ return krb5_gss_pseudo_random(minor_status, ctx->gssc, prf_key, prf_in, ++ desired_output_len, prf_out); ++} ++ ++OM_uint32 KRB5_CALLCONV ++iakerb_gss_get_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, ++ gss_qop_t qop_req, gss_iov_buffer_desc *iov, ++ int iov_count) ++{ ++ iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; ++ ++ if (ctx->gssc == GSS_C_NO_CONTEXT) ++ return GSS_S_NO_CONTEXT; ++ ++ return krb5_gss_get_mic_iov(minor_status, ctx->gssc, qop_req, iov, ++ iov_count); ++} ++ ++OM_uint32 KRB5_CALLCONV ++iakerb_gss_verify_mic_iov(OM_uint32 *minor_status, gss_ctx_id_t context_handle, ++ gss_qop_t *qop_state, gss_iov_buffer_desc *iov, ++ int iov_count) ++{ ++ iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; ++ ++ if (ctx->gssc == GSS_C_NO_CONTEXT) ++ return GSS_S_NO_CONTEXT; ++ ++ return krb5_gss_verify_mic_iov(minor_status, ctx->gssc, qop_state, iov, ++ iov_count); ++} ++ ++OM_uint32 KRB5_CALLCONV ++iakerb_gss_get_mic_iov_length(OM_uint32 *minor_status, ++ gss_ctx_id_t context_handle, gss_qop_t qop_req, ++ gss_iov_buffer_desc *iov, int iov_count) ++{ ++ iakerb_ctx_id_t ctx = (iakerb_ctx_id_t)context_handle; ++ ++ if (ctx->gssc == GSS_C_NO_CONTEXT) ++ return GSS_S_NO_CONTEXT; ++ ++ return krb5_gss_get_mic_iov_length(minor_status, ctx->gssc, qop_req, iov, ++ iov_count); ++}",1059,1390,2048 +295,"get_pdf14_device_proto(gx_device * dev, pdf14_device ** pdevproto, + pdf14_device * ptempdevproto, gs_gstate * pgs, + const gs_pdf14trans_t * pdf14pct, bool use_pdf14_accum) +{ + bool using_blend_cs; + pdf14_default_colorspace_t dev_cs = + pdf14_determine_default_blend_cs(dev, use_pdf14_accum, + &using_blend_cs); + + switch (dev_cs) { + case PDF14_DeviceGray: + *pdevproto = (pdf14_device *)&gs_pdf14_Gray_device; + *ptempdevproto = **pdevproto; + ptempdevproto->color_info.max_components = 1; + ptempdevproto->color_info.num_components = + ptempdevproto->color_info.max_components; + ptempdevproto->color_info.max_gray = 255; + ptempdevproto->color_info.gray_index = 0; /* Avoid halftoning */ + ptempdevproto->color_info.dither_grays = 256; + ptempdevproto->sep_device = false; + *pdevproto = ptempdevproto; + break; + case PDF14_DeviceRGB: + *pdevproto = (pdf14_device *)&gs_pdf14_RGB_device; + *ptempdevproto = **pdevproto; + ptempdevproto->sep_device = false; + *pdevproto = ptempdevproto; + break; + case PDF14_DeviceCMYK: + *pdevproto = (pdf14_device *)&gs_pdf14_CMYK_device; + *ptempdevproto = **pdevproto; + ptempdevproto->sep_device = false; + *pdevproto = ptempdevproto; + break; + case PDF14_DeviceCMYKspot: + *pdevproto = (pdf14_device *)&gs_pdf14_CMYKspot_device; + /* Need to figure out how we want to handle the device profile + for this case */ + /* + * The number of components for the PDF14 device is the sum + * of the process components and the number of spot colors + * for the page. + */ + if (pdf14pct->params.num_spot_colors >= 0) { + *ptempdevproto = **pdevproto; + ptempdevproto->devn_params.page_spot_colors = + pdf14pct->params.num_spot_colors; + ptempdevproto->color_info.num_components = + ptempdevproto->devn_params.num_std_colorant_names + + pdf14pct->params.num_spot_colors; + if (ptempdevproto->color_info.num_components > + GS_CLIENT_COLOR_MAX_COMPONENTS) + ptempdevproto->color_info.num_components = + GS_CLIENT_COLOR_MAX_COMPONENTS; + ptempdevproto->color_info.depth = + ptempdevproto->color_info.num_components * 8; + ptempdevproto->sep_device = true; + *pdevproto = ptempdevproto; + } + break; + case PDF14_DeviceCustom: + /* + * We are using the output device's process color model. The + * color_info for the PDF 1.4 compositing device needs to match + * the output device. + */ + *ptempdevproto = gs_pdf14_custom_device; + ptempdevproto->color_info = dev->color_info; + /* The pdf14 device has to be 8 bit continuous tone. Force it */ + ptempdevproto->color_info.depth = + ptempdevproto->color_info.num_components * 8; + ptempdevproto->color_info.max_gray = 255; + ptempdevproto->color_info.max_color = 255; + ptempdevproto->color_info.dither_grays = 256; + ptempdevproto->color_info.dither_colors = 256; + + *pdevproto = ptempdevproto; + break; + default: /* Should not occur */ + return_error(gs_error_rangecheck); + } + ptempdevproto->using_blend_cs = using_blend_cs; + return 0; +} +",0,"get_pdf14_device_proto(gx_device * dev, pdf14_device ** pdevproto, + pdf14_device * ptempdevproto, gs_gstate * pgs, + const gs_pdf14trans_t * pdf14pct, bool use_pdf14_accum) +{ + bool using_blend_cs; + pdf14_default_colorspace_t dev_cs = + pdf14_determine_default_blend_cs(dev, use_pdf14_accum, + &using_blend_cs); + + switch (dev_cs) { + case PDF14_DeviceGray: + *pdevproto = (pdf14_device *)&gs_pdf14_Gray_device; + *ptempdevproto = **pdevproto; + ptempdevproto->color_info.max_components = 1; + ptempdevproto->color_info.num_components = + ptempdevproto->color_info.max_components; + ptempdevproto->color_info.max_gray = 255; + ptempdevproto->color_info.gray_index = 0; /* Avoid halftoning */ + ptempdevproto->color_info.dither_grays = 256; + ptempdevproto->sep_device = false; + *pdevproto = ptempdevproto; + break; + case PDF14_DeviceRGB: + *pdevproto = (pdf14_device *)&gs_pdf14_RGB_device; + *ptempdevproto = **pdevproto; + ptempdevproto->sep_device = false; + *pdevproto = ptempdevproto; + break; + case PDF14_DeviceCMYK: + *pdevproto = (pdf14_device *)&gs_pdf14_CMYK_device; + *ptempdevproto = **pdevproto; + ptempdevproto->sep_device = false; + *pdevproto = ptempdevproto; + break; + case PDF14_DeviceCMYKspot: + *pdevproto = (pdf14_device *)&gs_pdf14_CMYKspot_device; + /* Need to figure out how we want to handle the device profile + for this case */ + /* + * The number of components for the PDF14 device is the sum + * of the process components and the number of spot colors + * for the page. + */ + if (pdf14pct->params.num_spot_colors >= 0) { + *ptempdevproto = **pdevproto; + ptempdevproto->devn_params.page_spot_colors = + pdf14pct->params.num_spot_colors; + ptempdevproto->color_info.num_components = + ptempdevproto->devn_params.num_std_colorant_names + + pdf14pct->params.num_spot_colors; + if (ptempdevproto->color_info.num_components > + GS_CLIENT_COLOR_MAX_COMPONENTS) + ptempdevproto->color_info.num_components = + GS_CLIENT_COLOR_MAX_COMPONENTS; + ptempdevproto->color_info.depth = + ptempdevproto->color_info.num_components * 8; + ptempdevproto->sep_device = true; + *pdevproto = ptempdevproto; + } + break; + case PDF14_DeviceCustom: + /* + * We are using the output device's process color model. The + * color_info for the PDF 1.4 compositing device needs to match + * the output device. + */ + *ptempdevproto = gs_pdf14_custom_device; + ptempdevproto->color_info = dev->color_info; + /* The pdf14 device has to be 8 bit continuous tone. Force it */ + ptempdevproto->color_info.depth = + ptempdevproto->color_info.num_components * 8; + ptempdevproto->color_info.max_gray = 255; + ptempdevproto->color_info.max_color = 255; + ptempdevproto->color_info.dither_grays = 256; + ptempdevproto->color_info.dither_colors = 256; + + *pdevproto = ptempdevproto; + break; + default: /* Should not occur */ + return_error(gs_error_rangecheck); + } + ptempdevproto->using_blend_cs = using_blend_cs; + return 0; +} +","@@ -178,6 +178,7 @@ static dev_proc_fill_mask(pdf14_fill_mask); + static dev_proc_stroke_path(pdf14_stroke_path); + static dev_proc_begin_typed_image(pdf14_begin_typed_image); + static dev_proc_text_begin(pdf14_text_begin); ++static dev_proc_finish_copydevice(pdf14_finish_copydevice); + static dev_proc_create_compositor(pdf14_create_compositor); + static dev_proc_create_compositor(pdf14_forward_create_compositor); + static dev_proc_begin_transparency_group(pdf14_begin_transparency_group); +@@ -245,7 +246,7 @@ static const gx_color_map_procs * + pdf14_create_compositor, /* create_compositor */\ + NULL, /* get_hardware_params */\ + pdf14_text_begin, /* text_begin */\ +- NULL, /* finish_copydevice */\ ++ pdf14_finish_copydevice, /* finish_copydevice */\ + pdf14_begin_transparency_group,\ + pdf14_end_transparency_group,\ + pdf14_begin_transparency_mask,\ +@@ -3935,6 +3936,19 @@ pdf14_text_begin(gx_device * dev, gs_gstate * pgs, + return code; + } + ++static int ++pdf14_finish_copydevice(gx_device *new_dev, const gx_device *from_dev) ++{ ++ pdf14_device *pdev = (pdf14_device*)new_dev; ++ ++ pdev->ctx = NULL; ++ pdev->trans_group_parent_cmap_procs = NULL; ++ pdev->smaskcolor = NULL; ++ ++ /* Only allow copying the prototype. */ ++ return (from_dev->memory ? gs_note_error(gs_error_rangecheck) : 0); ++} ++ + /* + * Implement copy_mono by filling lots of small rectangles. + */ +@@ -8093,6 +8107,7 @@ c_pdf14trans_clist_read_update(gs_composite_t * pcte, gx_device * cdev, + before reopening the device */ + if (p14dev->ctx != NULL) { + pdf14_ctx_free(p14dev->ctx); ++ p14dev->ctx = NULL; + } + dev_proc(tdev, open_device) (tdev); + }",905,1236,2048 +8629,"crm_ipcs_sendv(crm_client_t * c, struct iovec * iov, enum crm_ipc_flags flags) +{ + ssize_t rc; + static uint32_t id = 1; + struct crm_ipc_response_header *header = iov[0].iov_base; + + if (c->flags & crm_client_flag_ipc_proxied) { + /* _ALL_ replies to proxied connections need to be sent as events */ + if (is_not_set(flags, crm_ipc_server_event)) { + flags |= crm_ipc_server_event; + /* this flag lets us know this was originally meant to be a response. + * even though we're sending it over the event channel. */ + flags |= crm_ipc_proxied_relay_response; + } + } + + header->flags |= flags; + if (flags & crm_ipc_server_event) { + header->qb.id = id++; /* We don't really use it, but doesn't hurt to set one */ + + if (flags & crm_ipc_server_free) { + crm_trace(""Sending the original to %p[%d]"", c->ipcs, c->pid); + c->event_queue = g_list_append(c->event_queue, iov); + + } else { + struct iovec *iov_copy = calloc(2, sizeof(struct iovec)); + + crm_trace(""Sending a copy to %p[%d]"", c->ipcs, c->pid); + iov_copy[0].iov_len = iov[0].iov_len; + iov_copy[0].iov_base = malloc(iov[0].iov_len); + memcpy(iov_copy[0].iov_base, iov[0].iov_base, iov[0].iov_len); + + iov_copy[1].iov_len = iov[1].iov_len; + iov_copy[1].iov_base = malloc(iov[1].iov_len); + memcpy(iov_copy[1].iov_base, iov[1].iov_base, iov[1].iov_len); + + c->event_queue = g_list_append(c->event_queue, iov_copy); + } + + } else { + CRM_LOG_ASSERT(header->qb.id != 0); /* Replying to a specific request */ + + rc = qb_ipcs_response_sendv(c->ipcs, iov, 2); + if (rc < header->qb.size) { + crm_notice(""Response %d to %p[%d] (%u bytes) failed: %s (%d)"", + header->qb.id, c->ipcs, c->pid, header->qb.size, pcmk_strerror(rc), rc); + + } else { + crm_trace(""Response %d sent, %lld bytes to %p[%d]"", + header->qb.id, (long long) rc, c->ipcs, c->pid); + } + + if (flags & crm_ipc_server_free) { + free(iov[0].iov_base); + free(iov[1].iov_base); + free(iov); + } + } + + if (flags & crm_ipc_server_event) { + rc = crm_ipcs_flush_events(c); + } else { + crm_ipcs_flush_events(c); + } + + if (rc == -EPIPE || rc == -ENOTCONN) { + crm_trace(""Client %p disconnected"", c->ipcs); + } + + return rc; +} +",0,"crm_ipcs_sendv(crm_client_t * c, struct iovec * iov, enum crm_ipc_flags flags) +{ + ssize_t rc; + static uint32_t id = 1; + struct crm_ipc_response_header *header = iov[0].iov_base; + + if (c->flags & crm_client_flag_ipc_proxied) { + /* _ALL_ replies to proxied connections need to be sent as events */ + if (is_not_set(flags, crm_ipc_server_event)) { + flags |= crm_ipc_server_event; + /* this flag lets us know this was originally meant to be a response. + * even though we're sending it over the event channel. */ + flags |= crm_ipc_proxied_relay_response; + } + } + + header->flags |= flags; + if (flags & crm_ipc_server_event) { + header->qb.id = id++; /* We don't really use it, but doesn't hurt to set one */ + + if (flags & crm_ipc_server_free) { + crm_trace(""Sending the original to %p[%d]"", c->ipcs, c->pid); + c->event_queue = g_list_append(c->event_queue, iov); + + } else { + struct iovec *iov_copy = calloc(2, sizeof(struct iovec)); + + crm_trace(""Sending a copy to %p[%d]"", c->ipcs, c->pid); + iov_copy[0].iov_len = iov[0].iov_len; + iov_copy[0].iov_base = malloc(iov[0].iov_len); + memcpy(iov_copy[0].iov_base, iov[0].iov_base, iov[0].iov_len); + + iov_copy[1].iov_len = iov[1].iov_len; + iov_copy[1].iov_base = malloc(iov[1].iov_len); + memcpy(iov_copy[1].iov_base, iov[1].iov_base, iov[1].iov_len); + + c->event_queue = g_list_append(c->event_queue, iov_copy); + } + + } else { + CRM_LOG_ASSERT(header->qb.id != 0); /* Replying to a specific request */ + + rc = qb_ipcs_response_sendv(c->ipcs, iov, 2); + if (rc < header->qb.size) { + crm_notice(""Response %d to %p[%d] (%u bytes) failed: %s (%d)"", + header->qb.id, c->ipcs, c->pid, header->qb.size, pcmk_strerror(rc), rc); + + } else { + crm_trace(""Response %d sent, %lld bytes to %p[%d]"", + header->qb.id, (long long) rc, c->ipcs, c->pid); + } + + if (flags & crm_ipc_server_free) { + free(iov[0].iov_base); + free(iov[1].iov_base); + free(iov); + } + } + + if (flags & crm_ipc_server_event) { + rc = crm_ipcs_flush_events(c); + } else { + crm_ipcs_flush_events(c); + } + + if (rc == -EPIPE || rc == -ENOTCONN) { + crm_trace(""Client %p disconnected"", c->ipcs); + } + + return rc; +} +","@@ -293,7 +293,6 @@ crm_client_disconnect_all(qb_ipcs_service_t *service) + crm_client_t * + crm_client_new(qb_ipcs_connection_t * c, uid_t uid_client, gid_t gid_client) + { +- static uid_t uid_server = 0; + static gid_t gid_cluster = 0; + + crm_client_t *client = NULL; +@@ -304,7 +303,6 @@ crm_client_new(qb_ipcs_connection_t * c, uid_t uid_client, gid_t gid_client) + } + + if (gid_cluster == 0) { +- uid_server = getuid(); + if(crm_user_lookup(CRM_DAEMON_USER, NULL, &gid_cluster) < 0) { + static bool have_error = FALSE; + if(have_error == FALSE) { +@@ -314,16 +312,10 @@ crm_client_new(qb_ipcs_connection_t * c, uid_t uid_client, gid_t gid_client) + } + } + +- if(gid_cluster != 0 && gid_client != 0) { +- uid_t best_uid = -1; /* Passing -1 to chown(2) means don't change */ +- +- if(uid_client == 0 || uid_server == 0) { /* Someone is priveliged, but the other may not be */ +- best_uid = QB_MAX(uid_client, uid_server); +- crm_trace(""Allowing user %u to clean up after disconnect"", best_uid); +- } +- ++ if (uid_client != 0) { + crm_trace(""Giving access to group %u"", gid_cluster); +- qb_ipcs_connection_auth_set(c, best_uid, gid_cluster, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); ++ /* Passing -1 to chown(2) means don't change */ ++ qb_ipcs_connection_auth_set(c, -1, gid_cluster, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); + } + + crm_client_init();",715,1046,2048 +14367,"png_push_process_row(png_structp png_ptr) +{ + png_ptr->row_info.color_type = png_ptr->color_type; + png_ptr->row_info.width = png_ptr->iwidth; + png_ptr->row_info.channels = png_ptr->channels; + png_ptr->row_info.bit_depth = png_ptr->bit_depth; + png_ptr->row_info.pixel_depth = png_ptr->pixel_depth; + + png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth, + png_ptr->row_info.width); + + png_read_filter_row(png_ptr, &(png_ptr->row_info), + png_ptr->row_buf + 1, png_ptr->prev_row + 1, + (int)(png_ptr->row_buf[0])); + + png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf, + png_ptr->rowbytes + 1); + + if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA)) + png_do_read_transformations(png_ptr); + +#ifdef PNG_READ_INTERLACING_SUPPORTED + /* Blow up interlaced rows to full size */ + if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE)) + { + if (png_ptr->pass < 6) +/* old interface (pre-1.0.9): + png_do_read_interlace(&(png_ptr->row_info), + png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations); + */ + png_do_read_interlace(png_ptr); + + switch (png_ptr->pass) + { + case 0: + { + int i; + for (i = 0; i < 8 && png_ptr->pass == 0; i++) + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); /* Updates png_ptr->pass */ + } + + if (png_ptr->pass == 2) /* Pass 1 might be empty */ + { + for (i = 0; i < 4 && png_ptr->pass == 2; i++) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + } + + if (png_ptr->pass == 4 && png_ptr->height <= 4) + { + for (i = 0; i < 2 && png_ptr->pass == 4; i++) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + } + + if (png_ptr->pass == 6 && png_ptr->height <= 4) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + + break; + } + + case 1: + { + int i; + for (i = 0; i < 8 && png_ptr->pass == 1; i++) + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); + } + + if (png_ptr->pass == 2) /* Skip top 4 generated rows */ + { + for (i = 0; i < 4 && png_ptr->pass == 2; i++) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + } + + break; + } + + case 2: + { + int i; + + for (i = 0; i < 4 && png_ptr->pass == 2; i++) + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); + } + + for (i = 0; i < 4 && png_ptr->pass == 2; i++) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + + if (png_ptr->pass == 4) /* Pass 3 might be empty */ + { + for (i = 0; i < 2 && png_ptr->pass == 4; i++) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + } + + break; + } + + case 3: + { + int i; + + for (i = 0; i < 4 && png_ptr->pass == 3; i++) + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); + } + + if (png_ptr->pass == 4) /* Skip top two generated rows */ + { + for (i = 0; i < 2 && png_ptr->pass == 4; i++) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + } + + break; + } + + case 4: + { + int i; + + for (i = 0; i < 2 && png_ptr->pass == 4; i++) + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); + } + + for (i = 0; i < 2 && png_ptr->pass == 4; i++) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + + if (png_ptr->pass == 6) /* Pass 5 might be empty */ + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + + break; + } + + case 5: + { + int i; + + for (i = 0; i < 2 && png_ptr->pass == 5; i++) + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); + } + + if (png_ptr->pass == 6) /* Skip top generated row */ + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + + break; + } + case 6: + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); + + if (png_ptr->pass != 6) + break; + + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + } + } + else +#endif + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); + } +} +",0,"png_push_process_row(png_structp png_ptr) +{ + png_ptr->row_info.color_type = png_ptr->color_type; + png_ptr->row_info.width = png_ptr->iwidth; + png_ptr->row_info.channels = png_ptr->channels; + png_ptr->row_info.bit_depth = png_ptr->bit_depth; + png_ptr->row_info.pixel_depth = png_ptr->pixel_depth; + + png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth, + png_ptr->row_info.width); + + png_read_filter_row(png_ptr, &(png_ptr->row_info), + png_ptr->row_buf + 1, png_ptr->prev_row + 1, + (int)(png_ptr->row_buf[0])); + + png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf, + png_ptr->rowbytes + 1); + + if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA)) + png_do_read_transformations(png_ptr); + +#ifdef PNG_READ_INTERLACING_SUPPORTED + /* Blow up interlaced rows to full size */ + if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE)) + { + if (png_ptr->pass < 6) +/* old interface (pre-1.0.9): + png_do_read_interlace(&(png_ptr->row_info), + png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations); + */ + png_do_read_interlace(png_ptr); + + switch (png_ptr->pass) + { + case 0: + { + int i; + for (i = 0; i < 8 && png_ptr->pass == 0; i++) + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); /* Updates png_ptr->pass */ + } + + if (png_ptr->pass == 2) /* Pass 1 might be empty */ + { + for (i = 0; i < 4 && png_ptr->pass == 2; i++) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + } + + if (png_ptr->pass == 4 && png_ptr->height <= 4) + { + for (i = 0; i < 2 && png_ptr->pass == 4; i++) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + } + + if (png_ptr->pass == 6 && png_ptr->height <= 4) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + + break; + } + + case 1: + { + int i; + for (i = 0; i < 8 && png_ptr->pass == 1; i++) + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); + } + + if (png_ptr->pass == 2) /* Skip top 4 generated rows */ + { + for (i = 0; i < 4 && png_ptr->pass == 2; i++) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + } + + break; + } + + case 2: + { + int i; + + for (i = 0; i < 4 && png_ptr->pass == 2; i++) + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); + } + + for (i = 0; i < 4 && png_ptr->pass == 2; i++) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + + if (png_ptr->pass == 4) /* Pass 3 might be empty */ + { + for (i = 0; i < 2 && png_ptr->pass == 4; i++) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + } + + break; + } + + case 3: + { + int i; + + for (i = 0; i < 4 && png_ptr->pass == 3; i++) + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); + } + + if (png_ptr->pass == 4) /* Skip top two generated rows */ + { + for (i = 0; i < 2 && png_ptr->pass == 4; i++) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + } + + break; + } + + case 4: + { + int i; + + for (i = 0; i < 2 && png_ptr->pass == 4; i++) + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); + } + + for (i = 0; i < 2 && png_ptr->pass == 4; i++) + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + + if (png_ptr->pass == 6) /* Pass 5 might be empty */ + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + + break; + } + + case 5: + { + int i; + + for (i = 0; i < 2 && png_ptr->pass == 5; i++) + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); + } + + if (png_ptr->pass == 6) /* Skip top generated row */ + { + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + + break; + } + case 6: + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); + + if (png_ptr->pass != 6) + break; + + png_push_have_row(png_ptr, png_bytep_NULL); + png_read_push_finish_row(png_ptr); + } + } + } + else +#endif + { + png_push_have_row(png_ptr, png_ptr->row_buf + 1); + png_read_push_finish_row(png_ptr); + } +} +","@@ -685,9 +685,12 @@ png_push_save_buffer(png_structp png_ptr) + png_free(png_ptr, old_buffer); + png_error(png_ptr, ""Insufficient memory for save_buffer""); + } +- png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size); +- png_free(png_ptr, old_buffer); +- png_ptr->save_buffer_max = new_max; ++ else ++ { ++ png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size); ++ png_free(png_ptr, old_buffer); ++ png_ptr->save_buffer_max = new_max; ++ } + } + if (png_ptr->current_buffer_size) + {",1460,1791,2048 +15607,"void PeopleHandler::PushSyncPrefs() { +#if !defined(OS_CHROMEOS) + if (IsProfileAuthNeededOrHasErrors()) + return; +#endif + + ProfileSyncService* service = GetSyncService(); + if (!service || !service->IsEngineInitialized()) { + return; + } + + configuring_sync_ = true; + DCHECK(service->IsEngineInitialized()) + << ""Cannot configure sync until the sync engine is initialized""; + + base::DictionaryValue args; + + const syncer::ModelTypeSet registered_types = + service->GetRegisteredDataTypes(); + const syncer::ModelTypeSet preferred_types = service->GetPreferredDataTypes(); + const syncer::ModelTypeSet enforced_types = service->GetForcedDataTypes(); + syncer::ModelTypeNameMap type_names = syncer::GetUserSelectableTypeNameMap(); + for (syncer::ModelTypeNameMap::const_iterator it = type_names.begin(); + it != type_names.end(); ++it) { + syncer::ModelType sync_type = it->first; + const std::string key_name = it->second; + args.SetBoolean(key_name + ""Registered"", registered_types.Has(sync_type)); + args.SetBoolean(key_name + ""Synced"", preferred_types.Has(sync_type)); + args.SetBoolean(key_name + ""Enforced"", enforced_types.Has(sync_type)); + } + PrefService* pref_service = profile_->GetPrefs(); + syncer::SyncPrefs sync_prefs(pref_service); + args.SetBoolean(""syncAllDataTypes"", sync_prefs.HasKeepEverythingSynced()); + args.SetBoolean(""paymentsIntegrationEnabled"", + autofill::prefs::IsPaymentsIntegrationEnabled(pref_service)); + args.SetBoolean(""encryptAllData"", service->IsEncryptEverythingEnabled()); + args.SetBoolean(""encryptAllDataAllowed"", + service->IsEncryptEverythingAllowed()); + + args.SetBoolean(""passphraseRequired"", service->IsPassphraseRequired()); + + args.SetBoolean(""passphraseTypeIsCustom"", + service->GetPassphraseType() == + syncer::PassphraseType::CUSTOM_PASSPHRASE); + base::Time passphrase_time = service->GetExplicitPassphraseTime(); + syncer::PassphraseType passphrase_type = service->GetPassphraseType(); + if (!passphrase_time.is_null()) { + base::string16 passphrase_time_str = + base::TimeFormatShortDate(passphrase_time); + args.SetString(""enterPassphraseBody"", + GetStringFUTF16(IDS_SYNC_ENTER_PASSPHRASE_BODY_WITH_DATE, + passphrase_time_str)); + args.SetString( + ""enterGooglePassphraseBody"", + GetStringFUTF16(IDS_SYNC_ENTER_GOOGLE_PASSPHRASE_BODY_WITH_DATE, + passphrase_time_str)); + switch (passphrase_type) { + case syncer::PassphraseType::FROZEN_IMPLICIT_PASSPHRASE: + args.SetString( + ""fullEncryptionBody"", + GetStringFUTF16(IDS_SYNC_FULL_ENCRYPTION_BODY_GOOGLE_WITH_DATE, + passphrase_time_str)); + break; + case syncer::PassphraseType::CUSTOM_PASSPHRASE: + args.SetString( + ""fullEncryptionBody"", + GetStringFUTF16(IDS_SYNC_FULL_ENCRYPTION_BODY_CUSTOM_WITH_DATE, + passphrase_time_str)); + break; + default: + args.SetString(""fullEncryptionBody"", + GetStringUTF16(IDS_SYNC_FULL_ENCRYPTION_BODY_CUSTOM)); + break; + } + } else if (passphrase_type == syncer::PassphraseType::CUSTOM_PASSPHRASE) { + args.SetString(""fullEncryptionBody"", + GetStringUTF16(IDS_SYNC_FULL_ENCRYPTION_BODY_CUSTOM)); + } + + FireWebUIListener(""sync-prefs-changed"", args); +} +",0,"void PeopleHandler::PushSyncPrefs() { +#if !defined(OS_CHROMEOS) + if (IsProfileAuthNeededOrHasErrors()) + return; +#endif + + ProfileSyncService* service = GetSyncService(); + if (!service || !service->IsEngineInitialized()) { + return; + } + + configuring_sync_ = true; + DCHECK(service->IsEngineInitialized()) + << ""Cannot configure sync until the sync engine is initialized""; + + base::DictionaryValue args; + + const syncer::ModelTypeSet registered_types = + service->GetRegisteredDataTypes(); + const syncer::ModelTypeSet preferred_types = service->GetPreferredDataTypes(); + const syncer::ModelTypeSet enforced_types = service->GetForcedDataTypes(); + syncer::ModelTypeNameMap type_names = syncer::GetUserSelectableTypeNameMap(); + for (syncer::ModelTypeNameMap::const_iterator it = type_names.begin(); + it != type_names.end(); ++it) { + syncer::ModelType sync_type = it->first; + const std::string key_name = it->second; + args.SetBoolean(key_name + ""Registered"", registered_types.Has(sync_type)); + args.SetBoolean(key_name + ""Synced"", preferred_types.Has(sync_type)); + args.SetBoolean(key_name + ""Enforced"", enforced_types.Has(sync_type)); + } + PrefService* pref_service = profile_->GetPrefs(); + syncer::SyncPrefs sync_prefs(pref_service); + args.SetBoolean(""syncAllDataTypes"", sync_prefs.HasKeepEverythingSynced()); + args.SetBoolean(""paymentsIntegrationEnabled"", + autofill::prefs::IsPaymentsIntegrationEnabled(pref_service)); + args.SetBoolean(""encryptAllData"", service->IsEncryptEverythingEnabled()); + args.SetBoolean(""encryptAllDataAllowed"", + service->IsEncryptEverythingAllowed()); + + args.SetBoolean(""passphraseRequired"", service->IsPassphraseRequired()); + + args.SetBoolean(""passphraseTypeIsCustom"", + service->GetPassphraseType() == + syncer::PassphraseType::CUSTOM_PASSPHRASE); + base::Time passphrase_time = service->GetExplicitPassphraseTime(); + syncer::PassphraseType passphrase_type = service->GetPassphraseType(); + if (!passphrase_time.is_null()) { + base::string16 passphrase_time_str = + base::TimeFormatShortDate(passphrase_time); + args.SetString(""enterPassphraseBody"", + GetStringFUTF16(IDS_SYNC_ENTER_PASSPHRASE_BODY_WITH_DATE, + passphrase_time_str)); + args.SetString( + ""enterGooglePassphraseBody"", + GetStringFUTF16(IDS_SYNC_ENTER_GOOGLE_PASSPHRASE_BODY_WITH_DATE, + passphrase_time_str)); + switch (passphrase_type) { + case syncer::PassphraseType::FROZEN_IMPLICIT_PASSPHRASE: + args.SetString( + ""fullEncryptionBody"", + GetStringFUTF16(IDS_SYNC_FULL_ENCRYPTION_BODY_GOOGLE_WITH_DATE, + passphrase_time_str)); + break; + case syncer::PassphraseType::CUSTOM_PASSPHRASE: + args.SetString( + ""fullEncryptionBody"", + GetStringFUTF16(IDS_SYNC_FULL_ENCRYPTION_BODY_CUSTOM_WITH_DATE, + passphrase_time_str)); + break; + default: + args.SetString(""fullEncryptionBody"", + GetStringUTF16(IDS_SYNC_FULL_ENCRYPTION_BODY_CUSTOM)); + break; + } + } else if (passphrase_type == syncer::PassphraseType::CUSTOM_PASSPHRASE) { + args.SetString(""fullEncryptionBody"", + GetStringUTF16(IDS_SYNC_FULL_ENCRYPTION_BODY_CUSTOM)); + } + + FireWebUIListener(""sync-prefs-changed"", args); +} +","@@ -798,7 +798,9 @@ void PeopleHandler::HandleSignout(const base::ListValue* args) { + DCHECK(!delete_profile) + << ""Deleting the profile should only be offered the user is syncing.""; + ProfileOAuth2TokenServiceFactory::GetForProfile(profile_) +- ->RevokeAllCredentials(); ++ ->RevokeAllCredentials( ++ signin_metrics::SourceForRefreshTokenOperation:: ++ kSettings_Signout); + } + } + +@@ -814,7 +816,8 @@ void PeopleHandler::HandlePauseSync(const base::ListValue* args) { + DCHECK(signin_manager->IsAuthenticated()); + ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)->UpdateCredentials( + signin_manager->GetAuthenticatedAccountId(), +- OAuth2TokenServiceDelegate::kInvalidRefreshToken); ++ OAuth2TokenServiceDelegate::kInvalidRefreshToken, ++ signin_metrics::SourceForRefreshTokenOperation::kSettings_PauseSync); + } + #endif + ",768,1099,2048 +7914,"static int cmd_handle_untagged(struct ImapData *idata) +{ + unsigned int count = 0; + char *s = imap_next_word(idata->buf); + char *pn = imap_next_word(s); + + if ((idata->state >= IMAP_SELECTED) && isdigit((unsigned char) *s)) + { + pn = s; + s = imap_next_word(s); + + /* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the + * connection, so update that one. + */ + if (mutt_str_strncasecmp(""EXISTS"", s, 6) == 0) + { + mutt_debug(2, ""Handling EXISTS\n""); + + /* new mail arrived */ + if (mutt_str_atoui(pn, &count) < 0) + { + mutt_debug(1, ""Malformed EXISTS: '%s'\n"", pn); + } + + if (!(idata->reopen & IMAP_EXPUNGE_PENDING) && count < idata->max_msn) + { + /* Notes 6.0.3 has a tendency to report fewer messages exist than + * it should. */ + mutt_debug(1, ""Message count is out of sync\n""); + return 0; + } + /* at least the InterChange server sends EXISTS messages freely, + * even when there is no new mail */ + else if (count == idata->max_msn) + mutt_debug(3, ""superfluous EXISTS message.\n""); + else + { + if (!(idata->reopen & IMAP_EXPUNGE_PENDING)) + { + mutt_debug(2, ""New mail in %s - %d messages total.\n"", idata->mailbox, count); + idata->reopen |= IMAP_NEWMAIL_PENDING; + } + idata->new_mail_count = count; + } + } + /* pn vs. s: need initial seqno */ + else if (mutt_str_strncasecmp(""EXPUNGE"", s, 7) == 0) + cmd_parse_expunge(idata, pn); + else if (mutt_str_strncasecmp(""FETCH"", s, 5) == 0) + cmd_parse_fetch(idata, pn); + } + else if (mutt_str_strncasecmp(""CAPABILITY"", s, 10) == 0) + cmd_parse_capability(idata, s); + else if (mutt_str_strncasecmp(""OK [CAPABILITY"", s, 14) == 0) + cmd_parse_capability(idata, pn); + else if (mutt_str_strncasecmp(""OK [CAPABILITY"", pn, 14) == 0) + cmd_parse_capability(idata, imap_next_word(pn)); + else if (mutt_str_strncasecmp(""LIST"", s, 4) == 0) + cmd_parse_list(idata, s); + else if (mutt_str_strncasecmp(""LSUB"", s, 4) == 0) + cmd_parse_lsub(idata, s); + else if (mutt_str_strncasecmp(""MYRIGHTS"", s, 8) == 0) + cmd_parse_myrights(idata, s); + else if (mutt_str_strncasecmp(""SEARCH"", s, 6) == 0) + cmd_parse_search(idata, s); + else if (mutt_str_strncasecmp(""STATUS"", s, 6) == 0) + cmd_parse_status(idata, s); + else if (mutt_str_strncasecmp(""ENABLED"", s, 7) == 0) + cmd_parse_enabled(idata, s); + else if (mutt_str_strncasecmp(""BYE"", s, 3) == 0) + { + mutt_debug(2, ""Handling BYE\n""); + + /* check if we're logging out */ + if (idata->status == IMAP_BYE) + return 0; + + /* server shut down our connection */ + s += 3; + SKIPWS(s); + mutt_error(""%s"", s); + cmd_handle_fatal(idata); + + return -1; + } + else if (ImapServernoise && (mutt_str_strncasecmp(""NO"", s, 2) == 0)) + { + mutt_debug(2, ""Handling untagged NO\n""); + + /* Display the warning message from the server */ + mutt_error(""%s"", s + 3); + } + + return 0; +} +",0,"static int cmd_handle_untagged(struct ImapData *idata) +{ + unsigned int count = 0; + char *s = imap_next_word(idata->buf); + char *pn = imap_next_word(s); + + if ((idata->state >= IMAP_SELECTED) && isdigit((unsigned char) *s)) + { + pn = s; + s = imap_next_word(s); + + /* EXISTS and EXPUNGE are always related to the SELECTED mailbox for the + * connection, so update that one. + */ + if (mutt_str_strncasecmp(""EXISTS"", s, 6) == 0) + { + mutt_debug(2, ""Handling EXISTS\n""); + + /* new mail arrived */ + if (mutt_str_atoui(pn, &count) < 0) + { + mutt_debug(1, ""Malformed EXISTS: '%s'\n"", pn); + } + + if (!(idata->reopen & IMAP_EXPUNGE_PENDING) && count < idata->max_msn) + { + /* Notes 6.0.3 has a tendency to report fewer messages exist than + * it should. */ + mutt_debug(1, ""Message count is out of sync\n""); + return 0; + } + /* at least the InterChange server sends EXISTS messages freely, + * even when there is no new mail */ + else if (count == idata->max_msn) + mutt_debug(3, ""superfluous EXISTS message.\n""); + else + { + if (!(idata->reopen & IMAP_EXPUNGE_PENDING)) + { + mutt_debug(2, ""New mail in %s - %d messages total.\n"", idata->mailbox, count); + idata->reopen |= IMAP_NEWMAIL_PENDING; + } + idata->new_mail_count = count; + } + } + /* pn vs. s: need initial seqno */ + else if (mutt_str_strncasecmp(""EXPUNGE"", s, 7) == 0) + cmd_parse_expunge(idata, pn); + else if (mutt_str_strncasecmp(""FETCH"", s, 5) == 0) + cmd_parse_fetch(idata, pn); + } + else if (mutt_str_strncasecmp(""CAPABILITY"", s, 10) == 0) + cmd_parse_capability(idata, s); + else if (mutt_str_strncasecmp(""OK [CAPABILITY"", s, 14) == 0) + cmd_parse_capability(idata, pn); + else if (mutt_str_strncasecmp(""OK [CAPABILITY"", pn, 14) == 0) + cmd_parse_capability(idata, imap_next_word(pn)); + else if (mutt_str_strncasecmp(""LIST"", s, 4) == 0) + cmd_parse_list(idata, s); + else if (mutt_str_strncasecmp(""LSUB"", s, 4) == 0) + cmd_parse_lsub(idata, s); + else if (mutt_str_strncasecmp(""MYRIGHTS"", s, 8) == 0) + cmd_parse_myrights(idata, s); + else if (mutt_str_strncasecmp(""SEARCH"", s, 6) == 0) + cmd_parse_search(idata, s); + else if (mutt_str_strncasecmp(""STATUS"", s, 6) == 0) + cmd_parse_status(idata, s); + else if (mutt_str_strncasecmp(""ENABLED"", s, 7) == 0) + cmd_parse_enabled(idata, s); + else if (mutt_str_strncasecmp(""BYE"", s, 3) == 0) + { + mutt_debug(2, ""Handling BYE\n""); + + /* check if we're logging out */ + if (idata->status == IMAP_BYE) + return 0; + + /* server shut down our connection */ + s += 3; + SKIPWS(s); + mutt_error(""%s"", s); + cmd_handle_fatal(idata); + + return -1; + } + else if (ImapServernoise && (mutt_str_strncasecmp(""NO"", s, 2) == 0)) + { + mutt_debug(2, ""Handling untagged NO\n""); + + /* Display the warning message from the server */ + mutt_error(""%s"", s + 3); + } + + return 0; +} +","@@ -499,7 +499,7 @@ static void cmd_parse_lsub(struct ImapData *idata, char *s) + mutt_str_strfcpy(buf, ""mailboxes \"""", sizeof(buf)); + mutt_account_tourl(&idata->conn->account, &url); + /* escape \ and "" */ +- imap_quote_string(errstr, sizeof(errstr), list.name); ++ imap_quote_string(errstr, sizeof(errstr), list.name, true); + url.path = errstr + 1; + url.path[strlen(url.path) - 1] = '\0'; + if (mutt_str_strcmp(url.user, ImapUser) == 0)",971,1302,2048 +720," pcf_read_TOC( FT_Stream stream, + PCF_Face face ) + { + FT_Error error; + PCF_Toc toc = &face->toc; + PCF_Table tables; + + FT_Memory memory = FT_FACE( face )->memory; + FT_UInt n; + + + if ( FT_STREAM_SEEK ( 0 ) || + FT_STREAM_READ_FIELDS ( pcf_toc_header, toc ) ) + return FT_THROW( Cannot_Open_Resource ); + + if ( toc->version != PCF_FILE_VERSION || + toc->count > FT_ARRAY_MAX( face->toc.tables ) || + toc->count == 0 ) + return FT_THROW( Invalid_File_Format ); + + if ( FT_NEW_ARRAY( face->toc.tables, toc->count ) ) + return FT_THROW( Out_Of_Memory ); + + tables = face->toc.tables; + for ( n = 0; n < toc->count; n++ ) + { + if ( FT_STREAM_READ_FIELDS( pcf_table_header, tables ) ) + goto Exit; + tables++; + } + + /* Sort tables and check for overlaps. Because they are almost */ + /* always ordered already, an in-place bubble sort with simultaneous */ + /* boundary checking seems appropriate. */ + tables = face->toc.tables; + + for ( n = 0; n < toc->count - 1; n++ ) + { + FT_UInt i, have_change; + + + have_change = 0; + + for ( i = 0; i < toc->count - 1 - n; i++ ) + { + PCF_TableRec tmp; + + + if ( tables[i].offset > tables[i + 1].offset ) + { + tmp = tables[i]; + tables[i] = tables[i + 1]; + tables[i + 1] = tmp; + + have_change = 1; + } + + if ( ( tables[i].size > tables[i + 1].offset ) || + ( tables[i].offset > tables[i + 1].offset - tables[i].size ) ) + { + error = FT_THROW( Invalid_Offset ); + goto Exit; + } + } + + if ( !have_change ) + break; + } + + /* we now check whether the `size' and `offset' values are reasonable: */ + /* `offset' + `size' must not exceed the stream size */ + tables = face->toc.tables; + for ( n = 0; n < toc->count; n++ ) + { + /* we need two checks to avoid overflow */ + if ( ( tables->size > stream->size ) || + ( tables->offset > stream->size - tables->size ) ) + { + error = FT_THROW( Invalid_Table ); + goto Exit; + } + tables++; + } + +#ifdef FT_DEBUG_LEVEL_TRACE + + { + FT_UInt i, j; + const char* name = ""?""; + + + FT_TRACE4(( ""pcf_read_TOC:\n"" )); + + FT_TRACE4(( "" number of tables: %ld\n"", face->toc.count )); + + tables = face->toc.tables; + for ( i = 0; i < toc->count; i++ ) + { + for ( j = 0; j < sizeof ( tableNames ) / sizeof ( tableNames[0] ); + j++ ) + if ( tables[i].type == (FT_UInt)( 1 << j ) ) + name = tableNames[j]; + + FT_TRACE4(( "" %d: type=%s, format=0x%X, "" + ""size=%ld (0x%lX), offset=%ld (0x%lX)\n"", + i, name, + tables[i].format, + tables[i].size, tables[i].size, + tables[i].offset, tables[i].offset )); + } + } + +#endif + + return FT_Err_Ok; + + Exit: + FT_FREE( face->toc.tables ); + return error; + } +",0," pcf_read_TOC( FT_Stream stream, + PCF_Face face ) + { + FT_Error error; + PCF_Toc toc = &face->toc; + PCF_Table tables; + + FT_Memory memory = FT_FACE( face )->memory; + FT_UInt n; + + + if ( FT_STREAM_SEEK ( 0 ) || + FT_STREAM_READ_FIELDS ( pcf_toc_header, toc ) ) + return FT_THROW( Cannot_Open_Resource ); + + if ( toc->version != PCF_FILE_VERSION || + toc->count > FT_ARRAY_MAX( face->toc.tables ) || + toc->count == 0 ) + return FT_THROW( Invalid_File_Format ); + + if ( FT_NEW_ARRAY( face->toc.tables, toc->count ) ) + return FT_THROW( Out_Of_Memory ); + + tables = face->toc.tables; + for ( n = 0; n < toc->count; n++ ) + { + if ( FT_STREAM_READ_FIELDS( pcf_table_header, tables ) ) + goto Exit; + tables++; + } + + /* Sort tables and check for overlaps. Because they are almost */ + /* always ordered already, an in-place bubble sort with simultaneous */ + /* boundary checking seems appropriate. */ + tables = face->toc.tables; + + for ( n = 0; n < toc->count - 1; n++ ) + { + FT_UInt i, have_change; + + + have_change = 0; + + for ( i = 0; i < toc->count - 1 - n; i++ ) + { + PCF_TableRec tmp; + + + if ( tables[i].offset > tables[i + 1].offset ) + { + tmp = tables[i]; + tables[i] = tables[i + 1]; + tables[i + 1] = tmp; + + have_change = 1; + } + + if ( ( tables[i].size > tables[i + 1].offset ) || + ( tables[i].offset > tables[i + 1].offset - tables[i].size ) ) + { + error = FT_THROW( Invalid_Offset ); + goto Exit; + } + } + + if ( !have_change ) + break; + } + + /* we now check whether the `size' and `offset' values are reasonable: */ + /* `offset' + `size' must not exceed the stream size */ + tables = face->toc.tables; + for ( n = 0; n < toc->count; n++ ) + { + /* we need two checks to avoid overflow */ + if ( ( tables->size > stream->size ) || + ( tables->offset > stream->size - tables->size ) ) + { + error = FT_THROW( Invalid_Table ); + goto Exit; + } + tables++; + } + +#ifdef FT_DEBUG_LEVEL_TRACE + + { + FT_UInt i, j; + const char* name = ""?""; + + + FT_TRACE4(( ""pcf_read_TOC:\n"" )); + + FT_TRACE4(( "" number of tables: %ld\n"", face->toc.count )); + + tables = face->toc.tables; + for ( i = 0; i < toc->count; i++ ) + { + for ( j = 0; j < sizeof ( tableNames ) / sizeof ( tableNames[0] ); + j++ ) + if ( tables[i].type == (FT_UInt)( 1 << j ) ) + name = tableNames[j]; + + FT_TRACE4(( "" %d: type=%s, format=0x%X, "" + ""size=%ld (0x%lX), offset=%ld (0x%lX)\n"", + i, name, + tables[i].format, + tables[i].size, tables[i].size, + tables[i].offset, tables[i].offset )); + } + } + +#endif + + return FT_Err_Ok; + + Exit: + FT_FREE( face->toc.tables ); + return error; + } +","@@ -830,6 +830,15 @@ THE SOFTWARE. + if ( !PCF_FORMAT_MATCH( format, PCF_DEFAULT_FORMAT ) ) + return FT_THROW( Invalid_File_Format ); + ++ /* sanity checks */ ++ if ( firstCol < 0 || ++ firstCol > lastCol || ++ lastCol > 0xFF || ++ firstRow < 0 || ++ firstRow > lastRow || ++ lastRow > 0xFF ) ++ return FT_THROW( Invalid_Table ); ++ + FT_TRACE4(( ""pdf_get_encodings:\n"" )); + + FT_TRACE4(( "" firstCol %d, lastCol %d, firstRow %d, lastRow %d\n"",",856,1187,2048 +17948,"file_trycdf(struct magic_set *ms, int fd, const unsigned char *buf, + size_t nbytes) +{ + cdf_info_t info; + cdf_header_t h; + cdf_sat_t sat, ssat; + cdf_stream_t sst, scn; + cdf_dir_t dir; + int i; + const char *expn = """"; + const char *corrupt = ""corrupt: ""; + + info.i_fd = fd; + info.i_buf = buf; + info.i_len = nbytes; + if (ms->flags & MAGIC_APPLE) + return 0; + if (cdf_read_header(&info, &h) == -1) + return 0; +#ifdef CDF_DEBUG + cdf_dump_header(&h); +#endif + + if ((i = cdf_read_sat(&info, &h, &sat)) == -1) { + expn = ""Can't read SAT""; + goto out0; + } +#ifdef CDF_DEBUG + cdf_dump_sat(""SAT"", &sat, CDF_SEC_SIZE(&h)); +#endif + + if ((i = cdf_read_ssat(&info, &h, &sat, &ssat)) == -1) { + expn = ""Can't read SSAT""; + goto out1; + } +#ifdef CDF_DEBUG + cdf_dump_sat(""SSAT"", &ssat, CDF_SHORT_SEC_SIZE(&h)); +#endif + + if ((i = cdf_read_dir(&info, &h, &sat, &dir)) == -1) { + expn = ""Can't read directory""; + goto out2; + } + + const cdf_directory_t *root_storage; + if ((i = cdf_read_short_stream(&info, &h, &sat, &dir, &sst, + &root_storage)) == -1) { + expn = ""Cannot read short stream""; + goto out3; + } +#ifdef CDF_DEBUG + cdf_dump_dir(&info, &h, &sat, &ssat, &sst, &dir); +#endif +#ifdef notdef + if (root_storage) { + if (NOTMIME(ms)) { + char clsbuf[128]; + if (file_printf(ms, ""CLSID %s, "", + format_clsid(clsbuf, sizeof(clsbuf), + root_storage->d_storage_uuid)) == -1) + return -1; + } + } +#endif + + if ((i = cdf_read_summary_info(&info, &h, &sat, &ssat, &sst, &dir, + &scn)) == -1) { + if (errno == ESRCH) { + corrupt = expn; + expn = ""No summary info""; + } else { + expn = ""Cannot read summary info""; + } + goto out4; + } + #ifdef CDF_DEBUG + cdf_dump_summary_info(&h, &scn); + #endif + if ((i = cdf_file_summary_info(ms, &h, &scn, + root_storage->d_storage_uuid)) < 0) + expn = ""Can't expand summary_info""; + + if (i == 0) { + const char *str = NULL; + cdf_directory_t *d; + char name[__arraycount(d->d_name)]; + size_t j, k; + + for (j = 0; str == NULL && j < dir.dir_len; j++) { + d = &dir.dir_tab[j]; + for (k = 0; k < sizeof(name); k++) + name[k] = (char)cdf_tole2(d->d_name[k]); + str = cdf_app_to_mime(name, + NOTMIME(ms) ? name2desc : name2mime); + } + if (NOTMIME(ms)) { + if (str != NULL) { + if (file_printf(ms, ""%s"", str) == -1) + return -1; + i = 1; + } + } else { + if (str == NULL) + str = ""vnd.ms-office""; + if (file_printf(ms, ""application/%s"", str) == -1) + return -1; + i = 1; + } + } + free(scn.sst_tab); +out4: + free(sst.sst_tab); +out3: + free(dir.dir_tab); +out2: + free(ssat.sat_tab); +out1: + free(sat.sat_tab); +out0: + if (i == -1) { + if (NOTMIME(ms)) { + if (file_printf(ms, + ""Composite Document File V2 Document"") == -1) + return -1; + if (*expn) + if (file_printf(ms, "", %s%s"", corrupt, expn) == -1) + return -1; + } else { + if (file_printf(ms, ""application/CDFV2-corrupt"") == -1) + return -1; + } + i = 1; + } + return i; +} +",1,"file_trycdf(struct magic_set *ms, int fd, const unsigned char *buf, + size_t nbytes) +{ + cdf_info_t info; + cdf_header_t h; + cdf_sat_t sat, ssat; + cdf_stream_t sst, scn; + cdf_dir_t dir; + int i; + const char *expn = """"; + const char *corrupt = ""corrupt: ""; + + info.i_fd = fd; + info.i_buf = buf; + info.i_len = nbytes; + if (ms->flags & MAGIC_APPLE) + return 0; + if (cdf_read_header(&info, &h) == -1) + return 0; +#ifdef CDF_DEBUG + cdf_dump_header(&h); +#endif + + if ((i = cdf_read_sat(&info, &h, &sat)) == -1) { + expn = ""Can't read SAT""; + goto out0; + } +#ifdef CDF_DEBUG + cdf_dump_sat(""SAT"", &sat, CDF_SEC_SIZE(&h)); +#endif + + if ((i = cdf_read_ssat(&info, &h, &sat, &ssat)) == -1) { + expn = ""Can't read SSAT""; + goto out1; + } +#ifdef CDF_DEBUG + cdf_dump_sat(""SSAT"", &ssat, CDF_SHORT_SEC_SIZE(&h)); +#endif + + if ((i = cdf_read_dir(&info, &h, &sat, &dir)) == -1) { + expn = ""Can't read directory""; + goto out2; + } + + const cdf_directory_t *root_storage; + if ((i = cdf_read_short_stream(&info, &h, &sat, &dir, &sst, + &root_storage)) == -1) { + expn = ""Cannot read short stream""; + goto out3; + } +#ifdef CDF_DEBUG + cdf_dump_dir(&info, &h, &sat, &ssat, &sst, &dir); +#endif +#ifdef notdef + if (root_storage) { + if (NOTMIME(ms)) { + char clsbuf[128]; + if (file_printf(ms, ""CLSID %s, "", + format_clsid(clsbuf, sizeof(clsbuf), + root_storage->d_storage_uuid)) == -1) + return -1; + } + } +#endif + + if ((i = cdf_read_summary_info(&info, &h, &sat, &ssat, &sst, &dir, + &scn)) == -1) { + if (errno == ESRCH) { + corrupt = expn; + expn = ""No summary info""; + } else { + expn = ""Cannot read summary info""; + } + goto out4; + } + #ifdef CDF_DEBUG + cdf_dump_summary_info(&h, &scn); + #endif + if ((i = cdf_file_summary_info(ms, &h, &scn, root_storage)) < 0) + expn = ""Can't expand summary_info""; + + if (i == 0) { + const char *str = NULL; + cdf_directory_t *d; + char name[__arraycount(d->d_name)]; + size_t j, k; + + for (j = 0; str == NULL && j < dir.dir_len; j++) { + d = &dir.dir_tab[j]; + for (k = 0; k < sizeof(name); k++) + name[k] = (char)cdf_tole2(d->d_name[k]); + str = cdf_app_to_mime(name, + NOTMIME(ms) ? name2desc : name2mime); + } + if (NOTMIME(ms)) { + if (str != NULL) { + if (file_printf(ms, ""%s"", str) == -1) + return -1; + i = 1; + } + } else { + if (str == NULL) + str = ""vnd.ms-office""; + if (file_printf(ms, ""application/%s"", str) == -1) + return -1; + i = 1; + } + } + free(scn.sst_tab); +out4: + free(sst.sst_tab); +out3: + free(dir.dir_tab); +out2: + free(ssat.sat_tab); +out1: + free(sat.sat_tab); +out0: + if (i == -1) { + if (NOTMIME(ms)) { + if (file_printf(ms, + ""Composite Document File V2 Document"") == -1) + return -1; + if (*expn) + if (file_printf(ms, "", %s%s"", corrupt, expn) == -1) + return -1; + } else { + if (file_printf(ms, ""application/CDFV2-corrupt"") == -1) + return -1; + } + i = 1; + } + return i; +} +","@@ -26,7 +26,7 @@ + #include ""file.h"" + + #ifndef lint +-FILE_RCSID(""@(#)$File: readcdf.c,v 1.39 2014/02/27 23:26:18 christos Exp $"") ++FILE_RCSID(""@(#)$File: readcdf.c,v 1.40 2014/03/06 15:23:33 christos Exp $"") + #endif + + #include +@@ -120,7 +120,7 @@ cdf_app_to_mime(const char *vbuf, const struct nv *nv) + + private int + cdf_file_property_info(struct magic_set *ms, const cdf_property_info_t *info, +- size_t count, const uint64_t clsid[2]) ++ size_t count, const cdf_directory_t *root_storage) + { + size_t i; + cdf_timestamp_t tp; +@@ -130,8 +130,8 @@ cdf_file_property_info(struct magic_set *ms, const cdf_property_info_t *info, + const char *s; + int len; + +- if (!NOTMIME(ms)) +- str = cdf_clsid_to_mime(clsid, clsid2mime); ++ if (!NOTMIME(ms) && root_storage) ++ str = cdf_clsid_to_mime(root_storage->d_storage_uuid, clsid2mime); + + for (i = 0; i < count; i++) { + cdf_print_property_name(buf, sizeof(buf), info[i].pi_id); +@@ -236,7 +236,7 @@ cdf_file_property_info(struct magic_set *ms, const cdf_property_info_t *info, + + private int + cdf_file_summary_info(struct magic_set *ms, const cdf_header_t *h, +- const cdf_stream_t *sst, const uint64_t clsid[2]) ++ const cdf_stream_t *sst, const cdf_directory_t *root_storage) + { + cdf_summary_info_header_t si; + cdf_property_info_t *info; +@@ -276,13 +276,15 @@ cdf_file_summary_info(struct magic_set *ms, const cdf_header_t *h, + return -2; + break; + } +- str = cdf_clsid_to_mime(clsid, clsid2desc); +- if (str) +- if (file_printf(ms, "", %s"", str) == -1) +- return -2; +- } ++ if (root_storage) { ++ str = cdf_clsid_to_mime(root_storage->d_storage_uuid, clsid2desc); ++ if (str) ++ if (file_printf(ms, "", %s"", str) == -1) ++ return -2; ++ } ++ } + +- m = cdf_file_property_info(ms, info, count, clsid); ++ m = cdf_file_property_info(ms, info, count, root_storage); + free(info); + + return m == -1 ? -2 : m; +@@ -381,9 +383,8 @@ file_trycdf(struct magic_set *ms, int fd, const unsigned char *buf, + #ifdef CDF_DEBUG + cdf_dump_summary_info(&h, &scn); + #endif +- if ((i = cdf_file_summary_info(ms, &h, &scn, +- root_storage->d_storage_uuid)) < 0) +- expn = ""Can't expand summary_info""; ++ if ((i = cdf_file_summary_info(ms, &h, &scn, root_storage)) < 0) ++ expn = ""Can't expand summary_info""; + + if (i == 0) { + const char *str = NULL;",1072,1403,2048 +17855,"CatalogueRescan (FontPathElementPtr fpe) +{ + CataloguePtr cat = fpe->private; + char link[MAXFONTFILENAMELEN]; + char dest[MAXFONTFILENAMELEN]; + char *attrib; + FontPathElementPtr subfpe; + struct stat statbuf; + const char *path; + DIR *dir; + struct dirent *entry; + int len; + int pathlen; + + path = fpe->name + strlen(CataloguePrefix); + if (stat(path, &statbuf) < 0 || !S_ISDIR(statbuf.st_mode)) + return BadFontPath; + + if (statbuf.st_mtime <= cat->mtime) + return Successful; + + dir = opendir(path); + if (dir == NULL) + { + xfree(cat); + return BadFontPath; + } + + CatalogueUnrefFPEs (fpe); + while (entry = readdir(dir), entry != NULL) + { + snprintf(link, sizeof link, ""%s/%s"", path, entry->d_name); + len = readlink(link, dest, sizeof dest); + if (len < 0) + continue; + dest[len] = '\0'; + + if (dest[0] != '/') + { + pathlen = strlen(path); + memmove(dest + pathlen + 1, dest, sizeof dest - pathlen - 1); + memcpy(dest, path, pathlen); + memcpy(dest + pathlen, ""/"", 1); + len += pathlen + 1; + } + + attrib = strchr(link, ':'); + if (attrib && len + strlen(attrib) < sizeof dest) + { + memcpy(dest + len, attrib, strlen(attrib)); + len += strlen(attrib); + } + + subfpe = xalloc(sizeof *subfpe); + if (subfpe == NULL) + continue; + + /* The fonts returned by OpenFont will point back to the + * subfpe they come from. So set the type of the subfpe to + * what the catalogue fpe was assigned, so calls to CloseFont + * (which uses font->fpe->type) goes to CatalogueCloseFont. */ + subfpe->type = fpe->type; + subfpe->name_length = len; + subfpe->name = xalloc (len + 1); + if (subfpe == NULL) + { + xfree(subfpe); + continue; + } + + memcpy(subfpe->name, dest, len); + subfpe->name[len] = '\0'; + + /* The X server will manipulate the subfpe ref counts + * associated with the font in OpenFont and CloseFont, so we + * have to make sure it's valid. */ + subfpe->refcount = 1; + + if (FontFileInitFPE (subfpe) != Successful) + { + xfree(subfpe->name); + xfree(subfpe); + continue; + } + + if (CatalogueAddFPE(cat, subfpe) != Successful) + { + FontFileFreeFPE (subfpe); + xfree(subfpe); + continue; + } + } + + closedir(dir); + + qsort(cat->fpeList, + cat->fpeCount, sizeof cat->fpeList[0], ComparePriority); + + cat->mtime = statbuf.st_mtime; + + return Successful; +} +",1,"CatalogueRescan (FontPathElementPtr fpe) +{ + CataloguePtr cat = fpe->private; + char link[MAXFONTFILENAMELEN]; + char dest[MAXFONTFILENAMELEN]; + char *attrib; + FontPathElementPtr subfpe; + struct stat statbuf; + const char *path; + DIR *dir; + struct dirent *entry; + int len; + int pathlen; + + path = fpe->name + strlen(CataloguePrefix); + if (stat(path, &statbuf) < 0 || !S_ISDIR(statbuf.st_mode)) + return BadFontPath; + + if (statbuf.st_mtime <= cat->mtime) + return Successful; + + dir = opendir(path); + if (dir == NULL) + { + xfree(cat); + return BadFontPath; + } + + CatalogueUnrefFPEs (fpe); + while (entry = readdir(dir), entry != NULL) + { + snprintf(link, sizeof link, ""%s/%s"", path, entry->d_name); + len = readlink(link, dest, sizeof dest - 1); + if (len < 0) + continue; + dest[len] = '\0'; + + if (dest[0] != '/') + { + pathlen = strlen(path); + memmove(dest + pathlen + 1, dest, sizeof dest - pathlen - 1); + memcpy(dest, path, pathlen); + memcpy(dest + pathlen, ""/"", 1); + len += pathlen + 1; + } + + attrib = strchr(link, ':'); + if (attrib && len + strlen(attrib) < sizeof dest) + { + memcpy(dest + len, attrib, strlen(attrib)); + len += strlen(attrib); + } + + subfpe = xalloc(sizeof *subfpe); + if (subfpe == NULL) + continue; + + /* The fonts returned by OpenFont will point back to the + * subfpe they come from. So set the type of the subfpe to + * what the catalogue fpe was assigned, so calls to CloseFont + * (which uses font->fpe->type) goes to CatalogueCloseFont. */ + subfpe->type = fpe->type; + subfpe->name_length = len; + subfpe->name = xalloc (len + 1); + if (subfpe == NULL) + { + xfree(subfpe); + continue; + } + + memcpy(subfpe->name, dest, len); + subfpe->name[len] = '\0'; + + /* The X server will manipulate the subfpe ref counts + * associated with the font in OpenFont and CloseFont, so we + * have to make sure it's valid. */ + subfpe->refcount = 1; + + if (FontFileInitFPE (subfpe) != Successful) + { + xfree(subfpe->name); + xfree(subfpe); + continue; + } + + if (CatalogueAddFPE(cat, subfpe) != Successful) + { + FontFileFreeFPE (subfpe); + xfree(subfpe); + continue; + } + } + + closedir(dir); + + qsort(cat->fpeList, + cat->fpeCount, sizeof cat->fpeList[0], ComparePriority); + + cat->mtime = statbuf.st_mtime; + + return Successful; +} +","@@ -156,7 +156,7 @@ CatalogueRescan (FontPathElementPtr fpe) + while (entry = readdir(dir), entry != NULL) + { + snprintf(link, sizeof link, ""%s/%s"", path, entry->d_name); +- len = readlink(link, dest, sizeof dest); ++ len = readlink(link, dest, sizeof dest - 1); + if (len < 0) + continue;",724,1055,2048 +428,"void DCTStream::readScan() { + int data[64]; + int x1, y1, dx1, dy1, x2, y2, y3, cc, i; + int h, v, horiz, vert, vSub; + int *p1; + int c; + + if (scanInfo.numComps == 1) { + for (cc = 0; cc < numComps; ++cc) { + if (scanInfo.comp[cc]) { + break; + } + } + dx1 = mcuWidth / compInfo[cc].hSample; + dy1 = mcuHeight / compInfo[cc].vSample; + } else { + dx1 = mcuWidth; + dy1 = mcuHeight; + } + + for (y1 = 0; y1 < height; y1 += dy1) { + for (x1 = 0; x1 < width; x1 += dx1) { + + if (restartInterval > 0 && restartCtr == 0) { + c = readMarker(); + if (c != restartMarker) { + error(errSyntaxError, getPos(), + ""Bad DCT data: incorrect restart marker""); + return; + } + if (++restartMarker == 0xd8) { + restartMarker = 0xd0; + } + restart(); + } + + for (cc = 0; cc < numComps; ++cc) { + if (!scanInfo.comp[cc]) { + continue; + } + + h = compInfo[cc].hSample; + v = compInfo[cc].vSample; + horiz = mcuWidth / h; + vert = mcuHeight / v; + vSub = vert / 8; + for (y2 = 0; y2 < dy1; y2 += vert) { + for (x2 = 0; x2 < dx1; x2 += horiz) { + + p1 = &frameBuf[cc][(y1+y2) * bufWidth + (x1+x2)]; + for (y3 = 0, i = 0; y3 < 8; ++y3, i += 8) { + data[i] = p1[0]; + data[i+1] = p1[1]; + data[i+2] = p1[2]; + data[i+3] = p1[3]; + data[i+4] = p1[4]; + data[i+5] = p1[5]; + data[i+6] = p1[6]; + data[i+7] = p1[7]; + p1 += bufWidth * vSub; + } + + if (progressive) { + if (!readProgressiveDataUnit( + &dcHuffTables[scanInfo.dcHuffTable[cc]], + &acHuffTables[scanInfo.acHuffTable[cc]], + &compInfo[cc].prevDC, + data)) { + return; + } + } else { + if (!readDataUnit(&dcHuffTables[scanInfo.dcHuffTable[cc]], + &acHuffTables[scanInfo.acHuffTable[cc]], + &compInfo[cc].prevDC, + data)) { + return; + } + } + + p1 = &frameBuf[cc][(y1+y2) * bufWidth + (x1+x2)]; + for (y3 = 0, i = 0; y3 < 8; ++y3, i += 8) { + p1[0] = data[i]; + p1[1] = data[i+1]; + p1[2] = data[i+2]; + p1[3] = data[i+3]; + p1[4] = data[i+4]; + p1[5] = data[i+5]; + p1[6] = data[i+6]; + p1[7] = data[i+7]; + p1 += bufWidth * vSub; + } + } + } + } + --restartCtr; + } + } +} +",0,"void DCTStream::readScan() { + int data[64]; + int x1, y1, dx1, dy1, x2, y2, y3, cc, i; + int h, v, horiz, vert, vSub; + int *p1; + int c; + + if (scanInfo.numComps == 1) { + for (cc = 0; cc < numComps; ++cc) { + if (scanInfo.comp[cc]) { + break; + } + } + dx1 = mcuWidth / compInfo[cc].hSample; + dy1 = mcuHeight / compInfo[cc].vSample; + } else { + dx1 = mcuWidth; + dy1 = mcuHeight; + } + + for (y1 = 0; y1 < height; y1 += dy1) { + for (x1 = 0; x1 < width; x1 += dx1) { + + if (restartInterval > 0 && restartCtr == 0) { + c = readMarker(); + if (c != restartMarker) { + error(errSyntaxError, getPos(), + ""Bad DCT data: incorrect restart marker""); + return; + } + if (++restartMarker == 0xd8) { + restartMarker = 0xd0; + } + restart(); + } + + for (cc = 0; cc < numComps; ++cc) { + if (!scanInfo.comp[cc]) { + continue; + } + + h = compInfo[cc].hSample; + v = compInfo[cc].vSample; + horiz = mcuWidth / h; + vert = mcuHeight / v; + vSub = vert / 8; + for (y2 = 0; y2 < dy1; y2 += vert) { + for (x2 = 0; x2 < dx1; x2 += horiz) { + + p1 = &frameBuf[cc][(y1+y2) * bufWidth + (x1+x2)]; + for (y3 = 0, i = 0; y3 < 8; ++y3, i += 8) { + data[i] = p1[0]; + data[i+1] = p1[1]; + data[i+2] = p1[2]; + data[i+3] = p1[3]; + data[i+4] = p1[4]; + data[i+5] = p1[5]; + data[i+6] = p1[6]; + data[i+7] = p1[7]; + p1 += bufWidth * vSub; + } + + if (progressive) { + if (!readProgressiveDataUnit( + &dcHuffTables[scanInfo.dcHuffTable[cc]], + &acHuffTables[scanInfo.acHuffTable[cc]], + &compInfo[cc].prevDC, + data)) { + return; + } + } else { + if (!readDataUnit(&dcHuffTables[scanInfo.dcHuffTable[cc]], + &acHuffTables[scanInfo.acHuffTable[cc]], + &compInfo[cc].prevDC, + data)) { + return; + } + } + + p1 = &frameBuf[cc][(y1+y2) * bufWidth + (x1+x2)]; + for (y3 = 0, i = 0; y3 < 8; ++y3, i += 8) { + p1[0] = data[i]; + p1[1] = data[i+1]; + p1[2] = data[i+2]; + p1[3] = data[i+3]; + p1[4] = data[i+4]; + p1[5] = data[i+5]; + p1[6] = data[i+6]; + p1[7] = data[i+7]; + p1 += bufWidth * vSub; + } + } + } + } + --restartCtr; + } + } +} +","@@ -14,7 +14,7 @@ + // under GPL version 2 or later + // + // Copyright (C) 2005 Jeff Muizelaar +-// Copyright (C) 2006-2010, 2012 Albert Astals Cid ++// Copyright (C) 2006-2010, 2012, 2013 Albert Astals Cid + // Copyright (C) 2007 Krzysztof Kowalczyk + // Copyright (C) 2008 Julien Rebetez + // Copyright (C) 2009 Carlos Garcia Campos +@@ -1712,8 +1712,9 @@ int CCITTFaxStream::lookChar() { + for (i = 0; i < columns && codingLine[i] < columns; ++i) { + refLine[i] = codingLine[i]; + } +- refLine[i++] = columns; +- refLine[i] = columns; ++ for (; i < columns + 2; ++i) { ++ refLine[i] = columns; ++ } + codingLine[0] = 0; + a0i = 0; + b1i = 0;",883,1214,2048 +8730,"static void region16_copy_band_with_union(RECTANGLE_16* dst, + const RECTANGLE_16* src, const RECTANGLE_16* end, + UINT16 newTop, UINT16 newBottom, + const RECTANGLE_16* unionRect, + UINT32* dstCounter, + const RECTANGLE_16** srcPtr, RECTANGLE_16** dstPtr) +{ + UINT16 refY = src->top; + const RECTANGLE_16* startOverlap, *endOverlap; + + /* merges a band with the given rect + * Input: + * unionRect + * | | + * | | + * ==============+===============+================================ + * |Item1| |Item2| |Item3| |Item4| |Item5| Band + * ==============+===============+================================ + * before | overlap | after + * + * Resulting band: + * +-----+ +----------------------+ +-----+ + * |Item1| | Item2 | |Item3| + * +-----+ +----------------------+ +-----+ + * + * We first copy as-is items that are before Item2, the first overlapping + * item. + * Then we find the last one that overlap unionRect to agregate Item2, Item3 + * and Item4 to create Item2. + * Finally Item5 is copied as Item3. + * + * When no unionRect is provided, we skip the two first steps to just copy items + */ + + if (unionRect) + { + /* items before unionRect */ + while ((src < end) && (src->top == refY) && (src->right < unionRect->left)) + { + dst->top = newTop; + dst->bottom = newBottom; + dst->right = src->right; + dst->left = src->left; + src++; + dst++; + *dstCounter += 1; + } + + /* treat items overlapping with unionRect */ + startOverlap = unionRect; + endOverlap = unionRect; + + if ((src < end) && (src->top == refY) && (src->left < unionRect->left)) + startOverlap = src; + + while ((src < end) && (src->top == refY) && (src->right < unionRect->right)) + { + src++; + } + + if ((src < end) && (src->top == refY) && (src->left < unionRect->right)) + { + endOverlap = src; + src++; + } + + dst->bottom = newBottom; + dst->top = newTop; + dst->left = startOverlap->left; + dst->right = endOverlap->right; + dst++; + *dstCounter += 1; + } + + /* treat remaining items on the same band */ + while ((src < end) && (src->top == refY)) + { + dst->top = newTop; + dst->bottom = newBottom; + dst->right = src->right; + dst->left = src->left; + src++; + dst++; + *dstCounter += 1; + } + + if (srcPtr) + *srcPtr = src; + + *dstPtr = dst; +} +",0,"static void region16_copy_band_with_union(RECTANGLE_16* dst, + const RECTANGLE_16* src, const RECTANGLE_16* end, + UINT16 newTop, UINT16 newBottom, + const RECTANGLE_16* unionRect, + UINT32* dstCounter, + const RECTANGLE_16** srcPtr, RECTANGLE_16** dstPtr) +{ + UINT16 refY = src->top; + const RECTANGLE_16* startOverlap, *endOverlap; + + /* merges a band with the given rect + * Input: + * unionRect + * | | + * | | + * ==============+===============+================================ + * |Item1| |Item2| |Item3| |Item4| |Item5| Band + * ==============+===============+================================ + * before | overlap | after + * + * Resulting band: + * +-----+ +----------------------+ +-----+ + * |Item1| | Item2 | |Item3| + * +-----+ +----------------------+ +-----+ + * + * We first copy as-is items that are before Item2, the first overlapping + * item. + * Then we find the last one that overlap unionRect to agregate Item2, Item3 + * and Item4 to create Item2. + * Finally Item5 is copied as Item3. + * + * When no unionRect is provided, we skip the two first steps to just copy items + */ + + if (unionRect) + { + /* items before unionRect */ + while ((src < end) && (src->top == refY) && (src->right < unionRect->left)) + { + dst->top = newTop; + dst->bottom = newBottom; + dst->right = src->right; + dst->left = src->left; + src++; + dst++; + *dstCounter += 1; + } + + /* treat items overlapping with unionRect */ + startOverlap = unionRect; + endOverlap = unionRect; + + if ((src < end) && (src->top == refY) && (src->left < unionRect->left)) + startOverlap = src; + + while ((src < end) && (src->top == refY) && (src->right < unionRect->right)) + { + src++; + } + + if ((src < end) && (src->top == refY) && (src->left < unionRect->right)) + { + endOverlap = src; + src++; + } + + dst->bottom = newBottom; + dst->top = newTop; + dst->left = startOverlap->left; + dst->right = endOverlap->right; + dst++; + *dstCounter += 1; + } + + /* treat remaining items on the same band */ + while ((src < end) && (src->top == refY)) + { + dst->top = newTop; + dst->bottom = newBottom; + dst->right = src->right; + dst->left = src->left; + src++; + dst++; + *dstCounter += 1; + } + + if (srcPtr) + *srcPtr = src; + + *dstPtr = dst; +} +","@@ -467,8 +467,12 @@ static BOOL region16_simplify_bands(REGION16* region) + + if (finalNbRects != nbRects) + { +- int allocSize = sizeof(REGION16_DATA) + (finalNbRects * sizeof(RECTANGLE_16)); +- region->data = realloc(region->data, allocSize); ++ REGION16_DATA* data; ++ size_t allocSize = sizeof(REGION16_DATA) + (finalNbRects * sizeof(RECTANGLE_16)); ++ data = realloc(region->data, allocSize); ++ if (!data) ++ free(region->data); ++ region->data = data; + + if (!region->data) + { +@@ -485,6 +489,7 @@ static BOOL region16_simplify_bands(REGION16* region) + + BOOL region16_union_rect(REGION16* dst, const REGION16* src, const RECTANGLE_16* rect) + { ++ REGION16_DATA* data; + const RECTANGLE_16* srcExtents; + RECTANGLE_16* dstExtents; + const RECTANGLE_16* currentBand, *endSrcRect, *nextBand; +@@ -673,7 +678,10 @@ BOOL region16_union_rect(REGION16* dst, const REGION16* src, const RECTANGLE_16* + dstExtents->bottom = MAX(rect->bottom, srcExtents->bottom); + dstExtents->right = MAX(rect->right, srcExtents->right); + newItems->size = sizeof(REGION16_DATA) + (usedRects * sizeof(RECTANGLE_16)); +- dst->data = realloc(newItems, newItems->size); ++ data = realloc(newItems, newItems->size); ++ if (!data) ++ free(dst->data); ++ dst->data = data; + + if (!dst->data) + { +@@ -717,6 +725,7 @@ BOOL region16_intersects_rect(const REGION16* src, const RECTANGLE_16* arg2) + + BOOL region16_intersect_rect(REGION16* dst, const REGION16* src, const RECTANGLE_16* rect) + { ++ REGION16_DATA* data; + REGION16_DATA* newItems; + const RECTANGLE_16* srcPtr, *endPtr, *srcExtents; + RECTANGLE_16* dstPtr; +@@ -789,7 +798,10 @@ BOOL region16_intersect_rect(REGION16* dst, const REGION16* src, const RECTANGLE + if ((dst->data->size > 0) && (dst->data != &empty_region)) + free(dst->data); + +- dst->data = realloc(newItems, newItems->size); ++ data = realloc(newItems, newItems->size); ++ if (!data) ++ free(dst->data); ++ dst->data = data; + + if (!dst->data) + {",739,1070,2048 +825,"static void do_key_event(VncState *vs, int down, int keycode, int sym) +{ + /* QEMU console switch */ + switch(keycode) { + case 0x2a: /* Left Shift */ + case 0x36: /* Right Shift */ + case 0x1d: /* Left CTRL */ + case 0x9d: /* Right CTRL */ + case 0x38: /* Left ALT */ + case 0xb8: /* Right ALT */ + if (down) + vs->modifiers_state[keycode] = 1; + else + vs->modifiers_state[keycode] = 0; + break; + case 0x02 ... 0x0a: /* '1' to '9' keys */ + if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) { + /* Reset the modifiers sent to the current console */ + reset_keys(vs); + console_select(keycode - 0x02); + return; + } + break; + case 0x3a: /* CapsLock */ + case 0x45: /* NumLock */ + if (down) + vs->modifiers_state[keycode] ^= 1; + break; + } + + /* Turn off the lock state sync logic if the client support the led + state extension. + */ + if (down && vs->vd->lock_key_sync && + !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) && + keycode_is_keypad(vs->vd->kbd_layout, keycode)) { + /* If the numlock state needs to change then simulate an additional + keypress before sending this one. This will happen if the user + toggles numlock away from the VNC window. + */ + if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) { + if (!vs->modifiers_state[0x45]) { + trace_vnc_key_sync_numlock(true); + vs->modifiers_state[0x45] = 1; + press_key(vs, 0xff7f); + } + } else { + if (vs->modifiers_state[0x45]) { + trace_vnc_key_sync_numlock(false); + vs->modifiers_state[0x45] = 0; + press_key(vs, 0xff7f); + } + } + } + + if (down && vs->vd->lock_key_sync && + !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) && + ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) { + /* If the capslock state needs to change then simulate an additional + keypress before sending this one. This will happen if the user + toggles capslock away from the VNC window. + */ + int uppercase = !!(sym >= 'A' && sym <= 'Z'); + int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]); + int capslock = !!(vs->modifiers_state[0x3a]); + if (capslock) { + if (uppercase == shift) { + trace_vnc_key_sync_capslock(false); + vs->modifiers_state[0x3a] = 0; + press_key(vs, 0xffe5); + } + } else { + if (uppercase != shift) { + trace_vnc_key_sync_capslock(true); + vs->modifiers_state[0x3a] = 1; + press_key(vs, 0xffe5); + } + } + } + + if (qemu_console_is_graphic(NULL)) { + qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, down); + } else { + bool numlock = vs->modifiers_state[0x45]; + bool control = (vs->modifiers_state[0x1d] || + vs->modifiers_state[0x9d]); + /* QEMU console emulation */ + if (down) { + switch (keycode) { + case 0x2a: /* Left Shift */ + case 0x36: /* Right Shift */ + case 0x1d: /* Left CTRL */ + case 0x9d: /* Right CTRL */ + case 0x38: /* Left ALT */ + case 0xb8: /* Right ALT */ + break; + case 0xc8: + kbd_put_keysym(QEMU_KEY_UP); + break; + case 0xd0: + kbd_put_keysym(QEMU_KEY_DOWN); + break; + case 0xcb: + kbd_put_keysym(QEMU_KEY_LEFT); + break; + case 0xcd: + kbd_put_keysym(QEMU_KEY_RIGHT); + break; + case 0xd3: + kbd_put_keysym(QEMU_KEY_DELETE); + break; + case 0xc7: + kbd_put_keysym(QEMU_KEY_HOME); + break; + case 0xcf: + kbd_put_keysym(QEMU_KEY_END); + break; + case 0xc9: + kbd_put_keysym(QEMU_KEY_PAGEUP); + break; + case 0xd1: + kbd_put_keysym(QEMU_KEY_PAGEDOWN); + break; + + case 0x47: + kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME); + break; + case 0x48: + kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP); + break; + case 0x49: + kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP); + break; + case 0x4b: + kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT); + break; + case 0x4c: + kbd_put_keysym('5'); + break; + case 0x4d: + kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT); + break; + case 0x4f: + kbd_put_keysym(numlock ? '1' : QEMU_KEY_END); + break; + case 0x50: + kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN); + break; + case 0x51: + kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN); + break; + case 0x52: + kbd_put_keysym('0'); + break; + case 0x53: + kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE); + break; + + case 0xb5: + kbd_put_keysym('/'); + break; + case 0x37: + kbd_put_keysym('*'); + break; + case 0x4a: + kbd_put_keysym('-'); + break; + case 0x4e: + kbd_put_keysym('+'); + break; + case 0x9c: + kbd_put_keysym('\n'); + break; + + default: + if (control) { + kbd_put_keysym(sym & 0x1f); + } else { + kbd_put_keysym(sym); + } + break; + } + } + } +} +",0,"static void do_key_event(VncState *vs, int down, int keycode, int sym) +{ + /* QEMU console switch */ + switch(keycode) { + case 0x2a: /* Left Shift */ + case 0x36: /* Right Shift */ + case 0x1d: /* Left CTRL */ + case 0x9d: /* Right CTRL */ + case 0x38: /* Left ALT */ + case 0xb8: /* Right ALT */ + if (down) + vs->modifiers_state[keycode] = 1; + else + vs->modifiers_state[keycode] = 0; + break; + case 0x02 ... 0x0a: /* '1' to '9' keys */ + if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) { + /* Reset the modifiers sent to the current console */ + reset_keys(vs); + console_select(keycode - 0x02); + return; + } + break; + case 0x3a: /* CapsLock */ + case 0x45: /* NumLock */ + if (down) + vs->modifiers_state[keycode] ^= 1; + break; + } + + /* Turn off the lock state sync logic if the client support the led + state extension. + */ + if (down && vs->vd->lock_key_sync && + !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) && + keycode_is_keypad(vs->vd->kbd_layout, keycode)) { + /* If the numlock state needs to change then simulate an additional + keypress before sending this one. This will happen if the user + toggles numlock away from the VNC window. + */ + if (keysym_is_numlock(vs->vd->kbd_layout, sym & 0xFFFF)) { + if (!vs->modifiers_state[0x45]) { + trace_vnc_key_sync_numlock(true); + vs->modifiers_state[0x45] = 1; + press_key(vs, 0xff7f); + } + } else { + if (vs->modifiers_state[0x45]) { + trace_vnc_key_sync_numlock(false); + vs->modifiers_state[0x45] = 0; + press_key(vs, 0xff7f); + } + } + } + + if (down && vs->vd->lock_key_sync && + !vnc_has_feature(vs, VNC_FEATURE_LED_STATE) && + ((sym >= 'A' && sym <= 'Z') || (sym >= 'a' && sym <= 'z'))) { + /* If the capslock state needs to change then simulate an additional + keypress before sending this one. This will happen if the user + toggles capslock away from the VNC window. + */ + int uppercase = !!(sym >= 'A' && sym <= 'Z'); + int shift = !!(vs->modifiers_state[0x2a] | vs->modifiers_state[0x36]); + int capslock = !!(vs->modifiers_state[0x3a]); + if (capslock) { + if (uppercase == shift) { + trace_vnc_key_sync_capslock(false); + vs->modifiers_state[0x3a] = 0; + press_key(vs, 0xffe5); + } + } else { + if (uppercase != shift) { + trace_vnc_key_sync_capslock(true); + vs->modifiers_state[0x3a] = 1; + press_key(vs, 0xffe5); + } + } + } + + if (qemu_console_is_graphic(NULL)) { + qemu_input_event_send_key_number(vs->vd->dcl.con, keycode, down); + } else { + bool numlock = vs->modifiers_state[0x45]; + bool control = (vs->modifiers_state[0x1d] || + vs->modifiers_state[0x9d]); + /* QEMU console emulation */ + if (down) { + switch (keycode) { + case 0x2a: /* Left Shift */ + case 0x36: /* Right Shift */ + case 0x1d: /* Left CTRL */ + case 0x9d: /* Right CTRL */ + case 0x38: /* Left ALT */ + case 0xb8: /* Right ALT */ + break; + case 0xc8: + kbd_put_keysym(QEMU_KEY_UP); + break; + case 0xd0: + kbd_put_keysym(QEMU_KEY_DOWN); + break; + case 0xcb: + kbd_put_keysym(QEMU_KEY_LEFT); + break; + case 0xcd: + kbd_put_keysym(QEMU_KEY_RIGHT); + break; + case 0xd3: + kbd_put_keysym(QEMU_KEY_DELETE); + break; + case 0xc7: + kbd_put_keysym(QEMU_KEY_HOME); + break; + case 0xcf: + kbd_put_keysym(QEMU_KEY_END); + break; + case 0xc9: + kbd_put_keysym(QEMU_KEY_PAGEUP); + break; + case 0xd1: + kbd_put_keysym(QEMU_KEY_PAGEDOWN); + break; + + case 0x47: + kbd_put_keysym(numlock ? '7' : QEMU_KEY_HOME); + break; + case 0x48: + kbd_put_keysym(numlock ? '8' : QEMU_KEY_UP); + break; + case 0x49: + kbd_put_keysym(numlock ? '9' : QEMU_KEY_PAGEUP); + break; + case 0x4b: + kbd_put_keysym(numlock ? '4' : QEMU_KEY_LEFT); + break; + case 0x4c: + kbd_put_keysym('5'); + break; + case 0x4d: + kbd_put_keysym(numlock ? '6' : QEMU_KEY_RIGHT); + break; + case 0x4f: + kbd_put_keysym(numlock ? '1' : QEMU_KEY_END); + break; + case 0x50: + kbd_put_keysym(numlock ? '2' : QEMU_KEY_DOWN); + break; + case 0x51: + kbd_put_keysym(numlock ? '3' : QEMU_KEY_PAGEDOWN); + break; + case 0x52: + kbd_put_keysym('0'); + break; + case 0x53: + kbd_put_keysym(numlock ? '.' : QEMU_KEY_DELETE); + break; + + case 0xb5: + kbd_put_keysym('/'); + break; + case 0x37: + kbd_put_keysym('*'); + break; + case 0x4a: + kbd_put_keysym('-'); + break; + case 0x4e: + kbd_put_keysym('+'); + break; + case 0x9c: + kbd_put_keysym('\n'); + break; + + default: + if (control) { + kbd_put_keysym(sym & 0x1f); + } else { + kbd_put_keysym(sym); + } + break; + } + } + } +} +","@@ -2026,6 +2026,16 @@ static void set_pixel_format(VncState *vs, + return; + } + ++ switch (bits_per_pixel) { ++ case 8: ++ case 16: ++ case 32: ++ break; ++ default: ++ vnc_client_error(vs); ++ return; ++ } ++ + vs->client_pf.rmax = red_max; + vs->client_pf.rbits = hweight_long(red_max); + vs->client_pf.rshift = red_shift;",1603,1934,2048 +432,"SplashError Splash::blitTransparent(SplashBitmap *src, int xSrc, int ySrc, + int xDest, int yDest, int w, int h) { + SplashColorPtr p, sp; + Guchar *q; + int x, y, mask, srcMask; + + if (src->mode != bitmap->mode) { + return splashErrModeMismatch; + } + + switch (bitmap->mode) { + case splashModeMono1: + for (y = 0; y < h; ++y) { + p = &bitmap->data[(yDest + y) * bitmap->rowSize + (xDest >> 3)]; + mask = 0x80 >> (xDest & 7); + sp = &src->data[(ySrc + y) * src->rowSize + (xSrc >> 3)]; + srcMask = 0x80 >> (xSrc & 7); + for (x = 0; x < w; ++x) { + if (*sp & srcMask) { + *p |= mask; + } else { + *p &= ~mask; + } + if (!(mask >>= 1)) { + mask = 0x80; + ++p; + } + if (!(srcMask >>= 1)) { + srcMask = 0x80; + ++sp; + } + } + } + break; + case splashModeMono8: + for (y = 0; y < h; ++y) { + p = &bitmap->data[(yDest + y) * bitmap->rowSize + xDest]; + sp = &src->data[(ySrc + y) * bitmap->rowSize + xSrc]; + for (x = 0; x < w; ++x) { + *p++ = *sp++; + } + } + break; + case splashModeRGB8: + case splashModeBGR8: + for (y = 0; y < h; ++y) { + p = &bitmap->data[(yDest + y) * bitmap->rowSize + 3 * xDest]; + sp = &src->data[(ySrc + y) * src->rowSize + 3 * xSrc]; + for (x = 0; x < w; ++x) { + *p++ = *sp++; + *p++ = *sp++; + *p++ = *sp++; + } + } + break; + case splashModeXBGR8: + for (y = 0; y < h; ++y) { + p = &bitmap->data[(yDest + y) * bitmap->rowSize + 4 * xDest]; + sp = &src->data[(ySrc + y) * src->rowSize + 4 * xSrc]; + for (x = 0; x < w; ++x) { + *p++ = *sp++; + *p++ = *sp++; + *p++ = *sp++; + *p++ = 255; + sp++; + } + } + break; +#if SPLASH_CMYK + case splashModeCMYK8: + for (y = 0; y < h; ++y) { + p = &bitmap->data[(yDest + y) * bitmap->rowSize + 4 * xDest]; + sp = &src->data[(ySrc + y) * src->rowSize + 4 * xSrc]; + for (x = 0; x < w; ++x) { + *p++ = *sp++; + *p++ = *sp++; + *p++ = *sp++; + *p++ = *sp++; + } + } + break; + case splashModeDeviceN8: + for (y = 0; y < h; ++y) { + p = &bitmap->data[(yDest + y) * bitmap->rowSize + (SPOT_NCOMPS+4) * xDest]; + sp = &src->data[(ySrc + y) * src->rowSize + (SPOT_NCOMPS+4) * xSrc]; + for (x = 0; x < w; ++x) { + for (int cp=0; cp < SPOT_NCOMPS+4; cp++) + *p++ = *sp++; + } + } + break; +#endif + } + + if (bitmap->alpha) { + for (y = 0; y < h; ++y) { + q = &bitmap->alpha[(yDest + y) * bitmap->width + xDest]; + memset(q, 0x00, w); + } + } + + return splashOk; +} +",0,"SplashError Splash::blitTransparent(SplashBitmap *src, int xSrc, int ySrc, + int xDest, int yDest, int w, int h) { + SplashColorPtr p, sp; + Guchar *q; + int x, y, mask, srcMask; + + if (src->mode != bitmap->mode) { + return splashErrModeMismatch; + } + + switch (bitmap->mode) { + case splashModeMono1: + for (y = 0; y < h; ++y) { + p = &bitmap->data[(yDest + y) * bitmap->rowSize + (xDest >> 3)]; + mask = 0x80 >> (xDest & 7); + sp = &src->data[(ySrc + y) * src->rowSize + (xSrc >> 3)]; + srcMask = 0x80 >> (xSrc & 7); + for (x = 0; x < w; ++x) { + if (*sp & srcMask) { + *p |= mask; + } else { + *p &= ~mask; + } + if (!(mask >>= 1)) { + mask = 0x80; + ++p; + } + if (!(srcMask >>= 1)) { + srcMask = 0x80; + ++sp; + } + } + } + break; + case splashModeMono8: + for (y = 0; y < h; ++y) { + p = &bitmap->data[(yDest + y) * bitmap->rowSize + xDest]; + sp = &src->data[(ySrc + y) * bitmap->rowSize + xSrc]; + for (x = 0; x < w; ++x) { + *p++ = *sp++; + } + } + break; + case splashModeRGB8: + case splashModeBGR8: + for (y = 0; y < h; ++y) { + p = &bitmap->data[(yDest + y) * bitmap->rowSize + 3 * xDest]; + sp = &src->data[(ySrc + y) * src->rowSize + 3 * xSrc]; + for (x = 0; x < w; ++x) { + *p++ = *sp++; + *p++ = *sp++; + *p++ = *sp++; + } + } + break; + case splashModeXBGR8: + for (y = 0; y < h; ++y) { + p = &bitmap->data[(yDest + y) * bitmap->rowSize + 4 * xDest]; + sp = &src->data[(ySrc + y) * src->rowSize + 4 * xSrc]; + for (x = 0; x < w; ++x) { + *p++ = *sp++; + *p++ = *sp++; + *p++ = *sp++; + *p++ = 255; + sp++; + } + } + break; +#if SPLASH_CMYK + case splashModeCMYK8: + for (y = 0; y < h; ++y) { + p = &bitmap->data[(yDest + y) * bitmap->rowSize + 4 * xDest]; + sp = &src->data[(ySrc + y) * src->rowSize + 4 * xSrc]; + for (x = 0; x < w; ++x) { + *p++ = *sp++; + *p++ = *sp++; + *p++ = *sp++; + *p++ = *sp++; + } + } + break; + case splashModeDeviceN8: + for (y = 0; y < h; ++y) { + p = &bitmap->data[(yDest + y) * bitmap->rowSize + (SPOT_NCOMPS+4) * xDest]; + sp = &src->data[(ySrc + y) * src->rowSize + (SPOT_NCOMPS+4) * xSrc]; + for (x = 0; x < w; ++x) { + for (int cp=0; cp < SPOT_NCOMPS+4; cp++) + *p++ = *sp++; + } + } + break; +#endif + } + + if (bitmap->alpha) { + for (y = 0; y < h; ++y) { + q = &bitmap->alpha[(yDest + y) * bitmap->width + xDest]; + memset(q, 0x00, w); + } + } + + return splashOk; +} +","@@ -2955,7 +2955,7 @@ void Splash::arbitraryTransformMask(SplashImageMaskSource src, void *srcData, + scaledMask = scaleMask(src, srcData, srcWidth, srcHeight, + scaledWidth, scaledHeight); + if (scaledMask->data == NULL) { +- error(errInternal, -1, ""scaledMask->data is NULL in Splash::scaleMaskYuXu""); ++ error(errInternal, -1, ""scaledMask->data is NULL in Splash::arbitraryTransformMask""); + delete scaledMask; + return; + } +@@ -3461,11 +3461,15 @@ void Splash::blitMask(SplashBitmap *src, int xDest, int yDest, + + w = src->getWidth(); + h = src->getHeight(); ++ p = src->getDataPtr(); ++ if (p == NULL) { ++ error(errInternal, -1, ""src->getDataPtr() is NULL in Splash::blitMask""); ++ return; ++ } + if (vectorAntialias && clipRes != splashClipAllInside) { + pipeInit(&pipe, xDest, yDest, state->fillPattern, NULL, + (Guchar)splashRound(state->fillAlpha * 255), gTrue, gFalse); + drawAAPixelInit(); +- p = src->getDataPtr(); + for (y = 0; y < h; ++y) { + for (x = 0; x < w; ++x) { + pipe.shape = *p++; +@@ -3475,7 +3479,6 @@ void Splash::blitMask(SplashBitmap *src, int xDest, int yDest, + } else { + pipeInit(&pipe, xDest, yDest, state->fillPattern, NULL, + (Guchar)splashRound(state->fillAlpha * 255), gTrue, gFalse); +- p = src->getDataPtr(); + if (clipRes == splashClipAllInside) { + for (y = 0; y < h; ++y) { + pipeSetXY(&pipe, xDest, yDest + y);",992,1323,2048 +18290,"static MagickBooleanType DecodeImage(Image *image,unsigned char *luma, + unsigned char *chroma1,unsigned char *chroma2,ExceptionInfo *exception) +{ +#define IsSync(sum) ((sum & 0xffffff00UL) == 0xfffffe00UL) +#define PCDGetBits(n) \ +{ \ + sum=(sum << n) & 0xffffffff; \ + bits-=n; \ + while (bits <= 24) \ + { \ + if (p >= (buffer+0x800)) \ + { \ + count=ReadBlob(image,0x800,buffer); \ + p=buffer; \ + } \ + sum|=((unsigned int) (*p) << (24-bits)); \ + bits+=8; \ + p++; \ + } \ +} + + typedef struct PCDTable + { + unsigned int + length, + sequence; + + MagickStatusType + mask; + + unsigned char + key; + } PCDTable; + + PCDTable + *pcd_table[3]; + + register ssize_t + i, + j; + + register PCDTable + *r; + + register unsigned char + *p, + *q; + + size_t + bits, + length, + plane, + pcd_length[3], + row, + sum; + + ssize_t + count, + quantum; + + unsigned char + *buffer; + + /* + Initialize Huffman tables. + */ + assert(image != (const Image *) NULL); + assert(image->signature == MagickCoreSignature); + if (image->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); + assert(luma != (unsigned char *) NULL); + assert(chroma1 != (unsigned char *) NULL); + assert(chroma2 != (unsigned char *) NULL); + buffer=(unsigned char *) AcquireQuantumMemory(0x800,sizeof(*buffer)); + if (buffer == (unsigned char *) NULL) + ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", + image->filename); + sum=0; + bits=32; + p=buffer+0x800; + for (i=0; i < 3; i++) + { + pcd_table[i]=(PCDTable *) NULL; + pcd_length[i]=0; + } + for (i=0; i < (image->columns > 1536 ? 3 : 1); i++) + { + PCDGetBits(8); + length=(sum & 0xff)+1; + pcd_table[i]=(PCDTable *) AcquireQuantumMemory(length, + sizeof(*pcd_table[i])); + if (pcd_table[i] == (PCDTable *) NULL) + { + buffer=(unsigned char *) RelinquishMagickMemory(buffer); + ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", + image->filename); + } + r=pcd_table[i]; + for (j=0; j < (ssize_t) length; j++) + { + PCDGetBits(8); + r->length=(unsigned int) (sum & 0xff)+1; + if (r->length > 16) + { + buffer=(unsigned char *) RelinquishMagickMemory(buffer); + return(MagickFalse); + } + PCDGetBits(16); + r->sequence=(unsigned int) (sum & 0xffff) << 16; + PCDGetBits(8); + r->key=(unsigned char) (sum & 0xff); + r->mask=(~((1U << (32-r->length))-1)); + r++; + } + pcd_length[i]=(size_t) length; + } + /* + Search for Sync byte. + */ + for (i=0; i < 1; i++) + PCDGetBits(16); + for (i=0; i < 1; i++) + PCDGetBits(16); + while ((sum & 0x00fff000UL) != 0x00fff000UL) + PCDGetBits(8); + while (IsSync(sum) == 0) + PCDGetBits(1); + /* + Recover the Huffman encoded luminance and chrominance deltas. + */ + count=0; + length=0; + plane=0; + row=0; + q=luma; + for ( ; ; ) + { + if (IsSync(sum) != 0) + { + /* + Determine plane and row number. + */ + PCDGetBits(16); + row=((sum >> 9) & 0x1fff); + if (row == image->rows) + break; + PCDGetBits(8); + plane=sum >> 30; + PCDGetBits(16); + switch (plane) + { + case 0: + { + q=luma+row*image->columns; + count=(ssize_t) image->columns; + break; + } + case 2: + { + q=chroma1+(row >> 1)*image->columns; + count=(ssize_t) (image->columns >> 1); + plane--; + break; + } + case 3: + { + q=chroma2+(row >> 1)*image->columns; + count=(ssize_t) (image->columns >> 1); + plane--; + break; + } + default: + { + for (i=0; i < (image->columns > 1536 ? 3 : 1); i++) + pcd_table[i]=(PCDTable *) RelinquishMagickMemory(pcd_table[i]); + buffer=(unsigned char *) RelinquishMagickMemory(buffer); + ThrowBinaryException(CorruptImageError,""CorruptImage"", + image->filename); + } + } + length=pcd_length[plane]; + continue; + } + /* + Decode luminance or chrominance deltas. + */ + r=pcd_table[plane]; + for (i=0; ((i < (ssize_t) length) && ((sum & r->mask) != r->sequence)); i++) + r++; + if ((row > image->rows) || (r == (PCDTable *) NULL)) + { + (void) ThrowMagickException(exception,GetMagickModule(), + CorruptImageWarning,""SkipToSyncByte"",""`%s'"",image->filename); + while ((sum & 0x00fff000) != 0x00fff000) + PCDGetBits(8); + while (IsSync(sum) == 0) + PCDGetBits(1); + continue; + } + if (r->key < 128) + quantum=(ssize_t) (*q)+r->key; + else + quantum=(ssize_t) (*q)+r->key-256; + *q=(unsigned char) ((quantum < 0) ? 0 : (quantum > 255) ? 255 : quantum); + q++; + PCDGetBits(r->length); + count--; + } + /* + Relinquish resources. + */ + for (i=0; i < (image->columns > 1536 ? 3 : 1); i++) + pcd_table[i]=(PCDTable *) RelinquishMagickMemory(pcd_table[i]); + buffer=(unsigned char *) RelinquishMagickMemory(buffer); + return(MagickTrue); +} +",1,"static MagickBooleanType DecodeImage(Image *image,unsigned char *luma, + unsigned char *chroma1,unsigned char *chroma2,ExceptionInfo *exception) +{ +#define IsSync(sum) ((sum & 0xffffff00UL) == 0xfffffe00UL) +#define PCDGetBits(n) \ +{ \ + sum=(sum << n) & 0xffffffff; \ + bits-=n; \ + while (bits <= 24) \ + { \ + if (p >= (buffer+0x800)) \ + { \ + count=ReadBlob(image,0x800,buffer); \ + p=buffer; \ + } \ + sum|=((unsigned int) (*p) << (24-bits)); \ + bits+=8; \ + p++; \ + } \ +} + + typedef struct PCDTable + { + unsigned int + length, + sequence; + + MagickStatusType + mask; + + unsigned char + key; + } PCDTable; + + PCDTable + *pcd_table[3]; + + register ssize_t + i, + j; + + register PCDTable + *r; + + register unsigned char + *p, + *q; + + size_t + bits, + length, + plane, + pcd_length[3], + row, + sum; + + ssize_t + count, + quantum; + + unsigned char + *buffer; + + /* + Initialize Huffman tables. + */ + assert(image != (const Image *) NULL); + assert(image->signature == MagickCoreSignature); + if (image->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); + assert(luma != (unsigned char *) NULL); + assert(chroma1 != (unsigned char *) NULL); + assert(chroma2 != (unsigned char *) NULL); + buffer=(unsigned char *) AcquireQuantumMemory(0x800,sizeof(*buffer)); + if (buffer == (unsigned char *) NULL) + ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", + image->filename); + sum=0; + bits=32; + p=buffer+0x800; + for (i=0; i < 3; i++) + { + pcd_table[i]=(PCDTable *) NULL; + pcd_length[i]=0; + } + for (i=0; i < (image->columns > 1536 ? 3 : 1); i++) + { + PCDGetBits(8); + length=(sum & 0xff)+1; + pcd_table[i]=(PCDTable *) AcquireQuantumMemory(length, + sizeof(*pcd_table[i])); + if (pcd_table[i] == (PCDTable *) NULL) + { + buffer=(unsigned char *) RelinquishMagickMemory(buffer); + for (j=0; j < i; j++) + pcd_table[j]=(PCDTable *) RelinquishMagickMemory(pcd_table[j]); + ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", + image->filename); + } + r=pcd_table[i]; + for (j=0; j < (ssize_t) length; j++) + { + PCDGetBits(8); + r->length=(unsigned int) (sum & 0xff)+1; + if (r->length > 16) + { + buffer=(unsigned char *) RelinquishMagickMemory(buffer); + for (j=0; j <= i; j++) + pcd_table[j]=(PCDTable *) RelinquishMagickMemory(pcd_table[j]); + return(MagickFalse); + } + PCDGetBits(16); + r->sequence=(unsigned int) (sum & 0xffff) << 16; + PCDGetBits(8); + r->key=(unsigned char) (sum & 0xff); + r->mask=(~((1U << (32-r->length))-1)); + r++; + } + pcd_length[i]=(size_t) length; + } + /* + Search for Sync byte. + */ + for (i=0; i < 1; i++) + PCDGetBits(16); + for (i=0; i < 1; i++) + PCDGetBits(16); + while ((sum & 0x00fff000UL) != 0x00fff000UL) + PCDGetBits(8); + while (IsSync(sum) == 0) + PCDGetBits(1); + /* + Recover the Huffman encoded luminance and chrominance deltas. + */ + count=0; + length=0; + plane=0; + row=0; + q=luma; + for ( ; ; ) + { + if (IsSync(sum) != 0) + { + /* + Determine plane and row number. + */ + PCDGetBits(16); + row=((sum >> 9) & 0x1fff); + if (row == image->rows) + break; + PCDGetBits(8); + plane=sum >> 30; + PCDGetBits(16); + switch (plane) + { + case 0: + { + q=luma+row*image->columns; + count=(ssize_t) image->columns; + break; + } + case 2: + { + q=chroma1+(row >> 1)*image->columns; + count=(ssize_t) (image->columns >> 1); + plane--; + break; + } + case 3: + { + q=chroma2+(row >> 1)*image->columns; + count=(ssize_t) (image->columns >> 1); + plane--; + break; + } + default: + { + for (i=0; i < (image->columns > 1536 ? 3 : 1); i++) + pcd_table[i]=(PCDTable *) RelinquishMagickMemory(pcd_table[i]); + buffer=(unsigned char *) RelinquishMagickMemory(buffer); + ThrowBinaryException(CorruptImageError,""CorruptImage"", + image->filename); + } + } + length=pcd_length[plane]; + continue; + } + /* + Decode luminance or chrominance deltas. + */ + r=pcd_table[plane]; + for (i=0; ((i < (ssize_t) length) && ((sum & r->mask) != r->sequence)); i++) + r++; + if ((row > image->rows) || (r == (PCDTable *) NULL)) + { + (void) ThrowMagickException(exception,GetMagickModule(), + CorruptImageWarning,""SkipToSyncByte"",""`%s'"",image->filename); + while ((sum & 0x00fff000) != 0x00fff000) + PCDGetBits(8); + while (IsSync(sum) == 0) + PCDGetBits(1); + continue; + } + if (r->key < 128) + quantum=(ssize_t) (*q)+r->key; + else + quantum=(ssize_t) (*q)+r->key-256; + *q=(unsigned char) ((quantum < 0) ? 0 : (quantum > 255) ? 255 : quantum); + q++; + PCDGetBits(r->length); + count--; + } + /* + Relinquish resources. + */ + for (i=0; i < (image->columns > 1536 ? 3 : 1); i++) + pcd_table[i]=(PCDTable *) RelinquishMagickMemory(pcd_table[i]); + buffer=(unsigned char *) RelinquishMagickMemory(buffer); + return(MagickTrue); +} +","@@ -204,6 +204,8 @@ static MagickBooleanType DecodeImage(Image *image,unsigned char *luma, + if (pcd_table[i] == (PCDTable *) NULL) + { + buffer=(unsigned char *) RelinquishMagickMemory(buffer); ++ for (j=0; j < i; j++) ++ pcd_table[j]=(PCDTable *) RelinquishMagickMemory(pcd_table[j]); + ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", + image->filename); + } +@@ -215,6 +217,8 @@ static MagickBooleanType DecodeImage(Image *image,unsigned char *luma, + if (r->length > 16) + { + buffer=(unsigned char *) RelinquishMagickMemory(buffer); ++ for (j=0; j <= i; j++) ++ pcd_table[j]=(PCDTable *) RelinquishMagickMemory(pcd_table[j]); + return(MagickFalse); + } + PCDGetBits(16);",1647,1978,2048 +8131,"static int wc_ecc_import_raw_private(ecc_key* key, const char* qx, + const char* qy, const char* d, int curve_id, int encType) +{ + int err = MP_OKAY; + + /* if d is NULL, only import as public key using Qx,Qy */ + if (key == NULL || qx == NULL || qy == NULL) { + return BAD_FUNC_ARG; + } + + /* make sure required variables are reset */ + wc_ecc_reset(key); + + /* set curve type and index */ + err = wc_ecc_set_curve(key, 0, curve_id); + if (err != 0) { + return err; + } + +#ifdef WOLFSSL_ATECC508A + /* TODO: Implement equiv call to ATECC508A */ + err = BAD_COND_E; + +#else + + /* init key */ +#ifdef ALT_ECC_SIZE + key->pubkey.x = (mp_int*)&key->pubkey.xyz[0]; + key->pubkey.y = (mp_int*)&key->pubkey.xyz[1]; + key->pubkey.z = (mp_int*)&key->pubkey.xyz[2]; + alt_fp_init(key->pubkey.x); + alt_fp_init(key->pubkey.y); + alt_fp_init(key->pubkey.z); + err = mp_init(&key->k); +#else + err = mp_init_multi(&key->k, key->pubkey.x, key->pubkey.y, key->pubkey.z, + NULL, NULL); +#endif + if (err != MP_OKAY) + return MEMORY_E; + + /* read Qx */ + if (err == MP_OKAY) { + if (encType == ECC_TYPE_HEX_STR) + err = mp_read_radix(key->pubkey.x, qx, MP_RADIX_HEX); + else + err = mp_read_unsigned_bin(key->pubkey.x, (const byte*)qx, + key->dp->size); + } + + /* read Qy */ + if (err == MP_OKAY) { + if (encType == ECC_TYPE_HEX_STR) + err = mp_read_radix(key->pubkey.y, qy, MP_RADIX_HEX); + else + err = mp_read_unsigned_bin(key->pubkey.y, (const byte*)qy, + key->dp->size); + + } + + if (err == MP_OKAY) + err = mp_set(key->pubkey.z, 1); + + /* import private key */ + if (err == MP_OKAY) { + if (d != NULL) { + key->type = ECC_PRIVATEKEY; + + if (encType == ECC_TYPE_HEX_STR) + err = mp_read_radix(&key->k, d, MP_RADIX_HEX); + else + err = mp_read_unsigned_bin(&key->k, (const byte*)d, + key->dp->size); + + } else { + key->type = ECC_PUBLICKEY; + } + } + +#ifdef WOLFSSL_VALIDATE_ECC_IMPORT + if (err == MP_OKAY) + err = wc_ecc_check_key(key); +#endif + + if (err != MP_OKAY) { + mp_clear(key->pubkey.x); + mp_clear(key->pubkey.y); + mp_clear(key->pubkey.z); + mp_clear(&key->k); + } +#endif /* WOLFSSL_ATECC508A */ + + return err; +} +",0,"static int wc_ecc_import_raw_private(ecc_key* key, const char* qx, + const char* qy, const char* d, int curve_id, int encType) +{ + int err = MP_OKAY; + + /* if d is NULL, only import as public key using Qx,Qy */ + if (key == NULL || qx == NULL || qy == NULL) { + return BAD_FUNC_ARG; + } + + /* make sure required variables are reset */ + wc_ecc_reset(key); + + /* set curve type and index */ + err = wc_ecc_set_curve(key, 0, curve_id); + if (err != 0) { + return err; + } + +#ifdef WOLFSSL_ATECC508A + /* TODO: Implement equiv call to ATECC508A */ + err = BAD_COND_E; + +#else + + /* init key */ +#ifdef ALT_ECC_SIZE + key->pubkey.x = (mp_int*)&key->pubkey.xyz[0]; + key->pubkey.y = (mp_int*)&key->pubkey.xyz[1]; + key->pubkey.z = (mp_int*)&key->pubkey.xyz[2]; + alt_fp_init(key->pubkey.x); + alt_fp_init(key->pubkey.y); + alt_fp_init(key->pubkey.z); + err = mp_init(&key->k); +#else + err = mp_init_multi(&key->k, key->pubkey.x, key->pubkey.y, key->pubkey.z, + NULL, NULL); +#endif + if (err != MP_OKAY) + return MEMORY_E; + + /* read Qx */ + if (err == MP_OKAY) { + if (encType == ECC_TYPE_HEX_STR) + err = mp_read_radix(key->pubkey.x, qx, MP_RADIX_HEX); + else + err = mp_read_unsigned_bin(key->pubkey.x, (const byte*)qx, + key->dp->size); + } + + /* read Qy */ + if (err == MP_OKAY) { + if (encType == ECC_TYPE_HEX_STR) + err = mp_read_radix(key->pubkey.y, qy, MP_RADIX_HEX); + else + err = mp_read_unsigned_bin(key->pubkey.y, (const byte*)qy, + key->dp->size); + + } + + if (err == MP_OKAY) + err = mp_set(key->pubkey.z, 1); + + /* import private key */ + if (err == MP_OKAY) { + if (d != NULL) { + key->type = ECC_PRIVATEKEY; + + if (encType == ECC_TYPE_HEX_STR) + err = mp_read_radix(&key->k, d, MP_RADIX_HEX); + else + err = mp_read_unsigned_bin(&key->k, (const byte*)d, + key->dp->size); + + } else { + key->type = ECC_PUBLICKEY; + } + } + +#ifdef WOLFSSL_VALIDATE_ECC_IMPORT + if (err == MP_OKAY) + err = wc_ecc_check_key(key); +#endif + + if (err != MP_OKAY) { + mp_clear(key->pubkey.x); + mp_clear(key->pubkey.y); + mp_clear(key->pubkey.z); + mp_clear(&key->k); + } +#endif /* WOLFSSL_ATECC508A */ + + return err; +} +","@@ -3139,19 +3139,19 @@ static int wc_ecc_gen_k(WC_RNG* rng, int size, mp_int* k, mp_int* order) + if (err == 0) + err = mp_read_unsigned_bin(k, (byte*)buf, size); + +- /* quick sanity check to make sure we're not dealing with a 0 key */ +- if (err == MP_OKAY) { +- if (mp_iszero(k) == MP_YES) +- err = MP_ZERO_E; +- } +- + /* the key should be smaller than the order of base point */ + if (err == MP_OKAY) { + if (mp_cmp(k, order) != MP_LT) { + err = mp_mod(k, order, k); + } + } + ++ /* quick sanity check to make sure we're not dealing with a 0 key */ ++ if (err == MP_OKAY) { ++ if (mp_iszero(k) == MP_YES) ++ err = MP_ZERO_E; ++ } ++ + ForceZero(buf, ECC_MAXSIZE); + #ifdef WOLFSSL_SMALL_STACK + XFREE(buf, NULL, DYNAMIC_TYPE_ECC_BUFFER); +@@ -3924,20 +3924,40 @@ int wc_ecc_sign_hash_ex(const byte* in, word32 inlen, WC_RNG* rng, + + /* don't use async for key, since we don't support async return here */ + if ((err = wc_ecc_init_ex(&pubkey, key->heap, INVALID_DEVID)) == MP_OKAY) { ++ mp_int b; ++ ++ if (err == MP_OKAY) { ++ err = mp_init(&b); ++ } ++ + #ifdef WOLFSSL_CUSTOM_CURVES + /* if custom curve, apply params to pubkey */ +- if (key->idx == ECC_CUSTOM_IDX) { ++ if (err == MP_OKAY && key->idx == ECC_CUSTOM_IDX) { + err = wc_ecc_set_custom_curve(&pubkey, key->dp); + } + #endif + ++ if (err == MP_OKAY) { ++ /* Generate blinding value - non-zero value. */ ++ do { ++ if (++loop_check > 64) { ++ err = RNG_FAILURE_E; ++ break; ++ } ++ ++ err = wc_ecc_gen_k(rng, key->dp->size, &b, curve->order); ++ } ++ while (err == MP_ZERO_E); ++ loop_check = 0; ++ } ++ + for (; err == MP_OKAY;) { + if (++loop_check > 64) { + err = RNG_FAILURE_E; + break; + } + err = wc_ecc_make_key_ex(rng, key->dp->size, &pubkey, +- key->dp->id); ++ key->dp->id); + if (err != MP_OKAY) break; + + /* find r = x1 mod n */ +@@ -3953,30 +3973,50 @@ int wc_ecc_sign_hash_ex(const byte* in, word32 inlen, WC_RNG* rng, + mp_forcezero(&pubkey.k); + } + else { +- /* find s = (e + xr)/k */ ++ /* find s = (e + xr)/k ++ = b.(e/k.b + x.r/k.b) */ ++ ++ /* k = k.b */ ++ err = mp_mulmod(&pubkey.k, &b, curve->order, &pubkey.k); ++ if (err != MP_OKAY) break; ++ ++ /* k = 1/k.b */ + err = mp_invmod(&pubkey.k, curve->order, &pubkey.k); + if (err != MP_OKAY) break; + +- /* s = xr */ ++ /* s = x.r */ + err = mp_mulmod(&key->k, r, curve->order, s); + if (err != MP_OKAY) break; + +- /* s = e + xr */ ++ /* s = x.r/k.b */ ++ err = mp_mulmod(&pubkey.k, s, curve->order, s); ++ if (err != MP_OKAY) break; ++ ++ /* e = e/k.b */ ++ err = mp_mulmod(&pubkey.k, e, curve->order, e); ++ if (err != MP_OKAY) break; ++ ++ /* s = e/k.b + x.r/k.b ++ = (e + x.r)/k.b */ + err = mp_add(e, s, s); + if (err != MP_OKAY) break; + +- /* s = e + xr */ +- err = mp_mod(s, curve->order, s); ++ /* s = b.(e + x.r)/k.b ++ = (e + x.r)/k */ ++ err = mp_mulmod(s, &b, curve->order, s); + if (err != MP_OKAY) break; + + /* s = (e + xr)/k */ +- err = mp_mulmod(s, &pubkey.k, curve->order, s); ++ err = mp_mod(s, curve->order, s); ++ if (err != MP_OKAY) break; + + if (mp_iszero(s) == MP_NO) + break; + } + } + wc_ecc_free(&pubkey); ++ mp_clear(&b); ++ mp_free(&b); + } + } + ",728,1059,2048 +1270,"static void qemu_spice_create_one_update(SimpleSpiceDisplay *ssd, + QXLRect *rect) +{ + SimpleSpiceUpdate *update; + QXLDrawable *drawable; + QXLImage *image; + QXLCommand *cmd; + int bw, bh; + struct timespec time_space; + pixman_image_t *dest; + + trace_qemu_spice_create_update( + rect->left, rect->right, + rect->top, rect->bottom); + + update = g_malloc0(sizeof(*update)); + drawable = &update->drawable; + image = &update->image; + cmd = &update->ext.cmd; + + bw = rect->right - rect->left; + bh = rect->bottom - rect->top; + update->bitmap = g_malloc(bw * bh * 4); + + drawable->bbox = *rect; + drawable->clip.type = SPICE_CLIP_TYPE_NONE; + drawable->effect = QXL_EFFECT_OPAQUE; + drawable->release_info.id = (uintptr_t)(&update->ext); + drawable->type = QXL_DRAW_COPY; + drawable->surfaces_dest[0] = -1; + drawable->surfaces_dest[1] = -1; + drawable->surfaces_dest[2] = -1; + clock_gettime(CLOCK_MONOTONIC, &time_space); + /* time in milliseconds from epoch. */ + drawable->mm_time = time_space.tv_sec * 1000 + + time_space.tv_nsec / 1000 / 1000; + + drawable->u.copy.rop_descriptor = SPICE_ROPD_OP_PUT; + drawable->u.copy.src_bitmap = (uintptr_t)image; + drawable->u.copy.src_area.right = bw; + drawable->u.copy.src_area.bottom = bh; + + QXL_SET_IMAGE_ID(image, QXL_IMAGE_GROUP_DEVICE, ssd->unique++); + image->descriptor.type = SPICE_IMAGE_TYPE_BITMAP; + image->bitmap.flags = QXL_BITMAP_DIRECT | QXL_BITMAP_TOP_DOWN; + image->bitmap.stride = bw * 4; + image->descriptor.width = image->bitmap.x = bw; + image->descriptor.height = image->bitmap.y = bh; + image->bitmap.data = (uintptr_t)(update->bitmap); + image->bitmap.palette = 0; + image->bitmap.format = SPICE_BITMAP_FMT_32BIT; + + dest = pixman_image_create_bits(PIXMAN_x8r8g8b8, bw, bh, + (void *)update->bitmap, bw * 4); + pixman_image_composite(PIXMAN_OP_SRC, ssd->surface, NULL, ssd->mirror, + rect->left, rect->top, 0, 0, + rect->left, rect->top, bw, bh); + pixman_image_composite(PIXMAN_OP_SRC, ssd->mirror, NULL, dest, + rect->left, rect->top, 0, 0, + 0, 0, bw, bh); + pixman_image_unref(dest); + + cmd->type = QXL_CMD_DRAW; + cmd->data = (uintptr_t)drawable; + + QTAILQ_INSERT_TAIL(&ssd->updates, update, next); +} +",0,"static void qemu_spice_create_one_update(SimpleSpiceDisplay *ssd, + QXLRect *rect) +{ + SimpleSpiceUpdate *update; + QXLDrawable *drawable; + QXLImage *image; + QXLCommand *cmd; + int bw, bh; + struct timespec time_space; + pixman_image_t *dest; + + trace_qemu_spice_create_update( + rect->left, rect->right, + rect->top, rect->bottom); + + update = g_malloc0(sizeof(*update)); + drawable = &update->drawable; + image = &update->image; + cmd = &update->ext.cmd; + + bw = rect->right - rect->left; + bh = rect->bottom - rect->top; + update->bitmap = g_malloc(bw * bh * 4); + + drawable->bbox = *rect; + drawable->clip.type = SPICE_CLIP_TYPE_NONE; + drawable->effect = QXL_EFFECT_OPAQUE; + drawable->release_info.id = (uintptr_t)(&update->ext); + drawable->type = QXL_DRAW_COPY; + drawable->surfaces_dest[0] = -1; + drawable->surfaces_dest[1] = -1; + drawable->surfaces_dest[2] = -1; + clock_gettime(CLOCK_MONOTONIC, &time_space); + /* time in milliseconds from epoch. */ + drawable->mm_time = time_space.tv_sec * 1000 + + time_space.tv_nsec / 1000 / 1000; + + drawable->u.copy.rop_descriptor = SPICE_ROPD_OP_PUT; + drawable->u.copy.src_bitmap = (uintptr_t)image; + drawable->u.copy.src_area.right = bw; + drawable->u.copy.src_area.bottom = bh; + + QXL_SET_IMAGE_ID(image, QXL_IMAGE_GROUP_DEVICE, ssd->unique++); + image->descriptor.type = SPICE_IMAGE_TYPE_BITMAP; + image->bitmap.flags = QXL_BITMAP_DIRECT | QXL_BITMAP_TOP_DOWN; + image->bitmap.stride = bw * 4; + image->descriptor.width = image->bitmap.x = bw; + image->descriptor.height = image->bitmap.y = bh; + image->bitmap.data = (uintptr_t)(update->bitmap); + image->bitmap.palette = 0; + image->bitmap.format = SPICE_BITMAP_FMT_32BIT; + + dest = pixman_image_create_bits(PIXMAN_x8r8g8b8, bw, bh, + (void *)update->bitmap, bw * 4); + pixman_image_composite(PIXMAN_OP_SRC, ssd->surface, NULL, ssd->mirror, + rect->left, rect->top, 0, 0, + rect->left, rect->top, bw, bh); + pixman_image_composite(PIXMAN_OP_SRC, ssd->mirror, NULL, dest, + rect->left, rect->top, 0, 0, + 0, 0, bw, bh); + pixman_image_unref(dest); + + cmd->type = QXL_CMD_DRAW; + cmd->data = (uintptr_t)drawable; + + QTAILQ_INSERT_TAIL(&ssd->updates, update, next); +} +","@@ -334,11 +334,23 @@ void qemu_spice_create_host_memslot(SimpleSpiceDisplay *ssd) + void qemu_spice_create_host_primary(SimpleSpiceDisplay *ssd) + { + QXLDevSurfaceCreate surface; ++ uint64_t surface_size; + + memset(&surface, 0, sizeof(surface)); + +- dprint(1, ""%s/%d: %dx%d\n"", __func__, ssd->qxl.id, +- surface_width(ssd->ds), surface_height(ssd->ds)); ++ surface_size = (uint64_t) surface_width(ssd->ds) * ++ surface_height(ssd->ds) * 4; ++ assert(surface_size > 0); ++ assert(surface_size < INT_MAX); ++ if (ssd->bufsize < surface_size) { ++ ssd->bufsize = surface_size; ++ g_free(ssd->buf); ++ ssd->buf = g_malloc(ssd->bufsize); ++ } ++ ++ dprint(1, ""%s/%d: %ux%u (size %"" PRIu64 ""/%d)\n"", __func__, ssd->qxl.id, ++ surface_width(ssd->ds), surface_height(ssd->ds), ++ surface_size, ssd->bufsize); + + surface.format = SPICE_SURFACE_FMT_32_xRGB; + surface.width = surface_width(ssd->ds); +@@ -369,8 +381,6 @@ void qemu_spice_display_init_common(SimpleSpiceDisplay *ssd) + if (ssd->num_surfaces == 0) { + ssd->num_surfaces = 1024; + } +- ssd->bufsize = (16 * 1024 * 1024); +- ssd->buf = g_malloc(ssd->bufsize); + } + + /* display listener callbacks */ +@@ -495,7 +505,7 @@ static void interface_get_init_info(QXLInstance *sin, QXLDevInitInfo *info) + info->num_memslots = NUM_MEMSLOTS; + info->num_memslots_groups = NUM_MEMSLOTS_GROUPS; + info->internal_groupslot_id = 0; +- info->qxl_ram_size = ssd->bufsize; ++ info->qxl_ram_size = 16 * 1024 * 1024; + info->n_surfaces = ssd->num_surfaces; + }",703,1034,2048 +12273,"void SafeBrowsingBlockingPageV2::PopulateMalwareStringDictionary( + DictionaryValue* strings) { + std::string diagnostic_link = base::StringPrintf(kSbDiagnosticHtml, + l10n_util::GetStringUTF8( + IDS_SAFE_BROWSING_MALWARE_DIAGNOSTIC_PAGE).c_str()); + + string16 headline, description1, description2, description3; + + + description3 = l10n_util::GetStringUTF16( + IDS_SAFE_BROWSING_MALWARE_V2_DESCRIPTION3); + if (is_main_frame_load_blocked_) { + headline = l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_MALWARE_V2_HEADLINE); + description1 = l10n_util::GetStringFUTF16( + IDS_SAFE_BROWSING_MALWARE_V2_DESCRIPTION1, + l10n_util::GetStringUTF16(IDS_PRODUCT_NAME), + UTF8ToUTF16(url_.host())); + description2 = l10n_util::GetStringUTF16( + IDS_SAFE_BROWSING_MALWARE_V2_DESCRIPTION2); + strings->SetString(""details"", l10n_util::GetStringUTF16( + IDS_SAFE_BROWSING_MALWARE_V2_DETAILS)); + } else { + headline = l10n_util::GetStringUTF16( + IDS_SAFE_BROWSING_MALWARE_V2_HEADLINE_SUBRESOURCE); + description1 = l10n_util::GetStringFUTF16( + IDS_SAFE_BROWSING_MALWARE_V2_DESCRIPTION1_SUBRESOURCE, + l10n_util::GetStringUTF16(IDS_PRODUCT_NAME), + UTF8ToUTF16(web_contents_->GetURL().host())); + description2 = l10n_util::GetStringFUTF16( + IDS_SAFE_BROWSING_MALWARE_V2_DESCRIPTION2_SUBRESOURCE, + UTF8ToUTF16(url_.host())); + strings->SetString(""details"", l10n_util::GetStringFUTF16( + IDS_SAFE_BROWSING_MALWARE_V2_DETAILS_SUBRESOURCE, + UTF8ToUTF16(url_.host()))); + } + + PopulateStringDictionary( + strings, + l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_MALWARE_V2_TITLE), + headline, + description1, + description2, + description3); + + if (!CanShowMalwareDetailsOption()) { + strings->SetBoolean(kDisplayCheckBox, false); + strings->SetString(""confirm_text"", """"); + strings->SetString(kBoxChecked, """"); + } else { + strings->SetBoolean(kDisplayCheckBox, true); + + std::string privacy_link = base::StringPrintf( + kPrivacyLinkHtml, + l10n_util::GetStringUTF8( + IDS_SAFE_BROWSING_PRIVACY_POLICY_PAGE_V2).c_str()); + + strings->SetString(""confirm_text"", + l10n_util::GetStringFUTF16( + IDS_SAFE_BROWSING_MALWARE_V2_REPORTING_AGREE, + UTF8ToUTF16(privacy_link))); + if (IsPrefEnabled(prefs::kSafeBrowsingReportingEnabled)) + strings->SetString(kBoxChecked, ""yes""); + else + strings->SetString(kBoxChecked, """"); + } + + strings->SetString(""report_error"", string16()); + strings->SetString(""learnMore"", + l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_MALWARE_V2_LEARN_MORE)); +} +",0,"void SafeBrowsingBlockingPageV2::PopulateMalwareStringDictionary( + DictionaryValue* strings) { + std::string diagnostic_link = base::StringPrintf(kSbDiagnosticHtml, + l10n_util::GetStringUTF8( + IDS_SAFE_BROWSING_MALWARE_DIAGNOSTIC_PAGE).c_str()); + + string16 headline, description1, description2, description3; + + + description3 = l10n_util::GetStringUTF16( + IDS_SAFE_BROWSING_MALWARE_V2_DESCRIPTION3); + if (is_main_frame_load_blocked_) { + headline = l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_MALWARE_V2_HEADLINE); + description1 = l10n_util::GetStringFUTF16( + IDS_SAFE_BROWSING_MALWARE_V2_DESCRIPTION1, + l10n_util::GetStringUTF16(IDS_PRODUCT_NAME), + UTF8ToUTF16(url_.host())); + description2 = l10n_util::GetStringUTF16( + IDS_SAFE_BROWSING_MALWARE_V2_DESCRIPTION2); + strings->SetString(""details"", l10n_util::GetStringUTF16( + IDS_SAFE_BROWSING_MALWARE_V2_DETAILS)); + } else { + headline = l10n_util::GetStringUTF16( + IDS_SAFE_BROWSING_MALWARE_V2_HEADLINE_SUBRESOURCE); + description1 = l10n_util::GetStringFUTF16( + IDS_SAFE_BROWSING_MALWARE_V2_DESCRIPTION1_SUBRESOURCE, + l10n_util::GetStringUTF16(IDS_PRODUCT_NAME), + UTF8ToUTF16(web_contents_->GetURL().host())); + description2 = l10n_util::GetStringFUTF16( + IDS_SAFE_BROWSING_MALWARE_V2_DESCRIPTION2_SUBRESOURCE, + UTF8ToUTF16(url_.host())); + strings->SetString(""details"", l10n_util::GetStringFUTF16( + IDS_SAFE_BROWSING_MALWARE_V2_DETAILS_SUBRESOURCE, + UTF8ToUTF16(url_.host()))); + } + + PopulateStringDictionary( + strings, + l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_MALWARE_V2_TITLE), + headline, + description1, + description2, + description3); + + if (!CanShowMalwareDetailsOption()) { + strings->SetBoolean(kDisplayCheckBox, false); + strings->SetString(""confirm_text"", """"); + strings->SetString(kBoxChecked, """"); + } else { + strings->SetBoolean(kDisplayCheckBox, true); + + std::string privacy_link = base::StringPrintf( + kPrivacyLinkHtml, + l10n_util::GetStringUTF8( + IDS_SAFE_BROWSING_PRIVACY_POLICY_PAGE_V2).c_str()); + + strings->SetString(""confirm_text"", + l10n_util::GetStringFUTF16( + IDS_SAFE_BROWSING_MALWARE_V2_REPORTING_AGREE, + UTF8ToUTF16(privacy_link))); + if (IsPrefEnabled(prefs::kSafeBrowsingReportingEnabled)) + strings->SetString(kBoxChecked, ""yes""); + else + strings->SetString(kBoxChecked, """"); + } + + strings->SetString(""report_error"", string16()); + strings->SetString(""learnMore"", + l10n_util::GetStringUTF16(IDS_SAFE_BROWSING_MALWARE_V2_LEARN_MORE)); +} +","@@ -321,19 +321,21 @@ void SafeBrowsingBlockingPage::CommandReceived(const std::string& cmd) { + + // The ""report error"" and ""show diagnostic"" commands can have a number + // appended to them, which is the index of the element they apply to. +- int element_index = 0; ++ size_t element_index = 0; + size_t colon_index = command.find(':'); + if (colon_index != std::string::npos) { + DCHECK(colon_index < command.size() - 1); ++ int result_int = 0; + bool result = base::StringToInt(base::StringPiece(command.begin() + + colon_index + 1, + command.end()), +- &element_index); ++ &result_int); + command = command.substr(0, colon_index); +- DCHECK(result); ++ if (result) ++ element_index = static_cast(result_int); + } + +- if (element_index >= static_cast(unsafe_resources_.size())) { ++ if (element_index >= unsafe_resources_.size()) { + NOTREACHED(); + return; + }",747,1078,2048 +18224,"M_fs_error_t M_fs_delete(const char *path, M_bool remove_children, M_fs_progress_cb_t cb, M_uint32 progress_flags) +{ + char *norm_path; + char *join_path; + M_fs_dir_entries_t *entries; + const M_fs_dir_entry_t *entry; + M_fs_info_t *info; + M_fs_progress_t *progress = NULL; + M_fs_dir_walk_filter_t filter = M_FS_DIR_WALK_FILTER_ALL|M_FS_DIR_WALK_FILTER_RECURSE; + M_fs_type_t type; + /* The result that will be returned by this function. */ + M_fs_error_t res; + /* The result of the delete itself. */ + M_fs_error_t res2; + size_t len; + size_t i; + M_uint64 total_size = 0; + M_uint64 total_size_progress = 0; + M_uint64 entry_size; + + /* Normalize the path we are going to delete so we have a valid path to pass around. */ + res = M_fs_path_norm(&norm_path, path, M_FS_PATH_NORM_HOME, M_FS_SYSTEM_AUTO); + if (res != M_FS_ERROR_SUCCESS) { + M_free(norm_path); + return res; + } + + /* We need the info to determine if the path is valid and because we need the type. */ + res = M_fs_info(&info, norm_path, M_FS_PATH_INFO_FLAGS_BASIC); + if (res != M_FS_ERROR_SUCCESS) { + M_free(norm_path); + return res; + } + + /* We must know the type because there are different functions for deleting a file and deleting a directory. */ + type = M_fs_info_get_type(info); + if (type == M_FS_TYPE_UNKNOWN) { + M_fs_info_destroy(info); + M_free(norm_path); + return M_FS_ERROR_GENERIC; + } + + /* Create a list of entries to store all the places we need to delete. */ + entries = M_fs_dir_entries_create(); + + /* Recursive directory deletion isn't intuitive. We have to generate a list of files and delete the list. + * We cannot delete as walk because not all file systems support that operation. The walk; delete; behavior + * is undefined in Posix and HFS is known to skip files if the directory contents is modifies as the + * directory is being walked. */ + if (type == M_FS_TYPE_DIR && remove_children) { + /* We need to read the basic info if the we need to report the size totals to the cb. */ + if (cb && progress_flags & (M_FS_PROGRESS_SIZE_TOTAL|M_FS_PROGRESS_SIZE_CUR)) { + filter |= M_FS_DIR_WALK_FILTER_READ_INFO_BASIC; + } + M_fs_dir_entries_merge(&entries, M_fs_dir_walk_entries(norm_path, NULL, filter)); + } + + /* Add the original path to the list of entries. This may be the only entry in the list. We need to add + * it after a potential walk because we can't delete a directory that isn't empty. + * Note: + * - The info will be owned by the entry and destroyed when it is destroyed. + * - The basic info param doesn't get the info in this case. it's set so the info is stored in the entry. */ + M_fs_dir_entries_insert(entries, M_fs_dir_walk_fill_entry(norm_path, NULL, type, info, M_FS_DIR_WALK_FILTER_READ_INFO_BASIC)); + + len = M_fs_dir_entries_len(entries); + if (cb) { + /* Create the progress. The same progress will be used for the entire operation. It will be updated with + * new info as necessary. */ + progress = M_fs_progress_create(); + + /* Get the total size of all files to be deleted if using the progress cb and size totals is set. */ + if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) { + for (i=0; ilen; + register u_int caplen = h->caplen; + uint16_t ptype; + const u_char *q; + int i; + + if (caplen < PPP_BSDI_HDRLEN) { + ND_PRINT((ndo, ""[|ppp]"")); + return (caplen) + } + + hdrlength = 0; + +#if 0 + if (p[0] == PPP_ADDRESS && p[1] == PPP_CONTROL) { + if (ndo->ndo_eflag) + ND_PRINT((ndo, ""%02x %02x "", p[0], p[1])); + p += 2; + hdrlength = 2; + } + + if (ndo->ndo_eflag) + ND_PRINT((ndo, ""%d "", length)); + /* Retrieve the protocol type */ + if (*p & 01) { + /* Compressed protocol field */ + ptype = *p; + if (ndo->ndo_eflag) + ND_PRINT((ndo, ""%02x "", ptype)); + p++; + hdrlength += 1; + } else { + /* Un-compressed protocol field */ + ptype = EXTRACT_16BITS(p); + if (ndo->ndo_eflag) + ND_PRINT((ndo, ""%04x "", ptype)); + p += 2; + hdrlength += 2; + } +#else + ptype = 0; /*XXX*/ + if (ndo->ndo_eflag) + ND_PRINT((ndo, ""%c "", p[SLC_DIR] ? 'O' : 'I')); + if (p[SLC_LLHL]) { + /* link level header */ + struct ppp_header *ph; + + q = p + SLC_BPFHDRLEN; + ph = (struct ppp_header *)q; + if (ph->phdr_addr == PPP_ADDRESS + && ph->phdr_ctl == PPP_CONTROL) { + if (ndo->ndo_eflag) + ND_PRINT((ndo, ""%02x %02x "", q[0], q[1])); + ptype = EXTRACT_16BITS(&ph->phdr_type); + if (ndo->ndo_eflag && (ptype == PPP_VJC || ptype == PPP_VJNC)) { + ND_PRINT((ndo, ""%s "", tok2str(ppptype2str, + ""proto-#%d"", ptype))); + } + } else { + if (ndo->ndo_eflag) { + ND_PRINT((ndo, ""LLH=["")); + for (i = 0; i < p[SLC_LLHL]; i++) + ND_PRINT((ndo, ""%02x"", q[i])); + ND_PRINT((ndo, ""] "")); + } + } + } + if (ndo->ndo_eflag) + ND_PRINT((ndo, ""%d "", length)); + if (p[SLC_CHL]) { + q = p + SLC_BPFHDRLEN + p[SLC_LLHL]; + + switch (ptype) { + case PPP_VJC: + ptype = vjc_print(ndo, q, ptype); + hdrlength = PPP_BSDI_HDRLEN; + p += hdrlength; + switch (ptype) { + case PPP_IP: + ip_print(ndo, p, length); + break; + case PPP_IPV6: + ip6_print(ndo, p, length); + break; + case PPP_MPLS_UCAST: + case PPP_MPLS_MCAST: + mpls_print(ndo, p, length); + break; + } + goto printx; + case PPP_VJNC: + ptype = vjc_print(ndo, q, ptype); + hdrlength = PPP_BSDI_HDRLEN; + p += hdrlength; + switch (ptype) { + case PPP_IP: + ip_print(ndo, p, length); + break; + case PPP_IPV6: + ip6_print(ndo, p, length); + break; + case PPP_MPLS_UCAST: + case PPP_MPLS_MCAST: + mpls_print(ndo, p, length); + break; + } + goto printx; + default: + if (ndo->ndo_eflag) { + ND_PRINT((ndo, ""CH=["")); + for (i = 0; i < p[SLC_LLHL]; i++) + ND_PRINT((ndo, ""%02x"", q[i])); + ND_PRINT((ndo, ""] "")); + } + break; + } + } + + hdrlength = PPP_BSDI_HDRLEN; +#endif + + length -= hdrlength; + p += hdrlength; + + switch (ptype) { + case PPP_IP: + ip_print(p, length); + break; + case PPP_IPV6: + ip6_print(ndo, p, length); + break; + case PPP_MPLS_UCAST: + case PPP_MPLS_MCAST: + mpls_print(ndo, p, length); + break; + default: + ND_PRINT((ndo, ""%s "", tok2str(ppptype2str, ""unknown PPP protocol (0x%04x)"", ptype))); + } + +printx: +#else /* __bsdi */ + hdrlength = 0; +#endif /* __bsdi__ */ + return (hdrlength); +} +",0,"ppp_bsdos_if_print(netdissect_options *ndo _U_, + const struct pcap_pkthdr *h _U_, register const u_char *p _U_) +{ + register int hdrlength; +#ifdef __bsdi__ + register u_int length = h->len; + register u_int caplen = h->caplen; + uint16_t ptype; + const u_char *q; + int i; + + if (caplen < PPP_BSDI_HDRLEN) { + ND_PRINT((ndo, ""[|ppp]"")); + return (caplen) + } + + hdrlength = 0; + +#if 0 + if (p[0] == PPP_ADDRESS && p[1] == PPP_CONTROL) { + if (ndo->ndo_eflag) + ND_PRINT((ndo, ""%02x %02x "", p[0], p[1])); + p += 2; + hdrlength = 2; + } + + if (ndo->ndo_eflag) + ND_PRINT((ndo, ""%d "", length)); + /* Retrieve the protocol type */ + if (*p & 01) { + /* Compressed protocol field */ + ptype = *p; + if (ndo->ndo_eflag) + ND_PRINT((ndo, ""%02x "", ptype)); + p++; + hdrlength += 1; + } else { + /* Un-compressed protocol field */ + ptype = EXTRACT_16BITS(p); + if (ndo->ndo_eflag) + ND_PRINT((ndo, ""%04x "", ptype)); + p += 2; + hdrlength += 2; + } +#else + ptype = 0; /*XXX*/ + if (ndo->ndo_eflag) + ND_PRINT((ndo, ""%c "", p[SLC_DIR] ? 'O' : 'I')); + if (p[SLC_LLHL]) { + /* link level header */ + struct ppp_header *ph; + + q = p + SLC_BPFHDRLEN; + ph = (struct ppp_header *)q; + if (ph->phdr_addr == PPP_ADDRESS + && ph->phdr_ctl == PPP_CONTROL) { + if (ndo->ndo_eflag) + ND_PRINT((ndo, ""%02x %02x "", q[0], q[1])); + ptype = EXTRACT_16BITS(&ph->phdr_type); + if (ndo->ndo_eflag && (ptype == PPP_VJC || ptype == PPP_VJNC)) { + ND_PRINT((ndo, ""%s "", tok2str(ppptype2str, + ""proto-#%d"", ptype))); + } + } else { + if (ndo->ndo_eflag) { + ND_PRINT((ndo, ""LLH=["")); + for (i = 0; i < p[SLC_LLHL]; i++) + ND_PRINT((ndo, ""%02x"", q[i])); + ND_PRINT((ndo, ""] "")); + } + } + } + if (ndo->ndo_eflag) + ND_PRINT((ndo, ""%d "", length)); + if (p[SLC_CHL]) { + q = p + SLC_BPFHDRLEN + p[SLC_LLHL]; + + switch (ptype) { + case PPP_VJC: + ptype = vjc_print(ndo, q, ptype); + hdrlength = PPP_BSDI_HDRLEN; + p += hdrlength; + switch (ptype) { + case PPP_IP: + ip_print(ndo, p, length); + break; + case PPP_IPV6: + ip6_print(ndo, p, length); + break; + case PPP_MPLS_UCAST: + case PPP_MPLS_MCAST: + mpls_print(ndo, p, length); + break; + } + goto printx; + case PPP_VJNC: + ptype = vjc_print(ndo, q, ptype); + hdrlength = PPP_BSDI_HDRLEN; + p += hdrlength; + switch (ptype) { + case PPP_IP: + ip_print(ndo, p, length); + break; + case PPP_IPV6: + ip6_print(ndo, p, length); + break; + case PPP_MPLS_UCAST: + case PPP_MPLS_MCAST: + mpls_print(ndo, p, length); + break; + } + goto printx; + default: + if (ndo->ndo_eflag) { + ND_PRINT((ndo, ""CH=["")); + for (i = 0; i < p[SLC_LLHL]; i++) + ND_PRINT((ndo, ""%02x"", q[i])); + ND_PRINT((ndo, ""] "")); + } + break; + } + } + + hdrlength = PPP_BSDI_HDRLEN; +#endif + + length -= hdrlength; + p += hdrlength; + + switch (ptype) { + case PPP_IP: + ip_print(p, length); + break; + case PPP_IPV6: + ip6_print(ndo, p, length); + break; + case PPP_MPLS_UCAST: + case PPP_MPLS_MCAST: + mpls_print(ndo, p, length); + break; + default: + ND_PRINT((ndo, ""%s "", tok2str(ppptype2str, ""unknown PPP protocol (0x%04x)"", ptype))); + } + +printx: +#else /* __bsdi */ + hdrlength = 0; +#endif /* __bsdi__ */ + return (hdrlength); +} +","@@ -1351,14 +1351,15 @@ static void + ppp_hdlc(netdissect_options *ndo, + const u_char *p, int length) + { +- u_char *b, *s, *t, c; ++ u_char *b, *t, c; ++ const u_char *s; + int i, proto; + const void *se; + + if (length <= 0) + return; + +- b = (uint8_t *)malloc(length); ++ b = (u_char *)malloc(length); + if (b == NULL) + return; + +@@ -1367,14 +1368,13 @@ ppp_hdlc(netdissect_options *ndo, + * Do this so that we dont overwrite the original packet + * contents. + */ +- for (s = (u_char *)p, t = b, i = length; i > 0; i--) { ++ for (s = p, t = b, i = length; i > 0 && ND_TTEST(*s); i--) { + c = *s++; + if (c == 0x7d) { +- if (i > 1) { +- i--; +- c = *s++ ^ 0x20; +- } else +- continue; ++ if (i <= 1 || !ND_TTEST(*s)) ++ break; ++ i--; ++ c = *s++ ^ 0x20; + } + *t++ = c; + }",1203,1534,2048 +8603,"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; +} +",0,"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; +} +","@@ -3984,6 +3984,9 @@ int hugetlb_mcopy_atomic_pte(struct mm_struct *dst_mm, + 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; +@@ -4021,13 +4024,24 @@ int hugetlb_mcopy_atomic_pte(struct mm_struct *dst_mm, + __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) { +- struct address_space *mapping = dst_vma->vm_file->f_mapping; +- pgoff_t idx = vma_hugecache_offset(h, dst_vma, dst_addr); ++ 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; +@@ -4036,6 +4050,20 @@ int hugetlb_mcopy_atomic_pte(struct mm_struct *dst_mm, + 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;",1132,1463,2048 +17947,"int disrsi_( + + int stream, + int *negate, + unsigned *value, + unsigned count) + + { + int c; + unsigned locval; + unsigned ndigs; + char *cp; + char scratch[DIS_BUFSIZ+1]; + + assert(negate != NULL); + assert(value != NULL); + assert(count); + assert(stream >= 0); + assert(dis_getc != NULL); + assert(dis_gets != NULL); + + memset(scratch, 0, DIS_BUFSIZ+1); + if (dis_umaxd == 0) + disiui_(); + + switch (c = (*dis_getc)(stream)) + { + + case '-': + + case '+': + + *negate = c == '-'; + + if ((*dis_gets)(stream, scratch, count) != (int)count) + { + return(DIS_EOD); + } + + if (count >= dis_umaxd) + { + if (count > dis_umaxd) + goto overflow; + + if (memcmp(scratch, dis_umax, dis_umaxd) > 0) + goto overflow; + } + + cp = scratch; + + locval = 0; + + do + { + if (((c = *cp++) < '0') || (c > '9')) + { + return(DIS_NONDIGIT); + } + + locval = 10 * locval + c - '0'; + } + while (--count); + + *value = locval; + + return (DIS_SUCCESS); + + break; + + case '0': + + return (DIS_LEADZRO); + + break; + + case '1': + + case '2': + + case '3': + + case '4': + + case '5': + + case '6': + + case '7': + + case '8': + + case '9': + + ndigs = c - '0'; + + if (count > 1) + { + if ((*dis_gets)(stream, scratch + 1, count - 1) != (int)count - 1) + { + return(DIS_EOD); + } + + cp = scratch; + + if (count >= dis_umaxd) + { + if (count > dis_umaxd) + break; + + *cp = c; + + if (memcmp(scratch, dis_umax, dis_umaxd) > 0) + break; + } + + while (--count) + { + if (((c = *++cp) < '0') || (c > '9')) + { + return(DIS_NONDIGIT); + } + + ndigs = 10 * ndigs + c - '0'; + } + } /* END if (count > 1) */ + + return(disrsi_(stream, negate, value, ndigs)); + + /*NOTREACHED*/ + + break; + + case - 1: + + return(DIS_EOD); + + /*NOTREACHED*/ + + break; + + case -2: + + return(DIS_EOF); + + /*NOTREACHED*/ + + break; + + default: + + return(DIS_NONDIGIT); + + /*NOTREACHED*/ + + break; + } + + *negate = FALSE; + +overflow: + + *value = UINT_MAX; + + return(DIS_OVERFLOW); + } /* END disrsi_() */ +",1,"int disrsi_( + + int stream, + int *negate, + unsigned *value, + unsigned count) + + { + int c; + unsigned locval; + unsigned ndigs; + char *cp; + char scratch[DIS_BUFSIZ+1]; + + assert(negate != NULL); + assert(value != NULL); + assert(count); + assert(stream >= 0); + assert(dis_getc != NULL); + assert(dis_gets != NULL); + + memset(scratch, 0, DIS_BUFSIZ+1); + if (dis_umaxd == 0) + disiui_(); + + if (count >= dis_umaxd) + { + if (count > dis_umaxd) + goto overflow; + + if (memcmp(scratch, dis_umax, dis_umaxd) > 0) + goto overflow; + } + + switch (c = (*dis_getc)(stream)) + { + + case '-': + + case '+': + + *negate = c == '-'; + + if ((*dis_gets)(stream, scratch, count) != (int)count) + { + return(DIS_EOD); + } + + if (count >= dis_umaxd) + { + if (count > dis_umaxd) + goto overflow; + + if (memcmp(scratch, dis_umax, dis_umaxd) > 0) + goto overflow; + } + + cp = scratch; + + locval = 0; + + do + { + if (((c = *cp++) < '0') || (c > '9')) + { + return(DIS_NONDIGIT); + } + + locval = 10 * locval + c - '0'; + } + while (--count); + + *value = locval; + + return (DIS_SUCCESS); + + break; + + case '0': + + return (DIS_LEADZRO); + + break; + + case '1': + + case '2': + + case '3': + + case '4': + + case '5': + + case '6': + + case '7': + + case '8': + + case '9': + + ndigs = c - '0'; + + if (count > 1) + { + if ((*dis_gets)(stream, scratch + 1, count - 1) != (int)count - 1) + { + return(DIS_EOD); + } + + cp = scratch; + + if (count >= dis_umaxd) + { + if (count > dis_umaxd) + break; + + *cp = c; + + if (memcmp(scratch, dis_umax, dis_umaxd) > 0) + break; + } + + while (--count) + { + if (((c = *++cp) < '0') || (c > '9')) + { + return(DIS_NONDIGIT); + } + + ndigs = 10 * ndigs + c - '0'; + } + } /* END if (count > 1) */ + + return(disrsi_(stream, negate, value, ndigs)); + + /*NOTREACHED*/ + + break; + + case - 1: + + return(DIS_EOD); + + /*NOTREACHED*/ + + break; + + case -2: + + return(DIS_EOF); + + /*NOTREACHED*/ + + break; + + default: + + return(DIS_NONDIGIT); + + /*NOTREACHED*/ + + break; + } + + *negate = FALSE; + +overflow: + + *value = UINT_MAX; + + return(DIS_OVERFLOW); + } /* END disrsi_() */ +","@@ -112,6 +112,15 @@ int disrsi_( + if (dis_umaxd == 0) + disiui_(); + ++ if (count >= dis_umaxd) ++ { ++ if (count > dis_umaxd) ++ goto overflow; ++ ++ if (memcmp(scratch, dis_umax, dis_umaxd) > 0) ++ goto overflow; ++ } ++ + switch (c = (*dis_getc)(stream)) + { + ",702,1033,2048 +8375,"static int attach_to_pi_state(u32 __user *uaddr, u32 uval, + struct futex_pi_state *pi_state, + struct futex_pi_state **ps) +{ + pid_t pid = uval & FUTEX_TID_MASK; + u32 uval2; + int ret; + + /* + * Userspace might have messed up non-PI and PI futexes [3] + */ + if (unlikely(!pi_state)) + return -EINVAL; + + /* + * We get here with hb->lock held, and having found a + * futex_top_waiter(). This means that futex_lock_pi() of said futex_q + * has dropped the hb->lock in between queue_me() and unqueue_me_pi(), + * which in turn means that futex_lock_pi() still has a reference on + * our pi_state. + * + * The waiter holding a reference on @pi_state also protects against + * the unlocked put_pi_state() in futex_unlock_pi(), futex_lock_pi() + * and futex_wait_requeue_pi() as it cannot go to 0 and consequently + * free pi_state before we can take a reference ourselves. + */ + WARN_ON(!atomic_read(&pi_state->refcount)); + + /* + * Now that we have a pi_state, we can acquire wait_lock + * and do the state validation. + */ + raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock); + + /* + * Since {uval, pi_state} is serialized by wait_lock, and our current + * uval was read without holding it, it can have changed. Verify it + * still is what we expect it to be, otherwise retry the entire + * operation. + */ + if (get_futex_value_locked(&uval2, uaddr)) + goto out_efault; + + if (uval != uval2) + goto out_eagain; + + /* + * Handle the owner died case: + */ + if (uval & FUTEX_OWNER_DIED) { + /* + * exit_pi_state_list sets owner to NULL and wakes the + * topmost waiter. The task which acquires the + * pi_state->rt_mutex will fixup owner. + */ + if (!pi_state->owner) { + /* + * No pi state owner, but the user space TID + * is not 0. Inconsistent state. [5] + */ + if (pid) + goto out_einval; + /* + * Take a ref on the state and return success. [4] + */ + goto out_attach; + } + + /* + * If TID is 0, then either the dying owner has not + * yet executed exit_pi_state_list() or some waiter + * acquired the rtmutex in the pi state, but did not + * yet fixup the TID in user space. + * + * Take a ref on the state and return success. [6] + */ + if (!pid) + goto out_attach; + } else { + /* + * If the owner died bit is not set, then the pi_state + * must have an owner. [7] + */ + if (!pi_state->owner) + goto out_einval; + } + + /* + * Bail out if user space manipulated the futex value. If pi + * state exists then the owner TID must be the same as the + * user space TID. [9/10] + */ + if (pid != task_pid_vnr(pi_state->owner)) + goto out_einval; + +out_attach: + get_pi_state(pi_state); + raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock); + *ps = pi_state; + return 0; + +out_einval: + ret = -EINVAL; + goto out_error; + +out_eagain: + ret = -EAGAIN; + goto out_error; + +out_efault: + ret = -EFAULT; + goto out_error; + +out_error: + raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock); + return ret; +} +",0,"static int attach_to_pi_state(u32 __user *uaddr, u32 uval, + struct futex_pi_state *pi_state, + struct futex_pi_state **ps) +{ + pid_t pid = uval & FUTEX_TID_MASK; + u32 uval2; + int ret; + + /* + * Userspace might have messed up non-PI and PI futexes [3] + */ + if (unlikely(!pi_state)) + return -EINVAL; + + /* + * We get here with hb->lock held, and having found a + * futex_top_waiter(). This means that futex_lock_pi() of said futex_q + * has dropped the hb->lock in between queue_me() and unqueue_me_pi(), + * which in turn means that futex_lock_pi() still has a reference on + * our pi_state. + * + * The waiter holding a reference on @pi_state also protects against + * the unlocked put_pi_state() in futex_unlock_pi(), futex_lock_pi() + * and futex_wait_requeue_pi() as it cannot go to 0 and consequently + * free pi_state before we can take a reference ourselves. + */ + WARN_ON(!atomic_read(&pi_state->refcount)); + + /* + * Now that we have a pi_state, we can acquire wait_lock + * and do the state validation. + */ + raw_spin_lock_irq(&pi_state->pi_mutex.wait_lock); + + /* + * Since {uval, pi_state} is serialized by wait_lock, and our current + * uval was read without holding it, it can have changed. Verify it + * still is what we expect it to be, otherwise retry the entire + * operation. + */ + if (get_futex_value_locked(&uval2, uaddr)) + goto out_efault; + + if (uval != uval2) + goto out_eagain; + + /* + * Handle the owner died case: + */ + if (uval & FUTEX_OWNER_DIED) { + /* + * exit_pi_state_list sets owner to NULL and wakes the + * topmost waiter. The task which acquires the + * pi_state->rt_mutex will fixup owner. + */ + if (!pi_state->owner) { + /* + * No pi state owner, but the user space TID + * is not 0. Inconsistent state. [5] + */ + if (pid) + goto out_einval; + /* + * Take a ref on the state and return success. [4] + */ + goto out_attach; + } + + /* + * If TID is 0, then either the dying owner has not + * yet executed exit_pi_state_list() or some waiter + * acquired the rtmutex in the pi state, but did not + * yet fixup the TID in user space. + * + * Take a ref on the state and return success. [6] + */ + if (!pid) + goto out_attach; + } else { + /* + * If the owner died bit is not set, then the pi_state + * must have an owner. [7] + */ + if (!pi_state->owner) + goto out_einval; + } + + /* + * Bail out if user space manipulated the futex value. If pi + * state exists then the owner TID must be the same as the + * user space TID. [9/10] + */ + if (pid != task_pid_vnr(pi_state->owner)) + goto out_einval; + +out_attach: + get_pi_state(pi_state); + raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock); + *ps = pi_state; + return 0; + +out_einval: + ret = -EINVAL; + goto out_error; + +out_eagain: + ret = -EAGAIN; + goto out_error; + +out_efault: + ret = -EFAULT; + goto out_error; + +out_error: + raw_spin_unlock_irq(&pi_state->pi_mutex.wait_lock); + return ret; +} +","@@ -1878,6 +1878,9 @@ static int futex_requeue(u32 __user *uaddr1, unsigned int flags, + struct futex_q *this, *next; + DEFINE_WAKE_Q(wake_q); + ++ if (nr_wake < 0 || nr_requeue < 0) ++ return -EINVAL; ++ + /* + * When PI not supported: return -ENOSYS if requeue_pi is true, + * consequently the compiler knows requeue_pi is always false past",862,1193,2048 +14554,"static BrotliResult DecodeContextMap(uint32_t context_map_size, + uint32_t* num_htrees, + uint8_t** context_map_arg, + BrotliState* s) { + BrotliBitReader* br = &s->br; + BrotliResult result = BROTLI_RESULT_SUCCESS; + + switch((int)s->substate_context_map) { + case BROTLI_STATE_CONTEXT_MAP_NONE: + result = DecodeVarLenUint8(s, br, num_htrees); + if (result != BROTLI_RESULT_SUCCESS) { + return result; + } + (*num_htrees)++; + s->context_index = 0; + BROTLI_LOG_UINT(context_map_size); + BROTLI_LOG_UINT(*num_htrees); + *context_map_arg = (uint8_t*)BROTLI_ALLOC(s, (size_t)context_map_size); + if (*context_map_arg == 0) { + return BROTLI_FAILURE(); + } + if (*num_htrees <= 1) { + memset(*context_map_arg, 0, (size_t)context_map_size); + return BROTLI_RESULT_SUCCESS; + } + s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_READ_PREFIX; + /* No break, continue to next state. */ + case BROTLI_STATE_CONTEXT_MAP_READ_PREFIX: { + uint32_t bits; + /* In next stage ReadHuffmanCode uses at least 4 bits, so it is safe + to peek 4 bits ahead. */ + if (!BrotliSafeGetBits(br, 5, &bits)) { + return BROTLI_RESULT_NEEDS_MORE_INPUT; + } + if ((bits & 1) != 0) { /* Use RLE for zeroes. */ + s->max_run_length_prefix = (bits >> 1) + 1; + BrotliDropBits(br, 5); + } else { + s->max_run_length_prefix = 0; + BrotliDropBits(br, 1); + } + BROTLI_LOG_UINT(s->max_run_length_prefix); + s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_HUFFMAN; + /* No break, continue to next state. */ + } + case BROTLI_STATE_CONTEXT_MAP_HUFFMAN: + result = ReadHuffmanCode(*num_htrees + s->max_run_length_prefix, + s->context_map_table, NULL, s); + if (result != BROTLI_RESULT_SUCCESS) return result; + s->code = 0xFFFF; + s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_DECODE; + /* No break, continue to next state. */ + case BROTLI_STATE_CONTEXT_MAP_DECODE: { + uint32_t context_index = s->context_index; + uint32_t max_run_length_prefix = s->max_run_length_prefix; + uint8_t* context_map = *context_map_arg; + uint32_t code = s->code; + if (code != 0xFFFF) { + goto rleCode; + } + while (context_index < context_map_size) { + if (!SafeReadSymbol(s->context_map_table, br, &code)) { + s->code = 0xFFFF; + s->context_index = context_index; + return BROTLI_RESULT_NEEDS_MORE_INPUT; + } + BROTLI_LOG_UINT(code); + + if (code == 0) { + context_map[context_index++] = 0; + continue; + } + if (code > max_run_length_prefix) { + context_map[context_index++] = + (uint8_t)(code - max_run_length_prefix); + continue; + } +rleCode: + { + uint32_t reps; + if (!BrotliSafeReadBits(br, code, &reps)) { + s->code = code; + s->context_index = context_index; + return BROTLI_RESULT_NEEDS_MORE_INPUT; + } + reps += 1U << code; + BROTLI_LOG_UINT(reps); + if (context_index + reps > context_map_size) { + return BROTLI_FAILURE(); + } + do { + context_map[context_index++] = 0; + } while (--reps); + } + } + /* No break, continue to next state. */ + } + case BROTLI_STATE_CONTEXT_MAP_TRANSFORM: { + uint32_t bits; + if (!BrotliSafeReadBits(br, 1, &bits)) { + s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_TRANSFORM; + return BROTLI_RESULT_NEEDS_MORE_INPUT; + } + if (bits != 0) { + InverseMoveToFrontTransform(*context_map_arg, context_map_size, s); + } + s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_NONE; + return BROTLI_RESULT_SUCCESS; + } + } + + return BROTLI_FAILURE(); +} +",0,"static BrotliResult DecodeContextMap(uint32_t context_map_size, + uint32_t* num_htrees, + uint8_t** context_map_arg, + BrotliState* s) { + BrotliBitReader* br = &s->br; + BrotliResult result = BROTLI_RESULT_SUCCESS; + + switch((int)s->substate_context_map) { + case BROTLI_STATE_CONTEXT_MAP_NONE: + result = DecodeVarLenUint8(s, br, num_htrees); + if (result != BROTLI_RESULT_SUCCESS) { + return result; + } + (*num_htrees)++; + s->context_index = 0; + BROTLI_LOG_UINT(context_map_size); + BROTLI_LOG_UINT(*num_htrees); + *context_map_arg = (uint8_t*)BROTLI_ALLOC(s, (size_t)context_map_size); + if (*context_map_arg == 0) { + return BROTLI_FAILURE(); + } + if (*num_htrees <= 1) { + memset(*context_map_arg, 0, (size_t)context_map_size); + return BROTLI_RESULT_SUCCESS; + } + s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_READ_PREFIX; + /* No break, continue to next state. */ + case BROTLI_STATE_CONTEXT_MAP_READ_PREFIX: { + uint32_t bits; + /* In next stage ReadHuffmanCode uses at least 4 bits, so it is safe + to peek 4 bits ahead. */ + if (!BrotliSafeGetBits(br, 5, &bits)) { + return BROTLI_RESULT_NEEDS_MORE_INPUT; + } + if ((bits & 1) != 0) { /* Use RLE for zeroes. */ + s->max_run_length_prefix = (bits >> 1) + 1; + BrotliDropBits(br, 5); + } else { + s->max_run_length_prefix = 0; + BrotliDropBits(br, 1); + } + BROTLI_LOG_UINT(s->max_run_length_prefix); + s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_HUFFMAN; + /* No break, continue to next state. */ + } + case BROTLI_STATE_CONTEXT_MAP_HUFFMAN: + result = ReadHuffmanCode(*num_htrees + s->max_run_length_prefix, + s->context_map_table, NULL, s); + if (result != BROTLI_RESULT_SUCCESS) return result; + s->code = 0xFFFF; + s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_DECODE; + /* No break, continue to next state. */ + case BROTLI_STATE_CONTEXT_MAP_DECODE: { + uint32_t context_index = s->context_index; + uint32_t max_run_length_prefix = s->max_run_length_prefix; + uint8_t* context_map = *context_map_arg; + uint32_t code = s->code; + if (code != 0xFFFF) { + goto rleCode; + } + while (context_index < context_map_size) { + if (!SafeReadSymbol(s->context_map_table, br, &code)) { + s->code = 0xFFFF; + s->context_index = context_index; + return BROTLI_RESULT_NEEDS_MORE_INPUT; + } + BROTLI_LOG_UINT(code); + + if (code == 0) { + context_map[context_index++] = 0; + continue; + } + if (code > max_run_length_prefix) { + context_map[context_index++] = + (uint8_t)(code - max_run_length_prefix); + continue; + } +rleCode: + { + uint32_t reps; + if (!BrotliSafeReadBits(br, code, &reps)) { + s->code = code; + s->context_index = context_index; + return BROTLI_RESULT_NEEDS_MORE_INPUT; + } + reps += 1U << code; + BROTLI_LOG_UINT(reps); + if (context_index + reps > context_map_size) { + return BROTLI_FAILURE(); + } + do { + context_map[context_index++] = 0; + } while (--reps); + } + } + /* No break, continue to next state. */ + } + case BROTLI_STATE_CONTEXT_MAP_TRANSFORM: { + uint32_t bits; + if (!BrotliSafeReadBits(br, 1, &bits)) { + s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_TRANSFORM; + return BROTLI_RESULT_NEEDS_MORE_INPUT; + } + if (bits != 0) { + InverseMoveToFrontTransform(*context_map_arg, context_map_size, s); + } + s->substate_context_map = BROTLI_STATE_CONTEXT_MAP_NONE; + return BROTLI_RESULT_SUCCESS; + } + } + + return BROTLI_FAILURE(); +} +","@@ -1700,6 +1700,10 @@ static BROTLI_INLINE BrotliResult ProcessCommandsInternal(int safe, + uint8_t* copy_src = &s->ringbuffer[ + (pos - s->distance_code) & s->ringbuffer_mask]; + uint8_t* copy_dst = &s->ringbuffer[pos]; ++ /* Check for possible underflow and clamp the pointer to 0. */ ++ if (PREDICT_FALSE(s->ringbuffer_end < (const uint8_t*)0 + i)) { ++ ringbuffer_end_minus_copy_length = 0; ++ } + /* update the recent distances cache */ + s->dist_rb[s->dist_rb_idx & 3] = s->distance_code; + ++s->dist_rb_idx;",1053,1384,2048 +11679,"png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +{ + png_int_32 X0, X1; + png_byte type, nparams; + png_charp buf, units, endptr; + png_charpp params; + png_size_t slength; + int i; + + png_debug(1, ""in png_handle_pCAL""); + + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, ""Missing IHDR before pCAL""); + else if (png_ptr->mode & PNG_HAVE_IDAT) + { + png_warning(png_ptr, ""Invalid pCAL after IDAT""); + png_crc_finish(png_ptr, length); + return; + } + else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)) + { + png_warning(png_ptr, ""Duplicate pCAL chunk""); + png_crc_finish(png_ptr, length); + return; + } + + png_debug1(2, ""Allocating and reading pCAL chunk data (%lu bytes)"", + length + 1); + png_free(png_ptr, png_ptr->chunkdata); + png_ptr->chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1); + if (png_ptr->chunkdata == NULL) + { + png_warning(png_ptr, ""No memory for pCAL purpose.""); + return; + } + slength = (png_size_t)length; + png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength); + + if (png_crc_finish(png_ptr, 0)) + { + png_free(png_ptr, png_ptr->chunkdata); + png_ptr->chunkdata = NULL; + return; + } + + png_ptr->chunkdata[slength] = 0x00; /* Null terminate the last string */ + + png_debug(3, ""Finding end of pCAL purpose string""); + for (buf = png_ptr->chunkdata; *buf; buf++) + /* Empty loop */ ; + + endptr = png_ptr->chunkdata + slength; + + /* We need to have at least 12 bytes after the purpose string + in order to get the parameter information. */ + if (endptr <= buf + 12) + { + png_warning(png_ptr, ""Invalid pCAL data""); + png_free(png_ptr, png_ptr->chunkdata); + png_ptr->chunkdata = NULL; + return; + } + + png_debug(3, ""Reading pCAL X0, X1, type, nparams, and units""); + X0 = png_get_int_32((png_bytep)buf+1); + X1 = png_get_int_32((png_bytep)buf+5); + type = buf[9]; + nparams = buf[10]; + units = buf + 11; + + png_debug(3, ""Checking pCAL equation type and number of parameters""); + /* Check that we have the right number of parameters for known + equation types. */ + if ((type == PNG_EQUATION_LINEAR && nparams != 2) || + (type == PNG_EQUATION_BASE_E && nparams != 3) || + (type == PNG_EQUATION_ARBITRARY && nparams != 3) || + (type == PNG_EQUATION_HYPERBOLIC && nparams != 4)) + { + png_warning(png_ptr, ""Invalid pCAL parameters for equation type""); + png_free(png_ptr, png_ptr->chunkdata); + png_ptr->chunkdata = NULL; + return; + } + else if (type >= PNG_EQUATION_LAST) + { + png_warning(png_ptr, ""Unrecognized equation type for pCAL chunk""); + } + + for (buf = units; *buf; buf++) + /* Empty loop to move past the units string. */ ; + + png_debug(3, ""Allocating pCAL parameters array""); + params = (png_charpp)png_malloc_warn(png_ptr, + (png_uint_32)(nparams * png_sizeof(png_charp))) ; + if (params == NULL) + { + png_free(png_ptr, png_ptr->chunkdata); + png_ptr->chunkdata = NULL; + png_warning(png_ptr, ""No memory for pCAL params.""); + return; + } + + /* Get pointers to the start of each parameter string. */ + for (i = 0; i < (int)nparams; i++) + { + buf++; /* Skip the null string terminator from previous parameter. */ + + png_debug1(3, ""Reading pCAL parameter %d"", i); + for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++) + /* Empty loop to move past each parameter string */ ; + + /* Make sure we haven't run out of data yet */ + if (buf > endptr) + { + png_warning(png_ptr, ""Invalid pCAL data""); + png_free(png_ptr, png_ptr->chunkdata); + png_ptr->chunkdata = NULL; + png_free(png_ptr, params); + return; + } + } + + png_set_pCAL(png_ptr, info_ptr, png_ptr->chunkdata, X0, X1, type, nparams, + units, params); + + png_free(png_ptr, png_ptr->chunkdata); + png_ptr->chunkdata = NULL; + png_free(png_ptr, params); +} +",0,"png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length) +{ + png_int_32 X0, X1; + png_byte type, nparams; + png_charp buf, units, endptr; + png_charpp params; + png_size_t slength; + int i; + + png_debug(1, ""in png_handle_pCAL""); + + if (!(png_ptr->mode & PNG_HAVE_IHDR)) + png_error(png_ptr, ""Missing IHDR before pCAL""); + else if (png_ptr->mode & PNG_HAVE_IDAT) + { + png_warning(png_ptr, ""Invalid pCAL after IDAT""); + png_crc_finish(png_ptr, length); + return; + } + else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)) + { + png_warning(png_ptr, ""Duplicate pCAL chunk""); + png_crc_finish(png_ptr, length); + return; + } + + png_debug1(2, ""Allocating and reading pCAL chunk data (%lu bytes)"", + length + 1); + png_free(png_ptr, png_ptr->chunkdata); + png_ptr->chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1); + if (png_ptr->chunkdata == NULL) + { + png_warning(png_ptr, ""No memory for pCAL purpose.""); + return; + } + slength = (png_size_t)length; + png_crc_read(png_ptr, (png_bytep)png_ptr->chunkdata, slength); + + if (png_crc_finish(png_ptr, 0)) + { + png_free(png_ptr, png_ptr->chunkdata); + png_ptr->chunkdata = NULL; + return; + } + + png_ptr->chunkdata[slength] = 0x00; /* Null terminate the last string */ + + png_debug(3, ""Finding end of pCAL purpose string""); + for (buf = png_ptr->chunkdata; *buf; buf++) + /* Empty loop */ ; + + endptr = png_ptr->chunkdata + slength; + + /* We need to have at least 12 bytes after the purpose string + in order to get the parameter information. */ + if (endptr <= buf + 12) + { + png_warning(png_ptr, ""Invalid pCAL data""); + png_free(png_ptr, png_ptr->chunkdata); + png_ptr->chunkdata = NULL; + return; + } + + png_debug(3, ""Reading pCAL X0, X1, type, nparams, and units""); + X0 = png_get_int_32((png_bytep)buf+1); + X1 = png_get_int_32((png_bytep)buf+5); + type = buf[9]; + nparams = buf[10]; + units = buf + 11; + + png_debug(3, ""Checking pCAL equation type and number of parameters""); + /* Check that we have the right number of parameters for known + equation types. */ + if ((type == PNG_EQUATION_LINEAR && nparams != 2) || + (type == PNG_EQUATION_BASE_E && nparams != 3) || + (type == PNG_EQUATION_ARBITRARY && nparams != 3) || + (type == PNG_EQUATION_HYPERBOLIC && nparams != 4)) + { + png_warning(png_ptr, ""Invalid pCAL parameters for equation type""); + png_free(png_ptr, png_ptr->chunkdata); + png_ptr->chunkdata = NULL; + return; + } + else if (type >= PNG_EQUATION_LAST) + { + png_warning(png_ptr, ""Unrecognized equation type for pCAL chunk""); + } + + for (buf = units; *buf; buf++) + /* Empty loop to move past the units string. */ ; + + png_debug(3, ""Allocating pCAL parameters array""); + params = (png_charpp)png_malloc_warn(png_ptr, + (png_uint_32)(nparams * png_sizeof(png_charp))) ; + if (params == NULL) + { + png_free(png_ptr, png_ptr->chunkdata); + png_ptr->chunkdata = NULL; + png_warning(png_ptr, ""No memory for pCAL params.""); + return; + } + + /* Get pointers to the start of each parameter string. */ + for (i = 0; i < (int)nparams; i++) + { + buf++; /* Skip the null string terminator from previous parameter. */ + + png_debug1(3, ""Reading pCAL parameter %d"", i); + for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++) + /* Empty loop to move past each parameter string */ ; + + /* Make sure we haven't run out of data yet */ + if (buf > endptr) + { + png_warning(png_ptr, ""Invalid pCAL data""); + png_free(png_ptr, png_ptr->chunkdata); + png_ptr->chunkdata = NULL; + png_free(png_ptr, params); + return; + } + } + + png_set_pCAL(png_ptr, info_ptr, png_ptr->chunkdata, X0, X1, type, nparams, + units, params); + + png_free(png_ptr, png_ptr->chunkdata); + png_ptr->chunkdata = NULL; + png_free(png_ptr, params); +} +","@@ -247,8 +247,8 @@ png_inflate(png_structp png_ptr, const png_byte *data, png_size_t size, + { + if (output != 0 && output_size > count) + { +- int copy = output_size - count; +- if (avail < copy) copy = avail; ++ png_size_t copy = output_size - count; ++ if ((png_size_t) avail < copy) copy = (png_size_t) avail; + png_memcpy(output + count, png_ptr->zbuf, copy); + } + count += avail;",1152,1483,2048 +2519,"static void ieee80211_assign_perm_addr(struct ieee80211_local *local, + struct net_device *dev, + enum nl80211_iftype type) +{ + struct ieee80211_sub_if_data *sdata; + u64 mask, start, addr, val, inc; + u8 *m; + u8 tmp_addr[ETH_ALEN]; + int i; + + /* default ... something at least */ + memcpy(dev->perm_addr, local->hw.wiphy->perm_addr, ETH_ALEN); + + if (is_zero_ether_addr(local->hw.wiphy->addr_mask) && + local->hw.wiphy->n_addresses <= 1) + return; + + + mutex_lock(&local->iflist_mtx); + + switch (type) { + case NL80211_IFTYPE_MONITOR: + /* doesn't matter */ + break; + case NL80211_IFTYPE_WDS: + case NL80211_IFTYPE_AP_VLAN: + /* match up with an AP interface */ + list_for_each_entry(sdata, &local->interfaces, list) { + if (sdata->vif.type != NL80211_IFTYPE_AP) + continue; + memcpy(dev->perm_addr, sdata->vif.addr, ETH_ALEN); + break; + } + /* keep default if no AP interface present */ + break; + default: + /* assign a new address if possible -- try n_addresses first */ + for (i = 0; i < local->hw.wiphy->n_addresses; i++) { + bool used = false; + + list_for_each_entry(sdata, &local->interfaces, list) { + if (memcmp(local->hw.wiphy->addresses[i].addr, + sdata->vif.addr, ETH_ALEN) == 0) { + used = true; + break; + } + } + + if (!used) { + memcpy(dev->perm_addr, + local->hw.wiphy->addresses[i].addr, + ETH_ALEN); + break; + } + } + + /* try mask if available */ + if (is_zero_ether_addr(local->hw.wiphy->addr_mask)) + break; + + m = local->hw.wiphy->addr_mask; + mask = ((u64)m[0] << 5*8) | ((u64)m[1] << 4*8) | + ((u64)m[2] << 3*8) | ((u64)m[3] << 2*8) | + ((u64)m[4] << 1*8) | ((u64)m[5] << 0*8); + + if (__ffs64(mask) + hweight64(mask) != fls64(mask)) { + /* not a contiguous mask ... not handled now! */ + printk(KERN_DEBUG ""not contiguous\n""); + break; + } + + m = local->hw.wiphy->perm_addr; + start = ((u64)m[0] << 5*8) | ((u64)m[1] << 4*8) | + ((u64)m[2] << 3*8) | ((u64)m[3] << 2*8) | + ((u64)m[4] << 1*8) | ((u64)m[5] << 0*8); + + inc = 1ULL<<__ffs64(mask); + val = (start & mask); + addr = (start & ~mask) | (val & mask); + do { + bool used = false; + + tmp_addr[5] = addr >> 0*8; + tmp_addr[4] = addr >> 1*8; + tmp_addr[3] = addr >> 2*8; + tmp_addr[2] = addr >> 3*8; + tmp_addr[1] = addr >> 4*8; + tmp_addr[0] = addr >> 5*8; + + val += inc; + + list_for_each_entry(sdata, &local->interfaces, list) { + if (memcmp(tmp_addr, sdata->vif.addr, + ETH_ALEN) == 0) { + used = true; + break; + } + } + + if (!used) { + memcpy(dev->perm_addr, tmp_addr, ETH_ALEN); + break; + } + addr = (start & ~mask) | (val & mask); + } while (addr != start); + + break; + } + + mutex_unlock(&local->iflist_mtx); +} +",0,"static void ieee80211_assign_perm_addr(struct ieee80211_local *local, + struct net_device *dev, + enum nl80211_iftype type) +{ + struct ieee80211_sub_if_data *sdata; + u64 mask, start, addr, val, inc; + u8 *m; + u8 tmp_addr[ETH_ALEN]; + int i; + + /* default ... something at least */ + memcpy(dev->perm_addr, local->hw.wiphy->perm_addr, ETH_ALEN); + + if (is_zero_ether_addr(local->hw.wiphy->addr_mask) && + local->hw.wiphy->n_addresses <= 1) + return; + + + mutex_lock(&local->iflist_mtx); + + switch (type) { + case NL80211_IFTYPE_MONITOR: + /* doesn't matter */ + break; + case NL80211_IFTYPE_WDS: + case NL80211_IFTYPE_AP_VLAN: + /* match up with an AP interface */ + list_for_each_entry(sdata, &local->interfaces, list) { + if (sdata->vif.type != NL80211_IFTYPE_AP) + continue; + memcpy(dev->perm_addr, sdata->vif.addr, ETH_ALEN); + break; + } + /* keep default if no AP interface present */ + break; + default: + /* assign a new address if possible -- try n_addresses first */ + for (i = 0; i < local->hw.wiphy->n_addresses; i++) { + bool used = false; + + list_for_each_entry(sdata, &local->interfaces, list) { + if (memcmp(local->hw.wiphy->addresses[i].addr, + sdata->vif.addr, ETH_ALEN) == 0) { + used = true; + break; + } + } + + if (!used) { + memcpy(dev->perm_addr, + local->hw.wiphy->addresses[i].addr, + ETH_ALEN); + break; + } + } + + /* try mask if available */ + if (is_zero_ether_addr(local->hw.wiphy->addr_mask)) + break; + + m = local->hw.wiphy->addr_mask; + mask = ((u64)m[0] << 5*8) | ((u64)m[1] << 4*8) | + ((u64)m[2] << 3*8) | ((u64)m[3] << 2*8) | + ((u64)m[4] << 1*8) | ((u64)m[5] << 0*8); + + if (__ffs64(mask) + hweight64(mask) != fls64(mask)) { + /* not a contiguous mask ... not handled now! */ + printk(KERN_DEBUG ""not contiguous\n""); + break; + } + + m = local->hw.wiphy->perm_addr; + start = ((u64)m[0] << 5*8) | ((u64)m[1] << 4*8) | + ((u64)m[2] << 3*8) | ((u64)m[3] << 2*8) | + ((u64)m[4] << 1*8) | ((u64)m[5] << 0*8); + + inc = 1ULL<<__ffs64(mask); + val = (start & mask); + addr = (start & ~mask) | (val & mask); + do { + bool used = false; + + tmp_addr[5] = addr >> 0*8; + tmp_addr[4] = addr >> 1*8; + tmp_addr[3] = addr >> 2*8; + tmp_addr[2] = addr >> 3*8; + tmp_addr[1] = addr >> 4*8; + tmp_addr[0] = addr >> 5*8; + + val += inc; + + list_for_each_entry(sdata, &local->interfaces, list) { + if (memcmp(tmp_addr, sdata->vif.addr, + ETH_ALEN) == 0) { + used = true; + break; + } + } + + if (!used) { + memcpy(dev->perm_addr, tmp_addr, ETH_ALEN); + break; + } + addr = (start & ~mask) | (val & mask); + } while (addr != start); + + break; + } + + mutex_unlock(&local->iflist_mtx); +} +","@@ -698,6 +698,7 @@ static const struct net_device_ops ieee80211_monitorif_ops = { + static void ieee80211_if_setup(struct net_device *dev) + { + ether_setup(dev); ++ dev->priv_flags &= ~IFF_TX_SKB_SHARING; + dev->netdev_ops = &ieee80211_dataif_ops; + dev->destructor = free_netdev; + }",994,1325,2048 +17925,"static long gfs2_fallocate(struct file *file, int mode, loff_t offset, + loff_t len) +{ + struct inode *inode = file->f_path.dentry->d_inode; + struct gfs2_sbd *sdp = GFS2_SB(inode); + struct gfs2_inode *ip = GFS2_I(inode); + unsigned int data_blocks = 0, ind_blocks = 0, rblocks; + loff_t bytes, max_bytes; + struct gfs2_alloc *al; + int error; + loff_t bsize_mask = ~((loff_t)sdp->sd_sb.sb_bsize - 1); + loff_t next = (offset + len - 1) >> sdp->sd_sb.sb_bsize_shift; + next = (next + 1) << sdp->sd_sb.sb_bsize_shift; + + /* We only support the FALLOC_FL_KEEP_SIZE mode */ + if (mode & ~FALLOC_FL_KEEP_SIZE) + return -EOPNOTSUPP; + + offset &= bsize_mask; + + len = next - offset; + bytes = sdp->sd_max_rg_data * sdp->sd_sb.sb_bsize / 2; + if (!bytes) + bytes = UINT_MAX; + bytes &= bsize_mask; + if (bytes == 0) + bytes = sdp->sd_sb.sb_bsize; + + gfs2_holder_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &ip->i_gh); + error = gfs2_glock_nq(&ip->i_gh); + if (unlikely(error)) + goto out_uninit; + + if (!gfs2_write_alloc_required(ip, offset, len)) + goto out_unlock; + + while (len > 0) { + if (len < bytes) + bytes = len; + al = gfs2_alloc_get(ip); + if (!al) { + error = -ENOMEM; + goto out_unlock; + } + + error = gfs2_quota_lock_check(ip); + if (error) + goto out_alloc_put; + +retry: + gfs2_write_calc_reserv(ip, bytes, &data_blocks, &ind_blocks); + + al->al_requested = data_blocks + ind_blocks; + error = gfs2_inplace_reserve(ip); + if (error) { + if (error == -ENOSPC && bytes > sdp->sd_sb.sb_bsize) { + bytes >>= 1; + bytes &= bsize_mask; + if (bytes == 0) + bytes = sdp->sd_sb.sb_bsize; + goto retry; + } + goto out_qunlock; + } + max_bytes = bytes; + calc_max_reserv(ip, len, &max_bytes, &data_blocks, &ind_blocks); + al->al_requested = data_blocks + ind_blocks; + + rblocks = RES_DINODE + ind_blocks + RES_STATFS + RES_QUOTA + + RES_RG_HDR + gfs2_rg_blocks(ip); + if (gfs2_is_jdata(ip)) + rblocks += data_blocks ? data_blocks : 1; + + error = gfs2_trans_begin(sdp, rblocks, + PAGE_CACHE_SIZE/sdp->sd_sb.sb_bsize); + if (error) + goto out_trans_fail; + + error = fallocate_chunk(inode, offset, max_bytes, mode); + gfs2_trans_end(sdp); + + if (error) + goto out_trans_fail; + + len -= max_bytes; + offset += max_bytes; + gfs2_inplace_release(ip); + gfs2_quota_unlock(ip); + gfs2_alloc_put(ip); + } + goto out_unlock; + +out_trans_fail: + gfs2_inplace_release(ip); +out_qunlock: + gfs2_quota_unlock(ip); +out_alloc_put: + gfs2_alloc_put(ip); +out_unlock: + gfs2_glock_dq(&ip->i_gh); +out_uninit: + gfs2_holder_uninit(&ip->i_gh); + return error; +} +",1,"static long gfs2_fallocate(struct file *file, int mode, loff_t offset, + loff_t len) +{ + struct inode *inode = file->f_path.dentry->d_inode; + struct gfs2_sbd *sdp = GFS2_SB(inode); + struct gfs2_inode *ip = GFS2_I(inode); + unsigned int data_blocks = 0, ind_blocks = 0, rblocks; + loff_t bytes, max_bytes; + struct gfs2_alloc *al; + int error; + loff_t bsize_mask = ~((loff_t)sdp->sd_sb.sb_bsize - 1); + loff_t next = (offset + len - 1) >> sdp->sd_sb.sb_bsize_shift; + loff_t max_chunk_size = UINT_MAX & bsize_mask; + next = (next + 1) << sdp->sd_sb.sb_bsize_shift; + + /* We only support the FALLOC_FL_KEEP_SIZE mode */ + if (mode & ~FALLOC_FL_KEEP_SIZE) + return -EOPNOTSUPP; + + offset &= bsize_mask; + + len = next - offset; + bytes = sdp->sd_max_rg_data * sdp->sd_sb.sb_bsize / 2; + if (!bytes) + bytes = UINT_MAX; + bytes &= bsize_mask; + if (bytes == 0) + bytes = sdp->sd_sb.sb_bsize; + + gfs2_holder_init(ip->i_gl, LM_ST_EXCLUSIVE, 0, &ip->i_gh); + error = gfs2_glock_nq(&ip->i_gh); + if (unlikely(error)) + goto out_uninit; + + if (!gfs2_write_alloc_required(ip, offset, len)) + goto out_unlock; + + while (len > 0) { + if (len < bytes) + bytes = len; + al = gfs2_alloc_get(ip); + if (!al) { + error = -ENOMEM; + goto out_unlock; + } + + error = gfs2_quota_lock_check(ip); + if (error) + goto out_alloc_put; + +retry: + gfs2_write_calc_reserv(ip, bytes, &data_blocks, &ind_blocks); + + al->al_requested = data_blocks + ind_blocks; + error = gfs2_inplace_reserve(ip); + if (error) { + if (error == -ENOSPC && bytes > sdp->sd_sb.sb_bsize) { + bytes >>= 1; + bytes &= bsize_mask; + if (bytes == 0) + bytes = sdp->sd_sb.sb_bsize; + goto retry; + } + goto out_qunlock; + } + max_bytes = bytes; + calc_max_reserv(ip, (len > max_chunk_size)? max_chunk_size: len, + &max_bytes, &data_blocks, &ind_blocks); + al->al_requested = data_blocks + ind_blocks; + + rblocks = RES_DINODE + ind_blocks + RES_STATFS + RES_QUOTA + + RES_RG_HDR + gfs2_rg_blocks(ip); + if (gfs2_is_jdata(ip)) + rblocks += data_blocks ? data_blocks : 1; + + error = gfs2_trans_begin(sdp, rblocks, + PAGE_CACHE_SIZE/sdp->sd_sb.sb_bsize); + if (error) + goto out_trans_fail; + + error = fallocate_chunk(inode, offset, max_bytes, mode); + gfs2_trans_end(sdp); + + if (error) + goto out_trans_fail; + + len -= max_bytes; + offset += max_bytes; + gfs2_inplace_release(ip); + gfs2_quota_unlock(ip); + gfs2_alloc_put(ip); + } + goto out_unlock; + +out_trans_fail: + gfs2_inplace_release(ip); +out_qunlock: + gfs2_quota_unlock(ip); +out_alloc_put: + gfs2_alloc_put(ip); +out_unlock: + gfs2_glock_dq(&ip->i_gh); +out_uninit: + gfs2_holder_uninit(&ip->i_gh); + return error; +} +","@@ -669,135 +669,18 @@ static ssize_t gfs2_file_aio_write(struct kiocb *iocb, const struct iovec *iov, + return generic_file_aio_write(iocb, iov, nr_segs, pos); + } + +-static int empty_write_end(struct page *page, unsigned from, +- unsigned to, int mode) +-{ +- struct inode *inode = page->mapping->host; +- struct gfs2_inode *ip = GFS2_I(inode); +- struct buffer_head *bh; +- unsigned offset, blksize = 1 << inode->i_blkbits; +- pgoff_t end_index = i_size_read(inode) >> PAGE_CACHE_SHIFT; +- +- zero_user(page, from, to-from); +- mark_page_accessed(page); +- +- if (page->index < end_index || !(mode & FALLOC_FL_KEEP_SIZE)) { +- if (!gfs2_is_writeback(ip)) +- gfs2_page_add_databufs(ip, page, from, to); +- +- block_commit_write(page, from, to); +- return 0; +- } +- +- offset = 0; +- bh = page_buffers(page); +- while (offset < to) { +- if (offset >= from) { +- set_buffer_uptodate(bh); +- mark_buffer_dirty(bh); +- clear_buffer_new(bh); +- write_dirty_buffer(bh, WRITE); +- } +- offset += blksize; +- bh = bh->b_this_page; +- } +- +- offset = 0; +- bh = page_buffers(page); +- while (offset < to) { +- if (offset >= from) { +- wait_on_buffer(bh); +- if (!buffer_uptodate(bh)) +- return -EIO; +- } +- offset += blksize; +- bh = bh->b_this_page; +- } +- return 0; +-} +- +-static int needs_empty_write(sector_t block, struct inode *inode) +-{ +- int error; +- struct buffer_head bh_map = { .b_state = 0, .b_blocknr = 0 }; +- +- bh_map.b_size = 1 << inode->i_blkbits; +- error = gfs2_block_map(inode, block, &bh_map, 0); +- if (unlikely(error)) +- return error; +- return !buffer_mapped(&bh_map); +-} +- +-static int write_empty_blocks(struct page *page, unsigned from, unsigned to, +- int mode) +-{ +- struct inode *inode = page->mapping->host; +- unsigned start, end, next, blksize; +- sector_t block = page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits); +- int ret; +- +- blksize = 1 << inode->i_blkbits; +- next = end = 0; +- while (next < from) { +- next += blksize; +- block++; +- } +- start = next; +- do { +- next += blksize; +- ret = needs_empty_write(block, inode); +- if (unlikely(ret < 0)) +- return ret; +- if (ret == 0) { +- if (end) { +- ret = __block_write_begin(page, start, end - start, +- gfs2_block_map); +- if (unlikely(ret)) +- return ret; +- ret = empty_write_end(page, start, end, mode); +- if (unlikely(ret)) +- return ret; +- end = 0; +- } +- start = next; +- } +- else +- end = next; +- block++; +- } while (next < to); +- +- if (end) { +- ret = __block_write_begin(page, start, end - start, gfs2_block_map); +- if (unlikely(ret)) +- return ret; +- ret = empty_write_end(page, start, end, mode); +- if (unlikely(ret)) +- return ret; +- } +- +- return 0; +-} +- + static int fallocate_chunk(struct inode *inode, loff_t offset, loff_t len, + int mode) + { + struct gfs2_inode *ip = GFS2_I(inode); + struct buffer_head *dibh; + int error; +- u64 start = offset >> PAGE_CACHE_SHIFT; +- unsigned int start_offset = offset & ~PAGE_CACHE_MASK; +- u64 end = (offset + len - 1) >> PAGE_CACHE_SHIFT; +- pgoff_t curr; +- struct page *page; +- unsigned int end_offset = (offset + len) & ~PAGE_CACHE_MASK; +- unsigned int from, to; +- +- if (!end_offset) +- end_offset = PAGE_CACHE_SIZE; ++ unsigned int nr_blks; ++ sector_t lblock = offset >> inode->i_blkbits; + + error = gfs2_meta_inode_buffer(ip, &dibh); + if (unlikely(error)) +- goto out; ++ return error; + + gfs2_trans_add_bh(ip->i_gl, dibh, 1); + +@@ -807,39 +690,31 @@ static int fallocate_chunk(struct inode *inode, loff_t offset, loff_t len, + goto out; + } + +- curr = start; +- offset = start << PAGE_CACHE_SHIFT; +- from = start_offset; +- to = PAGE_CACHE_SIZE; +- while (curr <= end) { +- page = grab_cache_page_write_begin(inode->i_mapping, curr, +- AOP_FLAG_NOFS); +- if (unlikely(!page)) { +- error = -ENOMEM; +- goto out; +- } ++ while (len) { ++ struct buffer_head bh_map = { .b_state = 0, .b_blocknr = 0 }; ++ bh_map.b_size = len; ++ set_buffer_zeronew(&bh_map); + +- if (curr == end) +- to = end_offset; +- error = write_empty_blocks(page, from, to, mode); +- if (!error && offset + to > inode->i_size && +- !(mode & FALLOC_FL_KEEP_SIZE)) { +- i_size_write(inode, offset + to); +- } +- unlock_page(page); +- page_cache_release(page); +- if (error) ++ error = gfs2_block_map(inode, lblock, &bh_map, 1); ++ if (unlikely(error)) + goto out; +- curr++; +- offset += PAGE_CACHE_SIZE; +- from = 0; ++ len -= bh_map.b_size; ++ nr_blks = bh_map.b_size >> inode->i_blkbits; ++ lblock += nr_blks; ++ if (!buffer_new(&bh_map)) ++ continue; ++ if (unlikely(!buffer_zeronew(&bh_map))) { ++ error = -EIO; ++ goto out; ++ } + } ++ if (offset + len > inode->i_size && !(mode & FALLOC_FL_KEEP_SIZE)) ++ i_size_write(inode, offset + len); + + mark_inode_dirty(inode); + +- brelse(dibh); +- + out: ++ brelse(dibh); + return error; + } + +@@ -879,6 +754,7 @@ static long gfs2_fallocate(struct file *file, int mode, loff_t offset, + int error; + loff_t bsize_mask = ~((loff_t)sdp->sd_sb.sb_bsize - 1); + loff_t next = (offset + len - 1) >> sdp->sd_sb.sb_bsize_shift; ++ loff_t max_chunk_size = UINT_MAX & bsize_mask; + next = (next + 1) << sdp->sd_sb.sb_bsize_shift; + + /* We only support the FALLOC_FL_KEEP_SIZE mode */ +@@ -932,7 +808,8 @@ static long gfs2_fallocate(struct file *file, int mode, loff_t offset, + goto out_qunlock; + } + max_bytes = bytes; +- calc_max_reserv(ip, len, &max_bytes, &data_blocks, &ind_blocks); ++ calc_max_reserv(ip, (len > max_chunk_size)? max_chunk_size: len, ++ &max_bytes, &data_blocks, &ind_blocks); + al->al_requested = data_blocks + ind_blocks; + + rblocks = RES_DINODE + ind_blocks + RES_STATFS + RES_QUOTA +",833,1164,2048 +3794,"sctp_disposition_t sctp_sf_do_5_1B_init(struct net *net, + const struct sctp_endpoint *ep, + const struct sctp_association *asoc, + const sctp_subtype_t type, + void *arg, + sctp_cmd_seq_t *commands) +{ + struct sctp_chunk *chunk = arg; + struct sctp_chunk *repl; + struct sctp_association *new_asoc; + struct sctp_chunk *err_chunk; + struct sctp_packet *packet; + sctp_unrecognized_param_t *unk_param; + int len; + + /* 6.10 Bundling + * An endpoint MUST NOT bundle INIT, INIT ACK or + * SHUTDOWN COMPLETE with any other chunks. + * + * IG Section 2.11.2 + * Furthermore, we require that the receiver of an INIT chunk MUST + * enforce these rules by silently discarding an arriving packet + * with an INIT chunk that is bundled with other chunks. + */ + if (!chunk->singleton) + return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); + + /* If the packet is an OOTB packet which is temporarily on the + * control endpoint, respond with an ABORT. + */ + if (ep == sctp_sk(net->sctp.ctl_sock)->ep) { + SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES); + return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); + } + + /* 3.1 A packet containing an INIT chunk MUST have a zero Verification + * Tag. + */ + if (chunk->sctp_hdr->vtag != 0) + return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); + + /* Make sure that the INIT chunk has a valid length. + * Normally, this would cause an ABORT with a Protocol Violation + * error, but since we don't have an association, we'll + * just discard the packet. + */ + if (!sctp_chunk_length_valid(chunk, sizeof(sctp_init_chunk_t))) + return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); + + /* If the INIT is coming toward a closing socket, we'll send back + * and ABORT. Essentially, this catches the race of INIT being + * backloged to the socket at the same time as the user isses close(). + * Since the socket and all its associations are going away, we + * can treat this OOTB + */ + if (sctp_sstate(ep->base.sk, CLOSING)) + return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); + + /* Verify the INIT chunk before processing it. */ + err_chunk = NULL; + if (!sctp_verify_init(net, ep, asoc, chunk->chunk_hdr->type, + (sctp_init_chunk_t *)chunk->chunk_hdr, chunk, + &err_chunk)) { + /* This chunk contains fatal error. It is to be discarded. + * Send an ABORT, with causes if there is any. + */ + if (err_chunk) { + packet = sctp_abort_pkt_new(net, ep, asoc, arg, + (__u8 *)(err_chunk->chunk_hdr) + + sizeof(sctp_chunkhdr_t), + ntohs(err_chunk->chunk_hdr->length) - + sizeof(sctp_chunkhdr_t)); + + sctp_chunk_free(err_chunk); + + if (packet) { + sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT, + SCTP_PACKET(packet)); + SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS); + return SCTP_DISPOSITION_CONSUME; + } else { + return SCTP_DISPOSITION_NOMEM; + } + } else { + return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, + commands); + } + } + + /* Grab the INIT header. */ + chunk->subh.init_hdr = (sctp_inithdr_t *)chunk->skb->data; + + /* Tag the variable length parameters. */ + chunk->param_hdr.v = skb_pull(chunk->skb, sizeof(sctp_inithdr_t)); + + new_asoc = sctp_make_temp_asoc(ep, chunk, GFP_ATOMIC); + if (!new_asoc) + goto nomem; + + if (sctp_assoc_set_bind_addr_from_ep(new_asoc, + sctp_scope(sctp_source(chunk)), + GFP_ATOMIC) < 0) + goto nomem_init; + + /* The call, sctp_process_init(), can fail on memory allocation. */ + if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk), + (sctp_init_chunk_t *)chunk->chunk_hdr, + GFP_ATOMIC)) + goto nomem_init; + + /* B) ""Z"" shall respond immediately with an INIT ACK chunk. */ + + /* If there are errors need to be reported for unknown parameters, + * make sure to reserve enough room in the INIT ACK for them. + */ + len = 0; + if (err_chunk) + len = ntohs(err_chunk->chunk_hdr->length) - + sizeof(sctp_chunkhdr_t); + + repl = sctp_make_init_ack(new_asoc, chunk, GFP_ATOMIC, len); + if (!repl) + goto nomem_init; + + /* If there are errors need to be reported for unknown parameters, + * include them in the outgoing INIT ACK as ""Unrecognized parameter"" + * parameter. + */ + if (err_chunk) { + /* Get the ""Unrecognized parameter"" parameter(s) out of the + * ERROR chunk generated by sctp_verify_init(). Since the + * error cause code for ""unknown parameter"" and the + * ""Unrecognized parameter"" type is the same, we can + * construct the parameters in INIT ACK by copying the + * ERROR causes over. + */ + unk_param = (sctp_unrecognized_param_t *) + ((__u8 *)(err_chunk->chunk_hdr) + + sizeof(sctp_chunkhdr_t)); + /* Replace the cause code with the ""Unrecognized parameter"" + * parameter type. + */ + sctp_addto_chunk(repl, len, unk_param); + sctp_chunk_free(err_chunk); + } + + sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc)); + + sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl)); + + /* + * Note: After sending out INIT ACK with the State Cookie parameter, + * ""Z"" MUST NOT allocate any resources, nor keep any states for the + * new association. Otherwise, ""Z"" will be vulnerable to resource + * attacks. + */ + sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL()); + + return SCTP_DISPOSITION_DELETE_TCB; + +nomem_init: + sctp_association_free(new_asoc); +nomem: + if (err_chunk) + sctp_chunk_free(err_chunk); + return SCTP_DISPOSITION_NOMEM; +} +",0,"sctp_disposition_t sctp_sf_do_5_1B_init(struct net *net, + const struct sctp_endpoint *ep, + const struct sctp_association *asoc, + const sctp_subtype_t type, + void *arg, + sctp_cmd_seq_t *commands) +{ + struct sctp_chunk *chunk = arg; + struct sctp_chunk *repl; + struct sctp_association *new_asoc; + struct sctp_chunk *err_chunk; + struct sctp_packet *packet; + sctp_unrecognized_param_t *unk_param; + int len; + + /* 6.10 Bundling + * An endpoint MUST NOT bundle INIT, INIT ACK or + * SHUTDOWN COMPLETE with any other chunks. + * + * IG Section 2.11.2 + * Furthermore, we require that the receiver of an INIT chunk MUST + * enforce these rules by silently discarding an arriving packet + * with an INIT chunk that is bundled with other chunks. + */ + if (!chunk->singleton) + return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); + + /* If the packet is an OOTB packet which is temporarily on the + * control endpoint, respond with an ABORT. + */ + if (ep == sctp_sk(net->sctp.ctl_sock)->ep) { + SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES); + return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); + } + + /* 3.1 A packet containing an INIT chunk MUST have a zero Verification + * Tag. + */ + if (chunk->sctp_hdr->vtag != 0) + return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); + + /* Make sure that the INIT chunk has a valid length. + * Normally, this would cause an ABORT with a Protocol Violation + * error, but since we don't have an association, we'll + * just discard the packet. + */ + if (!sctp_chunk_length_valid(chunk, sizeof(sctp_init_chunk_t))) + return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); + + /* If the INIT is coming toward a closing socket, we'll send back + * and ABORT. Essentially, this catches the race of INIT being + * backloged to the socket at the same time as the user isses close(). + * Since the socket and all its associations are going away, we + * can treat this OOTB + */ + if (sctp_sstate(ep->base.sk, CLOSING)) + return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); + + /* Verify the INIT chunk before processing it. */ + err_chunk = NULL; + if (!sctp_verify_init(net, ep, asoc, chunk->chunk_hdr->type, + (sctp_init_chunk_t *)chunk->chunk_hdr, chunk, + &err_chunk)) { + /* This chunk contains fatal error. It is to be discarded. + * Send an ABORT, with causes if there is any. + */ + if (err_chunk) { + packet = sctp_abort_pkt_new(net, ep, asoc, arg, + (__u8 *)(err_chunk->chunk_hdr) + + sizeof(sctp_chunkhdr_t), + ntohs(err_chunk->chunk_hdr->length) - + sizeof(sctp_chunkhdr_t)); + + sctp_chunk_free(err_chunk); + + if (packet) { + sctp_add_cmd_sf(commands, SCTP_CMD_SEND_PKT, + SCTP_PACKET(packet)); + SCTP_INC_STATS(net, SCTP_MIB_OUTCTRLCHUNKS); + return SCTP_DISPOSITION_CONSUME; + } else { + return SCTP_DISPOSITION_NOMEM; + } + } else { + return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, + commands); + } + } + + /* Grab the INIT header. */ + chunk->subh.init_hdr = (sctp_inithdr_t *)chunk->skb->data; + + /* Tag the variable length parameters. */ + chunk->param_hdr.v = skb_pull(chunk->skb, sizeof(sctp_inithdr_t)); + + new_asoc = sctp_make_temp_asoc(ep, chunk, GFP_ATOMIC); + if (!new_asoc) + goto nomem; + + if (sctp_assoc_set_bind_addr_from_ep(new_asoc, + sctp_scope(sctp_source(chunk)), + GFP_ATOMIC) < 0) + goto nomem_init; + + /* The call, sctp_process_init(), can fail on memory allocation. */ + if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk), + (sctp_init_chunk_t *)chunk->chunk_hdr, + GFP_ATOMIC)) + goto nomem_init; + + /* B) ""Z"" shall respond immediately with an INIT ACK chunk. */ + + /* If there are errors need to be reported for unknown parameters, + * make sure to reserve enough room in the INIT ACK for them. + */ + len = 0; + if (err_chunk) + len = ntohs(err_chunk->chunk_hdr->length) - + sizeof(sctp_chunkhdr_t); + + repl = sctp_make_init_ack(new_asoc, chunk, GFP_ATOMIC, len); + if (!repl) + goto nomem_init; + + /* If there are errors need to be reported for unknown parameters, + * include them in the outgoing INIT ACK as ""Unrecognized parameter"" + * parameter. + */ + if (err_chunk) { + /* Get the ""Unrecognized parameter"" parameter(s) out of the + * ERROR chunk generated by sctp_verify_init(). Since the + * error cause code for ""unknown parameter"" and the + * ""Unrecognized parameter"" type is the same, we can + * construct the parameters in INIT ACK by copying the + * ERROR causes over. + */ + unk_param = (sctp_unrecognized_param_t *) + ((__u8 *)(err_chunk->chunk_hdr) + + sizeof(sctp_chunkhdr_t)); + /* Replace the cause code with the ""Unrecognized parameter"" + * parameter type. + */ + sctp_addto_chunk(repl, len, unk_param); + sctp_chunk_free(err_chunk); + } + + sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc)); + + sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl)); + + /* + * Note: After sending out INIT ACK with the State Cookie parameter, + * ""Z"" MUST NOT allocate any resources, nor keep any states for the + * new association. Otherwise, ""Z"" will be vulnerable to resource + * attacks. + */ + sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL()); + + return SCTP_DISPOSITION_DELETE_TCB; + +nomem_init: + sctp_association_free(new_asoc); +nomem: + if (err_chunk) + sctp_chunk_free(err_chunk); + return SCTP_DISPOSITION_NOMEM; +} +","@@ -170,6 +170,9 @@ sctp_chunk_length_valid(struct sctp_chunk *chunk, + { + __u16 chunk_length = ntohs(chunk->chunk_hdr->length); + ++ /* Previously already marked? */ ++ if (unlikely(chunk->pdiscard)) ++ return 0; + if (unlikely(chunk_length < required_length)) + return 0; + ",1530,1861,2048 +8878,"MagickExport MagickBooleanType HaldClutImage(Image *image, + const Image *hald_image,ExceptionInfo *exception) +{ +#define HaldClutImageTag ""Clut/Image"" + + typedef struct _HaldInfo + { + double + x, + y, + z; + } HaldInfo; + + CacheView + *hald_view, + *image_view; + + double + width; + + MagickBooleanType + status; + + MagickOffsetType + progress; + + PixelInfo + zero; + + size_t + cube_size, + length, + level; + + ssize_t + y; + + assert(image != (Image *) NULL); + assert(image->signature == MagickCoreSignature); + if (image->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); + assert(hald_image != (Image *) NULL); + assert(hald_image->signature == MagickCoreSignature); + if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) + return(MagickFalse); + if (image->alpha_trait == UndefinedPixelTrait) + (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); + /* + Hald clut image. + */ + status=MagickTrue; + progress=0; + length=(size_t) MagickMin((MagickRealType) hald_image->columns, + (MagickRealType) hald_image->rows); + for (level=2; (level*level*level) < length; level++) ; + level*=level; + cube_size=level*level; + width=(double) hald_image->columns; + GetPixelInfo(hald_image,&zero); + hald_view=AcquireVirtualCacheView(hald_image,exception); + image_view=AcquireAuthenticCacheView(image,exception); +#if defined(MAGICKCORE_OPENMP_SUPPORT) + #pragma omp parallel for schedule(static) shared(progress,status) \ + magick_number_threads(image,image,image->rows,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++) + { + double + offset; + + HaldInfo + point; + + PixelInfo + pixel, + pixel1, + pixel2, + pixel3, + pixel4; + + point.x=QuantumScale*(level-1.0)*GetPixelRed(image,q); + point.y=QuantumScale*(level-1.0)*GetPixelGreen(image,q); + point.z=QuantumScale*(level-1.0)*GetPixelBlue(image,q); + offset=point.x+level*floor(point.y)+cube_size*floor(point.z); + point.x-=floor(point.x); + point.y-=floor(point.y); + point.z-=floor(point.z); + pixel1=zero; + status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, + fmod(offset,width),floor(offset/width),&pixel1,exception); + if (status == MagickFalse) + break; + pixel2=zero; + status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, + fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception); + if (status == MagickFalse) + break; + pixel3=zero; + CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha, + point.y,&pixel3); + offset+=cube_size; + status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, + fmod(offset,width),floor(offset/width),&pixel1,exception); + if (status == MagickFalse) + break; + status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, + fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception); + if (status == MagickFalse) + break; + pixel4=zero; + CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha, + point.y,&pixel4); + pixel=zero; + CompositePixelInfoAreaBlend(&pixel3,pixel3.alpha,&pixel4,pixel4.alpha, + point.z,&pixel); + if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) + SetPixelRed(image,ClampToQuantum(pixel.red),q); + if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) + SetPixelGreen(image,ClampToQuantum(pixel.green),q); + if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) + SetPixelBlue(image,ClampToQuantum(pixel.blue),q); + if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && + (image->colorspace == CMYKColorspace)) + SetPixelBlack(image,ClampToQuantum(pixel.black),q); + if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && + (image->alpha_trait != UndefinedPixelTrait)) + SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); + 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 atomic +#endif + progress++; + proceed=SetImageProgress(image,HaldClutImageTag,progress,image->rows); + if (proceed == MagickFalse) + status=MagickFalse; + } + } + hald_view=DestroyCacheView(hald_view); + image_view=DestroyCacheView(image_view); + return(status); +} +",0,"MagickExport MagickBooleanType HaldClutImage(Image *image, + const Image *hald_image,ExceptionInfo *exception) +{ +#define HaldClutImageTag ""Clut/Image"" + + typedef struct _HaldInfo + { + double + x, + y, + z; + } HaldInfo; + + CacheView + *hald_view, + *image_view; + + double + width; + + MagickBooleanType + status; + + MagickOffsetType + progress; + + PixelInfo + zero; + + size_t + cube_size, + length, + level; + + ssize_t + y; + + assert(image != (Image *) NULL); + assert(image->signature == MagickCoreSignature); + if (image->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); + assert(hald_image != (Image *) NULL); + assert(hald_image->signature == MagickCoreSignature); + if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) + return(MagickFalse); + if (image->alpha_trait == UndefinedPixelTrait) + (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); + /* + Hald clut image. + */ + status=MagickTrue; + progress=0; + length=(size_t) MagickMin((MagickRealType) hald_image->columns, + (MagickRealType) hald_image->rows); + for (level=2; (level*level*level) < length; level++) ; + level*=level; + cube_size=level*level; + width=(double) hald_image->columns; + GetPixelInfo(hald_image,&zero); + hald_view=AcquireVirtualCacheView(hald_image,exception); + image_view=AcquireAuthenticCacheView(image,exception); +#if defined(MAGICKCORE_OPENMP_SUPPORT) + #pragma omp parallel for schedule(static) shared(progress,status) \ + magick_number_threads(image,image,image->rows,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++) + { + double + offset; + + HaldInfo + point; + + PixelInfo + pixel, + pixel1, + pixel2, + pixel3, + pixel4; + + point.x=QuantumScale*(level-1.0)*GetPixelRed(image,q); + point.y=QuantumScale*(level-1.0)*GetPixelGreen(image,q); + point.z=QuantumScale*(level-1.0)*GetPixelBlue(image,q); + offset=point.x+level*floor(point.y)+cube_size*floor(point.z); + point.x-=floor(point.x); + point.y-=floor(point.y); + point.z-=floor(point.z); + pixel1=zero; + status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, + fmod(offset,width),floor(offset/width),&pixel1,exception); + if (status == MagickFalse) + break; + pixel2=zero; + status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, + fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception); + if (status == MagickFalse) + break; + pixel3=zero; + CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha, + point.y,&pixel3); + offset+=cube_size; + status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, + fmod(offset,width),floor(offset/width),&pixel1,exception); + if (status == MagickFalse) + break; + status=InterpolatePixelInfo(hald_image,hald_view,hald_image->interpolate, + fmod(offset+level,width),floor((offset+level)/width),&pixel2,exception); + if (status == MagickFalse) + break; + pixel4=zero; + CompositePixelInfoAreaBlend(&pixel1,pixel1.alpha,&pixel2,pixel2.alpha, + point.y,&pixel4); + pixel=zero; + CompositePixelInfoAreaBlend(&pixel3,pixel3.alpha,&pixel4,pixel4.alpha, + point.z,&pixel); + if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) + SetPixelRed(image,ClampToQuantum(pixel.red),q); + if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) + SetPixelGreen(image,ClampToQuantum(pixel.green),q); + if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) + SetPixelBlue(image,ClampToQuantum(pixel.blue),q); + if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && + (image->colorspace == CMYKColorspace)) + SetPixelBlack(image,ClampToQuantum(pixel.black),q); + if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && + (image->alpha_trait != UndefinedPixelTrait)) + SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); + 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 atomic +#endif + progress++; + proceed=SetImageProgress(image,HaldClutImageTag,progress,image->rows); + if (proceed == MagickFalse) + status=MagickFalse; + } + } + hald_view=DestroyCacheView(hald_view); + image_view=DestroyCacheView(image_view); + return(status); +} +","@@ -1973,7 +1973,7 @@ MagickExport Image *EnhanceImage(const Image *image,ExceptionInfo *exception) + pixel.black=((aggregate.black+total_weight/2.0)/total_weight); + pixel.alpha=((aggregate.alpha+total_weight/2.0)/total_weight); + } +- SetPixelViaPixelInfo(image,&pixel,q); ++ SetPixelViaPixelInfo(enhance_image,&pixel,q); + p+=GetPixelChannels(image); + q+=GetPixelChannels(enhance_image); + }",1367,1698,2048 +18156,"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 + 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 { + 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; +} +",1,"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; +} +","@@ -2738,8 +2738,10 @@ static int http_receive_data(HTTPContext *c) + } 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 ++ 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) +@@ -2761,6 +2763,7 @@ static int http_receive_data(HTTPContext *c) + /* 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;",1381,1712,2048 +4568,"int ssl3_send_server_hello(SSL *s) + { + unsigned char *buf; + unsigned char *p,*d; + int i,sl; + int al = 0; + unsigned long l; + + if (s->state == SSL3_ST_SW_SRVR_HELLO_A) + { + buf=(unsigned char *)s->init_buf->data; +#ifdef OPENSSL_NO_TLSEXT + p=s->s3->server_random; + if (ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE) <= 0) + return -1; +#endif + /* Do the message type and length last */ + d=p= ssl_handshake_start(s); + + *(p++)=s->version>>8; + *(p++)=s->version&0xff; + + /* Random stuff */ + memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE); + p+=SSL3_RANDOM_SIZE; + + /*- + * There are several cases for the session ID to send + * back in the server hello: + * - For session reuse from the session cache, + * we send back the old session ID. + * - If stateless session reuse (using a session ticket) + * is successful, we send back the client's ""session ID"" + * (which doesn't actually identify the session). + * - If it is a new session, we send back the new + * session ID. + * - However, if we want the new session to be single-use, + * we send back a 0-length session ID. + * s->hit is non-zero in either case of session reuse, + * so the following won't overwrite an ID that we're supposed + * to send back. + */ + if (s->session->not_resumable || + (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER) + && !s->hit)) + s->session->session_id_length=0; + + sl=s->session->session_id_length; + if (sl > (int)sizeof(s->session->session_id)) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR); + return -1; + } + *(p++)=sl; + memcpy(p,s->session->session_id,sl); + p+=sl; + + /* put the cipher */ + i=ssl3_put_cipher_by_char(s->s3->tmp.new_cipher,p); + p+=i; + + /* put the compression method */ +#ifdef OPENSSL_NO_COMP + *(p++)=0; +#else + if (s->s3->tmp.new_compression == NULL) + *(p++)=0; + else + *(p++)=s->s3->tmp.new_compression->id; +#endif +#ifndef OPENSSL_NO_TLSEXT + if (ssl_prepare_serverhello_tlsext(s) <= 0) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT); + return -1; + } + if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH, &al)) == NULL) + { + ssl3_send_alert(s, SSL3_AL_FATAL, al); + SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,ERR_R_INTERNAL_ERROR); + return -1; + } +#endif + /* do the header */ + l=(p-d); + ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l); + s->state=SSL3_ST_SW_SRVR_HELLO_B; + } + + /* SSL3_ST_SW_SRVR_HELLO_B */ + return ssl_do_write(s); + } +",0,"int ssl3_send_server_hello(SSL *s) + { + unsigned char *buf; + unsigned char *p,*d; + int i,sl; + int al = 0; + unsigned long l; + + if (s->state == SSL3_ST_SW_SRVR_HELLO_A) + { + buf=(unsigned char *)s->init_buf->data; +#ifdef OPENSSL_NO_TLSEXT + p=s->s3->server_random; + if (ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE) <= 0) + return -1; +#endif + /* Do the message type and length last */ + d=p= ssl_handshake_start(s); + + *(p++)=s->version>>8; + *(p++)=s->version&0xff; + + /* Random stuff */ + memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE); + p+=SSL3_RANDOM_SIZE; + + /*- + * There are several cases for the session ID to send + * back in the server hello: + * - For session reuse from the session cache, + * we send back the old session ID. + * - If stateless session reuse (using a session ticket) + * is successful, we send back the client's ""session ID"" + * (which doesn't actually identify the session). + * - If it is a new session, we send back the new + * session ID. + * - However, if we want the new session to be single-use, + * we send back a 0-length session ID. + * s->hit is non-zero in either case of session reuse, + * so the following won't overwrite an ID that we're supposed + * to send back. + */ + if (s->session->not_resumable || + (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER) + && !s->hit)) + s->session->session_id_length=0; + + sl=s->session->session_id_length; + if (sl > (int)sizeof(s->session->session_id)) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR); + return -1; + } + *(p++)=sl; + memcpy(p,s->session->session_id,sl); + p+=sl; + + /* put the cipher */ + i=ssl3_put_cipher_by_char(s->s3->tmp.new_cipher,p); + p+=i; + + /* put the compression method */ +#ifdef OPENSSL_NO_COMP + *(p++)=0; +#else + if (s->s3->tmp.new_compression == NULL) + *(p++)=0; + else + *(p++)=s->s3->tmp.new_compression->id; +#endif +#ifndef OPENSSL_NO_TLSEXT + if (ssl_prepare_serverhello_tlsext(s) <= 0) + { + SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT); + return -1; + } + if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH, &al)) == NULL) + { + ssl3_send_alert(s, SSL3_AL_FATAL, al); + SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,ERR_R_INTERNAL_ERROR); + return -1; + } +#endif + /* do the header */ + l=(p-d); + ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l); + s->state=SSL3_ST_SW_SRVR_HELLO_B; + } + + /* SSL3_ST_SW_SRVR_HELLO_B */ + return ssl_do_write(s); + } +","@@ -3056,7 +3056,7 @@ int ssl3_get_cert_verify(SSL *s) + if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY) + { + s->s3->tmp.reuse_message=1; +- if ((peer != NULL) && (type & EVP_PKT_SIGN)) ++ if (peer != NULL) + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE);",814,1145,2048 +3689,"static int do_last(struct nameidata *nd, struct path *path, + struct file *file, const struct open_flags *op, + int *opened, struct filename *name) +{ + struct dentry *dir = nd->path.dentry; + int open_flag = op->open_flag; + bool will_truncate = (open_flag & O_TRUNC) != 0; + bool got_write = false; + int acc_mode = op->acc_mode; + struct inode *inode; + bool symlink_ok = false; + struct path save_parent = { .dentry = NULL, .mnt = NULL }; + bool retried = false; + int error; + + nd->flags &= ~LOOKUP_PARENT; + nd->flags |= op->intent; + + if (nd->last_type != LAST_NORM) { + error = handle_dots(nd, nd->last_type); + if (error) + return error; + goto finish_open; + } + + if (!(open_flag & O_CREAT)) { + if (nd->last.name[nd->last.len]) + nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY; + if (open_flag & O_PATH && !(nd->flags & LOOKUP_FOLLOW)) + symlink_ok = true; + /* we _can_ be in RCU mode here */ + error = lookup_fast(nd, path, &inode); + if (likely(!error)) + goto finish_lookup; + + if (error < 0) + goto out; + + BUG_ON(nd->inode != dir->d_inode); + } else { + /* create side of things */ + /* + * This will *only* deal with leaving RCU mode - LOOKUP_JUMPED + * has been cleared when we got to the last component we are + * about to look up + */ + error = complete_walk(nd); + if (error) + return error; + + audit_inode(name, dir, LOOKUP_PARENT); + error = -EISDIR; + /* trailing slashes? */ + if (nd->last.name[nd->last.len]) + goto out; + } + +retry_lookup: + if (op->open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) { + error = mnt_want_write(nd->path.mnt); + if (!error) + got_write = true; + /* + * do _not_ fail yet - we might not need that or fail with + * a different error; let lookup_open() decide; we'll be + * dropping this one anyway. + */ + } + mutex_lock(&dir->d_inode->i_mutex); + error = lookup_open(nd, path, file, op, got_write, opened); + mutex_unlock(&dir->d_inode->i_mutex); + + if (error <= 0) { + if (error) + goto out; + + if ((*opened & FILE_CREATED) || + !S_ISREG(file_inode(file)->i_mode)) + will_truncate = false; + + audit_inode(name, file->f_path.dentry, 0); + goto opened; + } + + if (*opened & FILE_CREATED) { + /* Don't check for write permission, don't truncate */ + open_flag &= ~O_TRUNC; + will_truncate = false; + acc_mode = MAY_OPEN; + path_to_nameidata(path, nd); + goto finish_open_created; + } + + /* + * create/update audit record if it already exists. + */ + if (d_is_positive(path->dentry)) + audit_inode(name, path->dentry, 0); + + /* + * If atomic_open() acquired write access it is dropped now due to + * possible mount and symlink following (this might be optimized away if + * necessary...) + */ + if (got_write) { + mnt_drop_write(nd->path.mnt); + got_write = false; + } + + error = -EEXIST; + if ((open_flag & (O_EXCL | O_CREAT)) == (O_EXCL | O_CREAT)) + goto exit_dput; + + error = follow_managed(path, nd->flags); + if (error < 0) + goto exit_dput; + + if (error) + nd->flags |= LOOKUP_JUMPED; + + BUG_ON(nd->flags & LOOKUP_RCU); + inode = path->dentry->d_inode; +finish_lookup: + /* we _can_ be in RCU mode here */ + error = -ENOENT; + if (!inode || d_is_negative(path->dentry)) { + path_to_nameidata(path, nd); + goto out; + } + + if (should_follow_link(path->dentry, !symlink_ok)) { + if (nd->flags & LOOKUP_RCU) { + if (unlikely(unlazy_walk(nd, path->dentry))) { + error = -ECHILD; + goto out; + } + } + BUG_ON(inode != path->dentry->d_inode); + return 1; + } + + if ((nd->flags & LOOKUP_RCU) || nd->path.mnt != path->mnt) { + path_to_nameidata(path, nd); + } else { + save_parent.dentry = nd->path.dentry; + save_parent.mnt = mntget(path->mnt); + nd->path.dentry = path->dentry; + + } + nd->inode = inode; + /* Why this, you ask? _Now_ we might have grown LOOKUP_JUMPED... */ +finish_open: + error = complete_walk(nd); + if (error) { + path_put(&save_parent); + return error; + } + audit_inode(name, nd->path.dentry, 0); + error = -EISDIR; + if ((open_flag & O_CREAT) && d_is_dir(nd->path.dentry)) + goto out; + error = -ENOTDIR; + if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry)) + goto out; + if (!S_ISREG(nd->inode->i_mode)) + will_truncate = false; + + if (will_truncate) { + error = mnt_want_write(nd->path.mnt); + if (error) + goto out; + got_write = true; + } +finish_open_created: + error = may_open(&nd->path, acc_mode, open_flag); + if (error) + goto out; + file->f_path.mnt = nd->path.mnt; + error = finish_open(file, nd->path.dentry, NULL, opened); + if (error) { + if (error == -EOPENSTALE) + goto stale_open; + goto out; + } +opened: + error = open_check_o_direct(file); + if (error) + goto exit_fput; + error = ima_file_check(file, op->acc_mode); + if (error) + goto exit_fput; + + if (will_truncate) { + error = handle_truncate(file); + if (error) + goto exit_fput; + } +out: + if (got_write) + mnt_drop_write(nd->path.mnt); + path_put(&save_parent); + terminate_walk(nd); + return error; + +exit_dput: + path_put_conditional(path, nd); + goto out; +exit_fput: + fput(file); + goto out; + +stale_open: + /* If no saved parent or already retried then can't retry */ + if (!save_parent.dentry || retried) + goto out; + + BUG_ON(save_parent.dentry != dir); + path_put(&nd->path); + nd->path = save_parent; + nd->inode = dir->d_inode; + save_parent.mnt = NULL; + save_parent.dentry = NULL; + if (got_write) { + mnt_drop_write(nd->path.mnt); + got_write = false; + } + retried = true; + goto retry_lookup; +} +",0,"static int do_last(struct nameidata *nd, struct path *path, + struct file *file, const struct open_flags *op, + int *opened, struct filename *name) +{ + struct dentry *dir = nd->path.dentry; + int open_flag = op->open_flag; + bool will_truncate = (open_flag & O_TRUNC) != 0; + bool got_write = false; + int acc_mode = op->acc_mode; + struct inode *inode; + bool symlink_ok = false; + struct path save_parent = { .dentry = NULL, .mnt = NULL }; + bool retried = false; + int error; + + nd->flags &= ~LOOKUP_PARENT; + nd->flags |= op->intent; + + if (nd->last_type != LAST_NORM) { + error = handle_dots(nd, nd->last_type); + if (error) + return error; + goto finish_open; + } + + if (!(open_flag & O_CREAT)) { + if (nd->last.name[nd->last.len]) + nd->flags |= LOOKUP_FOLLOW | LOOKUP_DIRECTORY; + if (open_flag & O_PATH && !(nd->flags & LOOKUP_FOLLOW)) + symlink_ok = true; + /* we _can_ be in RCU mode here */ + error = lookup_fast(nd, path, &inode); + if (likely(!error)) + goto finish_lookup; + + if (error < 0) + goto out; + + BUG_ON(nd->inode != dir->d_inode); + } else { + /* create side of things */ + /* + * This will *only* deal with leaving RCU mode - LOOKUP_JUMPED + * has been cleared when we got to the last component we are + * about to look up + */ + error = complete_walk(nd); + if (error) + return error; + + audit_inode(name, dir, LOOKUP_PARENT); + error = -EISDIR; + /* trailing slashes? */ + if (nd->last.name[nd->last.len]) + goto out; + } + +retry_lookup: + if (op->open_flag & (O_CREAT | O_TRUNC | O_WRONLY | O_RDWR)) { + error = mnt_want_write(nd->path.mnt); + if (!error) + got_write = true; + /* + * do _not_ fail yet - we might not need that or fail with + * a different error; let lookup_open() decide; we'll be + * dropping this one anyway. + */ + } + mutex_lock(&dir->d_inode->i_mutex); + error = lookup_open(nd, path, file, op, got_write, opened); + mutex_unlock(&dir->d_inode->i_mutex); + + if (error <= 0) { + if (error) + goto out; + + if ((*opened & FILE_CREATED) || + !S_ISREG(file_inode(file)->i_mode)) + will_truncate = false; + + audit_inode(name, file->f_path.dentry, 0); + goto opened; + } + + if (*opened & FILE_CREATED) { + /* Don't check for write permission, don't truncate */ + open_flag &= ~O_TRUNC; + will_truncate = false; + acc_mode = MAY_OPEN; + path_to_nameidata(path, nd); + goto finish_open_created; + } + + /* + * create/update audit record if it already exists. + */ + if (d_is_positive(path->dentry)) + audit_inode(name, path->dentry, 0); + + /* + * If atomic_open() acquired write access it is dropped now due to + * possible mount and symlink following (this might be optimized away if + * necessary...) + */ + if (got_write) { + mnt_drop_write(nd->path.mnt); + got_write = false; + } + + error = -EEXIST; + if ((open_flag & (O_EXCL | O_CREAT)) == (O_EXCL | O_CREAT)) + goto exit_dput; + + error = follow_managed(path, nd->flags); + if (error < 0) + goto exit_dput; + + if (error) + nd->flags |= LOOKUP_JUMPED; + + BUG_ON(nd->flags & LOOKUP_RCU); + inode = path->dentry->d_inode; +finish_lookup: + /* we _can_ be in RCU mode here */ + error = -ENOENT; + if (!inode || d_is_negative(path->dentry)) { + path_to_nameidata(path, nd); + goto out; + } + + if (should_follow_link(path->dentry, !symlink_ok)) { + if (nd->flags & LOOKUP_RCU) { + if (unlikely(unlazy_walk(nd, path->dentry))) { + error = -ECHILD; + goto out; + } + } + BUG_ON(inode != path->dentry->d_inode); + return 1; + } + + if ((nd->flags & LOOKUP_RCU) || nd->path.mnt != path->mnt) { + path_to_nameidata(path, nd); + } else { + save_parent.dentry = nd->path.dentry; + save_parent.mnt = mntget(path->mnt); + nd->path.dentry = path->dentry; + + } + nd->inode = inode; + /* Why this, you ask? _Now_ we might have grown LOOKUP_JUMPED... */ +finish_open: + error = complete_walk(nd); + if (error) { + path_put(&save_parent); + return error; + } + audit_inode(name, nd->path.dentry, 0); + error = -EISDIR; + if ((open_flag & O_CREAT) && d_is_dir(nd->path.dentry)) + goto out; + error = -ENOTDIR; + if ((nd->flags & LOOKUP_DIRECTORY) && !d_can_lookup(nd->path.dentry)) + goto out; + if (!S_ISREG(nd->inode->i_mode)) + will_truncate = false; + + if (will_truncate) { + error = mnt_want_write(nd->path.mnt); + if (error) + goto out; + got_write = true; + } +finish_open_created: + error = may_open(&nd->path, acc_mode, open_flag); + if (error) + goto out; + file->f_path.mnt = nd->path.mnt; + error = finish_open(file, nd->path.dentry, NULL, opened); + if (error) { + if (error == -EOPENSTALE) + goto stale_open; + goto out; + } +opened: + error = open_check_o_direct(file); + if (error) + goto exit_fput; + error = ima_file_check(file, op->acc_mode); + if (error) + goto exit_fput; + + if (will_truncate) { + error = handle_truncate(file); + if (error) + goto exit_fput; + } +out: + if (got_write) + mnt_drop_write(nd->path.mnt); + path_put(&save_parent); + terminate_walk(nd); + return error; + +exit_dput: + path_put_conditional(path, nd); + goto out; +exit_fput: + fput(file); + goto out; + +stale_open: + /* If no saved parent or already retried then can't retry */ + if (!save_parent.dentry || retried) + goto out; + + BUG_ON(save_parent.dentry != dir); + path_put(&nd->path); + nd->path = save_parent; + nd->inode = dir->d_inode; + save_parent.mnt = NULL; + save_parent.dentry = NULL; + if (got_write) { + mnt_drop_write(nd->path.mnt); + got_write = false; + } + retried = true; + goto retry_lookup; +} +","@@ -2256,9 +2256,10 @@ mountpoint_last(struct nameidata *nd, struct path *path) + goto out; + } + path->dentry = dentry; +- path->mnt = mntget(nd->path.mnt); ++ path->mnt = nd->path.mnt; + if (should_follow_link(dentry, nd->flags & LOOKUP_FOLLOW)) + return 1; ++ mntget(path->mnt); + follow_mount(path); + error = 0; + out:",1629,1960,2048 +3263,"int dev_ioctl(struct net *net, unsigned int cmd, void __user *arg) +{ + struct ifreq ifr; + int ret; + char *colon; + + /* One special case: SIOCGIFCONF takes ifconf argument + and requires shared lock, because it sleeps writing + to user space. + */ + + if (cmd == SIOCGIFCONF) { + rtnl_lock(); + ret = dev_ifconf(net, (char __user *) arg); + rtnl_unlock(); + return ret; + } + if (cmd == SIOCGIFNAME) + return dev_ifname(net, (struct ifreq __user *)arg); + + if (copy_from_user(&ifr, arg, sizeof(struct ifreq))) + return -EFAULT; + + ifr.ifr_name[IFNAMSIZ-1] = 0; + + colon = strchr(ifr.ifr_name, ':'); + if (colon) + *colon = 0; + + /* + * See which interface the caller is talking about. + */ + + switch (cmd) { + /* + * These ioctl calls: + * - can be done by all. + * - atomic and do not require locking. + * - return a value + */ + case SIOCGIFFLAGS: + case SIOCGIFMETRIC: + case SIOCGIFMTU: + case SIOCGIFHWADDR: + case SIOCGIFSLAVE: + case SIOCGIFMAP: + case SIOCGIFINDEX: + case SIOCGIFTXQLEN: + dev_load(net, ifr.ifr_name); + rcu_read_lock(); + ret = dev_ifsioc_locked(net, &ifr, cmd); + rcu_read_unlock(); + if (!ret) { + if (colon) + *colon = ':'; + if (copy_to_user(arg, &ifr, + sizeof(struct ifreq))) + ret = -EFAULT; + } + return ret; + + case SIOCETHTOOL: + dev_load(net, ifr.ifr_name); + rtnl_lock(); + ret = dev_ethtool(net, &ifr); + rtnl_unlock(); + if (!ret) { + if (colon) + *colon = ':'; + if (copy_to_user(arg, &ifr, + sizeof(struct ifreq))) + ret = -EFAULT; + } + return ret; + + /* + * These ioctl calls: + * - require superuser power. + * - require strict serialization. + * - return a value + */ + case SIOCGMIIPHY: + case SIOCGMIIREG: + case SIOCSIFNAME: + if (!capable(CAP_NET_ADMIN)) + return -EPERM; + dev_load(net, ifr.ifr_name); + rtnl_lock(); + ret = dev_ifsioc(net, &ifr, cmd); + rtnl_unlock(); + if (!ret) { + if (colon) + *colon = ':'; + if (copy_to_user(arg, &ifr, + sizeof(struct ifreq))) + ret = -EFAULT; + } + return ret; + + /* + * These ioctl calls: + * - require superuser power. + * - require strict serialization. + * - do not return a value + */ + case SIOCSIFFLAGS: + case SIOCSIFMETRIC: + case SIOCSIFMTU: + case SIOCSIFMAP: + case SIOCSIFHWADDR: + case SIOCSIFSLAVE: + case SIOCADDMULTI: + case SIOCDELMULTI: + case SIOCSIFHWBROADCAST: + case SIOCSIFTXQLEN: + case SIOCSMIIREG: + case SIOCBONDENSLAVE: + case SIOCBONDRELEASE: + case SIOCBONDSETHWADDR: + case SIOCBONDCHANGEACTIVE: + case SIOCBRADDIF: + case SIOCBRDELIF: + case SIOCSHWTSTAMP: + if (!capable(CAP_NET_ADMIN)) + return -EPERM; + /* fall through */ + case SIOCBONDSLAVEINFOQUERY: + case SIOCBONDINFOQUERY: + dev_load(net, ifr.ifr_name); + rtnl_lock(); + ret = dev_ifsioc(net, &ifr, cmd); + rtnl_unlock(); + return ret; + + case SIOCGIFMEM: + /* Get the per device memory space. We can add this but + * currently do not support it */ + case SIOCSIFMEM: + /* Set the per device memory buffer space. + * Not applicable in our case */ + case SIOCSIFLINK: + return -EINVAL; + + /* + * Unknown or private ioctl. + */ + default: + if (cmd == SIOCWANDEV || + (cmd >= SIOCDEVPRIVATE && + cmd <= SIOCDEVPRIVATE + 15)) { + dev_load(net, ifr.ifr_name); + rtnl_lock(); + ret = dev_ifsioc(net, &ifr, cmd); + rtnl_unlock(); + if (!ret && copy_to_user(arg, &ifr, + sizeof(struct ifreq))) + ret = -EFAULT; + return ret; + } + /* Take care of Wireless Extensions */ + if (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST) + return wext_handle_ioctl(net, &ifr, cmd, arg); + return -EINVAL; + } +} +",0,"int dev_ioctl(struct net *net, unsigned int cmd, void __user *arg) +{ + struct ifreq ifr; + int ret; + char *colon; + + /* One special case: SIOCGIFCONF takes ifconf argument + and requires shared lock, because it sleeps writing + to user space. + */ + + if (cmd == SIOCGIFCONF) { + rtnl_lock(); + ret = dev_ifconf(net, (char __user *) arg); + rtnl_unlock(); + return ret; + } + if (cmd == SIOCGIFNAME) + return dev_ifname(net, (struct ifreq __user *)arg); + + if (copy_from_user(&ifr, arg, sizeof(struct ifreq))) + return -EFAULT; + + ifr.ifr_name[IFNAMSIZ-1] = 0; + + colon = strchr(ifr.ifr_name, ':'); + if (colon) + *colon = 0; + + /* + * See which interface the caller is talking about. + */ + + switch (cmd) { + /* + * These ioctl calls: + * - can be done by all. + * - atomic and do not require locking. + * - return a value + */ + case SIOCGIFFLAGS: + case SIOCGIFMETRIC: + case SIOCGIFMTU: + case SIOCGIFHWADDR: + case SIOCGIFSLAVE: + case SIOCGIFMAP: + case SIOCGIFINDEX: + case SIOCGIFTXQLEN: + dev_load(net, ifr.ifr_name); + rcu_read_lock(); + ret = dev_ifsioc_locked(net, &ifr, cmd); + rcu_read_unlock(); + if (!ret) { + if (colon) + *colon = ':'; + if (copy_to_user(arg, &ifr, + sizeof(struct ifreq))) + ret = -EFAULT; + } + return ret; + + case SIOCETHTOOL: + dev_load(net, ifr.ifr_name); + rtnl_lock(); + ret = dev_ethtool(net, &ifr); + rtnl_unlock(); + if (!ret) { + if (colon) + *colon = ':'; + if (copy_to_user(arg, &ifr, + sizeof(struct ifreq))) + ret = -EFAULT; + } + return ret; + + /* + * These ioctl calls: + * - require superuser power. + * - require strict serialization. + * - return a value + */ + case SIOCGMIIPHY: + case SIOCGMIIREG: + case SIOCSIFNAME: + if (!capable(CAP_NET_ADMIN)) + return -EPERM; + dev_load(net, ifr.ifr_name); + rtnl_lock(); + ret = dev_ifsioc(net, &ifr, cmd); + rtnl_unlock(); + if (!ret) { + if (colon) + *colon = ':'; + if (copy_to_user(arg, &ifr, + sizeof(struct ifreq))) + ret = -EFAULT; + } + return ret; + + /* + * These ioctl calls: + * - require superuser power. + * - require strict serialization. + * - do not return a value + */ + case SIOCSIFFLAGS: + case SIOCSIFMETRIC: + case SIOCSIFMTU: + case SIOCSIFMAP: + case SIOCSIFHWADDR: + case SIOCSIFSLAVE: + case SIOCADDMULTI: + case SIOCDELMULTI: + case SIOCSIFHWBROADCAST: + case SIOCSIFTXQLEN: + case SIOCSMIIREG: + case SIOCBONDENSLAVE: + case SIOCBONDRELEASE: + case SIOCBONDSETHWADDR: + case SIOCBONDCHANGEACTIVE: + case SIOCBRADDIF: + case SIOCBRDELIF: + case SIOCSHWTSTAMP: + if (!capable(CAP_NET_ADMIN)) + return -EPERM; + /* fall through */ + case SIOCBONDSLAVEINFOQUERY: + case SIOCBONDINFOQUERY: + dev_load(net, ifr.ifr_name); + rtnl_lock(); + ret = dev_ifsioc(net, &ifr, cmd); + rtnl_unlock(); + return ret; + + case SIOCGIFMEM: + /* Get the per device memory space. We can add this but + * currently do not support it */ + case SIOCSIFMEM: + /* Set the per device memory buffer space. + * Not applicable in our case */ + case SIOCSIFLINK: + return -EINVAL; + + /* + * Unknown or private ioctl. + */ + default: + if (cmd == SIOCWANDEV || + (cmd >= SIOCDEVPRIVATE && + cmd <= SIOCDEVPRIVATE + 15)) { + dev_load(net, ifr.ifr_name); + rtnl_lock(); + ret = dev_ifsioc(net, &ifr, cmd); + rtnl_unlock(); + if (!ret && copy_to_user(arg, &ifr, + sizeof(struct ifreq))) + ret = -EFAULT; + return ret; + } + /* Take care of Wireless Extensions */ + if (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST) + return wext_handle_ioctl(net, &ifr, cmd, arg); + return -EINVAL; + } +} +","@@ -1451,7 +1451,7 @@ static inline void net_timestamp(struct sk_buff *skb) + * + * return values: + * NET_RX_SUCCESS (no congestion) +- * NET_RX_DROP (packet was dropped) ++ * NET_RX_DROP (packet was dropped, but freed) + * + * dev_forward_skb can be used for injecting an skb from the + * start_xmit function of one device into the receive queue +@@ -1465,12 +1465,11 @@ int dev_forward_skb(struct net_device *dev, struct sk_buff *skb) + { + skb_orphan(skb); + +- if (!(dev->flags & IFF_UP)) +- return NET_RX_DROP; +- +- if (skb->len > (dev->mtu + dev->hard_header_len)) ++ if (!(dev->flags & IFF_UP) || ++ (skb->len > (dev->mtu + dev->hard_header_len))) { ++ kfree_skb(skb); + return NET_RX_DROP; +- ++ } + skb_set_dev(skb, dev); + skb->tstamp.tv64 = 0; + skb->pkt_type = PACKET_HOST;",1162,1493,2048 +6594,"int saa7164_bus_set(struct saa7164_dev *dev, struct tmComResInfo* msg, + void *buf) +{ + struct tmComResBusInfo *bus = &dev->bus; + u32 bytes_to_write, free_write_space, timeout, curr_srp, curr_swp; + u32 new_swp, space_rem; + int ret = SAA_ERR_BAD_PARAMETER; + u16 size; + + if (!msg) { + printk(KERN_ERR ""%s() !msg\n"", __func__); + return SAA_ERR_BAD_PARAMETER; + } + + dprintk(DBGLVL_BUS, ""%s()\n"", __func__); + + saa7164_bus_verify(dev); + + if (msg->size > dev->bus.m_wMaxReqSize) { + printk(KERN_ERR ""%s() Exceeded dev->bus.m_wMaxReqSize\n"", + __func__); + return SAA_ERR_BAD_PARAMETER; + } + + if ((msg->size > 0) && (buf == NULL)) { + printk(KERN_ERR ""%s() Missing message buffer\n"", __func__); + return SAA_ERR_BAD_PARAMETER; + } + + /* Lock the bus from any other access */ + mutex_lock(&bus->lock); + + bytes_to_write = sizeof(*msg) + msg->size; + free_write_space = 0; + timeout = SAA_BUS_TIMEOUT; + curr_srp = saa7164_readl(bus->m_dwSetReadPos); + curr_swp = saa7164_readl(bus->m_dwSetWritePos); + + /* Deal with ring wrapping issues */ + if (curr_srp > curr_swp) + /* Deal with the wrapped ring */ + free_write_space = curr_srp - curr_swp; + else + /* The ring has not wrapped yet */ + free_write_space = (curr_srp + bus->m_dwSizeSetRing) - curr_swp; + + dprintk(DBGLVL_BUS, ""%s() bytes_to_write = %d\n"", __func__, + bytes_to_write); + + dprintk(DBGLVL_BUS, ""%s() free_write_space = %d\n"", __func__, + free_write_space); + + dprintk(DBGLVL_BUS, ""%s() curr_srp = %x\n"", __func__, curr_srp); + dprintk(DBGLVL_BUS, ""%s() curr_swp = %x\n"", __func__, curr_swp); + + /* Process the msg and write the content onto the bus */ + while (bytes_to_write >= free_write_space) { + + if (timeout-- == 0) { + printk(KERN_ERR ""%s() bus timeout\n"", __func__); + ret = SAA_ERR_NO_RESOURCES; + goto out; + } + + /* TODO: Review this delay, efficient? */ + /* Wait, allowing the hardware fetch time */ + mdelay(1); + + /* Check the space usage again */ + curr_srp = saa7164_readl(bus->m_dwSetReadPos); + + /* Deal with ring wrapping issues */ + if (curr_srp > curr_swp) + /* Deal with the wrapped ring */ + free_write_space = curr_srp - curr_swp; + else + /* Read didn't wrap around the buffer */ + free_write_space = (curr_srp + bus->m_dwSizeSetRing) - + curr_swp; + + } + + /* Calculate the new write position */ + new_swp = curr_swp + bytes_to_write; + + dprintk(DBGLVL_BUS, ""%s() new_swp = %x\n"", __func__, new_swp); + dprintk(DBGLVL_BUS, ""%s() bus->m_dwSizeSetRing = %x\n"", __func__, + bus->m_dwSizeSetRing); + + /* + * Make a copy of msg->size before it is converted to le16 since it is + * used in the code below. + */ + size = msg->size; + /* Convert to le16/le32 */ + msg->size = (__force u16)cpu_to_le16(msg->size); + msg->command = (__force u32)cpu_to_le32(msg->command); + msg->controlselector = (__force u16)cpu_to_le16(msg->controlselector); + + /* Mental Note: line 462 tmmhComResBusPCIe.cpp */ + + /* Check if we're going to wrap again */ + if (new_swp > bus->m_dwSizeSetRing) { + + /* Ring wraps */ + new_swp -= bus->m_dwSizeSetRing; + + space_rem = bus->m_dwSizeSetRing - curr_swp; + + dprintk(DBGLVL_BUS, ""%s() space_rem = %x\n"", __func__, + space_rem); + + dprintk(DBGLVL_BUS, ""%s() sizeof(*msg) = %d\n"", __func__, + (u32)sizeof(*msg)); + + if (space_rem < sizeof(*msg)) { + dprintk(DBGLVL_BUS, ""%s() tr4\n"", __func__); + + /* Split the msg into pieces as the ring wraps */ + memcpy_toio(bus->m_pdwSetRing + curr_swp, msg, space_rem); + memcpy_toio(bus->m_pdwSetRing, (u8 *)msg + space_rem, + sizeof(*msg) - space_rem); + + memcpy_toio(bus->m_pdwSetRing + sizeof(*msg) - space_rem, + buf, size); + + } else if (space_rem == sizeof(*msg)) { + dprintk(DBGLVL_BUS, ""%s() tr5\n"", __func__); + + /* Additional data at the beginning of the ring */ + memcpy_toio(bus->m_pdwSetRing + curr_swp, msg, sizeof(*msg)); + memcpy_toio(bus->m_pdwSetRing, buf, size); + + } else { + /* Additional data wraps around the ring */ + memcpy_toio(bus->m_pdwSetRing + curr_swp, msg, sizeof(*msg)); + if (size > 0) { + memcpy_toio(bus->m_pdwSetRing + curr_swp + + sizeof(*msg), buf, space_rem - + sizeof(*msg)); + memcpy_toio(bus->m_pdwSetRing, (u8 *)buf + + space_rem - sizeof(*msg), + bytes_to_write - space_rem); + } + + } + + } /* (new_swp > bus->m_dwSizeSetRing) */ + else { + dprintk(DBGLVL_BUS, ""%s() tr6\n"", __func__); + + /* The ring buffer doesn't wrap, two simple copies */ + memcpy_toio(bus->m_pdwSetRing + curr_swp, msg, sizeof(*msg)); + memcpy_toio(bus->m_pdwSetRing + curr_swp + sizeof(*msg), buf, + size); + } + + dprintk(DBGLVL_BUS, ""%s() new_swp = %x\n"", __func__, new_swp); + + /* Update the bus write position */ + saa7164_writel(bus->m_dwSetWritePos, new_swp); + + /* Convert back to cpu after writing the msg to the ringbuffer. */ + msg->size = le16_to_cpu((__force __le16)msg->size); + msg->command = le32_to_cpu((__force __le32)msg->command); + msg->controlselector = le16_to_cpu((__force __le16)msg->controlselector); + ret = SAA_OK; + +out: + saa7164_bus_dump(dev); + mutex_unlock(&bus->lock); + saa7164_bus_verify(dev); + return ret; +} +",0,"int saa7164_bus_set(struct saa7164_dev *dev, struct tmComResInfo* msg, + void *buf) +{ + struct tmComResBusInfo *bus = &dev->bus; + u32 bytes_to_write, free_write_space, timeout, curr_srp, curr_swp; + u32 new_swp, space_rem; + int ret = SAA_ERR_BAD_PARAMETER; + u16 size; + + if (!msg) { + printk(KERN_ERR ""%s() !msg\n"", __func__); + return SAA_ERR_BAD_PARAMETER; + } + + dprintk(DBGLVL_BUS, ""%s()\n"", __func__); + + saa7164_bus_verify(dev); + + if (msg->size > dev->bus.m_wMaxReqSize) { + printk(KERN_ERR ""%s() Exceeded dev->bus.m_wMaxReqSize\n"", + __func__); + return SAA_ERR_BAD_PARAMETER; + } + + if ((msg->size > 0) && (buf == NULL)) { + printk(KERN_ERR ""%s() Missing message buffer\n"", __func__); + return SAA_ERR_BAD_PARAMETER; + } + + /* Lock the bus from any other access */ + mutex_lock(&bus->lock); + + bytes_to_write = sizeof(*msg) + msg->size; + free_write_space = 0; + timeout = SAA_BUS_TIMEOUT; + curr_srp = saa7164_readl(bus->m_dwSetReadPos); + curr_swp = saa7164_readl(bus->m_dwSetWritePos); + + /* Deal with ring wrapping issues */ + if (curr_srp > curr_swp) + /* Deal with the wrapped ring */ + free_write_space = curr_srp - curr_swp; + else + /* The ring has not wrapped yet */ + free_write_space = (curr_srp + bus->m_dwSizeSetRing) - curr_swp; + + dprintk(DBGLVL_BUS, ""%s() bytes_to_write = %d\n"", __func__, + bytes_to_write); + + dprintk(DBGLVL_BUS, ""%s() free_write_space = %d\n"", __func__, + free_write_space); + + dprintk(DBGLVL_BUS, ""%s() curr_srp = %x\n"", __func__, curr_srp); + dprintk(DBGLVL_BUS, ""%s() curr_swp = %x\n"", __func__, curr_swp); + + /* Process the msg and write the content onto the bus */ + while (bytes_to_write >= free_write_space) { + + if (timeout-- == 0) { + printk(KERN_ERR ""%s() bus timeout\n"", __func__); + ret = SAA_ERR_NO_RESOURCES; + goto out; + } + + /* TODO: Review this delay, efficient? */ + /* Wait, allowing the hardware fetch time */ + mdelay(1); + + /* Check the space usage again */ + curr_srp = saa7164_readl(bus->m_dwSetReadPos); + + /* Deal with ring wrapping issues */ + if (curr_srp > curr_swp) + /* Deal with the wrapped ring */ + free_write_space = curr_srp - curr_swp; + else + /* Read didn't wrap around the buffer */ + free_write_space = (curr_srp + bus->m_dwSizeSetRing) - + curr_swp; + + } + + /* Calculate the new write position */ + new_swp = curr_swp + bytes_to_write; + + dprintk(DBGLVL_BUS, ""%s() new_swp = %x\n"", __func__, new_swp); + dprintk(DBGLVL_BUS, ""%s() bus->m_dwSizeSetRing = %x\n"", __func__, + bus->m_dwSizeSetRing); + + /* + * Make a copy of msg->size before it is converted to le16 since it is + * used in the code below. + */ + size = msg->size; + /* Convert to le16/le32 */ + msg->size = (__force u16)cpu_to_le16(msg->size); + msg->command = (__force u32)cpu_to_le32(msg->command); + msg->controlselector = (__force u16)cpu_to_le16(msg->controlselector); + + /* Mental Note: line 462 tmmhComResBusPCIe.cpp */ + + /* Check if we're going to wrap again */ + if (new_swp > bus->m_dwSizeSetRing) { + + /* Ring wraps */ + new_swp -= bus->m_dwSizeSetRing; + + space_rem = bus->m_dwSizeSetRing - curr_swp; + + dprintk(DBGLVL_BUS, ""%s() space_rem = %x\n"", __func__, + space_rem); + + dprintk(DBGLVL_BUS, ""%s() sizeof(*msg) = %d\n"", __func__, + (u32)sizeof(*msg)); + + if (space_rem < sizeof(*msg)) { + dprintk(DBGLVL_BUS, ""%s() tr4\n"", __func__); + + /* Split the msg into pieces as the ring wraps */ + memcpy_toio(bus->m_pdwSetRing + curr_swp, msg, space_rem); + memcpy_toio(bus->m_pdwSetRing, (u8 *)msg + space_rem, + sizeof(*msg) - space_rem); + + memcpy_toio(bus->m_pdwSetRing + sizeof(*msg) - space_rem, + buf, size); + + } else if (space_rem == sizeof(*msg)) { + dprintk(DBGLVL_BUS, ""%s() tr5\n"", __func__); + + /* Additional data at the beginning of the ring */ + memcpy_toio(bus->m_pdwSetRing + curr_swp, msg, sizeof(*msg)); + memcpy_toio(bus->m_pdwSetRing, buf, size); + + } else { + /* Additional data wraps around the ring */ + memcpy_toio(bus->m_pdwSetRing + curr_swp, msg, sizeof(*msg)); + if (size > 0) { + memcpy_toio(bus->m_pdwSetRing + curr_swp + + sizeof(*msg), buf, space_rem - + sizeof(*msg)); + memcpy_toio(bus->m_pdwSetRing, (u8 *)buf + + space_rem - sizeof(*msg), + bytes_to_write - space_rem); + } + + } + + } /* (new_swp > bus->m_dwSizeSetRing) */ + else { + dprintk(DBGLVL_BUS, ""%s() tr6\n"", __func__); + + /* The ring buffer doesn't wrap, two simple copies */ + memcpy_toio(bus->m_pdwSetRing + curr_swp, msg, sizeof(*msg)); + memcpy_toio(bus->m_pdwSetRing + curr_swp + sizeof(*msg), buf, + size); + } + + dprintk(DBGLVL_BUS, ""%s() new_swp = %x\n"", __func__, new_swp); + + /* Update the bus write position */ + saa7164_writel(bus->m_dwSetWritePos, new_swp); + + /* Convert back to cpu after writing the msg to the ringbuffer. */ + msg->size = le16_to_cpu((__force __le16)msg->size); + msg->command = le32_to_cpu((__force __le32)msg->command); + msg->controlselector = le16_to_cpu((__force __le16)msg->controlselector); + ret = SAA_OK; + +out: + saa7164_bus_dump(dev); + mutex_unlock(&bus->lock); + saa7164_bus_verify(dev); + return ret; +} +","@@ -389,11 +389,11 @@ int saa7164_bus_get(struct saa7164_dev *dev, struct tmComResInfo* msg, + msg_tmp.size = le16_to_cpu((__force __le16)msg_tmp.size); + msg_tmp.command = le32_to_cpu((__force __le32)msg_tmp.command); + msg_tmp.controlselector = le16_to_cpu((__force __le16)msg_tmp.controlselector); ++ memcpy(msg, &msg_tmp, sizeof(*msg)); + + /* No need to update the read positions, because this was a peek */ + /* If the caller specifically want to peek, return */ + if (peekonly) { +- memcpy(msg, &msg_tmp, sizeof(*msg)); + goto peekout; + } + +@@ -438,21 +438,15 @@ int saa7164_bus_get(struct saa7164_dev *dev, struct tmComResInfo* msg, + space_rem = bus->m_dwSizeGetRing - curr_grp; + + if (space_rem < sizeof(*msg)) { +- /* msg wraps around the ring */ +- memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, space_rem); +- memcpy_fromio((u8 *)msg + space_rem, bus->m_pdwGetRing, +- sizeof(*msg) - space_rem); + if (buf) + memcpy_fromio(buf, bus->m_pdwGetRing + sizeof(*msg) - + space_rem, buf_size); + + } else if (space_rem == sizeof(*msg)) { +- memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg)); + if (buf) + memcpy_fromio(buf, bus->m_pdwGetRing, buf_size); + } else { + /* Additional data wraps around the ring */ +- memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg)); + if (buf) { + memcpy_fromio(buf, bus->m_pdwGetRing + curr_grp + + sizeof(*msg), space_rem - sizeof(*msg)); +@@ -465,15 +459,10 @@ int saa7164_bus_get(struct saa7164_dev *dev, struct tmComResInfo* msg, + + } else { + /* No wrapping */ +- memcpy_fromio(msg, bus->m_pdwGetRing + curr_grp, sizeof(*msg)); + if (buf) + memcpy_fromio(buf, bus->m_pdwGetRing + curr_grp + sizeof(*msg), + buf_size); + } +- /* Convert from little endian to CPU */ +- msg->size = le16_to_cpu((__force __le16)msg->size); +- msg->command = le32_to_cpu((__force __le32)msg->command); +- msg->controlselector = le16_to_cpu((__force __le16)msg->controlselector); + + /* Update the read positions, adjusting the ring */ + saa7164_writel(bus->m_dwGetReadPos, new_grp);",1635,1966,2048 +17553,"void LvmEffect_limitLevel(EffectContext *pContext) { + LVM_ControlParams_t ActiveParams; /* Current control Parameters */ + LVM_ReturnStatus_en LvmStatus=LVM_SUCCESS; /* Function call status */ + + /* Get the current settings */ + LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams); + LVM_ERROR_CHECK(LvmStatus, ""LVM_GetControlParameters"", ""LvmEffect_limitLevel"") + + int gainCorrection = 0; + float energyContribution = 0; + float energyCross = 0; + float energyBassBoost = 0; + float crossCorrection = 0; + + if (pContext->pBundledContext->bEqualizerEnabled == LVM_TRUE) { + for (int i = 0; i < FIVEBAND_NUMBANDS; i++) { + float bandFactor = pContext->pBundledContext->bandGaindB[i]/15.0; + float bandCoefficient = LimitLevel_bandEnergyCoefficient[i]; + float bandEnergy = bandFactor * bandCoefficient * bandCoefficient; + if (bandEnergy > 0) + energyContribution += bandEnergy; + } + + float bandFactorSum = 0; + for (int i = 0; i < FIVEBAND_NUMBANDS-1; i++) { + float bandFactor1 = pContext->pBundledContext->bandGaindB[i]/15.0; + float bandFactor2 = pContext->pBundledContext->bandGaindB[i+1]/15.0; + + if (bandFactor1 > 0 && bandFactor2 > 0) { + float crossEnergy = bandFactor1 * bandFactor2 * + LimitLevel_bandEnergyCrossCoefficient[i]; + bandFactorSum += bandFactor1 * bandFactor2; + + if (crossEnergy > 0) + energyCross += crossEnergy; + } + } + bandFactorSum -= 1.0; + if (bandFactorSum > 0) + crossCorrection = bandFactorSum * 0.7; + } + + if (pContext->pBundledContext->bBassEnabled == LVM_TRUE) { + float boostFactor = (pContext->pBundledContext->BassStrengthSaved)/1000.0; + float boostCoefficient = LimitLevel_bassBoostEnergyCoefficient; + + energyContribution += boostFactor * boostCoefficient * boostCoefficient; + + for (int i = 0; i < FIVEBAND_NUMBANDS; i++) { + float bandFactor = pContext->pBundledContext->bandGaindB[i]/15.0; + float bandCrossCoefficient = LimitLevel_bassBoostEnergyCrossCoefficient[i]; + float bandEnergy = boostFactor * bandFactor * + bandCrossCoefficient; + if (bandEnergy > 0) + energyBassBoost += bandEnergy; + } + } + + if (pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE) { + energyContribution += LimitLevel_virtualizerContribution * + LimitLevel_virtualizerContribution; + } + + double totalEnergyEstimation = sqrt(energyContribution + energyCross + energyBassBoost) - + crossCorrection; + ALOGV("" TOTAL energy estimation: %0.2f"", totalEnergyEstimation); + + int maxLevelRound = (int)(totalEnergyEstimation + 0.99); + if (maxLevelRound + pContext->pBundledContext->volume > 0) { + gainCorrection = maxLevelRound + pContext->pBundledContext->volume; + } + + ActiveParams.VC_EffectLevel = pContext->pBundledContext->volume - gainCorrection; + if (ActiveParams.VC_EffectLevel < -96) { + ActiveParams.VC_EffectLevel = -96; + } + ALOGV(""\tVol:%d, GainCorrection: %d, Actual vol: %d"", pContext->pBundledContext->volume, + gainCorrection, ActiveParams.VC_EffectLevel); + + /* Activate the initial settings */ + LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams); + LVM_ERROR_CHECK(LvmStatus, ""LVM_SetControlParameters"", ""LvmEffect_limitLevel"") + + if (pContext->pBundledContext->firstVolume == LVM_TRUE){ + LvmStatus = LVM_SetVolumeNoSmoothing(pContext->pBundledContext->hInstance, &ActiveParams); + LVM_ERROR_CHECK(LvmStatus, ""LVM_SetVolumeNoSmoothing"", ""LvmBundle_process"") + ALOGV(""\tLVM_VOLUME: Disabling Smoothing for first volume change to remove spikes/clicks""); + pContext->pBundledContext->firstVolume = LVM_FALSE; + } +} +",0,"void LvmEffect_limitLevel(EffectContext *pContext) { + LVM_ControlParams_t ActiveParams; /* Current control Parameters */ + LVM_ReturnStatus_en LvmStatus=LVM_SUCCESS; /* Function call status */ + + /* Get the current settings */ + LvmStatus = LVM_GetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams); + LVM_ERROR_CHECK(LvmStatus, ""LVM_GetControlParameters"", ""LvmEffect_limitLevel"") + + int gainCorrection = 0; + float energyContribution = 0; + float energyCross = 0; + float energyBassBoost = 0; + float crossCorrection = 0; + + if (pContext->pBundledContext->bEqualizerEnabled == LVM_TRUE) { + for (int i = 0; i < FIVEBAND_NUMBANDS; i++) { + float bandFactor = pContext->pBundledContext->bandGaindB[i]/15.0; + float bandCoefficient = LimitLevel_bandEnergyCoefficient[i]; + float bandEnergy = bandFactor * bandCoefficient * bandCoefficient; + if (bandEnergy > 0) + energyContribution += bandEnergy; + } + + float bandFactorSum = 0; + for (int i = 0; i < FIVEBAND_NUMBANDS-1; i++) { + float bandFactor1 = pContext->pBundledContext->bandGaindB[i]/15.0; + float bandFactor2 = pContext->pBundledContext->bandGaindB[i+1]/15.0; + + if (bandFactor1 > 0 && bandFactor2 > 0) { + float crossEnergy = bandFactor1 * bandFactor2 * + LimitLevel_bandEnergyCrossCoefficient[i]; + bandFactorSum += bandFactor1 * bandFactor2; + + if (crossEnergy > 0) + energyCross += crossEnergy; + } + } + bandFactorSum -= 1.0; + if (bandFactorSum > 0) + crossCorrection = bandFactorSum * 0.7; + } + + if (pContext->pBundledContext->bBassEnabled == LVM_TRUE) { + float boostFactor = (pContext->pBundledContext->BassStrengthSaved)/1000.0; + float boostCoefficient = LimitLevel_bassBoostEnergyCoefficient; + + energyContribution += boostFactor * boostCoefficient * boostCoefficient; + + for (int i = 0; i < FIVEBAND_NUMBANDS; i++) { + float bandFactor = pContext->pBundledContext->bandGaindB[i]/15.0; + float bandCrossCoefficient = LimitLevel_bassBoostEnergyCrossCoefficient[i]; + float bandEnergy = boostFactor * bandFactor * + bandCrossCoefficient; + if (bandEnergy > 0) + energyBassBoost += bandEnergy; + } + } + + if (pContext->pBundledContext->bVirtualizerEnabled == LVM_TRUE) { + energyContribution += LimitLevel_virtualizerContribution * + LimitLevel_virtualizerContribution; + } + + double totalEnergyEstimation = sqrt(energyContribution + energyCross + energyBassBoost) - + crossCorrection; + ALOGV("" TOTAL energy estimation: %0.2f"", totalEnergyEstimation); + + int maxLevelRound = (int)(totalEnergyEstimation + 0.99); + if (maxLevelRound + pContext->pBundledContext->volume > 0) { + gainCorrection = maxLevelRound + pContext->pBundledContext->volume; + } + + ActiveParams.VC_EffectLevel = pContext->pBundledContext->volume - gainCorrection; + if (ActiveParams.VC_EffectLevel < -96) { + ActiveParams.VC_EffectLevel = -96; + } + ALOGV(""\tVol:%d, GainCorrection: %d, Actual vol: %d"", pContext->pBundledContext->volume, + gainCorrection, ActiveParams.VC_EffectLevel); + + /* Activate the initial settings */ + LvmStatus = LVM_SetControlParameters(pContext->pBundledContext->hInstance, &ActiveParams); + LVM_ERROR_CHECK(LvmStatus, ""LVM_SetControlParameters"", ""LvmEffect_limitLevel"") + + if (pContext->pBundledContext->firstVolume == LVM_TRUE){ + LvmStatus = LVM_SetVolumeNoSmoothing(pContext->pBundledContext->hInstance, &ActiveParams); + LVM_ERROR_CHECK(LvmStatus, ""LVM_SetVolumeNoSmoothing"", ""LvmBundle_process"") + ALOGV(""\tLVM_VOLUME: Disabling Smoothing for first volume change to remove spikes/clicks""); + pContext->pBundledContext->firstVolume = LVM_FALSE; + } +} +","@@ -2357,8 +2357,12 @@ + + + case EQ_PARAM_BAND_LEVEL: + param2 = *pParamTemp; +- if (param2 >= FIVEBAND_NUMBANDS) { ++ if (param2 < 0 || param2 >= FIVEBAND_NUMBANDS) { + status = -EINVAL; ++ if (param2 < 0) { ++ android_errorWriteLog(0x534e4554, ""32438598""); ++ ALOGW(""\tERROR Equalizer_getParameter() EQ_PARAM_BAND_LEVEL band %d"", param2); ++ } + break; + } + *(int16_t *)pValue = (int16_t)EqualizerGetBandLevel(pContext, param2); +@@ -2368,8 +2372,12 @@ + + + case EQ_PARAM_CENTER_FREQ: + param2 = *pParamTemp; +- if (param2 >= FIVEBAND_NUMBANDS) { ++ if (param2 < 0 || param2 >= FIVEBAND_NUMBANDS) { + status = -EINVAL; ++ if (param2 < 0) { ++ android_errorWriteLog(0x534e4554, ""32436341""); ++ ALOGW(""\tERROR Equalizer_getParameter() EQ_PARAM_CENTER_FREQ band %d"", param2); ++ } + break; + } + *(int32_t *)pValue = EqualizerGetCentreFrequency(pContext, param2); +@@ -2379,8 +2387,12 @@ + + + case EQ_PARAM_BAND_FREQ_RANGE: + param2 = *pParamTemp; +- if (param2 >= FIVEBAND_NUMBANDS) { ++ if (param2 < 0 || param2 >= FIVEBAND_NUMBANDS) { + status = -EINVAL; ++ if (param2 < 0) { ++ android_errorWriteLog(0x534e4554, ""32247948""); ++ ALOGW(""\tERROR Equalizer_getParameter() EQ_PARAM_BAND_FREQ_RANGE band %d"", param2); ++ } + break; + } + EqualizerGetBandFreqRange(pContext, param2, (uint32_t *)pValue, ((uint32_t *)pValue + 1)); +",1001,1332,2048 +2315,"void __init sched_init(void) +{ + int i, j; + unsigned long alloc_size = 0, ptr; + +#ifdef CONFIG_FAIR_GROUP_SCHED + alloc_size += 2 * nr_cpu_ids * sizeof(void **); +#endif +#ifdef CONFIG_RT_GROUP_SCHED + alloc_size += 2 * nr_cpu_ids * sizeof(void **); +#endif +#ifdef CONFIG_CPUMASK_OFFSTACK + alloc_size += num_possible_cpus() * cpumask_size(); +#endif + if (alloc_size) { + ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT); + +#ifdef CONFIG_FAIR_GROUP_SCHED + init_task_group.se = (struct sched_entity **)ptr; + ptr += nr_cpu_ids * sizeof(void **); + + init_task_group.cfs_rq = (struct cfs_rq **)ptr; + ptr += nr_cpu_ids * sizeof(void **); + +#endif /* CONFIG_FAIR_GROUP_SCHED */ +#ifdef CONFIG_RT_GROUP_SCHED + init_task_group.rt_se = (struct sched_rt_entity **)ptr; + ptr += nr_cpu_ids * sizeof(void **); + + init_task_group.rt_rq = (struct rt_rq **)ptr; + ptr += nr_cpu_ids * sizeof(void **); + +#endif /* CONFIG_RT_GROUP_SCHED */ +#ifdef CONFIG_CPUMASK_OFFSTACK + for_each_possible_cpu(i) { + per_cpu(load_balance_tmpmask, i) = (void *)ptr; + ptr += cpumask_size(); + } +#endif /* CONFIG_CPUMASK_OFFSTACK */ + } + +#ifdef CONFIG_SMP + init_defrootdomain(); +#endif + + init_rt_bandwidth(&def_rt_bandwidth, + global_rt_period(), global_rt_runtime()); + +#ifdef CONFIG_RT_GROUP_SCHED + init_rt_bandwidth(&init_task_group.rt_bandwidth, + global_rt_period(), global_rt_runtime()); +#endif /* CONFIG_RT_GROUP_SCHED */ + +#ifdef CONFIG_CGROUP_SCHED + list_add(&init_task_group.list, &task_groups); + INIT_LIST_HEAD(&init_task_group.children); + +#endif /* CONFIG_CGROUP_SCHED */ + +#if defined CONFIG_FAIR_GROUP_SCHED && defined CONFIG_SMP + update_shares_data = __alloc_percpu(nr_cpu_ids * sizeof(unsigned long), + __alignof__(unsigned long)); +#endif + for_each_possible_cpu(i) { + struct rq *rq; + + rq = cpu_rq(i); + raw_spin_lock_init(&rq->lock); + rq->nr_running = 0; + rq->calc_load_active = 0; + rq->calc_load_update = jiffies + LOAD_FREQ; + init_cfs_rq(&rq->cfs, rq); + init_rt_rq(&rq->rt, rq); +#ifdef CONFIG_FAIR_GROUP_SCHED + init_task_group.shares = init_task_group_load; + INIT_LIST_HEAD(&rq->leaf_cfs_rq_list); +#ifdef CONFIG_CGROUP_SCHED + /* + * How much cpu bandwidth does init_task_group get? + * + * In case of task-groups formed thr' the cgroup filesystem, it + * gets 100% of the cpu resources in the system. This overall + * system cpu resource is divided among the tasks of + * init_task_group and its child task-groups in a fair manner, + * based on each entity's (task or task-group's) weight + * (se->load.weight). + * + * In other words, if init_task_group has 10 tasks of weight + * 1024) and two child groups A0 and A1 (of weight 1024 each), + * then A0's share of the cpu resource is: + * + * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33% + * + * We achieve this by letting init_task_group's tasks sit + * directly in rq->cfs (i.e init_task_group->se[] = NULL). + */ + init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, 1, NULL); +#endif +#endif /* CONFIG_FAIR_GROUP_SCHED */ + + rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime; +#ifdef CONFIG_RT_GROUP_SCHED + INIT_LIST_HEAD(&rq->leaf_rt_rq_list); +#ifdef CONFIG_CGROUP_SCHED + init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, 1, NULL); +#endif +#endif + + for (j = 0; j < CPU_LOAD_IDX_MAX; j++) + rq->cpu_load[j] = 0; + + rq->last_load_update_tick = jiffies; + +#ifdef CONFIG_SMP + rq->sd = NULL; + rq->rd = NULL; + rq->cpu_power = SCHED_LOAD_SCALE; + rq->post_schedule = 0; + rq->active_balance = 0; + rq->next_balance = jiffies; + rq->push_cpu = 0; + rq->cpu = i; + rq->online = 0; + rq->idle_stamp = 0; + rq->avg_idle = 2*sysctl_sched_migration_cost; + rq_attach_root(rq, &def_root_domain); +#ifdef CONFIG_NO_HZ + rq->nohz_balance_kick = 0; + init_sched_softirq_csd(&per_cpu(remote_sched_softirq_cb, i)); +#endif +#endif + init_rq_hrtick(rq); + atomic_set(&rq->nr_iowait, 0); + } + + set_load_weight(&init_task); + +#ifdef CONFIG_PREEMPT_NOTIFIERS + INIT_HLIST_HEAD(&init_task.preempt_notifiers); +#endif + +#ifdef CONFIG_SMP + open_softirq(SCHED_SOFTIRQ, run_rebalance_domains); +#endif + +#ifdef CONFIG_RT_MUTEXES + plist_head_init_raw(&init_task.pi_waiters, &init_task.pi_lock); +#endif + + /* + * The boot idle thread does lazy MMU switching as well: + */ + atomic_inc(&init_mm.mm_count); + enter_lazy_tlb(&init_mm, current); + + /* + * Make us the idle thread. Technically, schedule() should not be + * called from this thread, however somewhere below it might be, + * but because we are the idle thread, we just pick up running again + * when this runqueue becomes ""idle"". + */ + init_idle(current, smp_processor_id()); + + calc_load_update = jiffies + LOAD_FREQ; + + /* + * During early bootup we pretend to be a normal task: + */ + current->sched_class = &fair_sched_class; + + /* Allocate the nohz_cpu_mask if CONFIG_CPUMASK_OFFSTACK */ + zalloc_cpumask_var(&nohz_cpu_mask, GFP_NOWAIT); +#ifdef CONFIG_SMP +#ifdef CONFIG_NO_HZ + zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT); + alloc_cpumask_var(&nohz.grp_idle_mask, GFP_NOWAIT); + atomic_set(&nohz.load_balancer, nr_cpu_ids); + atomic_set(&nohz.first_pick_cpu, nr_cpu_ids); + atomic_set(&nohz.second_pick_cpu, nr_cpu_ids); +#endif + /* May be allocated at isolcpus cmdline parse time */ + if (cpu_isolated_map == NULL) + zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT); +#endif /* SMP */ + + perf_event_init(); + + scheduler_running = 1; +} +",0,"void __init sched_init(void) +{ + int i, j; + unsigned long alloc_size = 0, ptr; + +#ifdef CONFIG_FAIR_GROUP_SCHED + alloc_size += 2 * nr_cpu_ids * sizeof(void **); +#endif +#ifdef CONFIG_RT_GROUP_SCHED + alloc_size += 2 * nr_cpu_ids * sizeof(void **); +#endif +#ifdef CONFIG_CPUMASK_OFFSTACK + alloc_size += num_possible_cpus() * cpumask_size(); +#endif + if (alloc_size) { + ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT); + +#ifdef CONFIG_FAIR_GROUP_SCHED + init_task_group.se = (struct sched_entity **)ptr; + ptr += nr_cpu_ids * sizeof(void **); + + init_task_group.cfs_rq = (struct cfs_rq **)ptr; + ptr += nr_cpu_ids * sizeof(void **); + +#endif /* CONFIG_FAIR_GROUP_SCHED */ +#ifdef CONFIG_RT_GROUP_SCHED + init_task_group.rt_se = (struct sched_rt_entity **)ptr; + ptr += nr_cpu_ids * sizeof(void **); + + init_task_group.rt_rq = (struct rt_rq **)ptr; + ptr += nr_cpu_ids * sizeof(void **); + +#endif /* CONFIG_RT_GROUP_SCHED */ +#ifdef CONFIG_CPUMASK_OFFSTACK + for_each_possible_cpu(i) { + per_cpu(load_balance_tmpmask, i) = (void *)ptr; + ptr += cpumask_size(); + } +#endif /* CONFIG_CPUMASK_OFFSTACK */ + } + +#ifdef CONFIG_SMP + init_defrootdomain(); +#endif + + init_rt_bandwidth(&def_rt_bandwidth, + global_rt_period(), global_rt_runtime()); + +#ifdef CONFIG_RT_GROUP_SCHED + init_rt_bandwidth(&init_task_group.rt_bandwidth, + global_rt_period(), global_rt_runtime()); +#endif /* CONFIG_RT_GROUP_SCHED */ + +#ifdef CONFIG_CGROUP_SCHED + list_add(&init_task_group.list, &task_groups); + INIT_LIST_HEAD(&init_task_group.children); + +#endif /* CONFIG_CGROUP_SCHED */ + +#if defined CONFIG_FAIR_GROUP_SCHED && defined CONFIG_SMP + update_shares_data = __alloc_percpu(nr_cpu_ids * sizeof(unsigned long), + __alignof__(unsigned long)); +#endif + for_each_possible_cpu(i) { + struct rq *rq; + + rq = cpu_rq(i); + raw_spin_lock_init(&rq->lock); + rq->nr_running = 0; + rq->calc_load_active = 0; + rq->calc_load_update = jiffies + LOAD_FREQ; + init_cfs_rq(&rq->cfs, rq); + init_rt_rq(&rq->rt, rq); +#ifdef CONFIG_FAIR_GROUP_SCHED + init_task_group.shares = init_task_group_load; + INIT_LIST_HEAD(&rq->leaf_cfs_rq_list); +#ifdef CONFIG_CGROUP_SCHED + /* + * How much cpu bandwidth does init_task_group get? + * + * In case of task-groups formed thr' the cgroup filesystem, it + * gets 100% of the cpu resources in the system. This overall + * system cpu resource is divided among the tasks of + * init_task_group and its child task-groups in a fair manner, + * based on each entity's (task or task-group's) weight + * (se->load.weight). + * + * In other words, if init_task_group has 10 tasks of weight + * 1024) and two child groups A0 and A1 (of weight 1024 each), + * then A0's share of the cpu resource is: + * + * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33% + * + * We achieve this by letting init_task_group's tasks sit + * directly in rq->cfs (i.e init_task_group->se[] = NULL). + */ + init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, 1, NULL); +#endif +#endif /* CONFIG_FAIR_GROUP_SCHED */ + + rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime; +#ifdef CONFIG_RT_GROUP_SCHED + INIT_LIST_HEAD(&rq->leaf_rt_rq_list); +#ifdef CONFIG_CGROUP_SCHED + init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, 1, NULL); +#endif +#endif + + for (j = 0; j < CPU_LOAD_IDX_MAX; j++) + rq->cpu_load[j] = 0; + + rq->last_load_update_tick = jiffies; + +#ifdef CONFIG_SMP + rq->sd = NULL; + rq->rd = NULL; + rq->cpu_power = SCHED_LOAD_SCALE; + rq->post_schedule = 0; + rq->active_balance = 0; + rq->next_balance = jiffies; + rq->push_cpu = 0; + rq->cpu = i; + rq->online = 0; + rq->idle_stamp = 0; + rq->avg_idle = 2*sysctl_sched_migration_cost; + rq_attach_root(rq, &def_root_domain); +#ifdef CONFIG_NO_HZ + rq->nohz_balance_kick = 0; + init_sched_softirq_csd(&per_cpu(remote_sched_softirq_cb, i)); +#endif +#endif + init_rq_hrtick(rq); + atomic_set(&rq->nr_iowait, 0); + } + + set_load_weight(&init_task); + +#ifdef CONFIG_PREEMPT_NOTIFIERS + INIT_HLIST_HEAD(&init_task.preempt_notifiers); +#endif + +#ifdef CONFIG_SMP + open_softirq(SCHED_SOFTIRQ, run_rebalance_domains); +#endif + +#ifdef CONFIG_RT_MUTEXES + plist_head_init_raw(&init_task.pi_waiters, &init_task.pi_lock); +#endif + + /* + * The boot idle thread does lazy MMU switching as well: + */ + atomic_inc(&init_mm.mm_count); + enter_lazy_tlb(&init_mm, current); + + /* + * Make us the idle thread. Technically, schedule() should not be + * called from this thread, however somewhere below it might be, + * but because we are the idle thread, we just pick up running again + * when this runqueue becomes ""idle"". + */ + init_idle(current, smp_processor_id()); + + calc_load_update = jiffies + LOAD_FREQ; + + /* + * During early bootup we pretend to be a normal task: + */ + current->sched_class = &fair_sched_class; + + /* Allocate the nohz_cpu_mask if CONFIG_CPUMASK_OFFSTACK */ + zalloc_cpumask_var(&nohz_cpu_mask, GFP_NOWAIT); +#ifdef CONFIG_SMP +#ifdef CONFIG_NO_HZ + zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT); + alloc_cpumask_var(&nohz.grp_idle_mask, GFP_NOWAIT); + atomic_set(&nohz.load_balancer, nr_cpu_ids); + atomic_set(&nohz.first_pick_cpu, nr_cpu_ids); + atomic_set(&nohz.second_pick_cpu, nr_cpu_ids); +#endif + /* May be allocated at isolcpus cmdline parse time */ + if (cpu_isolated_map == NULL) + zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT); +#endif /* SMP */ + + perf_event_init(); + + scheduler_running = 1; +} +","@@ -641,17 +641,18 @@ static void sched_irq_time_avg_update(struct rq *rq, u64 irq_time); + + inline void update_rq_clock(struct rq *rq) + { +- if (!rq->skip_clock_update) { +- int cpu = cpu_of(rq); +- u64 irq_time; ++ int cpu = cpu_of(rq); ++ u64 irq_time; + +- rq->clock = sched_clock_cpu(cpu); +- irq_time = irq_time_cpu(cpu); +- if (rq->clock - irq_time > rq->clock_task) +- rq->clock_task = rq->clock - irq_time; ++ if (rq->skip_clock_update) ++ return; + +- sched_irq_time_avg_update(rq, irq_time); +- } ++ rq->clock = sched_clock_cpu(cpu); ++ irq_time = irq_time_cpu(cpu); ++ if (rq->clock - irq_time > rq->clock_task) ++ rq->clock_task = rq->clock - irq_time; ++ ++ sched_irq_time_avg_update(rq, irq_time); + } + + /* +@@ -2129,7 +2130,7 @@ static void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags) + * A queue event has occurred, and we're going to schedule. In + * this case, we can save a useless back to back clock update. + */ +- if (test_tsk_need_resched(rq->curr)) ++ if (rq->curr->se.on_rq && test_tsk_need_resched(rq->curr)) + rq->skip_clock_update = 1; + } + +@@ -3973,7 +3974,6 @@ static void put_prev_task(struct rq *rq, struct task_struct *prev) + { + if (prev->se.on_rq) + update_rq_clock(rq); +- rq->skip_clock_update = 0; + prev->sched_class->put_prev_task(rq, prev); + } + +@@ -4031,7 +4031,6 @@ asmlinkage void __sched schedule(void) + hrtick_clear(rq); + + raw_spin_lock_irq(&rq->lock); +- clear_tsk_need_resched(prev); + + switch_count = &prev->nivcsw; + if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) { +@@ -4063,6 +4062,8 @@ asmlinkage void __sched schedule(void) + + put_prev_task(rq, prev); + next = pick_next_task(rq); ++ clear_tsk_need_resched(prev); ++ rq->skip_clock_update = 0; + + if (likely(prev != next)) { + sched_info_switch(prev, next); +@@ -4071,6 +4072,7 @@ asmlinkage void __sched schedule(void) + rq->nr_switches++; + rq->curr = next; + ++*switch_count; ++ WARN_ON_ONCE(test_tsk_need_resched(next)); + + context_switch(rq, prev, next); /* unlocks the rq */ + /*",1559,1890,2048 +18017,"static spl_filesystem_object * spl_filesystem_object_create_type(int ht, spl_filesystem_object *source, int type, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */ +{ + spl_filesystem_object *intern; + zend_bool use_include_path = 0; + zval *arg1, *arg2; + zend_error_handling error_handling; + + zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); + + switch (source->type) { + case SPL_FS_INFO: + case SPL_FS_FILE: + break; + case SPL_FS_DIR: + if (!source->u.dir.entry.d_name[0]) { + zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, ""Could not open file""); + zend_restore_error_handling(&error_handling TSRMLS_CC); + return NULL; + } + } + + switch (type) { + case SPL_FS_INFO: + ce = ce ? ce : source->info_class; + + zend_update_class_constants(ce TSRMLS_CC); + + return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); + Z_TYPE_P(return_value) = IS_OBJECT; + + spl_filesystem_object_get_file_name(source TSRMLS_CC); + if (ce->constructor->common.scope != spl_ce_SplFileInfo) { + MAKE_STD_ZVAL(arg1); + ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1); + zend_call_method_with_1_params(&return_value, ce, &ce->constructor, ""__construct"", NULL, arg1); + zval_ptr_dtor(&arg1); + } else { + intern->file_name = estrndup(source->file_name, source->file_name_len); + intern->file_name_len = source->file_name_len; + intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC); + intern->_path = estrndup(intern->_path, intern->_path_len); + } + break; + case SPL_FS_FILE: + ce = ce ? ce : source->file_class; + + zend_update_class_constants(ce TSRMLS_CC); + + return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); + Z_TYPE_P(return_value) = IS_OBJECT; + spl_filesystem_object_get_file_name(source TSRMLS_CC); + + if (ce->constructor->common.scope != spl_ce_SplFileObject) { + MAKE_STD_ZVAL(arg1); + MAKE_STD_ZVAL(arg2); + ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1); + ZVAL_STRINGL(arg2, ""r"", 1, 1); + zend_call_method_with_2_params(&return_value, ce, &ce->constructor, ""__construct"", NULL, arg1, arg2); + zval_ptr_dtor(&arg1); + zval_ptr_dtor(&arg2); + } else { + intern->file_name = source->file_name; + intern->file_name_len = source->file_name_len; + intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC); + intern->_path = estrndup(intern->_path, intern->_path_len); + intern->u.file.open_mode = ""r""; + intern->u.file.open_mode_len = 1; + if (ht && zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""|sbr"", + &intern->u.file.open_mode, &intern->u.file.open_mode_len, + &use_include_path, &intern->u.file.zcontext) == FAILURE) { + zend_restore_error_handling(&error_handling TSRMLS_CC); + intern->u.file.open_mode = NULL; + intern->file_name = NULL; + zval_dtor(return_value); + Z_TYPE_P(return_value) = IS_NULL; + return NULL; + } + if (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == FAILURE) { + zend_restore_error_handling(&error_handling TSRMLS_CC); + zval_dtor(return_value); + Z_TYPE_P(return_value) = IS_NULL; + return NULL; + } + } + break; + case SPL_FS_DIR: + zend_restore_error_handling(&error_handling TSRMLS_CC); + zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, ""Operation not supported""); + return NULL; + } + zend_restore_error_handling(&error_handling TSRMLS_CC); + return NULL; +} /* }}} */ +",1,"static spl_filesystem_object * spl_filesystem_object_create_type(int ht, spl_filesystem_object *source, int type, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */ +{ + spl_filesystem_object *intern; + zend_bool use_include_path = 0; + zval *arg1, *arg2; + zend_error_handling error_handling; + + zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); + + switch (source->type) { + case SPL_FS_INFO: + case SPL_FS_FILE: + break; + case SPL_FS_DIR: + if (!source->u.dir.entry.d_name[0]) { + zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, ""Could not open file""); + zend_restore_error_handling(&error_handling TSRMLS_CC); + return NULL; + } + } + + switch (type) { + case SPL_FS_INFO: + ce = ce ? ce : source->info_class; + + zend_update_class_constants(ce TSRMLS_CC); + + return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); + Z_TYPE_P(return_value) = IS_OBJECT; + + spl_filesystem_object_get_file_name(source TSRMLS_CC); + if (ce->constructor->common.scope != spl_ce_SplFileInfo) { + MAKE_STD_ZVAL(arg1); + ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1); + zend_call_method_with_1_params(&return_value, ce, &ce->constructor, ""__construct"", NULL, arg1); + zval_ptr_dtor(&arg1); + } else { + intern->file_name = estrndup(source->file_name, source->file_name_len); + intern->file_name_len = source->file_name_len; + intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC); + intern->_path = estrndup(intern->_path, intern->_path_len); + } + break; + case SPL_FS_FILE: + ce = ce ? ce : source->file_class; + + zend_update_class_constants(ce TSRMLS_CC); + + return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); + Z_TYPE_P(return_value) = IS_OBJECT; + + spl_filesystem_object_get_file_name(source TSRMLS_CC); + + if (ce->constructor->common.scope != spl_ce_SplFileObject) { + MAKE_STD_ZVAL(arg1); + MAKE_STD_ZVAL(arg2); + ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1); + ZVAL_STRINGL(arg2, ""r"", 1, 1); + zend_call_method_with_2_params(&return_value, ce, &ce->constructor, ""__construct"", NULL, arg1, arg2); + zval_ptr_dtor(&arg1); + zval_ptr_dtor(&arg2); + } else { + intern->file_name = source->file_name; + intern->file_name_len = source->file_name_len; + intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC); + intern->_path = estrndup(intern->_path, intern->_path_len); + + intern->u.file.open_mode = ""r""; + intern->u.file.open_mode_len = 1; + + if (ht && zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""|sbr"", + &intern->u.file.open_mode, &intern->u.file.open_mode_len, + &use_include_path, &intern->u.file.zcontext) == FAILURE) { + zend_restore_error_handling(&error_handling TSRMLS_CC); + intern->u.file.open_mode = NULL; + intern->file_name = NULL; + zval_dtor(return_value); + Z_TYPE_P(return_value) = IS_NULL; + return NULL; + } + + if (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == FAILURE) { + zend_restore_error_handling(&error_handling TSRMLS_CC); + zval_dtor(return_value); + Z_TYPE_P(return_value) = IS_NULL; + return NULL; + } + } + break; + case SPL_FS_DIR: + zend_restore_error_handling(&error_handling TSRMLS_CC); + zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, ""Operation not supported""); + return NULL; + } + zend_restore_error_handling(&error_handling TSRMLS_CC); + return NULL; +} /* }}} */ +","@@ -79,9 +79,9 @@ static void spl_filesystem_object_free_storage(void *object TSRMLS_DC) /* {{{ */ + if (intern->oth_handler && intern->oth_handler->dtor) { + intern->oth_handler->dtor(intern TSRMLS_CC); + } +- ++ + zend_object_std_dtor(&intern->std TSRMLS_CC); +- ++ + if (intern->_path) { + efree(intern->_path); + } +@@ -98,7 +98,7 @@ static void spl_filesystem_object_free_storage(void *object TSRMLS_DC) /* {{{ */ + } + if (intern->u.dir.sub_path) { + efree(intern->u.dir.sub_path); +- } ++ } + break; + case SPL_FS_FILE: + if (intern->u.file.stream) { +@@ -134,13 +134,13 @@ static void spl_filesystem_object_free_storage(void *object TSRMLS_DC) /* {{{ */ + } /* }}} */ + + /* {{{ spl_ce_dir_object_new */ +-/* creates the object by +- - allocating memory ++/* creates the object by ++ - allocating memory + - initializing the object members + - storing the object + - setting it's handlers + +- called from ++ called from + - clone + - new + */ +@@ -313,7 +313,7 @@ static int spl_filesystem_file_open(spl_filesystem_object *intern, int use_inclu + /* avoid reference counting in debug mode, thus do it manually */ + ZVAL_RESOURCE(&intern->u.file.zresource, php_stream_get_resource_id(intern->u.file.stream)); + Z_SET_REFCOUNT(intern->u.file.zresource, 1); +- ++ + intern->u.file.delimiter = ','; + intern->u.file.enclosure = '""'; + intern->u.file.escape = '\\'; +@@ -325,7 +325,7 @@ static int spl_filesystem_file_open(spl_filesystem_object *intern, int use_inclu + + /* {{{ spl_filesystem_object_clone */ + /* Local zend_object_value creation (on stack) +- Load the 'other' object ++ Load the 'other' object + Create a new empty object (See spl_filesystem_object_new_ex) + Open the directory + Clone other members (properties) +@@ -370,7 +370,7 @@ static zend_object_value spl_filesystem_object_clone(zval *zobject TSRMLS_DC) + php_error_docref(NULL TSRMLS_CC, E_ERROR, ""An object of class %s cannot be cloned"", old_object->ce->name); + break; + } +- ++ + intern->file_class = source->file_class; + intern->info_class = source->info_class; + intern->oth = source->oth; +@@ -389,7 +389,7 @@ static zend_object_value spl_filesystem_object_clone(zval *zobject TSRMLS_DC) + void spl_filesystem_info_set_filename(spl_filesystem_object *intern, char *path, int len, int use_copy TSRMLS_DC) /* {{{ */ + { + char *p1, *p2; +- ++ + if (intern->file_name) { + efree(intern->file_name); + } +@@ -413,7 +413,7 @@ void spl_filesystem_info_set_filename(spl_filesystem_object *intern, char *path, + } else { + intern->_path_len = 0; + } +- ++ + if (intern->_path) { + efree(intern->_path); + } +@@ -459,7 +459,7 @@ static spl_filesystem_object * spl_filesystem_object_create_info(spl_filesystem_ + } else { + spl_filesystem_info_set_filename(intern, file_path, file_path_len, use_copy TSRMLS_CC); + } +- ++ + zend_restore_error_handling(&error_handling TSRMLS_CC); + return intern; + } /* }}} */ +@@ -514,7 +514,7 @@ static spl_filesystem_object * spl_filesystem_object_create_type(int ht, spl_fil + + return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); + Z_TYPE_P(return_value) = IS_OBJECT; +- ++ + spl_filesystem_object_get_file_name(source TSRMLS_CC); + + if (ce->constructor->common.scope != spl_ce_SplFileObject) { +@@ -530,12 +530,12 @@ static spl_filesystem_object * spl_filesystem_object_create_type(int ht, spl_fil + intern->file_name_len = source->file_name_len; + intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC); + intern->_path = estrndup(intern->_path, intern->_path_len); +- ++ + intern->u.file.open_mode = ""r""; + intern->u.file.open_mode_len = 1; +- +- if (ht && zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""|sbr"", +- &intern->u.file.open_mode, &intern->u.file.open_mode_len, ++ ++ if (ht && zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""|sbr"", ++ &intern->u.file.open_mode, &intern->u.file.open_mode_len, + &use_include_path, &intern->u.file.zcontext) == FAILURE) { + zend_restore_error_handling(&error_handling TSRMLS_CC); + intern->u.file.open_mode = NULL; +@@ -544,7 +544,7 @@ static spl_filesystem_object * spl_filesystem_object_create_type(int ht, spl_fil + Z_TYPE_P(return_value) = IS_NULL; + return NULL; + } +- ++ + if (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == FAILURE) { + zend_restore_error_handling(&error_handling TSRMLS_CC); + zval_dtor(return_value); +@@ -553,7 +553,7 @@ static spl_filesystem_object * spl_filesystem_object_create_type(int ht, spl_fil + } + } + break; +- case SPL_FS_DIR: ++ case SPL_FS_DIR: + zend_restore_error_handling(&error_handling TSRMLS_CC); + zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, ""Operation not supported""); + return NULL; +@@ -617,7 +617,7 @@ static HashTable* spl_filesystem_object_get_debug_info(zval *obj, int *is_temp T + if (intern->file_name) { + pnstr = spl_gen_private_prop_name(spl_ce_SplFileInfo, ""fileName"", sizeof(""fileName"")-1, &pnlen TSRMLS_CC); + spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); +- ++ + if (path_len && path_len < intern->file_name_len) { + add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->file_name + path_len + 1, intern->file_name_len - (path_len + 1), 1); + } else { +@@ -665,13 +665,13 @@ static HashTable* spl_filesystem_object_get_debug_info(zval *obj, int *is_temp T + zend_function *spl_filesystem_object_get_method_check(zval **object_ptr, char *method, int method_len, const struct _zend_literal *key TSRMLS_DC) /* {{{ */ + { + spl_filesystem_object *fsobj = zend_object_store_get_object(*object_ptr TSRMLS_CC); +- ++ + if (fsobj->u.dir.entry.d_name[0] == '\0' && fsobj->orig_path == NULL) { + method = ""_bad_state_ex""; + method_len = sizeof(""_bad_state_ex"") - 1; + key = NULL; + } +- ++ + return zend_get_std_object_handlers()->get_method(object_ptr, method, method_len, key TSRMLS_CC); + } + /* }}} */ +@@ -751,7 +751,7 @@ SPL_METHOD(DirectoryIterator, __construct) + SPL_METHOD(DirectoryIterator, rewind) + { + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -769,7 +769,7 @@ SPL_METHOD(DirectoryIterator, rewind) + SPL_METHOD(DirectoryIterator, key) + { + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -799,7 +799,7 @@ SPL_METHOD(DirectoryIterator, next) + { + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); + int skip_dots = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_SKIPDOTS); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -859,7 +859,7 @@ SPL_METHOD(DirectoryIterator, seek) + SPL_METHOD(DirectoryIterator, valid) + { + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -875,7 +875,7 @@ SPL_METHOD(SplFileInfo, getPath) + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); + char *path; + int path_len; +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -891,13 +891,13 @@ SPL_METHOD(SplFileInfo, getFilename) + { + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); + int path_len; +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } + + spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); +- ++ + if (path_len && path_len < intern->file_name_len) { + RETURN_STRINGL(intern->file_name + path_len + 1, intern->file_name_len - (path_len + 1), 1); + } else { +@@ -911,7 +911,7 @@ SPL_METHOD(SplFileInfo, getFilename) + SPL_METHOD(DirectoryIterator, getFilename) + { + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -1019,7 +1019,7 @@ SPL_METHOD(SplFileInfo, getBasename) + + RETURN_STRINGL(fname, flen, 0); + } +-/* }}}*/ ++/* }}}*/ + + /* {{{ proto string DirectoryIterator::getBasename([string $suffix]) U + Returns filename component of current dir entry */ +@@ -1029,7 +1029,7 @@ SPL_METHOD(DirectoryIterator, getBasename) + char *suffix = 0, *fname; + int slen = 0; + size_t flen; +- ++ + if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""|s"", &suffix, &slen) == FAILURE) { + return; + } +@@ -1065,7 +1065,7 @@ SPL_METHOD(SplFileInfo, getPathname) + SPL_METHOD(FilesystemIterator, key) + { + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -1084,7 +1084,7 @@ SPL_METHOD(FilesystemIterator, key) + SPL_METHOD(FilesystemIterator, current) + { + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -1107,7 +1107,7 @@ SPL_METHOD(FilesystemIterator, current) + SPL_METHOD(DirectoryIterator, isDot) + { + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -1121,8 +1121,8 @@ SPL_METHOD(DirectoryIterator, isDot) + /* zend_replace_error_handling() is used to throw exceptions in case + the constructor fails. Here we use this to ensure the object + has a valid directory resource. +- +- When the constructor gets called the object is already created ++ ++ When the constructor gets called the object is already created + by the engine, so we must only call 'additional' initializations. + */ + SPL_METHOD(SplFileInfo, __construct) +@@ -1140,11 +1140,11 @@ SPL_METHOD(SplFileInfo, __construct) + } + + intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); +- ++ + spl_filesystem_info_set_filename(intern, path, len, 1 TSRMLS_CC); + + zend_restore_error_handling(&error_handling TSRMLS_CC); +- ++ + /* intern->type = SPL_FS_INFO; already set */ + } + /* }}} */ +@@ -1249,7 +1249,7 @@ SPL_METHOD(SplFileInfo, getLinkTarget) + int ret; + char buff[MAXPATHLEN]; + zend_error_handling error_handling; +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -1297,7 +1297,7 @@ SPL_METHOD(SplFileInfo, getRealPath) + char buff[MAXPATHLEN]; + char *filename; + zend_error_handling error_handling; +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -1307,10 +1307,10 @@ SPL_METHOD(SplFileInfo, getRealPath) + if (intern->type == SPL_FS_DIR && !intern->file_name && intern->u.dir.entry.d_name[0]) { + spl_filesystem_object_get_file_name(intern TSRMLS_CC); + } +- ++ + if (intern->orig_path) { + filename = intern->orig_path; +- } else { ++ } else { + filename = intern->file_name; + } + +@@ -1348,7 +1348,7 @@ SPL_METHOD(SplFileInfo, setFileClass) + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); + zend_class_entry *ce = spl_ce_SplFileObject; + zend_error_handling error_handling; +- ++ + zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); + + if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""|C"", &ce) == SUCCESS) { +@@ -1366,7 +1366,7 @@ SPL_METHOD(SplFileInfo, setInfoClass) + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); + zend_class_entry *ce = spl_ce_SplFileInfo; + zend_error_handling error_handling; +- ++ + zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); + + if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""|C"", &ce) == SUCCESS) { +@@ -1384,7 +1384,7 @@ SPL_METHOD(SplFileInfo, getFileInfo) + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); + zend_class_entry *ce = intern->info_class; + zend_error_handling error_handling; +- ++ + zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); + + if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""|C"", &ce) == SUCCESS) { +@@ -1402,7 +1402,7 @@ SPL_METHOD(SplFileInfo, getPathInfo) + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); + zend_class_entry *ce = intern->info_class; + zend_error_handling error_handling; +- ++ + zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); + + if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""|C"", &ce) == SUCCESS) { +@@ -1463,7 +1463,7 @@ SPL_METHOD(FilesystemIterator, rewind) + SPL_METHOD(FilesystemIterator, getFlags) + { + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -1519,11 +1519,11 @@ SPL_METHOD(RecursiveDirectoryIterator, getChildren) + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); + spl_filesystem_object *subdir; + char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH; +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +- ++ + spl_filesystem_object_get_file_name(intern TSRMLS_CC); + + MAKE_STD_ZVAL(zflags); +@@ -1554,7 +1554,7 @@ SPL_METHOD(RecursiveDirectoryIterator, getChildren) + SPL_METHOD(RecursiveDirectoryIterator, getSubPath) + { + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -1575,7 +1575,7 @@ SPL_METHOD(RecursiveDirectoryIterator, getSubPathname) + char *sub_name; + int len; + char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH; +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -1611,7 +1611,7 @@ SPL_METHOD(GlobIterator, __construct) + SPL_METHOD(GlobIterator, count) + { + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -1666,7 +1666,7 @@ zend_object_iterator *spl_filesystem_dir_get_iterator(zend_class_entry *ce, zval + iterator->current = object; + } + zval_add_ref(&object); +- ++ + return (zend_object_iterator*)iterator; + } + /* }}} */ +@@ -1701,7 +1701,7 @@ static int spl_filesystem_dir_it_valid(zend_object_iterator *iter TSRMLS_DC) + static void spl_filesystem_dir_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) + { + spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; +- ++ + *data = &iterator->current; + } + /* }}} */ +@@ -1719,7 +1719,7 @@ static void spl_filesystem_dir_it_current_key(zend_object_iterator *iter, zval * + static void spl_filesystem_dir_it_move_forward(zend_object_iterator *iter TSRMLS_DC) + { + spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); +- ++ + object->u.dir.index++; + spl_filesystem_dir_read(object TSRMLS_CC); + if (object->file_name) { +@@ -1733,7 +1733,7 @@ static void spl_filesystem_dir_it_move_forward(zend_object_iterator *iter TSRMLS + static void spl_filesystem_dir_it_rewind(zend_object_iterator *iter TSRMLS_DC) + { + spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); +- ++ + object->u.dir.index = 0; + if (object->u.dir.dirp) { + php_stream_rewinddir(object->u.dir.dirp); +@@ -1803,7 +1803,7 @@ static void spl_filesystem_tree_it_move_forward(zend_object_iterator *iter TSRML + { + spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; + spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); +- ++ + object->u.dir.index++; + do { + spl_filesystem_dir_read(object TSRMLS_CC); +@@ -1824,7 +1824,7 @@ static void spl_filesystem_tree_it_rewind(zend_object_iterator *iter TSRMLS_DC) + { + spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; + spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); +- ++ + object->u.dir.index = 0; + if (object->u.dir.dirp) { + php_stream_rewinddir(object->u.dir.dirp); +@@ -1868,7 +1868,7 @@ zend_object_iterator *spl_filesystem_tree_get_iterator(zend_class_entry *ce, zva + iterator->intern.funcs = &spl_filesystem_tree_it_funcs; + } + zval_add_ref(&object); +- ++ + return (zend_object_iterator*)iterator; + } + /* }}} */ +@@ -1924,7 +1924,7 @@ static int spl_filesystem_object_cast(zval *readobj, zval *writeobj, int type TS + + /* {{{ declare method parameters */ + /* supply a name and default to call by parameter */ +-ZEND_BEGIN_ARG_INFO(arginfo_info___construct, 0) ++ZEND_BEGIN_ARG_INFO(arginfo_info___construct, 0) + ZEND_ARG_INFO(0, file_name) + ZEND_END_ARG_INFO() + +@@ -1983,11 +1983,11 @@ static const zend_function_entry spl_SplFileInfo_functions[] = { + PHP_FE_END + }; + +-ZEND_BEGIN_ARG_INFO(arginfo_dir___construct, 0) ++ZEND_BEGIN_ARG_INFO(arginfo_dir___construct, 0) + ZEND_ARG_INFO(0, path) + ZEND_END_ARG_INFO() + +-ZEND_BEGIN_ARG_INFO(arginfo_dir_it_seek, 0) ++ZEND_BEGIN_ARG_INFO(arginfo_dir_it_seek, 0) + ZEND_ARG_INFO(0, position) + ZEND_END_ARG_INFO(); + +@@ -2009,7 +2009,7 @@ static const zend_function_entry spl_DirectoryIterator_functions[] = { + PHP_FE_END + }; + +-ZEND_BEGIN_ARG_INFO_EX(arginfo_r_dir___construct, 0, 0, 1) ++ZEND_BEGIN_ARG_INFO_EX(arginfo_r_dir___construct, 0, 0, 1) + ZEND_ARG_INFO(0, path) + ZEND_ARG_INFO(0, flags) + ZEND_END_ARG_INFO() +@@ -2058,7 +2058,7 @@ static int spl_filesystem_file_read(spl_filesystem_object *intern, int silent TS + long line_add = (intern->u.file.current_line || intern->u.file.current_zval) ? 1 : 0; + + spl_filesystem_file_free_line(intern TSRMLS_CC); +- ++ + if (php_stream_eof(intern->u.file.stream)) { + if (!silent) { + zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, ""Cannot read from file %s"", intern->file_name); +@@ -2086,7 +2086,7 @@ static int spl_filesystem_file_read(spl_filesystem_object *intern, int silent TS + line_len = strcspn(buf, ""\r\n""); + buf[line_len] = '\0'; + } +- ++ + intern->u.file.current_line = buf; + intern->u.file.current_line_len = line_len; + } +@@ -2107,7 +2107,7 @@ static int spl_filesystem_file_call(spl_filesystem_object *intern, zend_function + zval ***params = (zval***)safe_emalloc(num_args, sizeof(zval**), 0); + + params[0] = &zresource_ptr; +- ++ + if (arg2) { + params[1] = &arg2; + } +@@ -2133,7 +2133,7 @@ static int spl_filesystem_file_call(spl_filesystem_object *intern, zend_function + fcic.object_ptr = NULL; + + result = zend_call_function(&fci, &fcic TSRMLS_CC); +- ++ + if (result == FAILURE) { + RETVAL_FALSE; + } else { +@@ -2159,11 +2159,11 @@ static int spl_filesystem_file_call(spl_filesystem_object *intern, zend_function + static int spl_filesystem_file_read_csv(spl_filesystem_object *intern, char delimiter, char enclosure, char escape, zval *return_value TSRMLS_DC) /* {{{ */ + { + int ret = SUCCESS; +- ++ + do { + ret = spl_filesystem_file_read(intern, 1 TSRMLS_CC); + } while (ret == SUCCESS && !intern->u.file.current_line_len && SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY)); +- ++ + if (ret == SUCCESS) { + size_t buf_len = intern->u.file.current_line_len; + char *buf = estrndup(intern->u.file.current_line, buf_len); +@@ -2237,7 +2237,7 @@ static int spl_filesystem_file_is_empty_line(spl_filesystem_object *intern TSRML + if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) + && zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 1) { + zval ** first = Z_ARRVAL_P(intern->u.file.current_zval)->pListHead->pData; +- ++ + return Z_TYPE_PP(first) == IS_STRING && Z_STRLEN_PP(first) == 0; + } + return zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 0; +@@ -2260,7 +2260,7 @@ static int spl_filesystem_file_read_line(zval * this_ptr, spl_filesystem_object + spl_filesystem_file_free_line(intern TSRMLS_CC); + ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC); + } +- ++ + return ret; + } + /* }}} */ +@@ -2294,16 +2294,16 @@ SPL_METHOD(SplFileObject, __construct) + intern->u.file.open_mode = NULL; + intern->u.file.open_mode_len = 0; + +- if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""p|sbr!"", ++ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""p|sbr!"", + &intern->file_name, &intern->file_name_len, +- &intern->u.file.open_mode, &intern->u.file.open_mode_len, +- &use_include_path, &intern->u.file.zcontext) == FAILURE) { ++ &intern->u.file.open_mode, &intern->u.file.open_mode_len, ++ &use_include_path, &intern->u.file.zcontext) == FAILURE) { + intern->u.file.open_mode = NULL; + intern->file_name = NULL; + zend_restore_error_handling(&error_handling TSRMLS_CC); + return; + } +- ++ + if (intern->u.file.open_mode == NULL) { + intern->u.file.open_mode = ""r""; + intern->u.file.open_mode_len = 1; +@@ -2368,7 +2368,7 @@ SPL_METHOD(SplTempFileObject, __construct) + intern->u.file.open_mode = ""wb""; + intern->u.file.open_mode_len = 1; + intern->u.file.zcontext = NULL; +- ++ + if (spl_filesystem_file_open(intern, 0, 0 TSRMLS_CC) == SUCCESS) { + intern->_path_len = 0; + intern->_path = estrndup("""", 0); +@@ -2381,7 +2381,7 @@ SPL_METHOD(SplTempFileObject, __construct) + SPL_METHOD(SplFileObject, rewind) + { + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -2394,7 +2394,7 @@ SPL_METHOD(SplFileObject, rewind) + SPL_METHOD(SplFileObject, eof) + { + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -2407,7 +2407,7 @@ SPL_METHOD(SplFileObject, eof) + SPL_METHOD(SplFileObject, valid) + { + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -2424,7 +2424,7 @@ SPL_METHOD(SplFileObject, valid) + SPL_METHOD(SplFileObject, fgets) + { + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -2440,7 +2440,7 @@ SPL_METHOD(SplFileObject, fgets) + SPL_METHOD(SplFileObject, current) + { + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -2461,7 +2461,7 @@ SPL_METHOD(SplFileObject, current) + SPL_METHOD(SplFileObject, key) + { + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -2478,7 +2478,7 @@ SPL_METHOD(SplFileObject, key) + SPL_METHOD(SplFileObject, next) + { + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -2530,7 +2530,7 @@ SPL_METHOD(SplFileObject, setMaxLineLen) + zend_throw_exception_ex(spl_ce_DomainException, 0 TSRMLS_CC, ""Maximum line length must be greater than or equal zero""); + return; + } +- ++ + intern->u.file.max_line_len = max_len; + } /* }}} */ + +@@ -2539,7 +2539,7 @@ SPL_METHOD(SplFileObject, setMaxLineLen) + SPL_METHOD(SplFileObject, getMaxLineLen) + { + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -2554,7 +2554,7 @@ SPL_METHOD(SplFileObject, hasChildren) + if (zend_parse_parameters_none() == FAILURE) { + return; + } +- ++ + RETURN_FALSE; + } /* }}} */ + +@@ -2585,7 +2585,7 @@ SPL_METHOD(SplFileObject, fgetcsv) + char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape; + char *delim = NULL, *enclo = NULL, *esc = NULL; + int d_len = 0, e_len = 0, esc_len = 0; +- ++ + if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""|sss"", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { + switch(ZEND_NUM_ARGS()) + { +@@ -2627,7 +2627,7 @@ SPL_METHOD(SplFileObject, fputcsv) + char *delim = NULL, *enclo = NULL, *esc = NULL; + int d_len = 0, e_len = 0, esc_len = 0, ret; + zval *fields = NULL; +- ++ + if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""a|sss"", &fields, &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { + switch(ZEND_NUM_ARGS()) + { +@@ -2670,7 +2670,7 @@ SPL_METHOD(SplFileObject, setCsvControl) + char delimiter = ',', enclosure = '""', escape='\\'; + char *delim = NULL, *enclo = NULL, *esc = NULL; + int d_len = 0, e_len = 0, esc_len = 0; +- ++ + if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""|sss"", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { + switch(ZEND_NUM_ARGS()) + { +@@ -2713,7 +2713,7 @@ SPL_METHOD(SplFileObject, getCsvControl) + char delimiter[2], enclosure[2]; + + array_init(return_value); +- ++ + delimiter[0] = intern->u.file.delimiter; + delimiter[1] = '\0'; + enclosure[0] = intern->u.file.enclosure; +@@ -2742,7 +2742,7 @@ SPL_METHOD(SplFileObject, fflush) + Return current file position */ + SPL_METHOD(SplFileObject, ftell) + { +- spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); ++ spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); + long ret = php_stream_tell(intern->u.file.stream); + + if (ret == -1) { +@@ -2872,6 +2872,10 @@ SPL_METHOD(SplFileObject, fread) + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Length parameter must be greater than 0""); + RETURN_FALSE; + } ++ if (length > INT_MAX) { ++ php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Length parameter must be no more than %d"", INT_MAX); ++ RETURN_FALSE; ++ } + + Z_STRVAL_P(return_value) = emalloc(length + 1); + Z_STRLEN_P(return_value) = php_stream_read(intern->u.file.stream, Z_STRVAL_P(return_value), length); +@@ -2892,7 +2896,7 @@ SPL_METHOD(SplFileObject, ftruncate) + { + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); + long size; +- ++ + if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""l"", &size) == FAILURE) { + return; + } +@@ -2901,7 +2905,7 @@ SPL_METHOD(SplFileObject, ftruncate) + zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, ""Can't truncate file %s"", intern->file_name); + RETURN_FALSE; + } +- ++ + RETURN_BOOL(0 == php_stream_truncate_set_size(intern->u.file.stream, size)); + } /* }}} */ + +@@ -2911,17 +2915,17 @@ SPL_METHOD(SplFileObject, seek) + { + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); + long line_pos; +- ++ + if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""l"", &line_pos) == FAILURE) { + return; + } + if (line_pos < 0) { + zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, ""Can't seek file %s to negative line %ld"", intern->file_name, line_pos); +- RETURN_FALSE; ++ RETURN_FALSE; + } +- ++ + spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC); +- ++ + while(intern->u.file.current_line_num < line_pos) { + if (spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC) == FAILURE) { + break; +@@ -2958,25 +2962,25 @@ ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fputcsv, 0, 0, 1) + ZEND_ARG_INFO(0, escape) + ZEND_END_ARG_INFO() + +-ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_flock, 0, 0, 1) ++ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_flock, 0, 0, 1) + ZEND_ARG_INFO(0, operation) + ZEND_ARG_INFO(1, wouldblock) + ZEND_END_ARG_INFO() + +-ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fseek, 0, 0, 1) ++ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fseek, 0, 0, 1) + ZEND_ARG_INFO(0, pos) + ZEND_ARG_INFO(0, whence) + ZEND_END_ARG_INFO() + +-ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fgetss, 0, 0, 0) ++ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fgetss, 0, 0, 0) + ZEND_ARG_INFO(0, allowable_tags) + ZEND_END_ARG_INFO() + +-ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fscanf, 1, 0, 1) ++ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fscanf, 1, 0, 1) + ZEND_ARG_INFO(0, format) + ZEND_END_ARG_INFO() + +-ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fwrite, 0, 0, 1) ++ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fwrite, 0, 0, 1) + ZEND_ARG_INFO(0, str) + ZEND_ARG_INFO(0, length) + ZEND_END_ARG_INFO() +@@ -2985,11 +2989,11 @@ ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fread, 0, 0, 1) + ZEND_ARG_INFO(0, length) + ZEND_END_ARG_INFO() + +-ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_ftruncate, 0, 0, 1) ++ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_ftruncate, 0, 0, 1) + ZEND_ARG_INFO(0, size) + ZEND_END_ARG_INFO() + +-ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_seek, 0, 0, 1) ++ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_seek, 0, 0, 1) + ZEND_ARG_INFO(0, line_pos) + ZEND_END_ARG_INFO() + +@@ -3078,7 +3082,7 @@ PHP_MINIT_FUNCTION(spl_directory) + + REGISTER_SPL_SUB_CLASS_EX(RecursiveDirectoryIterator, FilesystemIterator, spl_filesystem_object_new, spl_RecursiveDirectoryIterator_functions); + REGISTER_SPL_IMPLEMENTS(RecursiveDirectoryIterator, RecursiveIterator); +- ++ + memcpy(&spl_filesystem_object_check_handlers, &spl_filesystem_object_handlers, sizeof(zend_object_handlers)); + spl_filesystem_object_check_handlers.get_method = spl_filesystem_object_get_method_check; + +@@ -3095,7 +3099,7 @@ PHP_MINIT_FUNCTION(spl_directory) + REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, ""READ_AHEAD"", SPL_FILE_OBJECT_READ_AHEAD); + REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, ""SKIP_EMPTY"", SPL_FILE_OBJECT_SKIP_EMPTY); + REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, ""READ_CSV"", SPL_FILE_OBJECT_READ_CSV); +- ++ + REGISTER_SPL_SUB_CLASS_EX(SplTempFileObject, SplFileObject, spl_filesystem_object_new_check, spl_SplTempFileObject_functions); + return SUCCESS; + }",983,1314,2048 +14079,"Document::Document(const DocumentInit& initializer, + DocumentClassFlags document_classes) + : ContainerNode(nullptr, kCreateDocument), + TreeScope(*this), + ExecutionContext(V8PerIsolateData::MainThreadIsolate()), + evaluate_media_queries_on_style_recalc_(false), + pending_sheet_layout_(kNoLayoutWithPendingSheets), + frame_(initializer.GetFrame()), + dom_window_(frame_ ? frame_->DomWindow() : nullptr), + imports_controller_(initializer.ImportsController()), + context_document_(initializer.ContextDocument()), + context_features_(ContextFeatures::DefaultSwitch()), + well_formed_(false), + printing_(kNotPrinting), + compatibility_mode_(kNoQuirksMode), + compatibility_mode_locked_(false), + has_autofocused_(false), + last_focus_type_(kWebFocusTypeNone), + had_keyboard_event_(false), + clear_focused_element_timer_( + GetTaskRunner(TaskType::kInternalUserInteraction), + this, + &Document::ClearFocusedElementTimerFired), + dom_tree_version_(++global_tree_version_), + style_version_(0), + listener_types_(0), + mutation_observer_types_(0), + visited_link_state_(VisitedLinkState::Create(*this)), + visually_ordered_(false), + ready_state_(kComplete), + parsing_state_(kFinishedParsing), + contains_validity_style_rules_(false), + contains_plugins_(false), + ignore_destructive_write_count_(0), + throw_on_dynamic_markup_insertion_count_(0), + ignore_opens_during_unload_count_(0), + markers_(MakeGarbageCollected(*this)), + update_focus_appearance_timer_( + GetTaskRunner(TaskType::kInternalUserInteraction), + this, + &Document::UpdateFocusAppearanceTimerFired), + css_target_(nullptr), + was_discarded_(false), + load_event_progress_(kLoadEventCompleted), + is_freezing_in_progress_(false), + start_time_(CurrentTime()), + script_runner_(ScriptRunner::Create(this)), + xml_version_(""1.0""), + xml_standalone_(kStandaloneUnspecified), + has_xml_declaration_(0), + design_mode_(false), + is_running_exec_command_(false), + has_annotated_regions_(false), + annotated_regions_dirty_(false), + document_classes_(document_classes), + is_view_source_(false), + saw_elements_in_known_namespaces_(false), + is_srcdoc_document_(initializer.IsSrcdocDocument()), + is_mobile_document_(false), + layout_view_(nullptr), + has_fullscreen_supplement_(false), + load_event_delay_count_(0), + load_event_delay_timer_(GetTaskRunner(TaskType::kNetworking), + this, + &Document::LoadEventDelayTimerFired), + plugin_loading_timer_(GetTaskRunner(TaskType::kInternalLoading), + this, + &Document::PluginLoadingTimerFired), + document_timing_(*this), + write_recursion_is_too_deep_(false), + write_recursion_depth_(0), + registration_context_(initializer.RegistrationContext(this)), + element_data_cache_clear_timer_( + GetTaskRunner(TaskType::kInternalUserInteraction), + this, + &Document::ElementDataCacheClearTimerFired), + timeline_(DocumentTimeline::Create(this)), + pending_animations_(MakeGarbageCollected(*this)), + worklet_animation_controller_( + MakeGarbageCollected(this)), + template_document_host_(nullptr), + did_associate_form_controls_timer_( + GetTaskRunner(TaskType::kInternalLoading), + this, + &Document::DidAssociateFormControlsTimerFired), + timers_(GetTaskRunner(TaskType::kJavascriptTimer)), + has_viewport_units_(false), + parser_sync_policy_(kAllowAsynchronousParsing), + node_count_(0), + logged_field_edit_(false), + secure_context_state_(SecureContextState::kUnknown), + ukm_source_id_(ukm::UkmRecorder::GetNewSourceID()), +#if DCHECK_IS_ON() + slot_assignment_recalc_forbidden_recursion_depth_(0), +#endif + needs_to_record_ukm_outlive_time_(false), + viewport_data_(MakeGarbageCollected(*this)), + agent_cluster_id_(base::UnguessableToken::Create()), + parsed_feature_policies_( + static_cast(mojom::FeaturePolicyFeature::kMaxValue) + 1), + potentially_violated_features_( + static_cast(mojom::FeaturePolicyFeature::kMaxValue) + 1U), + isolated_world_csp_map_( + MakeGarbageCollected< + HeapHashMap>>()) { + if (frame_) { + DCHECK(frame_->GetPage()); + ProvideContextFeaturesToDocumentFrom(*this, *frame_->GetPage()); + fetcher_ = FrameFetchContext::CreateFetcherForCommittedDocument( + *frame_->Loader().GetDocumentLoader(), *this); + CustomElementRegistry* registry = + frame_->DomWindow() ? frame_->DomWindow()->MaybeCustomElements() + : nullptr; + if (registry && registration_context_) + registry->Entangle(registration_context_); + } else if (imports_controller_) { + fetcher_ = FrameFetchContext::CreateFetcherForImportedDocument(this); + } else { + fetcher_ = MakeGarbageCollected(ResourceFetcherInit( + *MakeGarbageCollected(), + &FetchContext::NullInstance(), GetTaskRunner(TaskType::kNetworking))); + } + DCHECK(fetcher_); + + root_scroller_controller_ = RootScrollerController::Create(*this); + + if (initializer.ShouldSetURL()) { + SetURL(initializer.Url()); + } else { + UpdateBaseURL(); + } + + InitSecurityContext(initializer); + if (frame_) + frame_->Client()->DidSetFramePolicyHeaders(GetSandboxFlags(), {}); + + InitDNSPrefetch(); + + InstanceCounters::IncrementCounter(InstanceCounters::kDocumentCounter); + + lifecycle_.AdvanceTo(DocumentLifecycle::kInactive); + + style_engine_ = StyleEngine::Create(*this); + + DCHECK(!ParentDocument() || !ParentDocument()->IsContextPaused()); + +#ifndef NDEBUG + liveDocumentSet().insert(this); +#endif +} +",0,"Document::Document(const DocumentInit& initializer, + DocumentClassFlags document_classes) + : ContainerNode(nullptr, kCreateDocument), + TreeScope(*this), + ExecutionContext(V8PerIsolateData::MainThreadIsolate()), + evaluate_media_queries_on_style_recalc_(false), + pending_sheet_layout_(kNoLayoutWithPendingSheets), + frame_(initializer.GetFrame()), + dom_window_(frame_ ? frame_->DomWindow() : nullptr), + imports_controller_(initializer.ImportsController()), + context_document_(initializer.ContextDocument()), + context_features_(ContextFeatures::DefaultSwitch()), + well_formed_(false), + printing_(kNotPrinting), + compatibility_mode_(kNoQuirksMode), + compatibility_mode_locked_(false), + has_autofocused_(false), + last_focus_type_(kWebFocusTypeNone), + had_keyboard_event_(false), + clear_focused_element_timer_( + GetTaskRunner(TaskType::kInternalUserInteraction), + this, + &Document::ClearFocusedElementTimerFired), + dom_tree_version_(++global_tree_version_), + style_version_(0), + listener_types_(0), + mutation_observer_types_(0), + visited_link_state_(VisitedLinkState::Create(*this)), + visually_ordered_(false), + ready_state_(kComplete), + parsing_state_(kFinishedParsing), + contains_validity_style_rules_(false), + contains_plugins_(false), + ignore_destructive_write_count_(0), + throw_on_dynamic_markup_insertion_count_(0), + ignore_opens_during_unload_count_(0), + markers_(MakeGarbageCollected(*this)), + update_focus_appearance_timer_( + GetTaskRunner(TaskType::kInternalUserInteraction), + this, + &Document::UpdateFocusAppearanceTimerFired), + css_target_(nullptr), + was_discarded_(false), + load_event_progress_(kLoadEventCompleted), + is_freezing_in_progress_(false), + start_time_(CurrentTime()), + script_runner_(ScriptRunner::Create(this)), + xml_version_(""1.0""), + xml_standalone_(kStandaloneUnspecified), + has_xml_declaration_(0), + design_mode_(false), + is_running_exec_command_(false), + has_annotated_regions_(false), + annotated_regions_dirty_(false), + document_classes_(document_classes), + is_view_source_(false), + saw_elements_in_known_namespaces_(false), + is_srcdoc_document_(initializer.IsSrcdocDocument()), + is_mobile_document_(false), + layout_view_(nullptr), + has_fullscreen_supplement_(false), + load_event_delay_count_(0), + load_event_delay_timer_(GetTaskRunner(TaskType::kNetworking), + this, + &Document::LoadEventDelayTimerFired), + plugin_loading_timer_(GetTaskRunner(TaskType::kInternalLoading), + this, + &Document::PluginLoadingTimerFired), + document_timing_(*this), + write_recursion_is_too_deep_(false), + write_recursion_depth_(0), + registration_context_(initializer.RegistrationContext(this)), + element_data_cache_clear_timer_( + GetTaskRunner(TaskType::kInternalUserInteraction), + this, + &Document::ElementDataCacheClearTimerFired), + timeline_(DocumentTimeline::Create(this)), + pending_animations_(MakeGarbageCollected(*this)), + worklet_animation_controller_( + MakeGarbageCollected(this)), + template_document_host_(nullptr), + did_associate_form_controls_timer_( + GetTaskRunner(TaskType::kInternalLoading), + this, + &Document::DidAssociateFormControlsTimerFired), + timers_(GetTaskRunner(TaskType::kJavascriptTimer)), + has_viewport_units_(false), + parser_sync_policy_(kAllowAsynchronousParsing), + node_count_(0), + logged_field_edit_(false), + secure_context_state_(SecureContextState::kUnknown), + ukm_source_id_(ukm::UkmRecorder::GetNewSourceID()), +#if DCHECK_IS_ON() + slot_assignment_recalc_forbidden_recursion_depth_(0), +#endif + needs_to_record_ukm_outlive_time_(false), + viewport_data_(MakeGarbageCollected(*this)), + agent_cluster_id_(base::UnguessableToken::Create()), + parsed_feature_policies_( + static_cast(mojom::FeaturePolicyFeature::kMaxValue) + 1), + potentially_violated_features_( + static_cast(mojom::FeaturePolicyFeature::kMaxValue) + 1U), + isolated_world_csp_map_( + MakeGarbageCollected< + HeapHashMap>>()) { + if (frame_) { + DCHECK(frame_->GetPage()); + ProvideContextFeaturesToDocumentFrom(*this, *frame_->GetPage()); + fetcher_ = FrameFetchContext::CreateFetcherForCommittedDocument( + *frame_->Loader().GetDocumentLoader(), *this); + CustomElementRegistry* registry = + frame_->DomWindow() ? frame_->DomWindow()->MaybeCustomElements() + : nullptr; + if (registry && registration_context_) + registry->Entangle(registration_context_); + } else if (imports_controller_) { + fetcher_ = FrameFetchContext::CreateFetcherForImportedDocument(this); + } else { + fetcher_ = MakeGarbageCollected(ResourceFetcherInit( + *MakeGarbageCollected(), + &FetchContext::NullInstance(), GetTaskRunner(TaskType::kNetworking))); + } + DCHECK(fetcher_); + + root_scroller_controller_ = RootScrollerController::Create(*this); + + if (initializer.ShouldSetURL()) { + SetURL(initializer.Url()); + } else { + UpdateBaseURL(); + } + + InitSecurityContext(initializer); + if (frame_) + frame_->Client()->DidSetFramePolicyHeaders(GetSandboxFlags(), {}); + + InitDNSPrefetch(); + + InstanceCounters::IncrementCounter(InstanceCounters::kDocumentCounter); + + lifecycle_.AdvanceTo(DocumentLifecycle::kInactive); + + style_engine_ = StyleEngine::Create(*this); + + DCHECK(!ParentDocument() || !ParentDocument()->IsContextPaused()); + +#ifndef NDEBUG + liveDocumentSet().insert(this); +#endif +} +","@@ -4657,8 +4657,10 @@ bool Document::SetFocusedElement(Element* new_focused_element, + if (IsRootEditableElement(*new_focused_element) && + !AcceptsEditingFocus(*new_focused_element)) { + // delegate blocks focus change +- focus_change_blocked = true; +- goto SetFocusedElementDone; ++ UpdateStyleAndLayoutTree(); ++ if (LocalFrame* frame = GetFrame()) ++ frame->Selection().DidChangeFocus(); ++ return false; + } + // Set focus on the new node + focused_element_ = new_focused_element; +@@ -4673,18 +4675,13 @@ bool Document::SetFocusedElement(Element* new_focused_element, + + // Element::setFocused for frames can dispatch events. + if (focused_element_ != new_focused_element) { +- focus_change_blocked = true; +- goto SetFocusedElementDone; ++ UpdateStyleAndLayoutTree(); ++ if (LocalFrame* frame = GetFrame()) ++ frame->Selection().DidChangeFocus(); ++ return false; + } + CancelFocusAppearanceUpdate(); + EnsurePaintLocationDataValidForNode(focused_element_); +- // UpdateStyleAndLayout can call SetFocusedElement (through +- // InvokeFragmentAnchor called in Document::LayoutUpdated) and clear +- // focused_element_. +- if (focused_element_ != new_focused_element) { +- focus_change_blocked = true; +- goto SetFocusedElementDone; +- } + focused_element_->UpdateFocusAppearanceWithOptions( + params.selection_behavior, params.options); + +@@ -4698,8 +4695,10 @@ bool Document::SetFocusedElement(Element* new_focused_element, + + if (focused_element_ != new_focused_element) { + // handler shifted focus +- focus_change_blocked = true; +- goto SetFocusedElementDone; ++ UpdateStyleAndLayoutTree(); ++ if (LocalFrame* frame = GetFrame()) ++ frame->Selection().DidChangeFocus(); ++ return false; + } + // DOM level 3 bubbling focus event. + focused_element_->DispatchFocusInEvent(event_type_names::kFocusin, +@@ -4708,8 +4707,10 @@ bool Document::SetFocusedElement(Element* new_focused_element, + + if (focused_element_ != new_focused_element) { + // handler shifted focus +- focus_change_blocked = true; +- goto SetFocusedElementDone; ++ UpdateStyleAndLayoutTree(); ++ if (LocalFrame* frame = GetFrame()) ++ frame->Selection().DidChangeFocus(); ++ return false; + } + + // For DOM level 2 compatibility. +@@ -4721,8 +4722,10 @@ bool Document::SetFocusedElement(Element* new_focused_element, + + if (focused_element_ != new_focused_element) { + // handler shifted focus +- focus_change_blocked = true; +- goto SetFocusedElementDone; ++ UpdateStyleAndLayoutTree(); ++ if (LocalFrame* frame = GetFrame()) ++ frame->Selection().DidChangeFocus(); ++ return false; + } + } + } +@@ -4741,7 +4744,6 @@ bool Document::SetFocusedElement(Element* new_focused_element, + focused_element_.Get()); + } + +-SetFocusedElementDone: + UpdateStyleAndLayoutTree(); + if (LocalFrame* frame = GetFrame()) + frame->Selection().DidChangeFocus();",1310,1641,2048 +4475,"struct rtable *__ip_route_output_key(struct net *net, struct flowi4 *fl4) +{ + struct net_device *dev_out = NULL; + __u8 tos = RT_FL_TOS(fl4); + unsigned int flags = 0; + struct fib_result res; + struct rtable *rth; + int orig_oif; + + res.tclassid = 0; + res.fi = NULL; + res.table = NULL; + + orig_oif = fl4->flowi4_oif; + + fl4->flowi4_iif = LOOPBACK_IFINDEX; + fl4->flowi4_tos = tos & IPTOS_RT_MASK; + fl4->flowi4_scope = ((tos & RTO_ONLINK) ? + RT_SCOPE_LINK : RT_SCOPE_UNIVERSE); + + rcu_read_lock(); + if (fl4->saddr) { + rth = ERR_PTR(-EINVAL); + if (ipv4_is_multicast(fl4->saddr) || + ipv4_is_lbcast(fl4->saddr) || + ipv4_is_zeronet(fl4->saddr)) + goto out; + + /* I removed check for oif == dev_out->oif here. + It was wrong for two reasons: + 1. ip_dev_find(net, saddr) can return wrong iface, if saddr + is assigned to multiple interfaces. + 2. Moreover, we are allowed to send packets with saddr + of another iface. --ANK + */ + + if (fl4->flowi4_oif == 0 && + (ipv4_is_multicast(fl4->daddr) || + ipv4_is_lbcast(fl4->daddr))) { + /* It is equivalent to inet_addr_type(saddr) == RTN_LOCAL */ + dev_out = __ip_dev_find(net, fl4->saddr, false); + if (dev_out == NULL) + goto out; + + /* Special hack: user can direct multicasts + and limited broadcast via necessary interface + without fiddling with IP_MULTICAST_IF or IP_PKTINFO. + This hack is not just for fun, it allows + vic,vat and friends to work. + They bind socket to loopback, set ttl to zero + and expect that it will work. + From the viewpoint of routing cache they are broken, + because we are not allowed to build multicast path + with loopback source addr (look, routing cache + cannot know, that ttl is zero, so that packet + will not leave this host and route is valid). + Luckily, this hack is good workaround. + */ + + fl4->flowi4_oif = dev_out->ifindex; + goto make_route; + } + + if (!(fl4->flowi4_flags & FLOWI_FLAG_ANYSRC)) { + /* It is equivalent to inet_addr_type(saddr) == RTN_LOCAL */ + if (!__ip_dev_find(net, fl4->saddr, false)) + goto out; + } + } + + + if (fl4->flowi4_oif) { + dev_out = dev_get_by_index_rcu(net, fl4->flowi4_oif); + rth = ERR_PTR(-ENODEV); + if (dev_out == NULL) + goto out; + + /* RACE: Check return value of inet_select_addr instead. */ + if (!(dev_out->flags & IFF_UP) || !__in_dev_get_rcu(dev_out)) { + rth = ERR_PTR(-ENETUNREACH); + goto out; + } + if (ipv4_is_local_multicast(fl4->daddr) || + ipv4_is_lbcast(fl4->daddr)) { + if (!fl4->saddr) + fl4->saddr = inet_select_addr(dev_out, 0, + RT_SCOPE_LINK); + goto make_route; + } + if (!fl4->saddr) { + if (ipv4_is_multicast(fl4->daddr)) + fl4->saddr = inet_select_addr(dev_out, 0, + fl4->flowi4_scope); + else if (!fl4->daddr) + fl4->saddr = inet_select_addr(dev_out, 0, + RT_SCOPE_HOST); + } + } + + if (!fl4->daddr) { + fl4->daddr = fl4->saddr; + if (!fl4->daddr) + fl4->daddr = fl4->saddr = htonl(INADDR_LOOPBACK); + dev_out = net->loopback_dev; + fl4->flowi4_oif = LOOPBACK_IFINDEX; + res.type = RTN_LOCAL; + flags |= RTCF_LOCAL; + goto make_route; + } + + if (fib_lookup(net, fl4, &res)) { + res.fi = NULL; + res.table = NULL; + if (fl4->flowi4_oif) { + /* Apparently, routing tables are wrong. Assume, + that the destination is on link. + + WHY? DW. + Because we are allowed to send to iface + even if it has NO routes and NO assigned + addresses. When oif is specified, routing + tables are looked up with only one purpose: + to catch if destination is gatewayed, rather than + direct. Moreover, if MSG_DONTROUTE is set, + we send packet, ignoring both routing tables + and ifaddr state. --ANK + + + We could make it even if oif is unknown, + likely IPv6, but we do not. + */ + + if (fl4->saddr == 0) + fl4->saddr = inet_select_addr(dev_out, 0, + RT_SCOPE_LINK); + res.type = RTN_UNICAST; + goto make_route; + } + rth = ERR_PTR(-ENETUNREACH); + goto out; + } + + if (res.type == RTN_LOCAL) { + if (!fl4->saddr) { + if (res.fi->fib_prefsrc) + fl4->saddr = res.fi->fib_prefsrc; + else + fl4->saddr = fl4->daddr; + } + dev_out = net->loopback_dev; + fl4->flowi4_oif = dev_out->ifindex; + flags |= RTCF_LOCAL; + goto make_route; + } + +#ifdef CONFIG_IP_ROUTE_MULTIPATH + if (res.fi->fib_nhs > 1 && fl4->flowi4_oif == 0) + fib_select_multipath(&res); + else +#endif + if (!res.prefixlen && + res.table->tb_num_default > 1 && + res.type == RTN_UNICAST && !fl4->flowi4_oif) + fib_select_default(&res); + + if (!fl4->saddr) + fl4->saddr = FIB_RES_PREFSRC(net, res); + + dev_out = FIB_RES_DEV(res); + fl4->flowi4_oif = dev_out->ifindex; + + +make_route: + rth = __mkroute_output(&res, fl4, orig_oif, dev_out, flags); + +out: + rcu_read_unlock(); + return rth; +} +",0,"struct rtable *__ip_route_output_key(struct net *net, struct flowi4 *fl4) +{ + struct net_device *dev_out = NULL; + __u8 tos = RT_FL_TOS(fl4); + unsigned int flags = 0; + struct fib_result res; + struct rtable *rth; + int orig_oif; + + res.tclassid = 0; + res.fi = NULL; + res.table = NULL; + + orig_oif = fl4->flowi4_oif; + + fl4->flowi4_iif = LOOPBACK_IFINDEX; + fl4->flowi4_tos = tos & IPTOS_RT_MASK; + fl4->flowi4_scope = ((tos & RTO_ONLINK) ? + RT_SCOPE_LINK : RT_SCOPE_UNIVERSE); + + rcu_read_lock(); + if (fl4->saddr) { + rth = ERR_PTR(-EINVAL); + if (ipv4_is_multicast(fl4->saddr) || + ipv4_is_lbcast(fl4->saddr) || + ipv4_is_zeronet(fl4->saddr)) + goto out; + + /* I removed check for oif == dev_out->oif here. + It was wrong for two reasons: + 1. ip_dev_find(net, saddr) can return wrong iface, if saddr + is assigned to multiple interfaces. + 2. Moreover, we are allowed to send packets with saddr + of another iface. --ANK + */ + + if (fl4->flowi4_oif == 0 && + (ipv4_is_multicast(fl4->daddr) || + ipv4_is_lbcast(fl4->daddr))) { + /* It is equivalent to inet_addr_type(saddr) == RTN_LOCAL */ + dev_out = __ip_dev_find(net, fl4->saddr, false); + if (dev_out == NULL) + goto out; + + /* Special hack: user can direct multicasts + and limited broadcast via necessary interface + without fiddling with IP_MULTICAST_IF or IP_PKTINFO. + This hack is not just for fun, it allows + vic,vat and friends to work. + They bind socket to loopback, set ttl to zero + and expect that it will work. + From the viewpoint of routing cache they are broken, + because we are not allowed to build multicast path + with loopback source addr (look, routing cache + cannot know, that ttl is zero, so that packet + will not leave this host and route is valid). + Luckily, this hack is good workaround. + */ + + fl4->flowi4_oif = dev_out->ifindex; + goto make_route; + } + + if (!(fl4->flowi4_flags & FLOWI_FLAG_ANYSRC)) { + /* It is equivalent to inet_addr_type(saddr) == RTN_LOCAL */ + if (!__ip_dev_find(net, fl4->saddr, false)) + goto out; + } + } + + + if (fl4->flowi4_oif) { + dev_out = dev_get_by_index_rcu(net, fl4->flowi4_oif); + rth = ERR_PTR(-ENODEV); + if (dev_out == NULL) + goto out; + + /* RACE: Check return value of inet_select_addr instead. */ + if (!(dev_out->flags & IFF_UP) || !__in_dev_get_rcu(dev_out)) { + rth = ERR_PTR(-ENETUNREACH); + goto out; + } + if (ipv4_is_local_multicast(fl4->daddr) || + ipv4_is_lbcast(fl4->daddr)) { + if (!fl4->saddr) + fl4->saddr = inet_select_addr(dev_out, 0, + RT_SCOPE_LINK); + goto make_route; + } + if (!fl4->saddr) { + if (ipv4_is_multicast(fl4->daddr)) + fl4->saddr = inet_select_addr(dev_out, 0, + fl4->flowi4_scope); + else if (!fl4->daddr) + fl4->saddr = inet_select_addr(dev_out, 0, + RT_SCOPE_HOST); + } + } + + if (!fl4->daddr) { + fl4->daddr = fl4->saddr; + if (!fl4->daddr) + fl4->daddr = fl4->saddr = htonl(INADDR_LOOPBACK); + dev_out = net->loopback_dev; + fl4->flowi4_oif = LOOPBACK_IFINDEX; + res.type = RTN_LOCAL; + flags |= RTCF_LOCAL; + goto make_route; + } + + if (fib_lookup(net, fl4, &res)) { + res.fi = NULL; + res.table = NULL; + if (fl4->flowi4_oif) { + /* Apparently, routing tables are wrong. Assume, + that the destination is on link. + + WHY? DW. + Because we are allowed to send to iface + even if it has NO routes and NO assigned + addresses. When oif is specified, routing + tables are looked up with only one purpose: + to catch if destination is gatewayed, rather than + direct. Moreover, if MSG_DONTROUTE is set, + we send packet, ignoring both routing tables + and ifaddr state. --ANK + + + We could make it even if oif is unknown, + likely IPv6, but we do not. + */ + + if (fl4->saddr == 0) + fl4->saddr = inet_select_addr(dev_out, 0, + RT_SCOPE_LINK); + res.type = RTN_UNICAST; + goto make_route; + } + rth = ERR_PTR(-ENETUNREACH); + goto out; + } + + if (res.type == RTN_LOCAL) { + if (!fl4->saddr) { + if (res.fi->fib_prefsrc) + fl4->saddr = res.fi->fib_prefsrc; + else + fl4->saddr = fl4->daddr; + } + dev_out = net->loopback_dev; + fl4->flowi4_oif = dev_out->ifindex; + flags |= RTCF_LOCAL; + goto make_route; + } + +#ifdef CONFIG_IP_ROUTE_MULTIPATH + if (res.fi->fib_nhs > 1 && fl4->flowi4_oif == 0) + fib_select_multipath(&res); + else +#endif + if (!res.prefixlen && + res.table->tb_num_default > 1 && + res.type == RTN_UNICAST && !fl4->flowi4_oif) + fib_select_default(&res); + + if (!fl4->saddr) + fl4->saddr = FIB_RES_PREFSRC(net, res); + + dev_out = FIB_RES_DEV(res); + fl4->flowi4_oif = dev_out->ifindex; + + +make_route: + rth = __mkroute_output(&res, fl4, orig_oif, dev_out, flags); + +out: + rcu_read_unlock(); + return rth; +} +","@@ -1554,11 +1554,10 @@ static int __mkroute_input(struct sk_buff *skb, + + do_cache = res->fi && !itag; + if (out_dev == in_dev && err && IN_DEV_TX_REDIRECTS(out_dev) && ++ skb->protocol == htons(ETH_P_IP) && + (IN_DEV_SHARED_MEDIA(out_dev) || +- inet_addr_onlink(out_dev, saddr, FIB_RES_GW(*res)))) { +- flags |= RTCF_DOREDIRECT; +- do_cache = false; +- } ++ inet_addr_onlink(out_dev, saddr, FIB_RES_GW(*res)))) ++ IPCB(skb)->flags |= IPSKB_DOREDIRECT; + + if (skb->protocol != htons(ETH_P_IP)) { + /* Not IP (i.e. ARP). Do not create route, if it is +@@ -2303,6 +2302,8 @@ static int rt_fill_info(struct net *net, __be32 dst, __be32 src, + r->rtm_flags = (rt->rt_flags & ~0xFFFF) | RTM_F_CLONED; + if (rt->rt_flags & RTCF_NOTIFY) + r->rtm_flags |= RTM_F_NOTIFY; ++ if (IPCB(skb)->flags & IPSKB_DOREDIRECT) ++ r->rtm_flags |= RTCF_DOREDIRECT; + + if (nla_put_be32(skb, RTA_DST, dst)) + goto nla_put_failure;",1539,1870,2048 +7474,"static int server_socket(const char *interface, + int port, + enum network_transport transport, + FILE *portnumber_file) { + int sfd; + struct linger ling = {0, 0}; + struct addrinfo *ai; + struct addrinfo *next; + struct addrinfo hints = { .ai_flags = AI_PASSIVE, + .ai_family = AF_UNSPEC }; + char port_buf[NI_MAXSERV]; + int error; + int success = 0; + int flags =1; + + hints.ai_socktype = IS_UDP(transport) ? SOCK_DGRAM : SOCK_STREAM; + + if (port == -1) { + port = 0; + } + snprintf(port_buf, sizeof(port_buf), ""%d"", port); + error= getaddrinfo(interface, port_buf, &hints, &ai); + if (error != 0) { + if (error != EAI_SYSTEM) + fprintf(stderr, ""getaddrinfo(): %s\n"", gai_strerror(error)); + else + perror(""getaddrinfo()""); + return 1; + } + + for (next= ai; next; next= next->ai_next) { + conn *listen_conn_add; + if ((sfd = new_socket(next)) == -1) { + /* getaddrinfo can return ""junk"" addresses, + * we make sure at least one works before erroring. + */ + if (errno == EMFILE) { + /* ...unless we're out of fds */ + perror(""server_socket""); + exit(EX_OSERR); + } + continue; + } + +#ifdef IPV6_V6ONLY + if (next->ai_family == AF_INET6) { + error = setsockopt(sfd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &flags, sizeof(flags)); + if (error != 0) { + perror(""setsockopt""); + close(sfd); + continue; + } + } +#endif + + setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags)); + if (IS_UDP(transport)) { + maximize_sndbuf(sfd); + } else { + error = setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags)); + if (error != 0) + perror(""setsockopt""); + + error = setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling)); + if (error != 0) + perror(""setsockopt""); + + error = setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (void *)&flags, sizeof(flags)); + if (error != 0) + perror(""setsockopt""); + } + + if (bind(sfd, next->ai_addr, next->ai_addrlen) == -1) { + if (errno != EADDRINUSE) { + perror(""bind()""); + close(sfd); + freeaddrinfo(ai); + return 1; + } + close(sfd); + continue; + } else { + success++; + if (!IS_UDP(transport) && listen(sfd, settings.backlog) == -1) { + perror(""listen()""); + close(sfd); + freeaddrinfo(ai); + return 1; + } + if (portnumber_file != NULL && + (next->ai_addr->sa_family == AF_INET || + next->ai_addr->sa_family == AF_INET6)) { + union { + struct sockaddr_in in; + struct sockaddr_in6 in6; + } my_sockaddr; + socklen_t len = sizeof(my_sockaddr); + if (getsockname(sfd, (struct sockaddr*)&my_sockaddr, &len)==0) { + if (next->ai_addr->sa_family == AF_INET) { + fprintf(portnumber_file, ""%s INET: %u\n"", + IS_UDP(transport) ? ""UDP"" : ""TCP"", + ntohs(my_sockaddr.in.sin_port)); + } else { + fprintf(portnumber_file, ""%s INET6: %u\n"", + IS_UDP(transport) ? ""UDP"" : ""TCP"", + ntohs(my_sockaddr.in6.sin6_port)); + } + } + } + } + + if (IS_UDP(transport)) { + int c; + + for (c = 0; c < settings.num_threads_per_udp; c++) { + /* Allocate one UDP file descriptor per worker thread; + * this allows ""stats conns"" to separately list multiple + * parallel UDP requests in progress. + * + * The dispatch code round-robins new connection requests + * among threads, so this is guaranteed to assign one + * FD to each thread. + */ + int per_thread_fd = c ? dup(sfd) : sfd; + dispatch_conn_new(per_thread_fd, conn_read, + EV_READ | EV_PERSIST, + UDP_READ_BUFFER_SIZE, transport); + } + } else { + if (!(listen_conn_add = conn_new(sfd, conn_listening, + EV_READ | EV_PERSIST, 1, + transport, main_base))) { + fprintf(stderr, ""failed to create listening connection\n""); + exit(EXIT_FAILURE); + } + listen_conn_add->next = listen_conn; + listen_conn = listen_conn_add; + } + } + + freeaddrinfo(ai); + + /* Return zero iff we detected no errors in starting up connections */ + return success == 0; +} +",0,"static int server_socket(const char *interface, + int port, + enum network_transport transport, + FILE *portnumber_file) { + int sfd; + struct linger ling = {0, 0}; + struct addrinfo *ai; + struct addrinfo *next; + struct addrinfo hints = { .ai_flags = AI_PASSIVE, + .ai_family = AF_UNSPEC }; + char port_buf[NI_MAXSERV]; + int error; + int success = 0; + int flags =1; + + hints.ai_socktype = IS_UDP(transport) ? SOCK_DGRAM : SOCK_STREAM; + + if (port == -1) { + port = 0; + } + snprintf(port_buf, sizeof(port_buf), ""%d"", port); + error= getaddrinfo(interface, port_buf, &hints, &ai); + if (error != 0) { + if (error != EAI_SYSTEM) + fprintf(stderr, ""getaddrinfo(): %s\n"", gai_strerror(error)); + else + perror(""getaddrinfo()""); + return 1; + } + + for (next= ai; next; next= next->ai_next) { + conn *listen_conn_add; + if ((sfd = new_socket(next)) == -1) { + /* getaddrinfo can return ""junk"" addresses, + * we make sure at least one works before erroring. + */ + if (errno == EMFILE) { + /* ...unless we're out of fds */ + perror(""server_socket""); + exit(EX_OSERR); + } + continue; + } + +#ifdef IPV6_V6ONLY + if (next->ai_family == AF_INET6) { + error = setsockopt(sfd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &flags, sizeof(flags)); + if (error != 0) { + perror(""setsockopt""); + close(sfd); + continue; + } + } +#endif + + setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags)); + if (IS_UDP(transport)) { + maximize_sndbuf(sfd); + } else { + error = setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags)); + if (error != 0) + perror(""setsockopt""); + + error = setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling)); + if (error != 0) + perror(""setsockopt""); + + error = setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (void *)&flags, sizeof(flags)); + if (error != 0) + perror(""setsockopt""); + } + + if (bind(sfd, next->ai_addr, next->ai_addrlen) == -1) { + if (errno != EADDRINUSE) { + perror(""bind()""); + close(sfd); + freeaddrinfo(ai); + return 1; + } + close(sfd); + continue; + } else { + success++; + if (!IS_UDP(transport) && listen(sfd, settings.backlog) == -1) { + perror(""listen()""); + close(sfd); + freeaddrinfo(ai); + return 1; + } + if (portnumber_file != NULL && + (next->ai_addr->sa_family == AF_INET || + next->ai_addr->sa_family == AF_INET6)) { + union { + struct sockaddr_in in; + struct sockaddr_in6 in6; + } my_sockaddr; + socklen_t len = sizeof(my_sockaddr); + if (getsockname(sfd, (struct sockaddr*)&my_sockaddr, &len)==0) { + if (next->ai_addr->sa_family == AF_INET) { + fprintf(portnumber_file, ""%s INET: %u\n"", + IS_UDP(transport) ? ""UDP"" : ""TCP"", + ntohs(my_sockaddr.in.sin_port)); + } else { + fprintf(portnumber_file, ""%s INET6: %u\n"", + IS_UDP(transport) ? ""UDP"" : ""TCP"", + ntohs(my_sockaddr.in6.sin6_port)); + } + } + } + } + + if (IS_UDP(transport)) { + int c; + + for (c = 0; c < settings.num_threads_per_udp; c++) { + /* Allocate one UDP file descriptor per worker thread; + * this allows ""stats conns"" to separately list multiple + * parallel UDP requests in progress. + * + * The dispatch code round-robins new connection requests + * among threads, so this is guaranteed to assign one + * FD to each thread. + */ + int per_thread_fd = c ? dup(sfd) : sfd; + dispatch_conn_new(per_thread_fd, conn_read, + EV_READ | EV_PERSIST, + UDP_READ_BUFFER_SIZE, transport); + } + } else { + if (!(listen_conn_add = conn_new(sfd, conn_listening, + EV_READ | EV_PERSIST, 1, + transport, main_base))) { + fprintf(stderr, ""failed to create listening connection\n""); + exit(EXIT_FAILURE); + } + listen_conn_add->next = listen_conn; + listen_conn = listen_conn_add; + } + } + + freeaddrinfo(ai); + + /* Return zero iff we detected no errors in starting up connections */ + return success == 0; +} +","@@ -3249,6 +3249,16 @@ static inline int make_ascii_get_suffix(char *suffix, item *it, bool return_cas) + return (p - suffix) + 2; + } + ++#define IT_REFCOUNT_LIMIT 60000 ++static inline item* limited_get(char *key, size_t nkey, conn *c) { ++ item *it = item_get(key, nkey, c, DO_UPDATE); ++ if (it && it->refcount > IT_REFCOUNT_LIMIT) { ++ item_remove(it); ++ it = NULL; ++ } ++ return it; ++} ++ + /* ntokens is overwritten here... shrug.. */ + static inline void process_get_command(conn *c, token_t *tokens, size_t ntokens, bool return_cas) { + char *key; +@@ -3273,7 +3283,7 @@ static inline void process_get_command(conn *c, token_t *tokens, size_t ntokens, + return; + } + +- it = item_get(key, nkey, c, DO_UPDATE); ++ it = limited_get(key, nkey, c); + if (settings.detail_enabled) { + stats_prefix_record_get(key, nkey, NULL != it); + }",1135,1466,2048 +17798,"SplashPath *Splash::makeDashedPath(SplashPath *path) { + SplashPath *dPath; + SplashCoord lineDashTotal; + SplashCoord lineDashStartPhase, lineDashDist, segLen; + SplashCoord x0, y0, x1, y1, xa, ya; + GBool lineDashStartOn, lineDashOn, newPath; + int lineDashStartIdx, lineDashIdx; + int i, j, k; + + lineDashTotal = 0; + for (i = 0; i < state->lineDashLength; ++i) { + lineDashTotal += state->lineDash[i]; + } + if (lineDashTotal == 0) { + return new SplashPath(); + } + lineDashStartPhase = state->lineDashPhase; + i = splashFloor(lineDashStartPhase / lineDashTotal); + lineDashStartPhase -= (SplashCoord)i * lineDashTotal; + lineDashStartOn = gTrue; + lineDashStartIdx = 0; + if (lineDashStartPhase > 0) { + while (lineDashStartPhase >= state->lineDash[lineDashStartIdx]) { + lineDashStartOn = !lineDashStartOn; + lineDashStartPhase -= state->lineDash[lineDashStartIdx]; + ++lineDashStartIdx; + } + } + + dPath = new SplashPath(); + while (i < path->length) { + + for (j = i; + j < path->length - 1 && !(path->flags[j] & splashPathLast); + ++j) ; + + lineDashOn = lineDashStartOn; + lineDashIdx = lineDashStartIdx; + lineDashDist = state->lineDash[lineDashIdx] - lineDashStartPhase; + + newPath = gTrue; + for (k = i; k < j; ++k) { + + x0 = path->pts[k].x; + y0 = path->pts[k].y; + x1 = path->pts[k+1].x; + y1 = path->pts[k+1].y; + segLen = splashDist(x0, y0, x1, y1); + + while (segLen > 0) { + + if (lineDashDist >= segLen) { + if (lineDashOn) { + if (newPath) { + dPath->moveTo(x0, y0); + newPath = gFalse; + } + dPath->lineTo(x1, y1); + } + lineDashDist -= segLen; + segLen = 0; + + } else { + xa = x0 + (lineDashDist / segLen) * (x1 - x0); + ya = y0 + (lineDashDist / segLen) * (y1 - y0); + if (lineDashOn) { + if (newPath) { + dPath->moveTo(x0, y0); + newPath = gFalse; + } + dPath->lineTo(xa, ya); + } + x0 = xa; + y0 = ya; + segLen -= lineDashDist; + lineDashDist = 0; + } + + if (lineDashDist <= 0) { + lineDashOn = !lineDashOn; + if (++lineDashIdx == state->lineDashLength) { + lineDashIdx = 0; + } + lineDashDist = state->lineDash[lineDashIdx]; + newPath = gTrue; + } + } + } + i = j + 1; + } + + if (dPath->length == 0) { + GBool allSame = gTrue; + for (int i = 0; allSame && i < path->length - 1; ++i) { + allSame = path->pts[i].x == path->pts[i + 1].x && path->pts[i].y == path->pts[i + 1].y; + } + if (allSame) { + x0 = path->pts[0].x; + y0 = path->pts[0].y; + dPath->moveTo(x0, y0); + dPath->lineTo(x0, y0); + } + } + + return dPath; +} +",1,"SplashPath *Splash::makeDashedPath(SplashPath *path) { + SplashPath *dPath; + SplashCoord lineDashTotal; + SplashCoord lineDashStartPhase, lineDashDist, segLen; + SplashCoord x0, y0, x1, y1, xa, ya; + GBool lineDashStartOn, lineDashOn, newPath; + int lineDashStartIdx, lineDashIdx; + int i, j, k; + + lineDashTotal = 0; + for (i = 0; i < state->lineDashLength; ++i) { + lineDashTotal += state->lineDash[i]; + } + if (lineDashTotal == 0) { + return new SplashPath(); + } + lineDashStartPhase = state->lineDashPhase; + i = splashFloor(lineDashStartPhase / lineDashTotal); + lineDashStartPhase -= (SplashCoord)i * lineDashTotal; + lineDashStartOn = gTrue; + lineDashStartIdx = 0; + if (lineDashStartPhase > 0) { + while (lineDashStartIdx < state->lineDashLength && lineDashStartPhase >= state->lineDash[lineDashStartIdx]) { + lineDashStartOn = !lineDashStartOn; + lineDashStartPhase -= state->lineDash[lineDashStartIdx]; + ++lineDashStartIdx; + } + if (unlikely(lineDashStartIdx == state->lineDashLength)) { + return new SplashPath(); + } + } + + dPath = new SplashPath(); + while (i < path->length) { + + for (j = i; + j < path->length - 1 && !(path->flags[j] & splashPathLast); + ++j) ; + + lineDashOn = lineDashStartOn; + lineDashIdx = lineDashStartIdx; + lineDashDist = state->lineDash[lineDashIdx] - lineDashStartPhase; + + newPath = gTrue; + for (k = i; k < j; ++k) { + + x0 = path->pts[k].x; + y0 = path->pts[k].y; + x1 = path->pts[k+1].x; + y1 = path->pts[k+1].y; + segLen = splashDist(x0, y0, x1, y1); + + while (segLen > 0) { + + if (lineDashDist >= segLen) { + if (lineDashOn) { + if (newPath) { + dPath->moveTo(x0, y0); + newPath = gFalse; + } + dPath->lineTo(x1, y1); + } + lineDashDist -= segLen; + segLen = 0; + + } else { + xa = x0 + (lineDashDist / segLen) * (x1 - x0); + ya = y0 + (lineDashDist / segLen) * (y1 - y0); + if (lineDashOn) { + if (newPath) { + dPath->moveTo(x0, y0); + newPath = gFalse; + } + dPath->lineTo(xa, ya); + } + x0 = xa; + y0 = ya; + segLen -= lineDashDist; + lineDashDist = 0; + } + + if (lineDashDist <= 0) { + lineDashOn = !lineDashOn; + if (++lineDashIdx == state->lineDashLength) { + lineDashIdx = 0; + } + lineDashDist = state->lineDash[lineDashIdx]; + newPath = gTrue; + } + } + } + i = j + 1; + } + + if (dPath->length == 0) { + GBool allSame = gTrue; + for (int i = 0; allSame && i < path->length - 1; ++i) { + allSame = path->pts[i].x == path->pts[i + 1].x && path->pts[i].y == path->pts[i + 1].y; + } + if (allSame) { + x0 = path->pts[0].x; + y0 = path->pts[0].y; + dPath->moveTo(x0, y0); + dPath->lineTo(x0, y0); + } + } + + return dPath; +} +","@@ -2252,11 +2252,14 @@ SplashPath *Splash::makeDashedPath(SplashPath *path) { + lineDashStartOn = gTrue; + lineDashStartIdx = 0; + if (lineDashStartPhase > 0) { +- while (lineDashStartPhase >= state->lineDash[lineDashStartIdx]) { ++ while (lineDashStartIdx < state->lineDashLength && lineDashStartPhase >= state->lineDash[lineDashStartIdx]) { + lineDashStartOn = !lineDashStartOn; + lineDashStartPhase -= state->lineDash[lineDashStartIdx]; + ++lineDashStartIdx; + } ++ if (unlikely(lineDashStartIdx == state->lineDashLength)) { ++ return new SplashPath(); ++ } + } + + dPath = new SplashPath();",904,1235,2048 +9183,"GF_Err video_sample_entry_Size(GF_Box *s) +{ + GF_Err e; + GF_MPEGVisualSampleEntryBox *ptr = (GF_MPEGVisualSampleEntryBox *)s; + + gf_isom_video_sample_entry_size((GF_VisualSampleEntryBox *)s); + + if (ptr->esd) { + e = gf_isom_box_size((GF_Box *)ptr->esd); + if (e) return e; + ptr->size += ptr->esd->size; + } else if (ptr->cfg_3gpp) { + e = gf_isom_box_size((GF_Box *)ptr->cfg_3gpp); + if (e) return e; + ptr->size += ptr->cfg_3gpp->size; + } else { + switch (ptr->type) { + case GF_ISOM_BOX_TYPE_AVC1: + case GF_ISOM_BOX_TYPE_AVC2: + case GF_ISOM_BOX_TYPE_AVC3: + case GF_ISOM_BOX_TYPE_AVC4: + case GF_ISOM_BOX_TYPE_SVC1: + case GF_ISOM_BOX_TYPE_SVC2: + case GF_ISOM_BOX_TYPE_MVC1: + case GF_ISOM_BOX_TYPE_MVC2: + if (!ptr->avc_config && !ptr->svc_config && !ptr->mvc_config) + return GF_ISOM_INVALID_FILE; + break; + case GF_ISOM_BOX_TYPE_VP08: + case GF_ISOM_BOX_TYPE_VP09: + if (!ptr->vp_config) { + return GF_ISOM_INVALID_FILE; + } + break; + case GF_ISOM_BOX_TYPE_AV01: + if (!ptr->av1_config) { + return GF_ISOM_INVALID_FILE; + } + break; + case GF_ISOM_BOX_TYPE_HVC1: + case GF_ISOM_BOX_TYPE_HEV1: + case GF_ISOM_BOX_TYPE_HVC2: + case GF_ISOM_BOX_TYPE_HEV2: + case GF_ISOM_BOX_TYPE_LHV1: + case GF_ISOM_BOX_TYPE_LHE1: + if (!ptr->hevc_config && !ptr->lhvc_config) { + return GF_ISOM_INVALID_FILE; + } + break; + default: + break; + } + + if (ptr->hevc_config && ptr->hevc_config->config) { + e = gf_isom_box_size((GF_Box *)ptr->hevc_config); + if (e) return e; + ptr->size += ptr->hevc_config->size; + } + + if (ptr->avc_config && ptr->avc_config->config) { + e = gf_isom_box_size((GF_Box *) ptr->avc_config); + if (e) return e; + ptr->size += ptr->avc_config->size; + } + + if (ptr->svc_config && ptr->svc_config->config) { + e = gf_isom_box_size((GF_Box *) ptr->svc_config); + if (e) return e; + ptr->size += ptr->svc_config->size; + } + + if (ptr->mvc_config && ptr->mvc_config->config) { + e = gf_isom_box_size((GF_Box *) ptr->mvc_config); + if (e) return e; + ptr->size += ptr->mvc_config->size; + } + + if (ptr->lhvc_config && ptr->lhvc_config->config) { + e = gf_isom_box_size((GF_Box *) ptr->lhvc_config); + if (e) return e; + ptr->size += ptr->lhvc_config->size; + } + + if (ptr->av1_config && ptr->av1_config->config) { + e = gf_isom_box_size((GF_Box *)ptr->av1_config); + if (e) return e; + ptr->size += ptr->av1_config->size; + } + + if (ptr->vp_config && ptr->vp_config->config) { + e = gf_isom_box_size((GF_Box *)ptr->vp_config); + if (e) return e; + ptr->size += ptr->vp_config->size; + } + + if (ptr->ipod_ext) { + e = gf_isom_box_size((GF_Box *) ptr->ipod_ext); + if (e) return e; + ptr->size += ptr->ipod_ext->size; + } + if (ptr->descr) { + e = gf_isom_box_size((GF_Box *) ptr->descr); + if (e) return e; + ptr->size += ptr->descr->size; + } + } + if (ptr->pasp) { + e = gf_isom_box_size((GF_Box *)ptr->pasp); + if (e) return e; + ptr->size += ptr->pasp->size; + } + if (ptr->clap) { + e = gf_isom_box_size((GF_Box *)ptr->clap); + if (e) return e; + ptr->size += ptr->clap->size; + } + if (ptr->ccst) { + e = gf_isom_box_size((GF_Box *)ptr->ccst); + if (e) return e; + ptr->size += ptr->ccst->size; + } + if (ptr->auxi) { + e = gf_isom_box_size((GF_Box *)ptr->auxi); + if (e) return e; + ptr->size += ptr->auxi->size; + } + if (ptr->rvcc) { + e = gf_isom_box_size((GF_Box *)ptr->rvcc); + if (e) return e; + ptr->size += ptr->rvcc->size; + } + if (ptr->rinf) { + e = gf_isom_box_size((GF_Box *)ptr->rinf); + if (e) return e; + ptr->size += ptr->rinf->size; + } + return gf_isom_box_array_size(s, ptr->protections); +} +",0,"GF_Err video_sample_entry_Size(GF_Box *s) +{ + GF_Err e; + GF_MPEGVisualSampleEntryBox *ptr = (GF_MPEGVisualSampleEntryBox *)s; + + gf_isom_video_sample_entry_size((GF_VisualSampleEntryBox *)s); + + if (ptr->esd) { + e = gf_isom_box_size((GF_Box *)ptr->esd); + if (e) return e; + ptr->size += ptr->esd->size; + } else if (ptr->cfg_3gpp) { + e = gf_isom_box_size((GF_Box *)ptr->cfg_3gpp); + if (e) return e; + ptr->size += ptr->cfg_3gpp->size; + } else { + switch (ptr->type) { + case GF_ISOM_BOX_TYPE_AVC1: + case GF_ISOM_BOX_TYPE_AVC2: + case GF_ISOM_BOX_TYPE_AVC3: + case GF_ISOM_BOX_TYPE_AVC4: + case GF_ISOM_BOX_TYPE_SVC1: + case GF_ISOM_BOX_TYPE_SVC2: + case GF_ISOM_BOX_TYPE_MVC1: + case GF_ISOM_BOX_TYPE_MVC2: + if (!ptr->avc_config && !ptr->svc_config && !ptr->mvc_config) + return GF_ISOM_INVALID_FILE; + break; + case GF_ISOM_BOX_TYPE_VP08: + case GF_ISOM_BOX_TYPE_VP09: + if (!ptr->vp_config) { + return GF_ISOM_INVALID_FILE; + } + break; + case GF_ISOM_BOX_TYPE_AV01: + if (!ptr->av1_config) { + return GF_ISOM_INVALID_FILE; + } + break; + case GF_ISOM_BOX_TYPE_HVC1: + case GF_ISOM_BOX_TYPE_HEV1: + case GF_ISOM_BOX_TYPE_HVC2: + case GF_ISOM_BOX_TYPE_HEV2: + case GF_ISOM_BOX_TYPE_LHV1: + case GF_ISOM_BOX_TYPE_LHE1: + if (!ptr->hevc_config && !ptr->lhvc_config) { + return GF_ISOM_INVALID_FILE; + } + break; + default: + break; + } + + if (ptr->hevc_config && ptr->hevc_config->config) { + e = gf_isom_box_size((GF_Box *)ptr->hevc_config); + if (e) return e; + ptr->size += ptr->hevc_config->size; + } + + if (ptr->avc_config && ptr->avc_config->config) { + e = gf_isom_box_size((GF_Box *) ptr->avc_config); + if (e) return e; + ptr->size += ptr->avc_config->size; + } + + if (ptr->svc_config && ptr->svc_config->config) { + e = gf_isom_box_size((GF_Box *) ptr->svc_config); + if (e) return e; + ptr->size += ptr->svc_config->size; + } + + if (ptr->mvc_config && ptr->mvc_config->config) { + e = gf_isom_box_size((GF_Box *) ptr->mvc_config); + if (e) return e; + ptr->size += ptr->mvc_config->size; + } + + if (ptr->lhvc_config && ptr->lhvc_config->config) { + e = gf_isom_box_size((GF_Box *) ptr->lhvc_config); + if (e) return e; + ptr->size += ptr->lhvc_config->size; + } + + if (ptr->av1_config && ptr->av1_config->config) { + e = gf_isom_box_size((GF_Box *)ptr->av1_config); + if (e) return e; + ptr->size += ptr->av1_config->size; + } + + if (ptr->vp_config && ptr->vp_config->config) { + e = gf_isom_box_size((GF_Box *)ptr->vp_config); + if (e) return e; + ptr->size += ptr->vp_config->size; + } + + if (ptr->ipod_ext) { + e = gf_isom_box_size((GF_Box *) ptr->ipod_ext); + if (e) return e; + ptr->size += ptr->ipod_ext->size; + } + if (ptr->descr) { + e = gf_isom_box_size((GF_Box *) ptr->descr); + if (e) return e; + ptr->size += ptr->descr->size; + } + } + if (ptr->pasp) { + e = gf_isom_box_size((GF_Box *)ptr->pasp); + if (e) return e; + ptr->size += ptr->pasp->size; + } + if (ptr->clap) { + e = gf_isom_box_size((GF_Box *)ptr->clap); + if (e) return e; + ptr->size += ptr->clap->size; + } + if (ptr->ccst) { + e = gf_isom_box_size((GF_Box *)ptr->ccst); + if (e) return e; + ptr->size += ptr->ccst->size; + } + if (ptr->auxi) { + e = gf_isom_box_size((GF_Box *)ptr->auxi); + if (e) return e; + ptr->size += ptr->auxi->size; + } + if (ptr->rvcc) { + e = gf_isom_box_size((GF_Box *)ptr->rvcc); + if (e) return e; + ptr->size += ptr->rvcc->size; + } + if (ptr->rinf) { + e = gf_isom_box_size((GF_Box *)ptr->rinf); + if (e) return e; + ptr->size += ptr->rinf->size; + } + return gf_isom_box_array_size(s, ptr->protections); +} +","@@ -931,8 +931,11 @@ GF_Err dinf_Read(GF_Box *s, GF_BitStream *bs) + return e; + } + if (!((GF_DataInformationBox *)s)->dref) { ++ GF_Box* dref; + GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, (""[iso file] Missing dref box in dinf\n"")); +- ((GF_DataInformationBox *)s)->dref = (GF_DataReferenceBox *)gf_isom_box_new(GF_ISOM_BOX_TYPE_DREF); ++ dref = gf_isom_box_new(GF_ISOM_BOX_TYPE_DREF); ++ ((GF_DataInformationBox *)s)->dref = (GF_DataReferenceBox *)dref; ++ gf_isom_box_add_for_dump_mode(s, dref); + } + return GF_OK; + }",1289,1620,2048 +476,"PHP_FUNCTION(openssl_pkey_get_details) +{ + zval *key; + EVP_PKEY *pkey; + BIO *out; + unsigned int pbio_len; + char *pbio; + zend_long ktype; + + if (zend_parse_parameters(ZEND_NUM_ARGS(), ""r"", &key) == FAILURE) { + return; + } + if ((pkey = (EVP_PKEY *)zend_fetch_resource(Z_RES_P(key), ""OpenSSL key"", le_key)) == NULL) { + RETURN_FALSE; + } + out = BIO_new(BIO_s_mem()); + if (!PEM_write_bio_PUBKEY(out, pkey)) { + BIO_free(out); + php_openssl_store_errors(); + RETURN_FALSE; + } + pbio_len = BIO_get_mem_data(out, &pbio); + + array_init(return_value); + add_assoc_long(return_value, ""bits"", EVP_PKEY_bits(pkey)); + add_assoc_stringl(return_value, ""key"", pbio, pbio_len); + /*TODO: Use the real values once the openssl constants are used + * See the enum at the top of this file + */ + switch (EVP_PKEY_base_id(pkey)) { + case EVP_PKEY_RSA: + case EVP_PKEY_RSA2: + { + RSA *rsa = EVP_PKEY_get0_RSA(pkey); + ktype = OPENSSL_KEYTYPE_RSA; + + if (rsa != NULL) { + zval z_rsa; + const BIGNUM *n, *e, *d, *p, *q, *dmp1, *dmq1, *iqmp; + + RSA_get0_key(rsa, &n, &e, &d); + RSA_get0_factors(rsa, &p, &q); + RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp); + + array_init(&z_rsa); + OPENSSL_PKEY_GET_BN(z_rsa, n); + OPENSSL_PKEY_GET_BN(z_rsa, e); + OPENSSL_PKEY_GET_BN(z_rsa, d); + OPENSSL_PKEY_GET_BN(z_rsa, p); + OPENSSL_PKEY_GET_BN(z_rsa, q); + OPENSSL_PKEY_GET_BN(z_rsa, dmp1); + OPENSSL_PKEY_GET_BN(z_rsa, dmq1); + OPENSSL_PKEY_GET_BN(z_rsa, iqmp); + add_assoc_zval(return_value, ""rsa"", &z_rsa); + } + } + break; + case EVP_PKEY_DSA: + case EVP_PKEY_DSA2: + case EVP_PKEY_DSA3: + case EVP_PKEY_DSA4: + { + DSA *dsa = EVP_PKEY_get0_DSA(pkey); + ktype = OPENSSL_KEYTYPE_DSA; + + if (dsa != NULL) { + zval z_dsa; + const BIGNUM *p, *q, *g, *priv_key, *pub_key; + + DSA_get0_pqg(dsa, &p, &q, &g); + DSA_get0_key(dsa, &pub_key, &priv_key); + + array_init(&z_dsa); + OPENSSL_PKEY_GET_BN(z_dsa, p); + OPENSSL_PKEY_GET_BN(z_dsa, q); + OPENSSL_PKEY_GET_BN(z_dsa, g); + OPENSSL_PKEY_GET_BN(z_dsa, priv_key); + OPENSSL_PKEY_GET_BN(z_dsa, pub_key); + add_assoc_zval(return_value, ""dsa"", &z_dsa); + } + } + break; + case EVP_PKEY_DH: + { + DH *dh = EVP_PKEY_get0_DH(pkey); + ktype = OPENSSL_KEYTYPE_DH; + + if (dh != NULL) { + zval z_dh; + const BIGNUM *p, *q, *g, *priv_key, *pub_key; + + DH_get0_pqg(dh, &p, &q, &g); + DH_get0_key(dh, &pub_key, &priv_key); + + array_init(&z_dh); + OPENSSL_PKEY_GET_BN(z_dh, p); + OPENSSL_PKEY_GET_BN(z_dh, g); + OPENSSL_PKEY_GET_BN(z_dh, priv_key); + OPENSSL_PKEY_GET_BN(z_dh, pub_key); + add_assoc_zval(return_value, ""dh"", &z_dh); + } + } + break; +#ifdef HAVE_EVP_PKEY_EC + case EVP_PKEY_EC: + ktype = OPENSSL_KEYTYPE_EC; + if (EVP_PKEY_get0_EC_KEY(pkey) != NULL) { + zval ec; + const EC_GROUP *ec_group; + const EC_POINT *pub; + int nid; + char *crv_sn; + ASN1_OBJECT *obj; + char oir_buf[80]; + const EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(pkey); + BIGNUM *x = BN_new(); + BIGNUM *y = BN_new(); + const BIGNUM *d; + + ec_group = EC_KEY_get0_group(ec_key); + + nid = EC_GROUP_get_curve_name(ec_group); + if (nid == NID_undef) { + break; + } + array_init(&ec); + + crv_sn = (char*) OBJ_nid2sn(nid); + if (crv_sn != NULL) { + add_assoc_string(&ec, ""curve_name"", crv_sn); + } + + obj = OBJ_nid2obj(nid); + if (obj != NULL) { + int oir_len = OBJ_obj2txt(oir_buf, sizeof(oir_buf), obj, 1); + add_assoc_stringl(&ec, ""curve_oid"", (char*) oir_buf, oir_len); + ASN1_OBJECT_free(obj); + } + + pub = EC_KEY_get0_public_key(ec_key); + + if (EC_POINT_get_affine_coordinates_GFp(ec_group, pub, x, y, NULL)) { + OPENSSL_GET_BN(ec, x, x); + OPENSSL_GET_BN(ec, y, y); + } else { + php_openssl_store_errors(); + } + + if ((d = EC_KEY_get0_private_key(EVP_PKEY_get0_EC_KEY(pkey))) != NULL) { + OPENSSL_GET_BN(ec, d, d); + } + + add_assoc_zval(return_value, ""ec"", &ec); + + BN_free(x); + BN_free(y); + } + break; +#endif + default: + ktype = -1; + break; + } + add_assoc_long(return_value, ""type"", ktype); + + BIO_free(out); +} +",0,"PHP_FUNCTION(openssl_pkey_get_details) +{ + zval *key; + EVP_PKEY *pkey; + BIO *out; + unsigned int pbio_len; + char *pbio; + zend_long ktype; + + if (zend_parse_parameters(ZEND_NUM_ARGS(), ""r"", &key) == FAILURE) { + return; + } + if ((pkey = (EVP_PKEY *)zend_fetch_resource(Z_RES_P(key), ""OpenSSL key"", le_key)) == NULL) { + RETURN_FALSE; + } + out = BIO_new(BIO_s_mem()); + if (!PEM_write_bio_PUBKEY(out, pkey)) { + BIO_free(out); + php_openssl_store_errors(); + RETURN_FALSE; + } + pbio_len = BIO_get_mem_data(out, &pbio); + + array_init(return_value); + add_assoc_long(return_value, ""bits"", EVP_PKEY_bits(pkey)); + add_assoc_stringl(return_value, ""key"", pbio, pbio_len); + /*TODO: Use the real values once the openssl constants are used + * See the enum at the top of this file + */ + switch (EVP_PKEY_base_id(pkey)) { + case EVP_PKEY_RSA: + case EVP_PKEY_RSA2: + { + RSA *rsa = EVP_PKEY_get0_RSA(pkey); + ktype = OPENSSL_KEYTYPE_RSA; + + if (rsa != NULL) { + zval z_rsa; + const BIGNUM *n, *e, *d, *p, *q, *dmp1, *dmq1, *iqmp; + + RSA_get0_key(rsa, &n, &e, &d); + RSA_get0_factors(rsa, &p, &q); + RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp); + + array_init(&z_rsa); + OPENSSL_PKEY_GET_BN(z_rsa, n); + OPENSSL_PKEY_GET_BN(z_rsa, e); + OPENSSL_PKEY_GET_BN(z_rsa, d); + OPENSSL_PKEY_GET_BN(z_rsa, p); + OPENSSL_PKEY_GET_BN(z_rsa, q); + OPENSSL_PKEY_GET_BN(z_rsa, dmp1); + OPENSSL_PKEY_GET_BN(z_rsa, dmq1); + OPENSSL_PKEY_GET_BN(z_rsa, iqmp); + add_assoc_zval(return_value, ""rsa"", &z_rsa); + } + } + break; + case EVP_PKEY_DSA: + case EVP_PKEY_DSA2: + case EVP_PKEY_DSA3: + case EVP_PKEY_DSA4: + { + DSA *dsa = EVP_PKEY_get0_DSA(pkey); + ktype = OPENSSL_KEYTYPE_DSA; + + if (dsa != NULL) { + zval z_dsa; + const BIGNUM *p, *q, *g, *priv_key, *pub_key; + + DSA_get0_pqg(dsa, &p, &q, &g); + DSA_get0_key(dsa, &pub_key, &priv_key); + + array_init(&z_dsa); + OPENSSL_PKEY_GET_BN(z_dsa, p); + OPENSSL_PKEY_GET_BN(z_dsa, q); + OPENSSL_PKEY_GET_BN(z_dsa, g); + OPENSSL_PKEY_GET_BN(z_dsa, priv_key); + OPENSSL_PKEY_GET_BN(z_dsa, pub_key); + add_assoc_zval(return_value, ""dsa"", &z_dsa); + } + } + break; + case EVP_PKEY_DH: + { + DH *dh = EVP_PKEY_get0_DH(pkey); + ktype = OPENSSL_KEYTYPE_DH; + + if (dh != NULL) { + zval z_dh; + const BIGNUM *p, *q, *g, *priv_key, *pub_key; + + DH_get0_pqg(dh, &p, &q, &g); + DH_get0_key(dh, &pub_key, &priv_key); + + array_init(&z_dh); + OPENSSL_PKEY_GET_BN(z_dh, p); + OPENSSL_PKEY_GET_BN(z_dh, g); + OPENSSL_PKEY_GET_BN(z_dh, priv_key); + OPENSSL_PKEY_GET_BN(z_dh, pub_key); + add_assoc_zval(return_value, ""dh"", &z_dh); + } + } + break; +#ifdef HAVE_EVP_PKEY_EC + case EVP_PKEY_EC: + ktype = OPENSSL_KEYTYPE_EC; + if (EVP_PKEY_get0_EC_KEY(pkey) != NULL) { + zval ec; + const EC_GROUP *ec_group; + const EC_POINT *pub; + int nid; + char *crv_sn; + ASN1_OBJECT *obj; + char oir_buf[80]; + const EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(pkey); + BIGNUM *x = BN_new(); + BIGNUM *y = BN_new(); + const BIGNUM *d; + + ec_group = EC_KEY_get0_group(ec_key); + + nid = EC_GROUP_get_curve_name(ec_group); + if (nid == NID_undef) { + break; + } + array_init(&ec); + + crv_sn = (char*) OBJ_nid2sn(nid); + if (crv_sn != NULL) { + add_assoc_string(&ec, ""curve_name"", crv_sn); + } + + obj = OBJ_nid2obj(nid); + if (obj != NULL) { + int oir_len = OBJ_obj2txt(oir_buf, sizeof(oir_buf), obj, 1); + add_assoc_stringl(&ec, ""curve_oid"", (char*) oir_buf, oir_len); + ASN1_OBJECT_free(obj); + } + + pub = EC_KEY_get0_public_key(ec_key); + + if (EC_POINT_get_affine_coordinates_GFp(ec_group, pub, x, y, NULL)) { + OPENSSL_GET_BN(ec, x, x); + OPENSSL_GET_BN(ec, y, y); + } else { + php_openssl_store_errors(); + } + + if ((d = EC_KEY_get0_private_key(EVP_PKEY_get0_EC_KEY(pkey))) != NULL) { + OPENSSL_GET_BN(ec, d, d); + } + + add_assoc_zval(return_value, ""ec"", &ec); + + BN_free(x); + BN_free(y); + } + break; +#endif + default: + ktype = -1; + break; + } + add_assoc_long(return_value, ""type"", ktype); + + BIO_free(out); +} +","@@ -5926,7 +5926,7 @@ PHP_FUNCTION(openssl_seal) + buf = emalloc(data_len + EVP_CIPHER_CTX_block_size(ctx)); + EVP_CIPHER_CTX_cleanup(ctx); + +- if (!EVP_SealInit(ctx, cipher, eks, eksl, &iv_buf[0], pkeys, nkeys) || ++ if (EVP_SealInit(ctx, cipher, eks, eksl, &iv_buf[0], pkeys, nkeys) <= 0 || + !EVP_SealUpdate(ctx, buf, &len1, (unsigned char *)data, (int)data_len) || + !EVP_SealFinal(ctx, buf + len1, &len2)) { + efree(buf);",1490,1821,2048 +15611,"void InlineLoginHandlerImpl::FinishCompleteLogin( + const FinishCompleteLoginParams& params, + Profile* profile, + Profile::CreateStatus status) { + std::string default_email; + std::string validate_email; + if (net::GetValueForKeyInQuery(params.url, ""email"", &default_email) && + net::GetValueForKeyInQuery(params.url, ""validateEmail"", + &validate_email) && + validate_email == ""1"" && !default_email.empty()) { + if (!gaia::AreEmailsSame(params.email, default_email)) { + if (params.handler) { + params.handler->HandleLoginError( + l10n_util::GetStringFUTF8(IDS_SYNC_WRONG_EMAIL, + base::UTF8ToUTF16(default_email)), + base::UTF8ToUTF16(params.email)); + } + return; + } + } + + signin_metrics::AccessPoint access_point = + signin::GetAccessPointForPromoURL(params.url); + signin_metrics::Reason reason = + signin::GetSigninReasonForPromoURL(params.url); + LogHistogramValue(signin_metrics::HISTOGRAM_ACCEPTED); + bool switch_to_advanced = + params.choose_what_to_sync && + (access_point != signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS); + LogHistogramValue( + switch_to_advanced ? signin_metrics::HISTOGRAM_WITH_ADVANCED : + signin_metrics::HISTOGRAM_WITH_DEFAULTS); + + CanOfferSigninType can_offer_for = CAN_OFFER_SIGNIN_FOR_ALL_ACCOUNTS; + switch (reason) { + case signin_metrics::Reason::REASON_ADD_SECONDARY_ACCOUNT: + can_offer_for = CAN_OFFER_SIGNIN_FOR_SECONDARY_ACCOUNT; + break; + case signin_metrics::Reason::REASON_REAUTHENTICATION: + case signin_metrics::Reason::REASON_UNLOCK: { + std::string primary_username = + SigninManagerFactory::GetForProfile(profile) + ->GetAuthenticatedAccountInfo() + .email; + if (!gaia::AreEmailsSame(default_email, primary_username)) + can_offer_for = CAN_OFFER_SIGNIN_FOR_SECONDARY_ACCOUNT; + break; + } + default: + break; + } + + std::string error_msg; + bool can_offer = CanOfferSignin(profile, can_offer_for, params.gaia_id, + params.email, &error_msg); + if (!can_offer) { + if (params.handler) { + params.handler->HandleLoginError(error_msg, + base::UTF8ToUTF16(params.email)); + } + return; + } + + AboutSigninInternals* about_signin_internals = + AboutSigninInternalsFactory::GetForProfile(profile); + about_signin_internals->OnAuthenticationResultReceived(""Successful""); + + std::string signin_scoped_device_id = + GetSigninScopedDeviceIdForProfile(profile); + base::WeakPtr handler_weak_ptr; + if (params.handler) + handler_weak_ptr = params.handler->GetWeakPtr(); + + new InlineSigninHelper( + handler_weak_ptr, + params.partition->GetURLLoaderFactoryForBrowserProcess(), profile, status, + params.url, params.email, params.gaia_id, params.password, + params.auth_code, signin_scoped_device_id, params.choose_what_to_sync, + params.confirm_untrusted_signin, + params.is_force_sign_in_with_usermanager); + + if (!params.is_force_sign_in_with_usermanager) { + UnlockProfileAndHideLoginUI(params.profile_path, params.handler); + } +} +",0,"void InlineLoginHandlerImpl::FinishCompleteLogin( + const FinishCompleteLoginParams& params, + Profile* profile, + Profile::CreateStatus status) { + std::string default_email; + std::string validate_email; + if (net::GetValueForKeyInQuery(params.url, ""email"", &default_email) && + net::GetValueForKeyInQuery(params.url, ""validateEmail"", + &validate_email) && + validate_email == ""1"" && !default_email.empty()) { + if (!gaia::AreEmailsSame(params.email, default_email)) { + if (params.handler) { + params.handler->HandleLoginError( + l10n_util::GetStringFUTF8(IDS_SYNC_WRONG_EMAIL, + base::UTF8ToUTF16(default_email)), + base::UTF8ToUTF16(params.email)); + } + return; + } + } + + signin_metrics::AccessPoint access_point = + signin::GetAccessPointForPromoURL(params.url); + signin_metrics::Reason reason = + signin::GetSigninReasonForPromoURL(params.url); + LogHistogramValue(signin_metrics::HISTOGRAM_ACCEPTED); + bool switch_to_advanced = + params.choose_what_to_sync && + (access_point != signin_metrics::AccessPoint::ACCESS_POINT_SETTINGS); + LogHistogramValue( + switch_to_advanced ? signin_metrics::HISTOGRAM_WITH_ADVANCED : + signin_metrics::HISTOGRAM_WITH_DEFAULTS); + + CanOfferSigninType can_offer_for = CAN_OFFER_SIGNIN_FOR_ALL_ACCOUNTS; + switch (reason) { + case signin_metrics::Reason::REASON_ADD_SECONDARY_ACCOUNT: + can_offer_for = CAN_OFFER_SIGNIN_FOR_SECONDARY_ACCOUNT; + break; + case signin_metrics::Reason::REASON_REAUTHENTICATION: + case signin_metrics::Reason::REASON_UNLOCK: { + std::string primary_username = + SigninManagerFactory::GetForProfile(profile) + ->GetAuthenticatedAccountInfo() + .email; + if (!gaia::AreEmailsSame(default_email, primary_username)) + can_offer_for = CAN_OFFER_SIGNIN_FOR_SECONDARY_ACCOUNT; + break; + } + default: + break; + } + + std::string error_msg; + bool can_offer = CanOfferSignin(profile, can_offer_for, params.gaia_id, + params.email, &error_msg); + if (!can_offer) { + if (params.handler) { + params.handler->HandleLoginError(error_msg, + base::UTF8ToUTF16(params.email)); + } + return; + } + + AboutSigninInternals* about_signin_internals = + AboutSigninInternalsFactory::GetForProfile(profile); + about_signin_internals->OnAuthenticationResultReceived(""Successful""); + + std::string signin_scoped_device_id = + GetSigninScopedDeviceIdForProfile(profile); + base::WeakPtr handler_weak_ptr; + if (params.handler) + handler_weak_ptr = params.handler->GetWeakPtr(); + + new InlineSigninHelper( + handler_weak_ptr, + params.partition->GetURLLoaderFactoryForBrowserProcess(), profile, status, + params.url, params.email, params.gaia_id, params.password, + params.auth_code, signin_scoped_device_id, params.choose_what_to_sync, + params.confirm_untrusted_signin, + params.is_force_sign_in_with_usermanager); + + if (!params.is_force_sign_in_with_usermanager) { + UnlockProfileAndHideLoginUI(params.profile_path, params.handler); + } +} +","@@ -260,8 +260,10 @@ void InlineSigninHelper::OnClientOAuthSuccessAndBrowserOpened( + if (reason == signin_metrics::Reason::REASON_REAUTHENTICATION || + reason == signin_metrics::Reason::REASON_UNLOCK || + reason == signin_metrics::Reason::REASON_ADD_SECONDARY_ACCOUNT) { +- ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)-> +- UpdateCredentials(account_id, result.refresh_token); ++ ProfileOAuth2TokenServiceFactory::GetForProfile(profile_) ++ ->UpdateCredentials(account_id, result.refresh_token, ++ signin_metrics::SourceForRefreshTokenOperation:: ++ kInlineLoginHandler_Signin); + + if (signin::IsAutoCloseEnabledInURL(current_url_)) { + // Close the gaia sign in tab via a task to make sure we aren't in the",740,1071,2048 +17634,"xmlHasFeature(xmlFeature feature) +{ + switch (feature) { + case XML_WITH_THREAD: +#ifdef LIBXML_THREAD_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_TREE: +#ifdef LIBXML_TREE_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_OUTPUT: +#ifdef LIBXML_OUTPUT_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_PUSH: +#ifdef LIBXML_PUSH_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_READER: +#ifdef LIBXML_READER_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_PATTERN: +#ifdef LIBXML_PATTERN_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_WRITER: +#ifdef LIBXML_WRITER_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_SAX1: +#ifdef LIBXML_SAX1_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_FTP: +#ifdef LIBXML_FTP_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_HTTP: +#ifdef LIBXML_HTTP_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_VALID: +#ifdef LIBXML_VALID_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_HTML: +#ifdef LIBXML_HTML_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_LEGACY: +#ifdef LIBXML_LEGACY_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_C14N: +#ifdef LIBXML_C14N_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_CATALOG: +#ifdef LIBXML_CATALOG_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_XPATH: +#ifdef LIBXML_XPATH_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_XPTR: +#ifdef LIBXML_XPTR_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_XINCLUDE: +#ifdef LIBXML_XINCLUDE_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_ICONV: +#ifdef LIBXML_ICONV_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_ISO8859X: +#ifdef LIBXML_ISO8859X_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_UNICODE: +#ifdef LIBXML_UNICODE_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_REGEXP: +#ifdef LIBXML_REGEXP_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_AUTOMATA: +#ifdef LIBXML_AUTOMATA_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_EXPR: +#ifdef LIBXML_EXPR_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_SCHEMAS: +#ifdef LIBXML_SCHEMAS_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_SCHEMATRON: +#ifdef LIBXML_SCHEMATRON_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_MODULES: +#ifdef LIBXML_MODULES_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_DEBUG: +#ifdef LIBXML_DEBUG_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_DEBUG_MEM: +#ifdef DEBUG_MEMORY_LOCATION + return(1); +#else + return(0); +#endif + case XML_WITH_DEBUG_RUN: +#ifdef LIBXML_DEBUG_RUNTIME + return(1); +#else + return(0); +#endif + case XML_WITH_ZLIB: +#ifdef LIBXML_ZLIB_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_LZMA: +#ifdef LIBXML_LZMA_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_ICU: +#ifdef LIBXML_ICU_ENABLED + return(1); +#else + return(0); +#endif + default: + break; + } + return(0); +} +",0,"xmlHasFeature(xmlFeature feature) +{ + switch (feature) { + case XML_WITH_THREAD: +#ifdef LIBXML_THREAD_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_TREE: +#ifdef LIBXML_TREE_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_OUTPUT: +#ifdef LIBXML_OUTPUT_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_PUSH: +#ifdef LIBXML_PUSH_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_READER: +#ifdef LIBXML_READER_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_PATTERN: +#ifdef LIBXML_PATTERN_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_WRITER: +#ifdef LIBXML_WRITER_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_SAX1: +#ifdef LIBXML_SAX1_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_FTP: +#ifdef LIBXML_FTP_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_HTTP: +#ifdef LIBXML_HTTP_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_VALID: +#ifdef LIBXML_VALID_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_HTML: +#ifdef LIBXML_HTML_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_LEGACY: +#ifdef LIBXML_LEGACY_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_C14N: +#ifdef LIBXML_C14N_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_CATALOG: +#ifdef LIBXML_CATALOG_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_XPATH: +#ifdef LIBXML_XPATH_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_XPTR: +#ifdef LIBXML_XPTR_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_XINCLUDE: +#ifdef LIBXML_XINCLUDE_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_ICONV: +#ifdef LIBXML_ICONV_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_ISO8859X: +#ifdef LIBXML_ISO8859X_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_UNICODE: +#ifdef LIBXML_UNICODE_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_REGEXP: +#ifdef LIBXML_REGEXP_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_AUTOMATA: +#ifdef LIBXML_AUTOMATA_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_EXPR: +#ifdef LIBXML_EXPR_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_SCHEMAS: +#ifdef LIBXML_SCHEMAS_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_SCHEMATRON: +#ifdef LIBXML_SCHEMATRON_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_MODULES: +#ifdef LIBXML_MODULES_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_DEBUG: +#ifdef LIBXML_DEBUG_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_DEBUG_MEM: +#ifdef DEBUG_MEMORY_LOCATION + return(1); +#else + return(0); +#endif + case XML_WITH_DEBUG_RUN: +#ifdef LIBXML_DEBUG_RUNTIME + return(1); +#else + return(0); +#endif + case XML_WITH_ZLIB: +#ifdef LIBXML_ZLIB_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_LZMA: +#ifdef LIBXML_LZMA_ENABLED + return(1); +#else + return(0); +#endif + case XML_WITH_ICU: +#ifdef LIBXML_ICU_ENABLED + return(1); +#else + return(0); +#endif + default: + break; + } + return(0); +} +","@@ -8130,6 +8130,14 @@ + + if (xmlPushInput(ctxt, input) < 0) + return; + } else { ++ if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) && ++ ((ctxt->options & XML_PARSE_NOENT) == 0) && ++ ((ctxt->options & XML_PARSE_DTDVALID) == 0) && ++ ((ctxt->options & XML_PARSE_DTDLOAD) == 0) && ++ ((ctxt->options & XML_PARSE_DTDATTR) == 0) && ++ (ctxt->replaceEntities == 0) && ++ (ctxt->validate == 0)) ++ return; + /* + * TODO !!! + * handle the extra spaces added before and after +",846,1177,2048 +93,"void CairoOutputDev::setSoftMask(GfxState * state, double * bbox, GBool alpha, + Function * transferFunc, GfxColor * backdropColor) { + cairo_pattern_destroy(mask); + + if (alpha == false) { + /* We need to mask according to the luminocity of the group. + * So we paint the group to an image surface convert it to a luminocity map + * and then use that as the mask. */ + + double x1, y1, x2, y2, tmp; + cairo_clip_extents(cairo, &x1, &y1, &x2, &y2); + cairo_user_to_device(cairo, &x1, &y1); + cairo_user_to_device(cairo, &x2, &y2); + if (x1 > x2) { + tmp = x1; + x1 = x2; + x2 = tmp; + } + + if (y1 > y2) { + tmp = y1; + y1 = y2; + y2 = tmp; + } + + int width = (int)(ceil(x2) - floor(x1)); + int height = (int)(ceil(y2) - floor(y1)); + + cairo_surface_t *source = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height); + cairo_t *maskCtx = cairo_create(source); + + GfxRGB backdropColorRGB; + groupColorSpaceStack->cs->getRGB(backdropColor, &backdropColorRGB); + /* paint the backdrop */ + cairo_set_source_rgb(maskCtx, backdropColorRGB.r / 65535.0, + backdropColorRGB.g / 65535.0, + backdropColorRGB.b / 65535.0); + + + cairo_matrix_t mat; + cairo_get_matrix(cairo, &mat); + cairo_set_matrix(maskCtx, &mat); + + /* make the device offset of the new mask match that of the group */ + double x_offset, y_offset; + cairo_surface_t *pats; + cairo_pattern_get_surface(group, &pats); + cairo_surface_get_device_offset(pats, &x_offset, &y_offset); + cairo_surface_set_device_offset(source, x_offset, y_offset); + + /* paint the group */ + cairo_set_source(maskCtx, group); + cairo_paint(maskCtx); + + /* XXX status = cairo_status(maskCtx); */ + cairo_destroy(maskCtx); + + /* convert to a luminocity map */ + uint32_t *source_data = (uint32_t*)cairo_image_surface_get_data(source); + /* get stride in units of 32 bits */ + int stride = cairo_image_surface_get_stride(source)/4; + for (int y=0; ytransform(&lum, &lum2); + } else { + lum2 = lum; + } + p[x] = (int)(lum2 * 255.0 + 0.5); +#endif + + } + } + + /* setup the new mask pattern */ + mask = cairo_pattern_create_for_surface(source); + cairo_matrix_t patMatrix; + cairo_pattern_get_matrix(group, &patMatrix); + cairo_pattern_set_matrix(mask, &patMatrix); + + cairo_surface_destroy(source); + } else { + mask = cairo_pattern_reference(group); + } + + popTransparencyGroup(); +} +",0,"void CairoOutputDev::setSoftMask(GfxState * state, double * bbox, GBool alpha, + Function * transferFunc, GfxColor * backdropColor) { + cairo_pattern_destroy(mask); + + if (alpha == false) { + /* We need to mask according to the luminocity of the group. + * So we paint the group to an image surface convert it to a luminocity map + * and then use that as the mask. */ + + double x1, y1, x2, y2, tmp; + cairo_clip_extents(cairo, &x1, &y1, &x2, &y2); + cairo_user_to_device(cairo, &x1, &y1); + cairo_user_to_device(cairo, &x2, &y2); + if (x1 > x2) { + tmp = x1; + x1 = x2; + x2 = tmp; + } + + if (y1 > y2) { + tmp = y1; + y1 = y2; + y2 = tmp; + } + + int width = (int)(ceil(x2) - floor(x1)); + int height = (int)(ceil(y2) - floor(y1)); + + cairo_surface_t *source = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height); + cairo_t *maskCtx = cairo_create(source); + + GfxRGB backdropColorRGB; + groupColorSpaceStack->cs->getRGB(backdropColor, &backdropColorRGB); + /* paint the backdrop */ + cairo_set_source_rgb(maskCtx, backdropColorRGB.r / 65535.0, + backdropColorRGB.g / 65535.0, + backdropColorRGB.b / 65535.0); + + + cairo_matrix_t mat; + cairo_get_matrix(cairo, &mat); + cairo_set_matrix(maskCtx, &mat); + + /* make the device offset of the new mask match that of the group */ + double x_offset, y_offset; + cairo_surface_t *pats; + cairo_pattern_get_surface(group, &pats); + cairo_surface_get_device_offset(pats, &x_offset, &y_offset); + cairo_surface_set_device_offset(source, x_offset, y_offset); + + /* paint the group */ + cairo_set_source(maskCtx, group); + cairo_paint(maskCtx); + + /* XXX status = cairo_status(maskCtx); */ + cairo_destroy(maskCtx); + + /* convert to a luminocity map */ + uint32_t *source_data = (uint32_t*)cairo_image_surface_get_data(source); + /* get stride in units of 32 bits */ + int stride = cairo_image_surface_get_stride(source)/4; + for (int y=0; ytransform(&lum, &lum2); + } else { + lum2 = lum; + } + p[x] = (int)(lum2 * 255.0 + 0.5); +#endif + + } + } + + /* setup the new mask pattern */ + mask = cairo_pattern_create_for_surface(source); + cairo_matrix_t patMatrix; + cairo_pattern_get_matrix(group, &patMatrix); + cairo_pattern_set_matrix(mask, &patMatrix); + + cairo_surface_destroy(source); + } else { + mask = cairo_pattern_reference(group); + } + + popTransparencyGroup(); +} +","@@ -16,7 +16,7 @@ + // + // Copyright (C) 2005-2008 Jeff Muizelaar + // Copyright (C) 2005, 2006 Kristian Høgsberg +-// Copyright (C) 2005 Albert Astals Cid ++// Copyright (C) 2005, 2009 Albert Astals Cid + // Copyright (C) 2005 Nickolay V. Shmyrev + // Copyright (C) 2006-2008 Carlos Garcia Campos + // Copyright (C) 2008 Carl Worth +@@ -611,7 +611,7 @@ void CairoOutputDev::beginString(GfxState *state, GooString *s) + if (!currentFont) + return; + +- glyphs = (cairo_glyph_t *) gmalloc (len * sizeof (cairo_glyph_t)); ++ glyphs = (cairo_glyph_t *) gmallocn (len, sizeof (cairo_glyph_t)); + glyphCount = 0; + } + +@@ -1461,7 +1461,7 @@ void CairoOutputDev::drawMaskedImage(GfxState *state, Object *ref, + + int row_stride = (maskWidth + 3) & ~3; + unsigned char *maskBuffer; +- maskBuffer = (unsigned char *)gmalloc (row_stride * maskHeight); ++ maskBuffer = (unsigned char *)gmallocn (row_stride, maskHeight); + unsigned char *maskDest; + cairo_surface_t *maskImage; + cairo_pattern_t *maskPattern; +@@ -1497,7 +1497,7 @@ void CairoOutputDev::drawMaskedImage(GfxState *state, Object *ref, + cairo_matrix_t matrix; + int is_identity_transform; + +- buffer = (unsigned char *)gmalloc (width * height * 4); ++ buffer = (unsigned char *)gmallocn3 (width, height, 4); + + /* TODO: Do we want to cache these? */ + imgStr = new ImageStream(str, width, +@@ -1586,7 +1586,7 @@ void CairoOutputDev::drawSoftMaskedImage(GfxState *state, Object *ref, Stream *s + + int row_stride = (maskWidth + 3) & ~3; + unsigned char *maskBuffer; +- maskBuffer = (unsigned char *)gmalloc (row_stride * maskHeight); ++ maskBuffer = (unsigned char *)gmallocn (row_stride, maskHeight); + unsigned char *maskDest; + cairo_surface_t *maskImage; + cairo_pattern_t *maskPattern; +@@ -1613,7 +1613,7 @@ void CairoOutputDev::drawSoftMaskedImage(GfxState *state, Object *ref, Stream *s + cairo_matrix_t maskMatrix; + int is_identity_transform; + +- buffer = (unsigned char *)gmalloc (width * height * 4); ++ buffer = (unsigned char *)gmallocn3 (width, height, 4); + + /* TODO: Do we want to cache these? */ + imgStr = new ImageStream(str, width, +@@ -1705,7 +1705,7 @@ void CairoOutputDev::drawImage(GfxState *state, Object *ref, Stream *str, + cairo_matrix_t matrix; + int is_identity_transform; + +- buffer = (unsigned char *)gmalloc (width * height * 4); ++ buffer = (unsigned char *)gmallocn3 (width, height, 4); + + /* TODO: Do we want to cache these? */ + imgStr = new ImageStream(str, width,",786,1117,2048 +23,"char *phar_find_in_include_path(char *filename, int filename_len, phar_archive_data **pphar TSRMLS_DC) /* {{{ */ +{ + char *path, *fname, *arch, *entry, *ret, *test; + int arch_len, entry_len, fname_len, ret_len; + phar_archive_data *phar; + + if (pphar) { + *pphar = NULL; + } else { + pphar = &phar; + } + + if (!zend_is_executing(TSRMLS_C) || !PHAR_G(cwd)) { + return phar_save_resolve_path(filename, filename_len TSRMLS_CC); + } + + fname = (char*)zend_get_executed_filename(TSRMLS_C); + fname_len = strlen(fname); + + if (PHAR_G(last_phar) && !memcmp(fname, ""phar://"", 7) && fname_len - 7 >= PHAR_G(last_phar_name_len) && !memcmp(fname + 7, PHAR_G(last_phar_name), PHAR_G(last_phar_name_len))) { + arch = estrndup(PHAR_G(last_phar_name), PHAR_G(last_phar_name_len)); + arch_len = PHAR_G(last_phar_name_len); + phar = PHAR_G(last_phar); + goto splitted; + } + + if (fname_len < 7 || memcmp(fname, ""phar://"", 7) || SUCCESS != phar_split_fname(fname, strlen(fname), &arch, &arch_len, &entry, &entry_len, 1, 0 TSRMLS_CC)) { + return phar_save_resolve_path(filename, filename_len TSRMLS_CC); + } + + efree(entry); + + if (*filename == '.') { + int try_len; + + if (FAILURE == phar_get_archive(&phar, arch, arch_len, NULL, 0, NULL TSRMLS_CC)) { + efree(arch); + return phar_save_resolve_path(filename, filename_len TSRMLS_CC); + } +splitted: + if (pphar) { + *pphar = phar; + } + + try_len = filename_len; + test = phar_fix_filepath(estrndup(filename, filename_len), &try_len, 1 TSRMLS_CC); + + if (*test == '/') { + if (zend_hash_exists(&(phar->manifest), test + 1, try_len - 1)) { + spprintf(&ret, 0, ""phar://%s%s"", arch, test); + efree(arch); + efree(test); + return ret; + } + } else { + if (zend_hash_exists(&(phar->manifest), test, try_len)) { + spprintf(&ret, 0, ""phar://%s/%s"", arch, test); + efree(arch); + efree(test); + return ret; + } + } + efree(test); + } + + spprintf(&path, MAXPATHLEN, ""phar://%s/%s%c%s"", arch, PHAR_G(cwd), DEFAULT_DIR_SEPARATOR, PG(include_path)); + efree(arch); + ret = php_resolve_path(filename, filename_len, path TSRMLS_CC); + efree(path); + + if (ret && strlen(ret) > 8 && !strncmp(ret, ""phar://"", 7)) { + ret_len = strlen(ret); + /* found phar:// */ + + if (SUCCESS != phar_split_fname(ret, ret_len, &arch, &arch_len, &entry, &entry_len, 1, 0 TSRMLS_CC)) { + return ret; + } + + zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), arch, arch_len, (void **) &pphar); + + if (!pphar && PHAR_G(manifest_cached)) { + zend_hash_find(&cached_phars, arch, arch_len, (void **) &pphar); + } + + efree(arch); + efree(entry); + } + + return ret; +} +/* }}} */ +",0,"char *phar_find_in_include_path(char *filename, int filename_len, phar_archive_data **pphar TSRMLS_DC) /* {{{ */ +{ + char *path, *fname, *arch, *entry, *ret, *test; + int arch_len, entry_len, fname_len, ret_len; + phar_archive_data *phar; + + if (pphar) { + *pphar = NULL; + } else { + pphar = &phar; + } + + if (!zend_is_executing(TSRMLS_C) || !PHAR_G(cwd)) { + return phar_save_resolve_path(filename, filename_len TSRMLS_CC); + } + + fname = (char*)zend_get_executed_filename(TSRMLS_C); + fname_len = strlen(fname); + + if (PHAR_G(last_phar) && !memcmp(fname, ""phar://"", 7) && fname_len - 7 >= PHAR_G(last_phar_name_len) && !memcmp(fname + 7, PHAR_G(last_phar_name), PHAR_G(last_phar_name_len))) { + arch = estrndup(PHAR_G(last_phar_name), PHAR_G(last_phar_name_len)); + arch_len = PHAR_G(last_phar_name_len); + phar = PHAR_G(last_phar); + goto splitted; + } + + if (fname_len < 7 || memcmp(fname, ""phar://"", 7) || SUCCESS != phar_split_fname(fname, strlen(fname), &arch, &arch_len, &entry, &entry_len, 1, 0 TSRMLS_CC)) { + return phar_save_resolve_path(filename, filename_len TSRMLS_CC); + } + + efree(entry); + + if (*filename == '.') { + int try_len; + + if (FAILURE == phar_get_archive(&phar, arch, arch_len, NULL, 0, NULL TSRMLS_CC)) { + efree(arch); + return phar_save_resolve_path(filename, filename_len TSRMLS_CC); + } +splitted: + if (pphar) { + *pphar = phar; + } + + try_len = filename_len; + test = phar_fix_filepath(estrndup(filename, filename_len), &try_len, 1 TSRMLS_CC); + + if (*test == '/') { + if (zend_hash_exists(&(phar->manifest), test + 1, try_len - 1)) { + spprintf(&ret, 0, ""phar://%s%s"", arch, test); + efree(arch); + efree(test); + return ret; + } + } else { + if (zend_hash_exists(&(phar->manifest), test, try_len)) { + spprintf(&ret, 0, ""phar://%s/%s"", arch, test); + efree(arch); + efree(test); + return ret; + } + } + efree(test); + } + + spprintf(&path, MAXPATHLEN, ""phar://%s/%s%c%s"", arch, PHAR_G(cwd), DEFAULT_DIR_SEPARATOR, PG(include_path)); + efree(arch); + ret = php_resolve_path(filename, filename_len, path TSRMLS_CC); + efree(path); + + if (ret && strlen(ret) > 8 && !strncmp(ret, ""phar://"", 7)) { + ret_len = strlen(ret); + /* found phar:// */ + + if (SUCCESS != phar_split_fname(ret, ret_len, &arch, &arch_len, &entry, &entry_len, 1, 0 TSRMLS_CC)) { + return ret; + } + + zend_hash_find(&(PHAR_GLOBALS->phar_fname_map), arch, arch_len, (void **) &pphar); + + if (!pphar && PHAR_G(manifest_cached)) { + zend_hash_find(&cached_phars, arch, arch_len, (void **) &pphar); + } + + efree(arch); + efree(entry); + } + + return ret; +} +/* }}} */ +","@@ -1977,7 +1977,7 @@ void phar_add_virtual_dirs(phar_archive_data *phar, char *filename, int filename + + while ((s = zend_memrchr(filename, '/', filename_len))) { + filename_len = s - filename; +- if (FAILURE == zend_hash_add_empty_element(&phar->virtual_dirs, filename, filename_len)) { ++ if (!filename_len || FAILURE == zend_hash_add_empty_element(&phar->virtual_dirs, filename, filename_len)) { + break; + } + }",856,1187,2048 +5813,"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; + bool already_matched; + u64 data = msr->data; + + raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags); + offset = kvm_compute_tsc_offset(vcpu, data); + ns = get_kernel_ns(); + elapsed = ns - kvm->arch.last_tsc_nsec; + + if (vcpu->arch.virtual_tsc_khz) { + int faulted = 0; + + /* 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(""1: idivl %[divisor]\n"" + ""2: xor %%edx, %%edx\n"" + "" movl $0, %[faulted]\n"" + ""3:\n"" + "".section .fixup,\""ax\""\n"" + ""4: movl $1, %[faulted]\n"" + "" jmp 3b\n"" + "".previous\n"" + + _ASM_EXTABLE(1b, 4b) + + : ""=A""(usdiff), [faulted] ""=r"" (faulted) + : ""A""(usdiff * 1000), [divisor] ""rm""(vcpu->arch.virtual_tsc_khz)); + +#endif + do_div(elapsed, 1000); + usdiff -= elapsed; + if (usdiff < 0) + usdiff = -usdiff; + + /* idivl overflow => difference is larger than USEC_PER_SEC */ + if (faulted) + usdiff = USEC_PER_SEC; + } else + usdiff = USEC_PER_SEC; /* disable TSC match window below */ + + /* + * 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_compute_tsc_offset(vcpu, data); + pr_debug(""kvm: adjusted tsc offset by %llu\n"", delta); + } + matched = true; + already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation); + } 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 %llu, 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; + + 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 = 0; + } else if (!already_matched) { + kvm->arch.nr_vcpus_matched_tsc++; + } + + kvm_track_tsc_matching(vcpu); + spin_unlock(&kvm->arch.pvclock_gtod_sync_lock); +} +",0,"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; + bool already_matched; + u64 data = msr->data; + + raw_spin_lock_irqsave(&kvm->arch.tsc_write_lock, flags); + offset = kvm_compute_tsc_offset(vcpu, data); + ns = get_kernel_ns(); + elapsed = ns - kvm->arch.last_tsc_nsec; + + if (vcpu->arch.virtual_tsc_khz) { + int faulted = 0; + + /* 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(""1: idivl %[divisor]\n"" + ""2: xor %%edx, %%edx\n"" + "" movl $0, %[faulted]\n"" + ""3:\n"" + "".section .fixup,\""ax\""\n"" + ""4: movl $1, %[faulted]\n"" + "" jmp 3b\n"" + "".previous\n"" + + _ASM_EXTABLE(1b, 4b) + + : ""=A""(usdiff), [faulted] ""=r"" (faulted) + : ""A""(usdiff * 1000), [divisor] ""rm""(vcpu->arch.virtual_tsc_khz)); + +#endif + do_div(elapsed, 1000); + usdiff -= elapsed; + if (usdiff < 0) + usdiff = -usdiff; + + /* idivl overflow => difference is larger than USEC_PER_SEC */ + if (faulted) + usdiff = USEC_PER_SEC; + } else + usdiff = USEC_PER_SEC; /* disable TSC match window below */ + + /* + * 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_compute_tsc_offset(vcpu, data); + pr_debug(""kvm: adjusted tsc offset by %llu\n"", delta); + } + matched = true; + already_matched = (vcpu->arch.this_tsc_generation == kvm->arch.cur_tsc_generation); + } 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 %llu, 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; + + 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 = 0; + } else if (!already_matched) { + kvm->arch.nr_vcpus_matched_tsc++; + } + + kvm_track_tsc_matching(vcpu); + spin_unlock(&kvm->arch.pvclock_gtod_sync_lock); +} +","@@ -3572,9 +3572,11 @@ static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps) + + static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps) + { ++ int i; + 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); ++ for (i = 0; i < 3; i++) ++ kvm_pit_load_count(kvm, i, ps->channels[i].count, 0); + mutex_unlock(&kvm->arch.vpit->pit_state.lock); + return 0; + } +@@ -3593,6 +3595,7 @@ static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps) + static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps) + { + int start = 0; ++ int i; + 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; +@@ -3602,7 +3605,8 @@ static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps) + 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); ++ for (i = 0; i < 3; i++) ++ kvm_pit_load_count(kvm, i, kvm->arch.vpit->pit_state.channels[i].count, start); + mutex_unlock(&kvm->arch.vpit->pit_state.lock); + return 0; + }",1217,1548,2048 +6584,"static int nsv_parse_NSVs_header(AVFormatContext *s) +{ + NSVContext *nsv = s->priv_data; + AVIOContext *pb = s->pb; + uint32_t vtag, atag; + uint16_t vwidth, vheight; + AVRational framerate; + int i; + AVStream *st; + NSVStream *nst; + + vtag = avio_rl32(pb); + atag = avio_rl32(pb); + vwidth = avio_rl16(pb); + vheight = avio_rl16(pb); + i = avio_r8(pb); + + av_log(s, AV_LOG_TRACE, ""NSV NSVs framerate code %2x\n"", i); + if(i&0x80) { /* odd way of giving native framerates from docs */ + int t=(i & 0x7F)>>2; + if(t<16) framerate = (AVRational){1, t+1}; + else framerate = (AVRational){t-15, 1}; + + if(i&1){ + framerate.num *= 1000; + framerate.den *= 1001; + } + + if((i&3)==3) framerate.num *= 24; + else if((i&3)==2) framerate.num *= 25; + else framerate.num *= 30; + } + else + framerate= (AVRational){i, 1}; + + nsv->avsync = avio_rl16(pb); + nsv->framerate = framerate; + + av_log(s, AV_LOG_TRACE, ""NSV NSVs vsize %""PRIu16""x%""PRIu16""\n"", + vwidth, vheight); + + /* XXX change to ap != NULL ? */ + if (s->nb_streams == 0) { /* streams not yet published, let's do that */ + nsv->vtag = vtag; + nsv->atag = atag; + nsv->vwidth = vwidth; + nsv->vheight = vwidth; + if (vtag != T_NONE) { + int i; + st = avformat_new_stream(s, NULL); + if (!st) + goto fail; + + st->id = NSV_ST_VIDEO; + nst = av_mallocz(sizeof(NSVStream)); + if (!nst) + goto fail; + st->priv_data = nst; + st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; + st->codecpar->codec_tag = vtag; + st->codecpar->codec_id = ff_codec_get_id(nsv_codec_video_tags, vtag); + st->codecpar->width = vwidth; + st->codecpar->height = vheight; + st->codecpar->bits_per_coded_sample = 24; /* depth XXX */ + + avpriv_set_pts_info(st, 64, framerate.den, framerate.num); + st->start_time = 0; + st->duration = av_rescale(nsv->duration, framerate.num, 1000*framerate.den); + + for(i=0;iindex_entries;i++) { + if(nsv->nsvs_timestamps) { + av_add_index_entry(st, nsv->nsvs_file_offset[i], nsv->nsvs_timestamps[i], + 0, 0, AVINDEX_KEYFRAME); + } else { + int64_t ts = av_rescale(i*nsv->duration/nsv->index_entries, framerate.num, 1000*framerate.den); + av_add_index_entry(st, nsv->nsvs_file_offset[i], ts, 0, 0, AVINDEX_KEYFRAME); + } + } + } + if (atag != T_NONE) { + st = avformat_new_stream(s, NULL); + if (!st) + goto fail; + + st->id = NSV_ST_AUDIO; + nst = av_mallocz(sizeof(NSVStream)); + if (!nst) + goto fail; + st->priv_data = nst; + st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; + st->codecpar->codec_tag = atag; + st->codecpar->codec_id = ff_codec_get_id(nsv_codec_audio_tags, atag); + + st->need_parsing = AVSTREAM_PARSE_FULL; /* for PCM we will read a chunk later and put correct info */ + + /* set timebase to common denominator of ms and framerate */ + avpriv_set_pts_info(st, 64, 1, framerate.num*1000); + st->start_time = 0; + st->duration = (int64_t)nsv->duration * framerate.num; + } + } else { + if (nsv->vtag != vtag || nsv->atag != atag || nsv->vwidth != vwidth || nsv->vheight != vwidth) { + av_log(s, AV_LOG_TRACE, ""NSV NSVs header values differ from the first one!!!\n""); + } + } + + nsv->state = NSV_HAS_READ_NSVS; + return 0; +fail: + /* XXX */ + nsv->state = NSV_UNSYNC; + return -1; +} +",0,"static int nsv_parse_NSVs_header(AVFormatContext *s) +{ + NSVContext *nsv = s->priv_data; + AVIOContext *pb = s->pb; + uint32_t vtag, atag; + uint16_t vwidth, vheight; + AVRational framerate; + int i; + AVStream *st; + NSVStream *nst; + + vtag = avio_rl32(pb); + atag = avio_rl32(pb); + vwidth = avio_rl16(pb); + vheight = avio_rl16(pb); + i = avio_r8(pb); + + av_log(s, AV_LOG_TRACE, ""NSV NSVs framerate code %2x\n"", i); + if(i&0x80) { /* odd way of giving native framerates from docs */ + int t=(i & 0x7F)>>2; + if(t<16) framerate = (AVRational){1, t+1}; + else framerate = (AVRational){t-15, 1}; + + if(i&1){ + framerate.num *= 1000; + framerate.den *= 1001; + } + + if((i&3)==3) framerate.num *= 24; + else if((i&3)==2) framerate.num *= 25; + else framerate.num *= 30; + } + else + framerate= (AVRational){i, 1}; + + nsv->avsync = avio_rl16(pb); + nsv->framerate = framerate; + + av_log(s, AV_LOG_TRACE, ""NSV NSVs vsize %""PRIu16""x%""PRIu16""\n"", + vwidth, vheight); + + /* XXX change to ap != NULL ? */ + if (s->nb_streams == 0) { /* streams not yet published, let's do that */ + nsv->vtag = vtag; + nsv->atag = atag; + nsv->vwidth = vwidth; + nsv->vheight = vwidth; + if (vtag != T_NONE) { + int i; + st = avformat_new_stream(s, NULL); + if (!st) + goto fail; + + st->id = NSV_ST_VIDEO; + nst = av_mallocz(sizeof(NSVStream)); + if (!nst) + goto fail; + st->priv_data = nst; + st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; + st->codecpar->codec_tag = vtag; + st->codecpar->codec_id = ff_codec_get_id(nsv_codec_video_tags, vtag); + st->codecpar->width = vwidth; + st->codecpar->height = vheight; + st->codecpar->bits_per_coded_sample = 24; /* depth XXX */ + + avpriv_set_pts_info(st, 64, framerate.den, framerate.num); + st->start_time = 0; + st->duration = av_rescale(nsv->duration, framerate.num, 1000*framerate.den); + + for(i=0;iindex_entries;i++) { + if(nsv->nsvs_timestamps) { + av_add_index_entry(st, nsv->nsvs_file_offset[i], nsv->nsvs_timestamps[i], + 0, 0, AVINDEX_KEYFRAME); + } else { + int64_t ts = av_rescale(i*nsv->duration/nsv->index_entries, framerate.num, 1000*framerate.den); + av_add_index_entry(st, nsv->nsvs_file_offset[i], ts, 0, 0, AVINDEX_KEYFRAME); + } + } + } + if (atag != T_NONE) { + st = avformat_new_stream(s, NULL); + if (!st) + goto fail; + + st->id = NSV_ST_AUDIO; + nst = av_mallocz(sizeof(NSVStream)); + if (!nst) + goto fail; + st->priv_data = nst; + st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; + st->codecpar->codec_tag = atag; + st->codecpar->codec_id = ff_codec_get_id(nsv_codec_audio_tags, atag); + + st->need_parsing = AVSTREAM_PARSE_FULL; /* for PCM we will read a chunk later and put correct info */ + + /* set timebase to common denominator of ms and framerate */ + avpriv_set_pts_info(st, 64, 1, framerate.num*1000); + st->start_time = 0; + st->duration = (int64_t)nsv->duration * framerate.num; + } + } else { + if (nsv->vtag != vtag || nsv->atag != atag || nsv->vwidth != vwidth || nsv->vheight != vwidth) { + av_log(s, AV_LOG_TRACE, ""NSV NSVs header values differ from the first one!!!\n""); + } + } + + nsv->state = NSV_HAS_READ_NSVS; + return 0; +fail: + /* XXX */ + nsv->state = NSV_UNSYNC; + return -1; +} +","@@ -520,6 +520,7 @@ static int nsv_read_chunk(AVFormatContext *s, int fill_header) + uint32_t vsize; + uint16_t asize; + uint16_t auxsize; ++ int ret; + + if (nsv->ahead[0].data || nsv->ahead[1].data) + return 0; //-1; /* hey! eat what you've in your plate first! */ +@@ -571,7 +572,8 @@ static int nsv_read_chunk(AVFormatContext *s, int fill_header) + if (vsize && st[NSV_ST_VIDEO]) { + nst = st[NSV_ST_VIDEO]->priv_data; + pkt = &nsv->ahead[NSV_ST_VIDEO]; +- av_get_packet(pb, pkt, vsize); ++ if ((ret = av_get_packet(pb, pkt, vsize)) < 0) ++ return ret; + pkt->stream_index = st[NSV_ST_VIDEO]->index;//NSV_ST_VIDEO; + pkt->dts = nst->frame_offset; + pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */ +@@ -615,7 +617,8 @@ static int nsv_read_chunk(AVFormatContext *s, int fill_header) + bps, channels, samplerate); + } + } +- av_get_packet(pb, pkt, asize); ++ if ((ret = av_get_packet(pb, pkt, asize)) < 0) ++ return ret; + pkt->stream_index = st[NSV_ST_AUDIO]->index;//NSV_ST_AUDIO; + pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */ + if( nsv->state == NSV_HAS_READ_NSVS && st[NSV_ST_VIDEO] ) {",1141,1472,2048 +5689,"void ext4_evict_inode(struct inode *inode) +{ + handle_t *handle; + int err; + + trace_ext4_evict_inode(inode); + + if (inode->i_nlink) { + /* + * When journalling data dirty buffers are tracked only in the + * journal. So although mm thinks everything is clean and + * ready for reaping the inode might still have some pages to + * write in the running transaction or waiting to be + * checkpointed. Thus calling jbd2_journal_invalidatepage() + * (via truncate_inode_pages()) to discard these buffers can + * cause data loss. Also even if we did not discard these + * buffers, we would have no way to find them after the inode + * is reaped and thus user could see stale data if he tries to + * read them before the transaction is checkpointed. So be + * careful and force everything to disk here... We use + * ei->i_datasync_tid to store the newest transaction + * containing inode's data. + * + * Note that directories do not have this problem because they + * don't use page cache. + */ + if (ext4_should_journal_data(inode) && + (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) && + inode->i_ino != EXT4_JOURNAL_INO) { + journal_t *journal = EXT4_SB(inode->i_sb)->s_journal; + tid_t commit_tid = EXT4_I(inode)->i_datasync_tid; + + jbd2_complete_transaction(journal, commit_tid); + filemap_write_and_wait(&inode->i_data); + } + truncate_inode_pages_final(&inode->i_data); + + WARN_ON(atomic_read(&EXT4_I(inode)->i_ioend_count)); + goto no_delete; + } + + if (is_bad_inode(inode)) + goto no_delete; + dquot_initialize(inode); + + if (ext4_should_order_data(inode)) + ext4_begin_ordered_truncate(inode, 0); + truncate_inode_pages_final(&inode->i_data); + + WARN_ON(atomic_read(&EXT4_I(inode)->i_ioend_count)); + + /* + * Protect us against freezing - iput() caller didn't have to have any + * protection against it + */ + sb_start_intwrite(inode->i_sb); + handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, + ext4_blocks_for_truncate(inode)+3); + if (IS_ERR(handle)) { + ext4_std_error(inode->i_sb, PTR_ERR(handle)); + /* + * If we're going to skip the normal cleanup, we still need to + * make sure that the in-core orphan linked list is properly + * cleaned up. + */ + ext4_orphan_del(NULL, inode); + sb_end_intwrite(inode->i_sb); + goto no_delete; + } + + if (IS_SYNC(inode)) + ext4_handle_sync(handle); + inode->i_size = 0; + err = ext4_mark_inode_dirty(handle, inode); + if (err) { + ext4_warning(inode->i_sb, + ""couldn't mark inode dirty (err %d)"", err); + goto stop_handle; + } + if (inode->i_blocks) + ext4_truncate(inode); + + /* + * ext4_ext_truncate() doesn't reserve any slop when it + * restarts journal transactions; therefore there may not be + * enough credits left in the handle to remove the inode from + * the orphan list and set the dtime field. + */ + if (!ext4_handle_has_enough_credits(handle, 3)) { + err = ext4_journal_extend(handle, 3); + if (err > 0) + err = ext4_journal_restart(handle, 3); + if (err != 0) { + ext4_warning(inode->i_sb, + ""couldn't extend journal (err %d)"", err); + stop_handle: + ext4_journal_stop(handle); + ext4_orphan_del(NULL, inode); + sb_end_intwrite(inode->i_sb); + goto no_delete; + } + } + + /* + * Kill off the orphan record which ext4_truncate created. + * AKPM: I think this can be inside the above `if'. + * Note that ext4_orphan_del() has to be able to cope with the + * deletion of a non-existent orphan - this is because we don't + * know if ext4_truncate() actually created an orphan record. + * (Well, we could do this if we need to, but heck - it works) + */ + ext4_orphan_del(handle, inode); + EXT4_I(inode)->i_dtime = get_seconds(); + + /* + * One subtle ordering requirement: if anything has gone wrong + * (transaction abort, IO errors, whatever), then we can still + * do these next steps (the fs will already have been marked as + * having errors), but we can't free the inode if the mark_dirty + * fails. + */ + if (ext4_mark_inode_dirty(handle, inode)) + /* If that failed, just do the required in-core inode clear. */ + ext4_clear_inode(inode); + else + ext4_free_inode(handle, inode); + ext4_journal_stop(handle); + sb_end_intwrite(inode->i_sb); + return; +no_delete: + ext4_clear_inode(inode); /* We must guarantee clearing of inode... */ +} +",0,"void ext4_evict_inode(struct inode *inode) +{ + handle_t *handle; + int err; + + trace_ext4_evict_inode(inode); + + if (inode->i_nlink) { + /* + * When journalling data dirty buffers are tracked only in the + * journal. So although mm thinks everything is clean and + * ready for reaping the inode might still have some pages to + * write in the running transaction or waiting to be + * checkpointed. Thus calling jbd2_journal_invalidatepage() + * (via truncate_inode_pages()) to discard these buffers can + * cause data loss. Also even if we did not discard these + * buffers, we would have no way to find them after the inode + * is reaped and thus user could see stale data if he tries to + * read them before the transaction is checkpointed. So be + * careful and force everything to disk here... We use + * ei->i_datasync_tid to store the newest transaction + * containing inode's data. + * + * Note that directories do not have this problem because they + * don't use page cache. + */ + if (ext4_should_journal_data(inode) && + (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) && + inode->i_ino != EXT4_JOURNAL_INO) { + journal_t *journal = EXT4_SB(inode->i_sb)->s_journal; + tid_t commit_tid = EXT4_I(inode)->i_datasync_tid; + + jbd2_complete_transaction(journal, commit_tid); + filemap_write_and_wait(&inode->i_data); + } + truncate_inode_pages_final(&inode->i_data); + + WARN_ON(atomic_read(&EXT4_I(inode)->i_ioend_count)); + goto no_delete; + } + + if (is_bad_inode(inode)) + goto no_delete; + dquot_initialize(inode); + + if (ext4_should_order_data(inode)) + ext4_begin_ordered_truncate(inode, 0); + truncate_inode_pages_final(&inode->i_data); + + WARN_ON(atomic_read(&EXT4_I(inode)->i_ioend_count)); + + /* + * Protect us against freezing - iput() caller didn't have to have any + * protection against it + */ + sb_start_intwrite(inode->i_sb); + handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, + ext4_blocks_for_truncate(inode)+3); + if (IS_ERR(handle)) { + ext4_std_error(inode->i_sb, PTR_ERR(handle)); + /* + * If we're going to skip the normal cleanup, we still need to + * make sure that the in-core orphan linked list is properly + * cleaned up. + */ + ext4_orphan_del(NULL, inode); + sb_end_intwrite(inode->i_sb); + goto no_delete; + } + + if (IS_SYNC(inode)) + ext4_handle_sync(handle); + inode->i_size = 0; + err = ext4_mark_inode_dirty(handle, inode); + if (err) { + ext4_warning(inode->i_sb, + ""couldn't mark inode dirty (err %d)"", err); + goto stop_handle; + } + if (inode->i_blocks) + ext4_truncate(inode); + + /* + * ext4_ext_truncate() doesn't reserve any slop when it + * restarts journal transactions; therefore there may not be + * enough credits left in the handle to remove the inode from + * the orphan list and set the dtime field. + */ + if (!ext4_handle_has_enough_credits(handle, 3)) { + err = ext4_journal_extend(handle, 3); + if (err > 0) + err = ext4_journal_restart(handle, 3); + if (err != 0) { + ext4_warning(inode->i_sb, + ""couldn't extend journal (err %d)"", err); + stop_handle: + ext4_journal_stop(handle); + ext4_orphan_del(NULL, inode); + sb_end_intwrite(inode->i_sb); + goto no_delete; + } + } + + /* + * Kill off the orphan record which ext4_truncate created. + * AKPM: I think this can be inside the above `if'. + * Note that ext4_orphan_del() has to be able to cope with the + * deletion of a non-existent orphan - this is because we don't + * know if ext4_truncate() actually created an orphan record. + * (Well, we could do this if we need to, but heck - it works) + */ + ext4_orphan_del(handle, inode); + EXT4_I(inode)->i_dtime = get_seconds(); + + /* + * One subtle ordering requirement: if anything has gone wrong + * (transaction abort, IO errors, whatever), then we can still + * do these next steps (the fs will already have been marked as + * having errors), but we can't free the inode if the mark_dirty + * fails. + */ + if (ext4_mark_inode_dirty(handle, inode)) + /* If that failed, just do the required in-core inode clear. */ + ext4_clear_inode(inode); + else + ext4_free_inode(handle, inode); + ext4_journal_stop(handle); + sb_end_intwrite(inode->i_sb); + return; +no_delete: + ext4_clear_inode(inode); /* We must guarantee clearing of inode... */ +} +","@@ -3623,6 +3623,15 @@ int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length) + + } + ++ /* Wait all existing dio workers, newcomers will block on i_mutex */ ++ ext4_inode_block_unlocked_dio(inode); ++ inode_dio_wait(inode); ++ ++ /* ++ * Prevent page faults from reinstantiating pages we have released from ++ * page cache. ++ */ ++ down_write(&EXT4_I(inode)->i_mmap_sem); + first_block_offset = round_up(offset, sb->s_blocksize); + last_block_offset = round_down((offset + length), sb->s_blocksize) - 1; + +@@ -3631,10 +3640,6 @@ int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length) + truncate_pagecache_range(inode, first_block_offset, + last_block_offset); + +- /* Wait all existing dio workers, newcomers will block on i_mutex */ +- ext4_inode_block_unlocked_dio(inode); +- inode_dio_wait(inode); +- + if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) + credits = ext4_writepage_trans_blocks(inode); + else +@@ -3680,16 +3685,12 @@ int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length) + if (IS_SYNC(inode)) + ext4_handle_sync(handle); + +- /* Now release the pages again to reduce race window */ +- if (last_block_offset > first_block_offset) +- truncate_pagecache_range(inode, first_block_offset, +- last_block_offset); +- + inode->i_mtime = inode->i_ctime = ext4_current_time(inode); + ext4_mark_inode_dirty(handle, inode); + out_stop: + ext4_journal_stop(handle); + out_dio: ++ up_write(&EXT4_I(inode)->i_mmap_sem); + ext4_inode_resume_unlocked_dio(inode); + out_mutex: + mutex_unlock(&inode->i_mutex); +@@ -4823,13 +4824,15 @@ int ext4_setattr(struct dentry *dentry, struct iattr *attr) + } else + ext4_wait_for_tail_page_commit(inode); + } ++ down_write(&EXT4_I(inode)->i_mmap_sem); + /* + * Truncate pagecache after we've waited for commit + * in data=journal mode to make pages freeable. + */ + truncate_pagecache(inode, inode->i_size); + if (shrink) + ext4_truncate(inode); ++ up_write(&EXT4_I(inode)->i_mmap_sem); + } + + if (!rc) { +@@ -5278,6 +5281,8 @@ int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) + + sb_start_pagefault(inode->i_sb); + file_update_time(vma->vm_file); ++ ++ down_read(&EXT4_I(inode)->i_mmap_sem); + /* Delalloc case is easy... */ + if (test_opt(inode->i_sb, DELALLOC) && + !ext4_should_journal_data(inode) && +@@ -5347,6 +5352,19 @@ int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) + out_ret: + ret = block_page_mkwrite_return(ret); + out: ++ up_read(&EXT4_I(inode)->i_mmap_sem); + sb_end_pagefault(inode->i_sb); + return ret; + } ++ ++int ext4_filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf) ++{ ++ struct inode *inode = file_inode(vma->vm_file); ++ int err; ++ ++ down_read(&EXT4_I(inode)->i_mmap_sem); ++ err = filemap_fault(vma, vmf); ++ up_read(&EXT4_I(inode)->i_mmap_sem); ++ ++ return err; ++}",1151,1482,2048 +8214,"struct section_t* MACH0_(get_sections)(struct MACH0_(obj_t)* bin) { + struct section_t *sections; + char segname[32], sectname[32]; + int i, j, to; + + if (!bin) { + return NULL; + } + /* for core files */ + if (bin->nsects < 1 && bin->nsegs > 0) { + struct MACH0_(segment_command) *seg; + if (!(sections = calloc ((bin->nsegs + 1), sizeof (struct section_t)))) { + return NULL; + } + for (i = 0; i < bin->nsegs; i++) { + seg = &bin->segs[i]; + sections[i].addr = seg->vmaddr; + sections[i].offset = seg->fileoff; + sections[i].size = seg->vmsize; + sections[i].vsize = seg->vmsize; + sections[i].align = 4096; + sections[i].flags = seg->flags; + r_str_ncpy (sectname, seg->segname, sizeof (sectname)); + r_str_filter (sectname, -1); + sections[i].srwx = prot2perm (seg->initprot); + sections[i].last = 0; + } + sections[i].last = 1; + return sections; + } + + if (!bin->sects) { + return NULL; + } + to = R_MIN (bin->nsects, 128); // limit number of sections here to avoid fuzzed bins + if (to < 1) { + return NULL; + } + if (!(sections = calloc (bin->nsects + 1, sizeof (struct section_t)))) { + return NULL; + } + for (i = 0; i < to; i++) { + sections[i].offset = (ut64)bin->sects[i].offset; + sections[i].addr = (ut64)bin->sects[i].addr; + sections[i].size = (bin->sects[i].flags == S_ZEROFILL) ? 0 : (ut64)bin->sects[i].size; + sections[i].vsize = (ut64)bin->sects[i].size; + sections[i].align = bin->sects[i].align; + sections[i].flags = bin->sects[i].flags; + r_str_ncpy (sectname, bin->sects[i].sectname, sizeof (sectname)); + r_str_filter (sectname, -1); + snprintf (segname, sizeof (segname), ""%d.%s"", i, bin->sects[i].segname); + for (j = 0; j < bin->nsegs; j++) { + if (sections[i].addr >= bin->segs[j].vmaddr && + sections[i].addr < (bin->segs[j].vmaddr + bin->segs[j].vmsize)) { + sections[i].srwx = prot2perm (bin->segs[j].initprot); + break; + } + } + snprintf (sections[i].name, sizeof (sections[i].name), ""%s.%s"", segname, sectname); + sections[i].last = 0; + } + sections[i].last = 1; + return sections; +} +",0,"struct section_t* MACH0_(get_sections)(struct MACH0_(obj_t)* bin) { + struct section_t *sections; + char segname[32], sectname[32]; + int i, j, to; + + if (!bin) { + return NULL; + } + /* for core files */ + if (bin->nsects < 1 && bin->nsegs > 0) { + struct MACH0_(segment_command) *seg; + if (!(sections = calloc ((bin->nsegs + 1), sizeof (struct section_t)))) { + return NULL; + } + for (i = 0; i < bin->nsegs; i++) { + seg = &bin->segs[i]; + sections[i].addr = seg->vmaddr; + sections[i].offset = seg->fileoff; + sections[i].size = seg->vmsize; + sections[i].vsize = seg->vmsize; + sections[i].align = 4096; + sections[i].flags = seg->flags; + r_str_ncpy (sectname, seg->segname, sizeof (sectname)); + r_str_filter (sectname, -1); + sections[i].srwx = prot2perm (seg->initprot); + sections[i].last = 0; + } + sections[i].last = 1; + return sections; + } + + if (!bin->sects) { + return NULL; + } + to = R_MIN (bin->nsects, 128); // limit number of sections here to avoid fuzzed bins + if (to < 1) { + return NULL; + } + if (!(sections = calloc (bin->nsects + 1, sizeof (struct section_t)))) { + return NULL; + } + for (i = 0; i < to; i++) { + sections[i].offset = (ut64)bin->sects[i].offset; + sections[i].addr = (ut64)bin->sects[i].addr; + sections[i].size = (bin->sects[i].flags == S_ZEROFILL) ? 0 : (ut64)bin->sects[i].size; + sections[i].vsize = (ut64)bin->sects[i].size; + sections[i].align = bin->sects[i].align; + sections[i].flags = bin->sects[i].flags; + r_str_ncpy (sectname, bin->sects[i].sectname, sizeof (sectname)); + r_str_filter (sectname, -1); + snprintf (segname, sizeof (segname), ""%d.%s"", i, bin->sects[i].segname); + for (j = 0; j < bin->nsegs; j++) { + if (sections[i].addr >= bin->segs[j].vmaddr && + sections[i].addr < (bin->segs[j].vmaddr + bin->segs[j].vmsize)) { + sections[i].srwx = prot2perm (bin->segs[j].initprot); + break; + } + } + snprintf (sections[i].name, sizeof (sections[i].name), ""%s.%s"", segname, sectname); + sections[i].last = 0; + } + sections[i].last = 1; + return sections; +} +","@@ -1586,8 +1586,9 @@ struct symbol_t* MACH0_(get_symbols)(struct MACH0_(obj_t)* bin) { + bprintf (""mach0-get-symbols: error\n""); + break; + } +- if (parse_import_stub(bin, &symbols[j], i)) ++ if (parse_import_stub(bin, &symbols[j], i)) { + symbols[j++].last = 0; ++ } + } + + #if 1 +@@ -1662,12 +1663,16 @@ static int parse_import_ptr(struct MACH0_(obj_t)* bin, struct reloc_t *reloc, in + + for (i = 0; i < bin->nsects; i++) { + if ((bin->sects[i].flags & SECTION_TYPE) == stype) { +- for (j=0, sym=-1; bin->sects[i].reserved1+j < bin->nindirectsyms; j++) +- if (idx == bin->indirectsyms[bin->sects[i].reserved1 + j]) { ++ for (j = 0, sym = -1; bin->sects[i].reserved1 + j < bin->nindirectsyms; j++) { ++ int indidx = bin->sects[i].reserved1 + j; ++ if (indidx < 0 || indidx >= bin->nindirectsyms) { ++ break; ++ } ++ if (idx == bin->indirectsyms[indidx]) { + sym = j; + break; + } +- ++ } + reloc->offset = sym == -1 ? 0 : bin->sects[i].offset + sym * wordsize; + reloc->addr = sym == -1 ? 0 : bin->sects[i].addr + sym * wordsize; + return true; +@@ -1681,8 +1686,9 @@ struct import_t* MACH0_(get_imports)(struct MACH0_(obj_t)* bin) { + int i, j, idx, stridx; + const char *symstr; + +- if (!bin->symtab || !bin->symstr || !bin->sects || !bin->indirectsyms) ++ if (!bin->symtab || !bin->symstr || !bin->sects || !bin->indirectsyms) { + return NULL; ++ } + if (bin->dysymtab.nundefsym < 1 || bin->dysymtab.nundefsym > 0xfffff) { + return NULL; + }",731,1062,2048 +930,"void vrend_renderer_blit_gl(struct vrend_context *ctx, + struct vrend_resource *src_res, + struct vrend_resource *dst_res, + const struct pipe_blit_info *info) +{ + struct vrend_blitter_ctx *blit_ctx = &vrend_blit_ctx; + GLuint prog_id; + GLuint fs_id; + GLint lret; + GLenum filter; + GLuint pos_loc, tc_loc; + GLuint samp_loc; + bool has_depth, has_stencil; + bool blit_stencil, blit_depth; + int dst_z; + const struct util_format_description *src_desc = + util_format_description(src_res->base.format); + const struct util_format_description *dst_desc = + util_format_description(dst_res->base.format); + + has_depth = util_format_has_depth(src_desc) && + util_format_has_depth(dst_desc); + has_stencil = util_format_has_stencil(src_desc) && + util_format_has_stencil(dst_desc); + + blit_depth = has_depth && (info->mask & PIPE_MASK_Z); + blit_stencil = has_stencil && (info->mask & PIPE_MASK_S) & 0; + + filter = convert_mag_filter(info->filter); + vrend_renderer_init_blit_ctx(blit_ctx); + + blitter_set_dst_dim(blit_ctx, + u_minify(dst_res->base.width0, info->dst.level), + u_minify(dst_res->base.height0, info->dst.level)); + + blitter_set_rectangle(blit_ctx, info->dst.box.x, info->dst.box.y, + info->dst.box.x + info->dst.box.width, + info->dst.box.y + info->dst.box.height, 0); + + + prog_id = glCreateProgram(); + glAttachShader(prog_id, blit_ctx->vs); + + if (blit_depth || blit_stencil) + fs_id = blit_get_frag_tex_writedepth(blit_ctx, src_res->base.target, src_res->base.nr_samples); + else if (vrend_format_is_emulated_alpha(info->dst.format)) + fs_id = blit_get_frag_tex_col_emu_alpha(blit_ctx, src_res->base.target, src_res->base.nr_samples); + else + fs_id = blit_get_frag_tex_col(blit_ctx, src_res->base.target, src_res->base.nr_samples); + glAttachShader(prog_id, fs_id); + + glLinkProgram(prog_id); + glGetProgramiv(prog_id, GL_LINK_STATUS, &lret); + if (lret == GL_FALSE) { + char infolog[65536]; + int len; + glGetProgramInfoLog(prog_id, 65536, &len, infolog); + fprintf(stderr,""got error linking\n%s\n"", infolog); + /* dump shaders */ + glDeleteProgram(prog_id); + return; + } + + glUseProgram(prog_id); + + glBindFramebuffer(GL_FRAMEBUFFER_EXT, blit_ctx->fb_id); + vrend_fb_bind_texture(dst_res, 0, info->dst.level, info->dst.box.z); + + glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT); + + glBindTexture(src_res->target, src_res->id); + + if (vrend_format_is_emulated_alpha(info->src.format)) + glTexParameteri(src_res->target, GL_TEXTURE_SWIZZLE_R, GL_ALPHA); + + glTexParameteri(src_res->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(src_res->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(src_res->target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); + + glTexParameteri(src_res->target, GL_TEXTURE_BASE_LEVEL, info->src.level); + glTexParameteri(src_res->target, GL_TEXTURE_MAX_LEVEL, info->src.level); + glTexParameterf(src_res->target, GL_TEXTURE_MAG_FILTER, filter); + glTexParameterf(src_res->target, GL_TEXTURE_MIN_FILTER, filter); + pos_loc = glGetAttribLocation(prog_id, ""arg0""); + tc_loc = glGetAttribLocation(prog_id, ""arg1""); + samp_loc = glGetUniformLocation(prog_id, ""samp""); + + glUniform1i(samp_loc, 0); + + glVertexAttribPointer(pos_loc, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void *)0); + glVertexAttribPointer(tc_loc, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void *)(4 * sizeof(float))); + + glEnableVertexAttribArray(pos_loc); + glEnableVertexAttribArray(tc_loc); + + set_dsa_write_depth_keep_stencil(); + + for (dst_z = 0; dst_z < info->dst.box.depth; dst_z++) { + float dst2src_scale = info->src.box.depth / (float)info->dst.box.depth; + float dst_offset = ((info->src.box.depth - 1) - + (info->dst.box.depth - 1) * dst2src_scale) * 0.5; + float src_z = (dst_z + dst_offset) * dst2src_scale; + + glBindFramebuffer(GL_FRAMEBUFFER_EXT, blit_ctx->fb_id); + vrend_fb_bind_texture(dst_res, 0, info->dst.level, dst_z); + + glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT); + blitter_set_texcoords(blit_ctx, src_res, info->src.level, + info->src.box.z + src_z, 0, + info->src.box.x, info->src.box.y, + info->src.box.x + info->src.box.width, + info->src.box.y + info->src.box.height); + + glBufferData(GL_ARRAY_BUFFER, sizeof(blit_ctx->vertices), blit_ctx->vertices, GL_STATIC_DRAW); + glDrawArrays(GL_TRIANGLE_FAN, 0, 4); + } +} +",0,"void vrend_renderer_blit_gl(struct vrend_context *ctx, + struct vrend_resource *src_res, + struct vrend_resource *dst_res, + const struct pipe_blit_info *info) +{ + struct vrend_blitter_ctx *blit_ctx = &vrend_blit_ctx; + GLuint prog_id; + GLuint fs_id; + GLint lret; + GLenum filter; + GLuint pos_loc, tc_loc; + GLuint samp_loc; + bool has_depth, has_stencil; + bool blit_stencil, blit_depth; + int dst_z; + const struct util_format_description *src_desc = + util_format_description(src_res->base.format); + const struct util_format_description *dst_desc = + util_format_description(dst_res->base.format); + + has_depth = util_format_has_depth(src_desc) && + util_format_has_depth(dst_desc); + has_stencil = util_format_has_stencil(src_desc) && + util_format_has_stencil(dst_desc); + + blit_depth = has_depth && (info->mask & PIPE_MASK_Z); + blit_stencil = has_stencil && (info->mask & PIPE_MASK_S) & 0; + + filter = convert_mag_filter(info->filter); + vrend_renderer_init_blit_ctx(blit_ctx); + + blitter_set_dst_dim(blit_ctx, + u_minify(dst_res->base.width0, info->dst.level), + u_minify(dst_res->base.height0, info->dst.level)); + + blitter_set_rectangle(blit_ctx, info->dst.box.x, info->dst.box.y, + info->dst.box.x + info->dst.box.width, + info->dst.box.y + info->dst.box.height, 0); + + + prog_id = glCreateProgram(); + glAttachShader(prog_id, blit_ctx->vs); + + if (blit_depth || blit_stencil) + fs_id = blit_get_frag_tex_writedepth(blit_ctx, src_res->base.target, src_res->base.nr_samples); + else if (vrend_format_is_emulated_alpha(info->dst.format)) + fs_id = blit_get_frag_tex_col_emu_alpha(blit_ctx, src_res->base.target, src_res->base.nr_samples); + else + fs_id = blit_get_frag_tex_col(blit_ctx, src_res->base.target, src_res->base.nr_samples); + glAttachShader(prog_id, fs_id); + + glLinkProgram(prog_id); + glGetProgramiv(prog_id, GL_LINK_STATUS, &lret); + if (lret == GL_FALSE) { + char infolog[65536]; + int len; + glGetProgramInfoLog(prog_id, 65536, &len, infolog); + fprintf(stderr,""got error linking\n%s\n"", infolog); + /* dump shaders */ + glDeleteProgram(prog_id); + return; + } + + glUseProgram(prog_id); + + glBindFramebuffer(GL_FRAMEBUFFER_EXT, blit_ctx->fb_id); + vrend_fb_bind_texture(dst_res, 0, info->dst.level, info->dst.box.z); + + glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT); + + glBindTexture(src_res->target, src_res->id); + + if (vrend_format_is_emulated_alpha(info->src.format)) + glTexParameteri(src_res->target, GL_TEXTURE_SWIZZLE_R, GL_ALPHA); + + glTexParameteri(src_res->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(src_res->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(src_res->target, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); + + glTexParameteri(src_res->target, GL_TEXTURE_BASE_LEVEL, info->src.level); + glTexParameteri(src_res->target, GL_TEXTURE_MAX_LEVEL, info->src.level); + glTexParameterf(src_res->target, GL_TEXTURE_MAG_FILTER, filter); + glTexParameterf(src_res->target, GL_TEXTURE_MIN_FILTER, filter); + pos_loc = glGetAttribLocation(prog_id, ""arg0""); + tc_loc = glGetAttribLocation(prog_id, ""arg1""); + samp_loc = glGetUniformLocation(prog_id, ""samp""); + + glUniform1i(samp_loc, 0); + + glVertexAttribPointer(pos_loc, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void *)0); + glVertexAttribPointer(tc_loc, 4, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void *)(4 * sizeof(float))); + + glEnableVertexAttribArray(pos_loc); + glEnableVertexAttribArray(tc_loc); + + set_dsa_write_depth_keep_stencil(); + + for (dst_z = 0; dst_z < info->dst.box.depth; dst_z++) { + float dst2src_scale = info->src.box.depth / (float)info->dst.box.depth; + float dst_offset = ((info->src.box.depth - 1) - + (info->dst.box.depth - 1) * dst2src_scale) * 0.5; + float src_z = (dst_z + dst_offset) * dst2src_scale; + + glBindFramebuffer(GL_FRAMEBUFFER_EXT, blit_ctx->fb_id); + vrend_fb_bind_texture(dst_res, 0, info->dst.level, dst_z); + + glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT); + blitter_set_texcoords(blit_ctx, src_res, info->src.level, + info->src.box.z + src_z, 0, + info->src.box.x, info->src.box.y, + info->src.box.x + info->src.box.width, + info->src.box.y + info->src.box.height); + + glBufferData(GL_ARRAY_BUFFER, sizeof(blit_ctx->vertices), blit_ctx->vertices, GL_STATIC_DRAW); + glDrawArrays(GL_TRIANGLE_FAN, 0, 4); + } +} +","@@ -361,6 +361,7 @@ static void vrend_renderer_init_blit_ctx(struct vrend_blitter_ctx *blit_ctx) + return; + } + ++ blit_ctx->initialised = true; + ctx_params.shared = true; + ctx_params.major_ver = VREND_GL_VER_MAJOR; + ctx_params.minor_ver = VREND_GL_VER_MINOR;",1212,1543,2048 +18808,"void impeg2d_dec_hdr(void *pv_dec,impeg2d_video_decode_ip_t *ps_ip, + impeg2d_video_decode_op_t *ps_op) +{ + + UWORD32 u4_bits_read; + dec_state_t *ps_dec; + UWORD32 u4_size = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes; + + ps_dec = (dec_state_t *)pv_dec; + ps_op->s_ivd_video_decode_op_t.u4_error_code = 0; + if (u4_size > MAX_BITSTREAM_BUFFER_SIZE) + { + u4_size = MAX_BITSTREAM_BUFFER_SIZE; + } + + memcpy(ps_dec->pu1_input_buffer, ps_ip->s_ivd_video_decode_ip_t.pv_stream_buffer, u4_size); + + impeg2d_bit_stream_init(&(ps_dec->s_bit_stream), ps_dec->pu1_input_buffer, + u4_size); + + { + { + IMPEG2D_ERROR_CODES_T e_error; + e_error = impeg2d_process_video_header(ps_dec); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + ps_op->s_ivd_video_decode_op_t.u4_error_code = e_error; + + u4_bits_read = impeg2d_bit_stream_num_bits_read(&ps_dec->s_bit_stream); + + ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = u4_bits_read>> 3; + if(ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed > ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes) + { + ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes; + } + if(ps_op->s_ivd_video_decode_op_t.u4_error_code == 0) + ps_op->s_ivd_video_decode_op_t.u4_error_code = e_error; + + if (IMPEG2D_UNSUPPORTED_DIMENSIONS == e_error) + { + ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = 0; + ps_dec->u2_header_done = 0; + + ps_op->s_ivd_video_decode_op_t.u4_pic_ht = ps_dec->u2_reinit_max_height; + ps_op->s_ivd_video_decode_op_t.u4_pic_wd = ps_dec->u2_reinit_max_width; + } + impeg2d_next_code(ps_dec, SEQUENCE_HEADER_CODE); + return; + } + } + ps_op->s_ivd_video_decode_op_t.u4_pic_ht = ps_dec->u2_vertical_size; + ps_op->s_ivd_video_decode_op_t.u4_pic_wd = ps_dec->u2_horizontal_size; + + ps_op->s_ivd_video_decode_op_t.e_pic_type = IV_NA_FRAME; + ps_op->s_ivd_video_decode_op_t.u4_error_code = IV_SUCCESS; + + u4_bits_read = impeg2d_bit_stream_num_bits_read(&ps_dec->s_bit_stream); + ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = u4_bits_read>> 3; + if(ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed > ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes) + { + + ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes; + } + ps_op->s_ivd_video_decode_op_t.u4_frame_decoded_flag = 0; + /* MOD */ + ps_dec->u2_header_done = 1; + + } +} +",1,"void impeg2d_dec_hdr(void *pv_dec,impeg2d_video_decode_ip_t *ps_ip, + impeg2d_video_decode_op_t *ps_op) +{ + + UWORD32 u4_bits_read; + dec_state_t *ps_dec; + UWORD32 u4_size = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes; + + ps_dec = (dec_state_t *)pv_dec; + ps_op->s_ivd_video_decode_op_t.u4_error_code = 0; + if (u4_size > MAX_BITSTREAM_BUFFER_SIZE) + { + u4_size = MAX_BITSTREAM_BUFFER_SIZE; + } + + memcpy(ps_dec->pu1_input_buffer, ps_ip->s_ivd_video_decode_ip_t.pv_stream_buffer, u4_size); + + impeg2d_bit_stream_init(&(ps_dec->s_bit_stream), ps_dec->pu1_input_buffer, + u4_size); + + { + { + IMPEG2D_ERROR_CODES_T e_error; + e_error = impeg2d_process_video_header(ps_dec); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + ps_op->s_ivd_video_decode_op_t.u4_error_code = e_error; + + u4_bits_read = impeg2d_bit_stream_num_bits_read(&ps_dec->s_bit_stream); + + ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = u4_bits_read>> 3; + if(ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed > ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes) + { + ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes; + } + if(ps_op->s_ivd_video_decode_op_t.u4_error_code == 0) + ps_op->s_ivd_video_decode_op_t.u4_error_code = e_error; + + if (IMPEG2D_UNSUPPORTED_DIMENSIONS == e_error) + { + ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = 0; + ps_dec->u2_header_done = 0; + + ps_op->s_ivd_video_decode_op_t.u4_pic_ht = ps_dec->u2_reinit_max_height; + ps_op->s_ivd_video_decode_op_t.u4_pic_wd = ps_dec->u2_reinit_max_width; + } + impeg2d_next_code(ps_dec, SEQUENCE_HEADER_CODE); + return; + } + } + ps_op->s_ivd_video_decode_op_t.u4_pic_ht = ps_dec->u2_vertical_size; + ps_op->s_ivd_video_decode_op_t.u4_pic_wd = ps_dec->u2_horizontal_size; + + ps_op->s_ivd_video_decode_op_t.e_pic_type = IV_NA_FRAME; + ps_op->s_ivd_video_decode_op_t.u4_error_code = IV_SUCCESS; + + u4_bits_read = impeg2d_bit_stream_num_bits_read(&ps_dec->s_bit_stream); + ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = u4_bits_read>> 3; + if(ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed > ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes) + { + + ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes; + } + ps_op->s_ivd_video_decode_op_t.u4_frame_decoded_flag = 0; + + /* Set the stride */ + if (0 == ps_dec->u4_frm_buf_stride) + { + ps_dec->u4_frm_buf_stride = ps_dec->u2_horizontal_size; + } + /* MOD */ + ps_dec->u2_header_done = 1; + + } +} +","@@ -155,6 +155,12 @@ + + ps_op->s_ivd_video_decode_op_t.u4_num_bytes_consumed = ps_ip->s_ivd_video_decode_ip_t.u4_num_Bytes; + } + ps_op->s_ivd_video_decode_op_t.u4_frame_decoded_flag = 0; ++ ++ /* Set the stride */ ++ if (0 == ps_dec->u4_frm_buf_stride) ++ { ++ ps_dec->u4_frm_buf_stride = ps_dec->u2_horizontal_size; ++ } + /* MOD */ + ps_dec->u2_header_done = 1; + +",789,1120,2048 +8896,"compile_quantifier_node(QuantNode* qn, regex_t* reg, ScanEnv* env) +{ + int i, r, mod_tlen; + int infinite = IS_REPEAT_INFINITE(qn->upper); + enum BodyEmpty empty_info = qn->empty_info; + int tlen = compile_length_tree(NODE_QUANT_BODY(qn), reg); + + if (tlen < 0) return tlen; + if (tlen == 0) return 0; + + if (is_anychar_infinite_greedy(qn) && + (qn->lower <= 1 || + int_multiply_cmp(tlen, qn->lower, QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) { + r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env); + if (r != 0) return r; + if (IS_NOT_NULL(qn->next_head_exact)) { + r = add_op(reg, + IS_MULTILINE(CTYPE_OPTION(NODE_QUANT_BODY(qn), reg)) ? + OP_ANYCHAR_ML_STAR_PEEK_NEXT : OP_ANYCHAR_STAR_PEEK_NEXT); + if (r != 0) return r; + + COP(reg)->anychar_star_peek_next.c = STR_(qn->next_head_exact)->s[0]; + return 0; + } + else { + r = add_op(reg, + IS_MULTILINE(CTYPE_OPTION(NODE_QUANT_BODY(qn), reg)) ? + OP_ANYCHAR_ML_STAR : OP_ANYCHAR_STAR); + return r; + } + } + + if (empty_info == BODY_IS_NOT_EMPTY) + mod_tlen = tlen; + else + mod_tlen = tlen + (SIZE_OP_EMPTY_CHECK_START + SIZE_OP_EMPTY_CHECK_END); + + if (infinite && + (qn->lower <= 1 || + int_multiply_cmp(tlen, qn->lower, QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) { + int addr; + + if (qn->lower == 1 && tlen > QUANTIFIER_EXPAND_LIMIT_SIZE) { + r = add_op(reg, OP_JUMP); + if (r != 0) return r; + if (qn->greedy) { +#ifdef USE_OP_PUSH_OR_JUMP_EXACT + if (IS_NOT_NULL(qn->head_exact)) + COP(reg)->jump.addr = SIZE_OP_PUSH_OR_JUMP_EXACT1 + SIZE_INC_OP; + else +#endif + if (IS_NOT_NULL(qn->next_head_exact)) + COP(reg)->jump.addr = SIZE_OP_PUSH_IF_PEEK_NEXT + SIZE_INC_OP; + else + COP(reg)->jump.addr = SIZE_OP_PUSH + SIZE_INC_OP; + } + else { + COP(reg)->jump.addr = SIZE_OP_JUMP + SIZE_INC_OP; + } + } + else { + r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env); + if (r != 0) return r; + } + + if (qn->greedy) { +#ifdef USE_OP_PUSH_OR_JUMP_EXACT + if (IS_NOT_NULL(qn->head_exact)) { + r = add_op(reg, OP_PUSH_OR_JUMP_EXACT1); + if (r != 0) return r; + COP(reg)->push_or_jump_exact1.addr = SIZE_INC_OP + mod_tlen + SIZE_OP_JUMP; + COP(reg)->push_or_jump_exact1.c = STR_(qn->head_exact)->s[0]; + + r = compile_tree_empty_check(NODE_QUANT_BODY(qn), reg, empty_info, env); + if (r != 0) return r; + + addr = -(mod_tlen + (int )SIZE_OP_PUSH_OR_JUMP_EXACT1); + } + else +#endif + if (IS_NOT_NULL(qn->next_head_exact)) { + r = add_op(reg, OP_PUSH_IF_PEEK_NEXT); + if (r != 0) return r; + COP(reg)->push_if_peek_next.addr = SIZE_INC_OP + mod_tlen + SIZE_OP_JUMP; + COP(reg)->push_if_peek_next.c = STR_(qn->next_head_exact)->s[0]; + + r = compile_tree_empty_check(NODE_QUANT_BODY(qn), reg, empty_info, env); + if (r != 0) return r; + + addr = -(mod_tlen + (int )SIZE_OP_PUSH_IF_PEEK_NEXT); + } + else { + r = add_op(reg, OP_PUSH); + if (r != 0) return r; + COP(reg)->push.addr = SIZE_INC_OP + mod_tlen + SIZE_OP_JUMP; + + r = compile_tree_empty_check(NODE_QUANT_BODY(qn), reg, empty_info, env); + if (r != 0) return r; + + addr = -(mod_tlen + (int )SIZE_OP_PUSH); + } + + r = add_op(reg, OP_JUMP); + if (r != 0) return r; + COP(reg)->jump.addr = addr; + } + else { + r = add_op(reg, OP_JUMP); + if (r != 0) return r; + COP(reg)->jump.addr = mod_tlen + SIZE_INC_OP; + + r = compile_tree_empty_check(NODE_QUANT_BODY(qn), reg, empty_info, env); + if (r != 0) return r; + + r = add_op(reg, OP_PUSH); + if (r != 0) return r; + COP(reg)->push.addr = -mod_tlen; + } + } + else if (qn->upper == 0) { + if (qn->is_refered != 0) { /* /(?..){0}/ */ + r = add_op(reg, OP_JUMP); + if (r != 0) return r; + COP(reg)->jump.addr = tlen + SIZE_INC_OP; + + r = compile_tree(NODE_QUANT_BODY(qn), reg, env); + } + else { + /* Nothing output */ + r = 0; + } + } + else if (! infinite && qn->greedy && + (qn->upper == 1 || + int_multiply_cmp(tlen + SIZE_OP_PUSH, qn->upper, + QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) { + int n = qn->upper - qn->lower; + + r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env); + if (r != 0) return r; + + for (i = 0; i < n; i++) { + int v = onig_positive_int_multiply(n - i, tlen + SIZE_OP_PUSH); + if (v < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; + + r = add_op(reg, OP_PUSH); + if (r != 0) return r; + COP(reg)->push.addr = v; + + r = compile_tree(NODE_QUANT_BODY(qn), reg, env); + if (r != 0) return r; + } + } + else if (! qn->greedy && qn->upper == 1 && qn->lower == 0) { /* '??' */ + r = add_op(reg, OP_PUSH); + if (r != 0) return r; + COP(reg)->push.addr = SIZE_INC_OP + SIZE_OP_JUMP; + + r = add_op(reg, OP_JUMP); + if (r != 0) return r; + COP(reg)->jump.addr = tlen + SIZE_INC_OP; + + r = compile_tree(NODE_QUANT_BODY(qn), reg, env); + } + else { + r = compile_range_repeat_node(qn, mod_tlen, empty_info, reg, env); + } + return r; +} +",0,"compile_quantifier_node(QuantNode* qn, regex_t* reg, ScanEnv* env) +{ + int i, r, mod_tlen; + int infinite = IS_REPEAT_INFINITE(qn->upper); + enum BodyEmpty empty_info = qn->empty_info; + int tlen = compile_length_tree(NODE_QUANT_BODY(qn), reg); + + if (tlen < 0) return tlen; + if (tlen == 0) return 0; + + if (is_anychar_infinite_greedy(qn) && + (qn->lower <= 1 || + int_multiply_cmp(tlen, qn->lower, QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) { + r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env); + if (r != 0) return r; + if (IS_NOT_NULL(qn->next_head_exact)) { + r = add_op(reg, + IS_MULTILINE(CTYPE_OPTION(NODE_QUANT_BODY(qn), reg)) ? + OP_ANYCHAR_ML_STAR_PEEK_NEXT : OP_ANYCHAR_STAR_PEEK_NEXT); + if (r != 0) return r; + + COP(reg)->anychar_star_peek_next.c = STR_(qn->next_head_exact)->s[0]; + return 0; + } + else { + r = add_op(reg, + IS_MULTILINE(CTYPE_OPTION(NODE_QUANT_BODY(qn), reg)) ? + OP_ANYCHAR_ML_STAR : OP_ANYCHAR_STAR); + return r; + } + } + + if (empty_info == BODY_IS_NOT_EMPTY) + mod_tlen = tlen; + else + mod_tlen = tlen + (SIZE_OP_EMPTY_CHECK_START + SIZE_OP_EMPTY_CHECK_END); + + if (infinite && + (qn->lower <= 1 || + int_multiply_cmp(tlen, qn->lower, QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) { + int addr; + + if (qn->lower == 1 && tlen > QUANTIFIER_EXPAND_LIMIT_SIZE) { + r = add_op(reg, OP_JUMP); + if (r != 0) return r; + if (qn->greedy) { +#ifdef USE_OP_PUSH_OR_JUMP_EXACT + if (IS_NOT_NULL(qn->head_exact)) + COP(reg)->jump.addr = SIZE_OP_PUSH_OR_JUMP_EXACT1 + SIZE_INC_OP; + else +#endif + if (IS_NOT_NULL(qn->next_head_exact)) + COP(reg)->jump.addr = SIZE_OP_PUSH_IF_PEEK_NEXT + SIZE_INC_OP; + else + COP(reg)->jump.addr = SIZE_OP_PUSH + SIZE_INC_OP; + } + else { + COP(reg)->jump.addr = SIZE_OP_JUMP + SIZE_INC_OP; + } + } + else { + r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env); + if (r != 0) return r; + } + + if (qn->greedy) { +#ifdef USE_OP_PUSH_OR_JUMP_EXACT + if (IS_NOT_NULL(qn->head_exact)) { + r = add_op(reg, OP_PUSH_OR_JUMP_EXACT1); + if (r != 0) return r; + COP(reg)->push_or_jump_exact1.addr = SIZE_INC_OP + mod_tlen + SIZE_OP_JUMP; + COP(reg)->push_or_jump_exact1.c = STR_(qn->head_exact)->s[0]; + + r = compile_tree_empty_check(NODE_QUANT_BODY(qn), reg, empty_info, env); + if (r != 0) return r; + + addr = -(mod_tlen + (int )SIZE_OP_PUSH_OR_JUMP_EXACT1); + } + else +#endif + if (IS_NOT_NULL(qn->next_head_exact)) { + r = add_op(reg, OP_PUSH_IF_PEEK_NEXT); + if (r != 0) return r; + COP(reg)->push_if_peek_next.addr = SIZE_INC_OP + mod_tlen + SIZE_OP_JUMP; + COP(reg)->push_if_peek_next.c = STR_(qn->next_head_exact)->s[0]; + + r = compile_tree_empty_check(NODE_QUANT_BODY(qn), reg, empty_info, env); + if (r != 0) return r; + + addr = -(mod_tlen + (int )SIZE_OP_PUSH_IF_PEEK_NEXT); + } + else { + r = add_op(reg, OP_PUSH); + if (r != 0) return r; + COP(reg)->push.addr = SIZE_INC_OP + mod_tlen + SIZE_OP_JUMP; + + r = compile_tree_empty_check(NODE_QUANT_BODY(qn), reg, empty_info, env); + if (r != 0) return r; + + addr = -(mod_tlen + (int )SIZE_OP_PUSH); + } + + r = add_op(reg, OP_JUMP); + if (r != 0) return r; + COP(reg)->jump.addr = addr; + } + else { + r = add_op(reg, OP_JUMP); + if (r != 0) return r; + COP(reg)->jump.addr = mod_tlen + SIZE_INC_OP; + + r = compile_tree_empty_check(NODE_QUANT_BODY(qn), reg, empty_info, env); + if (r != 0) return r; + + r = add_op(reg, OP_PUSH); + if (r != 0) return r; + COP(reg)->push.addr = -mod_tlen; + } + } + else if (qn->upper == 0) { + if (qn->is_refered != 0) { /* /(?..){0}/ */ + r = add_op(reg, OP_JUMP); + if (r != 0) return r; + COP(reg)->jump.addr = tlen + SIZE_INC_OP; + + r = compile_tree(NODE_QUANT_BODY(qn), reg, env); + } + else { + /* Nothing output */ + r = 0; + } + } + else if (! infinite && qn->greedy && + (qn->upper == 1 || + int_multiply_cmp(tlen + SIZE_OP_PUSH, qn->upper, + QUANTIFIER_EXPAND_LIMIT_SIZE) <= 0)) { + int n = qn->upper - qn->lower; + + r = compile_tree_n_times(NODE_QUANT_BODY(qn), qn->lower, reg, env); + if (r != 0) return r; + + for (i = 0; i < n; i++) { + int v = onig_positive_int_multiply(n - i, tlen + SIZE_OP_PUSH); + if (v < 0) return ONIGERR_TOO_BIG_NUMBER_FOR_REPEAT_RANGE; + + r = add_op(reg, OP_PUSH); + if (r != 0) return r; + COP(reg)->push.addr = v; + + r = compile_tree(NODE_QUANT_BODY(qn), reg, env); + if (r != 0) return r; + } + } + else if (! qn->greedy && qn->upper == 1 && qn->lower == 0) { /* '??' */ + r = add_op(reg, OP_PUSH); + if (r != 0) return r; + COP(reg)->push.addr = SIZE_INC_OP + SIZE_OP_JUMP; + + r = add_op(reg, OP_JUMP); + if (r != 0) return r; + COP(reg)->jump.addr = tlen + SIZE_INC_OP; + + r = compile_tree(NODE_QUANT_BODY(qn), reg, env); + } + else { + r = compile_range_repeat_node(qn, mod_tlen, empty_info, reg, env); + } + return r; +} +","@@ -1307,8 +1307,9 @@ compile_length_bag_node(BagNode* node, regex_t* reg) + len += tlen; + } + ++ len += SIZE_OP_JUMP + SIZE_OP_ATOMIC_END; ++ + if (IS_NOT_NULL(Else)) { +- len += SIZE_OP_JUMP; + tlen = compile_length_tree(Else, reg); + if (tlen < 0) return tlen; + len += tlen; +@@ -1455,7 +1456,7 @@ compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env) + + case BAG_IF_ELSE: + { +- int cond_len, then_len, jump_len; ++ int cond_len, then_len, else_len, jump_len; + Node* cond = NODE_BAG_BODY(node); + Node* Then = node->te.Then; + Node* Else = node->te.Else; +@@ -1472,8 +1473,7 @@ compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env) + else + then_len = 0; + +- jump_len = cond_len + then_len + SIZE_OP_ATOMIC_END; +- if (IS_NOT_NULL(Else)) jump_len += SIZE_OP_JUMP; ++ jump_len = cond_len + then_len + SIZE_OP_ATOMIC_END + SIZE_OP_JUMP; + + r = add_op(reg, OP_PUSH); + if (r != 0) return r; +@@ -1490,11 +1490,20 @@ compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env) + } + + if (IS_NOT_NULL(Else)) { +- int else_len = compile_length_tree(Else, reg); +- r = add_op(reg, OP_JUMP); +- if (r != 0) return r; +- COP(reg)->jump.addr = else_len + SIZE_INC_OP; ++ else_len = compile_length_tree(Else, reg); ++ if (else_len < 0) return else_len; ++ } ++ else ++ else_len = 0; + ++ r = add_op(reg, OP_JUMP); ++ if (r != 0) return r; ++ COP(reg)->jump.addr = SIZE_OP_ATOMIC_END + else_len + SIZE_INC_OP; ++ ++ r = add_op(reg, OP_ATOMIC_END); ++ if (r != 0) return r; ++ ++ if (IS_NOT_NULL(Else)) { + r = compile_tree(Else, reg, env); + } + }",1649,1980,2048 +5747,"int nfs41_sequence_done(struct rpc_task *task, struct nfs4_sequence_res *res) +{ + struct nfs4_session *session; + struct nfs4_slot *slot = res->sr_slot; + struct nfs_client *clp; + bool interrupted = false; + int ret = 1; + + if (slot == NULL) + goto out_noaction; + /* don't increment the sequence number if the task wasn't sent */ + if (!RPC_WAS_SENT(task)) + goto out; + + session = slot->table->session; + + if (slot->interrupted) { + slot->interrupted = 0; + interrupted = true; + } + + trace_nfs4_sequence_done(session, res); + /* Check the SEQUENCE operation status */ + switch (res->sr_status) { + case 0: + /* Update the slot's sequence and clientid lease timer */ + ++slot->seq_nr; + clp = session->clp; + do_renew_lease(clp, res->sr_timestamp); + /* Check sequence flags */ + nfs41_handle_sequence_flag_errors(clp, res->sr_status_flags); + nfs41_update_target_slotid(slot->table, slot, res); + break; + case 1: + /* + * sr_status remains 1 if an RPC level error occurred. + * The server may or may not have processed the sequence + * operation.. + * Mark the slot as having hosted an interrupted RPC call. + */ + slot->interrupted = 1; + goto out; + case -NFS4ERR_DELAY: + /* The server detected a resend of the RPC call and + * returned NFS4ERR_DELAY as per Section 2.10.6.2 + * of RFC5661. + */ + dprintk(""%s: slot=%u seq=%u: Operation in progress\n"", + __func__, + slot->slot_nr, + slot->seq_nr); + goto out_retry; + case -NFS4ERR_BADSLOT: + /* + * The slot id we used was probably retired. Try again + * using a different slot id. + */ + goto retry_nowait; + case -NFS4ERR_SEQ_MISORDERED: + /* + * Was the last operation on this sequence interrupted? + * If so, retry after bumping the sequence number. + */ + if (interrupted) { + ++slot->seq_nr; + goto retry_nowait; + } + /* + * Could this slot have been previously retired? + * If so, then the server may be expecting seq_nr = 1! + */ + if (slot->seq_nr != 1) { + slot->seq_nr = 1; + goto retry_nowait; + } + break; + case -NFS4ERR_SEQ_FALSE_RETRY: + ++slot->seq_nr; + goto retry_nowait; + default: + /* Just update the slot sequence no. */ + ++slot->seq_nr; + } +out: + /* The session may be reset by one of the error handlers. */ + dprintk(""%s: Error %d free the slot \n"", __func__, res->sr_status); + nfs41_sequence_free_slot(res); +out_noaction: + return ret; +retry_nowait: + if (rpc_restart_call_prepare(task)) { + task->tk_status = 0; + ret = 0; + } + goto out; +out_retry: + if (!rpc_restart_call(task)) + goto out; + rpc_delay(task, NFS4_POLL_RETRY_MAX); + return 0; +} +",0,"int nfs41_sequence_done(struct rpc_task *task, struct nfs4_sequence_res *res) +{ + struct nfs4_session *session; + struct nfs4_slot *slot = res->sr_slot; + struct nfs_client *clp; + bool interrupted = false; + int ret = 1; + + if (slot == NULL) + goto out_noaction; + /* don't increment the sequence number if the task wasn't sent */ + if (!RPC_WAS_SENT(task)) + goto out; + + session = slot->table->session; + + if (slot->interrupted) { + slot->interrupted = 0; + interrupted = true; + } + + trace_nfs4_sequence_done(session, res); + /* Check the SEQUENCE operation status */ + switch (res->sr_status) { + case 0: + /* Update the slot's sequence and clientid lease timer */ + ++slot->seq_nr; + clp = session->clp; + do_renew_lease(clp, res->sr_timestamp); + /* Check sequence flags */ + nfs41_handle_sequence_flag_errors(clp, res->sr_status_flags); + nfs41_update_target_slotid(slot->table, slot, res); + break; + case 1: + /* + * sr_status remains 1 if an RPC level error occurred. + * The server may or may not have processed the sequence + * operation.. + * Mark the slot as having hosted an interrupted RPC call. + */ + slot->interrupted = 1; + goto out; + case -NFS4ERR_DELAY: + /* The server detected a resend of the RPC call and + * returned NFS4ERR_DELAY as per Section 2.10.6.2 + * of RFC5661. + */ + dprintk(""%s: slot=%u seq=%u: Operation in progress\n"", + __func__, + slot->slot_nr, + slot->seq_nr); + goto out_retry; + case -NFS4ERR_BADSLOT: + /* + * The slot id we used was probably retired. Try again + * using a different slot id. + */ + goto retry_nowait; + case -NFS4ERR_SEQ_MISORDERED: + /* + * Was the last operation on this sequence interrupted? + * If so, retry after bumping the sequence number. + */ + if (interrupted) { + ++slot->seq_nr; + goto retry_nowait; + } + /* + * Could this slot have been previously retired? + * If so, then the server may be expecting seq_nr = 1! + */ + if (slot->seq_nr != 1) { + slot->seq_nr = 1; + goto retry_nowait; + } + break; + case -NFS4ERR_SEQ_FALSE_RETRY: + ++slot->seq_nr; + goto retry_nowait; + default: + /* Just update the slot sequence no. */ + ++slot->seq_nr; + } +out: + /* The session may be reset by one of the error handlers. */ + dprintk(""%s: Error %d free the slot \n"", __func__, res->sr_status); + nfs41_sequence_free_slot(res); +out_noaction: + return ret; +retry_nowait: + if (rpc_restart_call_prepare(task)) { + task->tk_status = 0; + ret = 0; + } + goto out; +out_retry: + if (!rpc_restart_call(task)) + goto out; + rpc_delay(task, NFS4_POLL_RETRY_MAX); + return 0; +} +","@@ -8661,6 +8661,7 @@ static const struct nfs4_minor_version_ops nfs_v4_2_minor_ops = { + .reboot_recovery_ops = &nfs41_reboot_recovery_ops, + .nograce_recovery_ops = &nfs41_nograce_recovery_ops, + .state_renewal_ops = &nfs41_state_renewal_ops, ++ .mig_recovery_ops = &nfs41_mig_recovery_ops, + }; + #endif + ",751,1082,2048 +4226,"int ipv6_dev_get_saddr(struct net *net, const struct net_device *dst_dev, + const struct in6_addr *daddr, unsigned int prefs, + struct in6_addr *saddr) +{ + struct ipv6_saddr_score scores[2], + *score = &scores[0], *hiscore = &scores[1]; + struct ipv6_saddr_dst dst; + struct net_device *dev; + int dst_type; + + dst_type = __ipv6_addr_type(daddr); + dst.addr = daddr; + dst.ifindex = dst_dev ? dst_dev->ifindex : 0; + dst.scope = __ipv6_addr_src_scope(dst_type); + dst.label = ipv6_addr_label(net, daddr, dst_type, dst.ifindex); + dst.prefs = prefs; + + hiscore->rule = -1; + hiscore->ifa = NULL; + + rcu_read_lock(); + + for_each_netdev_rcu(net, dev) { + struct inet6_dev *idev; + + /* Candidate Source Address (section 4) + * - multicast and link-local destination address, + * the set of candidate source address MUST only + * include addresses assigned to interfaces + * belonging to the same link as the outgoing + * interface. + * (- For site-local destination addresses, the + * set of candidate source addresses MUST only + * include addresses assigned to interfaces + * belonging to the same site as the outgoing + * interface.) + */ + if (((dst_type & IPV6_ADDR_MULTICAST) || + dst.scope <= IPV6_ADDR_SCOPE_LINKLOCAL) && + dst.ifindex && dev->ifindex != dst.ifindex) + continue; + + idev = __in6_dev_get(dev); + if (!idev) + continue; + + read_lock_bh(&idev->lock); + list_for_each_entry(score->ifa, &idev->addr_list, if_list) { + int i; + + /* + * - Tentative Address (RFC2462 section 5.4) + * - A tentative address is not considered + * ""assigned to an interface"" in the traditional + * sense, unless it is also flagged as optimistic. + * - Candidate Source Address (section 4) + * - In any case, anycast addresses, multicast + * addresses, and the unspecified address MUST + * NOT be included in a candidate set. + */ + if ((score->ifa->flags & IFA_F_TENTATIVE) && + (!(score->ifa->flags & IFA_F_OPTIMISTIC))) + continue; + + score->addr_type = __ipv6_addr_type(&score->ifa->addr); + + if (unlikely(score->addr_type == IPV6_ADDR_ANY || + score->addr_type & IPV6_ADDR_MULTICAST)) { + net_dbg_ratelimited(""ADDRCONF: unspecified / multicast address assigned as unicast address on %s"", + dev->name); + continue; + } + + score->rule = -1; + bitmap_zero(score->scorebits, IPV6_SADDR_RULE_MAX); + + for (i = 0; i < IPV6_SADDR_RULE_MAX; i++) { + int minihiscore, miniscore; + + minihiscore = ipv6_get_saddr_eval(net, hiscore, &dst, i); + miniscore = ipv6_get_saddr_eval(net, score, &dst, i); + + if (minihiscore > miniscore) { + if (i == IPV6_SADDR_RULE_SCOPE && + score->scopedist > 0) { + /* + * special case: + * each remaining entry + * has too small (not enough) + * scope, because ifa entries + * are sorted by their scope + * values. + */ + goto try_nextdev; + } + break; + } else if (minihiscore < miniscore) { + if (hiscore->ifa) + in6_ifa_put(hiscore->ifa); + + in6_ifa_hold(score->ifa); + + swap(hiscore, score); + + /* restore our iterator */ + score->ifa = hiscore->ifa; + + break; + } + } + } +try_nextdev: + read_unlock_bh(&idev->lock); + } + rcu_read_unlock(); + + if (!hiscore->ifa) + return -EADDRNOTAVAIL; + + *saddr = hiscore->ifa->addr; + in6_ifa_put(hiscore->ifa); + return 0; +} +",0,"int ipv6_dev_get_saddr(struct net *net, const struct net_device *dst_dev, + const struct in6_addr *daddr, unsigned int prefs, + struct in6_addr *saddr) +{ + struct ipv6_saddr_score scores[2], + *score = &scores[0], *hiscore = &scores[1]; + struct ipv6_saddr_dst dst; + struct net_device *dev; + int dst_type; + + dst_type = __ipv6_addr_type(daddr); + dst.addr = daddr; + dst.ifindex = dst_dev ? dst_dev->ifindex : 0; + dst.scope = __ipv6_addr_src_scope(dst_type); + dst.label = ipv6_addr_label(net, daddr, dst_type, dst.ifindex); + dst.prefs = prefs; + + hiscore->rule = -1; + hiscore->ifa = NULL; + + rcu_read_lock(); + + for_each_netdev_rcu(net, dev) { + struct inet6_dev *idev; + + /* Candidate Source Address (section 4) + * - multicast and link-local destination address, + * the set of candidate source address MUST only + * include addresses assigned to interfaces + * belonging to the same link as the outgoing + * interface. + * (- For site-local destination addresses, the + * set of candidate source addresses MUST only + * include addresses assigned to interfaces + * belonging to the same site as the outgoing + * interface.) + */ + if (((dst_type & IPV6_ADDR_MULTICAST) || + dst.scope <= IPV6_ADDR_SCOPE_LINKLOCAL) && + dst.ifindex && dev->ifindex != dst.ifindex) + continue; + + idev = __in6_dev_get(dev); + if (!idev) + continue; + + read_lock_bh(&idev->lock); + list_for_each_entry(score->ifa, &idev->addr_list, if_list) { + int i; + + /* + * - Tentative Address (RFC2462 section 5.4) + * - A tentative address is not considered + * ""assigned to an interface"" in the traditional + * sense, unless it is also flagged as optimistic. + * - Candidate Source Address (section 4) + * - In any case, anycast addresses, multicast + * addresses, and the unspecified address MUST + * NOT be included in a candidate set. + */ + if ((score->ifa->flags & IFA_F_TENTATIVE) && + (!(score->ifa->flags & IFA_F_OPTIMISTIC))) + continue; + + score->addr_type = __ipv6_addr_type(&score->ifa->addr); + + if (unlikely(score->addr_type == IPV6_ADDR_ANY || + score->addr_type & IPV6_ADDR_MULTICAST)) { + net_dbg_ratelimited(""ADDRCONF: unspecified / multicast address assigned as unicast address on %s"", + dev->name); + continue; + } + + score->rule = -1; + bitmap_zero(score->scorebits, IPV6_SADDR_RULE_MAX); + + for (i = 0; i < IPV6_SADDR_RULE_MAX; i++) { + int minihiscore, miniscore; + + minihiscore = ipv6_get_saddr_eval(net, hiscore, &dst, i); + miniscore = ipv6_get_saddr_eval(net, score, &dst, i); + + if (minihiscore > miniscore) { + if (i == IPV6_SADDR_RULE_SCOPE && + score->scopedist > 0) { + /* + * special case: + * each remaining entry + * has too small (not enough) + * scope, because ifa entries + * are sorted by their scope + * values. + */ + goto try_nextdev; + } + break; + } else if (minihiscore < miniscore) { + if (hiscore->ifa) + in6_ifa_put(hiscore->ifa); + + in6_ifa_hold(score->ifa); + + swap(hiscore, score); + + /* restore our iterator */ + score->ifa = hiscore->ifa; + + break; + } + } + } +try_nextdev: + read_unlock_bh(&idev->lock); + } + rcu_read_unlock(); + + if (!hiscore->ifa) + return -EADDRNOTAVAIL; + + *saddr = hiscore->ifa->addr; + in6_ifa_put(hiscore->ifa); + return 0; +} +","@@ -4903,6 +4903,21 @@ int addrconf_sysctl_forward(struct ctl_table *ctl, int write, + return ret; + } + ++static ++int addrconf_sysctl_mtu(struct ctl_table *ctl, int write, ++ void __user *buffer, size_t *lenp, loff_t *ppos) ++{ ++ struct inet6_dev *idev = ctl->extra1; ++ int min_mtu = IPV6_MIN_MTU; ++ struct ctl_table lctl; ++ ++ lctl = *ctl; ++ lctl.extra1 = &min_mtu; ++ lctl.extra2 = idev ? &idev->dev->mtu : NULL; ++ ++ return proc_dointvec_minmax(&lctl, write, buffer, lenp, ppos); ++} ++ + static void dev_disable_change(struct inet6_dev *idev) + { + struct netdev_notifier_info info; +@@ -5054,7 +5069,7 @@ static struct addrconf_sysctl_table + .data = &ipv6_devconf.mtu6, + .maxlen = sizeof(int), + .mode = 0644, +- .proc_handler = proc_dointvec, ++ .proc_handler = addrconf_sysctl_mtu, + }, + { + .procname = ""accept_ra"",",969,1300,2048 +17797,"void Splash::arbitraryTransformMask(SplashImageMaskSource src, void *srcData, + int srcWidth, int srcHeight, + SplashCoord *mat, GBool glyphMode) { + SplashBitmap *scaledMask; + SplashClipResult clipRes, clipRes2; + SplashPipe pipe; + int scaledWidth, scaledHeight, t0, t1; + SplashCoord r00, r01, r10, r11, det, ir00, ir01, ir10, ir11; + SplashCoord vx[4], vy[4]; + int xMin, yMin, xMax, yMax; + ImageSection section[3]; + int nSections; + int y, xa, xb, x, i, xx, yy; + + vx[0] = mat[4]; vy[0] = mat[5]; + vx[1] = mat[2] + mat[4]; vy[1] = mat[3] + mat[5]; + vx[2] = mat[0] + mat[2] + mat[4]; vy[2] = mat[1] + mat[3] + mat[5]; + vx[3] = mat[0] + mat[4]; vy[3] = mat[1] + mat[5]; + + xMin = imgCoordMungeLowerC(vx[0], glyphMode); + xMax = imgCoordMungeUpperC(vx[0], glyphMode); + yMin = imgCoordMungeLowerC(vy[0], glyphMode); + yMax = imgCoordMungeUpperC(vy[0], glyphMode); + for (i = 1; i < 4; ++i) { + t0 = imgCoordMungeLowerC(vx[i], glyphMode); + if (t0 < xMin) { + xMin = t0; + } + t0 = imgCoordMungeUpperC(vx[i], glyphMode); + if (t0 > xMax) { + xMax = t0; + } + t1 = imgCoordMungeLowerC(vy[i], glyphMode); + if (t1 < yMin) { + yMin = t1; + } + t1 = imgCoordMungeUpperC(vy[i], glyphMode); + if (t1 > yMax) { + yMax = t1; + } + } + clipRes = state->clip->testRect(xMin, yMin, xMax - 1, yMax - 1); + opClipRes = clipRes; + if (clipRes == splashClipAllOutside) { + return; + } + + if (mat[0] >= 0) { + t0 = imgCoordMungeUpperC(mat[0] + mat[4], glyphMode) - + imgCoordMungeLowerC(mat[4], glyphMode); + } else { + t0 = imgCoordMungeUpperC(mat[4], glyphMode) - + imgCoordMungeLowerC(mat[0] + mat[4], glyphMode); + } + if (mat[1] >= 0) { + t1 = imgCoordMungeUpperC(mat[1] + mat[5], glyphMode) - + imgCoordMungeLowerC(mat[5], glyphMode); + } else { + t1 = imgCoordMungeUpperC(mat[5], glyphMode) - + imgCoordMungeLowerC(mat[1] + mat[5], glyphMode); + } + scaledWidth = t0 > t1 ? t0 : t1; + if (mat[2] >= 0) { + t0 = imgCoordMungeUpperC(mat[2] + mat[4], glyphMode) - + imgCoordMungeLowerC(mat[4], glyphMode); + } else { + t0 = imgCoordMungeUpperC(mat[4], glyphMode) - + imgCoordMungeLowerC(mat[2] + mat[4], glyphMode); + } + if (mat[3] >= 0) { + t1 = imgCoordMungeUpperC(mat[3] + mat[5], glyphMode) - + imgCoordMungeLowerC(mat[5], glyphMode); + } else { + t1 = imgCoordMungeUpperC(mat[5], glyphMode) - + imgCoordMungeLowerC(mat[3] + mat[5], glyphMode); + } + scaledHeight = t0 > t1 ? t0 : t1; + if (scaledWidth == 0) { + scaledWidth = 1; + } + if (scaledHeight == 0) { + scaledHeight = 1; + } + + r00 = mat[0] / scaledWidth; + r01 = mat[1] / scaledWidth; + r10 = mat[2] / scaledHeight; + r11 = mat[3] / scaledHeight; + det = r00 * r11 - r01 * r10; + if (splashAbs(det) < 1e-6) { + return; + } + ir00 = r11 / det; + ir01 = -r01 / det; + ir10 = -r10 / det; + ir11 = r00 / det; + + scaledMask = scaleMask(src, srcData, srcWidth, srcHeight, + scaledWidth, scaledHeight); + + i = (vy[2] <= vy[3]) ? 2 : 3; + } +",1,"void Splash::arbitraryTransformMask(SplashImageMaskSource src, void *srcData, + int srcWidth, int srcHeight, + SplashCoord *mat, GBool glyphMode) { + SplashBitmap *scaledMask; + SplashClipResult clipRes, clipRes2; + SplashPipe pipe; + int scaledWidth, scaledHeight, t0, t1; + SplashCoord r00, r01, r10, r11, det, ir00, ir01, ir10, ir11; + SplashCoord vx[4], vy[4]; + int xMin, yMin, xMax, yMax; + ImageSection section[3]; + int nSections; + int y, xa, xb, x, i, xx, yy; + + vx[0] = mat[4]; vy[0] = mat[5]; + vx[1] = mat[2] + mat[4]; vy[1] = mat[3] + mat[5]; + vx[2] = mat[0] + mat[2] + mat[4]; vy[2] = mat[1] + mat[3] + mat[5]; + vx[3] = mat[0] + mat[4]; vy[3] = mat[1] + mat[5]; + + xMin = imgCoordMungeLowerC(vx[0], glyphMode); + xMax = imgCoordMungeUpperC(vx[0], glyphMode); + yMin = imgCoordMungeLowerC(vy[0], glyphMode); + yMax = imgCoordMungeUpperC(vy[0], glyphMode); + for (i = 1; i < 4; ++i) { + t0 = imgCoordMungeLowerC(vx[i], glyphMode); + if (t0 < xMin) { + xMin = t0; + } + t0 = imgCoordMungeUpperC(vx[i], glyphMode); + if (t0 > xMax) { + xMax = t0; + } + t1 = imgCoordMungeLowerC(vy[i], glyphMode); + if (t1 < yMin) { + yMin = t1; + } + t1 = imgCoordMungeUpperC(vy[i], glyphMode); + if (t1 > yMax) { + yMax = t1; + } + } + clipRes = state->clip->testRect(xMin, yMin, xMax - 1, yMax - 1); + opClipRes = clipRes; + if (clipRes == splashClipAllOutside) { + return; + } + + if (mat[0] >= 0) { + t0 = imgCoordMungeUpperC(mat[0] + mat[4], glyphMode) - + imgCoordMungeLowerC(mat[4], glyphMode); + } else { + t0 = imgCoordMungeUpperC(mat[4], glyphMode) - + imgCoordMungeLowerC(mat[0] + mat[4], glyphMode); + } + if (mat[1] >= 0) { + t1 = imgCoordMungeUpperC(mat[1] + mat[5], glyphMode) - + imgCoordMungeLowerC(mat[5], glyphMode); + } else { + t1 = imgCoordMungeUpperC(mat[5], glyphMode) - + imgCoordMungeLowerC(mat[1] + mat[5], glyphMode); + } + scaledWidth = t0 > t1 ? t0 : t1; + if (mat[2] >= 0) { + t0 = imgCoordMungeUpperC(mat[2] + mat[4], glyphMode) - + imgCoordMungeLowerC(mat[4], glyphMode); + } else { + t0 = imgCoordMungeUpperC(mat[4], glyphMode) - + imgCoordMungeLowerC(mat[2] + mat[4], glyphMode); + } + if (mat[3] >= 0) { + t1 = imgCoordMungeUpperC(mat[3] + mat[5], glyphMode) - + imgCoordMungeLowerC(mat[5], glyphMode); + } else { + t1 = imgCoordMungeUpperC(mat[5], glyphMode) - + imgCoordMungeLowerC(mat[3] + mat[5], glyphMode); + } + scaledHeight = t0 > t1 ? t0 : t1; + if (scaledWidth == 0) { + scaledWidth = 1; + } + if (scaledHeight == 0) { + scaledHeight = 1; + } + + r00 = mat[0] / scaledWidth; + r01 = mat[1] / scaledWidth; + r10 = mat[2] / scaledHeight; + r11 = mat[3] / scaledHeight; + det = r00 * r11 - r01 * r10; + if (splashAbs(det) < 1e-6) { + return; + } + ir00 = r11 / det; + ir01 = -r01 / det; + ir10 = -r10 / det; + ir11 = r00 / det; + + scaledMask = scaleMask(src, srcData, srcWidth, srcHeight, + scaledWidth, scaledHeight); + if (scaledMask->data == NULL) { + error(errInternal, -1, ""scaledMask->data is NULL in Splash::scaleMaskYuXu""); + delete scaledMask; + return; + } + + i = (vy[2] <= vy[3]) ? 2 : 3; + } +","@@ -2954,6 +2954,11 @@ void Splash::arbitraryTransformMask(SplashImageMaskSource src, void *srcData, + // scale the input image + scaledMask = scaleMask(src, srcData, srcWidth, srcHeight, + scaledWidth, scaledHeight); ++ if (scaledMask->data == NULL) { ++ error(errInternal, -1, ""scaledMask->data is NULL in Splash::scaleMaskYuXu""); ++ delete scaledMask; ++ return; ++ } + + // construct the three sections + i = (vy[2] <= vy[3]) ? 2 : 3; +@@ -3381,6 +3386,12 @@ void Splash::scaleMaskYuXu(SplashImageMaskSource src, void *srcData, + int yp, yq, xp, xq, yt, y, yStep, xt, x, xStep, xx; + int i, j; + ++ destPtr0 = dest->data; ++ if (destPtr0 == NULL) { ++ error(errInternal, -1, ""dest->data is NULL in Splash::scaleMaskYuXu""); ++ return; ++ } ++ + // Bresenham parameters for y scale + yp = scaledHeight / srcHeight; + yq = scaledHeight % srcHeight; +@@ -3395,7 +3406,6 @@ void Splash::scaleMaskYuXu(SplashImageMaskSource src, void *srcData, + // init y scale Bresenham + yt = 0; + +- destPtr0 = dest->data; + for (y = 0; y < srcHeight; ++y) { + + // y scale Bresenham",1198,1529,2048 +6234,"ikev1_id_print(netdissect_options *ndo, u_char tpay _U_, + const struct isakmp_gen *ext, u_int item_len, + const u_char *ep _U_, uint32_t phase, uint32_t doi _U_, + uint32_t proto _U_, int depth _U_) +{ +#define USE_IPSECDOI_IN_PHASE1 1 + const struct ikev1_pl_id *p; + struct ikev1_pl_id id; + static const char *idtypestr[] = { + ""IPv4"", ""IPv4net"", ""IPv6"", ""IPv6net"", + }; + static const char *ipsecidtypestr[] = { + NULL, ""IPv4"", ""FQDN"", ""user FQDN"", ""IPv4net"", ""IPv6"", + ""IPv6net"", ""IPv4range"", ""IPv6range"", ""ASN1 DN"", ""ASN1 GN"", + ""keyid"", + }; + int len; + const u_char *data; + + ND_PRINT((ndo,""%s:"", NPSTR(ISAKMP_NPTYPE_ID))); + + p = (const struct ikev1_pl_id *)ext; + ND_TCHECK(*p); + UNALIGNED_MEMCPY(&id, ext, sizeof(id)); + if (sizeof(*p) < item_len) { + data = (const u_char *)(p + 1); + len = item_len - sizeof(*p); + } else { + data = NULL; + len = 0; + } + +#if 0 /*debug*/ + ND_PRINT((ndo,"" [phase=%d doi=%d proto=%d]"", phase, doi, proto)); +#endif + switch (phase) { +#ifndef USE_IPSECDOI_IN_PHASE1 + case 1: +#endif + default: + ND_PRINT((ndo,"" idtype=%s"", STR_OR_ID(id.d.id_type, idtypestr))); + ND_PRINT((ndo,"" doi_data=%u"", + (uint32_t)(ntohl(id.d.doi_data) & 0xffffff))); + break; + +#ifdef USE_IPSECDOI_IN_PHASE1 + case 1: +#endif + case 2: + { + const struct ipsecdoi_id *doi_p; + struct ipsecdoi_id doi_id; + const char *p_name; + + doi_p = (const struct ipsecdoi_id *)ext; + ND_TCHECK(*doi_p); + UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id)); + ND_PRINT((ndo,"" idtype=%s"", STR_OR_ID(doi_id.type, ipsecidtypestr))); + /* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */ + if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL) + ND_PRINT((ndo,"" protoid=%s"", p_name)); + else + ND_PRINT((ndo,"" protoid=%u"", doi_id.proto_id)); + ND_PRINT((ndo,"" port=%d"", ntohs(doi_id.port))); + if (!len) + break; + if (data == NULL) + goto trunc; + ND_TCHECK2(*data, len); + switch (doi_id.type) { + case IPSECDOI_ID_IPV4_ADDR: + if (len < 4) + ND_PRINT((ndo,"" len=%d [bad: < 4]"", len)); + else + ND_PRINT((ndo,"" len=%d %s"", len, ipaddr_string(ndo, data))); + len = 0; + break; + case IPSECDOI_ID_FQDN: + case IPSECDOI_ID_USER_FQDN: + { + int i; + ND_PRINT((ndo,"" len=%d "", len)); + for (i = 0; i < len; i++) + safeputchar(ndo, data[i]); + len = 0; + break; + } + case IPSECDOI_ID_IPV4_ADDR_SUBNET: + { + const u_char *mask; + if (len < 8) + ND_PRINT((ndo,"" len=%d [bad: < 8]"", len)); + else { + mask = data + sizeof(struct in_addr); + ND_PRINT((ndo,"" len=%d %s/%u.%u.%u.%u"", len, + ipaddr_string(ndo, data), + mask[0], mask[1], mask[2], mask[3])); + } + len = 0; + break; + } + case IPSECDOI_ID_IPV6_ADDR: + if (len < 16) + ND_PRINT((ndo,"" len=%d [bad: < 16]"", len)); + else + ND_PRINT((ndo,"" len=%d %s"", len, ip6addr_string(ndo, data))); + len = 0; + break; + case IPSECDOI_ID_IPV6_ADDR_SUBNET: + { + const u_char *mask; + if (len < 20) + ND_PRINT((ndo,"" len=%d [bad: < 20]"", len)); + else { + mask = (const u_char *)(data + sizeof(struct in6_addr)); + /*XXX*/ + ND_PRINT((ndo,"" len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x"", len, + ip6addr_string(ndo, data), + mask[0], mask[1], mask[2], mask[3], + mask[4], mask[5], mask[6], mask[7], + mask[8], mask[9], mask[10], mask[11], + mask[12], mask[13], mask[14], mask[15])); + } + len = 0; + break; + } + case IPSECDOI_ID_IPV4_ADDR_RANGE: + if (len < 8) + ND_PRINT((ndo,"" len=%d [bad: < 8]"", len)); + else { + ND_PRINT((ndo,"" len=%d %s-%s"", len, + ipaddr_string(ndo, data), + ipaddr_string(ndo, data + sizeof(struct in_addr)))); + } + len = 0; + break; + case IPSECDOI_ID_IPV6_ADDR_RANGE: + if (len < 32) + ND_PRINT((ndo,"" len=%d [bad: < 32]"", len)); + else { + ND_PRINT((ndo,"" len=%d %s-%s"", len, + ip6addr_string(ndo, data), + ip6addr_string(ndo, data + sizeof(struct in6_addr)))); + } + len = 0; + break; + case IPSECDOI_ID_DER_ASN1_DN: + case IPSECDOI_ID_DER_ASN1_GN: + case IPSECDOI_ID_KEY_ID: + break; + } + break; + } + } + if (data && len) { + ND_PRINT((ndo,"" len=%d"", len)); + if (2 < ndo->ndo_vflag) { + ND_PRINT((ndo,"" "")); + if (!rawprint(ndo, (const uint8_t *)data, len)) + goto trunc; + } + } + return (const u_char *)ext + item_len; +trunc: + ND_PRINT((ndo,"" [|%s]"", NPSTR(ISAKMP_NPTYPE_ID))); + return NULL; +} +",0,"ikev1_id_print(netdissect_options *ndo, u_char tpay _U_, + const struct isakmp_gen *ext, u_int item_len, + const u_char *ep _U_, uint32_t phase, uint32_t doi _U_, + uint32_t proto _U_, int depth _U_) +{ +#define USE_IPSECDOI_IN_PHASE1 1 + const struct ikev1_pl_id *p; + struct ikev1_pl_id id; + static const char *idtypestr[] = { + ""IPv4"", ""IPv4net"", ""IPv6"", ""IPv6net"", + }; + static const char *ipsecidtypestr[] = { + NULL, ""IPv4"", ""FQDN"", ""user FQDN"", ""IPv4net"", ""IPv6"", + ""IPv6net"", ""IPv4range"", ""IPv6range"", ""ASN1 DN"", ""ASN1 GN"", + ""keyid"", + }; + int len; + const u_char *data; + + ND_PRINT((ndo,""%s:"", NPSTR(ISAKMP_NPTYPE_ID))); + + p = (const struct ikev1_pl_id *)ext; + ND_TCHECK(*p); + UNALIGNED_MEMCPY(&id, ext, sizeof(id)); + if (sizeof(*p) < item_len) { + data = (const u_char *)(p + 1); + len = item_len - sizeof(*p); + } else { + data = NULL; + len = 0; + } + +#if 0 /*debug*/ + ND_PRINT((ndo,"" [phase=%d doi=%d proto=%d]"", phase, doi, proto)); +#endif + switch (phase) { +#ifndef USE_IPSECDOI_IN_PHASE1 + case 1: +#endif + default: + ND_PRINT((ndo,"" idtype=%s"", STR_OR_ID(id.d.id_type, idtypestr))); + ND_PRINT((ndo,"" doi_data=%u"", + (uint32_t)(ntohl(id.d.doi_data) & 0xffffff))); + break; + +#ifdef USE_IPSECDOI_IN_PHASE1 + case 1: +#endif + case 2: + { + const struct ipsecdoi_id *doi_p; + struct ipsecdoi_id doi_id; + const char *p_name; + + doi_p = (const struct ipsecdoi_id *)ext; + ND_TCHECK(*doi_p); + UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id)); + ND_PRINT((ndo,"" idtype=%s"", STR_OR_ID(doi_id.type, ipsecidtypestr))); + /* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */ + if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL) + ND_PRINT((ndo,"" protoid=%s"", p_name)); + else + ND_PRINT((ndo,"" protoid=%u"", doi_id.proto_id)); + ND_PRINT((ndo,"" port=%d"", ntohs(doi_id.port))); + if (!len) + break; + if (data == NULL) + goto trunc; + ND_TCHECK2(*data, len); + switch (doi_id.type) { + case IPSECDOI_ID_IPV4_ADDR: + if (len < 4) + ND_PRINT((ndo,"" len=%d [bad: < 4]"", len)); + else + ND_PRINT((ndo,"" len=%d %s"", len, ipaddr_string(ndo, data))); + len = 0; + break; + case IPSECDOI_ID_FQDN: + case IPSECDOI_ID_USER_FQDN: + { + int i; + ND_PRINT((ndo,"" len=%d "", len)); + for (i = 0; i < len; i++) + safeputchar(ndo, data[i]); + len = 0; + break; + } + case IPSECDOI_ID_IPV4_ADDR_SUBNET: + { + const u_char *mask; + if (len < 8) + ND_PRINT((ndo,"" len=%d [bad: < 8]"", len)); + else { + mask = data + sizeof(struct in_addr); + ND_PRINT((ndo,"" len=%d %s/%u.%u.%u.%u"", len, + ipaddr_string(ndo, data), + mask[0], mask[1], mask[2], mask[3])); + } + len = 0; + break; + } + case IPSECDOI_ID_IPV6_ADDR: + if (len < 16) + ND_PRINT((ndo,"" len=%d [bad: < 16]"", len)); + else + ND_PRINT((ndo,"" len=%d %s"", len, ip6addr_string(ndo, data))); + len = 0; + break; + case IPSECDOI_ID_IPV6_ADDR_SUBNET: + { + const u_char *mask; + if (len < 20) + ND_PRINT((ndo,"" len=%d [bad: < 20]"", len)); + else { + mask = (const u_char *)(data + sizeof(struct in6_addr)); + /*XXX*/ + ND_PRINT((ndo,"" len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x"", len, + ip6addr_string(ndo, data), + mask[0], mask[1], mask[2], mask[3], + mask[4], mask[5], mask[6], mask[7], + mask[8], mask[9], mask[10], mask[11], + mask[12], mask[13], mask[14], mask[15])); + } + len = 0; + break; + } + case IPSECDOI_ID_IPV4_ADDR_RANGE: + if (len < 8) + ND_PRINT((ndo,"" len=%d [bad: < 8]"", len)); + else { + ND_PRINT((ndo,"" len=%d %s-%s"", len, + ipaddr_string(ndo, data), + ipaddr_string(ndo, data + sizeof(struct in_addr)))); + } + len = 0; + break; + case IPSECDOI_ID_IPV6_ADDR_RANGE: + if (len < 32) + ND_PRINT((ndo,"" len=%d [bad: < 32]"", len)); + else { + ND_PRINT((ndo,"" len=%d %s-%s"", len, + ip6addr_string(ndo, data), + ip6addr_string(ndo, data + sizeof(struct in6_addr)))); + } + len = 0; + break; + case IPSECDOI_ID_DER_ASN1_DN: + case IPSECDOI_ID_DER_ASN1_GN: + case IPSECDOI_ID_KEY_ID: + break; + } + break; + } + } + if (data && len) { + ND_PRINT((ndo,"" len=%d"", len)); + if (2 < ndo->ndo_vflag) { + ND_PRINT((ndo,"" "")); + if (!rawprint(ndo, (const uint8_t *)data, len)) + goto trunc; + } + } + return (const u_char *)ext + item_len; +trunc: + ND_PRINT((ndo,"" [|%s]"", NPSTR(ISAKMP_NPTYPE_ID))); + return NULL; +} +","@@ -912,21 +912,25 @@ struct attrmap { + + static const u_char * + ikev1_attrmap_print(netdissect_options *ndo, +- const u_char *p, const u_char *ep, ++ const u_char *p, const u_char *ep2, + const struct attrmap *map, size_t nmap) + { + int totlen; + uint32_t t, v; + ++ ND_TCHECK(p[0]); + if (p[0] & 0x80) + totlen = 4; +- else ++ else { ++ ND_TCHECK_16BITS(&p[2]); + totlen = 4 + EXTRACT_16BITS(&p[2]); +- if (ep < p + totlen) { ++ } ++ if (ep2 < p + totlen) { + ND_PRINT((ndo,""[|attr]"")); +- return ep + 1; ++ return ep2 + 1; + } + ++ ND_TCHECK_16BITS(&p[0]); + ND_PRINT((ndo,""("")); + t = EXTRACT_16BITS(&p[0]) & 0x7fff; + if (map && t < nmap && map[t].type) +@@ -935,47 +939,71 @@ ikev1_attrmap_print(netdissect_options *ndo, + ND_PRINT((ndo,""type=#%d "", t)); + if (p[0] & 0x80) { + ND_PRINT((ndo,""value="")); ++ ND_TCHECK_16BITS(&p[2]); + v = EXTRACT_16BITS(&p[2]); + if (map && t < nmap && v < map[t].nvalue && map[t].value[v]) + ND_PRINT((ndo,""%s"", map[t].value[v])); +- else +- rawprint(ndo, (const uint8_t *)&p[2], 2); ++ else { ++ if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) { ++ ND_PRINT((ndo,"")"")); ++ goto trunc; ++ } ++ } + } else { +- ND_PRINT((ndo,""len=%d value="", EXTRACT_16BITS(&p[2]))); +- rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2])); ++ ND_PRINT((ndo,""len=%d value="", totlen - 4)); ++ if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) { ++ ND_PRINT((ndo,"")"")); ++ goto trunc; ++ } + } + ND_PRINT((ndo,"")"")); + return p + totlen; ++ ++trunc: ++ return NULL; + } + + static const u_char * +-ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep) ++ikev1_attr_print(netdissect_options *ndo, const u_char *p, const u_char *ep2) + { + int totlen; + uint32_t t; + ++ ND_TCHECK(p[0]); + if (p[0] & 0x80) + totlen = 4; +- else ++ else { ++ ND_TCHECK_16BITS(&p[2]); + totlen = 4 + EXTRACT_16BITS(&p[2]); +- if (ep < p + totlen) { ++ } ++ if (ep2 < p + totlen) { + ND_PRINT((ndo,""[|attr]"")); +- return ep + 1; ++ return ep2 + 1; + } + ++ ND_TCHECK_16BITS(&p[0]); + ND_PRINT((ndo,""("")); + t = EXTRACT_16BITS(&p[0]) & 0x7fff; + ND_PRINT((ndo,""type=#%d "", t)); + if (p[0] & 0x80) { + ND_PRINT((ndo,""value="")); + t = p[2]; +- rawprint(ndo, (const uint8_t *)&p[2], 2); ++ if (!rawprint(ndo, (const uint8_t *)&p[2], 2)) { ++ ND_PRINT((ndo,"")"")); ++ goto trunc; ++ } + } else { +- ND_PRINT((ndo,""len=%d value="", EXTRACT_16BITS(&p[2]))); +- rawprint(ndo, (const uint8_t *)&p[4], EXTRACT_16BITS(&p[2])); ++ ND_PRINT((ndo,""len=%d value="", totlen - 4)); ++ if (!rawprint(ndo, (const uint8_t *)&p[4], totlen - 4)) { ++ ND_PRINT((ndo,"")"")); ++ goto trunc; ++ } + } + ND_PRINT((ndo,"")"")); + return p + totlen; ++ ++trunc: ++ return NULL; + } + + static const u_char * +@@ -1256,11 +1284,12 @@ ikev1_t_print(netdissect_options *ndo, u_char tpay _U_, + cp = (const u_char *)(p + 1); + ep2 = (const u_char *)p + item_len; + while (cp < ep && cp < ep2) { +- if (map && nmap) { +- cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, +- map, nmap); +- } else +- cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2); ++ if (map && nmap) ++ cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); ++ else ++ cp = ikev1_attr_print(ndo, cp, ep2); ++ if (cp == NULL) ++ goto trunc; + } + if (ep < ep2) + ND_PRINT((ndo,""..."")); +@@ -1724,8 +1753,11 @@ ikev1_n_print(netdissect_options *ndo, u_char tpay _U_, + size_t nmap = sizeof(oakley_t_map)/sizeof(oakley_t_map[0]); + ND_PRINT((ndo,"" attrs=("")); + while (cp < ep && cp < ep2) { +- cp = ikev1_attrmap_print(ndo, cp, +- (ep < ep2) ? ep : ep2, map, nmap); ++ cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); ++ if (cp == NULL) { ++ ND_PRINT((ndo,"")"")); ++ goto trunc; ++ } + } + ND_PRINT((ndo,"")"")); + break; +@@ -1926,10 +1958,11 @@ ikev2_t_print(netdissect_options *ndo, int tcount, + ep2 = (const u_char *)p + item_len; + while (cp < ep && cp < ep2) { + if (map && nmap) { +- cp = ikev1_attrmap_print(ndo, cp, (ep < ep2) ? ep : ep2, +- map, nmap); ++ cp = ikev1_attrmap_print(ndo, cp, ep2, map, nmap); + } else +- cp = ikev1_attr_print(ndo, cp, (ep < ep2) ? ep : ep2); ++ cp = ikev1_attr_print(ndo, cp, ep2); ++ if (cp == NULL) ++ goto trunc; + } + if (ep < ep2) + ND_PRINT((ndo,""...""));",1635,1966,2048 +7747,"test_bson_validate_dbref (void) +{ + size_t offset; + bson_t dbref, child, child2; + + /* should fail, $ref without an $id */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_UTF8 (&child, ""$ref"", ""foo""); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should fail, $ref with non id field */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_UTF8 (&child, ""$ref"", ""foo""); + BSON_APPEND_UTF8 (&child, ""extra"", ""field""); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should fail, $ref with $id at the top */ + { + bson_init (&dbref); + BSON_APPEND_UTF8 (&dbref, ""$ref"", ""foo""); + BSON_APPEND_UTF8 (&dbref, ""$id"", ""bar""); + + BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should fail, $ref with $id not first keys */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_UTF8 (&child, ""extra"", ""field""); + BSON_APPEND_UTF8 (&child, ""$ref"", ""foo""); + BSON_APPEND_UTF8 (&child, ""$id"", ""bar""); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should fail, $ref with $db */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_UTF8 (&child, ""$ref"", ""foo""); + BSON_APPEND_UTF8 (&child, ""$db"", ""bar""); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should fail, non-string $ref with $id */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_INT32 (&child, ""$ref"", 1); + BSON_APPEND_UTF8 (&child, ""$id"", ""bar""); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should fail, non-string $ref with nothing */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_INT32 (&child, ""$ref"", 1); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should fail, $ref with $id with non-string $db */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_UTF8 (&child, ""$ref"", ""foo""); + BSON_APPEND_UTF8 (&child, ""$id"", ""bar""); + BSON_APPEND_INT32 (&child, ""$db"", 1); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should fail, $ref with $id with non-string $db with stuff after */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_UTF8 (&child, ""$ref"", ""foo""); + BSON_APPEND_UTF8 (&child, ""$id"", ""bar""); + BSON_APPEND_INT32 (&child, ""$db"", 1); + BSON_APPEND_UTF8 (&child, ""extra"", ""field""); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should fail, $ref with $id with stuff, then $db */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_UTF8 (&child, ""$ref"", ""foo""); + BSON_APPEND_UTF8 (&child, ""$id"", ""bar""); + BSON_APPEND_UTF8 (&child, ""extra"", ""field""); + BSON_APPEND_UTF8 (&child, ""$db"", ""baz""); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should succeed, $ref with $id */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_UTF8 (&child, ""$ref"", ""foo""); + BSON_APPEND_UTF8 (&child, ""$id"", ""bar""); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should succeed, $ref with nested dbref $id */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_UTF8 (&child, ""$ref"", ""foo""); + BSON_APPEND_DOCUMENT_BEGIN (&child, ""$id"", &child2); + BSON_APPEND_UTF8 (&child2, ""$ref"", ""foo2""); + BSON_APPEND_UTF8 (&child2, ""$id"", ""bar2""); + BSON_APPEND_UTF8 (&child2, ""$db"", ""baz2""); + bson_append_document_end (&child, &child2); + BSON_APPEND_UTF8 (&child, ""$db"", ""baz""); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should succeed, $ref with $id and $db */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_UTF8 (&child, ""$ref"", ""foo""); + BSON_APPEND_UTF8 (&child, ""$id"", ""bar""); + BSON_APPEND_UTF8 (&child, ""$db"", ""baz""); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should succeed, $ref with $id and $db and trailing */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_UTF8 (&child, ""$ref"", ""foo""); + BSON_APPEND_UTF8 (&child, ""$id"", ""bar""); + BSON_APPEND_UTF8 (&child, ""$db"", ""baz""); + BSON_APPEND_UTF8 (&child, ""extra"", ""field""); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } +} +",0,"test_bson_validate_dbref (void) +{ + size_t offset; + bson_t dbref, child, child2; + + /* should fail, $ref without an $id */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_UTF8 (&child, ""$ref"", ""foo""); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should fail, $ref with non id field */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_UTF8 (&child, ""$ref"", ""foo""); + BSON_APPEND_UTF8 (&child, ""extra"", ""field""); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should fail, $ref with $id at the top */ + { + bson_init (&dbref); + BSON_APPEND_UTF8 (&dbref, ""$ref"", ""foo""); + BSON_APPEND_UTF8 (&dbref, ""$id"", ""bar""); + + BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should fail, $ref with $id not first keys */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_UTF8 (&child, ""extra"", ""field""); + BSON_APPEND_UTF8 (&child, ""$ref"", ""foo""); + BSON_APPEND_UTF8 (&child, ""$id"", ""bar""); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should fail, $ref with $db */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_UTF8 (&child, ""$ref"", ""foo""); + BSON_APPEND_UTF8 (&child, ""$db"", ""bar""); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should fail, non-string $ref with $id */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_INT32 (&child, ""$ref"", 1); + BSON_APPEND_UTF8 (&child, ""$id"", ""bar""); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should fail, non-string $ref with nothing */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_INT32 (&child, ""$ref"", 1); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should fail, $ref with $id with non-string $db */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_UTF8 (&child, ""$ref"", ""foo""); + BSON_APPEND_UTF8 (&child, ""$id"", ""bar""); + BSON_APPEND_INT32 (&child, ""$db"", 1); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should fail, $ref with $id with non-string $db with stuff after */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_UTF8 (&child, ""$ref"", ""foo""); + BSON_APPEND_UTF8 (&child, ""$id"", ""bar""); + BSON_APPEND_INT32 (&child, ""$db"", 1); + BSON_APPEND_UTF8 (&child, ""extra"", ""field""); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should fail, $ref with $id with stuff, then $db */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_UTF8 (&child, ""$ref"", ""foo""); + BSON_APPEND_UTF8 (&child, ""$id"", ""bar""); + BSON_APPEND_UTF8 (&child, ""extra"", ""field""); + BSON_APPEND_UTF8 (&child, ""$db"", ""baz""); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (!bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should succeed, $ref with $id */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_UTF8 (&child, ""$ref"", ""foo""); + BSON_APPEND_UTF8 (&child, ""$id"", ""bar""); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should succeed, $ref with nested dbref $id */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_UTF8 (&child, ""$ref"", ""foo""); + BSON_APPEND_DOCUMENT_BEGIN (&child, ""$id"", &child2); + BSON_APPEND_UTF8 (&child2, ""$ref"", ""foo2""); + BSON_APPEND_UTF8 (&child2, ""$id"", ""bar2""); + BSON_APPEND_UTF8 (&child2, ""$db"", ""baz2""); + bson_append_document_end (&child, &child2); + BSON_APPEND_UTF8 (&child, ""$db"", ""baz""); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should succeed, $ref with $id and $db */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_UTF8 (&child, ""$ref"", ""foo""); + BSON_APPEND_UTF8 (&child, ""$id"", ""bar""); + BSON_APPEND_UTF8 (&child, ""$db"", ""baz""); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } + + /* should succeed, $ref with $id and $db and trailing */ + { + bson_init (&dbref); + BSON_APPEND_DOCUMENT_BEGIN (&dbref, ""dbref"", &child); + BSON_APPEND_UTF8 (&child, ""$ref"", ""foo""); + BSON_APPEND_UTF8 (&child, ""$id"", ""bar""); + BSON_APPEND_UTF8 (&child, ""$db"", ""baz""); + BSON_APPEND_UTF8 (&child, ""extra"", ""field""); + bson_append_document_end (&dbref, &child); + + BSON_ASSERT (bson_validate (&dbref, BSON_VALIDATE_DOLLAR_KEYS, &offset)); + + bson_destroy (&dbref); + } +} +","@@ -1249,6 +1249,11 @@ test_bson_validate (void) + 12, + BSON_VALIDATE_NONE, + ""corrupt BSON""); ++ VALIDATE_TEST (""test59.bson"", ++ BSON_VALIDATE_NONE, ++ 9, ++ BSON_VALIDATE_NONE, ++ ""corrupt BSON""); + + /* DBRef validation */ + b = BCON_NEW (""my_dbref"",",1690,2021,2048 +9443,"static int l2cap_sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) +{ + struct sock *sk = sock->sk; + struct l2cap_chan *chan = l2cap_pi(sk)->chan; + struct bt_security sec; + struct bt_power pwr; + struct l2cap_conn *conn; + int len, err = 0; + u32 opt; + + BT_DBG(""sk %p"", sk); + + if (level == SOL_L2CAP) + return l2cap_sock_setsockopt_old(sock, optname, optval, optlen); + + if (level != SOL_BLUETOOTH) + return -ENOPROTOOPT; + + lock_sock(sk); + + switch (optname) { + case BT_SECURITY: + if (chan->chan_type != L2CAP_CHAN_CONN_ORIENTED && + chan->chan_type != L2CAP_CHAN_RAW) { + err = -EINVAL; + break; + } + + sec.level = BT_SECURITY_LOW; + + len = min_t(unsigned int, sizeof(sec), optlen); + if (copy_from_user((char *) &sec, optval, len)) { + err = -EFAULT; + break; + } + + if (sec.level < BT_SECURITY_LOW || + sec.level > BT_SECURITY_HIGH) { + err = -EINVAL; + break; + } + + chan->sec_level = sec.level; + + if (!chan->conn) + break; + + conn = chan->conn; + + /*change security for LE channels */ + if (chan->scid == L2CAP_CID_LE_DATA) { + if (!conn->hcon->out) { + err = -EINVAL; + break; + } + + if (smp_conn_security(conn, sec.level)) + break; + sk->sk_state = BT_CONFIG; + chan->state = BT_CONFIG; + + /* or for ACL link */ + } else if ((sk->sk_state == BT_CONNECT2 && + test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) || + sk->sk_state == BT_CONNECTED) { + if (!l2cap_chan_check_security(chan)) + set_bit(BT_SK_SUSPEND, &bt_sk(sk)->flags); + else + sk->sk_state_change(sk); + } else { + err = -EINVAL; + } + break; + + case BT_DEFER_SETUP: + if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) { + err = -EINVAL; + break; + } + + if (get_user(opt, (u32 __user *) optval)) { + err = -EFAULT; + break; + } + + if (opt) + set_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); + else + clear_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); + break; + + case BT_FLUSHABLE: + if (get_user(opt, (u32 __user *) optval)) { + err = -EFAULT; + break; + } + + if (opt > BT_FLUSHABLE_ON) { + err = -EINVAL; + break; + } + + if (opt == BT_FLUSHABLE_OFF) { + struct l2cap_conn *conn = chan->conn; + /* proceed further only when we have l2cap_conn and + No Flush support in the LM */ + if (!conn || !lmp_no_flush_capable(conn->hcon->hdev)) { + err = -EINVAL; + break; + } + } + + if (opt) + set_bit(FLAG_FLUSHABLE, &chan->flags); + else + clear_bit(FLAG_FLUSHABLE, &chan->flags); + break; + + case BT_POWER: + if (chan->chan_type != L2CAP_CHAN_CONN_ORIENTED && + chan->chan_type != L2CAP_CHAN_RAW) { + err = -EINVAL; + break; + } + + pwr.force_active = BT_POWER_FORCE_ACTIVE_ON; + + len = min_t(unsigned int, sizeof(pwr), optlen); + if (copy_from_user((char *) &pwr, optval, len)) { + err = -EFAULT; + break; + } + + if (pwr.force_active) + set_bit(FLAG_FORCE_ACTIVE, &chan->flags); + else + clear_bit(FLAG_FORCE_ACTIVE, &chan->flags); + break; + + case BT_CHANNEL_POLICY: + if (!enable_hs) { + err = -ENOPROTOOPT; + break; + } + + if (get_user(opt, (u32 __user *) optval)) { + err = -EFAULT; + break; + } + + if (opt > BT_CHANNEL_POLICY_AMP_PREFERRED) { + err = -EINVAL; + break; + } + + if (chan->mode != L2CAP_MODE_ERTM && + chan->mode != L2CAP_MODE_STREAMING) { + err = -EOPNOTSUPP; + break; + } + + chan->chan_policy = (u8) opt; + break; + + default: + err = -ENOPROTOOPT; + break; + } + + release_sock(sk); + return err; +} +",0,"static int l2cap_sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) +{ + struct sock *sk = sock->sk; + struct l2cap_chan *chan = l2cap_pi(sk)->chan; + struct bt_security sec; + struct bt_power pwr; + struct l2cap_conn *conn; + int len, err = 0; + u32 opt; + + BT_DBG(""sk %p"", sk); + + if (level == SOL_L2CAP) + return l2cap_sock_setsockopt_old(sock, optname, optval, optlen); + + if (level != SOL_BLUETOOTH) + return -ENOPROTOOPT; + + lock_sock(sk); + + switch (optname) { + case BT_SECURITY: + if (chan->chan_type != L2CAP_CHAN_CONN_ORIENTED && + chan->chan_type != L2CAP_CHAN_RAW) { + err = -EINVAL; + break; + } + + sec.level = BT_SECURITY_LOW; + + len = min_t(unsigned int, sizeof(sec), optlen); + if (copy_from_user((char *) &sec, optval, len)) { + err = -EFAULT; + break; + } + + if (sec.level < BT_SECURITY_LOW || + sec.level > BT_SECURITY_HIGH) { + err = -EINVAL; + break; + } + + chan->sec_level = sec.level; + + if (!chan->conn) + break; + + conn = chan->conn; + + /*change security for LE channels */ + if (chan->scid == L2CAP_CID_LE_DATA) { + if (!conn->hcon->out) { + err = -EINVAL; + break; + } + + if (smp_conn_security(conn, sec.level)) + break; + sk->sk_state = BT_CONFIG; + chan->state = BT_CONFIG; + + /* or for ACL link */ + } else if ((sk->sk_state == BT_CONNECT2 && + test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) || + sk->sk_state == BT_CONNECTED) { + if (!l2cap_chan_check_security(chan)) + set_bit(BT_SK_SUSPEND, &bt_sk(sk)->flags); + else + sk->sk_state_change(sk); + } else { + err = -EINVAL; + } + break; + + case BT_DEFER_SETUP: + if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) { + err = -EINVAL; + break; + } + + if (get_user(opt, (u32 __user *) optval)) { + err = -EFAULT; + break; + } + + if (opt) + set_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); + else + clear_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); + break; + + case BT_FLUSHABLE: + if (get_user(opt, (u32 __user *) optval)) { + err = -EFAULT; + break; + } + + if (opt > BT_FLUSHABLE_ON) { + err = -EINVAL; + break; + } + + if (opt == BT_FLUSHABLE_OFF) { + struct l2cap_conn *conn = chan->conn; + /* proceed further only when we have l2cap_conn and + No Flush support in the LM */ + if (!conn || !lmp_no_flush_capable(conn->hcon->hdev)) { + err = -EINVAL; + break; + } + } + + if (opt) + set_bit(FLAG_FLUSHABLE, &chan->flags); + else + clear_bit(FLAG_FLUSHABLE, &chan->flags); + break; + + case BT_POWER: + if (chan->chan_type != L2CAP_CHAN_CONN_ORIENTED && + chan->chan_type != L2CAP_CHAN_RAW) { + err = -EINVAL; + break; + } + + pwr.force_active = BT_POWER_FORCE_ACTIVE_ON; + + len = min_t(unsigned int, sizeof(pwr), optlen); + if (copy_from_user((char *) &pwr, optval, len)) { + err = -EFAULT; + break; + } + + if (pwr.force_active) + set_bit(FLAG_FORCE_ACTIVE, &chan->flags); + else + clear_bit(FLAG_FORCE_ACTIVE, &chan->flags); + break; + + case BT_CHANNEL_POLICY: + if (!enable_hs) { + err = -ENOPROTOOPT; + break; + } + + if (get_user(opt, (u32 __user *) optval)) { + err = -EFAULT; + break; + } + + if (opt > BT_CHANNEL_POLICY_AMP_PREFERRED) { + err = -EINVAL; + break; + } + + if (chan->mode != L2CAP_MODE_ERTM && + chan->mode != L2CAP_MODE_STREAMING) { + err = -EOPNOTSUPP; + break; + } + + chan->chan_policy = (u8) opt; + break; + + default: + err = -ENOPROTOOPT; + break; + } + + release_sock(sk); + return err; +} +","@@ -245,6 +245,7 @@ static int l2cap_sock_getname(struct socket *sock, struct sockaddr *addr, int *l + + BT_DBG(""sock %p, sk %p"", sock, sk); + ++ memset(la, 0, sizeof(struct sockaddr_l2)); + addr->sa_family = AF_BLUETOOTH; + *len = sizeof(struct sockaddr_l2); + ",1112,1443,2048 +2019,"static int nf_ct_frag6_queue(struct nf_ct_frag6_queue *fq, struct sk_buff *skb, + const struct frag_hdr *fhdr, int nhoff) +{ + struct sk_buff *prev, *next; + int offset, end; + + if (fq->q.last_in & INET_FRAG_COMPLETE) { + pr_debug(""Allready completed\n""); + goto err; + } + + offset = ntohs(fhdr->frag_off) & ~0x7; + end = offset + (ntohs(ipv6_hdr(skb)->payload_len) - + ((u8 *)(fhdr + 1) - (u8 *)(ipv6_hdr(skb) + 1))); + + if ((unsigned int)end > IPV6_MAXPLEN) { + pr_debug(""offset is too large.\n""); + return -1; + } + + if (skb->ip_summed == CHECKSUM_COMPLETE) { + const unsigned char *nh = skb_network_header(skb); + skb->csum = csum_sub(skb->csum, + csum_partial(nh, (u8 *)(fhdr + 1) - nh, + 0)); + } + + /* Is this the final fragment? */ + if (!(fhdr->frag_off & htons(IP6_MF))) { + /* If we already have some bits beyond end + * or have different end, the segment is corrupted. + */ + if (end < fq->q.len || + ((fq->q.last_in & INET_FRAG_LAST_IN) && end != fq->q.len)) { + pr_debug(""already received last fragment\n""); + goto err; + } + fq->q.last_in |= INET_FRAG_LAST_IN; + fq->q.len = end; + } else { + /* Check if the fragment is rounded to 8 bytes. + * Required by the RFC. + */ + if (end & 0x7) { + /* RFC2460 says always send parameter problem in + * this case. -DaveM + */ + pr_debug(""end of fragment not rounded to 8 bytes.\n""); + return -1; + } + if (end > fq->q.len) { + /* Some bits beyond end -> corruption. */ + if (fq->q.last_in & INET_FRAG_LAST_IN) { + pr_debug(""last packet already reached.\n""); + goto err; + } + fq->q.len = end; + } + } + + if (end == offset) + goto err; + + /* Point into the IP datagram 'data' part. */ + if (!pskb_pull(skb, (u8 *) (fhdr + 1) - skb->data)) { + pr_debug(""queue: message is too short.\n""); + goto err; + } + if (pskb_trim_rcsum(skb, end - offset)) { + pr_debug(""Can't trim\n""); + goto err; + } + + /* Find out which fragments are in front and at the back of us + * in the chain of fragments so far. We must know where to put + * this fragment, right? + */ + prev = NULL; + for (next = fq->q.fragments; next != NULL; next = next->next) { + if (NFCT_FRAG6_CB(next)->offset >= offset) + break; /* bingo! */ + prev = next; + } + + /* We found where to put this one. Check for overlap with + * preceding fragment, and, if needed, align things so that + * any overlaps are eliminated. + */ + if (prev) { + int i = (NFCT_FRAG6_CB(prev)->offset + prev->len) - offset; + + if (i > 0) { + offset += i; + if (end <= offset) { + pr_debug(""overlap\n""); + goto err; + } + if (!pskb_pull(skb, i)) { + pr_debug(""Can't pull\n""); + goto err; + } + if (skb->ip_summed != CHECKSUM_UNNECESSARY) + skb->ip_summed = CHECKSUM_NONE; + } + } + + /* Look for overlap with succeeding segments. + * If we can merge fragments, do it. + */ + while (next && NFCT_FRAG6_CB(next)->offset < end) { + /* overlap is 'i' bytes */ + int i = end - NFCT_FRAG6_CB(next)->offset; + + if (i < next->len) { + /* Eat head of the next overlapped fragment + * and leave the loop. The next ones cannot overlap. + */ + pr_debug(""Eat head of the overlapped parts.: %d"", i); + if (!pskb_pull(next, i)) + goto err; + + /* next fragment */ + NFCT_FRAG6_CB(next)->offset += i; + fq->q.meat -= i; + if (next->ip_summed != CHECKSUM_UNNECESSARY) + next->ip_summed = CHECKSUM_NONE; + break; + } else { + struct sk_buff *free_it = next; + + /* Old fragmnet is completely overridden with + * new one drop it. + */ + next = next->next; + + if (prev) + prev->next = next; + else + fq->q.fragments = next; + + fq->q.meat -= free_it->len; + frag_kfree_skb(free_it, NULL); + } + } + + NFCT_FRAG6_CB(skb)->offset = offset; + + /* Insert this fragment in the chain of fragments. */ + skb->next = next; + if (prev) + prev->next = skb; + else + fq->q.fragments = skb; + + skb->dev = NULL; + fq->q.stamp = skb->tstamp; + fq->q.meat += skb->len; + atomic_add(skb->truesize, &nf_init_frags.mem); + + /* The first fragment. + * nhoffset is obtained from the first fragment, of course. + */ + if (offset == 0) { + fq->nhoffset = nhoff; + fq->q.last_in |= INET_FRAG_FIRST_IN; + } + write_lock(&nf_frags.lock); + list_move_tail(&fq->q.lru_list, &nf_init_frags.lru_list); + write_unlock(&nf_frags.lock); + return 0; + +err: + return -1; +} +",0,"static int nf_ct_frag6_queue(struct nf_ct_frag6_queue *fq, struct sk_buff *skb, + const struct frag_hdr *fhdr, int nhoff) +{ + struct sk_buff *prev, *next; + int offset, end; + + if (fq->q.last_in & INET_FRAG_COMPLETE) { + pr_debug(""Allready completed\n""); + goto err; + } + + offset = ntohs(fhdr->frag_off) & ~0x7; + end = offset + (ntohs(ipv6_hdr(skb)->payload_len) - + ((u8 *)(fhdr + 1) - (u8 *)(ipv6_hdr(skb) + 1))); + + if ((unsigned int)end > IPV6_MAXPLEN) { + pr_debug(""offset is too large.\n""); + return -1; + } + + if (skb->ip_summed == CHECKSUM_COMPLETE) { + const unsigned char *nh = skb_network_header(skb); + skb->csum = csum_sub(skb->csum, + csum_partial(nh, (u8 *)(fhdr + 1) - nh, + 0)); + } + + /* Is this the final fragment? */ + if (!(fhdr->frag_off & htons(IP6_MF))) { + /* If we already have some bits beyond end + * or have different end, the segment is corrupted. + */ + if (end < fq->q.len || + ((fq->q.last_in & INET_FRAG_LAST_IN) && end != fq->q.len)) { + pr_debug(""already received last fragment\n""); + goto err; + } + fq->q.last_in |= INET_FRAG_LAST_IN; + fq->q.len = end; + } else { + /* Check if the fragment is rounded to 8 bytes. + * Required by the RFC. + */ + if (end & 0x7) { + /* RFC2460 says always send parameter problem in + * this case. -DaveM + */ + pr_debug(""end of fragment not rounded to 8 bytes.\n""); + return -1; + } + if (end > fq->q.len) { + /* Some bits beyond end -> corruption. */ + if (fq->q.last_in & INET_FRAG_LAST_IN) { + pr_debug(""last packet already reached.\n""); + goto err; + } + fq->q.len = end; + } + } + + if (end == offset) + goto err; + + /* Point into the IP datagram 'data' part. */ + if (!pskb_pull(skb, (u8 *) (fhdr + 1) - skb->data)) { + pr_debug(""queue: message is too short.\n""); + goto err; + } + if (pskb_trim_rcsum(skb, end - offset)) { + pr_debug(""Can't trim\n""); + goto err; + } + + /* Find out which fragments are in front and at the back of us + * in the chain of fragments so far. We must know where to put + * this fragment, right? + */ + prev = NULL; + for (next = fq->q.fragments; next != NULL; next = next->next) { + if (NFCT_FRAG6_CB(next)->offset >= offset) + break; /* bingo! */ + prev = next; + } + + /* We found where to put this one. Check for overlap with + * preceding fragment, and, if needed, align things so that + * any overlaps are eliminated. + */ + if (prev) { + int i = (NFCT_FRAG6_CB(prev)->offset + prev->len) - offset; + + if (i > 0) { + offset += i; + if (end <= offset) { + pr_debug(""overlap\n""); + goto err; + } + if (!pskb_pull(skb, i)) { + pr_debug(""Can't pull\n""); + goto err; + } + if (skb->ip_summed != CHECKSUM_UNNECESSARY) + skb->ip_summed = CHECKSUM_NONE; + } + } + + /* Look for overlap with succeeding segments. + * If we can merge fragments, do it. + */ + while (next && NFCT_FRAG6_CB(next)->offset < end) { + /* overlap is 'i' bytes */ + int i = end - NFCT_FRAG6_CB(next)->offset; + + if (i < next->len) { + /* Eat head of the next overlapped fragment + * and leave the loop. The next ones cannot overlap. + */ + pr_debug(""Eat head of the overlapped parts.: %d"", i); + if (!pskb_pull(next, i)) + goto err; + + /* next fragment */ + NFCT_FRAG6_CB(next)->offset += i; + fq->q.meat -= i; + if (next->ip_summed != CHECKSUM_UNNECESSARY) + next->ip_summed = CHECKSUM_NONE; + break; + } else { + struct sk_buff *free_it = next; + + /* Old fragmnet is completely overridden with + * new one drop it. + */ + next = next->next; + + if (prev) + prev->next = next; + else + fq->q.fragments = next; + + fq->q.meat -= free_it->len; + frag_kfree_skb(free_it, NULL); + } + } + + NFCT_FRAG6_CB(skb)->offset = offset; + + /* Insert this fragment in the chain of fragments. */ + skb->next = next; + if (prev) + prev->next = skb; + else + fq->q.fragments = skb; + + skb->dev = NULL; + fq->q.stamp = skb->tstamp; + fq->q.meat += skb->len; + atomic_add(skb->truesize, &nf_init_frags.mem); + + /* The first fragment. + * nhoffset is obtained from the first fragment, of course. + */ + if (offset == 0) { + fq->nhoffset = nhoff; + fq->q.last_in |= INET_FRAG_FIRST_IN; + } + write_lock(&nf_frags.lock); + list_move_tail(&fq->q.lru_list, &nf_init_frags.lru_list); + write_unlock(&nf_frags.lock); + return 0; + +err: + return -1; +} +","@@ -469,7 +469,7 @@ nf_ct_frag6_reasm(struct nf_ct_frag6_queue *fq, struct net_device *dev) + + /* all original skbs are linked into the NFCT_FRAG6_CB(head).orig */ + fp = skb_shinfo(head)->frag_list; +- if (NFCT_FRAG6_CB(fp)->orig == NULL) ++ if (fp && NFCT_FRAG6_CB(fp)->orig == NULL) + /* at above code, head skb is divided into two skbs. */ + fp = fp->next; + +@@ -595,12 +595,6 @@ struct sk_buff *nf_ct_frag6_gather(struct sk_buff *skb, u32 user) + hdr = ipv6_hdr(clone); + fhdr = (struct frag_hdr *)skb_transport_header(clone); + +- if (!(fhdr->frag_off & htons(0xFFF9))) { +- pr_debug(""Invalid fragment offset\n""); +- /* It is not a fragmented frame */ +- goto ret_orig; +- } +- + if (atomic_read(&nf_init_frags.mem) > nf_init_frags.high_thresh) + nf_ct_frag6_evictor(); + ",1370,1701,2048 +12083,"void WebURLLoaderImpl::Context::Start( + const WebURLRequest& request, + ResourceLoaderBridge::SyncLoadResponse* sync_load_response, + WebKitPlatformSupportImpl* platform) { + DCHECK(!bridge_.get()); + + request_ = request; // Save the request. + + GURL url = request.url(); + if (url.SchemeIs(""data"") && CanHandleDataURL(url)) { + if (sync_load_response) { + sync_load_response->url = url; + std::string data; + GetInfoFromDataURL(sync_load_response->url, sync_load_response, + &sync_load_response->data, + &sync_load_response->error_code); + } else { + AddRef(); // Balanced in OnCompletedRequest + base::MessageLoop::current()->PostTask( + FROM_HERE, base::Bind(&Context::HandleDataURL, this)); + } + return; + } + + GURL referrer_url( + request.httpHeaderField(WebString::fromUTF8(""Referer"")).utf8()); + const std::string& method = request.httpMethod().utf8(); + + int load_flags = net::LOAD_NORMAL; + switch (request.cachePolicy()) { + case WebURLRequest::ReloadIgnoringCacheData: + load_flags |= net::LOAD_VALIDATE_CACHE; + break; + case WebURLRequest::ReturnCacheDataElseLoad: + load_flags |= net::LOAD_PREFERRING_CACHE; + break; + case WebURLRequest::ReturnCacheDataDontLoad: + load_flags |= net::LOAD_ONLY_FROM_CACHE; + break; + case WebURLRequest::UseProtocolCachePolicy: + break; + } + + if (request.reportUploadProgress()) + load_flags |= net::LOAD_ENABLE_UPLOAD_PROGRESS; + if (request.reportLoadTiming()) + load_flags |= net::LOAD_ENABLE_LOAD_TIMING; + if (request.reportRawHeaders()) + load_flags |= net::LOAD_REPORT_RAW_HEADERS; + + if (!request.allowCookies() || !request.allowStoredCredentials()) { + load_flags |= net::LOAD_DO_NOT_SAVE_COOKIES; + load_flags |= net::LOAD_DO_NOT_SEND_COOKIES; + } + + if (!request.allowStoredCredentials()) + load_flags |= net::LOAD_DO_NOT_SEND_AUTH_DATA; + + HeaderFlattener flattener(load_flags); + request.visitHTTPHeaderFields(&flattener); + + + ResourceLoaderBridge::RequestInfo request_info; + request_info.method = method; + request_info.url = url; + request_info.first_party_for_cookies = request.firstPartyForCookies(); + request_info.referrer = referrer_url; + request_info.headers = flattener.GetBuffer(); + request_info.load_flags = load_flags; + request_info.requestor_pid = request.requestorProcessID(); + request_info.request_type = + ResourceType::FromTargetType(request.targetType()); + request_info.priority = + ConvertWebKitPriorityToNetPriority(request.priority()); + request_info.appcache_host_id = request.appCacheHostID(); + request_info.routing_id = request.requestorID(); + request_info.download_to_file = request.downloadToFile(); + request_info.has_user_gesture = request.hasUserGesture(); + request_info.extra_data = request.extraData(); + if (request.extraData()) { + referrer_policy_ = static_cast( + request.extraData())->referrer_policy(); + request_info.referrer_policy = referrer_policy_; + } + bridge_.reset(platform->CreateResourceLoader(request_info)); + + if (!request.httpBody().isNull()) { + DCHECK(method != ""GET"" && method != ""HEAD""); + const WebHTTPBody& httpBody = request.httpBody(); + size_t i = 0; + WebHTTPBody::Element element; + scoped_refptr request_body = new ResourceRequestBody; + while (httpBody.elementAt(i++, element)) { + switch (element.type) { + case WebHTTPBody::Element::TypeData: + if (!element.data.isEmpty()) { + request_body->AppendBytes( + element.data.data(), static_cast(element.data.size())); + } + break; + case WebHTTPBody::Element::TypeFile: + if (element.fileLength == -1) { + request_body->AppendFileRange( + webkit_base::WebStringToFilePath(element.filePath), + 0, kuint64max, base::Time()); + } else { + request_body->AppendFileRange( + webkit_base::WebStringToFilePath(element.filePath), + static_cast(element.fileStart), + static_cast(element.fileLength), + base::Time::FromDoubleT(element.modificationTime)); + } + break; + case WebHTTPBody::Element::TypeURL: { + GURL url = GURL(element.url); + DCHECK(url.SchemeIsFileSystem()); + request_body->AppendFileSystemFileRange( + url, + static_cast(element.fileStart), + static_cast(element.fileLength), + base::Time::FromDoubleT(element.modificationTime)); + break; + } + case WebHTTPBody::Element::TypeBlob: + request_body->AppendBlob(GURL(element.blobURL)); + break; + default: + NOTREACHED(); + } + } + request_body->set_identifier(request.httpBody().identifier()); + bridge_->SetRequestBody(request_body); + } + + if (sync_load_response) { + bridge_->SyncLoad(sync_load_response); + return; + } + + if (bridge_->Start(this)) { + AddRef(); // Balanced in OnCompletedRequest + } else { + bridge_.reset(); + } +} +",0,"void WebURLLoaderImpl::Context::Start( + const WebURLRequest& request, + ResourceLoaderBridge::SyncLoadResponse* sync_load_response, + WebKitPlatformSupportImpl* platform) { + DCHECK(!bridge_.get()); + + request_ = request; // Save the request. + + GURL url = request.url(); + if (url.SchemeIs(""data"") && CanHandleDataURL(url)) { + if (sync_load_response) { + sync_load_response->url = url; + std::string data; + GetInfoFromDataURL(sync_load_response->url, sync_load_response, + &sync_load_response->data, + &sync_load_response->error_code); + } else { + AddRef(); // Balanced in OnCompletedRequest + base::MessageLoop::current()->PostTask( + FROM_HERE, base::Bind(&Context::HandleDataURL, this)); + } + return; + } + + GURL referrer_url( + request.httpHeaderField(WebString::fromUTF8(""Referer"")).utf8()); + const std::string& method = request.httpMethod().utf8(); + + int load_flags = net::LOAD_NORMAL; + switch (request.cachePolicy()) { + case WebURLRequest::ReloadIgnoringCacheData: + load_flags |= net::LOAD_VALIDATE_CACHE; + break; + case WebURLRequest::ReturnCacheDataElseLoad: + load_flags |= net::LOAD_PREFERRING_CACHE; + break; + case WebURLRequest::ReturnCacheDataDontLoad: + load_flags |= net::LOAD_ONLY_FROM_CACHE; + break; + case WebURLRequest::UseProtocolCachePolicy: + break; + } + + if (request.reportUploadProgress()) + load_flags |= net::LOAD_ENABLE_UPLOAD_PROGRESS; + if (request.reportLoadTiming()) + load_flags |= net::LOAD_ENABLE_LOAD_TIMING; + if (request.reportRawHeaders()) + load_flags |= net::LOAD_REPORT_RAW_HEADERS; + + if (!request.allowCookies() || !request.allowStoredCredentials()) { + load_flags |= net::LOAD_DO_NOT_SAVE_COOKIES; + load_flags |= net::LOAD_DO_NOT_SEND_COOKIES; + } + + if (!request.allowStoredCredentials()) + load_flags |= net::LOAD_DO_NOT_SEND_AUTH_DATA; + + HeaderFlattener flattener(load_flags); + request.visitHTTPHeaderFields(&flattener); + + + ResourceLoaderBridge::RequestInfo request_info; + request_info.method = method; + request_info.url = url; + request_info.first_party_for_cookies = request.firstPartyForCookies(); + request_info.referrer = referrer_url; + request_info.headers = flattener.GetBuffer(); + request_info.load_flags = load_flags; + request_info.requestor_pid = request.requestorProcessID(); + request_info.request_type = + ResourceType::FromTargetType(request.targetType()); + request_info.priority = + ConvertWebKitPriorityToNetPriority(request.priority()); + request_info.appcache_host_id = request.appCacheHostID(); + request_info.routing_id = request.requestorID(); + request_info.download_to_file = request.downloadToFile(); + request_info.has_user_gesture = request.hasUserGesture(); + request_info.extra_data = request.extraData(); + if (request.extraData()) { + referrer_policy_ = static_cast( + request.extraData())->referrer_policy(); + request_info.referrer_policy = referrer_policy_; + } + bridge_.reset(platform->CreateResourceLoader(request_info)); + + if (!request.httpBody().isNull()) { + DCHECK(method != ""GET"" && method != ""HEAD""); + const WebHTTPBody& httpBody = request.httpBody(); + size_t i = 0; + WebHTTPBody::Element element; + scoped_refptr request_body = new ResourceRequestBody; + while (httpBody.elementAt(i++, element)) { + switch (element.type) { + case WebHTTPBody::Element::TypeData: + if (!element.data.isEmpty()) { + request_body->AppendBytes( + element.data.data(), static_cast(element.data.size())); + } + break; + case WebHTTPBody::Element::TypeFile: + if (element.fileLength == -1) { + request_body->AppendFileRange( + webkit_base::WebStringToFilePath(element.filePath), + 0, kuint64max, base::Time()); + } else { + request_body->AppendFileRange( + webkit_base::WebStringToFilePath(element.filePath), + static_cast(element.fileStart), + static_cast(element.fileLength), + base::Time::FromDoubleT(element.modificationTime)); + } + break; + case WebHTTPBody::Element::TypeURL: { + GURL url = GURL(element.url); + DCHECK(url.SchemeIsFileSystem()); + request_body->AppendFileSystemFileRange( + url, + static_cast(element.fileStart), + static_cast(element.fileLength), + base::Time::FromDoubleT(element.modificationTime)); + break; + } + case WebHTTPBody::Element::TypeBlob: + request_body->AppendBlob(GURL(element.blobURL)); + break; + default: + NOTREACHED(); + } + } + request_body->set_identifier(request.httpBody().identifier()); + bridge_->SetRequestBody(request_body); + } + + if (sync_load_response) { + bridge_->SyncLoad(sync_load_response); + return; + } + + if (bridge_->Start(this)) { + AddRef(); // Balanced in OnCompletedRequest + } else { + bridge_.reset(); + } +} +","@@ -637,6 +637,7 @@ void WebURLLoaderImpl::Context::OnReceivedResponse( + } + } + ++ scoped_refptr protect(this); + client_->didReceiveResponse(loader_, response); + + // We may have been cancelled after didReceiveResponse, which would leave us",1146,1477,2048 +1729,"int qcow2_get_cluster_offset(BlockDriverState *bs, uint64_t offset, + int *num, uint64_t *cluster_offset) +{ + BDRVQcowState *s = bs->opaque; + unsigned int l2_index; + uint64_t l1_index, l2_offset, *l2_table; + int l1_bits, c; + unsigned int index_in_cluster, nb_clusters; + uint64_t nb_available, nb_needed; + int ret; + + index_in_cluster = (offset >> 9) & (s->cluster_sectors - 1); + nb_needed = *num + index_in_cluster; + + l1_bits = s->l2_bits + s->cluster_bits; + + /* compute how many bytes there are between the offset and + * the end of the l1 entry + */ + + nb_available = (1ULL << l1_bits) - (offset & ((1ULL << l1_bits) - 1)); + + /* compute the number of available sectors */ + + nb_available = (nb_available >> 9) + index_in_cluster; + + if (nb_needed > nb_available) { + nb_needed = nb_available; + } + + *cluster_offset = 0; + + /* seek the the l2 offset in the l1 table */ + + l1_index = offset >> l1_bits; + if (l1_index >= s->l1_size) { + ret = QCOW2_CLUSTER_UNALLOCATED; + goto out; + } + + l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK; + if (!l2_offset) { + ret = QCOW2_CLUSTER_UNALLOCATED; + goto out; + } + + /* load the l2 table in memory */ + + ret = l2_load(bs, l2_offset, &l2_table); + if (ret < 0) { + return ret; + } + + /* find the cluster offset for the given disk offset */ + + l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1); + *cluster_offset = be64_to_cpu(l2_table[l2_index]); + nb_clusters = size_to_clusters(s, nb_needed << 9); + + ret = qcow2_get_cluster_type(*cluster_offset); + switch (ret) { + case QCOW2_CLUSTER_COMPRESSED: + /* Compressed clusters can only be processed one by one */ + c = 1; + *cluster_offset &= L2E_COMPRESSED_OFFSET_SIZE_MASK; + break; + case QCOW2_CLUSTER_ZERO: + if (s->qcow_version < 3) { + return -EIO; + } + c = count_contiguous_clusters(nb_clusters, s->cluster_size, + &l2_table[l2_index], QCOW_OFLAG_ZERO); + *cluster_offset = 0; + break; + case QCOW2_CLUSTER_UNALLOCATED: + /* how many empty clusters ? */ + c = count_contiguous_free_clusters(nb_clusters, &l2_table[l2_index]); + *cluster_offset = 0; + break; + case QCOW2_CLUSTER_NORMAL: + /* how many allocated clusters ? */ + c = count_contiguous_clusters(nb_clusters, s->cluster_size, + &l2_table[l2_index], QCOW_OFLAG_ZERO); + *cluster_offset &= L2E_OFFSET_MASK; + break; + default: + abort(); + } + + qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table); + + nb_available = (c * s->cluster_sectors); + +out: + if (nb_available > nb_needed) + nb_available = nb_needed; + + *num = nb_available - index_in_cluster; + + return ret; +} +",0,"int qcow2_get_cluster_offset(BlockDriverState *bs, uint64_t offset, + int *num, uint64_t *cluster_offset) +{ + BDRVQcowState *s = bs->opaque; + unsigned int l2_index; + uint64_t l1_index, l2_offset, *l2_table; + int l1_bits, c; + unsigned int index_in_cluster, nb_clusters; + uint64_t nb_available, nb_needed; + int ret; + + index_in_cluster = (offset >> 9) & (s->cluster_sectors - 1); + nb_needed = *num + index_in_cluster; + + l1_bits = s->l2_bits + s->cluster_bits; + + /* compute how many bytes there are between the offset and + * the end of the l1 entry + */ + + nb_available = (1ULL << l1_bits) - (offset & ((1ULL << l1_bits) - 1)); + + /* compute the number of available sectors */ + + nb_available = (nb_available >> 9) + index_in_cluster; + + if (nb_needed > nb_available) { + nb_needed = nb_available; + } + + *cluster_offset = 0; + + /* seek the the l2 offset in the l1 table */ + + l1_index = offset >> l1_bits; + if (l1_index >= s->l1_size) { + ret = QCOW2_CLUSTER_UNALLOCATED; + goto out; + } + + l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK; + if (!l2_offset) { + ret = QCOW2_CLUSTER_UNALLOCATED; + goto out; + } + + /* load the l2 table in memory */ + + ret = l2_load(bs, l2_offset, &l2_table); + if (ret < 0) { + return ret; + } + + /* find the cluster offset for the given disk offset */ + + l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1); + *cluster_offset = be64_to_cpu(l2_table[l2_index]); + nb_clusters = size_to_clusters(s, nb_needed << 9); + + ret = qcow2_get_cluster_type(*cluster_offset); + switch (ret) { + case QCOW2_CLUSTER_COMPRESSED: + /* Compressed clusters can only be processed one by one */ + c = 1; + *cluster_offset &= L2E_COMPRESSED_OFFSET_SIZE_MASK; + break; + case QCOW2_CLUSTER_ZERO: + if (s->qcow_version < 3) { + return -EIO; + } + c = count_contiguous_clusters(nb_clusters, s->cluster_size, + &l2_table[l2_index], QCOW_OFLAG_ZERO); + *cluster_offset = 0; + break; + case QCOW2_CLUSTER_UNALLOCATED: + /* how many empty clusters ? */ + c = count_contiguous_free_clusters(nb_clusters, &l2_table[l2_index]); + *cluster_offset = 0; + break; + case QCOW2_CLUSTER_NORMAL: + /* how many allocated clusters ? */ + c = count_contiguous_clusters(nb_clusters, s->cluster_size, + &l2_table[l2_index], QCOW_OFLAG_ZERO); + *cluster_offset &= L2E_OFFSET_MASK; + break; + default: + abort(); + } + + qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table); + + nb_available = (c * s->cluster_sectors); + +out: + if (nb_available > nb_needed) + nb_available = nb_needed; + + *num = nb_available - index_in_cluster; + + return ret; +} +","@@ -55,7 +55,7 @@ int qcow2_grow_l1_table(BlockDriverState *bs, uint64_t min_size, + } + } + +- if (new_l1_size > INT_MAX) { ++ if (new_l1_size > INT_MAX / sizeof(uint64_t)) { + return -EFBIG; + }",791,1122,2048 +12181,"void HTMLSelectElement::menuListDefaultEventHandler(Event* event) +{ + RenderTheme& renderTheme = RenderTheme::theme(); + + if (event->type() == EventTypeNames::keydown) { + if (!renderer() || !event->isKeyboardEvent()) + return; + + if (platformHandleKeydownEvent(toKeyboardEvent(event))) + return; + + if (isSpatialNavigationEnabled(document().frame())) { + if (!m_activeSelectionState) + return; + } + + const String& keyIdentifier = toKeyboardEvent(event)->keyIdentifier(); + bool handled = true; + const Vector& listItems = this->listItems(); + int listIndex = optionToListIndex(selectedIndex()); + + if (keyIdentifier == ""Down"" || keyIdentifier == ""Right"") + listIndex = nextValidIndex(listIndex, SkipForwards, 1); + else if (keyIdentifier == ""Up"" || keyIdentifier == ""Left"") + listIndex = nextValidIndex(listIndex, SkipBackwards, 1); + else if (keyIdentifier == ""PageDown"") + listIndex = nextValidIndex(listIndex, SkipForwards, 3); + else if (keyIdentifier == ""PageUp"") + listIndex = nextValidIndex(listIndex, SkipBackwards, 3); + else if (keyIdentifier == ""Home"") + listIndex = nextValidIndex(-1, SkipForwards, 1); + else if (keyIdentifier == ""End"") + listIndex = nextValidIndex(listItems.size(), SkipBackwards, 1); + else + handled = false; + + if (handled && static_cast(listIndex) < listItems.size()) + selectOption(listToOptionIndex(listIndex), DeselectOtherOptions | DispatchChangeEvent | UserDriven); + + if (handled) + event->setDefaultHandled(); + } + + if (event->type() == EventTypeNames::keypress) { + if (!renderer() || !event->isKeyboardEvent()) + return; + + int keyCode = toKeyboardEvent(event)->keyCode(); + bool handled = false; + + if (keyCode == ' ' && isSpatialNavigationEnabled(document().frame())) { + m_activeSelectionState = !m_activeSelectionState; + event->setDefaultHandled(); + return; + } + + if (renderTheme.popsMenuBySpaceOrReturn()) { + if (keyCode == ' ' || keyCode == '\r') { + focus(); + + if (!renderer() || !renderer()->isMenuList()) + return; + + saveLastSelection(); + if (RenderMenuList* menuList = toRenderMenuList(renderer())) + menuList->showPopup(); + handled = true; + } + } else if (renderTheme.popsMenuByArrowKeys()) { + if (keyCode == ' ') { + focus(); + + if (!renderer() || !renderer()->isMenuList()) + return; + + saveLastSelection(); + if (RenderMenuList* menuList = toRenderMenuList(renderer())) + menuList->showPopup(); + handled = true; + } else if (keyCode == '\r') { + if (form()) + form()->submitImplicitly(event, false); + dispatchChangeEventForMenuList(); + handled = true; + } + } + + if (handled) + event->setDefaultHandled(); + } + + if (event->type() == EventTypeNames::mousedown && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) { + focus(); + if (renderer() && renderer()->isMenuList()) { + if (RenderMenuList* menuList = toRenderMenuList(renderer())) { + if (menuList->popupIsVisible()) + menuList->hidePopup(); + else { + saveLastSelection(); + menuList->showPopup(); + } + } + } + event->setDefaultHandled(); + } + + if (event->type() == EventTypeNames::blur) { + if (RenderMenuList* menuList = toRenderMenuList(renderer())) { + if (menuList->popupIsVisible()) + menuList->hidePopup(); + } + } +} +",0,"void HTMLSelectElement::menuListDefaultEventHandler(Event* event) +{ + RenderTheme& renderTheme = RenderTheme::theme(); + + if (event->type() == EventTypeNames::keydown) { + if (!renderer() || !event->isKeyboardEvent()) + return; + + if (platformHandleKeydownEvent(toKeyboardEvent(event))) + return; + + if (isSpatialNavigationEnabled(document().frame())) { + if (!m_activeSelectionState) + return; + } + + const String& keyIdentifier = toKeyboardEvent(event)->keyIdentifier(); + bool handled = true; + const Vector& listItems = this->listItems(); + int listIndex = optionToListIndex(selectedIndex()); + + if (keyIdentifier == ""Down"" || keyIdentifier == ""Right"") + listIndex = nextValidIndex(listIndex, SkipForwards, 1); + else if (keyIdentifier == ""Up"" || keyIdentifier == ""Left"") + listIndex = nextValidIndex(listIndex, SkipBackwards, 1); + else if (keyIdentifier == ""PageDown"") + listIndex = nextValidIndex(listIndex, SkipForwards, 3); + else if (keyIdentifier == ""PageUp"") + listIndex = nextValidIndex(listIndex, SkipBackwards, 3); + else if (keyIdentifier == ""Home"") + listIndex = nextValidIndex(-1, SkipForwards, 1); + else if (keyIdentifier == ""End"") + listIndex = nextValidIndex(listItems.size(), SkipBackwards, 1); + else + handled = false; + + if (handled && static_cast(listIndex) < listItems.size()) + selectOption(listToOptionIndex(listIndex), DeselectOtherOptions | DispatchChangeEvent | UserDriven); + + if (handled) + event->setDefaultHandled(); + } + + if (event->type() == EventTypeNames::keypress) { + if (!renderer() || !event->isKeyboardEvent()) + return; + + int keyCode = toKeyboardEvent(event)->keyCode(); + bool handled = false; + + if (keyCode == ' ' && isSpatialNavigationEnabled(document().frame())) { + m_activeSelectionState = !m_activeSelectionState; + event->setDefaultHandled(); + return; + } + + if (renderTheme.popsMenuBySpaceOrReturn()) { + if (keyCode == ' ' || keyCode == '\r') { + focus(); + + if (!renderer() || !renderer()->isMenuList()) + return; + + saveLastSelection(); + if (RenderMenuList* menuList = toRenderMenuList(renderer())) + menuList->showPopup(); + handled = true; + } + } else if (renderTheme.popsMenuByArrowKeys()) { + if (keyCode == ' ') { + focus(); + + if (!renderer() || !renderer()->isMenuList()) + return; + + saveLastSelection(); + if (RenderMenuList* menuList = toRenderMenuList(renderer())) + menuList->showPopup(); + handled = true; + } else if (keyCode == '\r') { + if (form()) + form()->submitImplicitly(event, false); + dispatchChangeEventForMenuList(); + handled = true; + } + } + + if (handled) + event->setDefaultHandled(); + } + + if (event->type() == EventTypeNames::mousedown && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) { + focus(); + if (renderer() && renderer()->isMenuList()) { + if (RenderMenuList* menuList = toRenderMenuList(renderer())) { + if (menuList->popupIsVisible()) + menuList->hidePopup(); + else { + saveLastSelection(); + menuList->showPopup(); + } + } + } + event->setDefaultHandled(); + } + + if (event->type() == EventTypeNames::blur) { + if (RenderMenuList* menuList = toRenderMenuList(renderer())) { + if (menuList->popupIsVisible()) + menuList->hidePopup(); + } + } +} +","@@ -1569,4 +1569,9 @@ bool HTMLSelectElement::isInteractiveContent() const + return true; + } + ++bool HTMLSelectElement::supportsAutofocus() const ++{ ++ return true; ++} ++ + } // namespace",843,1174,2048 +9124,"static MagickBooleanType sixel_encode_impl(unsigned char *pixels, size_t width,size_t height, + unsigned char *palette, size_t ncolors, int keycolor, + sixel_output_t *context) +{ +#define RelinquishNodesAndMap \ + while ((np = context->node_free) != NULL) { \ + context->node_free = np->next; \ + np=(sixel_node_t *) RelinquishMagickMemory(np); \ + } \ + map = (unsigned char *) RelinquishMagickMemory(map) + + int x, y, i, n, c; + int left, right; + int pix; + unsigned char *map; + sixel_node_t *np, *tp, top; + int nwrite; + size_t len; + + context->pos = 0; + + if (ncolors < 1) { + return (MagickFalse); + } + len = ncolors * width; + context->active_palette = (-1); + + if ((map = (unsigned char *)AcquireQuantumMemory(len, sizeof(unsigned char))) == NULL) { + return (MagickFalse); + } + (void) memset(map, 0, len); + + if (context->has_8bit_control) { + nwrite = sprintf((char *)context->buffer, ""\x90"" ""0;0;0"" ""q""); + } else { + nwrite = sprintf((char *)context->buffer, ""\x1bP"" ""0;0;0"" ""q""); + } + if (nwrite <= 0) { + return (MagickFalse); + } + sixel_advance(context, nwrite); + nwrite = sprintf((char *)context->buffer + context->pos, ""\""1;1;%d;%d"", (int) width, (int) height); + if (nwrite <= 0) { + RelinquishNodesAndMap; + return (MagickFalse); + } + sixel_advance(context, nwrite); + + if (ncolors != 2 || keycolor == -1) { + for (n = 0; n < (ssize_t) ncolors; n++) { + /* DECGCI Graphics Color Introducer # Pc ; Pu; Px; Py; Pz */ + nwrite = sprintf((char *)context->buffer + context->pos, ""#%d;2;%d;%d;%d"", + n, + (palette[n * 3 + 0] * 100 + 127) / 255, + (palette[n * 3 + 1] * 100 + 127) / 255, + (palette[n * 3 + 2] * 100 + 127) / 255); + if (nwrite <= 0) { + RelinquishNodesAndMap; + return (MagickFalse); + } + sixel_advance(context, nwrite); + if (nwrite <= 0) { + RelinquishNodesAndMap; + return (MagickFalse); + } + } + } + + for (y = i = 0; y < (ssize_t) height; y++) { + for (x = 0; x < (ssize_t) width; x++) { + pix = pixels[y * width + x]; + if (pix >= 0 && pix < (ssize_t) ncolors && pix != keycolor) { + map[pix * width + x] |= (1 << i); + } + } + + if (++i < 6 && (y + 1) < (ssize_t) height) { + continue; + } + + for (c = 0; c < (ssize_t) ncolors; c++) { + for (left = 0; left < (ssize_t) width; left++) { + if (*(map + c * width + left) == 0) { + continue; + } + + for (right = left + 1; right < (ssize_t) width; right++) { + if (*(map + c * width + right) != 0) { + continue; + } + + for (n = 1; (right + n) < (ssize_t) width; n++) { + if (*(map + c * width + right + n) != 0) { + break; + } + } + + if (n >= 10 || right + n >= (ssize_t) width) { + break; + } + right = right + n - 1; + } + + if ((np = context->node_free) != NULL) { + context->node_free = np->next; + } else if ((np = (sixel_node_t *)AcquireMagickMemory(sizeof(sixel_node_t))) == NULL) { + RelinquishNodesAndMap; + return (MagickFalse); + } + + np->color = c; + np->left = left; + np->right = right; + np->map = map + c * width; + + top.next = context->node_top; + tp = ⊤ + + while (tp->next != NULL) { + if (np->left < tp->next->left) { + break; + } + if (np->left == tp->next->left && np->right > tp->next->right) { + break; + } + tp = tp->next; + } + + np->next = tp->next; + tp->next = np; + context->node_top = top.next; + + left = right - 1; + } + + } + + for (x = 0; (np = context->node_top) != NULL;) { + if (x > np->left) { + /* DECGCR Graphics Carriage Return */ + context->buffer[context->pos] = '$'; + sixel_advance(context, 1); + x = 0; + } + + x = sixel_put_node(context, x, np, (int) ncolors, keycolor); + sixel_node_del(context, np); + np = context->node_top; + + while (np != NULL) { + if (np->left < x) { + np = np->next; + continue; + } + + x = sixel_put_node(context, x, np, (int) ncolors, keycolor); + sixel_node_del(context, np); + np = context->node_top; + } + } + + /* DECGNL Graphics Next Line */ + context->buffer[context->pos] = '-'; + sixel_advance(context, 1); + if (nwrite <= 0) { + RelinquishNodesAndMap; + return (MagickFalse); + } + + i = 0; + (void) memset(map, 0, len); + } + + if (context->has_8bit_control) { + context->buffer[context->pos] = 0x9c; + sixel_advance(context, 1); + } else { + context->buffer[context->pos] = 0x1b; + context->buffer[context->pos + 1] = '\\'; + sixel_advance(context, 2); + } + if (nwrite <= 0) { + RelinquishNodesAndMap; + return (MagickFalse); + } + + /* flush buffer */ + if (context->pos > 0) { + WriteBlob(context->image,context->pos,context->buffer); + } + + RelinquishNodesAndMap; + + return(MagickTrue); +} +",0,"static MagickBooleanType sixel_encode_impl(unsigned char *pixels, size_t width,size_t height, + unsigned char *palette, size_t ncolors, int keycolor, + sixel_output_t *context) +{ +#define RelinquishNodesAndMap \ + while ((np = context->node_free) != NULL) { \ + context->node_free = np->next; \ + np=(sixel_node_t *) RelinquishMagickMemory(np); \ + } \ + map = (unsigned char *) RelinquishMagickMemory(map) + + int x, y, i, n, c; + int left, right; + int pix; + unsigned char *map; + sixel_node_t *np, *tp, top; + int nwrite; + size_t len; + + context->pos = 0; + + if (ncolors < 1) { + return (MagickFalse); + } + len = ncolors * width; + context->active_palette = (-1); + + if ((map = (unsigned char *)AcquireQuantumMemory(len, sizeof(unsigned char))) == NULL) { + return (MagickFalse); + } + (void) memset(map, 0, len); + + if (context->has_8bit_control) { + nwrite = sprintf((char *)context->buffer, ""\x90"" ""0;0;0"" ""q""); + } else { + nwrite = sprintf((char *)context->buffer, ""\x1bP"" ""0;0;0"" ""q""); + } + if (nwrite <= 0) { + return (MagickFalse); + } + sixel_advance(context, nwrite); + nwrite = sprintf((char *)context->buffer + context->pos, ""\""1;1;%d;%d"", (int) width, (int) height); + if (nwrite <= 0) { + RelinquishNodesAndMap; + return (MagickFalse); + } + sixel_advance(context, nwrite); + + if (ncolors != 2 || keycolor == -1) { + for (n = 0; n < (ssize_t) ncolors; n++) { + /* DECGCI Graphics Color Introducer # Pc ; Pu; Px; Py; Pz */ + nwrite = sprintf((char *)context->buffer + context->pos, ""#%d;2;%d;%d;%d"", + n, + (palette[n * 3 + 0] * 100 + 127) / 255, + (palette[n * 3 + 1] * 100 + 127) / 255, + (palette[n * 3 + 2] * 100 + 127) / 255); + if (nwrite <= 0) { + RelinquishNodesAndMap; + return (MagickFalse); + } + sixel_advance(context, nwrite); + if (nwrite <= 0) { + RelinquishNodesAndMap; + return (MagickFalse); + } + } + } + + for (y = i = 0; y < (ssize_t) height; y++) { + for (x = 0; x < (ssize_t) width; x++) { + pix = pixels[y * width + x]; + if (pix >= 0 && pix < (ssize_t) ncolors && pix != keycolor) { + map[pix * width + x] |= (1 << i); + } + } + + if (++i < 6 && (y + 1) < (ssize_t) height) { + continue; + } + + for (c = 0; c < (ssize_t) ncolors; c++) { + for (left = 0; left < (ssize_t) width; left++) { + if (*(map + c * width + left) == 0) { + continue; + } + + for (right = left + 1; right < (ssize_t) width; right++) { + if (*(map + c * width + right) != 0) { + continue; + } + + for (n = 1; (right + n) < (ssize_t) width; n++) { + if (*(map + c * width + right + n) != 0) { + break; + } + } + + if (n >= 10 || right + n >= (ssize_t) width) { + break; + } + right = right + n - 1; + } + + if ((np = context->node_free) != NULL) { + context->node_free = np->next; + } else if ((np = (sixel_node_t *)AcquireMagickMemory(sizeof(sixel_node_t))) == NULL) { + RelinquishNodesAndMap; + return (MagickFalse); + } + + np->color = c; + np->left = left; + np->right = right; + np->map = map + c * width; + + top.next = context->node_top; + tp = ⊤ + + while (tp->next != NULL) { + if (np->left < tp->next->left) { + break; + } + if (np->left == tp->next->left && np->right > tp->next->right) { + break; + } + tp = tp->next; + } + + np->next = tp->next; + tp->next = np; + context->node_top = top.next; + + left = right - 1; + } + + } + + for (x = 0; (np = context->node_top) != NULL;) { + if (x > np->left) { + /* DECGCR Graphics Carriage Return */ + context->buffer[context->pos] = '$'; + sixel_advance(context, 1); + x = 0; + } + + x = sixel_put_node(context, x, np, (int) ncolors, keycolor); + sixel_node_del(context, np); + np = context->node_top; + + while (np != NULL) { + if (np->left < x) { + np = np->next; + continue; + } + + x = sixel_put_node(context, x, np, (int) ncolors, keycolor); + sixel_node_del(context, np); + np = context->node_top; + } + } + + /* DECGNL Graphics Next Line */ + context->buffer[context->pos] = '-'; + sixel_advance(context, 1); + if (nwrite <= 0) { + RelinquishNodesAndMap; + return (MagickFalse); + } + + i = 0; + (void) memset(map, 0, len); + } + + if (context->has_8bit_control) { + context->buffer[context->pos] = 0x9c; + sixel_advance(context, 1); + } else { + context->buffer[context->pos] = 0x1b; + context->buffer[context->pos + 1] = '\\'; + sixel_advance(context, 2); + } + if (nwrite <= 0) { + RelinquishNodesAndMap; + return (MagickFalse); + } + + /* flush buffer */ + if (context->pos > 0) { + WriteBlob(context->image,context->pos,context->buffer); + } + + RelinquishNodesAndMap; + + return(MagickTrue); +} +","@@ -1057,6 +1057,7 @@ static Image *ReadSIXELImage(const ImageInfo *image_info,ExceptionInfo *exceptio + if (sixel_decode(image,(unsigned char *) sixel_buffer,&sixel_pixels,&image->columns,&image->rows,&sixel_palette,&image->colors,exception) == MagickFalse) + { + sixel_buffer=(char *) RelinquishMagickMemory(sixel_buffer); ++ sixel_pixels=(unsigned char *) RelinquishMagickMemory(sixel_pixels); + ThrowReaderException(CorruptImageError,""CorruptImage""); + } + sixel_buffer=(char *) RelinquishMagickMemory(sixel_buffer);",1611,1942,2048 +8349,"void AVC_RewriteESDescriptorEx(GF_MPEGVisualSampleEntryBox *avc, GF_MediaBox *mdia) +{ + GF_AVCConfig *avcc, *svcc, *mvcc; + GF_BitRateBox *btrt = gf_isom_sample_entry_get_bitrate((GF_SampleEntryBox *)avc, GF_FALSE); + + if (avc->emul_esd) gf_odf_desc_del((GF_Descriptor *)avc->emul_esd); + avc->emul_esd = gf_odf_desc_esd_new(2); + avc->emul_esd->decoderConfig->streamType = GF_STREAM_VISUAL; + /*AVC OTI is 0x21, AVC parameter set stream OTI (not supported in gpac) is 0x22, SVC OTI is 0x24*/ + /*if we have only SVC stream, set objectTypeIndication to AVC OTI; else set it to AVC OTI*/ + if (avc->svc_config && !avc->avc_config) + avc->emul_esd->decoderConfig->objectTypeIndication = GPAC_OTI_VIDEO_SVC; + else if (avc->mvc_config && !avc->avc_config) + avc->emul_esd->decoderConfig->objectTypeIndication = GPAC_OTI_VIDEO_MVC; + else + avc->emul_esd->decoderConfig->objectTypeIndication = GPAC_OTI_VIDEO_AVC; + + if (btrt) { + avc->emul_esd->decoderConfig->bufferSizeDB = btrt->bufferSizeDB; + avc->emul_esd->decoderConfig->avgBitrate = btrt->avgBitrate; + avc->emul_esd->decoderConfig->maxBitrate = btrt->maxBitrate; + } + if (avc->descr) { + u32 i=0; + GF_Descriptor *desc,*clone; + i=0; + while ((desc = (GF_Descriptor *)gf_list_enum(avc->descr->descriptors, &i))) { + clone = NULL; + gf_odf_desc_copy(desc, &clone); + if (gf_odf_desc_add_desc((GF_Descriptor *)avc->emul_esd, clone) != GF_OK) + gf_odf_desc_del(clone); + } + } + if (avc->avc_config) { + avcc = avc->avc_config->config ? AVC_DuplicateConfig(avc->avc_config->config) : NULL; + /*merge SVC config*/ + if (avc->svc_config) { + merge_avc_config(avcc, avc->svc_config->config); + } + /*merge MVC config*/ + if (avc->mvc_config) { + merge_avc_config(avcc, avc->mvc_config->config); + } + if (avcc) { + if (mdia) merge_all_config(avcc, NULL, mdia); + + gf_odf_avc_cfg_write(avcc, &avc->emul_esd->decoderConfig->decoderSpecificInfo->data, &avc->emul_esd->decoderConfig->decoderSpecificInfo->dataLength); + gf_odf_avc_cfg_del(avcc); + } + } else if (avc->svc_config) { + svcc = AVC_DuplicateConfig(avc->svc_config->config); + + if (mdia) merge_all_config(svcc, NULL, mdia); + + gf_odf_avc_cfg_write(svcc, &avc->emul_esd->decoderConfig->decoderSpecificInfo->data, &avc->emul_esd->decoderConfig->decoderSpecificInfo->dataLength); + gf_odf_avc_cfg_del(svcc); + } + else if (avc->mvc_config) { + mvcc = AVC_DuplicateConfig(avc->mvc_config->config); + + if (mdia) merge_all_config(mvcc, NULL, mdia); + + gf_odf_avc_cfg_write(mvcc, &avc->emul_esd->decoderConfig->decoderSpecificInfo->data, &avc->emul_esd->decoderConfig->decoderSpecificInfo->dataLength); + gf_odf_avc_cfg_del(mvcc); + } +} +",0,"void AVC_RewriteESDescriptorEx(GF_MPEGVisualSampleEntryBox *avc, GF_MediaBox *mdia) +{ + GF_AVCConfig *avcc, *svcc, *mvcc; + GF_BitRateBox *btrt = gf_isom_sample_entry_get_bitrate((GF_SampleEntryBox *)avc, GF_FALSE); + + if (avc->emul_esd) gf_odf_desc_del((GF_Descriptor *)avc->emul_esd); + avc->emul_esd = gf_odf_desc_esd_new(2); + avc->emul_esd->decoderConfig->streamType = GF_STREAM_VISUAL; + /*AVC OTI is 0x21, AVC parameter set stream OTI (not supported in gpac) is 0x22, SVC OTI is 0x24*/ + /*if we have only SVC stream, set objectTypeIndication to AVC OTI; else set it to AVC OTI*/ + if (avc->svc_config && !avc->avc_config) + avc->emul_esd->decoderConfig->objectTypeIndication = GPAC_OTI_VIDEO_SVC; + else if (avc->mvc_config && !avc->avc_config) + avc->emul_esd->decoderConfig->objectTypeIndication = GPAC_OTI_VIDEO_MVC; + else + avc->emul_esd->decoderConfig->objectTypeIndication = GPAC_OTI_VIDEO_AVC; + + if (btrt) { + avc->emul_esd->decoderConfig->bufferSizeDB = btrt->bufferSizeDB; + avc->emul_esd->decoderConfig->avgBitrate = btrt->avgBitrate; + avc->emul_esd->decoderConfig->maxBitrate = btrt->maxBitrate; + } + if (avc->descr) { + u32 i=0; + GF_Descriptor *desc,*clone; + i=0; + while ((desc = (GF_Descriptor *)gf_list_enum(avc->descr->descriptors, &i))) { + clone = NULL; + gf_odf_desc_copy(desc, &clone); + if (gf_odf_desc_add_desc((GF_Descriptor *)avc->emul_esd, clone) != GF_OK) + gf_odf_desc_del(clone); + } + } + if (avc->avc_config) { + avcc = avc->avc_config->config ? AVC_DuplicateConfig(avc->avc_config->config) : NULL; + /*merge SVC config*/ + if (avc->svc_config) { + merge_avc_config(avcc, avc->svc_config->config); + } + /*merge MVC config*/ + if (avc->mvc_config) { + merge_avc_config(avcc, avc->mvc_config->config); + } + if (avcc) { + if (mdia) merge_all_config(avcc, NULL, mdia); + + gf_odf_avc_cfg_write(avcc, &avc->emul_esd->decoderConfig->decoderSpecificInfo->data, &avc->emul_esd->decoderConfig->decoderSpecificInfo->dataLength); + gf_odf_avc_cfg_del(avcc); + } + } else if (avc->svc_config) { + svcc = AVC_DuplicateConfig(avc->svc_config->config); + + if (mdia) merge_all_config(svcc, NULL, mdia); + + gf_odf_avc_cfg_write(svcc, &avc->emul_esd->decoderConfig->decoderSpecificInfo->data, &avc->emul_esd->decoderConfig->decoderSpecificInfo->dataLength); + gf_odf_avc_cfg_del(svcc); + } + else if (avc->mvc_config) { + mvcc = AVC_DuplicateConfig(avc->mvc_config->config); + + if (mdia) merge_all_config(mvcc, NULL, mdia); + + gf_odf_avc_cfg_write(mvcc, &avc->emul_esd->decoderConfig->decoderSpecificInfo->data, &avc->emul_esd->decoderConfig->decoderSpecificInfo->dataLength); + gf_odf_avc_cfg_del(mvcc); + } +} +","@@ -2413,6 +2413,8 @@ GF_Err gf_isom_oinf_read_entry(void *entry, GF_BitStream *bs) + op->output_layer_set_idx = gf_bs_read_u16(bs); + op->max_temporal_id = gf_bs_read_u8(bs); + op->layer_count = gf_bs_read_u8(bs); ++ if (op->layer_count > ARRAY_LENGTH(op->layers_info)) ++ return GF_NON_COMPLIANT_BITSTREAM; + for (j = 0; j < op->layer_count; j++) { + op->layers_info[j].ptl_idx = gf_bs_read_u8(bs); + op->layers_info[j].layer_id = gf_bs_read_int(bs, 6);",949,1280,2048 +18039,"read_SubStreamsInfo(struct archive_read *a, struct _7z_substream_info *ss, + struct _7z_folder *f, size_t numFolders) +{ + const unsigned char *p; + uint64_t *usizes; + size_t unpack_streams; + int type; + unsigned i; + uint32_t numDigests; + + memset(ss, 0, sizeof(*ss)); + + for (i = 0; i < numFolders; i++) + f[i].numUnpackStreams = 1; + + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + type = *p; + + if (type == kNumUnPackStream) { + unpack_streams = 0; + for (i = 0; i < numFolders; i++) { + if (parse_7zip_uint64(a, &(f[i].numUnpackStreams)) < 0) + return (-1); + if (UMAX_ENTRY < f[i].numUnpackStreams) + return (-1); + unpack_streams += (size_t)f[i].numUnpackStreams; + } + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + type = *p; + } else + unpack_streams = numFolders; + + ss->unpack_streams = unpack_streams; + if (unpack_streams) { + ss->unpackSizes = calloc(unpack_streams, + sizeof(*ss->unpackSizes)); + ss->digestsDefined = calloc(unpack_streams, + sizeof(*ss->digestsDefined)); + ss->digests = calloc(unpack_streams, + sizeof(*ss->digests)); + if (ss->unpackSizes == NULL || ss->digestsDefined == NULL || + ss->digests == NULL) + return (-1); + } + + usizes = ss->unpackSizes; + for (i = 0; i < numFolders; i++) { + unsigned pack; + uint64_t sum; + + if (f[i].numUnpackStreams == 0) + continue; + + sum = 0; + if (type == kSize) { + for (pack = 1; pack < f[i].numUnpackStreams; pack++) { + if (parse_7zip_uint64(a, usizes) < 0) + return (-1); + sum += *usizes++; + } + } + *usizes++ = folder_uncompressed_size(&f[i]) - sum; + } + + if (type == kSize) { + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + type = *p; + } + + for (i = 0; i < unpack_streams; i++) { + ss->digestsDefined[i] = 0; + ss->digests[i] = 0; + } + + numDigests = 0; + for (i = 0; i < numFolders; i++) { + if (f[i].numUnpackStreams != 1 || !f[i].digest_defined) + numDigests += (uint32_t)f[i].numUnpackStreams; + } + + if (type == kCRC) { + struct _7z_digests tmpDigests; + unsigned char *digestsDefined = ss->digestsDefined; + uint32_t * digests = ss->digests; + int di = 0; + + memset(&tmpDigests, 0, sizeof(tmpDigests)); + if (read_Digests(a, &(tmpDigests), numDigests) < 0) { + free_Digest(&tmpDigests); + return (-1); + } + for (i = 0; i < numFolders; i++) { + if (f[i].numUnpackStreams == 1 && f[i].digest_defined) { + *digestsDefined++ = 1; + *digests++ = f[i].digest; + } else { + unsigned j; + + for (j = 0; j < f[i].numUnpackStreams; + j++, di++) { + *digestsDefined++ = + tmpDigests.defineds[di]; + *digests++ = + tmpDigests.digests[di]; + } + } + } + free_Digest(&tmpDigests); + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + type = *p; + } + + /* + * Must be kEnd. + */ + if (type != kEnd) + return (-1); + return (0); +} +",1,"read_SubStreamsInfo(struct archive_read *a, struct _7z_substream_info *ss, + struct _7z_folder *f, size_t numFolders) +{ + const unsigned char *p; + uint64_t *usizes; + size_t unpack_streams; + int type; + unsigned i; + uint32_t numDigests; + + memset(ss, 0, sizeof(*ss)); + + for (i = 0; i < numFolders; i++) + f[i].numUnpackStreams = 1; + + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + type = *p; + + if (type == kNumUnPackStream) { + unpack_streams = 0; + for (i = 0; i < numFolders; i++) { + if (parse_7zip_uint64(a, &(f[i].numUnpackStreams)) < 0) + return (-1); + if (UMAX_ENTRY < f[i].numUnpackStreams) + return (-1); + if (unpack_streams > SIZE_MAX - UMAX_ENTRY) { + return (-1); + } + unpack_streams += (size_t)f[i].numUnpackStreams; + } + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + type = *p; + } else + unpack_streams = numFolders; + + ss->unpack_streams = unpack_streams; + if (unpack_streams) { + ss->unpackSizes = calloc(unpack_streams, + sizeof(*ss->unpackSizes)); + ss->digestsDefined = calloc(unpack_streams, + sizeof(*ss->digestsDefined)); + ss->digests = calloc(unpack_streams, + sizeof(*ss->digests)); + if (ss->unpackSizes == NULL || ss->digestsDefined == NULL || + ss->digests == NULL) + return (-1); + } + + usizes = ss->unpackSizes; + for (i = 0; i < numFolders; i++) { + unsigned pack; + uint64_t sum; + + if (f[i].numUnpackStreams == 0) + continue; + + sum = 0; + if (type == kSize) { + for (pack = 1; pack < f[i].numUnpackStreams; pack++) { + if (parse_7zip_uint64(a, usizes) < 0) + return (-1); + sum += *usizes++; + } + } + *usizes++ = folder_uncompressed_size(&f[i]) - sum; + } + + if (type == kSize) { + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + type = *p; + } + + for (i = 0; i < unpack_streams; i++) { + ss->digestsDefined[i] = 0; + ss->digests[i] = 0; + } + + numDigests = 0; + for (i = 0; i < numFolders; i++) { + if (f[i].numUnpackStreams != 1 || !f[i].digest_defined) + numDigests += (uint32_t)f[i].numUnpackStreams; + } + + if (type == kCRC) { + struct _7z_digests tmpDigests; + unsigned char *digestsDefined = ss->digestsDefined; + uint32_t * digests = ss->digests; + int di = 0; + + memset(&tmpDigests, 0, sizeof(tmpDigests)); + if (read_Digests(a, &(tmpDigests), numDigests) < 0) { + free_Digest(&tmpDigests); + return (-1); + } + for (i = 0; i < numFolders; i++) { + if (f[i].numUnpackStreams == 1 && f[i].digest_defined) { + *digestsDefined++ = 1; + *digests++ = f[i].digest; + } else { + unsigned j; + + for (j = 0; j < f[i].numUnpackStreams; + j++, di++) { + *digestsDefined++ = + tmpDigests.defineds[di]; + *digests++ = + tmpDigests.digests[di]; + } + } + } + free_Digest(&tmpDigests); + if ((p = header_bytes(a, 1)) == NULL) + return (-1); + type = *p; + } + + /* + * Must be kEnd. + */ + if (type != kEnd) + return (-1); + return (0); +} +","@@ -2153,6 +2153,9 @@ read_SubStreamsInfo(struct archive_read *a, struct _7z_substream_info *ss, + return (-1); + if (UMAX_ENTRY < f[i].numUnpackStreams) + return (-1); ++ if (unpack_streams > SIZE_MAX - UMAX_ENTRY) { ++ return (-1); ++ } + unpack_streams += (size_t)f[i].numUnpackStreams; + } + if ((p = header_bytes(a, 1)) == NULL)",971,1302,2048 +1053," FT_Add_Module( FT_Library library, + const FT_Module_Class* clazz ) + { + FT_Error error; + FT_Memory memory; + FT_Module module; + FT_UInt nn; + + +#define FREETYPE_VER_FIXED ( ( (FT_Long)FREETYPE_MAJOR << 16 ) | \ + FREETYPE_MINOR ) + + if ( !library ) + return FT_Err_Invalid_Library_Handle; + + if ( !clazz ) + return FT_Err_Invalid_Argument; + + /* check freetype version */ + if ( clazz->module_requires > FREETYPE_VER_FIXED ) + return FT_Err_Invalid_Version; + + /* look for a module with the same name in the library's table */ + for ( nn = 0; nn < library->num_modules; nn++ ) + { + module = library->modules[nn]; + if ( ft_strcmp( module->clazz->module_name, clazz->module_name ) == 0 ) + { + /* this installed module has the same name, compare their versions */ + if ( clazz->module_version <= module->clazz->module_version ) + return FT_Err_Lower_Module_Version; + + /* remove the module from our list, then exit the loop to replace */ + /* it by our new version.. */ + FT_Remove_Module( library, module ); + break; + } + } + + memory = library->memory; + error = FT_Err_Ok; + + if ( library->num_modules >= FT_MAX_MODULES ) + { + error = FT_Err_Too_Many_Drivers; + goto Exit; + } + + /* allocate module object */ + if ( FT_ALLOC( module, clazz->module_size ) ) + goto Exit; + + /* base initialization */ + module->library = library; + module->memory = memory; + module->clazz = (FT_Module_Class*)clazz; + + /* check whether the module is a renderer - this must be performed */ + /* before the normal module initialization */ + if ( FT_MODULE_IS_RENDERER( module ) ) + { + /* add to the renderers list */ + error = ft_add_renderer( module ); + if ( error ) + goto Fail; + } + + /* is the module a auto-hinter? */ + if ( FT_MODULE_IS_HINTER( module ) ) + library->auto_hinter = module; + + /* if the module is a font driver */ + if ( FT_MODULE_IS_DRIVER( module ) ) + { + /* allocate glyph loader if needed */ + FT_Driver driver = FT_DRIVER( module ); + + + driver->clazz = (FT_Driver_Class)module->clazz; + if ( FT_DRIVER_USES_OUTLINES( driver ) ) + { + error = FT_GlyphLoader_New( memory, &driver->glyph_loader ); + if ( error ) + goto Fail; + } + } + + if ( clazz->module_init ) + { + error = clazz->module_init( module ); + if ( error ) + goto Fail; + } + + /* add module to the library's table */ + library->modules[library->num_modules++] = module; + + Exit: + return error; + + Fail: + if ( FT_MODULE_IS_DRIVER( module ) ) + { + FT_Driver driver = FT_DRIVER( module ); + + + if ( FT_DRIVER_USES_OUTLINES( driver ) ) + FT_GlyphLoader_Done( driver->glyph_loader ); + } + + if ( FT_MODULE_IS_RENDERER( module ) ) + { + FT_Renderer renderer = FT_RENDERER( module ); + + + if ( renderer->raster ) + renderer->clazz->raster_class->raster_done( renderer->raster ); + } + + FT_FREE( module ); + goto Exit; + } +",0," FT_Add_Module( FT_Library library, + const FT_Module_Class* clazz ) + { + FT_Error error; + FT_Memory memory; + FT_Module module; + FT_UInt nn; + + +#define FREETYPE_VER_FIXED ( ( (FT_Long)FREETYPE_MAJOR << 16 ) | \ + FREETYPE_MINOR ) + + if ( !library ) + return FT_Err_Invalid_Library_Handle; + + if ( !clazz ) + return FT_Err_Invalid_Argument; + + /* check freetype version */ + if ( clazz->module_requires > FREETYPE_VER_FIXED ) + return FT_Err_Invalid_Version; + + /* look for a module with the same name in the library's table */ + for ( nn = 0; nn < library->num_modules; nn++ ) + { + module = library->modules[nn]; + if ( ft_strcmp( module->clazz->module_name, clazz->module_name ) == 0 ) + { + /* this installed module has the same name, compare their versions */ + if ( clazz->module_version <= module->clazz->module_version ) + return FT_Err_Lower_Module_Version; + + /* remove the module from our list, then exit the loop to replace */ + /* it by our new version.. */ + FT_Remove_Module( library, module ); + break; + } + } + + memory = library->memory; + error = FT_Err_Ok; + + if ( library->num_modules >= FT_MAX_MODULES ) + { + error = FT_Err_Too_Many_Drivers; + goto Exit; + } + + /* allocate module object */ + if ( FT_ALLOC( module, clazz->module_size ) ) + goto Exit; + + /* base initialization */ + module->library = library; + module->memory = memory; + module->clazz = (FT_Module_Class*)clazz; + + /* check whether the module is a renderer - this must be performed */ + /* before the normal module initialization */ + if ( FT_MODULE_IS_RENDERER( module ) ) + { + /* add to the renderers list */ + error = ft_add_renderer( module ); + if ( error ) + goto Fail; + } + + /* is the module a auto-hinter? */ + if ( FT_MODULE_IS_HINTER( module ) ) + library->auto_hinter = module; + + /* if the module is a font driver */ + if ( FT_MODULE_IS_DRIVER( module ) ) + { + /* allocate glyph loader if needed */ + FT_Driver driver = FT_DRIVER( module ); + + + driver->clazz = (FT_Driver_Class)module->clazz; + if ( FT_DRIVER_USES_OUTLINES( driver ) ) + { + error = FT_GlyphLoader_New( memory, &driver->glyph_loader ); + if ( error ) + goto Fail; + } + } + + if ( clazz->module_init ) + { + error = clazz->module_init( module ); + if ( error ) + goto Fail; + } + + /* add module to the library's table */ + library->modules[library->num_modules++] = module; + + Exit: + return error; + + Fail: + if ( FT_MODULE_IS_DRIVER( module ) ) + { + FT_Driver driver = FT_DRIVER( module ); + + + if ( FT_DRIVER_USES_OUTLINES( driver ) ) + FT_GlyphLoader_Done( driver->glyph_loader ); + } + + if ( FT_MODULE_IS_RENDERER( module ) ) + { + FT_Renderer renderer = FT_RENDERER( module ); + + + if ( renderer->raster ) + renderer->clazz->raster_class->raster_done( renderer->raster ); + } + + FT_FREE( module ); + goto Exit; + } +","@@ -1550,6 +1550,9 @@ + FT_TRACE3(( ""POST fragment[%d]: offsets=0x%08x, rlen=0x%08x, flags=0x%04x\n"", + i, offsets[i], rlen, flags )); + ++ if ( ( flags >> 8 ) == 0 ) /* Comment, should not be loaded */ ++ continue; ++ + /* the flags are part of the resource, so rlen >= 2. */ + /* but some fonts declare rlen = 0 for empty fragment */ + if ( rlen > 2 )",779,1110,2048 +17656,"xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len, + int what, xmlChar end, xmlChar end2, xmlChar end3) { + xmlChar *buffer = NULL; + size_t buffer_size = 0; + size_t nbchars = 0; + + xmlChar *current = NULL; + xmlChar *rep = NULL; + const xmlChar *last; + xmlEntityPtr ent; + int c,l; + + if ((ctxt == NULL) || (str == NULL) || (len < 0)) + return(NULL); + last = str + len; + + if (((ctxt->depth > 40) && + ((ctxt->options & XML_PARSE_HUGE) == 0)) || + (ctxt->depth > 1024)) { + xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL); + return(NULL); + } + + /* + * allocate a translation buffer. + */ + buffer_size = XML_PARSER_BIG_BUFFER_SIZE; + buffer = (xmlChar *) xmlMallocAtomic(buffer_size); + if (buffer == NULL) goto mem_error; + + /* + * OK loop until we reach one of the ending char or a size limit. + * we are operating on already parsed values. + */ + if (str < last) + c = CUR_SCHAR(str, l); + else + c = 0; + while ((c != 0) && (c != end) && /* non input consuming loop */ + (c != end2) && (c != end3)) { + + if (c == 0) break; + if ((c == '&') && (str[1] == '#')) { + int val = xmlParseStringCharRef(ctxt, &str); + if (val != 0) { + COPY_BUF(0,buffer,nbchars,val); + } + if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { + growBuffer(buffer, XML_PARSER_BUFFER_SIZE); + } + } else if ((c == '&') && (what & XML_SUBSTITUTE_REF)) { + if (xmlParserDebugEntities) + xmlGenericError(xmlGenericErrorContext, + ""String decoding Entity Reference: %.30s\n"", + str); + ent = xmlParseStringEntityRef(ctxt, &str); + if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) || + (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR)) + goto int_error; + xmlParserEntityCheck(ctxt, 0, ent, 0); + if (ent != NULL) + ctxt->nbentities += ent->checked / 2; + if ((ent != NULL) && + (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { + if (ent->content != NULL) { + COPY_BUF(0,buffer,nbchars,ent->content[0]); + if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { + growBuffer(buffer, XML_PARSER_BUFFER_SIZE); + } + } else { + xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR, + ""predefined entity has no content\n""); + } + } else if ((ent != NULL) && (ent->content != NULL)) { + ctxt->depth++; + rep = xmlStringDecodeEntities(ctxt, ent->content, what, + 0, 0, 0); + ctxt->depth--; + + if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) || + (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR)) + goto int_error; + + if (rep != NULL) { + current = rep; + while (*current != 0) { /* non input consuming loop */ + buffer[nbchars++] = *current++; + if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { + if (xmlParserEntityCheck(ctxt, nbchars, ent, 0)) + goto int_error; + growBuffer(buffer, XML_PARSER_BUFFER_SIZE); + } + } + xmlFree(rep); + rep = NULL; + } + } else if (ent != NULL) { + int i = xmlStrlen(ent->name); + const xmlChar *cur = ent->name; + + buffer[nbchars++] = '&'; + if (nbchars + i + XML_PARSER_BUFFER_SIZE > buffer_size) { + growBuffer(buffer, i + XML_PARSER_BUFFER_SIZE); + } + for (;i > 0;i--) + buffer[nbchars++] = *cur++; + buffer[nbchars++] = ';'; + } + } else if (c == '%' && (what & XML_SUBSTITUTE_PEREF)) { + if (xmlParserDebugEntities) + xmlGenericError(xmlGenericErrorContext, + ""String decoding PE Reference: %.30s\n"", str); + ent = xmlParseStringPEReference(ctxt, &str); + if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP) + goto int_error; + xmlParserEntityCheck(ctxt, 0, ent, 0); + if (ent != NULL) + ctxt->nbentities += ent->checked / 2; + if (ent != NULL) { + if (ent->content == NULL) { + /* + * Note: external parsed entities will not be loaded, + * it is not required for a non-validating parser to + * complete external PEreferences coming from the + * internal subset + */ + if (((ctxt->options & XML_PARSE_NOENT) != 0) || + ((ctxt->options & XML_PARSE_DTDVALID) != 0) || + (ctxt->validate != 0)) { + xmlLoadEntityContent(ctxt, ent); + } else { + xmlWarningMsg(ctxt, XML_ERR_ENTITY_PROCESSING, + ""not validating will not read content for PE entity %s\n"", + ent->name, NULL); + } + } + ctxt->depth++; + rep = xmlStringDecodeEntities(ctxt, ent->content, what, + 0, 0, 0); + ctxt->depth--; + if (rep != NULL) { + current = rep; + while (*current != 0) { /* non input consuming loop */ + buffer[nbchars++] = *current++; + if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { + if (xmlParserEntityCheck(ctxt, nbchars, ent, 0)) + goto int_error; + growBuffer(buffer, XML_PARSER_BUFFER_SIZE); + } + } + xmlFree(rep); + rep = NULL; + } + } + } else { + COPY_BUF(l,buffer,nbchars,c); + str += l; + if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { + growBuffer(buffer, XML_PARSER_BUFFER_SIZE); + } + } + if (str < last) + c = CUR_SCHAR(str, l); + else + c = 0; + } + buffer[nbchars] = 0; + return(buffer); + +mem_error: + xmlErrMemory(ctxt, NULL); +int_error: + if (rep != NULL) + xmlFree(rep); + if (buffer != NULL) + xmlFree(buffer); + return(NULL); +} +",0,"xmlStringLenDecodeEntities(xmlParserCtxtPtr ctxt, const xmlChar *str, int len, + int what, xmlChar end, xmlChar end2, xmlChar end3) { + xmlChar *buffer = NULL; + size_t buffer_size = 0; + size_t nbchars = 0; + + xmlChar *current = NULL; + xmlChar *rep = NULL; + const xmlChar *last; + xmlEntityPtr ent; + int c,l; + + if ((ctxt == NULL) || (str == NULL) || (len < 0)) + return(NULL); + last = str + len; + + if (((ctxt->depth > 40) && + ((ctxt->options & XML_PARSE_HUGE) == 0)) || + (ctxt->depth > 1024)) { + xmlFatalErr(ctxt, XML_ERR_ENTITY_LOOP, NULL); + return(NULL); + } + + /* + * allocate a translation buffer. + */ + buffer_size = XML_PARSER_BIG_BUFFER_SIZE; + buffer = (xmlChar *) xmlMallocAtomic(buffer_size); + if (buffer == NULL) goto mem_error; + + /* + * OK loop until we reach one of the ending char or a size limit. + * we are operating on already parsed values. + */ + if (str < last) + c = CUR_SCHAR(str, l); + else + c = 0; + while ((c != 0) && (c != end) && /* non input consuming loop */ + (c != end2) && (c != end3)) { + + if (c == 0) break; + if ((c == '&') && (str[1] == '#')) { + int val = xmlParseStringCharRef(ctxt, &str); + if (val != 0) { + COPY_BUF(0,buffer,nbchars,val); + } + if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { + growBuffer(buffer, XML_PARSER_BUFFER_SIZE); + } + } else if ((c == '&') && (what & XML_SUBSTITUTE_REF)) { + if (xmlParserDebugEntities) + xmlGenericError(xmlGenericErrorContext, + ""String decoding Entity Reference: %.30s\n"", + str); + ent = xmlParseStringEntityRef(ctxt, &str); + if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) || + (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR)) + goto int_error; + xmlParserEntityCheck(ctxt, 0, ent, 0); + if (ent != NULL) + ctxt->nbentities += ent->checked / 2; + if ((ent != NULL) && + (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { + if (ent->content != NULL) { + COPY_BUF(0,buffer,nbchars,ent->content[0]); + if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { + growBuffer(buffer, XML_PARSER_BUFFER_SIZE); + } + } else { + xmlFatalErrMsg(ctxt, XML_ERR_INTERNAL_ERROR, + ""predefined entity has no content\n""); + } + } else if ((ent != NULL) && (ent->content != NULL)) { + ctxt->depth++; + rep = xmlStringDecodeEntities(ctxt, ent->content, what, + 0, 0, 0); + ctxt->depth--; + + if ((ctxt->lastError.code == XML_ERR_ENTITY_LOOP) || + (ctxt->lastError.code == XML_ERR_INTERNAL_ERROR)) + goto int_error; + + if (rep != NULL) { + current = rep; + while (*current != 0) { /* non input consuming loop */ + buffer[nbchars++] = *current++; + if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { + if (xmlParserEntityCheck(ctxt, nbchars, ent, 0)) + goto int_error; + growBuffer(buffer, XML_PARSER_BUFFER_SIZE); + } + } + xmlFree(rep); + rep = NULL; + } + } else if (ent != NULL) { + int i = xmlStrlen(ent->name); + const xmlChar *cur = ent->name; + + buffer[nbchars++] = '&'; + if (nbchars + i + XML_PARSER_BUFFER_SIZE > buffer_size) { + growBuffer(buffer, i + XML_PARSER_BUFFER_SIZE); + } + for (;i > 0;i--) + buffer[nbchars++] = *cur++; + buffer[nbchars++] = ';'; + } + } else if (c == '%' && (what & XML_SUBSTITUTE_PEREF)) { + if (xmlParserDebugEntities) + xmlGenericError(xmlGenericErrorContext, + ""String decoding PE Reference: %.30s\n"", str); + ent = xmlParseStringPEReference(ctxt, &str); + if (ctxt->lastError.code == XML_ERR_ENTITY_LOOP) + goto int_error; + xmlParserEntityCheck(ctxt, 0, ent, 0); + if (ent != NULL) + ctxt->nbentities += ent->checked / 2; + if (ent != NULL) { + if (ent->content == NULL) { + /* + * Note: external parsed entities will not be loaded, + * it is not required for a non-validating parser to + * complete external PEreferences coming from the + * internal subset + */ + if (((ctxt->options & XML_PARSE_NOENT) != 0) || + ((ctxt->options & XML_PARSE_DTDVALID) != 0) || + (ctxt->validate != 0)) { + xmlLoadEntityContent(ctxt, ent); + } else { + xmlWarningMsg(ctxt, XML_ERR_ENTITY_PROCESSING, + ""not validating will not read content for PE entity %s\n"", + ent->name, NULL); + } + } + ctxt->depth++; + rep = xmlStringDecodeEntities(ctxt, ent->content, what, + 0, 0, 0); + ctxt->depth--; + if (rep != NULL) { + current = rep; + while (*current != 0) { /* non input consuming loop */ + buffer[nbchars++] = *current++; + if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { + if (xmlParserEntityCheck(ctxt, nbchars, ent, 0)) + goto int_error; + growBuffer(buffer, XML_PARSER_BUFFER_SIZE); + } + } + xmlFree(rep); + rep = NULL; + } + } + } else { + COPY_BUF(l,buffer,nbchars,c); + str += l; + if (nbchars + XML_PARSER_BUFFER_SIZE > buffer_size) { + growBuffer(buffer, XML_PARSER_BUFFER_SIZE); + } + } + if (str < last) + c = CUR_SCHAR(str, l); + else + c = 0; + } + buffer[nbchars] = 0; + return(buffer); + +mem_error: + xmlErrMemory(ctxt, NULL); +int_error: + if (rep != NULL) + xmlFree(rep); + if (buffer != NULL) + xmlFree(buffer); + return(NULL); +} +","@@ -8130,6 +8130,14 @@ + + if (xmlPushInput(ctxt, input) < 0) + return; + } else { ++ if ((entity->etype == XML_EXTERNAL_PARAMETER_ENTITY) && ++ ((ctxt->options & XML_PARSE_NOENT) == 0) && ++ ((ctxt->options & XML_PARSE_DTDVALID) == 0) && ++ ((ctxt->options & XML_PARSE_DTDLOAD) == 0) && ++ ((ctxt->options & XML_PARSE_DTDATTR) == 0) && ++ (ctxt->replaceEntities == 0) && ++ (ctxt->validate == 0)) ++ return; + /* + * TODO !!! + * handle the extra spaces added before and after +",1416,1747,2048 +3402,"static int shmem_parse_options(char *options, struct shmem_sb_info *sbinfo, + bool remount) +{ + char *this_char, *value, *rest; + uid_t uid; + gid_t gid; + + while (options != NULL) { + this_char = options; + for (;;) { + /* + * NUL-terminate this option: unfortunately, + * mount options form a comma-separated list, + * but mpol's nodelist may also contain commas. + */ + options = strchr(options, ','); + if (options == NULL) + break; + options++; + if (!isdigit(*options)) { + options[-1] = '\0'; + break; + } + } + if (!*this_char) + continue; + if ((value = strchr(this_char,'=')) != NULL) { + *value++ = 0; + } else { + printk(KERN_ERR + ""tmpfs: No value for mount option '%s'\n"", + this_char); + return 1; + } + + if (!strcmp(this_char,""size"")) { + unsigned long long size; + size = memparse(value,&rest); + if (*rest == '%') { + size <<= PAGE_SHIFT; + size *= totalram_pages; + do_div(size, 100); + rest++; + } + if (*rest) + goto bad_val; + sbinfo->max_blocks = + DIV_ROUND_UP(size, PAGE_CACHE_SIZE); + } else if (!strcmp(this_char,""nr_blocks"")) { + sbinfo->max_blocks = memparse(value, &rest); + if (*rest) + goto bad_val; + } else if (!strcmp(this_char,""nr_inodes"")) { + sbinfo->max_inodes = memparse(value, &rest); + if (*rest) + goto bad_val; + } else if (!strcmp(this_char,""mode"")) { + if (remount) + continue; + sbinfo->mode = simple_strtoul(value, &rest, 8) & 07777; + if (*rest) + goto bad_val; + } else if (!strcmp(this_char,""uid"")) { + if (remount) + continue; + uid = simple_strtoul(value, &rest, 0); + if (*rest) + goto bad_val; + sbinfo->uid = make_kuid(current_user_ns(), uid); + if (!uid_valid(sbinfo->uid)) + goto bad_val; + } else if (!strcmp(this_char,""gid"")) { + if (remount) + continue; + gid = simple_strtoul(value, &rest, 0); + if (*rest) + goto bad_val; + sbinfo->gid = make_kgid(current_user_ns(), gid); + if (!gid_valid(sbinfo->gid)) + goto bad_val; + } else if (!strcmp(this_char,""mpol"")) { + if (mpol_parse_str(value, &sbinfo->mpol)) + goto bad_val; + } else { + printk(KERN_ERR ""tmpfs: Bad mount option %s\n"", + this_char); + return 1; + } + } + return 0; + +bad_val: + printk(KERN_ERR ""tmpfs: Bad value '%s' for mount option '%s'\n"", + value, this_char); + return 1; + +} +",0,"static int shmem_parse_options(char *options, struct shmem_sb_info *sbinfo, + bool remount) +{ + char *this_char, *value, *rest; + uid_t uid; + gid_t gid; + + while (options != NULL) { + this_char = options; + for (;;) { + /* + * NUL-terminate this option: unfortunately, + * mount options form a comma-separated list, + * but mpol's nodelist may also contain commas. + */ + options = strchr(options, ','); + if (options == NULL) + break; + options++; + if (!isdigit(*options)) { + options[-1] = '\0'; + break; + } + } + if (!*this_char) + continue; + if ((value = strchr(this_char,'=')) != NULL) { + *value++ = 0; + } else { + printk(KERN_ERR + ""tmpfs: No value for mount option '%s'\n"", + this_char); + return 1; + } + + if (!strcmp(this_char,""size"")) { + unsigned long long size; + size = memparse(value,&rest); + if (*rest == '%') { + size <<= PAGE_SHIFT; + size *= totalram_pages; + do_div(size, 100); + rest++; + } + if (*rest) + goto bad_val; + sbinfo->max_blocks = + DIV_ROUND_UP(size, PAGE_CACHE_SIZE); + } else if (!strcmp(this_char,""nr_blocks"")) { + sbinfo->max_blocks = memparse(value, &rest); + if (*rest) + goto bad_val; + } else if (!strcmp(this_char,""nr_inodes"")) { + sbinfo->max_inodes = memparse(value, &rest); + if (*rest) + goto bad_val; + } else if (!strcmp(this_char,""mode"")) { + if (remount) + continue; + sbinfo->mode = simple_strtoul(value, &rest, 8) & 07777; + if (*rest) + goto bad_val; + } else if (!strcmp(this_char,""uid"")) { + if (remount) + continue; + uid = simple_strtoul(value, &rest, 0); + if (*rest) + goto bad_val; + sbinfo->uid = make_kuid(current_user_ns(), uid); + if (!uid_valid(sbinfo->uid)) + goto bad_val; + } else if (!strcmp(this_char,""gid"")) { + if (remount) + continue; + gid = simple_strtoul(value, &rest, 0); + if (*rest) + goto bad_val; + sbinfo->gid = make_kgid(current_user_ns(), gid); + if (!gid_valid(sbinfo->gid)) + goto bad_val; + } else if (!strcmp(this_char,""mpol"")) { + if (mpol_parse_str(value, &sbinfo->mpol)) + goto bad_val; + } else { + printk(KERN_ERR ""tmpfs: Bad mount option %s\n"", + this_char); + return 1; + } + } + return 0; + +bad_val: + printk(KERN_ERR ""tmpfs: Bad value '%s' for mount option '%s'\n"", + value, this_char); + return 1; + +} +","@@ -2486,6 +2486,7 @@ static int shmem_remount_fs(struct super_block *sb, int *flags, char *data) + unsigned long inodes; + int error = -EINVAL; + ++ config.mpol = NULL; + if (shmem_parse_options(data, &config, true)) + return error; + +@@ -2510,8 +2511,13 @@ static int shmem_remount_fs(struct super_block *sb, int *flags, char *data) + sbinfo->max_inodes = config.max_inodes; + sbinfo->free_inodes = config.max_inodes - inodes; + +- mpol_put(sbinfo->mpol); +- sbinfo->mpol = config.mpol; /* transfers initial ref */ ++ /* ++ * Preserve previous mempolicy unless mpol remount option was specified. ++ */ ++ if (config.mpol) { ++ mpol_put(sbinfo->mpol); ++ sbinfo->mpol = config.mpol; /* transfers initial ref */ ++ } + out: + spin_unlock(&sbinfo->stat_lock); + return error;",711,1042,2048 +3602,"print_ccp_config_options(netdissect_options *ndo, + const u_char *p, int length) +{ + int len, opt; + + if (length < 2) + return 0; + ND_TCHECK2(*p, 2); + len = p[1]; + opt = p[0]; + if (length < len) + return 0; + if (len < 2) { + ND_PRINT((ndo, ""\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)"", + tok2str(ccpconfopts_values, ""Unknown"", opt), + opt, + len)); + return 0; + } + + ND_PRINT((ndo, ""\n\t %s Option (0x%02x), length %u"", + tok2str(ccpconfopts_values, ""Unknown"", opt), + opt, + len)); + + switch (opt) { + case CCPOPT_BSDCOMP: + if (len < 3) { + ND_PRINT((ndo, "" (length bogus, should be >= 3)"")); + return len; + } + ND_TCHECK2(*(p + 2), 1); + ND_PRINT((ndo, "": Version: %u, Dictionary Bits: %u"", + p[2] >> 5, p[2] & 0x1f)); + break; + case CCPOPT_MVRCA: + if (len < 4) { + ND_PRINT((ndo, "" (length bogus, should be >= 4)"")); + return len; + } + ND_TCHECK2(*(p + 2), 1); + ND_PRINT((ndo, "": Features: %u, PxP: %s, History: %u, #CTX-ID: %u"", + (p[2] & 0xc0) >> 6, + (p[2] & 0x20) ? ""Enabled"" : ""Disabled"", + p[2] & 0x1f, p[3])); + break; + case CCPOPT_DEFLATE: + if (len < 4) { + ND_PRINT((ndo, "" (length bogus, should be >= 4)"")); + return len; + } + ND_TCHECK2(*(p + 2), 1); + ND_PRINT((ndo, "": Window: %uK, Method: %s (0x%x), MBZ: %u, CHK: %u"", + (p[2] & 0xf0) >> 4, + ((p[2] & 0x0f) == 8) ? ""zlib"" : ""unkown"", + p[2] & 0x0f, (p[3] & 0xfc) >> 2, p[3] & 0x03)); + break; + +/* XXX: to be supported */ +#if 0 + case CCPOPT_OUI: + case CCPOPT_PRED1: + case CCPOPT_PRED2: + case CCPOPT_PJUMP: + case CCPOPT_HPPPC: + case CCPOPT_STACLZS: + case CCPOPT_MPPC: + case CCPOPT_GFZA: + case CCPOPT_V42BIS: + case CCPOPT_LZSDCP: + case CCPOPT_DEC: + case CCPOPT_RESV: + break; +#endif + default: + /* + * Unknown option; dump it as raw bytes now if we're + * not going to do so below. + */ + if (ndo->ndo_vflag < 2) + print_unknown_data(ndo, &p[2], ""\n\t "", len - 2); + break; + } + if (ndo->ndo_vflag > 1) + print_unknown_data(ndo, &p[2], ""\n\t "", len - 2); /* exclude TLV header */ + + return len; + +trunc: + ND_PRINT((ndo, ""[|ccp]"")); + return 0; +} +",0,"print_ccp_config_options(netdissect_options *ndo, + const u_char *p, int length) +{ + int len, opt; + + if (length < 2) + return 0; + ND_TCHECK2(*p, 2); + len = p[1]; + opt = p[0]; + if (length < len) + return 0; + if (len < 2) { + ND_PRINT((ndo, ""\n\t %s Option (0x%02x), length %u (length bogus, should be >= 2)"", + tok2str(ccpconfopts_values, ""Unknown"", opt), + opt, + len)); + return 0; + } + + ND_PRINT((ndo, ""\n\t %s Option (0x%02x), length %u"", + tok2str(ccpconfopts_values, ""Unknown"", opt), + opt, + len)); + + switch (opt) { + case CCPOPT_BSDCOMP: + if (len < 3) { + ND_PRINT((ndo, "" (length bogus, should be >= 3)"")); + return len; + } + ND_TCHECK2(*(p + 2), 1); + ND_PRINT((ndo, "": Version: %u, Dictionary Bits: %u"", + p[2] >> 5, p[2] & 0x1f)); + break; + case CCPOPT_MVRCA: + if (len < 4) { + ND_PRINT((ndo, "" (length bogus, should be >= 4)"")); + return len; + } + ND_TCHECK2(*(p + 2), 1); + ND_PRINT((ndo, "": Features: %u, PxP: %s, History: %u, #CTX-ID: %u"", + (p[2] & 0xc0) >> 6, + (p[2] & 0x20) ? ""Enabled"" : ""Disabled"", + p[2] & 0x1f, p[3])); + break; + case CCPOPT_DEFLATE: + if (len < 4) { + ND_PRINT((ndo, "" (length bogus, should be >= 4)"")); + return len; + } + ND_TCHECK2(*(p + 2), 1); + ND_PRINT((ndo, "": Window: %uK, Method: %s (0x%x), MBZ: %u, CHK: %u"", + (p[2] & 0xf0) >> 4, + ((p[2] & 0x0f) == 8) ? ""zlib"" : ""unkown"", + p[2] & 0x0f, (p[3] & 0xfc) >> 2, p[3] & 0x03)); + break; + +/* XXX: to be supported */ +#if 0 + case CCPOPT_OUI: + case CCPOPT_PRED1: + case CCPOPT_PRED2: + case CCPOPT_PJUMP: + case CCPOPT_HPPPC: + case CCPOPT_STACLZS: + case CCPOPT_MPPC: + case CCPOPT_GFZA: + case CCPOPT_V42BIS: + case CCPOPT_LZSDCP: + case CCPOPT_DEC: + case CCPOPT_RESV: + break; +#endif + default: + /* + * Unknown option; dump it as raw bytes now if we're + * not going to do so below. + */ + if (ndo->ndo_vflag < 2) + print_unknown_data(ndo, &p[2], ""\n\t "", len - 2); + break; + } + if (ndo->ndo_vflag > 1) + print_unknown_data(ndo, &p[2], ""\n\t "", len - 2); /* exclude TLV header */ + + return len; + +trunc: + ND_PRINT((ndo, ""[|ccp]"")); + return 0; +} +","@@ -1351,14 +1351,15 @@ static void + ppp_hdlc(netdissect_options *ndo, + const u_char *p, int length) + { +- u_char *b, *s, *t, c; ++ u_char *b, *t, c; ++ const u_char *s; + int i, proto; + const void *se; + + if (length <= 0) + return; + +- b = (uint8_t *)malloc(length); ++ b = (u_char *)malloc(length); + if (b == NULL) + return; + +@@ -1367,14 +1368,13 @@ ppp_hdlc(netdissect_options *ndo, + * Do this so that we dont overwrite the original packet + * contents. + */ +- for (s = (u_char *)p, t = b, i = length; i > 0; i--) { ++ for (s = p, t = b, i = length; i > 0 && ND_TTEST(*s); i--) { + c = *s++; + if (c == 0x7d) { +- if (i > 1) { +- i--; +- c = *s++ ^ 0x20; +- } else +- continue; ++ if (i <= 1 || !ND_TTEST(*s)) ++ break; ++ i--; ++ c = *s++ ^ 0x20; + } + *t++ = c; + }",860,1191,2048 +18569,"void RenderProcessHostImpl::CreateMessageFilters() { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + AddFilter(new ResourceSchedulerFilter(GetID())); + MediaInternals* media_internals = MediaInternals::GetInstance(); + scoped_refptr bp_message_filter( + new BrowserPluginMessageFilter(GetID())); + AddFilter(bp_message_filter.get()); + + scoped_refptr request_context( + storage_partition_impl_->GetURLRequestContext()); + scoped_refptr render_message_filter( + new RenderMessageFilter( + GetID(), GetBrowserContext(), request_context.get(), + widget_helper_.get(), media_internals, + storage_partition_impl_->GetDOMStorageContext(), + storage_partition_impl_->GetCacheStorageContext())); + AddFilter(render_message_filter.get()); + + render_frame_message_filter_ = new RenderFrameMessageFilter( + GetID(), +#if BUILDFLAG(ENABLE_PLUGINS) + PluginServiceImpl::GetInstance(), +#else + nullptr, +#endif + GetBrowserContext(), + request_context.get(), + widget_helper_.get()); + AddFilter(render_frame_message_filter_.get()); + + BrowserContext* browser_context = GetBrowserContext(); + ResourceContext* resource_context = browser_context->GetResourceContext(); + + scoped_refptr media_request_context( + GetStoragePartition()->GetMediaURLRequestContext()); + + ResourceMessageFilter::GetContextsCallback get_contexts_callback( + base::Bind(&GetContexts, browser_context->GetResourceContext(), + request_context, media_request_context)); + + scoped_refptr blob_storage_context = + ChromeBlobStorageContext::GetFor(browser_context); + + resource_message_filter_ = new ResourceMessageFilter( + GetID(), storage_partition_impl_->GetAppCacheService(), + blob_storage_context.get(), + storage_partition_impl_->GetFileSystemContext(), + storage_partition_impl_->GetServiceWorkerContext(), + get_contexts_callback); + + AddFilter(resource_message_filter_.get()); + + media::AudioManager* audio_manager = + BrowserMainLoop::GetInstance()->audio_manager(); + MediaStreamManager* media_stream_manager = + BrowserMainLoop::GetInstance()->media_stream_manager(); + audio_input_renderer_host_ = new AudioInputRendererHost( + GetID(), base::GetProcId(GetHandle()), audio_manager, + media_stream_manager, AudioMirroringManager::GetInstance(), + BrowserMainLoop::GetInstance()->user_input_monitor()); + AddFilter(audio_input_renderer_host_.get()); + audio_renderer_host_ = new AudioRendererHost( + GetID(), audio_manager, AudioMirroringManager::GetInstance(), + media_stream_manager, + browser_context->GetResourceContext()->GetMediaDeviceIDSalt()); + AddFilter(audio_renderer_host_.get()); + AddFilter( + new MidiHost(GetID(), BrowserMainLoop::GetInstance()->midi_service())); + AddFilter(new AppCacheDispatcherHost( + storage_partition_impl_->GetAppCacheService(), GetID())); + AddFilter(new ClipboardMessageFilter(blob_storage_context)); + AddFilter(new DOMStorageMessageFilter( + storage_partition_impl_->GetDOMStorageContext())); + +#if BUILDFLAG(ENABLE_WEBRTC) + peer_connection_tracker_host_ = new PeerConnectionTrackerHost( + GetID(), webrtc_eventlog_host_.GetWeakPtr()); + AddFilter(peer_connection_tracker_host_.get()); + AddFilter(new MediaStreamDispatcherHost( + GetID(), browser_context->GetResourceContext()->GetMediaDeviceIDSalt(), + media_stream_manager)); + AddFilter(new MediaStreamTrackMetricsHost()); +#endif +#if BUILDFLAG(ENABLE_PLUGINS) + AddFilter(new PepperRendererConnection(GetID())); +#endif + AddFilter(new SpeechRecognitionDispatcherHost( + GetID(), storage_partition_impl_->GetURLRequestContext())); + AddFilter(new FileAPIMessageFilter( + GetID(), storage_partition_impl_->GetURLRequestContext(), + storage_partition_impl_->GetFileSystemContext(), + blob_storage_context.get(), StreamContext::GetFor(browser_context))); + AddFilter(new BlobDispatcherHost( + GetID(), blob_storage_context, + make_scoped_refptr(storage_partition_impl_->GetFileSystemContext()))); + AddFilter(new FileUtilitiesMessageFilter(GetID())); + AddFilter( + new DatabaseMessageFilter(storage_partition_impl_->GetDatabaseTracker())); +#if defined(OS_MACOSX) + AddFilter(new TextInputClientMessageFilter()); +#elif defined(OS_WIN) + AddFilter(new DWriteFontProxyMessageFilter()); + + channel_->AddFilter(new FontCacheDispatcher()); +#endif + + message_port_message_filter_ = new MessagePortMessageFilter( + base::Bind(&RenderWidgetHelper::GetNextRoutingID, + base::Unretained(widget_helper_.get()))); + AddFilter(message_port_message_filter_.get()); + + scoped_refptr cache_storage_filter = + new CacheStorageDispatcherHost(); + cache_storage_filter->Init(storage_partition_impl_->GetCacheStorageContext()); + AddFilter(cache_storage_filter.get()); + + scoped_refptr service_worker_filter = + new ServiceWorkerDispatcherHost( + GetID(), message_port_message_filter_.get(), resource_context); + service_worker_filter->Init( + storage_partition_impl_->GetServiceWorkerContext()); + AddFilter(service_worker_filter.get()); + + AddFilter(new SharedWorkerMessageFilter( + GetID(), resource_context, + WorkerStoragePartition( + storage_partition_impl_->GetURLRequestContext(), + storage_partition_impl_->GetMediaURLRequestContext(), + storage_partition_impl_->GetAppCacheService(), + storage_partition_impl_->GetQuotaManager(), + storage_partition_impl_->GetFileSystemContext(), + storage_partition_impl_->GetDatabaseTracker(), + storage_partition_impl_->GetIndexedDBContext(), + storage_partition_impl_->GetServiceWorkerContext()), + message_port_message_filter_.get())); + +#if BUILDFLAG(ENABLE_WEBRTC) + p2p_socket_dispatcher_host_ = new P2PSocketDispatcherHost( + resource_context, request_context.get()); + AddFilter(p2p_socket_dispatcher_host_.get()); +#endif + + AddFilter(new TraceMessageFilter(GetID())); + AddFilter(new ResolveProxyMsgHelper(request_context.get())); + AddFilter(new QuotaDispatcherHost( + GetID(), storage_partition_impl_->GetQuotaManager(), + GetContentClient()->browser()->CreateQuotaPermissionContext())); + + scoped_refptr service_worker_context( + static_cast( + storage_partition_impl_->GetServiceWorkerContext())); + notification_message_filter_ = new NotificationMessageFilter( + GetID(), storage_partition_impl_->GetPlatformNotificationContext(), + resource_context, service_worker_context, browser_context); + AddFilter(notification_message_filter_.get()); + + AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER)); + AddFilter(new HistogramMessageFilter()); + AddFilter(new MemoryMessageFilter(this)); + AddFilter(new PushMessagingMessageFilter( + GetID(), storage_partition_impl_->GetServiceWorkerContext())); +#if defined(OS_ANDROID) + AddFilter(new ScreenOrientationListenerAndroid()); + synchronous_compositor_filter_ = + new SynchronousCompositorBrowserFilter(GetID()); + AddFilter(synchronous_compositor_filter_.get()); +#endif +} +",1,"void RenderProcessHostImpl::CreateMessageFilters() { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + AddFilter(new ResourceSchedulerFilter(GetID())); + MediaInternals* media_internals = MediaInternals::GetInstance(); + scoped_refptr bp_message_filter( + new BrowserPluginMessageFilter(GetID())); + AddFilter(bp_message_filter.get()); + + scoped_refptr request_context( + storage_partition_impl_->GetURLRequestContext()); + scoped_refptr render_message_filter( + new RenderMessageFilter( + GetID(), GetBrowserContext(), request_context.get(), + widget_helper_.get(), media_internals, + storage_partition_impl_->GetDOMStorageContext(), + storage_partition_impl_->GetCacheStorageContext())); + AddFilter(render_message_filter.get()); + + render_frame_message_filter_ = new RenderFrameMessageFilter( + GetID(), +#if BUILDFLAG(ENABLE_PLUGINS) + PluginServiceImpl::GetInstance(), +#else + nullptr, +#endif + GetBrowserContext(), + request_context.get(), + widget_helper_.get()); + AddFilter(render_frame_message_filter_.get()); + + BrowserContext* browser_context = GetBrowserContext(); + ResourceContext* resource_context = browser_context->GetResourceContext(); + + scoped_refptr media_request_context( + GetStoragePartition()->GetMediaURLRequestContext()); + + ResourceMessageFilter::GetContextsCallback get_contexts_callback( + base::Bind(&GetContexts, browser_context->GetResourceContext(), + request_context, media_request_context)); + + scoped_refptr blob_storage_context = + ChromeBlobStorageContext::GetFor(browser_context); + + resource_message_filter_ = new ResourceMessageFilter( + GetID(), storage_partition_impl_->GetAppCacheService(), + blob_storage_context.get(), + storage_partition_impl_->GetFileSystemContext(), + storage_partition_impl_->GetServiceWorkerContext(), + get_contexts_callback); + + AddFilter(resource_message_filter_.get()); + + media::AudioManager* audio_manager = + BrowserMainLoop::GetInstance()->audio_manager(); + MediaStreamManager* media_stream_manager = + BrowserMainLoop::GetInstance()->media_stream_manager(); + audio_input_renderer_host_ = new AudioInputRendererHost( + GetID(), base::GetProcId(GetHandle()), audio_manager, + media_stream_manager, AudioMirroringManager::GetInstance(), + BrowserMainLoop::GetInstance()->user_input_monitor()); + AddFilter(audio_input_renderer_host_.get()); + audio_renderer_host_ = new AudioRendererHost( + GetID(), audio_manager, BrowserMainLoop::GetInstance()->audio_system(), + AudioMirroringManager::GetInstance(), media_stream_manager, + browser_context->GetResourceContext()->GetMediaDeviceIDSalt()); + AddFilter(audio_renderer_host_.get()); + AddFilter( + new MidiHost(GetID(), BrowserMainLoop::GetInstance()->midi_service())); + AddFilter(new AppCacheDispatcherHost( + storage_partition_impl_->GetAppCacheService(), GetID())); + AddFilter(new ClipboardMessageFilter(blob_storage_context)); + AddFilter(new DOMStorageMessageFilter( + storage_partition_impl_->GetDOMStorageContext())); + +#if BUILDFLAG(ENABLE_WEBRTC) + peer_connection_tracker_host_ = new PeerConnectionTrackerHost( + GetID(), webrtc_eventlog_host_.GetWeakPtr()); + AddFilter(peer_connection_tracker_host_.get()); + AddFilter(new MediaStreamDispatcherHost( + GetID(), browser_context->GetResourceContext()->GetMediaDeviceIDSalt(), + media_stream_manager)); + AddFilter(new MediaStreamTrackMetricsHost()); +#endif +#if BUILDFLAG(ENABLE_PLUGINS) + AddFilter(new PepperRendererConnection(GetID())); +#endif + AddFilter(new SpeechRecognitionDispatcherHost( + GetID(), storage_partition_impl_->GetURLRequestContext())); + AddFilter(new FileAPIMessageFilter( + GetID(), storage_partition_impl_->GetURLRequestContext(), + storage_partition_impl_->GetFileSystemContext(), + blob_storage_context.get(), StreamContext::GetFor(browser_context))); + AddFilter(new BlobDispatcherHost( + GetID(), blob_storage_context, + make_scoped_refptr(storage_partition_impl_->GetFileSystemContext()))); + AddFilter(new FileUtilitiesMessageFilter(GetID())); + AddFilter( + new DatabaseMessageFilter(storage_partition_impl_->GetDatabaseTracker())); +#if defined(OS_MACOSX) + AddFilter(new TextInputClientMessageFilter()); +#elif defined(OS_WIN) + AddFilter(new DWriteFontProxyMessageFilter()); + + channel_->AddFilter(new FontCacheDispatcher()); +#endif + + message_port_message_filter_ = new MessagePortMessageFilter( + base::Bind(&RenderWidgetHelper::GetNextRoutingID, + base::Unretained(widget_helper_.get()))); + AddFilter(message_port_message_filter_.get()); + + scoped_refptr cache_storage_filter = + new CacheStorageDispatcherHost(); + cache_storage_filter->Init(storage_partition_impl_->GetCacheStorageContext()); + AddFilter(cache_storage_filter.get()); + + scoped_refptr service_worker_filter = + new ServiceWorkerDispatcherHost( + GetID(), message_port_message_filter_.get(), resource_context); + service_worker_filter->Init( + storage_partition_impl_->GetServiceWorkerContext()); + AddFilter(service_worker_filter.get()); + + AddFilter(new SharedWorkerMessageFilter( + GetID(), resource_context, + WorkerStoragePartition( + storage_partition_impl_->GetURLRequestContext(), + storage_partition_impl_->GetMediaURLRequestContext(), + storage_partition_impl_->GetAppCacheService(), + storage_partition_impl_->GetQuotaManager(), + storage_partition_impl_->GetFileSystemContext(), + storage_partition_impl_->GetDatabaseTracker(), + storage_partition_impl_->GetIndexedDBContext(), + storage_partition_impl_->GetServiceWorkerContext()), + message_port_message_filter_.get())); + +#if BUILDFLAG(ENABLE_WEBRTC) + p2p_socket_dispatcher_host_ = new P2PSocketDispatcherHost( + resource_context, request_context.get()); + AddFilter(p2p_socket_dispatcher_host_.get()); +#endif + + AddFilter(new TraceMessageFilter(GetID())); + AddFilter(new ResolveProxyMsgHelper(request_context.get())); + AddFilter(new QuotaDispatcherHost( + GetID(), storage_partition_impl_->GetQuotaManager(), + GetContentClient()->browser()->CreateQuotaPermissionContext())); + + scoped_refptr service_worker_context( + static_cast( + storage_partition_impl_->GetServiceWorkerContext())); + notification_message_filter_ = new NotificationMessageFilter( + GetID(), storage_partition_impl_->GetPlatformNotificationContext(), + resource_context, service_worker_context, browser_context); + AddFilter(notification_message_filter_.get()); + + AddFilter(new ProfilerMessageFilter(PROCESS_TYPE_RENDERER)); + AddFilter(new HistogramMessageFilter()); + AddFilter(new MemoryMessageFilter(this)); + AddFilter(new PushMessagingMessageFilter( + GetID(), storage_partition_impl_->GetServiceWorkerContext())); +#if defined(OS_ANDROID) + AddFilter(new ScreenOrientationListenerAndroid()); + synchronous_compositor_filter_ = + new SynchronousCompositorBrowserFilter(GetID()); + AddFilter(synchronous_compositor_filter_.get()); +#endif +} +","@@ -1089,8 +1089,8 @@ void RenderProcessHostImpl::CreateMessageFilters() { + BrowserMainLoop::GetInstance()->user_input_monitor()); + AddFilter(audio_input_renderer_host_.get()); + audio_renderer_host_ = new AudioRendererHost( +- GetID(), audio_manager, AudioMirroringManager::GetInstance(), +- media_stream_manager, ++ GetID(), audio_manager, BrowserMainLoop::GetInstance()->audio_system(), ++ AudioMirroringManager::GetInstance(), media_stream_manager, + browser_context->GetResourceContext()->GetMediaDeviceIDSalt()); + AddFilter(audio_renderer_host_.get()); + AddFilter(",1447,1778,2048 +14882,"bool RenderFrameHostManager::InitRenderFrame( + RenderFrameHostImpl* render_frame_host) { + if (render_frame_host->IsRenderFrameLive()) + return true; + + SiteInstance* site_instance = render_frame_host->GetSiteInstance(); + + int opener_routing_id = MSG_ROUTING_NONE; + if (frame_tree_node_->opener()) + opener_routing_id = GetOpenerRoutingID(site_instance); + + int parent_routing_id = MSG_ROUTING_NONE; + if (frame_tree_node_->parent()) { + parent_routing_id = frame_tree_node_->parent() + ->render_manager() + ->GetRoutingIdForSiteInstance(site_instance); + CHECK_NE(parent_routing_id, MSG_ROUTING_NONE); + } + + int previous_sibling_routing_id = MSG_ROUTING_NONE; + FrameTreeNode* previous_sibling = frame_tree_node_->PreviousSibling(); + if (previous_sibling) { + previous_sibling_routing_id = + previous_sibling->render_manager()->GetRoutingIdForSiteInstance( + site_instance); + CHECK_NE(previous_sibling_routing_id, MSG_ROUTING_NONE); + } + + int proxy_routing_id = MSG_ROUTING_NONE; + RenderFrameProxyHost* existing_proxy = GetRenderFrameProxyHost(site_instance); + if (existing_proxy) { + proxy_routing_id = existing_proxy->GetRoutingID(); + CHECK_NE(proxy_routing_id, MSG_ROUTING_NONE); + if (!existing_proxy->is_render_frame_proxy_live()) + existing_proxy->InitRenderFrameProxy(); + } + + if (!existing_proxy && frame_tree_node_->parent()) { + RenderFrameProxyHost* parent_proxy = RenderFrameProxyHost::FromID( + render_frame_host->GetProcess()->GetID(), parent_routing_id); + if (!parent_proxy || !parent_proxy->is_render_frame_proxy_live()) { + base::debug::SetCrashKeyValue(""initrf_parent_proxy_exists"", + parent_proxy ? ""yes"" : ""no""); + + SiteInstance* parent_instance = + frame_tree_node_->parent()->current_frame_host()->GetSiteInstance(); + base::debug::SetCrashKeyValue( + ""initrf_parent_is_in_same_site_instance"", + site_instance == parent_instance ? ""yes"" : ""no""); + base::debug::SetCrashKeyValue(""initrf_parent_process_is_live"", + frame_tree_node_->parent() + ->current_frame_host() + ->GetProcess() + ->HasConnection() + ? ""yes"" + : ""no""); + base::debug::SetCrashKeyValue( + ""initrf_render_view_is_live"", + render_frame_host->render_view_host()->IsRenderViewLive() ? ""yes"" + : ""no""); + + FrameTreeNode* root = frame_tree_node_->frame_tree()->root(); + if (root != frame_tree_node_->parent()) { + SiteInstance* root_instance = + root->current_frame_host()->GetSiteInstance(); + base::debug::SetCrashKeyValue( + ""initrf_root_is_in_same_site_instance"", + site_instance == root_instance ? ""yes"" : ""no""); + base::debug::SetCrashKeyValue( + ""initrf_root_is_in_same_site_instance_as_parent"", + parent_instance == root_instance ? ""yes"" : ""no""); + base::debug::SetCrashKeyValue(""initrf_root_process_is_live"", + frame_tree_node_->frame_tree() + ->root() + ->current_frame_host() + ->GetProcess() + ->HasConnection() + ? ""yes"" + : ""no""); + + RenderFrameProxyHost* top_proxy = + root->render_manager()->GetRenderFrameProxyHost(site_instance); + if (top_proxy) { + base::debug::SetCrashKeyValue( + ""initrf_root_proxy_is_live"", + top_proxy->is_render_frame_proxy_live() ? ""yes"" : ""no""); + } + } + + base::debug::DumpWithoutCrashing(); + } + } + + return delegate_->CreateRenderFrameForRenderManager( + render_frame_host, proxy_routing_id, opener_routing_id, parent_routing_id, + previous_sibling_routing_id); +} +",0,"bool RenderFrameHostManager::InitRenderFrame( + RenderFrameHostImpl* render_frame_host) { + if (render_frame_host->IsRenderFrameLive()) + return true; + + SiteInstance* site_instance = render_frame_host->GetSiteInstance(); + + int opener_routing_id = MSG_ROUTING_NONE; + if (frame_tree_node_->opener()) + opener_routing_id = GetOpenerRoutingID(site_instance); + + int parent_routing_id = MSG_ROUTING_NONE; + if (frame_tree_node_->parent()) { + parent_routing_id = frame_tree_node_->parent() + ->render_manager() + ->GetRoutingIdForSiteInstance(site_instance); + CHECK_NE(parent_routing_id, MSG_ROUTING_NONE); + } + + int previous_sibling_routing_id = MSG_ROUTING_NONE; + FrameTreeNode* previous_sibling = frame_tree_node_->PreviousSibling(); + if (previous_sibling) { + previous_sibling_routing_id = + previous_sibling->render_manager()->GetRoutingIdForSiteInstance( + site_instance); + CHECK_NE(previous_sibling_routing_id, MSG_ROUTING_NONE); + } + + int proxy_routing_id = MSG_ROUTING_NONE; + RenderFrameProxyHost* existing_proxy = GetRenderFrameProxyHost(site_instance); + if (existing_proxy) { + proxy_routing_id = existing_proxy->GetRoutingID(); + CHECK_NE(proxy_routing_id, MSG_ROUTING_NONE); + if (!existing_proxy->is_render_frame_proxy_live()) + existing_proxy->InitRenderFrameProxy(); + } + + if (!existing_proxy && frame_tree_node_->parent()) { + RenderFrameProxyHost* parent_proxy = RenderFrameProxyHost::FromID( + render_frame_host->GetProcess()->GetID(), parent_routing_id); + if (!parent_proxy || !parent_proxy->is_render_frame_proxy_live()) { + base::debug::SetCrashKeyValue(""initrf_parent_proxy_exists"", + parent_proxy ? ""yes"" : ""no""); + + SiteInstance* parent_instance = + frame_tree_node_->parent()->current_frame_host()->GetSiteInstance(); + base::debug::SetCrashKeyValue( + ""initrf_parent_is_in_same_site_instance"", + site_instance == parent_instance ? ""yes"" : ""no""); + base::debug::SetCrashKeyValue(""initrf_parent_process_is_live"", + frame_tree_node_->parent() + ->current_frame_host() + ->GetProcess() + ->HasConnection() + ? ""yes"" + : ""no""); + base::debug::SetCrashKeyValue( + ""initrf_render_view_is_live"", + render_frame_host->render_view_host()->IsRenderViewLive() ? ""yes"" + : ""no""); + + FrameTreeNode* root = frame_tree_node_->frame_tree()->root(); + if (root != frame_tree_node_->parent()) { + SiteInstance* root_instance = + root->current_frame_host()->GetSiteInstance(); + base::debug::SetCrashKeyValue( + ""initrf_root_is_in_same_site_instance"", + site_instance == root_instance ? ""yes"" : ""no""); + base::debug::SetCrashKeyValue( + ""initrf_root_is_in_same_site_instance_as_parent"", + parent_instance == root_instance ? ""yes"" : ""no""); + base::debug::SetCrashKeyValue(""initrf_root_process_is_live"", + frame_tree_node_->frame_tree() + ->root() + ->current_frame_host() + ->GetProcess() + ->HasConnection() + ? ""yes"" + : ""no""); + + RenderFrameProxyHost* top_proxy = + root->render_manager()->GetRenderFrameProxyHost(site_instance); + if (top_proxy) { + base::debug::SetCrashKeyValue( + ""initrf_root_proxy_is_live"", + top_proxy->is_render_frame_proxy_live() ? ""yes"" : ""no""); + } + } + + base::debug::DumpWithoutCrashing(); + } + } + + return delegate_->CreateRenderFrameForRenderManager( + render_frame_host, proxy_routing_id, opener_routing_id, parent_routing_id, + previous_sibling_routing_id); +} +","@@ -61,7 +61,6 @@ RenderFrameHostManager::RenderFrameHostManager( + delegate_(delegate), + render_frame_delegate_(render_frame_delegate), + render_widget_delegate_(render_widget_delegate), +- interstitial_page_(nullptr), + weak_factory_(this) { + DCHECK(frame_tree_node_); + } +@@ -133,8 +132,8 @@ WebUIImpl* RenderFrameHostManager::GetNavigatingWebUI() const { + } + + RenderWidgetHostView* RenderFrameHostManager::GetRenderWidgetHostView() const { +- if (interstitial_page_) +- return interstitial_page_->GetView(); ++ if (delegate_->GetInterstitialForRenderManager()) ++ return delegate_->GetInterstitialForRenderManager()->GetView(); + if (render_frame_host_) + return render_frame_host_->GetView(); + return nullptr; +@@ -1424,7 +1423,7 @@ RenderFrameHostManager::DetermineSiteInstanceForURL( + // SiteInstances if you type in a cross-site URL. This means we have to + // compare the entry's URL to the last committed entry's URL. + NavigationEntry* current_entry = controller.GetLastCommittedEntry(); +- if (interstitial_page_) { ++ if (delegate_->GetInterstitialForRenderManager()) { + // The interstitial is currently the last committed entry, but we want to + // compare against the last non-interstitial entry. + current_entry = controller.GetEntryAtOffset(-1); +@@ -2825,13 +2824,13 @@ bool RenderFrameHostManager::CanSubframeSwapProcess( + } + + void RenderFrameHostManager::EnsureRenderFrameHostVisibilityConsistent() { +- if (render_frame_host_->GetView() && +- render_frame_host_->render_view_host()->GetWidget()->is_hidden() != +- delegate_->IsHidden()) { ++ RenderWidgetHostView* view = GetRenderWidgetHostView(); ++ if (view && static_cast(view->GetRenderWidgetHost()) ++ ->is_hidden() != delegate_->IsHidden()) { + if (delegate_->IsHidden()) { +- render_frame_host_->GetView()->Hide(); ++ view->Hide(); + } else { +- render_frame_host_->GetView()->Show(); ++ view->Show(); + } + } + }",833,1164,2048 +6733,"static int lookup_open(struct nameidata *nd, struct path *path, + struct file *file, + const struct open_flags *op, + bool got_write, int *opened) +{ + struct dentry *dir = nd->path.dentry; + struct inode *dir_inode = dir->d_inode; + int open_flag = op->open_flag; + struct dentry *dentry; + int error, create_error = 0; + umode_t mode = op->mode; + DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq); + + if (unlikely(IS_DEADDIR(dir_inode))) + return -ENOENT; + + *opened &= ~FILE_CREATED; + dentry = d_lookup(dir, &nd->last); + for (;;) { + if (!dentry) { + dentry = d_alloc_parallel(dir, &nd->last, &wq); + if (IS_ERR(dentry)) + return PTR_ERR(dentry); + } + if (d_in_lookup(dentry)) + break; + + error = d_revalidate(dentry, nd->flags); + if (likely(error > 0)) + break; + if (error) + goto out_dput; + d_invalidate(dentry); + dput(dentry); + dentry = NULL; + } + if (dentry->d_inode) { + /* Cached positive dentry: will open in f_op->open */ + goto out_no_open; + } + + /* + * Checking write permission is tricky, bacuse we don't know if we are + * going to actually need it: O_CREAT opens should work as long as the + * file exists. But checking existence breaks atomicity. The trick is + * to check access and if not granted clear O_CREAT from the flags. + * + * Another problem is returing the ""right"" error value (e.g. for an + * O_EXCL open we want to return EEXIST not EROFS). + */ + if (open_flag & O_CREAT) { + if (!IS_POSIXACL(dir->d_inode)) + mode &= ~current_umask(); + if (unlikely(!got_write)) { + create_error = -EROFS; + open_flag &= ~O_CREAT; + if (open_flag & (O_EXCL | O_TRUNC)) + goto no_open; + /* No side effects, safe to clear O_CREAT */ + } else { + create_error = may_o_create(&nd->path, dentry, mode); + if (create_error) { + open_flag &= ~O_CREAT; + if (open_flag & O_EXCL) + goto no_open; + } + } + } else if ((open_flag & (O_TRUNC|O_WRONLY|O_RDWR)) && + unlikely(!got_write)) { + /* + * No O_CREATE -> atomicity not a requirement -> fall + * back to lookup + open + */ + goto no_open; + } + + if (dir_inode->i_op->atomic_open) { + error = atomic_open(nd, dentry, path, file, op, open_flag, + mode, opened); + if (unlikely(error == -ENOENT) && create_error) + error = create_error; + return error; + } + +no_open: + if (d_in_lookup(dentry)) { + struct dentry *res = dir_inode->i_op->lookup(dir_inode, dentry, + nd->flags); + d_lookup_done(dentry); + if (unlikely(res)) { + if (IS_ERR(res)) { + error = PTR_ERR(res); + goto out_dput; + } + dput(dentry); + dentry = res; + } + } + + /* Negative dentry, just create the file */ + if (!dentry->d_inode && (open_flag & O_CREAT)) { + *opened |= FILE_CREATED; + audit_inode_child(dir_inode, dentry, AUDIT_TYPE_CHILD_CREATE); + if (!dir_inode->i_op->create) { + error = -EACCES; + goto out_dput; + } + error = dir_inode->i_op->create(dir_inode, dentry, mode, + open_flag & O_EXCL); + if (error) + goto out_dput; + fsnotify_create(dir_inode, dentry); + } + if (unlikely(create_error) && !dentry->d_inode) { + error = create_error; + goto out_dput; + } +out_no_open: + path->dentry = dentry; + path->mnt = nd->path.mnt; + return 1; + +out_dput: + dput(dentry); + return error; +} +",0,"static int lookup_open(struct nameidata *nd, struct path *path, + struct file *file, + const struct open_flags *op, + bool got_write, int *opened) +{ + struct dentry *dir = nd->path.dentry; + struct inode *dir_inode = dir->d_inode; + int open_flag = op->open_flag; + struct dentry *dentry; + int error, create_error = 0; + umode_t mode = op->mode; + DECLARE_WAIT_QUEUE_HEAD_ONSTACK(wq); + + if (unlikely(IS_DEADDIR(dir_inode))) + return -ENOENT; + + *opened &= ~FILE_CREATED; + dentry = d_lookup(dir, &nd->last); + for (;;) { + if (!dentry) { + dentry = d_alloc_parallel(dir, &nd->last, &wq); + if (IS_ERR(dentry)) + return PTR_ERR(dentry); + } + if (d_in_lookup(dentry)) + break; + + error = d_revalidate(dentry, nd->flags); + if (likely(error > 0)) + break; + if (error) + goto out_dput; + d_invalidate(dentry); + dput(dentry); + dentry = NULL; + } + if (dentry->d_inode) { + /* Cached positive dentry: will open in f_op->open */ + goto out_no_open; + } + + /* + * Checking write permission is tricky, bacuse we don't know if we are + * going to actually need it: O_CREAT opens should work as long as the + * file exists. But checking existence breaks atomicity. The trick is + * to check access and if not granted clear O_CREAT from the flags. + * + * Another problem is returing the ""right"" error value (e.g. for an + * O_EXCL open we want to return EEXIST not EROFS). + */ + if (open_flag & O_CREAT) { + if (!IS_POSIXACL(dir->d_inode)) + mode &= ~current_umask(); + if (unlikely(!got_write)) { + create_error = -EROFS; + open_flag &= ~O_CREAT; + if (open_flag & (O_EXCL | O_TRUNC)) + goto no_open; + /* No side effects, safe to clear O_CREAT */ + } else { + create_error = may_o_create(&nd->path, dentry, mode); + if (create_error) { + open_flag &= ~O_CREAT; + if (open_flag & O_EXCL) + goto no_open; + } + } + } else if ((open_flag & (O_TRUNC|O_WRONLY|O_RDWR)) && + unlikely(!got_write)) { + /* + * No O_CREATE -> atomicity not a requirement -> fall + * back to lookup + open + */ + goto no_open; + } + + if (dir_inode->i_op->atomic_open) { + error = atomic_open(nd, dentry, path, file, op, open_flag, + mode, opened); + if (unlikely(error == -ENOENT) && create_error) + error = create_error; + return error; + } + +no_open: + if (d_in_lookup(dentry)) { + struct dentry *res = dir_inode->i_op->lookup(dir_inode, dentry, + nd->flags); + d_lookup_done(dentry); + if (unlikely(res)) { + if (IS_ERR(res)) { + error = PTR_ERR(res); + goto out_dput; + } + dput(dentry); + dentry = res; + } + } + + /* Negative dentry, just create the file */ + if (!dentry->d_inode && (open_flag & O_CREAT)) { + *opened |= FILE_CREATED; + audit_inode_child(dir_inode, dentry, AUDIT_TYPE_CHILD_CREATE); + if (!dir_inode->i_op->create) { + error = -EACCES; + goto out_dput; + } + error = dir_inode->i_op->create(dir_inode, dentry, mode, + open_flag & O_EXCL); + if (error) + goto out_dput; + fsnotify_create(dir_inode, dentry); + } + if (unlikely(create_error) && !dentry->d_inode) { + error = create_error; + goto out_dput; + } +out_no_open: + path->dentry = dentry; + path->mnt = nd->path.mnt; + return 1; + +out_dput: + dput(dentry); + return error; +} +","@@ -4362,11 +4362,11 @@ int vfs_rename(struct inode *old_dir, struct dentry *old_dentry, + { + int error; + bool is_dir = d_is_dir(old_dentry); +- const unsigned char *old_name; + struct inode *source = old_dentry->d_inode; + struct inode *target = new_dentry->d_inode; + bool new_is_dir = false; + unsigned max_links = new_dir->i_sb->s_max_links; ++ struct name_snapshot old_name; + + if (source == target) + return 0; +@@ -4413,7 +4413,7 @@ int vfs_rename(struct inode *old_dir, struct dentry *old_dentry, + if (error) + return error; + +- old_name = fsnotify_oldname_init(old_dentry->d_name.name); ++ take_dentry_name_snapshot(&old_name, old_dentry); + dget(new_dentry); + if (!is_dir || (flags & RENAME_EXCHANGE)) + lock_two_nondirectories(source, target); +@@ -4468,14 +4468,14 @@ int vfs_rename(struct inode *old_dir, struct dentry *old_dentry, + inode_unlock(target); + dput(new_dentry); + if (!error) { +- fsnotify_move(old_dir, new_dir, old_name, is_dir, ++ fsnotify_move(old_dir, new_dir, old_name.name, is_dir, + !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry); + if (flags & RENAME_EXCHANGE) { + fsnotify_move(new_dir, old_dir, old_dentry->d_name.name, + new_is_dir, NULL, new_dentry); + } + } +- fsnotify_oldname_free(old_name); ++ release_dentry_name_snapshot(&old_name); + + return error; + }",960,1291,2048 +1453,"do_exec_pty(Session *s, const char *command) +{ + int fdout, ptyfd, ttyfd, ptymaster; + pid_t pid; + + if (s == NULL) + fatal(""do_exec_pty: no session""); + ptyfd = s->ptyfd; + ttyfd = s->ttyfd; + + /* + * Create another descriptor of the pty master side for use as the + * standard input. We could use the original descriptor, but this + * simplifies code in server_loop. The descriptor is bidirectional. + * Do this before forking (and cleanup in the child) so as to + * detect and gracefully fail out-of-fd conditions. + */ + if ((fdout = dup(ptyfd)) < 0) { + error(""%s: dup #1: %s"", __func__, strerror(errno)); + close(ttyfd); + close(ptyfd); + return -1; + } + /* we keep a reference to the pty master */ + if ((ptymaster = dup(ptyfd)) < 0) { + error(""%s: dup #2: %s"", __func__, strerror(errno)); + close(ttyfd); + close(ptyfd); + close(fdout); + return -1; + } + + /* Fork the child. */ + switch ((pid = fork())) { + case -1: + error(""%s: fork: %.100s"", __func__, strerror(errno)); + close(fdout); + close(ptymaster); + close(ttyfd); + close(ptyfd); + return -1; + case 0: + is_child = 1; + + close(fdout); + close(ptymaster); + + /* Child. Reinitialize the log because the pid has changed. */ + log_init(__progname, options.log_level, + options.log_facility, log_stderr); + /* Close the master side of the pseudo tty. */ + close(ptyfd); + + /* Make the pseudo tty our controlling tty. */ + pty_make_controlling_tty(&ttyfd, s->tty); + + /* Redirect stdin/stdout/stderr from the pseudo tty. */ + if (dup2(ttyfd, 0) < 0) + error(""dup2 stdin: %s"", strerror(errno)); + if (dup2(ttyfd, 1) < 0) + error(""dup2 stdout: %s"", strerror(errno)); + if (dup2(ttyfd, 2) < 0) + error(""dup2 stderr: %s"", strerror(errno)); + + /* Close the extra descriptor for the pseudo tty. */ + close(ttyfd); + + /* record login, etc. similar to login(1) */ +#ifndef HAVE_OSF_SIA + if (!(options.use_login && command == NULL)) { +#ifdef _UNICOS + cray_init_job(s->pw); /* set up cray jid and tmpdir */ +#endif /* _UNICOS */ + do_login(s, command); + } +# ifdef LOGIN_NEEDS_UTMPX + else + do_pre_login(s); +# endif +#endif + /* + * Do common processing for the child, such as execing + * the command. + */ + do_child(s, command); + /* NOTREACHED */ + default: + break; + } + +#ifdef _UNICOS + signal(WJSIGNAL, cray_job_termination_handler); +#endif /* _UNICOS */ +#ifdef HAVE_CYGWIN + cygwin_set_impersonation_token(INVALID_HANDLE_VALUE); +#endif + + s->pid = pid; + + /* Parent. Close the slave side of the pseudo tty. */ + close(ttyfd); + + /* Enter interactive session. */ + s->ptymaster = ptymaster; + packet_set_interactive(1, + options.ip_qos_interactive, options.ip_qos_bulk); + if (compat20) { + session_set_fds(s, ptyfd, fdout, -1, 1, 1); + } else { + server_loop(pid, ptyfd, fdout, -1); + /* server_loop _has_ closed ptyfd and fdout. */ + } + return 0; +} +",0,"do_exec_pty(Session *s, const char *command) +{ + int fdout, ptyfd, ttyfd, ptymaster; + pid_t pid; + + if (s == NULL) + fatal(""do_exec_pty: no session""); + ptyfd = s->ptyfd; + ttyfd = s->ttyfd; + + /* + * Create another descriptor of the pty master side for use as the + * standard input. We could use the original descriptor, but this + * simplifies code in server_loop. The descriptor is bidirectional. + * Do this before forking (and cleanup in the child) so as to + * detect and gracefully fail out-of-fd conditions. + */ + if ((fdout = dup(ptyfd)) < 0) { + error(""%s: dup #1: %s"", __func__, strerror(errno)); + close(ttyfd); + close(ptyfd); + return -1; + } + /* we keep a reference to the pty master */ + if ((ptymaster = dup(ptyfd)) < 0) { + error(""%s: dup #2: %s"", __func__, strerror(errno)); + close(ttyfd); + close(ptyfd); + close(fdout); + return -1; + } + + /* Fork the child. */ + switch ((pid = fork())) { + case -1: + error(""%s: fork: %.100s"", __func__, strerror(errno)); + close(fdout); + close(ptymaster); + close(ttyfd); + close(ptyfd); + return -1; + case 0: + is_child = 1; + + close(fdout); + close(ptymaster); + + /* Child. Reinitialize the log because the pid has changed. */ + log_init(__progname, options.log_level, + options.log_facility, log_stderr); + /* Close the master side of the pseudo tty. */ + close(ptyfd); + + /* Make the pseudo tty our controlling tty. */ + pty_make_controlling_tty(&ttyfd, s->tty); + + /* Redirect stdin/stdout/stderr from the pseudo tty. */ + if (dup2(ttyfd, 0) < 0) + error(""dup2 stdin: %s"", strerror(errno)); + if (dup2(ttyfd, 1) < 0) + error(""dup2 stdout: %s"", strerror(errno)); + if (dup2(ttyfd, 2) < 0) + error(""dup2 stderr: %s"", strerror(errno)); + + /* Close the extra descriptor for the pseudo tty. */ + close(ttyfd); + + /* record login, etc. similar to login(1) */ +#ifndef HAVE_OSF_SIA + if (!(options.use_login && command == NULL)) { +#ifdef _UNICOS + cray_init_job(s->pw); /* set up cray jid and tmpdir */ +#endif /* _UNICOS */ + do_login(s, command); + } +# ifdef LOGIN_NEEDS_UTMPX + else + do_pre_login(s); +# endif +#endif + /* + * Do common processing for the child, such as execing + * the command. + */ + do_child(s, command); + /* NOTREACHED */ + default: + break; + } + +#ifdef _UNICOS + signal(WJSIGNAL, cray_job_termination_handler); +#endif /* _UNICOS */ +#ifdef HAVE_CYGWIN + cygwin_set_impersonation_token(INVALID_HANDLE_VALUE); +#endif + + s->pid = pid; + + /* Parent. Close the slave side of the pseudo tty. */ + close(ttyfd); + + /* Enter interactive session. */ + s->ptymaster = ptymaster; + packet_set_interactive(1, + options.ip_qos_interactive, options.ip_qos_bulk); + if (compat20) { + session_set_fds(s, ptyfd, fdout, -1, 1, 1); + } else { + server_loop(pid, ptyfd, fdout, -1); + /* server_loop _has_ closed ptyfd and fdout. */ + } + return 0; +} +","@@ -1322,7 +1322,7 @@ do_setup_env(Session *s, const char *shell) + * Pull in any environment variables that may have + * been set by PAM. + */ +- if (options.use_pam) { ++ if (options.use_pam && !options.use_login) { + char **p; + + p = fetch_pam_child_environment();",888,1219,2048 +5871,"gdImagePtr gdImageRotateBilinear(gdImagePtr src, const float degrees, const int bgColor) +{ + float _angle = (float)((- degrees / 180.0f) * M_PI); + const unsigned int src_w = gdImageSX(src); + const unsigned int src_h = gdImageSY(src); + unsigned int new_width = abs((int)(src_w*cos(_angle))) + abs((int)(src_h*sin(_angle) + 0.5f)); + unsigned int new_height = abs((int)(src_w*sin(_angle))) + abs((int)(src_h*cos(_angle) + 0.5f)); + const gdFixed f_0_5 = gd_ftofx(0.5f); + const gdFixed f_H = gd_itofx(src_h/2); + const gdFixed f_W = gd_itofx(src_w/2); + const gdFixed f_cos = gd_ftofx(cos(-_angle)); + const gdFixed f_sin = gd_ftofx(sin(-_angle)); + const gdFixed f_1 = gd_itofx(1); + unsigned int i; + unsigned int dst_offset_x; + unsigned int dst_offset_y = 0; + unsigned int src_offset_x, src_offset_y; + gdImagePtr dst; + + /* impact perf a bit, but not that much. Implementation for palette + images can be done at a later point. + */ + if (src->trueColor == 0) { + gdImagePaletteToTrueColor(src); + } + + dst = gdImageCreateTrueColor(new_width, new_height); + if (dst == NULL) { + return NULL; + } + dst->saveAlphaFlag = 1; + + for (i = 0; i < new_height; i++) { + unsigned int j; + dst_offset_x = 0; + + for (j=0; j < new_width; j++) { + const gdFixed f_i = gd_itofx((int)i - (int)new_height / 2); + const gdFixed f_j = gd_itofx((int)j - (int)new_width / 2); + const gdFixed f_m = gd_mulfx(f_j,f_sin) + gd_mulfx(f_i,f_cos) + f_0_5 + f_H; + const gdFixed f_n = gd_mulfx(f_j,f_cos) - gd_mulfx(f_i,f_sin) + f_0_5 + f_W; + const unsigned int m = gd_fxtoi(f_m); + const unsigned int n = gd_fxtoi(f_n); + + if ((m > 0) && (m < src_h - 1) && (n > 0) && (n < src_w - 1)) { + const gdFixed f_f = f_m - gd_itofx(m); + const gdFixed f_g = f_n - gd_itofx(n); + const gdFixed f_w1 = gd_mulfx(f_1-f_f, f_1-f_g); + const gdFixed f_w2 = gd_mulfx(f_1-f_f, f_g); + const gdFixed f_w3 = gd_mulfx(f_f, f_1-f_g); + const gdFixed f_w4 = gd_mulfx(f_f, f_g); + + if (n < src_w - 1) { + src_offset_x = n + 1; + src_offset_y = m; + } + + if (m < src_h - 1) { + src_offset_x = n; + src_offset_y = m + 1; + } + + if (!((n >= src_w - 1) || (m >= src_h - 1))) { + src_offset_x = n + 1; + src_offset_y = m + 1; + } + { + const int pixel1 = src->tpixels[src_offset_y][src_offset_x]; + register int pixel2, pixel3, pixel4; + + if (src_offset_y + 1 >= src_h) { + pixel2 = bgColor; + pixel3 = bgColor; + pixel4 = bgColor; + } else if (src_offset_x + 1 >= src_w) { + pixel2 = bgColor; + pixel3 = bgColor; + pixel4 = bgColor; + } else { + pixel2 = src->tpixels[src_offset_y][src_offset_x + 1]; + pixel3 = src->tpixels[src_offset_y + 1][src_offset_x]; + pixel4 = src->tpixels[src_offset_y + 1][src_offset_x + 1]; + } + { + const gdFixed f_r1 = gd_itofx(gdTrueColorGetRed(pixel1)); + const gdFixed f_r2 = gd_itofx(gdTrueColorGetRed(pixel2)); + const gdFixed f_r3 = gd_itofx(gdTrueColorGetRed(pixel3)); + const gdFixed f_r4 = gd_itofx(gdTrueColorGetRed(pixel4)); + const gdFixed f_g1 = gd_itofx(gdTrueColorGetGreen(pixel1)); + const gdFixed f_g2 = gd_itofx(gdTrueColorGetGreen(pixel2)); + const gdFixed f_g3 = gd_itofx(gdTrueColorGetGreen(pixel3)); + const gdFixed f_g4 = gd_itofx(gdTrueColorGetGreen(pixel4)); + const gdFixed f_b1 = gd_itofx(gdTrueColorGetBlue(pixel1)); + const gdFixed f_b2 = gd_itofx(gdTrueColorGetBlue(pixel2)); + const gdFixed f_b3 = gd_itofx(gdTrueColorGetBlue(pixel3)); + const gdFixed f_b4 = gd_itofx(gdTrueColorGetBlue(pixel4)); + const gdFixed f_a1 = gd_itofx(gdTrueColorGetAlpha(pixel1)); + const gdFixed f_a2 = gd_itofx(gdTrueColorGetAlpha(pixel2)); + const gdFixed f_a3 = gd_itofx(gdTrueColorGetAlpha(pixel3)); + const gdFixed f_a4 = gd_itofx(gdTrueColorGetAlpha(pixel4)); + const gdFixed f_red = gd_mulfx(f_w1, f_r1) + gd_mulfx(f_w2, f_r2) + gd_mulfx(f_w3, f_r3) + gd_mulfx(f_w4, f_r4); + const gdFixed f_green = gd_mulfx(f_w1, f_g1) + gd_mulfx(f_w2, f_g2) + gd_mulfx(f_w3, f_g3) + gd_mulfx(f_w4, f_g4); + const gdFixed f_blue = gd_mulfx(f_w1, f_b1) + gd_mulfx(f_w2, f_b2) + gd_mulfx(f_w3, f_b3) + gd_mulfx(f_w4, f_b4); + const gdFixed f_alpha = gd_mulfx(f_w1, f_a1) + gd_mulfx(f_w2, f_a2) + gd_mulfx(f_w3, f_a3) + gd_mulfx(f_w4, f_a4); + + const unsigned char red = (unsigned char) CLAMP(gd_fxtoi(f_red), 0, 255); + const unsigned char green = (unsigned char) CLAMP(gd_fxtoi(f_green), 0, 255); + const unsigned char blue = (unsigned char) CLAMP(gd_fxtoi(f_blue), 0, 255); + const unsigned char alpha = (unsigned char) CLAMP(gd_fxtoi(f_alpha), 0, 127); + + dst->tpixels[dst_offset_y][dst_offset_x++] = gdTrueColorAlpha(red, green, blue, alpha); + } + } + } else { + dst->tpixels[dst_offset_y][dst_offset_x++] = bgColor; + } + } + dst_offset_y++; + } + return dst; +} +",0,"gdImagePtr gdImageRotateBilinear(gdImagePtr src, const float degrees, const int bgColor) +{ + float _angle = (float)((- degrees / 180.0f) * M_PI); + const unsigned int src_w = gdImageSX(src); + const unsigned int src_h = gdImageSY(src); + unsigned int new_width = abs((int)(src_w*cos(_angle))) + abs((int)(src_h*sin(_angle) + 0.5f)); + unsigned int new_height = abs((int)(src_w*sin(_angle))) + abs((int)(src_h*cos(_angle) + 0.5f)); + const gdFixed f_0_5 = gd_ftofx(0.5f); + const gdFixed f_H = gd_itofx(src_h/2); + const gdFixed f_W = gd_itofx(src_w/2); + const gdFixed f_cos = gd_ftofx(cos(-_angle)); + const gdFixed f_sin = gd_ftofx(sin(-_angle)); + const gdFixed f_1 = gd_itofx(1); + unsigned int i; + unsigned int dst_offset_x; + unsigned int dst_offset_y = 0; + unsigned int src_offset_x, src_offset_y; + gdImagePtr dst; + + /* impact perf a bit, but not that much. Implementation for palette + images can be done at a later point. + */ + if (src->trueColor == 0) { + gdImagePaletteToTrueColor(src); + } + + dst = gdImageCreateTrueColor(new_width, new_height); + if (dst == NULL) { + return NULL; + } + dst->saveAlphaFlag = 1; + + for (i = 0; i < new_height; i++) { + unsigned int j; + dst_offset_x = 0; + + for (j=0; j < new_width; j++) { + const gdFixed f_i = gd_itofx((int)i - (int)new_height / 2); + const gdFixed f_j = gd_itofx((int)j - (int)new_width / 2); + const gdFixed f_m = gd_mulfx(f_j,f_sin) + gd_mulfx(f_i,f_cos) + f_0_5 + f_H; + const gdFixed f_n = gd_mulfx(f_j,f_cos) - gd_mulfx(f_i,f_sin) + f_0_5 + f_W; + const unsigned int m = gd_fxtoi(f_m); + const unsigned int n = gd_fxtoi(f_n); + + if ((m > 0) && (m < src_h - 1) && (n > 0) && (n < src_w - 1)) { + const gdFixed f_f = f_m - gd_itofx(m); + const gdFixed f_g = f_n - gd_itofx(n); + const gdFixed f_w1 = gd_mulfx(f_1-f_f, f_1-f_g); + const gdFixed f_w2 = gd_mulfx(f_1-f_f, f_g); + const gdFixed f_w3 = gd_mulfx(f_f, f_1-f_g); + const gdFixed f_w4 = gd_mulfx(f_f, f_g); + + if (n < src_w - 1) { + src_offset_x = n + 1; + src_offset_y = m; + } + + if (m < src_h - 1) { + src_offset_x = n; + src_offset_y = m + 1; + } + + if (!((n >= src_w - 1) || (m >= src_h - 1))) { + src_offset_x = n + 1; + src_offset_y = m + 1; + } + { + const int pixel1 = src->tpixels[src_offset_y][src_offset_x]; + register int pixel2, pixel3, pixel4; + + if (src_offset_y + 1 >= src_h) { + pixel2 = bgColor; + pixel3 = bgColor; + pixel4 = bgColor; + } else if (src_offset_x + 1 >= src_w) { + pixel2 = bgColor; + pixel3 = bgColor; + pixel4 = bgColor; + } else { + pixel2 = src->tpixels[src_offset_y][src_offset_x + 1]; + pixel3 = src->tpixels[src_offset_y + 1][src_offset_x]; + pixel4 = src->tpixels[src_offset_y + 1][src_offset_x + 1]; + } + { + const gdFixed f_r1 = gd_itofx(gdTrueColorGetRed(pixel1)); + const gdFixed f_r2 = gd_itofx(gdTrueColorGetRed(pixel2)); + const gdFixed f_r3 = gd_itofx(gdTrueColorGetRed(pixel3)); + const gdFixed f_r4 = gd_itofx(gdTrueColorGetRed(pixel4)); + const gdFixed f_g1 = gd_itofx(gdTrueColorGetGreen(pixel1)); + const gdFixed f_g2 = gd_itofx(gdTrueColorGetGreen(pixel2)); + const gdFixed f_g3 = gd_itofx(gdTrueColorGetGreen(pixel3)); + const gdFixed f_g4 = gd_itofx(gdTrueColorGetGreen(pixel4)); + const gdFixed f_b1 = gd_itofx(gdTrueColorGetBlue(pixel1)); + const gdFixed f_b2 = gd_itofx(gdTrueColorGetBlue(pixel2)); + const gdFixed f_b3 = gd_itofx(gdTrueColorGetBlue(pixel3)); + const gdFixed f_b4 = gd_itofx(gdTrueColorGetBlue(pixel4)); + const gdFixed f_a1 = gd_itofx(gdTrueColorGetAlpha(pixel1)); + const gdFixed f_a2 = gd_itofx(gdTrueColorGetAlpha(pixel2)); + const gdFixed f_a3 = gd_itofx(gdTrueColorGetAlpha(pixel3)); + const gdFixed f_a4 = gd_itofx(gdTrueColorGetAlpha(pixel4)); + const gdFixed f_red = gd_mulfx(f_w1, f_r1) + gd_mulfx(f_w2, f_r2) + gd_mulfx(f_w3, f_r3) + gd_mulfx(f_w4, f_r4); + const gdFixed f_green = gd_mulfx(f_w1, f_g1) + gd_mulfx(f_w2, f_g2) + gd_mulfx(f_w3, f_g3) + gd_mulfx(f_w4, f_g4); + const gdFixed f_blue = gd_mulfx(f_w1, f_b1) + gd_mulfx(f_w2, f_b2) + gd_mulfx(f_w3, f_b3) + gd_mulfx(f_w4, f_b4); + const gdFixed f_alpha = gd_mulfx(f_w1, f_a1) + gd_mulfx(f_w2, f_a2) + gd_mulfx(f_w3, f_a3) + gd_mulfx(f_w4, f_a4); + + const unsigned char red = (unsigned char) CLAMP(gd_fxtoi(f_red), 0, 255); + const unsigned char green = (unsigned char) CLAMP(gd_fxtoi(f_green), 0, 255); + const unsigned char blue = (unsigned char) CLAMP(gd_fxtoi(f_blue), 0, 255); + const unsigned char alpha = (unsigned char) CLAMP(gd_fxtoi(f_alpha), 0, 127); + + dst->tpixels[dst_offset_y][dst_offset_x++] = gdTrueColorAlpha(red, green, blue, alpha); + } + } + } else { + dst->tpixels[dst_offset_y][dst_offset_x++] = bgColor; + } + } + dst_offset_y++; + } + return dst; +} +","@@ -953,9 +953,6 @@ static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsi + double dTotalWeight = 0.0; + int iSrc; + +- res->ContribRow[u].Left = iLeft; +- res->ContribRow[u].Right = iRight; +- + /* Cut edge points to fit in filter window in case of spill-off */ + if (iRight - iLeft + 1 > windows_size) { + if (iLeft < ((int)src_size - 1 / 2)) { +@@ -965,6 +962,9 @@ static inline LineContribType *_gdContributionsCalc(unsigned int line_size, unsi + } + } + ++ res->ContribRow[u].Left = iLeft; ++ res->ContribRow[u].Right = iRight; ++ + for (iSrc = iLeft; iSrc <= iRight; iSrc++) { + dTotalWeight += (res->ContribRow[u].Weights[iSrc-iLeft] = scale_f_d * (*pFilter)(scale_f_d * (dCenter - (double)iSrc))); + }",1703,2034,2048 +13157,"void RenderFrameImpl::SendDidCommitProvisionalLoad( + blink::WebFrame* frame, + blink::WebHistoryCommitType commit_type, + const blink::WebHistoryItem& item) { + DCHECK(!frame_ || frame_ == frame); + WebDataSource* ds = frame->dataSource(); + DCHECK(ds); + + const WebURLRequest& request = ds->request(); + const WebURLResponse& response = ds->response(); + + DocumentState* document_state = DocumentState::FromDataSource(ds); + NavigationStateImpl* navigation_state = + static_cast(document_state->navigation_state()); + InternalDocumentStateData* internal_data = + InternalDocumentStateData::FromDocumentState(document_state); + + FrameHostMsg_DidCommitProvisionalLoad_Params params; + params.http_status_code = response.httpStatusCode(); + params.url_is_unreachable = ds->hasUnreachableURL(); + params.is_post = false; + params.intended_as_new_entry = + navigation_state->request_params().intended_as_new_entry; + params.did_create_new_entry = commit_type == blink::WebStandardCommit; + params.post_id = -1; + params.page_id = render_view_->page_id_; + params.nav_entry_id = navigation_state->request_params().nav_entry_id; + params.render_view_routing_id = render_view_->routing_id(); + params.socket_address.set_host(response.remoteIPAddress().utf8()); + params.socket_address.set_port(response.remotePort()); + WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response); + if (extra_data) + params.was_fetched_via_proxy = extra_data->was_fetched_via_proxy(); + params.was_within_same_page = navigation_state->WasWithinSamePage(); + params.security_info = response.securityInfo(); + + params.url = GetLoadingUrl(); + DCHECK(!is_swapped_out_ || params.url == GURL(kSwappedOutURL)); + + if (!is_swapped_out_) { + std::string scheme = frame->document().securityOrigin().protocol().utf8(); + if (url::IsStandard(scheme.c_str(), + url::Component(0, static_cast(scheme.length())))) { + params.origin = frame->document().securityOrigin(); + } + } + + if (frame->document().baseURL() != params.url) + params.base_url = frame->document().baseURL(); + + GetRedirectChain(ds, ¶ms.redirects); + params.should_update_history = !ds->hasUnreachableURL() && + !response.isMultipartPayload() && (response.httpStatusCode() != 404); + + params.searchable_form_url = internal_data->searchable_form_url(); + params.searchable_form_encoding = internal_data->searchable_form_encoding(); + + params.gesture = render_view_->navigation_gesture_; + render_view_->navigation_gesture_ = NavigationGestureUnknown; + + HistoryEntry* entry = render_view_->history_controller()->GetCurrentEntry(); + if (!SiteIsolationPolicy::UseSubframeNavigationEntries()) { + if (entry) + params.page_state = HistoryEntryToPageState(entry); + else + params.page_state = PageState::CreateFromURL(request.url()); + } else { + params.page_state = SingleHistoryItemToPageState(item); + } + params.item_sequence_number = item.itemSequenceNumber(); + params.document_sequence_number = item.documentSequenceNumber(); + + if (!frame->parent()) { + + render_view_->webview()->zoomLimitsChanged( + ZoomFactorToZoomLevel(kMinimumZoomFactor), + ZoomFactorToZoomLevel(kMaximumZoomFactor)); + + HostZoomLevels::iterator host_zoom = + render_view_->host_zoom_levels_.find(GURL(request.url())); + if (render_view_->webview()->mainFrame()->document().isPluginDocument()) { + render_view_->webview()->setZoomLevel(0); + } else { + if (host_zoom != render_view_->host_zoom_levels_.end()) + render_view_->webview()->setZoomLevel(host_zoom->second); + } + + if (host_zoom != render_view_->host_zoom_levels_.end()) { + render_view_->host_zoom_levels_.erase(host_zoom); + } + + params.contents_mime_type = ds->response().mimeType().utf8(); + + params.transition = navigation_state->GetTransitionType(); + if (!ui::PageTransitionIsMainFrame(params.transition)) { + params.transition = ui::PAGE_TRANSITION_LINK; + } + + if (ds->isClientRedirect()) { + params.referrer = + Referrer(params.redirects[0], ds->request().referrerPolicy()); + params.transition = ui::PageTransitionFromInt( + params.transition | ui::PAGE_TRANSITION_CLIENT_REDIRECT); + } else { + params.referrer = RenderViewImpl::GetReferrerFromRequest( + frame, ds->request()); + } + + base::string16 method = request.httpMethod(); + if (base::EqualsASCII(method, ""POST"")) { + params.is_post = true; + params.post_id = ExtractPostId(entry); + } + + params.is_overriding_user_agent = internal_data->is_overriding_user_agent(); + + params.original_request_url = GetOriginalRequestURL(ds); + + params.history_list_was_cleared = + navigation_state->request_params().should_clear_history_list; + + params.report_type = static_cast( + frame->dataSource()->request().inputPerfMetricReportPolicy()); + params.ui_timestamp = base::TimeTicks() + base::TimeDelta::FromSecondsD( + frame->dataSource()->request().uiStartTime()); + + UMA_HISTOGRAM_COUNTS_10000(""Memory.GlyphPagesPerLoad"", + blink::WebGlyphCache::pageCount()); + + Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params)); + } else { + if (commit_type == blink::WebStandardCommit) + params.transition = ui::PAGE_TRANSITION_MANUAL_SUBFRAME; + else + params.transition = ui::PAGE_TRANSITION_AUTO_SUBFRAME; + + DCHECK(!navigation_state->request_params().should_clear_history_list); + params.history_list_was_cleared = false; + params.report_type = FrameMsg_UILoadMetricsReportType::NO_REPORT; + + if (!is_swapped_out()) + Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params)); + } + + navigation_state->set_transition_type(ui::PAGE_TRANSITION_LINK); +} +",0,"void RenderFrameImpl::SendDidCommitProvisionalLoad( + blink::WebFrame* frame, + blink::WebHistoryCommitType commit_type, + const blink::WebHistoryItem& item) { + DCHECK(!frame_ || frame_ == frame); + WebDataSource* ds = frame->dataSource(); + DCHECK(ds); + + const WebURLRequest& request = ds->request(); + const WebURLResponse& response = ds->response(); + + DocumentState* document_state = DocumentState::FromDataSource(ds); + NavigationStateImpl* navigation_state = + static_cast(document_state->navigation_state()); + InternalDocumentStateData* internal_data = + InternalDocumentStateData::FromDocumentState(document_state); + + FrameHostMsg_DidCommitProvisionalLoad_Params params; + params.http_status_code = response.httpStatusCode(); + params.url_is_unreachable = ds->hasUnreachableURL(); + params.is_post = false; + params.intended_as_new_entry = + navigation_state->request_params().intended_as_new_entry; + params.did_create_new_entry = commit_type == blink::WebStandardCommit; + params.post_id = -1; + params.page_id = render_view_->page_id_; + params.nav_entry_id = navigation_state->request_params().nav_entry_id; + params.render_view_routing_id = render_view_->routing_id(); + params.socket_address.set_host(response.remoteIPAddress().utf8()); + params.socket_address.set_port(response.remotePort()); + WebURLResponseExtraDataImpl* extra_data = GetExtraDataFromResponse(response); + if (extra_data) + params.was_fetched_via_proxy = extra_data->was_fetched_via_proxy(); + params.was_within_same_page = navigation_state->WasWithinSamePage(); + params.security_info = response.securityInfo(); + + params.url = GetLoadingUrl(); + DCHECK(!is_swapped_out_ || params.url == GURL(kSwappedOutURL)); + + if (!is_swapped_out_) { + std::string scheme = frame->document().securityOrigin().protocol().utf8(); + if (url::IsStandard(scheme.c_str(), + url::Component(0, static_cast(scheme.length())))) { + params.origin = frame->document().securityOrigin(); + } + } + + if (frame->document().baseURL() != params.url) + params.base_url = frame->document().baseURL(); + + GetRedirectChain(ds, ¶ms.redirects); + params.should_update_history = !ds->hasUnreachableURL() && + !response.isMultipartPayload() && (response.httpStatusCode() != 404); + + params.searchable_form_url = internal_data->searchable_form_url(); + params.searchable_form_encoding = internal_data->searchable_form_encoding(); + + params.gesture = render_view_->navigation_gesture_; + render_view_->navigation_gesture_ = NavigationGestureUnknown; + + HistoryEntry* entry = render_view_->history_controller()->GetCurrentEntry(); + if (!SiteIsolationPolicy::UseSubframeNavigationEntries()) { + if (entry) + params.page_state = HistoryEntryToPageState(entry); + else + params.page_state = PageState::CreateFromURL(request.url()); + } else { + params.page_state = SingleHistoryItemToPageState(item); + } + params.item_sequence_number = item.itemSequenceNumber(); + params.document_sequence_number = item.documentSequenceNumber(); + + if (!frame->parent()) { + + render_view_->webview()->zoomLimitsChanged( + ZoomFactorToZoomLevel(kMinimumZoomFactor), + ZoomFactorToZoomLevel(kMaximumZoomFactor)); + + HostZoomLevels::iterator host_zoom = + render_view_->host_zoom_levels_.find(GURL(request.url())); + if (render_view_->webview()->mainFrame()->document().isPluginDocument()) { + render_view_->webview()->setZoomLevel(0); + } else { + if (host_zoom != render_view_->host_zoom_levels_.end()) + render_view_->webview()->setZoomLevel(host_zoom->second); + } + + if (host_zoom != render_view_->host_zoom_levels_.end()) { + render_view_->host_zoom_levels_.erase(host_zoom); + } + + params.contents_mime_type = ds->response().mimeType().utf8(); + + params.transition = navigation_state->GetTransitionType(); + if (!ui::PageTransitionIsMainFrame(params.transition)) { + params.transition = ui::PAGE_TRANSITION_LINK; + } + + if (ds->isClientRedirect()) { + params.referrer = + Referrer(params.redirects[0], ds->request().referrerPolicy()); + params.transition = ui::PageTransitionFromInt( + params.transition | ui::PAGE_TRANSITION_CLIENT_REDIRECT); + } else { + params.referrer = RenderViewImpl::GetReferrerFromRequest( + frame, ds->request()); + } + + base::string16 method = request.httpMethod(); + if (base::EqualsASCII(method, ""POST"")) { + params.is_post = true; + params.post_id = ExtractPostId(entry); + } + + params.is_overriding_user_agent = internal_data->is_overriding_user_agent(); + + params.original_request_url = GetOriginalRequestURL(ds); + + params.history_list_was_cleared = + navigation_state->request_params().should_clear_history_list; + + params.report_type = static_cast( + frame->dataSource()->request().inputPerfMetricReportPolicy()); + params.ui_timestamp = base::TimeTicks() + base::TimeDelta::FromSecondsD( + frame->dataSource()->request().uiStartTime()); + + UMA_HISTOGRAM_COUNTS_10000(""Memory.GlyphPagesPerLoad"", + blink::WebGlyphCache::pageCount()); + + Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params)); + } else { + if (commit_type == blink::WebStandardCommit) + params.transition = ui::PAGE_TRANSITION_MANUAL_SUBFRAME; + else + params.transition = ui::PAGE_TRANSITION_AUTO_SUBFRAME; + + DCHECK(!navigation_state->request_params().should_clear_history_list); + params.history_list_was_cleared = false; + params.report_type = FrameMsg_UILoadMetricsReportType::NO_REPORT; + + if (!is_swapped_out()) + Send(new FrameHostMsg_DidCommitProvisionalLoad(routing_id_, params)); + } + + navigation_state->set_transition_type(ui::PAGE_TRANSITION_LINK); +} +","@@ -115,6 +115,7 @@ + #include ""media/blink/webmediaplayer_impl.h"" + #include ""media/blink/webmediaplayer_params.h"" + #include ""media/renderers/gpu_video_accelerator_factories.h"" ++#include ""mojo/common/url_type_converters.h"" + #include ""net/base/data_url.h"" + #include ""net/base/net_errors.h"" + #include ""net/base/registry_controlled_domains/registry_controlled_domain.h"" +@@ -125,6 +126,7 @@ + #include ""third_party/WebKit/public/platform/WebURLError.h"" + #include ""third_party/WebKit/public/platform/WebURLResponse.h"" + #include ""third_party/WebKit/public/platform/WebVector.h"" ++#include ""third_party/WebKit/public/platform/modules/webusb/WebUSBClient.h"" + #include ""third_party/WebKit/public/web/WebColorSuggestion.h"" + #include ""third_party/WebKit/public/web/WebDocument.h"" + #include ""third_party/WebKit/public/web/WebFrameWidget.h"" +@@ -174,6 +176,8 @@ + #include ""content/renderer/media/android/webmediaplayer_android.h"" + #else + #include ""cc/blink/context_provider_web_context.h"" ++#include ""content/renderer/usb/web_usb_client_impl.h"" ++#include ""device/devices_app/public/cpp/constants.h"" + #endif + + #if defined(ENABLE_PEPPER_CDMS) +@@ -705,6 +709,8 @@ RenderFrameImpl::RenderFrameImpl(const CreateParams& params) + #endif + + manifest_manager_ = new ManifestManager(this); ++ ++ GetServiceRegistry()->ConnectToRemoteService(mojo::GetProxy(&mojo_shell_)); + } + + RenderFrameImpl::~RenderFrameImpl() { +@@ -3812,6 +3818,17 @@ blink::WebBluetooth* RenderFrameImpl::bluetooth() { + return bluetooth_.get(); + } + ++blink::WebUSBClient* RenderFrameImpl::usbClient() { ++#if !defined(OS_ANDROID) ++ if (!usb_client_) { ++ mojo::ServiceProviderPtr device_services = ++ ConnectToApplication(GURL(device::kDevicesMojoAppUrl)); ++ usb_client_.reset(new WebUSBClientImpl(device_services.Pass())); ++ } ++#endif ++ return usb_client_.get(); ++} ++ + #if defined(ENABLE_WEBVR) + blink::WebVRClient* RenderFrameImpl::webVRClient() { + if (!vr_dispatcher_) +@@ -5003,17 +5020,9 @@ media::MediaPermission* RenderFrameImpl::GetMediaPermission() { + #if defined(ENABLE_MOJO_MEDIA) + media::interfaces::ServiceFactory* RenderFrameImpl::GetMediaServiceFactory() { + if (!media_service_factory_) { +- mojo::InterfacePtr shell_ptr; +- GetServiceRegistry()->ConnectToRemoteService(mojo::GetProxy(&shell_ptr)); +- +- mojo::ServiceProviderPtr service_provider; +- mojo::URLRequestPtr request(mojo::URLRequest::New()); +- request->url = mojo::String::From(""mojo:media""); +- shell_ptr->ConnectToApplication(request.Pass(), GetProxy(&service_provider), +- nullptr, nullptr); +- ++ mojo::ServiceProviderPtr service_provider = ++ ConnectToApplication(GURL(""mojo:media"")); + mojo::ConnectToService(service_provider.get(), &media_service_factory_); +- + media_service_factory_.set_connection_error_handler( + base::Bind(&RenderFrameImpl::OnMediaServiceFactoryConnectionError, + base::Unretained(this))); +@@ -5075,4 +5084,15 @@ void RenderFrameImpl::RegisterMojoServices() { + } + } + ++mojo::ServiceProviderPtr RenderFrameImpl::ConnectToApplication( ++ const GURL& url) { ++ DCHECK(mojo_shell_); ++ mojo::ServiceProviderPtr service_provider; ++ mojo::URLRequestPtr request(mojo::URLRequest::New()); ++ request->url = mojo::String::From(url); ++ mojo_shell_->ConnectToApplication(request.Pass(), GetProxy(&service_provider), ++ nullptr, nullptr); ++ return service_provider.Pass(); ++} ++ + } // namespace content",1333,1664,2048 +5800,"int kvm_arch_hardware_enable(void) +{ + 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(); + if (ret != 0) + return ret; + + local_tsc = rdtsc(); + 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()) + kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu); + 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; + backwards_tsc_observed = true; + 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; + kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu); + } + + /* + * 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; +} +",0,"int kvm_arch_hardware_enable(void) +{ + 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(); + if (ret != 0) + return ret; + + local_tsc = rdtsc(); + 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()) + kvm_make_request(KVM_REQ_CLOCK_UPDATE, vcpu); + 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; + backwards_tsc_observed = true; + 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; + kvm_make_request(KVM_REQ_MASTERCLOCK_UPDATE, vcpu); + } + + /* + * 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; +} +","@@ -3572,9 +3572,11 @@ static int kvm_vm_ioctl_get_pit(struct kvm *kvm, struct kvm_pit_state *ps) + + static int kvm_vm_ioctl_set_pit(struct kvm *kvm, struct kvm_pit_state *ps) + { ++ int i; + 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); ++ for (i = 0; i < 3; i++) ++ kvm_pit_load_count(kvm, i, ps->channels[i].count, 0); + mutex_unlock(&kvm->arch.vpit->pit_state.lock); + return 0; + } +@@ -3593,6 +3595,7 @@ static int kvm_vm_ioctl_get_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps) + static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps) + { + int start = 0; ++ int i; + 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; +@@ -3602,7 +3605,8 @@ static int kvm_vm_ioctl_set_pit2(struct kvm *kvm, struct kvm_pit_state2 *ps) + 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); ++ for (i = 0; i < 3; i++) ++ kvm_pit_load_count(kvm, i, kvm->arch.vpit->pit_state.channels[i].count, start); + mutex_unlock(&kvm->arch.vpit->pit_state.lock); + return 0; + }",1019,1350,2048 +4867,"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 */ +",0,"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 */ +","@@ -819,9 +819,18 @@ static int readContigTilesIntoBuffer (TIFF* in, uint8* buf, + } + } + +- tilebuf = _TIFFmalloc(tile_buffsize); ++ /* Add 3 padding bytes for extractContigSamplesShifted32bits */ ++ if( tile_buffsize > 0xFFFFFFFFU - 3 ) ++ { ++ 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)",1041,1372,2048 +15917,"error::Error GLES2DecoderImpl::HandleTexImage2D(uint32_t immediate_data_size, + const volatile void* cmd_data) { + const char* func_name = ""glTexImage2D""; + const volatile gles2::cmds::TexImage2D& c = + *static_cast(cmd_data); + TRACE_EVENT2(""gpu"", ""GLES2DecoderImpl::HandleTexImage2D"", + ""width"", c.width, ""height"", c.height); + texture_state_.tex_image_failed = true; + GLenum target = static_cast(c.target); + GLint level = static_cast(c.level); + GLint internal_format = static_cast(c.internalformat); + GLsizei width = static_cast(c.width); + GLsizei height = static_cast(c.height); + GLint border = static_cast(c.border); + GLenum format = static_cast(c.format); + GLenum type = static_cast(c.type); + uint32_t pixels_shm_id = static_cast(c.pixels_shm_id); + uint32_t pixels_shm_offset = static_cast(c.pixels_shm_offset); + + if (width < 0 || height < 0) { + LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, func_name, ""dimensions < 0""); + return error::kNoError; + } + + PixelStoreParams params; + Buffer* buffer = state_.bound_pixel_unpack_buffer.get(); + if (buffer) { + if (pixels_shm_id) + return error::kInvalidArguments; + if (buffer->GetMappedRange()) { + LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, func_name, + ""pixel unpack buffer should not be mapped to client memory""); + return error::kNoError; + } + params = state_.GetUnpackParams(ContextState::k2D); + } else { + if (!pixels_shm_id && pixels_shm_offset) + return error::kInvalidArguments; + params.alignment = state_.unpack_alignment; + } + uint32_t pixels_size; + uint32_t skip_size; + uint32_t padding; + if (!GLES2Util::ComputeImageDataSizesES3(width, height, 1, + format, type, + params, + &pixels_size, + nullptr, + nullptr, + &skip_size, + &padding)) { + return error::kOutOfBounds; + } + DCHECK_EQ(0u, skip_size); + + const void* pixels; + if (pixels_shm_id) { + pixels = GetSharedMemoryAs( + pixels_shm_id, pixels_shm_offset, pixels_size); + if (!pixels) + return error::kOutOfBounds; + } else { + pixels = reinterpret_cast(pixels_shm_offset); + } + + uint32_t num_pixels; + if (workarounds().simulate_out_of_memory_on_large_textures && + (!SafeMultiplyUint32(width, height, &num_pixels) || + (num_pixels >= 4096 * 4096))) { + LOCAL_SET_GL_ERROR(GL_OUT_OF_MEMORY, func_name, ""synthetic out of memory""); + return error::kNoError; + } + + TextureManager::DoTexImageArguments args = { + target, level, internal_format, width, height, 1, border, format, type, + pixels, pixels_size, padding, + TextureManager::DoTexImageArguments::kTexImage2D }; + texture_manager()->ValidateAndDoTexImage( + &texture_state_, &state_, &framebuffer_state_, func_name, args); + + ExitCommandProcessingEarly(); + return error::kNoError; +} +",0,"error::Error GLES2DecoderImpl::HandleTexImage2D(uint32_t immediate_data_size, + const volatile void* cmd_data) { + const char* func_name = ""glTexImage2D""; + const volatile gles2::cmds::TexImage2D& c = + *static_cast(cmd_data); + TRACE_EVENT2(""gpu"", ""GLES2DecoderImpl::HandleTexImage2D"", + ""width"", c.width, ""height"", c.height); + texture_state_.tex_image_failed = true; + GLenum target = static_cast(c.target); + GLint level = static_cast(c.level); + GLint internal_format = static_cast(c.internalformat); + GLsizei width = static_cast(c.width); + GLsizei height = static_cast(c.height); + GLint border = static_cast(c.border); + GLenum format = static_cast(c.format); + GLenum type = static_cast(c.type); + uint32_t pixels_shm_id = static_cast(c.pixels_shm_id); + uint32_t pixels_shm_offset = static_cast(c.pixels_shm_offset); + + if (width < 0 || height < 0) { + LOCAL_SET_GL_ERROR(GL_INVALID_VALUE, func_name, ""dimensions < 0""); + return error::kNoError; + } + + PixelStoreParams params; + Buffer* buffer = state_.bound_pixel_unpack_buffer.get(); + if (buffer) { + if (pixels_shm_id) + return error::kInvalidArguments; + if (buffer->GetMappedRange()) { + LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, func_name, + ""pixel unpack buffer should not be mapped to client memory""); + return error::kNoError; + } + params = state_.GetUnpackParams(ContextState::k2D); + } else { + if (!pixels_shm_id && pixels_shm_offset) + return error::kInvalidArguments; + params.alignment = state_.unpack_alignment; + } + uint32_t pixels_size; + uint32_t skip_size; + uint32_t padding; + if (!GLES2Util::ComputeImageDataSizesES3(width, height, 1, + format, type, + params, + &pixels_size, + nullptr, + nullptr, + &skip_size, + &padding)) { + return error::kOutOfBounds; + } + DCHECK_EQ(0u, skip_size); + + const void* pixels; + if (pixels_shm_id) { + pixels = GetSharedMemoryAs( + pixels_shm_id, pixels_shm_offset, pixels_size); + if (!pixels) + return error::kOutOfBounds; + } else { + pixels = reinterpret_cast(pixels_shm_offset); + } + + uint32_t num_pixels; + if (workarounds().simulate_out_of_memory_on_large_textures && + (!SafeMultiplyUint32(width, height, &num_pixels) || + (num_pixels >= 4096 * 4096))) { + LOCAL_SET_GL_ERROR(GL_OUT_OF_MEMORY, func_name, ""synthetic out of memory""); + return error::kNoError; + } + + TextureManager::DoTexImageArguments args = { + target, level, internal_format, width, height, 1, border, format, type, + pixels, pixels_size, padding, + TextureManager::DoTexImageArguments::kTexImage2D }; + texture_manager()->ValidateAndDoTexImage( + &texture_state_, &state_, &framebuffer_state_, func_name, args); + + ExitCommandProcessingEarly(); + return error::kNoError; +} +","@@ -11384,29 +11384,24 @@ void GLES2DecoderImpl::GetTexParameterImpl( + return; + } + break; +- // Get the level information from the texture to avoid a Mac driver +- // bug where they store the levels in int16_t, making values bigger +- // than 2^15-1 overflow in the negative range. + case GL_TEXTURE_BASE_LEVEL: +- if (workarounds().use_shadowed_tex_level_params) { +- if (fparams) { +- fparams[0] = static_cast(texture->base_level()); +- } else { +- iparams[0] = texture->base_level(); +- } +- return; ++ // Use shadowed value in case it's clamped; also because older MacOSX ++ // stores the value on int16_t (see https://crbug.com/610153). ++ if (fparams) { ++ fparams[0] = static_cast(texture->unclamped_base_level()); ++ } else { ++ iparams[0] = texture->unclamped_base_level(); + } +- break; ++ return; + case GL_TEXTURE_MAX_LEVEL: +- if (workarounds().use_shadowed_tex_level_params) { +- if (fparams) { +- fparams[0] = static_cast(texture->max_level()); +- } else { +- iparams[0] = texture->max_level(); +- } +- return; ++ // Use shadowed value in case it's clamped; also because older MacOSX ++ // stores the value on int16_t (see https://crbug.com/610153). ++ if (fparams) { ++ fparams[0] = static_cast(texture->unclamped_max_level()); ++ } else { ++ iparams[0] = texture->unclamped_max_level(); + } +- break; ++ return; + case GL_TEXTURE_SWIZZLE_R: + if (fparams) { + fparams[0] = static_cast(texture->swizzle_r()); +@@ -17573,25 +17568,6 @@ void GLES2DecoderImpl::TexStorageImpl(GLenum target, + compatibility_internal_format = format_info->decompressed_internal_format; + } + +- if (workarounds().reset_base_mipmap_level_before_texstorage && +- texture->base_level() > 0) +- api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, 0); +- +- // TODO(zmo): We might need to emulate TexStorage using TexImage or +- // CompressedTexImage on Mac OSX where we expose ES3 APIs when the underlying +- // driver is lower than 4.2 and ARB_texture_storage extension doesn't exist. +- if (dimension == ContextState::k2D) { +- api()->glTexStorage2DEXTFn(target, levels, compatibility_internal_format, +- width, height); +- } else { +- api()->glTexStorage3DFn(target, levels, compatibility_internal_format, +- width, height, depth); +- } +- if (workarounds().reset_base_mipmap_level_before_texstorage && +- texture->base_level() > 0) +- api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, +- texture->base_level()); +- + { + GLsizei level_width = width; + GLsizei level_height = height; +@@ -17620,6 +17596,29 @@ void GLES2DecoderImpl::TexStorageImpl(GLenum target, + texture->ApplyFormatWorkarounds(feature_info_.get()); + texture->SetImmutable(true); + } ++ ++ if (workarounds().reset_base_mipmap_level_before_texstorage && ++ texture->base_level() > 0) ++ api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, 0); ++ ++ // TODO(zmo): We might need to emulate TexStorage using TexImage or ++ // CompressedTexImage on Mac OSX where we expose ES3 APIs when the underlying ++ // driver is lower than 4.2 and ARB_texture_storage extension doesn't exist. ++ if (dimension == ContextState::k2D) { ++ api()->glTexStorage2DEXTFn(target, levels, compatibility_internal_format, ++ width, height); ++ } else { ++ api()->glTexStorage3DFn(target, levels, compatibility_internal_format, ++ width, height, depth); ++ } ++ if (workarounds().reset_base_mipmap_level_before_texstorage && ++ texture->base_level() > 0) { ++ // Note base_level is already clamped due to texture->SetImmutable(true). ++ // This is necessary for certain NVidia Linux drivers; otherwise they ++ // may trigger segmentation fault. See https://crbug.com/877874. ++ api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, ++ texture->base_level()); ++ } + } + + void GLES2DecoderImpl::DoTexStorage2DEXT(GLenum target,",794,1125,2048 +8147,"static int handle_bb_cf_recursive_descent (RAnal *anal, RAnalState *state) { + + RAnalBlock *bb = state->current_bb; + + ut64 addr = 0; + int result = 0; + if (!bb) { + eprintf (""Error: unable to handle basic block @ 0x%08""PFMT64x""\n"", addr); + return R_ANAL_RET_ERROR; + } else if (state->max_depth <= state->current_depth) { + return R_ANAL_RET_ERROR; + } + + state->current_depth++; + addr = bb->addr; + IFDBG eprintf (""Handling a control flow change @ 0x%04""PFMT64x"".\n"", addr); + ut64 control_type = r_anal_ex_map_anal_ex_to_anal_op_type (bb->type2); + + switch (control_type) { + case R_ANAL_OP_TYPE_CALL: + IFDBG eprintf ("" - Handling a call @ 0x%04""PFMT64x"".\n"", addr); + r_anal_xrefs_set (anal, bb->addr, bb->jump, R_ANAL_REF_TYPE_CALL); + result = R_ANAL_RET_ERROR; + break; + case R_ANAL_OP_TYPE_JMP: + { + RList * jmp_list; + IFDBG eprintf ("" - Handling a jmp @ 0x%04""PFMT64x"" to 0x%04""PFMT64x"".\n"", addr, bb->jump); + + if (!r_anal_state_search_bb (state, bb->jump)) { + jmp_list = r_anal_ex_perform_analysis ( anal, state, bb->jump ); + if (jmp_list) + bb->jumpbb = (RAnalBlock *) r_list_get_n (jmp_list, 0); + if (bb->jumpbb) + bb->jump = bb->jumpbb->addr; + } else { + bb->jumpbb = r_anal_state_search_bb (state, bb->jump); + if (bb->jumpbb) + bb->jump = bb->jumpbb->addr; + } + + if (state->done == 1) { + IFDBG eprintf ("" Looks like this jmp (bb @ 0x%04""PFMT64x"") found a return.\n"", addr); + } + result = R_ANAL_RET_END; + } + break; + case R_ANAL_OP_TYPE_CJMP: + { + RList *jmp_list; + ut8 encountered_stop = 0; + IFDBG eprintf ("" - Handling a cjmp @ 0x%04""PFMT64x"" jmp to 0x%04""PFMT64x"" and fail to 0x%04""PFMT64x"".\n"", addr, bb->jump, bb->fail); + IFDBG eprintf ("" - Handling jmp to 0x%04""PFMT64x"".\n"", bb->jump); + if (!r_anal_state_search_bb (state, bb->jump)) { + jmp_list = r_anal_ex_perform_analysis ( anal, state, bb->jump ); + if (jmp_list) + bb->jumpbb = (RAnalBlock *) r_list_get_n (jmp_list, 0); + if (bb->jumpbb) { + bb->jump = bb->jumpbb->addr; + } + } else { + bb->jumpbb = r_anal_state_search_bb (state, bb->jump); + bb->jump = bb->jumpbb->addr; + } + + if (state->done == 1) { + IFDBG eprintf ("" Looks like this jmp (bb @ 0x%04""PFMT64x"") found a return.\n"", addr); + state->done = 0; + encountered_stop = 1; + } + + if (!r_anal_state_search_bb (state, bb->fail)) { + jmp_list = r_anal_ex_perform_analysis ( anal, state, bb->fail ); + if (jmp_list) + bb->failbb = (RAnalBlock *) r_list_get_n (jmp_list, 0); + if (bb->failbb) { + bb->fail = bb->failbb->addr; + } + } else { + bb->failbb = r_anal_state_search_bb (state, bb->fail); + if (bb->failbb) { + bb->fail = bb->failbb->addr; + } + } + + IFDBG eprintf ("" - Handling an cjmp @ 0x%04""PFMT64x"" jmp to 0x%04""PFMT64x"" and fail to 0x%04""PFMT64x"".\n"", addr, bb->jump, bb->fail); + IFDBG eprintf ("" - Handling fail to 0x%04""PFMT64x"".\n"", bb->fail); + if (state->done == 1) { + IFDBG eprintf ("" Looks like this fail (bb @ 0x%04""PFMT64x"") found a return.\n"", addr); + } + + result = R_ANAL_RET_END; + if (encountered_stop) state->done = 1; + } + break; + + case R_ANAL_OP_TYPE_SWITCH: + { + IFDBG eprintf ("" - Handling an switch @ 0x%04""PFMT64x"".\n"", addr); + if (bb->switch_op) { + RAnalCaseOp *caseop; + RListIter *iter; + RList *jmp_list = NULL; + ut8 encountered_stop = 0; + r_list_foreach (bb->switch_op->cases, iter, caseop) { + if (caseop) { + if (r_anal_state_addr_is_valid (state, caseop->jump) ) { + jmp_list = r_anal_ex_perform_analysis ( anal, state, caseop->jump ); + if (jmp_list) + caseop->jumpbb = (RAnalBlock *) r_list_get_n (jmp_list, 0); + if (state->done == 1) { + IFDBG eprintf ("" Looks like this jmp (bb @ 0x%04""PFMT64x"") found a return.\n"", addr); + state->done = 0; + encountered_stop = 1; + } + } + } + } + r_list_free (jmp_list); + if (encountered_stop) state->done = 1; + } + + result = R_ANAL_RET_END; + } + break; + case R_ANAL_OP_TYPE_TRAP: + case R_ANAL_OP_TYPE_UJMP: + case R_ANAL_OP_TYPE_IJMP: + case R_ANAL_OP_TYPE_RJMP: + case R_ANAL_OP_TYPE_IRJMP: + case R_ANAL_OP_TYPE_RET: + case R_ANAL_OP_TYPE_ILL: + IFDBG eprintf ("" - Handling an ret @ 0x%04""PFMT64x"".\n"", addr); + state->done = 1; + result = R_ANAL_RET_END; + break; + default: break; + } + + state->current_depth--; + return result; +} +",0,"static int handle_bb_cf_recursive_descent (RAnal *anal, RAnalState *state) { + + RAnalBlock *bb = state->current_bb; + + ut64 addr = 0; + int result = 0; + if (!bb) { + eprintf (""Error: unable to handle basic block @ 0x%08""PFMT64x""\n"", addr); + return R_ANAL_RET_ERROR; + } else if (state->max_depth <= state->current_depth) { + return R_ANAL_RET_ERROR; + } + + state->current_depth++; + addr = bb->addr; + IFDBG eprintf (""Handling a control flow change @ 0x%04""PFMT64x"".\n"", addr); + ut64 control_type = r_anal_ex_map_anal_ex_to_anal_op_type (bb->type2); + + switch (control_type) { + case R_ANAL_OP_TYPE_CALL: + IFDBG eprintf ("" - Handling a call @ 0x%04""PFMT64x"".\n"", addr); + r_anal_xrefs_set (anal, bb->addr, bb->jump, R_ANAL_REF_TYPE_CALL); + result = R_ANAL_RET_ERROR; + break; + case R_ANAL_OP_TYPE_JMP: + { + RList * jmp_list; + IFDBG eprintf ("" - Handling a jmp @ 0x%04""PFMT64x"" to 0x%04""PFMT64x"".\n"", addr, bb->jump); + + if (!r_anal_state_search_bb (state, bb->jump)) { + jmp_list = r_anal_ex_perform_analysis ( anal, state, bb->jump ); + if (jmp_list) + bb->jumpbb = (RAnalBlock *) r_list_get_n (jmp_list, 0); + if (bb->jumpbb) + bb->jump = bb->jumpbb->addr; + } else { + bb->jumpbb = r_anal_state_search_bb (state, bb->jump); + if (bb->jumpbb) + bb->jump = bb->jumpbb->addr; + } + + if (state->done == 1) { + IFDBG eprintf ("" Looks like this jmp (bb @ 0x%04""PFMT64x"") found a return.\n"", addr); + } + result = R_ANAL_RET_END; + } + break; + case R_ANAL_OP_TYPE_CJMP: + { + RList *jmp_list; + ut8 encountered_stop = 0; + IFDBG eprintf ("" - Handling a cjmp @ 0x%04""PFMT64x"" jmp to 0x%04""PFMT64x"" and fail to 0x%04""PFMT64x"".\n"", addr, bb->jump, bb->fail); + IFDBG eprintf ("" - Handling jmp to 0x%04""PFMT64x"".\n"", bb->jump); + if (!r_anal_state_search_bb (state, bb->jump)) { + jmp_list = r_anal_ex_perform_analysis ( anal, state, bb->jump ); + if (jmp_list) + bb->jumpbb = (RAnalBlock *) r_list_get_n (jmp_list, 0); + if (bb->jumpbb) { + bb->jump = bb->jumpbb->addr; + } + } else { + bb->jumpbb = r_anal_state_search_bb (state, bb->jump); + bb->jump = bb->jumpbb->addr; + } + + if (state->done == 1) { + IFDBG eprintf ("" Looks like this jmp (bb @ 0x%04""PFMT64x"") found a return.\n"", addr); + state->done = 0; + encountered_stop = 1; + } + + if (!r_anal_state_search_bb (state, bb->fail)) { + jmp_list = r_anal_ex_perform_analysis ( anal, state, bb->fail ); + if (jmp_list) + bb->failbb = (RAnalBlock *) r_list_get_n (jmp_list, 0); + if (bb->failbb) { + bb->fail = bb->failbb->addr; + } + } else { + bb->failbb = r_anal_state_search_bb (state, bb->fail); + if (bb->failbb) { + bb->fail = bb->failbb->addr; + } + } + + IFDBG eprintf ("" - Handling an cjmp @ 0x%04""PFMT64x"" jmp to 0x%04""PFMT64x"" and fail to 0x%04""PFMT64x"".\n"", addr, bb->jump, bb->fail); + IFDBG eprintf ("" - Handling fail to 0x%04""PFMT64x"".\n"", bb->fail); + if (state->done == 1) { + IFDBG eprintf ("" Looks like this fail (bb @ 0x%04""PFMT64x"") found a return.\n"", addr); + } + + result = R_ANAL_RET_END; + if (encountered_stop) state->done = 1; + } + break; + + case R_ANAL_OP_TYPE_SWITCH: + { + IFDBG eprintf ("" - Handling an switch @ 0x%04""PFMT64x"".\n"", addr); + if (bb->switch_op) { + RAnalCaseOp *caseop; + RListIter *iter; + RList *jmp_list = NULL; + ut8 encountered_stop = 0; + r_list_foreach (bb->switch_op->cases, iter, caseop) { + if (caseop) { + if (r_anal_state_addr_is_valid (state, caseop->jump) ) { + jmp_list = r_anal_ex_perform_analysis ( anal, state, caseop->jump ); + if (jmp_list) + caseop->jumpbb = (RAnalBlock *) r_list_get_n (jmp_list, 0); + if (state->done == 1) { + IFDBG eprintf ("" Looks like this jmp (bb @ 0x%04""PFMT64x"") found a return.\n"", addr); + state->done = 0; + encountered_stop = 1; + } + } + } + } + r_list_free (jmp_list); + if (encountered_stop) state->done = 1; + } + + result = R_ANAL_RET_END; + } + break; + case R_ANAL_OP_TYPE_TRAP: + case R_ANAL_OP_TYPE_UJMP: + case R_ANAL_OP_TYPE_IJMP: + case R_ANAL_OP_TYPE_RJMP: + case R_ANAL_OP_TYPE_IRJMP: + case R_ANAL_OP_TYPE_RET: + case R_ANAL_OP_TYPE_ILL: + IFDBG eprintf ("" - Handling an ret @ 0x%04""PFMT64x"".\n"", addr); + state->done = 1; + result = R_ANAL_RET_END; + break; + default: break; + } + + state->current_depth--; + return result; +} +","@@ -679,11 +679,11 @@ static int java_switch_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, + + if (op_byte == 0xaa) { + // handle a table switch condition +- if (pos + 8 > len) { ++ if (pos + 8 + 8 > len) { + return op->size; + } +- int min_val = (ut32)(UINT (data, pos + 4)), +- max_val = (ut32)(UINT (data, pos + 8)); ++ const int min_val = (ut32)(UINT (data, pos + 4)); ++ const int max_val = (ut32)(UINT (data, pos + 8)); + + ut32 default_loc = (ut32) (UINT (data, pos)), cur_case = 0; + op->switch_op = r_anal_switch_op_new (addr, min_val, default_loc);",1611,1942,2048 +5516,"static int handle_revision_pseudo_opt(const char *submodule, + struct rev_info *revs, + int argc, const char **argv, int *flags) +{ + const char *arg = argv[0]; + const char *optarg; + int argcount; + + /* + * NOTE! + * + * Commands like ""git shortlog"" will not accept the options below + * unless parse_revision_opt queues them (as opposed to erroring + * out). + * + * When implementing your new pseudo-option, remember to + * register it in the list at the top of handle_revision_opt. + */ + if (!strcmp(arg, ""--all"")) { + handle_refs(submodule, revs, *flags, for_each_ref_submodule); + handle_refs(submodule, revs, *flags, head_ref_submodule); + clear_ref_exclusion(&revs->ref_excludes); + } else if (!strcmp(arg, ""--branches"")) { + handle_refs(submodule, revs, *flags, for_each_branch_ref_submodule); + clear_ref_exclusion(&revs->ref_excludes); + } else if (!strcmp(arg, ""--bisect"")) { + read_bisect_terms(&term_bad, &term_good); + handle_refs(submodule, revs, *flags, for_each_bad_bisect_ref); + handle_refs(submodule, revs, *flags ^ (UNINTERESTING | BOTTOM), for_each_good_bisect_ref); + revs->bisect = 1; + } else if (!strcmp(arg, ""--tags"")) { + handle_refs(submodule, revs, *flags, for_each_tag_ref_submodule); + clear_ref_exclusion(&revs->ref_excludes); + } else if (!strcmp(arg, ""--remotes"")) { + handle_refs(submodule, revs, *flags, for_each_remote_ref_submodule); + clear_ref_exclusion(&revs->ref_excludes); + } else if ((argcount = parse_long_opt(""glob"", argv, &optarg))) { + struct all_refs_cb cb; + init_all_refs_cb(&cb, revs, *flags); + for_each_glob_ref(handle_one_ref, optarg, &cb); + clear_ref_exclusion(&revs->ref_excludes); + return argcount; + } else if ((argcount = parse_long_opt(""exclude"", argv, &optarg))) { + add_ref_exclusion(&revs->ref_excludes, optarg); + return argcount; + } else if (starts_with(arg, ""--branches="")) { + struct all_refs_cb cb; + init_all_refs_cb(&cb, revs, *flags); + for_each_glob_ref_in(handle_one_ref, arg + 11, ""refs/heads/"", &cb); + clear_ref_exclusion(&revs->ref_excludes); + } else if (starts_with(arg, ""--tags="")) { + struct all_refs_cb cb; + init_all_refs_cb(&cb, revs, *flags); + for_each_glob_ref_in(handle_one_ref, arg + 7, ""refs/tags/"", &cb); + clear_ref_exclusion(&revs->ref_excludes); + } else if (starts_with(arg, ""--remotes="")) { + struct all_refs_cb cb; + init_all_refs_cb(&cb, revs, *flags); + for_each_glob_ref_in(handle_one_ref, arg + 10, ""refs/remotes/"", &cb); + clear_ref_exclusion(&revs->ref_excludes); + } else if (!strcmp(arg, ""--reflog"")) { + add_reflogs_to_pending(revs, *flags); + } else if (!strcmp(arg, ""--indexed-objects"")) { + add_index_objects_to_pending(revs, *flags); + } else if (!strcmp(arg, ""--not"")) { + *flags ^= UNINTERESTING | BOTTOM; + } else if (!strcmp(arg, ""--no-walk"")) { + revs->no_walk = REVISION_WALK_NO_WALK_SORTED; + } else if (starts_with(arg, ""--no-walk="")) { + /* + * Detached form (""--no-walk X"" as opposed to ""--no-walk=X"") + * not allowed, since the argument is optional. + */ + if (!strcmp(arg + 10, ""sorted"")) + revs->no_walk = REVISION_WALK_NO_WALK_SORTED; + else if (!strcmp(arg + 10, ""unsorted"")) + revs->no_walk = REVISION_WALK_NO_WALK_UNSORTED; + else + return error(""invalid argument to --no-walk""); + } else if (!strcmp(arg, ""--do-walk"")) { + revs->no_walk = 0; + } else { + return 0; + } + + return 1; +} +",0,"static int handle_revision_pseudo_opt(const char *submodule, + struct rev_info *revs, + int argc, const char **argv, int *flags) +{ + const char *arg = argv[0]; + const char *optarg; + int argcount; + + /* + * NOTE! + * + * Commands like ""git shortlog"" will not accept the options below + * unless parse_revision_opt queues them (as opposed to erroring + * out). + * + * When implementing your new pseudo-option, remember to + * register it in the list at the top of handle_revision_opt. + */ + if (!strcmp(arg, ""--all"")) { + handle_refs(submodule, revs, *flags, for_each_ref_submodule); + handle_refs(submodule, revs, *flags, head_ref_submodule); + clear_ref_exclusion(&revs->ref_excludes); + } else if (!strcmp(arg, ""--branches"")) { + handle_refs(submodule, revs, *flags, for_each_branch_ref_submodule); + clear_ref_exclusion(&revs->ref_excludes); + } else if (!strcmp(arg, ""--bisect"")) { + read_bisect_terms(&term_bad, &term_good); + handle_refs(submodule, revs, *flags, for_each_bad_bisect_ref); + handle_refs(submodule, revs, *flags ^ (UNINTERESTING | BOTTOM), for_each_good_bisect_ref); + revs->bisect = 1; + } else if (!strcmp(arg, ""--tags"")) { + handle_refs(submodule, revs, *flags, for_each_tag_ref_submodule); + clear_ref_exclusion(&revs->ref_excludes); + } else if (!strcmp(arg, ""--remotes"")) { + handle_refs(submodule, revs, *flags, for_each_remote_ref_submodule); + clear_ref_exclusion(&revs->ref_excludes); + } else if ((argcount = parse_long_opt(""glob"", argv, &optarg))) { + struct all_refs_cb cb; + init_all_refs_cb(&cb, revs, *flags); + for_each_glob_ref(handle_one_ref, optarg, &cb); + clear_ref_exclusion(&revs->ref_excludes); + return argcount; + } else if ((argcount = parse_long_opt(""exclude"", argv, &optarg))) { + add_ref_exclusion(&revs->ref_excludes, optarg); + return argcount; + } else if (starts_with(arg, ""--branches="")) { + struct all_refs_cb cb; + init_all_refs_cb(&cb, revs, *flags); + for_each_glob_ref_in(handle_one_ref, arg + 11, ""refs/heads/"", &cb); + clear_ref_exclusion(&revs->ref_excludes); + } else if (starts_with(arg, ""--tags="")) { + struct all_refs_cb cb; + init_all_refs_cb(&cb, revs, *flags); + for_each_glob_ref_in(handle_one_ref, arg + 7, ""refs/tags/"", &cb); + clear_ref_exclusion(&revs->ref_excludes); + } else if (starts_with(arg, ""--remotes="")) { + struct all_refs_cb cb; + init_all_refs_cb(&cb, revs, *flags); + for_each_glob_ref_in(handle_one_ref, arg + 10, ""refs/remotes/"", &cb); + clear_ref_exclusion(&revs->ref_excludes); + } else if (!strcmp(arg, ""--reflog"")) { + add_reflogs_to_pending(revs, *flags); + } else if (!strcmp(arg, ""--indexed-objects"")) { + add_index_objects_to_pending(revs, *flags); + } else if (!strcmp(arg, ""--not"")) { + *flags ^= UNINTERESTING | BOTTOM; + } else if (!strcmp(arg, ""--no-walk"")) { + revs->no_walk = REVISION_WALK_NO_WALK_SORTED; + } else if (starts_with(arg, ""--no-walk="")) { + /* + * Detached form (""--no-walk X"" as opposed to ""--no-walk=X"") + * not allowed, since the argument is optional. + */ + if (!strcmp(arg + 10, ""sorted"")) + revs->no_walk = REVISION_WALK_NO_WALK_SORTED; + else if (!strcmp(arg + 10, ""unsorted"")) + revs->no_walk = REVISION_WALK_NO_WALK_UNSORTED; + else + return error(""invalid argument to --no-walk""); + } else if (!strcmp(arg, ""--do-walk"")) { + revs->no_walk = 0; + } else { + return 0; + } + + return 1; +} +","@@ -25,27 +25,14 @@ volatile show_early_output_fn_t show_early_output; + static const char *term_bad; + static const char *term_good; + +-char *path_name(struct strbuf *path, const char *name) ++void show_object_with_name(FILE *out, struct object *obj, const char *name) + { +- struct strbuf ret = STRBUF_INIT; +- if (path) +- strbuf_addbuf(&ret, path); +- strbuf_addstr(&ret, name); +- return strbuf_detach(&ret, NULL); +-} +- +-void show_object_with_name(FILE *out, struct object *obj, +- struct strbuf *path, const char *component) +-{ +- char *name = path_name(path, component); +- char *p; ++ const char *p; + + fprintf(out, ""%s "", oid_to_hex(&obj->oid)); + for (p = name; *p && *p != '\n'; p++) + fputc(*p, out); + fputc('\n', out); +- +- free(name); + } + + static void mark_blob_uninteresting(struct blob *blob)",1016,1347,2048 +4904,"static apr_status_t h2_session_start(h2_session *session, int *rv) +{ + apr_status_t status = APR_SUCCESS; + nghttp2_settings_entry settings[3]; + size_t slen; + int win_size; + + ap_assert(session); + /* Start the conversation by submitting our SETTINGS frame */ + *rv = 0; + if (session->r) { + const char *s, *cs; + apr_size_t dlen; + h2_stream * stream; + + /* 'h2c' mode: we should have a 'HTTP2-Settings' header with + * base64 encoded client settings. */ + s = apr_table_get(session->r->headers_in, ""HTTP2-Settings""); + if (!s) { + ap_log_rerror(APLOG_MARK, APLOG_ERR, APR_EINVAL, session->r, + APLOGNO(02931) + ""HTTP2-Settings header missing in request""); + return APR_EINVAL; + } + cs = NULL; + dlen = h2_util_base64url_decode(&cs, s, session->pool); + + if (APLOGrdebug(session->r)) { + char buffer[128]; + h2_util_hex_dump(buffer, 128, (char*)cs, dlen); + ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, session->r, APLOGNO(03070) + ""upgrading h2c session with HTTP2-Settings: %s -> %s (%d)"", + s, buffer, (int)dlen); + } + + *rv = nghttp2_session_upgrade(session->ngh2, (uint8_t*)cs, dlen, NULL); + if (*rv != 0) { + status = APR_EINVAL; + ap_log_rerror(APLOG_MARK, APLOG_ERR, status, session->r, + APLOGNO(02932) ""nghttp2_session_upgrade: %s"", + nghttp2_strerror(*rv)); + return status; + } + + /* Now we need to auto-open stream 1 for the request we got. */ + stream = h2_session_open_stream(session, 1, 0, NULL); + if (!stream) { + status = APR_EGENERAL; + ap_log_rerror(APLOG_MARK, APLOG_ERR, status, session->r, + APLOGNO(02933) ""open stream 1: %s"", + nghttp2_strerror(*rv)); + return status; + } + + status = h2_stream_set_request_rec(stream, session->r); + if (status != APR_SUCCESS) { + return status; + } + status = stream_schedule(session, stream, 1); + if (status != APR_SUCCESS) { + return status; + } + } + + slen = 0; + settings[slen].settings_id = NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS; + settings[slen].value = (uint32_t)session->max_stream_count; + ++slen; + win_size = h2_config_geti(session->config, H2_CONF_WIN_SIZE); + if (win_size != H2_INITIAL_WINDOW_SIZE) { + settings[slen].settings_id = NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE; + settings[slen].value = win_size; + ++slen; + } + + ap_log_cerror(APLOG_MARK, APLOG_DEBUG, status, session->c, APLOGNO(03201) + ""h2_session(%ld): start, INITIAL_WINDOW_SIZE=%ld, "" + ""MAX_CONCURRENT_STREAMS=%d"", + session->id, (long)win_size, (int)session->max_stream_count); + *rv = nghttp2_submit_settings(session->ngh2, NGHTTP2_FLAG_NONE, + settings, slen); + if (*rv != 0) { + status = APR_EGENERAL; + ap_log_cerror(APLOG_MARK, APLOG_ERR, status, session->c, + APLOGNO(02935) ""nghttp2_submit_settings: %s"", + nghttp2_strerror(*rv)); + } + else { + /* use maximum possible value for connection window size. We are only + * interested in per stream flow control. which have the initial window + * size configured above. + * Therefore, for our use, the connection window can only get in the + * way. Example: if we allow 100 streams with a 32KB window each, we + * buffer up to 3.2 MB of data. Unless we do separate connection window + * interim updates, any smaller connection window will lead to blocking + * in DATA flow. + */ + *rv = nghttp2_submit_window_update(session->ngh2, NGHTTP2_FLAG_NONE, + 0, NGHTTP2_MAX_WINDOW_SIZE - win_size); + if (*rv != 0) { + status = APR_EGENERAL; + ap_log_cerror(APLOG_MARK, APLOG_ERR, status, session->c, + APLOGNO(02970) ""nghttp2_submit_window_update: %s"", + nghttp2_strerror(*rv)); + } + } + + return status; +} +",0,"static apr_status_t h2_session_start(h2_session *session, int *rv) +{ + apr_status_t status = APR_SUCCESS; + nghttp2_settings_entry settings[3]; + size_t slen; + int win_size; + + ap_assert(session); + /* Start the conversation by submitting our SETTINGS frame */ + *rv = 0; + if (session->r) { + const char *s, *cs; + apr_size_t dlen; + h2_stream * stream; + + /* 'h2c' mode: we should have a 'HTTP2-Settings' header with + * base64 encoded client settings. */ + s = apr_table_get(session->r->headers_in, ""HTTP2-Settings""); + if (!s) { + ap_log_rerror(APLOG_MARK, APLOG_ERR, APR_EINVAL, session->r, + APLOGNO(02931) + ""HTTP2-Settings header missing in request""); + return APR_EINVAL; + } + cs = NULL; + dlen = h2_util_base64url_decode(&cs, s, session->pool); + + if (APLOGrdebug(session->r)) { + char buffer[128]; + h2_util_hex_dump(buffer, 128, (char*)cs, dlen); + ap_log_rerror(APLOG_MARK, APLOG_DEBUG, 0, session->r, APLOGNO(03070) + ""upgrading h2c session with HTTP2-Settings: %s -> %s (%d)"", + s, buffer, (int)dlen); + } + + *rv = nghttp2_session_upgrade(session->ngh2, (uint8_t*)cs, dlen, NULL); + if (*rv != 0) { + status = APR_EINVAL; + ap_log_rerror(APLOG_MARK, APLOG_ERR, status, session->r, + APLOGNO(02932) ""nghttp2_session_upgrade: %s"", + nghttp2_strerror(*rv)); + return status; + } + + /* Now we need to auto-open stream 1 for the request we got. */ + stream = h2_session_open_stream(session, 1, 0, NULL); + if (!stream) { + status = APR_EGENERAL; + ap_log_rerror(APLOG_MARK, APLOG_ERR, status, session->r, + APLOGNO(02933) ""open stream 1: %s"", + nghttp2_strerror(*rv)); + return status; + } + + status = h2_stream_set_request_rec(stream, session->r); + if (status != APR_SUCCESS) { + return status; + } + status = stream_schedule(session, stream, 1); + if (status != APR_SUCCESS) { + return status; + } + } + + slen = 0; + settings[slen].settings_id = NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS; + settings[slen].value = (uint32_t)session->max_stream_count; + ++slen; + win_size = h2_config_geti(session->config, H2_CONF_WIN_SIZE); + if (win_size != H2_INITIAL_WINDOW_SIZE) { + settings[slen].settings_id = NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE; + settings[slen].value = win_size; + ++slen; + } + + ap_log_cerror(APLOG_MARK, APLOG_DEBUG, status, session->c, APLOGNO(03201) + ""h2_session(%ld): start, INITIAL_WINDOW_SIZE=%ld, "" + ""MAX_CONCURRENT_STREAMS=%d"", + session->id, (long)win_size, (int)session->max_stream_count); + *rv = nghttp2_submit_settings(session->ngh2, NGHTTP2_FLAG_NONE, + settings, slen); + if (*rv != 0) { + status = APR_EGENERAL; + ap_log_cerror(APLOG_MARK, APLOG_ERR, status, session->c, + APLOGNO(02935) ""nghttp2_submit_settings: %s"", + nghttp2_strerror(*rv)); + } + else { + /* use maximum possible value for connection window size. We are only + * interested in per stream flow control. which have the initial window + * size configured above. + * Therefore, for our use, the connection window can only get in the + * way. Example: if we allow 100 streams with a 32KB window each, we + * buffer up to 3.2 MB of data. Unless we do separate connection window + * interim updates, any smaller connection window will lead to blocking + * in DATA flow. + */ + *rv = nghttp2_submit_window_update(session->ngh2, NGHTTP2_FLAG_NONE, + 0, NGHTTP2_MAX_WINDOW_SIZE - win_size); + if (*rv != 0) { + status = APR_EGENERAL; + ap_log_cerror(APLOG_MARK, APLOG_ERR, status, session->c, + APLOGNO(02970) ""nghttp2_submit_window_update: %s"", + nghttp2_strerror(*rv)); + } + } + + return status; +} +","@@ -394,7 +394,7 @@ static int on_header_cb(nghttp2_session *ngh2, const nghttp2_frame *frame, + (void)flags; + stream = get_stream(session, frame->hd.stream_id); + if (!stream) { +- ap_log_cerror(APLOG_MARK, APLOG_ERR, 0, session->c, ++ ap_log_cerror(APLOG_MARK, APLOG_DEBUG, 0, session->c, + APLOGNO(02920) + ""h2_session: stream(%ld-%d): on_header unknown stream"", + session->id, (int)frame->hd.stream_id); +@@ -403,7 +403,14 @@ static int on_header_cb(nghttp2_session *ngh2, const nghttp2_frame *frame, + + status = h2_stream_add_header(stream, (const char *)name, namelen, + (const char *)value, valuelen); +- if (status != APR_SUCCESS && !h2_stream_is_ready(stream)) { ++ if (status == APR_ECONNRESET) { ++ ap_log_cerror(APLOG_MARK, APLOG_TRACE1, status, session->c, ++ ""h2-stream(%ld-%d): on_header, reset stream"", ++ session->id, stream->id); ++ nghttp2_submit_rst_stream(ngh2, NGHTTP2_FLAG_NONE, stream->id, ++ NGHTTP2_INTERNAL_ERROR); ++ } ++ else if (status != APR_SUCCESS && !h2_stream_is_ready(stream)) { + return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE; + } + return 0;",1132,1463,2048 +7247,"int jas_image_sampcmpt(jas_image_t *image, int cmptno, int newcmptno, + jas_image_coord_t ho, jas_image_coord_t vo, jas_image_coord_t hs, + jas_image_coord_t vs, int sgnd, int prec) +{ + jas_image_cmpt_t *oldcmpt; + jas_image_cmpt_t *newcmpt; + int width; + int height; + jas_image_coord_t tlx; + jas_image_coord_t tly; + jas_image_coord_t brx; + jas_image_coord_t bry; + int i; + int j; + jas_image_cmptparm_t cmptparm; + jas_image_coord_t ax; + jas_image_coord_t ay; + jas_image_coord_t bx; + jas_image_coord_t by; + jas_image_coord_t d0; + jas_image_coord_t d1; + jas_image_coord_t d2; + jas_image_coord_t d3; + jas_image_coord_t oldx; + jas_image_coord_t oldy; + jas_image_coord_t x; + jas_image_coord_t y; + long v; + jas_image_coord_t cmptbrx; + jas_image_coord_t cmptbry; + + assert(cmptno >= 0 && cmptno < image->numcmpts_); + oldcmpt = image->cmpts_[cmptno]; + assert(oldcmpt->tlx_ == 0 && oldcmpt->tly_ == 0); + jas_image_calcbbox2(image, &tlx, &tly, &brx, &bry); + width = FLOORDIV(brx - ho + hs, hs); + height = FLOORDIV(bry - vo + vs, vs); + cmptparm.tlx = ho; + cmptparm.tly = vo; + cmptparm.hstep = hs; + cmptparm.vstep = vs; + cmptparm.width = width; + cmptparm.height = height; + cmptparm.prec = prec; + cmptparm.sgnd = sgnd; + if (jas_image_addcmpt(image, newcmptno, &cmptparm)) + goto error; +cmptbrx = oldcmpt->tlx_ + (oldcmpt->width_ - 1) * oldcmpt->hstep_; +cmptbry = oldcmpt->tly_ + (oldcmpt->height_ - 1) * oldcmpt->vstep_; + newcmpt = image->cmpts_[newcmptno]; + jas_stream_rewind(newcmpt->stream_); + for (i = 0; i < height; ++i) { + y = newcmpt->tly_ + newcmpt->vstep_ * i; + for (j = 0; j < width; ++j) { + x = newcmpt->tlx_ + newcmpt->hstep_ * j; + ax = downtomult(x - oldcmpt->tlx_, oldcmpt->hstep_) + oldcmpt->tlx_; + ay = downtomult(y - oldcmpt->tly_, oldcmpt->vstep_) + oldcmpt->tly_; + bx = uptomult(x - oldcmpt->tlx_, oldcmpt->hstep_) + oldcmpt->tlx_; + if (bx > cmptbrx) + bx = cmptbrx; + by = uptomult(y - oldcmpt->tly_, oldcmpt->vstep_) + oldcmpt->tly_; + if (by > cmptbry) + by = cmptbry; + d0 = (ax - x) * (ax - x) + (ay - y) * (ay - y); + d1 = (bx - x) * (bx - x) + (ay - y) * (ay - y); + d2 = (bx - x) * (bx - x) + (by - y) * (by - y); + d3 = (ax - x) * (ax - x) + (by - y) * (by - y); + if (d0 <= d1 && d0 <= d2 && d0 <= d3) { + oldx = (ax - oldcmpt->tlx_) / oldcmpt->hstep_; + oldy = (ay - oldcmpt->tly_) / oldcmpt->vstep_; + } else if (d1 <= d0 && d1 <= d2 && d1 <= d3) { + oldx = (bx - oldcmpt->tlx_) / oldcmpt->hstep_; + oldy = (ay - oldcmpt->tly_) / oldcmpt->vstep_; + } else if (d2 <= d0 && d2 <= d1 && d1 <= d3) { + oldx = (bx - oldcmpt->tlx_) / oldcmpt->hstep_; + oldy = (by - oldcmpt->tly_) / oldcmpt->vstep_; + } else { + oldx = (ax - oldcmpt->tlx_) / oldcmpt->hstep_; + oldy = (by - oldcmpt->tly_) / oldcmpt->vstep_; + } + assert(oldx >= 0 && oldx < oldcmpt->width_ && + oldy >= 0 && oldy < oldcmpt->height_); + if (jas_stream_seek(oldcmpt->stream_, oldcmpt->cps_ * + (oldy * oldcmpt->width_ + oldx), SEEK_SET) < 0) + goto error; + if (getint(oldcmpt->stream_, oldcmpt->sgnd_, + oldcmpt->prec_, &v)) + goto error; + if (newcmpt->prec_ != oldcmpt->prec_ || + newcmpt->sgnd_ != oldcmpt->sgnd_) { + v = convert(v, oldcmpt->sgnd_, oldcmpt->prec_, + newcmpt->sgnd_, newcmpt->prec_); + } + if (putint(newcmpt->stream_, newcmpt->sgnd_, + newcmpt->prec_, v)) + goto error; + } + } + return 0; +error: + return -1; +} +",0,"int jas_image_sampcmpt(jas_image_t *image, int cmptno, int newcmptno, + jas_image_coord_t ho, jas_image_coord_t vo, jas_image_coord_t hs, + jas_image_coord_t vs, int sgnd, int prec) +{ + jas_image_cmpt_t *oldcmpt; + jas_image_cmpt_t *newcmpt; + int width; + int height; + jas_image_coord_t tlx; + jas_image_coord_t tly; + jas_image_coord_t brx; + jas_image_coord_t bry; + int i; + int j; + jas_image_cmptparm_t cmptparm; + jas_image_coord_t ax; + jas_image_coord_t ay; + jas_image_coord_t bx; + jas_image_coord_t by; + jas_image_coord_t d0; + jas_image_coord_t d1; + jas_image_coord_t d2; + jas_image_coord_t d3; + jas_image_coord_t oldx; + jas_image_coord_t oldy; + jas_image_coord_t x; + jas_image_coord_t y; + long v; + jas_image_coord_t cmptbrx; + jas_image_coord_t cmptbry; + + assert(cmptno >= 0 && cmptno < image->numcmpts_); + oldcmpt = image->cmpts_[cmptno]; + assert(oldcmpt->tlx_ == 0 && oldcmpt->tly_ == 0); + jas_image_calcbbox2(image, &tlx, &tly, &brx, &bry); + width = FLOORDIV(brx - ho + hs, hs); + height = FLOORDIV(bry - vo + vs, vs); + cmptparm.tlx = ho; + cmptparm.tly = vo; + cmptparm.hstep = hs; + cmptparm.vstep = vs; + cmptparm.width = width; + cmptparm.height = height; + cmptparm.prec = prec; + cmptparm.sgnd = sgnd; + if (jas_image_addcmpt(image, newcmptno, &cmptparm)) + goto error; +cmptbrx = oldcmpt->tlx_ + (oldcmpt->width_ - 1) * oldcmpt->hstep_; +cmptbry = oldcmpt->tly_ + (oldcmpt->height_ - 1) * oldcmpt->vstep_; + newcmpt = image->cmpts_[newcmptno]; + jas_stream_rewind(newcmpt->stream_); + for (i = 0; i < height; ++i) { + y = newcmpt->tly_ + newcmpt->vstep_ * i; + for (j = 0; j < width; ++j) { + x = newcmpt->tlx_ + newcmpt->hstep_ * j; + ax = downtomult(x - oldcmpt->tlx_, oldcmpt->hstep_) + oldcmpt->tlx_; + ay = downtomult(y - oldcmpt->tly_, oldcmpt->vstep_) + oldcmpt->tly_; + bx = uptomult(x - oldcmpt->tlx_, oldcmpt->hstep_) + oldcmpt->tlx_; + if (bx > cmptbrx) + bx = cmptbrx; + by = uptomult(y - oldcmpt->tly_, oldcmpt->vstep_) + oldcmpt->tly_; + if (by > cmptbry) + by = cmptbry; + d0 = (ax - x) * (ax - x) + (ay - y) * (ay - y); + d1 = (bx - x) * (bx - x) + (ay - y) * (ay - y); + d2 = (bx - x) * (bx - x) + (by - y) * (by - y); + d3 = (ax - x) * (ax - x) + (by - y) * (by - y); + if (d0 <= d1 && d0 <= d2 && d0 <= d3) { + oldx = (ax - oldcmpt->tlx_) / oldcmpt->hstep_; + oldy = (ay - oldcmpt->tly_) / oldcmpt->vstep_; + } else if (d1 <= d0 && d1 <= d2 && d1 <= d3) { + oldx = (bx - oldcmpt->tlx_) / oldcmpt->hstep_; + oldy = (ay - oldcmpt->tly_) / oldcmpt->vstep_; + } else if (d2 <= d0 && d2 <= d1 && d1 <= d3) { + oldx = (bx - oldcmpt->tlx_) / oldcmpt->hstep_; + oldy = (by - oldcmpt->tly_) / oldcmpt->vstep_; + } else { + oldx = (ax - oldcmpt->tlx_) / oldcmpt->hstep_; + oldy = (by - oldcmpt->tly_) / oldcmpt->vstep_; + } + assert(oldx >= 0 && oldx < oldcmpt->width_ && + oldy >= 0 && oldy < oldcmpt->height_); + if (jas_stream_seek(oldcmpt->stream_, oldcmpt->cps_ * + (oldy * oldcmpt->width_ + oldx), SEEK_SET) < 0) + goto error; + if (getint(oldcmpt->stream_, oldcmpt->sgnd_, + oldcmpt->prec_, &v)) + goto error; + if (newcmpt->prec_ != oldcmpt->prec_ || + newcmpt->sgnd_ != oldcmpt->sgnd_) { + v = convert(v, oldcmpt->sgnd_, oldcmpt->prec_, + newcmpt->sgnd_, newcmpt->prec_); + } + if (putint(newcmpt->stream_, newcmpt->sgnd_, + newcmpt->prec_, v)) + goto error; + } + } + return 0; +error: + return -1; +} +","@@ -133,30 +133,35 @@ jas_image_t *jas_image_create(int numcmpts, jas_image_cmptparm_t *cmptparms, + int clrspc) + { + jas_image_t *image; +- uint_fast32_t rawsize; ++ size_t rawsize; + uint_fast32_t inmem; + int cmptno; + jas_image_cmptparm_t *cmptparm; + ++ image = 0; ++ ++ JAS_DBGLOG(100, (""jas_image_create(%d, %p, %d)\n"", numcmpts, cmptparms, ++ clrspc)); ++ + if (!(image = jas_image_create0())) { +- return 0; ++ goto error; + } + + image->clrspc_ = clrspc; + image->maxcmpts_ = numcmpts; +- image->inmem_ = true; ++// image->inmem_ = true; + + /* Allocate memory for the per-component information. */ + if (!(image->cmpts_ = jas_alloc2(image->maxcmpts_, + sizeof(jas_image_cmpt_t *)))) { +- jas_image_destroy(image); +- return 0; ++ goto error; + } + /* Initialize in case of failure. */ + for (cmptno = 0; cmptno < image->maxcmpts_; ++cmptno) { + image->cmpts_[cmptno] = 0; + } + ++#if 0 + /* Compute the approximate raw size of the image. */ + rawsize = 0; + for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno, +@@ -167,16 +172,22 @@ jas_image_t *jas_image_create(int numcmpts, jas_image_cmptparm_t *cmptparms, + /* Decide whether to buffer the image data in memory, based on the + raw size of the image. */ + inmem = (rawsize < JAS_IMAGE_INMEMTHRESH); ++#endif + + /* Create the individual image components. */ + for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno, + ++cmptparm) { ++ if (!jas_safe_size_mul3(cmptparm->width, cmptparm->height, ++ (cmptparm->prec + 7), &rawsize)) { ++ goto error; ++ } ++ rawsize /= 8; ++ inmem = (rawsize < JAS_IMAGE_INMEMTHRESH); + if (!(image->cmpts_[cmptno] = jas_image_cmpt_create(cmptparm->tlx, + cmptparm->tly, cmptparm->hstep, cmptparm->vstep, + cmptparm->width, cmptparm->height, cmptparm->prec, + cmptparm->sgnd, inmem))) { +- jas_image_destroy(image); +- return 0; ++ goto error; + } + ++image->numcmpts_; + } +@@ -186,6 +197,12 @@ jas_image_t *jas_image_create(int numcmpts, jas_image_cmptparm_t *cmptparms, + jas_image_setbbox(image); + + return image; ++ ++error: ++ if (image) { ++ jas_image_destroy(image); ++ } ++ return 0; + } + + jas_image_t *jas_image_create0() +@@ -204,7 +221,7 @@ jas_image_t *jas_image_create0() + image->numcmpts_ = 0; + image->maxcmpts_ = 0; + image->cmpts_ = 0; +- image->inmem_ = true; ++// image->inmem_ = true; + image->cmprof_ = 0; + + return image; +@@ -316,6 +333,19 @@ static jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx, + jas_image_cmpt_t *cmpt; + size_t size; + ++ JAS_DBGLOG(100, ( ++ ""jas_image_cmpt_create(%ld, %ld, %ld, %ld, %ld, %ld, %d, %d, %d)\n"", ++ JAS_CAST(long, tlx), ++ JAS_CAST(long, tly), ++ JAS_CAST(long, hstep), ++ JAS_CAST(long, vstep), ++ JAS_CAST(long, width), ++ JAS_CAST(long, height), ++ JAS_CAST(int, depth), ++ sgnd, ++ inmem ++ )); ++ + cmpt = 0; + if (width < 0 || height < 0 || hstep <= 0 || vstep <= 0) { + goto error; +@@ -324,6 +354,9 @@ static jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx, + !jas_safe_intfast32_add(tly, height, 0)) { + goto error; + } ++ if (!jas_safe_intfast32_mul3(width, height, depth, 0)) { ++ goto error; ++ } + + if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) { + goto error; +@@ -344,8 +377,7 @@ static jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx, + // Compute the number of samples in the image component, while protecting + // against overflow. + // size = cmpt->width_ * cmpt->height_ * cmpt->cps_; +- if (!jas_safe_size_mul(cmpt->width_, cmpt->height_, &size) || +- !jas_safe_size_mul(size, cmpt->cps_, &size)) { ++ if (!jas_safe_size_mul3(cmpt->width_, cmpt->height_, cmpt->cps_, &size)) { + goto error; + } + cmpt->stream_ = (inmem) ? jas_stream_memopen2(0, size) : +@@ -1279,7 +1311,7 @@ static void jas_image_calcbbox2(jas_image_t *image, jas_image_coord_t *tlx, + *bry = tmpbry; + } + +-static inline long decode_twos_comp(ulong c, int prec) ++static inline long decode_twos_comp(jas_ulong c, int prec) + { + long result; + assert(prec >= 2); +@@ -1289,9 +1321,9 @@ static inline long decode_twos_comp(ulong c, int prec) + return result; + } + +-static inline ulong encode_twos_comp(long n, int prec) ++static inline jas_ulong encode_twos_comp(long n, int prec) + { +- ulong result; ++ jas_ulong result; + assert(prec >= 2); + jas_eprintf(""warning: support for signed data is untested\n""); + // NOTE: Is this correct? +@@ -1332,7 +1364,7 @@ static int putint(jas_stream_t *out, int sgnd, int prec, long val) + int n; + int c; + bool s; +- ulong tmp; ++ jas_ulong tmp; + assert((!sgnd && prec >= 1) || (sgnd && prec >= 2)); + if (sgnd) { + val = encode_twos_comp(val, prec);",1365,1696,2048 +9239,"static struct sched_group *find_busiest_group(struct lb_env *env) +{ + struct sg_lb_stats *local, *busiest; + struct sd_lb_stats sds; + + init_sd_lb_stats(&sds); + + /* + * Compute the various statistics relavent for load balancing at + * this level. + */ + update_sd_lb_stats(env, &sds); + + if (static_branch_unlikely(&sched_energy_present)) { + struct root_domain *rd = env->dst_rq->rd; + + if (rcu_dereference(rd->pd) && !READ_ONCE(rd->overutilized)) + goto out_balanced; + } + + local = &sds.local_stat; + busiest = &sds.busiest_stat; + + /* ASYM feature bypasses nice load balance check */ + if (check_asym_packing(env, &sds)) + return sds.busiest; + + /* There is no busy sibling group to pull tasks from */ + if (!sds.busiest || busiest->sum_nr_running == 0) + goto out_balanced; + + /* XXX broken for overlapping NUMA groups */ + sds.avg_load = (SCHED_CAPACITY_SCALE * sds.total_load) + / sds.total_capacity; + + /* + * If the busiest group is imbalanced the below checks don't + * work because they assume all things are equal, which typically + * isn't true due to cpus_allowed constraints and the like. + */ + if (busiest->group_type == group_imbalanced) + goto force_balance; + + /* + * When dst_cpu is idle, prevent SMP nice and/or asymmetric group + * capacities from resulting in underutilization due to avg_load. + */ + if (env->idle != CPU_NOT_IDLE && group_has_capacity(env, local) && + busiest->group_no_capacity) + goto force_balance; + + /* Misfit tasks should be dealt with regardless of the avg load */ + if (busiest->group_type == group_misfit_task) + goto force_balance; + + /* + * If the local group is busier than the selected busiest group + * don't try and pull any tasks. + */ + if (local->avg_load >= busiest->avg_load) + goto out_balanced; + + /* + * Don't pull any tasks if this group is already above the domain + * average load. + */ + if (local->avg_load >= sds.avg_load) + goto out_balanced; + + if (env->idle == CPU_IDLE) { + /* + * This CPU is idle. If the busiest group is not overloaded + * and there is no imbalance between this and busiest group + * wrt idle CPUs, it is balanced. The imbalance becomes + * significant if the diff is greater than 1 otherwise we + * might end up to just move the imbalance on another group + */ + if ((busiest->group_type != group_overloaded) && + (local->idle_cpus <= (busiest->idle_cpus + 1))) + goto out_balanced; + } else { + /* + * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use + * imbalance_pct to be conservative. + */ + if (100 * busiest->avg_load <= + env->sd->imbalance_pct * local->avg_load) + goto out_balanced; + } + +force_balance: + /* Looks like there is an imbalance. Compute it */ + env->src_grp_type = busiest->group_type; + calculate_imbalance(env, &sds); + return env->imbalance ? sds.busiest : NULL; + +out_balanced: + env->imbalance = 0; + return NULL; +} +",0,"static struct sched_group *find_busiest_group(struct lb_env *env) +{ + struct sg_lb_stats *local, *busiest; + struct sd_lb_stats sds; + + init_sd_lb_stats(&sds); + + /* + * Compute the various statistics relavent for load balancing at + * this level. + */ + update_sd_lb_stats(env, &sds); + + if (static_branch_unlikely(&sched_energy_present)) { + struct root_domain *rd = env->dst_rq->rd; + + if (rcu_dereference(rd->pd) && !READ_ONCE(rd->overutilized)) + goto out_balanced; + } + + local = &sds.local_stat; + busiest = &sds.busiest_stat; + + /* ASYM feature bypasses nice load balance check */ + if (check_asym_packing(env, &sds)) + return sds.busiest; + + /* There is no busy sibling group to pull tasks from */ + if (!sds.busiest || busiest->sum_nr_running == 0) + goto out_balanced; + + /* XXX broken for overlapping NUMA groups */ + sds.avg_load = (SCHED_CAPACITY_SCALE * sds.total_load) + / sds.total_capacity; + + /* + * If the busiest group is imbalanced the below checks don't + * work because they assume all things are equal, which typically + * isn't true due to cpus_allowed constraints and the like. + */ + if (busiest->group_type == group_imbalanced) + goto force_balance; + + /* + * When dst_cpu is idle, prevent SMP nice and/or asymmetric group + * capacities from resulting in underutilization due to avg_load. + */ + if (env->idle != CPU_NOT_IDLE && group_has_capacity(env, local) && + busiest->group_no_capacity) + goto force_balance; + + /* Misfit tasks should be dealt with regardless of the avg load */ + if (busiest->group_type == group_misfit_task) + goto force_balance; + + /* + * If the local group is busier than the selected busiest group + * don't try and pull any tasks. + */ + if (local->avg_load >= busiest->avg_load) + goto out_balanced; + + /* + * Don't pull any tasks if this group is already above the domain + * average load. + */ + if (local->avg_load >= sds.avg_load) + goto out_balanced; + + if (env->idle == CPU_IDLE) { + /* + * This CPU is idle. If the busiest group is not overloaded + * and there is no imbalance between this and busiest group + * wrt idle CPUs, it is balanced. The imbalance becomes + * significant if the diff is greater than 1 otherwise we + * might end up to just move the imbalance on another group + */ + if ((busiest->group_type != group_overloaded) && + (local->idle_cpus <= (busiest->idle_cpus + 1))) + goto out_balanced; + } else { + /* + * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use + * imbalance_pct to be conservative. + */ + if (100 * busiest->avg_load <= + env->sd->imbalance_pct * local->avg_load) + goto out_balanced; + } + +force_balance: + /* Looks like there is an imbalance. Compute it */ + env->src_grp_type = busiest->group_type; + calculate_imbalance(env, &sds); + return env->imbalance ? sds.busiest : NULL; + +out_balanced: + env->imbalance = 0; + return NULL; +} +","@@ -352,10 +352,9 @@ static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq) + } + } + +-/* Iterate thr' all leaf cfs_rq's on a runqueue */ +-#define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \ +- list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list, \ +- leaf_cfs_rq_list) ++/* Iterate through all leaf cfs_rq's on a runqueue: */ ++#define for_each_leaf_cfs_rq(rq, cfs_rq) \ ++ list_for_each_entry_rcu(cfs_rq, &rq->leaf_cfs_rq_list, leaf_cfs_rq_list) + + /* Do the two (enqueued) entities belong to the same group ? */ + static inline struct cfs_rq * +@@ -447,8 +446,8 @@ static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq) + { + } + +-#define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \ +- for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos) ++#define for_each_leaf_cfs_rq(rq, cfs_rq) \ ++ for (cfs_rq = &rq->cfs; cfs_rq; cfs_rq = NULL) + + static inline struct sched_entity *parent_entity(struct sched_entity *se) + { +@@ -7647,27 +7646,10 @@ static inline bool others_have_blocked(struct rq *rq) + + #ifdef CONFIG_FAIR_GROUP_SCHED + +-static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq) +-{ +- if (cfs_rq->load.weight) +- return false; +- +- if (cfs_rq->avg.load_sum) +- return false; +- +- if (cfs_rq->avg.util_sum) +- return false; +- +- if (cfs_rq->avg.runnable_load_sum) +- return false; +- +- return true; +-} +- + static void update_blocked_averages(int cpu) + { + struct rq *rq = cpu_rq(cpu); +- struct cfs_rq *cfs_rq, *pos; ++ struct cfs_rq *cfs_rq; + const struct sched_class *curr_class; + struct rq_flags rf; + bool done = true; +@@ -7679,7 +7661,7 @@ static void update_blocked_averages(int cpu) + * Iterates the task_group tree in a bottom up fashion, see + * list_add_leaf_cfs_rq() for details. + */ +- for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) { ++ for_each_leaf_cfs_rq(rq, cfs_rq) { + struct sched_entity *se; + + /* throttled entities do not contribute to load */ +@@ -7694,13 +7676,6 @@ static void update_blocked_averages(int cpu) + if (se && !skip_blocked_update(se)) + update_load_avg(cfs_rq_of(se), se, 0); + +- /* +- * There can be a lot of idle CPU cgroups. Don't let fully +- * decayed cfs_rqs linger on the list. +- */ +- if (cfs_rq_is_decayed(cfs_rq)) +- list_del_leaf_cfs_rq(cfs_rq); +- + /* Don't need periodic decay once load/util_avg are null */ + if (cfs_rq_has_blocked(cfs_rq)) + done = false; +@@ -10570,10 +10545,10 @@ const struct sched_class fair_sched_class = { + #ifdef CONFIG_SCHED_DEBUG + void print_cfs_stats(struct seq_file *m, int cpu) + { +- struct cfs_rq *cfs_rq, *pos; ++ struct cfs_rq *cfs_rq; + + rcu_read_lock(); +- for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos) ++ for_each_leaf_cfs_rq(cpu_rq(cpu), cfs_rq) + print_cfs_rq(m, cpu, cfs_rq); + rcu_read_unlock(); + }",760,1091,2048 +17791,"s_aes_process(stream_state * ss, stream_cursor_read * pr, + stream_cursor_write * pw, bool last) +{ + stream_aes_state *const state = (stream_aes_state *) ss; + const unsigned char *limit; + const long in_size = pr->limit - pr->ptr; + const long out_size = pw->limit - pw->ptr; + unsigned char temp[16]; + int status = 0; + + /* figure out if we're going to run out of space */ + if (in_size > out_size) { + limit = pr->ptr + out_size; + status = 1; /* need more output space */ + } else { + limit = pr->limit; + status = last ? EOFC : 0; /* need more input */ + } + + /* set up state and context */ + if (state->ctx == NULL) { + /* allocate the aes context. this is a public struct but it + contains internal pointers, so we need to store it separately + in immovable memory like any opaque structure. */ + state->ctx = (aes_context *)gs_alloc_bytes_immovable(state->memory, + sizeof(aes_context), ""aes context structure""); + if (state->ctx == NULL) { + gs_throw(gs_error_VMerror, ""could not allocate aes context""); + return ERRC; + } + if (state->keylength < 1 || state->keylength > SAES_MAX_KEYLENGTH) { + gs_throw1(gs_error_rangecheck, ""invalid aes key length (%d bytes)"", + state->keylength); + } + aes_setkey_dec(state->ctx, state->key, state->keylength * 8); + } + if (!state->initialized) { + /* read the initialization vector from the first 16 bytes */ + if (in_size < 16) return 0; /* get more data */ + memcpy(state->iv, pr->ptr + 1, 16); + state->initialized = 1; + pr->ptr += 16; + } + + /* decrypt available blocks */ + while (pr->ptr + 16 <= limit) { + aes_crypt_cbc(state->ctx, AES_DECRYPT, 16, state->iv, + pr->ptr + 1, temp); + pr->ptr += 16; + if (last && pr->ptr == pr->limit) { + /* we're on the last block; unpad if necessary */ + int pad; + + if (state->use_padding) { + /* we are using RFC 1423-style padding, so the last byte of the + plaintext gives the number of bytes to discard */ + pad = temp[15]; + if (pad < 1 || pad > 16) { + /* Bug 692343 - don't error here, just warn. Take padding to be + * zero. This may give us a stream that's too long - preferable + * to the alternatives. */ + gs_warn1(""invalid aes padding byte (0x%02x)"", + (unsigned char)pad); + pad = 0; + } + } else { + /* not using padding */ + pad = 0; + } + + memcpy(pw->ptr + 1, temp, 16 - pad); + pw->ptr += 16 - pad; + return EOFC; + } + memcpy(pw->ptr + 1, temp, 16); + pw->ptr += 16; + } + + /* if we got to the end of the file without triggering the padding + check, the input must not have been a multiple of 16 bytes long. + complain. */ + if (status == EOFC) { + gs_throw(gs_error_rangecheck, ""aes stream isn't a multiple of 16 bytes""); + return 0; + } + + return status; +} +",1,"s_aes_process(stream_state * ss, stream_cursor_read * pr, + stream_cursor_write * pw, bool last) +{ + stream_aes_state *const state = (stream_aes_state *) ss; + const unsigned char *limit; + const long in_size = pr->limit - pr->ptr; + const long out_size = pw->limit - pw->ptr; + unsigned char temp[16]; + int status = 0; + + /* figure out if we're going to run out of space */ + if (in_size > out_size) { + limit = pr->ptr + out_size; + status = 1; /* need more output space */ + } else { + limit = pr->limit; + status = last ? EOFC : 0; /* need more input */ + } + + /* set up state and context */ + if (state->ctx == NULL) { + /* allocate the aes context. this is a public struct but it + contains internal pointers, so we need to store it separately + in immovable memory like any opaque structure. */ + state->ctx = (aes_context *)gs_alloc_bytes_immovable(state->memory, + sizeof(aes_context), ""aes context structure""); + if (state->ctx == NULL) { + gs_throw(gs_error_VMerror, ""could not allocate aes context""); + return ERRC; + } + memset(state->ctx, 0x00, sizeof(aes_context)); + if (state->keylength < 1 || state->keylength > SAES_MAX_KEYLENGTH) { + gs_throw1(gs_error_rangecheck, ""invalid aes key length (%d bytes)"", + state->keylength); + } + aes_setkey_dec(state->ctx, state->key, state->keylength * 8); + } + if (!state->initialized) { + /* read the initialization vector from the first 16 bytes */ + if (in_size < 16) return 0; /* get more data */ + memcpy(state->iv, pr->ptr + 1, 16); + state->initialized = 1; + pr->ptr += 16; + } + + /* decrypt available blocks */ + while (pr->ptr + 16 <= limit) { + aes_crypt_cbc(state->ctx, AES_DECRYPT, 16, state->iv, + pr->ptr + 1, temp); + pr->ptr += 16; + if (last && pr->ptr == pr->limit) { + /* we're on the last block; unpad if necessary */ + int pad; + + if (state->use_padding) { + /* we are using RFC 1423-style padding, so the last byte of the + plaintext gives the number of bytes to discard */ + pad = temp[15]; + if (pad < 1 || pad > 16) { + /* Bug 692343 - don't error here, just warn. Take padding to be + * zero. This may give us a stream that's too long - preferable + * to the alternatives. */ + gs_warn1(""invalid aes padding byte (0x%02x)"", + (unsigned char)pad); + pad = 0; + } + } else { + /* not using padding */ + pad = 0; + } + + memcpy(pw->ptr + 1, temp, 16 - pad); + pw->ptr += 16 - pad; + return EOFC; + } + memcpy(pw->ptr + 1, temp, 16); + pw->ptr += 16; + } + + /* if we got to the end of the file without triggering the padding + check, the input must not have been a multiple of 16 bytes long. + complain. */ + if (status == EOFC) { + gs_throw(gs_error_rangecheck, ""aes stream isn't a multiple of 16 bytes""); + return 0; + } + + return status; +} +","@@ -120,6 +120,7 @@ s_aes_process(stream_state * ss, stream_cursor_read * pr, + gs_throw(gs_error_VMerror, ""could not allocate aes context""); + return ERRC; + } ++ memset(state->ctx, 0x00, sizeof(aes_context)); + if (state->keylength < 1 || state->keylength > SAES_MAX_KEYLENGTH) { + gs_throw1(gs_error_rangecheck, ""invalid aes key length (%d bytes)"", + state->keylength);",831,1162,2048 +4536,"ext4_ext_handle_unwritten_extents(handle_t *handle, struct inode *inode, + struct ext4_map_blocks *map, + struct ext4_ext_path **ppath, int flags, + unsigned int allocated, ext4_fsblk_t newblock) +{ + struct ext4_ext_path *path = *ppath; + int ret = 0; + int err = 0; + ext4_io_end_t *io = ext4_inode_aio(inode); + + ext_debug(""ext4_ext_handle_unwritten_extents: inode %lu, logical "" + ""block %llu, max_blocks %u, flags %x, allocated %u\n"", + inode->i_ino, (unsigned long long)map->m_lblk, map->m_len, + flags, allocated); + ext4_ext_show_leaf(inode, path); + + /* + * When writing into unwritten space, we should not fail to + * allocate metadata blocks for the new extent block if needed. + */ + flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL; + + trace_ext4_ext_handle_unwritten_extents(inode, map, flags, + allocated, newblock); + + /* get_block() before submit the IO, split the extent */ + if (flags & EXT4_GET_BLOCKS_PRE_IO) { + ret = ext4_split_convert_extents(handle, inode, map, ppath, + flags | EXT4_GET_BLOCKS_CONVERT); + if (ret <= 0) + goto out; + /* + * Flag the inode(non aio case) or end_io struct (aio case) + * that this IO needs to conversion to written when IO is + * completed + */ + if (io) + ext4_set_io_unwritten_flag(inode, io); + else + ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN); + map->m_flags |= EXT4_MAP_UNWRITTEN; + goto out; + } + /* IO end_io complete, convert the filled extent to written */ + if (flags & EXT4_GET_BLOCKS_CONVERT) { + ret = ext4_convert_unwritten_extents_endio(handle, inode, map, + ppath); + if (ret >= 0) { + ext4_update_inode_fsync_trans(handle, inode, 1); + err = check_eofblocks_fl(handle, inode, map->m_lblk, + path, map->m_len); + } else + err = ret; + map->m_flags |= EXT4_MAP_MAPPED; + map->m_pblk = newblock; + if (allocated > map->m_len) + allocated = map->m_len; + map->m_len = allocated; + goto out2; + } + /* buffered IO case */ + /* + * repeat fallocate creation request + * we already have an unwritten extent + */ + if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) { + map->m_flags |= EXT4_MAP_UNWRITTEN; + goto map_out; + } + + /* buffered READ or buffered write_begin() lookup */ + if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) { + /* + * We have blocks reserved already. We + * return allocated blocks so that delalloc + * won't do block reservation for us. But + * the buffer head will be unmapped so that + * a read from the block returns 0s. + */ + map->m_flags |= EXT4_MAP_UNWRITTEN; + goto out1; + } + + /* buffered write, writepage time, convert*/ + ret = ext4_ext_convert_to_initialized(handle, inode, map, ppath, flags); + if (ret >= 0) + ext4_update_inode_fsync_trans(handle, inode, 1); +out: + if (ret <= 0) { + err = ret; + goto out2; + } else + allocated = ret; + map->m_flags |= EXT4_MAP_NEW; + /* + * if we allocated more blocks than requested + * we need to make sure we unmap the extra block + * allocated. The actual needed block will get + * unmapped later when we find the buffer_head marked + * new. + */ + if (allocated > map->m_len) { + unmap_underlying_metadata_blocks(inode->i_sb->s_bdev, + newblock + map->m_len, + allocated - map->m_len); + allocated = map->m_len; + } + map->m_len = allocated; + + /* + * If we have done fallocate with the offset that is already + * delayed allocated, we would have block reservation + * and quota reservation done in the delayed write path. + * But fallocate would have already updated quota and block + * count for this offset. So cancel these reservation + */ + if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) { + unsigned int reserved_clusters; + reserved_clusters = get_reserved_cluster_alloc(inode, + map->m_lblk, map->m_len); + if (reserved_clusters) + ext4_da_update_reserve_space(inode, + reserved_clusters, + 0); + } + +map_out: + map->m_flags |= EXT4_MAP_MAPPED; + if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0) { + err = check_eofblocks_fl(handle, inode, map->m_lblk, path, + map->m_len); + if (err < 0) + goto out2; + } +out1: + if (allocated > map->m_len) + allocated = map->m_len; + ext4_ext_show_leaf(inode, path); + map->m_pblk = newblock; + map->m_len = allocated; +out2: + return err ? err : allocated; +} +",0,"ext4_ext_handle_unwritten_extents(handle_t *handle, struct inode *inode, + struct ext4_map_blocks *map, + struct ext4_ext_path **ppath, int flags, + unsigned int allocated, ext4_fsblk_t newblock) +{ + struct ext4_ext_path *path = *ppath; + int ret = 0; + int err = 0; + ext4_io_end_t *io = ext4_inode_aio(inode); + + ext_debug(""ext4_ext_handle_unwritten_extents: inode %lu, logical "" + ""block %llu, max_blocks %u, flags %x, allocated %u\n"", + inode->i_ino, (unsigned long long)map->m_lblk, map->m_len, + flags, allocated); + ext4_ext_show_leaf(inode, path); + + /* + * When writing into unwritten space, we should not fail to + * allocate metadata blocks for the new extent block if needed. + */ + flags |= EXT4_GET_BLOCKS_METADATA_NOFAIL; + + trace_ext4_ext_handle_unwritten_extents(inode, map, flags, + allocated, newblock); + + /* get_block() before submit the IO, split the extent */ + if (flags & EXT4_GET_BLOCKS_PRE_IO) { + ret = ext4_split_convert_extents(handle, inode, map, ppath, + flags | EXT4_GET_BLOCKS_CONVERT); + if (ret <= 0) + goto out; + /* + * Flag the inode(non aio case) or end_io struct (aio case) + * that this IO needs to conversion to written when IO is + * completed + */ + if (io) + ext4_set_io_unwritten_flag(inode, io); + else + ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN); + map->m_flags |= EXT4_MAP_UNWRITTEN; + goto out; + } + /* IO end_io complete, convert the filled extent to written */ + if (flags & EXT4_GET_BLOCKS_CONVERT) { + ret = ext4_convert_unwritten_extents_endio(handle, inode, map, + ppath); + if (ret >= 0) { + ext4_update_inode_fsync_trans(handle, inode, 1); + err = check_eofblocks_fl(handle, inode, map->m_lblk, + path, map->m_len); + } else + err = ret; + map->m_flags |= EXT4_MAP_MAPPED; + map->m_pblk = newblock; + if (allocated > map->m_len) + allocated = map->m_len; + map->m_len = allocated; + goto out2; + } + /* buffered IO case */ + /* + * repeat fallocate creation request + * we already have an unwritten extent + */ + if (flags & EXT4_GET_BLOCKS_UNWRIT_EXT) { + map->m_flags |= EXT4_MAP_UNWRITTEN; + goto map_out; + } + + /* buffered READ or buffered write_begin() lookup */ + if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) { + /* + * We have blocks reserved already. We + * return allocated blocks so that delalloc + * won't do block reservation for us. But + * the buffer head will be unmapped so that + * a read from the block returns 0s. + */ + map->m_flags |= EXT4_MAP_UNWRITTEN; + goto out1; + } + + /* buffered write, writepage time, convert*/ + ret = ext4_ext_convert_to_initialized(handle, inode, map, ppath, flags); + if (ret >= 0) + ext4_update_inode_fsync_trans(handle, inode, 1); +out: + if (ret <= 0) { + err = ret; + goto out2; + } else + allocated = ret; + map->m_flags |= EXT4_MAP_NEW; + /* + * if we allocated more blocks than requested + * we need to make sure we unmap the extra block + * allocated. The actual needed block will get + * unmapped later when we find the buffer_head marked + * new. + */ + if (allocated > map->m_len) { + unmap_underlying_metadata_blocks(inode->i_sb->s_bdev, + newblock + map->m_len, + allocated - map->m_len); + allocated = map->m_len; + } + map->m_len = allocated; + + /* + * If we have done fallocate with the offset that is already + * delayed allocated, we would have block reservation + * and quota reservation done in the delayed write path. + * But fallocate would have already updated quota and block + * count for this offset. So cancel these reservation + */ + if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) { + unsigned int reserved_clusters; + reserved_clusters = get_reserved_cluster_alloc(inode, + map->m_lblk, map->m_len); + if (reserved_clusters) + ext4_da_update_reserve_space(inode, + reserved_clusters, + 0); + } + +map_out: + map->m_flags |= EXT4_MAP_MAPPED; + if ((flags & EXT4_GET_BLOCKS_KEEP_SIZE) == 0) { + err = check_eofblocks_fl(handle, inode, map->m_lblk, path, + map->m_len); + if (err < 0) + goto out2; + } +out1: + if (allocated > map->m_len) + allocated = map->m_len; + ext4_ext_show_leaf(inode, path); + map->m_pblk = newblock; + map->m_len = allocated; +out2: + return err ? err : allocated; +} +","@@ -4797,12 +4797,6 @@ static long ext4_zero_range(struct file *file, loff_t offset, + else + max_blocks -= lblk; + +- flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT | +- EXT4_GET_BLOCKS_CONVERT_UNWRITTEN | +- EXT4_EX_NOCACHE; +- if (mode & FALLOC_FL_KEEP_SIZE) +- flags |= EXT4_GET_BLOCKS_KEEP_SIZE; +- + mutex_lock(&inode->i_mutex); + + /* +@@ -4819,15 +4813,28 @@ static long ext4_zero_range(struct file *file, loff_t offset, + ret = inode_newsize_ok(inode, new_size); + if (ret) + goto out_mutex; +- /* +- * If we have a partial block after EOF we have to allocate +- * the entire block. +- */ +- if (partial_end) +- max_blocks += 1; + } + ++ flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT; ++ if (mode & FALLOC_FL_KEEP_SIZE) ++ flags |= EXT4_GET_BLOCKS_KEEP_SIZE; ++ ++ /* Preallocate the range including the unaligned edges */ ++ if (partial_begin || partial_end) { ++ ret = ext4_alloc_file_blocks(file, ++ round_down(offset, 1 << blkbits) >> blkbits, ++ (round_up((offset + len), 1 << blkbits) - ++ round_down(offset, 1 << blkbits)) >> blkbits, ++ new_size, flags, mode); ++ if (ret) ++ goto out_mutex; ++ ++ } ++ ++ /* Zero range excluding the unaligned edges */ + if (max_blocks > 0) { ++ flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN | ++ EXT4_EX_NOCACHE); + + /* Now release the pages and zero block aligned part of pages*/ + truncate_pagecache_range(inode, start, end - 1);",1203,1534,2048 +4124,"static int ethtool_ioctl(struct net *net, struct compat_ifreq __user *ifr32) +{ + struct compat_ethtool_rxnfc __user *compat_rxnfc; + bool convert_in = false, convert_out = false; + size_t buf_size = ALIGN(sizeof(struct ifreq), 8); + struct ethtool_rxnfc __user *rxnfc; + struct ifreq __user *ifr; + u32 rule_cnt = 0, actual_rule_cnt; + u32 ethcmd; + u32 data; + int ret; + + if (get_user(data, &ifr32->ifr_ifru.ifru_data)) + return -EFAULT; + + compat_rxnfc = compat_ptr(data); + + if (get_user(ethcmd, &compat_rxnfc->cmd)) + return -EFAULT; + + /* Most ethtool structures are defined without padding. + * Unfortunately struct ethtool_rxnfc is an exception. + */ + switch (ethcmd) { + default: + break; + case ETHTOOL_GRXCLSRLALL: + /* Buffer size is variable */ + if (get_user(rule_cnt, &compat_rxnfc->rule_cnt)) + return -EFAULT; + if (rule_cnt > KMALLOC_MAX_SIZE / sizeof(u32)) + return -ENOMEM; + buf_size += rule_cnt * sizeof(u32); + /* fall through */ + case ETHTOOL_GRXRINGS: + case ETHTOOL_GRXCLSRLCNT: + case ETHTOOL_GRXCLSRULE: + case ETHTOOL_SRXCLSRLINS: + convert_out = true; + /* fall through */ + case ETHTOOL_SRXCLSRLDEL: + buf_size += sizeof(struct ethtool_rxnfc); + convert_in = true; + break; + } + + ifr = compat_alloc_user_space(buf_size); + rxnfc = (void __user *)ifr + ALIGN(sizeof(struct ifreq), 8); + + if (copy_in_user(&ifr->ifr_name, &ifr32->ifr_name, IFNAMSIZ)) + return -EFAULT; + + if (put_user(convert_in ? rxnfc : compat_ptr(data), + &ifr->ifr_ifru.ifru_data)) + return -EFAULT; + + if (convert_in) { + /* We expect there to be holes between fs.m_ext and + * fs.ring_cookie and at the end of fs, but nowhere else. + */ + BUILD_BUG_ON(offsetof(struct compat_ethtool_rxnfc, fs.m_ext) + + sizeof(compat_rxnfc->fs.m_ext) != + offsetof(struct ethtool_rxnfc, fs.m_ext) + + sizeof(rxnfc->fs.m_ext)); + BUILD_BUG_ON( + offsetof(struct compat_ethtool_rxnfc, fs.location) - + offsetof(struct compat_ethtool_rxnfc, fs.ring_cookie) != + offsetof(struct ethtool_rxnfc, fs.location) - + offsetof(struct ethtool_rxnfc, fs.ring_cookie)); + + if (copy_in_user(rxnfc, compat_rxnfc, + (void __user *)(&rxnfc->fs.m_ext + 1) - + (void __user *)rxnfc) || + copy_in_user(&rxnfc->fs.ring_cookie, + &compat_rxnfc->fs.ring_cookie, + (void __user *)(&rxnfc->fs.location + 1) - + (void __user *)&rxnfc->fs.ring_cookie) || + copy_in_user(&rxnfc->rule_cnt, &compat_rxnfc->rule_cnt, + sizeof(rxnfc->rule_cnt))) + return -EFAULT; + } + + ret = dev_ioctl(net, SIOCETHTOOL, ifr); + if (ret) + return ret; + + if (convert_out) { + if (copy_in_user(compat_rxnfc, rxnfc, + (const void __user *)(&rxnfc->fs.m_ext + 1) - + (const void __user *)rxnfc) || + copy_in_user(&compat_rxnfc->fs.ring_cookie, + &rxnfc->fs.ring_cookie, + (const void __user *)(&rxnfc->fs.location + 1) - + (const void __user *)&rxnfc->fs.ring_cookie) || + copy_in_user(&compat_rxnfc->rule_cnt, &rxnfc->rule_cnt, + sizeof(rxnfc->rule_cnt))) + return -EFAULT; + + if (ethcmd == ETHTOOL_GRXCLSRLALL) { + /* As an optimisation, we only copy the actual + * number of rules that the underlying + * function returned. Since Mallory might + * change the rule count in user memory, we + * check that it is less than the rule count + * originally given (as the user buffer size), + * which has been range-checked. + */ + if (get_user(actual_rule_cnt, &rxnfc->rule_cnt)) + return -EFAULT; + if (actual_rule_cnt < rule_cnt) + rule_cnt = actual_rule_cnt; + if (copy_in_user(&compat_rxnfc->rule_locs[0], + &rxnfc->rule_locs[0], + rule_cnt * sizeof(u32))) + return -EFAULT; + } + } + + return 0; +} +",0,"static int ethtool_ioctl(struct net *net, struct compat_ifreq __user *ifr32) +{ + struct compat_ethtool_rxnfc __user *compat_rxnfc; + bool convert_in = false, convert_out = false; + size_t buf_size = ALIGN(sizeof(struct ifreq), 8); + struct ethtool_rxnfc __user *rxnfc; + struct ifreq __user *ifr; + u32 rule_cnt = 0, actual_rule_cnt; + u32 ethcmd; + u32 data; + int ret; + + if (get_user(data, &ifr32->ifr_ifru.ifru_data)) + return -EFAULT; + + compat_rxnfc = compat_ptr(data); + + if (get_user(ethcmd, &compat_rxnfc->cmd)) + return -EFAULT; + + /* Most ethtool structures are defined without padding. + * Unfortunately struct ethtool_rxnfc is an exception. + */ + switch (ethcmd) { + default: + break; + case ETHTOOL_GRXCLSRLALL: + /* Buffer size is variable */ + if (get_user(rule_cnt, &compat_rxnfc->rule_cnt)) + return -EFAULT; + if (rule_cnt > KMALLOC_MAX_SIZE / sizeof(u32)) + return -ENOMEM; + buf_size += rule_cnt * sizeof(u32); + /* fall through */ + case ETHTOOL_GRXRINGS: + case ETHTOOL_GRXCLSRLCNT: + case ETHTOOL_GRXCLSRULE: + case ETHTOOL_SRXCLSRLINS: + convert_out = true; + /* fall through */ + case ETHTOOL_SRXCLSRLDEL: + buf_size += sizeof(struct ethtool_rxnfc); + convert_in = true; + break; + } + + ifr = compat_alloc_user_space(buf_size); + rxnfc = (void __user *)ifr + ALIGN(sizeof(struct ifreq), 8); + + if (copy_in_user(&ifr->ifr_name, &ifr32->ifr_name, IFNAMSIZ)) + return -EFAULT; + + if (put_user(convert_in ? rxnfc : compat_ptr(data), + &ifr->ifr_ifru.ifru_data)) + return -EFAULT; + + if (convert_in) { + /* We expect there to be holes between fs.m_ext and + * fs.ring_cookie and at the end of fs, but nowhere else. + */ + BUILD_BUG_ON(offsetof(struct compat_ethtool_rxnfc, fs.m_ext) + + sizeof(compat_rxnfc->fs.m_ext) != + offsetof(struct ethtool_rxnfc, fs.m_ext) + + sizeof(rxnfc->fs.m_ext)); + BUILD_BUG_ON( + offsetof(struct compat_ethtool_rxnfc, fs.location) - + offsetof(struct compat_ethtool_rxnfc, fs.ring_cookie) != + offsetof(struct ethtool_rxnfc, fs.location) - + offsetof(struct ethtool_rxnfc, fs.ring_cookie)); + + if (copy_in_user(rxnfc, compat_rxnfc, + (void __user *)(&rxnfc->fs.m_ext + 1) - + (void __user *)rxnfc) || + copy_in_user(&rxnfc->fs.ring_cookie, + &compat_rxnfc->fs.ring_cookie, + (void __user *)(&rxnfc->fs.location + 1) - + (void __user *)&rxnfc->fs.ring_cookie) || + copy_in_user(&rxnfc->rule_cnt, &compat_rxnfc->rule_cnt, + sizeof(rxnfc->rule_cnt))) + return -EFAULT; + } + + ret = dev_ioctl(net, SIOCETHTOOL, ifr); + if (ret) + return ret; + + if (convert_out) { + if (copy_in_user(compat_rxnfc, rxnfc, + (const void __user *)(&rxnfc->fs.m_ext + 1) - + (const void __user *)rxnfc) || + copy_in_user(&compat_rxnfc->fs.ring_cookie, + &rxnfc->fs.ring_cookie, + (const void __user *)(&rxnfc->fs.location + 1) - + (const void __user *)&rxnfc->fs.ring_cookie) || + copy_in_user(&compat_rxnfc->rule_cnt, &rxnfc->rule_cnt, + sizeof(rxnfc->rule_cnt))) + return -EFAULT; + + if (ethcmd == ETHTOOL_GRXCLSRLALL) { + /* As an optimisation, we only copy the actual + * number of rules that the underlying + * function returned. Since Mallory might + * change the rule count in user memory, we + * check that it is less than the rule count + * originally given (as the user buffer size), + * which has been range-checked. + */ + if (get_user(actual_rule_cnt, &rxnfc->rule_cnt)) + return -EFAULT; + if (actual_rule_cnt < rule_cnt) + rule_cnt = actual_rule_cnt; + if (copy_in_user(&compat_rxnfc->rule_locs[0], + &rxnfc->rule_locs[0], + rule_cnt * sizeof(u32))) + return -EFAULT; + } + } + + return 0; +} +","@@ -1840,8 +1840,10 @@ SYSCALL_DEFINE6(recvfrom, int, fd, void __user *, ubuf, size_t, size, + msg.msg_iov = &iov; + iov.iov_len = size; + iov.iov_base = ubuf; +- msg.msg_name = (struct sockaddr *)&address; +- msg.msg_namelen = sizeof(address); ++ /* Save some cycles and don't copy the address if not needed */ ++ msg.msg_name = addr ? (struct sockaddr *)&address : NULL; ++ /* We assume all kernel code knows the size of sockaddr_storage */ ++ msg.msg_namelen = 0; + if (sock->file->f_flags & O_NONBLOCK) + flags |= MSG_DONTWAIT; + err = sock_recvmsg(sock, &msg, size, flags); +@@ -2221,16 +2223,14 @@ static int ___sys_recvmsg(struct socket *sock, struct msghdr __user *msg, + goto out; + } + +- /* +- * Save the user-mode address (verify_iovec will change the +- * kernel msghdr to use the kernel address space) ++ /* Save the user-mode address (verify_iovec will change the ++ * kernel msghdr to use the kernel address space) + */ +- + uaddr = (__force void __user *)msg_sys->msg_name; + uaddr_len = COMPAT_NAMELEN(msg); +- if (MSG_CMSG_COMPAT & flags) { ++ if (MSG_CMSG_COMPAT & flags) + err = verify_compat_iovec(msg_sys, iov, &addr, VERIFY_WRITE); +- } else ++ else + err = verify_iovec(msg_sys, iov, &addr, VERIFY_WRITE); + if (err < 0) + goto out_freeiov; +@@ -2239,6 +2239,9 @@ static int ___sys_recvmsg(struct socket *sock, struct msghdr __user *msg, + cmsg_ptr = (unsigned long)msg_sys->msg_control; + msg_sys->msg_flags = flags & (MSG_CMSG_CLOEXEC|MSG_CMSG_COMPAT); + ++ /* We assume all kernel code knows the size of sockaddr_storage */ ++ msg_sys->msg_namelen = 0; ++ + if (sock->file->f_flags & O_NONBLOCK) + flags |= MSG_DONTWAIT; + err = (nosec ? sock_recvmsg_nosec : sock_recvmsg)(sock, msg_sys,",1146,1477,2048 +8887,"MagickExport MagickBooleanType OrderedDitherImage(Image *image, + const char *threshold_map,ExceptionInfo *exception) +{ +#define DitherImageTag ""Dither/Image"" + + CacheView + *image_view; + + char + token[MagickPathExtent]; + + 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 == MagickCoreSignature); + if (image->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + 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) >= (MagickPathExtent-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)) + { + GetNextToken(p,&p,MagickPathExtent,token); + for (i=0; (i < MaxPixelChannels); i++) + levels[i]=StringToDouble(token,(char **) NULL); + for (i=0; (*p != '\0') && (i < MaxPixelChannels); i++) + { + GetNextToken(p,&p,MagickPathExtent,token); + if (*token == ',') + GetNextToken(p,&p,MagickPathExtent,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) shared(progress,status) \ + magick_number_threads(image,image,image->rows,1) +#endif + for (y=0; y < (ssize_t) image->rows; y++) + { + register ssize_t + x; + + register Quantum + *magick_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; + 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) + { + n++; + 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 atomic +#endif + progress++; + proceed=SetImageProgress(image,DitherImageTag,progress,image->rows); + if (proceed == MagickFalse) + status=MagickFalse; + } + } + image_view=DestroyCacheView(image_view); + map=DestroyThresholdMap(map); + return(MagickTrue); +} +",0,"MagickExport MagickBooleanType OrderedDitherImage(Image *image, + const char *threshold_map,ExceptionInfo *exception) +{ +#define DitherImageTag ""Dither/Image"" + + CacheView + *image_view; + + char + token[MagickPathExtent]; + + 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 == MagickCoreSignature); + if (image->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + 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) >= (MagickPathExtent-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)) + { + GetNextToken(p,&p,MagickPathExtent,token); + for (i=0; (i < MaxPixelChannels); i++) + levels[i]=StringToDouble(token,(char **) NULL); + for (i=0; (*p != '\0') && (i < MaxPixelChannels); i++) + { + GetNextToken(p,&p,MagickPathExtent,token); + if (*token == ',') + GetNextToken(p,&p,MagickPathExtent,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) shared(progress,status) \ + magick_number_threads(image,image,image->rows,1) +#endif + for (y=0; y < (ssize_t) image->rows; y++) + { + register ssize_t + x; + + register Quantum + *magick_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; + 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) + { + n++; + 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 atomic +#endif + progress++; + proceed=SetImageProgress(image,DitherImageTag,progress,image->rows); + if (proceed == MagickFalse) + status=MagickFalse; + } + } + image_view=DestroyCacheView(image_view); + map=DestroyThresholdMap(map); + return(MagickTrue); +} +","@@ -212,6 +212,8 @@ MagickExport Image *AdaptiveThresholdImage(const Image *image, + threshold_image=CloneImage(image,0,0,MagickTrue,exception); + if (threshold_image == (Image *) NULL) + return((Image *) NULL); ++ if (width == 0) ++ return(threshold_image); + status=SetImageStorageClass(threshold_image,DirectClass,exception); + if (status == MagickFalse) + {",1196,1527,2048 +1326,"int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, + ENGINE *impl, const unsigned char *key, + const unsigned char *iv, int enc) +{ + if (enc == -1) + enc = ctx->encrypt; + else { + if (enc) + enc = 1; + ctx->encrypt = enc; + } +#ifndef OPENSSL_NO_ENGINE + /* + * Whether it's nice or not, ""Inits"" can be used on ""Final""'d contexts so + * this context may already have an ENGINE! Try to avoid releasing the + * previous handle, re-querying for an ENGINE, and having a + * reinitialisation, when it may all be unnecessary. + */ + if (ctx->engine && ctx->cipher + && (!cipher || (cipher && (cipher->nid == ctx->cipher->nid)))) + goto skip_to_init; +#endif + if (cipher) { + /* + * Ensure a context left lying around from last time is cleared (the + * previous check attempted to avoid this if the same ENGINE and + * EVP_CIPHER could be used). + */ + if (ctx->cipher) { + unsigned long flags = ctx->flags; + EVP_CIPHER_CTX_reset(ctx); + /* Restore encrypt and flags */ + ctx->encrypt = enc; + ctx->flags = flags; + } +#ifndef OPENSSL_NO_ENGINE + if (impl) { + if (!ENGINE_init(impl)) { + EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR); + return 0; + } + } else + /* Ask if an ENGINE is reserved for this job */ + impl = ENGINE_get_cipher_engine(cipher->nid); + if (impl) { + /* There's an ENGINE for this job ... (apparently) */ + const EVP_CIPHER *c = ENGINE_get_cipher(impl, cipher->nid); + if (!c) { + /* + * One positive side-effect of US's export control history, + * is that we should at least be able to avoid using US + * misspellings of ""initialisation""? + */ + EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR); + return 0; + } + /* We'll use the ENGINE's private cipher definition */ + cipher = c; + /* + * Store the ENGINE functional reference so we know 'cipher' came + * from an ENGINE and we need to release it when done. + */ + ctx->engine = impl; + } else + ctx->engine = NULL; +#endif + + ctx->cipher = cipher; + if (ctx->cipher->ctx_size) { + ctx->cipher_data = OPENSSL_zalloc(ctx->cipher->ctx_size); + if (ctx->cipher_data == NULL) { + EVPerr(EVP_F_EVP_CIPHERINIT_EX, ERR_R_MALLOC_FAILURE); + return 0; + } + } else { + ctx->cipher_data = NULL; + } + ctx->key_len = cipher->key_len; + /* Preserve wrap enable flag, zero everything else */ + ctx->flags &= EVP_CIPHER_CTX_FLAG_WRAP_ALLOW; + if (ctx->cipher->flags & EVP_CIPH_CTRL_INIT) { + if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_INIT, 0, NULL)) { + EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR); + return 0; + } + } + } else if (!ctx->cipher) { + EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_NO_CIPHER_SET); + return 0; + } +#ifndef OPENSSL_NO_ENGINE + skip_to_init: +#endif + /* we assume block size is a power of 2 in *cryptUpdate */ + OPENSSL_assert(ctx->cipher->block_size == 1 + || ctx->cipher->block_size == 8 + || ctx->cipher->block_size == 16); + + if (!(ctx->flags & EVP_CIPHER_CTX_FLAG_WRAP_ALLOW) + && EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_WRAP_MODE) { + EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_WRAP_MODE_NOT_ALLOWED); + return 0; + } + + if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ctx)) & EVP_CIPH_CUSTOM_IV)) { + switch (EVP_CIPHER_CTX_mode(ctx)) { + + case EVP_CIPH_STREAM_CIPHER: + case EVP_CIPH_ECB_MODE: + break; + + case EVP_CIPH_CFB_MODE: + case EVP_CIPH_OFB_MODE: + + ctx->num = 0; + /* fall-through */ + + case EVP_CIPH_CBC_MODE: + + OPENSSL_assert(EVP_CIPHER_CTX_iv_length(ctx) <= + (int)sizeof(ctx->iv)); + if (iv) + memcpy(ctx->oiv, iv, EVP_CIPHER_CTX_iv_length(ctx)); + memcpy(ctx->iv, ctx->oiv, EVP_CIPHER_CTX_iv_length(ctx)); + break; + + case EVP_CIPH_CTR_MODE: + ctx->num = 0; + /* Don't reuse IV for CTR mode */ + if (iv) + memcpy(ctx->iv, iv, EVP_CIPHER_CTX_iv_length(ctx)); + break; + + default: + return 0; + } + } + + if (key || (ctx->cipher->flags & EVP_CIPH_ALWAYS_CALL_INIT)) { + if (!ctx->cipher->init(ctx, key, iv, enc)) + return 0; + } + ctx->buf_len = 0; + ctx->final_used = 0; + ctx->block_mask = ctx->cipher->block_size - 1; + return 1; +} +",0,"int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, + ENGINE *impl, const unsigned char *key, + const unsigned char *iv, int enc) +{ + if (enc == -1) + enc = ctx->encrypt; + else { + if (enc) + enc = 1; + ctx->encrypt = enc; + } +#ifndef OPENSSL_NO_ENGINE + /* + * Whether it's nice or not, ""Inits"" can be used on ""Final""'d contexts so + * this context may already have an ENGINE! Try to avoid releasing the + * previous handle, re-querying for an ENGINE, and having a + * reinitialisation, when it may all be unnecessary. + */ + if (ctx->engine && ctx->cipher + && (!cipher || (cipher && (cipher->nid == ctx->cipher->nid)))) + goto skip_to_init; +#endif + if (cipher) { + /* + * Ensure a context left lying around from last time is cleared (the + * previous check attempted to avoid this if the same ENGINE and + * EVP_CIPHER could be used). + */ + if (ctx->cipher) { + unsigned long flags = ctx->flags; + EVP_CIPHER_CTX_reset(ctx); + /* Restore encrypt and flags */ + ctx->encrypt = enc; + ctx->flags = flags; + } +#ifndef OPENSSL_NO_ENGINE + if (impl) { + if (!ENGINE_init(impl)) { + EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR); + return 0; + } + } else + /* Ask if an ENGINE is reserved for this job */ + impl = ENGINE_get_cipher_engine(cipher->nid); + if (impl) { + /* There's an ENGINE for this job ... (apparently) */ + const EVP_CIPHER *c = ENGINE_get_cipher(impl, cipher->nid); + if (!c) { + /* + * One positive side-effect of US's export control history, + * is that we should at least be able to avoid using US + * misspellings of ""initialisation""? + */ + EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR); + return 0; + } + /* We'll use the ENGINE's private cipher definition */ + cipher = c; + /* + * Store the ENGINE functional reference so we know 'cipher' came + * from an ENGINE and we need to release it when done. + */ + ctx->engine = impl; + } else + ctx->engine = NULL; +#endif + + ctx->cipher = cipher; + if (ctx->cipher->ctx_size) { + ctx->cipher_data = OPENSSL_zalloc(ctx->cipher->ctx_size); + if (ctx->cipher_data == NULL) { + EVPerr(EVP_F_EVP_CIPHERINIT_EX, ERR_R_MALLOC_FAILURE); + return 0; + } + } else { + ctx->cipher_data = NULL; + } + ctx->key_len = cipher->key_len; + /* Preserve wrap enable flag, zero everything else */ + ctx->flags &= EVP_CIPHER_CTX_FLAG_WRAP_ALLOW; + if (ctx->cipher->flags & EVP_CIPH_CTRL_INIT) { + if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_INIT, 0, NULL)) { + EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR); + return 0; + } + } + } else if (!ctx->cipher) { + EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_NO_CIPHER_SET); + return 0; + } +#ifndef OPENSSL_NO_ENGINE + skip_to_init: +#endif + /* we assume block size is a power of 2 in *cryptUpdate */ + OPENSSL_assert(ctx->cipher->block_size == 1 + || ctx->cipher->block_size == 8 + || ctx->cipher->block_size == 16); + + if (!(ctx->flags & EVP_CIPHER_CTX_FLAG_WRAP_ALLOW) + && EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_WRAP_MODE) { + EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_WRAP_MODE_NOT_ALLOWED); + return 0; + } + + if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ctx)) & EVP_CIPH_CUSTOM_IV)) { + switch (EVP_CIPHER_CTX_mode(ctx)) { + + case EVP_CIPH_STREAM_CIPHER: + case EVP_CIPH_ECB_MODE: + break; + + case EVP_CIPH_CFB_MODE: + case EVP_CIPH_OFB_MODE: + + ctx->num = 0; + /* fall-through */ + + case EVP_CIPH_CBC_MODE: + + OPENSSL_assert(EVP_CIPHER_CTX_iv_length(ctx) <= + (int)sizeof(ctx->iv)); + if (iv) + memcpy(ctx->oiv, iv, EVP_CIPHER_CTX_iv_length(ctx)); + memcpy(ctx->iv, ctx->oiv, EVP_CIPHER_CTX_iv_length(ctx)); + break; + + case EVP_CIPH_CTR_MODE: + ctx->num = 0; + /* Don't reuse IV for CTR mode */ + if (iv) + memcpy(ctx->iv, iv, EVP_CIPHER_CTX_iv_length(ctx)); + break; + + default: + return 0; + } + } + + if (key || (ctx->cipher->flags & EVP_CIPH_ALWAYS_CALL_INIT)) { + if (!ctx->cipher->init(ctx, key, iv, enc)) + return 0; + } + ctx->buf_len = 0; + ctx->final_used = 0; + ctx->block_mask = ctx->cipher->block_size - 1; + return 1; +} +","@@ -332,7 +332,7 @@ int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, + bl = ctx->cipher->block_size; + OPENSSL_assert(bl <= (int)sizeof(ctx->buf)); + if (i != 0) { +- if (i + inl < bl) { ++ if (bl - i > inl) { + memcpy(&(ctx->buf[i]), in, inl); + ctx->buf_len += inl; + *outl = 0;",1191,1522,2048 +3474,"static void ccid3_hc_rx_packet_recv(struct sock *sk, struct sk_buff *skb) +{ + struct ccid3_hc_rx_sock *hc = ccid3_hc_rx_sk(sk); + enum ccid3_fback_type do_feedback = CCID3_FBACK_NONE; + const u64 ndp = dccp_sk(sk)->dccps_options_received.dccpor_ndp; + const bool is_data_packet = dccp_data_packet(skb); + + if (unlikely(hc->rx_state == TFRC_RSTATE_NO_DATA)) { + if (is_data_packet) { + const u32 payload = skb->len - dccp_hdr(skb)->dccph_doff * 4; + do_feedback = CCID3_FBACK_INITIAL; + ccid3_hc_rx_set_state(sk, TFRC_RSTATE_DATA); + hc->rx_s = payload; + /* + * Not necessary to update rx_bytes_recv here, + * since X_recv = 0 for the first feedback packet (cf. + * RFC 3448, 6.3) -- gerrit + */ + } + goto update_records; + } + + if (tfrc_rx_hist_duplicate(&hc->rx_hist, skb)) + return; /* done receiving */ + + if (is_data_packet) { + const u32 payload = skb->len - dccp_hdr(skb)->dccph_doff * 4; + /* + * Update moving-average of s and the sum of received payload bytes + */ + hc->rx_s = tfrc_ewma(hc->rx_s, payload, 9); + hc->rx_bytes_recv += payload; + } + + /* + * Perform loss detection and handle pending losses + */ + if (tfrc_rx_handle_loss(&hc->rx_hist, &hc->rx_li_hist, + skb, ndp, ccid3_first_li, sk)) { + do_feedback = CCID3_FBACK_PARAM_CHANGE; + goto done_receiving; + } + + if (tfrc_rx_hist_loss_pending(&hc->rx_hist)) + return; /* done receiving */ + + /* + * Handle data packets: RTT sampling and monitoring p + */ + if (unlikely(!is_data_packet)) + goto update_records; + + if (!tfrc_lh_is_initialised(&hc->rx_li_hist)) { + const u32 sample = tfrc_rx_hist_sample_rtt(&hc->rx_hist, skb); + /* + * Empty loss history: no loss so far, hence p stays 0. + * Sample RTT values, since an RTT estimate is required for the + * computation of p when the first loss occurs; RFC 3448, 6.3.1. + */ + if (sample != 0) + hc->rx_rtt = tfrc_ewma(hc->rx_rtt, sample, 9); + + } else if (tfrc_lh_update_i_mean(&hc->rx_li_hist, skb)) { + /* + * Step (3) of [RFC 3448, 6.1]: Recompute I_mean and, if I_mean + * has decreased (resp. p has increased), send feedback now. + */ + do_feedback = CCID3_FBACK_PARAM_CHANGE; + } + + /* + * Check if the periodic once-per-RTT feedback is due; RFC 4342, 10.3 + */ + if (SUB16(dccp_hdr(skb)->dccph_ccval, hc->rx_last_counter) > 3) + do_feedback = CCID3_FBACK_PERIODIC; + +update_records: + tfrc_rx_hist_add_packet(&hc->rx_hist, skb, ndp); + +done_receiving: + if (do_feedback) + ccid3_hc_rx_send_feedback(sk, skb, do_feedback); +} +",0,"static void ccid3_hc_rx_packet_recv(struct sock *sk, struct sk_buff *skb) +{ + struct ccid3_hc_rx_sock *hc = ccid3_hc_rx_sk(sk); + enum ccid3_fback_type do_feedback = CCID3_FBACK_NONE; + const u64 ndp = dccp_sk(sk)->dccps_options_received.dccpor_ndp; + const bool is_data_packet = dccp_data_packet(skb); + + if (unlikely(hc->rx_state == TFRC_RSTATE_NO_DATA)) { + if (is_data_packet) { + const u32 payload = skb->len - dccp_hdr(skb)->dccph_doff * 4; + do_feedback = CCID3_FBACK_INITIAL; + ccid3_hc_rx_set_state(sk, TFRC_RSTATE_DATA); + hc->rx_s = payload; + /* + * Not necessary to update rx_bytes_recv here, + * since X_recv = 0 for the first feedback packet (cf. + * RFC 3448, 6.3) -- gerrit + */ + } + goto update_records; + } + + if (tfrc_rx_hist_duplicate(&hc->rx_hist, skb)) + return; /* done receiving */ + + if (is_data_packet) { + const u32 payload = skb->len - dccp_hdr(skb)->dccph_doff * 4; + /* + * Update moving-average of s and the sum of received payload bytes + */ + hc->rx_s = tfrc_ewma(hc->rx_s, payload, 9); + hc->rx_bytes_recv += payload; + } + + /* + * Perform loss detection and handle pending losses + */ + if (tfrc_rx_handle_loss(&hc->rx_hist, &hc->rx_li_hist, + skb, ndp, ccid3_first_li, sk)) { + do_feedback = CCID3_FBACK_PARAM_CHANGE; + goto done_receiving; + } + + if (tfrc_rx_hist_loss_pending(&hc->rx_hist)) + return; /* done receiving */ + + /* + * Handle data packets: RTT sampling and monitoring p + */ + if (unlikely(!is_data_packet)) + goto update_records; + + if (!tfrc_lh_is_initialised(&hc->rx_li_hist)) { + const u32 sample = tfrc_rx_hist_sample_rtt(&hc->rx_hist, skb); + /* + * Empty loss history: no loss so far, hence p stays 0. + * Sample RTT values, since an RTT estimate is required for the + * computation of p when the first loss occurs; RFC 3448, 6.3.1. + */ + if (sample != 0) + hc->rx_rtt = tfrc_ewma(hc->rx_rtt, sample, 9); + + } else if (tfrc_lh_update_i_mean(&hc->rx_li_hist, skb)) { + /* + * Step (3) of [RFC 3448, 6.1]: Recompute I_mean and, if I_mean + * has decreased (resp. p has increased), send feedback now. + */ + do_feedback = CCID3_FBACK_PARAM_CHANGE; + } + + /* + * Check if the periodic once-per-RTT feedback is due; RFC 4342, 10.3 + */ + if (SUB16(dccp_hdr(skb)->dccph_ccval, hc->rx_last_counter) > 3) + do_feedback = CCID3_FBACK_PERIODIC; + +update_records: + tfrc_rx_hist_add_packet(&hc->rx_hist, skb, ndp); + +done_receiving: + if (do_feedback) + ccid3_hc_rx_send_feedback(sk, skb, do_feedback); +} +","@@ -535,6 +535,7 @@ static int ccid3_hc_tx_getsockopt(struct sock *sk, const int optname, int len, + case DCCP_SOCKOPT_CCID_TX_INFO: + if (len < sizeof(tfrc)) + return -EINVAL; ++ memset(&tfrc, 0, sizeof(tfrc)); + tfrc.tfrctx_x = hc->tx_x; + tfrc.tfrctx_x_recv = hc->tx_x_recv; + tfrc.tfrctx_x_calc = hc->tx_x_calc;",810,1141,2048 +1877,"static void usage(void) { + printf(PACKAGE "" "" VERSION ""\n""); + printf(""-p TCP port number to listen on (default: 11211)\n"" + ""-U UDP port number to listen on (default: 11211, 0 is off)\n"" + ""-s UNIX socket path to listen on (disables network support)\n"" + ""-a access mask for UNIX socket, in octal (default: 0700)\n"" + ""-l interface to listen on (default: INADDR_ANY, all addresses)\n"" + ""-d run as a daemon\n"" + ""-r maximize core file limit\n"" + ""-u assume identity of (only when run as root)\n"" + ""-m max memory to use for items in megabytes (default: 64 MB)\n"" + ""-M return error on memory exhausted (rather than removing items)\n"" + ""-c max simultaneous connections (default: 1024)\n"" + ""-k lock down all paged memory. Note that there is a\n"" + "" limit on how much memory you may lock. Trying to\n"" + "" allocate more than that would fail, so be sure you\n"" + "" set the limit correctly for the user you started\n"" + "" the daemon with (not for -u user;\n"" + "" under sh this is done with 'ulimit -S -l NUM_KB').\n"" + ""-v verbose (print errors/warnings while in event loop)\n"" + ""-vv very verbose (also print client commands/reponses)\n"" + ""-vvv extremely verbose (also print internal state transitions)\n"" + ""-h print this help and exit\n"" + ""-i print memcached and libevent license\n"" + ""-P save PID in , only used with -d option\n"" + ""-f chunk size growth factor (default: 1.25)\n"" + ""-n minimum space allocated for key+value+flags (default: 48)\n""); + printf(""-L Try to use large memory pages (if available). Increasing\n"" + "" the memory page size could reduce the number of TLB misses\n"" + "" and improve the performance. In order to get large pages\n"" + "" from the OS, memcached will allocate the total item-cache\n"" + "" in one large chunk.\n""); + printf(""-D Use as the delimiter between key prefixes and IDs.\n"" + "" This is used for per-prefix stats reporting. The default is\n"" + "" \"":\"" (colon). If this option is specified, stats collection\n"" + "" is turned on automatically; if not, then it may be turned on\n"" + "" by sending the \""stats detail on\"" command to the server.\n""); + printf(""-t number of threads to use (default: 4)\n""); + printf(""-R Maximum number of requests per event, limits the number of\n"" + "" requests process for a given connection to prevent \n"" + "" starvation (default: 20)\n""); + printf(""-C Disable use of CAS\n""); + printf(""-b Set the backlog queue limit (default: 1024)\n""); + printf(""-B Binding protocol - one of ascii, binary, or auto (default)\n""); + printf(""-I Override the size of each slab page. Adjusts max item size\n"" + "" (default: 1mb, min: 1k, max: 128m)\n""); +#ifdef ENABLE_SASL + printf(""-S Turn on Sasl authentication\n""); +#endif + return; +} +",0,"static void usage(void) { + printf(PACKAGE "" "" VERSION ""\n""); + printf(""-p TCP port number to listen on (default: 11211)\n"" + ""-U UDP port number to listen on (default: 11211, 0 is off)\n"" + ""-s UNIX socket path to listen on (disables network support)\n"" + ""-a access mask for UNIX socket, in octal (default: 0700)\n"" + ""-l interface to listen on (default: INADDR_ANY, all addresses)\n"" + ""-d run as a daemon\n"" + ""-r maximize core file limit\n"" + ""-u assume identity of (only when run as root)\n"" + ""-m max memory to use for items in megabytes (default: 64 MB)\n"" + ""-M return error on memory exhausted (rather than removing items)\n"" + ""-c max simultaneous connections (default: 1024)\n"" + ""-k lock down all paged memory. Note that there is a\n"" + "" limit on how much memory you may lock. Trying to\n"" + "" allocate more than that would fail, so be sure you\n"" + "" set the limit correctly for the user you started\n"" + "" the daemon with (not for -u user;\n"" + "" under sh this is done with 'ulimit -S -l NUM_KB').\n"" + ""-v verbose (print errors/warnings while in event loop)\n"" + ""-vv very verbose (also print client commands/reponses)\n"" + ""-vvv extremely verbose (also print internal state transitions)\n"" + ""-h print this help and exit\n"" + ""-i print memcached and libevent license\n"" + ""-P save PID in , only used with -d option\n"" + ""-f chunk size growth factor (default: 1.25)\n"" + ""-n minimum space allocated for key+value+flags (default: 48)\n""); + printf(""-L Try to use large memory pages (if available). Increasing\n"" + "" the memory page size could reduce the number of TLB misses\n"" + "" and improve the performance. In order to get large pages\n"" + "" from the OS, memcached will allocate the total item-cache\n"" + "" in one large chunk.\n""); + printf(""-D Use as the delimiter between key prefixes and IDs.\n"" + "" This is used for per-prefix stats reporting. The default is\n"" + "" \"":\"" (colon). If this option is specified, stats collection\n"" + "" is turned on automatically; if not, then it may be turned on\n"" + "" by sending the \""stats detail on\"" command to the server.\n""); + printf(""-t number of threads to use (default: 4)\n""); + printf(""-R Maximum number of requests per event, limits the number of\n"" + "" requests process for a given connection to prevent \n"" + "" starvation (default: 20)\n""); + printf(""-C Disable use of CAS\n""); + printf(""-b Set the backlog queue limit (default: 1024)\n""); + printf(""-B Binding protocol - one of ascii, binary, or auto (default)\n""); + printf(""-I Override the size of each slab page. Adjusts max item size\n"" + "" (default: 1mb, min: 1k, max: 128m)\n""); +#ifdef ENABLE_SASL + printf(""-S Turn on Sasl authentication\n""); +#endif + return; +} +","@@ -3148,7 +3148,9 @@ static int try_read_command(conn *c) { + ++ptr; + } + +- if (strcmp(ptr, ""get "") && strcmp(ptr, ""gets "")) { ++ if (ptr - c->rcurr > 100 || ++ (strncmp(ptr, ""get "", 4) && strncmp(ptr, ""gets "", 5))) { ++ + conn_set_state(c, conn_closing); + return 1; + }",862,1193,2048 +18858," void RunSignBiasCheck() { + ACMRandom rnd(ACMRandom::DeterministicSeed()); + DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, 64); + DECLARE_ALIGNED_ARRAY(16, int16_t, test_output_block, 64); + int count_sign_block[64][2]; + const int count_test_block = 100000; + + memset(count_sign_block, 0, sizeof(count_sign_block)); + + + for (int i = 0; i < count_test_block; ++i) { + for (int j = 0; j < 64; ++j) + test_input_block[j] = rnd.Rand8() - rnd.Rand8(); + REGISTER_STATE_CHECK( + RunFwdTxfm(test_input_block, test_output_block, pitch_)); + + for (int j = 0; j < 64; ++j) { + if (test_output_block[j] < 0) + ++count_sign_block[j][0]; + else if (test_output_block[j] > 0) + ++count_sign_block[j][1]; + } + } + + + for (int j = 0; j < 64; ++j) { + const int diff = abs(count_sign_block[j][0] - count_sign_block[j][1]); + const int max_diff = 1125; + EXPECT_LT(diff, max_diff) + << ""Error: 8x8 FDCT/FHT has a sign bias > "" + << 1. * max_diff / count_test_block * 100 << ""%"" + << "" for input range [-255, 255] at index "" << j + << "" count0: "" << count_sign_block[j][0] + << "" count1: "" << count_sign_block[j][1] + << "" diff: "" << diff; + } + + + memset(count_sign_block, 0, sizeof(count_sign_block)); + + for (int i = 0; i < count_test_block; ++i) { + for (int j = 0; j < 64; ++j) + test_input_block[j] = (rnd.Rand8() >> 4) - (rnd.Rand8() >> 4); + REGISTER_STATE_CHECK( + RunFwdTxfm(test_input_block, test_output_block, pitch_)); + + for (int j = 0; j < 64; ++j) { + if (test_output_block[j] < 0) + ++count_sign_block[j][0]; + else if (test_output_block[j] > 0) + ++count_sign_block[j][1]; + } + } + + + for (int j = 0; j < 64; ++j) { + const int diff = abs(count_sign_block[j][0] - count_sign_block[j][1]); + const int max_diff = 10000; + EXPECT_LT(diff, max_diff) + << ""Error: 4x4 FDCT/FHT has a sign bias > "" + << 1. * max_diff / count_test_block * 100 << ""%"" + << "" for input range [-15, 15] at index "" << j + << "" count0: "" << count_sign_block[j][0] + << "" count1: "" << count_sign_block[j][1] + << "" diff: "" << diff; + } + } +",1," void RunSignBiasCheck() { + ACMRandom rnd(ACMRandom::DeterministicSeed()); + DECLARE_ALIGNED(16, int16_t, test_input_block[64]); + DECLARE_ALIGNED(16, tran_low_t, test_output_block[64]); + int count_sign_block[64][2]; + const int count_test_block = 100000; + + memset(count_sign_block, 0, sizeof(count_sign_block)); + + + for (int i = 0; i < count_test_block; ++i) { + for (int j = 0; j < 64; ++j) + test_input_block[j] = ((rnd.Rand16() >> (16 - bit_depth_)) & mask_) - + ((rnd.Rand16() >> (16 - bit_depth_)) & mask_); + ASM_REGISTER_STATE_CHECK( + RunFwdTxfm(test_input_block, test_output_block, pitch_)); + + for (int j = 0; j < 64; ++j) { + if (test_output_block[j] < 0) + ++count_sign_block[j][0]; + else if (test_output_block[j] > 0) + ++count_sign_block[j][1]; + } + } + + + for (int j = 0; j < 64; ++j) { + const int diff = abs(count_sign_block[j][0] - count_sign_block[j][1]); + const int max_diff = kSignBiasMaxDiff255; + EXPECT_LT(diff, max_diff << (bit_depth_ - 8)) + << ""Error: 8x8 FDCT/FHT has a sign bias > "" + << 1. * max_diff / count_test_block * 100 << ""%"" + << "" for input range [-255, 255] at index "" << j + << "" count0: "" << count_sign_block[j][0] + << "" count1: "" << count_sign_block[j][1] + << "" diff: "" << diff; + } + + + memset(count_sign_block, 0, sizeof(count_sign_block)); + + for (int i = 0; i < count_test_block; ++i) { + // Initialize a test block with input range [-mask_ / 16, mask_ / 16]. + for (int j = 0; j < 64; ++j) + test_input_block[j] = ((rnd.Rand16() & mask_) >> 4) - + ((rnd.Rand16() & mask_) >> 4); + ASM_REGISTER_STATE_CHECK( + RunFwdTxfm(test_input_block, test_output_block, pitch_)); + + for (int j = 0; j < 64; ++j) { + if (test_output_block[j] < 0) + ++count_sign_block[j][0]; + else if (test_output_block[j] > 0) + ++count_sign_block[j][1]; + } + } + + + for (int j = 0; j < 64; ++j) { + const int diff = abs(count_sign_block[j][0] - count_sign_block[j][1]); + const int max_diff = kSignBiasMaxDiff15; + EXPECT_LT(diff, max_diff << (bit_depth_ - 8)) + << ""Error: 8x8 FDCT/FHT has a sign bias > "" + << 1. * max_diff / count_test_block * 100 << ""%"" + << "" for input range [-15, 15] at index "" << j + << "" count0: "" << count_sign_block[j][0] + << "" count1: "" << count_sign_block[j][1] + << "" diff: "" << diff; + } + } +","@@ -13,52 +13,139 @@ + + #include + + #include ""third_party/googletest/src/include/gtest/gtest.h"" ++ ++#include ""./vp9_rtcd.h"" ++#include ""./vpx_dsp_rtcd.h"" + #include ""test/acm_random.h"" + #include ""test/clear_system_state.h"" + #include ""test/register_state_check.h"" + #include ""test/util.h"" +- +-#include ""./vp9_rtcd.h"" + #include ""vp9/common/vp9_entropy.h"" ++#include ""vp9/common/vp9_scan.h"" ++#include ""vpx/vpx_codec.h"" + #include ""vpx/vpx_integer.h"" +- +-extern ""C"" { +-void vp9_idct8x8_64_add_c(const int16_t *input, uint8_t *output, int pitch); +-} ++#include ""vpx_ports/mem.h"" + + using libvpx_test::ACMRandom; + + namespace { +-typedef void (*fdct_t)(const int16_t *in, int16_t *out, int stride); +-typedef void (*idct_t)(const int16_t *in, uint8_t *out, int stride); +-typedef void (*fht_t) (const int16_t *in, int16_t *out, int stride, +- int tx_type); +-typedef void (*iht_t) (const int16_t *in, uint8_t *out, int stride, +- int tx_type); + +-typedef std::tr1::tuple dct_8x8_param_t; +-typedef std::tr1::tuple ht_8x8_param_t; ++const int kNumCoeffs = 64; ++const double kPi = 3.141592653589793238462643383279502884; + +-void fdct8x8_ref(const int16_t *in, int16_t *out, int stride, int tx_type) { +- vp9_fdct8x8_c(in, out, stride); ++const int kSignBiasMaxDiff255 = 1500; ++const int kSignBiasMaxDiff15 = 10000; ++ ++typedef void (*FdctFunc)(const int16_t *in, tran_low_t *out, int stride); ++typedef void (*IdctFunc)(const tran_low_t *in, uint8_t *out, int stride); ++typedef void (*FhtFunc)(const int16_t *in, tran_low_t *out, int stride, ++ int tx_type); ++typedef void (*IhtFunc)(const tran_low_t *in, uint8_t *out, int stride, ++ int tx_type); ++ ++typedef std::tr1::tuple Dct8x8Param; ++typedef std::tr1::tuple Ht8x8Param; ++typedef std::tr1::tuple Idct8x8Param; ++ ++void reference_8x8_dct_1d(const double in[8], double out[8], int stride) { ++ const double kInvSqrt2 = 0.707106781186547524400844362104; ++ for (int k = 0; k < 8; k++) { ++ out[k] = 0.0; ++ for (int n = 0; n < 8; n++) ++ out[k] += in[n] * cos(kPi * (2 * n + 1) * k / 16.0); ++ if (k == 0) ++ out[k] = out[k] * kInvSqrt2; ++ } + } + +-void fht8x8_ref(const int16_t *in, int16_t *out, int stride, int tx_type) { ++void reference_8x8_dct_2d(const int16_t input[kNumCoeffs], ++ double output[kNumCoeffs]) { ++ // First transform columns ++ for (int i = 0; i < 8; ++i) { ++ double temp_in[8], temp_out[8]; ++ for (int j = 0; j < 8; ++j) ++ temp_in[j] = input[j*8 + i]; ++ reference_8x8_dct_1d(temp_in, temp_out, 1); ++ for (int j = 0; j < 8; ++j) ++ output[j * 8 + i] = temp_out[j]; ++ } ++ // Then transform rows ++ for (int i = 0; i < 8; ++i) { ++ double temp_in[8], temp_out[8]; ++ for (int j = 0; j < 8; ++j) ++ temp_in[j] = output[j + i*8]; ++ reference_8x8_dct_1d(temp_in, temp_out, 1); ++ // Scale by some magic number ++ for (int j = 0; j < 8; ++j) ++ output[j + i * 8] = temp_out[j] * 2; ++ } ++} ++ ++ ++void fdct8x8_ref(const int16_t *in, tran_low_t *out, int stride, int tx_type) { ++ vpx_fdct8x8_c(in, out, stride); ++} ++ ++void fht8x8_ref(const int16_t *in, tran_low_t *out, int stride, int tx_type) { + vp9_fht8x8_c(in, out, stride, tx_type); + } + ++#if CONFIG_VP9_HIGHBITDEPTH ++void idct8x8_10(const tran_low_t *in, uint8_t *out, int stride) { ++ vpx_highbd_idct8x8_64_add_c(in, out, stride, 10); ++} ++ ++void idct8x8_12(const tran_low_t *in, uint8_t *out, int stride) { ++ vpx_highbd_idct8x8_64_add_c(in, out, stride, 12); ++} ++ ++void iht8x8_10(const tran_low_t *in, uint8_t *out, int stride, int tx_type) { ++ vp9_highbd_iht8x8_64_add_c(in, out, stride, tx_type, 10); ++} ++ ++void iht8x8_12(const tran_low_t *in, uint8_t *out, int stride, int tx_type) { ++ vp9_highbd_iht8x8_64_add_c(in, out, stride, tx_type, 12); ++} ++ ++void idct8x8_10_add_10_c(const tran_low_t *in, uint8_t *out, int stride) { ++ vpx_highbd_idct8x8_10_add_c(in, out, stride, 10); ++} ++ ++void idct8x8_10_add_12_c(const tran_low_t *in, uint8_t *out, int stride) { ++ vpx_highbd_idct8x8_10_add_c(in, out, stride, 12); ++} ++ ++#if HAVE_SSE2 ++void idct8x8_10_add_10_sse2(const tran_low_t *in, uint8_t *out, int stride) { ++ vpx_highbd_idct8x8_10_add_sse2(in, out, stride, 10); ++} ++ ++void idct8x8_10_add_12_sse2(const tran_low_t *in, uint8_t *out, int stride) { ++ vpx_highbd_idct8x8_10_add_sse2(in, out, stride, 12); ++} ++ ++void idct8x8_64_add_10_sse2(const tran_low_t *in, uint8_t *out, int stride) { ++ vpx_highbd_idct8x8_64_add_sse2(in, out, stride, 10); ++} ++ ++void idct8x8_64_add_12_sse2(const tran_low_t *in, uint8_t *out, int stride) { ++ vpx_highbd_idct8x8_64_add_sse2(in, out, stride, 12); ++} ++#endif // HAVE_SSE2 ++#endif // CONFIG_VP9_HIGHBITDEPTH ++ + class FwdTrans8x8TestBase { + public: + virtual ~FwdTrans8x8TestBase() {} + + protected: +- virtual void RunFwdTxfm(int16_t *in, int16_t *out, int stride) = 0; +- virtual void RunInvTxfm(int16_t *out, uint8_t *dst, int stride) = 0; ++ virtual void RunFwdTxfm(int16_t *in, tran_low_t *out, int stride) = 0; ++ virtual void RunInvTxfm(tran_low_t *out, uint8_t *dst, int stride) = 0; + + void RunSignBiasCheck() { + ACMRandom rnd(ACMRandom::DeterministicSeed()); +- DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, 64); +- DECLARE_ALIGNED_ARRAY(16, int16_t, test_output_block, 64); ++ DECLARE_ALIGNED(16, int16_t, test_input_block[64]); ++ DECLARE_ALIGNED(16, tran_low_t, test_output_block[64]); + int count_sign_block[64][2]; + const int count_test_block = 100000; + +@@ -67,8 +154,9 @@ + + for (int i = 0; i < count_test_block; ++i) { + // Initialize a test block with input range [-255, 255]. + for (int j = 0; j < 64; ++j) +- test_input_block[j] = rnd.Rand8() - rnd.Rand8(); +- REGISTER_STATE_CHECK( ++ test_input_block[j] = ((rnd.Rand16() >> (16 - bit_depth_)) & mask_) - ++ ((rnd.Rand16() >> (16 - bit_depth_)) & mask_); ++ ASM_REGISTER_STATE_CHECK( + RunFwdTxfm(test_input_block, test_output_block, pitch_)); + + for (int j = 0; j < 64; ++j) { +@@ -81,8 +169,8 @@ + + + for (int j = 0; j < 64; ++j) { + const int diff = abs(count_sign_block[j][0] - count_sign_block[j][1]); +- const int max_diff = 1125; +- EXPECT_LT(diff, max_diff) ++ const int max_diff = kSignBiasMaxDiff255; ++ EXPECT_LT(diff, max_diff << (bit_depth_ - 8)) + << ""Error: 8x8 FDCT/FHT has a sign bias > "" + << 1. * max_diff / count_test_block * 100 << ""%"" + << "" for input range [-255, 255] at index "" << j +@@ -94,10 +182,11 @@ + + memset(count_sign_block, 0, sizeof(count_sign_block)); + + for (int i = 0; i < count_test_block; ++i) { +- // Initialize a test block with input range [-15, 15]. ++ // Initialize a test block with input range [-mask_ / 16, mask_ / 16]. + for (int j = 0; j < 64; ++j) +- test_input_block[j] = (rnd.Rand8() >> 4) - (rnd.Rand8() >> 4); +- REGISTER_STATE_CHECK( ++ test_input_block[j] = ((rnd.Rand16() & mask_) >> 4) - ++ ((rnd.Rand16() & mask_) >> 4); ++ ASM_REGISTER_STATE_CHECK( + RunFwdTxfm(test_input_block, test_output_block, pitch_)); + + for (int j = 0; j < 64; ++j) { +@@ -110,9 +199,9 @@ + + + for (int j = 0; j < 64; ++j) { + const int diff = abs(count_sign_block[j][0] - count_sign_block[j][1]); +- const int max_diff = 10000; +- EXPECT_LT(diff, max_diff) +- << ""Error: 4x4 FDCT/FHT has a sign bias > "" ++ const int max_diff = kSignBiasMaxDiff15; ++ EXPECT_LT(diff, max_diff << (bit_depth_ - 8)) ++ << ""Error: 8x8 FDCT/FHT has a sign bias > "" + << 1. * max_diff / count_test_block * 100 << ""%"" + << "" for input range [-15, 15] at index "" << j + << "" count0: "" << count_sign_block[j][0] +@@ -126,20 +215,32 @@ + + int max_error = 0; + int total_error = 0; + const int count_test_block = 100000; +- DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, 64); +- DECLARE_ALIGNED_ARRAY(16, int16_t, test_temp_block, 64); +- DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, 64); +- DECLARE_ALIGNED_ARRAY(16, uint8_t, src, 64); ++ DECLARE_ALIGNED(16, int16_t, test_input_block[64]); ++ DECLARE_ALIGNED(16, tran_low_t, test_temp_block[64]); ++ DECLARE_ALIGNED(16, uint8_t, dst[64]); ++ DECLARE_ALIGNED(16, uint8_t, src[64]); ++#if CONFIG_VP9_HIGHBITDEPTH ++ DECLARE_ALIGNED(16, uint16_t, dst16[64]); ++ DECLARE_ALIGNED(16, uint16_t, src16[64]); ++#endif + + for (int i = 0; i < count_test_block; ++i) { +- // Initialize a test block with input range [-255, 255]. ++ // Initialize a test block with input range [-mask_, mask_]. + for (int j = 0; j < 64; ++j) { +- src[j] = rnd.Rand8(); +- dst[j] = rnd.Rand8(); +- test_input_block[j] = src[j] - dst[j]; ++ if (bit_depth_ == VPX_BITS_8) { ++ src[j] = rnd.Rand8(); ++ dst[j] = rnd.Rand8(); ++ test_input_block[j] = src[j] - dst[j]; ++#if CONFIG_VP9_HIGHBITDEPTH ++ } else { ++ src16[j] = rnd.Rand16() & mask_; ++ dst16[j] = rnd.Rand16() & mask_; ++ test_input_block[j] = src16[j] - dst16[j]; ++#endif ++ } + } + +- REGISTER_STATE_CHECK( ++ ASM_REGISTER_STATE_CHECK( + RunFwdTxfm(test_input_block, test_temp_block, pitch_)); + for (int j = 0; j < 64; ++j) { + if (test_temp_block[j] > 0) { +@@ -152,11 +253,23 @@ + + test_temp_block[j] *= 4; + } + } +- REGISTER_STATE_CHECK( +- RunInvTxfm(test_temp_block, dst, pitch_)); ++ if (bit_depth_ == VPX_BITS_8) { ++ ASM_REGISTER_STATE_CHECK( ++ RunInvTxfm(test_temp_block, dst, pitch_)); ++#if CONFIG_VP9_HIGHBITDEPTH ++ } else { ++ ASM_REGISTER_STATE_CHECK( ++ RunInvTxfm(test_temp_block, CONVERT_TO_BYTEPTR(dst16), pitch_)); ++#endif ++ } + + for (int j = 0; j < 64; ++j) { ++#if CONFIG_VP9_HIGHBITDEPTH ++ const int diff = ++ bit_depth_ == VPX_BITS_8 ? dst[j] - src[j] : dst16[j] - src16[j]; ++#else + const int diff = dst[j] - src[j]; ++#endif + const int error = diff * diff; + if (max_error < error) + max_error = error; +@@ -164,11 +277,11 @@ + + } + } + +- EXPECT_GE(1, max_error) ++ EXPECT_GE(1 << 2 * (bit_depth_ - 8), max_error) + << ""Error: 8x8 FDCT/IDCT or FHT/IHT has an individual"" + << "" roundtrip error > 1""; + +- EXPECT_GE(count_test_block/5, total_error) ++ EXPECT_GE((count_test_block << 2 * (bit_depth_ - 8))/5, total_error) + << ""Error: 8x8 FDCT/IDCT or FHT/IHT has average roundtrip "" + << ""error > 1/5 per block""; + } +@@ -177,51 +290,247 @@ + + ACMRandom rnd(ACMRandom::DeterministicSeed()); + int max_error = 0; + int total_error = 0; ++ int total_coeff_error = 0; + const int count_test_block = 100000; +- DECLARE_ALIGNED_ARRAY(16, int16_t, test_input_block, 64); +- DECLARE_ALIGNED_ARRAY(16, int16_t, test_temp_block, 64); +- DECLARE_ALIGNED_ARRAY(16, uint8_t, dst, 64); +- DECLARE_ALIGNED_ARRAY(16, uint8_t, src, 64); ++ DECLARE_ALIGNED(16, int16_t, test_input_block[64]); ++ DECLARE_ALIGNED(16, tran_low_t, test_temp_block[64]); ++ DECLARE_ALIGNED(16, tran_low_t, ref_temp_block[64]); ++ DECLARE_ALIGNED(16, uint8_t, dst[64]); ++ DECLARE_ALIGNED(16, uint8_t, src[64]); ++#if CONFIG_VP9_HIGHBITDEPTH ++ DECLARE_ALIGNED(16, uint16_t, dst16[64]); ++ DECLARE_ALIGNED(16, uint16_t, src16[64]); ++#endif + + for (int i = 0; i < count_test_block; ++i) { +- // Initialize a test block with input range [-255, 255]. ++ // Initialize a test block with input range [-mask_, mask_]. + for (int j = 0; j < 64; ++j) { +- src[j] = rnd.Rand8() % 2 ? 255 : 0; +- dst[j] = src[j] > 0 ? 0 : 255; +- test_input_block[j] = src[j] - dst[j]; ++ if (bit_depth_ == VPX_BITS_8) { ++ if (i == 0) { ++ src[j] = 255; ++ dst[j] = 0; ++ } else if (i == 1) { ++ src[j] = 0; ++ dst[j] = 255; ++ } else { ++ src[j] = rnd.Rand8() % 2 ? 255 : 0; ++ dst[j] = rnd.Rand8() % 2 ? 255 : 0; ++ } ++ test_input_block[j] = src[j] - dst[j]; ++#if CONFIG_VP9_HIGHBITDEPTH ++ } else { ++ if (i == 0) { ++ src16[j] = mask_; ++ dst16[j] = 0; ++ } else if (i == 1) { ++ src16[j] = 0; ++ dst16[j] = mask_; ++ } else { ++ src16[j] = rnd.Rand8() % 2 ? mask_ : 0; ++ dst16[j] = rnd.Rand8() % 2 ? mask_ : 0; ++ } ++ test_input_block[j] = src16[j] - dst16[j]; ++#endif ++ } + } + +- REGISTER_STATE_CHECK( ++ ASM_REGISTER_STATE_CHECK( + RunFwdTxfm(test_input_block, test_temp_block, pitch_)); +- REGISTER_STATE_CHECK( +- RunInvTxfm(test_temp_block, dst, pitch_)); ++ ASM_REGISTER_STATE_CHECK( ++ fwd_txfm_ref(test_input_block, ref_temp_block, pitch_, tx_type_)); ++ if (bit_depth_ == VPX_BITS_8) { ++ ASM_REGISTER_STATE_CHECK( ++ RunInvTxfm(test_temp_block, dst, pitch_)); ++#if CONFIG_VP9_HIGHBITDEPTH ++ } else { ++ ASM_REGISTER_STATE_CHECK( ++ RunInvTxfm(test_temp_block, CONVERT_TO_BYTEPTR(dst16), pitch_)); ++#endif ++ } + + for (int j = 0; j < 64; ++j) { ++#if CONFIG_VP9_HIGHBITDEPTH ++ const int diff = ++ bit_depth_ == VPX_BITS_8 ? dst[j] - src[j] : dst16[j] - src16[j]; ++#else + const int diff = dst[j] - src[j]; ++#endif + const int error = diff * diff; + if (max_error < error) + max_error = error; + total_error += error; ++ ++ const int coeff_diff = test_temp_block[j] - ref_temp_block[j]; ++ total_coeff_error += abs(coeff_diff); + } + +- EXPECT_GE(1, max_error) ++ EXPECT_GE(1 << 2 * (bit_depth_ - 8), max_error) + << ""Error: Extremal 8x8 FDCT/IDCT or FHT/IHT has"" + << ""an individual roundtrip error > 1""; + +- EXPECT_GE(count_test_block/5, total_error) ++ EXPECT_GE((count_test_block << 2 * (bit_depth_ - 8))/5, total_error) + << ""Error: Extremal 8x8 FDCT/IDCT or FHT/IHT has average"" + << "" roundtrip error > 1/5 per block""; ++ ++ EXPECT_EQ(0, total_coeff_error) ++ << ""Error: Extremal 8x8 FDCT/FHT has"" ++ << ""overflow issues in the intermediate steps > 1""; + } + } + ++ void RunInvAccuracyCheck() { ++ ACMRandom rnd(ACMRandom::DeterministicSeed()); ++ const int count_test_block = 1000; ++ DECLARE_ALIGNED(16, int16_t, in[kNumCoeffs]); ++ DECLARE_ALIGNED(16, tran_low_t, coeff[kNumCoeffs]); ++ DECLARE_ALIGNED(16, uint8_t, dst[kNumCoeffs]); ++ DECLARE_ALIGNED(16, uint8_t, src[kNumCoeffs]); ++#if CONFIG_VP9_HIGHBITDEPTH ++ DECLARE_ALIGNED(16, uint16_t, src16[kNumCoeffs]); ++ DECLARE_ALIGNED(16, uint16_t, dst16[kNumCoeffs]); ++#endif ++ ++ for (int i = 0; i < count_test_block; ++i) { ++ double out_r[kNumCoeffs]; ++ ++ // Initialize a test block with input range [-255, 255]. ++ for (int j = 0; j < kNumCoeffs; ++j) { ++ if (bit_depth_ == VPX_BITS_8) { ++ src[j] = rnd.Rand8() % 2 ? 255 : 0; ++ dst[j] = src[j] > 0 ? 0 : 255; ++ in[j] = src[j] - dst[j]; ++#if CONFIG_VP9_HIGHBITDEPTH ++ } else { ++ src16[j] = rnd.Rand8() % 2 ? mask_ : 0; ++ dst16[j] = src16[j] > 0 ? 0 : mask_; ++ in[j] = src16[j] - dst16[j]; ++#endif ++ } ++ } ++ ++ reference_8x8_dct_2d(in, out_r); ++ for (int j = 0; j < kNumCoeffs; ++j) ++ coeff[j] = static_cast(round(out_r[j])); ++ ++ if (bit_depth_ == VPX_BITS_8) { ++ ASM_REGISTER_STATE_CHECK(RunInvTxfm(coeff, dst, pitch_)); ++#if CONFIG_VP9_HIGHBITDEPTH ++ } else { ++ ASM_REGISTER_STATE_CHECK(RunInvTxfm(coeff, CONVERT_TO_BYTEPTR(dst16), ++ pitch_)); ++#endif ++ } ++ ++ for (int j = 0; j < kNumCoeffs; ++j) { ++#if CONFIG_VP9_HIGHBITDEPTH ++ const uint32_t diff = ++ bit_depth_ == VPX_BITS_8 ? dst[j] - src[j] : dst16[j] - src16[j]; ++#else ++ const uint32_t diff = dst[j] - src[j]; ++#endif ++ const uint32_t error = diff * diff; ++ EXPECT_GE(1u << 2 * (bit_depth_ - 8), error) ++ << ""Error: 8x8 IDCT has error "" << error ++ << "" at index "" << j; ++ } ++ } ++ } ++ ++ void RunFwdAccuracyCheck() { ++ ACMRandom rnd(ACMRandom::DeterministicSeed()); ++ const int count_test_block = 1000; ++ DECLARE_ALIGNED(16, int16_t, in[kNumCoeffs]); ++ DECLARE_ALIGNED(16, tran_low_t, coeff_r[kNumCoeffs]); ++ DECLARE_ALIGNED(16, tran_low_t, coeff[kNumCoeffs]); ++ ++ for (int i = 0; i < count_test_block; ++i) { ++ double out_r[kNumCoeffs]; ++ ++ // Initialize a test block with input range [-mask_, mask_]. ++ for (int j = 0; j < kNumCoeffs; ++j) ++ in[j] = rnd.Rand8() % 2 == 0 ? mask_ : -mask_; ++ ++ RunFwdTxfm(in, coeff, pitch_); ++ reference_8x8_dct_2d(in, out_r); ++ for (int j = 0; j < kNumCoeffs; ++j) ++ coeff_r[j] = static_cast(round(out_r[j])); ++ ++ for (int j = 0; j < kNumCoeffs; ++j) { ++ const uint32_t diff = coeff[j] - coeff_r[j]; ++ const uint32_t error = diff * diff; ++ EXPECT_GE(9u << 2 * (bit_depth_ - 8), error) ++ << ""Error: 8x8 DCT has error "" << error ++ << "" at index "" << j; ++ } ++ } ++ } ++ ++void CompareInvReference(IdctFunc ref_txfm, int thresh) { ++ ACMRandom rnd(ACMRandom::DeterministicSeed()); ++ const int count_test_block = 10000; ++ const int eob = 12; ++ DECLARE_ALIGNED(16, tran_low_t, coeff[kNumCoeffs]); ++ DECLARE_ALIGNED(16, uint8_t, dst[kNumCoeffs]); ++ DECLARE_ALIGNED(16, uint8_t, ref[kNumCoeffs]); ++#if CONFIG_VP9_HIGHBITDEPTH ++ DECLARE_ALIGNED(16, uint16_t, dst16[kNumCoeffs]); ++ DECLARE_ALIGNED(16, uint16_t, ref16[kNumCoeffs]); ++#endif ++ const int16_t *scan = vp9_default_scan_orders[TX_8X8].scan; ++ ++ for (int i = 0; i < count_test_block; ++i) { ++ for (int j = 0; j < kNumCoeffs; ++j) { ++ if (j < eob) { ++ // Random values less than the threshold, either positive or negative ++ coeff[scan[j]] = rnd(thresh) * (1-2*(i%2)); ++ } else { ++ coeff[scan[j]] = 0; ++ } ++ if (bit_depth_ == VPX_BITS_8) { ++ dst[j] = 0; ++ ref[j] = 0; ++#if CONFIG_VP9_HIGHBITDEPTH ++ } else { ++ dst16[j] = 0; ++ ref16[j] = 0; ++#endif ++ } ++ } ++ if (bit_depth_ == VPX_BITS_8) { ++ ref_txfm(coeff, ref, pitch_); ++ ASM_REGISTER_STATE_CHECK(RunInvTxfm(coeff, dst, pitch_)); ++#if CONFIG_VP9_HIGHBITDEPTH ++ } else { ++ ref_txfm(coeff, CONVERT_TO_BYTEPTR(ref16), pitch_); ++ ASM_REGISTER_STATE_CHECK(RunInvTxfm(coeff, CONVERT_TO_BYTEPTR(dst16), ++ pitch_)); ++#endif ++ } ++ ++ for (int j = 0; j < kNumCoeffs; ++j) { ++#if CONFIG_VP9_HIGHBITDEPTH ++ const uint32_t diff = ++ bit_depth_ == VPX_BITS_8 ? dst[j] - ref[j] : dst16[j] - ref16[j]; ++#else ++ const uint32_t diff = dst[j] - ref[j]; ++#endif ++ const uint32_t error = diff * diff; ++ EXPECT_EQ(0u, error) ++ << ""Error: 8x8 IDCT has error "" << error ++ << "" at index "" << j; ++ } ++ } ++ } + int pitch_; + int tx_type_; +- fht_t fwd_txfm_ref; ++ FhtFunc fwd_txfm_ref; ++ vpx_bit_depth_t bit_depth_; ++ int mask_; + }; + + class FwdTrans8x8DCT + : public FwdTrans8x8TestBase, +- public ::testing::TestWithParam { ++ public ::testing::TestWithParam { + public: + virtual ~FwdTrans8x8DCT() {} + +@@ -231,20 +540,22 @@ + + tx_type_ = GET_PARAM(2); + pitch_ = 8; + fwd_txfm_ref = fdct8x8_ref; ++ bit_depth_ = GET_PARAM(3); ++ mask_ = (1 << bit_depth_) - 1; + } + + virtual void TearDown() { libvpx_test::ClearSystemState(); } + + protected: +- void RunFwdTxfm(int16_t *in, int16_t *out, int stride) { ++ void RunFwdTxfm(int16_t *in, tran_low_t *out, int stride) { + fwd_txfm_(in, out, stride); + } +- void RunInvTxfm(int16_t *out, uint8_t *dst, int stride) { ++ void RunInvTxfm(tran_low_t *out, uint8_t *dst, int stride) { + inv_txfm_(out, dst, stride); + } + +- fdct_t fwd_txfm_; +- idct_t inv_txfm_; ++ FdctFunc fwd_txfm_; ++ IdctFunc inv_txfm_; + }; + + TEST_P(FwdTrans8x8DCT, SignBiasCheck) { +@@ -259,9 +570,17 @@ + + RunExtremalCheck(); + } + ++TEST_P(FwdTrans8x8DCT, FwdAccuracyCheck) { ++ RunFwdAccuracyCheck(); ++} ++ ++TEST_P(FwdTrans8x8DCT, InvAccuracyCheck) { ++ RunInvAccuracyCheck(); ++} ++ + class FwdTrans8x8HT + : public FwdTrans8x8TestBase, +- public ::testing::TestWithParam { ++ public ::testing::TestWithParam { + public: + virtual ~FwdTrans8x8HT() {} + +@@ -271,20 +590,22 @@ + + tx_type_ = GET_PARAM(2); + pitch_ = 8; + fwd_txfm_ref = fht8x8_ref; ++ bit_depth_ = GET_PARAM(3); ++ mask_ = (1 << bit_depth_) - 1; + } + + virtual void TearDown() { libvpx_test::ClearSystemState(); } + + protected: +- void RunFwdTxfm(int16_t *in, int16_t *out, int stride) { ++ void RunFwdTxfm(int16_t *in, tran_low_t *out, int stride) { + fwd_txfm_(in, out, stride, tx_type_); + } +- void RunInvTxfm(int16_t *out, uint8_t *dst, int stride) { ++ void RunInvTxfm(tran_low_t *out, uint8_t *dst, int stride) { + inv_txfm_(out, dst, stride, tx_type_); + } + +- fht_t fwd_txfm_; +- iht_t inv_txfm_; ++ FhtFunc fwd_txfm_; ++ IhtFunc inv_txfm_; + }; + + TEST_P(FwdTrans8x8HT, SignBiasCheck) { +@@ -299,45 +620,170 @@ + + RunExtremalCheck(); + } + ++class InvTrans8x8DCT ++ : public FwdTrans8x8TestBase, ++ public ::testing::TestWithParam { ++ public: ++ virtual ~InvTrans8x8DCT() {} ++ ++ virtual void SetUp() { ++ ref_txfm_ = GET_PARAM(0); ++ inv_txfm_ = GET_PARAM(1); ++ thresh_ = GET_PARAM(2); ++ pitch_ = 8; ++ bit_depth_ = GET_PARAM(3); ++ mask_ = (1 << bit_depth_) - 1; ++ } ++ ++ virtual void TearDown() { libvpx_test::ClearSystemState(); } ++ ++ protected: ++ void RunInvTxfm(tran_low_t *out, uint8_t *dst, int stride) { ++ inv_txfm_(out, dst, stride); ++ } ++ void RunFwdTxfm(int16_t *out, tran_low_t *dst, int stride) {} ++ ++ IdctFunc ref_txfm_; ++ IdctFunc inv_txfm_; ++ int thresh_; ++}; ++ ++TEST_P(InvTrans8x8DCT, CompareReference) { ++ CompareInvReference(ref_txfm_, thresh_); ++} ++ + using std::tr1::make_tuple; + ++#if CONFIG_VP9_HIGHBITDEPTH + INSTANTIATE_TEST_CASE_P( + C, FwdTrans8x8DCT, + ::testing::Values( +- make_tuple(&vp9_fdct8x8_c, &vp9_idct8x8_64_add_c, 0))); ++ make_tuple(&vpx_fdct8x8_c, &vpx_idct8x8_64_add_c, 0, VPX_BITS_8), ++ make_tuple(&vpx_highbd_fdct8x8_c, &idct8x8_10, 0, VPX_BITS_10), ++ make_tuple(&vpx_highbd_fdct8x8_c, &idct8x8_12, 0, VPX_BITS_12))); ++#else ++INSTANTIATE_TEST_CASE_P( ++ C, FwdTrans8x8DCT, ++ ::testing::Values( ++ make_tuple(&vpx_fdct8x8_c, &vpx_idct8x8_64_add_c, 0, VPX_BITS_8))); ++#endif // CONFIG_VP9_HIGHBITDEPTH ++ ++#if CONFIG_VP9_HIGHBITDEPTH + INSTANTIATE_TEST_CASE_P( + C, FwdTrans8x8HT, + ::testing::Values( +- make_tuple(&vp9_fht8x8_c, &vp9_iht8x8_64_add_c, 0), +- make_tuple(&vp9_fht8x8_c, &vp9_iht8x8_64_add_c, 1), +- make_tuple(&vp9_fht8x8_c, &vp9_iht8x8_64_add_c, 2), +- make_tuple(&vp9_fht8x8_c, &vp9_iht8x8_64_add_c, 3))); ++ make_tuple(&vp9_fht8x8_c, &vp9_iht8x8_64_add_c, 0, VPX_BITS_8), ++ make_tuple(&vp9_highbd_fht8x8_c, &iht8x8_10, 0, VPX_BITS_10), ++ make_tuple(&vp9_highbd_fht8x8_c, &iht8x8_10, 1, VPX_BITS_10), ++ make_tuple(&vp9_highbd_fht8x8_c, &iht8x8_10, 2, VPX_BITS_10), ++ make_tuple(&vp9_highbd_fht8x8_c, &iht8x8_10, 3, VPX_BITS_10), ++ make_tuple(&vp9_highbd_fht8x8_c, &iht8x8_12, 0, VPX_BITS_12), ++ make_tuple(&vp9_highbd_fht8x8_c, &iht8x8_12, 1, VPX_BITS_12), ++ make_tuple(&vp9_highbd_fht8x8_c, &iht8x8_12, 2, VPX_BITS_12), ++ make_tuple(&vp9_highbd_fht8x8_c, &iht8x8_12, 3, VPX_BITS_12), ++ make_tuple(&vp9_fht8x8_c, &vp9_iht8x8_64_add_c, 1, VPX_BITS_8), ++ make_tuple(&vp9_fht8x8_c, &vp9_iht8x8_64_add_c, 2, VPX_BITS_8), ++ make_tuple(&vp9_fht8x8_c, &vp9_iht8x8_64_add_c, 3, VPX_BITS_8))); ++#else ++INSTANTIATE_TEST_CASE_P( ++ C, FwdTrans8x8HT, ++ ::testing::Values( ++ make_tuple(&vp9_fht8x8_c, &vp9_iht8x8_64_add_c, 0, VPX_BITS_8), ++ make_tuple(&vp9_fht8x8_c, &vp9_iht8x8_64_add_c, 1, VPX_BITS_8), ++ make_tuple(&vp9_fht8x8_c, &vp9_iht8x8_64_add_c, 2, VPX_BITS_8), ++ make_tuple(&vp9_fht8x8_c, &vp9_iht8x8_64_add_c, 3, VPX_BITS_8))); ++#endif // CONFIG_VP9_HIGHBITDEPTH + +-#if HAVE_NEON ++#if HAVE_NEON_ASM && !CONFIG_VP9_HIGHBITDEPTH && !CONFIG_EMULATE_HARDWARE + INSTANTIATE_TEST_CASE_P( + NEON, FwdTrans8x8DCT, + ::testing::Values( +- make_tuple(&vp9_fdct8x8_c, &vp9_idct8x8_64_add_neon, 0))); +-INSTANTIATE_TEST_CASE_P( +- DISABLED_NEON, FwdTrans8x8HT, +- ::testing::Values( +- make_tuple(&vp9_fht8x8_c, &vp9_iht8x8_64_add_neon, 0), +- make_tuple(&vp9_fht8x8_c, &vp9_iht8x8_64_add_neon, 1), +- make_tuple(&vp9_fht8x8_c, &vp9_iht8x8_64_add_neon, 2), +- make_tuple(&vp9_fht8x8_c, &vp9_iht8x8_64_add_neon, 3))); +-#endif ++ make_tuple(&vpx_fdct8x8_neon, &vpx_idct8x8_64_add_neon, 0, ++ VPX_BITS_8))); ++#endif // HAVE_NEON_ASM && !CONFIG_VP9_HIGHBITDEPTH && !CONFIG_EMULATE_HARDWARE + +-#if HAVE_SSE2 ++#if HAVE_NEON && !CONFIG_VP9_HIGHBITDEPTH && !CONFIG_EMULATE_HARDWARE ++INSTANTIATE_TEST_CASE_P( ++ NEON, FwdTrans8x8HT, ++ ::testing::Values( ++ make_tuple(&vp9_fht8x8_c, &vp9_iht8x8_64_add_neon, 0, VPX_BITS_8), ++ make_tuple(&vp9_fht8x8_c, &vp9_iht8x8_64_add_neon, 1, VPX_BITS_8), ++ make_tuple(&vp9_fht8x8_c, &vp9_iht8x8_64_add_neon, 2, VPX_BITS_8), ++ make_tuple(&vp9_fht8x8_c, &vp9_iht8x8_64_add_neon, 3, VPX_BITS_8))); ++#endif // HAVE_NEON && !CONFIG_VP9_HIGHBITDEPTH && !CONFIG_EMULATE_HARDWARE ++ ++#if HAVE_SSE2 && !CONFIG_VP9_HIGHBITDEPTH && !CONFIG_EMULATE_HARDWARE + INSTANTIATE_TEST_CASE_P( + SSE2, FwdTrans8x8DCT, + ::testing::Values( +- make_tuple(&vp9_fdct8x8_sse2, &vp9_idct8x8_64_add_sse2, 0))); ++ make_tuple(&vpx_fdct8x8_sse2, &vpx_idct8x8_64_add_sse2, 0, ++ VPX_BITS_8))); + INSTANTIATE_TEST_CASE_P( + SSE2, FwdTrans8x8HT, + ::testing::Values( +- make_tuple(&vp9_fht8x8_sse2, &vp9_iht8x8_64_add_sse2, 0), +- make_tuple(&vp9_fht8x8_sse2, &vp9_iht8x8_64_add_sse2, 1), +- make_tuple(&vp9_fht8x8_sse2, &vp9_iht8x8_64_add_sse2, 2), +- make_tuple(&vp9_fht8x8_sse2, &vp9_iht8x8_64_add_sse2, 3))); ++ make_tuple(&vp9_fht8x8_sse2, &vp9_iht8x8_64_add_sse2, 0, VPX_BITS_8), ++ make_tuple(&vp9_fht8x8_sse2, &vp9_iht8x8_64_add_sse2, 1, VPX_BITS_8), ++ make_tuple(&vp9_fht8x8_sse2, &vp9_iht8x8_64_add_sse2, 2, VPX_BITS_8), ++ make_tuple(&vp9_fht8x8_sse2, &vp9_iht8x8_64_add_sse2, 3, VPX_BITS_8))); ++#endif // HAVE_SSE2 && !CONFIG_VP9_HIGHBITDEPTH && !CONFIG_EMULATE_HARDWARE ++ ++#if HAVE_SSE2 && CONFIG_VP9_HIGHBITDEPTH && !CONFIG_EMULATE_HARDWARE ++INSTANTIATE_TEST_CASE_P( ++ SSE2, FwdTrans8x8DCT, ++ ::testing::Values( ++ make_tuple(&vpx_fdct8x8_sse2, &vpx_idct8x8_64_add_c, 0, VPX_BITS_8), ++ make_tuple(&vpx_highbd_fdct8x8_c, ++ &idct8x8_64_add_10_sse2, 12, VPX_BITS_10), ++ make_tuple(&vpx_highbd_fdct8x8_sse2, ++ &idct8x8_64_add_10_sse2, 12, VPX_BITS_10), ++ make_tuple(&vpx_highbd_fdct8x8_c, ++ &idct8x8_64_add_12_sse2, 12, VPX_BITS_12), ++ make_tuple(&vpx_highbd_fdct8x8_sse2, ++ &idct8x8_64_add_12_sse2, 12, VPX_BITS_12))); ++ ++INSTANTIATE_TEST_CASE_P( ++ SSE2, FwdTrans8x8HT, ++ ::testing::Values( ++ make_tuple(&vp9_fht8x8_sse2, &vp9_iht8x8_64_add_c, 0, VPX_BITS_8), ++ make_tuple(&vp9_fht8x8_sse2, &vp9_iht8x8_64_add_c, 1, VPX_BITS_8), ++ make_tuple(&vp9_fht8x8_sse2, &vp9_iht8x8_64_add_c, 2, VPX_BITS_8), ++ make_tuple(&vp9_fht8x8_sse2, &vp9_iht8x8_64_add_c, 3, VPX_BITS_8))); ++ ++// Optimizations take effect at a threshold of 6201, so we use a value close to ++// that to test both branches. ++INSTANTIATE_TEST_CASE_P( ++ SSE2, InvTrans8x8DCT, ++ ::testing::Values( ++ make_tuple(&idct8x8_10_add_10_c, ++ &idct8x8_10_add_10_sse2, 6225, VPX_BITS_10), ++ make_tuple(&idct8x8_10, ++ &idct8x8_64_add_10_sse2, 6225, VPX_BITS_10), ++ make_tuple(&idct8x8_10_add_12_c, ++ &idct8x8_10_add_12_sse2, 6225, VPX_BITS_12), ++ make_tuple(&idct8x8_12, ++ &idct8x8_64_add_12_sse2, 6225, VPX_BITS_12))); ++#endif // HAVE_SSE2 && CONFIG_VP9_HIGHBITDEPTH && !CONFIG_EMULATE_HARDWARE ++ ++#if HAVE_SSSE3 && CONFIG_USE_X86INC && ARCH_X86_64 && \ ++ !CONFIG_VP9_HIGHBITDEPTH && !CONFIG_EMULATE_HARDWARE ++INSTANTIATE_TEST_CASE_P( ++ SSSE3, FwdTrans8x8DCT, ++ ::testing::Values( ++ make_tuple(&vpx_fdct8x8_ssse3, &vpx_idct8x8_64_add_ssse3, 0, ++ VPX_BITS_8))); + #endif ++ ++#if HAVE_MSA && !CONFIG_VP9_HIGHBITDEPTH && !CONFIG_EMULATE_HARDWARE ++INSTANTIATE_TEST_CASE_P( ++ MSA, FwdTrans8x8DCT, ++ ::testing::Values( ++ make_tuple(&vpx_fdct8x8_msa, &vpx_idct8x8_64_add_msa, 0, VPX_BITS_8))); ++INSTANTIATE_TEST_CASE_P( ++ MSA, FwdTrans8x8HT, ++ ::testing::Values( ++ make_tuple(&vp9_fht8x8_msa, &vp9_iht8x8_64_add_msa, 0, VPX_BITS_8), ++ make_tuple(&vp9_fht8x8_msa, &vp9_iht8x8_64_add_msa, 1, VPX_BITS_8), ++ make_tuple(&vp9_fht8x8_msa, &vp9_iht8x8_64_add_msa, 2, VPX_BITS_8), ++ make_tuple(&vp9_fht8x8_msa, &vp9_iht8x8_64_add_msa, 3, VPX_BITS_8))); ++#endif // HAVE_MSA && !CONFIG_VP9_HIGHBITDEPTH && !CONFIG_EMULATE_HARDWARE + } // namespace +",727,1058,2048 +13578,"void BlockPainter::PaintObject(const PaintInfo& paint_info, + const LayoutPoint& paint_offset) { + if (layout_block_.IsTruncated()) + return; + + const PaintPhase paint_phase = paint_info.phase; + + if (ShouldPaintSelfBlockBackground(paint_phase)) { + if (layout_block_.Style()->Visibility() == EVisibility::kVisible && + layout_block_.HasBoxDecorationBackground()) + layout_block_.PaintBoxDecorationBackground(paint_info, paint_offset); + if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) + PaintScrollHitTestDisplayItem(paint_info); + if (paint_phase == PaintPhase::kSelfBlockBackgroundOnly) + return; + } + + if (paint_phase == PaintPhase::kMask && + layout_block_.Style()->Visibility() == EVisibility::kVisible) { + layout_block_.PaintMask(paint_info, paint_offset); + return; + } + + if (paint_phase == PaintPhase::kClippingMask && + layout_block_.Style()->Visibility() == EVisibility::kVisible) { + DCHECK(!RuntimeEnabledFeatures::SlimmingPaintV175Enabled()); + BoxPainter(layout_block_).PaintClippingMask(paint_info, paint_offset); + return; + } + + if (paint_phase == PaintPhase::kForeground && paint_info.IsPrinting()) + ObjectPainter(layout_block_) + .AddPDFURLRectIfNeeded(paint_info, paint_offset); + + if (paint_phase != PaintPhase::kSelfOutlineOnly) { + base::Optional scoped_scroll_property; + base::Optional scroll_recorder; + base::Optional scrolled_paint_info; + if (RuntimeEnabledFeatures::SlimmingPaintV175Enabled()) { + if (const auto* fragment = paint_info.FragmentToPaint(layout_block_)) { + const auto* object_properties = fragment->PaintProperties(); + auto* scroll_translation = object_properties + ? object_properties->ScrollTranslation() + : nullptr; + if (scroll_translation) { + scoped_scroll_property.emplace( + paint_info.context.GetPaintController(), scroll_translation, + layout_block_, DisplayItem::PaintPhaseToScrollType(paint_phase)); + scrolled_paint_info.emplace(paint_info); + if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) { + scrolled_paint_info->UpdateCullRectForScrollingContents( + EnclosingIntRect(layout_block_.OverflowClipRect(paint_offset)), + scroll_translation->Matrix().ToAffineTransform()); + } else { + scrolled_paint_info->UpdateCullRect( + scroll_translation->Matrix().ToAffineTransform()); + } + } + } + } else if (layout_block_.HasOverflowClip()) { + IntSize scroll_offset = layout_block_.ScrolledContentOffset(); + if (layout_block_.Layer()->ScrollsOverflow() || !scroll_offset.IsZero()) { + scroll_recorder.emplace(paint_info.context, layout_block_, paint_phase, + scroll_offset); + scrolled_paint_info.emplace(paint_info); + AffineTransform transform; + transform.Translate(-scroll_offset.Width(), -scroll_offset.Height()); + scrolled_paint_info->UpdateCullRect(transform); + } + } + + const PaintInfo& contents_paint_info = + scrolled_paint_info ? *scrolled_paint_info : paint_info; + + if (layout_block_.IsLayoutBlockFlow()) { + BlockFlowPainter block_flow_painter(ToLayoutBlockFlow(layout_block_)); + block_flow_painter.PaintContents(contents_paint_info, paint_offset); + if (paint_phase == PaintPhase::kFloat || + paint_phase == PaintPhase::kSelection || + paint_phase == PaintPhase::kTextClip) + block_flow_painter.PaintFloats(contents_paint_info, paint_offset); + } else { + PaintContents(contents_paint_info, paint_offset); + } + } + + if (ShouldPaintSelfOutline(paint_phase)) + ObjectPainter(layout_block_).PaintOutline(paint_info, paint_offset); + + if (paint_phase == PaintPhase::kForeground && + layout_block_.ShouldPaintCarets()) + PaintCarets(paint_info, paint_offset); +} +",0,"void BlockPainter::PaintObject(const PaintInfo& paint_info, + const LayoutPoint& paint_offset) { + if (layout_block_.IsTruncated()) + return; + + const PaintPhase paint_phase = paint_info.phase; + + if (ShouldPaintSelfBlockBackground(paint_phase)) { + if (layout_block_.Style()->Visibility() == EVisibility::kVisible && + layout_block_.HasBoxDecorationBackground()) + layout_block_.PaintBoxDecorationBackground(paint_info, paint_offset); + if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) + PaintScrollHitTestDisplayItem(paint_info); + if (paint_phase == PaintPhase::kSelfBlockBackgroundOnly) + return; + } + + if (paint_phase == PaintPhase::kMask && + layout_block_.Style()->Visibility() == EVisibility::kVisible) { + layout_block_.PaintMask(paint_info, paint_offset); + return; + } + + if (paint_phase == PaintPhase::kClippingMask && + layout_block_.Style()->Visibility() == EVisibility::kVisible) { + DCHECK(!RuntimeEnabledFeatures::SlimmingPaintV175Enabled()); + BoxPainter(layout_block_).PaintClippingMask(paint_info, paint_offset); + return; + } + + if (paint_phase == PaintPhase::kForeground && paint_info.IsPrinting()) + ObjectPainter(layout_block_) + .AddPDFURLRectIfNeeded(paint_info, paint_offset); + + if (paint_phase != PaintPhase::kSelfOutlineOnly) { + base::Optional scoped_scroll_property; + base::Optional scroll_recorder; + base::Optional scrolled_paint_info; + if (RuntimeEnabledFeatures::SlimmingPaintV175Enabled()) { + if (const auto* fragment = paint_info.FragmentToPaint(layout_block_)) { + const auto* object_properties = fragment->PaintProperties(); + auto* scroll_translation = object_properties + ? object_properties->ScrollTranslation() + : nullptr; + if (scroll_translation) { + scoped_scroll_property.emplace( + paint_info.context.GetPaintController(), scroll_translation, + layout_block_, DisplayItem::PaintPhaseToScrollType(paint_phase)); + scrolled_paint_info.emplace(paint_info); + if (RuntimeEnabledFeatures::SlimmingPaintV2Enabled()) { + scrolled_paint_info->UpdateCullRectForScrollingContents( + EnclosingIntRect(layout_block_.OverflowClipRect(paint_offset)), + scroll_translation->Matrix().ToAffineTransform()); + } else { + scrolled_paint_info->UpdateCullRect( + scroll_translation->Matrix().ToAffineTransform()); + } + } + } + } else if (layout_block_.HasOverflowClip()) { + IntSize scroll_offset = layout_block_.ScrolledContentOffset(); + if (layout_block_.Layer()->ScrollsOverflow() || !scroll_offset.IsZero()) { + scroll_recorder.emplace(paint_info.context, layout_block_, paint_phase, + scroll_offset); + scrolled_paint_info.emplace(paint_info); + AffineTransform transform; + transform.Translate(-scroll_offset.Width(), -scroll_offset.Height()); + scrolled_paint_info->UpdateCullRect(transform); + } + } + + const PaintInfo& contents_paint_info = + scrolled_paint_info ? *scrolled_paint_info : paint_info; + + if (layout_block_.IsLayoutBlockFlow()) { + BlockFlowPainter block_flow_painter(ToLayoutBlockFlow(layout_block_)); + block_flow_painter.PaintContents(contents_paint_info, paint_offset); + if (paint_phase == PaintPhase::kFloat || + paint_phase == PaintPhase::kSelection || + paint_phase == PaintPhase::kTextClip) + block_flow_painter.PaintFloats(contents_paint_info, paint_offset); + } else { + PaintContents(contents_paint_info, paint_offset); + } + } + + if (ShouldPaintSelfOutline(paint_phase)) + ObjectPainter(layout_block_).PaintOutline(paint_info, paint_offset); + + if (paint_phase == PaintPhase::kForeground && + layout_block_.ShouldPaintCarets()) + PaintCarets(paint_info, paint_offset); +} +","@@ -196,7 +196,7 @@ void BlockPainter::PaintScrollHitTestDisplayItem(const PaintInfo& paint_info) { + DisplayItem::kScrollHitTest); + ScrollHitTestDisplayItem::Record(paint_info.context, layout_block_, + DisplayItem::kScrollHitTest, +- properties->ScrollTranslation()); ++ *properties->ScrollTranslation()); + } + } + ",850,1181,2048 +17813," t42_parse_charstrings( T42_Face face, + T42_Loader loader ) + { + T42_Parser parser = &loader->parser; + PS_Table code_table = &loader->charstrings; + PS_Table name_table = &loader->glyph_names; + PS_Table swap_table = &loader->swap_table; + FT_Memory memory = parser->root.memory; + FT_Error error; + + PSAux_Service psaux = (PSAux_Service)face->psaux; + + FT_Byte* cur; + FT_Byte* limit = parser->root.limit; + FT_UInt n; + FT_UInt notdef_index = 0; + FT_Byte notdef_found = 0; + + + T1_Skip_Spaces( parser ); + + if ( parser->root.cursor >= limit ) + { + FT_ERROR(( ""t42_parse_charstrings: out of bounds\n"" )); + error = FT_THROW( Invalid_File_Format ); + goto Fail; + } + + if ( ft_isdigit( *parser->root.cursor ) ) + { + loader->num_glyphs = (FT_UInt)T1_ToInt( parser ); + if ( parser->root.error ) + return; + } + else if ( *parser->root.cursor == '<' ) + { + /* We have `<< ... >>'. Count the number of `/' in the dictionary */ + /* to get its size. */ + FT_UInt count = 0; + + + T1_Skip_PS_Token( parser ); + if ( parser->root.error ) + return; + T1_Skip_Spaces( parser ); + cur = parser->root.cursor; + + while ( parser->root.cursor < limit ) + { + if ( *parser->root.cursor == '/' ) + count++; + else if ( *parser->root.cursor == '>' ) + { + loader->num_glyphs = count; + parser->root.cursor = cur; /* rewind */ + break; + } + T1_Skip_PS_Token( parser ); + if ( parser->root.error ) + return; + T1_Skip_Spaces( parser ); + } + } + else + { + FT_ERROR(( ""t42_parse_charstrings: invalid token\n"" )); + error = FT_THROW( Invalid_File_Format ); + goto Fail; + } + + if ( parser->root.cursor >= limit ) + { + FT_ERROR(( ""t42_parse_charstrings: out of bounds\n"" )); + error = FT_THROW( Invalid_File_Format ); + goto Fail; + } + + /* initialize tables */ + + error = psaux->ps_table_funcs->init( code_table, + loader->num_glyphs, + memory ); + if ( error ) + goto Fail; + + error = psaux->ps_table_funcs->init( name_table, + loader->num_glyphs, + memory ); + if ( error ) + goto Fail; + + /* Initialize table for swapping index notdef_index and */ + /* index 0 names and codes (if necessary). */ + + error = psaux->ps_table_funcs->init( swap_table, 4, memory ); + if ( error ) + goto Fail; + + n = 0; + + for (;;) + { + /* The format is simple: */ + /* `/glyphname' + index [+ def] */ + + T1_Skip_Spaces( parser ); + + cur = parser->root.cursor; + if ( cur >= limit ) + break; + + /* We stop when we find an `end' keyword or '>' */ + if ( *cur == 'e' && + cur + 3 < limit && + cur[1] == 'n' && + cur[2] == 'd' && + t42_is_space( cur[3] ) ) + break; + if ( *cur == '>' ) + break; + + T1_Skip_PS_Token( parser ); + if ( parser->root.error ) + return; + { + FT_ERROR(( ""t42_parse_charstrings: out of bounds\n"" )); + error = FT_THROW( Invalid_File_Format ); + goto Fail; + } + + cur++; /* skip `/' */ + len = parser->root.cursor - cur; + + error = T1_Add_Table( name_table, n, cur, len + 1 ); + if ( error ) + goto Fail; + + /* add a trailing zero to the name table */ + name_table->elements[n][len] = '\0'; + + /* record index of /.notdef */ + if ( *cur == '.' && + ft_strcmp( "".notdef"", + (const char*)(name_table->elements[n]) ) == 0 ) + { + notdef_index = n; + notdef_found = 1; + } + + T1_Skip_Spaces( parser ); + + cur = parser->root.cursor; + + (void)T1_ToInt( parser ); + if ( parser->root.cursor >= limit ) + { + FT_ERROR(( ""t42_parse_charstrings: out of bounds\n"" )); + error = FT_THROW( Invalid_File_Format ); + goto Fail; + } + + len = parser->root.cursor - cur; + + error = T1_Add_Table( code_table, n, cur, len + 1 ); + if ( error ) + goto Fail; + + code_table->elements[n][len] = '\0'; + + n++; + if ( n >= loader->num_glyphs ) + break; + } + } +",1," t42_parse_charstrings( T42_Face face, + T42_Loader loader ) + { + T42_Parser parser = &loader->parser; + PS_Table code_table = &loader->charstrings; + PS_Table name_table = &loader->glyph_names; + PS_Table swap_table = &loader->swap_table; + FT_Memory memory = parser->root.memory; + FT_Error error; + + PSAux_Service psaux = (PSAux_Service)face->psaux; + + FT_Byte* cur; + FT_Byte* limit = parser->root.limit; + FT_UInt n; + FT_UInt notdef_index = 0; + FT_Byte notdef_found = 0; + + + T1_Skip_Spaces( parser ); + + if ( parser->root.cursor >= limit ) + { + FT_ERROR(( ""t42_parse_charstrings: out of bounds\n"" )); + error = FT_THROW( Invalid_File_Format ); + goto Fail; + } + + if ( ft_isdigit( *parser->root.cursor ) ) + { + loader->num_glyphs = (FT_UInt)T1_ToInt( parser ); + if ( parser->root.error ) + return; + } + else if ( *parser->root.cursor == '<' ) + { + /* We have `<< ... >>'. Count the number of `/' in the dictionary */ + /* to get its size. */ + FT_UInt count = 0; + + + T1_Skip_PS_Token( parser ); + if ( parser->root.error ) + return; + T1_Skip_Spaces( parser ); + cur = parser->root.cursor; + + while ( parser->root.cursor < limit ) + { + if ( *parser->root.cursor == '/' ) + count++; + else if ( *parser->root.cursor == '>' ) + { + loader->num_glyphs = count; + parser->root.cursor = cur; /* rewind */ + break; + } + T1_Skip_PS_Token( parser ); + if ( parser->root.error ) + return; + T1_Skip_Spaces( parser ); + } + } + else + { + FT_ERROR(( ""t42_parse_charstrings: invalid token\n"" )); + error = FT_THROW( Invalid_File_Format ); + goto Fail; + } + + if ( parser->root.cursor >= limit ) + { + FT_ERROR(( ""t42_parse_charstrings: out of bounds\n"" )); + error = FT_THROW( Invalid_File_Format ); + goto Fail; + } + + /* initialize tables */ + + error = psaux->ps_table_funcs->init( code_table, + loader->num_glyphs, + memory ); + if ( error ) + goto Fail; + + error = psaux->ps_table_funcs->init( name_table, + loader->num_glyphs, + memory ); + if ( error ) + goto Fail; + + /* Initialize table for swapping index notdef_index and */ + /* index 0 names and codes (if necessary). */ + + error = psaux->ps_table_funcs->init( swap_table, 4, memory ); + if ( error ) + goto Fail; + + n = 0; + + for (;;) + { + /* The format is simple: */ + /* `/glyphname' + index [+ def] */ + + T1_Skip_Spaces( parser ); + + cur = parser->root.cursor; + if ( cur >= limit ) + break; + + /* We stop when we find an `end' keyword or '>' */ + if ( *cur == 'e' && + cur + 3 < limit && + cur[1] == 'n' && + cur[2] == 'd' && + t42_is_space( cur[3] ) ) + break; + if ( *cur == '>' ) + break; + + T1_Skip_PS_Token( parser ); + if ( parser->root.cursor >= limit ) + { + FT_ERROR(( ""t42_parse_charstrings: out of bounds\n"" )); + error = FT_THROW( Invalid_File_Format ); + goto Fail; + } + if ( parser->root.error ) + return; + { + FT_ERROR(( ""t42_parse_charstrings: out of bounds\n"" )); + error = FT_THROW( Invalid_File_Format ); + goto Fail; + } + + cur++; /* skip `/' */ + len = parser->root.cursor - cur; + + error = T1_Add_Table( name_table, n, cur, len + 1 ); + if ( error ) + goto Fail; + + /* add a trailing zero to the name table */ + name_table->elements[n][len] = '\0'; + + /* record index of /.notdef */ + if ( *cur == '.' && + ft_strcmp( "".notdef"", + (const char*)(name_table->elements[n]) ) == 0 ) + { + notdef_index = n; + notdef_found = 1; + } + + T1_Skip_Spaces( parser ); + + cur = parser->root.cursor; + + (void)T1_ToInt( parser ); + if ( parser->root.cursor >= limit ) + { + FT_ERROR(( ""t42_parse_charstrings: out of bounds\n"" )); + error = FT_THROW( Invalid_File_Format ); + goto Fail; + } + + len = parser->root.cursor - cur; + + error = T1_Add_Table( code_table, n, cur, len + 1 ); + if ( error ) + goto Fail; + + code_table->elements[n][len] = '\0'; + + n++; + if ( n >= loader->num_glyphs ) + break; + } + } +","@@ -849,6 +849,12 @@ + break; + + T1_Skip_PS_Token( parser ); ++ if ( parser->root.cursor >= limit ) ++ { ++ FT_ERROR(( ""t42_parse_charstrings: out of bounds\n"" )); ++ error = FT_THROW( Invalid_File_Format ); ++ goto Fail; ++ } + if ( parser->root.error ) + return;",1177,1508,2048 +18196,"static void WriteDDSInfo(Image *image, const size_t pixelFormat, + const size_t compression, const size_t mipmaps) +{ + char + software[MaxTextExtent]; + + register ssize_t + i; + + unsigned int + format, + caps, + flags; + + flags=(unsigned int) (DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT | + DDSD_PIXELFORMAT | DDSD_LINEARSIZE); + caps=(unsigned int) DDSCAPS_TEXTURE; + format=(unsigned int) pixelFormat; + + if (mipmaps > 0) + { + flags=flags | (unsigned int) DDSD_MIPMAPCOUNT; + caps=caps | (unsigned int) (DDSCAPS_MIPMAP | DDSCAPS_COMPLEX); + } + + if (format != DDPF_FOURCC && image->matte) + format=format | DDPF_ALPHAPIXELS; + + (void) WriteBlob(image,4,(unsigned char *) ""DDS ""); + (void) WriteBlobLSBLong(image,124); + (void) WriteBlobLSBLong(image,flags); + (void) WriteBlobLSBLong(image,(unsigned int) image->rows); + (void) WriteBlobLSBLong(image,(unsigned int) image->columns); + + if (compression == FOURCC_DXT1) + (void) WriteBlobLSBLong(image, + (unsigned int) (Max(1,(image->columns+3)/4) * 8)); + else + (void) WriteBlobLSBLong(image, + (unsigned int) (Max(1,(image->columns+3)/4) * 16)); + + (void) WriteBlobLSBLong(image,0x00); + (void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1); + (void) ResetMagickMemory(software,0,sizeof(software)); + (void) strcpy(software,""IMAGEMAGICK""); + (void) WriteBlob(image,44,(unsigned char *) software); + + (void) WriteBlobLSBLong(image,32); + (void) WriteBlobLSBLong(image,format); + + if (pixelFormat == DDPF_FOURCC) + { + (void) WriteBlobLSBLong(image,(unsigned int) compression); + for(i=0;i < 5;i++) // bitcount / masks + (void) WriteBlobLSBLong(image,0x00); + } + else + { + (void) WriteBlobLSBLong(image,0x00); + if (image->matte) + { + (void) WriteBlobLSBLong(image,32); + (void) WriteBlobLSBLong(image,0xff0000); + (void) WriteBlobLSBLong(image,0xff00); + (void) WriteBlobLSBLong(image,0xff); + (void) WriteBlobLSBLong(image,0xff000000); + } + else + { + (void) WriteBlobLSBLong(image,24); + (void) WriteBlobLSBLong(image,0xff); + (void) WriteBlobLSBLong(image,0x00); + (void) WriteBlobLSBLong(image,0x00); + (void) WriteBlobLSBLong(image,0x00); + } + } + + (void) WriteBlobLSBLong(image,caps); + for(i=0;i < 4;i++) // ddscaps2 + reserved region + (void) WriteBlobLSBLong(image,0x00); +} +",1,"static void WriteDDSInfo(Image *image, const size_t pixelFormat, + const size_t compression, const size_t mipmaps) +{ + char + software[MaxTextExtent]; + + register ssize_t + i; + + unsigned int + format, + caps, + flags; + + flags=(unsigned int) (DDSD_CAPS | DDSD_WIDTH | DDSD_HEIGHT | + DDSD_PIXELFORMAT | DDSD_LINEARSIZE); + caps=(unsigned int) DDSCAPS_TEXTURE; + format=(unsigned int) pixelFormat; + + if (mipmaps > 0) + { + flags=flags | (unsigned int) DDSD_MIPMAPCOUNT; + caps=caps | (unsigned int) (DDSCAPS_MIPMAP | DDSCAPS_COMPLEX); + } + + if (format != DDPF_FOURCC && image->matte) + format=format | DDPF_ALPHAPIXELS; + + (void) WriteBlob(image,4,(unsigned char *) ""DDS ""); + (void) WriteBlobLSBLong(image,124); + (void) WriteBlobLSBLong(image,flags); + (void) WriteBlobLSBLong(image,(unsigned int) image->rows); + (void) WriteBlobLSBLong(image,(unsigned int) image->columns); + + if (compression == FOURCC_DXT1) + (void) WriteBlobLSBLong(image, + (unsigned int) (MagickMax(1,(image->columns+3)/4) * 8)); + else + (void) WriteBlobLSBLong(image, + (unsigned int) (MagickMax(1,(image->columns+3)/4) * 16)); + + (void) WriteBlobLSBLong(image,0x00); + (void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1); + (void) ResetMagickMemory(software,0,sizeof(software)); + (void) strcpy(software,""IMAGEMAGICK""); + (void) WriteBlob(image,44,(unsigned char *) software); + + (void) WriteBlobLSBLong(image,32); + (void) WriteBlobLSBLong(image,format); + + if (pixelFormat == DDPF_FOURCC) + { + (void) WriteBlobLSBLong(image,(unsigned int) compression); + for(i=0;i < 5;i++) // bitcount / masks + (void) WriteBlobLSBLong(image,0x00); + } + else + { + (void) WriteBlobLSBLong(image,0x00); + if (image->matte) + { + (void) WriteBlobLSBLong(image,32); + (void) WriteBlobLSBLong(image,0xff0000); + (void) WriteBlobLSBLong(image,0xff00); + (void) WriteBlobLSBLong(image,0xff); + (void) WriteBlobLSBLong(image,0xff000000); + } + else + { + (void) WriteBlobLSBLong(image,24); + (void) WriteBlobLSBLong(image,0xff); + (void) WriteBlobLSBLong(image,0x00); + (void) WriteBlobLSBLong(image,0x00); + (void) WriteBlobLSBLong(image,0x00); + } + } + + (void) WriteBlobLSBLong(image,caps); + for(i=0;i < 4;i++) // ddscaps2 + reserved region + (void) WriteBlobLSBLong(image,0x00); +} +","@@ -726,9 +726,9 @@ static const DDSSingleColourLookup* + if (min > max) \ + min = max; \ + if (max - min < steps) \ +- max = Min(min + steps, 255); \ ++ max = MagickMin(min + steps, 255); \ + if (max - min < steps) \ +- min = Max(min - steps, 0) ++ min = MagickMax(min - steps, 0) + + #define Dot(left, right) (left.x*right.x) + (left.y*right.y) + (left.z*right.z) + +@@ -743,90 +743,30 @@ if (max - min < steps) \ + Forward declarations + */ + static MagickBooleanType +- ConstructOrdering(const size_t, const DDSVector4 *, const DDSVector3, +- DDSVector4 *, DDSVector4 *, unsigned char *, size_t); +- +-static MagickBooleanType +- ReadDDSInfo(Image *, DDSInfo *); +- +-static MagickBooleanType +- ReadDXT1(Image *, DDSInfo *, ExceptionInfo *); +- +-static MagickBooleanType +- ReadDXT3(Image *, DDSInfo *, ExceptionInfo *); +- +-static MagickBooleanType +- ReadDXT5(Image *, DDSInfo *, ExceptionInfo *); +- +-static MagickBooleanType +- ReadUncompressedRGB(Image *, DDSInfo *, ExceptionInfo *); +- +-static MagickBooleanType +- ReadUncompressedRGBA(Image *, DDSInfo *, ExceptionInfo *); +- +-static void +- RemapIndices(const ssize_t *, const unsigned char *, unsigned char *); +- +-static void +- SkipDXTMipmaps(Image *, DDSInfo *, int); +- +-static void +- SkipRGBMipmaps(Image *, DDSInfo *, int); +- +-static +- MagickBooleanType WriteDDSImage(const ImageInfo *, Image *); +- +-static void +- WriteDDSInfo(Image *, const size_t, const size_t, const size_t); +- +-static void +- WriteFourCC(Image *, const size_t, const MagickBooleanType, +- const MagickBooleanType, ExceptionInfo *); ++ ConstructOrdering(const size_t,const DDSVector4 *,const DDSVector3, ++ DDSVector4 *,DDSVector4 *,unsigned char *,size_t), ++ ReadDDSInfo(Image *,DDSInfo *), ++ ReadDXT1(Image *,DDSInfo *,ExceptionInfo *), ++ ReadDXT3(Image *,DDSInfo *,ExceptionInfo *), ++ ReadDXT5(Image *,DDSInfo *,ExceptionInfo *), ++ ReadUncompressedRGB(Image *,DDSInfo *,ExceptionInfo *), ++ ReadUncompressedRGBA(Image *,DDSInfo *,ExceptionInfo *), ++ SkipDXTMipmaps(Image *,DDSInfo *,int,ExceptionInfo *), ++ SkipRGBMipmaps(Image *,DDSInfo *,int,ExceptionInfo *), ++ WriteDDSImage(const ImageInfo *,Image *), ++ WriteMipmaps(Image *,const size_t,const size_t,const size_t, ++ const MagickBooleanType,const MagickBooleanType,ExceptionInfo *); + + static void +- WriteImageData(Image *, const size_t, const size_t, const MagickBooleanType, +- const MagickBooleanType, ExceptionInfo *); +- +-static void +- WriteIndices(Image *, const DDSVector3, const DDSVector3, unsigned char *); +- +-static MagickBooleanType +- WriteMipmaps(Image *, const size_t, const size_t, const size_t, +- const MagickBooleanType, const MagickBooleanType, ExceptionInfo *); +- +-static void +- WriteSingleColorFit(Image *, const DDSVector4 *, const ssize_t *); +- +-static void +- WriteUncompressed(Image *, ExceptionInfo *); +- +-static inline size_t Max(size_t one, size_t two) +-{ +- if (one > two) +- return one; +- return two; +-} +- +-static inline float MaxF(float one, float two) +-{ +- if (one > two) +- return one; +- return two; +-} +- +-static inline size_t Min(size_t one, size_t two) +-{ +- if (one < two) +- return one; +- return two; +-} +- +-static inline float MinF(float one, float two) +-{ +- if (one < two) +- return one; +- return two; +-} ++ RemapIndices(const ssize_t *,const unsigned char *,unsigned char *), ++ WriteDDSInfo(Image *,const size_t,const size_t,const size_t), ++ WriteFourCC(Image *,const size_t,const MagickBooleanType, ++ const MagickBooleanType,ExceptionInfo *), ++ WriteImageData(Image *,const size_t,const size_t,const MagickBooleanType, ++ const MagickBooleanType,ExceptionInfo *), ++ WriteIndices(Image *,const DDSVector3,const DDSVector3, unsigned char *), ++ WriteSingleColorFit(Image *,const DDSVector4 *,const ssize_t *), ++ WriteUncompressed(Image *,ExceptionInfo *); + + static inline void VectorAdd(const DDSVector4 left, const DDSVector4 right, + DDSVector4 *destination) +@@ -839,17 +779,17 @@ static inline void VectorAdd(const DDSVector4 left, const DDSVector4 right, + + static inline void VectorClamp(DDSVector4 *value) + { +- value->x = MinF(1.0f,MaxF(0.0f,value->x)); +- value->y = MinF(1.0f,MaxF(0.0f,value->y)); +- value->z = MinF(1.0f,MaxF(0.0f,value->z)); +- value->w = MinF(1.0f,MaxF(0.0f,value->w)); ++ value->x = MagickMin(1.0f,MagickMax(0.0f,value->x)); ++ value->y = MagickMin(1.0f,MagickMax(0.0f,value->y)); ++ value->z = MagickMin(1.0f,MagickMax(0.0f,value->z)); ++ value->w = MagickMin(1.0f,MagickMax(0.0f,value->w)); + } + + static inline void VectorClamp3(DDSVector3 *value) + { +- value->x = MinF(1.0f,MaxF(0.0f,value->x)); +- value->y = MinF(1.0f,MaxF(0.0f,value->y)); +- value->z = MinF(1.0f,MaxF(0.0f,value->z)); ++ value->x = MagickMin(1.0f,MagickMax(0.0f,value->x)); ++ value->y = MagickMin(1.0f,MagickMax(0.0f,value->y)); ++ value->z = MagickMin(1.0f,MagickMax(0.0f,value->z)); + } + + static inline void VectorCopy43(const DDSVector4 source, +@@ -1474,7 +1414,7 @@ static void ComputePrincipleComponent(const float *covariance, + w.z = (row2.z * v.z) + w.z; + w.w = (row2.w * v.z) + w.w; + +- a = 1.0f / MaxF(w.x,MaxF(w.y,w.z)); ++ a = 1.0f / MagickMax(w.x,MagickMax(w.y,w.z)); + + v.x = w.x * a; + v.y = w.y * a; +@@ -1961,8 +1901,8 @@ static MagickBooleanType ReadDXT1(Image *image, DDSInfo *dds_info, + for (x = 0; x < (ssize_t) dds_info->width; x += 4) + { + /* Get 4x4 patch of pixels to write on */ +- q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x), +- Min(4, dds_info->height - y),exception); ++ q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x), ++ MagickMin(4, dds_info->height - y),exception); + + if (q == (PixelPacket *) NULL) + return MagickFalse; +@@ -1999,9 +1939,7 @@ static MagickBooleanType ReadDXT1(Image *image, DDSInfo *dds_info, + } + } + +- SkipDXTMipmaps(image, dds_info, 8); +- +- return MagickTrue; ++ return(SkipDXTMipmaps(image,dds_info,8,exception)); + } + + static MagickBooleanType ReadDXT3(Image *image, DDSInfo *dds_info, +@@ -2039,8 +1977,8 @@ static MagickBooleanType ReadDXT3(Image *image, DDSInfo *dds_info, + for (x = 0; x < (ssize_t) dds_info->width; x += 4) + { + /* Get 4x4 patch of pixels to write on */ +- q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x), +- Min(4, dds_info->height - y),exception); ++ q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x), ++ MagickMin(4, dds_info->height - y),exception); + + if (q == (PixelPacket *) NULL) + return MagickFalse; +@@ -2086,9 +2024,7 @@ static MagickBooleanType ReadDXT3(Image *image, DDSInfo *dds_info, + } + } + +- SkipDXTMipmaps(image, dds_info, 16); +- +- return MagickTrue; ++ return(SkipDXTMipmaps(image,dds_info,16,exception)); + } + + static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info, +@@ -2130,8 +2066,8 @@ static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info, + for (x = 0; x < (ssize_t) dds_info->width; x += 4) + { + /* Get 4x4 patch of pixels to write on */ +- q = QueueAuthenticPixels(image, x, y, Min(4, dds_info->width - x), +- Min(4, dds_info->height - y),exception); ++ q = QueueAuthenticPixels(image, x, y, MagickMin(4, dds_info->width - x), ++ MagickMin(4, dds_info->height - y),exception); + + if (q == (PixelPacket *) NULL) + return MagickFalse; +@@ -2187,9 +2123,7 @@ static MagickBooleanType ReadDXT5(Image *image, DDSInfo *dds_info, + } + } + +- SkipDXTMipmaps(image, dds_info, 16); +- +- return MagickTrue; ++ return(SkipDXTMipmaps(image,dds_info,16,exception)); + } + + static MagickBooleanType ReadUncompressedRGB(Image *image, DDSInfo *dds_info, +@@ -2251,9 +2185,7 @@ static MagickBooleanType ReadUncompressedRGB(Image *image, DDSInfo *dds_info, + return MagickFalse; + } + +- SkipRGBMipmaps(image, dds_info, 3); +- +- return MagickTrue; ++ return(SkipRGBMipmaps(image,dds_info,3,exception)); + } + + static MagickBooleanType ReadUncompressedRGBA(Image *image, DDSInfo *dds_info, +@@ -2345,9 +2277,7 @@ static MagickBooleanType ReadUncompressedRGBA(Image *image, DDSInfo *dds_info, + return MagickFalse; + } + +- SkipRGBMipmaps(image, dds_info, 4); +- +- return MagickTrue; ++ return(SkipRGBMipmaps(image,dds_info,4,exception)); + } + + /* +@@ -2423,7 +2353,8 @@ static void RemapIndices(const ssize_t *map, const unsigned char *source, + /* + Skip the mipmap images for compressed (DXTn) dds files + */ +-static void SkipDXTMipmaps(Image *image, DDSInfo *dds_info, int texel_size) ++static MagickBooleanType SkipDXTMipmaps(Image *image,DDSInfo *dds_info, ++ int texel_size,ExceptionInfo *exception) + { + register ssize_t + i; +@@ -2442,6 +2373,12 @@ static void SkipDXTMipmaps(Image *image, DDSInfo *dds_info, int texel_size) + && (dds_info->ddscaps1 & DDSCAPS_TEXTURE + || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) + { ++ if (EOFBlob(image) != MagickFalse) ++ { ++ ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", ++ image->filename); ++ return(MagickFalse); ++ } + w = DIV2(dds_info->width); + h = DIV2(dds_info->height); + +@@ -2457,12 +2394,14 @@ static void SkipDXTMipmaps(Image *image, DDSInfo *dds_info, int texel_size) + h = DIV2(h); + } + } ++ return(MagickTrue); + } + + /* + Skip the mipmap images for uncompressed (RGB or RGBA) dds files + */ +-static void SkipRGBMipmaps(Image *image, DDSInfo *dds_info, int pixel_size) ++static MagickBooleanType SkipRGBMipmaps(Image *image,DDSInfo *dds_info, ++ int pixel_size,ExceptionInfo *exception) + { + MagickOffsetType + offset; +@@ -2481,6 +2420,12 @@ static void SkipRGBMipmaps(Image *image, DDSInfo *dds_info, int pixel_size) + && (dds_info->ddscaps1 & DDSCAPS_TEXTURE + || dds_info->ddscaps2 & DDSCAPS2_CUBEMAP)) + { ++ if (EOFBlob(image) != MagickFalse) ++ { ++ ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", ++ image->filename); ++ return(MagickFalse); ++ } + w = DIV2(dds_info->width); + h = DIV2(dds_info->height); + +@@ -2496,6 +2441,7 @@ static void SkipRGBMipmaps(Image *image, DDSInfo *dds_info, int pixel_size) + h = DIV2(h); + } + } ++ return(MagickTrue); + } + + /* +@@ -2779,10 +2725,10 @@ static void WriteDDSInfo(Image *image, const size_t pixelFormat, + + if (compression == FOURCC_DXT1) + (void) WriteBlobLSBLong(image, +- (unsigned int) (Max(1,(image->columns+3)/4) * 8)); ++ (unsigned int) (MagickMax(1,(image->columns+3)/4) * 8)); + else + (void) WriteBlobLSBLong(image, +- (unsigned int) (Max(1,(image->columns+3)/4) * 16)); ++ (unsigned int) (MagickMax(1,(image->columns+3)/4) * 16)); + + (void) WriteBlobLSBLong(image,0x00); + (void) WriteBlobLSBLong(image,(unsigned int) mipmaps+1);",782,1113,2048 +586,"_gcry_ecc_eddsa_recover_x (gcry_mpi_t x, gcry_mpi_t y, int sign, mpi_ec_t ec) +{ + gpg_err_code_t rc = 0; + gcry_mpi_t u, v, v3, t; + static gcry_mpi_t p58, seven; + + if (ec->dialect != ECC_DIALECT_ED25519) + return GPG_ERR_NOT_IMPLEMENTED; + + if (!p58) + p58 = scanval (""0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"" + ""FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD""); + if (!seven) + seven = mpi_set_ui (NULL, 7); + + u = mpi_new (0); + v = mpi_new (0); + v3 = mpi_new (0); + t = mpi_new (0); + + /* Compute u and v */ + /* u = y^2 */ + mpi_mulm (u, y, y, ec->p); + /* v = b*y^2 */ + mpi_mulm (v, ec->b, u, ec->p); + /* u = y^2-1 */ + mpi_sub_ui (u, u, 1); + /* v = b*y^2+1 */ + mpi_add_ui (v, v, 1); + + /* Compute sqrt(u/v) */ + /* v3 = v^3 */ + mpi_powm (v3, v, mpi_const (MPI_C_THREE), ec->p); + /* t = v3 * v3 * u * v = u * v^7 */ + mpi_powm (t, v, seven, ec->p); + mpi_mulm (t, t, u, ec->p); + /* t = t^((p-5)/8) = (u * v^7)^((p-5)/8) */ + mpi_powm (t, t, p58, ec->p); + /* x = t * u * v^3 = (u * v^3) * (u * v^7)^((p-5)/8) */ + mpi_mulm (t, t, u, ec->p); + mpi_mulm (x, t, v3, ec->p); + + /* Adjust if needed. */ + /* t = v * x^2 */ + mpi_mulm (t, x, x, ec->p); + mpi_mulm (t, t, v, ec->p); + /* -t == u ? x = x * sqrt(-1) */ + mpi_sub (t, ec->p, t); + if (!mpi_cmp (t, u)) + { + static gcry_mpi_t m1; /* Fixme: this is not thread-safe. */ + if (!m1) + m1 = scanval (""2B8324804FC1DF0B2B4D00993DFBD7A7"" + ""2F431806AD2FE478C4EE1B274A0EA0B0""); + mpi_mulm (x, x, m1, ec->p); + /* t = v * x^2 */ + mpi_mulm (t, x, x, ec->p); + mpi_mulm (t, t, v, ec->p); + /* -t == u ? x = x * sqrt(-1) */ + mpi_sub (t, ec->p, t); + if (!mpi_cmp (t, u)) + rc = GPG_ERR_INV_OBJ; + } + + /* Choose the desired square root according to parity */ + if (mpi_test_bit (x, 0) != !!sign) + mpi_sub (x, ec->p, x); + + mpi_free (t); + mpi_free (v3); + mpi_free (v); + mpi_free (u); + + return rc; +} +",0,"_gcry_ecc_eddsa_recover_x (gcry_mpi_t x, gcry_mpi_t y, int sign, mpi_ec_t ec) +{ + gpg_err_code_t rc = 0; + gcry_mpi_t u, v, v3, t; + static gcry_mpi_t p58, seven; + + if (ec->dialect != ECC_DIALECT_ED25519) + return GPG_ERR_NOT_IMPLEMENTED; + + if (!p58) + p58 = scanval (""0FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"" + ""FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFD""); + if (!seven) + seven = mpi_set_ui (NULL, 7); + + u = mpi_new (0); + v = mpi_new (0); + v3 = mpi_new (0); + t = mpi_new (0); + + /* Compute u and v */ + /* u = y^2 */ + mpi_mulm (u, y, y, ec->p); + /* v = b*y^2 */ + mpi_mulm (v, ec->b, u, ec->p); + /* u = y^2-1 */ + mpi_sub_ui (u, u, 1); + /* v = b*y^2+1 */ + mpi_add_ui (v, v, 1); + + /* Compute sqrt(u/v) */ + /* v3 = v^3 */ + mpi_powm (v3, v, mpi_const (MPI_C_THREE), ec->p); + /* t = v3 * v3 * u * v = u * v^7 */ + mpi_powm (t, v, seven, ec->p); + mpi_mulm (t, t, u, ec->p); + /* t = t^((p-5)/8) = (u * v^7)^((p-5)/8) */ + mpi_powm (t, t, p58, ec->p); + /* x = t * u * v^3 = (u * v^3) * (u * v^7)^((p-5)/8) */ + mpi_mulm (t, t, u, ec->p); + mpi_mulm (x, t, v3, ec->p); + + /* Adjust if needed. */ + /* t = v * x^2 */ + mpi_mulm (t, x, x, ec->p); + mpi_mulm (t, t, v, ec->p); + /* -t == u ? x = x * sqrt(-1) */ + mpi_sub (t, ec->p, t); + if (!mpi_cmp (t, u)) + { + static gcry_mpi_t m1; /* Fixme: this is not thread-safe. */ + if (!m1) + m1 = scanval (""2B8324804FC1DF0B2B4D00993DFBD7A7"" + ""2F431806AD2FE478C4EE1B274A0EA0B0""); + mpi_mulm (x, x, m1, ec->p); + /* t = v * x^2 */ + mpi_mulm (t, x, x, ec->p); + mpi_mulm (t, t, v, ec->p); + /* -t == u ? x = x * sqrt(-1) */ + mpi_sub (t, ec->p, t); + if (!mpi_cmp (t, u)) + rc = GPG_ERR_INV_OBJ; + } + + /* Choose the desired square root according to parity */ + if (mpi_test_bit (x, 0) != !!sign) + mpi_sub (x, ec->p, x); + + mpi_free (t); + mpi_free (v3); + mpi_free (v); + mpi_free (u); + + return rc; +} +","@@ -603,7 +603,7 @@ _gcry_ecc_eddsa_sign (gcry_mpi_t input, ECC_secret_key *skey, + a = mpi_snew (0); + x = mpi_new (0); + y = mpi_new (0); +- r = mpi_new (0); ++ r = mpi_snew (0); + ctx = _gcry_mpi_ec_p_internal_new (skey->E.model, skey->E.dialect, 0, + skey->E.p, skey->E.a, skey->E.b); + b = (ctx->nbits+7)/8;",846,1177,2048 +6173,"static ssize_t do_tcp_sendpages(struct sock *sk, struct page *page, int offset, + size_t size, int flags) +{ + struct tcp_sock *tp = tcp_sk(sk); + int mss_now, size_goal; + int err; + ssize_t copied; + long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT); + + /* Wait for a connection to finish. One exception is TCP Fast Open + * (passive side) where data is allowed to be sent before a connection + * is fully established. + */ + if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) && + !tcp_passive_fastopen(sk)) { + err = sk_stream_wait_connect(sk, &timeo); + if (err != 0) + goto out_err; + } + + sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk); + + mss_now = tcp_send_mss(sk, &size_goal, flags); + copied = 0; + + err = -EPIPE; + if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN)) + goto out_err; + + while (size > 0) { + struct sk_buff *skb = tcp_write_queue_tail(sk); + int copy, i; + bool can_coalesce; + + if (!tcp_send_head(sk) || (copy = size_goal - skb->len) <= 0 || + !tcp_skb_can_collapse_to(skb)) { +new_segment: + if (!sk_stream_memory_free(sk)) + goto wait_for_sndbuf; + + skb = sk_stream_alloc_skb(sk, 0, sk->sk_allocation, + skb_queue_empty(&sk->sk_write_queue)); + if (!skb) + goto wait_for_memory; + + skb_entail(sk, skb); + copy = size_goal; + } + + if (copy > size) + copy = size; + + i = skb_shinfo(skb)->nr_frags; + can_coalesce = skb_can_coalesce(skb, i, page, offset); + if (!can_coalesce && i >= sysctl_max_skb_frags) { + tcp_mark_push(tp, skb); + goto new_segment; + } + if (!sk_wmem_schedule(sk, copy)) + goto wait_for_memory; + + if (can_coalesce) { + skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy); + } else { + get_page(page); + skb_fill_page_desc(skb, i, page, offset, copy); + } + skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG; + + skb->len += copy; + skb->data_len += copy; + skb->truesize += copy; + sk->sk_wmem_queued += copy; + sk_mem_charge(sk, copy); + skb->ip_summed = CHECKSUM_PARTIAL; + tp->write_seq += copy; + TCP_SKB_CB(skb)->end_seq += copy; + tcp_skb_pcount_set(skb, 0); + + if (!copied) + TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH; + + copied += copy; + offset += copy; + size -= copy; + if (!size) + goto out; + + if (skb->len < size_goal || (flags & MSG_OOB)) + continue; + + if (forced_push(tp)) { + tcp_mark_push(tp, skb); + __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH); + } else if (skb == tcp_send_head(sk)) + tcp_push_one(sk, mss_now); + continue; + +wait_for_sndbuf: + set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); +wait_for_memory: + tcp_push(sk, flags & ~MSG_MORE, mss_now, + TCP_NAGLE_PUSH, size_goal); + + err = sk_stream_wait_memory(sk, &timeo); + if (err != 0) + goto do_error; + + mss_now = tcp_send_mss(sk, &size_goal, flags); + } + +out: + if (copied) { + tcp_tx_timestamp(sk, sk->sk_tsflags, tcp_write_queue_tail(sk)); + if (!(flags & MSG_SENDPAGE_NOTLAST)) + tcp_push(sk, flags, mss_now, tp->nonagle, size_goal); + } + return copied; + +do_error: + if (copied) + goto out; +out_err: + /* make sure we wake any epoll edge trigger waiter */ + if (unlikely(skb_queue_len(&sk->sk_write_queue) == 0 && + err == -EAGAIN)) { + sk->sk_write_space(sk); + tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED); + } + return sk_stream_error(sk, flags, err); +} +",0,"static ssize_t do_tcp_sendpages(struct sock *sk, struct page *page, int offset, + size_t size, int flags) +{ + struct tcp_sock *tp = tcp_sk(sk); + int mss_now, size_goal; + int err; + ssize_t copied; + long timeo = sock_sndtimeo(sk, flags & MSG_DONTWAIT); + + /* Wait for a connection to finish. One exception is TCP Fast Open + * (passive side) where data is allowed to be sent before a connection + * is fully established. + */ + if (((1 << sk->sk_state) & ~(TCPF_ESTABLISHED | TCPF_CLOSE_WAIT)) && + !tcp_passive_fastopen(sk)) { + err = sk_stream_wait_connect(sk, &timeo); + if (err != 0) + goto out_err; + } + + sk_clear_bit(SOCKWQ_ASYNC_NOSPACE, sk); + + mss_now = tcp_send_mss(sk, &size_goal, flags); + copied = 0; + + err = -EPIPE; + if (sk->sk_err || (sk->sk_shutdown & SEND_SHUTDOWN)) + goto out_err; + + while (size > 0) { + struct sk_buff *skb = tcp_write_queue_tail(sk); + int copy, i; + bool can_coalesce; + + if (!tcp_send_head(sk) || (copy = size_goal - skb->len) <= 0 || + !tcp_skb_can_collapse_to(skb)) { +new_segment: + if (!sk_stream_memory_free(sk)) + goto wait_for_sndbuf; + + skb = sk_stream_alloc_skb(sk, 0, sk->sk_allocation, + skb_queue_empty(&sk->sk_write_queue)); + if (!skb) + goto wait_for_memory; + + skb_entail(sk, skb); + copy = size_goal; + } + + if (copy > size) + copy = size; + + i = skb_shinfo(skb)->nr_frags; + can_coalesce = skb_can_coalesce(skb, i, page, offset); + if (!can_coalesce && i >= sysctl_max_skb_frags) { + tcp_mark_push(tp, skb); + goto new_segment; + } + if (!sk_wmem_schedule(sk, copy)) + goto wait_for_memory; + + if (can_coalesce) { + skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy); + } else { + get_page(page); + skb_fill_page_desc(skb, i, page, offset, copy); + } + skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG; + + skb->len += copy; + skb->data_len += copy; + skb->truesize += copy; + sk->sk_wmem_queued += copy; + sk_mem_charge(sk, copy); + skb->ip_summed = CHECKSUM_PARTIAL; + tp->write_seq += copy; + TCP_SKB_CB(skb)->end_seq += copy; + tcp_skb_pcount_set(skb, 0); + + if (!copied) + TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_PSH; + + copied += copy; + offset += copy; + size -= copy; + if (!size) + goto out; + + if (skb->len < size_goal || (flags & MSG_OOB)) + continue; + + if (forced_push(tp)) { + tcp_mark_push(tp, skb); + __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_PUSH); + } else if (skb == tcp_send_head(sk)) + tcp_push_one(sk, mss_now); + continue; + +wait_for_sndbuf: + set_bit(SOCK_NOSPACE, &sk->sk_socket->flags); +wait_for_memory: + tcp_push(sk, flags & ~MSG_MORE, mss_now, + TCP_NAGLE_PUSH, size_goal); + + err = sk_stream_wait_memory(sk, &timeo); + if (err != 0) + goto do_error; + + mss_now = tcp_send_mss(sk, &size_goal, flags); + } + +out: + if (copied) { + tcp_tx_timestamp(sk, sk->sk_tsflags, tcp_write_queue_tail(sk)); + if (!(flags & MSG_SENDPAGE_NOTLAST)) + tcp_push(sk, flags, mss_now, tp->nonagle, size_goal); + } + return copied; + +do_error: + if (copied) + goto out; +out_err: + /* make sure we wake any epoll edge trigger waiter */ + if (unlikely(skb_queue_len(&sk->sk_write_queue) == 0 && + err == -EAGAIN)) { + sk->sk_write_space(sk); + tcp_chrono_stop(sk, TCP_CHRONO_SNDBUF_LIMITED); + } + return sk_stream_error(sk, flags, err); +} +","@@ -2320,6 +2320,10 @@ int tcp_disconnect(struct sock *sk, int flags) + tcp_set_ca_state(sk, TCP_CA_Open); + tcp_clear_retrans(tp); + inet_csk_delack_init(sk); ++ /* Initialize rcv_mss to TCP_MIN_MSS to avoid division by 0 ++ * issue in __tcp_select_window() ++ */ ++ icsk->icsk_ack.rcv_mss = TCP_MIN_MSS; + tcp_init_send_head(sk); + memset(&tp->rx_opt, 0, sizeof(tp->rx_opt)); + __sk_dst_reset(sk);",1032,1363,2048 +5535,"static int tree_content_set( + struct tree_entry *root, + const char *p, + const unsigned char *sha1, + const uint16_t mode, + struct tree_content *subtree) +{ + struct tree_content *t; + const char *slash1; + unsigned int i, n; + struct tree_entry *e; + + slash1 = strchrnul(p, '/'); + n = slash1 - p; + if (!n) + die(""Empty path component found in input""); + if (!*slash1 && !S_ISDIR(mode) && subtree) + die(""Non-directories cannot have subtrees""); + + if (!root->tree) + load_tree(root); + t = root->tree; + for (i = 0; i < t->entry_count; i++) { + e = t->entries[i]; + if (e->name->str_len == n && !strncmp_icase(p, e->name->str_dat, n)) { + if (!*slash1) { + if (!S_ISDIR(mode) + && e->versions[1].mode == mode + && !hashcmp(e->versions[1].sha1, sha1)) + return 0; + e->versions[1].mode = mode; + hashcpy(e->versions[1].sha1, sha1); + if (e->tree) + release_tree_content_recursive(e->tree); + e->tree = subtree; + + /* + * We need to leave e->versions[0].sha1 alone + * to avoid modifying the preimage tree used + * when writing out the parent directory. + * But after replacing the subdir with a + * completely different one, it's not a good + * delta base any more, and besides, we've + * thrown away the tree entries needed to + * make a delta against it. + * + * So let's just explicitly disable deltas + * for the subtree. + */ + if (S_ISDIR(e->versions[0].mode)) + e->versions[0].mode |= NO_DELTA; + + hashclr(root->versions[1].sha1); + return 1; + } + if (!S_ISDIR(e->versions[1].mode)) { + e->tree = new_tree_content(8); + e->versions[1].mode = S_IFDIR; + } + if (!e->tree) + load_tree(e); + if (tree_content_set(e, slash1 + 1, sha1, mode, subtree)) { + hashclr(root->versions[1].sha1); + return 1; + } + return 0; + } + } + + if (t->entry_count == t->entry_capacity) + root->tree = t = grow_tree_content(t, t->entry_count); + e = new_tree_entry(); + e->name = to_atom(p, n); + e->versions[0].mode = 0; + hashclr(e->versions[0].sha1); + t->entries[t->entry_count++] = e; + if (*slash1) { + e->tree = new_tree_content(8); + e->versions[1].mode = S_IFDIR; + tree_content_set(e, slash1 + 1, sha1, mode, subtree); + } else { + e->tree = subtree; + e->versions[1].mode = mode; + hashcpy(e->versions[1].sha1, sha1); + } + hashclr(root->versions[1].sha1); + return 1; +} +",0,"static int tree_content_set( + struct tree_entry *root, + const char *p, + const unsigned char *sha1, + const uint16_t mode, + struct tree_content *subtree) +{ + struct tree_content *t; + const char *slash1; + unsigned int i, n; + struct tree_entry *e; + + slash1 = strchrnul(p, '/'); + n = slash1 - p; + if (!n) + die(""Empty path component found in input""); + if (!*slash1 && !S_ISDIR(mode) && subtree) + die(""Non-directories cannot have subtrees""); + + if (!root->tree) + load_tree(root); + t = root->tree; + for (i = 0; i < t->entry_count; i++) { + e = t->entries[i]; + if (e->name->str_len == n && !strncmp_icase(p, e->name->str_dat, n)) { + if (!*slash1) { + if (!S_ISDIR(mode) + && e->versions[1].mode == mode + && !hashcmp(e->versions[1].sha1, sha1)) + return 0; + e->versions[1].mode = mode; + hashcpy(e->versions[1].sha1, sha1); + if (e->tree) + release_tree_content_recursive(e->tree); + e->tree = subtree; + + /* + * We need to leave e->versions[0].sha1 alone + * to avoid modifying the preimage tree used + * when writing out the parent directory. + * But after replacing the subdir with a + * completely different one, it's not a good + * delta base any more, and besides, we've + * thrown away the tree entries needed to + * make a delta against it. + * + * So let's just explicitly disable deltas + * for the subtree. + */ + if (S_ISDIR(e->versions[0].mode)) + e->versions[0].mode |= NO_DELTA; + + hashclr(root->versions[1].sha1); + return 1; + } + if (!S_ISDIR(e->versions[1].mode)) { + e->tree = new_tree_content(8); + e->versions[1].mode = S_IFDIR; + } + if (!e->tree) + load_tree(e); + if (tree_content_set(e, slash1 + 1, sha1, mode, subtree)) { + hashclr(root->versions[1].sha1); + return 1; + } + return 0; + } + } + + if (t->entry_count == t->entry_capacity) + root->tree = t = grow_tree_content(t, t->entry_count); + e = new_tree_entry(); + e->name = to_atom(p, n); + e->versions[0].mode = 0; + hashclr(e->versions[0].sha1); + t->entries[t->entry_count++] = e; + if (*slash1) { + e->tree = new_tree_content(8); + e->versions[1].mode = S_IFDIR; + tree_content_set(e, slash1 + 1, sha1, mode, subtree); + } else { + e->tree = subtree; + e->versions[1].mode = mode; + hashcpy(e->versions[1].sha1, sha1); + } + hashclr(root->versions[1].sha1); + return 1; +} +","@@ -644,8 +644,9 @@ static void *pool_calloc(size_t count, size_t size) + + static char *pool_strdup(const char *s) + { +- char *r = pool_alloc(strlen(s) + 1); +- strcpy(r, s); ++ size_t len = strlen(s) + 1; ++ char *r = pool_alloc(len); ++ memcpy(r, s, len); + return r; + } + ",739,1070,2048 +14888,"static int SplitNode( + Rtree *pRtree, + RtreeNode *pNode, + RtreeCell *pCell, + int iHeight +){ + int i; + int newCellIsRight = 0; + + int rc = SQLITE_OK; + int nCell = NCELL(pNode); + RtreeCell *aCell; + int *aiUsed; + + RtreeNode *pLeft = 0; + RtreeNode *pRight = 0; + + RtreeCell leftbbox; + RtreeCell rightbbox; + + /* Allocate an array and populate it with a copy of pCell and + ** all cells from node pLeft. Then zero the original node. + */ + aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1)); + if( !aCell ){ + rc = SQLITE_NOMEM; + goto splitnode_out; + } + aiUsed = (int *)&aCell[nCell+1]; + memset(aiUsed, 0, sizeof(int)*(nCell+1)); + for(i=0; iiNode==1 ){ + pRight = nodeNew(pRtree, pNode); + pLeft = nodeNew(pRtree, pNode); + pRtree->iDepth++; + pNode->isDirty = 1; + writeInt16(pNode->zData, pRtree->iDepth); + }else{ + pLeft = pNode; + pRight = nodeNew(pRtree, pLeft->pParent); + nodeReference(pLeft); + } + + if( !pLeft || !pRight ){ + rc = SQLITE_NOMEM; + goto splitnode_out; + } + + memset(pLeft->zData, 0, pRtree->iNodeSize); + memset(pRight->zData, 0, pRtree->iNodeSize); + + rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight, + &leftbbox, &rightbbox); + if( rc!=SQLITE_OK ){ + goto splitnode_out; + } + + /* Ensure both child nodes have node numbers assigned to them by calling + ** nodeWrite(). Node pRight always needs a node number, as it was created + ** by nodeNew() above. But node pLeft sometimes already has a node number. + ** In this case avoid the all to nodeWrite(). + */ + if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)) + || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft))) + ){ + goto splitnode_out; + } + + rightbbox.iRowid = pRight->iNode; + leftbbox.iRowid = pLeft->iNode; + + if( pNode->iNode==1 ){ + rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1); + if( rc!=SQLITE_OK ){ + goto splitnode_out; + } + }else{ + RtreeNode *pParent = pLeft->pParent; + int iCell; + rc = nodeParentIndex(pRtree, pLeft, &iCell); + if( rc==SQLITE_OK ){ + nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell); + rc = AdjustTree(pRtree, pParent, &leftbbox); + } + if( rc!=SQLITE_OK ){ + goto splitnode_out; + } + } + if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){ + goto splitnode_out; + } + + for(i=0; iiRowid ){ + newCellIsRight = 1; + } + if( rc!=SQLITE_OK ){ + goto splitnode_out; + } + } + if( pNode->iNode==1 ){ + for(i=0; iiRowid, pLeft, iHeight); + } + + if( rc==SQLITE_OK ){ + rc = nodeRelease(pRtree, pRight); + pRight = 0; + } + if( rc==SQLITE_OK ){ + rc = nodeRelease(pRtree, pLeft); + pLeft = 0; + } + +splitnode_out: + nodeRelease(pRtree, pRight); + nodeRelease(pRtree, pLeft); + sqlite3_free(aCell); + return rc; +} +",0,"static int SplitNode( + Rtree *pRtree, + RtreeNode *pNode, + RtreeCell *pCell, + int iHeight +){ + int i; + int newCellIsRight = 0; + + int rc = SQLITE_OK; + int nCell = NCELL(pNode); + RtreeCell *aCell; + int *aiUsed; + + RtreeNode *pLeft = 0; + RtreeNode *pRight = 0; + + RtreeCell leftbbox; + RtreeCell rightbbox; + + /* Allocate an array and populate it with a copy of pCell and + ** all cells from node pLeft. Then zero the original node. + */ + aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1)); + if( !aCell ){ + rc = SQLITE_NOMEM; + goto splitnode_out; + } + aiUsed = (int *)&aCell[nCell+1]; + memset(aiUsed, 0, sizeof(int)*(nCell+1)); + for(i=0; iiNode==1 ){ + pRight = nodeNew(pRtree, pNode); + pLeft = nodeNew(pRtree, pNode); + pRtree->iDepth++; + pNode->isDirty = 1; + writeInt16(pNode->zData, pRtree->iDepth); + }else{ + pLeft = pNode; + pRight = nodeNew(pRtree, pLeft->pParent); + nodeReference(pLeft); + } + + if( !pLeft || !pRight ){ + rc = SQLITE_NOMEM; + goto splitnode_out; + } + + memset(pLeft->zData, 0, pRtree->iNodeSize); + memset(pRight->zData, 0, pRtree->iNodeSize); + + rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight, + &leftbbox, &rightbbox); + if( rc!=SQLITE_OK ){ + goto splitnode_out; + } + + /* Ensure both child nodes have node numbers assigned to them by calling + ** nodeWrite(). Node pRight always needs a node number, as it was created + ** by nodeNew() above. But node pLeft sometimes already has a node number. + ** In this case avoid the all to nodeWrite(). + */ + if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)) + || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft))) + ){ + goto splitnode_out; + } + + rightbbox.iRowid = pRight->iNode; + leftbbox.iRowid = pLeft->iNode; + + if( pNode->iNode==1 ){ + rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1); + if( rc!=SQLITE_OK ){ + goto splitnode_out; + } + }else{ + RtreeNode *pParent = pLeft->pParent; + int iCell; + rc = nodeParentIndex(pRtree, pLeft, &iCell); + if( rc==SQLITE_OK ){ + nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell); + rc = AdjustTree(pRtree, pParent, &leftbbox); + } + if( rc!=SQLITE_OK ){ + goto splitnode_out; + } + } + if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){ + goto splitnode_out; + } + + for(i=0; iiRowid ){ + newCellIsRight = 1; + } + if( rc!=SQLITE_OK ){ + goto splitnode_out; + } + } + if( pNode->iNode==1 ){ + for(i=0; iiRowid, pLeft, iHeight); + } + + if( rc==SQLITE_OK ){ + rc = nodeRelease(pRtree, pRight); + pRight = 0; + } + if( rc==SQLITE_OK ){ + rc = nodeRelease(pRtree, pLeft); + pLeft = 0; + } + +splitnode_out: + nodeRelease(pRtree, pRight); + nodeRelease(pRtree, pLeft); + sqlite3_free(aCell); + return rc; +} +","@@ -4065,6 +4065,15 @@ typedef struct sqlite3_context sqlite3_context; + ** [sqlite3_blob_open | incremental BLOB I/O] routines. + ** ^A negative value for the zeroblob results in a zero-length BLOB. + ** ++** ^The sqlite3_bind_pointer(S,I,P) routine causes the I-th parameter in ++** [prepared statement] S to have an SQL value of NULL, but to also be ++** associated with the pointer P. ++** ^The sqlite3_bind_pointer() routine can be used to pass ++** host-language pointers into [application-defined SQL functions]. ++** ^A parameter that is initialized using [sqlite3_bind_pointer()] appears ++** to be an ordinary SQL NULL value to everything other than ++** [sqlite3_value_pointer()]. ++** + ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer + ** for the [prepared statement] or with a prepared statement for which + ** [sqlite3_step()] has been called more recently than [sqlite3_reset()], +@@ -4098,6 +4107,7 @@ SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*) + SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64, + void(*)(void*), unsigned char encoding); + SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); ++SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt*, int, void*); + SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); + SQLITE_API int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64); + +@@ -4867,6 +4877,11 @@ SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int6 + ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces + ** extract UTF-16 strings as big-endian and little-endian respectively. + ** ++** ^If [sqlite3_value] object V was initialized ++** using [sqlite3_bind_pointer(S,I,P)] or [sqlite3_result_pointer(C,P)], then ++** sqlite3_value_pointer(V) will return the pointer P. Otherwise, ++** sqlite3_value_pointer(V) returns a NULL. ++** + ** ^(The sqlite3_value_numeric_type() interface attempts to apply + ** numeric affinity to the value. This means that an attempt is + ** made to convert the value to an integer or floating point. If +@@ -4894,6 +4909,7 @@ SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*); + SQLITE_API const void *sqlite3_value_text16(sqlite3_value*); + SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*); + SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*); ++SQLITE_API void *sqlite3_value_pointer(sqlite3_value*); + SQLITE_API int sqlite3_value_type(sqlite3_value*); + SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*); + +@@ -4906,10 +4922,6 @@ SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*); + ** information can be used to pass a limited amount of context from + ** one SQL function to another. Use the [sqlite3_result_subtype()] + ** routine to set the subtype for the return value of an SQL function. +-** +-** SQLite makes no use of subtype itself. It merely passes the subtype +-** from the result of one [application-defined SQL function] into the +-** input of another. + */ + SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value*); + +@@ -5187,6 +5199,14 @@ typedef void (*sqlite3_destructor_type)(void*); + ** [unprotected sqlite3_value] object is required, so either + ** kind of [sqlite3_value] object can be used with this interface. + ** ++** ^The sqlite3_result_pointer(C,P) interface sets the result to an ++** SQL NULL value, just like [sqlite3_result_null(C)], except that it ++** also associates the host-language pointer P with that NULL value such ++** that the pointer can be retrieved within an ++** [application-defined SQL function] using [sqlite3_value_pointer()]. ++** This mechanism can be used to pass non-SQL values between ++** application-defined functions. ++** + ** If these routines are called from within the different thread + ** than the one containing the application-defined function that received + ** the [sqlite3_context] pointer, the results are undefined. +@@ -5210,6 +5230,7 @@ SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(* + SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); + SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); + SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*); ++SQLITE_API void sqlite3_result_pointer(sqlite3_context*, void*); + SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n); + SQLITE_API int sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n); + +@@ -18089,6 +18110,7 @@ struct Mem { + double r; /* Real value used when MEM_Real is set in flags */ + i64 i; /* Integer value used when MEM_Int is set in flags */ + int nZero; /* Used when bit MEM_Zero is set in flags */ ++ void *pPtr; /* Pointer when flags=MEM_NULL and eSubtype='p' */ + FuncDef *pDef; /* Used only when flags==MEM_Agg */ + RowSet *pRowSet; /* Used only when flags==MEM_RowSet */ + VdbeFrame *pFrame; /* Used when flags==MEM_Frame */ +@@ -18374,6 +18396,7 @@ SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64); + #else + SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double); + #endif ++SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(Mem*, void*); + SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16); + SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*); + SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int); +@@ -70280,6 +70303,17 @@ SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){ + } + } + ++/* ++** Set the value stored in *pMem should already be a NULL. ++** Also store a pointer to go with it. ++*/ ++SQLITE_PRIVATE void sqlite3VdbeMemSetPointer(Mem *pMem, void *pPtr){ ++ assert( pMem->flags==MEM_Null ); ++ pMem->flags = MEM_Null|MEM_Subtype; ++ pMem->u.pPtr = pPtr; ++ pMem->eSubtype = 'p'; ++} ++ + #ifndef SQLITE_OMIT_FLOATING_POINT + /* + ** Delete any previous value and set the value stored in *pMem to val, +@@ -76159,6 +76193,14 @@ SQLITE_API unsigned int sqlite3_value_subtype(sqlite3_value *pVal){ + Mem *pMem = (Mem*)pVal; + return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0); + } ++SQLITE_API void *sqlite3_value_pointer(sqlite3_value *pVal){ ++ Mem *p = (Mem*)pVal; ++ if( (p->flags & MEM_TypeMask)==(MEM_Null|MEM_Subtype) && p->eSubtype=='p' ){ ++ return p->u.pPtr; ++ }else{ ++ return 0; ++ } ++} + SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){ + return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8); + } +@@ -76337,6 +76379,12 @@ SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){ + assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) ); + sqlite3VdbeMemSetNull(pCtx->pOut); + } ++SQLITE_API void sqlite3_result_pointer(sqlite3_context *pCtx, void *pPtr){ ++ Mem *pOut = pCtx->pOut; ++ assert( sqlite3_mutex_held(pOut->db->mutex) ); ++ sqlite3VdbeMemSetNull(pOut); ++ sqlite3VdbeMemSetPointer(pOut, pPtr); ++} + SQLITE_API void sqlite3_result_subtype(sqlite3_context *pCtx, unsigned int eSubtype){ + Mem *pOut = pCtx->pOut; + assert( sqlite3_mutex_held(pOut->db->mutex) ); +@@ -77322,6 +77370,16 @@ SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){ + } + return rc; + } ++SQLITE_API int sqlite3_bind_pointer(sqlite3_stmt *pStmt, int i, void *pPtr){ ++ int rc; ++ Vdbe *p = (Vdbe*)pStmt; ++ rc = vdbeUnbind(p, i); ++ if( rc==SQLITE_OK ){ ++ sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr); ++ sqlite3_mutex_leave(p->db->mutex); ++ } ++ return rc; ++} + SQLITE_API int sqlite3_bind_text( + sqlite3_stmt *pStmt, + int i, +@@ -148237,9 +148295,8 @@ static int fts3ColumnMethod( + sqlite3_result_int64(pCtx, pCsr->iPrevId); + }else if( iCol==p->nColumn ){ + /* The extra column whose name is the same as the table. +- ** Return a blob which is a pointer to the cursor. */ +- sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT); +- sqlite3_result_subtype(pCtx, '3'); ++ ** Return a pointer to the cursor. */ ++ sqlite3_result_pointer(pCtx, pCsr); + }else if( iCol==p->nColumn+2 && pCsr->pExpr ){ + sqlite3_result_int64(pCtx, pCsr->iLangid); + }else{ +@@ -148451,17 +148508,13 @@ static int fts3FunctionArg( + sqlite3_value *pVal, /* argv[0] passed to function */ + Fts3Cursor **ppCsr /* OUT: Store cursor handle here */ + ){ +- Fts3Cursor *pRet; +- if( sqlite3_value_type(pVal)!=SQLITE_BLOB +- || sqlite3_value_subtype(pVal)!='3' +- || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *) +- ){ ++ Fts3Cursor *pRet = (Fts3Cursor*)sqlite3_value_pointer(pVal); ++ if( pRet==0 ){ + char *zErr = sqlite3_mprintf(""illegal first argument to %s"", zFunc); + sqlite3_result_error(pContext, zErr, -1); + sqlite3_free(zErr); + return SQLITE_ERROR; + } +- memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *)); + *ppCsr = pRet; + return SQLITE_OK; + }",1151,1482,2048 +4062,"asmlinkage long compat_sys_socketcall(int call, u32 __user *args) +{ + int ret; + u32 a[6]; + u32 a0, a1; + + if (call < SYS_SOCKET || call > SYS_SENDMMSG) + return -EINVAL; + if (copy_from_user(a, args, nas[call])) + return -EFAULT; + a0 = a[0]; + a1 = a[1]; + + switch (call) { + case SYS_SOCKET: + ret = sys_socket(a0, a1, a[2]); + break; + case SYS_BIND: + ret = sys_bind(a0, compat_ptr(a1), a[2]); + break; + case SYS_CONNECT: + ret = sys_connect(a0, compat_ptr(a1), a[2]); + break; + case SYS_LISTEN: + ret = sys_listen(a0, a1); + break; + case SYS_ACCEPT: + ret = sys_accept4(a0, compat_ptr(a1), compat_ptr(a[2]), 0); + break; + case SYS_GETSOCKNAME: + ret = sys_getsockname(a0, compat_ptr(a1), compat_ptr(a[2])); + break; + case SYS_GETPEERNAME: + ret = sys_getpeername(a0, compat_ptr(a1), compat_ptr(a[2])); + break; + case SYS_SOCKETPAIR: + ret = sys_socketpair(a0, a1, a[2], compat_ptr(a[3])); + break; + case SYS_SEND: + ret = sys_send(a0, compat_ptr(a1), a[2], a[3]); + break; + case SYS_SENDTO: + ret = sys_sendto(a0, compat_ptr(a1), a[2], a[3], compat_ptr(a[4]), a[5]); + break; + case SYS_RECV: + ret = compat_sys_recv(a0, compat_ptr(a1), a[2], a[3]); + break; + case SYS_RECVFROM: + ret = compat_sys_recvfrom(a0, compat_ptr(a1), a[2], a[3], + compat_ptr(a[4]), compat_ptr(a[5])); + break; + case SYS_SHUTDOWN: + ret = sys_shutdown(a0, a1); + break; + case SYS_SETSOCKOPT: + ret = compat_sys_setsockopt(a0, a1, a[2], + compat_ptr(a[3]), a[4]); + break; + case SYS_GETSOCKOPT: + ret = compat_sys_getsockopt(a0, a1, a[2], + compat_ptr(a[3]), compat_ptr(a[4])); + break; + case SYS_SENDMSG: + ret = compat_sys_sendmsg(a0, compat_ptr(a1), a[2]); + break; + case SYS_SENDMMSG: + ret = compat_sys_sendmmsg(a0, compat_ptr(a1), a[2], a[3]); + break; + case SYS_RECVMSG: + ret = compat_sys_recvmsg(a0, compat_ptr(a1), a[2]); + break; + case SYS_RECVMMSG: + ret = compat_sys_recvmmsg(a0, compat_ptr(a1), a[2], a[3], + compat_ptr(a[4])); + break; + case SYS_ACCEPT4: + ret = sys_accept4(a0, compat_ptr(a1), compat_ptr(a[2]), a[3]); + break; + default: + ret = -EINVAL; + break; + } + return ret; +} +",0,"asmlinkage long compat_sys_socketcall(int call, u32 __user *args) +{ + int ret; + u32 a[6]; + u32 a0, a1; + + if (call < SYS_SOCKET || call > SYS_SENDMMSG) + return -EINVAL; + if (copy_from_user(a, args, nas[call])) + return -EFAULT; + a0 = a[0]; + a1 = a[1]; + + switch (call) { + case SYS_SOCKET: + ret = sys_socket(a0, a1, a[2]); + break; + case SYS_BIND: + ret = sys_bind(a0, compat_ptr(a1), a[2]); + break; + case SYS_CONNECT: + ret = sys_connect(a0, compat_ptr(a1), a[2]); + break; + case SYS_LISTEN: + ret = sys_listen(a0, a1); + break; + case SYS_ACCEPT: + ret = sys_accept4(a0, compat_ptr(a1), compat_ptr(a[2]), 0); + break; + case SYS_GETSOCKNAME: + ret = sys_getsockname(a0, compat_ptr(a1), compat_ptr(a[2])); + break; + case SYS_GETPEERNAME: + ret = sys_getpeername(a0, compat_ptr(a1), compat_ptr(a[2])); + break; + case SYS_SOCKETPAIR: + ret = sys_socketpair(a0, a1, a[2], compat_ptr(a[3])); + break; + case SYS_SEND: + ret = sys_send(a0, compat_ptr(a1), a[2], a[3]); + break; + case SYS_SENDTO: + ret = sys_sendto(a0, compat_ptr(a1), a[2], a[3], compat_ptr(a[4]), a[5]); + break; + case SYS_RECV: + ret = compat_sys_recv(a0, compat_ptr(a1), a[2], a[3]); + break; + case SYS_RECVFROM: + ret = compat_sys_recvfrom(a0, compat_ptr(a1), a[2], a[3], + compat_ptr(a[4]), compat_ptr(a[5])); + break; + case SYS_SHUTDOWN: + ret = sys_shutdown(a0, a1); + break; + case SYS_SETSOCKOPT: + ret = compat_sys_setsockopt(a0, a1, a[2], + compat_ptr(a[3]), a[4]); + break; + case SYS_GETSOCKOPT: + ret = compat_sys_getsockopt(a0, a1, a[2], + compat_ptr(a[3]), compat_ptr(a[4])); + break; + case SYS_SENDMSG: + ret = compat_sys_sendmsg(a0, compat_ptr(a1), a[2]); + break; + case SYS_SENDMMSG: + ret = compat_sys_sendmmsg(a0, compat_ptr(a1), a[2], a[3]); + break; + case SYS_RECVMSG: + ret = compat_sys_recvmsg(a0, compat_ptr(a1), a[2]); + break; + case SYS_RECVMMSG: + ret = compat_sys_recvmmsg(a0, compat_ptr(a1), a[2], a[3], + compat_ptr(a[4])); + break; + case SYS_ACCEPT4: + ret = sys_accept4(a0, compat_ptr(a1), compat_ptr(a[2]), a[3]); + break; + default: + ret = -EINVAL; + break; + } + return ret; +} +","@@ -780,21 +780,16 @@ asmlinkage long compat_sys_recvmmsg(int fd, struct compat_mmsghdr __user *mmsg, + if (flags & MSG_CMSG_COMPAT) + return -EINVAL; + +- if (COMPAT_USE_64BIT_TIME) +- return __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen, +- flags | MSG_CMSG_COMPAT, +- (struct timespec *) timeout); +- + if (timeout == NULL) + return __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen, + flags | MSG_CMSG_COMPAT, NULL); + +- if (get_compat_timespec(&ktspec, timeout)) ++ if (compat_get_timespec(&ktspec, timeout)) + return -EFAULT; + + datagrams = __sys_recvmmsg(fd, (struct mmsghdr __user *)mmsg, vlen, + flags | MSG_CMSG_COMPAT, &ktspec); +- if (datagrams > 0 && put_compat_timespec(&ktspec, timeout)) ++ if (datagrams > 0 && compat_put_timespec(&ktspec, timeout)) + datagrams = -EFAULT; + + return datagrams;",723,1054,2048 +18496,"xmlParsePI(xmlParserCtxtPtr ctxt) { + xmlChar *buf = NULL; + int len = 0; + int size = XML_PARSER_BUFFER_SIZE; + int cur, l; + const xmlChar *target; + xmlParserInputState state; + int count = 0; + + if ((RAW == '<') && (NXT(1) == '?')) { + xmlParserInputPtr input = ctxt->input; + state = ctxt->instate; + ctxt->instate = XML_PARSER_PI; + /* + * this is a Processing Instruction. + */ + SKIP(2); + SHRINK; + + /* + * Parse the target name and check for special support like + * namespace. + */ + target = xmlParsePITarget(ctxt); + if (target != NULL) { + if ((RAW == '?') && (NXT(1) == '>')) { + if (input != ctxt->input) { + xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY, + ""PI declaration doesn't start and stop in the same entity\n""); + } + SKIP(2); + + /* + * SAX: PI detected. + */ + if ((ctxt->sax) && (!ctxt->disableSAX) && + (ctxt->sax->processingInstruction != NULL)) + ctxt->sax->processingInstruction(ctxt->userData, + target, NULL); + if (ctxt->instate != XML_PARSER_EOF) + ctxt->instate = state; + return; + } + buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); + if (buf == NULL) { + xmlErrMemory(ctxt, NULL); + ctxt->instate = state; + return; + } + cur = CUR; + if (!IS_BLANK(cur)) { + xmlFatalErrMsgStr(ctxt, XML_ERR_SPACE_REQUIRED, + ""ParsePI: PI %s space expected\n"", target); + } + SKIP_BLANKS; + cur = CUR_CHAR(l); + while (IS_CHAR(cur) && /* checked */ + ((cur != '?') || (NXT(1) != '>'))) { + if (len + 5 >= size) { + xmlChar *tmp; + + size *= 2; + tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); + if (tmp == NULL) { + xmlErrMemory(ctxt, NULL); + xmlFree(buf); + ctxt->instate = state; + return; + } + buf = tmp; + } + count++; + if (count > 50) { + GROW; + count = 0; + } + COPY_BUF(l,buf,len,cur); + NEXTL(l); + cur = CUR_CHAR(l); + if (cur == 0) { + SHRINK; + GROW; + cur = CUR_CHAR(l); + } + } + buf[len] = 0; + if (cur != '?') { + xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED, + ""ParsePI: PI %s never end ...\n"", target); + } else { + if (input != ctxt->input) { + xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, + ""PI declaration doesn't start and stop in the same entity\n""); + } + SKIP(2); + +#ifdef LIBXML_CATALOG_ENABLED + if (((state == XML_PARSER_MISC) || + (state == XML_PARSER_START)) && + (xmlStrEqual(target, XML_CATALOG_PI))) { + xmlCatalogAllow allow = xmlCatalogGetDefaults(); + if ((allow == XML_CATA_ALLOW_DOCUMENT) || + (allow == XML_CATA_ALLOW_ALL)) + xmlParseCatalogPI(ctxt, buf); + } +#endif + + + /* + * SAX: PI detected. + */ + if ((ctxt->sax) && (!ctxt->disableSAX) && + (ctxt->sax->processingInstruction != NULL)) + ctxt->sax->processingInstruction(ctxt->userData, + target, buf); + } + xmlFree(buf); + } else { + xmlFatalErr(ctxt, XML_ERR_PI_NOT_STARTED, NULL); + } + if (ctxt->instate != XML_PARSER_EOF) + ctxt->instate = state; + } +} +",1,"xmlParsePI(xmlParserCtxtPtr ctxt) { + xmlChar *buf = NULL; + int len = 0; + int size = XML_PARSER_BUFFER_SIZE; + int cur, l; + const xmlChar *target; + xmlParserInputState state; + int count = 0; + + if ((RAW == '<') && (NXT(1) == '?')) { + xmlParserInputPtr input = ctxt->input; + state = ctxt->instate; + ctxt->instate = XML_PARSER_PI; + /* + * this is a Processing Instruction. + */ + SKIP(2); + SHRINK; + + /* + * Parse the target name and check for special support like + * namespace. + */ + target = xmlParsePITarget(ctxt); + if (target != NULL) { + if ((RAW == '?') && (NXT(1) == '>')) { + if (input != ctxt->input) { + xmlFatalErrMsg(ctxt, XML_ERR_ENTITY_BOUNDARY, + ""PI declaration doesn't start and stop in the same entity\n""); + } + SKIP(2); + + /* + * SAX: PI detected. + */ + if ((ctxt->sax) && (!ctxt->disableSAX) && + (ctxt->sax->processingInstruction != NULL)) + ctxt->sax->processingInstruction(ctxt->userData, + target, NULL); + if (ctxt->instate != XML_PARSER_EOF) + ctxt->instate = state; + return; + } + buf = (xmlChar *) xmlMallocAtomic(size * sizeof(xmlChar)); + if (buf == NULL) { + xmlErrMemory(ctxt, NULL); + ctxt->instate = state; + return; + } + cur = CUR; + if (!IS_BLANK(cur)) { + xmlFatalErrMsgStr(ctxt, XML_ERR_SPACE_REQUIRED, + ""ParsePI: PI %s space expected\n"", target); + } + SKIP_BLANKS; + cur = CUR_CHAR(l); + while (IS_CHAR(cur) && /* checked */ + ((cur != '?') || (NXT(1) != '>'))) { + if (len + 5 >= size) { + xmlChar *tmp; + + size *= 2; + tmp = (xmlChar *) xmlRealloc(buf, size * sizeof(xmlChar)); + if (tmp == NULL) { + xmlErrMemory(ctxt, NULL); + xmlFree(buf); + ctxt->instate = state; + return; + } + buf = tmp; + } + count++; + if (count > 50) { + GROW; + if (ctxt->instate == XML_PARSER_EOF) { + xmlFree(buf); + return; + } + count = 0; + } + COPY_BUF(l,buf,len,cur); + NEXTL(l); + cur = CUR_CHAR(l); + if (cur == 0) { + SHRINK; + GROW; + cur = CUR_CHAR(l); + } + } + buf[len] = 0; + if (cur != '?') { + xmlFatalErrMsgStr(ctxt, XML_ERR_PI_NOT_FINISHED, + ""ParsePI: PI %s never end ...\n"", target); + } else { + if (input != ctxt->input) { + xmlFatalErrMsg(ctxt, XML_ERR_SPACE_REQUIRED, + ""PI declaration doesn't start and stop in the same entity\n""); + } + SKIP(2); + +#ifdef LIBXML_CATALOG_ENABLED + if (((state == XML_PARSER_MISC) || + (state == XML_PARSER_START)) && + (xmlStrEqual(target, XML_CATALOG_PI))) { + xmlCatalogAllow allow = xmlCatalogGetDefaults(); + if ((allow == XML_CATA_ALLOW_DOCUMENT) || + (allow == XML_CATA_ALLOW_ALL)) + xmlParseCatalogPI(ctxt, buf); + } +#endif + + + /* + * SAX: PI detected. + */ + if ((ctxt->sax) && (!ctxt->disableSAX) && + (ctxt->sax->processingInstruction != NULL)) + ctxt->sax->processingInstruction(ctxt->userData, + target, buf); + } + xmlFree(buf); + } else { + xmlFatalErr(ctxt, XML_ERR_PI_NOT_STARTED, NULL); + } + if (ctxt->instate != XML_PARSER_EOF) + ctxt->instate = state; + } +} +","@@ -2013,6 +2013,8 @@ xmlPushInput(xmlParserCtxtPtr ctxt, xmlParserInputPtr input) { + ""Pushing input %d : %.30s\n"", ctxt->inputNr+1, input->cur); + } + ret = inputPush(ctxt, input); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + GROW; + return(ret); + } +@@ -2049,6 +2051,8 @@ xmlParseCharRef(xmlParserCtxtPtr ctxt) { + if (count++ > 20) { + count = 0; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(0); + } + if ((RAW >= '0') && (RAW <= '9')) + val = val * 16 + (CUR - '0'); +@@ -2080,6 +2084,8 @@ xmlParseCharRef(xmlParserCtxtPtr ctxt) { + if (count++ > 20) { + count = 0; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(0); + } + if ((RAW >= '0') && (RAW <= '9')) + val = val * 10 + (CUR - '0'); +@@ -2366,6 +2372,8 @@ xmlParserHandlePEReference(xmlParserCtxtPtr ctxt) { + NEXT; + if ((ctxt->sax != NULL) && (ctxt->sax->getParameterEntity != NULL)) + entity = ctxt->sax->getParameterEntity(ctxt->userData, name); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + if (entity == NULL) { + + /* +@@ -2428,6 +2436,8 @@ xmlParserHandlePEReference(xmlParserCtxtPtr ctxt) { + * the amount of data in the buffer. + */ + GROW ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + if ((ctxt->input->end - ctxt->input->cur)>=4) { + start[0] = RAW; + start[1] = NXT(1); +@@ -3046,6 +3056,8 @@ xmlParseNameComplex(xmlParserCtxtPtr ctxt) { + * Handler for more complex cases + */ + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + c = CUR_CHAR(l); + if ((ctxt->options & XML_PARSE_OLD10) == 0) { + /* +@@ -3097,6 +3109,8 @@ xmlParseNameComplex(xmlParserCtxtPtr ctxt) { + if (count++ > 100) { + count = 0; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + } + len += l; + NEXTL(l); +@@ -3121,6 +3135,8 @@ xmlParseNameComplex(xmlParserCtxtPtr ctxt) { + if (count++ > 100) { + count = 0; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + } + len += l; + NEXTL(l); +@@ -3214,6 +3230,8 @@ xmlParseNCNameComplex(xmlParserCtxtPtr ctxt) { + if (count++ > 100) { + count = 0; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + } + len += l; + NEXTL(l); +@@ -3294,6 +3312,8 @@ xmlParseNameAndCompare(xmlParserCtxtPtr ctxt, xmlChar const *other) { + const xmlChar *ret; + + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + + in = ctxt->input->cur; + while (*in != 0 && *in == *cmp) { +@@ -3421,6 +3441,8 @@ xmlParseNmtoken(xmlParserCtxtPtr ctxt) { + #endif + + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + c = CUR_CHAR(l); + + while (xmlIsNameChar(ctxt, c)) { +@@ -3449,6 +3471,10 @@ xmlParseNmtoken(xmlParserCtxtPtr ctxt) { + if (count++ > 100) { + count = 0; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buffer); ++ return(NULL); ++ } + } + if (len + 10 > max) { + xmlChar *tmp; +@@ -3519,6 +3545,10 @@ xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) { + ctxt->instate = XML_PARSER_ENTITY_VALUE; + input = ctxt->input; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return(NULL); ++ } + NEXT; + c = CUR_CHAR(l); + /* +@@ -3530,8 +3560,8 @@ xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) { + * In practice it means we stop the loop only when back at parsing + * the initial entity and the quote is found + */ +- while ((IS_CHAR(c)) && ((c != stop) || /* checked */ +- (ctxt->input != input))) { ++ while (((IS_CHAR(c)) && ((c != stop) || /* checked */ ++ (ctxt->input != input))) && (ctxt->instate != XML_PARSER_EOF)) { + if (len + 5 >= size) { + xmlChar *tmp; + +@@ -3560,6 +3590,10 @@ xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) { + } + } + buf[len] = 0; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return(NULL); ++ } + + /* + * Raise problem w.r.t. '&' and '%' being used in non-entities +@@ -3607,12 +3641,12 @@ xmlParseEntityValue(xmlParserCtxtPtr ctxt, xmlChar **orig) { + */ + ret = xmlStringDecodeEntities(ctxt, buf, XML_SUBSTITUTE_PEREF, + 0, 0, 0); +- if (orig != NULL) ++ if (orig != NULL) + *orig = buf; + else + xmlFree(buf); + } +- ++ + return(ret); + } + +@@ -3663,8 +3697,9 @@ xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) { + * OK loop until we reach one of the ending char or a size limit. + */ + c = CUR_CHAR(l); +- while ((NXT(0) != limit) && /* checked */ +- (IS_CHAR(c)) && (c != '<')) { ++ while (((NXT(0) != limit) && /* checked */ ++ (IS_CHAR(c)) && (c != '<')) && ++ (ctxt->instate != XML_PARSER_EOF)) { + if (c == 0) break; + if (c == '&') { + in_space = 0; +@@ -3799,6 +3834,9 @@ xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) { + GROW; + c = CUR_CHAR(l); + } ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto error; ++ + if ((in_space) && (normalize)) { + while ((len > 0) && (buf[len - 1] == 0x20)) len--; + } +@@ -3820,6 +3858,7 @@ xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) { + + mem_error: + xmlErrMemory(ctxt, NULL); ++error: + if (buf != NULL) + xmlFree(buf); + if (rep != NULL) +@@ -3925,6 +3964,10 @@ xmlParseSystemLiteral(xmlParserCtxtPtr ctxt) { + if (count > 50) { + GROW; + count = 0; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return(NULL); ++ } + } + COPY_BUF(l,buf,len,cur); + NEXTL(l); +@@ -4002,6 +4045,10 @@ xmlParsePubidLiteral(xmlParserCtxtPtr ctxt) { + if (count > 50) { + GROW; + count = 0; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return(NULL); ++ } + } + NEXT; + cur = CUR; +@@ -4208,6 +4255,8 @@ xmlParseCharData(xmlParserCtxtPtr ctxt, int cdata) { + } + SHRINK; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + in = ctxt->input->cur; + } while (((*in >= 0x20) && (*in <= 0x7F)) || (*in == 0x09)); + nbchar = 0; +@@ -4276,6 +4325,8 @@ xmlParseCharDataComplex(xmlParserCtxtPtr ctxt, int cdata) { + if (count > 50) { + GROW; + count = 0; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + } + NEXTL(l); + cur = CUR_CHAR(l); +@@ -4476,6 +4527,10 @@ xmlParseCommentComplex(xmlParserCtxtPtr ctxt, xmlChar *buf, int len, int size) { + if (count > 50) { + GROW; + count = 0; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return; ++ } + } + NEXTL(l); + cur = CUR_CHAR(l); +@@ -4626,6 +4681,10 @@ xmlParseComment(xmlParserCtxtPtr ctxt) { + } + SHRINK; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return; ++ } + in = ctxt->input->cur; + if (*in == '-') { + if (in[1] == '-') { +@@ -4644,7 +4703,8 @@ xmlParseComment(xmlParserCtxtPtr ctxt) { + } + if (buf != NULL) + xmlFree(buf); +- ctxt->instate = state; ++ if (ctxt->instate != XML_PARSER_EOF) ++ ctxt->instate = state; + return; + } + if (buf != NULL) +@@ -4862,6 +4922,10 @@ xmlParsePI(xmlParserCtxtPtr ctxt) { + count++; + if (count > 50) { + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return; ++ } + count = 0; + } + COPY_BUF(l,buf,len,cur); +@@ -5211,6 +5275,8 @@ xmlParseEntityDecl(xmlParserCtxtPtr ctxt) { + } + } + } ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + SKIP_BLANKS; + if (RAW != '>') { + xmlFatalErrMsgStr(ctxt, XML_ERR_ENTITY_NOT_FINISHED, +@@ -5602,7 +5668,7 @@ xmlParseAttributeListDecl(xmlParserCtxtPtr ctxt) { + } + SKIP_BLANKS; + GROW; +- while (RAW != '>') { ++ while ((RAW != '>') && (ctxt->instate != XML_PARSER_EOF)) { + const xmlChar *check = CUR_PTR; + int type; + int def; +@@ -5751,7 +5817,7 @@ xmlParseElementMixedContentDecl(xmlParserCtxtPtr ctxt, int inputchk) { + ret = cur = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_PCDATA); + if (ret == NULL) return(NULL); + } +- while (RAW == '|') { ++ while ((RAW == '|') && (ctxt->instate != XML_PARSER_EOF)) { + NEXT; + if (elem == NULL) { + ret = xmlNewDocElementContent(ctxt->myDoc, NULL, XML_ELEMENT_CONTENT_OR); +@@ -5895,7 +5961,7 @@ xmlParseElementChildrenContentDeclPriv(xmlParserCtxtPtr ctxt, int inputchk, + } + SKIP_BLANKS; + SHRINK; +- while (RAW != ')') { ++ while ((RAW != ')') && (ctxt->instate != XML_PARSER_EOF)) { + /* + * Each loop we parse one separator and one element. + */ +@@ -6174,6 +6240,8 @@ xmlParseElementContentDecl(xmlParserCtxtPtr ctxt, const xmlChar *name, + } + NEXT; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + SKIP_BLANKS; + if (CMP7(CUR_PTR, '#', 'P', 'C', 'D', 'A', 'T', 'A')) { + tree = xmlParseElementMixedContentDecl(ctxt, inputid); +@@ -6341,8 +6409,8 @@ xmlParseConditionalSections(xmlParserCtxtPtr ctxt) { + ""Entering INCLUDE Conditional Section\n""); + } + +- while ((RAW != 0) && ((RAW != ']') || (NXT(1) != ']') || +- (NXT(2) != '>'))) { ++ while (((RAW != 0) && ((RAW != ']') || (NXT(1) != ']') || ++ (NXT(2) != '>'))) && (ctxt->instate != XML_PARSER_EOF)) { + const xmlChar *check = CUR_PTR; + unsigned int cons = ctxt->input->consumed; + +@@ -6410,7 +6478,8 @@ xmlParseConditionalSections(xmlParserCtxtPtr ctxt) { + if (ctxt->recovery == 0) ctxt->disableSAX = 1; + ctxt->instate = XML_PARSER_IGNORE; + +- while ((depth >= 0) && (RAW != 0)) { ++ while (((depth >= 0) && (RAW != 0)) && ++ (ctxt->instate != XML_PARSER_EOF)) { + if ((RAW == '<') && (NXT(1) == '!') && (NXT(2) == '[')) { + depth++; + SKIP(3); +@@ -6681,7 +6750,7 @@ xmlParseExternalSubset(xmlParserCtxtPtr ctxt, const xmlChar *ExternalID, + break; + } + } +- ++ + if (RAW != 0) { + xmlFatalErr(ctxt, XML_ERR_EXT_SUBSET_NOT_FINISHED, NULL); + } +@@ -7127,6 +7196,8 @@ xmlParseEntityRef(xmlParserCtxtPtr ctxt) { + xmlEntityPtr ent = NULL; + + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + + if (RAW != '&') + return(NULL); +@@ -7172,6 +7243,8 @@ xmlParseEntityRef(xmlParserCtxtPtr ctxt) { + ent = xmlSAX2GetEntity(ctxt, name); + } + } ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + /* + * [ WFC: Entity Declared ] + * In a document without any DTD, a document with only an +@@ -7362,6 +7435,10 @@ xmlParseStringEntityRef(xmlParserCtxtPtr ctxt, const xmlChar ** str) { + ent = xmlSAX2GetEntity(ctxt, name); + } + } ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(name); ++ return(NULL); ++ } + + /* + * [ WFC: Entity Declared ] +@@ -7523,8 +7600,9 @@ xmlParsePEReference(xmlParserCtxtPtr ctxt) + */ + if ((ctxt->sax != NULL) && + (ctxt->sax->getParameterEntity != NULL)) +- entity = ctxt->sax->getParameterEntity(ctxt->userData, +- name); ++ entity = ctxt->sax->getParameterEntity(ctxt->userData, name); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + if (entity == NULL) { + /* + * [ WFC: Entity Declared ] +@@ -7657,6 +7735,10 @@ xmlLoadEntityContent(xmlParserCtxtPtr ctxt, xmlEntityPtr entity) { + if (count++ > 100) { + count = 0; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlBufferFree(buf); ++ return(-1); ++ } + } + NEXTL(l); + c = CUR_CHAR(l); +@@ -7748,8 +7830,11 @@ xmlParseStringPEReference(xmlParserCtxtPtr ctxt, const xmlChar **str) { + */ + if ((ctxt->sax != NULL) && + (ctxt->sax->getParameterEntity != NULL)) +- entity = ctxt->sax->getParameterEntity(ctxt->userData, +- name); ++ entity = ctxt->sax->getParameterEntity(ctxt->userData, name); ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(name); ++ return(NULL); ++ } + if (entity == NULL) { + /* + * [ WFC: Entity Declared ] +@@ -7851,6 +7936,8 @@ xmlParseDocTypeDecl(xmlParserCtxtPtr ctxt) { + if ((ctxt->sax != NULL) && (ctxt->sax->internalSubset != NULL) && + (!ctxt->disableSAX)) + ctxt->sax->internalSubset(ctxt->userData, name, ExternalID, URI); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + + /* + * Is there any internal subset declarations ? +@@ -7890,7 +7977,7 @@ xmlParseInternalSubset(xmlParserCtxtPtr ctxt) { + * PEReferences. + * Subsequence (markupdecl | PEReference | S)* + */ +- while (RAW != ']') { ++ while ((RAW != ']') && (ctxt->instate != XML_PARSER_EOF)) { + const xmlChar *check = CUR_PTR; + unsigned int cons = ctxt->input->consumed; + +@@ -8076,9 +8163,9 @@ xmlParseStartTag(xmlParserCtxtPtr ctxt) { + SKIP_BLANKS; + GROW; + +- while ((RAW != '>') && ++ while (((RAW != '>') && + ((RAW != '/') || (NXT(1) != '>')) && +- (IS_BYTE_CHAR(RAW))) { ++ (IS_BYTE_CHAR(RAW))) && (ctxt->instate != XML_PARSER_EOF)) { + const xmlChar *q = CUR_PTR; + unsigned int cons = ctxt->input->consumed; + +@@ -8502,6 +8589,8 @@ xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc, + if (in >= end) { + const xmlChar *oldbase = ctxt->input->base; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + if (oldbase != ctxt->input->base) { + long delta = ctxt->input->base - oldbase; + start = start + delta; +@@ -8516,6 +8605,8 @@ xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc, + if (in >= end) { + const xmlChar *oldbase = ctxt->input->base; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + if (oldbase != ctxt->input->base) { + long delta = ctxt->input->base - oldbase; + start = start + delta; +@@ -8536,6 +8627,8 @@ xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc, + if (in >= end) { + const xmlChar *oldbase = ctxt->input->base; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + if (oldbase != ctxt->input->base) { + long delta = ctxt->input->base - oldbase; + start = start + delta; +@@ -8553,6 +8646,8 @@ xmlParseAttValueInternal(xmlParserCtxtPtr ctxt, int *len, int *alloc, + if (in >= end) { + const xmlChar *oldbase = ctxt->input->base; + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(NULL); + if (oldbase != ctxt->input->base) { + long delta = ctxt->input->base - oldbase; + start = start + delta; +@@ -8784,9 +8879,9 @@ xmlParseStartTag2(xmlParserCtxtPtr ctxt, const xmlChar **pref, + GROW; + if (ctxt->input->base != base) goto base_changed; + +- while ((RAW != '>') && ++ while (((RAW != '>') && + ((RAW != '/') || (NXT(1) != '>')) && +- (IS_BYTE_CHAR(RAW))) { ++ (IS_BYTE_CHAR(RAW))) && (ctxt->instate != XML_PARSER_EOF)) { + const xmlChar *q = CUR_PTR; + unsigned int cons = ctxt->input->consumed; + int len = -1, alloc = 0; +@@ -8957,6 +9052,8 @@ xmlParseStartTag2(xmlParserCtxtPtr ctxt, const xmlChar **pref, + failed: + + GROW ++ if (ctxt->instate == XML_PARSER_EOF) ++ break; + if (ctxt->input->base != base) goto base_changed; + if ((RAW == '>') || (((RAW == '/') && (NXT(1) == '>')))) + break; +@@ -9194,6 +9291,8 @@ xmlParseEndTag2(xmlParserCtxtPtr ctxt, const xmlChar *prefix, + * We should definitely be at the ending ""S? '>'"" part + */ + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + SKIP_BLANKS; + if ((!IS_BYTE_CHAR(RAW)) || (RAW != '>')) { + xmlFatalErr(ctxt, XML_ERR_GT_REQUIRED, NULL); +@@ -9302,6 +9401,10 @@ xmlParseCDSect(xmlParserCtxtPtr ctxt) { + count++; + if (count > 50) { + GROW; ++ if (ctxt->instate == XML_PARSER_EOF) { ++ xmlFree(buf); ++ return; ++ } + count = 0; + } + NEXTL(l); +@@ -9550,6 +9653,8 @@ xmlParseElement(xmlParserCtxtPtr ctxt) { + * Parse the content of the element: + */ + xmlParseContent(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return; + if (!IS_BYTE_CHAR(RAW)) { + xmlFatalErrMsgStrIntStr(ctxt, XML_ERR_TAG_NOT_FINISHED, + ""Premature end of data in tag %s line %d\n"", +@@ -10065,9 +10170,10 @@ xmlParseXMLDecl(xmlParserCtxtPtr ctxt) { + + void + xmlParseMisc(xmlParserCtxtPtr ctxt) { +- while (((RAW == '<') && (NXT(1) == '?')) || +- (CMP4(CUR_PTR, '<', '!', '-', '-')) || +- IS_BLANK_CH(CUR)) { ++ while ((ctxt->instate != XML_PARSER_EOF) && ++ (((RAW == '<') && (NXT(1) == '?')) || ++ (CMP4(CUR_PTR, '<', '!', '-', '-')) || ++ IS_BLANK_CH(CUR))) { + if ((RAW == '<') && (NXT(1) == '?')) { + xmlParsePI(ctxt); + } else if (IS_BLANK_CH(CUR)) { +@@ -10114,6 +10220,8 @@ xmlParseDocument(xmlParserCtxtPtr ctxt) { + */ + if ((ctxt->sax) && (ctxt->sax->setDocumentLocator)) + ctxt->sax->setDocumentLocator(ctxt->userData, &xmlDefaultSAXLocator); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + + if ((ctxt->encoding == (const xmlChar *)XML_CHAR_ENCODING_NONE) && + ((ctxt->input->end - ctxt->input->cur) >= 4)) { +@@ -10165,6 +10273,8 @@ xmlParseDocument(xmlParserCtxtPtr ctxt) { + } + if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) + ctxt->sax->startDocument(ctxt->userData); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + + /* + * The Misc part of the Prolog +@@ -10184,6 +10294,8 @@ xmlParseDocument(xmlParserCtxtPtr ctxt) { + if (RAW == '[') { + ctxt->instate = XML_PARSER_DTD; + xmlParseInternalSubset(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + } + + /* +@@ -10194,6 +10306,8 @@ xmlParseDocument(xmlParserCtxtPtr ctxt) { + (!ctxt->disableSAX)) + ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, + ctxt->extSubSystem, ctxt->extSubURI); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + ctxt->inSubset = 0; + + xmlCleanSpecialAttr(ctxt); +@@ -10334,6 +10448,8 @@ xmlParseExtParsedEnt(xmlParserCtxtPtr ctxt) { + } + if ((ctxt->sax) && (ctxt->sax->startDocument) && (!ctxt->disableSAX)) + ctxt->sax->startDocument(ctxt->userData); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + + /* + * Doing validity checking on chunk doesn't make sense +@@ -10344,6 +10460,8 @@ xmlParseExtParsedEnt(xmlParserCtxtPtr ctxt) { + ctxt->depth = 0; + + xmlParseContent(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + + if ((RAW == '<') && (NXT(1) == '/')) { + xmlFatalErr(ctxt, XML_ERR_NOT_WELL_BALANCED, NULL); +@@ -10651,7 +10769,7 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + } + xmlParseGetLasts(ctxt, &lastlt, &lastgt); + +- while (1) { ++ while (ctxt->instate != XML_PARSER_EOF) { + if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) + return(0); + +@@ -10891,6 +11009,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ctxt->sax->endElement(ctxt->userData, name); + #endif /* LIBXML_SAX1_ENABLED */ + } ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + spacePop(ctxt); + if (ctxt->nameNr == 0) { + ctxt->instate = XML_PARSER_EPILOG; +@@ -11072,6 +11192,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ctxt->sax->characters(ctxt->userData, + ctxt->input->cur, tmp); + } ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + SKIPL(tmp); + ctxt->checkIndex = 0; + } +@@ -11107,6 +11229,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ctxt->sax->characters(ctxt->userData, + ctxt->input->cur, base); + } ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + SKIPL(base + 3); + ctxt->checkIndex = 0; + ctxt->instate = XML_PARSER_CONTENT; +@@ -11138,6 +11262,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ""PP: Parsing PI\n""); + #endif + xmlParsePI(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + ctxt->checkIndex = 0; + } else if ((cur == '<') && (next == '!') && + (ctxt->input->cur[2] == '-') && +@@ -11150,6 +11276,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ""PP: Parsing Comment\n""); + #endif + xmlParseComment(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + ctxt->instate = XML_PARSER_MISC; + ctxt->checkIndex = 0; + } else if ((cur == '<') && (next == '!') && +@@ -11169,6 +11297,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + #endif + ctxt->inSubset = 1; + xmlParseDocTypeDecl(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + if (RAW == '[') { + ctxt->instate = XML_PARSER_DTD; + #ifdef DEBUG_PUSH +@@ -11225,6 +11355,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ""PP: Parsing PI\n""); + #endif + xmlParsePI(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + } else if ((cur == '<') && (next == '!') && + (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { + if ((!terminate) && +@@ -11235,6 +11367,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ""PP: Parsing Comment\n""); + #endif + xmlParseComment(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + ctxt->instate = XML_PARSER_PROLOG; + } else if ((cur == '<') && (next == '!') && + (avail < 4)) { +@@ -11269,6 +11403,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ""PP: Parsing PI\n""); + #endif + xmlParsePI(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + ctxt->instate = XML_PARSER_EPILOG; + } else if ((cur == '<') && (next == '!') && + (ctxt->input->cur[2] == '-') && (ctxt->input->cur[3] == '-')) { +@@ -11280,6 +11416,8 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + ""PP: Parsing Comment\n""); + #endif + xmlParseComment(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + ctxt->instate = XML_PARSER_EPILOG; + } else if ((cur == '<') && (next == '!') && + (avail < 4)) { +@@ -11408,13 +11546,17 @@ xmlParseTryOrFinish(xmlParserCtxtPtr ctxt, int terminate) { + + found_end_int_subset: + xmlParseInternalSubset(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + ctxt->inSubset = 2; + if ((ctxt->sax != NULL) && (!ctxt->disableSAX) && + (ctxt->sax->externalSubset != NULL)) + ctxt->sax->externalSubset(ctxt->userData, ctxt->intSubName, + ctxt->extSubSystem, ctxt->extSubURI); + ctxt->inSubset = 0; + xmlCleanSpecialAttr(ctxt); ++ if (ctxt->instate == XML_PARSER_EOF) ++ goto done; + ctxt->instate = XML_PARSER_PROLOG; + ctxt->checkIndex = 0; + #ifdef DEBUG_PUSH +@@ -11537,6 +11679,8 @@ xmlParseChunk(xmlParserCtxtPtr ctxt, const char *chunk, int size, + return(XML_ERR_INTERNAL_ERROR); + if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) + return(ctxt->errNo); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(-1); + if (ctxt->instate == XML_PARSER_START) + xmlDetectSAX2(ctxt); + if ((size > 0) && (chunk != NULL) && (!terminate) && +@@ -11623,6 +11767,8 @@ xmlParseChunk(xmlParserCtxtPtr ctxt, const char *chunk, int size, + xmlParseTryOrFinish(ctxt, 0); + else + xmlParseTryOrFinish(ctxt, terminate); ++ if (ctxt->instate == XML_PARSER_EOF) ++ return(ctxt->errNo); + if ((ctxt->errNo != XML_ERR_OK) && (ctxt->disableSAX == 1)) + return(ctxt->errNo); + +@@ -11816,6 +11962,7 @@ xmlStopParser(xmlParserCtxtPtr ctxt) { + if (ctxt == NULL) + return; + ctxt->instate = XML_PARSER_EOF; ++ ctxt->errNo = XML_ERR_USER_STOP; + ctxt->disableSAX = 1; + if (ctxt->input != NULL) { + ctxt->input->cur = BAD_CAST"""";",911,1242,2048 +1897,"static void ape_dumpinfo(AVFormatContext * s, APEContext * ape_ctx) +{ +#if ENABLE_DEBUG + int i; + + av_log(s, AV_LOG_DEBUG, ""Descriptor Block:\n\n""); + av_log(s, AV_LOG_DEBUG, ""magic = \""%c%c%c%c\""\n"", ape_ctx->magic[0], ape_ctx->magic[1], ape_ctx->magic[2], ape_ctx->magic[3]); + av_log(s, AV_LOG_DEBUG, ""fileversion = %d\n"", ape_ctx->fileversion); + av_log(s, AV_LOG_DEBUG, ""descriptorlength = %d\n"", ape_ctx->descriptorlength); + av_log(s, AV_LOG_DEBUG, ""headerlength = %d\n"", ape_ctx->headerlength); + av_log(s, AV_LOG_DEBUG, ""seektablelength = %d\n"", ape_ctx->seektablelength); + av_log(s, AV_LOG_DEBUG, ""wavheaderlength = %d\n"", ape_ctx->wavheaderlength); + av_log(s, AV_LOG_DEBUG, ""audiodatalength = %d\n"", ape_ctx->audiodatalength); + av_log(s, AV_LOG_DEBUG, ""audiodatalength_high = %d\n"", ape_ctx->audiodatalength_high); + av_log(s, AV_LOG_DEBUG, ""wavtaillength = %d\n"", ape_ctx->wavtaillength); + av_log(s, AV_LOG_DEBUG, ""md5 = ""); + for (i = 0; i < 16; i++) + av_log(s, AV_LOG_DEBUG, ""%02x"", ape_ctx->md5[i]); + av_log(s, AV_LOG_DEBUG, ""\n""); + + av_log(s, AV_LOG_DEBUG, ""\nHeader Block:\n\n""); + + av_log(s, AV_LOG_DEBUG, ""compressiontype = %d\n"", ape_ctx->compressiontype); + av_log(s, AV_LOG_DEBUG, ""formatflags = %d\n"", ape_ctx->formatflags); + av_log(s, AV_LOG_DEBUG, ""blocksperframe = %d\n"", ape_ctx->blocksperframe); + av_log(s, AV_LOG_DEBUG, ""finalframeblocks = %d\n"", ape_ctx->finalframeblocks); + av_log(s, AV_LOG_DEBUG, ""totalframes = %d\n"", ape_ctx->totalframes); + av_log(s, AV_LOG_DEBUG, ""bps = %d\n"", ape_ctx->bps); + av_log(s, AV_LOG_DEBUG, ""channels = %d\n"", ape_ctx->channels); + av_log(s, AV_LOG_DEBUG, ""samplerate = %d\n"", ape_ctx->samplerate); + + av_log(s, AV_LOG_DEBUG, ""\nSeektable\n\n""); + if ((ape_ctx->seektablelength / sizeof(uint32_t)) != ape_ctx->totalframes) { + av_log(s, AV_LOG_DEBUG, ""No seektable\n""); + } else { + for (i = 0; i < ape_ctx->seektablelength / sizeof(uint32_t); i++) { + if (i < ape_ctx->totalframes - 1) { + av_log(s, AV_LOG_DEBUG, ""%8d %d (%d bytes)\n"", i, ape_ctx->seektable[i], ape_ctx->seektable[i + 1] - ape_ctx->seektable[i]); + } else { + av_log(s, AV_LOG_DEBUG, ""%8d %d\n"", i, ape_ctx->seektable[i]); + } + } + } + + av_log(s, AV_LOG_DEBUG, ""\nFrames\n\n""); + for (i = 0; i < ape_ctx->totalframes; i++) + av_log(s, AV_LOG_DEBUG, ""%8d %8lld %8d (%d samples)\n"", i, ape_ctx->frames[i].pos, ape_ctx->frames[i].size, ape_ctx->frames[i].nblocks); + + av_log(s, AV_LOG_DEBUG, ""\nCalculated information:\n\n""); + av_log(s, AV_LOG_DEBUG, ""junklength = %d\n"", ape_ctx->junklength); + av_log(s, AV_LOG_DEBUG, ""firstframe = %d\n"", ape_ctx->firstframe); + av_log(s, AV_LOG_DEBUG, ""totalsamples = %d\n"", ape_ctx->totalsamples); +#endif +} +",0,"static void ape_dumpinfo(AVFormatContext * s, APEContext * ape_ctx) +{ +#if ENABLE_DEBUG + int i; + + av_log(s, AV_LOG_DEBUG, ""Descriptor Block:\n\n""); + av_log(s, AV_LOG_DEBUG, ""magic = \""%c%c%c%c\""\n"", ape_ctx->magic[0], ape_ctx->magic[1], ape_ctx->magic[2], ape_ctx->magic[3]); + av_log(s, AV_LOG_DEBUG, ""fileversion = %d\n"", ape_ctx->fileversion); + av_log(s, AV_LOG_DEBUG, ""descriptorlength = %d\n"", ape_ctx->descriptorlength); + av_log(s, AV_LOG_DEBUG, ""headerlength = %d\n"", ape_ctx->headerlength); + av_log(s, AV_LOG_DEBUG, ""seektablelength = %d\n"", ape_ctx->seektablelength); + av_log(s, AV_LOG_DEBUG, ""wavheaderlength = %d\n"", ape_ctx->wavheaderlength); + av_log(s, AV_LOG_DEBUG, ""audiodatalength = %d\n"", ape_ctx->audiodatalength); + av_log(s, AV_LOG_DEBUG, ""audiodatalength_high = %d\n"", ape_ctx->audiodatalength_high); + av_log(s, AV_LOG_DEBUG, ""wavtaillength = %d\n"", ape_ctx->wavtaillength); + av_log(s, AV_LOG_DEBUG, ""md5 = ""); + for (i = 0; i < 16; i++) + av_log(s, AV_LOG_DEBUG, ""%02x"", ape_ctx->md5[i]); + av_log(s, AV_LOG_DEBUG, ""\n""); + + av_log(s, AV_LOG_DEBUG, ""\nHeader Block:\n\n""); + + av_log(s, AV_LOG_DEBUG, ""compressiontype = %d\n"", ape_ctx->compressiontype); + av_log(s, AV_LOG_DEBUG, ""formatflags = %d\n"", ape_ctx->formatflags); + av_log(s, AV_LOG_DEBUG, ""blocksperframe = %d\n"", ape_ctx->blocksperframe); + av_log(s, AV_LOG_DEBUG, ""finalframeblocks = %d\n"", ape_ctx->finalframeblocks); + av_log(s, AV_LOG_DEBUG, ""totalframes = %d\n"", ape_ctx->totalframes); + av_log(s, AV_LOG_DEBUG, ""bps = %d\n"", ape_ctx->bps); + av_log(s, AV_LOG_DEBUG, ""channels = %d\n"", ape_ctx->channels); + av_log(s, AV_LOG_DEBUG, ""samplerate = %d\n"", ape_ctx->samplerate); + + av_log(s, AV_LOG_DEBUG, ""\nSeektable\n\n""); + if ((ape_ctx->seektablelength / sizeof(uint32_t)) != ape_ctx->totalframes) { + av_log(s, AV_LOG_DEBUG, ""No seektable\n""); + } else { + for (i = 0; i < ape_ctx->seektablelength / sizeof(uint32_t); i++) { + if (i < ape_ctx->totalframes - 1) { + av_log(s, AV_LOG_DEBUG, ""%8d %d (%d bytes)\n"", i, ape_ctx->seektable[i], ape_ctx->seektable[i + 1] - ape_ctx->seektable[i]); + } else { + av_log(s, AV_LOG_DEBUG, ""%8d %d\n"", i, ape_ctx->seektable[i]); + } + } + } + + av_log(s, AV_LOG_DEBUG, ""\nFrames\n\n""); + for (i = 0; i < ape_ctx->totalframes; i++) + av_log(s, AV_LOG_DEBUG, ""%8d %8lld %8d (%d samples)\n"", i, ape_ctx->frames[i].pos, ape_ctx->frames[i].size, ape_ctx->frames[i].nblocks); + + av_log(s, AV_LOG_DEBUG, ""\nCalculated information:\n\n""); + av_log(s, AV_LOG_DEBUG, ""junklength = %d\n"", ape_ctx->junklength); + av_log(s, AV_LOG_DEBUG, ""firstframe = %d\n"", ape_ctx->firstframe); + av_log(s, AV_LOG_DEBUG, ""totalsamples = %d\n"", ape_ctx->totalsamples); +#endif +} +","@@ -242,6 +242,10 @@ static int ape_read_header(AVFormatContext * s, AVFormatParameters * ap) + avio_seek(pb, ape->wavheaderlength, SEEK_CUR); + } + ++ if(!ape->totalframes){ ++ av_log(s, AV_LOG_ERROR, ""No frames in the file!\n""); ++ return AVERROR(EINVAL); ++ } + if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){ + av_log(s, AV_LOG_ERROR, ""Too many frames: %d\n"", ape->totalframes); + return -1;",942,1273,2048 +5221,"proto_reg_handoff_wbxml(void) +{ + dissector_handle_t wbxml_handle; + + /* Heuristic dissectors would be declared by means of: + * heur_dissector_add(""wsp"", dissect_wbxml_heur, proto_wbxml); + */ + + wbxml_handle = find_dissector(""wbxml""); + + /* Register the WSP content types (defined as protocol port) + * for WBXML dissection. + * + * See http://www.wapforum.org/wina/wsp-content-type.htm + * + * As the media types for WSP and HTTP are the same, the WSP dissector + * uses the same string dissector table as the HTTP protocol. + */ + + /**** Well-known WBXML WSP Content-Type values ****/ + + dissector_add_string(""media_type"", + ""application/vnd.wap.wmlc"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.wap.wta-eventc"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.wap.wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.wap.sic"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.wap.slc"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.wap.coc"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.wap.connectivity-wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.wap.locc+wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.syncml+wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.syncml.dm+wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.oma.drm.rights+wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.wv.csp.wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.ms-sync.wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.ms-sync"", wbxml_handle); + + /**** Registered WBXML WSP Content-Type values ****/ + + dissector_add_string(""media_type"", + ""application/vnd.uplanet.cacheop-wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.uplanet.alert-wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.uplanet.list-wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.uplanet.listcmd-wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.uplanet.channel-wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.uplanet.bearer-choice-wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.phonecom.mmc-wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.nokia.syncset+wbxml"", wbxml_handle); + + /***** Content types that only have a textual representation *****/ + dissector_add_string(""media_type"", + ""application/x-wap-prov.browser-bookmarks"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/x-wap-prov.browser-settings"", wbxml_handle); + /* Same as application/vnd.nokia.syncset+wbxml */ + dissector_add_string(""media_type"", + ""application/x-prov.syncset+wbxml"", wbxml_handle); +} +",0,"proto_reg_handoff_wbxml(void) +{ + dissector_handle_t wbxml_handle; + + /* Heuristic dissectors would be declared by means of: + * heur_dissector_add(""wsp"", dissect_wbxml_heur, proto_wbxml); + */ + + wbxml_handle = find_dissector(""wbxml""); + + /* Register the WSP content types (defined as protocol port) + * for WBXML dissection. + * + * See http://www.wapforum.org/wina/wsp-content-type.htm + * + * As the media types for WSP and HTTP are the same, the WSP dissector + * uses the same string dissector table as the HTTP protocol. + */ + + /**** Well-known WBXML WSP Content-Type values ****/ + + dissector_add_string(""media_type"", + ""application/vnd.wap.wmlc"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.wap.wta-eventc"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.wap.wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.wap.sic"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.wap.slc"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.wap.coc"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.wap.connectivity-wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.wap.locc+wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.syncml+wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.syncml.dm+wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.oma.drm.rights+wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.wv.csp.wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.ms-sync.wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.ms-sync"", wbxml_handle); + + /**** Registered WBXML WSP Content-Type values ****/ + + dissector_add_string(""media_type"", + ""application/vnd.uplanet.cacheop-wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.uplanet.alert-wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.uplanet.list-wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.uplanet.listcmd-wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.uplanet.channel-wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.uplanet.bearer-choice-wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.phonecom.mmc-wbxml"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/vnd.nokia.syncset+wbxml"", wbxml_handle); + + /***** Content types that only have a textual representation *****/ + dissector_add_string(""media_type"", + ""application/x-wap-prov.browser-bookmarks"", wbxml_handle); + dissector_add_string(""media_type"", + ""application/x-wap-prov.browser-settings"", wbxml_handle); + /* Same as application/vnd.nokia.syncset+wbxml */ + dissector_add_string(""media_type"", + ""application/x-prov.syncset+wbxml"", wbxml_handle); +} +","@@ -7304,7 +7304,7 @@ parse_wbxml_tag_defined (proto_tree *tree, tvbuff_t *tvb, guint32 offset, + const wbxml_decoding *map) + { + guint32 tvb_len = tvb_reported_length (tvb); +- guint32 off = offset; ++ guint32 off = offset, last_off; + guint32 len; + guint str_len; + guint32 ent; +@@ -7323,6 +7323,7 @@ parse_wbxml_tag_defined (proto_tree *tree, tvbuff_t *tvb, guint32 offset, + tag_save_literal = NULL; /* Prevents compiler warning */ + + DebugLog((""parse_wbxml_tag_defined (level = %u, offset = %u)\n"", *level, offset)); ++ last_off = off; + while (off < tvb_len) { + peek = tvb_get_guint8 (tvb, off); + DebugLog((""STAG: (top of while) level = %3u, peek = 0x%02X, off = %u, tvb_len = %u\n"", *level, peek, off, tvb_len)); +@@ -7694,6 +7695,10 @@ parse_wbxml_tag_defined (proto_tree *tree, tvbuff_t *tvb, guint32 offset, + /* TODO: Do I have to reset code page here? */ + } + } /* if (tag & 0x3F) >= 5 */ ++ if (off < last_off) { ++ THROW(ReportedBoundsError); ++ } ++ last_off = off; + } /* while */ + DebugLog((""STAG: level = %u, Return: len = %u (end of function body)\n"", *level, off - offset)); + return (off - offset); +@@ -7711,7 +7716,7 @@ parse_wbxml_tag (proto_tree *tree, tvbuff_t *tvb, guint32 offset, + guint8 *codepage_stag, guint8 *codepage_attr) + { + guint32 tvb_len = tvb_reported_length (tvb); +- guint32 off = offset; ++ guint32 off = offset, last_off; + guint32 len; + guint str_len; + guint32 ent; +@@ -7732,6 +7737,7 @@ parse_wbxml_tag (proto_tree *tree, tvbuff_t *tvb, guint32 offset, + tag_save_literal = NULL; /* Prevents compiler warning */ + + DebugLog((""parse_wbxml_tag (level = %u, offset = %u)\n"", *level, offset)); ++ last_off = off; + while (off < tvb_len) { + peek = tvb_get_guint8 (tvb, off); + DebugLog((""STAG: (top of while) level = %3u, peek = 0x%02X, off = %u, tvb_len = %u\n"", *level, peek, off, tvb_len)); +@@ -8091,6 +8097,10 @@ parse_wbxml_tag (proto_tree *tree, tvbuff_t *tvb, guint32 offset, + /* TODO: Do I have to reset code page here? */ + } + } /* if (tag & 0x3F) >= 5 */ ++ if (off < last_off) { ++ THROW(ReportedBoundsError); ++ } ++ last_off = off; + } /* while */ + DebugLog((""STAG: level = %u, Return: len = %u (end of function body)\n"", + *level, off - offset)); +@@ -8126,7 +8136,7 @@ parse_wbxml_attribute_list_defined (proto_tree *tree, tvbuff_t *tvb, + const wbxml_decoding *map) + { + guint32 tvb_len = tvb_reported_length (tvb); +- guint32 off = offset; ++ guint32 off = offset, last_off; + guint32 len; + guint str_len; + guint32 ent; +@@ -8138,6 +8148,7 @@ parse_wbxml_attribute_list_defined (proto_tree *tree, tvbuff_t *tvb, + DebugLog((""parse_wbxml_attr_defined (level = %u, offset = %u)\n"", + level, offset)); + /* Parse attributes */ ++ last_off = off; + while (off < tvb_len) { + peek = tvb_get_guint8 (tvb, off); + DebugLog((""ATTR: (top of while) level = %3u, peek = 0x%02X, "" +@@ -8330,6 +8341,10 @@ parse_wbxml_attribute_list_defined (proto_tree *tree, tvbuff_t *tvb, + off++; + } + } ++ if (off < last_off) { ++ THROW(ReportedBoundsError); ++ } ++ last_off = off; + } /* End WHILE */ + DebugLog((""ATTR: level = %u, Return: len = %u (end of function body)\n"", + level, off - offset)); +@@ -8350,7 +8365,7 @@ parse_wbxml_attribute_list (proto_tree *tree, tvbuff_t *tvb, + guint32 offset, guint32 str_tbl, guint8 level, guint8 *codepage_attr) + { + guint32 tvb_len = tvb_reported_length (tvb); +- guint32 off = offset; ++ guint32 off = offset, last_off; + guint32 len; + guint str_len; + guint32 ent; +@@ -8359,6 +8374,7 @@ parse_wbxml_attribute_list (proto_tree *tree, tvbuff_t *tvb, + + DebugLog((""parse_wbxml_attr (level = %u, offset = %u)\n"", level, offset)); + /* Parse attributes */ ++ last_off = off; + while (off < tvb_len) { + peek = tvb_get_guint8 (tvb, off); + DebugLog((""ATTR: (top of while) level = %3u, peek = 0x%02X, "" +@@ -8516,6 +8532,10 @@ parse_wbxml_attribute_list (proto_tree *tree, tvbuff_t *tvb, + off++; + } + } ++ if (off < last_off) { ++ THROW(ReportedBoundsError); ++ } ++ last_off = off; + } /* End WHILE */ + DebugLog((""ATTR: level = %u, Return: len = %u (end of function body)\n"", + level, off - offset));",812,1143,2048 +18257,"static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait, + struct uffd_msg *msg) +{ + ssize_t ret; + DECLARE_WAITQUEUE(wait, current); + struct userfaultfd_wait_queue *uwq; + /* + * Handling fork event requires sleeping operations, so + * we drop the event_wqh lock, then do these ops, then + * lock it back and wake up the waiter. While the lock is + * dropped the ewq may go away so we keep track of it + * carefully. + */ + LIST_HEAD(fork_event); + struct userfaultfd_ctx *fork_nctx = NULL; + + /* always take the fd_wqh lock before the fault_pending_wqh lock */ + spin_lock(&ctx->fd_wqh.lock); + __add_wait_queue(&ctx->fd_wqh, &wait); + for (;;) { + set_current_state(TASK_INTERRUPTIBLE); + spin_lock(&ctx->fault_pending_wqh.lock); + uwq = find_userfault(ctx); + if (uwq) { + /* + * Use a seqcount to repeat the lockless check + * in wake_userfault() to avoid missing + * wakeups because during the refile both + * waitqueue could become empty if this is the + * only userfault. + */ + write_seqcount_begin(&ctx->refile_seq); + + /* + * The fault_pending_wqh.lock prevents the uwq + * to disappear from under us. + * + * Refile this userfault from + * fault_pending_wqh to fault_wqh, it's not + * pending anymore after we read it. + * + * Use list_del() by hand (as + * userfaultfd_wake_function also uses + * list_del_init() by hand) to be sure nobody + * changes __remove_wait_queue() to use + * list_del_init() in turn breaking the + * !list_empty_careful() check in + * handle_userfault(). The uwq->wq.head list + * must never be empty at any time during the + * refile, or the waitqueue could disappear + * from under us. The ""wait_queue_head_t"" + * parameter of __remove_wait_queue() is unused + * anyway. + */ + list_del(&uwq->wq.entry); + __add_wait_queue(&ctx->fault_wqh, &uwq->wq); + + write_seqcount_end(&ctx->refile_seq); + + /* careful to always initialize msg if ret == 0 */ + *msg = uwq->msg; + spin_unlock(&ctx->fault_pending_wqh.lock); + ret = 0; + break; + } + spin_unlock(&ctx->fault_pending_wqh.lock); + + spin_lock(&ctx->event_wqh.lock); + uwq = find_userfault_evt(ctx); + if (uwq) { + *msg = uwq->msg; + + if (uwq->msg.event == UFFD_EVENT_FORK) { + fork_nctx = (struct userfaultfd_ctx *) + (unsigned long) + uwq->msg.arg.reserved.reserved1; + list_move(&uwq->wq.entry, &fork_event); + spin_unlock(&ctx->event_wqh.lock); + ret = 0; + break; + } + + userfaultfd_event_complete(ctx, uwq); + spin_unlock(&ctx->event_wqh.lock); + ret = 0; + break; + } + spin_unlock(&ctx->event_wqh.lock); + + if (signal_pending(current)) { + ret = -ERESTARTSYS; + break; + } + if (no_wait) { + ret = -EAGAIN; + break; + } + spin_unlock(&ctx->fd_wqh.lock); + schedule(); + spin_lock(&ctx->fd_wqh.lock); + } + __remove_wait_queue(&ctx->fd_wqh, &wait); + __set_current_state(TASK_RUNNING); + spin_unlock(&ctx->fd_wqh.lock); + + if (!ret && msg->event == UFFD_EVENT_FORK) { + ret = resolve_userfault_fork(ctx, fork_nctx, msg); + + if (!ret) { + spin_lock(&ctx->event_wqh.lock); + if (!list_empty(&fork_event)) { + uwq = list_first_entry(&fork_event, + typeof(*uwq), + wq.entry); + list_del(&uwq->wq.entry); + __add_wait_queue(&ctx->event_wqh, &uwq->wq); + userfaultfd_event_complete(ctx, uwq); + } + spin_unlock(&ctx->event_wqh.lock); + } + } + + return ret; +} +",1,"static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait, + struct uffd_msg *msg) +{ + ssize_t ret; + DECLARE_WAITQUEUE(wait, current); + struct userfaultfd_wait_queue *uwq; + /* + * Handling fork event requires sleeping operations, so + * we drop the event_wqh lock, then do these ops, then + * lock it back and wake up the waiter. While the lock is + * dropped the ewq may go away so we keep track of it + * carefully. + */ + LIST_HEAD(fork_event); + struct userfaultfd_ctx *fork_nctx = NULL; + + /* always take the fd_wqh lock before the fault_pending_wqh lock */ + spin_lock(&ctx->fd_wqh.lock); + __add_wait_queue(&ctx->fd_wqh, &wait); + for (;;) { + set_current_state(TASK_INTERRUPTIBLE); + spin_lock(&ctx->fault_pending_wqh.lock); + uwq = find_userfault(ctx); + if (uwq) { + /* + * Use a seqcount to repeat the lockless check + * in wake_userfault() to avoid missing + * wakeups because during the refile both + * waitqueue could become empty if this is the + * only userfault. + */ + write_seqcount_begin(&ctx->refile_seq); + + /* + * The fault_pending_wqh.lock prevents the uwq + * to disappear from under us. + * + * Refile this userfault from + * fault_pending_wqh to fault_wqh, it's not + * pending anymore after we read it. + * + * Use list_del() by hand (as + * userfaultfd_wake_function also uses + * list_del_init() by hand) to be sure nobody + * changes __remove_wait_queue() to use + * list_del_init() in turn breaking the + * !list_empty_careful() check in + * handle_userfault(). The uwq->wq.head list + * must never be empty at any time during the + * refile, or the waitqueue could disappear + * from under us. The ""wait_queue_head_t"" + * parameter of __remove_wait_queue() is unused + * anyway. + */ + list_del(&uwq->wq.entry); + __add_wait_queue(&ctx->fault_wqh, &uwq->wq); + + write_seqcount_end(&ctx->refile_seq); + + /* careful to always initialize msg if ret == 0 */ + *msg = uwq->msg; + spin_unlock(&ctx->fault_pending_wqh.lock); + ret = 0; + break; + } + spin_unlock(&ctx->fault_pending_wqh.lock); + + spin_lock(&ctx->event_wqh.lock); + uwq = find_userfault_evt(ctx); + if (uwq) { + *msg = uwq->msg; + + if (uwq->msg.event == UFFD_EVENT_FORK) { + fork_nctx = (struct userfaultfd_ctx *) + (unsigned long) + uwq->msg.arg.reserved.reserved1; + list_move(&uwq->wq.entry, &fork_event); + /* + * fork_nctx can be freed as soon as + * we drop the lock, unless we take a + * reference on it. + */ + userfaultfd_ctx_get(fork_nctx); + spin_unlock(&ctx->event_wqh.lock); + ret = 0; + break; + } + + userfaultfd_event_complete(ctx, uwq); + spin_unlock(&ctx->event_wqh.lock); + ret = 0; + break; + } + spin_unlock(&ctx->event_wqh.lock); + + if (signal_pending(current)) { + ret = -ERESTARTSYS; + break; + } + if (no_wait) { + ret = -EAGAIN; + break; + } + spin_unlock(&ctx->fd_wqh.lock); + schedule(); + spin_lock(&ctx->fd_wqh.lock); + } + __remove_wait_queue(&ctx->fd_wqh, &wait); + __set_current_state(TASK_RUNNING); + spin_unlock(&ctx->fd_wqh.lock); + + if (!ret && msg->event == UFFD_EVENT_FORK) { + ret = resolve_userfault_fork(ctx, fork_nctx, msg); + spin_lock(&ctx->event_wqh.lock); + if (!list_empty(&fork_event)) { + /* + * The fork thread didn't abort, so we can + * drop the temporary refcount. + */ + userfaultfd_ctx_put(fork_nctx); + + uwq = list_first_entry(&fork_event, + typeof(*uwq), + wq.entry); + /* + * If fork_event list wasn't empty and in turn + * the event wasn't already released by fork + * (the event is allocated on fork kernel + * stack), put the event back to its place in + * the event_wq. fork_event head will be freed + * as soon as we return so the event cannot + * stay queued there no matter the current + * ""ret"" value. + */ + list_del(&uwq->wq.entry); + __add_wait_queue(&ctx->event_wqh, &uwq->wq); + + /* + * Leave the event in the waitqueue and report + * error to userland if we failed to resolve + * the userfault fork. + */ + if (likely(!ret)) + userfaultfd_event_complete(ctx, uwq); + } else { + /* + * Here the fork thread aborted and the + * refcount from the fork thread on fork_nctx + * has already been released. We still hold + * the reference we took before releasing the + * lock above. If resolve_userfault_fork + * failed we've to drop it because the + * fork_nctx has to be freed in such case. If + * it succeeded we'll hold it because the new + * uffd references it. + */ + if (ret) + userfaultfd_ctx_put(fork_nctx); + } + spin_unlock(&ctx->event_wqh.lock); + } + + return ret; +} +","@@ -588,6 +588,12 @@ static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx, + break; + if (ACCESS_ONCE(ctx->released) || + fatal_signal_pending(current)) { ++ /* ++ * &ewq->wq may be queued in fork_event, but ++ * __remove_wait_queue ignores the head ++ * parameter. It would be a problem if it ++ * didn't. ++ */ + __remove_wait_queue(&ctx->event_wqh, &ewq->wq); + if (ewq->msg.event == UFFD_EVENT_FORK) { + struct userfaultfd_ctx *new; +@@ -1061,6 +1067,12 @@ static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait, + (unsigned long) + uwq->msg.arg.reserved.reserved1; + list_move(&uwq->wq.entry, &fork_event); ++ /* ++ * fork_nctx can be freed as soon as ++ * we drop the lock, unless we take a ++ * reference on it. ++ */ ++ userfaultfd_ctx_get(fork_nctx); + spin_unlock(&ctx->event_wqh.lock); + ret = 0; + break; +@@ -1091,19 +1103,53 @@ static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait, + + if (!ret && msg->event == UFFD_EVENT_FORK) { + ret = resolve_userfault_fork(ctx, fork_nctx, msg); ++ spin_lock(&ctx->event_wqh.lock); ++ if (!list_empty(&fork_event)) { ++ /* ++ * The fork thread didn't abort, so we can ++ * drop the temporary refcount. ++ */ ++ userfaultfd_ctx_put(fork_nctx); ++ ++ uwq = list_first_entry(&fork_event, ++ typeof(*uwq), ++ wq.entry); ++ /* ++ * If fork_event list wasn't empty and in turn ++ * the event wasn't already released by fork ++ * (the event is allocated on fork kernel ++ * stack), put the event back to its place in ++ * the event_wq. fork_event head will be freed ++ * as soon as we return so the event cannot ++ * stay queued there no matter the current ++ * ""ret"" value. ++ */ ++ list_del(&uwq->wq.entry); ++ __add_wait_queue(&ctx->event_wqh, &uwq->wq); + +- if (!ret) { +- spin_lock(&ctx->event_wqh.lock); +- if (!list_empty(&fork_event)) { +- uwq = list_first_entry(&fork_event, +- typeof(*uwq), +- wq.entry); +- list_del(&uwq->wq.entry); +- __add_wait_queue(&ctx->event_wqh, &uwq->wq); ++ /* ++ * Leave the event in the waitqueue and report ++ * error to userland if we failed to resolve ++ * the userfault fork. ++ */ ++ if (likely(!ret)) + userfaultfd_event_complete(ctx, uwq); +- } +- spin_unlock(&ctx->event_wqh.lock); ++ } else { ++ /* ++ * Here the fork thread aborted and the ++ * refcount from the fork thread on fork_nctx ++ * has already been released. We still hold ++ * the reference we took before releasing the ++ * lock above. If resolve_userfault_fork ++ * failed we've to drop it because the ++ * fork_nctx has to be freed in such case. If ++ * it succeeded we'll hold it because the new ++ * uffd references it. ++ */ ++ if (ret) ++ userfaultfd_ctx_put(fork_nctx); + } ++ spin_unlock(&ctx->event_wqh.lock); + } + + return ret;",1026,1357,2048 +18784,"void SoftVPXEncoder::onQueueFilled(OMX_U32 /* portIndex */) { + if (mCodecContext == NULL) { + if (OK != initEncoder()) { + ALOGE(""Failed to initialize encoder""); + notify(OMX_EventError, + OMX_ErrorUndefined, + 0, // Extra notification data + NULL); // Notification data pointer + return; + } + } + + vpx_codec_err_t codec_return; + List &inputBufferInfoQueue = getPortQueue(kInputPortIndex); + List &outputBufferInfoQueue = getPortQueue(kOutputPortIndex); + + while (!inputBufferInfoQueue.empty() && !outputBufferInfoQueue.empty()) { + BufferInfo *inputBufferInfo = *inputBufferInfoQueue.begin(); + OMX_BUFFERHEADERTYPE *inputBufferHeader = inputBufferInfo->mHeader; + + BufferInfo *outputBufferInfo = *outputBufferInfoQueue.begin(); + OMX_BUFFERHEADERTYPE *outputBufferHeader = outputBufferInfo->mHeader; + + if ((inputBufferHeader->nFlags & OMX_BUFFERFLAG_EOS) && + inputBufferHeader->nFilledLen == 0) { + inputBufferInfoQueue.erase(inputBufferInfoQueue.begin()); + inputBufferInfo->mOwnedByUs = false; + notifyEmptyBufferDone(inputBufferHeader); + + outputBufferHeader->nFilledLen = 0; + outputBufferHeader->nFlags = OMX_BUFFERFLAG_EOS; + + outputBufferInfoQueue.erase(outputBufferInfoQueue.begin()); + outputBufferInfo->mOwnedByUs = false; + notifyFillBufferDone(outputBufferHeader); + return; + } + + + const uint8_t *source = + inputBufferHeader->pBuffer + inputBufferHeader->nOffset; + + if (mInputDataIsMeta) { + source = extractGraphicBuffer( + mConversionBuffer, mWidth * mHeight * 3 / 2, + source, inputBufferHeader->nFilledLen, + mWidth, mHeight); + if (source == NULL) { + ALOGE(""Unable to extract gralloc buffer in metadata mode""); + + notify(OMX_EventError, OMX_ErrorUndefined, 0, 0); + return; + } + } else if (mColorFormat == OMX_COLOR_FormatYUV420SemiPlanar) { + ConvertYUV420SemiPlanarToYUV420Planar( + source, mConversionBuffer, mWidth, mHeight); + + source = mConversionBuffer; + } + vpx_image_t raw_frame; + vpx_img_wrap(&raw_frame, VPX_IMG_FMT_I420, mWidth, mHeight, + kInputBufferAlignment, (uint8_t *)source); + + vpx_enc_frame_flags_t flags = 0; + if (mTemporalPatternLength > 0) { + flags = getEncodeFlags(); + } + if (mKeyFrameRequested) { + flags |= VPX_EFLAG_FORCE_KF; + mKeyFrameRequested = false; + } + + if (mBitrateUpdated) { + mCodecConfiguration->rc_target_bitrate = mBitrate/1000; + vpx_codec_err_t res = vpx_codec_enc_config_set(mCodecContext, + mCodecConfiguration); + if (res != VPX_CODEC_OK) { + ALOGE(""vp8 encoder failed to update bitrate: %s"", + vpx_codec_err_to_string(res)); + notify(OMX_EventError, + OMX_ErrorUndefined, + 0, // Extra notification data + NULL); // Notification data pointer + } + mBitrateUpdated = false; + } + + uint32_t frameDuration; + if (inputBufferHeader->nTimeStamp > mLastTimestamp) { + frameDuration = (uint32_t)(inputBufferHeader->nTimeStamp - mLastTimestamp); + } else { + frameDuration = (uint32_t)(((uint64_t)1000000 << 16) / mFramerate); + } + mLastTimestamp = inputBufferHeader->nTimeStamp; + codec_return = vpx_codec_encode( + mCodecContext, + &raw_frame, + inputBufferHeader->nTimeStamp, // in timebase units + frameDuration, // frame duration in timebase units + flags, // frame flags + VPX_DL_REALTIME); // encoding deadline + if (codec_return != VPX_CODEC_OK) { + ALOGE(""vpx encoder failed to encode frame""); + notify(OMX_EventError, + OMX_ErrorUndefined, + 0, // Extra notification data + NULL); // Notification data pointer + return; + } + + vpx_codec_iter_t encoded_packet_iterator = NULL; + const vpx_codec_cx_pkt_t* encoded_packet; + + while ((encoded_packet = vpx_codec_get_cx_data( + mCodecContext, &encoded_packet_iterator))) { + if (encoded_packet->kind == VPX_CODEC_CX_FRAME_PKT) { + + outputBufferHeader->nTimeStamp = encoded_packet->data.frame.pts; + outputBufferHeader->nFlags = 0; + if (encoded_packet->data.frame.flags & VPX_FRAME_IS_KEY) + outputBufferHeader->nFlags |= OMX_BUFFERFLAG_SYNCFRAME; + outputBufferHeader->nOffset = 0; + outputBufferHeader->nFilledLen = encoded_packet->data.frame.sz; + memcpy(outputBufferHeader->pBuffer, + encoded_packet->data.frame.buf, + encoded_packet->data.frame.sz); + outputBufferInfo->mOwnedByUs = false; + outputBufferInfoQueue.erase(outputBufferInfoQueue.begin()); + if (inputBufferHeader->nFlags & OMX_BUFFERFLAG_EOS) { + outputBufferHeader->nFlags |= OMX_BUFFERFLAG_EOS; + } + notifyFillBufferDone(outputBufferHeader); + } + } + + inputBufferInfo->mOwnedByUs = false; + inputBufferInfoQueue.erase(inputBufferInfoQueue.begin()); + notifyEmptyBufferDone(inputBufferHeader); + } +} +",1,"void SoftVPXEncoder::onQueueFilled(OMX_U32 /* portIndex */) { + if (mCodecContext == NULL) { + if (OK != initEncoder()) { + ALOGE(""Failed to initialize encoder""); + notify(OMX_EventError, + OMX_ErrorUndefined, + 0, // Extra notification data + NULL); // Notification data pointer + return; + } + } + + vpx_codec_err_t codec_return; + List &inputBufferInfoQueue = getPortQueue(kInputPortIndex); + List &outputBufferInfoQueue = getPortQueue(kOutputPortIndex); + + while (!inputBufferInfoQueue.empty() && !outputBufferInfoQueue.empty()) { + BufferInfo *inputBufferInfo = *inputBufferInfoQueue.begin(); + OMX_BUFFERHEADERTYPE *inputBufferHeader = inputBufferInfo->mHeader; + + BufferInfo *outputBufferInfo = *outputBufferInfoQueue.begin(); + OMX_BUFFERHEADERTYPE *outputBufferHeader = outputBufferInfo->mHeader; + + if ((inputBufferHeader->nFlags & OMX_BUFFERFLAG_EOS) && + inputBufferHeader->nFilledLen == 0) { + inputBufferInfoQueue.erase(inputBufferInfoQueue.begin()); + inputBufferInfo->mOwnedByUs = false; + notifyEmptyBufferDone(inputBufferHeader); + + outputBufferHeader->nFilledLen = 0; + outputBufferHeader->nFlags = OMX_BUFFERFLAG_EOS; + + outputBufferInfoQueue.erase(outputBufferInfoQueue.begin()); + outputBufferInfo->mOwnedByUs = false; + notifyFillBufferDone(outputBufferHeader); + return; + } + + + const uint8_t *source = + inputBufferHeader->pBuffer + inputBufferHeader->nOffset; + + size_t frameSize = mWidth * mHeight * 3 / 2; + if (mInputDataIsMeta) { + source = extractGraphicBuffer( + mConversionBuffer, frameSize, + source, inputBufferHeader->nFilledLen, + mWidth, mHeight); + if (source == NULL) { + ALOGE(""Unable to extract gralloc buffer in metadata mode""); + + notify(OMX_EventError, OMX_ErrorUndefined, 0, 0); + return; + } + } else { + if (inputBufferHeader->nFilledLen < frameSize) { + android_errorWriteLog(0x534e4554, ""27569635""); + notify(OMX_EventError, OMX_ErrorUndefined, 0, 0); + return; + } else if (inputBufferHeader->nFilledLen > frameSize) { + ALOGW(""Input buffer contains too many pixels""); + } + + if (mColorFormat == OMX_COLOR_FormatYUV420SemiPlanar) { + ConvertYUV420SemiPlanarToYUV420Planar( + source, mConversionBuffer, mWidth, mHeight); + + source = mConversionBuffer; + } + } + vpx_image_t raw_frame; + vpx_img_wrap(&raw_frame, VPX_IMG_FMT_I420, mWidth, mHeight, + kInputBufferAlignment, (uint8_t *)source); + + vpx_enc_frame_flags_t flags = 0; + if (mTemporalPatternLength > 0) { + flags = getEncodeFlags(); + } + if (mKeyFrameRequested) { + flags |= VPX_EFLAG_FORCE_KF; + mKeyFrameRequested = false; + } + + if (mBitrateUpdated) { + mCodecConfiguration->rc_target_bitrate = mBitrate/1000; + vpx_codec_err_t res = vpx_codec_enc_config_set(mCodecContext, + mCodecConfiguration); + if (res != VPX_CODEC_OK) { + ALOGE(""vp8 encoder failed to update bitrate: %s"", + vpx_codec_err_to_string(res)); + notify(OMX_EventError, + OMX_ErrorUndefined, + 0, // Extra notification data + NULL); // Notification data pointer + } + mBitrateUpdated = false; + } + + uint32_t frameDuration; + if (inputBufferHeader->nTimeStamp > mLastTimestamp) { + frameDuration = (uint32_t)(inputBufferHeader->nTimeStamp - mLastTimestamp); + } else { + frameDuration = (uint32_t)(((uint64_t)1000000 << 16) / mFramerate); + } + mLastTimestamp = inputBufferHeader->nTimeStamp; + codec_return = vpx_codec_encode( + mCodecContext, + &raw_frame, + inputBufferHeader->nTimeStamp, // in timebase units + frameDuration, // frame duration in timebase units + flags, // frame flags + VPX_DL_REALTIME); // encoding deadline + if (codec_return != VPX_CODEC_OK) { + ALOGE(""vpx encoder failed to encode frame""); + notify(OMX_EventError, + OMX_ErrorUndefined, + 0, // Extra notification data + NULL); // Notification data pointer + return; + } + + vpx_codec_iter_t encoded_packet_iterator = NULL; + const vpx_codec_cx_pkt_t* encoded_packet; + + while ((encoded_packet = vpx_codec_get_cx_data( + mCodecContext, &encoded_packet_iterator))) { + if (encoded_packet->kind == VPX_CODEC_CX_FRAME_PKT) { + + outputBufferHeader->nTimeStamp = encoded_packet->data.frame.pts; + outputBufferHeader->nFlags = 0; + if (encoded_packet->data.frame.flags & VPX_FRAME_IS_KEY) + outputBufferHeader->nFlags |= OMX_BUFFERFLAG_SYNCFRAME; + outputBufferHeader->nOffset = 0; + outputBufferHeader->nFilledLen = encoded_packet->data.frame.sz; + if (outputBufferHeader->nFilledLen > outputBufferHeader->nAllocLen) { + android_errorWriteLog(0x534e4554, ""27569635""); + notify(OMX_EventError, OMX_ErrorUndefined, 0, 0); + return; + } + memcpy(outputBufferHeader->pBuffer, + encoded_packet->data.frame.buf, + encoded_packet->data.frame.sz); + outputBufferInfo->mOwnedByUs = false; + outputBufferInfoQueue.erase(outputBufferInfoQueue.begin()); + if (inputBufferHeader->nFlags & OMX_BUFFERFLAG_EOS) { + outputBufferHeader->nFlags |= OMX_BUFFERFLAG_EOS; + } + notifyFillBufferDone(outputBufferHeader); + } + } + + inputBufferInfo->mOwnedByUs = false; + inputBufferInfoQueue.erase(inputBufferInfoQueue.begin()); + notifyEmptyBufferDone(inputBufferHeader); + } +} +","@@ -688,9 +688,10 @@ + + const uint8_t *source = + inputBufferHeader->pBuffer + inputBufferHeader->nOffset; + ++ size_t frameSize = mWidth * mHeight * 3 / 2; + if (mInputDataIsMeta) { + source = extractGraphicBuffer( +- mConversionBuffer, mWidth * mHeight * 3 / 2, ++ mConversionBuffer, frameSize, + source, inputBufferHeader->nFilledLen, + mWidth, mHeight); + if (source == NULL) { +@@ -698,11 +699,21 @@ + + notify(OMX_EventError, OMX_ErrorUndefined, 0, 0); + return; + } +- } else if (mColorFormat == OMX_COLOR_FormatYUV420SemiPlanar) { +- ConvertYUV420SemiPlanarToYUV420Planar( +- source, mConversionBuffer, mWidth, mHeight); ++ } else { ++ if (inputBufferHeader->nFilledLen < frameSize) { ++ android_errorWriteLog(0x534e4554, ""27569635""); ++ notify(OMX_EventError, OMX_ErrorUndefined, 0, 0); ++ return; ++ } else if (inputBufferHeader->nFilledLen > frameSize) { ++ ALOGW(""Input buffer contains too many pixels""); ++ } + +- source = mConversionBuffer; ++ if (mColorFormat == OMX_COLOR_FormatYUV420SemiPlanar) { ++ ConvertYUV420SemiPlanarToYUV420Planar( ++ source, mConversionBuffer, mWidth, mHeight); ++ ++ source = mConversionBuffer; ++ } + } + vpx_image_t raw_frame; + vpx_img_wrap(&raw_frame, VPX_IMG_FMT_I420, mWidth, mHeight, +@@ -764,9 +775,14 @@ + + outputBufferHeader->nTimeStamp = encoded_packet->data.frame.pts; + outputBufferHeader->nFlags = 0; + if (encoded_packet->data.frame.flags & VPX_FRAME_IS_KEY) +- outputBufferHeader->nFlags |= OMX_BUFFERFLAG_SYNCFRAME; ++ outputBufferHeader->nFlags |= OMX_BUFFERFLAG_SYNCFRAME; + outputBufferHeader->nOffset = 0; + outputBufferHeader->nFilledLen = encoded_packet->data.frame.sz; ++ if (outputBufferHeader->nFilledLen > outputBufferHeader->nAllocLen) { ++ android_errorWriteLog(0x534e4554, ""27569635""); ++ notify(OMX_EventError, OMX_ErrorUndefined, 0, 0); ++ return; ++ } + memcpy(outputBufferHeader->pBuffer, + encoded_packet->data.frame.buf, + encoded_packet->data.frame.sz); +",1226,1557,2048 +17870,"int mainloop(CLIENT *client) { + struct nbd_request request; + struct nbd_reply reply; + gboolean go_on=TRUE; +#ifdef DODBG + int i = 0; +#endif + negotiate(client->net, client, NULL); + DEBUG(""Entering request loop!\n""); + reply.magic = htonl(NBD_REPLY_MAGIC); + reply.error = 0; + while (go_on) { + char buf[BUFSIZE]; + size_t len; +#ifdef DODBG + i++; + printf(""%d: "", i); +#endif + readit(client->net, &request, sizeof(request)); + request.from = ntohll(request.from); + request.type = ntohl(request.type); + + if (request.type==NBD_CMD_DISC) { + msg2(LOG_INFO, ""Disconnect request received.""); + if (client->server->flags & F_COPYONWRITE) { + if (client->difmap) g_free(client->difmap) ; + close(client->difffile); + unlink(client->difffilename); + free(client->difffilename); + } + go_on=FALSE; + continue; + } + + len = ntohl(request.len); + + if (request.magic != htonl(NBD_REQUEST_MAGIC)) + err(""Not enough magic.""); + if (len > BUFSIZE + sizeof(struct nbd_reply)) + err(""Request too big!""); + #ifdef DODBG + printf(""%s from %llu (%llu) len %d, "", request.type ? ""WRITE"" : + ""READ"", (unsigned long long)request.from, + (unsigned long long)request.from / 512, len); +#endif + memcpy(reply.handle, request.handle, sizeof(reply.handle)); + if ((request.from + len) > (OFFT_MAX)) { + DEBUG(""[Number too large!]""); + ERROR(client, reply, EINVAL); + continue; + } + + if (((ssize_t)((off_t)request.from + len) > client->exportsize)) { + DEBUG(""[RANGE!]""); + ERROR(client, reply, EINVAL); + continue; + } + + if (request.type==NBD_CMD_WRITE) { + DEBUG(""wr: net->buf, ""); + readit(client->net, buf, len); + DEBUG(""buf->exp, ""); + if ((client->server->flags & F_READONLY) || + (client->server->flags & F_AUTOREADONLY)) { + DEBUG(""[WRITE to READONLY!]""); + ERROR(client, reply, EPERM); + continue; + } + if (expwrite(request.from, buf, len, client)) { + DEBUG(""Write failed: %m"" ); + ERROR(client, reply, errno); + continue; + } + SEND(client->net, reply); + DEBUG(""OK!\n""); + continue; + } + /* READ */ + + DEBUG(""exp->buf, ""); + if (expread(request.from, buf + sizeof(struct nbd_reply), len, client)) { + DEBUG(""Read failed: %m""); + ERROR(client, reply, errno); + continue; + } + + DEBUG(""buf->net, ""); + memcpy(buf, &reply, sizeof(struct nbd_reply)); + writeit(client->net, buf, len + sizeof(struct nbd_reply)); + DEBUG(""OK!\n""); + } + return 0; +} +",1,"int mainloop(CLIENT *client) { + struct nbd_request request; + struct nbd_reply reply; + gboolean go_on=TRUE; +#ifdef DODBG + int i = 0; +#endif + negotiate(client->net, client, NULL); + DEBUG(""Entering request loop!\n""); + reply.magic = htonl(NBD_REPLY_MAGIC); + reply.error = 0; + while (go_on) { + char buf[BUFSIZE]; + size_t len; +#ifdef DODBG + i++; + printf(""%d: "", i); +#endif + readit(client->net, &request, sizeof(request)); + request.from = ntohll(request.from); + request.type = ntohl(request.type); + + if (request.type==NBD_CMD_DISC) { + msg2(LOG_INFO, ""Disconnect request received.""); + if (client->server->flags & F_COPYONWRITE) { + if (client->difmap) g_free(client->difmap) ; + close(client->difffile); + unlink(client->difffilename); + free(client->difffilename); + } + go_on=FALSE; + continue; + } + + len = ntohl(request.len); + + if (request.magic != htonl(NBD_REQUEST_MAGIC)) + err(""Not enough magic.""); + if (len > BUFSIZE - sizeof(struct nbd_reply)) + err(""Request too big!""); + #ifdef DODBG + printf(""%s from %llu (%llu) len %d, "", request.type ? ""WRITE"" : + ""READ"", (unsigned long long)request.from, + (unsigned long long)request.from / 512, len); +#endif + memcpy(reply.handle, request.handle, sizeof(reply.handle)); + if ((request.from + len) > (OFFT_MAX)) { + DEBUG(""[Number too large!]""); + ERROR(client, reply, EINVAL); + continue; + } + + if (((ssize_t)((off_t)request.from + len) > client->exportsize)) { + DEBUG(""[RANGE!]""); + ERROR(client, reply, EINVAL); + continue; + } + + if (request.type==NBD_CMD_WRITE) { + DEBUG(""wr: net->buf, ""); + readit(client->net, buf, len); + DEBUG(""buf->exp, ""); + if ((client->server->flags & F_READONLY) || + (client->server->flags & F_AUTOREADONLY)) { + DEBUG(""[WRITE to READONLY!]""); + ERROR(client, reply, EPERM); + continue; + } + if (expwrite(request.from, buf, len, client)) { + DEBUG(""Write failed: %m"" ); + ERROR(client, reply, errno); + continue; + } + SEND(client->net, reply); + DEBUG(""OK!\n""); + continue; + } + /* READ */ + + DEBUG(""exp->buf, ""); + if (expread(request.from, buf + sizeof(struct nbd_reply), len, client)) { + DEBUG(""Read failed: %m""); + ERROR(client, reply, errno); + continue; + } + + DEBUG(""buf->net, ""); + memcpy(buf, &reply, sizeof(struct nbd_reply)); + writeit(client->net, buf, len + sizeof(struct nbd_reply)); + DEBUG(""OK!\n""); + } + return 0; +} +","@@ -150,7 +150,7 @@ gboolean do_oldstyle=FALSE; + #define OFFT_MAX ~((off_t)1<<(sizeof(off_t)*8-1)) + #define LINELEN 256 /**< Size of static buffer used to read the + authorization file (yuck) */ +-#define BUFSIZE (1024*1024) /**< Size of buffer that can hold requests */ ++#define BUFSIZE ((1024*1024)+sizeof(struct nbd_reply)) /**< Size of buffer that can hold requests */ + #define DIFFPAGESIZE 4096 /**< diff file uses those chunks */ + #define F_READONLY 1 /**< flag to tell us a file is readonly */ + #define F_MULTIFILE 2 /**< flag to tell us a file is exported using -m */ +@@ -1389,7 +1389,7 @@ int mainloop(CLIENT *client) { + + if (request.magic != htonl(NBD_REQUEST_MAGIC)) + err(""Not enough magic.""); +- if (len > BUFSIZE + sizeof(struct nbd_reply)) ++ if (len > BUFSIZE - sizeof(struct nbd_reply)) + err(""Request too big!""); + #ifdef DODBG + printf(""%s from %llu (%llu) len %d, "", request.type ? ""WRITE"" :",703,1034,2048 +6608,"static int mailimf_zone_parse(const char * message, size_t length, + size_t * indx, int * result) +{ + int zone; + int sign; + size_t cur_token; + int r; + uint32_t value; + + cur_token = * indx; + + if (cur_token + 1 < length) { + if ((message[cur_token] == 'U') && (message[cur_token + 1] == 'T')) { + * result = TRUE; + * indx = cur_token + 2; + + return MAILIMF_NO_ERROR; + } + } + + zone = 0; + if (cur_token + 2 < length) { + int state; + + state = STATE_ZONE_1; + + while (state <= 2) { + switch (state) { + case STATE_ZONE_1: + switch (message[cur_token]) { + case 'G': + if (message[cur_token + 1] == 'M' && message[cur_token + 2] == 'T') { + if ((cur_token + 3 < length) && ((message[cur_token + 3] == '+') || (message[cur_token + 3] == '-'))) { + cur_token += 3; + state = STATE_ZONE_CONT; + } + else { + zone = 0; + state = STATE_ZONE_OK; + } + } + else { + state = STATE_ZONE_ERR; + } + break; + case 'E': + zone = -5; + state = STATE_ZONE_2; + break; + case 'C': + zone = -6; + state = STATE_ZONE_2; + break; + case 'M': + zone = -7; + state = STATE_ZONE_2; + break; + case 'P': + zone = -8; + state = STATE_ZONE_2; + break; + default: + state = STATE_ZONE_CONT; + break; + } + break; + case STATE_ZONE_2: + switch (message[cur_token + 1]) { + case 'S': + state = STATE_ZONE_3; + break; + case 'D': + zone ++; + state = STATE_ZONE_3; + break; + default: + state = STATE_ZONE_ERR; + break; + } + break; + case STATE_ZONE_3: + if (message[cur_token + 2] == 'T') { + zone *= 100; + state = STATE_ZONE_OK; + } + else + state = STATE_ZONE_ERR; + break; + } + } + + switch (state) { + case STATE_ZONE_OK: + * result = zone; + * indx = cur_token + 3; + return MAILIMF_NO_ERROR; + + case STATE_ZONE_ERR: + return MAILIMF_ERROR_PARSE; + } + } + + sign = 1; + r = mailimf_plus_parse(message, length, &cur_token); + if (r == MAILIMF_NO_ERROR) + sign = 1; + + if (r == MAILIMF_ERROR_PARSE) { + r = mailimf_minus_parse(message, length, &cur_token); + if (r == MAILIMF_NO_ERROR) + sign = -1; + } + + if (r == MAILIMF_NO_ERROR) { + /* do nothing */ + } + else if (r == MAILIMF_ERROR_PARSE) + sign = 1; + else + return r; + + r = mailimf_number_parse(message, length, &cur_token, &value); + if (r != MAILIMF_NO_ERROR) + return r; + + zone = value * sign; + + * indx = cur_token; + * result = zone; + + return MAILIMF_NO_ERROR; +} +",0,"static int mailimf_zone_parse(const char * message, size_t length, + size_t * indx, int * result) +{ + int zone; + int sign; + size_t cur_token; + int r; + uint32_t value; + + cur_token = * indx; + + if (cur_token + 1 < length) { + if ((message[cur_token] == 'U') && (message[cur_token + 1] == 'T')) { + * result = TRUE; + * indx = cur_token + 2; + + return MAILIMF_NO_ERROR; + } + } + + zone = 0; + if (cur_token + 2 < length) { + int state; + + state = STATE_ZONE_1; + + while (state <= 2) { + switch (state) { + case STATE_ZONE_1: + switch (message[cur_token]) { + case 'G': + if (message[cur_token + 1] == 'M' && message[cur_token + 2] == 'T') { + if ((cur_token + 3 < length) && ((message[cur_token + 3] == '+') || (message[cur_token + 3] == '-'))) { + cur_token += 3; + state = STATE_ZONE_CONT; + } + else { + zone = 0; + state = STATE_ZONE_OK; + } + } + else { + state = STATE_ZONE_ERR; + } + break; + case 'E': + zone = -5; + state = STATE_ZONE_2; + break; + case 'C': + zone = -6; + state = STATE_ZONE_2; + break; + case 'M': + zone = -7; + state = STATE_ZONE_2; + break; + case 'P': + zone = -8; + state = STATE_ZONE_2; + break; + default: + state = STATE_ZONE_CONT; + break; + } + break; + case STATE_ZONE_2: + switch (message[cur_token + 1]) { + case 'S': + state = STATE_ZONE_3; + break; + case 'D': + zone ++; + state = STATE_ZONE_3; + break; + default: + state = STATE_ZONE_ERR; + break; + } + break; + case STATE_ZONE_3: + if (message[cur_token + 2] == 'T') { + zone *= 100; + state = STATE_ZONE_OK; + } + else + state = STATE_ZONE_ERR; + break; + } + } + + switch (state) { + case STATE_ZONE_OK: + * result = zone; + * indx = cur_token + 3; + return MAILIMF_NO_ERROR; + + case STATE_ZONE_ERR: + return MAILIMF_ERROR_PARSE; + } + } + + sign = 1; + r = mailimf_plus_parse(message, length, &cur_token); + if (r == MAILIMF_NO_ERROR) + sign = 1; + + if (r == MAILIMF_ERROR_PARSE) { + r = mailimf_minus_parse(message, length, &cur_token); + if (r == MAILIMF_NO_ERROR) + sign = -1; + } + + if (r == MAILIMF_NO_ERROR) { + /* do nothing */ + } + else if (r == MAILIMF_ERROR_PARSE) + sign = 1; + else + return r; + + r = mailimf_number_parse(message, length, &cur_token, &value); + if (r != MAILIMF_NO_ERROR) + return r; + + zone = value * sign; + + * indx = cur_token; + * result = zone; + + return MAILIMF_NO_ERROR; +} +","@@ -3083,6 +3083,7 @@ static int mailimf_group_parse(const char * message, size_t length, + struct mailimf_group * group; + int r; + int res; ++ clist * list; + + cur_token = * indx; + +@@ -3110,6 +3111,17 @@ static int mailimf_group_parse(const char * message, size_t length, + res = r; + goto free_display_name; + } ++ list = clist_new(); ++ if (list == NULL) { ++ res = MAILIMF_ERROR_MEMORY; ++ goto free_display_name; ++ } ++ mailbox_list = mailimf_mailbox_list_new(list); ++ if (mailbox_list == NULL) { ++ res = MAILIMF_ERROR_MEMORY; ++ clist_free(list); ++ goto free_display_name; ++ } + break; + default: + res = r;",784,1115,2048 +5847,"static int __sched_setscheduler(struct task_struct *p, + const struct sched_attr *attr, + bool user) +{ + int retval, oldprio, oldpolicy = -1, on_rq, running; + int policy = attr->sched_policy; + unsigned long flags; + const struct sched_class *prev_class; + struct rq *rq; + int reset_on_fork; + + /* may grab non-irq protected spin_locks */ + BUG_ON(in_interrupt()); +recheck: + /* double check policy once rq lock held */ + if (policy < 0) { + reset_on_fork = p->sched_reset_on_fork; + policy = oldpolicy = p->policy; + } else { + reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK); + + if (policy != SCHED_DEADLINE && + policy != SCHED_FIFO && policy != SCHED_RR && + policy != SCHED_NORMAL && policy != SCHED_BATCH && + policy != SCHED_IDLE) + return -EINVAL; + } + + if (attr->sched_flags & ~(SCHED_FLAG_RESET_ON_FORK)) + return -EINVAL; + + /* + * Valid priorities for SCHED_FIFO and SCHED_RR are + * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL, + * SCHED_BATCH and SCHED_IDLE is 0. + */ + if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) || + (!p->mm && attr->sched_priority > MAX_RT_PRIO-1)) + return -EINVAL; + if ((dl_policy(policy) && !__checkparam_dl(attr)) || + (rt_policy(policy) != (attr->sched_priority != 0))) + return -EINVAL; + + /* + * Allow unprivileged RT tasks to decrease priority: + */ + if (user && !capable(CAP_SYS_NICE)) { + if (fair_policy(policy)) { + if (attr->sched_nice < TASK_NICE(p) && + !can_nice(p, attr->sched_nice)) + return -EPERM; + } + + if (rt_policy(policy)) { + unsigned long rlim_rtprio = + task_rlimit(p, RLIMIT_RTPRIO); + + /* can't set/change the rt policy */ + if (policy != p->policy && !rlim_rtprio) + return -EPERM; + + /* can't increase priority */ + if (attr->sched_priority > p->rt_priority && + attr->sched_priority > rlim_rtprio) + return -EPERM; + } + + /* + * Treat SCHED_IDLE as nice 20. Only allow a switch to + * SCHED_NORMAL if the RLIMIT_NICE would normally permit it. + */ + if (p->policy == SCHED_IDLE && policy != SCHED_IDLE) { + if (!can_nice(p, TASK_NICE(p))) + return -EPERM; + } + + /* can't change other user's priorities */ + if (!check_same_owner(p)) + return -EPERM; + + /* Normal users shall not reset the sched_reset_on_fork flag */ + if (p->sched_reset_on_fork && !reset_on_fork) + return -EPERM; + } + + if (user) { + retval = security_task_setscheduler(p); + if (retval) + return retval; + } + + /* + * make sure no PI-waiters arrive (or leave) while we are + * changing the priority of the task: + * + * To be able to change p->policy safely, the appropriate + * runqueue lock must be held. + */ + rq = task_rq_lock(p, &flags); + + /* + * Changing the policy of the stop threads its a very bad idea + */ + if (p == rq->stop) { + task_rq_unlock(rq, p, &flags); + return -EINVAL; + } + + /* + * If not changing anything there's no need to proceed further: + */ + if (unlikely(policy == p->policy)) { + if (fair_policy(policy) && attr->sched_nice != TASK_NICE(p)) + goto change; + if (rt_policy(policy) && attr->sched_priority != p->rt_priority) + goto change; + if (dl_policy(policy)) + goto change; + + task_rq_unlock(rq, p, &flags); + return 0; + } +change: + + if (user) { +#ifdef CONFIG_RT_GROUP_SCHED + /* + * Do not allow realtime tasks into groups that have no runtime + * assigned. + */ + if (rt_bandwidth_enabled() && rt_policy(policy) && + task_group(p)->rt_bandwidth.rt_runtime == 0 && + !task_group_is_autogroup(task_group(p))) { + task_rq_unlock(rq, p, &flags); + return -EPERM; + } +#endif +#ifdef CONFIG_SMP + if (dl_bandwidth_enabled() && dl_policy(policy)) { + cpumask_t *span = rq->rd->span; + + /* + * Don't allow tasks with an affinity mask smaller than + * the entire root_domain to become SCHED_DEADLINE. We + * will also fail if there's no bandwidth available. + */ + if (!cpumask_subset(span, &p->cpus_allowed) || + rq->rd->dl_bw.bw == 0) { + task_rq_unlock(rq, p, &flags); + return -EPERM; + } + } +#endif + } + + /* recheck policy now with rq lock held */ + if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) { + policy = oldpolicy = -1; + task_rq_unlock(rq, p, &flags); + goto recheck; + } + + /* + * If setscheduling to SCHED_DEADLINE (or changing the parameters + * of a SCHED_DEADLINE task) we need to check if enough bandwidth + * is available. + */ + if ((dl_policy(policy) || dl_task(p)) && dl_overflow(p, policy, attr)) { + task_rq_unlock(rq, p, &flags); + return -EBUSY; + } + + on_rq = p->on_rq; + running = task_current(rq, p); + if (on_rq) + dequeue_task(rq, p, 0); + if (running) + p->sched_class->put_prev_task(rq, p); + + p->sched_reset_on_fork = reset_on_fork; + + oldprio = p->prio; + prev_class = p->sched_class; + __setscheduler(rq, p, attr); + + if (running) + p->sched_class->set_curr_task(rq); + if (on_rq) + enqueue_task(rq, p, 0); + + check_class_changed(rq, p, prev_class, oldprio); + task_rq_unlock(rq, p, &flags); + + rt_mutex_adjust_pi(p); + + return 0; +} +",0,"static int __sched_setscheduler(struct task_struct *p, + const struct sched_attr *attr, + bool user) +{ + int retval, oldprio, oldpolicy = -1, on_rq, running; + int policy = attr->sched_policy; + unsigned long flags; + const struct sched_class *prev_class; + struct rq *rq; + int reset_on_fork; + + /* may grab non-irq protected spin_locks */ + BUG_ON(in_interrupt()); +recheck: + /* double check policy once rq lock held */ + if (policy < 0) { + reset_on_fork = p->sched_reset_on_fork; + policy = oldpolicy = p->policy; + } else { + reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK); + + if (policy != SCHED_DEADLINE && + policy != SCHED_FIFO && policy != SCHED_RR && + policy != SCHED_NORMAL && policy != SCHED_BATCH && + policy != SCHED_IDLE) + return -EINVAL; + } + + if (attr->sched_flags & ~(SCHED_FLAG_RESET_ON_FORK)) + return -EINVAL; + + /* + * Valid priorities for SCHED_FIFO and SCHED_RR are + * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL, + * SCHED_BATCH and SCHED_IDLE is 0. + */ + if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) || + (!p->mm && attr->sched_priority > MAX_RT_PRIO-1)) + return -EINVAL; + if ((dl_policy(policy) && !__checkparam_dl(attr)) || + (rt_policy(policy) != (attr->sched_priority != 0))) + return -EINVAL; + + /* + * Allow unprivileged RT tasks to decrease priority: + */ + if (user && !capable(CAP_SYS_NICE)) { + if (fair_policy(policy)) { + if (attr->sched_nice < TASK_NICE(p) && + !can_nice(p, attr->sched_nice)) + return -EPERM; + } + + if (rt_policy(policy)) { + unsigned long rlim_rtprio = + task_rlimit(p, RLIMIT_RTPRIO); + + /* can't set/change the rt policy */ + if (policy != p->policy && !rlim_rtprio) + return -EPERM; + + /* can't increase priority */ + if (attr->sched_priority > p->rt_priority && + attr->sched_priority > rlim_rtprio) + return -EPERM; + } + + /* + * Treat SCHED_IDLE as nice 20. Only allow a switch to + * SCHED_NORMAL if the RLIMIT_NICE would normally permit it. + */ + if (p->policy == SCHED_IDLE && policy != SCHED_IDLE) { + if (!can_nice(p, TASK_NICE(p))) + return -EPERM; + } + + /* can't change other user's priorities */ + if (!check_same_owner(p)) + return -EPERM; + + /* Normal users shall not reset the sched_reset_on_fork flag */ + if (p->sched_reset_on_fork && !reset_on_fork) + return -EPERM; + } + + if (user) { + retval = security_task_setscheduler(p); + if (retval) + return retval; + } + + /* + * make sure no PI-waiters arrive (or leave) while we are + * changing the priority of the task: + * + * To be able to change p->policy safely, the appropriate + * runqueue lock must be held. + */ + rq = task_rq_lock(p, &flags); + + /* + * Changing the policy of the stop threads its a very bad idea + */ + if (p == rq->stop) { + task_rq_unlock(rq, p, &flags); + return -EINVAL; + } + + /* + * If not changing anything there's no need to proceed further: + */ + if (unlikely(policy == p->policy)) { + if (fair_policy(policy) && attr->sched_nice != TASK_NICE(p)) + goto change; + if (rt_policy(policy) && attr->sched_priority != p->rt_priority) + goto change; + if (dl_policy(policy)) + goto change; + + task_rq_unlock(rq, p, &flags); + return 0; + } +change: + + if (user) { +#ifdef CONFIG_RT_GROUP_SCHED + /* + * Do not allow realtime tasks into groups that have no runtime + * assigned. + */ + if (rt_bandwidth_enabled() && rt_policy(policy) && + task_group(p)->rt_bandwidth.rt_runtime == 0 && + !task_group_is_autogroup(task_group(p))) { + task_rq_unlock(rq, p, &flags); + return -EPERM; + } +#endif +#ifdef CONFIG_SMP + if (dl_bandwidth_enabled() && dl_policy(policy)) { + cpumask_t *span = rq->rd->span; + + /* + * Don't allow tasks with an affinity mask smaller than + * the entire root_domain to become SCHED_DEADLINE. We + * will also fail if there's no bandwidth available. + */ + if (!cpumask_subset(span, &p->cpus_allowed) || + rq->rd->dl_bw.bw == 0) { + task_rq_unlock(rq, p, &flags); + return -EPERM; + } + } +#endif + } + + /* recheck policy now with rq lock held */ + if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) { + policy = oldpolicy = -1; + task_rq_unlock(rq, p, &flags); + goto recheck; + } + + /* + * If setscheduling to SCHED_DEADLINE (or changing the parameters + * of a SCHED_DEADLINE task) we need to check if enough bandwidth + * is available. + */ + if ((dl_policy(policy) || dl_task(p)) && dl_overflow(p, policy, attr)) { + task_rq_unlock(rq, p, &flags); + return -EBUSY; + } + + on_rq = p->on_rq; + running = task_current(rq, p); + if (on_rq) + dequeue_task(rq, p, 0); + if (running) + p->sched_class->put_prev_task(rq, p); + + p->sched_reset_on_fork = reset_on_fork; + + oldprio = p->prio; + prev_class = p->sched_class; + __setscheduler(rq, p, attr); + + if (running) + p->sched_class->set_curr_task(rq); + if (on_rq) + enqueue_task(rq, p, 0); + + check_class_changed(rq, p, prev_class, oldprio); + task_rq_unlock(rq, p, &flags); + + rt_mutex_adjust_pi(p); + + return 0; +} +","@@ -3786,7 +3786,7 @@ static int sched_read_attr(struct sched_attr __user *uattr, + attr->size = usize; + } + +- ret = copy_to_user(uattr, attr, usize); ++ ret = copy_to_user(uattr, attr, attr->size); + if (ret) + return -EFAULT; + ",1481,1812,2048 +14883,"RenderFrameHostImpl* RenderFrameHostManager::UpdateStateForNavigate( + const GURL& dest_url, + SiteInstance* source_instance, + SiteInstance* dest_instance, + ui::PageTransition transition, + bool dest_is_restore, + bool dest_is_view_source_mode, + const GlobalRequestID& transferred_request_id, + int bindings, + bool is_reload) { + SiteInstance* current_instance = render_frame_host_->GetSiteInstance(); + bool was_server_redirect = transfer_navigation_handle_ && + transfer_navigation_handle_->WasServerRedirect(); + scoped_refptr new_instance = GetSiteInstanceForNavigation( + dest_url, source_instance, dest_instance, nullptr, transition, + dest_is_restore, dest_is_view_source_mode, was_server_redirect); + + bool allowed_to_swap_process = + frame_tree_node_->IsMainFrame() || + CanSubframeSwapProcess(dest_url, source_instance, dest_instance, + was_server_redirect); + + if (transfer_navigation_handle_.get() && + transfer_navigation_handle_->GetGlobalRequestID() == + transferred_request_id) { + RenderFrameHostImpl* transferring_rfh = + transfer_navigation_handle_->GetRenderFrameHost(); + bool transfer_started_from_current_rfh = + transferring_rfh == render_frame_host_.get(); + bool should_transfer = + new_instance.get() != transferring_rfh->GetSiteInstance() && + (!transfer_started_from_current_rfh || allowed_to_swap_process); + if (should_transfer) + transfer_navigation_handle_->Transfer(); + } + + if (pending_render_frame_host_) { + if (pending_render_frame_host_->GetSiteInstance() != new_instance) { + CancelPending(); + } else { + CHECK(pending_render_frame_host_->IsRenderFrameLive()); + } + } + + if (new_instance.get() != current_instance && allowed_to_swap_process) { + TRACE_EVENT_INSTANT2( + ""navigation"", + ""RenderFrameHostManager::UpdateStateForNavigate:New SiteInstance"", + TRACE_EVENT_SCOPE_THREAD, + ""current_instance id"", current_instance->GetId(), + ""new_instance id"", new_instance->GetId()); + + + if (!pending_render_frame_host_) + CreatePendingRenderFrameHost(current_instance, new_instance.get()); + DCHECK(pending_render_frame_host_); + if (!pending_render_frame_host_) + return nullptr; + DCHECK_EQ(new_instance, pending_render_frame_host_->GetSiteInstance()); + + pending_render_frame_host_->UpdatePendingWebUI(dest_url, bindings); + pending_render_frame_host_->CommitPendingWebUI(); + DCHECK_EQ(GetNavigatingWebUI(), pending_render_frame_host_->web_ui()); + + if (pending_render_frame_host_->web_ui()) { + pending_render_frame_host_->web_ui()->RenderFrameCreated( + pending_render_frame_host_.get()); + } + + if (!render_frame_host_->IsRenderFrameLive()) { + if (GetRenderFrameProxyHost(new_instance.get())) { + pending_render_frame_host_->Send( + new FrameMsg_SwapIn(pending_render_frame_host_->GetRoutingID())); + } + CommitPending(); + return render_frame_host_.get(); + } + + bool is_transfer = transferred_request_id != GlobalRequestID(); + if (is_transfer) { + DCHECK(transfer_navigation_handle_ && + transfer_navigation_handle_->GetGlobalRequestID() == + transferred_request_id); + } else if (!pending_render_frame_host_->are_navigations_suspended()) { + render_frame_host_->Send(new FrameMsg_Stop( + render_frame_host_->GetRoutingID())); + pending_render_frame_host_->SetNavigationsSuspended(true, + base::TimeTicks()); + render_frame_host_->DispatchBeforeUnload(true, is_reload); + } + + return pending_render_frame_host_.get(); + } + + + DeleteRenderFrameProxyHost(new_instance.get()); + + UpdatePendingWebUIOnCurrentFrameHost(dest_url, bindings); + + if (dest_is_view_source_mode) { + DCHECK(!render_frame_host_->GetParent()); + render_frame_host_->Send( + new FrameMsg_EnableViewSourceMode(render_frame_host_->GetRoutingID())); + } + + return render_frame_host_.get(); +} +",0,"RenderFrameHostImpl* RenderFrameHostManager::UpdateStateForNavigate( + const GURL& dest_url, + SiteInstance* source_instance, + SiteInstance* dest_instance, + ui::PageTransition transition, + bool dest_is_restore, + bool dest_is_view_source_mode, + const GlobalRequestID& transferred_request_id, + int bindings, + bool is_reload) { + SiteInstance* current_instance = render_frame_host_->GetSiteInstance(); + bool was_server_redirect = transfer_navigation_handle_ && + transfer_navigation_handle_->WasServerRedirect(); + scoped_refptr new_instance = GetSiteInstanceForNavigation( + dest_url, source_instance, dest_instance, nullptr, transition, + dest_is_restore, dest_is_view_source_mode, was_server_redirect); + + bool allowed_to_swap_process = + frame_tree_node_->IsMainFrame() || + CanSubframeSwapProcess(dest_url, source_instance, dest_instance, + was_server_redirect); + + if (transfer_navigation_handle_.get() && + transfer_navigation_handle_->GetGlobalRequestID() == + transferred_request_id) { + RenderFrameHostImpl* transferring_rfh = + transfer_navigation_handle_->GetRenderFrameHost(); + bool transfer_started_from_current_rfh = + transferring_rfh == render_frame_host_.get(); + bool should_transfer = + new_instance.get() != transferring_rfh->GetSiteInstance() && + (!transfer_started_from_current_rfh || allowed_to_swap_process); + if (should_transfer) + transfer_navigation_handle_->Transfer(); + } + + if (pending_render_frame_host_) { + if (pending_render_frame_host_->GetSiteInstance() != new_instance) { + CancelPending(); + } else { + CHECK(pending_render_frame_host_->IsRenderFrameLive()); + } + } + + if (new_instance.get() != current_instance && allowed_to_swap_process) { + TRACE_EVENT_INSTANT2( + ""navigation"", + ""RenderFrameHostManager::UpdateStateForNavigate:New SiteInstance"", + TRACE_EVENT_SCOPE_THREAD, + ""current_instance id"", current_instance->GetId(), + ""new_instance id"", new_instance->GetId()); + + + if (!pending_render_frame_host_) + CreatePendingRenderFrameHost(current_instance, new_instance.get()); + DCHECK(pending_render_frame_host_); + if (!pending_render_frame_host_) + return nullptr; + DCHECK_EQ(new_instance, pending_render_frame_host_->GetSiteInstance()); + + pending_render_frame_host_->UpdatePendingWebUI(dest_url, bindings); + pending_render_frame_host_->CommitPendingWebUI(); + DCHECK_EQ(GetNavigatingWebUI(), pending_render_frame_host_->web_ui()); + + if (pending_render_frame_host_->web_ui()) { + pending_render_frame_host_->web_ui()->RenderFrameCreated( + pending_render_frame_host_.get()); + } + + if (!render_frame_host_->IsRenderFrameLive()) { + if (GetRenderFrameProxyHost(new_instance.get())) { + pending_render_frame_host_->Send( + new FrameMsg_SwapIn(pending_render_frame_host_->GetRoutingID())); + } + CommitPending(); + return render_frame_host_.get(); + } + + bool is_transfer = transferred_request_id != GlobalRequestID(); + if (is_transfer) { + DCHECK(transfer_navigation_handle_ && + transfer_navigation_handle_->GetGlobalRequestID() == + transferred_request_id); + } else if (!pending_render_frame_host_->are_navigations_suspended()) { + render_frame_host_->Send(new FrameMsg_Stop( + render_frame_host_->GetRoutingID())); + pending_render_frame_host_->SetNavigationsSuspended(true, + base::TimeTicks()); + render_frame_host_->DispatchBeforeUnload(true, is_reload); + } + + return pending_render_frame_host_.get(); + } + + + DeleteRenderFrameProxyHost(new_instance.get()); + + UpdatePendingWebUIOnCurrentFrameHost(dest_url, bindings); + + if (dest_is_view_source_mode) { + DCHECK(!render_frame_host_->GetParent()); + render_frame_host_->Send( + new FrameMsg_EnableViewSourceMode(render_frame_host_->GetRoutingID())); + } + + return render_frame_host_.get(); +} +","@@ -61,7 +61,6 @@ RenderFrameHostManager::RenderFrameHostManager( + delegate_(delegate), + render_frame_delegate_(render_frame_delegate), + render_widget_delegate_(render_widget_delegate), +- interstitial_page_(nullptr), + weak_factory_(this) { + DCHECK(frame_tree_node_); + } +@@ -133,8 +132,8 @@ WebUIImpl* RenderFrameHostManager::GetNavigatingWebUI() const { + } + + RenderWidgetHostView* RenderFrameHostManager::GetRenderWidgetHostView() const { +- if (interstitial_page_) +- return interstitial_page_->GetView(); ++ if (delegate_->GetInterstitialForRenderManager()) ++ return delegate_->GetInterstitialForRenderManager()->GetView(); + if (render_frame_host_) + return render_frame_host_->GetView(); + return nullptr; +@@ -1424,7 +1423,7 @@ RenderFrameHostManager::DetermineSiteInstanceForURL( + // SiteInstances if you type in a cross-site URL. This means we have to + // compare the entry's URL to the last committed entry's URL. + NavigationEntry* current_entry = controller.GetLastCommittedEntry(); +- if (interstitial_page_) { ++ if (delegate_->GetInterstitialForRenderManager()) { + // The interstitial is currently the last committed entry, but we want to + // compare against the last non-interstitial entry. + current_entry = controller.GetEntryAtOffset(-1); +@@ -2825,13 +2824,13 @@ bool RenderFrameHostManager::CanSubframeSwapProcess( + } + + void RenderFrameHostManager::EnsureRenderFrameHostVisibilityConsistent() { +- if (render_frame_host_->GetView() && +- render_frame_host_->render_view_host()->GetWidget()->is_hidden() != +- delegate_->IsHidden()) { ++ RenderWidgetHostView* view = GetRenderWidgetHostView(); ++ if (view && static_cast(view->GetRenderWidgetHost()) ++ ->is_hidden() != delegate_->IsHidden()) { + if (delegate_->IsHidden()) { +- render_frame_host_->GetView()->Hide(); ++ view->Hide(); + } else { +- render_frame_host_->GetView()->Show(); ++ view->Show(); + } + } + }",842,1173,2048 +17935,"int snd_card_new(struct device *parent, int idx, const char *xid, + struct module *module, int extra_size, + struct snd_card **card_ret) +{ + struct snd_card *card; + int err; + + if (snd_BUG_ON(!card_ret)) + return -EINVAL; + *card_ret = NULL; + + if (extra_size < 0) + extra_size = 0; + card = kzalloc(sizeof(*card) + extra_size, GFP_KERNEL); + if (!card) + return -ENOMEM; + if (extra_size > 0) + card->private_data = (char *)card + sizeof(struct snd_card); + if (xid) + strlcpy(card->id, xid, sizeof(card->id)); + err = 0; + mutex_lock(&snd_card_mutex); + if (idx < 0) /* first check the matching module-name slot */ + idx = get_slot_from_bitmask(idx, module_slot_match, module); + if (idx < 0) /* if not matched, assign an empty slot */ + idx = get_slot_from_bitmask(idx, check_empty_slot, module); + if (idx < 0) + err = -ENODEV; + else if (idx < snd_ecards_limit) { + if (test_bit(idx, snd_cards_lock)) + err = -EBUSY; /* invalid */ + } else if (idx >= SNDRV_CARDS) + err = -ENODEV; + if (err < 0) { + mutex_unlock(&snd_card_mutex); + dev_err(parent, ""cannot find the slot for index %d (range 0-%i), error: %d\n"", + idx, snd_ecards_limit - 1, err); + kfree(card); + return err; + } + set_bit(idx, snd_cards_lock); /* lock it */ + if (idx >= snd_ecards_limit) + snd_ecards_limit = idx + 1; /* increase the limit */ + mutex_unlock(&snd_card_mutex); + card->dev = parent; + card->number = idx; + card->module = module; + INIT_LIST_HEAD(&card->devices); + init_rwsem(&card->controls_rwsem); + rwlock_init(&card->ctl_files_rwlock); + INIT_LIST_HEAD(&card->controls); + INIT_LIST_HEAD(&card->ctl_files); + spin_lock_init(&card->files_lock); + INIT_LIST_HEAD(&card->files_list); +#ifdef CONFIG_PM + mutex_init(&card->power_lock); + init_waitqueue_head(&card->power_sleep); +#endif + + device_initialize(&card->card_dev); + card->card_dev.parent = parent; + card->card_dev.class = sound_class; + card->card_dev.release = release_card_device; + card->card_dev.groups = card_dev_attr_groups; + err = kobject_set_name(&card->card_dev.kobj, ""card%d"", idx); + if (err < 0) + goto __error; + + /* the control interface cannot be accessed from the user space until */ + /* snd_cards_bitmask and snd_cards are set with snd_card_register */ + err = snd_ctl_create(card); + if (err < 0) { + dev_err(parent, ""unable to register control minors\n""); + goto __error; + } + err = snd_info_card_create(card); + if (err < 0) { + dev_err(parent, ""unable to create card info\n""); + goto __error_ctl; + } + *card_ret = card; + return 0; + + __error_ctl: + snd_device_free_all(card); + __error: + put_device(&card->card_dev); + return err; +} +",1,"int snd_card_new(struct device *parent, int idx, const char *xid, + struct module *module, int extra_size, + struct snd_card **card_ret) +{ + struct snd_card *card; + int err; + + if (snd_BUG_ON(!card_ret)) + return -EINVAL; + *card_ret = NULL; + + if (extra_size < 0) + extra_size = 0; + card = kzalloc(sizeof(*card) + extra_size, GFP_KERNEL); + if (!card) + return -ENOMEM; + if (extra_size > 0) + card->private_data = (char *)card + sizeof(struct snd_card); + if (xid) + strlcpy(card->id, xid, sizeof(card->id)); + err = 0; + mutex_lock(&snd_card_mutex); + if (idx < 0) /* first check the matching module-name slot */ + idx = get_slot_from_bitmask(idx, module_slot_match, module); + if (idx < 0) /* if not matched, assign an empty slot */ + idx = get_slot_from_bitmask(idx, check_empty_slot, module); + if (idx < 0) + err = -ENODEV; + else if (idx < snd_ecards_limit) { + if (test_bit(idx, snd_cards_lock)) + err = -EBUSY; /* invalid */ + } else if (idx >= SNDRV_CARDS) + err = -ENODEV; + if (err < 0) { + mutex_unlock(&snd_card_mutex); + dev_err(parent, ""cannot find the slot for index %d (range 0-%i), error: %d\n"", + idx, snd_ecards_limit - 1, err); + kfree(card); + return err; + } + set_bit(idx, snd_cards_lock); /* lock it */ + if (idx >= snd_ecards_limit) + snd_ecards_limit = idx + 1; /* increase the limit */ + mutex_unlock(&snd_card_mutex); + card->dev = parent; + card->number = idx; + card->module = module; + INIT_LIST_HEAD(&card->devices); + init_rwsem(&card->controls_rwsem); + rwlock_init(&card->ctl_files_rwlock); + mutex_init(&card->user_ctl_lock); + INIT_LIST_HEAD(&card->controls); + INIT_LIST_HEAD(&card->ctl_files); + spin_lock_init(&card->files_lock); + INIT_LIST_HEAD(&card->files_list); +#ifdef CONFIG_PM + mutex_init(&card->power_lock); + init_waitqueue_head(&card->power_sleep); +#endif + + device_initialize(&card->card_dev); + card->card_dev.parent = parent; + card->card_dev.class = sound_class; + card->card_dev.release = release_card_device; + card->card_dev.groups = card_dev_attr_groups; + err = kobject_set_name(&card->card_dev.kobj, ""card%d"", idx); + if (err < 0) + goto __error; + + /* the control interface cannot be accessed from the user space until */ + /* snd_cards_bitmask and snd_cards are set with snd_card_register */ + err = snd_ctl_create(card); + if (err < 0) { + dev_err(parent, ""unable to register control minors\n""); + goto __error; + } + err = snd_info_card_create(card); + if (err < 0) { + dev_err(parent, ""unable to create card info\n""); + goto __error_ctl; + } + *card_ret = card; + return 0; + + __error_ctl: + snd_device_free_all(card); + __error: + put_device(&card->card_dev); + return err; +} +","@@ -232,6 +232,7 @@ int snd_card_new(struct device *parent, int idx, const char *xid, + INIT_LIST_HEAD(&card->devices); + init_rwsem(&card->controls_rwsem); + rwlock_init(&card->ctl_files_rwlock); ++ mutex_init(&card->user_ctl_lock); + INIT_LIST_HEAD(&card->controls); + INIT_LIST_HEAD(&card->ctl_files); + spin_lock_init(&card->files_lock);",747,1078,2048 +7188,"_rpc_reattach_tasks(slurm_msg_t *msg) +{ + reattach_tasks_request_msg_t *req = msg->data; + reattach_tasks_response_msg_t *resp = + xmalloc(sizeof(reattach_tasks_response_msg_t)); + slurm_msg_t resp_msg; + int rc = SLURM_SUCCESS; + uint16_t port = 0; + char host[MAXHOSTNAMELEN]; + slurm_addr_t ioaddr; + void *job_cred_sig; + uint32_t len; + int fd; + uid_t req_uid; + slurm_addr_t *cli = &msg->orig_addr; + uint32_t nodeid = (uint32_t)NO_VAL; + uid_t uid = -1; + uint16_t protocol_version; + + slurm_msg_t_copy(&resp_msg, msg); + fd = stepd_connect(conf->spooldir, conf->node_name, + req->job_id, req->job_step_id, &protocol_version); + if (fd == -1) { + debug(""reattach for nonexistent job %u.%u stepd_connect"" + "" failed: %m"", req->job_id, req->job_step_id); + rc = ESLURM_INVALID_JOB_ID; + goto done; + } + + if ((int)(uid = stepd_get_uid(fd, protocol_version)) < 0) { + debug(""_rpc_reattach_tasks couldn't read from the "" + ""step %u.%u: %m"", + req->job_id, req->job_step_id); + rc = ESLURM_INVALID_JOB_ID; + goto done2; + } + + nodeid = stepd_get_nodeid(fd, protocol_version); + + debug2(""_rpc_reattach_tasks: nodeid %d in the job step"", nodeid); + + req_uid = g_slurm_auth_get_uid(msg->auth_cred, conf->auth_info); + if ((req_uid != uid) && (!_slurm_authorized_user(req_uid))) { + error(""uid %ld attempt to attach to job %u.%u owned by %ld"", + (long) req_uid, req->job_id, req->job_step_id, + (long) uid); + rc = EPERM; + goto done2; + } + + memset(resp, 0, sizeof(reattach_tasks_response_msg_t)); + slurm_get_ip_str(cli, &port, host, sizeof(host)); + + /* + * Set response address by resp_port and client address + */ + memcpy(&resp_msg.address, cli, sizeof(slurm_addr_t)); + if (req->num_resp_port > 0) { + port = req->resp_port[nodeid % req->num_resp_port]; + slurm_set_addr(&resp_msg.address, port, NULL); + } + + /* + * Set IO address by io_port and client address + */ + memcpy(&ioaddr, cli, sizeof(slurm_addr_t)); + + if (req->num_io_port > 0) { + port = req->io_port[nodeid % req->num_io_port]; + slurm_set_addr(&ioaddr, port, NULL); + } + + /* + * Get the signature of the job credential. slurmstepd will need + * this to prove its identity when it connects back to srun. + */ + slurm_cred_get_signature(req->cred, (char **)(&job_cred_sig), &len); + if (len != SLURM_IO_KEY_SIZE) { + error(""Incorrect slurm cred signature length""); + goto done2; + } + + resp->gtids = NULL; + resp->local_pids = NULL; + + /* NOTE: We need to use the protocol_version from + * sattach here since responses will be sent back to it. */ + if (msg->protocol_version < protocol_version) + protocol_version = msg->protocol_version; + + /* Following call fills in gtids and local_pids when successful. */ + rc = stepd_attach(fd, protocol_version, &ioaddr, + &resp_msg.address, job_cred_sig, resp); + if (rc != SLURM_SUCCESS) { + debug2(""stepd_attach call failed""); + goto done2; + } + +done2: + close(fd); +done: + debug2(""update step addrs rc = %d"", rc); + resp_msg.data = resp; + resp_msg.msg_type = RESPONSE_REATTACH_TASKS; + resp->node_name = xstrdup(conf->node_name); + resp->return_code = rc; + debug2(""node %s sending rc = %d"", conf->node_name, rc); + + slurm_send_node_msg(msg->conn_fd, &resp_msg); + slurm_free_reattach_tasks_response_msg(resp); +} +",0,"_rpc_reattach_tasks(slurm_msg_t *msg) +{ + reattach_tasks_request_msg_t *req = msg->data; + reattach_tasks_response_msg_t *resp = + xmalloc(sizeof(reattach_tasks_response_msg_t)); + slurm_msg_t resp_msg; + int rc = SLURM_SUCCESS; + uint16_t port = 0; + char host[MAXHOSTNAMELEN]; + slurm_addr_t ioaddr; + void *job_cred_sig; + uint32_t len; + int fd; + uid_t req_uid; + slurm_addr_t *cli = &msg->orig_addr; + uint32_t nodeid = (uint32_t)NO_VAL; + uid_t uid = -1; + uint16_t protocol_version; + + slurm_msg_t_copy(&resp_msg, msg); + fd = stepd_connect(conf->spooldir, conf->node_name, + req->job_id, req->job_step_id, &protocol_version); + if (fd == -1) { + debug(""reattach for nonexistent job %u.%u stepd_connect"" + "" failed: %m"", req->job_id, req->job_step_id); + rc = ESLURM_INVALID_JOB_ID; + goto done; + } + + if ((int)(uid = stepd_get_uid(fd, protocol_version)) < 0) { + debug(""_rpc_reattach_tasks couldn't read from the "" + ""step %u.%u: %m"", + req->job_id, req->job_step_id); + rc = ESLURM_INVALID_JOB_ID; + goto done2; + } + + nodeid = stepd_get_nodeid(fd, protocol_version); + + debug2(""_rpc_reattach_tasks: nodeid %d in the job step"", nodeid); + + req_uid = g_slurm_auth_get_uid(msg->auth_cred, conf->auth_info); + if ((req_uid != uid) && (!_slurm_authorized_user(req_uid))) { + error(""uid %ld attempt to attach to job %u.%u owned by %ld"", + (long) req_uid, req->job_id, req->job_step_id, + (long) uid); + rc = EPERM; + goto done2; + } + + memset(resp, 0, sizeof(reattach_tasks_response_msg_t)); + slurm_get_ip_str(cli, &port, host, sizeof(host)); + + /* + * Set response address by resp_port and client address + */ + memcpy(&resp_msg.address, cli, sizeof(slurm_addr_t)); + if (req->num_resp_port > 0) { + port = req->resp_port[nodeid % req->num_resp_port]; + slurm_set_addr(&resp_msg.address, port, NULL); + } + + /* + * Set IO address by io_port and client address + */ + memcpy(&ioaddr, cli, sizeof(slurm_addr_t)); + + if (req->num_io_port > 0) { + port = req->io_port[nodeid % req->num_io_port]; + slurm_set_addr(&ioaddr, port, NULL); + } + + /* + * Get the signature of the job credential. slurmstepd will need + * this to prove its identity when it connects back to srun. + */ + slurm_cred_get_signature(req->cred, (char **)(&job_cred_sig), &len); + if (len != SLURM_IO_KEY_SIZE) { + error(""Incorrect slurm cred signature length""); + goto done2; + } + + resp->gtids = NULL; + resp->local_pids = NULL; + + /* NOTE: We need to use the protocol_version from + * sattach here since responses will be sent back to it. */ + if (msg->protocol_version < protocol_version) + protocol_version = msg->protocol_version; + + /* Following call fills in gtids and local_pids when successful. */ + rc = stepd_attach(fd, protocol_version, &ioaddr, + &resp_msg.address, job_cred_sig, resp); + if (rc != SLURM_SUCCESS) { + debug2(""stepd_attach call failed""); + goto done2; + } + +done2: + close(fd); +done: + debug2(""update step addrs rc = %d"", rc); + resp_msg.data = resp; + resp_msg.msg_type = RESPONSE_REATTACH_TASKS; + resp->node_name = xstrdup(conf->node_name); + resp->return_code = rc; + debug2(""node %s sending rc = %d"", conf->node_name, rc); + + slurm_send_node_msg(msg->conn_fd, &resp_msg); + slurm_free_reattach_tasks_response_msg(resp); +} +","@@ -168,6 +168,7 @@ static void _note_batch_job_finished(uint32_t job_id); + static int _prolog_is_running (uint32_t jobid); + static int _step_limits_match(void *x, void *key); + static int _terminate_all_steps(uint32_t jobid, bool batch); ++static int _receive_fd(int socket); + static void _rpc_launch_tasks(slurm_msg_t *); + static void _rpc_abort_job(slurm_msg_t *); + static void _rpc_batch_job(slurm_msg_t *msg, bool new_msg); +@@ -214,6 +215,7 @@ static void _sync_messages_kill(kill_job_msg_t *req); + static int _waiter_init (uint32_t jobid); + static int _waiter_complete (uint32_t jobid); + ++static void _send_back_fd(int socket, int fd); + static bool _steps_completed_now(uint32_t jobid); + static int _valid_sbcast_cred(file_bcast_msg_t *req, uid_t req_uid, + uint16_t block_no, uint32_t *job_id); +@@ -1383,6 +1385,111 @@ _rpc_launch_tasks(slurm_msg_t *msg) + send_registration_msg(errnum, false); + } + ++/* ++ * Open file based upon permissions of a different user ++ * IN path_name - name of file to open ++ * IN uid - User ID to use for file access check ++ * IN gid - Group ID to use for file access check ++ * RET -1 on error, file descriptor otherwise ++ */ ++static int _open_as_other(char *path_name, batch_job_launch_msg_t *req) ++{ ++ pid_t child; ++ gids_t *gids; ++ int pipe[2]; ++ int fd = -1, rc = 0; ++ ++ if (!(gids = _gids_cache_lookup(req->user_name, req->gid))) { ++ error(""%s: gids_cache_lookup for %s failed"", ++ __func__, req->user_name); ++ return -1; ++ } ++ ++ if ((rc = container_g_create(req->job_id))) { ++ error(""%s: container_g_create(%u): %m"", __func__, req->job_id); ++ _dealloc_gids(gids); ++ return -1; ++ } ++ ++ /* child process will setuid to the user, register the process ++ * with the container, and open the file for us. */ ++ if (socketpair(AF_UNIX, SOCK_DGRAM, 0, pipe) != 0) { ++ error(""%s: Failed to open pipe: %m"", __func__); ++ _dealloc_gids(gids); ++ return -1; ++ } ++ ++ child = fork(); ++ if (child == -1) { ++ error(""%s: fork failure"", __func__); ++ _dealloc_gids(gids); ++ close(pipe[0]); ++ close(pipe[1]); ++ return -1; ++ } else if (child > 0) { ++ close(pipe[0]); ++ (void) waitpid(child, &rc, 0); ++ _dealloc_gids(gids); ++ if (WIFEXITED(rc) && (WEXITSTATUS(rc) == 0)) ++ fd = _receive_fd(pipe[1]); ++ close(pipe[1]); ++ return fd; ++ } ++ ++ /* child process below here */ ++ ++ close(pipe[1]); ++ ++ /* container_g_add_pid needs to be called in the ++ * forked process part of the fork to avoid a race ++ * condition where if this process makes a file or ++ * detacts itself from a child before we add the pid ++ * to the container in the parent of the fork. */ ++ if (container_g_add_pid(req->job_id, getpid(), req->uid)) { ++ error(""%s container_g_add_pid(%u): %m"", __func__, req->job_id); ++ exit(SLURM_ERROR); ++ } ++ ++ /* The child actually performs the I/O and exits with ++ * a return code, do not return! */ ++ ++ /*********************************************************************\ ++ * NOTE: It would be best to do an exec() immediately after the fork() ++ * in order to help prevent a possible deadlock in the child process ++ * due to locks being set at the time of the fork and being freed by ++ * the parent process, but not freed by the child process. Performing ++ * the work inline is done for simplicity. Note that the logging ++ * performed by error() should be safe due to the use of ++ * atfork_install_handlers() as defined in src/common/log.c. ++ * Change the code below with caution. ++ \*********************************************************************/ ++ ++ if (setgroups(gids->ngids, gids->gids) < 0) { ++ error(""%s: uid: %u setgroups failed: %m"", __func__, req->uid); ++ exit(errno); ++ } ++ _dealloc_gids(gids); ++ ++ if (setgid(req->gid) < 0) { ++ error(""%s: uid:%u setgid(%u): %m"", __func__, req->uid,req->gid); ++ exit(errno); ++ } ++ if (setuid(req->uid) < 0) { ++ error(""%s: getuid(%u): %m"", __func__, req->uid); ++ exit(errno); ++ } ++ ++ fd = open(path_name, (O_CREAT|O_APPEND|O_WRONLY), 0644); ++ if (fd == -1) { ++ error(""%s: uid:%u can't open `%s`: %m"", ++ __func__, req->uid, path_name); ++ exit(errno); ++ } ++ _send_back_fd(pipe[0], fd); ++ close(fd); ++ exit(SLURM_SUCCESS); ++} ++ + static void + _prolog_error(batch_job_launch_msg_t *req, int rc) + { +@@ -1415,10 +1522,8 @@ _prolog_error(batch_job_launch_msg_t *req, int rc) + req->work_dir, err_name_ptr); + else + snprintf(path_name, MAXPATHLEN, ""/%s"", err_name_ptr); +- +- if ((fd = open(path_name, (O_CREAT|O_APPEND|O_WRONLY), 0644)) == -1) { +- error(""Unable to open %s: %s"", path_name, +- slurm_strerror(errno)); ++ if ((fd = _open_as_other(path_name, req)) == -1) { ++ error(""Unable to open %s: Permission denied"", path_name); + return; + } + snprintf(err_name, sizeof(err_name),",980,1311,2048 +17008,"xsltFreeStylePreComp(xsltStylePreCompPtr comp) { + if (comp == NULL) + return; +#ifdef XSLT_REFACTORED + /* + * URGENT TODO: Implement destructors. + */ + switch (comp->type) { + case XSLT_FUNC_LITERAL_RESULT_ELEMENT: + break; + case XSLT_FUNC_COPY: + break; + case XSLT_FUNC_SORT: { + xsltStyleItemSortPtr item = (xsltStyleItemSortPtr) comp; + if (item->locale != (xsltLocale)0) + xsltFreeLocale(item->locale); + if (item->comp != NULL) + xmlXPathFreeCompExpr(item->comp); + } + break; + case XSLT_FUNC_TEXT: + break; + case XSLT_FUNC_ELEMENT: + break; + case XSLT_FUNC_ATTRIBUTE: + break; + case XSLT_FUNC_COMMENT: + break; + case XSLT_FUNC_PI: + break; + case XSLT_FUNC_COPYOF: { + xsltStyleItemCopyOfPtr item = (xsltStyleItemCopyOfPtr) comp; + if (item->comp != NULL) + xmlXPathFreeCompExpr(item->comp); + } + break; + case XSLT_FUNC_VALUEOF: { + xsltStyleItemValueOfPtr item = (xsltStyleItemValueOfPtr) comp; + if (item->comp != NULL) + xmlXPathFreeCompExpr(item->comp); + } + break; + case XSLT_FUNC_NUMBER: { + xsltStyleItemNumberPtr item = (xsltStyleItemNumberPtr) comp; + if (item->numdata.countPat != NULL) + xsltFreeCompMatchList(item->numdata.countPat); + if (item->numdata.fromPat != NULL) + xsltFreeCompMatchList(item->numdata.fromPat); + } + break; + case XSLT_FUNC_APPLYIMPORTS: + break; + case XSLT_FUNC_CALLTEMPLATE: + break; + case XSLT_FUNC_APPLYTEMPLATES: { + xsltStyleItemApplyTemplatesPtr item = + (xsltStyleItemApplyTemplatesPtr) comp; + if (item->comp != NULL) + xmlXPathFreeCompExpr(item->comp); + } + break; + case XSLT_FUNC_CHOOSE: + break; + case XSLT_FUNC_IF: { + xsltStyleItemIfPtr item = (xsltStyleItemIfPtr) comp; + if (item->comp != NULL) + xmlXPathFreeCompExpr(item->comp); + } + break; + case XSLT_FUNC_FOREACH: { + xsltStyleItemForEachPtr item = + (xsltStyleItemForEachPtr) comp; + if (item->comp != NULL) + xmlXPathFreeCompExpr(item->comp); + } + break; + case XSLT_FUNC_DOCUMENT: + break; + case XSLT_FUNC_WITHPARAM: { + xsltStyleItemWithParamPtr item = + (xsltStyleItemWithParamPtr) comp; + if (item->comp != NULL) + xmlXPathFreeCompExpr(item->comp); + } + break; + case XSLT_FUNC_PARAM: { + xsltStyleItemParamPtr item = + (xsltStyleItemParamPtr) comp; + if (item->comp != NULL) + xmlXPathFreeCompExpr(item->comp); + } + break; + case XSLT_FUNC_VARIABLE: { + xsltStyleItemVariablePtr item = + (xsltStyleItemVariablePtr) comp; + if (item->comp != NULL) + xmlXPathFreeCompExpr(item->comp); + } + break; + case XSLT_FUNC_WHEN: { + xsltStyleItemWhenPtr item = + (xsltStyleItemWhenPtr) comp; + if (item->comp != NULL) + xmlXPathFreeCompExpr(item->comp); + } + break; + case XSLT_FUNC_OTHERWISE: + case XSLT_FUNC_FALLBACK: + case XSLT_FUNC_MESSAGE: + case XSLT_FUNC_INCLUDE: + case XSLT_FUNC_ATTRSET: + + break; + default: + /* TODO: Raise error. */ + break; + } +#else + if (comp->locale != (xsltLocale)0) + xsltFreeLocale(comp->locale); + if (comp->comp != NULL) + xmlXPathFreeCompExpr(comp->comp); + if (comp->numdata.countPat != NULL) + xsltFreeCompMatchList(comp->numdata.countPat); + if (comp->numdata.fromPat != NULL) + xsltFreeCompMatchList(comp->numdata.fromPat); + if (comp->nsList != NULL) + xmlFree(comp->nsList); +#endif + + xmlFree(comp); +} +",0,"xsltFreeStylePreComp(xsltStylePreCompPtr comp) { + if (comp == NULL) + return; +#ifdef XSLT_REFACTORED + /* + * URGENT TODO: Implement destructors. + */ + switch (comp->type) { + case XSLT_FUNC_LITERAL_RESULT_ELEMENT: + break; + case XSLT_FUNC_COPY: + break; + case XSLT_FUNC_SORT: { + xsltStyleItemSortPtr item = (xsltStyleItemSortPtr) comp; + if (item->locale != (xsltLocale)0) + xsltFreeLocale(item->locale); + if (item->comp != NULL) + xmlXPathFreeCompExpr(item->comp); + } + break; + case XSLT_FUNC_TEXT: + break; + case XSLT_FUNC_ELEMENT: + break; + case XSLT_FUNC_ATTRIBUTE: + break; + case XSLT_FUNC_COMMENT: + break; + case XSLT_FUNC_PI: + break; + case XSLT_FUNC_COPYOF: { + xsltStyleItemCopyOfPtr item = (xsltStyleItemCopyOfPtr) comp; + if (item->comp != NULL) + xmlXPathFreeCompExpr(item->comp); + } + break; + case XSLT_FUNC_VALUEOF: { + xsltStyleItemValueOfPtr item = (xsltStyleItemValueOfPtr) comp; + if (item->comp != NULL) + xmlXPathFreeCompExpr(item->comp); + } + break; + case XSLT_FUNC_NUMBER: { + xsltStyleItemNumberPtr item = (xsltStyleItemNumberPtr) comp; + if (item->numdata.countPat != NULL) + xsltFreeCompMatchList(item->numdata.countPat); + if (item->numdata.fromPat != NULL) + xsltFreeCompMatchList(item->numdata.fromPat); + } + break; + case XSLT_FUNC_APPLYIMPORTS: + break; + case XSLT_FUNC_CALLTEMPLATE: + break; + case XSLT_FUNC_APPLYTEMPLATES: { + xsltStyleItemApplyTemplatesPtr item = + (xsltStyleItemApplyTemplatesPtr) comp; + if (item->comp != NULL) + xmlXPathFreeCompExpr(item->comp); + } + break; + case XSLT_FUNC_CHOOSE: + break; + case XSLT_FUNC_IF: { + xsltStyleItemIfPtr item = (xsltStyleItemIfPtr) comp; + if (item->comp != NULL) + xmlXPathFreeCompExpr(item->comp); + } + break; + case XSLT_FUNC_FOREACH: { + xsltStyleItemForEachPtr item = + (xsltStyleItemForEachPtr) comp; + if (item->comp != NULL) + xmlXPathFreeCompExpr(item->comp); + } + break; + case XSLT_FUNC_DOCUMENT: + break; + case XSLT_FUNC_WITHPARAM: { + xsltStyleItemWithParamPtr item = + (xsltStyleItemWithParamPtr) comp; + if (item->comp != NULL) + xmlXPathFreeCompExpr(item->comp); + } + break; + case XSLT_FUNC_PARAM: { + xsltStyleItemParamPtr item = + (xsltStyleItemParamPtr) comp; + if (item->comp != NULL) + xmlXPathFreeCompExpr(item->comp); + } + break; + case XSLT_FUNC_VARIABLE: { + xsltStyleItemVariablePtr item = + (xsltStyleItemVariablePtr) comp; + if (item->comp != NULL) + xmlXPathFreeCompExpr(item->comp); + } + break; + case XSLT_FUNC_WHEN: { + xsltStyleItemWhenPtr item = + (xsltStyleItemWhenPtr) comp; + if (item->comp != NULL) + xmlXPathFreeCompExpr(item->comp); + } + break; + case XSLT_FUNC_OTHERWISE: + case XSLT_FUNC_FALLBACK: + case XSLT_FUNC_MESSAGE: + case XSLT_FUNC_INCLUDE: + case XSLT_FUNC_ATTRSET: + + break; + default: + /* TODO: Raise error. */ + break; + } +#else + if (comp->locale != (xsltLocale)0) + xsltFreeLocale(comp->locale); + if (comp->comp != NULL) + xmlXPathFreeCompExpr(comp->comp); + if (comp->numdata.countPat != NULL) + xsltFreeCompMatchList(comp->numdata.countPat); + if (comp->numdata.fromPat != NULL) + xsltFreeCompMatchList(comp->numdata.fromPat); + if (comp->nsList != NULL) + xmlFree(comp->nsList); +#endif + + xmlFree(comp); +} +","@@ -949,6 +949,8 @@ xsltElementComp(xsltStylesheetPtr style, xmlNodePtr inst) { + #ifdef XSLT_REFACTORED + comp->nsPrefix = prefix; + comp->name = name; ++#else ++ (void)name; /* Suppress unused variable warning. */ + #endif + } else if (prefix != NULL) { + xsltTransformError(NULL, style, inst, +@@ -1074,6 +1076,8 @@ xsltAttributeComp(xsltStylesheetPtr style, xmlNodePtr inst) { + #ifdef XSLT_REFACTORED + comp->nsPrefix = prefix; + comp->name = name; ++#else ++ (void)name; /* Suppress unused variable warning. */ + #endif + } else { + xsltTransformError(NULL, style, inst, +@@ -1301,7 +1305,8 @@ xsltGetQNameProperty(xsltStylesheetPtr style, xmlNodePtr inst, + if (prop == NULL) { + style->errors++; + } else { +- *localName = prop; ++ if (localName) ++ *localName = prop; + if (hasProp) + *hasProp = 1; + if (URI != NULL) { +@@ -2245,7 +2250,8 @@ xsltStylePreCompute(xsltStylesheetPtr style, xmlNodePtr inst) { + } else if (IS_XSLT_NAME(inst, ""attribute"")) { + xmlNodePtr parent = inst->parent; + +- if ((parent == NULL) || (parent->ns == NULL) || ++ if ((parent == NULL) || ++ (parent->type != XML_ELEMENT_NODE) || (parent->ns == NULL) || + ((parent->ns != inst->ns) && + (!xmlStrEqual(parent->ns->href, inst->ns->href))) || + (!xmlStrEqual(parent->name, BAD_CAST ""attribute-set""))) {",1002,1333,2048 +1983,"void rds_recv_incoming(struct rds_connection *conn, __be32 saddr, __be32 daddr, + struct rds_incoming *inc, gfp_t gfp) +{ + struct rds_sock *rs = NULL; + struct sock *sk; + unsigned long flags; + + inc->i_conn = conn; + inc->i_rx_jiffies = jiffies; + + rdsdebug(""conn %p next %llu inc %p seq %llu len %u sport %u dport %u "" + ""flags 0x%x rx_jiffies %lu\n"", conn, + (unsigned long long)conn->c_next_rx_seq, + inc, + (unsigned long long)be64_to_cpu(inc->i_hdr.h_sequence), + be32_to_cpu(inc->i_hdr.h_len), + be16_to_cpu(inc->i_hdr.h_sport), + be16_to_cpu(inc->i_hdr.h_dport), + inc->i_hdr.h_flags, + inc->i_rx_jiffies); + + /* + * Sequence numbers should only increase. Messages get their + * sequence number as they're queued in a sending conn. They + * can be dropped, though, if the sending socket is closed before + * they hit the wire. So sequence numbers can skip forward + * under normal operation. They can also drop back in the conn + * failover case as previously sent messages are resent down the + * new instance of a conn. We drop those, otherwise we have + * to assume that the next valid seq does not come after a + * hole in the fragment stream. + * + * The headers don't give us a way to realize if fragments of + * a message have been dropped. We assume that frags that arrive + * to a flow are part of the current message on the flow that is + * being reassembled. This means that senders can't drop messages + * from the sending conn until all their frags are sent. + * + * XXX we could spend more on the wire to get more robust failure + * detection, arguably worth it to avoid data corruption. + */ + if (be64_to_cpu(inc->i_hdr.h_sequence) < conn->c_next_rx_seq && + (inc->i_hdr.h_flags & RDS_FLAG_RETRANSMITTED)) { + rds_stats_inc(s_recv_drop_old_seq); + goto out; + } + conn->c_next_rx_seq = be64_to_cpu(inc->i_hdr.h_sequence) + 1; + + if (rds_sysctl_ping_enable && inc->i_hdr.h_dport == 0) { + rds_stats_inc(s_recv_ping); + rds_send_pong(conn, inc->i_hdr.h_sport); + goto out; + } + + rs = rds_find_bound(daddr, inc->i_hdr.h_dport); + if (!rs) { + rds_stats_inc(s_recv_drop_no_sock); + goto out; + } + + /* Process extension headers */ + rds_recv_incoming_exthdrs(inc, rs); + + /* We can be racing with rds_release() which marks the socket dead. */ + sk = rds_rs_to_sk(rs); + + /* serialize with rds_release -> sock_orphan */ + write_lock_irqsave(&rs->rs_recv_lock, flags); + if (!sock_flag(sk, SOCK_DEAD)) { + rdsdebug(""adding inc %p to rs %p's recv queue\n"", inc, rs); + rds_stats_inc(s_recv_queued); + rds_recv_rcvbuf_delta(rs, sk, inc->i_conn->c_lcong, + be32_to_cpu(inc->i_hdr.h_len), + inc->i_hdr.h_dport); + rds_inc_addref(inc); + list_add_tail(&inc->i_item, &rs->rs_recv_queue); + __rds_wake_sk_sleep(sk); + } else { + rds_stats_inc(s_recv_drop_dead_sock); + } + write_unlock_irqrestore(&rs->rs_recv_lock, flags); + +out: + if (rs) + rds_sock_put(rs); +} +",0,"void rds_recv_incoming(struct rds_connection *conn, __be32 saddr, __be32 daddr, + struct rds_incoming *inc, gfp_t gfp) +{ + struct rds_sock *rs = NULL; + struct sock *sk; + unsigned long flags; + + inc->i_conn = conn; + inc->i_rx_jiffies = jiffies; + + rdsdebug(""conn %p next %llu inc %p seq %llu len %u sport %u dport %u "" + ""flags 0x%x rx_jiffies %lu\n"", conn, + (unsigned long long)conn->c_next_rx_seq, + inc, + (unsigned long long)be64_to_cpu(inc->i_hdr.h_sequence), + be32_to_cpu(inc->i_hdr.h_len), + be16_to_cpu(inc->i_hdr.h_sport), + be16_to_cpu(inc->i_hdr.h_dport), + inc->i_hdr.h_flags, + inc->i_rx_jiffies); + + /* + * Sequence numbers should only increase. Messages get their + * sequence number as they're queued in a sending conn. They + * can be dropped, though, if the sending socket is closed before + * they hit the wire. So sequence numbers can skip forward + * under normal operation. They can also drop back in the conn + * failover case as previously sent messages are resent down the + * new instance of a conn. We drop those, otherwise we have + * to assume that the next valid seq does not come after a + * hole in the fragment stream. + * + * The headers don't give us a way to realize if fragments of + * a message have been dropped. We assume that frags that arrive + * to a flow are part of the current message on the flow that is + * being reassembled. This means that senders can't drop messages + * from the sending conn until all their frags are sent. + * + * XXX we could spend more on the wire to get more robust failure + * detection, arguably worth it to avoid data corruption. + */ + if (be64_to_cpu(inc->i_hdr.h_sequence) < conn->c_next_rx_seq && + (inc->i_hdr.h_flags & RDS_FLAG_RETRANSMITTED)) { + rds_stats_inc(s_recv_drop_old_seq); + goto out; + } + conn->c_next_rx_seq = be64_to_cpu(inc->i_hdr.h_sequence) + 1; + + if (rds_sysctl_ping_enable && inc->i_hdr.h_dport == 0) { + rds_stats_inc(s_recv_ping); + rds_send_pong(conn, inc->i_hdr.h_sport); + goto out; + } + + rs = rds_find_bound(daddr, inc->i_hdr.h_dport); + if (!rs) { + rds_stats_inc(s_recv_drop_no_sock); + goto out; + } + + /* Process extension headers */ + rds_recv_incoming_exthdrs(inc, rs); + + /* We can be racing with rds_release() which marks the socket dead. */ + sk = rds_rs_to_sk(rs); + + /* serialize with rds_release -> sock_orphan */ + write_lock_irqsave(&rs->rs_recv_lock, flags); + if (!sock_flag(sk, SOCK_DEAD)) { + rdsdebug(""adding inc %p to rs %p's recv queue\n"", inc, rs); + rds_stats_inc(s_recv_queued); + rds_recv_rcvbuf_delta(rs, sk, inc->i_conn->c_lcong, + be32_to_cpu(inc->i_hdr.h_len), + inc->i_hdr.h_dport); + rds_inc_addref(inc); + list_add_tail(&inc->i_item, &rs->rs_recv_queue); + __rds_wake_sk_sleep(sk); + } else { + rds_stats_inc(s_recv_drop_dead_sock); + } + write_unlock_irqrestore(&rs->rs_recv_lock, flags); + +out: + if (rs) + rds_sock_put(rs); +} +","@@ -410,6 +410,8 @@ int rds_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, + + rdsdebug(""size %zu flags 0x%x timeo %ld\n"", size, msg_flags, timeo); + ++ msg->msg_namelen = 0; ++ + if (msg_flags & MSG_OOB) + goto out; + +@@ -485,6 +487,7 @@ int rds_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, + sin->sin_port = inc->i_hdr.h_sport; + sin->sin_addr.s_addr = inc->i_saddr; + memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); ++ msg->msg_namelen = sizeof(*sin); + } + break; + }",879,1210,2048 +1139,"static int exif_process_user_comment(image_info_type *ImageInfo, char **pszInfoPtr, char **pszEncoding, char *szValuePtr, int ByteCount TSRMLS_DC) +{ + int a; + char *decode; + size_t len;; + + *pszEncoding = NULL; + /* Copy the comment */ + if (ByteCount>=8) { + if (!memcmp(szValuePtr, ""UNICODE\0"", 8)) { + *pszEncoding = estrdup((const char*)szValuePtr); + szValuePtr = szValuePtr+8; + ByteCount -= 8; + /* First try to detect BOM: ZERO WIDTH NOBREAK SPACE (FEFF 16) + * since we have no encoding support for the BOM yet we skip that. + */ + if (!memcmp(szValuePtr, ""\xFE\xFF"", 2)) { + decode = ""UCS-2BE""; + szValuePtr = szValuePtr+2; + ByteCount -= 2; + } else if (!memcmp(szValuePtr, ""\xFF\xFE"", 2)) { + decode = ""UCS-2LE""; + szValuePtr = szValuePtr+2; + ByteCount -= 2; + } else if (ImageInfo->motorola_intel) { + decode = ImageInfo->decode_unicode_be; + } else { + decode = ImageInfo->decode_unicode_le; + } + /* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX */ + if (zend_multibyte_encoding_converter( + (unsigned char**)pszInfoPtr, + &len, + (unsigned char*)szValuePtr, + ByteCount, + zend_multibyte_fetch_encoding(ImageInfo->encode_unicode TSRMLS_CC), + zend_multibyte_fetch_encoding(decode TSRMLS_CC) + TSRMLS_CC) == (size_t)-1) { + len = exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount); + } + return len; + } else if (!memcmp(szValuePtr, ""ASCII\0\0\0"", 8)) { + *pszEncoding = estrdup((const char*)szValuePtr); + szValuePtr = szValuePtr+8; + ByteCount -= 8; + } else if (!memcmp(szValuePtr, ""JIS\0\0\0\0\0"", 8)) { + /* JIS should be tanslated to MB or we leave it to the user - leave it to the user */ + *pszEncoding = estrdup((const char*)szValuePtr); + szValuePtr = szValuePtr+8; + ByteCount -= 8; + /* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX */ + if (zend_multibyte_encoding_converter( + (unsigned char**)pszInfoPtr, + &len, + (unsigned char*)szValuePtr, + ByteCount, + zend_multibyte_fetch_encoding(ImageInfo->encode_jis TSRMLS_CC), + zend_multibyte_fetch_encoding(ImageInfo->motorola_intel ? ImageInfo->decode_jis_be : ImageInfo->decode_jis_le TSRMLS_CC) + TSRMLS_CC) == (size_t)-1) { + len = exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount); + } + return len; + } else if (!memcmp(szValuePtr, ""\0\0\0\0\0\0\0\0"", 8)) { + /* 8 NULL means undefined and should be ASCII... */ + *pszEncoding = estrdup(""UNDEFINED""); + szValuePtr = szValuePtr+8; + ByteCount -= 8; + } + } + + /* Olympus has this padded with trailing spaces. Remove these first. */ + if (ByteCount>0) { + for (a=ByteCount-1;a && szValuePtr[a]==' ';a--) { + (szValuePtr)[a] = '\0'; + } + } + + /* normal text without encoding */ + exif_process_string(pszInfoPtr, szValuePtr, ByteCount TSRMLS_CC); + return strlen(*pszInfoPtr); +} +",0,"static int exif_process_user_comment(image_info_type *ImageInfo, char **pszInfoPtr, char **pszEncoding, char *szValuePtr, int ByteCount TSRMLS_DC) +{ + int a; + char *decode; + size_t len;; + + *pszEncoding = NULL; + /* Copy the comment */ + if (ByteCount>=8) { + if (!memcmp(szValuePtr, ""UNICODE\0"", 8)) { + *pszEncoding = estrdup((const char*)szValuePtr); + szValuePtr = szValuePtr+8; + ByteCount -= 8; + /* First try to detect BOM: ZERO WIDTH NOBREAK SPACE (FEFF 16) + * since we have no encoding support for the BOM yet we skip that. + */ + if (!memcmp(szValuePtr, ""\xFE\xFF"", 2)) { + decode = ""UCS-2BE""; + szValuePtr = szValuePtr+2; + ByteCount -= 2; + } else if (!memcmp(szValuePtr, ""\xFF\xFE"", 2)) { + decode = ""UCS-2LE""; + szValuePtr = szValuePtr+2; + ByteCount -= 2; + } else if (ImageInfo->motorola_intel) { + decode = ImageInfo->decode_unicode_be; + } else { + decode = ImageInfo->decode_unicode_le; + } + /* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX */ + if (zend_multibyte_encoding_converter( + (unsigned char**)pszInfoPtr, + &len, + (unsigned char*)szValuePtr, + ByteCount, + zend_multibyte_fetch_encoding(ImageInfo->encode_unicode TSRMLS_CC), + zend_multibyte_fetch_encoding(decode TSRMLS_CC) + TSRMLS_CC) == (size_t)-1) { + len = exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount); + } + return len; + } else if (!memcmp(szValuePtr, ""ASCII\0\0\0"", 8)) { + *pszEncoding = estrdup((const char*)szValuePtr); + szValuePtr = szValuePtr+8; + ByteCount -= 8; + } else if (!memcmp(szValuePtr, ""JIS\0\0\0\0\0"", 8)) { + /* JIS should be tanslated to MB or we leave it to the user - leave it to the user */ + *pszEncoding = estrdup((const char*)szValuePtr); + szValuePtr = szValuePtr+8; + ByteCount -= 8; + /* XXX this will fail again if encoding_converter returns on error something different than SIZE_MAX */ + if (zend_multibyte_encoding_converter( + (unsigned char**)pszInfoPtr, + &len, + (unsigned char*)szValuePtr, + ByteCount, + zend_multibyte_fetch_encoding(ImageInfo->encode_jis TSRMLS_CC), + zend_multibyte_fetch_encoding(ImageInfo->motorola_intel ? ImageInfo->decode_jis_be : ImageInfo->decode_jis_le TSRMLS_CC) + TSRMLS_CC) == (size_t)-1) { + len = exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount); + } + return len; + } else if (!memcmp(szValuePtr, ""\0\0\0\0\0\0\0\0"", 8)) { + /* 8 NULL means undefined and should be ASCII... */ + *pszEncoding = estrdup(""UNDEFINED""); + szValuePtr = szValuePtr+8; + ByteCount -= 8; + } + } + + /* Olympus has this padded with trailing spaces. Remove these first. */ + if (ByteCount>0) { + for (a=ByteCount-1;a && szValuePtr[a]==' ';a--) { + (szValuePtr)[a] = '\0'; + } + } + + /* normal text without encoding */ + exif_process_string(pszInfoPtr, szValuePtr, ByteCount TSRMLS_CC); + return strlen(*pszInfoPtr); +} +","@@ -2965,7 +2965,7 @@ static int exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, cha + /* When there are any characters after the first NUL */ + ImageInfo->CopyrightPhotographer = estrdup(value_ptr); + ImageInfo->CopyrightEditor = estrndup(value_ptr+length+1, byte_count-length-1); +- spprintf(&ImageInfo->Copyright, 0, ""%s, %s"", value_ptr, value_ptr+length+1); ++ spprintf(&ImageInfo->Copyright, 0, ""%s, %s"", ImageInfo->CopyrightPhotographer, ImageInfo->CopyrightEditor); + /* format = TAG_FMT_UNDEFINED; this musn't be ASCII */ + /* but we are not supposed to change this */ + /* keep in mind that image_info does not store editor value */ +@@ -3134,6 +3134,11 @@ static int exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, + + ImageInfo->sections_found |= FOUND_IFD0; + ++ if ((dir_start + 2) >= (offset_base+IFDlength)) { ++ exif_error_docref(""exif_read_data#error_ifd"" EXIFERR_CC, ImageInfo, E_WARNING, ""Illegal IFD size""); ++ return FALSE; ++ } ++ + NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); + + if ((dir_start+2+NumDirEntries*12) > (offset_base+IFDlength)) { +@@ -3157,6 +3162,10 @@ static int exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, + * Hack to make it process IDF1 I hope + * There are 2 IDFs, the second one holds the keys (0x0201 and 0x0202) to the thumbnail + */ ++ if ((dir_start+2+12*de + 4) >= (offset_base+IFDlength)) { ++ exif_error_docref(""exif_read_data#error_ifd"" EXIFERR_CC, ImageInfo, E_WARNING, ""Illegal IFD size""); ++ return FALSE; ++ } + NextDirOffset = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel); + if (NextDirOffset) { + /* the next line seems false but here IFDlength means length of all IFDs */ +@@ -3206,9 +3215,13 @@ static void exif_process_TIFF_in_JPEG(image_info_type *ImageInfo, char *CharBuf, + } + + /* Check the next two values for correctness. */ ++ if (length < 8) { ++ exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, ""Invalid TIFF start (1)""); ++ return; ++ } + exif_value_2a = php_ifd_get16u(CharBuf+2, ImageInfo->motorola_intel); + offset_of_ifd = php_ifd_get32u(CharBuf+4, ImageInfo->motorola_intel); +- if ( exif_value_2a != 0x2a || offset_of_ifd < 0x08) { ++ if (exif_value_2a != 0x2a || offset_of_ifd < 0x08) { + exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_WARNING, ""Invalid TIFF start (1)""); + return; + }",922,1253,2048 +16905,"ExtensionFunction::ResponseAction TabsQueryFunction::Run() { + std::unique_ptr params( + tabs::Query::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params.get()); + + bool loading_status_set = params->query_info.status != tabs::TAB_STATUS_NONE; + bool loading = params->query_info.status == tabs::TAB_STATUS_LOADING; + + URLPatternSet url_patterns; + if (params->query_info.url.get()) { + std::vector url_pattern_strings; + if (params->query_info.url->as_string) + url_pattern_strings.push_back(*params->query_info.url->as_string); + else if (params->query_info.url->as_strings) + url_pattern_strings.swap(*params->query_info.url->as_strings); + std::string error; + if (!url_patterns.Populate(url_pattern_strings, URLPattern::SCHEME_ALL, + true, &error)) { + return RespondNow(Error(error)); + } + } + + std::string title; + if (params->query_info.title.get()) + title = *params->query_info.title; + + int window_id = extension_misc::kUnknownWindowId; + if (params->query_info.window_id.get()) + window_id = *params->query_info.window_id; + + int index = -1; + if (params->query_info.index.get()) + index = *params->query_info.index; + + std::string window_type; + if (params->query_info.window_type != tabs::WINDOW_TYPE_NONE) + window_type = tabs::ToString(params->query_info.window_type); + + std::unique_ptr result(new base::ListValue()); + Profile* profile = Profile::FromBrowserContext(browser_context()); + Browser* last_active_browser = + chrome::FindAnyBrowser(profile, include_incognito()); + Browser* current_browser = + ChromeExtensionFunctionDetails(this).GetCurrentBrowser(); + for (auto* browser : *BrowserList::GetInstance()) { + if (!profile->IsSameProfile(browser->profile())) + continue; + + if (!browser->window()) + continue; + + if (!include_incognito() && profile != browser->profile()) + continue; + + if (!browser->extension_window_controller()->IsVisibleToTabsAPIForExtension( + extension(), false /*allow_dev_tools_windows*/)) { + continue; + } + + if (window_id >= 0 && window_id != ExtensionTabUtil::GetWindowId(browser)) + continue; + + if (window_id == extension_misc::kCurrentWindowId && + browser != current_browser) { + continue; + } + + if (!MatchesBool(params->query_info.current_window.get(), + browser == current_browser)) { + continue; + } + + if (!MatchesBool(params->query_info.last_focused_window.get(), + browser == last_active_browser)) { + continue; + } + + if (!window_type.empty() && + window_type != + browser->extension_window_controller()->GetWindowTypeText()) { + continue; + } + + TabStripModel* tab_strip = browser->tab_strip_model(); + for (int i = 0; i < tab_strip->count(); ++i) { + WebContents* web_contents = tab_strip->GetWebContentsAt(i); + + if (index > -1 && i != index) + continue; + + if (!web_contents) { + continue; + } + + if (!MatchesBool(params->query_info.highlighted.get(), + tab_strip->IsTabSelected(i))) { + continue; + } + + if (!MatchesBool(params->query_info.active.get(), + i == tab_strip->active_index())) { + continue; + } + + if (!MatchesBool(params->query_info.pinned.get(), + tab_strip->IsTabPinned(i))) { + continue; + } + + if (!MatchesBool(params->query_info.audible.get(), + web_contents->WasRecentlyAudible())) { + continue; + } + + auto* tab_lifecycle_unit_external = + resource_coordinator::TabLifecycleUnitExternal::FromWebContents( + web_contents); + + if (!MatchesBool(params->query_info.discarded.get(), + tab_lifecycle_unit_external->IsDiscarded())) { + continue; + } + + if (!MatchesBool(params->query_info.auto_discardable.get(), + tab_lifecycle_unit_external->IsAutoDiscardable())) { + continue; + } + + if (!MatchesBool(params->query_info.muted.get(), + web_contents->IsAudioMuted())) { + continue; + } + + if (!title.empty() || !url_patterns.is_empty()) { + if (!extension_->permissions_data()->HasAPIPermissionForTab( + ExtensionTabUtil::GetTabId(web_contents), + APIPermission::kTab) && + !extension_->permissions_data()->HasHostPermission( + web_contents->GetURL())) { + continue; + } + + if (!title.empty() && + !base::MatchPattern(web_contents->GetTitle(), + base::UTF8ToUTF16(title))) { + continue; + } + + if (!url_patterns.is_empty() && + !url_patterns.MatchesURL(web_contents->GetURL())) { + continue; + } + } + + if (loading_status_set && loading != web_contents->IsLoading()) + continue; + + result->Append(ExtensionTabUtil::CreateTabObject( + web_contents, ExtensionTabUtil::kScrubTab, extension(), + tab_strip, i) + ->ToValue()); + } + } + + return RespondNow(OneArgument(std::move(result))); +} +",0,"ExtensionFunction::ResponseAction TabsQueryFunction::Run() { + std::unique_ptr params( + tabs::Query::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params.get()); + + bool loading_status_set = params->query_info.status != tabs::TAB_STATUS_NONE; + bool loading = params->query_info.status == tabs::TAB_STATUS_LOADING; + + URLPatternSet url_patterns; + if (params->query_info.url.get()) { + std::vector url_pattern_strings; + if (params->query_info.url->as_string) + url_pattern_strings.push_back(*params->query_info.url->as_string); + else if (params->query_info.url->as_strings) + url_pattern_strings.swap(*params->query_info.url->as_strings); + std::string error; + if (!url_patterns.Populate(url_pattern_strings, URLPattern::SCHEME_ALL, + true, &error)) { + return RespondNow(Error(error)); + } + } + + std::string title; + if (params->query_info.title.get()) + title = *params->query_info.title; + + int window_id = extension_misc::kUnknownWindowId; + if (params->query_info.window_id.get()) + window_id = *params->query_info.window_id; + + int index = -1; + if (params->query_info.index.get()) + index = *params->query_info.index; + + std::string window_type; + if (params->query_info.window_type != tabs::WINDOW_TYPE_NONE) + window_type = tabs::ToString(params->query_info.window_type); + + std::unique_ptr result(new base::ListValue()); + Profile* profile = Profile::FromBrowserContext(browser_context()); + Browser* last_active_browser = + chrome::FindAnyBrowser(profile, include_incognito()); + Browser* current_browser = + ChromeExtensionFunctionDetails(this).GetCurrentBrowser(); + for (auto* browser : *BrowserList::GetInstance()) { + if (!profile->IsSameProfile(browser->profile())) + continue; + + if (!browser->window()) + continue; + + if (!include_incognito() && profile != browser->profile()) + continue; + + if (!browser->extension_window_controller()->IsVisibleToTabsAPIForExtension( + extension(), false /*allow_dev_tools_windows*/)) { + continue; + } + + if (window_id >= 0 && window_id != ExtensionTabUtil::GetWindowId(browser)) + continue; + + if (window_id == extension_misc::kCurrentWindowId && + browser != current_browser) { + continue; + } + + if (!MatchesBool(params->query_info.current_window.get(), + browser == current_browser)) { + continue; + } + + if (!MatchesBool(params->query_info.last_focused_window.get(), + browser == last_active_browser)) { + continue; + } + + if (!window_type.empty() && + window_type != + browser->extension_window_controller()->GetWindowTypeText()) { + continue; + } + + TabStripModel* tab_strip = browser->tab_strip_model(); + for (int i = 0; i < tab_strip->count(); ++i) { + WebContents* web_contents = tab_strip->GetWebContentsAt(i); + + if (index > -1 && i != index) + continue; + + if (!web_contents) { + continue; + } + + if (!MatchesBool(params->query_info.highlighted.get(), + tab_strip->IsTabSelected(i))) { + continue; + } + + if (!MatchesBool(params->query_info.active.get(), + i == tab_strip->active_index())) { + continue; + } + + if (!MatchesBool(params->query_info.pinned.get(), + tab_strip->IsTabPinned(i))) { + continue; + } + + if (!MatchesBool(params->query_info.audible.get(), + web_contents->WasRecentlyAudible())) { + continue; + } + + auto* tab_lifecycle_unit_external = + resource_coordinator::TabLifecycleUnitExternal::FromWebContents( + web_contents); + + if (!MatchesBool(params->query_info.discarded.get(), + tab_lifecycle_unit_external->IsDiscarded())) { + continue; + } + + if (!MatchesBool(params->query_info.auto_discardable.get(), + tab_lifecycle_unit_external->IsAutoDiscardable())) { + continue; + } + + if (!MatchesBool(params->query_info.muted.get(), + web_contents->IsAudioMuted())) { + continue; + } + + if (!title.empty() || !url_patterns.is_empty()) { + if (!extension_->permissions_data()->HasAPIPermissionForTab( + ExtensionTabUtil::GetTabId(web_contents), + APIPermission::kTab) && + !extension_->permissions_data()->HasHostPermission( + web_contents->GetURL())) { + continue; + } + + if (!title.empty() && + !base::MatchPattern(web_contents->GetTitle(), + base::UTF8ToUTF16(title))) { + continue; + } + + if (!url_patterns.is_empty() && + !url_patterns.MatchesURL(web_contents->GetURL())) { + continue; + } + } + + if (loading_status_set && loading != web_contents->IsLoading()) + continue; + + result->Append(ExtensionTabUtil::CreateTabObject( + web_contents, ExtensionTabUtil::kScrubTab, extension(), + tab_strip, i) + ->ToValue()); + } + } + + return RespondNow(OneArgument(std::move(result))); +} +","@@ -1739,6 +1739,7 @@ WebContents* TabsCaptureVisibleTabFunction::GetWebContentsForID( + } + + if (!extension()->permissions_data()->CanCaptureVisiblePage( ++ contents->GetLastCommittedURL(), extension(), + SessionTabHelper::IdForTab(contents).id(), error)) { + return nullptr; + } +@@ -1762,9 +1763,8 @@ ExtensionFunction::ResponseAction TabsCaptureVisibleTabFunction::Run() { + + std::string error; + WebContents* contents = GetWebContentsForID(context_id, &error); +- // TODO(wjmaclean): If |error| was populated, shouldn't we send error +- // response? Currently doing that will fail +- // ExtensionApiCaptureTest.CaptureNullWindow test. ++ if (!contents) ++ return RespondNow(Error(error)); + + const CaptureResult capture_result = CaptureAsync( + contents, image_details.get(),",1143,1474,2048 +18248,"int build_ntlmssp_auth_blob(unsigned char **pbuffer, + u16 *buflen, + struct cifs_ses *ses, + const struct nls_table *nls_cp) +{ + int rc; + AUTHENTICATE_MESSAGE *sec_blob; + __u32 flags; + unsigned char *tmp; + + rc = setup_ntlmv2_rsp(ses, nls_cp); + if (rc) { + cifs_dbg(VFS, ""Error %d during NTLMSSP authentication\n"", rc); + *buflen = 0; + goto setup_ntlmv2_ret; + } + *pbuffer = kmalloc(size_of_ntlmssp_blob(ses), GFP_KERNEL); + sec_blob = (AUTHENTICATE_MESSAGE *)*pbuffer; + + memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8); + sec_blob->MessageType = NtLmAuthenticate; + + flags = NTLMSSP_NEGOTIATE_56 | + NTLMSSP_REQUEST_TARGET | NTLMSSP_NEGOTIATE_TARGET_INFO | + NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE | + NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC; + if (ses->server->sign) { + flags |= NTLMSSP_NEGOTIATE_SIGN; + if (!ses->server->session_estab || + ses->ntlmssp->sesskey_per_smbsess) + flags |= NTLMSSP_NEGOTIATE_KEY_XCH; + } + + tmp = *pbuffer + sizeof(AUTHENTICATE_MESSAGE); + sec_blob->NegotiateFlags = cpu_to_le32(flags); + + sec_blob->LmChallengeResponse.BufferOffset = + cpu_to_le32(sizeof(AUTHENTICATE_MESSAGE)); + sec_blob->LmChallengeResponse.Length = 0; + sec_blob->LmChallengeResponse.MaximumLength = 0; + + sec_blob->NtChallengeResponse.BufferOffset = + cpu_to_le32(tmp - *pbuffer); + if (ses->user_name != NULL) { + memcpy(tmp, ses->auth_key.response + CIFS_SESS_KEY_SIZE, + ses->auth_key.len - CIFS_SESS_KEY_SIZE); + tmp += ses->auth_key.len - CIFS_SESS_KEY_SIZE; + + sec_blob->NtChallengeResponse.Length = + cpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE); + sec_blob->NtChallengeResponse.MaximumLength = + cpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE); + } else { + /* + * don't send an NT Response for anonymous access + */ + sec_blob->NtChallengeResponse.Length = 0; + sec_blob->NtChallengeResponse.MaximumLength = 0; + } + + if (ses->domainName == NULL) { + sec_blob->DomainName.BufferOffset = cpu_to_le32(tmp - *pbuffer); + sec_blob->DomainName.Length = 0; + sec_blob->DomainName.MaximumLength = 0; + tmp += 2; + } else { + int len; + len = cifs_strtoUTF16((__le16 *)tmp, ses->domainName, + CIFS_MAX_DOMAINNAME_LEN, nls_cp); + len *= 2; /* unicode is 2 bytes each */ + sec_blob->DomainName.BufferOffset = cpu_to_le32(tmp - *pbuffer); + sec_blob->DomainName.Length = cpu_to_le16(len); + sec_blob->DomainName.MaximumLength = cpu_to_le16(len); + tmp += len; + } + + if (ses->user_name == NULL) { + sec_blob->UserName.BufferOffset = cpu_to_le32(tmp - *pbuffer); + sec_blob->UserName.Length = 0; + sec_blob->UserName.MaximumLength = 0; + tmp += 2; + } else { + int len; + len = cifs_strtoUTF16((__le16 *)tmp, ses->user_name, + CIFS_MAX_USERNAME_LEN, nls_cp); + len *= 2; /* unicode is 2 bytes each */ + sec_blob->UserName.BufferOffset = cpu_to_le32(tmp - *pbuffer); + sec_blob->UserName.Length = cpu_to_le16(len); + sec_blob->UserName.MaximumLength = cpu_to_le16(len); + tmp += len; + } + + sec_blob->WorkstationName.BufferOffset = cpu_to_le32(tmp - *pbuffer); + sec_blob->WorkstationName.Length = 0; + sec_blob->WorkstationName.MaximumLength = 0; + tmp += 2; + + if (((ses->ntlmssp->server_flags & NTLMSSP_NEGOTIATE_KEY_XCH) || + (ses->ntlmssp->server_flags & NTLMSSP_NEGOTIATE_EXTENDED_SEC)) + && !calc_seckey(ses)) { + memcpy(tmp, ses->ntlmssp->ciphertext, CIFS_CPHTXT_SIZE); + sec_blob->SessionKey.BufferOffset = cpu_to_le32(tmp - *pbuffer); + sec_blob->SessionKey.Length = cpu_to_le16(CIFS_CPHTXT_SIZE); + sec_blob->SessionKey.MaximumLength = + cpu_to_le16(CIFS_CPHTXT_SIZE); + tmp += CIFS_CPHTXT_SIZE; + } else { + sec_blob->SessionKey.BufferOffset = cpu_to_le32(tmp - *pbuffer); + sec_blob->SessionKey.Length = 0; + sec_blob->SessionKey.MaximumLength = 0; + } + + *buflen = tmp - *pbuffer; +setup_ntlmv2_ret: + return rc; +} +",1,"int build_ntlmssp_auth_blob(unsigned char **pbuffer, + u16 *buflen, + struct cifs_ses *ses, + const struct nls_table *nls_cp) +{ + int rc; + AUTHENTICATE_MESSAGE *sec_blob; + __u32 flags; + unsigned char *tmp; + + rc = setup_ntlmv2_rsp(ses, nls_cp); + if (rc) { + cifs_dbg(VFS, ""Error %d during NTLMSSP authentication\n"", rc); + *buflen = 0; + goto setup_ntlmv2_ret; + } + *pbuffer = kmalloc(size_of_ntlmssp_blob(ses), GFP_KERNEL); + sec_blob = (AUTHENTICATE_MESSAGE *)*pbuffer; + + memcpy(sec_blob->Signature, NTLMSSP_SIGNATURE, 8); + sec_blob->MessageType = NtLmAuthenticate; + + flags = NTLMSSP_NEGOTIATE_56 | + NTLMSSP_REQUEST_TARGET | NTLMSSP_NEGOTIATE_TARGET_INFO | + NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE | + NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC | + NTLMSSP_NEGOTIATE_SEAL; + if (ses->server->sign) + flags |= NTLMSSP_NEGOTIATE_SIGN; + if (!ses->server->session_estab || ses->ntlmssp->sesskey_per_smbsess) + flags |= NTLMSSP_NEGOTIATE_KEY_XCH; + + tmp = *pbuffer + sizeof(AUTHENTICATE_MESSAGE); + sec_blob->NegotiateFlags = cpu_to_le32(flags); + + sec_blob->LmChallengeResponse.BufferOffset = + cpu_to_le32(sizeof(AUTHENTICATE_MESSAGE)); + sec_blob->LmChallengeResponse.Length = 0; + sec_blob->LmChallengeResponse.MaximumLength = 0; + + sec_blob->NtChallengeResponse.BufferOffset = + cpu_to_le32(tmp - *pbuffer); + if (ses->user_name != NULL) { + memcpy(tmp, ses->auth_key.response + CIFS_SESS_KEY_SIZE, + ses->auth_key.len - CIFS_SESS_KEY_SIZE); + tmp += ses->auth_key.len - CIFS_SESS_KEY_SIZE; + + sec_blob->NtChallengeResponse.Length = + cpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE); + sec_blob->NtChallengeResponse.MaximumLength = + cpu_to_le16(ses->auth_key.len - CIFS_SESS_KEY_SIZE); + } else { + /* + * don't send an NT Response for anonymous access + */ + sec_blob->NtChallengeResponse.Length = 0; + sec_blob->NtChallengeResponse.MaximumLength = 0; + } + + if (ses->domainName == NULL) { + sec_blob->DomainName.BufferOffset = cpu_to_le32(tmp - *pbuffer); + sec_blob->DomainName.Length = 0; + sec_blob->DomainName.MaximumLength = 0; + tmp += 2; + } else { + int len; + len = cifs_strtoUTF16((__le16 *)tmp, ses->domainName, + CIFS_MAX_DOMAINNAME_LEN, nls_cp); + len *= 2; /* unicode is 2 bytes each */ + sec_blob->DomainName.BufferOffset = cpu_to_le32(tmp - *pbuffer); + sec_blob->DomainName.Length = cpu_to_le16(len); + sec_blob->DomainName.MaximumLength = cpu_to_le16(len); + tmp += len; + } + + if (ses->user_name == NULL) { + sec_blob->UserName.BufferOffset = cpu_to_le32(tmp - *pbuffer); + sec_blob->UserName.Length = 0; + sec_blob->UserName.MaximumLength = 0; + tmp += 2; + } else { + int len; + len = cifs_strtoUTF16((__le16 *)tmp, ses->user_name, + CIFS_MAX_USERNAME_LEN, nls_cp); + len *= 2; /* unicode is 2 bytes each */ + sec_blob->UserName.BufferOffset = cpu_to_le32(tmp - *pbuffer); + sec_blob->UserName.Length = cpu_to_le16(len); + sec_blob->UserName.MaximumLength = cpu_to_le16(len); + tmp += len; + } + + sec_blob->WorkstationName.BufferOffset = cpu_to_le32(tmp - *pbuffer); + sec_blob->WorkstationName.Length = 0; + sec_blob->WorkstationName.MaximumLength = 0; + tmp += 2; + + if (((ses->ntlmssp->server_flags & NTLMSSP_NEGOTIATE_KEY_XCH) || + (ses->ntlmssp->server_flags & NTLMSSP_NEGOTIATE_EXTENDED_SEC)) + && !calc_seckey(ses)) { + memcpy(tmp, ses->ntlmssp->ciphertext, CIFS_CPHTXT_SIZE); + sec_blob->SessionKey.BufferOffset = cpu_to_le32(tmp - *pbuffer); + sec_blob->SessionKey.Length = cpu_to_le16(CIFS_CPHTXT_SIZE); + sec_blob->SessionKey.MaximumLength = + cpu_to_le16(CIFS_CPHTXT_SIZE); + tmp += CIFS_CPHTXT_SIZE; + } else { + sec_blob->SessionKey.BufferOffset = cpu_to_le32(tmp - *pbuffer); + sec_blob->SessionKey.Length = 0; + sec_blob->SessionKey.MaximumLength = 0; + } + + *buflen = tmp - *pbuffer; +setup_ntlmv2_ret: + return rc; +} +","@@ -344,13 +344,12 @@ void build_ntlmssp_negotiate_blob(unsigned char *pbuffer, + /* BB is NTLMV2 session security format easier to use here? */ + flags = NTLMSSP_NEGOTIATE_56 | NTLMSSP_REQUEST_TARGET | + NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE | +- NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC; +- if (ses->server->sign) { ++ NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC | ++ NTLMSSP_NEGOTIATE_SEAL; ++ if (ses->server->sign) + flags |= NTLMSSP_NEGOTIATE_SIGN; +- if (!ses->server->session_estab || +- ses->ntlmssp->sesskey_per_smbsess) +- flags |= NTLMSSP_NEGOTIATE_KEY_XCH; +- } ++ if (!ses->server->session_estab || ses->ntlmssp->sesskey_per_smbsess) ++ flags |= NTLMSSP_NEGOTIATE_KEY_XCH; + + sec_blob->NegotiateFlags = cpu_to_le32(flags); + +@@ -407,13 +406,12 @@ int build_ntlmssp_auth_blob(unsigned char **pbuffer, + flags = NTLMSSP_NEGOTIATE_56 | + NTLMSSP_REQUEST_TARGET | NTLMSSP_NEGOTIATE_TARGET_INFO | + NTLMSSP_NEGOTIATE_128 | NTLMSSP_NEGOTIATE_UNICODE | +- NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC; +- if (ses->server->sign) { ++ NTLMSSP_NEGOTIATE_NTLM | NTLMSSP_NEGOTIATE_EXTENDED_SEC | ++ NTLMSSP_NEGOTIATE_SEAL; ++ if (ses->server->sign) + flags |= NTLMSSP_NEGOTIATE_SIGN; +- if (!ses->server->session_estab || +- ses->ntlmssp->sesskey_per_smbsess) +- flags |= NTLMSSP_NEGOTIATE_KEY_XCH; +- } ++ if (!ses->server->session_estab || ses->ntlmssp->sesskey_per_smbsess) ++ flags |= NTLMSSP_NEGOTIATE_KEY_XCH; + + tmp = *pbuffer + sizeof(AUTHENTICATE_MESSAGE); + sec_blob->NegotiateFlags = cpu_to_le32(flags);",1245,1576,2048 +11089,"void WebPagePrivate::zoomBlock() +{ + if (!m_mainFrame) + return; + + IntPoint anchor(roundUntransformedPoint(m_finalBlockPoint)); + bool willUseTextReflow = false; + +#if ENABLE(VIEWPORT_REFLOW) + willUseTextReflow = m_webPage->settings()->textReflowMode() != WebSettings::TextReflowDisabled; + toggleTextReflowIfEnabledForBlockZoomOnly(m_shouldReflowBlock); + setNeedsLayout(); +#endif + + TransformationMatrix zoom; + zoom.scale(m_blockZoomFinalScale); + *m_transformationMatrix = zoom; + m_backingStore->d->suspendBackingStoreUpdates(); + m_backingStore->d->suspendScreenUpdates(); + updateViewportSize(); + + FrameView* mainFrameView = m_mainFrame->view(); + bool constrainsScrollingToContentEdge = true; + if (mainFrameView) { + constrainsScrollingToContentEdge = mainFrameView->constrainsScrollingToContentEdge(); + mainFrameView->setConstrainsScrollingToContentEdge(m_shouldConstrainScrollingToContentEdge); + } + +#if ENABLE(VIEWPORT_REFLOW) + requestLayoutIfNeeded(); + if (willUseTextReflow && m_shouldReflowBlock) { + IntRect reflowedRect = rectForNode(m_currentBlockZoomAdjustedNode.get()); + reflowedRect = adjustRectOffsetForFrameOffset(reflowedRect, m_currentBlockZoomAdjustedNode.get()); + reflowedRect.move(roundTransformedPoint(m_finalBlockPointReflowOffset).x(), roundTransformedPoint(m_finalBlockPointReflowOffset).y()); + RenderObject* renderer = m_currentBlockZoomAdjustedNode->renderer(); + IntPoint topLeftPoint(reflowedRect.location()); + if (renderer && renderer->isText()) { + ETextAlign textAlign = renderer->style()->textAlign(); + IntPoint textAnchor; + switch (textAlign) { + case CENTER: + case WEBKIT_CENTER: + textAnchor = IntPoint(reflowedRect.x() + (reflowedRect.width() - actualVisibleSize().width()) / 2, topLeftPoint.y()); + break; + case LEFT: + case WEBKIT_LEFT: + textAnchor = topLeftPoint; + break; + case RIGHT: + case WEBKIT_RIGHT: + textAnchor = IntPoint(reflowedRect.x() + reflowedRect.width() - actualVisibleSize().width(), topLeftPoint.y()); + break; + case TAAUTO: + case JUSTIFY: + default: + if (renderer->style()->isLeftToRightDirection()) + textAnchor = topLeftPoint; + else + textAnchor = IntPoint(reflowedRect.x() + reflowedRect.width() - actualVisibleSize().width(), topLeftPoint.y()); + break; + } + setScrollPosition(textAnchor); + } else { + renderer->style()->isLeftToRightDirection() + ? setScrollPosition(topLeftPoint) + : setScrollPosition(IntPoint(reflowedRect.x() + reflowedRect.width() - actualVisibleSize().width(), topLeftPoint.y())); + } + } else if (willUseTextReflow) { + IntRect finalRect = rectForNode(m_currentBlockZoomAdjustedNode.get()); + finalRect = adjustRectOffsetForFrameOffset(finalRect, m_currentBlockZoomAdjustedNode.get()); + setScrollPosition(IntPoint(0, finalRect.y() + m_finalBlockPointReflowOffset.y())); + resetBlockZoom(); + } +#endif + if (!willUseTextReflow) { + setScrollPosition(anchor); + if (!m_shouldReflowBlock) + resetBlockZoom(); + } + + notifyTransformChanged(); + m_client->scaleChanged(); + + if (mainFrameView) + mainFrameView->setConstrainsScrollingToContentEdge(constrainsScrollingToContentEdge); + + m_backingStore->d->resumeBackingStoreUpdates(); + m_backingStore->d->resumeScreenUpdates(BackingStore::RenderAndBlit); +} +",0,"void WebPagePrivate::zoomBlock() +{ + if (!m_mainFrame) + return; + + IntPoint anchor(roundUntransformedPoint(m_finalBlockPoint)); + bool willUseTextReflow = false; + +#if ENABLE(VIEWPORT_REFLOW) + willUseTextReflow = m_webPage->settings()->textReflowMode() != WebSettings::TextReflowDisabled; + toggleTextReflowIfEnabledForBlockZoomOnly(m_shouldReflowBlock); + setNeedsLayout(); +#endif + + TransformationMatrix zoom; + zoom.scale(m_blockZoomFinalScale); + *m_transformationMatrix = zoom; + m_backingStore->d->suspendBackingStoreUpdates(); + m_backingStore->d->suspendScreenUpdates(); + updateViewportSize(); + + FrameView* mainFrameView = m_mainFrame->view(); + bool constrainsScrollingToContentEdge = true; + if (mainFrameView) { + constrainsScrollingToContentEdge = mainFrameView->constrainsScrollingToContentEdge(); + mainFrameView->setConstrainsScrollingToContentEdge(m_shouldConstrainScrollingToContentEdge); + } + +#if ENABLE(VIEWPORT_REFLOW) + requestLayoutIfNeeded(); + if (willUseTextReflow && m_shouldReflowBlock) { + IntRect reflowedRect = rectForNode(m_currentBlockZoomAdjustedNode.get()); + reflowedRect = adjustRectOffsetForFrameOffset(reflowedRect, m_currentBlockZoomAdjustedNode.get()); + reflowedRect.move(roundTransformedPoint(m_finalBlockPointReflowOffset).x(), roundTransformedPoint(m_finalBlockPointReflowOffset).y()); + RenderObject* renderer = m_currentBlockZoomAdjustedNode->renderer(); + IntPoint topLeftPoint(reflowedRect.location()); + if (renderer && renderer->isText()) { + ETextAlign textAlign = renderer->style()->textAlign(); + IntPoint textAnchor; + switch (textAlign) { + case CENTER: + case WEBKIT_CENTER: + textAnchor = IntPoint(reflowedRect.x() + (reflowedRect.width() - actualVisibleSize().width()) / 2, topLeftPoint.y()); + break; + case LEFT: + case WEBKIT_LEFT: + textAnchor = topLeftPoint; + break; + case RIGHT: + case WEBKIT_RIGHT: + textAnchor = IntPoint(reflowedRect.x() + reflowedRect.width() - actualVisibleSize().width(), topLeftPoint.y()); + break; + case TAAUTO: + case JUSTIFY: + default: + if (renderer->style()->isLeftToRightDirection()) + textAnchor = topLeftPoint; + else + textAnchor = IntPoint(reflowedRect.x() + reflowedRect.width() - actualVisibleSize().width(), topLeftPoint.y()); + break; + } + setScrollPosition(textAnchor); + } else { + renderer->style()->isLeftToRightDirection() + ? setScrollPosition(topLeftPoint) + : setScrollPosition(IntPoint(reflowedRect.x() + reflowedRect.width() - actualVisibleSize().width(), topLeftPoint.y())); + } + } else if (willUseTextReflow) { + IntRect finalRect = rectForNode(m_currentBlockZoomAdjustedNode.get()); + finalRect = adjustRectOffsetForFrameOffset(finalRect, m_currentBlockZoomAdjustedNode.get()); + setScrollPosition(IntPoint(0, finalRect.y() + m_finalBlockPointReflowOffset.y())); + resetBlockZoom(); + } +#endif + if (!willUseTextReflow) { + setScrollPosition(anchor); + if (!m_shouldReflowBlock) + resetBlockZoom(); + } + + notifyTransformChanged(); + m_client->scaleChanged(); + + if (mainFrameView) + mainFrameView->setConstrainsScrollingToContentEdge(constrainsScrollingToContentEdge); + + m_backingStore->d->resumeBackingStoreUpdates(); + m_backingStore->d->resumeScreenUpdates(BackingStore::RenderAndBlit); +} +","@@ -4058,11 +4058,6 @@ bool WebPage::touchEvent(const Platform::TouchEvent& event) + return d->dispatchTouchEventToFullScreenPlugin(pluginView, event); + + Platform::TouchEvent tEvent = event; +- for (unsigned i = 0; i < event.m_points.size(); i++) { +- tEvent.m_points[i].m_pos = d->mapFromTransformed(tEvent.m_points[i].m_pos); +- tEvent.m_points[i].m_screenPos = tEvent.m_points[i].m_screenPos; +- } +- + if (event.isSingleTap()) + d->m_pluginMayOpenNewTab = true; + else if (tEvent.m_type == Platform::TouchEvent::TouchStart || tEvent.m_type == Platform::TouchEvent::TouchCancel) +@@ -4132,10 +4127,7 @@ void WebPage::touchPointAsMouseEvent(const Platform::TouchPoint& point, unsigned + + d->m_lastUserEventTimestamp = currentTime(); + +- Platform::TouchPoint tPoint = point; +- tPoint.m_pos = d->mapFromTransformed(tPoint.m_pos); +- +- d->m_touchEventHandler->handleTouchPoint(tPoint, modifiers); ++ d->m_touchEventHandler->handleTouchPoint(point, modifiers); + } + + void WebPage::playSoundIfAnchorIsTarget() const +@@ -4165,13 +4157,13 @@ bool WebPagePrivate::dispatchTouchEventToFullScreenPlugin(PluginView* plugin, co + if (npTouchEvent.size) { + npTouchEvent.points = new NPTouchPoint[npTouchEvent.size]; + for (int i = 0; i < npTouchEvent.size; i++) { +- npTouchEvent.points[i].touchId = event.m_points[i].m_id; +- npTouchEvent.points[i].clientX = event.m_points[i].m_screenPos.x(); +- npTouchEvent.points[i].clientY = event.m_points[i].m_screenPos.y(); +- npTouchEvent.points[i].screenX = event.m_points[i].m_screenPos.x(); +- npTouchEvent.points[i].screenY = event.m_points[i].m_screenPos.y(); +- npTouchEvent.points[i].pageX = event.m_points[i].m_pos.x(); +- npTouchEvent.points[i].pageY = event.m_points[i].m_pos.y(); ++ npTouchEvent.points[i].touchId = event.m_points[i].id(); ++ npTouchEvent.points[i].clientX = event.m_points[i].screenPosition().x(); ++ npTouchEvent.points[i].clientY = event.m_points[i].screenPosition().y(); ++ npTouchEvent.points[i].screenX = event.m_points[i].screenPosition().x(); ++ npTouchEvent.points[i].screenY = event.m_points[i].screenPosition().y(); ++ npTouchEvent.points[i].pageX = event.m_points[i].pixelViewportPosition().x(); ++ npTouchEvent.points[i].pageY = event.m_points[i].pixelViewportPosition().y(); + } + } + +@@ -4193,7 +4185,7 @@ bool WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin(PluginView + NPEvent npEvent; + NPMouseEvent mouse; + +- switch (point.m_state) { ++ switch (point.state()) { + case Platform::TouchPoint::TouchPressed: + mouse.type = MOUSE_BUTTON_DOWN; + break; +@@ -4207,8 +4199,8 @@ bool WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin(PluginView + return true; + } + +- mouse.x = point.m_screenPos.x(); +- mouse.y = point.m_screenPos.y(); ++ mouse.x = point.screenPosition().x(); ++ mouse.y = point.screenPosition().y(); + mouse.button = mouse.type != MOUSE_BUTTON_UP; + mouse.flags = 0; + npEvent.type = NP_MouseEvent;",843,1174,2048 +11681,"png_read_filter_row(png_structp png_ptr, png_row_infop row_info, png_bytep row, + png_bytep prev_row, int filter) +{ + png_debug(1, ""in png_read_filter_row""); + png_debug2(2, ""row = %lu, filter = %d"", png_ptr->row_number, filter); + switch (filter) + { + case PNG_FILTER_VALUE_NONE: + break; + case PNG_FILTER_VALUE_SUB: + { + png_uint_32 i; + png_uint_32 istop = row_info->rowbytes; + png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3; + png_bytep rp = row + bpp; + png_bytep lp = row; + + for (i = bpp; i < istop; i++) + { + *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff); + rp++; + } + break; + } + case PNG_FILTER_VALUE_UP: + { + png_uint_32 i; + png_uint_32 istop = row_info->rowbytes; + png_bytep rp = row; + png_bytep pp = prev_row; + + for (i = 0; i < istop; i++) + { + *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff); + rp++; + } + break; + } + case PNG_FILTER_VALUE_AVG: + { + png_uint_32 i; + png_bytep rp = row; + png_bytep pp = prev_row; + png_bytep lp = row; + png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3; + png_uint_32 istop = row_info->rowbytes - bpp; + + for (i = 0; i < bpp; i++) + { + *rp = (png_byte)(((int)(*rp) + + ((int)(*pp++) / 2 )) & 0xff); + rp++; + } + + for (i = 0; i < istop; i++) + { + *rp = (png_byte)(((int)(*rp) + + (int)(*pp++ + *lp++) / 2 ) & 0xff); + rp++; + } + break; + } + case PNG_FILTER_VALUE_PAETH: + { + png_uint_32 i; + png_bytep rp = row; + png_bytep pp = prev_row; + png_bytep lp = row; + png_bytep cp = prev_row; + png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3; + png_uint_32 istop=row_info->rowbytes - bpp; + + for (i = 0; i < bpp; i++) + { + *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff); + rp++; + } + + for (i = 0; i < istop; i++) /* Use leftover rp,pp */ + { + int a, b, c, pa, pb, pc, p; + + a = *lp++; + b = *pp++; + c = *cp++; + + p = b - c; + pc = a - c; + +#ifdef PNG_USE_ABS + pa = abs(p); + pb = abs(pc); + pc = abs(p + pc); +#else + pa = p < 0 ? -p : p; + pb = pc < 0 ? -pc : pc; + pc = (p + pc) < 0 ? -(p + pc) : p + pc; +#endif + + /* + if (pa <= pb && pa <= pc) + p = a; + else if (pb <= pc) + p = b; + else + p = c; + */ + + p = (pa <= pb && pa <= pc) ? a : (pb <= pc) ? b : c; + + *rp = (png_byte)(((int)(*rp) + p) & 0xff); + rp++; + } + break; + } + default: + png_warning(png_ptr, ""Ignoring bad adaptive filter type""); + *row = 0; + break; + } +} +",0,"png_read_filter_row(png_structp png_ptr, png_row_infop row_info, png_bytep row, + png_bytep prev_row, int filter) +{ + png_debug(1, ""in png_read_filter_row""); + png_debug2(2, ""row = %lu, filter = %d"", png_ptr->row_number, filter); + switch (filter) + { + case PNG_FILTER_VALUE_NONE: + break; + case PNG_FILTER_VALUE_SUB: + { + png_uint_32 i; + png_uint_32 istop = row_info->rowbytes; + png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3; + png_bytep rp = row + bpp; + png_bytep lp = row; + + for (i = bpp; i < istop; i++) + { + *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff); + rp++; + } + break; + } + case PNG_FILTER_VALUE_UP: + { + png_uint_32 i; + png_uint_32 istop = row_info->rowbytes; + png_bytep rp = row; + png_bytep pp = prev_row; + + for (i = 0; i < istop; i++) + { + *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff); + rp++; + } + break; + } + case PNG_FILTER_VALUE_AVG: + { + png_uint_32 i; + png_bytep rp = row; + png_bytep pp = prev_row; + png_bytep lp = row; + png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3; + png_uint_32 istop = row_info->rowbytes - bpp; + + for (i = 0; i < bpp; i++) + { + *rp = (png_byte)(((int)(*rp) + + ((int)(*pp++) / 2 )) & 0xff); + rp++; + } + + for (i = 0; i < istop; i++) + { + *rp = (png_byte)(((int)(*rp) + + (int)(*pp++ + *lp++) / 2 ) & 0xff); + rp++; + } + break; + } + case PNG_FILTER_VALUE_PAETH: + { + png_uint_32 i; + png_bytep rp = row; + png_bytep pp = prev_row; + png_bytep lp = row; + png_bytep cp = prev_row; + png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3; + png_uint_32 istop=row_info->rowbytes - bpp; + + for (i = 0; i < bpp; i++) + { + *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff); + rp++; + } + + for (i = 0; i < istop; i++) /* Use leftover rp,pp */ + { + int a, b, c, pa, pb, pc, p; + + a = *lp++; + b = *pp++; + c = *cp++; + + p = b - c; + pc = a - c; + +#ifdef PNG_USE_ABS + pa = abs(p); + pb = abs(pc); + pc = abs(p + pc); +#else + pa = p < 0 ? -p : p; + pb = pc < 0 ? -pc : pc; + pc = (p + pc) < 0 ? -(p + pc) : p + pc; +#endif + + /* + if (pa <= pb && pa <= pc) + p = a; + else if (pb <= pc) + p = b; + else + p = c; + */ + + p = (pa <= pb && pa <= pc) ? a : (pb <= pc) ? b : c; + + *rp = (png_byte)(((int)(*rp) + p) & 0xff); + rp++; + } + break; + } + default: + png_warning(png_ptr, ""Ignoring bad adaptive filter type""); + *row = 0; + break; + } +} +","@@ -247,8 +247,8 @@ png_inflate(png_structp png_ptr, const png_byte *data, png_size_t size, + { + if (output != 0 && output_size > count) + { +- int copy = output_size - count; +- if (avail < copy) copy = avail; ++ png_size_t copy = output_size - count; ++ if ((png_size_t) avail < copy) copy = (png_size_t) avail; + png_memcpy(output + count, png_ptr->zbuf, copy); + } + count += avail;",912,1243,2048 +17999,"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; + + /* Opening a Tx-ring is NOT supported in TPACKET_V3 */ + if (!closing && tx_ring && (po->tp_version > TPACKET_V2)) { + net_warn_ratelimited(""Tx-ring is not supported.\n""); + goto out; + } + + 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 && + (int)(req->tp_block_size - + BLK_PLUS_PRIV(req_u->req3.tp_sizeof_priv)) <= 0) + 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((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: + /* Transmit path is not supported. We checked + * it above but just being paranoid + */ + if (!tx_ring) + init_prb_bdqc(po, rb, pg_vec, req_u); + break; + default: + break; + } + } + /* Done */ + else { + err = -EINVAL; + if (unlikely(req->tp_frame_nr)) + goto out; + } + + lock_sock(sk); + + /* 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 (closing && (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); + } + release_sock(sk); + + if (pg_vec) + free_pg_vec(pg_vec, order, req->tp_block_nr); + out: + return err; + } +",1,"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); + /* Opening a Tx-ring is NOT supported in TPACKET_V3 */ + if (!closing && tx_ring && (po->tp_version > TPACKET_V2)) { + net_warn_ratelimited(""Tx-ring is not supported.\n""); + goto out; + } + + 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 && + (int)(req->tp_block_size - + BLK_PLUS_PRIV(req_u->req3.tp_sizeof_priv)) <= 0) + 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((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: + /* Transmit path is not supported. We checked + * it above but just being paranoid + */ + if (!tx_ring) + init_prb_bdqc(po, rb, pg_vec, req_u); + 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 (closing && (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; + } +","@@ -3648,19 +3648,25 @@ packet_setsockopt(struct socket *sock, int level, int optname, char __user *optv + + 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; + switch (val) { + case TPACKET_V1: + case TPACKET_V2: + case TPACKET_V3: +- po->tp_version = val; +- return 0; ++ 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: + { +@@ -4164,6 +4170,7 @@ static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u, + /* Added to avoid minimal code churn */ + struct tpacket_req *req = &req_u->req; + ++ lock_sock(sk); + /* Opening a Tx-ring is NOT supported in TPACKET_V3 */ + if (!closing && tx_ring && (po->tp_version > TPACKET_V2)) { + net_warn_ratelimited(""Tx-ring is not supported.\n""); +@@ -4245,7 +4252,6 @@ static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u, + goto out; + } + +- lock_sock(sk); + + /* Detach socket from network */ + spin_lock(&po->bind_lock); +@@ -4294,11 +4300,11 @@ static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u, + if (!tx_ring) + prb_shutdown_retire_blk_timer(po, rb_queue); + } +- release_sock(sk); + + if (pg_vec) + free_pg_vec(pg_vec, order, req->tp_block_nr); + out: ++ release_sock(sk); + return err; + } + ",1156,1487,2048 +18786,"FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj, unsigned length) +{ + FLAC__uint32 i; + + FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)); + + /* read vendor string */ + if (length >= 8) { + length -= 8; /* vendor string length + num comments entries alone take 8 bytes */ + FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32); + if (!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length)) + return false; /* read_callback_ sets the state for us */ + if (obj->vendor_string.length > 0) { + if (length < obj->vendor_string.length) { + obj->vendor_string.length = 0; + obj->vendor_string.entry = 0; + goto skip; + } + else + length -= obj->vendor_string.length; + if (0 == (obj->vendor_string.entry = safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + return false; + } + if (!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length)) + return false; /* read_callback_ sets the state for us */ + obj->vendor_string.entry[obj->vendor_string.length] = '\0'; + } + else + obj->vendor_string.entry = 0; + + /* read num comments */ + FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32); + if (!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments)) + return false; /* read_callback_ sets the state for us */ + + /* read comments */ + if (obj->num_comments > 100000) { + /* Possibly malicious file. */ + obj->num_comments = 0; + return false; + } + + if (obj->num_comments > 0) { + if (0 == (obj->comments = safe_malloc_mul_2op_p(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + return false; + } + for (i = 0; i < obj->num_comments; i++) { + /* Initialize here just to make sure. */ + obj->comments[i].length = 0; + obj->comments[i].entry = 0; + + FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32); + if (length < 4) { + obj->num_comments = i; + goto skip; + } + else + length -= 4; + if (!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length)) + return false; /* read_callback_ sets the state for us */ + if (obj->comments[i].length > 0) { + if (length < obj->comments[i].length) { + obj->num_comments = i; + goto skip; + } + else + length -= obj->comments[i].length; + if (0 == (obj->comments[i].entry = safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + return false; + } + memset (obj->comments[i].entry, 0, obj->comments[i].length) ; + if (!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length)) { + obj->num_comments = i; + goto skip; + } + obj->comments[i].entry[obj->comments[i].length] = '\0'; + } + else + obj->comments[i].entry = 0; + } + } + else + obj->comments = 0; + } + + skip: + if (length > 0) { + /* This will only happen on files with invalid data in comments */ + if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length)) + return false; /* read_callback_ sets the state for us */ + } + + return true; +} +",1,"FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj, unsigned length) +{ + FLAC__uint32 i; + + FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)); + + /* read vendor string */ + if (length >= 8) { + length -= 8; /* vendor string length + num comments entries alone take 8 bytes */ + FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32); + if (!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length)) + return false; /* read_callback_ sets the state for us */ + if (obj->vendor_string.length > 0) { + if (length < obj->vendor_string.length) { + obj->vendor_string.length = 0; + obj->vendor_string.entry = 0; + goto skip; + } + else + length -= obj->vendor_string.length; + if (0 == (obj->vendor_string.entry = safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + return false; + } + if (!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length)) + return false; /* read_callback_ sets the state for us */ + obj->vendor_string.entry[obj->vendor_string.length] = '\0'; + } + else + obj->vendor_string.entry = 0; + + /* read num comments */ + FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32); + if (!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments)) + return false; /* read_callback_ sets the state for us */ + + /* read comments */ + if (obj->num_comments > 100000) { + /* Possibly malicious file. */ + obj->num_comments = 0; + return false; + } + + if (obj->num_comments > 0) { + if (0 == (obj->comments = safe_malloc_mul_2op_p(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + obj->num_comments = 0; + return false; + } + for (i = 0; i < obj->num_comments; i++) { + /* Initialize here just to make sure. */ + obj->comments[i].length = 0; + obj->comments[i].entry = 0; + + FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32); + if (length < 4) { + obj->num_comments = i; + goto skip; + } + else + length -= 4; + if (!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length)) + return false; /* read_callback_ sets the state for us */ + if (obj->comments[i].length > 0) { + if (length < obj->comments[i].length) { + obj->num_comments = i; + goto skip; + } + else + length -= obj->comments[i].length; + if (0 == (obj->comments[i].entry = safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; + return false; + } + memset (obj->comments[i].entry, 0, obj->comments[i].length) ; + if (!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length)) { + obj->num_comments = i; + goto skip; + } + obj->comments[i].entry[obj->comments[i].length] = '\0'; + } + else + obj->comments[i].entry = 0; + } + } + else + obj->comments = 0; + } + + skip: + if (length > 0) { + /* This will only happen on files with invalid data in comments */ + if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length)) + return false; /* read_callback_ sets the state for us */ + } + + return true; +} +","@@ -1739,6 +1739,7 @@ + + if (obj->num_comments > 0) { + if (0 == (obj->comments = safe_malloc_mul_2op_p(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; ++ obj->num_comments = 0; + return false; + } + for (i = 0; i < obj->num_comments; i++) { +",960,1291,2048 +8917,"static int label_boot(cmd_tbl_t *cmdtp, struct pxe_label *label) +{ + char *bootm_argv[] = { ""bootm"", NULL, NULL, NULL, NULL }; + char initrd_str[28]; + char mac_str[29] = """"; + char ip_str[68] = """"; + char *fit_addr = NULL; + int bootm_argc = 2; + int len = 0; + ulong kernel_addr; + void *buf; + + label_print(label); + + label->attempted = 1; + + if (label->localboot) { + if (label->localboot_val >= 0) + label_localboot(label); + return 0; + } + + if (!label->kernel) { + printf(""No kernel given, skipping %s\n"", + label->name); + return 1; + } + + if (label->initrd) { + if (get_relfile_envaddr(cmdtp, label->initrd, ""ramdisk_addr_r"") < 0) { + printf(""Skipping %s for failure retrieving initrd\n"", + label->name); + return 1; + } + + bootm_argv[2] = initrd_str; + strncpy(bootm_argv[2], env_get(""ramdisk_addr_r""), 18); + strcat(bootm_argv[2], "":""); + strncat(bootm_argv[2], env_get(""filesize""), 9); + bootm_argc = 3; + } + + if (get_relfile_envaddr(cmdtp, label->kernel, ""kernel_addr_r"") < 0) { + printf(""Skipping %s for failure retrieving kernel\n"", + label->name); + return 1; + } + + if (label->ipappend & 0x1) { + sprintf(ip_str, "" ip=%s:%s:%s:%s"", + env_get(""ipaddr""), env_get(""serverip""), + env_get(""gatewayip""), env_get(""netmask"")); + } + +#ifdef CONFIG_CMD_NET + if (label->ipappend & 0x2) { + int err; + + strcpy(mac_str, "" BOOTIF=""); + err = format_mac_pxe(mac_str + 8, sizeof(mac_str) - 8); + if (err < 0) + mac_str[0] = '\0'; + } +#endif + + if ((label->ipappend & 0x3) || label->append) { + char bootargs[CONFIG_SYS_CBSIZE] = """"; + char finalbootargs[CONFIG_SYS_CBSIZE]; + + if (strlen(label->append ?: """") + + strlen(ip_str) + strlen(mac_str) + 1 > sizeof(bootargs)) { + printf(""bootarg overflow %zd+%zd+%zd+1 > %zd\n"", + strlen(label->append ?: """"), + strlen(ip_str), strlen(mac_str), + sizeof(bootargs)); + return 1; + } + + if (label->append) + strncpy(bootargs, label->append, sizeof(bootargs)); + + strcat(bootargs, ip_str); + strcat(bootargs, mac_str); + + cli_simple_process_macros(bootargs, finalbootargs); + env_set(""bootargs"", finalbootargs); + printf(""append: %s\n"", finalbootargs); + } + + bootm_argv[1] = env_get(""kernel_addr_r""); + /* for FIT, append the configuration identifier */ + if (label->config) { + int len = strlen(bootm_argv[1]) + strlen(label->config) + 1; + + fit_addr = malloc(len); + if (!fit_addr) { + printf(""malloc fail (FIT address)\n""); + return 1; + } + snprintf(fit_addr, len, ""%s%s"", bootm_argv[1], label->config); + bootm_argv[1] = fit_addr; + } + + /* + * fdt usage is optional: + * It handles the following scenarios. All scenarios are exclusive + * + * Scenario 1: If fdt_addr_r specified and ""fdt"" label is defined in + * pxe file, retrieve fdt blob from server. Pass fdt_addr_r to bootm, + * and adjust argc appropriately. + * + * Scenario 2: If there is an fdt_addr specified, pass it along to + * bootm, and adjust argc appropriately. + * + * Scenario 3: fdt blob is not available. + */ + bootm_argv[3] = env_get(""fdt_addr_r""); + + /* if fdt label is defined then get fdt from server */ + if (bootm_argv[3]) { + char *fdtfile = NULL; + char *fdtfilefree = NULL; + + if (label->fdt) { + fdtfile = label->fdt; + } else if (label->fdtdir) { + char *f1, *f2, *f3, *f4, *slash; + + f1 = env_get(""fdtfile""); + if (f1) { + f2 = """"; + f3 = """"; + f4 = """"; + } else { + /* + * For complex cases where this code doesn't + * generate the correct filename, the board + * code should set $fdtfile during early boot, + * or the boot scripts should set $fdtfile + * before invoking ""pxe"" or ""sysboot"". + */ + f1 = env_get(""soc""); + f2 = ""-""; + f3 = env_get(""board""); + f4 = "".dtb""; + } + + len = strlen(label->fdtdir); + if (!len) + slash = ""./""; + else if (label->fdtdir[len - 1] != '/') + slash = ""/""; + else + slash = """"; + + len = strlen(label->fdtdir) + strlen(slash) + + strlen(f1) + strlen(f2) + strlen(f3) + + strlen(f4) + 1; + fdtfilefree = malloc(len); + if (!fdtfilefree) { + printf(""malloc fail (FDT filename)\n""); + goto cleanup; + } + + snprintf(fdtfilefree, len, ""%s%s%s%s%s%s"", + label->fdtdir, slash, f1, f2, f3, f4); + fdtfile = fdtfilefree; + } + + if (fdtfile) { + int err = get_relfile_envaddr(cmdtp, fdtfile, + ""fdt_addr_r""); + + free(fdtfilefree); + if (err < 0) { + printf(""Skipping %s for failure retrieving fdt\n"", + label->name); + goto cleanup; + } + } else { + bootm_argv[3] = NULL; + } + } + + if (!bootm_argv[3]) + bootm_argv[3] = env_get(""fdt_addr""); + + if (bootm_argv[3]) { + if (!bootm_argv[2]) + bootm_argv[2] = ""-""; + bootm_argc = 4; + } + + kernel_addr = genimg_get_kernel_addr(bootm_argv[1]); + buf = map_sysmem(kernel_addr, 0); + /* Try bootm for legacy and FIT format image */ + if (genimg_get_format(buf) != IMAGE_FORMAT_INVALID) + do_bootm(cmdtp, 0, bootm_argc, bootm_argv); +#ifdef CONFIG_CMD_BOOTI + /* Try booting an AArch64 Linux kernel image */ + else + do_booti(cmdtp, 0, bootm_argc, bootm_argv); +#elif defined(CONFIG_CMD_BOOTZ) + /* Try booting a Image */ + else + do_bootz(cmdtp, 0, bootm_argc, bootm_argv); +#endif + unmap_sysmem(buf); + +cleanup: + if (fit_addr) + free(fit_addr); + return 1; +} +",0,"static int label_boot(cmd_tbl_t *cmdtp, struct pxe_label *label) +{ + char *bootm_argv[] = { ""bootm"", NULL, NULL, NULL, NULL }; + char initrd_str[28]; + char mac_str[29] = """"; + char ip_str[68] = """"; + char *fit_addr = NULL; + int bootm_argc = 2; + int len = 0; + ulong kernel_addr; + void *buf; + + label_print(label); + + label->attempted = 1; + + if (label->localboot) { + if (label->localboot_val >= 0) + label_localboot(label); + return 0; + } + + if (!label->kernel) { + printf(""No kernel given, skipping %s\n"", + label->name); + return 1; + } + + if (label->initrd) { + if (get_relfile_envaddr(cmdtp, label->initrd, ""ramdisk_addr_r"") < 0) { + printf(""Skipping %s for failure retrieving initrd\n"", + label->name); + return 1; + } + + bootm_argv[2] = initrd_str; + strncpy(bootm_argv[2], env_get(""ramdisk_addr_r""), 18); + strcat(bootm_argv[2], "":""); + strncat(bootm_argv[2], env_get(""filesize""), 9); + bootm_argc = 3; + } + + if (get_relfile_envaddr(cmdtp, label->kernel, ""kernel_addr_r"") < 0) { + printf(""Skipping %s for failure retrieving kernel\n"", + label->name); + return 1; + } + + if (label->ipappend & 0x1) { + sprintf(ip_str, "" ip=%s:%s:%s:%s"", + env_get(""ipaddr""), env_get(""serverip""), + env_get(""gatewayip""), env_get(""netmask"")); + } + +#ifdef CONFIG_CMD_NET + if (label->ipappend & 0x2) { + int err; + + strcpy(mac_str, "" BOOTIF=""); + err = format_mac_pxe(mac_str + 8, sizeof(mac_str) - 8); + if (err < 0) + mac_str[0] = '\0'; + } +#endif + + if ((label->ipappend & 0x3) || label->append) { + char bootargs[CONFIG_SYS_CBSIZE] = """"; + char finalbootargs[CONFIG_SYS_CBSIZE]; + + if (strlen(label->append ?: """") + + strlen(ip_str) + strlen(mac_str) + 1 > sizeof(bootargs)) { + printf(""bootarg overflow %zd+%zd+%zd+1 > %zd\n"", + strlen(label->append ?: """"), + strlen(ip_str), strlen(mac_str), + sizeof(bootargs)); + return 1; + } + + if (label->append) + strncpy(bootargs, label->append, sizeof(bootargs)); + + strcat(bootargs, ip_str); + strcat(bootargs, mac_str); + + cli_simple_process_macros(bootargs, finalbootargs); + env_set(""bootargs"", finalbootargs); + printf(""append: %s\n"", finalbootargs); + } + + bootm_argv[1] = env_get(""kernel_addr_r""); + /* for FIT, append the configuration identifier */ + if (label->config) { + int len = strlen(bootm_argv[1]) + strlen(label->config) + 1; + + fit_addr = malloc(len); + if (!fit_addr) { + printf(""malloc fail (FIT address)\n""); + return 1; + } + snprintf(fit_addr, len, ""%s%s"", bootm_argv[1], label->config); + bootm_argv[1] = fit_addr; + } + + /* + * fdt usage is optional: + * It handles the following scenarios. All scenarios are exclusive + * + * Scenario 1: If fdt_addr_r specified and ""fdt"" label is defined in + * pxe file, retrieve fdt blob from server. Pass fdt_addr_r to bootm, + * and adjust argc appropriately. + * + * Scenario 2: If there is an fdt_addr specified, pass it along to + * bootm, and adjust argc appropriately. + * + * Scenario 3: fdt blob is not available. + */ + bootm_argv[3] = env_get(""fdt_addr_r""); + + /* if fdt label is defined then get fdt from server */ + if (bootm_argv[3]) { + char *fdtfile = NULL; + char *fdtfilefree = NULL; + + if (label->fdt) { + fdtfile = label->fdt; + } else if (label->fdtdir) { + char *f1, *f2, *f3, *f4, *slash; + + f1 = env_get(""fdtfile""); + if (f1) { + f2 = """"; + f3 = """"; + f4 = """"; + } else { + /* + * For complex cases where this code doesn't + * generate the correct filename, the board + * code should set $fdtfile during early boot, + * or the boot scripts should set $fdtfile + * before invoking ""pxe"" or ""sysboot"". + */ + f1 = env_get(""soc""); + f2 = ""-""; + f3 = env_get(""board""); + f4 = "".dtb""; + } + + len = strlen(label->fdtdir); + if (!len) + slash = ""./""; + else if (label->fdtdir[len - 1] != '/') + slash = ""/""; + else + slash = """"; + + len = strlen(label->fdtdir) + strlen(slash) + + strlen(f1) + strlen(f2) + strlen(f3) + + strlen(f4) + 1; + fdtfilefree = malloc(len); + if (!fdtfilefree) { + printf(""malloc fail (FDT filename)\n""); + goto cleanup; + } + + snprintf(fdtfilefree, len, ""%s%s%s%s%s%s"", + label->fdtdir, slash, f1, f2, f3, f4); + fdtfile = fdtfilefree; + } + + if (fdtfile) { + int err = get_relfile_envaddr(cmdtp, fdtfile, + ""fdt_addr_r""); + + free(fdtfilefree); + if (err < 0) { + printf(""Skipping %s for failure retrieving fdt\n"", + label->name); + goto cleanup; + } + } else { + bootm_argv[3] = NULL; + } + } + + if (!bootm_argv[3]) + bootm_argv[3] = env_get(""fdt_addr""); + + if (bootm_argv[3]) { + if (!bootm_argv[2]) + bootm_argv[2] = ""-""; + bootm_argc = 4; + } + + kernel_addr = genimg_get_kernel_addr(bootm_argv[1]); + buf = map_sysmem(kernel_addr, 0); + /* Try bootm for legacy and FIT format image */ + if (genimg_get_format(buf) != IMAGE_FORMAT_INVALID) + do_bootm(cmdtp, 0, bootm_argc, bootm_argv); +#ifdef CONFIG_CMD_BOOTI + /* Try booting an AArch64 Linux kernel image */ + else + do_booti(cmdtp, 0, bootm_argc, bootm_argv); +#elif defined(CONFIG_CMD_BOOTZ) + /* Try booting a Image */ + else + do_bootz(cmdtp, 0, bootm_argc, bootm_argv); +#endif + unmap_sysmem(buf); + +cleanup: + if (fit_addr) + free(fit_addr); + return 1; +} +","@@ -1312,7 +1312,8 @@ void handle_pxe_menu(cmd_tbl_t *cmdtp, struct pxe_menu *cfg) + /* display BMP if available */ + if (cfg->bmp) { + if (get_relfile(cmdtp, cfg->bmp, image_load_addr)) { +- run_command(""cls"", 0); ++ if (CONFIG_IS_ENABLED(CMD_CLS)) ++ run_command(""cls"", 0); + bmp_display(image_load_addr, + BMP_ALIGN_CENTER, BMP_ALIGN_CENTER); + } else {",1702,2033,2048 +7326,"static int UnpackWPG2Raster(Image *image,int bpp) +{ + int XorMe = 0; + + int + RunCount; + + size_t + x, + y; + + ssize_t + i, + ldblk; + + unsigned int + SampleSize=1; + + unsigned char + bbuf, + *BImgBuff, + SampleBuffer[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + + x=0; + y=0; + ldblk=(ssize_t) ((bpp*image->columns+7)/8); + BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk, + sizeof(*BImgBuff)); + if(BImgBuff==NULL) + return(-2); + + while( y< image->rows) + { + bbuf=ReadBlobByte(image); + + switch(bbuf) + { + case 0x7D: + SampleSize=ReadBlobByte(image); /* DSZ */ + if(SampleSize>8) + return(-2); + if(SampleSize<1) + return(-2); + break; + case 0x7E: + (void) FormatLocaleFile(stderr, + ""\nUnsupported WPG token XOR, please report!""); + XorMe=!XorMe; + break; + case 0x7F: + RunCount=ReadBlobByte(image); /* BLK */ + if (RunCount < 0) + break; + for(i=0; i < SampleSize*(RunCount+1); i++) + { + InsertByte6(0); + } + break; + case 0xFD: + RunCount=ReadBlobByte(image); /* EXT */ + if (RunCount < 0) + break; + for(i=0; i<= RunCount;i++) + for(bbuf=0; bbuf < SampleSize; bbuf++) + InsertByte6(SampleBuffer[bbuf]); + break; + case 0xFE: + RunCount=ReadBlobByte(image); /* RST */ + if (RunCount < 0) + break; + if(x!=0) + { + (void) FormatLocaleFile(stderr, + ""\nUnsupported WPG2 unaligned token RST x=%.20g, please report!\n"" + ,(double) x); + return(-3); + } + { + /* duplicate the previous row RunCount x */ + for(i=0;i<=RunCount;i++) + { + InsertRow(BImgBuff,(ssize_t) (image->rows >= y ? y : image->rows-1), + image,bpp); + y++; + } + } + break; + case 0xFF: + RunCount=ReadBlobByte(image); /* WHT */ + if (RunCount < 0) + break; + for (i=0; i < SampleSize*(RunCount+1); i++) + { + InsertByte6(0xFF); + } + break; + default: + RunCount=bbuf & 0x7F; + + if(bbuf & 0x80) /* REP */ + { + for(i=0; i < SampleSize; i++) + SampleBuffer[i]=ReadBlobByte(image); + for(i=0;i<=RunCount;i++) + for(bbuf=0;bbufcolumns+7)/8); + BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) ldblk, + sizeof(*BImgBuff)); + if(BImgBuff==NULL) + return(-2); + + while( y< image->rows) + { + bbuf=ReadBlobByte(image); + + switch(bbuf) + { + case 0x7D: + SampleSize=ReadBlobByte(image); /* DSZ */ + if(SampleSize>8) + return(-2); + if(SampleSize<1) + return(-2); + break; + case 0x7E: + (void) FormatLocaleFile(stderr, + ""\nUnsupported WPG token XOR, please report!""); + XorMe=!XorMe; + break; + case 0x7F: + RunCount=ReadBlobByte(image); /* BLK */ + if (RunCount < 0) + break; + for(i=0; i < SampleSize*(RunCount+1); i++) + { + InsertByte6(0); + } + break; + case 0xFD: + RunCount=ReadBlobByte(image); /* EXT */ + if (RunCount < 0) + break; + for(i=0; i<= RunCount;i++) + for(bbuf=0; bbuf < SampleSize; bbuf++) + InsertByte6(SampleBuffer[bbuf]); + break; + case 0xFE: + RunCount=ReadBlobByte(image); /* RST */ + if (RunCount < 0) + break; + if(x!=0) + { + (void) FormatLocaleFile(stderr, + ""\nUnsupported WPG2 unaligned token RST x=%.20g, please report!\n"" + ,(double) x); + return(-3); + } + { + /* duplicate the previous row RunCount x */ + for(i=0;i<=RunCount;i++) + { + InsertRow(BImgBuff,(ssize_t) (image->rows >= y ? y : image->rows-1), + image,bpp); + y++; + } + } + break; + case 0xFF: + RunCount=ReadBlobByte(image); /* WHT */ + if (RunCount < 0) + break; + for (i=0; i < SampleSize*(RunCount+1); i++) + { + InsertByte6(0xFF); + } + break; + default: + RunCount=bbuf & 0x7F; + + if(bbuf & 0x80) /* REP */ + { + for(i=0; i < SampleSize; i++) + SampleBuffer[i]=ReadBlobByte(image); + for(i=0;i<=RunCount;i++) + for(bbuf=0;bbufseverity != UndefinedException) goto FINISH_UNL; + if(magic_info->name == (char *) NULL) goto FINISH_UNL; + +- (void) CopyMagickMemory(clone_info->magick,magic_info->name,MaxTextExtent); ++ (void) strncpy(clone_info->magick,magic_info->name,MaxTextExtent); + + /* Read nested image */ + /*FormatString(clone_info->filename,""%s:%s"",magic_info->name,postscript_file);*/",818,1149,2048 +17451,"static void check_and_set_gain_dep_cal() +{ + + struct listnode *node = NULL; + float new_vol = 0.0; + int max_level = 0; + vol_listener_context_t *context = NULL; + if (dumping_enabled) { + dump_list_l(); + } + + ALOGV(""%s ==> Start ..."", __func__); + + list_for_each(node, &vol_effect_list) { + context = node_to_item(node, struct vol_listener_context_s, effect_list_node); + if ((context->state == VOL_LISTENER_STATE_ACTIVE) && + (context->dev_id & AUDIO_DEVICE_OUT_SPEAKER) && + (new_vol < (context->left_vol + context->right_vol) / 2)) { + new_vol = (context->left_vol + context->right_vol) / 2; + } + } + + if (new_vol != current_vol) { + ALOGV(""%s:: Change in decision :: current volume is %f new volume is %f"", + __func__, current_vol, new_vol); + + if (send_gain_dep_cal != NULL) { + int gain_dep_cal_level = -1; + + if (new_vol >= 1) { // max amplitude, use highest DRC level + gain_dep_cal_level = volume_curve_gain_mapping_table[MAX_GAIN_LEVELS - 1].level; + } else if (new_vol <= 0) { + gain_dep_cal_level = volume_curve_gain_mapping_table[0].level; + } else { + for (max_level = 0; max_level + 1 < MAX_GAIN_LEVELS; max_level++) { + if (new_vol < volume_curve_gain_mapping_table[max_level + 1].amp && + new_vol >= volume_curve_gain_mapping_table[max_level].amp) { + gain_dep_cal_level = volume_curve_gain_mapping_table[max_level].level; + ALOGV(""%s: volume(%f), gain dep cal selcetd %d "", + __func__, current_vol, gain_dep_cal_level); + break; + } + } + } + + if (gain_dep_cal_level != -1) { + if (gain_dep_cal_level != current_gain_dep_cal_level) { + if (!send_gain_dep_cal(gain_dep_cal_level)) { + ALOGE(""%s: Failed to set gain dep cal level"", __func__); + } else { + if (dumping_enabled) { + ALOGW(""%s: (old/new) Volume (%f/%f) (old/new) level (%d/%d)"", + __func__, current_vol, new_vol, current_gain_dep_cal_level, + gain_dep_cal_level); + } else { + ALOGV(""%s: Change in Cal::(old/new) Volume (%f/%f) (old/new) level (%d/%d)"", + __func__, current_vol, new_vol, current_gain_dep_cal_level, + gain_dep_cal_level); + } + current_gain_dep_cal_level = gain_dep_cal_level; + current_vol = new_vol; + } + } else { + if (dumping_enabled) { + ALOGW(""%s: volume changed but gain dep cal level is still the same"", + __func__); + } else { + ALOGV(""%s: volume changed but gain dep cal level is still the same"", + __func__); + } + } + } else { + ALOGW(""%s: Failed to find gain dep cal level for volume %f"", __func__, new_vol); + } + } else { + ALOGE(""%s: not able to send calibration, NULL function pointer"", + __func__); + } + } else { + ALOGV(""%s:: volume not changed, stick to same config ..... "", __func__); + } + + ALOGV(""check_and_set_gain_dep_cal ==> End ""); +} +",0,"static void check_and_set_gain_dep_cal() +{ + + struct listnode *node = NULL; + float new_vol = 0.0; + int max_level = 0; + vol_listener_context_t *context = NULL; + if (dumping_enabled) { + dump_list_l(); + } + + ALOGV(""%s ==> Start ..."", __func__); + + list_for_each(node, &vol_effect_list) { + context = node_to_item(node, struct vol_listener_context_s, effect_list_node); + if ((context->state == VOL_LISTENER_STATE_ACTIVE) && + (context->dev_id & AUDIO_DEVICE_OUT_SPEAKER) && + (new_vol < (context->left_vol + context->right_vol) / 2)) { + new_vol = (context->left_vol + context->right_vol) / 2; + } + } + + if (new_vol != current_vol) { + ALOGV(""%s:: Change in decision :: current volume is %f new volume is %f"", + __func__, current_vol, new_vol); + + if (send_gain_dep_cal != NULL) { + int gain_dep_cal_level = -1; + + if (new_vol >= 1) { // max amplitude, use highest DRC level + gain_dep_cal_level = volume_curve_gain_mapping_table[MAX_GAIN_LEVELS - 1].level; + } else if (new_vol <= 0) { + gain_dep_cal_level = volume_curve_gain_mapping_table[0].level; + } else { + for (max_level = 0; max_level + 1 < MAX_GAIN_LEVELS; max_level++) { + if (new_vol < volume_curve_gain_mapping_table[max_level + 1].amp && + new_vol >= volume_curve_gain_mapping_table[max_level].amp) { + gain_dep_cal_level = volume_curve_gain_mapping_table[max_level].level; + ALOGV(""%s: volume(%f), gain dep cal selcetd %d "", + __func__, current_vol, gain_dep_cal_level); + break; + } + } + } + + if (gain_dep_cal_level != -1) { + if (gain_dep_cal_level != current_gain_dep_cal_level) { + if (!send_gain_dep_cal(gain_dep_cal_level)) { + ALOGE(""%s: Failed to set gain dep cal level"", __func__); + } else { + if (dumping_enabled) { + ALOGW(""%s: (old/new) Volume (%f/%f) (old/new) level (%d/%d)"", + __func__, current_vol, new_vol, current_gain_dep_cal_level, + gain_dep_cal_level); + } else { + ALOGV(""%s: Change in Cal::(old/new) Volume (%f/%f) (old/new) level (%d/%d)"", + __func__, current_vol, new_vol, current_gain_dep_cal_level, + gain_dep_cal_level); + } + current_gain_dep_cal_level = gain_dep_cal_level; + current_vol = new_vol; + } + } else { + if (dumping_enabled) { + ALOGW(""%s: volume changed but gain dep cal level is still the same"", + __func__); + } else { + ALOGV(""%s: volume changed but gain dep cal level is still the same"", + __func__); + } + } + } else { + ALOGW(""%s: Failed to find gain dep cal level for volume %f"", __func__, new_vol); + } + } else { + ALOGE(""%s: not able to send calibration, NULL function pointer"", + __func__); + } + } else { + ALOGV(""%s:: volume not changed, stick to same config ..... "", __func__); + } + + ALOGV(""check_and_set_gain_dep_cal ==> End ""); +} +","@@ -667,20 +667,31 @@ + + struct listnode *node, *temp_node_next; + vol_listener_context_t *context = NULL; + vol_listener_context_t *recv_contex = (vol_listener_context_t *)handle; +- int status = -1; ++ int status = -EINVAL; + bool recompute_flag = false; + int active_stream_count = 0; ++ uint32_t session_id; ++ uint32_t stream_type; ++ effect_uuid_t uuid; ++ + ALOGV(""%s context %p"", __func__, handle); ++ ++ if (recv_contex == NULL) { ++ return status; ++ } + pthread_mutex_lock(&vol_listner_init_lock); ++ session_id = recv_contex->session_id; ++ stream_type = recv_contex->stream_type; ++ uuid = recv_contex->desc->uuid; + + // check if the handle/context provided is valid + list_for_each_safe(node, temp_node_next, &vol_effect_list) { + context = node_to_item(node, struct vol_listener_context_s, effect_list_node); +- if ((memcmp(&(context->desc->uuid), &(recv_contex->desc->uuid), sizeof(effect_uuid_t)) == 0) +- && (context->session_id == recv_contex->session_id) +- && (context->stream_type == recv_contex->stream_type)) { ++ if ((memcmp(&(context->desc->uuid), &uuid, sizeof(effect_uuid_t)) == 0) ++ && (context->session_id == session_id) ++ && (context->stream_type == stream_type)) { + ALOGV(""--- Found something to remove ---""); +- list_remove(&context->effect_list_node); ++ list_remove(node); + PRINT_STREAM_TYPE(context->stream_type); + if (context->dev_id && AUDIO_DEVICE_OUT_SPEAKER) { + recompute_flag = true; +@@ -694,6 +705,8 @@ + + + if (status != 0) { + ALOGE(""something wrong ... <<<--- Found NOTHING to remove ... ???? --->>>>>""); ++ pthread_mutex_unlock(&vol_listner_init_lock); ++ return status; + } + + // if there are no active streams, reset cal and volume level +",741,1072,2048 +6149,"static int nsv_parse_NSVs_header(AVFormatContext *s) +{ + NSVContext *nsv = s->priv_data; + AVIOContext *pb = s->pb; + uint32_t vtag, atag; + uint16_t vwidth, vheight; + AVRational framerate; + int i; + AVStream *st; + NSVStream *nst; + + vtag = avio_rl32(pb); + atag = avio_rl32(pb); + vwidth = avio_rl16(pb); + vheight = avio_rl16(pb); + i = avio_r8(pb); + + av_log(s, AV_LOG_TRACE, ""NSV NSVs framerate code %2x\n"", i); + if(i&0x80) { /* odd way of giving native framerates from docs */ + int t=(i & 0x7F)>>2; + if(t<16) framerate = (AVRational){1, t+1}; + else framerate = (AVRational){t-15, 1}; + + if(i&1){ + framerate.num *= 1000; + framerate.den *= 1001; + } + + if((i&3)==3) framerate.num *= 24; + else if((i&3)==2) framerate.num *= 25; + else framerate.num *= 30; + } + else + framerate= (AVRational){i, 1}; + + nsv->avsync = avio_rl16(pb); + nsv->framerate = framerate; + + av_log(s, AV_LOG_TRACE, ""NSV NSVs vsize %dx%d\n"", vwidth, vheight); + + /* XXX change to ap != NULL ? */ + if (s->nb_streams == 0) { /* streams not yet published, let's do that */ + nsv->vtag = vtag; + nsv->atag = atag; + nsv->vwidth = vwidth; + nsv->vheight = vwidth; + if (vtag != T_NONE) { + int i; + st = avformat_new_stream(s, NULL); + if (!st) + goto fail; + + st->id = NSV_ST_VIDEO; + nst = av_mallocz(sizeof(NSVStream)); + if (!nst) + goto fail; + st->priv_data = nst; + st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; + st->codecpar->codec_tag = vtag; + st->codecpar->codec_id = ff_codec_get_id(nsv_codec_video_tags, vtag); + st->codecpar->width = vwidth; + st->codecpar->height = vheight; + st->codecpar->bits_per_coded_sample = 24; /* depth XXX */ + + avpriv_set_pts_info(st, 64, framerate.den, framerate.num); + st->start_time = 0; + st->duration = av_rescale(nsv->duration, framerate.num, 1000*framerate.den); + + for(i=0;iindex_entries;i++) { + if(nsv->nsvs_timestamps) { + av_add_index_entry(st, nsv->nsvs_file_offset[i], nsv->nsvs_timestamps[i], + 0, 0, AVINDEX_KEYFRAME); + } else { + int64_t ts = av_rescale(i*nsv->duration/nsv->index_entries, framerate.num, 1000*framerate.den); + av_add_index_entry(st, nsv->nsvs_file_offset[i], ts, 0, 0, AVINDEX_KEYFRAME); + } + } + } + if (atag != T_NONE) { + st = avformat_new_stream(s, NULL); + if (!st) + goto fail; + + st->id = NSV_ST_AUDIO; + nst = av_mallocz(sizeof(NSVStream)); + if (!nst) + goto fail; + st->priv_data = nst; + st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; + st->codecpar->codec_tag = atag; + st->codecpar->codec_id = ff_codec_get_id(nsv_codec_audio_tags, atag); + + st->need_parsing = AVSTREAM_PARSE_FULL; /* for PCM we will read a chunk later and put correct info */ + + /* set timebase to common denominator of ms and framerate */ + avpriv_set_pts_info(st, 64, 1, framerate.num*1000); + st->start_time = 0; + st->duration = (int64_t)nsv->duration * framerate.num; + } + } else { + if (nsv->vtag != vtag || nsv->atag != atag || nsv->vwidth != vwidth || nsv->vheight != vwidth) { + av_log(s, AV_LOG_TRACE, ""NSV NSVs header values differ from the first one!!!\n""); + } + } + + nsv->state = NSV_HAS_READ_NSVS; + return 0; +fail: + /* XXX */ + nsv->state = NSV_UNSYNC; + return -1; +} +",0,"static int nsv_parse_NSVs_header(AVFormatContext *s) +{ + NSVContext *nsv = s->priv_data; + AVIOContext *pb = s->pb; + uint32_t vtag, atag; + uint16_t vwidth, vheight; + AVRational framerate; + int i; + AVStream *st; + NSVStream *nst; + + vtag = avio_rl32(pb); + atag = avio_rl32(pb); + vwidth = avio_rl16(pb); + vheight = avio_rl16(pb); + i = avio_r8(pb); + + av_log(s, AV_LOG_TRACE, ""NSV NSVs framerate code %2x\n"", i); + if(i&0x80) { /* odd way of giving native framerates from docs */ + int t=(i & 0x7F)>>2; + if(t<16) framerate = (AVRational){1, t+1}; + else framerate = (AVRational){t-15, 1}; + + if(i&1){ + framerate.num *= 1000; + framerate.den *= 1001; + } + + if((i&3)==3) framerate.num *= 24; + else if((i&3)==2) framerate.num *= 25; + else framerate.num *= 30; + } + else + framerate= (AVRational){i, 1}; + + nsv->avsync = avio_rl16(pb); + nsv->framerate = framerate; + + av_log(s, AV_LOG_TRACE, ""NSV NSVs vsize %dx%d\n"", vwidth, vheight); + + /* XXX change to ap != NULL ? */ + if (s->nb_streams == 0) { /* streams not yet published, let's do that */ + nsv->vtag = vtag; + nsv->atag = atag; + nsv->vwidth = vwidth; + nsv->vheight = vwidth; + if (vtag != T_NONE) { + int i; + st = avformat_new_stream(s, NULL); + if (!st) + goto fail; + + st->id = NSV_ST_VIDEO; + nst = av_mallocz(sizeof(NSVStream)); + if (!nst) + goto fail; + st->priv_data = nst; + st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; + st->codecpar->codec_tag = vtag; + st->codecpar->codec_id = ff_codec_get_id(nsv_codec_video_tags, vtag); + st->codecpar->width = vwidth; + st->codecpar->height = vheight; + st->codecpar->bits_per_coded_sample = 24; /* depth XXX */ + + avpriv_set_pts_info(st, 64, framerate.den, framerate.num); + st->start_time = 0; + st->duration = av_rescale(nsv->duration, framerate.num, 1000*framerate.den); + + for(i=0;iindex_entries;i++) { + if(nsv->nsvs_timestamps) { + av_add_index_entry(st, nsv->nsvs_file_offset[i], nsv->nsvs_timestamps[i], + 0, 0, AVINDEX_KEYFRAME); + } else { + int64_t ts = av_rescale(i*nsv->duration/nsv->index_entries, framerate.num, 1000*framerate.den); + av_add_index_entry(st, nsv->nsvs_file_offset[i], ts, 0, 0, AVINDEX_KEYFRAME); + } + } + } + if (atag != T_NONE) { + st = avformat_new_stream(s, NULL); + if (!st) + goto fail; + + st->id = NSV_ST_AUDIO; + nst = av_mallocz(sizeof(NSVStream)); + if (!nst) + goto fail; + st->priv_data = nst; + st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; + st->codecpar->codec_tag = atag; + st->codecpar->codec_id = ff_codec_get_id(nsv_codec_audio_tags, atag); + + st->need_parsing = AVSTREAM_PARSE_FULL; /* for PCM we will read a chunk later and put correct info */ + + /* set timebase to common denominator of ms and framerate */ + avpriv_set_pts_info(st, 64, 1, framerate.num*1000); + st->start_time = 0; + st->duration = (int64_t)nsv->duration * framerate.num; + } + } else { + if (nsv->vtag != vtag || nsv->atag != atag || nsv->vwidth != vwidth || nsv->vheight != vwidth) { + av_log(s, AV_LOG_TRACE, ""NSV NSVs header values differ from the first one!!!\n""); + } + } + + nsv->state = NSV_HAS_READ_NSVS; + return 0; +fail: + /* XXX */ + nsv->state = NSV_UNSYNC; + return -1; +} +","@@ -335,8 +335,11 @@ static int nsv_parse_NSVf_header(AVFormatContext *s) + if (!nsv->nsvs_file_offset) + return AVERROR(ENOMEM); + +- for(i=0;insvs_file_offset[i] = avio_rl32(pb) + size; ++ } + + if(table_entries > table_entries_used && + avio_rl32(pb) == MKTAG('T','O','C','2')) {",1131,1462,2048 +18419,"void Browser::Observe(NotificationType type, + const NotificationSource& source, + const NotificationDetails& details) { + switch (type.value) { + case NotificationType::TAB_CONTENTS_DISCONNECTED: + if (is_attempting_to_close_browser_) { + MessageLoop::current()->PostTask( + FROM_HERE, + method_factory_.NewRunnableMethod(&Browser::ClearUnloadState, + Source(source).ptr())); + } + break; + + case NotificationType::SSL_VISIBLE_STATE_CHANGED: + if (GetSelectedTabContents() && + &GetSelectedTabContents()->controller() == + Source(source).ptr()) + UpdateToolbar(false); + break; + + case NotificationType::EXTENSION_UPDATE_DISABLED: { + Profile* profile = Source(source).ptr(); + if (profile_->IsSameProfile(profile)) { + ExtensionService* service = profile->GetExtensionService(); + DCHECK(service); + const Extension* extension = Details(details).ptr(); + if (service->extension_prefs()->DidExtensionEscalatePermissions( + extension->id())) + ShowExtensionDisabledUI(service, profile_, extension); + } + break; + } + + case NotificationType::EXTENSION_UNLOADED: { + window()->GetLocationBar()->UpdatePageActions(); + + const Extension* extension = + Details(details)->extension; + TabStripModel* model = tab_handler_->GetTabStripModel(); + for (int i = model->count() - 1; i >= 0; --i) { + TabContents* tc = model->GetTabContentsAt(i)->tab_contents(); + if (tc->GetURL().SchemeIs(chrome::kExtensionScheme) && + tc->GetURL().host() == extension->id()) { + CloseTabContents(tc); + } + } + + break; + } + + case NotificationType::EXTENSION_PROCESS_TERMINATED: { + window()->GetLocationBar()->InvalidatePageActions(); + + TabContents* tab_contents = GetSelectedTabContents(); + if (!tab_contents) + break; + ExtensionService* extensions_service = + Source(source).ptr()->GetExtensionService(); + ExtensionHost* extension_host = Details(details).ptr(); + tab_contents->AddInfoBar(new CrashedExtensionInfoBarDelegate( + tab_contents, extensions_service, extension_host->extension())); + break; + } + + case NotificationType::EXTENSION_LOADED: { + window()->GetLocationBar()->UpdatePageActions(); + + const Extension* extension = Details(details).ptr(); + CrashedExtensionInfoBarDelegate* delegate = NULL; + TabStripModel* model = tab_handler_->GetTabStripModel(); + for (int m = 0; m < model->count(); ++m) { + TabContents* tab_contents = model->GetTabContentsAt(m)->tab_contents(); + for (int i = 0; i < tab_contents->infobar_delegate_count();) { + delegate = tab_contents->GetInfoBarDelegateAt(i)-> + AsCrashedExtensionInfoBarDelegate(); + if (delegate && delegate->extension_id() == extension->id()) { + tab_contents->RemoveInfoBar(delegate); + continue; + } + ++i; + } + } + break; + } + + case NotificationType::BROWSER_THEME_CHANGED: + window()->UserChangedTheme(); + break; + + case NotificationType::EXTENSION_READY_FOR_INSTALL: { + if (BrowserList::FindBrowserWithType(profile(), + Browser::TYPE_NORMAL, + true) != this) + break; + + GURL download_url = *(Details(details).ptr()); + if (ExtensionService::IsDownloadFromMiniGallery(download_url)) + window()->ShowThemeInstallBubble(); + break; + } + + case NotificationType::PROFILE_ERROR: { + if (BrowserList::GetLastActive() != this) + break; + int* message_id = Details(details).ptr(); + window()->ShowProfileErrorDialog(*message_id); + break; + } + + case NotificationType::PREF_CHANGED: { + const std::string& pref_name = *Details(details).ptr(); + if (pref_name == prefs::kUseVerticalTabs) { + UseVerticalTabsChanged(); + } else if (pref_name == prefs::kPrintingEnabled) { + UpdatePrintingState(0); + } else if (pref_name == prefs::kInstantEnabled) { + if (!InstantController::IsEnabled(profile())) { + if (instant()) { + instant()->DestroyPreviewContents(); + instant_.reset(); + instant_unload_handler_.reset(); + } + } else { + CreateInstantIfNecessary(); + } + } else if (pref_name == prefs::kDevToolsDisabled) { + UpdateCommandsForDevTools(); + if (dev_tools_disabled_.GetValue()) + g_browser_process->devtools_manager()->CloseAllClientHosts(); + } else { + NOTREACHED(); + } + break; + } + + default: + NOTREACHED() << ""Got a notification we didn't register for.""; + } +} +",1,"void Browser::Observe(NotificationType type, + const NotificationSource& source, + const NotificationDetails& details) { + switch (type.value) { + case NotificationType::TAB_CONTENTS_DISCONNECTED: + if (is_attempting_to_close_browser_) { + // Pass in false so that we delay processing. We need to delay the + // processing as it may close the tab, which is currently on the call + // stack above us. + ClearUnloadState(Source(source).ptr(), false); + } + break; + + case NotificationType::SSL_VISIBLE_STATE_CHANGED: + if (GetSelectedTabContents() && + &GetSelectedTabContents()->controller() == + Source(source).ptr()) + UpdateToolbar(false); + break; + + case NotificationType::EXTENSION_UPDATE_DISABLED: { + Profile* profile = Source(source).ptr(); + if (profile_->IsSameProfile(profile)) { + ExtensionService* service = profile->GetExtensionService(); + DCHECK(service); + const Extension* extension = Details(details).ptr(); + if (service->extension_prefs()->DidExtensionEscalatePermissions( + extension->id())) + ShowExtensionDisabledUI(service, profile_, extension); + } + break; + } + + case NotificationType::EXTENSION_UNLOADED: { + window()->GetLocationBar()->UpdatePageActions(); + + const Extension* extension = + Details(details)->extension; + TabStripModel* model = tab_handler_->GetTabStripModel(); + for (int i = model->count() - 1; i >= 0; --i) { + TabContents* tc = model->GetTabContentsAt(i)->tab_contents(); + if (tc->GetURL().SchemeIs(chrome::kExtensionScheme) && + tc->GetURL().host() == extension->id()) { + CloseTabContents(tc); + } + } + + break; + } + + case NotificationType::EXTENSION_PROCESS_TERMINATED: { + window()->GetLocationBar()->InvalidatePageActions(); + + TabContents* tab_contents = GetSelectedTabContents(); + if (!tab_contents) + break; + ExtensionService* extensions_service = + Source(source).ptr()->GetExtensionService(); + ExtensionHost* extension_host = Details(details).ptr(); + tab_contents->AddInfoBar(new CrashedExtensionInfoBarDelegate( + tab_contents, extensions_service, extension_host->extension())); + break; + } + + case NotificationType::EXTENSION_LOADED: { + window()->GetLocationBar()->UpdatePageActions(); + + const Extension* extension = Details(details).ptr(); + CrashedExtensionInfoBarDelegate* delegate = NULL; + TabStripModel* model = tab_handler_->GetTabStripModel(); + for (int m = 0; m < model->count(); ++m) { + TabContents* tab_contents = model->GetTabContentsAt(m)->tab_contents(); + for (int i = 0; i < tab_contents->infobar_delegate_count();) { + delegate = tab_contents->GetInfoBarDelegateAt(i)-> + AsCrashedExtensionInfoBarDelegate(); + if (delegate && delegate->extension_id() == extension->id()) { + tab_contents->RemoveInfoBar(delegate); + continue; + } + ++i; + } + } + break; + } + + case NotificationType::BROWSER_THEME_CHANGED: + window()->UserChangedTheme(); + break; + + case NotificationType::EXTENSION_READY_FOR_INSTALL: { + if (BrowserList::FindBrowserWithType(profile(), + Browser::TYPE_NORMAL, + true) != this) + break; + + GURL download_url = *(Details(details).ptr()); + if (ExtensionService::IsDownloadFromMiniGallery(download_url)) + window()->ShowThemeInstallBubble(); + break; + } + + case NotificationType::PROFILE_ERROR: { + if (BrowserList::GetLastActive() != this) + break; + int* message_id = Details(details).ptr(); + window()->ShowProfileErrorDialog(*message_id); + break; + } + + case NotificationType::PREF_CHANGED: { + const std::string& pref_name = *Details(details).ptr(); + if (pref_name == prefs::kUseVerticalTabs) { + UseVerticalTabsChanged(); + } else if (pref_name == prefs::kPrintingEnabled) { + UpdatePrintingState(0); + } else if (pref_name == prefs::kInstantEnabled) { + if (!InstantController::IsEnabled(profile())) { + if (instant()) { + instant()->DestroyPreviewContents(); + instant_.reset(); + instant_unload_handler_.reset(); + } + } else { + CreateInstantIfNecessary(); + } + } else if (pref_name == prefs::kDevToolsDisabled) { + UpdateCommandsForDevTools(); + if (dev_tools_disabled_.GetValue()) + g_browser_process->devtools_manager()->CloseAllClientHosts(); + } else { + NOTREACHED(); + } + break; + } + + default: + NOTREACHED() << ""Got a notification we didn't register for.""; + } +} +","@@ -2847,7 +2847,7 @@ void Browser::CloseContents(TabContents* source) { + // waiting for unload to fire. Don't actually try to close the tab as it + // will go down the slow shutdown path instead of the fast path of killing + // all the renderer processes. +- ClearUnloadState(source); ++ ClearUnloadState(source, true); + return; + } + +@@ -3208,12 +3208,10 @@ void Browser::Observe(NotificationType type, + switch (type.value) { + case NotificationType::TAB_CONTENTS_DISCONNECTED: + if (is_attempting_to_close_browser_) { +- // Need to do this asynchronously as it will close the tab, which is +- // currently on the call stack above us. +- MessageLoop::current()->PostTask( +- FROM_HERE, +- method_factory_.NewRunnableMethod(&Browser::ClearUnloadState, +- Source(source).ptr())); ++ // Pass in false so that we delay processing. We need to delay the ++ // processing as it may close the tab, which is currently on the call ++ // stack above us. ++ ClearUnloadState(Source(source).ptr(), false); + } + break; + +@@ -3852,7 +3850,12 @@ void Browser::SyncHistoryWithTabs(int index) { + // Browser, OnBeforeUnload handling (private): + + void Browser::ProcessPendingTabs() { +- DCHECK(is_attempting_to_close_browser_); ++ if (!is_attempting_to_close_browser_) { ++ // Because we might invoke this after a delay it's possible for the value of ++ // is_attempting_to_close_browser_ to have changed since we scheduled the ++ // task. ++ return; ++ } + + if (HasCompletedUnloadProcessing()) { + // We've finished all the unload events and can proceed to close the +@@ -3870,7 +3873,7 @@ void Browser::ProcessPendingTabs() { + if (tab->render_view_host()) { + tab->render_view_host()->FirePageBeforeUnload(false); + } else { +- ClearUnloadState(tab); ++ ClearUnloadState(tab, true); + } + } else if (!tabs_needing_unload_fired_.empty()) { + // We've finished firing all beforeunload events and can proceed with unload +@@ -3887,7 +3890,7 @@ void Browser::ProcessPendingTabs() { + if (tab->render_view_host()) { + tab->render_view_host()->ClosePage(false, -1, -1); + } else { +- ClearUnloadState(tab); ++ ClearUnloadState(tab, true); + } + } else { + NOTREACHED(); +@@ -3927,18 +3930,23 @@ bool Browser::RemoveFromSet(UnloadListenerSet* set, TabContents* tab) { + return false; + } + +-void Browser::ClearUnloadState(TabContents* tab) { ++void Browser::ClearUnloadState(TabContents* tab, bool process_now) { + // Closing of browser could be canceled (via IsClosingPermitted) between the + // time when request was initiated and when this method is called, so check + // for is_attempting_to_close_browser_ flag before proceeding. + if (is_attempting_to_close_browser_) { + RemoveFromSet(&tabs_needing_before_unload_fired_, tab); + RemoveFromSet(&tabs_needing_unload_fired_, tab); +- ProcessPendingTabs(); ++ if (process_now) { ++ ProcessPendingTabs(); ++ } else { ++ MessageLoop::current()->PostTask( ++ FROM_HERE, ++ method_factory_.NewRunnableMethod(&Browser::ProcessPendingTabs)); ++ } + } + } + +- + /////////////////////////////////////////////////////////////////////////////// + // Browser, In-progress download termination handling (private): + +@@ -4097,6 +4105,14 @@ void Browser::TabDetachedAtImpl(TabContentsWrapper* contents, int index, + find_bar_controller_->ChangeTabContents(NULL); + } + ++ if (is_attempting_to_close_browser_) { ++ // If this is the last tab with unload handlers, then ProcessPendingTabs ++ // would call back into the TabStripModel (which is invoking this method on ++ // us). Avoid that by passing in false so that the call to ++ // ProcessPendingTabs is delayed. ++ ClearUnloadState(contents->tab_contents(), false); ++ } ++ + registrar_.Remove(this, NotificationType::TAB_CONTENTS_DISCONNECTED, + Source(contents)); + }",1064,1395,2048 +1118,"int ssl3_check_cert_and_algorithm(SSL *s) + { + int i,idx; + long alg_k,alg_a; + EVP_PKEY *pkey=NULL; + SESS_CERT *sc; +#ifndef OPENSSL_NO_RSA + RSA *rsa; +#endif +#ifndef OPENSSL_NO_DH + DH *dh; +#endif + + alg_k=s->s3->tmp.new_cipher->algorithm_mkey; + alg_a=s->s3->tmp.new_cipher->algorithm_auth; + + /* we don't have a certificate */ + if ((alg_a & (SSL_aDH|SSL_aNULL|SSL_aKRB5)) || (alg_k & SSL_kPSK)) + return(1); + + sc=s->session->sess_cert; + if (sc == NULL) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,ERR_R_INTERNAL_ERROR); + goto err; + } + +#ifndef OPENSSL_NO_RSA + rsa=s->session->sess_cert->peer_rsa_tmp; +#endif +#ifndef OPENSSL_NO_DH + dh=s->session->sess_cert->peer_dh_tmp; +#endif + + /* This is the passed certificate */ + + idx=sc->peer_cert_type; +#ifndef OPENSSL_NO_ECDH + if (idx == SSL_PKEY_ECC) + { + if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509, + s) == 0) + { /* check failed */ + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_BAD_ECC_CERT); + goto f_err; + } + else + { + return 1; + } + } +#endif + pkey=X509_get_pubkey(sc->peer_pkeys[idx].x509); + i=X509_certificate_type(sc->peer_pkeys[idx].x509,pkey); + EVP_PKEY_free(pkey); + + + /* Check that we have a certificate if we require one */ + if ((alg_a & SSL_aRSA) && !has_bits(i,EVP_PK_RSA|EVP_PKT_SIGN)) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_SIGNING_CERT); + goto f_err; + } +#ifndef OPENSSL_NO_DSA + else if ((alg_a & SSL_aDSS) && !has_bits(i,EVP_PK_DSA|EVP_PKT_SIGN)) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DSA_SIGNING_CERT); + goto f_err; + } +#endif +#ifndef OPENSSL_NO_RSA + if ((alg_k & SSL_kRSA) && + !(has_bits(i,EVP_PK_RSA|EVP_PKT_ENC) || (rsa != NULL))) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_ENCRYPTING_CERT); + goto f_err; + } +#endif +#ifndef OPENSSL_NO_DH + if ((alg_k & SSL_kEDH) && + !(has_bits(i,EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL))) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_KEY); + goto f_err; + } + else if ((alg_k & SSL_kDHr) && !has_bits(i,EVP_PK_DH|EVP_PKS_RSA)) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_RSA_CERT); + goto f_err; + } +#ifndef OPENSSL_NO_DSA + else if ((alg_k & SSL_kDHd) && !has_bits(i,EVP_PK_DH|EVP_PKS_DSA)) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_DSA_CERT); + goto f_err; + } +#endif +#endif + + if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && !has_bits(i,EVP_PKT_EXP)) + { +#ifndef OPENSSL_NO_RSA + if (alg_k & SSL_kRSA) + { + if (rsa == NULL + || RSA_size(rsa)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_RSA_KEY); + goto f_err; + } + } + else +#endif +#ifndef OPENSSL_NO_DH + if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd)) + { + if (dh == NULL + || DH_size(dh)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_DH_KEY); + goto f_err; + } + } + else +#endif + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE); + goto f_err; + } + } + return(1); +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); +err: + return(0); + } +",0,"int ssl3_check_cert_and_algorithm(SSL *s) + { + int i,idx; + long alg_k,alg_a; + EVP_PKEY *pkey=NULL; + SESS_CERT *sc; +#ifndef OPENSSL_NO_RSA + RSA *rsa; +#endif +#ifndef OPENSSL_NO_DH + DH *dh; +#endif + + alg_k=s->s3->tmp.new_cipher->algorithm_mkey; + alg_a=s->s3->tmp.new_cipher->algorithm_auth; + + /* we don't have a certificate */ + if ((alg_a & (SSL_aDH|SSL_aNULL|SSL_aKRB5)) || (alg_k & SSL_kPSK)) + return(1); + + sc=s->session->sess_cert; + if (sc == NULL) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,ERR_R_INTERNAL_ERROR); + goto err; + } + +#ifndef OPENSSL_NO_RSA + rsa=s->session->sess_cert->peer_rsa_tmp; +#endif +#ifndef OPENSSL_NO_DH + dh=s->session->sess_cert->peer_dh_tmp; +#endif + + /* This is the passed certificate */ + + idx=sc->peer_cert_type; +#ifndef OPENSSL_NO_ECDH + if (idx == SSL_PKEY_ECC) + { + if (ssl_check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509, + s) == 0) + { /* check failed */ + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_BAD_ECC_CERT); + goto f_err; + } + else + { + return 1; + } + } +#endif + pkey=X509_get_pubkey(sc->peer_pkeys[idx].x509); + i=X509_certificate_type(sc->peer_pkeys[idx].x509,pkey); + EVP_PKEY_free(pkey); + + + /* Check that we have a certificate if we require one */ + if ((alg_a & SSL_aRSA) && !has_bits(i,EVP_PK_RSA|EVP_PKT_SIGN)) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_SIGNING_CERT); + goto f_err; + } +#ifndef OPENSSL_NO_DSA + else if ((alg_a & SSL_aDSS) && !has_bits(i,EVP_PK_DSA|EVP_PKT_SIGN)) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DSA_SIGNING_CERT); + goto f_err; + } +#endif +#ifndef OPENSSL_NO_RSA + if ((alg_k & SSL_kRSA) && + !(has_bits(i,EVP_PK_RSA|EVP_PKT_ENC) || (rsa != NULL))) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_ENCRYPTING_CERT); + goto f_err; + } +#endif +#ifndef OPENSSL_NO_DH + if ((alg_k & SSL_kEDH) && + !(has_bits(i,EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL))) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_KEY); + goto f_err; + } + else if ((alg_k & SSL_kDHr) && !has_bits(i,EVP_PK_DH|EVP_PKS_RSA)) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_RSA_CERT); + goto f_err; + } +#ifndef OPENSSL_NO_DSA + else if ((alg_k & SSL_kDHd) && !has_bits(i,EVP_PK_DH|EVP_PKS_DSA)) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_DSA_CERT); + goto f_err; + } +#endif +#endif + + if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && !has_bits(i,EVP_PKT_EXP)) + { +#ifndef OPENSSL_NO_RSA + if (alg_k & SSL_kRSA) + { + if (rsa == NULL + || RSA_size(rsa)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_RSA_KEY); + goto f_err; + } + } + else +#endif +#ifndef OPENSSL_NO_DH + if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd)) + { + if (dh == NULL + || DH_size(dh)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)) + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_DH_KEY); + goto f_err; + } + } + else +#endif + { + SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE); + goto f_err; + } + } + return(1); +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); +err: + return(0); + } +","@@ -954,6 +954,15 @@ int ssl3_get_server_hello(SSL *s) + SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED); + goto f_err; + } ++#ifndef OPENSSL_NO_SRP ++ if (((c->algorithm_mkey & SSL_kSRP) || (c->algorithm_auth & SSL_aSRP)) && ++ !(s->srp_ctx.srp_Mask & SSL_kSRP)) ++ { ++ al=SSL_AD_ILLEGAL_PARAMETER; ++ SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED); ++ goto f_err; ++ } ++#endif /* OPENSSL_NO_SRP */ + p+=ssl_put_cipher_by_char(s,NULL,NULL); + + sk=ssl_get_ciphers_by_id(s);",1123,1454,2048 +18295,"static int dccp_print_option(netdissect_options *ndo, const u_char *option, u_int hlen) + { + uint8_t optlen, i; + + ND_TCHECK(*option); + + if (*option >= 32) { + ND_TCHECK(*(option+1)); + optlen = *(option +1); + if (optlen < 2) { + if (*option >= 128) + ND_PRINT((ndo, ""CCID option %u optlen too short"", *option)); + else + ND_PRINT((ndo, ""%s optlen too short"", + tok2str(dccp_option_values, ""Option %u"", *option))); + return 0; + } + } else + optlen = 1; + + if (hlen < optlen) { + if (*option >= 128) + ND_PRINT((ndo, ""CCID option %u optlen goes past header length"", + *option)); + else + ND_PRINT((ndo, ""%s optlen goes past header length"", + tok2str(dccp_option_values, ""Option %u"", *option))); + return 0; + } + ND_TCHECK2(*option, optlen); + + if (*option >= 128) { + ND_PRINT((ndo, ""CCID option %d"", *option)); + switch (optlen) { + case 4: + ND_PRINT((ndo, "" %u"", EXTRACT_16BITS(option + 2))); + break; + case 6: + ND_PRINT((ndo, "" %u"", EXTRACT_32BITS(option + 2))); + break; + default: + break; + } + } else { + ND_PRINT((ndo, ""%s"", tok2str(dccp_option_values, ""Option %u"", *option))); + switch (*option) { + case 32: + case 33: + case 34: + case 35: + if (optlen < 3) { + ND_PRINT((ndo, "" optlen too short"")); + return optlen; + } + if (*(option + 2) < 10){ + ND_PRINT((ndo, "" %s"", dccp_feature_nums[*(option + 2)])); + for (i = 0; i < optlen - 3; i++) + ND_PRINT((ndo, "" %d"", *(option + 3 + i))); + } + break; + case 36: + if (optlen > 2) { + ND_PRINT((ndo, "" 0x"")); + for (i = 0; i < optlen - 2; i++) + ND_PRINT((ndo, ""%02x"", *(option + 2 + i))); + } + break; + case 37: + for (i = 0; i < optlen - 2; i++) + ND_PRINT((ndo, "" %d"", *(option + 2 + i))); + break; + case 38: + if (optlen > 2) { + ND_PRINT((ndo, "" 0x"")); + for (i = 0; i < optlen - 2; i++) + ND_PRINT((ndo, ""%02x"", *(option + 2 + i))); + } + break; + case 39: + if (optlen > 2) { + ND_PRINT((ndo, "" 0x"")); + for (i = 0; i < optlen - 2; i++) + ND_PRINT((ndo, ""%02x"", *(option + 2 + i))); + } + break; + case 40: + if (optlen > 2) { + ND_PRINT((ndo, "" 0x"")); + for (i = 0; i < optlen - 2; i++) + ND_PRINT((ndo, ""%02x"", *(option + 2 + i))); + } + break; + case 41: + if (optlen == 4) + ND_PRINT((ndo, "" %u"", EXTRACT_32BITS(option + 2))); + else + ND_PRINT((ndo, "" optlen != 4"")); + break; + case 42: + if (optlen == 4) + ND_PRINT((ndo, "" %u"", EXTRACT_32BITS(option + 2))); + else + ND_PRINT((ndo, "" optlen != 4"")); + break; + case 43: + if (optlen == 6) + ND_PRINT((ndo, "" %u"", EXTRACT_32BITS(option + 2))); + else if (optlen == 4) + ND_PRINT((ndo, "" %u"", EXTRACT_16BITS(option + 2))); + else + ND_PRINT((ndo, "" optlen != 4 or 6"")); + break; + case 44: + if (optlen > 2) { + ND_PRINT((ndo, "" "")); + for (i = 0; i < optlen - 2; i++) + ND_PRINT((ndo, ""%02x"", *(option + 2 + i))); + } + break; + } + } + + return optlen; +trunc: + ND_PRINT((ndo, ""%s"", tstr)); + return 0; +} +",1,"static int dccp_print_option(netdissect_options *ndo, const u_char *option, u_int hlen) +static int +dccp_print_option(netdissect_options *ndo, const u_char *option, u_int hlen) + { + uint8_t optlen, i; + + ND_TCHECK(*option); + + if (*option >= 32) { + ND_TCHECK(*(option+1)); + optlen = *(option +1); + if (optlen < 2) { + if (*option >= 128) + ND_PRINT((ndo, ""CCID option %u optlen too short"", *option)); + else + ND_PRINT((ndo, ""%s optlen too short"", + tok2str(dccp_option_values, ""Option %u"", *option))); + return 0; + } + } else + optlen = 1; + + if (hlen < optlen) { + if (*option >= 128) + ND_PRINT((ndo, ""CCID option %u optlen goes past header length"", + *option)); + else + ND_PRINT((ndo, ""%s optlen goes past header length"", + tok2str(dccp_option_values, ""Option %u"", *option))); + return 0; + } + ND_TCHECK2(*option, optlen); + + if (*option >= 128) { + ND_PRINT((ndo, ""CCID option %d"", *option)); + switch (optlen) { + case 4: + ND_PRINT((ndo, "" %u"", EXTRACT_16BITS(option + 2))); + break; + case 6: + ND_PRINT((ndo, "" %u"", EXTRACT_32BITS(option + 2))); + break; + default: + break; + } + } else { + ND_PRINT((ndo, ""%s"", tok2str(dccp_option_values, ""Option %u"", *option))); + switch (*option) { + case 32: + case 33: + case 34: + case 35: + if (optlen < 3) { + ND_PRINT((ndo, "" optlen too short"")); + return optlen; + } + if (*(option + 2) < 10){ + ND_PRINT((ndo, "" %s"", dccp_feature_nums[*(option + 2)])); + for (i = 0; i < optlen - 3; i++) + ND_PRINT((ndo, "" %d"", *(option + 3 + i))); + } + break; + case 36: + if (optlen > 2) { + ND_PRINT((ndo, "" 0x"")); + for (i = 0; i < optlen - 2; i++) + ND_PRINT((ndo, ""%02x"", *(option + 2 + i))); + } + break; + case 37: + for (i = 0; i < optlen - 2; i++) + ND_PRINT((ndo, "" %d"", *(option + 2 + i))); + break; + case 38: + if (optlen > 2) { + ND_PRINT((ndo, "" 0x"")); + for (i = 0; i < optlen - 2; i++) + ND_PRINT((ndo, ""%02x"", *(option + 2 + i))); + } + break; + case 39: + if (optlen > 2) { + ND_PRINT((ndo, "" 0x"")); + for (i = 0; i < optlen - 2; i++) + ND_PRINT((ndo, ""%02x"", *(option + 2 + i))); + } + break; + case 40: + if (optlen > 2) { + ND_PRINT((ndo, "" 0x"")); + for (i = 0; i < optlen - 2; i++) + ND_PRINT((ndo, ""%02x"", *(option + 2 + i))); + } + break; + case 41: + /* + * 13.1. Timestamp Option + * + * +--------+--------+--------+--------+--------+--------+ + * |00101001|00000110| Timestamp Value | + * +--------+--------+--------+--------+--------+--------+ + * Type=41 Length=6 + */ + if (optlen == 6) + ND_PRINT((ndo, "" %u"", EXTRACT_32BITS(option + 2))); + else + ND_PRINT((ndo, "" [optlen != 6]"")); + break; + case 42: + /* + * 13.3. Timestamp Echo Option + * + * +--------+--------+--------+--------+--------+--------+ + * |00101010|00000110| Timestamp Echo | + * +--------+--------+--------+--------+--------+--------+ + * Type=42 Len=6 + * + * +--------+--------+------- ... -------+--------+--------+ + * |00101010|00001000| Timestamp Echo | Elapsed Time | + * +--------+--------+------- ... -------+--------+--------+ + * Type=42 Len=8 (4 bytes) + * + * +--------+--------+------- ... -------+------- ... -------+ + * |00101010|00001010| Timestamp Echo | Elapsed Time | + * +--------+--------+------- ... -------+------- ... -------+ + * Type=42 Len=10 (4 bytes) (4 bytes) + */ + switch (optlen) { + case 6: + ND_PRINT((ndo, "" %u"", EXTRACT_32BITS(option + 2))); + break; + case 8: + ND_PRINT((ndo, "" %u"", EXTRACT_32BITS(option + 2))); + ND_PRINT((ndo, "" (elapsed time %u)"", EXTRACT_16BITS(option + 6))); + break; + case 10: + ND_PRINT((ndo, "" %u"", EXTRACT_32BITS(option + 2))); + ND_PRINT((ndo, "" (elapsed time %u)"", EXTRACT_32BITS(option + 6))); + break; + default: + ND_PRINT((ndo, "" [optlen != 6 or 8 or 10]"")); + break; + } + break; + case 43: + if (optlen == 6) + ND_PRINT((ndo, "" %u"", EXTRACT_32BITS(option + 2))); + else if (optlen == 4) + ND_PRINT((ndo, "" %u"", EXTRACT_16BITS(option + 2))); + else + ND_PRINT((ndo, "" [optlen != 4 or 6]"")); + break; + case 44: + if (optlen > 2) { + ND_PRINT((ndo, "" "")); + for (i = 0; i < optlen - 2; i++) + ND_PRINT((ndo, ""%02x"", *(option + 2 + i))); + } + break; + } + } + + return optlen; +trunc: + ND_PRINT((ndo, ""%s"", tstr)); + return 0; +} +","@@ -530,7 +530,8 @@ static const struct tok dccp_option_values[] = { + { 0, NULL } + }; + +-static int dccp_print_option(netdissect_options *ndo, const u_char *option, u_int hlen) ++static int ++dccp_print_option(netdissect_options *ndo, const u_char *option, u_int hlen) + { + uint8_t optlen, i; + +@@ -623,24 +624,62 @@ static int dccp_print_option(netdissect_options *ndo, const u_char *option, u_in + } + break; + case 41: +- if (optlen == 4) ++ /* ++ * 13.1. Timestamp Option ++ * ++ * +--------+--------+--------+--------+--------+--------+ ++ * |00101001|00000110| Timestamp Value | ++ * +--------+--------+--------+--------+--------+--------+ ++ * Type=41 Length=6 ++ */ ++ if (optlen == 6) + ND_PRINT((ndo, "" %u"", EXTRACT_32BITS(option + 2))); + else +- ND_PRINT((ndo, "" optlen != 4"")); ++ ND_PRINT((ndo, "" [optlen != 6]"")); + break; + case 42: +- if (optlen == 4) ++ /* ++ * 13.3. Timestamp Echo Option ++ * ++ * +--------+--------+--------+--------+--------+--------+ ++ * |00101010|00000110| Timestamp Echo | ++ * +--------+--------+--------+--------+--------+--------+ ++ * Type=42 Len=6 ++ * ++ * +--------+--------+------- ... -------+--------+--------+ ++ * |00101010|00001000| Timestamp Echo | Elapsed Time | ++ * +--------+--------+------- ... -------+--------+--------+ ++ * Type=42 Len=8 (4 bytes) ++ * ++ * +--------+--------+------- ... -------+------- ... -------+ ++ * |00101010|00001010| Timestamp Echo | Elapsed Time | ++ * +--------+--------+------- ... -------+------- ... -------+ ++ * Type=42 Len=10 (4 bytes) (4 bytes) ++ */ ++ switch (optlen) { ++ case 6: + ND_PRINT((ndo, "" %u"", EXTRACT_32BITS(option + 2))); +- else +- ND_PRINT((ndo, "" optlen != 4"")); ++ break; ++ case 8: ++ ND_PRINT((ndo, "" %u"", EXTRACT_32BITS(option + 2))); ++ ND_PRINT((ndo, "" (elapsed time %u)"", EXTRACT_16BITS(option + 6))); ++ break; ++ case 10: ++ ND_PRINT((ndo, "" %u"", EXTRACT_32BITS(option + 2))); ++ ND_PRINT((ndo, "" (elapsed time %u)"", EXTRACT_32BITS(option + 6))); ++ break; ++ default: ++ ND_PRINT((ndo, "" [optlen != 6 or 8 or 10]"")); ++ break; ++ } + break; + case 43: + if (optlen == 6) + ND_PRINT((ndo, "" %u"", EXTRACT_32BITS(option + 2))); + else if (optlen == 4) + ND_PRINT((ndo, "" %u"", EXTRACT_16BITS(option + 2))); + else +- ND_PRINT((ndo, "" optlen != 4 or 6"")); ++ ND_PRINT((ndo, "" [optlen != 4 or 6]"")); + break; + case 44: + if (optlen > 2) {",1175,1506,2048 +18424,"xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) { + xmlChar limit = 0; + xmlChar *buf = NULL; + xmlChar *rep = NULL; + int len = 0; + int buf_size = 0; + int c, l, in_space = 0; + xmlChar *current = NULL; + xmlEntityPtr ent; + + if (NXT(0) == '""') { + ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; + limit = '""'; + NEXT; + } else if (NXT(0) == '\'') { + limit = '\''; + ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; + NEXT; + } else { + xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL); + return(NULL); + } + + /* + * allocate a translation buffer. + */ + buf_size = XML_PARSER_BUFFER_SIZE; + buf = (xmlChar *) xmlMallocAtomic(buf_size * sizeof(xmlChar)); + if (buf == NULL) goto mem_error; + + /* + * OK loop until we reach one of the ending char or a size limit. + */ + c = CUR_CHAR(l); + while ((NXT(0) != limit) && /* checked */ + (IS_CHAR(c)) && (c != '<')) { + if (c == 0) break; + if (c == '&') { + in_space = 0; + if (NXT(1) == '#') { + int val = xmlParseCharRef(ctxt); + + if (val == '&') { + if (ctxt->replaceEntities) { + if (len > buf_size - 10) { + growBuffer(buf, 10); + } + buf[len++] = '&'; + } else { + /* + * The reparsing will be done in xmlStringGetNodeList() + * called by the attribute() function in SAX.c + */ + if (len > buf_size - 10) { + growBuffer(buf, 10); + } + buf[len++] = '&'; + buf[len++] = '#'; + buf[len++] = '3'; + buf[len++] = '8'; + buf[len++] = ';'; + } + } else if (val != 0) { + if (len > buf_size - 10) { + growBuffer(buf, 10); + } + len += xmlCopyChar(0, &buf[len], val); + } + } else { + ent = xmlParseEntityRef(ctxt); + ctxt->nbentities++; + if (ent != NULL) + ctxt->nbentities += ent->owner; + if ((ent != NULL) && + (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { + if (len > buf_size - 10) { + growBuffer(buf, 10); + } + if ((ctxt->replaceEntities == 0) && + (ent->content[0] == '&')) { + buf[len++] = '&'; + buf[len++] = '#'; + buf[len++] = '3'; + buf[len++] = '8'; + buf[len++] = ';'; + } else { + buf[len++] = ent->content[0]; + } + } else if ((ent != NULL) && + (ctxt->replaceEntities != 0)) { + if (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) { + rep = xmlStringDecodeEntities(ctxt, ent->content, + XML_SUBSTITUTE_REF, + 0, 0, 0); + if (rep != NULL) { + current = rep; + while (*current != 0) { /* non input consuming */ + if ((*current == 0xD) || (*current == 0xA) || + (*current == 0x9)) { + buf[len++] = 0x20; + current++; + } else + buf[len++] = *current++; + if (len > buf_size - 10) { + growBuffer(buf, 10); + } + } + xmlFree(rep); + rep = NULL; + } + } else { + if (len > buf_size - 10) { + growBuffer(buf, 10); + } + if (ent->content != NULL) + buf[len++] = ent->content[0]; + } + } else if (ent != NULL) { + int i = xmlStrlen(ent->name); + const xmlChar *cur = ent->name; + + /* + * This may look absurd but is needed to detect + * entities problems + */ + if ((ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) && + (ent->content != NULL)) { + rep = xmlStringDecodeEntities(ctxt, ent->content, + XML_SUBSTITUTE_REF, 0, 0, 0); + if (rep != NULL) { + xmlFree(rep); + rep = NULL; + } + } + + /* + * Just output the reference + */ + buf[len++] = '&'; + while (len > buf_size - i - 10) { + growBuffer(buf, i + 10); + } + for (;i > 0;i--) + buf[len++] = *cur++; + buf[len++] = ';'; + } + } + } else { + if ((c == 0x20) || (c == 0xD) || (c == 0xA) || (c == 0x9)) { + if ((len != 0) || (!normalize)) { + if ((!normalize) || (!in_space)) { + COPY_BUF(l,buf,len,0x20); + while (len > buf_size - 10) { + growBuffer(buf, 10); + } + } + in_space = 1; + } + } else { + in_space = 0; + COPY_BUF(l,buf,len,c); + if (len > buf_size - 10) { + growBuffer(buf, 10); + } + } + NEXTL(l); + } + GROW; + c = CUR_CHAR(l); + } + if ((in_space) && (normalize)) { + while (buf[len - 1] == 0x20) len--; + } + buf[len] = 0; + if (RAW == '<') { + xmlFatalErr(ctxt, XML_ERR_LT_IN_ATTRIBUTE, NULL); + } else if (RAW != limit) { + if ((c != 0) && (!IS_CHAR(c))) { + xmlFatalErrMsg(ctxt, XML_ERR_INVALID_CHAR, + ""invalid character in attribute value\n""); + } else { + xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, + ""AttValue: ' expected\n""); + } + } else + NEXT; + if (attlen != NULL) *attlen = len; + return(buf); + +mem_error: + xmlErrMemory(ctxt, NULL); + if (buf != NULL) + xmlFree(buf); + if (rep != NULL) + xmlFree(rep); + return(NULL); +} +",1,"xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) { + xmlChar limit = 0; + xmlChar *buf = NULL; + xmlChar *rep = NULL; + int len = 0; + int buf_size = 0; + int c, l, in_space = 0; + xmlChar *current = NULL; + xmlEntityPtr ent; + + if (NXT(0) == '""') { + ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; + limit = '""'; + NEXT; + } else if (NXT(0) == '\'') { + limit = '\''; + ctxt->instate = XML_PARSER_ATTRIBUTE_VALUE; + NEXT; + } else { + xmlFatalErr(ctxt, XML_ERR_ATTRIBUTE_NOT_STARTED, NULL); + return(NULL); + } + + /* + * allocate a translation buffer. + */ + buf_size = XML_PARSER_BUFFER_SIZE; + buf = (xmlChar *) xmlMallocAtomic(buf_size * sizeof(xmlChar)); + if (buf == NULL) goto mem_error; + + /* + * OK loop until we reach one of the ending char or a size limit. + */ + c = CUR_CHAR(l); + while ((NXT(0) != limit) && /* checked */ + (IS_CHAR(c)) && (c != '<')) { + if (c == 0) break; + if (c == '&') { + in_space = 0; + if (NXT(1) == '#') { + int val = xmlParseCharRef(ctxt); + + if (val == '&') { + if (ctxt->replaceEntities) { + if (len > buf_size - 10) { + growBuffer(buf, 10); + } + buf[len++] = '&'; + } else { + /* + * The reparsing will be done in xmlStringGetNodeList() + * called by the attribute() function in SAX.c + */ + if (len > buf_size - 10) { + growBuffer(buf, 10); + } + buf[len++] = '&'; + buf[len++] = '#'; + buf[len++] = '3'; + buf[len++] = '8'; + buf[len++] = ';'; + } + } else if (val != 0) { + if (len > buf_size - 10) { + growBuffer(buf, 10); + } + len += xmlCopyChar(0, &buf[len], val); + } + } else { + ent = xmlParseEntityRef(ctxt); + ctxt->nbentities++; + if (ent != NULL) + ctxt->nbentities += ent->owner; + if ((ent != NULL) && + (ent->etype == XML_INTERNAL_PREDEFINED_ENTITY)) { + if (len > buf_size - 10) { + growBuffer(buf, 10); + } + if ((ctxt->replaceEntities == 0) && + (ent->content[0] == '&')) { + buf[len++] = '&'; + buf[len++] = '#'; + buf[len++] = '3'; + buf[len++] = '8'; + buf[len++] = ';'; + } else { + buf[len++] = ent->content[0]; + } + } else if ((ent != NULL) && + (ctxt->replaceEntities != 0)) { + if (ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) { + rep = xmlStringDecodeEntities(ctxt, ent->content, + XML_SUBSTITUTE_REF, + 0, 0, 0); + if (rep != NULL) { + current = rep; + while (*current != 0) { /* non input consuming */ + if ((*current == 0xD) || (*current == 0xA) || + (*current == 0x9)) { + buf[len++] = 0x20; + current++; + } else + buf[len++] = *current++; + if (len > buf_size - 10) { + growBuffer(buf, 10); + } + } + xmlFree(rep); + rep = NULL; + } + } else { + if (len > buf_size - 10) { + growBuffer(buf, 10); + } + if (ent->content != NULL) + buf[len++] = ent->content[0]; + } + } else if (ent != NULL) { + int i = xmlStrlen(ent->name); + const xmlChar *cur = ent->name; + + /* + * This may look absurd but is needed to detect + * entities problems + */ + if ((ent->etype != XML_INTERNAL_PREDEFINED_ENTITY) && + (ent->content != NULL)) { + rep = xmlStringDecodeEntities(ctxt, ent->content, + XML_SUBSTITUTE_REF, 0, 0, 0); + if (rep != NULL) { + xmlFree(rep); + rep = NULL; + } + } + + /* + * Just output the reference + */ + buf[len++] = '&'; + while (len > buf_size - i - 10) { + growBuffer(buf, i + 10); + } + for (;i > 0;i--) + buf[len++] = *cur++; + buf[len++] = ';'; + } + } + } else { + if ((c == 0x20) || (c == 0xD) || (c == 0xA) || (c == 0x9)) { + if ((len != 0) || (!normalize)) { + if ((!normalize) || (!in_space)) { + COPY_BUF(l,buf,len,0x20); + while (len > buf_size - 10) { + growBuffer(buf, 10); + } + } + in_space = 1; + } + } else { + in_space = 0; + COPY_BUF(l,buf,len,c); + if (len > buf_size - 10) { + growBuffer(buf, 10); + } + } + NEXTL(l); + } + GROW; + c = CUR_CHAR(l); + } + if ((in_space) && (normalize)) { + while ((len > 0) && (buf[len - 1] == 0x20)) len--; + } + buf[len] = 0; + if (RAW == '<') { + xmlFatalErr(ctxt, XML_ERR_LT_IN_ATTRIBUTE, NULL); + } else if (RAW != limit) { + if ((c != 0) && (!IS_CHAR(c))) { + xmlFatalErrMsg(ctxt, XML_ERR_INVALID_CHAR, + ""invalid character in attribute value\n""); + } else { + xmlFatalErrMsg(ctxt, XML_ERR_ATTRIBUTE_NOT_FINISHED, + ""AttValue: ' expected\n""); + } + } else + NEXT; + if (attlen != NULL) *attlen = len; + return(buf); + +mem_error: + xmlErrMemory(ctxt, NULL); + if (buf != NULL) + xmlFree(buf); + if (rep != NULL) + xmlFree(rep); + return(NULL); +} +","@@ -3800,7 +3800,7 @@ xmlParseAttValueComplex(xmlParserCtxtPtr ctxt, int *attlen, int normalize) { + c = CUR_CHAR(l); + } + if ((in_space) && (normalize)) { +- while (buf[len - 1] == 0x20) len--; ++ while ((len > 0) && (buf[len - 1] == 0x20)) len--; + } + buf[len] = 0; + if (RAW == '<') {",1518,1849,2048 +3222,"static sctp_disposition_t sctp_sf_do_dupcook_a(struct net *net, + const struct sctp_endpoint *ep, + const struct sctp_association *asoc, + struct sctp_chunk *chunk, + sctp_cmd_seq_t *commands, + struct sctp_association *new_asoc) +{ + sctp_init_chunk_t *peer_init; + struct sctp_ulpevent *ev; + struct sctp_chunk *repl; + struct sctp_chunk *err; + sctp_disposition_t disposition; + + /* new_asoc is a brand-new association, so these are not yet + * side effects--it is safe to run them here. + */ + peer_init = &chunk->subh.cookie_hdr->c.peer_init[0]; + + if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk), peer_init, + GFP_ATOMIC)) + goto nomem; + + /* Make sure no new addresses are being added during the + * restart. Though this is a pretty complicated attack + * since you'd have to get inside the cookie. + */ + if (!sctp_sf_check_restart_addrs(new_asoc, asoc, chunk, commands)) { + return SCTP_DISPOSITION_CONSUME; + } + + /* If the endpoint is in the SHUTDOWN-ACK-SENT state and recognizes + * the peer has restarted (Action A), it MUST NOT setup a new + * association but instead resend the SHUTDOWN ACK and send an ERROR + * chunk with a ""Cookie Received while Shutting Down"" error cause to + * its peer. + */ + if (sctp_state(asoc, SHUTDOWN_ACK_SENT)) { + disposition = sctp_sf_do_9_2_reshutack(net, ep, asoc, + SCTP_ST_CHUNK(chunk->chunk_hdr->type), + chunk, commands); + if (SCTP_DISPOSITION_NOMEM == disposition) + goto nomem; + + err = sctp_make_op_error(asoc, chunk, + SCTP_ERROR_COOKIE_IN_SHUTDOWN, + NULL, 0, 0); + if (err) + sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, + SCTP_CHUNK(err)); + + return SCTP_DISPOSITION_CONSUME; + } + + /* For now, stop pending T3-rtx and SACK timers, fail any unsent/unacked + * data. Consider the optional choice of resending of this data. + */ + sctp_add_cmd_sf(commands, SCTP_CMD_T3_RTX_TIMERS_STOP, SCTP_NULL()); + sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, + SCTP_TO(SCTP_EVENT_TIMEOUT_SACK)); + sctp_add_cmd_sf(commands, SCTP_CMD_PURGE_OUTQUEUE, SCTP_NULL()); + + /* Stop pending T4-rto timer, teardown ASCONF queue, ASCONF-ACK queue + * and ASCONF-ACK cache. + */ + sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, + SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO)); + sctp_add_cmd_sf(commands, SCTP_CMD_PURGE_ASCONF_QUEUE, SCTP_NULL()); + + repl = sctp_make_cookie_ack(new_asoc, chunk); + if (!repl) + goto nomem; + + /* Report association restart to upper layer. */ + ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_RESTART, 0, + new_asoc->c.sinit_num_ostreams, + new_asoc->c.sinit_max_instreams, + NULL, GFP_ATOMIC); + if (!ev) + goto nomem_ev; + + /* Update the content of current association. */ + sctp_add_cmd_sf(commands, SCTP_CMD_UPDATE_ASSOC, SCTP_ASOC(new_asoc)); + sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev)); + sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, + SCTP_STATE(SCTP_STATE_ESTABLISHED)); + sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl)); + return SCTP_DISPOSITION_CONSUME; + +nomem_ev: + sctp_chunk_free(repl); +nomem: + return SCTP_DISPOSITION_NOMEM; +} +",0,"static sctp_disposition_t sctp_sf_do_dupcook_a(struct net *net, + const struct sctp_endpoint *ep, + const struct sctp_association *asoc, + struct sctp_chunk *chunk, + sctp_cmd_seq_t *commands, + struct sctp_association *new_asoc) +{ + sctp_init_chunk_t *peer_init; + struct sctp_ulpevent *ev; + struct sctp_chunk *repl; + struct sctp_chunk *err; + sctp_disposition_t disposition; + + /* new_asoc is a brand-new association, so these are not yet + * side effects--it is safe to run them here. + */ + peer_init = &chunk->subh.cookie_hdr->c.peer_init[0]; + + if (!sctp_process_init(new_asoc, chunk, sctp_source(chunk), peer_init, + GFP_ATOMIC)) + goto nomem; + + /* Make sure no new addresses are being added during the + * restart. Though this is a pretty complicated attack + * since you'd have to get inside the cookie. + */ + if (!sctp_sf_check_restart_addrs(new_asoc, asoc, chunk, commands)) { + return SCTP_DISPOSITION_CONSUME; + } + + /* If the endpoint is in the SHUTDOWN-ACK-SENT state and recognizes + * the peer has restarted (Action A), it MUST NOT setup a new + * association but instead resend the SHUTDOWN ACK and send an ERROR + * chunk with a ""Cookie Received while Shutting Down"" error cause to + * its peer. + */ + if (sctp_state(asoc, SHUTDOWN_ACK_SENT)) { + disposition = sctp_sf_do_9_2_reshutack(net, ep, asoc, + SCTP_ST_CHUNK(chunk->chunk_hdr->type), + chunk, commands); + if (SCTP_DISPOSITION_NOMEM == disposition) + goto nomem; + + err = sctp_make_op_error(asoc, chunk, + SCTP_ERROR_COOKIE_IN_SHUTDOWN, + NULL, 0, 0); + if (err) + sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, + SCTP_CHUNK(err)); + + return SCTP_DISPOSITION_CONSUME; + } + + /* For now, stop pending T3-rtx and SACK timers, fail any unsent/unacked + * data. Consider the optional choice of resending of this data. + */ + sctp_add_cmd_sf(commands, SCTP_CMD_T3_RTX_TIMERS_STOP, SCTP_NULL()); + sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, + SCTP_TO(SCTP_EVENT_TIMEOUT_SACK)); + sctp_add_cmd_sf(commands, SCTP_CMD_PURGE_OUTQUEUE, SCTP_NULL()); + + /* Stop pending T4-rto timer, teardown ASCONF queue, ASCONF-ACK queue + * and ASCONF-ACK cache. + */ + sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_STOP, + SCTP_TO(SCTP_EVENT_TIMEOUT_T4_RTO)); + sctp_add_cmd_sf(commands, SCTP_CMD_PURGE_ASCONF_QUEUE, SCTP_NULL()); + + repl = sctp_make_cookie_ack(new_asoc, chunk); + if (!repl) + goto nomem; + + /* Report association restart to upper layer. */ + ev = sctp_ulpevent_make_assoc_change(asoc, 0, SCTP_RESTART, 0, + new_asoc->c.sinit_num_ostreams, + new_asoc->c.sinit_max_instreams, + NULL, GFP_ATOMIC); + if (!ev) + goto nomem_ev; + + /* Update the content of current association. */ + sctp_add_cmd_sf(commands, SCTP_CMD_UPDATE_ASSOC, SCTP_ASOC(new_asoc)); + sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev)); + sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, + SCTP_STATE(SCTP_STATE_ESTABLISHED)); + sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl)); + return SCTP_DISPOSITION_CONSUME; + +nomem_ev: + sctp_chunk_free(repl); +nomem: + return SCTP_DISPOSITION_NOMEM; +} +","@@ -2082,7 +2082,7 @@ sctp_disposition_t sctp_sf_do_5_2_4_dupcook(struct net *net, + } + + /* Delete the tempory new association. */ +- sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc)); ++ sctp_add_cmd_sf(commands, SCTP_CMD_SET_ASOC, SCTP_ASOC(new_asoc)); + sctp_add_cmd_sf(commands, SCTP_CMD_DELETE_TCB, SCTP_NULL()); + + /* Restore association pointer to provide SCTP command interpeter",895,1226,2048 +1796,"dmxProcRenderCompositeGlyphs(ClientPtr client) +{ + int ret; + + REQUEST(xRenderCompositeGlyphsReq); + + ret = dmxSaveRenderVector[stuff->renderReqType] (client); + + /* For the following to work with PanoramiX, it assumes that Render + * wraps the ProcRenderVector after dmxRenderInit has been called. + */ + if (ret == Success) { + PicturePtr pSrc; + dmxPictPrivPtr pSrcPriv; + PicturePtr pDst; + dmxPictPrivPtr pDstPriv; + PictFormatPtr pFmt; + XRenderPictFormat *pFormat; + int size; + + int scrnNum; + DMXScreenInfo *dmxScreen; + + CARD8 *buffer; + CARD8 *end; + int space; + + int nglyph; + char *glyphs; + char *curGlyph; + + xGlyphElt *elt; + int nelt; + XGlyphElt8 *elts; + XGlyphElt8 *curElt; + + GlyphSetPtr glyphSet; + dmxGlyphPrivPtr glyphPriv; + + dixLookupResourceByType((void **) &pSrc, + stuff->src, PictureType, client, DixReadAccess); + + pSrcPriv = DMX_GET_PICT_PRIV(pSrc); + if (!pSrcPriv->pict) + return ret; + + dixLookupResourceByType((void **) &pDst, + stuff->dst, PictureType, + client, DixWriteAccess); + + pDstPriv = DMX_GET_PICT_PRIV(pDst); + if (!pDstPriv->pict) + return ret; + + scrnNum = pDst->pDrawable->pScreen->myNum; + dmxScreen = &dmxScreens[scrnNum]; + + /* Note: If the back-end display has been detached, then it + * should not be possible to reach here since the pSrcPriv->pict + * and pDstPriv->pict will have already been set to 0. + */ + if (!dmxScreen->beDisplay) + return ret; + + if (stuff->maskFormat) + dixLookupResourceByType((void **) &pFmt, + stuff->maskFormat, PictFormatType, + client, DixReadAccess); + else + pFmt = NULL; + + pFormat = dmxFindFormat(dmxScreen, pFmt); + + switch (stuff->renderReqType) { + case X_RenderCompositeGlyphs8: + size = sizeof(CARD8); + break; + case X_RenderCompositeGlyphs16: + size = sizeof(CARD16); + break; + case X_RenderCompositeGlyphs32: + size = sizeof(CARD32); + break; + default: + return BadPictOp; /* Can't happen */ + } + + buffer = (CARD8 *) (stuff + 1); + end = (CARD8 *) stuff + (stuff->length << 2); + nelt = 0; + nglyph = 0; + while (buffer + sizeof(xGlyphElt) < end) { + elt = (xGlyphElt *) buffer; + buffer += sizeof(xGlyphElt); + + if (elt->len == 0xff) { + buffer += 4; + } + else { + nelt++; + nglyph += elt->len; + space = size * elt->len; + if (space & 3) + space += 4 - (space & 3); + buffer += space; + } + } + + /* The following only works for Render version > 0.2 */ + + /* All of the XGlyphElt* structure sizes are identical */ + elts = xallocarray(nelt, sizeof(XGlyphElt8)); + if (!elts) + return BadAlloc; + + glyphs = xallocarray(nglyph, size); + if (!glyphs) { + free(elts); + return BadAlloc; + } + + buffer = (CARD8 *) (stuff + 1); + end = (CARD8 *) stuff + (stuff->length << 2); + curGlyph = glyphs; + curElt = elts; + + dixLookupResourceByType((void **) &glyphSet, + stuff->glyphset, GlyphSetType, + client, DixReadAccess); + glyphPriv = DMX_GET_GLYPH_PRIV(glyphSet); + + while (buffer + sizeof(xGlyphElt) < end) { + elt = (xGlyphElt *) buffer; + buffer += sizeof(xGlyphElt); + + if (elt->len == 0xff) { + dixLookupResourceByType((void **) &glyphSet, + *((CARD32 *) buffer), + GlyphSetType, client, DixReadAccess); + glyphPriv = DMX_GET_GLYPH_PRIV(glyphSet); + buffer += 4; + } + else { + curElt->glyphset = glyphPriv->glyphSets[scrnNum]; + curElt->xOff = elt->deltax; + curElt->yOff = elt->deltay; + curElt->nchars = elt->len; + curElt->chars = curGlyph; + + memcpy(curGlyph, buffer, size * elt->len); + curGlyph += size * elt->len; + + curElt++; + + space = size * elt->len; + if (space & 3) + space += 4 - (space & 3); + buffer += space; + } + } + + switch (stuff->renderReqType) { + case X_RenderCompositeGlyphs8: + XRenderCompositeText8(dmxScreen->beDisplay, stuff->op, + pSrcPriv->pict, pDstPriv->pict, + pFormat, + stuff->xSrc, stuff->ySrc, 0, 0, elts, nelt); + break; + case X_RenderCompositeGlyphs16: + XRenderCompositeText16(dmxScreen->beDisplay, stuff->op, + pSrcPriv->pict, pDstPriv->pict, + pFormat, + stuff->xSrc, stuff->ySrc, + 0, 0, (XGlyphElt16 *) elts, nelt); + break; + case X_RenderCompositeGlyphs32: + XRenderCompositeText32(dmxScreen->beDisplay, stuff->op, + pSrcPriv->pict, pDstPriv->pict, + pFormat, + stuff->xSrc, stuff->ySrc, + 0, 0, (XGlyphElt32 *) elts, nelt); + break; + } + + dmxSync(dmxScreen, FALSE); + + free(elts); + free(glyphs); + } + + return ret; +} +",0,"dmxProcRenderCompositeGlyphs(ClientPtr client) +{ + int ret; + + REQUEST(xRenderCompositeGlyphsReq); + + ret = dmxSaveRenderVector[stuff->renderReqType] (client); + + /* For the following to work with PanoramiX, it assumes that Render + * wraps the ProcRenderVector after dmxRenderInit has been called. + */ + if (ret == Success) { + PicturePtr pSrc; + dmxPictPrivPtr pSrcPriv; + PicturePtr pDst; + dmxPictPrivPtr pDstPriv; + PictFormatPtr pFmt; + XRenderPictFormat *pFormat; + int size; + + int scrnNum; + DMXScreenInfo *dmxScreen; + + CARD8 *buffer; + CARD8 *end; + int space; + + int nglyph; + char *glyphs; + char *curGlyph; + + xGlyphElt *elt; + int nelt; + XGlyphElt8 *elts; + XGlyphElt8 *curElt; + + GlyphSetPtr glyphSet; + dmxGlyphPrivPtr glyphPriv; + + dixLookupResourceByType((void **) &pSrc, + stuff->src, PictureType, client, DixReadAccess); + + pSrcPriv = DMX_GET_PICT_PRIV(pSrc); + if (!pSrcPriv->pict) + return ret; + + dixLookupResourceByType((void **) &pDst, + stuff->dst, PictureType, + client, DixWriteAccess); + + pDstPriv = DMX_GET_PICT_PRIV(pDst); + if (!pDstPriv->pict) + return ret; + + scrnNum = pDst->pDrawable->pScreen->myNum; + dmxScreen = &dmxScreens[scrnNum]; + + /* Note: If the back-end display has been detached, then it + * should not be possible to reach here since the pSrcPriv->pict + * and pDstPriv->pict will have already been set to 0. + */ + if (!dmxScreen->beDisplay) + return ret; + + if (stuff->maskFormat) + dixLookupResourceByType((void **) &pFmt, + stuff->maskFormat, PictFormatType, + client, DixReadAccess); + else + pFmt = NULL; + + pFormat = dmxFindFormat(dmxScreen, pFmt); + + switch (stuff->renderReqType) { + case X_RenderCompositeGlyphs8: + size = sizeof(CARD8); + break; + case X_RenderCompositeGlyphs16: + size = sizeof(CARD16); + break; + case X_RenderCompositeGlyphs32: + size = sizeof(CARD32); + break; + default: + return BadPictOp; /* Can't happen */ + } + + buffer = (CARD8 *) (stuff + 1); + end = (CARD8 *) stuff + (stuff->length << 2); + nelt = 0; + nglyph = 0; + while (buffer + sizeof(xGlyphElt) < end) { + elt = (xGlyphElt *) buffer; + buffer += sizeof(xGlyphElt); + + if (elt->len == 0xff) { + buffer += 4; + } + else { + nelt++; + nglyph += elt->len; + space = size * elt->len; + if (space & 3) + space += 4 - (space & 3); + buffer += space; + } + } + + /* The following only works for Render version > 0.2 */ + + /* All of the XGlyphElt* structure sizes are identical */ + elts = xallocarray(nelt, sizeof(XGlyphElt8)); + if (!elts) + return BadAlloc; + + glyphs = xallocarray(nglyph, size); + if (!glyphs) { + free(elts); + return BadAlloc; + } + + buffer = (CARD8 *) (stuff + 1); + end = (CARD8 *) stuff + (stuff->length << 2); + curGlyph = glyphs; + curElt = elts; + + dixLookupResourceByType((void **) &glyphSet, + stuff->glyphset, GlyphSetType, + client, DixReadAccess); + glyphPriv = DMX_GET_GLYPH_PRIV(glyphSet); + + while (buffer + sizeof(xGlyphElt) < end) { + elt = (xGlyphElt *) buffer; + buffer += sizeof(xGlyphElt); + + if (elt->len == 0xff) { + dixLookupResourceByType((void **) &glyphSet, + *((CARD32 *) buffer), + GlyphSetType, client, DixReadAccess); + glyphPriv = DMX_GET_GLYPH_PRIV(glyphSet); + buffer += 4; + } + else { + curElt->glyphset = glyphPriv->glyphSets[scrnNum]; + curElt->xOff = elt->deltax; + curElt->yOff = elt->deltay; + curElt->nchars = elt->len; + curElt->chars = curGlyph; + + memcpy(curGlyph, buffer, size * elt->len); + curGlyph += size * elt->len; + + curElt++; + + space = size * elt->len; + if (space & 3) + space += 4 - (space & 3); + buffer += space; + } + } + + switch (stuff->renderReqType) { + case X_RenderCompositeGlyphs8: + XRenderCompositeText8(dmxScreen->beDisplay, stuff->op, + pSrcPriv->pict, pDstPriv->pict, + pFormat, + stuff->xSrc, stuff->ySrc, 0, 0, elts, nelt); + break; + case X_RenderCompositeGlyphs16: + XRenderCompositeText16(dmxScreen->beDisplay, stuff->op, + pSrcPriv->pict, pDstPriv->pict, + pFormat, + stuff->xSrc, stuff->ySrc, + 0, 0, (XGlyphElt16 *) elts, nelt); + break; + case X_RenderCompositeGlyphs32: + XRenderCompositeText32(dmxScreen->beDisplay, stuff->op, + pSrcPriv->pict, pDstPriv->pict, + pFormat, + stuff->xSrc, stuff->ySrc, + 0, 0, (XGlyphElt32 *) elts, nelt); + break; + } + + dmxSync(dmxScreen, FALSE); + + free(elts); + free(glyphs); + } + + return ret; +} +","@@ -716,6 +716,8 @@ dmxProcRenderSetPictureFilter(ClientPtr client) + filter = (char *) (stuff + 1); + params = (XFixed *) (filter + ((stuff->nbytes + 3) & ~3)); + nparams = ((XFixed *) stuff + client->req_len) - params; ++ if (nparams < 0) ++ return BadLength; + + XRenderSetPictureFilter(dmxScreen->beDisplay, + pPictPriv->pict, filter, params, nparams);",1455,1786,2048 +1711,"pdf_obj_read(fz_context *ctx, pdf_document *doc, int64_t *offset, int *nump, pdf_obj **page) +{ + pdf_lexbuf *buf = &doc->lexbuf.base; + int num, gen, tok; + int64_t numofs, genofs, stmofs, tmpofs, newtmpofs; + int xref_len; + pdf_xref_entry *entry; + + numofs = *offset; + fz_seek(ctx, doc->file, numofs, SEEK_SET); + + /* We expect to read 'num' here */ + tok = pdf_lex(ctx, doc->file, buf); + genofs = fz_tell(ctx, doc->file); + if (tok != PDF_TOK_INT) + { + /* Failed! */ + DEBUGMESS((ctx, ""skipping unexpected data (tok=%d) at %d"", tok, *offset)); + *offset = genofs; + return tok == PDF_TOK_EOF; + } + *nump = num = buf->i; + + /* We expect to read 'gen' here */ + tok = pdf_lex(ctx, doc->file, buf); + tmpofs = fz_tell(ctx, doc->file); + if (tok != PDF_TOK_INT) + { + /* Failed! */ + DEBUGMESS((ctx, ""skipping unexpected data after \""%d\"" (tok=%d) at %d"", num, tok, *offset)); + *offset = tmpofs; + return tok == PDF_TOK_EOF; + } + gen = buf->i; + + /* We expect to read 'obj' here */ + do + { + tmpofs = fz_tell(ctx, doc->file); + tok = pdf_lex(ctx, doc->file, buf); + if (tok == PDF_TOK_OBJ) + break; + if (tok != PDF_TOK_INT) + { + DEBUGMESS((ctx, ""skipping unexpected data (tok=%d) at %d"", tok, tmpofs)); + *offset = fz_tell(ctx, doc->file); + return tok == PDF_TOK_EOF; + } + DEBUGMESS((ctx, ""skipping unexpected int %d at %d"", num, numofs)); + *nump = num = gen; + numofs = genofs; + gen = buf->i; + genofs = tmpofs; + } + while (1); + + /* Now we read the actual object */ + xref_len = pdf_xref_len(ctx, doc); + + /* When we are reading a progressive file, we typically see: + * File Header + * obj m (Linearization params) + * xref #1 (refers to objects m-n) + * obj m+1 + * ... + * obj n + * obj 1 + * ... + * obj n-1 + * xref #2 + * + * The linearisation params are read elsewhere, hence + * whenever we read an object it should just go into the + * previous xref. + */ + tok = pdf_repair_obj(ctx, doc, buf, &stmofs, NULL, NULL, NULL, page, &newtmpofs, NULL); + + do /* So we can break out of it */ + { + if (num <= 0 || num >= xref_len) + { + fz_warn(ctx, ""Not a valid object number (%d %d obj)"", num, gen); + break; + } + if (gen != 0) + { + fz_warn(ctx, ""Unexpected non zero generation number in linearized file""); + } + entry = pdf_get_populating_xref_entry(ctx, doc, num); + if (entry->type != 0) + { + DEBUGMESS((ctx, ""Duplicate object found (%d %d obj)"", num, gen)); + break; + } + if (page && *page) + { + DEBUGMESS((ctx, ""Successfully read object %d @ %d - and found page %d!"", num, numofs, doc->linear_page_num)); + if (!entry->obj) + entry->obj = pdf_keep_obj(ctx, *page); + + if (doc->linear_page_refs[doc->linear_page_num] == NULL) + doc->linear_page_refs[doc->linear_page_num] = pdf_new_indirect(ctx, doc, num, gen); + } + else + { + DEBUGMESS((ctx, ""Successfully read object %d @ %d"", num, numofs)); + } + entry->type = 'n'; + entry->gen = gen; // XXX: was 0 + entry->num = num; + entry->ofs = numofs; + entry->stm_ofs = stmofs; + } + while (0); + if (page && *page) + doc->linear_page_num++; + + if (tok == PDF_TOK_ENDOBJ) + { + *offset = fz_tell(ctx, doc->file); + } + else + { + *offset = newtmpofs; + } + return 0; +} +",0,"pdf_obj_read(fz_context *ctx, pdf_document *doc, int64_t *offset, int *nump, pdf_obj **page) +{ + pdf_lexbuf *buf = &doc->lexbuf.base; + int num, gen, tok; + int64_t numofs, genofs, stmofs, tmpofs, newtmpofs; + int xref_len; + pdf_xref_entry *entry; + + numofs = *offset; + fz_seek(ctx, doc->file, numofs, SEEK_SET); + + /* We expect to read 'num' here */ + tok = pdf_lex(ctx, doc->file, buf); + genofs = fz_tell(ctx, doc->file); + if (tok != PDF_TOK_INT) + { + /* Failed! */ + DEBUGMESS((ctx, ""skipping unexpected data (tok=%d) at %d"", tok, *offset)); + *offset = genofs; + return tok == PDF_TOK_EOF; + } + *nump = num = buf->i; + + /* We expect to read 'gen' here */ + tok = pdf_lex(ctx, doc->file, buf); + tmpofs = fz_tell(ctx, doc->file); + if (tok != PDF_TOK_INT) + { + /* Failed! */ + DEBUGMESS((ctx, ""skipping unexpected data after \""%d\"" (tok=%d) at %d"", num, tok, *offset)); + *offset = tmpofs; + return tok == PDF_TOK_EOF; + } + gen = buf->i; + + /* We expect to read 'obj' here */ + do + { + tmpofs = fz_tell(ctx, doc->file); + tok = pdf_lex(ctx, doc->file, buf); + if (tok == PDF_TOK_OBJ) + break; + if (tok != PDF_TOK_INT) + { + DEBUGMESS((ctx, ""skipping unexpected data (tok=%d) at %d"", tok, tmpofs)); + *offset = fz_tell(ctx, doc->file); + return tok == PDF_TOK_EOF; + } + DEBUGMESS((ctx, ""skipping unexpected int %d at %d"", num, numofs)); + *nump = num = gen; + numofs = genofs; + gen = buf->i; + genofs = tmpofs; + } + while (1); + + /* Now we read the actual object */ + xref_len = pdf_xref_len(ctx, doc); + + /* When we are reading a progressive file, we typically see: + * File Header + * obj m (Linearization params) + * xref #1 (refers to objects m-n) + * obj m+1 + * ... + * obj n + * obj 1 + * ... + * obj n-1 + * xref #2 + * + * The linearisation params are read elsewhere, hence + * whenever we read an object it should just go into the + * previous xref. + */ + tok = pdf_repair_obj(ctx, doc, buf, &stmofs, NULL, NULL, NULL, page, &newtmpofs, NULL); + + do /* So we can break out of it */ + { + if (num <= 0 || num >= xref_len) + { + fz_warn(ctx, ""Not a valid object number (%d %d obj)"", num, gen); + break; + } + if (gen != 0) + { + fz_warn(ctx, ""Unexpected non zero generation number in linearized file""); + } + entry = pdf_get_populating_xref_entry(ctx, doc, num); + if (entry->type != 0) + { + DEBUGMESS((ctx, ""Duplicate object found (%d %d obj)"", num, gen)); + break; + } + if (page && *page) + { + DEBUGMESS((ctx, ""Successfully read object %d @ %d - and found page %d!"", num, numofs, doc->linear_page_num)); + if (!entry->obj) + entry->obj = pdf_keep_obj(ctx, *page); + + if (doc->linear_page_refs[doc->linear_page_num] == NULL) + doc->linear_page_refs[doc->linear_page_num] = pdf_new_indirect(ctx, doc, num, gen); + } + else + { + DEBUGMESS((ctx, ""Successfully read object %d @ %d"", num, numofs)); + } + entry->type = 'n'; + entry->gen = gen; // XXX: was 0 + entry->num = num; + entry->ofs = numofs; + entry->stm_ofs = stmofs; + } + while (0); + if (page && *page) + doc->linear_page_num++; + + if (tok == PDF_TOK_ENDOBJ) + { + *offset = fz_tell(ctx, doc->file); + } + else + { + *offset = newtmpofs; + } + return 0; +} +","@@ -868,11 +868,12 @@ pdf_read_old_xref(fz_context *ctx, pdf_document *doc, pdf_lexbuf *buf) + fz_seek(ctx, file, -(2 + (int)strlen(s)), SEEK_CUR); + } + +- if (ofs < 0) +- fz_throw(ctx, FZ_ERROR_GENERIC, ""out of range object num in xref: %d"", (int)ofs); +- if (ofs > INT64_MAX - len) +- fz_throw(ctx, FZ_ERROR_GENERIC, ""xref section object numbers too big""); +- ++ if (ofs < 0 || ofs > PDF_MAX_OBJECT_NUMBER ++ || len < 0 || len > PDF_MAX_OBJECT_NUMBER ++ || ofs + len - 1 > PDF_MAX_OBJECT_NUMBER) ++ { ++ fz_throw(ctx, FZ_ERROR_GENERIC, ""xref subsection object numbers are out of range""); ++ } + /* broken pdfs where size in trailer undershoots entries in xref sections */ + if (ofs + len > xref_len) + { +@@ -933,10 +934,8 @@ pdf_read_new_xref_section(fz_context *ctx, pdf_document *doc, fz_stream *stm, in + pdf_xref_entry *table; + int i, n; + +- if (i0 < 0 || i1 < 0 || i0 > INT_MAX - i1) +- fz_throw(ctx, FZ_ERROR_GENERIC, ""negative xref stream entry index""); +- //if (i0 + i1 > pdf_xref_len(ctx, doc)) +- // fz_throw(ctx, FZ_ERROR_GENERIC, ""xref stream has too many entries""); ++ if (i0 < 0 || i0 > PDF_MAX_OBJECT_NUMBER || i1 < 0 || i1 > PDF_MAX_OBJECT_NUMBER || i0 + i1 - 1 > PDF_MAX_OBJECT_NUMBER) ++ fz_throw(ctx, FZ_ERROR_GENERIC, ""xref subsection object numbers are out of range""); + + table = pdf_xref_find_subsection(ctx, doc, i0, i1); + for (i = i0; i < i0 + i1; i++) +@@ -2086,6 +2085,10 @@ pdf_create_object(fz_context *ctx, pdf_document *doc) + /* TODO: reuse free object slots by properly linking free object chains in the ofs field */ + pdf_xref_entry *entry; + int num = pdf_xref_len(ctx, doc); ++ ++ if (num > PDF_MAX_OBJECT_NUMBER) ++ fz_throw(ctx, FZ_ERROR_GENERIC, ""too many objects stored in pdf""); ++ + entry = pdf_get_incremental_xref_entry(ctx, doc, num); + entry->type = 'f'; + entry->ofs = -1;",1079,1410,2048 +18165,"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)); + } + /* + 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)); +} +",1,"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)); +} +","@@ -206,6 +206,12 @@ static Image *ReadMAPImage(const ImageInfo *image_info,ExceptionInfo *exception) + (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. + */",1124,1455,2048 +17936," int lzo1x_decompress_safe(const unsigned char *in, size_t in_len, + unsigned char *out, size_t *out_len) +{ + unsigned char *op; + const unsigned char *ip; + size_t t, next; + size_t state = 0; + const unsigned char *m_pos; + const unsigned char * const ip_end = in + in_len; + unsigned char * const op_end = out + *out_len; + + op = out; + ip = in; + + if (unlikely(in_len < 3)) + goto input_overrun; + if (*ip > 17) { + t = *ip++ - 17; + if (t < 4) { + next = t; + goto match_next; + } + goto copy_literal_run; + } + + for (;;) { + t = *ip++; + if (t < 16) { + if (likely(state == 0)) { + if (unlikely(t == 0)) { + while (unlikely(*ip == 0)) { + t += 255; + ip++; + NEED_IP(1); + } + t += 15 + *ip++; + } + t += 3; + copy_literal_run: + #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) + if (likely(HAVE_IP(t + 15) && HAVE_OP(t + 15))) { + const unsigned char *ie = ip + t; + unsigned char *oe = op + t; + do { + COPY8(op, ip); + op += 8; + ip += 8; + COPY8(op, ip); + op += 8; + ip += 8; + } while (ip < ie); + ip = ie; + op = oe; + } else + #endif + { + NEED_OP(t); + NEED_IP(t + 3); + do { + *op++ = *ip++; + } while (--t > 0); + } + state = 4; + continue; + } else if (state != 4) { + next = t & 3; + m_pos = op - 1; + m_pos -= t >> 2; + m_pos -= *ip++ << 2; + TEST_LB(m_pos); + NEED_OP(2); + op[0] = m_pos[0]; + op[1] = m_pos[1]; + op += 2; + goto match_next; + } else { + next = t & 3; + m_pos = op - (1 + M2_MAX_OFFSET); + m_pos -= t >> 2; + m_pos -= *ip++ << 2; + t = 3; + } + } else if (t >= 64) { + next = t & 3; + m_pos = op - 1; + m_pos -= (t >> 2) & 7; + m_pos -= *ip++ << 3; + t = (t >> 5) - 1 + (3 - 1); + } else if (t >= 32) { + t = (t & 31) + (3 - 1); + if (unlikely(t == 2)) { + while (unlikely(*ip == 0)) { + t += 255; + ip++; + NEED_IP(1); + } + t += 31 + *ip++; + NEED_IP(2); + } + m_pos = op - 1; + next = get_unaligned_le16(ip); + ip += 2; + m_pos -= next >> 2; + next &= 3; + } else { + m_pos = op; + m_pos -= (t & 8) << 11; + t = (t & 7) + (3 - 1); + if (unlikely(t == 2)) { + while (unlikely(*ip == 0)) { + t += 255; + ip++; + NEED_IP(1); + } + t += 7 + *ip++; + NEED_IP(2); + } + next = get_unaligned_le16(ip); + ip += 2; + m_pos -= next >> 2; + next &= 3; + if (m_pos == op) + goto eof_found; + m_pos -= 0x4000; + } + TEST_LB(m_pos); + #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) + if (op - m_pos >= 8) { + unsigned char *oe = op + t; + if (likely(HAVE_OP(t + 15))) { + do { + COPY8(op, m_pos); + op += 8; + m_pos += 8; + COPY8(op, m_pos); + op += 8; + m_pos += 8; + } while (op < oe); + op = oe; + if (HAVE_IP(6)) { + state = next; + COPY4(op, ip); + op += next; + ip += next; + continue; + } + } else { + NEED_OP(t); + do { + *op++ = *m_pos++; + } while (op < oe); + } + } else + #endif + { + unsigned char *oe = op + t; + NEED_OP(t); + op[0] = m_pos[0]; + op[1] = m_pos[1]; + op += 2; + m_pos += 2; + do { + *op++ = *m_pos++; + } while (op < oe); + } +match_next: + state = next; + t = next; + #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) + if (likely(HAVE_IP(6) && HAVE_OP(4))) { + COPY4(op, ip); + op += t; + ip += t; + } else + #endif + { + NEED_IP(t + 3); + NEED_OP(t); + while (t > 0) { + *op++ = *ip++; + t--; + } + } + } + +eof_found: + *out_len = op - out; + return (t != 3 ? LZO_E_ERROR : + ip == ip_end ? LZO_E_OK : + ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN); + +input_overrun: + *out_len = op - out; + return LZO_E_INPUT_OVERRUN; + +output_overrun: + *out_len = op - out; + return LZO_E_OUTPUT_OVERRUN; + +lookbehind_overrun: + *out_len = op - out; + return LZO_E_LOOKBEHIND_OVERRUN; +} +",1," int lzo1x_decompress_safe(const unsigned char *in, size_t in_len, + unsigned char *out, size_t *out_len) +{ + unsigned char *op; + const unsigned char *ip; + size_t t, next; + size_t state = 0; + const unsigned char *m_pos; + const unsigned char * const ip_end = in + in_len; + unsigned char * const op_end = out + *out_len; + + op = out; + ip = in; + + if (unlikely(in_len < 3)) + goto input_overrun; + if (*ip > 17) { + t = *ip++ - 17; + if (t < 4) { + next = t; + goto match_next; + } + goto copy_literal_run; + } + + for (;;) { + t = *ip++; + if (t < 16) { + if (likely(state == 0)) { + if (unlikely(t == 0)) { + while (unlikely(*ip == 0)) { + t += 255; + ip++; + NEED_IP(1, 0); + } + t += 15 + *ip++; + } + t += 3; + copy_literal_run: + #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) + if (likely(HAVE_IP(t, 15) && HAVE_OP(t, 15))) { + const unsigned char *ie = ip + t; + unsigned char *oe = op + t; + do { + COPY8(op, ip); + op += 8; + ip += 8; + COPY8(op, ip); + op += 8; + ip += 8; + } while (ip < ie); + ip = ie; + op = oe; + } else + #endif + { + NEED_OP(t, 0); + NEED_IP(t, 3); + do { + *op++ = *ip++; + } while (--t > 0); + } + state = 4; + continue; + } else if (state != 4) { + next = t & 3; + m_pos = op - 1; + m_pos -= t >> 2; + m_pos -= *ip++ << 2; + TEST_LB(m_pos); + NEED_OP(2, 0); + op[0] = m_pos[0]; + op[1] = m_pos[1]; + op += 2; + goto match_next; + } else { + next = t & 3; + m_pos = op - (1 + M2_MAX_OFFSET); + m_pos -= t >> 2; + m_pos -= *ip++ << 2; + t = 3; + } + } else if (t >= 64) { + next = t & 3; + m_pos = op - 1; + m_pos -= (t >> 2) & 7; + m_pos -= *ip++ << 3; + t = (t >> 5) - 1 + (3 - 1); + } else if (t >= 32) { + t = (t & 31) + (3 - 1); + if (unlikely(t == 2)) { + while (unlikely(*ip == 0)) { + t += 255; + ip++; + NEED_IP(1, 0); + } + t += 31 + *ip++; + NEED_IP(2, 0); + } + m_pos = op - 1; + next = get_unaligned_le16(ip); + ip += 2; + m_pos -= next >> 2; + next &= 3; + } else { + m_pos = op; + m_pos -= (t & 8) << 11; + t = (t & 7) + (3 - 1); + if (unlikely(t == 2)) { + while (unlikely(*ip == 0)) { + t += 255; + ip++; + NEED_IP(1, 0); + } + t += 7 + *ip++; + NEED_IP(2, 0); + } + next = get_unaligned_le16(ip); + ip += 2; + m_pos -= next >> 2; + next &= 3; + if (m_pos == op) + goto eof_found; + m_pos -= 0x4000; + } + TEST_LB(m_pos); + #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) + if (op - m_pos >= 8) { + unsigned char *oe = op + t; + if (likely(HAVE_OP(t, 15))) { + do { + COPY8(op, m_pos); + op += 8; + m_pos += 8; + COPY8(op, m_pos); + op += 8; + m_pos += 8; + } while (op < oe); + op = oe; + if (HAVE_IP(6, 0)) { + state = next; + COPY4(op, ip); + op += next; + ip += next; + continue; + } + } else { + NEED_OP(t, 0); + do { + *op++ = *m_pos++; + } while (op < oe); + } + } else + #endif + { + unsigned char *oe = op + t; + NEED_OP(t, 0); + op[0] = m_pos[0]; + op[1] = m_pos[1]; + op += 2; + m_pos += 2; + do { + *op++ = *m_pos++; + } while (op < oe); + } +match_next: + state = next; + t = next; + #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) + if (likely(HAVE_IP(6, 0) && HAVE_OP(4, 0))) { + COPY4(op, ip); + op += t; + ip += t; + } else + #endif + { + NEED_IP(t, 3); + NEED_OP(t, 0); + while (t > 0) { + *op++ = *ip++; + t--; + } + } + } + +eof_found: + *out_len = op - out; + return (t != 3 ? LZO_E_ERROR : + ip == ip_end ? LZO_E_OK : + ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN); + +input_overrun: + *out_len = op - out; + return LZO_E_INPUT_OVERRUN; + +output_overrun: + *out_len = op - out; + return LZO_E_OUTPUT_OVERRUN; + +lookbehind_overrun: + *out_len = op - out; + return LZO_E_LOOKBEHIND_OVERRUN; +} +","@@ -19,11 +19,31 @@ + #include + #include ""lzodefs.h"" + +-#define HAVE_IP(x) ((size_t)(ip_end - ip) >= (size_t)(x)) +-#define HAVE_OP(x) ((size_t)(op_end - op) >= (size_t)(x)) +-#define NEED_IP(x) if (!HAVE_IP(x)) goto input_overrun +-#define NEED_OP(x) if (!HAVE_OP(x)) goto output_overrun +-#define TEST_LB(m_pos) if ((m_pos) < out) goto lookbehind_overrun ++#define HAVE_IP(t, x) \ ++ (((size_t)(ip_end - ip) >= (size_t)(t + x)) && \ ++ (((t + x) >= t) && ((t + x) >= x))) ++ ++#define HAVE_OP(t, x) \ ++ (((size_t)(op_end - op) >= (size_t)(t + x)) && \ ++ (((t + x) >= t) && ((t + x) >= x))) ++ ++#define NEED_IP(t, x) \ ++ do { \ ++ if (!HAVE_IP(t, x)) \ ++ goto input_overrun; \ ++ } while (0) ++ ++#define NEED_OP(t, x) \ ++ do { \ ++ if (!HAVE_OP(t, x)) \ ++ goto output_overrun; \ ++ } while (0) ++ ++#define TEST_LB(m_pos) \ ++ do { \ ++ if ((m_pos) < out) \ ++ goto lookbehind_overrun; \ ++ } while (0) + + int lzo1x_decompress_safe(const unsigned char *in, size_t in_len, + unsigned char *out, size_t *out_len) +@@ -58,14 +78,14 @@ int lzo1x_decompress_safe(const unsigned char *in, size_t in_len, + while (unlikely(*ip == 0)) { + t += 255; + ip++; +- NEED_IP(1); ++ NEED_IP(1, 0); + } + t += 15 + *ip++; + } + t += 3; + copy_literal_run: + #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) +- if (likely(HAVE_IP(t + 15) && HAVE_OP(t + 15))) { ++ if (likely(HAVE_IP(t, 15) && HAVE_OP(t, 15))) { + const unsigned char *ie = ip + t; + unsigned char *oe = op + t; + do { +@@ -81,8 +101,8 @@ int lzo1x_decompress_safe(const unsigned char *in, size_t in_len, + } else + #endif + { +- NEED_OP(t); +- NEED_IP(t + 3); ++ NEED_OP(t, 0); ++ NEED_IP(t, 3); + do { + *op++ = *ip++; + } while (--t > 0); +@@ -95,7 +115,7 @@ int lzo1x_decompress_safe(const unsigned char *in, size_t in_len, + m_pos -= t >> 2; + m_pos -= *ip++ << 2; + TEST_LB(m_pos); +- NEED_OP(2); ++ NEED_OP(2, 0); + op[0] = m_pos[0]; + op[1] = m_pos[1]; + op += 2; +@@ -119,10 +139,10 @@ int lzo1x_decompress_safe(const unsigned char *in, size_t in_len, + while (unlikely(*ip == 0)) { + t += 255; + ip++; +- NEED_IP(1); ++ NEED_IP(1, 0); + } + t += 31 + *ip++; +- NEED_IP(2); ++ NEED_IP(2, 0); + } + m_pos = op - 1; + next = get_unaligned_le16(ip); +@@ -137,10 +157,10 @@ int lzo1x_decompress_safe(const unsigned char *in, size_t in_len, + while (unlikely(*ip == 0)) { + t += 255; + ip++; +- NEED_IP(1); ++ NEED_IP(1, 0); + } + t += 7 + *ip++; +- NEED_IP(2); ++ NEED_IP(2, 0); + } + next = get_unaligned_le16(ip); + ip += 2; +@@ -154,7 +174,7 @@ int lzo1x_decompress_safe(const unsigned char *in, size_t in_len, + #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) + if (op - m_pos >= 8) { + unsigned char *oe = op + t; +- if (likely(HAVE_OP(t + 15))) { ++ if (likely(HAVE_OP(t, 15))) { + do { + COPY8(op, m_pos); + op += 8; +@@ -164,15 +184,15 @@ int lzo1x_decompress_safe(const unsigned char *in, size_t in_len, + m_pos += 8; + } while (op < oe); + op = oe; +- if (HAVE_IP(6)) { ++ if (HAVE_IP(6, 0)) { + state = next; + COPY4(op, ip); + op += next; + ip += next; + continue; + } + } else { +- NEED_OP(t); ++ NEED_OP(t, 0); + do { + *op++ = *m_pos++; + } while (op < oe); +@@ -181,7 +201,7 @@ int lzo1x_decompress_safe(const unsigned char *in, size_t in_len, + #endif + { + unsigned char *oe = op + t; +- NEED_OP(t); ++ NEED_OP(t, 0); + op[0] = m_pos[0]; + op[1] = m_pos[1]; + op += 2; +@@ -194,15 +214,15 @@ int lzo1x_decompress_safe(const unsigned char *in, size_t in_len, + state = next; + t = next; + #if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) +- if (likely(HAVE_IP(6) && HAVE_OP(4))) { ++ if (likely(HAVE_IP(6, 0) && HAVE_OP(4, 0))) { + COPY4(op, ip); + op += t; + ip += t; + } else + #endif + { +- NEED_IP(t + 3); +- NEED_OP(t); ++ NEED_IP(t, 3); ++ NEED_OP(t, 0); + while (t > 0) { + *op++ = *ip++; + t--;",1493,1824,2048 +15592,"void SupervisedUserService::SetActive(bool active) { + if (active_ == active) + return; + active_ = active; + + if (!delegate_ || !delegate_->SetActive(active_)) { + if (active_) { +#if !defined(OS_ANDROID) + ProfileOAuth2TokenService* token_service = + ProfileOAuth2TokenServiceFactory::GetForProfile(profile_); + token_service->LoadCredentials( + supervised_users::kSupervisedUserPseudoEmail); +#else + NOTREACHED(); +#endif + } + } + + +#if !defined(OS_ANDROID) + ThemeService* theme_service = ThemeServiceFactory::GetForProfile(profile_); + if (theme_service->UsingDefaultTheme() || theme_service->UsingSystemTheme()) + theme_service->UseDefaultTheme(); +#endif + + browser_sync::ProfileSyncService* sync_service = + ProfileSyncServiceFactory::GetForProfile(profile_); + sync_service->SetEncryptEverythingAllowed(!active_); + + GetSettingsService()->SetActive(active_); + +#if BUILDFLAG(ENABLE_EXTENSIONS) + SetExtensionsActive(); +#endif + + if (active_) { + pref_change_registrar_.Add( + prefs::kDefaultSupervisedUserFilteringBehavior, + base::BindRepeating( + &SupervisedUserService::OnDefaultFilteringBehaviorChanged, + base::Unretained(this))); +#if BUILDFLAG(ENABLE_EXTENSIONS) + pref_change_registrar_.Add( + prefs::kSupervisedUserApprovedExtensions, + base::BindRepeating(&SupervisedUserService::UpdateApprovedExtensions, + base::Unretained(this))); +#endif + pref_change_registrar_.Add( + prefs::kSupervisedUserSafeSites, + base::BindRepeating(&SupervisedUserService::OnSafeSitesSettingChanged, + base::Unretained(this))); + pref_change_registrar_.Add( + prefs::kSupervisedUserManualHosts, + base::BindRepeating(&SupervisedUserService::UpdateManualHosts, + base::Unretained(this))); + pref_change_registrar_.Add( + prefs::kSupervisedUserManualURLs, + base::BindRepeating(&SupervisedUserService::UpdateManualURLs, + base::Unretained(this))); + for (const char* pref : kCustodianInfoPrefs) { + pref_change_registrar_.Add( + pref, + base::BindRepeating(&SupervisedUserService::OnCustodianInfoChanged, + base::Unretained(this))); + } + + OnDefaultFilteringBehaviorChanged(); + OnSafeSitesSettingChanged(); + whitelist_service_->Init(); + UpdateManualHosts(); + UpdateManualURLs(); + +#if BUILDFLAG(ENABLE_EXTENSIONS) + UpdateApprovedExtensions(); +#endif + +#if !defined(OS_ANDROID) + BrowserList::AddObserver(this); +#endif + } else { + permissions_creators_.clear(); + url_reporter_.reset(); + + pref_change_registrar_.Remove( + prefs::kDefaultSupervisedUserFilteringBehavior); +#if BUILDFLAG(ENABLE_EXTENSIONS) + pref_change_registrar_.Remove(prefs::kSupervisedUserApprovedExtensions); +#endif + pref_change_registrar_.Remove(prefs::kSupervisedUserManualHosts); + pref_change_registrar_.Remove(prefs::kSupervisedUserManualURLs); + for (const char* pref : kCustodianInfoPrefs) { + pref_change_registrar_.Remove(pref); + } + + url_filter_.Clear(); + for (SupervisedUserServiceObserver& observer : observer_list_) + observer.OnURLFilterChanged(); + +#if !defined(OS_ANDROID) + BrowserList::RemoveObserver(this); +#endif + } +} +",0,"void SupervisedUserService::SetActive(bool active) { + if (active_ == active) + return; + active_ = active; + + if (!delegate_ || !delegate_->SetActive(active_)) { + if (active_) { +#if !defined(OS_ANDROID) + ProfileOAuth2TokenService* token_service = + ProfileOAuth2TokenServiceFactory::GetForProfile(profile_); + token_service->LoadCredentials( + supervised_users::kSupervisedUserPseudoEmail); +#else + NOTREACHED(); +#endif + } + } + + +#if !defined(OS_ANDROID) + ThemeService* theme_service = ThemeServiceFactory::GetForProfile(profile_); + if (theme_service->UsingDefaultTheme() || theme_service->UsingSystemTheme()) + theme_service->UseDefaultTheme(); +#endif + + browser_sync::ProfileSyncService* sync_service = + ProfileSyncServiceFactory::GetForProfile(profile_); + sync_service->SetEncryptEverythingAllowed(!active_); + + GetSettingsService()->SetActive(active_); + +#if BUILDFLAG(ENABLE_EXTENSIONS) + SetExtensionsActive(); +#endif + + if (active_) { + pref_change_registrar_.Add( + prefs::kDefaultSupervisedUserFilteringBehavior, + base::BindRepeating( + &SupervisedUserService::OnDefaultFilteringBehaviorChanged, + base::Unretained(this))); +#if BUILDFLAG(ENABLE_EXTENSIONS) + pref_change_registrar_.Add( + prefs::kSupervisedUserApprovedExtensions, + base::BindRepeating(&SupervisedUserService::UpdateApprovedExtensions, + base::Unretained(this))); +#endif + pref_change_registrar_.Add( + prefs::kSupervisedUserSafeSites, + base::BindRepeating(&SupervisedUserService::OnSafeSitesSettingChanged, + base::Unretained(this))); + pref_change_registrar_.Add( + prefs::kSupervisedUserManualHosts, + base::BindRepeating(&SupervisedUserService::UpdateManualHosts, + base::Unretained(this))); + pref_change_registrar_.Add( + prefs::kSupervisedUserManualURLs, + base::BindRepeating(&SupervisedUserService::UpdateManualURLs, + base::Unretained(this))); + for (const char* pref : kCustodianInfoPrefs) { + pref_change_registrar_.Add( + pref, + base::BindRepeating(&SupervisedUserService::OnCustodianInfoChanged, + base::Unretained(this))); + } + + OnDefaultFilteringBehaviorChanged(); + OnSafeSitesSettingChanged(); + whitelist_service_->Init(); + UpdateManualHosts(); + UpdateManualURLs(); + +#if BUILDFLAG(ENABLE_EXTENSIONS) + UpdateApprovedExtensions(); +#endif + +#if !defined(OS_ANDROID) + BrowserList::AddObserver(this); +#endif + } else { + permissions_creators_.clear(); + url_reporter_.reset(); + + pref_change_registrar_.Remove( + prefs::kDefaultSupervisedUserFilteringBehavior); +#if BUILDFLAG(ENABLE_EXTENSIONS) + pref_change_registrar_.Remove(prefs::kSupervisedUserApprovedExtensions); +#endif + pref_change_registrar_.Remove(prefs::kSupervisedUserManualHosts); + pref_change_registrar_.Remove(prefs::kSupervisedUserManualURLs); + for (const char* pref : kCustodianInfoPrefs) { + pref_change_registrar_.Remove(pref); + } + + url_filter_.Clear(); + for (SupervisedUserServiceObserver& observer : observer_list_) + observer.OnURLFilterChanged(); + +#if !defined(OS_ANDROID) + BrowserList::RemoveObserver(this); +#endif + } +} +","@@ -324,8 +324,9 @@ base::string16 SupervisedUserService::GetExtensionsLockedMessage() const { + void SupervisedUserService::InitSync(const std::string& refresh_token) { + ProfileOAuth2TokenService* token_service = + ProfileOAuth2TokenServiceFactory::GetForProfile(profile_); +- token_service->UpdateCredentials(supervised_users::kSupervisedUserPseudoEmail, +- refresh_token); ++ token_service->UpdateCredentials( ++ supervised_users::kSupervisedUserPseudoEmail, refresh_token, ++ signin_metrics::SourceForRefreshTokenOperation::kSupervisedUser_InitSync); + } + #endif // !defined(OS_ANDROID) + ",745,1076,2048 +6480,"static int check_call(struct bpf_verifier_env *env, int func_id, int insn_idx) +{ + struct bpf_verifier_state *state = &env->cur_state; + const struct bpf_func_proto *fn = NULL; + struct bpf_reg_state *regs = state->regs; + struct bpf_reg_state *reg; + struct bpf_call_arg_meta meta; + bool changes_data; + int i, err; + + /* find function prototype */ + if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { + verbose(""invalid func %s#%d\n"", func_id_name(func_id), func_id); + return -EINVAL; + } + + if (env->prog->aux->ops->get_func_proto) + fn = env->prog->aux->ops->get_func_proto(func_id); + + if (!fn) { + verbose(""unknown func %s#%d\n"", func_id_name(func_id), func_id); + return -EINVAL; + } + + /* eBPF programs must be GPL compatible to use GPL-ed functions */ + if (!env->prog->gpl_compatible && fn->gpl_only) { + verbose(""cannot call GPL only function from proprietary program\n""); + return -EINVAL; + } + + changes_data = bpf_helper_changes_pkt_data(fn->func); + + memset(&meta, 0, sizeof(meta)); + meta.pkt_access = fn->pkt_access; + + /* We only support one arg being in raw mode at the moment, which + * is sufficient for the helper functions we have right now. + */ + err = check_raw_mode(fn); + if (err) { + verbose(""kernel subsystem misconfigured func %s#%d\n"", + func_id_name(func_id), func_id); + return err; + } + + /* check args */ + err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta); + if (err) + return err; + err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta); + if (err) + return err; + err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta); + if (err) + return err; + err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta); + if (err) + return err; + err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta); + if (err) + return err; + + /* Mark slots with STACK_MISC in case of raw mode, stack offset + * is inferred from register state. + */ + for (i = 0; i < meta.access_size; i++) { + err = check_mem_access(env, meta.regno, i, BPF_B, BPF_WRITE, -1); + if (err) + return err; + } + + /* reset caller saved regs */ + for (i = 0; i < CALLER_SAVED_REGS; i++) { + reg = regs + caller_saved[i]; + reg->type = NOT_INIT; + reg->imm = 0; + } + + /* update return register */ + if (fn->ret_type == RET_INTEGER) { + regs[BPF_REG_0].type = UNKNOWN_VALUE; + } else if (fn->ret_type == RET_VOID) { + regs[BPF_REG_0].type = NOT_INIT; + } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) { + struct bpf_insn_aux_data *insn_aux; + + regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL; + regs[BPF_REG_0].max_value = regs[BPF_REG_0].min_value = 0; + /* remember map_ptr, so that check_map_access() + * can check 'value_size' boundary of memory access + * to map element returned from bpf_map_lookup_elem() + */ + if (meta.map_ptr == NULL) { + verbose(""kernel subsystem misconfigured verifier\n""); + return -EINVAL; + } + regs[BPF_REG_0].map_ptr = meta.map_ptr; + regs[BPF_REG_0].id = ++env->id_gen; + insn_aux = &env->insn_aux_data[insn_idx]; + if (!insn_aux->map_ptr) + insn_aux->map_ptr = meta.map_ptr; + else if (insn_aux->map_ptr != meta.map_ptr) + insn_aux->map_ptr = BPF_MAP_PTR_POISON; + } else { + verbose(""unknown return type %d of func %s#%d\n"", + fn->ret_type, func_id_name(func_id), func_id); + return -EINVAL; + } + + err = check_map_func_compatibility(meta.map_ptr, func_id); + if (err) + return err; + + if (changes_data) + clear_all_pkt_pointers(env); + return 0; +} +",0,"static int check_call(struct bpf_verifier_env *env, int func_id, int insn_idx) +{ + struct bpf_verifier_state *state = &env->cur_state; + const struct bpf_func_proto *fn = NULL; + struct bpf_reg_state *regs = state->regs; + struct bpf_reg_state *reg; + struct bpf_call_arg_meta meta; + bool changes_data; + int i, err; + + /* find function prototype */ + if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { + verbose(""invalid func %s#%d\n"", func_id_name(func_id), func_id); + return -EINVAL; + } + + if (env->prog->aux->ops->get_func_proto) + fn = env->prog->aux->ops->get_func_proto(func_id); + + if (!fn) { + verbose(""unknown func %s#%d\n"", func_id_name(func_id), func_id); + return -EINVAL; + } + + /* eBPF programs must be GPL compatible to use GPL-ed functions */ + if (!env->prog->gpl_compatible && fn->gpl_only) { + verbose(""cannot call GPL only function from proprietary program\n""); + return -EINVAL; + } + + changes_data = bpf_helper_changes_pkt_data(fn->func); + + memset(&meta, 0, sizeof(meta)); + meta.pkt_access = fn->pkt_access; + + /* We only support one arg being in raw mode at the moment, which + * is sufficient for the helper functions we have right now. + */ + err = check_raw_mode(fn); + if (err) { + verbose(""kernel subsystem misconfigured func %s#%d\n"", + func_id_name(func_id), func_id); + return err; + } + + /* check args */ + err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta); + if (err) + return err; + err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta); + if (err) + return err; + err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta); + if (err) + return err; + err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta); + if (err) + return err; + err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta); + if (err) + return err; + + /* Mark slots with STACK_MISC in case of raw mode, stack offset + * is inferred from register state. + */ + for (i = 0; i < meta.access_size; i++) { + err = check_mem_access(env, meta.regno, i, BPF_B, BPF_WRITE, -1); + if (err) + return err; + } + + /* reset caller saved regs */ + for (i = 0; i < CALLER_SAVED_REGS; i++) { + reg = regs + caller_saved[i]; + reg->type = NOT_INIT; + reg->imm = 0; + } + + /* update return register */ + if (fn->ret_type == RET_INTEGER) { + regs[BPF_REG_0].type = UNKNOWN_VALUE; + } else if (fn->ret_type == RET_VOID) { + regs[BPF_REG_0].type = NOT_INIT; + } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) { + struct bpf_insn_aux_data *insn_aux; + + regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL; + regs[BPF_REG_0].max_value = regs[BPF_REG_0].min_value = 0; + /* remember map_ptr, so that check_map_access() + * can check 'value_size' boundary of memory access + * to map element returned from bpf_map_lookup_elem() + */ + if (meta.map_ptr == NULL) { + verbose(""kernel subsystem misconfigured verifier\n""); + return -EINVAL; + } + regs[BPF_REG_0].map_ptr = meta.map_ptr; + regs[BPF_REG_0].id = ++env->id_gen; + insn_aux = &env->insn_aux_data[insn_idx]; + if (!insn_aux->map_ptr) + insn_aux->map_ptr = meta.map_ptr; + else if (insn_aux->map_ptr != meta.map_ptr) + insn_aux->map_ptr = BPF_MAP_PTR_POISON; + } else { + verbose(""unknown return type %d of func %s#%d\n"", + fn->ret_type, func_id_name(func_id), func_id); + return -EINVAL; + } + + err = check_map_func_compatibility(meta.map_ptr, func_id); + if (err) + return err; + + if (changes_data) + clear_all_pkt_pointers(env); + return 0; +} +","@@ -298,7 +298,8 @@ static const char *const bpf_jmp_string[16] = { + [BPF_EXIT >> 4] = ""exit"", + }; + +-static void print_bpf_insn(struct bpf_insn *insn) ++static void print_bpf_insn(const struct bpf_verifier_env *env, ++ const struct bpf_insn *insn) + { + u8 class = BPF_CLASS(insn->code); + +@@ -362,9 +363,19 @@ static void print_bpf_insn(struct bpf_insn *insn) + insn->code, + bpf_ldst_string[BPF_SIZE(insn->code) >> 3], + insn->src_reg, insn->imm); +- } else if (BPF_MODE(insn->code) == BPF_IMM) { +- verbose(""(%02x) r%d = 0x%x\n"", +- insn->code, insn->dst_reg, insn->imm); ++ } else if (BPF_MODE(insn->code) == BPF_IMM && ++ BPF_SIZE(insn->code) == BPF_DW) { ++ /* At this point, we already made sure that the second ++ * part of the ldimm64 insn is accessible. ++ */ ++ u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; ++ bool map_ptr = insn->src_reg == BPF_PSEUDO_MAP_FD; ++ ++ if (map_ptr && !env->allow_ptr_leaks) ++ imm = 0; ++ ++ verbose(""(%02x) r%d = 0x%llx\n"", insn->code, ++ insn->dst_reg, (unsigned long long)imm); + } else { + verbose(""BUG_ld_%02x\n"", insn->code); + return; +@@ -2853,7 +2864,7 @@ static int do_check(struct bpf_verifier_env *env) + + if (log_level) { + verbose(""%d: "", insn_idx); +- print_bpf_insn(insn); ++ print_bpf_insn(env, insn); + } + + err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx);",1039,1370,2048 +18229,"av_cold void ff_idctdsp_init(IDCTDSPContext *c, AVCodecContext *avctx) +{ + const unsigned high_bit_depth = avctx->bits_per_raw_sample > 8; + + if (avctx->lowres==1) { + c->idct_put = ff_jref_idct4_put; + c->idct_add = ff_jref_idct4_add; + c->idct = ff_j_rev_dct4; + c->perm_type = FF_IDCT_PERM_NONE; + } else if (avctx->lowres==2) { + c->idct_put = ff_jref_idct2_put; + c->idct_add = ff_jref_idct2_add; + c->idct = ff_j_rev_dct2; + c->perm_type = FF_IDCT_PERM_NONE; + } else if (avctx->lowres==3) { + c->idct_put = ff_jref_idct1_put; + c->idct_add = ff_jref_idct1_add; + c->idct = ff_j_rev_dct1; + c->perm_type = FF_IDCT_PERM_NONE; + } else { + if (avctx->bits_per_raw_sample == 10 || avctx->bits_per_raw_sample == 9) { + /* 10-bit MPEG-4 Simple Studio Profile requires a higher precision IDCT + However, it only uses idct_put */ + if (avctx->codec_id == AV_CODEC_ID_MPEG4 && avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO) + c->idct_put = ff_simple_idct_put_int32_10bit; + else { + c->idct_put = ff_simple_idct_put_int16_10bit; + c->idct_add = ff_simple_idct_add_int16_10bit; + c->idct = ff_simple_idct_int16_10bit; + } + c->perm_type = FF_IDCT_PERM_NONE; + } else if (avctx->bits_per_raw_sample == 12) { + c->idct_put = ff_simple_idct_put_int16_12bit; + c->idct_add = ff_simple_idct_add_int16_12bit; + c->idct = ff_simple_idct_int16_12bit; + c->perm_type = FF_IDCT_PERM_NONE; + } else { + if (avctx->idct_algo == FF_IDCT_INT) { + c->idct_put = ff_jref_idct_put; + c->idct_add = ff_jref_idct_add; + c->idct = ff_j_rev_dct; + c->perm_type = FF_IDCT_PERM_LIBMPEG2; +#if CONFIG_FAANIDCT + } else if (avctx->idct_algo == FF_IDCT_FAAN) { + c->idct_put = ff_faanidct_put; + c->idct_add = ff_faanidct_add; + c->idct = ff_faanidct; + c->perm_type = FF_IDCT_PERM_NONE; +#endif /* CONFIG_FAANIDCT */ + } else { // accurate/default + /* Be sure FF_IDCT_NONE will select this one, since it uses FF_IDCT_PERM_NONE */ + c->idct_put = ff_simple_idct_put_int16_8bit; + c->idct_add = ff_simple_idct_add_int16_8bit; + c->idct = ff_simple_idct_int16_8bit; + c->perm_type = FF_IDCT_PERM_NONE; + } + } + } + + c->put_pixels_clamped = ff_put_pixels_clamped_c; + c->put_signed_pixels_clamped = put_signed_pixels_clamped_c; + c->add_pixels_clamped = ff_add_pixels_clamped_c; + + if (CONFIG_MPEG4_DECODER && avctx->idct_algo == FF_IDCT_XVID) + ff_xvid_idct_init(c, avctx); + + if (ARCH_AARCH64) + ff_idctdsp_init_aarch64(c, avctx, high_bit_depth); + if (ARCH_ALPHA) + ff_idctdsp_init_alpha(c, avctx, high_bit_depth); + if (ARCH_ARM) + ff_idctdsp_init_arm(c, avctx, high_bit_depth); + if (ARCH_PPC) + ff_idctdsp_init_ppc(c, avctx, high_bit_depth); + if (ARCH_X86) + ff_idctdsp_init_x86(c, avctx, high_bit_depth); + if (ARCH_MIPS) + ff_idctdsp_init_mips(c, avctx, high_bit_depth); + + ff_init_scantable_permutation(c->idct_permutation, + c->perm_type); +} +",1,"av_cold void ff_idctdsp_init(IDCTDSPContext *c, AVCodecContext *avctx) +{ + const unsigned high_bit_depth = avctx->bits_per_raw_sample > 8; + + if (avctx->lowres==1) { + c->idct_put = ff_jref_idct4_put; + c->idct_add = ff_jref_idct4_add; + c->idct = ff_j_rev_dct4; + c->perm_type = FF_IDCT_PERM_NONE; + } else if (avctx->lowres==2) { + c->idct_put = ff_jref_idct2_put; + c->idct_add = ff_jref_idct2_add; + c->idct = ff_j_rev_dct2; + c->perm_type = FF_IDCT_PERM_NONE; + } else if (avctx->lowres==3) { + c->idct_put = ff_jref_idct1_put; + c->idct_add = ff_jref_idct1_add; + c->idct = ff_j_rev_dct1; + c->perm_type = FF_IDCT_PERM_NONE; + } else { + if (avctx->bits_per_raw_sample == 10 || avctx->bits_per_raw_sample == 9) { + /* 10-bit MPEG-4 Simple Studio Profile requires a higher precision IDCT + However, it only uses idct_put */ + if (c->mpeg4_studio_profile) + c->idct_put = ff_simple_idct_put_int32_10bit; + else { + c->idct_put = ff_simple_idct_put_int16_10bit; + c->idct_add = ff_simple_idct_add_int16_10bit; + c->idct = ff_simple_idct_int16_10bit; + } + c->perm_type = FF_IDCT_PERM_NONE; + } else if (avctx->bits_per_raw_sample == 12) { + c->idct_put = ff_simple_idct_put_int16_12bit; + c->idct_add = ff_simple_idct_add_int16_12bit; + c->idct = ff_simple_idct_int16_12bit; + c->perm_type = FF_IDCT_PERM_NONE; + } else { + if (avctx->idct_algo == FF_IDCT_INT) { + c->idct_put = ff_jref_idct_put; + c->idct_add = ff_jref_idct_add; + c->idct = ff_j_rev_dct; + c->perm_type = FF_IDCT_PERM_LIBMPEG2; +#if CONFIG_FAANIDCT + } else if (avctx->idct_algo == FF_IDCT_FAAN) { + c->idct_put = ff_faanidct_put; + c->idct_add = ff_faanidct_add; + c->idct = ff_faanidct; + c->perm_type = FF_IDCT_PERM_NONE; +#endif /* CONFIG_FAANIDCT */ + } else { // accurate/default + /* Be sure FF_IDCT_NONE will select this one, since it uses FF_IDCT_PERM_NONE */ + c->idct_put = ff_simple_idct_put_int16_8bit; + c->idct_add = ff_simple_idct_add_int16_8bit; + c->idct = ff_simple_idct_int16_8bit; + c->perm_type = FF_IDCT_PERM_NONE; + } + } + } + + c->put_pixels_clamped = ff_put_pixels_clamped_c; + c->put_signed_pixels_clamped = put_signed_pixels_clamped_c; + c->add_pixels_clamped = ff_add_pixels_clamped_c; + + if (CONFIG_MPEG4_DECODER && avctx->idct_algo == FF_IDCT_XVID) + ff_xvid_idct_init(c, avctx); + + if (ARCH_AARCH64) + ff_idctdsp_init_aarch64(c, avctx, high_bit_depth); + if (ARCH_ALPHA) + ff_idctdsp_init_alpha(c, avctx, high_bit_depth); + if (ARCH_ARM) + ff_idctdsp_init_arm(c, avctx, high_bit_depth); + if (ARCH_PPC) + ff_idctdsp_init_ppc(c, avctx, high_bit_depth); + if (ARCH_X86) + ff_idctdsp_init_x86(c, avctx, high_bit_depth); + if (ARCH_MIPS) + ff_idctdsp_init_mips(c, avctx, high_bit_depth); + + ff_init_scantable_permutation(c->idct_permutation, + c->perm_type); +} +","@@ -258,7 +258,7 @@ av_cold void ff_idctdsp_init(IDCTDSPContext *c, AVCodecContext *avctx) + if (avctx->bits_per_raw_sample == 10 || avctx->bits_per_raw_sample == 9) { + /* 10-bit MPEG-4 Simple Studio Profile requires a higher precision IDCT + However, it only uses idct_put */ +- if (avctx->codec_id == AV_CODEC_ID_MPEG4 && avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO) ++ if (c->mpeg4_studio_profile) + c->idct_put = ff_simple_idct_put_int32_10bit; + else { + c->idct_put = ff_simple_idct_put_int16_10bit;",1073,1404,2048 +7828,"static int itacns_add_keyset(sc_pkcs15_card_t *p15card, + const char *label, int sec_env, sc_pkcs15_id_t *cert_id, + const char *pubkey_path, const char *prkey_path, + unsigned int pubkey_usage_flags, unsigned int prkey_usage_flags, + u8 pin_ref) +{ + int r; + sc_path_t path; + sc_path_t *private_path = NULL; + char pinlabel[16]; + int fake_puk_authid, pin_flags; + + /* This is hard-coded, for the time being. */ + int modulus_length = 1024; + + /* Public key; not really needed */ + /* FIXME: set usage according to the certificate. */ + if (pubkey_path) { + sc_format_path(pubkey_path, &path); + r = itacns_add_pubkey(p15card, &path, cert_id, label, + pubkey_usage_flags, sec_env, 0, &modulus_length); + SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r, + ""Could not add public key""); + } + + /* + * FIXME: usage should be inferred from the X.509 certificate, and not + * from whether the key needs Secure Messaging. + */ + if (prkey_path) { + sc_format_path(prkey_path, &path); + private_path = &path; + } + r = itacns_add_prkey(p15card, cert_id, label, SC_PKCS15_TYPE_PRKEY_RSA, + modulus_length, + prkey_usage_flags, + private_path, sec_env, cert_id, SC_PKCS15_CO_FLAG_PRIVATE); + SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r, + ""Could not add private key""); + + /* PIN and PUK */ + strlcpy(pinlabel, ""PIN "", sizeof(pinlabel)); + strlcat(pinlabel, label, sizeof(pinlabel)); + + /* We are making up ID 0x90+ to link the PIN and the PUK. */ + fake_puk_authid = 0x90 + pin_ref; + pin_flags = SC_PKCS15_PIN_FLAG_CASE_SENSITIVE + | SC_PKCS15_PIN_FLAG_INITIALIZED; + r = itacns_add_pin(p15card, pinlabel, sec_env, fake_puk_authid, pin_ref, + private_path, pin_flags); + SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r, + ""Could not add PIN""); + + strlcpy(pinlabel, ""PUK "", sizeof(pinlabel)); + strlcat(pinlabel, label, sizeof(pinlabel)); + /* + * Looking at pkcs15-tcos.c and pkcs15-framework.c, it seems that the + * right thing to do here is to define a PUK as a SO PIN. Can anybody + * comment on this? + */ + pin_flags |= SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN + | SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED; + r = itacns_add_pin(p15card, pinlabel, fake_puk_authid, 0, pin_ref+1, + private_path, pin_flags); + SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r, + ""Could not add PUK""); + + return 0; +} +",0,"static int itacns_add_keyset(sc_pkcs15_card_t *p15card, + const char *label, int sec_env, sc_pkcs15_id_t *cert_id, + const char *pubkey_path, const char *prkey_path, + unsigned int pubkey_usage_flags, unsigned int prkey_usage_flags, + u8 pin_ref) +{ + int r; + sc_path_t path; + sc_path_t *private_path = NULL; + char pinlabel[16]; + int fake_puk_authid, pin_flags; + + /* This is hard-coded, for the time being. */ + int modulus_length = 1024; + + /* Public key; not really needed */ + /* FIXME: set usage according to the certificate. */ + if (pubkey_path) { + sc_format_path(pubkey_path, &path); + r = itacns_add_pubkey(p15card, &path, cert_id, label, + pubkey_usage_flags, sec_env, 0, &modulus_length); + SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r, + ""Could not add public key""); + } + + /* + * FIXME: usage should be inferred from the X.509 certificate, and not + * from whether the key needs Secure Messaging. + */ + if (prkey_path) { + sc_format_path(prkey_path, &path); + private_path = &path; + } + r = itacns_add_prkey(p15card, cert_id, label, SC_PKCS15_TYPE_PRKEY_RSA, + modulus_length, + prkey_usage_flags, + private_path, sec_env, cert_id, SC_PKCS15_CO_FLAG_PRIVATE); + SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r, + ""Could not add private key""); + + /* PIN and PUK */ + strlcpy(pinlabel, ""PIN "", sizeof(pinlabel)); + strlcat(pinlabel, label, sizeof(pinlabel)); + + /* We are making up ID 0x90+ to link the PIN and the PUK. */ + fake_puk_authid = 0x90 + pin_ref; + pin_flags = SC_PKCS15_PIN_FLAG_CASE_SENSITIVE + | SC_PKCS15_PIN_FLAG_INITIALIZED; + r = itacns_add_pin(p15card, pinlabel, sec_env, fake_puk_authid, pin_ref, + private_path, pin_flags); + SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r, + ""Could not add PIN""); + + strlcpy(pinlabel, ""PUK "", sizeof(pinlabel)); + strlcat(pinlabel, label, sizeof(pinlabel)); + /* + * Looking at pkcs15-tcos.c and pkcs15-framework.c, it seems that the + * right thing to do here is to define a PUK as a SO PIN. Can anybody + * comment on this? + */ + pin_flags |= SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN + | SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED; + r = itacns_add_pin(p15card, pinlabel, fake_puk_authid, 0, pin_ref+1, + private_path, pin_flags); + SC_TEST_RET(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, r, + ""Could not add PUK""); + + return 0; +} +","@@ -550,6 +550,7 @@ static int itacns_add_data_files(sc_pkcs15_card_t *p15card) + sc_debug(p15card->card->ctx, SC_LOG_DEBUG_NORMAL, + ""Could not read EF_DatiPersonali: "" + ""keeping generic card name""); ++ return SC_SUCCESS; + } + + {",727,1058,2048 +7268,"static jpc_enc_rlvl_t *rlvl_create(jpc_enc_rlvl_t *rlvl, jpc_enc_cp_t *cp, + jpc_enc_tcmpt_t *tcmpt, jpc_tsfb_band_t *bandinfos) +{ + uint_fast16_t rlvlno; + uint_fast32_t tlprctlx; + uint_fast32_t tlprctly; + uint_fast32_t brprcbrx; + uint_fast32_t brprcbry; + uint_fast16_t bandno; + jpc_enc_band_t *band; + + /* Deduce the resolution level. */ + rlvlno = rlvl - tcmpt->rlvls; + + /* Initialize members required for error recovery. */ + rlvl->bands = 0; + rlvl->tcmpt = tcmpt; + + /* Compute the coordinates of the top-left and bottom-right + corners of the tile-component at this resolution. */ + rlvl->tlx = JPC_CEILDIVPOW2(jas_seq2d_xstart(tcmpt->data), tcmpt->numrlvls - + 1 - rlvlno); + rlvl->tly = JPC_CEILDIVPOW2(jas_seq2d_ystart(tcmpt->data), tcmpt->numrlvls - + 1 - rlvlno); + rlvl->brx = JPC_CEILDIVPOW2(jas_seq2d_xend(tcmpt->data), tcmpt->numrlvls - + 1 - rlvlno); + rlvl->bry = JPC_CEILDIVPOW2(jas_seq2d_yend(tcmpt->data), tcmpt->numrlvls - + 1 - rlvlno); + + if (rlvl->tlx >= rlvl->brx || rlvl->tly >= rlvl->bry) { + rlvl->numhprcs = 0; + rlvl->numvprcs = 0; + rlvl->numprcs = 0; + return rlvl; + } + + rlvl->numbands = (!rlvlno) ? 1 : 3; + rlvl->prcwidthexpn = cp->tccp.prcwidthexpns[rlvlno]; + rlvl->prcheightexpn = cp->tccp.prcheightexpns[rlvlno]; + if (!rlvlno) { + rlvl->cbgwidthexpn = rlvl->prcwidthexpn; + rlvl->cbgheightexpn = rlvl->prcheightexpn; + } else { + rlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1; + rlvl->cbgheightexpn = rlvl->prcheightexpn - 1; + } + rlvl->cblkwidthexpn = JAS_MIN(cp->tccp.cblkwidthexpn, rlvl->cbgwidthexpn); + rlvl->cblkheightexpn = JAS_MIN(cp->tccp.cblkheightexpn, rlvl->cbgheightexpn); + + /* Compute the number of precincts. */ + tlprctlx = JPC_FLOORTOMULTPOW2(rlvl->tlx, rlvl->prcwidthexpn); + tlprctly = JPC_FLOORTOMULTPOW2(rlvl->tly, rlvl->prcheightexpn); + brprcbrx = JPC_CEILTOMULTPOW2(rlvl->brx, rlvl->prcwidthexpn); + brprcbry = JPC_CEILTOMULTPOW2(rlvl->bry, rlvl->prcheightexpn); + rlvl->numhprcs = JPC_FLOORDIVPOW2(brprcbrx - tlprctlx, rlvl->prcwidthexpn); + rlvl->numvprcs = JPC_FLOORDIVPOW2(brprcbry - tlprctly, rlvl->prcheightexpn); + rlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs; + + if (!(rlvl->bands = jas_alloc2(rlvl->numbands, sizeof(jpc_enc_band_t)))) { + goto error; + } + for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; + ++bandno, ++band) { + band->prcs = 0; + band->data = 0; + band->rlvl = rlvl; + } + for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; + ++bandno, ++band) { + if (!band_create(band, cp, rlvl, bandinfos)) { + goto error; + } + } + + return rlvl; +error: + + rlvl_destroy(rlvl); + return 0; +} +",0,"static jpc_enc_rlvl_t *rlvl_create(jpc_enc_rlvl_t *rlvl, jpc_enc_cp_t *cp, + jpc_enc_tcmpt_t *tcmpt, jpc_tsfb_band_t *bandinfos) +{ + uint_fast16_t rlvlno; + uint_fast32_t tlprctlx; + uint_fast32_t tlprctly; + uint_fast32_t brprcbrx; + uint_fast32_t brprcbry; + uint_fast16_t bandno; + jpc_enc_band_t *band; + + /* Deduce the resolution level. */ + rlvlno = rlvl - tcmpt->rlvls; + + /* Initialize members required for error recovery. */ + rlvl->bands = 0; + rlvl->tcmpt = tcmpt; + + /* Compute the coordinates of the top-left and bottom-right + corners of the tile-component at this resolution. */ + rlvl->tlx = JPC_CEILDIVPOW2(jas_seq2d_xstart(tcmpt->data), tcmpt->numrlvls - + 1 - rlvlno); + rlvl->tly = JPC_CEILDIVPOW2(jas_seq2d_ystart(tcmpt->data), tcmpt->numrlvls - + 1 - rlvlno); + rlvl->brx = JPC_CEILDIVPOW2(jas_seq2d_xend(tcmpt->data), tcmpt->numrlvls - + 1 - rlvlno); + rlvl->bry = JPC_CEILDIVPOW2(jas_seq2d_yend(tcmpt->data), tcmpt->numrlvls - + 1 - rlvlno); + + if (rlvl->tlx >= rlvl->brx || rlvl->tly >= rlvl->bry) { + rlvl->numhprcs = 0; + rlvl->numvprcs = 0; + rlvl->numprcs = 0; + return rlvl; + } + + rlvl->numbands = (!rlvlno) ? 1 : 3; + rlvl->prcwidthexpn = cp->tccp.prcwidthexpns[rlvlno]; + rlvl->prcheightexpn = cp->tccp.prcheightexpns[rlvlno]; + if (!rlvlno) { + rlvl->cbgwidthexpn = rlvl->prcwidthexpn; + rlvl->cbgheightexpn = rlvl->prcheightexpn; + } else { + rlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1; + rlvl->cbgheightexpn = rlvl->prcheightexpn - 1; + } + rlvl->cblkwidthexpn = JAS_MIN(cp->tccp.cblkwidthexpn, rlvl->cbgwidthexpn); + rlvl->cblkheightexpn = JAS_MIN(cp->tccp.cblkheightexpn, rlvl->cbgheightexpn); + + /* Compute the number of precincts. */ + tlprctlx = JPC_FLOORTOMULTPOW2(rlvl->tlx, rlvl->prcwidthexpn); + tlprctly = JPC_FLOORTOMULTPOW2(rlvl->tly, rlvl->prcheightexpn); + brprcbrx = JPC_CEILTOMULTPOW2(rlvl->brx, rlvl->prcwidthexpn); + brprcbry = JPC_CEILTOMULTPOW2(rlvl->bry, rlvl->prcheightexpn); + rlvl->numhprcs = JPC_FLOORDIVPOW2(brprcbrx - tlprctlx, rlvl->prcwidthexpn); + rlvl->numvprcs = JPC_FLOORDIVPOW2(brprcbry - tlprctly, rlvl->prcheightexpn); + rlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs; + + if (!(rlvl->bands = jas_alloc2(rlvl->numbands, sizeof(jpc_enc_band_t)))) { + goto error; + } + for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; + ++bandno, ++band) { + band->prcs = 0; + band->data = 0; + band->rlvl = rlvl; + } + for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; + ++bandno, ++band) { + if (!band_create(band, cp, rlvl, bandinfos)) { + goto error; + } + } + + return rlvl; +error: + + rlvl_destroy(rlvl); + return 0; +} +","@@ -961,7 +961,7 @@ startoff = jas_stream_getrwcount(enc->out); + com = &enc->mrk->parms.com; + com->len = JAS_CAST(uint_fast16_t, strlen(buf)); + com->regid = JPC_COM_LATIN; +- if (!(com->data = JAS_CAST(uchar *, jas_strdup(buf)))) { ++ if (!(com->data = JAS_CAST(jas_uchar *, jas_strdup(buf)))) { + abort(); + } + if (jpc_putms(enc->out, enc->cstate, enc->mrk)) {",1095,1426,2048 +18010,"static MagickBooleanType Get8BIMProperty(const Image *image,const char *key, + ExceptionInfo *exception) +{ + char + *attribute, + format[MagickPathExtent], + name[MagickPathExtent], + *resource; + + const StringInfo + *profile; + + const unsigned char + *info; + + long + start, + stop; + + MagickBooleanType + status; + + register ssize_t + i; + + size_t + length; + + ssize_t + count, + id, + sub_number; + + /* + There are no newlines in path names, so it's safe as terminator. + */ + profile=GetImageProfile(image,""8bim""); + if (profile == (StringInfo *) NULL) + return(MagickFalse); + count=(ssize_t) sscanf(key,""8BIM:%ld,%ld:%1024[^\n]\n%1024[^\n]"",&start,&stop, + name,format); + if ((count != 2) && (count != 3) && (count != 4)) + return(MagickFalse); + if (count < 4) + (void) CopyMagickString(format,""SVG"",MagickPathExtent); + if (count < 3) + *name='\0'; + sub_number=1; + if (*name == '#') + sub_number=(ssize_t) StringToLong(&name[1]); + sub_number=MagickMax(sub_number,1L); + resource=(char *) NULL; + status=MagickFalse; + length=GetStringInfoLength(profile); + info=GetStringInfoDatum(profile); + while ((length > 0) && (status == MagickFalse)) + { + if (ReadPropertyByte(&info,&length) != (unsigned char) '8') + continue; + if (ReadPropertyByte(&info,&length) != (unsigned char) 'B') + continue; + if (ReadPropertyByte(&info,&length) != (unsigned char) 'I') + continue; + if (ReadPropertyByte(&info,&length) != (unsigned char) 'M') + continue; + id=(ssize_t) ReadPropertyMSBShort(&info,&length); + if (id < (ssize_t) start) + continue; + if (id > (ssize_t) stop) + continue; + if (resource != (char *) NULL) + resource=DestroyString(resource); + count=(ssize_t) ReadPropertyByte(&info,&length); + if ((count != 0) && ((size_t) count <= length)) + { + resource=(char *) NULL; + if (~((size_t) count) >= (MagickPathExtent-1)) + resource=(char *) AcquireQuantumMemory((size_t) count+ + MagickPathExtent,sizeof(*resource)); + if (resource != (char *) NULL) + { + for (i=0; i < (ssize_t) count; i++) + resource[i]=(char) ReadPropertyByte(&info,&length); + resource[count]='\0'; + } + } + if ((count & 0x01) == 0) + (void) ReadPropertyByte(&info,&length); + count=(ssize_t) ReadPropertyMSBLong(&info,&length); + if ((*name != '\0') && (*name != '#')) + if ((resource == (char *) NULL) || (LocaleCompare(name,resource) != 0)) + { + /* + No name match, scroll forward and try next. + */ + info+=count; + length-=MagickMin(count,(ssize_t) length); + continue; + } + if ((*name == '#') && (sub_number != 1)) + { + /* + No numbered match, scroll forward and try next. + */ + sub_number--; + info+=count; + length-=MagickMin(count,(ssize_t) length); + continue; + } + /* + We have the resource of interest. + */ + attribute=(char *) NULL; + if (~((size_t) count) >= (MagickPathExtent-1)) + attribute=(char *) AcquireQuantumMemory((size_t) count+MagickPathExtent, + sizeof(*attribute)); + if (attribute != (char *) NULL) + { + (void) CopyMagickMemory(attribute,(char *) info,(size_t) count); + attribute[count]='\0'; + info+=count; + length-=MagickMin(count,(ssize_t) length); + if ((id <= 1999) || (id >= 2999)) + (void) SetImageProperty((Image *) image,key,(const char *) + attribute,exception); + else + { + char + *path; + + if (LocaleCompare(format,""svg"") == 0) + path=TraceSVGClippath((unsigned char *) attribute,(size_t) count, + image->columns,image->rows); + else + path=TracePSClippath((unsigned char *) attribute,(size_t) count); + (void) SetImageProperty((Image *) image,key,(const char *) path, + exception); + path=DestroyString(path); + } + attribute=DestroyString(attribute); + status=MagickTrue; + } + } + if (resource != (char *) NULL) + resource=DestroyString(resource); + return(status); +} +",1,"static MagickBooleanType Get8BIMProperty(const Image *image,const char *key, + ExceptionInfo *exception) +{ + char + *attribute, + format[MagickPathExtent], + name[MagickPathExtent], + *resource; + + const StringInfo + *profile; + + const unsigned char + *info; + + long + start, + stop; + + MagickBooleanType + status; + + register ssize_t + i; + + size_t + length; + + ssize_t + count, + id, + sub_number; + + /* + There are no newlines in path names, so it's safe as terminator. + */ + profile=GetImageProfile(image,""8bim""); + if (profile == (StringInfo *) NULL) + return(MagickFalse); + count=(ssize_t) sscanf(key,""8BIM:%ld,%ld:%1024[^\n]\n%1024[^\n]"",&start,&stop, + name,format); + if ((count != 2) && (count != 3) && (count != 4)) + return(MagickFalse); + if (count < 4) + (void) CopyMagickString(format,""SVG"",MagickPathExtent); + if (count < 3) + *name='\0'; + sub_number=1; + if (*name == '#') + sub_number=(ssize_t) StringToLong(&name[1]); + sub_number=MagickMax(sub_number,1L); + resource=(char *) NULL; + status=MagickFalse; + length=GetStringInfoLength(profile); + info=GetStringInfoDatum(profile); + while ((length > 0) && (status == MagickFalse)) + { + if (ReadPropertyByte(&info,&length) != (unsigned char) '8') + continue; + if (ReadPropertyByte(&info,&length) != (unsigned char) 'B') + continue; + if (ReadPropertyByte(&info,&length) != (unsigned char) 'I') + continue; + if (ReadPropertyByte(&info,&length) != (unsigned char) 'M') + continue; + id=(ssize_t) ReadPropertyMSBShort(&info,&length); + if (id < (ssize_t) start) + continue; + if (id > (ssize_t) stop) + continue; + if (resource != (char *) NULL) + resource=DestroyString(resource); + count=(ssize_t) ReadPropertyByte(&info,&length); + if ((count != 0) && ((size_t) count <= length)) + { + resource=(char *) NULL; + if (~((size_t) count) >= (MagickPathExtent-1)) + resource=(char *) AcquireQuantumMemory((size_t) count+ + MagickPathExtent,sizeof(*resource)); + if (resource != (char *) NULL) + { + for (i=0; i < (ssize_t) count; i++) + resource[i]=(char) ReadPropertyByte(&info,&length); + resource[count]='\0'; + } + } + if ((count & 0x01) == 0) + (void) ReadPropertyByte(&info,&length); + count=(ssize_t) ReadPropertyMSBLong(&info,&length); + if ((count < 0) || ((size_t) count > length)) + { + length=0; + continue; + } + if ((*name != '\0') && (*name != '#')) + if ((resource == (char *) NULL) || (LocaleCompare(name,resource) != 0)) + { + /* + No name match, scroll forward and try next. + */ + info+=count; + length-=MagickMin(count,(ssize_t) length); + continue; + } + if ((*name == '#') && (sub_number != 1)) + { + /* + No numbered match, scroll forward and try next. + */ + sub_number--; + info+=count; + length-=MagickMin(count,(ssize_t) length); + continue; + } + /* + We have the resource of interest. + */ + attribute=(char *) NULL; + if (~((size_t) count) >= (MagickPathExtent-1)) + attribute=(char *) AcquireQuantumMemory((size_t) count+MagickPathExtent, + sizeof(*attribute)); + if (attribute != (char *) NULL) + { + (void) CopyMagickMemory(attribute,(char *) info,(size_t) count); + attribute[count]='\0'; + info+=count; + length-=MagickMin(count,(ssize_t) length); + if ((id <= 1999) || (id >= 2999)) + (void) SetImageProperty((Image *) image,key,(const char *) + attribute,exception); + else + { + char + *path; + + if (LocaleCompare(format,""svg"") == 0) + path=TraceSVGClippath((unsigned char *) attribute,(size_t) count, + image->columns,image->rows); + else + path=TracePSClippath((unsigned char *) attribute,(size_t) count); + (void) SetImageProperty((Image *) image,key,(const char *) path, + exception); + path=DestroyString(path); + } + attribute=DestroyString(attribute); + status=MagickTrue; + } + } + if (resource != (char *) NULL) + resource=DestroyString(resource); + return(status); +} +","@@ -665,6 +665,11 @@ static MagickBooleanType Get8BIMProperty(const Image *image,const char *key, + if ((count & 0x01) == 0) + (void) ReadPropertyByte(&info,&length); + count=(ssize_t) ReadPropertyMSBLong(&info,&length); ++ if ((count < 0) || ((size_t) count > length)) ++ { ++ length=0; ++ continue; ++ } + if ((*name != '\0') && (*name != '#')) + if ((resource == (char *) NULL) || (LocaleCompare(name,resource) != 0)) + {",1134,1465,2048 +5250,"dissect_DEVMODE(tvbuff_t *tvb, int offset, packet_info *pinfo, + proto_tree *tree, dcerpc_info *di, guint8 *drep) +{ + proto_item *item; + proto_tree *subtree; + guint16 driver_extra; + gint16 print_quality; + guint32 fields; + int struct_start = offset; + + if (di->conformant_run) + return offset; + + subtree = proto_tree_add_subtree(tree, tvb, offset, 0, ett_DEVMODE, &item, ""Devicemode""); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, hf_devmode_size, + NULL); + + /* The device name is stored in a 32-wchar buffer */ + + dissect_spoolss_uint16uni(tvb, offset, pinfo, subtree, drep, NULL, hf_devmode_devicename); + offset += 64; + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_spec_version, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_driver_version, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_size2, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_driver_extra_len, &driver_extra); + + offset = dissect_DEVMODE_fields( + tvb, offset, pinfo, subtree, di, drep, &fields); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_orientation, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_paper_size, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_paper_length, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_paper_width, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_scale, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_copies, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_default_source, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, NULL, di, drep, + hf_devmode_print_quality, &print_quality); + + if (print_quality < 0) + proto_tree_add_item( + subtree, hf_devmode_print_quality, tvb, + offset - 2, 2, DREP_ENC_INTEGER(drep)); + else + proto_tree_add_uint_format_value( + subtree, hf_devmode_print_quality, tvb, offset - 4, 4, + print_quality, ""%d dpi"", print_quality); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_color, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_duplex, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_y_resolution, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_tt_option, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_collate, NULL); + + dissect_spoolss_uint16uni(tvb, offset, pinfo, subtree, drep, NULL, hf_devmode_form_name); + offset += 64; + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_log_pixels, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_bits_per_pel, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_pels_width, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_pels_height, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_display_flags, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_display_freq, NULL); + + /* TODO: Some of the remaining fields are optional. See + rpc_parse/parse_spoolss.c in the Samba source for details. */ + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_icm_method, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_icm_intent, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_media_type, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_dither_type, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_reserved1, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_reserved2, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_panning_width, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_panning_height, NULL); + + if (driver_extra) + offset = dissect_ndr_uint8s( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_driver_extra, driver_extra, NULL); + + proto_item_set_len(item, offset - struct_start); + + return offset; +} +",0,"dissect_DEVMODE(tvbuff_t *tvb, int offset, packet_info *pinfo, + proto_tree *tree, dcerpc_info *di, guint8 *drep) +{ + proto_item *item; + proto_tree *subtree; + guint16 driver_extra; + gint16 print_quality; + guint32 fields; + int struct_start = offset; + + if (di->conformant_run) + return offset; + + subtree = proto_tree_add_subtree(tree, tvb, offset, 0, ett_DEVMODE, &item, ""Devicemode""); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, hf_devmode_size, + NULL); + + /* The device name is stored in a 32-wchar buffer */ + + dissect_spoolss_uint16uni(tvb, offset, pinfo, subtree, drep, NULL, hf_devmode_devicename); + offset += 64; + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_spec_version, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_driver_version, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_size2, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_driver_extra_len, &driver_extra); + + offset = dissect_DEVMODE_fields( + tvb, offset, pinfo, subtree, di, drep, &fields); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_orientation, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_paper_size, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_paper_length, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_paper_width, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_scale, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_copies, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_default_source, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, NULL, di, drep, + hf_devmode_print_quality, &print_quality); + + if (print_quality < 0) + proto_tree_add_item( + subtree, hf_devmode_print_quality, tvb, + offset - 2, 2, DREP_ENC_INTEGER(drep)); + else + proto_tree_add_uint_format_value( + subtree, hf_devmode_print_quality, tvb, offset - 4, 4, + print_quality, ""%d dpi"", print_quality); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_color, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_duplex, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_y_resolution, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_tt_option, NULL); + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_collate, NULL); + + dissect_spoolss_uint16uni(tvb, offset, pinfo, subtree, drep, NULL, hf_devmode_form_name); + offset += 64; + + offset = dissect_ndr_uint16( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_log_pixels, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_bits_per_pel, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_pels_width, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_pels_height, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_display_flags, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_display_freq, NULL); + + /* TODO: Some of the remaining fields are optional. See + rpc_parse/parse_spoolss.c in the Samba source for details. */ + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_icm_method, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_icm_intent, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_media_type, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_dither_type, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_reserved1, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_reserved2, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_panning_width, NULL); + + offset = dissect_ndr_uint32( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_panning_height, NULL); + + if (driver_extra) + offset = dissect_ndr_uint8s( + tvb, offset, pinfo, subtree, di, drep, + hf_devmode_driver_extra, driver_extra, NULL); + + proto_item_set_len(item, offset - struct_start); + + return offset; +} +","@@ -1090,7 +1090,7 @@ dissect_spoolss_uint16uni(tvbuff_t *tvb, int offset, packet_info *pinfo _U_, + + /* Get remaining data in buffer as a string */ + +- remaining = tvb_captured_length_remaining(tvb, offset); ++ remaining = tvb_reported_length_remaining(tvb, offset); + if (remaining <= 0) { + if (data) + *data = g_strdup(""""); +@@ -6198,9 +6198,10 @@ dissect_spoolss_keybuffer(tvbuff_t *tvb, int offset, packet_info *pinfo, + end_offset = tvb_reported_length_remaining(tvb, offset) + 1; + } + +- while (offset < end_offset) ++ while (offset > 0 && offset < end_offset) { + offset = dissect_spoolss_uint16uni( + tvb, offset, pinfo, tree, drep, NULL, hf_keybuffer); ++ } + + return offset; + }",1583,1914,2048 +2943,"static void qeth_flush_buffers(struct qeth_qdio_out_q *queue, int index, + int count) +{ + struct qeth_qdio_out_buffer *buf; + int rc; + int i; + unsigned int qdio_flags; + + for (i = index; i < index + count; ++i) { + int bidx = i % QDIO_MAX_BUFFERS_PER_Q; + buf = queue->bufs[bidx]; + buf->buffer->element[buf->next_element_to_fill - 1].eflags |= + SBAL_EFLAGS_LAST_ENTRY; + + if (queue->bufstates) + queue->bufstates[bidx].user = buf; + + if (queue->card->info.type == QETH_CARD_TYPE_IQD) + continue; + + if (!queue->do_pack) { + if ((atomic_read(&queue->used_buffers) >= + (QETH_HIGH_WATERMARK_PACK - + QETH_WATERMARK_PACK_FUZZ)) && + !atomic_read(&queue->set_pci_flags_count)) { + /* it's likely that we'll go to packing + * mode soon */ + atomic_inc(&queue->set_pci_flags_count); + buf->buffer->element[0].sflags |= SBAL_SFLAGS0_PCI_REQ; + } + } else { + if (!atomic_read(&queue->set_pci_flags_count)) { + /* + * there's no outstanding PCI any more, so we + * have to request a PCI to be sure the the PCI + * will wake at some time in the future then we + * can flush packed buffers that might still be + * hanging around, which can happen if no + * further send was requested by the stack + */ + atomic_inc(&queue->set_pci_flags_count); + buf->buffer->element[0].sflags |= SBAL_SFLAGS0_PCI_REQ; + } + } + } + + queue->card->dev->trans_start = jiffies; + if (queue->card->options.performance_stats) { + queue->card->perf_stats.outbound_do_qdio_cnt++; + queue->card->perf_stats.outbound_do_qdio_start_time = + qeth_get_micros(); + } + qdio_flags = QDIO_FLAG_SYNC_OUTPUT; + if (atomic_read(&queue->set_pci_flags_count)) + qdio_flags |= QDIO_FLAG_PCI_OUT; + rc = do_QDIO(CARD_DDEV(queue->card), qdio_flags, + queue->queue_no, index, count); + if (queue->card->options.performance_stats) + queue->card->perf_stats.outbound_do_qdio_time += + qeth_get_micros() - + queue->card->perf_stats.outbound_do_qdio_start_time; + atomic_add(count, &queue->used_buffers); + if (rc) { + queue->card->stats.tx_errors += count; + /* ignore temporary SIGA errors without busy condition */ + if (rc == -ENOBUFS) + return; + QETH_CARD_TEXT(queue->card, 2, ""flushbuf""); + QETH_CARD_TEXT_(queue->card, 2, "" q%d"", queue->queue_no); + QETH_CARD_TEXT_(queue->card, 2, "" idx%d"", index); + QETH_CARD_TEXT_(queue->card, 2, "" c%d"", count); + QETH_CARD_TEXT_(queue->card, 2, "" err%d"", rc); + + /* this must not happen under normal circumstances. if it + * happens something is really wrong -> recover */ + qeth_schedule_recovery(queue->card); + return; + } + if (queue->card->options.performance_stats) + queue->card->perf_stats.bufs_sent += count; +} +",0,"static void qeth_flush_buffers(struct qeth_qdio_out_q *queue, int index, + int count) +{ + struct qeth_qdio_out_buffer *buf; + int rc; + int i; + unsigned int qdio_flags; + + for (i = index; i < index + count; ++i) { + int bidx = i % QDIO_MAX_BUFFERS_PER_Q; + buf = queue->bufs[bidx]; + buf->buffer->element[buf->next_element_to_fill - 1].eflags |= + SBAL_EFLAGS_LAST_ENTRY; + + if (queue->bufstates) + queue->bufstates[bidx].user = buf; + + if (queue->card->info.type == QETH_CARD_TYPE_IQD) + continue; + + if (!queue->do_pack) { + if ((atomic_read(&queue->used_buffers) >= + (QETH_HIGH_WATERMARK_PACK - + QETH_WATERMARK_PACK_FUZZ)) && + !atomic_read(&queue->set_pci_flags_count)) { + /* it's likely that we'll go to packing + * mode soon */ + atomic_inc(&queue->set_pci_flags_count); + buf->buffer->element[0].sflags |= SBAL_SFLAGS0_PCI_REQ; + } + } else { + if (!atomic_read(&queue->set_pci_flags_count)) { + /* + * there's no outstanding PCI any more, so we + * have to request a PCI to be sure the the PCI + * will wake at some time in the future then we + * can flush packed buffers that might still be + * hanging around, which can happen if no + * further send was requested by the stack + */ + atomic_inc(&queue->set_pci_flags_count); + buf->buffer->element[0].sflags |= SBAL_SFLAGS0_PCI_REQ; + } + } + } + + queue->card->dev->trans_start = jiffies; + if (queue->card->options.performance_stats) { + queue->card->perf_stats.outbound_do_qdio_cnt++; + queue->card->perf_stats.outbound_do_qdio_start_time = + qeth_get_micros(); + } + qdio_flags = QDIO_FLAG_SYNC_OUTPUT; + if (atomic_read(&queue->set_pci_flags_count)) + qdio_flags |= QDIO_FLAG_PCI_OUT; + rc = do_QDIO(CARD_DDEV(queue->card), qdio_flags, + queue->queue_no, index, count); + if (queue->card->options.performance_stats) + queue->card->perf_stats.outbound_do_qdio_time += + qeth_get_micros() - + queue->card->perf_stats.outbound_do_qdio_start_time; + atomic_add(count, &queue->used_buffers); + if (rc) { + queue->card->stats.tx_errors += count; + /* ignore temporary SIGA errors without busy condition */ + if (rc == -ENOBUFS) + return; + QETH_CARD_TEXT(queue->card, 2, ""flushbuf""); + QETH_CARD_TEXT_(queue->card, 2, "" q%d"", queue->queue_no); + QETH_CARD_TEXT_(queue->card, 2, "" idx%d"", index); + QETH_CARD_TEXT_(queue->card, 2, "" c%d"", count); + QETH_CARD_TEXT_(queue->card, 2, "" err%d"", rc); + + /* this must not happen under normal circumstances. if it + * happens something is really wrong -> recover */ + qeth_schedule_recovery(queue->card); + return; + } + if (queue->card->options.performance_stats) + queue->card->perf_stats.bufs_sent += count; +} +","@@ -4451,7 +4451,7 @@ int qeth_snmp_command(struct qeth_card *card, char __user *udata) + struct qeth_cmd_buffer *iob; + struct qeth_ipa_cmd *cmd; + struct qeth_snmp_ureq *ureq; +- int req_len; ++ unsigned int req_len; + struct qeth_arp_query_info qinfo = {0, }; + int rc = 0; + +@@ -4467,6 +4467,10 @@ int qeth_snmp_command(struct qeth_card *card, char __user *udata) + /* skip 4 bytes (data_len struct member) to get req_len */ + if (copy_from_user(&req_len, udata + sizeof(int), sizeof(int))) + return -EFAULT; ++ if (req_len > (QETH_BUFSIZE - IPA_PDU_HEADER_SIZE - ++ sizeof(struct qeth_ipacmd_hdr) - ++ sizeof(struct qeth_ipacmd_setadpparms_hdr))) ++ return -EINVAL; + ureq = memdup_user(udata, req_len + sizeof(struct qeth_snmp_ureq_hdr)); + if (IS_ERR(ureq)) { + QETH_CARD_TEXT(card, 2, ""snmpnome"");",780,1111,2048 +7472,"enum delta_result_type do_add_delta(conn *c, const char *key, const size_t nkey, + const bool incr, const int64_t delta, + char *buf, uint64_t *cas, + const uint32_t hv) { + char *ptr; + uint64_t value; + int res; + item *it; + + it = do_item_get(key, nkey, hv, c, DONT_UPDATE); + if (!it) { + return DELTA_ITEM_NOT_FOUND; + } + + /* Can't delta zero byte values. 2-byte are the ""\r\n"" */ + /* Also can't delta for chunked items. Too large to be a number */ + if (it->nbytes <= 2 || (it->it_flags & ITEM_CHUNKED) != 0) { + return NON_NUMERIC; + } + + if (cas != NULL && *cas != 0 && ITEM_get_cas(it) != *cas) { + do_item_remove(it); + return DELTA_ITEM_CAS_MISMATCH; + } + + ptr = ITEM_data(it); + + if (!safe_strtoull(ptr, &value)) { + do_item_remove(it); + return NON_NUMERIC; + } + + if (incr) { + value += delta; + MEMCACHED_COMMAND_INCR(c->sfd, ITEM_key(it), it->nkey, value); + } else { + if(delta > value) { + value = 0; + } else { + value -= delta; + } + MEMCACHED_COMMAND_DECR(c->sfd, ITEM_key(it), it->nkey, value); + } + + pthread_mutex_lock(&c->thread->stats.mutex); + if (incr) { + c->thread->stats.slab_stats[ITEM_clsid(it)].incr_hits++; + } else { + c->thread->stats.slab_stats[ITEM_clsid(it)].decr_hits++; + } + pthread_mutex_unlock(&c->thread->stats.mutex); + + snprintf(buf, INCR_MAX_STORAGE_LEN, ""%llu"", (unsigned long long)value); + res = strlen(buf); + /* refcount == 2 means we are the only ones holding the item, and it is + * linked. We hold the item's lock in this function, so refcount cannot + * increase. */ + if (res + 2 <= it->nbytes && it->refcount == 2) { /* replace in-place */ + /* When changing the value without replacing the item, we + need to update the CAS on the existing item. */ + /* We also need to fiddle it in the sizes tracker in case the tracking + * was enabled at runtime, since it relies on the CAS value to know + * whether to remove an item or not. */ + item_stats_sizes_remove(it); + ITEM_set_cas(it, (settings.use_cas) ? get_cas_id() : 0); + item_stats_sizes_add(it); + memcpy(ITEM_data(it), buf, res); + memset(ITEM_data(it) + res, ' ', it->nbytes - res - 2); + do_item_update(it); + } else if (it->refcount > 1) { + item *new_it; + uint32_t flags; + if (settings.inline_ascii_response) { + flags = (uint32_t) strtoul(ITEM_suffix(it)+1, (char **) NULL, 10); + } else { + flags = *((uint32_t *)ITEM_suffix(it)); + } + new_it = do_item_alloc(ITEM_key(it), it->nkey, flags, it->exptime, res + 2); + if (new_it == 0) { + do_item_remove(it); + return EOM; + } + memcpy(ITEM_data(new_it), buf, res); + memcpy(ITEM_data(new_it) + res, ""\r\n"", 2); + item_replace(it, new_it, hv); + ITEM_set_cas(it, (settings.use_cas) ? ITEM_get_cas(new_it) : 0); + do_item_remove(new_it); /* release our reference */ + } else { + /* Should never get here. This means we somehow fetched an unlinked + * item. TODO: Add a counter? */ + if (settings.verbose) { + fprintf(stderr, ""Tried to do incr/decr on invalid item\n""); + } + if (it->refcount == 1) + do_item_remove(it); + return DELTA_ITEM_NOT_FOUND; + } + + if (cas) { + *cas = ITEM_get_cas(it); /* swap the incoming CAS value */ + } + do_item_remove(it); /* release our reference */ + return OK; +} +",0,"enum delta_result_type do_add_delta(conn *c, const char *key, const size_t nkey, + const bool incr, const int64_t delta, + char *buf, uint64_t *cas, + const uint32_t hv) { + char *ptr; + uint64_t value; + int res; + item *it; + + it = do_item_get(key, nkey, hv, c, DONT_UPDATE); + if (!it) { + return DELTA_ITEM_NOT_FOUND; + } + + /* Can't delta zero byte values. 2-byte are the ""\r\n"" */ + /* Also can't delta for chunked items. Too large to be a number */ + if (it->nbytes <= 2 || (it->it_flags & ITEM_CHUNKED) != 0) { + return NON_NUMERIC; + } + + if (cas != NULL && *cas != 0 && ITEM_get_cas(it) != *cas) { + do_item_remove(it); + return DELTA_ITEM_CAS_MISMATCH; + } + + ptr = ITEM_data(it); + + if (!safe_strtoull(ptr, &value)) { + do_item_remove(it); + return NON_NUMERIC; + } + + if (incr) { + value += delta; + MEMCACHED_COMMAND_INCR(c->sfd, ITEM_key(it), it->nkey, value); + } else { + if(delta > value) { + value = 0; + } else { + value -= delta; + } + MEMCACHED_COMMAND_DECR(c->sfd, ITEM_key(it), it->nkey, value); + } + + pthread_mutex_lock(&c->thread->stats.mutex); + if (incr) { + c->thread->stats.slab_stats[ITEM_clsid(it)].incr_hits++; + } else { + c->thread->stats.slab_stats[ITEM_clsid(it)].decr_hits++; + } + pthread_mutex_unlock(&c->thread->stats.mutex); + + snprintf(buf, INCR_MAX_STORAGE_LEN, ""%llu"", (unsigned long long)value); + res = strlen(buf); + /* refcount == 2 means we are the only ones holding the item, and it is + * linked. We hold the item's lock in this function, so refcount cannot + * increase. */ + if (res + 2 <= it->nbytes && it->refcount == 2) { /* replace in-place */ + /* When changing the value without replacing the item, we + need to update the CAS on the existing item. */ + /* We also need to fiddle it in the sizes tracker in case the tracking + * was enabled at runtime, since it relies on the CAS value to know + * whether to remove an item or not. */ + item_stats_sizes_remove(it); + ITEM_set_cas(it, (settings.use_cas) ? get_cas_id() : 0); + item_stats_sizes_add(it); + memcpy(ITEM_data(it), buf, res); + memset(ITEM_data(it) + res, ' ', it->nbytes - res - 2); + do_item_update(it); + } else if (it->refcount > 1) { + item *new_it; + uint32_t flags; + if (settings.inline_ascii_response) { + flags = (uint32_t) strtoul(ITEM_suffix(it)+1, (char **) NULL, 10); + } else { + flags = *((uint32_t *)ITEM_suffix(it)); + } + new_it = do_item_alloc(ITEM_key(it), it->nkey, flags, it->exptime, res + 2); + if (new_it == 0) { + do_item_remove(it); + return EOM; + } + memcpy(ITEM_data(new_it), buf, res); + memcpy(ITEM_data(new_it) + res, ""\r\n"", 2); + item_replace(it, new_it, hv); + ITEM_set_cas(it, (settings.use_cas) ? ITEM_get_cas(new_it) : 0); + do_item_remove(new_it); /* release our reference */ + } else { + /* Should never get here. This means we somehow fetched an unlinked + * item. TODO: Add a counter? */ + if (settings.verbose) { + fprintf(stderr, ""Tried to do incr/decr on invalid item\n""); + } + if (it->refcount == 1) + do_item_remove(it); + return DELTA_ITEM_NOT_FOUND; + } + + if (cas) { + *cas = ITEM_get_cas(it); /* swap the incoming CAS value */ + } + do_item_remove(it); /* release our reference */ + return OK; +} +","@@ -3249,6 +3249,16 @@ static inline int make_ascii_get_suffix(char *suffix, item *it, bool return_cas) + return (p - suffix) + 2; + } + ++#define IT_REFCOUNT_LIMIT 60000 ++static inline item* limited_get(char *key, size_t nkey, conn *c) { ++ item *it = item_get(key, nkey, c, DO_UPDATE); ++ if (it && it->refcount > IT_REFCOUNT_LIMIT) { ++ item_remove(it); ++ it = NULL; ++ } ++ return it; ++} ++ + /* ntokens is overwritten here... shrug.. */ + static inline void process_get_command(conn *c, token_t *tokens, size_t ntokens, bool return_cas) { + char *key; +@@ -3273,7 +3283,7 @@ static inline void process_get_command(conn *c, token_t *tokens, size_t ntokens, + return; + } + +- it = item_get(key, nkey, c, DO_UPDATE); ++ it = limited_get(key, nkey, c); + if (settings.detail_enabled) { + stats_prefix_record_get(key, nkey, NULL != it); + }",1001,1332,2048 +1726,"int qcow2_alloc_cluster_offset(BlockDriverState *bs, uint64_t offset, + int *num, uint64_t *host_offset, QCowL2Meta **m) +{ + BDRVQcowState *s = bs->opaque; + uint64_t start, remaining; + uint64_t cluster_offset; + uint64_t cur_bytes; + int ret; + + trace_qcow2_alloc_clusters_offset(qemu_coroutine_self(), offset, *num); + + assert((offset & ~BDRV_SECTOR_MASK) == 0); + +again: + start = offset; + remaining = *num << BDRV_SECTOR_BITS; + cluster_offset = 0; + *host_offset = 0; + cur_bytes = 0; + *m = NULL; + + while (true) { + + if (!*host_offset) { + *host_offset = start_of_cluster(s, cluster_offset); + } + + assert(remaining >= cur_bytes); + + start += cur_bytes; + remaining -= cur_bytes; + cluster_offset += cur_bytes; + + if (remaining == 0) { + break; + } + + cur_bytes = remaining; + + /* + * Now start gathering as many contiguous clusters as possible: + * + * 1. Check for overlaps with in-flight allocations + * + * a) Overlap not in the first cluster -> shorten this request and + * let the caller handle the rest in its next loop iteration. + * + * b) Real overlaps of two requests. Yield and restart the search + * for contiguous clusters (the situation could have changed + * while we were sleeping) + * + * c) TODO: Request starts in the same cluster as the in-flight + * allocation ends. Shorten the COW of the in-fight allocation, + * set cluster_offset to write to the same cluster and set up + * the right synchronisation between the in-flight request and + * the new one. + */ + ret = handle_dependencies(bs, start, &cur_bytes, m); + if (ret == -EAGAIN) { + /* Currently handle_dependencies() doesn't yield if we already had + * an allocation. If it did, we would have to clean up the L2Meta + * structs before starting over. */ + assert(*m == NULL); + goto again; + } else if (ret < 0) { + return ret; + } else if (cur_bytes == 0) { + break; + } else { + /* handle_dependencies() may have decreased cur_bytes (shortened + * the allocations below) so that the next dependency is processed + * correctly during the next loop iteration. */ + } + + /* + * 2. Count contiguous COPIED clusters. + */ + ret = handle_copied(bs, start, &cluster_offset, &cur_bytes, m); + if (ret < 0) { + return ret; + } else if (ret) { + continue; + } else if (cur_bytes == 0) { + break; + } + + /* + * 3. If the request still hasn't completed, allocate new clusters, + * considering any cluster_offset of steps 1c or 2. + */ + ret = handle_alloc(bs, start, &cluster_offset, &cur_bytes, m); + if (ret < 0) { + return ret; + } else if (ret) { + continue; + } else { + assert(cur_bytes == 0); + break; + } + } + + *num -= remaining >> BDRV_SECTOR_BITS; + assert(*num > 0); + assert(*host_offset != 0); + + return 0; +} +",0,"int qcow2_alloc_cluster_offset(BlockDriverState *bs, uint64_t offset, + int *num, uint64_t *host_offset, QCowL2Meta **m) +{ + BDRVQcowState *s = bs->opaque; + uint64_t start, remaining; + uint64_t cluster_offset; + uint64_t cur_bytes; + int ret; + + trace_qcow2_alloc_clusters_offset(qemu_coroutine_self(), offset, *num); + + assert((offset & ~BDRV_SECTOR_MASK) == 0); + +again: + start = offset; + remaining = *num << BDRV_SECTOR_BITS; + cluster_offset = 0; + *host_offset = 0; + cur_bytes = 0; + *m = NULL; + + while (true) { + + if (!*host_offset) { + *host_offset = start_of_cluster(s, cluster_offset); + } + + assert(remaining >= cur_bytes); + + start += cur_bytes; + remaining -= cur_bytes; + cluster_offset += cur_bytes; + + if (remaining == 0) { + break; + } + + cur_bytes = remaining; + + /* + * Now start gathering as many contiguous clusters as possible: + * + * 1. Check for overlaps with in-flight allocations + * + * a) Overlap not in the first cluster -> shorten this request and + * let the caller handle the rest in its next loop iteration. + * + * b) Real overlaps of two requests. Yield and restart the search + * for contiguous clusters (the situation could have changed + * while we were sleeping) + * + * c) TODO: Request starts in the same cluster as the in-flight + * allocation ends. Shorten the COW of the in-fight allocation, + * set cluster_offset to write to the same cluster and set up + * the right synchronisation between the in-flight request and + * the new one. + */ + ret = handle_dependencies(bs, start, &cur_bytes, m); + if (ret == -EAGAIN) { + /* Currently handle_dependencies() doesn't yield if we already had + * an allocation. If it did, we would have to clean up the L2Meta + * structs before starting over. */ + assert(*m == NULL); + goto again; + } else if (ret < 0) { + return ret; + } else if (cur_bytes == 0) { + break; + } else { + /* handle_dependencies() may have decreased cur_bytes (shortened + * the allocations below) so that the next dependency is processed + * correctly during the next loop iteration. */ + } + + /* + * 2. Count contiguous COPIED clusters. + */ + ret = handle_copied(bs, start, &cluster_offset, &cur_bytes, m); + if (ret < 0) { + return ret; + } else if (ret) { + continue; + } else if (cur_bytes == 0) { + break; + } + + /* + * 3. If the request still hasn't completed, allocate new clusters, + * considering any cluster_offset of steps 1c or 2. + */ + ret = handle_alloc(bs, start, &cluster_offset, &cur_bytes, m); + if (ret < 0) { + return ret; + } else if (ret) { + continue; + } else { + assert(cur_bytes == 0); + break; + } + } + + *num -= remaining >> BDRV_SECTOR_BITS; + assert(*num > 0); + assert(*host_offset != 0); + + return 0; +} +","@@ -55,7 +55,7 @@ int qcow2_grow_l1_table(BlockDriverState *bs, uint64_t min_size, + } + } + +- if (new_l1_size > INT_MAX) { ++ if (new_l1_size > INT_MAX / sizeof(uint64_t)) { + return -EFBIG; + }",790,1121,2048 +18785,"status_t IPCThreadState::executeCommand(int32_t cmd) +{ + BBinder* obj; + RefBase::weakref_type* refs; + status_t result = NO_ERROR; + + switch ((uint32_t)cmd) { + case BR_ERROR: + result = mIn.readInt32(); + break; + + case BR_OK: + break; + + case BR_ACQUIRE: + refs = (RefBase::weakref_type*)mIn.readPointer(); + obj = (BBinder*)mIn.readPointer(); + ALOG_ASSERT(refs->refBase() == obj, + ""BR_ACQUIRE: object %p does not match cookie %p (expected %p)"", + refs, obj, refs->refBase()); + obj->incStrong(mProcess.get()); + IF_LOG_REMOTEREFS() { + LOG_REMOTEREFS(""BR_ACQUIRE from driver on %p"", obj); + obj->printRefs(); + } + mOut.writeInt32(BC_ACQUIRE_DONE); + mOut.writePointer((uintptr_t)refs); + mOut.writePointer((uintptr_t)obj); + break; + + case BR_RELEASE: + refs = (RefBase::weakref_type*)mIn.readPointer(); + obj = (BBinder*)mIn.readPointer(); + ALOG_ASSERT(refs->refBase() == obj, + ""BR_RELEASE: object %p does not match cookie %p (expected %p)"", + refs, obj, refs->refBase()); + IF_LOG_REMOTEREFS() { + LOG_REMOTEREFS(""BR_RELEASE from driver on %p"", obj); + obj->printRefs(); + } + mPendingStrongDerefs.push(obj); + break; + + case BR_INCREFS: + refs = (RefBase::weakref_type*)mIn.readPointer(); + obj = (BBinder*)mIn.readPointer(); + refs->incWeak(mProcess.get()); + mOut.writeInt32(BC_INCREFS_DONE); + mOut.writePointer((uintptr_t)refs); + mOut.writePointer((uintptr_t)obj); + break; + + case BR_DECREFS: + refs = (RefBase::weakref_type*)mIn.readPointer(); + obj = (BBinder*)mIn.readPointer(); + mPendingWeakDerefs.push(refs); + break; + + case BR_ATTEMPT_ACQUIRE: + refs = (RefBase::weakref_type*)mIn.readPointer(); + obj = (BBinder*)mIn.readPointer(); + + { + const bool success = refs->attemptIncStrong(mProcess.get()); + ALOG_ASSERT(success && refs->refBase() == obj, + ""BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)"", + refs, obj, refs->refBase()); + + mOut.writeInt32(BC_ACQUIRE_RESULT); + mOut.writeInt32((int32_t)success); + } + break; + + case BR_TRANSACTION: + { + binder_transaction_data tr; + result = mIn.read(&tr, sizeof(tr)); + ALOG_ASSERT(result == NO_ERROR, + ""Not enough command data for brTRANSACTION""); + if (result != NO_ERROR) break; + + Parcel buffer; + buffer.ipcSetDataReference( + reinterpret_cast(tr.data.ptr.buffer), + tr.data_size, + reinterpret_cast(tr.data.ptr.offsets), + tr.offsets_size/sizeof(binder_size_t), freeBuffer, this); + + const pid_t origPid = mCallingPid; + const uid_t origUid = mCallingUid; + const int32_t origStrictModePolicy = mStrictModePolicy; + const int32_t origTransactionBinderFlags = mLastTransactionBinderFlags; + + mCallingPid = tr.sender_pid; + mCallingUid = tr.sender_euid; + mLastTransactionBinderFlags = tr.flags; + + int curPrio = getpriority(PRIO_PROCESS, mMyThreadId); + if (gDisableBackgroundScheduling) { + if (curPrio > ANDROID_PRIORITY_NORMAL) { + setpriority(PRIO_PROCESS, mMyThreadId, ANDROID_PRIORITY_NORMAL); + } + } else { + if (curPrio >= ANDROID_PRIORITY_BACKGROUND) { + set_sched_policy(mMyThreadId, SP_BACKGROUND); + } + } + + + Parcel reply; + status_t error; + IF_LOG_TRANSACTIONS() { + TextOutput::Bundle _b(alog); + alog << ""BR_TRANSACTION thr "" << (void*)pthread_self() + << "" / obj "" << tr.target.ptr << "" / code "" + << TypeCode(tr.code) << "": "" << indent << buffer + << dedent << endl + << ""Data addr = "" + << reinterpret_cast(tr.data.ptr.buffer) + << "", offsets addr="" + + << reinterpret_cast(tr.data.ptr.offsets) << endl; + } + if (tr.target.ptr) { + sp b((BBinder*)tr.cookie); + error = b->transact(tr.code, buffer, &reply, tr.flags); + + } else { + error = the_context_object->transact(tr.code, buffer, &reply, tr.flags); + } + + + if ((tr.flags & TF_ONE_WAY) == 0) { + LOG_ONEWAY(""Sending reply to %d!"", mCallingPid); + if (error < NO_ERROR) reply.setError(error); + sendReply(reply, 0); + } else { + LOG_ONEWAY(""NOT sending reply to %d!"", mCallingPid); + } + + mCallingPid = origPid; + mCallingUid = origUid; + mStrictModePolicy = origStrictModePolicy; + mLastTransactionBinderFlags = origTransactionBinderFlags; + + IF_LOG_TRANSACTIONS() { + TextOutput::Bundle _b(alog); + alog << ""BC_REPLY thr "" << (void*)pthread_self() << "" / obj "" + << tr.target.ptr << "": "" << indent << reply << dedent << endl; + } + + } + break; + + case BR_DEAD_BINDER: + { + BpBinder *proxy = (BpBinder*)mIn.readPointer(); + proxy->sendObituary(); + mOut.writeInt32(BC_DEAD_BINDER_DONE); + mOut.writePointer((uintptr_t)proxy); + } break; + + case BR_CLEAR_DEATH_NOTIFICATION_DONE: + { + BpBinder *proxy = (BpBinder*)mIn.readPointer(); + proxy->getWeakRefs()->decWeak(proxy); + } break; + + case BR_FINISHED: + result = TIMED_OUT; + break; + + case BR_NOOP: + break; + + case BR_SPAWN_LOOPER: + mProcess->spawnPooledThread(false); + break; + + default: + printf(""*** BAD COMMAND %d received from Binder driver\n"", cmd); + result = UNKNOWN_ERROR; + break; + } + + if (result != NO_ERROR) { + mLastError = result; + } + + return result; +} +",1,"status_t IPCThreadState::executeCommand(int32_t cmd) +{ + BBinder* obj; + RefBase::weakref_type* refs; + status_t result = NO_ERROR; + + switch ((uint32_t)cmd) { + case BR_ERROR: + result = mIn.readInt32(); + break; + + case BR_OK: + break; + + case BR_ACQUIRE: + refs = (RefBase::weakref_type*)mIn.readPointer(); + obj = (BBinder*)mIn.readPointer(); + ALOG_ASSERT(refs->refBase() == obj, + ""BR_ACQUIRE: object %p does not match cookie %p (expected %p)"", + refs, obj, refs->refBase()); + obj->incStrong(mProcess.get()); + IF_LOG_REMOTEREFS() { + LOG_REMOTEREFS(""BR_ACQUIRE from driver on %p"", obj); + obj->printRefs(); + } + mOut.writeInt32(BC_ACQUIRE_DONE); + mOut.writePointer((uintptr_t)refs); + mOut.writePointer((uintptr_t)obj); + break; + + case BR_RELEASE: + refs = (RefBase::weakref_type*)mIn.readPointer(); + obj = (BBinder*)mIn.readPointer(); + ALOG_ASSERT(refs->refBase() == obj, + ""BR_RELEASE: object %p does not match cookie %p (expected %p)"", + refs, obj, refs->refBase()); + IF_LOG_REMOTEREFS() { + LOG_REMOTEREFS(""BR_RELEASE from driver on %p"", obj); + obj->printRefs(); + } + mPendingStrongDerefs.push(obj); + break; + + case BR_INCREFS: + refs = (RefBase::weakref_type*)mIn.readPointer(); + obj = (BBinder*)mIn.readPointer(); + refs->incWeak(mProcess.get()); + mOut.writeInt32(BC_INCREFS_DONE); + mOut.writePointer((uintptr_t)refs); + mOut.writePointer((uintptr_t)obj); + break; + + case BR_DECREFS: + refs = (RefBase::weakref_type*)mIn.readPointer(); + obj = (BBinder*)mIn.readPointer(); + mPendingWeakDerefs.push(refs); + break; + + case BR_ATTEMPT_ACQUIRE: + refs = (RefBase::weakref_type*)mIn.readPointer(); + obj = (BBinder*)mIn.readPointer(); + + { + const bool success = refs->attemptIncStrong(mProcess.get()); + ALOG_ASSERT(success && refs->refBase() == obj, + ""BR_ATTEMPT_ACQUIRE: object %p does not match cookie %p (expected %p)"", + refs, obj, refs->refBase()); + + mOut.writeInt32(BC_ACQUIRE_RESULT); + mOut.writeInt32((int32_t)success); + } + break; + + case BR_TRANSACTION: + { + binder_transaction_data tr; + result = mIn.read(&tr, sizeof(tr)); + ALOG_ASSERT(result == NO_ERROR, + ""Not enough command data for brTRANSACTION""); + if (result != NO_ERROR) break; + + Parcel buffer; + buffer.ipcSetDataReference( + reinterpret_cast(tr.data.ptr.buffer), + tr.data_size, + reinterpret_cast(tr.data.ptr.offsets), + tr.offsets_size/sizeof(binder_size_t), freeBuffer, this); + + const pid_t origPid = mCallingPid; + const uid_t origUid = mCallingUid; + const int32_t origStrictModePolicy = mStrictModePolicy; + const int32_t origTransactionBinderFlags = mLastTransactionBinderFlags; + + mCallingPid = tr.sender_pid; + mCallingUid = tr.sender_euid; + mLastTransactionBinderFlags = tr.flags; + + int curPrio = getpriority(PRIO_PROCESS, mMyThreadId); + if (gDisableBackgroundScheduling) { + if (curPrio > ANDROID_PRIORITY_NORMAL) { + setpriority(PRIO_PROCESS, mMyThreadId, ANDROID_PRIORITY_NORMAL); + } + } else { + if (curPrio >= ANDROID_PRIORITY_BACKGROUND) { + set_sched_policy(mMyThreadId, SP_BACKGROUND); + } + } + + + Parcel reply; + status_t error; + IF_LOG_TRANSACTIONS() { + TextOutput::Bundle _b(alog); + alog << ""BR_TRANSACTION thr "" << (void*)pthread_self() + << "" / obj "" << tr.target.ptr << "" / code "" + << TypeCode(tr.code) << "": "" << indent << buffer + << dedent << endl + << ""Data addr = "" + << reinterpret_cast(tr.data.ptr.buffer) + << "", offsets addr="" + + << reinterpret_cast(tr.data.ptr.offsets) << endl; + } + if (tr.target.ptr) { + // We only have a weak reference on the target object, so we must first try to + // safely acquire a strong reference before doing anything else with it. + if (reinterpret_cast( + tr.target.ptr)->attemptIncStrong(this)) { + error = reinterpret_cast(tr.cookie)->transact(tr.code, buffer, + &reply, tr.flags); + reinterpret_cast(tr.cookie)->decStrong(this); + } else { + error = UNKNOWN_TRANSACTION; + } + + } else { + error = the_context_object->transact(tr.code, buffer, &reply, tr.flags); + } + + + if ((tr.flags & TF_ONE_WAY) == 0) { + LOG_ONEWAY(""Sending reply to %d!"", mCallingPid); + if (error < NO_ERROR) reply.setError(error); + sendReply(reply, 0); + } else { + LOG_ONEWAY(""NOT sending reply to %d!"", mCallingPid); + } + + mCallingPid = origPid; + mCallingUid = origUid; + mStrictModePolicy = origStrictModePolicy; + mLastTransactionBinderFlags = origTransactionBinderFlags; + + IF_LOG_TRANSACTIONS() { + TextOutput::Bundle _b(alog); + alog << ""BC_REPLY thr "" << (void*)pthread_self() << "" / obj "" + << tr.target.ptr << "": "" << indent << reply << dedent << endl; + } + + } + break; + + case BR_DEAD_BINDER: + { + BpBinder *proxy = (BpBinder*)mIn.readPointer(); + proxy->sendObituary(); + mOut.writeInt32(BC_DEAD_BINDER_DONE); + mOut.writePointer((uintptr_t)proxy); + } break; + + case BR_CLEAR_DEATH_NOTIFICATION_DONE: + { + BpBinder *proxy = (BpBinder*)mIn.readPointer(); + proxy->getWeakRefs()->decWeak(proxy); + } break; + + case BR_FINISHED: + result = TIMED_OUT; + break; + + case BR_NOOP: + break; + + case BR_SPAWN_LOOPER: + mProcess->spawnPooledThread(false); + break; + + default: + printf(""*** BAD COMMAND %d received from Binder driver\n"", cmd); + result = UNKNOWN_ERROR; + break; + } + + if (result != NO_ERROR) { + mLastError = result; + } + + return result; +} +","@@ -1083,8 +1083,16 @@ + + << reinterpret_cast(tr.data.ptr.offsets) << endl; + } + if (tr.target.ptr) { +- sp b((BBinder*)tr.cookie); +- error = b->transact(tr.code, buffer, &reply, tr.flags); ++ // We only have a weak reference on the target object, so we must first try to ++ // safely acquire a strong reference before doing anything else with it. ++ if (reinterpret_cast( ++ tr.target.ptr)->attemptIncStrong(this)) { ++ error = reinterpret_cast(tr.cookie)->transact(tr.code, buffer, ++ &reply, tr.flags); ++ reinterpret_cast(tr.cookie)->decStrong(this); ++ } else { ++ error = UNKNOWN_TRANSACTION; ++ } + + } else { + error = the_context_object->transact(tr.code, buffer, &reply, tr.flags); +",1413,1744,2048 +18136,"int vfs_rename(struct inode *old_dir, struct dentry *old_dentry, + struct inode *new_dir, struct dentry *new_dentry, + struct inode **delegated_inode, unsigned int flags) + { + int error; + bool is_dir = d_is_dir(old_dentry); + const unsigned char *old_name; + struct inode *source = old_dentry->d_inode; + struct inode *target = new_dentry->d_inode; + bool new_is_dir = false; + unsigned max_links = new_dir->i_sb->s_max_links; + + if (source == target) + return 0; + + error = may_delete(old_dir, old_dentry, is_dir); + if (error) + return error; + + if (!target) { + error = may_create(new_dir, new_dentry); + } else { + new_is_dir = d_is_dir(new_dentry); + + if (!(flags & RENAME_EXCHANGE)) + error = may_delete(new_dir, new_dentry, is_dir); + else + error = may_delete(new_dir, new_dentry, new_is_dir); + } + if (error) + return error; + + if (!old_dir->i_op->rename) + return -EPERM; + + /* + * If we are going to change the parent - check write permissions, + * we'll need to flip '..'. + */ + if (new_dir != old_dir) { + if (is_dir) { + error = inode_permission(source, MAY_WRITE); + if (error) + return error; + } + if ((flags & RENAME_EXCHANGE) && new_is_dir) { + error = inode_permission(target, MAY_WRITE); + if (error) + return error; + } + } + + error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry, + flags); + if (error) + return error; + + old_name = fsnotify_oldname_init(old_dentry->d_name.name); + dget(new_dentry); + if (!is_dir || (flags & RENAME_EXCHANGE)) + lock_two_nondirectories(source, target); + else if (target) + inode_lock(target); + + error = -EBUSY; + if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry)) + goto out; + + if (max_links && new_dir != old_dir) { + error = -EMLINK; + if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links) + goto out; + if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir && + old_dir->i_nlink >= max_links) + goto out; + } + if (is_dir && !(flags & RENAME_EXCHANGE) && target) + shrink_dcache_parent(new_dentry); + if (!is_dir) { + error = try_break_deleg(source, delegated_inode); + if (error) + goto out; + } + if (target && !new_is_dir) { + error = try_break_deleg(target, delegated_inode); + if (error) + goto out; + } + error = old_dir->i_op->rename(old_dir, old_dentry, + new_dir, new_dentry, flags); + if (error) + goto out; + + if (!(flags & RENAME_EXCHANGE) && target) { + if (is_dir) + target->i_flags |= S_DEAD; + dont_mount(new_dentry); + detach_mounts(new_dentry); + } + if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) { + if (!(flags & RENAME_EXCHANGE)) + d_move(old_dentry, new_dentry); + else + d_exchange(old_dentry, new_dentry); + } +out: + if (!is_dir || (flags & RENAME_EXCHANGE)) + unlock_two_nondirectories(source, target); + else if (target) + inode_unlock(target); + dput(new_dentry); + if (!error) { + fsnotify_move(old_dir, new_dir, old_name, is_dir, + !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry); + if (flags & RENAME_EXCHANGE) { + fsnotify_move(new_dir, old_dir, old_dentry->d_name.name, + new_is_dir, NULL, new_dentry); + } + } + fsnotify_oldname_free(old_name); + + return error; + } +",1,"int vfs_rename(struct inode *old_dir, struct dentry *old_dentry, + struct inode *new_dir, struct dentry *new_dentry, + struct inode **delegated_inode, unsigned int flags) + { + int error; + bool is_dir = d_is_dir(old_dentry); + struct inode *source = old_dentry->d_inode; + struct inode *target = new_dentry->d_inode; + bool new_is_dir = false; + unsigned max_links = new_dir->i_sb->s_max_links; + struct name_snapshot old_name; + + if (source == target) + return 0; + + error = may_delete(old_dir, old_dentry, is_dir); + if (error) + return error; + + if (!target) { + error = may_create(new_dir, new_dentry); + } else { + new_is_dir = d_is_dir(new_dentry); + + if (!(flags & RENAME_EXCHANGE)) + error = may_delete(new_dir, new_dentry, is_dir); + else + error = may_delete(new_dir, new_dentry, new_is_dir); + } + if (error) + return error; + + if (!old_dir->i_op->rename) + return -EPERM; + + /* + * If we are going to change the parent - check write permissions, + * we'll need to flip '..'. + */ + if (new_dir != old_dir) { + if (is_dir) { + error = inode_permission(source, MAY_WRITE); + if (error) + return error; + } + if ((flags & RENAME_EXCHANGE) && new_is_dir) { + error = inode_permission(target, MAY_WRITE); + if (error) + return error; + } + } + + error = security_inode_rename(old_dir, old_dentry, new_dir, new_dentry, + flags); + if (error) + return error; + + take_dentry_name_snapshot(&old_name, old_dentry); + dget(new_dentry); + if (!is_dir || (flags & RENAME_EXCHANGE)) + lock_two_nondirectories(source, target); + else if (target) + inode_lock(target); + + error = -EBUSY; + if (is_local_mountpoint(old_dentry) || is_local_mountpoint(new_dentry)) + goto out; + + if (max_links && new_dir != old_dir) { + error = -EMLINK; + if (is_dir && !new_is_dir && new_dir->i_nlink >= max_links) + goto out; + if ((flags & RENAME_EXCHANGE) && !is_dir && new_is_dir && + old_dir->i_nlink >= max_links) + goto out; + } + if (is_dir && !(flags & RENAME_EXCHANGE) && target) + shrink_dcache_parent(new_dentry); + if (!is_dir) { + error = try_break_deleg(source, delegated_inode); + if (error) + goto out; + } + if (target && !new_is_dir) { + error = try_break_deleg(target, delegated_inode); + if (error) + goto out; + } + error = old_dir->i_op->rename(old_dir, old_dentry, + new_dir, new_dentry, flags); + if (error) + goto out; + + if (!(flags & RENAME_EXCHANGE) && target) { + if (is_dir) + target->i_flags |= S_DEAD; + dont_mount(new_dentry); + detach_mounts(new_dentry); + } + if (!(old_dir->i_sb->s_type->fs_flags & FS_RENAME_DOES_D_MOVE)) { + if (!(flags & RENAME_EXCHANGE)) + d_move(old_dentry, new_dentry); + else + d_exchange(old_dentry, new_dentry); + } +out: + if (!is_dir || (flags & RENAME_EXCHANGE)) + unlock_two_nondirectories(source, target); + else if (target) + inode_unlock(target); + dput(new_dentry); + if (!error) { + fsnotify_move(old_dir, new_dir, old_name.name, is_dir, + !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry); + if (flags & RENAME_EXCHANGE) { + fsnotify_move(new_dir, old_dir, old_dentry->d_name.name, + new_is_dir, NULL, new_dentry); + } + } + release_dentry_name_snapshot(&old_name); + + return error; + } +","@@ -4362,11 +4362,11 @@ int vfs_rename(struct inode *old_dir, struct dentry *old_dentry, + { + int error; + bool is_dir = d_is_dir(old_dentry); +- const unsigned char *old_name; + struct inode *source = old_dentry->d_inode; + struct inode *target = new_dentry->d_inode; + bool new_is_dir = false; + unsigned max_links = new_dir->i_sb->s_max_links; ++ struct name_snapshot old_name; + + if (source == target) + return 0; +@@ -4413,7 +4413,7 @@ int vfs_rename(struct inode *old_dir, struct dentry *old_dentry, + if (error) + return error; + +- old_name = fsnotify_oldname_init(old_dentry->d_name.name); ++ take_dentry_name_snapshot(&old_name, old_dentry); + dget(new_dentry); + if (!is_dir || (flags & RENAME_EXCHANGE)) + lock_two_nondirectories(source, target); +@@ -4468,14 +4468,14 @@ int vfs_rename(struct inode *old_dir, struct dentry *old_dentry, + inode_unlock(target); + dput(new_dentry); + if (!error) { +- fsnotify_move(old_dir, new_dir, old_name, is_dir, ++ fsnotify_move(old_dir, new_dir, old_name.name, is_dir, + !(flags & RENAME_EXCHANGE) ? target : NULL, old_dentry); + if (flags & RENAME_EXCHANGE) { + fsnotify_move(new_dir, old_dir, old_dentry->d_name.name, + new_is_dir, NULL, new_dentry); + } + } +- fsnotify_oldname_free(old_name); ++ release_dentry_name_snapshot(&old_name); + + return error; + }",942,1273,2048 +16977,"std::string TestURLLoader::TestUntrustedHttpRequests() { + { + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""cOnNeCt"", std::string())); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""tRaCk"", std::string())); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""tRaCe"", std::string())); + ASSERT_EQ(PP_ERROR_NOACCESS, + OpenUntrusted(""POST\x0d\x0ax-csrf-token:\x20test1234"", std::string())); + } + { + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Accept-Charset:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Accept-Encoding:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Connection:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Content-Length:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Cookie:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Cookie2:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Date:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Dnt:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Expect:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Host:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Keep-Alive:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Referer:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""TE:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Trailer:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, + OpenUntrusted(""GET"", ""Transfer-Encoding:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Upgrade:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""User-Agent:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Via:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted( + ""GET"", ""Proxy-Authorization: Basic dXNlcjpwYXNzd29yZA==:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Sec-foo:\n"")); + } + { + pp::URLRequestInfo request(instance_); + request.SetCustomReferrerURL(""http://www.google.com/""); + + int32_t rv = OpenUntrusted(request, NULL); + if (rv != PP_ERROR_NOACCESS) + return ReportError( + ""Untrusted request with custom referrer restriction"", rv); + } + { + pp::URLRequestInfo request(instance_); + request.SetCustomContentTransferEncoding(""foo""); + + int32_t rv = OpenUntrusted(request, NULL); + if (rv != PP_ERROR_NOACCESS) + return ReportError( + ""Untrusted request with content-transfer-encoding restriction"", rv); + } + + PASS(); +} +",0,"std::string TestURLLoader::TestUntrustedHttpRequests() { + { + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""cOnNeCt"", std::string())); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""tRaCk"", std::string())); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""tRaCe"", std::string())); + ASSERT_EQ(PP_ERROR_NOACCESS, + OpenUntrusted(""POST\x0d\x0ax-csrf-token:\x20test1234"", std::string())); + } + { + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Accept-Charset:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Accept-Encoding:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Connection:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Content-Length:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Cookie:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Cookie2:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Date:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Dnt:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Expect:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Host:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Keep-Alive:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Referer:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""TE:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Trailer:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, + OpenUntrusted(""GET"", ""Transfer-Encoding:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Upgrade:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""User-Agent:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Via:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted( + ""GET"", ""Proxy-Authorization: Basic dXNlcjpwYXNzd29yZA==:\n"")); + ASSERT_EQ(PP_ERROR_NOACCESS, OpenUntrusted(""GET"", ""Sec-foo:\n"")); + } + { + pp::URLRequestInfo request(instance_); + request.SetCustomReferrerURL(""http://www.google.com/""); + + int32_t rv = OpenUntrusted(request, NULL); + if (rv != PP_ERROR_NOACCESS) + return ReportError( + ""Untrusted request with custom referrer restriction"", rv); + } + { + pp::URLRequestInfo request(instance_); + request.SetCustomContentTransferEncoding(""foo""); + + int32_t rv = OpenUntrusted(request, NULL); + if (rv != PP_ERROR_NOACCESS) + return ReportError( + ""Untrusted request with content-transfer-encoding restriction"", rv); + } + + PASS(); +} +","@@ -874,7 +874,7 @@ std::string TestURLLoader::TestUntendedLoad() { + loader.GetDownloadProgress(&bytes_received, &total_bytes_to_be_received); + if (total_bytes_to_be_received <= 0) + return ReportError(""URLLoader::GetDownloadProgress total size"", +- total_bytes_to_be_received); ++ static_cast(total_bytes_to_be_received)); + if (bytes_received == total_bytes_to_be_received) + break; + // Yield if we're on the main thread, so that URLLoader can receive more",703,1034,2048 +2191,"static unsigned long zap_pte_range(struct mmu_gather *tlb, + struct vm_area_struct *vma, pmd_t *pmd, + unsigned long addr, unsigned long end, + struct zap_details *details) +{ + struct mm_struct *mm = tlb->mm; + int force_flush = 0; + int rss[NR_MM_COUNTERS]; + spinlock_t *ptl; + pte_t *start_pte; + pte_t *pte; + +again: + init_rss_vec(rss); + start_pte = pte_offset_map_lock(mm, pmd, addr, &ptl); + pte = start_pte; + arch_enter_lazy_mmu_mode(); + do { + pte_t ptent = *pte; + if (pte_none(ptent)) { + continue; + } + + if (pte_present(ptent)) { + struct page *page; + + page = vm_normal_page(vma, addr, ptent); + if (unlikely(details) && page) { + /* + * unmap_shared_mapping_pages() wants to + * invalidate cache without truncating: + * unmap shared but keep private pages. + */ + if (details->check_mapping && + details->check_mapping != page->mapping) + continue; + /* + * Each page->index must be checked when + * invalidating or truncating nonlinear. + */ + if (details->nonlinear_vma && + (page->index < details->first_index || + page->index > details->last_index)) + continue; + } + ptent = ptep_get_and_clear_full(mm, addr, pte, + tlb->fullmm); + tlb_remove_tlb_entry(tlb, pte, addr); + if (unlikely(!page)) + continue; + if (unlikely(details) && details->nonlinear_vma + && linear_page_index(details->nonlinear_vma, + addr) != page->index) + set_pte_at(mm, addr, pte, + pgoff_to_pte(page->index)); + if (PageAnon(page)) + rss[MM_ANONPAGES]--; + else { + if (pte_dirty(ptent)) + set_page_dirty(page); + if (pte_young(ptent) && + likely(!VM_SequentialReadHint(vma))) + mark_page_accessed(page); + rss[MM_FILEPAGES]--; + } + page_remove_rmap(page); + if (unlikely(page_mapcount(page) < 0)) + print_bad_pte(vma, addr, ptent, page); + force_flush = !__tlb_remove_page(tlb, page); + if (force_flush) + break; + continue; + } + /* + * If details->check_mapping, we leave swap entries; + * if details->nonlinear_vma, we leave file entries. + */ + if (unlikely(details)) + continue; + if (pte_file(ptent)) { + if (unlikely(!(vma->vm_flags & VM_NONLINEAR))) + print_bad_pte(vma, addr, ptent, NULL); + } else { + swp_entry_t entry = pte_to_swp_entry(ptent); + + if (!non_swap_entry(entry)) + rss[MM_SWAPENTS]--; + else if (is_migration_entry(entry)) { + struct page *page; + + page = migration_entry_to_page(entry); + + if (PageAnon(page)) + rss[MM_ANONPAGES]--; + else + rss[MM_FILEPAGES]--; + } + if (unlikely(!free_swap_and_cache(entry))) + print_bad_pte(vma, addr, ptent, NULL); + } + pte_clear_not_present_full(mm, addr, pte, tlb->fullmm); + } while (pte++, addr += PAGE_SIZE, addr != end); + + add_mm_rss_vec(mm, rss); + arch_leave_lazy_mmu_mode(); + pte_unmap_unlock(start_pte, ptl); + + /* + * mmu_gather ran out of room to batch pages, we break out of + * the PTE lock to avoid doing the potential expensive TLB invalidate + * and page-free while holding it. + */ + if (force_flush) { + force_flush = 0; + tlb_flush_mmu(tlb); + if (addr != end) + goto again; + } + + return addr; +} +",0,"static unsigned long zap_pte_range(struct mmu_gather *tlb, + struct vm_area_struct *vma, pmd_t *pmd, + unsigned long addr, unsigned long end, + struct zap_details *details) +{ + struct mm_struct *mm = tlb->mm; + int force_flush = 0; + int rss[NR_MM_COUNTERS]; + spinlock_t *ptl; + pte_t *start_pte; + pte_t *pte; + +again: + init_rss_vec(rss); + start_pte = pte_offset_map_lock(mm, pmd, addr, &ptl); + pte = start_pte; + arch_enter_lazy_mmu_mode(); + do { + pte_t ptent = *pte; + if (pte_none(ptent)) { + continue; + } + + if (pte_present(ptent)) { + struct page *page; + + page = vm_normal_page(vma, addr, ptent); + if (unlikely(details) && page) { + /* + * unmap_shared_mapping_pages() wants to + * invalidate cache without truncating: + * unmap shared but keep private pages. + */ + if (details->check_mapping && + details->check_mapping != page->mapping) + continue; + /* + * Each page->index must be checked when + * invalidating or truncating nonlinear. + */ + if (details->nonlinear_vma && + (page->index < details->first_index || + page->index > details->last_index)) + continue; + } + ptent = ptep_get_and_clear_full(mm, addr, pte, + tlb->fullmm); + tlb_remove_tlb_entry(tlb, pte, addr); + if (unlikely(!page)) + continue; + if (unlikely(details) && details->nonlinear_vma + && linear_page_index(details->nonlinear_vma, + addr) != page->index) + set_pte_at(mm, addr, pte, + pgoff_to_pte(page->index)); + if (PageAnon(page)) + rss[MM_ANONPAGES]--; + else { + if (pte_dirty(ptent)) + set_page_dirty(page); + if (pte_young(ptent) && + likely(!VM_SequentialReadHint(vma))) + mark_page_accessed(page); + rss[MM_FILEPAGES]--; + } + page_remove_rmap(page); + if (unlikely(page_mapcount(page) < 0)) + print_bad_pte(vma, addr, ptent, page); + force_flush = !__tlb_remove_page(tlb, page); + if (force_flush) + break; + continue; + } + /* + * If details->check_mapping, we leave swap entries; + * if details->nonlinear_vma, we leave file entries. + */ + if (unlikely(details)) + continue; + if (pte_file(ptent)) { + if (unlikely(!(vma->vm_flags & VM_NONLINEAR))) + print_bad_pte(vma, addr, ptent, NULL); + } else { + swp_entry_t entry = pte_to_swp_entry(ptent); + + if (!non_swap_entry(entry)) + rss[MM_SWAPENTS]--; + else if (is_migration_entry(entry)) { + struct page *page; + + page = migration_entry_to_page(entry); + + if (PageAnon(page)) + rss[MM_ANONPAGES]--; + else + rss[MM_FILEPAGES]--; + } + if (unlikely(!free_swap_and_cache(entry))) + print_bad_pte(vma, addr, ptent, NULL); + } + pte_clear_not_present_full(mm, addr, pte, tlb->fullmm); + } while (pte++, addr += PAGE_SIZE, addr != end); + + add_mm_rss_vec(mm, rss); + arch_leave_lazy_mmu_mode(); + pte_unmap_unlock(start_pte, ptl); + + /* + * mmu_gather ran out of room to batch pages, we break out of + * the PTE lock to avoid doing the potential expensive TLB invalidate + * and page-free while holding it. + */ + if (force_flush) { + force_flush = 0; + tlb_flush_mmu(tlb); + if (addr != end) + goto again; + } + + return addr; +} +","@@ -1247,16 +1247,24 @@ static inline unsigned long zap_pmd_range(struct mmu_gather *tlb, + do { + next = pmd_addr_end(addr, end); + if (pmd_trans_huge(*pmd)) { +- if (next-addr != HPAGE_PMD_SIZE) { ++ if (next - addr != HPAGE_PMD_SIZE) { + VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); + split_huge_page_pmd(vma->vm_mm, pmd); + } else if (zap_huge_pmd(tlb, vma, pmd, addr)) +- continue; ++ goto next; + /* fall through */ + } +- if (pmd_none_or_clear_bad(pmd)) +- continue; ++ /* ++ * Here there can be other concurrent MADV_DONTNEED or ++ * trans huge page faults running, and if the pmd is ++ * none or trans huge it can change under us. This is ++ * because MADV_DONTNEED holds the mmap_sem in read ++ * mode. ++ */ ++ if (pmd_none_or_trans_huge_or_clear_bad(pmd)) ++ goto next; + next = zap_pte_range(tlb, vma, pmd, addr, next, details); ++next: + cond_resched(); + } while (pmd++, addr = next, addr != end); + ",929,1260,2048 +17845,"vmnc_handle_wmvi_rectangle (GstVMncDec * dec, struct RfbRectangle *rect, + const guint8 * data, int len, gboolean decode) +{ + GstVideoFormat format; + gint bpp, tc; + guint32 redmask, greenmask, bluemask; + guint32 endianness, dataendianness; + GstVideoCodecState *state; + + /* A WMVi rectangle has a 16byte payload */ + if (len < 16) { + GST_DEBUG_OBJECT (dec, ""Bad WMVi rect: too short""); + return ERROR_INSUFFICIENT_DATA; + } + + /* We only compare 13 bytes; ignoring the 3 padding bytes at the end */ + if (dec->have_format && memcmp (data, dec->format.descriptor, 13) == 0) { + /* Nothing changed, so just exit */ + return 16; + } + + /* Store the whole block for simple comparison later */ + memcpy (dec->format.descriptor, data, 16); + + if (rect->x != 0 || rect->y != 0) { + GST_WARNING_OBJECT (dec, ""Bad WMVi rect: wrong coordinates""); + return ERROR_INVALID; + } + + bpp = data[0]; + dec->format.depth = data[1]; + dec->format.big_endian = data[2]; + dataendianness = data[2] ? G_BIG_ENDIAN : G_LITTLE_ENDIAN; + tc = data[3]; + + if (bpp != 8 && bpp != 16 && bpp != 32) { + GST_WARNING_OBJECT (dec, ""Bad bpp value: %d"", bpp); + return ERROR_INVALID; + } + + if (!tc) { + GST_WARNING_OBJECT (dec, ""Paletted video not supported""); + return ERROR_INVALID; + } + + dec->format.bytes_per_pixel = bpp / 8; + dec->format.width = rect->width; + dec->format.height = rect->height; + + redmask = (guint32) (RFB_GET_UINT16 (data + 4)) << data[10]; + greenmask = (guint32) (RFB_GET_UINT16 (data + 6)) << data[11]; + bluemask = (guint32) (RFB_GET_UINT16 (data + 8)) << data[12]; + + GST_DEBUG_OBJECT (dec, ""Red: mask %d, shift %d"", + RFB_GET_UINT16 (data + 4), data[10]); + GST_DEBUG_OBJECT (dec, ""Green: mask %d, shift %d"", + RFB_GET_UINT16 (data + 6), data[11]); + GST_DEBUG_OBJECT (dec, ""Blue: mask %d, shift %d"", + RFB_GET_UINT16 (data + 8), data[12]); + GST_DEBUG_OBJECT (dec, ""BPP: %d. endianness: %s"", bpp, + data[2] ? ""big"" : ""little""); + + /* GStreamer's RGB caps are a bit weird. */ + if (bpp == 8) { + endianness = G_BYTE_ORDER; /* Doesn't matter */ + } else if (bpp == 16) { + /* We require host-endian. */ + endianness = G_BYTE_ORDER; + } else { /* bpp == 32 */ + /* We require big endian */ + endianness = G_BIG_ENDIAN; + if (endianness != dataendianness) { + redmask = GUINT32_SWAP_LE_BE (redmask); + greenmask = GUINT32_SWAP_LE_BE (greenmask); + bluemask = GUINT32_SWAP_LE_BE (bluemask); + } + } + + format = gst_video_format_from_masks (dec->format.depth, bpp, endianness, + redmask, greenmask, bluemask, 0); + + GST_DEBUG_OBJECT (dec, ""From depth: %d bpp: %u endianess: %s redmask: %X "" + ""greenmask: %X bluemask: %X got format %s"", + dec->format.depth, bpp, endianness == G_BIG_ENDIAN ? ""BE"" : ""LE"", + GUINT32_FROM_BE (redmask), GUINT32_FROM_BE (greenmask), + GUINT32_FROM_BE (bluemask), + format == GST_VIDEO_FORMAT_UNKNOWN ? ""UNKOWN"" : + gst_video_format_to_string (format)); + + if (format == GST_VIDEO_FORMAT_UNKNOWN) { + GST_WARNING_OBJECT (dec, ""Video format unknown to GStreamer""); + return ERROR_INVALID; + } + + dec->have_format = TRUE; + if (!decode) { + GST_LOG_OBJECT (dec, ""Parsing, not setting caps""); + return 16; + } + + + state = gst_video_decoder_set_output_state (GST_VIDEO_DECODER (dec), format, + rect->width, rect->height, dec->input_state); + gst_video_codec_state_unref (state); + + g_free (dec->imagedata); + dec->imagedata = g_malloc (dec->format.width * dec->format.height * + dec->format.bytes_per_pixel); + GST_DEBUG_OBJECT (dec, ""Allocated image data at %p"", dec->imagedata); + + dec->format.stride = dec->format.width * dec->format.bytes_per_pixel; + + return 16; +} +",1,"vmnc_handle_wmvi_rectangle (GstVMncDec * dec, struct RfbRectangle *rect, + const guint8 * data, int len, gboolean decode) +{ + GstVideoFormat format; + gint bpp, tc; + guint32 redmask, greenmask, bluemask; + guint32 endianness, dataendianness; + GstVideoCodecState *state; + + /* A WMVi rectangle has a 16byte payload */ + if (len < 16) { + GST_DEBUG_OBJECT (dec, ""Bad WMVi rect: too short""); + return ERROR_INSUFFICIENT_DATA; + } + + /* We only compare 13 bytes; ignoring the 3 padding bytes at the end */ + if (dec->have_format && memcmp (data, dec->format.descriptor, 13) == 0) { + /* Nothing changed, so just exit */ + return 16; + } + + /* Store the whole block for simple comparison later */ + memcpy (dec->format.descriptor, data, 16); + + if (rect->x != 0 || rect->y != 0) { + GST_WARNING_OBJECT (dec, ""Bad WMVi rect: wrong coordinates""); + return ERROR_INVALID; + } + + bpp = data[0]; + dec->format.depth = data[1]; + dec->format.big_endian = data[2]; + dataendianness = data[2] ? G_BIG_ENDIAN : G_LITTLE_ENDIAN; + tc = data[3]; + + if (bpp != 8 && bpp != 16 && bpp != 32) { + GST_WARNING_OBJECT (dec, ""Bad bpp value: %d"", bpp); + return ERROR_INVALID; + } + + if (!tc) { + GST_WARNING_OBJECT (dec, ""Paletted video not supported""); + return ERROR_INVALID; + } + + dec->format.bytes_per_pixel = bpp / 8; + dec->format.width = rect->width; + dec->format.height = rect->height; + + redmask = (guint32) (RFB_GET_UINT16 (data + 4)) << data[10]; + greenmask = (guint32) (RFB_GET_UINT16 (data + 6)) << data[11]; + bluemask = (guint32) (RFB_GET_UINT16 (data + 8)) << data[12]; + + GST_DEBUG_OBJECT (dec, ""Red: mask %d, shift %d"", + RFB_GET_UINT16 (data + 4), data[10]); + GST_DEBUG_OBJECT (dec, ""Green: mask %d, shift %d"", + RFB_GET_UINT16 (data + 6), data[11]); + GST_DEBUG_OBJECT (dec, ""Blue: mask %d, shift %d"", + RFB_GET_UINT16 (data + 8), data[12]); + GST_DEBUG_OBJECT (dec, ""BPP: %d. endianness: %s"", bpp, + data[2] ? ""big"" : ""little""); + + /* GStreamer's RGB caps are a bit weird. */ + if (bpp == 8) { + endianness = G_BYTE_ORDER; /* Doesn't matter */ + } else if (bpp == 16) { + /* We require host-endian. */ + endianness = G_BYTE_ORDER; + } else { /* bpp == 32 */ + /* We require big endian */ + endianness = G_BIG_ENDIAN; + if (endianness != dataendianness) { + redmask = GUINT32_SWAP_LE_BE (redmask); + greenmask = GUINT32_SWAP_LE_BE (greenmask); + bluemask = GUINT32_SWAP_LE_BE (bluemask); + } + } + + format = gst_video_format_from_masks (dec->format.depth, bpp, endianness, + redmask, greenmask, bluemask, 0); + + GST_DEBUG_OBJECT (dec, ""From depth: %d bpp: %u endianess: %s redmask: %X "" + ""greenmask: %X bluemask: %X got format %s"", + dec->format.depth, bpp, endianness == G_BIG_ENDIAN ? ""BE"" : ""LE"", + GUINT32_FROM_BE (redmask), GUINT32_FROM_BE (greenmask), + GUINT32_FROM_BE (bluemask), + format == GST_VIDEO_FORMAT_UNKNOWN ? ""UNKOWN"" : + gst_video_format_to_string (format)); + + if (format == GST_VIDEO_FORMAT_UNKNOWN) { + GST_WARNING_OBJECT (dec, ""Video format unknown to GStreamer""); + return ERROR_INVALID; + } + + dec->have_format = TRUE; + if (!decode) { + GST_LOG_OBJECT (dec, ""Parsing, not setting caps""); + return 16; + } + + + state = gst_video_decoder_set_output_state (GST_VIDEO_DECODER (dec), format, + rect->width, rect->height, dec->input_state); + gst_video_codec_state_unref (state); + + g_free (dec->imagedata); + dec->imagedata = g_malloc0 (dec->format.width * dec->format.height * + dec->format.bytes_per_pixel); + GST_DEBUG_OBJECT (dec, ""Allocated image data at %p"", dec->imagedata); + + dec->format.stride = dec->format.width * dec->format.bytes_per_pixel; + + return 16; +} +","@@ -260,7 +260,7 @@ vmnc_handle_wmvi_rectangle (GstVMncDec * dec, struct RfbRectangle *rect, + gst_video_codec_state_unref (state); + + g_free (dec->imagedata); +- dec->imagedata = g_malloc (dec->format.width * dec->format.height * ++ dec->imagedata = g_malloc0 (dec->format.width * dec->format.height * + dec->format.bytes_per_pixel); + GST_DEBUG_OBJECT (dec, ""Allocated image data at %p"", dec->imagedata); + +@@ -790,6 +790,10 @@ vmnc_handle_packet (GstVMncDec * dec, const guint8 * data, int len, + GST_WARNING_OBJECT (dec, ""Rectangle out of range, type %d"", r.type); + return ERROR_INVALID; + } ++ } else if (r.width > 16384 || r.height > 16384) { ++ GST_WARNING_OBJECT (dec, ""Width or height too high: %ux%u"", r.width, ++ r.height); ++ return ERROR_INVALID; + } + + switch (r.type) {",1169,1500,2048 +9129,"static int check_cond_jmp_op(struct bpf_verifier_env *env, + struct bpf_insn *insn, int *insn_idx) +{ + struct bpf_verifier_state *this_branch = env->cur_state; + struct bpf_verifier_state *other_branch; + struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; + struct bpf_reg_state *dst_reg, *other_branch_regs; + u8 opcode = BPF_OP(insn->code); + int err; + + if (opcode > BPF_JSLE) { + verbose(env, ""invalid BPF_JMP opcode %x\n"", opcode); + return -EINVAL; + } + + if (BPF_SRC(insn->code) == BPF_X) { + if (insn->imm != 0) { + verbose(env, ""BPF_JMP uses reserved fields\n""); + return -EINVAL; + } + + /* check src1 operand */ + err = check_reg_arg(env, insn->src_reg, SRC_OP); + if (err) + return err; + + if (is_pointer_value(env, insn->src_reg)) { + verbose(env, ""R%d pointer comparison prohibited\n"", + insn->src_reg); + return -EACCES; + } + } else { + if (insn->src_reg != BPF_REG_0) { + verbose(env, ""BPF_JMP uses reserved fields\n""); + return -EINVAL; + } + } + + /* check src2 operand */ + err = check_reg_arg(env, insn->dst_reg, SRC_OP); + if (err) + return err; + + dst_reg = ®s[insn->dst_reg]; + + if (BPF_SRC(insn->code) == BPF_K) { + int pred = is_branch_taken(dst_reg, insn->imm, opcode); + + if (pred == 1) { + /* only follow the goto, ignore fall-through */ + *insn_idx += insn->off; + return 0; + } else if (pred == 0) { + /* only follow fall-through branch, since + * that's where the program will go + */ + return 0; + } + } + + other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, + false); + if (!other_branch) + return -EFAULT; + other_branch_regs = other_branch->frame[other_branch->curframe]->regs; + + /* detect if we are comparing against a constant value so we can adjust + * our min/max values for our dst register. + * this is only legit if both are scalars (or pointers to the same + * object, I suppose, but we don't support that right now), because + * otherwise the different base pointers mean the offsets aren't + * comparable. + */ + if (BPF_SRC(insn->code) == BPF_X) { + if (dst_reg->type == SCALAR_VALUE && + regs[insn->src_reg].type == SCALAR_VALUE) { + if (tnum_is_const(regs[insn->src_reg].var_off)) + reg_set_min_max(&other_branch_regs[insn->dst_reg], + dst_reg, regs[insn->src_reg].var_off.value, + opcode); + else if (tnum_is_const(dst_reg->var_off)) + reg_set_min_max_inv(&other_branch_regs[insn->src_reg], + ®s[insn->src_reg], + dst_reg->var_off.value, opcode); + else if (opcode == BPF_JEQ || opcode == BPF_JNE) + /* Comparing for equality, we can combine knowledge */ + reg_combine_min_max(&other_branch_regs[insn->src_reg], + &other_branch_regs[insn->dst_reg], + ®s[insn->src_reg], + ®s[insn->dst_reg], opcode); + } + } else if (dst_reg->type == SCALAR_VALUE) { + reg_set_min_max(&other_branch_regs[insn->dst_reg], + dst_reg, insn->imm, opcode); + } + + /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */ + if (BPF_SRC(insn->code) == BPF_K && + insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && + reg_type_may_be_null(dst_reg->type)) { + /* Mark all identical registers in each branch as either + * safe or unknown depending R == 0 or R != 0 conditional. + */ + mark_ptr_or_null_regs(this_branch, insn->dst_reg, + opcode == BPF_JNE); + mark_ptr_or_null_regs(other_branch, insn->dst_reg, + opcode == BPF_JEQ); + } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], + this_branch, other_branch) && + is_pointer_value(env, insn->dst_reg)) { + verbose(env, ""R%d pointer comparison prohibited\n"", + insn->dst_reg); + return -EACCES; + } + if (env->log.level) + print_verifier_state(env, this_branch->frame[this_branch->curframe]); + return 0; +} +",0,"static int check_cond_jmp_op(struct bpf_verifier_env *env, + struct bpf_insn *insn, int *insn_idx) +{ + struct bpf_verifier_state *this_branch = env->cur_state; + struct bpf_verifier_state *other_branch; + struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; + struct bpf_reg_state *dst_reg, *other_branch_regs; + u8 opcode = BPF_OP(insn->code); + int err; + + if (opcode > BPF_JSLE) { + verbose(env, ""invalid BPF_JMP opcode %x\n"", opcode); + return -EINVAL; + } + + if (BPF_SRC(insn->code) == BPF_X) { + if (insn->imm != 0) { + verbose(env, ""BPF_JMP uses reserved fields\n""); + return -EINVAL; + } + + /* check src1 operand */ + err = check_reg_arg(env, insn->src_reg, SRC_OP); + if (err) + return err; + + if (is_pointer_value(env, insn->src_reg)) { + verbose(env, ""R%d pointer comparison prohibited\n"", + insn->src_reg); + return -EACCES; + } + } else { + if (insn->src_reg != BPF_REG_0) { + verbose(env, ""BPF_JMP uses reserved fields\n""); + return -EINVAL; + } + } + + /* check src2 operand */ + err = check_reg_arg(env, insn->dst_reg, SRC_OP); + if (err) + return err; + + dst_reg = ®s[insn->dst_reg]; + + if (BPF_SRC(insn->code) == BPF_K) { + int pred = is_branch_taken(dst_reg, insn->imm, opcode); + + if (pred == 1) { + /* only follow the goto, ignore fall-through */ + *insn_idx += insn->off; + return 0; + } else if (pred == 0) { + /* only follow fall-through branch, since + * that's where the program will go + */ + return 0; + } + } + + other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, + false); + if (!other_branch) + return -EFAULT; + other_branch_regs = other_branch->frame[other_branch->curframe]->regs; + + /* detect if we are comparing against a constant value so we can adjust + * our min/max values for our dst register. + * this is only legit if both are scalars (or pointers to the same + * object, I suppose, but we don't support that right now), because + * otherwise the different base pointers mean the offsets aren't + * comparable. + */ + if (BPF_SRC(insn->code) == BPF_X) { + if (dst_reg->type == SCALAR_VALUE && + regs[insn->src_reg].type == SCALAR_VALUE) { + if (tnum_is_const(regs[insn->src_reg].var_off)) + reg_set_min_max(&other_branch_regs[insn->dst_reg], + dst_reg, regs[insn->src_reg].var_off.value, + opcode); + else if (tnum_is_const(dst_reg->var_off)) + reg_set_min_max_inv(&other_branch_regs[insn->src_reg], + ®s[insn->src_reg], + dst_reg->var_off.value, opcode); + else if (opcode == BPF_JEQ || opcode == BPF_JNE) + /* Comparing for equality, we can combine knowledge */ + reg_combine_min_max(&other_branch_regs[insn->src_reg], + &other_branch_regs[insn->dst_reg], + ®s[insn->src_reg], + ®s[insn->dst_reg], opcode); + } + } else if (dst_reg->type == SCALAR_VALUE) { + reg_set_min_max(&other_branch_regs[insn->dst_reg], + dst_reg, insn->imm, opcode); + } + + /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */ + if (BPF_SRC(insn->code) == BPF_K && + insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && + reg_type_may_be_null(dst_reg->type)) { + /* Mark all identical registers in each branch as either + * safe or unknown depending R == 0 or R != 0 conditional. + */ + mark_ptr_or_null_regs(this_branch, insn->dst_reg, + opcode == BPF_JNE); + mark_ptr_or_null_regs(other_branch, insn->dst_reg, + opcode == BPF_JEQ); + } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], + this_branch, other_branch) && + is_pointer_value(env, insn->dst_reg)) { + verbose(env, ""R%d pointer comparison prohibited\n"", + insn->dst_reg); + return -EACCES; + } + if (env->log.level) + print_verifier_state(env, this_branch->frame[this_branch->curframe]); + return 0; +} +","@@ -3103,6 +3103,40 @@ static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, + } + } + ++static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, ++ const struct bpf_insn *insn) ++{ ++ return env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K; ++} ++ ++static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, ++ u32 alu_state, u32 alu_limit) ++{ ++ /* If we arrived here from different branches with different ++ * state or limits to sanitize, then this won't work. ++ */ ++ if (aux->alu_state && ++ (aux->alu_state != alu_state || ++ aux->alu_limit != alu_limit)) ++ return -EACCES; ++ ++ /* Corresponding fixup done in fixup_bpf_calls(). */ ++ aux->alu_state = alu_state; ++ aux->alu_limit = alu_limit; ++ return 0; ++} ++ ++static int sanitize_val_alu(struct bpf_verifier_env *env, ++ struct bpf_insn *insn) ++{ ++ struct bpf_insn_aux_data *aux = cur_aux(env); ++ ++ if (can_skip_alu_sanitation(env, insn)) ++ return 0; ++ ++ return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); ++} ++ + static int sanitize_ptr_alu(struct bpf_verifier_env *env, + struct bpf_insn *insn, + const struct bpf_reg_state *ptr_reg, +@@ -3117,7 +3151,7 @@ static int sanitize_ptr_alu(struct bpf_verifier_env *env, + struct bpf_reg_state tmp; + bool ret; + +- if (env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K) ++ if (can_skip_alu_sanitation(env, insn)) + return 0; + + /* We already marked aux for masking from non-speculative +@@ -3133,19 +3167,8 @@ static int sanitize_ptr_alu(struct bpf_verifier_env *env, + + if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg)) + return 0; +- +- /* If we arrived here from different branches with different +- * limits to sanitize, then this won't work. +- */ +- if (aux->alu_state && +- (aux->alu_state != alu_state || +- aux->alu_limit != alu_limit)) ++ if (update_alu_sanitation_state(aux, alu_state, alu_limit)) + return -EACCES; +- +- /* Corresponding fixup done in fixup_bpf_calls(). */ +- aux->alu_state = alu_state; +- aux->alu_limit = alu_limit; +- + do_sim: + /* Simulate and find potential out-of-bounds access under + * speculative execution from truncation as a result of +@@ -3418,6 +3441,8 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, + s64 smin_val, smax_val; + u64 umin_val, umax_val; + u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; ++ u32 dst = insn->dst_reg; ++ int ret; + + if (insn_bitness == 32) { + /* Relevant for 32-bit RSH: Information can propagate towards +@@ -3452,6 +3477,11 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, + + switch (opcode) { + case BPF_ADD: ++ ret = sanitize_val_alu(env, insn); ++ if (ret < 0) { ++ verbose(env, ""R%d tried to add from different pointers or scalars\n"", dst); ++ return ret; ++ } + if (signed_add_overflows(dst_reg->smin_value, smin_val) || + signed_add_overflows(dst_reg->smax_value, smax_val)) { + dst_reg->smin_value = S64_MIN; +@@ -3471,6 +3501,11 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, + dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); + break; + case BPF_SUB: ++ ret = sanitize_val_alu(env, insn); ++ if (ret < 0) { ++ verbose(env, ""R%d tried to sub from different pointers or scalars\n"", dst); ++ return ret; ++ } + if (signed_sub_overflows(dst_reg->smin_value, smax_val) || + signed_sub_overflows(dst_reg->smax_value, smin_val)) { + /* Overflow possible, we know nothing */",1118,1449,2048 +18845,"long ContentEncoding::ParseEncryptionEntry( + long long start, + long long size, + IMkvReader* pReader, + ContentEncryption* encryption) { + assert(pReader); + assert(encryption); + + long long pos = start; + const long long stop = start + size; + + + while (pos < stop) { + long long id, size; + const long status = ParseElementHeader(pReader, + pos, + stop, + id, + size); + if (status < 0) //error + return status; + + if (id == 0x7E1) { + encryption->algo = UnserializeUInt(pReader, pos, size); + if (encryption->algo != 5) + + return E_FILE_FORMAT_INVALID; + } else if (id == 0x7E2) { + delete[] encryption->key_id; + encryption->key_id = NULL; + encryption->key_id_len = 0; + + if (size <= 0) + return E_FILE_FORMAT_INVALID; + + const size_t buflen = static_cast(size); + typedef unsigned char* buf_t; + const buf_t buf = new (std::nothrow) unsigned char[buflen]; + + if (buf == NULL) + return -1; + + const int read_status = pReader->Read(pos, buflen, buf); + if (read_status) { + delete [] buf; + return status; + } + + encryption->key_id = buf; + + encryption->key_id_len = buflen; + } else if (id == 0x7E3) { + delete[] encryption->signature; + encryption->signature = NULL; + encryption->signature_len = 0; + + if (size <= 0) + return E_FILE_FORMAT_INVALID; + + const size_t buflen = static_cast(size); + typedef unsigned char* buf_t; + const buf_t buf = new (std::nothrow) unsigned char[buflen]; + + if (buf == NULL) + return -1; + + const int read_status = pReader->Read(pos, buflen, buf); + if (read_status) { + delete [] buf; + return status; + } + + encryption->signature = buf; + + encryption->signature_len = buflen; + } else if (id == 0x7E4) { + delete[] encryption->sig_key_id; + encryption->sig_key_id = NULL; + encryption->sig_key_id_len = 0; + + if (size <= 0) + return E_FILE_FORMAT_INVALID; + + const size_t buflen = static_cast(size); + typedef unsigned char* buf_t; + const buf_t buf = new (std::nothrow) unsigned char[buflen]; + + if (buf == NULL) + return -1; + + const int read_status = pReader->Read(pos, buflen, buf); + if (read_status) { + delete [] buf; + return status; + } + + encryption->sig_key_id = buf; + encryption->sig_key_id_len = buflen; + } else if (id == 0x7E5) { + encryption->sig_algo = UnserializeUInt(pReader, pos, size); + } else if (id == 0x7E6) { + encryption->sig_hash_algo = UnserializeUInt(pReader, pos, size); + + } else if (id == 0x7E7) { + const long status = ParseContentEncAESSettingsEntry( + pos, + size, + pReader, + &encryption->aes_settings); + if (status) + return status; + } + + pos += size; //consume payload + assert(pos <= stop); + } + + return 0; + } +",1,"long ContentEncoding::ParseEncryptionEntry( +long ContentEncoding::ParseEncryptionEntry(long long start, long long size, + IMkvReader* pReader, + ContentEncryption* encryption) { + assert(pReader); + assert(encryption); + + long long pos = start; + const long long stop = start + size; + + + while (pos < stop) { + long long id, size; + const long status = ParseElementHeader(pReader, pos, stop, id, size); + if (status < 0) // error + return status; + + if (id == 0x7E1) { + encryption->algo = UnserializeUInt(pReader, pos, size); + if (encryption->algo != 5) + + return E_FILE_FORMAT_INVALID; + } else if (id == 0x7E2) { + delete[] encryption -> key_id; + encryption->key_id = NULL; + encryption->key_id_len = 0; + + if (size <= 0) + return E_FILE_FORMAT_INVALID; + + const size_t buflen = static_cast(size); + typedef unsigned char* buf_t; + const buf_t buf = new (std::nothrow) unsigned char[buflen]; + + if (buf == NULL) + return -1; + + const int read_status = + pReader->Read(pos, static_cast(buflen), buf); + if (read_status) { + delete[] buf; + return status; + } + + encryption->key_id = buf; + + encryption->key_id_len = buflen; + } else if (id == 0x7E3) { + delete[] encryption -> signature; + encryption->signature = NULL; + encryption->signature_len = 0; + + if (size <= 0) + return E_FILE_FORMAT_INVALID; + + const size_t buflen = static_cast(size); + typedef unsigned char* buf_t; + const buf_t buf = new (std::nothrow) unsigned char[buflen]; + + if (buf == NULL) + return -1; + + const int read_status = + pReader->Read(pos, static_cast(buflen), buf); + if (read_status) { + delete[] buf; + return status; + } + + encryption->signature = buf; + + encryption->signature_len = buflen; + } else if (id == 0x7E4) { + delete[] encryption -> sig_key_id; + encryption->sig_key_id = NULL; + encryption->sig_key_id_len = 0; + + if (size <= 0) + return E_FILE_FORMAT_INVALID; + + const size_t buflen = static_cast(size); + typedef unsigned char* buf_t; + const buf_t buf = new (std::nothrow) unsigned char[buflen]; + + if (buf == NULL) + return -1; + + const int read_status = + pReader->Read(pos, static_cast(buflen), buf); + if (read_status) { + delete[] buf; + return status; + } + + encryption->sig_key_id = buf; + encryption->sig_key_id_len = buflen; + } else if (id == 0x7E5) { + encryption->sig_algo = UnserializeUInt(pReader, pos, size); + } else if (id == 0x7E6) { + encryption->sig_hash_algo = UnserializeUInt(pReader, pos, size); + + } else if (id == 0x7E7) { + const long status = ParseContentEncAESSettingsEntry( + pos, size, pReader, &encryption->aes_settings); + if (status) + return status; + } + + pos += size; // consume payload + assert(pos <= stop); + } + + return 0; + } +","@@ -12,1380 +12,1208 @@ + + #include + #include + +-mkvparser::IMkvReader::~IMkvReader() +-{ ++#ifdef _MSC_VER ++// Disable MSVC warnings that suggest making code non-portable. ++#pragma warning(disable : 4996) ++#endif ++ ++mkvparser::IMkvReader::~IMkvReader() {} ++ ++void mkvparser::GetVersion(int& major, int& minor, int& build, int& revision) { ++ major = 1; ++ minor = 0; ++ build = 0; ++ revision = 28; + } + +-void mkvparser::GetVersion(int& major, int& minor, int& build, int& revision) +-{ +- major = 1; +- minor = 0; +- build = 0; +- revision = 27; +-} ++long long mkvparser::ReadUInt(IMkvReader* pReader, long long pos, long& len) { ++ assert(pReader); ++ assert(pos >= 0); + +-long long mkvparser::ReadUInt(IMkvReader* pReader, long long pos, long& len) +-{ +- assert(pReader); +- assert(pos >= 0); ++ int status; + +- int status; ++ //#ifdef _DEBUG ++ // long long total, available; ++ // status = pReader->Length(&total, &available); ++ // assert(status >= 0); ++ // assert((total < 0) || (available <= total)); ++ // assert(pos < available); ++ // assert((available - pos) >= 1); //assume here max u-int len is 8 ++ //#endif + +-//#ifdef _DEBUG +-// long long total, available; +-// status = pReader->Length(&total, &available); +-// assert(status >= 0); +-// assert((total < 0) || (available <= total)); +-// assert(pos < available); +-// assert((available - pos) >= 1); //assume here max u-int len is 8 +-//#endif ++ len = 1; + +- len = 1; ++ unsigned char b; + +- unsigned char b; ++ status = pReader->Read(pos, 1, &b); + ++ if (status < 0) // error or underflow ++ return status; ++ ++ if (status > 0) // interpreted as ""underflow"" ++ return E_BUFFER_NOT_FULL; ++ ++ if (b == 0) // we can't handle u-int values larger than 8 bytes ++ return E_FILE_FORMAT_INVALID; ++ ++ unsigned char m = 0x80; ++ ++ while (!(b & m)) { ++ m >>= 1; ++ ++len; ++ } ++ ++ //#ifdef _DEBUG ++ // assert((available - pos) >= len); ++ //#endif ++ ++ long long result = b & (~m); ++ ++pos; ++ ++ for (int i = 1; i < len; ++i) { + status = pReader->Read(pos, 1, &b); + +- if (status < 0) //error or underflow +- return status; +- +- if (status > 0) //interpreted as ""underflow"" +- return E_BUFFER_NOT_FULL; +- +- if (b == 0) //we can't handle u-int values larger than 8 bytes +- return E_FILE_FORMAT_INVALID; +- +- unsigned char m = 0x80; +- +- while (!(b & m)) +- { +- m >>= 1; +- ++len; ++ if (status < 0) { ++ len = 1; ++ return status; + } + +-//#ifdef _DEBUG +-// assert((available - pos) >= len); +-//#endif ++ if (status > 0) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; ++ } + +- long long result = b & (~m); ++ result <<= 8; ++ result |= b; ++ + ++pos; ++ } + +- for (int i = 1; i < len; ++i) +- { +- status = pReader->Read(pos, 1, &b); +- +- if (status < 0) +- { +- len = 1; +- return status; +- } +- +- if (status > 0) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } +- +- result <<= 8; +- result |= b; +- +- ++pos; +- } +- +- return result; ++ return result; + } + +-long long mkvparser::GetUIntLength( +- IMkvReader* pReader, +- long long pos, +- long& len) +-{ +- assert(pReader); +- assert(pos >= 0); ++long long mkvparser::GetUIntLength(IMkvReader* pReader, long long pos, ++ long& len) { ++ assert(pReader); ++ assert(pos >= 0); + +- long long total, available; ++ long long total, available; + +- int status = pReader->Length(&total, &available); +- assert(status >= 0); +- assert((total < 0) || (available <= total)); ++ int status = pReader->Length(&total, &available); ++ assert(status >= 0); ++ assert((total < 0) || (available <= total)); + +- len = 1; ++ len = 1; + +- if (pos >= available) +- return pos; //too few bytes available ++ if (pos >= available) ++ return pos; // too few bytes available + ++ unsigned char b; ++ ++ status = pReader->Read(pos, 1, &b); ++ ++ if (status < 0) ++ return status; ++ ++ assert(status == 0); ++ ++ if (b == 0) // we can't handle u-int values larger than 8 bytes ++ return E_FILE_FORMAT_INVALID; ++ ++ unsigned char m = 0x80; ++ ++ while (!(b & m)) { ++ m >>= 1; ++ ++len; ++ } ++ ++ return 0; // success ++} ++ ++// TODO(vigneshv): This function assumes that unsigned values never have their ++// high bit set. ++long long mkvparser::UnserializeUInt(IMkvReader* pReader, long long pos, ++ long long size) { ++ assert(pReader); ++ assert(pos >= 0); ++ ++ if ((size <= 0) || (size > 8)) ++ return E_FILE_FORMAT_INVALID; ++ ++ long long result = 0; ++ ++ for (long long i = 0; i < size; ++i) { + unsigned char b; + +- status = pReader->Read(pos, 1, &b); ++ const long status = pReader->Read(pos, 1, &b); + + if (status < 0) +- return status; ++ return status; + +- assert(status == 0); ++ result <<= 8; ++ result |= b; + +- if (b == 0) //we can't handle u-int values larger than 8 bytes +- return E_FILE_FORMAT_INVALID; ++ ++pos; ++ } + +- unsigned char m = 0x80; +- +- while (!(b & m)) +- { +- m >>= 1; +- ++len; +- } +- +- return 0; //success ++ return result; + } + ++long mkvparser::UnserializeFloat(IMkvReader* pReader, long long pos, ++ long long size_, double& result) { ++ assert(pReader); ++ assert(pos >= 0); + +-long long mkvparser::UnserializeUInt( +- IMkvReader* pReader, +- long long pos, +- long long size) +-{ +- assert(pReader); +- assert(pos >= 0); ++ if ((size_ != 4) && (size_ != 8)) ++ return E_FILE_FORMAT_INVALID; + +- if ((size <= 0) || (size > 8)) +- return E_FILE_FORMAT_INVALID; ++ const long size = static_cast(size_); + +- long long result = 0; ++ unsigned char buf[8]; + +- for (long long i = 0; i < size; ++i) +- { +- unsigned char b; ++ const int status = pReader->Read(pos, size, buf); + +- const long status = pReader->Read(pos, 1, &b); ++ if (status < 0) // error ++ return status; + +- if (status < 0) +- return status; ++ if (size == 4) { ++ union { ++ float f; ++ unsigned long ff; ++ }; + +- result <<= 8; +- result |= b; ++ ff = 0; + +- ++pos; ++ for (int i = 0;;) { ++ ff |= buf[i]; ++ ++ if (++i >= 4) ++ break; ++ ++ ff <<= 8; + } + +- return result; ++ result = f; ++ } else { ++ assert(size == 8); ++ ++ union { ++ double d; ++ unsigned long long dd; ++ }; ++ ++ dd = 0; ++ ++ for (int i = 0;;) { ++ dd |= buf[i]; ++ ++ if (++i >= 8) ++ break; ++ ++ dd <<= 8; ++ } ++ ++ result = d; ++ } ++ ++ return 0; + } + ++long mkvparser::UnserializeInt(IMkvReader* pReader, long long pos, long size, ++ long long& result) { ++ assert(pReader); ++ assert(pos >= 0); ++ assert(size > 0); ++ assert(size <= 8); + +-long mkvparser::UnserializeFloat( +- IMkvReader* pReader, +- long long pos, +- long long size_, +- double& result) +-{ +- assert(pReader); +- assert(pos >= 0); ++ { ++ signed char b; + +- if ((size_ != 4) && (size_ != 8)) +- return E_FILE_FORMAT_INVALID; ++ const long status = pReader->Read(pos, 1, (unsigned char*)&b); + +- const long size = static_cast(size_); ++ if (status < 0) ++ return status; + +- unsigned char buf[8]; ++ result = b; + +- const int status = pReader->Read(pos, size, buf); ++ ++pos; ++ } + +- if (status < 0) //error +- return status; ++ for (long i = 1; i < size; ++i) { ++ unsigned char b; + +- if (size == 4) +- { +- union +- { +- float f; +- unsigned long ff; +- }; ++ const long status = pReader->Read(pos, 1, &b); + +- ff = 0; ++ if (status < 0) ++ return status; + +- for (int i = 0;;) +- { +- ff |= buf[i]; ++ result <<= 8; ++ result |= b; + +- if (++i >= 4) +- break; ++ ++pos; ++ } + +- ff <<= 8; +- } +- +- result = f; +- } +- else +- { +- assert(size == 8); +- +- union +- { +- double d; +- unsigned long long dd; +- }; +- +- dd = 0; +- +- for (int i = 0;;) +- { +- dd |= buf[i]; +- +- if (++i >= 8) +- break; +- +- dd <<= 8; +- } +- +- result = d; +- } +- +- return 0; ++ return 0; // success + } + ++long mkvparser::UnserializeString(IMkvReader* pReader, long long pos, ++ long long size_, char*& str) { ++ delete[] str; ++ str = NULL; + +-long mkvparser::UnserializeInt( +- IMkvReader* pReader, +- long long pos, +- long size, +- long long& result) +-{ +- assert(pReader); +- assert(pos >= 0); +- assert(size > 0); +- assert(size <= 8); ++ if (size_ >= LONG_MAX) // we need (size+1) chars ++ return E_FILE_FORMAT_INVALID; + +- { +- signed char b; ++ const long size = static_cast(size_); + +- const long status = pReader->Read(pos, 1, (unsigned char*)&b); ++ str = new (std::nothrow) char[size + 1]; + +- if (status < 0) +- return status; ++ if (str == NULL) ++ return -1; + +- result = b; ++ unsigned char* const buf = reinterpret_cast(str); + +- ++pos; +- } ++ const long status = pReader->Read(pos, size, buf); + +- for (long i = 1; i < size; ++i) +- { +- unsigned char b; +- +- const long status = pReader->Read(pos, 1, &b); +- +- if (status < 0) +- return status; +- +- result <<= 8; +- result |= b; +- +- ++pos; +- } +- +- return 0; //success +-} +- +- +-long mkvparser::UnserializeString( +- IMkvReader* pReader, +- long long pos, +- long long size_, +- char*& str) +-{ ++ if (status) { + delete[] str; + str = NULL; + +- if (size_ >= LONG_MAX) //we need (size+1) chars +- return E_FILE_FORMAT_INVALID; ++ return status; ++ } + +- const long size = static_cast(size_); ++ str[size] = '\0'; + +- str = new (std::nothrow) char[size+1]; +- +- if (str == NULL) +- return -1; +- +- unsigned char* const buf = reinterpret_cast(str); +- +- const long status = pReader->Read(pos, size, buf); +- +- if (status) +- { +- delete[] str; +- str = NULL; +- +- return status; +- } +- +- str[size] = '\0'; +- +- return 0; //success ++ return 0; // success + } + ++long mkvparser::ParseElementHeader(IMkvReader* pReader, long long& pos, ++ long long stop, long long& id, ++ long long& size) { ++ if ((stop >= 0) && (pos >= stop)) ++ return E_FILE_FORMAT_INVALID; + +-long mkvparser::ParseElementHeader( +- IMkvReader* pReader, +- long long& pos, +- long long stop, +- long long& id, +- long long& size) +-{ +- if ((stop >= 0) && (pos >= stop)) +- return E_FILE_FORMAT_INVALID; ++ long len; + +- long len; ++ id = ReadUInt(pReader, pos, len); + +- id = ReadUInt(pReader, pos, len); ++ if (id < 0) ++ return E_FILE_FORMAT_INVALID; + +- if (id < 0) +- return E_FILE_FORMAT_INVALID; ++ pos += len; // consume id + +- pos += len; //consume id ++ if ((stop >= 0) && (pos >= stop)) ++ return E_FILE_FORMAT_INVALID; + +- if ((stop >= 0) && (pos >= stop)) +- return E_FILE_FORMAT_INVALID; ++ size = ReadUInt(pReader, pos, len); + +- size = ReadUInt(pReader, pos, len); ++ if (size < 0) ++ return E_FILE_FORMAT_INVALID; + +- if (size < 0) +- return E_FILE_FORMAT_INVALID; ++ pos += len; // consume length of size + +- pos += len; //consume length of size ++ // pos now designates payload + +- //pos now designates payload ++ if ((stop >= 0) && ((pos + size) > stop)) ++ return E_FILE_FORMAT_INVALID; + +- if ((stop >= 0) && ((pos + size) > stop)) +- return E_FILE_FORMAT_INVALID; +- +- return 0; //success ++ return 0; // success + } + ++bool mkvparser::Match(IMkvReader* pReader, long long& pos, unsigned long id_, ++ long long& val) { ++ assert(pReader); ++ assert(pos >= 0); + +-bool mkvparser::Match( +- IMkvReader* pReader, +- long long& pos, +- unsigned long id_, +- long long& val) +-{ +- assert(pReader); +- assert(pos >= 0); ++ long long total, available; + +- long long total, available; ++ const long status = pReader->Length(&total, &available); ++ assert(status >= 0); ++ assert((total < 0) || (available <= total)); ++ if (status < 0) ++ return false; + +- const long status = pReader->Length(&total, &available); +- assert(status >= 0); +- assert((total < 0) || (available <= total)); +- if (status < 0) +- return false; ++ long len; + +- long len; ++ const long long id = ReadUInt(pReader, pos, len); ++ assert(id >= 0); ++ assert(len > 0); ++ assert(len <= 8); ++ assert((pos + len) <= available); + +- const long long id = ReadUInt(pReader, pos, len); +- assert(id >= 0); +- assert(len > 0); +- assert(len <= 8); +- assert((pos + len) <= available); ++ if ((unsigned long)id != id_) ++ return false; + +- if ((unsigned long)id != id_) +- return false; ++ pos += len; // consume id + +- pos += len; //consume id ++ const long long size = ReadUInt(pReader, pos, len); ++ assert(size >= 0); ++ assert(size <= 8); ++ assert(len > 0); ++ assert(len <= 8); ++ assert((pos + len) <= available); + +- const long long size = ReadUInt(pReader, pos, len); +- assert(size >= 0); +- assert(size <= 8); +- assert(len > 0); +- assert(len <= 8); +- assert((pos + len) <= available); ++ pos += len; // consume length of size of payload + +- pos += len; //consume length of size of payload ++ val = UnserializeUInt(pReader, pos, size); ++ assert(val >= 0); + +- val = UnserializeUInt(pReader, pos, size); +- assert(val >= 0); ++ pos += size; // consume size of payload + +- pos += size; //consume size of payload +- +- return true; ++ return true; + } + +-bool mkvparser::Match( +- IMkvReader* pReader, +- long long& pos, +- unsigned long id_, +- unsigned char*& buf, +- size_t& buflen) +-{ +- assert(pReader); +- assert(pos >= 0); ++bool mkvparser::Match(IMkvReader* pReader, long long& pos, unsigned long id_, ++ unsigned char*& buf, size_t& buflen) { ++ assert(pReader); ++ assert(pos >= 0); + +- long long total, available; ++ long long total, available; + +- long status = pReader->Length(&total, &available); +- assert(status >= 0); +- assert((total < 0) || (available <= total)); +- if (status < 0) +- return false; ++ long status = pReader->Length(&total, &available); ++ assert(status >= 0); ++ assert((total < 0) || (available <= total)); ++ if (status < 0) ++ return false; + +- long len; +- const long long id = ReadUInt(pReader, pos, len); +- assert(id >= 0); +- assert(len > 0); +- assert(len <= 8); +- assert((pos + len) <= available); ++ long len; ++ const long long id = ReadUInt(pReader, pos, len); ++ assert(id >= 0); ++ assert(len > 0); ++ assert(len <= 8); ++ assert((pos + len) <= available); + +- if ((unsigned long)id != id_) +- return false; ++ if ((unsigned long)id != id_) ++ return false; + +- pos += len; //consume id ++ pos += len; // consume id + +- const long long size_ = ReadUInt(pReader, pos, len); +- assert(size_ >= 0); +- assert(len > 0); +- assert(len <= 8); +- assert((pos + len) <= available); ++ const long long size_ = ReadUInt(pReader, pos, len); ++ assert(size_ >= 0); ++ assert(len > 0); ++ assert(len <= 8); ++ assert((pos + len) <= available); + +- pos += len; //consume length of size of payload +- assert((pos + size_) <= available); ++ pos += len; // consume length of size of payload ++ assert((pos + size_) <= available); + +- const long buflen_ = static_cast(size_); ++ const long buflen_ = static_cast(size_); + +- buf = new (std::nothrow) unsigned char[buflen_]; +- assert(buf); //TODO ++ buf = new (std::nothrow) unsigned char[buflen_]; ++ assert(buf); // TODO + +- status = pReader->Read(pos, buflen_, buf); +- assert(status == 0); //TODO ++ status = pReader->Read(pos, buflen_, buf); ++ assert(status == 0); // TODO + +- buflen = buflen_; ++ buflen = buflen_; + +- pos += size_; //consume size of payload +- return true; ++ pos += size_; // consume size of payload ++ return true; + } + ++namespace mkvparser { + +-namespace mkvparser +-{ ++EBMLHeader::EBMLHeader() : m_docType(NULL) { Init(); } + +-EBMLHeader::EBMLHeader() : +- m_docType(NULL) +-{ +- Init(); +-} ++EBMLHeader::~EBMLHeader() { delete[] m_docType; } + +-EBMLHeader::~EBMLHeader() +-{ ++void EBMLHeader::Init() { ++ m_version = 1; ++ m_readVersion = 1; ++ m_maxIdLength = 4; ++ m_maxSizeLength = 8; ++ ++ if (m_docType) { + delete[] m_docType; ++ m_docType = NULL; ++ } ++ ++ m_docTypeVersion = 1; ++ m_docTypeReadVersion = 1; + } + +-void EBMLHeader::Init() +-{ +- m_version = 1; +- m_readVersion = 1; +- m_maxIdLength = 4; +- m_maxSizeLength = 8; ++long long EBMLHeader::Parse(IMkvReader* pReader, long long& pos) { ++ assert(pReader); + +- if (m_docType) +- { +- delete[] m_docType; +- m_docType = NULL; +- } ++ long long total, available; + +- m_docTypeVersion = 1; +- m_docTypeReadVersion = 1; +-} ++ long status = pReader->Length(&total, &available); + +-long long EBMLHeader::Parse( +- IMkvReader* pReader, +- long long& pos) +-{ +- assert(pReader); ++ if (status < 0) // error ++ return status; + +- long long total, available; ++ pos = 0; ++ long long end = (available >= 1024) ? 1024 : available; + +- long status = pReader->Length(&total, &available); ++ for (;;) { ++ unsigned char b = 0; + +- if (status < 0) //error ++ while (pos < end) { ++ status = pReader->Read(pos, 1, &b); ++ ++ if (status < 0) // error + return status; + +- pos = 0; +- long long end = (available >= 1024) ? 1024 : available; ++ if (b == 0x1A) ++ break; + +- for (;;) +- { +- unsigned char b = 0; +- +- while (pos < end) +- { +- status = pReader->Read(pos, 1, &b); +- +- if (status < 0) //error +- return status; +- +- if (b == 0x1A) +- break; +- +- ++pos; +- } +- +- if (b != 0x1A) +- { +- if (pos >= 1024) +- return E_FILE_FORMAT_INVALID; //don't bother looking anymore +- +- if ((total >= 0) && ((total - available) < 5)) +- return E_FILE_FORMAT_INVALID; +- +- return available + 5; //5 = 4-byte ID + 1st byte of size +- } +- +- if ((total >= 0) && ((total - pos) < 5)) +- return E_FILE_FORMAT_INVALID; +- +- if ((available - pos) < 5) +- return pos + 5; //try again later +- +- long len; +- +- const long long result = ReadUInt(pReader, pos, len); +- +- if (result < 0) //error +- return result; +- +- if (result == 0x0A45DFA3) //EBML Header ID +- { +- pos += len; //consume ID +- break; +- } +- +- ++pos; //throw away just the 0x1A byte, and try again ++ ++pos; + } + +- //pos designates start of size field ++ if (b != 0x1A) { ++ if (pos >= 1024) ++ return E_FILE_FORMAT_INVALID; // don't bother looking anymore + +- //get length of size field ++ if ((total >= 0) && ((total - available) < 5)) ++ return E_FILE_FORMAT_INVALID; + ++ return available + 5; // 5 = 4-byte ID + 1st byte of size ++ } ++ ++ if ((total >= 0) && ((total - pos) < 5)) ++ return E_FILE_FORMAT_INVALID; ++ ++ if ((available - pos) < 5) ++ return pos + 5; // try again later ++ ++ long len; ++ ++ const long long result = ReadUInt(pReader, pos, len); ++ ++ if (result < 0) // error ++ return result; ++ ++ if (result == 0x0A45DFA3) { // EBML Header ID ++ pos += len; // consume ID ++ break; ++ } ++ ++ ++pos; // throw away just the 0x1A byte, and try again ++ } ++ ++ // pos designates start of size field ++ ++ // get length of size field ++ ++ long len; ++ long long result = GetUIntLength(pReader, pos, len); ++ ++ if (result < 0) // error ++ return result; ++ ++ if (result > 0) // need more data ++ return result; ++ ++ assert(len > 0); ++ assert(len <= 8); ++ ++ if ((total >= 0) && ((total - pos) < len)) ++ return E_FILE_FORMAT_INVALID; ++ ++ if ((available - pos) < len) ++ return pos + len; // try again later ++ ++ // get the EBML header size ++ ++ result = ReadUInt(pReader, pos, len); ++ ++ if (result < 0) // error ++ return result; ++ ++ pos += len; // consume size field ++ ++ // pos now designates start of payload ++ ++ if ((total >= 0) && ((total - pos) < result)) ++ return E_FILE_FORMAT_INVALID; ++ ++ if ((available - pos) < result) ++ return pos + result; ++ ++ end = pos + result; ++ ++ Init(); ++ ++ while (pos < end) { ++ long long id, size; ++ ++ status = ParseElementHeader(pReader, pos, end, id, size); ++ ++ if (status < 0) // error ++ return status; ++ ++ if (size == 0) // weird ++ return E_FILE_FORMAT_INVALID; ++ ++ if (id == 0x0286) { // version ++ m_version = UnserializeUInt(pReader, pos, size); ++ ++ if (m_version <= 0) ++ return E_FILE_FORMAT_INVALID; ++ } else if (id == 0x02F7) { // read version ++ m_readVersion = UnserializeUInt(pReader, pos, size); ++ ++ if (m_readVersion <= 0) ++ return E_FILE_FORMAT_INVALID; ++ } else if (id == 0x02F2) { // max id length ++ m_maxIdLength = UnserializeUInt(pReader, pos, size); ++ ++ if (m_maxIdLength <= 0) ++ return E_FILE_FORMAT_INVALID; ++ } else if (id == 0x02F3) { // max size length ++ m_maxSizeLength = UnserializeUInt(pReader, pos, size); ++ ++ if (m_maxSizeLength <= 0) ++ return E_FILE_FORMAT_INVALID; ++ } else if (id == 0x0282) { // doctype ++ if (m_docType) ++ return E_FILE_FORMAT_INVALID; ++ ++ status = UnserializeString(pReader, pos, size, m_docType); ++ ++ if (status) // error ++ return status; ++ } else if (id == 0x0287) { // doctype version ++ m_docTypeVersion = UnserializeUInt(pReader, pos, size); ++ ++ if (m_docTypeVersion <= 0) ++ return E_FILE_FORMAT_INVALID; ++ } else if (id == 0x0285) { // doctype read version ++ m_docTypeReadVersion = UnserializeUInt(pReader, pos, size); ++ ++ if (m_docTypeReadVersion <= 0) ++ return E_FILE_FORMAT_INVALID; ++ } ++ ++ pos += size; ++ } ++ ++ assert(pos == end); ++ return 0; ++} ++ ++Segment::Segment(IMkvReader* pReader, long long elem_start, ++ // long long elem_size, ++ long long start, long long size) ++ : m_pReader(pReader), ++ m_element_start(elem_start), ++ // m_element_size(elem_size), ++ m_start(start), ++ m_size(size), ++ m_pos(start), ++ m_pUnknownSize(0), ++ m_pSeekHead(NULL), ++ m_pInfo(NULL), ++ m_pTracks(NULL), ++ m_pCues(NULL), ++ m_pChapters(NULL), ++ m_clusters(NULL), ++ m_clusterCount(0), ++ m_clusterPreloadCount(0), ++ m_clusterSize(0) {} ++ ++Segment::~Segment() { ++ const long count = m_clusterCount + m_clusterPreloadCount; ++ ++ Cluster** i = m_clusters; ++ Cluster** j = m_clusters + count; ++ ++ while (i != j) { ++ Cluster* const p = *i++; ++ assert(p); ++ ++ delete p; ++ } ++ ++ delete[] m_clusters; ++ ++ delete m_pTracks; ++ delete m_pInfo; ++ delete m_pCues; ++ delete m_pChapters; ++ delete m_pSeekHead; ++} ++ ++long long Segment::CreateInstance(IMkvReader* pReader, long long pos, ++ Segment*& pSegment) { ++ assert(pReader); ++ assert(pos >= 0); ++ ++ pSegment = NULL; ++ ++ long long total, available; ++ ++ const long status = pReader->Length(&total, &available); ++ ++ if (status < 0) // error ++ return status; ++ ++ if (available < 0) ++ return -1; ++ ++ if ((total >= 0) && (available > total)) ++ return -1; ++ ++ // I would assume that in practice this loop would execute ++ // exactly once, but we allow for other elements (e.g. Void) ++ // to immediately follow the EBML header. This is fine for ++ // the source filter case (since the entire file is available), ++ // but in the splitter case over a network we should probably ++ // just give up early. We could for example decide only to ++ // execute this loop a maximum of, say, 10 times. ++ // TODO: ++ // There is an implied ""give up early"" by only parsing up ++ // to the available limit. We do do that, but only if the ++ // total file size is unknown. We could decide to always ++ // use what's available as our limit (irrespective of whether ++ // we happen to know the total file length). This would have ++ // as its sense ""parse this much of the file before giving up"", ++ // which a slightly different sense from ""try to parse up to ++ // 10 EMBL elements before giving up"". ++ ++ for (;;) { ++ if ((total >= 0) && (pos >= total)) ++ return E_FILE_FORMAT_INVALID; ++ ++ // Read ID + long len; + long long result = GetUIntLength(pReader, pos, len); + +- if (result < 0) //error +- return result; ++ if (result) // error, or too few available bytes ++ return result; + +- if (result > 0) //need more data +- return result; ++ if ((total >= 0) && ((pos + len) > total)) ++ return E_FILE_FORMAT_INVALID; + +- assert(len > 0); +- assert(len <= 8); ++ if ((pos + len) > available) ++ return pos + len; + +- if ((total >= 0) && ((total - pos) < len)) +- return E_FILE_FORMAT_INVALID; ++ const long long idpos = pos; ++ const long long id = ReadUInt(pReader, pos, len); + +- if ((available - pos) < len) +- return pos + len; //try again later ++ if (id < 0) // error ++ return id; + +- //get the EBML header size ++ pos += len; // consume ID + +- result = ReadUInt(pReader, pos, len); ++ // Read Size + +- if (result < 0) //error +- return result; ++ result = GetUIntLength(pReader, pos, len); + +- pos += len; //consume size field ++ if (result) // error, or too few available bytes ++ return result; + +- //pos now designates start of payload ++ if ((total >= 0) && ((pos + len) > total)) ++ return E_FILE_FORMAT_INVALID; + +- if ((total >= 0) && ((total - pos) < result)) +- return E_FILE_FORMAT_INVALID; ++ if ((pos + len) > available) ++ return pos + len; + +- if ((available - pos) < result) +- return pos + result; ++ long long size = ReadUInt(pReader, pos, len); + +- end = pos + result; ++ if (size < 0) // error ++ return size; + +- Init(); ++ pos += len; // consume length of size of element + +- while (pos < end) +- { +- long long id, size; ++ // Pos now points to start of payload + +- status = ParseElementHeader( +- pReader, +- pos, +- end, +- id, +- size); ++ // Handle ""unknown size"" for live streaming of webm files. ++ const long long unknown_size = (1LL << (7 * len)) - 1; + +- if (status < 0) //error +- return status; ++ if (id == 0x08538067) { // Segment ID ++ if (size == unknown_size) ++ size = -1; + +- if (size == 0) //weird +- return E_FILE_FORMAT_INVALID; ++ else if (total < 0) ++ size = -1; + +- if (id == 0x0286) //version +- { +- m_version = UnserializeUInt(pReader, pos, size); ++ else if ((pos + size) > total) ++ size = -1; + +- if (m_version <= 0) +- return E_FILE_FORMAT_INVALID; +- } +- else if (id == 0x02F7) //read version +- { +- m_readVersion = UnserializeUInt(pReader, pos, size); ++ pSegment = new (std::nothrow) Segment(pReader, idpos, ++ // elem_size ++ pos, size); + +- if (m_readVersion <= 0) +- return E_FILE_FORMAT_INVALID; +- } +- else if (id == 0x02F2) //max id length +- { +- m_maxIdLength = UnserializeUInt(pReader, pos, size); ++ if (pSegment == 0) ++ return -1; // generic error + +- if (m_maxIdLength <= 0) +- return E_FILE_FORMAT_INVALID; +- } +- else if (id == 0x02F3) //max size length +- { +- m_maxSizeLength = UnserializeUInt(pReader, pos, size); +- +- if (m_maxSizeLength <= 0) +- return E_FILE_FORMAT_INVALID; +- } +- else if (id == 0x0282) //doctype +- { +- if (m_docType) +- return E_FILE_FORMAT_INVALID; +- +- status = UnserializeString(pReader, pos, size, m_docType); +- +- if (status) //error +- return status; +- } +- else if (id == 0x0287) //doctype version +- { +- m_docTypeVersion = UnserializeUInt(pReader, pos, size); +- +- if (m_docTypeVersion <= 0) +- return E_FILE_FORMAT_INVALID; +- } +- else if (id == 0x0285) //doctype read version +- { +- m_docTypeReadVersion = UnserializeUInt(pReader, pos, size); +- +- if (m_docTypeReadVersion <= 0) +- return E_FILE_FORMAT_INVALID; +- } +- +- pos += size; ++ return 0; // success + } + +- assert(pos == end); +- return 0; ++ if (size == unknown_size) ++ return E_FILE_FORMAT_INVALID; ++ ++ if ((total >= 0) && ((pos + size) > total)) ++ return E_FILE_FORMAT_INVALID; ++ ++ if ((pos + size) > available) ++ return pos + size; ++ ++ pos += size; // consume payload ++ } + } + ++long long Segment::ParseHeaders() { ++ // Outermost (level 0) segment object has been constructed, ++ // and pos designates start of payload. We need to find the ++ // inner (level 1) elements. ++ long long total, available; + +-Segment::Segment( +- IMkvReader* pReader, +- long long elem_start, +- //long long elem_size, +- long long start, +- long long size) : +- m_pReader(pReader), +- m_element_start(elem_start), +- //m_element_size(elem_size), +- m_start(start), +- m_size(size), +- m_pos(start), +- m_pUnknownSize(0), +- m_pSeekHead(NULL), +- m_pInfo(NULL), +- m_pTracks(NULL), +- m_pCues(NULL), +- m_pChapters(NULL), +- m_clusters(NULL), +- m_clusterCount(0), +- m_clusterPreloadCount(0), +- m_clusterSize(0) +-{ +-} ++ const int status = m_pReader->Length(&total, &available); + ++ if (status < 0) // error ++ return status; + +-Segment::~Segment() +-{ +- const long count = m_clusterCount + m_clusterPreloadCount; ++ assert((total < 0) || (available <= total)); + +- Cluster** i = m_clusters; +- Cluster** j = m_clusters + count; ++ const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; ++ assert((segment_stop < 0) || (total < 0) || (segment_stop <= total)); ++ assert((segment_stop < 0) || (m_pos <= segment_stop)); + +- while (i != j) +- { +- Cluster* const p = *i++; +- assert(p); ++ for (;;) { ++ if ((total >= 0) && (m_pos >= total)) ++ break; + +- delete p; +- } ++ if ((segment_stop >= 0) && (m_pos >= segment_stop)) ++ break; + +- delete[] m_clusters; ++ long long pos = m_pos; ++ const long long element_start = pos; + +- delete m_pTracks; +- delete m_pInfo; +- delete m_pCues; +- delete m_pChapters; +- delete m_pSeekHead; +-} ++ if ((pos + 1) > available) ++ return (pos + 1); + ++ long len; ++ long long result = GetUIntLength(m_pReader, pos, len); + +-long long Segment::CreateInstance( +- IMkvReader* pReader, +- long long pos, +- Segment*& pSegment) +-{ +- assert(pReader); +- assert(pos >= 0); ++ if (result < 0) // error ++ return result; + +- pSegment = NULL; ++ if (result > 0) // underflow (weird) ++ return (pos + 1); + +- long long total, available; ++ if ((segment_stop >= 0) && ((pos + len) > segment_stop)) ++ return E_FILE_FORMAT_INVALID; + +- const long status = pReader->Length(&total, &available); ++ if ((pos + len) > available) ++ return pos + len; + +- if (status < 0) //error +- return status; ++ const long long idpos = pos; ++ const long long id = ReadUInt(m_pReader, idpos, len); + +- if (available < 0) ++ if (id < 0) // error ++ return id; ++ ++ if (id == 0x0F43B675) // Cluster ID ++ break; ++ ++ pos += len; // consume ID ++ ++ if ((pos + 1) > available) ++ return (pos + 1); ++ ++ // Read Size ++ result = GetUIntLength(m_pReader, pos, len); ++ ++ if (result < 0) // error ++ return result; ++ ++ if (result > 0) // underflow (weird) ++ return (pos + 1); ++ ++ if ((segment_stop >= 0) && ((pos + len) > segment_stop)) ++ return E_FILE_FORMAT_INVALID; ++ ++ if ((pos + len) > available) ++ return pos + len; ++ ++ const long long size = ReadUInt(m_pReader, pos, len); ++ ++ if (size < 0) // error ++ return size; ++ ++ pos += len; // consume length of size of element ++ ++ const long long element_size = size + pos - element_start; ++ ++ // Pos now points to start of payload ++ ++ if ((segment_stop >= 0) && ((pos + size) > segment_stop)) ++ return E_FILE_FORMAT_INVALID; ++ ++ // We read EBML elements either in total or nothing at all. ++ ++ if ((pos + size) > available) ++ return pos + size; ++ ++ if (id == 0x0549A966) { // Segment Info ID ++ if (m_pInfo) ++ return E_FILE_FORMAT_INVALID; ++ ++ m_pInfo = new (std::nothrow) ++ SegmentInfo(this, pos, size, element_start, element_size); ++ ++ if (m_pInfo == NULL) + return -1; + +- if ((total >= 0) && (available > total)) ++ const long status = m_pInfo->Parse(); ++ ++ if (status) ++ return status; ++ } else if (id == 0x0654AE6B) { // Tracks ID ++ if (m_pTracks) ++ return E_FILE_FORMAT_INVALID; ++ ++ m_pTracks = new (std::nothrow) ++ Tracks(this, pos, size, element_start, element_size); ++ ++ if (m_pTracks == NULL) + return -1; + +- //I would assume that in practice this loop would execute +- //exactly once, but we allow for other elements (e.g. Void) +- //to immediately follow the EBML header. This is fine for +- //the source filter case (since the entire file is available), +- //but in the splitter case over a network we should probably +- //just give up early. We could for example decide only to +- //execute this loop a maximum of, say, 10 times. +- //TODO: +- //There is an implied ""give up early"" by only parsing up +- //to the available limit. We do do that, but only if the +- //total file size is unknown. We could decide to always +- //use what's available as our limit (irrespective of whether +- //we happen to know the total file length). This would have +- //as its sense ""parse this much of the file before giving up"", +- //which a slightly different sense from ""try to parse up to +- //10 EMBL elements before giving up"". ++ const long status = m_pTracks->Parse(); + +- for (;;) +- { +- if ((total >= 0) && (pos >= total)) +- return E_FILE_FORMAT_INVALID; +- +- //Read ID +- long len; +- long long result = GetUIntLength(pReader, pos, len); +- +- if (result) //error, or too few available bytes +- return result; +- +- if ((total >= 0) && ((pos + len) > total)) +- return E_FILE_FORMAT_INVALID; +- +- if ((pos + len) > available) +- return pos + len; +- +- const long long idpos = pos; +- const long long id = ReadUInt(pReader, pos, len); +- +- if (id < 0) //error +- return id; +- +- pos += len; //consume ID +- +- //Read Size +- +- result = GetUIntLength(pReader, pos, len); +- +- if (result) //error, or too few available bytes +- return result; +- +- if ((total >= 0) && ((pos + len) > total)) +- return E_FILE_FORMAT_INVALID; +- +- if ((pos + len) > available) +- return pos + len; +- +- long long size = ReadUInt(pReader, pos, len); +- +- if (size < 0) //error +- return size; +- +- pos += len; //consume length of size of element +- +- //Pos now points to start of payload +- +- //Handle ""unknown size"" for live streaming of webm files. +- const long long unknown_size = (1LL << (7 * len)) - 1; +- +- if (id == 0x08538067) //Segment ID +- { +- if (size == unknown_size) +- size = -1; +- +- else if (total < 0) +- size = -1; +- +- else if ((pos + size) > total) +- size = -1; +- +- pSegment = new (std::nothrow) Segment( +- pReader, +- idpos, +- //elem_size +- pos, +- size); +- +- if (pSegment == 0) +- return -1; //generic error +- +- return 0; //success +- } +- +- if (size == unknown_size) +- return E_FILE_FORMAT_INVALID; +- +- if ((total >= 0) && ((pos + size) > total)) +- return E_FILE_FORMAT_INVALID; +- +- if ((pos + size) > available) +- return pos + size; +- +- pos += size; //consume payload +- } +-} +- +- +-long long Segment::ParseHeaders() +-{ +- //Outermost (level 0) segment object has been constructed, +- //and pos designates start of payload. We need to find the +- //inner (level 1) elements. +- long long total, available; +- +- const int status = m_pReader->Length(&total, &available); +- +- if (status < 0) //error ++ if (status) + return status; ++ } else if (id == 0x0C53BB6B) { // Cues ID ++ if (m_pCues == NULL) { ++ m_pCues = new (std::nothrow) ++ Cues(this, pos, size, element_start, element_size); + +- assert((total < 0) || (available <= total)); ++ if (m_pCues == NULL) ++ return -1; ++ } ++ } else if (id == 0x014D9B74) { // SeekHead ID ++ if (m_pSeekHead == NULL) { ++ m_pSeekHead = new (std::nothrow) ++ SeekHead(this, pos, size, element_start, element_size); + +- const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; +- assert((segment_stop < 0) || (total < 0) || (segment_stop <= total)); +- assert((segment_stop < 0) || (m_pos <= segment_stop)); ++ if (m_pSeekHead == NULL) ++ return -1; + +- for (;;) +- { +- if ((total >= 0) && (m_pos >= total)) +- break; ++ const long status = m_pSeekHead->Parse(); + +- if ((segment_stop >= 0) && (m_pos >= segment_stop)) +- break; ++ if (status) ++ return status; ++ } ++ } else if (id == 0x0043A770) { // Chapters ID ++ if (m_pChapters == NULL) { ++ m_pChapters = new (std::nothrow) ++ Chapters(this, pos, size, element_start, element_size); + +- long long pos = m_pos; +- const long long element_start = pos; ++ if (m_pChapters == NULL) ++ return -1; + +- if ((pos + 1) > available) +- return (pos + 1); ++ const long status = m_pChapters->Parse(); + +- long len; +- long long result = GetUIntLength(m_pReader, pos, len); +- +- if (result < 0) //error +- return result; +- +- if (result > 0) //underflow (weird) +- return (pos + 1); +- +- if ((segment_stop >= 0) && ((pos + len) > segment_stop)) +- return E_FILE_FORMAT_INVALID; +- +- if ((pos + len) > available) +- return pos + len; +- +- const long long idpos = pos; +- const long long id = ReadUInt(m_pReader, idpos, len); +- +- if (id < 0) //error +- return id; +- +- if (id == 0x0F43B675) //Cluster ID +- break; +- +- pos += len; //consume ID +- +- if ((pos + 1) > available) +- return (pos + 1); +- +- //Read Size +- result = GetUIntLength(m_pReader, pos, len); +- +- if (result < 0) //error +- return result; +- +- if (result > 0) //underflow (weird) +- return (pos + 1); +- +- if ((segment_stop >= 0) && ((pos + len) > segment_stop)) +- return E_FILE_FORMAT_INVALID; +- +- if ((pos + len) > available) +- return pos + len; +- +- const long long size = ReadUInt(m_pReader, pos, len); +- +- if (size < 0) //error +- return size; +- +- pos += len; //consume length of size of element +- +- const long long element_size = size + pos - element_start; +- +- //Pos now points to start of payload +- +- if ((segment_stop >= 0) && ((pos + size) > segment_stop)) +- return E_FILE_FORMAT_INVALID; +- +- //We read EBML elements either in total or nothing at all. +- +- if ((pos + size) > available) +- return pos + size; +- +- if (id == 0x0549A966) //Segment Info ID +- { +- if (m_pInfo) +- return E_FILE_FORMAT_INVALID; +- +- m_pInfo = new (std::nothrow) SegmentInfo( +- this, +- pos, +- size, +- element_start, +- element_size); +- +- if (m_pInfo == NULL) +- return -1; +- +- const long status = m_pInfo->Parse(); +- +- if (status) +- return status; +- } +- else if (id == 0x0654AE6B) //Tracks ID +- { +- if (m_pTracks) +- return E_FILE_FORMAT_INVALID; +- +- m_pTracks = new (std::nothrow) Tracks(this, +- pos, +- size, +- element_start, +- element_size); +- +- if (m_pTracks == NULL) +- return -1; +- +- const long status = m_pTracks->Parse(); +- +- if (status) +- return status; +- } +- else if (id == 0x0C53BB6B) //Cues ID +- { +- if (m_pCues == NULL) +- { +- m_pCues = new (std::nothrow) Cues( +- this, +- pos, +- size, +- element_start, +- element_size); +- +- if (m_pCues == NULL) +- return -1; +- } +- } +- else if (id == 0x014D9B74) //SeekHead ID +- { +- if (m_pSeekHead == NULL) +- { +- m_pSeekHead = new (std::nothrow) SeekHead( +- this, +- pos, +- size, +- element_start, +- element_size); +- +- if (m_pSeekHead == NULL) +- return -1; +- +- const long status = m_pSeekHead->Parse(); +- +- if (status) +- return status; +- } +- } +- else if (id == 0x0043A770) //Chapters ID +- { +- if (m_pChapters == NULL) +- { +- m_pChapters = new (std::nothrow) Chapters( +- this, +- pos, +- size, +- element_start, +- element_size); +- +- if (m_pChapters == NULL) +- return -1; +- +- const long status = m_pChapters->Parse(); +- +- if (status) +- return status; +- } +- } +- +- m_pos = pos + size; //consume payload ++ if (status) ++ return status; ++ } + } + +- assert((segment_stop < 0) || (m_pos <= segment_stop)); ++ m_pos = pos + size; // consume payload ++ } + +- if (m_pInfo == NULL) //TODO: liberalize this behavior +- return E_FILE_FORMAT_INVALID; ++ assert((segment_stop < 0) || (m_pos <= segment_stop)); + +- if (m_pTracks == NULL) +- return E_FILE_FORMAT_INVALID; ++ if (m_pInfo == NULL) // TODO: liberalize this behavior ++ return E_FILE_FORMAT_INVALID; + +- return 0; //success ++ if (m_pTracks == NULL) ++ return E_FILE_FORMAT_INVALID; ++ ++ return 0; // success + } + ++long Segment::LoadCluster(long long& pos, long& len) { ++ for (;;) { ++ const long result = DoLoadCluster(pos, len); + +-long Segment::LoadCluster( +- long long& pos, +- long& len) +-{ +- for (;;) +- { +- const long result = DoLoadCluster(pos, len); ++ if (result <= 1) ++ return result; ++ } ++} + +- if (result <= 1) +- return result; ++long Segment::DoLoadCluster(long long& pos, long& len) { ++ if (m_pos < 0) ++ return DoLoadClusterUnknownSize(pos, len); ++ ++ long long total, avail; ++ ++ long status = m_pReader->Length(&total, &avail); ++ ++ if (status < 0) // error ++ return status; ++ ++ assert((total < 0) || (avail <= total)); ++ ++ const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; ++ ++ long long cluster_off = -1; // offset relative to start of segment ++ long long cluster_size = -1; // size of cluster payload ++ ++ for (;;) { ++ if ((total >= 0) && (m_pos >= total)) ++ return 1; // no more clusters ++ ++ if ((segment_stop >= 0) && (m_pos >= segment_stop)) ++ return 1; // no more clusters ++ ++ pos = m_pos; ++ ++ // Read ID ++ ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; + } +-} + ++ long long result = GetUIntLength(m_pReader, pos, len); + +-long Segment::DoLoadCluster( +- long long& pos, +- long& len) +-{ +- if (m_pos < 0) +- return DoLoadClusterUnknownSize(pos, len); ++ if (result < 0) // error ++ return static_cast(result); + +- long long total, avail; ++ if (result > 0) // weird ++ return E_BUFFER_NOT_FULL; + +- long status = m_pReader->Length(&total, &avail); ++ if ((segment_stop >= 0) && ((pos + len) > segment_stop)) ++ return E_FILE_FORMAT_INVALID; + +- if (status < 0) //error +- return status; ++ if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; + +- assert((total < 0) || (avail <= total)); ++ const long long idpos = pos; ++ const long long id = ReadUInt(m_pReader, idpos, len); + +- const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; ++ if (id < 0) // error (or underflow) ++ return static_cast(id); + +- long long cluster_off = -1; //offset relative to start of segment +- long long cluster_size = -1; //size of cluster payload ++ pos += len; // consume ID + +- for (;;) +- { +- if ((total >= 0) && (m_pos >= total)) +- return 1; //no more clusters ++ // Read Size + +- if ((segment_stop >= 0) && (m_pos >= segment_stop)) +- return 1; //no more clusters ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; ++ } + +- pos = m_pos; ++ result = GetUIntLength(m_pReader, pos, len); + +- //Read ID ++ if (result < 0) // error ++ return static_cast(result); + +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } ++ if (result > 0) // weird ++ return E_BUFFER_NOT_FULL; + +- long long result = GetUIntLength(m_pReader, pos, len); ++ if ((segment_stop >= 0) && ((pos + len) > segment_stop)) ++ return E_FILE_FORMAT_INVALID; + +- if (result < 0) //error +- return static_cast(result); ++ if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; + +- if (result > 0) //weird +- return E_BUFFER_NOT_FULL; ++ const long long size = ReadUInt(m_pReader, pos, len); + +- if ((segment_stop >= 0) && ((pos + len) > segment_stop)) +- return E_FILE_FORMAT_INVALID; ++ if (size < 0) // error ++ return static_cast(size); + +- if ((pos + len) > avail) +- return E_BUFFER_NOT_FULL; ++ pos += len; // consume length of size of element + +- const long long idpos = pos; +- const long long id = ReadUInt(m_pReader, idpos, len); ++ // pos now points to start of payload + +- if (id < 0) //error (or underflow) +- return static_cast(id); ++ if (size == 0) { // weird ++ m_pos = pos; ++ continue; ++ } + +- pos += len; //consume ID ++ const long long unknown_size = (1LL << (7 * len)) - 1; + +- //Read Size +- +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } +- +- result = GetUIntLength(m_pReader, pos, len); +- +- if (result < 0) //error +- return static_cast(result); +- +- if (result > 0) //weird +- return E_BUFFER_NOT_FULL; +- +- if ((segment_stop >= 0) && ((pos + len) > segment_stop)) +- return E_FILE_FORMAT_INVALID; +- +- if ((pos + len) > avail) +- return E_BUFFER_NOT_FULL; +- +- const long long size = ReadUInt(m_pReader, pos, len); +- +- if (size < 0) //error +- return static_cast(size); +- +- pos += len; //consume length of size of element +- +- //pos now points to start of payload +- +- if (size == 0) //weird +- { +- m_pos = pos; +- continue; +- } +- +- const long long unknown_size = (1LL << (7 * len)) - 1; +- +-#if 0 //we must handle this to support live webm ++#if 0 // we must handle this to support live webm + if (size == unknown_size) + return E_FILE_FORMAT_INVALID; //TODO: allow this + #endif + +- if ((segment_stop >= 0) && +- (size != unknown_size) && +- ((pos + size) > segment_stop)) +- { +- return E_FILE_FORMAT_INVALID; +- } ++ if ((segment_stop >= 0) && (size != unknown_size) && ++ ((pos + size) > segment_stop)) { ++ return E_FILE_FORMAT_INVALID; ++ } + +-#if 0 //commented-out, to support incremental cluster parsing ++#if 0 // commented-out, to support incremental cluster parsing + len = static_cast(size); + + if ((pos + size) > avail) + return E_BUFFER_NOT_FULL; + #endif + +- if (id == 0x0C53BB6B) //Cues ID +- { +- if (size == unknown_size) +- return E_FILE_FORMAT_INVALID; //TODO: liberalize ++ if (id == 0x0C53BB6B) { // Cues ID ++ if (size == unknown_size) ++ return E_FILE_FORMAT_INVALID; // TODO: liberalize + +- if (m_pCues == NULL) +- { +- const long long element_size = (pos - idpos) + size; ++ if (m_pCues == NULL) { ++ const long long element_size = (pos - idpos) + size; + +- m_pCues = new Cues(this, +- pos, +- size, +- idpos, +- element_size); +- assert(m_pCues); //TODO +- } ++ m_pCues = new Cues(this, pos, size, idpos, element_size); ++ assert(m_pCues); // TODO ++ } + +- m_pos = pos + size; //consume payload +- continue; +- } +- +- if (id != 0x0F43B675) //Cluster ID +- { +- if (size == unknown_size) +- return E_FILE_FORMAT_INVALID; //TODO: liberalize +- +- m_pos = pos + size; //consume payload +- continue; +- } +- +- //We have a cluster. +- +- cluster_off = idpos - m_start; //relative pos +- +- if (size != unknown_size) +- cluster_size = size; +- +- break; ++ m_pos = pos + size; // consume payload ++ continue; + } + +- assert(cluster_off >= 0); //have cluster ++ if (id != 0x0F43B675) { // Cluster ID ++ if (size == unknown_size) ++ return E_FILE_FORMAT_INVALID; // TODO: liberalize + +- long long pos_; +- long len_; +- +- status = Cluster::HasBlockEntries(this, cluster_off, pos_, len_); +- +- if (status < 0) //error, or underflow +- { +- pos = pos_; +- len = len_; +- +- return status; ++ m_pos = pos + size; // consume payload ++ continue; + } + +- //status == 0 means ""no block entries found"" +- //status > 0 means ""found at least one block entry"" ++ // We have a cluster. + +- //TODO: +- //The issue here is that the segment increments its own +- //pos ptr past the most recent cluster parsed, and then +- //starts from there to parse the next cluster. If we +- //don't know the size of the current cluster, then we +- //must either parse its payload (as we do below), looking +- //for the cluster (or cues) ID to terminate the parse. +- //This isn't really what we want: rather, we really need +- //a way to create the curr cluster object immediately. +- //The pity is that cluster::parse can determine its own +- //boundary, and we largely duplicate that same logic here. +- // +- //Maybe we need to get rid of our look-ahead preloading +- //in source::parse??? +- // +- //As we're parsing the blocks in the curr cluster +- //(in cluster::parse), we should have some way to signal +- //to the segment that we have determined the boundary, +- //so it can adjust its own segment::m_pos member. +- // +- //The problem is that we're asserting in asyncreadinit, +- //because we adjust the pos down to the curr seek pos, +- //and the resulting adjusted len is > 2GB. I'm suspicious +- //that this is even correct, but even if it is, we can't +- //be loading that much data in the cache anyway. ++ cluster_off = idpos - m_start; // relative pos + +- const long idx = m_clusterCount; ++ if (size != unknown_size) ++ cluster_size = size; + +- if (m_clusterPreloadCount > 0) +- { +- assert(idx < m_clusterSize); ++ break; ++ } + +- Cluster* const pCluster = m_clusters[idx]; +- assert(pCluster); +- assert(pCluster->m_index < 0); ++ assert(cluster_off >= 0); // have cluster + +- const long long off = pCluster->GetPosition(); +- assert(off >= 0); ++ long long pos_; ++ long len_; + +- if (off == cluster_off) //preloaded already +- { +- if (status == 0) //no entries found +- return E_FILE_FORMAT_INVALID; ++ status = Cluster::HasBlockEntries(this, cluster_off, pos_, len_); + +- if (cluster_size >= 0) +- pos += cluster_size; +- else +- { +- const long long element_size = pCluster->GetElementSize(); ++ if (status < 0) { // error, or underflow ++ pos = pos_; ++ len = len_; + +- if (element_size <= 0) +- return E_FILE_FORMAT_INVALID; //TODO: handle this case ++ return status; ++ } + +- pos = pCluster->m_element_start + element_size; +- } ++ // status == 0 means ""no block entries found"" ++ // status > 0 means ""found at least one block entry"" + +- pCluster->m_index = idx; //move from preloaded to loaded +- ++m_clusterCount; +- --m_clusterPreloadCount; ++ // TODO: ++ // The issue here is that the segment increments its own ++ // pos ptr past the most recent cluster parsed, and then ++ // starts from there to parse the next cluster. If we ++ // don't know the size of the current cluster, then we ++ // must either parse its payload (as we do below), looking ++ // for the cluster (or cues) ID to terminate the parse. ++ // This isn't really what we want: rather, we really need ++ // a way to create the curr cluster object immediately. ++ // The pity is that cluster::parse can determine its own ++ // boundary, and we largely duplicate that same logic here. ++ // ++ // Maybe we need to get rid of our look-ahead preloading ++ // in source::parse??? ++ // ++ // As we're parsing the blocks in the curr cluster ++ //(in cluster::parse), we should have some way to signal ++ // to the segment that we have determined the boundary, ++ // so it can adjust its own segment::m_pos member. ++ // ++ // The problem is that we're asserting in asyncreadinit, ++ // because we adjust the pos down to the curr seek pos, ++ // and the resulting adjusted len is > 2GB. I'm suspicious ++ // that this is even correct, but even if it is, we can't ++ // be loading that much data in the cache anyway. + +- m_pos = pos; //consume payload +- assert((segment_stop < 0) || (m_pos <= segment_stop)); ++ const long idx = m_clusterCount; + +- return 0; //success +- } +- } +- +- if (status == 0) //no entries found +- { +- if (cluster_size < 0) +- return E_FILE_FORMAT_INVALID; //TODO: handle this +- +- pos += cluster_size; +- +- if ((total >= 0) && (pos >= total)) +- { +- m_pos = total; +- return 1; //no more clusters +- } +- +- if ((segment_stop >= 0) && (pos >= segment_stop)) +- { +- m_pos = segment_stop; +- return 1; //no more clusters +- } +- +- m_pos = pos; +- return 2; //try again +- } +- +- //status > 0 means we have an entry +- +- Cluster* const pCluster = Cluster::Create(this, +- idx, +- cluster_off); +- //element_size); +- assert(pCluster); +- +- AppendCluster(pCluster); +- assert(m_clusters); ++ if (m_clusterPreloadCount > 0) { + assert(idx < m_clusterSize); +- assert(m_clusters[idx] == pCluster); + +- if (cluster_size >= 0) +- { ++ Cluster* const pCluster = m_clusters[idx]; ++ assert(pCluster); ++ assert(pCluster->m_index < 0); ++ ++ const long long off = pCluster->GetPosition(); ++ assert(off >= 0); ++ ++ if (off == cluster_off) { // preloaded already ++ if (status == 0) // no entries found ++ return E_FILE_FORMAT_INVALID; ++ ++ if (cluster_size >= 0) + pos += cluster_size; ++ else { ++ const long long element_size = pCluster->GetElementSize(); + +- m_pos = pos; +- assert((segment_stop < 0) || (m_pos <= segment_stop)); ++ if (element_size <= 0) ++ return E_FILE_FORMAT_INVALID; // TODO: handle this case + +- return 0; ++ pos = pCluster->m_element_start + element_size; ++ } ++ ++ pCluster->m_index = idx; // move from preloaded to loaded ++ ++m_clusterCount; ++ --m_clusterPreloadCount; ++ ++ m_pos = pos; // consume payload ++ assert((segment_stop < 0) || (m_pos <= segment_stop)); ++ ++ return 0; // success ++ } ++ } ++ ++ if (status == 0) { // no entries found ++ if (cluster_size < 0) ++ return E_FILE_FORMAT_INVALID; // TODO: handle this ++ ++ pos += cluster_size; ++ ++ if ((total >= 0) && (pos >= total)) { ++ m_pos = total; ++ return 1; // no more clusters + } + +- m_pUnknownSize = pCluster; +- m_pos = -pos; ++ if ((segment_stop >= 0) && (pos >= segment_stop)) { ++ m_pos = segment_stop; ++ return 1; // no more clusters ++ } + +- return 0; //partial success, since we have a new cluster ++ m_pos = pos; ++ return 2; // try again ++ } + +- //status == 0 means ""no block entries found"" ++ // status > 0 means we have an entry + +- //pos designates start of payload +- //m_pos has NOT been adjusted yet (in case we need to come back here) ++ Cluster* const pCluster = Cluster::Create(this, idx, cluster_off); ++ // element_size); ++ assert(pCluster); ++ ++ AppendCluster(pCluster); ++ assert(m_clusters); ++ assert(idx < m_clusterSize); ++ assert(m_clusters[idx] == pCluster); ++ ++ if (cluster_size >= 0) { ++ pos += cluster_size; ++ ++ m_pos = pos; ++ assert((segment_stop < 0) || (m_pos <= segment_stop)); ++ ++ return 0; ++ } ++ ++ m_pUnknownSize = pCluster; ++ m_pos = -pos; ++ ++ return 0; // partial success, since we have a new cluster ++ ++// status == 0 means ""no block entries found"" ++ ++// pos designates start of payload ++// m_pos has NOT been adjusted yet (in case we need to come back here) + + #if 0 + +- if (cluster_size < 0) //unknown size +- { ++ if (cluster_size < 0) { //unknown size + const long long payload_pos = pos; //absolute pos of cluster payload + +- for (;;) //determine cluster size +- { ++ for (;;) { //determine cluster size + if ((total >= 0) && (pos >= total)) + break; + +@@ -1518,16 +1346,11 @@ + + return 2; //try to find another cluster + + #endif +- + } + +- +-long Segment::DoLoadClusterUnknownSize( +- long long& pos, +- long& len) +-{ +- assert(m_pos < 0); +- assert(m_pUnknownSize); ++long Segment::DoLoadClusterUnknownSize(long long& pos, long& len) { ++ assert(m_pos < 0); ++ assert(m_pUnknownSize); + + #if 0 + assert(m_pUnknownSize->GetElementSize() < 0); //TODO: verify this +@@ -1554,8 +1377,7 @@ + + + long long element_size = -1; + +- for (;;) //determine cluster size +- { ++ for (;;) { //determine cluster size + if ((total >= 0) && (pos >= total)) + { + element_size = total - element_start; +@@ -1604,8 +1426,7 @@ + + //that we have exhausted the sub-element's inside the cluster + //whose ID we parsed earlier. + +- if ((id == 0x0F43B675) || (id == 0x0C53BB6B)) //Cluster ID or Cues ID +- { ++ if ((id == 0x0F43B675) || (id == 0x0C53BB6B)) { //Cluster ID or Cues ID + element_size = pos - element_start; + assert(element_size > 0); + +@@ -1682,348 +1503,299 @@ + + + return 2; //continue parsing + #else +- const long status = m_pUnknownSize->Parse(pos, len); ++ const long status = m_pUnknownSize->Parse(pos, len); + +- if (status < 0) //error or underflow +- return status; ++ if (status < 0) // error or underflow ++ return status; + +- if (status == 0) //parsed a block +- return 2; //continue parsing ++ if (status == 0) // parsed a block ++ return 2; // continue parsing + +- assert(status > 0); //nothing left to parse of this cluster ++ assert(status > 0); // nothing left to parse of this cluster + +- const long long start = m_pUnknownSize->m_element_start; ++ const long long start = m_pUnknownSize->m_element_start; + +- const long long size = m_pUnknownSize->GetElementSize(); +- assert(size >= 0); ++ const long long size = m_pUnknownSize->GetElementSize(); ++ assert(size >= 0); + +- pos = start + size; +- m_pos = pos; ++ pos = start + size; ++ m_pos = pos; + +- m_pUnknownSize = 0; ++ m_pUnknownSize = 0; + +- return 2; //continue parsing ++ return 2; // continue parsing + #endif + } + ++void Segment::AppendCluster(Cluster* pCluster) { ++ assert(pCluster); ++ assert(pCluster->m_index >= 0); + +-void Segment::AppendCluster(Cluster* pCluster) +-{ +- assert(pCluster); +- assert(pCluster->m_index >= 0); ++ const long count = m_clusterCount + m_clusterPreloadCount; + +- const long count = m_clusterCount + m_clusterPreloadCount; ++ long& size = m_clusterSize; ++ assert(size >= count); + +- long& size = m_clusterSize; +- assert(size >= count); ++ const long idx = pCluster->m_index; ++ assert(idx == m_clusterCount); + +- const long idx = pCluster->m_index; +- assert(idx == m_clusterCount); ++ if (count >= size) { ++ const long n = (size <= 0) ? 2048 : 2 * size; + +- if (count >= size) +- { +- const long n = (size <= 0) ? 2048 : 2*size; ++ Cluster** const qq = new Cluster* [n]; ++ Cluster** q = qq; + +- Cluster** const qq = new Cluster*[n]; +- Cluster** q = qq; ++ Cluster** p = m_clusters; ++ Cluster** const pp = p + count; + +- Cluster** p = m_clusters; +- Cluster** const pp = p + count; ++ while (p != pp) ++ *q++ = *p++; + +- while (p != pp) +- *q++ = *p++; ++ delete[] m_clusters; + +- delete[] m_clusters; ++ m_clusters = qq; ++ size = n; ++ } + +- m_clusters = qq; +- size = n; +- } +- +- if (m_clusterPreloadCount > 0) +- { +- assert(m_clusters); +- +- Cluster** const p = m_clusters + m_clusterCount; +- assert(*p); +- assert((*p)->m_index < 0); +- +- Cluster** q = p + m_clusterPreloadCount; +- assert(q < (m_clusters + size)); +- +- for (;;) +- { +- Cluster** const qq = q - 1; +- assert((*qq)->m_index < 0); +- +- *q = *qq; +- q = qq; +- +- if (q == p) +- break; +- } +- } +- +- m_clusters[idx] = pCluster; +- ++m_clusterCount; +-} +- +- +-void Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx) +-{ +- assert(pCluster); +- assert(pCluster->m_index < 0); +- assert(idx >= m_clusterCount); +- +- const long count = m_clusterCount + m_clusterPreloadCount; +- +- long& size = m_clusterSize; +- assert(size >= count); +- +- if (count >= size) +- { +- const long n = (size <= 0) ? 2048 : 2*size; +- +- Cluster** const qq = new Cluster*[n]; +- Cluster** q = qq; +- +- Cluster** p = m_clusters; +- Cluster** const pp = p + count; +- +- while (p != pp) +- *q++ = *p++; +- +- delete[] m_clusters; +- +- m_clusters = qq; +- size = n; +- } +- ++ if (m_clusterPreloadCount > 0) { + assert(m_clusters); + +- Cluster** const p = m_clusters + idx; ++ Cluster** const p = m_clusters + m_clusterCount; ++ assert(*p); ++ assert((*p)->m_index < 0); + +- Cluster** q = m_clusters + count; +- assert(q >= p); ++ Cluster** q = p + m_clusterPreloadCount; + assert(q < (m_clusters + size)); + +- while (q > p) +- { +- Cluster** const qq = q - 1; +- assert((*qq)->m_index < 0); ++ for (;;) { ++ Cluster** const qq = q - 1; ++ assert((*qq)->m_index < 0); + +- *q = *qq; +- q = qq; ++ *q = *qq; ++ q = qq; ++ ++ if (q == p) ++ break; + } ++ } + +- m_clusters[idx] = pCluster; +- ++m_clusterPreloadCount; ++ m_clusters[idx] = pCluster; ++ ++m_clusterCount; + } + ++void Segment::PreloadCluster(Cluster* pCluster, ptrdiff_t idx) { ++ assert(pCluster); ++ assert(pCluster->m_index < 0); ++ assert(idx >= m_clusterCount); + +-long Segment::Load() +-{ +- assert(m_clusters == NULL); +- assert(m_clusterSize == 0); +- assert(m_clusterCount == 0); +- //assert(m_size >= 0); ++ const long count = m_clusterCount + m_clusterPreloadCount; + +- //Outermost (level 0) segment object has been constructed, +- //and pos designates start of payload. We need to find the +- //inner (level 1) elements. ++ long& size = m_clusterSize; ++ assert(size >= count); + +- const long long header_status = ParseHeaders(); ++ if (count >= size) { ++ const long n = (size <= 0) ? 2048 : 2 * size; + +- if (header_status < 0) //error +- return static_cast(header_status); ++ Cluster** const qq = new Cluster* [n]; ++ Cluster** q = qq; + +- if (header_status > 0) //underflow +- return E_BUFFER_NOT_FULL; ++ Cluster** p = m_clusters; ++ Cluster** const pp = p + count; + +- assert(m_pInfo); +- assert(m_pTracks); ++ while (p != pp) ++ *q++ = *p++; + +- for (;;) +- { +- const int status = LoadCluster(); ++ delete[] m_clusters; + +- if (status < 0) //error +- return status; ++ m_clusters = qq; ++ size = n; ++ } + +- if (status >= 1) //no more clusters +- return 0; +- } ++ assert(m_clusters); ++ ++ Cluster** const p = m_clusters + idx; ++ ++ Cluster** q = m_clusters + count; ++ assert(q >= p); ++ assert(q < (m_clusters + size)); ++ ++ while (q > p) { ++ Cluster** const qq = q - 1; ++ assert((*qq)->m_index < 0); ++ ++ *q = *qq; ++ q = qq; ++ } ++ ++ m_clusters[idx] = pCluster; ++ ++m_clusterPreloadCount; + } + ++long Segment::Load() { ++ assert(m_clusters == NULL); ++ assert(m_clusterSize == 0); ++ assert(m_clusterCount == 0); ++ // assert(m_size >= 0); + +-SeekHead::SeekHead( +- Segment* pSegment, +- long long start, +- long long size_, +- long long element_start, +- long long element_size) : +- m_pSegment(pSegment), +- m_start(start), +- m_size(size_), +- m_element_start(element_start), +- m_element_size(element_size), +- m_entries(0), +- m_entry_count(0), +- m_void_elements(0), +- m_void_element_count(0) +-{ ++ // Outermost (level 0) segment object has been constructed, ++ // and pos designates start of payload. We need to find the ++ // inner (level 1) elements. ++ ++ const long long header_status = ParseHeaders(); ++ ++ if (header_status < 0) // error ++ return static_cast(header_status); ++ ++ if (header_status > 0) // underflow ++ return E_BUFFER_NOT_FULL; ++ ++ assert(m_pInfo); ++ assert(m_pTracks); ++ ++ for (;;) { ++ const int status = LoadCluster(); ++ ++ if (status < 0) // error ++ return status; ++ ++ if (status >= 1) // no more clusters ++ return 0; ++ } + } + ++SeekHead::SeekHead(Segment* pSegment, long long start, long long size_, ++ long long element_start, long long element_size) ++ : m_pSegment(pSegment), ++ m_start(start), ++ m_size(size_), ++ m_element_start(element_start), ++ m_element_size(element_size), ++ m_entries(0), ++ m_entry_count(0), ++ m_void_elements(0), ++ m_void_element_count(0) {} + +-SeekHead::~SeekHead() +-{ +- delete[] m_entries; +- delete[] m_void_elements; ++SeekHead::~SeekHead() { ++ delete[] m_entries; ++ delete[] m_void_elements; + } + ++long SeekHead::Parse() { ++ IMkvReader* const pReader = m_pSegment->m_pReader; + +-long SeekHead::Parse() +-{ +- IMkvReader* const pReader = m_pSegment->m_pReader; ++ long long pos = m_start; ++ const long long stop = m_start + m_size; + +- long long pos = m_start; +- const long long stop = m_start + m_size; ++ // first count the seek head entries + +- //first count the seek head entries ++ int entry_count = 0; ++ int void_element_count = 0; + +- int entry_count = 0; +- int void_element_count = 0; ++ while (pos < stop) { ++ long long id, size; + +- while (pos < stop) +- { +- long long id, size; ++ const long status = ParseElementHeader(pReader, pos, stop, id, size); + +- const long status = ParseElementHeader( +- pReader, +- pos, +- stop, +- id, +- size); ++ if (status < 0) // error ++ return status; + +- if (status < 0) //error +- return status; ++ if (id == 0x0DBB) // SeekEntry ID ++ ++entry_count; ++ else if (id == 0x6C) // Void ID ++ ++void_element_count; + +- if (id == 0x0DBB) //SeekEntry ID +- ++entry_count; +- else if (id == 0x6C) //Void ID +- ++void_element_count; ++ pos += size; // consume payload ++ assert(pos <= stop); ++ } + +- pos += size; //consume payload +- assert(pos <= stop); ++ assert(pos == stop); ++ ++ m_entries = new (std::nothrow) Entry[entry_count]; ++ ++ if (m_entries == NULL) ++ return -1; ++ ++ m_void_elements = new (std::nothrow) VoidElement[void_element_count]; ++ ++ if (m_void_elements == NULL) ++ return -1; ++ ++ // now parse the entries and void elements ++ ++ Entry* pEntry = m_entries; ++ VoidElement* pVoidElement = m_void_elements; ++ ++ pos = m_start; ++ ++ while (pos < stop) { ++ const long long idpos = pos; ++ ++ long long id, size; ++ ++ const long status = ParseElementHeader(pReader, pos, stop, id, size); ++ ++ if (status < 0) // error ++ return status; ++ ++ if (id == 0x0DBB) { // SeekEntry ID ++ if (ParseEntry(pReader, pos, size, pEntry)) { ++ Entry& e = *pEntry++; ++ ++ e.element_start = idpos; ++ e.element_size = (pos + size) - idpos; ++ } ++ } else if (id == 0x6C) { // Void ID ++ VoidElement& e = *pVoidElement++; ++ ++ e.element_start = idpos; ++ e.element_size = (pos + size) - idpos; + } + +- assert(pos == stop); ++ pos += size; // consume payload ++ assert(pos <= stop); ++ } + +- m_entries = new (std::nothrow) Entry[entry_count]; ++ assert(pos == stop); + +- if (m_entries == NULL) +- return -1; ++ ptrdiff_t count_ = ptrdiff_t(pEntry - m_entries); ++ assert(count_ >= 0); ++ assert(count_ <= entry_count); + +- m_void_elements = new (std::nothrow) VoidElement[void_element_count]; ++ m_entry_count = static_cast(count_); + +- if (m_void_elements == NULL) +- return -1; ++ count_ = ptrdiff_t(pVoidElement - m_void_elements); ++ assert(count_ >= 0); ++ assert(count_ <= void_element_count); + +- //now parse the entries and void elements ++ m_void_element_count = static_cast(count_); + +- Entry* pEntry = m_entries; +- VoidElement* pVoidElement = m_void_elements; ++ return 0; ++} + +- pos = m_start; ++int SeekHead::GetCount() const { return m_entry_count; } + +- while (pos < stop) +- { +- const long long idpos = pos; +- +- long long id, size; +- +- const long status = ParseElementHeader( +- pReader, +- pos, +- stop, +- id, +- size); +- +- if (status < 0) //error +- return status; +- +- if (id == 0x0DBB) //SeekEntry ID +- { +- if (ParseEntry(pReader, pos, size, pEntry)) +- { +- Entry& e = *pEntry++; +- +- e.element_start = idpos; +- e.element_size = (pos + size) - idpos; +- } +- } +- else if (id == 0x6C) //Void ID +- { +- VoidElement& e = *pVoidElement++; +- +- e.element_start = idpos; +- e.element_size = (pos + size) - idpos; +- } +- +- pos += size; //consume payload +- assert(pos <= stop); +- } +- +- assert(pos == stop); +- +- ptrdiff_t count_ = ptrdiff_t(pEntry - m_entries); +- assert(count_ >= 0); +- assert(count_ <= entry_count); +- +- m_entry_count = static_cast(count_); +- +- count_ = ptrdiff_t(pVoidElement - m_void_elements); +- assert(count_ >= 0); +- assert(count_ <= void_element_count); +- +- m_void_element_count = static_cast(count_); +- ++const SeekHead::Entry* SeekHead::GetEntry(int idx) const { ++ if (idx < 0) + return 0; ++ ++ if (idx >= m_entry_count) ++ return 0; ++ ++ return m_entries + idx; + } + ++int SeekHead::GetVoidElementCount() const { return m_void_element_count; } + +-int SeekHead::GetCount() const +-{ +- return m_entry_count; ++const SeekHead::VoidElement* SeekHead::GetVoidElement(int idx) const { ++ if (idx < 0) ++ return 0; ++ ++ if (idx >= m_void_element_count) ++ return 0; ++ ++ return m_void_elements + idx; + } + +-const SeekHead::Entry* SeekHead::GetEntry(int idx) const +-{ +- if (idx < 0) +- return 0; +- +- if (idx >= m_entry_count) +- return 0; +- +- return m_entries + idx; +-} +- +-int SeekHead::GetVoidElementCount() const +-{ +- return m_void_element_count; +-} +- +-const SeekHead::VoidElement* SeekHead::GetVoidElement(int idx) const +-{ +- if (idx < 0) +- return 0; +- +- if (idx >= m_void_element_count) +- return 0; +- +- return m_void_elements + idx; +-} +- +- + #if 0 + void Segment::ParseCues(long long off) + { +@@ -2073,133 +1845,122 @@ + + //os << ""Segment::ParseCues (end)"" << endl; + } + #else +-long Segment::ParseCues( +- long long off, +- long long& pos, +- long& len) +-{ +- if (m_pCues) +- return 0; //success ++long Segment::ParseCues(long long off, long long& pos, long& len) { ++ if (m_pCues) ++ return 0; // success + +- if (off < 0) +- return -1; ++ if (off < 0) ++ return -1; + +- long long total, avail; ++ long long total, avail; + +- const int status = m_pReader->Length(&total, &avail); ++ const int status = m_pReader->Length(&total, &avail); + +- if (status < 0) //error +- return status; ++ if (status < 0) // error ++ return status; + +- assert((total < 0) || (avail <= total)); ++ assert((total < 0) || (avail <= total)); + +- pos = m_start + off; ++ pos = m_start + off; + +- if ((total < 0) || (pos >= total)) +- return 1; //don't bother parsing cues ++ if ((total < 0) || (pos >= total)) ++ return 1; // don't bother parsing cues + +- const long long element_start = pos; +- const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; ++ const long long element_start = pos; ++ const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; + +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; ++ } + +- long long result = GetUIntLength(m_pReader, pos, len); ++ long long result = GetUIntLength(m_pReader, pos, len); + +- if (result < 0) //error +- return static_cast(result); ++ if (result < 0) // error ++ return static_cast(result); + +- if (result > 0) //underflow (weird) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } ++ if (result > 0) // underflow (weird) ++ { ++ len = 1; ++ return E_BUFFER_NOT_FULL; ++ } + +- if ((segment_stop >= 0) && ((pos + len) > segment_stop)) +- return E_FILE_FORMAT_INVALID; ++ if ((segment_stop >= 0) && ((pos + len) > segment_stop)) ++ return E_FILE_FORMAT_INVALID; + +- if ((pos + len) > avail) +- return E_BUFFER_NOT_FULL; ++ if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; + +- const long long idpos = pos; ++ const long long idpos = pos; + +- const long long id = ReadUInt(m_pReader, idpos, len); ++ const long long id = ReadUInt(m_pReader, idpos, len); + +- if (id != 0x0C53BB6B) //Cues ID +- return E_FILE_FORMAT_INVALID; ++ if (id != 0x0C53BB6B) // Cues ID ++ return E_FILE_FORMAT_INVALID; + +- pos += len; //consume ID +- assert((segment_stop < 0) || (pos <= segment_stop)); ++ pos += len; // consume ID ++ assert((segment_stop < 0) || (pos <= segment_stop)); + +- //Read Size ++ // Read Size + +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; ++ } + +- result = GetUIntLength(m_pReader, pos, len); ++ result = GetUIntLength(m_pReader, pos, len); + +- if (result < 0) //error +- return static_cast(result); ++ if (result < 0) // error ++ return static_cast(result); + +- if (result > 0) //underflow (weird) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } ++ if (result > 0) // underflow (weird) ++ { ++ len = 1; ++ return E_BUFFER_NOT_FULL; ++ } + +- if ((segment_stop >= 0) && ((pos + len) > segment_stop)) +- return E_FILE_FORMAT_INVALID; ++ if ((segment_stop >= 0) && ((pos + len) > segment_stop)) ++ return E_FILE_FORMAT_INVALID; + +- if ((pos + len) > avail) +- return E_BUFFER_NOT_FULL; ++ if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; + +- const long long size = ReadUInt(m_pReader, pos, len); ++ const long long size = ReadUInt(m_pReader, pos, len); + +- if (size < 0) //error +- return static_cast(size); ++ if (size < 0) // error ++ return static_cast(size); + +- if (size == 0) //weird, although technically not illegal +- return 1; //done ++ if (size == 0) // weird, although technically not illegal ++ return 1; // done + +- pos += len; //consume length of size of element +- assert((segment_stop < 0) || (pos <= segment_stop)); ++ pos += len; // consume length of size of element ++ assert((segment_stop < 0) || (pos <= segment_stop)); + +- //Pos now points to start of payload ++ // Pos now points to start of payload + +- const long long element_stop = pos + size; ++ const long long element_stop = pos + size; + +- if ((segment_stop >= 0) && (element_stop > segment_stop)) +- return E_FILE_FORMAT_INVALID; ++ if ((segment_stop >= 0) && (element_stop > segment_stop)) ++ return E_FILE_FORMAT_INVALID; + +- if ((total >= 0) && (element_stop > total)) +- return 1; //don't bother parsing anymore ++ if ((total >= 0) && (element_stop > total)) ++ return 1; // don't bother parsing anymore + +- len = static_cast(size); ++ len = static_cast(size); + +- if (element_stop > avail) +- return E_BUFFER_NOT_FULL; ++ if (element_stop > avail) ++ return E_BUFFER_NOT_FULL; + +- const long long element_size = element_stop - element_start; ++ const long long element_size = element_stop - element_start; + +- m_pCues = new (std::nothrow) Cues( +- this, +- pos, +- size, +- element_start, +- element_size); +- assert(m_pCues); //TODO ++ m_pCues = ++ new (std::nothrow) Cues(this, pos, size, element_start, element_size); ++ assert(m_pCues); // TODO + +- return 0; //success ++ return 0; // success + } + #endif + +- + #if 0 + void Segment::ParseSeekEntry( + long long start, +@@ -2259,304 +2020,269 @@ + + ParseCues(seekOff); + } + #else +-bool SeekHead::ParseEntry( +- IMkvReader* pReader, +- long long start, +- long long size_, +- Entry* pEntry) +-{ +- if (size_ <= 0) +- return false; ++bool SeekHead::ParseEntry(IMkvReader* pReader, long long start, long long size_, ++ Entry* pEntry) { ++ if (size_ <= 0) ++ return false; + +- long long pos = start; +- const long long stop = start + size_; ++ long long pos = start; ++ const long long stop = start + size_; + +- long len; ++ long len; + +- //parse the container for the level-1 element ID ++ // parse the container for the level-1 element ID + +- const long long seekIdId = ReadUInt(pReader, pos, len); +- //seekIdId; ++ const long long seekIdId = ReadUInt(pReader, pos, len); ++ // seekIdId; + +- if (seekIdId != 0x13AB) //SeekID ID +- return false; ++ if (seekIdId != 0x13AB) // SeekID ID ++ return false; + +- if ((pos + len) > stop) +- return false; ++ if ((pos + len) > stop) ++ return false; + +- pos += len; //consume SeekID id ++ pos += len; // consume SeekID id + +- const long long seekIdSize = ReadUInt(pReader, pos, len); ++ const long long seekIdSize = ReadUInt(pReader, pos, len); + +- if (seekIdSize <= 0) +- return false; ++ if (seekIdSize <= 0) ++ return false; + +- if ((pos + len) > stop) +- return false; ++ if ((pos + len) > stop) ++ return false; + +- pos += len; //consume size of field ++ pos += len; // consume size of field + +- if ((pos + seekIdSize) > stop) +- return false; ++ if ((pos + seekIdSize) > stop) ++ return false; + +- //Note that the SeekId payload really is serialized +- //as a ""Matroska integer"", not as a plain binary value. +- //In fact, Matroska requires that ID values in the +- //stream exactly match the binary representation as listed +- //in the Matroska specification. +- // +- //This parser is more liberal, and permits IDs to have +- //any width. (This could make the representation in the stream +- //different from what's in the spec, but it doesn't matter here, +- //since we always normalize ""Matroska integer"" values.) ++ // Note that the SeekId payload really is serialized ++ // as a ""Matroska integer"", not as a plain binary value. ++ // In fact, Matroska requires that ID values in the ++ // stream exactly match the binary representation as listed ++ // in the Matroska specification. ++ // ++ // This parser is more liberal, and permits IDs to have ++ // any width. (This could make the representation in the stream ++ // different from what's in the spec, but it doesn't matter here, ++ // since we always normalize ""Matroska integer"" values.) + +- pEntry->id = ReadUInt(pReader, pos, len); //payload ++ pEntry->id = ReadUInt(pReader, pos, len); // payload + +- if (pEntry->id <= 0) +- return false; ++ if (pEntry->id <= 0) ++ return false; + +- if (len != seekIdSize) +- return false; ++ if (len != seekIdSize) ++ return false; + +- pos += seekIdSize; //consume SeekID payload ++ pos += seekIdSize; // consume SeekID payload + +- const long long seekPosId = ReadUInt(pReader, pos, len); ++ const long long seekPosId = ReadUInt(pReader, pos, len); + +- if (seekPosId != 0x13AC) //SeekPos ID +- return false; ++ if (seekPosId != 0x13AC) // SeekPos ID ++ return false; + +- if ((pos + len) > stop) +- return false; ++ if ((pos + len) > stop) ++ return false; + +- pos += len; //consume id ++ pos += len; // consume id + +- const long long seekPosSize = ReadUInt(pReader, pos, len); ++ const long long seekPosSize = ReadUInt(pReader, pos, len); + +- if (seekPosSize <= 0) +- return false; ++ if (seekPosSize <= 0) ++ return false; + +- if ((pos + len) > stop) +- return false; ++ if ((pos + len) > stop) ++ return false; + +- pos += len; //consume size ++ pos += len; // consume size + +- if ((pos + seekPosSize) > stop) +- return false; ++ if ((pos + seekPosSize) > stop) ++ return false; + +- pEntry->pos = UnserializeUInt(pReader, pos, seekPosSize); ++ pEntry->pos = UnserializeUInt(pReader, pos, seekPosSize); + +- if (pEntry->pos < 0) +- return false; ++ if (pEntry->pos < 0) ++ return false; + +- pos += seekPosSize; //consume payload ++ pos += seekPosSize; // consume payload + +- if (pos != stop) +- return false; ++ if (pos != stop) ++ return false; + +- return true; ++ return true; + } + #endif + ++Cues::Cues(Segment* pSegment, long long start_, long long size_, ++ long long element_start, long long element_size) ++ : m_pSegment(pSegment), ++ m_start(start_), ++ m_size(size_), ++ m_element_start(element_start), ++ m_element_size(element_size), ++ m_cue_points(NULL), ++ m_count(0), ++ m_preload_count(0), ++ m_pos(start_) {} + +-Cues::Cues( +- Segment* pSegment, +- long long start_, +- long long size_, +- long long element_start, +- long long element_size) : +- m_pSegment(pSegment), +- m_start(start_), +- m_size(size_), +- m_element_start(element_start), +- m_element_size(element_size), +- m_cue_points(NULL), +- m_count(0), +- m_preload_count(0), +- m_pos(start_) +-{ ++Cues::~Cues() { ++ const long n = m_count + m_preload_count; ++ ++ CuePoint** p = m_cue_points; ++ CuePoint** const q = p + n; ++ ++ while (p != q) { ++ CuePoint* const pCP = *p++; ++ assert(pCP); ++ ++ delete pCP; ++ } ++ ++ delete[] m_cue_points; + } + ++long Cues::GetCount() const { ++ if (m_cue_points == NULL) ++ return -1; + +-Cues::~Cues() +-{ +- const long n = m_count + m_preload_count; ++ return m_count; // TODO: really ignore preload count? ++} + +- CuePoint** p = m_cue_points; +- CuePoint** const q = p + n; ++bool Cues::DoneParsing() const { ++ const long long stop = m_start + m_size; ++ return (m_pos >= stop); ++} + +- while (p != q) +- { +- CuePoint* const pCP = *p++; +- assert(pCP); ++void Cues::Init() const { ++ if (m_cue_points) ++ return; + +- delete pCP; +- } ++ assert(m_count == 0); ++ assert(m_preload_count == 0); ++ ++ IMkvReader* const pReader = m_pSegment->m_pReader; ++ ++ const long long stop = m_start + m_size; ++ long long pos = m_start; ++ ++ long cue_points_size = 0; ++ ++ while (pos < stop) { ++ const long long idpos = pos; ++ ++ long len; ++ ++ const long long id = ReadUInt(pReader, pos, len); ++ assert(id >= 0); // TODO ++ assert((pos + len) <= stop); ++ ++ pos += len; // consume ID ++ ++ const long long size = ReadUInt(pReader, pos, len); ++ assert(size >= 0); ++ assert((pos + len) <= stop); ++ ++ pos += len; // consume Size field ++ assert((pos + size) <= stop); ++ ++ if (id == 0x3B) // CuePoint ID ++ PreloadCuePoint(cue_points_size, idpos); ++ ++ pos += size; // consume payload ++ assert(pos <= stop); ++ } ++} ++ ++void Cues::PreloadCuePoint(long& cue_points_size, long long pos) const { ++ assert(m_count == 0); ++ ++ if (m_preload_count >= cue_points_size) { ++ const long n = (cue_points_size <= 0) ? 2048 : 2 * cue_points_size; ++ ++ CuePoint** const qq = new CuePoint* [n]; ++ CuePoint** q = qq; // beginning of target ++ ++ CuePoint** p = m_cue_points; // beginning of source ++ CuePoint** const pp = p + m_preload_count; // end of source ++ ++ while (p != pp) ++ *q++ = *p++; + + delete[] m_cue_points; ++ ++ m_cue_points = qq; ++ cue_points_size = n; ++ } ++ ++ CuePoint* const pCP = new CuePoint(m_preload_count, pos); ++ m_cue_points[m_preload_count++] = pCP; + } + ++bool Cues::LoadCuePoint() const { ++ // odbgstream os; ++ // os << ""Cues::LoadCuePoint"" << endl; + +-long Cues::GetCount() const +-{ +- if (m_cue_points == NULL) +- return -1; ++ const long long stop = m_start + m_size; + +- return m_count; //TODO: really ignore preload count? +-} ++ if (m_pos >= stop) ++ return false; // nothing else to do + ++ Init(); + +-bool Cues::DoneParsing() const +-{ +- const long long stop = m_start + m_size; +- return (m_pos >= stop); +-} ++ IMkvReader* const pReader = m_pSegment->m_pReader; + ++ while (m_pos < stop) { ++ const long long idpos = m_pos; + +-void Cues::Init() const +-{ +- if (m_cue_points) +- return; ++ long len; + +- assert(m_count == 0); +- assert(m_preload_count == 0); ++ const long long id = ReadUInt(pReader, m_pos, len); ++ assert(id >= 0); // TODO ++ assert((m_pos + len) <= stop); + +- IMkvReader* const pReader = m_pSegment->m_pReader; ++ m_pos += len; // consume ID + +- const long long stop = m_start + m_size; +- long long pos = m_start; ++ const long long size = ReadUInt(pReader, m_pos, len); ++ assert(size >= 0); ++ assert((m_pos + len) <= stop); + +- long cue_points_size = 0; ++ m_pos += len; // consume Size field ++ assert((m_pos + size) <= stop); + +- while (pos < stop) +- { +- const long long idpos = pos; ++ if (id != 0x3B) { // CuePoint ID ++ m_pos += size; // consume payload ++ assert(m_pos <= stop); + +- long len; +- +- const long long id = ReadUInt(pReader, pos, len); +- assert(id >= 0); //TODO +- assert((pos + len) <= stop); +- +- pos += len; //consume ID +- +- const long long size = ReadUInt(pReader, pos, len); +- assert(size >= 0); +- assert((pos + len) <= stop); +- +- pos += len; //consume Size field +- assert((pos + size) <= stop); +- +- if (id == 0x3B) //CuePoint ID +- PreloadCuePoint(cue_points_size, idpos); +- +- pos += size; //consume payload +- assert(pos <= stop); +- } +-} +- +- +-void Cues::PreloadCuePoint( +- long& cue_points_size, +- long long pos) const +-{ +- assert(m_count == 0); +- +- if (m_preload_count >= cue_points_size) +- { +- const long n = (cue_points_size <= 0) ? 2048 : 2*cue_points_size; +- +- CuePoint** const qq = new CuePoint*[n]; +- CuePoint** q = qq; //beginning of target +- +- CuePoint** p = m_cue_points; //beginning of source +- CuePoint** const pp = p + m_preload_count; //end of source +- +- while (p != pp) +- *q++ = *p++; +- +- delete[] m_cue_points; +- +- m_cue_points = qq; +- cue_points_size = n; ++ continue; + } + +- CuePoint* const pCP = new CuePoint(m_preload_count, pos); +- m_cue_points[m_preload_count++] = pCP; ++ assert(m_preload_count > 0); ++ ++ CuePoint* const pCP = m_cue_points[m_count]; ++ assert(pCP); ++ assert((pCP->GetTimeCode() >= 0) || (-pCP->GetTimeCode() == idpos)); ++ if (pCP->GetTimeCode() < 0 && (-pCP->GetTimeCode() != idpos)) ++ return false; ++ ++ pCP->Load(pReader); ++ ++m_count; ++ --m_preload_count; ++ ++ m_pos += size; // consume payload ++ assert(m_pos <= stop); ++ ++ return true; // yes, we loaded a cue point ++ } ++ ++ // return (m_pos < stop); ++ return false; // no, we did not load a cue point + } + +- +-bool Cues::LoadCuePoint() const +-{ +- //odbgstream os; +- //os << ""Cues::LoadCuePoint"" << endl; +- +- const long long stop = m_start + m_size; +- +- if (m_pos >= stop) +- return false; //nothing else to do +- +- Init(); +- +- IMkvReader* const pReader = m_pSegment->m_pReader; +- +- while (m_pos < stop) +- { +- const long long idpos = m_pos; +- +- long len; +- +- const long long id = ReadUInt(pReader, m_pos, len); +- assert(id >= 0); //TODO +- assert((m_pos + len) <= stop); +- +- m_pos += len; //consume ID +- +- const long long size = ReadUInt(pReader, m_pos, len); +- assert(size >= 0); +- assert((m_pos + len) <= stop); +- +- m_pos += len; //consume Size field +- assert((m_pos + size) <= stop); +- +- if (id != 0x3B) //CuePoint ID +- { +- m_pos += size; //consume payload +- assert(m_pos <= stop); +- +- continue; +- } +- +- assert(m_preload_count > 0); +- +- CuePoint* const pCP = m_cue_points[m_count]; +- assert(pCP); +- assert((pCP->GetTimeCode() >= 0) || (-pCP->GetTimeCode() == idpos)); +- if (pCP->GetTimeCode() < 0 && (-pCP->GetTimeCode() != idpos)) +- return false; +- +- pCP->Load(pReader); +- ++m_count; +- --m_preload_count; +- +- m_pos += size; //consume payload +- assert(m_pos <= stop); +- +- return true; //yes, we loaded a cue point +- } +- +- //return (m_pos < stop); +- return false; //no, we did not load a cue point +-} +- +- +-bool Cues::Find( +- long long time_ns, +- const Track* pTrack, +- const CuePoint*& pCP, +- const CuePoint::TrackPosition*& pTP) const +-{ +- assert(time_ns >= 0); +- assert(pTrack); ++bool Cues::Find(long long time_ns, const Track* pTrack, const CuePoint*& pCP, ++ const CuePoint::TrackPosition*& pTP) const { ++ assert(time_ns >= 0); ++ assert(pTrack); + + #if 0 + LoadCuePoint(); //establish invariant +@@ -2614,71 +2340,68 @@ + + assert(pCP); + assert(pCP->GetTime(m_pSegment) <= time_ns); + #else +- if (m_cue_points == NULL) +- return false; ++ if (m_cue_points == NULL) ++ return false; + +- if (m_count == 0) +- return false; ++ if (m_count == 0) ++ return false; + +- CuePoint** const ii = m_cue_points; +- CuePoint** i = ii; ++ CuePoint** const ii = m_cue_points; ++ CuePoint** i = ii; + +- CuePoint** const jj = ii + m_count; +- CuePoint** j = jj; ++ CuePoint** const jj = ii + m_count; ++ CuePoint** j = jj; + +- pCP = *i; +- assert(pCP); ++ pCP = *i; ++ assert(pCP); + +- if (time_ns <= pCP->GetTime(m_pSegment)) +- { +- pTP = pCP->Find(pTrack); +- return (pTP != NULL); +- } +- +- while (i < j) +- { +- //INVARIANT: +- //[ii, i) <= time_ns +- //[i, j) ? +- //[j, jj) > time_ns +- +- CuePoint** const k = i + (j - i) / 2; +- assert(k < jj); +- +- CuePoint* const pCP = *k; +- assert(pCP); +- +- const long long t = pCP->GetTime(m_pSegment); +- +- if (t <= time_ns) +- i = k + 1; +- else +- j = k; +- +- assert(i <= j); +- } +- +- assert(i == j); +- assert(i <= jj); +- assert(i > ii); +- +- pCP = *--i; +- assert(pCP); +- assert(pCP->GetTime(m_pSegment) <= time_ns); +-#endif +- +- //TODO: here and elsewhere, it's probably not correct to search +- //for the cue point with this time, and then search for a matching +- //track. In principle, the matching track could be on some earlier +- //cue point, and with our current algorithm, we'd miss it. To make +- //this bullet-proof, we'd need to create a secondary structure, +- //with a list of cue points that apply to a track, and then search +- //that track-based structure for a matching cue point. +- ++ if (time_ns <= pCP->GetTime(m_pSegment)) { + pTP = pCP->Find(pTrack); + return (pTP != NULL); +-} ++ } + ++ while (i < j) { ++ // INVARIANT: ++ //[ii, i) <= time_ns ++ //[i, j) ? ++ //[j, jj) > time_ns ++ ++ CuePoint** const k = i + (j - i) / 2; ++ assert(k < jj); ++ ++ CuePoint* const pCP = *k; ++ assert(pCP); ++ ++ const long long t = pCP->GetTime(m_pSegment); ++ ++ if (t <= time_ns) ++ i = k + 1; ++ else ++ j = k; ++ ++ assert(i <= j); ++ } ++ ++ assert(i == j); ++ assert(i <= jj); ++ assert(i > ii); ++ ++ pCP = *--i; ++ assert(pCP); ++ assert(pCP->GetTime(m_pSegment) <= time_ns); ++#endif ++ ++ // TODO: here and elsewhere, it's probably not correct to search ++ // for the cue point with this time, and then search for a matching ++ // track. In principle, the matching track could be on some earlier ++ // cue point, and with our current algorithm, we'd miss it. To make ++ // this bullet-proof, we'd need to create a secondary structure, ++ // with a list of cue points that apply to a track, and then search ++ // that track-based structure for a matching cue point. ++ ++ pTP = pCP->Find(pTrack); ++ return (pTP != NULL); ++} + + #if 0 + bool Cues::FindNext( +@@ -2739,14 +2462,12 @@ + + } + #endif + ++const CuePoint* Cues::GetFirst() const { ++ if (m_cue_points == NULL) ++ return NULL; + +-const CuePoint* Cues::GetFirst() const +-{ +- if (m_cue_points == NULL) +- return NULL; +- +- if (m_count == 0) +- return NULL; ++ if (m_count == 0) ++ return NULL; + + #if 0 + LoadCuePoint(); //init cues +@@ -2757,24 +2478,22 @@ + + return NULL; + #endif + +- CuePoint* const* const pp = m_cue_points; +- assert(pp); ++ CuePoint* const* const pp = m_cue_points; ++ assert(pp); + +- CuePoint* const pCP = pp[0]; +- assert(pCP); +- assert(pCP->GetTimeCode() >= 0); ++ CuePoint* const pCP = pp[0]; ++ assert(pCP); ++ assert(pCP->GetTimeCode() >= 0); + +- return pCP; ++ return pCP; + } + ++const CuePoint* Cues::GetLast() const { ++ if (m_cue_points == NULL) ++ return NULL; + +-const CuePoint* Cues::GetLast() const +-{ +- if (m_cue_points == NULL) +- return NULL; +- +- if (m_count <= 0) +- return NULL; ++ if (m_count <= 0) ++ return NULL; + + #if 0 + LoadCuePoint(); //init cues +@@ -2795,28 +2514,26 @@ + + pCP->Load(m_pSegment->m_pReader); + assert(pCP->GetTimeCode() >= 0); + #else +- const long index = m_count - 1; ++ const long index = m_count - 1; + +- CuePoint* const* const pp = m_cue_points; +- assert(pp); ++ CuePoint* const* const pp = m_cue_points; ++ assert(pp); + +- CuePoint* const pCP = pp[index]; +- assert(pCP); +- assert(pCP->GetTimeCode() >= 0); ++ CuePoint* const pCP = pp[index]; ++ assert(pCP); ++ assert(pCP->GetTimeCode() >= 0); + #endif + +- return pCP; ++ return pCP; + } + ++const CuePoint* Cues::GetNext(const CuePoint* pCurr) const { ++ if (pCurr == NULL) ++ return NULL; + +-const CuePoint* Cues::GetNext(const CuePoint* pCurr) const +-{ +- if (pCurr == NULL) +- return NULL; +- +- assert(pCurr->GetTimeCode() >= 0); +- assert(m_cue_points); +- assert(m_count >= 1); ++ assert(pCurr->GetTimeCode() >= 0); ++ assert(m_cue_points); ++ assert(m_count >= 1); + + #if 0 + const size_t count = m_count + m_preload_count; +@@ -2838,386 +2555,347 @@ + + + pNext->Load(m_pSegment->m_pReader); + #else +- long index = pCurr->m_index; +- assert(index < m_count); ++ long index = pCurr->m_index; ++ assert(index < m_count); + +- CuePoint* const* const pp = m_cue_points; +- assert(pp); +- assert(pp[index] == pCurr); ++ CuePoint* const* const pp = m_cue_points; ++ assert(pp); ++ assert(pp[index] == pCurr); + +- ++index; ++ ++index; + +- if (index >= m_count) +- return NULL; ++ if (index >= m_count) ++ return NULL; + +- CuePoint* const pNext = pp[index]; +- assert(pNext); +- assert(pNext->GetTimeCode() >= 0); ++ CuePoint* const pNext = pp[index]; ++ assert(pNext); ++ assert(pNext->GetTimeCode() >= 0); + #endif + +- return pNext; ++ return pNext; + } + ++const BlockEntry* Cues::GetBlock(const CuePoint* pCP, ++ const CuePoint::TrackPosition* pTP) const { ++ if (pCP == NULL) ++ return NULL; + +-const BlockEntry* Cues::GetBlock( +- const CuePoint* pCP, +- const CuePoint::TrackPosition* pTP) const +-{ +- if (pCP == NULL) +- return NULL; ++ if (pTP == NULL) ++ return NULL; + +- if (pTP == NULL) +- return NULL; +- +- return m_pSegment->GetBlock(*pCP, *pTP); ++ return m_pSegment->GetBlock(*pCP, *pTP); + } + ++const BlockEntry* Segment::GetBlock(const CuePoint& cp, ++ const CuePoint::TrackPosition& tp) { ++ Cluster** const ii = m_clusters; ++ Cluster** i = ii; + +-const BlockEntry* Segment::GetBlock( +- const CuePoint& cp, +- const CuePoint::TrackPosition& tp) +-{ +- Cluster** const ii = m_clusters; +- Cluster** i = ii; ++ const long count = m_clusterCount + m_clusterPreloadCount; + +- const long count = m_clusterCount + m_clusterPreloadCount; ++ Cluster** const jj = ii + count; ++ Cluster** j = jj; + +- Cluster** const jj = ii + count; +- Cluster** j = jj; ++ while (i < j) { ++ // INVARIANT: ++ //[ii, i) < pTP->m_pos ++ //[i, j) ? ++ //[j, jj) > pTP->m_pos + +- while (i < j) +- { +- //INVARIANT: +- //[ii, i) < pTP->m_pos +- //[i, j) ? +- //[j, jj) > pTP->m_pos ++ Cluster** const k = i + (j - i) / 2; ++ assert(k < jj); + +- Cluster** const k = i + (j - i) / 2; +- assert(k < jj); +- +- Cluster* const pCluster = *k; +- assert(pCluster); +- +- //const long long pos_ = pCluster->m_pos; +- //assert(pos_); +- //const long long pos = pos_ * ((pos_ < 0) ? -1 : 1); +- +- const long long pos = pCluster->GetPosition(); +- assert(pos >= 0); +- +- if (pos < tp.m_pos) +- i = k + 1; +- else if (pos > tp.m_pos) +- j = k; +- else +- return pCluster->GetEntry(cp, tp); +- } +- +- assert(i == j); +- //assert(Cluster::HasBlockEntries(this, tp.m_pos)); +- +- Cluster* const pCluster = Cluster::Create(this, -1, tp.m_pos); //, -1); ++ Cluster* const pCluster = *k; + assert(pCluster); + +- const ptrdiff_t idx = i - m_clusters; ++ // const long long pos_ = pCluster->m_pos; ++ // assert(pos_); ++ // const long long pos = pos_ * ((pos_ < 0) ? -1 : 1); + +- PreloadCluster(pCluster, idx); +- assert(m_clusters); +- assert(m_clusterPreloadCount > 0); +- assert(m_clusters[idx] == pCluster); ++ const long long pos = pCluster->GetPosition(); ++ assert(pos >= 0); + +- return pCluster->GetEntry(cp, tp); ++ if (pos < tp.m_pos) ++ i = k + 1; ++ else if (pos > tp.m_pos) ++ j = k; ++ else ++ return pCluster->GetEntry(cp, tp); ++ } ++ ++ assert(i == j); ++ // assert(Cluster::HasBlockEntries(this, tp.m_pos)); ++ ++ Cluster* const pCluster = Cluster::Create(this, -1, tp.m_pos); //, -1); ++ assert(pCluster); ++ ++ const ptrdiff_t idx = i - m_clusters; ++ ++ PreloadCluster(pCluster, idx); ++ assert(m_clusters); ++ assert(m_clusterPreloadCount > 0); ++ assert(m_clusters[idx] == pCluster); ++ ++ return pCluster->GetEntry(cp, tp); + } + ++const Cluster* Segment::FindOrPreloadCluster(long long requested_pos) { ++ if (requested_pos < 0) ++ return 0; + +-const Cluster* Segment::FindOrPreloadCluster(long long requested_pos) +-{ +- if (requested_pos < 0) +- return 0; ++ Cluster** const ii = m_clusters; ++ Cluster** i = ii; + +- Cluster** const ii = m_clusters; +- Cluster** i = ii; ++ const long count = m_clusterCount + m_clusterPreloadCount; + +- const long count = m_clusterCount + m_clusterPreloadCount; ++ Cluster** const jj = ii + count; ++ Cluster** j = jj; + +- Cluster** const jj = ii + count; +- Cluster** j = jj; ++ while (i < j) { ++ // INVARIANT: ++ //[ii, i) < pTP->m_pos ++ //[i, j) ? ++ //[j, jj) > pTP->m_pos + +- while (i < j) +- { +- //INVARIANT: +- //[ii, i) < pTP->m_pos +- //[i, j) ? +- //[j, jj) > pTP->m_pos ++ Cluster** const k = i + (j - i) / 2; ++ assert(k < jj); + +- Cluster** const k = i + (j - i) / 2; +- assert(k < jj); +- +- Cluster* const pCluster = *k; +- assert(pCluster); +- +- //const long long pos_ = pCluster->m_pos; +- //assert(pos_); +- //const long long pos = pos_ * ((pos_ < 0) ? -1 : 1); +- +- const long long pos = pCluster->GetPosition(); +- assert(pos >= 0); +- +- if (pos < requested_pos) +- i = k + 1; +- else if (pos > requested_pos) +- j = k; +- else +- return pCluster; +- } +- +- assert(i == j); +- //assert(Cluster::HasBlockEntries(this, tp.m_pos)); +- +- Cluster* const pCluster = Cluster::Create( +- this, +- -1, +- requested_pos); +- //-1); ++ Cluster* const pCluster = *k; + assert(pCluster); + +- const ptrdiff_t idx = i - m_clusters; ++ // const long long pos_ = pCluster->m_pos; ++ // assert(pos_); ++ // const long long pos = pos_ * ((pos_ < 0) ? -1 : 1); + +- PreloadCluster(pCluster, idx); +- assert(m_clusters); +- assert(m_clusterPreloadCount > 0); +- assert(m_clusters[idx] == pCluster); ++ const long long pos = pCluster->GetPosition(); ++ assert(pos >= 0); + +- return pCluster; ++ if (pos < requested_pos) ++ i = k + 1; ++ else if (pos > requested_pos) ++ j = k; ++ else ++ return pCluster; ++ } ++ ++ assert(i == j); ++ // assert(Cluster::HasBlockEntries(this, tp.m_pos)); ++ ++ Cluster* const pCluster = Cluster::Create(this, -1, requested_pos); ++ //-1); ++ assert(pCluster); ++ ++ const ptrdiff_t idx = i - m_clusters; ++ ++ PreloadCluster(pCluster, idx); ++ assert(m_clusters); ++ assert(m_clusterPreloadCount > 0); ++ assert(m_clusters[idx] == pCluster); ++ ++ return pCluster; + } + +- +-CuePoint::CuePoint(long idx, long long pos) : +- m_element_start(0), +- m_element_size(0), +- m_index(idx), +- m_timecode(-1 * pos), +- m_track_positions(NULL), +- m_track_positions_count(0) +-{ +- assert(pos > 0); ++CuePoint::CuePoint(long idx, long long pos) ++ : m_element_start(0), ++ m_element_size(0), ++ m_index(idx), ++ m_timecode(-1 * pos), ++ m_track_positions(NULL), ++ m_track_positions_count(0) { ++ assert(pos > 0); + } + ++CuePoint::~CuePoint() { delete[] m_track_positions; } + +-CuePoint::~CuePoint() +-{ +- delete[] m_track_positions; +-} ++void CuePoint::Load(IMkvReader* pReader) { ++ // odbgstream os; ++ // os << ""CuePoint::Load(begin): timecode="" << m_timecode << endl; + ++ if (m_timecode >= 0) // already loaded ++ return; + +-void CuePoint::Load(IMkvReader* pReader) +-{ +- //odbgstream os; +- //os << ""CuePoint::Load(begin): timecode="" << m_timecode << endl; ++ assert(m_track_positions == NULL); ++ assert(m_track_positions_count == 0); + +- if (m_timecode >= 0) //already loaded +- return; ++ long long pos_ = -m_timecode; ++ const long long element_start = pos_; + +- assert(m_track_positions == NULL); +- assert(m_track_positions_count == 0); ++ long long stop; + +- long long pos_ = -m_timecode; +- const long long element_start = pos_; ++ { ++ long len; + +- long long stop; ++ const long long id = ReadUInt(pReader, pos_, len); ++ assert(id == 0x3B); // CuePoint ID ++ if (id != 0x3B) ++ return; + +- { +- long len; ++ pos_ += len; // consume ID + +- const long long id = ReadUInt(pReader, pos_, len); +- assert(id == 0x3B); //CuePoint ID +- if (id != 0x3B) +- return; ++ const long long size = ReadUInt(pReader, pos_, len); ++ assert(size >= 0); + +- pos_ += len; //consume ID ++ pos_ += len; // consume Size field ++ // pos_ now points to start of payload + +- const long long size = ReadUInt(pReader, pos_, len); +- assert(size >= 0); ++ stop = pos_ + size; ++ } + +- pos_ += len; //consume Size field +- //pos_ now points to start of payload ++ const long long element_size = stop - element_start; + +- stop = pos_ + size; ++ long long pos = pos_; ++ ++ // First count number of track positions ++ ++ while (pos < stop) { ++ long len; ++ ++ const long long id = ReadUInt(pReader, pos, len); ++ assert(id >= 0); // TODO ++ assert((pos + len) <= stop); ++ ++ pos += len; // consume ID ++ ++ const long long size = ReadUInt(pReader, pos, len); ++ assert(size >= 0); ++ assert((pos + len) <= stop); ++ ++ pos += len; // consume Size field ++ assert((pos + size) <= stop); ++ ++ if (id == 0x33) // CueTime ID ++ m_timecode = UnserializeUInt(pReader, pos, size); ++ ++ else if (id == 0x37) // CueTrackPosition(s) ID ++ ++m_track_positions_count; ++ ++ pos += size; // consume payload ++ assert(pos <= stop); ++ } ++ ++ assert(m_timecode >= 0); ++ assert(m_track_positions_count > 0); ++ ++ // os << ""CuePoint::Load(cont'd): idpos="" << idpos ++ // << "" timecode="" << m_timecode ++ // << endl; ++ ++ m_track_positions = new TrackPosition[m_track_positions_count]; ++ ++ // Now parse track positions ++ ++ TrackPosition* p = m_track_positions; ++ pos = pos_; ++ ++ while (pos < stop) { ++ long len; ++ ++ const long long id = ReadUInt(pReader, pos, len); ++ assert(id >= 0); // TODO ++ assert((pos + len) <= stop); ++ ++ pos += len; // consume ID ++ ++ const long long size = ReadUInt(pReader, pos, len); ++ assert(size >= 0); ++ assert((pos + len) <= stop); ++ ++ pos += len; // consume Size field ++ assert((pos + size) <= stop); ++ ++ if (id == 0x37) { // CueTrackPosition(s) ID ++ TrackPosition& tp = *p++; ++ tp.Parse(pReader, pos, size); + } + +- const long long element_size = stop - element_start; ++ pos += size; // consume payload ++ assert(pos <= stop); ++ } + +- long long pos = pos_; ++ assert(size_t(p - m_track_positions) == m_track_positions_count); + +- //First count number of track positions +- +- while (pos < stop) +- { +- long len; +- +- const long long id = ReadUInt(pReader, pos, len); +- assert(id >= 0); //TODO +- assert((pos + len) <= stop); +- +- pos += len; //consume ID +- +- const long long size = ReadUInt(pReader, pos, len); +- assert(size >= 0); +- assert((pos + len) <= stop); +- +- pos += len; //consume Size field +- assert((pos + size) <= stop); +- +- if (id == 0x33) //CueTime ID +- m_timecode = UnserializeUInt(pReader, pos, size); +- +- else if (id == 0x37) //CueTrackPosition(s) ID +- ++m_track_positions_count; +- +- pos += size; //consume payload +- assert(pos <= stop); +- } +- +- assert(m_timecode >= 0); +- assert(m_track_positions_count > 0); +- +- //os << ""CuePoint::Load(cont'd): idpos="" << idpos +- // << "" timecode="" << m_timecode +- // << endl; +- +- m_track_positions = new TrackPosition[m_track_positions_count]; +- +- //Now parse track positions +- +- TrackPosition* p = m_track_positions; +- pos = pos_; +- +- while (pos < stop) +- { +- long len; +- +- const long long id = ReadUInt(pReader, pos, len); +- assert(id >= 0); //TODO +- assert((pos + len) <= stop); +- +- pos += len; //consume ID +- +- const long long size = ReadUInt(pReader, pos, len); +- assert(size >= 0); +- assert((pos + len) <= stop); +- +- pos += len; //consume Size field +- assert((pos + size) <= stop); +- +- if (id == 0x37) //CueTrackPosition(s) ID +- { +- TrackPosition& tp = *p++; +- tp.Parse(pReader, pos, size); +- } +- +- pos += size; //consume payload +- assert(pos <= stop); +- } +- +- assert(size_t(p - m_track_positions) == m_track_positions_count); +- +- m_element_start = element_start; +- m_element_size = element_size; ++ m_element_start = element_start; ++ m_element_size = element_size; + } + ++void CuePoint::TrackPosition::Parse(IMkvReader* pReader, long long start_, ++ long long size_) { ++ const long long stop = start_ + size_; ++ long long pos = start_; + ++ m_track = -1; ++ m_pos = -1; ++ m_block = 1; // default + +-void CuePoint::TrackPosition::Parse( +- IMkvReader* pReader, +- long long start_, +- long long size_) +-{ +- const long long stop = start_ + size_; +- long long pos = start_; ++ while (pos < stop) { ++ long len; + +- m_track = -1; +- m_pos = -1; +- m_block = 1; //default ++ const long long id = ReadUInt(pReader, pos, len); ++ assert(id >= 0); // TODO ++ assert((pos + len) <= stop); + +- while (pos < stop) +- { +- long len; ++ pos += len; // consume ID + +- const long long id = ReadUInt(pReader, pos, len); +- assert(id >= 0); //TODO +- assert((pos + len) <= stop); ++ const long long size = ReadUInt(pReader, pos, len); ++ assert(size >= 0); ++ assert((pos + len) <= stop); + +- pos += len; //consume ID ++ pos += len; // consume Size field ++ assert((pos + size) <= stop); + +- const long long size = ReadUInt(pReader, pos, len); +- assert(size >= 0); +- assert((pos + len) <= stop); ++ if (id == 0x77) // CueTrack ID ++ m_track = UnserializeUInt(pReader, pos, size); + +- pos += len; //consume Size field +- assert((pos + size) <= stop); ++ else if (id == 0x71) // CueClusterPos ID ++ m_pos = UnserializeUInt(pReader, pos, size); + +- if (id == 0x77) //CueTrack ID +- m_track = UnserializeUInt(pReader, pos, size); ++ else if (id == 0x1378) // CueBlockNumber ++ m_block = UnserializeUInt(pReader, pos, size); + +- else if (id == 0x71) //CueClusterPos ID +- m_pos = UnserializeUInt(pReader, pos, size); ++ pos += size; // consume payload ++ assert(pos <= stop); ++ } + +- else if (id == 0x1378) //CueBlockNumber +- m_block = UnserializeUInt(pReader, pos, size); +- +- pos += size; //consume payload +- assert(pos <= stop); +- } +- +- assert(m_pos >= 0); +- assert(m_track > 0); +- //assert(m_block > 0); ++ assert(m_pos >= 0); ++ assert(m_track > 0); ++ // assert(m_block > 0); + } + ++const CuePoint::TrackPosition* CuePoint::Find(const Track* pTrack) const { ++ assert(pTrack); + +-const CuePoint::TrackPosition* CuePoint::Find(const Track* pTrack) const +-{ +- assert(pTrack); ++ const long long n = pTrack->GetNumber(); + +- const long long n = pTrack->GetNumber(); ++ const TrackPosition* i = m_track_positions; ++ const TrackPosition* const j = i + m_track_positions_count; + +- const TrackPosition* i = m_track_positions; +- const TrackPosition* const j = i + m_track_positions_count; ++ while (i != j) { ++ const TrackPosition& p = *i++; + +- while (i != j) +- { +- const TrackPosition& p = *i++; ++ if (p.m_track == n) ++ return &p; ++ } + +- if (p.m_track == n) +- return &p; +- } +- +- return NULL; //no matching track number found ++ return NULL; // no matching track number found + } + ++long long CuePoint::GetTimeCode() const { return m_timecode; } + +-long long CuePoint::GetTimeCode() const +-{ +- return m_timecode; ++long long CuePoint::GetTime(const Segment* pSegment) const { ++ assert(pSegment); ++ assert(m_timecode >= 0); ++ ++ const SegmentInfo* const pInfo = pSegment->GetInfo(); ++ assert(pInfo); ++ ++ const long long scale = pInfo->GetTimeCodeScale(); ++ assert(scale >= 1); ++ ++ const long long time = scale * m_timecode; ++ ++ return time; + } + +-long long CuePoint::GetTime(const Segment* pSegment) const +-{ +- assert(pSegment); +- assert(m_timecode >= 0); +- +- const SegmentInfo* const pInfo = pSegment->GetInfo(); +- assert(pInfo); +- +- const long long scale = pInfo->GetTimeCodeScale(); +- assert(scale >= 1); +- +- const long long time = scale * m_timecode; +- +- return time; +-} +- +- + #if 0 + long long Segment::Unparsed() const + { +@@ -3232,808 +2910,745 @@ + + return result; + } + #else +-bool Segment::DoneParsing() const +-{ +- if (m_size < 0) +- { +- long long total, avail; ++bool Segment::DoneParsing() const { ++ if (m_size < 0) { ++ long long total, avail; + +- const int status = m_pReader->Length(&total, &avail); ++ const int status = m_pReader->Length(&total, &avail); + +- if (status < 0) //error +- return true; //must assume done ++ if (status < 0) // error ++ return true; // must assume done + +- if (total < 0) +- return false; //assume live stream ++ if (total < 0) ++ return false; // assume live stream + +- return (m_pos >= total); +- } ++ return (m_pos >= total); ++ } + +- const long long stop = m_start + m_size; ++ const long long stop = m_start + m_size; + +- return (m_pos >= stop); ++ return (m_pos >= stop); + } + #endif + ++const Cluster* Segment::GetFirst() const { ++ if ((m_clusters == NULL) || (m_clusterCount <= 0)) ++ return &m_eos; + +-const Cluster* Segment::GetFirst() const +-{ +- if ((m_clusters == NULL) || (m_clusterCount <= 0)) +- return &m_eos; ++ Cluster* const pCluster = m_clusters[0]; ++ assert(pCluster); + +- Cluster* const pCluster = m_clusters[0]; +- assert(pCluster); +- +- return pCluster; ++ return pCluster; + } + ++const Cluster* Segment::GetLast() const { ++ if ((m_clusters == NULL) || (m_clusterCount <= 0)) ++ return &m_eos; + +-const Cluster* Segment::GetLast() const +-{ +- if ((m_clusters == NULL) || (m_clusterCount <= 0)) +- return &m_eos; ++ const long idx = m_clusterCount - 1; + +- const long idx = m_clusterCount - 1; ++ Cluster* const pCluster = m_clusters[idx]; ++ assert(pCluster); + +- Cluster* const pCluster = m_clusters[idx]; +- assert(pCluster); +- +- return pCluster; ++ return pCluster; + } + ++unsigned long Segment::GetCount() const { return m_clusterCount; } + +-unsigned long Segment::GetCount() const +-{ +- return m_clusterCount; +-} ++const Cluster* Segment::GetNext(const Cluster* pCurr) { ++ assert(pCurr); ++ assert(pCurr != &m_eos); ++ assert(m_clusters); + ++ long idx = pCurr->m_index; + +-const Cluster* Segment::GetNext(const Cluster* pCurr) +-{ +- assert(pCurr); +- assert(pCurr != &m_eos); +- assert(m_clusters); ++ if (idx >= 0) { ++ assert(m_clusterCount > 0); ++ assert(idx < m_clusterCount); ++ assert(pCurr == m_clusters[idx]); + +- long idx = pCurr->m_index; ++ ++idx; + +- if (idx >= 0) +- { +- assert(m_clusterCount > 0); +- assert(idx < m_clusterCount); +- assert(pCurr == m_clusters[idx]); ++ if (idx >= m_clusterCount) ++ return &m_eos; // caller will LoadCluster as desired + +- ++idx; +- +- if (idx >= m_clusterCount) +- return &m_eos; //caller will LoadCluster as desired +- +- Cluster* const pNext = m_clusters[idx]; +- assert(pNext); +- assert(pNext->m_index >= 0); +- assert(pNext->m_index == idx); +- +- return pNext; +- } +- +- assert(m_clusterPreloadCount > 0); +- +- long long pos = pCurr->m_element_start; +- +- assert(m_size >= 0); //TODO +- const long long stop = m_start + m_size; //end of segment +- +- { +- long len; +- +- long long result = GetUIntLength(m_pReader, pos, len); +- assert(result == 0); +- assert((pos + len) <= stop); //TODO +- if (result != 0) +- return NULL; +- +- const long long id = ReadUInt(m_pReader, pos, len); +- assert(id == 0x0F43B675); //Cluster ID +- if (id != 0x0F43B675) +- return NULL; +- +- pos += len; //consume ID +- +- //Read Size +- result = GetUIntLength(m_pReader, pos, len); +- assert(result == 0); //TODO +- assert((pos + len) <= stop); //TODO +- +- const long long size = ReadUInt(m_pReader, pos, len); +- assert(size > 0); //TODO +- //assert((pCurr->m_size <= 0) || (pCurr->m_size == size)); +- +- pos += len; //consume length of size of element +- assert((pos + size) <= stop); //TODO +- +- //Pos now points to start of payload +- +- pos += size; //consume payload +- } +- +- long long off_next = 0; +- +- while (pos < stop) +- { +- long len; +- +- long long result = GetUIntLength(m_pReader, pos, len); +- assert(result == 0); +- assert((pos + len) <= stop); //TODO +- if (result != 0) +- return NULL; +- +- const long long idpos = pos; //pos of next (potential) cluster +- +- const long long id = ReadUInt(m_pReader, idpos, len); +- assert(id > 0); //TODO +- +- pos += len; //consume ID +- +- //Read Size +- result = GetUIntLength(m_pReader, pos, len); +- assert(result == 0); //TODO +- assert((pos + len) <= stop); //TODO +- +- const long long size = ReadUInt(m_pReader, pos, len); +- assert(size >= 0); //TODO +- +- pos += len; //consume length of size of element +- assert((pos + size) <= stop); //TODO +- +- //Pos now points to start of payload +- +- if (size == 0) //weird +- continue; +- +- if (id == 0x0F43B675) //Cluster ID +- { +- const long long off_next_ = idpos - m_start; +- +- long long pos_; +- long len_; +- +- const long status = Cluster::HasBlockEntries( +- this, +- off_next_, +- pos_, +- len_); +- +- assert(status >= 0); +- +- if (status > 0) +- { +- off_next = off_next_; +- break; +- } +- } +- +- pos += size; //consume payload +- } +- +- if (off_next <= 0) +- return 0; +- +- Cluster** const ii = m_clusters + m_clusterCount; +- Cluster** i = ii; +- +- Cluster** const jj = ii + m_clusterPreloadCount; +- Cluster** j = jj; +- +- while (i < j) +- { +- //INVARIANT: +- //[0, i) < pos_next +- //[i, j) ? +- //[j, jj) > pos_next +- +- Cluster** const k = i + (j - i) / 2; +- assert(k < jj); +- +- Cluster* const pNext = *k; +- assert(pNext); +- assert(pNext->m_index < 0); +- +- //const long long pos_ = pNext->m_pos; +- //assert(pos_); +- //pos = pos_ * ((pos_ < 0) ? -1 : 1); +- +- pos = pNext->GetPosition(); +- +- if (pos < off_next) +- i = k + 1; +- else if (pos > off_next) +- j = k; +- else +- return pNext; +- } +- +- assert(i == j); +- +- Cluster* const pNext = Cluster::Create(this, +- -1, +- off_next); ++ Cluster* const pNext = m_clusters[idx]; + assert(pNext); +- +- const ptrdiff_t idx_next = i - m_clusters; //insertion position +- +- PreloadCluster(pNext, idx_next); +- assert(m_clusters); +- assert(idx_next < m_clusterSize); +- assert(m_clusters[idx_next] == pNext); ++ assert(pNext->m_index >= 0); ++ assert(pNext->m_index == idx); + + return pNext; +-} ++ } + ++ assert(m_clusterPreloadCount > 0); + +-long Segment::ParseNext( +- const Cluster* pCurr, +- const Cluster*& pResult, +- long long& pos, +- long& len) +-{ +- assert(pCurr); +- assert(!pCurr->EOS()); +- assert(m_clusters); ++ long long pos = pCurr->m_element_start; + +- pResult = 0; ++ assert(m_size >= 0); // TODO ++ const long long stop = m_start + m_size; // end of segment + +- if (pCurr->m_index >= 0) //loaded (not merely preloaded) +- { +- assert(m_clusters[pCurr->m_index] == pCurr); ++ { ++ long len; + +- const long next_idx = pCurr->m_index + 1; ++ long long result = GetUIntLength(m_pReader, pos, len); ++ assert(result == 0); ++ assert((pos + len) <= stop); // TODO ++ if (result != 0) ++ return NULL; + +- if (next_idx < m_clusterCount) +- { +- pResult = m_clusters[next_idx]; +- return 0; //success +- } ++ const long long id = ReadUInt(m_pReader, pos, len); ++ assert(id == 0x0F43B675); // Cluster ID ++ if (id != 0x0F43B675) ++ return NULL; + +- //curr cluster is last among loaded ++ pos += len; // consume ID + +- const long result = LoadCluster(pos, len); ++ // Read Size ++ result = GetUIntLength(m_pReader, pos, len); ++ assert(result == 0); // TODO ++ assert((pos + len) <= stop); // TODO + +- if (result < 0) //error or underflow +- return result; ++ const long long size = ReadUInt(m_pReader, pos, len); ++ assert(size > 0); // TODO ++ // assert((pCurr->m_size <= 0) || (pCurr->m_size == size)); + +- if (result > 0) //no more clusters +- { +- //pResult = &m_eos; +- return 1; +- } ++ pos += len; // consume length of size of element ++ assert((pos + size) <= stop); // TODO + +- pResult = GetLast(); +- return 0; //success ++ // Pos now points to start of payload ++ ++ pos += size; // consume payload ++ } ++ ++ long long off_next = 0; ++ ++ while (pos < stop) { ++ long len; ++ ++ long long result = GetUIntLength(m_pReader, pos, len); ++ assert(result == 0); ++ assert((pos + len) <= stop); // TODO ++ if (result != 0) ++ return NULL; ++ ++ const long long idpos = pos; // pos of next (potential) cluster ++ ++ const long long id = ReadUInt(m_pReader, idpos, len); ++ assert(id > 0); // TODO ++ ++ pos += len; // consume ID ++ ++ // Read Size ++ result = GetUIntLength(m_pReader, pos, len); ++ assert(result == 0); // TODO ++ assert((pos + len) <= stop); // TODO ++ ++ const long long size = ReadUInt(m_pReader, pos, len); ++ assert(size >= 0); // TODO ++ ++ pos += len; // consume length of size of element ++ assert((pos + size) <= stop); // TODO ++ ++ // Pos now points to start of payload ++ ++ if (size == 0) // weird ++ continue; ++ ++ if (id == 0x0F43B675) { // Cluster ID ++ const long long off_next_ = idpos - m_start; ++ ++ long long pos_; ++ long len_; ++ ++ const long status = Cluster::HasBlockEntries(this, off_next_, pos_, len_); ++ ++ assert(status >= 0); ++ ++ if (status > 0) { ++ off_next = off_next_; ++ break; ++ } + } + +- assert(m_pos > 0); ++ pos += size; // consume payload ++ } + +- long long total, avail; ++ if (off_next <= 0) ++ return 0; + +- long status = m_pReader->Length(&total, &avail); ++ Cluster** const ii = m_clusters + m_clusterCount; ++ Cluster** i = ii; + +- if (status < 0) //error +- return status; ++ Cluster** const jj = ii + m_clusterPreloadCount; ++ Cluster** j = jj; + +- assert((total < 0) || (avail <= total)); ++ while (i < j) { ++ // INVARIANT: ++ //[0, i) < pos_next ++ //[i, j) ? ++ //[j, jj) > pos_next + +- const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; ++ Cluster** const k = i + (j - i) / 2; ++ assert(k < jj); + +- //interrogate curr cluster ++ Cluster* const pNext = *k; ++ assert(pNext); ++ assert(pNext->m_index < 0); + +- pos = pCurr->m_element_start; ++ // const long long pos_ = pNext->m_pos; ++ // assert(pos_); ++ // pos = pos_ * ((pos_ < 0) ? -1 : 1); + +- if (pCurr->m_element_size >= 0) +- pos += pCurr->m_element_size; ++ pos = pNext->GetPosition(); ++ ++ if (pos < off_next) ++ i = k + 1; ++ else if (pos > off_next) ++ j = k; + else +- { +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } ++ return pNext; ++ } + +- long long result = GetUIntLength(m_pReader, pos, len); ++ assert(i == j); + +- if (result < 0) //error +- return static_cast(result); ++ Cluster* const pNext = Cluster::Create(this, -1, off_next); ++ assert(pNext); + +- if (result > 0) //weird +- return E_BUFFER_NOT_FULL; ++ const ptrdiff_t idx_next = i - m_clusters; // insertion position + +- if ((segment_stop >= 0) && ((pos + len) > segment_stop)) +- return E_FILE_FORMAT_INVALID; ++ PreloadCluster(pNext, idx_next); ++ assert(m_clusters); ++ assert(idx_next < m_clusterSize); ++ assert(m_clusters[idx_next] == pNext); + +- if ((pos + len) > avail) +- return E_BUFFER_NOT_FULL; +- +- const long long id = ReadUInt(m_pReader, pos, len); +- +- if (id != 0x0F43B675) //weird: not Cluster ID +- return -1; +- +- pos += len; //consume ID +- +- //Read Size +- +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } +- +- result = GetUIntLength(m_pReader, pos, len); +- +- if (result < 0) //error +- return static_cast(result); +- +- if (result > 0) //weird +- return E_BUFFER_NOT_FULL; +- +- if ((segment_stop >= 0) && ((pos + len) > segment_stop)) +- return E_FILE_FORMAT_INVALID; +- +- if ((pos + len) > avail) +- return E_BUFFER_NOT_FULL; +- +- const long long size = ReadUInt(m_pReader, pos, len); +- +- if (size < 0) //error +- return static_cast(size); +- +- pos += len; //consume size field +- +- const long long unknown_size = (1LL << (7 * len)) - 1; +- +- if (size == unknown_size) //TODO: should never happen +- return E_FILE_FORMAT_INVALID; //TODO: resolve this +- +- //assert((pCurr->m_size <= 0) || (pCurr->m_size == size)); +- +- if ((segment_stop >= 0) && ((pos + size) > segment_stop)) +- return E_FILE_FORMAT_INVALID; +- +- //Pos now points to start of payload +- +- pos += size; //consume payload (that is, the current cluster) +- assert((segment_stop < 0) || (pos <= segment_stop)); +- +- //By consuming the payload, we are assuming that the curr +- //cluster isn't interesting. That is, we don't bother checking +- //whether the payload of the curr cluster is less than what +- //happens to be available (obtained via IMkvReader::Length). +- //Presumably the caller has already dispensed with the current +- //cluster, and really does want the next cluster. +- } +- +- //pos now points to just beyond the last fully-loaded cluster +- +- for (;;) +- { +- const long status = DoParseNext(pResult, pos, len); +- +- if (status <= 1) +- return status; +- } ++ return pNext; + } + ++long Segment::ParseNext(const Cluster* pCurr, const Cluster*& pResult, ++ long long& pos, long& len) { ++ assert(pCurr); ++ assert(!pCurr->EOS()); ++ assert(m_clusters); + +-long Segment::DoParseNext( +- const Cluster*& pResult, +- long long& pos, +- long& len) +-{ +- long long total, avail; ++ pResult = 0; + +- long status = m_pReader->Length(&total, &avail); ++ if (pCurr->m_index >= 0) { // loaded (not merely preloaded) ++ assert(m_clusters[pCurr->m_index] == pCurr); + +- if (status < 0) //error +- return status; ++ const long next_idx = pCurr->m_index + 1; + +- assert((total < 0) || (avail <= total)); ++ if (next_idx < m_clusterCount) { ++ pResult = m_clusters[next_idx]; ++ return 0; // success ++ } + +- const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; ++ // curr cluster is last among loaded + +- //Parse next cluster. This is strictly a parsing activity. +- //Creation of a new cluster object happens later, after the +- //parsing is done. ++ const long result = LoadCluster(pos, len); + +- long long off_next = 0; +- long long cluster_size = -1; ++ if (result < 0) // error or underflow ++ return result; + +- for (;;) ++ if (result > 0) // no more clusters + { +- if ((total >= 0) && (pos >= total)) +- return 1; //EOF ++ // pResult = &m_eos; ++ return 1; ++ } + +- if ((segment_stop >= 0) && (pos >= segment_stop)) +- return 1; //EOF ++ pResult = GetLast(); ++ return 0; // success ++ } + +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } ++ assert(m_pos > 0); + +- long long result = GetUIntLength(m_pReader, pos, len); ++ long long total, avail; + +- if (result < 0) //error +- return static_cast(result); ++ long status = m_pReader->Length(&total, &avail); + +- if (result > 0) //weird +- return E_BUFFER_NOT_FULL; ++ if (status < 0) // error ++ return status; + +- if ((segment_stop >= 0) && ((pos + len) > segment_stop)) +- return E_FILE_FORMAT_INVALID; ++ assert((total < 0) || (avail <= total)); + +- if ((pos + len) > avail) +- return E_BUFFER_NOT_FULL; ++ const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; + +- const long long idpos = pos; //absolute +- const long long idoff = pos - m_start; //relative ++ // interrogate curr cluster + +- const long long id = ReadUInt(m_pReader, idpos, len); //absolute ++ pos = pCurr->m_element_start; + +- if (id < 0) //error +- return static_cast(id); ++ if (pCurr->m_element_size >= 0) ++ pos += pCurr->m_element_size; ++ else { ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; ++ } + +- if (id == 0) //weird +- return -1; //generic error ++ long long result = GetUIntLength(m_pReader, pos, len); + +- pos += len; //consume ID ++ if (result < 0) // error ++ return static_cast(result); + +- //Read Size ++ if (result > 0) // weird ++ return E_BUFFER_NOT_FULL; + +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } ++ if ((segment_stop >= 0) && ((pos + len) > segment_stop)) ++ return E_FILE_FORMAT_INVALID; + +- result = GetUIntLength(m_pReader, pos, len); ++ if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; + +- if (result < 0) //error +- return static_cast(result); ++ const long long id = ReadUInt(m_pReader, pos, len); + +- if (result > 0) //weird +- return E_BUFFER_NOT_FULL; ++ if (id != 0x0F43B675) // weird: not Cluster ID ++ return -1; + +- if ((segment_stop >= 0) && ((pos + len) > segment_stop)) +- return E_FILE_FORMAT_INVALID; ++ pos += len; // consume ID + +- if ((pos + len) > avail) +- return E_BUFFER_NOT_FULL; ++ // Read Size + +- const long long size = ReadUInt(m_pReader, pos, len); ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; ++ } + +- if (size < 0) //error +- return static_cast(size); ++ result = GetUIntLength(m_pReader, pos, len); + +- pos += len; //consume length of size of element ++ if (result < 0) // error ++ return static_cast(result); + +- //Pos now points to start of payload ++ if (result > 0) // weird ++ return E_BUFFER_NOT_FULL; + +- if (size == 0) //weird +- continue; ++ if ((segment_stop >= 0) && ((pos + len) > segment_stop)) ++ return E_FILE_FORMAT_INVALID; + +- const long long unknown_size = (1LL << (7 * len)) - 1; ++ if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; + +- if ((segment_stop >= 0) && +- (size != unknown_size) && +- ((pos + size) > segment_stop)) +- { +- return E_FILE_FORMAT_INVALID; +- } ++ const long long size = ReadUInt(m_pReader, pos, len); + +- if (id == 0x0C53BB6B) //Cues ID +- { +- if (size == unknown_size) +- return E_FILE_FORMAT_INVALID; ++ if (size < 0) // error ++ return static_cast(size); + +- const long long element_stop = pos + size; ++ pos += len; // consume size field + +- if ((segment_stop >= 0) && (element_stop > segment_stop)) +- return E_FILE_FORMAT_INVALID; ++ const long long unknown_size = (1LL << (7 * len)) - 1; + +- const long long element_start = idpos; +- const long long element_size = element_stop - element_start; ++ if (size == unknown_size) // TODO: should never happen ++ return E_FILE_FORMAT_INVALID; // TODO: resolve this + +- if (m_pCues == NULL) +- { +- m_pCues = new Cues(this, +- pos, +- size, +- element_start, +- element_size); +- assert(m_pCues); //TODO +- } ++ // assert((pCurr->m_size <= 0) || (pCurr->m_size == size)); + +- pos += size; //consume payload +- assert((segment_stop < 0) || (pos <= segment_stop)); ++ if ((segment_stop >= 0) && ((pos + size) > segment_stop)) ++ return E_FILE_FORMAT_INVALID; + +- continue; +- } ++ // Pos now points to start of payload + +- if (id != 0x0F43B675) //not a Cluster ID +- { +- if (size == unknown_size) +- return E_FILE_FORMAT_INVALID; ++ pos += size; // consume payload (that is, the current cluster) ++ assert((segment_stop < 0) || (pos <= segment_stop)); + +- pos += size; //consume payload +- assert((segment_stop < 0) || (pos <= segment_stop)); ++ // By consuming the payload, we are assuming that the curr ++ // cluster isn't interesting. That is, we don't bother checking ++ // whether the payload of the curr cluster is less than what ++ // happens to be available (obtained via IMkvReader::Length). ++ // Presumably the caller has already dispensed with the current ++ // cluster, and really does want the next cluster. ++ } + +- continue; +- } ++ // pos now points to just beyond the last fully-loaded cluster + +-#if 0 //this is commented-out to support incremental cluster parsing ++ for (;;) { ++ const long status = DoParseNext(pResult, pos, len); ++ ++ if (status <= 1) ++ return status; ++ } ++} ++ ++long Segment::DoParseNext(const Cluster*& pResult, long long& pos, long& len) { ++ long long total, avail; ++ ++ long status = m_pReader->Length(&total, &avail); ++ ++ if (status < 0) // error ++ return status; ++ ++ assert((total < 0) || (avail <= total)); ++ ++ const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size; ++ ++ // Parse next cluster. This is strictly a parsing activity. ++ // Creation of a new cluster object happens later, after the ++ // parsing is done. ++ ++ long long off_next = 0; ++ long long cluster_size = -1; ++ ++ for (;;) { ++ if ((total >= 0) && (pos >= total)) ++ return 1; // EOF ++ ++ if ((segment_stop >= 0) && (pos >= segment_stop)) ++ return 1; // EOF ++ ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; ++ } ++ ++ long long result = GetUIntLength(m_pReader, pos, len); ++ ++ if (result < 0) // error ++ return static_cast(result); ++ ++ if (result > 0) // weird ++ return E_BUFFER_NOT_FULL; ++ ++ if ((segment_stop >= 0) && ((pos + len) > segment_stop)) ++ return E_FILE_FORMAT_INVALID; ++ ++ if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; ++ ++ const long long idpos = pos; // absolute ++ const long long idoff = pos - m_start; // relative ++ ++ const long long id = ReadUInt(m_pReader, idpos, len); // absolute ++ ++ if (id < 0) // error ++ return static_cast(id); ++ ++ if (id == 0) // weird ++ return -1; // generic error ++ ++ pos += len; // consume ID ++ ++ // Read Size ++ ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; ++ } ++ ++ result = GetUIntLength(m_pReader, pos, len); ++ ++ if (result < 0) // error ++ return static_cast(result); ++ ++ if (result > 0) // weird ++ return E_BUFFER_NOT_FULL; ++ ++ if ((segment_stop >= 0) && ((pos + len) > segment_stop)) ++ return E_FILE_FORMAT_INVALID; ++ ++ if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; ++ ++ const long long size = ReadUInt(m_pReader, pos, len); ++ ++ if (size < 0) // error ++ return static_cast(size); ++ ++ pos += len; // consume length of size of element ++ ++ // Pos now points to start of payload ++ ++ if (size == 0) // weird ++ continue; ++ ++ const long long unknown_size = (1LL << (7 * len)) - 1; ++ ++ if ((segment_stop >= 0) && (size != unknown_size) && ++ ((pos + size) > segment_stop)) { ++ return E_FILE_FORMAT_INVALID; ++ } ++ ++ if (id == 0x0C53BB6B) { // Cues ID ++ if (size == unknown_size) ++ return E_FILE_FORMAT_INVALID; ++ ++ const long long element_stop = pos + size; ++ ++ if ((segment_stop >= 0) && (element_stop > segment_stop)) ++ return E_FILE_FORMAT_INVALID; ++ ++ const long long element_start = idpos; ++ const long long element_size = element_stop - element_start; ++ ++ if (m_pCues == NULL) { ++ m_pCues = new Cues(this, pos, size, element_start, element_size); ++ assert(m_pCues); // TODO ++ } ++ ++ pos += size; // consume payload ++ assert((segment_stop < 0) || (pos <= segment_stop)); ++ ++ continue; ++ } ++ ++ if (id != 0x0F43B675) { // not a Cluster ID ++ if (size == unknown_size) ++ return E_FILE_FORMAT_INVALID; ++ ++ pos += size; // consume payload ++ assert((segment_stop < 0) || (pos <= segment_stop)); ++ ++ continue; ++ } ++ ++#if 0 // this is commented-out to support incremental cluster parsing + len = static_cast(size); + + if (element_stop > avail) + return E_BUFFER_NOT_FULL; + #endif + +- //We have a cluster. ++ // We have a cluster. + +- off_next = idoff; ++ off_next = idoff; + +- if (size != unknown_size) +- cluster_size = size; ++ if (size != unknown_size) ++ cluster_size = size; + ++ break; ++ } ++ ++ assert(off_next > 0); // have cluster ++ ++ // We have parsed the next cluster. ++ // We have not created a cluster object yet. What we need ++ // to do now is determine whether it has already be preloaded ++ //(in which case, an object for this cluster has already been ++ // created), and if not, create a new cluster object. ++ ++ Cluster** const ii = m_clusters + m_clusterCount; ++ Cluster** i = ii; ++ ++ Cluster** const jj = ii + m_clusterPreloadCount; ++ Cluster** j = jj; ++ ++ while (i < j) { ++ // INVARIANT: ++ //[0, i) < pos_next ++ //[i, j) ? ++ //[j, jj) > pos_next ++ ++ Cluster** const k = i + (j - i) / 2; ++ assert(k < jj); ++ ++ const Cluster* const pNext = *k; ++ assert(pNext); ++ assert(pNext->m_index < 0); ++ ++ pos = pNext->GetPosition(); ++ assert(pos >= 0); ++ ++ if (pos < off_next) ++ i = k + 1; ++ else if (pos > off_next) ++ j = k; ++ else { ++ pResult = pNext; ++ return 0; // success ++ } ++ } ++ ++ assert(i == j); ++ ++ long long pos_; ++ long len_; ++ ++ status = Cluster::HasBlockEntries(this, off_next, pos_, len_); ++ ++ if (status < 0) { // error or underflow ++ pos = pos_; ++ len = len_; ++ ++ return status; ++ } ++ ++ if (status > 0) { // means ""found at least one block entry"" ++ Cluster* const pNext = Cluster::Create(this, ++ -1, // preloaded ++ off_next); ++ // element_size); ++ assert(pNext); ++ ++ const ptrdiff_t idx_next = i - m_clusters; // insertion position ++ ++ PreloadCluster(pNext, idx_next); ++ assert(m_clusters); ++ assert(idx_next < m_clusterSize); ++ assert(m_clusters[idx_next] == pNext); ++ ++ pResult = pNext; ++ return 0; // success ++ } ++ ++ // status == 0 means ""no block entries found"" ++ ++ if (cluster_size < 0) { // unknown size ++ const long long payload_pos = pos; // absolute pos of cluster payload ++ ++ for (;;) { // determine cluster size ++ if ((total >= 0) && (pos >= total)) + break; +- } + +- assert(off_next > 0); //have cluster ++ if ((segment_stop >= 0) && (pos >= segment_stop)) ++ break; // no more clusters + +- //We have parsed the next cluster. +- //We have not created a cluster object yet. What we need +- //to do now is determine whether it has already be preloaded +- //(in which case, an object for this cluster has already been +- //created), and if not, create a new cluster object. ++ // Read ID + +- Cluster** const ii = m_clusters + m_clusterCount; +- Cluster** i = ii; ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; ++ } + +- Cluster** const jj = ii + m_clusterPreloadCount; +- Cluster** j = jj; ++ long long result = GetUIntLength(m_pReader, pos, len); + +- while (i < j) +- { +- //INVARIANT: +- //[0, i) < pos_next +- //[i, j) ? +- //[j, jj) > pos_next ++ if (result < 0) // error ++ return static_cast(result); + +- Cluster** const k = i + (j - i) / 2; +- assert(k < jj); ++ if (result > 0) // weird ++ return E_BUFFER_NOT_FULL; + +- const Cluster* const pNext = *k; +- assert(pNext); +- assert(pNext->m_index < 0); ++ if ((segment_stop >= 0) && ((pos + len) > segment_stop)) ++ return E_FILE_FORMAT_INVALID; + +- pos = pNext->GetPosition(); +- assert(pos >= 0); ++ if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; + +- if (pos < off_next) +- i = k + 1; +- else if (pos > off_next) +- j = k; +- else +- { +- pResult = pNext; +- return 0; //success +- } +- } ++ const long long idpos = pos; ++ const long long id = ReadUInt(m_pReader, idpos, len); + +- assert(i == j); ++ if (id < 0) // error (or underflow) ++ return static_cast(id); + +- long long pos_; +- long len_; ++ // This is the distinguished set of ID's we use to determine ++ // that we have exhausted the sub-element's inside the cluster ++ // whose ID we parsed earlier. + +- status = Cluster::HasBlockEntries(this, off_next, pos_, len_); ++ if (id == 0x0F43B675) // Cluster ID ++ break; + +- if (status < 0) //error or underflow +- { +- pos = pos_; +- len = len_; ++ if (id == 0x0C53BB6B) // Cues ID ++ break; + +- return status; +- } ++ pos += len; // consume ID (of sub-element) + +- if (status > 0) //means ""found at least one block entry"" +- { +- Cluster* const pNext = Cluster::Create(this, +- -1, //preloaded +- off_next); +- //element_size); +- assert(pNext); ++ // Read Size + +- const ptrdiff_t idx_next = i - m_clusters; //insertion position ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; ++ } + +- PreloadCluster(pNext, idx_next); +- assert(m_clusters); +- assert(idx_next < m_clusterSize); +- assert(m_clusters[idx_next] == pNext); ++ result = GetUIntLength(m_pReader, pos, len); + +- pResult = pNext; +- return 0; //success +- } ++ if (result < 0) // error ++ return static_cast(result); + +- //status == 0 means ""no block entries found"" ++ if (result > 0) // weird ++ return E_BUFFER_NOT_FULL; + +- if (cluster_size < 0) //unknown size +- { +- const long long payload_pos = pos; //absolute pos of cluster payload ++ if ((segment_stop >= 0) && ((pos + len) > segment_stop)) ++ return E_FILE_FORMAT_INVALID; + +- for (;;) //determine cluster size +- { +- if ((total >= 0) && (pos >= total)) +- break; ++ if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; + +- if ((segment_stop >= 0) && (pos >= segment_stop)) +- break; //no more clusters ++ const long long size = ReadUInt(m_pReader, pos, len); + +- //Read ID ++ if (size < 0) // error ++ return static_cast(size); + +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } ++ pos += len; // consume size field of element + +- long long result = GetUIntLength(m_pReader, pos, len); ++ // pos now points to start of sub-element's payload + +- if (result < 0) //error +- return static_cast(result); ++ if (size == 0) // weird ++ continue; + +- if (result > 0) //weird +- return E_BUFFER_NOT_FULL; ++ const long long unknown_size = (1LL << (7 * len)) - 1; + +- if ((segment_stop >= 0) && ((pos + len) > segment_stop)) +- return E_FILE_FORMAT_INVALID; ++ if (size == unknown_size) ++ return E_FILE_FORMAT_INVALID; // not allowed for sub-elements + +- if ((pos + len) > avail) +- return E_BUFFER_NOT_FULL; ++ if ((segment_stop >= 0) && ((pos + size) > segment_stop)) // weird ++ return E_FILE_FORMAT_INVALID; + +- const long long idpos = pos; +- const long long id = ReadUInt(m_pReader, idpos, len); ++ pos += size; // consume payload of sub-element ++ assert((segment_stop < 0) || (pos <= segment_stop)); ++ } // determine cluster size + +- if (id < 0) //error (or underflow) +- return static_cast(id); ++ cluster_size = pos - payload_pos; ++ assert(cluster_size >= 0); // TODO: handle cluster_size = 0 + +- //This is the distinguished set of ID's we use to determine +- //that we have exhausted the sub-element's inside the cluster +- //whose ID we parsed earlier. ++ pos = payload_pos; // reset and re-parse original cluster ++ } + +- if (id == 0x0F43B675) //Cluster ID +- break; ++ pos += cluster_size; // consume payload ++ assert((segment_stop < 0) || (pos <= segment_stop)); + +- if (id == 0x0C53BB6B) //Cues ID +- break; +- +- pos += len; //consume ID (of sub-element) +- +- //Read Size +- +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } +- +- result = GetUIntLength(m_pReader, pos, len); +- +- if (result < 0) //error +- return static_cast(result); +- +- if (result > 0) //weird +- return E_BUFFER_NOT_FULL; +- +- if ((segment_stop >= 0) && ((pos + len) > segment_stop)) +- return E_FILE_FORMAT_INVALID; +- +- if ((pos + len) > avail) +- return E_BUFFER_NOT_FULL; +- +- const long long size = ReadUInt(m_pReader, pos, len); +- +- if (size < 0) //error +- return static_cast(size); +- +- pos += len; //consume size field of element +- +- //pos now points to start of sub-element's payload +- +- if (size == 0) //weird +- continue; +- +- const long long unknown_size = (1LL << (7 * len)) - 1; +- +- if (size == unknown_size) +- return E_FILE_FORMAT_INVALID; //not allowed for sub-elements +- +- if ((segment_stop >= 0) && ((pos + size) > segment_stop)) //weird +- return E_FILE_FORMAT_INVALID; +- +- pos += size; //consume payload of sub-element +- assert((segment_stop < 0) || (pos <= segment_stop)); +- } //determine cluster size +- +- cluster_size = pos - payload_pos; +- assert(cluster_size >= 0); //TODO: handle cluster_size = 0 +- +- pos = payload_pos; //reset and re-parse original cluster +- } +- +- pos += cluster_size; //consume payload +- assert((segment_stop < 0) || (pos <= segment_stop)); +- +- return 2; //try to find a cluster that follows next ++ return 2; // try to find a cluster that follows next + } + ++const Cluster* Segment::FindCluster(long long time_ns) const { ++ if ((m_clusters == NULL) || (m_clusterCount <= 0)) ++ return &m_eos; + +-const Cluster* Segment::FindCluster(long long time_ns) const +-{ +- if ((m_clusters == NULL) || (m_clusterCount <= 0)) +- return &m_eos; ++ { ++ Cluster* const pCluster = m_clusters[0]; ++ assert(pCluster); ++ assert(pCluster->m_index == 0); + +- { +- Cluster* const pCluster = m_clusters[0]; +- assert(pCluster); +- assert(pCluster->m_index == 0); ++ if (time_ns <= pCluster->GetTime()) ++ return pCluster; ++ } + +- if (time_ns <= pCluster->GetTime()) +- return pCluster; +- } ++ // Binary search of cluster array + +- //Binary search of cluster array ++ long i = 0; ++ long j = m_clusterCount; + +- long i = 0; +- long j = m_clusterCount; ++ while (i < j) { ++ // INVARIANT: ++ //[0, i) <= time_ns ++ //[i, j) ? ++ //[j, m_clusterCount) > time_ns + +- while (i < j) +- { +- //INVARIANT: +- //[0, i) <= time_ns +- //[i, j) ? +- //[j, m_clusterCount) > time_ns +- +- const long k = i + (j - i) / 2; +- assert(k < m_clusterCount); +- +- Cluster* const pCluster = m_clusters[k]; +- assert(pCluster); +- assert(pCluster->m_index == k); +- +- const long long t = pCluster->GetTime(); +- +- if (t <= time_ns) +- i = k + 1; +- else +- j = k; +- +- assert(i <= j); +- } +- +- assert(i == j); +- assert(i > 0); +- assert(i <= m_clusterCount); +- +- const long k = i - 1; ++ const long k = i + (j - i) / 2; ++ assert(k < m_clusterCount); + + Cluster* const pCluster = m_clusters[k]; + assert(pCluster); + assert(pCluster->m_index == k); +- assert(pCluster->GetTime() <= time_ns); + +- return pCluster; ++ const long long t = pCluster->GetTime(); ++ ++ if (t <= time_ns) ++ i = k + 1; ++ else ++ j = k; ++ ++ assert(i <= j); ++ } ++ ++ assert(i == j); ++ assert(i > 0); ++ assert(i <= m_clusterCount); ++ ++ const long k = i - 1; ++ ++ Cluster* const pCluster = m_clusters[k]; ++ assert(pCluster); ++ assert(pCluster->m_index == k); ++ assert(pCluster->GetTime() <= time_ns); ++ ++ return pCluster; + } + +- + #if 0 + const BlockEntry* Segment::Seek( + long long time_ns, +@@ -4059,8 +3674,7 @@ + + + Cluster** const j = i + m_clusterCount; + +- if (pTrack->GetType() == 2) //audio +- { ++ if (pTrack->GetType() == 2) { //audio + //TODO: we could decide to use cues for this, as we do for video. + //But we only use it for video because looking around for a keyframe + //can get expensive. Audio doesn't require anything special so a +@@ -4179,7 +3793,6 @@ + + } + #endif + +- + #if 0 + bool Segment::SearchCues( + long long time_ns, +@@ -4210,845 +3823,593 @@ + + } + #endif + ++const Tracks* Segment::GetTracks() const { return m_pTracks; } + +-const Tracks* Segment::GetTracks() const +-{ +- return m_pTracks; ++const SegmentInfo* Segment::GetInfo() const { return m_pInfo; } ++ ++const Cues* Segment::GetCues() const { return m_pCues; } ++ ++const Chapters* Segment::GetChapters() const { return m_pChapters; } ++ ++const SeekHead* Segment::GetSeekHead() const { return m_pSeekHead; } ++ ++long long Segment::GetDuration() const { ++ assert(m_pInfo); ++ return m_pInfo->GetDuration(); + } + ++Chapters::Chapters(Segment* pSegment, long long payload_start, ++ long long payload_size, long long element_start, ++ long long element_size) ++ : m_pSegment(pSegment), ++ m_start(payload_start), ++ m_size(payload_size), ++ m_element_start(element_start), ++ m_element_size(element_size), ++ m_editions(NULL), ++ m_editions_size(0), ++ m_editions_count(0) {} + +-const SegmentInfo* Segment::GetInfo() const +-{ +- return m_pInfo; ++Chapters::~Chapters() { ++ while (m_editions_count > 0) { ++ Edition& e = m_editions[--m_editions_count]; ++ e.Clear(); ++ } + } + ++long Chapters::Parse() { ++ IMkvReader* const pReader = m_pSegment->m_pReader; + +-const Cues* Segment::GetCues() const +-{ +- return m_pCues; +-} ++ long long pos = m_start; // payload start ++ const long long stop = pos + m_size; // payload stop + ++ while (pos < stop) { ++ long long id, size; + +-const Chapters* Segment::GetChapters() const +-{ +- return m_pChapters; +-} ++ long status = ParseElementHeader(pReader, pos, stop, id, size); + ++ if (status < 0) // error ++ return status; + +-const SeekHead* Segment::GetSeekHead() const +-{ +- return m_pSeekHead; +-} ++ if (size == 0) // weird ++ continue; + ++ if (id == 0x05B9) { // EditionEntry ID ++ status = ParseEdition(pos, size); + +-long long Segment::GetDuration() const +-{ +- assert(m_pInfo); +- return m_pInfo->GetDuration(); +-} +- +- +-Chapters::Chapters( +- Segment* pSegment, +- long long payload_start, +- long long payload_size, +- long long element_start, +- long long element_size) : +- m_pSegment(pSegment), +- m_start(payload_start), +- m_size(payload_size), +- m_element_start(element_start), +- m_element_size(element_size), +- m_editions(NULL), +- m_editions_size(0), +- m_editions_count(0) +-{ +-} +- +- +-Chapters::~Chapters() +-{ +- while (m_editions_count > 0) +- { +- Edition& e = m_editions[--m_editions_count]; +- e.Clear(); +- } +-} +- +- +-long Chapters::Parse() +-{ +- IMkvReader* const pReader = m_pSegment->m_pReader; +- +- long long pos = m_start; // payload start +- const long long stop = pos + m_size; // payload stop +- +- while (pos < stop) +- { +- long long id, size; +- +- long status = ParseElementHeader( +- pReader, +- pos, +- stop, +- id, +- size); +- +- if (status < 0) // error +- return status; +- +- if (size == 0) // weird +- continue; +- +- if (id == 0x05B9) // EditionEntry ID +- { +- status = ParseEdition(pos, size); +- +- if (status < 0) // error +- return status; +- } +- +- pos += size; +- assert(pos <= stop); ++ if (status < 0) // error ++ return status; + } + +- assert(pos == stop); +- return 0; ++ pos += size; ++ assert(pos <= stop); ++ } ++ ++ assert(pos == stop); ++ return 0; + } + ++int Chapters::GetEditionCount() const { return m_editions_count; } + +-int Chapters::GetEditionCount() const +-{ +- return m_editions_count; ++const Chapters::Edition* Chapters::GetEdition(int idx) const { ++ if (idx < 0) ++ return NULL; ++ ++ if (idx >= m_editions_count) ++ return NULL; ++ ++ return m_editions + idx; + } + ++bool Chapters::ExpandEditionsArray() { ++ if (m_editions_size > m_editions_count) ++ return true; // nothing else to do + +-const Chapters::Edition* Chapters::GetEdition(int idx) const +-{ +- if (idx < 0) +- return NULL; ++ const int size = (m_editions_size == 0) ? 1 : 2 * m_editions_size; + +- if (idx >= m_editions_count) +- return NULL; ++ Edition* const editions = new (std::nothrow) Edition[size]; + +- return m_editions + idx; ++ if (editions == NULL) ++ return false; ++ ++ for (int idx = 0; idx < m_editions_count; ++idx) { ++ m_editions[idx].ShallowCopy(editions[idx]); ++ } ++ ++ delete[] m_editions; ++ m_editions = editions; ++ ++ m_editions_size = size; ++ return true; + } + ++long Chapters::ParseEdition(long long pos, long long size) { ++ if (!ExpandEditionsArray()) ++ return -1; + +-bool Chapters::ExpandEditionsArray() +-{ +- if (m_editions_size > m_editions_count) +- return true; // nothing else to do ++ Edition& e = m_editions[m_editions_count++]; ++ e.Init(); + +- const int size = (m_editions_size == 0) ? 1 : 2 * m_editions_size; ++ return e.Parse(m_pSegment->m_pReader, pos, size); ++} + +- Edition* const editions = new (std::nothrow) Edition[size]; ++Chapters::Edition::Edition() {} + +- if (editions == NULL) +- return false; ++Chapters::Edition::~Edition() {} + +- for (int idx = 0; idx < m_editions_count; ++idx) +- { +- m_editions[idx].ShallowCopy(editions[idx]); ++int Chapters::Edition::GetAtomCount() const { return m_atoms_count; } ++ ++const Chapters::Atom* Chapters::Edition::GetAtom(int index) const { ++ if (index < 0) ++ return NULL; ++ ++ if (index >= m_atoms_count) ++ return NULL; ++ ++ return m_atoms + index; ++} ++ ++void Chapters::Edition::Init() { ++ m_atoms = NULL; ++ m_atoms_size = 0; ++ m_atoms_count = 0; ++} ++ ++void Chapters::Edition::ShallowCopy(Edition& rhs) const { ++ rhs.m_atoms = m_atoms; ++ rhs.m_atoms_size = m_atoms_size; ++ rhs.m_atoms_count = m_atoms_count; ++} ++ ++void Chapters::Edition::Clear() { ++ while (m_atoms_count > 0) { ++ Atom& a = m_atoms[--m_atoms_count]; ++ a.Clear(); ++ } ++ ++ delete[] m_atoms; ++ m_atoms = NULL; ++ ++ m_atoms_size = 0; ++} ++ ++long Chapters::Edition::Parse(IMkvReader* pReader, long long pos, ++ long long size) { ++ const long long stop = pos + size; ++ ++ while (pos < stop) { ++ long long id, size; ++ ++ long status = ParseElementHeader(pReader, pos, stop, id, size); ++ ++ if (status < 0) // error ++ return status; ++ ++ if (size == 0) // weird ++ continue; ++ ++ if (id == 0x36) { // Atom ID ++ status = ParseAtom(pReader, pos, size); ++ ++ if (status < 0) // error ++ return status; + } + +- delete[] m_editions; +- m_editions = editions; ++ pos += size; ++ assert(pos <= stop); ++ } + +- m_editions_size = size; +- return true; ++ assert(pos == stop); ++ return 0; + } + ++long Chapters::Edition::ParseAtom(IMkvReader* pReader, long long pos, ++ long long size) { ++ if (!ExpandAtomsArray()) ++ return -1; + +-long Chapters::ParseEdition( +- long long pos, +- long long size) +-{ +- if (!ExpandEditionsArray()) +- return -1; ++ Atom& a = m_atoms[m_atoms_count++]; ++ a.Init(); + +- Edition& e = m_editions[m_editions_count++]; +- e.Init(); +- +- return e.Parse(m_pSegment->m_pReader, pos, size); ++ return a.Parse(pReader, pos, size); + } + ++bool Chapters::Edition::ExpandAtomsArray() { ++ if (m_atoms_size > m_atoms_count) ++ return true; // nothing else to do + +-Chapters::Edition::Edition() +-{ ++ const int size = (m_atoms_size == 0) ? 1 : 2 * m_atoms_size; ++ ++ Atom* const atoms = new (std::nothrow) Atom[size]; ++ ++ if (atoms == NULL) ++ return false; ++ ++ for (int idx = 0; idx < m_atoms_count; ++idx) { ++ m_atoms[idx].ShallowCopy(atoms[idx]); ++ } ++ ++ delete[] m_atoms; ++ m_atoms = atoms; ++ ++ m_atoms_size = size; ++ return true; + } + ++Chapters::Atom::Atom() {} + +-Chapters::Edition::~Edition() +-{ ++Chapters::Atom::~Atom() {} ++ ++unsigned long long Chapters::Atom::GetUID() const { return m_uid; } ++ ++const char* Chapters::Atom::GetStringUID() const { return m_string_uid; } ++ ++long long Chapters::Atom::GetStartTimecode() const { return m_start_timecode; } ++ ++long long Chapters::Atom::GetStopTimecode() const { return m_stop_timecode; } ++ ++long long Chapters::Atom::GetStartTime(const Chapters* pChapters) const { ++ return GetTime(pChapters, m_start_timecode); + } + +- +-int Chapters::Edition::GetAtomCount() const +-{ +- return m_atoms_count; ++long long Chapters::Atom::GetStopTime(const Chapters* pChapters) const { ++ return GetTime(pChapters, m_stop_timecode); + } + ++int Chapters::Atom::GetDisplayCount() const { return m_displays_count; } + +-const Chapters::Atom* Chapters::Edition::GetAtom(int index) const +-{ +- if (index < 0) +- return NULL; ++const Chapters::Display* Chapters::Atom::GetDisplay(int index) const { ++ if (index < 0) ++ return NULL; + +- if (index >= m_atoms_count) +- return NULL; ++ if (index >= m_displays_count) ++ return NULL; + +- return m_atoms + index; ++ return m_displays + index; + } + ++void Chapters::Atom::Init() { ++ m_string_uid = NULL; ++ m_uid = 0; ++ m_start_timecode = -1; ++ m_stop_timecode = -1; + +-void Chapters::Edition::Init() +-{ +- m_atoms = NULL; +- m_atoms_size = 0; +- m_atoms_count = 0; ++ m_displays = NULL; ++ m_displays_size = 0; ++ m_displays_count = 0; + } + ++void Chapters::Atom::ShallowCopy(Atom& rhs) const { ++ rhs.m_string_uid = m_string_uid; ++ rhs.m_uid = m_uid; ++ rhs.m_start_timecode = m_start_timecode; ++ rhs.m_stop_timecode = m_stop_timecode; + +-void Chapters::Edition::ShallowCopy(Edition& rhs) const +-{ +- rhs.m_atoms = m_atoms; +- rhs.m_atoms_size = m_atoms_size; +- rhs.m_atoms_count = m_atoms_count; ++ rhs.m_displays = m_displays; ++ rhs.m_displays_size = m_displays_size; ++ rhs.m_displays_count = m_displays_count; + } + ++void Chapters::Atom::Clear() { ++ delete[] m_string_uid; ++ m_string_uid = NULL; + +-void Chapters::Edition::Clear() +-{ +- while (m_atoms_count > 0) +- { +- Atom& a = m_atoms[--m_atoms_count]; +- a.Clear(); ++ while (m_displays_count > 0) { ++ Display& d = m_displays[--m_displays_count]; ++ d.Clear(); ++ } ++ ++ delete[] m_displays; ++ m_displays = NULL; ++ ++ m_displays_size = 0; ++} ++ ++long Chapters::Atom::Parse(IMkvReader* pReader, long long pos, long long size) { ++ const long long stop = pos + size; ++ ++ while (pos < stop) { ++ long long id, size; ++ ++ long status = ParseElementHeader(pReader, pos, stop, id, size); ++ ++ if (status < 0) // error ++ return status; ++ ++ if (size == 0) // weird ++ continue; ++ ++ if (id == 0x00) { // Display ID ++ status = ParseDisplay(pReader, pos, size); ++ ++ if (status < 0) // error ++ return status; ++ } else if (id == 0x1654) { // StringUID ID ++ status = UnserializeString(pReader, pos, size, m_string_uid); ++ ++ if (status < 0) // error ++ return status; ++ } else if (id == 0x33C4) { // UID ID ++ long long val; ++ status = UnserializeInt(pReader, pos, size, val); ++ ++ if (val < 0) // error ++ return status; ++ ++ m_uid = static_cast(val); ++ } else if (id == 0x11) { // TimeStart ID ++ const long long val = UnserializeUInt(pReader, pos, size); ++ ++ if (val < 0) // error ++ return static_cast(val); ++ ++ m_start_timecode = val; ++ } else if (id == 0x12) { // TimeEnd ID ++ const long long val = UnserializeUInt(pReader, pos, size); ++ ++ if (val < 0) // error ++ return static_cast(val); ++ ++ m_stop_timecode = val; + } + +- delete[] m_atoms; +- m_atoms = NULL; ++ pos += size; ++ assert(pos <= stop); ++ } + +- m_atoms_size = 0; ++ assert(pos == stop); ++ return 0; + } + ++long long Chapters::Atom::GetTime(const Chapters* pChapters, ++ long long timecode) { ++ if (pChapters == NULL) ++ return -1; + +-long Chapters::Edition::Parse( +- IMkvReader* pReader, +- long long pos, +- long long size) +-{ +- const long long stop = pos + size; ++ Segment* const pSegment = pChapters->m_pSegment; + +- while (pos < stop) +- { +- long long id, size; ++ if (pSegment == NULL) // weird ++ return -1; + +- long status = ParseElementHeader( +- pReader, +- pos, +- stop, +- id, +- size); ++ const SegmentInfo* const pInfo = pSegment->GetInfo(); + +- if (status < 0) // error +- return status; ++ if (pInfo == NULL) ++ return -1; + +- if (size == 0) // weird +- continue; ++ const long long timecode_scale = pInfo->GetTimeCodeScale(); + +- if (id == 0x36) // Atom ID +- { +- status = ParseAtom(pReader, pos, size); ++ if (timecode_scale < 1) // weird ++ return -1; + +- if (status < 0) // error +- return status; +- } ++ if (timecode < 0) ++ return -1; + +- pos += size; +- assert(pos <= stop); ++ const long long result = timecode_scale * timecode; ++ ++ return result; ++} ++ ++long Chapters::Atom::ParseDisplay(IMkvReader* pReader, long long pos, ++ long long size) { ++ if (!ExpandDisplaysArray()) ++ return -1; ++ ++ Display& d = m_displays[m_displays_count++]; ++ d.Init(); ++ ++ return d.Parse(pReader, pos, size); ++} ++ ++bool Chapters::Atom::ExpandDisplaysArray() { ++ if (m_displays_size > m_displays_count) ++ return true; // nothing else to do ++ ++ const int size = (m_displays_size == 0) ? 1 : 2 * m_displays_size; ++ ++ Display* const displays = new (std::nothrow) Display[size]; ++ ++ if (displays == NULL) ++ return false; ++ ++ for (int idx = 0; idx < m_displays_count; ++idx) { ++ m_displays[idx].ShallowCopy(displays[idx]); ++ } ++ ++ delete[] m_displays; ++ m_displays = displays; ++ ++ m_displays_size = size; ++ return true; ++} ++ ++Chapters::Display::Display() {} ++ ++Chapters::Display::~Display() {} ++ ++const char* Chapters::Display::GetString() const { return m_string; } ++ ++const char* Chapters::Display::GetLanguage() const { return m_language; } ++ ++const char* Chapters::Display::GetCountry() const { return m_country; } ++ ++void Chapters::Display::Init() { ++ m_string = NULL; ++ m_language = NULL; ++ m_country = NULL; ++} ++ ++void Chapters::Display::ShallowCopy(Display& rhs) const { ++ rhs.m_string = m_string; ++ rhs.m_language = m_language; ++ rhs.m_country = m_country; ++} ++ ++void Chapters::Display::Clear() { ++ delete[] m_string; ++ m_string = NULL; ++ ++ delete[] m_language; ++ m_language = NULL; ++ ++ delete[] m_country; ++ m_country = NULL; ++} ++ ++long Chapters::Display::Parse(IMkvReader* pReader, long long pos, ++ long long size) { ++ const long long stop = pos + size; ++ ++ while (pos < stop) { ++ long long id, size; ++ ++ long status = ParseElementHeader(pReader, pos, stop, id, size); ++ ++ if (status < 0) // error ++ return status; ++ ++ if (size == 0) // weird ++ continue; ++ ++ if (id == 0x05) { // ChapterString ID ++ status = UnserializeString(pReader, pos, size, m_string); ++ ++ if (status) ++ return status; ++ } else if (id == 0x037C) { // ChapterLanguage ID ++ status = UnserializeString(pReader, pos, size, m_language); ++ ++ if (status) ++ return status; ++ } else if (id == 0x037E) { // ChapterCountry ID ++ status = UnserializeString(pReader, pos, size, m_country); ++ ++ if (status) ++ return status; + } + +- assert(pos == stop); +- return 0; ++ pos += size; ++ assert(pos <= stop); ++ } ++ ++ assert(pos == stop); ++ return 0; + } + ++SegmentInfo::SegmentInfo(Segment* pSegment, long long start, long long size_, ++ long long element_start, long long element_size) ++ : m_pSegment(pSegment), ++ m_start(start), ++ m_size(size_), ++ m_element_start(element_start), ++ m_element_size(element_size), ++ m_pMuxingAppAsUTF8(NULL), ++ m_pWritingAppAsUTF8(NULL), ++ m_pTitleAsUTF8(NULL) {} + +-long Chapters::Edition::ParseAtom( +- IMkvReader* pReader, +- long long pos, +- long long size) +-{ +- if (!ExpandAtomsArray()) +- return -1; ++SegmentInfo::~SegmentInfo() { ++ delete[] m_pMuxingAppAsUTF8; ++ m_pMuxingAppAsUTF8 = NULL; + +- Atom& a = m_atoms[m_atoms_count++]; +- a.Init(); ++ delete[] m_pWritingAppAsUTF8; ++ m_pWritingAppAsUTF8 = NULL; + +- return a.Parse(pReader, pos, size); ++ delete[] m_pTitleAsUTF8; ++ m_pTitleAsUTF8 = NULL; + } + ++long SegmentInfo::Parse() { ++ assert(m_pMuxingAppAsUTF8 == NULL); ++ assert(m_pWritingAppAsUTF8 == NULL); ++ assert(m_pTitleAsUTF8 == NULL); + +-bool Chapters::Edition::ExpandAtomsArray() +-{ +- if (m_atoms_size > m_atoms_count) +- return true; // nothing else to do ++ IMkvReader* const pReader = m_pSegment->m_pReader; + +- const int size = (m_atoms_size == 0) ? 1 : 2 * m_atoms_size; ++ long long pos = m_start; ++ const long long stop = m_start + m_size; + +- Atom* const atoms = new (std::nothrow) Atom[size]; ++ m_timecodeScale = 1000000; ++ m_duration = -1; + +- if (atoms == NULL) +- return false; ++ while (pos < stop) { ++ long long id, size; + +- for (int idx = 0; idx < m_atoms_count; ++idx) +- { +- m_atoms[idx].ShallowCopy(atoms[idx]); ++ const long status = ParseElementHeader(pReader, pos, stop, id, size); ++ ++ if (status < 0) // error ++ return status; ++ ++ if (id == 0x0AD7B1) { // Timecode Scale ++ m_timecodeScale = UnserializeUInt(pReader, pos, size); ++ ++ if (m_timecodeScale <= 0) ++ return E_FILE_FORMAT_INVALID; ++ } else if (id == 0x0489) { // Segment duration ++ const long status = UnserializeFloat(pReader, pos, size, m_duration); ++ ++ if (status < 0) ++ return status; ++ ++ if (m_duration < 0) ++ return E_FILE_FORMAT_INVALID; ++ } else if (id == 0x0D80) { // MuxingApp ++ const long status = ++ UnserializeString(pReader, pos, size, m_pMuxingAppAsUTF8); ++ ++ if (status) ++ return status; ++ } else if (id == 0x1741) { // WritingApp ++ const long status = ++ UnserializeString(pReader, pos, size, m_pWritingAppAsUTF8); ++ ++ if (status) ++ return status; ++ } else if (id == 0x3BA9) { // Title ++ const long status = UnserializeString(pReader, pos, size, m_pTitleAsUTF8); ++ ++ if (status) ++ return status; + } + +- delete[] m_atoms; +- m_atoms = atoms; ++ pos += size; ++ assert(pos <= stop); ++ } + +- m_atoms_size = size; +- return true; ++ assert(pos == stop); ++ ++ return 0; + } + ++long long SegmentInfo::GetTimeCodeScale() const { return m_timecodeScale; } + +-Chapters::Atom::Atom() +-{ ++long long SegmentInfo::GetDuration() const { ++ if (m_duration < 0) ++ return -1; ++ ++ assert(m_timecodeScale >= 1); ++ ++ const double dd = double(m_duration) * double(m_timecodeScale); ++ const long long d = static_cast(dd); ++ ++ return d; + } + +- +-Chapters::Atom::~Atom() +-{ ++const char* SegmentInfo::GetMuxingAppAsUTF8() const { ++ return m_pMuxingAppAsUTF8; + } + +- +-unsigned long long Chapters::Atom::GetUID() const +-{ +- return m_uid; ++const char* SegmentInfo::GetWritingAppAsUTF8() const { ++ return m_pWritingAppAsUTF8; + } + +- +-const char* Chapters::Atom::GetStringUID() const +-{ +- return m_string_uid; +-} +- +- +-long long Chapters::Atom::GetStartTimecode() const +-{ +- return m_start_timecode; +-} +- +- +-long long Chapters::Atom::GetStopTimecode() const +-{ +- return m_stop_timecode; +-} +- +- +-long long Chapters::Atom::GetStartTime(const Chapters* pChapters) const +-{ +- return GetTime(pChapters, m_start_timecode); +-} +- +- +-long long Chapters::Atom::GetStopTime(const Chapters* pChapters) const +-{ +- return GetTime(pChapters, m_stop_timecode); +-} +- +- +-int Chapters::Atom::GetDisplayCount() const +-{ +- return m_displays_count; +-} +- +- +-const Chapters::Display* Chapters::Atom::GetDisplay(int index) const +-{ +- if (index < 0) +- return NULL; +- +- if (index >= m_displays_count) +- return NULL; +- +- return m_displays + index; +-} +- +- +-void Chapters::Atom::Init() +-{ +- m_string_uid = NULL; +- m_uid = 0; +- m_start_timecode = -1; +- m_stop_timecode = -1; +- +- m_displays = NULL; +- m_displays_size = 0; +- m_displays_count = 0; +-} +- +- +-void Chapters::Atom::ShallowCopy(Atom& rhs) const +-{ +- rhs.m_string_uid = m_string_uid; +- rhs.m_uid = m_uid; +- rhs.m_start_timecode = m_start_timecode; +- rhs.m_stop_timecode = m_stop_timecode; +- +- rhs.m_displays = m_displays; +- rhs.m_displays_size = m_displays_size; +- rhs.m_displays_count = m_displays_count; +-} +- +- +-void Chapters::Atom::Clear() +-{ +- delete[] m_string_uid; +- m_string_uid = NULL; +- +- while (m_displays_count > 0) +- { +- Display& d = m_displays[--m_displays_count]; +- d.Clear(); +- } +- +- delete[] m_displays; +- m_displays = NULL; +- +- m_displays_size = 0; +-} +- +- +-long Chapters::Atom::Parse( +- IMkvReader* pReader, +- long long pos, +- long long size) +-{ +- const long long stop = pos + size; +- +- while (pos < stop) +- { +- long long id, size; +- +- long status = ParseElementHeader( +- pReader, +- pos, +- stop, +- id, +- size); +- +- if (status < 0) // error +- return status; +- +- if (size == 0) // weird +- continue; +- +- if (id == 0x00) // Display ID +- { +- status = ParseDisplay(pReader, pos, size); +- +- if (status < 0) // error +- return status; +- } +- else if (id == 0x1654) // StringUID ID +- { +- status = UnserializeString(pReader, pos, size, m_string_uid); +- +- if (status < 0) // error +- return status; +- } +- else if (id == 0x33C4) // UID ID +- { +- long long val; +- status = UnserializeInt(pReader, pos, size, val); +- +- if (status < 0) // error +- return status; +- +- m_uid = val; +- } +- else if (id == 0x11) // TimeStart ID +- { +- const long long val = UnserializeUInt(pReader, pos, size); +- +- if (val < 0) // error +- return static_cast(val); +- +- m_start_timecode = val; +- } +- else if (id == 0x12) // TimeEnd ID +- { +- const long long val = UnserializeUInt(pReader, pos, size); +- +- if (val < 0) // error +- return static_cast(val); +- +- m_stop_timecode = val; +- } +- +- pos += size; +- assert(pos <= stop); +- } +- +- assert(pos == stop); +- return 0; +-} +- +- +-long long Chapters::Atom::GetTime( +- const Chapters* pChapters, +- long long timecode) +-{ +- if (pChapters == NULL) +- return -1; +- +- Segment* const pSegment = pChapters->m_pSegment; +- +- if (pSegment == NULL) // weird +- return -1; +- +- const SegmentInfo* const pInfo = pSegment->GetInfo(); +- +- if (pInfo == NULL) +- return -1; +- +- const long long timecode_scale = pInfo->GetTimeCodeScale(); +- +- if (timecode_scale < 1) // weird +- return -1; +- +- if (timecode < 0) +- return -1; +- +- const long long result = timecode_scale * timecode; +- +- return result; +-} +- +- +-long Chapters::Atom::ParseDisplay( +- IMkvReader* pReader, +- long long pos, +- long long size) +-{ +- if (!ExpandDisplaysArray()) +- return -1; +- +- Display& d = m_displays[m_displays_count++]; +- d.Init(); +- +- return d.Parse(pReader, pos, size); +-} +- +- +-bool Chapters::Atom::ExpandDisplaysArray() +-{ +- if (m_displays_size > m_displays_count) +- return true; // nothing else to do +- +- const int size = (m_displays_size == 0) ? 1 : 2 * m_displays_size; +- +- Display* const displays = new (std::nothrow) Display[size]; +- +- if (displays == NULL) +- return false; +- +- for (int idx = 0; idx < m_displays_count; ++idx) +- { +- m_displays[idx].ShallowCopy(displays[idx]); +- } +- +- delete[] m_displays; +- m_displays = displays; +- +- m_displays_size = size; +- return true; +-} +- +- +-Chapters::Display::Display() +-{ +-} +- +- +-Chapters::Display::~Display() +-{ +-} +- +- +-const char* Chapters::Display::GetString() const +-{ +- return m_string; +-} +- +- +-const char* Chapters::Display::GetLanguage() const +-{ +- return m_language; +-} +- +- +-const char* Chapters::Display::GetCountry() const +-{ +- return m_country; +-} +- +- +-void Chapters::Display::Init() +-{ +- m_string = NULL; +- m_language = NULL; +- m_country = NULL; +-} +- +- +-void Chapters::Display::ShallowCopy(Display& rhs) const +-{ +- rhs.m_string = m_string; +- rhs.m_language = m_language; +- rhs.m_country = m_country; +-} +- +- +-void Chapters::Display::Clear() +-{ +- delete[] m_string; +- m_string = NULL; +- +- delete[] m_language; +- m_language = NULL; +- +- delete[] m_country; +- m_country = NULL; +-} +- +- +-long Chapters::Display::Parse( +- IMkvReader* pReader, +- long long pos, +- long long size) +-{ +- const long long stop = pos + size; +- +- while (pos < stop) +- { +- long long id, size; +- +- long status = ParseElementHeader( +- pReader, +- pos, +- stop, +- id, +- size); +- +- if (status < 0) // error +- return status; +- +- if (size == 0) // weird +- continue; +- +- if (id == 0x05) // ChapterString ID +- { +- status = UnserializeString(pReader, pos, size, m_string); +- +- if (status) +- return status; +- } +- else if (id == 0x037C) // ChapterLanguage ID +- { +- status = UnserializeString(pReader, pos, size, m_language); +- +- if (status) +- return status; +- } +- else if (id == 0x037E) // ChapterCountry ID +- { +- status = UnserializeString(pReader, pos, size, m_country); +- +- if (status) +- return status; +- } +- +- pos += size; +- assert(pos <= stop); +- } +- +- assert(pos == stop); +- return 0; +-} +- +- +-SegmentInfo::SegmentInfo( +- Segment* pSegment, +- long long start, +- long long size_, +- long long element_start, +- long long element_size) : +- m_pSegment(pSegment), +- m_start(start), +- m_size(size_), +- m_element_start(element_start), +- m_element_size(element_size), +- m_pMuxingAppAsUTF8(NULL), +- m_pWritingAppAsUTF8(NULL), +- m_pTitleAsUTF8(NULL) +-{ +-} +- +-SegmentInfo::~SegmentInfo() +-{ +- delete[] m_pMuxingAppAsUTF8; +- m_pMuxingAppAsUTF8 = NULL; +- +- delete[] m_pWritingAppAsUTF8; +- m_pWritingAppAsUTF8 = NULL; +- +- delete[] m_pTitleAsUTF8; +- m_pTitleAsUTF8 = NULL; +-} +- +- +-long SegmentInfo::Parse() +-{ +- assert(m_pMuxingAppAsUTF8 == NULL); +- assert(m_pWritingAppAsUTF8 == NULL); +- assert(m_pTitleAsUTF8 == NULL); +- +- IMkvReader* const pReader = m_pSegment->m_pReader; +- +- long long pos = m_start; +- const long long stop = m_start + m_size; +- +- m_timecodeScale = 1000000; +- m_duration = -1; +- +- while (pos < stop) +- { +- long long id, size; +- +- const long status = ParseElementHeader( +- pReader, +- pos, +- stop, +- id, +- size); +- +- if (status < 0) //error +- return status; +- +- if (id == 0x0AD7B1) //Timecode Scale +- { +- m_timecodeScale = UnserializeUInt(pReader, pos, size); +- +- if (m_timecodeScale <= 0) +- return E_FILE_FORMAT_INVALID; +- } +- else if (id == 0x0489) //Segment duration +- { +- const long status = UnserializeFloat( +- pReader, +- pos, +- size, +- m_duration); +- +- if (status < 0) +- return status; +- +- if (m_duration < 0) +- return E_FILE_FORMAT_INVALID; +- } +- else if (id == 0x0D80) //MuxingApp +- { +- const long status = UnserializeString( +- pReader, +- pos, +- size, +- m_pMuxingAppAsUTF8); +- +- if (status) +- return status; +- } +- else if (id == 0x1741) //WritingApp +- { +- const long status = UnserializeString( +- pReader, +- pos, +- size, +- m_pWritingAppAsUTF8); +- +- if (status) +- return status; +- } +- else if (id == 0x3BA9) //Title +- { +- const long status = UnserializeString( +- pReader, +- pos, +- size, +- m_pTitleAsUTF8); +- +- if (status) +- return status; +- } +- +- pos += size; +- assert(pos <= stop); +- } +- +- assert(pos == stop); +- +- return 0; +-} +- +- +-long long SegmentInfo::GetTimeCodeScale() const +-{ +- return m_timecodeScale; +-} +- +- +-long long SegmentInfo::GetDuration() const +-{ +- if (m_duration < 0) +- return -1; +- +- assert(m_timecodeScale >= 1); +- +- const double dd = double(m_duration) * double(m_timecodeScale); +- const long long d = static_cast(dd); +- +- return d; +-} +- +-const char* SegmentInfo::GetMuxingAppAsUTF8() const +-{ +- return m_pMuxingAppAsUTF8; +-} +- +- +-const char* SegmentInfo::GetWritingAppAsUTF8() const +-{ +- return m_pWritingAppAsUTF8; +-} +- +-const char* SegmentInfo::GetTitleAsUTF8() const +-{ +- return m_pTitleAsUTF8; +-} ++const char* SegmentInfo::GetTitleAsUTF8() const { return m_pTitleAsUTF8; } + + /////////////////////////////////////////////////////////////// + // ContentEncoding element + ContentEncoding::ContentCompression::ContentCompression() +- : algo(0), +- settings(NULL), +- settings_len(0) { +-} ++ : algo(0), settings(NULL), settings_len(0) {} + + ContentEncoding::ContentCompression::~ContentCompression() { +- delete [] settings; ++ delete[] settings; + } + + ContentEncoding::ContentEncryption::ContentEncryption() +@@ -5060,13 +4421,12 @@ + + sig_key_id(NULL), + sig_key_id_len(0), + sig_algo(0), +- sig_hash_algo(0) { +-} ++ sig_hash_algo(0) {} + + ContentEncoding::ContentEncryption::~ContentEncryption() { +- delete [] key_id; +- delete [] signature; +- delete [] sig_key_id; ++ delete[] key_id; ++ delete[] signature; ++ delete[] sig_key_id; + } + + ContentEncoding::ContentEncoding() +@@ -5076,8 +4436,7 @@ + + encryption_entries_end_(NULL), + encoding_order_(0), + encoding_scope_(1), +- encoding_type_(0) { +-} ++ encoding_type_(0) {} + + ContentEncoding::~ContentEncoding() { + ContentCompression** comp_i = compression_entries_; +@@ -5088,7 +4447,7 @@ + + delete comp; + } + +- delete [] compression_entries_; ++ delete[] compression_entries_; + + ContentEncryption** enc_i = encryption_entries_; + ContentEncryption** const enc_j = encryption_entries_end_; +@@ -5098,10 +4457,9 @@ + + delete enc; + } + +- delete [] encryption_entries_; ++ delete[] encryption_entries_; + } + +- + const ContentEncoding::ContentCompression* + ContentEncoding::GetCompressionByIndex(unsigned long idx) const { + const ptrdiff_t count = compression_entries_end_ - compression_entries_; +@@ -5120,8 +4478,8 @@ + + return static_cast(count); + } + +-const ContentEncoding::ContentEncryption* +-ContentEncoding::GetEncryptionByIndex(unsigned long idx) const { ++const ContentEncoding::ContentEncryption* ContentEncoding::GetEncryptionByIndex( ++ unsigned long idx) const { + const ptrdiff_t count = encryption_entries_end_ - encryption_entries_; + assert(count >= 0); + +@@ -5139,9 +4497,7 @@ + + } + + long ContentEncoding::ParseContentEncAESSettingsEntry( +- long long start, +- long long size, +- IMkvReader* pReader, ++ long long start, long long size, IMkvReader* pReader, + ContentEncAESSettings* aes) { + assert(pReader); + assert(aes); +@@ -5151,12 +4507,8 @@ + + + while (pos < stop) { + long long id, size; +- const long status = ParseElementHeader(pReader, +- pos, +- stop, +- id, +- size); +- if (status < 0) //error ++ const long status = ParseElementHeader(pReader, pos, stop, id, size); ++ if (status < 0) // error + return status; + + if (id == 0x7E8) { +@@ -5166,15 +4518,14 @@ + + return E_FILE_FORMAT_INVALID; + } + +- pos += size; //consume payload ++ pos += size; // consume payload + assert(pos <= stop); + } + + return 0; + } + +-long ContentEncoding::ParseContentEncodingEntry(long long start, +- long long size, ++long ContentEncoding::ParseContentEncodingEntry(long long start, long long size, + IMkvReader* pReader) { + assert(pReader); + +@@ -5187,12 +4538,8 @@ + + + while (pos < stop) { + long long id, size; +- const long status = ParseElementHeader(pReader, +- pos, +- stop, +- id, +- size); +- if (status < 0) //error ++ const long status = ParseElementHeader(pReader, pos, stop, id, size); ++ if (status < 0) // error + return status; + + if (id == 0x1034) // ContentCompression ID +@@ -5201,7 +4548,7 @@ + + if (id == 0x1035) // ContentEncryption ID + ++encryption_count; + +- pos += size; //consume payload ++ pos += size; // consume payload + assert(pos <= stop); + } + +@@ -5210,7 +4557,7 @@ + + + if (compression_count > 0) { + compression_entries_ = +- new (std::nothrow) ContentCompression*[compression_count]; ++ new (std::nothrow) ContentCompression* [compression_count]; + if (!compression_entries_) + return -1; + compression_entries_end_ = compression_entries_; +@@ -5218,9 +4565,9 @@ + + + if (encryption_count > 0) { + encryption_entries_ = +- new (std::nothrow) ContentEncryption*[encryption_count]; ++ new (std::nothrow) ContentEncryption* [encryption_count]; + if (!encryption_entries_) { +- delete [] compression_entries_; ++ delete[] compression_entries_; + return -1; + } + encryption_entries_end_ = encryption_entries_; +@@ -5229,12 +4576,8 @@ + + pos = start; + while (pos < stop) { + long long id, size; +- long status = ParseElementHeader(pReader, +- pos, +- stop, +- id, +- size); +- if (status < 0) //error ++ long status = ParseElementHeader(pReader, pos, stop, id, size); ++ if (status < 0) // error + return status; + + if (id == 0x1031) { +@@ -5251,7 +4594,7 @@ + + } else if (id == 0x1034) { + // ContentCompression ID + ContentCompression* const compression = +- new (std::nothrow) ContentCompression(); ++ new (std::nothrow) ContentCompression(); + if (!compression) + return -1; + +@@ -5276,7 +4619,7 @@ + + *encryption_entries_end_++ = encryption; + } + +- pos += size; //consume payload ++ pos += size; // consume payload + assert(pos <= stop); + } + +@@ -5284,11 +4627,9 @@ + + return 0; + } + +-long ContentEncoding::ParseCompressionEntry( +- long long start, +- long long size, +- IMkvReader* pReader, +- ContentCompression* compression) { ++long ContentEncoding::ParseCompressionEntry(long long start, long long size, ++ IMkvReader* pReader, ++ ContentCompression* compression) { + assert(pReader); + assert(compression); + +@@ -5299,12 +4640,8 @@ + + + while (pos < stop) { + long long id, size; +- const long status = ParseElementHeader(pReader, +- pos, +- stop, +- id, +- size); +- if (status < 0) //error ++ const long status = ParseElementHeader(pReader, pos, stop, id, size); ++ if (status < 0) // error + return status; + + if (id == 0x254) { +@@ -5325,9 +4662,10 @@ + + if (buf == NULL) + return -1; + +- const int read_status = pReader->Read(pos, buflen, buf); ++ const int read_status = ++ pReader->Read(pos, static_cast(buflen), buf); + if (read_status) { +- delete [] buf; ++ delete[] buf; + return status; + } + +@@ -5335,7 +4673,7 @@ + + compression->settings_len = buflen; + } + +- pos += size; //consume payload ++ pos += size; // consume payload + assert(pos <= stop); + } + +@@ -5346,11 +4684,9 @@ + + return 0; + } + +-long ContentEncoding::ParseEncryptionEntry( +- long long start, +- long long size, +- IMkvReader* pReader, +- ContentEncryption* encryption) { ++long ContentEncoding::ParseEncryptionEntry(long long start, long long size, ++ IMkvReader* pReader, ++ ContentEncryption* encryption) { + assert(pReader); + assert(encryption); + +@@ -5359,12 +4695,8 @@ + + + while (pos < stop) { + long long id, size; +- const long status = ParseElementHeader(pReader, +- pos, +- stop, +- id, +- size); +- if (status < 0) //error ++ const long status = ParseElementHeader(pReader, pos, stop, id, size); ++ if (status < 0) // error + return status; + + if (id == 0x7E1) { +@@ -5374,7 +4706,7 @@ + + return E_FILE_FORMAT_INVALID; + } else if (id == 0x7E2) { + // ContentEncKeyID +- delete[] encryption->key_id; ++ delete[] encryption -> key_id; + encryption->key_id = NULL; + encryption->key_id_len = 0; + +@@ -5387,9 +4719,10 @@ + + if (buf == NULL) + return -1; + +- const int read_status = pReader->Read(pos, buflen, buf); ++ const int read_status = ++ pReader->Read(pos, static_cast(buflen), buf); + if (read_status) { +- delete [] buf; ++ delete[] buf; + return status; + } + +@@ -5397,7 +4730,7 @@ + + encryption->key_id_len = buflen; + } else if (id == 0x7E3) { + // ContentSignature +- delete[] encryption->signature; ++ delete[] encryption -> signature; + encryption->signature = NULL; + encryption->signature_len = 0; + +@@ -5410,9 +4743,10 @@ + + if (buf == NULL) + return -1; + +- const int read_status = pReader->Read(pos, buflen, buf); ++ const int read_status = ++ pReader->Read(pos, static_cast(buflen), buf); + if (read_status) { +- delete [] buf; ++ delete[] buf; + return status; + } + +@@ -5420,7 +4754,7 @@ + + encryption->signature_len = buflen; + } else if (id == 0x7E4) { + // ContentSigKeyID +- delete[] encryption->sig_key_id; ++ delete[] encryption -> sig_key_id; + encryption->sig_key_id = NULL; + encryption->sig_key_id_len = 0; + +@@ -5433,9 +4767,10 @@ + + if (buf == NULL) + return -1; + +- const int read_status = pReader->Read(pos, buflen, buf); ++ const int read_status = ++ pReader->Read(pos, static_cast(buflen), buf); + if (read_status) { +- delete [] buf; ++ delete[] buf; + return status; + } + +@@ -5450,400 +4785,322 @@ + + } else if (id == 0x7E7) { + // ContentEncAESSettings + const long status = ParseContentEncAESSettingsEntry( +- pos, +- size, +- pReader, +- &encryption->aes_settings); ++ pos, size, pReader, &encryption->aes_settings); + if (status) + return status; + } + +- pos += size; //consume payload ++ pos += size; // consume payload + assert(pos <= stop); + } + + return 0; + } + +-Track::Track( +- Segment* pSegment, +- long long element_start, +- long long element_size) : +- m_pSegment(pSegment), +- m_element_start(element_start), +- m_element_size(element_size), +- content_encoding_entries_(NULL), +- content_encoding_entries_end_(NULL) +-{ ++Track::Track(Segment* pSegment, long long element_start, long long element_size) ++ : m_pSegment(pSegment), ++ m_element_start(element_start), ++ m_element_size(element_size), ++ content_encoding_entries_(NULL), ++ content_encoding_entries_end_(NULL) {} ++ ++Track::~Track() { ++ Info& info = const_cast(m_info); ++ info.Clear(); ++ ++ ContentEncoding** i = content_encoding_entries_; ++ ContentEncoding** const j = content_encoding_entries_end_; ++ ++ while (i != j) { ++ ContentEncoding* const encoding = *i++; ++ delete encoding; ++ } ++ ++ delete[] content_encoding_entries_; + } + +-Track::~Track() +-{ +- Info& info = const_cast(m_info); +- info.Clear(); ++long Track::Create(Segment* pSegment, const Info& info, long long element_start, ++ long long element_size, Track*& pResult) { ++ if (pResult) ++ return -1; + +- ContentEncoding** i = content_encoding_entries_; +- ContentEncoding** const j = content_encoding_entries_end_; ++ Track* const pTrack = ++ new (std::nothrow) Track(pSegment, element_start, element_size); + +- while (i != j) { +- ContentEncoding* const encoding = *i++; +- delete encoding; +- } ++ if (pTrack == NULL) ++ return -1; // generic error + +- delete [] content_encoding_entries_; ++ const int status = info.Copy(pTrack->m_info); ++ ++ if (status) { // error ++ delete pTrack; ++ return status; ++ } ++ ++ pResult = pTrack; ++ return 0; // success + } + +-long Track::Create( +- Segment* pSegment, +- const Info& info, +- long long element_start, +- long long element_size, +- Track*& pResult) +-{ +- if (pResult) +- return -1; ++Track::Info::Info() ++ : uid(0), ++ defaultDuration(0), ++ codecDelay(0), ++ seekPreRoll(0), ++ nameAsUTF8(NULL), ++ language(NULL), ++ codecId(NULL), ++ codecNameAsUTF8(NULL), ++ codecPrivate(NULL), ++ codecPrivateSize(0), ++ lacing(false) {} + +- Track* const pTrack = new (std::nothrow) Track(pSegment, +- element_start, +- element_size); ++Track::Info::~Info() { Clear(); } + +- if (pTrack == NULL) +- return -1; //generic error ++void Track::Info::Clear() { ++ delete[] nameAsUTF8; ++ nameAsUTF8 = NULL; + +- const int status = info.Copy(pTrack->m_info); ++ delete[] language; ++ language = NULL; + +- if (status) // error +- { +- delete pTrack; +- return status; +- } ++ delete[] codecId; ++ codecId = NULL; + +- pResult = pTrack; +- return 0; //success ++ delete[] codecPrivate; ++ codecPrivate = NULL; ++ codecPrivateSize = 0; ++ ++ delete[] codecNameAsUTF8; ++ codecNameAsUTF8 = NULL; + } + +-Track::Info::Info(): +- uid(0), +- defaultDuration(0), +- codecDelay(0), +- seekPreRoll(0), +- nameAsUTF8(NULL), +- language(NULL), +- codecId(NULL), +- codecNameAsUTF8(NULL), +- codecPrivate(NULL), +- codecPrivateSize(0), +- lacing(false) +-{ +-} ++int Track::Info::CopyStr(char* Info::*str, Info& dst_) const { ++ if (str == static_cast(NULL)) ++ return -1; + +-Track::Info::~Info() +-{ +- Clear(); +-} ++ char*& dst = dst_.*str; + +-void Track::Info::Clear() +-{ +- delete[] nameAsUTF8; +- nameAsUTF8 = NULL; ++ if (dst) // should be NULL already ++ return -1; + +- delete[] language; +- language = NULL; ++ const char* const src = this->*str; + +- delete[] codecId; +- codecId = NULL; +- +- delete[] codecPrivate; +- codecPrivate = NULL; +- codecPrivateSize = 0; +- +- delete[] codecNameAsUTF8; +- codecNameAsUTF8 = NULL; +-} +- +-int Track::Info::CopyStr(char* Info::*str, Info& dst_) const +-{ +- if (str == static_cast(NULL)) +- return -1; +- +- char*& dst = dst_.*str; +- +- if (dst) //should be NULL already +- return -1; +- +- const char* const src = this->*str; +- +- if (src == NULL) +- return 0; +- +- const size_t len = strlen(src); +- +- dst = new (std::nothrow) char[len+1]; +- +- if (dst == NULL) +- return -1; +- +- strcpy(dst, src); +- ++ if (src == NULL) + return 0; ++ ++ const size_t len = strlen(src); ++ ++ dst = new (std::nothrow) char[len + 1]; ++ ++ if (dst == NULL) ++ return -1; ++ ++ strcpy(dst, src); ++ ++ return 0; + } + ++int Track::Info::Copy(Info& dst) const { ++ if (&dst == this) ++ return 0; + +-int Track::Info::Copy(Info& dst) const +-{ +- if (&dst == this) +- return 0; ++ dst.type = type; ++ dst.number = number; ++ dst.defaultDuration = defaultDuration; ++ dst.codecDelay = codecDelay; ++ dst.seekPreRoll = seekPreRoll; ++ dst.uid = uid; ++ dst.lacing = lacing; ++ dst.settings = settings; + +- dst.type = type; +- dst.number = number; +- dst.defaultDuration = defaultDuration; +- dst.codecDelay = codecDelay; +- dst.seekPreRoll = seekPreRoll; +- dst.uid = uid; +- dst.lacing = lacing; +- dst.settings = settings; ++ // We now copy the string member variables from src to dst. ++ // This involves memory allocation so in principle the operation ++ // can fail (indeed, that's why we have Info::Copy), so we must ++ // report this to the caller. An error return from this function ++ // therefore implies that the copy was only partially successful. + +- //We now copy the string member variables from src to dst. +- //This involves memory allocation so in principle the operation +- //can fail (indeed, that's why we have Info::Copy), so we must +- //report this to the caller. An error return from this function +- //therefore implies that the copy was only partially successful. ++ if (int status = CopyStr(&Info::nameAsUTF8, dst)) ++ return status; + +- if (int status = CopyStr(&Info::nameAsUTF8, dst)) +- return status; ++ if (int status = CopyStr(&Info::language, dst)) ++ return status; + +- if (int status = CopyStr(&Info::language, dst)) +- return status; ++ if (int status = CopyStr(&Info::codecId, dst)) ++ return status; + +- if (int status = CopyStr(&Info::codecId, dst)) +- return status; ++ if (int status = CopyStr(&Info::codecNameAsUTF8, dst)) ++ return status; + +- if (int status = CopyStr(&Info::codecNameAsUTF8, dst)) +- return status; ++ if (codecPrivateSize > 0) { ++ if (codecPrivate == NULL) ++ return -1; + +- if (codecPrivateSize > 0) +- { +- if (codecPrivate == NULL) +- return -1; ++ if (dst.codecPrivate) ++ return -1; + +- if (dst.codecPrivate) +- return -1; ++ if (dst.codecPrivateSize != 0) ++ return -1; + +- if (dst.codecPrivateSize != 0) +- return -1; ++ dst.codecPrivate = new (std::nothrow) unsigned char[codecPrivateSize]; + +- dst.codecPrivate = new (std::nothrow) unsigned char[codecPrivateSize]; ++ if (dst.codecPrivate == NULL) ++ return -1; + +- if (dst.codecPrivate == NULL) +- return -1; ++ memcpy(dst.codecPrivate, codecPrivate, codecPrivateSize); ++ dst.codecPrivateSize = codecPrivateSize; ++ } + +- memcpy(dst.codecPrivate, codecPrivate, codecPrivateSize); +- dst.codecPrivateSize = codecPrivateSize; ++ return 0; ++} ++ ++const BlockEntry* Track::GetEOS() const { return &m_eos; } ++ ++long Track::GetType() const { return m_info.type; } ++ ++long Track::GetNumber() const { return m_info.number; } ++ ++unsigned long long Track::GetUid() const { return m_info.uid; } ++ ++const char* Track::GetNameAsUTF8() const { return m_info.nameAsUTF8; } ++ ++const char* Track::GetLanguage() const { return m_info.language; } ++ ++const char* Track::GetCodecNameAsUTF8() const { return m_info.codecNameAsUTF8; } ++ ++const char* Track::GetCodecId() const { return m_info.codecId; } ++ ++const unsigned char* Track::GetCodecPrivate(size_t& size) const { ++ size = m_info.codecPrivateSize; ++ return m_info.codecPrivate; ++} ++ ++bool Track::GetLacing() const { return m_info.lacing; } ++ ++unsigned long long Track::GetDefaultDuration() const { ++ return m_info.defaultDuration; ++} ++ ++unsigned long long Track::GetCodecDelay() const { return m_info.codecDelay; } ++ ++unsigned long long Track::GetSeekPreRoll() const { return m_info.seekPreRoll; } ++ ++long Track::GetFirst(const BlockEntry*& pBlockEntry) const { ++ const Cluster* pCluster = m_pSegment->GetFirst(); ++ ++ for (int i = 0;;) { ++ if (pCluster == NULL) { ++ pBlockEntry = GetEOS(); ++ return 1; + } + +- return 0; +-} +- +-const BlockEntry* Track::GetEOS() const +-{ +- return &m_eos; +-} +- +-long Track::GetType() const +-{ +- return m_info.type; +-} +- +-long Track::GetNumber() const +-{ +- return m_info.number; +-} +- +-unsigned long long Track::GetUid() const +-{ +- return m_info.uid; +-} +- +-const char* Track::GetNameAsUTF8() const +-{ +- return m_info.nameAsUTF8; +-} +- +-const char* Track::GetLanguage() const +-{ +- return m_info.language; +-} +- +-const char* Track::GetCodecNameAsUTF8() const +-{ +- return m_info.codecNameAsUTF8; +-} +- +- +-const char* Track::GetCodecId() const +-{ +- return m_info.codecId; +-} +- +-const unsigned char* Track::GetCodecPrivate(size_t& size) const +-{ +- size = m_info.codecPrivateSize; +- return m_info.codecPrivate; +-} +- +- +-bool Track::GetLacing() const +-{ +- return m_info.lacing; +-} +- +-unsigned long long Track::GetDefaultDuration() const +-{ +- return m_info.defaultDuration; +-} +- +-unsigned long long Track::GetCodecDelay() const +-{ +- return m_info.codecDelay; +-} +- +-unsigned long long Track::GetSeekPreRoll() const +-{ +- return m_info.seekPreRoll; +-} +- +-long Track::GetFirst(const BlockEntry*& pBlockEntry) const +-{ +- const Cluster* pCluster = m_pSegment->GetFirst(); +- +- for (int i = 0; ; ) +- { +- if (pCluster == NULL) +- { +- pBlockEntry = GetEOS(); +- return 1; +- } +- +- if (pCluster->EOS()) +- { ++ if (pCluster->EOS()) { + #if 0 +- if (m_pSegment->Unparsed() <= 0) //all clusters have been loaded +- { ++ if (m_pSegment->Unparsed() <= 0) { //all clusters have been loaded + pBlockEntry = GetEOS(); + return 1; + } + #else +- if (m_pSegment->DoneParsing()) +- { +- pBlockEntry = GetEOS(); +- return 1; +- } ++ if (m_pSegment->DoneParsing()) { ++ pBlockEntry = GetEOS(); ++ return 1; ++ } + #endif + +- pBlockEntry = 0; +- return E_BUFFER_NOT_FULL; +- } +- +- long status = pCluster->GetFirst(pBlockEntry); +- +- if (status < 0) //error +- return status; +- +- if (pBlockEntry == 0) //empty cluster +- { +- pCluster = m_pSegment->GetNext(pCluster); +- continue; +- } +- +- for (;;) +- { +- const Block* const pBlock = pBlockEntry->GetBlock(); +- assert(pBlock); +- +- const long long tn = pBlock->GetTrackNumber(); +- +- if ((tn == m_info.number) && VetEntry(pBlockEntry)) +- return 0; +- +- const BlockEntry* pNextEntry; +- +- status = pCluster->GetNext(pBlockEntry, pNextEntry); +- +- if (status < 0) //error +- return status; +- +- if (pNextEntry == 0) +- break; +- +- pBlockEntry = pNextEntry; +- } +- +- ++i; +- +- if (i >= 100) +- break; +- +- pCluster = m_pSegment->GetNext(pCluster); ++ pBlockEntry = 0; ++ return E_BUFFER_NOT_FULL; + } + +- //NOTE: if we get here, it means that we didn't find a block with +- //a matching track number. We interpret that as an error (which +- //might be too conservative). ++ long status = pCluster->GetFirst(pBlockEntry); + +- pBlockEntry = GetEOS(); //so we can return a non-NULL value +- return 1; +-} ++ if (status < 0) // error ++ return status; + ++ if (pBlockEntry == 0) { // empty cluster ++ pCluster = m_pSegment->GetNext(pCluster); ++ continue; ++ } + +-long Track::GetNext( +- const BlockEntry* pCurrEntry, +- const BlockEntry*& pNextEntry) const +-{ +- assert(pCurrEntry); +- assert(!pCurrEntry->EOS()); //? ++ for (;;) { ++ const Block* const pBlock = pBlockEntry->GetBlock(); ++ assert(pBlock); + +- const Block* const pCurrBlock = pCurrEntry->GetBlock(); +- assert(pCurrBlock && pCurrBlock->GetTrackNumber() == m_info.number); +- if (!pCurrBlock || pCurrBlock->GetTrackNumber() != m_info.number) +- return -1; ++ const long long tn = pBlock->GetTrackNumber(); + +- const Cluster* pCluster = pCurrEntry->GetCluster(); +- assert(pCluster); +- assert(!pCluster->EOS()); ++ if ((tn == m_info.number) && VetEntry(pBlockEntry)) ++ return 0; + +- long status = pCluster->GetNext(pCurrEntry, pNextEntry); ++ const BlockEntry* pNextEntry; + +- if (status < 0) //error ++ status = pCluster->GetNext(pBlockEntry, pNextEntry); ++ ++ if (status < 0) // error + return status; + +- for (int i = 0; ; ) +- { +- while (pNextEntry) +- { +- const Block* const pNextBlock = pNextEntry->GetBlock(); +- assert(pNextBlock); ++ if (pNextEntry == 0) ++ break; + +- if (pNextBlock->GetTrackNumber() == m_info.number) +- return 0; ++ pBlockEntry = pNextEntry; ++ } + +- pCurrEntry = pNextEntry; ++ ++i; + +- status = pCluster->GetNext(pCurrEntry, pNextEntry); ++ if (i >= 100) ++ break; + +- if (status < 0) //error +- return status; +- } ++ pCluster = m_pSegment->GetNext(pCluster); ++ } + +- pCluster = m_pSegment->GetNext(pCluster); ++ // NOTE: if we get here, it means that we didn't find a block with ++ // a matching track number. We interpret that as an error (which ++ // might be too conservative). + +- if (pCluster == NULL) +- { +- pNextEntry = GetEOS(); +- return 1; +- } ++ pBlockEntry = GetEOS(); // so we can return a non-NULL value ++ return 1; ++} + +- if (pCluster->EOS()) +- { ++long Track::GetNext(const BlockEntry* pCurrEntry, ++ const BlockEntry*& pNextEntry) const { ++ assert(pCurrEntry); ++ assert(!pCurrEntry->EOS()); //? ++ ++ const Block* const pCurrBlock = pCurrEntry->GetBlock(); ++ assert(pCurrBlock && pCurrBlock->GetTrackNumber() == m_info.number); ++ if (!pCurrBlock || pCurrBlock->GetTrackNumber() != m_info.number) ++ return -1; ++ ++ const Cluster* pCluster = pCurrEntry->GetCluster(); ++ assert(pCluster); ++ assert(!pCluster->EOS()); ++ ++ long status = pCluster->GetNext(pCurrEntry, pNextEntry); ++ ++ if (status < 0) // error ++ return status; ++ ++ for (int i = 0;;) { ++ while (pNextEntry) { ++ const Block* const pNextBlock = pNextEntry->GetBlock(); ++ assert(pNextBlock); ++ ++ if (pNextBlock->GetTrackNumber() == m_info.number) ++ return 0; ++ ++ pCurrEntry = pNextEntry; ++ ++ status = pCluster->GetNext(pCurrEntry, pNextEntry); ++ ++ if (status < 0) // error ++ return status; ++ } ++ ++ pCluster = m_pSegment->GetNext(pCluster); ++ ++ if (pCluster == NULL) { ++ pNextEntry = GetEOS(); ++ return 1; ++ } ++ ++ if (pCluster->EOS()) { + #if 0 + if (m_pSegment->Unparsed() <= 0) //all clusters have been loaded + { +@@ -5851,155 +5108,148 @@ + + return 1; + } + #else +- if (m_pSegment->DoneParsing()) +- { +- pNextEntry = GetEOS(); +- return 1; +- } ++ if (m_pSegment->DoneParsing()) { ++ pNextEntry = GetEOS(); ++ return 1; ++ } + #endif + +- //TODO: there is a potential O(n^2) problem here: we tell the +- //caller to (pre)load another cluster, which he does, but then he +- //calls GetNext again, which repeats the same search. This is +- //a pathological case, since the only way it can happen is if +- //there exists a long sequence of clusters none of which contain a +- // block from this track. One way around this problem is for the +- //caller to be smarter when he loads another cluster: don't call +- //us back until you have a cluster that contains a block from this +- //track. (Of course, that's not cheap either, since our caller +- //would have to scan the each cluster as it's loaded, so that +- //would just push back the problem.) ++ // TODO: there is a potential O(n^2) problem here: we tell the ++ // caller to (pre)load another cluster, which he does, but then he ++ // calls GetNext again, which repeats the same search. This is ++ // a pathological case, since the only way it can happen is if ++ // there exists a long sequence of clusters none of which contain a ++ // block from this track. One way around this problem is for the ++ // caller to be smarter when he loads another cluster: don't call ++ // us back until you have a cluster that contains a block from this ++ // track. (Of course, that's not cheap either, since our caller ++ // would have to scan the each cluster as it's loaded, so that ++ // would just push back the problem.) + +- pNextEntry = NULL; +- return E_BUFFER_NOT_FULL; +- } +- +- status = pCluster->GetFirst(pNextEntry); +- +- if (status < 0) //error +- return status; +- +- if (pNextEntry == NULL) //empty cluster +- continue; +- +- ++i; +- +- if (i >= 100) +- break; ++ pNextEntry = NULL; ++ return E_BUFFER_NOT_FULL; + } + +- //NOTE: if we get here, it means that we didn't find a block with +- //a matching track number after lots of searching, so we give +- //up trying. ++ status = pCluster->GetFirst(pNextEntry); + +- pNextEntry = GetEOS(); //so we can return a non-NULL value +- return 1; ++ if (status < 0) // error ++ return status; ++ ++ if (pNextEntry == NULL) // empty cluster ++ continue; ++ ++ ++i; ++ ++ if (i >= 100) ++ break; ++ } ++ ++ // NOTE: if we get here, it means that we didn't find a block with ++ // a matching track number after lots of searching, so we give ++ // up trying. ++ ++ pNextEntry = GetEOS(); // so we can return a non-NULL value ++ return 1; + } + +-bool Track::VetEntry(const BlockEntry* pBlockEntry) const +-{ +- assert(pBlockEntry); +- const Block* const pBlock = pBlockEntry->GetBlock(); +- assert(pBlock); +- assert(pBlock->GetTrackNumber() == m_info.number); +- if (!pBlock || pBlock->GetTrackNumber() != m_info.number) +- return false; ++bool Track::VetEntry(const BlockEntry* pBlockEntry) const { ++ assert(pBlockEntry); ++ const Block* const pBlock = pBlockEntry->GetBlock(); ++ assert(pBlock); ++ assert(pBlock->GetTrackNumber() == m_info.number); ++ if (!pBlock || pBlock->GetTrackNumber() != m_info.number) ++ return false; + +- // This function is used during a seek to determine whether the +- // frame is a valid seek target. This default function simply +- // returns true, which means all frames are valid seek targets. +- // It gets overridden by the VideoTrack class, because only video +- // keyframes can be used as seek target. ++ // This function is used during a seek to determine whether the ++ // frame is a valid seek target. This default function simply ++ // returns true, which means all frames are valid seek targets. ++ // It gets overridden by the VideoTrack class, because only video ++ // keyframes can be used as seek target. + +- return true; ++ return true; + } + +-long Track::Seek( +- long long time_ns, +- const BlockEntry*& pResult) const +-{ +- const long status = GetFirst(pResult); ++long Track::Seek(long long time_ns, const BlockEntry*& pResult) const { ++ const long status = GetFirst(pResult); + +- if (status < 0) //buffer underflow, etc +- return status; ++ if (status < 0) // buffer underflow, etc ++ return status; + +- assert(pResult); ++ assert(pResult); + +- if (pResult->EOS()) +- return 0; ++ if (pResult->EOS()) ++ return 0; + +- const Cluster* pCluster = pResult->GetCluster(); ++ const Cluster* pCluster = pResult->GetCluster(); ++ assert(pCluster); ++ assert(pCluster->GetIndex() >= 0); ++ ++ if (time_ns <= pResult->GetBlock()->GetTime(pCluster)) ++ return 0; ++ ++ Cluster** const clusters = m_pSegment->m_clusters; ++ assert(clusters); ++ ++ const long count = m_pSegment->GetCount(); // loaded only, not preloaded ++ assert(count > 0); ++ ++ Cluster** const i = clusters + pCluster->GetIndex(); ++ assert(i); ++ assert(*i == pCluster); ++ assert(pCluster->GetTime() <= time_ns); ++ ++ Cluster** const j = clusters + count; ++ ++ Cluster** lo = i; ++ Cluster** hi = j; ++ ++ while (lo < hi) { ++ // INVARIANT: ++ //[i, lo) <= time_ns ++ //[lo, hi) ? ++ //[hi, j) > time_ns ++ ++ Cluster** const mid = lo + (hi - lo) / 2; ++ assert(mid < hi); ++ ++ pCluster = *mid; + assert(pCluster); + assert(pCluster->GetIndex() >= 0); ++ assert(pCluster->GetIndex() == long(mid - m_pSegment->m_clusters)); + +- if (time_ns <= pResult->GetBlock()->GetTime(pCluster)) +- return 0; ++ const long long t = pCluster->GetTime(); + +- Cluster** const clusters = m_pSegment->m_clusters; +- assert(clusters); ++ if (t <= time_ns) ++ lo = mid + 1; ++ else ++ hi = mid; + +- const long count = m_pSegment->GetCount(); //loaded only, not preloaded +- assert(count > 0); ++ assert(lo <= hi); ++ } + +- Cluster** const i = clusters + pCluster->GetIndex(); +- assert(i); +- assert(*i == pCluster); ++ assert(lo == hi); ++ assert(lo > i); ++ assert(lo <= j); ++ ++ while (lo > i) { ++ pCluster = *--lo; ++ assert(pCluster); + assert(pCluster->GetTime() <= time_ns); + +- Cluster** const j = clusters + count; ++ pResult = pCluster->GetEntry(this); + +- Cluster** lo = i; +- Cluster** hi = j; ++ if ((pResult != 0) && !pResult->EOS()) ++ return 0; + +- while (lo < hi) +- { +- //INVARIANT: +- //[i, lo) <= time_ns +- //[lo, hi) ? +- //[hi, j) > time_ns ++ // landed on empty cluster (no entries) ++ } + +- Cluster** const mid = lo + (hi - lo) / 2; +- assert(mid < hi); +- +- pCluster = *mid; +- assert(pCluster); +- assert(pCluster->GetIndex() >= 0); +- assert(pCluster->GetIndex() == long(mid - m_pSegment->m_clusters)); +- +- const long long t = pCluster->GetTime(); +- +- if (t <= time_ns) +- lo = mid + 1; +- else +- hi = mid; +- +- assert(lo <= hi); +- } +- +- assert(lo == hi); +- assert(lo > i); +- assert(lo <= j); +- +- while (lo > i) +- { +- pCluster = *--lo; +- assert(pCluster); +- assert(pCluster->GetTime() <= time_ns); +- +- pResult = pCluster->GetEntry(this); +- +- if ((pResult != 0) && !pResult->EOS()) +- return 0; +- +- //landed on empty cluster (no entries) +- } +- +- pResult = GetEOS(); //weird +- return 0; ++ pResult = GetEOS(); // weird ++ return 0; + } + +-const ContentEncoding* +-Track::GetContentEncodingByIndex(unsigned long idx) const { ++const ContentEncoding* Track::GetContentEncodingByIndex( ++ unsigned long idx) const { + const ptrdiff_t count = + content_encoding_entries_end_ - content_encoding_entries_; + assert(count >= 0); +@@ -6029,27 +5279,22 @@ + + int count = 0; + while (pos < stop) { + long long id, size; +- const long status = ParseElementHeader(pReader, +- pos, +- stop, +- id, +- size); +- if (status < 0) //error ++ const long status = ParseElementHeader(pReader, pos, stop, id, size); ++ if (status < 0) // error + return status; + +- +- //pos now designates start of element ++ // pos now designates start of element + if (id == 0x2240) // ContentEncoding ID + ++count; + +- pos += size; //consume payload ++ pos += size; // consume payload + assert(pos <= stop); + } + + if (count <= 0) + return -1; + +- content_encoding_entries_ = new (std::nothrow) ContentEncoding*[count]; ++ content_encoding_entries_ = new (std::nothrow) ContentEncoding* [count]; + if (!content_encoding_entries_) + return -1; + +@@ -6058,24 +5303,18 @@ + + pos = start; + while (pos < stop) { + long long id, size; +- long status = ParseElementHeader(pReader, +- pos, +- stop, +- id, +- size); +- if (status < 0) //error ++ long status = ParseElementHeader(pReader, pos, stop, id, size); ++ if (status < 0) // error + return status; + +- //pos now designates start of element +- if (id == 0x2240) { // ContentEncoding ID ++ // pos now designates start of element ++ if (id == 0x2240) { // ContentEncoding ID + ContentEncoding* const content_encoding = + new (std::nothrow) ContentEncoding(); + if (!content_encoding) + return -1; + +- status = content_encoding->ParseContentEncodingEntry(pos, +- size, +- pReader); ++ status = content_encoding->ParseContentEncodingEntry(pos, size, pReader); + if (status) { + delete content_encoding; + return status; +@@ -6084,7 +5323,7 @@ + + *content_encoding_entries_end_++ = content_encoding; + } + +- pos += size; //consume payload ++ pos += size; // consume payload + assert(pos <= stop); + } + +@@ -6093,219 +5332,175 @@ + + return 0; + } + +-Track::EOSBlock::EOSBlock() : +- BlockEntry(NULL, LONG_MIN) +-{ +-} ++Track::EOSBlock::EOSBlock() : BlockEntry(NULL, LONG_MIN) {} + +-BlockEntry::Kind Track::EOSBlock::GetKind() const +-{ +- return kBlockEOS; +-} ++BlockEntry::Kind Track::EOSBlock::GetKind() const { return kBlockEOS; } + ++const Block* Track::EOSBlock::GetBlock() const { return NULL; } + +-const Block* Track::EOSBlock::GetBlock() const +-{ +- return NULL; +-} ++VideoTrack::VideoTrack(Segment* pSegment, long long element_start, ++ long long element_size) ++ : Track(pSegment, element_start, element_size) {} + ++long VideoTrack::Parse(Segment* pSegment, const Info& info, ++ long long element_start, long long element_size, ++ VideoTrack*& pResult) { ++ if (pResult) ++ return -1; + +-VideoTrack::VideoTrack( +- Segment* pSegment, +- long long element_start, +- long long element_size) : +- Track(pSegment, element_start, element_size) +-{ +-} ++ if (info.type != Track::kVideo) ++ return -1; + ++ long long width = 0; ++ long long height = 0; ++ double rate = 0.0; + +-long VideoTrack::Parse( +- Segment* pSegment, +- const Info& info, +- long long element_start, +- long long element_size, +- VideoTrack*& pResult) +-{ +- if (pResult) +- return -1; ++ IMkvReader* const pReader = pSegment->m_pReader; + +- if (info.type != Track::kVideo) +- return -1; ++ const Settings& s = info.settings; ++ assert(s.start >= 0); ++ assert(s.size >= 0); + +- long long width = 0; +- long long height = 0; +- double rate = 0.0; ++ long long pos = s.start; ++ assert(pos >= 0); + +- IMkvReader* const pReader = pSegment->m_pReader; ++ const long long stop = pos + s.size; + +- const Settings& s = info.settings; +- assert(s.start >= 0); +- assert(s.size >= 0); ++ while (pos < stop) { ++ long long id, size; + +- long long pos = s.start; +- assert(pos >= 0); ++ const long status = ParseElementHeader(pReader, pos, stop, id, size); + +- const long long stop = pos + s.size; ++ if (status < 0) // error ++ return status; + +- while (pos < stop) +- { +- long long id, size; ++ if (id == 0x30) { // pixel width ++ width = UnserializeUInt(pReader, pos, size); + +- const long status = ParseElementHeader( +- pReader, +- pos, +- stop, +- id, +- size); ++ if (width <= 0) ++ return E_FILE_FORMAT_INVALID; ++ } else if (id == 0x3A) { // pixel height ++ height = UnserializeUInt(pReader, pos, size); + +- if (status < 0) //error +- return status; ++ if (height <= 0) ++ return E_FILE_FORMAT_INVALID; ++ } else if (id == 0x0383E3) { // frame rate ++ const long status = UnserializeFloat(pReader, pos, size, rate); + +- if (id == 0x30) //pixel width +- { +- width = UnserializeUInt(pReader, pos, size); +- +- if (width <= 0) +- return E_FILE_FORMAT_INVALID; +- } +- else if (id == 0x3A) //pixel height +- { +- height = UnserializeUInt(pReader, pos, size); +- +- if (height <= 0) +- return E_FILE_FORMAT_INVALID; +- } +- else if (id == 0x0383E3) //frame rate +- { +- const long status = UnserializeFloat( +- pReader, +- pos, +- size, +- rate); +- +- if (status < 0) +- return status; +- +- if (rate <= 0) +- return E_FILE_FORMAT_INVALID; +- } +- +- pos += size; //consume payload +- assert(pos <= stop); +- } +- +- assert(pos == stop); +- +- VideoTrack* const pTrack = new (std::nothrow) VideoTrack(pSegment, +- element_start, +- element_size); +- +- if (pTrack == NULL) +- return -1; //generic error +- +- const int status = info.Copy(pTrack->m_info); +- +- if (status) // error +- { +- delete pTrack; +- return status; +- } +- +- pTrack->m_width = width; +- pTrack->m_height = height; +- pTrack->m_rate = rate; +- +- pResult = pTrack; +- return 0; //success +-} +- +- +-bool VideoTrack::VetEntry(const BlockEntry* pBlockEntry) const +-{ +- return Track::VetEntry(pBlockEntry) && pBlockEntry->GetBlock()->IsKey(); +-} +- +-long VideoTrack::Seek( +- long long time_ns, +- const BlockEntry*& pResult) const +-{ +- const long status = GetFirst(pResult); +- +- if (status < 0) //buffer underflow, etc ++ if (status < 0) + return status; + +- assert(pResult); ++ if (rate <= 0) ++ return E_FILE_FORMAT_INVALID; ++ } + +- if (pResult->EOS()) +- return 0; ++ pos += size; // consume payload ++ assert(pos <= stop); ++ } + +- const Cluster* pCluster = pResult->GetCluster(); ++ assert(pos == stop); ++ ++ VideoTrack* const pTrack = ++ new (std::nothrow) VideoTrack(pSegment, element_start, element_size); ++ ++ if (pTrack == NULL) ++ return -1; // generic error ++ ++ const int status = info.Copy(pTrack->m_info); ++ ++ if (status) { // error ++ delete pTrack; ++ return status; ++ } ++ ++ pTrack->m_width = width; ++ pTrack->m_height = height; ++ pTrack->m_rate = rate; ++ ++ pResult = pTrack; ++ return 0; // success ++} ++ ++bool VideoTrack::VetEntry(const BlockEntry* pBlockEntry) const { ++ return Track::VetEntry(pBlockEntry) && pBlockEntry->GetBlock()->IsKey(); ++} ++ ++long VideoTrack::Seek(long long time_ns, const BlockEntry*& pResult) const { ++ const long status = GetFirst(pResult); ++ ++ if (status < 0) // buffer underflow, etc ++ return status; ++ ++ assert(pResult); ++ ++ if (pResult->EOS()) ++ return 0; ++ ++ const Cluster* pCluster = pResult->GetCluster(); ++ assert(pCluster); ++ assert(pCluster->GetIndex() >= 0); ++ ++ if (time_ns <= pResult->GetBlock()->GetTime(pCluster)) ++ return 0; ++ ++ Cluster** const clusters = m_pSegment->m_clusters; ++ assert(clusters); ++ ++ const long count = m_pSegment->GetCount(); // loaded only, not pre-loaded ++ assert(count > 0); ++ ++ Cluster** const i = clusters + pCluster->GetIndex(); ++ assert(i); ++ assert(*i == pCluster); ++ assert(pCluster->GetTime() <= time_ns); ++ ++ Cluster** const j = clusters + count; ++ ++ Cluster** lo = i; ++ Cluster** hi = j; ++ ++ while (lo < hi) { ++ // INVARIANT: ++ //[i, lo) <= time_ns ++ //[lo, hi) ? ++ //[hi, j) > time_ns ++ ++ Cluster** const mid = lo + (hi - lo) / 2; ++ assert(mid < hi); ++ ++ pCluster = *mid; + assert(pCluster); + assert(pCluster->GetIndex() >= 0); ++ assert(pCluster->GetIndex() == long(mid - m_pSegment->m_clusters)); + +- if (time_ns <= pResult->GetBlock()->GetTime(pCluster)) +- return 0; ++ const long long t = pCluster->GetTime(); + +- Cluster** const clusters = m_pSegment->m_clusters; +- assert(clusters); ++ if (t <= time_ns) ++ lo = mid + 1; ++ else ++ hi = mid; + +- const long count = m_pSegment->GetCount(); //loaded only, not pre-loaded +- assert(count > 0); ++ assert(lo <= hi); ++ } + +- Cluster** const i = clusters + pCluster->GetIndex(); +- assert(i); +- assert(*i == pCluster); +- assert(pCluster->GetTime() <= time_ns); ++ assert(lo == hi); ++ assert(lo > i); ++ assert(lo <= j); + +- Cluster** const j = clusters + count; ++ pCluster = *--lo; ++ assert(pCluster); ++ assert(pCluster->GetTime() <= time_ns); + +- Cluster** lo = i; +- Cluster** hi = j; ++ pResult = pCluster->GetEntry(this, time_ns); + +- while (lo < hi) +- { +- //INVARIANT: +- //[i, lo) <= time_ns +- //[lo, hi) ? +- //[hi, j) > time_ns ++ if ((pResult != 0) && !pResult->EOS()) // found a keyframe ++ return 0; + +- Cluster** const mid = lo + (hi - lo) / 2; +- assert(mid < hi); +- +- pCluster = *mid; +- assert(pCluster); +- assert(pCluster->GetIndex() >= 0); +- assert(pCluster->GetIndex() == long(mid - m_pSegment->m_clusters)); +- +- const long long t = pCluster->GetTime(); +- +- if (t <= time_ns) +- lo = mid + 1; +- else +- hi = mid; +- +- assert(lo <= hi); +- } +- +- assert(lo == hi); +- assert(lo > i); +- assert(lo <= j); +- ++ while (lo != i) { + pCluster = *--lo; + assert(pCluster); + assert(pCluster->GetTime() <= time_ns); + +- pResult = pCluster->GetEntry(this, time_ns); +- +- if ((pResult != 0) && !pResult->EOS()) //found a keyframe +- return 0; +- +- while (lo != i) +- { +- pCluster = *--lo; +- assert(pCluster); +- assert(pCluster->GetTime() <= time_ns); +- + #if 0 + //TODO: + //We need to handle the case when a cluster +@@ -6314,651 +5509,501 @@ + + //good enough. + pResult = pCluster->GetMaxKey(this); + #else +- pResult = pCluster->GetEntry(this, time_ns); ++ pResult = pCluster->GetEntry(this, time_ns); + #endif + +- if ((pResult != 0) && !pResult->EOS()) +- return 0; ++ if ((pResult != 0) && !pResult->EOS()) ++ return 0; ++ } ++ ++ // weird: we're on the first cluster, but no keyframe found ++ // should never happen but we must return something anyway ++ ++ pResult = GetEOS(); ++ return 0; ++} ++ ++long long VideoTrack::GetWidth() const { return m_width; } ++ ++long long VideoTrack::GetHeight() const { return m_height; } ++ ++double VideoTrack::GetFrameRate() const { return m_rate; } ++ ++AudioTrack::AudioTrack(Segment* pSegment, long long element_start, ++ long long element_size) ++ : Track(pSegment, element_start, element_size) {} ++ ++long AudioTrack::Parse(Segment* pSegment, const Info& info, ++ long long element_start, long long element_size, ++ AudioTrack*& pResult) { ++ if (pResult) ++ return -1; ++ ++ if (info.type != Track::kAudio) ++ return -1; ++ ++ IMkvReader* const pReader = pSegment->m_pReader; ++ ++ const Settings& s = info.settings; ++ assert(s.start >= 0); ++ assert(s.size >= 0); ++ ++ long long pos = s.start; ++ assert(pos >= 0); ++ ++ const long long stop = pos + s.size; ++ ++ double rate = 8000.0; // MKV default ++ long long channels = 1; ++ long long bit_depth = 0; ++ ++ while (pos < stop) { ++ long long id, size; ++ ++ long status = ParseElementHeader(pReader, pos, stop, id, size); ++ ++ if (status < 0) // error ++ return status; ++ ++ if (id == 0x35) { // Sample Rate ++ status = UnserializeFloat(pReader, pos, size, rate); ++ ++ if (status < 0) ++ return status; ++ ++ if (rate <= 0) ++ return E_FILE_FORMAT_INVALID; ++ } else if (id == 0x1F) { // Channel Count ++ channels = UnserializeUInt(pReader, pos, size); ++ ++ if (channels <= 0) ++ return E_FILE_FORMAT_INVALID; ++ } else if (id == 0x2264) { // Bit Depth ++ bit_depth = UnserializeUInt(pReader, pos, size); ++ ++ if (bit_depth <= 0) ++ return E_FILE_FORMAT_INVALID; + } + +- //weird: we're on the first cluster, but no keyframe found +- //should never happen but we must return something anyway ++ pos += size; // consume payload ++ assert(pos <= stop); ++ } + +- pResult = GetEOS(); +- return 0; ++ assert(pos == stop); ++ ++ AudioTrack* const pTrack = ++ new (std::nothrow) AudioTrack(pSegment, element_start, element_size); ++ ++ if (pTrack == NULL) ++ return -1; // generic error ++ ++ const int status = info.Copy(pTrack->m_info); ++ ++ if (status) { ++ delete pTrack; ++ return status; ++ } ++ ++ pTrack->m_rate = rate; ++ pTrack->m_channels = channels; ++ pTrack->m_bitDepth = bit_depth; ++ ++ pResult = pTrack; ++ return 0; // success + } + ++double AudioTrack::GetSamplingRate() const { return m_rate; } + +-long long VideoTrack::GetWidth() const +-{ +- return m_width; +-} ++long long AudioTrack::GetChannels() const { return m_channels; } + ++long long AudioTrack::GetBitDepth() const { return m_bitDepth; } + +-long long VideoTrack::GetHeight() const +-{ +- return m_height; +-} ++Tracks::Tracks(Segment* pSegment, long long start, long long size_, ++ long long element_start, long long element_size) ++ : m_pSegment(pSegment), ++ m_start(start), ++ m_size(size_), ++ m_element_start(element_start), ++ m_element_size(element_size), ++ m_trackEntries(NULL), ++ m_trackEntriesEnd(NULL) {} + ++long Tracks::Parse() { ++ assert(m_trackEntries == NULL); ++ assert(m_trackEntriesEnd == NULL); + +-double VideoTrack::GetFrameRate() const +-{ +- return m_rate; +-} ++ const long long stop = m_start + m_size; ++ IMkvReader* const pReader = m_pSegment->m_pReader; + ++ int count = 0; ++ long long pos = m_start; + +-AudioTrack::AudioTrack( +- Segment* pSegment, +- long long element_start, +- long long element_size) : +- Track(pSegment, element_start, element_size) +-{ +-} ++ while (pos < stop) { ++ long long id, size; + ++ const long status = ParseElementHeader(pReader, pos, stop, id, size); + +-long AudioTrack::Parse( +- Segment* pSegment, +- const Info& info, +- long long element_start, +- long long element_size, +- AudioTrack*& pResult) +-{ +- if (pResult) +- return -1; ++ if (status < 0) // error ++ return status; + +- if (info.type != Track::kAudio) +- return -1; ++ if (size == 0) // weird ++ continue; + +- IMkvReader* const pReader = pSegment->m_pReader; ++ if (id == 0x2E) // TrackEntry ID ++ ++count; + +- const Settings& s = info.settings; +- assert(s.start >= 0); +- assert(s.size >= 0); ++ pos += size; // consume payload ++ assert(pos <= stop); ++ } + +- long long pos = s.start; +- assert(pos >= 0); ++ assert(pos == stop); + +- const long long stop = pos + s.size; ++ if (count <= 0) ++ return 0; // success + +- double rate = 8000.0; // MKV default +- long long channels = 1; +- long long bit_depth = 0; ++ m_trackEntries = new (std::nothrow) Track* [count]; + +- while (pos < stop) +- { +- long long id, size; ++ if (m_trackEntries == NULL) ++ return -1; + +- long status = ParseElementHeader( +- pReader, +- pos, +- stop, +- id, +- size); ++ m_trackEntriesEnd = m_trackEntries; + +- if (status < 0) //error +- return status; ++ pos = m_start; + +- if (id == 0x35) //Sample Rate +- { +- status = UnserializeFloat(pReader, pos, size, rate); ++ while (pos < stop) { ++ const long long element_start = pos; + +- if (status < 0) +- return status; ++ long long id, payload_size; + +- if (rate <= 0) +- return E_FILE_FORMAT_INVALID; +- } +- else if (id == 0x1F) //Channel Count +- { +- channels = UnserializeUInt(pReader, pos, size); ++ const long status = ++ ParseElementHeader(pReader, pos, stop, id, payload_size); + +- if (channels <= 0) +- return E_FILE_FORMAT_INVALID; +- } +- else if (id == 0x2264) //Bit Depth +- { +- bit_depth = UnserializeUInt(pReader, pos, size); ++ if (status < 0) // error ++ return status; + +- if (bit_depth <= 0) +- return E_FILE_FORMAT_INVALID; +- } ++ if (payload_size == 0) // weird ++ continue; + +- pos += size; //consume payload +- assert(pos <= stop); ++ const long long payload_stop = pos + payload_size; ++ assert(payload_stop <= stop); // checked in ParseElement ++ ++ const long long element_size = payload_stop - element_start; ++ ++ if (id == 0x2E) { // TrackEntry ID ++ Track*& pTrack = *m_trackEntriesEnd; ++ pTrack = NULL; ++ ++ const long status = ParseTrackEntry(pos, payload_size, element_start, ++ element_size, pTrack); ++ ++ if (status) ++ return status; ++ ++ if (pTrack) ++ ++m_trackEntriesEnd; + } + +- assert(pos == stop); ++ pos = payload_stop; ++ assert(pos <= stop); ++ } + +- AudioTrack* const pTrack = new (std::nothrow) AudioTrack(pSegment, +- element_start, +- element_size); ++ assert(pos == stop); + +- if (pTrack == NULL) +- return -1; //generic error ++ return 0; // success ++} + +- const int status = info.Copy(pTrack->m_info); ++unsigned long Tracks::GetTracksCount() const { ++ const ptrdiff_t result = m_trackEntriesEnd - m_trackEntries; ++ assert(result >= 0); ++ ++ return static_cast(result); ++} ++ ++long Tracks::ParseTrackEntry(long long track_start, long long track_size, ++ long long element_start, long long element_size, ++ Track*& pResult) const { ++ if (pResult) ++ return -1; ++ ++ IMkvReader* const pReader = m_pSegment->m_pReader; ++ ++ long long pos = track_start; ++ const long long track_stop = track_start + track_size; ++ ++ Track::Info info; ++ ++ info.type = 0; ++ info.number = 0; ++ info.uid = 0; ++ info.defaultDuration = 0; ++ ++ Track::Settings v; ++ v.start = -1; ++ v.size = -1; ++ ++ Track::Settings a; ++ a.start = -1; ++ a.size = -1; ++ ++ Track::Settings e; // content_encodings_settings; ++ e.start = -1; ++ e.size = -1; ++ ++ long long lacing = 1; // default is true ++ ++ while (pos < track_stop) { ++ long long id, size; ++ ++ const long status = ParseElementHeader(pReader, pos, track_stop, id, size); ++ ++ if (status < 0) // error ++ return status; ++ ++ if (size < 0) ++ return E_FILE_FORMAT_INVALID; ++ ++ const long long start = pos; ++ ++ if (id == 0x60) { // VideoSettings ID ++ v.start = start; ++ v.size = size; ++ } else if (id == 0x61) { // AudioSettings ID ++ a.start = start; ++ a.size = size; ++ } else if (id == 0x2D80) { // ContentEncodings ID ++ e.start = start; ++ e.size = size; ++ } else if (id == 0x33C5) { // Track UID ++ if (size > 8) ++ return E_FILE_FORMAT_INVALID; ++ ++ info.uid = 0; ++ ++ long long pos_ = start; ++ const long long pos_end = start + size; ++ ++ while (pos_ != pos_end) { ++ unsigned char b; ++ ++ const int status = pReader->Read(pos_, 1, &b); ++ ++ if (status) ++ return status; ++ ++ info.uid <<= 8; ++ info.uid |= b; ++ ++ ++pos_; ++ } ++ } else if (id == 0x57) { // Track Number ++ const long long num = UnserializeUInt(pReader, pos, size); ++ ++ if ((num <= 0) || (num > 127)) ++ return E_FILE_FORMAT_INVALID; ++ ++ info.number = static_cast(num); ++ } else if (id == 0x03) { // Track Type ++ const long long type = UnserializeUInt(pReader, pos, size); ++ ++ if ((type <= 0) || (type > 254)) ++ return E_FILE_FORMAT_INVALID; ++ ++ info.type = static_cast(type); ++ } else if (id == 0x136E) { // Track Name ++ const long status = ++ UnserializeString(pReader, pos, size, info.nameAsUTF8); ++ ++ if (status) ++ return status; ++ } else if (id == 0x02B59C) { // Track Language ++ const long status = UnserializeString(pReader, pos, size, info.language); ++ ++ if (status) ++ return status; ++ } else if (id == 0x03E383) { // Default Duration ++ const long long duration = UnserializeUInt(pReader, pos, size); ++ ++ if (duration < 0) ++ return E_FILE_FORMAT_INVALID; ++ ++ info.defaultDuration = static_cast(duration); ++ } else if (id == 0x06) { // CodecID ++ const long status = UnserializeString(pReader, pos, size, info.codecId); ++ ++ if (status) ++ return status; ++ } else if (id == 0x1C) { // lacing ++ lacing = UnserializeUInt(pReader, pos, size); ++ ++ if ((lacing < 0) || (lacing > 1)) ++ return E_FILE_FORMAT_INVALID; ++ } else if (id == 0x23A2) { // Codec Private ++ delete[] info.codecPrivate; ++ info.codecPrivate = NULL; ++ info.codecPrivateSize = 0; ++ ++ const size_t buflen = static_cast(size); ++ ++ if (buflen) { ++ typedef unsigned char* buf_t; ++ ++ const buf_t buf = new (std::nothrow) unsigned char[buflen]; ++ ++ if (buf == NULL) ++ return -1; ++ ++ const int status = pReader->Read(pos, static_cast(buflen), buf); ++ ++ if (status) { ++ delete[] buf; ++ return status; ++ } ++ ++ info.codecPrivate = buf; ++ info.codecPrivateSize = buflen; ++ } ++ } else if (id == 0x058688) { // Codec Name ++ const long status = ++ UnserializeString(pReader, pos, size, info.codecNameAsUTF8); ++ ++ if (status) ++ return status; ++ } else if (id == 0x16AA) { // Codec Delay ++ info.codecDelay = UnserializeUInt(pReader, pos, size); ++ } else if (id == 0x16BB) { // Seek Pre Roll ++ info.seekPreRoll = UnserializeUInt(pReader, pos, size); ++ } ++ ++ pos += size; // consume payload ++ assert(pos <= track_stop); ++ } ++ ++ assert(pos == track_stop); ++ ++ if (info.number <= 0) // not specified ++ return E_FILE_FORMAT_INVALID; ++ ++ if (GetTrackByNumber(info.number)) ++ return E_FILE_FORMAT_INVALID; ++ ++ if (info.type <= 0) // not specified ++ return E_FILE_FORMAT_INVALID; ++ ++ info.lacing = (lacing > 0) ? true : false; ++ ++ if (info.type == Track::kVideo) { ++ if (v.start < 0) ++ return E_FILE_FORMAT_INVALID; ++ ++ if (a.start >= 0) ++ return E_FILE_FORMAT_INVALID; ++ ++ info.settings = v; ++ ++ VideoTrack* pTrack = NULL; ++ ++ const long status = VideoTrack::Parse(m_pSegment, info, element_start, ++ element_size, pTrack); + + if (status) +- { +- delete pTrack; +- return status; +- } +- +- pTrack->m_rate = rate; +- pTrack->m_channels = channels; +- pTrack->m_bitDepth = bit_depth; ++ return status; + + pResult = pTrack; +- return 0; //success ++ assert(pResult); ++ ++ if (e.start >= 0) ++ pResult->ParseContentEncodingsEntry(e.start, e.size); ++ } else if (info.type == Track::kAudio) { ++ if (a.start < 0) ++ return E_FILE_FORMAT_INVALID; ++ ++ if (v.start >= 0) ++ return E_FILE_FORMAT_INVALID; ++ ++ info.settings = a; ++ ++ AudioTrack* pTrack = NULL; ++ ++ const long status = AudioTrack::Parse(m_pSegment, info, element_start, ++ element_size, pTrack); ++ ++ if (status) ++ return status; ++ ++ pResult = pTrack; ++ assert(pResult); ++ ++ if (e.start >= 0) ++ pResult->ParseContentEncodingsEntry(e.start, e.size); ++ } else { ++ // neither video nor audio - probably metadata or subtitles ++ ++ if (a.start >= 0) ++ return E_FILE_FORMAT_INVALID; ++ ++ if (v.start >= 0) ++ return E_FILE_FORMAT_INVALID; ++ ++ if (e.start >= 0) ++ return E_FILE_FORMAT_INVALID; ++ ++ info.settings.start = -1; ++ info.settings.size = 0; ++ ++ Track* pTrack = NULL; ++ ++ const long status = ++ Track::Create(m_pSegment, info, element_start, element_size, pTrack); ++ ++ if (status) ++ return status; ++ ++ pResult = pTrack; ++ assert(pResult); ++ } ++ ++ return 0; // success + } + ++Tracks::~Tracks() { ++ Track** i = m_trackEntries; ++ Track** const j = m_trackEntriesEnd; + +-double AudioTrack::GetSamplingRate() const +-{ +- return m_rate; ++ while (i != j) { ++ Track* const pTrack = *i++; ++ delete pTrack; ++ } ++ ++ delete[] m_trackEntries; + } + ++const Track* Tracks::GetTrackByNumber(long tn) const { ++ if (tn < 0) ++ return NULL; + +-long long AudioTrack::GetChannels() const +-{ +- return m_channels; ++ Track** i = m_trackEntries; ++ Track** const j = m_trackEntriesEnd; ++ ++ while (i != j) { ++ Track* const pTrack = *i++; ++ ++ if (pTrack == NULL) ++ continue; ++ ++ if (tn == pTrack->GetNumber()) ++ return pTrack; ++ } ++ ++ return NULL; // not found + } + +-long long AudioTrack::GetBitDepth() const +-{ +- return m_bitDepth; +-} ++const Track* Tracks::GetTrackByIndex(unsigned long idx) const { ++ const ptrdiff_t count = m_trackEntriesEnd - m_trackEntries; + +-Tracks::Tracks( +- Segment* pSegment, +- long long start, +- long long size_, +- long long element_start, +- long long element_size) : +- m_pSegment(pSegment), +- m_start(start), +- m_size(size_), +- m_element_start(element_start), +- m_element_size(element_size), +- m_trackEntries(NULL), +- m_trackEntriesEnd(NULL) +-{ +-} ++ if (idx >= static_cast(count)) ++ return NULL; + +- +-long Tracks::Parse() +-{ +- assert(m_trackEntries == NULL); +- assert(m_trackEntriesEnd == NULL); +- +- const long long stop = m_start + m_size; +- IMkvReader* const pReader = m_pSegment->m_pReader; +- +- int count = 0; +- long long pos = m_start; +- +- while (pos < stop) +- { +- long long id, size; +- +- const long status = ParseElementHeader( +- pReader, +- pos, +- stop, +- id, +- size); +- +- if (status < 0) //error +- return status; +- +- if (size == 0) //weird +- continue; +- +- if (id == 0x2E) //TrackEntry ID +- ++count; +- +- pos += size; //consume payload +- assert(pos <= stop); +- } +- +- assert(pos == stop); +- +- if (count <= 0) +- return 0; //success +- +- m_trackEntries = new (std::nothrow) Track*[count]; +- +- if (m_trackEntries == NULL) +- return -1; +- +- m_trackEntriesEnd = m_trackEntries; +- +- pos = m_start; +- +- while (pos < stop) +- { +- const long long element_start = pos; +- +- long long id, payload_size; +- +- const long status = ParseElementHeader( +- pReader, +- pos, +- stop, +- id, +- payload_size); +- +- if (status < 0) //error +- return status; +- +- if (payload_size == 0) //weird +- continue; +- +- const long long payload_stop = pos + payload_size; +- assert(payload_stop <= stop); //checked in ParseElement +- +- const long long element_size = payload_stop - element_start; +- +- if (id == 0x2E) //TrackEntry ID +- { +- Track*& pTrack = *m_trackEntriesEnd; +- pTrack = NULL; +- +- const long status = ParseTrackEntry( +- pos, +- payload_size, +- element_start, +- element_size, +- pTrack); +- +- if (status) +- return status; +- +- if (pTrack) +- ++m_trackEntriesEnd; +- } +- +- pos = payload_stop; +- assert(pos <= stop); +- } +- +- assert(pos == stop); +- +- return 0; //success +-} +- +- +-unsigned long Tracks::GetTracksCount() const +-{ +- const ptrdiff_t result = m_trackEntriesEnd - m_trackEntries; +- assert(result >= 0); +- +- return static_cast(result); +-} +- +-long Tracks::ParseTrackEntry( +- long long track_start, +- long long track_size, +- long long element_start, +- long long element_size, +- Track*& pResult) const +-{ +- if (pResult) +- return -1; +- +- IMkvReader* const pReader = m_pSegment->m_pReader; +- +- long long pos = track_start; +- const long long track_stop = track_start + track_size; +- +- Track::Info info; +- +- info.type = 0; +- info.number = 0; +- info.uid = 0; +- info.defaultDuration = 0; +- +- Track::Settings v; +- v.start = -1; +- v.size = -1; +- +- Track::Settings a; +- a.start = -1; +- a.size = -1; +- +- Track::Settings e; //content_encodings_settings; +- e.start = -1; +- e.size = -1; +- +- long long lacing = 1; //default is true +- +- while (pos < track_stop) +- { +- long long id, size; +- +- const long status = ParseElementHeader( +- pReader, +- pos, +- track_stop, +- id, +- size); +- +- if (status < 0) //error +- return status; +- +- if (size < 0) +- return E_FILE_FORMAT_INVALID; +- +- const long long start = pos; +- +- if (id == 0x60) // VideoSettings ID +- { +- v.start = start; +- v.size = size; +- } +- else if (id == 0x61) // AudioSettings ID +- { +- a.start = start; +- a.size = size; +- } +- else if (id == 0x2D80) // ContentEncodings ID +- { +- e.start = start; +- e.size = size; +- } +- else if (id == 0x33C5) //Track UID +- { +- if (size > 8) +- return E_FILE_FORMAT_INVALID; +- +- info.uid = 0; +- +- long long pos_ = start; +- const long long pos_end = start + size; +- +- while (pos_ != pos_end) +- { +- unsigned char b; +- +- const int status = pReader->Read(pos_, 1, &b); +- +- if (status) +- return status; +- +- info.uid <<= 8; +- info.uid |= b; +- +- ++pos_; +- } +- } +- else if (id == 0x57) //Track Number +- { +- const long long num = UnserializeUInt(pReader, pos, size); +- +- if ((num <= 0) || (num > 127)) +- return E_FILE_FORMAT_INVALID; +- +- info.number = static_cast(num); +- } +- else if (id == 0x03) //Track Type +- { +- const long long type = UnserializeUInt(pReader, pos, size); +- +- if ((type <= 0) || (type > 254)) +- return E_FILE_FORMAT_INVALID; +- +- info.type = static_cast(type); +- } +- else if (id == 0x136E) //Track Name +- { +- const long status = UnserializeString( +- pReader, +- pos, +- size, +- info.nameAsUTF8); +- +- if (status) +- return status; +- } +- else if (id == 0x02B59C) //Track Language +- { +- const long status = UnserializeString( +- pReader, +- pos, +- size, +- info.language); +- +- if (status) +- return status; +- } +- else if (id == 0x03E383) //Default Duration +- { +- const long long duration = UnserializeUInt(pReader, pos, size); +- +- if (duration < 0) +- return E_FILE_FORMAT_INVALID; +- +- info.defaultDuration = static_cast(duration); +- } +- else if (id == 0x06) //CodecID +- { +- const long status = UnserializeString( +- pReader, +- pos, +- size, +- info.codecId); +- +- if (status) +- return status; +- } +- else if (id == 0x1C) //lacing +- { +- lacing = UnserializeUInt(pReader, pos, size); +- +- if ((lacing < 0) || (lacing > 1)) +- return E_FILE_FORMAT_INVALID; +- } +- else if (id == 0x23A2) //Codec Private +- { +- delete[] info.codecPrivate; +- info.codecPrivate = NULL; +- info.codecPrivateSize = 0; +- +- const size_t buflen = static_cast(size); +- +- if (buflen) +- { +- typedef unsigned char* buf_t; +- +- const buf_t buf = new (std::nothrow) unsigned char[buflen]; +- +- if (buf == NULL) +- return -1; +- +- const int status = pReader->Read(pos, buflen, buf); +- +- if (status) +- { +- delete[] buf; +- return status; +- } +- +- info.codecPrivate = buf; +- info.codecPrivateSize = buflen; +- } +- } +- else if (id == 0x058688) //Codec Name +- { +- const long status = UnserializeString( +- pReader, +- pos, +- size, +- info.codecNameAsUTF8); +- +- if (status) +- return status; +- } +- else if (id == 0x16AA) //Codec Delay +- { +- info.codecDelay = UnserializeUInt(pReader, pos, size); +- +- } +- else if (id == 0x16BB) //Seek Pre Roll +- { +- info.seekPreRoll = UnserializeUInt(pReader, pos, size); +- } +- +- pos += size; //consume payload +- assert(pos <= track_stop); +- } +- +- assert(pos == track_stop); +- +- if (info.number <= 0) //not specified +- return E_FILE_FORMAT_INVALID; +- +- if (GetTrackByNumber(info.number)) +- return E_FILE_FORMAT_INVALID; +- +- if (info.type <= 0) //not specified +- return E_FILE_FORMAT_INVALID; +- +- info.lacing = (lacing > 0) ? true : false; +- +- if (info.type == Track::kVideo) +- { +- if (v.start < 0) +- return E_FILE_FORMAT_INVALID; +- +- if (a.start >= 0) +- return E_FILE_FORMAT_INVALID; +- +- info.settings = v; +- +- VideoTrack* pTrack = NULL; +- +- const long status = VideoTrack::Parse(m_pSegment, +- info, +- element_start, +- element_size, +- pTrack); +- +- if (status) +- return status; +- +- pResult = pTrack; +- assert(pResult); +- +- if (e.start >= 0) +- pResult->ParseContentEncodingsEntry(e.start, e.size); +- } +- else if (info.type == Track::kAudio) +- { +- if (a.start < 0) +- return E_FILE_FORMAT_INVALID; +- +- if (v.start >= 0) +- return E_FILE_FORMAT_INVALID; +- +- info.settings = a; +- +- AudioTrack* pTrack = NULL; +- +- const long status = AudioTrack::Parse(m_pSegment, +- info, +- element_start, +- element_size, +- pTrack); +- +- if (status) +- return status; +- +- pResult = pTrack; +- assert(pResult); +- +- if (e.start >= 0) +- pResult->ParseContentEncodingsEntry(e.start, e.size); +- } +- else +- { +- // neither video nor audio - probably metadata or subtitles +- +- if (a.start >= 0) +- return E_FILE_FORMAT_INVALID; +- +- if (v.start >= 0) +- return E_FILE_FORMAT_INVALID; +- +- if (e.start >= 0) +- return E_FILE_FORMAT_INVALID; +- +- info.settings.start = -1; +- info.settings.size = 0; +- +- Track* pTrack = NULL; +- +- const long status = Track::Create(m_pSegment, +- info, +- element_start, +- element_size, +- pTrack); +- +- if (status) +- return status; +- +- pResult = pTrack; +- assert(pResult); +- } +- +- return 0; //success +-} +- +- +-Tracks::~Tracks() +-{ +- Track** i = m_trackEntries; +- Track** const j = m_trackEntriesEnd; +- +- while (i != j) +- { +- Track* const pTrack = *i++; +- delete pTrack; +- } +- +- delete[] m_trackEntries; +-} +- +-const Track* Tracks::GetTrackByNumber(long tn) const +-{ +- if (tn < 0) +- return NULL; +- +- Track** i = m_trackEntries; +- Track** const j = m_trackEntriesEnd; +- +- while (i != j) +- { +- Track* const pTrack = *i++; +- +- if (pTrack == NULL) +- continue; +- +- if (tn == pTrack->GetNumber()) +- return pTrack; +- } +- +- return NULL; //not found +-} +- +- +-const Track* Tracks::GetTrackByIndex(unsigned long idx) const +-{ +- const ptrdiff_t count = m_trackEntriesEnd - m_trackEntries; +- +- if (idx >= static_cast(count)) +- return NULL; +- +- return m_trackEntries[idx]; ++ return m_trackEntries[idx]; + } + + #if 0 +@@ -6980,104 +6025,100 @@ + + } + #endif + ++long Cluster::Load(long long& pos, long& len) const { ++ assert(m_pSegment); ++ assert(m_pos >= m_element_start); + +-long Cluster::Load(long long& pos, long& len) const +-{ +- assert(m_pSegment); +- assert(m_pos >= m_element_start); ++ if (m_timecode >= 0) // at least partially loaded ++ return 0; + +- if (m_timecode >= 0) //at least partially loaded +- return 0; ++ assert(m_pos == m_element_start); ++ assert(m_element_size < 0); + +- assert(m_pos == m_element_start); +- assert(m_element_size < 0); ++ IMkvReader* const pReader = m_pSegment->m_pReader; + +- IMkvReader* const pReader = m_pSegment->m_pReader; ++ long long total, avail; + +- long long total, avail; ++ const int status = pReader->Length(&total, &avail); + +- const int status = pReader->Length(&total, &avail); ++ if (status < 0) // error ++ return status; + +- if (status < 0) //error +- return status; ++ assert((total < 0) || (avail <= total)); ++ assert((total < 0) || (m_pos <= total)); // TODO: verify this + +- assert((total < 0) || (avail <= total)); +- assert((total < 0) || (m_pos <= total)); //TODO: verify this ++ pos = m_pos; + +- pos = m_pos; ++ long long cluster_size = -1; + +- long long cluster_size = -1; +- +- { +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } +- +- long long result = GetUIntLength(pReader, pos, len); +- +- if (result < 0) //error or underflow +- return static_cast(result); +- +- if (result > 0) //underflow (weird) +- return E_BUFFER_NOT_FULL; +- +- //if ((pos + len) > segment_stop) +- // return E_FILE_FORMAT_INVALID; +- +- if ((pos + len) > avail) +- return E_BUFFER_NOT_FULL; +- +- const long long id_ = ReadUInt(pReader, pos, len); +- +- if (id_ < 0) //error +- return static_cast(id_); +- +- if (id_ != 0x0F43B675) //Cluster ID +- return E_FILE_FORMAT_INVALID; +- +- pos += len; //consume id +- +- //read cluster size +- +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } +- +- result = GetUIntLength(pReader, pos, len); +- +- if (result < 0) //error +- return static_cast(result); +- +- if (result > 0) //weird +- return E_BUFFER_NOT_FULL; +- +- //if ((pos + len) > segment_stop) +- // return E_FILE_FORMAT_INVALID; +- +- if ((pos + len) > avail) +- return E_BUFFER_NOT_FULL; +- +- const long long size = ReadUInt(pReader, pos, len); +- +- if (size < 0) //error +- return static_cast(cluster_size); +- +- if (size == 0) +- return E_FILE_FORMAT_INVALID; //TODO: verify this +- +- pos += len; //consume length of size of element +- +- const long long unknown_size = (1LL << (7 * len)) - 1; +- +- if (size != unknown_size) +- cluster_size = size; ++ { ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; + } + +- //pos points to start of payload ++ long long result = GetUIntLength(pReader, pos, len); ++ ++ if (result < 0) // error or underflow ++ return static_cast(result); ++ ++ if (result > 0) // underflow (weird) ++ return E_BUFFER_NOT_FULL; ++ ++ // if ((pos + len) > segment_stop) ++ // return E_FILE_FORMAT_INVALID; ++ ++ if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; ++ ++ const long long id_ = ReadUInt(pReader, pos, len); ++ ++ if (id_ < 0) // error ++ return static_cast(id_); ++ ++ if (id_ != 0x0F43B675) // Cluster ID ++ return E_FILE_FORMAT_INVALID; ++ ++ pos += len; // consume id ++ ++ // read cluster size ++ ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; ++ } ++ ++ result = GetUIntLength(pReader, pos, len); ++ ++ if (result < 0) // error ++ return static_cast(result); ++ ++ if (result > 0) // weird ++ return E_BUFFER_NOT_FULL; ++ ++ // if ((pos + len) > segment_stop) ++ // return E_FILE_FORMAT_INVALID; ++ ++ if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; ++ ++ const long long size = ReadUInt(pReader, pos, len); ++ ++ if (size < 0) // error ++ return static_cast(cluster_size); ++ ++ if (size == 0) ++ return E_FILE_FORMAT_INVALID; // TODO: verify this ++ ++ pos += len; // consume length of size of element ++ ++ const long long unknown_size = (1LL << (7 * len)) - 1; ++ ++ if (size != unknown_size) ++ cluster_size = size; ++ } ++ ++// pos points to start of payload + + #if 0 + len = static_cast(size_); +@@ -7086,403 +6127,376 @@ + + return E_BUFFER_NOT_FULL; + #endif + +- long long timecode = -1; +- long long new_pos = -1; +- bool bBlock = false; ++ long long timecode = -1; ++ long long new_pos = -1; ++ bool bBlock = false; + +- long long cluster_stop = (cluster_size < 0) ? -1 : pos + cluster_size; ++ long long cluster_stop = (cluster_size < 0) ? -1 : pos + cluster_size; + +- for (;;) +- { +- if ((cluster_stop >= 0) && (pos >= cluster_stop)) +- break; ++ for (;;) { ++ if ((cluster_stop >= 0) && (pos >= cluster_stop)) ++ break; + +- //Parse ID ++ // Parse ID + +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } +- +- long long result = GetUIntLength(pReader, pos, len); +- +- if (result < 0) //error +- return static_cast(result); +- +- if (result > 0) //weird +- return E_BUFFER_NOT_FULL; +- +- if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) +- return E_FILE_FORMAT_INVALID; +- +- if ((pos + len) > avail) +- return E_BUFFER_NOT_FULL; +- +- const long long id = ReadUInt(pReader, pos, len); +- +- if (id < 0) //error +- return static_cast(id); +- +- if (id == 0) +- return E_FILE_FORMAT_INVALID; +- +- //This is the distinguished set of ID's we use to determine +- //that we have exhausted the sub-element's inside the cluster +- //whose ID we parsed earlier. +- +- if (id == 0x0F43B675) //Cluster ID +- break; +- +- if (id == 0x0C53BB6B) //Cues ID +- break; +- +- pos += len; //consume ID field +- +- //Parse Size +- +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } +- +- result = GetUIntLength(pReader, pos, len); +- +- if (result < 0) //error +- return static_cast(result); +- +- if (result > 0) //weird +- return E_BUFFER_NOT_FULL; +- +- if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) +- return E_FILE_FORMAT_INVALID; +- +- if ((pos + len) > avail) +- return E_BUFFER_NOT_FULL; +- +- const long long size = ReadUInt(pReader, pos, len); +- +- if (size < 0) //error +- return static_cast(size); +- +- const long long unknown_size = (1LL << (7 * len)) - 1; +- +- if (size == unknown_size) +- return E_FILE_FORMAT_INVALID; +- +- pos += len; //consume size field +- +- if ((cluster_stop >= 0) && (pos > cluster_stop)) +- return E_FILE_FORMAT_INVALID; +- +- //pos now points to start of payload +- +- if (size == 0) //weird +- continue; +- +- if ((cluster_stop >= 0) && ((pos + size) > cluster_stop)) +- return E_FILE_FORMAT_INVALID; +- +- if (id == 0x67) //TimeCode ID +- { +- len = static_cast(size); +- +- if ((pos + size) > avail) +- return E_BUFFER_NOT_FULL; +- +- timecode = UnserializeUInt(pReader, pos, size); +- +- if (timecode < 0) //error (or underflow) +- return static_cast(timecode); +- +- new_pos = pos + size; +- +- if (bBlock) +- break; +- } +- else if (id == 0x20) //BlockGroup ID +- { +- bBlock = true; +- break; +- } +- else if (id == 0x23) //SimpleBlock ID +- { +- bBlock = true; +- break; +- } +- +- pos += size; //consume payload +- assert((cluster_stop < 0) || (pos <= cluster_stop)); +- } +- +- assert((cluster_stop < 0) || (pos <= cluster_stop)); +- +- if (timecode < 0) //no timecode found +- return E_FILE_FORMAT_INVALID; +- +- if (!bBlock) +- return E_FILE_FORMAT_INVALID; +- +- m_pos = new_pos; //designates position just beyond timecode payload +- m_timecode = timecode; // m_timecode >= 0 means we're partially loaded +- +- if (cluster_size >= 0) +- m_element_size = cluster_stop - m_element_start; +- +- return 0; +-} +- +- +-long Cluster::Parse(long long& pos, long& len) const +-{ +- long status = Load(pos, len); +- +- if (status < 0) +- return status; +- +- assert(m_pos >= m_element_start); +- assert(m_timecode >= 0); +- //assert(m_size > 0); +- //assert(m_element_size > m_size); +- +- const long long cluster_stop = +- (m_element_size < 0) ? -1 : m_element_start + m_element_size; +- +- if ((cluster_stop >= 0) && (m_pos >= cluster_stop)) +- return 1; //nothing else to do +- +- IMkvReader* const pReader = m_pSegment->m_pReader; +- +- long long total, avail; +- +- status = pReader->Length(&total, &avail); +- +- if (status < 0) //error +- return status; +- +- assert((total < 0) || (avail <= total)); +- +- pos = m_pos; +- +- for (;;) +- { +- if ((cluster_stop >= 0) && (pos >= cluster_stop)) +- break; +- +- if ((total >= 0) && (pos >= total)) +- { +- if (m_element_size < 0) +- m_element_size = pos - m_element_start; +- +- break; +- } +- +- //Parse ID +- +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } +- +- long long result = GetUIntLength(pReader, pos, len); +- +- if (result < 0) //error +- return static_cast(result); +- +- if (result > 0) //weird +- return E_BUFFER_NOT_FULL; +- +- if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) +- return E_FILE_FORMAT_INVALID; +- +- if ((pos + len) > avail) +- return E_BUFFER_NOT_FULL; +- +- const long long id = ReadUInt(pReader, pos, len); +- +- if (id < 0) //error +- return static_cast(id); +- +- if (id == 0) //weird +- return E_FILE_FORMAT_INVALID; +- +- //This is the distinguished set of ID's we use to determine +- //that we have exhausted the sub-element's inside the cluster +- //whose ID we parsed earlier. +- +- if ((id == 0x0F43B675) || (id == 0x0C53BB6B)) //Cluster or Cues ID +- { +- if (m_element_size < 0) +- m_element_size = pos - m_element_start; +- +- break; +- } +- +- pos += len; //consume ID field +- +- //Parse Size +- +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } +- +- result = GetUIntLength(pReader, pos, len); +- +- if (result < 0) //error +- return static_cast(result); +- +- if (result > 0) //weird +- return E_BUFFER_NOT_FULL; +- +- if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) +- return E_FILE_FORMAT_INVALID; +- +- if ((pos + len) > avail) +- return E_BUFFER_NOT_FULL; +- +- const long long size = ReadUInt(pReader, pos, len); +- +- if (size < 0) //error +- return static_cast(size); +- +- const long long unknown_size = (1LL << (7 * len)) - 1; +- +- if (size == unknown_size) +- return E_FILE_FORMAT_INVALID; +- +- pos += len; //consume size field +- +- if ((cluster_stop >= 0) && (pos > cluster_stop)) +- return E_FILE_FORMAT_INVALID; +- +- //pos now points to start of payload +- +- if (size == 0) //weird +- continue; +- +- //const long long block_start = pos; +- const long long block_stop = pos + size; +- +- if (cluster_stop >= 0) +- { +- if (block_stop > cluster_stop) +- { +- if ((id == 0x20) || (id == 0x23)) +- return E_FILE_FORMAT_INVALID; +- +- pos = cluster_stop; +- break; +- } +- } +- else if ((total >= 0) && (block_stop > total)) +- { +- m_element_size = total - m_element_start; +- pos = total; +- break; +- } +- else if (block_stop > avail) +- { +- len = static_cast(size); +- return E_BUFFER_NOT_FULL; +- } +- +- Cluster* const this_ = const_cast(this); +- +- if (id == 0x20) //BlockGroup +- return this_->ParseBlockGroup(size, pos, len); +- +- if (id == 0x23) //SimpleBlock +- return this_->ParseSimpleBlock(size, pos, len); +- +- pos += size; //consume payload +- assert((cluster_stop < 0) || (pos <= cluster_stop)); +- } +- +- assert(m_element_size > 0); +- +- m_pos = pos; +- assert((cluster_stop < 0) || (m_pos <= cluster_stop)); +- +- if (m_entries_count > 0) +- { +- const long idx = m_entries_count - 1; +- +- const BlockEntry* const pLast = m_entries[idx]; +- assert(pLast); +- +- const Block* const pBlock = pLast->GetBlock(); +- assert(pBlock); +- +- const long long start = pBlock->m_start; +- +- if ((total >= 0) && (start > total)) +- return -1; //defend against trucated stream +- +- const long long size = pBlock->m_size; +- +- const long long stop = start + size; +- assert((cluster_stop < 0) || (stop <= cluster_stop)); +- +- if ((total >= 0) && (stop > total)) +- return -1; //defend against trucated stream +- } +- +- return 1; //no more entries +-} +- +- +-long Cluster::ParseSimpleBlock( +- long long block_size, +- long long& pos, +- long& len) +-{ +- const long long block_start = pos; +- const long long block_stop = pos + block_size; +- +- IMkvReader* const pReader = m_pSegment->m_pReader; +- +- long long total, avail; +- +- long status = pReader->Length(&total, &avail); +- +- if (status < 0) //error +- return status; +- +- assert((total < 0) || (avail <= total)); +- +- //parse track number +- +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; + } + + long long result = GetUIntLength(pReader, pos, len); + +- if (result < 0) //error +- return static_cast(result); ++ if (result < 0) // error ++ return static_cast(result); + +- if (result > 0) //weird +- return E_BUFFER_NOT_FULL; ++ if (result > 0) // weird ++ return E_BUFFER_NOT_FULL; + +- if ((pos + len) > block_stop) +- return E_FILE_FORMAT_INVALID; ++ if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) ++ return E_FILE_FORMAT_INVALID; + + if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; ++ ++ const long long id = ReadUInt(pReader, pos, len); ++ ++ if (id < 0) // error ++ return static_cast(id); ++ ++ if (id == 0) ++ return E_FILE_FORMAT_INVALID; ++ ++ // This is the distinguished set of ID's we use to determine ++ // that we have exhausted the sub-element's inside the cluster ++ // whose ID we parsed earlier. ++ ++ if (id == 0x0F43B675) // Cluster ID ++ break; ++ ++ if (id == 0x0C53BB6B) // Cues ID ++ break; ++ ++ pos += len; // consume ID field ++ ++ // Parse Size ++ ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; ++ } ++ ++ result = GetUIntLength(pReader, pos, len); ++ ++ if (result < 0) // error ++ return static_cast(result); ++ ++ if (result > 0) // weird ++ return E_BUFFER_NOT_FULL; ++ ++ if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) ++ return E_FILE_FORMAT_INVALID; ++ ++ if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; ++ ++ const long long size = ReadUInt(pReader, pos, len); ++ ++ if (size < 0) // error ++ return static_cast(size); ++ ++ const long long unknown_size = (1LL << (7 * len)) - 1; ++ ++ if (size == unknown_size) ++ return E_FILE_FORMAT_INVALID; ++ ++ pos += len; // consume size field ++ ++ if ((cluster_stop >= 0) && (pos > cluster_stop)) ++ return E_FILE_FORMAT_INVALID; ++ ++ // pos now points to start of payload ++ ++ if (size == 0) // weird ++ continue; ++ ++ if ((cluster_stop >= 0) && ((pos + size) > cluster_stop)) ++ return E_FILE_FORMAT_INVALID; ++ ++ if (id == 0x67) { // TimeCode ID ++ len = static_cast(size); ++ ++ if ((pos + size) > avail) + return E_BUFFER_NOT_FULL; + +- const long long track = ReadUInt(pReader, pos, len); ++ timecode = UnserializeUInt(pReader, pos, size); + +- if (track < 0) //error +- return static_cast(track); ++ if (timecode < 0) // error (or underflow) ++ return static_cast(timecode); + +- if (track == 0) +- return E_FILE_FORMAT_INVALID; ++ new_pos = pos + size; ++ ++ if (bBlock) ++ break; ++ } else if (id == 0x20) { // BlockGroup ID ++ bBlock = true; ++ break; ++ } else if (id == 0x23) { // SimpleBlock ID ++ bBlock = true; ++ break; ++ } ++ ++ pos += size; // consume payload ++ assert((cluster_stop < 0) || (pos <= cluster_stop)); ++ } ++ ++ assert((cluster_stop < 0) || (pos <= cluster_stop)); ++ ++ if (timecode < 0) // no timecode found ++ return E_FILE_FORMAT_INVALID; ++ ++ if (!bBlock) ++ return E_FILE_FORMAT_INVALID; ++ ++ m_pos = new_pos; // designates position just beyond timecode payload ++ m_timecode = timecode; // m_timecode >= 0 means we're partially loaded ++ ++ if (cluster_size >= 0) ++ m_element_size = cluster_stop - m_element_start; ++ ++ return 0; ++} ++ ++long Cluster::Parse(long long& pos, long& len) const { ++ long status = Load(pos, len); ++ ++ if (status < 0) ++ return status; ++ ++ assert(m_pos >= m_element_start); ++ assert(m_timecode >= 0); ++ // assert(m_size > 0); ++ // assert(m_element_size > m_size); ++ ++ const long long cluster_stop = ++ (m_element_size < 0) ? -1 : m_element_start + m_element_size; ++ ++ if ((cluster_stop >= 0) && (m_pos >= cluster_stop)) ++ return 1; // nothing else to do ++ ++ IMkvReader* const pReader = m_pSegment->m_pReader; ++ ++ long long total, avail; ++ ++ status = pReader->Length(&total, &avail); ++ ++ if (status < 0) // error ++ return status; ++ ++ assert((total < 0) || (avail <= total)); ++ ++ pos = m_pos; ++ ++ for (;;) { ++ if ((cluster_stop >= 0) && (pos >= cluster_stop)) ++ break; ++ ++ if ((total >= 0) && (pos >= total)) { ++ if (m_element_size < 0) ++ m_element_size = pos - m_element_start; ++ ++ break; ++ } ++ ++ // Parse ID ++ ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; ++ } ++ ++ long long result = GetUIntLength(pReader, pos, len); ++ ++ if (result < 0) // error ++ return static_cast(result); ++ ++ if (result > 0) // weird ++ return E_BUFFER_NOT_FULL; ++ ++ if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) ++ return E_FILE_FORMAT_INVALID; ++ ++ if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; ++ ++ const long long id = ReadUInt(pReader, pos, len); ++ ++ if (id < 0) // error ++ return static_cast(id); ++ ++ if (id == 0) // weird ++ return E_FILE_FORMAT_INVALID; ++ ++ // This is the distinguished set of ID's we use to determine ++ // that we have exhausted the sub-element's inside the cluster ++ // whose ID we parsed earlier. ++ ++ if ((id == 0x0F43B675) || (id == 0x0C53BB6B)) { // Cluster or Cues ID ++ if (m_element_size < 0) ++ m_element_size = pos - m_element_start; ++ ++ break; ++ } ++ ++ pos += len; // consume ID field ++ ++ // Parse Size ++ ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; ++ } ++ ++ result = GetUIntLength(pReader, pos, len); ++ ++ if (result < 0) // error ++ return static_cast(result); ++ ++ if (result > 0) // weird ++ return E_BUFFER_NOT_FULL; ++ ++ if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) ++ return E_FILE_FORMAT_INVALID; ++ ++ if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; ++ ++ const long long size = ReadUInt(pReader, pos, len); ++ ++ if (size < 0) // error ++ return static_cast(size); ++ ++ const long long unknown_size = (1LL << (7 * len)) - 1; ++ ++ if (size == unknown_size) ++ return E_FILE_FORMAT_INVALID; ++ ++ pos += len; // consume size field ++ ++ if ((cluster_stop >= 0) && (pos > cluster_stop)) ++ return E_FILE_FORMAT_INVALID; ++ ++ // pos now points to start of payload ++ ++ if (size == 0) // weird ++ continue; ++ ++ // const long long block_start = pos; ++ const long long block_stop = pos + size; ++ ++ if (cluster_stop >= 0) { ++ if (block_stop > cluster_stop) { ++ if ((id == 0x20) || (id == 0x23)) ++ return E_FILE_FORMAT_INVALID; ++ ++ pos = cluster_stop; ++ break; ++ } ++ } else if ((total >= 0) && (block_stop > total)) { ++ m_element_size = total - m_element_start; ++ pos = total; ++ break; ++ } else if (block_stop > avail) { ++ len = static_cast(size); ++ return E_BUFFER_NOT_FULL; ++ } ++ ++ Cluster* const this_ = const_cast(this); ++ ++ if (id == 0x20) // BlockGroup ++ return this_->ParseBlockGroup(size, pos, len); ++ ++ if (id == 0x23) // SimpleBlock ++ return this_->ParseSimpleBlock(size, pos, len); ++ ++ pos += size; // consume payload ++ assert((cluster_stop < 0) || (pos <= cluster_stop)); ++ } ++ ++ assert(m_element_size > 0); ++ ++ m_pos = pos; ++ assert((cluster_stop < 0) || (m_pos <= cluster_stop)); ++ ++ if (m_entries_count > 0) { ++ const long idx = m_entries_count - 1; ++ ++ const BlockEntry* const pLast = m_entries[idx]; ++ assert(pLast); ++ ++ const Block* const pBlock = pLast->GetBlock(); ++ assert(pBlock); ++ ++ const long long start = pBlock->m_start; ++ ++ if ((total >= 0) && (start > total)) ++ return -1; // defend against trucated stream ++ ++ const long long size = pBlock->m_size; ++ ++ const long long stop = start + size; ++ assert((cluster_stop < 0) || (stop <= cluster_stop)); ++ ++ if ((total >= 0) && (stop > total)) ++ return -1; // defend against trucated stream ++ } ++ ++ return 1; // no more entries ++} ++ ++long Cluster::ParseSimpleBlock(long long block_size, long long& pos, ++ long& len) { ++ const long long block_start = pos; ++ const long long block_stop = pos + block_size; ++ ++ IMkvReader* const pReader = m_pSegment->m_pReader; ++ ++ long long total, avail; ++ ++ long status = pReader->Length(&total, &avail); ++ ++ if (status < 0) // error ++ return status; ++ ++ assert((total < 0) || (avail <= total)); ++ ++ // parse track number ++ ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; ++ } ++ ++ long long result = GetUIntLength(pReader, pos, len); ++ ++ if (result < 0) // error ++ return static_cast(result); ++ ++ if (result > 0) // weird ++ return E_BUFFER_NOT_FULL; ++ ++ if ((pos + len) > block_stop) ++ return E_FILE_FORMAT_INVALID; ++ ++ if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; ++ ++ const long long track = ReadUInt(pReader, pos, len); ++ ++ if (track < 0) // error ++ return static_cast(track); ++ ++ if (track == 0) ++ return E_FILE_FORMAT_INVALID; + + #if 0 + //TODO(matthewjheaney) +@@ -7514,228 +6528,208 @@ + + return E_FILE_FORMAT_INVALID; + #endif + +- pos += len; //consume track number ++ pos += len; // consume track number + +- if ((pos + 2) > block_stop) +- return E_FILE_FORMAT_INVALID; ++ if ((pos + 2) > block_stop) ++ return E_FILE_FORMAT_INVALID; + +- if ((pos + 2) > avail) +- { +- len = 2; +- return E_BUFFER_NOT_FULL; +- } ++ if ((pos + 2) > avail) { ++ len = 2; ++ return E_BUFFER_NOT_FULL; ++ } + +- pos += 2; //consume timecode ++ pos += 2; // consume timecode + +- if ((pos + 1) > block_stop) +- return E_FILE_FORMAT_INVALID; ++ if ((pos + 1) > block_stop) ++ return E_FILE_FORMAT_INVALID; + +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; ++ } + +- unsigned char flags; ++ unsigned char flags; + +- status = pReader->Read(pos, 1, &flags); ++ status = pReader->Read(pos, 1, &flags); + +- if (status < 0) //error or underflow +- { +- len = 1; +- return status; +- } ++ if (status < 0) { // error or underflow ++ len = 1; ++ return status; ++ } + +- ++pos; //consume flags byte +- assert(pos <= avail); ++ ++pos; // consume flags byte ++ assert(pos <= avail); + +- if (pos >= block_stop) +- return E_FILE_FORMAT_INVALID; ++ if (pos >= block_stop) ++ return E_FILE_FORMAT_INVALID; + +- const int lacing = int(flags & 0x06) >> 1; ++ const int lacing = int(flags & 0x06) >> 1; + +- if ((lacing != 0) && (block_stop > avail)) +- { +- len = static_cast(block_stop - pos); +- return E_BUFFER_NOT_FULL; +- } ++ if ((lacing != 0) && (block_stop > avail)) { ++ len = static_cast(block_stop - pos); ++ return E_BUFFER_NOT_FULL; ++ } + +- status = CreateBlock(0x23, //simple block id +- block_start, block_size, +- 0); //DiscardPadding ++ status = CreateBlock(0x23, // simple block id ++ block_start, block_size, ++ 0); // DiscardPadding + +- if (status != 0) +- return status; ++ if (status != 0) ++ return status; + +- m_pos = block_stop; ++ m_pos = block_stop; + +- return 0; //success ++ return 0; // success + } + ++long Cluster::ParseBlockGroup(long long payload_size, long long& pos, ++ long& len) { ++ const long long payload_start = pos; ++ const long long payload_stop = pos + payload_size; + +-long Cluster::ParseBlockGroup( +- long long payload_size, +- long long& pos, +- long& len) +-{ +- const long long payload_start = pos; +- const long long payload_stop = pos + payload_size; ++ IMkvReader* const pReader = m_pSegment->m_pReader; + +- IMkvReader* const pReader = m_pSegment->m_pReader; ++ long long total, avail; + +- long long total, avail; ++ long status = pReader->Length(&total, &avail); + +- long status = pReader->Length(&total, &avail); ++ if (status < 0) // error ++ return status; + +- if (status < 0) //error +- return status; ++ assert((total < 0) || (avail <= total)); + +- assert((total < 0) || (avail <= total)); ++ if ((total >= 0) && (payload_stop > total)) ++ return E_FILE_FORMAT_INVALID; + +- if ((total >= 0) && (payload_stop > total)) +- return E_FILE_FORMAT_INVALID; ++ if (payload_stop > avail) { ++ len = static_cast(payload_size); ++ return E_BUFFER_NOT_FULL; ++ } + +- if (payload_stop > avail) +- { +- len = static_cast(payload_size); +- return E_BUFFER_NOT_FULL; ++ long long discard_padding = 0; ++ ++ while (pos < payload_stop) { ++ // parse sub-block element ID ++ ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; + } + +- long long discard_padding = 0; ++ long long result = GetUIntLength(pReader, pos, len); + +- while (pos < payload_stop) +- { +- //parse sub-block element ID ++ if (result < 0) // error ++ return static_cast(result); + +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } ++ if (result > 0) // weird ++ return E_BUFFER_NOT_FULL; + +- long long result = GetUIntLength(pReader, pos, len); ++ if ((pos + len) > payload_stop) ++ return E_FILE_FORMAT_INVALID; + +- if (result < 0) //error +- return static_cast(result); ++ if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; + +- if (result > 0) //weird +- return E_BUFFER_NOT_FULL; ++ const long long id = ReadUInt(pReader, pos, len); + +- if ((pos + len) > payload_stop) +- return E_FILE_FORMAT_INVALID; ++ if (id < 0) // error ++ return static_cast(id); + +- if ((pos + len) > avail) +- return E_BUFFER_NOT_FULL; ++ if (id == 0) // not a value ID ++ return E_FILE_FORMAT_INVALID; + +- const long long id = ReadUInt(pReader, pos, len); ++ pos += len; // consume ID field + +- if (id < 0) //error +- return static_cast(id); ++ // Parse Size + +- if (id == 0) //not a value ID +- return E_FILE_FORMAT_INVALID; ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; ++ } + +- pos += len; //consume ID field ++ result = GetUIntLength(pReader, pos, len); + +- //Parse Size ++ if (result < 0) // error ++ return static_cast(result); + +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } ++ if (result > 0) // weird ++ return E_BUFFER_NOT_FULL; + +- result = GetUIntLength(pReader, pos, len); ++ if ((pos + len) > payload_stop) ++ return E_FILE_FORMAT_INVALID; + +- if (result < 0) //error +- return static_cast(result); ++ if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; + +- if (result > 0) //weird +- return E_BUFFER_NOT_FULL; ++ const long long size = ReadUInt(pReader, pos, len); + +- if ((pos + len) > payload_stop) +- return E_FILE_FORMAT_INVALID; ++ if (size < 0) // error ++ return static_cast(size); + +- if ((pos + len) > avail) +- return E_BUFFER_NOT_FULL; ++ pos += len; // consume size field + +- const long long size = ReadUInt(pReader, pos, len); ++ // pos now points to start of sub-block group payload + +- if (size < 0) //error +- return static_cast(size); ++ if (pos > payload_stop) ++ return E_FILE_FORMAT_INVALID; + +- pos += len; //consume size field ++ if (size == 0) // weird ++ continue; + +- //pos now points to start of sub-block group payload ++ const long long unknown_size = (1LL << (7 * len)) - 1; + +- if (pos > payload_stop) +- return E_FILE_FORMAT_INVALID; ++ if (size == unknown_size) ++ return E_FILE_FORMAT_INVALID; + +- if (size == 0) //weird +- continue; ++ if (id == 0x35A2) { // DiscardPadding ++ status = UnserializeInt(pReader, pos, size, discard_padding); + +- const long long unknown_size = (1LL << (7 * len)) - 1; ++ if (status < 0) // error ++ return status; ++ } + +- if (size == unknown_size) +- return E_FILE_FORMAT_INVALID; ++ if (id != 0x21) { // sub-part of BlockGroup is not a Block ++ pos += size; // consume sub-part of block group + +- if (id == 0x35A2) //DiscardPadding +- { +- result = GetUIntLength(pReader, pos, len); ++ if (pos > payload_stop) ++ return E_FILE_FORMAT_INVALID; + +- if (result < 0) //error +- return static_cast(result); ++ continue; ++ } + +- status = UnserializeInt(pReader, pos, len, discard_padding); ++ const long long block_stop = pos + size; + +- if (status < 0) //error +- return status; +- } ++ if (block_stop > payload_stop) ++ return E_FILE_FORMAT_INVALID; + +- if (id != 0x21) //sub-part of BlockGroup is not a Block +- { +- pos += size; //consume sub-part of block group ++ // parse track number + +- if (pos > payload_stop) +- return E_FILE_FORMAT_INVALID; ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; ++ } + +- continue; +- } ++ result = GetUIntLength(pReader, pos, len); + +- const long long block_stop = pos + size; ++ if (result < 0) // error ++ return static_cast(result); + +- if (block_stop > payload_stop) +- return E_FILE_FORMAT_INVALID; ++ if (result > 0) // weird ++ return E_BUFFER_NOT_FULL; + +- //parse track number ++ if ((pos + len) > block_stop) ++ return E_FILE_FORMAT_INVALID; + +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } ++ if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; + +- result = GetUIntLength(pReader, pos, len); ++ const long long track = ReadUInt(pReader, pos, len); + +- if (result < 0) //error +- return static_cast(result); ++ if (track < 0) // error ++ return static_cast(track); + +- if (result > 0) //weird +- return E_BUFFER_NOT_FULL; +- +- if ((pos + len) > block_stop) +- return E_FILE_FORMAT_INVALID; +- +- if ((pos + len) > avail) +- return E_BUFFER_NOT_FULL; +- +- const long long track = ReadUInt(pReader, pos, len); +- +- if (track < 0) //error +- return static_cast(track); +- +- if (track == 0) +- return E_FILE_FORMAT_INVALID; ++ if (track == 0) ++ return E_FILE_FORMAT_INVALID; + + #if 0 + //TODO(matthewjheaney) +@@ -7767,213 +6761,173 @@ + + return E_FILE_FORMAT_INVALID; + #endif + +- pos += len; //consume track number ++ pos += len; // consume track number + +- if ((pos + 2) > block_stop) +- return E_FILE_FORMAT_INVALID; ++ if ((pos + 2) > block_stop) ++ return E_FILE_FORMAT_INVALID; + +- if ((pos + 2) > avail) +- { +- len = 2; +- return E_BUFFER_NOT_FULL; +- } +- +- pos += 2; //consume timecode +- +- if ((pos + 1) > block_stop) +- return E_FILE_FORMAT_INVALID; +- +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } +- +- unsigned char flags; +- +- status = pReader->Read(pos, 1, &flags); +- +- if (status < 0) //error or underflow +- { +- len = 1; +- return status; +- } +- +- ++pos; //consume flags byte +- assert(pos <= avail); +- +- if (pos >= block_stop) +- return E_FILE_FORMAT_INVALID; +- +- const int lacing = int(flags & 0x06) >> 1; +- +- if ((lacing != 0) && (block_stop > avail)) +- { +- len = static_cast(block_stop - pos); +- return E_BUFFER_NOT_FULL; +- } +- +- pos = block_stop; //consume block-part of block group +- assert(pos <= payload_stop); ++ if ((pos + 2) > avail) { ++ len = 2; ++ return E_BUFFER_NOT_FULL; + } + +- assert(pos == payload_stop); ++ pos += 2; // consume timecode + +- status = CreateBlock(0x20, //BlockGroup ID +- payload_start, payload_size, +- discard_padding); +- if (status != 0) +- return status; ++ if ((pos + 1) > block_stop) ++ return E_FILE_FORMAT_INVALID; + +- m_pos = payload_stop; +- +- return 0; //success +-} +- +- +-long Cluster::GetEntry(long index, const mkvparser::BlockEntry*& pEntry) const +-{ +- assert(m_pos >= m_element_start); +- +- pEntry = NULL; +- +- if (index < 0) +- return -1; //generic error +- +- if (m_entries_count < 0) +- return E_BUFFER_NOT_FULL; +- +- assert(m_entries); +- assert(m_entries_size > 0); +- assert(m_entries_count <= m_entries_size); +- +- if (index < m_entries_count) +- { +- pEntry = m_entries[index]; +- assert(pEntry); +- +- return 1; //found entry ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; + } + +- if (m_element_size < 0) //we don't know cluster end yet +- return E_BUFFER_NOT_FULL; //underflow ++ unsigned char flags; + +- const long long element_stop = m_element_start + m_element_size; ++ status = pReader->Read(pos, 1, &flags); + +- if (m_pos >= element_stop) +- return 0; //nothing left to parse +- +- return E_BUFFER_NOT_FULL; //underflow, since more remains to be parsed +-} +- +- +-Cluster* Cluster::Create( +- Segment* pSegment, +- long idx, +- long long off) +- //long long element_size) +-{ +- assert(pSegment); +- assert(off >= 0); +- +- const long long element_start = pSegment->m_start + off; +- +- Cluster* const pCluster = new Cluster(pSegment, +- idx, +- element_start); +- //element_size); +- assert(pCluster); +- +- return pCluster; +-} +- +- +-Cluster::Cluster() : +- m_pSegment(NULL), +- m_element_start(0), +- m_index(0), +- m_pos(0), +- m_element_size(0), +- m_timecode(0), +- m_entries(NULL), +- m_entries_size(0), +- m_entries_count(0) //means ""no entries"" +-{ +-} +- +- +-Cluster::Cluster( +- Segment* pSegment, +- long idx, +- long long element_start +- /* long long element_size */ ) : +- m_pSegment(pSegment), +- m_element_start(element_start), +- m_index(idx), +- m_pos(element_start), +- m_element_size(-1 /* element_size */ ), +- m_timecode(-1), +- m_entries(NULL), +- m_entries_size(0), +- m_entries_count(-1) //means ""has not been parsed yet"" +-{ +-} +- +- +-Cluster::~Cluster() +-{ +- if (m_entries_count <= 0) +- return; +- +- BlockEntry** i = m_entries; +- BlockEntry** const j = m_entries + m_entries_count; +- +- while (i != j) +- { +- BlockEntry* p = *i++; +- assert(p); +- +- delete p; ++ if (status < 0) { // error or underflow ++ len = 1; ++ return status; + } + +- delete[] m_entries; ++ ++pos; // consume flags byte ++ assert(pos <= avail); ++ ++ if (pos >= block_stop) ++ return E_FILE_FORMAT_INVALID; ++ ++ const int lacing = int(flags & 0x06) >> 1; ++ ++ if ((lacing != 0) && (block_stop > avail)) { ++ len = static_cast(block_stop - pos); ++ return E_BUFFER_NOT_FULL; ++ } ++ ++ pos = block_stop; // consume block-part of block group ++ assert(pos <= payload_stop); ++ } ++ ++ assert(pos == payload_stop); ++ ++ status = CreateBlock(0x20, // BlockGroup ID ++ payload_start, payload_size, discard_padding); ++ if (status != 0) ++ return status; ++ ++ m_pos = payload_stop; ++ ++ return 0; // success + } + ++long Cluster::GetEntry(long index, const mkvparser::BlockEntry*& pEntry) const { ++ assert(m_pos >= m_element_start); + +-bool Cluster::EOS() const ++ pEntry = NULL; ++ ++ if (index < 0) ++ return -1; // generic error ++ ++ if (m_entries_count < 0) ++ return E_BUFFER_NOT_FULL; ++ ++ assert(m_entries); ++ assert(m_entries_size > 0); ++ assert(m_entries_count <= m_entries_size); ++ ++ if (index < m_entries_count) { ++ pEntry = m_entries[index]; ++ assert(pEntry); ++ ++ return 1; // found entry ++ } ++ ++ if (m_element_size < 0) // we don't know cluster end yet ++ return E_BUFFER_NOT_FULL; // underflow ++ ++ const long long element_stop = m_element_start + m_element_size; ++ ++ if (m_pos >= element_stop) ++ return 0; // nothing left to parse ++ ++ return E_BUFFER_NOT_FULL; // underflow, since more remains to be parsed ++} ++ ++Cluster* Cluster::Create(Segment* pSegment, long idx, long long off) ++// long long element_size) + { +- return (m_pSegment == NULL); ++ assert(pSegment); ++ assert(off >= 0); ++ ++ const long long element_start = pSegment->m_start + off; ++ ++ Cluster* const pCluster = new Cluster(pSegment, idx, element_start); ++ // element_size); ++ assert(pCluster); ++ ++ return pCluster; + } + ++Cluster::Cluster() ++ : m_pSegment(NULL), ++ m_element_start(0), ++ m_index(0), ++ m_pos(0), ++ m_element_size(0), ++ m_timecode(0), ++ m_entries(NULL), ++ m_entries_size(0), ++ m_entries_count(0) // means ""no entries"" ++{} + +-long Cluster::GetIndex() const +-{ +- return m_index; ++Cluster::Cluster(Segment* pSegment, long idx, long long element_start ++ /* long long element_size */) ++ : m_pSegment(pSegment), ++ m_element_start(element_start), ++ m_index(idx), ++ m_pos(element_start), ++ m_element_size(-1 /* element_size */), ++ m_timecode(-1), ++ m_entries(NULL), ++ m_entries_size(0), ++ m_entries_count(-1) // means ""has not been parsed yet"" ++{} ++ ++Cluster::~Cluster() { ++ if (m_entries_count <= 0) ++ return; ++ ++ BlockEntry** i = m_entries; ++ BlockEntry** const j = m_entries + m_entries_count; ++ ++ while (i != j) { ++ BlockEntry* p = *i++; ++ assert(p); ++ ++ delete p; ++ } ++ ++ delete[] m_entries; + } + ++bool Cluster::EOS() const { return (m_pSegment == NULL); } + +-long long Cluster::GetPosition() const +-{ +- const long long pos = m_element_start - m_pSegment->m_start; +- assert(pos >= 0); ++long Cluster::GetIndex() const { return m_index; } + +- return pos; ++long long Cluster::GetPosition() const { ++ const long long pos = m_element_start - m_pSegment->m_start; ++ assert(pos >= 0); ++ ++ return pos; + } + +- +-long long Cluster::GetElementSize() const +-{ +- return m_element_size; +-} +- ++long long Cluster::GetElementSize() const { return m_element_size; } + + #if 0 + bool Cluster::HasBlockEntries( + const Segment* pSegment, +- long long off) //relative to start of segment payload +-{ ++ long long off) { + assert(pSegment); +- assert(off >= 0); //relative to segment ++ assert(off >= 0); //relative to start of segment payload + + IMkvReader* const pReader = pSegment->m_pReader; + +@@ -8030,631 +6984,558 @@ + + } + #endif + +- + long Cluster::HasBlockEntries( + const Segment* pSegment, +- long long off, //relative to start of segment payload +- long long& pos, +- long& len) +-{ +- assert(pSegment); +- assert(off >= 0); //relative to segment ++ long long off, // relative to start of segment payload ++ long long& pos, long& len) { ++ assert(pSegment); ++ assert(off >= 0); // relative to segment + +- IMkvReader* const pReader = pSegment->m_pReader; ++ IMkvReader* const pReader = pSegment->m_pReader; + +- long long total, avail; ++ long long total, avail; + +- long status = pReader->Length(&total, &avail); ++ long status = pReader->Length(&total, &avail); + +- if (status < 0) //error +- return status; ++ if (status < 0) // error ++ return status; + +- assert((total < 0) || (avail <= total)); ++ assert((total < 0) || (avail <= total)); + +- pos = pSegment->m_start + off; //absolute ++ pos = pSegment->m_start + off; // absolute + +- if ((total >= 0) && (pos >= total)) +- return 0; //we don't even have a complete cluster ++ if ((total >= 0) && (pos >= total)) ++ return 0; // we don't even have a complete cluster + +- const long long segment_stop = +- (pSegment->m_size < 0) ? -1 : pSegment->m_start + pSegment->m_size; ++ const long long segment_stop = ++ (pSegment->m_size < 0) ? -1 : pSegment->m_start + pSegment->m_size; + +- long long cluster_stop = -1; //interpreted later to mean ""unknown size"" ++ long long cluster_stop = -1; // interpreted later to mean ""unknown size"" + +- { +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } +- +- long long result = GetUIntLength(pReader, pos, len); +- +- if (result < 0) //error +- return static_cast(result); +- +- if (result > 0) //need more data +- return E_BUFFER_NOT_FULL; +- +- if ((segment_stop >= 0) && ((pos + len) > segment_stop)) +- return E_FILE_FORMAT_INVALID; +- +- if ((total >= 0) && ((pos + len) > total)) +- return 0; +- +- if ((pos + len) > avail) +- return E_BUFFER_NOT_FULL; +- +- const long long id = ReadUInt(pReader, pos, len); +- +- if (id < 0) //error +- return static_cast(id); +- +- if (id != 0x0F43B675) //weird: not cluster ID +- return -1; //generic error +- +- pos += len; //consume Cluster ID field +- +- //read size field +- +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } +- +- result = GetUIntLength(pReader, pos, len); +- +- if (result < 0) //error +- return static_cast(result); +- +- if (result > 0) //weird +- return E_BUFFER_NOT_FULL; +- +- if ((segment_stop >= 0) && ((pos + len) > segment_stop)) +- return E_FILE_FORMAT_INVALID; +- +- if ((total >= 0) && ((pos + len) > total)) +- return 0; +- +- if ((pos + len) > avail) +- return E_BUFFER_NOT_FULL; +- +- const long long size = ReadUInt(pReader, pos, len); +- +- if (size < 0) //error +- return static_cast(size); +- +- if (size == 0) +- return 0; //cluster does not have entries +- +- pos += len; //consume size field +- +- //pos now points to start of payload +- +- const long long unknown_size = (1LL << (7 * len)) - 1; +- +- if (size != unknown_size) +- { +- cluster_stop = pos + size; +- assert(cluster_stop >= 0); +- +- if ((segment_stop >= 0) && (cluster_stop > segment_stop)) +- return E_FILE_FORMAT_INVALID; +- +- if ((total >= 0) && (cluster_stop > total)) +- //return E_FILE_FORMAT_INVALID; //too conservative +- return 0; //cluster does not have any entries +- } ++ { ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; + } + +- for (;;) +- { +- if ((cluster_stop >= 0) && (pos >= cluster_stop)) +- return 0; //no entries detected ++ long long result = GetUIntLength(pReader, pos, len); + +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } ++ if (result < 0) // error ++ return static_cast(result); + +- long long result = GetUIntLength(pReader, pos, len); ++ if (result > 0) // need more data ++ return E_BUFFER_NOT_FULL; + +- if (result < 0) //error +- return static_cast(result); ++ if ((segment_stop >= 0) && ((pos + len) > segment_stop)) ++ return E_FILE_FORMAT_INVALID; + +- if (result > 0) //need more data +- return E_BUFFER_NOT_FULL; ++ if ((total >= 0) && ((pos + len) > total)) ++ return 0; + +- if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) +- return E_FILE_FORMAT_INVALID; ++ if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; + +- if ((pos + len) > avail) +- return E_BUFFER_NOT_FULL; ++ const long long id = ReadUInt(pReader, pos, len); + +- const long long id = ReadUInt(pReader, pos, len); ++ if (id < 0) // error ++ return static_cast(id); + +- if (id < 0) //error +- return static_cast(id); ++ if (id != 0x0F43B675) // weird: not cluster ID ++ return -1; // generic error + +- //This is the distinguished set of ID's we use to determine +- //that we have exhausted the sub-element's inside the cluster +- //whose ID we parsed earlier. ++ pos += len; // consume Cluster ID field + +- if (id == 0x0F43B675) //Cluster ID +- return 0; //no entries found ++ // read size field + +- if (id == 0x0C53BB6B) //Cues ID +- return 0; //no entries found +- +- pos += len; //consume id field +- +- if ((cluster_stop >= 0) && (pos >= cluster_stop)) +- return E_FILE_FORMAT_INVALID; +- +- //read size field +- +- if ((pos + 1) > avail) +- { +- len = 1; +- return E_BUFFER_NOT_FULL; +- } +- +- result = GetUIntLength(pReader, pos, len); +- +- if (result < 0) //error +- return static_cast(result); +- +- if (result > 0) //underflow +- return E_BUFFER_NOT_FULL; +- +- if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) +- return E_FILE_FORMAT_INVALID; +- +- if ((pos + len) > avail) +- return E_BUFFER_NOT_FULL; +- +- const long long size = ReadUInt(pReader, pos, len); +- +- if (size < 0) //error +- return static_cast(size); +- +- pos += len; //consume size field +- +- //pos now points to start of payload +- +- if ((cluster_stop >= 0) && (pos > cluster_stop)) +- return E_FILE_FORMAT_INVALID; +- +- if (size == 0) //weird +- continue; +- +- const long long unknown_size = (1LL << (7 * len)) - 1; +- +- if (size == unknown_size) +- return E_FILE_FORMAT_INVALID; //not supported inside cluster +- +- if ((cluster_stop >= 0) && ((pos + size) > cluster_stop)) +- return E_FILE_FORMAT_INVALID; +- +- if (id == 0x20) //BlockGroup ID +- return 1; //have at least one entry +- +- if (id == 0x23) //SimpleBlock ID +- return 1; //have at least one entry +- +- pos += size; //consume payload +- assert((cluster_stop < 0) || (pos <= cluster_stop)); ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; + } ++ ++ result = GetUIntLength(pReader, pos, len); ++ ++ if (result < 0) // error ++ return static_cast(result); ++ ++ if (result > 0) // weird ++ return E_BUFFER_NOT_FULL; ++ ++ if ((segment_stop >= 0) && ((pos + len) > segment_stop)) ++ return E_FILE_FORMAT_INVALID; ++ ++ if ((total >= 0) && ((pos + len) > total)) ++ return 0; ++ ++ if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; ++ ++ const long long size = ReadUInt(pReader, pos, len); ++ ++ if (size < 0) // error ++ return static_cast(size); ++ ++ if (size == 0) ++ return 0; // cluster does not have entries ++ ++ pos += len; // consume size field ++ ++ // pos now points to start of payload ++ ++ const long long unknown_size = (1LL << (7 * len)) - 1; ++ ++ if (size != unknown_size) { ++ cluster_stop = pos + size; ++ assert(cluster_stop >= 0); ++ ++ if ((segment_stop >= 0) && (cluster_stop > segment_stop)) ++ return E_FILE_FORMAT_INVALID; ++ ++ if ((total >= 0) && (cluster_stop > total)) ++ // return E_FILE_FORMAT_INVALID; //too conservative ++ return 0; // cluster does not have any entries ++ } ++ } ++ ++ for (;;) { ++ if ((cluster_stop >= 0) && (pos >= cluster_stop)) ++ return 0; // no entries detected ++ ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; ++ } ++ ++ long long result = GetUIntLength(pReader, pos, len); ++ ++ if (result < 0) // error ++ return static_cast(result); ++ ++ if (result > 0) // need more data ++ return E_BUFFER_NOT_FULL; ++ ++ if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) ++ return E_FILE_FORMAT_INVALID; ++ ++ if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; ++ ++ const long long id = ReadUInt(pReader, pos, len); ++ ++ if (id < 0) // error ++ return static_cast(id); ++ ++ // This is the distinguished set of ID's we use to determine ++ // that we have exhausted the sub-element's inside the cluster ++ // whose ID we parsed earlier. ++ ++ if (id == 0x0F43B675) // Cluster ID ++ return 0; // no entries found ++ ++ if (id == 0x0C53BB6B) // Cues ID ++ return 0; // no entries found ++ ++ pos += len; // consume id field ++ ++ if ((cluster_stop >= 0) && (pos >= cluster_stop)) ++ return E_FILE_FORMAT_INVALID; ++ ++ // read size field ++ ++ if ((pos + 1) > avail) { ++ len = 1; ++ return E_BUFFER_NOT_FULL; ++ } ++ ++ result = GetUIntLength(pReader, pos, len); ++ ++ if (result < 0) // error ++ return static_cast(result); ++ ++ if (result > 0) // underflow ++ return E_BUFFER_NOT_FULL; ++ ++ if ((cluster_stop >= 0) && ((pos + len) > cluster_stop)) ++ return E_FILE_FORMAT_INVALID; ++ ++ if ((pos + len) > avail) ++ return E_BUFFER_NOT_FULL; ++ ++ const long long size = ReadUInt(pReader, pos, len); ++ ++ if (size < 0) // error ++ return static_cast(size); ++ ++ pos += len; // consume size field ++ ++ // pos now points to start of payload ++ ++ if ((cluster_stop >= 0) && (pos > cluster_stop)) ++ return E_FILE_FORMAT_INVALID; ++ ++ if (size == 0) // weird ++ continue; ++ ++ const long long unknown_size = (1LL << (7 * len)) - 1; ++ ++ if (size == unknown_size) ++ return E_FILE_FORMAT_INVALID; // not supported inside cluster ++ ++ if ((cluster_stop >= 0) && ((pos + size) > cluster_stop)) ++ return E_FILE_FORMAT_INVALID; ++ ++ if (id == 0x20) // BlockGroup ID ++ return 1; // have at least one entry ++ ++ if (id == 0x23) // SimpleBlock ID ++ return 1; // have at least one entry ++ ++ pos += size; // consume payload ++ assert((cluster_stop < 0) || (pos <= cluster_stop)); ++ } + } + ++long long Cluster::GetTimeCode() const { ++ long long pos; ++ long len; + +-long long Cluster::GetTimeCode() const +-{ ++ const long status = Load(pos, len); ++ ++ if (status < 0) // error ++ return status; ++ ++ return m_timecode; ++} ++ ++long long Cluster::GetTime() const { ++ const long long tc = GetTimeCode(); ++ ++ if (tc < 0) ++ return tc; ++ ++ const SegmentInfo* const pInfo = m_pSegment->GetInfo(); ++ assert(pInfo); ++ ++ const long long scale = pInfo->GetTimeCodeScale(); ++ assert(scale >= 1); ++ ++ const long long t = m_timecode * scale; ++ ++ return t; ++} ++ ++long long Cluster::GetFirstTime() const { ++ const BlockEntry* pEntry; ++ ++ const long status = GetFirst(pEntry); ++ ++ if (status < 0) // error ++ return status; ++ ++ if (pEntry == NULL) // empty cluster ++ return GetTime(); ++ ++ const Block* const pBlock = pEntry->GetBlock(); ++ assert(pBlock); ++ ++ return pBlock->GetTime(this); ++} ++ ++long long Cluster::GetLastTime() const { ++ const BlockEntry* pEntry; ++ ++ const long status = GetLast(pEntry); ++ ++ if (status < 0) // error ++ return status; ++ ++ if (pEntry == NULL) // empty cluster ++ return GetTime(); ++ ++ const Block* const pBlock = pEntry->GetBlock(); ++ assert(pBlock); ++ ++ return pBlock->GetTime(this); ++} ++ ++long Cluster::CreateBlock(long long id, ++ long long pos, // absolute pos of payload ++ long long size, long long discard_padding) { ++ assert((id == 0x20) || (id == 0x23)); // BlockGroup or SimpleBlock ++ ++ if (m_entries_count < 0) { // haven't parsed anything yet ++ assert(m_entries == NULL); ++ assert(m_entries_size == 0); ++ ++ m_entries_size = 1024; ++ m_entries = new BlockEntry* [m_entries_size]; ++ ++ m_entries_count = 0; ++ } else { ++ assert(m_entries); ++ assert(m_entries_size > 0); ++ assert(m_entries_count <= m_entries_size); ++ ++ if (m_entries_count >= m_entries_size) { ++ const long entries_size = 2 * m_entries_size; ++ ++ BlockEntry** const entries = new BlockEntry* [entries_size]; ++ assert(entries); ++ ++ BlockEntry** src = m_entries; ++ BlockEntry** const src_end = src + m_entries_count; ++ ++ BlockEntry** dst = entries; ++ ++ while (src != src_end) ++ *dst++ = *src++; ++ ++ delete[] m_entries; ++ ++ m_entries = entries; ++ m_entries_size = entries_size; ++ } ++ } ++ ++ if (id == 0x20) // BlockGroup ID ++ return CreateBlockGroup(pos, size, discard_padding); ++ else // SimpleBlock ID ++ return CreateSimpleBlock(pos, size); ++} ++ ++long Cluster::CreateBlockGroup(long long start_offset, long long size, ++ long long discard_padding) { ++ assert(m_entries); ++ assert(m_entries_size > 0); ++ assert(m_entries_count >= 0); ++ assert(m_entries_count < m_entries_size); ++ ++ IMkvReader* const pReader = m_pSegment->m_pReader; ++ ++ long long pos = start_offset; ++ const long long stop = start_offset + size; ++ ++ // For WebM files, there is a bias towards previous reference times ++ //(in order to support alt-ref frames, which refer back to the previous ++ // keyframe). Normally a 0 value is not possible, but here we tenatively ++ // allow 0 as the value of a reference frame, with the interpretation ++ // that this is a ""previous"" reference time. ++ ++ long long prev = 1; // nonce ++ long long next = 0; // nonce ++ long long duration = -1; // really, this is unsigned ++ ++ long long bpos = -1; ++ long long bsize = -1; ++ ++ while (pos < stop) { ++ long len; ++ const long long id = ReadUInt(pReader, pos, len); ++ assert(id >= 0); // TODO ++ assert((pos + len) <= stop); ++ ++ pos += len; // consume ID ++ ++ const long long size = ReadUInt(pReader, pos, len); ++ assert(size >= 0); // TODO ++ assert((pos + len) <= stop); ++ ++ pos += len; // consume size ++ ++ if (id == 0x21) { // Block ID ++ if (bpos < 0) { // Block ID ++ bpos = pos; ++ bsize = size; ++ } ++ } else if (id == 0x1B) { // Duration ID ++ assert(size <= 8); ++ ++ duration = UnserializeUInt(pReader, pos, size); ++ assert(duration >= 0); // TODO ++ } else if (id == 0x7B) { // ReferenceBlock ++ assert(size <= 8); ++ const long size_ = static_cast(size); ++ ++ long long time; ++ ++ long status = UnserializeInt(pReader, pos, size_, time); ++ assert(status == 0); ++ if (status != 0) ++ return -1; ++ ++ if (time <= 0) // see note above ++ prev = time; ++ else // weird ++ next = time; ++ } ++ ++ pos += size; // consume payload ++ assert(pos <= stop); ++ } ++ ++ assert(pos == stop); ++ assert(bpos >= 0); ++ assert(bsize >= 0); ++ ++ const long idx = m_entries_count; ++ ++ BlockEntry** const ppEntry = m_entries + idx; ++ BlockEntry*& pEntry = *ppEntry; ++ ++ pEntry = new (std::nothrow) ++ BlockGroup(this, idx, bpos, bsize, prev, next, duration, discard_padding); ++ ++ if (pEntry == NULL) ++ return -1; // generic error ++ ++ BlockGroup* const p = static_cast(pEntry); ++ ++ const long status = p->Parse(); ++ ++ if (status == 0) { // success ++ ++m_entries_count; ++ return 0; ++ } ++ ++ delete pEntry; ++ pEntry = 0; ++ ++ return status; ++} ++ ++long Cluster::CreateSimpleBlock(long long st, long long sz) { ++ assert(m_entries); ++ assert(m_entries_size > 0); ++ assert(m_entries_count >= 0); ++ assert(m_entries_count < m_entries_size); ++ ++ const long idx = m_entries_count; ++ ++ BlockEntry** const ppEntry = m_entries + idx; ++ BlockEntry*& pEntry = *ppEntry; ++ ++ pEntry = new (std::nothrow) SimpleBlock(this, idx, st, sz); ++ ++ if (pEntry == NULL) ++ return -1; // generic error ++ ++ SimpleBlock* const p = static_cast(pEntry); ++ ++ const long status = p->Parse(); ++ ++ if (status == 0) { ++ ++m_entries_count; ++ return 0; ++ } ++ ++ delete pEntry; ++ pEntry = 0; ++ ++ return status; ++} ++ ++long Cluster::GetFirst(const BlockEntry*& pFirst) const { ++ if (m_entries_count <= 0) { + long long pos; + long len; + +- const long status = Load(pos, len); ++ const long status = Parse(pos, len); + +- if (status < 0) //error +- return status; +- +- return m_timecode; +-} +- +- +-long long Cluster::GetTime() const +-{ +- const long long tc = GetTimeCode(); +- +- if (tc < 0) +- return tc; +- +- const SegmentInfo* const pInfo = m_pSegment->GetInfo(); +- assert(pInfo); +- +- const long long scale = pInfo->GetTimeCodeScale(); +- assert(scale >= 1); +- +- const long long t = m_timecode * scale; +- +- return t; +-} +- +- +-long long Cluster::GetFirstTime() const +-{ +- const BlockEntry* pEntry; +- +- const long status = GetFirst(pEntry); +- +- if (status < 0) //error +- return status; +- +- if (pEntry == NULL) //empty cluster +- return GetTime(); +- +- const Block* const pBlock = pEntry->GetBlock(); +- assert(pBlock); +- +- return pBlock->GetTime(this); +-} +- +- +-long long Cluster::GetLastTime() const +-{ +- const BlockEntry* pEntry; +- +- const long status = GetLast(pEntry); +- +- if (status < 0) //error +- return status; +- +- if (pEntry == NULL) //empty cluster +- return GetTime(); +- +- const Block* const pBlock = pEntry->GetBlock(); +- assert(pBlock); +- +- return pBlock->GetTime(this); +-} +- +- +-long Cluster::CreateBlock( +- long long id, +- long long pos, //absolute pos of payload +- long long size, +- long long discard_padding) +-{ +- assert((id == 0x20) || (id == 0x23)); //BlockGroup or SimpleBlock +- +- if (m_entries_count < 0) //haven't parsed anything yet +- { +- assert(m_entries == NULL); +- assert(m_entries_size == 0); +- +- m_entries_size = 1024; +- m_entries = new BlockEntry*[m_entries_size]; +- +- m_entries_count = 0; +- } +- else +- { +- assert(m_entries); +- assert(m_entries_size > 0); +- assert(m_entries_count <= m_entries_size); +- +- if (m_entries_count >= m_entries_size) +- { +- const long entries_size = 2 * m_entries_size; +- +- BlockEntry** const entries = new BlockEntry*[entries_size]; +- assert(entries); +- +- BlockEntry** src = m_entries; +- BlockEntry** const src_end = src + m_entries_count; +- +- BlockEntry** dst = entries; +- +- while (src != src_end) +- *dst++ = *src++; +- +- delete[] m_entries; +- +- m_entries = entries; +- m_entries_size = entries_size; +- } ++ if (status < 0) { // error ++ pFirst = NULL; ++ return status; + } + +- if (id == 0x20) //BlockGroup ID +- return CreateBlockGroup(pos, size, discard_padding); +- else //SimpleBlock ID +- return CreateSimpleBlock(pos, size); ++ if (m_entries_count <= 0) { // empty cluster ++ pFirst = NULL; ++ return 0; ++ } ++ } ++ ++ assert(m_entries); ++ ++ pFirst = m_entries[0]; ++ assert(pFirst); ++ ++ return 0; // success + } + ++long Cluster::GetLast(const BlockEntry*& pLast) const { ++ for (;;) { ++ long long pos; ++ long len; + +-long Cluster::CreateBlockGroup( +- long long start_offset, +- long long size, +- long long discard_padding) +-{ +- assert(m_entries); +- assert(m_entries_size > 0); +- assert(m_entries_count >= 0); +- assert(m_entries_count < m_entries_size); ++ const long status = Parse(pos, len); + +- IMkvReader* const pReader = m_pSegment->m_pReader; +- +- long long pos = start_offset; +- const long long stop = start_offset + size; +- +- //For WebM files, there is a bias towards previous reference times +- //(in order to support alt-ref frames, which refer back to the previous +- //keyframe). Normally a 0 value is not possible, but here we tenatively +- //allow 0 as the value of a reference frame, with the interpretation +- //that this is a ""previous"" reference time. +- +- long long prev = 1; //nonce +- long long next = 0; //nonce +- long long duration = -1; //really, this is unsigned +- +- long long bpos = -1; +- long long bsize = -1; +- +- while (pos < stop) +- { +- long len; +- const long long id = ReadUInt(pReader, pos, len); +- assert(id >= 0); //TODO +- assert((pos + len) <= stop); +- +- pos += len; //consume ID +- +- const long long size = ReadUInt(pReader, pos, len); +- assert(size >= 0); //TODO +- assert((pos + len) <= stop); +- +- pos += len; //consume size +- +- if (id == 0x21) //Block ID +- { +- if (bpos < 0) //Block ID +- { +- bpos = pos; +- bsize = size; +- } +- } +- else if (id == 0x1B) //Duration ID +- { +- assert(size <= 8); +- +- duration = UnserializeUInt(pReader, pos, size); +- assert(duration >= 0); //TODO +- } +- else if (id == 0x7B) //ReferenceBlock +- { +- assert(size <= 8); +- const long size_ = static_cast(size); +- +- long long time; +- +- long status = UnserializeInt(pReader, pos, size_, time); +- assert(status == 0); +- if (status != 0) +- return -1; +- +- if (time <= 0) //see note above +- prev = time; +- else //weird +- next = time; +- } +- +- pos += size; //consume payload +- assert(pos <= stop); ++ if (status < 0) { // error ++ pLast = NULL; ++ return status; + } + +- assert(pos == stop); +- assert(bpos >= 0); +- assert(bsize >= 0); ++ if (status > 0) // no new block ++ break; ++ } + +- const long idx = m_entries_count; +- +- BlockEntry** const ppEntry = m_entries + idx; +- BlockEntry*& pEntry = *ppEntry; +- +- pEntry = new (std::nothrow) BlockGroup( +- this, +- idx, +- bpos, +- bsize, +- prev, +- next, +- duration, +- discard_padding); +- +- if (pEntry == NULL) +- return -1; //generic error +- +- BlockGroup* const p = static_cast(pEntry); +- +- const long status = p->Parse(); +- +- if (status == 0) //success +- { +- ++m_entries_count; +- return 0; +- } +- +- delete pEntry; +- pEntry = 0; +- +- return status; +-} +- +- +- +-long Cluster::CreateSimpleBlock( +- long long st, +- long long sz) +-{ +- assert(m_entries); +- assert(m_entries_size > 0); +- assert(m_entries_count >= 0); +- assert(m_entries_count < m_entries_size); +- +- const long idx = m_entries_count; +- +- BlockEntry** const ppEntry = m_entries + idx; +- BlockEntry*& pEntry = *ppEntry; +- +- pEntry = new (std::nothrow) SimpleBlock(this, idx, st, sz); +- +- if (pEntry == NULL) +- return -1; //generic error +- +- SimpleBlock* const p = static_cast(pEntry); +- +- const long status = p->Parse(); +- +- if (status == 0) +- { +- ++m_entries_count; +- return 0; +- } +- +- delete pEntry; +- pEntry = 0; +- +- return status; +-} +- +- +-long Cluster::GetFirst(const BlockEntry*& pFirst) const +-{ +- if (m_entries_count <= 0) +- { +- long long pos; +- long len; +- +- const long status = Parse(pos, len); +- +- if (status < 0) //error +- { +- pFirst = NULL; +- return status; +- } +- +- if (m_entries_count <= 0) //empty cluster +- { +- pFirst = NULL; +- return 0; +- } +- } +- +- assert(m_entries); +- +- pFirst = m_entries[0]; +- assert(pFirst); +- +- return 0; //success +-} +- +-long Cluster::GetLast(const BlockEntry*& pLast) const +-{ +- for (;;) +- { +- long long pos; +- long len; +- +- const long status = Parse(pos, len); +- +- if (status < 0) //error +- { +- pLast = NULL; +- return status; +- } +- +- if (status > 0) //no new block +- break; +- } +- +- if (m_entries_count <= 0) +- { +- pLast = NULL; +- return 0; +- } +- +- assert(m_entries); +- +- const long idx = m_entries_count - 1; +- +- pLast = m_entries[idx]; +- assert(pLast); +- ++ if (m_entries_count <= 0) { ++ pLast = NULL; + return 0; ++ } ++ ++ assert(m_entries); ++ ++ const long idx = m_entries_count - 1; ++ ++ pLast = m_entries[idx]; ++ assert(pLast); ++ ++ return 0; + } + ++long Cluster::GetNext(const BlockEntry* pCurr, const BlockEntry*& pNext) const { ++ assert(pCurr); ++ assert(m_entries); ++ assert(m_entries_count > 0); + +-long Cluster::GetNext( +- const BlockEntry* pCurr, +- const BlockEntry*& pNext) const +-{ +- assert(pCurr); ++ size_t idx = pCurr->GetIndex(); ++ assert(idx < size_t(m_entries_count)); ++ assert(m_entries[idx] == pCurr); ++ ++ ++idx; ++ ++ if (idx >= size_t(m_entries_count)) { ++ long long pos; ++ long len; ++ ++ const long status = Parse(pos, len); ++ ++ if (status < 0) { // error ++ pNext = NULL; ++ return status; ++ } ++ ++ if (status > 0) { ++ pNext = NULL; ++ return 0; ++ } ++ + assert(m_entries); + assert(m_entries_count > 0); +- +- size_t idx = pCurr->GetIndex(); + assert(idx < size_t(m_entries_count)); +- assert(m_entries[idx] == pCurr); ++ } + +- ++idx; ++ pNext = m_entries[idx]; ++ assert(pNext); + +- if (idx >= size_t(m_entries_count)) +- { +- long long pos; +- long len; +- +- const long status = Parse(pos, len); +- +- if (status < 0) //error +- { +- pNext = NULL; +- return status; +- } +- +- if (status > 0) +- { +- pNext = NULL; +- return 0; +- } +- +- assert(m_entries); +- assert(m_entries_count > 0); +- assert(idx < size_t(m_entries_count)); +- } +- +- pNext = m_entries[idx]; +- assert(pNext); +- +- return 0; ++ return 0; + } + ++long Cluster::GetEntryCount() const { return m_entries_count; } + +-long Cluster::GetEntryCount() const +-{ +- return m_entries_count; +-} ++const BlockEntry* Cluster::GetEntry(const Track* pTrack, ++ long long time_ns) const { ++ assert(pTrack); + +- +-const BlockEntry* Cluster::GetEntry( +- const Track* pTrack, +- long long time_ns) const +-{ +- assert(pTrack); +- +- if (m_pSegment == NULL) //this is the special EOS cluster +- return pTrack->GetEOS(); ++ if (m_pSegment == NULL) // this is the special EOS cluster ++ return pTrack->GetEOS(); + + #if 0 + +@@ -8707,76 +7588,66 @@ + + + #else + +- const BlockEntry* pResult = pTrack->GetEOS(); ++ const BlockEntry* pResult = pTrack->GetEOS(); + +- long index = 0; ++ long index = 0; + +- for (;;) +- { +- if (index >= m_entries_count) +- { +- long long pos; +- long len; ++ for (;;) { ++ if (index >= m_entries_count) { ++ long long pos; ++ long len; + +- const long status = Parse(pos, len); +- assert(status >= 0); ++ const long status = Parse(pos, len); ++ assert(status >= 0); + +- if (status > 0) //completely parsed, and no more entries +- return pResult; ++ if (status > 0) // completely parsed, and no more entries ++ return pResult; + +- if (status < 0) //should never happen +- return 0; ++ if (status < 0) // should never happen ++ return 0; + +- assert(m_entries); +- assert(index < m_entries_count); +- } +- +- const BlockEntry* const pEntry = m_entries[index]; +- assert(pEntry); +- assert(!pEntry->EOS()); +- +- const Block* const pBlock = pEntry->GetBlock(); +- assert(pBlock); +- +- if (pBlock->GetTrackNumber() != pTrack->GetNumber()) +- { +- ++index; +- continue; +- } +- +- if (pTrack->VetEntry(pEntry)) +- { +- if (time_ns < 0) //just want first candidate block +- return pEntry; +- +- const long long ns = pBlock->GetTime(this); +- +- if (ns > time_ns) +- return pResult; +- +- pResult = pEntry; //have a candidate +- } +- else if (time_ns >= 0) +- { +- const long long ns = pBlock->GetTime(this); +- +- if (ns > time_ns) +- return pResult; +- } +- +- ++index; ++ assert(m_entries); ++ assert(index < m_entries_count); + } + ++ const BlockEntry* const pEntry = m_entries[index]; ++ assert(pEntry); ++ assert(!pEntry->EOS()); ++ ++ const Block* const pBlock = pEntry->GetBlock(); ++ assert(pBlock); ++ ++ if (pBlock->GetTrackNumber() != pTrack->GetNumber()) { ++ ++index; ++ continue; ++ } ++ ++ if (pTrack->VetEntry(pEntry)) { ++ if (time_ns < 0) // just want first candidate block ++ return pEntry; ++ ++ const long long ns = pBlock->GetTime(this); ++ ++ if (ns > time_ns) ++ return pResult; ++ ++ pResult = pEntry; // have a candidate ++ } else if (time_ns >= 0) { ++ const long long ns = pBlock->GetTime(this); ++ ++ if (ns > time_ns) ++ return pResult; ++ } ++ ++ ++index; ++ } ++ + #endif + } + +- +-const BlockEntry* +-Cluster::GetEntry( +- const CuePoint& cp, +- const CuePoint::TrackPosition& tp) const +-{ +- assert(m_pSegment); ++const BlockEntry* Cluster::GetEntry(const CuePoint& cp, ++ const CuePoint::TrackPosition& tp) const { ++ assert(m_pSegment); + + #if 0 + +@@ -8867,114 +7738,105 @@ + + + #else + +- const long long tc = cp.GetTimeCode(); ++ const long long tc = cp.GetTimeCode(); + +- if (tp.m_block > 0) +- { +- const long block = static_cast(tp.m_block); +- const long index = block - 1; ++ if (tp.m_block > 0) { ++ const long block = static_cast(tp.m_block); ++ const long index = block - 1; + +- while (index >= m_entries_count) +- { +- long long pos; +- long len; ++ while (index >= m_entries_count) { ++ long long pos; ++ long len; + +- const long status = Parse(pos, len); ++ const long status = Parse(pos, len); + +- if (status < 0) //TODO: can this happen? +- return NULL; ++ if (status < 0) // TODO: can this happen? ++ return NULL; + +- if (status > 0) //nothing remains to be parsed +- return NULL; +- } +- +- const BlockEntry* const pEntry = m_entries[index]; +- assert(pEntry); +- assert(!pEntry->EOS()); +- +- const Block* const pBlock = pEntry->GetBlock(); +- assert(pBlock); +- +- if ((pBlock->GetTrackNumber() == tp.m_track) && +- (pBlock->GetTimeCode(this) == tc)) +- { +- return pEntry; +- } ++ if (status > 0) // nothing remains to be parsed ++ return NULL; + } + +- long index = 0; ++ const BlockEntry* const pEntry = m_entries[index]; ++ assert(pEntry); ++ assert(!pEntry->EOS()); + +- for (;;) +- { +- if (index >= m_entries_count) +- { +- long long pos; +- long len; ++ const Block* const pBlock = pEntry->GetBlock(); ++ assert(pBlock); + +- const long status = Parse(pos, len); +- +- if (status < 0) //TODO: can this happen? +- return NULL; +- +- if (status > 0) //nothing remains to be parsed +- return NULL; +- +- assert(m_entries); +- assert(index < m_entries_count); +- } +- +- const BlockEntry* const pEntry = m_entries[index]; +- assert(pEntry); +- assert(!pEntry->EOS()); +- +- const Block* const pBlock = pEntry->GetBlock(); +- assert(pBlock); +- +- if (pBlock->GetTrackNumber() != tp.m_track) +- { +- ++index; +- continue; +- } +- +- const long long tc_ = pBlock->GetTimeCode(this); +- +- if (tc_ < tc) +- { +- ++index; +- continue; +- } +- +- if (tc_ > tc) +- return NULL; +- +- const Tracks* const pTracks = m_pSegment->GetTracks(); +- assert(pTracks); +- +- const long tn = static_cast(tp.m_track); +- const Track* const pTrack = pTracks->GetTrackByNumber(tn); +- +- if (pTrack == NULL) +- return NULL; +- +- const long long type = pTrack->GetType(); +- +- if (type == 2) //audio +- return pEntry; +- +- if (type != 1) //not video +- return NULL; +- +- if (!pBlock->IsKey()) +- return NULL; +- +- return pEntry; ++ if ((pBlock->GetTrackNumber() == tp.m_track) && ++ (pBlock->GetTimeCode(this) == tc)) { ++ return pEntry; + } ++ } ++ ++ long index = 0; ++ ++ for (;;) { ++ if (index >= m_entries_count) { ++ long long pos; ++ long len; ++ ++ const long status = Parse(pos, len); ++ ++ if (status < 0) // TODO: can this happen? ++ return NULL; ++ ++ if (status > 0) // nothing remains to be parsed ++ return NULL; ++ ++ assert(m_entries); ++ assert(index < m_entries_count); ++ } ++ ++ const BlockEntry* const pEntry = m_entries[index]; ++ assert(pEntry); ++ assert(!pEntry->EOS()); ++ ++ const Block* const pBlock = pEntry->GetBlock(); ++ assert(pBlock); ++ ++ if (pBlock->GetTrackNumber() != tp.m_track) { ++ ++index; ++ continue; ++ } ++ ++ const long long tc_ = pBlock->GetTimeCode(this); ++ ++ if (tc_ < tc) { ++ ++index; ++ continue; ++ } ++ ++ if (tc_ > tc) ++ return NULL; ++ ++ const Tracks* const pTracks = m_pSegment->GetTracks(); ++ assert(pTracks); ++ ++ const long tn = static_cast(tp.m_track); ++ const Track* const pTrack = pTracks->GetTrackByNumber(tn); ++ ++ if (pTrack == NULL) ++ return NULL; ++ ++ const long long type = pTrack->GetType(); ++ ++ if (type == 2) // audio ++ return pEntry; ++ ++ if (type != 1) // not video ++ return NULL; ++ ++ if (!pBlock->IsKey()) ++ return NULL; ++ ++ return pEntry; ++ } + + #endif +- + } + +- + #if 0 + const BlockEntry* Cluster::GetMaxKey(const VideoTrack* pTrack) const + { +@@ -9011,97 +7873,46 @@ + + } + #endif + ++BlockEntry::BlockEntry(Cluster* p, long idx) : m_pCluster(p), m_index(idx) {} + +-BlockEntry::BlockEntry(Cluster* p, long idx) : +- m_pCluster(p), +- m_index(idx) +-{ ++BlockEntry::~BlockEntry() {} ++ ++bool BlockEntry::EOS() const { return (GetKind() == kBlockEOS); } ++ ++const Cluster* BlockEntry::GetCluster() const { return m_pCluster; } ++ ++long BlockEntry::GetIndex() const { return m_index; } ++ ++SimpleBlock::SimpleBlock(Cluster* pCluster, long idx, long long start, ++ long long size) ++ : BlockEntry(pCluster, idx), m_block(start, size, 0) {} ++ ++long SimpleBlock::Parse() { return m_block.Parse(m_pCluster); } ++ ++BlockEntry::Kind SimpleBlock::GetKind() const { return kBlockSimple; } ++ ++const Block* SimpleBlock::GetBlock() const { return &m_block; } ++ ++BlockGroup::BlockGroup(Cluster* pCluster, long idx, long long block_start, ++ long long block_size, long long prev, long long next, ++ long long duration, long long discard_padding) ++ : BlockEntry(pCluster, idx), ++ m_block(block_start, block_size, discard_padding), ++ m_prev(prev), ++ m_next(next), ++ m_duration(duration) {} ++ ++long BlockGroup::Parse() { ++ const long status = m_block.Parse(m_pCluster); ++ ++ if (status) ++ return status; ++ ++ m_block.SetKey((m_prev > 0) && (m_next <= 0)); ++ ++ return 0; + } + +- +-BlockEntry::~BlockEntry() +-{ +-} +- +- +-bool BlockEntry::EOS() const +-{ +- return (GetKind() == kBlockEOS); +-} +- +- +-const Cluster* BlockEntry::GetCluster() const +-{ +- return m_pCluster; +-} +- +- +-long BlockEntry::GetIndex() const +-{ +- return m_index; +-} +- +- +-SimpleBlock::SimpleBlock( +- Cluster* pCluster, +- long idx, +- long long start, +- long long size) : +- BlockEntry(pCluster, idx), +- m_block(start, size, 0) +-{ +-} +- +- +-long SimpleBlock::Parse() +-{ +- return m_block.Parse(m_pCluster); +-} +- +- +-BlockEntry::Kind SimpleBlock::GetKind() const +-{ +- return kBlockSimple; +-} +- +- +-const Block* SimpleBlock::GetBlock() const +-{ +- return &m_block; +-} +- +- +-BlockGroup::BlockGroup( +- Cluster* pCluster, +- long idx, +- long long block_start, +- long long block_size, +- long long prev, +- long long next, +- long long duration, +- long long discard_padding) : +- BlockEntry(pCluster, idx), +- m_block(block_start, block_size, discard_padding), +- m_prev(prev), +- m_next(next), +- m_duration(duration) +-{ +-} +- +- +-long BlockGroup::Parse() +-{ +- const long status = m_block.Parse(m_pCluster); +- +- if (status) +- return status; +- +- m_block.SetKey((m_prev > 0) && (m_next <= 0)); +- +- return 0; +-} +- +- + #if 0 + void BlockGroup::ParseBlock(long long start, long long size) + { +@@ -9118,496 +7929,428 @@ + + } + #endif + ++BlockEntry::Kind BlockGroup::GetKind() const { return kBlockGroup; } + +-BlockEntry::Kind BlockGroup::GetKind() const +-{ +- return kBlockGroup; +-} ++const Block* BlockGroup::GetBlock() const { return &m_block; } + ++long long BlockGroup::GetPrevTimeCode() const { return m_prev; } + +-const Block* BlockGroup::GetBlock() const +-{ +- return &m_block; +-} ++long long BlockGroup::GetNextTimeCode() const { return m_next; } + ++long long BlockGroup::GetDurationTimeCode() const { return m_duration; } + +-long long BlockGroup::GetPrevTimeCode() const +-{ +- return m_prev; +-} ++Block::Block(long long start, long long size_, long long discard_padding) ++ : m_start(start), ++ m_size(size_), ++ m_track(0), ++ m_timecode(-1), ++ m_flags(0), ++ m_frames(NULL), ++ m_frame_count(-1), ++ m_discard_padding(discard_padding) {} + ++Block::~Block() { delete[] m_frames; } + +-long long BlockGroup::GetNextTimeCode() const +-{ +- return m_next; +-} ++long Block::Parse(const Cluster* pCluster) { ++ if (pCluster == NULL) ++ return -1; + +-long long BlockGroup::GetDurationTimeCode() const +-{ +- return m_duration; +-} ++ if (pCluster->m_pSegment == NULL) ++ return -1; + +-Block::Block(long long start, long long size_, long long discard_padding) : +- m_start(start), +- m_size(size_), +- m_track(0), +- m_timecode(-1), +- m_flags(0), +- m_frames(NULL), +- m_frame_count(-1), +- m_discard_padding(discard_padding) +-{ +-} ++ assert(m_start >= 0); ++ assert(m_size >= 0); ++ assert(m_track <= 0); ++ assert(m_frames == NULL); ++ assert(m_frame_count <= 0); + ++ long long pos = m_start; ++ const long long stop = m_start + m_size; + +-Block::~Block() +-{ +- delete[] m_frames; +-} ++ long len; + ++ IMkvReader* const pReader = pCluster->m_pSegment->m_pReader; + +-long Block::Parse(const Cluster* pCluster) +-{ +- if (pCluster == NULL) +- return -1; ++ m_track = ReadUInt(pReader, pos, len); + +- if (pCluster->m_pSegment == NULL) +- return -1; ++ if (m_track <= 0) ++ return E_FILE_FORMAT_INVALID; + +- assert(m_start >= 0); +- assert(m_size >= 0); +- assert(m_track <= 0); +- assert(m_frames == NULL); +- assert(m_frame_count <= 0); ++ if ((pos + len) > stop) ++ return E_FILE_FORMAT_INVALID; + +- long long pos = m_start; +- const long long stop = m_start + m_size; ++ pos += len; // consume track number + +- long len; ++ if ((stop - pos) < 2) ++ return E_FILE_FORMAT_INVALID; + +- IMkvReader* const pReader = pCluster->m_pSegment->m_pReader; ++ long status; ++ long long value; + +- m_track = ReadUInt(pReader, pos, len); ++ status = UnserializeInt(pReader, pos, 2, value); + +- if (m_track <= 0) +- return E_FILE_FORMAT_INVALID; ++ if (status) ++ return E_FILE_FORMAT_INVALID; + +- if ((pos + len) > stop) +- return E_FILE_FORMAT_INVALID; ++ if (value < SHRT_MIN) ++ return E_FILE_FORMAT_INVALID; + +- pos += len; //consume track number ++ if (value > SHRT_MAX) ++ return E_FILE_FORMAT_INVALID; + +- if ((stop - pos) < 2) +- return E_FILE_FORMAT_INVALID; ++ m_timecode = static_cast(value); + +- long status; +- long long value; ++ pos += 2; + +- status = UnserializeInt(pReader, pos, 2, value); ++ if ((stop - pos) <= 0) ++ return E_FILE_FORMAT_INVALID; + +- if (status) +- return E_FILE_FORMAT_INVALID; ++ status = pReader->Read(pos, 1, &m_flags); + +- if (value < SHRT_MIN) +- return E_FILE_FORMAT_INVALID; ++ if (status) ++ return E_FILE_FORMAT_INVALID; + +- if (value > SHRT_MAX) +- return E_FILE_FORMAT_INVALID; ++ const int lacing = int(m_flags & 0x06) >> 1; + +- m_timecode = static_cast(value); ++ ++pos; // consume flags byte + +- pos += 2; ++ if (lacing == 0) { // no lacing ++ if (pos > stop) ++ return E_FILE_FORMAT_INVALID; + +- if ((stop - pos) <= 0) +- return E_FILE_FORMAT_INVALID; +- +- status = pReader->Read(pos, 1, &m_flags); +- +- if (status) +- return E_FILE_FORMAT_INVALID; +- +- const int lacing = int(m_flags & 0x06) >> 1; +- +- ++pos; //consume flags byte +- +- if (lacing == 0) //no lacing +- { +- if (pos > stop) +- return E_FILE_FORMAT_INVALID; +- +- m_frame_count = 1; +- m_frames = new Frame[m_frame_count]; +- +- Frame& f = m_frames[0]; +- f.pos = pos; +- +- const long long frame_size = stop - pos; +- +- if (frame_size > LONG_MAX) +- return E_FILE_FORMAT_INVALID; +- +- f.len = static_cast(frame_size); +- +- return 0; //success +- } +- +- if (pos >= stop) +- return E_FILE_FORMAT_INVALID; +- +- unsigned char biased_count; +- +- status = pReader->Read(pos, 1, &biased_count); +- +- if (status) +- return E_FILE_FORMAT_INVALID; +- +- ++pos; //consume frame count +- assert(pos <= stop); +- +- m_frame_count = int(biased_count) + 1; +- ++ m_frame_count = 1; + m_frames = new Frame[m_frame_count]; +- assert(m_frames); + +- if (lacing == 1) //Xiph +- { +- Frame* pf = m_frames; +- Frame* const pf_end = pf + m_frame_count; ++ Frame& f = m_frames[0]; ++ f.pos = pos; + +- long size = 0; +- int frame_count = m_frame_count; ++ const long long frame_size = stop - pos; + +- while (frame_count > 1) +- { +- long frame_size = 0; ++ if (frame_size > LONG_MAX) ++ return E_FILE_FORMAT_INVALID; + +- for (;;) +- { +- unsigned char val; ++ f.len = static_cast(frame_size); + +- if (pos >= stop) +- return E_FILE_FORMAT_INVALID; ++ return 0; // success ++ } + +- status = pReader->Read(pos, 1, &val); ++ if (pos >= stop) ++ return E_FILE_FORMAT_INVALID; + +- if (status) +- return E_FILE_FORMAT_INVALID; ++ unsigned char biased_count; + +- ++pos; //consume xiph size byte ++ status = pReader->Read(pos, 1, &biased_count); + +- frame_size += val; ++ if (status) ++ return E_FILE_FORMAT_INVALID; + +- if (val < 255) +- break; +- } ++ ++pos; // consume frame count ++ assert(pos <= stop); + +- Frame& f = *pf++; +- assert(pf < pf_end); ++ m_frame_count = int(biased_count) + 1; + +- f.pos = 0; //patch later ++ m_frames = new Frame[m_frame_count]; ++ assert(m_frames); + +- f.len = frame_size; +- size += frame_size; //contribution of this frame ++ if (lacing == 1) { // Xiph ++ Frame* pf = m_frames; ++ Frame* const pf_end = pf + m_frame_count; + +- --frame_count; +- } ++ long size = 0; ++ int frame_count = m_frame_count; + +- assert(pf < pf_end); +- assert(pos <= stop); ++ while (frame_count > 1) { ++ long frame_size = 0; + +- { +- Frame& f = *pf++; +- +- if (pf != pf_end) +- return E_FILE_FORMAT_INVALID; +- +- f.pos = 0; //patch later +- +- const long long total_size = stop - pos; +- +- if (total_size < size) +- return E_FILE_FORMAT_INVALID; +- +- const long long frame_size = total_size - size; +- +- if (frame_size > LONG_MAX) +- return E_FILE_FORMAT_INVALID; +- +- f.len = static_cast(frame_size); +- } +- +- pf = m_frames; +- while (pf != pf_end) +- { +- Frame& f = *pf++; +- assert((pos + f.len) <= stop); +- +- f.pos = pos; +- pos += f.len; +- } +- +- assert(pos == stop); +- } +- else if (lacing == 2) //fixed-size lacing +- { +- const long long total_size = stop - pos; +- +- if ((total_size % m_frame_count) != 0) +- return E_FILE_FORMAT_INVALID; +- +- const long long frame_size = total_size / m_frame_count; +- +- if (frame_size > LONG_MAX) +- return E_FILE_FORMAT_INVALID; +- +- Frame* pf = m_frames; +- Frame* const pf_end = pf + m_frame_count; +- +- while (pf != pf_end) +- { +- assert((pos + frame_size) <= stop); +- +- Frame& f = *pf++; +- +- f.pos = pos; +- f.len = static_cast(frame_size); +- +- pos += frame_size; +- } +- +- assert(pos == stop); +- } +- else +- { +- assert(lacing == 3); //EBML lacing ++ for (;;) { ++ unsigned char val; + + if (pos >= stop) +- return E_FILE_FORMAT_INVALID; ++ return E_FILE_FORMAT_INVALID; + +- long size = 0; +- int frame_count = m_frame_count; ++ status = pReader->Read(pos, 1, &val); + +- long long frame_size = ReadUInt(pReader, pos, len); ++ if (status) ++ return E_FILE_FORMAT_INVALID; + +- if (frame_size < 0) +- return E_FILE_FORMAT_INVALID; ++ ++pos; // consume xiph size byte + +- if (frame_size > LONG_MAX) +- return E_FILE_FORMAT_INVALID; ++ frame_size += val; + +- if ((pos + len) > stop) +- return E_FILE_FORMAT_INVALID; ++ if (val < 255) ++ break; ++ } + +- pos += len; //consume length of size of first frame ++ Frame& f = *pf++; ++ assert(pf < pf_end); + +- if ((pos + frame_size) > stop) +- return E_FILE_FORMAT_INVALID; ++ f.pos = 0; // patch later + +- Frame* pf = m_frames; +- Frame* const pf_end = pf + m_frame_count; ++ f.len = frame_size; ++ size += frame_size; // contribution of this frame + +- { +- Frame& curr = *pf; +- +- curr.pos = 0; //patch later +- +- curr.len = static_cast(frame_size); +- size += curr.len; //contribution of this frame +- } +- +- --frame_count; +- +- while (frame_count > 1) +- { +- if (pos >= stop) +- return E_FILE_FORMAT_INVALID; +- +- assert(pf < pf_end); +- +- const Frame& prev = *pf++; +- assert(prev.len == frame_size); +- if (prev.len != frame_size) +- return E_FILE_FORMAT_INVALID; +- +- assert(pf < pf_end); +- +- Frame& curr = *pf; +- +- curr.pos = 0; //patch later +- +- const long long delta_size_ = ReadUInt(pReader, pos, len); +- +- if (delta_size_ < 0) +- return E_FILE_FORMAT_INVALID; +- +- if ((pos + len) > stop) +- return E_FILE_FORMAT_INVALID; +- +- pos += len; //consume length of (delta) size +- assert(pos <= stop); +- +- const int exp = 7*len - 1; +- const long long bias = (1LL << exp) - 1LL; +- const long long delta_size = delta_size_ - bias; +- +- frame_size += delta_size; +- +- if (frame_size < 0) +- return E_FILE_FORMAT_INVALID; +- +- if (frame_size > LONG_MAX) +- return E_FILE_FORMAT_INVALID; +- +- curr.len = static_cast(frame_size); +- size += curr.len; //contribution of this frame +- +- --frame_count; +- } +- +- { +- assert(pos <= stop); +- assert(pf < pf_end); +- +- const Frame& prev = *pf++; +- assert(prev.len == frame_size); +- if (prev.len != frame_size) +- return E_FILE_FORMAT_INVALID; +- +- assert(pf < pf_end); +- +- Frame& curr = *pf++; +- assert(pf == pf_end); +- +- curr.pos = 0; //patch later +- +- const long long total_size = stop - pos; +- +- if (total_size < size) +- return E_FILE_FORMAT_INVALID; +- +- frame_size = total_size - size; +- +- if (frame_size > LONG_MAX) +- return E_FILE_FORMAT_INVALID; +- +- curr.len = static_cast(frame_size); +- } +- +- pf = m_frames; +- while (pf != pf_end) +- { +- Frame& f = *pf++; +- assert((pos + f.len) <= stop); +- +- f.pos = pos; +- pos += f.len; +- } +- +- assert(pos == stop); ++ --frame_count; + } + +- return 0; //success ++ assert(pf < pf_end); ++ assert(pos <= stop); ++ ++ { ++ Frame& f = *pf++; ++ ++ if (pf != pf_end) ++ return E_FILE_FORMAT_INVALID; ++ ++ f.pos = 0; // patch later ++ ++ const long long total_size = stop - pos; ++ ++ if (total_size < size) ++ return E_FILE_FORMAT_INVALID; ++ ++ const long long frame_size = total_size - size; ++ ++ if (frame_size > LONG_MAX) ++ return E_FILE_FORMAT_INVALID; ++ ++ f.len = static_cast(frame_size); ++ } ++ ++ pf = m_frames; ++ while (pf != pf_end) { ++ Frame& f = *pf++; ++ assert((pos + f.len) <= stop); ++ ++ f.pos = pos; ++ pos += f.len; ++ } ++ ++ assert(pos == stop); ++ } else if (lacing == 2) { // fixed-size lacing ++ const long long total_size = stop - pos; ++ ++ if ((total_size % m_frame_count) != 0) ++ return E_FILE_FORMAT_INVALID; ++ ++ const long long frame_size = total_size / m_frame_count; ++ ++ if (frame_size > LONG_MAX) ++ return E_FILE_FORMAT_INVALID; ++ ++ Frame* pf = m_frames; ++ Frame* const pf_end = pf + m_frame_count; ++ ++ while (pf != pf_end) { ++ assert((pos + frame_size) <= stop); ++ ++ Frame& f = *pf++; ++ ++ f.pos = pos; ++ f.len = static_cast(frame_size); ++ ++ pos += frame_size; ++ } ++ ++ assert(pos == stop); ++ } else { ++ assert(lacing == 3); // EBML lacing ++ ++ if (pos >= stop) ++ return E_FILE_FORMAT_INVALID; ++ ++ long size = 0; ++ int frame_count = m_frame_count; ++ ++ long long frame_size = ReadUInt(pReader, pos, len); ++ ++ if (frame_size < 0) ++ return E_FILE_FORMAT_INVALID; ++ ++ if (frame_size > LONG_MAX) ++ return E_FILE_FORMAT_INVALID; ++ ++ if ((pos + len) > stop) ++ return E_FILE_FORMAT_INVALID; ++ ++ pos += len; // consume length of size of first frame ++ ++ if ((pos + frame_size) > stop) ++ return E_FILE_FORMAT_INVALID; ++ ++ Frame* pf = m_frames; ++ Frame* const pf_end = pf + m_frame_count; ++ ++ { ++ Frame& curr = *pf; ++ ++ curr.pos = 0; // patch later ++ ++ curr.len = static_cast(frame_size); ++ size += curr.len; // contribution of this frame ++ } ++ ++ --frame_count; ++ ++ while (frame_count > 1) { ++ if (pos >= stop) ++ return E_FILE_FORMAT_INVALID; ++ ++ assert(pf < pf_end); ++ ++ const Frame& prev = *pf++; ++ assert(prev.len == frame_size); ++ if (prev.len != frame_size) ++ return E_FILE_FORMAT_INVALID; ++ ++ assert(pf < pf_end); ++ ++ Frame& curr = *pf; ++ ++ curr.pos = 0; // patch later ++ ++ const long long delta_size_ = ReadUInt(pReader, pos, len); ++ ++ if (delta_size_ < 0) ++ return E_FILE_FORMAT_INVALID; ++ ++ if ((pos + len) > stop) ++ return E_FILE_FORMAT_INVALID; ++ ++ pos += len; // consume length of (delta) size ++ assert(pos <= stop); ++ ++ const int exp = 7 * len - 1; ++ const long long bias = (1LL << exp) - 1LL; ++ const long long delta_size = delta_size_ - bias; ++ ++ frame_size += delta_size; ++ ++ if (frame_size < 0) ++ return E_FILE_FORMAT_INVALID; ++ ++ if (frame_size > LONG_MAX) ++ return E_FILE_FORMAT_INVALID; ++ ++ curr.len = static_cast(frame_size); ++ size += curr.len; // contribution of this frame ++ ++ --frame_count; ++ } ++ ++ { ++ assert(pos <= stop); ++ assert(pf < pf_end); ++ ++ const Frame& prev = *pf++; ++ assert(prev.len == frame_size); ++ if (prev.len != frame_size) ++ return E_FILE_FORMAT_INVALID; ++ ++ assert(pf < pf_end); ++ ++ Frame& curr = *pf++; ++ assert(pf == pf_end); ++ ++ curr.pos = 0; // patch later ++ ++ const long long total_size = stop - pos; ++ ++ if (total_size < size) ++ return E_FILE_FORMAT_INVALID; ++ ++ frame_size = total_size - size; ++ ++ if (frame_size > LONG_MAX) ++ return E_FILE_FORMAT_INVALID; ++ ++ curr.len = static_cast(frame_size); ++ } ++ ++ pf = m_frames; ++ while (pf != pf_end) { ++ Frame& f = *pf++; ++ assert((pos + f.len) <= stop); ++ ++ f.pos = pos; ++ pos += f.len; ++ } ++ ++ assert(pos == stop); ++ } ++ ++ return 0; // success + } + ++long long Block::GetTimeCode(const Cluster* pCluster) const { ++ if (pCluster == 0) ++ return m_timecode; + +-long long Block::GetTimeCode(const Cluster* pCluster) const +-{ +- if (pCluster == 0) +- return m_timecode; ++ const long long tc0 = pCluster->GetTimeCode(); ++ assert(tc0 >= 0); + +- const long long tc0 = pCluster->GetTimeCode(); +- assert(tc0 >= 0); ++ const long long tc = tc0 + m_timecode; + +- const long long tc = tc0 + m_timecode; +- +- return tc; //unscaled timecode units ++ return tc; // unscaled timecode units + } + ++long long Block::GetTime(const Cluster* pCluster) const { ++ assert(pCluster); + +-long long Block::GetTime(const Cluster* pCluster) const +-{ +- assert(pCluster); ++ const long long tc = GetTimeCode(pCluster); + +- const long long tc = GetTimeCode(pCluster); ++ const Segment* const pSegment = pCluster->m_pSegment; ++ const SegmentInfo* const pInfo = pSegment->GetInfo(); ++ assert(pInfo); + +- const Segment* const pSegment = pCluster->m_pSegment; +- const SegmentInfo* const pInfo = pSegment->GetInfo(); +- assert(pInfo); ++ const long long scale = pInfo->GetTimeCodeScale(); ++ assert(scale >= 1); + +- const long long scale = pInfo->GetTimeCodeScale(); +- assert(scale >= 1); ++ const long long ns = tc * scale; + +- const long long ns = tc * scale; +- +- return ns; ++ return ns; + } + ++long long Block::GetTrackNumber() const { return m_track; } + +-long long Block::GetTrackNumber() const +-{ +- return m_track; ++bool Block::IsKey() const { ++ return ((m_flags & static_cast(1 << 7)) != 0); + } + +- +-bool Block::IsKey() const +-{ +- return ((m_flags & static_cast(1 << 7)) != 0); ++void Block::SetKey(bool bKey) { ++ if (bKey) ++ m_flags |= static_cast(1 << 7); ++ else ++ m_flags &= 0x7F; + } + ++bool Block::IsInvisible() const { return bool(int(m_flags & 0x08) != 0); } + +-void Block::SetKey(bool bKey) +-{ +- if (bKey) +- m_flags |= static_cast(1 << 7); +- else +- m_flags &= 0x7F; ++Block::Lacing Block::GetLacing() const { ++ const int value = int(m_flags & 0x06) >> 1; ++ return static_cast(value); + } + ++int Block::GetFrameCount() const { return m_frame_count; } + +-bool Block::IsInvisible() const +-{ +- return bool(int(m_flags & 0x08) != 0); ++const Block::Frame& Block::GetFrame(int idx) const { ++ assert(idx >= 0); ++ assert(idx < m_frame_count); ++ ++ const Frame& f = m_frames[idx]; ++ assert(f.pos > 0); ++ assert(f.len > 0); ++ ++ return f; + } + ++long Block::Frame::Read(IMkvReader* pReader, unsigned char* buf) const { ++ assert(pReader); ++ assert(buf); + +-Block::Lacing Block::GetLacing() const +-{ +- const int value = int(m_flags & 0x06) >> 1; +- return static_cast(value); ++ const long status = pReader->Read(pos, len, buf); ++ return status; + } + ++long long Block::GetDiscardPadding() const { return m_discard_padding; } + +-int Block::GetFrameCount() const +-{ +- return m_frame_count; +-} +- +- +-const Block::Frame& Block::GetFrame(int idx) const +-{ +- assert(idx >= 0); +- assert(idx < m_frame_count); +- +- const Frame& f = m_frames[idx]; +- assert(f.pos > 0); +- assert(f.len > 0); +- +- return f; +-} +- +- +-long Block::Frame::Read(IMkvReader* pReader, unsigned char* buf) const +-{ +- assert(pReader); +- assert(buf); +- +- const long status = pReader->Read(pos, len, buf); +- return status; +-} +- +-long long Block::GetDiscardPadding() const +-{ +- return m_discard_padding; +-} +- +-} //end namespace mkvparser ++} // end namespace mkvparser +",771,1102,2048 +3328,"static int tg3_test_loopback(struct tg3 *tp, u64 *data, bool do_extlpbk) +{ + int err = -EIO; + u32 eee_cap; + u32 jmb_pkt_sz = 9000; + + if (tp->dma_limit) + jmb_pkt_sz = tp->dma_limit - ETH_HLEN; + + eee_cap = tp->phy_flags & TG3_PHYFLG_EEE_CAP; + tp->phy_flags &= ~TG3_PHYFLG_EEE_CAP; + + if (!netif_running(tp->dev)) { + data[TG3_MAC_LOOPB_TEST] = TG3_LOOPBACK_FAILED; + data[TG3_PHY_LOOPB_TEST] = TG3_LOOPBACK_FAILED; + if (do_extlpbk) + data[TG3_EXT_LOOPB_TEST] = TG3_LOOPBACK_FAILED; + goto done; + } + + err = tg3_reset_hw(tp, 1); + if (err) { + data[TG3_MAC_LOOPB_TEST] = TG3_LOOPBACK_FAILED; + data[TG3_PHY_LOOPB_TEST] = TG3_LOOPBACK_FAILED; + if (do_extlpbk) + data[TG3_EXT_LOOPB_TEST] = TG3_LOOPBACK_FAILED; + goto done; + } + + if (tg3_flag(tp, ENABLE_RSS)) { + int i; + + /* Reroute all rx packets to the 1st queue */ + for (i = MAC_RSS_INDIR_TBL_0; + i < MAC_RSS_INDIR_TBL_0 + TG3_RSS_INDIR_TBL_SIZE; i += 4) + tw32(i, 0x0); + } + + /* HW errata - mac loopback fails in some cases on 5780. + * Normal traffic and PHY loopback are not affected by + * errata. Also, the MAC loopback test is deprecated for + * all newer ASIC revisions. + */ + if (tg3_asic_rev(tp) != ASIC_REV_5780 && + !tg3_flag(tp, CPMU_PRESENT)) { + tg3_mac_loopback(tp, true); + + if (tg3_run_loopback(tp, ETH_FRAME_LEN, false)) + data[TG3_MAC_LOOPB_TEST] |= TG3_STD_LOOPBACK_FAILED; + + if (tg3_flag(tp, JUMBO_RING_ENABLE) && + tg3_run_loopback(tp, jmb_pkt_sz + ETH_HLEN, false)) + data[TG3_MAC_LOOPB_TEST] |= TG3_JMB_LOOPBACK_FAILED; + + tg3_mac_loopback(tp, false); + } + + if (!(tp->phy_flags & TG3_PHYFLG_PHY_SERDES) && + !tg3_flag(tp, USE_PHYLIB)) { + int i; + + tg3_phy_lpbk_set(tp, 0, false); + + /* Wait for link */ + for (i = 0; i < 100; i++) { + if (tr32(MAC_TX_STATUS) & TX_STATUS_LINK_UP) + break; + mdelay(1); + } + + if (tg3_run_loopback(tp, ETH_FRAME_LEN, false)) + data[TG3_PHY_LOOPB_TEST] |= TG3_STD_LOOPBACK_FAILED; + if (tg3_flag(tp, TSO_CAPABLE) && + tg3_run_loopback(tp, ETH_FRAME_LEN, true)) + data[TG3_PHY_LOOPB_TEST] |= TG3_TSO_LOOPBACK_FAILED; + if (tg3_flag(tp, JUMBO_RING_ENABLE) && + tg3_run_loopback(tp, jmb_pkt_sz + ETH_HLEN, false)) + data[TG3_PHY_LOOPB_TEST] |= TG3_JMB_LOOPBACK_FAILED; + + if (do_extlpbk) { + tg3_phy_lpbk_set(tp, 0, true); + + /* All link indications report up, but the hardware + * isn't really ready for about 20 msec. Double it + * to be sure. + */ + mdelay(40); + + if (tg3_run_loopback(tp, ETH_FRAME_LEN, false)) + data[TG3_EXT_LOOPB_TEST] |= + TG3_STD_LOOPBACK_FAILED; + if (tg3_flag(tp, TSO_CAPABLE) && + tg3_run_loopback(tp, ETH_FRAME_LEN, true)) + data[TG3_EXT_LOOPB_TEST] |= + TG3_TSO_LOOPBACK_FAILED; + if (tg3_flag(tp, JUMBO_RING_ENABLE) && + tg3_run_loopback(tp, jmb_pkt_sz + ETH_HLEN, false)) + data[TG3_EXT_LOOPB_TEST] |= + TG3_JMB_LOOPBACK_FAILED; + } + + /* Re-enable gphy autopowerdown. */ + if (tp->phy_flags & TG3_PHYFLG_ENABLE_APD) + tg3_phy_toggle_apd(tp, true); + } + + err = (data[TG3_MAC_LOOPB_TEST] | data[TG3_PHY_LOOPB_TEST] | + data[TG3_EXT_LOOPB_TEST]) ? -EIO : 0; + +done: + tp->phy_flags |= eee_cap; + + return err; +} +",0,"static int tg3_test_loopback(struct tg3 *tp, u64 *data, bool do_extlpbk) +{ + int err = -EIO; + u32 eee_cap; + u32 jmb_pkt_sz = 9000; + + if (tp->dma_limit) + jmb_pkt_sz = tp->dma_limit - ETH_HLEN; + + eee_cap = tp->phy_flags & TG3_PHYFLG_EEE_CAP; + tp->phy_flags &= ~TG3_PHYFLG_EEE_CAP; + + if (!netif_running(tp->dev)) { + data[TG3_MAC_LOOPB_TEST] = TG3_LOOPBACK_FAILED; + data[TG3_PHY_LOOPB_TEST] = TG3_LOOPBACK_FAILED; + if (do_extlpbk) + data[TG3_EXT_LOOPB_TEST] = TG3_LOOPBACK_FAILED; + goto done; + } + + err = tg3_reset_hw(tp, 1); + if (err) { + data[TG3_MAC_LOOPB_TEST] = TG3_LOOPBACK_FAILED; + data[TG3_PHY_LOOPB_TEST] = TG3_LOOPBACK_FAILED; + if (do_extlpbk) + data[TG3_EXT_LOOPB_TEST] = TG3_LOOPBACK_FAILED; + goto done; + } + + if (tg3_flag(tp, ENABLE_RSS)) { + int i; + + /* Reroute all rx packets to the 1st queue */ + for (i = MAC_RSS_INDIR_TBL_0; + i < MAC_RSS_INDIR_TBL_0 + TG3_RSS_INDIR_TBL_SIZE; i += 4) + tw32(i, 0x0); + } + + /* HW errata - mac loopback fails in some cases on 5780. + * Normal traffic and PHY loopback are not affected by + * errata. Also, the MAC loopback test is deprecated for + * all newer ASIC revisions. + */ + if (tg3_asic_rev(tp) != ASIC_REV_5780 && + !tg3_flag(tp, CPMU_PRESENT)) { + tg3_mac_loopback(tp, true); + + if (tg3_run_loopback(tp, ETH_FRAME_LEN, false)) + data[TG3_MAC_LOOPB_TEST] |= TG3_STD_LOOPBACK_FAILED; + + if (tg3_flag(tp, JUMBO_RING_ENABLE) && + tg3_run_loopback(tp, jmb_pkt_sz + ETH_HLEN, false)) + data[TG3_MAC_LOOPB_TEST] |= TG3_JMB_LOOPBACK_FAILED; + + tg3_mac_loopback(tp, false); + } + + if (!(tp->phy_flags & TG3_PHYFLG_PHY_SERDES) && + !tg3_flag(tp, USE_PHYLIB)) { + int i; + + tg3_phy_lpbk_set(tp, 0, false); + + /* Wait for link */ + for (i = 0; i < 100; i++) { + if (tr32(MAC_TX_STATUS) & TX_STATUS_LINK_UP) + break; + mdelay(1); + } + + if (tg3_run_loopback(tp, ETH_FRAME_LEN, false)) + data[TG3_PHY_LOOPB_TEST] |= TG3_STD_LOOPBACK_FAILED; + if (tg3_flag(tp, TSO_CAPABLE) && + tg3_run_loopback(tp, ETH_FRAME_LEN, true)) + data[TG3_PHY_LOOPB_TEST] |= TG3_TSO_LOOPBACK_FAILED; + if (tg3_flag(tp, JUMBO_RING_ENABLE) && + tg3_run_loopback(tp, jmb_pkt_sz + ETH_HLEN, false)) + data[TG3_PHY_LOOPB_TEST] |= TG3_JMB_LOOPBACK_FAILED; + + if (do_extlpbk) { + tg3_phy_lpbk_set(tp, 0, true); + + /* All link indications report up, but the hardware + * isn't really ready for about 20 msec. Double it + * to be sure. + */ + mdelay(40); + + if (tg3_run_loopback(tp, ETH_FRAME_LEN, false)) + data[TG3_EXT_LOOPB_TEST] |= + TG3_STD_LOOPBACK_FAILED; + if (tg3_flag(tp, TSO_CAPABLE) && + tg3_run_loopback(tp, ETH_FRAME_LEN, true)) + data[TG3_EXT_LOOPB_TEST] |= + TG3_TSO_LOOPBACK_FAILED; + if (tg3_flag(tp, JUMBO_RING_ENABLE) && + tg3_run_loopback(tp, jmb_pkt_sz + ETH_HLEN, false)) + data[TG3_EXT_LOOPB_TEST] |= + TG3_JMB_LOOPBACK_FAILED; + } + + /* Re-enable gphy autopowerdown. */ + if (tp->phy_flags & TG3_PHYFLG_ENABLE_APD) + tg3_phy_toggle_apd(tp, true); + } + + err = (data[TG3_MAC_LOOPB_TEST] | data[TG3_PHY_LOOPB_TEST] | + data[TG3_EXT_LOOPB_TEST]) ? -EIO : 0; + +done: + tp->phy_flags |= eee_cap; + + return err; +} +","@@ -14604,8 +14604,11 @@ static void tg3_read_vpd(struct tg3 *tp) + if (j + len > block_end) + goto partno; + +- memcpy(tp->fw_ver, &vpd_data[j], len); +- strncat(tp->fw_ver, "" bc "", vpdlen - len - 1); ++ if (len >= sizeof(tp->fw_ver)) ++ len = sizeof(tp->fw_ver) - 1; ++ memset(tp->fw_ver, 0, sizeof(tp->fw_ver)); ++ snprintf(tp->fw_ver, sizeof(tp->fw_ver), ""%.*s bc "", len, ++ &vpd_data[j]); + } + + partno:",1105,1436,2048 +8140,"static int cliSendCommand(int argc, char **argv, long repeat) { + char *command = argv[0]; + size_t *argvlen; + int j, output_raw; + + if (!config.eval_ldb && /* In debugging mode, let's pass ""help"" to Redis. */ + (!strcasecmp(command,""help"") || !strcasecmp(command,""?""))) { + cliOutputHelp(--argc, ++argv); + return REDIS_OK; + } + + if (context == NULL) return REDIS_ERR; + + output_raw = 0; + if (!strcasecmp(command,""info"") || + (argc >= 2 && !strcasecmp(command,""debug"") && + !strcasecmp(argv[1],""htstats"")) || + (argc >= 2 && !strcasecmp(command,""memory"") && + (!strcasecmp(argv[1],""malloc-stats"") || + !strcasecmp(argv[1],""doctor""))) || + (argc == 2 && !strcasecmp(command,""cluster"") && + (!strcasecmp(argv[1],""nodes"") || + !strcasecmp(argv[1],""info""))) || + (argc == 2 && !strcasecmp(command,""client"") && + !strcasecmp(argv[1],""list"")) || + (argc == 3 && !strcasecmp(command,""latency"") && + !strcasecmp(argv[1],""graph"")) || + (argc == 2 && !strcasecmp(command,""latency"") && + !strcasecmp(argv[1],""doctor""))) + { + output_raw = 1; + } + + if (!strcasecmp(command,""shutdown"")) config.shutdown = 1; + if (!strcasecmp(command,""monitor"")) config.monitor_mode = 1; + if (!strcasecmp(command,""subscribe"") || + !strcasecmp(command,""psubscribe"")) config.pubsub_mode = 1; + if (!strcasecmp(command,""sync"") || + !strcasecmp(command,""psync"")) config.slave_mode = 1; + + /* When the user manually calls SCRIPT DEBUG, setup the activation of + * debugging mode on the next eval if needed. */ + if (argc == 3 && !strcasecmp(argv[0],""script"") && + !strcasecmp(argv[1],""debug"")) + { + if (!strcasecmp(argv[2],""yes"") || !strcasecmp(argv[2],""sync"")) { + config.enable_ldb_on_eval = 1; + } else { + config.enable_ldb_on_eval = 0; + } + } + + /* Actually activate LDB on EVAL if needed. */ + if (!strcasecmp(command,""eval"") && config.enable_ldb_on_eval) { + config.eval_ldb = 1; + config.output = OUTPUT_RAW; + } + + /* Setup argument length */ + argvlen = zmalloc(argc*sizeof(size_t)); + for (j = 0; j < argc; j++) + argvlen[j] = sdslen(argv[j]); + + while(repeat-- > 0) { + redisAppendCommandArgv(context,argc,(const char**)argv,argvlen); + while (config.monitor_mode) { + if (cliReadReply(output_raw) != REDIS_OK) exit(1); + fflush(stdout); + } + + if (config.pubsub_mode) { + if (config.output != OUTPUT_RAW) + printf(""Reading messages... (press Ctrl-C to quit)\n""); + while (1) { + if (cliReadReply(output_raw) != REDIS_OK) exit(1); + } + } + + if (config.slave_mode) { + printf(""Entering slave output mode... (press Ctrl-C to quit)\n""); + slaveMode(); + config.slave_mode = 0; + zfree(argvlen); + return REDIS_ERR; /* Error = slaveMode lost connection to master */ + } + + if (cliReadReply(output_raw) != REDIS_OK) { + zfree(argvlen); + return REDIS_ERR; + } else { + /* Store database number when SELECT was successfully executed. */ + if (!strcasecmp(command,""select"") && argc == 2 && config.last_cmd_type != REDIS_REPLY_ERROR) { + config.dbnum = atoi(argv[1]); + cliRefreshPrompt(); + } else if (!strcasecmp(command,""auth"") && argc == 2) { + cliSelect(); + } + } + if (config.interval) usleep(config.interval); + fflush(stdout); /* Make it grep friendly */ + } + + zfree(argvlen); + return REDIS_OK; +} +",0,"static int cliSendCommand(int argc, char **argv, long repeat) { + char *command = argv[0]; + size_t *argvlen; + int j, output_raw; + + if (!config.eval_ldb && /* In debugging mode, let's pass ""help"" to Redis. */ + (!strcasecmp(command,""help"") || !strcasecmp(command,""?""))) { + cliOutputHelp(--argc, ++argv); + return REDIS_OK; + } + + if (context == NULL) return REDIS_ERR; + + output_raw = 0; + if (!strcasecmp(command,""info"") || + (argc >= 2 && !strcasecmp(command,""debug"") && + !strcasecmp(argv[1],""htstats"")) || + (argc >= 2 && !strcasecmp(command,""memory"") && + (!strcasecmp(argv[1],""malloc-stats"") || + !strcasecmp(argv[1],""doctor""))) || + (argc == 2 && !strcasecmp(command,""cluster"") && + (!strcasecmp(argv[1],""nodes"") || + !strcasecmp(argv[1],""info""))) || + (argc == 2 && !strcasecmp(command,""client"") && + !strcasecmp(argv[1],""list"")) || + (argc == 3 && !strcasecmp(command,""latency"") && + !strcasecmp(argv[1],""graph"")) || + (argc == 2 && !strcasecmp(command,""latency"") && + !strcasecmp(argv[1],""doctor""))) + { + output_raw = 1; + } + + if (!strcasecmp(command,""shutdown"")) config.shutdown = 1; + if (!strcasecmp(command,""monitor"")) config.monitor_mode = 1; + if (!strcasecmp(command,""subscribe"") || + !strcasecmp(command,""psubscribe"")) config.pubsub_mode = 1; + if (!strcasecmp(command,""sync"") || + !strcasecmp(command,""psync"")) config.slave_mode = 1; + + /* When the user manually calls SCRIPT DEBUG, setup the activation of + * debugging mode on the next eval if needed. */ + if (argc == 3 && !strcasecmp(argv[0],""script"") && + !strcasecmp(argv[1],""debug"")) + { + if (!strcasecmp(argv[2],""yes"") || !strcasecmp(argv[2],""sync"")) { + config.enable_ldb_on_eval = 1; + } else { + config.enable_ldb_on_eval = 0; + } + } + + /* Actually activate LDB on EVAL if needed. */ + if (!strcasecmp(command,""eval"") && config.enable_ldb_on_eval) { + config.eval_ldb = 1; + config.output = OUTPUT_RAW; + } + + /* Setup argument length */ + argvlen = zmalloc(argc*sizeof(size_t)); + for (j = 0; j < argc; j++) + argvlen[j] = sdslen(argv[j]); + + while(repeat-- > 0) { + redisAppendCommandArgv(context,argc,(const char**)argv,argvlen); + while (config.monitor_mode) { + if (cliReadReply(output_raw) != REDIS_OK) exit(1); + fflush(stdout); + } + + if (config.pubsub_mode) { + if (config.output != OUTPUT_RAW) + printf(""Reading messages... (press Ctrl-C to quit)\n""); + while (1) { + if (cliReadReply(output_raw) != REDIS_OK) exit(1); + } + } + + if (config.slave_mode) { + printf(""Entering slave output mode... (press Ctrl-C to quit)\n""); + slaveMode(); + config.slave_mode = 0; + zfree(argvlen); + return REDIS_ERR; /* Error = slaveMode lost connection to master */ + } + + if (cliReadReply(output_raw) != REDIS_OK) { + zfree(argvlen); + return REDIS_ERR; + } else { + /* Store database number when SELECT was successfully executed. */ + if (!strcasecmp(command,""select"") && argc == 2 && config.last_cmd_type != REDIS_REPLY_ERROR) { + config.dbnum = atoi(argv[1]); + cliRefreshPrompt(); + } else if (!strcasecmp(command,""auth"") && argc == 2) { + cliSelect(); + } + } + if (config.interval) usleep(config.interval); + fflush(stdout); /* Make it grep friendly */ + } + + zfree(argvlen); + return REDIS_OK; +} +","@@ -152,20 +152,25 @@ static long long mstime(void) { + } + + static void cliRefreshPrompt(void) { +- int len; +- + if (config.eval_ldb) return; +- if (config.hostsocket != NULL) +- len = snprintf(config.prompt,sizeof(config.prompt),""redis %s"", +- config.hostsocket); +- else +- len = anetFormatAddr(config.prompt, sizeof(config.prompt), +- config.hostip, config.hostport); ++ ++ sds prompt = sdsempty(); ++ if (config.hostsocket != NULL) { ++ prompt = sdscatfmt(prompt,""redis %s"",config.hostsocket); ++ } else { ++ char addr[256]; ++ anetFormatAddr(addr, sizeof(addr), config.hostip, config.hostport); ++ prompt = sdscatlen(prompt,addr,strlen(addr)); ++ } ++ + /* Add [dbnum] if needed */ + if (config.dbnum != 0) +- len += snprintf(config.prompt+len,sizeof(config.prompt)-len,""[%d]"", +- config.dbnum); +- snprintf(config.prompt+len,sizeof(config.prompt)-len,""> ""); ++ prompt = sdscatfmt(prompt,""[%i]"",config.dbnum); ++ ++ /* Copy the prompt in the static buffer. */ ++ prompt = sdscatlen(prompt,""> "",2); ++ snprintf(config.prompt,sizeof(config.prompt),""%s"",prompt); ++ sdsfree(prompt); + } + + /* Return the name of the dotfile for the specified 'dotfilename'.",906,1237,2048 +18179,"static MagickBooleanType WriteTXTImage(const ImageInfo *image_info,Image *image, + ExceptionInfo *exception) +{ + char + buffer[MagickPathExtent], + colorspace[MagickPathExtent], + tuple[MagickPathExtent]; + + MagickBooleanType + status; + + MagickOffsetType + scene; + + PixelInfo + pixel; + + register const Quantum + *p; + + register ssize_t + x; + + ssize_t + 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,WriteBlobMode,exception); + if (status == MagickFalse) + return(status); + scene=0; + do + { + ComplianceType + compliance; + + const char + *value; + + (void) CopyMagickString(colorspace,CommandOptionToMnemonic( + MagickColorspaceOptions,(ssize_t) image->colorspace),MagickPathExtent); + LocaleLower(colorspace); + image->depth=GetImageQuantumDepth(image,MagickTrue); + if (image->alpha_trait != UndefinedPixelTrait) + (void) ConcatenateMagickString(colorspace,""a"",MagickPathExtent); + compliance=NoCompliance; + value=GetImageOption(image_info,""txt:compliance""); + if (value != (char *) NULL) + compliance=(ComplianceType) ParseCommandOption(MagickComplianceOptions, + MagickFalse,value); + if (LocaleCompare(image_info->magick,""SPARSE-COLOR"") != 0) + { + size_t + depth; + + depth=compliance == SVGCompliance ? image->depth : + MAGICKCORE_QUANTUM_DEPTH; + (void) FormatLocaleString(buffer,MagickPathExtent, + ""# ImageMagick pixel enumeration: %.20g,%.20g,%.20g,%s\n"",(double) + image->columns,(double) image->rows,(double) ((MagickOffsetType) + GetQuantumRange(depth)),colorspace); + (void) WriteBlobString(image,buffer); + } + GetPixelInfo(image,&pixel); + for (y=0; y < (ssize_t) image->rows; y++) + { + p=GetVirtualPixels(image,0,y,image->columns,1,exception); + if (p == (const Quantum *) NULL) + break; + for (x=0; x < (ssize_t) image->columns; x++) + { + GetPixelInfoPixel(image,p,&pixel); + if (pixel.colorspace == LabColorspace) + { + pixel.green-=(QuantumRange+1)/2.0; + pixel.blue-=(QuantumRange+1)/2.0; + } + if (LocaleCompare(image_info->magick,""SPARSE-COLOR"") == 0) + { + /* + Sparse-color format. + */ + if (GetPixelAlpha(image,p) == (Quantum) OpaqueAlpha) + { + GetColorTuple(&pixel,MagickFalse,tuple); + (void) FormatLocaleString(buffer,MagickPathExtent, + ""%.20g,%.20g,"",(double) x,(double) y); + (void) WriteBlobString(image,buffer); + (void) WriteBlobString(image,tuple); + (void) WriteBlobString(image,"" ""); + } + p+=GetPixelChannels(image); + continue; + } + (void) FormatLocaleString(buffer,MagickPathExtent,""%.20g,%.20g: "", + (double) x,(double) y); + (void) WriteBlobString(image,buffer); + (void) CopyMagickString(tuple,""("",MagickPathExtent); + if (pixel.colorspace == GRAYColorspace) + ConcatenateColorComponent(&pixel,GrayPixelChannel,compliance, + tuple); + else + { + ConcatenateColorComponent(&pixel,RedPixelChannel,compliance,tuple); + (void) ConcatenateMagickString(tuple,"","",MagickPathExtent); + ConcatenateColorComponent(&pixel,GreenPixelChannel,compliance, + tuple); + (void) ConcatenateMagickString(tuple,"","",MagickPathExtent); + ConcatenateColorComponent(&pixel,BluePixelChannel,compliance,tuple); + } + if (pixel.colorspace == CMYKColorspace) + { + (void) ConcatenateMagickString(tuple,"","",MagickPathExtent); + ConcatenateColorComponent(&pixel,BlackPixelChannel,compliance, + tuple); + } + if (pixel.alpha_trait != UndefinedPixelTrait) + { + (void) ConcatenateMagickString(tuple,"","",MagickPathExtent); + ConcatenateColorComponent(&pixel,AlphaPixelChannel,compliance, + tuple); + } + (void) ConcatenateMagickString(tuple,"")"",MagickPathExtent); + (void) WriteBlobString(image,tuple); + (void) WriteBlobString(image,"" ""); + GetColorTuple(&pixel,MagickTrue,tuple); + (void) FormatLocaleString(buffer,MagickPathExtent,""%s"",tuple); + (void) WriteBlobString(image,buffer); + (void) WriteBlobString(image,"" ""); + (void) QueryColorname(image,&pixel,SVGCompliance,tuple,exception); + (void) WriteBlobString(image,tuple); + (void) WriteBlobString(image,""\n""); + p+=GetPixelChannels(image); + } + status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + 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); +} +",1,"static MagickBooleanType WriteTXTImage(const ImageInfo *image_info,Image *image, + ExceptionInfo *exception) +{ + char + buffer[MagickPathExtent], + colorspace[MagickPathExtent], + tuple[MagickPathExtent]; + + MagickBooleanType + status; + + MagickOffsetType + scene; + + PixelInfo + pixel; + + register const Quantum + *p; + + register ssize_t + x; + + ssize_t + 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,WriteBlobMode,exception); + if (status == MagickFalse) + return(status); + scene=0; + do + { + ComplianceType + compliance; + + const char + *value; + + (void) CopyMagickString(colorspace,CommandOptionToMnemonic( + MagickColorspaceOptions,(ssize_t) image->colorspace),MagickPathExtent); + LocaleLower(colorspace); + image->depth=GetImageQuantumDepth(image,MagickTrue); + if (image->alpha_trait != UndefinedPixelTrait) + (void) ConcatenateMagickString(colorspace,""a"",MagickPathExtent); + compliance=NoCompliance; + value=GetImageOption(image_info,""txt:compliance""); + if (value != (char *) NULL) + compliance=(ComplianceType) ParseCommandOption(MagickComplianceOptions, + MagickFalse,value); + if (LocaleCompare(image_info->magick,""SPARSE-COLOR"") != 0) + { + size_t + depth; + + depth=compliance == SVGCompliance ? image->depth : + MAGICKCORE_QUANTUM_DEPTH; + (void) FormatLocaleString(buffer,MagickPathExtent, + ""# ImageMagick pixel enumeration: %.20g,%.20g,%.20g,%s\n"",(double) + image->columns,(double) image->rows,(double) ((MagickOffsetType) + GetQuantumRange(depth)),colorspace); + (void) WriteBlobString(image,buffer); + } + GetPixelInfo(image,&pixel); + for (y=0; y < (ssize_t) image->rows; y++) + { + p=GetVirtualPixels(image,0,y,image->columns,1,exception); + if (p == (const Quantum *) NULL) + break; + for (x=0; x < (ssize_t) image->columns; x++) + { + GetPixelInfoPixel(image,p,&pixel); + if (pixel.colorspace == LabColorspace) + { + pixel.green-=(QuantumRange+1)/2.0; + pixel.blue-=(QuantumRange+1)/2.0; + } + if (LocaleCompare(image_info->magick,""SPARSE-COLOR"") == 0) + { + /* + Sparse-color format. + */ + if (GetPixelAlpha(image,p) == (Quantum) OpaqueAlpha) + { + GetColorTuple(&pixel,MagickFalse,tuple); + (void) FormatLocaleString(buffer,MagickPathExtent, + ""%.20g,%.20g,"",(double) x,(double) y); + (void) WriteBlobString(image,buffer); + (void) WriteBlobString(image,tuple); + (void) WriteBlobString(image,"" ""); + } + p+=GetPixelChannels(image); + continue; + } + (void) FormatLocaleString(buffer,MagickPathExtent,""%.20g,%.20g: "", + (double) x,(double) y); + (void) WriteBlobString(image,buffer); + (void) CopyMagickString(tuple,""("",MagickPathExtent); + if (pixel.colorspace == GRAYColorspace) + ConcatenateColorComponent(&pixel,GrayPixelChannel,compliance,tuple); + else + { + ConcatenateColorComponent(&pixel,RedPixelChannel,compliance,tuple); + (void) ConcatenateMagickString(tuple,"","",MagickPathExtent); + ConcatenateColorComponent(&pixel,GreenPixelChannel,compliance, + tuple); + (void) ConcatenateMagickString(tuple,"","",MagickPathExtent); + ConcatenateColorComponent(&pixel,BluePixelChannel,compliance,tuple); + } + if (pixel.colorspace == CMYKColorspace) + { + (void) ConcatenateMagickString(tuple,"","",MagickPathExtent); + ConcatenateColorComponent(&pixel,BlackPixelChannel,compliance, + tuple); + } + if (pixel.alpha_trait != UndefinedPixelTrait) + { + (void) ConcatenateMagickString(tuple,"","",MagickPathExtent); + ConcatenateColorComponent(&pixel,AlphaPixelChannel,compliance, + tuple); + } + (void) ConcatenateMagickString(tuple,"")"",MagickPathExtent); + (void) WriteBlobString(image,tuple); + (void) WriteBlobString(image,"" ""); + GetColorTuple(&pixel,MagickTrue,tuple); + (void) FormatLocaleString(buffer,MagickPathExtent,""%s"",tuple); + (void) WriteBlobString(image,buffer); + (void) WriteBlobString(image,"" ""); + (void) QueryColorname(image,&pixel,SVGCompliance,tuple,exception); + (void) WriteBlobString(image,tuple); + (void) WriteBlobString(image,""\n""); + p+=GetPixelChannels(image); + } + status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + 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); +} +","@@ -793,8 +793,7 @@ static MagickBooleanType WriteTXTImage(const ImageInfo *image_info,Image *image, + (void) WriteBlobString(image,buffer); + (void) CopyMagickString(tuple,""("",MagickPathExtent); + if (pixel.colorspace == GRAYColorspace) +- ConcatenateColorComponent(&pixel,GrayPixelChannel,compliance, +- tuple); ++ ConcatenateColorComponent(&pixel,GrayPixelChannel,compliance,tuple); + else + { + ConcatenateColorComponent(&pixel,RedPixelChannel,compliance,tuple);",1357,1688,2048 +657,"process_tx_desc(E1000State *s, struct e1000_tx_desc *dp) +{ + uint32_t txd_lower = le32_to_cpu(dp->lower.data); + uint32_t dtype = txd_lower & (E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D); + unsigned int split_size = txd_lower & 0xffff, bytes, sz, op; + unsigned int msh = 0xfffff, hdr = 0; + uint64_t addr; + struct e1000_context_desc *xp = (struct e1000_context_desc *)dp; + struct e1000_tx *tp = &s->tx; + + if (dtype == E1000_TXD_CMD_DEXT) { // context descriptor + op = le32_to_cpu(xp->cmd_and_length); + tp->ipcss = xp->lower_setup.ip_fields.ipcss; + tp->ipcso = xp->lower_setup.ip_fields.ipcso; + tp->ipcse = le16_to_cpu(xp->lower_setup.ip_fields.ipcse); + tp->tucss = xp->upper_setup.tcp_fields.tucss; + tp->tucso = xp->upper_setup.tcp_fields.tucso; + tp->tucse = le16_to_cpu(xp->upper_setup.tcp_fields.tucse); + tp->paylen = op & 0xfffff; + tp->hdr_len = xp->tcp_seg_setup.fields.hdr_len; + tp->mss = le16_to_cpu(xp->tcp_seg_setup.fields.mss); + tp->ip = (op & E1000_TXD_CMD_IP) ? 1 : 0; + tp->tcp = (op & E1000_TXD_CMD_TCP) ? 1 : 0; + tp->tse = (op & E1000_TXD_CMD_TSE) ? 1 : 0; + tp->tso_frames = 0; + if (tp->tucso == 0) { // this is probably wrong + DBGOUT(TXSUM, ""TCP/UDP: cso 0!\n""); + tp->tucso = tp->tucss + (tp->tcp ? 16 : 6); + } + return; + } else if (dtype == (E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D)) { + if (tp->size == 0) { + tp->sum_needed = le32_to_cpu(dp->upper.data) >> 8; + } + tp->cptse = ( txd_lower & E1000_TXD_CMD_TSE ) ? 1 : 0; + } else { + tp->cptse = 0; + } + + if (vlan_enabled(s) && is_vlan_txd(txd_lower) && + (tp->cptse || txd_lower & E1000_TXD_CMD_EOP)) { + tp->vlan_needed = 1; + cpu_to_be16wu((uint16_t *)(tp->vlan_header), + le16_to_cpup((uint16_t *)(s->mac_reg + VET))); + cpu_to_be16wu((uint16_t *)(tp->vlan_header + 2), + le16_to_cpu(dp->upper.fields.special)); + } + + addr = le64_to_cpu(dp->buffer_addr); + if (tp->tse && tp->cptse) { + hdr = tp->hdr_len; + msh = hdr + tp->mss; + do { + bytes = split_size; + if (tp->size + bytes > msh) + bytes = msh - tp->size; + + bytes = MIN(sizeof(tp->data) - tp->size, bytes); + pci_dma_read(&s->dev, addr, tp->data + tp->size, bytes); + if ((sz = tp->size + bytes) >= hdr && tp->size < hdr) + memmove(tp->header, tp->data, hdr); + tp->size = sz; + addr += bytes; + if (sz == msh) { + xmit_seg(s); + memmove(tp->data, tp->header, hdr); + tp->size = hdr; + } + } while (split_size -= bytes); + } else if (!tp->tse && tp->cptse) { + DBGOUT(TXERR, ""TCP segmentation error\n""); + } else { + split_size = MIN(sizeof(tp->data) - tp->size, split_size); + pci_dma_read(&s->dev, addr, tp->data + tp->size, split_size); + tp->size += split_size; + } + + if (!(txd_lower & E1000_TXD_CMD_EOP)) + return; + if (!(tp->tse && tp->cptse && tp->size < hdr)) + xmit_seg(s); + tp->tso_frames = 0; + tp->sum_needed = 0; + tp->vlan_needed = 0; + tp->size = 0; + tp->cptse = 0; +} +",0,"process_tx_desc(E1000State *s, struct e1000_tx_desc *dp) +{ + uint32_t txd_lower = le32_to_cpu(dp->lower.data); + uint32_t dtype = txd_lower & (E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D); + unsigned int split_size = txd_lower & 0xffff, bytes, sz, op; + unsigned int msh = 0xfffff, hdr = 0; + uint64_t addr; + struct e1000_context_desc *xp = (struct e1000_context_desc *)dp; + struct e1000_tx *tp = &s->tx; + + if (dtype == E1000_TXD_CMD_DEXT) { // context descriptor + op = le32_to_cpu(xp->cmd_and_length); + tp->ipcss = xp->lower_setup.ip_fields.ipcss; + tp->ipcso = xp->lower_setup.ip_fields.ipcso; + tp->ipcse = le16_to_cpu(xp->lower_setup.ip_fields.ipcse); + tp->tucss = xp->upper_setup.tcp_fields.tucss; + tp->tucso = xp->upper_setup.tcp_fields.tucso; + tp->tucse = le16_to_cpu(xp->upper_setup.tcp_fields.tucse); + tp->paylen = op & 0xfffff; + tp->hdr_len = xp->tcp_seg_setup.fields.hdr_len; + tp->mss = le16_to_cpu(xp->tcp_seg_setup.fields.mss); + tp->ip = (op & E1000_TXD_CMD_IP) ? 1 : 0; + tp->tcp = (op & E1000_TXD_CMD_TCP) ? 1 : 0; + tp->tse = (op & E1000_TXD_CMD_TSE) ? 1 : 0; + tp->tso_frames = 0; + if (tp->tucso == 0) { // this is probably wrong + DBGOUT(TXSUM, ""TCP/UDP: cso 0!\n""); + tp->tucso = tp->tucss + (tp->tcp ? 16 : 6); + } + return; + } else if (dtype == (E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D)) { + if (tp->size == 0) { + tp->sum_needed = le32_to_cpu(dp->upper.data) >> 8; + } + tp->cptse = ( txd_lower & E1000_TXD_CMD_TSE ) ? 1 : 0; + } else { + tp->cptse = 0; + } + + if (vlan_enabled(s) && is_vlan_txd(txd_lower) && + (tp->cptse || txd_lower & E1000_TXD_CMD_EOP)) { + tp->vlan_needed = 1; + cpu_to_be16wu((uint16_t *)(tp->vlan_header), + le16_to_cpup((uint16_t *)(s->mac_reg + VET))); + cpu_to_be16wu((uint16_t *)(tp->vlan_header + 2), + le16_to_cpu(dp->upper.fields.special)); + } + + addr = le64_to_cpu(dp->buffer_addr); + if (tp->tse && tp->cptse) { + hdr = tp->hdr_len; + msh = hdr + tp->mss; + do { + bytes = split_size; + if (tp->size + bytes > msh) + bytes = msh - tp->size; + + bytes = MIN(sizeof(tp->data) - tp->size, bytes); + pci_dma_read(&s->dev, addr, tp->data + tp->size, bytes); + if ((sz = tp->size + bytes) >= hdr && tp->size < hdr) + memmove(tp->header, tp->data, hdr); + tp->size = sz; + addr += bytes; + if (sz == msh) { + xmit_seg(s); + memmove(tp->data, tp->header, hdr); + tp->size = hdr; + } + } while (split_size -= bytes); + } else if (!tp->tse && tp->cptse) { + DBGOUT(TXERR, ""TCP segmentation error\n""); + } else { + split_size = MIN(sizeof(tp->data) - tp->size, split_size); + pci_dma_read(&s->dev, addr, tp->data + tp->size, split_size); + tp->size += split_size; + } + + if (!(txd_lower & E1000_TXD_CMD_EOP)) + return; + if (!(tp->tse && tp->cptse && tp->size < hdr)) + xmit_seg(s); + tp->tso_frames = 0; + tp->sum_needed = 0; + tp->vlan_needed = 0; + tp->size = 0; + tp->cptse = 0; +} +","@@ -59,6 +59,9 @@ static int debugflags = DBGBIT(TXERR) | DBGBIT(GENERAL); + #define PNPMMIO_SIZE 0x20000 + #define MIN_BUF_SIZE 60 /* Min. octets in an ethernet frame sans FCS */ + ++/* this is the size past which hardware will drop packets when setting LPE=0 */ ++#define MAXIMUM_ETHERNET_VLAN_SIZE 1522 ++ + /* + * HW models: + * E1000_DEV_ID_82540EM works with Windows and Linux +@@ -805,6 +808,13 @@ e1000_receive(NetClientState *nc, const uint8_t *buf, size_t size) + size = sizeof(min_buf); + } + ++ /* Discard oversized packets if !LPE and !SBP. */ ++ if (size > MAXIMUM_ETHERNET_VLAN_SIZE ++ && !(s->mac_reg[RCTL] & E1000_RCTL_LPE) ++ && !(s->mac_reg[RCTL] & E1000_RCTL_SBP)) { ++ return size; ++ } ++ + if (!receive_filter(s, buf, size)) + return size;",1126,1457,2048 +18773,"OMX_ERRORTYPE omx_vdec::get_config(OMX_IN OMX_HANDLETYPE hComp, + OMX_IN OMX_INDEXTYPE configIndex, + OMX_INOUT OMX_PTR configData) +{ + (void) hComp; + OMX_ERRORTYPE eRet = OMX_ErrorNone; + + if (m_state == OMX_StateInvalid) { + DEBUG_PRINT_ERROR(""Get Config in Invalid State""); + return OMX_ErrorInvalidState; + } + + + switch ((unsigned long)configIndex) { + case OMX_QcomIndexConfigInterlaced: { + OMX_QCOM_CONFIG_INTERLACETYPE *configFmt = + (OMX_QCOM_CONFIG_INTERLACETYPE *) configData; + if (configFmt->nPortIndex == 1) { + if (configFmt->nIndex == 0) { + configFmt->eInterlaceType = OMX_QCOM_InterlaceFrameProgressive; + } else if (configFmt->nIndex == 1) { + configFmt->eInterlaceType = + OMX_QCOM_InterlaceInterleaveFrameTopFieldFirst; + } else if (configFmt->nIndex == 2) { + configFmt->eInterlaceType = + OMX_QCOM_InterlaceInterleaveFrameBottomFieldFirst; + } else { + DEBUG_PRINT_ERROR(""get_config: OMX_QcomIndexConfigInterlaced:"" + "" NoMore Interlaced formats""); + eRet = OMX_ErrorNoMore; + } + + } else { + DEBUG_PRINT_ERROR(""get_config: Bad port index %d queried on only o/p port"", + (int)configFmt->nPortIndex); + eRet = OMX_ErrorBadPortIndex; + } + + break; + } + case OMX_QcomIndexQueryNumberOfVideoDecInstance: { + QOMX_VIDEO_QUERY_DECODER_INSTANCES *decoderinstances = + (QOMX_VIDEO_QUERY_DECODER_INSTANCES*)configData; + decoderinstances->nNumOfInstances = 16; + /*TODO: How to handle this case */ + break; + + } + case OMX_QcomIndexConfigVideoFramePackingArrangement: { + if (drv_ctx.decoder_format == VDEC_CODECTYPE_H264) { + OMX_QCOM_FRAME_PACK_ARRANGEMENT *configFmt = + (OMX_QCOM_FRAME_PACK_ARRANGEMENT *) configData; + memcpy(configFmt, &m_frame_pack_arrangement, + sizeof(OMX_QCOM_FRAME_PACK_ARRANGEMENT)); + } else { + DEBUG_PRINT_ERROR(""get_config: Framepack data not supported for non H264 codecs""); + } + + break; + } + case OMX_IndexConfigCommonOutputCrop: { + OMX_CONFIG_RECTTYPE *rect = (OMX_CONFIG_RECTTYPE *) configData; + memcpy(rect, &rectangle, sizeof(OMX_CONFIG_RECTTYPE)); + DEBUG_PRINT_HIGH(""get_config: crop info: L: %u, T: %u, R: %u, B: %u"", + rectangle.nLeft, rectangle.nTop, + rectangle.nWidth, rectangle.nHeight); + + break; + } + case OMX_QcomIndexConfigPerfLevel: { + struct v4l2_control control; + OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *perf = + (OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *)configData; + + control.id = V4L2_CID_MPEG_VIDC_SET_PERF_LEVEL; + if (ioctl(drv_ctx.video_driver_fd, VIDIOC_G_CTRL, &control) < 0) { + DEBUG_PRINT_ERROR(""Failed getting performance level: %d"", errno); + eRet = OMX_ErrorHardware; + } + + if (eRet == OMX_ErrorNone) { + switch (control.value) { + case V4L2_CID_MPEG_VIDC_PERF_LEVEL_TURBO: + perf->ePerfLevel = OMX_QCOM_PerfLevelTurbo; + break; + default: + DEBUG_PRINT_HIGH(""Unknown perf level %d, reporting Nominal instead"", control.value); + /* Fall through */ + case V4L2_CID_MPEG_VIDC_PERF_LEVEL_NOMINAL: + perf->ePerfLevel = OMX_QCOM_PerfLevelNominal; + break; + } + + } + + break; + } + default: { + DEBUG_PRINT_ERROR(""get_config: unknown param %d"",configIndex); + eRet = OMX_ErrorBadParameter; + } + + } + + return eRet; +} +",1,"OMX_ERRORTYPE omx_vdec::get_config(OMX_IN OMX_HANDLETYPE hComp, + OMX_IN OMX_INDEXTYPE configIndex, + OMX_INOUT OMX_PTR configData) +{ + (void) hComp; + OMX_ERRORTYPE eRet = OMX_ErrorNone; + + if (m_state == OMX_StateInvalid) { + DEBUG_PRINT_ERROR(""Get Config in Invalid State""); + return OMX_ErrorInvalidState; + } + + + switch ((unsigned long)configIndex) { + case OMX_QcomIndexConfigInterlaced: { + VALIDATE_OMX_PARAM_DATA(configData, OMX_QCOM_CONFIG_INTERLACETYPE); + OMX_QCOM_CONFIG_INTERLACETYPE *configFmt = + (OMX_QCOM_CONFIG_INTERLACETYPE *) configData; + if (configFmt->nPortIndex == 1) { + if (configFmt->nIndex == 0) { + configFmt->eInterlaceType = OMX_QCOM_InterlaceFrameProgressive; + } else if (configFmt->nIndex == 1) { + configFmt->eInterlaceType = + OMX_QCOM_InterlaceInterleaveFrameTopFieldFirst; + } else if (configFmt->nIndex == 2) { + configFmt->eInterlaceType = + OMX_QCOM_InterlaceInterleaveFrameBottomFieldFirst; + } else { + DEBUG_PRINT_ERROR(""get_config: OMX_QcomIndexConfigInterlaced:"" + "" NoMore Interlaced formats""); + eRet = OMX_ErrorNoMore; + } + + } else { + DEBUG_PRINT_ERROR(""get_config: Bad port index %d queried on only o/p port"", + (int)configFmt->nPortIndex); + eRet = OMX_ErrorBadPortIndex; + } + + break; + } + case OMX_QcomIndexQueryNumberOfVideoDecInstance: { + VALIDATE_OMX_PARAM_DATA(configData, QOMX_VIDEO_QUERY_DECODER_INSTANCES); + QOMX_VIDEO_QUERY_DECODER_INSTANCES *decoderinstances = + (QOMX_VIDEO_QUERY_DECODER_INSTANCES*)configData; + decoderinstances->nNumOfInstances = 16; + /*TODO: How to handle this case */ + break; + + } + case OMX_QcomIndexConfigVideoFramePackingArrangement: { + if (drv_ctx.decoder_format == VDEC_CODECTYPE_H264) { + VALIDATE_OMX_PARAM_DATA(configData, OMX_QCOM_FRAME_PACK_ARRANGEMENT); + OMX_QCOM_FRAME_PACK_ARRANGEMENT *configFmt = + (OMX_QCOM_FRAME_PACK_ARRANGEMENT *) configData; + memcpy(configFmt, &m_frame_pack_arrangement, + sizeof(OMX_QCOM_FRAME_PACK_ARRANGEMENT)); + } else { + DEBUG_PRINT_ERROR(""get_config: Framepack data not supported for non H264 codecs""); + } + + break; + } + case OMX_IndexConfigCommonOutputCrop: { + VALIDATE_OMX_PARAM_DATA(configData, OMX_CONFIG_RECTTYPE); + OMX_CONFIG_RECTTYPE *rect = (OMX_CONFIG_RECTTYPE *) configData; + memcpy(rect, &rectangle, sizeof(OMX_CONFIG_RECTTYPE)); + DEBUG_PRINT_HIGH(""get_config: crop info: L: %u, T: %u, R: %u, B: %u"", + rectangle.nLeft, rectangle.nTop, + rectangle.nWidth, rectangle.nHeight); + + break; + } + case OMX_QcomIndexConfigPerfLevel: { + VALIDATE_OMX_PARAM_DATA(configData, OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL); + struct v4l2_control control; + OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *perf = + (OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *)configData; + + control.id = V4L2_CID_MPEG_VIDC_SET_PERF_LEVEL; + if (ioctl(drv_ctx.video_driver_fd, VIDIOC_G_CTRL, &control) < 0) { + DEBUG_PRINT_ERROR(""Failed getting performance level: %d"", errno); + eRet = OMX_ErrorHardware; + } + + if (eRet == OMX_ErrorNone) { + switch (control.value) { + case V4L2_CID_MPEG_VIDC_PERF_LEVEL_TURBO: + perf->ePerfLevel = OMX_QCOM_PerfLevelTurbo; + break; + default: + DEBUG_PRINT_HIGH(""Unknown perf level %d, reporting Nominal instead"", control.value); + /* Fall through */ + case V4L2_CID_MPEG_VIDC_PERF_LEVEL_NOMINAL: + perf->ePerfLevel = OMX_QCOM_PerfLevelNominal; + break; + } + + } + + break; + } + default: { + DEBUG_PRINT_ERROR(""get_config: unknown param %d"",configIndex); + eRet = OMX_ErrorBadParameter; + } + + } + + return eRet; +} +","@@ -2979,6 +2979,7 @@ + + } + switch ((unsigned long)paramIndex) { + case OMX_IndexParamPortDefinition: { ++ VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_PORTDEFINITIONTYPE); + OMX_PARAM_PORTDEFINITIONTYPE *portDefn = + (OMX_PARAM_PORTDEFINITIONTYPE *) paramData; + DEBUG_PRINT_LOW(""get_parameter: OMX_IndexParamPortDefinition""); +@@ -2988,23 +2989,25 @@ + + break; + } + case OMX_IndexParamVideoInit: { ++ VALIDATE_OMX_PARAM_DATA(paramData, OMX_PORT_PARAM_TYPE); + OMX_PORT_PARAM_TYPE *portParamType = + (OMX_PORT_PARAM_TYPE *) paramData; + DEBUG_PRINT_LOW(""get_parameter: OMX_IndexParamVideoInit""); + + portParamType->nVersion.nVersion = OMX_SPEC_VERSION; +- portParamType->nSize = sizeof(portParamType); ++ portParamType->nSize = sizeof(OMX_PORT_PARAM_TYPE); + portParamType->nPorts = 2; + portParamType->nStartPortNumber = 0; + break; + } + case OMX_IndexParamVideoPortFormat: { ++ VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_PORTFORMATTYPE); + OMX_VIDEO_PARAM_PORTFORMATTYPE *portFmt = + (OMX_VIDEO_PARAM_PORTFORMATTYPE *)paramData; + DEBUG_PRINT_LOW(""get_parameter: OMX_IndexParamVideoPortFormat""); + + portFmt->nVersion.nVersion = OMX_SPEC_VERSION; +- portFmt->nSize = sizeof(portFmt); ++ portFmt->nSize = sizeof(OMX_VIDEO_PARAM_PORTFORMATTYPE); + + if (0 == portFmt->nPortIndex) { + if (0 == portFmt->nIndex) { +@@ -3046,22 +3049,24 @@ + + } + /*Component should support this port definition*/ + case OMX_IndexParamAudioInit: { ++ VALIDATE_OMX_PARAM_DATA(paramData, OMX_PORT_PARAM_TYPE); + OMX_PORT_PARAM_TYPE *audioPortParamType = + (OMX_PORT_PARAM_TYPE *) paramData; + DEBUG_PRINT_LOW(""get_parameter: OMX_IndexParamAudioInit""); + audioPortParamType->nVersion.nVersion = OMX_SPEC_VERSION; +- audioPortParamType->nSize = sizeof(audioPortParamType); ++ audioPortParamType->nSize = sizeof(OMX_PORT_PARAM_TYPE); + audioPortParamType->nPorts = 0; + audioPortParamType->nStartPortNumber = 0; + break; + } + /*Component should support this port definition*/ + case OMX_IndexParamImageInit: { ++ VALIDATE_OMX_PARAM_DATA(paramData, OMX_PORT_PARAM_TYPE); + OMX_PORT_PARAM_TYPE *imagePortParamType = + (OMX_PORT_PARAM_TYPE *) paramData; + DEBUG_PRINT_LOW(""get_parameter: OMX_IndexParamImageInit""); + imagePortParamType->nVersion.nVersion = OMX_SPEC_VERSION; +- imagePortParamType->nSize = sizeof(imagePortParamType); ++ imagePortParamType->nSize = sizeof(OMX_PORT_PARAM_TYPE); + imagePortParamType->nPorts = 0; + imagePortParamType->nStartPortNumber = 0; + break; +@@ -3075,6 +3080,7 @@ + + break; + } + case OMX_IndexParamStandardComponentRole: { ++ VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_COMPONENTROLETYPE); + OMX_PARAM_COMPONENTROLETYPE *comp_role; + comp_role = (OMX_PARAM_COMPONENTROLETYPE *) paramData; + comp_role->nVersion.nVersion = OMX_SPEC_VERSION; +@@ -3088,22 +3094,23 @@ + + } + /* Added for parameter test */ + case OMX_IndexParamPriorityMgmt: { +- ++ VALIDATE_OMX_PARAM_DATA(paramData, OMX_PRIORITYMGMTTYPE); + OMX_PRIORITYMGMTTYPE *priorityMgmType = + (OMX_PRIORITYMGMTTYPE *) paramData; + DEBUG_PRINT_LOW(""get_parameter: OMX_IndexParamPriorityMgmt""); + priorityMgmType->nVersion.nVersion = OMX_SPEC_VERSION; +- priorityMgmType->nSize = sizeof(priorityMgmType); ++ priorityMgmType->nSize = sizeof(OMX_PRIORITYMGMTTYPE); + + break; + } + /* Added for parameter test */ + case OMX_IndexParamCompBufferSupplier: { ++ VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_BUFFERSUPPLIERTYPE); + OMX_PARAM_BUFFERSUPPLIERTYPE *bufferSupplierType = + (OMX_PARAM_BUFFERSUPPLIERTYPE*) paramData; + DEBUG_PRINT_LOW(""get_parameter: OMX_IndexParamCompBufferSupplier""); + +- bufferSupplierType->nSize = sizeof(bufferSupplierType); ++ bufferSupplierType->nSize = sizeof(OMX_PARAM_BUFFERSUPPLIERTYPE); + bufferSupplierType->nVersion.nVersion = OMX_SPEC_VERSION; + if (0 == bufferSupplierType->nPortIndex) + bufferSupplierType->nPortIndex = OMX_BufferSupplyUnspecified; +@@ -3141,6 +3148,7 @@ + + break; + } + case OMX_IndexParamVideoProfileLevelQuerySupported: { ++ VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_PROFILELEVELTYPE); + DEBUG_PRINT_LOW(""get_parameter: OMX_IndexParamVideoProfileLevelQuerySupported %08x"", paramIndex); + OMX_VIDEO_PARAM_PROFILELEVELTYPE *profileLevelType = + (OMX_VIDEO_PARAM_PROFILELEVELTYPE *)paramData; +@@ -3149,6 +3157,7 @@ + + } + #if defined (_ANDROID_HONEYCOMB_) || defined (_ANDROID_ICS_) + case OMX_GoogleAndroidIndexGetAndroidNativeBufferUsage: { ++ VALIDATE_OMX_PARAM_DATA(paramData, GetAndroidNativeBufferUsageParams); + DEBUG_PRINT_LOW(""get_parameter: OMX_GoogleAndroidIndexGetAndroidNativeBufferUsage""); + GetAndroidNativeBufferUsageParams* nativeBuffersUsage = (GetAndroidNativeBufferUsageParams *) paramData; + if (nativeBuffersUsage->nPortIndex == OMX_CORE_OUTPUT_PORT_INDEX) { +@@ -3172,6 +3181,7 @@ + + #ifdef FLEXYUV_SUPPORTED + case OMX_QcomIndexFlexibleYUVDescription: { + DEBUG_PRINT_LOW(""get_parameter: describeColorFormat""); ++ VALIDATE_OMX_PARAM_DATA(paramData, DescribeColorFormatParams); + eRet = describeColorFormat(paramData); + break; + } +@@ -3282,6 +3292,7 @@ + + } + switch ((unsigned long)paramIndex) { + case OMX_IndexParamPortDefinition: { ++ VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_PORTDEFINITIONTYPE); + OMX_PARAM_PORTDEFINITIONTYPE *portDefn; + portDefn = (OMX_PARAM_PORTDEFINITIONTYPE *) paramData; + //TODO: Check if any allocate buffer/use buffer/useNativeBuffer has +@@ -3525,6 +3536,7 @@ + + } + break; + case OMX_IndexParamVideoPortFormat: { ++ VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_PORTFORMATTYPE); + OMX_VIDEO_PARAM_PORTFORMATTYPE *portFmt = + (OMX_VIDEO_PARAM_PORTFORMATTYPE *)paramData; + int ret=0; +@@ -3571,6 +3583,7 @@ + + break; + + case OMX_QcomIndexPortDefn: { ++ VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_PARAM_PORTDEFINITIONTYPE); + OMX_QCOM_PARAM_PORTDEFINITIONTYPE *portFmt = + (OMX_QCOM_PARAM_PORTDEFINITIONTYPE *) paramData; + DEBUG_PRINT_LOW(""set_parameter: OMX_IndexQcomParamPortDefinitionType %u"", +@@ -3617,6 +3630,7 @@ + + break; + + case OMX_IndexParamStandardComponentRole: { ++ VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_COMPONENTROLETYPE); + OMX_PARAM_COMPONENTROLETYPE *comp_role; + comp_role = (OMX_PARAM_COMPONENTROLETYPE *) paramData; + DEBUG_PRINT_LOW(""set_parameter: OMX_IndexParamStandardComponentRole %s"", +@@ -3707,6 +3721,7 @@ + + } + + case OMX_IndexParamPriorityMgmt: { ++ VALIDATE_OMX_PARAM_DATA(paramData, OMX_PRIORITYMGMTTYPE); + if (m_state != OMX_StateLoaded) { + DEBUG_PRINT_ERROR(""Set Parameter called in Invalid State""); + return OMX_ErrorIncorrectStateOperation; +@@ -3725,6 +3740,7 @@ + + } + + case OMX_IndexParamCompBufferSupplier: { ++ VALIDATE_OMX_PARAM_DATA(paramData, OMX_PARAM_BUFFERSUPPLIERTYPE); + OMX_PARAM_BUFFERSUPPLIERTYPE *bufferSupplierType = (OMX_PARAM_BUFFERSUPPLIERTYPE*) paramData; + DEBUG_PRINT_LOW(""set_parameter: OMX_IndexParamCompBufferSupplier %d"", + bufferSupplierType->eBufferSupplier); +@@ -3764,6 +3780,7 @@ + + break; + } + case OMX_QcomIndexParamVideoDecoderPictureOrder: { ++ VALIDATE_OMX_PARAM_DATA(paramData, QOMX_VIDEO_DECODER_PICTURE_ORDER); + QOMX_VIDEO_DECODER_PICTURE_ORDER *pictureOrder = + (QOMX_VIDEO_DECODER_PICTURE_ORDER *)paramData; + struct v4l2_control control; +@@ -3789,42 +3806,52 @@ + + break; + } + case OMX_QcomIndexParamConcealMBMapExtraData: ++ VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); + eRet = enable_extradata(VDEC_EXTRADATA_MB_ERROR_MAP, false, + ((QOMX_ENABLETYPE *)paramData)->bEnable); + break; + case OMX_QcomIndexParamFrameInfoExtraData: ++ VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); + eRet = enable_extradata(OMX_FRAMEINFO_EXTRADATA, false, + ((QOMX_ENABLETYPE *)paramData)->bEnable); + break; + case OMX_ExtraDataFrameDimension: ++ VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); + eRet = enable_extradata(OMX_FRAMEDIMENSION_EXTRADATA, false, + ((QOMX_ENABLETYPE *)paramData)->bEnable); + break; + case OMX_QcomIndexParamInterlaceExtraData: ++ VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); + eRet = enable_extradata(OMX_INTERLACE_EXTRADATA, false, + ((QOMX_ENABLETYPE *)paramData)->bEnable); + break; + case OMX_QcomIndexParamH264TimeInfo: ++ VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); + eRet = enable_extradata(OMX_TIMEINFO_EXTRADATA, false, + ((QOMX_ENABLETYPE *)paramData)->bEnable); + break; + case OMX_QcomIndexParamVideoFramePackingExtradata: ++ VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); + eRet = enable_extradata(OMX_FRAMEPACK_EXTRADATA, false, + ((QOMX_ENABLETYPE *)paramData)->bEnable); + break; + case OMX_QcomIndexParamVideoQPExtraData: ++ VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); + eRet = enable_extradata(OMX_QP_EXTRADATA, false, + ((QOMX_ENABLETYPE *)paramData)->bEnable); + break; + case OMX_QcomIndexParamVideoInputBitsInfoExtraData: ++ VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); + eRet = enable_extradata(OMX_BITSINFO_EXTRADATA, false, + ((QOMX_ENABLETYPE *)paramData)->bEnable); + break; + case OMX_QcomIndexEnableExtnUserData: ++ VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); + eRet = enable_extradata(OMX_EXTNUSER_EXTRADATA, false, + ((QOMX_ENABLETYPE *)paramData)->bEnable); + break; + case OMX_QcomIndexParamMpeg2SeqDispExtraData: ++ VALIDATE_OMX_PARAM_DATA(paramData, QOMX_ENABLETYPE); + eRet = enable_extradata(OMX_MPEG2SEQDISP_EXTRADATA, false, + ((QOMX_ENABLETYPE *)paramData)->bEnable); + break; +@@ -3833,6 +3860,7 @@ + + } + break; + case OMX_QcomIndexPlatformPvt: { ++ VALIDATE_OMX_PARAM_DATA(paramData, OMX_QCOM_PLATFORMPRIVATE_EXTN); + DEBUG_PRINT_HIGH(""set_parameter: OMX_QcomIndexPlatformPvt OP Port""); + OMX_QCOM_PLATFORMPRIVATE_EXTN* entryType = (OMX_QCOM_PLATFORMPRIVATE_EXTN *) paramData; + if (entryType->type != OMX_QCOM_PLATFORM_PRIVATE_PMEM) { +@@ -3883,6 +3911,7 @@ + + break; + + case OMX_QcomIndexParamIndexExtraDataType: { ++ VALIDATE_OMX_PARAM_DATA(paramData, QOMX_INDEXEXTRADATATYPE); + QOMX_INDEXEXTRADATATYPE *extradataIndexType = (QOMX_INDEXEXTRADATATYPE *) paramData; + if ((extradataIndexType->nIndex == OMX_IndexParamPortDefinition) && + (extradataIndexType->bEnabled == OMX_TRUE) && +@@ -3906,6 +3935,7 @@ + + * state. This is ANDROID architecture which is not in sync + * with openmax standard. */ + case OMX_GoogleAndroidIndexEnableAndroidNativeBuffers: { ++ VALIDATE_OMX_PARAM_DATA(paramData, EnableAndroidNativeBuffersParams); + EnableAndroidNativeBuffersParams* enableNativeBuffers = (EnableAndroidNativeBuffersParams *) paramData; + if (enableNativeBuffers) { + m_enable_android_native_buffers = enableNativeBuffers->enable; +@@ -3922,11 +3952,13 @@ + + } + break; + case OMX_GoogleAndroidIndexUseAndroidNativeBuffer: { ++ VALIDATE_OMX_PARAM_DATA(paramData, UseAndroidNativeBufferParams); + eRet = use_android_native_buffer(hComp, paramData); + } + break; + #endif + case OMX_QcomIndexParamEnableTimeStampReorder: { ++ VALIDATE_OMX_PARAM_DATA(paramData, QOMX_INDEXTIMESTAMPREORDER); + QOMX_INDEXTIMESTAMPREORDER *reorder = (QOMX_INDEXTIMESTAMPREORDER *)paramData; + if (drv_ctx.picture_order == (vdec_output_order)QOMX_VIDEO_DISPLAY_ORDER) { + if (reorder->bEnable == OMX_TRUE) { +@@ -3943,6 +3975,7 @@ + + } + break; + case OMX_IndexParamVideoProfileLevelCurrent: { ++ VALIDATE_OMX_PARAM_DATA(paramData, OMX_VIDEO_PARAM_PROFILELEVELTYPE); + OMX_VIDEO_PARAM_PROFILELEVELTYPE* pParam = + (OMX_VIDEO_PARAM_PROFILELEVELTYPE*)paramData; + if (pParam) { +@@ -3954,6 +3987,7 @@ + + } + case OMX_QcomIndexParamVideoMetaBufferMode: + { ++ VALIDATE_OMX_PARAM_DATA(paramData, StoreMetaDataInBuffersParams); + StoreMetaDataInBuffersParams *metabuffer = + (StoreMetaDataInBuffersParams *)paramData; + if (!metabuffer) { +@@ -3996,6 +4030,7 @@ + + } + case OMX_QcomIndexParamVideoDownScalar: + { ++ VALIDATE_OMX_PARAM_DATA(paramData, QOMX_INDEXDOWNSCALAR); + QOMX_INDEXDOWNSCALAR* pParam = (QOMX_INDEXDOWNSCALAR*)paramData; + struct v4l2_control control; + int rc; +@@ -4024,6 +4059,7 @@ + + #ifdef ADAPTIVE_PLAYBACK_SUPPORTED + case OMX_QcomIndexParamVideoAdaptivePlaybackMode: + { ++ VALIDATE_OMX_PARAM_DATA(paramData, PrepareForAdaptivePlaybackParams); + DEBUG_PRINT_LOW(""set_parameter: OMX_GoogleAndroidIndexPrepareForAdaptivePlayback""); + PrepareForAdaptivePlaybackParams* pParams = + (PrepareForAdaptivePlaybackParams *) paramData; +@@ -4052,6 +4088,7 @@ + + #endif + case OMX_QcomIndexParamVideoCustomBufferSize: + { ++ VALIDATE_OMX_PARAM_DATA(paramData, QOMX_VIDEO_CUSTOM_BUFFERSIZE); + DEBUG_PRINT_LOW(""set_parameter: OMX_QcomIndexParamVideoCustomBufferSize""); + QOMX_VIDEO_CUSTOM_BUFFERSIZE* pParam = (QOMX_VIDEO_CUSTOM_BUFFERSIZE*)paramData; + if (pParam->nPortIndex == OMX_CORE_INPUT_PORT_INDEX) { +@@ -4115,6 +4152,7 @@ + + + switch ((unsigned long)configIndex) { + case OMX_QcomIndexConfigInterlaced: { ++ VALIDATE_OMX_PARAM_DATA(configData, OMX_QCOM_CONFIG_INTERLACETYPE); + OMX_QCOM_CONFIG_INTERLACETYPE *configFmt = + (OMX_QCOM_CONFIG_INTERLACETYPE *) configData; + if (configFmt->nPortIndex == 1) { +@@ -4140,6 +4178,7 @@ + + break; + } + case OMX_QcomIndexQueryNumberOfVideoDecInstance: { ++ VALIDATE_OMX_PARAM_DATA(configData, QOMX_VIDEO_QUERY_DECODER_INSTANCES); + QOMX_VIDEO_QUERY_DECODER_INSTANCES *decoderinstances = + (QOMX_VIDEO_QUERY_DECODER_INSTANCES*)configData; + decoderinstances->nNumOfInstances = 16; +@@ -4148,6 +4187,7 @@ + + } + case OMX_QcomIndexConfigVideoFramePackingArrangement: { + if (drv_ctx.decoder_format == VDEC_CODECTYPE_H264) { ++ VALIDATE_OMX_PARAM_DATA(configData, OMX_QCOM_FRAME_PACK_ARRANGEMENT); + OMX_QCOM_FRAME_PACK_ARRANGEMENT *configFmt = + (OMX_QCOM_FRAME_PACK_ARRANGEMENT *) configData; + memcpy(configFmt, &m_frame_pack_arrangement, +@@ -4158,6 +4198,7 @@ + + break; + } + case OMX_IndexConfigCommonOutputCrop: { ++ VALIDATE_OMX_PARAM_DATA(configData, OMX_CONFIG_RECTTYPE); + OMX_CONFIG_RECTTYPE *rect = (OMX_CONFIG_RECTTYPE *) configData; + memcpy(rect, &rectangle, sizeof(OMX_CONFIG_RECTTYPE)); + DEBUG_PRINT_HIGH(""get_config: crop info: L: %u, T: %u, R: %u, B: %u"", +@@ -4166,6 +4207,7 @@ + + break; + } + case OMX_QcomIndexConfigPerfLevel: { ++ VALIDATE_OMX_PARAM_DATA(configData, OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL); + struct v4l2_control control; + OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *perf = + (OMX_QCOM_VIDEO_CONFIG_PERF_LEVEL *)configData; +@@ -4191,7 +4233,7 @@ + + } + + break; +- } ++ } + default: { + DEBUG_PRINT_ERROR(""get_config: unknown param %d"",configIndex); + eRet = OMX_ErrorBadParameter; +@@ -4337,6 +4379,7 @@ + + struct v4l2_control temp; + temp.id = V4L2_CID_MPEG_VIDC_VIDEO_STREAM_FORMAT; + ++ VALIDATE_OMX_PARAM_DATA(configData, OMX_VIDEO_CONFIG_NALSIZE); + pNal = reinterpret_cast < OMX_VIDEO_CONFIG_NALSIZE * >(configData); + switch (pNal->nNaluBytes) { + case 0: +@@ -8752,7 +8795,7 @@ + + } + DEBUG_PRINT_LOW(""omx_vdec::update_portdef""); + portDefn->nVersion.nVersion = OMX_SPEC_VERSION; +- portDefn->nSize = sizeof(portDefn); ++ portDefn->nSize = sizeof(OMX_PARAM_PORTDEFINITIONTYPE); + portDefn->eDomain = OMX_PortDomainVideo; + if (drv_ctx.frame_rate.fps_denominator > 0) + portDefn->format.video.xFramerate = (drv_ctx.frame_rate.fps_numerator / +",903,1234,2048 +18261,"static int jpc_pi_nextrpcl(register jpc_pi_t *pi) +{ + int rlvlno; + jpc_pirlvl_t *pirlvl; + jpc_pchg_t *pchg; + int prchind; + int prcvind; + int *prclyrno; + int compno; + jpc_picomp_t *picomp; + int xstep; + int ystep; + uint_fast32_t r; + uint_fast32_t rpx; + uint_fast32_t rpy; + uint_fast32_t trx0; + uint_fast32_t try0; + + pchg = pi->pchg; + if (!pi->prgvolfirst) { + goto skip; + } else { + pi->xstep = 0; + pi->ystep = 0; + for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; + ++compno, ++picomp) { + for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < + picomp->numrlvls; ++rlvlno, ++pirlvl) { + xstep = picomp->hsamp * (1 << (pirlvl->prcwidthexpn + + picomp->numrlvls - rlvlno - 1)); + ystep = picomp->vsamp * (1 << (pirlvl->prcheightexpn + + picomp->numrlvls - rlvlno - 1)); + pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); + pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); + } + } + pi->prgvolfirst = 0; + } + + for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend && + pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) { + for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += + pi->ystep - (pi->y % pi->ystep)) { + for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += + pi->xstep - (pi->x % pi->xstep)) { + for (pi->compno = pchg->compnostart, + pi->picomp = &pi->picomps[pi->compno]; + pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < + pi->numcomps; ++pi->compno, ++pi->picomp) { + if (pi->rlvlno >= pi->picomp->numrlvls) { + continue; + } + pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; + if (pi->pirlvl->numprcs == 0) { + continue; + } + r = pi->picomp->numrlvls - 1 - pi->rlvlno; + rpx = r + pi->pirlvl->prcwidthexpn; + rpy = r + pi->pirlvl->prcheightexpn; + trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); + try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); + if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) + || !(pi->x % (1 << rpx))) && + ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) + || !(pi->y % (1 << rpy)))) { + prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp + << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, + pi->pirlvl->prcwidthexpn); + prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp + << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, + pi->pirlvl->prcheightexpn); + pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; + + assert(pi->prcno < pi->pirlvl->numprcs); + for (pi->lyrno = 0; pi->lyrno < + pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { + prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; + if (pi->lyrno >= *prclyrno) { + ++(*prclyrno); + return 0; + } +skip: + ; + } + } + } + } + } + } + return 1; +} +",1,"static int jpc_pi_nextrpcl(register jpc_pi_t *pi) +{ + int rlvlno; + jpc_pirlvl_t *pirlvl; + jpc_pchg_t *pchg; + int prchind; + int prcvind; + int *prclyrno; + int compno; + jpc_picomp_t *picomp; + int xstep; + int ystep; + uint_fast32_t r; + uint_fast32_t rpx; + uint_fast32_t rpy; + uint_fast32_t trx0; + uint_fast32_t try0; + + pchg = pi->pchg; + if (!pi->prgvolfirst) { + goto skip; + } else { + pi->xstep = 0; + pi->ystep = 0; + for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; + ++compno, ++picomp) { + for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < + picomp->numrlvls; ++rlvlno, ++pirlvl) { + // Check for the potential for overflow problems. + if (pirlvl->prcwidthexpn + pi->picomp->numrlvls > + JAS_UINTFAST32_NUMBITS - 2 || + pirlvl->prcheightexpn + pi->picomp->numrlvls > + JAS_UINTFAST32_NUMBITS - 2) { + return -1; + } + xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << + (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1)); + ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << + (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1)); + pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); + pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); + } + } + pi->prgvolfirst = 0; + } + + for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend && + pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) { + for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += + pi->ystep - (pi->y % pi->ystep)) { + for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += + pi->xstep - (pi->x % pi->xstep)) { + for (pi->compno = pchg->compnostart, + pi->picomp = &pi->picomps[pi->compno]; + pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < + pi->numcomps; ++pi->compno, ++pi->picomp) { + if (pi->rlvlno >= pi->picomp->numrlvls) { + continue; + } + pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; + if (pi->pirlvl->numprcs == 0) { + continue; + } + r = pi->picomp->numrlvls - 1 - pi->rlvlno; + rpx = r + pi->pirlvl->prcwidthexpn; + rpy = r + pi->pirlvl->prcheightexpn; + trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); + try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); + if (((pi->x == pi->xstart && + ((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) + || !(pi->x % (JAS_CAST(uint_fast32_t, 1) << rpx))) && + ((pi->y == pi->ystart && + ((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) + || !(pi->y % (JAS_CAST(uint_fast32_t, 1) << rpy)))) { + prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, + pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - + JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); + prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, + pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - + JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); + pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; + + assert(pi->prcno < pi->pirlvl->numprcs); + for (pi->lyrno = 0; pi->lyrno < + pi->numlyrs && pi->lyrno < JAS_CAST(int, + pchg->lyrnoend); ++pi->lyrno) { + prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; + if (pi->lyrno >= *prclyrno) { + ++(*prclyrno); + return 0; + } +skip: + ; + } + } + } + } + } + } + return 1; +} +","@@ -198,7 +198,8 @@ static int jpc_pi_nextrlcp(register jpc_pi_t *pi) + JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { + for (pi->compno = pchg->compnostart, pi->picomp = + &pi->picomps[pi->compno]; pi->compno < pi->numcomps && +- pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) { ++ pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++ ++pi->picomp) { + if (pi->rlvlno >= pi->picomp->numrlvls) { + continue; + } +@@ -247,10 +248,17 @@ static int jpc_pi_nextrpcl(register jpc_pi_t *pi) + ++compno, ++picomp) { + for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < + picomp->numrlvls; ++rlvlno, ++pirlvl) { +- xstep = picomp->hsamp * (1 << (pirlvl->prcwidthexpn + +- picomp->numrlvls - rlvlno - 1)); +- ystep = picomp->vsamp * (1 << (pirlvl->prcheightexpn + +- picomp->numrlvls - rlvlno - 1)); ++ // Check for the potential for overflow problems. ++ if (pirlvl->prcwidthexpn + pi->picomp->numrlvls > ++ JAS_UINTFAST32_NUMBITS - 2 || ++ pirlvl->prcheightexpn + pi->picomp->numrlvls > ++ JAS_UINTFAST32_NUMBITS - 2) { ++ return -1; ++ } ++ xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << ++ (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1)); ++ ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << ++ (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1)); + pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); + pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); + } +@@ -280,21 +288,24 @@ static int jpc_pi_nextrpcl(register jpc_pi_t *pi) + rpy = r + pi->pirlvl->prcheightexpn; + trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); + try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); +- if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) +- || !(pi->x % (1 << rpx))) && +- ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) +- || !(pi->y % (1 << rpy)))) { +- prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp +- << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, +- pi->pirlvl->prcwidthexpn); +- prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp +- << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, +- pi->pirlvl->prcheightexpn); ++ if (((pi->x == pi->xstart && ++ ((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) ++ || !(pi->x % (JAS_CAST(uint_fast32_t, 1) << rpx))) && ++ ((pi->y == pi->ystart && ++ ((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) ++ || !(pi->y % (JAS_CAST(uint_fast32_t, 1) << rpy)))) { ++ prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, ++ pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - ++ JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); ++ prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, ++ pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - ++ JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); + pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; + + assert(pi->prcno < pi->pirlvl->numprcs); + for (pi->lyrno = 0; pi->lyrno < +- pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { ++ pi->numlyrs && pi->lyrno < JAS_CAST(int, ++ pchg->lyrnoend); ++pi->lyrno) { + prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; + if (pi->lyrno >= *prclyrno) { + ++(*prclyrno); +@@ -339,16 +350,19 @@ static int jpc_pi_nextpcrl(register jpc_pi_t *pi) + ++compno, ++picomp) { + for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < + picomp->numrlvls; ++rlvlno, ++pirlvl) { +- xstep = picomp->hsamp * (1 << +- (pirlvl->prcwidthexpn + picomp->numrlvls - +- rlvlno - 1)); +- ystep = picomp->vsamp * (1 << +- (pirlvl->prcheightexpn + picomp->numrlvls - +- rlvlno - 1)); +- pi->xstep = (!pi->xstep) ? xstep : +- JAS_MIN(pi->xstep, xstep); +- pi->ystep = (!pi->ystep) ? ystep : +- JAS_MIN(pi->ystep, ystep); ++ // Check for the potential for overflow problems. ++ if (pirlvl->prcwidthexpn + pi->picomp->numrlvls > ++ JAS_UINTFAST32_NUMBITS - 2 || ++ pirlvl->prcheightexpn + pi->picomp->numrlvls > ++ JAS_UINTFAST32_NUMBITS - 2) { ++ return -1; ++ } ++ xstep = picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << ++ (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1)); ++ ystep = picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << ++ (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1)); ++ pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); ++ pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); + } + } + pi->prgvolfirst = 0; +@@ -375,20 +389,23 @@ static int jpc_pi_nextpcrl(register jpc_pi_t *pi) + try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); + rpx = r + pi->pirlvl->prcwidthexpn; + rpy = r + pi->pirlvl->prcheightexpn; +- if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) || ++ if (((pi->x == pi->xstart && ++ ((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) || + !(pi->x % (pi->picomp->hsamp << rpx))) && +- ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) || ++ ((pi->y == pi->ystart && ++ ((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) || + !(pi->y % (pi->picomp->vsamp << rpy)))) { +- prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp +- << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, +- pi->pirlvl->prcwidthexpn); +- prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp +- << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, +- pi->pirlvl->prcheightexpn); ++ prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, ++ pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - ++ JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); ++ prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, ++ pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - ++ JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); + pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; + assert(pi->prcno < pi->pirlvl->numprcs); + for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && +- pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { ++ pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++ ++pi->lyrno) { + prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; + if (pi->lyrno >= *prclyrno) { + ++(*prclyrno); +@@ -426,10 +443,17 @@ static int jpc_pi_nextcprl(register jpc_pi_t *pi) + pi->prgvolfirst = 0; + } + +- for (pi->compno = pchg->compnostart, pi->picomp = +- &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno, +- ++pi->picomp) { ++ for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; ++ pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++ ++pi->compno, ++pi->picomp) { + pirlvl = pi->picomp->pirlvls; ++ // Check for the potential for overflow problems. ++ if (pirlvl->prcwidthexpn + pi->picomp->numrlvls > ++ JAS_UINTFAST32_NUMBITS - 2 || ++ pirlvl->prcheightexpn + pi->picomp->numrlvls > ++ JAS_UINTFAST32_NUMBITS - 2) { ++ return -1; ++ } + pi->xstep = pi->picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << + (pirlvl->prcwidthexpn + pi->picomp->numrlvls - 1)); + pi->ystep = pi->picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << +@@ -459,23 +483,23 @@ static int jpc_pi_nextcprl(register jpc_pi_t *pi) + try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); + rpx = r + pi->pirlvl->prcwidthexpn; + rpy = r + pi->pirlvl->prcheightexpn; +- if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) || ++ if (((pi->x == pi->xstart && ++ ((trx0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpx))) || + !(pi->x % (pi->picomp->hsamp << rpx))) && +- ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) || ++ ((pi->y == pi->ystart && ++ ((try0 << r) % (JAS_CAST(uint_fast32_t, 1) << rpy))) || + !(pi->y % (pi->picomp->vsamp << rpy)))) { +- prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp +- << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, +- pi->pirlvl->prcwidthexpn); +- prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp +- << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, +- pi->pirlvl->prcheightexpn); +- pi->prcno = prcvind * +- pi->pirlvl->numhprcs + +- prchind; +- assert(pi->prcno < +- pi->pirlvl->numprcs); +- for (pi->lyrno = 0; pi->lyrno < +- pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { ++ prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, ++ pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - ++ JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); ++ prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, ++ pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - ++ JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); ++ pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; ++ assert(pi->prcno < pi->pirlvl->numprcs); ++ for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && ++ pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++ ++pi->lyrno) { + prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; + if (pi->lyrno >= *prclyrno) { + ++(*prclyrno);",1211,1542,2048 +1452,"do_exec_no_pty(Session *s, const char *command) +{ + pid_t pid; + +#ifdef USE_PIPES + int pin[2], pout[2], perr[2]; + + if (s == NULL) + fatal(""do_exec_no_pty: no session""); + + /* Allocate pipes for communicating with the program. */ + if (pipe(pin) < 0) { + error(""%s: pipe in: %.100s"", __func__, strerror(errno)); + return -1; + } + if (pipe(pout) < 0) { + error(""%s: pipe out: %.100s"", __func__, strerror(errno)); + close(pin[0]); + close(pin[1]); + return -1; + } + if (pipe(perr) < 0) { + error(""%s: pipe err: %.100s"", __func__, + strerror(errno)); + close(pin[0]); + close(pin[1]); + close(pout[0]); + close(pout[1]); + return -1; + } +#else + int inout[2], err[2]; + + if (s == NULL) + fatal(""do_exec_no_pty: no session""); + + /* Uses socket pairs to communicate with the program. */ + if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0) { + error(""%s: socketpair #1: %.100s"", __func__, strerror(errno)); + return -1; + } + if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0) { + error(""%s: socketpair #2: %.100s"", __func__, + strerror(errno)); + close(inout[0]); + close(inout[1]); + return -1; + } +#endif + + session_proctitle(s); + + /* Fork the child. */ + switch ((pid = fork())) { + case -1: + error(""%s: fork: %.100s"", __func__, strerror(errno)); +#ifdef USE_PIPES + close(pin[0]); + close(pin[1]); + close(pout[0]); + close(pout[1]); + close(perr[0]); + close(perr[1]); +#else + close(inout[0]); + close(inout[1]); + close(err[0]); + close(err[1]); +#endif + return -1; + case 0: + is_child = 1; + + /* Child. Reinitialize the log since the pid has changed. */ + log_init(__progname, options.log_level, + options.log_facility, log_stderr); + + /* + * Create a new session and process group since the 4.4BSD + * setlogin() affects the entire process group. + */ + if (setsid() < 0) + error(""setsid failed: %.100s"", strerror(errno)); + +#ifdef USE_PIPES + /* + * Redirect stdin. We close the parent side of the socket + * pair, and make the child side the standard input. + */ + close(pin[1]); + if (dup2(pin[0], 0) < 0) + perror(""dup2 stdin""); + close(pin[0]); + + /* Redirect stdout. */ + close(pout[0]); + if (dup2(pout[1], 1) < 0) + perror(""dup2 stdout""); + close(pout[1]); + + /* Redirect stderr. */ + close(perr[0]); + if (dup2(perr[1], 2) < 0) + perror(""dup2 stderr""); + close(perr[1]); +#else + /* + * Redirect stdin, stdout, and stderr. Stdin and stdout will + * use the same socket, as some programs (particularly rdist) + * seem to depend on it. + */ + close(inout[1]); + close(err[1]); + if (dup2(inout[0], 0) < 0) /* stdin */ + perror(""dup2 stdin""); + if (dup2(inout[0], 1) < 0) /* stdout (same as stdin) */ + perror(""dup2 stdout""); + close(inout[0]); + if (dup2(err[0], 2) < 0) /* stderr */ + perror(""dup2 stderr""); + close(err[0]); +#endif + + +#ifdef _UNICOS + cray_init_job(s->pw); /* set up cray jid and tmpdir */ +#endif + + /* Do processing for the child (exec command etc). */ + do_child(s, command); + /* NOTREACHED */ + default: + break; + } + +#ifdef _UNICOS + signal(WJSIGNAL, cray_job_termination_handler); +#endif /* _UNICOS */ +#ifdef HAVE_CYGWIN + cygwin_set_impersonation_token(INVALID_HANDLE_VALUE); +#endif + + s->pid = pid; + /* Set interactive/non-interactive mode. */ + packet_set_interactive(s->display != NULL, + options.ip_qos_interactive, options.ip_qos_bulk); + + /* + * Clear loginmsg, since it's the child's responsibility to display + * it to the user, otherwise multiple sessions may accumulate + * multiple copies of the login messages. + */ + buffer_clear(&loginmsg); + +#ifdef USE_PIPES + /* We are the parent. Close the child sides of the pipes. */ + close(pin[0]); + close(pout[1]); + close(perr[1]); + + if (compat20) { + session_set_fds(s, pin[1], pout[0], perr[0], + s->is_subsystem, 0); + } else { + /* Enter the interactive session. */ + server_loop(pid, pin[1], pout[0], perr[0]); + /* server_loop has closed pin[1], pout[0], and perr[0]. */ + } +#else + /* We are the parent. Close the child sides of the socket pairs. */ + close(inout[0]); + close(err[0]); + + /* + * Enter the interactive session. Note: server_loop must be able to + * handle the case that fdin and fdout are the same. + */ + if (compat20) { + session_set_fds(s, inout[1], inout[1], err[1], + s->is_subsystem, 0); + } else { + server_loop(pid, inout[1], inout[1], err[1]); + /* server_loop has closed inout[1] and err[1]. */ + } +#endif + return 0; +} +",0,"do_exec_no_pty(Session *s, const char *command) +{ + pid_t pid; + +#ifdef USE_PIPES + int pin[2], pout[2], perr[2]; + + if (s == NULL) + fatal(""do_exec_no_pty: no session""); + + /* Allocate pipes for communicating with the program. */ + if (pipe(pin) < 0) { + error(""%s: pipe in: %.100s"", __func__, strerror(errno)); + return -1; + } + if (pipe(pout) < 0) { + error(""%s: pipe out: %.100s"", __func__, strerror(errno)); + close(pin[0]); + close(pin[1]); + return -1; + } + if (pipe(perr) < 0) { + error(""%s: pipe err: %.100s"", __func__, + strerror(errno)); + close(pin[0]); + close(pin[1]); + close(pout[0]); + close(pout[1]); + return -1; + } +#else + int inout[2], err[2]; + + if (s == NULL) + fatal(""do_exec_no_pty: no session""); + + /* Uses socket pairs to communicate with the program. */ + if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0) { + error(""%s: socketpair #1: %.100s"", __func__, strerror(errno)); + return -1; + } + if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0) { + error(""%s: socketpair #2: %.100s"", __func__, + strerror(errno)); + close(inout[0]); + close(inout[1]); + return -1; + } +#endif + + session_proctitle(s); + + /* Fork the child. */ + switch ((pid = fork())) { + case -1: + error(""%s: fork: %.100s"", __func__, strerror(errno)); +#ifdef USE_PIPES + close(pin[0]); + close(pin[1]); + close(pout[0]); + close(pout[1]); + close(perr[0]); + close(perr[1]); +#else + close(inout[0]); + close(inout[1]); + close(err[0]); + close(err[1]); +#endif + return -1; + case 0: + is_child = 1; + + /* Child. Reinitialize the log since the pid has changed. */ + log_init(__progname, options.log_level, + options.log_facility, log_stderr); + + /* + * Create a new session and process group since the 4.4BSD + * setlogin() affects the entire process group. + */ + if (setsid() < 0) + error(""setsid failed: %.100s"", strerror(errno)); + +#ifdef USE_PIPES + /* + * Redirect stdin. We close the parent side of the socket + * pair, and make the child side the standard input. + */ + close(pin[1]); + if (dup2(pin[0], 0) < 0) + perror(""dup2 stdin""); + close(pin[0]); + + /* Redirect stdout. */ + close(pout[0]); + if (dup2(pout[1], 1) < 0) + perror(""dup2 stdout""); + close(pout[1]); + + /* Redirect stderr. */ + close(perr[0]); + if (dup2(perr[1], 2) < 0) + perror(""dup2 stderr""); + close(perr[1]); +#else + /* + * Redirect stdin, stdout, and stderr. Stdin and stdout will + * use the same socket, as some programs (particularly rdist) + * seem to depend on it. + */ + close(inout[1]); + close(err[1]); + if (dup2(inout[0], 0) < 0) /* stdin */ + perror(""dup2 stdin""); + if (dup2(inout[0], 1) < 0) /* stdout (same as stdin) */ + perror(""dup2 stdout""); + close(inout[0]); + if (dup2(err[0], 2) < 0) /* stderr */ + perror(""dup2 stderr""); + close(err[0]); +#endif + + +#ifdef _UNICOS + cray_init_job(s->pw); /* set up cray jid and tmpdir */ +#endif + + /* Do processing for the child (exec command etc). */ + do_child(s, command); + /* NOTREACHED */ + default: + break; + } + +#ifdef _UNICOS + signal(WJSIGNAL, cray_job_termination_handler); +#endif /* _UNICOS */ +#ifdef HAVE_CYGWIN + cygwin_set_impersonation_token(INVALID_HANDLE_VALUE); +#endif + + s->pid = pid; + /* Set interactive/non-interactive mode. */ + packet_set_interactive(s->display != NULL, + options.ip_qos_interactive, options.ip_qos_bulk); + + /* + * Clear loginmsg, since it's the child's responsibility to display + * it to the user, otherwise multiple sessions may accumulate + * multiple copies of the login messages. + */ + buffer_clear(&loginmsg); + +#ifdef USE_PIPES + /* We are the parent. Close the child sides of the pipes. */ + close(pin[0]); + close(pout[1]); + close(perr[1]); + + if (compat20) { + session_set_fds(s, pin[1], pout[0], perr[0], + s->is_subsystem, 0); + } else { + /* Enter the interactive session. */ + server_loop(pid, pin[1], pout[0], perr[0]); + /* server_loop has closed pin[1], pout[0], and perr[0]. */ + } +#else + /* We are the parent. Close the child sides of the socket pairs. */ + close(inout[0]); + close(err[0]); + + /* + * Enter the interactive session. Note: server_loop must be able to + * handle the case that fdin and fdout are the same. + */ + if (compat20) { + session_set_fds(s, inout[1], inout[1], err[1], + s->is_subsystem, 0); + } else { + server_loop(pid, inout[1], inout[1], err[1]); + /* server_loop has closed inout[1] and err[1]. */ + } +#endif + return 0; +} +","@@ -1322,7 +1322,7 @@ do_setup_env(Session *s, const char *shell) + * Pull in any environment variables that may have + * been set by PAM. + */ +- if (options.use_pam) { ++ if (options.use_pam && !options.use_login) { + char **p; + + p = fetch_pam_child_environment();",1414,1745,2048 +9123,"do_note_freebsd_version(struct magic_set *ms, int swap, void *v) +{ + uint32_t desc; + + memcpy(&desc, v, sizeof(desc)); + desc = elf_getu32(swap, desc); + if (file_printf(ms, "", for FreeBSD"") == -1) + return; + + /* + * Contents is __FreeBSD_version, whose relation to OS + * versions is defined by a huge table in the Porter's + * Handbook. This is the general scheme: + * + * Releases: + * Mmp000 (before 4.10) + * Mmi0p0 (before 5.0) + * Mmm0p0 + * + * Development branches: + * Mmpxxx (before 4.6) + * Mmp1xx (before 4.10) + * Mmi1xx (before 5.0) + * M000xx (pre-M.0) + * Mmm1xx + * + * M = major version + * m = minor version + * i = minor version increment (491000 -> 4.10) + * p = patchlevel + * x = revision + * + * The first release of FreeBSD to use ELF by default + * was version 3.0. + */ + if (desc == 460002) { + if (file_printf(ms, "" 4.6.2"") == -1) + return; + } else if (desc < 460100) { + if (file_printf(ms, "" %d.%d"", desc / 100000, + desc / 10000 % 10) == -1) + return; + if (desc / 1000 % 10 > 0) + if (file_printf(ms, "".%d"", desc / 1000 % 10) == -1) + return; + if ((desc % 1000 > 0) || (desc % 100000 == 0)) + if (file_printf(ms, "" (%d)"", desc) == -1) + return; + } else if (desc < 500000) { + if (file_printf(ms, "" %d.%d"", desc / 100000, + desc / 10000 % 10 + desc / 1000 % 10) == -1) + return; + if (desc / 100 % 10 > 0) { + if (file_printf(ms, "" (%d)"", desc) == -1) + return; + } else if (desc / 10 % 10 > 0) { + if (file_printf(ms, "".%d"", desc / 10 % 10) == -1) + return; + } + } else { + if (file_printf(ms, "" %d.%d"", desc / 100000, + desc / 1000 % 100) == -1) + return; + if ((desc / 100 % 10 > 0) || + (desc % 100000 / 100 == 0)) { + if (file_printf(ms, "" (%d)"", desc) == -1) + return; + } else if (desc / 10 % 10 > 0) { + if (file_printf(ms, "".%d"", desc / 10 % 10) == -1) + return; + } + } +} +",0,"do_note_freebsd_version(struct magic_set *ms, int swap, void *v) +{ + uint32_t desc; + + memcpy(&desc, v, sizeof(desc)); + desc = elf_getu32(swap, desc); + if (file_printf(ms, "", for FreeBSD"") == -1) + return; + + /* + * Contents is __FreeBSD_version, whose relation to OS + * versions is defined by a huge table in the Porter's + * Handbook. This is the general scheme: + * + * Releases: + * Mmp000 (before 4.10) + * Mmi0p0 (before 5.0) + * Mmm0p0 + * + * Development branches: + * Mmpxxx (before 4.6) + * Mmp1xx (before 4.10) + * Mmi1xx (before 5.0) + * M000xx (pre-M.0) + * Mmm1xx + * + * M = major version + * m = minor version + * i = minor version increment (491000 -> 4.10) + * p = patchlevel + * x = revision + * + * The first release of FreeBSD to use ELF by default + * was version 3.0. + */ + if (desc == 460002) { + if (file_printf(ms, "" 4.6.2"") == -1) + return; + } else if (desc < 460100) { + if (file_printf(ms, "" %d.%d"", desc / 100000, + desc / 10000 % 10) == -1) + return; + if (desc / 1000 % 10 > 0) + if (file_printf(ms, "".%d"", desc / 1000 % 10) == -1) + return; + if ((desc % 1000 > 0) || (desc % 100000 == 0)) + if (file_printf(ms, "" (%d)"", desc) == -1) + return; + } else if (desc < 500000) { + if (file_printf(ms, "" %d.%d"", desc / 100000, + desc / 10000 % 10 + desc / 1000 % 10) == -1) + return; + if (desc / 100 % 10 > 0) { + if (file_printf(ms, "" (%d)"", desc) == -1) + return; + } else if (desc / 10 % 10 > 0) { + if (file_printf(ms, "".%d"", desc / 10 % 10) == -1) + return; + } + } else { + if (file_printf(ms, "" %d.%d"", desc / 100000, + desc / 1000 % 100) == -1) + return; + if ((desc / 100 % 10 > 0) || + (desc % 100000 / 100 == 0)) { + if (file_printf(ms, "" (%d)"", desc) == -1) + return; + } else if (desc / 10 % 10 > 0) { + if (file_printf(ms, "".%d"", desc / 10 % 10) == -1) + return; + } + } +} +","@@ -27,7 +27,7 @@ + #include ""file.h"" + + #ifndef lint +-FILE_RCSID(""@(#)$File: readelf.c,v 1.156 2018/10/19 00:33:04 christos Exp $"") ++FILE_RCSID(""@(#)$File: readelf.c,v 1.157 2019/01/02 19:44:14 christos Exp $"") + #endif + + #ifdef BUILTIN_ELF +@@ -752,7 +752,7 @@ do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, + char sbuf[512]; + struct NetBSD_elfcore_procinfo pi; + memset(&pi, 0, sizeof(pi)); +- memcpy(&pi, nbuf + doff, descsz); ++ memcpy(&pi, nbuf + doff, MIN(descsz, sizeof(pi))); + + if (file_printf(ms, "", from '%.31s', pid=%u, uid=%u, "" + ""gid=%u, nlwps=%u, lwp=%u (signal %u/code %u)"",",812,1143,2048 +4850,"static int get_vmx_mem_address(struct kvm_vcpu *vcpu, + unsigned long exit_qualification, + u32 vmx_instruction_info, bool wr, gva_t *ret) +{ + gva_t off; + bool exn; + struct kvm_segment s; + + /* + * According to Vol. 3B, ""Information for VM Exits Due to Instruction + * Execution"", on an exit, vmx_instruction_info holds most of the + * addressing components of the operand. Only the displacement part + * is put in exit_qualification (see 3B, ""Basic VM-Exit Information""). + * For how an actual address is calculated from all these components, + * refer to Vol. 1, ""Operand Addressing"". + */ + int scaling = vmx_instruction_info & 3; + int addr_size = (vmx_instruction_info >> 7) & 7; + bool is_reg = vmx_instruction_info & (1u << 10); + int seg_reg = (vmx_instruction_info >> 15) & 7; + int index_reg = (vmx_instruction_info >> 18) & 0xf; + bool index_is_valid = !(vmx_instruction_info & (1u << 22)); + int base_reg = (vmx_instruction_info >> 23) & 0xf; + bool base_is_valid = !(vmx_instruction_info & (1u << 27)); + + if (is_reg) { + kvm_queue_exception(vcpu, UD_VECTOR); + return 1; + } + + /* Addr = segment_base + offset */ + /* offset = base + [index * scale] + displacement */ + off = exit_qualification; /* holds the displacement */ + if (base_is_valid) + off += kvm_register_read(vcpu, base_reg); + if (index_is_valid) + off += kvm_register_read(vcpu, index_reg)< s.limit); + } + if (exn) { + kvm_queue_exception_e(vcpu, + seg_reg == VCPU_SREG_SS ? + SS_VECTOR : GP_VECTOR, + 0); + return 1; + } + + return 0; +} +",0,"static int get_vmx_mem_address(struct kvm_vcpu *vcpu, + unsigned long exit_qualification, + u32 vmx_instruction_info, bool wr, gva_t *ret) +{ + gva_t off; + bool exn; + struct kvm_segment s; + + /* + * According to Vol. 3B, ""Information for VM Exits Due to Instruction + * Execution"", on an exit, vmx_instruction_info holds most of the + * addressing components of the operand. Only the displacement part + * is put in exit_qualification (see 3B, ""Basic VM-Exit Information""). + * For how an actual address is calculated from all these components, + * refer to Vol. 1, ""Operand Addressing"". + */ + int scaling = vmx_instruction_info & 3; + int addr_size = (vmx_instruction_info >> 7) & 7; + bool is_reg = vmx_instruction_info & (1u << 10); + int seg_reg = (vmx_instruction_info >> 15) & 7; + int index_reg = (vmx_instruction_info >> 18) & 0xf; + bool index_is_valid = !(vmx_instruction_info & (1u << 22)); + int base_reg = (vmx_instruction_info >> 23) & 0xf; + bool base_is_valid = !(vmx_instruction_info & (1u << 27)); + + if (is_reg) { + kvm_queue_exception(vcpu, UD_VECTOR); + return 1; + } + + /* Addr = segment_base + offset */ + /* offset = base + [index * scale] + displacement */ + off = exit_qualification; /* holds the displacement */ + if (base_is_valid) + off += kvm_register_read(vcpu, base_reg); + if (index_is_valid) + off += kvm_register_read(vcpu, index_reg)< s.limit); + } + if (exn) { + kvm_queue_exception_e(vcpu, + seg_reg == VCPU_SREG_SS ? + SS_VECTOR : GP_VECTOR, + 0); + return 1; + } + + return 0; +} +","@@ -1389,10 +1389,10 @@ static inline bool nested_cpu_has_posted_intr(struct vmcs12 *vmcs12) + return vmcs12->pin_based_vm_exec_control & PIN_BASED_POSTED_INTR; + } + +-static inline bool is_exception(u32 intr_info) ++static inline bool is_nmi(u32 intr_info) + { + return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK)) +- == (INTR_TYPE_HARD_EXCEPTION | INTR_INFO_VALID_MASK); ++ == (INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK); + } + + static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason, +@@ -5728,7 +5728,7 @@ static int handle_exception(struct kvm_vcpu *vcpu) + if (is_machine_check(intr_info)) + return handle_machine_check(vcpu); + +- if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR) ++ if (is_nmi(intr_info)) + return 1; /* already handled by vmx_vcpu_run() */ + + if (is_no_device(intr_info)) { +@@ -8170,7 +8170,7 @@ static bool nested_vmx_exit_handled(struct kvm_vcpu *vcpu) + + switch (exit_reason) { + case EXIT_REASON_EXCEPTION_NMI: +- if (!is_exception(intr_info)) ++ if (is_nmi(intr_info)) + return false; + else if (is_page_fault(intr_info)) + return enable_ept; +@@ -8765,8 +8765,7 @@ static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx) + kvm_machine_check(); + + /* We need to handle NMIs before interrupts are enabled */ +- if ((exit_intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR && +- (exit_intr_info & INTR_INFO_VALID_MASK)) { ++ if (is_nmi(exit_intr_info)) { + kvm_before_handle_nmi(&vmx->vcpu); + asm(""int $2""); + kvm_after_handle_nmi(&vmx->vcpu);",883,1214,2048 +18042,"static int l2tp_ip6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len) +{ + struct ipv6_txoptions opt_space; + DECLARE_SOCKADDR(struct sockaddr_l2tpip6 *, lsa, msg->msg_name); + struct in6_addr *daddr, *final_p, final; + struct ipv6_pinfo *np = inet6_sk(sk); + struct ipv6_txoptions *opt = NULL; + struct ip6_flowlabel *flowlabel = NULL; + struct dst_entry *dst = NULL; + struct flowi6 fl6; + int addr_len = msg->msg_namelen; + int hlimit = -1; + int tclass = -1; + int dontfrag = -1; + int transhdrlen = 4; /* zero session-id */ + int ulen = len + transhdrlen; + int err; + + /* Rough check on arithmetic overflow, + better check is made in ip6_append_data(). + */ + if (len > INT_MAX) + return -EMSGSIZE; + + /* Mirror BSD error message compatibility */ + if (msg->msg_flags & MSG_OOB) + return -EOPNOTSUPP; + + /* + * Get and verify the address. + */ + memset(&fl6, 0, sizeof(fl6)); + + fl6.flowi6_mark = sk->sk_mark; + + if (lsa) { + if (addr_len < SIN6_LEN_RFC2133) + return -EINVAL; + + if (lsa->l2tp_family && lsa->l2tp_family != AF_INET6) + return -EAFNOSUPPORT; + + daddr = &lsa->l2tp_addr; + if (np->sndflow) { + fl6.flowlabel = lsa->l2tp_flowinfo & IPV6_FLOWINFO_MASK; + if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) { + flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); + if (flowlabel == NULL) + return -EINVAL; + } + } + + /* + * Otherwise it will be difficult to maintain + * sk->sk_dst_cache. + */ + if (sk->sk_state == TCP_ESTABLISHED && + ipv6_addr_equal(daddr, &sk->sk_v6_daddr)) + daddr = &sk->sk_v6_daddr; + + if (addr_len >= sizeof(struct sockaddr_in6) && + lsa->l2tp_scope_id && + ipv6_addr_type(daddr) & IPV6_ADDR_LINKLOCAL) + fl6.flowi6_oif = lsa->l2tp_scope_id; + } else { + if (sk->sk_state != TCP_ESTABLISHED) + return -EDESTADDRREQ; + + daddr = &sk->sk_v6_daddr; + fl6.flowlabel = np->flow_label; + } + + if (fl6.flowi6_oif == 0) + fl6.flowi6_oif = sk->sk_bound_dev_if; + + if (msg->msg_controllen) { + opt = &opt_space; + memset(opt, 0, sizeof(struct ipv6_txoptions)); + opt->tot_len = sizeof(struct ipv6_txoptions); + + err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt, + &hlimit, &tclass, &dontfrag); + if (err < 0) { + fl6_sock_release(flowlabel); + return err; + } + if ((fl6.flowlabel & IPV6_FLOWLABEL_MASK) && !flowlabel) { + flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); + if (flowlabel == NULL) + return -EINVAL; + } + if (!(opt->opt_nflen|opt->opt_flen)) + opt = NULL; + } + + if (opt == NULL) + opt = np->opt; + if (flowlabel) + opt = fl6_merge_options(&opt_space, flowlabel, opt); + opt = ipv6_fixup_options(&opt_space, opt); + + fl6.flowi6_proto = sk->sk_protocol; + if (!ipv6_addr_any(daddr)) + fl6.daddr = *daddr; + else + fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */ + if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr)) + fl6.saddr = np->saddr; + + final_p = fl6_update_dst(&fl6, opt, &final); + + if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr)) + fl6.flowi6_oif = np->mcast_oif; + else if (!fl6.flowi6_oif) + fl6.flowi6_oif = np->ucast_oif; + + security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); + + dst = ip6_dst_lookup_flow(sk, &fl6, final_p); + if (IS_ERR(dst)) { + err = PTR_ERR(dst); + goto out; + } + + if (hlimit < 0) + hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst); + + if (tclass < 0) + tclass = np->tclass; + + if (dontfrag < 0) + dontfrag = np->dontfrag; + + if (msg->msg_flags & MSG_CONFIRM) + goto do_confirm; + +back_from_confirm: + lock_sock(sk); + err = ip6_append_data(sk, ip_generic_getfrag, msg, + ulen, transhdrlen, hlimit, tclass, opt, + &fl6, (struct rt6_info *)dst, + msg->msg_flags, dontfrag); + if (err) + ip6_flush_pending_frames(sk); + else if (!(msg->msg_flags & MSG_MORE)) + err = l2tp_ip6_push_pending_frames(sk); + release_sock(sk); +done: + dst_release(dst); + out: + fl6_sock_release(flowlabel); + + return err < 0 ? err : len; + +do_confirm: + dst_confirm(dst); + if (!(msg->msg_flags & MSG_PROBE) || len) + goto back_from_confirm; + err = 0; + goto done; +} +",1,"static int l2tp_ip6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len) +{ + struct ipv6_txoptions opt_space; + DECLARE_SOCKADDR(struct sockaddr_l2tpip6 *, lsa, msg->msg_name); + struct in6_addr *daddr, *final_p, final; + struct ipv6_pinfo *np = inet6_sk(sk); + struct ipv6_txoptions *opt_to_free = NULL; + struct ipv6_txoptions *opt = NULL; + struct ip6_flowlabel *flowlabel = NULL; + struct dst_entry *dst = NULL; + struct flowi6 fl6; + int addr_len = msg->msg_namelen; + int hlimit = -1; + int tclass = -1; + int dontfrag = -1; + int transhdrlen = 4; /* zero session-id */ + int ulen = len + transhdrlen; + int err; + + /* Rough check on arithmetic overflow, + better check is made in ip6_append_data(). + */ + if (len > INT_MAX) + return -EMSGSIZE; + + /* Mirror BSD error message compatibility */ + if (msg->msg_flags & MSG_OOB) + return -EOPNOTSUPP; + + /* + * Get and verify the address. + */ + memset(&fl6, 0, sizeof(fl6)); + + fl6.flowi6_mark = sk->sk_mark; + + if (lsa) { + if (addr_len < SIN6_LEN_RFC2133) + return -EINVAL; + + if (lsa->l2tp_family && lsa->l2tp_family != AF_INET6) + return -EAFNOSUPPORT; + + daddr = &lsa->l2tp_addr; + if (np->sndflow) { + fl6.flowlabel = lsa->l2tp_flowinfo & IPV6_FLOWINFO_MASK; + if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) { + flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); + if (flowlabel == NULL) + return -EINVAL; + } + } + + /* + * Otherwise it will be difficult to maintain + * sk->sk_dst_cache. + */ + if (sk->sk_state == TCP_ESTABLISHED && + ipv6_addr_equal(daddr, &sk->sk_v6_daddr)) + daddr = &sk->sk_v6_daddr; + + if (addr_len >= sizeof(struct sockaddr_in6) && + lsa->l2tp_scope_id && + ipv6_addr_type(daddr) & IPV6_ADDR_LINKLOCAL) + fl6.flowi6_oif = lsa->l2tp_scope_id; + } else { + if (sk->sk_state != TCP_ESTABLISHED) + return -EDESTADDRREQ; + + daddr = &sk->sk_v6_daddr; + fl6.flowlabel = np->flow_label; + } + + if (fl6.flowi6_oif == 0) + fl6.flowi6_oif = sk->sk_bound_dev_if; + + if (msg->msg_controllen) { + opt = &opt_space; + memset(opt, 0, sizeof(struct ipv6_txoptions)); + opt->tot_len = sizeof(struct ipv6_txoptions); + + err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt, + &hlimit, &tclass, &dontfrag); + if (err < 0) { + fl6_sock_release(flowlabel); + return err; + } + if ((fl6.flowlabel & IPV6_FLOWLABEL_MASK) && !flowlabel) { + flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); + if (flowlabel == NULL) + return -EINVAL; + } + if (!(opt->opt_nflen|opt->opt_flen)) + opt = NULL; + } + + if (!opt) { + opt = txopt_get(np); + opt_to_free = opt; + } + if (flowlabel) + opt = fl6_merge_options(&opt_space, flowlabel, opt); + opt = ipv6_fixup_options(&opt_space, opt); + + fl6.flowi6_proto = sk->sk_protocol; + if (!ipv6_addr_any(daddr)) + fl6.daddr = *daddr; + else + fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */ + if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr)) + fl6.saddr = np->saddr; + + final_p = fl6_update_dst(&fl6, opt, &final); + + if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr)) + fl6.flowi6_oif = np->mcast_oif; + else if (!fl6.flowi6_oif) + fl6.flowi6_oif = np->ucast_oif; + + security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); + + dst = ip6_dst_lookup_flow(sk, &fl6, final_p); + if (IS_ERR(dst)) { + err = PTR_ERR(dst); + goto out; + } + + if (hlimit < 0) + hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst); + + if (tclass < 0) + tclass = np->tclass; + + if (dontfrag < 0) + dontfrag = np->dontfrag; + + if (msg->msg_flags & MSG_CONFIRM) + goto do_confirm; + +back_from_confirm: + lock_sock(sk); + err = ip6_append_data(sk, ip_generic_getfrag, msg, + ulen, transhdrlen, hlimit, tclass, opt, + &fl6, (struct rt6_info *)dst, + msg->msg_flags, dontfrag); + if (err) + ip6_flush_pending_frames(sk); + else if (!(msg->msg_flags & MSG_MORE)) + err = l2tp_ip6_push_pending_frames(sk); + release_sock(sk); +done: + dst_release(dst); + out: + fl6_sock_release(flowlabel); + txopt_put(opt_to_free); + + return err < 0 ? err : len; + +do_confirm: + dst_confirm(dst); + if (!(msg->msg_flags & MSG_PROBE) || len) + goto back_from_confirm; + err = 0; + goto done; +} +","@@ -486,6 +486,7 @@ static int l2tp_ip6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len) + DECLARE_SOCKADDR(struct sockaddr_l2tpip6 *, lsa, msg->msg_name); + struct in6_addr *daddr, *final_p, final; + struct ipv6_pinfo *np = inet6_sk(sk); ++ struct ipv6_txoptions *opt_to_free = NULL; + struct ipv6_txoptions *opt = NULL; + struct ip6_flowlabel *flowlabel = NULL; + struct dst_entry *dst = NULL; +@@ -575,8 +576,10 @@ static int l2tp_ip6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len) + opt = NULL; + } + +- if (opt == NULL) +- opt = np->opt; ++ if (!opt) { ++ opt = txopt_get(np); ++ opt_to_free = opt; ++ } + if (flowlabel) + opt = fl6_merge_options(&opt_space, flowlabel, opt); + opt = ipv6_fixup_options(&opt_space, opt); +@@ -631,6 +634,7 @@ static int l2tp_ip6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len) + dst_release(dst); + out: + fl6_sock_release(flowlabel); ++ txopt_put(opt_to_free); + + return err < 0 ? err : len; + ",1351,1682,2048 +7931,"png_handle_iTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) +{ + png_const_charp errmsg = NULL; + png_bytep buffer; + png_uint_32 prefix_length; + + png_debug(1, ""in png_handle_iTXt""); + +#ifdef PNG_USER_LIMITS_SUPPORTED + if (png_ptr->user_chunk_cache_max != 0) + { + if (png_ptr->user_chunk_cache_max == 1) + { + png_crc_finish(png_ptr, length); + return; + } + + if (--png_ptr->user_chunk_cache_max == 1) + { + png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, ""no space in chunk cache""); + return; + } + } +#endif + + if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) + png_chunk_error(png_ptr, ""missing IHDR""); + + if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) + png_ptr->mode |= PNG_AFTER_IDAT; + + buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/); + + if (buffer == NULL) + { + png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, ""out of memory""); + return; + } + + png_crc_read(png_ptr, buffer, length); + + if (png_crc_finish(png_ptr, 0) != 0) + return; + + /* First the keyword. */ + for (prefix_length=0; + prefix_length < length && buffer[prefix_length] != 0; + ++prefix_length) + /* Empty loop */ ; + + /* Perform a basic check on the keyword length here. */ + if (prefix_length > 79 || prefix_length < 1) + errmsg = ""bad keyword""; + + /* Expect keyword, compression flag, compression type, language, translated + * keyword (both may be empty but are 0 terminated) then the text, which may + * be empty. + */ + else if (prefix_length + 5 > length) + errmsg = ""truncated""; + + else if (buffer[prefix_length+1] == 0 || + (buffer[prefix_length+1] == 1 && + buffer[prefix_length+2] == PNG_COMPRESSION_TYPE_BASE)) + { + int compressed = buffer[prefix_length+1] != 0; + png_uint_32 language_offset, translated_keyword_offset; + png_alloc_size_t uncompressed_length = 0; + + /* Now the language tag */ + prefix_length += 3; + language_offset = prefix_length; + + for (; prefix_length < length && buffer[prefix_length] != 0; + ++prefix_length) + /* Empty loop */ ; + + /* WARNING: the length may be invalid here, this is checked below. */ + translated_keyword_offset = ++prefix_length; + + for (; prefix_length < length && buffer[prefix_length] != 0; + ++prefix_length) + /* Empty loop */ ; + + /* prefix_length should now be at the trailing '\0' of the translated + * keyword, but it may already be over the end. None of this arithmetic + * can overflow because chunks are at most 2^31 bytes long, but on 16-bit + * systems the available allocation may overflow. + */ + ++prefix_length; + + if (compressed == 0 && prefix_length <= length) + uncompressed_length = length - prefix_length; + + else if (compressed != 0 && prefix_length < length) + { + uncompressed_length = PNG_SIZE_MAX; + + /* TODO: at present png_decompress_chunk imposes a single application + * level memory limit, this should be split to different values for + * iCCP and text chunks. + */ + if (png_decompress_chunk(png_ptr, length, prefix_length, + &uncompressed_length, 1/*terminate*/) == Z_STREAM_END) + buffer = png_ptr->read_buffer; + + else + errmsg = png_ptr->zstream.msg; + } + + else + errmsg = ""truncated""; + + if (errmsg == NULL) + { + png_text text; + + buffer[uncompressed_length+prefix_length] = 0; + + if (compressed == 0) + text.compression = PNG_ITXT_COMPRESSION_NONE; + + else + text.compression = PNG_ITXT_COMPRESSION_zTXt; + + text.key = (png_charp)buffer; + text.lang = (png_charp)buffer + language_offset; + text.lang_key = (png_charp)buffer + translated_keyword_offset; + text.text = (png_charp)buffer + prefix_length; + text.text_length = 0; + text.itxt_length = uncompressed_length; + + if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0) + errmsg = ""insufficient memory""; + } + } + + else + errmsg = ""bad compression info""; + + if (errmsg != NULL) + png_chunk_benign_error(png_ptr, errmsg); +} +",0,"png_handle_iTXt(png_structrp png_ptr, png_inforp info_ptr, png_uint_32 length) +{ + png_const_charp errmsg = NULL; + png_bytep buffer; + png_uint_32 prefix_length; + + png_debug(1, ""in png_handle_iTXt""); + +#ifdef PNG_USER_LIMITS_SUPPORTED + if (png_ptr->user_chunk_cache_max != 0) + { + if (png_ptr->user_chunk_cache_max == 1) + { + png_crc_finish(png_ptr, length); + return; + } + + if (--png_ptr->user_chunk_cache_max == 1) + { + png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, ""no space in chunk cache""); + return; + } + } +#endif + + if ((png_ptr->mode & PNG_HAVE_IHDR) == 0) + png_chunk_error(png_ptr, ""missing IHDR""); + + if ((png_ptr->mode & PNG_HAVE_IDAT) != 0) + png_ptr->mode |= PNG_AFTER_IDAT; + + buffer = png_read_buffer(png_ptr, length+1, 1/*warn*/); + + if (buffer == NULL) + { + png_crc_finish(png_ptr, length); + png_chunk_benign_error(png_ptr, ""out of memory""); + return; + } + + png_crc_read(png_ptr, buffer, length); + + if (png_crc_finish(png_ptr, 0) != 0) + return; + + /* First the keyword. */ + for (prefix_length=0; + prefix_length < length && buffer[prefix_length] != 0; + ++prefix_length) + /* Empty loop */ ; + + /* Perform a basic check on the keyword length here. */ + if (prefix_length > 79 || prefix_length < 1) + errmsg = ""bad keyword""; + + /* Expect keyword, compression flag, compression type, language, translated + * keyword (both may be empty but are 0 terminated) then the text, which may + * be empty. + */ + else if (prefix_length + 5 > length) + errmsg = ""truncated""; + + else if (buffer[prefix_length+1] == 0 || + (buffer[prefix_length+1] == 1 && + buffer[prefix_length+2] == PNG_COMPRESSION_TYPE_BASE)) + { + int compressed = buffer[prefix_length+1] != 0; + png_uint_32 language_offset, translated_keyword_offset; + png_alloc_size_t uncompressed_length = 0; + + /* Now the language tag */ + prefix_length += 3; + language_offset = prefix_length; + + for (; prefix_length < length && buffer[prefix_length] != 0; + ++prefix_length) + /* Empty loop */ ; + + /* WARNING: the length may be invalid here, this is checked below. */ + translated_keyword_offset = ++prefix_length; + + for (; prefix_length < length && buffer[prefix_length] != 0; + ++prefix_length) + /* Empty loop */ ; + + /* prefix_length should now be at the trailing '\0' of the translated + * keyword, but it may already be over the end. None of this arithmetic + * can overflow because chunks are at most 2^31 bytes long, but on 16-bit + * systems the available allocation may overflow. + */ + ++prefix_length; + + if (compressed == 0 && prefix_length <= length) + uncompressed_length = length - prefix_length; + + else if (compressed != 0 && prefix_length < length) + { + uncompressed_length = PNG_SIZE_MAX; + + /* TODO: at present png_decompress_chunk imposes a single application + * level memory limit, this should be split to different values for + * iCCP and text chunks. + */ + if (png_decompress_chunk(png_ptr, length, prefix_length, + &uncompressed_length, 1/*terminate*/) == Z_STREAM_END) + buffer = png_ptr->read_buffer; + + else + errmsg = png_ptr->zstream.msg; + } + + else + errmsg = ""truncated""; + + if (errmsg == NULL) + { + png_text text; + + buffer[uncompressed_length+prefix_length] = 0; + + if (compressed == 0) + text.compression = PNG_ITXT_COMPRESSION_NONE; + + else + text.compression = PNG_ITXT_COMPRESSION_zTXt; + + text.key = (png_charp)buffer; + text.lang = (png_charp)buffer + language_offset; + text.lang_key = (png_charp)buffer + translated_keyword_offset; + text.text = (png_charp)buffer + prefix_length; + text.text_length = 0; + text.itxt_length = uncompressed_length; + + if (png_set_text_2(png_ptr, info_ptr, &text, 1) != 0) + errmsg = ""insufficient memory""; + } + } + + else + errmsg = ""bad compression info""; + + if (errmsg != NULL) + png_chunk_benign_error(png_ptr, errmsg); +} +","@@ -3167,10 +3167,13 @@ png_check_chunk_length(png_const_structrp png_ptr, const png_uint_32 length) + { + png_alloc_size_t idat_limit = PNG_UINT_31_MAX; + size_t row_factor = +- (png_ptr->width * png_ptr->channels * (png_ptr->bit_depth > 8? 2: 1) +- + 1 + (png_ptr->interlaced? 6: 0)); ++ (size_t)png_ptr->width ++ * (size_t)png_ptr->channels ++ * (png_ptr->bit_depth > 8? 2: 1) ++ + 1 ++ + (png_ptr->interlaced? 6: 0); + if (png_ptr->height > PNG_UINT_32_MAX/row_factor) +- idat_limit=PNG_UINT_31_MAX; ++ idat_limit = PNG_UINT_31_MAX; + else + idat_limit = png_ptr->height * row_factor; + row_factor = row_factor > 32566? 32566 : row_factor;",1071,1402,2048 +17980,"static int do_setxattr(struct btrfs_trans_handle *trans, + struct inode *inode, const char *name, + const void *value, size_t size, int flags) + { + struct btrfs_dir_item *di; + struct btrfs_root *root = BTRFS_I(inode)->root; + struct btrfs_path *path; + size_t name_len = strlen(name); + int ret = 0; + + if (name_len + size > BTRFS_MAX_XATTR_SIZE(root)) + return -ENOSPC; + + path = btrfs_alloc_path(); + if (!path) + return -ENOMEM; + + if (flags & XATTR_REPLACE) { + di = btrfs_lookup_xattr(trans, root, path, btrfs_ino(inode), name, + name_len, -1); + if (IS_ERR(di)) { + ret = PTR_ERR(di); + goto out; + } else if (!di) { + ret = -ENODATA; + goto out; + } + ret = btrfs_delete_one_dir_name(trans, root, path, di); + if (ret) + goto out; + btrfs_release_path(path); + + /* + * remove the attribute + */ + if (!value) + goto out; + } else { + di = btrfs_lookup_xattr(NULL, root, path, btrfs_ino(inode), + name, name_len, 0); + if (IS_ERR(di)) { + ret = PTR_ERR(di); + goto out; + } + if (!di && !value) + goto out; + btrfs_release_path(path); + } + +again: + ret = btrfs_insert_xattr_item(trans, root, path, btrfs_ino(inode), + name, name_len, value, size); + /* + * If we're setting an xattr to a new value but the new value is say + * exactly BTRFS_MAX_XATTR_SIZE, we could end up with EOVERFLOW getting + * back from split_leaf. This is because it thinks we'll be extending + * the existing item size, but we're asking for enough space to add the + * item itself. So if we get EOVERFLOW just set ret to EEXIST and let + * the rest of the function figure it out. + */ + if (ret == -EOVERFLOW) + ret = -EEXIST; + + if (ret == -EEXIST) { + if (flags & XATTR_CREATE) + goto out; + /* + * We can't use the path we already have since we won't have the + * proper locking for a delete, so release the path and + * re-lookup to delete the thing. + */ + btrfs_release_path(path); + di = btrfs_lookup_xattr(trans, root, path, btrfs_ino(inode), + name, name_len, -1); + if (IS_ERR(di)) { + ret = PTR_ERR(di); + goto out; + } else if (!di) { + /* Shouldn't happen but just in case... */ + btrfs_release_path(path); + goto again; + } + + ret = btrfs_delete_one_dir_name(trans, root, path, di); + if (ret) + goto out; + + /* + * We have a value to set, so go back and try to insert it now. + */ + if (value) { + btrfs_release_path(path); + goto again; + } + } + out: + btrfs_free_path(path); + return ret; +} +",1,"static int do_setxattr(struct btrfs_trans_handle *trans, + struct inode *inode, const char *name, + const void *value, size_t size, int flags) + { + struct btrfs_dir_item *di = NULL; + struct btrfs_root *root = BTRFS_I(inode)->root; + struct btrfs_path *path; + size_t name_len = strlen(name); + int ret = 0; + + if (name_len + size > BTRFS_MAX_XATTR_SIZE(root)) + return -ENOSPC; + + path = btrfs_alloc_path(); + if (!path) + return -ENOMEM; + path->skip_release_on_error = 1; + + if (!value) { + di = btrfs_lookup_xattr(trans, root, path, btrfs_ino(inode), + name, name_len, -1); + if (!di && (flags & XATTR_REPLACE)) + ret = -ENODATA; + else if (di) + ret = btrfs_delete_one_dir_name(trans, root, path, di); + goto out; + } + + /* + * For a replace we can't just do the insert blindly. + * Do a lookup first (read-only btrfs_search_slot), and return if xattr + * doesn't exist. If it exists, fall down below to the insert/replace + * path - we can't race with a concurrent xattr delete, because the VFS + * locks the inode's i_mutex before calling setxattr or removexattr. + */ + if (flags & XATTR_REPLACE) { + ASSERT(mutex_is_locked(&inode->i_mutex)); + di = btrfs_lookup_xattr(NULL, root, path, btrfs_ino(inode), + name, name_len, 0); + if (!di) { + ret = -ENODATA; + goto out; + } + btrfs_release_path(path); + di = NULL; + } + + ret = btrfs_insert_xattr_item(trans, root, path, btrfs_ino(inode), + name, name_len, value, size); + if (ret == -EOVERFLOW) { + /* + * We have an existing item in a leaf, split_leaf couldn't + * expand it. That item might have or not a dir_item that + * matches our target xattr, so lets check. + */ + ret = 0; + btrfs_assert_tree_locked(path->nodes[0]); + di = btrfs_match_dir_item_name(root, path, name, name_len); + if (!di && !(flags & XATTR_REPLACE)) { + ret = -ENOSPC; + goto out; + } + } else if (ret == -EEXIST) { + ret = 0; + di = btrfs_match_dir_item_name(root, path, name, name_len); + ASSERT(di); /* logic error */ + } else if (ret) { + goto out; + } + + if (di && (flags & XATTR_CREATE)) { + ret = -EEXIST; + goto out; + } + + if (di) { + /* + * We're doing a replace, and it must be atomic, that is, at + * any point in time we have either the old or the new xattr + * value in the tree. We don't want readers (getxattr and + * listxattrs) to miss a value, this is specially important + * for ACLs. + */ + const int slot = path->slots[0]; + struct extent_buffer *leaf = path->nodes[0]; + const u16 old_data_len = btrfs_dir_data_len(leaf, di); + const u32 item_size = btrfs_item_size_nr(leaf, slot); + const u32 data_size = sizeof(*di) + name_len + size; + struct btrfs_item *item; + unsigned long data_ptr; + char *ptr; + + if (size > old_data_len) { + if (btrfs_leaf_free_space(root, leaf) < + (size - old_data_len)) { + ret = -ENOSPC; + goto out; + } + } + + if (old_data_len + name_len + sizeof(*di) == item_size) { + /* No other xattrs packed in the same leaf item. */ + if (size > old_data_len) + btrfs_extend_item(root, path, + size - old_data_len); + else if (size < old_data_len) + btrfs_truncate_item(root, path, data_size, 1); + } else { + /* There are other xattrs packed in the same item. */ + ret = btrfs_delete_one_dir_name(trans, root, path, di); + if (ret) + goto out; + btrfs_extend_item(root, path, data_size); + } + + item = btrfs_item_nr(slot); + ptr = btrfs_item_ptr(leaf, slot, char); + ptr += btrfs_item_size(leaf, item) - data_size; + di = (struct btrfs_dir_item *)ptr; + btrfs_set_dir_data_len(leaf, di, size); + data_ptr = ((unsigned long)(di + 1)) + name_len; + write_extent_buffer(leaf, value, data_ptr, size); + btrfs_mark_buffer_dirty(leaf); + } else { + /* + * Insert, and we had space for the xattr, so path->slots[0] is + * where our xattr dir_item is and btrfs_insert_xattr_item() + * filled it. + */ + } + out: + btrfs_free_path(path); + return ret; +} +","@@ -29,6 +29,7 @@ + #include ""xattr.h"" + #include ""disk-io.h"" + #include ""props.h"" ++#include ""locking.h"" + + + ssize_t __btrfs_getxattr(struct inode *inode, const char *name, +@@ -91,7 +92,7 @@ static int do_setxattr(struct btrfs_trans_handle *trans, + struct inode *inode, const char *name, + const void *value, size_t size, int flags) + { +- struct btrfs_dir_item *di; ++ struct btrfs_dir_item *di = NULL; + struct btrfs_root *root = BTRFS_I(inode)->root; + struct btrfs_path *path; + size_t name_len = strlen(name); +@@ -103,84 +104,119 @@ static int do_setxattr(struct btrfs_trans_handle *trans, + path = btrfs_alloc_path(); + if (!path) + return -ENOMEM; ++ path->skip_release_on_error = 1; ++ ++ if (!value) { ++ di = btrfs_lookup_xattr(trans, root, path, btrfs_ino(inode), ++ name, name_len, -1); ++ if (!di && (flags & XATTR_REPLACE)) ++ ret = -ENODATA; ++ else if (di) ++ ret = btrfs_delete_one_dir_name(trans, root, path, di); ++ goto out; ++ } + ++ /* ++ * For a replace we can't just do the insert blindly. ++ * Do a lookup first (read-only btrfs_search_slot), and return if xattr ++ * doesn't exist. If it exists, fall down below to the insert/replace ++ * path - we can't race with a concurrent xattr delete, because the VFS ++ * locks the inode's i_mutex before calling setxattr or removexattr. ++ */ + if (flags & XATTR_REPLACE) { +- di = btrfs_lookup_xattr(trans, root, path, btrfs_ino(inode), name, +- name_len, -1); +- if (IS_ERR(di)) { +- ret = PTR_ERR(di); +- goto out; +- } else if (!di) { ++ ASSERT(mutex_is_locked(&inode->i_mutex)); ++ di = btrfs_lookup_xattr(NULL, root, path, btrfs_ino(inode), ++ name, name_len, 0); ++ if (!di) { + ret = -ENODATA; + goto out; + } +- ret = btrfs_delete_one_dir_name(trans, root, path, di); +- if (ret) +- goto out; + btrfs_release_path(path); ++ di = NULL; ++ } + ++ ret = btrfs_insert_xattr_item(trans, root, path, btrfs_ino(inode), ++ name, name_len, value, size); ++ if (ret == -EOVERFLOW) { + /* +- * remove the attribute ++ * We have an existing item in a leaf, split_leaf couldn't ++ * expand it. That item might have or not a dir_item that ++ * matches our target xattr, so lets check. + */ +- if (!value) +- goto out; +- } else { +- di = btrfs_lookup_xattr(NULL, root, path, btrfs_ino(inode), +- name, name_len, 0); +- if (IS_ERR(di)) { +- ret = PTR_ERR(di); ++ ret = 0; ++ btrfs_assert_tree_locked(path->nodes[0]); ++ di = btrfs_match_dir_item_name(root, path, name, name_len); ++ if (!di && !(flags & XATTR_REPLACE)) { ++ ret = -ENOSPC; + goto out; + } +- if (!di && !value) +- goto out; +- btrfs_release_path(path); ++ } else if (ret == -EEXIST) { ++ ret = 0; ++ di = btrfs_match_dir_item_name(root, path, name, name_len); ++ ASSERT(di); /* logic error */ ++ } else if (ret) { ++ goto out; + } + +-again: +- ret = btrfs_insert_xattr_item(trans, root, path, btrfs_ino(inode), +- name, name_len, value, size); +- /* +- * If we're setting an xattr to a new value but the new value is say +- * exactly BTRFS_MAX_XATTR_SIZE, we could end up with EOVERFLOW getting +- * back from split_leaf. This is because it thinks we'll be extending +- * the existing item size, but we're asking for enough space to add the +- * item itself. So if we get EOVERFLOW just set ret to EEXIST and let +- * the rest of the function figure it out. +- */ +- if (ret == -EOVERFLOW) ++ if (di && (flags & XATTR_CREATE)) { + ret = -EEXIST; ++ goto out; ++ } + +- if (ret == -EEXIST) { +- if (flags & XATTR_CREATE) +- goto out; ++ if (di) { + /* +- * We can't use the path we already have since we won't have the +- * proper locking for a delete, so release the path and +- * re-lookup to delete the thing. ++ * We're doing a replace, and it must be atomic, that is, at ++ * any point in time we have either the old or the new xattr ++ * value in the tree. We don't want readers (getxattr and ++ * listxattrs) to miss a value, this is specially important ++ * for ACLs. + */ +- btrfs_release_path(path); +- di = btrfs_lookup_xattr(trans, root, path, btrfs_ino(inode), +- name, name_len, -1); +- if (IS_ERR(di)) { +- ret = PTR_ERR(di); +- goto out; +- } else if (!di) { +- /* Shouldn't happen but just in case... */ +- btrfs_release_path(path); +- goto again; ++ const int slot = path->slots[0]; ++ struct extent_buffer *leaf = path->nodes[0]; ++ const u16 old_data_len = btrfs_dir_data_len(leaf, di); ++ const u32 item_size = btrfs_item_size_nr(leaf, slot); ++ const u32 data_size = sizeof(*di) + name_len + size; ++ struct btrfs_item *item; ++ unsigned long data_ptr; ++ char *ptr; ++ ++ if (size > old_data_len) { ++ if (btrfs_leaf_free_space(root, leaf) < ++ (size - old_data_len)) { ++ ret = -ENOSPC; ++ goto out; ++ } + } + +- ret = btrfs_delete_one_dir_name(trans, root, path, di); +- if (ret) +- goto out; ++ if (old_data_len + name_len + sizeof(*di) == item_size) { ++ /* No other xattrs packed in the same leaf item. */ ++ if (size > old_data_len) ++ btrfs_extend_item(root, path, ++ size - old_data_len); ++ else if (size < old_data_len) ++ btrfs_truncate_item(root, path, data_size, 1); ++ } else { ++ /* There are other xattrs packed in the same item. */ ++ ret = btrfs_delete_one_dir_name(trans, root, path, di); ++ if (ret) ++ goto out; ++ btrfs_extend_item(root, path, data_size); ++ } + ++ item = btrfs_item_nr(slot); ++ ptr = btrfs_item_ptr(leaf, slot, char); ++ ptr += btrfs_item_size(leaf, item) - data_size; ++ di = (struct btrfs_dir_item *)ptr; ++ btrfs_set_dir_data_len(leaf, di, size); ++ data_ptr = ((unsigned long)(di + 1)) + name_len; ++ write_extent_buffer(leaf, value, data_ptr, size); ++ btrfs_mark_buffer_dirty(leaf); ++ } else { + /* +- * We have a value to set, so go back and try to insert it now. ++ * Insert, and we had space for the xattr, so path->slots[0] is ++ * where our xattr dir_item is and btrfs_insert_xattr_item() ++ * filled it. + */ +- if (value) { +- btrfs_release_path(path); +- goto again; +- } + } + out: + btrfs_free_path(path);",759,1090,2048 +3651,"xfs_da3_blk_link( + struct xfs_da_state *state, + struct xfs_da_state_blk *old_blk, + struct xfs_da_state_blk *new_blk) +{ + struct xfs_da_blkinfo *old_info; + struct xfs_da_blkinfo *new_info; + struct xfs_da_blkinfo *tmp_info; + struct xfs_da_args *args; + struct xfs_buf *bp; + int before = 0; + int error; + struct xfs_inode *dp = state->args->dp; + + /* + * Set up environment. + */ + args = state->args; + ASSERT(args != NULL); + old_info = old_blk->bp->b_addr; + new_info = new_blk->bp->b_addr; + ASSERT(old_blk->magic == XFS_DA_NODE_MAGIC || + old_blk->magic == XFS_DIR2_LEAFN_MAGIC || + old_blk->magic == XFS_ATTR_LEAF_MAGIC); + + switch (old_blk->magic) { + case XFS_ATTR_LEAF_MAGIC: + before = xfs_attr_leaf_order(old_blk->bp, new_blk->bp); + break; + case XFS_DIR2_LEAFN_MAGIC: + before = xfs_dir2_leafn_order(dp, old_blk->bp, new_blk->bp); + break; + case XFS_DA_NODE_MAGIC: + before = xfs_da3_node_order(dp, old_blk->bp, new_blk->bp); + break; + } + + /* + * Link blocks in appropriate order. + */ + if (before) { + /* + * Link new block in before existing block. + */ + trace_xfs_da_link_before(args); + new_info->forw = cpu_to_be32(old_blk->blkno); + new_info->back = old_info->back; + if (old_info->back) { + error = xfs_da3_node_read(args->trans, dp, + be32_to_cpu(old_info->back), + -1, &bp, args->whichfork); + if (error) + return(error); + ASSERT(bp != NULL); + tmp_info = bp->b_addr; + ASSERT(tmp_info->magic == old_info->magic); + ASSERT(be32_to_cpu(tmp_info->forw) == old_blk->blkno); + tmp_info->forw = cpu_to_be32(new_blk->blkno); + xfs_trans_log_buf(args->trans, bp, 0, sizeof(*tmp_info)-1); + } + old_info->back = cpu_to_be32(new_blk->blkno); + } else { + /* + * Link new block in after existing block. + */ + trace_xfs_da_link_after(args); + new_info->forw = old_info->forw; + new_info->back = cpu_to_be32(old_blk->blkno); + if (old_info->forw) { + error = xfs_da3_node_read(args->trans, dp, + be32_to_cpu(old_info->forw), + -1, &bp, args->whichfork); + if (error) + return(error); + ASSERT(bp != NULL); + tmp_info = bp->b_addr; + ASSERT(tmp_info->magic == old_info->magic); + ASSERT(be32_to_cpu(tmp_info->back) == old_blk->blkno); + tmp_info->back = cpu_to_be32(new_blk->blkno); + xfs_trans_log_buf(args->trans, bp, 0, sizeof(*tmp_info)-1); + } + old_info->forw = cpu_to_be32(new_blk->blkno); + } + + xfs_trans_log_buf(args->trans, old_blk->bp, 0, sizeof(*tmp_info) - 1); + xfs_trans_log_buf(args->trans, new_blk->bp, 0, sizeof(*tmp_info) - 1); + return(0); +} +",0,"xfs_da3_blk_link( + struct xfs_da_state *state, + struct xfs_da_state_blk *old_blk, + struct xfs_da_state_blk *new_blk) +{ + struct xfs_da_blkinfo *old_info; + struct xfs_da_blkinfo *new_info; + struct xfs_da_blkinfo *tmp_info; + struct xfs_da_args *args; + struct xfs_buf *bp; + int before = 0; + int error; + struct xfs_inode *dp = state->args->dp; + + /* + * Set up environment. + */ + args = state->args; + ASSERT(args != NULL); + old_info = old_blk->bp->b_addr; + new_info = new_blk->bp->b_addr; + ASSERT(old_blk->magic == XFS_DA_NODE_MAGIC || + old_blk->magic == XFS_DIR2_LEAFN_MAGIC || + old_blk->magic == XFS_ATTR_LEAF_MAGIC); + + switch (old_blk->magic) { + case XFS_ATTR_LEAF_MAGIC: + before = xfs_attr_leaf_order(old_blk->bp, new_blk->bp); + break; + case XFS_DIR2_LEAFN_MAGIC: + before = xfs_dir2_leafn_order(dp, old_blk->bp, new_blk->bp); + break; + case XFS_DA_NODE_MAGIC: + before = xfs_da3_node_order(dp, old_blk->bp, new_blk->bp); + break; + } + + /* + * Link blocks in appropriate order. + */ + if (before) { + /* + * Link new block in before existing block. + */ + trace_xfs_da_link_before(args); + new_info->forw = cpu_to_be32(old_blk->blkno); + new_info->back = old_info->back; + if (old_info->back) { + error = xfs_da3_node_read(args->trans, dp, + be32_to_cpu(old_info->back), + -1, &bp, args->whichfork); + if (error) + return(error); + ASSERT(bp != NULL); + tmp_info = bp->b_addr; + ASSERT(tmp_info->magic == old_info->magic); + ASSERT(be32_to_cpu(tmp_info->forw) == old_blk->blkno); + tmp_info->forw = cpu_to_be32(new_blk->blkno); + xfs_trans_log_buf(args->trans, bp, 0, sizeof(*tmp_info)-1); + } + old_info->back = cpu_to_be32(new_blk->blkno); + } else { + /* + * Link new block in after existing block. + */ + trace_xfs_da_link_after(args); + new_info->forw = old_info->forw; + new_info->back = cpu_to_be32(old_blk->blkno); + if (old_info->forw) { + error = xfs_da3_node_read(args->trans, dp, + be32_to_cpu(old_info->forw), + -1, &bp, args->whichfork); + if (error) + return(error); + ASSERT(bp != NULL); + tmp_info = bp->b_addr; + ASSERT(tmp_info->magic == old_info->magic); + ASSERT(be32_to_cpu(tmp_info->back) == old_blk->blkno); + tmp_info->back = cpu_to_be32(new_blk->blkno); + xfs_trans_log_buf(args->trans, bp, 0, sizeof(*tmp_info)-1); + } + old_info->forw = cpu_to_be32(new_blk->blkno); + } + + xfs_trans_log_buf(args->trans, old_blk->bp, 0, sizeof(*tmp_info) - 1); + xfs_trans_log_buf(args->trans, new_blk->bp, 0, sizeof(*tmp_info) - 1); + return(0); +} +","@@ -1295,7 +1295,7 @@ xfs_da3_fixhashpath( + node = blk->bp->b_addr; + dp->d_ops->node_hdr_from_disk(&nodehdr, node); + btree = dp->d_ops->node_tree_p(node); +- if (be32_to_cpu(btree->hashval) == lasthash) ++ if (be32_to_cpu(btree[blk->index].hashval) == lasthash) + break; + blk->hashval = lasthash; + btree[blk->index].hashval = cpu_to_be32(lasthash);",820,1151,2048 +6750,"MODRET auth_user(cmd_rec *cmd) { + int nopass = FALSE; + config_rec *c; + const char *denymsg = NULL, *user, *origuser; + int failnopwprompt = 0, aclp, i; + unsigned char *anon_require_passwd = NULL, *login_passwd_prompt = NULL; + + if (cmd->argc < 2) { + return PR_ERROR_MSG(cmd, R_500, _(""USER: command requires a parameter"")); + } + + if (logged_in) { + /* If the client has already authenticated, BUT the given USER command + * here is for the exact same user name, then allow the command to + * succeed (Bug#4217). + */ + origuser = pr_table_get(session.notes, ""mod_auth.orig-user"", NULL); + if (origuser != NULL && + strcmp(origuser, cmd->arg) == 0) { + pr_response_add(R_230, _(""User %s logged in""), origuser); + return PR_HANDLED(cmd); + } + + pr_response_add_err(R_501, ""%s"", _(""Reauthentication not supported"")); + return PR_ERROR(cmd); + } + + user = cmd->arg; + + (void) pr_table_remove(session.notes, ""mod_auth.orig-user"", NULL); + (void) pr_table_remove(session.notes, ""mod_auth.anon-passwd"", NULL); + + if (pr_table_add_dup(session.notes, ""mod_auth.orig-user"", user, 0) < 0) { + pr_log_debug(DEBUG3, ""error stashing 'mod_auth.orig-user' in "" + ""session.notes: %s"", strerror(errno)); + } + + origuser = user; + c = pr_auth_get_anon_config(cmd->tmp_pool, &user, NULL, NULL); + + /* Check for AccessDenyMsg */ + denymsg = get_param_ptr((c ? c->subset : cmd->server->conf), ""AccessDenyMsg"", + FALSE); + if (denymsg != NULL) { + if (strstr(denymsg, ""%u"") != NULL) { + denymsg = sreplace(cmd->tmp_pool, denymsg, ""%u"", user, NULL); + } + } + + login_passwd_prompt = get_param_ptr( + (c && c->config_type == CONF_ANON) ? c->subset : main_server->conf, + ""LoginPasswordPrompt"", FALSE); + + if (login_passwd_prompt && + *login_passwd_prompt == FALSE) { + failnopwprompt = TRUE; + + } else { + failnopwprompt = FALSE; + } + + if (failnopwprompt) { + if (!user) { + (void) pr_table_remove(session.notes, ""mod_auth.orig-user"", NULL); + (void) pr_table_remove(session.notes, ""mod_auth.anon-passwd"", NULL); + + pr_log_pri(PR_LOG_NOTICE, ""USER %s (Login failed): Not a UserAlias"", + origuser); + + if (denymsg) { + pr_response_send(R_530, ""%s"", denymsg); + + } else { + pr_response_send(R_530, _(""Login incorrect."")); + } + + pr_session_end(0); + } + + aclp = login_check_limits(main_server->conf, FALSE, TRUE, &i); + + if (c && c->config_type != CONF_ANON) { + c = (config_rec *) pcalloc(session.pool, sizeof(config_rec)); + c->config_type = CONF_ANON; + c->name = """"; /* don't really need this yet */ + c->subset = main_server->conf; + } + + if (c) { + if (!login_check_limits(c->subset, FALSE, TRUE, &i) || + (!aclp && !i) ) { + (void) pr_table_remove(session.notes, ""mod_auth.orig-user"", NULL); + (void) pr_table_remove(session.notes, ""mod_auth.anon-passwd"", NULL); + + pr_log_auth(PR_LOG_NOTICE, ""ANON %s: Limit access denies login"", + origuser); + + if (denymsg) { + pr_response_send(R_530, ""%s"", denymsg); + + } else { + pr_response_send(R_530, _(""Login incorrect."")); + } + + pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, + ""Denied by ""); + } + } + + if (c == NULL && + aclp == 0) { + (void) pr_table_remove(session.notes, ""mod_auth.orig-user"", NULL); + (void) pr_table_remove(session.notes, ""mod_auth.anon-passwd"", NULL); + + pr_log_auth(PR_LOG_NOTICE, + ""USER %s: Limit access denies login"", origuser); + + if (denymsg) { + pr_response_send(R_530, ""%s"", denymsg); + + } else { + pr_response_send(R_530, ""%s"", _(""Login incorrect."")); + } + + pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, + ""Denied by ""); + } + } + + if (c) + anon_require_passwd = get_param_ptr(c->subset, ""AnonRequirePassword"", + FALSE); + + if (c && user && (!anon_require_passwd || *anon_require_passwd == FALSE)) + nopass = TRUE; + + session.gids = NULL; + session.groups = NULL; + session.user = NULL; + session.group = NULL; + + if (nopass) { + pr_response_add(R_331, _(""Anonymous login ok, send your complete email "" + ""address as your password"")); + + } else if (pr_auth_requires_pass(cmd->tmp_pool, user) == FALSE) { + /* Check to see if a password from the client is required. In the + * vast majority of cases, a password will be required. + */ + + /* Act as if we received a PASS command from the client. */ + cmd_rec *fakecmd = pr_cmd_alloc(cmd->pool, 2, NULL); + + /* We use pstrdup() here, rather than assigning C_PASS directly, since + * code elsewhere will attempt to modify this buffer, and C_PASS is + * a string literal. + */ + fakecmd->argv[0] = pstrdup(fakecmd->pool, C_PASS); + fakecmd->argv[1] = NULL; + fakecmd->arg = NULL; + + c = add_config_param_set(&cmd->server->conf, ""authenticated"", 1, NULL); + c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); + *((unsigned char *) c->argv[0]) = TRUE; + + authenticated_without_pass = TRUE; + pr_log_auth(PR_LOG_NOTICE, ""USER %s: Authenticated without password"", user); + + pr_cmd_dispatch(fakecmd); + + } else { + pr_response_add(R_331, _(""Password required for %s""), + (char *) cmd->argv[1]); + } + + return PR_HANDLED(cmd); +} +",0,"MODRET auth_user(cmd_rec *cmd) { + int nopass = FALSE; + config_rec *c; + const char *denymsg = NULL, *user, *origuser; + int failnopwprompt = 0, aclp, i; + unsigned char *anon_require_passwd = NULL, *login_passwd_prompt = NULL; + + if (cmd->argc < 2) { + return PR_ERROR_MSG(cmd, R_500, _(""USER: command requires a parameter"")); + } + + if (logged_in) { + /* If the client has already authenticated, BUT the given USER command + * here is for the exact same user name, then allow the command to + * succeed (Bug#4217). + */ + origuser = pr_table_get(session.notes, ""mod_auth.orig-user"", NULL); + if (origuser != NULL && + strcmp(origuser, cmd->arg) == 0) { + pr_response_add(R_230, _(""User %s logged in""), origuser); + return PR_HANDLED(cmd); + } + + pr_response_add_err(R_501, ""%s"", _(""Reauthentication not supported"")); + return PR_ERROR(cmd); + } + + user = cmd->arg; + + (void) pr_table_remove(session.notes, ""mod_auth.orig-user"", NULL); + (void) pr_table_remove(session.notes, ""mod_auth.anon-passwd"", NULL); + + if (pr_table_add_dup(session.notes, ""mod_auth.orig-user"", user, 0) < 0) { + pr_log_debug(DEBUG3, ""error stashing 'mod_auth.orig-user' in "" + ""session.notes: %s"", strerror(errno)); + } + + origuser = user; + c = pr_auth_get_anon_config(cmd->tmp_pool, &user, NULL, NULL); + + /* Check for AccessDenyMsg */ + denymsg = get_param_ptr((c ? c->subset : cmd->server->conf), ""AccessDenyMsg"", + FALSE); + if (denymsg != NULL) { + if (strstr(denymsg, ""%u"") != NULL) { + denymsg = sreplace(cmd->tmp_pool, denymsg, ""%u"", user, NULL); + } + } + + login_passwd_prompt = get_param_ptr( + (c && c->config_type == CONF_ANON) ? c->subset : main_server->conf, + ""LoginPasswordPrompt"", FALSE); + + if (login_passwd_prompt && + *login_passwd_prompt == FALSE) { + failnopwprompt = TRUE; + + } else { + failnopwprompt = FALSE; + } + + if (failnopwprompt) { + if (!user) { + (void) pr_table_remove(session.notes, ""mod_auth.orig-user"", NULL); + (void) pr_table_remove(session.notes, ""mod_auth.anon-passwd"", NULL); + + pr_log_pri(PR_LOG_NOTICE, ""USER %s (Login failed): Not a UserAlias"", + origuser); + + if (denymsg) { + pr_response_send(R_530, ""%s"", denymsg); + + } else { + pr_response_send(R_530, _(""Login incorrect."")); + } + + pr_session_end(0); + } + + aclp = login_check_limits(main_server->conf, FALSE, TRUE, &i); + + if (c && c->config_type != CONF_ANON) { + c = (config_rec *) pcalloc(session.pool, sizeof(config_rec)); + c->config_type = CONF_ANON; + c->name = """"; /* don't really need this yet */ + c->subset = main_server->conf; + } + + if (c) { + if (!login_check_limits(c->subset, FALSE, TRUE, &i) || + (!aclp && !i) ) { + (void) pr_table_remove(session.notes, ""mod_auth.orig-user"", NULL); + (void) pr_table_remove(session.notes, ""mod_auth.anon-passwd"", NULL); + + pr_log_auth(PR_LOG_NOTICE, ""ANON %s: Limit access denies login"", + origuser); + + if (denymsg) { + pr_response_send(R_530, ""%s"", denymsg); + + } else { + pr_response_send(R_530, _(""Login incorrect."")); + } + + pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, + ""Denied by ""); + } + } + + if (c == NULL && + aclp == 0) { + (void) pr_table_remove(session.notes, ""mod_auth.orig-user"", NULL); + (void) pr_table_remove(session.notes, ""mod_auth.anon-passwd"", NULL); + + pr_log_auth(PR_LOG_NOTICE, + ""USER %s: Limit access denies login"", origuser); + + if (denymsg) { + pr_response_send(R_530, ""%s"", denymsg); + + } else { + pr_response_send(R_530, ""%s"", _(""Login incorrect."")); + } + + pr_session_disconnect(&auth_module, PR_SESS_DISCONNECT_CONFIG_ACL, + ""Denied by ""); + } + } + + if (c) + anon_require_passwd = get_param_ptr(c->subset, ""AnonRequirePassword"", + FALSE); + + if (c && user && (!anon_require_passwd || *anon_require_passwd == FALSE)) + nopass = TRUE; + + session.gids = NULL; + session.groups = NULL; + session.user = NULL; + session.group = NULL; + + if (nopass) { + pr_response_add(R_331, _(""Anonymous login ok, send your complete email "" + ""address as your password"")); + + } else if (pr_auth_requires_pass(cmd->tmp_pool, user) == FALSE) { + /* Check to see if a password from the client is required. In the + * vast majority of cases, a password will be required. + */ + + /* Act as if we received a PASS command from the client. */ + cmd_rec *fakecmd = pr_cmd_alloc(cmd->pool, 2, NULL); + + /* We use pstrdup() here, rather than assigning C_PASS directly, since + * code elsewhere will attempt to modify this buffer, and C_PASS is + * a string literal. + */ + fakecmd->argv[0] = pstrdup(fakecmd->pool, C_PASS); + fakecmd->argv[1] = NULL; + fakecmd->arg = NULL; + + c = add_config_param_set(&cmd->server->conf, ""authenticated"", 1, NULL); + c->argv[0] = pcalloc(c->pool, sizeof(unsigned char)); + *((unsigned char *) c->argv[0]) = TRUE; + + authenticated_without_pass = TRUE; + pr_log_auth(PR_LOG_NOTICE, ""USER %s: Authenticated without password"", user); + + pr_cmd_dispatch(fakecmd); + + } else { + pr_response_add(R_331, _(""Password required for %s""), + (char *) cmd->argv[1]); + } + + return PR_HANDLED(cmd); +} +","@@ -804,6 +804,59 @@ static const char *get_default_chdir(pool *p, xaset_t *conf) { + return dir; + } + ++static int is_symlink_path(pool *p, const char *path, size_t pathlen) { ++ int res, xerrno = 0; ++ struct stat st; ++ char *ptr; ++ ++ if (pathlen == 0) { ++ return 0; ++ } ++ ++ pr_fs_clear_cache2(path); ++ res = pr_fsio_lstat(path, &st); ++ if (res < 0) { ++ xerrno = errno; ++ ++ pr_log_pri(PR_LOG_WARNING, ""error: unable to check %s: %s"", path, ++ strerror(xerrno)); ++ ++ errno = xerrno; ++ return -1; ++ } ++ ++ if (S_ISLNK(st.st_mode)) { ++ errno = EPERM; ++ return -1; ++ } ++ ++ /* To handle the case where a component further up the path might be a ++ * symlink (which lstat(2) will NOT handle), we walk the path backwards, ++ * calling ourselves recursively. ++ */ ++ ++ ptr = strrchr(path, '/'); ++ if (ptr != NULL) { ++ char *new_path; ++ size_t new_pathlen; ++ ++ pr_signals_handle(); ++ ++ new_pathlen = ptr - path; ++ new_path = pstrndup(p, path, new_pathlen); ++ ++ pr_log_debug(DEBUG10, ++ ""AllowChrootSymlink: path '%s' not a symlink, checking '%s'"", path, ++ new_path); ++ res = is_symlink_path(p, new_path, new_pathlen); ++ if (res < 0) { ++ return -1; ++ } ++ } ++ ++ return 0; ++} ++ + /* Determine if the user (non-anon) needs a default root dir other than /. */ + static int get_default_root(pool *p, int allow_symlinks, const char **root) { + config_rec *c = NULL; +@@ -847,7 +900,6 @@ static int get_default_root(pool *p, int allow_symlinks, const char **root) { + + if (allow_symlinks == FALSE) { + char *path, target_path[PR_TUNABLE_PATH_MAX + 1]; +- struct stat st; + size_t pathlen; + + /* First, deal with any possible interpolation. dir_realpath() will +@@ -878,22 +930,13 @@ static int get_default_root(pool *p, int allow_symlinks, const char **root) { + path[pathlen-1] = '\0'; + } + +- pr_fs_clear_cache2(path); +- res = pr_fsio_lstat(path, &st); ++ res = is_symlink_path(p, path, pathlen); + if (res < 0) { +- xerrno = errno; +- +- pr_log_pri(PR_LOG_WARNING, ""error: unable to check %s: %s"", path, +- strerror(xerrno)); +- +- errno = xerrno; +- return -1; +- } ++ if (errno == EPERM) { ++ pr_log_pri(PR_LOG_WARNING, ""error: DefaultRoot %s is a symlink "" ++ ""(denied by AllowChrootSymlinks config)"", path); ++ } + +- if (S_ISLNK(st.st_mode)) { +- pr_log_pri(PR_LOG_WARNING, +- ""error: DefaultRoot %s is a symlink (denied by AllowChrootSymlinks "" +- ""config)"", path); + errno = EPERM; + return -1; + }",1488,1819,2048 +8183,"JsVar *jsvMakeIntoVariableName(JsVar *var, JsVar *valueOrZero) { + if (!var) return 0; + assert(jsvGetRefs(var)==0); // make sure it's unused + assert(jsvIsSimpleInt(var) || jsvIsString(var)); + JsVarFlags varType = (var->flags & JSV_VARTYPEMASK); + if (varType==JSV_INTEGER) { + int t = JSV_NAME_INT; + if ((jsvIsInt(valueOrZero) || jsvIsBoolean(valueOrZero)) && !jsvIsPin(valueOrZero)) { + JsVarInt v = valueOrZero->varData.integer; + if (v>=JSVARREF_MIN && v<=JSVARREF_MAX) { + t = jsvIsInt(valueOrZero) ? JSV_NAME_INT_INT : JSV_NAME_INT_BOOL; + jsvSetFirstChild(var, (JsVarRef)v); + valueOrZero = 0; + } + } + var->flags = (JsVarFlags)(var->flags & ~JSV_VARTYPEMASK) | t; + } else if (varType>=_JSV_STRING_START && varType<=_JSV_STRING_END) { + if (jsvGetCharactersInVar(var) > JSVAR_DATA_STRING_NAME_LEN) { + /* Argh. String is too large to fit in a JSV_NAME! We must chomp make + * new STRINGEXTs to put the data in + */ + JsvStringIterator it; + jsvStringIteratorNew(&it, var, JSVAR_DATA_STRING_NAME_LEN); + JsVar *startExt = jsvNewWithFlags(JSV_STRING_EXT_0); + JsVar *ext = jsvLockAgainSafe(startExt); + size_t nChars = 0; + while (ext && jsvStringIteratorHasChar(&it)) { + if (nChars >= JSVAR_DATA_STRING_MAX_LEN) { + jsvSetCharactersInVar(ext, nChars); + JsVar *ext2 = jsvNewWithFlags(JSV_STRING_EXT_0); + if (ext2) { + jsvSetLastChild(ext, jsvGetRef(ext2)); + } + jsvUnLock(ext); + ext = ext2; + nChars = 0; + } + ext->varData.str[nChars++] = jsvStringIteratorGetChar(&it); + jsvStringIteratorNext(&it); + } + jsvStringIteratorFree(&it); + if (ext) { + jsvSetCharactersInVar(ext, nChars); + jsvUnLock(ext); + } + jsvSetCharactersInVar(var, JSVAR_DATA_STRING_NAME_LEN); + JsVarRef oldRef = jsvGetLastChild(var); + while (oldRef) { + JsVar *v = jsvGetAddressOf(oldRef); + oldRef = jsvGetLastChild(v); + jsvFreePtrInternal(v); + } + jsvSetLastChild(var, jsvGetRef(startExt)); + jsvSetNextSibling(var, 0); + jsvSetPrevSibling(var, 0); + jsvSetFirstChild(var, 0); + jsvUnLock(startExt); + } + + size_t t = JSV_NAME_STRING_0; + if (jsvIsInt(valueOrZero) && !jsvIsPin(valueOrZero)) { + JsVarInt v = valueOrZero->varData.integer; + if (v>=JSVARREF_MIN && v<=JSVARREF_MAX) { + t = JSV_NAME_STRING_INT_0; + jsvSetFirstChild(var, (JsVarRef)v); + valueOrZero = 0; + } + } else + jsvSetFirstChild(var, 0); + var->flags = (var->flags & (JsVarFlags)~JSV_VARTYPEMASK) | (t+jsvGetCharactersInVar(var)); + } else assert(0); + + if (valueOrZero) + jsvSetFirstChild(var, jsvGetRef(jsvRef(valueOrZero))); + return var; +} +",0,"JsVar *jsvMakeIntoVariableName(JsVar *var, JsVar *valueOrZero) { + if (!var) return 0; + assert(jsvGetRefs(var)==0); // make sure it's unused + assert(jsvIsSimpleInt(var) || jsvIsString(var)); + JsVarFlags varType = (var->flags & JSV_VARTYPEMASK); + if (varType==JSV_INTEGER) { + int t = JSV_NAME_INT; + if ((jsvIsInt(valueOrZero) || jsvIsBoolean(valueOrZero)) && !jsvIsPin(valueOrZero)) { + JsVarInt v = valueOrZero->varData.integer; + if (v>=JSVARREF_MIN && v<=JSVARREF_MAX) { + t = jsvIsInt(valueOrZero) ? JSV_NAME_INT_INT : JSV_NAME_INT_BOOL; + jsvSetFirstChild(var, (JsVarRef)v); + valueOrZero = 0; + } + } + var->flags = (JsVarFlags)(var->flags & ~JSV_VARTYPEMASK) | t; + } else if (varType>=_JSV_STRING_START && varType<=_JSV_STRING_END) { + if (jsvGetCharactersInVar(var) > JSVAR_DATA_STRING_NAME_LEN) { + /* Argh. String is too large to fit in a JSV_NAME! We must chomp make + * new STRINGEXTs to put the data in + */ + JsvStringIterator it; + jsvStringIteratorNew(&it, var, JSVAR_DATA_STRING_NAME_LEN); + JsVar *startExt = jsvNewWithFlags(JSV_STRING_EXT_0); + JsVar *ext = jsvLockAgainSafe(startExt); + size_t nChars = 0; + while (ext && jsvStringIteratorHasChar(&it)) { + if (nChars >= JSVAR_DATA_STRING_MAX_LEN) { + jsvSetCharactersInVar(ext, nChars); + JsVar *ext2 = jsvNewWithFlags(JSV_STRING_EXT_0); + if (ext2) { + jsvSetLastChild(ext, jsvGetRef(ext2)); + } + jsvUnLock(ext); + ext = ext2; + nChars = 0; + } + ext->varData.str[nChars++] = jsvStringIteratorGetChar(&it); + jsvStringIteratorNext(&it); + } + jsvStringIteratorFree(&it); + if (ext) { + jsvSetCharactersInVar(ext, nChars); + jsvUnLock(ext); + } + jsvSetCharactersInVar(var, JSVAR_DATA_STRING_NAME_LEN); + JsVarRef oldRef = jsvGetLastChild(var); + while (oldRef) { + JsVar *v = jsvGetAddressOf(oldRef); + oldRef = jsvGetLastChild(v); + jsvFreePtrInternal(v); + } + jsvSetLastChild(var, jsvGetRef(startExt)); + jsvSetNextSibling(var, 0); + jsvSetPrevSibling(var, 0); + jsvSetFirstChild(var, 0); + jsvUnLock(startExt); + } + + size_t t = JSV_NAME_STRING_0; + if (jsvIsInt(valueOrZero) && !jsvIsPin(valueOrZero)) { + JsVarInt v = valueOrZero->varData.integer; + if (v>=JSVARREF_MIN && v<=JSVARREF_MAX) { + t = JSV_NAME_STRING_INT_0; + jsvSetFirstChild(var, (JsVarRef)v); + valueOrZero = 0; + } + } else + jsvSetFirstChild(var, 0); + var->flags = (var->flags & (JsVarFlags)~JSV_VARTYPEMASK) | (t+jsvGetCharactersInVar(var)); + } else assert(0); + + if (valueOrZero) + jsvSetFirstChild(var, jsvGetRef(jsvRef(valueOrZero))); + return var; +} +","@@ -1190,7 +1190,7 @@ size_t jsvGetString(const JsVar *v, char *str, size_t len) { + * want to pad the entire buffer with zeros */ + len--; + int l = 0; +- while (*s && l= GCRY_GCM_BLOCK_LEN)) + return GPG_ERR_INV_LENGTH; + if (c->u_mode.gcm.datalen_over_limits) + return GPG_ERR_INV_LENGTH; + + if (!c->marks.tag) + { + u32 bitlengths[2][2]; + + if (!c->u_mode.gcm.ghash_fn) + return GPG_ERR_INV_STATE; + + /* aad length */ + bitlengths[0][1] = be_bswap32(c->u_mode.gcm.aadlen[0] << 3); + bitlengths[0][0] = be_bswap32((c->u_mode.gcm.aadlen[0] >> 29) | + (c->u_mode.gcm.aadlen[1] << 3)); + /* data length */ + bitlengths[1][1] = be_bswap32(c->u_mode.gcm.datalen[0] << 3); + bitlengths[1][0] = be_bswap32((c->u_mode.gcm.datalen[0] >> 29) | + (c->u_mode.gcm.datalen[1] << 3)); + + /* Finalize data-stream. */ + do_ghash_buf(c, c->u_mode.gcm.u_tag.tag, NULL, 0, 1); + c->u_mode.gcm.ghash_aad_finalized = 1; + c->u_mode.gcm.ghash_data_finalized = 1; + + /* Add bitlengths to tag. */ + do_ghash_buf(c, c->u_mode.gcm.u_tag.tag, (byte*)bitlengths, + GCRY_GCM_BLOCK_LEN, 1); + cipher_block_xor (c->u_mode.gcm.u_tag.tag, c->u_mode.gcm.tagiv, + c->u_mode.gcm.u_tag.tag, GCRY_GCM_BLOCK_LEN); + c->marks.tag = 1; + + wipememory (bitlengths, sizeof (bitlengths)); + wipememory (c->u_mode.gcm.macbuf, GCRY_GCM_BLOCK_LEN); + wipememory (c->u_mode.gcm.tagiv, GCRY_GCM_BLOCK_LEN); + wipememory (c->u_mode.gcm.aadlen, sizeof (c->u_mode.gcm.aadlen)); + wipememory (c->u_mode.gcm.datalen, sizeof (c->u_mode.gcm.datalen)); + } + + if (!check) + { + if (outbuflen > GCRY_GCM_BLOCK_LEN) + outbuflen = GCRY_GCM_BLOCK_LEN; + + /* NB: We already checked that OUTBUF is large enough to hold + * the result or has valid truncated length. */ + memcpy (outbuf, c->u_mode.gcm.u_tag.tag, outbuflen); + } + else + { + /* OUTBUFLEN gives the length of the user supplied tag in OUTBUF + * and thus we need to compare its length first. */ + if (!is_tag_length_valid (outbuflen) + || !buf_eq_const (outbuf, c->u_mode.gcm.u_tag.tag, outbuflen)) + return GPG_ERR_CHECKSUM; + } + + return 0; +} +",0,"_gcry_cipher_gcm_tag (gcry_cipher_hd_t c, + byte * outbuf, size_t outbuflen, int check) +{ + if (!(is_tag_length_valid (outbuflen) || outbuflen >= GCRY_GCM_BLOCK_LEN)) + return GPG_ERR_INV_LENGTH; + if (c->u_mode.gcm.datalen_over_limits) + return GPG_ERR_INV_LENGTH; + + if (!c->marks.tag) + { + u32 bitlengths[2][2]; + + if (!c->u_mode.gcm.ghash_fn) + return GPG_ERR_INV_STATE; + + /* aad length */ + bitlengths[0][1] = be_bswap32(c->u_mode.gcm.aadlen[0] << 3); + bitlengths[0][0] = be_bswap32((c->u_mode.gcm.aadlen[0] >> 29) | + (c->u_mode.gcm.aadlen[1] << 3)); + /* data length */ + bitlengths[1][1] = be_bswap32(c->u_mode.gcm.datalen[0] << 3); + bitlengths[1][0] = be_bswap32((c->u_mode.gcm.datalen[0] >> 29) | + (c->u_mode.gcm.datalen[1] << 3)); + + /* Finalize data-stream. */ + do_ghash_buf(c, c->u_mode.gcm.u_tag.tag, NULL, 0, 1); + c->u_mode.gcm.ghash_aad_finalized = 1; + c->u_mode.gcm.ghash_data_finalized = 1; + + /* Add bitlengths to tag. */ + do_ghash_buf(c, c->u_mode.gcm.u_tag.tag, (byte*)bitlengths, + GCRY_GCM_BLOCK_LEN, 1); + cipher_block_xor (c->u_mode.gcm.u_tag.tag, c->u_mode.gcm.tagiv, + c->u_mode.gcm.u_tag.tag, GCRY_GCM_BLOCK_LEN); + c->marks.tag = 1; + + wipememory (bitlengths, sizeof (bitlengths)); + wipememory (c->u_mode.gcm.macbuf, GCRY_GCM_BLOCK_LEN); + wipememory (c->u_mode.gcm.tagiv, GCRY_GCM_BLOCK_LEN); + wipememory (c->u_mode.gcm.aadlen, sizeof (c->u_mode.gcm.aadlen)); + wipememory (c->u_mode.gcm.datalen, sizeof (c->u_mode.gcm.datalen)); + } + + if (!check) + { + if (outbuflen > GCRY_GCM_BLOCK_LEN) + outbuflen = GCRY_GCM_BLOCK_LEN; + + /* NB: We already checked that OUTBUF is large enough to hold + * the result or has valid truncated length. */ + memcpy (outbuf, c->u_mode.gcm.u_tag.tag, outbuflen); + } + else + { + /* OUTBUFLEN gives the length of the user supplied tag in OUTBUF + * and thus we need to compare its length first. */ + if (!is_tag_length_valid (outbuflen) + || !buf_eq_const (outbuf, c->u_mode.gcm.u_tag.tag, outbuflen)) + return GPG_ERR_CHECKSUM; + } + + return 0; +} +","@@ -30,6 +30,14 @@ + #include ""./cipher-internal.h"" + + ++/* Helper macro to force alignment to 16 or 64 bytes. */ ++#ifdef HAVE_GCC_ATTRIBUTE_ALIGNED ++# define ATTR_ALIGNED_64 __attribute__ ((aligned (64))) ++#else ++# define ATTR_ALIGNED_64 ++#endif ++ ++ + #ifdef GCM_USE_INTEL_PCLMUL + extern void _gcry_ghash_setup_intel_pclmul (gcry_cipher_hd_t c); + +@@ -83,48 +91,62 @@ ghash_armv7_neon (gcry_cipher_hd_t c, byte *result, const byte *buf, + + + #ifdef GCM_USE_TABLES +-static const u16 gcmR[256] = { +- 0x0000, 0x01c2, 0x0384, 0x0246, 0x0708, 0x06ca, 0x048c, 0x054e, +- 0x0e10, 0x0fd2, 0x0d94, 0x0c56, 0x0918, 0x08da, 0x0a9c, 0x0b5e, +- 0x1c20, 0x1de2, 0x1fa4, 0x1e66, 0x1b28, 0x1aea, 0x18ac, 0x196e, +- 0x1230, 0x13f2, 0x11b4, 0x1076, 0x1538, 0x14fa, 0x16bc, 0x177e, +- 0x3840, 0x3982, 0x3bc4, 0x3a06, 0x3f48, 0x3e8a, 0x3ccc, 0x3d0e, +- 0x3650, 0x3792, 0x35d4, 0x3416, 0x3158, 0x309a, 0x32dc, 0x331e, +- 0x2460, 0x25a2, 0x27e4, 0x2626, 0x2368, 0x22aa, 0x20ec, 0x212e, +- 0x2a70, 0x2bb2, 0x29f4, 0x2836, 0x2d78, 0x2cba, 0x2efc, 0x2f3e, +- 0x7080, 0x7142, 0x7304, 0x72c6, 0x7788, 0x764a, 0x740c, 0x75ce, +- 0x7e90, 0x7f52, 0x7d14, 0x7cd6, 0x7998, 0x785a, 0x7a1c, 0x7bde, +- 0x6ca0, 0x6d62, 0x6f24, 0x6ee6, 0x6ba8, 0x6a6a, 0x682c, 0x69ee, +- 0x62b0, 0x6372, 0x6134, 0x60f6, 0x65b8, 0x647a, 0x663c, 0x67fe, +- 0x48c0, 0x4902, 0x4b44, 0x4a86, 0x4fc8, 0x4e0a, 0x4c4c, 0x4d8e, +- 0x46d0, 0x4712, 0x4554, 0x4496, 0x41d8, 0x401a, 0x425c, 0x439e, +- 0x54e0, 0x5522, 0x5764, 0x56a6, 0x53e8, 0x522a, 0x506c, 0x51ae, +- 0x5af0, 0x5b32, 0x5974, 0x58b6, 0x5df8, 0x5c3a, 0x5e7c, 0x5fbe, +- 0xe100, 0xe0c2, 0xe284, 0xe346, 0xe608, 0xe7ca, 0xe58c, 0xe44e, +- 0xef10, 0xeed2, 0xec94, 0xed56, 0xe818, 0xe9da, 0xeb9c, 0xea5e, +- 0xfd20, 0xfce2, 0xfea4, 0xff66, 0xfa28, 0xfbea, 0xf9ac, 0xf86e, +- 0xf330, 0xf2f2, 0xf0b4, 0xf176, 0xf438, 0xf5fa, 0xf7bc, 0xf67e, +- 0xd940, 0xd882, 0xdac4, 0xdb06, 0xde48, 0xdf8a, 0xddcc, 0xdc0e, +- 0xd750, 0xd692, 0xd4d4, 0xd516, 0xd058, 0xd19a, 0xd3dc, 0xd21e, +- 0xc560, 0xc4a2, 0xc6e4, 0xc726, 0xc268, 0xc3aa, 0xc1ec, 0xc02e, +- 0xcb70, 0xcab2, 0xc8f4, 0xc936, 0xcc78, 0xcdba, 0xcffc, 0xce3e, +- 0x9180, 0x9042, 0x9204, 0x93c6, 0x9688, 0x974a, 0x950c, 0x94ce, +- 0x9f90, 0x9e52, 0x9c14, 0x9dd6, 0x9898, 0x995a, 0x9b1c, 0x9ade, +- 0x8da0, 0x8c62, 0x8e24, 0x8fe6, 0x8aa8, 0x8b6a, 0x892c, 0x88ee, +- 0x83b0, 0x8272, 0x8034, 0x81f6, 0x84b8, 0x857a, 0x873c, 0x86fe, +- 0xa9c0, 0xa802, 0xaa44, 0xab86, 0xaec8, 0xaf0a, 0xad4c, 0xac8e, +- 0xa7d0, 0xa612, 0xa454, 0xa596, 0xa0d8, 0xa11a, 0xa35c, 0xa29e, +- 0xb5e0, 0xb422, 0xb664, 0xb7a6, 0xb2e8, 0xb32a, 0xb16c, 0xb0ae, +- 0xbbf0, 0xba32, 0xb874, 0xb9b6, 0xbcf8, 0xbd3a, 0xbf7c, 0xbebe, +-}; ++static struct ++{ ++ volatile u32 counter_head; ++ u32 cacheline_align[64 / 4 - 1]; ++ u16 R[256]; ++ volatile u32 counter_tail; ++} gcm_table ATTR_ALIGNED_64 = ++ { ++ 0, ++ { 0, }, ++ { ++ 0x0000, 0x01c2, 0x0384, 0x0246, 0x0708, 0x06ca, 0x048c, 0x054e, ++ 0x0e10, 0x0fd2, 0x0d94, 0x0c56, 0x0918, 0x08da, 0x0a9c, 0x0b5e, ++ 0x1c20, 0x1de2, 0x1fa4, 0x1e66, 0x1b28, 0x1aea, 0x18ac, 0x196e, ++ 0x1230, 0x13f2, 0x11b4, 0x1076, 0x1538, 0x14fa, 0x16bc, 0x177e, ++ 0x3840, 0x3982, 0x3bc4, 0x3a06, 0x3f48, 0x3e8a, 0x3ccc, 0x3d0e, ++ 0x3650, 0x3792, 0x35d4, 0x3416, 0x3158, 0x309a, 0x32dc, 0x331e, ++ 0x2460, 0x25a2, 0x27e4, 0x2626, 0x2368, 0x22aa, 0x20ec, 0x212e, ++ 0x2a70, 0x2bb2, 0x29f4, 0x2836, 0x2d78, 0x2cba, 0x2efc, 0x2f3e, ++ 0x7080, 0x7142, 0x7304, 0x72c6, 0x7788, 0x764a, 0x740c, 0x75ce, ++ 0x7e90, 0x7f52, 0x7d14, 0x7cd6, 0x7998, 0x785a, 0x7a1c, 0x7bde, ++ 0x6ca0, 0x6d62, 0x6f24, 0x6ee6, 0x6ba8, 0x6a6a, 0x682c, 0x69ee, ++ 0x62b0, 0x6372, 0x6134, 0x60f6, 0x65b8, 0x647a, 0x663c, 0x67fe, ++ 0x48c0, 0x4902, 0x4b44, 0x4a86, 0x4fc8, 0x4e0a, 0x4c4c, 0x4d8e, ++ 0x46d0, 0x4712, 0x4554, 0x4496, 0x41d8, 0x401a, 0x425c, 0x439e, ++ 0x54e0, 0x5522, 0x5764, 0x56a6, 0x53e8, 0x522a, 0x506c, 0x51ae, ++ 0x5af0, 0x5b32, 0x5974, 0x58b6, 0x5df8, 0x5c3a, 0x5e7c, 0x5fbe, ++ 0xe100, 0xe0c2, 0xe284, 0xe346, 0xe608, 0xe7ca, 0xe58c, 0xe44e, ++ 0xef10, 0xeed2, 0xec94, 0xed56, 0xe818, 0xe9da, 0xeb9c, 0xea5e, ++ 0xfd20, 0xfce2, 0xfea4, 0xff66, 0xfa28, 0xfbea, 0xf9ac, 0xf86e, ++ 0xf330, 0xf2f2, 0xf0b4, 0xf176, 0xf438, 0xf5fa, 0xf7bc, 0xf67e, ++ 0xd940, 0xd882, 0xdac4, 0xdb06, 0xde48, 0xdf8a, 0xddcc, 0xdc0e, ++ 0xd750, 0xd692, 0xd4d4, 0xd516, 0xd058, 0xd19a, 0xd3dc, 0xd21e, ++ 0xc560, 0xc4a2, 0xc6e4, 0xc726, 0xc268, 0xc3aa, 0xc1ec, 0xc02e, ++ 0xcb70, 0xcab2, 0xc8f4, 0xc936, 0xcc78, 0xcdba, 0xcffc, 0xce3e, ++ 0x9180, 0x9042, 0x9204, 0x93c6, 0x9688, 0x974a, 0x950c, 0x94ce, ++ 0x9f90, 0x9e52, 0x9c14, 0x9dd6, 0x9898, 0x995a, 0x9b1c, 0x9ade, ++ 0x8da0, 0x8c62, 0x8e24, 0x8fe6, 0x8aa8, 0x8b6a, 0x892c, 0x88ee, ++ 0x83b0, 0x8272, 0x8034, 0x81f6, 0x84b8, 0x857a, 0x873c, 0x86fe, ++ 0xa9c0, 0xa802, 0xaa44, 0xab86, 0xaec8, 0xaf0a, 0xad4c, 0xac8e, ++ 0xa7d0, 0xa612, 0xa454, 0xa596, 0xa0d8, 0xa11a, 0xa35c, 0xa29e, ++ 0xb5e0, 0xb422, 0xb664, 0xb7a6, 0xb2e8, 0xb32a, 0xb16c, 0xb0ae, ++ 0xbbf0, 0xba32, 0xb874, 0xb9b6, 0xbcf8, 0xbd3a, 0xbf7c, 0xbebe, ++ }, ++ 0 ++ }; ++ ++#define gcmR gcm_table.R + + static inline + void prefetch_table(const void *tab, size_t len) + { + const volatile byte *vtab = tab; + size_t i; + +- for (i = 0; i < len; i += 8 * 32) ++ for (i = 0; len - i >= 8 * 32; i += 8 * 32) + { + (void)vtab[i + 0 * 32]; + (void)vtab[i + 1 * 32]; +@@ -135,15 +157,27 @@ void prefetch_table(const void *tab, size_t len) + (void)vtab[i + 6 * 32]; + (void)vtab[i + 7 * 32]; + } ++ for (; i < len; i += 32) ++ { ++ (void)vtab[i]; ++ } + + (void)vtab[len - 1]; + } + + static inline void + do_prefetch_tables (const void *gcmM, size_t gcmM_size) + { ++ /* Modify counters to trigger copy-on-write and unsharing if physical pages ++ * of look-up table are shared between processes. Modifying counters also ++ * causes checksums for pages to change and hint same-page merging algorithm ++ * that these pages are frequently changing. */ ++ gcm_table.counter_head++; ++ gcm_table.counter_tail++; ++ ++ /* Prefetch look-up tables to cache. */ + prefetch_table(gcmM, gcmM_size); +- prefetch_table(gcmR, sizeof(gcmR)); ++ prefetch_table(&gcm_table, sizeof(gcm_table)); + } + + #ifdef GCM_TABLES_USE_U64",762,1093,2048 +18823,"void SoftAMR::onQueueFilled(OMX_U32 /* portIndex */) { + List &inQueue = getPortQueue(0); + List &outQueue = getPortQueue(1); + + if (mSignalledError || mOutputPortSettingsChange != NONE) { + return; + } + + while (!inQueue.empty() && !outQueue.empty()) { + + BufferInfo *inInfo = *inQueue.begin(); + OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; + + if (inHeader->nFilledLen == 0) { + inInfo->mOwnedByUs = false; + inQueue.erase(inQueue.begin()); + notifyEmptyBufferDone(inHeader); + continue; + } + BufferInfo *outInfo = *outQueue.begin(); + OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; + + if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { + inQueue.erase(inQueue.begin()); + inInfo->mOwnedByUs = false; + notifyEmptyBufferDone(inHeader); + + outHeader->nFilledLen = 0; + outHeader->nFlags = OMX_BUFFERFLAG_EOS; + + outQueue.erase(outQueue.begin()); + outInfo->mOwnedByUs = false; + notifyFillBufferDone(outHeader); + + return; + } + + if (inHeader->nOffset == 0) { + mAnchorTimeUs = inHeader->nTimeStamp; + mNumSamplesOutput = 0; + } + + const uint8_t *inputPtr = inHeader->pBuffer + inHeader->nOffset; + int32_t numBytesRead; + + if (mMode == MODE_NARROW) { + if (outHeader->nAllocLen < kNumSamplesPerFrameNB * sizeof(int16_t)) { + ALOGE(""b/27662364: NB expected output buffer %zu bytes vs %u"", + kNumSamplesPerFrameNB * sizeof(int16_t), outHeader->nAllocLen); + android_errorWriteLog(0x534e4554, ""27662364""); + notify(OMX_EventError, OMX_ErrorOverflow, 0, NULL); + mSignalledError = true; + return; + } + + int16 mode = ((inputPtr[0] >> 3) & 0x0f); + size_t frameSize = WmfDecBytesPerFrame[mode] + 1; + + if (inHeader->nFilledLen < frameSize) { + ALOGE(""b/27662364: expected %zu bytes vs %u"", frameSize, inHeader->nFilledLen); + notify(OMX_EventError, OMX_ErrorStreamCorrupt, 0, NULL); + mSignalledError = true; + return; + } + + numBytesRead = + AMRDecode(mState, + (Frame_Type_3GPP)((inputPtr[0] >> 3) & 0x0f), + (UWord8 *)&inputPtr[1], + reinterpret_cast(outHeader->pBuffer), + MIME_IETF); + + if (numBytesRead == -1) { + ALOGE(""PV AMR decoder AMRDecode() call failed""); + + notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); + mSignalledError = true; + + return; + } + + ++numBytesRead; // Include the frame type header byte. + + if (static_cast(numBytesRead) > inHeader->nFilledLen) { + + notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); + mSignalledError = true; + + return; + } + } else { + if (outHeader->nAllocLen < kNumSamplesPerFrameWB * sizeof(int16_t)) { + ALOGE(""b/27662364: WB expected output buffer %zu bytes vs %u"", + kNumSamplesPerFrameWB * sizeof(int16_t), outHeader->nAllocLen); + android_errorWriteLog(0x534e4554, ""27662364""); + notify(OMX_EventError, OMX_ErrorOverflow, 0, NULL); + mSignalledError = true; + return; + } + + int16 mode = ((inputPtr[0] >> 3) & 0x0f); + + if (mode >= 10 && mode <= 13) { + ALOGE(""encountered illegal frame type %d in AMR WB content."", + mode); + + notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); + mSignalledError = true; + + return; + } + + size_t frameSize = getFrameSize(mode); + if (inHeader->nFilledLen < frameSize) { + ALOGE(""b/27662364: expected %zu bytes vs %u"", frameSize, inHeader->nFilledLen); + notify(OMX_EventError, OMX_ErrorStreamCorrupt, 0, NULL); + mSignalledError = true; + return; + } + + int16_t *outPtr = (int16_t *)outHeader->pBuffer; + + if (mode >= 9) { + memset(outPtr, 0, kNumSamplesPerFrameWB * sizeof(int16_t)); + } else if (mode < 9) { + int16 frameType; + RX_State_wb rx_state; + mime_unsorting( + const_cast(&inputPtr[1]), + mInputSampleBuffer, + &frameType, &mode, 1, &rx_state); + + int16_t numSamplesOutput; + pvDecoder_AmrWb( + mode, mInputSampleBuffer, + outPtr, + &numSamplesOutput, + mDecoderBuf, frameType, mDecoderCookie); + + CHECK_EQ((int)numSamplesOutput, (int)kNumSamplesPerFrameWB); + + for (int i = 0; i < kNumSamplesPerFrameWB; ++i) { + /* Delete the 2 LSBs (14-bit output) */ + outPtr[i] &= 0xfffC; + } + } + + numBytesRead = frameSize; + } + + inHeader->nOffset += numBytesRead; + inHeader->nFilledLen -= numBytesRead; + + outHeader->nFlags = 0; + outHeader->nOffset = 0; + + if (mMode == MODE_NARROW) { + outHeader->nFilledLen = kNumSamplesPerFrameNB * sizeof(int16_t); + + outHeader->nTimeStamp = + mAnchorTimeUs + + (mNumSamplesOutput * 1000000ll) / kSampleRateNB; + + mNumSamplesOutput += kNumSamplesPerFrameNB; + } else { + outHeader->nFilledLen = kNumSamplesPerFrameWB * sizeof(int16_t); + + outHeader->nTimeStamp = + mAnchorTimeUs + + (mNumSamplesOutput * 1000000ll) / kSampleRateWB; + + mNumSamplesOutput += kNumSamplesPerFrameWB; + } + + if (inHeader->nFilledLen == 0) { + inInfo->mOwnedByUs = false; + inQueue.erase(inQueue.begin()); + inInfo = NULL; + notifyEmptyBufferDone(inHeader); + inHeader = NULL; + } + + outInfo->mOwnedByUs = false; + outQueue.erase(outQueue.begin()); + outInfo = NULL; + notifyFillBufferDone(outHeader); + outHeader = NULL; + + ++mInputBufferCount; + } +} +",1,"void SoftAMR::onQueueFilled(OMX_U32 /* portIndex */) { + List &inQueue = getPortQueue(0); + List &outQueue = getPortQueue(1); + + if (mSignalledError || mOutputPortSettingsChange != NONE) { + return; + } + + while (!inQueue.empty() && !outQueue.empty()) { + + BufferInfo *inInfo = *inQueue.begin(); + OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; + + BufferInfo *outInfo = *outQueue.begin(); + OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; + + if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) { + inQueue.erase(inQueue.begin()); + inInfo->mOwnedByUs = false; + notifyEmptyBufferDone(inHeader); + + outHeader->nFilledLen = 0; + outHeader->nFlags = OMX_BUFFERFLAG_EOS; + + outQueue.erase(outQueue.begin()); + outInfo->mOwnedByUs = false; + notifyFillBufferDone(outHeader); + + return; + } + + if (inHeader->nFilledLen == 0) { + inInfo->mOwnedByUs = false; + inQueue.erase(inQueue.begin()); + notifyEmptyBufferDone(inHeader); + continue; + } + + if (inHeader->nOffset == 0) { + mAnchorTimeUs = inHeader->nTimeStamp; + mNumSamplesOutput = 0; + } + + const uint8_t *inputPtr = inHeader->pBuffer + inHeader->nOffset; + int32_t numBytesRead; + + if (mMode == MODE_NARROW) { + if (outHeader->nAllocLen < kNumSamplesPerFrameNB * sizeof(int16_t)) { + ALOGE(""b/27662364: NB expected output buffer %zu bytes vs %u"", + kNumSamplesPerFrameNB * sizeof(int16_t), outHeader->nAllocLen); + android_errorWriteLog(0x534e4554, ""27662364""); + notify(OMX_EventError, OMX_ErrorOverflow, 0, NULL); + mSignalledError = true; + return; + } + + int16 mode = ((inputPtr[0] >> 3) & 0x0f); + size_t frameSize = WmfDecBytesPerFrame[mode] + 1; + + if (inHeader->nFilledLen < frameSize) { + ALOGE(""b/27662364: expected %zu bytes vs %u"", frameSize, inHeader->nFilledLen); + notify(OMX_EventError, OMX_ErrorStreamCorrupt, 0, NULL); + mSignalledError = true; + return; + } + + numBytesRead = + AMRDecode(mState, + (Frame_Type_3GPP)((inputPtr[0] >> 3) & 0x0f), + (UWord8 *)&inputPtr[1], + reinterpret_cast(outHeader->pBuffer), + MIME_IETF); + + if (numBytesRead == -1) { + ALOGE(""PV AMR decoder AMRDecode() call failed""); + + notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); + mSignalledError = true; + + return; + } + + ++numBytesRead; // Include the frame type header byte. + + if (static_cast(numBytesRead) > inHeader->nFilledLen) { + + notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); + mSignalledError = true; + + return; + } + } else { + if (outHeader->nAllocLen < kNumSamplesPerFrameWB * sizeof(int16_t)) { + ALOGE(""b/27662364: WB expected output buffer %zu bytes vs %u"", + kNumSamplesPerFrameWB * sizeof(int16_t), outHeader->nAllocLen); + android_errorWriteLog(0x534e4554, ""27662364""); + notify(OMX_EventError, OMX_ErrorOverflow, 0, NULL); + mSignalledError = true; + return; + } + + int16 mode = ((inputPtr[0] >> 3) & 0x0f); + + if (mode >= 10 && mode <= 13) { + ALOGE(""encountered illegal frame type %d in AMR WB content."", + mode); + + notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); + mSignalledError = true; + + return; + } + + size_t frameSize = getFrameSize(mode); + if (inHeader->nFilledLen < frameSize) { + ALOGE(""b/27662364: expected %zu bytes vs %u"", frameSize, inHeader->nFilledLen); + notify(OMX_EventError, OMX_ErrorStreamCorrupt, 0, NULL); + mSignalledError = true; + return; + } + + int16_t *outPtr = (int16_t *)outHeader->pBuffer; + + if (mode >= 9) { + memset(outPtr, 0, kNumSamplesPerFrameWB * sizeof(int16_t)); + } else if (mode < 9) { + int16 frameType; + RX_State_wb rx_state; + mime_unsorting( + const_cast(&inputPtr[1]), + mInputSampleBuffer, + &frameType, &mode, 1, &rx_state); + + int16_t numSamplesOutput; + pvDecoder_AmrWb( + mode, mInputSampleBuffer, + outPtr, + &numSamplesOutput, + mDecoderBuf, frameType, mDecoderCookie); + + CHECK_EQ((int)numSamplesOutput, (int)kNumSamplesPerFrameWB); + + for (int i = 0; i < kNumSamplesPerFrameWB; ++i) { + /* Delete the 2 LSBs (14-bit output) */ + outPtr[i] &= 0xfffC; + } + } + + numBytesRead = frameSize; + } + + inHeader->nOffset += numBytesRead; + inHeader->nFilledLen -= numBytesRead; + + outHeader->nFlags = 0; + outHeader->nOffset = 0; + + if (mMode == MODE_NARROW) { + outHeader->nFilledLen = kNumSamplesPerFrameNB * sizeof(int16_t); + + outHeader->nTimeStamp = + mAnchorTimeUs + + (mNumSamplesOutput * 1000000ll) / kSampleRateNB; + + mNumSamplesOutput += kNumSamplesPerFrameNB; + } else { + outHeader->nFilledLen = kNumSamplesPerFrameWB * sizeof(int16_t); + + outHeader->nTimeStamp = + mAnchorTimeUs + + (mNumSamplesOutput * 1000000ll) / kSampleRateWB; + + mNumSamplesOutput += kNumSamplesPerFrameWB; + } + + if (inHeader->nFilledLen == 0) { + inInfo->mOwnedByUs = false; + inQueue.erase(inQueue.begin()); + inInfo = NULL; + notifyEmptyBufferDone(inHeader); + inHeader = NULL; + } + + outInfo->mOwnedByUs = false; + outQueue.erase(outQueue.begin()); + outInfo = NULL; + notifyFillBufferDone(outHeader); + outHeader = NULL; + + ++mInputBufferCount; + } +} +","@@ -286,13 +286,6 @@ + + BufferInfo *inInfo = *inQueue.begin(); + OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader; + +- if (inHeader->nFilledLen == 0) { +- inInfo->mOwnedByUs = false; +- inQueue.erase(inQueue.begin()); +- notifyEmptyBufferDone(inHeader); +- continue; +- } +- + BufferInfo *outInfo = *outQueue.begin(); + OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader; + +@@ -310,6 +303,13 @@ + + return; + } + ++ if (inHeader->nFilledLen == 0) { ++ inInfo->mOwnedByUs = false; ++ inQueue.erase(inQueue.begin()); ++ notifyEmptyBufferDone(inHeader); ++ continue; ++ } ++ + if (inHeader->nOffset == 0) { + mAnchorTimeUs = inHeader->nTimeStamp; + mNumSamplesOutput = 0; +",1607,1938,2048 +17419,"FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length) +{ + FLAC__uint32 x; + unsigned bits, used_bits = 0; + + FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)); + + decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO; + decoder->private_->stream_info.is_last = is_last; + decoder->private_->stream_info.length = length; + + bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->stream_info.data.stream_info.min_blocksize = x; + used_bits += bits; + + bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->stream_info.data.stream_info.max_blocksize = x; + used_bits += bits; + + bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->stream_info.data.stream_info.min_framesize = x; + used_bits += bits; + + bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->stream_info.data.stream_info.max_framesize = x; + used_bits += bits; + + bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->stream_info.data.stream_info.sample_rate = x; + used_bits += bits; + + bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->stream_info.data.stream_info.channels = x+1; + used_bits += bits; + + bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1; + used_bits += bits; + + bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; + if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &decoder->private_->stream_info.data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN)) + return false; /* read_callback_ sets the state for us */ + used_bits += bits; + + if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16)) + return false; /* read_callback_ sets the state for us */ + used_bits += 16*8; + + /* skip the rest of the block */ + FLAC__ASSERT(used_bits % 8 == 0); + length -= (used_bits / 8); + if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length)) + return false; /* read_callback_ sets the state for us */ + + return true; +} +",0,"FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length) +{ + FLAC__uint32 x; + unsigned bits, used_bits = 0; + + FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)); + + decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO; + decoder->private_->stream_info.is_last = is_last; + decoder->private_->stream_info.length = length; + + bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->stream_info.data.stream_info.min_blocksize = x; + used_bits += bits; + + bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->stream_info.data.stream_info.max_blocksize = x; + used_bits += bits; + + bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->stream_info.data.stream_info.min_framesize = x; + used_bits += bits; + + bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->stream_info.data.stream_info.max_framesize = x; + used_bits += bits; + + bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->stream_info.data.stream_info.sample_rate = x; + used_bits += bits; + + bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->stream_info.data.stream_info.channels = x+1; + used_bits += bits; + + bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; + if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN)) + return false; /* read_callback_ sets the state for us */ + decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1; + used_bits += bits; + + bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; + if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &decoder->private_->stream_info.data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN)) + return false; /* read_callback_ sets the state for us */ + used_bits += bits; + + if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16)) + return false; /* read_callback_ sets the state for us */ + used_bits += 16*8; + + /* skip the rest of the block */ + FLAC__ASSERT(used_bits % 8 == 0); + length -= (used_bits / 8); + if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length)) + return false; /* read_callback_ sets the state for us */ + + return true; +} +","@@ -1739,6 +1739,7 @@ + + if (obj->num_comments > 0) { + if (0 == (obj->comments = safe_malloc_mul_2op_p(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) { + decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR; ++ obj->num_comments = 0; + return false; + } + for (i = 0; i < obj->num_comments; i++) { +",875,1206,2048 +1195,"fbCombineConjointGeneralC (CARD32 *dest, CARD32 *src, CARD32 *mask, int width, CARD8 combine) +{ + int i; + + for (i = 0; i < width; ++i) { + CARD32 s, d; + CARD32 m,n,o,p; + CARD32 Fa, Fb; + CARD16 t, u, v; + CARD32 sa; + CARD8 da; + + s = READ(src + i); + m = READ(mask + i); + d = READ(dest + i); + da = d >> 24; + + fbCombineMaskC (&s, &m); + + sa = m; + + switch (combine & CombineA) { + default: + Fa = 0; + break; + case CombineAOut: + m = fbCombineConjointOutPart ((CARD8) (sa >> 0), da); + n = fbCombineConjointOutPart ((CARD8) (sa >> 8), da) << 8; + o = fbCombineConjointOutPart ((CARD8) (sa >> 16), da) << 16; + p = fbCombineConjointOutPart ((CARD8) (sa >> 24), da) << 24; + Fa = m|n|o|p; + break; + case CombineAIn: + m = fbCombineConjointInPart ((CARD8) (sa >> 0), da); + n = fbCombineConjointInPart ((CARD8) (sa >> 8), da) << 8; + o = fbCombineConjointInPart ((CARD8) (sa >> 16), da) << 16; + p = fbCombineConjointInPart ((CARD8) (sa >> 24), da) << 24; + Fa = m|n|o|p; + break; + case CombineA: + Fa = 0xffffffff; + break; + } + + switch (combine & CombineB) { + default: + Fb = 0; + break; + case CombineBOut: + m = fbCombineConjointOutPart (da, (CARD8) (sa >> 0)); + n = fbCombineConjointOutPart (da, (CARD8) (sa >> 8)) << 8; + o = fbCombineConjointOutPart (da, (CARD8) (sa >> 16)) << 16; + p = fbCombineConjointOutPart (da, (CARD8) (sa >> 24)) << 24; + Fb = m|n|o|p; + break; + case CombineBIn: + m = fbCombineConjointInPart (da, (CARD8) (sa >> 0)); + n = fbCombineConjointInPart (da, (CARD8) (sa >> 8)) << 8; + o = fbCombineConjointInPart (da, (CARD8) (sa >> 16)) << 16; + p = fbCombineConjointInPart (da, (CARD8) (sa >> 24)) << 24; + Fb = m|n|o|p; + break; + case CombineB: + Fb = 0xffffffff; + break; + } + m = FbGen (s,d,0,FbGet8(Fa,0),FbGet8(Fb,0),t, u, v); + n = FbGen (s,d,8,FbGet8(Fa,8),FbGet8(Fb,8),t, u, v); + o = FbGen (s,d,16,FbGet8(Fa,16),FbGet8(Fb,16),t, u, v); + p = FbGen (s,d,24,FbGet8(Fa,24),FbGet8(Fb,24),t, u, v); + s = m|n|o|p; + WRITE(dest + i, s); + } +} +",0,"fbCombineConjointGeneralC (CARD32 *dest, CARD32 *src, CARD32 *mask, int width, CARD8 combine) +{ + int i; + + for (i = 0; i < width; ++i) { + CARD32 s, d; + CARD32 m,n,o,p; + CARD32 Fa, Fb; + CARD16 t, u, v; + CARD32 sa; + CARD8 da; + + s = READ(src + i); + m = READ(mask + i); + d = READ(dest + i); + da = d >> 24; + + fbCombineMaskC (&s, &m); + + sa = m; + + switch (combine & CombineA) { + default: + Fa = 0; + break; + case CombineAOut: + m = fbCombineConjointOutPart ((CARD8) (sa >> 0), da); + n = fbCombineConjointOutPart ((CARD8) (sa >> 8), da) << 8; + o = fbCombineConjointOutPart ((CARD8) (sa >> 16), da) << 16; + p = fbCombineConjointOutPart ((CARD8) (sa >> 24), da) << 24; + Fa = m|n|o|p; + break; + case CombineAIn: + m = fbCombineConjointInPart ((CARD8) (sa >> 0), da); + n = fbCombineConjointInPart ((CARD8) (sa >> 8), da) << 8; + o = fbCombineConjointInPart ((CARD8) (sa >> 16), da) << 16; + p = fbCombineConjointInPart ((CARD8) (sa >> 24), da) << 24; + Fa = m|n|o|p; + break; + case CombineA: + Fa = 0xffffffff; + break; + } + + switch (combine & CombineB) { + default: + Fb = 0; + break; + case CombineBOut: + m = fbCombineConjointOutPart (da, (CARD8) (sa >> 0)); + n = fbCombineConjointOutPart (da, (CARD8) (sa >> 8)) << 8; + o = fbCombineConjointOutPart (da, (CARD8) (sa >> 16)) << 16; + p = fbCombineConjointOutPart (da, (CARD8) (sa >> 24)) << 24; + Fb = m|n|o|p; + break; + case CombineBIn: + m = fbCombineConjointInPart (da, (CARD8) (sa >> 0)); + n = fbCombineConjointInPart (da, (CARD8) (sa >> 8)) << 8; + o = fbCombineConjointInPart (da, (CARD8) (sa >> 16)) << 16; + p = fbCombineConjointInPart (da, (CARD8) (sa >> 24)) << 24; + Fb = m|n|o|p; + break; + case CombineB: + Fb = 0xffffffff; + break; + } + m = FbGen (s,d,0,FbGet8(Fa,0),FbGet8(Fb,0),t, u, v); + n = FbGen (s,d,8,FbGet8(Fa,8),FbGet8(Fb,8),t, u, v); + o = FbGen (s,d,16,FbGet8(Fa,16),FbGet8(Fb,16),t, u, v); + p = FbGen (s,d,24,FbGet8(Fa,24),FbGet8(Fb,24),t, u, v); + s = m|n|o|p; + WRITE(dest + i, s); + } +} +","@@ -4308,107 +4308,9 @@ fbCompositeGeneral (CARD8 op, + CARD16 width, + CARD16 height) + { +- RegionRec region; +- int n; +- BoxPtr pbox; +- Bool srcRepeat = FALSE; +- Bool maskRepeat = FALSE; +- int w, h; +- CARD32 _scanline_buffer[SCANLINE_BUFFER_LENGTH*3]; +- CARD32 *scanline_buffer = _scanline_buffer; +- FbComposeData compose_data; +- +- if (pSrc->pDrawable) +- srcRepeat = pSrc->repeatType == RepeatNormal && !pSrc->transform +- && (pSrc->pDrawable->width != 1 || pSrc->pDrawable->height != 1); +- +- if (pMask && pMask->pDrawable) +- maskRepeat = pMask->repeatType == RepeatNormal && !pMask->transform +- && (pMask->pDrawable->width != 1 || pMask->pDrawable->height != 1); +- +- if (op == PictOpOver && !pMask && !pSrc->transform && !PICT_FORMAT_A(pSrc->format) && !pSrc->alphaMap) +- op = PictOpSrc; +- +- if (!miComputeCompositeRegion (®ion, +- pSrc, +- pMask, +- pDst, +- xSrc, +- ySrc, +- xMask, +- yMask, +- xDst, +- yDst, +- width, +- height)) +- return; +- +- compose_data.op = op; +- compose_data.src = pSrc; +- compose_data.mask = pMask; +- compose_data.dest = pDst; +- if (width > SCANLINE_BUFFER_LENGTH) +- scanline_buffer = (CARD32 *) malloc(width * 3 * sizeof(CARD32)); +- +- n = REGION_NUM_RECTS (®ion); +- pbox = REGION_RECTS (®ion); +- while (n--) +- { +- h = pbox->y2 - pbox->y1; +- compose_data.ySrc = pbox->y1 - yDst + ySrc; +- compose_data.yMask = pbox->y1 - yDst + yMask; +- compose_data.yDest = pbox->y1; +- while (h) +- { +- compose_data.height = h; +- w = pbox->x2 - pbox->x1; +- compose_data.xSrc = pbox->x1 - xDst + xSrc; +- compose_data.xMask = pbox->x1 - xDst + xMask; +- compose_data.xDest = pbox->x1; +- if (maskRepeat) +- { +- compose_data.yMask = mod (compose_data.yMask, pMask->pDrawable->height); +- if (compose_data.height > pMask->pDrawable->height - compose_data.yMask) +- compose_data.height = pMask->pDrawable->height - compose_data.yMask; +- } +- if (srcRepeat) +- { +- compose_data.ySrc = mod (compose_data.ySrc, pSrc->pDrawable->height); +- if (compose_data.height > pSrc->pDrawable->height - compose_data.ySrc) +- compose_data.height = pSrc->pDrawable->height - compose_data.ySrc; +- } +- while (w) +- { +- compose_data.width = w; +- if (maskRepeat) +- { +- compose_data.xMask = mod (compose_data.xMask, pMask->pDrawable->width); +- if (compose_data.width > pMask->pDrawable->width - compose_data.xMask) +- compose_data.width = pMask->pDrawable->width - compose_data.xMask; +- } +- if (srcRepeat) +- { +- compose_data.xSrc = mod (compose_data.xSrc, pSrc->pDrawable->width); +- if (compose_data.width > pSrc->pDrawable->width - compose_data.xSrc) +- compose_data.width = pSrc->pDrawable->width - compose_data.xSrc; +- } +- fbCompositeRect(&compose_data, scanline_buffer); +- w -= compose_data.width; +- compose_data.xSrc += compose_data.width; +- compose_data.xMask += compose_data.width; +- compose_data.xDest += compose_data.width; +- } +- h -= compose_data.height; +- compose_data.ySrc += compose_data.height; +- compose_data.yMask += compose_data.height; +- compose_data.yDest += compose_data.height; +- } +- pbox++; +- } +- REGION_UNINIT (pDst->pDrawable->pScreen, ®ion); +- +- if (scanline_buffer != _scanline_buffer) +- free(scanline_buffer); ++ return fbComposite (op, pSrc, pMask, pDst, ++ xSrc, ySrc, xMask, yMask, xDst, yDst, ++ width, height); + } + + #endif",892,1223,2048 +18459,"xsltCompilePatternInternal(const xmlChar *pattern, xmlDocPtr doc, + xmlNodePtr node, xsltStylesheetPtr style, + xsltTransformContextPtr runtime, int novar) { + xsltParserContextPtr ctxt = NULL; + xsltCompMatchPtr element, first = NULL, previous = NULL; + int current, start, end, level, j; + + if (pattern == NULL) { + xsltTransformError(NULL, NULL, node, + ""xsltCompilePattern : NULL pattern\n""); + return(NULL); + } + + ctxt = xsltNewParserContext(style, runtime); + if (ctxt == NULL) + return(NULL); + ctxt->doc = doc; + ctxt->elem = node; + current = end = 0; + while (pattern[current] != 0) { + start = current; + while (IS_BLANK_CH(pattern[current])) + current++; + end = current; + level = 0; + while ((pattern[end] != 0) && ((pattern[end] != '|') || (level != 0))) { + if (pattern[end] == '[') + level++; + else if (pattern[end] == ']') + level--; + else if (pattern[end] == '\'') { + end++; + while ((pattern[end] != 0) && (pattern[end] != '\'')) + end++; + } else if (pattern[end] == '""') { + end++; + while ((pattern[end] != 0) && (pattern[end] != '""')) + end++; + } + end++; + } + if (current == end) { + xsltTransformError(NULL, NULL, node, + ""xsltCompilePattern : NULL pattern\n""); + goto error; + } + element = xsltNewCompMatch(); + if (element == NULL) { + goto error; + } + if (first == NULL) + first = element; + else if (previous != NULL) + previous->next = element; + previous = element; + + ctxt->comp = element; + ctxt->base = xmlStrndup(&pattern[start], end - start); + if (ctxt->base == NULL) + goto error; + ctxt->cur = &(ctxt->base)[current - start]; + element->pattern = ctxt->base; + element->nsList = xmlGetNsList(doc, node); + j = 0; + if (element->nsList != NULL) { + while (element->nsList[j] != NULL) + j++; + } + element->nsNr = j; + + +#ifdef WITH_XSLT_DEBUG_PATTERN + xsltGenericDebug(xsltGenericDebugContext, + ""xsltCompilePattern : parsing '%s'\n"", + element->pattern); +#endif + /* + Preset default priority to be zero. + This may be changed by xsltCompileLocationPathPattern. + */ + element->priority = 0; + xsltCompileLocationPathPattern(ctxt, novar); + if (ctxt->error) { + xsltTransformError(NULL, style, node, + ""xsltCompilePattern : failed to compile '%s'\n"", + element->pattern); + if (style != NULL) style->errors++; + goto error; + } + + /* + * Reverse for faster interpretation. + */ + xsltReverseCompMatch(ctxt, element); + + /* + * Set-up the priority + */ + if (element->priority == 0) { /* if not yet determined */ + if (((element->steps[0].op == XSLT_OP_ELEM) || + (element->steps[0].op == XSLT_OP_ATTR) || + (element->steps[0].op == XSLT_OP_PI)) && + (element->steps[0].value != NULL) && + (element->steps[1].op == XSLT_OP_END)) { + ; /* previously preset */ + } else if ((element->steps[0].op == XSLT_OP_ATTR) && + (element->steps[0].value2 != NULL) && + (element->steps[1].op == XSLT_OP_END)) { + element->priority = -0.25; + } else if ((element->steps[0].op == XSLT_OP_NS) && + (element->steps[0].value != NULL) && + (element->steps[1].op == XSLT_OP_END)) { + element->priority = -0.25; + } else if ((element->steps[0].op == XSLT_OP_ATTR) && + (element->steps[0].value == NULL) && + (element->steps[0].value2 == NULL) && + (element->steps[1].op == XSLT_OP_END)) { + element->priority = -0.5; + } else if (((element->steps[0].op == XSLT_OP_PI) || + (element->steps[0].op == XSLT_OP_TEXT) || + (element->steps[0].op == XSLT_OP_ALL) || + (element->steps[0].op == XSLT_OP_NODE) || + (element->steps[0].op == XSLT_OP_COMMENT)) && + (element->steps[1].op == XSLT_OP_END)) { + element->priority = -0.5; + } else { + element->priority = 0.5; + } + } +#ifdef WITH_XSLT_DEBUG_PATTERN + xsltGenericDebug(xsltGenericDebugContext, + ""xsltCompilePattern : parsed %s, default priority %f\n"", + element->pattern, element->priority); +#endif + if (pattern[end] == '|') + end++; + current = end; + } + if (end == 0) { + xsltTransformError(NULL, style, node, + ""xsltCompilePattern : NULL pattern\n""); + if (style != NULL) style->errors++; + goto error; + } + + xsltFreeParserContext(ctxt); + return(first); + +error: + if (ctxt != NULL) + xsltFreeParserContext(ctxt); + if (first != NULL) + xsltFreeCompMatchList(first); + return(NULL); +} +",1,"xsltCompilePatternInternal(const xmlChar *pattern, xmlDocPtr doc, + xmlNodePtr node, xsltStylesheetPtr style, + xsltTransformContextPtr runtime, int novar) { + xsltParserContextPtr ctxt = NULL; + xsltCompMatchPtr element, first = NULL, previous = NULL; + int current, start, end, level, j; + + if (pattern == NULL) { + xsltTransformError(NULL, NULL, node, + ""xsltCompilePattern : NULL pattern\n""); + return(NULL); + } + + ctxt = xsltNewParserContext(style, runtime); + if (ctxt == NULL) + return(NULL); + ctxt->doc = doc; + ctxt->elem = node; + current = end = 0; + while (pattern[current] != 0) { + start = current; + while (IS_BLANK_CH(pattern[current])) + current++; + end = current; + level = 0; + while ((pattern[end] != 0) && ((pattern[end] != '|') || (level != 0))) { + if (pattern[end] == '[') + level++; + else if (pattern[end] == ']') + level--; + else if (pattern[end] == '\'') { + end++; + while ((pattern[end] != 0) && (pattern[end] != '\'')) + end++; + } else if (pattern[end] == '""') { + end++; + while ((pattern[end] != 0) && (pattern[end] != '""')) + end++; + } + if (pattern[end] == 0) + break; + end++; + } + if (current == end) { + xsltTransformError(NULL, NULL, node, + ""xsltCompilePattern : NULL pattern\n""); + goto error; + } + element = xsltNewCompMatch(); + if (element == NULL) { + goto error; + } + if (first == NULL) + first = element; + else if (previous != NULL) + previous->next = element; + previous = element; + + ctxt->comp = element; + ctxt->base = xmlStrndup(&pattern[start], end - start); + if (ctxt->base == NULL) + goto error; + ctxt->cur = &(ctxt->base)[current - start]; + element->pattern = ctxt->base; + element->nsList = xmlGetNsList(doc, node); + j = 0; + if (element->nsList != NULL) { + while (element->nsList[j] != NULL) + j++; + } + element->nsNr = j; + + +#ifdef WITH_XSLT_DEBUG_PATTERN + xsltGenericDebug(xsltGenericDebugContext, + ""xsltCompilePattern : parsing '%s'\n"", + element->pattern); +#endif + /* + Preset default priority to be zero. + This may be changed by xsltCompileLocationPathPattern. + */ + element->priority = 0; + xsltCompileLocationPathPattern(ctxt, novar); + if (ctxt->error) { + xsltTransformError(NULL, style, node, + ""xsltCompilePattern : failed to compile '%s'\n"", + element->pattern); + if (style != NULL) style->errors++; + goto error; + } + + /* + * Reverse for faster interpretation. + */ + xsltReverseCompMatch(ctxt, element); + + /* + * Set-up the priority + */ + if (element->priority == 0) { /* if not yet determined */ + if (((element->steps[0].op == XSLT_OP_ELEM) || + (element->steps[0].op == XSLT_OP_ATTR) || + (element->steps[0].op == XSLT_OP_PI)) && + (element->steps[0].value != NULL) && + (element->steps[1].op == XSLT_OP_END)) { + ; /* previously preset */ + } else if ((element->steps[0].op == XSLT_OP_ATTR) && + (element->steps[0].value2 != NULL) && + (element->steps[1].op == XSLT_OP_END)) { + element->priority = -0.25; + } else if ((element->steps[0].op == XSLT_OP_NS) && + (element->steps[0].value != NULL) && + (element->steps[1].op == XSLT_OP_END)) { + element->priority = -0.25; + } else if ((element->steps[0].op == XSLT_OP_ATTR) && + (element->steps[0].value == NULL) && + (element->steps[0].value2 == NULL) && + (element->steps[1].op == XSLT_OP_END)) { + element->priority = -0.5; + } else if (((element->steps[0].op == XSLT_OP_PI) || + (element->steps[0].op == XSLT_OP_TEXT) || + (element->steps[0].op == XSLT_OP_ALL) || + (element->steps[0].op == XSLT_OP_NODE) || + (element->steps[0].op == XSLT_OP_COMMENT)) && + (element->steps[1].op == XSLT_OP_END)) { + element->priority = -0.5; + } else { + element->priority = 0.5; + } + } +#ifdef WITH_XSLT_DEBUG_PATTERN + xsltGenericDebug(xsltGenericDebugContext, + ""xsltCompilePattern : parsed %s, default priority %f\n"", + element->pattern, element->priority); +#endif + if (pattern[end] == '|') + end++; + current = end; + } + if (end == 0) { + xsltTransformError(NULL, style, node, + ""xsltCompilePattern : NULL pattern\n""); + if (style != NULL) style->errors++; + goto error; + } + + xsltFreeParserContext(ctxt); + return(first); + +error: + if (ctxt != NULL) + xsltFreeParserContext(ctxt); + if (first != NULL) + xsltFreeCompMatchList(first); + return(NULL); +} +","@@ -1864,6 +1864,8 @@ xsltCompilePatternInternal(const xmlChar *pattern, xmlDocPtr doc, + while ((pattern[end] != 0) && (pattern[end] != '""')) + end++; + } ++ if (pattern[end] == 0) ++ break; + end++; + } + if (current == end) {",1286,1617,2048 +17346,"void NuPlayer::GenericSource::onMessageReceived(const sp &msg) { + switch (msg->what()) { + case kWhatPrepareAsync: + { + onPrepareAsync(); + break; + } + case kWhatFetchSubtitleData: + { + fetchTextData(kWhatSendSubtitleData, MEDIA_TRACK_TYPE_SUBTITLE, + mFetchSubtitleDataGeneration, mSubtitleTrack.mPackets, msg); + break; + } + + case kWhatFetchTimedTextData: + { + fetchTextData(kWhatSendTimedTextData, MEDIA_TRACK_TYPE_TIMEDTEXT, + mFetchTimedTextDataGeneration, mTimedTextTrack.mPackets, msg); + break; + } + + case kWhatSendSubtitleData: + { + sendTextData(kWhatSubtitleData, MEDIA_TRACK_TYPE_SUBTITLE, + mFetchSubtitleDataGeneration, mSubtitleTrack.mPackets, msg); + break; + } + + case kWhatSendTimedTextData: + { + sendTextData(kWhatTimedTextData, MEDIA_TRACK_TYPE_TIMEDTEXT, + mFetchTimedTextDataGeneration, mTimedTextTrack.mPackets, msg); + break; + } + + case kWhatChangeAVSource: + { + int32_t trackIndex; + CHECK(msg->findInt32(""trackIndex"", &trackIndex)); + const sp source = mSources.itemAt(trackIndex); + + Track* track; + const char *mime; + media_track_type trackType, counterpartType; + sp meta = source->getFormat(); + meta->findCString(kKeyMIMEType, &mime); + if (!strncasecmp(mime, ""audio/"", 6)) { + track = &mAudioTrack; + trackType = MEDIA_TRACK_TYPE_AUDIO; + counterpartType = MEDIA_TRACK_TYPE_VIDEO;; + } else { + CHECK(!strncasecmp(mime, ""video/"", 6)); + track = &mVideoTrack; + trackType = MEDIA_TRACK_TYPE_VIDEO; + counterpartType = MEDIA_TRACK_TYPE_AUDIO;; + } + + + if (track->mSource != NULL) { + track->mSource->stop(); + } + track->mSource = source; + track->mSource->start(); + track->mIndex = trackIndex; + + int64_t timeUs, actualTimeUs; + const bool formatChange = true; + if (trackType == MEDIA_TRACK_TYPE_AUDIO) { + timeUs = mAudioLastDequeueTimeUs; + } else { + timeUs = mVideoLastDequeueTimeUs; + } + readBuffer(trackType, timeUs, &actualTimeUs, formatChange); + readBuffer(counterpartType, -1, NULL, formatChange); + ALOGV(""timeUs %lld actualTimeUs %lld"", (long long)timeUs, (long long)actualTimeUs); + + break; + } + + case kWhatStart: + case kWhatResume: + { + restartPollBuffering(); + break; + } + + case kWhatPollBuffering: + { + int32_t generation; + CHECK(msg->findInt32(""generation"", &generation)); + if (generation == mPollBufferingGeneration) { + onPollBuffering(); + } + break; + } + + case kWhatGetFormat: + { + onGetFormatMeta(msg); + break; + } + + case kWhatGetSelectedTrack: + { + onGetSelectedTrack(msg); + break; + } + + case kWhatSelectTrack: + { + onSelectTrack(msg); + break; + } + + case kWhatSeek: + { + onSeek(msg); + break; + } + + case kWhatReadBuffer: + { + onReadBuffer(msg); + break; + } + + case kWhatSecureDecodersInstantiated: + { + int32_t err; + CHECK(msg->findInt32(""err"", &err)); + onSecureDecodersInstantiated(err); + break; + } + + case kWhatStopWidevine: + { + mStopRead = true; + if (mVideoTrack.mSource != NULL) { + mVideoTrack.mPackets->clear(); + } + sp response = new AMessage; + sp replyID; + CHECK(msg->senderAwaitsResponse(&replyID)); + response->postReply(replyID); + break; + } + default: + Source::onMessageReceived(msg); + break; + } +} +",0,"void NuPlayer::GenericSource::onMessageReceived(const sp &msg) { + switch (msg->what()) { + case kWhatPrepareAsync: + { + onPrepareAsync(); + break; + } + case kWhatFetchSubtitleData: + { + fetchTextData(kWhatSendSubtitleData, MEDIA_TRACK_TYPE_SUBTITLE, + mFetchSubtitleDataGeneration, mSubtitleTrack.mPackets, msg); + break; + } + + case kWhatFetchTimedTextData: + { + fetchTextData(kWhatSendTimedTextData, MEDIA_TRACK_TYPE_TIMEDTEXT, + mFetchTimedTextDataGeneration, mTimedTextTrack.mPackets, msg); + break; + } + + case kWhatSendSubtitleData: + { + sendTextData(kWhatSubtitleData, MEDIA_TRACK_TYPE_SUBTITLE, + mFetchSubtitleDataGeneration, mSubtitleTrack.mPackets, msg); + break; + } + + case kWhatSendTimedTextData: + { + sendTextData(kWhatTimedTextData, MEDIA_TRACK_TYPE_TIMEDTEXT, + mFetchTimedTextDataGeneration, mTimedTextTrack.mPackets, msg); + break; + } + + case kWhatChangeAVSource: + { + int32_t trackIndex; + CHECK(msg->findInt32(""trackIndex"", &trackIndex)); + const sp source = mSources.itemAt(trackIndex); + + Track* track; + const char *mime; + media_track_type trackType, counterpartType; + sp meta = source->getFormat(); + meta->findCString(kKeyMIMEType, &mime); + if (!strncasecmp(mime, ""audio/"", 6)) { + track = &mAudioTrack; + trackType = MEDIA_TRACK_TYPE_AUDIO; + counterpartType = MEDIA_TRACK_TYPE_VIDEO;; + } else { + CHECK(!strncasecmp(mime, ""video/"", 6)); + track = &mVideoTrack; + trackType = MEDIA_TRACK_TYPE_VIDEO; + counterpartType = MEDIA_TRACK_TYPE_AUDIO;; + } + + + if (track->mSource != NULL) { + track->mSource->stop(); + } + track->mSource = source; + track->mSource->start(); + track->mIndex = trackIndex; + + int64_t timeUs, actualTimeUs; + const bool formatChange = true; + if (trackType == MEDIA_TRACK_TYPE_AUDIO) { + timeUs = mAudioLastDequeueTimeUs; + } else { + timeUs = mVideoLastDequeueTimeUs; + } + readBuffer(trackType, timeUs, &actualTimeUs, formatChange); + readBuffer(counterpartType, -1, NULL, formatChange); + ALOGV(""timeUs %lld actualTimeUs %lld"", (long long)timeUs, (long long)actualTimeUs); + + break; + } + + case kWhatStart: + case kWhatResume: + { + restartPollBuffering(); + break; + } + + case kWhatPollBuffering: + { + int32_t generation; + CHECK(msg->findInt32(""generation"", &generation)); + if (generation == mPollBufferingGeneration) { + onPollBuffering(); + } + break; + } + + case kWhatGetFormat: + { + onGetFormatMeta(msg); + break; + } + + case kWhatGetSelectedTrack: + { + onGetSelectedTrack(msg); + break; + } + + case kWhatSelectTrack: + { + onSelectTrack(msg); + break; + } + + case kWhatSeek: + { + onSeek(msg); + break; + } + + case kWhatReadBuffer: + { + onReadBuffer(msg); + break; + } + + case kWhatSecureDecodersInstantiated: + { + int32_t err; + CHECK(msg->findInt32(""err"", &err)); + onSecureDecodersInstantiated(err); + break; + } + + case kWhatStopWidevine: + { + mStopRead = true; + if (mVideoTrack.mSource != NULL) { + mVideoTrack.mPackets->clear(); + } + sp response = new AMessage; + sp replyID; + CHECK(msg->senderAwaitsResponse(&replyID)); + response->postReply(replyID); + break; + } + default: + Source::onMessageReceived(msg); + break; + } +} +","@@ -211,6 +211,9 @@ + + + for (size_t i = 0; i < numtracks; ++i) { + sp track = extractor->getTrack(i); ++ if (track == NULL) { ++ continue; ++ } + + sp meta = extractor->getTrackMetaData(i); + +@@ -253,22 +256,25 @@ + + } + } + +- if (track != NULL) { +- mSources.push(track); +- int64_t durationUs; +- if (meta->findInt64(kKeyDuration, &durationUs)) { +- if (durationUs > mDurationUs) { +- mDurationUs = durationUs; +- } +- } +- +- int32_t bitrate; +- if (totalBitrate >= 0 && meta->findInt32(kKeyBitRate, &bitrate)) { +- totalBitrate += bitrate; +- } else { +- totalBitrate = -1; ++ mSources.push(track); ++ int64_t durationUs; ++ if (meta->findInt64(kKeyDuration, &durationUs)) { ++ if (durationUs > mDurationUs) { ++ mDurationUs = durationUs; + } + } ++ ++ int32_t bitrate; ++ if (totalBitrate >= 0 && meta->findInt32(kKeyBitRate, &bitrate)) { ++ totalBitrate += bitrate; ++ } else { ++ totalBitrate = -1; ++ } ++ } ++ ++ if (mSources.size() == 0) { ++ ALOGE(""b/23705695""); ++ return UNKNOWN_ERROR; + } + + mBitrate = totalBitrate; +@@ -318,7 +324,7 @@ + + + status_t NuPlayer::GenericSource::setBuffers( + bool audio, Vector &buffers) { +- if (mIsSecure && !audio) { ++ if (mIsWidevine && !audio && mVideoTrack.mSource != NULL) { + return mVideoTrack.mSource->setBuffers(buffers); + } + return INVALID_OPERATION; +",859,1190,2048 +13210,"void ChromotingInstance::HandleConnect(const base::DictionaryValue& data) { + std::string local_jid; + std::string host_jid; + std::string host_public_key; + std::string auth_methods_str; + std::string authentication_tag; + std::vector auth_methods; + if (!data.GetString(""hostJid"", &host_jid) || + !data.GetString(""hostPublicKey"", &host_public_key) || + !data.GetString(""localJid"", &local_jid) || + !data.GetString(""authenticationMethods"", &auth_methods_str) || + !ParseAuthMethods(auth_methods_str, &auth_methods) || + !data.GetString(""authenticationTag"", &authentication_tag)) { + LOG(ERROR) << ""Invalid connect() data.""; + return; + } + + std::string client_pairing_id; + data.GetString(""clientPairingId"", &client_pairing_id); + std::string client_paired_secret; + data.GetString(""clientPairedSecret"", &client_paired_secret); + + protocol::FetchSecretCallback fetch_secret_callback; + if (use_async_pin_dialog_) { + fetch_secret_callback = base::Bind( + &ChromotingInstance::FetchSecretFromDialog, weak_factory_.GetWeakPtr()); + } else { + std::string shared_secret; + if (!data.GetString(""sharedSecret"", &shared_secret)) { + LOG(ERROR) << ""sharedSecret not specified in connect().""; + return; + } + fetch_secret_callback = + base::Bind(&ChromotingInstance::FetchSecretFromString, shared_secret); + } + + std::string capabilities; + if (data.HasKey(""capabilities"")) { + if (!data.GetString(""capabilities"", &capabilities)) { + LOG(ERROR) << ""Invalid connect() data.""; + return; + } + } + + VLOG(0) << ""Connecting to "" << host_jid + << "". Local jid: "" << local_jid << "".""; + +#if defined(OS_NACL) + std::string key_filter; + if (!data.GetString(""keyFilter"", &key_filter)) { + NOTREACHED(); + normalizing_input_filter_.reset(new protocol::InputFilter(&key_mapper_)); + } else if (key_filter == ""mac"") { + normalizing_input_filter_.reset( + new NormalizingInputFilterMac(&key_mapper_)); + } else if (key_filter == ""cros"") { + normalizing_input_filter_.reset( + new NormalizingInputFilterCros(&key_mapper_)); + } else { + DCHECK(key_filter.empty()); + normalizing_input_filter_.reset(new protocol::InputFilter(&key_mapper_)); + } +#elif defined(OS_MACOSX) + normalizing_input_filter_.reset(new NormalizingInputFilterMac(&key_mapper_)); +#elif defined(OS_CHROMEOS) + normalizing_input_filter_.reset(new NormalizingInputFilterCros(&key_mapper_)); +#else + normalizing_input_filter_.reset(new protocol::InputFilter(&key_mapper_)); +#endif + input_handler_.set_input_stub(normalizing_input_filter_.get()); + + bool enable_video_decode_renderer = false; + if (data.GetBoolean(""enableVideoDecodeRenderer"", + &enable_video_decode_renderer) && + enable_video_decode_renderer) { + LogToWebapp(""Initializing 3D renderer.""); + video_renderer_.reset(new PepperVideoRenderer3D()); + if (!video_renderer_->Initialize(this, context_, this)) + video_renderer_.reset(); + } + + if (!video_renderer_) { + LogToWebapp(""Initializing 2D renderer.""); + video_renderer_.reset(new PepperVideoRenderer2D()); + if (!video_renderer_->Initialize(this, context_, this)) + video_renderer_.reset(); + } + + CHECK(video_renderer_); + + if (!plugin_view_.is_null()) + video_renderer_->OnViewChanged(plugin_view_); + + scoped_ptr audio_player(new PepperAudioPlayer(this)); + client_.reset(new ChromotingClient(&context_, this, video_renderer_.get(), + audio_player.Pass())); + + mouse_input_filter_.set_input_stub(client_->input_stub()); + if (!plugin_view_.is_null()) { + mouse_input_filter_.set_input_size(webrtc::DesktopSize( + plugin_view_.GetRect().width(), plugin_view_.GetRect().height())); + } + + signal_strategy_.reset(new DelegatingSignalStrategy( + local_jid, base::Bind(&ChromotingInstance::SendOutgoingIq, + weak_factory_.GetWeakPtr()))); + + scoped_ptr transport_factory( + new protocol::LibjingleTransportFactory( + signal_strategy_.get(), + PepperPortAllocator::Create(this).Pass(), + protocol::NetworkSettings( + protocol::NetworkSettings::NAT_TRAVERSAL_FULL))); + + scoped_ptr + token_fetcher(new TokenFetcherProxy( + base::Bind(&ChromotingInstance::FetchThirdPartyToken, + weak_factory_.GetWeakPtr()), + host_public_key)); + scoped_ptr authenticator( + new protocol::NegotiatingClientAuthenticator( + client_pairing_id, client_paired_secret, authentication_tag, + fetch_secret_callback, token_fetcher.Pass(), auth_methods)); + + client_->Start(signal_strategy_.get(), authenticator.Pass(), + transport_factory.Pass(), host_jid, capabilities); + + plugin_task_runner_->PostDelayedTask( + FROM_HERE, base::Bind(&ChromotingInstance::SendPerfStats, + weak_factory_.GetWeakPtr()), + base::TimeDelta::FromMilliseconds(kPerfStatsIntervalMs)); +} +",0,"void ChromotingInstance::HandleConnect(const base::DictionaryValue& data) { + std::string local_jid; + std::string host_jid; + std::string host_public_key; + std::string auth_methods_str; + std::string authentication_tag; + std::vector auth_methods; + if (!data.GetString(""hostJid"", &host_jid) || + !data.GetString(""hostPublicKey"", &host_public_key) || + !data.GetString(""localJid"", &local_jid) || + !data.GetString(""authenticationMethods"", &auth_methods_str) || + !ParseAuthMethods(auth_methods_str, &auth_methods) || + !data.GetString(""authenticationTag"", &authentication_tag)) { + LOG(ERROR) << ""Invalid connect() data.""; + return; + } + + std::string client_pairing_id; + data.GetString(""clientPairingId"", &client_pairing_id); + std::string client_paired_secret; + data.GetString(""clientPairedSecret"", &client_paired_secret); + + protocol::FetchSecretCallback fetch_secret_callback; + if (use_async_pin_dialog_) { + fetch_secret_callback = base::Bind( + &ChromotingInstance::FetchSecretFromDialog, weak_factory_.GetWeakPtr()); + } else { + std::string shared_secret; + if (!data.GetString(""sharedSecret"", &shared_secret)) { + LOG(ERROR) << ""sharedSecret not specified in connect().""; + return; + } + fetch_secret_callback = + base::Bind(&ChromotingInstance::FetchSecretFromString, shared_secret); + } + + std::string capabilities; + if (data.HasKey(""capabilities"")) { + if (!data.GetString(""capabilities"", &capabilities)) { + LOG(ERROR) << ""Invalid connect() data.""; + return; + } + } + + VLOG(0) << ""Connecting to "" << host_jid + << "". Local jid: "" << local_jid << "".""; + +#if defined(OS_NACL) + std::string key_filter; + if (!data.GetString(""keyFilter"", &key_filter)) { + NOTREACHED(); + normalizing_input_filter_.reset(new protocol::InputFilter(&key_mapper_)); + } else if (key_filter == ""mac"") { + normalizing_input_filter_.reset( + new NormalizingInputFilterMac(&key_mapper_)); + } else if (key_filter == ""cros"") { + normalizing_input_filter_.reset( + new NormalizingInputFilterCros(&key_mapper_)); + } else { + DCHECK(key_filter.empty()); + normalizing_input_filter_.reset(new protocol::InputFilter(&key_mapper_)); + } +#elif defined(OS_MACOSX) + normalizing_input_filter_.reset(new NormalizingInputFilterMac(&key_mapper_)); +#elif defined(OS_CHROMEOS) + normalizing_input_filter_.reset(new NormalizingInputFilterCros(&key_mapper_)); +#else + normalizing_input_filter_.reset(new protocol::InputFilter(&key_mapper_)); +#endif + input_handler_.set_input_stub(normalizing_input_filter_.get()); + + bool enable_video_decode_renderer = false; + if (data.GetBoolean(""enableVideoDecodeRenderer"", + &enable_video_decode_renderer) && + enable_video_decode_renderer) { + LogToWebapp(""Initializing 3D renderer.""); + video_renderer_.reset(new PepperVideoRenderer3D()); + if (!video_renderer_->Initialize(this, context_, this)) + video_renderer_.reset(); + } + + if (!video_renderer_) { + LogToWebapp(""Initializing 2D renderer.""); + video_renderer_.reset(new PepperVideoRenderer2D()); + if (!video_renderer_->Initialize(this, context_, this)) + video_renderer_.reset(); + } + + CHECK(video_renderer_); + + if (!plugin_view_.is_null()) + video_renderer_->OnViewChanged(plugin_view_); + + scoped_ptr audio_player(new PepperAudioPlayer(this)); + client_.reset(new ChromotingClient(&context_, this, video_renderer_.get(), + audio_player.Pass())); + + mouse_input_filter_.set_input_stub(client_->input_stub()); + if (!plugin_view_.is_null()) { + mouse_input_filter_.set_input_size(webrtc::DesktopSize( + plugin_view_.GetRect().width(), plugin_view_.GetRect().height())); + } + + signal_strategy_.reset(new DelegatingSignalStrategy( + local_jid, base::Bind(&ChromotingInstance::SendOutgoingIq, + weak_factory_.GetWeakPtr()))); + + scoped_ptr transport_factory( + new protocol::LibjingleTransportFactory( + signal_strategy_.get(), + PepperPortAllocator::Create(this).Pass(), + protocol::NetworkSettings( + protocol::NetworkSettings::NAT_TRAVERSAL_FULL))); + + scoped_ptr + token_fetcher(new TokenFetcherProxy( + base::Bind(&ChromotingInstance::FetchThirdPartyToken, + weak_factory_.GetWeakPtr()), + host_public_key)); + scoped_ptr authenticator( + new protocol::NegotiatingClientAuthenticator( + client_pairing_id, client_paired_secret, authentication_tag, + fetch_secret_callback, token_fetcher.Pass(), auth_methods)); + + client_->Start(signal_strategy_.get(), authenticator.Pass(), + transport_factory.Pass(), host_jid, capabilities); + + plugin_task_runner_->PostDelayedTask( + FROM_HERE, base::Bind(&ChromotingInstance::SendPerfStats, + weak_factory_.GetWeakPtr()), + base::TimeDelta::FromMilliseconds(kPerfStatsIntervalMs)); +} +","@@ -350,6 +350,8 @@ void ChromotingInstance::HandleMessage(const pp::Var& message) { + HandleSendMouseInputWhenUnfocused(); + } else if (method == ""delegateLargeCursors"") { + HandleDelegateLargeCursors(); ++ } else if (method == ""enableDebugRegion"") { ++ HandleEnableDebugRegion(*data); + } + } + +@@ -436,6 +438,25 @@ void ChromotingInstance::OnVideoShape(const webrtc::DesktopRegion& shape) { + PostLegacyJsonMessage(""onDesktopShape"", data.Pass()); + } + ++void ChromotingInstance::OnVideoFrameDirtyRegion( ++ const webrtc::DesktopRegion& dirty_region) { ++ scoped_ptr rects_value(new base::ListValue()); ++ for (webrtc::DesktopRegion::Iterator i(dirty_region); !i.IsAtEnd(); ++ i.Advance()) { ++ const webrtc::DesktopRect& rect = i.rect(); ++ scoped_ptr rect_value(new base::ListValue()); ++ rect_value->AppendInteger(rect.left()); ++ rect_value->AppendInteger(rect.top()); ++ rect_value->AppendInteger(rect.width()); ++ rect_value->AppendInteger(rect.height()); ++ rects_value->Append(rect_value.release()); ++ } ++ ++ scoped_ptr data(new base::DictionaryValue()); ++ data->Set(""rects"", rects_value.release()); ++ PostLegacyJsonMessage(""onDebugRegion"", data.Pass()); ++} ++ + void ChromotingInstance::OnConnectionState( + protocol::ConnectionToHost::State state, + protocol::ErrorCode error) { +@@ -947,6 +968,17 @@ void ChromotingInstance::HandleDelegateLargeCursors() { + cursor_setter_.set_delegate_stub(this); + } + ++void ChromotingInstance::HandleEnableDebugRegion( ++ const base::DictionaryValue& data) { ++ bool enable = false; ++ if (!data.GetBoolean(""enable"", &enable)) { ++ LOG(ERROR) << ""Invalid enableDebugRegion.""; ++ return; ++ } ++ ++ video_renderer_->EnableDebugDirtyRegion(enable); ++} ++ + void ChromotingInstance::Disconnect() { + DCHECK(plugin_task_runner_->BelongsToCurrentThread()); + ",1159,1490,2048 +9646,"MagickExport void *ImagesToBlob(const ImageInfo *image_info,Image *images, + size_t *length,ExceptionInfo *exception) +{ + const MagickInfo + *magick_info; + + ImageInfo + *clone_info; + + MagickBooleanType + status; + + void + *blob; + + 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(images != (Image *) NULL); + assert(images->signature == MagickCoreSignature); + assert(exception != (ExceptionInfo *) NULL); + *length=0; + blob=(unsigned char *) NULL; + clone_info=CloneImageInfo(image_info); + (void) SetImageInfo(clone_info,(unsigned int) GetImageListLength(images), + exception); + if (*clone_info->magick != '\0') + (void) CopyMagickString(images->magick,clone_info->magick,MagickPathExtent); + magick_info=GetMagickInfo(images->magick,exception); + if (magick_info == (const MagickInfo *) NULL) + { + (void) ThrowMagickException(exception,GetMagickModule(), + MissingDelegateError,""NoDecodeDelegateForThisImageFormat"",""`%s'"", + images->magick); + clone_info=DestroyImageInfo(clone_info); + return(blob); + } + if (GetMagickAdjoin(magick_info) == MagickFalse) + { + clone_info=DestroyImageInfo(clone_info); + return(ImageToBlob(image_info,images,length,exception)); + } + (void) CopyMagickString(clone_info->magick,images->magick,MagickPathExtent); + if (GetMagickBlobSupport(magick_info) != MagickFalse) + { + /* + Native blob support for this images format. + */ + clone_info->length=0; + clone_info->blob=(void *) AcquireQuantumMemory(MagickMaxBlobExtent, + sizeof(unsigned char)); + if (clone_info->blob == (void *) NULL) + (void) ThrowMagickException(exception,GetMagickModule(), + ResourceLimitError,""MemoryAllocationFailed"",""`%s'"",images->filename); + else + { + (void) CloseBlob(images); + images->blob->exempt=MagickTrue; + *images->filename='\0'; + status=WriteImages(clone_info,images,images->filename,exception); + *length=images->blob->length; + blob=DetachBlob(images->blob); + if (blob == (void *) NULL) + clone_info->blob=RelinquishMagickMemory(clone_info->blob); + else if (status == MagickFalse) + blob=RelinquishMagickMemory(blob); + else + blob=ResizeQuantumMemory(blob,*length+1,sizeof(unsigned char)); + } + } + else + { + char + filename[MagickPathExtent], + unique[MagickPathExtent]; + + int + file; + + /* + Write file to disk in blob images format. + */ + file=AcquireUniqueFileResource(unique); + if (file == -1) + { + ThrowFileException(exception,FileOpenError,""UnableToWriteBlob"", + image_info->filename); + } + else + { + clone_info->file=fdopen(file,""wb""); + if (clone_info->file != (FILE *) NULL) + { + (void) FormatLocaleString(filename,MagickPathExtent,""%s:%s"", + images->magick,unique); + status=WriteImages(clone_info,images,filename,exception); + (void) CloseBlob(images); + (void) fclose(clone_info->file); + if (status != MagickFalse) + blob=FileToBlob(unique,~0UL,length,exception); + } + (void) RelinquishUniqueFileResource(unique); + } + } + clone_info=DestroyImageInfo(clone_info); + return(blob); +} +",0,"MagickExport void *ImagesToBlob(const ImageInfo *image_info,Image *images, + size_t *length,ExceptionInfo *exception) +{ + const MagickInfo + *magick_info; + + ImageInfo + *clone_info; + + MagickBooleanType + status; + + void + *blob; + + 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(images != (Image *) NULL); + assert(images->signature == MagickCoreSignature); + assert(exception != (ExceptionInfo *) NULL); + *length=0; + blob=(unsigned char *) NULL; + clone_info=CloneImageInfo(image_info); + (void) SetImageInfo(clone_info,(unsigned int) GetImageListLength(images), + exception); + if (*clone_info->magick != '\0') + (void) CopyMagickString(images->magick,clone_info->magick,MagickPathExtent); + magick_info=GetMagickInfo(images->magick,exception); + if (magick_info == (const MagickInfo *) NULL) + { + (void) ThrowMagickException(exception,GetMagickModule(), + MissingDelegateError,""NoDecodeDelegateForThisImageFormat"",""`%s'"", + images->magick); + clone_info=DestroyImageInfo(clone_info); + return(blob); + } + if (GetMagickAdjoin(magick_info) == MagickFalse) + { + clone_info=DestroyImageInfo(clone_info); + return(ImageToBlob(image_info,images,length,exception)); + } + (void) CopyMagickString(clone_info->magick,images->magick,MagickPathExtent); + if (GetMagickBlobSupport(magick_info) != MagickFalse) + { + /* + Native blob support for this images format. + */ + clone_info->length=0; + clone_info->blob=(void *) AcquireQuantumMemory(MagickMaxBlobExtent, + sizeof(unsigned char)); + if (clone_info->blob == (void *) NULL) + (void) ThrowMagickException(exception,GetMagickModule(), + ResourceLimitError,""MemoryAllocationFailed"",""`%s'"",images->filename); + else + { + (void) CloseBlob(images); + images->blob->exempt=MagickTrue; + *images->filename='\0'; + status=WriteImages(clone_info,images,images->filename,exception); + *length=images->blob->length; + blob=DetachBlob(images->blob); + if (blob == (void *) NULL) + clone_info->blob=RelinquishMagickMemory(clone_info->blob); + else if (status == MagickFalse) + blob=RelinquishMagickMemory(blob); + else + blob=ResizeQuantumMemory(blob,*length+1,sizeof(unsigned char)); + } + } + else + { + char + filename[MagickPathExtent], + unique[MagickPathExtent]; + + int + file; + + /* + Write file to disk in blob images format. + */ + file=AcquireUniqueFileResource(unique); + if (file == -1) + { + ThrowFileException(exception,FileOpenError,""UnableToWriteBlob"", + image_info->filename); + } + else + { + clone_info->file=fdopen(file,""wb""); + if (clone_info->file != (FILE *) NULL) + { + (void) FormatLocaleString(filename,MagickPathExtent,""%s:%s"", + images->magick,unique); + status=WriteImages(clone_info,images,filename,exception); + (void) CloseBlob(images); + (void) fclose(clone_info->file); + if (status != MagickFalse) + blob=FileToBlob(unique,~0UL,length,exception); + } + (void) RelinquishUniqueFileResource(unique); + } + } + clone_info=DestroyImageInfo(clone_info); + return(blob); +} +","@@ -996,6 +996,7 @@ MagickExport void *DetachBlob(BlobInfo *blob_info) + if (blob_info->mapped != MagickFalse) + { + (void) UnmapBlob(blob_info->data,blob_info->length); ++ blob_info->data=NULL; + RelinquishMagickResource(MapResource,blob_info->length); + } + blob_info->mapped=MagickFalse;",872,1203,2048 +4328,"static void start_event_run(const char *event_name) +{ + /* Start event asynchronously on the dump dir + * (synchronous run would freeze GUI until completion) + */ + + /* https://bugzilla.redhat.com/show_bug.cgi?id=1044653 */ + correct_bz_private_goup_name(event_name); + + struct run_event_state *state = new_run_event_state(); + state->logging_callback = run_event_gtk_logging; + state->error_callback = run_event_gtk_error; + state->alert_callback = run_event_gtk_alert; + state->ask_callback = run_event_gtk_ask; + state->ask_yes_no_callback = run_event_gtk_ask_yes_no; + state->ask_yes_no_yesforever_callback = run_event_gtk_ask_yes_no_yesforever; + state->ask_yes_no_save_result_callback = run_event_gtk_ask_yes_no_save_result; + state->ask_password_callback = run_event_gtk_ask_password; + + if (prepare_commands(state, g_dump_dir_name, event_name) == 0) + { + no_cmds: + /* No commands needed?! (This is untypical) */ + free_run_event_state(state); + char *msg = xasprintf(_(""No processing for event '%s' is defined""), event_name); + append_to_textview(g_tv_event_log, msg); + free(msg); + cancel_processing(g_lbl_event_log, _(""Processing failed.""), TERMINATE_NOFLAGS); + return; + } + + struct dump_dir *dd = wizard_open_directory_for_writing(g_dump_dir_name); + dd_close(dd); + if (!dd) + { + free_run_event_state(state); + if (!g_expert_mode) + { + cancel_processing(g_lbl_event_log, _(""Processing interrupted: can't continue without writable directory.""), TERMINATE_NOFLAGS); + } + return; /* user refused to steal, or write error, etc... */ + } + + set_excluded_envvar(); + GList *env_list = export_event_config(event_name); + + if (spawn_next_command(state, g_dump_dir_name, event_name, EXECFLG_SETPGID) < 0) + { + unexport_event_config(env_list); + goto no_cmds; + } + g_event_child_pid = state->command_pid; + + /* At least one command is needed, and we started first one. + * Hook its output fd to the main loop. + */ + struct analyze_event_data *evd = xzalloc(sizeof(*evd)); + evd->run_state = state; + evd->event_name = xstrdup(event_name); + evd->env_list = env_list; + evd->event_log = strbuf_new(); + evd->fd = state->command_out_fd; + + state->logging_param = evd; + state->error_param = evd; + state->interaction_param = evd; + + ndelay_on(evd->fd); + evd->channel = g_io_channel_unix_new(evd->fd); + g_event_source_id = g_io_add_watch(evd->channel, + G_IO_IN | G_IO_ERR | G_IO_HUP, /* need HUP to detect EOF w/o any data */ + consume_cmd_output, + evd + ); + + gtk_label_set_text(g_lbl_event_log, _(""Processing..."")); + log_notice(""running event '%s' on '%s'"", event_name, g_dump_dir_name); + char *msg = xasprintf(""--- Running %s ---\n"", event_name); + append_to_textview(g_tv_event_log, msg); + free(msg); + + /* don't bother testing if they are visible, this is faster */ + gtk_widget_hide(GTK_WIDGET(g_img_process_fail)); + + gtk_widget_show(GTK_WIDGET(g_spinner_event_log)); + gtk_widget_show(g_btn_stop); + /* Disable (gray out) navigation buttons */ + gtk_widget_set_sensitive(g_btn_close, false); + gtk_widget_set_sensitive(g_btn_next, false); +} +",0,"static void start_event_run(const char *event_name) +{ + /* Start event asynchronously on the dump dir + * (synchronous run would freeze GUI until completion) + */ + + /* https://bugzilla.redhat.com/show_bug.cgi?id=1044653 */ + correct_bz_private_goup_name(event_name); + + struct run_event_state *state = new_run_event_state(); + state->logging_callback = run_event_gtk_logging; + state->error_callback = run_event_gtk_error; + state->alert_callback = run_event_gtk_alert; + state->ask_callback = run_event_gtk_ask; + state->ask_yes_no_callback = run_event_gtk_ask_yes_no; + state->ask_yes_no_yesforever_callback = run_event_gtk_ask_yes_no_yesforever; + state->ask_yes_no_save_result_callback = run_event_gtk_ask_yes_no_save_result; + state->ask_password_callback = run_event_gtk_ask_password; + + if (prepare_commands(state, g_dump_dir_name, event_name) == 0) + { + no_cmds: + /* No commands needed?! (This is untypical) */ + free_run_event_state(state); + char *msg = xasprintf(_(""No processing for event '%s' is defined""), event_name); + append_to_textview(g_tv_event_log, msg); + free(msg); + cancel_processing(g_lbl_event_log, _(""Processing failed.""), TERMINATE_NOFLAGS); + return; + } + + struct dump_dir *dd = wizard_open_directory_for_writing(g_dump_dir_name); + dd_close(dd); + if (!dd) + { + free_run_event_state(state); + if (!g_expert_mode) + { + cancel_processing(g_lbl_event_log, _(""Processing interrupted: can't continue without writable directory.""), TERMINATE_NOFLAGS); + } + return; /* user refused to steal, or write error, etc... */ + } + + set_excluded_envvar(); + GList *env_list = export_event_config(event_name); + + if (spawn_next_command(state, g_dump_dir_name, event_name, EXECFLG_SETPGID) < 0) + { + unexport_event_config(env_list); + goto no_cmds; + } + g_event_child_pid = state->command_pid; + + /* At least one command is needed, and we started first one. + * Hook its output fd to the main loop. + */ + struct analyze_event_data *evd = xzalloc(sizeof(*evd)); + evd->run_state = state; + evd->event_name = xstrdup(event_name); + evd->env_list = env_list; + evd->event_log = strbuf_new(); + evd->fd = state->command_out_fd; + + state->logging_param = evd; + state->error_param = evd; + state->interaction_param = evd; + + ndelay_on(evd->fd); + evd->channel = g_io_channel_unix_new(evd->fd); + g_event_source_id = g_io_add_watch(evd->channel, + G_IO_IN | G_IO_ERR | G_IO_HUP, /* need HUP to detect EOF w/o any data */ + consume_cmd_output, + evd + ); + + gtk_label_set_text(g_lbl_event_log, _(""Processing..."")); + log_notice(""running event '%s' on '%s'"", event_name, g_dump_dir_name); + char *msg = xasprintf(""--- Running %s ---\n"", event_name); + append_to_textview(g_tv_event_log, msg); + free(msg); + + /* don't bother testing if they are visible, this is faster */ + gtk_widget_hide(GTK_WIDGET(g_img_process_fail)); + + gtk_widget_show(GTK_WIDGET(g_spinner_event_log)); + gtk_widget_show(g_btn_stop); + /* Disable (gray out) navigation buttons */ + gtk_widget_set_sensitive(g_btn_close, false); + gtk_widget_set_sensitive(g_btn_next, false); +} +","@@ -433,8 +433,6 @@ static void save_text_if_changed(const char *name, const char *new_value) + + //FIXME: else: what to do with still-unsaved data in the widget?? + dd_close(dd); +- problem_data_reload_from_dump_dir(); +- update_gui_state_from_problem_data(/* don't update selected event */ 0); + } + } + +@@ -777,7 +775,11 @@ static void tv_details_row_activated( + load_text_to_text_view(GTK_TEXT_VIEW(textview), item_name); + + if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK) ++ { + save_text_from_text_view(GTK_TEXT_VIEW(textview), item_name); ++ problem_data_reload_from_dump_dir(); ++ update_gui_state_from_problem_data(/* don't update selected event */ 0); ++ } + + gtk_widget_destroy(textview); + gtk_widget_destroy(scrolled); +@@ -2709,7 +2711,8 @@ static void on_page_prepare(GtkNotebook *assistant, GtkWidget *page, gpointer us + * these tabs will be lost */ + save_items_from_notepad(); + save_text_from_text_view(g_tv_comment, FILENAME_COMMENT); +- ++ problem_data_reload_from_dump_dir(); ++ update_gui_state_from_problem_data(/* don't update selected event */ 0); + + if (pages[PAGENO_SUMMARY].page_widget == page) + {",827,1158,2048 +15441,"bool GLES2DecoderImpl::SimulateFixedAttribs( + const char* function_name, + GLuint max_vertex_accessed, bool* simulated, GLsizei primcount) { + DCHECK(simulated); + *simulated = false; + if (gl_version_info().SupportsFixedType()) + return true; + + if (!state_.vertex_attrib_manager->HaveFixedAttribs()) { + return true; + } + + LOCAL_PERFORMANCE_WARNING( + ""GL_FIXED attributes have a significant performance penalty""); + + + base::CheckedNumeric elements_needed = 0; + const VertexAttribManager::VertexAttribList& enabled_attribs = + state_.vertex_attrib_manager->GetEnabledVertexAttribs(); + for (VertexAttribManager::VertexAttribList::const_iterator it = + enabled_attribs.begin(); it != enabled_attribs.end(); ++it) { + const VertexAttrib* attrib = *it; + const Program::VertexAttrib* attrib_info = + state_.current_program->GetAttribInfoByLocation(attrib->index()); + GLuint max_accessed = attrib->MaxVertexAccessed(primcount, + max_vertex_accessed); + GLuint num_vertices = max_accessed + 1; + if (num_vertices == 0) { + LOCAL_SET_GL_ERROR( + GL_OUT_OF_MEMORY, function_name, ""Simulating attrib 0""); + return false; + } + if (attrib_info && + attrib->CanAccess(max_accessed) && + attrib->type() == GL_FIXED) { + elements_needed += base::CheckMul(num_vertices, attrib->size()); + } + } + + const uint32_t kSizeOfFloat = sizeof(float); // NOLINT + uint32_t size_needed = 0; + if (!base::CheckMul(elements_needed, kSizeOfFloat) + .AssignIfValid(&size_needed) || + size_needed > 0x7FFFFFFFU) { + LOCAL_SET_GL_ERROR( + GL_OUT_OF_MEMORY, function_name, ""simulating GL_FIXED attribs""); + return false; + } + + LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER(function_name); + + api()->glBindBufferFn(GL_ARRAY_BUFFER, fixed_attrib_buffer_id_); + if (static_cast(size_needed) > fixed_attrib_buffer_size_) { + api()->glBufferDataFn(GL_ARRAY_BUFFER, size_needed, nullptr, + GL_DYNAMIC_DRAW); + GLenum error = api()->glGetErrorFn(); + if (error != GL_NO_ERROR) { + LOCAL_SET_GL_ERROR( + GL_OUT_OF_MEMORY, function_name, ""simulating GL_FIXED attribs""); + return false; + } + } + + GLintptr offset = 0; + for (VertexAttribManager::VertexAttribList::const_iterator it = + enabled_attribs.begin(); it != enabled_attribs.end(); ++it) { + const VertexAttrib* attrib = *it; + const Program::VertexAttrib* attrib_info = + state_.current_program->GetAttribInfoByLocation(attrib->index()); + GLuint max_accessed = attrib->MaxVertexAccessed(primcount, + max_vertex_accessed); + GLuint num_vertices = max_accessed + 1; + if (num_vertices == 0) { + LOCAL_SET_GL_ERROR( + GL_OUT_OF_MEMORY, function_name, ""Simulating attrib 0""); + return false; + } + if (attrib_info && + attrib->CanAccess(max_accessed) && + attrib->type() == GL_FIXED) { + int num_elements = attrib->size() * num_vertices; + const int src_size = num_elements * sizeof(int32_t); + const int dst_size = num_elements * sizeof(float); + std::unique_ptr data(new float[num_elements]); + const int32_t* src = reinterpret_cast( + attrib->buffer()->GetRange(attrib->offset(), src_size)); + const int32_t* end = src + num_elements; + float* dst = data.get(); + while (src != end) { + *dst++ = static_cast(*src++) / 65536.0f; + } + api()->glBufferSubDataFn(GL_ARRAY_BUFFER, offset, dst_size, data.get()); + api()->glVertexAttribPointerFn(attrib->index(), attrib->size(), GL_FLOAT, + false, 0, + reinterpret_cast(offset)); + offset += dst_size; + } + } + *simulated = true; + return true; +} +",0,"bool GLES2DecoderImpl::SimulateFixedAttribs( + const char* function_name, + GLuint max_vertex_accessed, bool* simulated, GLsizei primcount) { + DCHECK(simulated); + *simulated = false; + if (gl_version_info().SupportsFixedType()) + return true; + + if (!state_.vertex_attrib_manager->HaveFixedAttribs()) { + return true; + } + + LOCAL_PERFORMANCE_WARNING( + ""GL_FIXED attributes have a significant performance penalty""); + + + base::CheckedNumeric elements_needed = 0; + const VertexAttribManager::VertexAttribList& enabled_attribs = + state_.vertex_attrib_manager->GetEnabledVertexAttribs(); + for (VertexAttribManager::VertexAttribList::const_iterator it = + enabled_attribs.begin(); it != enabled_attribs.end(); ++it) { + const VertexAttrib* attrib = *it; + const Program::VertexAttrib* attrib_info = + state_.current_program->GetAttribInfoByLocation(attrib->index()); + GLuint max_accessed = attrib->MaxVertexAccessed(primcount, + max_vertex_accessed); + GLuint num_vertices = max_accessed + 1; + if (num_vertices == 0) { + LOCAL_SET_GL_ERROR( + GL_OUT_OF_MEMORY, function_name, ""Simulating attrib 0""); + return false; + } + if (attrib_info && + attrib->CanAccess(max_accessed) && + attrib->type() == GL_FIXED) { + elements_needed += base::CheckMul(num_vertices, attrib->size()); + } + } + + const uint32_t kSizeOfFloat = sizeof(float); // NOLINT + uint32_t size_needed = 0; + if (!base::CheckMul(elements_needed, kSizeOfFloat) + .AssignIfValid(&size_needed) || + size_needed > 0x7FFFFFFFU) { + LOCAL_SET_GL_ERROR( + GL_OUT_OF_MEMORY, function_name, ""simulating GL_FIXED attribs""); + return false; + } + + LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER(function_name); + + api()->glBindBufferFn(GL_ARRAY_BUFFER, fixed_attrib_buffer_id_); + if (static_cast(size_needed) > fixed_attrib_buffer_size_) { + api()->glBufferDataFn(GL_ARRAY_BUFFER, size_needed, nullptr, + GL_DYNAMIC_DRAW); + GLenum error = api()->glGetErrorFn(); + if (error != GL_NO_ERROR) { + LOCAL_SET_GL_ERROR( + GL_OUT_OF_MEMORY, function_name, ""simulating GL_FIXED attribs""); + return false; + } + } + + GLintptr offset = 0; + for (VertexAttribManager::VertexAttribList::const_iterator it = + enabled_attribs.begin(); it != enabled_attribs.end(); ++it) { + const VertexAttrib* attrib = *it; + const Program::VertexAttrib* attrib_info = + state_.current_program->GetAttribInfoByLocation(attrib->index()); + GLuint max_accessed = attrib->MaxVertexAccessed(primcount, + max_vertex_accessed); + GLuint num_vertices = max_accessed + 1; + if (num_vertices == 0) { + LOCAL_SET_GL_ERROR( + GL_OUT_OF_MEMORY, function_name, ""Simulating attrib 0""); + return false; + } + if (attrib_info && + attrib->CanAccess(max_accessed) && + attrib->type() == GL_FIXED) { + int num_elements = attrib->size() * num_vertices; + const int src_size = num_elements * sizeof(int32_t); + const int dst_size = num_elements * sizeof(float); + std::unique_ptr data(new float[num_elements]); + const int32_t* src = reinterpret_cast( + attrib->buffer()->GetRange(attrib->offset(), src_size)); + const int32_t* end = src + num_elements; + float* dst = data.get(); + while (src != end) { + *dst++ = static_cast(*src++) / 65536.0f; + } + api()->glBufferSubDataFn(GL_ARRAY_BUFFER, offset, dst_size, data.get()); + api()->glVertexAttribPointerFn(attrib->index(), attrib->size(), GL_FLOAT, + false, 0, + reinterpret_cast(offset)); + offset += dst_size; + } + } + *simulated = true; + return true; +} +","@@ -17209,6 +17209,13 @@ error::Error GLES2DecoderImpl::HandleBeginQueryEXT( + return error::kNoError; + } + break; ++ case GL_PROGRAM_COMPLETION_QUERY_CHROMIUM: ++ if (!features().chromium_completion_query) { ++ LOCAL_SET_GL_ERROR(GL_INVALID_OPERATION, ""glBeginQueryEXT"", ++ ""not enabled for program completion queries""); ++ return error::kNoError; ++ } ++ break; + case GL_SAMPLES_PASSED_ARB: + if (!features().occlusion_query) { + LOCAL_SET_GL_ERROR(",927,1258,2048 +3653,"xfs_da3_node_toosmall( + struct xfs_da_state *state, + int *action) +{ + struct xfs_da_intnode *node; + struct xfs_da_state_blk *blk; + struct xfs_da_blkinfo *info; + xfs_dablk_t blkno; + struct xfs_buf *bp; + struct xfs_da3_icnode_hdr nodehdr; + int count; + int forward; + int error; + int retval; + int i; + struct xfs_inode *dp = state->args->dp; + + trace_xfs_da_node_toosmall(state->args); + + /* + * Check for the degenerate case of the block being over 50% full. + * If so, it's not worth even looking to see if we might be able + * to coalesce with a sibling. + */ + blk = &state->path.blk[ state->path.active-1 ]; + info = blk->bp->b_addr; + node = (xfs_da_intnode_t *)info; + dp->d_ops->node_hdr_from_disk(&nodehdr, node); + if (nodehdr.count > (state->node_ents >> 1)) { + *action = 0; /* blk over 50%, don't try to join */ + return(0); /* blk over 50%, don't try to join */ + } + + /* + * Check for the degenerate case of the block being empty. + * If the block is empty, we'll simply delete it, no need to + * coalesce it with a sibling block. We choose (arbitrarily) + * to merge with the forward block unless it is NULL. + */ + if (nodehdr.count == 0) { + /* + * Make altpath point to the block we want to keep and + * path point to the block we want to drop (this one). + */ + forward = (info->forw != 0); + memcpy(&state->altpath, &state->path, sizeof(state->path)); + error = xfs_da3_path_shift(state, &state->altpath, forward, + 0, &retval); + if (error) + return(error); + if (retval) { + *action = 0; + } else { + *action = 2; + } + return(0); + } + + /* + * Examine each sibling block to see if we can coalesce with + * at least 25% free space to spare. We need to figure out + * whether to merge with the forward or the backward block. + * We prefer coalescing with the lower numbered sibling so as + * to shrink a directory over time. + */ + count = state->node_ents; + count -= state->node_ents >> 2; + count -= nodehdr.count; + + /* start with smaller blk num */ + forward = nodehdr.forw < nodehdr.back; + for (i = 0; i < 2; forward = !forward, i++) { + struct xfs_da3_icnode_hdr thdr; + if (forward) + blkno = nodehdr.forw; + else + blkno = nodehdr.back; + if (blkno == 0) + continue; + error = xfs_da3_node_read(state->args->trans, dp, + blkno, -1, &bp, state->args->whichfork); + if (error) + return(error); + + node = bp->b_addr; + dp->d_ops->node_hdr_from_disk(&thdr, node); + xfs_trans_brelse(state->args->trans, bp); + + if (count - thdr.count >= 0) + break; /* fits with at least 25% to spare */ + } + if (i >= 2) { + *action = 0; + return 0; + } + + /* + * Make altpath point to the block we want to keep (the lower + * numbered block) and path point to the block we want to drop. + */ + memcpy(&state->altpath, &state->path, sizeof(state->path)); + if (blkno < blk->blkno) { + error = xfs_da3_path_shift(state, &state->altpath, forward, + 0, &retval); + } else { + error = xfs_da3_path_shift(state, &state->path, forward, + 0, &retval); + } + if (error) + return error; + if (retval) { + *action = 0; + return 0; + } + *action = 1; + return 0; +} +",0,"xfs_da3_node_toosmall( + struct xfs_da_state *state, + int *action) +{ + struct xfs_da_intnode *node; + struct xfs_da_state_blk *blk; + struct xfs_da_blkinfo *info; + xfs_dablk_t blkno; + struct xfs_buf *bp; + struct xfs_da3_icnode_hdr nodehdr; + int count; + int forward; + int error; + int retval; + int i; + struct xfs_inode *dp = state->args->dp; + + trace_xfs_da_node_toosmall(state->args); + + /* + * Check for the degenerate case of the block being over 50% full. + * If so, it's not worth even looking to see if we might be able + * to coalesce with a sibling. + */ + blk = &state->path.blk[ state->path.active-1 ]; + info = blk->bp->b_addr; + node = (xfs_da_intnode_t *)info; + dp->d_ops->node_hdr_from_disk(&nodehdr, node); + if (nodehdr.count > (state->node_ents >> 1)) { + *action = 0; /* blk over 50%, don't try to join */ + return(0); /* blk over 50%, don't try to join */ + } + + /* + * Check for the degenerate case of the block being empty. + * If the block is empty, we'll simply delete it, no need to + * coalesce it with a sibling block. We choose (arbitrarily) + * to merge with the forward block unless it is NULL. + */ + if (nodehdr.count == 0) { + /* + * Make altpath point to the block we want to keep and + * path point to the block we want to drop (this one). + */ + forward = (info->forw != 0); + memcpy(&state->altpath, &state->path, sizeof(state->path)); + error = xfs_da3_path_shift(state, &state->altpath, forward, + 0, &retval); + if (error) + return(error); + if (retval) { + *action = 0; + } else { + *action = 2; + } + return(0); + } + + /* + * Examine each sibling block to see if we can coalesce with + * at least 25% free space to spare. We need to figure out + * whether to merge with the forward or the backward block. + * We prefer coalescing with the lower numbered sibling so as + * to shrink a directory over time. + */ + count = state->node_ents; + count -= state->node_ents >> 2; + count -= nodehdr.count; + + /* start with smaller blk num */ + forward = nodehdr.forw < nodehdr.back; + for (i = 0; i < 2; forward = !forward, i++) { + struct xfs_da3_icnode_hdr thdr; + if (forward) + blkno = nodehdr.forw; + else + blkno = nodehdr.back; + if (blkno == 0) + continue; + error = xfs_da3_node_read(state->args->trans, dp, + blkno, -1, &bp, state->args->whichfork); + if (error) + return(error); + + node = bp->b_addr; + dp->d_ops->node_hdr_from_disk(&thdr, node); + xfs_trans_brelse(state->args->trans, bp); + + if (count - thdr.count >= 0) + break; /* fits with at least 25% to spare */ + } + if (i >= 2) { + *action = 0; + return 0; + } + + /* + * Make altpath point to the block we want to keep (the lower + * numbered block) and path point to the block we want to drop. + */ + memcpy(&state->altpath, &state->path, sizeof(state->path)); + if (blkno < blk->blkno) { + error = xfs_da3_path_shift(state, &state->altpath, forward, + 0, &retval); + } else { + error = xfs_da3_path_shift(state, &state->path, forward, + 0, &retval); + } + if (error) + return error; + if (retval) { + *action = 0; + return 0; + } + *action = 1; + return 0; +} +","@@ -1295,7 +1295,7 @@ xfs_da3_fixhashpath( + node = blk->bp->b_addr; + dp->d_ops->node_hdr_from_disk(&nodehdr, node); + btree = dp->d_ops->node_tree_p(node); +- if (be32_to_cpu(btree->hashval) == lasthash) ++ if (be32_to_cpu(btree[blk->index].hashval) == lasthash) + break; + blk->hashval = lasthash; + btree[blk->index].hashval = cpu_to_be32(lasthash);",1012,1343,2048 +15946,"PDFiumEngine::PDFiumEngine(PDFEngine::Client* client) + : client_(client), + current_zoom_(1.0), + current_rotation_(0), + doc_(nullptr), + form_(nullptr), + defer_page_unload_(false), + selecting_(false), + mouse_down_state_(PDFiumPage::NONSELECTABLE_AREA, + PDFiumPage::LinkTarget()), + in_form_text_area_(false), + editable_form_text_area_(false), + mouse_left_button_down_(false), + permissions_(0), + permissions_handler_revision_(-1), + fpdf_availability_(nullptr), + last_page_mouse_down_(-1), + most_visible_page_(-1), + called_do_document_action_(false), + render_grayscale_(false), + render_annots_(true) { + find_factory_.Initialize(this); + password_factory_.Initialize(this); + + file_access_.m_FileLen = 0; + file_access_.m_GetBlock = &GetBlock; + file_access_.m_Param = this; + + file_availability_.version = 1; + file_availability_.IsDataAvail = &IsDataAvail; + file_availability_.engine = this; + + download_hints_.version = 1; + download_hints_.AddSegment = &AddSegment; + download_hints_.engine = this; + + FPDF_FORMFILLINFO::version = 1; + FPDF_FORMFILLINFO::m_pJsPlatform = this; + FPDF_FORMFILLINFO::Release = nullptr; + FPDF_FORMFILLINFO::FFI_Invalidate = Form_Invalidate; + FPDF_FORMFILLINFO::FFI_OutputSelectedRect = Form_OutputSelectedRect; + FPDF_FORMFILLINFO::FFI_SetCursor = Form_SetCursor; + FPDF_FORMFILLINFO::FFI_SetTimer = Form_SetTimer; + FPDF_FORMFILLINFO::FFI_KillTimer = Form_KillTimer; + FPDF_FORMFILLINFO::FFI_GetLocalTime = Form_GetLocalTime; + FPDF_FORMFILLINFO::FFI_OnChange = Form_OnChange; + FPDF_FORMFILLINFO::FFI_GetPage = Form_GetPage; + FPDF_FORMFILLINFO::FFI_GetCurrentPage = Form_GetCurrentPage; + FPDF_FORMFILLINFO::FFI_GetRotation = Form_GetRotation; + FPDF_FORMFILLINFO::FFI_ExecuteNamedAction = Form_ExecuteNamedAction; + FPDF_FORMFILLINFO::FFI_SetTextFieldFocus = Form_SetTextFieldFocus; + FPDF_FORMFILLINFO::FFI_DoURIAction = Form_DoURIAction; + FPDF_FORMFILLINFO::FFI_DoGoToAction = Form_DoGoToAction; +#if defined(PDF_ENABLE_XFA) + FPDF_FORMFILLINFO::version = 2; + FPDF_FORMFILLINFO::FFI_EmailTo = Form_EmailTo; + FPDF_FORMFILLINFO::FFI_DisplayCaret = Form_DisplayCaret; + FPDF_FORMFILLINFO::FFI_SetCurrentPage = Form_SetCurrentPage; + FPDF_FORMFILLINFO::FFI_GetCurrentPageIndex = Form_GetCurrentPageIndex; + FPDF_FORMFILLINFO::FFI_GetPageViewRect = Form_GetPageViewRect; + FPDF_FORMFILLINFO::FFI_GetPlatform = Form_GetPlatform; + FPDF_FORMFILLINFO::FFI_PageEvent = nullptr; + FPDF_FORMFILLINFO::FFI_PopupMenu = Form_PopupMenu; + FPDF_FORMFILLINFO::FFI_PostRequestURL = Form_PostRequestURL; + FPDF_FORMFILLINFO::FFI_PutRequestURL = Form_PutRequestURL; + FPDF_FORMFILLINFO::FFI_UploadTo = Form_UploadTo; + FPDF_FORMFILLINFO::FFI_DownloadFromURL = Form_DownloadFromURL; + FPDF_FORMFILLINFO::FFI_OpenFile = Form_OpenFile; + FPDF_FORMFILLINFO::FFI_GotoURL = Form_GotoURL; + FPDF_FORMFILLINFO::FFI_GetLanguage = Form_GetLanguage; +#endif // defined(PDF_ENABLE_XFA) + IPDF_JSPLATFORM::version = 3; + IPDF_JSPLATFORM::app_alert = Form_Alert; + IPDF_JSPLATFORM::app_beep = Form_Beep; + IPDF_JSPLATFORM::app_response = Form_Response; + IPDF_JSPLATFORM::Doc_getFilePath = Form_GetFilePath; + IPDF_JSPLATFORM::Doc_mail = Form_Mail; + IPDF_JSPLATFORM::Doc_print = Form_Print; + IPDF_JSPLATFORM::Doc_submitForm = Form_SubmitForm; + IPDF_JSPLATFORM::Doc_gotoPage = Form_GotoPage; + IPDF_JSPLATFORM::Field_browse = nullptr; + + IFSDK_PAUSE::version = 1; + IFSDK_PAUSE::user = nullptr; + IFSDK_PAUSE::NeedToPauseNow = Pause_NeedToPauseNow; + +#if defined(OS_LINUX) + pp::Instance* instance = client_->GetPluginInstance(); + if (instance) + g_last_instance_id = instance->pp_instance(); +#endif +} +",0,"PDFiumEngine::PDFiumEngine(PDFEngine::Client* client) + : client_(client), + current_zoom_(1.0), + current_rotation_(0), + doc_(nullptr), + form_(nullptr), + defer_page_unload_(false), + selecting_(false), + mouse_down_state_(PDFiumPage::NONSELECTABLE_AREA, + PDFiumPage::LinkTarget()), + in_form_text_area_(false), + editable_form_text_area_(false), + mouse_left_button_down_(false), + permissions_(0), + permissions_handler_revision_(-1), + fpdf_availability_(nullptr), + last_page_mouse_down_(-1), + most_visible_page_(-1), + called_do_document_action_(false), + render_grayscale_(false), + render_annots_(true) { + find_factory_.Initialize(this); + password_factory_.Initialize(this); + + file_access_.m_FileLen = 0; + file_access_.m_GetBlock = &GetBlock; + file_access_.m_Param = this; + + file_availability_.version = 1; + file_availability_.IsDataAvail = &IsDataAvail; + file_availability_.engine = this; + + download_hints_.version = 1; + download_hints_.AddSegment = &AddSegment; + download_hints_.engine = this; + + FPDF_FORMFILLINFO::version = 1; + FPDF_FORMFILLINFO::m_pJsPlatform = this; + FPDF_FORMFILLINFO::Release = nullptr; + FPDF_FORMFILLINFO::FFI_Invalidate = Form_Invalidate; + FPDF_FORMFILLINFO::FFI_OutputSelectedRect = Form_OutputSelectedRect; + FPDF_FORMFILLINFO::FFI_SetCursor = Form_SetCursor; + FPDF_FORMFILLINFO::FFI_SetTimer = Form_SetTimer; + FPDF_FORMFILLINFO::FFI_KillTimer = Form_KillTimer; + FPDF_FORMFILLINFO::FFI_GetLocalTime = Form_GetLocalTime; + FPDF_FORMFILLINFO::FFI_OnChange = Form_OnChange; + FPDF_FORMFILLINFO::FFI_GetPage = Form_GetPage; + FPDF_FORMFILLINFO::FFI_GetCurrentPage = Form_GetCurrentPage; + FPDF_FORMFILLINFO::FFI_GetRotation = Form_GetRotation; + FPDF_FORMFILLINFO::FFI_ExecuteNamedAction = Form_ExecuteNamedAction; + FPDF_FORMFILLINFO::FFI_SetTextFieldFocus = Form_SetTextFieldFocus; + FPDF_FORMFILLINFO::FFI_DoURIAction = Form_DoURIAction; + FPDF_FORMFILLINFO::FFI_DoGoToAction = Form_DoGoToAction; +#if defined(PDF_ENABLE_XFA) + FPDF_FORMFILLINFO::version = 2; + FPDF_FORMFILLINFO::FFI_EmailTo = Form_EmailTo; + FPDF_FORMFILLINFO::FFI_DisplayCaret = Form_DisplayCaret; + FPDF_FORMFILLINFO::FFI_SetCurrentPage = Form_SetCurrentPage; + FPDF_FORMFILLINFO::FFI_GetCurrentPageIndex = Form_GetCurrentPageIndex; + FPDF_FORMFILLINFO::FFI_GetPageViewRect = Form_GetPageViewRect; + FPDF_FORMFILLINFO::FFI_GetPlatform = Form_GetPlatform; + FPDF_FORMFILLINFO::FFI_PageEvent = nullptr; + FPDF_FORMFILLINFO::FFI_PopupMenu = Form_PopupMenu; + FPDF_FORMFILLINFO::FFI_PostRequestURL = Form_PostRequestURL; + FPDF_FORMFILLINFO::FFI_PutRequestURL = Form_PutRequestURL; + FPDF_FORMFILLINFO::FFI_UploadTo = Form_UploadTo; + FPDF_FORMFILLINFO::FFI_DownloadFromURL = Form_DownloadFromURL; + FPDF_FORMFILLINFO::FFI_OpenFile = Form_OpenFile; + FPDF_FORMFILLINFO::FFI_GotoURL = Form_GotoURL; + FPDF_FORMFILLINFO::FFI_GetLanguage = Form_GetLanguage; +#endif // defined(PDF_ENABLE_XFA) + IPDF_JSPLATFORM::version = 3; + IPDF_JSPLATFORM::app_alert = Form_Alert; + IPDF_JSPLATFORM::app_beep = Form_Beep; + IPDF_JSPLATFORM::app_response = Form_Response; + IPDF_JSPLATFORM::Doc_getFilePath = Form_GetFilePath; + IPDF_JSPLATFORM::Doc_mail = Form_Mail; + IPDF_JSPLATFORM::Doc_print = Form_Print; + IPDF_JSPLATFORM::Doc_submitForm = Form_SubmitForm; + IPDF_JSPLATFORM::Doc_gotoPage = Form_GotoPage; + IPDF_JSPLATFORM::Field_browse = nullptr; + + IFSDK_PAUSE::version = 1; + IFSDK_PAUSE::user = nullptr; + IFSDK_PAUSE::NeedToPauseNow = Pause_NeedToPauseNow; + +#if defined(OS_LINUX) + pp::Instance* instance = client_->GetPluginInstance(); + if (instance) + g_last_instance_id = instance->pp_instance(); +#endif +} +","@@ -1405,9 +1405,15 @@ bool PDFiumEngine::HandleEvent(const pp::InputEvent& event) { + + DCHECK(defer_page_unload_); + defer_page_unload_ = false; +- for (int page_index : deferred_page_unloads_) ++ ++ // Store the pages to unload away because the act of unloading pages can cause ++ // there to be more pages to unload. We leave those extra pages to be unloaded ++ // on the next go around. ++ std::vector pages_to_unload; ++ std::swap(pages_to_unload, deferred_page_unloads_); ++ for (int page_index : pages_to_unload) + pages_[page_index]->Unload(); +- deferred_page_unloads_.clear(); ++ + return rv; + } + ",1089,1420,2048 +960,"int ssl3_client_hello(SSL *s) +{ + unsigned char *buf; + unsigned char *p, *d; + int i; + unsigned long l; +#ifndef OPENSSL_NO_COMP + int j; + SSL_COMP *comp; +#endif + + buf = (unsigned char *)s->init_buf->data; + if (s->state == SSL3_ST_CW_CLNT_HELLO_A) { + SSL_SESSION *sess = s->session; + if ((sess == NULL) || (sess->ssl_version != s->version) || +#ifdef OPENSSL_NO_TLSEXT + !sess->session_id_length || +#else + /* + * In the case of EAP-FAST, we can have a pre-shared + * ""ticket"" without a session ID. + */ + (!sess->session_id_length && !sess->tlsext_tick) || +#endif + (sess->not_resumable)) { + if (!ssl_get_new_session(s, 0)) + goto err; + } + /* else use the pre-loaded session */ + + p = s->s3->client_random; + + if (ssl_fill_hello_random(s, 0, p, SSL3_RANDOM_SIZE) <= 0) + goto err; + + /* Do the message type and length last */ + d = p = &(buf[4]); + + /*- + * version indicates the negotiated version: for example from + * an SSLv2/v3 compatible client hello). The client_version + * field is the maximum version we permit and it is also + * used in RSA encrypted premaster secrets. Some servers can + * choke if we initially report a higher version then + * renegotiate to a lower one in the premaster secret. This + * didn't happen with TLS 1.0 as most servers supported it + * but it can with TLS 1.1 or later if the server only supports + * 1.0. + * + * Possible scenario with previous logic: + * 1. Client hello indicates TLS 1.2 + * 2. Server hello says TLS 1.0 + * 3. RSA encrypted premaster secret uses 1.2. + * 4. Handhaked proceeds using TLS 1.0. + * 5. Server sends hello request to renegotiate. + * 6. Client hello indicates TLS v1.0 as we now + * know that is maximum server supports. + * 7. Server chokes on RSA encrypted premaster secret + * containing version 1.0. + * + * For interoperability it should be OK to always use the + * maximum version we support in client hello and then rely + * on the checking of version to ensure the servers isn't + * being inconsistent: for example initially negotiating with + * TLS 1.0 and renegotiating with TLS 1.2. We do this by using + * client_version in client hello and not resetting it to + * the negotiated version. + */ +#if 0 + *(p++) = s->version >> 8; + *(p++) = s->version & 0xff; + s->client_version = s->version; +#else + *(p++) = s->client_version >> 8; + *(p++) = s->client_version & 0xff; +#endif + + /* Random stuff */ + memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE); + p += SSL3_RANDOM_SIZE; + + /* Session ID */ + if (s->new_session) + i = 0; + else + i = s->session->session_id_length; + *(p++) = i; + if (i != 0) { + if (i > (int)sizeof(s->session->session_id)) { + SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); + goto err; + } + memcpy(p, s->session->session_id, i); + p += i; + } + + /* Ciphers supported */ + i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &(p[2]), 0); + if (i == 0) { + SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_NO_CIPHERS_AVAILABLE); + goto err; + } +#ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH + /* + * Some servers hang if client hello > 256 bytes as hack workaround + * chop number of supported ciphers to keep it well below this if we + * use TLS v1.2 + */ + if (TLS1_get_version(s) >= TLS1_2_VERSION + && i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH) + i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1; +#endif + s2n(i, p); + p += i; + + /* COMPRESSION */ +#ifdef OPENSSL_NO_COMP + *(p++) = 1; +#else + + if ((s->options & SSL_OP_NO_COMPRESSION) + || !s->ctx->comp_methods) + j = 0; + else + j = sk_SSL_COMP_num(s->ctx->comp_methods); + *(p++) = 1 + j; + for (i = 0; i < j; i++) { + comp = sk_SSL_COMP_value(s->ctx->comp_methods, i); + *(p++) = comp->id; + } +#endif + *(p++) = 0; /* Add the NULL method */ + +#ifndef OPENSSL_NO_TLSEXT + /* TLS extensions */ + if (ssl_prepare_clienthello_tlsext(s) <= 0) { + SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT); + goto err; + } + if ((p = + ssl_add_clienthello_tlsext(s, p, + buf + SSL3_RT_MAX_PLAIN_LENGTH)) == + NULL) { + SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); + goto err; + } +#endif + + l = (p - d); + d = buf; + *(d++) = SSL3_MT_CLIENT_HELLO; + l2n3(l, d); + + s->state = SSL3_ST_CW_CLNT_HELLO_B; + /* number of bytes to write */ + s->init_num = p - buf; + s->init_off = 0; + } + + /* SSL3_ST_CW_CLNT_HELLO_B */ + return (ssl3_do_write(s, SSL3_RT_HANDSHAKE)); + err: + s->state = SSL_ST_ERR; + return (-1); +} +",0,"int ssl3_client_hello(SSL *s) +{ + unsigned char *buf; + unsigned char *p, *d; + int i; + unsigned long l; +#ifndef OPENSSL_NO_COMP + int j; + SSL_COMP *comp; +#endif + + buf = (unsigned char *)s->init_buf->data; + if (s->state == SSL3_ST_CW_CLNT_HELLO_A) { + SSL_SESSION *sess = s->session; + if ((sess == NULL) || (sess->ssl_version != s->version) || +#ifdef OPENSSL_NO_TLSEXT + !sess->session_id_length || +#else + /* + * In the case of EAP-FAST, we can have a pre-shared + * ""ticket"" without a session ID. + */ + (!sess->session_id_length && !sess->tlsext_tick) || +#endif + (sess->not_resumable)) { + if (!ssl_get_new_session(s, 0)) + goto err; + } + /* else use the pre-loaded session */ + + p = s->s3->client_random; + + if (ssl_fill_hello_random(s, 0, p, SSL3_RANDOM_SIZE) <= 0) + goto err; + + /* Do the message type and length last */ + d = p = &(buf[4]); + + /*- + * version indicates the negotiated version: for example from + * an SSLv2/v3 compatible client hello). The client_version + * field is the maximum version we permit and it is also + * used in RSA encrypted premaster secrets. Some servers can + * choke if we initially report a higher version then + * renegotiate to a lower one in the premaster secret. This + * didn't happen with TLS 1.0 as most servers supported it + * but it can with TLS 1.1 or later if the server only supports + * 1.0. + * + * Possible scenario with previous logic: + * 1. Client hello indicates TLS 1.2 + * 2. Server hello says TLS 1.0 + * 3. RSA encrypted premaster secret uses 1.2. + * 4. Handhaked proceeds using TLS 1.0. + * 5. Server sends hello request to renegotiate. + * 6. Client hello indicates TLS v1.0 as we now + * know that is maximum server supports. + * 7. Server chokes on RSA encrypted premaster secret + * containing version 1.0. + * + * For interoperability it should be OK to always use the + * maximum version we support in client hello and then rely + * on the checking of version to ensure the servers isn't + * being inconsistent: for example initially negotiating with + * TLS 1.0 and renegotiating with TLS 1.2. We do this by using + * client_version in client hello and not resetting it to + * the negotiated version. + */ +#if 0 + *(p++) = s->version >> 8; + *(p++) = s->version & 0xff; + s->client_version = s->version; +#else + *(p++) = s->client_version >> 8; + *(p++) = s->client_version & 0xff; +#endif + + /* Random stuff */ + memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE); + p += SSL3_RANDOM_SIZE; + + /* Session ID */ + if (s->new_session) + i = 0; + else + i = s->session->session_id_length; + *(p++) = i; + if (i != 0) { + if (i > (int)sizeof(s->session->session_id)) { + SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); + goto err; + } + memcpy(p, s->session->session_id, i); + p += i; + } + + /* Ciphers supported */ + i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &(p[2]), 0); + if (i == 0) { + SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_NO_CIPHERS_AVAILABLE); + goto err; + } +#ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH + /* + * Some servers hang if client hello > 256 bytes as hack workaround + * chop number of supported ciphers to keep it well below this if we + * use TLS v1.2 + */ + if (TLS1_get_version(s) >= TLS1_2_VERSION + && i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH) + i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1; +#endif + s2n(i, p); + p += i; + + /* COMPRESSION */ +#ifdef OPENSSL_NO_COMP + *(p++) = 1; +#else + + if ((s->options & SSL_OP_NO_COMPRESSION) + || !s->ctx->comp_methods) + j = 0; + else + j = sk_SSL_COMP_num(s->ctx->comp_methods); + *(p++) = 1 + j; + for (i = 0; i < j; i++) { + comp = sk_SSL_COMP_value(s->ctx->comp_methods, i); + *(p++) = comp->id; + } +#endif + *(p++) = 0; /* Add the NULL method */ + +#ifndef OPENSSL_NO_TLSEXT + /* TLS extensions */ + if (ssl_prepare_clienthello_tlsext(s) <= 0) { + SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT); + goto err; + } + if ((p = + ssl_add_clienthello_tlsext(s, p, + buf + SSL3_RT_MAX_PLAIN_LENGTH)) == + NULL) { + SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); + goto err; + } +#endif + + l = (p - d); + d = buf; + *(d++) = SSL3_MT_CLIENT_HELLO; + l2n3(l, d); + + s->state = SSL3_ST_CW_CLNT_HELLO_B; + /* number of bytes to write */ + s->init_num = p - buf; + s->init_off = 0; + } + + /* SSL3_ST_CW_CLNT_HELLO_B */ + return (ssl3_do_write(s, SSL3_RT_HANDSHAKE)); + err: + s->state = SSL_ST_ERR; + return (-1); +} +","@@ -1143,6 +1143,12 @@ int ssl3_get_server_certificate(SSL *s) + goto f_err; + } + for (nc = 0; nc < llen;) { ++ if (nc + 3 > llen) { ++ al = SSL_AD_DECODE_ERROR; ++ SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE, ++ SSL_R_CERT_LENGTH_MISMATCH); ++ goto f_err; ++ } + n2l3(p, l); + if ((l + nc + 3) > llen) { + al = SSL_AD_DECODE_ERROR; +@@ -2072,6 +2078,11 @@ int ssl3_get_certificate_request(SSL *s) + } + + for (nc = 0; nc < llen;) { ++ if (nc + 2 > llen) { ++ ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR); ++ SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST, SSL_R_CA_DN_TOO_LONG); ++ goto err; ++ } + n2s(p, l); + if ((l + nc + 2) > llen) { + if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG))",1422,1753,2048 +18111,"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); +} +",1,"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)) + { + if (colormap != (unsigned char *) NULL) + colormap=(unsigned char *) RelinquishMagickMemory(colormap); + if (pixels != (unsigned char *) NULL) + pixels=(unsigned char *) RelinquishMagickMemory(pixels); + ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); + } + /* + Write colormap to file. + */ + 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); +} +","@@ -396,12 +396,17 @@ static MagickBooleanType WriteMAPImage(const ImageInfo *image_info,Image *image) + sizeof(*colormap)); + if ((pixels == (unsigned char *) NULL) || + (colormap == (unsigned char *) NULL)) +- ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); ++ { ++ if (colormap != (unsigned char *) NULL) ++ colormap=(unsigned char *) RelinquishMagickMemory(colormap); ++ if (pixels != (unsigned char *) NULL) ++ pixels=(unsigned char *) RelinquishMagickMemory(pixels); ++ ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); ++ } + /* + Write colormap to file. + */ + q=colormap; +- q=colormap; + if (image->colors <= 256) + for (i=0; i < (ssize_t) image->colors; i++) + { +@@ -415,9 +420,11 @@ static MagickBooleanType WriteMAPImage(const ImageInfo *image_info,Image *image) + *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].green) & ++ 0xff); + *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) >> 8); +- *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) & 0xff); ++ *q++=(unsigned char) (ScaleQuantumToShort(image->colormap[i].blue) & ++ 0xff); + } + (void) WriteBlob(image,packet_size*image->colors,colormap); + colormap=(unsigned char *) RelinquishMagickMemory(colormap);",935,1266,2048 +1119,"int ssl3_client_hello(SSL *s) + { + unsigned char *buf; + unsigned char *p,*d; + int i; + unsigned long l; +#ifndef OPENSSL_NO_COMP + int j; + SSL_COMP *comp; +#endif + + buf=(unsigned char *)s->init_buf->data; + if (s->state == SSL3_ST_CW_CLNT_HELLO_A) + { + SSL_SESSION *sess = s->session; + if ((sess == NULL) || + (sess->ssl_version != s->version) || +#ifdef OPENSSL_NO_TLSEXT + !sess->session_id_length || +#else + (!sess->session_id_length && !sess->tlsext_tick) || +#endif + (sess->not_resumable)) + { + if (!ssl_get_new_session(s,0)) + goto err; + } + /* else use the pre-loaded session */ + + p=s->s3->client_random; + + if (ssl_fill_hello_random(s, 0, p, SSL3_RANDOM_SIZE) <= 0) + goto err; + + /* Do the message type and length last */ + d=p= &(buf[4]); + + /* version indicates the negotiated version: for example from + * an SSLv2/v3 compatible client hello). The client_version + * field is the maximum version we permit and it is also + * used in RSA encrypted premaster secrets. Some servers can + * choke if we initially report a higher version then + * renegotiate to a lower one in the premaster secret. This + * didn't happen with TLS 1.0 as most servers supported it + * but it can with TLS 1.1 or later if the server only supports + * 1.0. + * + * Possible scenario with previous logic: + * 1. Client hello indicates TLS 1.2 + * 2. Server hello says TLS 1.0 + * 3. RSA encrypted premaster secret uses 1.2. + * 4. Handhaked proceeds using TLS 1.0. + * 5. Server sends hello request to renegotiate. + * 6. Client hello indicates TLS v1.0 as we now + * know that is maximum server supports. + * 7. Server chokes on RSA encrypted premaster secret + * containing version 1.0. + * + * For interoperability it should be OK to always use the + * maximum version we support in client hello and then rely + * on the checking of version to ensure the servers isn't + * being inconsistent: for example initially negotiating with + * TLS 1.0 and renegotiating with TLS 1.2. We do this by using + * client_version in client hello and not resetting it to + * the negotiated version. + */ +#if 0 + *(p++)=s->version>>8; + *(p++)=s->version&0xff; + s->client_version=s->version; +#else + *(p++)=s->client_version>>8; + *(p++)=s->client_version&0xff; +#endif + + /* Random stuff */ + memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE); + p+=SSL3_RANDOM_SIZE; + + /* Session ID */ + if (s->new_session) + i=0; + else + i=s->session->session_id_length; + *(p++)=i; + if (i != 0) + { + if (i > (int)sizeof(s->session->session_id)) + { + SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); + goto err; + } + memcpy(p,s->session->session_id,i); + p+=i; + } + + /* Ciphers supported */ + i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0); + if (i == 0) + { + SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE); + goto err; + } +#ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH + /* Some servers hang if client hello > 256 bytes + * as hack workaround chop number of supported ciphers + * to keep it well below this if we use TLS v1.2 + */ + if (TLS1_get_version(s) >= TLS1_2_VERSION + && i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH) + i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1; +#endif + s2n(i,p); + p+=i; + + /* COMPRESSION */ +#ifdef OPENSSL_NO_COMP + *(p++)=1; +#else + + if ((s->options & SSL_OP_NO_COMPRESSION) + || !s->ctx->comp_methods) + j=0; + else + j=sk_SSL_COMP_num(s->ctx->comp_methods); + *(p++)=1+j; + for (i=0; ictx->comp_methods,i); + *(p++)=comp->id; + } +#endif + *(p++)=0; /* Add the NULL method */ + +#ifndef OPENSSL_NO_TLSEXT + /* TLS extensions*/ + if (ssl_prepare_clienthello_tlsext(s) <= 0) + { + SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_CLIENTHELLO_TLSEXT); + goto err; + } + if ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL) + { + SSLerr(SSL_F_SSL3_CLIENT_HELLO,ERR_R_INTERNAL_ERROR); + goto err; + } +#endif + + l=(p-d); + d=buf; + *(d++)=SSL3_MT_CLIENT_HELLO; + l2n3(l,d); + + s->state=SSL3_ST_CW_CLNT_HELLO_B; + /* number of bytes to write */ + s->init_num=p-buf; + s->init_off=0; + } + + /* SSL3_ST_CW_CLNT_HELLO_B */ + return(ssl3_do_write(s,SSL3_RT_HANDSHAKE)); +err: + return(-1); + } +",0,"int ssl3_client_hello(SSL *s) + { + unsigned char *buf; + unsigned char *p,*d; + int i; + unsigned long l; +#ifndef OPENSSL_NO_COMP + int j; + SSL_COMP *comp; +#endif + + buf=(unsigned char *)s->init_buf->data; + if (s->state == SSL3_ST_CW_CLNT_HELLO_A) + { + SSL_SESSION *sess = s->session; + if ((sess == NULL) || + (sess->ssl_version != s->version) || +#ifdef OPENSSL_NO_TLSEXT + !sess->session_id_length || +#else + (!sess->session_id_length && !sess->tlsext_tick) || +#endif + (sess->not_resumable)) + { + if (!ssl_get_new_session(s,0)) + goto err; + } + /* else use the pre-loaded session */ + + p=s->s3->client_random; + + if (ssl_fill_hello_random(s, 0, p, SSL3_RANDOM_SIZE) <= 0) + goto err; + + /* Do the message type and length last */ + d=p= &(buf[4]); + + /* version indicates the negotiated version: for example from + * an SSLv2/v3 compatible client hello). The client_version + * field is the maximum version we permit and it is also + * used in RSA encrypted premaster secrets. Some servers can + * choke if we initially report a higher version then + * renegotiate to a lower one in the premaster secret. This + * didn't happen with TLS 1.0 as most servers supported it + * but it can with TLS 1.1 or later if the server only supports + * 1.0. + * + * Possible scenario with previous logic: + * 1. Client hello indicates TLS 1.2 + * 2. Server hello says TLS 1.0 + * 3. RSA encrypted premaster secret uses 1.2. + * 4. Handhaked proceeds using TLS 1.0. + * 5. Server sends hello request to renegotiate. + * 6. Client hello indicates TLS v1.0 as we now + * know that is maximum server supports. + * 7. Server chokes on RSA encrypted premaster secret + * containing version 1.0. + * + * For interoperability it should be OK to always use the + * maximum version we support in client hello and then rely + * on the checking of version to ensure the servers isn't + * being inconsistent: for example initially negotiating with + * TLS 1.0 and renegotiating with TLS 1.2. We do this by using + * client_version in client hello and not resetting it to + * the negotiated version. + */ +#if 0 + *(p++)=s->version>>8; + *(p++)=s->version&0xff; + s->client_version=s->version; +#else + *(p++)=s->client_version>>8; + *(p++)=s->client_version&0xff; +#endif + + /* Random stuff */ + memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE); + p+=SSL3_RANDOM_SIZE; + + /* Session ID */ + if (s->new_session) + i=0; + else + i=s->session->session_id_length; + *(p++)=i; + if (i != 0) + { + if (i > (int)sizeof(s->session->session_id)) + { + SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); + goto err; + } + memcpy(p,s->session->session_id,i); + p+=i; + } + + /* Ciphers supported */ + i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0); + if (i == 0) + { + SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE); + goto err; + } +#ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH + /* Some servers hang if client hello > 256 bytes + * as hack workaround chop number of supported ciphers + * to keep it well below this if we use TLS v1.2 + */ + if (TLS1_get_version(s) >= TLS1_2_VERSION + && i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH) + i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1; +#endif + s2n(i,p); + p+=i; + + /* COMPRESSION */ +#ifdef OPENSSL_NO_COMP + *(p++)=1; +#else + + if ((s->options & SSL_OP_NO_COMPRESSION) + || !s->ctx->comp_methods) + j=0; + else + j=sk_SSL_COMP_num(s->ctx->comp_methods); + *(p++)=1+j; + for (i=0; ictx->comp_methods,i); + *(p++)=comp->id; + } +#endif + *(p++)=0; /* Add the NULL method */ + +#ifndef OPENSSL_NO_TLSEXT + /* TLS extensions*/ + if (ssl_prepare_clienthello_tlsext(s) <= 0) + { + SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_CLIENTHELLO_TLSEXT); + goto err; + } + if ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL) + { + SSLerr(SSL_F_SSL3_CLIENT_HELLO,ERR_R_INTERNAL_ERROR); + goto err; + } +#endif + + l=(p-d); + d=buf; + *(d++)=SSL3_MT_CLIENT_HELLO; + l2n3(l,d); + + s->state=SSL3_ST_CW_CLNT_HELLO_B; + /* number of bytes to write */ + s->init_num=p-buf; + s->init_off=0; + } + + /* SSL3_ST_CW_CLNT_HELLO_B */ + return(ssl3_do_write(s,SSL3_RT_HANDSHAKE)); +err: + return(-1); + } +","@@ -954,6 +954,15 @@ int ssl3_get_server_hello(SSL *s) + SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED); + goto f_err; + } ++#ifndef OPENSSL_NO_SRP ++ if (((c->algorithm_mkey & SSL_kSRP) || (c->algorithm_auth & SSL_aSRP)) && ++ !(s->srp_ctx.srp_Mask & SSL_kSRP)) ++ { ++ al=SSL_AD_ILLEGAL_PARAMETER; ++ SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED); ++ goto f_err; ++ } ++#endif /* OPENSSL_NO_SRP */ + p+=ssl_put_cipher_by_char(s,NULL,NULL); + + sk=ssl_get_ciphers_by_id(s);",1387,1718,2048 +17926,"__switch_to(struct task_struct *prev_p, struct task_struct *next_p) +{ + struct thread_struct *prev = &prev_p->thread; + struct thread_struct *next = &next_p->thread; + int cpu = smp_processor_id(); + struct tss_struct *tss = &per_cpu(init_tss, cpu); + unsigned fsindex, gsindex; + fpu_switch_t fpu; + + fpu = switch_fpu_prepare(prev_p, next_p, cpu); + + /* + * Reload esp0, LDT and the page table pointer: + */ + load_sp0(tss, next); + + /* + * Switch DS and ES. + * This won't pick up thread selector changes, but I guess that is ok. + */ + savesegment(es, prev->es); + if (unlikely(next->es | prev->es)) + loadsegment(es, next->es); + savesegment(ds, prev->ds); + if (unlikely(next->ds | prev->ds)) + loadsegment(ds, next->ds); + /* We must save %fs and %gs before load_TLS() because + * %fs and %gs may be cleared by load_TLS(). + * + * (e.g. xen_load_tls()) + */ + savesegment(fs, fsindex); + savesegment(gs, gsindex); + + load_TLS(next, cpu); + + /* + * Leave lazy mode, flushing any hypercalls made here. + * This must be done before restoring TLS segments so + * the GDT and LDT are properly updated, and must be + * done before math_state_restore, so the TS bit is up + * to date. + */ + arch_end_context_switch(next_p); + + /* + * Switch FS and GS. + * + * Segment register != 0 always requires a reload. Also + * reload when it has changed. When prev process used 64bit + * base always reload to avoid an information leak. + */ + if (unlikely(fsindex | next->fsindex | prev->fs)) { + loadsegment(fs, next->fsindex); + /* + * Check if the user used a selector != 0; if yes + * clear 64bit base, since overloaded base is always + * mapped to the Null selector + */ + if (fsindex) + prev->fs = 0; + } + /* when next process has a 64bit base use it */ + if (next->fs) + wrmsrl(MSR_FS_BASE, next->fs); + prev->fsindex = fsindex; + + if (unlikely(gsindex | next->gsindex | prev->gs)) { + load_gs_index(next->gsindex); + if (gsindex) + prev->gs = 0; + } + if (next->gs) + wrmsrl(MSR_KERNEL_GS_BASE, next->gs); + prev->gsindex = gsindex; + + switch_fpu_finish(next_p, fpu); + + /* + * Switch the PDA and FPU contexts. + */ + prev->usersp = this_cpu_read(old_rsp); + this_cpu_write(old_rsp, next->usersp); + this_cpu_write(current_task, next_p); + + /* + * If it were not for PREEMPT_ACTIVE we could guarantee that the + * preempt_count of all tasks was equal here and this would not be + * needed. + */ + task_thread_info(prev_p)->saved_preempt_count = this_cpu_read(__preempt_count); + this_cpu_write(__preempt_count, task_thread_info(next_p)->saved_preempt_count); + + this_cpu_write(kernel_stack, + (unsigned long)task_stack_page(next_p) + + THREAD_SIZE - KERNEL_STACK_OFFSET); + + /* + * Now maybe reload the debug registers and handle I/O bitmaps + */ + if (unlikely(task_thread_info(next_p)->flags & _TIF_WORK_CTXSW_NEXT || + task_thread_info(prev_p)->flags & _TIF_WORK_CTXSW_PREV)) + __switch_to_xtra(prev_p, next_p, tss); + + return prev_p; +} +",1,"__switch_to(struct task_struct *prev_p, struct task_struct *next_p) +{ + struct thread_struct *prev = &prev_p->thread; + struct thread_struct *next = &next_p->thread; + int cpu = smp_processor_id(); + struct tss_struct *tss = &per_cpu(init_tss, cpu); + unsigned fsindex, gsindex; + fpu_switch_t fpu; + + fpu = switch_fpu_prepare(prev_p, next_p, cpu); + + /* Reload esp0 and ss1. */ + load_sp0(tss, next); + + /* We must save %fs and %gs before load_TLS() because + * %fs and %gs may be cleared by load_TLS(). + * + * (e.g. xen_load_tls()) + */ + savesegment(fs, fsindex); + savesegment(gs, gsindex); + + /* + * Load TLS before restoring any segments so that segment loads + * reference the correct GDT entries. + */ + load_TLS(next, cpu); + + /* + * Leave lazy mode, flushing any hypercalls made here. This + * must be done after loading TLS entries in the GDT but before + * loading segments that might reference them, and and it must + * be done before math_state_restore, so the TS bit is up to + * date. + */ + arch_end_context_switch(next_p); + + /* Switch DS and ES. + * + * Reading them only returns the selectors, but writing them (if + * nonzero) loads the full descriptor from the GDT or LDT. The + * LDT for next is loaded in switch_mm, and the GDT is loaded + * above. + * + * We therefore need to write new values to the segment + * registers on every context switch unless both the new and old + * values are zero. + * + * Note that we don't need to do anything for CS and SS, as + * those are saved and restored as part of pt_regs. + */ + savesegment(es, prev->es); + if (unlikely(next->es | prev->es)) + loadsegment(es, next->es); + + savesegment(ds, prev->ds); + if (unlikely(next->ds | prev->ds)) + loadsegment(ds, next->ds); + + /* + * Switch FS and GS. + * + * These are even more complicated than FS and GS: they have + * 64-bit bases are that controlled by arch_prctl. Those bases + * only differ from the values in the GDT or LDT if the selector + * is 0. + * + * Loading the segment register resets the hidden base part of + * the register to 0 or the value from the GDT / LDT. If the + * next base address zero, writing 0 to the segment register is + * much faster than using wrmsr to explicitly zero the base. + * + * The thread_struct.fs and thread_struct.gs values are 0 + * if the fs and gs bases respectively are not overridden + * from the values implied by fsindex and gsindex. They + * are nonzero, and store the nonzero base addresses, if + * the bases are overridden. + * + * (fs != 0 && fsindex != 0) || (gs != 0 && gsindex != 0) should + * be impossible. + * + * Therefore we need to reload the segment registers if either + * the old or new selector is nonzero, and we need to override + * the base address if next thread expects it to be overridden. + * + * This code is unnecessarily slow in the case where the old and + * new indexes are zero and the new base is nonzero -- it will + * unnecessarily write 0 to the selector before writing the new + * base address. + * + * Note: This all depends on arch_prctl being the only way that + * user code can override the segment base. Once wrfsbase and + * wrgsbase are enabled, most of this code will need to change. + */ + if (unlikely(fsindex | next->fsindex | prev->fs)) { + loadsegment(fs, next->fsindex); + + /* + * If user code wrote a nonzero value to FS, then it also + * cleared the overridden base address. + * + * XXX: if user code wrote 0 to FS and cleared the base + * address itself, we won't notice and we'll incorrectly + * restore the prior base address next time we reschdule + * the process. + */ + if (fsindex) + prev->fs = 0; + } + if (next->fs) + wrmsrl(MSR_FS_BASE, next->fs); + prev->fsindex = fsindex; + + if (unlikely(gsindex | next->gsindex | prev->gs)) { + load_gs_index(next->gsindex); + + /* This works (and fails) the same way as fsindex above. */ + if (gsindex) + prev->gs = 0; + } + if (next->gs) + wrmsrl(MSR_KERNEL_GS_BASE, next->gs); + prev->gsindex = gsindex; + + switch_fpu_finish(next_p, fpu); + + /* + * Switch the PDA and FPU contexts. + */ + prev->usersp = this_cpu_read(old_rsp); + this_cpu_write(old_rsp, next->usersp); + this_cpu_write(current_task, next_p); + + /* + * If it were not for PREEMPT_ACTIVE we could guarantee that the + * preempt_count of all tasks was equal here and this would not be + * needed. + */ + task_thread_info(prev_p)->saved_preempt_count = this_cpu_read(__preempt_count); + this_cpu_write(__preempt_count, task_thread_info(next_p)->saved_preempt_count); + + this_cpu_write(kernel_stack, + (unsigned long)task_stack_page(next_p) + + THREAD_SIZE - KERNEL_STACK_OFFSET); + + /* + * Now maybe reload the debug registers and handle I/O bitmaps + */ + if (unlikely(task_thread_info(next_p)->flags & _TIF_WORK_CTXSW_NEXT || + task_thread_info(prev_p)->flags & _TIF_WORK_CTXSW_PREV)) + __switch_to_xtra(prev_p, next_p, tss); + + return prev_p; +} +","@@ -283,24 +283,9 @@ __switch_to(struct task_struct *prev_p, struct task_struct *next_p) + + fpu = switch_fpu_prepare(prev_p, next_p, cpu); + +- /* +- * Reload esp0, LDT and the page table pointer: +- */ ++ /* Reload esp0 and ss1. */ + load_sp0(tss, next); + +- /* +- * Switch DS and ES. +- * This won't pick up thread selector changes, but I guess that is ok. +- */ +- savesegment(es, prev->es); +- if (unlikely(next->es | prev->es)) +- loadsegment(es, next->es); +- +- savesegment(ds, prev->ds); +- if (unlikely(next->ds | prev->ds)) +- loadsegment(ds, next->ds); +- +- + /* We must save %fs and %gs before load_TLS() because + * %fs and %gs may be cleared by load_TLS(). + * +@@ -309,41 +294,101 @@ __switch_to(struct task_struct *prev_p, struct task_struct *next_p) + savesegment(fs, fsindex); + savesegment(gs, gsindex); + ++ /* ++ * Load TLS before restoring any segments so that segment loads ++ * reference the correct GDT entries. ++ */ + load_TLS(next, cpu); + + /* +- * Leave lazy mode, flushing any hypercalls made here. +- * This must be done before restoring TLS segments so +- * the GDT and LDT are properly updated, and must be +- * done before math_state_restore, so the TS bit is up +- * to date. ++ * Leave lazy mode, flushing any hypercalls made here. This ++ * must be done after loading TLS entries in the GDT but before ++ * loading segments that might reference them, and and it must ++ * be done before math_state_restore, so the TS bit is up to ++ * date. + */ + arch_end_context_switch(next_p); + ++ /* Switch DS and ES. ++ * ++ * Reading them only returns the selectors, but writing them (if ++ * nonzero) loads the full descriptor from the GDT or LDT. The ++ * LDT for next is loaded in switch_mm, and the GDT is loaded ++ * above. ++ * ++ * We therefore need to write new values to the segment ++ * registers on every context switch unless both the new and old ++ * values are zero. ++ * ++ * Note that we don't need to do anything for CS and SS, as ++ * those are saved and restored as part of pt_regs. ++ */ ++ savesegment(es, prev->es); ++ if (unlikely(next->es | prev->es)) ++ loadsegment(es, next->es); ++ ++ savesegment(ds, prev->ds); ++ if (unlikely(next->ds | prev->ds)) ++ loadsegment(ds, next->ds); ++ + /* + * Switch FS and GS. + * +- * Segment register != 0 always requires a reload. Also +- * reload when it has changed. When prev process used 64bit +- * base always reload to avoid an information leak. ++ * These are even more complicated than FS and GS: they have ++ * 64-bit bases are that controlled by arch_prctl. Those bases ++ * only differ from the values in the GDT or LDT if the selector ++ * is 0. ++ * ++ * Loading the segment register resets the hidden base part of ++ * the register to 0 or the value from the GDT / LDT. If the ++ * next base address zero, writing 0 to the segment register is ++ * much faster than using wrmsr to explicitly zero the base. ++ * ++ * The thread_struct.fs and thread_struct.gs values are 0 ++ * if the fs and gs bases respectively are not overridden ++ * from the values implied by fsindex and gsindex. They ++ * are nonzero, and store the nonzero base addresses, if ++ * the bases are overridden. ++ * ++ * (fs != 0 && fsindex != 0) || (gs != 0 && gsindex != 0) should ++ * be impossible. ++ * ++ * Therefore we need to reload the segment registers if either ++ * the old or new selector is nonzero, and we need to override ++ * the base address if next thread expects it to be overridden. ++ * ++ * This code is unnecessarily slow in the case where the old and ++ * new indexes are zero and the new base is nonzero -- it will ++ * unnecessarily write 0 to the selector before writing the new ++ * base address. ++ * ++ * Note: This all depends on arch_prctl being the only way that ++ * user code can override the segment base. Once wrfsbase and ++ * wrgsbase are enabled, most of this code will need to change. + */ + if (unlikely(fsindex | next->fsindex | prev->fs)) { + loadsegment(fs, next->fsindex); ++ + /* +- * Check if the user used a selector != 0; if yes +- * clear 64bit base, since overloaded base is always +- * mapped to the Null selector ++ * If user code wrote a nonzero value to FS, then it also ++ * cleared the overridden base address. ++ * ++ * XXX: if user code wrote 0 to FS and cleared the base ++ * address itself, we won't notice and we'll incorrectly ++ * restore the prior base address next time we reschdule ++ * the process. + */ + if (fsindex) + prev->fs = 0; + } +- /* when next process has a 64bit base use it */ + if (next->fs) + wrmsrl(MSR_FS_BASE, next->fs); + prev->fsindex = fsindex; + + if (unlikely(gsindex | next->gsindex | prev->gs)) { + load_gs_index(next->gsindex); ++ ++ /* This works (and fails) the same way as fsindex above. */ + if (gsindex) + prev->gs = 0; + }",866,1197,2048 +18254,"static int ocfs2_dio_get_block(struct inode *inode, sector_t iblock, + struct buffer_head *bh_result, int create) + { + struct ocfs2_super *osb = OCFS2_SB(inode->i_sb); + struct ocfs2_inode_info *oi = OCFS2_I(inode); + struct ocfs2_write_ctxt *wc; + struct ocfs2_write_cluster_desc *desc = NULL; + struct ocfs2_dio_write_ctxt *dwc = NULL; + struct buffer_head *di_bh = NULL; + u64 p_blkno; + loff_t pos = iblock << inode->i_sb->s_blocksize_bits; + unsigned len, total_len = bh_result->b_size; + int ret = 0, first_get_block = 0; + + len = osb->s_clustersize - (pos & (osb->s_clustersize - 1)); + len = min(total_len, len); + + mlog(0, ""get block of %lu at %llu:%u req %u\n"", + inode->i_ino, pos, len, total_len); + + /* + * Because we need to change file size in ocfs2_dio_end_io_write(), or + * we may need to add it to orphan dir. So can not fall to fast path + * while file size will be changed. + */ + if (pos + total_len <= i_size_read(inode)) { + down_read(&oi->ip_alloc_sem); + /* This is the fast path for re-write. */ + ret = ocfs2_get_block(inode, iblock, bh_result, create); + up_read(&oi->ip_alloc_sem); + + if (buffer_mapped(bh_result) && + !buffer_new(bh_result) && + ret == 0) + goto out; + + /* Clear state set by ocfs2_get_block. */ + bh_result->b_state = 0; + } + + dwc = ocfs2_dio_alloc_write_ctx(bh_result, &first_get_block); + if (unlikely(dwc == NULL)) { + ret = -ENOMEM; + mlog_errno(ret); + goto out; + } + + if (ocfs2_clusters_for_bytes(inode->i_sb, pos + total_len) > + ocfs2_clusters_for_bytes(inode->i_sb, i_size_read(inode)) && + !dwc->dw_orphaned) { + /* + * when we are going to alloc extents beyond file size, add the + * inode to orphan dir, so we can recall those spaces when + * system crashed during write. + */ + ret = ocfs2_add_inode_to_orphan(osb, inode); + if (ret < 0) { + mlog_errno(ret); + goto out; + } + dwc->dw_orphaned = 1; + } + + ret = ocfs2_inode_lock(inode, &di_bh, 1); + if (ret) { + mlog_errno(ret); + goto out; + } + + down_write(&oi->ip_alloc_sem); + + if (first_get_block) { + if (ocfs2_sparse_alloc(OCFS2_SB(inode->i_sb))) + ret = ocfs2_zero_tail(inode, di_bh, pos); + else + ret = ocfs2_expand_nonsparse_inode(inode, di_bh, pos, + total_len, NULL); + if (ret < 0) { + mlog_errno(ret); + goto unlock; + } + } + + ret = ocfs2_write_begin_nolock(inode->i_mapping, pos, len, + OCFS2_WRITE_DIRECT, NULL, + (void **)&wc, di_bh, NULL); + if (ret) { + mlog_errno(ret); + goto unlock; + } + + desc = &wc->w_desc[0]; + + p_blkno = ocfs2_clusters_to_blocks(inode->i_sb, desc->c_phys); + BUG_ON(p_blkno == 0); + p_blkno += iblock & (u64)(ocfs2_clusters_to_blocks(inode->i_sb, 1) - 1); + + map_bh(bh_result, inode->i_sb, p_blkno); + bh_result->b_size = len; + if (desc->c_needs_zero) + set_buffer_new(bh_result); + + /* May sleep in end_io. It should not happen in a irq context. So defer + * it to dio work queue. */ + set_buffer_defer_completion(bh_result); + + if (!list_empty(&wc->w_unwritten_list)) { + struct ocfs2_unwritten_extent *ue = NULL; + + ue = list_first_entry(&wc->w_unwritten_list, + struct ocfs2_unwritten_extent, + ue_node); + BUG_ON(ue->ue_cpos != desc->c_cpos); + /* The physical address may be 0, fill it. */ + ue->ue_phys = desc->c_phys; + + list_splice_tail_init(&wc->w_unwritten_list, &dwc->dw_zero_list); + dwc->dw_zero_count++; + } + + ret = ocfs2_write_end_nolock(inode->i_mapping, pos, len, len, wc); + BUG_ON(ret != len); + ret = 0; +unlock: + up_write(&oi->ip_alloc_sem); + ocfs2_inode_unlock(inode, 1); + brelse(di_bh); +out: + if (ret < 0) + ret = -EIO; + return ret; +} +",1,"static int ocfs2_dio_get_block(struct inode *inode, sector_t iblock, +static int ocfs2_dio_wr_get_block(struct inode *inode, sector_t iblock, + struct buffer_head *bh_result, int create) + { + struct ocfs2_super *osb = OCFS2_SB(inode->i_sb); + struct ocfs2_inode_info *oi = OCFS2_I(inode); + struct ocfs2_write_ctxt *wc; + struct ocfs2_write_cluster_desc *desc = NULL; + struct ocfs2_dio_write_ctxt *dwc = NULL; + struct buffer_head *di_bh = NULL; + u64 p_blkno; + loff_t pos = iblock << inode->i_sb->s_blocksize_bits; + unsigned len, total_len = bh_result->b_size; + int ret = 0, first_get_block = 0; + + len = osb->s_clustersize - (pos & (osb->s_clustersize - 1)); + len = min(total_len, len); + + mlog(0, ""get block of %lu at %llu:%u req %u\n"", + inode->i_ino, pos, len, total_len); + + /* + * Because we need to change file size in ocfs2_dio_end_io_write(), or + * we may need to add it to orphan dir. So can not fall to fast path + * while file size will be changed. + */ + if (pos + total_len <= i_size_read(inode)) { + + /* This is the fast path for re-write. */ + ret = ocfs2_lock_get_block(inode, iblock, bh_result, create); + if (buffer_mapped(bh_result) && + !buffer_new(bh_result) && + ret == 0) + goto out; + + /* Clear state set by ocfs2_get_block. */ + bh_result->b_state = 0; + } + + dwc = ocfs2_dio_alloc_write_ctx(bh_result, &first_get_block); + if (unlikely(dwc == NULL)) { + ret = -ENOMEM; + mlog_errno(ret); + goto out; + } + + if (ocfs2_clusters_for_bytes(inode->i_sb, pos + total_len) > + ocfs2_clusters_for_bytes(inode->i_sb, i_size_read(inode)) && + !dwc->dw_orphaned) { + /* + * when we are going to alloc extents beyond file size, add the + * inode to orphan dir, so we can recall those spaces when + * system crashed during write. + */ + ret = ocfs2_add_inode_to_orphan(osb, inode); + if (ret < 0) { + mlog_errno(ret); + goto out; + } + dwc->dw_orphaned = 1; + } + + ret = ocfs2_inode_lock(inode, &di_bh, 1); + if (ret) { + mlog_errno(ret); + goto out; + } + + down_write(&oi->ip_alloc_sem); + + if (first_get_block) { + if (ocfs2_sparse_alloc(OCFS2_SB(inode->i_sb))) + ret = ocfs2_zero_tail(inode, di_bh, pos); + else + ret = ocfs2_expand_nonsparse_inode(inode, di_bh, pos, + total_len, NULL); + if (ret < 0) { + mlog_errno(ret); + goto unlock; + } + } + + ret = ocfs2_write_begin_nolock(inode->i_mapping, pos, len, + OCFS2_WRITE_DIRECT, NULL, + (void **)&wc, di_bh, NULL); + if (ret) { + mlog_errno(ret); + goto unlock; + } + + desc = &wc->w_desc[0]; + + p_blkno = ocfs2_clusters_to_blocks(inode->i_sb, desc->c_phys); + BUG_ON(p_blkno == 0); + p_blkno += iblock & (u64)(ocfs2_clusters_to_blocks(inode->i_sb, 1) - 1); + + map_bh(bh_result, inode->i_sb, p_blkno); + bh_result->b_size = len; + if (desc->c_needs_zero) + set_buffer_new(bh_result); + + /* May sleep in end_io. It should not happen in a irq context. So defer + * it to dio work queue. */ + set_buffer_defer_completion(bh_result); + + if (!list_empty(&wc->w_unwritten_list)) { + struct ocfs2_unwritten_extent *ue = NULL; + + ue = list_first_entry(&wc->w_unwritten_list, + struct ocfs2_unwritten_extent, + ue_node); + BUG_ON(ue->ue_cpos != desc->c_cpos); + /* The physical address may be 0, fill it. */ + ue->ue_phys = desc->c_phys; + + list_splice_tail_init(&wc->w_unwritten_list, &dwc->dw_zero_list); + dwc->dw_zero_count++; + } + + ret = ocfs2_write_end_nolock(inode->i_mapping, pos, len, len, wc); + BUG_ON(ret != len); + ret = 0; +unlock: + up_write(&oi->ip_alloc_sem); + ocfs2_inode_unlock(inode, 1); + brelse(di_bh); +out: + if (ret < 0) + ret = -EIO; + return ret; +} +","@@ -134,6 +134,19 @@ static int ocfs2_symlink_get_block(struct inode *inode, sector_t iblock, + return err; + } + ++static int ocfs2_lock_get_block(struct inode *inode, sector_t iblock, ++ struct buffer_head *bh_result, int create) ++{ ++ int ret = 0; ++ struct ocfs2_inode_info *oi = OCFS2_I(inode); ++ ++ down_read(&oi->ip_alloc_sem); ++ ret = ocfs2_get_block(inode, iblock, bh_result, create); ++ up_read(&oi->ip_alloc_sem); ++ ++ return ret; ++} ++ + int ocfs2_get_block(struct inode *inode, sector_t iblock, + struct buffer_head *bh_result, int create) + { +@@ -2128,7 +2141,7 @@ static void ocfs2_dio_free_write_ctx(struct inode *inode, + * called like this: dio->get_blocks(dio->inode, fs_startblk, + * fs_count, map_bh, dio->rw == WRITE); + */ +-static int ocfs2_dio_get_block(struct inode *inode, sector_t iblock, ++static int ocfs2_dio_wr_get_block(struct inode *inode, sector_t iblock, + struct buffer_head *bh_result, int create) + { + struct ocfs2_super *osb = OCFS2_SB(inode->i_sb); +@@ -2154,12 +2167,9 @@ static int ocfs2_dio_get_block(struct inode *inode, sector_t iblock, + * while file size will be changed. + */ + if (pos + total_len <= i_size_read(inode)) { +- down_read(&oi->ip_alloc_sem); +- /* This is the fast path for re-write. */ +- ret = ocfs2_get_block(inode, iblock, bh_result, create); +- +- up_read(&oi->ip_alloc_sem); + ++ /* This is the fast path for re-write. */ ++ ret = ocfs2_lock_get_block(inode, iblock, bh_result, create); + if (buffer_mapped(bh_result) && + !buffer_new(bh_result) && + ret == 0) +@@ -2424,9 +2434,9 @@ static ssize_t ocfs2_direct_IO(struct kiocb *iocb, struct iov_iter *iter) + return 0; + + if (iov_iter_rw(iter) == READ) +- get_block = ocfs2_get_block; ++ get_block = ocfs2_lock_get_block; + else +- get_block = ocfs2_dio_get_block; ++ get_block = ocfs2_dio_wr_get_block; + + return __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev, + iter, get_block,",1149,1480,2048 +2913,"static av_always_inline void mc_dir_part(H264Context *h, Picture *pic, + int n, int square, int height, + int delta, int list, + uint8_t *dest_y, uint8_t *dest_cb, + uint8_t *dest_cr, + int src_x_offset, int src_y_offset, + qpel_mc_func *qpix_op, + h264_chroma_mc_func chroma_op, + int pixel_shift, int chroma_idc) +{ + const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8; + int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8; + const int luma_xy = (mx & 3) + ((my & 3) << 2); + ptrdiff_t offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize; + uint8_t *src_y = pic->f.data[0] + offset; + uint8_t *src_cb, *src_cr; + int extra_width = 0; + int extra_height = 0; + int emu = 0; + const int full_mx = mx >> 2; + const int full_my = my >> 2; + const int pic_width = 16 * h->mb_width; + const int pic_height = 16 * h->mb_height >> MB_FIELD(h); + int ysh; + + if (mx & 7) + extra_width -= 3; + if (my & 7) + extra_height -= 3; + + if (full_mx < 0 - extra_width || + full_my < 0 - extra_height || + full_mx + 16 /*FIXME*/ > pic_width + extra_width || + full_my + 16 /*FIXME*/ > pic_height + extra_height) { + h->vdsp.emulated_edge_mc(h->edge_emu_buffer, h->mb_linesize, + src_y - (2 << pixel_shift) - 2 * h->mb_linesize, + h->mb_linesize, + 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2, + full_my - 2, pic_width, pic_height); + src_y = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize; + emu = 1; + } + + qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps? + if (!square) + qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize); + + if (CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY) + return; + + if (chroma_idc == 3 /* yuv444 */) { + src_cb = pic->f.data[1] + offset; + if (emu) { + h->vdsp.emulated_edge_mc(h->edge_emu_buffer, h->mb_linesize, + src_cb - (2 << pixel_shift) - 2 * h->mb_linesize, + h->mb_linesize, + 16 + 5, 16 + 5 /*FIXME*/, + full_mx - 2, full_my - 2, + pic_width, pic_height); + src_cb = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize; + } + qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps? + if (!square) + qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize); + + src_cr = pic->f.data[2] + offset; + if (emu) { + h->vdsp.emulated_edge_mc(h->edge_emu_buffer, h->mb_linesize, + src_cr - (2 << pixel_shift) - 2 * h->mb_linesize, + h->mb_linesize, + 16 + 5, 16 + 5 /*FIXME*/, + full_mx - 2, full_my - 2, + pic_width, pic_height); + src_cr = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize; + } + qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps? + if (!square) + qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize); + return; + } + + ysh = 3 - (chroma_idc == 2 /* yuv422 */); + if (chroma_idc == 1 /* yuv420 */ && MB_FIELD(h)) { + my += 2 * ((h->mb_y & 1) - (pic->reference - 1)); + emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1); + } + + src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) + + (my >> ysh) * h->mb_uvlinesize; + src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) + + (my >> ysh) * h->mb_uvlinesize; + + if (emu) { + h->vdsp.emulated_edge_mc(h->edge_emu_buffer, h->mb_uvlinesize, src_cb, h->mb_uvlinesize, + 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh), + pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */)); + src_cb = h->edge_emu_buffer; + } + chroma_op(dest_cb, src_cb, h->mb_uvlinesize, + height >> (chroma_idc == 1 /* yuv420 */), + mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7); + + if (emu) { + h->vdsp.emulated_edge_mc(h->edge_emu_buffer, h->mb_uvlinesize, src_cr, h->mb_uvlinesize, + 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh), + pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */)); + src_cr = h->edge_emu_buffer; + } + chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */), + mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7); +} +",0,"static av_always_inline void mc_dir_part(H264Context *h, Picture *pic, + int n, int square, int height, + int delta, int list, + uint8_t *dest_y, uint8_t *dest_cb, + uint8_t *dest_cr, + int src_x_offset, int src_y_offset, + qpel_mc_func *qpix_op, + h264_chroma_mc_func chroma_op, + int pixel_shift, int chroma_idc) +{ + const int mx = h->mv_cache[list][scan8[n]][0] + src_x_offset * 8; + int my = h->mv_cache[list][scan8[n]][1] + src_y_offset * 8; + const int luma_xy = (mx & 3) + ((my & 3) << 2); + ptrdiff_t offset = ((mx >> 2) << pixel_shift) + (my >> 2) * h->mb_linesize; + uint8_t *src_y = pic->f.data[0] + offset; + uint8_t *src_cb, *src_cr; + int extra_width = 0; + int extra_height = 0; + int emu = 0; + const int full_mx = mx >> 2; + const int full_my = my >> 2; + const int pic_width = 16 * h->mb_width; + const int pic_height = 16 * h->mb_height >> MB_FIELD(h); + int ysh; + + if (mx & 7) + extra_width -= 3; + if (my & 7) + extra_height -= 3; + + if (full_mx < 0 - extra_width || + full_my < 0 - extra_height || + full_mx + 16 /*FIXME*/ > pic_width + extra_width || + full_my + 16 /*FIXME*/ > pic_height + extra_height) { + h->vdsp.emulated_edge_mc(h->edge_emu_buffer, h->mb_linesize, + src_y - (2 << pixel_shift) - 2 * h->mb_linesize, + h->mb_linesize, + 16 + 5, 16 + 5 /*FIXME*/, full_mx - 2, + full_my - 2, pic_width, pic_height); + src_y = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize; + emu = 1; + } + + qpix_op[luma_xy](dest_y, src_y, h->mb_linesize); // FIXME try variable height perhaps? + if (!square) + qpix_op[luma_xy](dest_y + delta, src_y + delta, h->mb_linesize); + + if (CONFIG_GRAY && h->flags & CODEC_FLAG_GRAY) + return; + + if (chroma_idc == 3 /* yuv444 */) { + src_cb = pic->f.data[1] + offset; + if (emu) { + h->vdsp.emulated_edge_mc(h->edge_emu_buffer, h->mb_linesize, + src_cb - (2 << pixel_shift) - 2 * h->mb_linesize, + h->mb_linesize, + 16 + 5, 16 + 5 /*FIXME*/, + full_mx - 2, full_my - 2, + pic_width, pic_height); + src_cb = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize; + } + qpix_op[luma_xy](dest_cb, src_cb, h->mb_linesize); // FIXME try variable height perhaps? + if (!square) + qpix_op[luma_xy](dest_cb + delta, src_cb + delta, h->mb_linesize); + + src_cr = pic->f.data[2] + offset; + if (emu) { + h->vdsp.emulated_edge_mc(h->edge_emu_buffer, h->mb_linesize, + src_cr - (2 << pixel_shift) - 2 * h->mb_linesize, + h->mb_linesize, + 16 + 5, 16 + 5 /*FIXME*/, + full_mx - 2, full_my - 2, + pic_width, pic_height); + src_cr = h->edge_emu_buffer + (2 << pixel_shift) + 2 * h->mb_linesize; + } + qpix_op[luma_xy](dest_cr, src_cr, h->mb_linesize); // FIXME try variable height perhaps? + if (!square) + qpix_op[luma_xy](dest_cr + delta, src_cr + delta, h->mb_linesize); + return; + } + + ysh = 3 - (chroma_idc == 2 /* yuv422 */); + if (chroma_idc == 1 /* yuv420 */ && MB_FIELD(h)) { + my += 2 * ((h->mb_y & 1) - (pic->reference - 1)); + emu |= (my >> 3) < 0 || (my >> 3) + 8 >= (pic_height >> 1); + } + + src_cb = pic->f.data[1] + ((mx >> 3) << pixel_shift) + + (my >> ysh) * h->mb_uvlinesize; + src_cr = pic->f.data[2] + ((mx >> 3) << pixel_shift) + + (my >> ysh) * h->mb_uvlinesize; + + if (emu) { + h->vdsp.emulated_edge_mc(h->edge_emu_buffer, h->mb_uvlinesize, src_cb, h->mb_uvlinesize, + 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh), + pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */)); + src_cb = h->edge_emu_buffer; + } + chroma_op(dest_cb, src_cb, h->mb_uvlinesize, + height >> (chroma_idc == 1 /* yuv420 */), + mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7); + + if (emu) { + h->vdsp.emulated_edge_mc(h->edge_emu_buffer, h->mb_uvlinesize, src_cr, h->mb_uvlinesize, + 9, 8 * chroma_idc + 1, (mx >> 3), (my >> ysh), + pic_width >> 1, pic_height >> (chroma_idc == 1 /* yuv420 */)); + src_cr = h->edge_emu_buffer; + } + chroma_op(dest_cr, src_cr, h->mb_uvlinesize, height >> (chroma_idc == 1 /* yuv420 */), + mx & 7, (my << (chroma_idc == 2 /* yuv422 */)) & 7); +} +","@@ -3621,7 +3621,7 @@ static int decode_slice_header(H264Context *h, H264Context *h0) + assert(h0->cur_pic_ptr->reference != DELAYED_PIC_REF); + + /* Mark old field/frame as completed */ +- if (!last_pic_droppable && h0->cur_pic_ptr->tf.owner == h0->avctx) { ++ if (h0->cur_pic_ptr->tf.owner == h0->avctx) { + ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, + last_pic_structure == PICT_BOTTOM_FIELD); + } +@@ -3630,7 +3630,7 @@ static int decode_slice_header(H264Context *h, H264Context *h0) + if (!FIELD_PICTURE(h) || h->picture_structure == last_pic_structure) { + /* Previous field is unmatched. Don't display it, but let it + * remain for reference if marked as such. */ +- if (!last_pic_droppable && last_pic_structure != PICT_FRAME) { ++ if (last_pic_structure != PICT_FRAME) { + ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, + last_pic_structure == PICT_TOP_FIELD); + } +@@ -3640,7 +3640,7 @@ static int decode_slice_header(H264Context *h, H264Context *h0) + * different frame_nums. Consider this field first in + * pair. Throw away previous field except for reference + * purposes. */ +- if (!last_pic_droppable && last_pic_structure != PICT_FRAME) { ++ if (last_pic_structure != PICT_FRAME) { + ff_thread_report_progress(&h0->cur_pic_ptr->tf, INT_MAX, + last_pic_structure == PICT_TOP_FIELD); + }",1549,1880,2048 +3572,"CIFSTCon(unsigned int xid, struct cifsSesInfo *ses, + const char *tree, struct cifsTconInfo *tcon, + const struct nls_table *nls_codepage) +{ + struct smb_hdr *smb_buffer; + struct smb_hdr *smb_buffer_response; + TCONX_REQ *pSMB; + TCONX_RSP *pSMBr; + unsigned char *bcc_ptr; + int rc = 0; + int length, bytes_left; + __u16 count; + + if (ses == NULL) + return -EIO; + + smb_buffer = cifs_buf_get(); + if (smb_buffer == NULL) + return -ENOMEM; + + smb_buffer_response = smb_buffer; + + header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX, + NULL /*no tid */ , 4 /*wct */ ); + + smb_buffer->Mid = GetNextMid(ses->server); + smb_buffer->Uid = ses->Suid; + pSMB = (TCONX_REQ *) smb_buffer; + pSMBr = (TCONX_RSP *) smb_buffer_response; + + pSMB->AndXCommand = 0xFF; + pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO); + bcc_ptr = &pSMB->Password[0]; + if ((ses->server->secMode) & SECMODE_USER) { + pSMB->PasswordLength = cpu_to_le16(1); /* minimum */ + *bcc_ptr = 0; /* password is null byte */ + bcc_ptr++; /* skip password */ + /* already aligned so no need to do it below */ + } else { + pSMB->PasswordLength = cpu_to_le16(CIFS_SESS_KEY_SIZE); + /* BB FIXME add code to fail this if NTLMv2 or Kerberos + specified as required (when that support is added to + the vfs in the future) as only NTLM or the much + weaker LANMAN (which we do not send by default) is accepted + by Samba (not sure whether other servers allow + NTLMv2 password here) */ +#ifdef CONFIG_CIFS_WEAK_PW_HASH + if ((global_secflags & CIFSSEC_MAY_LANMAN) && + (ses->server->secType == LANMAN)) + calc_lanman_hash(tcon->password, ses->server->cryptKey, + ses->server->secMode & + SECMODE_PW_ENCRYPT ? true : false, + bcc_ptr); + else +#endif /* CIFS_WEAK_PW_HASH */ + SMBNTencrypt(tcon->password, ses->server->cryptKey, + bcc_ptr); + + bcc_ptr += CIFS_SESS_KEY_SIZE; + if (ses->capabilities & CAP_UNICODE) { + /* must align unicode strings */ + *bcc_ptr = 0; /* null byte password */ + bcc_ptr++; + } + } + + if (ses->server->secMode & + (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED)) + smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE; + + if (ses->capabilities & CAP_STATUS32) { + smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS; + } + if (ses->capabilities & CAP_DFS) { + smb_buffer->Flags2 |= SMBFLG2_DFS; + } + if (ses->capabilities & CAP_UNICODE) { + smb_buffer->Flags2 |= SMBFLG2_UNICODE; + length = + cifs_strtoUCS((__le16 *) bcc_ptr, tree, + 6 /* max utf8 char length in bytes */ * + (/* server len*/ + 256 /* share len */), nls_codepage); + bcc_ptr += 2 * length; /* convert num 16 bit words to bytes */ + bcc_ptr += 2; /* skip trailing null */ + } else { /* ASCII */ + strcpy(bcc_ptr, tree); + bcc_ptr += strlen(tree) + 1; + } + strcpy(bcc_ptr, ""?????""); + bcc_ptr += strlen(""?????""); + bcc_ptr += 1; + count = bcc_ptr - &pSMB->Password[0]; + pSMB->hdr.smb_buf_length += count; + pSMB->ByteCount = cpu_to_le16(count); + + rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length, + CIFS_STD_OP); + + /* above now done in SendReceive */ + if ((rc == 0) && (tcon != NULL)) { + bool is_unicode; + + tcon->tidStatus = CifsGood; + tcon->need_reconnect = false; + tcon->tid = smb_buffer_response->Tid; + bcc_ptr = pByteArea(smb_buffer_response); + bytes_left = BCC(smb_buffer_response); + length = strnlen(bcc_ptr, bytes_left - 2); + if (smb_buffer->Flags2 & SMBFLG2_UNICODE) + is_unicode = true; + else + is_unicode = false; + + + /* skip service field (NB: this field is always ASCII) */ + if (length == 3) { + if ((bcc_ptr[0] == 'I') && (bcc_ptr[1] == 'P') && + (bcc_ptr[2] == 'C')) { + cFYI(1, ""IPC connection""); + tcon->ipc = 1; + } + } else if (length == 2) { + if ((bcc_ptr[0] == 'A') && (bcc_ptr[1] == ':')) { + /* the most common case */ + cFYI(1, ""disk share connection""); + } + } + bcc_ptr += length + 1; + bytes_left -= (length + 1); + strncpy(tcon->treeName, tree, MAX_TREE_SIZE); + + /* mostly informational -- no need to fail on error here */ + kfree(tcon->nativeFileSystem); + tcon->nativeFileSystem = cifs_strndup_from_ucs(bcc_ptr, + bytes_left, is_unicode, + nls_codepage); + + cFYI(1, ""nativeFileSystem=%s"", tcon->nativeFileSystem); + + if ((smb_buffer_response->WordCount == 3) || + (smb_buffer_response->WordCount == 7)) + /* field is in same location */ + tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport); + else + tcon->Flags = 0; + cFYI(1, ""Tcon flags: 0x%x "", tcon->Flags); + } else if ((rc == 0) && tcon == NULL) { + /* all we need to save for IPC$ connection */ + ses->ipc_tid = smb_buffer_response->Tid; + } + + cifs_buf_release(smb_buffer); + return rc; +} +",0,"CIFSTCon(unsigned int xid, struct cifsSesInfo *ses, + const char *tree, struct cifsTconInfo *tcon, + const struct nls_table *nls_codepage) +{ + struct smb_hdr *smb_buffer; + struct smb_hdr *smb_buffer_response; + TCONX_REQ *pSMB; + TCONX_RSP *pSMBr; + unsigned char *bcc_ptr; + int rc = 0; + int length, bytes_left; + __u16 count; + + if (ses == NULL) + return -EIO; + + smb_buffer = cifs_buf_get(); + if (smb_buffer == NULL) + return -ENOMEM; + + smb_buffer_response = smb_buffer; + + header_assemble(smb_buffer, SMB_COM_TREE_CONNECT_ANDX, + NULL /*no tid */ , 4 /*wct */ ); + + smb_buffer->Mid = GetNextMid(ses->server); + smb_buffer->Uid = ses->Suid; + pSMB = (TCONX_REQ *) smb_buffer; + pSMBr = (TCONX_RSP *) smb_buffer_response; + + pSMB->AndXCommand = 0xFF; + pSMB->Flags = cpu_to_le16(TCON_EXTENDED_SECINFO); + bcc_ptr = &pSMB->Password[0]; + if ((ses->server->secMode) & SECMODE_USER) { + pSMB->PasswordLength = cpu_to_le16(1); /* minimum */ + *bcc_ptr = 0; /* password is null byte */ + bcc_ptr++; /* skip password */ + /* already aligned so no need to do it below */ + } else { + pSMB->PasswordLength = cpu_to_le16(CIFS_SESS_KEY_SIZE); + /* BB FIXME add code to fail this if NTLMv2 or Kerberos + specified as required (when that support is added to + the vfs in the future) as only NTLM or the much + weaker LANMAN (which we do not send by default) is accepted + by Samba (not sure whether other servers allow + NTLMv2 password here) */ +#ifdef CONFIG_CIFS_WEAK_PW_HASH + if ((global_secflags & CIFSSEC_MAY_LANMAN) && + (ses->server->secType == LANMAN)) + calc_lanman_hash(tcon->password, ses->server->cryptKey, + ses->server->secMode & + SECMODE_PW_ENCRYPT ? true : false, + bcc_ptr); + else +#endif /* CIFS_WEAK_PW_HASH */ + SMBNTencrypt(tcon->password, ses->server->cryptKey, + bcc_ptr); + + bcc_ptr += CIFS_SESS_KEY_SIZE; + if (ses->capabilities & CAP_UNICODE) { + /* must align unicode strings */ + *bcc_ptr = 0; /* null byte password */ + bcc_ptr++; + } + } + + if (ses->server->secMode & + (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED)) + smb_buffer->Flags2 |= SMBFLG2_SECURITY_SIGNATURE; + + if (ses->capabilities & CAP_STATUS32) { + smb_buffer->Flags2 |= SMBFLG2_ERR_STATUS; + } + if (ses->capabilities & CAP_DFS) { + smb_buffer->Flags2 |= SMBFLG2_DFS; + } + if (ses->capabilities & CAP_UNICODE) { + smb_buffer->Flags2 |= SMBFLG2_UNICODE; + length = + cifs_strtoUCS((__le16 *) bcc_ptr, tree, + 6 /* max utf8 char length in bytes */ * + (/* server len*/ + 256 /* share len */), nls_codepage); + bcc_ptr += 2 * length; /* convert num 16 bit words to bytes */ + bcc_ptr += 2; /* skip trailing null */ + } else { /* ASCII */ + strcpy(bcc_ptr, tree); + bcc_ptr += strlen(tree) + 1; + } + strcpy(bcc_ptr, ""?????""); + bcc_ptr += strlen(""?????""); + bcc_ptr += 1; + count = bcc_ptr - &pSMB->Password[0]; + pSMB->hdr.smb_buf_length += count; + pSMB->ByteCount = cpu_to_le16(count); + + rc = SendReceive(xid, ses, smb_buffer, smb_buffer_response, &length, + CIFS_STD_OP); + + /* above now done in SendReceive */ + if ((rc == 0) && (tcon != NULL)) { + bool is_unicode; + + tcon->tidStatus = CifsGood; + tcon->need_reconnect = false; + tcon->tid = smb_buffer_response->Tid; + bcc_ptr = pByteArea(smb_buffer_response); + bytes_left = BCC(smb_buffer_response); + length = strnlen(bcc_ptr, bytes_left - 2); + if (smb_buffer->Flags2 & SMBFLG2_UNICODE) + is_unicode = true; + else + is_unicode = false; + + + /* skip service field (NB: this field is always ASCII) */ + if (length == 3) { + if ((bcc_ptr[0] == 'I') && (bcc_ptr[1] == 'P') && + (bcc_ptr[2] == 'C')) { + cFYI(1, ""IPC connection""); + tcon->ipc = 1; + } + } else if (length == 2) { + if ((bcc_ptr[0] == 'A') && (bcc_ptr[1] == ':')) { + /* the most common case */ + cFYI(1, ""disk share connection""); + } + } + bcc_ptr += length + 1; + bytes_left -= (length + 1); + strncpy(tcon->treeName, tree, MAX_TREE_SIZE); + + /* mostly informational -- no need to fail on error here */ + kfree(tcon->nativeFileSystem); + tcon->nativeFileSystem = cifs_strndup_from_ucs(bcc_ptr, + bytes_left, is_unicode, + nls_codepage); + + cFYI(1, ""nativeFileSystem=%s"", tcon->nativeFileSystem); + + if ((smb_buffer_response->WordCount == 3) || + (smb_buffer_response->WordCount == 7)) + /* field is in same location */ + tcon->Flags = le16_to_cpu(pSMBr->OptionalSupport); + else + tcon->Flags = 0; + cFYI(1, ""Tcon flags: 0x%x "", tcon->Flags); + } else if ((rc == 0) && tcon == NULL) { + /* all we need to save for IPC$ connection */ + ses->ipc_tid = smb_buffer_response->Tid; + } + + cifs_buf_release(smb_buffer); + return rc; +} +","@@ -1644,17 +1644,27 @@ cifs_get_tcp_session(struct smb_vol *volume_info) + } + + static struct cifsSesInfo * +-cifs_find_smb_ses(struct TCP_Server_Info *server, char *username) ++cifs_find_smb_ses(struct TCP_Server_Info *server, struct smb_vol *vol) + { +- struct list_head *tmp; + struct cifsSesInfo *ses; + + write_lock(&cifs_tcp_ses_lock); +- list_for_each(tmp, &server->smb_ses_list) { +- ses = list_entry(tmp, struct cifsSesInfo, smb_ses_list); +- if (strncmp(ses->userName, username, MAX_USERNAME_SIZE)) +- continue; +- ++ list_for_each_entry(ses, &server->smb_ses_list, smb_ses_list) { ++ switch (server->secType) { ++ case Kerberos: ++ if (vol->linux_uid != ses->linux_uid) ++ continue; ++ break; ++ default: ++ /* anything else takes username/password */ ++ if (strncmp(ses->userName, vol->username, ++ MAX_USERNAME_SIZE)) ++ continue; ++ if (strlen(vol->username) != 0 && ++ strncmp(ses->password, vol->password, ++ MAX_PASSWORD_SIZE)) ++ continue; ++ } + ++ses->ses_count; + write_unlock(&cifs_tcp_ses_lock); + return ses; +@@ -1696,7 +1706,7 @@ cifs_get_smb_ses(struct TCP_Server_Info *server, struct smb_vol *volume_info) + + xid = GetXid(); + +- ses = cifs_find_smb_ses(server, volume_info->username); ++ ses = cifs_find_smb_ses(server, volume_info); + if (ses) { + cFYI(1, ""Existing smb sess found (status=%d)"", ses->status); + ",1488,1819,2048 +7042,"static int jpc_dec_tilefini(jpc_dec_t *dec, jpc_dec_tile_t *tile) +{ + jpc_dec_tcomp_t *tcomp; + int compno; + int bandno; + int rlvlno; + jpc_dec_band_t *band; + jpc_dec_rlvl_t *rlvl; + int prcno; + jpc_dec_prc_t *prc; + jpc_dec_seg_t *seg; + jpc_dec_cblk_t *cblk; + int cblkno; + + if (tile->tcomps) { + + for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; + ++compno, ++tcomp) { + for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; + ++rlvlno, ++rlvl) { + if (!rlvl->bands) { + continue; + } + for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; + ++bandno, ++band) { + if (band->prcs) { + for (prcno = 0, prc = band->prcs; prcno < + rlvl->numprcs; ++prcno, ++prc) { + if (!prc->cblks) { + continue; + } + for (cblkno = 0, cblk = prc->cblks; cblkno < + prc->numcblks; ++cblkno, ++cblk) { + + while (cblk->segs.head) { + seg = cblk->segs.head; + jpc_seglist_remove(&cblk->segs, seg); + jpc_seg_destroy(seg); + } + jas_matrix_destroy(cblk->data); + if (cblk->mqdec) { + jpc_mqdec_destroy(cblk->mqdec); + } + if (cblk->nulldec) { + jpc_bitstream_close(cblk->nulldec); + } + if (cblk->flags) { + jas_matrix_destroy(cblk->flags); + } + } + if (prc->incltagtree) { + jpc_tagtree_destroy(prc->incltagtree); + } + if (prc->numimsbstagtree) { + jpc_tagtree_destroy(prc->numimsbstagtree); + } + if (prc->cblks) { + jas_free(prc->cblks); + } + } + } + if (band->data) { + jas_matrix_destroy(band->data); + } + if (band->prcs) { + jas_free(band->prcs); + } + } + if (rlvl->bands) { + jas_free(rlvl->bands); + } + } + if (tcomp->rlvls) { + jas_free(tcomp->rlvls); + } + if (tcomp->data) { + jas_matrix_destroy(tcomp->data); + } + if (tcomp->tsfb) { + jpc_tsfb_destroy(tcomp->tsfb); + } + } + } + + if (tile->cp) { + jpc_dec_cp_destroy(tile->cp); + } + if (tile->tcomps) { + jas_free(tile->tcomps); + } + if (tile->pi) { + jpc_pi_destroy(tile->pi); + } + if (tile->pkthdrstream) { + jas_stream_close(tile->pkthdrstream); + } + if (tile->pptstab) { + jpc_ppxstab_destroy(tile->pptstab); + } + + tile->state = JPC_TILE_DONE; + + return 0; +} +",0,"static int jpc_dec_tilefini(jpc_dec_t *dec, jpc_dec_tile_t *tile) +{ + jpc_dec_tcomp_t *tcomp; + int compno; + int bandno; + int rlvlno; + jpc_dec_band_t *band; + jpc_dec_rlvl_t *rlvl; + int prcno; + jpc_dec_prc_t *prc; + jpc_dec_seg_t *seg; + jpc_dec_cblk_t *cblk; + int cblkno; + + if (tile->tcomps) { + + for (compno = 0, tcomp = tile->tcomps; compno < dec->numcomps; + ++compno, ++tcomp) { + for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; + ++rlvlno, ++rlvl) { + if (!rlvl->bands) { + continue; + } + for (bandno = 0, band = rlvl->bands; bandno < rlvl->numbands; + ++bandno, ++band) { + if (band->prcs) { + for (prcno = 0, prc = band->prcs; prcno < + rlvl->numprcs; ++prcno, ++prc) { + if (!prc->cblks) { + continue; + } + for (cblkno = 0, cblk = prc->cblks; cblkno < + prc->numcblks; ++cblkno, ++cblk) { + + while (cblk->segs.head) { + seg = cblk->segs.head; + jpc_seglist_remove(&cblk->segs, seg); + jpc_seg_destroy(seg); + } + jas_matrix_destroy(cblk->data); + if (cblk->mqdec) { + jpc_mqdec_destroy(cblk->mqdec); + } + if (cblk->nulldec) { + jpc_bitstream_close(cblk->nulldec); + } + if (cblk->flags) { + jas_matrix_destroy(cblk->flags); + } + } + if (prc->incltagtree) { + jpc_tagtree_destroy(prc->incltagtree); + } + if (prc->numimsbstagtree) { + jpc_tagtree_destroy(prc->numimsbstagtree); + } + if (prc->cblks) { + jas_free(prc->cblks); + } + } + } + if (band->data) { + jas_matrix_destroy(band->data); + } + if (band->prcs) { + jas_free(band->prcs); + } + } + if (rlvl->bands) { + jas_free(rlvl->bands); + } + } + if (tcomp->rlvls) { + jas_free(tcomp->rlvls); + } + if (tcomp->data) { + jas_matrix_destroy(tcomp->data); + } + if (tcomp->tsfb) { + jpc_tsfb_destroy(tcomp->tsfb); + } + } + } + + if (tile->cp) { + jpc_dec_cp_destroy(tile->cp); + } + if (tile->tcomps) { + jas_free(tile->tcomps); + } + if (tile->pi) { + jpc_pi_destroy(tile->pi); + } + if (tile->pkthdrstream) { + jas_stream_close(tile->pkthdrstream); + } + if (tile->pptstab) { + jpc_ppxstab_destroy(tile->pptstab); + } + + tile->state = JPC_TILE_DONE; + + return 0; +} +","@@ -1838,6 +1838,13 @@ static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps) + bool warn; + uint_fast32_t mask; + ++ if (roishift < 0) { ++ /* We could instead return an error here. */ ++ /* I do not think it matters much. */ ++ jas_eprintf(""warning: forcing negative ROI shift to zero "" ++ ""(bitstream is probably corrupt)\n""); ++ roishift = 0; ++ } + if (roishift == 0 && bgshift == 0) { + return; + } +@@ -1856,7 +1863,7 @@ static void jpc_undo_roi(jas_matrix_t *x, int roishift, int bgshift, int numbps) + } else { + /* We are dealing with non-ROI (i.e., background) data. */ + mag <<= bgshift; +- mask = (1 << numbps) - 1; ++ mask = (JAS_CAST(uint_fast32_t, 1) << numbps) - 1; + /* Perform a basic sanity check on the sample value. */ + /* Some implementations write garbage in the unused + most-significant bit planes introduced by ROI shifting.",839,1170,2048 +6668,"static int s6x0_i2c_transfer(struct i2c_adapter *adap, struct i2c_msg msg[], + int num) +{ + struct dvb_usb_device *d = i2c_get_adapdata(adap); + struct usb_device *udev; + int len, i, j, ret; + + if (!d) + return -ENODEV; + udev = d->udev; + if (mutex_lock_interruptible(&d->i2c_mutex) < 0) + return -EAGAIN; + + for (j = 0; j < num; j++) { + switch (msg[j].addr) { + case (DW2102_RC_QUERY): { + u8 ibuf[5]; + dw210x_op_rw(d->udev, 0xb8, 0, 0, + ibuf, 5, DW210X_READ_MSG); + memcpy(msg[j].buf, ibuf + 3, 2); + break; + } + case (DW2102_VOLTAGE_CTRL): { + u8 obuf[2]; + + obuf[0] = 1; + obuf[1] = msg[j].buf[1];/* off-on */ + dw210x_op_rw(d->udev, 0x8a, 0, 0, + obuf, 2, DW210X_WRITE_MSG); + obuf[0] = 3; + obuf[1] = msg[j].buf[0];/* 13v-18v */ + dw210x_op_rw(d->udev, 0x8a, 0, 0, + obuf, 2, DW210X_WRITE_MSG); + break; + } + case (DW2102_LED_CTRL): { + u8 obuf[2]; + + obuf[0] = 5; + obuf[1] = msg[j].buf[0]; + dw210x_op_rw(d->udev, 0x8a, 0, 0, + obuf, 2, DW210X_WRITE_MSG); + break; + } + /*case 0x55: cx24116 + case 0x6a: stv0903 + case 0x68: ds3000, stv0903, rs2000 + case 0x60: ts2020, stv6110, stb6100 + case 0xa0: eeprom */ + default: { + if (msg[j].flags == I2C_M_RD) { + /* read registers */ + u8 ibuf[MAX_XFER_SIZE]; + + if (msg[j].len > sizeof(ibuf)) { + warn(""i2c rd: len=%d is too big!\n"", + msg[j].len); + ret = -EOPNOTSUPP; + goto unlock; + } + + dw210x_op_rw(d->udev, 0x91, 0, 0, + ibuf, msg[j].len, + DW210X_READ_MSG); + memcpy(msg[j].buf, ibuf, msg[j].len); + break; + } else if ((msg[j].buf[0] == 0xb0) && + (msg[j].addr == 0x68)) { + /* write firmware */ + u8 obuf[19]; + obuf[0] = (msg[j].len > 16 ? + 18 : msg[j].len + 1); + obuf[1] = msg[j].addr << 1; + obuf[2] = msg[j].buf[0]; + len = msg[j].len - 1; + i = 1; + do { + memcpy(obuf + 3, msg[j].buf + i, + (len > 16 ? 16 : len)); + dw210x_op_rw(d->udev, 0x80, 0, 0, + obuf, (len > 16 ? 16 : len) + 3, + DW210X_WRITE_MSG); + i += 16; + len -= 16; + } while (len > 0); + } else if (j < (num - 1)) { + /* write register addr before read */ + u8 obuf[MAX_XFER_SIZE]; + + if (2 + msg[j].len > sizeof(obuf)) { + warn(""i2c wr: len=%d is too big!\n"", + msg[j].len); + ret = -EOPNOTSUPP; + goto unlock; + } + + obuf[0] = msg[j + 1].len; + obuf[1] = (msg[j].addr << 1); + memcpy(obuf + 2, msg[j].buf, msg[j].len); + dw210x_op_rw(d->udev, + le16_to_cpu(udev->descriptor.idProduct) == + 0x7500 ? 0x92 : 0x90, 0, 0, + obuf, msg[j].len + 2, + DW210X_WRITE_MSG); + break; + } else { + /* write registers */ + u8 obuf[MAX_XFER_SIZE]; + + if (2 + msg[j].len > sizeof(obuf)) { + warn(""i2c wr: len=%d is too big!\n"", + msg[j].len); + ret = -EOPNOTSUPP; + goto unlock; + } + obuf[0] = msg[j].len + 1; + obuf[1] = (msg[j].addr << 1); + memcpy(obuf + 2, msg[j].buf, msg[j].len); + dw210x_op_rw(d->udev, 0x80, 0, 0, + obuf, msg[j].len + 2, + DW210X_WRITE_MSG); + break; + } + break; + } + } + } + ret = num; + +unlock: + mutex_unlock(&d->i2c_mutex); + return ret; +} +",0,"static int s6x0_i2c_transfer(struct i2c_adapter *adap, struct i2c_msg msg[], + int num) +{ + struct dvb_usb_device *d = i2c_get_adapdata(adap); + struct usb_device *udev; + int len, i, j, ret; + + if (!d) + return -ENODEV; + udev = d->udev; + if (mutex_lock_interruptible(&d->i2c_mutex) < 0) + return -EAGAIN; + + for (j = 0; j < num; j++) { + switch (msg[j].addr) { + case (DW2102_RC_QUERY): { + u8 ibuf[5]; + dw210x_op_rw(d->udev, 0xb8, 0, 0, + ibuf, 5, DW210X_READ_MSG); + memcpy(msg[j].buf, ibuf + 3, 2); + break; + } + case (DW2102_VOLTAGE_CTRL): { + u8 obuf[2]; + + obuf[0] = 1; + obuf[1] = msg[j].buf[1];/* off-on */ + dw210x_op_rw(d->udev, 0x8a, 0, 0, + obuf, 2, DW210X_WRITE_MSG); + obuf[0] = 3; + obuf[1] = msg[j].buf[0];/* 13v-18v */ + dw210x_op_rw(d->udev, 0x8a, 0, 0, + obuf, 2, DW210X_WRITE_MSG); + break; + } + case (DW2102_LED_CTRL): { + u8 obuf[2]; + + obuf[0] = 5; + obuf[1] = msg[j].buf[0]; + dw210x_op_rw(d->udev, 0x8a, 0, 0, + obuf, 2, DW210X_WRITE_MSG); + break; + } + /*case 0x55: cx24116 + case 0x6a: stv0903 + case 0x68: ds3000, stv0903, rs2000 + case 0x60: ts2020, stv6110, stb6100 + case 0xa0: eeprom */ + default: { + if (msg[j].flags == I2C_M_RD) { + /* read registers */ + u8 ibuf[MAX_XFER_SIZE]; + + if (msg[j].len > sizeof(ibuf)) { + warn(""i2c rd: len=%d is too big!\n"", + msg[j].len); + ret = -EOPNOTSUPP; + goto unlock; + } + + dw210x_op_rw(d->udev, 0x91, 0, 0, + ibuf, msg[j].len, + DW210X_READ_MSG); + memcpy(msg[j].buf, ibuf, msg[j].len); + break; + } else if ((msg[j].buf[0] == 0xb0) && + (msg[j].addr == 0x68)) { + /* write firmware */ + u8 obuf[19]; + obuf[0] = (msg[j].len > 16 ? + 18 : msg[j].len + 1); + obuf[1] = msg[j].addr << 1; + obuf[2] = msg[j].buf[0]; + len = msg[j].len - 1; + i = 1; + do { + memcpy(obuf + 3, msg[j].buf + i, + (len > 16 ? 16 : len)); + dw210x_op_rw(d->udev, 0x80, 0, 0, + obuf, (len > 16 ? 16 : len) + 3, + DW210X_WRITE_MSG); + i += 16; + len -= 16; + } while (len > 0); + } else if (j < (num - 1)) { + /* write register addr before read */ + u8 obuf[MAX_XFER_SIZE]; + + if (2 + msg[j].len > sizeof(obuf)) { + warn(""i2c wr: len=%d is too big!\n"", + msg[j].len); + ret = -EOPNOTSUPP; + goto unlock; + } + + obuf[0] = msg[j + 1].len; + obuf[1] = (msg[j].addr << 1); + memcpy(obuf + 2, msg[j].buf, msg[j].len); + dw210x_op_rw(d->udev, + le16_to_cpu(udev->descriptor.idProduct) == + 0x7500 ? 0x92 : 0x90, 0, 0, + obuf, msg[j].len + 2, + DW210X_WRITE_MSG); + break; + } else { + /* write registers */ + u8 obuf[MAX_XFER_SIZE]; + + if (2 + msg[j].len > sizeof(obuf)) { + warn(""i2c wr: len=%d is too big!\n"", + msg[j].len); + ret = -EOPNOTSUPP; + goto unlock; + } + obuf[0] = msg[j].len + 1; + obuf[1] = (msg[j].addr << 1); + memcpy(obuf + 2, msg[j].buf, msg[j].len); + dw210x_op_rw(d->udev, 0x80, 0, 0, + obuf, msg[j].len + 2, + DW210X_WRITE_MSG); + break; + } + break; + } + } + } + ret = num; + +unlock: + mutex_unlock(&d->i2c_mutex); + return ret; +} +","@@ -68,6 +68,7 @@ + struct dw2102_state { + u8 initialized; + u8 last_lock; ++ u8 data[MAX_XFER_SIZE + 4]; + struct i2c_client *i2c_client_demod; + struct i2c_client *i2c_client_tuner; + +@@ -661,62 +662,72 @@ static int su3000_i2c_transfer(struct i2c_adapter *adap, struct i2c_msg msg[], + int num) + { + struct dvb_usb_device *d = i2c_get_adapdata(adap); +- u8 obuf[0x40], ibuf[0x40]; ++ struct dw2102_state *state; + + if (!d) + return -ENODEV; ++ ++ state = d->priv; ++ + if (mutex_lock_interruptible(&d->i2c_mutex) < 0) + return -EAGAIN; ++ if (mutex_lock_interruptible(&d->data_mutex) < 0) { ++ mutex_unlock(&d->i2c_mutex); ++ return -EAGAIN; ++ } + + switch (num) { + case 1: + switch (msg[0].addr) { + case SU3000_STREAM_CTRL: +- obuf[0] = msg[0].buf[0] + 0x36; +- obuf[1] = 3; +- obuf[2] = 0; +- if (dvb_usb_generic_rw(d, obuf, 3, ibuf, 0, 0) < 0) ++ state->data[0] = msg[0].buf[0] + 0x36; ++ state->data[1] = 3; ++ state->data[2] = 0; ++ if (dvb_usb_generic_rw(d, state->data, 3, ++ state->data, 0, 0) < 0) + err(""i2c transfer failed.""); + break; + case DW2102_RC_QUERY: +- obuf[0] = 0x10; +- if (dvb_usb_generic_rw(d, obuf, 1, ibuf, 2, 0) < 0) ++ state->data[0] = 0x10; ++ if (dvb_usb_generic_rw(d, state->data, 1, ++ state->data, 2, 0) < 0) + err(""i2c transfer failed.""); +- msg[0].buf[1] = ibuf[0]; +- msg[0].buf[0] = ibuf[1]; ++ msg[0].buf[1] = state->data[0]; ++ msg[0].buf[0] = state->data[1]; + break; + default: + /* always i2c write*/ +- obuf[0] = 0x08; +- obuf[1] = msg[0].addr; +- obuf[2] = msg[0].len; ++ state->data[0] = 0x08; ++ state->data[1] = msg[0].addr; ++ state->data[2] = msg[0].len; + +- memcpy(&obuf[3], msg[0].buf, msg[0].len); ++ memcpy(&state->data[3], msg[0].buf, msg[0].len); + +- if (dvb_usb_generic_rw(d, obuf, msg[0].len + 3, +- ibuf, 1, 0) < 0) ++ if (dvb_usb_generic_rw(d, state->data, msg[0].len + 3, ++ state->data, 1, 0) < 0) + err(""i2c transfer failed.""); + + } + break; + case 2: + /* always i2c read */ +- obuf[0] = 0x09; +- obuf[1] = msg[0].len; +- obuf[2] = msg[1].len; +- obuf[3] = msg[0].addr; +- memcpy(&obuf[4], msg[0].buf, msg[0].len); +- +- if (dvb_usb_generic_rw(d, obuf, msg[0].len + 4, +- ibuf, msg[1].len + 1, 0) < 0) ++ state->data[0] = 0x09; ++ state->data[1] = msg[0].len; ++ state->data[2] = msg[1].len; ++ state->data[3] = msg[0].addr; ++ memcpy(&state->data[4], msg[0].buf, msg[0].len); ++ ++ if (dvb_usb_generic_rw(d, state->data, msg[0].len + 4, ++ state->data, msg[1].len + 1, 0) < 0) + err(""i2c transfer failed.""); + +- memcpy(msg[1].buf, &ibuf[1], msg[1].len); ++ memcpy(msg[1].buf, &state->data[1], msg[1].len); + break; + default: + warn(""more than 2 i2c messages at a time is not handled yet.""); + break; + } ++ mutex_unlock(&d->data_mutex); + mutex_unlock(&d->i2c_mutex); + return num; + } +@@ -844,17 +855,23 @@ static int su3000_streaming_ctrl(struct dvb_usb_adapter *adap, int onoff) + static int su3000_power_ctrl(struct dvb_usb_device *d, int i) + { + struct dw2102_state *state = (struct dw2102_state *)d->priv; +- u8 obuf[] = {0xde, 0}; ++ int ret = 0; + + info(""%s: %d, initialized %d"", __func__, i, state->initialized); + + if (i && !state->initialized) { ++ mutex_lock(&d->data_mutex); ++ ++ state->data[0] = 0xde; ++ state->data[1] = 0; ++ + state->initialized = 1; + /* reset board */ +- return dvb_usb_generic_rw(d, obuf, 2, NULL, 0, 0); ++ ret = dvb_usb_generic_rw(d, state->data, 2, NULL, 0, 0); ++ mutex_unlock(&d->data_mutex); + } + +- return 0; ++ return ret; + } + + static int su3000_read_mac_address(struct dvb_usb_device *d, u8 mac[6]) +@@ -1309,49 +1326,57 @@ static int prof_7500_frontend_attach(struct dvb_usb_adapter *d) + return 0; + } + +-static int su3000_frontend_attach(struct dvb_usb_adapter *d) ++static int su3000_frontend_attach(struct dvb_usb_adapter *adap) + { +- u8 obuf[3] = { 0xe, 0x80, 0 }; +- u8 ibuf[] = { 0 }; ++ struct dvb_usb_device *d = adap->dev; ++ struct dw2102_state *state = d->priv; ++ ++ mutex_lock(&d->data_mutex); ++ ++ state->data[0] = 0xe; ++ state->data[1] = 0x80; ++ state->data[2] = 0; + +- if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) ++ if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) + err(""command 0x0e transfer failed.""); + +- obuf[0] = 0xe; +- obuf[1] = 0x02; +- obuf[2] = 1; ++ state->data[0] = 0xe; ++ state->data[1] = 0x02; ++ state->data[2] = 1; + +- if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) ++ if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) + err(""command 0x0e transfer failed.""); + msleep(300); + +- obuf[0] = 0xe; +- obuf[1] = 0x83; +- obuf[2] = 0; ++ state->data[0] = 0xe; ++ state->data[1] = 0x83; ++ state->data[2] = 0; + +- if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) ++ if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) + err(""command 0x0e transfer failed.""); + +- obuf[0] = 0xe; +- obuf[1] = 0x83; +- obuf[2] = 1; ++ state->data[0] = 0xe; ++ state->data[1] = 0x83; ++ state->data[2] = 1; + +- if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) ++ if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) + err(""command 0x0e transfer failed.""); + +- obuf[0] = 0x51; ++ state->data[0] = 0x51; + +- if (dvb_usb_generic_rw(d->dev, obuf, 1, ibuf, 1, 0) < 0) ++ if (dvb_usb_generic_rw(d, state->data, 1, state->data, 1, 0) < 0) + err(""command 0x51 transfer failed.""); + +- d->fe_adap[0].fe = dvb_attach(ds3000_attach, &su3000_ds3000_config, +- &d->dev->i2c_adap); +- if (d->fe_adap[0].fe == NULL) ++ mutex_unlock(&d->data_mutex); ++ ++ adap->fe_adap[0].fe = dvb_attach(ds3000_attach, &su3000_ds3000_config, ++ &d->i2c_adap); ++ if (adap->fe_adap[0].fe == NULL) + return -EIO; + +- if (dvb_attach(ts2020_attach, d->fe_adap[0].fe, ++ if (dvb_attach(ts2020_attach, adap->fe_adap[0].fe, + &dw2104_ts2020_config, +- &d->dev->i2c_adap)) { ++ &d->i2c_adap)) { + info(""Attached DS3000/TS2020!""); + return 0; + } +@@ -1360,47 +1385,55 @@ static int su3000_frontend_attach(struct dvb_usb_adapter *d) + return -EIO; + } + +-static int t220_frontend_attach(struct dvb_usb_adapter *d) ++static int t220_frontend_attach(struct dvb_usb_adapter *adap) + { +- u8 obuf[3] = { 0xe, 0x87, 0 }; +- u8 ibuf[] = { 0 }; ++ struct dvb_usb_device *d = adap->dev; ++ struct dw2102_state *state = d->priv; ++ ++ mutex_lock(&d->data_mutex); + +- if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) ++ state->data[0] = 0xe; ++ state->data[1] = 0x87; ++ state->data[2] = 0x0; ++ ++ if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) + err(""command 0x0e transfer failed.""); + +- obuf[0] = 0xe; +- obuf[1] = 0x86; +- obuf[2] = 1; ++ state->data[0] = 0xe; ++ state->data[1] = 0x86; ++ state->data[2] = 1; + +- if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) ++ if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) + err(""command 0x0e transfer failed.""); + +- obuf[0] = 0xe; +- obuf[1] = 0x80; +- obuf[2] = 0; ++ state->data[0] = 0xe; ++ state->data[1] = 0x80; ++ state->data[2] = 0; + +- if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) ++ if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) + err(""command 0x0e transfer failed.""); + + msleep(50); + +- obuf[0] = 0xe; +- obuf[1] = 0x80; +- obuf[2] = 1; ++ state->data[0] = 0xe; ++ state->data[1] = 0x80; ++ state->data[2] = 1; + +- if (dvb_usb_generic_rw(d->dev, obuf, 3, ibuf, 1, 0) < 0) ++ if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) + err(""command 0x0e transfer failed.""); + +- obuf[0] = 0x51; ++ state->data[0] = 0x51; + +- if (dvb_usb_generic_rw(d->dev, obuf, 1, ibuf, 1, 0) < 0) ++ if (dvb_usb_generic_rw(d, state->data, 1, state->data, 1, 0) < 0) + err(""command 0x51 transfer failed.""); + +- d->fe_adap[0].fe = dvb_attach(cxd2820r_attach, &cxd2820r_config, +- &d->dev->i2c_adap, NULL); +- if (d->fe_adap[0].fe != NULL) { +- if (dvb_attach(tda18271_attach, d->fe_adap[0].fe, 0x60, +- &d->dev->i2c_adap, &tda18271_config)) { ++ mutex_unlock(&d->data_mutex); ++ ++ adap->fe_adap[0].fe = dvb_attach(cxd2820r_attach, &cxd2820r_config, ++ &d->i2c_adap, NULL); ++ if (adap->fe_adap[0].fe != NULL) { ++ if (dvb_attach(tda18271_attach, adap->fe_adap[0].fe, 0x60, ++ &d->i2c_adap, &tda18271_config)) { + info(""Attached TDA18271HD/CXD2820R!""); + return 0; + } +@@ -1410,23 +1443,30 @@ static int t220_frontend_attach(struct dvb_usb_adapter *d) + return -EIO; + } + +-static int m88rs2000_frontend_attach(struct dvb_usb_adapter *d) ++static int m88rs2000_frontend_attach(struct dvb_usb_adapter *adap) + { +- u8 obuf[] = { 0x51 }; +- u8 ibuf[] = { 0 }; ++ struct dvb_usb_device *d = adap->dev; ++ struct dw2102_state *state = d->priv; ++ ++ mutex_lock(&d->data_mutex); + +- if (dvb_usb_generic_rw(d->dev, obuf, 1, ibuf, 1, 0) < 0) ++ state->data[0] = 0x51; ++ ++ if (dvb_usb_generic_rw(d, state->data, 1, state->data, 1, 0) < 0) + err(""command 0x51 transfer failed.""); + +- d->fe_adap[0].fe = dvb_attach(m88rs2000_attach, &s421_m88rs2000_config, +- &d->dev->i2c_adap); ++ mutex_unlock(&d->data_mutex); + +- if (d->fe_adap[0].fe == NULL) ++ adap->fe_adap[0].fe = dvb_attach(m88rs2000_attach, ++ &s421_m88rs2000_config, ++ &d->i2c_adap); ++ ++ if (adap->fe_adap[0].fe == NULL) + return -EIO; + +- if (dvb_attach(ts2020_attach, d->fe_adap[0].fe, ++ if (dvb_attach(ts2020_attach, adap->fe_adap[0].fe, + &dw2104_ts2020_config, +- &d->dev->i2c_adap)) { ++ &d->i2c_adap)) { + info(""Attached RS2000/TS2020!""); + return 0; + } +@@ -1439,44 +1479,50 @@ static int tt_s2_4600_frontend_attach(struct dvb_usb_adapter *adap) + { + struct dvb_usb_device *d = adap->dev; + struct dw2102_state *state = d->priv; +- u8 obuf[3] = { 0xe, 0x80, 0 }; +- u8 ibuf[] = { 0 }; + struct i2c_adapter *i2c_adapter; + struct i2c_client *client; + struct i2c_board_info board_info; + struct m88ds3103_platform_data m88ds3103_pdata = {}; + struct ts2020_config ts2020_config = {}; + +- if (dvb_usb_generic_rw(d, obuf, 3, ibuf, 1, 0) < 0) ++ mutex_lock(&d->data_mutex); ++ ++ state->data[0] = 0xe; ++ state->data[1] = 0x80; ++ state->data[2] = 0x0; ++ ++ if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) + err(""command 0x0e transfer failed.""); + +- obuf[0] = 0xe; +- obuf[1] = 0x02; +- obuf[2] = 1; ++ state->data[0] = 0xe; ++ state->data[1] = 0x02; ++ state->data[2] = 1; + +- if (dvb_usb_generic_rw(d, obuf, 3, ibuf, 1, 0) < 0) ++ if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) + err(""command 0x0e transfer failed.""); + msleep(300); + +- obuf[0] = 0xe; +- obuf[1] = 0x83; +- obuf[2] = 0; ++ state->data[0] = 0xe; ++ state->data[1] = 0x83; ++ state->data[2] = 0; + +- if (dvb_usb_generic_rw(d, obuf, 3, ibuf, 1, 0) < 0) ++ if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) + err(""command 0x0e transfer failed.""); + +- obuf[0] = 0xe; +- obuf[1] = 0x83; +- obuf[2] = 1; ++ state->data[0] = 0xe; ++ state->data[1] = 0x83; ++ state->data[2] = 1; + +- if (dvb_usb_generic_rw(d, obuf, 3, ibuf, 1, 0) < 0) ++ if (dvb_usb_generic_rw(d, state->data, 3, state->data, 1, 0) < 0) + err(""command 0x0e transfer failed.""); + +- obuf[0] = 0x51; ++ state->data[0] = 0x51; + +- if (dvb_usb_generic_rw(d, obuf, 1, ibuf, 1, 0) < 0) ++ if (dvb_usb_generic_rw(d, state->data, 1, state->data, 1, 0) < 0) + err(""command 0x51 transfer failed.""); + ++ mutex_unlock(&d->data_mutex); ++ + /* attach demod */ + m88ds3103_pdata.clk = 27000000; + m88ds3103_pdata.i2c_wr_max = 33;",1385,1716,2048 +3475,"static void ccid3_hc_tx_no_feedback_timer(unsigned long data) +{ + struct sock *sk = (struct sock *)data; + struct ccid3_hc_tx_sock *hc = ccid3_hc_tx_sk(sk); + unsigned long t_nfb = USEC_PER_SEC / 5; + + bh_lock_sock(sk); + if (sock_owned_by_user(sk)) { + /* Try again later. */ + /* XXX: set some sensible MIB */ + goto restart_timer; + } + + ccid3_pr_debug(""%s(%p, state=%s) - entry\n"", dccp_role(sk), sk, + ccid3_tx_state_name(hc->tx_state)); + + /* Ignore and do not restart after leaving the established state */ + if ((1 << sk->sk_state) & ~(DCCPF_OPEN | DCCPF_PARTOPEN)) + goto out; + + /* Reset feedback state to ""no feedback received"" */ + if (hc->tx_state == TFRC_SSTATE_FBACK) + ccid3_hc_tx_set_state(sk, TFRC_SSTATE_NO_FBACK); + + /* + * Determine new allowed sending rate X as per draft rfc3448bis-00, 4.4 + * RTO is 0 if and only if no feedback has been received yet. + */ + if (hc->tx_t_rto == 0 || hc->tx_p == 0) { + + /* halve send rate directly */ + hc->tx_x = max(hc->tx_x / 2, + (((__u64)hc->tx_s) << 6) / TFRC_T_MBI); + ccid3_update_send_interval(hc); + } else { + /* + * Modify the cached value of X_recv + * + * If (X_calc > 2 * X_recv) + * X_recv = max(X_recv / 2, s / (2 * t_mbi)); + * Else + * X_recv = X_calc / 4; + * + * Note that X_recv is scaled by 2^6 while X_calc is not + */ + if (hc->tx_x_calc > (hc->tx_x_recv >> 5)) + hc->tx_x_recv = + max(hc->tx_x_recv / 2, + (((__u64)hc->tx_s) << 6) / (2*TFRC_T_MBI)); + else { + hc->tx_x_recv = hc->tx_x_calc; + hc->tx_x_recv <<= 4; + } + ccid3_hc_tx_update_x(sk, NULL); + } + ccid3_pr_debug(""Reduced X to %llu/64 bytes/sec\n"", + (unsigned long long)hc->tx_x); + + /* + * Set new timeout for the nofeedback timer. + * See comments in packet_recv() regarding the value of t_RTO. + */ + if (unlikely(hc->tx_t_rto == 0)) /* no feedback received yet */ + t_nfb = TFRC_INITIAL_TIMEOUT; + else + t_nfb = max(hc->tx_t_rto, 2 * hc->tx_t_ipi); + +restart_timer: + sk_reset_timer(sk, &hc->tx_no_feedback_timer, + jiffies + usecs_to_jiffies(t_nfb)); +out: + bh_unlock_sock(sk); + sock_put(sk); +} +",0,"static void ccid3_hc_tx_no_feedback_timer(unsigned long data) +{ + struct sock *sk = (struct sock *)data; + struct ccid3_hc_tx_sock *hc = ccid3_hc_tx_sk(sk); + unsigned long t_nfb = USEC_PER_SEC / 5; + + bh_lock_sock(sk); + if (sock_owned_by_user(sk)) { + /* Try again later. */ + /* XXX: set some sensible MIB */ + goto restart_timer; + } + + ccid3_pr_debug(""%s(%p, state=%s) - entry\n"", dccp_role(sk), sk, + ccid3_tx_state_name(hc->tx_state)); + + /* Ignore and do not restart after leaving the established state */ + if ((1 << sk->sk_state) & ~(DCCPF_OPEN | DCCPF_PARTOPEN)) + goto out; + + /* Reset feedback state to ""no feedback received"" */ + if (hc->tx_state == TFRC_SSTATE_FBACK) + ccid3_hc_tx_set_state(sk, TFRC_SSTATE_NO_FBACK); + + /* + * Determine new allowed sending rate X as per draft rfc3448bis-00, 4.4 + * RTO is 0 if and only if no feedback has been received yet. + */ + if (hc->tx_t_rto == 0 || hc->tx_p == 0) { + + /* halve send rate directly */ + hc->tx_x = max(hc->tx_x / 2, + (((__u64)hc->tx_s) << 6) / TFRC_T_MBI); + ccid3_update_send_interval(hc); + } else { + /* + * Modify the cached value of X_recv + * + * If (X_calc > 2 * X_recv) + * X_recv = max(X_recv / 2, s / (2 * t_mbi)); + * Else + * X_recv = X_calc / 4; + * + * Note that X_recv is scaled by 2^6 while X_calc is not + */ + if (hc->tx_x_calc > (hc->tx_x_recv >> 5)) + hc->tx_x_recv = + max(hc->tx_x_recv / 2, + (((__u64)hc->tx_s) << 6) / (2*TFRC_T_MBI)); + else { + hc->tx_x_recv = hc->tx_x_calc; + hc->tx_x_recv <<= 4; + } + ccid3_hc_tx_update_x(sk, NULL); + } + ccid3_pr_debug(""Reduced X to %llu/64 bytes/sec\n"", + (unsigned long long)hc->tx_x); + + /* + * Set new timeout for the nofeedback timer. + * See comments in packet_recv() regarding the value of t_RTO. + */ + if (unlikely(hc->tx_t_rto == 0)) /* no feedback received yet */ + t_nfb = TFRC_INITIAL_TIMEOUT; + else + t_nfb = max(hc->tx_t_rto, 2 * hc->tx_t_ipi); + +restart_timer: + sk_reset_timer(sk, &hc->tx_no_feedback_timer, + jiffies + usecs_to_jiffies(t_nfb)); +out: + bh_unlock_sock(sk); + sock_put(sk); +} +","@@ -535,6 +535,7 @@ static int ccid3_hc_tx_getsockopt(struct sock *sk, const int optname, int len, + case DCCP_SOCKOPT_CCID_TX_INFO: + if (len < sizeof(tfrc)) + return -EINVAL; ++ memset(&tfrc, 0, sizeof(tfrc)); + tfrc.tfrctx_x = hc->tx_x; + tfrc.tfrctx_x_recv = hc->tx_x_recv; + tfrc.tfrctx_x_calc = hc->tx_x_calc;",723,1054,2048 +18716,"HTMLTreeBuilderSimulator::SimulatedToken HTMLTreeBuilderSimulator::Simulate( + const CompactHTMLToken& token, + HTMLTokenizer* tokenizer) { + SimulatedToken simulated_token = kOtherToken; + + if (token.GetType() == HTMLToken::kStartTag) { + const String& tag_name = token.Data(); + if (ThreadSafeMatch(tag_name, SVGNames::svgTag)) + namespace_stack_.push_back(SVG); + if (ThreadSafeMatch(tag_name, MathMLNames::mathTag)) + namespace_stack_.push_back(kMathML); + if (InForeignContent() && TokenExitsForeignContent(token)) + namespace_stack_.pop_back(); + if ((namespace_stack_.back() == SVG && TokenExitsSVG(token)) || + (namespace_stack_.back() == kMathML && TokenExitsMath(token))) + namespace_stack_.push_back(HTML); + if (!InForeignContent()) { + if (ThreadSafeMatch(tag_name, textareaTag) || + ThreadSafeMatch(tag_name, titleTag)) { + tokenizer->SetState(HTMLTokenizer::kRCDATAState); + } else if (ThreadSafeMatch(tag_name, scriptTag)) { + tokenizer->SetState(HTMLTokenizer::kScriptDataState); + simulated_token = kScriptStart; + } else if (ThreadSafeMatch(tag_name, linkTag)) { + simulated_token = kLink; + } else if (!in_select_insertion_mode_) { + if (ThreadSafeMatch(tag_name, plaintextTag) && + !in_select_insertion_mode_) { + tokenizer->SetState(HTMLTokenizer::kPLAINTEXTState); + } else if (ThreadSafeMatch(tag_name, styleTag) || + ThreadSafeMatch(tag_name, iframeTag) || + ThreadSafeMatch(tag_name, xmpTag) || + (ThreadSafeMatch(tag_name, noembedTag) && + options_.plugins_enabled) || + ThreadSafeMatch(tag_name, noframesTag) || + (ThreadSafeMatch(tag_name, noscriptTag) && + options_.script_enabled)) { + tokenizer->SetState(HTMLTokenizer::kRAWTEXTState); + } + } + + if (ThreadSafeMatch(tag_name, selectTag)) { + in_select_insertion_mode_ = true; + } else if (in_select_insertion_mode_ && TokenExitsInSelect(token)) { + in_select_insertion_mode_ = false; + } + } + } + + if (token.GetType() == HTMLToken::kEndTag || + (token.GetType() == HTMLToken::kStartTag && token.SelfClosing() && + InForeignContent())) { + const String& tag_name = token.Data(); + if ((namespace_stack_.back() == SVG && + ThreadSafeMatch(tag_name, SVGNames::svgTag)) || + (namespace_stack_.back() == kMathML && + ThreadSafeMatch(tag_name, MathMLNames::mathTag)) || + (namespace_stack_.Contains(SVG) && namespace_stack_.back() == HTML && + TokenExitsSVG(token)) || + (namespace_stack_.Contains(kMathML) && + namespace_stack_.back() == HTML && TokenExitsMath(token))) { + namespace_stack_.pop_back(); + } + if (ThreadSafeMatch(tag_name, scriptTag)) { + if (!InForeignContent()) + tokenizer->SetState(HTMLTokenizer::kDataState); + return kScriptEnd; + } else if (ThreadSafeMatch(tag_name, selectTag)) { + in_select_insertion_mode_ = false; + } + if (ThreadSafeMatch(tag_name, styleTag)) + simulated_token = kStyleEnd; + } + + tokenizer->SetForceNullCharacterReplacement(InForeignContent()); + tokenizer->SetShouldAllowCDATA(InForeignContent()); + return simulated_token; + } +",1,"HTMLTreeBuilderSimulator::SimulatedToken HTMLTreeBuilderSimulator::Simulate( + const CompactHTMLToken& token, + HTMLTokenizer* tokenizer) { + SimulatedToken simulated_token = kOtherToken; + + if (token.GetType() == HTMLToken::kStartTag) { + const String& tag_name = token.Data(); + if (ThreadSafeMatch(tag_name, SVGNames::svgTag)) + namespace_stack_.push_back(SVG); + if (ThreadSafeMatch(tag_name, MathMLNames::mathTag)) + namespace_stack_.push_back(kMathML); + if (InForeignContent() && TokenExitsForeignContent(token)) + namespace_stack_.pop_back(); + if (IsHTMLIntegrationPointForStartTag(token) || + (namespace_stack_.back() == kMathML && TokenExitsMath(token))) { + namespace_stack_.push_back(HTML); + } else if (!InForeignContent()) { + if (ThreadSafeMatch(tag_name, textareaTag) || + ThreadSafeMatch(tag_name, titleTag)) { + tokenizer->SetState(HTMLTokenizer::kRCDATAState); + } else if (ThreadSafeMatch(tag_name, scriptTag)) { + tokenizer->SetState(HTMLTokenizer::kScriptDataState); + simulated_token = kScriptStart; + } else if (ThreadSafeMatch(tag_name, linkTag)) { + simulated_token = kLink; + } else if (!in_select_insertion_mode_) { + if (ThreadSafeMatch(tag_name, plaintextTag) && + !in_select_insertion_mode_) { + tokenizer->SetState(HTMLTokenizer::kPLAINTEXTState); + } else if (ThreadSafeMatch(tag_name, styleTag) || + ThreadSafeMatch(tag_name, iframeTag) || + ThreadSafeMatch(tag_name, xmpTag) || + (ThreadSafeMatch(tag_name, noembedTag) && + options_.plugins_enabled) || + ThreadSafeMatch(tag_name, noframesTag) || + (ThreadSafeMatch(tag_name, noscriptTag) && + options_.script_enabled)) { + tokenizer->SetState(HTMLTokenizer::kRAWTEXTState); + } + } + + if (ThreadSafeMatch(tag_name, selectTag)) { + in_select_insertion_mode_ = true; + } else if (in_select_insertion_mode_ && TokenExitsInSelect(token)) { + in_select_insertion_mode_ = false; + } + } + } + + if (token.GetType() == HTMLToken::kEndTag || + (token.GetType() == HTMLToken::kStartTag && token.SelfClosing() && + InForeignContent())) { + const String& tag_name = token.Data(); + if ((namespace_stack_.back() == SVG && + ThreadSafeMatch(tag_name, SVGNames::svgTag)) || + (namespace_stack_.back() == kMathML && + ThreadSafeMatch(tag_name, MathMLNames::mathTag)) || + IsHTMLIntegrationPointForEndTag(token) || + (namespace_stack_.Contains(kMathML) && + namespace_stack_.back() == HTML && TokenExitsMath(token))) { + namespace_stack_.pop_back(); + } + if (ThreadSafeMatch(tag_name, scriptTag)) { + if (!InForeignContent()) + tokenizer->SetState(HTMLTokenizer::kDataState); + return kScriptEnd; + } else if (ThreadSafeMatch(tag_name, selectTag)) { + in_select_insertion_mode_ = false; + } + if (ThreadSafeMatch(tag_name, styleTag)) + simulated_token = kStyleEnd; + } + + tokenizer->SetForceNullCharacterReplacement(InForeignContent()); + tokenizer->SetShouldAllowCDATA(InForeignContent()); + return simulated_token; + } +","@@ -82,13 +82,6 @@ static bool TokenExitsForeignContent(const CompactHTMLToken& token) { + token.GetAttributeItem(sizeAttr))); + } + +-static bool TokenExitsSVG(const CompactHTMLToken& token) { +- // FIXME: It's very fragile that we special case foreignObject here to be +- // case-insensitive. +- return DeprecatedEqualIgnoringCase(token.Data(), +- SVGNames::foreignObjectTag.LocalName()); +-} +- + static bool TokenExitsMath(const CompactHTMLToken& token) { + // FIXME: This is copied from HTMLElementStack::isMathMLTextIntegrationPoint + // and changed to use threadSafeMatch. +@@ -148,10 +141,10 @@ HTMLTreeBuilderSimulator::SimulatedToken HTMLTreeBuilderSimulator::Simulate( + namespace_stack_.push_back(kMathML); + if (InForeignContent() && TokenExitsForeignContent(token)) + namespace_stack_.pop_back(); +- if ((namespace_stack_.back() == SVG && TokenExitsSVG(token)) || +- (namespace_stack_.back() == kMathML && TokenExitsMath(token))) ++ if (IsHTMLIntegrationPointForStartTag(token) || ++ (namespace_stack_.back() == kMathML && TokenExitsMath(token))) { + namespace_stack_.push_back(HTML); +- if (!InForeignContent()) { ++ } else if (!InForeignContent()) { + // FIXME: This is just a copy of Tokenizer::updateStateFor which uses + // threadSafeMatches. + if (ThreadSafeMatch(tag_name, textareaTag) || +@@ -203,8 +196,7 @@ HTMLTreeBuilderSimulator::SimulatedToken HTMLTreeBuilderSimulator::Simulate( + ThreadSafeMatch(tag_name, SVGNames::svgTag)) || + (namespace_stack_.back() == kMathML && + ThreadSafeMatch(tag_name, MathMLNames::mathTag)) || +- (namespace_stack_.Contains(SVG) && namespace_stack_.back() == HTML && +- TokenExitsSVG(token)) || ++ IsHTMLIntegrationPointForEndTag(token) || + (namespace_stack_.Contains(kMathML) && + namespace_stack_.back() == HTML && TokenExitsMath(token))) { + namespace_stack_.pop_back(); +@@ -226,4 +218,59 @@ HTMLTreeBuilderSimulator::SimulatedToken HTMLTreeBuilderSimulator::Simulate( + return simulated_token; + } + ++// https://html.spec.whatwg.org/multipage/parsing.html#html-integration-point ++bool HTMLTreeBuilderSimulator::IsHTMLIntegrationPointForStartTag( ++ const CompactHTMLToken& token) const { ++ DCHECK(token.GetType() == HTMLToken::kStartTag) << token.GetType(); ++ ++ Namespace tokens_ns = namespace_stack_.back(); ++ const String& tag_name = token.Data(); ++ if (tokens_ns == kMathML) { ++ if (!ThreadSafeMatch(tag_name, MathMLNames::annotation_xmlTag)) ++ return false; ++ if (auto* encoding = token.GetAttributeItem(MathMLNames::encodingAttr)) { ++ return EqualIgnoringASCIICase(encoding->Value(), ""text/html"") || ++ EqualIgnoringASCIICase(encoding->Value(), ""application/xhtml+xml""); ++ } ++ } else if (tokens_ns == SVG) { ++ // FIXME: It's very fragile that we special case foreignObject here to be ++ // case-insensitive. ++ if (DeprecatedEqualIgnoringCase(tag_name, ++ SVGNames::foreignObjectTag.LocalName())) ++ return true; ++ return ThreadSafeMatch(tag_name, SVGNames::descTag) || ++ ThreadSafeMatch(tag_name, SVGNames::titleTag); ++ } ++ return false; ++} ++ ++// https://html.spec.whatwg.org/multipage/parsing.html#html-integration-point ++bool HTMLTreeBuilderSimulator::IsHTMLIntegrationPointForEndTag( ++ const CompactHTMLToken& token) const { ++ if (token.GetType() != HTMLToken::kEndTag) ++ return false; ++ ++ // If it's inside an HTML integration point, the top namespace is ++ // HTML, and its next namespace is not HTML. ++ if (namespace_stack_.back() != HTML) ++ return false; ++ if (namespace_stack_.size() < 2) ++ return false; ++ Namespace tokens_ns = namespace_stack_[namespace_stack_.size() - 2]; ++ ++ const String& tag_name = token.Data(); ++ if (tokens_ns == kMathML) ++ return ThreadSafeMatch(tag_name, MathMLNames::annotation_xmlTag); ++ if (tokens_ns == SVG) { ++ // FIXME: It's very fragile that we special case foreignObject here to be ++ // case-insensitive. ++ if (DeprecatedEqualIgnoringCase(tag_name, ++ SVGNames::foreignObjectTag.LocalName())) ++ return true; ++ return ThreadSafeMatch(tag_name, SVGNames::descTag) || ++ ThreadSafeMatch(tag_name, SVGNames::titleTag); ++ } ++ return false; ++} ++ + } // namespace blink",787,1118,2048 +4202,"static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans, + struct btrfs_root *root, + struct inode *dir, struct inode *inode, + const char *name, int name_len) +{ + struct btrfs_path *path; + int ret = 0; + struct extent_buffer *leaf; + struct btrfs_dir_item *di; + struct btrfs_key key; + u64 index; + u64 ino = btrfs_ino(inode); + u64 dir_ino = btrfs_ino(dir); + + path = btrfs_alloc_path(); + if (!path) { + ret = -ENOMEM; + goto out; + } + + path->leave_spinning = 1; + di = btrfs_lookup_dir_item(trans, root, path, dir_ino, + name, name_len, -1); + if (IS_ERR(di)) { + ret = PTR_ERR(di); + goto err; + } + if (!di) { + ret = -ENOENT; + goto err; + } + leaf = path->nodes[0]; + btrfs_dir_item_key_to_cpu(leaf, di, &key); + ret = btrfs_delete_one_dir_name(trans, root, path, di); + if (ret) + goto err; + btrfs_release_path(path); + + /* + * If we don't have dir index, we have to get it by looking up + * the inode ref, since we get the inode ref, remove it directly, + * it is unnecessary to do delayed deletion. + * + * But if we have dir index, needn't search inode ref to get it. + * Since the inode ref is close to the inode item, it is better + * that we delay to delete it, and just do this deletion when + * we update the inode item. + */ + if (BTRFS_I(inode)->dir_index) { + ret = btrfs_delayed_delete_inode_ref(inode); + if (!ret) { + index = BTRFS_I(inode)->dir_index; + goto skip_backref; + } + } + + ret = btrfs_del_inode_ref(trans, root, name, name_len, ino, + dir_ino, &index); + if (ret) { + btrfs_info(root->fs_info, + ""failed to delete reference to %.*s, inode %llu parent %llu"", + name_len, name, ino, dir_ino); + btrfs_abort_transaction(trans, root, ret); + goto err; + } +skip_backref: + ret = btrfs_delete_delayed_dir_index(trans, root, dir, index); + if (ret) { + btrfs_abort_transaction(trans, root, ret); + goto err; + } + + ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, + inode, dir_ino); + if (ret != 0 && ret != -ENOENT) { + btrfs_abort_transaction(trans, root, ret); + goto err; + } + + ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, + dir, index); + if (ret == -ENOENT) + ret = 0; + else if (ret) + btrfs_abort_transaction(trans, root, ret); +err: + btrfs_free_path(path); + if (ret) + goto out; + + btrfs_i_size_write(dir, dir->i_size - name_len * 2); + inode_inc_iversion(inode); + inode_inc_iversion(dir); + inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME; + ret = btrfs_update_inode(trans, root, dir); +out: + return ret; +} +",0,"static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans, + struct btrfs_root *root, + struct inode *dir, struct inode *inode, + const char *name, int name_len) +{ + struct btrfs_path *path; + int ret = 0; + struct extent_buffer *leaf; + struct btrfs_dir_item *di; + struct btrfs_key key; + u64 index; + u64 ino = btrfs_ino(inode); + u64 dir_ino = btrfs_ino(dir); + + path = btrfs_alloc_path(); + if (!path) { + ret = -ENOMEM; + goto out; + } + + path->leave_spinning = 1; + di = btrfs_lookup_dir_item(trans, root, path, dir_ino, + name, name_len, -1); + if (IS_ERR(di)) { + ret = PTR_ERR(di); + goto err; + } + if (!di) { + ret = -ENOENT; + goto err; + } + leaf = path->nodes[0]; + btrfs_dir_item_key_to_cpu(leaf, di, &key); + ret = btrfs_delete_one_dir_name(trans, root, path, di); + if (ret) + goto err; + btrfs_release_path(path); + + /* + * If we don't have dir index, we have to get it by looking up + * the inode ref, since we get the inode ref, remove it directly, + * it is unnecessary to do delayed deletion. + * + * But if we have dir index, needn't search inode ref to get it. + * Since the inode ref is close to the inode item, it is better + * that we delay to delete it, and just do this deletion when + * we update the inode item. + */ + if (BTRFS_I(inode)->dir_index) { + ret = btrfs_delayed_delete_inode_ref(inode); + if (!ret) { + index = BTRFS_I(inode)->dir_index; + goto skip_backref; + } + } + + ret = btrfs_del_inode_ref(trans, root, name, name_len, ino, + dir_ino, &index); + if (ret) { + btrfs_info(root->fs_info, + ""failed to delete reference to %.*s, inode %llu parent %llu"", + name_len, name, ino, dir_ino); + btrfs_abort_transaction(trans, root, ret); + goto err; + } +skip_backref: + ret = btrfs_delete_delayed_dir_index(trans, root, dir, index); + if (ret) { + btrfs_abort_transaction(trans, root, ret); + goto err; + } + + ret = btrfs_del_inode_ref_in_log(trans, root, name, name_len, + inode, dir_ino); + if (ret != 0 && ret != -ENOENT) { + btrfs_abort_transaction(trans, root, ret); + goto err; + } + + ret = btrfs_del_dir_entries_in_log(trans, root, name, name_len, + dir, index); + if (ret == -ENOENT) + ret = 0; + else if (ret) + btrfs_abort_transaction(trans, root, ret); +err: + btrfs_free_path(path); + if (ret) + goto out; + + btrfs_i_size_write(dir, dir->i_size - name_len * 2); + inode_inc_iversion(inode); + inode_inc_iversion(dir); + inode->i_ctime = dir->i_mtime = dir->i_ctime = CURRENT_TIME; + ret = btrfs_update_inode(trans, root, dir); +out: + return ret; +} +","@@ -4217,6 +4217,47 @@ static int truncate_space_check(struct btrfs_trans_handle *trans, + + } + ++static int truncate_inline_extent(struct inode *inode, ++ struct btrfs_path *path, ++ struct btrfs_key *found_key, ++ const u64 item_end, ++ const u64 new_size) ++{ ++ struct extent_buffer *leaf = path->nodes[0]; ++ int slot = path->slots[0]; ++ struct btrfs_file_extent_item *fi; ++ u32 size = (u32)(new_size - found_key->offset); ++ struct btrfs_root *root = BTRFS_I(inode)->root; ++ ++ fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item); ++ ++ if (btrfs_file_extent_compression(leaf, fi) != BTRFS_COMPRESS_NONE) { ++ loff_t offset = new_size; ++ loff_t page_end = ALIGN(offset, PAGE_CACHE_SIZE); ++ ++ /* ++ * Zero out the remaining of the last page of our inline extent, ++ * instead of directly truncating our inline extent here - that ++ * would be much more complex (decompressing all the data, then ++ * compressing the truncated data, which might be bigger than ++ * the size of the inline extent, resize the extent, etc). ++ * We release the path because to get the page we might need to ++ * read the extent item from disk (data not in the page cache). ++ */ ++ btrfs_release_path(path); ++ return btrfs_truncate_page(inode, offset, page_end - offset, 0); ++ } ++ ++ btrfs_set_file_extent_ram_bytes(leaf, fi, size); ++ size = btrfs_file_extent_calc_inline_size(size); ++ btrfs_truncate_item(root, path, size, 1); ++ ++ if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) ++ inode_sub_bytes(inode, item_end + 1 - new_size); ++ ++ return 0; ++} ++ + /* + * this can truncate away extent items, csum items and directory items. + * It starts at a high offset and removes keys until it can't find +@@ -4411,27 +4452,40 @@ int btrfs_truncate_inode_items(struct btrfs_trans_handle *trans, + * special encodings + */ + if (!del_item && +- btrfs_file_extent_compression(leaf, fi) == 0 && + btrfs_file_extent_encryption(leaf, fi) == 0 && + btrfs_file_extent_other_encoding(leaf, fi) == 0) { +- u32 size = new_size - found_key.offset; +- +- if (test_bit(BTRFS_ROOT_REF_COWS, &root->state)) +- inode_sub_bytes(inode, item_end + 1 - +- new_size); + + /* +- * update the ram bytes to properly reflect +- * the new size of our item ++ * Need to release path in order to truncate a ++ * compressed extent. So delete any accumulated ++ * extent items so far. + */ +- btrfs_set_file_extent_ram_bytes(leaf, fi, size); +- size = +- btrfs_file_extent_calc_inline_size(size); +- btrfs_truncate_item(root, path, size, 1); ++ if (btrfs_file_extent_compression(leaf, fi) != ++ BTRFS_COMPRESS_NONE && pending_del_nr) { ++ err = btrfs_del_items(trans, root, path, ++ pending_del_slot, ++ pending_del_nr); ++ if (err) { ++ btrfs_abort_transaction(trans, ++ root, ++ err); ++ goto error; ++ } ++ pending_del_nr = 0; ++ } ++ ++ err = truncate_inline_extent(inode, path, ++ &found_key, ++ item_end, ++ new_size); ++ if (err) { ++ btrfs_abort_transaction(trans, ++ root, err); ++ goto error; ++ } + } else if (test_bit(BTRFS_ROOT_REF_COWS, + &root->state)) { +- inode_sub_bytes(inode, item_end + 1 - +- found_key.offset); ++ inode_sub_bytes(inode, item_end + 1 - new_size); + } + } + delete:",756,1087,2048 +3502,"static void nci_rf_intf_activated_ntf_packet(struct nci_dev *ndev, + struct sk_buff *skb) +{ + struct nci_rf_intf_activated_ntf ntf; + __u8 *data = skb->data; + int err = NCI_STATUS_OK; + + ntf.rf_discovery_id = *data++; + ntf.rf_interface = *data++; + ntf.rf_protocol = *data++; + ntf.activation_rf_tech_and_mode = *data++; + ntf.max_data_pkt_payload_size = *data++; + ntf.initial_num_credits = *data++; + ntf.rf_tech_specific_params_len = *data++; + + pr_debug(""rf_discovery_id %d\n"", ntf.rf_discovery_id); + pr_debug(""rf_interface 0x%x\n"", ntf.rf_interface); + pr_debug(""rf_protocol 0x%x\n"", ntf.rf_protocol); + pr_debug(""activation_rf_tech_and_mode 0x%x\n"", + ntf.activation_rf_tech_and_mode); + pr_debug(""max_data_pkt_payload_size 0x%x\n"", + ntf.max_data_pkt_payload_size); + pr_debug(""initial_num_credits 0x%x\n"", + ntf.initial_num_credits); + pr_debug(""rf_tech_specific_params_len %d\n"", + ntf.rf_tech_specific_params_len); + + if (ntf.rf_tech_specific_params_len > 0) { + switch (ntf.activation_rf_tech_and_mode) { + case NCI_NFC_A_PASSIVE_POLL_MODE: + data = nci_extract_rf_params_nfca_passive_poll(ndev, + &(ntf.rf_tech_specific_params.nfca_poll), data); + break; + + case NCI_NFC_B_PASSIVE_POLL_MODE: + data = nci_extract_rf_params_nfcb_passive_poll(ndev, + &(ntf.rf_tech_specific_params.nfcb_poll), data); + break; + + case NCI_NFC_F_PASSIVE_POLL_MODE: + data = nci_extract_rf_params_nfcf_passive_poll(ndev, + &(ntf.rf_tech_specific_params.nfcf_poll), data); + break; + + default: + pr_err(""unsupported activation_rf_tech_and_mode 0x%x\n"", + ntf.activation_rf_tech_and_mode); + err = NCI_STATUS_RF_PROTOCOL_ERROR; + goto exit; + } + } + + ntf.data_exch_rf_tech_and_mode = *data++; + ntf.data_exch_tx_bit_rate = *data++; + ntf.data_exch_rx_bit_rate = *data++; + ntf.activation_params_len = *data++; + + pr_debug(""data_exch_rf_tech_and_mode 0x%x\n"", + ntf.data_exch_rf_tech_and_mode); + pr_debug(""data_exch_tx_bit_rate 0x%x\n"", ntf.data_exch_tx_bit_rate); + pr_debug(""data_exch_rx_bit_rate 0x%x\n"", ntf.data_exch_rx_bit_rate); + pr_debug(""activation_params_len %d\n"", ntf.activation_params_len); + + if (ntf.activation_params_len > 0) { + switch (ntf.rf_interface) { + case NCI_RF_INTERFACE_ISO_DEP: + err = nci_extract_activation_params_iso_dep(ndev, + &ntf, data); + break; + + case NCI_RF_INTERFACE_FRAME: + /* no activation params */ + break; + + default: + pr_err(""unsupported rf_interface 0x%x\n"", + ntf.rf_interface); + err = NCI_STATUS_RF_PROTOCOL_ERROR; + break; + } + } + +exit: + if (err == NCI_STATUS_OK) { + ndev->max_data_pkt_payload_size = ntf.max_data_pkt_payload_size; + ndev->initial_num_credits = ntf.initial_num_credits; + + /* set the available credits to initial value */ + atomic_set(&ndev->credits_cnt, ndev->initial_num_credits); + } + + if (atomic_read(&ndev->state) == NCI_DISCOVERY) { + /* A single target was found and activated automatically */ + atomic_set(&ndev->state, NCI_POLL_ACTIVE); + if (err == NCI_STATUS_OK) + nci_target_auto_activated(ndev, &ntf); + } else { /* ndev->state == NCI_W4_HOST_SELECT */ + /* A selected target was activated, so complete the request */ + atomic_set(&ndev->state, NCI_POLL_ACTIVE); + nci_req_complete(ndev, err); + } +} +",0,"static void nci_rf_intf_activated_ntf_packet(struct nci_dev *ndev, + struct sk_buff *skb) +{ + struct nci_rf_intf_activated_ntf ntf; + __u8 *data = skb->data; + int err = NCI_STATUS_OK; + + ntf.rf_discovery_id = *data++; + ntf.rf_interface = *data++; + ntf.rf_protocol = *data++; + ntf.activation_rf_tech_and_mode = *data++; + ntf.max_data_pkt_payload_size = *data++; + ntf.initial_num_credits = *data++; + ntf.rf_tech_specific_params_len = *data++; + + pr_debug(""rf_discovery_id %d\n"", ntf.rf_discovery_id); + pr_debug(""rf_interface 0x%x\n"", ntf.rf_interface); + pr_debug(""rf_protocol 0x%x\n"", ntf.rf_protocol); + pr_debug(""activation_rf_tech_and_mode 0x%x\n"", + ntf.activation_rf_tech_and_mode); + pr_debug(""max_data_pkt_payload_size 0x%x\n"", + ntf.max_data_pkt_payload_size); + pr_debug(""initial_num_credits 0x%x\n"", + ntf.initial_num_credits); + pr_debug(""rf_tech_specific_params_len %d\n"", + ntf.rf_tech_specific_params_len); + + if (ntf.rf_tech_specific_params_len > 0) { + switch (ntf.activation_rf_tech_and_mode) { + case NCI_NFC_A_PASSIVE_POLL_MODE: + data = nci_extract_rf_params_nfca_passive_poll(ndev, + &(ntf.rf_tech_specific_params.nfca_poll), data); + break; + + case NCI_NFC_B_PASSIVE_POLL_MODE: + data = nci_extract_rf_params_nfcb_passive_poll(ndev, + &(ntf.rf_tech_specific_params.nfcb_poll), data); + break; + + case NCI_NFC_F_PASSIVE_POLL_MODE: + data = nci_extract_rf_params_nfcf_passive_poll(ndev, + &(ntf.rf_tech_specific_params.nfcf_poll), data); + break; + + default: + pr_err(""unsupported activation_rf_tech_and_mode 0x%x\n"", + ntf.activation_rf_tech_and_mode); + err = NCI_STATUS_RF_PROTOCOL_ERROR; + goto exit; + } + } + + ntf.data_exch_rf_tech_and_mode = *data++; + ntf.data_exch_tx_bit_rate = *data++; + ntf.data_exch_rx_bit_rate = *data++; + ntf.activation_params_len = *data++; + + pr_debug(""data_exch_rf_tech_and_mode 0x%x\n"", + ntf.data_exch_rf_tech_and_mode); + pr_debug(""data_exch_tx_bit_rate 0x%x\n"", ntf.data_exch_tx_bit_rate); + pr_debug(""data_exch_rx_bit_rate 0x%x\n"", ntf.data_exch_rx_bit_rate); + pr_debug(""activation_params_len %d\n"", ntf.activation_params_len); + + if (ntf.activation_params_len > 0) { + switch (ntf.rf_interface) { + case NCI_RF_INTERFACE_ISO_DEP: + err = nci_extract_activation_params_iso_dep(ndev, + &ntf, data); + break; + + case NCI_RF_INTERFACE_FRAME: + /* no activation params */ + break; + + default: + pr_err(""unsupported rf_interface 0x%x\n"", + ntf.rf_interface); + err = NCI_STATUS_RF_PROTOCOL_ERROR; + break; + } + } + +exit: + if (err == NCI_STATUS_OK) { + ndev->max_data_pkt_payload_size = ntf.max_data_pkt_payload_size; + ndev->initial_num_credits = ntf.initial_num_credits; + + /* set the available credits to initial value */ + atomic_set(&ndev->credits_cnt, ndev->initial_num_credits); + } + + if (atomic_read(&ndev->state) == NCI_DISCOVERY) { + /* A single target was found and activated automatically */ + atomic_set(&ndev->state, NCI_POLL_ACTIVE); + if (err == NCI_STATUS_OK) + nci_target_auto_activated(ndev, &ntf); + } else { /* ndev->state == NCI_W4_HOST_SELECT */ + /* A selected target was activated, so complete the request */ + atomic_set(&ndev->state, NCI_POLL_ACTIVE); + nci_req_complete(ndev, err); + } +} +","@@ -106,7 +106,7 @@ static __u8 *nci_extract_rf_params_nfca_passive_poll(struct nci_dev *ndev, + nfca_poll->sens_res = __le16_to_cpu(*((__u16 *)data)); + data += 2; + +- nfca_poll->nfcid1_len = *data++; ++ nfca_poll->nfcid1_len = min_t(__u8, *data++, NFC_NFCID1_MAXSIZE); + + pr_debug(""sens_res 0x%x, nfcid1_len %d\n"", + nfca_poll->sens_res, nfca_poll->nfcid1_len); +@@ -130,7 +130,7 @@ static __u8 *nci_extract_rf_params_nfcb_passive_poll(struct nci_dev *ndev, + struct rf_tech_specific_params_nfcb_poll *nfcb_poll, + __u8 *data) + { +- nfcb_poll->sensb_res_len = *data++; ++ nfcb_poll->sensb_res_len = min_t(__u8, *data++, NFC_SENSB_RES_MAXSIZE); + + pr_debug(""sensb_res_len %d\n"", nfcb_poll->sensb_res_len); + +@@ -145,7 +145,7 @@ static __u8 *nci_extract_rf_params_nfcf_passive_poll(struct nci_dev *ndev, + __u8 *data) + { + nfcf_poll->bit_rate = *data++; +- nfcf_poll->sensf_res_len = *data++; ++ nfcf_poll->sensf_res_len = min_t(__u8, *data++, NFC_SENSF_RES_MAXSIZE); + + pr_debug(""bit_rate %d, sensf_res_len %d\n"", + nfcf_poll->bit_rate, nfcf_poll->sensf_res_len); +@@ -331,7 +331,7 @@ static int nci_extract_activation_params_iso_dep(struct nci_dev *ndev, + switch (ntf->activation_rf_tech_and_mode) { + case NCI_NFC_A_PASSIVE_POLL_MODE: + nfca_poll = &ntf->activation_params.nfca_poll_iso_dep; +- nfca_poll->rats_res_len = *data++; ++ nfca_poll->rats_res_len = min_t(__u8, *data++, 20); + pr_debug(""rats_res_len %d\n"", nfca_poll->rats_res_len); + if (nfca_poll->rats_res_len > 0) { + memcpy(nfca_poll->rats_res, +@@ -341,7 +341,7 @@ static int nci_extract_activation_params_iso_dep(struct nci_dev *ndev, + + case NCI_NFC_B_PASSIVE_POLL_MODE: + nfcb_poll = &ntf->activation_params.nfcb_poll_iso_dep; +- nfcb_poll->attrib_res_len = *data++; ++ nfcb_poll->attrib_res_len = min_t(__u8, *data++, 50); + pr_debug(""attrib_res_len %d\n"", nfcb_poll->attrib_res_len); + if (nfcb_poll->attrib_res_len > 0) { + memcpy(nfcb_poll->attrib_res,",965,1296,2048 +17827,"static int megasas_ctrl_get_info(MegasasState *s, MegasasCmd *cmd) +{ + PCIDevice *pci_dev = PCI_DEVICE(s); + PCIDeviceClass *pci_class = PCI_DEVICE_GET_CLASS(pci_dev); + MegasasBaseClass *base_class = MEGASAS_DEVICE_GET_CLASS(s); + struct mfi_ctrl_info info; + size_t dcmd_size = sizeof(info); + BusChild *kid; + int num_pd_disks = 0; + + memset(&info, 0x0, dcmd_size); + if (cmd->iov_size < dcmd_size) { + trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size, + dcmd_size); + return MFI_STAT_INVALID_PARAMETER; + } + + info.pci.vendor = cpu_to_le16(pci_class->vendor_id); + info.pci.device = cpu_to_le16(pci_class->device_id); + info.pci.subvendor = cpu_to_le16(pci_class->subsystem_vendor_id); + info.pci.subdevice = cpu_to_le16(pci_class->subsystem_id); + + /* + * For some reason the firmware supports + * only up to 8 device ports. + * Despite supporting a far larger number + * of devices for the physical devices. + * So just display the first 8 devices + * in the device port list, independent + * of how many logical devices are actually + * present. + */ + info.host.type = MFI_INFO_HOST_PCIE; + info.device.type = MFI_INFO_DEV_SAS3G; + info.device.port_count = 8; + QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) { + SCSIDevice *sdev = SCSI_DEVICE(kid->child); + uint16_t pd_id; + + if (num_pd_disks < 8) { + pd_id = ((sdev->id & 0xFF) << 8) | (sdev->lun & 0xFF); + info.device.port_addr[num_pd_disks] = + cpu_to_le64(megasas_get_sata_addr(pd_id)); + } + num_pd_disks++; + } + + memcpy(info.product_name, base_class->product_name, 24); + snprintf(info.serial_number, 32, ""%s"", s->hba_serial); + snprintf(info.package_version, 0x60, ""%s-QEMU"", qemu_hw_version()); + memcpy(info.image_component[0].name, ""APP"", 3); + snprintf(info.image_component[0].version, 10, ""%s-QEMU"", + base_class->product_version); + memcpy(info.image_component[0].build_date, ""Apr 1 2014"", 11); + memcpy(info.image_component[0].build_time, ""12:34:56"", 8); + info.image_component_count = 1; + if (pci_dev->has_rom) { + uint8_t biosver[32]; + uint8_t *ptr; + + ptr = memory_region_get_ram_ptr(&pci_dev->rom); + memcpy(biosver, ptr + 0x41, 31); + memcpy(info.image_component[1].name, ""BIOS"", 4); + memcpy(info.image_component[1].version, biosver, + strlen((const char *)biosver)); + } + info.current_fw_time = cpu_to_le32(megasas_fw_time()); + info.max_arms = 32; + info.max_spans = 8; + info.max_arrays = MEGASAS_MAX_ARRAYS; + info.max_lds = MFI_MAX_LD; + info.max_cmds = cpu_to_le16(s->fw_cmds); + info.max_sg_elements = cpu_to_le16(s->fw_sge); + info.max_request_size = cpu_to_le32(MEGASAS_MAX_SECTORS); + if (!megasas_is_jbod(s)) + info.lds_present = cpu_to_le16(num_pd_disks); + info.pd_present = cpu_to_le16(num_pd_disks); + info.pd_disks_present = cpu_to_le16(num_pd_disks); + info.hw_present = cpu_to_le32(MFI_INFO_HW_NVRAM | + MFI_INFO_HW_MEM | + MFI_INFO_HW_FLASH); + info.memory_size = cpu_to_le16(512); + info.nvram_size = cpu_to_le16(32); + info.flash_size = cpu_to_le16(16); + info.raid_levels = cpu_to_le32(MFI_INFO_RAID_0); + info.adapter_ops = cpu_to_le32(MFI_INFO_AOPS_RBLD_RATE | + MFI_INFO_AOPS_SELF_DIAGNOSTIC | + MFI_INFO_AOPS_MIXED_ARRAY); + info.ld_ops = cpu_to_le32(MFI_INFO_LDOPS_DISK_CACHE_POLICY | + MFI_INFO_LDOPS_ACCESS_POLICY | + MFI_INFO_LDOPS_IO_POLICY | + MFI_INFO_LDOPS_WRITE_POLICY | + MFI_INFO_LDOPS_READ_POLICY); + info.max_strips_per_io = cpu_to_le16(s->fw_sge); + info.stripe_sz_ops.min = 3; + info.stripe_sz_ops.max = ctz32(MEGASAS_MAX_SECTORS + 1); + info.properties.pred_fail_poll_interval = cpu_to_le16(300); + info.properties.intr_throttle_cnt = cpu_to_le16(16); + info.properties.intr_throttle_timeout = cpu_to_le16(50); + info.properties.rebuild_rate = 30; + info.properties.patrol_read_rate = 30; + info.properties.bgi_rate = 30; + info.properties.cc_rate = 30; + info.properties.recon_rate = 30; + info.properties.cache_flush_interval = 4; + info.properties.spinup_drv_cnt = 2; + info.properties.spinup_delay = 6; + info.properties.ecc_bucket_size = 15; + info.properties.ecc_bucket_leak_rate = cpu_to_le16(1440); + info.properties.expose_encl_devices = 1; + info.properties.OnOffProperties = cpu_to_le32(MFI_CTRL_PROP_EnableJBOD); + info.pd_ops = cpu_to_le32(MFI_INFO_PDOPS_FORCE_ONLINE | + MFI_INFO_PDOPS_FORCE_OFFLINE); + info.pd_mix_support = cpu_to_le32(MFI_INFO_PDMIX_SAS | + MFI_INFO_PDMIX_SATA | + MFI_INFO_PDMIX_LD); + + cmd->iov_size -= dma_buf_read((uint8_t *)&info, dcmd_size, &cmd->qsg); + return MFI_STAT_OK; +} +",1,"static int megasas_ctrl_get_info(MegasasState *s, MegasasCmd *cmd) +{ + PCIDevice *pci_dev = PCI_DEVICE(s); + PCIDeviceClass *pci_class = PCI_DEVICE_GET_CLASS(pci_dev); + MegasasBaseClass *base_class = MEGASAS_DEVICE_GET_CLASS(s); + struct mfi_ctrl_info info; + size_t dcmd_size = sizeof(info); + BusChild *kid; + int num_pd_disks = 0; + + memset(&info, 0x0, dcmd_size); + if (cmd->iov_size < dcmd_size) { + trace_megasas_dcmd_invalid_xfer_len(cmd->index, cmd->iov_size, + dcmd_size); + return MFI_STAT_INVALID_PARAMETER; + } + + info.pci.vendor = cpu_to_le16(pci_class->vendor_id); + info.pci.device = cpu_to_le16(pci_class->device_id); + info.pci.subvendor = cpu_to_le16(pci_class->subsystem_vendor_id); + info.pci.subdevice = cpu_to_le16(pci_class->subsystem_id); + + /* + * For some reason the firmware supports + * only up to 8 device ports. + * Despite supporting a far larger number + * of devices for the physical devices. + * So just display the first 8 devices + * in the device port list, independent + * of how many logical devices are actually + * present. + */ + info.host.type = MFI_INFO_HOST_PCIE; + info.device.type = MFI_INFO_DEV_SAS3G; + info.device.port_count = 8; + QTAILQ_FOREACH(kid, &s->bus.qbus.children, sibling) { + SCSIDevice *sdev = SCSI_DEVICE(kid->child); + uint16_t pd_id; + + if (num_pd_disks < 8) { + pd_id = ((sdev->id & 0xFF) << 8) | (sdev->lun & 0xFF); + info.device.port_addr[num_pd_disks] = + cpu_to_le64(megasas_get_sata_addr(pd_id)); + } + num_pd_disks++; + } + + memcpy(info.product_name, base_class->product_name, 24); + snprintf(info.serial_number, 32, ""%s"", s->hba_serial); + snprintf(info.package_version, 0x60, ""%s-QEMU"", qemu_hw_version()); + memcpy(info.image_component[0].name, ""APP"", 3); + snprintf(info.image_component[0].version, 10, ""%s-QEMU"", + base_class->product_version); + memcpy(info.image_component[0].build_date, ""Apr 1 2014"", 11); + memcpy(info.image_component[0].build_time, ""12:34:56"", 8); + info.image_component_count = 1; + if (pci_dev->has_rom) { + uint8_t biosver[32]; + uint8_t *ptr; + + ptr = memory_region_get_ram_ptr(&pci_dev->rom); + memcpy(biosver, ptr + 0x41, 31); + biosver[31] = 0; + memcpy(info.image_component[1].name, ""BIOS"", 4); + memcpy(info.image_component[1].version, biosver, + strlen((const char *)biosver)); + } + info.current_fw_time = cpu_to_le32(megasas_fw_time()); + info.max_arms = 32; + info.max_spans = 8; + info.max_arrays = MEGASAS_MAX_ARRAYS; + info.max_lds = MFI_MAX_LD; + info.max_cmds = cpu_to_le16(s->fw_cmds); + info.max_sg_elements = cpu_to_le16(s->fw_sge); + info.max_request_size = cpu_to_le32(MEGASAS_MAX_SECTORS); + if (!megasas_is_jbod(s)) + info.lds_present = cpu_to_le16(num_pd_disks); + info.pd_present = cpu_to_le16(num_pd_disks); + info.pd_disks_present = cpu_to_le16(num_pd_disks); + info.hw_present = cpu_to_le32(MFI_INFO_HW_NVRAM | + MFI_INFO_HW_MEM | + MFI_INFO_HW_FLASH); + info.memory_size = cpu_to_le16(512); + info.nvram_size = cpu_to_le16(32); + info.flash_size = cpu_to_le16(16); + info.raid_levels = cpu_to_le32(MFI_INFO_RAID_0); + info.adapter_ops = cpu_to_le32(MFI_INFO_AOPS_RBLD_RATE | + MFI_INFO_AOPS_SELF_DIAGNOSTIC | + MFI_INFO_AOPS_MIXED_ARRAY); + info.ld_ops = cpu_to_le32(MFI_INFO_LDOPS_DISK_CACHE_POLICY | + MFI_INFO_LDOPS_ACCESS_POLICY | + MFI_INFO_LDOPS_IO_POLICY | + MFI_INFO_LDOPS_WRITE_POLICY | + MFI_INFO_LDOPS_READ_POLICY); + info.max_strips_per_io = cpu_to_le16(s->fw_sge); + info.stripe_sz_ops.min = 3; + info.stripe_sz_ops.max = ctz32(MEGASAS_MAX_SECTORS + 1); + info.properties.pred_fail_poll_interval = cpu_to_le16(300); + info.properties.intr_throttle_cnt = cpu_to_le16(16); + info.properties.intr_throttle_timeout = cpu_to_le16(50); + info.properties.rebuild_rate = 30; + info.properties.patrol_read_rate = 30; + info.properties.bgi_rate = 30; + info.properties.cc_rate = 30; + info.properties.recon_rate = 30; + info.properties.cache_flush_interval = 4; + info.properties.spinup_drv_cnt = 2; + info.properties.spinup_delay = 6; + info.properties.ecc_bucket_size = 15; + info.properties.ecc_bucket_leak_rate = cpu_to_le16(1440); + info.properties.expose_encl_devices = 1; + info.properties.OnOffProperties = cpu_to_le32(MFI_CTRL_PROP_EnableJBOD); + info.pd_ops = cpu_to_le32(MFI_INFO_PDOPS_FORCE_ONLINE | + MFI_INFO_PDOPS_FORCE_OFFLINE); + info.pd_mix_support = cpu_to_le32(MFI_INFO_PDMIX_SAS | + MFI_INFO_PDMIX_SATA | + MFI_INFO_PDMIX_LD); + + cmd->iov_size -= dma_buf_read((uint8_t *)&info, dcmd_size, &cmd->qsg); + return MFI_STAT_OK; +} +","@@ -773,6 +773,7 @@ static int megasas_ctrl_get_info(MegasasState *s, MegasasCmd *cmd) + + ptr = memory_region_get_ram_ptr(&pci_dev->rom); + memcpy(biosver, ptr + 0x41, 31); ++ biosver[31] = 0; + memcpy(info.image_component[1].name, ""BIOS"", 4); + memcpy(info.image_component[1].version, biosver, + strlen((const char *)biosver));",1465,1796,2048 +7764,"static void write_tIME_chunk(Image *image,png_struct *ping,png_info *info, + const char *timestamp,ExceptionInfo *exception) +{ + int + ret; + + int + day, + hour, + minute, + month, + second, + year; + + int + addhours=0, + addminutes=0; + + png_time + ptime; + + assert(timestamp != (const char *) NULL); + LogMagickEvent(CoderEvent,GetMagickModule(), + "" Writing tIME chunk: timestamp property is %30s\n"",timestamp); + ret=sscanf(timestamp,""%d-%d-%dT%d:%d:%d"",&year,&month,&day,&hour, + &minute, &second); + addhours=0; + addminutes=0; + ret=sscanf(timestamp,""%d-%d-%dT%d:%d:%d%d:%d"",&year,&month,&day,&hour, + &minute, &second, &addhours, &addminutes); + LogMagickEvent(CoderEvent,GetMagickModule(), + "" Date format specified for png:tIME=%s"" ,timestamp); + LogMagickEvent(CoderEvent,GetMagickModule(), + "" ret=%d,y=%d, m=%d, d=%d, h=%d, m=%d, s=%d, ah=%d, as=%d"", + ret,year,month,day,hour,minute,second,addhours,addminutes); + if (ret < 6) + { + LogMagickEvent(CoderEvent,GetMagickModule(), + "" Invalid date, ret=%d"",ret); + (void) ThrowMagickException(exception,GetMagickModule(),CoderError, + ""Invalid date format specified for png:tIME"",""`%s' (ret=%d)"", + image->filename,ret); + return; + } + if (addhours < 0) + { + addhours+=24; + addminutes=-addminutes; + day--; + } + hour+=addhours; + minute+=addminutes; + if (day == 0) + { + month--; + day=31; + if(month == 2) + day=28; + else + { + if(month == 4 || month == 6 || month == 9 || month == 11) + day=30; + else + day=31; + } + } + if (month == 0) + { + month++; + year--; + } + if (minute > 59) + { + hour++; + minute-=60; + } + if (hour > 23) + { + day ++; + hour -=24; + } + if (hour < 0) + { + day --; + hour +=24; + } + /* To do: fix this for leap years */ + if (day > 31 || (month == 2 && day > 28) || ((month == 4 || month == 6 || + month == 9 || month == 11) && day > 30)) + { + month++; + day = 1; + } + if (month > 12) + { + year++; + month=1; + } + + ptime.year = year; + ptime.month = month; + ptime.day = day; + ptime.hour = hour; + ptime.minute = minute; + ptime.second = second; + + LogMagickEvent(CoderEvent,GetMagickModule(), + "" png_set_tIME: y=%d, m=%d, d=%d, h=%d, m=%d, s=%d, ah=%d, am=%d"", + ptime.year, ptime.month, ptime.day, ptime.hour, ptime.minute, + ptime.second, addhours, addminutes); + png_set_tIME(ping,info,&ptime); +} +",0,"static void write_tIME_chunk(Image *image,png_struct *ping,png_info *info, + const char *timestamp,ExceptionInfo *exception) +{ + int + ret; + + int + day, + hour, + minute, + month, + second, + year; + + int + addhours=0, + addminutes=0; + + png_time + ptime; + + assert(timestamp != (const char *) NULL); + LogMagickEvent(CoderEvent,GetMagickModule(), + "" Writing tIME chunk: timestamp property is %30s\n"",timestamp); + ret=sscanf(timestamp,""%d-%d-%dT%d:%d:%d"",&year,&month,&day,&hour, + &minute, &second); + addhours=0; + addminutes=0; + ret=sscanf(timestamp,""%d-%d-%dT%d:%d:%d%d:%d"",&year,&month,&day,&hour, + &minute, &second, &addhours, &addminutes); + LogMagickEvent(CoderEvent,GetMagickModule(), + "" Date format specified for png:tIME=%s"" ,timestamp); + LogMagickEvent(CoderEvent,GetMagickModule(), + "" ret=%d,y=%d, m=%d, d=%d, h=%d, m=%d, s=%d, ah=%d, as=%d"", + ret,year,month,day,hour,minute,second,addhours,addminutes); + if (ret < 6) + { + LogMagickEvent(CoderEvent,GetMagickModule(), + "" Invalid date, ret=%d"",ret); + (void) ThrowMagickException(exception,GetMagickModule(),CoderError, + ""Invalid date format specified for png:tIME"",""`%s' (ret=%d)"", + image->filename,ret); + return; + } + if (addhours < 0) + { + addhours+=24; + addminutes=-addminutes; + day--; + } + hour+=addhours; + minute+=addminutes; + if (day == 0) + { + month--; + day=31; + if(month == 2) + day=28; + else + { + if(month == 4 || month == 6 || month == 9 || month == 11) + day=30; + else + day=31; + } + } + if (month == 0) + { + month++; + year--; + } + if (minute > 59) + { + hour++; + minute-=60; + } + if (hour > 23) + { + day ++; + hour -=24; + } + if (hour < 0) + { + day --; + hour +=24; + } + /* To do: fix this for leap years */ + if (day > 31 || (month == 2 && day > 28) || ((month == 4 || month == 6 || + month == 9 || month == 11) && day > 30)) + { + month++; + day = 1; + } + if (month > 12) + { + year++; + month=1; + } + + ptime.year = year; + ptime.month = month; + ptime.day = day; + ptime.hour = hour; + ptime.minute = minute; + ptime.second = second; + + LogMagickEvent(CoderEvent,GetMagickModule(), + "" png_set_tIME: y=%d, m=%d, d=%d, h=%d, m=%d, s=%d, ah=%d, am=%d"", + ptime.year, ptime.month, ptime.day, ptime.hour, ptime.minute, + ptime.second, addhours, addminutes); + png_set_tIME(ping,info,&ptime); +} +","@@ -4560,7 +4560,11 @@ static Image *ReadOneJNGImage(MngInfo *mng_info, + chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); + + if (chunk == (unsigned char *) NULL) +- ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); ++ { ++ DestroyJNG(NULL,&color_image,&color_image_info, ++ &alpha_image,&alpha_image_info); ++ ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); ++ } + + for (i=0; i < (ssize_t) length; i++) + { +@@ -4587,13 +4591,12 @@ static Image *ReadOneJNGImage(MngInfo *mng_info, + jng_width=(png_uint_32)mng_get_long(p); + jng_height=(png_uint_32)mng_get_long(&p[4]); + if ((jng_width == 0) || (jng_height == 0)) +- { +- DestroyJNG(chunk,&color_image,&color_image_info, +- &alpha_image,&alpha_image_info); +- +- ThrowReaderException(CorruptImageError, +- ""NegativeOrZeroImageSize""); +- } ++ { ++ DestroyJNG(chunk,&color_image,&color_image_info, ++ &alpha_image,&alpha_image_info); ++ ThrowReaderException(CorruptImageError, ++ ""NegativeOrZeroImageSize""); ++ } + jng_color_type=p[8]; + jng_image_sample_depth=p[9]; + jng_image_compression_method=p[10];",847,1178,2048 +1190,"_gnutls_compressed2ciphertext (gnutls_session_t session, + opaque * cipher_data, int cipher_size, + gnutls_datum_t compressed, + content_type_t _type, int random_pad, + record_parameters_st * params) +{ + uint8_t MAC[MAX_HASH_SIZE]; + uint16_t c_length; + uint8_t pad; + int length, ret; + uint8_t type = _type; + opaque preamble[PREAMBLE_SIZE]; + int preamble_size; + int hash_size = _gnutls_hash_get_algo_len (params->mac_algorithm); + int blocksize = gnutls_cipher_get_block_size (params->cipher_algorithm); + cipher_type_t block_algo = + _gnutls_cipher_is_block (params->cipher_algorithm); + opaque *data_ptr; + int ver = gnutls_protocol_get_version (session); + + + /* Initialize MAC */ + + c_length = _gnutls_conv_uint16 (compressed.size); + + if (params->mac_algorithm != GNUTLS_MAC_NULL) + { /* actually when the algorithm in not the NULL one */ + digest_hd_st td; + + ret = mac_init (&td, params->mac_algorithm, + params->write.mac_secret.data, + params->write.mac_secret.size, ver); + + if (ret < 0) + { + gnutls_assert (); + return ret; + } + preamble_size = + make_preamble (UINT64DATA + (params->write.sequence_number), + type, c_length, ver, preamble); + mac_hash (&td, preamble, preamble_size, ver); + mac_hash (&td, compressed.data, compressed.size, ver); + mac_deinit (&td, MAC, ver); + } + + + /* Calculate the encrypted length (padding etc.) + */ + length = + calc_enc_length (session, compressed.size, hash_size, &pad, + random_pad, block_algo, blocksize); + if (length < 0) + { + gnutls_assert (); + return length; + } + + /* copy the encrypted data to cipher_data. + */ + if (cipher_size < length) + { + gnutls_assert (); + return GNUTLS_E_MEMORY_ERROR; + } + + data_ptr = cipher_data; + if (block_algo == CIPHER_BLOCK && + _gnutls_version_has_explicit_iv (session->security_parameters.version)) + { + /* copy the random IV. + */ + ret = _gnutls_rnd (GNUTLS_RND_NONCE, data_ptr, blocksize); + if (ret < 0) + { + gnutls_assert (); + return ret; + } + + data_ptr += blocksize; + } + + memcpy (data_ptr, compressed.data, compressed.size); + data_ptr += compressed.size; + + if (hash_size > 0) + { + memcpy (data_ptr, MAC, hash_size); + data_ptr += hash_size; + } + if (block_algo == CIPHER_BLOCK && pad > 0) + { + memset (data_ptr, pad - 1, pad); + } + + + /* Actual encryption (inplace). + */ + ret = + _gnutls_cipher_encrypt (¶ms->write.cipher_state, cipher_data, length); + if (ret < 0) + { + gnutls_assert (); + return ret; + } + + return length; +} +",0,"_gnutls_compressed2ciphertext (gnutls_session_t session, + opaque * cipher_data, int cipher_size, + gnutls_datum_t compressed, + content_type_t _type, int random_pad, + record_parameters_st * params) +{ + uint8_t MAC[MAX_HASH_SIZE]; + uint16_t c_length; + uint8_t pad; + int length, ret; + uint8_t type = _type; + opaque preamble[PREAMBLE_SIZE]; + int preamble_size; + int hash_size = _gnutls_hash_get_algo_len (params->mac_algorithm); + int blocksize = gnutls_cipher_get_block_size (params->cipher_algorithm); + cipher_type_t block_algo = + _gnutls_cipher_is_block (params->cipher_algorithm); + opaque *data_ptr; + int ver = gnutls_protocol_get_version (session); + + + /* Initialize MAC */ + + c_length = _gnutls_conv_uint16 (compressed.size); + + if (params->mac_algorithm != GNUTLS_MAC_NULL) + { /* actually when the algorithm in not the NULL one */ + digest_hd_st td; + + ret = mac_init (&td, params->mac_algorithm, + params->write.mac_secret.data, + params->write.mac_secret.size, ver); + + if (ret < 0) + { + gnutls_assert (); + return ret; + } + preamble_size = + make_preamble (UINT64DATA + (params->write.sequence_number), + type, c_length, ver, preamble); + mac_hash (&td, preamble, preamble_size, ver); + mac_hash (&td, compressed.data, compressed.size, ver); + mac_deinit (&td, MAC, ver); + } + + + /* Calculate the encrypted length (padding etc.) + */ + length = + calc_enc_length (session, compressed.size, hash_size, &pad, + random_pad, block_algo, blocksize); + if (length < 0) + { + gnutls_assert (); + return length; + } + + /* copy the encrypted data to cipher_data. + */ + if (cipher_size < length) + { + gnutls_assert (); + return GNUTLS_E_MEMORY_ERROR; + } + + data_ptr = cipher_data; + if (block_algo == CIPHER_BLOCK && + _gnutls_version_has_explicit_iv (session->security_parameters.version)) + { + /* copy the random IV. + */ + ret = _gnutls_rnd (GNUTLS_RND_NONCE, data_ptr, blocksize); + if (ret < 0) + { + gnutls_assert (); + return ret; + } + + data_ptr += blocksize; + } + + memcpy (data_ptr, compressed.data, compressed.size); + data_ptr += compressed.size; + + if (hash_size > 0) + { + memcpy (data_ptr, MAC, hash_size); + data_ptr += hash_size; + } + if (block_algo == CIPHER_BLOCK && pad > 0) + { + memset (data_ptr, pad - 1, pad); + } + + + /* Actual encryption (inplace). + */ + ret = + _gnutls_cipher_encrypt (¶ms->write.cipher_state, cipher_data, length); + if (ret < 0) + { + gnutls_assert (); + return ret; + } + + return length; +} +","@@ -511,14 +511,13 @@ _gnutls_ciphertext2compressed (gnutls_session_t session, + { + ciphertext.size -= blocksize; + ciphertext.data += blocksize; +- +- if (ciphertext.size == 0) +- { +- gnutls_assert (); +- return GNUTLS_E_DECRYPTION_FAILED; +- } + } + ++ if (ciphertext.size < hash_size) ++ { ++ gnutls_assert (); ++ return GNUTLS_E_DECRYPTION_FAILED; ++ } + pad = ciphertext.data[ciphertext.size - 1] + 1; /* pad */ + + if ((int) pad > (int) ciphertext.size - hash_size)",706,1037,2048 +18118,"grub_ext2_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock) +{ + struct grub_ext2_data *data = node->data; + struct grub_ext2_inode *inode = &node->inode; + int blknr = -1; + unsigned int blksz = EXT2_BLOCK_SIZE (data); + int log2_blksz = LOG2_EXT2_BLOCK_SIZE (data); + + if (grub_le_to_cpu32(inode->flags) & EXT4_EXTENTS_FLAG) + { +#ifndef _MSC_VER + char buf[EXT2_BLOCK_SIZE (data)]; +#else + char * buf = grub_malloc (EXT2_BLOCK_SIZE(data)); +#endif + struct grub_ext4_extent_header *leaf; + struct grub_ext4_extent *ext; + int i; + + leaf = grub_ext4_find_leaf (data, buf, + (struct grub_ext4_extent_header *) inode->blocks.dir_blocks, + fileblock); + if (! leaf) + { + grub_error (GRUB_ERR_BAD_FS, ""invalid extent""); + return -1; + } + + ext = (struct grub_ext4_extent *) (leaf + 1); + for (i = 0; i < grub_le_to_cpu16 (leaf->entries); i++) + { + if (fileblock < grub_le_to_cpu32 (ext[i].block)) + break; + } + + if (--i >= 0) + { + fileblock -= grub_le_to_cpu32 (ext[i].block); + if (fileblock >= grub_le_to_cpu16 (ext[i].len)) + return 0; + else + { + grub_disk_addr_t start; + + start = grub_le_to_cpu16 (ext[i].start_hi); + start = (start << 32) + grub_le_to_cpu32 (ext[i].start); + + return fileblock + start; + } + } + else + { + grub_error (GRUB_ERR_BAD_FS, ""something wrong with extent""); + return -1; + } + } + /* Direct blocks. */ + if (fileblock < INDIRECT_BLOCKS) { + blknr = grub_le_to_cpu32 (inode->blocks.dir_blocks[fileblock]); + /* Indirect. */ + } else if (fileblock < INDIRECT_BLOCKS + blksz / 4) + { + grub_uint32_t *indir; + + indir = grub_malloc (blksz); + if (! indir) + return grub_errno; + + if (grub_disk_read (data->disk, + ((grub_disk_addr_t) + grub_le_to_cpu32 (inode->blocks.indir_block)) + << log2_blksz, + 0, blksz, indir)) + return grub_errno; + + blknr = grub_le_to_cpu32 (indir[fileblock - INDIRECT_BLOCKS]); + grub_free (indir); + } + /* Double indirect. */ + else if (fileblock < (grub_disk_addr_t)(INDIRECT_BLOCKS + blksz / 4) \ + * (grub_disk_addr_t)(blksz / 4 + 1)) + { + unsigned int perblock = blksz / 4; + unsigned int rblock = fileblock - (INDIRECT_BLOCKS + + blksz / 4); + grub_uint32_t *indir; + + indir = grub_malloc (blksz); + if (! indir) + return grub_errno; + + if (grub_disk_read (data->disk, + ((grub_disk_addr_t) + grub_le_to_cpu32 (inode->blocks.double_indir_block)) + << log2_blksz, + 0, blksz, indir)) + return grub_errno; + + if (grub_disk_read (data->disk, + ((grub_disk_addr_t) + grub_le_to_cpu32 (indir[rblock / perblock])) + << log2_blksz, + 0, blksz, indir)) + return grub_errno; + + blknr = grub_le_to_cpu32 (indir[rblock % perblock]); + grub_free (indir); + } + /* triple indirect. */ + else + { + grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET, + ""ext2fs doesn't support triple indirect blocks""); + } + + return blknr; +} +",1,"grub_ext2_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock) +{ + struct grub_ext2_data *data = node->data; + struct grub_ext2_inode *inode = &node->inode; + int blknr = -1; + unsigned int blksz = EXT2_BLOCK_SIZE (data); + int log2_blksz = LOG2_EXT2_BLOCK_SIZE (data); + + if (grub_le_to_cpu32(inode->flags) & EXT4_EXTENTS_FLAG) + { + char * buf = grub_malloc (EXT2_BLOCK_SIZE (data)); + if (!buf) { + return -1; + } + struct grub_ext4_extent_header *leaf; + struct grub_ext4_extent *ext; + int i; + + leaf = grub_ext4_find_leaf (data, buf, + (struct grub_ext4_extent_header *) inode->blocks.dir_blocks, + fileblock); + if (! leaf) + { + grub_error (GRUB_ERR_BAD_FS, ""invalid extent""); + free (buf); + return -1; + } + + ext = (struct grub_ext4_extent *) (leaf + 1); + for (i = 0; i < grub_le_to_cpu16 (leaf->entries); i++) + { + if (fileblock < grub_le_to_cpu32 (ext[i].block)) + break; + } + + if (--i >= 0) + { + fileblock -= grub_le_to_cpu32 (ext[i].block); + if (fileblock >= grub_le_to_cpu16 (ext[i].len)) { + free (buf); + return 0; + } else + { + grub_disk_addr_t start; + + start = grub_le_to_cpu16 (ext[i].start_hi); + start = (start << 32) + grub_le_to_cpu32 (ext[i].start); + free (buf); + + return fileblock + start; + } + } + else + { + grub_error (GRUB_ERR_BAD_FS, ""something wrong with extent""); + free (buf); + return -1; + } +free (buf); + } + /* Direct blocks. */ + if (fileblock < INDIRECT_BLOCKS) { + blknr = grub_le_to_cpu32 (inode->blocks.dir_blocks[fileblock]); + /* Indirect. */ + } else if (fileblock < INDIRECT_BLOCKS + blksz / 4) + { + grub_uint32_t *indir; + + indir = grub_malloc (blksz); + if (! indir) { + return grub_errno; +} + + if (grub_disk_read (data->disk, + ((grub_disk_addr_t) + grub_le_to_cpu32 (inode->blocks.indir_block)) + << log2_blksz, + 0, blksz, indir)) { + return grub_errno; +} + + blknr = grub_le_to_cpu32 (indir[fileblock - INDIRECT_BLOCKS]); + grub_free (indir); + } + /* Double indirect. */ + else if (fileblock < (grub_disk_addr_t)(INDIRECT_BLOCKS + blksz / 4) \ + * (grub_disk_addr_t)(blksz / 4 + 1)) + { + unsigned int perblock = blksz / 4; + unsigned int rblock = fileblock - (INDIRECT_BLOCKS + + blksz / 4); + grub_uint32_t *indir; + + indir = grub_malloc (blksz); + if (! indir) { + return grub_errno; +} + + if (grub_disk_read (data->disk, + ((grub_disk_addr_t) + grub_le_to_cpu32 (inode->blocks.double_indir_block)) + << log2_blksz, + 0, blksz, indir)) { + return grub_errno; +} + + if (grub_disk_read (data->disk, + ((grub_disk_addr_t) + grub_le_to_cpu32 (indir[rblock / perblock])) + << log2_blksz, + 0, blksz, indir)) { + return grub_errno; +} + + blknr = grub_le_to_cpu32 (indir[rblock % perblock]); + grub_free (indir); + } + /* triple indirect. */ + else + { + grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET, + ""ext2fs doesn't support triple indirect blocks""); + } + + return blknr; +} +","@@ -42,6 +42,7 @@ + #define FILETYPE_INO_DIRECTORY 0040000 + #define FILETYPE_INO_SYMLINK 0120000 + ++#include + #include + #include + #include +@@ -367,8 +368,9 @@ grub_ext4_find_leaf (struct grub_ext2_data *data, char *buf, + block = (block << 32) + grub_le_to_cpu32 (index[i].leaf); + if (grub_disk_read (data->disk, + block << LOG2_EXT2_BLOCK_SIZE (data), +- 0, EXT2_BLOCK_SIZE(data), buf)) ++ 0, EXT2_BLOCK_SIZE(data), buf)) { + return 0; ++ } + + ext_block = (struct grub_ext4_extent_header *) buf; + } +@@ -385,11 +387,10 @@ grub_ext2_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock) + + if (grub_le_to_cpu32(inode->flags) & EXT4_EXTENTS_FLAG) + { +-#ifndef _MSC_VER +- char buf[EXT2_BLOCK_SIZE (data)]; +-#else +- char * buf = grub_malloc (EXT2_BLOCK_SIZE(data)); +-#endif ++ char * buf = grub_malloc (EXT2_BLOCK_SIZE (data)); ++ if (!buf) { ++ return -1; ++ } + struct grub_ext4_extent_header *leaf; + struct grub_ext4_extent *ext; + int i; +@@ -400,6 +401,7 @@ grub_ext2_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock) + if (! leaf) + { + grub_error (GRUB_ERR_BAD_FS, ""invalid extent""); ++ free (buf); + return -1; + } + +@@ -413,23 +415,27 @@ grub_ext2_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock) + if (--i >= 0) + { + fileblock -= grub_le_to_cpu32 (ext[i].block); +- if (fileblock >= grub_le_to_cpu16 (ext[i].len)) ++ if (fileblock >= grub_le_to_cpu16 (ext[i].len)) { ++ free (buf); + return 0; +- else ++ } else + { + grub_disk_addr_t start; + + start = grub_le_to_cpu16 (ext[i].start_hi); + start = (start << 32) + grub_le_to_cpu32 (ext[i].start); ++ free (buf); + + return fileblock + start; + } + } + else + { + grub_error (GRUB_ERR_BAD_FS, ""something wrong with extent""); ++ free (buf); + return -1; + } ++free (buf); + } + /* Direct blocks. */ + if (fileblock < INDIRECT_BLOCKS) { +@@ -440,15 +446,17 @@ grub_ext2_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock) + grub_uint32_t *indir; + + indir = grub_malloc (blksz); +- if (! indir) ++ if (! indir) { + return grub_errno; ++} + + if (grub_disk_read (data->disk, + ((grub_disk_addr_t) + grub_le_to_cpu32 (inode->blocks.indir_block)) + << log2_blksz, +- 0, blksz, indir)) ++ 0, blksz, indir)) { + return grub_errno; ++} + + blknr = grub_le_to_cpu32 (indir[fileblock - INDIRECT_BLOCKS]); + grub_free (indir); +@@ -463,22 +471,25 @@ grub_ext2_read_block (grub_fshelp_node_t node, grub_disk_addr_t fileblock) + grub_uint32_t *indir; + + indir = grub_malloc (blksz); +- if (! indir) ++ if (! indir) { + return grub_errno; ++} + + if (grub_disk_read (data->disk, + ((grub_disk_addr_t) + grub_le_to_cpu32 (inode->blocks.double_indir_block)) + << log2_blksz, +- 0, blksz, indir)) ++ 0, blksz, indir)) { + return grub_errno; ++} + + if (grub_disk_read (data->disk, + ((grub_disk_addr_t) + grub_le_to_cpu32 (indir[rblock / perblock])) + << log2_blksz, +- 0, blksz, indir)) ++ 0, blksz, indir)) { + return grub_errno; ++} + + blknr = grub_le_to_cpu32 (indir[rblock % perblock]); + grub_free (indir);",943,1274,2048 +1922,"static int dccp_v6_conn_request(struct sock *sk, struct sk_buff *skb) +{ + struct request_sock *req; + struct dccp_request_sock *dreq; + struct inet6_request_sock *ireq6; + struct ipv6_pinfo *np = inet6_sk(sk); + const __be32 service = dccp_hdr_request(skb)->dccph_req_service; + struct dccp_skb_cb *dcb = DCCP_SKB_CB(skb); + + if (skb->protocol == htons(ETH_P_IP)) + return dccp_v4_conn_request(sk, skb); + + if (!ipv6_unicast_destination(skb)) + return 0; /* discard, don't send a reset here */ + + if (dccp_bad_service_code(sk, service)) { + dcb->dccpd_reset_code = DCCP_RESET_CODE_BAD_SERVICE_CODE; + goto drop; + } + /* + * There are no SYN attacks on IPv6, yet... + */ + dcb->dccpd_reset_code = DCCP_RESET_CODE_TOO_BUSY; + if (inet_csk_reqsk_queue_is_full(sk)) + goto drop; + + if (sk_acceptq_is_full(sk) && inet_csk_reqsk_queue_young(sk) > 1) + goto drop; + + req = inet6_reqsk_alloc(&dccp6_request_sock_ops); + if (req == NULL) + goto drop; + + if (dccp_reqsk_init(req, dccp_sk(sk), skb)) + goto drop_and_free; + + dreq = dccp_rsk(req); + if (dccp_parse_options(sk, dreq, skb)) + goto drop_and_free; + + if (security_inet_conn_request(sk, skb, req)) + goto drop_and_free; + + ireq6 = inet6_rsk(req); + ipv6_addr_copy(&ireq6->rmt_addr, &ipv6_hdr(skb)->saddr); + ipv6_addr_copy(&ireq6->loc_addr, &ipv6_hdr(skb)->daddr); + + if (ipv6_opt_accepted(sk, skb) || + np->rxopt.bits.rxinfo || np->rxopt.bits.rxoinfo || + np->rxopt.bits.rxhlim || np->rxopt.bits.rxohlim) { + atomic_inc(&skb->users); + ireq6->pktopts = skb; + } + ireq6->iif = sk->sk_bound_dev_if; + + /* So that link locals have meaning */ + if (!sk->sk_bound_dev_if && + ipv6_addr_type(&ireq6->rmt_addr) & IPV6_ADDR_LINKLOCAL) + ireq6->iif = inet6_iif(skb); + + /* + * Step 3: Process LISTEN state + * + * Set S.ISR, S.GSR, S.SWL, S.SWH from packet or Init Cookie + * + * In fact we defer setting S.GSR, S.SWL, S.SWH to + * dccp_create_openreq_child. + */ + dreq->dreq_isr = dcb->dccpd_seq; + dreq->dreq_iss = dccp_v6_init_sequence(skb); + dreq->dreq_service = service; + + if (dccp_v6_send_response(sk, req, NULL)) + goto drop_and_free; + + inet6_csk_reqsk_queue_hash_add(sk, req, DCCP_TIMEOUT_INIT); + return 0; + +drop_and_free: + reqsk_free(req); +drop: + DCCP_INC_STATS_BH(DCCP_MIB_ATTEMPTFAILS); + return -1; +} +",0,"static int dccp_v6_conn_request(struct sock *sk, struct sk_buff *skb) +{ + struct request_sock *req; + struct dccp_request_sock *dreq; + struct inet6_request_sock *ireq6; + struct ipv6_pinfo *np = inet6_sk(sk); + const __be32 service = dccp_hdr_request(skb)->dccph_req_service; + struct dccp_skb_cb *dcb = DCCP_SKB_CB(skb); + + if (skb->protocol == htons(ETH_P_IP)) + return dccp_v4_conn_request(sk, skb); + + if (!ipv6_unicast_destination(skb)) + return 0; /* discard, don't send a reset here */ + + if (dccp_bad_service_code(sk, service)) { + dcb->dccpd_reset_code = DCCP_RESET_CODE_BAD_SERVICE_CODE; + goto drop; + } + /* + * There are no SYN attacks on IPv6, yet... + */ + dcb->dccpd_reset_code = DCCP_RESET_CODE_TOO_BUSY; + if (inet_csk_reqsk_queue_is_full(sk)) + goto drop; + + if (sk_acceptq_is_full(sk) && inet_csk_reqsk_queue_young(sk) > 1) + goto drop; + + req = inet6_reqsk_alloc(&dccp6_request_sock_ops); + if (req == NULL) + goto drop; + + if (dccp_reqsk_init(req, dccp_sk(sk), skb)) + goto drop_and_free; + + dreq = dccp_rsk(req); + if (dccp_parse_options(sk, dreq, skb)) + goto drop_and_free; + + if (security_inet_conn_request(sk, skb, req)) + goto drop_and_free; + + ireq6 = inet6_rsk(req); + ipv6_addr_copy(&ireq6->rmt_addr, &ipv6_hdr(skb)->saddr); + ipv6_addr_copy(&ireq6->loc_addr, &ipv6_hdr(skb)->daddr); + + if (ipv6_opt_accepted(sk, skb) || + np->rxopt.bits.rxinfo || np->rxopt.bits.rxoinfo || + np->rxopt.bits.rxhlim || np->rxopt.bits.rxohlim) { + atomic_inc(&skb->users); + ireq6->pktopts = skb; + } + ireq6->iif = sk->sk_bound_dev_if; + + /* So that link locals have meaning */ + if (!sk->sk_bound_dev_if && + ipv6_addr_type(&ireq6->rmt_addr) & IPV6_ADDR_LINKLOCAL) + ireq6->iif = inet6_iif(skb); + + /* + * Step 3: Process LISTEN state + * + * Set S.ISR, S.GSR, S.SWL, S.SWH from packet or Init Cookie + * + * In fact we defer setting S.GSR, S.SWL, S.SWH to + * dccp_create_openreq_child. + */ + dreq->dreq_isr = dcb->dccpd_seq; + dreq->dreq_iss = dccp_v6_init_sequence(skb); + dreq->dreq_service = service; + + if (dccp_v6_send_response(sk, req, NULL)) + goto drop_and_free; + + inet6_csk_reqsk_queue_hash_add(sk, req, DCCP_TIMEOUT_INIT); + return 0; + +drop_and_free: + reqsk_free(req); +drop: + DCCP_INC_STATS_BH(DCCP_MIB_ATTEMPTFAILS); + return -1; +} +","@@ -573,7 +573,7 @@ static struct sock *dccp_v6_request_recv_sock(struct sock *sk, + + First: no IPv4 options. + */ +- newinet->opt = NULL; ++ newinet->inet_opt = NULL; + + /* Clone RX bits */ + newnp->rxopt.all = np->rxopt.all;",741,1072,2048 +9286,"inline int web_client_api_request_v1_registry(RRDHOST *host, struct web_client *w, char *url) { + static uint32_t hash_action = 0, hash_access = 0, hash_hello = 0, hash_delete = 0, hash_search = 0, + hash_switch = 0, hash_machine = 0, hash_url = 0, hash_name = 0, hash_delete_url = 0, hash_for = 0, + hash_to = 0 /*, hash_redirects = 0 */; + + if(unlikely(!hash_action)) { + hash_action = simple_hash(""action""); + hash_access = simple_hash(""access""); + hash_hello = simple_hash(""hello""); + hash_delete = simple_hash(""delete""); + hash_search = simple_hash(""search""); + hash_switch = simple_hash(""switch""); + hash_machine = simple_hash(""machine""); + hash_url = simple_hash(""url""); + hash_name = simple_hash(""name""); + hash_delete_url = simple_hash(""delete_url""); + hash_for = simple_hash(""for""); + hash_to = simple_hash(""to""); +/* + hash_redirects = simple_hash(""redirects""); +*/ + } + + char person_guid[GUID_LEN + 1] = """"; + + debug(D_WEB_CLIENT, ""%llu: API v1 registry with URL '%s'"", w->id, url); + + + char *cookie = strstr(w->response.data->buffer, NETDATA_REGISTRY_COOKIE_NAME ""=""); + if(cookie) + strncpyz(person_guid, &cookie[sizeof(NETDATA_REGISTRY_COOKIE_NAME)], 36); + + char action = '\0'; + char *machine_guid = NULL, + *machine_url = NULL, + *url_name = NULL, + *search_machine_guid = NULL, + *delete_url = NULL, + *to_person_guid = NULL; +/* + int redirects = 0; +*/ + + while(url) { + char *value = mystrsep(&url, ""?&""); + if (!value || !*value) continue; + + char *name = mystrsep(&value, ""=""); + if (!name || !*name) continue; + if (!value || !*value) continue; + + debug(D_WEB_CLIENT, ""%llu: API v1 registry query param '%s' with value '%s'"", w->id, name, value); + + uint32_t hash = simple_hash(name); + + if(hash == hash_action && !strcmp(name, ""action"")) { + uint32_t vhash = simple_hash(value); + + if(vhash == hash_access && !strcmp(value, ""access"")) action = 'A'; + else if(vhash == hash_hello && !strcmp(value, ""hello"")) action = 'H'; + else if(vhash == hash_delete && !strcmp(value, ""delete"")) action = 'D'; + else if(vhash == hash_search && !strcmp(value, ""search"")) action = 'S'; + else if(vhash == hash_switch && !strcmp(value, ""switch"")) action = 'W'; +#ifdef NETDATA_INTERNAL_CHECKS + else error(""unknown registry action '%s'"", value); +#endif /* NETDATA_INTERNAL_CHECKS */ + } +/* + else if(hash == hash_redirects && !strcmp(name, ""redirects"")) + redirects = atoi(value); +*/ + else if(hash == hash_machine && !strcmp(name, ""machine"")) + machine_guid = value; + + else if(hash == hash_url && !strcmp(name, ""url"")) + machine_url = value; + + else if(action == 'A') { + if(hash == hash_name && !strcmp(name, ""name"")) + url_name = value; + } + else if(action == 'D') { + if(hash == hash_delete_url && !strcmp(name, ""delete_url"")) + delete_url = value; + } + else if(action == 'S') { + if(hash == hash_for && !strcmp(name, ""for"")) + search_machine_guid = value; + } + else if(action == 'W') { + if(hash == hash_to && !strcmp(name, ""to"")) + to_person_guid = value; + } +#ifdef NETDATA_INTERNAL_CHECKS + else error(""unused registry URL parameter '%s' with value '%s'"", name, value); +#endif /* NETDATA_INTERNAL_CHECKS */ + } + + if(unlikely(respect_web_browser_do_not_track_policy && web_client_has_donottrack(w))) { + buffer_flush(w->response.data); + buffer_sprintf(w->response.data, ""Your web browser is sending 'DNT: 1' (Do Not Track). The registry requires persistent cookies on your browser to work.""); + return 400; + } + + if(unlikely(action == 'H')) { + if(unlikely(!web_client_can_access_dashboard(w))) + return web_client_permission_denied(w); + } + else { + if(unlikely(!web_client_can_access_registry(w))) + return web_client_permission_denied(w); + } + + switch(action) { + case 'A': + if(unlikely(!machine_guid || !machine_url || !url_name)) { + error(""Invalid registry request - access requires these parameters: machine ('%s'), url ('%s'), name ('%s')"", machine_guid ? machine_guid : ""UNSET"", machine_url ? machine_url : ""UNSET"", url_name ? url_name : ""UNSET""); + buffer_flush(w->response.data); + buffer_strcat(w->response.data, ""Invalid registry Access request.""); + return 400; + } + + web_client_enable_tracking_required(w); + return registry_request_access_json(host, w, person_guid, machine_guid, machine_url, url_name, now_realtime_sec()); + + case 'D': + if(unlikely(!machine_guid || !machine_url || !delete_url)) { + error(""Invalid registry request - delete requires these parameters: machine ('%s'), url ('%s'), delete_url ('%s')"", machine_guid?machine_guid:""UNSET"", machine_url?machine_url:""UNSET"", delete_url?delete_url:""UNSET""); + buffer_flush(w->response.data); + buffer_strcat(w->response.data, ""Invalid registry Delete request.""); + return 400; + } + + web_client_enable_tracking_required(w); + return registry_request_delete_json(host, w, person_guid, machine_guid, machine_url, delete_url, now_realtime_sec()); + + case 'S': + if(unlikely(!machine_guid || !machine_url || !search_machine_guid)) { + error(""Invalid registry request - search requires these parameters: machine ('%s'), url ('%s'), for ('%s')"", machine_guid?machine_guid:""UNSET"", machine_url?machine_url:""UNSET"", search_machine_guid?search_machine_guid:""UNSET""); + buffer_flush(w->response.data); + buffer_strcat(w->response.data, ""Invalid registry Search request.""); + return 400; + } + + web_client_enable_tracking_required(w); + return registry_request_search_json(host, w, person_guid, machine_guid, machine_url, search_machine_guid, now_realtime_sec()); + + case 'W': + if(unlikely(!machine_guid || !machine_url || !to_person_guid)) { + error(""Invalid registry request - switching identity requires these parameters: machine ('%s'), url ('%s'), to ('%s')"", machine_guid?machine_guid:""UNSET"", machine_url?machine_url:""UNSET"", to_person_guid?to_person_guid:""UNSET""); + buffer_flush(w->response.data); + buffer_strcat(w->response.data, ""Invalid registry Switch request.""); + return 400; + } + + web_client_enable_tracking_required(w); + return registry_request_switch_json(host, w, person_guid, machine_guid, machine_url, to_person_guid, now_realtime_sec()); + + case 'H': + return registry_request_hello_json(host, w); + + default: + buffer_flush(w->response.data); + buffer_strcat(w->response.data, ""Invalid registry request - you need to set an action: hello, access, delete, search""); + return 400; + } +} +",0,"inline int web_client_api_request_v1_registry(RRDHOST *host, struct web_client *w, char *url) { + static uint32_t hash_action = 0, hash_access = 0, hash_hello = 0, hash_delete = 0, hash_search = 0, + hash_switch = 0, hash_machine = 0, hash_url = 0, hash_name = 0, hash_delete_url = 0, hash_for = 0, + hash_to = 0 /*, hash_redirects = 0 */; + + if(unlikely(!hash_action)) { + hash_action = simple_hash(""action""); + hash_access = simple_hash(""access""); + hash_hello = simple_hash(""hello""); + hash_delete = simple_hash(""delete""); + hash_search = simple_hash(""search""); + hash_switch = simple_hash(""switch""); + hash_machine = simple_hash(""machine""); + hash_url = simple_hash(""url""); + hash_name = simple_hash(""name""); + hash_delete_url = simple_hash(""delete_url""); + hash_for = simple_hash(""for""); + hash_to = simple_hash(""to""); +/* + hash_redirects = simple_hash(""redirects""); +*/ + } + + char person_guid[GUID_LEN + 1] = """"; + + debug(D_WEB_CLIENT, ""%llu: API v1 registry with URL '%s'"", w->id, url); + + + char *cookie = strstr(w->response.data->buffer, NETDATA_REGISTRY_COOKIE_NAME ""=""); + if(cookie) + strncpyz(person_guid, &cookie[sizeof(NETDATA_REGISTRY_COOKIE_NAME)], 36); + + char action = '\0'; + char *machine_guid = NULL, + *machine_url = NULL, + *url_name = NULL, + *search_machine_guid = NULL, + *delete_url = NULL, + *to_person_guid = NULL; +/* + int redirects = 0; +*/ + + while(url) { + char *value = mystrsep(&url, ""?&""); + if (!value || !*value) continue; + + char *name = mystrsep(&value, ""=""); + if (!name || !*name) continue; + if (!value || !*value) continue; + + debug(D_WEB_CLIENT, ""%llu: API v1 registry query param '%s' with value '%s'"", w->id, name, value); + + uint32_t hash = simple_hash(name); + + if(hash == hash_action && !strcmp(name, ""action"")) { + uint32_t vhash = simple_hash(value); + + if(vhash == hash_access && !strcmp(value, ""access"")) action = 'A'; + else if(vhash == hash_hello && !strcmp(value, ""hello"")) action = 'H'; + else if(vhash == hash_delete && !strcmp(value, ""delete"")) action = 'D'; + else if(vhash == hash_search && !strcmp(value, ""search"")) action = 'S'; + else if(vhash == hash_switch && !strcmp(value, ""switch"")) action = 'W'; +#ifdef NETDATA_INTERNAL_CHECKS + else error(""unknown registry action '%s'"", value); +#endif /* NETDATA_INTERNAL_CHECKS */ + } +/* + else if(hash == hash_redirects && !strcmp(name, ""redirects"")) + redirects = atoi(value); +*/ + else if(hash == hash_machine && !strcmp(name, ""machine"")) + machine_guid = value; + + else if(hash == hash_url && !strcmp(name, ""url"")) + machine_url = value; + + else if(action == 'A') { + if(hash == hash_name && !strcmp(name, ""name"")) + url_name = value; + } + else if(action == 'D') { + if(hash == hash_delete_url && !strcmp(name, ""delete_url"")) + delete_url = value; + } + else if(action == 'S') { + if(hash == hash_for && !strcmp(name, ""for"")) + search_machine_guid = value; + } + else if(action == 'W') { + if(hash == hash_to && !strcmp(name, ""to"")) + to_person_guid = value; + } +#ifdef NETDATA_INTERNAL_CHECKS + else error(""unused registry URL parameter '%s' with value '%s'"", name, value); +#endif /* NETDATA_INTERNAL_CHECKS */ + } + + if(unlikely(respect_web_browser_do_not_track_policy && web_client_has_donottrack(w))) { + buffer_flush(w->response.data); + buffer_sprintf(w->response.data, ""Your web browser is sending 'DNT: 1' (Do Not Track). The registry requires persistent cookies on your browser to work.""); + return 400; + } + + if(unlikely(action == 'H')) { + if(unlikely(!web_client_can_access_dashboard(w))) + return web_client_permission_denied(w); + } + else { + if(unlikely(!web_client_can_access_registry(w))) + return web_client_permission_denied(w); + } + + switch(action) { + case 'A': + if(unlikely(!machine_guid || !machine_url || !url_name)) { + error(""Invalid registry request - access requires these parameters: machine ('%s'), url ('%s'), name ('%s')"", machine_guid ? machine_guid : ""UNSET"", machine_url ? machine_url : ""UNSET"", url_name ? url_name : ""UNSET""); + buffer_flush(w->response.data); + buffer_strcat(w->response.data, ""Invalid registry Access request.""); + return 400; + } + + web_client_enable_tracking_required(w); + return registry_request_access_json(host, w, person_guid, machine_guid, machine_url, url_name, now_realtime_sec()); + + case 'D': + if(unlikely(!machine_guid || !machine_url || !delete_url)) { + error(""Invalid registry request - delete requires these parameters: machine ('%s'), url ('%s'), delete_url ('%s')"", machine_guid?machine_guid:""UNSET"", machine_url?machine_url:""UNSET"", delete_url?delete_url:""UNSET""); + buffer_flush(w->response.data); + buffer_strcat(w->response.data, ""Invalid registry Delete request.""); + return 400; + } + + web_client_enable_tracking_required(w); + return registry_request_delete_json(host, w, person_guid, machine_guid, machine_url, delete_url, now_realtime_sec()); + + case 'S': + if(unlikely(!machine_guid || !machine_url || !search_machine_guid)) { + error(""Invalid registry request - search requires these parameters: machine ('%s'), url ('%s'), for ('%s')"", machine_guid?machine_guid:""UNSET"", machine_url?machine_url:""UNSET"", search_machine_guid?search_machine_guid:""UNSET""); + buffer_flush(w->response.data); + buffer_strcat(w->response.data, ""Invalid registry Search request.""); + return 400; + } + + web_client_enable_tracking_required(w); + return registry_request_search_json(host, w, person_guid, machine_guid, machine_url, search_machine_guid, now_realtime_sec()); + + case 'W': + if(unlikely(!machine_guid || !machine_url || !to_person_guid)) { + error(""Invalid registry request - switching identity requires these parameters: machine ('%s'), url ('%s'), to ('%s')"", machine_guid?machine_guid:""UNSET"", machine_url?machine_url:""UNSET"", to_person_guid?to_person_guid:""UNSET""); + buffer_flush(w->response.data); + buffer_strcat(w->response.data, ""Invalid registry Switch request.""); + return 400; + } + + web_client_enable_tracking_required(w); + return registry_request_switch_json(host, w, person_guid, machine_guid, machine_url, to_person_guid, now_realtime_sec()); + + case 'H': + return registry_request_hello_json(host, w); + + default: + buffer_flush(w->response.data); + buffer_strcat(w->response.data, ""Invalid registry request - you need to set an action: hello, access, delete, search""); + return 400; + } +} +","@@ -233,6 +233,15 @@ inline int web_client_api_request_v1_chart(RRDHOST *host, struct web_client *w, + return web_client_api_request_single_chart(host, w, url, rrd_stats_api_v1_chart); + } + ++void fix_google_param(char *s) { ++ if(unlikely(!s)) return; ++ ++ for( ; *s ;s++) { ++ if(!isalnum(*s) && *s != '.' && *s != '_' && *s != '-') ++ *s = '_'; ++ } ++} ++ + // returns the HTTP code + inline int web_client_api_request_v1_data(RRDHOST *host, struct web_client *w, char *url) { + debug(D_WEB_CLIENT, ""%llu: API v1 data with URL '%s'"", w->id, url); +@@ -332,6 +341,14 @@ inline int web_client_api_request_v1_data(RRDHOST *host, struct web_client *w, c + } + } + ++ // validate the google parameters given ++ fix_google_param(google_out); ++ fix_google_param(google_sig); ++ fix_google_param(google_reqId); ++ fix_google_param(google_version); ++ fix_google_param(responseHandler); ++ fix_google_param(outFileName); ++ + if(!chart || !*chart) { + buffer_sprintf(w->response.data, ""No chart id is given at the request.""); + goto cleanup;",1687,2018,2048 +8621,"void jpc_ft_fwdlift_colgrp(jpc_fix_t *a, int numrows, int stride, int parity) +{ + + jpc_fix_t *lptr; + jpc_fix_t *hptr; + register jpc_fix_t *lptr2; + register jpc_fix_t *hptr2; + register int n; + register int i; + int llen; + + llen = (numrows + 1 - parity) >> 1; + + if (numrows > 1) { + + /* Apply the first lifting step. */ + lptr = &a[0]; + hptr = &a[llen * stride]; + if (parity) { + lptr2 = lptr; + hptr2 = hptr; + for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { + hptr2[0] -= lptr2[0]; + ++hptr2; + ++lptr2; + } + hptr += stride; + } + n = numrows - llen - parity - (parity == (numrows & 1)); + while (n-- > 0) { + lptr2 = lptr; + hptr2 = hptr; + for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { + hptr2[0] -= jpc_fix_asr(lptr2[0] + lptr2[stride], 1); + ++lptr2; + ++hptr2; + } + hptr += stride; + lptr += stride; + } + if (parity == (numrows & 1)) { + lptr2 = lptr; + hptr2 = hptr; + for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { + hptr2[0] -= lptr2[0]; + ++lptr2; + ++hptr2; + } + } + + /* Apply the second lifting step. */ + lptr = &a[0]; + hptr = &a[llen * stride]; + if (!parity) { + lptr2 = lptr; + hptr2 = hptr; + for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { + lptr2[0] += jpc_fix_asr(hptr2[0] + 1, 1); + ++lptr2; + ++hptr2; + } + lptr += stride; + } + n = llen - (!parity) - (parity != (numrows & 1)); + while (n-- > 0) { + lptr2 = lptr; + hptr2 = hptr; + for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { + lptr2[0] += jpc_fix_asr(hptr2[0] + hptr2[stride] + 2, 2); + ++lptr2; + ++hptr2; + } + lptr += stride; + hptr += stride; + } + if (parity != (numrows & 1)) { + lptr2 = lptr; + hptr2 = hptr; + for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { + lptr2[0] += jpc_fix_asr(hptr2[0] + 1, 1); + ++lptr2; + ++hptr2; + } + } + + } else { + + if (parity) { + lptr2 = &a[0]; + for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { + lptr2[0] = jpc_fix_asl(lptr2[0], 1); + ++lptr2; + } + } + + } + +} +",0,"void jpc_ft_fwdlift_colgrp(jpc_fix_t *a, int numrows, int stride, int parity) +{ + + jpc_fix_t *lptr; + jpc_fix_t *hptr; + register jpc_fix_t *lptr2; + register jpc_fix_t *hptr2; + register int n; + register int i; + int llen; + + llen = (numrows + 1 - parity) >> 1; + + if (numrows > 1) { + + /* Apply the first lifting step. */ + lptr = &a[0]; + hptr = &a[llen * stride]; + if (parity) { + lptr2 = lptr; + hptr2 = hptr; + for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { + hptr2[0] -= lptr2[0]; + ++hptr2; + ++lptr2; + } + hptr += stride; + } + n = numrows - llen - parity - (parity == (numrows & 1)); + while (n-- > 0) { + lptr2 = lptr; + hptr2 = hptr; + for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { + hptr2[0] -= jpc_fix_asr(lptr2[0] + lptr2[stride], 1); + ++lptr2; + ++hptr2; + } + hptr += stride; + lptr += stride; + } + if (parity == (numrows & 1)) { + lptr2 = lptr; + hptr2 = hptr; + for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { + hptr2[0] -= lptr2[0]; + ++lptr2; + ++hptr2; + } + } + + /* Apply the second lifting step. */ + lptr = &a[0]; + hptr = &a[llen * stride]; + if (!parity) { + lptr2 = lptr; + hptr2 = hptr; + for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { + lptr2[0] += jpc_fix_asr(hptr2[0] + 1, 1); + ++lptr2; + ++hptr2; + } + lptr += stride; + } + n = llen - (!parity) - (parity != (numrows & 1)); + while (n-- > 0) { + lptr2 = lptr; + hptr2 = hptr; + for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { + lptr2[0] += jpc_fix_asr(hptr2[0] + hptr2[stride] + 2, 2); + ++lptr2; + ++hptr2; + } + lptr += stride; + hptr += stride; + } + if (parity != (numrows & 1)) { + lptr2 = lptr; + hptr2 = hptr; + for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { + lptr2[0] += jpc_fix_asr(hptr2[0] + 1, 1); + ++lptr2; + ++hptr2; + } + } + + } else { + + if (parity) { + lptr2 = &a[0]; + for (i = 0; i < JPC_QMFB_COLGRPSIZE; ++i) { + lptr2[0] = jpc_fix_asl(lptr2[0], 1); + ++lptr2; + } + } + + } + +} +","@@ -374,7 +374,7 @@ void jpc_qmfb_split_col(jpc_fix_t *a, int numrows, int stride, + register jpc_fix_t *dstptr; + register int n; + register int m; +- int hstartcol; ++ int hstartrow; + + /* Get a buffer. */ + if (bufsize > QMFB_SPLITBUFSIZE) { +@@ -385,9 +385,9 @@ void jpc_qmfb_split_col(jpc_fix_t *a, int numrows, int stride, + } + + if (numrows >= 2) { +- hstartcol = (numrows + 1 - parity) >> 1; +- // ORIGINAL (WRONG): m = (parity) ? hstartcol : (numrows - hstartcol); +- m = numrows - hstartcol; ++ hstartrow = (numrows + 1 - parity) >> 1; ++ // ORIGINAL (WRONG): m = (parity) ? hstartrow : (numrows - hstartrow); ++ m = numrows - hstartrow; + + /* Save the samples destined for the highpass channel. */ + n = m; +@@ -408,7 +408,7 @@ void jpc_qmfb_split_col(jpc_fix_t *a, int numrows, int stride, + srcptr += stride << 1; + } + /* Copy the saved samples into the highpass channel. */ +- dstptr = &a[hstartcol * stride]; ++ dstptr = &a[hstartrow * stride]; + srcptr = buf; + n = m; + while (n-- > 0) { +@@ -439,20 +439,21 @@ void jpc_qmfb_split_colgrp(jpc_fix_t *a, int numrows, int stride, + register int n; + register int i; + int m; +- int hstartcol; ++ int hstartrow; + + /* Get a buffer. */ + if (bufsize > QMFB_SPLITBUFSIZE) { +- if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) { ++ if (!(buf = jas_alloc3(bufsize, JPC_QMFB_COLGRPSIZE, ++ sizeof(jpc_fix_t)))) { + /* We have no choice but to commit suicide in this case. */ + abort(); + } + } + + if (numrows >= 2) { +- hstartcol = (numrows + 1 - parity) >> 1; +- // ORIGINAL (WRONG): m = (parity) ? hstartcol : (numrows - hstartcol); +- m = numrows - hstartcol; ++ hstartrow = (numrows + 1 - parity) >> 1; ++ // ORIGINAL (WRONG): m = (parity) ? hstartrow : (numrows - hstartrow); ++ m = numrows - hstartrow; + + /* Save the samples destined for the highpass channel. */ + n = m; +@@ -485,7 +486,7 @@ void jpc_qmfb_split_colgrp(jpc_fix_t *a, int numrows, int stride, + srcptr += stride << 1; + } + /* Copy the saved samples into the highpass channel. */ +- dstptr = &a[hstartcol * stride]; ++ dstptr = &a[hstartrow * stride]; + srcptr = buf; + n = m; + while (n-- > 0) { +@@ -526,7 +527,7 @@ void jpc_qmfb_split_colres(jpc_fix_t *a, int numrows, int numcols, + + /* Get a buffer. */ + if (bufsize > QMFB_SPLITBUFSIZE) { +- if (!(buf = jas_alloc2(bufsize, sizeof(jpc_fix_t)))) { ++ if (!(buf = jas_alloc3(bufsize, numcols, sizeof(jpc_fix_t)))) { + /* We have no choice but to commit suicide in this case. */ + abort(); + } +@@ -721,7 +722,8 @@ void jpc_qmfb_join_colgrp(jpc_fix_t *a, int numrows, int stride, + + /* Allocate memory for the join buffer from the heap. */ + if (bufsize > QMFB_JOINBUFSIZE) { +- if (!(buf = jas_alloc3(bufsize, JPC_QMFB_COLGRPSIZE, sizeof(jpc_fix_t)))) { ++ if (!(buf = jas_alloc3(bufsize, JPC_QMFB_COLGRPSIZE, ++ sizeof(jpc_fix_t)))) { + /* We have no choice but to commit suicide. */ + abort(); + }",876,1207,2048 +8873,"MagickExport MagickBooleanType EvaluateImageChannel(Image *image, + const ChannelType channel,const MagickEvaluateOperator op,const double value, + ExceptionInfo *exception) +{ + CacheView + *image_view; + + MagickBooleanType + status; + + MagickOffsetType + progress; + + RandomInfo + **magick_restrict random_info; + + ssize_t + y; + +#if defined(MAGICKCORE_OPENMP_SUPPORT) + unsigned long + key; +#endif + + 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); + if (SetImageStorageClass(image,DirectClass) == MagickFalse) + { + InheritException(exception,&image->exception); + return(MagickFalse); + } + status=MagickTrue; + progress=0; + random_info=AcquireRandomInfoThreadSet(); + image_view=AcquireAuthenticCacheView(image,exception); +#if defined(MAGICKCORE_OPENMP_SUPPORT) + key=GetRandomSecretKey(random_info[0]); + #pragma omp parallel for schedule(static) shared(progress,status) \ + magick_number_threads(image,image,image->rows,key == ~0UL) +#endif + for (y=0; y < (ssize_t) image->rows; y++) + { + const int + id = GetOpenMPThreadId(); + + register IndexPacket + *magick_restrict indexes; + + 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; + } + indexes=GetCacheViewAuthenticIndexQueue(image_view); + for (x=0; x < (ssize_t) image->columns; x++) + { + MagickRealType + result; + + if ((channel & RedChannel) != 0) + { + result=ApplyEvaluateOperator(random_info[id],GetPixelRed(q),op,value); + if (op == MeanEvaluateOperator) + result/=2.0; + SetPixelRed(q,ClampToQuantum(result)); + } + if ((channel & GreenChannel) != 0) + { + result=ApplyEvaluateOperator(random_info[id],GetPixelGreen(q),op, + value); + if (op == MeanEvaluateOperator) + result/=2.0; + SetPixelGreen(q,ClampToQuantum(result)); + } + if ((channel & BlueChannel) != 0) + { + result=ApplyEvaluateOperator(random_info[id],GetPixelBlue(q),op, + value); + if (op == MeanEvaluateOperator) + result/=2.0; + SetPixelBlue(q,ClampToQuantum(result)); + } + if ((channel & OpacityChannel) != 0) + { + if (image->matte == MagickFalse) + { + result=ApplyEvaluateOperator(random_info[id],GetPixelOpacity(q), + op,value); + if (op == MeanEvaluateOperator) + result/=2.0; + SetPixelOpacity(q,ClampToQuantum(result)); + } + else + { + result=ApplyEvaluateOperator(random_info[id],GetPixelAlpha(q), + op,value); + if (op == MeanEvaluateOperator) + result/=2.0; + SetPixelAlpha(q,ClampToQuantum(result)); + } + } + if (((channel & IndexChannel) != 0) && (indexes != (IndexPacket *) NULL)) + { + result=ApplyEvaluateOperator(random_info[id],GetPixelIndex(indexes+x), + op,value); + if (op == MeanEvaluateOperator) + result/=2.0; + SetPixelIndex(indexes+x,ClampToQuantum(result)); + } + q++; + } + if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) + status=MagickFalse; + if (image->progress_monitor != (MagickProgressMonitor) NULL) + { + MagickBooleanType + proceed; + + proceed=SetImageProgress(image,EvaluateImageTag,progress++,image->rows); + if (proceed == MagickFalse) + status=MagickFalse; + } + } + image_view=DestroyCacheView(image_view); + random_info=DestroyRandomInfoThreadSet(random_info); + return(status); +} +",0,"MagickExport MagickBooleanType EvaluateImageChannel(Image *image, + const ChannelType channel,const MagickEvaluateOperator op,const double value, + ExceptionInfo *exception) +{ + CacheView + *image_view; + + MagickBooleanType + status; + + MagickOffsetType + progress; + + RandomInfo + **magick_restrict random_info; + + ssize_t + y; + +#if defined(MAGICKCORE_OPENMP_SUPPORT) + unsigned long + key; +#endif + + 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); + if (SetImageStorageClass(image,DirectClass) == MagickFalse) + { + InheritException(exception,&image->exception); + return(MagickFalse); + } + status=MagickTrue; + progress=0; + random_info=AcquireRandomInfoThreadSet(); + image_view=AcquireAuthenticCacheView(image,exception); +#if defined(MAGICKCORE_OPENMP_SUPPORT) + key=GetRandomSecretKey(random_info[0]); + #pragma omp parallel for schedule(static) shared(progress,status) \ + magick_number_threads(image,image,image->rows,key == ~0UL) +#endif + for (y=0; y < (ssize_t) image->rows; y++) + { + const int + id = GetOpenMPThreadId(); + + register IndexPacket + *magick_restrict indexes; + + 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; + } + indexes=GetCacheViewAuthenticIndexQueue(image_view); + for (x=0; x < (ssize_t) image->columns; x++) + { + MagickRealType + result; + + if ((channel & RedChannel) != 0) + { + result=ApplyEvaluateOperator(random_info[id],GetPixelRed(q),op,value); + if (op == MeanEvaluateOperator) + result/=2.0; + SetPixelRed(q,ClampToQuantum(result)); + } + if ((channel & GreenChannel) != 0) + { + result=ApplyEvaluateOperator(random_info[id],GetPixelGreen(q),op, + value); + if (op == MeanEvaluateOperator) + result/=2.0; + SetPixelGreen(q,ClampToQuantum(result)); + } + if ((channel & BlueChannel) != 0) + { + result=ApplyEvaluateOperator(random_info[id],GetPixelBlue(q),op, + value); + if (op == MeanEvaluateOperator) + result/=2.0; + SetPixelBlue(q,ClampToQuantum(result)); + } + if ((channel & OpacityChannel) != 0) + { + if (image->matte == MagickFalse) + { + result=ApplyEvaluateOperator(random_info[id],GetPixelOpacity(q), + op,value); + if (op == MeanEvaluateOperator) + result/=2.0; + SetPixelOpacity(q,ClampToQuantum(result)); + } + else + { + result=ApplyEvaluateOperator(random_info[id],GetPixelAlpha(q), + op,value); + if (op == MeanEvaluateOperator) + result/=2.0; + SetPixelAlpha(q,ClampToQuantum(result)); + } + } + if (((channel & IndexChannel) != 0) && (indexes != (IndexPacket *) NULL)) + { + result=ApplyEvaluateOperator(random_info[id],GetPixelIndex(indexes+x), + op,value); + if (op == MeanEvaluateOperator) + result/=2.0; + SetPixelIndex(indexes+x,ClampToQuantum(result)); + } + q++; + } + if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) + status=MagickFalse; + if (image->progress_monitor != (MagickProgressMonitor) NULL) + { + MagickBooleanType + proceed; + + proceed=SetImageProgress(image,EvaluateImageTag,progress++,image->rows); + if (proceed == MagickFalse) + status=MagickFalse; + } + } + image_view=DestroyCacheView(image_view); + random_info=DestroyRandomInfoThreadSet(random_info); + return(status); +} +","@@ -163,18 +163,17 @@ static MagickPixelPacket **AcquirePixelThreadSet(const Image *images) + + size_t + columns, +- number_threads; ++ rows; + +- number_threads=(size_t) GetMagickResourceLimit(ThreadResource); +- pixels=(MagickPixelPacket **) AcquireQuantumMemory(number_threads, +- sizeof(*pixels)); ++ rows=MagickMax(GetImageListLength(images), ++ (size_t) GetMagickResourceLimit(ThreadResource)); ++ pixels=(MagickPixelPacket **) AcquireQuantumMemory(rows,sizeof(*pixels)); + if (pixels == (MagickPixelPacket **) NULL) + return((MagickPixelPacket **) NULL); +- (void) memset(pixels,0,number_threads*sizeof(*pixels)); + columns=images->columns; + for (next=images; next != (Image *) NULL; next=next->next) + columns=MagickMax(next->columns,columns); +- for (i=0; i < (ssize_t) number_threads; i++) ++ for (i=0; i < (ssize_t) rows; i++) + { + pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(columns, + sizeof(**pixels));",991,1322,2048 +18008,"int read_image_tga( gdIOCtx *ctx, oTga *tga ) +{ + int pixel_block_size = (tga->bits / 8); + int image_block_size = (tga->width * tga->height) * pixel_block_size; + uint8_t* decompression_buffer = NULL; + unsigned char* conversion_buffer = NULL; + int buffer_caret = 0; + int bitmap_caret = 0; + int i = 0; + int j = 0; + uint8_t encoded_pixels; + + if(overflow2(tga->width, tga->height)) { + return -1; + } + + if(overflow2(tga->width * tga->height, pixel_block_size)) { + return -1; + } + + if(overflow2(image_block_size, sizeof(int))) { + return -1; + } + + /*! \todo Add more image type support. + */ + if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE) + return -1; + + /*! \brief Allocate memmory for image block + * Allocate a chunk of memory for the image block to be passed into. + */ + tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int)); + if (tga->bitmap == NULL) + return -1; + + switch (tga->imagetype) { + case TGA_TYPE_RGB: + /*! \brief Read in uncompressed RGB TGA + * Chunk load the pixel data from an uncompressed RGB type TGA. + */ + conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); + if (conversion_buffer == NULL) { + return -1; + } + + if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) { + gd_error(""gd-tga: premature end of image data\n""); + gdFree(conversion_buffer); + return -1; + } + + while (buffer_caret < image_block_size) { + tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret]; + buffer_caret++; + } + + gdFree(conversion_buffer); + break; + + case TGA_TYPE_RGB_RLE: + /*! \brief Read in RLE compressed RGB TGA + * Chunk load the pixel data from an RLE compressed RGB type TGA. + */ + decompression_buffer = (uint8_t*) gdMalloc(image_block_size * sizeof(uint8_t)); + if (decompression_buffer == NULL) { + return -1; + } + conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); + if (conversion_buffer == NULL) { + gd_error(""gd-tga: premature end of image data\n""); + gdFree( decompression_buffer ); + return -1; + } + + if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) { + gdFree(conversion_buffer); + gdFree(decompression_buffer); + return -1; + } + + buffer_caret = 0; + + while( buffer_caret < image_block_size) { + decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret]; + buffer_caret++; + } + + buffer_caret = 0; + + while( bitmap_caret < image_block_size ) { + + if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) { + encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & 127 ) + 1 ); + buffer_caret++; + + if (encoded_pixels != 0) { + if (!((buffer_caret + (encoded_pixels * pixel_block_size)) < image_block_size)) { + gdFree( decompression_buffer ); + gdFree( conversion_buffer ); + return -1; + } + for (i = 0; i < encoded_pixels; i++) { + for (j = 0; j < pixel_block_size; j++, bitmap_caret++) { + tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ]; + } + } + } + buffer_caret += pixel_block_size; + } else { + encoded_pixels = decompression_buffer[ buffer_caret ] + 1; + buffer_caret++; + + if (encoded_pixels != 0) { + if (!((buffer_caret + (encoded_pixels * pixel_block_size)) < image_block_size)) { + gdFree( decompression_buffer ); + gdFree( conversion_buffer ); + return -1; + } + for (i = 0; i < encoded_pixels; i++) { + for( j = 0; j < pixel_block_size; j++, bitmap_caret++ ) { + tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ]; + } + buffer_caret += pixel_block_size; + } + } + } + } + gdFree( decompression_buffer ); + gdFree( conversion_buffer ); + break; + } + + return 1; +} +",1,"int read_image_tga( gdIOCtx *ctx, oTga *tga ) +{ + int pixel_block_size = (tga->bits / 8); + int image_block_size = (tga->width * tga->height) * pixel_block_size; + uint8_t* decompression_buffer = NULL; + unsigned char* conversion_buffer = NULL; + int buffer_caret = 0; + int bitmap_caret = 0; + int i = 0; + uint8_t encoded_pixels; + + if(overflow2(tga->width, tga->height)) { + return -1; + } + + if(overflow2(tga->width * tga->height, pixel_block_size)) { + return -1; + } + + if(overflow2(image_block_size, sizeof(int))) { + return -1; + } + + /*! \todo Add more image type support. + */ + if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE) + return -1; + + /*! \brief Allocate memmory for image block + * Allocate a chunk of memory for the image block to be passed into. + */ + tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int)); + if (tga->bitmap == NULL) + return -1; + + switch (tga->imagetype) { + case TGA_TYPE_RGB: + /*! \brief Read in uncompressed RGB TGA + * Chunk load the pixel data from an uncompressed RGB type TGA. + */ + conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); + if (conversion_buffer == NULL) { + return -1; + } + + if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) { + gd_error(""gd-tga: premature end of image data\n""); + gdFree(conversion_buffer); + return -1; + } + + while (buffer_caret < image_block_size) { + tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret]; + buffer_caret++; + } + + gdFree(conversion_buffer); + break; + + case TGA_TYPE_RGB_RLE: + /*! \brief Read in RLE compressed RGB TGA + * Chunk load the pixel data from an RLE compressed RGB type TGA. + */ + decompression_buffer = (uint8_t*) gdMalloc(image_block_size * sizeof(uint8_t)); + if (decompression_buffer == NULL) { + return -1; + } + conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); + if (conversion_buffer == NULL) { + gd_error(""gd-tga: premature end of image data\n""); + gdFree( decompression_buffer ); + return -1; + } + + if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) { + gdFree(conversion_buffer); + gdFree(decompression_buffer); + return -1; + } + + buffer_caret = 0; + + while( buffer_caret < image_block_size) { + decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret]; + buffer_caret++; + } + + buffer_caret = 0; + + while( bitmap_caret < image_block_size ) { + + if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) { + encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & !TGA_RLE_FLAG ) + 1 ); + buffer_caret++; + + if ((bitmap_caret + (encoded_pixels * pixel_block_size)) >= image_block_size) { + gdFree( decompression_buffer ); + gdFree( conversion_buffer ); + return -1; + } + + for (i = 0; i < encoded_pixels; i++) { + memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, pixel_block_size); + bitmap_caret += pixel_block_size; + } + buffer_caret += pixel_block_size; + + } else { + encoded_pixels = decompression_buffer[ buffer_caret ] + 1; + buffer_caret++; + + if ((bitmap_caret + (encoded_pixels * pixel_block_size)) >= image_block_size) { + gdFree( decompression_buffer ); + gdFree( conversion_buffer ); + return -1; + } + + memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, encoded_pixels * pixel_block_size); + bitmap_caret += (encoded_pixels * pixel_block_size); + buffer_caret += (encoded_pixels * pixel_block_size); + } + } + gdFree( decompression_buffer ); + gdFree( conversion_buffer ); + break; + } + + return 1; +} +","@@ -196,7 +196,6 @@ int read_image_tga( gdIOCtx *ctx, oTga *tga ) + int buffer_caret = 0; + int bitmap_caret = 0; + int i = 0; +- int j = 0; + uint8_t encoded_pixels; + + if(overflow2(tga->width, tga->height)) { +@@ -280,43 +279,34 @@ int read_image_tga( gdIOCtx *ctx, oTga *tga ) + while( bitmap_caret < image_block_size ) { + + if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) { +- encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & 127 ) + 1 ); ++ encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & !TGA_RLE_FLAG ) + 1 ); + buffer_caret++; + +- if (encoded_pixels != 0) { +- +- if (!((buffer_caret + (encoded_pixels * pixel_block_size)) < image_block_size)) { +- gdFree( decompression_buffer ); +- gdFree( conversion_buffer ); +- return -1; +- } +- +- for (i = 0; i < encoded_pixels; i++) { +- for (j = 0; j < pixel_block_size; j++, bitmap_caret++) { +- tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ]; +- } +- } ++ if ((bitmap_caret + (encoded_pixels * pixel_block_size)) >= image_block_size) { ++ gdFree( decompression_buffer ); ++ gdFree( conversion_buffer ); ++ return -1; ++ } ++ ++ for (i = 0; i < encoded_pixels; i++) { ++ memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, pixel_block_size); ++ bitmap_caret += pixel_block_size; + } + buffer_caret += pixel_block_size; ++ + } else { + encoded_pixels = decompression_buffer[ buffer_caret ] + 1; + buffer_caret++; + +- if (encoded_pixels != 0) { +- +- if (!((buffer_caret + (encoded_pixels * pixel_block_size)) < image_block_size)) { +- gdFree( decompression_buffer ); +- gdFree( conversion_buffer ); +- return -1; +- } +- +- for (i = 0; i < encoded_pixels; i++) { +- for( j = 0; j < pixel_block_size; j++, bitmap_caret++ ) { +- tga->bitmap[ bitmap_caret ] = decompression_buffer[ buffer_caret + j ]; +- } +- buffer_caret += pixel_block_size; +- } ++ if ((bitmap_caret + (encoded_pixels * pixel_block_size)) >= image_block_size) { ++ gdFree( decompression_buffer ); ++ gdFree( conversion_buffer ); ++ return -1; + } ++ ++ memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, encoded_pixels * pixel_block_size); ++ bitmap_caret += (encoded_pixels * pixel_block_size); ++ buffer_caret += (encoded_pixels * pixel_block_size); + } + } + gdFree( decompression_buffer );",1114,1445,2048 +4483,"static int cg_getattr(const char *path, struct stat *sb) +{ + struct timespec now; + struct fuse_context *fc = fuse_get_context(); + char * cgdir = NULL; + char *fpath = NULL, *path1, *path2; + struct cgfs_files *k = NULL; + const char *cgroup; + const char *controller = NULL; + int ret = -ENOENT; + + + if (!fc) + return -EIO; + + memset(sb, 0, sizeof(struct stat)); + + if (clock_gettime(CLOCK_REALTIME, &now) < 0) + return -EINVAL; + + sb->st_uid = sb->st_gid = 0; + sb->st_atim = sb->st_mtim = sb->st_ctim = now; + sb->st_size = 0; + + if (strcmp(path, ""/cgroup"") == 0) { + sb->st_mode = S_IFDIR | 00755; + sb->st_nlink = 2; + return 0; + } + + controller = pick_controller_from_path(fc, path); + if (!controller) + return -EIO; + cgroup = find_cgroup_in_path(path); + if (!cgroup) { + /* this is just /cgroup/controller, return it as a dir */ + sb->st_mode = S_IFDIR | 00755; + sb->st_nlink = 2; + return 0; + } + + get_cgdir_and_path(cgroup, &cgdir, &fpath); + + if (!fpath) { + path1 = ""/""; + path2 = cgdir; + } else { + path1 = cgdir; + path2 = fpath; + } + + /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys. + * Then check that caller's cgroup is under path if fpath is a child + * cgroup, or cgdir if fpath is a file */ + + if (is_child_cgroup(controller, path1, path2)) { + if (!caller_may_see_dir(fc->pid, controller, cgroup)) { + ret = -ENOENT; + goto out; + } + if (!caller_is_in_ancestor(fc->pid, controller, cgroup, NULL)) { + /* this is just /cgroup/controller, return it as a dir */ + sb->st_mode = S_IFDIR | 00555; + sb->st_nlink = 2; + ret = 0; + goto out; + } + if (!fc_may_access(fc, controller, cgroup, NULL, O_RDONLY)) { + ret = -EACCES; + goto out; + } + + sb->st_mode = S_IFDIR | 00755; + k = cgfs_get_key(controller, cgroup, ""tasks""); + if (!k) { + sb->st_uid = sb->st_gid = 0; + } else { + sb->st_uid = k->uid; + sb->st_gid = k->gid; + } + free_key(k); + sb->st_nlink = 2; + ret = 0; + goto out; + } + + if ((k = cgfs_get_key(controller, path1, path2)) != NULL) { + sb->st_mode = S_IFREG | k->mode; + sb->st_nlink = 1; + sb->st_uid = k->uid; + sb->st_gid = k->gid; + sb->st_size = 0; + free_key(k); + if (!caller_is_in_ancestor(fc->pid, controller, path1, NULL)) { + ret = -ENOENT; + goto out; + } + if (!fc_may_access(fc, controller, path1, path2, O_RDONLY)) { + ret = -EACCES; + goto out; + } + + ret = 0; + } + +out: + free(cgdir); + return ret; +} +",0,"static int cg_getattr(const char *path, struct stat *sb) +{ + struct timespec now; + struct fuse_context *fc = fuse_get_context(); + char * cgdir = NULL; + char *fpath = NULL, *path1, *path2; + struct cgfs_files *k = NULL; + const char *cgroup; + const char *controller = NULL; + int ret = -ENOENT; + + + if (!fc) + return -EIO; + + memset(sb, 0, sizeof(struct stat)); + + if (clock_gettime(CLOCK_REALTIME, &now) < 0) + return -EINVAL; + + sb->st_uid = sb->st_gid = 0; + sb->st_atim = sb->st_mtim = sb->st_ctim = now; + sb->st_size = 0; + + if (strcmp(path, ""/cgroup"") == 0) { + sb->st_mode = S_IFDIR | 00755; + sb->st_nlink = 2; + return 0; + } + + controller = pick_controller_from_path(fc, path); + if (!controller) + return -EIO; + cgroup = find_cgroup_in_path(path); + if (!cgroup) { + /* this is just /cgroup/controller, return it as a dir */ + sb->st_mode = S_IFDIR | 00755; + sb->st_nlink = 2; + return 0; + } + + get_cgdir_and_path(cgroup, &cgdir, &fpath); + + if (!fpath) { + path1 = ""/""; + path2 = cgdir; + } else { + path1 = cgdir; + path2 = fpath; + } + + /* check that cgcopy is either a child cgroup of cgdir, or listed in its keys. + * Then check that caller's cgroup is under path if fpath is a child + * cgroup, or cgdir if fpath is a file */ + + if (is_child_cgroup(controller, path1, path2)) { + if (!caller_may_see_dir(fc->pid, controller, cgroup)) { + ret = -ENOENT; + goto out; + } + if (!caller_is_in_ancestor(fc->pid, controller, cgroup, NULL)) { + /* this is just /cgroup/controller, return it as a dir */ + sb->st_mode = S_IFDIR | 00555; + sb->st_nlink = 2; + ret = 0; + goto out; + } + if (!fc_may_access(fc, controller, cgroup, NULL, O_RDONLY)) { + ret = -EACCES; + goto out; + } + + sb->st_mode = S_IFDIR | 00755; + k = cgfs_get_key(controller, cgroup, ""tasks""); + if (!k) { + sb->st_uid = sb->st_gid = 0; + } else { + sb->st_uid = k->uid; + sb->st_gid = k->gid; + } + free_key(k); + sb->st_nlink = 2; + ret = 0; + goto out; + } + + if ((k = cgfs_get_key(controller, path1, path2)) != NULL) { + sb->st_mode = S_IFREG | k->mode; + sb->st_nlink = 1; + sb->st_uid = k->uid; + sb->st_gid = k->gid; + sb->st_size = 0; + free_key(k); + if (!caller_is_in_ancestor(fc->pid, controller, path1, NULL)) { + ret = -ENOENT; + goto out; + } + if (!fc_may_access(fc, controller, path1, path2, O_RDONLY)) { + ret = -EACCES; + goto out; + } + + ret = 0; + } + +out: + free(cgdir); + return ret; +} +","@@ -1336,7 +1336,95 @@ static void pid_from_ns_wrapper(int sock, pid_t tpid) + goto loop; + } + +-static bool do_write_pids(pid_t tpid, const char *contrl, const char *cg, const char *file, const char *buf) ++/* ++ * Given host @uid, return the uid to which it maps in ++ * @pid's user namespace, or -1 if none. ++ */ ++bool hostuid_to_ns(uid_t uid, pid_t pid, uid_t *answer) ++{ ++ FILE *f; ++ char line[400]; ++ ++ sprintf(line, ""/proc/%d/uid_map"", pid); ++ if ((f = fopen(line, ""r"")) == NULL) { ++ return false; ++ } ++ ++ *answer = convert_id_to_ns(f, uid); ++ fclose(f); ++ ++ if (*answer == -1) ++ return false; ++ return true; ++} ++ ++/* ++ * get_pid_creds: get the real uid and gid of @pid from ++ * /proc/$$/status ++ * (XXX should we use euid here?) ++ */ ++void get_pid_creds(pid_t pid, uid_t *uid, gid_t *gid) ++{ ++ char line[400]; ++ uid_t u; ++ gid_t g; ++ FILE *f; ++ ++ *uid = -1; ++ *gid = -1; ++ sprintf(line, ""/proc/%d/status"", pid); ++ if ((f = fopen(line, ""r"")) == NULL) { ++ fprintf(stderr, ""Error opening %s: %s\n"", line, strerror(errno)); ++ return; ++ } ++ while (fgets(line, 400, f)) { ++ if (strncmp(line, ""Uid:"", 4) == 0) { ++ if (sscanf(line+4, ""%u"", &u) != 1) { ++ fprintf(stderr, ""bad uid line for pid %u\n"", pid); ++ fclose(f); ++ return; ++ } ++ *uid = u; ++ } else if (strncmp(line, ""Gid:"", 4) == 0) { ++ if (sscanf(line+4, ""%u"", &g) != 1) { ++ fprintf(stderr, ""bad gid line for pid %u\n"", pid); ++ fclose(f); ++ return; ++ } ++ *gid = g; ++ } ++ } ++ fclose(f); ++} ++ ++/* ++ * May the requestor @r move victim @v to a new cgroup? ++ * This is allowed if ++ * . they are the same task ++ * . they are ownedy by the same uid ++ * . @r is root on the host, or ++ * . @v's uid is mapped into @r's where @r is root. ++ */ ++bool may_move_pid(pid_t r, uid_t r_uid, pid_t v) ++{ ++ uid_t v_uid, tmpuid; ++ gid_t v_gid; ++ ++ if (r == v) ++ return true; ++ if (r_uid == 0) ++ return true; ++ get_pid_creds(v, &v_uid, &v_gid); ++ if (r_uid == v_uid) ++ return true; ++ if (hostuid_to_ns(r_uid, r, &tmpuid) && tmpuid == 0 ++ && hostuid_to_ns(v_uid, r, &tmpuid)) ++ return true; ++ return false; ++} ++ ++static bool do_write_pids(pid_t tpid, uid_t tuid, const char *contrl, const char *cg, ++ const char *file, const char *buf) + { + int sock[2] = {-1, -1}; + pid_t qpid, cpid = -1; +@@ -1378,6 +1466,10 @@ static bool do_write_pids(pid_t tpid, const char *contrl, const char *cg, const + + if (recv_creds(sock[0], &cred, &v)) { + if (v == '0') { ++ if (!may_move_pid(tpid, tuid, cred.pid)) { ++ fail = true; ++ break; ++ } + if (fprintf(pids_file, ""%d"", (int) cred.pid) < 0) + fail = true; + } +@@ -1450,7 +1542,7 @@ int cg_write(const char *path, const char *buf, size_t size, off_t offset, + strcmp(f->file, ""/cgroup.procs"") == 0 || + strcmp(f->file, ""cgroup.procs"") == 0) + // special case - we have to translate the pids +- r = do_write_pids(fc->pid, f->controller, f->cgroup, f->file, localbuf); ++ r = do_write_pids(fc->pid, fc->uid, f->controller, f->cgroup, f->file, localbuf); + else + r = cgfs_set_value(f->controller, f->cgroup, f->file, localbuf); + ",843,1174,2048 +2922,"void ping_err(struct sk_buff *skb, int offset, u32 info) +{ + int family; + struct icmphdr *icmph; + struct inet_sock *inet_sock; + int type; + int code; + struct net *net = dev_net(skb->dev); + struct sock *sk; + int harderr; + int err; + + if (skb->protocol == htons(ETH_P_IP)) { + family = AF_INET; + type = icmp_hdr(skb)->type; + code = icmp_hdr(skb)->code; + icmph = (struct icmphdr *)(skb->data + offset); + } else if (skb->protocol == htons(ETH_P_IPV6)) { + family = AF_INET6; + type = icmp6_hdr(skb)->icmp6_type; + code = icmp6_hdr(skb)->icmp6_code; + icmph = (struct icmphdr *) (skb->data + offset); + } else { + BUG(); + } + + /* We assume the packet has already been checked by icmp_unreach */ + + if (!ping_supported(family, icmph->type, icmph->code)) + return; + + pr_debug(""ping_err(proto=0x%x,type=%d,code=%d,id=%04x,seq=%04x)\n"", + skb->protocol, type, code, ntohs(icmph->un.echo.id), + ntohs(icmph->un.echo.sequence)); + + sk = ping_lookup(net, skb, ntohs(icmph->un.echo.id)); + if (sk == NULL) { + pr_debug(""no socket, dropping\n""); + return; /* No socket for error */ + } + pr_debug(""err on socket %p\n"", sk); + + err = 0; + harderr = 0; + inet_sock = inet_sk(sk); + + if (skb->protocol == htons(ETH_P_IP)) { + switch (type) { + default: + case ICMP_TIME_EXCEEDED: + err = EHOSTUNREACH; + break; + case ICMP_SOURCE_QUENCH: + /* This is not a real error but ping wants to see it. + * Report it with some fake errno. + */ + err = EREMOTEIO; + break; + case ICMP_PARAMETERPROB: + err = EPROTO; + harderr = 1; + break; + case ICMP_DEST_UNREACH: + if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */ + ipv4_sk_update_pmtu(skb, sk, info); + if (inet_sock->pmtudisc != IP_PMTUDISC_DONT) { + err = EMSGSIZE; + harderr = 1; + break; + } + goto out; + } + err = EHOSTUNREACH; + if (code <= NR_ICMP_UNREACH) { + harderr = icmp_err_convert[code].fatal; + err = icmp_err_convert[code].errno; + } + break; + case ICMP_REDIRECT: + /* See ICMP_SOURCE_QUENCH */ + ipv4_sk_redirect(skb, sk); + err = EREMOTEIO; + break; + } +#if IS_ENABLED(CONFIG_IPV6) + } else if (skb->protocol == htons(ETH_P_IPV6)) { + harderr = pingv6_ops.icmpv6_err_convert(type, code, &err); +#endif + } + + /* + * RFC1122: OK. Passes ICMP errors back to application, as per + * 4.1.3.3. + */ + if ((family == AF_INET && !inet_sock->recverr) || + (family == AF_INET6 && !inet6_sk(sk)->recverr)) { + if (!harderr || sk->sk_state != TCP_ESTABLISHED) + goto out; + } else { + if (family == AF_INET) { + ip_icmp_error(sk, skb, err, 0 /* no remote port */, + info, (u8 *)icmph); +#if IS_ENABLED(CONFIG_IPV6) + } else if (family == AF_INET6) { + pingv6_ops.ipv6_icmp_error(sk, skb, err, 0, + info, (u8 *)icmph); +#endif + } + } + sk->sk_err = err; + sk->sk_error_report(sk); +out: + sock_put(sk); +} +",0,"void ping_err(struct sk_buff *skb, int offset, u32 info) +{ + int family; + struct icmphdr *icmph; + struct inet_sock *inet_sock; + int type; + int code; + struct net *net = dev_net(skb->dev); + struct sock *sk; + int harderr; + int err; + + if (skb->protocol == htons(ETH_P_IP)) { + family = AF_INET; + type = icmp_hdr(skb)->type; + code = icmp_hdr(skb)->code; + icmph = (struct icmphdr *)(skb->data + offset); + } else if (skb->protocol == htons(ETH_P_IPV6)) { + family = AF_INET6; + type = icmp6_hdr(skb)->icmp6_type; + code = icmp6_hdr(skb)->icmp6_code; + icmph = (struct icmphdr *) (skb->data + offset); + } else { + BUG(); + } + + /* We assume the packet has already been checked by icmp_unreach */ + + if (!ping_supported(family, icmph->type, icmph->code)) + return; + + pr_debug(""ping_err(proto=0x%x,type=%d,code=%d,id=%04x,seq=%04x)\n"", + skb->protocol, type, code, ntohs(icmph->un.echo.id), + ntohs(icmph->un.echo.sequence)); + + sk = ping_lookup(net, skb, ntohs(icmph->un.echo.id)); + if (sk == NULL) { + pr_debug(""no socket, dropping\n""); + return; /* No socket for error */ + } + pr_debug(""err on socket %p\n"", sk); + + err = 0; + harderr = 0; + inet_sock = inet_sk(sk); + + if (skb->protocol == htons(ETH_P_IP)) { + switch (type) { + default: + case ICMP_TIME_EXCEEDED: + err = EHOSTUNREACH; + break; + case ICMP_SOURCE_QUENCH: + /* This is not a real error but ping wants to see it. + * Report it with some fake errno. + */ + err = EREMOTEIO; + break; + case ICMP_PARAMETERPROB: + err = EPROTO; + harderr = 1; + break; + case ICMP_DEST_UNREACH: + if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */ + ipv4_sk_update_pmtu(skb, sk, info); + if (inet_sock->pmtudisc != IP_PMTUDISC_DONT) { + err = EMSGSIZE; + harderr = 1; + break; + } + goto out; + } + err = EHOSTUNREACH; + if (code <= NR_ICMP_UNREACH) { + harderr = icmp_err_convert[code].fatal; + err = icmp_err_convert[code].errno; + } + break; + case ICMP_REDIRECT: + /* See ICMP_SOURCE_QUENCH */ + ipv4_sk_redirect(skb, sk); + err = EREMOTEIO; + break; + } +#if IS_ENABLED(CONFIG_IPV6) + } else if (skb->protocol == htons(ETH_P_IPV6)) { + harderr = pingv6_ops.icmpv6_err_convert(type, code, &err); +#endif + } + + /* + * RFC1122: OK. Passes ICMP errors back to application, as per + * 4.1.3.3. + */ + if ((family == AF_INET && !inet_sock->recverr) || + (family == AF_INET6 && !inet6_sk(sk)->recverr)) { + if (!harderr || sk->sk_state != TCP_ESTABLISHED) + goto out; + } else { + if (family == AF_INET) { + ip_icmp_error(sk, skb, err, 0 /* no remote port */, + info, (u8 *)icmph); +#if IS_ENABLED(CONFIG_IPV6) + } else if (family == AF_INET6) { + pingv6_ops.ipv6_icmp_error(sk, skb, err, 0, + info, (u8 *)icmph); +#endif + } + } + sk->sk_err = err; + sk->sk_error_report(sk); +out: + sock_put(sk); +} +","@@ -870,11 +870,13 @@ int ping_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, + if (family == AF_INET) { + struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name; + +- sin->sin_family = AF_INET; +- sin->sin_port = 0 /* skb->h.uh->source */; +- sin->sin_addr.s_addr = ip_hdr(skb)->saddr; +- memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); +- *addr_len = sizeof(*sin); ++ if (sin) { ++ sin->sin_family = AF_INET; ++ sin->sin_port = 0 /* skb->h.uh->source */; ++ sin->sin_addr.s_addr = ip_hdr(skb)->saddr; ++ memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); ++ *addr_len = sizeof(*sin); ++ } + + if (isk->cmsg_flags) + ip_cmsg_recv(msg, skb); +@@ -886,16 +888,18 @@ int ping_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, + struct sockaddr_in6 *sin6 = + (struct sockaddr_in6 *)msg->msg_name; + +- sin6->sin6_family = AF_INET6; +- sin6->sin6_port = 0; +- sin6->sin6_addr = ip6->saddr; +- sin6->sin6_flowinfo = 0; +- if (np->sndflow) +- sin6->sin6_flowinfo = ip6_flowinfo(ip6); +- +- sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr, +- IP6CB(skb)->iif); +- *addr_len = sizeof(*sin6); ++ if (sin6) { ++ sin6->sin6_family = AF_INET6; ++ sin6->sin6_port = 0; ++ sin6->sin6_addr = ip6->saddr; ++ sin6->sin6_flowinfo = 0; ++ if (np->sndflow) ++ sin6->sin6_flowinfo = ip6_flowinfo(ip6); ++ sin6->sin6_scope_id = ++ ipv6_iface_scope_id(&sin6->sin6_addr, ++ IP6CB(skb)->iif); ++ *addr_len = sizeof(*sin6); ++ } + + if (inet6_sk(sk)->rxopt.all) + pingv6_ops.ip6_datagram_recv_ctl(sk, msg, skb);",917,1248,2048 +3118,"static int rose_sendmsg(struct kiocb *iocb, struct socket *sock, + struct msghdr *msg, size_t len) +{ + struct sock *sk = sock->sk; + struct rose_sock *rose = rose_sk(sk); + struct sockaddr_rose *usrose = (struct sockaddr_rose *)msg->msg_name; + int err; + struct full_sockaddr_rose srose; + struct sk_buff *skb; + unsigned char *asmptr; + int n, size, qbit = 0; + + if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_EOR|MSG_CMSG_COMPAT)) + return -EINVAL; + + if (sock_flag(sk, SOCK_ZAPPED)) + return -EADDRNOTAVAIL; + + if (sk->sk_shutdown & SEND_SHUTDOWN) { + send_sig(SIGPIPE, current, 0); + return -EPIPE; + } + + if (rose->neighbour == NULL || rose->device == NULL) + return -ENETUNREACH; + + if (usrose != NULL) { + if (msg->msg_namelen != sizeof(struct sockaddr_rose) && msg->msg_namelen != sizeof(struct full_sockaddr_rose)) + return -EINVAL; + memset(&srose, 0, sizeof(struct full_sockaddr_rose)); + memcpy(&srose, usrose, msg->msg_namelen); + if (rosecmp(&rose->dest_addr, &srose.srose_addr) != 0 || + ax25cmp(&rose->dest_call, &srose.srose_call) != 0) + return -EISCONN; + if (srose.srose_ndigis != rose->dest_ndigis) + return -EISCONN; + if (srose.srose_ndigis == rose->dest_ndigis) { + for (n = 0 ; n < srose.srose_ndigis ; n++) + if (ax25cmp(&rose->dest_digis[n], + &srose.srose_digis[n])) + return -EISCONN; + } + if (srose.srose_family != AF_ROSE) + return -EINVAL; + } else { + if (sk->sk_state != TCP_ESTABLISHED) + return -ENOTCONN; + + srose.srose_family = AF_ROSE; + srose.srose_addr = rose->dest_addr; + srose.srose_call = rose->dest_call; + srose.srose_ndigis = rose->dest_ndigis; + for (n = 0 ; n < rose->dest_ndigis ; n++) + srose.srose_digis[n] = rose->dest_digis[n]; + } + + /* Build a packet */ + /* Sanity check the packet size */ + if (len > 65535) + return -EMSGSIZE; + + size = len + AX25_BPQ_HEADER_LEN + AX25_MAX_HEADER_LEN + ROSE_MIN_LEN; + + if ((skb = sock_alloc_send_skb(sk, size, msg->msg_flags & MSG_DONTWAIT, &err)) == NULL) + return err; + + skb_reserve(skb, AX25_BPQ_HEADER_LEN + AX25_MAX_HEADER_LEN + ROSE_MIN_LEN); + + /* + * Put the data on the end + */ + + skb_reset_transport_header(skb); + skb_put(skb, len); + + err = memcpy_fromiovec(skb_transport_header(skb), msg->msg_iov, len); + if (err) { + kfree_skb(skb); + return err; + } + + /* + * If the Q BIT Include socket option is in force, the first + * byte of the user data is the logical value of the Q Bit. + */ + if (rose->qbitincl) { + qbit = skb->data[0]; + skb_pull(skb, 1); + } + + /* + * Push down the ROSE header + */ + asmptr = skb_push(skb, ROSE_MIN_LEN); + + /* Build a ROSE Network header */ + asmptr[0] = ((rose->lci >> 8) & 0x0F) | ROSE_GFI; + asmptr[1] = (rose->lci >> 0) & 0xFF; + asmptr[2] = ROSE_DATA; + + if (qbit) + asmptr[0] |= ROSE_Q_BIT; + + if (sk->sk_state != TCP_ESTABLISHED) { + kfree_skb(skb); + return -ENOTCONN; + } + +#ifdef M_BIT +#define ROSE_PACLEN (256-ROSE_MIN_LEN) + if (skb->len - ROSE_MIN_LEN > ROSE_PACLEN) { + unsigned char header[ROSE_MIN_LEN]; + struct sk_buff *skbn; + int frontlen; + int lg; + + /* Save a copy of the Header */ + skb_copy_from_linear_data(skb, header, ROSE_MIN_LEN); + skb_pull(skb, ROSE_MIN_LEN); + + frontlen = skb_headroom(skb); + + while (skb->len > 0) { + if ((skbn = sock_alloc_send_skb(sk, frontlen + ROSE_PACLEN, 0, &err)) == NULL) { + kfree_skb(skb); + return err; + } + + skbn->sk = sk; + skbn->free = 1; + skbn->arp = 1; + + skb_reserve(skbn, frontlen); + + lg = (ROSE_PACLEN > skb->len) ? skb->len : ROSE_PACLEN; + + /* Copy the user data */ + skb_copy_from_linear_data(skb, skb_put(skbn, lg), lg); + skb_pull(skb, lg); + + /* Duplicate the Header */ + skb_push(skbn, ROSE_MIN_LEN); + skb_copy_to_linear_data(skbn, header, ROSE_MIN_LEN); + + if (skb->len > 0) + skbn->data[2] |= M_BIT; + + skb_queue_tail(&sk->sk_write_queue, skbn); /* Throw it on the queue */ + } + + skb->free = 1; + kfree_skb(skb); + } else { + skb_queue_tail(&sk->sk_write_queue, skb); /* Throw it on the queue */ + } +#else + skb_queue_tail(&sk->sk_write_queue, skb); /* Shove it onto the queue */ +#endif + + rose_kick(sk); + + return len; +} +",0,"static int rose_sendmsg(struct kiocb *iocb, struct socket *sock, + struct msghdr *msg, size_t len) +{ + struct sock *sk = sock->sk; + struct rose_sock *rose = rose_sk(sk); + struct sockaddr_rose *usrose = (struct sockaddr_rose *)msg->msg_name; + int err; + struct full_sockaddr_rose srose; + struct sk_buff *skb; + unsigned char *asmptr; + int n, size, qbit = 0; + + if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_EOR|MSG_CMSG_COMPAT)) + return -EINVAL; + + if (sock_flag(sk, SOCK_ZAPPED)) + return -EADDRNOTAVAIL; + + if (sk->sk_shutdown & SEND_SHUTDOWN) { + send_sig(SIGPIPE, current, 0); + return -EPIPE; + } + + if (rose->neighbour == NULL || rose->device == NULL) + return -ENETUNREACH; + + if (usrose != NULL) { + if (msg->msg_namelen != sizeof(struct sockaddr_rose) && msg->msg_namelen != sizeof(struct full_sockaddr_rose)) + return -EINVAL; + memset(&srose, 0, sizeof(struct full_sockaddr_rose)); + memcpy(&srose, usrose, msg->msg_namelen); + if (rosecmp(&rose->dest_addr, &srose.srose_addr) != 0 || + ax25cmp(&rose->dest_call, &srose.srose_call) != 0) + return -EISCONN; + if (srose.srose_ndigis != rose->dest_ndigis) + return -EISCONN; + if (srose.srose_ndigis == rose->dest_ndigis) { + for (n = 0 ; n < srose.srose_ndigis ; n++) + if (ax25cmp(&rose->dest_digis[n], + &srose.srose_digis[n])) + return -EISCONN; + } + if (srose.srose_family != AF_ROSE) + return -EINVAL; + } else { + if (sk->sk_state != TCP_ESTABLISHED) + return -ENOTCONN; + + srose.srose_family = AF_ROSE; + srose.srose_addr = rose->dest_addr; + srose.srose_call = rose->dest_call; + srose.srose_ndigis = rose->dest_ndigis; + for (n = 0 ; n < rose->dest_ndigis ; n++) + srose.srose_digis[n] = rose->dest_digis[n]; + } + + /* Build a packet */ + /* Sanity check the packet size */ + if (len > 65535) + return -EMSGSIZE; + + size = len + AX25_BPQ_HEADER_LEN + AX25_MAX_HEADER_LEN + ROSE_MIN_LEN; + + if ((skb = sock_alloc_send_skb(sk, size, msg->msg_flags & MSG_DONTWAIT, &err)) == NULL) + return err; + + skb_reserve(skb, AX25_BPQ_HEADER_LEN + AX25_MAX_HEADER_LEN + ROSE_MIN_LEN); + + /* + * Put the data on the end + */ + + skb_reset_transport_header(skb); + skb_put(skb, len); + + err = memcpy_fromiovec(skb_transport_header(skb), msg->msg_iov, len); + if (err) { + kfree_skb(skb); + return err; + } + + /* + * If the Q BIT Include socket option is in force, the first + * byte of the user data is the logical value of the Q Bit. + */ + if (rose->qbitincl) { + qbit = skb->data[0]; + skb_pull(skb, 1); + } + + /* + * Push down the ROSE header + */ + asmptr = skb_push(skb, ROSE_MIN_LEN); + + /* Build a ROSE Network header */ + asmptr[0] = ((rose->lci >> 8) & 0x0F) | ROSE_GFI; + asmptr[1] = (rose->lci >> 0) & 0xFF; + asmptr[2] = ROSE_DATA; + + if (qbit) + asmptr[0] |= ROSE_Q_BIT; + + if (sk->sk_state != TCP_ESTABLISHED) { + kfree_skb(skb); + return -ENOTCONN; + } + +#ifdef M_BIT +#define ROSE_PACLEN (256-ROSE_MIN_LEN) + if (skb->len - ROSE_MIN_LEN > ROSE_PACLEN) { + unsigned char header[ROSE_MIN_LEN]; + struct sk_buff *skbn; + int frontlen; + int lg; + + /* Save a copy of the Header */ + skb_copy_from_linear_data(skb, header, ROSE_MIN_LEN); + skb_pull(skb, ROSE_MIN_LEN); + + frontlen = skb_headroom(skb); + + while (skb->len > 0) { + if ((skbn = sock_alloc_send_skb(sk, frontlen + ROSE_PACLEN, 0, &err)) == NULL) { + kfree_skb(skb); + return err; + } + + skbn->sk = sk; + skbn->free = 1; + skbn->arp = 1; + + skb_reserve(skbn, frontlen); + + lg = (ROSE_PACLEN > skb->len) ? skb->len : ROSE_PACLEN; + + /* Copy the user data */ + skb_copy_from_linear_data(skb, skb_put(skbn, lg), lg); + skb_pull(skb, lg); + + /* Duplicate the Header */ + skb_push(skbn, ROSE_MIN_LEN); + skb_copy_to_linear_data(skbn, header, ROSE_MIN_LEN); + + if (skb->len > 0) + skbn->data[2] |= M_BIT; + + skb_queue_tail(&sk->sk_write_queue, skbn); /* Throw it on the queue */ + } + + skb->free = 1; + kfree_skb(skb); + } else { + skb_queue_tail(&sk->sk_write_queue, skb); /* Throw it on the queue */ + } +#else + skb_queue_tail(&sk->sk_write_queue, skb); /* Shove it onto the queue */ +#endif + + rose_kick(sk); + + return len; +} +","@@ -1253,6 +1253,7 @@ static int rose_recvmsg(struct kiocb *iocb, struct socket *sock, + skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); + + if (srose != NULL) { ++ memset(srose, 0, msg->msg_namelen); + srose->srose_family = AF_ROSE; + srose->srose_addr = rose->dest_addr; + srose->srose_call = rose->dest_call;",1387,1718,2048 +473,"static time_t asn1_time_to_time_t(ASN1_UTCTIME * timestr) /* {{{ */ +{ +/* + This is how the time string is formatted: + + snprintf(p, sizeof(p), ""%02d%02d%02d%02d%02d%02dZ"",ts->tm_year%100, + ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec); +*/ + + time_t ret; + struct tm thetime; + char * strbuf; + char * thestr; + long gmadjust = 0; + size_t timestr_len; + + if (ASN1_STRING_type(timestr) != V_ASN1_UTCTIME && ASN1_STRING_type(timestr) != V_ASN1_GENERALIZEDTIME) { + php_error_docref(NULL, E_WARNING, ""illegal ASN1 data type for timestamp""); + return (time_t)-1; + } + + timestr_len = (size_t)ASN1_STRING_length(timestr); + + if (timestr_len != strlen((const char *)ASN1_STRING_get0_data(timestr))) { + php_error_docref(NULL, E_WARNING, ""illegal length in timestamp""); + return (time_t)-1; + } + + if (timestr_len < 13 && timestr_len != 11) { + php_error_docref(NULL, E_WARNING, ""unable to parse time string %s correctly"", timestr->data); + return (time_t)-1; + } + + if (ASN1_STRING_type(timestr) == V_ASN1_GENERALIZEDTIME && timestr_len < 15) { + php_error_docref(NULL, E_WARNING, ""unable to parse time string %s correctly"", timestr->data); + return (time_t)-1; + } + + strbuf = estrdup((const char *)ASN1_STRING_get0_data(timestr)); + + memset(&thetime, 0, sizeof(thetime)); + + /* we work backwards so that we can use atoi more easily */ + + thestr = strbuf + timestr_len - 3; + + if (timestr_len == 11) { + thetime.tm_sec = 0; + } else { + thetime.tm_sec = atoi(thestr); + *thestr = '\0'; + thestr -= 2; + } + thetime.tm_min = atoi(thestr); + *thestr = '\0'; + thestr -= 2; + thetime.tm_hour = atoi(thestr); + *thestr = '\0'; + thestr -= 2; + thetime.tm_mday = atoi(thestr); + *thestr = '\0'; + thestr -= 2; + thetime.tm_mon = atoi(thestr)-1; + + *thestr = '\0'; + if( ASN1_STRING_type(timestr) == V_ASN1_UTCTIME ) { + thestr -= 2; + thetime.tm_year = atoi(thestr); + + if (thetime.tm_year < 68) { + thetime.tm_year += 100; + } + } else if( ASN1_STRING_type(timestr) == V_ASN1_GENERALIZEDTIME ) { + thestr -= 4; + thetime.tm_year = atoi(thestr) - 1900; + } + + + thetime.tm_isdst = -1; + ret = mktime(&thetime); + +#if HAVE_TM_GMTOFF + gmadjust = thetime.tm_gmtoff; +#else + /* + ** If correcting for daylight savings time, we set the adjustment to + ** the value of timezone - 3600 seconds. Otherwise, we need to overcorrect and + ** set the adjustment to the main timezone + 3600 seconds. + */ + gmadjust = -(thetime.tm_isdst ? (long)timezone - 3600 : (long)timezone); +#endif + ret += gmadjust; + + efree(strbuf); + + return ret; +} +/* }}} */ +",0,"static time_t asn1_time_to_time_t(ASN1_UTCTIME * timestr) /* {{{ */ +{ +/* + This is how the time string is formatted: + + snprintf(p, sizeof(p), ""%02d%02d%02d%02d%02d%02dZ"",ts->tm_year%100, + ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec); +*/ + + time_t ret; + struct tm thetime; + char * strbuf; + char * thestr; + long gmadjust = 0; + size_t timestr_len; + + if (ASN1_STRING_type(timestr) != V_ASN1_UTCTIME && ASN1_STRING_type(timestr) != V_ASN1_GENERALIZEDTIME) { + php_error_docref(NULL, E_WARNING, ""illegal ASN1 data type for timestamp""); + return (time_t)-1; + } + + timestr_len = (size_t)ASN1_STRING_length(timestr); + + if (timestr_len != strlen((const char *)ASN1_STRING_get0_data(timestr))) { + php_error_docref(NULL, E_WARNING, ""illegal length in timestamp""); + return (time_t)-1; + } + + if (timestr_len < 13 && timestr_len != 11) { + php_error_docref(NULL, E_WARNING, ""unable to parse time string %s correctly"", timestr->data); + return (time_t)-1; + } + + if (ASN1_STRING_type(timestr) == V_ASN1_GENERALIZEDTIME && timestr_len < 15) { + php_error_docref(NULL, E_WARNING, ""unable to parse time string %s correctly"", timestr->data); + return (time_t)-1; + } + + strbuf = estrdup((const char *)ASN1_STRING_get0_data(timestr)); + + memset(&thetime, 0, sizeof(thetime)); + + /* we work backwards so that we can use atoi more easily */ + + thestr = strbuf + timestr_len - 3; + + if (timestr_len == 11) { + thetime.tm_sec = 0; + } else { + thetime.tm_sec = atoi(thestr); + *thestr = '\0'; + thestr -= 2; + } + thetime.tm_min = atoi(thestr); + *thestr = '\0'; + thestr -= 2; + thetime.tm_hour = atoi(thestr); + *thestr = '\0'; + thestr -= 2; + thetime.tm_mday = atoi(thestr); + *thestr = '\0'; + thestr -= 2; + thetime.tm_mon = atoi(thestr)-1; + + *thestr = '\0'; + if( ASN1_STRING_type(timestr) == V_ASN1_UTCTIME ) { + thestr -= 2; + thetime.tm_year = atoi(thestr); + + if (thetime.tm_year < 68) { + thetime.tm_year += 100; + } + } else if( ASN1_STRING_type(timestr) == V_ASN1_GENERALIZEDTIME ) { + thestr -= 4; + thetime.tm_year = atoi(thestr) - 1900; + } + + + thetime.tm_isdst = -1; + ret = mktime(&thetime); + +#if HAVE_TM_GMTOFF + gmadjust = thetime.tm_gmtoff; +#else + /* + ** If correcting for daylight savings time, we set the adjustment to + ** the value of timezone - 3600 seconds. Otherwise, we need to overcorrect and + ** set the adjustment to the main timezone + 3600 seconds. + */ + gmadjust = -(thetime.tm_isdst ? (long)timezone - 3600 : (long)timezone); +#endif + ret += gmadjust; + + efree(strbuf); + + return ret; +} +/* }}} */ +","@@ -5421,7 +5421,7 @@ PHP_FUNCTION(openssl_seal) + buf = emalloc(data_len + EVP_CIPHER_CTX_block_size(ctx)); + EVP_CIPHER_CTX_cleanup(ctx); + +- if (!EVP_SealInit(ctx, cipher, eks, eksl, &iv_buf[0], pkeys, nkeys) || ++ if (EVP_SealInit(ctx, cipher, eks, eksl, &iv_buf[0], pkeys, nkeys) <= 0 || + !EVP_SealUpdate(ctx, buf, &len1, (unsigned char *)data, (int)data_len) || + !EVP_SealFinal(ctx, buf + len1, &len2)) { + RETVAL_FALSE;",858,1189,2048 +18005,"static void _php_image_convert(INTERNAL_FUNCTION_PARAMETERS, int image_type ) +{ + char *f_org, *f_dest; + int f_org_len, f_dest_len; + long height, width, threshold; + gdImagePtr im_org, im_dest, im_tmp; + char *fn_org = NULL; + char *fn_dest = NULL; + FILE *org, *dest; + int dest_height = -1; + int dest_width = -1; + int org_height, org_width; + int white, black; + int color, color_org, median; + int int_threshold; + int x, y; + float x_ratio, y_ratio; + long ignore_warning; + if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""pplll"", &f_org, &f_org_len, &f_dest, &f_dest_len, &height, &width, &threshold) == FAILURE) { + return; + } + + fn_org = f_org; + fn_dest = f_dest; + dest_height = height; + dest_width = width; + int_threshold = threshold; + + /* Check threshold value */ + if (int_threshold < 0 || int_threshold > 8) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Invalid threshold value '%d'"", int_threshold); + RETURN_FALSE; + } + + /* Check origin file */ + PHP_GD_CHECK_OPEN_BASEDIR(fn_org, ""Invalid origin filename""); + + /* Check destination file */ + PHP_GD_CHECK_OPEN_BASEDIR(fn_dest, ""Invalid destination filename""); + + /* Open origin file */ + org = VCWD_FOPEN(fn_org, ""rb""); + if (!org) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to open '%s' for reading"", fn_org); + RETURN_FALSE; + } + + /* Open destination file */ + dest = VCWD_FOPEN(fn_dest, ""wb""); + if (!dest) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to open '%s' for writing"", fn_dest); + RETURN_FALSE; + } + + switch (image_type) { + case PHP_GDIMG_TYPE_GIF: + im_org = gdImageCreateFromGif(org); + if (im_org == NULL) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to open '%s' Not a valid GIF file"", fn_dest); + RETURN_FALSE; + } + break; + +#ifdef HAVE_GD_JPG + case PHP_GDIMG_TYPE_JPG: + ignore_warning = INI_INT(""gd.jpeg_ignore_warning""); + im_org = gdImageCreateFromJpegEx(org, ignore_warning); + if (im_org == NULL) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to open '%s' Not a valid JPEG file"", fn_dest); + RETURN_FALSE; + } + break; +#endif /* HAVE_GD_JPG */ + +#ifdef HAVE_GD_PNG + case PHP_GDIMG_TYPE_PNG: + im_org = gdImageCreateFromPng(org); + if (im_org == NULL) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to open '%s' Not a valid PNG file"", fn_dest); + RETURN_FALSE; + } + break; +#endif /* HAVE_GD_PNG */ + + default: + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Format not supported""); + RETURN_FALSE; + break; + } + + org_width = gdImageSX (im_org); + org_height = gdImageSY (im_org); + + x_ratio = (float) org_width / (float) dest_width; + y_ratio = (float) org_height / (float) dest_height; + + if (x_ratio > 1 && y_ratio > 1) { + if (y_ratio > x_ratio) { + x_ratio = y_ratio; + } else { + y_ratio = x_ratio; + } + dest_width = (int) (org_width / x_ratio); + dest_height = (int) (org_height / y_ratio); + } else { + x_ratio = (float) dest_width / (float) org_width; + y_ratio = (float) dest_height / (float) org_height; + + if (y_ratio < x_ratio) { + x_ratio = y_ratio; + } else { + y_ratio = x_ratio; + } + dest_width = (int) (org_width * x_ratio); + dest_height = (int) (org_height * y_ratio); + } + + im_tmp = gdImageCreate (dest_width, dest_height); + if (im_tmp == NULL ) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to allocate temporary buffer""); + RETURN_FALSE; + } + + gdImageCopyResized (im_tmp, im_org, 0, 0, 0, 0, dest_width, dest_height, org_width, org_height); + + gdImageDestroy(im_org); + + fclose(org); + + im_dest = gdImageCreate(dest_width, dest_height); + if (im_dest == NULL) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to allocate destination buffer""); + RETURN_FALSE; + } + + white = gdImageColorAllocate(im_dest, 255, 255, 255); + if (white == -1) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to allocate the colors for the destination buffer""); + RETURN_FALSE; + } + + black = gdImageColorAllocate(im_dest, 0, 0, 0); + if (black == -1) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to allocate the colors for the destination buffer""); + RETURN_FALSE; + } + + int_threshold = int_threshold * 32; + + for (y = 0; y < dest_height; y++) { + for (x = 0; x < dest_width; x++) { + color_org = gdImageGetPixel (im_tmp, x, y); + median = (im_tmp->red[color_org] + im_tmp->green[color_org] + im_tmp->blue[color_org]) / 3; + if (median < int_threshold) { + color = black; + } else { + color = white; + } + gdImageSetPixel (im_dest, x, y, color); + } + } + + gdImageDestroy (im_tmp ); + + gdImageWBMP(im_dest, black , dest); + + fflush(dest); + fclose(dest); + + gdImageDestroy(im_dest); + + RETURN_TRUE; +} +",1,"static void _php_image_convert(INTERNAL_FUNCTION_PARAMETERS, int image_type ) +{ + char *f_org, *f_dest; + int f_org_len, f_dest_len; + long height, width, threshold; + gdImagePtr im_org, im_dest, im_tmp; + char *fn_org = NULL; + char *fn_dest = NULL; + FILE *org, *dest; + int dest_height = -1; + int dest_width = -1; + int org_height, org_width; + int white, black; + int color, color_org, median; + int int_threshold; + int x, y; + float x_ratio, y_ratio; + long ignore_warning; + + if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""pplll"", &f_org, &f_org_len, &f_dest, &f_dest_len, &height, &width, &threshold) == FAILURE) { + return; + } + + fn_org = f_org; + fn_dest = f_dest; + dest_height = height; + dest_width = width; + int_threshold = threshold; + + /* Check threshold value */ + if (int_threshold < 0 || int_threshold > 8) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Invalid threshold value '%d'"", int_threshold); + RETURN_FALSE; + } + + /* Check origin file */ + PHP_GD_CHECK_OPEN_BASEDIR(fn_org, ""Invalid origin filename""); + + /* Check destination file */ + PHP_GD_CHECK_OPEN_BASEDIR(fn_dest, ""Invalid destination filename""); + + /* Open origin file */ + org = VCWD_FOPEN(fn_org, ""rb""); + if (!org) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to open '%s' for reading"", fn_org); + RETURN_FALSE; + } + + /* Open destination file */ + dest = VCWD_FOPEN(fn_dest, ""wb""); + if (!dest) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to open '%s' for writing"", fn_dest); + RETURN_FALSE; + } + + switch (image_type) { + case PHP_GDIMG_TYPE_GIF: + im_org = gdImageCreateFromGif(org); + if (im_org == NULL) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to open '%s' Not a valid GIF file"", fn_dest); + RETURN_FALSE; + } + break; + +#ifdef HAVE_GD_JPG + case PHP_GDIMG_TYPE_JPG: + ignore_warning = INI_INT(""gd.jpeg_ignore_warning""); + im_org = gdImageCreateFromJpegEx(org, ignore_warning); + if (im_org == NULL) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to open '%s' Not a valid JPEG file"", fn_dest); + RETURN_FALSE; + } + break; +#endif /* HAVE_GD_JPG */ + +#ifdef HAVE_GD_PNG + case PHP_GDIMG_TYPE_PNG: + im_org = gdImageCreateFromPng(org); + if (im_org == NULL) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to open '%s' Not a valid PNG file"", fn_dest); + RETURN_FALSE; + } + break; +#endif /* HAVE_GD_PNG */ + + default: + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Format not supported""); + RETURN_FALSE; + break; + } + + org_width = gdImageSX (im_org); + org_height = gdImageSY (im_org); + + x_ratio = (float) org_width / (float) dest_width; + y_ratio = (float) org_height / (float) dest_height; + + if (x_ratio > 1 && y_ratio > 1) { + if (y_ratio > x_ratio) { + x_ratio = y_ratio; + } else { + y_ratio = x_ratio; + } + dest_width = (int) (org_width / x_ratio); + dest_height = (int) (org_height / y_ratio); + } else { + x_ratio = (float) dest_width / (float) org_width; + y_ratio = (float) dest_height / (float) org_height; + + if (y_ratio < x_ratio) { + x_ratio = y_ratio; + } else { + y_ratio = x_ratio; + } + dest_width = (int) (org_width * x_ratio); + dest_height = (int) (org_height * y_ratio); + } + + im_tmp = gdImageCreate (dest_width, dest_height); + if (im_tmp == NULL ) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to allocate temporary buffer""); + RETURN_FALSE; + } + + gdImageCopyResized (im_tmp, im_org, 0, 0, 0, 0, dest_width, dest_height, org_width, org_height); + + gdImageDestroy(im_org); + + fclose(org); + + im_dest = gdImageCreate(dest_width, dest_height); + if (im_dest == NULL) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to allocate destination buffer""); + RETURN_FALSE; + } + + white = gdImageColorAllocate(im_dest, 255, 255, 255); + if (white == -1) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to allocate the colors for the destination buffer""); + RETURN_FALSE; + } + + black = gdImageColorAllocate(im_dest, 0, 0, 0); + if (black == -1) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Unable to allocate the colors for the destination buffer""); + RETURN_FALSE; + } + + int_threshold = int_threshold * 32; + + for (y = 0; y < dest_height; y++) { + for (x = 0; x < dest_width; x++) { + color_org = gdImageGetPixel (im_tmp, x, y); + median = (im_tmp->red[color_org] + im_tmp->green[color_org] + im_tmp->blue[color_org]) / 3; + if (median < int_threshold) { + color = black; + } else { + color = white; + } + gdImageSetPixel (im_dest, x, y, color); + } + } + + gdImageDestroy (im_tmp ); + + gdImageWBMP(im_dest, black , dest); + + fflush(dest); + fclose(dest); + + gdImageDestroy(im_dest); + + RETURN_TRUE; +} +","@@ -99,7 +99,7 @@ static void php_imagettftext_common(INTERNAL_FUNCTION_PARAMETERS, int, int); + + #include ""gd_ctx.c"" + +-/* as it is not really public, duplicate declaration here to avoid ++/* as it is not really public, duplicate declaration here to avoid + pointless warnings */ + int overflow2(int a, int b); + +@@ -1197,7 +1197,7 @@ PHP_MINIT_FUNCTION(gd) + REGISTER_LONG_CONSTANT(""IMG_CROP_SIDES"", GD_CROP_SIDES, CONST_CS | CONST_PERSISTENT); + REGISTER_LONG_CONSTANT(""IMG_CROP_THRESHOLD"", GD_CROP_THRESHOLD, CONST_CS | CONST_PERSISTENT); + +- ++ + REGISTER_LONG_CONSTANT(""IMG_BELL"", GD_BELL, CONST_CS | CONST_PERSISTENT); + REGISTER_LONG_CONSTANT(""IMG_BESSEL"", GD_BESSEL, CONST_CS | CONST_PERSISTENT); + REGISTER_LONG_CONSTANT(""IMG_BILINEAR_FIXED"", GD_BILINEAR_FIXED, CONST_CS | CONST_PERSISTENT); +@@ -1651,11 +1651,11 @@ PHP_FUNCTION(imagetruecolortopalette) + + ZEND_FETCH_RESOURCE(im, gdImagePtr, &IM, -1, ""Image"", le_gd); + +- if (ncolors <= 0) { +- php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Number of colors has to be greater than zero""); ++ if (ncolors <= 0 || ncolors > INT_MAX) { ++ php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Number of colors has to be greater than zero and no more than %d"", INT_MAX); + RETURN_FALSE; + } +- gdImageTrueColorToPalette(im, dither, ncolors); ++ gdImageTrueColorToPalette(im, dither, (int)ncolors); + + RETURN_TRUE; + } +@@ -3906,7 +3906,7 @@ static void php_imagettftext_common(INTERNAL_FUNCTION_PARAMETERS, int mode, int + #endif /* VIRTUAL_DIR */ + + PHP_GD_CHECK_OPEN_BASEDIR(fontname, ""Invalid font filename""); +- ++ + #ifdef HAVE_GD_FREETYPE + if (extended) { + error = gdImageStringFTEx(im, brect, col, fontname, ptsize, angle, x, y, str, &strex); +@@ -4484,7 +4484,7 @@ static void _php_image_convert(INTERNAL_FUNCTION_PARAMETERS, int image_type ) + int x, y; + float x_ratio, y_ratio; + long ignore_warning; +- ++ + if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, ""pplll"", &f_org, &f_org_len, &f_dest, &f_dest_len, &height, &width, &threshold) == FAILURE) { + return; + } +@@ -5367,7 +5367,7 @@ PHP_FUNCTION(imageaffinematrixget) + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Missing y position""); + RETURN_FALSE; + } +- ++ + if (type == GD_AFFINE_TRANSLATE) { + res = gdAffineTranslate(affine, x, y); + } else {",1373,1704,2048 +9657,"_gcry_aes_ocb_crypt (gcry_cipher_hd_t c, void *outbuf_arg, + const void *inbuf_arg, size_t nblocks, int encrypt) +{ + RIJNDAEL_context *ctx = (void *)&c->context.c; + unsigned char *outbuf = outbuf_arg; + const unsigned char *inbuf = inbuf_arg; + unsigned int burn_depth = 0; + + if (0) + ; +#ifdef USE_AESNI + else if (ctx->use_aesni) + { + return _gcry_aes_aesni_ocb_crypt (c, outbuf, inbuf, nblocks, encrypt); + } +#endif /*USE_AESNI*/ +#ifdef USE_SSSE3 + else if (ctx->use_ssse3) + { + return _gcry_aes_ssse3_ocb_crypt (c, outbuf, inbuf, nblocks, encrypt); + } +#endif /*USE_SSSE3*/ +#ifdef USE_ARM_CE + else if (ctx->use_arm_ce) + { + return _gcry_aes_armv8_ce_ocb_crypt (c, outbuf, inbuf, nblocks, encrypt); + } +#endif /*USE_ARM_CE*/ + else if (encrypt) + { + union { unsigned char x1[16] ATTR_ALIGNED_16; u32 x32[4]; } l_tmp; + rijndael_cryptfn_t encrypt_fn = ctx->encrypt_fn; + + if (ctx->prefetch_enc_fn) + ctx->prefetch_enc_fn(); + + for ( ;nblocks; nblocks-- ) + { + u64 i = ++c->u_mode.ocb.data_nblocks; + const unsigned char *l = ocb_get_l(c, i); + + /* Offset_i = Offset_{i-1} xor L_{ntz(i)} */ + cipher_block_xor_1 (c->u_iv.iv, l, BLOCKSIZE); + cipher_block_cpy (l_tmp.x1, inbuf, BLOCKSIZE); + /* Checksum_i = Checksum_{i-1} xor P_i */ + cipher_block_xor_1 (c->u_ctr.ctr, l_tmp.x1, BLOCKSIZE); + /* C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i) */ + cipher_block_xor_1 (l_tmp.x1, c->u_iv.iv, BLOCKSIZE); + burn_depth = encrypt_fn (ctx, l_tmp.x1, l_tmp.x1); + cipher_block_xor_1 (l_tmp.x1, c->u_iv.iv, BLOCKSIZE); + cipher_block_cpy (outbuf, l_tmp.x1, BLOCKSIZE); + + inbuf += BLOCKSIZE; + outbuf += BLOCKSIZE; + } + } + else + { + union { unsigned char x1[16] ATTR_ALIGNED_16; u32 x32[4]; } l_tmp; + rijndael_cryptfn_t decrypt_fn = ctx->decrypt_fn; + + check_decryption_preparation (ctx); + + if (ctx->prefetch_dec_fn) + ctx->prefetch_dec_fn(); + + for ( ;nblocks; nblocks-- ) + { + u64 i = ++c->u_mode.ocb.data_nblocks; + const unsigned char *l = ocb_get_l(c, i); + + /* Offset_i = Offset_{i-1} xor L_{ntz(i)} */ + cipher_block_xor_1 (c->u_iv.iv, l, BLOCKSIZE); + cipher_block_cpy (l_tmp.x1, inbuf, BLOCKSIZE); + /* C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i) */ + cipher_block_xor_1 (l_tmp.x1, c->u_iv.iv, BLOCKSIZE); + burn_depth = decrypt_fn (ctx, l_tmp.x1, l_tmp.x1); + cipher_block_xor_1 (l_tmp.x1, c->u_iv.iv, BLOCKSIZE); + /* Checksum_i = Checksum_{i-1} xor P_i */ + cipher_block_xor_1 (c->u_ctr.ctr, l_tmp.x1, BLOCKSIZE); + cipher_block_cpy (outbuf, l_tmp.x1, BLOCKSIZE); + + inbuf += BLOCKSIZE; + outbuf += BLOCKSIZE; + } + } + + if (burn_depth) + _gcry_burn_stack (burn_depth + 4 * sizeof(void *)); + + return 0; +} +",0,"_gcry_aes_ocb_crypt (gcry_cipher_hd_t c, void *outbuf_arg, + const void *inbuf_arg, size_t nblocks, int encrypt) +{ + RIJNDAEL_context *ctx = (void *)&c->context.c; + unsigned char *outbuf = outbuf_arg; + const unsigned char *inbuf = inbuf_arg; + unsigned int burn_depth = 0; + + if (0) + ; +#ifdef USE_AESNI + else if (ctx->use_aesni) + { + return _gcry_aes_aesni_ocb_crypt (c, outbuf, inbuf, nblocks, encrypt); + } +#endif /*USE_AESNI*/ +#ifdef USE_SSSE3 + else if (ctx->use_ssse3) + { + return _gcry_aes_ssse3_ocb_crypt (c, outbuf, inbuf, nblocks, encrypt); + } +#endif /*USE_SSSE3*/ +#ifdef USE_ARM_CE + else if (ctx->use_arm_ce) + { + return _gcry_aes_armv8_ce_ocb_crypt (c, outbuf, inbuf, nblocks, encrypt); + } +#endif /*USE_ARM_CE*/ + else if (encrypt) + { + union { unsigned char x1[16] ATTR_ALIGNED_16; u32 x32[4]; } l_tmp; + rijndael_cryptfn_t encrypt_fn = ctx->encrypt_fn; + + if (ctx->prefetch_enc_fn) + ctx->prefetch_enc_fn(); + + for ( ;nblocks; nblocks-- ) + { + u64 i = ++c->u_mode.ocb.data_nblocks; + const unsigned char *l = ocb_get_l(c, i); + + /* Offset_i = Offset_{i-1} xor L_{ntz(i)} */ + cipher_block_xor_1 (c->u_iv.iv, l, BLOCKSIZE); + cipher_block_cpy (l_tmp.x1, inbuf, BLOCKSIZE); + /* Checksum_i = Checksum_{i-1} xor P_i */ + cipher_block_xor_1 (c->u_ctr.ctr, l_tmp.x1, BLOCKSIZE); + /* C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i) */ + cipher_block_xor_1 (l_tmp.x1, c->u_iv.iv, BLOCKSIZE); + burn_depth = encrypt_fn (ctx, l_tmp.x1, l_tmp.x1); + cipher_block_xor_1 (l_tmp.x1, c->u_iv.iv, BLOCKSIZE); + cipher_block_cpy (outbuf, l_tmp.x1, BLOCKSIZE); + + inbuf += BLOCKSIZE; + outbuf += BLOCKSIZE; + } + } + else + { + union { unsigned char x1[16] ATTR_ALIGNED_16; u32 x32[4]; } l_tmp; + rijndael_cryptfn_t decrypt_fn = ctx->decrypt_fn; + + check_decryption_preparation (ctx); + + if (ctx->prefetch_dec_fn) + ctx->prefetch_dec_fn(); + + for ( ;nblocks; nblocks-- ) + { + u64 i = ++c->u_mode.ocb.data_nblocks; + const unsigned char *l = ocb_get_l(c, i); + + /* Offset_i = Offset_{i-1} xor L_{ntz(i)} */ + cipher_block_xor_1 (c->u_iv.iv, l, BLOCKSIZE); + cipher_block_cpy (l_tmp.x1, inbuf, BLOCKSIZE); + /* C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i) */ + cipher_block_xor_1 (l_tmp.x1, c->u_iv.iv, BLOCKSIZE); + burn_depth = decrypt_fn (ctx, l_tmp.x1, l_tmp.x1); + cipher_block_xor_1 (l_tmp.x1, c->u_iv.iv, BLOCKSIZE); + /* Checksum_i = Checksum_{i-1} xor P_i */ + cipher_block_xor_1 (c->u_ctr.ctr, l_tmp.x1, BLOCKSIZE); + cipher_block_cpy (outbuf, l_tmp.x1, BLOCKSIZE); + + inbuf += BLOCKSIZE; + outbuf += BLOCKSIZE; + } + } + + if (burn_depth) + _gcry_burn_stack (burn_depth + 4 * sizeof(void *)); + + return 0; +} +","@@ -218,11 +218,11 @@ static const char *selftest(void); + + + /* Prefetching for encryption/decryption tables. */ +-static void prefetch_table(const volatile byte *tab, size_t len) ++static inline void prefetch_table(const volatile byte *tab, size_t len) + { + size_t i; + +- for (i = 0; i < len; i += 8 * 32) ++ for (i = 0; len - i >= 8 * 32; i += 8 * 32) + { + (void)tab[i + 0 * 32]; + (void)tab[i + 1 * 32]; +@@ -233,17 +233,37 @@ static void prefetch_table(const volatile byte *tab, size_t len) + (void)tab[i + 6 * 32]; + (void)tab[i + 7 * 32]; + } ++ for (; i < len; i += 32) ++ { ++ (void)tab[i]; ++ } + + (void)tab[len - 1]; + } + + static void prefetch_enc(void) + { +- prefetch_table((const void *)encT, sizeof(encT)); ++ /* Modify counters to trigger copy-on-write and unsharing if physical pages ++ * of look-up table are shared between processes. Modifying counters also ++ * causes checksums for pages to change and hint same-page merging algorithm ++ * that these pages are frequently changing. */ ++ enc_tables.counter_head++; ++ enc_tables.counter_tail++; ++ ++ /* Prefetch look-up tables to cache. */ ++ prefetch_table((const void *)&enc_tables, sizeof(enc_tables)); + } + + static void prefetch_dec(void) + { ++ /* Modify counters to trigger copy-on-write and unsharing if physical pages ++ * of look-up table are shared between processes. Modifying counters also ++ * causes checksums for pages to change and hint same-page merging algorithm ++ * that these pages are frequently changing. */ ++ dec_tables.counter_head++; ++ dec_tables.counter_tail++; ++ ++ /* Prefetch look-up tables to cache. */ + prefetch_table((const void *)&dec_tables, sizeof(dec_tables)); + } + +@@ -765,9 +785,10 @@ do_encrypt (const RIJNDAEL_context *ctx, + { + #ifdef USE_AMD64_ASM + return _gcry_aes_amd64_encrypt_block(ctx->keyschenc, bx, ax, ctx->rounds, +- encT); ++ enc_tables.T); + #elif defined(USE_ARM_ASM) +- return _gcry_aes_arm_encrypt_block(ctx->keyschenc, bx, ax, ctx->rounds, encT); ++ return _gcry_aes_arm_encrypt_block(ctx->keyschenc, bx, ax, ctx->rounds, ++ enc_tables.T); + #else + return do_encrypt_fn (ctx, bx, ax); + #endif /* !USE_ARM_ASM && !USE_AMD64_ASM*/ +@@ -1123,10 +1144,10 @@ do_decrypt (const RIJNDAEL_context *ctx, unsigned char *bx, + { + #ifdef USE_AMD64_ASM + return _gcry_aes_amd64_decrypt_block(ctx->keyschdec, bx, ax, ctx->rounds, +- &dec_tables); ++ dec_tables.T); + #elif defined(USE_ARM_ASM) + return _gcry_aes_arm_decrypt_block(ctx->keyschdec, bx, ax, ctx->rounds, +- &dec_tables); ++ dec_tables.T); + #else + return do_decrypt_fn (ctx, bx, ax); + #endif /*!USE_ARM_ASM && !USE_AMD64_ASM*/",947,1278,2048 +2830,"static netdev_tx_t ipip6_tunnel_xmit(struct sk_buff *skb, + struct net_device *dev) +{ + struct ip_tunnel *tunnel = netdev_priv(dev); + struct net_device_stats *stats = &dev->stats; + struct netdev_queue *txq = netdev_get_tx_queue(dev, 0); + struct iphdr *tiph = &tunnel->parms.iph; + struct ipv6hdr *iph6 = ipv6_hdr(skb); + u8 tos = tunnel->parms.iph.tos; + __be16 df = tiph->frag_off; + struct rtable *rt; /* Route to the other host */ + struct net_device *tdev; /* Device to other host */ + struct iphdr *iph; /* Our new IP header */ + unsigned int max_headroom; /* The extra header space needed */ + __be32 dst = tiph->daddr; + int mtu; + struct in6_addr *addr6; + int addr_type; + + if (skb->protocol != htons(ETH_P_IPV6)) + goto tx_error; + + /* ISATAP (RFC4214) - must come before 6to4 */ + if (dev->priv_flags & IFF_ISATAP) { + struct neighbour *neigh = NULL; + + if (skb_dst(skb)) + neigh = skb_dst(skb)->neighbour; + + if (neigh == NULL) { + if (net_ratelimit()) + printk(KERN_DEBUG ""sit: nexthop == NULL\n""); + goto tx_error; + } + + addr6 = (struct in6_addr*)&neigh->primary_key; + addr_type = ipv6_addr_type(addr6); + + if ((addr_type & IPV6_ADDR_UNICAST) && + ipv6_addr_is_isatap(addr6)) + dst = addr6->s6_addr32[3]; + else + goto tx_error; + } + + if (!dst) + dst = try_6rd(&iph6->daddr, tunnel); + + if (!dst) { + struct neighbour *neigh = NULL; + + if (skb_dst(skb)) + neigh = skb_dst(skb)->neighbour; + + if (neigh == NULL) { + if (net_ratelimit()) + printk(KERN_DEBUG ""sit: nexthop == NULL\n""); + goto tx_error; + } + + addr6 = (struct in6_addr*)&neigh->primary_key; + addr_type = ipv6_addr_type(addr6); + + if (addr_type == IPV6_ADDR_ANY) { + addr6 = &ipv6_hdr(skb)->daddr; + addr_type = ipv6_addr_type(addr6); + } + + if ((addr_type & IPV6_ADDR_COMPATv4) == 0) + goto tx_error_icmp; + + dst = addr6->s6_addr32[3]; + } + + { + struct flowi fl = { .nl_u = { .ip4_u = + { .daddr = dst, + .saddr = tiph->saddr, + .tos = RT_TOS(tos) } }, + .oif = tunnel->parms.link, + .proto = IPPROTO_IPV6 }; + if (ip_route_output_key(dev_net(dev), &rt, &fl)) { + stats->tx_carrier_errors++; + goto tx_error_icmp; + } + } + if (rt->rt_type != RTN_UNICAST) { + ip_rt_put(rt); + stats->tx_carrier_errors++; + goto tx_error_icmp; + } + tdev = rt->u.dst.dev; + + if (tdev == dev) { + ip_rt_put(rt); + stats->collisions++; + goto tx_error; + } + + if (df) { + mtu = dst_mtu(&rt->u.dst) - sizeof(struct iphdr); + + if (mtu < 68) { + stats->collisions++; + ip_rt_put(rt); + goto tx_error; + } + + if (mtu < IPV6_MIN_MTU) { + mtu = IPV6_MIN_MTU; + df = 0; + } + + if (tunnel->parms.iph.daddr && skb_dst(skb)) + skb_dst(skb)->ops->update_pmtu(skb_dst(skb), mtu); + + if (skb->len > mtu) { + icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu, dev); + ip_rt_put(rt); + goto tx_error; + } + } + + if (tunnel->err_count > 0) { + if (time_before(jiffies, + tunnel->err_time + IPTUNNEL_ERR_TIMEO)) { + tunnel->err_count--; + dst_link_failure(skb); + } else + tunnel->err_count = 0; + } + + /* + * Okay, now see if we can stuff it in the buffer as-is. + */ + max_headroom = LL_RESERVED_SPACE(tdev)+sizeof(struct iphdr); + + if (skb_headroom(skb) < max_headroom || skb_shared(skb) || + (skb_cloned(skb) && !skb_clone_writable(skb, 0))) { + struct sk_buff *new_skb = skb_realloc_headroom(skb, max_headroom); + if (!new_skb) { + ip_rt_put(rt); + txq->tx_dropped++; + dev_kfree_skb(skb); + return NETDEV_TX_OK; + } + if (skb->sk) + skb_set_owner_w(new_skb, skb->sk); + dev_kfree_skb(skb); + skb = new_skb; + iph6 = ipv6_hdr(skb); + } + + skb->transport_header = skb->network_header; + skb_push(skb, sizeof(struct iphdr)); + skb_reset_network_header(skb); + memset(&(IPCB(skb)->opt), 0, sizeof(IPCB(skb)->opt)); + IPCB(skb)->flags = 0; + skb_dst_drop(skb); + skb_dst_set(skb, &rt->u.dst); + + /* + * Push down and install the IPIP header. + */ + + iph = ip_hdr(skb); + iph->version = 4; + iph->ihl = sizeof(struct iphdr)>>2; + iph->frag_off = df; + iph->protocol = IPPROTO_IPV6; + iph->tos = INET_ECN_encapsulate(tos, ipv6_get_dsfield(iph6)); + iph->daddr = rt->rt_dst; + iph->saddr = rt->rt_src; + + if ((iph->ttl = tiph->ttl) == 0) + iph->ttl = iph6->hop_limit; + + nf_reset(skb); + + IPTUNNEL_XMIT(); + return NETDEV_TX_OK; + +tx_error_icmp: + dst_link_failure(skb); +tx_error: + stats->tx_errors++; + dev_kfree_skb(skb); + return NETDEV_TX_OK; +} +",0,"static netdev_tx_t ipip6_tunnel_xmit(struct sk_buff *skb, + struct net_device *dev) +{ + struct ip_tunnel *tunnel = netdev_priv(dev); + struct net_device_stats *stats = &dev->stats; + struct netdev_queue *txq = netdev_get_tx_queue(dev, 0); + struct iphdr *tiph = &tunnel->parms.iph; + struct ipv6hdr *iph6 = ipv6_hdr(skb); + u8 tos = tunnel->parms.iph.tos; + __be16 df = tiph->frag_off; + struct rtable *rt; /* Route to the other host */ + struct net_device *tdev; /* Device to other host */ + struct iphdr *iph; /* Our new IP header */ + unsigned int max_headroom; /* The extra header space needed */ + __be32 dst = tiph->daddr; + int mtu; + struct in6_addr *addr6; + int addr_type; + + if (skb->protocol != htons(ETH_P_IPV6)) + goto tx_error; + + /* ISATAP (RFC4214) - must come before 6to4 */ + if (dev->priv_flags & IFF_ISATAP) { + struct neighbour *neigh = NULL; + + if (skb_dst(skb)) + neigh = skb_dst(skb)->neighbour; + + if (neigh == NULL) { + if (net_ratelimit()) + printk(KERN_DEBUG ""sit: nexthop == NULL\n""); + goto tx_error; + } + + addr6 = (struct in6_addr*)&neigh->primary_key; + addr_type = ipv6_addr_type(addr6); + + if ((addr_type & IPV6_ADDR_UNICAST) && + ipv6_addr_is_isatap(addr6)) + dst = addr6->s6_addr32[3]; + else + goto tx_error; + } + + if (!dst) + dst = try_6rd(&iph6->daddr, tunnel); + + if (!dst) { + struct neighbour *neigh = NULL; + + if (skb_dst(skb)) + neigh = skb_dst(skb)->neighbour; + + if (neigh == NULL) { + if (net_ratelimit()) + printk(KERN_DEBUG ""sit: nexthop == NULL\n""); + goto tx_error; + } + + addr6 = (struct in6_addr*)&neigh->primary_key; + addr_type = ipv6_addr_type(addr6); + + if (addr_type == IPV6_ADDR_ANY) { + addr6 = &ipv6_hdr(skb)->daddr; + addr_type = ipv6_addr_type(addr6); + } + + if ((addr_type & IPV6_ADDR_COMPATv4) == 0) + goto tx_error_icmp; + + dst = addr6->s6_addr32[3]; + } + + { + struct flowi fl = { .nl_u = { .ip4_u = + { .daddr = dst, + .saddr = tiph->saddr, + .tos = RT_TOS(tos) } }, + .oif = tunnel->parms.link, + .proto = IPPROTO_IPV6 }; + if (ip_route_output_key(dev_net(dev), &rt, &fl)) { + stats->tx_carrier_errors++; + goto tx_error_icmp; + } + } + if (rt->rt_type != RTN_UNICAST) { + ip_rt_put(rt); + stats->tx_carrier_errors++; + goto tx_error_icmp; + } + tdev = rt->u.dst.dev; + + if (tdev == dev) { + ip_rt_put(rt); + stats->collisions++; + goto tx_error; + } + + if (df) { + mtu = dst_mtu(&rt->u.dst) - sizeof(struct iphdr); + + if (mtu < 68) { + stats->collisions++; + ip_rt_put(rt); + goto tx_error; + } + + if (mtu < IPV6_MIN_MTU) { + mtu = IPV6_MIN_MTU; + df = 0; + } + + if (tunnel->parms.iph.daddr && skb_dst(skb)) + skb_dst(skb)->ops->update_pmtu(skb_dst(skb), mtu); + + if (skb->len > mtu) { + icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu, dev); + ip_rt_put(rt); + goto tx_error; + } + } + + if (tunnel->err_count > 0) { + if (time_before(jiffies, + tunnel->err_time + IPTUNNEL_ERR_TIMEO)) { + tunnel->err_count--; + dst_link_failure(skb); + } else + tunnel->err_count = 0; + } + + /* + * Okay, now see if we can stuff it in the buffer as-is. + */ + max_headroom = LL_RESERVED_SPACE(tdev)+sizeof(struct iphdr); + + if (skb_headroom(skb) < max_headroom || skb_shared(skb) || + (skb_cloned(skb) && !skb_clone_writable(skb, 0))) { + struct sk_buff *new_skb = skb_realloc_headroom(skb, max_headroom); + if (!new_skb) { + ip_rt_put(rt); + txq->tx_dropped++; + dev_kfree_skb(skb); + return NETDEV_TX_OK; + } + if (skb->sk) + skb_set_owner_w(new_skb, skb->sk); + dev_kfree_skb(skb); + skb = new_skb; + iph6 = ipv6_hdr(skb); + } + + skb->transport_header = skb->network_header; + skb_push(skb, sizeof(struct iphdr)); + skb_reset_network_header(skb); + memset(&(IPCB(skb)->opt), 0, sizeof(IPCB(skb)->opt)); + IPCB(skb)->flags = 0; + skb_dst_drop(skb); + skb_dst_set(skb, &rt->u.dst); + + /* + * Push down and install the IPIP header. + */ + + iph = ip_hdr(skb); + iph->version = 4; + iph->ihl = sizeof(struct iphdr)>>2; + iph->frag_off = df; + iph->protocol = IPPROTO_IPV6; + iph->tos = INET_ECN_encapsulate(tos, ipv6_get_dsfield(iph6)); + iph->daddr = rt->rt_dst; + iph->saddr = rt->rt_src; + + if ((iph->ttl = tiph->ttl) == 0) + iph->ttl = iph6->hop_limit; + + nf_reset(skb); + + IPTUNNEL_XMIT(); + return NETDEV_TX_OK; + +tx_error_icmp: + dst_link_failure(skb); +tx_error: + stats->tx_errors++; + dev_kfree_skb(skb); + return NETDEV_TX_OK; +} +","@@ -1227,15 +1227,14 @@ static int __init sit_init(void) + + printk(KERN_INFO ""IPv6 over IPv4 tunneling driver\n""); + +- if (xfrm4_tunnel_register(&sit_handler, AF_INET6) < 0) { +- printk(KERN_INFO ""sit init: Can't add protocol\n""); +- return -EAGAIN; +- } +- + err = register_pernet_device(&sit_net_ops); + if (err < 0) +- xfrm4_tunnel_deregister(&sit_handler, AF_INET6); +- ++ return err; ++ err = xfrm4_tunnel_register(&sit_handler, AF_INET6); ++ if (err < 0) { ++ unregister_pernet_device(&sit_net_ops); ++ printk(KERN_INFO ""sit init: Can't add protocol\n""); ++ } + return err; + } + ",1477,1808,2048 +6306,"static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason, + u32 exit_intr_info, + unsigned long exit_qualification) +{ + struct vcpu_vmx *vmx = to_vmx(vcpu); + struct vmcs12 *vmcs12 = get_vmcs12(vcpu); + u32 vm_inst_error = 0; + + /* trying to cancel vmlaunch/vmresume is a bug */ + WARN_ON_ONCE(vmx->nested.nested_run_pending); + + leave_guest_mode(vcpu); + prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info, + exit_qualification); + + if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr, + vmcs12->vm_exit_msr_store_count)) + nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL); + + if (unlikely(vmx->fail)) + vm_inst_error = vmcs_read32(VM_INSTRUCTION_ERROR); + + vmx_switch_vmcs(vcpu, &vmx->vmcs01); + + /* + * TODO: SDM says that with acknowledge interrupt on exit, bit 31 of + * the VM-exit interrupt information (valid interrupt) is always set to + * 1 on EXIT_REASON_EXTERNAL_INTERRUPT, so we shouldn't need + * kvm_cpu_has_interrupt(). See the commit message for details. + */ + if (nested_exit_intr_ack_set(vcpu) && + exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT && + kvm_cpu_has_interrupt(vcpu)) { + int irq = kvm_cpu_get_interrupt(vcpu); + WARN_ON(irq < 0); + vmcs12->vm_exit_intr_info = irq | + INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR; + } + + trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason, + vmcs12->exit_qualification, + vmcs12->idt_vectoring_info_field, + vmcs12->vm_exit_intr_info, + vmcs12->vm_exit_intr_error_code, + KVM_ISA_VMX); + + vm_entry_controls_reset_shadow(vmx); + vm_exit_controls_reset_shadow(vmx); + vmx_segment_cache_clear(vmx); + + /* if no vmcs02 cache requested, remove the one we used */ + if (VMCS02_POOL_SIZE == 0) + nested_free_vmcs02(vmx, vmx->nested.current_vmptr); + + load_vmcs12_host_state(vcpu, vmcs12); + + /* Update any VMCS fields that might have changed while L2 ran */ + vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.nr); + vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.nr); + vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset); + if (vmx->hv_deadline_tsc == -1) + vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL, + PIN_BASED_VMX_PREEMPTION_TIMER); + else + vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL, + PIN_BASED_VMX_PREEMPTION_TIMER); + if (kvm_has_tsc_control) + decache_tsc_multiplier(vmx); + + if (vmx->nested.change_vmcs01_virtual_x2apic_mode) { + vmx->nested.change_vmcs01_virtual_x2apic_mode = false; + vmx_set_virtual_x2apic_mode(vcpu, + vcpu->arch.apic_base & X2APIC_ENABLE); + } else if (!nested_cpu_has_ept(vmcs12) && + nested_cpu_has2(vmcs12, + SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) { + vmx_flush_tlb_ept_only(vcpu); + } + + /* This is needed for same reason as it was needed in prepare_vmcs02 */ + vmx->host_rsp = 0; + + /* Unpin physical memory we referred to in vmcs02 */ + if (vmx->nested.apic_access_page) { + kvm_release_page_dirty(vmx->nested.apic_access_page); + vmx->nested.apic_access_page = NULL; + } + if (vmx->nested.virtual_apic_page) { + kvm_release_page_dirty(vmx->nested.virtual_apic_page); + vmx->nested.virtual_apic_page = NULL; + } + if (vmx->nested.pi_desc_page) { + kunmap(vmx->nested.pi_desc_page); + kvm_release_page_dirty(vmx->nested.pi_desc_page); + vmx->nested.pi_desc_page = NULL; + vmx->nested.pi_desc = NULL; + } + + /* + * We are now running in L2, mmu_notifier will force to reload the + * page's hpa for L2 vmcs. Need to reload it for L1 before entering L1. + */ + kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu); + + /* + * Exiting from L2 to L1, we're now back to L1 which thinks it just + * finished a VMLAUNCH or VMRESUME instruction, so we need to set the + * success or failure flag accordingly. + */ + if (unlikely(vmx->fail)) { + vmx->fail = 0; + nested_vmx_failValid(vcpu, vm_inst_error); + } else + nested_vmx_succeed(vcpu); + if (enable_shadow_vmcs) + vmx->nested.sync_shadow_vmcs = true; + + /* in case we halted in L2 */ + vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE; +} +",0,"static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason, + u32 exit_intr_info, + unsigned long exit_qualification) +{ + struct vcpu_vmx *vmx = to_vmx(vcpu); + struct vmcs12 *vmcs12 = get_vmcs12(vcpu); + u32 vm_inst_error = 0; + + /* trying to cancel vmlaunch/vmresume is a bug */ + WARN_ON_ONCE(vmx->nested.nested_run_pending); + + leave_guest_mode(vcpu); + prepare_vmcs12(vcpu, vmcs12, exit_reason, exit_intr_info, + exit_qualification); + + if (nested_vmx_store_msr(vcpu, vmcs12->vm_exit_msr_store_addr, + vmcs12->vm_exit_msr_store_count)) + nested_vmx_abort(vcpu, VMX_ABORT_SAVE_GUEST_MSR_FAIL); + + if (unlikely(vmx->fail)) + vm_inst_error = vmcs_read32(VM_INSTRUCTION_ERROR); + + vmx_switch_vmcs(vcpu, &vmx->vmcs01); + + /* + * TODO: SDM says that with acknowledge interrupt on exit, bit 31 of + * the VM-exit interrupt information (valid interrupt) is always set to + * 1 on EXIT_REASON_EXTERNAL_INTERRUPT, so we shouldn't need + * kvm_cpu_has_interrupt(). See the commit message for details. + */ + if (nested_exit_intr_ack_set(vcpu) && + exit_reason == EXIT_REASON_EXTERNAL_INTERRUPT && + kvm_cpu_has_interrupt(vcpu)) { + int irq = kvm_cpu_get_interrupt(vcpu); + WARN_ON(irq < 0); + vmcs12->vm_exit_intr_info = irq | + INTR_INFO_VALID_MASK | INTR_TYPE_EXT_INTR; + } + + trace_kvm_nested_vmexit_inject(vmcs12->vm_exit_reason, + vmcs12->exit_qualification, + vmcs12->idt_vectoring_info_field, + vmcs12->vm_exit_intr_info, + vmcs12->vm_exit_intr_error_code, + KVM_ISA_VMX); + + vm_entry_controls_reset_shadow(vmx); + vm_exit_controls_reset_shadow(vmx); + vmx_segment_cache_clear(vmx); + + /* if no vmcs02 cache requested, remove the one we used */ + if (VMCS02_POOL_SIZE == 0) + nested_free_vmcs02(vmx, vmx->nested.current_vmptr); + + load_vmcs12_host_state(vcpu, vmcs12); + + /* Update any VMCS fields that might have changed while L2 ran */ + vmcs_write32(VM_EXIT_MSR_LOAD_COUNT, vmx->msr_autoload.nr); + vmcs_write32(VM_ENTRY_MSR_LOAD_COUNT, vmx->msr_autoload.nr); + vmcs_write64(TSC_OFFSET, vcpu->arch.tsc_offset); + if (vmx->hv_deadline_tsc == -1) + vmcs_clear_bits(PIN_BASED_VM_EXEC_CONTROL, + PIN_BASED_VMX_PREEMPTION_TIMER); + else + vmcs_set_bits(PIN_BASED_VM_EXEC_CONTROL, + PIN_BASED_VMX_PREEMPTION_TIMER); + if (kvm_has_tsc_control) + decache_tsc_multiplier(vmx); + + if (vmx->nested.change_vmcs01_virtual_x2apic_mode) { + vmx->nested.change_vmcs01_virtual_x2apic_mode = false; + vmx_set_virtual_x2apic_mode(vcpu, + vcpu->arch.apic_base & X2APIC_ENABLE); + } else if (!nested_cpu_has_ept(vmcs12) && + nested_cpu_has2(vmcs12, + SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES)) { + vmx_flush_tlb_ept_only(vcpu); + } + + /* This is needed for same reason as it was needed in prepare_vmcs02 */ + vmx->host_rsp = 0; + + /* Unpin physical memory we referred to in vmcs02 */ + if (vmx->nested.apic_access_page) { + kvm_release_page_dirty(vmx->nested.apic_access_page); + vmx->nested.apic_access_page = NULL; + } + if (vmx->nested.virtual_apic_page) { + kvm_release_page_dirty(vmx->nested.virtual_apic_page); + vmx->nested.virtual_apic_page = NULL; + } + if (vmx->nested.pi_desc_page) { + kunmap(vmx->nested.pi_desc_page); + kvm_release_page_dirty(vmx->nested.pi_desc_page); + vmx->nested.pi_desc_page = NULL; + vmx->nested.pi_desc = NULL; + } + + /* + * We are now running in L2, mmu_notifier will force to reload the + * page's hpa for L2 vmcs. Need to reload it for L1 before entering L1. + */ + kvm_make_request(KVM_REQ_APIC_PAGE_RELOAD, vcpu); + + /* + * Exiting from L2 to L1, we're now back to L1 which thinks it just + * finished a VMLAUNCH or VMRESUME instruction, so we need to set the + * success or failure flag accordingly. + */ + if (unlikely(vmx->fail)) { + vmx->fail = 0; + nested_vmx_failValid(vcpu, vm_inst_error); + } else + nested_vmx_succeed(vcpu); + if (enable_shadow_vmcs) + vmx->nested.sync_shadow_vmcs = true; + + /* in case we halted in L2 */ + vcpu->arch.mp_state = KVM_MP_STATE_RUNNABLE; +} +","@@ -10525,6 +10525,11 @@ static int prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12, + if (exec_control & CPU_BASED_TPR_SHADOW) { + vmcs_write64(VIRTUAL_APIC_PAGE_ADDR, -1ull); + vmcs_write32(TPR_THRESHOLD, vmcs12->tpr_threshold); ++ } else { ++#ifdef CONFIG_X86_64 ++ exec_control |= CPU_BASED_CR8_LOAD_EXITING | ++ CPU_BASED_CR8_STORE_EXITING; ++#endif + } + + /*",1222,1553,2048 +3280,"static int ext4_symlink(struct inode *dir, + struct dentry *dentry, const char *symname) +{ + handle_t *handle; + struct inode *inode; + int l, err, retries = 0; + int credits; + + l = strlen(symname)+1; + if (l > dir->i_sb->s_blocksize) + return -ENAMETOOLONG; + + dquot_initialize(dir); + + if (l > EXT4_N_BLOCKS * 4) { + /* + * For non-fast symlinks, we just allocate inode and put it on + * orphan list in the first transaction => we need bitmap, + * group descriptor, sb, inode block, quota blocks, and + * possibly selinux xattr blocks. + */ + credits = 4 + EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) + + EXT4_XATTR_TRANS_BLOCKS; + } else { + /* + * Fast symlink. We have to add entry to directory + * (EXT4_DATA_TRANS_BLOCKS + EXT4_INDEX_EXTRA_TRANS_BLOCKS), + * allocate new inode (bitmap, group descriptor, inode block, + * quota blocks, sb is already counted in previous macros). + */ + credits = EXT4_DATA_TRANS_BLOCKS(dir->i_sb) + + EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3 + + EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb); + } +retry: + handle = ext4_journal_start(dir, credits); + if (IS_ERR(handle)) + return PTR_ERR(handle); + + if (IS_DIRSYNC(dir)) + ext4_handle_sync(handle); + + inode = ext4_new_inode(handle, dir, S_IFLNK|S_IRWXUGO, + &dentry->d_name, 0, NULL); + err = PTR_ERR(inode); + if (IS_ERR(inode)) + goto out_stop; + + if (l > EXT4_N_BLOCKS * 4) { + inode->i_op = &ext4_symlink_inode_operations; + ext4_set_aops(inode); + /* + * We cannot call page_symlink() with transaction started + * because it calls into ext4_write_begin() which can wait + * for transaction commit if we are running out of space + * and thus we deadlock. So we have to stop transaction now + * and restart it when symlink contents is written. + * + * To keep fs consistent in case of crash, we have to put inode + * to orphan list in the mean time. + */ + drop_nlink(inode); + err = ext4_orphan_add(handle, inode); + ext4_journal_stop(handle); + if (err) + goto err_drop_inode; + err = __page_symlink(inode, symname, l, 1); + if (err) + goto err_drop_inode; + /* + * Now inode is being linked into dir (EXT4_DATA_TRANS_BLOCKS + * + EXT4_INDEX_EXTRA_TRANS_BLOCKS), inode is also modified + */ + handle = ext4_journal_start(dir, + EXT4_DATA_TRANS_BLOCKS(dir->i_sb) + + EXT4_INDEX_EXTRA_TRANS_BLOCKS + 1); + if (IS_ERR(handle)) { + err = PTR_ERR(handle); + goto err_drop_inode; + } + set_nlink(inode, 1); + err = ext4_orphan_del(handle, inode); + if (err) { + ext4_journal_stop(handle); + clear_nlink(inode); + goto err_drop_inode; + } + } else { + /* clear the extent format for fast symlink */ + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + inode->i_op = &ext4_fast_symlink_inode_operations; + memcpy((char *)&EXT4_I(inode)->i_data, symname, l); + inode->i_size = l-1; + } + EXT4_I(inode)->i_disksize = inode->i_size; + err = ext4_add_nondir(handle, dentry, inode); +out_stop: + ext4_journal_stop(handle); + if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries)) + goto retry; + return err; +err_drop_inode: + unlock_new_inode(inode); + iput(inode); + return err; +} +",0,"static int ext4_symlink(struct inode *dir, + struct dentry *dentry, const char *symname) +{ + handle_t *handle; + struct inode *inode; + int l, err, retries = 0; + int credits; + + l = strlen(symname)+1; + if (l > dir->i_sb->s_blocksize) + return -ENAMETOOLONG; + + dquot_initialize(dir); + + if (l > EXT4_N_BLOCKS * 4) { + /* + * For non-fast symlinks, we just allocate inode and put it on + * orphan list in the first transaction => we need bitmap, + * group descriptor, sb, inode block, quota blocks, and + * possibly selinux xattr blocks. + */ + credits = 4 + EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) + + EXT4_XATTR_TRANS_BLOCKS; + } else { + /* + * Fast symlink. We have to add entry to directory + * (EXT4_DATA_TRANS_BLOCKS + EXT4_INDEX_EXTRA_TRANS_BLOCKS), + * allocate new inode (bitmap, group descriptor, inode block, + * quota blocks, sb is already counted in previous macros). + */ + credits = EXT4_DATA_TRANS_BLOCKS(dir->i_sb) + + EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3 + + EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb); + } +retry: + handle = ext4_journal_start(dir, credits); + if (IS_ERR(handle)) + return PTR_ERR(handle); + + if (IS_DIRSYNC(dir)) + ext4_handle_sync(handle); + + inode = ext4_new_inode(handle, dir, S_IFLNK|S_IRWXUGO, + &dentry->d_name, 0, NULL); + err = PTR_ERR(inode); + if (IS_ERR(inode)) + goto out_stop; + + if (l > EXT4_N_BLOCKS * 4) { + inode->i_op = &ext4_symlink_inode_operations; + ext4_set_aops(inode); + /* + * We cannot call page_symlink() with transaction started + * because it calls into ext4_write_begin() which can wait + * for transaction commit if we are running out of space + * and thus we deadlock. So we have to stop transaction now + * and restart it when symlink contents is written. + * + * To keep fs consistent in case of crash, we have to put inode + * to orphan list in the mean time. + */ + drop_nlink(inode); + err = ext4_orphan_add(handle, inode); + ext4_journal_stop(handle); + if (err) + goto err_drop_inode; + err = __page_symlink(inode, symname, l, 1); + if (err) + goto err_drop_inode; + /* + * Now inode is being linked into dir (EXT4_DATA_TRANS_BLOCKS + * + EXT4_INDEX_EXTRA_TRANS_BLOCKS), inode is also modified + */ + handle = ext4_journal_start(dir, + EXT4_DATA_TRANS_BLOCKS(dir->i_sb) + + EXT4_INDEX_EXTRA_TRANS_BLOCKS + 1); + if (IS_ERR(handle)) { + err = PTR_ERR(handle); + goto err_drop_inode; + } + set_nlink(inode, 1); + err = ext4_orphan_del(handle, inode); + if (err) { + ext4_journal_stop(handle); + clear_nlink(inode); + goto err_drop_inode; + } + } else { + /* clear the extent format for fast symlink */ + ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); + inode->i_op = &ext4_fast_symlink_inode_operations; + memcpy((char *)&EXT4_I(inode)->i_data, symname, l); + inode->i_size = l-1; + } + EXT4_I(inode)->i_disksize = inode->i_size; + err = ext4_add_nondir(handle, dentry, inode); +out_stop: + ext4_journal_stop(handle); + if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries)) + goto retry; + return err; +err_drop_inode: + unlock_new_inode(inode); + iput(inode); + return err; +} +","@@ -2648,7 +2648,8 @@ int ext4_orphan_del(handle_t *handle, struct inode *inode) + struct ext4_iloc iloc; + int err = 0; + +- if (!EXT4_SB(inode->i_sb)->s_journal) ++ if ((!EXT4_SB(inode->i_sb)->s_journal) && ++ !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) + return 0; + + mutex_lock(&EXT4_SB(inode->i_sb)->s_orphan_lock);",894,1225,2048 +16452,"ExtensionFunction::ResponseAction WindowsCreateFunction::Run() { + std::unique_ptr params( + windows::Create::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params); + std::vector urls; + TabStripModel* source_tab_strip = NULL; + int tab_index = -1; + + windows::Create::Params::CreateData* create_data = params->create_data.get(); + + if (create_data && create_data->url) { + std::vector url_strings; + if (create_data->url->as_string) + url_strings.push_back(*create_data->url->as_string); + else if (create_data->url->as_strings) + url_strings.swap(*create_data->url->as_strings); + + for (auto i = url_strings.begin(); i != url_strings.end(); ++i) { + GURL url = ExtensionTabUtil::ResolvePossiblyRelativeURL(*i, extension()); + if (!url.is_valid()) + return RespondNow(Error(tabs_constants::kInvalidUrlError, *i)); + if (ExtensionTabUtil::IsKillURL(url)) + return RespondNow(Error(tabs_constants::kNoCrashBrowserError)); + urls.push_back(url); + } + } + + std::string error; + bool open_incognito_window = + ShouldOpenIncognitoWindow(create_data, &urls, &error); + if (!error.empty()) + return RespondNow(Error(error)); + + Profile* calling_profile = Profile::FromBrowserContext(browser_context()); + Profile* window_profile = open_incognito_window + ? calling_profile->GetOffTheRecordProfile() + : calling_profile; + + if (create_data && create_data->tab_id) { + Browser* source_browser = nullptr; + if (!GetTabById(*create_data->tab_id, calling_profile, + include_incognito_information(), &source_browser, + &source_tab_strip, nullptr, &tab_index, &error)) { + return RespondNow(Error(error)); + } + + if (!source_browser->window()->IsTabStripEditable()) + return RespondNow(Error(tabs_constants::kTabStripNotEditableError)); + + if (source_browser->profile() != window_profile) + return RespondNow( + Error(tabs_constants::kCanOnlyMoveTabsWithinSameProfileError)); + } + + if (!IsValidStateForWindowsCreateFunction(create_data)) + return RespondNow(Error(tabs_constants::kInvalidWindowStateError)); + + Browser::Type window_type = Browser::TYPE_TABBED; + + gfx::Rect window_bounds; + bool focused = true; + std::string extension_id; + + if (create_data) { + ReportRequestedWindowState(create_data->state); + + switch (create_data->type) { + case windows::CREATE_TYPE_PANEL: + case windows::CREATE_TYPE_POPUP: + window_type = Browser::TYPE_POPUP; + extension_id = extension()->id(); + break; + case windows::CREATE_TYPE_NONE: + case windows::CREATE_TYPE_NORMAL: + break; + default: + return RespondNow(Error(tabs_constants::kInvalidWindowTypeError)); + } + + if (window_type == Browser::TYPE_TABBED || + window_type == Browser::TYPE_POPUP) { + ui::WindowShowState ignored_show_state = ui::SHOW_STATE_DEFAULT; + WindowSizer::GetBrowserWindowBoundsAndShowState( + std::string(), gfx::Rect(), nullptr, &window_bounds, + &ignored_show_state); + } + + if (create_data->left) + window_bounds.set_x(*create_data->left); + + if (create_data->top) + window_bounds.set_y(*create_data->top); + + if (create_data->width) + window_bounds.set_width(*create_data->width); + + if (create_data->height) + window_bounds.set_height(*create_data->height); + + if (create_data->focused) + focused = *create_data->focused; + } + + Browser::CreateParams create_params(window_type, window_profile, + user_gesture()); + if (extension_id.empty()) { + create_params.initial_bounds = window_bounds; + } else { + create_params = Browser::CreateParams::CreateForApp( + web_app::GenerateApplicationNameFromAppId(extension_id), + false /* trusted_source */, window_bounds, window_profile, + user_gesture()); + } + create_params.initial_show_state = ui::SHOW_STATE_NORMAL; + if (create_data && create_data->state) { + if (create_data->state == windows::WINDOW_STATE_LOCKED_FULLSCREEN && + !ExtensionHasLockedFullscreenPermission(extension())) { + return RespondNow( + Error(tabs_constants::kMissingLockWindowFullscreenPrivatePermission)); + } + create_params.initial_show_state = + ConvertToWindowShowState(create_data->state); + } + + Browser* new_window = new Browser(create_params); + + for (const GURL& url : urls) { + NavigateParams navigate_params(new_window, url, ui::PAGE_TRANSITION_LINK); + navigate_params.disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB; + + bool set_self_as_opener = create_data->set_self_as_opener && // present? + *create_data->set_self_as_opener; // set to true? + navigate_params.opener = set_self_as_opener ? render_frame_host() : nullptr; + navigate_params.source_site_instance = + render_frame_host()->GetSiteInstance(); + + Navigate(&navigate_params); + } + + WebContents* contents = NULL; + if ((window_type == Browser::TYPE_POPUP && urls.empty()) || + window_type == Browser::TYPE_TABBED) { + if (source_tab_strip) { + std::unique_ptr detached_tab = + source_tab_strip->DetachWebContentsAt(tab_index); + contents = detached_tab.get(); + TabStripModel* target_tab_strip = new_window->tab_strip_model(); + target_tab_strip->InsertWebContentsAt( + urls.size(), std::move(detached_tab), TabStripModel::ADD_NONE); + } + } + if (!contents && urls.empty() && window_type != Browser::TYPE_POPUP) { + chrome::NewTab(new_window); + } + chrome::SelectNumberedTab(new_window, 0); + + if (focused) + new_window->window()->Show(); + else + new_window->window()->ShowInactive(); + +#if defined(OS_CHROMEOS) + if (create_data && + create_data->state == windows::WINDOW_STATE_LOCKED_FULLSCREEN) { + SetLockedFullscreenState(new_window, true); + } +#endif + + std::unique_ptr result; + if (new_window->profile()->IsOffTheRecord() && + !browser_context()->IsOffTheRecord() && + !include_incognito_information()) { + result = std::make_unique(); + } else { + result = ExtensionTabUtil::CreateWindowValueForExtension( + *new_window, extension(), ExtensionTabUtil::kPopulateTabs); + } + + return RespondNow(OneArgument(std::move(result))); +} +",0,"ExtensionFunction::ResponseAction WindowsCreateFunction::Run() { + std::unique_ptr params( + windows::Create::Params::Create(*args_)); + EXTENSION_FUNCTION_VALIDATE(params); + std::vector urls; + TabStripModel* source_tab_strip = NULL; + int tab_index = -1; + + windows::Create::Params::CreateData* create_data = params->create_data.get(); + + if (create_data && create_data->url) { + std::vector url_strings; + if (create_data->url->as_string) + url_strings.push_back(*create_data->url->as_string); + else if (create_data->url->as_strings) + url_strings.swap(*create_data->url->as_strings); + + for (auto i = url_strings.begin(); i != url_strings.end(); ++i) { + GURL url = ExtensionTabUtil::ResolvePossiblyRelativeURL(*i, extension()); + if (!url.is_valid()) + return RespondNow(Error(tabs_constants::kInvalidUrlError, *i)); + if (ExtensionTabUtil::IsKillURL(url)) + return RespondNow(Error(tabs_constants::kNoCrashBrowserError)); + urls.push_back(url); + } + } + + std::string error; + bool open_incognito_window = + ShouldOpenIncognitoWindow(create_data, &urls, &error); + if (!error.empty()) + return RespondNow(Error(error)); + + Profile* calling_profile = Profile::FromBrowserContext(browser_context()); + Profile* window_profile = open_incognito_window + ? calling_profile->GetOffTheRecordProfile() + : calling_profile; + + if (create_data && create_data->tab_id) { + Browser* source_browser = nullptr; + if (!GetTabById(*create_data->tab_id, calling_profile, + include_incognito_information(), &source_browser, + &source_tab_strip, nullptr, &tab_index, &error)) { + return RespondNow(Error(error)); + } + + if (!source_browser->window()->IsTabStripEditable()) + return RespondNow(Error(tabs_constants::kTabStripNotEditableError)); + + if (source_browser->profile() != window_profile) + return RespondNow( + Error(tabs_constants::kCanOnlyMoveTabsWithinSameProfileError)); + } + + if (!IsValidStateForWindowsCreateFunction(create_data)) + return RespondNow(Error(tabs_constants::kInvalidWindowStateError)); + + Browser::Type window_type = Browser::TYPE_TABBED; + + gfx::Rect window_bounds; + bool focused = true; + std::string extension_id; + + if (create_data) { + ReportRequestedWindowState(create_data->state); + + switch (create_data->type) { + case windows::CREATE_TYPE_PANEL: + case windows::CREATE_TYPE_POPUP: + window_type = Browser::TYPE_POPUP; + extension_id = extension()->id(); + break; + case windows::CREATE_TYPE_NONE: + case windows::CREATE_TYPE_NORMAL: + break; + default: + return RespondNow(Error(tabs_constants::kInvalidWindowTypeError)); + } + + if (window_type == Browser::TYPE_TABBED || + window_type == Browser::TYPE_POPUP) { + ui::WindowShowState ignored_show_state = ui::SHOW_STATE_DEFAULT; + WindowSizer::GetBrowserWindowBoundsAndShowState( + std::string(), gfx::Rect(), nullptr, &window_bounds, + &ignored_show_state); + } + + if (create_data->left) + window_bounds.set_x(*create_data->left); + + if (create_data->top) + window_bounds.set_y(*create_data->top); + + if (create_data->width) + window_bounds.set_width(*create_data->width); + + if (create_data->height) + window_bounds.set_height(*create_data->height); + + if (create_data->focused) + focused = *create_data->focused; + } + + Browser::CreateParams create_params(window_type, window_profile, + user_gesture()); + if (extension_id.empty()) { + create_params.initial_bounds = window_bounds; + } else { + create_params = Browser::CreateParams::CreateForApp( + web_app::GenerateApplicationNameFromAppId(extension_id), + false /* trusted_source */, window_bounds, window_profile, + user_gesture()); + } + create_params.initial_show_state = ui::SHOW_STATE_NORMAL; + if (create_data && create_data->state) { + if (create_data->state == windows::WINDOW_STATE_LOCKED_FULLSCREEN && + !ExtensionHasLockedFullscreenPermission(extension())) { + return RespondNow( + Error(tabs_constants::kMissingLockWindowFullscreenPrivatePermission)); + } + create_params.initial_show_state = + ConvertToWindowShowState(create_data->state); + } + + Browser* new_window = new Browser(create_params); + + for (const GURL& url : urls) { + NavigateParams navigate_params(new_window, url, ui::PAGE_TRANSITION_LINK); + navigate_params.disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB; + + bool set_self_as_opener = create_data->set_self_as_opener && // present? + *create_data->set_self_as_opener; // set to true? + navigate_params.opener = set_self_as_opener ? render_frame_host() : nullptr; + navigate_params.source_site_instance = + render_frame_host()->GetSiteInstance(); + + Navigate(&navigate_params); + } + + WebContents* contents = NULL; + if ((window_type == Browser::TYPE_POPUP && urls.empty()) || + window_type == Browser::TYPE_TABBED) { + if (source_tab_strip) { + std::unique_ptr detached_tab = + source_tab_strip->DetachWebContentsAt(tab_index); + contents = detached_tab.get(); + TabStripModel* target_tab_strip = new_window->tab_strip_model(); + target_tab_strip->InsertWebContentsAt( + urls.size(), std::move(detached_tab), TabStripModel::ADD_NONE); + } + } + if (!contents && urls.empty() && window_type != Browser::TYPE_POPUP) { + chrome::NewTab(new_window); + } + chrome::SelectNumberedTab(new_window, 0); + + if (focused) + new_window->window()->Show(); + else + new_window->window()->ShowInactive(); + +#if defined(OS_CHROMEOS) + if (create_data && + create_data->state == windows::WINDOW_STATE_LOCKED_FULLSCREEN) { + SetLockedFullscreenState(new_window, true); + } +#endif + + std::unique_ptr result; + if (new_window->profile()->IsOffTheRecord() && + !browser_context()->IsOffTheRecord() && + !include_incognito_information()) { + result = std::make_unique(); + } else { + result = ExtensionTabUtil::CreateWindowValueForExtension( + *new_window, extension(), ExtensionTabUtil::kPopulateTabs); + } + + return RespondNow(OneArgument(std::move(result))); +} +","@@ -1712,7 +1712,8 @@ WebContents* TabsCaptureVisibleTabFunction::GetWebContentsForID( + + if (!extension()->permissions_data()->CanCaptureVisiblePage( + contents->GetLastCommittedURL(), +- SessionTabHelper::IdForTab(contents).id(), error)) { ++ SessionTabHelper::IdForTab(contents).id(), error, ++ extensions::CaptureRequirement::kActiveTabOrAllUrls)) { + return nullptr; + } + return contents;",1461,1792,2048 +18022,"static int _gd2GetHeader(gdIOCtxPtr in, int *sx, int *sy, int *cs, int *vers, int *fmt, int *ncx, int *ncy, t_chunk_info ** chunkIdx) +{ + int i; + int ch; + char id[5]; + t_chunk_info *cidx; + int sidx; + int nc; + + GD2_DBG(php_gd_error(""Reading gd2 header info"")); + + for (i = 0; i < 4; i++) { + ch = gdGetC(in); + if (ch == EOF) { + goto fail1; + } + id[i] = ch; + } + id[4] = 0; + + GD2_DBG(php_gd_error(""Got file code: %s"", id)); + + /* Equiv. of 'magick'. */ + if (strcmp(id, GD2_ID) != 0) { + GD2_DBG(php_gd_error(""Not a valid gd2 file"")); + goto fail1; + } + + /* Version */ + if (gdGetWord(vers, in) != 1) { + goto fail1; + } + GD2_DBG(php_gd_error(""Version: %d"", *vers)); + + if ((*vers != 1) && (*vers != 2)) { + GD2_DBG(php_gd_error(""Bad version: %d"", *vers)); + goto fail1; + } + + /* Image Size */ + if (!gdGetWord(sx, in)) { + GD2_DBG(php_gd_error(""Could not get x-size"")); + goto fail1; + } + if (!gdGetWord(sy, in)) { + GD2_DBG(php_gd_error(""Could not get y-size"")); + goto fail1; + } + GD2_DBG(php_gd_error(""Image is %dx%d"", *sx, *sy)); + + /* Chunk Size (pixels, not bytes!) */ + if (gdGetWord(cs, in) != 1) { + goto fail1; + } + GD2_DBG(php_gd_error(""ChunkSize: %d"", *cs)); + + if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) { + GD2_DBG(php_gd_error(""Bad chunk size: %d"", *cs)); + goto fail1; + } + + /* Data Format */ + if (gdGetWord(fmt, in) != 1) { + goto fail1; + } + GD2_DBG(php_gd_error(""Format: %d"", *fmt)); + + if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) && (*fmt != GD2_FMT_TRUECOLOR_RAW) && (*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) { + GD2_DBG(php_gd_error(""Bad data format: %d"", *fmt)); + goto fail1; + } + + /* # of chunks wide */ + if (gdGetWord(ncx, in) != 1) { + goto fail1; + } + GD2_DBG(php_gd_error(""%d Chunks Wide"", *ncx)); + + /* # of chunks high */ + if (gdGetWord(ncy, in) != 1) { + goto fail1; + } + GD2_DBG(php_gd_error(""%d Chunks vertically"", *ncy)); + + if (gd2_compressed(*fmt)) { + nc = (*ncx) * (*ncy); + GD2_DBG(php_gd_error(""Reading %d chunk index entries"", nc)); + sidx = sizeof(t_chunk_info) * nc; + if (sidx <= 0) { + goto fail1; + } + cidx = gdCalloc(sidx, 1); + for (i = 0; i < nc; i++) { + if (gdGetInt(&cidx[i].offset, in) != 1) { + gdFree(cidx); + goto fail1; + } + if (gdGetInt(&cidx[i].size, in) != 1) { + gdFree(cidx); + goto fail1; + } + if (cidx[i].offset < 0 || cidx[i].size < 0) { + gdFree(cidx); + goto fail1; + } + } + *chunkIdx = cidx; + } + + GD2_DBG(php_gd_error(""gd2 header complete"")); + + return 1; + +fail1: + return 0; +} +",1,"static int _gd2GetHeader(gdIOCtxPtr in, int *sx, int *sy, int *cs, int *vers, int *fmt, int *ncx, int *ncy, t_chunk_info ** chunkIdx) +{ + int i; + int ch; + char id[5]; + t_chunk_info *cidx; + int sidx; + int nc; + + GD2_DBG(php_gd_error(""Reading gd2 header info"")); + + for (i = 0; i < 4; i++) { + ch = gdGetC(in); + if (ch == EOF) { + goto fail1; + } + id[i] = ch; + } + id[4] = 0; + + GD2_DBG(php_gd_error(""Got file code: %s"", id)); + + /* Equiv. of 'magick'. */ + if (strcmp(id, GD2_ID) != 0) { + GD2_DBG(php_gd_error(""Not a valid gd2 file"")); + goto fail1; + } + + /* Version */ + if (gdGetWord(vers, in) != 1) { + goto fail1; + } + GD2_DBG(php_gd_error(""Version: %d"", *vers)); + + if ((*vers != 1) && (*vers != 2)) { + GD2_DBG(php_gd_error(""Bad version: %d"", *vers)); + goto fail1; + } + + /* Image Size */ + if (!gdGetWord(sx, in)) { + GD2_DBG(php_gd_error(""Could not get x-size"")); + goto fail1; + } + if (!gdGetWord(sy, in)) { + GD2_DBG(php_gd_error(""Could not get y-size"")); + goto fail1; + } + GD2_DBG(php_gd_error(""Image is %dx%d"", *sx, *sy)); + + /* Chunk Size (pixels, not bytes!) */ + if (gdGetWord(cs, in) != 1) { + goto fail1; + } + GD2_DBG(php_gd_error(""ChunkSize: %d"", *cs)); + + if ((*cs < GD2_CHUNKSIZE_MIN) || (*cs > GD2_CHUNKSIZE_MAX)) { + GD2_DBG(php_gd_error(""Bad chunk size: %d"", *cs)); + goto fail1; + } + + /* Data Format */ + if (gdGetWord(fmt, in) != 1) { + goto fail1; + } + GD2_DBG(php_gd_error(""Format: %d"", *fmt)); + + if ((*fmt != GD2_FMT_RAW) && (*fmt != GD2_FMT_COMPRESSED) && (*fmt != GD2_FMT_TRUECOLOR_RAW) && (*fmt != GD2_FMT_TRUECOLOR_COMPRESSED)) { + GD2_DBG(php_gd_error(""Bad data format: %d"", *fmt)); + goto fail1; + } + + /* # of chunks wide */ + if (gdGetWord(ncx, in) != 1) { + goto fail1; + } + GD2_DBG(php_gd_error(""%d Chunks Wide"", *ncx)); + + /* # of chunks high */ + if (gdGetWord(ncy, in) != 1) { + goto fail1; + } + GD2_DBG(php_gd_error(""%d Chunks vertically"", *ncy)); + + if (gd2_compressed(*fmt)) { + nc = (*ncx) * (*ncy); + GD2_DBG(php_gd_error(""Reading %d chunk index entries"", nc)); + if (overflow2(sidx, nc)) { + goto fail1; + } + sidx = sizeof(t_chunk_info) * nc; + if (sidx <= 0) { + goto fail1; + } + cidx = gdCalloc(sidx, 1); + if (cidx == NULL) { + goto fail1; + } + + for (i = 0; i < nc; i++) { + if (gdGetInt(&cidx[i].offset, in) != 1) { + gdFree(cidx); + goto fail1; + } + if (gdGetInt(&cidx[i].size, in) != 1) { + gdFree(cidx); + goto fail1; + } + if (cidx[i].offset < 0 || cidx[i].size < 0) { + gdFree(cidx); + goto fail1; + } + } + *chunkIdx = cidx; + } + + GD2_DBG(php_gd_error(""gd2 header complete"")); + + return 1; + +fail1: + return 0; +} +","@@ -138,11 +138,18 @@ static int _gd2GetHeader(gdIOCtxPtr in, int *sx, int *sy, int *cs, int *vers, in + if (gd2_compressed(*fmt)) { + nc = (*ncx) * (*ncy); + GD2_DBG(php_gd_error(""Reading %d chunk index entries"", nc)); ++ if (overflow2(sidx, nc)) { ++ goto fail1; ++ } + sidx = sizeof(t_chunk_info) * nc; + if (sidx <= 0) { + goto fail1; + } + cidx = gdCalloc(sidx, 1); ++ if (cidx == NULL) { ++ goto fail1; ++ } ++ + for (i = 0; i < nc; i++) { + if (gdGetInt(&cidx[i].offset, in) != 1) { + gdFree(cidx);",959,1290,2048 +2889,"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: + bytestream2_skip(&s->g, len - 2); + break; + case JPEG2000_TLM: + 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; +} +",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: + bytestream2_skip(&s->g, len - 2); + break; + case JPEG2000_TLM: + 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; +} +","@@ -384,6 +384,11 @@ static int get_cox(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c) + return AVERROR_INVALIDDATA; + } + ++ if (c->log2_cblk_width > 6 || c->log2_cblk_height > 6) { ++ avpriv_request_sample(s->avctx, ""cblk size > 64""); ++ return AVERROR_PATCHWELCOME; ++ } ++ + 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); +@@ -1025,6 +1030,9 @@ static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty, + int bpass_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_BYPASS; + int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC; + ++ av_assert0(width <= JPEG2000_MAX_CBLKW); ++ av_assert0(height <= JPEG2000_MAX_CBLKH); ++ + for (y = 0; y < height; y++) + memset(t1->data[y], 0, width * sizeof(**t1->data)); + ",874,1205,2048 +18157,"static int http_connect(URLContext *h, const char *path, const char *local_path, + const char *hoststr, const char *auth, + const char *proxyauth, int *new_location) +{ + HTTPContext *s = h->priv_data; + int post, err; + char headers[HTTP_HEADERS_SIZE] = """"; + char *authstr = NULL, *proxyauthstr = NULL; + int64_t off = s->off; + int len = 0; + const char *method; + int send_expect_100 = 0; + + /* send http header */ + post = h->flags & AVIO_FLAG_WRITE; + + if (s->post_data) { + /* force POST method and disable chunked encoding when + * custom HTTP post data is set */ + post = 1; + s->chunked_post = 0; + } + + if (s->method) + method = s->method; + else + method = post ? ""POST"" : ""GET""; + + authstr = ff_http_auth_create_response(&s->auth_state, auth, + local_path, method); + proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth, + local_path, method); + if (post && !s->post_data) { + send_expect_100 = s->send_expect_100; + /* The user has supplied authentication but we don't know the auth type, + * send Expect: 100-continue to get the 401 response including the + * WWW-Authenticate header, or an 100 continue if no auth actually + * is needed. */ + if (auth && *auth && + s->auth_state.auth_type == HTTP_AUTH_NONE && + s->http_code != 401) + send_expect_100 = 1; + } + +#if FF_API_HTTP_USER_AGENT + if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) { + av_log(s, AV_LOG_WARNING, ""the user-agent option is deprecated, please use user_agent option\n""); + s->user_agent = av_strdup(s->user_agent_deprecated); + } +#endif + /* set default headers if needed */ + if (!has_header(s->headers, ""\r\nUser-Agent: "")) + len += av_strlcatf(headers + len, sizeof(headers) - len, + ""User-Agent: %s\r\n"", s->user_agent); + if (!has_header(s->headers, ""\r\nAccept: "")) + len += av_strlcpy(headers + len, ""Accept: */*\r\n"", + sizeof(headers) - len); + if (!has_header(s->headers, ""\r\nRange: "") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) { + len += av_strlcatf(headers + len, sizeof(headers) - len, + ""Range: bytes=%""PRId64""-"", s->off); + if (s->end_off) + len += av_strlcatf(headers + len, sizeof(headers) - len, + ""%""PRId64, s->end_off - 1); + len += av_strlcpy(headers + len, ""\r\n"", + sizeof(headers) - len); + } + if (send_expect_100 && !has_header(s->headers, ""\r\nExpect: "")) + len += av_strlcatf(headers + len, sizeof(headers) - len, + ""Expect: 100-continue\r\n""); + + if (!has_header(s->headers, ""\r\nConnection: "")) { + if (s->multiple_requests) + len += av_strlcpy(headers + len, ""Connection: keep-alive\r\n"", + sizeof(headers) - len); + else + len += av_strlcpy(headers + len, ""Connection: close\r\n"", + sizeof(headers) - len); + } + + if (!has_header(s->headers, ""\r\nHost: "")) + len += av_strlcatf(headers + len, sizeof(headers) - len, + ""Host: %s\r\n"", hoststr); + if (!has_header(s->headers, ""\r\nContent-Length: "") && s->post_data) + len += av_strlcatf(headers + len, sizeof(headers) - len, + ""Content-Length: %d\r\n"", s->post_datalen); + + if (!has_header(s->headers, ""\r\nContent-Type: "") && s->content_type) + len += av_strlcatf(headers + len, sizeof(headers) - len, + ""Content-Type: %s\r\n"", s->content_type); + if (!has_header(s->headers, ""\r\nCookie: "") && s->cookies) { + char *cookies = NULL; + if (!get_cookies(s, &cookies, path, hoststr) && cookies) { + len += av_strlcatf(headers + len, sizeof(headers) - len, + ""Cookie: %s\r\n"", cookies); + av_free(cookies); + } + } + if (!has_header(s->headers, ""\r\nIcy-MetaData: "") && s->icy) + len += av_strlcatf(headers + len, sizeof(headers) - len, + ""Icy-MetaData: %d\r\n"", 1); + + /* now add in custom headers */ + if (s->headers) + av_strlcpy(headers + len, s->headers, sizeof(headers) - len); + + snprintf(s->buffer, sizeof(s->buffer), + ""%s %s HTTP/1.1\r\n"" + ""%s"" + ""%s"" + ""%s"" + ""%s%s"" + ""\r\n"", + method, + path, + post && s->chunked_post ? ""Transfer-Encoding: chunked\r\n"" : """", + headers, + authstr ? authstr : """", + proxyauthstr ? ""Proxy-"" : """", proxyauthstr ? proxyauthstr : """"); + + av_log(h, AV_LOG_DEBUG, ""request: %s\n"", s->buffer); + + if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0) + goto done; + + if (s->post_data) + if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0) + goto done; + + /* init input buffer */ + s->buf_ptr = s->buffer; + s->buf_end = s->buffer; + s->line_count = 0; + s->off = 0; + s->icy_data_read = 0; + s->filesize = -1; + s->willclose = 0; + s->end_chunked_post = 0; + s->end_header = 0; + if (post && !s->post_data && !send_expect_100) { + /* Pretend that it did work. We didn't read any header yet, since + * we've still to send the POST data, but the code calling this + * function will check http_code after we return. */ + s->http_code = 200; + err = 0; + goto done; + } + + /* wait for header */ + err = http_read_header(h, new_location); + if (err < 0) + goto done; + + if (*new_location) + s->off = off; + + err = (off == s->off) ? 0 : -1; +done: + av_freep(&authstr); + av_freep(&proxyauthstr); + return err; +} +",1,"static int http_connect(URLContext *h, const char *path, const char *local_path, + const char *hoststr, const char *auth, + const char *proxyauth, int *new_location) +{ + HTTPContext *s = h->priv_data; + int post, err; + char headers[HTTP_HEADERS_SIZE] = """"; + char *authstr = NULL, *proxyauthstr = NULL; + uint64_t off = s->off; + int len = 0; + const char *method; + int send_expect_100 = 0; + + /* send http header */ + post = h->flags & AVIO_FLAG_WRITE; + + if (s->post_data) { + /* force POST method and disable chunked encoding when + * custom HTTP post data is set */ + post = 1; + s->chunked_post = 0; + } + + if (s->method) + method = s->method; + else + method = post ? ""POST"" : ""GET""; + + authstr = ff_http_auth_create_response(&s->auth_state, auth, + local_path, method); + proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth, + local_path, method); + if (post && !s->post_data) { + send_expect_100 = s->send_expect_100; + /* The user has supplied authentication but we don't know the auth type, + * send Expect: 100-continue to get the 401 response including the + * WWW-Authenticate header, or an 100 continue if no auth actually + * is needed. */ + if (auth && *auth && + s->auth_state.auth_type == HTTP_AUTH_NONE && + s->http_code != 401) + send_expect_100 = 1; + } + +#if FF_API_HTTP_USER_AGENT + if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) { + av_log(s, AV_LOG_WARNING, ""the user-agent option is deprecated, please use user_agent option\n""); + s->user_agent = av_strdup(s->user_agent_deprecated); + } +#endif + /* set default headers if needed */ + if (!has_header(s->headers, ""\r\nUser-Agent: "")) + len += av_strlcatf(headers + len, sizeof(headers) - len, + ""User-Agent: %s\r\n"", s->user_agent); + if (!has_header(s->headers, ""\r\nAccept: "")) + len += av_strlcpy(headers + len, ""Accept: */*\r\n"", + sizeof(headers) - len); + if (!has_header(s->headers, ""\r\nRange: "") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) { + len += av_strlcatf(headers + len, sizeof(headers) - len, + ""Range: bytes=%""PRIu64""-"", s->off); + if (s->end_off) + len += av_strlcatf(headers + len, sizeof(headers) - len, + ""%""PRId64, s->end_off - 1); + len += av_strlcpy(headers + len, ""\r\n"", + sizeof(headers) - len); + } + if (send_expect_100 && !has_header(s->headers, ""\r\nExpect: "")) + len += av_strlcatf(headers + len, sizeof(headers) - len, + ""Expect: 100-continue\r\n""); + + if (!has_header(s->headers, ""\r\nConnection: "")) { + if (s->multiple_requests) + len += av_strlcpy(headers + len, ""Connection: keep-alive\r\n"", + sizeof(headers) - len); + else + len += av_strlcpy(headers + len, ""Connection: close\r\n"", + sizeof(headers) - len); + } + + if (!has_header(s->headers, ""\r\nHost: "")) + len += av_strlcatf(headers + len, sizeof(headers) - len, + ""Host: %s\r\n"", hoststr); + if (!has_header(s->headers, ""\r\nContent-Length: "") && s->post_data) + len += av_strlcatf(headers + len, sizeof(headers) - len, + ""Content-Length: %d\r\n"", s->post_datalen); + + if (!has_header(s->headers, ""\r\nContent-Type: "") && s->content_type) + len += av_strlcatf(headers + len, sizeof(headers) - len, + ""Content-Type: %s\r\n"", s->content_type); + if (!has_header(s->headers, ""\r\nCookie: "") && s->cookies) { + char *cookies = NULL; + if (!get_cookies(s, &cookies, path, hoststr) && cookies) { + len += av_strlcatf(headers + len, sizeof(headers) - len, + ""Cookie: %s\r\n"", cookies); + av_free(cookies); + } + } + if (!has_header(s->headers, ""\r\nIcy-MetaData: "") && s->icy) + len += av_strlcatf(headers + len, sizeof(headers) - len, + ""Icy-MetaData: %d\r\n"", 1); + + /* now add in custom headers */ + if (s->headers) + av_strlcpy(headers + len, s->headers, sizeof(headers) - len); + + snprintf(s->buffer, sizeof(s->buffer), + ""%s %s HTTP/1.1\r\n"" + ""%s"" + ""%s"" + ""%s"" + ""%s%s"" + ""\r\n"", + method, + path, + post && s->chunked_post ? ""Transfer-Encoding: chunked\r\n"" : """", + headers, + authstr ? authstr : """", + proxyauthstr ? ""Proxy-"" : """", proxyauthstr ? proxyauthstr : """"); + + av_log(h, AV_LOG_DEBUG, ""request: %s\n"", s->buffer); + + if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0) + goto done; + + if (s->post_data) + if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0) + goto done; + + /* init input buffer */ + s->buf_ptr = s->buffer; + s->buf_end = s->buffer; + s->line_count = 0; + s->off = 0; + s->icy_data_read = 0; + s->filesize = UINT64_MAX; + s->willclose = 0; + s->end_chunked_post = 0; + s->end_header = 0; + if (post && !s->post_data && !send_expect_100) { + /* Pretend that it did work. We didn't read any header yet, since + * we've still to send the POST data, but the code calling this + * function will check http_code after we return. */ + s->http_code = 200; + err = 0; + goto done; + } + + /* wait for header */ + err = http_read_header(h, new_location); + if (err < 0) + goto done; + + if (*new_location) + s->off = off; + + err = (off == s->off) ? 0 : -1; +done: + av_freep(&authstr); + av_freep(&proxyauthstr); + return err; +} +","@@ -62,8 +62,8 @@ typedef struct HTTPContext { + int line_count; + int http_code; + /* Used if ""Transfer-Encoding: chunked"" otherwise -1. */ +- int64_t chunksize; +- int64_t off, end_off, filesize; ++ uint64_t chunksize; ++ uint64_t off, end_off, filesize; + char *location; + HTTPAuthState auth_state; + HTTPAuthState proxy_auth_state; +@@ -95,9 +95,9 @@ typedef struct HTTPContext { + AVDictionary *cookie_dict; + int icy; + /* how much data was read since the last ICY metadata packet */ +- int icy_data_read; ++ uint64_t icy_data_read; + /* after how many bytes of read data a new metadata packet will be found */ +- int icy_metaint; ++ uint64_t icy_metaint; + char *icy_metadata_headers; + char *icy_metadata_packet; + AVDictionary *metadata; +@@ -489,7 +489,7 @@ static int http_open(URLContext *h, const char *uri, int flags, + else + h->is_streamed = 1; + +- s->filesize = -1; ++ s->filesize = UINT64_MAX; + s->location = av_strdup(uri); + if (!s->location) + return AVERROR(ENOMEM); +@@ -616,9 +616,9 @@ static void parse_content_range(URLContext *h, const char *p) + + if (!strncmp(p, ""bytes "", 6)) { + p += 6; +- s->off = strtoll(p, NULL, 10); ++ s->off = strtoull(p, NULL, 10); + if ((slash = strchr(p, '/')) && strlen(slash) > 0) +- s->filesize = strtoll(slash + 1, NULL, 10); ++ s->filesize = strtoull(slash + 1, NULL, 10); + } + if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647)) + h->is_streamed = 0; /* we _can_ in fact seek */ +@@ -808,8 +808,9 @@ static int process_line(URLContext *h, char *line, int line_count, + if ((ret = parse_location(s, p)) < 0) + return ret; + *new_location = 1; +- } else if (!av_strcasecmp(tag, ""Content-Length"") && s->filesize == -1) { +- s->filesize = strtoll(p, NULL, 10); ++ } else if (!av_strcasecmp(tag, ""Content-Length"") && ++ s->filesize == UINT64_MAX) { ++ s->filesize = strtoull(p, NULL, 10); + } else if (!av_strcasecmp(tag, ""Content-Range"")) { + parse_content_range(h, p); + } else if (!av_strcasecmp(tag, ""Accept-Ranges"") && +@@ -818,7 +819,7 @@ static int process_line(URLContext *h, char *line, int line_count, + h->is_streamed = 0; + } else if (!av_strcasecmp(tag, ""Transfer-Encoding"") && + !av_strncasecmp(p, ""chunked"", 7)) { +- s->filesize = -1; ++ s->filesize = UINT64_MAX; + s->chunksize = 0; + } else if (!av_strcasecmp(tag, ""WWW-Authenticate"")) { + ff_http_auth_handle_header(&s->auth_state, tag, p); +@@ -842,7 +843,7 @@ static int process_line(URLContext *h, char *line, int line_count, + if (parse_cookie(s, p, &s->cookie_dict)) + av_log(h, AV_LOG_WARNING, ""Unable to parse '%s'\n"", p); + } else if (!av_strcasecmp(tag, ""Icy-MetaInt"")) { +- s->icy_metaint = strtoll(p, NULL, 10); ++ s->icy_metaint = strtoull(p, NULL, 10); + } else if (!av_strncasecmp(tag, ""Icy-"", 4)) { + if ((ret = parse_icy(s, tag, p)) < 0) + return ret; +@@ -972,7 +973,7 @@ static int http_read_header(URLContext *h, int *new_location) + char line[MAX_URL_SIZE]; + int err = 0; + +- s->chunksize = -1; ++ s->chunksize = UINT64_MAX; + + for (;;) { + if ((err = http_get_line(s, line, sizeof(line))) < 0) +@@ -1006,7 +1007,7 @@ static int http_connect(URLContext *h, const char *path, const char *local_path, + int post, err; + char headers[HTTP_HEADERS_SIZE] = """"; + char *authstr = NULL, *proxyauthstr = NULL; +- int64_t off = s->off; ++ uint64_t off = s->off; + int len = 0; + const char *method; + int send_expect_100 = 0; +@@ -1060,7 +1061,7 @@ static int http_connect(URLContext *h, const char *path, const char *local_path, + // server supports seeking by analysing the reply headers. + if (!has_header(s->headers, ""\r\nRange: "") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) { + len += av_strlcatf(headers + len, sizeof(headers) - len, +- ""Range: bytes=%""PRId64""-"", s->off); ++ ""Range: bytes=%""PRIu64""-"", s->off); + if (s->end_off) + len += av_strlcatf(headers + len, sizeof(headers) - len, + ""%""PRId64, s->end_off - 1); +@@ -1135,7 +1136,7 @@ static int http_connect(URLContext *h, const char *path, const char *local_path, + s->line_count = 0; + s->off = 0; + s->icy_data_read = 0; +- s->filesize = -1; ++ s->filesize = UINT64_MAX; + s->willclose = 0; + s->end_chunked_post = 0; + s->end_header = 0; +@@ -1175,15 +1176,13 @@ static int http_buf_read(URLContext *h, uint8_t *buf, int size) + memcpy(buf, s->buf_ptr, len); + s->buf_ptr += len; + } else { +- int64_t target_end = s->end_off ? s->end_off : s->filesize; +- if ((!s->willclose || s->chunksize < 0) && +- target_end >= 0 && s->off >= target_end) ++ uint64_t target_end = s->end_off ? s->end_off : s->filesize; ++ if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end) + return AVERROR_EOF; + len = ffurl_read(s->hd, buf, size); +- if (!len && (!s->willclose || s->chunksize < 0) && +- target_end >= 0 && s->off < target_end) { ++ if (!len && (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) { + av_log(h, AV_LOG_ERROR, +- ""Stream ends prematurely at %""PRId64"", should be %""PRId64""\n"", ++ ""Stream ends prematurely at %""PRIu64"", should be %""PRIu64""\n"", + s->off, target_end + ); + return AVERROR(EIO); +@@ -1247,7 +1246,7 @@ static int http_read_stream(URLContext *h, uint8_t *buf, int size) + return err; + } + +- if (s->chunksize >= 0) { ++ if (s->chunksize != UINT64_MAX) { + if (!s->chunksize) { + char line[32]; + +@@ -1256,13 +1255,19 @@ static int http_read_stream(URLContext *h, uint8_t *buf, int size) + return err; + } while (!*line); /* skip CR LF from last chunk */ + +- s->chunksize = strtoll(line, NULL, 16); ++ s->chunksize = strtoull(line, NULL, 16); + +- av_log(NULL, AV_LOG_TRACE, ""Chunked encoding data size: %""PRId64""'\n"", ++ av_log(h, AV_LOG_TRACE, ++ ""Chunked encoding data size: %""PRIu64""'\n"", + s->chunksize); + + if (!s->chunksize) + return 0; ++ else if (s->chunksize == UINT64_MAX) { ++ av_log(h, AV_LOG_ERROR, ""Invalid chunk size %""PRIu64""\n"", ++ s->chunksize); ++ return AVERROR(EINVAL); ++ } + } + size = FFMIN(size, s->chunksize); + } +@@ -1273,17 +1278,17 @@ static int http_read_stream(URLContext *h, uint8_t *buf, int size) + read_ret = http_buf_read(h, buf, size); + if ( (read_ret < 0 && s->reconnect && (!h->is_streamed || s->reconnect_streamed) && s->filesize > 0 && s->off < s->filesize) + || (read_ret == 0 && s->reconnect_at_eof && (!h->is_streamed || s->reconnect_streamed))) { +- int64_t target = h->is_streamed ? 0 : s->off; ++ uint64_t target = h->is_streamed ? 0 : s->off; + + if (s->reconnect_delay > s->reconnect_delay_max) + return AVERROR(EIO); + +- av_log(h, AV_LOG_INFO, ""Will reconnect at %""PRId64"" error=%s.\n"", s->off, av_err2str(read_ret)); ++ av_log(h, AV_LOG_INFO, ""Will reconnect at %""PRIu64"" error=%s.\n"", s->off, av_err2str(read_ret)); + av_usleep(1000U*1000*s->reconnect_delay); + s->reconnect_delay = 1 + 2*s->reconnect_delay; + seek_ret = http_seek_internal(h, target, SEEK_SET, 1); + if (seek_ret != target) { +- av_log(h, AV_LOG_ERROR, ""Failed to reconnect at %""PRId64"".\n"", target); ++ av_log(h, AV_LOG_ERROR, ""Failed to reconnect at %""PRIu64"".\n"", target); + return read_ret; + } + +@@ -1338,10 +1343,11 @@ static int store_icy(URLContext *h, int size) + { + HTTPContext *s = h->priv_data; + /* until next metadata packet */ +- int remaining = s->icy_metaint - s->icy_data_read; ++ uint64_t remaining; + +- if (remaining < 0) ++ if (s->icy_metaint < s->icy_data_read) + return AVERROR_INVALIDDATA; ++ remaining = s->icy_metaint - s->icy_data_read; + + if (!remaining) { + /* The metadata packet is variable sized. It has a 1 byte header +@@ -1455,7 +1461,7 @@ static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int fo + { + HTTPContext *s = h->priv_data; + URLContext *old_hd = s->hd; +- int64_t old_off = s->off; ++ uint64_t old_off = s->off; + uint8_t old_buf[BUFFER_SIZE]; + int old_buf_size, ret; + AVDictionary *options = NULL; +@@ -1466,7 +1472,7 @@ static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int fo + ((whence == SEEK_CUR && off == 0) || + (whence == SEEK_SET && off == s->off))) + return s->off; +- else if ((s->filesize == -1 && whence == SEEK_END)) ++ else if ((s->filesize == UINT64_MAX && whence == SEEK_END)) + return AVERROR(ENOSYS); + + if (whence == SEEK_CUR) +@@ -1621,7 +1627,7 @@ static int http_proxy_open(URLContext *h, const char *uri, int flags) + s->buf_ptr = s->buffer; + s->buf_end = s->buffer; + s->line_count = 0; +- s->filesize = -1; ++ s->filesize = UINT64_MAX; + cur_auth_type = s->proxy_auth_state.auth_type; + + /* Note: This uses buffering, potentially reading more than the",1644,1975,2048 +8974,"AddPinhole(struct upnphttp * h, const char * action, const char * ns) +{ + int r; + static const char resp[] = + """" + ""%d"" + """"; + char body[512]; + int bodylen; + struct NameValueParserData data; + char * rem_host, * rem_port, * int_ip, * int_port, * protocol, * leaseTime; + int uid = 0; + unsigned short iport, rport; + int ltime; + long proto; + char rem_ip[INET6_ADDRSTRLEN]; + + if(CheckStatus(h)==0) + return; + + ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data); + rem_host = GetValueFromNameValueList(&data, ""RemoteHost""); + rem_port = GetValueFromNameValueList(&data, ""RemotePort""); + int_ip = GetValueFromNameValueList(&data, ""InternalClient""); + int_port = GetValueFromNameValueList(&data, ""InternalPort""); + protocol = GetValueFromNameValueList(&data, ""Protocol""); + leaseTime = GetValueFromNameValueList(&data, ""LeaseTime""); + + rport = (unsigned short)(rem_port ? atoi(rem_port) : 0); + iport = (unsigned short)(int_port ? atoi(int_port) : 0); + ltime = leaseTime ? atoi(leaseTime) : -1; + errno = 0; + proto = protocol ? strtol(protocol, NULL, 0) : -1; + if(errno != 0 || proto > 65535 || proto < 0) + { + SoapError(h, 402, ""Invalid Args""); + goto clear_and_exit; + } + if(iport == 0) + { + SoapError(h, 706, ""InternalPortWilcardingNotAllowed""); + goto clear_and_exit; + } + + /* In particular, [IGD2] RECOMMENDS that unauthenticated and + * unauthorized control points are only allowed to invoke + * this action with: + * - InternalPort value greater than or equal to 1024, + * - InternalClient value equals to the control point's IP address. + * It is REQUIRED that InternalClient cannot be one of IPv6 + * addresses used by the gateway. */ + if(!int_ip || int_ip[0] == '\0' || 0 == strcmp(int_ip, ""*"")) + { + SoapError(h, 708, ""WildCardNotPermittedInSrcIP""); + goto clear_and_exit; + } + /* I guess it is useless to convert int_ip to literal ipv6 address */ + if(rem_host) + { + /* trim */ + while(isspace(rem_host[0])) + rem_host++; + } + /* rem_host should be converted to literal ipv6 : */ + if(rem_host && (rem_host[0] != '\0') && (rem_host[0] != '*')) + { + struct addrinfo *ai, *p; + struct addrinfo hints; + int err; + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_INET6; + /*hints.ai_flags = */ + /* hints.ai_protocol = proto; */ + err = getaddrinfo(rem_host, rem_port, &hints, &ai); + if(err == 0) + { + /* take the 1st IPv6 address */ + for(p = ai; p; p = p->ai_next) + { + if(p->ai_family == AF_INET6) + { + inet_ntop(AF_INET6, + &(((struct sockaddr_in6 *)p->ai_addr)->sin6_addr), + rem_ip, sizeof(rem_ip)); + syslog(LOG_INFO, ""resolved '%s' to '%s'"", rem_host, rem_ip); + rem_host = rem_ip; + break; + } + } + freeaddrinfo(ai); + } + else + { + syslog(LOG_WARNING, ""AddPinhole : getaddrinfo(%s) : %s"", + rem_host, gai_strerror(err)); +#if 0 + SoapError(h, 402, ""Invalid Args""); + goto clear_and_exit; +#endif + } + } + + if(proto == 65535) + { + SoapError(h, 707, ""ProtocolWilcardingNotAllowed""); + goto clear_and_exit; + } + if(proto != IPPROTO_UDP && proto != IPPROTO_TCP +#ifdef IPPROTO_UDPITE + && atoi(protocol) != IPPROTO_UDPLITE +#endif + ) + { + SoapError(h, 705, ""ProtocolNotSupported""); + goto clear_and_exit; + } + if(ltime < 1 || ltime > 86400) + { + syslog(LOG_WARNING, ""%s: LeaseTime=%d not supported, (ip=%s)"", + action, ltime, int_ip); + SoapError(h, 402, ""Invalid Args""); + goto clear_and_exit; + } + + if(PinholeVerification(h, int_ip, iport) <= 0) + goto clear_and_exit; + + syslog(LOG_INFO, ""%s: (inbound) from [%s]:%hu to [%s]:%hu with proto %ld during %d sec"", + action, rem_host?rem_host:""any"", + rport, int_ip, iport, + proto, ltime); + + /* In cases where the RemoteHost, RemotePort, InternalPort, + * InternalClient and Protocol are the same than an existing pinhole, + * but LeaseTime is different, the device MUST extend the existing + * pinhole's lease time and return the UniqueID of the existing pinhole. */ + r = upnp_add_inboundpinhole(rem_host, rport, int_ip, iport, proto, ""IGD2 pinhole"", ltime, &uid); + + switch(r) + { + case 1: /* success */ + bodylen = snprintf(body, sizeof(body), + resp, action, + ns/*""urn:schemas-upnp-org:service:WANIPv6FirewallControl:1""*/, + uid, action); + BuildSendAndCloseSoapResp(h, body, bodylen); + break; + case -1: /* not permitted */ + SoapError(h, 701, ""PinholeSpaceExhausted""); + break; + default: + SoapError(h, 501, ""ActionFailed""); + break; + } + /* 606 Action not authorized + * 701 PinholeSpaceExhausted + * 702 FirewallDisabled + * 703 InboundPinholeNotAllowed + * 705 ProtocolNotSupported + * 706 InternalPortWildcardingNotAllowed + * 707 ProtocolWildcardingNotAllowed + * 708 WildCardNotPermittedInSrcIP */ +clear_and_exit: + ClearNameValueList(&data); +} +",0,"AddPinhole(struct upnphttp * h, const char * action, const char * ns) +{ + int r; + static const char resp[] = + """" + ""%d"" + """"; + char body[512]; + int bodylen; + struct NameValueParserData data; + char * rem_host, * rem_port, * int_ip, * int_port, * protocol, * leaseTime; + int uid = 0; + unsigned short iport, rport; + int ltime; + long proto; + char rem_ip[INET6_ADDRSTRLEN]; + + if(CheckStatus(h)==0) + return; + + ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data); + rem_host = GetValueFromNameValueList(&data, ""RemoteHost""); + rem_port = GetValueFromNameValueList(&data, ""RemotePort""); + int_ip = GetValueFromNameValueList(&data, ""InternalClient""); + int_port = GetValueFromNameValueList(&data, ""InternalPort""); + protocol = GetValueFromNameValueList(&data, ""Protocol""); + leaseTime = GetValueFromNameValueList(&data, ""LeaseTime""); + + rport = (unsigned short)(rem_port ? atoi(rem_port) : 0); + iport = (unsigned short)(int_port ? atoi(int_port) : 0); + ltime = leaseTime ? atoi(leaseTime) : -1; + errno = 0; + proto = protocol ? strtol(protocol, NULL, 0) : -1; + if(errno != 0 || proto > 65535 || proto < 0) + { + SoapError(h, 402, ""Invalid Args""); + goto clear_and_exit; + } + if(iport == 0) + { + SoapError(h, 706, ""InternalPortWilcardingNotAllowed""); + goto clear_and_exit; + } + + /* In particular, [IGD2] RECOMMENDS that unauthenticated and + * unauthorized control points are only allowed to invoke + * this action with: + * - InternalPort value greater than or equal to 1024, + * - InternalClient value equals to the control point's IP address. + * It is REQUIRED that InternalClient cannot be one of IPv6 + * addresses used by the gateway. */ + if(!int_ip || int_ip[0] == '\0' || 0 == strcmp(int_ip, ""*"")) + { + SoapError(h, 708, ""WildCardNotPermittedInSrcIP""); + goto clear_and_exit; + } + /* I guess it is useless to convert int_ip to literal ipv6 address */ + if(rem_host) + { + /* trim */ + while(isspace(rem_host[0])) + rem_host++; + } + /* rem_host should be converted to literal ipv6 : */ + if(rem_host && (rem_host[0] != '\0') && (rem_host[0] != '*')) + { + struct addrinfo *ai, *p; + struct addrinfo hints; + int err; + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_INET6; + /*hints.ai_flags = */ + /* hints.ai_protocol = proto; */ + err = getaddrinfo(rem_host, rem_port, &hints, &ai); + if(err == 0) + { + /* take the 1st IPv6 address */ + for(p = ai; p; p = p->ai_next) + { + if(p->ai_family == AF_INET6) + { + inet_ntop(AF_INET6, + &(((struct sockaddr_in6 *)p->ai_addr)->sin6_addr), + rem_ip, sizeof(rem_ip)); + syslog(LOG_INFO, ""resolved '%s' to '%s'"", rem_host, rem_ip); + rem_host = rem_ip; + break; + } + } + freeaddrinfo(ai); + } + else + { + syslog(LOG_WARNING, ""AddPinhole : getaddrinfo(%s) : %s"", + rem_host, gai_strerror(err)); +#if 0 + SoapError(h, 402, ""Invalid Args""); + goto clear_and_exit; +#endif + } + } + + if(proto == 65535) + { + SoapError(h, 707, ""ProtocolWilcardingNotAllowed""); + goto clear_and_exit; + } + if(proto != IPPROTO_UDP && proto != IPPROTO_TCP +#ifdef IPPROTO_UDPITE + && atoi(protocol) != IPPROTO_UDPLITE +#endif + ) + { + SoapError(h, 705, ""ProtocolNotSupported""); + goto clear_and_exit; + } + if(ltime < 1 || ltime > 86400) + { + syslog(LOG_WARNING, ""%s: LeaseTime=%d not supported, (ip=%s)"", + action, ltime, int_ip); + SoapError(h, 402, ""Invalid Args""); + goto clear_and_exit; + } + + if(PinholeVerification(h, int_ip, iport) <= 0) + goto clear_and_exit; + + syslog(LOG_INFO, ""%s: (inbound) from [%s]:%hu to [%s]:%hu with proto %ld during %d sec"", + action, rem_host?rem_host:""any"", + rport, int_ip, iport, + proto, ltime); + + /* In cases where the RemoteHost, RemotePort, InternalPort, + * InternalClient and Protocol are the same than an existing pinhole, + * but LeaseTime is different, the device MUST extend the existing + * pinhole's lease time and return the UniqueID of the existing pinhole. */ + r = upnp_add_inboundpinhole(rem_host, rport, int_ip, iport, proto, ""IGD2 pinhole"", ltime, &uid); + + switch(r) + { + case 1: /* success */ + bodylen = snprintf(body, sizeof(body), + resp, action, + ns/*""urn:schemas-upnp-org:service:WANIPv6FirewallControl:1""*/, + uid, action); + BuildSendAndCloseSoapResp(h, body, bodylen); + break; + case -1: /* not permitted */ + SoapError(h, 701, ""PinholeSpaceExhausted""); + break; + default: + SoapError(h, 501, ""ActionFailed""); + break; + } + /* 606 Action not authorized + * 701 PinholeSpaceExhausted + * 702 FirewallDisabled + * 703 InboundPinholeNotAllowed + * 705 ProtocolNotSupported + * 706 InternalPortWildcardingNotAllowed + * 707 ProtocolWildcardingNotAllowed + * 708 WildCardNotPermittedInSrcIP */ +clear_and_exit: + ClearNameValueList(&data); +} +","@@ -1850,6 +1850,13 @@ GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * + rem_port = GetValueFromNameValueList(&data, ""RemotePort""); + protocol = GetValueFromNameValueList(&data, ""Protocol""); + ++ if (!int_port || !ext_port || !protocol) ++ { ++ ClearNameValueList(&data); ++ SoapError(h, 402, ""Invalid Args""); ++ return; ++ } ++ + rport = (unsigned short)atoi(rem_port); + iport = (unsigned short)atoi(int_port); + /*proto = atoi(protocol);*/",1535,1866,2048 +6962,"rend_service_intro_has_opened(origin_circuit_t *circuit) +{ + rend_service_t *service; + char buf[RELAY_PAYLOAD_SIZE]; + char serviceid[REND_SERVICE_ID_LEN_BASE32+1]; + unsigned int expiring_nodes_len, num_ip_circuits, valid_ip_circuits = 0; + int reason = END_CIRC_REASON_TORPROTOCOL; + const char *rend_pk_digest; + + tor_assert(circuit->base_.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO); + assert_circ_anonymity_ok(circuit, get_options()); + tor_assert(circuit->cpath); + tor_assert(circuit->rend_data); + /* XXX: This is version 2 specific (only on supported). */ + rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data, NULL); + + base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1, + rend_pk_digest, REND_SERVICE_ID_LEN); + + service = rend_service_get_by_pk_digest(rend_pk_digest); + if (!service) { + log_warn(LD_REND, ""Unrecognized service ID %s on introduction circuit %u."", + safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id); + reason = END_CIRC_REASON_NOSUCHSERVICE; + goto err; + } + + /* Take the current amount of expiring nodes and the current amount of IP + * circuits and compute how many valid IP circuits we have. */ + expiring_nodes_len = (unsigned int) smartlist_len(service->expiring_nodes); + num_ip_circuits = count_intro_point_circuits(service); + /* Let's avoid an underflow. The valid_ip_circuits is initialized to 0 in + * case this condition turns out false because it means that all circuits + * are expiring so we need to keep this circuit. */ + if (num_ip_circuits > expiring_nodes_len) { + valid_ip_circuits = num_ip_circuits - expiring_nodes_len; + } + + /* If we already have enough introduction circuits for this service, + * redefine this one as a general circuit or close it, depending. + * Substract the amount of expiring nodes here because the circuits are + * still opened. */ + if (valid_ip_circuits > service->n_intro_points_wanted) { + const or_options_t *options = get_options(); + /* Remove the intro point associated with this circuit, it's being + * repurposed or closed thus cleanup memory. */ + rend_intro_point_t *intro = find_intro_point(circuit); + if (intro != NULL) { + smartlist_remove(service->intro_nodes, intro); + rend_intro_point_free(intro); + } + + if (options->ExcludeNodes) { + /* XXXX in some future version, we can test whether the transition is + allowed or not given the actual nodes in the circuit. But for now, + this case, we might as well close the thing. */ + log_info(LD_CIRC|LD_REND, ""We have just finished an introduction "" + ""circuit, but we already have enough. Closing it.""); + reason = END_CIRC_REASON_NONE; + goto err; + } else { + tor_assert(circuit->build_state->is_internal); + log_info(LD_CIRC|LD_REND, ""We have just finished an introduction "" + ""circuit, but we already have enough. Redefining purpose to "" + ""general; leaving as internal.""); + + circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_C_GENERAL); + + { + rend_data_free(circuit->rend_data); + circuit->rend_data = NULL; + } + { + crypto_pk_t *intro_key = circuit->intro_key; + circuit->intro_key = NULL; + crypto_pk_free(intro_key); + } + + circuit_has_opened(circuit); + goto done; + } + } + + log_info(LD_REND, + ""Established circuit %u as introduction point for service %s"", + (unsigned)circuit->base_.n_circ_id, serviceid); + circuit_log_path(LOG_INFO, LD_REND, circuit); + + /* Send the ESTABLISH_INTRO cell */ + { + ssize_t len; + len = encode_establish_intro_cell_legacy(buf, sizeof(buf), + circuit->intro_key, + circuit->cpath->prev->rend_circ_nonce); + if (len < 0) { + reason = END_CIRC_REASON_INTERNAL; + goto err; + } + + if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit), + RELAY_COMMAND_ESTABLISH_INTRO, + buf, len, circuit->cpath->prev)<0) { + log_info(LD_GENERAL, + ""Couldn't send introduction request for service %s on circuit %u"", + serviceid, (unsigned)circuit->base_.n_circ_id); + goto done; + } + } + + /* We've attempted to use this circuit */ + pathbias_count_use_attempt(circuit); + + goto done; + + err: + circuit_mark_for_close(TO_CIRCUIT(circuit), reason); + done: + memwipe(buf, 0, sizeof(buf)); + memwipe(serviceid, 0, sizeof(serviceid)); + + return; +} +",0,"rend_service_intro_has_opened(origin_circuit_t *circuit) +{ + rend_service_t *service; + char buf[RELAY_PAYLOAD_SIZE]; + char serviceid[REND_SERVICE_ID_LEN_BASE32+1]; + unsigned int expiring_nodes_len, num_ip_circuits, valid_ip_circuits = 0; + int reason = END_CIRC_REASON_TORPROTOCOL; + const char *rend_pk_digest; + + tor_assert(circuit->base_.purpose == CIRCUIT_PURPOSE_S_ESTABLISH_INTRO); + assert_circ_anonymity_ok(circuit, get_options()); + tor_assert(circuit->cpath); + tor_assert(circuit->rend_data); + /* XXX: This is version 2 specific (only on supported). */ + rend_pk_digest = (char *) rend_data_get_pk_digest(circuit->rend_data, NULL); + + base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32+1, + rend_pk_digest, REND_SERVICE_ID_LEN); + + service = rend_service_get_by_pk_digest(rend_pk_digest); + if (!service) { + log_warn(LD_REND, ""Unrecognized service ID %s on introduction circuit %u."", + safe_str_client(serviceid), (unsigned)circuit->base_.n_circ_id); + reason = END_CIRC_REASON_NOSUCHSERVICE; + goto err; + } + + /* Take the current amount of expiring nodes and the current amount of IP + * circuits and compute how many valid IP circuits we have. */ + expiring_nodes_len = (unsigned int) smartlist_len(service->expiring_nodes); + num_ip_circuits = count_intro_point_circuits(service); + /* Let's avoid an underflow. The valid_ip_circuits is initialized to 0 in + * case this condition turns out false because it means that all circuits + * are expiring so we need to keep this circuit. */ + if (num_ip_circuits > expiring_nodes_len) { + valid_ip_circuits = num_ip_circuits - expiring_nodes_len; + } + + /* If we already have enough introduction circuits for this service, + * redefine this one as a general circuit or close it, depending. + * Substract the amount of expiring nodes here because the circuits are + * still opened. */ + if (valid_ip_circuits > service->n_intro_points_wanted) { + const or_options_t *options = get_options(); + /* Remove the intro point associated with this circuit, it's being + * repurposed or closed thus cleanup memory. */ + rend_intro_point_t *intro = find_intro_point(circuit); + if (intro != NULL) { + smartlist_remove(service->intro_nodes, intro); + rend_intro_point_free(intro); + } + + if (options->ExcludeNodes) { + /* XXXX in some future version, we can test whether the transition is + allowed or not given the actual nodes in the circuit. But for now, + this case, we might as well close the thing. */ + log_info(LD_CIRC|LD_REND, ""We have just finished an introduction "" + ""circuit, but we already have enough. Closing it.""); + reason = END_CIRC_REASON_NONE; + goto err; + } else { + tor_assert(circuit->build_state->is_internal); + log_info(LD_CIRC|LD_REND, ""We have just finished an introduction "" + ""circuit, but we already have enough. Redefining purpose to "" + ""general; leaving as internal.""); + + circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_C_GENERAL); + + { + rend_data_free(circuit->rend_data); + circuit->rend_data = NULL; + } + { + crypto_pk_t *intro_key = circuit->intro_key; + circuit->intro_key = NULL; + crypto_pk_free(intro_key); + } + + circuit_has_opened(circuit); + goto done; + } + } + + log_info(LD_REND, + ""Established circuit %u as introduction point for service %s"", + (unsigned)circuit->base_.n_circ_id, serviceid); + circuit_log_path(LOG_INFO, LD_REND, circuit); + + /* Send the ESTABLISH_INTRO cell */ + { + ssize_t len; + len = encode_establish_intro_cell_legacy(buf, sizeof(buf), + circuit->intro_key, + circuit->cpath->prev->rend_circ_nonce); + if (len < 0) { + reason = END_CIRC_REASON_INTERNAL; + goto err; + } + + if (relay_send_command_from_edge(0, TO_CIRCUIT(circuit), + RELAY_COMMAND_ESTABLISH_INTRO, + buf, len, circuit->cpath->prev)<0) { + log_info(LD_GENERAL, + ""Couldn't send introduction request for service %s on circuit %u"", + serviceid, (unsigned)circuit->base_.n_circ_id); + goto done; + } + } + + /* We've attempted to use this circuit */ + pathbias_count_use_attempt(circuit); + + goto done; + + err: + circuit_mark_for_close(TO_CIRCUIT(circuit), reason); + done: + memwipe(buf, 0, sizeof(buf)); + memwipe(serviceid, 0, sizeof(serviceid)); + + return; +} +","@@ -3372,6 +3372,8 @@ rend_service_intro_established(origin_circuit_t *circuit, + (unsigned)circuit->base_.n_circ_id); + goto err; + } ++ base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1, ++ rend_pk_digest, REND_SERVICE_ID_LEN); + /* We've just successfully established a intro circuit to one of our + * introduction point, account for it. */ + intro = find_intro_point(circuit); +@@ -3388,8 +3390,6 @@ rend_service_intro_established(origin_circuit_t *circuit, + service->desc_is_dirty = time(NULL); + circuit_change_purpose(TO_CIRCUIT(circuit), CIRCUIT_PURPOSE_S_INTRO); + +- base32_encode(serviceid, REND_SERVICE_ID_LEN_BASE32 + 1, +- rend_pk_digest, REND_SERVICE_ID_LEN); + log_info(LD_REND, + ""Received INTRO_ESTABLISHED cell on circuit %u for service %s"", + (unsigned)circuit->base_.n_circ_id, serviceid);",1140,1471,2048 +9397,"bool radeon_atom_get_clock_info(struct drm_device *dev) +{ + struct radeon_device *rdev = dev->dev_private; + struct radeon_mode_info *mode_info = &rdev->mode_info; + int index = GetIndexIntoMasterTable(DATA, FirmwareInfo); + union firmware_info *firmware_info; + uint8_t frev, crev; + struct radeon_pll *p1pll = &rdev->clock.p1pll; + struct radeon_pll *p2pll = &rdev->clock.p2pll; + struct radeon_pll *dcpll = &rdev->clock.dcpll; + struct radeon_pll *spll = &rdev->clock.spll; + struct radeon_pll *mpll = &rdev->clock.mpll; + uint16_t data_offset; + + if (atom_parse_data_header(mode_info->atom_context, index, NULL, + &frev, &crev, &data_offset)) { + firmware_info = + (union firmware_info *)(mode_info->atom_context->bios + + data_offset); + /* pixel clocks */ + p1pll->reference_freq = + le16_to_cpu(firmware_info->info.usReferenceClock); + p1pll->reference_div = 0; + + if (crev < 2) + p1pll->pll_out_min = + le16_to_cpu(firmware_info->info.usMinPixelClockPLL_Output); + else + p1pll->pll_out_min = + le32_to_cpu(firmware_info->info_12.ulMinPixelClockPLL_Output); + p1pll->pll_out_max = + le32_to_cpu(firmware_info->info.ulMaxPixelClockPLL_Output); + + if (crev >= 4) { + p1pll->lcd_pll_out_min = + le16_to_cpu(firmware_info->info_14.usLcdMinPixelClockPLL_Output) * 100; + if (p1pll->lcd_pll_out_min == 0) + p1pll->lcd_pll_out_min = p1pll->pll_out_min; + p1pll->lcd_pll_out_max = + le16_to_cpu(firmware_info->info_14.usLcdMaxPixelClockPLL_Output) * 100; + if (p1pll->lcd_pll_out_max == 0) + p1pll->lcd_pll_out_max = p1pll->pll_out_max; + } else { + p1pll->lcd_pll_out_min = p1pll->pll_out_min; + p1pll->lcd_pll_out_max = p1pll->pll_out_max; + } + + if (p1pll->pll_out_min == 0) { + if (ASIC_IS_AVIVO(rdev)) + p1pll->pll_out_min = 64800; + else + p1pll->pll_out_min = 20000; + } else if (p1pll->pll_out_min > 64800) { + /* Limiting the pll output range is a good thing generally as + * it limits the number of possible pll combinations for a given + * frequency presumably to the ones that work best on each card. + * However, certain duallink DVI monitors seem to like + * pll combinations that would be limited by this at least on + * pre-DCE 3.0 r6xx hardware. This might need to be adjusted per + * family. + */ + if (!radeon_new_pll) + p1pll->pll_out_min = 64800; + } + + p1pll->pll_in_min = + le16_to_cpu(firmware_info->info.usMinPixelClockPLL_Input); + p1pll->pll_in_max = + le16_to_cpu(firmware_info->info.usMaxPixelClockPLL_Input); + + *p2pll = *p1pll; + + /* system clock */ + spll->reference_freq = + le16_to_cpu(firmware_info->info.usReferenceClock); + spll->reference_div = 0; + + spll->pll_out_min = + le16_to_cpu(firmware_info->info.usMinEngineClockPLL_Output); + spll->pll_out_max = + le32_to_cpu(firmware_info->info.ulMaxEngineClockPLL_Output); + + /* ??? */ + if (spll->pll_out_min == 0) { + if (ASIC_IS_AVIVO(rdev)) + spll->pll_out_min = 64800; + else + spll->pll_out_min = 20000; + } + + spll->pll_in_min = + le16_to_cpu(firmware_info->info.usMinEngineClockPLL_Input); + spll->pll_in_max = + le16_to_cpu(firmware_info->info.usMaxEngineClockPLL_Input); + + /* memory clock */ + mpll->reference_freq = + le16_to_cpu(firmware_info->info.usReferenceClock); + mpll->reference_div = 0; + + mpll->pll_out_min = + le16_to_cpu(firmware_info->info.usMinMemoryClockPLL_Output); + mpll->pll_out_max = + le32_to_cpu(firmware_info->info.ulMaxMemoryClockPLL_Output); + + /* ??? */ + if (mpll->pll_out_min == 0) { + if (ASIC_IS_AVIVO(rdev)) + mpll->pll_out_min = 64800; + else + mpll->pll_out_min = 20000; + } + + mpll->pll_in_min = + le16_to_cpu(firmware_info->info.usMinMemoryClockPLL_Input); + mpll->pll_in_max = + le16_to_cpu(firmware_info->info.usMaxMemoryClockPLL_Input); + + rdev->clock.default_sclk = + le32_to_cpu(firmware_info->info.ulDefaultEngineClock); + rdev->clock.default_mclk = + le32_to_cpu(firmware_info->info.ulDefaultMemoryClock); + + if (ASIC_IS_DCE4(rdev)) { + rdev->clock.default_dispclk = + le32_to_cpu(firmware_info->info_21.ulDefaultDispEngineClkFreq); + if (rdev->clock.default_dispclk == 0) + rdev->clock.default_dispclk = 60000; /* 600 Mhz */ + rdev->clock.dp_extclk = + le16_to_cpu(firmware_info->info_21.usUniphyDPModeExtClkFreq); + } + *dcpll = *p1pll; + + return true; + } + + return false; +} +",0,"bool radeon_atom_get_clock_info(struct drm_device *dev) +{ + struct radeon_device *rdev = dev->dev_private; + struct radeon_mode_info *mode_info = &rdev->mode_info; + int index = GetIndexIntoMasterTable(DATA, FirmwareInfo); + union firmware_info *firmware_info; + uint8_t frev, crev; + struct radeon_pll *p1pll = &rdev->clock.p1pll; + struct radeon_pll *p2pll = &rdev->clock.p2pll; + struct radeon_pll *dcpll = &rdev->clock.dcpll; + struct radeon_pll *spll = &rdev->clock.spll; + struct radeon_pll *mpll = &rdev->clock.mpll; + uint16_t data_offset; + + if (atom_parse_data_header(mode_info->atom_context, index, NULL, + &frev, &crev, &data_offset)) { + firmware_info = + (union firmware_info *)(mode_info->atom_context->bios + + data_offset); + /* pixel clocks */ + p1pll->reference_freq = + le16_to_cpu(firmware_info->info.usReferenceClock); + p1pll->reference_div = 0; + + if (crev < 2) + p1pll->pll_out_min = + le16_to_cpu(firmware_info->info.usMinPixelClockPLL_Output); + else + p1pll->pll_out_min = + le32_to_cpu(firmware_info->info_12.ulMinPixelClockPLL_Output); + p1pll->pll_out_max = + le32_to_cpu(firmware_info->info.ulMaxPixelClockPLL_Output); + + if (crev >= 4) { + p1pll->lcd_pll_out_min = + le16_to_cpu(firmware_info->info_14.usLcdMinPixelClockPLL_Output) * 100; + if (p1pll->lcd_pll_out_min == 0) + p1pll->lcd_pll_out_min = p1pll->pll_out_min; + p1pll->lcd_pll_out_max = + le16_to_cpu(firmware_info->info_14.usLcdMaxPixelClockPLL_Output) * 100; + if (p1pll->lcd_pll_out_max == 0) + p1pll->lcd_pll_out_max = p1pll->pll_out_max; + } else { + p1pll->lcd_pll_out_min = p1pll->pll_out_min; + p1pll->lcd_pll_out_max = p1pll->pll_out_max; + } + + if (p1pll->pll_out_min == 0) { + if (ASIC_IS_AVIVO(rdev)) + p1pll->pll_out_min = 64800; + else + p1pll->pll_out_min = 20000; + } else if (p1pll->pll_out_min > 64800) { + /* Limiting the pll output range is a good thing generally as + * it limits the number of possible pll combinations for a given + * frequency presumably to the ones that work best on each card. + * However, certain duallink DVI monitors seem to like + * pll combinations that would be limited by this at least on + * pre-DCE 3.0 r6xx hardware. This might need to be adjusted per + * family. + */ + if (!radeon_new_pll) + p1pll->pll_out_min = 64800; + } + + p1pll->pll_in_min = + le16_to_cpu(firmware_info->info.usMinPixelClockPLL_Input); + p1pll->pll_in_max = + le16_to_cpu(firmware_info->info.usMaxPixelClockPLL_Input); + + *p2pll = *p1pll; + + /* system clock */ + spll->reference_freq = + le16_to_cpu(firmware_info->info.usReferenceClock); + spll->reference_div = 0; + + spll->pll_out_min = + le16_to_cpu(firmware_info->info.usMinEngineClockPLL_Output); + spll->pll_out_max = + le32_to_cpu(firmware_info->info.ulMaxEngineClockPLL_Output); + + /* ??? */ + if (spll->pll_out_min == 0) { + if (ASIC_IS_AVIVO(rdev)) + spll->pll_out_min = 64800; + else + spll->pll_out_min = 20000; + } + + spll->pll_in_min = + le16_to_cpu(firmware_info->info.usMinEngineClockPLL_Input); + spll->pll_in_max = + le16_to_cpu(firmware_info->info.usMaxEngineClockPLL_Input); + + /* memory clock */ + mpll->reference_freq = + le16_to_cpu(firmware_info->info.usReferenceClock); + mpll->reference_div = 0; + + mpll->pll_out_min = + le16_to_cpu(firmware_info->info.usMinMemoryClockPLL_Output); + mpll->pll_out_max = + le32_to_cpu(firmware_info->info.ulMaxMemoryClockPLL_Output); + + /* ??? */ + if (mpll->pll_out_min == 0) { + if (ASIC_IS_AVIVO(rdev)) + mpll->pll_out_min = 64800; + else + mpll->pll_out_min = 20000; + } + + mpll->pll_in_min = + le16_to_cpu(firmware_info->info.usMinMemoryClockPLL_Input); + mpll->pll_in_max = + le16_to_cpu(firmware_info->info.usMaxMemoryClockPLL_Input); + + rdev->clock.default_sclk = + le32_to_cpu(firmware_info->info.ulDefaultEngineClock); + rdev->clock.default_mclk = + le32_to_cpu(firmware_info->info.ulDefaultMemoryClock); + + if (ASIC_IS_DCE4(rdev)) { + rdev->clock.default_dispclk = + le32_to_cpu(firmware_info->info_21.ulDefaultDispEngineClkFreq); + if (rdev->clock.default_dispclk == 0) + rdev->clock.default_dispclk = 60000; /* 600 Mhz */ + rdev->clock.dp_extclk = + le16_to_cpu(firmware_info->info_21.usUniphyDPModeExtClkFreq); + } + *dcpll = *p1pll; + + return true; + } + + return false; +} +","@@ -1264,7 +1264,7 @@ bool radeon_atom_get_tv_timings(struct radeon_device *rdev, int index, + switch (crev) { + case 1: + tv_info = (ATOM_ANALOG_TV_INFO *)(mode_info->atom_context->bios + data_offset); +- if (index > MAX_SUPPORTED_TV_TIMING) ++ if (index >= MAX_SUPPORTED_TV_TIMING) + return false; + + mode->crtc_htotal = le16_to_cpu(tv_info->aModeTimings[index].usCRTC_H_Total); +@@ -1302,7 +1302,7 @@ bool radeon_atom_get_tv_timings(struct radeon_device *rdev, int index, + break; + case 2: + tv_info_v1_2 = (ATOM_ANALOG_TV_INFO_V1_2 *)(mode_info->atom_context->bios + data_offset); +- if (index > MAX_SUPPORTED_TV_TIMING_V1_2) ++ if (index >= MAX_SUPPORTED_TV_TIMING_V1_2) + return false; + + dtd_timings = &tv_info_v1_2->aModeTimings[index];",1437,1768,2048 +9420,"static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm) +{ + struct vm_area_struct *mpnt, *tmp, **pprev; + struct rb_node **rb_link, *rb_parent; + int retval; + unsigned long charge; + struct mempolicy *pol; + + down_write(&oldmm->mmap_sem); + flush_cache_dup_mm(oldmm); + /* + * Not linked in yet - no deadlock potential: + */ + down_write_nested(&mm->mmap_sem, SINGLE_DEPTH_NESTING); + + mm->locked_vm = 0; + mm->mmap = NULL; + mm->mmap_cache = NULL; + mm->free_area_cache = oldmm->mmap_base; + mm->cached_hole_size = ~0UL; + mm->map_count = 0; + cpumask_clear(mm_cpumask(mm)); + mm->mm_rb = RB_ROOT; + rb_link = &mm->mm_rb.rb_node; + rb_parent = NULL; + pprev = &mm->mmap; + retval = ksm_fork(mm, oldmm); + if (retval) + goto out; + + for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) { + struct file *file; + + if (mpnt->vm_flags & VM_DONTCOPY) { + long pages = vma_pages(mpnt); + mm->total_vm -= pages; + vm_stat_account(mm, mpnt->vm_flags, mpnt->vm_file, + -pages); + continue; + } + charge = 0; + if (mpnt->vm_flags & VM_ACCOUNT) { + unsigned int len = (mpnt->vm_end - mpnt->vm_start) >> PAGE_SHIFT; + if (security_vm_enough_memory(len)) + goto fail_nomem; + charge = len; + } + tmp = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL); + if (!tmp) + goto fail_nomem; + *tmp = *mpnt; + pol = mpol_dup(vma_policy(mpnt)); + retval = PTR_ERR(pol); + if (IS_ERR(pol)) + goto fail_nomem_policy; + vma_set_policy(tmp, pol); + tmp->vm_flags &= ~VM_LOCKED; + tmp->vm_mm = mm; + tmp->vm_next = NULL; + anon_vma_link(tmp); + file = tmp->vm_file; + if (file) { + struct inode *inode = file->f_path.dentry->d_inode; + struct address_space *mapping = file->f_mapping; + + get_file(file); + if (tmp->vm_flags & VM_DENYWRITE) + atomic_dec(&inode->i_writecount); + spin_lock(&mapping->i_mmap_lock); + if (tmp->vm_flags & VM_SHARED) + mapping->i_mmap_writable++; + tmp->vm_truncate_count = mpnt->vm_truncate_count; + flush_dcache_mmap_lock(mapping); + /* insert tmp into the share list, just after mpnt */ + vma_prio_tree_add(tmp, mpnt); + flush_dcache_mmap_unlock(mapping); + spin_unlock(&mapping->i_mmap_lock); + } + + /* + * Clear hugetlb-related page reserves for children. This only + * affects MAP_PRIVATE mappings. Faults generated by the child + * are not guaranteed to succeed, even if read-only + */ + if (is_vm_hugetlb_page(tmp)) + reset_vma_resv_huge_pages(tmp); + + /* + * Link in the new vma and copy the page table entries. + */ + *pprev = tmp; + pprev = &tmp->vm_next; + + __vma_link_rb(mm, tmp, rb_link, rb_parent); + rb_link = &tmp->vm_rb.rb_right; + rb_parent = &tmp->vm_rb; + + mm->map_count++; + retval = copy_page_range(mm, oldmm, mpnt); + + if (tmp->vm_ops && tmp->vm_ops->open) + tmp->vm_ops->open(tmp); + + if (retval) + goto out; + } + /* a new mm has just been created */ + arch_dup_mmap(oldmm, mm); + retval = 0; +out: + up_write(&mm->mmap_sem); + flush_tlb_mm(oldmm); + up_write(&oldmm->mmap_sem); + return retval; +fail_nomem_policy: + kmem_cache_free(vm_area_cachep, tmp); +fail_nomem: + retval = -ENOMEM; + vm_unacct_memory(charge); + goto out; +} +",0,"static int dup_mmap(struct mm_struct *mm, struct mm_struct *oldmm) +{ + struct vm_area_struct *mpnt, *tmp, **pprev; + struct rb_node **rb_link, *rb_parent; + int retval; + unsigned long charge; + struct mempolicy *pol; + + down_write(&oldmm->mmap_sem); + flush_cache_dup_mm(oldmm); + /* + * Not linked in yet - no deadlock potential: + */ + down_write_nested(&mm->mmap_sem, SINGLE_DEPTH_NESTING); + + mm->locked_vm = 0; + mm->mmap = NULL; + mm->mmap_cache = NULL; + mm->free_area_cache = oldmm->mmap_base; + mm->cached_hole_size = ~0UL; + mm->map_count = 0; + cpumask_clear(mm_cpumask(mm)); + mm->mm_rb = RB_ROOT; + rb_link = &mm->mm_rb.rb_node; + rb_parent = NULL; + pprev = &mm->mmap; + retval = ksm_fork(mm, oldmm); + if (retval) + goto out; + + for (mpnt = oldmm->mmap; mpnt; mpnt = mpnt->vm_next) { + struct file *file; + + if (mpnt->vm_flags & VM_DONTCOPY) { + long pages = vma_pages(mpnt); + mm->total_vm -= pages; + vm_stat_account(mm, mpnt->vm_flags, mpnt->vm_file, + -pages); + continue; + } + charge = 0; + if (mpnt->vm_flags & VM_ACCOUNT) { + unsigned int len = (mpnt->vm_end - mpnt->vm_start) >> PAGE_SHIFT; + if (security_vm_enough_memory(len)) + goto fail_nomem; + charge = len; + } + tmp = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL); + if (!tmp) + goto fail_nomem; + *tmp = *mpnt; + pol = mpol_dup(vma_policy(mpnt)); + retval = PTR_ERR(pol); + if (IS_ERR(pol)) + goto fail_nomem_policy; + vma_set_policy(tmp, pol); + tmp->vm_flags &= ~VM_LOCKED; + tmp->vm_mm = mm; + tmp->vm_next = NULL; + anon_vma_link(tmp); + file = tmp->vm_file; + if (file) { + struct inode *inode = file->f_path.dentry->d_inode; + struct address_space *mapping = file->f_mapping; + + get_file(file); + if (tmp->vm_flags & VM_DENYWRITE) + atomic_dec(&inode->i_writecount); + spin_lock(&mapping->i_mmap_lock); + if (tmp->vm_flags & VM_SHARED) + mapping->i_mmap_writable++; + tmp->vm_truncate_count = mpnt->vm_truncate_count; + flush_dcache_mmap_lock(mapping); + /* insert tmp into the share list, just after mpnt */ + vma_prio_tree_add(tmp, mpnt); + flush_dcache_mmap_unlock(mapping); + spin_unlock(&mapping->i_mmap_lock); + } + + /* + * Clear hugetlb-related page reserves for children. This only + * affects MAP_PRIVATE mappings. Faults generated by the child + * are not guaranteed to succeed, even if read-only + */ + if (is_vm_hugetlb_page(tmp)) + reset_vma_resv_huge_pages(tmp); + + /* + * Link in the new vma and copy the page table entries. + */ + *pprev = tmp; + pprev = &tmp->vm_next; + + __vma_link_rb(mm, tmp, rb_link, rb_parent); + rb_link = &tmp->vm_rb.rb_right; + rb_parent = &tmp->vm_rb; + + mm->map_count++; + retval = copy_page_range(mm, oldmm, mpnt); + + if (tmp->vm_ops && tmp->vm_ops->open) + tmp->vm_ops->open(tmp); + + if (retval) + goto out; + } + /* a new mm has just been created */ + arch_dup_mmap(oldmm, mm); + retval = 0; +out: + up_write(&mm->mmap_sem); + flush_tlb_mm(oldmm); + up_write(&oldmm->mmap_sem); + return retval; +fail_nomem_policy: + kmem_cache_free(vm_area_cachep, tmp); +fail_nomem: + retval = -ENOMEM; + vm_unacct_memory(charge); + goto out; +} +","@@ -1310,7 +1310,8 @@ static struct task_struct *copy_process(unsigned long clone_flags, + if (pid != &init_struct_pid) + free_pid(pid); + bad_fork_cleanup_io: +- put_io_context(p->io_context); ++ if (p->io_context) ++ exit_io_context(p); + bad_fork_cleanup_namespaces: + exit_task_namespaces(p); + bad_fork_cleanup_mm:",984,1315,2048 +9645,"MagickExport void *FileToBlob(const char *filename,const size_t extent, + size_t *length,ExceptionInfo *exception) +{ + int + file; + + MagickBooleanType + status; + + MagickOffsetType + offset; + + register size_t + i; + + ssize_t + count; + + struct stat + attributes; + + unsigned char + *blob; + + void + *map; + + assert(filename != (const char *) NULL); + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",filename); + assert(exception != (ExceptionInfo *) NULL); + *length=0; + status=IsRightsAuthorized(PathPolicyDomain,ReadPolicyRights,filename); + if (status == MagickFalse) + { + errno=EPERM; + (void) ThrowMagickException(exception,GetMagickModule(),PolicyError, + ""NotAuthorized"",""`%s'"",filename); + return(NULL); + } + file=fileno(stdin); + if (LocaleCompare(filename,""-"") != 0) + { + status=GetPathAttributes(filename,&attributes); + if ((status == MagickFalse) || (S_ISDIR(attributes.st_mode) != 0)) + { + ThrowFileException(exception,BlobError,""UnableToReadBlob"",filename); + return(NULL); + } + file=open_utf8(filename,O_RDONLY | O_BINARY,0); + } + if (file == -1) + { + ThrowFileException(exception,BlobError,""UnableToOpenFile"",filename); + return(NULL); + } + offset=(MagickOffsetType) lseek(file,0,SEEK_END); + count=0; + if ((file == fileno(stdin)) || (offset < 0) || + (offset != (MagickOffsetType) ((ssize_t) offset))) + { + size_t + quantum; + + struct stat + file_stats; + + /* + Stream is not seekable. + */ + offset=(MagickOffsetType) lseek(file,0,SEEK_SET); + quantum=(size_t) MagickMaxBufferExtent; + if ((fstat(file,&file_stats) == 0) && (file_stats.st_size > 0)) + quantum=(size_t) MagickMin(file_stats.st_size,MagickMaxBufferExtent); + blob=(unsigned char *) AcquireQuantumMemory(quantum,sizeof(*blob)); + for (i=0; blob != (unsigned char *) NULL; i+=count) + { + count=read(file,blob+i,quantum); + if (count <= 0) + { + count=0; + if (errno != EINTR) + break; + } + if (~((size_t) i) < (quantum+1)) + { + blob=(unsigned char *) RelinquishMagickMemory(blob); + break; + } + blob=(unsigned char *) ResizeQuantumMemory(blob,i+quantum+1, + sizeof(*blob)); + if ((size_t) (i+count) >= extent) + break; + } + if (LocaleCompare(filename,""-"") != 0) + file=close(file); + if (blob == (unsigned char *) NULL) + { + (void) ThrowMagickException(exception,GetMagickModule(), + ResourceLimitError,""MemoryAllocationFailed"",""`%s'"",filename); + return(NULL); + } + if (file == -1) + { + blob=(unsigned char *) RelinquishMagickMemory(blob); + ThrowFileException(exception,BlobError,""UnableToReadBlob"",filename); + return(NULL); + } + *length=(size_t) MagickMin(i+count,extent); + blob[*length]='\0'; + return(blob); + } + *length=(size_t) MagickMin(offset,(MagickOffsetType) + MagickMin(extent,(size_t) SSIZE_MAX)); + blob=(unsigned char *) NULL; + if (~(*length) >= (MagickPathExtent-1)) + blob=(unsigned char *) AcquireQuantumMemory(*length+MagickPathExtent, + sizeof(*blob)); + if (blob == (unsigned char *) NULL) + { + file=close(file); + (void) ThrowMagickException(exception,GetMagickModule(), + ResourceLimitError,""MemoryAllocationFailed"",""`%s'"",filename); + return(NULL); + } + map=MapBlob(file,ReadMode,0,*length); + if (map != (unsigned char *) NULL) + { + (void) memcpy(blob,map,*length); + (void) UnmapBlob(map,*length); + } + else + { + (void) lseek(file,0,SEEK_SET); + for (i=0; i < *length; i+=count) + { + count=read(file,blob+i,(size_t) MagickMin(*length-i,(size_t) + SSIZE_MAX)); + if (count <= 0) + { + count=0; + if (errno != EINTR) + break; + } + } + if (i < *length) + { + file=close(file)-1; + blob=(unsigned char *) RelinquishMagickMemory(blob); + ThrowFileException(exception,BlobError,""UnableToReadBlob"",filename); + return(NULL); + } + } + blob[*length]='\0'; + if (LocaleCompare(filename,""-"") != 0) + file=close(file); + if (file == -1) + { + blob=(unsigned char *) RelinquishMagickMemory(blob); + ThrowFileException(exception,BlobError,""UnableToReadBlob"",filename); + } + return(blob); +} +",0,"MagickExport void *FileToBlob(const char *filename,const size_t extent, + size_t *length,ExceptionInfo *exception) +{ + int + file; + + MagickBooleanType + status; + + MagickOffsetType + offset; + + register size_t + i; + + ssize_t + count; + + struct stat + attributes; + + unsigned char + *blob; + + void + *map; + + assert(filename != (const char *) NULL); + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",filename); + assert(exception != (ExceptionInfo *) NULL); + *length=0; + status=IsRightsAuthorized(PathPolicyDomain,ReadPolicyRights,filename); + if (status == MagickFalse) + { + errno=EPERM; + (void) ThrowMagickException(exception,GetMagickModule(),PolicyError, + ""NotAuthorized"",""`%s'"",filename); + return(NULL); + } + file=fileno(stdin); + if (LocaleCompare(filename,""-"") != 0) + { + status=GetPathAttributes(filename,&attributes); + if ((status == MagickFalse) || (S_ISDIR(attributes.st_mode) != 0)) + { + ThrowFileException(exception,BlobError,""UnableToReadBlob"",filename); + return(NULL); + } + file=open_utf8(filename,O_RDONLY | O_BINARY,0); + } + if (file == -1) + { + ThrowFileException(exception,BlobError,""UnableToOpenFile"",filename); + return(NULL); + } + offset=(MagickOffsetType) lseek(file,0,SEEK_END); + count=0; + if ((file == fileno(stdin)) || (offset < 0) || + (offset != (MagickOffsetType) ((ssize_t) offset))) + { + size_t + quantum; + + struct stat + file_stats; + + /* + Stream is not seekable. + */ + offset=(MagickOffsetType) lseek(file,0,SEEK_SET); + quantum=(size_t) MagickMaxBufferExtent; + if ((fstat(file,&file_stats) == 0) && (file_stats.st_size > 0)) + quantum=(size_t) MagickMin(file_stats.st_size,MagickMaxBufferExtent); + blob=(unsigned char *) AcquireQuantumMemory(quantum,sizeof(*blob)); + for (i=0; blob != (unsigned char *) NULL; i+=count) + { + count=read(file,blob+i,quantum); + if (count <= 0) + { + count=0; + if (errno != EINTR) + break; + } + if (~((size_t) i) < (quantum+1)) + { + blob=(unsigned char *) RelinquishMagickMemory(blob); + break; + } + blob=(unsigned char *) ResizeQuantumMemory(blob,i+quantum+1, + sizeof(*blob)); + if ((size_t) (i+count) >= extent) + break; + } + if (LocaleCompare(filename,""-"") != 0) + file=close(file); + if (blob == (unsigned char *) NULL) + { + (void) ThrowMagickException(exception,GetMagickModule(), + ResourceLimitError,""MemoryAllocationFailed"",""`%s'"",filename); + return(NULL); + } + if (file == -1) + { + blob=(unsigned char *) RelinquishMagickMemory(blob); + ThrowFileException(exception,BlobError,""UnableToReadBlob"",filename); + return(NULL); + } + *length=(size_t) MagickMin(i+count,extent); + blob[*length]='\0'; + return(blob); + } + *length=(size_t) MagickMin(offset,(MagickOffsetType) + MagickMin(extent,(size_t) SSIZE_MAX)); + blob=(unsigned char *) NULL; + if (~(*length) >= (MagickPathExtent-1)) + blob=(unsigned char *) AcquireQuantumMemory(*length+MagickPathExtent, + sizeof(*blob)); + if (blob == (unsigned char *) NULL) + { + file=close(file); + (void) ThrowMagickException(exception,GetMagickModule(), + ResourceLimitError,""MemoryAllocationFailed"",""`%s'"",filename); + return(NULL); + } + map=MapBlob(file,ReadMode,0,*length); + if (map != (unsigned char *) NULL) + { + (void) memcpy(blob,map,*length); + (void) UnmapBlob(map,*length); + } + else + { + (void) lseek(file,0,SEEK_SET); + for (i=0; i < *length; i+=count) + { + count=read(file,blob+i,(size_t) MagickMin(*length-i,(size_t) + SSIZE_MAX)); + if (count <= 0) + { + count=0; + if (errno != EINTR) + break; + } + } + if (i < *length) + { + file=close(file)-1; + blob=(unsigned char *) RelinquishMagickMemory(blob); + ThrowFileException(exception,BlobError,""UnableToReadBlob"",filename); + return(NULL); + } + } + blob[*length]='\0'; + if (LocaleCompare(filename,""-"") != 0) + file=close(file); + if (file == -1) + { + blob=(unsigned char *) RelinquishMagickMemory(blob); + ThrowFileException(exception,BlobError,""UnableToReadBlob"",filename); + } + return(blob); +} +","@@ -996,6 +996,7 @@ MagickExport void *DetachBlob(BlobInfo *blob_info) + if (blob_info->mapped != MagickFalse) + { + (void) UnmapBlob(blob_info->data,blob_info->length); ++ blob_info->data=NULL; + RelinquishMagickResource(MapResource,blob_info->length); + } + blob_info->mapped=MagickFalse;",1185,1516,2048 +6166,"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; +} +",0,"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; +} +","@@ -1187,8 +1187,11 @@ static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t * + { + OPJ_UINT32 l_data_size; + +- /* The +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */ +- l_data_size = 1 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) * ++ /* +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */ ++ /* and actually +2 required for https://github.com/uclouvain/openjpeg/issues/982 */ ++ /* TODO: is there a theoretical upper-bound for the compressed code */ ++ /* block size ? */ ++ l_data_size = 2 + (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) {",814,1145,2048 +4506,"int lxc_setup(struct lxc_handler *handler) +{ + const char *name = handler->name; + struct lxc_conf *lxc_conf = handler->conf; + const char *lxcpath = handler->lxcpath; + + if (do_rootfs_setup(lxc_conf, name, lxcpath) < 0) { + ERROR(""Error setting up rootfs mount after spawn""); + return -1; + } + + if (lxc_conf->inherit_ns_fd[LXC_NS_UTS] == -1) { + if (setup_utsname(lxc_conf->utsname)) { + ERROR(""failed to setup the utsname for '%s'"", name); + return -1; + } + } + + if (setup_network(&lxc_conf->network)) { + ERROR(""failed to setup the network for '%s'"", name); + return -1; + } + + if (lxc_conf->autodev > 0) { + if (mount_autodev(name, &lxc_conf->rootfs, lxcpath)) { + ERROR(""failed to mount /dev in the container""); + return -1; + } + } + + /* do automatic mounts (mainly /proc and /sys), but exclude + * those that need to wait until other stuff has finished + */ + if (lxc_mount_auto_mounts(lxc_conf, lxc_conf->auto_mounts & ~LXC_AUTO_CGROUP_MASK, handler) < 0) { + ERROR(""failed to setup the automatic mounts for '%s'"", name); + return -1; + } + + if (setup_mount(&lxc_conf->rootfs, lxc_conf->fstab, name)) { + ERROR(""failed to setup the mounts for '%s'"", name); + return -1; + } + + if (!lxc_list_empty(&lxc_conf->mount_list) && setup_mount_entries(&lxc_conf->rootfs, &lxc_conf->mount_list, name)) { + ERROR(""failed to setup the mount entries for '%s'"", name); + return -1; + } + + /* Make sure any start hooks are in the container */ + if (!verify_start_hooks(lxc_conf)) + return -1; + + if (lxc_conf->is_execute) + lxc_execute_bind_init(lxc_conf); + + /* now mount only cgroup, if wanted; + * before, /sys could not have been mounted + * (is either mounted automatically or via fstab entries) + */ + if (lxc_mount_auto_mounts(lxc_conf, lxc_conf->auto_mounts & LXC_AUTO_CGROUP_MASK, handler) < 0) { + ERROR(""failed to setup the automatic mounts for '%s'"", name); + return -1; + } + + if (run_lxc_hooks(name, ""mount"", lxc_conf, lxcpath, NULL)) { + ERROR(""failed to run mount hooks for container '%s'."", name); + return -1; + } + + if (lxc_conf->autodev > 0) { + if (run_lxc_hooks(name, ""autodev"", lxc_conf, lxcpath, NULL)) { + ERROR(""failed to run autodev hooks for container '%s'."", name); + return -1; + } + if (fill_autodev(&lxc_conf->rootfs)) { + ERROR(""failed to populate /dev in the container""); + return -1; + } + } + + if (!lxc_conf->is_execute && setup_console(&lxc_conf->rootfs, &lxc_conf->console, lxc_conf->ttydir)) { + ERROR(""failed to setup the console for '%s'"", name); + return -1; + } + + if (lxc_conf->kmsg) { + if (setup_kmsg(&lxc_conf->rootfs, &lxc_conf->console)) // don't fail + ERROR(""failed to setup kmsg for '%s'"", name); + } + + if (!lxc_conf->is_execute && setup_dev_symlinks(&lxc_conf->rootfs)) { + ERROR(""failed to setup /dev symlinks for '%s'"", name); + return -1; + } + + /* mount /proc if it's not already there */ + if (tmp_proc_mount(lxc_conf) < 0) { + ERROR(""failed to LSM mount proc for '%s'"", name); + return -1; + } + + if (setup_pivot_root(&lxc_conf->rootfs)) { + ERROR(""failed to set rootfs for '%s'"", name); + return -1; + } + + if (setup_pts(lxc_conf->pts)) { + ERROR(""failed to setup the new pts instance""); + return -1; + } + + if (lxc_create_tty(name, lxc_conf)) { + ERROR(""failed to create the ttys""); + return -1; + } + + if (send_ttys_to_parent(handler) < 0) { + ERROR(""failure sending console info to parent""); + return -1; + } + + + if (!lxc_conf->is_execute && setup_tty(lxc_conf)) { + ERROR(""failed to setup the ttys for '%s'"", name); + return -1; + } + + if (lxc_conf->pty_names && setenv(""container_ttys"", lxc_conf->pty_names, 1)) + SYSERROR(""failed to set environment variable for container ptys""); + + + if (setup_personality(lxc_conf->personality)) { + ERROR(""failed to setup personality""); + return -1; + } + + if (!lxc_list_empty(&lxc_conf->keepcaps)) { + if (!lxc_list_empty(&lxc_conf->caps)) { + ERROR(""Simultaneously requested dropping and keeping caps""); + return -1; + } + if (dropcaps_except(&lxc_conf->keepcaps)) { + ERROR(""failed to keep requested caps""); + return -1; + } + } else if (setup_caps(&lxc_conf->caps)) { + ERROR(""failed to drop capabilities""); + return -1; + } + + NOTICE(""'%s' is setup."", name); + + return 0; +} +",0,"int lxc_setup(struct lxc_handler *handler) +{ + const char *name = handler->name; + struct lxc_conf *lxc_conf = handler->conf; + const char *lxcpath = handler->lxcpath; + + if (do_rootfs_setup(lxc_conf, name, lxcpath) < 0) { + ERROR(""Error setting up rootfs mount after spawn""); + return -1; + } + + if (lxc_conf->inherit_ns_fd[LXC_NS_UTS] == -1) { + if (setup_utsname(lxc_conf->utsname)) { + ERROR(""failed to setup the utsname for '%s'"", name); + return -1; + } + } + + if (setup_network(&lxc_conf->network)) { + ERROR(""failed to setup the network for '%s'"", name); + return -1; + } + + if (lxc_conf->autodev > 0) { + if (mount_autodev(name, &lxc_conf->rootfs, lxcpath)) { + ERROR(""failed to mount /dev in the container""); + return -1; + } + } + + /* do automatic mounts (mainly /proc and /sys), but exclude + * those that need to wait until other stuff has finished + */ + if (lxc_mount_auto_mounts(lxc_conf, lxc_conf->auto_mounts & ~LXC_AUTO_CGROUP_MASK, handler) < 0) { + ERROR(""failed to setup the automatic mounts for '%s'"", name); + return -1; + } + + if (setup_mount(&lxc_conf->rootfs, lxc_conf->fstab, name)) { + ERROR(""failed to setup the mounts for '%s'"", name); + return -1; + } + + if (!lxc_list_empty(&lxc_conf->mount_list) && setup_mount_entries(&lxc_conf->rootfs, &lxc_conf->mount_list, name)) { + ERROR(""failed to setup the mount entries for '%s'"", name); + return -1; + } + + /* Make sure any start hooks are in the container */ + if (!verify_start_hooks(lxc_conf)) + return -1; + + if (lxc_conf->is_execute) + lxc_execute_bind_init(lxc_conf); + + /* now mount only cgroup, if wanted; + * before, /sys could not have been mounted + * (is either mounted automatically or via fstab entries) + */ + if (lxc_mount_auto_mounts(lxc_conf, lxc_conf->auto_mounts & LXC_AUTO_CGROUP_MASK, handler) < 0) { + ERROR(""failed to setup the automatic mounts for '%s'"", name); + return -1; + } + + if (run_lxc_hooks(name, ""mount"", lxc_conf, lxcpath, NULL)) { + ERROR(""failed to run mount hooks for container '%s'."", name); + return -1; + } + + if (lxc_conf->autodev > 0) { + if (run_lxc_hooks(name, ""autodev"", lxc_conf, lxcpath, NULL)) { + ERROR(""failed to run autodev hooks for container '%s'."", name); + return -1; + } + if (fill_autodev(&lxc_conf->rootfs)) { + ERROR(""failed to populate /dev in the container""); + return -1; + } + } + + if (!lxc_conf->is_execute && setup_console(&lxc_conf->rootfs, &lxc_conf->console, lxc_conf->ttydir)) { + ERROR(""failed to setup the console for '%s'"", name); + return -1; + } + + if (lxc_conf->kmsg) { + if (setup_kmsg(&lxc_conf->rootfs, &lxc_conf->console)) // don't fail + ERROR(""failed to setup kmsg for '%s'"", name); + } + + if (!lxc_conf->is_execute && setup_dev_symlinks(&lxc_conf->rootfs)) { + ERROR(""failed to setup /dev symlinks for '%s'"", name); + return -1; + } + + /* mount /proc if it's not already there */ + if (tmp_proc_mount(lxc_conf) < 0) { + ERROR(""failed to LSM mount proc for '%s'"", name); + return -1; + } + + if (setup_pivot_root(&lxc_conf->rootfs)) { + ERROR(""failed to set rootfs for '%s'"", name); + return -1; + } + + if (setup_pts(lxc_conf->pts)) { + ERROR(""failed to setup the new pts instance""); + return -1; + } + + if (lxc_create_tty(name, lxc_conf)) { + ERROR(""failed to create the ttys""); + return -1; + } + + if (send_ttys_to_parent(handler) < 0) { + ERROR(""failure sending console info to parent""); + return -1; + } + + + if (!lxc_conf->is_execute && setup_tty(lxc_conf)) { + ERROR(""failed to setup the ttys for '%s'"", name); + return -1; + } + + if (lxc_conf->pty_names && setenv(""container_ttys"", lxc_conf->pty_names, 1)) + SYSERROR(""failed to set environment variable for container ptys""); + + + if (setup_personality(lxc_conf->personality)) { + ERROR(""failed to setup personality""); + return -1; + } + + if (!lxc_list_empty(&lxc_conf->keepcaps)) { + if (!lxc_list_empty(&lxc_conf->caps)) { + ERROR(""Simultaneously requested dropping and keeping caps""); + return -1; + } + if (dropcaps_except(&lxc_conf->keepcaps)) { + ERROR(""failed to keep requested caps""); + return -1; + } + } else if (setup_caps(&lxc_conf->caps)) { + ERROR(""failed to drop capabilities""); + return -1; + } + + NOTICE(""'%s' is setup."", name); + + return 0; +} +","@@ -769,10 +769,11 @@ static int lxc_mount_auto_mounts(struct lxc_conf *conf, int flags, struct lxc_ha + * 2.6.32... + */ + { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, ""proc"", ""%r/proc"", ""proc"", MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL }, +- { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, ""%r/proc/sys/net"", ""%r/proc/net"", NULL, MS_BIND, NULL }, ++ /* proc/tty is used as a temporary placeholder for proc/sys/net which we'll move back in a few steps */ ++ { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, ""%r/proc/sys/net"", ""%r/proc/tty"", NULL, MS_BIND, NULL }, + { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, ""%r/proc/sys"", ""%r/proc/sys"", NULL, MS_BIND, NULL }, + { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, NULL, ""%r/proc/sys"", NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL }, +- { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, ""%r/proc/net"", ""%r/proc/sys/net"", NULL, MS_MOVE, NULL }, ++ { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, ""%r/proc/tty"", ""%r/proc/sys/net"", NULL, MS_MOVE, NULL }, + { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, ""%r/proc/sysrq-trigger"", ""%r/proc/sysrq-trigger"", NULL, MS_BIND, NULL }, + { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_MIXED, NULL, ""%r/proc/sysrq-trigger"", NULL, MS_REMOUNT|MS_BIND|MS_RDONLY, NULL }, + { LXC_AUTO_PROC_MASK, LXC_AUTO_PROC_RW, ""proc"", ""%r/proc"", ""proc"", MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL }, +@@ -815,7 +816,7 @@ static int lxc_mount_auto_mounts(struct lxc_conf *conf, int flags, struct lxc_ha + } + mflags = add_required_remount_flags(source, destination, + default_mounts[i].flags); +- r = mount(source, destination, default_mounts[i].fstype, mflags, default_mounts[i].options); ++ r = safe_mount(source, destination, default_mounts[i].fstype, mflags, default_mounts[i].options, conf->rootfs.path ? conf->rootfs.mount : NULL); + saved_errno = errno; + if (r < 0 && errno == ENOENT) { + INFO(""Mount source or target for %s on %s doesn't exist. Skipping."", source, destination); +@@ -1167,7 +1168,8 @@ static int mount_autodev(const char *name, const struct lxc_rootfs *rootfs, cons + return 0; + } + +- if (mount(""none"", path, ""tmpfs"", 0, ""size=100000,mode=755"")) { ++ if (safe_mount(""none"", path, ""tmpfs"", 0, ""size=100000,mode=755"", ++ rootfs->path ? rootfs->mount : NULL)) { + SYSERROR(""Failed mounting tmpfs onto %s\n"", path); + return false; + } +@@ -1252,7 +1254,8 @@ static int fill_autodev(const struct lxc_rootfs *rootfs) + return -1; + } + fclose(pathfile); +- if (mount(hostpath, path, 0, MS_BIND, NULL) != 0) { ++ if (safe_mount(hostpath, path, 0, MS_BIND, NULL, ++ rootfs->path ? rootfs->mount : NULL) != 0) { + SYSERROR(""Failed bind mounting device %s from host into container"", + d->name); + return -1; +@@ -1505,7 +1508,7 @@ static int setup_dev_console(const struct lxc_rootfs *rootfs, + return -1; + } + +- if (mount(console->name, path, ""none"", MS_BIND, 0)) { ++ if (safe_mount(console->name, path, ""none"", MS_BIND, 0, rootfs->mount)) { + ERROR(""failed to mount '%s' on '%s'"", console->name, path); + return -1; + } +@@ -1560,7 +1563,7 @@ static int setup_ttydir_console(const struct lxc_rootfs *rootfs, + return 0; + } + +- if (mount(console->name, lxcpath, ""none"", MS_BIND, 0)) { ++ if (safe_mount(console->name, lxcpath, ""none"", MS_BIND, 0, rootfs->mount)) { + ERROR(""failed to mount '%s' on '%s'"", console->name, lxcpath); + return -1; + } +@@ -1710,13 +1713,13 @@ static char *get_field(char *src, int nfields) + + static int mount_entry(const char *fsname, const char *target, + const char *fstype, unsigned long mountflags, +- const char *data, int optional) ++ const char *data, int optional, const char *rootfs) + { + #ifdef HAVE_STATVFS + struct statvfs sb; + #endif + +- if (mount(fsname, target, fstype, mountflags & ~MS_REMOUNT, data)) { ++ if (safe_mount(fsname, target, fstype, mountflags & ~MS_REMOUNT, data, rootfs)) { + if (optional) { + INFO(""failed to mount '%s' on '%s' (optional): %s"", fsname, + target, strerror(errno)); +@@ -1763,7 +1766,7 @@ static int mount_entry(const char *fsname, const char *target, + #endif + + if (mount(fsname, target, fstype, +- mountflags | MS_REMOUNT, data)) { ++ mountflags | MS_REMOUNT, data) < 0) { + if (optional) { + INFO(""failed to mount '%s' on '%s' (optional): %s"", + fsname, target, strerror(errno)); +@@ -1843,7 +1846,7 @@ static int mount_entry_create_dir_file(const struct mntent *mntent, + } + + static inline int mount_entry_on_generic(struct mntent *mntent, +- const char* path) ++ const char* path, const char *rootfs) + { + unsigned long mntflags; + char *mntdata; +@@ -1863,7 +1866,7 @@ static inline int mount_entry_on_generic(struct mntent *mntent, + } + + ret = mount_entry(mntent->mnt_fsname, path, mntent->mnt_type, +- mntflags, mntdata, optional); ++ mntflags, mntdata, optional, rootfs); + + free(mntdata); + +@@ -1872,7 +1875,7 @@ static inline int mount_entry_on_generic(struct mntent *mntent, + + static inline int mount_entry_on_systemfs(struct mntent *mntent) + { +- return mount_entry_on_generic(mntent, mntent->mnt_dir); ++ return mount_entry_on_generic(mntent, mntent->mnt_dir, NULL); + } + + static int mount_entry_on_absolute_rootfs(struct mntent *mntent, +@@ -1919,7 +1922,7 @@ static int mount_entry_on_absolute_rootfs(struct mntent *mntent, + return -1; + } + +- return mount_entry_on_generic(mntent, path); ++ return mount_entry_on_generic(mntent, path, rootfs->mount); + } + + static int mount_entry_on_relative_rootfs(struct mntent *mntent, +@@ -1935,7 +1938,7 @@ static int mount_entry_on_relative_rootfs(struct mntent *mntent, + return -1; + } + +- return mount_entry_on_generic(mntent, path); ++ return mount_entry_on_generic(mntent, path, rootfs); + } + + static int mount_file_entries(const struct lxc_rootfs *rootfs, FILE *file, +@@ -3602,7 +3605,7 @@ void lxc_execute_bind_init(struct lxc_conf *conf) + fclose(pathfile); + } + +- ret = mount(path, destpath, ""none"", MS_BIND, NULL); ++ ret = safe_mount(path, destpath, ""none"", MS_BIND, NULL, conf->rootfs.mount); + if (ret < 0) + SYSERROR(""Failed to bind lxc.init.static into container""); + INFO(""lxc.init.static bound into container at %s"", path);",1284,1615,2048 +18168,"static Image *ReadOTBImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ +#define GetBit(a,i) (((a) >> (i)) & 1L) + + Image + *image; + + int + byte; + + MagickBooleanType + status; + + register IndexPacket + *indexes; + + register ssize_t + x; + + register PixelPacket + *q; + + ssize_t + y; + + unsigned char + bit, + info, + depth; + + /* + 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); + } + /* + Initialize image structure. + */ + info=(unsigned char) ReadBlobByte(image); + if (GetBit(info,4) == 0) + { + image->columns=(size_t) ReadBlobByte(image); + image->rows=(size_t) ReadBlobByte(image); + } + else + { + image->columns=(size_t) ReadBlobMSBShort(image); + image->rows=(size_t) ReadBlobMSBShort(image); + } + if ((image->columns == 0) || (image->rows == 0)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + depth=(unsigned char) ReadBlobByte(image); + if (depth != 1) + ThrowReaderException(CoderError,""OnlyLevelZerofilesSupported""); + if (AcquireImageColormap(image,2) == MagickFalse) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + if (image_info->ping != MagickFalse) + { + (void) CloseBlob(image); + return(GetFirstImageInList(image)); + } + /* + Convert bi-level image to pixel packets. + */ + 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); + bit=0; + byte=0; + for (x=0; x < (ssize_t) image->columns; x++) + { + if (bit == 0) + { + byte=ReadBlobByte(image); + if (byte == EOF) + ThrowReaderException(CorruptImageError,""CorruptImage""); + } + SetPixelIndex(indexes+x,(byte & (0x01 << (7-bit))) ? + 0x00 : 0x01); + bit++; + if (bit == 8) + bit=0; + } + 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); + if (EOFBlob(image) != MagickFalse) + ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", + image->filename); + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +",1,"static Image *ReadOTBImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ +#define GetBit(a,i) (((a) >> (i)) & 1L) + + Image + *image; + + int + byte; + + MagickBooleanType + status; + + register IndexPacket + *indexes; + + register ssize_t + x; + + register PixelPacket + *q; + + ssize_t + y; + + unsigned char + bit, + info, + depth; + + /* + 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); + } + /* + Initialize image structure. + */ + info=(unsigned char) ReadBlobByte(image); + if (GetBit(info,4) == 0) + { + image->columns=(size_t) ReadBlobByte(image); + image->rows=(size_t) ReadBlobByte(image); + } + else + { + image->columns=(size_t) ReadBlobMSBShort(image); + image->rows=(size_t) ReadBlobMSBShort(image); + } + if ((image->columns == 0) || (image->rows == 0)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + depth=(unsigned char) ReadBlobByte(image); + if (depth != 1) + ThrowReaderException(CoderError,""OnlyLevelZerofilesSupported""); + if (AcquireImageColormap(image,2) == MagickFalse) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + 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)); + } + /* + Convert bi-level image to pixel packets. + */ + 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); + bit=0; + byte=0; + for (x=0; x < (ssize_t) image->columns; x++) + { + if (bit == 0) + { + byte=ReadBlobByte(image); + if (byte == EOF) + ThrowReaderException(CorruptImageError,""CorruptImage""); + } + SetPixelIndex(indexes+x,(byte & (0x01 << (7-bit))) ? + 0x00 : 0x01); + bit++; + if (bit == 8) + bit=0; + } + 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); + if (EOFBlob(image) != MagickFalse) + ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", + image->filename); + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +","@@ -168,6 +168,12 @@ static Image *ReadOTBImage(const ImageInfo *image_info,ExceptionInfo *exception) + (void) CloseBlob(image); + return(GetFirstImageInList(image)); + } ++ status=SetImageExtent(image,image->columns,image->rows); ++ if (status == MagickFalse) ++ { ++ InheritException(exception,&image->exception); ++ return(DestroyImageList(image)); ++ } + /* + Convert bi-level image to pixel packets. + */",804,1135,2048 +5349,"static int proc_control(struct usb_dev_state *ps, void __user *arg) +{ + struct usb_device *dev = ps->dev; + struct usbdevfs_ctrltransfer ctrl; + unsigned int tmo; + unsigned char *tbuf; + unsigned wLength; + int i, pipe, ret; + + if (copy_from_user(&ctrl, arg, sizeof(ctrl))) + return -EFAULT; + ret = check_ctrlrecip(ps, ctrl.bRequestType, ctrl.bRequest, + ctrl.wIndex); + if (ret) + return ret; + wLength = ctrl.wLength; /* To suppress 64k PAGE_SIZE warning */ + if (wLength > PAGE_SIZE) + return -EINVAL; + ret = usbfs_increase_memory_usage(PAGE_SIZE + sizeof(struct urb) + + sizeof(struct usb_ctrlrequest)); + if (ret) + return ret; + tbuf = (unsigned char *)__get_free_page(GFP_KERNEL); + if (!tbuf) { + ret = -ENOMEM; + goto done; + } + tmo = ctrl.timeout; + snoop(&dev->dev, ""control urb: bRequestType=%02x "" + ""bRequest=%02x wValue=%04x "" + ""wIndex=%04x wLength=%04x\n"", + ctrl.bRequestType, ctrl.bRequest, ctrl.wValue, + ctrl.wIndex, ctrl.wLength); + if (ctrl.bRequestType & 0x80) { + if (ctrl.wLength && !access_ok(VERIFY_WRITE, ctrl.data, + ctrl.wLength)) { + ret = -EINVAL; + goto done; + } + pipe = usb_rcvctrlpipe(dev, 0); + snoop_urb(dev, NULL, pipe, ctrl.wLength, tmo, SUBMIT, NULL, 0); + + usb_unlock_device(dev); + i = usb_control_msg(dev, pipe, ctrl.bRequest, + ctrl.bRequestType, ctrl.wValue, ctrl.wIndex, + tbuf, ctrl.wLength, tmo); + usb_lock_device(dev); + snoop_urb(dev, NULL, pipe, max(i, 0), min(i, 0), COMPLETE, + tbuf, max(i, 0)); + if ((i > 0) && ctrl.wLength) { + if (copy_to_user(ctrl.data, tbuf, i)) { + ret = -EFAULT; + goto done; + } + } + } else { + if (ctrl.wLength) { + if (copy_from_user(tbuf, ctrl.data, ctrl.wLength)) { + ret = -EFAULT; + goto done; + } + } + pipe = usb_sndctrlpipe(dev, 0); + snoop_urb(dev, NULL, pipe, ctrl.wLength, tmo, SUBMIT, + tbuf, ctrl.wLength); + + usb_unlock_device(dev); + i = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), ctrl.bRequest, + ctrl.bRequestType, ctrl.wValue, ctrl.wIndex, + tbuf, ctrl.wLength, tmo); + usb_lock_device(dev); + snoop_urb(dev, NULL, pipe, max(i, 0), min(i, 0), COMPLETE, NULL, 0); + } + if (i < 0 && i != -EPIPE) { + dev_printk(KERN_DEBUG, &dev->dev, ""usbfs: USBDEVFS_CONTROL "" + ""failed cmd %s rqt %u rq %u len %u ret %d\n"", + current->comm, ctrl.bRequestType, ctrl.bRequest, + ctrl.wLength, i); + } + ret = i; + done: + free_page((unsigned long) tbuf); + usbfs_decrease_memory_usage(PAGE_SIZE + sizeof(struct urb) + + sizeof(struct usb_ctrlrequest)); + return ret; +} +",0,"static int proc_control(struct usb_dev_state *ps, void __user *arg) +{ + struct usb_device *dev = ps->dev; + struct usbdevfs_ctrltransfer ctrl; + unsigned int tmo; + unsigned char *tbuf; + unsigned wLength; + int i, pipe, ret; + + if (copy_from_user(&ctrl, arg, sizeof(ctrl))) + return -EFAULT; + ret = check_ctrlrecip(ps, ctrl.bRequestType, ctrl.bRequest, + ctrl.wIndex); + if (ret) + return ret; + wLength = ctrl.wLength; /* To suppress 64k PAGE_SIZE warning */ + if (wLength > PAGE_SIZE) + return -EINVAL; + ret = usbfs_increase_memory_usage(PAGE_SIZE + sizeof(struct urb) + + sizeof(struct usb_ctrlrequest)); + if (ret) + return ret; + tbuf = (unsigned char *)__get_free_page(GFP_KERNEL); + if (!tbuf) { + ret = -ENOMEM; + goto done; + } + tmo = ctrl.timeout; + snoop(&dev->dev, ""control urb: bRequestType=%02x "" + ""bRequest=%02x wValue=%04x "" + ""wIndex=%04x wLength=%04x\n"", + ctrl.bRequestType, ctrl.bRequest, ctrl.wValue, + ctrl.wIndex, ctrl.wLength); + if (ctrl.bRequestType & 0x80) { + if (ctrl.wLength && !access_ok(VERIFY_WRITE, ctrl.data, + ctrl.wLength)) { + ret = -EINVAL; + goto done; + } + pipe = usb_rcvctrlpipe(dev, 0); + snoop_urb(dev, NULL, pipe, ctrl.wLength, tmo, SUBMIT, NULL, 0); + + usb_unlock_device(dev); + i = usb_control_msg(dev, pipe, ctrl.bRequest, + ctrl.bRequestType, ctrl.wValue, ctrl.wIndex, + tbuf, ctrl.wLength, tmo); + usb_lock_device(dev); + snoop_urb(dev, NULL, pipe, max(i, 0), min(i, 0), COMPLETE, + tbuf, max(i, 0)); + if ((i > 0) && ctrl.wLength) { + if (copy_to_user(ctrl.data, tbuf, i)) { + ret = -EFAULT; + goto done; + } + } + } else { + if (ctrl.wLength) { + if (copy_from_user(tbuf, ctrl.data, ctrl.wLength)) { + ret = -EFAULT; + goto done; + } + } + pipe = usb_sndctrlpipe(dev, 0); + snoop_urb(dev, NULL, pipe, ctrl.wLength, tmo, SUBMIT, + tbuf, ctrl.wLength); + + usb_unlock_device(dev); + i = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), ctrl.bRequest, + ctrl.bRequestType, ctrl.wValue, ctrl.wIndex, + tbuf, ctrl.wLength, tmo); + usb_lock_device(dev); + snoop_urb(dev, NULL, pipe, max(i, 0), min(i, 0), COMPLETE, NULL, 0); + } + if (i < 0 && i != -EPIPE) { + dev_printk(KERN_DEBUG, &dev->dev, ""usbfs: USBDEVFS_CONTROL "" + ""failed cmd %s rqt %u rq %u len %u ret %d\n"", + current->comm, ctrl.bRequestType, ctrl.bRequest, + ctrl.wLength, i); + } + ret = i; + done: + free_page((unsigned long) tbuf); + usbfs_decrease_memory_usage(PAGE_SIZE + sizeof(struct urb) + + sizeof(struct usb_ctrlrequest)); + return ret; +} +","@@ -1316,10 +1316,11 @@ static int proc_getdriver(struct usb_dev_state *ps, void __user *arg) + + static int proc_connectinfo(struct usb_dev_state *ps, void __user *arg) + { +- struct usbdevfs_connectinfo ci = { +- .devnum = ps->dev->devnum, +- .slow = ps->dev->speed == USB_SPEED_LOW +- }; ++ struct usbdevfs_connectinfo ci; ++ ++ memset(&ci, 0, sizeof(ci)); ++ ci.devnum = ps->dev->devnum; ++ ci.slow = ps->dev->speed == USB_SPEED_LOW; + + if (copy_to_user(arg, &ci, sizeof(ci))) + return -EFAULT;",806,1137,2048 +578,"dbus_g_proxy_manager_register (DBusGProxyManager *manager, + DBusGProxy *proxy) +{ + DBusGProxyList *list; + DBusGProxyPrivate *priv = DBUS_G_PROXY_GET_PRIVATE(proxy); + + LOCK_MANAGER (manager); + + if (manager->proxy_lists == NULL) + { + g_assert (manager->owner_names == NULL); + g_assert (manager->owner_match_rules == NULL); + + list = NULL; + manager->proxy_lists = g_hash_table_new_full (tristring_hash, + tristring_equal, + NULL, + (GFreeFunc) g_proxy_list_free); + manager->owner_names = g_hash_table_new_full (g_str_hash, + g_str_equal, + g_free, + NULL); + manager->owner_match_rules = g_hash_table_new_full (g_str_hash, + g_str_equal, + g_free, + guint_slice_free); + } + else + { + char *tri; + + tri = tristring_from_proxy (proxy); + + list = g_hash_table_lookup (manager->proxy_lists, tri); + + g_free (tri); + } + + if (list == NULL) + { + list = g_proxy_list_new (proxy); + + g_hash_table_replace (manager->proxy_lists, + list->name, list); + } + + if (list->proxies == NULL && priv->name) + { + /* We have to add match rules to the server, + * but only if the server is a message bus, + * not if it's a peer. + */ + char *rule; + guint *refcount; + + rule = g_proxy_get_signal_match_rule (proxy); + /* We don't check for errors; it's not like anyone would handle them, and + * we don't want a round trip here. + */ + dbus_bus_add_match (manager->connection, rule, NULL); + g_free (rule); + + refcount = g_hash_table_lookup (manager->owner_match_rules, priv->name); + + if (refcount != NULL) + { + g_assert (*refcount != 0); + g_assert (*refcount < G_MAXUINT); + (*refcount)++; + } + else + { + char *rule; + rule = get_owner_match_rule (priv->name); + dbus_bus_add_match (manager->connection, + rule, NULL); + g_free (rule); + + refcount = g_slice_new (guint); + *refcount = 1; + g_hash_table_insert (manager->owner_match_rules, + g_strdup (priv->name), refcount); + } + } + + g_assert (g_slist_find (list->proxies, proxy) == NULL); + + list->proxies = g_slist_prepend (list->proxies, proxy); + + if (!priv->for_owner) + { + const char *owner; + DBusGProxyNameOwnerInfo *info; + + if (!dbus_g_proxy_manager_lookup_name_owner (manager, priv->name, &info, &owner)) + { + priv->name_call = manager_begin_bus_call (manager, ""GetNameOwner"", + got_name_owner_cb, + proxy, NULL, + G_TYPE_STRING, + priv->name, + G_TYPE_INVALID); + + priv->associated = FALSE; + } + else + { + info->refcount++; + priv->associated = TRUE; + } + } + + UNLOCK_MANAGER (manager); +} +",0,"dbus_g_proxy_manager_register (DBusGProxyManager *manager, + DBusGProxy *proxy) +{ + DBusGProxyList *list; + DBusGProxyPrivate *priv = DBUS_G_PROXY_GET_PRIVATE(proxy); + + LOCK_MANAGER (manager); + + if (manager->proxy_lists == NULL) + { + g_assert (manager->owner_names == NULL); + g_assert (manager->owner_match_rules == NULL); + + list = NULL; + manager->proxy_lists = g_hash_table_new_full (tristring_hash, + tristring_equal, + NULL, + (GFreeFunc) g_proxy_list_free); + manager->owner_names = g_hash_table_new_full (g_str_hash, + g_str_equal, + g_free, + NULL); + manager->owner_match_rules = g_hash_table_new_full (g_str_hash, + g_str_equal, + g_free, + guint_slice_free); + } + else + { + char *tri; + + tri = tristring_from_proxy (proxy); + + list = g_hash_table_lookup (manager->proxy_lists, tri); + + g_free (tri); + } + + if (list == NULL) + { + list = g_proxy_list_new (proxy); + + g_hash_table_replace (manager->proxy_lists, + list->name, list); + } + + if (list->proxies == NULL && priv->name) + { + /* We have to add match rules to the server, + * but only if the server is a message bus, + * not if it's a peer. + */ + char *rule; + guint *refcount; + + rule = g_proxy_get_signal_match_rule (proxy); + /* We don't check for errors; it's not like anyone would handle them, and + * we don't want a round trip here. + */ + dbus_bus_add_match (manager->connection, rule, NULL); + g_free (rule); + + refcount = g_hash_table_lookup (manager->owner_match_rules, priv->name); + + if (refcount != NULL) + { + g_assert (*refcount != 0); + g_assert (*refcount < G_MAXUINT); + (*refcount)++; + } + else + { + char *rule; + rule = get_owner_match_rule (priv->name); + dbus_bus_add_match (manager->connection, + rule, NULL); + g_free (rule); + + refcount = g_slice_new (guint); + *refcount = 1; + g_hash_table_insert (manager->owner_match_rules, + g_strdup (priv->name), refcount); + } + } + + g_assert (g_slist_find (list->proxies, proxy) == NULL); + + list->proxies = g_slist_prepend (list->proxies, proxy); + + if (!priv->for_owner) + { + const char *owner; + DBusGProxyNameOwnerInfo *info; + + if (!dbus_g_proxy_manager_lookup_name_owner (manager, priv->name, &info, &owner)) + { + priv->name_call = manager_begin_bus_call (manager, ""GetNameOwner"", + got_name_owner_cb, + proxy, NULL, + G_TYPE_STRING, + priv->name, + G_TYPE_INVALID); + + priv->associated = FALSE; + } + else + { + info->refcount++; + priv->associated = TRUE; + } + } + + UNLOCK_MANAGER (manager); +} +","@@ -1250,8 +1250,11 @@ dbus_g_proxy_manager_filter (DBusConnection *connection, + GSList *tmp; + const char *sender; + ++ sender = dbus_message_get_sender (message); ++ + /* First we handle NameOwnerChanged internally */ +- if (dbus_message_is_signal (message, ++ if (g_strcmp0 (sender, DBUS_SERVICE_DBUS) == 0 && ++ dbus_message_is_signal (message, + DBUS_INTERFACE_DBUS, + ""NameOwnerChanged"")) + { +@@ -1280,8 +1283,6 @@ dbus_g_proxy_manager_filter (DBusConnection *connection, + } + } + +- sender = dbus_message_get_sender (message); +- + /* dbus spec requires these, libdbus validates */ + g_assert (dbus_message_get_path (message) != NULL); + g_assert (dbus_message_get_interface (message) != NULL);",727,1058,2048 +18190,"main(int argc, char * * argv) +{ + const char command0[] = { 0x00, 0x00 }; + char command1[] = ""\x01\x00urn:schemas-upnp-org:device:InternetGatewayDevice""; + char command2[] = ""\x02\x00uuid:fc4ec57e-b051-11db-88f8-0060085db3f6::upnp:rootdevice""; + const char command3[] = { 0x03, 0x00 }; + /* old versions of minissdpd would reject a command with + * a zero length string argument */ + char command3compat[] = ""\x03\x00ssdp:all""; + char command4[] = ""\x04\x00test:test:test""; + const char bad_command[] = { 0xff, 0xff }; + const char overflow[] = { 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; + const char command5[] = { 0x05, 0x00 }; + int s; + int i; + void * tmp; + unsigned char * resp = NULL; + size_t respsize = 0; + unsigned char buf[4096]; + ssize_t n; + int total = 0; + const char * sockpath = ""/var/run/minissdpd.sock""; + + for(i=0; i 0) { + printversion(buf, n); + } else { + printf(""Command 0 (get version) not supported\n""); + close(s); + s = connect_unix_socket(sockpath); + } + + n = SENDCOMMAND(command1, sizeof(command1) - 1); + n = read(s, buf, sizeof(buf)); + printf(""Response received %d bytes\n"", (int)n); + printresponse(buf, n); + if(n == 0) { + close(s); + s = connect_unix_socket(sockpath); + } + + n = SENDCOMMAND(command2, sizeof(command2) - 1); + n = read(s, buf, sizeof(buf)); + printf(""Response received %d bytes\n"", (int)n); + printresponse(buf, n); + if(n == 0) { + close(s); + s = connect_unix_socket(sockpath); + } + + buf[0] = 0; /* Slight hack for printing num devices when 0 */ + n = SENDCOMMAND(command3, sizeof(command3)); + n = read(s, buf, sizeof(buf)); + if(n == 0) { + printf(""command3 failed, testing compatible one\n""); + close(s); + s = connect_unix_socket(sockpath); + n = SENDCOMMAND(command3compat, sizeof(command3compat) - 1); + n = read(s, buf, sizeof(buf)); + } + printf(""Response received %d bytes\n"", (int)n); + printf(""Number of devices %d\n"", (int)buf[0]); + while(n > 0) { + tmp = realloc(resp, respsize + n); + if(tmp == NULL) { + fprintf(stderr, ""memory allocation error\n""); + break; + } + resp = tmp; + respsize += n; + if (n > 0) { + memcpy(resp + total, buf, n); + total += n; + } + if (n < (ssize_t)sizeof(buf)) { + break; + } + + n = read(s, buf, sizeof(buf)); + printf(""response received %d bytes\n"", (int)n); + } + if(resp != NULL) { + printresponse(resp, total); + free(resp); + resp = NULL; + } + if(n == 0) { + close(s); + s = connect_unix_socket(sockpath); + } + + n = SENDCOMMAND(command4, sizeof(command4)); + /* no response for request type 4 */ + + n = SENDCOMMAND(bad_command, sizeof(bad_command)); + n = read(s, buf, sizeof(buf)); + printf(""Response received %d bytes\n"", (int)n); + printresponse(buf, n); + if(n == 0) { + close(s); + s = connect_unix_socket(sockpath); + } + + n = SENDCOMMAND(overflow, sizeof(overflow)); + n = read(s, buf, sizeof(buf)); + printf(""Response received %d bytes\n"", (int)n); + printresponse(buf, n); + if(n == 0) { + close(s); + s = connect_unix_socket(sockpath); + } + + n = SENDCOMMAND(command5, sizeof(command5)); + n = read(s, buf, sizeof(buf)); + printf(""Response received %d bytes\n"", (int)n); + printresponse(buf, n); + + close(s); + return 0; +} +",1,"main(int argc, char * * argv) +{ + const char command0[] = { 0x00, 0x00 }; + char command1[] = ""\x01\x00urn:schemas-upnp-org:device:InternetGatewayDevice""; + char command2[] = ""\x02\x00uuid:fc4ec57e-b051-11db-88f8-0060085db3f6::upnp:rootdevice""; + const char command3[] = { 0x03, 0x00 }; + /* old versions of minissdpd would reject a command with + * a zero length string argument */ + char command3compat[] = ""\x03\x00ssdp:all""; + char command4[] = ""\x04\x00test:test:test""; + const char bad_command[] = { 0xff, 0xff }; + const char overflow[] = { 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; + const char command5[] = { 0x05, 0x00 }; + const char bad_command4[] = { 0x04, 0x01, 0x60, 0x8f, 0xff, 0xff, 0xff, 0x7f}; + int s; + int i; + void * tmp; + unsigned char * resp = NULL; + size_t respsize = 0; + unsigned char buf[4096]; + ssize_t n; + int total = 0; + const char * sockpath = ""/var/run/minissdpd.sock""; + + for(i=0; i 0) { + printversion(buf, n); + } else { + printf(""Command 0 (get version) not supported\n""); + close(s); + s = connect_unix_socket(sockpath); + } + + n = SENDCOMMAND(command1, sizeof(command1) - 1); + n = read(s, buf, sizeof(buf)); + printf(""Response received %d bytes\n"", (int)n); + printresponse(buf, n); + if(n == 0) { + close(s); + s = connect_unix_socket(sockpath); + } + + n = SENDCOMMAND(command2, sizeof(command2) - 1); + n = read(s, buf, sizeof(buf)); + printf(""Response received %d bytes\n"", (int)n); + printresponse(buf, n); + if(n == 0) { + close(s); + s = connect_unix_socket(sockpath); + } + + buf[0] = 0; /* Slight hack for printing num devices when 0 */ + n = SENDCOMMAND(command3, sizeof(command3)); + n = read(s, buf, sizeof(buf)); + if(n == 0) { + printf(""command3 failed, testing compatible one\n""); + close(s); + s = connect_unix_socket(sockpath); + n = SENDCOMMAND(command3compat, sizeof(command3compat) - 1); + n = read(s, buf, sizeof(buf)); + } + printf(""Response received %d bytes\n"", (int)n); + printf(""Number of devices %d\n"", (int)buf[0]); + while(n > 0) { + tmp = realloc(resp, respsize + n); + if(tmp == NULL) { + fprintf(stderr, ""memory allocation error\n""); + break; + } + resp = tmp; + respsize += n; + if (n > 0) { + memcpy(resp + total, buf, n); + total += n; + } + if (n < (ssize_t)sizeof(buf)) { + break; + } + + n = read(s, buf, sizeof(buf)); + printf(""response received %d bytes\n"", (int)n); + } + if(resp != NULL) { + printresponse(resp, total); + free(resp); + resp = NULL; + } + if(n == 0) { + close(s); + s = connect_unix_socket(sockpath); + } + + n = SENDCOMMAND(command4, sizeof(command4)); + /* no response for request type 4 */ + + n = SENDCOMMAND(bad_command, sizeof(bad_command)); + n = read(s, buf, sizeof(buf)); + printf(""Response received %d bytes\n"", (int)n); + printresponse(buf, n); + if(n == 0) { + close(s); + s = connect_unix_socket(sockpath); + } + + n = SENDCOMMAND(overflow, sizeof(overflow)); + n = read(s, buf, sizeof(buf)); + printf(""Response received %d bytes\n"", (int)n); + printresponse(buf, n); + if(n == 0) { + close(s); + s = connect_unix_socket(sockpath); + } + + n = SENDCOMMAND(command5, sizeof(command5)); + n = read(s, buf, sizeof(buf)); + printf(""Response received %d bytes\n"", (int)n); + printresponse(buf, n); + if(n == 0) { + close(s); + s = connect_unix_socket(sockpath); + } + + n = SENDCOMMAND(bad_command4, sizeof(bad_command4)); + n = read(s, buf, sizeof(buf)); + printf(""Response received %d bytes\n"", (int)n); + printresponse(buf, n); + + close(s); + return 0; +} +","@@ -1,4 +1,4 @@ +-/* $Id: testminissdpd.c,v 1.12 2015/08/06 13:16:59 nanard Exp $ */ ++/* $Id: testminissdpd.c,v 1.14 2016/03/01 17:49:51 nanard Exp $ */ + /* Project : miniupnp + * website : http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/ + * Author : Thomas BERNARD +@@ -65,6 +65,7 @@ main(int argc, char * * argv) + const char bad_command[] = { 0xff, 0xff }; + const char overflow[] = { 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; + const char command5[] = { 0x05, 0x00 }; ++ const char bad_command4[] = { 0x04, 0x01, 0x60, 0x8f, 0xff, 0xff, 0xff, 0x7f}; + int s; + int i; + void * tmp; +@@ -180,6 +181,15 @@ main(int argc, char * * argv) + n = read(s, buf, sizeof(buf)); + printf(""Response received %d bytes\n"", (int)n); + printresponse(buf, n); ++ if(n == 0) { ++ close(s); ++ s = connect_unix_socket(sockpath); ++ } ++ ++ n = SENDCOMMAND(bad_command4, sizeof(bad_command4)); ++ n = read(s, buf, sizeof(buf)); ++ printf(""Response received %d bytes\n"", (int)n); ++ printresponse(buf, n); + + close(s); + return 0;",1146,1477,2048 +18624,"static PassRefPtr cropImage( + Image* image, + const ParsedOptions& parsedOptions, + AlphaDisposition imageFormat = PremultiplyAlpha, + ImageDecoder::ColorSpaceOption colorSpaceOp = + ImageDecoder::ColorSpaceApplied) { + ASSERT(image); + IntRect imgRect(IntPoint(), IntSize(image->width(), image->height())); + const IntRect srcRect = intersection(imgRect, parsedOptions.cropRect); + + if (srcRect.isEmpty() && !parsedOptions.premultiplyAlpha) { + SkImageInfo info = + SkImageInfo::Make(parsedOptions.resizeWidth, parsedOptions.resizeHeight, + kN32_SkColorType, kUnpremul_SkAlphaType); + RefPtr dstBuffer = ArrayBuffer::createOrNull( + static_cast(info.width()) * info.height(), + info.bytesPerPixel()); + if (!dstBuffer) + return nullptr; + RefPtr dstPixels = + Uint8Array::create(dstBuffer, 0, dstBuffer->byteLength()); + return StaticBitmapImage::create(newSkImageFromRaster( + info, std::move(dstPixels), + static_cast(info.width()) * info.bytesPerPixel())); + } + + sk_sp skiaImage = image->imageForCurrentFrame(); + if ((((!parsedOptions.premultiplyAlpha && !skiaImage->isOpaque()) || + !skiaImage) && + image->data() && imageFormat == PremultiplyAlpha) || + colorSpaceOp == ImageDecoder::ColorSpaceIgnored) { + std::unique_ptr decoder(ImageDecoder::create( + image->data(), true, + parsedOptions.premultiplyAlpha ? ImageDecoder::AlphaPremultiplied + : ImageDecoder::AlphaNotPremultiplied, + colorSpaceOp)); + if (!decoder) + return nullptr; + skiaImage = ImageBitmap::getSkImageFromDecoder(std::move(decoder)); + if (!skiaImage) + return nullptr; + } + + if (parsedOptions.cropRect == srcRect && !parsedOptions.shouldScaleInput) { + sk_sp croppedSkImage = skiaImage->makeSubset(srcRect); + if (parsedOptions.flipY) + return StaticBitmapImage::create(flipSkImageVertically( + croppedSkImage.get(), parsedOptions.premultiplyAlpha + ? PremultiplyAlpha + : DontPremultiplyAlpha)); + if (parsedOptions.premultiplyAlpha && imageFormat == DontPremultiplyAlpha) + return StaticBitmapImage::create( + unPremulSkImageToPremul(croppedSkImage.get())); + croppedSkImage->preroll(); + return StaticBitmapImage::create(std::move(croppedSkImage)); + } + + sk_sp surface = SkSurface::MakeRasterN32Premul( + parsedOptions.resizeWidth, parsedOptions.resizeHeight); + if (!surface) + return nullptr; + if (srcRect.isEmpty()) + return StaticBitmapImage::create(surface->makeImageSnapshot()); + + SkScalar dstLeft = std::min(0, -parsedOptions.cropRect.x()); + SkScalar dstTop = std::min(0, -parsedOptions.cropRect.y()); + if (parsedOptions.cropRect.x() < 0) + dstLeft = -parsedOptions.cropRect.x(); + if (parsedOptions.cropRect.y() < 0) + dstTop = -parsedOptions.cropRect.y(); + if (parsedOptions.flipY) { + surface->getCanvas()->translate(0, surface->height()); + surface->getCanvas()->scale(1, -1); + } + if (parsedOptions.shouldScaleInput) { + SkRect drawSrcRect = SkRect::MakeXYWH( + parsedOptions.cropRect.x(), parsedOptions.cropRect.y(), + parsedOptions.cropRect.width(), parsedOptions.cropRect.height()); + SkRect drawDstRect = SkRect::MakeXYWH(0, 0, parsedOptions.resizeWidth, + parsedOptions.resizeHeight); + SkPaint paint; + paint.setFilterQuality(parsedOptions.resizeQuality); + surface->getCanvas()->drawImageRect(skiaImage, drawSrcRect, drawDstRect, + &paint); + } else { + surface->getCanvas()->drawImage(skiaImage, dstLeft, dstTop); + } + skiaImage = surface->makeImageSnapshot(); + + if (parsedOptions.premultiplyAlpha) { + if (imageFormat == DontPremultiplyAlpha) + return StaticBitmapImage::create( + unPremulSkImageToPremul(skiaImage.get())); + return StaticBitmapImage::create(std::move(skiaImage)); + } + return StaticBitmapImage::create(premulSkImageToUnPremul(skiaImage.get())); +} +",1,"static PassRefPtr cropImage( + Image* image, + const ParsedOptions& parsedOptions, + AlphaDisposition imageFormat = PremultiplyAlpha, + ImageDecoder::ColorSpaceOption colorSpaceOp = + ImageDecoder::ColorSpaceApplied) { + ASSERT(image); + IntRect imgRect(IntPoint(), IntSize(image->width(), image->height())); + const IntRect srcRect = intersection(imgRect, parsedOptions.cropRect); + + if (srcRect.isEmpty() && !parsedOptions.premultiplyAlpha) { + SkImageInfo info = + SkImageInfo::Make(parsedOptions.resizeWidth, parsedOptions.resizeHeight, + kN32_SkColorType, kUnpremul_SkAlphaType); + RefPtr dstBuffer = ArrayBuffer::createOrNull( + static_cast(info.width()) * info.height(), + info.bytesPerPixel()); + if (!dstBuffer) + return nullptr; + RefPtr dstPixels = + Uint8Array::create(dstBuffer, 0, dstBuffer->byteLength()); + return StaticBitmapImage::create(newSkImageFromRaster( + info, std::move(dstPixels), + static_cast(info.width()) * info.bytesPerPixel())); + } + + sk_sp skiaImage = image->imageForCurrentFrame(); + if ((((!parsedOptions.premultiplyAlpha && !skiaImage->isOpaque()) || + !skiaImage) && + image->data() && imageFormat == PremultiplyAlpha) || + colorSpaceOp == ImageDecoder::ColorSpaceIgnored) { + std::unique_ptr decoder(ImageDecoder::create( + image->data(), true, + parsedOptions.premultiplyAlpha ? ImageDecoder::AlphaPremultiplied + : ImageDecoder::AlphaNotPremultiplied, + colorSpaceOp)); + if (!decoder) + return nullptr; + skiaImage = ImageBitmap::getSkImageFromDecoder(std::move(decoder)); + if (!skiaImage) + return nullptr; + } + + if (parsedOptions.cropRect == srcRect && !parsedOptions.shouldScaleInput) { + sk_sp croppedSkImage = skiaImage->makeSubset(srcRect); + if (parsedOptions.flipY) + return StaticBitmapImage::create(flipSkImageVertically( + croppedSkImage.get(), parsedOptions.premultiplyAlpha + ? PremultiplyAlpha + : DontPremultiplyAlpha)); + if (parsedOptions.premultiplyAlpha && imageFormat == DontPremultiplyAlpha) + return StaticBitmapImage::create( + unPremulSkImageToPremul(croppedSkImage.get())); + croppedSkImage->preroll(); + return StaticBitmapImage::create(std::move(croppedSkImage)); + } + + sk_sp surface = SkSurface::MakeRasterN32Premul( + parsedOptions.resizeWidth, parsedOptions.resizeHeight); + if (!surface) + return nullptr; + if (srcRect.isEmpty()) + return StaticBitmapImage::create(surface->makeImageSnapshot()); + + SkScalar dstLeft = std::min(0, -parsedOptions.cropRect.x()); + SkScalar dstTop = std::min(0, -parsedOptions.cropRect.y()); + if (parsedOptions.cropRect.x() < 0) + dstLeft = -parsedOptions.cropRect.x(); + if (parsedOptions.cropRect.y() < 0) + dstTop = -parsedOptions.cropRect.y(); + if (parsedOptions.flipY) { + surface->getCanvas()->translate(0, surface->height()); + surface->getCanvas()->scale(1, -1); + } + if (parsedOptions.shouldScaleInput) { + SkRect drawSrcRect = SkRect::MakeXYWH( + parsedOptions.cropRect.x(), parsedOptions.cropRect.y(), + parsedOptions.cropRect.width(), parsedOptions.cropRect.height()); + SkRect drawDstRect = SkRect::MakeXYWH(0, 0, parsedOptions.resizeWidth, + parsedOptions.resizeHeight); + SkPaint paint; + paint.setFilterQuality(parsedOptions.resizeQuality); + surface->getCanvas()->drawImageRect(skiaImage, drawSrcRect, drawDstRect, + &paint); + } else { + surface->getCanvas()->drawImage(skiaImage, dstLeft, dstTop); + } + skiaImage = surface->makeImageSnapshot(); + + if (parsedOptions.premultiplyAlpha) { + if (imageFormat == DontPremultiplyAlpha) + return StaticBitmapImage::create( + unPremulSkImageToPremul(skiaImage.get())); + return StaticBitmapImage::create(std::move(skiaImage)); + } + return StaticBitmapImage::create(premulSkImageToUnPremul(skiaImage.get())); +} +","@@ -108,7 +108,7 @@ ParsedOptions parseOptions(const ImageBitmapOptions& options, + } + + bool dstBufferSizeHasOverflow(ParsedOptions options) { +- CheckedNumeric totalBytes = options.cropRect.width(); ++ CheckedNumeric totalBytes = options.cropRect.width(); + totalBytes *= options.cropRect.height(); + totalBytes *= options.bytesPerPixel; + if (!totalBytes.IsValid()) +@@ -131,8 +131,8 @@ static PassRefPtr copySkImageData(SkImage* input, + const SkImageInfo& info) { + // The function dstBufferSizeHasOverflow() is being called at the beginning of + // each ImageBitmap() constructor, which makes sure that doing +- // width * height * bytesPerPixel will never overflow size_t. +- size_t width = static_cast(input->width()); ++ // width * height * bytesPerPixel will never overflow unsigned. ++ unsigned width = static_cast(input->width()); + RefPtr dstBuffer = + ArrayBuffer::createOrNull(width * input->height(), info.bytesPerPixel()); + if (!dstBuffer) +@@ -146,7 +146,7 @@ static PassRefPtr copySkImageData(SkImage* input, + + static sk_sp newSkImageFromRaster(const SkImageInfo& info, + PassRefPtr imagePixels, +- size_t imageRowBytes) { ++ unsigned imageRowBytes) { + SkPixmap pixmap(info, imagePixels->data(), imageRowBytes); + return SkImage::MakeFromRaster(pixmap, + [](const void*, void* pixels) { +@@ -156,15 +156,15 @@ static sk_sp newSkImageFromRaster(const SkImageInfo& info, + } + + static void swizzleImageData(unsigned char* srcAddr, +- size_t height, +- size_t bytesPerRow, ++ unsigned height, ++ unsigned bytesPerRow, + bool flipY) { + if (flipY) { +- for (size_t i = 0; i < height / 2; i++) { +- size_t topRowStartPosition = i * bytesPerRow; +- size_t bottomRowStartPosition = (height - 1 - i) * bytesPerRow; ++ for (unsigned i = 0; i < height / 2; i++) { ++ unsigned topRowStartPosition = i * bytesPerRow; ++ unsigned bottomRowStartPosition = (height - 1 - i) * bytesPerRow; + if (kN32_SkColorType == kBGRA_8888_SkColorType) { // needs to swizzle +- for (size_t j = 0; j < bytesPerRow; j += 4) { ++ for (unsigned j = 0; j < bytesPerRow; j += 4) { + std::swap(srcAddr[topRowStartPosition + j], + srcAddr[bottomRowStartPosition + j + 2]); + std::swap(srcAddr[topRowStartPosition + j + 1], +@@ -182,27 +182,27 @@ static void swizzleImageData(unsigned char* srcAddr, + } + } else { + if (kN32_SkColorType == kBGRA_8888_SkColorType) // needs to swizzle +- for (size_t i = 0; i < height * bytesPerRow; i += 4) ++ for (unsigned i = 0; i < height * bytesPerRow; i += 4) + std::swap(srcAddr[i], srcAddr[i + 2]); + } + } + + static sk_sp flipSkImageVertically(SkImage* input, + AlphaDisposition alphaOp) { +- size_t width = static_cast(input->width()); +- size_t height = static_cast(input->height()); ++ unsigned width = static_cast(input->width()); ++ unsigned height = static_cast(input->height()); + SkImageInfo info = SkImageInfo::MakeN32(input->width(), input->height(), + (alphaOp == PremultiplyAlpha) + ? kPremul_SkAlphaType + : kUnpremul_SkAlphaType); +- size_t imageRowBytes = width * info.bytesPerPixel(); ++ unsigned imageRowBytes = width * info.bytesPerPixel(); + RefPtr imagePixels = copySkImageData(input, info); + if (!imagePixels) + return nullptr; +- for (size_t i = 0; i < height / 2; i++) { +- size_t topFirstElement = i * imageRowBytes; +- size_t topLastElement = (i + 1) * imageRowBytes; +- size_t bottomFirstElement = (height - 1 - i) * imageRowBytes; ++ for (unsigned i = 0; i < height / 2; i++) { ++ unsigned topFirstElement = i * imageRowBytes; ++ unsigned topLastElement = (i + 1) * imageRowBytes; ++ unsigned bottomFirstElement = (height - 1 - i) * imageRowBytes; + std::swap_ranges(imagePixels->data() + topFirstElement, + imagePixels->data() + topLastElement, + imagePixels->data() + bottomFirstElement); +@@ -218,7 +218,7 @@ static sk_sp premulSkImageToUnPremul(SkImage* input) { + return nullptr; + return newSkImageFromRaster( + info, std::move(dstPixels), +- static_cast(input->width()) * info.bytesPerPixel()); ++ static_cast(input->width()) * info.bytesPerPixel()); + } + + static sk_sp unPremulSkImageToPremul(SkImage* input) { +@@ -229,7 +229,7 @@ static sk_sp unPremulSkImageToPremul(SkImage* input) { + return nullptr; + return newSkImageFromRaster( + info, std::move(dstPixels), +- static_cast(input->width()) * info.bytesPerPixel()); ++ static_cast(input->width()) * info.bytesPerPixel()); + } + + sk_sp ImageBitmap::getSkImageFromDecoder( +@@ -290,15 +290,15 @@ static PassRefPtr cropImage( + SkImageInfo::Make(parsedOptions.resizeWidth, parsedOptions.resizeHeight, + kN32_SkColorType, kUnpremul_SkAlphaType); + RefPtr dstBuffer = ArrayBuffer::createOrNull( +- static_cast(info.width()) * info.height(), ++ static_cast(info.width()) * info.height(), + info.bytesPerPixel()); + if (!dstBuffer) + return nullptr; + RefPtr dstPixels = + Uint8Array::create(dstBuffer, 0, dstBuffer->byteLength()); + return StaticBitmapImage::create(newSkImageFromRaster( + info, std::move(dstPixels), +- static_cast(info.width()) * info.bytesPerPixel())); ++ static_cast(info.width()) * info.bytesPerPixel())); + } + + sk_sp skiaImage = image->imageForCurrentFrame(); +@@ -524,7 +524,7 @@ static sk_sp scaleSkImage(sk_sp skImage, + Uint8Array::create(dstBuffer, 0, dstBuffer->byteLength()); + SkPixmap pixmap( + resizedInfo, resizedPixels->data(), +- static_cast(resizeWidth) * resizedInfo.bytesPerPixel()); ++ static_cast(resizeWidth) * resizedInfo.bytesPerPixel()); + skImage->scalePixels(pixmap, resizeQuality); + return SkImage::MakeFromRaster(pixmap, + [](const void*, void* pixels) { +@@ -553,9 +553,10 @@ ImageBitmap::ImageBitmap(ImageData* data, + SkImageInfo info = SkImageInfo::Make( + parsedOptions.cropRect.width(), parsedOptions.cropRect.height(), + kN32_SkColorType, kUnpremul_SkAlphaType); +- size_t bytesPerPixel = static_cast(info.bytesPerPixel()); +- size_t srcPixelBytesPerRow = bytesPerPixel * data->size().width(); +- size_t dstPixelBytesPerRow = bytesPerPixel * parsedOptions.cropRect.width(); ++ unsigned bytesPerPixel = static_cast(info.bytesPerPixel()); ++ unsigned srcPixelBytesPerRow = bytesPerPixel * data->size().width(); ++ unsigned dstPixelBytesPerRow = ++ bytesPerPixel * parsedOptions.cropRect.width(); + sk_sp skImage; + if (parsedOptions.cropRect == IntRect(IntPoint(), data->size())) { + swizzleImageData(srcAddr, data->size().height(), srcPixelBytesPerRow, +@@ -567,7 +568,7 @@ ImageBitmap::ImageBitmap(ImageData* data, + parsedOptions.flipY); + } else { + RefPtr dstBuffer = ArrayBuffer::createOrNull( +- static_cast(parsedOptions.cropRect.height()) * ++ static_cast(parsedOptions.cropRect.height()) * + parsedOptions.cropRect.width(), + bytesPerPixel); + if (!dstBuffer) +@@ -589,12 +590,12 @@ ImageBitmap::ImageBitmap(ImageData* data, + if (parsedOptions.cropRect.width() < copyWidth) + copyWidth = parsedOptions.cropRect.width(); + for (int i = 0; i < copyHeight; i++) { +- size_t srcStartCopyPosition = ++ unsigned srcStartCopyPosition = + (i + srcPoint.y()) * srcPixelBytesPerRow + + srcPoint.x() * bytesPerPixel; +- size_t srcEndCopyPosition = ++ unsigned srcEndCopyPosition = + srcStartCopyPosition + copyWidth * bytesPerPixel; +- size_t dstStartCopyPosition; ++ unsigned dstStartCopyPosition; + if (parsedOptions.flipY) + dstStartCopyPosition = + (parsedOptions.cropRect.height() - 1 - dstPoint.y() - i) * +@@ -603,7 +604,7 @@ ImageBitmap::ImageBitmap(ImageData* data, + else + dstStartCopyPosition = (dstPoint.y() + i) * dstPixelBytesPerRow + + dstPoint.x() * bytesPerPixel; +- for (size_t j = 0; j < srcEndCopyPosition - srcStartCopyPosition; ++ for (unsigned j = 0; j < srcEndCopyPosition - srcStartCopyPosition; + j++) { + // swizzle when necessary + if (kN32_SkColorType == kBGRA_8888_SkColorType) {",1004,1335,2048 +18285,"static int userfaultfd_register(struct userfaultfd_ctx *ctx, + unsigned long arg) +{ + struct mm_struct *mm = ctx->mm; + struct vm_area_struct *vma, *prev, *cur; + int ret; + struct uffdio_register uffdio_register; + struct uffdio_register __user *user_uffdio_register; + unsigned long vm_flags, new_flags; + bool found; + bool basic_ioctls; + unsigned long start, end, vma_end; + + user_uffdio_register = (struct uffdio_register __user *) arg; + + ret = -EFAULT; + if (copy_from_user(&uffdio_register, user_uffdio_register, + sizeof(uffdio_register)-sizeof(__u64))) + goto out; + + ret = -EINVAL; + if (!uffdio_register.mode) + goto out; + if (uffdio_register.mode & ~(UFFDIO_REGISTER_MODE_MISSING| + UFFDIO_REGISTER_MODE_WP)) + goto out; + vm_flags = 0; + if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING) + vm_flags |= VM_UFFD_MISSING; + if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) { + vm_flags |= VM_UFFD_WP; + /* + * FIXME: remove the below error constraint by + * implementing the wprotect tracking mode. + */ + ret = -EINVAL; + goto out; + } + + ret = validate_range(mm, uffdio_register.range.start, + uffdio_register.range.len); + if (ret) + goto out; + + start = uffdio_register.range.start; + end = start + uffdio_register.range.len; + + ret = -ENOMEM; + if (!mmget_not_zero(mm)) + goto out; + + down_write(&mm->mmap_sem); + vma = find_vma_prev(mm, start, &prev); + if (!vma) + goto out_unlock; + + /* check that there's at least one vma in the range */ + ret = -EINVAL; + if (vma->vm_start >= end) + goto out_unlock; + + /* + * If the first vma contains huge pages, make sure start address + * is aligned to huge page size. + */ + if (is_vm_hugetlb_page(vma)) { + unsigned long vma_hpagesize = vma_kernel_pagesize(vma); + + if (start & (vma_hpagesize - 1)) + goto out_unlock; + } + + /* + * Search for not compatible vmas. + */ + found = false; + basic_ioctls = false; + for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) { + cond_resched(); + + BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^ + !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP))); + + /* check not compatible vmas */ + ret = -EINVAL; + if (!vma_can_userfault(cur)) + goto out_unlock; + + /* + * UFFDIO_COPY will fill file holes even without + * PROT_WRITE. This check enforces that if this is a + * MAP_SHARED, the process has write permission to the backing + * file. If VM_MAYWRITE is set it also enforces that on a + * MAP_SHARED vma: there is no F_WRITE_SEAL and no further + * F_WRITE_SEAL can be taken until the vma is destroyed. + */ + ret = -EPERM; + if (unlikely(!(cur->vm_flags & VM_MAYWRITE))) + goto out_unlock; + + /* + * If this vma contains ending address, and huge pages + * check alignment. + */ + if (is_vm_hugetlb_page(cur) && end <= cur->vm_end && + end > cur->vm_start) { + unsigned long vma_hpagesize = vma_kernel_pagesize(cur); + + ret = -EINVAL; + + if (end & (vma_hpagesize - 1)) + goto out_unlock; + } + + /* + * Check that this vma isn't already owned by a + * different userfaultfd. We can't allow more than one + * userfaultfd to own a single vma simultaneously or we + * wouldn't know which one to deliver the userfaults to. + */ + ret = -EBUSY; + if (cur->vm_userfaultfd_ctx.ctx && + cur->vm_userfaultfd_ctx.ctx != ctx) + goto out_unlock; + + /* + * Note vmas containing huge pages + */ + if (is_vm_hugetlb_page(cur)) + basic_ioctls = true; + + found = true; + } + BUG_ON(!found); + + if (vma->vm_start < start) + prev = vma; + + ret = 0; + do { + cond_resched(); + + BUG_ON(!vma_can_userfault(vma)); + BUG_ON(vma->vm_userfaultfd_ctx.ctx && + vma->vm_userfaultfd_ctx.ctx != ctx); + WARN_ON(!(vma->vm_flags & VM_MAYWRITE)); + + /* + * Nothing to do: this vma is already registered into this + * userfaultfd and with the right tracking mode too. + */ + if (vma->vm_userfaultfd_ctx.ctx == ctx && + (vma->vm_flags & vm_flags) == vm_flags) + goto skip; + + if (vma->vm_start > start) + start = vma->vm_start; + vma_end = min(end, vma->vm_end); + + new_flags = (vma->vm_flags & ~vm_flags) | vm_flags; + prev = vma_merge(mm, prev, start, vma_end, new_flags, + vma->anon_vma, vma->vm_file, vma->vm_pgoff, + vma_policy(vma), + ((struct vm_userfaultfd_ctx){ ctx })); + if (prev) { + vma = prev; + goto next; + } + if (vma->vm_start < start) { + ret = split_vma(mm, vma, start, 1); + if (ret) + break; + } + if (vma->vm_end > end) { + ret = split_vma(mm, vma, end, 0); + if (ret) + break; + } + next: + /* + * In the vma_merge() successful mprotect-like case 8: + * the next vma was merged into the current one and + * the current one has not been updated yet. + */ + vma->vm_flags = new_flags; + vma->vm_userfaultfd_ctx.ctx = ctx; + + skip: + prev = vma; + start = vma->vm_end; + vma = vma->vm_next; + } while (vma && vma->vm_start < end); +out_unlock: + up_write(&mm->mmap_sem); + mmput(mm); + if (!ret) { + /* + * Now that we scanned all vmas we can already tell + * userland which ioctls methods are guaranteed to + * succeed on this range. + */ + if (put_user(basic_ioctls ? UFFD_API_RANGE_IOCTLS_BASIC : + UFFD_API_RANGE_IOCTLS, + &user_uffdio_register->ioctls)) + ret = -EFAULT; + } +out: + return ret; +} +",1,"static int userfaultfd_register(struct userfaultfd_ctx *ctx, + unsigned long arg) +{ + struct mm_struct *mm = ctx->mm; + struct vm_area_struct *vma, *prev, *cur; + int ret; + struct uffdio_register uffdio_register; + struct uffdio_register __user *user_uffdio_register; + unsigned long vm_flags, new_flags; + bool found; + bool basic_ioctls; + unsigned long start, end, vma_end; + + user_uffdio_register = (struct uffdio_register __user *) arg; + + ret = -EFAULT; + if (copy_from_user(&uffdio_register, user_uffdio_register, + sizeof(uffdio_register)-sizeof(__u64))) + goto out; + + ret = -EINVAL; + if (!uffdio_register.mode) + goto out; + if (uffdio_register.mode & ~(UFFDIO_REGISTER_MODE_MISSING| + UFFDIO_REGISTER_MODE_WP)) + goto out; + vm_flags = 0; + if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING) + vm_flags |= VM_UFFD_MISSING; + if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) { + vm_flags |= VM_UFFD_WP; + /* + * FIXME: remove the below error constraint by + * implementing the wprotect tracking mode. + */ + ret = -EINVAL; + goto out; + } + + ret = validate_range(mm, uffdio_register.range.start, + uffdio_register.range.len); + if (ret) + goto out; + + start = uffdio_register.range.start; + end = start + uffdio_register.range.len; + + ret = -ENOMEM; + if (!mmget_not_zero(mm)) + goto out; + + down_write(&mm->mmap_sem); + if (!mmget_still_valid(mm)) + goto out_unlock; + vma = find_vma_prev(mm, start, &prev); + if (!vma) + goto out_unlock; + + /* check that there's at least one vma in the range */ + ret = -EINVAL; + if (vma->vm_start >= end) + goto out_unlock; + + /* + * If the first vma contains huge pages, make sure start address + * is aligned to huge page size. + */ + if (is_vm_hugetlb_page(vma)) { + unsigned long vma_hpagesize = vma_kernel_pagesize(vma); + + if (start & (vma_hpagesize - 1)) + goto out_unlock; + } + + /* + * Search for not compatible vmas. + */ + found = false; + basic_ioctls = false; + for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) { + cond_resched(); + + BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^ + !!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP))); + + /* check not compatible vmas */ + ret = -EINVAL; + if (!vma_can_userfault(cur)) + goto out_unlock; + + /* + * UFFDIO_COPY will fill file holes even without + * PROT_WRITE. This check enforces that if this is a + * MAP_SHARED, the process has write permission to the backing + * file. If VM_MAYWRITE is set it also enforces that on a + * MAP_SHARED vma: there is no F_WRITE_SEAL and no further + * F_WRITE_SEAL can be taken until the vma is destroyed. + */ + ret = -EPERM; + if (unlikely(!(cur->vm_flags & VM_MAYWRITE))) + goto out_unlock; + + /* + * If this vma contains ending address, and huge pages + * check alignment. + */ + if (is_vm_hugetlb_page(cur) && end <= cur->vm_end && + end > cur->vm_start) { + unsigned long vma_hpagesize = vma_kernel_pagesize(cur); + + ret = -EINVAL; + + if (end & (vma_hpagesize - 1)) + goto out_unlock; + } + + /* + * Check that this vma isn't already owned by a + * different userfaultfd. We can't allow more than one + * userfaultfd to own a single vma simultaneously or we + * wouldn't know which one to deliver the userfaults to. + */ + ret = -EBUSY; + if (cur->vm_userfaultfd_ctx.ctx && + cur->vm_userfaultfd_ctx.ctx != ctx) + goto out_unlock; + + /* + * Note vmas containing huge pages + */ + if (is_vm_hugetlb_page(cur)) + basic_ioctls = true; + + found = true; + } + BUG_ON(!found); + + if (vma->vm_start < start) + prev = vma; + + ret = 0; + do { + cond_resched(); + + BUG_ON(!vma_can_userfault(vma)); + BUG_ON(vma->vm_userfaultfd_ctx.ctx && + vma->vm_userfaultfd_ctx.ctx != ctx); + WARN_ON(!(vma->vm_flags & VM_MAYWRITE)); + + /* + * Nothing to do: this vma is already registered into this + * userfaultfd and with the right tracking mode too. + */ + if (vma->vm_userfaultfd_ctx.ctx == ctx && + (vma->vm_flags & vm_flags) == vm_flags) + goto skip; + + if (vma->vm_start > start) + start = vma->vm_start; + vma_end = min(end, vma->vm_end); + + new_flags = (vma->vm_flags & ~vm_flags) | vm_flags; + prev = vma_merge(mm, prev, start, vma_end, new_flags, + vma->anon_vma, vma->vm_file, vma->vm_pgoff, + vma_policy(vma), + ((struct vm_userfaultfd_ctx){ ctx })); + if (prev) { + vma = prev; + goto next; + } + if (vma->vm_start < start) { + ret = split_vma(mm, vma, start, 1); + if (ret) + break; + } + if (vma->vm_end > end) { + ret = split_vma(mm, vma, end, 0); + if (ret) + break; + } + next: + /* + * In the vma_merge() successful mprotect-like case 8: + * the next vma was merged into the current one and + * the current one has not been updated yet. + */ + vma->vm_flags = new_flags; + vma->vm_userfaultfd_ctx.ctx = ctx; + + skip: + prev = vma; + start = vma->vm_end; + vma = vma->vm_next; + } while (vma && vma->vm_start < end); +out_unlock: + up_write(&mm->mmap_sem); + mmput(mm); + if (!ret) { + /* + * Now that we scanned all vmas we can already tell + * userland which ioctls methods are guaranteed to + * succeed on this range. + */ + if (put_user(basic_ioctls ? UFFD_API_RANGE_IOCTLS_BASIC : + UFFD_API_RANGE_IOCTLS, + &user_uffdio_register->ioctls)) + ret = -EFAULT; + } +out: + return ret; +} +","@@ -629,6 +629,8 @@ static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx, + + /* the various vma->vm_userfaultfd_ctx still points to it */ + down_write(&mm->mmap_sem); ++ /* no task can run (and in turn coredump) yet */ ++ VM_WARN_ON(!mmget_still_valid(mm)); + for (vma = mm->mmap; vma; vma = vma->vm_next) + if (vma->vm_userfaultfd_ctx.ctx == release_new_ctx) { + vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX; +@@ -883,6 +885,8 @@ static int userfaultfd_release(struct inode *inode, struct file *file) + * taking the mmap_sem for writing. + */ + down_write(&mm->mmap_sem); ++ if (!mmget_still_valid(mm)) ++ goto skip_mm; + prev = NULL; + for (vma = mm->mmap; vma; vma = vma->vm_next) { + cond_resched(); +@@ -905,6 +909,7 @@ static int userfaultfd_release(struct inode *inode, struct file *file) + vma->vm_flags = new_flags; + vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX; + } ++skip_mm: + up_write(&mm->mmap_sem); + mmput(mm); + wakeup: +@@ -1333,6 +1338,8 @@ static int userfaultfd_register(struct userfaultfd_ctx *ctx, + goto out; + + down_write(&mm->mmap_sem); ++ if (!mmget_still_valid(mm)) ++ goto out_unlock; + vma = find_vma_prev(mm, start, &prev); + if (!vma) + goto out_unlock; +@@ -1520,6 +1527,8 @@ static int userfaultfd_unregister(struct userfaultfd_ctx *ctx, + goto out; + + down_write(&mm->mmap_sem); ++ if (!mmget_still_valid(mm)) ++ goto out_unlock; + vma = find_vma_prev(mm, start, &prev); + if (!vma) + goto out_unlock;",1593,1924,2048 +372,"int main(int argc, char *argv[]) +{ + BN_CTX *ctx; + BIO *out; + char *outfile = NULL; + + results = 0; + + RAND_seed(rnd_seed, sizeof rnd_seed); /* or BN_generate_prime may fail */ + + argc--; + argv++; + while (argc >= 1) { + if (strcmp(*argv, ""-results"") == 0) + results = 1; + else if (strcmp(*argv, ""-out"") == 0) { + if (--argc < 1) + break; + outfile = *(++argv); + } + argc--; + argv++; + } + + ctx = BN_CTX_new(); + if (ctx == NULL) + EXIT(1); + + out = BIO_new(BIO_s_file()); + if (out == NULL) + EXIT(1); + if (outfile == NULL) { + BIO_set_fp(out, stdout, BIO_NOCLOSE); + } else { + if (!BIO_write_filename(out, outfile)) { + perror(outfile); + EXIT(1); + } + } + + if (!results) + BIO_puts(out, ""obase=16\nibase=16\n""); + + message(out, ""BN_add""); + if (!test_add(out)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_sub""); + if (!test_sub(out)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_lshift1""); + if (!test_lshift1(out)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_lshift (fixed)""); + if (!test_lshift(out, ctx, BN_bin2bn(lst, sizeof(lst) - 1, NULL))) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_lshift""); + if (!test_lshift(out, ctx, NULL)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_rshift1""); + if (!test_rshift1(out)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_rshift""); + if (!test_rshift(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_sqr""); + if (!test_sqr(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_mul""); + if (!test_mul(out)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_div""); + if (!test_div(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_div_word""); + if (!test_div_word(out)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_div_recp""); + if (!test_div_recp(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_mod""); + if (!test_mod(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_mod_mul""); + if (!test_mod_mul(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_mont""); + if (!test_mont(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_mod_exp""); + if (!test_mod_exp(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_mod_exp_mont_consttime""); + if (!test_mod_exp_mont_consttime(out, ctx)) + goto err; + if (!test_mod_exp_mont5(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_exp""); + if (!test_exp(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_kronecker""); + if (!test_kron(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_mod_sqrt""); + if (!test_sqrt(out, ctx)) + goto err; + (void)BIO_flush(out); +#ifndef OPENSSL_NO_EC2M + message(out, ""BN_GF2m_add""); + if (!test_gf2m_add(out)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_GF2m_mod""); + if (!test_gf2m_mod(out)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_GF2m_mod_mul""); + if (!test_gf2m_mod_mul(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_GF2m_mod_sqr""); + if (!test_gf2m_mod_sqr(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_GF2m_mod_inv""); + if (!test_gf2m_mod_inv(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_GF2m_mod_div""); + if (!test_gf2m_mod_div(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_GF2m_mod_exp""); + if (!test_gf2m_mod_exp(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_GF2m_mod_sqrt""); + if (!test_gf2m_mod_sqrt(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_GF2m_mod_solve_quad""); + if (!test_gf2m_mod_solve_quad(out, ctx)) + goto err; + (void)BIO_flush(out); +#endif + BN_CTX_free(ctx); + BIO_free(out); + + EXIT(0); + err: + BIO_puts(out, ""1\n""); /* make sure the Perl script fed by bc + * notices the failure, see test_bn in + * test/Makefile.ssl */ + (void)BIO_flush(out); + ERR_load_crypto_strings(); + ERR_print_errors_fp(stderr); + EXIT(1); + return (1); +} +",0,"int main(int argc, char *argv[]) +{ + BN_CTX *ctx; + BIO *out; + char *outfile = NULL; + + results = 0; + + RAND_seed(rnd_seed, sizeof rnd_seed); /* or BN_generate_prime may fail */ + + argc--; + argv++; + while (argc >= 1) { + if (strcmp(*argv, ""-results"") == 0) + results = 1; + else if (strcmp(*argv, ""-out"") == 0) { + if (--argc < 1) + break; + outfile = *(++argv); + } + argc--; + argv++; + } + + ctx = BN_CTX_new(); + if (ctx == NULL) + EXIT(1); + + out = BIO_new(BIO_s_file()); + if (out == NULL) + EXIT(1); + if (outfile == NULL) { + BIO_set_fp(out, stdout, BIO_NOCLOSE); + } else { + if (!BIO_write_filename(out, outfile)) { + perror(outfile); + EXIT(1); + } + } + + if (!results) + BIO_puts(out, ""obase=16\nibase=16\n""); + + message(out, ""BN_add""); + if (!test_add(out)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_sub""); + if (!test_sub(out)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_lshift1""); + if (!test_lshift1(out)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_lshift (fixed)""); + if (!test_lshift(out, ctx, BN_bin2bn(lst, sizeof(lst) - 1, NULL))) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_lshift""); + if (!test_lshift(out, ctx, NULL)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_rshift1""); + if (!test_rshift1(out)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_rshift""); + if (!test_rshift(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_sqr""); + if (!test_sqr(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_mul""); + if (!test_mul(out)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_div""); + if (!test_div(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_div_word""); + if (!test_div_word(out)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_div_recp""); + if (!test_div_recp(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_mod""); + if (!test_mod(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_mod_mul""); + if (!test_mod_mul(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_mont""); + if (!test_mont(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_mod_exp""); + if (!test_mod_exp(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_mod_exp_mont_consttime""); + if (!test_mod_exp_mont_consttime(out, ctx)) + goto err; + if (!test_mod_exp_mont5(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_exp""); + if (!test_exp(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_kronecker""); + if (!test_kron(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_mod_sqrt""); + if (!test_sqrt(out, ctx)) + goto err; + (void)BIO_flush(out); +#ifndef OPENSSL_NO_EC2M + message(out, ""BN_GF2m_add""); + if (!test_gf2m_add(out)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_GF2m_mod""); + if (!test_gf2m_mod(out)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_GF2m_mod_mul""); + if (!test_gf2m_mod_mul(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_GF2m_mod_sqr""); + if (!test_gf2m_mod_sqr(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_GF2m_mod_inv""); + if (!test_gf2m_mod_inv(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_GF2m_mod_div""); + if (!test_gf2m_mod_div(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_GF2m_mod_exp""); + if (!test_gf2m_mod_exp(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_GF2m_mod_sqrt""); + if (!test_gf2m_mod_sqrt(out, ctx)) + goto err; + (void)BIO_flush(out); + + message(out, ""BN_GF2m_mod_solve_quad""); + if (!test_gf2m_mod_solve_quad(out, ctx)) + goto err; + (void)BIO_flush(out); +#endif + BN_CTX_free(ctx); + BIO_free(out); + + EXIT(0); + err: + BIO_puts(out, ""1\n""); /* make sure the Perl script fed by bc + * notices the failure, see test_bn in + * test/Makefile.ssl */ + (void)BIO_flush(out); + ERR_load_crypto_strings(); + ERR_print_errors_fp(stderr); + EXIT(1); + return (1); +} +","@@ -1016,6 +1016,24 @@ int test_mod_exp(BIO *bp, BN_CTX *ctx) + return 0; + } + } ++ ++ /* Regression test for carry propagation bug in sqr8x_reduction */ ++ BN_hex2bn(&a, ""050505050505""); ++ BN_hex2bn(&b, ""02""); ++ BN_hex2bn(&c, ++ ""4141414141414141414141274141414141414141414141414141414141414141"" ++ ""4141414141414141414141414141414141414141414141414141414141414141"" ++ ""4141414141414141414141800000000000000000000000000000000000000000"" ++ ""0000000000000000000000000000000000000000000000000000000000000000"" ++ ""0000000000000000000000000000000000000000000000000000000000000000"" ++ ""0000000000000000000000000000000000000000000000000000000001""); ++ BN_mod_exp(d, a, b, c, ctx); ++ BN_mul(e, a, a, ctx); ++ if (BN_cmp(d, e)) { ++ fprintf(stderr, ""BN_mod_exp and BN_mul produce different results!\n""); ++ return 0; ++ } ++ + BN_free(a); + BN_free(b); + BN_free(c);",1360,1691,2048 +841,"void Gfx::doFunctionShFill1(GfxFunctionShading *shading, + double x0, double y0, + double x1, double y1, + GfxColor *colors, int depth) { + GfxColor fillColor; + GfxColor color0M, color1M, colorM0, colorM1, colorMM; + GfxColor colors2[4]; + double *matrix; + double xM, yM; + int nComps, i, j; + + nComps = shading->getColorSpace()->getNComps(); + matrix = shading->getMatrix(); + + for (i = 0; i < 4; ++i) { + for (j = 0; j < nComps; ++j) { + if (abs(colors[i].c[j] - colors[(i+1)&3].c[j]) > functionColorDelta) { + break; + } + } + if (j < nComps) { + break; + } + } + + xM = 0.5 * (x0 + x1); + yM = 0.5 * (y0 + y1); + + if ((i == 4 && depth > 0) || depth == functionMaxDepth) { + + shading->getColor(xM, yM, &fillColor); + state->setFillColor(&fillColor); + out->updateFillColor(state); + + state->moveTo(x0 * matrix[0] + y0 * matrix[2] + matrix[4], + x0 * matrix[1] + y0 * matrix[3] + matrix[5]); + state->lineTo(x1 * matrix[0] + y0 * matrix[2] + matrix[4], + x1 * matrix[1] + y0 * matrix[3] + matrix[5]); + state->lineTo(x1 * matrix[0] + y1 * matrix[2] + matrix[4], + x1 * matrix[1] + y1 * matrix[3] + matrix[5]); + state->lineTo(x0 * matrix[0] + y1 * matrix[2] + matrix[4], + x0 * matrix[1] + y1 * matrix[3] + matrix[5]); + state->closePath(); + if (!contentIsHidden()) + out->fill(state); + state->clearPath(); + + } else { + + + shading->getColor(x0, yM, &color0M); + shading->getColor(x1, yM, &color1M); + shading->getColor(xM, y0, &colorM0); + shading->getColor(xM, y1, &colorM1); + shading->getColor(xM, yM, &colorMM); + + colors2[0] = colors[0]; + colors2[1] = color0M; + colors2[2] = colorM0; + colors2[3] = colorMM; + doFunctionShFill1(shading, x0, y0, xM, yM, colors2, depth + 1); + + colors2[0] = color0M; + colors2[1] = colors[1]; + colors2[2] = colorMM; + colors2[3] = colorM1; + doFunctionShFill1(shading, x0, yM, xM, y1, colors2, depth + 1); + + colors2[0] = colorM0; + colors2[1] = colorMM; + colors2[2] = colors[2]; + colors2[3] = color1M; + doFunctionShFill1(shading, xM, y0, x1, yM, colors2, depth + 1); + + colors2[0] = colorMM; + colors2[1] = colorM1; + colors2[2] = color1M; + colors2[3] = colors[3]; + doFunctionShFill1(shading, xM, yM, x1, y1, colors2, depth + 1); + } +} +",0,"void Gfx::doFunctionShFill1(GfxFunctionShading *shading, + double x0, double y0, + double x1, double y1, + GfxColor *colors, int depth) { + GfxColor fillColor; + GfxColor color0M, color1M, colorM0, colorM1, colorMM; + GfxColor colors2[4]; + double *matrix; + double xM, yM; + int nComps, i, j; + + nComps = shading->getColorSpace()->getNComps(); + matrix = shading->getMatrix(); + + for (i = 0; i < 4; ++i) { + for (j = 0; j < nComps; ++j) { + if (abs(colors[i].c[j] - colors[(i+1)&3].c[j]) > functionColorDelta) { + break; + } + } + if (j < nComps) { + break; + } + } + + xM = 0.5 * (x0 + x1); + yM = 0.5 * (y0 + y1); + + if ((i == 4 && depth > 0) || depth == functionMaxDepth) { + + shading->getColor(xM, yM, &fillColor); + state->setFillColor(&fillColor); + out->updateFillColor(state); + + state->moveTo(x0 * matrix[0] + y0 * matrix[2] + matrix[4], + x0 * matrix[1] + y0 * matrix[3] + matrix[5]); + state->lineTo(x1 * matrix[0] + y0 * matrix[2] + matrix[4], + x1 * matrix[1] + y0 * matrix[3] + matrix[5]); + state->lineTo(x1 * matrix[0] + y1 * matrix[2] + matrix[4], + x1 * matrix[1] + y1 * matrix[3] + matrix[5]); + state->lineTo(x0 * matrix[0] + y1 * matrix[2] + matrix[4], + x0 * matrix[1] + y1 * matrix[3] + matrix[5]); + state->closePath(); + if (!contentIsHidden()) + out->fill(state); + state->clearPath(); + + } else { + + + shading->getColor(x0, yM, &color0M); + shading->getColor(x1, yM, &color1M); + shading->getColor(xM, y0, &colorM0); + shading->getColor(xM, y1, &colorM1); + shading->getColor(xM, yM, &colorMM); + + colors2[0] = colors[0]; + colors2[1] = color0M; + colors2[2] = colorM0; + colors2[3] = colorMM; + doFunctionShFill1(shading, x0, y0, xM, yM, colors2, depth + 1); + + colors2[0] = color0M; + colors2[1] = colors[1]; + colors2[2] = colorMM; + colors2[3] = colorM1; + doFunctionShFill1(shading, x0, yM, xM, y1, colors2, depth + 1); + + colors2[0] = colorM0; + colors2[1] = colorMM; + colors2[2] = colors[2]; + colors2[3] = color1M; + doFunctionShFill1(shading, xM, y0, x1, yM, colors2, depth + 1); + + colors2[0] = colorMM; + colors2[1] = colorM1; + colors2[2] = color1M; + colors2[3] = colors[3]; + doFunctionShFill1(shading, xM, yM, x1, y1, colors2, depth + 1); + } +} +","@@ -536,6 +536,7 @@ Gfx::Gfx(XRef *xrefA, OutputDev *outA, int pageNum, Dict *resDict, Catalog *cata + drawText = gFalse; + maskHaveCSPattern = gFalse; + mcStack = NULL; ++ parser = NULL; + + // start the resource stack + res = new GfxResources(xref, resDict, NULL); +@@ -590,6 +591,7 @@ Gfx::Gfx(XRef *xrefA, OutputDev *outA, Dict *resDict, Catalog *catalogA, + drawText = gFalse; + maskHaveCSPattern = gFalse; + mcStack = NULL; ++ parser = NULL; + + // start the resource stack + res = new GfxResources(xref, resDict, NULL);",881,1212,2048 +5601,"init_WinZip_AES_decryption(struct archive_read *a) +{ + struct zip *zip = (struct zip *)(a->format->data); + const void *p; + const uint8_t *pv; + size_t key_len, salt_len; + uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE]; + int retry; + int r; + + if (zip->cctx_valid || zip->hctx_valid) + return (ARCHIVE_OK); + + switch (zip->entry->aes_extra.strength) { + case 1: salt_len = 8; key_len = 16; break; + case 2: salt_len = 12; key_len = 24; break; + case 3: salt_len = 16; key_len = 32; break; + default: goto corrupted; + } + p = __archive_read_ahead(a, salt_len + 2, NULL); + if (p == NULL) + goto truncated; + + for (retry = 0;; retry++) { + const char *passphrase; + + passphrase = __archive_read_next_passphrase(a); + if (passphrase == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + (retry > 0)? + ""Incorrect passphrase"": + ""Passphrase required for this entry""); + return (ARCHIVE_FAILED); + } + memset(derived_key, 0, sizeof(derived_key)); + r = archive_pbkdf2_sha1(passphrase, strlen(passphrase), + p, salt_len, 1000, derived_key, key_len * 2 + 2); + if (r != 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + ""Decryption is unsupported due to lack of "" + ""crypto library""); + return (ARCHIVE_FAILED); + } + + /* Check password verification value. */ + pv = ((const uint8_t *)p) + salt_len; + if (derived_key[key_len * 2] == pv[0] && + derived_key[key_len * 2 + 1] == pv[1]) + break;/* The passphrase is OK. */ + if (retry > 10000) { + /* Avoid infinity loop. */ + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + ""Too many incorrect passphrases""); + return (ARCHIVE_FAILED); + } + } + + r = archive_decrypto_aes_ctr_init(&zip->cctx, derived_key, key_len); + if (r != 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + ""Decryption is unsupported due to lack of crypto library""); + return (ARCHIVE_FAILED); + } + r = archive_hmac_sha1_init(&zip->hctx, derived_key + key_len, key_len); + if (r != 0) { + archive_decrypto_aes_ctr_release(&zip->cctx); + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + ""Failed to initialize HMAC-SHA1""); + return (ARCHIVE_FAILED); + } + zip->cctx_valid = zip->hctx_valid = 1; + __archive_read_consume(a, salt_len + 2); + zip->entry_bytes_remaining -= salt_len + 2 + AUTH_CODE_SIZE; + if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END) + && zip->entry_bytes_remaining < 0) + goto corrupted; + zip->entry_compressed_bytes_read += salt_len + 2 + AUTH_CODE_SIZE; + zip->decrypted_bytes_remaining = 0; + + zip->entry->compression = zip->entry->aes_extra.compression; + return (zip_alloc_decryption_buffer(a)); + +truncated: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + ""Truncated ZIP file data""); + return (ARCHIVE_FATAL); +corrupted: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + ""Corrupted ZIP file data""); + return (ARCHIVE_FATAL); +} +",0,"init_WinZip_AES_decryption(struct archive_read *a) +{ + struct zip *zip = (struct zip *)(a->format->data); + const void *p; + const uint8_t *pv; + size_t key_len, salt_len; + uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE]; + int retry; + int r; + + if (zip->cctx_valid || zip->hctx_valid) + return (ARCHIVE_OK); + + switch (zip->entry->aes_extra.strength) { + case 1: salt_len = 8; key_len = 16; break; + case 2: salt_len = 12; key_len = 24; break; + case 3: salt_len = 16; key_len = 32; break; + default: goto corrupted; + } + p = __archive_read_ahead(a, salt_len + 2, NULL); + if (p == NULL) + goto truncated; + + for (retry = 0;; retry++) { + const char *passphrase; + + passphrase = __archive_read_next_passphrase(a); + if (passphrase == NULL) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + (retry > 0)? + ""Incorrect passphrase"": + ""Passphrase required for this entry""); + return (ARCHIVE_FAILED); + } + memset(derived_key, 0, sizeof(derived_key)); + r = archive_pbkdf2_sha1(passphrase, strlen(passphrase), + p, salt_len, 1000, derived_key, key_len * 2 + 2); + if (r != 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + ""Decryption is unsupported due to lack of "" + ""crypto library""); + return (ARCHIVE_FAILED); + } + + /* Check password verification value. */ + pv = ((const uint8_t *)p) + salt_len; + if (derived_key[key_len * 2] == pv[0] && + derived_key[key_len * 2 + 1] == pv[1]) + break;/* The passphrase is OK. */ + if (retry > 10000) { + /* Avoid infinity loop. */ + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + ""Too many incorrect passphrases""); + return (ARCHIVE_FAILED); + } + } + + r = archive_decrypto_aes_ctr_init(&zip->cctx, derived_key, key_len); + if (r != 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + ""Decryption is unsupported due to lack of crypto library""); + return (ARCHIVE_FAILED); + } + r = archive_hmac_sha1_init(&zip->hctx, derived_key + key_len, key_len); + if (r != 0) { + archive_decrypto_aes_ctr_release(&zip->cctx); + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + ""Failed to initialize HMAC-SHA1""); + return (ARCHIVE_FAILED); + } + zip->cctx_valid = zip->hctx_valid = 1; + __archive_read_consume(a, salt_len + 2); + zip->entry_bytes_remaining -= salt_len + 2 + AUTH_CODE_SIZE; + if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END) + && zip->entry_bytes_remaining < 0) + goto corrupted; + zip->entry_compressed_bytes_read += salt_len + 2 + AUTH_CODE_SIZE; + zip->decrypted_bytes_remaining = 0; + + zip->entry->compression = zip->entry->aes_extra.compression; + return (zip_alloc_decryption_buffer(a)); + +truncated: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + ""Truncated ZIP file data""); + return (ARCHIVE_FATAL); +corrupted: + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + ""Corrupted ZIP file data""); + return (ARCHIVE_FATAL); +} +","@@ -2778,6 +2778,11 @@ zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry, + + switch(rsrc->compression) { + case 0: /* No compression. */ ++ if (rsrc->uncompressed_size != rsrc->compressed_size) { ++ archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, ++ ""Malformed OS X metadata entry: inconsistent size""); ++ return (ARCHIVE_FATAL); ++ } + #ifdef HAVE_ZLIB_H + case 8: /* Deflate compression. */ + #endif +@@ -2798,6 +2803,12 @@ zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry, + (intmax_t)rsrc->uncompressed_size); + return (ARCHIVE_WARN); + } ++ if (rsrc->compressed_size > (4 * 1024 * 1024)) { ++ archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, ++ ""Mac metadata is too large: %jd > 4M bytes"", ++ (intmax_t)rsrc->compressed_size); ++ return (ARCHIVE_WARN); ++ } + + metadata = malloc((size_t)rsrc->uncompressed_size); + if (metadata == NULL) { +@@ -2836,6 +2847,8 @@ zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry, + bytes_avail = remaining_bytes; + switch(rsrc->compression) { + case 0: /* No compression. */ ++ if ((size_t)bytes_avail > metadata_bytes) ++ bytes_avail = metadata_bytes; + memcpy(mp, p, bytes_avail); + bytes_used = (size_t)bytes_avail; + metadata_bytes -= bytes_used;",861,1192,2048 +7932,"png_inflate_claim(png_structrp png_ptr, png_uint_32 owner) +{ + if (png_ptr->zowner != 0) + { + char msg[64]; + + PNG_STRING_FROM_CHUNK(msg, png_ptr->zowner); + /* So the message that results is "" using zstream""; this is an + * internal error, but is very useful for debugging. i18n requirements + * are minimal. + */ + (void)png_safecat(msg, (sizeof msg), 4, "" using zstream""); +#if PNG_RELEASE_BUILD + png_chunk_warning(png_ptr, msg); + png_ptr->zowner = 0; +#else + png_chunk_error(png_ptr, msg); +#endif + } + + /* Implementation note: unlike 'png_deflate_claim' this internal function + * does not take the size of the data as an argument. Some efficiency could + * be gained by using this when it is known *if* the zlib stream itself does + * not record the number; however, this is an illusion: the original writer + * of the PNG may have selected a lower window size, and we really must + * follow that because, for systems with with limited capabilities, we + * would otherwise reject the application's attempts to use a smaller window + * size (zlib doesn't have an interface to say ""this or lower""!). + * + * inflateReset2 was added to zlib 1.2.4; before this the window could not be + * reset, therefore it is necessary to always allocate the maximum window + * size with earlier zlibs just in case later compressed chunks need it. + */ + { + int ret; /* zlib return code */ +#if ZLIB_VERNUM >= 0x1240 + int window_bits = 0; + +# if defined(PNG_SET_OPTION_SUPPORTED) && defined(PNG_MAXIMUM_INFLATE_WINDOW) + if (((png_ptr->options >> PNG_MAXIMUM_INFLATE_WINDOW) & 3) == + PNG_OPTION_ON) + { + window_bits = 15; + png_ptr->zstream_start = 0; /* fixed window size */ + } + + else + { + png_ptr->zstream_start = 1; + } +# endif + +#endif /* ZLIB_VERNUM >= 0x1240 */ + + /* Set this for safety, just in case the previous owner left pointers to + * memory allocations. + */ + png_ptr->zstream.next_in = NULL; + png_ptr->zstream.avail_in = 0; + png_ptr->zstream.next_out = NULL; + png_ptr->zstream.avail_out = 0; + + if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0) + { +#if ZLIB_VERNUM >= 0x1240 + ret = inflateReset2(&png_ptr->zstream, window_bits); +#else + ret = inflateReset(&png_ptr->zstream); +#endif + } + + else + { +#if ZLIB_VERNUM >= 0x1240 + ret = inflateInit2(&png_ptr->zstream, window_bits); +#else + ret = inflateInit(&png_ptr->zstream); +#endif + + if (ret == Z_OK) + png_ptr->flags |= PNG_FLAG_ZSTREAM_INITIALIZED; + } + +#if ZLIB_VERNUM >= 0x1290 && \ + defined(PNG_SET_OPTION_SUPPORTED) && defined(PNG_IGNORE_ADLER32) + if (((png_ptr->options >> PNG_IGNORE_ADLER32) & 3) == PNG_OPTION_ON) + /* Turn off validation of the ADLER32 checksum in IDAT chunks */ + ret = inflateValidate(&png_ptr->zstream, 0); +#endif + + if (ret == Z_OK) + png_ptr->zowner = owner; + + else + png_zstream_error(png_ptr, ret); + + return ret; + } + +#ifdef window_bits +# undef window_bits +#endif +} +",0,"png_inflate_claim(png_structrp png_ptr, png_uint_32 owner) +{ + if (png_ptr->zowner != 0) + { + char msg[64]; + + PNG_STRING_FROM_CHUNK(msg, png_ptr->zowner); + /* So the message that results is "" using zstream""; this is an + * internal error, but is very useful for debugging. i18n requirements + * are minimal. + */ + (void)png_safecat(msg, (sizeof msg), 4, "" using zstream""); +#if PNG_RELEASE_BUILD + png_chunk_warning(png_ptr, msg); + png_ptr->zowner = 0; +#else + png_chunk_error(png_ptr, msg); +#endif + } + + /* Implementation note: unlike 'png_deflate_claim' this internal function + * does not take the size of the data as an argument. Some efficiency could + * be gained by using this when it is known *if* the zlib stream itself does + * not record the number; however, this is an illusion: the original writer + * of the PNG may have selected a lower window size, and we really must + * follow that because, for systems with with limited capabilities, we + * would otherwise reject the application's attempts to use a smaller window + * size (zlib doesn't have an interface to say ""this or lower""!). + * + * inflateReset2 was added to zlib 1.2.4; before this the window could not be + * reset, therefore it is necessary to always allocate the maximum window + * size with earlier zlibs just in case later compressed chunks need it. + */ + { + int ret; /* zlib return code */ +#if ZLIB_VERNUM >= 0x1240 + int window_bits = 0; + +# if defined(PNG_SET_OPTION_SUPPORTED) && defined(PNG_MAXIMUM_INFLATE_WINDOW) + if (((png_ptr->options >> PNG_MAXIMUM_INFLATE_WINDOW) & 3) == + PNG_OPTION_ON) + { + window_bits = 15; + png_ptr->zstream_start = 0; /* fixed window size */ + } + + else + { + png_ptr->zstream_start = 1; + } +# endif + +#endif /* ZLIB_VERNUM >= 0x1240 */ + + /* Set this for safety, just in case the previous owner left pointers to + * memory allocations. + */ + png_ptr->zstream.next_in = NULL; + png_ptr->zstream.avail_in = 0; + png_ptr->zstream.next_out = NULL; + png_ptr->zstream.avail_out = 0; + + if ((png_ptr->flags & PNG_FLAG_ZSTREAM_INITIALIZED) != 0) + { +#if ZLIB_VERNUM >= 0x1240 + ret = inflateReset2(&png_ptr->zstream, window_bits); +#else + ret = inflateReset(&png_ptr->zstream); +#endif + } + + else + { +#if ZLIB_VERNUM >= 0x1240 + ret = inflateInit2(&png_ptr->zstream, window_bits); +#else + ret = inflateInit(&png_ptr->zstream); +#endif + + if (ret == Z_OK) + png_ptr->flags |= PNG_FLAG_ZSTREAM_INITIALIZED; + } + +#if ZLIB_VERNUM >= 0x1290 && \ + defined(PNG_SET_OPTION_SUPPORTED) && defined(PNG_IGNORE_ADLER32) + if (((png_ptr->options >> PNG_IGNORE_ADLER32) & 3) == PNG_OPTION_ON) + /* Turn off validation of the ADLER32 checksum in IDAT chunks */ + ret = inflateValidate(&png_ptr->zstream, 0); +#endif + + if (ret == Z_OK) + png_ptr->zowner = owner; + + else + png_zstream_error(png_ptr, ret); + + return ret; + } + +#ifdef window_bits +# undef window_bits +#endif +} +","@@ -3167,10 +3167,13 @@ png_check_chunk_length(png_const_structrp png_ptr, const png_uint_32 length) + { + png_alloc_size_t idat_limit = PNG_UINT_31_MAX; + size_t row_factor = +- (png_ptr->width * png_ptr->channels * (png_ptr->bit_depth > 8? 2: 1) +- + 1 + (png_ptr->interlaced? 6: 0)); ++ (size_t)png_ptr->width ++ * (size_t)png_ptr->channels ++ * (png_ptr->bit_depth > 8? 2: 1) ++ + 1 ++ + (png_ptr->interlaced? 6: 0); + if (png_ptr->height > PNG_UINT_32_MAX/row_factor) +- idat_limit=PNG_UINT_31_MAX; ++ idat_limit = PNG_UINT_31_MAX; + else + idat_limit = png_ptr->height * row_factor; + row_factor = row_factor > 32566? 32566 : row_factor;",862,1193,2048 +1950,"int __udp4_lib_rcv(struct sk_buff *skb, struct udp_table *udptable, + int proto) +{ + struct sock *sk; + struct udphdr *uh; + unsigned short ulen; + struct rtable *rt = skb_rtable(skb); + __be32 saddr, daddr; + struct net *net = dev_net(skb->dev); + + /* + * Validate the packet. + */ + if (!pskb_may_pull(skb, sizeof(struct udphdr))) + goto drop; /* No space for header. */ + + uh = udp_hdr(skb); + ulen = ntohs(uh->len); + saddr = ip_hdr(skb)->saddr; + daddr = ip_hdr(skb)->daddr; + + if (ulen > skb->len) + goto short_packet; + + if (proto == IPPROTO_UDP) { + /* UDP validates ulen. */ + if (ulen < sizeof(*uh) || pskb_trim_rcsum(skb, ulen)) + goto short_packet; + uh = udp_hdr(skb); + } + + if (udp4_csum_init(skb, uh, proto)) + goto csum_error; + + if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST)) + return __udp4_lib_mcast_deliver(net, skb, uh, + saddr, daddr, udptable); + + sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest, udptable); + + if (sk != NULL) { + int ret = udp_queue_rcv_skb(sk, skb); + sock_put(sk); + + /* a return value > 0 means to resubmit the input, but + * it wants the return to be -protocol, or 0 + */ + if (ret > 0) + return -ret; + return 0; + } + + if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) + goto drop; + nf_reset(skb); + + /* No socket. Drop packet silently, if checksum is wrong */ + if (udp_lib_checksum_complete(skb)) + goto csum_error; + + UDP_INC_STATS_BH(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE); + icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0); + + /* + * Hmm. We got an UDP packet to a port to which we + * don't wanna listen. Ignore it. + */ + kfree_skb(skb); + return 0; + +short_packet: + LIMIT_NETDEBUG(KERN_DEBUG ""UDP%s: short packet: From %pI4:%u %d/%d to %pI4:%u\n"", + proto == IPPROTO_UDPLITE ? ""-Lite"" : """", + &saddr, + ntohs(uh->source), + ulen, + skb->len, + &daddr, + ntohs(uh->dest)); + goto drop; + +csum_error: + /* + * RFC1122: OK. Discards the bad packet silently (as far as + * the network is concerned, anyway) as per 4.1.3.4 (MUST). + */ + LIMIT_NETDEBUG(KERN_DEBUG ""UDP%s: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n"", + proto == IPPROTO_UDPLITE ? ""-Lite"" : """", + &saddr, + ntohs(uh->source), + &daddr, + ntohs(uh->dest), + ulen); +drop: + UDP_INC_STATS_BH(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE); + kfree_skb(skb); + return 0; +} +",0,"int __udp4_lib_rcv(struct sk_buff *skb, struct udp_table *udptable, + int proto) +{ + struct sock *sk; + struct udphdr *uh; + unsigned short ulen; + struct rtable *rt = skb_rtable(skb); + __be32 saddr, daddr; + struct net *net = dev_net(skb->dev); + + /* + * Validate the packet. + */ + if (!pskb_may_pull(skb, sizeof(struct udphdr))) + goto drop; /* No space for header. */ + + uh = udp_hdr(skb); + ulen = ntohs(uh->len); + saddr = ip_hdr(skb)->saddr; + daddr = ip_hdr(skb)->daddr; + + if (ulen > skb->len) + goto short_packet; + + if (proto == IPPROTO_UDP) { + /* UDP validates ulen. */ + if (ulen < sizeof(*uh) || pskb_trim_rcsum(skb, ulen)) + goto short_packet; + uh = udp_hdr(skb); + } + + if (udp4_csum_init(skb, uh, proto)) + goto csum_error; + + if (rt->rt_flags & (RTCF_BROADCAST|RTCF_MULTICAST)) + return __udp4_lib_mcast_deliver(net, skb, uh, + saddr, daddr, udptable); + + sk = __udp4_lib_lookup_skb(skb, uh->source, uh->dest, udptable); + + if (sk != NULL) { + int ret = udp_queue_rcv_skb(sk, skb); + sock_put(sk); + + /* a return value > 0 means to resubmit the input, but + * it wants the return to be -protocol, or 0 + */ + if (ret > 0) + return -ret; + return 0; + } + + if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) + goto drop; + nf_reset(skb); + + /* No socket. Drop packet silently, if checksum is wrong */ + if (udp_lib_checksum_complete(skb)) + goto csum_error; + + UDP_INC_STATS_BH(net, UDP_MIB_NOPORTS, proto == IPPROTO_UDPLITE); + icmp_send(skb, ICMP_DEST_UNREACH, ICMP_PORT_UNREACH, 0); + + /* + * Hmm. We got an UDP packet to a port to which we + * don't wanna listen. Ignore it. + */ + kfree_skb(skb); + return 0; + +short_packet: + LIMIT_NETDEBUG(KERN_DEBUG ""UDP%s: short packet: From %pI4:%u %d/%d to %pI4:%u\n"", + proto == IPPROTO_UDPLITE ? ""-Lite"" : """", + &saddr, + ntohs(uh->source), + ulen, + skb->len, + &daddr, + ntohs(uh->dest)); + goto drop; + +csum_error: + /* + * RFC1122: OK. Discards the bad packet silently (as far as + * the network is concerned, anyway) as per 4.1.3.4 (MUST). + */ + LIMIT_NETDEBUG(KERN_DEBUG ""UDP%s: bad checksum. From %pI4:%u to %pI4:%u ulen %d\n"", + proto == IPPROTO_UDPLITE ? ""-Lite"" : """", + &saddr, + ntohs(uh->source), + &daddr, + ntohs(uh->dest), + ulen); +drop: + UDP_INC_STATS_BH(net, UDP_MIB_INERRORS, proto == IPPROTO_UDPLITE); + kfree_skb(skb); + return 0; +} +","@@ -804,6 +804,7 @@ int udp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, + int corkreq = up->corkflag || msg->msg_flags&MSG_MORE; + int (*getfrag)(void *, char *, int, int, int, struct sk_buff *); + struct sk_buff *skb; ++ struct ip_options_data opt_copy; + + if (len > 0xFFFF) + return -EMSGSIZE; +@@ -877,22 +878,32 @@ int udp_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, + free = 1; + connected = 0; + } +- if (!ipc.opt) +- ipc.opt = inet->opt; ++ if (!ipc.opt) { ++ struct ip_options_rcu *inet_opt; ++ ++ rcu_read_lock(); ++ inet_opt = rcu_dereference(inet->inet_opt); ++ if (inet_opt) { ++ memcpy(&opt_copy, inet_opt, ++ sizeof(*inet_opt) + inet_opt->opt.optlen); ++ ipc.opt = &opt_copy.opt; ++ } ++ rcu_read_unlock(); ++ } + + saddr = ipc.addr; + ipc.addr = faddr = daddr; + +- if (ipc.opt && ipc.opt->srr) { ++ if (ipc.opt && ipc.opt->opt.srr) { + if (!daddr) + return -EINVAL; +- faddr = ipc.opt->faddr; ++ faddr = ipc.opt->opt.faddr; + connected = 0; + } + tos = RT_TOS(inet->tos); + if (sock_flag(sk, SOCK_LOCALROUTE) || + (msg->msg_flags & MSG_DONTROUTE) || +- (ipc.opt && ipc.opt->is_strictroute)) { ++ (ipc.opt && ipc.opt->opt.is_strictroute)) { + tos |= RTO_ONLINK; + connected = 0; + }",767,1098,2048 +18347,"static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe, + struct pipe_inode_info *opipe, + size_t len, unsigned int flags) +{ + struct pipe_buffer *ibuf, *obuf; + int ret = 0, nbuf; + bool input_wakeup = false; + + +retry: + ret = ipipe_prep(ipipe, flags); + if (ret) + return ret; + + ret = opipe_prep(opipe, flags); + if (ret) + return ret; + + /* + * Potential ABBA deadlock, work around it by ordering lock + * grabbing by pipe info address. Otherwise two different processes + * could deadlock (one doing tee from A -> B, the other from B -> A). + */ + pipe_double_lock(ipipe, opipe); + + do { + if (!opipe->readers) { + send_sig(SIGPIPE, current, 0); + if (!ret) + ret = -EPIPE; + break; + } + + if (!ipipe->nrbufs && !ipipe->writers) + break; + + /* + * Cannot make any progress, because either the input + * pipe is empty or the output pipe is full. + */ + if (!ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) { + /* Already processed some buffers, break */ + if (ret) + break; + + if (flags & SPLICE_F_NONBLOCK) { + ret = -EAGAIN; + break; + } + + /* + * We raced with another reader/writer and haven't + * managed to process any buffers. A zero return + * value means EOF, so retry instead. + */ + pipe_unlock(ipipe); + pipe_unlock(opipe); + goto retry; + } + + ibuf = ipipe->bufs + ipipe->curbuf; + nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1); + obuf = opipe->bufs + nbuf; + + if (len >= ibuf->len) { + /* + * Simply move the whole buffer from ipipe to opipe + */ + *obuf = *ibuf; + ibuf->ops = NULL; + opipe->nrbufs++; + ipipe->curbuf = (ipipe->curbuf + 1) & (ipipe->buffers - 1); + ipipe->nrbufs--; + input_wakeup = true; + } else { + /* + * Get a reference to this pipe buffer, + * so we can copy the contents over. + */ + pipe_buf_get(ipipe, ibuf); + *obuf = *ibuf; + + /* + * Don't inherit the gift flag, we need to + * prevent multiple steals of this page. + */ + obuf->flags &= ~PIPE_BUF_FLAG_GIFT; + + pipe_buf_mark_unmergeable(obuf); + + obuf->len = len; + opipe->nrbufs++; + ibuf->offset += obuf->len; + ibuf->len -= obuf->len; + } + ret += obuf->len; + len -= obuf->len; + } while (len); + + pipe_unlock(ipipe); + pipe_unlock(opipe); + + /* + * If we put data in the output pipe, wakeup any potential readers. + */ + if (ret > 0) + wakeup_pipe_readers(opipe); + + if (input_wakeup) + wakeup_pipe_writers(ipipe); + + return ret; +} +",1,"static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe, + struct pipe_inode_info *opipe, + size_t len, unsigned int flags) +{ + struct pipe_buffer *ibuf, *obuf; + int ret = 0, nbuf; + bool input_wakeup = false; + + +retry: + ret = ipipe_prep(ipipe, flags); + if (ret) + return ret; + + ret = opipe_prep(opipe, flags); + if (ret) + return ret; + + /* + * Potential ABBA deadlock, work around it by ordering lock + * grabbing by pipe info address. Otherwise two different processes + * could deadlock (one doing tee from A -> B, the other from B -> A). + */ + pipe_double_lock(ipipe, opipe); + + do { + if (!opipe->readers) { + send_sig(SIGPIPE, current, 0); + if (!ret) + ret = -EPIPE; + break; + } + + if (!ipipe->nrbufs && !ipipe->writers) + break; + + /* + * Cannot make any progress, because either the input + * pipe is empty or the output pipe is full. + */ + if (!ipipe->nrbufs || opipe->nrbufs >= opipe->buffers) { + /* Already processed some buffers, break */ + if (ret) + break; + + if (flags & SPLICE_F_NONBLOCK) { + ret = -EAGAIN; + break; + } + + /* + * We raced with another reader/writer and haven't + * managed to process any buffers. A zero return + * value means EOF, so retry instead. + */ + pipe_unlock(ipipe); + pipe_unlock(opipe); + goto retry; + } + + ibuf = ipipe->bufs + ipipe->curbuf; + nbuf = (opipe->curbuf + opipe->nrbufs) & (opipe->buffers - 1); + obuf = opipe->bufs + nbuf; + + if (len >= ibuf->len) { + /* + * Simply move the whole buffer from ipipe to opipe + */ + *obuf = *ibuf; + ibuf->ops = NULL; + opipe->nrbufs++; + ipipe->curbuf = (ipipe->curbuf + 1) & (ipipe->buffers - 1); + ipipe->nrbufs--; + input_wakeup = true; + } else { + /* + * Get a reference to this pipe buffer, + * so we can copy the contents over. + */ + if (!pipe_buf_get(ipipe, ibuf)) { + if (ret == 0) + ret = -EFAULT; + break; + } + *obuf = *ibuf; + + /* + * Don't inherit the gift flag, we need to + * prevent multiple steals of this page. + */ + obuf->flags &= ~PIPE_BUF_FLAG_GIFT; + + pipe_buf_mark_unmergeable(obuf); + + obuf->len = len; + opipe->nrbufs++; + ibuf->offset += obuf->len; + ibuf->len -= obuf->len; + } + ret += obuf->len; + len -= obuf->len; + } while (len); + + pipe_unlock(ipipe); + pipe_unlock(opipe); + + /* + * If we put data in the output pipe, wakeup any potential readers. + */ + if (ret > 0) + wakeup_pipe_readers(opipe); + + if (input_wakeup) + wakeup_pipe_writers(ipipe); + + return ret; +} +","@@ -1593,7 +1593,11 @@ static int splice_pipe_to_pipe(struct pipe_inode_info *ipipe, + * Get a reference to this pipe buffer, + * so we can copy the contents over. + */ +- pipe_buf_get(ipipe, ibuf); ++ if (!pipe_buf_get(ipipe, ibuf)) { ++ if (ret == 0) ++ ret = -EFAULT; ++ break; ++ } + *obuf = *ibuf; + + /* +@@ -1667,7 +1671,11 @@ static int link_pipe(struct pipe_inode_info *ipipe, + * Get a reference to this pipe buffer, + * so we can copy the contents over. + */ +- pipe_buf_get(ipipe, ibuf); ++ if (!pipe_buf_get(ipipe, ibuf)) { ++ if (ret == 0) ++ ret = -EFAULT; ++ break; ++ } + + obuf = opipe->bufs + nbuf; + *obuf = *ibuf;",766,1097,2048 +5436,"static void cypress_set_termios(struct tty_struct *tty, + struct usb_serial_port *port, struct ktermios *old_termios) +{ + struct cypress_private *priv = usb_get_serial_port_data(port); + struct device *dev = &port->dev; + int data_bits, stop_bits, parity_type, parity_enable; + unsigned cflag, iflag; + unsigned long flags; + __u8 oldlines; + int linechange = 0; + + spin_lock_irqsave(&priv->lock, flags); + /* We can't clean this one up as we don't know the device type + early enough */ + if (!priv->termios_initialized) { + if (priv->chiptype == CT_EARTHMATE) { + tty->termios = tty_std_termios; + tty->termios.c_cflag = B4800 | CS8 | CREAD | HUPCL | + CLOCAL; + tty->termios.c_ispeed = 4800; + tty->termios.c_ospeed = 4800; + } else if (priv->chiptype == CT_CYPHIDCOM) { + tty->termios = tty_std_termios; + tty->termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | + CLOCAL; + tty->termios.c_ispeed = 9600; + tty->termios.c_ospeed = 9600; + } else if (priv->chiptype == CT_CA42V2) { + tty->termios = tty_std_termios; + tty->termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | + CLOCAL; + tty->termios.c_ispeed = 9600; + tty->termios.c_ospeed = 9600; + } + priv->termios_initialized = 1; + } + spin_unlock_irqrestore(&priv->lock, flags); + + /* Unsupported features need clearing */ + tty->termios.c_cflag &= ~(CMSPAR|CRTSCTS); + + cflag = tty->termios.c_cflag; + iflag = tty->termios.c_iflag; + + /* check if there are new settings */ + if (old_termios) { + spin_lock_irqsave(&priv->lock, flags); + priv->tmp_termios = tty->termios; + spin_unlock_irqrestore(&priv->lock, flags); + } + + /* set number of data bits, parity, stop bits */ + /* when parity is disabled the parity type bit is ignored */ + + /* 1 means 2 stop bits, 0 means 1 stop bit */ + stop_bits = cflag & CSTOPB ? 1 : 0; + + if (cflag & PARENB) { + parity_enable = 1; + /* 1 means odd parity, 0 means even parity */ + parity_type = cflag & PARODD ? 1 : 0; + } else + parity_enable = parity_type = 0; + + switch (cflag & CSIZE) { + case CS5: + data_bits = 0; + break; + case CS6: + data_bits = 1; + break; + case CS7: + data_bits = 2; + break; + case CS8: + data_bits = 3; + break; + default: + dev_err(dev, ""%s - CSIZE was set, but not CS5-CS8\n"", __func__); + data_bits = 3; + } + spin_lock_irqsave(&priv->lock, flags); + oldlines = priv->line_control; + if ((cflag & CBAUD) == B0) { + /* drop dtr and rts */ + dev_dbg(dev, ""%s - dropping the lines, baud rate 0bps\n"", __func__); + priv->line_control &= ~(CONTROL_DTR | CONTROL_RTS); + } else + priv->line_control = (CONTROL_DTR | CONTROL_RTS); + spin_unlock_irqrestore(&priv->lock, flags); + + dev_dbg(dev, ""%s - sending %d stop_bits, %d parity_enable, %d parity_type, %d data_bits (+5)\n"", + __func__, stop_bits, parity_enable, parity_type, data_bits); + + cypress_serial_control(tty, port, tty_get_baud_rate(tty), + data_bits, stop_bits, + parity_enable, parity_type, + 0, CYPRESS_SET_CONFIG); + + /* we perform a CYPRESS_GET_CONFIG so that the current settings are + * filled into the private structure this should confirm that all is + * working if it returns what we just set */ + cypress_serial_control(tty, port, 0, 0, 0, 0, 0, 0, CYPRESS_GET_CONFIG); + + /* Here we can define custom tty settings for devices; the main tty + * termios flag base comes from empeg.c */ + + spin_lock_irqsave(&priv->lock, flags); + if (priv->chiptype == CT_EARTHMATE && priv->baud_rate == 4800) { + dev_dbg(dev, ""Using custom termios settings for a baud rate of 4800bps.\n""); + /* define custom termios settings for NMEA protocol */ + + tty->termios.c_iflag /* input modes - */ + &= ~(IGNBRK /* disable ignore break */ + | BRKINT /* disable break causes interrupt */ + | PARMRK /* disable mark parity errors */ + | ISTRIP /* disable clear high bit of input char */ + | INLCR /* disable translate NL to CR */ + | IGNCR /* disable ignore CR */ + | ICRNL /* disable translate CR to NL */ + | IXON); /* disable enable XON/XOFF flow control */ + + tty->termios.c_oflag /* output modes */ + &= ~OPOST; /* disable postprocess output char */ + + tty->termios.c_lflag /* line discipline modes */ + &= ~(ECHO /* disable echo input characters */ + | ECHONL /* disable echo new line */ + | ICANON /* disable erase, kill, werase, and rprnt + special characters */ + | ISIG /* disable interrupt, quit, and suspend + special characters */ + | IEXTEN); /* disable non-POSIX special characters */ + } /* CT_CYPHIDCOM: Application should handle this for device */ + + linechange = (priv->line_control != oldlines); + spin_unlock_irqrestore(&priv->lock, flags); + + /* if necessary, set lines */ + if (linechange) { + priv->cmd_ctrl = 1; + cypress_write(tty, port, NULL, 0); + } +} /* cypress_set_termios */ +",0,"static void cypress_set_termios(struct tty_struct *tty, + struct usb_serial_port *port, struct ktermios *old_termios) +{ + struct cypress_private *priv = usb_get_serial_port_data(port); + struct device *dev = &port->dev; + int data_bits, stop_bits, parity_type, parity_enable; + unsigned cflag, iflag; + unsigned long flags; + __u8 oldlines; + int linechange = 0; + + spin_lock_irqsave(&priv->lock, flags); + /* We can't clean this one up as we don't know the device type + early enough */ + if (!priv->termios_initialized) { + if (priv->chiptype == CT_EARTHMATE) { + tty->termios = tty_std_termios; + tty->termios.c_cflag = B4800 | CS8 | CREAD | HUPCL | + CLOCAL; + tty->termios.c_ispeed = 4800; + tty->termios.c_ospeed = 4800; + } else if (priv->chiptype == CT_CYPHIDCOM) { + tty->termios = tty_std_termios; + tty->termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | + CLOCAL; + tty->termios.c_ispeed = 9600; + tty->termios.c_ospeed = 9600; + } else if (priv->chiptype == CT_CA42V2) { + tty->termios = tty_std_termios; + tty->termios.c_cflag = B9600 | CS8 | CREAD | HUPCL | + CLOCAL; + tty->termios.c_ispeed = 9600; + tty->termios.c_ospeed = 9600; + } + priv->termios_initialized = 1; + } + spin_unlock_irqrestore(&priv->lock, flags); + + /* Unsupported features need clearing */ + tty->termios.c_cflag &= ~(CMSPAR|CRTSCTS); + + cflag = tty->termios.c_cflag; + iflag = tty->termios.c_iflag; + + /* check if there are new settings */ + if (old_termios) { + spin_lock_irqsave(&priv->lock, flags); + priv->tmp_termios = tty->termios; + spin_unlock_irqrestore(&priv->lock, flags); + } + + /* set number of data bits, parity, stop bits */ + /* when parity is disabled the parity type bit is ignored */ + + /* 1 means 2 stop bits, 0 means 1 stop bit */ + stop_bits = cflag & CSTOPB ? 1 : 0; + + if (cflag & PARENB) { + parity_enable = 1; + /* 1 means odd parity, 0 means even parity */ + parity_type = cflag & PARODD ? 1 : 0; + } else + parity_enable = parity_type = 0; + + switch (cflag & CSIZE) { + case CS5: + data_bits = 0; + break; + case CS6: + data_bits = 1; + break; + case CS7: + data_bits = 2; + break; + case CS8: + data_bits = 3; + break; + default: + dev_err(dev, ""%s - CSIZE was set, but not CS5-CS8\n"", __func__); + data_bits = 3; + } + spin_lock_irqsave(&priv->lock, flags); + oldlines = priv->line_control; + if ((cflag & CBAUD) == B0) { + /* drop dtr and rts */ + dev_dbg(dev, ""%s - dropping the lines, baud rate 0bps\n"", __func__); + priv->line_control &= ~(CONTROL_DTR | CONTROL_RTS); + } else + priv->line_control = (CONTROL_DTR | CONTROL_RTS); + spin_unlock_irqrestore(&priv->lock, flags); + + dev_dbg(dev, ""%s - sending %d stop_bits, %d parity_enable, %d parity_type, %d data_bits (+5)\n"", + __func__, stop_bits, parity_enable, parity_type, data_bits); + + cypress_serial_control(tty, port, tty_get_baud_rate(tty), + data_bits, stop_bits, + parity_enable, parity_type, + 0, CYPRESS_SET_CONFIG); + + /* we perform a CYPRESS_GET_CONFIG so that the current settings are + * filled into the private structure this should confirm that all is + * working if it returns what we just set */ + cypress_serial_control(tty, port, 0, 0, 0, 0, 0, 0, CYPRESS_GET_CONFIG); + + /* Here we can define custom tty settings for devices; the main tty + * termios flag base comes from empeg.c */ + + spin_lock_irqsave(&priv->lock, flags); + if (priv->chiptype == CT_EARTHMATE && priv->baud_rate == 4800) { + dev_dbg(dev, ""Using custom termios settings for a baud rate of 4800bps.\n""); + /* define custom termios settings for NMEA protocol */ + + tty->termios.c_iflag /* input modes - */ + &= ~(IGNBRK /* disable ignore break */ + | BRKINT /* disable break causes interrupt */ + | PARMRK /* disable mark parity errors */ + | ISTRIP /* disable clear high bit of input char */ + | INLCR /* disable translate NL to CR */ + | IGNCR /* disable ignore CR */ + | ICRNL /* disable translate CR to NL */ + | IXON); /* disable enable XON/XOFF flow control */ + + tty->termios.c_oflag /* output modes */ + &= ~OPOST; /* disable postprocess output char */ + + tty->termios.c_lflag /* line discipline modes */ + &= ~(ECHO /* disable echo input characters */ + | ECHONL /* disable echo new line */ + | ICANON /* disable erase, kill, werase, and rprnt + special characters */ + | ISIG /* disable interrupt, quit, and suspend + special characters */ + | IEXTEN); /* disable non-POSIX special characters */ + } /* CT_CYPHIDCOM: Application should handle this for device */ + + linechange = (priv->line_control != oldlines); + spin_unlock_irqrestore(&priv->lock, flags); + + /* if necessary, set lines */ + if (linechange) { + priv->cmd_ctrl = 1; + cypress_write(tty, port, NULL, 0); + } +} /* cypress_set_termios */ +","@@ -447,6 +447,11 @@ static int cypress_generic_port_probe(struct usb_serial_port *port) + struct usb_serial *serial = port->serial; + struct cypress_private *priv; + ++ if (!port->interrupt_out_urb || !port->interrupt_in_urb) { ++ dev_err(&port->dev, ""required endpoint is missing\n""); ++ return -ENODEV; ++ } ++ + priv = kzalloc(sizeof(struct cypress_private), GFP_KERNEL); + if (!priv) + return -ENOMEM; +@@ -606,12 +611,6 @@ static int cypress_open(struct tty_struct *tty, struct usb_serial_port *port) + cypress_set_termios(tty, port, &priv->tmp_termios); + + /* setup the port and start reading from the device */ +- if (!port->interrupt_in_urb) { +- dev_err(&port->dev, ""%s - interrupt_in_urb is empty!\n"", +- __func__); +- return -1; +- } +- + usb_fill_int_urb(port->interrupt_in_urb, serial->dev, + usb_rcvintpipe(serial->dev, port->interrupt_in_endpointAddress), + port->interrupt_in_urb->transfer_buffer,",1491,1822,2048 +8908,"tree_min_len(Node* node, ScanEnv* env) +{ + OnigLen len; + OnigLen tmin; + + len = 0; + switch (NODE_TYPE(node)) { + case NODE_BACKREF: + if (! NODE_IS_CHECKER(node)) { + int i; + int* backs; + MemEnv* mem_env = SCANENV_MEMENV(env); + BackRefNode* br = BACKREF_(node); + if (NODE_IS_RECURSION(node)) break; + + backs = BACKREFS_P(br); + len = tree_min_len(mem_env[backs[0]].node, env); + for (i = 1; i < br->back_num; i++) { + tmin = tree_min_len(mem_env[backs[i]].node, env); + if (len > tmin) len = tmin; + } + } + break; + +#ifdef USE_CALL + case NODE_CALL: + { + Node* t = NODE_BODY(node); + if (NODE_IS_RECURSION(node)) { + if (NODE_IS_MIN_FIXED(t)) + len = BAG_(t)->min_len; + } + else + len = tree_min_len(t, env); + } + break; +#endif + + case NODE_LIST: + do { + tmin = tree_min_len(NODE_CAR(node), env); + len = distance_add(len, tmin); + } while (IS_NOT_NULL(node = NODE_CDR(node))); + break; + + case NODE_ALT: + { + Node *x, *y; + y = node; + do { + x = NODE_CAR(y); + tmin = tree_min_len(x, env); + if (y == node) len = tmin; + else if (len > tmin) len = tmin; + } while (IS_NOT_NULL(y = NODE_CDR(y))); + } + break; + + case NODE_STRING: + { + StrNode* sn = STR_(node); + len = (int )(sn->end - sn->s); + } + break; + + case NODE_CTYPE: + case NODE_CCLASS: + len = ONIGENC_MBC_MINLEN(env->enc); + break; + + case NODE_QUANT: + { + QuantNode* qn = QUANT_(node); + + if (qn->lower > 0) { + len = tree_min_len(NODE_BODY(node), env); + len = distance_multiply(len, qn->lower); + } + } + break; + + case NODE_BAG: + { + BagNode* en = BAG_(node); + switch (en->type) { + case BAG_MEMORY: + if (NODE_IS_MIN_FIXED(node)) + len = en->min_len; + else { + if (NODE_IS_MARK1(node)) + len = 0; /* recursive */ + else { + NODE_STATUS_ADD(node, MARK1); + len = tree_min_len(NODE_BODY(node), env); + NODE_STATUS_REMOVE(node, MARK1); + + en->min_len = len; + NODE_STATUS_ADD(node, MIN_FIXED); + } + } + break; + + case BAG_OPTION: + case BAG_STOP_BACKTRACK: + len = tree_min_len(NODE_BODY(node), env); + break; + case BAG_IF_ELSE: + { + OnigLen elen; + + len = tree_min_len(NODE_BODY(node), env); + if (IS_NOT_NULL(en->te.Then)) + len += tree_min_len(en->te.Then, env); + if (IS_NOT_NULL(en->te.Else)) + elen = tree_min_len(en->te.Else, env); + else elen = 0; + + if (elen < len) len = elen; + } + break; + } + } + break; + + case NODE_GIMMICK: + { + GimmickNode* g = GIMMICK_(node); + if (g->type == GIMMICK_FAIL) { + len = INFINITE_LEN; + break; + } + } + /* fall */ + case NODE_ANCHOR: + default: + break; + } + + return len; +} +",0,"tree_min_len(Node* node, ScanEnv* env) +{ + OnigLen len; + OnigLen tmin; + + len = 0; + switch (NODE_TYPE(node)) { + case NODE_BACKREF: + if (! NODE_IS_CHECKER(node)) { + int i; + int* backs; + MemEnv* mem_env = SCANENV_MEMENV(env); + BackRefNode* br = BACKREF_(node); + if (NODE_IS_RECURSION(node)) break; + + backs = BACKREFS_P(br); + len = tree_min_len(mem_env[backs[0]].node, env); + for (i = 1; i < br->back_num; i++) { + tmin = tree_min_len(mem_env[backs[i]].node, env); + if (len > tmin) len = tmin; + } + } + break; + +#ifdef USE_CALL + case NODE_CALL: + { + Node* t = NODE_BODY(node); + if (NODE_IS_RECURSION(node)) { + if (NODE_IS_MIN_FIXED(t)) + len = BAG_(t)->min_len; + } + else + len = tree_min_len(t, env); + } + break; +#endif + + case NODE_LIST: + do { + tmin = tree_min_len(NODE_CAR(node), env); + len = distance_add(len, tmin); + } while (IS_NOT_NULL(node = NODE_CDR(node))); + break; + + case NODE_ALT: + { + Node *x, *y; + y = node; + do { + x = NODE_CAR(y); + tmin = tree_min_len(x, env); + if (y == node) len = tmin; + else if (len > tmin) len = tmin; + } while (IS_NOT_NULL(y = NODE_CDR(y))); + } + break; + + case NODE_STRING: + { + StrNode* sn = STR_(node); + len = (int )(sn->end - sn->s); + } + break; + + case NODE_CTYPE: + case NODE_CCLASS: + len = ONIGENC_MBC_MINLEN(env->enc); + break; + + case NODE_QUANT: + { + QuantNode* qn = QUANT_(node); + + if (qn->lower > 0) { + len = tree_min_len(NODE_BODY(node), env); + len = distance_multiply(len, qn->lower); + } + } + break; + + case NODE_BAG: + { + BagNode* en = BAG_(node); + switch (en->type) { + case BAG_MEMORY: + if (NODE_IS_MIN_FIXED(node)) + len = en->min_len; + else { + if (NODE_IS_MARK1(node)) + len = 0; /* recursive */ + else { + NODE_STATUS_ADD(node, MARK1); + len = tree_min_len(NODE_BODY(node), env); + NODE_STATUS_REMOVE(node, MARK1); + + en->min_len = len; + NODE_STATUS_ADD(node, MIN_FIXED); + } + } + break; + + case BAG_OPTION: + case BAG_STOP_BACKTRACK: + len = tree_min_len(NODE_BODY(node), env); + break; + case BAG_IF_ELSE: + { + OnigLen elen; + + len = tree_min_len(NODE_BODY(node), env); + if (IS_NOT_NULL(en->te.Then)) + len += tree_min_len(en->te.Then, env); + if (IS_NOT_NULL(en->te.Else)) + elen = tree_min_len(en->te.Else, env); + else elen = 0; + + if (elen < len) len = elen; + } + break; + } + } + break; + + case NODE_GIMMICK: + { + GimmickNode* g = GIMMICK_(node); + if (g->type == GIMMICK_FAIL) { + len = INFINITE_LEN; + break; + } + } + /* fall */ + case NODE_ANCHOR: + default: + break; + } + + return len; +} +","@@ -1307,8 +1307,9 @@ compile_length_bag_node(BagNode* node, regex_t* reg) + len += tlen; + } + ++ len += SIZE_OP_JUMP + SIZE_OP_ATOMIC_END; ++ + if (IS_NOT_NULL(Else)) { +- len += SIZE_OP_JUMP; + tlen = compile_length_tree(Else, reg); + if (tlen < 0) return tlen; + len += tlen; +@@ -1455,7 +1456,7 @@ compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env) + + case BAG_IF_ELSE: + { +- int cond_len, then_len, jump_len; ++ int cond_len, then_len, else_len, jump_len; + Node* cond = NODE_BAG_BODY(node); + Node* Then = node->te.Then; + Node* Else = node->te.Else; +@@ -1472,8 +1473,7 @@ compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env) + else + then_len = 0; + +- jump_len = cond_len + then_len + SIZE_OP_ATOMIC_END; +- if (IS_NOT_NULL(Else)) jump_len += SIZE_OP_JUMP; ++ jump_len = cond_len + then_len + SIZE_OP_ATOMIC_END + SIZE_OP_JUMP; + + r = add_op(reg, OP_PUSH); + if (r != 0) return r; +@@ -1490,11 +1490,20 @@ compile_bag_node(BagNode* node, regex_t* reg, ScanEnv* env) + } + + if (IS_NOT_NULL(Else)) { +- int else_len = compile_length_tree(Else, reg); +- r = add_op(reg, OP_JUMP); +- if (r != 0) return r; +- COP(reg)->jump.addr = else_len + SIZE_INC_OP; ++ else_len = compile_length_tree(Else, reg); ++ if (else_len < 0) return else_len; ++ } ++ else ++ else_len = 0; + ++ r = add_op(reg, OP_JUMP); ++ if (r != 0) return r; ++ COP(reg)->jump.addr = SIZE_OP_ATOMIC_END + else_len + SIZE_INC_OP; ++ ++ r = add_op(reg, OP_ATOMIC_END); ++ if (r != 0) return r; ++ ++ if (IS_NOT_NULL(Else)) { + r = compile_tree(Else, reg, env); + } + }",870,1201,2048 +63,"pdf_show_pattern(fz_context *ctx, pdf_run_processor *pr, pdf_pattern *pat, pdf_gstate *pat_gstate, const fz_rect *area, int what) +{ + pdf_gstate *gstate; + int gparent_save; + fz_matrix ptm, invptm, gparent_save_ctm; + int x0, y0, x1, y1; + float fx0, fy0, fx1, fy1; + fz_rect local_area; + int id; + + pdf_gsave(ctx, pr); + gstate = pr->gstate + pr->gtop; + + /* Patterns are run with the gstate of the parent */ + pdf_copy_pattern_gstate(ctx, gstate, pat_gstate); + + if (pat->ismask) + { + pdf_unset_pattern(ctx, pr, PDF_FILL); + pdf_unset_pattern(ctx, pr, PDF_STROKE); + if (what == PDF_FILL) + { + pdf_drop_material(ctx, &gstate->stroke); + pdf_keep_material(ctx, &gstate->fill); + gstate->stroke = gstate->fill; + } + if (what == PDF_STROKE) + { + pdf_drop_material(ctx, &gstate->fill); + pdf_keep_material(ctx, &gstate->stroke); + gstate->fill = gstate->stroke; + } + id = 0; /* don't cache uncolored patterns, since we colorize them when drawing */ + } + else + { + pdf_unset_pattern(ctx, pr, what); + id = pat->id; + } + + /* don't apply soft masks to objects in the pattern as well */ + if (gstate->softmask) + { + pdf_drop_xobject(ctx, gstate->softmask); + gstate->softmask = NULL; + } + + fz_concat(&ptm, &pat->matrix, &pat_gstate->ctm); + fz_invert_matrix(&invptm, &ptm); + + /* The parent_ctm is amended with our pattern matrix */ + gparent_save = pr->gparent; + pr->gparent = pr->gtop-1; + gparent_save_ctm = pr->gstate[pr->gparent].ctm; + pr->gstate[pr->gparent].ctm = ptm; + + fz_try(ctx) + { + /* patterns are painted using the parent_ctm. area = bbox of + * shape to be filled in device space. Map it back to pattern + * space. */ + local_area = *area; + fz_transform_rect(&local_area, &invptm); + + fx0 = (local_area.x0 - pat->bbox.x0) / pat->xstep; + fy0 = (local_area.y0 - pat->bbox.y0) / pat->ystep; + fx1 = (local_area.x1 - pat->bbox.x0) / pat->xstep; + fy1 = (local_area.y1 - pat->bbox.y0) / pat->ystep; + if (fx0 > fx1) + { + float t = fx0; fx0 = fx1; fx1 = t; + } + if (fy0 > fy1) + { + float t = fy0; fy0 = fy1; fy1 = t; + } + +#ifdef TILE + /* We have tried various formulations in the past, but this one is + * best we've found; only use it as a tile if a whole repeat is + * required in at least one direction. Note, that this allows for + * 'sections' of 4 tiles to be show, but all non-overlapping. */ + if (fx1-fx0 > 1 || fy1-fy0 > 1) +#else + if (0) +#endif + { + int cached = fz_begin_tile_id(ctx, pr->dev, &local_area, &pat->bbox, pat->xstep, pat->ystep, &ptm, id); + if (cached) + { + fz_end_tile(ctx, pr->dev); + } + else + { + gstate->ctm = ptm; + pdf_gsave(ctx, pr); + fz_try(ctx) + pdf_process_contents(ctx, (pdf_processor*)pr, pat->document, pat->resources, pat->contents, NULL); + fz_always(ctx) + { + pdf_grestore(ctx, pr); + fz_end_tile(ctx, pr->dev); + } + fz_catch(ctx) + fz_rethrow(ctx); + } + } + else + { + int x, y; + + /* When calculating the number of tiles required, we adjust by + * a small amount to allow for rounding errors. By choosing + * this amount to be smaller than 1/256, we guarantee we won't + * cause problems that will be visible even under our most + * extreme antialiasing. */ + x0 = floorf(fx0 + 0.001f); + y0 = floorf(fy0 + 0.001f); + x1 = ceilf(fx1 - 0.001f); + y1 = ceilf(fy1 - 0.001f); + /* The above adjustments cause problems for sufficiently + * large values for xstep/ystep which may be used if the + * pattern is expected to be rendered exactly once. */ + if (fx1 > fx0 && x1 == x0) + x1 = x0 + 1; + if (fy1 > fy0 && y1 == y0) + y1 = y0 + 1; + + for (y = y0; y < y1; y++) + { + for (x = x0; x < x1; x++) + { + gstate->ctm = ptm; + fz_pre_translate(&gstate->ctm, x * pat->xstep, y * pat->ystep); + pdf_gsave(ctx, pr); + fz_try(ctx) + pdf_process_contents(ctx, (pdf_processor*)pr, pat->document, pat->resources, pat->contents, NULL); + fz_always(ctx) + pdf_grestore(ctx, pr); + fz_catch(ctx) + fz_rethrow(ctx); + } + } + } + } + fz_always(ctx) + { + pr->gstate[pr->gparent].ctm = gparent_save_ctm; + pr->gparent = gparent_save; + } + fz_catch(ctx) + { + fz_rethrow(ctx); + } + + pdf_grestore(ctx, pr); +} +",0,"pdf_show_pattern(fz_context *ctx, pdf_run_processor *pr, pdf_pattern *pat, pdf_gstate *pat_gstate, const fz_rect *area, int what) +{ + pdf_gstate *gstate; + int gparent_save; + fz_matrix ptm, invptm, gparent_save_ctm; + int x0, y0, x1, y1; + float fx0, fy0, fx1, fy1; + fz_rect local_area; + int id; + + pdf_gsave(ctx, pr); + gstate = pr->gstate + pr->gtop; + + /* Patterns are run with the gstate of the parent */ + pdf_copy_pattern_gstate(ctx, gstate, pat_gstate); + + if (pat->ismask) + { + pdf_unset_pattern(ctx, pr, PDF_FILL); + pdf_unset_pattern(ctx, pr, PDF_STROKE); + if (what == PDF_FILL) + { + pdf_drop_material(ctx, &gstate->stroke); + pdf_keep_material(ctx, &gstate->fill); + gstate->stroke = gstate->fill; + } + if (what == PDF_STROKE) + { + pdf_drop_material(ctx, &gstate->fill); + pdf_keep_material(ctx, &gstate->stroke); + gstate->fill = gstate->stroke; + } + id = 0; /* don't cache uncolored patterns, since we colorize them when drawing */ + } + else + { + pdf_unset_pattern(ctx, pr, what); + id = pat->id; + } + + /* don't apply soft masks to objects in the pattern as well */ + if (gstate->softmask) + { + pdf_drop_xobject(ctx, gstate->softmask); + gstate->softmask = NULL; + } + + fz_concat(&ptm, &pat->matrix, &pat_gstate->ctm); + fz_invert_matrix(&invptm, &ptm); + + /* The parent_ctm is amended with our pattern matrix */ + gparent_save = pr->gparent; + pr->gparent = pr->gtop-1; + gparent_save_ctm = pr->gstate[pr->gparent].ctm; + pr->gstate[pr->gparent].ctm = ptm; + + fz_try(ctx) + { + /* patterns are painted using the parent_ctm. area = bbox of + * shape to be filled in device space. Map it back to pattern + * space. */ + local_area = *area; + fz_transform_rect(&local_area, &invptm); + + fx0 = (local_area.x0 - pat->bbox.x0) / pat->xstep; + fy0 = (local_area.y0 - pat->bbox.y0) / pat->ystep; + fx1 = (local_area.x1 - pat->bbox.x0) / pat->xstep; + fy1 = (local_area.y1 - pat->bbox.y0) / pat->ystep; + if (fx0 > fx1) + { + float t = fx0; fx0 = fx1; fx1 = t; + } + if (fy0 > fy1) + { + float t = fy0; fy0 = fy1; fy1 = t; + } + +#ifdef TILE + /* We have tried various formulations in the past, but this one is + * best we've found; only use it as a tile if a whole repeat is + * required in at least one direction. Note, that this allows for + * 'sections' of 4 tiles to be show, but all non-overlapping. */ + if (fx1-fx0 > 1 || fy1-fy0 > 1) +#else + if (0) +#endif + { + int cached = fz_begin_tile_id(ctx, pr->dev, &local_area, &pat->bbox, pat->xstep, pat->ystep, &ptm, id); + if (cached) + { + fz_end_tile(ctx, pr->dev); + } + else + { + gstate->ctm = ptm; + pdf_gsave(ctx, pr); + fz_try(ctx) + pdf_process_contents(ctx, (pdf_processor*)pr, pat->document, pat->resources, pat->contents, NULL); + fz_always(ctx) + { + pdf_grestore(ctx, pr); + fz_end_tile(ctx, pr->dev); + } + fz_catch(ctx) + fz_rethrow(ctx); + } + } + else + { + int x, y; + + /* When calculating the number of tiles required, we adjust by + * a small amount to allow for rounding errors. By choosing + * this amount to be smaller than 1/256, we guarantee we won't + * cause problems that will be visible even under our most + * extreme antialiasing. */ + x0 = floorf(fx0 + 0.001f); + y0 = floorf(fy0 + 0.001f); + x1 = ceilf(fx1 - 0.001f); + y1 = ceilf(fy1 - 0.001f); + /* The above adjustments cause problems for sufficiently + * large values for xstep/ystep which may be used if the + * pattern is expected to be rendered exactly once. */ + if (fx1 > fx0 && x1 == x0) + x1 = x0 + 1; + if (fy1 > fy0 && y1 == y0) + y1 = y0 + 1; + + for (y = y0; y < y1; y++) + { + for (x = x0; x < x1; x++) + { + gstate->ctm = ptm; + fz_pre_translate(&gstate->ctm, x * pat->xstep, y * pat->ystep); + pdf_gsave(ctx, pr); + fz_try(ctx) + pdf_process_contents(ctx, (pdf_processor*)pr, pat->document, pat->resources, pat->contents, NULL); + fz_always(ctx) + pdf_grestore(ctx, pr); + fz_catch(ctx) + fz_rethrow(ctx); + } + } + } + } + fz_always(ctx) + { + pr->gstate[pr->gparent].ctm = gparent_save_ctm; + pr->gparent = gparent_save; + } + fz_catch(ctx) + { + fz_rethrow(ctx); + } + + pdf_grestore(ctx, pr); +} +","@@ -135,7 +135,7 @@ begin_softmask(fz_context *ctx, pdf_run_processor *pr, softmask_save *save) + mask_colorspace = pdf_xobject_colorspace(ctx, softmask); + + if (gstate->luminosity && !mask_colorspace) +- mask_colorspace = fz_device_gray(ctx); ++ mask_colorspace = fz_keep_colorspace(ctx, fz_device_gray(ctx)); + + fz_try(ctx) + {",1461,1792,2048 +18342,"static int read_entry( + git_index_entry **out, + size_t *out_size, + git_index *index, + const void *buffer, + size_t buffer_size, + const char *last) +{ + size_t path_length, entry_size; + const char *path_ptr; + struct entry_short source; + git_index_entry entry = {{0}}; + bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP; + char *tmp_path = NULL; + + if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size) + return -1; + + /* buffer is not guaranteed to be aligned */ + memcpy(&source, buffer, sizeof(struct entry_short)); + + entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds); + entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds); + entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds); + entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds); + entry.dev = ntohl(source.dev); + entry.ino = ntohl(source.ino); + entry.mode = ntohl(source.mode); + entry.uid = ntohl(source.uid); + entry.gid = ntohl(source.gid); + entry.file_size = ntohl(source.file_size); + git_oid_cpy(&entry.id, &source.oid); + entry.flags = ntohs(source.flags); + + if (entry.flags & GIT_IDXENTRY_EXTENDED) { + uint16_t flags_raw; + size_t flags_offset; + + flags_offset = offsetof(struct entry_long, flags_extended); + memcpy(&flags_raw, (const char *) buffer + flags_offset, + sizeof(flags_raw)); + flags_raw = ntohs(flags_raw); + + memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw)); + path_ptr = (const char *) buffer + offsetof(struct entry_long, path); + } else + path_ptr = (const char *) buffer + offsetof(struct entry_short, path); + + if (!compressed) { + path_length = entry.flags & GIT_IDXENTRY_NAMEMASK; + + /* if this is a very long string, we must find its + * real length without overflowing */ + if (path_length == 0xFFF) { + const char *path_end; + + path_end = memchr(path_ptr, '\0', buffer_size); + if (path_end == NULL) + return -1; + + path_length = path_end - path_ptr; + } + + entry_size = index_entry_size(path_length, 0, entry.flags); + entry.path = (char *)path_ptr; + } else { + size_t varint_len, last_len, prefix_len, suffix_len, path_len; + uintmax_t strip_len; + + strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len); + last_len = strlen(last); + + if (varint_len == 0 || last_len < strip_len) + return index_error_invalid(""incorrect prefix length""); + + prefix_len = last_len - strip_len; + suffix_len = strlen(path_ptr + varint_len); + + GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len); + GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1); + tmp_path = git__malloc(path_len); + GITERR_CHECK_ALLOC(tmp_path); + + memcpy(tmp_path, last, prefix_len); + memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1); + entry_size = index_entry_size(suffix_len, varint_len, entry.flags); + entry.path = tmp_path; + } + + if (entry_size == 0) + return -1; + + if (INDEX_FOOTER_SIZE + entry_size > buffer_size) + return -1; + + if (index_entry_dup(out, index, &entry) < 0) { + git__free(tmp_path); + return -1; + } + + git__free(tmp_path); + *out_size = entry_size; + return 0; +} +",1,"static int read_entry( + git_index_entry **out, + size_t *out_size, + git_index *index, + const void *buffer, + size_t buffer_size, + const char *last) +{ + size_t path_length, entry_size; + const char *path_ptr; + struct entry_short source; + git_index_entry entry = {{0}}; + bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP; + char *tmp_path = NULL; + + if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size) + return -1; + + /* buffer is not guaranteed to be aligned */ + memcpy(&source, buffer, sizeof(struct entry_short)); + + entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds); + entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds); + entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds); + entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds); + entry.dev = ntohl(source.dev); + entry.ino = ntohl(source.ino); + entry.mode = ntohl(source.mode); + entry.uid = ntohl(source.uid); + entry.gid = ntohl(source.gid); + entry.file_size = ntohl(source.file_size); + git_oid_cpy(&entry.id, &source.oid); + entry.flags = ntohs(source.flags); + + if (entry.flags & GIT_IDXENTRY_EXTENDED) { + uint16_t flags_raw; + size_t flags_offset; + + flags_offset = offsetof(struct entry_long, flags_extended); + memcpy(&flags_raw, (const char *) buffer + flags_offset, + sizeof(flags_raw)); + flags_raw = ntohs(flags_raw); + + memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw)); + path_ptr = (const char *) buffer + offsetof(struct entry_long, path); + } else + path_ptr = (const char *) buffer + offsetof(struct entry_short, path); + + if (!compressed) { + path_length = entry.flags & GIT_IDXENTRY_NAMEMASK; + + /* if this is a very long string, we must find its + * real length without overflowing */ + if (path_length == 0xFFF) { + const char *path_end; + + path_end = memchr(path_ptr, '\0', buffer_size); + if (path_end == NULL) + return -1; + + path_length = path_end - path_ptr; + } + + entry_size = index_entry_size(path_length, 0, entry.flags); + entry.path = (char *)path_ptr; + } else { + size_t varint_len, last_len, prefix_len, suffix_len, path_len; + uintmax_t strip_len; + + strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len); + last_len = strlen(last); + + if (varint_len == 0 || last_len < strip_len) + return index_error_invalid(""incorrect prefix length""); + + prefix_len = last_len - strip_len; + suffix_len = strlen(path_ptr + varint_len); + + GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len); + GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1); + + if (path_len > GIT_PATH_MAX) + return index_error_invalid(""unreasonable path length""); + + tmp_path = git__malloc(path_len); + GITERR_CHECK_ALLOC(tmp_path); + + memcpy(tmp_path, last, prefix_len); + memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1); + entry_size = index_entry_size(suffix_len, varint_len, entry.flags); + entry.path = tmp_path; + } + + if (entry_size == 0) + return -1; + + if (INDEX_FOOTER_SIZE + entry_size > buffer_size) + return -1; + + if (index_entry_dup(out, index, &entry) < 0) { + git__free(tmp_path); + return -1; + } + + git__free(tmp_path); + *out_size = entry_size; + return 0; +} +","@@ -2379,6 +2379,10 @@ static int read_entry( + + GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len); + GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1); ++ ++ if (path_len > GIT_PATH_MAX) ++ return index_error_invalid(""unreasonable path length""); ++ + tmp_path = git__malloc(path_len); + GITERR_CHECK_ALLOC(tmp_path); + ",810,1141,2048 +6395,"static int vp8_decode_frame_header(VP8Context *s, const uint8_t *buf, int buf_size) +{ + VP56RangeCoder *c = &s->c; + int header_size, hscale, vscale, ret; + int width = s->avctx->width; + int height = s->avctx->height; + + if (buf_size < 3) { + av_log(s->avctx, AV_LOG_ERROR, ""Insufficent data (%d) for header\n"", buf_size); + return AVERROR_INVALIDDATA; + } + + s->keyframe = !(buf[0] & 1); + s->profile = (buf[0]>>1) & 7; + s->invisible = !(buf[0] & 0x10); + header_size = AV_RL24(buf) >> 5; + buf += 3; + buf_size -= 3; + + if (s->profile > 3) + av_log(s->avctx, AV_LOG_WARNING, ""Unknown profile %d\n"", s->profile); + + if (!s->profile) + memcpy(s->put_pixels_tab, s->vp8dsp.put_vp8_epel_pixels_tab, + sizeof(s->put_pixels_tab)); + else // profile 1-3 use bilinear, 4+ aren't defined so whatever + memcpy(s->put_pixels_tab, s->vp8dsp.put_vp8_bilinear_pixels_tab, + sizeof(s->put_pixels_tab)); + + if (header_size > buf_size - 7 * s->keyframe) { + av_log(s->avctx, AV_LOG_ERROR, ""Header size larger than data provided\n""); + return AVERROR_INVALIDDATA; + } + + if (s->keyframe) { + if (AV_RL24(buf) != 0x2a019d) { + av_log(s->avctx, AV_LOG_ERROR, + ""Invalid start code 0x%x\n"", AV_RL24(buf)); + return AVERROR_INVALIDDATA; + } + width = AV_RL16(buf + 3) & 0x3fff; + height = AV_RL16(buf + 5) & 0x3fff; + hscale = buf[4] >> 6; + vscale = buf[6] >> 6; + buf += 7; + buf_size -= 7; + + if (hscale || vscale) + avpriv_request_sample(s->avctx, ""Upscaling""); + + s->update_golden = s->update_altref = VP56_FRAME_CURRENT; + vp78_reset_probability_tables(s); + memcpy(s->prob->pred16x16, vp8_pred16x16_prob_inter, + sizeof(s->prob->pred16x16)); + memcpy(s->prob->pred8x8c, vp8_pred8x8c_prob_inter, + sizeof(s->prob->pred8x8c)); + memcpy(s->prob->mvc, vp8_mv_default_prob, + sizeof(s->prob->mvc)); + memset(&s->segmentation, 0, sizeof(s->segmentation)); + memset(&s->lf_delta, 0, sizeof(s->lf_delta)); + } + + ret = ff_vp56_init_range_decoder(c, buf, header_size); + if (ret < 0) + return ret; + buf += header_size; + buf_size -= header_size; + + if (s->keyframe) { + s->colorspace = vp8_rac_get(c); + if (s->colorspace) + av_log(s->avctx, AV_LOG_WARNING, ""Unspecified colorspace\n""); + s->fullrange = vp8_rac_get(c); + } + + if ((s->segmentation.enabled = vp8_rac_get(c))) + parse_segment_info(s); + else + s->segmentation.update_map = 0; // FIXME: move this to some init function? + + s->filter.simple = vp8_rac_get(c); + s->filter.level = vp8_rac_get_uint(c, 6); + s->filter.sharpness = vp8_rac_get_uint(c, 3); + + if ((s->lf_delta.enabled = vp8_rac_get(c))) + if (vp8_rac_get(c)) + update_lf_deltas(s); + + if (setup_partitions(s, buf, buf_size)) { + av_log(s->avctx, AV_LOG_ERROR, ""Invalid partitions\n""); + return AVERROR_INVALIDDATA; + } + + if (!s->macroblocks_base || /* first frame */ + width != s->avctx->width || height != s->avctx->height || + (width+15)/16 != s->mb_width || (height+15)/16 != s->mb_height) + if ((ret = vp8_update_dimensions(s, width, height)) < 0) + return ret; + + vp8_get_quants(s); + + if (!s->keyframe) { + update_refs(s); + s->sign_bias[VP56_FRAME_GOLDEN] = vp8_rac_get(c); + s->sign_bias[VP56_FRAME_GOLDEN2 /* altref */] = vp8_rac_get(c); + } + + if (!(s->update_probabilities = vp8_rac_get(c))) + s->prob[1] = s->prob[0]; + + s->update_last = s->keyframe || vp8_rac_get(c); + + vp78_update_probability_tables(s); + + if ((s->mbskip_enabled = vp8_rac_get(c))) + s->prob->mbskip = vp8_rac_get_uint(c, 8); + + if (!s->keyframe) { + s->prob->intra = vp8_rac_get_uint(c, 8); + s->prob->last = vp8_rac_get_uint(c, 8); + s->prob->golden = vp8_rac_get_uint(c, 8); + vp78_update_pred16x16_pred8x8_mvc_probabilities(s, VP8_MVC_SIZE); + } + + return 0; +} +",0,"static int vp8_decode_frame_header(VP8Context *s, const uint8_t *buf, int buf_size) +{ + VP56RangeCoder *c = &s->c; + int header_size, hscale, vscale, ret; + int width = s->avctx->width; + int height = s->avctx->height; + + if (buf_size < 3) { + av_log(s->avctx, AV_LOG_ERROR, ""Insufficent data (%d) for header\n"", buf_size); + return AVERROR_INVALIDDATA; + } + + s->keyframe = !(buf[0] & 1); + s->profile = (buf[0]>>1) & 7; + s->invisible = !(buf[0] & 0x10); + header_size = AV_RL24(buf) >> 5; + buf += 3; + buf_size -= 3; + + if (s->profile > 3) + av_log(s->avctx, AV_LOG_WARNING, ""Unknown profile %d\n"", s->profile); + + if (!s->profile) + memcpy(s->put_pixels_tab, s->vp8dsp.put_vp8_epel_pixels_tab, + sizeof(s->put_pixels_tab)); + else // profile 1-3 use bilinear, 4+ aren't defined so whatever + memcpy(s->put_pixels_tab, s->vp8dsp.put_vp8_bilinear_pixels_tab, + sizeof(s->put_pixels_tab)); + + if (header_size > buf_size - 7 * s->keyframe) { + av_log(s->avctx, AV_LOG_ERROR, ""Header size larger than data provided\n""); + return AVERROR_INVALIDDATA; + } + + if (s->keyframe) { + if (AV_RL24(buf) != 0x2a019d) { + av_log(s->avctx, AV_LOG_ERROR, + ""Invalid start code 0x%x\n"", AV_RL24(buf)); + return AVERROR_INVALIDDATA; + } + width = AV_RL16(buf + 3) & 0x3fff; + height = AV_RL16(buf + 5) & 0x3fff; + hscale = buf[4] >> 6; + vscale = buf[6] >> 6; + buf += 7; + buf_size -= 7; + + if (hscale || vscale) + avpriv_request_sample(s->avctx, ""Upscaling""); + + s->update_golden = s->update_altref = VP56_FRAME_CURRENT; + vp78_reset_probability_tables(s); + memcpy(s->prob->pred16x16, vp8_pred16x16_prob_inter, + sizeof(s->prob->pred16x16)); + memcpy(s->prob->pred8x8c, vp8_pred8x8c_prob_inter, + sizeof(s->prob->pred8x8c)); + memcpy(s->prob->mvc, vp8_mv_default_prob, + sizeof(s->prob->mvc)); + memset(&s->segmentation, 0, sizeof(s->segmentation)); + memset(&s->lf_delta, 0, sizeof(s->lf_delta)); + } + + ret = ff_vp56_init_range_decoder(c, buf, header_size); + if (ret < 0) + return ret; + buf += header_size; + buf_size -= header_size; + + if (s->keyframe) { + s->colorspace = vp8_rac_get(c); + if (s->colorspace) + av_log(s->avctx, AV_LOG_WARNING, ""Unspecified colorspace\n""); + s->fullrange = vp8_rac_get(c); + } + + if ((s->segmentation.enabled = vp8_rac_get(c))) + parse_segment_info(s); + else + s->segmentation.update_map = 0; // FIXME: move this to some init function? + + s->filter.simple = vp8_rac_get(c); + s->filter.level = vp8_rac_get_uint(c, 6); + s->filter.sharpness = vp8_rac_get_uint(c, 3); + + if ((s->lf_delta.enabled = vp8_rac_get(c))) + if (vp8_rac_get(c)) + update_lf_deltas(s); + + if (setup_partitions(s, buf, buf_size)) { + av_log(s->avctx, AV_LOG_ERROR, ""Invalid partitions\n""); + return AVERROR_INVALIDDATA; + } + + if (!s->macroblocks_base || /* first frame */ + width != s->avctx->width || height != s->avctx->height || + (width+15)/16 != s->mb_width || (height+15)/16 != s->mb_height) + if ((ret = vp8_update_dimensions(s, width, height)) < 0) + return ret; + + vp8_get_quants(s); + + if (!s->keyframe) { + update_refs(s); + s->sign_bias[VP56_FRAME_GOLDEN] = vp8_rac_get(c); + s->sign_bias[VP56_FRAME_GOLDEN2 /* altref */] = vp8_rac_get(c); + } + + if (!(s->update_probabilities = vp8_rac_get(c))) + s->prob[1] = s->prob[0]; + + s->update_last = s->keyframe || vp8_rac_get(c); + + vp78_update_probability_tables(s); + + if ((s->mbskip_enabled = vp8_rac_get(c))) + s->prob->mbskip = vp8_rac_get_uint(c, 8); + + if (!s->keyframe) { + s->prob->intra = vp8_rac_get_uint(c, 8); + s->prob->last = vp8_rac_get_uint(c, 8); + s->prob->golden = vp8_rac_get_uint(c, 8); + vp78_update_pred16x16_pred8x8_mvc_probabilities(s, VP8_MVC_SIZE); + } + + return 0; +} +","@@ -2550,6 +2550,8 @@ int vp78_decode_frame(AVCodecContext *avctx, void *data, int *got_frame, + enum AVDiscard skip_thresh; + VP8Frame *av_uninit(curframe), *prev_frame; + ++ av_assert0(avctx->pix_fmt == AV_PIX_FMT_YUVA420P || avctx->pix_fmt == AV_PIX_FMT_YUV420P); ++ + if (is_vp7) + ret = vp7_decode_frame_header(s, avpkt->data, avpkt->size); + else",1336,1667,2048 +2185,"static int do_swap_page(struct mm_struct *mm, struct vm_area_struct *vma, + unsigned long address, pte_t *page_table, pmd_t *pmd, + unsigned int flags, pte_t orig_pte) +{ + spinlock_t *ptl; + struct page *page, *swapcache = NULL; + swp_entry_t entry; + pte_t pte; + int locked; + struct mem_cgroup *ptr; + int exclusive = 0; + int ret = 0; + + if (!pte_unmap_same(mm, pmd, page_table, orig_pte)) + goto out; + + entry = pte_to_swp_entry(orig_pte); + if (unlikely(non_swap_entry(entry))) { + if (is_migration_entry(entry)) { + migration_entry_wait(mm, pmd, address); + } else if (is_hwpoison_entry(entry)) { + ret = VM_FAULT_HWPOISON; + } else { + print_bad_pte(vma, address, orig_pte, NULL); + ret = VM_FAULT_SIGBUS; + } + goto out; + } + delayacct_set_flag(DELAYACCT_PF_SWAPIN); + page = lookup_swap_cache(entry); + if (!page) { + grab_swap_token(mm); /* Contend for token _before_ read-in */ + page = swapin_readahead(entry, + GFP_HIGHUSER_MOVABLE, vma, address); + if (!page) { + /* + * Back out if somebody else faulted in this pte + * while we released the pte lock. + */ + page_table = pte_offset_map_lock(mm, pmd, address, &ptl); + if (likely(pte_same(*page_table, orig_pte))) + ret = VM_FAULT_OOM; + delayacct_clear_flag(DELAYACCT_PF_SWAPIN); + goto unlock; + } + + /* Had to read the page from swap area: Major fault */ + ret = VM_FAULT_MAJOR; + count_vm_event(PGMAJFAULT); + mem_cgroup_count_vm_event(mm, PGMAJFAULT); + } else if (PageHWPoison(page)) { + /* + * hwpoisoned dirty swapcache pages are kept for killing + * owner processes (which may be unknown at hwpoison time) + */ + ret = VM_FAULT_HWPOISON; + delayacct_clear_flag(DELAYACCT_PF_SWAPIN); + goto out_release; + } + + locked = lock_page_or_retry(page, mm, flags); + delayacct_clear_flag(DELAYACCT_PF_SWAPIN); + if (!locked) { + ret |= VM_FAULT_RETRY; + goto out_release; + } + + /* + * Make sure try_to_free_swap or reuse_swap_page or swapoff did not + * release the swapcache from under us. The page pin, and pte_same + * test below, are not enough to exclude that. Even if it is still + * swapcache, we need to check that the page's swap has not changed. + */ + if (unlikely(!PageSwapCache(page) || page_private(page) != entry.val)) + goto out_page; + + if (ksm_might_need_to_copy(page, vma, address)) { + swapcache = page; + page = ksm_does_need_to_copy(page, vma, address); + + if (unlikely(!page)) { + ret = VM_FAULT_OOM; + page = swapcache; + swapcache = NULL; + goto out_page; + } + } + + if (mem_cgroup_try_charge_swapin(mm, page, GFP_KERNEL, &ptr)) { + ret = VM_FAULT_OOM; + goto out_page; + } + + /* + * Back out if somebody else already faulted in this pte. + */ + page_table = pte_offset_map_lock(mm, pmd, address, &ptl); + if (unlikely(!pte_same(*page_table, orig_pte))) + goto out_nomap; + + if (unlikely(!PageUptodate(page))) { + ret = VM_FAULT_SIGBUS; + goto out_nomap; + } + + /* + * The page isn't present yet, go ahead with the fault. + * + * Be careful about the sequence of operations here. + * To get its accounting right, reuse_swap_page() must be called + * while the page is counted on swap but not yet in mapcount i.e. + * before page_add_anon_rmap() and swap_free(); try_to_free_swap() + * must be called after the swap_free(), or it will never succeed. + * Because delete_from_swap_page() may be called by reuse_swap_page(), + * mem_cgroup_commit_charge_swapin() may not be able to find swp_entry + * in page->private. In this case, a record in swap_cgroup is silently + * discarded at swap_free(). + */ + + inc_mm_counter_fast(mm, MM_ANONPAGES); + dec_mm_counter_fast(mm, MM_SWAPENTS); + pte = mk_pte(page, vma->vm_page_prot); + if ((flags & FAULT_FLAG_WRITE) && reuse_swap_page(page)) { + pte = maybe_mkwrite(pte_mkdirty(pte), vma); + flags &= ~FAULT_FLAG_WRITE; + ret |= VM_FAULT_WRITE; + exclusive = 1; + } + flush_icache_page(vma, page); + set_pte_at(mm, address, page_table, pte); + do_page_add_anon_rmap(page, vma, address, exclusive); + /* It's better to call commit-charge after rmap is established */ + mem_cgroup_commit_charge_swapin(page, ptr); + + swap_free(entry); + if (vm_swap_full() || (vma->vm_flags & VM_LOCKED) || PageMlocked(page)) + try_to_free_swap(page); + unlock_page(page); + if (swapcache) { + /* + * Hold the lock to avoid the swap entry to be reused + * until we take the PT lock for the pte_same() check + * (to avoid false positives from pte_same). For + * further safety release the lock after the swap_free + * so that the swap count won't change under a + * parallel locked swapcache. + */ + unlock_page(swapcache); + page_cache_release(swapcache); + } + + if (flags & FAULT_FLAG_WRITE) { + ret |= do_wp_page(mm, vma, address, page_table, pmd, ptl, pte); + if (ret & VM_FAULT_ERROR) + ret &= VM_FAULT_ERROR; + goto out; + } + + /* No need to invalidate - it was non-present before */ + update_mmu_cache(vma, address, page_table); +unlock: + pte_unmap_unlock(page_table, ptl); +out: + return ret; +out_nomap: + mem_cgroup_cancel_charge_swapin(ptr); + pte_unmap_unlock(page_table, ptl); +out_page: + unlock_page(page); +out_release: + page_cache_release(page); + if (swapcache) { + unlock_page(swapcache); + page_cache_release(swapcache); + } + return ret; +} +",0,"static int do_swap_page(struct mm_struct *mm, struct vm_area_struct *vma, + unsigned long address, pte_t *page_table, pmd_t *pmd, + unsigned int flags, pte_t orig_pte) +{ + spinlock_t *ptl; + struct page *page, *swapcache = NULL; + swp_entry_t entry; + pte_t pte; + int locked; + struct mem_cgroup *ptr; + int exclusive = 0; + int ret = 0; + + if (!pte_unmap_same(mm, pmd, page_table, orig_pte)) + goto out; + + entry = pte_to_swp_entry(orig_pte); + if (unlikely(non_swap_entry(entry))) { + if (is_migration_entry(entry)) { + migration_entry_wait(mm, pmd, address); + } else if (is_hwpoison_entry(entry)) { + ret = VM_FAULT_HWPOISON; + } else { + print_bad_pte(vma, address, orig_pte, NULL); + ret = VM_FAULT_SIGBUS; + } + goto out; + } + delayacct_set_flag(DELAYACCT_PF_SWAPIN); + page = lookup_swap_cache(entry); + if (!page) { + grab_swap_token(mm); /* Contend for token _before_ read-in */ + page = swapin_readahead(entry, + GFP_HIGHUSER_MOVABLE, vma, address); + if (!page) { + /* + * Back out if somebody else faulted in this pte + * while we released the pte lock. + */ + page_table = pte_offset_map_lock(mm, pmd, address, &ptl); + if (likely(pte_same(*page_table, orig_pte))) + ret = VM_FAULT_OOM; + delayacct_clear_flag(DELAYACCT_PF_SWAPIN); + goto unlock; + } + + /* Had to read the page from swap area: Major fault */ + ret = VM_FAULT_MAJOR; + count_vm_event(PGMAJFAULT); + mem_cgroup_count_vm_event(mm, PGMAJFAULT); + } else if (PageHWPoison(page)) { + /* + * hwpoisoned dirty swapcache pages are kept for killing + * owner processes (which may be unknown at hwpoison time) + */ + ret = VM_FAULT_HWPOISON; + delayacct_clear_flag(DELAYACCT_PF_SWAPIN); + goto out_release; + } + + locked = lock_page_or_retry(page, mm, flags); + delayacct_clear_flag(DELAYACCT_PF_SWAPIN); + if (!locked) { + ret |= VM_FAULT_RETRY; + goto out_release; + } + + /* + * Make sure try_to_free_swap or reuse_swap_page or swapoff did not + * release the swapcache from under us. The page pin, and pte_same + * test below, are not enough to exclude that. Even if it is still + * swapcache, we need to check that the page's swap has not changed. + */ + if (unlikely(!PageSwapCache(page) || page_private(page) != entry.val)) + goto out_page; + + if (ksm_might_need_to_copy(page, vma, address)) { + swapcache = page; + page = ksm_does_need_to_copy(page, vma, address); + + if (unlikely(!page)) { + ret = VM_FAULT_OOM; + page = swapcache; + swapcache = NULL; + goto out_page; + } + } + + if (mem_cgroup_try_charge_swapin(mm, page, GFP_KERNEL, &ptr)) { + ret = VM_FAULT_OOM; + goto out_page; + } + + /* + * Back out if somebody else already faulted in this pte. + */ + page_table = pte_offset_map_lock(mm, pmd, address, &ptl); + if (unlikely(!pte_same(*page_table, orig_pte))) + goto out_nomap; + + if (unlikely(!PageUptodate(page))) { + ret = VM_FAULT_SIGBUS; + goto out_nomap; + } + + /* + * The page isn't present yet, go ahead with the fault. + * + * Be careful about the sequence of operations here. + * To get its accounting right, reuse_swap_page() must be called + * while the page is counted on swap but not yet in mapcount i.e. + * before page_add_anon_rmap() and swap_free(); try_to_free_swap() + * must be called after the swap_free(), or it will never succeed. + * Because delete_from_swap_page() may be called by reuse_swap_page(), + * mem_cgroup_commit_charge_swapin() may not be able to find swp_entry + * in page->private. In this case, a record in swap_cgroup is silently + * discarded at swap_free(). + */ + + inc_mm_counter_fast(mm, MM_ANONPAGES); + dec_mm_counter_fast(mm, MM_SWAPENTS); + pte = mk_pte(page, vma->vm_page_prot); + if ((flags & FAULT_FLAG_WRITE) && reuse_swap_page(page)) { + pte = maybe_mkwrite(pte_mkdirty(pte), vma); + flags &= ~FAULT_FLAG_WRITE; + ret |= VM_FAULT_WRITE; + exclusive = 1; + } + flush_icache_page(vma, page); + set_pte_at(mm, address, page_table, pte); + do_page_add_anon_rmap(page, vma, address, exclusive); + /* It's better to call commit-charge after rmap is established */ + mem_cgroup_commit_charge_swapin(page, ptr); + + swap_free(entry); + if (vm_swap_full() || (vma->vm_flags & VM_LOCKED) || PageMlocked(page)) + try_to_free_swap(page); + unlock_page(page); + if (swapcache) { + /* + * Hold the lock to avoid the swap entry to be reused + * until we take the PT lock for the pte_same() check + * (to avoid false positives from pte_same). For + * further safety release the lock after the swap_free + * so that the swap count won't change under a + * parallel locked swapcache. + */ + unlock_page(swapcache); + page_cache_release(swapcache); + } + + if (flags & FAULT_FLAG_WRITE) { + ret |= do_wp_page(mm, vma, address, page_table, pmd, ptl, pte); + if (ret & VM_FAULT_ERROR) + ret &= VM_FAULT_ERROR; + goto out; + } + + /* No need to invalidate - it was non-present before */ + update_mmu_cache(vma, address, page_table); +unlock: + pte_unmap_unlock(page_table, ptl); +out: + return ret; +out_nomap: + mem_cgroup_cancel_charge_swapin(ptr); + pte_unmap_unlock(page_table, ptl); +out_page: + unlock_page(page); +out_release: + page_cache_release(page); + if (swapcache) { + unlock_page(swapcache); + page_cache_release(swapcache); + } + return ret; +} +","@@ -1247,16 +1247,24 @@ static inline unsigned long zap_pmd_range(struct mmu_gather *tlb, + do { + next = pmd_addr_end(addr, end); + if (pmd_trans_huge(*pmd)) { +- if (next-addr != HPAGE_PMD_SIZE) { ++ if (next - addr != HPAGE_PMD_SIZE) { + VM_BUG_ON(!rwsem_is_locked(&tlb->mm->mmap_sem)); + split_huge_page_pmd(vma->vm_mm, pmd); + } else if (zap_huge_pmd(tlb, vma, pmd, addr)) +- continue; ++ goto next; + /* fall through */ + } +- if (pmd_none_or_clear_bad(pmd)) +- continue; ++ /* ++ * Here there can be other concurrent MADV_DONTNEED or ++ * trans huge page faults running, and if the pmd is ++ * none or trans huge it can change under us. This is ++ * because MADV_DONTNEED holds the mmap_sem in read ++ * mode. ++ */ ++ if (pmd_none_or_trans_huge_or_clear_bad(pmd)) ++ goto next; + next = zap_pte_range(tlb, vma, pmd, addr, next, details); ++next: + cond_resched(); + } while (pmd++, addr = next, addr != end); + ",1499,1830,2048 +18818,"void SoftMPEG2::onQueueFilled(OMX_U32 portIndex) { + UNUSED(portIndex); + + if (mOutputPortSettingsChange != NONE) { + return; + } + + List &inQueue = getPortQueue(kInputPortIndex); + List &outQueue = getPortQueue(kOutputPortIndex); + + /* If input EOS is seen and decoder is not in flush mode, + * set the decoder in flush mode. + * There can be a case where EOS is sent along with last picture data + * In that case, only after decoding that input data, decoder has to be + * put in flush. This case is handled here */ + + if (mReceivedEOS && !mIsInFlush) { + setFlushMode(); + } + + while (!outQueue.empty()) { + BufferInfo *inInfo; + OMX_BUFFERHEADERTYPE *inHeader; + + BufferInfo *outInfo; + OMX_BUFFERHEADERTYPE *outHeader; + size_t timeStampIx; + + inInfo = NULL; + inHeader = NULL; + + if (!mIsInFlush) { + if (!inQueue.empty()) { + inInfo = *inQueue.begin(); + inHeader = inInfo->mHeader; + } else { + break; + } + } + + outInfo = *outQueue.begin(); + outHeader = outInfo->mHeader; + outHeader->nFlags = 0; + outHeader->nTimeStamp = 0; + outHeader->nOffset = 0; + + if (inHeader != NULL && (inHeader->nFlags & OMX_BUFFERFLAG_EOS)) { + mReceivedEOS = true; + if (inHeader->nFilledLen == 0) { + inQueue.erase(inQueue.begin()); + inInfo->mOwnedByUs = false; + notifyEmptyBufferDone(inHeader); + inHeader = NULL; + setFlushMode(); + } + } + + if (mInitNeeded && !mIsInFlush) { + bool portWillReset = false; + handlePortSettingsChange(&portWillReset, mNewWidth, mNewHeight); + + CHECK_EQ(reInitDecoder(), (status_t)OK); + return; + } + + /* Get a free slot in timestamp array to hold input timestamp */ + { + size_t i; + timeStampIx = 0; + for (i = 0; i < MAX_TIME_STAMPS; i++) { + if (!mTimeStampsValid[i]) { + timeStampIx = i; + break; + } + } + if (inHeader != NULL) { + mTimeStampsValid[timeStampIx] = true; + mTimeStamps[timeStampIx] = inHeader->nTimeStamp; + } + } + + { + ivd_video_decode_ip_t s_dec_ip; + ivd_video_decode_op_t s_dec_op; + + WORD32 timeDelay, timeTaken; + size_t sizeY, sizeUV; + + setDecodeArgs(&s_dec_ip, &s_dec_op, inHeader, outHeader, timeStampIx); + DUMP_TO_FILE(mInFile, s_dec_ip.pv_stream_buffer, s_dec_ip.u4_num_Bytes); + + if (s_dec_ip.u4_num_Bytes > 0) { + char *ptr = (char *)s_dec_ip.pv_stream_buffer; + } + + GETTIME(&mTimeStart, NULL); + /* Compute time elapsed between end of previous decode() + * to start of current decode() */ + TIME_DIFF(mTimeEnd, mTimeStart, timeDelay); + + IV_API_CALL_STATUS_T status; + status = ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op); + + bool unsupportedDimensions = (IMPEG2D_UNSUPPORTED_DIMENSIONS == s_dec_op.u4_error_code); + bool resChanged = (IVD_RES_CHANGED == (s_dec_op.u4_error_code & 0xFF)); + + GETTIME(&mTimeEnd, NULL); + /* Compute time taken for decode() */ + TIME_DIFF(mTimeStart, mTimeEnd, timeTaken); + + ALOGV(""timeTaken=%6d delay=%6d numBytes=%6d"", timeTaken, timeDelay, + s_dec_op.u4_num_bytes_consumed); + if (s_dec_op.u4_frame_decoded_flag && !mFlushNeeded) { + mFlushNeeded = true; + } + + if ((inHeader != NULL) && (1 != s_dec_op.u4_frame_decoded_flag)) { + /* If the input did not contain picture data, then ignore + * the associated timestamp */ + mTimeStampsValid[timeStampIx] = false; + } + + if (unsupportedDimensions && !mFlushNeeded) { + bool portWillReset = false; + handlePortSettingsChange(&portWillReset, s_dec_op.u4_pic_wd, s_dec_op.u4_pic_ht); + + + CHECK_EQ(reInitDecoder(), (status_t)OK); + + setDecodeArgs(&s_dec_ip, &s_dec_op, inHeader, outHeader, timeStampIx); + ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op); + return; + } + + if (mChangingResolution && !s_dec_op.u4_output_present) { + mChangingResolution = false; + resetDecoder(); + resetPlugin(); + continue; + } + + if (unsupportedDimensions || resChanged) { + mChangingResolution = true; + if (mFlushNeeded) { + setFlushMode(); + } + + if (unsupportedDimensions) { + mNewWidth = s_dec_op.u4_pic_wd; + mNewHeight = s_dec_op.u4_pic_ht; + mInitNeeded = true; + } + continue; + } + + if ((0 < s_dec_op.u4_pic_wd) && (0 < s_dec_op.u4_pic_ht)) { + uint32_t width = s_dec_op.u4_pic_wd; + uint32_t height = s_dec_op.u4_pic_ht; + bool portWillReset = false; + handlePortSettingsChange(&portWillReset, width, height); + + if (portWillReset) { + resetDecoder(); + return; + } + } + + if (s_dec_op.u4_output_present) { + size_t timeStampIdx; + outHeader->nFilledLen = (mWidth * mHeight * 3) / 2; + + timeStampIdx = getMinTimestampIdx(mTimeStamps, mTimeStampsValid); + outHeader->nTimeStamp = mTimeStamps[timeStampIdx]; + mTimeStampsValid[timeStampIdx] = false; + + /* mWaitForI waits for the first I picture. Once made FALSE, it + has to remain false till explicitly set to TRUE. */ + mWaitForI = mWaitForI && !(IV_I_FRAME == s_dec_op.e_pic_type); + + if (mWaitForI) { + s_dec_op.u4_output_present = false; + } else { + ALOGV(""Output timestamp: %lld, res: %ux%u"", + (long long)outHeader->nTimeStamp, mWidth, mHeight); + DUMP_TO_FILE(mOutFile, outHeader->pBuffer, outHeader->nFilledLen); + outInfo->mOwnedByUs = false; + outQueue.erase(outQueue.begin()); + outInfo = NULL; + notifyFillBufferDone(outHeader); + outHeader = NULL; + } + } else { + /* If in flush mode and no output is returned by the codec, + * then come out of flush mode */ + mIsInFlush = false; + + /* If EOS was recieved on input port and there is no output + * from the codec, then signal EOS on output port */ + if (mReceivedEOS) { + outHeader->nFilledLen = 0; + outHeader->nFlags |= OMX_BUFFERFLAG_EOS; + + outInfo->mOwnedByUs = false; + outQueue.erase(outQueue.begin()); + outInfo = NULL; + notifyFillBufferDone(outHeader); + outHeader = NULL; + resetPlugin(); + } + } + } + + if (inHeader != NULL) { + inInfo->mOwnedByUs = false; + inQueue.erase(inQueue.begin()); + inInfo = NULL; + notifyEmptyBufferDone(inHeader); + inHeader = NULL; + } + } +} +",1,"void SoftMPEG2::onQueueFilled(OMX_U32 portIndex) { + UNUSED(portIndex); + + if (mOutputPortSettingsChange != NONE) { + return; + } + + List &inQueue = getPortQueue(kInputPortIndex); + List &outQueue = getPortQueue(kOutputPortIndex); + + /* If input EOS is seen and decoder is not in flush mode, + * set the decoder in flush mode. + * There can be a case where EOS is sent along with last picture data + * In that case, only after decoding that input data, decoder has to be + * put in flush. This case is handled here */ + + if (mReceivedEOS && !mIsInFlush) { + setFlushMode(); + } + + while (!outQueue.empty()) { + BufferInfo *inInfo; + OMX_BUFFERHEADERTYPE *inHeader; + + BufferInfo *outInfo; + OMX_BUFFERHEADERTYPE *outHeader; + size_t timeStampIx; + + inInfo = NULL; + inHeader = NULL; + + if (!mIsInFlush) { + if (!inQueue.empty()) { + inInfo = *inQueue.begin(); + inHeader = inInfo->mHeader; + } else { + break; + } + } + + outInfo = *outQueue.begin(); + outHeader = outInfo->mHeader; + outHeader->nFlags = 0; + outHeader->nTimeStamp = 0; + outHeader->nOffset = 0; + + if (inHeader != NULL && (inHeader->nFlags & OMX_BUFFERFLAG_EOS)) { + mReceivedEOS = true; + if (inHeader->nFilledLen == 0) { + inQueue.erase(inQueue.begin()); + inInfo->mOwnedByUs = false; + notifyEmptyBufferDone(inHeader); + inHeader = NULL; + setFlushMode(); + } + } + + if (mInitNeeded && !mIsInFlush) { + bool portWillReset = false; + handlePortSettingsChange(&portWillReset, mNewWidth, mNewHeight); + + CHECK_EQ(reInitDecoder(), (status_t)OK); + return; + } + + /* Get a free slot in timestamp array to hold input timestamp */ + { + size_t i; + timeStampIx = 0; + for (i = 0; i < MAX_TIME_STAMPS; i++) { + if (!mTimeStampsValid[i]) { + timeStampIx = i; + break; + } + } + if (inHeader != NULL) { + mTimeStampsValid[timeStampIx] = true; + mTimeStamps[timeStampIx] = inHeader->nTimeStamp; + } + } + + { + ivd_video_decode_ip_t s_dec_ip; + ivd_video_decode_op_t s_dec_op; + + WORD32 timeDelay, timeTaken; + size_t sizeY, sizeUV; + + if (!setDecodeArgs(&s_dec_ip, &s_dec_op, inHeader, outHeader, timeStampIx)) { + ALOGE(""Decoder arg setup failed""); + notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); + return; + } + DUMP_TO_FILE(mInFile, s_dec_ip.pv_stream_buffer, s_dec_ip.u4_num_Bytes); + + if (s_dec_ip.u4_num_Bytes > 0) { + char *ptr = (char *)s_dec_ip.pv_stream_buffer; + } + + GETTIME(&mTimeStart, NULL); + /* Compute time elapsed between end of previous decode() + * to start of current decode() */ + TIME_DIFF(mTimeEnd, mTimeStart, timeDelay); + + IV_API_CALL_STATUS_T status; + status = ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op); + + bool unsupportedDimensions = (IMPEG2D_UNSUPPORTED_DIMENSIONS == s_dec_op.u4_error_code); + bool resChanged = (IVD_RES_CHANGED == (s_dec_op.u4_error_code & 0xFF)); + + GETTIME(&mTimeEnd, NULL); + /* Compute time taken for decode() */ + TIME_DIFF(mTimeStart, mTimeEnd, timeTaken); + + ALOGV(""timeTaken=%6d delay=%6d numBytes=%6d"", timeTaken, timeDelay, + s_dec_op.u4_num_bytes_consumed); + if (s_dec_op.u4_frame_decoded_flag && !mFlushNeeded) { + mFlushNeeded = true; + } + + if ((inHeader != NULL) && (1 != s_dec_op.u4_frame_decoded_flag)) { + /* If the input did not contain picture data, then ignore + * the associated timestamp */ + mTimeStampsValid[timeStampIx] = false; + } + + if (unsupportedDimensions && !mFlushNeeded) { + bool portWillReset = false; + handlePortSettingsChange(&portWillReset, s_dec_op.u4_pic_wd, s_dec_op.u4_pic_ht); + + + CHECK_EQ(reInitDecoder(), (status_t)OK); + + if (setDecodeArgs(&s_dec_ip, &s_dec_op, inHeader, outHeader, timeStampIx)) { + ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op); + } + return; + } + + if (mChangingResolution && !s_dec_op.u4_output_present) { + mChangingResolution = false; + resetDecoder(); + resetPlugin(); + continue; + } + + if (unsupportedDimensions || resChanged) { + mChangingResolution = true; + if (mFlushNeeded) { + setFlushMode(); + } + + if (unsupportedDimensions) { + mNewWidth = s_dec_op.u4_pic_wd; + mNewHeight = s_dec_op.u4_pic_ht; + mInitNeeded = true; + } + continue; + } + + if ((0 < s_dec_op.u4_pic_wd) && (0 < s_dec_op.u4_pic_ht)) { + uint32_t width = s_dec_op.u4_pic_wd; + uint32_t height = s_dec_op.u4_pic_ht; + bool portWillReset = false; + handlePortSettingsChange(&portWillReset, width, height); + + if (portWillReset) { + resetDecoder(); + return; + } + } + + if (s_dec_op.u4_output_present) { + size_t timeStampIdx; + outHeader->nFilledLen = (mWidth * mHeight * 3) / 2; + + timeStampIdx = getMinTimestampIdx(mTimeStamps, mTimeStampsValid); + outHeader->nTimeStamp = mTimeStamps[timeStampIdx]; + mTimeStampsValid[timeStampIdx] = false; + + /* mWaitForI waits for the first I picture. Once made FALSE, it + has to remain false till explicitly set to TRUE. */ + mWaitForI = mWaitForI && !(IV_I_FRAME == s_dec_op.e_pic_type); + + if (mWaitForI) { + s_dec_op.u4_output_present = false; + } else { + ALOGV(""Output timestamp: %lld, res: %ux%u"", + (long long)outHeader->nTimeStamp, mWidth, mHeight); + DUMP_TO_FILE(mOutFile, outHeader->pBuffer, outHeader->nFilledLen); + outInfo->mOwnedByUs = false; + outQueue.erase(outQueue.begin()); + outInfo = NULL; + notifyFillBufferDone(outHeader); + outHeader = NULL; + } + } else { + /* If in flush mode and no output is returned by the codec, + * then come out of flush mode */ + mIsInFlush = false; + + /* If EOS was recieved on input port and there is no output + * from the codec, then signal EOS on output port */ + if (mReceivedEOS) { + outHeader->nFilledLen = 0; + outHeader->nFlags |= OMX_BUFFERFLAG_EOS; + + outInfo->mOwnedByUs = false; + outQueue.erase(outQueue.begin()); + outInfo = NULL; + notifyFillBufferDone(outHeader); + outHeader = NULL; + resetPlugin(); + } + } + } + + if (inHeader != NULL) { + inInfo->mOwnedByUs = false; + inQueue.erase(inQueue.begin()); + inInfo = NULL; + notifyEmptyBufferDone(inHeader); + inHeader = NULL; + } + } +} +","@@ -466,7 +466,7 @@ + + return ret; + } + +-void SoftMPEG2::setDecodeArgs( ++bool SoftMPEG2::setDecodeArgs( + ivd_video_decode_ip_t *ps_dec_ip, + ivd_video_decode_op_t *ps_dec_op, + OMX_BUFFERHEADERTYPE *inHeader, +@@ -474,7 +474,6 @@ + + size_t timeStampIx) { + size_t sizeY = outputBufferWidth() * outputBufferHeight(); + size_t sizeUV; +- uint8_t *pBuf; + + ps_dec_ip->u4_size = sizeof(ivd_video_decode_ip_t); + ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); +@@ -494,22 +493,28 @@ + + ps_dec_ip->u4_num_Bytes = 0; + } + +- if (outHeader) { +- pBuf = outHeader->pBuffer; +- } else { +- pBuf = mFlushOutBuffer; +- } +- + sizeUV = sizeY / 4; + ps_dec_ip->s_out_buffer.u4_min_out_buf_size[0] = sizeY; + ps_dec_ip->s_out_buffer.u4_min_out_buf_size[1] = sizeUV; + ps_dec_ip->s_out_buffer.u4_min_out_buf_size[2] = sizeUV; + ++ uint8_t *pBuf; ++ if (outHeader) { ++ if (outHeader->nAllocLen < sizeY + (sizeUV * 2)) { ++ android_errorWriteLog(0x534e4554, ""27569635""); ++ return false; ++ } ++ pBuf = outHeader->pBuffer; ++ } else { ++ // mFlushOutBuffer always has the right size. ++ pBuf = mFlushOutBuffer; ++ } ++ + ps_dec_ip->s_out_buffer.pu1_bufs[0] = pBuf; + ps_dec_ip->s_out_buffer.pu1_bufs[1] = pBuf + sizeY; + ps_dec_ip->s_out_buffer.pu1_bufs[2] = pBuf + sizeY + sizeUV; + ps_dec_ip->s_out_buffer.u4_num_bufs = 3; +- return; ++ return true; + } + void SoftMPEG2::onPortFlushCompleted(OMX_U32 portIndex) { + /* Once the output buffers are flushed, ignore any buffers that are held in decoder */ +@@ -622,7 +627,11 @@ + + WORD32 timeDelay, timeTaken; + size_t sizeY, sizeUV; + +- setDecodeArgs(&s_dec_ip, &s_dec_op, inHeader, outHeader, timeStampIx); ++ if (!setDecodeArgs(&s_dec_ip, &s_dec_op, inHeader, outHeader, timeStampIx)) { ++ ALOGE(""Decoder arg setup failed""); ++ notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL); ++ return; ++ } + // If input dump is enabled, then write to file + DUMP_TO_FILE(mInFile, s_dec_ip.pv_stream_buffer, s_dec_ip.u4_num_Bytes); + +@@ -665,9 +674,9 @@ + + + CHECK_EQ(reInitDecoder(), (status_t)OK); + +- setDecodeArgs(&s_dec_ip, &s_dec_op, inHeader, outHeader, timeStampIx); +- +- ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op); ++ if (setDecodeArgs(&s_dec_ip, &s_dec_op, inHeader, outHeader, timeStampIx)) { ++ ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op); ++ } + return; + } + +",1695,2026,2048 +17006,"xsltGetTemplate(xsltTransformContextPtr ctxt, xmlNodePtr node, + xsltStylesheetPtr style) +{ + xsltStylesheetPtr curstyle; + xsltTemplatePtr ret = NULL; + const xmlChar *name = NULL; + xsltCompMatchPtr list = NULL; + float priority; + int keyed = 0; + + if ((ctxt == NULL) || (node == NULL)) + return(NULL); + + if (style == NULL) { + curstyle = ctxt->style; + } else { + curstyle = xsltNextImport(style); + } + + while ((curstyle != NULL) && (curstyle != style)) { + priority = XSLT_PAT_NO_PRIORITY; + /* TODO : handle IDs/keys here ! */ + if (curstyle->templatesHash != NULL) { + /* + * Use the top name as selector + */ + switch (node->type) { + case XML_ELEMENT_NODE: + if (node->name[0] == ' ') + break; + case XML_ATTRIBUTE_NODE: + case XML_PI_NODE: + name = node->name; + break; + case XML_DOCUMENT_NODE: + case XML_HTML_DOCUMENT_NODE: + case XML_TEXT_NODE: + case XML_CDATA_SECTION_NODE: + case XML_COMMENT_NODE: + case XML_ENTITY_REF_NODE: + case XML_ENTITY_NODE: + case XML_DOCUMENT_TYPE_NODE: + case XML_DOCUMENT_FRAG_NODE: + case XML_NOTATION_NODE: + case XML_DTD_NODE: + case XML_ELEMENT_DECL: + case XML_ATTRIBUTE_DECL: + case XML_ENTITY_DECL: + case XML_NAMESPACE_DECL: + case XML_XINCLUDE_START: + case XML_XINCLUDE_END: + break; + default: + return(NULL); + + } + } + if (name != NULL) { + /* + * find the list of applicable expressions based on the name + */ + list = (xsltCompMatchPtr) xmlHashLookup3(curstyle->templatesHash, + name, ctxt->mode, ctxt->modeURI); + } else + list = NULL; + while (list != NULL) { + if (xsltTestCompMatch(ctxt, list, node, + ctxt->mode, ctxt->modeURI)) { + ret = list->template; + priority = list->priority; + break; + } + list = list->next; + } + list = NULL; + + /* + * find alternate generic matches + */ + switch (node->type) { + case XML_ELEMENT_NODE: + if (node->name[0] == ' ') + list = curstyle->rootMatch; + else + list = curstyle->elemMatch; + if (node->psvi != NULL) keyed = 1; + break; + case XML_ATTRIBUTE_NODE: { + xmlAttrPtr attr; + + list = curstyle->attrMatch; + attr = (xmlAttrPtr) node; + if (attr->psvi != NULL) keyed = 1; + break; + } + case XML_PI_NODE: + list = curstyle->piMatch; + if (node->psvi != NULL) keyed = 1; + break; + case XML_DOCUMENT_NODE: + case XML_HTML_DOCUMENT_NODE: { + xmlDocPtr doc; + + list = curstyle->rootMatch; + doc = (xmlDocPtr) node; + if (doc->psvi != NULL) keyed = 1; + break; + } + case XML_TEXT_NODE: + case XML_CDATA_SECTION_NODE: + list = curstyle->textMatch; + if (node->psvi != NULL) keyed = 1; + break; + case XML_COMMENT_NODE: + list = curstyle->commentMatch; + if (node->psvi != NULL) keyed = 1; + break; + case XML_ENTITY_REF_NODE: + case XML_ENTITY_NODE: + case XML_DOCUMENT_TYPE_NODE: + case XML_DOCUMENT_FRAG_NODE: + case XML_NOTATION_NODE: + case XML_DTD_NODE: + case XML_ELEMENT_DECL: + case XML_ATTRIBUTE_DECL: + case XML_ENTITY_DECL: + case XML_NAMESPACE_DECL: + case XML_XINCLUDE_START: + case XML_XINCLUDE_END: + break; + default: + break; + } + while ((list != NULL) && + ((ret == NULL) || (list->priority > priority))) { + if (xsltTestCompMatch(ctxt, list, node, + ctxt->mode, ctxt->modeURI)) { + ret = list->template; + priority = list->priority; + break; + } + list = list->next; + } + /* + * Some of the tests for elements can also apply to documents + */ + if ((node->type == XML_DOCUMENT_NODE) || + (node->type == XML_HTML_DOCUMENT_NODE) || + (node->type == XML_TEXT_NODE)) { + list = curstyle->elemMatch; + while ((list != NULL) && + ((ret == NULL) || (list->priority > priority))) { + if (xsltTestCompMatch(ctxt, list, node, + ctxt->mode, ctxt->modeURI)) { + ret = list->template; + priority = list->priority; + break; + } + list = list->next; + } + } else if ((node->type == XML_PI_NODE) || + (node->type == XML_COMMENT_NODE)) { + list = curstyle->elemMatch; + while ((list != NULL) && + ((ret == NULL) || (list->priority > priority))) { + if (xsltTestCompMatch(ctxt, list, node, + ctxt->mode, ctxt->modeURI)) { + ret = list->template; + priority = list->priority; + break; + } + list = list->next; + } + } + +keyed_match: + if (keyed) { + list = curstyle->keyMatch; + while ((list != NULL) && + ((ret == NULL) || (list->priority > priority))) { + if (xsltTestCompMatch(ctxt, list, node, + ctxt->mode, ctxt->modeURI)) { + ret = list->template; + priority = list->priority; + break; + } + list = list->next; + } + } + else if (ctxt->hasTemplKeyPatterns && + ((ctxt->document == NULL) || + (ctxt->document->nbKeysComputed < ctxt->nbKeys))) + { + /* + * Compute all remaining keys for this document. + * + * REVISIT TODO: I think this could be further optimized. + */ + if (xsltComputeAllKeys(ctxt, node) == -1) + goto error; + + switch (node->type) { + case XML_ELEMENT_NODE: + if (node->psvi != NULL) keyed = 1; + break; + case XML_ATTRIBUTE_NODE: + if (((xmlAttrPtr) node)->psvi != NULL) keyed = 1; + break; + case XML_TEXT_NODE: + case XML_CDATA_SECTION_NODE: + case XML_COMMENT_NODE: + case XML_PI_NODE: + if (node->psvi != NULL) keyed = 1; + break; + case XML_DOCUMENT_NODE: + case XML_HTML_DOCUMENT_NODE: + if (((xmlDocPtr) node)->psvi != NULL) keyed = 1; + break; + default: + break; + } + if (keyed) + goto keyed_match; + } + if (ret != NULL) + return(ret); + + /* + * Cycle on next curstylesheet import. + */ + curstyle = xsltNextImport(curstyle); + } + +error: + return(NULL); +} +",0,"xsltGetTemplate(xsltTransformContextPtr ctxt, xmlNodePtr node, + xsltStylesheetPtr style) +{ + xsltStylesheetPtr curstyle; + xsltTemplatePtr ret = NULL; + const xmlChar *name = NULL; + xsltCompMatchPtr list = NULL; + float priority; + int keyed = 0; + + if ((ctxt == NULL) || (node == NULL)) + return(NULL); + + if (style == NULL) { + curstyle = ctxt->style; + } else { + curstyle = xsltNextImport(style); + } + + while ((curstyle != NULL) && (curstyle != style)) { + priority = XSLT_PAT_NO_PRIORITY; + /* TODO : handle IDs/keys here ! */ + if (curstyle->templatesHash != NULL) { + /* + * Use the top name as selector + */ + switch (node->type) { + case XML_ELEMENT_NODE: + if (node->name[0] == ' ') + break; + case XML_ATTRIBUTE_NODE: + case XML_PI_NODE: + name = node->name; + break; + case XML_DOCUMENT_NODE: + case XML_HTML_DOCUMENT_NODE: + case XML_TEXT_NODE: + case XML_CDATA_SECTION_NODE: + case XML_COMMENT_NODE: + case XML_ENTITY_REF_NODE: + case XML_ENTITY_NODE: + case XML_DOCUMENT_TYPE_NODE: + case XML_DOCUMENT_FRAG_NODE: + case XML_NOTATION_NODE: + case XML_DTD_NODE: + case XML_ELEMENT_DECL: + case XML_ATTRIBUTE_DECL: + case XML_ENTITY_DECL: + case XML_NAMESPACE_DECL: + case XML_XINCLUDE_START: + case XML_XINCLUDE_END: + break; + default: + return(NULL); + + } + } + if (name != NULL) { + /* + * find the list of applicable expressions based on the name + */ + list = (xsltCompMatchPtr) xmlHashLookup3(curstyle->templatesHash, + name, ctxt->mode, ctxt->modeURI); + } else + list = NULL; + while (list != NULL) { + if (xsltTestCompMatch(ctxt, list, node, + ctxt->mode, ctxt->modeURI)) { + ret = list->template; + priority = list->priority; + break; + } + list = list->next; + } + list = NULL; + + /* + * find alternate generic matches + */ + switch (node->type) { + case XML_ELEMENT_NODE: + if (node->name[0] == ' ') + list = curstyle->rootMatch; + else + list = curstyle->elemMatch; + if (node->psvi != NULL) keyed = 1; + break; + case XML_ATTRIBUTE_NODE: { + xmlAttrPtr attr; + + list = curstyle->attrMatch; + attr = (xmlAttrPtr) node; + if (attr->psvi != NULL) keyed = 1; + break; + } + case XML_PI_NODE: + list = curstyle->piMatch; + if (node->psvi != NULL) keyed = 1; + break; + case XML_DOCUMENT_NODE: + case XML_HTML_DOCUMENT_NODE: { + xmlDocPtr doc; + + list = curstyle->rootMatch; + doc = (xmlDocPtr) node; + if (doc->psvi != NULL) keyed = 1; + break; + } + case XML_TEXT_NODE: + case XML_CDATA_SECTION_NODE: + list = curstyle->textMatch; + if (node->psvi != NULL) keyed = 1; + break; + case XML_COMMENT_NODE: + list = curstyle->commentMatch; + if (node->psvi != NULL) keyed = 1; + break; + case XML_ENTITY_REF_NODE: + case XML_ENTITY_NODE: + case XML_DOCUMENT_TYPE_NODE: + case XML_DOCUMENT_FRAG_NODE: + case XML_NOTATION_NODE: + case XML_DTD_NODE: + case XML_ELEMENT_DECL: + case XML_ATTRIBUTE_DECL: + case XML_ENTITY_DECL: + case XML_NAMESPACE_DECL: + case XML_XINCLUDE_START: + case XML_XINCLUDE_END: + break; + default: + break; + } + while ((list != NULL) && + ((ret == NULL) || (list->priority > priority))) { + if (xsltTestCompMatch(ctxt, list, node, + ctxt->mode, ctxt->modeURI)) { + ret = list->template; + priority = list->priority; + break; + } + list = list->next; + } + /* + * Some of the tests for elements can also apply to documents + */ + if ((node->type == XML_DOCUMENT_NODE) || + (node->type == XML_HTML_DOCUMENT_NODE) || + (node->type == XML_TEXT_NODE)) { + list = curstyle->elemMatch; + while ((list != NULL) && + ((ret == NULL) || (list->priority > priority))) { + if (xsltTestCompMatch(ctxt, list, node, + ctxt->mode, ctxt->modeURI)) { + ret = list->template; + priority = list->priority; + break; + } + list = list->next; + } + } else if ((node->type == XML_PI_NODE) || + (node->type == XML_COMMENT_NODE)) { + list = curstyle->elemMatch; + while ((list != NULL) && + ((ret == NULL) || (list->priority > priority))) { + if (xsltTestCompMatch(ctxt, list, node, + ctxt->mode, ctxt->modeURI)) { + ret = list->template; + priority = list->priority; + break; + } + list = list->next; + } + } + +keyed_match: + if (keyed) { + list = curstyle->keyMatch; + while ((list != NULL) && + ((ret == NULL) || (list->priority > priority))) { + if (xsltTestCompMatch(ctxt, list, node, + ctxt->mode, ctxt->modeURI)) { + ret = list->template; + priority = list->priority; + break; + } + list = list->next; + } + } + else if (ctxt->hasTemplKeyPatterns && + ((ctxt->document == NULL) || + (ctxt->document->nbKeysComputed < ctxt->nbKeys))) + { + /* + * Compute all remaining keys for this document. + * + * REVISIT TODO: I think this could be further optimized. + */ + if (xsltComputeAllKeys(ctxt, node) == -1) + goto error; + + switch (node->type) { + case XML_ELEMENT_NODE: + if (node->psvi != NULL) keyed = 1; + break; + case XML_ATTRIBUTE_NODE: + if (((xmlAttrPtr) node)->psvi != NULL) keyed = 1; + break; + case XML_TEXT_NODE: + case XML_CDATA_SECTION_NODE: + case XML_COMMENT_NODE: + case XML_PI_NODE: + if (node->psvi != NULL) keyed = 1; + break; + case XML_DOCUMENT_NODE: + case XML_HTML_DOCUMENT_NODE: + if (((xmlDocPtr) node)->psvi != NULL) keyed = 1; + break; + default: + break; + } + if (keyed) + goto keyed_match; + } + if (ret != NULL) + return(ret); + + /* + * Cycle on next curstylesheet import. + */ + curstyle = xsltNextImport(curstyle); + } + +error: + return(NULL); +} +","@@ -451,11 +451,14 @@ xsltReverseCompMatch(xsltParserContextPtr ctxt, xsltCompMatchPtr comp) { + xsltCompMatchAdd(ctxt, comp, XSLT_OP_END, NULL, NULL, 0); + + /* +- * detect consecutive XSLT_OP_PREDICATE indicating a direct +- * matching should be done. ++ * Detect consecutive XSLT_OP_PREDICATE and predicates on ops which ++ * haven't been optimized yet indicating a direct matching should be done. + */ + for (i = 0;i < comp->nbStep - 1;i++) { +- if ((comp->steps[i].op == XSLT_OP_PREDICATE) && ++ xsltOp op = comp->steps[i].op; ++ ++ if ((op != XSLT_OP_ELEM) && ++ (op != XSLT_OP_ALL) && + (comp->steps[i + 1].op == XSLT_OP_PREDICATE)) { + + comp->direct = 1; +@@ -620,6 +623,280 @@ xsltTestCompMatchDirect(xsltTransformContextPtr ctxt, xsltCompMatchPtr comp, + return(0); + } + ++/** ++ * xsltTestPredicateMatch: ++ * @ctxt: a XSLT process context ++ * @comp: the precompiled pattern ++ * @node: a node ++ * @step: the predicate step ++ * @sel: the previous step ++ * ++ * Test whether the node matches the predicate ++ * ++ * Returns 1 if it matches, 0 if it doesn't and -1 in case of failure ++ */ ++static int ++xsltTestPredicateMatch(xsltTransformContextPtr ctxt, xsltCompMatchPtr comp, ++ xmlNodePtr node, xsltStepOpPtr step, ++ xsltStepOpPtr sel) { ++ xmlNodePtr oldNode; ++ xmlDocPtr doc; ++ int oldCS, oldCP; ++ int pos = 0, len = 0; ++ int isRVT; ++ int match; ++ ++ if (step->value == NULL) ++ return(0); ++ if (step->comp == NULL) ++ return(0); ++ ++ doc = node->doc; ++ if (XSLT_IS_RES_TREE_FRAG(doc)) ++ isRVT = 1; ++ else ++ isRVT = 0; ++ ++ /* ++ * Recompute contextSize and proximityPosition. ++ * ++ * TODO: Make this work for additional ops. Currently, only XSLT_OP_ELEM ++ * and XSLT_OP_ALL are supported. ++ */ ++ oldCS = ctxt->xpathCtxt->contextSize; ++ oldCP = ctxt->xpathCtxt->proximityPosition; ++ if ((sel != NULL) && ++ (sel->op == XSLT_OP_ELEM) && ++ (sel->value != NULL) && ++ (node->type == XML_ELEMENT_NODE) && ++ (node->parent != NULL)) { ++ xmlNodePtr previous; ++ int nocache = 0; ++ ++ previous = (xmlNodePtr) ++ XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr); ++ if ((previous != NULL) && ++ (previous->parent == node->parent)) { ++ /* ++ * just walk back to adjust the index ++ */ ++ int indx = 0; ++ xmlNodePtr sibling = node; ++ ++ while (sibling != NULL) { ++ if (sibling == previous) ++ break; ++ if ((sibling->type == XML_ELEMENT_NODE) && ++ (previous->name != NULL) && ++ (sibling->name != NULL) && ++ (previous->name[0] == sibling->name[0]) && ++ (xmlStrEqual(previous->name, sibling->name))) ++ { ++ if ((sel->value2 == NULL) || ++ ((sibling->ns != NULL) && ++ (xmlStrEqual(sel->value2, sibling->ns->href)))) ++ indx++; ++ } ++ sibling = sibling->prev; ++ } ++ if (sibling == NULL) { ++ /* hum going backward in document order ... */ ++ indx = 0; ++ sibling = node; ++ while (sibling != NULL) { ++ if (sibling == previous) ++ break; ++ if ((sibling->type == XML_ELEMENT_NODE) && ++ (previous->name != NULL) && ++ (sibling->name != NULL) && ++ (previous->name[0] == sibling->name[0]) && ++ (xmlStrEqual(previous->name, sibling->name))) ++ { ++ if ((sel->value2 == NULL) || ++ ((sibling->ns != NULL) && ++ (xmlStrEqual(sel->value2, ++ sibling->ns->href)))) ++ { ++ indx--; ++ } ++ } ++ sibling = sibling->next; ++ } ++ } ++ if (sibling != NULL) { ++ pos = XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) + indx; ++ /* ++ * If the node is in a Value Tree we need to ++ * save len, but cannot cache the node! ++ * (bugs 153137 and 158840) ++ */ ++ if (node->doc != NULL) { ++ len = XSLT_RUNTIME_EXTRA(ctxt, sel->lenExtra, ival); ++ if (!isRVT) { ++ XSLT_RUNTIME_EXTRA(ctxt, ++ sel->previousExtra, ptr) = node; ++ XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) = pos; ++ } ++ } ++ } else ++ pos = 0; ++ } else { ++ /* ++ * recompute the index ++ */ ++ xmlNodePtr parent = node->parent; ++ xmlNodePtr siblings = NULL; ++ ++ if (parent) siblings = parent->children; ++ ++ while (siblings != NULL) { ++ if (siblings->type == XML_ELEMENT_NODE) { ++ if (siblings == node) { ++ len++; ++ pos = len; ++ } else if ((node->name != NULL) && ++ (siblings->name != NULL) && ++ (node->name[0] == siblings->name[0]) && ++ (xmlStrEqual(node->name, siblings->name))) { ++ if ((sel->value2 == NULL) || ++ ((siblings->ns != NULL) && ++ (xmlStrEqual(sel->value2, siblings->ns->href)))) ++ len++; ++ } ++ } ++ siblings = siblings->next; ++ } ++ if ((parent == NULL) || (node->doc == NULL)) ++ nocache = 1; ++ else { ++ while (parent->parent != NULL) ++ parent = parent->parent; ++ if (((parent->type != XML_DOCUMENT_NODE) && ++ (parent->type != XML_HTML_DOCUMENT_NODE)) || ++ (parent != (xmlNodePtr) node->doc)) ++ nocache = 1; ++ } ++ } ++ if (pos != 0) { ++ ctxt->xpathCtxt->contextSize = len; ++ ctxt->xpathCtxt->proximityPosition = pos; ++ /* ++ * If the node is in a Value Tree we cannot ++ * cache it ! ++ */ ++ if ((!isRVT) && (node->doc != NULL) && ++ (nocache == 0)) { ++ XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr) = node; ++ XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) = pos; ++ XSLT_RUNTIME_EXTRA(ctxt, sel->lenExtra, ival) = len; ++ } ++ } ++ } else if ((sel != NULL) && (sel->op == XSLT_OP_ALL) && ++ (node->type == XML_ELEMENT_NODE)) { ++ xmlNodePtr previous; ++ int nocache = 0; ++ ++ previous = (xmlNodePtr) ++ XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr); ++ if ((previous != NULL) && ++ (previous->parent == node->parent)) { ++ /* ++ * just walk back to adjust the index ++ */ ++ int indx = 0; ++ xmlNodePtr sibling = node; ++ ++ while (sibling != NULL) { ++ if (sibling == previous) ++ break; ++ if (sibling->type == XML_ELEMENT_NODE) ++ indx++; ++ sibling = sibling->prev; ++ } ++ if (sibling == NULL) { ++ /* hum going backward in document order ... */ ++ indx = 0; ++ sibling = node; ++ while (sibling != NULL) { ++ if (sibling == previous) ++ break; ++ if (sibling->type == XML_ELEMENT_NODE) ++ indx--; ++ sibling = sibling->next; ++ } ++ } ++ if (sibling != NULL) { ++ pos = XSLT_RUNTIME_EXTRA(ctxt, ++ sel->indexExtra, ival) + indx; ++ /* ++ * If the node is in a Value Tree we cannot ++ * cache it ! ++ */ ++ if ((node->doc != NULL) && !isRVT) { ++ len = XSLT_RUNTIME_EXTRA(ctxt, sel->lenExtra, ival); ++ XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr) = node; ++ XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) = pos; ++ } ++ } else ++ pos = 0; ++ } else { ++ /* ++ * recompute the index ++ */ ++ xmlNodePtr parent = node->parent; ++ xmlNodePtr siblings = NULL; ++ ++ if (parent) siblings = parent->children; ++ ++ while (siblings != NULL) { ++ if (siblings->type == XML_ELEMENT_NODE) { ++ len++; ++ if (siblings == node) { ++ pos = len; ++ } ++ } ++ siblings = siblings->next; ++ } ++ if ((parent == NULL) || (node->doc == NULL)) ++ nocache = 1; ++ else { ++ while (parent->parent != NULL) ++ parent = parent->parent; ++ if (((parent->type != XML_DOCUMENT_NODE) && ++ (parent->type != XML_HTML_DOCUMENT_NODE)) || ++ (parent != (xmlNodePtr) node->doc)) ++ nocache = 1; ++ } ++ } ++ if (pos != 0) { ++ ctxt->xpathCtxt->contextSize = len; ++ ctxt->xpathCtxt->proximityPosition = pos; ++ /* ++ * If the node is in a Value Tree we cannot ++ * cache it ! ++ */ ++ if ((node->doc != NULL) && (nocache == 0) && !isRVT) { ++ XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr) = node; ++ XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) = pos; ++ XSLT_RUNTIME_EXTRA(ctxt, sel->lenExtra, ival) = len; ++ } ++ } ++ } ++ ++ oldNode = ctxt->node; ++ ctxt->node = node; ++ ++ match = xsltEvalXPathPredicate(ctxt, step->comp, comp->nsList, comp->nsNr); ++ ++ if (pos != 0) { ++ ctxt->xpathCtxt->contextSize = oldCS; ++ ctxt->xpathCtxt->proximityPosition = oldCP; ++ } ++ ctxt->node = oldNode; ++ ++ return match; ++} ++ + /** + * xsltTestCompMatch: + * @ctxt: a XSLT process context +@@ -634,9 +911,10 @@ xsltTestCompMatchDirect(xsltTransformContextPtr ctxt, xsltCompMatchPtr comp, + */ + static int + xsltTestCompMatch(xsltTransformContextPtr ctxt, xsltCompMatchPtr comp, +- xmlNodePtr node, const xmlChar *mode, ++ xmlNodePtr matchNode, const xmlChar *mode, + const xmlChar *modeURI) { + int i; ++ xmlNodePtr node = matchNode; + xsltStepOpPtr step, sel = NULL; + xsltStepStates states = {0, 0, NULL}; /* // may require backtrack */ + +@@ -854,14 +1132,9 @@ xsltTestCompMatch(xsltTransformContextPtr ctxt, xsltCompMatchPtr comp, + goto rollback; + break; + case XSLT_OP_PREDICATE: { +- xmlNodePtr oldNode; +- xmlDocPtr doc; +- int oldCS, oldCP; +- int pos = 0, len = 0; +- int isRVT; +- + /* +- * when there is cascading XSLT_OP_PREDICATE, then use a ++ * When there is cascading XSLT_OP_PREDICATE or a predicate ++ * after an op which hasn't been optimized yet, then use a + * direct computation approach. It's not done directly + * at the beginning of the routine to filter out as much + * as possible this costly computation. +@@ -871,278 +1144,14 @@ xsltTestCompMatch(xsltTransformContextPtr ctxt, xsltCompMatchPtr comp, + /* Free the rollback states */ + xmlFree(states.states); + } +- return(xsltTestCompMatchDirect(ctxt, comp, node, ++ return(xsltTestCompMatchDirect(ctxt, comp, matchNode, + comp->nsList, comp->nsNr)); + } + +- doc = node->doc; +- if (XSLT_IS_RES_TREE_FRAG(doc)) +- isRVT = 1; +- else +- isRVT = 0; +- +- /* +- * Depending on the last selection, one may need to +- * recompute contextSize and proximityPosition. +- */ +- oldCS = ctxt->xpathCtxt->contextSize; +- oldCP = ctxt->xpathCtxt->proximityPosition; +- if ((sel != NULL) && +- (sel->op == XSLT_OP_ELEM) && +- (sel->value != NULL) && +- (node->type == XML_ELEMENT_NODE) && +- (node->parent != NULL)) { +- xmlNodePtr previous; +- int nocache = 0; +- +- previous = (xmlNodePtr) +- XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr); +- if ((previous != NULL) && +- (previous->parent == node->parent)) { +- /* +- * just walk back to adjust the index +- */ +- int indx = 0; +- xmlNodePtr sibling = node; +- +- while (sibling != NULL) { +- if (sibling == previous) +- break; +- if ((sibling->type == XML_ELEMENT_NODE) && +- (previous->name != NULL) && +- (sibling->name != NULL) && +- (previous->name[0] == sibling->name[0]) && +- (xmlStrEqual(previous->name, sibling->name))) +- { +- if ((sel->value2 == NULL) || +- ((sibling->ns != NULL) && +- (xmlStrEqual(sel->value2, +- sibling->ns->href)))) +- indx++; +- } +- sibling = sibling->prev; +- } +- if (sibling == NULL) { +- /* hum going backward in document order ... */ +- indx = 0; +- sibling = node; +- while (sibling != NULL) { +- if (sibling == previous) +- break; +- if ((sibling->type == XML_ELEMENT_NODE) && +- (previous->name != NULL) && +- (sibling->name != NULL) && +- (previous->name[0] == sibling->name[0]) && +- (xmlStrEqual(previous->name, sibling->name))) +- { +- if ((sel->value2 == NULL) || +- ((sibling->ns != NULL) && +- (xmlStrEqual(sel->value2, +- sibling->ns->href)))) +- { +- indx--; +- } +- } +- sibling = sibling->next; +- } +- } +- if (sibling != NULL) { +- pos = XSLT_RUNTIME_EXTRA(ctxt, +- sel->indexExtra, ival) + indx; +- /* +- * If the node is in a Value Tree we need to +- * save len, but cannot cache the node! +- * (bugs 153137 and 158840) +- */ +- if (node->doc != NULL) { +- len = XSLT_RUNTIME_EXTRA(ctxt, +- sel->lenExtra, ival); +- if (!isRVT) { +- XSLT_RUNTIME_EXTRA(ctxt, +- sel->previousExtra, ptr) = node; +- XSLT_RUNTIME_EXTRA(ctxt, +- sel->indexExtra, ival) = pos; +- } +- } +- } else +- pos = 0; +- } else { +- /* +- * recompute the index +- */ +- xmlNodePtr parent = node->parent; +- xmlNodePtr siblings = NULL; +- +- if (parent) siblings = parent->children; +- +- while (siblings != NULL) { +- if (siblings->type == XML_ELEMENT_NODE) { +- if (siblings == node) { +- len++; +- pos = len; +- } else if ((node->name != NULL) && +- (siblings->name != NULL) && +- (node->name[0] == siblings->name[0]) && +- (xmlStrEqual(node->name, siblings->name))) { +- if ((sel->value2 == NULL) || +- ((siblings->ns != NULL) && +- (xmlStrEqual(sel->value2, +- siblings->ns->href)))) +- len++; +- } +- } +- siblings = siblings->next; +- } +- if ((parent == NULL) || (node->doc == NULL)) +- nocache = 1; +- else { +- while (parent->parent != NULL) +- parent = parent->parent; +- if (((parent->type != XML_DOCUMENT_NODE) && +- (parent->type != XML_HTML_DOCUMENT_NODE)) || +- (parent != (xmlNodePtr) node->doc)) +- nocache = 1; +- } +- } +- if (pos != 0) { +- ctxt->xpathCtxt->contextSize = len; +- ctxt->xpathCtxt->proximityPosition = pos; +- /* +- * If the node is in a Value Tree we cannot +- * cache it ! +- */ +- if ((!isRVT) && (node->doc != NULL) && +- (nocache == 0)) { +- XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr) = +- node; +- XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) = +- pos; +- XSLT_RUNTIME_EXTRA(ctxt, sel->lenExtra, ival) = +- len; +- } +- } +- } else if ((sel != NULL) && (sel->op == XSLT_OP_ALL) && +- (node->type == XML_ELEMENT_NODE)) { +- xmlNodePtr previous; +- int nocache = 0; +- +- previous = (xmlNodePtr) +- XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr); +- if ((previous != NULL) && +- (previous->parent == node->parent)) { +- /* +- * just walk back to adjust the index +- */ +- int indx = 0; +- xmlNodePtr sibling = node; +- +- while (sibling != NULL) { +- if (sibling == previous) +- break; +- if (sibling->type == XML_ELEMENT_NODE) +- indx++; +- sibling = sibling->prev; +- } +- if (sibling == NULL) { +- /* hum going backward in document order ... */ +- indx = 0; +- sibling = node; +- while (sibling != NULL) { +- if (sibling == previous) +- break; +- if (sibling->type == XML_ELEMENT_NODE) +- indx--; +- sibling = sibling->next; +- } +- } +- if (sibling != NULL) { +- pos = XSLT_RUNTIME_EXTRA(ctxt, +- sel->indexExtra, ival) + indx; +- /* +- * If the node is in a Value Tree we cannot +- * cache it ! +- */ +- if ((node->doc != NULL) && !isRVT) { +- len = XSLT_RUNTIME_EXTRA(ctxt, +- sel->lenExtra, ival); +- XSLT_RUNTIME_EXTRA(ctxt, +- sel->previousExtra, ptr) = node; +- XSLT_RUNTIME_EXTRA(ctxt, +- sel->indexExtra, ival) = pos; +- } +- } else +- pos = 0; +- } else { +- /* +- * recompute the index +- */ +- xmlNodePtr parent = node->parent; +- xmlNodePtr siblings = NULL; +- +- if (parent) siblings = parent->children; +- +- while (siblings != NULL) { +- if (siblings->type == XML_ELEMENT_NODE) { +- len++; +- if (siblings == node) { +- pos = len; +- } +- } +- siblings = siblings->next; +- } +- if ((parent == NULL) || (node->doc == NULL)) +- nocache = 1; +- else { +- while (parent->parent != NULL) +- parent = parent->parent; +- if (((parent->type != XML_DOCUMENT_NODE) && +- (parent->type != XML_HTML_DOCUMENT_NODE)) || +- (parent != (xmlNodePtr) node->doc)) +- nocache = 1; +- } +- } +- if (pos != 0) { +- ctxt->xpathCtxt->contextSize = len; +- ctxt->xpathCtxt->proximityPosition = pos; +- /* +- * If the node is in a Value Tree we cannot +- * cache it ! +- */ +- if ((node->doc != NULL) && (nocache == 0) && !isRVT) { +- XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr) = +- node; +- XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) = +- pos; +- XSLT_RUNTIME_EXTRA(ctxt, sel->lenExtra, ival) = +- len; +- } +- } +- } +- oldNode = ctxt->node; +- ctxt->node = node; +- +- if (step->value == NULL) +- goto wrong_index; +- if (step->comp == NULL) +- goto wrong_index; +- +- if (!xsltEvalXPathPredicate(ctxt, step->comp, comp->nsList, +- comp->nsNr)) +- goto wrong_index; ++ if (!xsltTestPredicateMatch(ctxt, comp, node, step, sel)) ++ goto rollback; + +- if (pos != 0) { +- ctxt->xpathCtxt->contextSize = oldCS; +- ctxt->xpathCtxt->proximityPosition = oldCP; +- } +- ctxt->node = oldNode; + break; +-wrong_index: +- if (pos != 0) { +- ctxt->xpathCtxt->contextSize = oldCS; +- ctxt->xpathCtxt->proximityPosition = oldCP; +- } +- ctxt->node = oldNode; +- goto rollback; + } + case XSLT_OP_PI: + if (node->type != XML_PI_NODE) +@@ -1424,6 +1433,7 @@ xsltCompileIdKeyPattern(xsltParserContextPtr ctxt, xmlChar *name, + if (CUR != ',') { + xsltTransformError(NULL, NULL, NULL, + ""xsltCompileIdKeyPattern : , expected\n""); ++ xmlFree(lit); + ctxt->error = 1; + return; + } +@@ -2080,9 +2090,34 @@ xsltAddTemplate(xsltStylesheetPtr style, xsltTemplatePtr cur, + const xmlChar *name = NULL; + float priority; /* the priority */ + +- if ((style == NULL) || (cur == NULL) || (cur->match == NULL)) ++ if ((style == NULL) || (cur == NULL)) + return(-1); + ++ /* Register named template */ ++ if (cur->name != NULL) { ++ if (style->namedTemplates == NULL) { ++ style->namedTemplates = xmlHashCreate(10); ++ if (style->namedTemplates == NULL) ++ return(-1); ++ } ++ else { ++ void *dup = xmlHashLookup2(style->namedTemplates, cur->name, ++ cur->nameURI); ++ if (dup != NULL) { ++ xsltTransformError(NULL, style, NULL, ++ ""xsl:template: error duplicate name '%s'\n"", ++ cur->name); ++ style->errors++; ++ return(-1); ++ } ++ } ++ ++ xmlHashAddEntry2(style->namedTemplates, cur->name, cur->nameURI, cur); ++ } ++ ++ if (cur->match == NULL) ++ return(0); ++ + priority = cur->priority; + pat = xsltCompilePatternInternal(cur->match, style->doc, cur->elem, + style, NULL, 1); +@@ -2552,5 +2587,7 @@ xsltFreeTemplateHashes(xsltStylesheetPtr style) { + xsltFreeCompMatchList(style->piMatch); + if (style->commentMatch != NULL) + xsltFreeCompMatchList(style->commentMatch); ++ if (style->namedTemplates != NULL) ++ xmlHashFree(style->namedTemplates, NULL); + } + ",1600,1931,2048 +6131,"static int asf_read_picture(AVFormatContext *s, int len) +{ + AVPacket pkt = { 0 }; + const CodecMime *mime = ff_id3v2_mime_tags; + enum AVCodecID id = AV_CODEC_ID_NONE; + char mimetype[64]; + uint8_t *desc = NULL; + AVStream *st = NULL; + int ret, type, picsize, desc_len; + + /* type + picsize + mime + desc */ + if (len < 1 + 4 + 2 + 2) { + av_log(s, AV_LOG_ERROR, ""Invalid attached picture size: %d.\n"", len); + return AVERROR_INVALIDDATA; + } + + /* picture type */ + type = avio_r8(s->pb); + len--; + if (type >= FF_ARRAY_ELEMS(ff_id3v2_picture_types) || type < 0) { + av_log(s, AV_LOG_WARNING, ""Unknown attached picture type: %d.\n"", type); + type = 0; + } + + /* picture data size */ + picsize = avio_rl32(s->pb); + len -= 4; + + /* picture MIME type */ + len -= avio_get_str16le(s->pb, len, mimetype, sizeof(mimetype)); + while (mime->id != AV_CODEC_ID_NONE) { + if (!strncmp(mime->str, mimetype, sizeof(mimetype))) { + id = mime->id; + break; + } + mime++; + } + if (id == AV_CODEC_ID_NONE) { + av_log(s, AV_LOG_ERROR, ""Unknown attached picture mimetype: %s.\n"", + mimetype); + return 0; + } + + if (picsize >= len) { + av_log(s, AV_LOG_ERROR, ""Invalid attached picture data size: %d >= %d.\n"", + picsize, len); + return AVERROR_INVALIDDATA; + } + + /* picture description */ + desc_len = (len - picsize) * 2 + 1; + desc = av_malloc(desc_len); + if (!desc) + return AVERROR(ENOMEM); + len -= avio_get_str16le(s->pb, len - picsize, desc, desc_len); + + ret = av_get_packet(s->pb, &pkt, picsize); + if (ret < 0) + goto fail; + + st = avformat_new_stream(s, NULL); + if (!st) { + ret = AVERROR(ENOMEM); + goto fail; + } + st->disposition |= AV_DISPOSITION_ATTACHED_PIC; + st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; + st->codecpar->codec_id = id; + st->attached_pic = pkt; + st->attached_pic.stream_index = st->index; + st->attached_pic.flags |= AV_PKT_FLAG_KEY; + + if (*desc) + av_dict_set(&st->metadata, ""title"", desc, AV_DICT_DONT_STRDUP_VAL); + else + av_freep(&desc); + + av_dict_set(&st->metadata, ""comment"", ff_id3v2_picture_types[type], 0); + + return 0; + +fail: + av_freep(&desc); + av_packet_unref(&pkt); + return ret; +} +",0,"static int asf_read_picture(AVFormatContext *s, int len) +{ + AVPacket pkt = { 0 }; + const CodecMime *mime = ff_id3v2_mime_tags; + enum AVCodecID id = AV_CODEC_ID_NONE; + char mimetype[64]; + uint8_t *desc = NULL; + AVStream *st = NULL; + int ret, type, picsize, desc_len; + + /* type + picsize + mime + desc */ + if (len < 1 + 4 + 2 + 2) { + av_log(s, AV_LOG_ERROR, ""Invalid attached picture size: %d.\n"", len); + return AVERROR_INVALIDDATA; + } + + /* picture type */ + type = avio_r8(s->pb); + len--; + if (type >= FF_ARRAY_ELEMS(ff_id3v2_picture_types) || type < 0) { + av_log(s, AV_LOG_WARNING, ""Unknown attached picture type: %d.\n"", type); + type = 0; + } + + /* picture data size */ + picsize = avio_rl32(s->pb); + len -= 4; + + /* picture MIME type */ + len -= avio_get_str16le(s->pb, len, mimetype, sizeof(mimetype)); + while (mime->id != AV_CODEC_ID_NONE) { + if (!strncmp(mime->str, mimetype, sizeof(mimetype))) { + id = mime->id; + break; + } + mime++; + } + if (id == AV_CODEC_ID_NONE) { + av_log(s, AV_LOG_ERROR, ""Unknown attached picture mimetype: %s.\n"", + mimetype); + return 0; + } + + if (picsize >= len) { + av_log(s, AV_LOG_ERROR, ""Invalid attached picture data size: %d >= %d.\n"", + picsize, len); + return AVERROR_INVALIDDATA; + } + + /* picture description */ + desc_len = (len - picsize) * 2 + 1; + desc = av_malloc(desc_len); + if (!desc) + return AVERROR(ENOMEM); + len -= avio_get_str16le(s->pb, len - picsize, desc, desc_len); + + ret = av_get_packet(s->pb, &pkt, picsize); + if (ret < 0) + goto fail; + + st = avformat_new_stream(s, NULL); + if (!st) { + ret = AVERROR(ENOMEM); + goto fail; + } + st->disposition |= AV_DISPOSITION_ATTACHED_PIC; + st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; + st->codecpar->codec_id = id; + st->attached_pic = pkt; + st->attached_pic.stream_index = st->index; + st->attached_pic.flags |= AV_PKT_FLAG_KEY; + + if (*desc) + av_dict_set(&st->metadata, ""title"", desc, AV_DICT_DONT_STRDUP_VAL); + else + av_freep(&desc); + + av_dict_set(&st->metadata, ""comment"", ff_id3v2_picture_types[type], 0); + + return 0; + +fail: + av_freep(&desc); + av_packet_unref(&pkt); + return ret; +} +","@@ -1610,6 +1610,11 @@ static int asf_build_simple_index(AVFormatContext *s, int stream_index) + int64_t pos = s->internal->data_offset + s->packet_size * (int64_t)pktnum; + int64_t index_pts = FFMAX(av_rescale(itime, i, 10000) - asf->hdr.preroll, 0); + ++ if (avio_feof(s->pb)) { ++ ret = AVERROR_INVALIDDATA; ++ goto end; ++ } ++ + if (pos != last_pos) { + av_log(s, AV_LOG_DEBUG, ""pktnum:%d, pktct:%d pts: %""PRId64""\n"", + pktnum, pktct, index_pts);",711,1042,2048 +7947,"static void vc1_put_blocks_clamped(VC1Context *v, int put_signed) +{ + MpegEncContext *s = &v->s; + uint8_t *dest; + int block_count = CONFIG_GRAY && (s->avctx->flags & AV_CODEC_FLAG_GRAY) ? 4 : 6; + int fieldtx = 0; + int i; + + /* The put pixels loop is one MB row and one MB column behind the decoding + * loop because we can only put pixels when overlap filtering is done. For + * interlaced frame pictures, however, the put pixels loop is only one + * column behind the decoding loop as interlaced frame pictures only need + * horizontal overlap filtering. */ + if (!s->first_slice_line && v->fcm != ILACE_FRAME) { + if (s->mb_x) { + for (i = 0; i < block_count; i++) { + if (i > 3 ? v->mb_type[0][s->block_index[i] - s->block_wrap[i] - 1] : + v->mb_type[0][s->block_index[i] - 2 * s->block_wrap[i] - 2]) { + dest = s->dest[0] + ((i & 2) - 4) * 4 * s->linesize + ((i & 1) - 2) * 8; + if (put_signed) + s->idsp.put_signed_pixels_clamped(v->block[v->topleft_blk_idx][block_map[i]], + i > 3 ? s->dest[i - 3] - 8 * s->uvlinesize - 8 : dest, + i > 3 ? s->uvlinesize : s->linesize); + else + s->idsp.put_pixels_clamped(v->block[v->topleft_blk_idx][block_map[i]], + i > 3 ? s->dest[i - 3] - 8 * s->uvlinesize - 8 : dest, + i > 3 ? s->uvlinesize : s->linesize); + } + } + } + if (s->mb_x == v->end_mb_x - 1) { + for (i = 0; i < block_count; i++) { + if (i > 3 ? v->mb_type[0][s->block_index[i] - s->block_wrap[i]] : + v->mb_type[0][s->block_index[i] - 2 * s->block_wrap[i]]) { + dest = s->dest[0] + ((i & 2) - 4) * 4 * s->linesize + (i & 1) * 8; + if (put_signed) + s->idsp.put_signed_pixels_clamped(v->block[v->top_blk_idx][block_map[i]], + i > 3 ? s->dest[i - 3] - 8 * s->uvlinesize : dest, + i > 3 ? s->uvlinesize : s->linesize); + else + s->idsp.put_pixels_clamped(v->block[v->top_blk_idx][block_map[i]], + i > 3 ? s->dest[i - 3] - 8 * s->uvlinesize : dest, + i > 3 ? s->uvlinesize : s->linesize); + } + } + } + } + if (s->mb_y == s->end_mb_y - 1 || v->fcm == ILACE_FRAME) { + if (s->mb_x) { + if (v->fcm == ILACE_FRAME) + fieldtx = v->fieldtx_plane[s->mb_y * s->mb_stride + s->mb_x - 1]; + for (i = 0; i < block_count; i++) { + if (i > 3 ? v->mb_type[0][s->block_index[i] - 1] : + v->mb_type[0][s->block_index[i] - 2]) { + if (fieldtx) + dest = s->dest[0] + ((i & 2) >> 1) * s->linesize + ((i & 1) - 2) * 8; + else + dest = s->dest[0] + (i & 2) * 4 * s->linesize + ((i & 1) - 2) * 8; + if (put_signed) + s->idsp.put_signed_pixels_clamped(v->block[v->left_blk_idx][block_map[i]], + i > 3 ? s->dest[i - 3] - 8 : dest, + i > 3 ? s->uvlinesize : s->linesize << fieldtx); + else + s->idsp.put_pixels_clamped(v->block[v->left_blk_idx][block_map[i]], + i > 3 ? s->dest[i - 3] - 8 : dest, + i > 3 ? s->uvlinesize : s->linesize << fieldtx); + } + } + } + if (s->mb_x == v->end_mb_x - 1) { + if (v->fcm == ILACE_FRAME) + fieldtx = v->fieldtx_plane[s->mb_y * s->mb_stride + s->mb_x]; + for (i = 0; i < block_count; i++) { + if (v->mb_type[0][s->block_index[i]]) { + if (fieldtx) + dest = s->dest[0] + ((i & 2) >> 1) * s->linesize + (i & 1) * 8; + else + dest = s->dest[0] + (i & 2) * 4 * s->linesize + (i & 1) * 8; + if (put_signed) + s->idsp.put_signed_pixels_clamped(v->block[v->cur_blk_idx][block_map[i]], + i > 3 ? s->dest[i - 3] : dest, + i > 3 ? s->uvlinesize : s->linesize << fieldtx); + else + s->idsp.put_pixels_clamped(v->block[v->cur_blk_idx][block_map[i]], + i > 3 ? s->dest[i - 3] : dest, + i > 3 ? s->uvlinesize : s->linesize << fieldtx); + } + } + } + } +} +",0,"static void vc1_put_blocks_clamped(VC1Context *v, int put_signed) +{ + MpegEncContext *s = &v->s; + uint8_t *dest; + int block_count = CONFIG_GRAY && (s->avctx->flags & AV_CODEC_FLAG_GRAY) ? 4 : 6; + int fieldtx = 0; + int i; + + /* The put pixels loop is one MB row and one MB column behind the decoding + * loop because we can only put pixels when overlap filtering is done. For + * interlaced frame pictures, however, the put pixels loop is only one + * column behind the decoding loop as interlaced frame pictures only need + * horizontal overlap filtering. */ + if (!s->first_slice_line && v->fcm != ILACE_FRAME) { + if (s->mb_x) { + for (i = 0; i < block_count; i++) { + if (i > 3 ? v->mb_type[0][s->block_index[i] - s->block_wrap[i] - 1] : + v->mb_type[0][s->block_index[i] - 2 * s->block_wrap[i] - 2]) { + dest = s->dest[0] + ((i & 2) - 4) * 4 * s->linesize + ((i & 1) - 2) * 8; + if (put_signed) + s->idsp.put_signed_pixels_clamped(v->block[v->topleft_blk_idx][block_map[i]], + i > 3 ? s->dest[i - 3] - 8 * s->uvlinesize - 8 : dest, + i > 3 ? s->uvlinesize : s->linesize); + else + s->idsp.put_pixels_clamped(v->block[v->topleft_blk_idx][block_map[i]], + i > 3 ? s->dest[i - 3] - 8 * s->uvlinesize - 8 : dest, + i > 3 ? s->uvlinesize : s->linesize); + } + } + } + if (s->mb_x == v->end_mb_x - 1) { + for (i = 0; i < block_count; i++) { + if (i > 3 ? v->mb_type[0][s->block_index[i] - s->block_wrap[i]] : + v->mb_type[0][s->block_index[i] - 2 * s->block_wrap[i]]) { + dest = s->dest[0] + ((i & 2) - 4) * 4 * s->linesize + (i & 1) * 8; + if (put_signed) + s->idsp.put_signed_pixels_clamped(v->block[v->top_blk_idx][block_map[i]], + i > 3 ? s->dest[i - 3] - 8 * s->uvlinesize : dest, + i > 3 ? s->uvlinesize : s->linesize); + else + s->idsp.put_pixels_clamped(v->block[v->top_blk_idx][block_map[i]], + i > 3 ? s->dest[i - 3] - 8 * s->uvlinesize : dest, + i > 3 ? s->uvlinesize : s->linesize); + } + } + } + } + if (s->mb_y == s->end_mb_y - 1 || v->fcm == ILACE_FRAME) { + if (s->mb_x) { + if (v->fcm == ILACE_FRAME) + fieldtx = v->fieldtx_plane[s->mb_y * s->mb_stride + s->mb_x - 1]; + for (i = 0; i < block_count; i++) { + if (i > 3 ? v->mb_type[0][s->block_index[i] - 1] : + v->mb_type[0][s->block_index[i] - 2]) { + if (fieldtx) + dest = s->dest[0] + ((i & 2) >> 1) * s->linesize + ((i & 1) - 2) * 8; + else + dest = s->dest[0] + (i & 2) * 4 * s->linesize + ((i & 1) - 2) * 8; + if (put_signed) + s->idsp.put_signed_pixels_clamped(v->block[v->left_blk_idx][block_map[i]], + i > 3 ? s->dest[i - 3] - 8 : dest, + i > 3 ? s->uvlinesize : s->linesize << fieldtx); + else + s->idsp.put_pixels_clamped(v->block[v->left_blk_idx][block_map[i]], + i > 3 ? s->dest[i - 3] - 8 : dest, + i > 3 ? s->uvlinesize : s->linesize << fieldtx); + } + } + } + if (s->mb_x == v->end_mb_x - 1) { + if (v->fcm == ILACE_FRAME) + fieldtx = v->fieldtx_plane[s->mb_y * s->mb_stride + s->mb_x]; + for (i = 0; i < block_count; i++) { + if (v->mb_type[0][s->block_index[i]]) { + if (fieldtx) + dest = s->dest[0] + ((i & 2) >> 1) * s->linesize + (i & 1) * 8; + else + dest = s->dest[0] + (i & 2) * 4 * s->linesize + (i & 1) * 8; + if (put_signed) + s->idsp.put_signed_pixels_clamped(v->block[v->cur_blk_idx][block_map[i]], + i > 3 ? s->dest[i - 3] : dest, + i > 3 ? s->uvlinesize : s->linesize << fieldtx); + else + s->idsp.put_pixels_clamped(v->block[v->cur_blk_idx][block_map[i]], + i > 3 ? s->dest[i - 3] : dest, + i > 3 ? s->uvlinesize : s->linesize << fieldtx); + } + } + } + } +} +","@@ -207,7 +207,7 @@ static void vc1_put_blocks_clamped(VC1Context *v, int put_signed) + if ((edges&8) && \ + s->mb_y == ((s->mb_height >> v->field_mode) - 1)) \ + mquant = -v->altpq; \ +- if (!mquant || mquant > 31) { \ ++ if (!mquant || mquant > 31 || mquant < -31) { \ + av_log(v->s.avctx, AV_LOG_ERROR, \ + ""Overriding invalid mquant %d\n"", mquant); \ + mquant = 1; \",1403,1734,2048 +16361,"void RenderThreadImpl::InitializeWebKit( + const scoped_refptr& resource_task_queue, + blink::InterfaceRegistry* interface_registry) { + DCHECK(!blink_platform_impl_); + + const base::CommandLine& command_line = + *base::CommandLine::ForCurrentProcess(); + +#ifdef ENABLE_VTUNE_JIT_INTERFACE + if (command_line.HasSwitch(switches::kEnableVtune)) + gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler()); +#endif + + blink_platform_impl_.reset( + new RendererBlinkPlatformImpl(renderer_scheduler_.get())); + SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line); + GetContentClient() + ->renderer() + ->SetRuntimeFeaturesDefaultsBeforeBlinkInitialization(); + blink::Initialize(blink_platform_impl_.get(), interface_registry); + + v8::Isolate* isolate = blink::MainThreadIsolate(); + isolate->SetCreateHistogramFunction(CreateHistogram); + isolate->SetAddHistogramSampleFunction(AddHistogramSample); + renderer_scheduler_->SetRAILModeObserver(this); + + main_thread_compositor_task_runner_ = + renderer_scheduler_->CompositorTaskRunner(); + + main_input_callback_.Reset( + base::Bind(base::IgnoreResult(&RenderThreadImpl::OnMessageReceived), + base::Unretained(this))); + + scoped_refptr resource_task_queue2; + if (resource_task_queue) { + resource_task_queue2 = resource_task_queue; + } else { + resource_task_queue2 = renderer_scheduler_->LoadingTaskRunner(); + } + scoped_refptr filter( + new ResourceSchedulingFilter( + resource_task_queue2, resource_dispatcher_.get())); + channel()->AddFilter(filter.get()); + resource_dispatcher_->SetResourceSchedulingFilter(filter); + + resource_message_filter_->SetMainThreadTaskRunner( + resource_task_queue2); + resource_dispatcher_->SetThreadTaskRunner(resource_task_queue2); + + if (!command_line.HasSwitch(switches::kDisableThreadedCompositing)) + InitializeCompositorThread(); + + if (!input_event_filter_.get()) { + input_event_filter_ = new MainThreadInputEventFilter( + main_input_callback_.callback(), main_thread_compositor_task_runner_); + } + AddFilter(input_event_filter_.get()); + + scoped_refptr compositor_impl_side_task_runner; + if (compositor_task_runner_) + compositor_impl_side_task_runner = compositor_task_runner_; + else + compositor_impl_side_task_runner = base::ThreadTaskRunnerHandle::Get(); + + compositor_message_filter_ = new CompositorForwardingMessageFilter( + compositor_impl_side_task_runner.get()); + AddFilter(compositor_message_filter_.get()); + + RenderThreadImpl::RegisterSchemes(); + + RenderMediaClient::Initialize(); + + devtools_agent_message_filter_ = new DevToolsAgentFilter(); + AddFilter(devtools_agent_message_filter_.get()); + + if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) { + ScheduleIdleHandler(kLongIdleHandlerDelayMs); + } else { + isolate->IsolateInBackgroundNotification(); + } + + service_worker_message_filter_ = + new ServiceWorkerMessageFilter(thread_safe_sender()); + AddFilter(service_worker_message_filter_->GetFilter()); + + renderer_scheduler_->SetStoppingWhenBackgroundedEnabled( + GetContentClient()->renderer()->AllowStoppingWhenProcessBackgrounded()); + + SkGraphics::SetResourceCacheSingleAllocationByteLimit( + kImageCacheSingleAllocationByteLimit); + + SkGraphics::SetImageGeneratorFromEncodedDataFactory( + blink::WebImageGenerator::CreateAsSkImageGenerator); + + if (command_line.HasSwitch(switches::kExplicitlyAllowedPorts)) { + std::string allowed_ports = + command_line.GetSwitchValueASCII(switches::kExplicitlyAllowedPorts); + net::SetExplicitlyAllowedPorts(allowed_ports); + } +} +",0,"void RenderThreadImpl::InitializeWebKit( + const scoped_refptr& resource_task_queue, + blink::InterfaceRegistry* interface_registry) { + DCHECK(!blink_platform_impl_); + + const base::CommandLine& command_line = + *base::CommandLine::ForCurrentProcess(); + +#ifdef ENABLE_VTUNE_JIT_INTERFACE + if (command_line.HasSwitch(switches::kEnableVtune)) + gin::Debug::SetJitCodeEventHandler(vTune::GetVtuneCodeEventHandler()); +#endif + + blink_platform_impl_.reset( + new RendererBlinkPlatformImpl(renderer_scheduler_.get())); + SetRuntimeFeaturesDefaultsAndUpdateFromArgs(command_line); + GetContentClient() + ->renderer() + ->SetRuntimeFeaturesDefaultsBeforeBlinkInitialization(); + blink::Initialize(blink_platform_impl_.get(), interface_registry); + + v8::Isolate* isolate = blink::MainThreadIsolate(); + isolate->SetCreateHistogramFunction(CreateHistogram); + isolate->SetAddHistogramSampleFunction(AddHistogramSample); + renderer_scheduler_->SetRAILModeObserver(this); + + main_thread_compositor_task_runner_ = + renderer_scheduler_->CompositorTaskRunner(); + + main_input_callback_.Reset( + base::Bind(base::IgnoreResult(&RenderThreadImpl::OnMessageReceived), + base::Unretained(this))); + + scoped_refptr resource_task_queue2; + if (resource_task_queue) { + resource_task_queue2 = resource_task_queue; + } else { + resource_task_queue2 = renderer_scheduler_->LoadingTaskRunner(); + } + scoped_refptr filter( + new ResourceSchedulingFilter( + resource_task_queue2, resource_dispatcher_.get())); + channel()->AddFilter(filter.get()); + resource_dispatcher_->SetResourceSchedulingFilter(filter); + + resource_message_filter_->SetMainThreadTaskRunner( + resource_task_queue2); + resource_dispatcher_->SetThreadTaskRunner(resource_task_queue2); + + if (!command_line.HasSwitch(switches::kDisableThreadedCompositing)) + InitializeCompositorThread(); + + if (!input_event_filter_.get()) { + input_event_filter_ = new MainThreadInputEventFilter( + main_input_callback_.callback(), main_thread_compositor_task_runner_); + } + AddFilter(input_event_filter_.get()); + + scoped_refptr compositor_impl_side_task_runner; + if (compositor_task_runner_) + compositor_impl_side_task_runner = compositor_task_runner_; + else + compositor_impl_side_task_runner = base::ThreadTaskRunnerHandle::Get(); + + compositor_message_filter_ = new CompositorForwardingMessageFilter( + compositor_impl_side_task_runner.get()); + AddFilter(compositor_message_filter_.get()); + + RenderThreadImpl::RegisterSchemes(); + + RenderMediaClient::Initialize(); + + devtools_agent_message_filter_ = new DevToolsAgentFilter(); + AddFilter(devtools_agent_message_filter_.get()); + + if (GetContentClient()->renderer()->RunIdleHandlerWhenWidgetsHidden()) { + ScheduleIdleHandler(kLongIdleHandlerDelayMs); + } else { + isolate->IsolateInBackgroundNotification(); + } + + service_worker_message_filter_ = + new ServiceWorkerMessageFilter(thread_safe_sender()); + AddFilter(service_worker_message_filter_->GetFilter()); + + renderer_scheduler_->SetStoppingWhenBackgroundedEnabled( + GetContentClient()->renderer()->AllowStoppingWhenProcessBackgrounded()); + + SkGraphics::SetResourceCacheSingleAllocationByteLimit( + kImageCacheSingleAllocationByteLimit); + + SkGraphics::SetImageGeneratorFromEncodedDataFactory( + blink::WebImageGenerator::CreateAsSkImageGenerator); + + if (command_line.HasSwitch(switches::kExplicitlyAllowedPorts)) { + std::string allowed_ports = + command_line.GetSwitchValueASCII(switches::kExplicitlyAllowedPorts); + net::SetExplicitlyAllowedPorts(allowed_ports); + } +} +","@@ -994,9 +994,6 @@ void RenderThreadImpl::Init( + if (!command_line.HasSwitch(switches::kSingleProcess)) + base::SequencedWorkerPool::EnableForProcess(); + +- EVP_set_buggy_rsa_parser( +- base::FeatureList::IsEnabled(features::kBuggyRSAParser)); +- + GetConnector()->BindInterface(mojom::kBrowserServiceName, + mojo::MakeRequest(&frame_sink_provider_)); + ",807,1138,2048 +9149,"static bgp_attr_parse_ret_t bgp_attr_psid_sub(int32_t type, + int32_t length, + struct bgp_attr_parser_args *args, + struct bgp_nlri *mp_update) +{ + struct peer *const peer = args->peer; + struct attr *const attr = args->attr; + uint32_t label_index; + struct in6_addr ipv6_sid; + uint32_t srgb_base; + uint32_t srgb_range; + int srgb_count; + + if (type == BGP_PREFIX_SID_LABEL_INDEX) { + if (length != BGP_PREFIX_SID_LABEL_INDEX_LENGTH) { + flog_err( + EC_BGP_ATTR_LEN, + ""Prefix SID label index length is %d instead of %d"", + length, BGP_PREFIX_SID_LABEL_INDEX_LENGTH); + return bgp_attr_malformed(args, + BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, + args->total); + } + + /* Ignore flags and reserved */ + stream_getc(peer->curr); + stream_getw(peer->curr); + + /* Fetch the label index and see if it is valid. */ + label_index = stream_getl(peer->curr); + if (label_index == BGP_INVALID_LABEL_INDEX) + return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_OPT_ATTR_ERR, + args->total); + + /* Store label index; subsequently, we'll check on + * address-family */ + attr->label_index = label_index; + + /* + * Ignore the Label index attribute unless received for + * labeled-unicast + * SAFI. + */ + if (!mp_update->length + || mp_update->safi != SAFI_LABELED_UNICAST) + attr->label_index = BGP_INVALID_LABEL_INDEX; + } + + /* Placeholder code for the IPv6 SID type */ + else if (type == BGP_PREFIX_SID_IPV6) { + if (length != BGP_PREFIX_SID_IPV6_LENGTH) { + flog_err(EC_BGP_ATTR_LEN, + ""Prefix SID IPv6 length is %d instead of %d"", + length, BGP_PREFIX_SID_IPV6_LENGTH); + return bgp_attr_malformed(args, + BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, + args->total); + } + + /* Ignore reserved */ + stream_getc(peer->curr); + stream_getw(peer->curr); + + stream_get(&ipv6_sid, peer->curr, 16); + } + + /* Placeholder code for the Originator SRGB type */ + else if (type == BGP_PREFIX_SID_ORIGINATOR_SRGB) { + /* Ignore flags */ + stream_getw(peer->curr); + + length -= 2; + + if (length % BGP_PREFIX_SID_ORIGINATOR_SRGB_LENGTH) { + flog_err( + EC_BGP_ATTR_LEN, + ""Prefix SID Originator SRGB length is %d, it must be a multiple of %d "", + length, BGP_PREFIX_SID_ORIGINATOR_SRGB_LENGTH); + return bgp_attr_malformed( + args, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, + args->total); + } + + srgb_count = length / BGP_PREFIX_SID_ORIGINATOR_SRGB_LENGTH; + + for (int i = 0; i < srgb_count; i++) { + stream_get(&srgb_base, peer->curr, 3); + stream_get(&srgb_range, peer->curr, 3); + } + } + + return BGP_ATTR_PARSE_PROCEED; +} +",0,"static bgp_attr_parse_ret_t bgp_attr_psid_sub(int32_t type, + int32_t length, + struct bgp_attr_parser_args *args, + struct bgp_nlri *mp_update) +{ + struct peer *const peer = args->peer; + struct attr *const attr = args->attr; + uint32_t label_index; + struct in6_addr ipv6_sid; + uint32_t srgb_base; + uint32_t srgb_range; + int srgb_count; + + if (type == BGP_PREFIX_SID_LABEL_INDEX) { + if (length != BGP_PREFIX_SID_LABEL_INDEX_LENGTH) { + flog_err( + EC_BGP_ATTR_LEN, + ""Prefix SID label index length is %d instead of %d"", + length, BGP_PREFIX_SID_LABEL_INDEX_LENGTH); + return bgp_attr_malformed(args, + BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, + args->total); + } + + /* Ignore flags and reserved */ + stream_getc(peer->curr); + stream_getw(peer->curr); + + /* Fetch the label index and see if it is valid. */ + label_index = stream_getl(peer->curr); + if (label_index == BGP_INVALID_LABEL_INDEX) + return bgp_attr_malformed(args, BGP_NOTIFY_UPDATE_OPT_ATTR_ERR, + args->total); + + /* Store label index; subsequently, we'll check on + * address-family */ + attr->label_index = label_index; + + /* + * Ignore the Label index attribute unless received for + * labeled-unicast + * SAFI. + */ + if (!mp_update->length + || mp_update->safi != SAFI_LABELED_UNICAST) + attr->label_index = BGP_INVALID_LABEL_INDEX; + } + + /* Placeholder code for the IPv6 SID type */ + else if (type == BGP_PREFIX_SID_IPV6) { + if (length != BGP_PREFIX_SID_IPV6_LENGTH) { + flog_err(EC_BGP_ATTR_LEN, + ""Prefix SID IPv6 length is %d instead of %d"", + length, BGP_PREFIX_SID_IPV6_LENGTH); + return bgp_attr_malformed(args, + BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, + args->total); + } + + /* Ignore reserved */ + stream_getc(peer->curr); + stream_getw(peer->curr); + + stream_get(&ipv6_sid, peer->curr, 16); + } + + /* Placeholder code for the Originator SRGB type */ + else if (type == BGP_PREFIX_SID_ORIGINATOR_SRGB) { + /* Ignore flags */ + stream_getw(peer->curr); + + length -= 2; + + if (length % BGP_PREFIX_SID_ORIGINATOR_SRGB_LENGTH) { + flog_err( + EC_BGP_ATTR_LEN, + ""Prefix SID Originator SRGB length is %d, it must be a multiple of %d "", + length, BGP_PREFIX_SID_ORIGINATOR_SRGB_LENGTH); + return bgp_attr_malformed( + args, BGP_NOTIFY_UPDATE_ATTR_LENG_ERR, + args->total); + } + + srgb_count = length / BGP_PREFIX_SID_ORIGINATOR_SRGB_LENGTH; + + for (int i = 0; i < srgb_count; i++) { + stream_get(&srgb_base, peer->curr, 3); + stream_get(&srgb_range, peer->curr, 3); + } + } + + return BGP_ATTR_PARSE_PROCEED; +} +","@@ -78,7 +78,7 @@ static const struct message attr_str[] = { + {BGP_ATTR_AS_PATHLIMIT, ""AS_PATHLIMIT""}, + {BGP_ATTR_PMSI_TUNNEL, ""PMSI_TUNNEL_ATTRIBUTE""}, + {BGP_ATTR_ENCAP, ""ENCAP""}, +-#if ENABLE_BGP_VNC ++#if ENABLE_BGP_VNC_ATTR + {BGP_ATTR_VNC, ""VNC""}, + #endif + {BGP_ATTR_LARGE_COMMUNITIES, ""LARGE_COMMUNITY""}, +@@ -2593,7 +2593,7 @@ bgp_attr_parse_ret_t bgp_attr_parse(struct peer *peer, struct attr *attr, + case BGP_ATTR_EXT_COMMUNITIES: + ret = bgp_attr_ext_communities(&attr_args); + break; +-#if ENABLE_BGP_VNC ++#if ENABLE_BGP_VNC_ATTR + case BGP_ATTR_VNC: + #endif + case BGP_ATTR_ENCAP: +@@ -2946,7 +2946,7 @@ static void bgp_packet_mpattr_tea(struct bgp *bgp, struct peer *peer, + attrhdrlen = 1 + 1; /* subTLV T + L */ + break; + +-#if ENABLE_BGP_VNC ++#if ENABLE_BGP_VNC_ATTR + case BGP_ATTR_VNC: + attrname = ""VNC""; + subtlvs = attr->vnc_subtlvs; +@@ -3433,7 +3433,7 @@ bgp_size_t bgp_packet_attribute(struct bgp *bgp, struct peer *peer, + /* Tunnel Encap attribute */ + bgp_packet_mpattr_tea(bgp, peer, s, attr, BGP_ATTR_ENCAP); + +-#if ENABLE_BGP_VNC ++#if ENABLE_BGP_VNC_ATTR + /* VNC attribute */ + bgp_packet_mpattr_tea(bgp, peer, s, attr, BGP_ATTR_VNC); + #endif",740,1071,2048 +5333,"static double GetFillAlpha(PolygonInfo *polygon_info,const double mid, + const MagickBooleanType fill,const FillRule fill_rule,const ssize_t x, + const ssize_t y,double *stroke_alpha) +{ + double + alpha, + beta, + distance, + subpath_alpha; + + PointInfo + delta; + + register const PointInfo + *q; + + register EdgeInfo + *p; + + register ssize_t + i; + + ssize_t + j, + winding_number; + + /* + Compute fill & stroke opacity for this (x,y) point. + */ + *stroke_alpha=0.0; + subpath_alpha=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_alpha < 1.0) && + (distance <= ((alpha+0.25)*(alpha+0.25)))) + { + alpha=mid-0.5; + if (distance <= ((alpha+0.25)*(alpha+0.25))) + *stroke_alpha=1.0; + else + { + beta=1.0; + if (distance != 1.0) + beta=sqrt((double) distance); + alpha=beta-mid-0.5; + if (*stroke_alpha < ((alpha-0.25)*(alpha-0.25))) + *stroke_alpha=(alpha-0.25)*(alpha-0.25); + } + } + } + if ((fill == MagickFalse) || (distance > 1.0) || (subpath_alpha >= 1.0)) + continue; + if (distance <= 0.0) + { + subpath_alpha=1.0; + continue; + } + if (distance > 1.0) + continue; + if (beta == 0.0) + { + beta=1.0; + if (distance != 1.0) + beta=sqrt(distance); + } + alpha=beta-1.0; + if (subpath_alpha < (alpha*alpha)) + subpath_alpha=alpha*alpha; + } + } + /* + Compute fill opacity. + */ + if (fill == MagickFalse) + return(0.0); + if (subpath_alpha >= 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_alpha); +} +",0,"static double GetFillAlpha(PolygonInfo *polygon_info,const double mid, + const MagickBooleanType fill,const FillRule fill_rule,const ssize_t x, + const ssize_t y,double *stroke_alpha) +{ + double + alpha, + beta, + distance, + subpath_alpha; + + PointInfo + delta; + + register const PointInfo + *q; + + register EdgeInfo + *p; + + register ssize_t + i; + + ssize_t + j, + winding_number; + + /* + Compute fill & stroke opacity for this (x,y) point. + */ + *stroke_alpha=0.0; + subpath_alpha=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_alpha < 1.0) && + (distance <= ((alpha+0.25)*(alpha+0.25)))) + { + alpha=mid-0.5; + if (distance <= ((alpha+0.25)*(alpha+0.25))) + *stroke_alpha=1.0; + else + { + beta=1.0; + if (distance != 1.0) + beta=sqrt((double) distance); + alpha=beta-mid-0.5; + if (*stroke_alpha < ((alpha-0.25)*(alpha-0.25))) + *stroke_alpha=(alpha-0.25)*(alpha-0.25); + } + } + } + if ((fill == MagickFalse) || (distance > 1.0) || (subpath_alpha >= 1.0)) + continue; + if (distance <= 0.0) + { + subpath_alpha=1.0; + continue; + } + if (distance > 1.0) + continue; + if (beta == 0.0) + { + beta=1.0; + if (distance != 1.0) + beta=sqrt(distance); + } + alpha=beta-1.0; + if (subpath_alpha < (alpha*alpha)) + subpath_alpha=alpha*alpha; + } + } + /* + Compute fill opacity. + */ + if (fill == MagickFalse) + return(0.0); + if (subpath_alpha >= 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_alpha); +} +","@@ -1417,7 +1417,7 @@ MagickExport MagickBooleanType DrawClipPath(Image *image, + return(MagickFalse); + (void) QueryColorCompliance(""#0000"",AllCompliance, + &clip_mask->background_color,exception); +- clip_mask->background_color.alpha=(Quantum) TransparentAlpha; ++ clip_mask->background_color.alpha=(MagickRealType) TransparentAlpha; + (void) SetImageBackgroundColor(clip_mask,exception); + if (image->debug != MagickFalse) + (void) LogMagickEvent(DrawEvent,GetMagickModule(),""\nbegin clip-path %s"", +@@ -1541,7 +1541,7 @@ static MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info, + status=MagickTrue; + maximum_length=0.0; + total_length=0.0; +- for (i=1; (i < number_vertices) && (length >= 0.0); i++) ++ 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; +@@ -1794,7 +1794,7 @@ MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info, + /* + Interpret graphic primitive. + */ +- GetNextToken(q,&q,extent,keyword); ++ GetNextToken(q,&q,MagickPathExtent,keyword); + if (*keyword == '\0') + break; + if (*keyword == '#') +@@ -2104,7 +2104,7 @@ MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info, + GetNextToken(q,&q,extent,token); + weight=ParseCommandOption(MagickWeightOptions,MagickFalse,token); + if (weight == -1) +- weight=StringToUnsignedLong(token); ++ weight=(ssize_t) StringToUnsignedLong(token); + graphic_context[n]->weight=(size_t) weight; + break; + } +@@ -2353,7 +2353,8 @@ MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info, + (void) SetImageArtifact(image,key,token); + (void) FormatLocaleString(key,MagickPathExtent,""%s-type"",name); + (void) SetImageArtifact(image,key,type); +- (void) FormatLocaleString(key,MagickPathExtent,""%s-geometry"",name); ++ (void) FormatLocaleString(key,MagickPathExtent,""%s-geometry"", ++ name); + (void) FormatLocaleString(geometry,MagickPathExtent, + ""%gx%g%+.15g%+.15g"", + MagickMax(fabs(bounds.x2-bounds.x1+1.0),1.0), +@@ -4608,7 +4609,7 @@ MagickExport MagickBooleanType DrawPrimitive(Image *image, + */ + clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); + clone_info->stroke_width=0.0; +- clone_info->stroke.alpha=(Quantum) TransparentAlpha; ++ clone_info->stroke.alpha=(MagickRealType) TransparentAlpha; + status&=DrawPolygonPrimitive(image,clone_info,primitive_info, + exception); + clone_info=DestroyDrawInfo(clone_info); +@@ -4643,7 +4644,7 @@ MagickExport MagickBooleanType DrawPrimitive(Image *image, + } + clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); + clone_info->stroke_width=0.0; +- clone_info->stroke.alpha=(Quantum) TransparentAlpha; ++ clone_info->stroke.alpha=(MagickRealType) TransparentAlpha; + status&=DrawPolygonPrimitive(image,clone_info,primitive_info, + exception); + clone_info=DestroyDrawInfo(clone_info); +@@ -4743,7 +4744,7 @@ static MagickBooleanType DrawStrokePolygon(Image *image, + if (clone_info->stroke_pattern != (Image *) NULL) + clone_info->fill_pattern=CloneImage(clone_info->stroke_pattern,0,0, + MagickTrue,exception); +- clone_info->stroke.alpha=(Quantum) TransparentAlpha; ++ clone_info->stroke.alpha=(MagickRealType) TransparentAlpha; + clone_info->stroke_width=0.0; + clone_info->fill_rule=NonZeroRule; + status=MagickTrue; +@@ -4858,7 +4859,7 @@ MagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info) + draw_info->miterlimit=10; + draw_info->decorate=NoDecoration; + draw_info->pointsize=12.0; +- draw_info->undercolor.alpha=(Quantum) TransparentAlpha; ++ draw_info->undercolor.alpha=(MagickRealType) TransparentAlpha; + draw_info->compose=OverCompositeOp; + draw_info->render=MagickTrue; + draw_info->debug=IsEventLogging(); +@@ -4925,7 +4926,7 @@ MagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info) + + weight=ParseCommandOption(MagickWeightOptions,MagickFalse,option); + if (weight == -1) +- weight=StringToUnsignedLong(option); ++ weight=(ssize_t) StringToUnsignedLong(option); + draw_info->weight=(size_t) weight; + } + exception=DestroyExceptionInfo(exception); +@@ -6021,17 +6022,29 @@ static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *draw_info, + } + if (q >= (ssize_t) (max_strokes-6*BezierQuantum-360)) + { +- max_strokes+=6*BezierQuantum+360; +- path_p=(PointInfo *) ResizeQuantumMemory(path_p,(size_t) max_strokes, +- sizeof(*path_p)); +- path_q=(PointInfo *) ResizeQuantumMemory(path_q,(size_t) max_strokes, +- sizeof(*path_q)); +- if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL)) +- { +- polygon_primitive=(PrimitiveInfo *) +- RelinquishMagickMemory(polygon_primitive); +- return((PrimitiveInfo *) NULL); +- } ++ 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)",1345,1676,2048 +15510,"void WebGLRenderingContextBase::TexImageHelperImageData( + TexImageFunctionID function_id, + GLenum target, + GLint level, + GLint internalformat, + GLint border, + GLenum format, + GLenum type, + GLsizei depth, + GLint xoffset, + GLint yoffset, + GLint zoffset, + ImageData* pixels, + const IntRect& source_image_rect, + GLint unpack_image_height) { + const char* func_name = GetTexImageFunctionName(function_id); + if (isContextLost()) + return; + DCHECK(pixels); + if (pixels->data()->BufferBase()->IsNeutered()) { + SynthesizeGLError(GL_INVALID_VALUE, func_name, + ""The source data has been neutered.""); + return; + } + if (!ValidateTexImageBinding(func_name, function_id, target)) + return; + TexImageFunctionType function_type; + if (function_id == kTexImage2D || function_id == kTexImage3D) + function_type = kTexImage; + else + function_type = kTexSubImage; + if (!ValidateTexFunc(func_name, function_type, kSourceImageData, target, + level, internalformat, pixels->width(), pixels->height(), + depth, border, format, type, xoffset, yoffset, zoffset)) + return; + + bool selecting_sub_rectangle = false; + if (!ValidateTexImageSubRectangle( + func_name, function_id, pixels, source_image_rect, depth, + unpack_image_height, &selecting_sub_rectangle)) { + return; + } + IntRect adjusted_source_image_rect = source_image_rect; + if (unpack_flip_y_) { + adjusted_source_image_rect.SetY(pixels->height() - + adjusted_source_image_rect.MaxY()); + } + + Vector data; + bool need_conversion = true; + if (!unpack_flip_y_ && !unpack_premultiply_alpha_ && format == GL_RGBA && + type == GL_UNSIGNED_BYTE && !selecting_sub_rectangle && depth == 1) { + need_conversion = false; + } else { + if (type == GL_UNSIGNED_INT_10F_11F_11F_REV) { + type = GL_FLOAT; + } + if (!WebGLImageConversion::ExtractImageData( + pixels->data()->Data(), + WebGLImageConversion::DataFormat::kDataFormatRGBA8, pixels->Size(), + adjusted_source_image_rect, depth, unpack_image_height, format, + type, unpack_flip_y_, unpack_premultiply_alpha_, data)) { + SynthesizeGLError(GL_INVALID_VALUE, func_name, ""bad image data""); + return; + } + } + ScopedUnpackParametersResetRestore temporary_reset_unpack(this); + const uint8_t* bytes = need_conversion ? data.data() : pixels->data()->Data(); + if (function_id == kTexImage2D) { + DCHECK_EQ(unpack_image_height, 0); + TexImage2DBase( + target, level, internalformat, adjusted_source_image_rect.Width(), + adjusted_source_image_rect.Height(), border, format, type, bytes); + } else if (function_id == kTexSubImage2D) { + DCHECK_EQ(unpack_image_height, 0); + ContextGL()->TexSubImage2D( + target, level, xoffset, yoffset, adjusted_source_image_rect.Width(), + adjusted_source_image_rect.Height(), format, type, bytes); + } else { + GLint upload_height = adjusted_source_image_rect.Height(); + if (function_id == kTexImage3D) { + ContextGL()->TexImage3D(target, level, internalformat, + adjusted_source_image_rect.Width(), upload_height, + depth, border, format, type, bytes); + } else { + DCHECK_EQ(function_id, kTexSubImage3D); + ContextGL()->TexSubImage3D(target, level, xoffset, yoffset, zoffset, + adjusted_source_image_rect.Width(), + upload_height, depth, format, type, bytes); + } + } +} +",0,"void WebGLRenderingContextBase::TexImageHelperImageData( + TexImageFunctionID function_id, + GLenum target, + GLint level, + GLint internalformat, + GLint border, + GLenum format, + GLenum type, + GLsizei depth, + GLint xoffset, + GLint yoffset, + GLint zoffset, + ImageData* pixels, + const IntRect& source_image_rect, + GLint unpack_image_height) { + const char* func_name = GetTexImageFunctionName(function_id); + if (isContextLost()) + return; + DCHECK(pixels); + if (pixels->data()->BufferBase()->IsNeutered()) { + SynthesizeGLError(GL_INVALID_VALUE, func_name, + ""The source data has been neutered.""); + return; + } + if (!ValidateTexImageBinding(func_name, function_id, target)) + return; + TexImageFunctionType function_type; + if (function_id == kTexImage2D || function_id == kTexImage3D) + function_type = kTexImage; + else + function_type = kTexSubImage; + if (!ValidateTexFunc(func_name, function_type, kSourceImageData, target, + level, internalformat, pixels->width(), pixels->height(), + depth, border, format, type, xoffset, yoffset, zoffset)) + return; + + bool selecting_sub_rectangle = false; + if (!ValidateTexImageSubRectangle( + func_name, function_id, pixels, source_image_rect, depth, + unpack_image_height, &selecting_sub_rectangle)) { + return; + } + IntRect adjusted_source_image_rect = source_image_rect; + if (unpack_flip_y_) { + adjusted_source_image_rect.SetY(pixels->height() - + adjusted_source_image_rect.MaxY()); + } + + Vector data; + bool need_conversion = true; + if (!unpack_flip_y_ && !unpack_premultiply_alpha_ && format == GL_RGBA && + type == GL_UNSIGNED_BYTE && !selecting_sub_rectangle && depth == 1) { + need_conversion = false; + } else { + if (type == GL_UNSIGNED_INT_10F_11F_11F_REV) { + type = GL_FLOAT; + } + if (!WebGLImageConversion::ExtractImageData( + pixels->data()->Data(), + WebGLImageConversion::DataFormat::kDataFormatRGBA8, pixels->Size(), + adjusted_source_image_rect, depth, unpack_image_height, format, + type, unpack_flip_y_, unpack_premultiply_alpha_, data)) { + SynthesizeGLError(GL_INVALID_VALUE, func_name, ""bad image data""); + return; + } + } + ScopedUnpackParametersResetRestore temporary_reset_unpack(this); + const uint8_t* bytes = need_conversion ? data.data() : pixels->data()->Data(); + if (function_id == kTexImage2D) { + DCHECK_EQ(unpack_image_height, 0); + TexImage2DBase( + target, level, internalformat, adjusted_source_image_rect.Width(), + adjusted_source_image_rect.Height(), border, format, type, bytes); + } else if (function_id == kTexSubImage2D) { + DCHECK_EQ(unpack_image_height, 0); + ContextGL()->TexSubImage2D( + target, level, xoffset, yoffset, adjusted_source_image_rect.Width(), + adjusted_source_image_rect.Height(), format, type, bytes); + } else { + GLint upload_height = adjusted_source_image_rect.Height(); + if (function_id == kTexImage3D) { + ContextGL()->TexImage3D(target, level, internalformat, + adjusted_source_image_rect.Width(), upload_height, + depth, border, format, type, bytes); + } else { + DCHECK_EQ(function_id, kTexSubImage3D); + ContextGL()->TexSubImage3D(target, level, xoffset, yoffset, zoffset, + adjusted_source_image_rect.Width(), + upload_height, depth, format, type, bytes); + } + } +} +","@@ -30,6 +30,7 @@ + #include ""base/numerics/checked_math.h"" + #include ""base/stl_util.h"" + #include ""build/build_config.h"" ++#include ""gpu/GLES2/gl2extchromium.h"" + #include ""gpu/command_buffer/client/gles2_interface.h"" + #include ""gpu/command_buffer/common/capabilities.h"" + #include ""gpu/config/gpu_feature_info.h"" +@@ -1015,7 +1016,9 @@ WebGLRenderingContextBase::WebGLRenderingContextBase( + &WebGLRenderingContextBase::MaybeRestoreContext), + task_runner_(task_runner), + num_gl_errors_to_console_allowed_(kMaxGLErrorsAllowedToConsole), +- context_type_(context_type) { ++ context_type_(context_type), ++ program_completion_queries_( ++ base::MRUCache::NO_AUTO_EVICT) { + DCHECK(context_provider); + + // TODO(http://crbug.com/876140) Make sure this is being created on a +@@ -1304,6 +1307,8 @@ WebGLRenderingContextBase::~WebGLRenderingContextBase() { + // context state. + destruction_in_progress_ = true; + ++ clearProgramCompletionQueries(); ++ + // Now that the context and context group no longer hold on to the + // objects they create, and now that the objects are eagerly finalized + // rather than the context, there is very little useful work that this +@@ -3455,7 +3460,10 @@ ScriptValue WebGLRenderingContextBase::getProgramParameter( + ""invalid parameter name""); + return ScriptValue::CreateNull(script_state); + } +- ++ bool completed; ++ if (checkProgramCompletionQueryAvailable(program, &completed)) { ++ return WebGLAny(script_state, completed); ++ } + return WebGLAny(script_state, program->CompletionStatus(this)); + case GL_ACTIVE_UNIFORM_BLOCKS: + case GL_TRANSFORM_FEEDBACK_VARYINGS: +@@ -4190,7 +4198,17 @@ void WebGLRenderingContextBase::linkProgram(WebGLProgram* program) { + return; + } + ++ GLuint query = 0u; ++ if (ExtensionEnabled(kKHRParallelShaderCompileName)) { ++ ContextGL()->GenQueriesEXT(1, &query); ++ ContextGL()->BeginQueryEXT(GL_PROGRAM_COMPLETION_QUERY_CHROMIUM, query); ++ } + ContextGL()->LinkProgram(ObjectOrZero(program)); ++ if (ExtensionEnabled(kKHRParallelShaderCompileName)) { ++ ContextGL()->EndQueryEXT(GL_PROGRAM_COMPLETION_QUERY_CHROMIUM); ++ addProgramCompletionQuery(program, query); ++ } ++ + program->IncreaseLinkCount(); + } + +@@ -8151,4 +8169,40 @@ void WebGLRenderingContextBase::getHTMLOrOffscreenCanvas( + } + } + ++void WebGLRenderingContextBase::addProgramCompletionQuery(WebGLProgram* program, ++ GLuint query) { ++ auto old_query = program_completion_queries_.Get(program); ++ if (old_query != program_completion_queries_.end()) { ++ ContextGL()->DeleteQueriesEXT(1, &old_query->second); ++ } ++ program_completion_queries_.Put(program, query); ++ if (program_completion_queries_.size() > kMaxProgramCompletionQueries) { ++ auto oldest = program_completion_queries_.rbegin(); ++ ContextGL()->DeleteQueriesEXT(1, &oldest->second); ++ program_completion_queries_.Erase(oldest); ++ } ++} ++ ++void WebGLRenderingContextBase::clearProgramCompletionQueries() { ++ for (auto query : program_completion_queries_) { ++ ContextGL()->DeleteQueriesEXT(1, &query.second); ++ } ++ program_completion_queries_.Clear(); ++} ++ ++bool WebGLRenderingContextBase::checkProgramCompletionQueryAvailable( ++ WebGLProgram* program, ++ bool* completed) { ++ GLuint id = 0; ++ auto found = program_completion_queries_.Get(program); ++ if (found != program_completion_queries_.end()) { ++ id = found->second; ++ GLuint available; ++ ContextGL()->GetQueryObjectuivEXT(id, GL_QUERY_RESULT_AVAILABLE, ++ &available); ++ *completed = (available == GL_TRUE); ++ return true; ++ } ++ return false; ++} + } // namespace blink",833,1164,2048 +5504,"static unsigned long write_reuse_object(struct sha1file *f, struct object_entry *entry, + unsigned long limit, int usable_delta) +{ + struct packed_git *p = entry->in_pack; + struct pack_window *w_curs = NULL; + struct revindex_entry *revidx; + off_t offset; + enum object_type type = entry->type; + unsigned long datalen; + unsigned char header[10], dheader[10]; + unsigned hdrlen; + + if (entry->delta) + type = (allow_ofs_delta && entry->delta->idx.offset) ? + OBJ_OFS_DELTA : OBJ_REF_DELTA; + hdrlen = encode_in_pack_object_header(type, entry->size, header); + + offset = entry->in_pack_offset; + revidx = find_pack_revindex(p, offset); + datalen = revidx[1].offset - offset; + if (!pack_to_stdout && p->index_version > 1 && + check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) { + error(""bad packed object CRC for %s"", sha1_to_hex(entry->idx.sha1)); + unuse_pack(&w_curs); + return write_no_reuse_object(f, entry, limit, usable_delta); + } + + offset += entry->in_pack_header_size; + datalen -= entry->in_pack_header_size; + + if (!pack_to_stdout && p->index_version == 1 && + check_pack_inflate(p, &w_curs, offset, datalen, entry->size)) { + error(""corrupt packed object for %s"", sha1_to_hex(entry->idx.sha1)); + unuse_pack(&w_curs); + return write_no_reuse_object(f, entry, limit, usable_delta); + } + + if (type == OBJ_OFS_DELTA) { + off_t ofs = entry->idx.offset - entry->delta->idx.offset; + unsigned pos = sizeof(dheader) - 1; + dheader[pos] = ofs & 127; + while (ofs >>= 7) + dheader[--pos] = 128 | (--ofs & 127); + if (limit && hdrlen + sizeof(dheader) - pos + datalen + 20 >= limit) { + unuse_pack(&w_curs); + return 0; + } + sha1write(f, header, hdrlen); + sha1write(f, dheader + pos, sizeof(dheader) - pos); + hdrlen += sizeof(dheader) - pos; + reused_delta++; + } else if (type == OBJ_REF_DELTA) { + if (limit && hdrlen + 20 + datalen + 20 >= limit) { + unuse_pack(&w_curs); + return 0; + } + sha1write(f, header, hdrlen); + sha1write(f, entry->delta->idx.sha1, 20); + hdrlen += 20; + reused_delta++; + } else { + if (limit && hdrlen + datalen + 20 >= limit) { + unuse_pack(&w_curs); + return 0; + } + sha1write(f, header, hdrlen); + } + copy_pack_data(f, p, &w_curs, offset, datalen); + unuse_pack(&w_curs); + reused++; + return hdrlen + datalen; +} +",0,"static unsigned long write_reuse_object(struct sha1file *f, struct object_entry *entry, + unsigned long limit, int usable_delta) +{ + struct packed_git *p = entry->in_pack; + struct pack_window *w_curs = NULL; + struct revindex_entry *revidx; + off_t offset; + enum object_type type = entry->type; + unsigned long datalen; + unsigned char header[10], dheader[10]; + unsigned hdrlen; + + if (entry->delta) + type = (allow_ofs_delta && entry->delta->idx.offset) ? + OBJ_OFS_DELTA : OBJ_REF_DELTA; + hdrlen = encode_in_pack_object_header(type, entry->size, header); + + offset = entry->in_pack_offset; + revidx = find_pack_revindex(p, offset); + datalen = revidx[1].offset - offset; + if (!pack_to_stdout && p->index_version > 1 && + check_pack_crc(p, &w_curs, offset, datalen, revidx->nr)) { + error(""bad packed object CRC for %s"", sha1_to_hex(entry->idx.sha1)); + unuse_pack(&w_curs); + return write_no_reuse_object(f, entry, limit, usable_delta); + } + + offset += entry->in_pack_header_size; + datalen -= entry->in_pack_header_size; + + if (!pack_to_stdout && p->index_version == 1 && + check_pack_inflate(p, &w_curs, offset, datalen, entry->size)) { + error(""corrupt packed object for %s"", sha1_to_hex(entry->idx.sha1)); + unuse_pack(&w_curs); + return write_no_reuse_object(f, entry, limit, usable_delta); + } + + if (type == OBJ_OFS_DELTA) { + off_t ofs = entry->idx.offset - entry->delta->idx.offset; + unsigned pos = sizeof(dheader) - 1; + dheader[pos] = ofs & 127; + while (ofs >>= 7) + dheader[--pos] = 128 | (--ofs & 127); + if (limit && hdrlen + sizeof(dheader) - pos + datalen + 20 >= limit) { + unuse_pack(&w_curs); + return 0; + } + sha1write(f, header, hdrlen); + sha1write(f, dheader + pos, sizeof(dheader) - pos); + hdrlen += sizeof(dheader) - pos; + reused_delta++; + } else if (type == OBJ_REF_DELTA) { + if (limit && hdrlen + 20 + datalen + 20 >= limit) { + unuse_pack(&w_curs); + return 0; + } + sha1write(f, header, hdrlen); + sha1write(f, entry->delta->idx.sha1, 20); + hdrlen += 20; + reused_delta++; + } else { + if (limit && hdrlen + datalen + 20 >= limit) { + unuse_pack(&w_curs); + return 0; + } + sha1write(f, header, hdrlen); + } + copy_pack_data(f, p, &w_curs, offset, datalen); + unuse_pack(&w_curs); + reused++; + return hdrlen + datalen; +} +","@@ -2284,21 +2284,11 @@ static void show_commit(struct commit *commit, void *data) + index_commit_for_bitmap(commit); + } + +-static void show_object(struct object *obj, +- struct strbuf *path, const char *last, +- void *data) ++static void show_object(struct object *obj, const char *name, void *data) + { +- char *name = path_name(path, last); +- + add_preferred_base_object(name); + add_object_entry(obj->oid.hash, obj->type, name, 0); + obj->flags |= OBJECT_ADDED; +- +- /* +- * We will have generated the hash from the name, +- * but not saved a pointer to it - we can free it +- */ +- free((char *)name); + } + + static void show_edge(struct commit *commit) +@@ -2480,8 +2470,7 @@ static int get_object_list_from_bitmap(struct rev_info *revs) + } + + static void record_recent_object(struct object *obj, +- struct strbuf *path, +- const char *last, ++ const char *name, + void *data) + { + sha1_array_append(&recent_objects, obj->oid.hash);",727,1058,2048 +5228,"proto_register_usb_ms(void) +{ + static hf_register_info hf[] = { + { &hf_usb_ms_dCBWSignature, + { ""Signature"", ""usbms.dCBWSignature"", FT_UINT32, BASE_HEX, + NULL, 0x0, NULL, HFILL }}, + + { &hf_usb_ms_dCBWTag, + { ""Tag"", ""usbms.dCBWTag"", FT_UINT32, BASE_HEX, + NULL, 0x0, NULL, HFILL }}, + + { &hf_usb_ms_dCBWDataTransferLength, + { ""DataTransferLength"", ""usbms.dCBWDataTransferLength"", FT_UINT32, BASE_DEC, + NULL, 0x0, NULL, HFILL }}, + + { &hf_usb_ms_dCBWFlags, + { ""Flags"", ""usbms.dCBWFlags"", FT_UINT8, BASE_HEX, + NULL, 0x0, NULL, HFILL }}, + + { &hf_usb_ms_dCBWTarget, + { ""Target"", ""usbms.dCBWTarget"", FT_UINT8, BASE_HEX_DEC, + NULL, 0x70, ""Target Number when enabling multi-target mode"", HFILL }}, + + { &hf_usb_ms_dCBWLUN, + { ""LUN"", ""usbms.dCBWLUN"", FT_UINT8, BASE_HEX, + NULL, 0x0f, NULL, HFILL }}, + + { &hf_usb_ms_dCBWCBLength, + { ""CDB Length"", ""usbms.dCBWCBLength"", FT_UINT8, BASE_HEX, + NULL, 0x1f, NULL, HFILL }}, + + { &hf_usb_ms_dCSWSignature, + { ""Signature"", ""usbms.dCSWSignature"", FT_UINT32, BASE_HEX, + NULL, 0x0, NULL, HFILL }}, + + { &hf_usb_ms_dCSWDataResidue, + { ""DataResidue"", ""usbms.dCSWDataResidue"", FT_UINT32, BASE_DEC, + NULL, 0x0, NULL, HFILL }}, + + { &hf_usb_ms_dCSWStatus, + { ""Status"", ""usbms.dCSWStatus"", FT_UINT8, BASE_HEX, + VALS(status_vals), 0x0, NULL, HFILL }}, + + { &hf_usb_ms_request, + { ""bRequest"", ""usbms.setup.bRequest"", FT_UINT8, BASE_HEX, VALS(setup_request_names_vals), 0x0, + NULL, HFILL }}, + + { &hf_usb_ms_value, + { ""wValue"", ""usbms.setup.wValue"", FT_UINT16, BASE_HEX, NULL, 0x0, + NULL, HFILL }}, + + { &hf_usb_ms_index, + { ""wIndex"", ""usbms.setup.wIndex"", FT_UINT16, BASE_DEC, NULL, 0x0, + NULL, HFILL }}, + + { &hf_usb_ms_length, + { ""wLength"", ""usbms.setup.wLength"", FT_UINT16, BASE_DEC, NULL, 0x0, + NULL, HFILL }}, + + { &hf_usb_ms_maxlun, + { ""Max LUN"", ""usbms.setup.maxlun"", FT_UINT8, BASE_DEC, NULL, 0x0, + NULL, HFILL }}, + + }; + + static gint *usb_ms_subtrees[] = { + &ett_usb_ms, + }; + + + proto_usb_ms = proto_register_protocol(""USB Mass Storage"", ""USBMS"", ""usbms""); + proto_register_field_array(proto_usb_ms, hf, array_length(hf)); + proto_register_subtree_array(usb_ms_subtrees, array_length(usb_ms_subtrees)); + + register_dissector(""usbms"", dissect_usb_ms_bulk, proto_usb_ms); +} +",0,"proto_register_usb_ms(void) +{ + static hf_register_info hf[] = { + { &hf_usb_ms_dCBWSignature, + { ""Signature"", ""usbms.dCBWSignature"", FT_UINT32, BASE_HEX, + NULL, 0x0, NULL, HFILL }}, + + { &hf_usb_ms_dCBWTag, + { ""Tag"", ""usbms.dCBWTag"", FT_UINT32, BASE_HEX, + NULL, 0x0, NULL, HFILL }}, + + { &hf_usb_ms_dCBWDataTransferLength, + { ""DataTransferLength"", ""usbms.dCBWDataTransferLength"", FT_UINT32, BASE_DEC, + NULL, 0x0, NULL, HFILL }}, + + { &hf_usb_ms_dCBWFlags, + { ""Flags"", ""usbms.dCBWFlags"", FT_UINT8, BASE_HEX, + NULL, 0x0, NULL, HFILL }}, + + { &hf_usb_ms_dCBWTarget, + { ""Target"", ""usbms.dCBWTarget"", FT_UINT8, BASE_HEX_DEC, + NULL, 0x70, ""Target Number when enabling multi-target mode"", HFILL }}, + + { &hf_usb_ms_dCBWLUN, + { ""LUN"", ""usbms.dCBWLUN"", FT_UINT8, BASE_HEX, + NULL, 0x0f, NULL, HFILL }}, + + { &hf_usb_ms_dCBWCBLength, + { ""CDB Length"", ""usbms.dCBWCBLength"", FT_UINT8, BASE_HEX, + NULL, 0x1f, NULL, HFILL }}, + + { &hf_usb_ms_dCSWSignature, + { ""Signature"", ""usbms.dCSWSignature"", FT_UINT32, BASE_HEX, + NULL, 0x0, NULL, HFILL }}, + + { &hf_usb_ms_dCSWDataResidue, + { ""DataResidue"", ""usbms.dCSWDataResidue"", FT_UINT32, BASE_DEC, + NULL, 0x0, NULL, HFILL }}, + + { &hf_usb_ms_dCSWStatus, + { ""Status"", ""usbms.dCSWStatus"", FT_UINT8, BASE_HEX, + VALS(status_vals), 0x0, NULL, HFILL }}, + + { &hf_usb_ms_request, + { ""bRequest"", ""usbms.setup.bRequest"", FT_UINT8, BASE_HEX, VALS(setup_request_names_vals), 0x0, + NULL, HFILL }}, + + { &hf_usb_ms_value, + { ""wValue"", ""usbms.setup.wValue"", FT_UINT16, BASE_HEX, NULL, 0x0, + NULL, HFILL }}, + + { &hf_usb_ms_index, + { ""wIndex"", ""usbms.setup.wIndex"", FT_UINT16, BASE_DEC, NULL, 0x0, + NULL, HFILL }}, + + { &hf_usb_ms_length, + { ""wLength"", ""usbms.setup.wLength"", FT_UINT16, BASE_DEC, NULL, 0x0, + NULL, HFILL }}, + + { &hf_usb_ms_maxlun, + { ""Max LUN"", ""usbms.setup.maxlun"", FT_UINT8, BASE_DEC, NULL, 0x0, + NULL, HFILL }}, + + }; + + static gint *usb_ms_subtrees[] = { + &ett_usb_ms, + }; + + + proto_usb_ms = proto_register_protocol(""USB Mass Storage"", ""USBMS"", ""usbms""); + proto_register_field_array(proto_usb_ms, hf, array_length(hf)); + proto_register_subtree_array(usb_ms_subtrees, array_length(usb_ms_subtrees)); + + register_dissector(""usbms"", dissect_usb_ms_bulk, proto_usb_ms); +} +","@@ -199,9 +199,12 @@ dissect_usb_ms_bulk(tvbuff_t *tvb, packet_info *pinfo, proto_tree *parent_tree, + usb_ms_conv_info->itl=wmem_tree_new(wmem_file_scope()); + usb_ms_conv_info->itlq=wmem_tree_new(wmem_file_scope()); + usb_conv_info->class_data=usb_ms_conv_info; ++ usb_conv_info->class_data_type = USB_CONV_MASS_STORAGE; ++ } else if (usb_conv_info->class_data_type != USB_CONV_MASS_STORAGE) { ++ /* Don't dissect if another USB type is in the conversation */ ++ return 0; + } + +- + is_request=(pinfo->srcport==NO_ENDPOINT); + + col_set_str(pinfo->cinfo, COL_PROTOCOL, ""USBMS"");",822,1153,2048 +903,"int vrend_create_shader(struct vrend_context *ctx, + uint32_t handle, + const struct pipe_stream_output_info *so_info, + const char *shd_text, uint32_t offlen, uint32_t num_tokens, + uint32_t type, uint32_t pkt_length) +{ + struct vrend_shader_selector *sel = NULL; + int ret_handle; + bool new_shader = true, long_shader = false; + bool finished = false; + int ret; + + if (type > PIPE_SHADER_GEOMETRY) + return EINVAL; + + if (offlen & VIRGL_OBJ_SHADER_OFFSET_CONT) + new_shader = false; + else if (((offlen + 3) / 4) > pkt_length) + long_shader = true; + + /* if we have an in progress one - don't allow a new shader + of that type or a different handle. */ + if (ctx->sub->long_shader_in_progress_handle[type]) { + if (new_shader == true) + return EINVAL; + if (handle != ctx->sub->long_shader_in_progress_handle[type]) + return EINVAL; + } + + if (new_shader) { + sel = vrend_create_shader_state(ctx, so_info, type); + if (sel == NULL) + return ENOMEM; + + if (long_shader) { + sel->buf_len = ((offlen + 3) / 4) * 4; /* round up buffer size */ + sel->tmp_buf = malloc(sel->buf_len); + if (!sel->tmp_buf) { + ret = ENOMEM; + goto error; + } + memcpy(sel->tmp_buf, shd_text, pkt_length * 4); + sel->buf_offset = pkt_length * 4; + ctx->sub->long_shader_in_progress_handle[type] = handle; + } else + finished = true; + } else { + sel = vrend_object_lookup(ctx->sub->object_hash, handle, VIRGL_OBJECT_SHADER); + if (!sel) { + fprintf(stderr, ""got continuation without original shader %d\n"", handle); + ret = EINVAL; + goto error; + } + + offlen &= ~VIRGL_OBJ_SHADER_OFFSET_CONT; + if (offlen != sel->buf_offset) { + fprintf(stderr, ""Got mismatched shader continuation %d vs %d\n"", + offlen, sel->buf_offset); + ret = EINVAL; + goto error; + } + + /*make sure no overflow */ + if (pkt_length * 4 < pkt_length || + pkt_length * 4 + sel->buf_offset < pkt_length * 4 || + pkt_length * 4 + sel->buf_offset < sel->buf_offset) { + ret = EINVAL; + goto error; + } + + if ((pkt_length * 4 + sel->buf_offset) > sel->buf_len) { + fprintf(stderr, ""Got too large shader continuation %d vs %d\n"", + pkt_length * 4 + sel->buf_offset, sel->buf_len); + ret = EINVAL; + goto error; + } + + memcpy(sel->tmp_buf + sel->buf_offset, shd_text, pkt_length * 4); + + sel->buf_offset += pkt_length * 4; + if (sel->buf_offset >= sel->buf_len) { + finished = true; + shd_text = sel->tmp_buf; + } + } + + if (finished) { + struct tgsi_token *tokens; + + tokens = calloc(num_tokens + 10, sizeof(struct tgsi_token)); + if (!tokens) { + ret = ENOMEM; + goto error; + } + + if (vrend_dump_shaders) + fprintf(stderr,""shader\n%s\n"", shd_text); + if (!tgsi_text_translate((const char *)shd_text, tokens, num_tokens + 10)) { + free(tokens); + ret = EINVAL; + goto error; + } + + if (vrend_finish_shader(ctx, sel, tokens)) { + free(tokens); + ret = EINVAL; + goto error; + } else { + free(sel->tmp_buf); + sel->tmp_buf = NULL; + } + free(tokens); + ctx->sub->long_shader_in_progress_handle[type] = 0; + } + + if (new_shader) { + ret_handle = vrend_renderer_object_insert(ctx, sel, sizeof(*sel), handle, VIRGL_OBJECT_SHADER); + if (ret_handle == 0) { + ret = ENOMEM; + goto error; + } + } + + return 0; + +error: + if (new_shader) + vrend_destroy_shader_selector(sel); + else + vrend_renderer_object_destroy(ctx, handle); + + return ret; +} +",0,"int vrend_create_shader(struct vrend_context *ctx, + uint32_t handle, + const struct pipe_stream_output_info *so_info, + const char *shd_text, uint32_t offlen, uint32_t num_tokens, + uint32_t type, uint32_t pkt_length) +{ + struct vrend_shader_selector *sel = NULL; + int ret_handle; + bool new_shader = true, long_shader = false; + bool finished = false; + int ret; + + if (type > PIPE_SHADER_GEOMETRY) + return EINVAL; + + if (offlen & VIRGL_OBJ_SHADER_OFFSET_CONT) + new_shader = false; + else if (((offlen + 3) / 4) > pkt_length) + long_shader = true; + + /* if we have an in progress one - don't allow a new shader + of that type or a different handle. */ + if (ctx->sub->long_shader_in_progress_handle[type]) { + if (new_shader == true) + return EINVAL; + if (handle != ctx->sub->long_shader_in_progress_handle[type]) + return EINVAL; + } + + if (new_shader) { + sel = vrend_create_shader_state(ctx, so_info, type); + if (sel == NULL) + return ENOMEM; + + if (long_shader) { + sel->buf_len = ((offlen + 3) / 4) * 4; /* round up buffer size */ + sel->tmp_buf = malloc(sel->buf_len); + if (!sel->tmp_buf) { + ret = ENOMEM; + goto error; + } + memcpy(sel->tmp_buf, shd_text, pkt_length * 4); + sel->buf_offset = pkt_length * 4; + ctx->sub->long_shader_in_progress_handle[type] = handle; + } else + finished = true; + } else { + sel = vrend_object_lookup(ctx->sub->object_hash, handle, VIRGL_OBJECT_SHADER); + if (!sel) { + fprintf(stderr, ""got continuation without original shader %d\n"", handle); + ret = EINVAL; + goto error; + } + + offlen &= ~VIRGL_OBJ_SHADER_OFFSET_CONT; + if (offlen != sel->buf_offset) { + fprintf(stderr, ""Got mismatched shader continuation %d vs %d\n"", + offlen, sel->buf_offset); + ret = EINVAL; + goto error; + } + + /*make sure no overflow */ + if (pkt_length * 4 < pkt_length || + pkt_length * 4 + sel->buf_offset < pkt_length * 4 || + pkt_length * 4 + sel->buf_offset < sel->buf_offset) { + ret = EINVAL; + goto error; + } + + if ((pkt_length * 4 + sel->buf_offset) > sel->buf_len) { + fprintf(stderr, ""Got too large shader continuation %d vs %d\n"", + pkt_length * 4 + sel->buf_offset, sel->buf_len); + ret = EINVAL; + goto error; + } + + memcpy(sel->tmp_buf + sel->buf_offset, shd_text, pkt_length * 4); + + sel->buf_offset += pkt_length * 4; + if (sel->buf_offset >= sel->buf_len) { + finished = true; + shd_text = sel->tmp_buf; + } + } + + if (finished) { + struct tgsi_token *tokens; + + tokens = calloc(num_tokens + 10, sizeof(struct tgsi_token)); + if (!tokens) { + ret = ENOMEM; + goto error; + } + + if (vrend_dump_shaders) + fprintf(stderr,""shader\n%s\n"", shd_text); + if (!tgsi_text_translate((const char *)shd_text, tokens, num_tokens + 10)) { + free(tokens); + ret = EINVAL; + goto error; + } + + if (vrend_finish_shader(ctx, sel, tokens)) { + free(tokens); + ret = EINVAL; + goto error; + } else { + free(sel->tmp_buf); + sel->tmp_buf = NULL; + } + free(tokens); + ctx->sub->long_shader_in_progress_handle[type] = 0; + } + + if (new_shader) { + ret_handle = vrend_renderer_object_insert(ctx, sel, sizeof(*sel), handle, VIRGL_OBJECT_SHADER); + if (ret_handle == 0) { + ret = ENOMEM; + goto error; + } + } + + return 0; + +error: + if (new_shader) + vrend_destroy_shader_selector(sel); + else + vrend_renderer_object_destroy(ctx, handle); + + return ret; +} +","@@ -1648,18 +1648,19 @@ int vrend_create_vertex_elements_state(struct vrend_context *ctx, + unsigned num_elements, + const struct pipe_vertex_element *elements) + { +- struct vrend_vertex_element_array *v = CALLOC_STRUCT(vrend_vertex_element_array); ++ struct vrend_vertex_element_array *v; + const struct util_format_description *desc; + GLenum type; + int i; + uint32_t ret_handle; + +- if (!v) +- return ENOMEM; +- + if (num_elements > PIPE_MAX_ATTRIBS) + return EINVAL; + ++ v = CALLOC_STRUCT(vrend_vertex_element_array); ++ if (!v) ++ return ENOMEM; ++ + v->count = num_elements; + for (i = 0; i < num_elements; i++) { + memcpy(&v->elements[i].base, &elements[i], sizeof(struct pipe_vertex_element));",990,1321,2048 +18636," std::unique_ptr HandleFileRequest( + const base::FilePath& server_root, + const HttpRequest& request) { + base::ScopedAllowBlockingForTesting allow_blocking; + + GURL request_url = request.GetURL(); + std::string relative_path(request_url.path()); + + std::string post_prefix(""/post/""); + if (base::StartsWith(relative_path, post_prefix, + base::CompareCase::SENSITIVE)) { + if (request.method != METHOD_POST) + return nullptr; + relative_path = relative_path.substr(post_prefix.size() - 1); + } + + RequestQuery query = ParseQuery(request_url); + + std::unique_ptr failed_response(new BasicHttpResponse); + failed_response->set_code(HTTP_NOT_FOUND); + + if (query.find(""expected_body"") != query.end()) { + if (request.content.find(query[""expected_body""].front()) == + std::string::npos) { + return std::move(failed_response); + } + } + + if (query.find(""expected_headers"") != query.end()) { + for (const auto& header : query[""expected_headers""]) { + if (header.find("":"") == std::string::npos) + return std::move(failed_response); + std::string key = header.substr(0, header.find("":"")); + std::string value = header.substr(header.find("":"") + 1); + if (request.headers.find(key) == request.headers.end() || + request.headers.at(key) != value) { + return std::move(failed_response); + } + } + } + + DCHECK(base::StartsWith(relative_path, ""/"", base::CompareCase::SENSITIVE)); + std::string request_path = relative_path.substr(1); + base::FilePath file_path(server_root.AppendASCII(request_path)); + std::string file_contents; + if (!base::ReadFileToString(file_path, &file_contents)) { + file_path = file_path.AppendASCII(""index.html""); + if (!base::ReadFileToString(file_path, &file_contents)) + return nullptr; + } + + if (request.method == METHOD_HEAD) + file_contents = """"; + + if (query.find(""replace_text"") != query.end()) { + for (const auto& replacement : query[""replace_text""]) { + if (replacement.find("":"") == std::string::npos) + return std::move(failed_response); + std::string find; + std::string with; + base::Base64Decode(replacement.substr(0, replacement.find("":"")), &find); + base::Base64Decode(replacement.substr(replacement.find("":"") + 1), &with); + base::ReplaceSubstringsAfterOffset(&file_contents, 0, find, with); + } + } + + base::FilePath::StringPieceType mock_headers_extension; + #if defined(OS_WIN) + base::string16 temp = base::ASCIIToUTF16(kMockHttpHeadersExtension); + mock_headers_extension = temp; +#else + mock_headers_extension = kMockHttpHeadersExtension; +#endif + + base::FilePath headers_path(file_path.AddExtension(mock_headers_extension)); + + if (base::PathExists(headers_path)) { + std::string headers_contents; + + if (!base::ReadFileToString(headers_path, &headers_contents)) + return nullptr; + + return std::make_unique(headers_contents, file_contents); + } + + std::unique_ptr http_response(new BasicHttpResponse); + http_response->set_code(HTTP_OK); + + if (request.headers.find(""Range"") != request.headers.end()) { + std::vector ranges; + + if (HttpUtil::ParseRangeHeader(request.headers.at(""Range""), &ranges) && + ranges.size() == 1) { + ranges[0].ComputeBounds(file_contents.size()); + size_t start = ranges[0].first_byte_position(); + size_t end = ranges[0].last_byte_position(); + + http_response->set_code(HTTP_PARTIAL_CONTENT); + http_response->AddCustomHeader( + ""Content-Range"", + base::StringPrintf(""bytes %"" PRIuS ""-%"" PRIuS ""/%"" PRIuS, start, end, + file_contents.size())); + + file_contents = file_contents.substr(start, end - start + 1); + } + } + + http_response->set_content_type(GetContentType(file_path)); + http_response->AddCustomHeader(""Accept-Ranges"", ""bytes""); + http_response->AddCustomHeader(""ETag"", ""'"" + file_path.MaybeAsASCII() + ""'""); + http_response->set_content(file_contents); + return std::move(http_response); +} +",1," std::unique_ptr HandleFileRequest( + const base::FilePath& server_root, + const HttpRequest& request) { + base::ScopedAllowBlockingForTesting allow_blocking; + + GURL request_url = request.GetURL(); + std::string relative_path(request_url.path()); + + std::string post_prefix(""/post/""); + if (base::StartsWith(relative_path, post_prefix, + base::CompareCase::SENSITIVE)) { + if (request.method != METHOD_POST) + return nullptr; + relative_path = relative_path.substr(post_prefix.size() - 1); + } + + RequestQuery query = ParseQuery(request_url); + + std::unique_ptr failed_response(new BasicHttpResponse); + failed_response->set_code(HTTP_NOT_FOUND); + + if (query.find(""expected_body"") != query.end()) { + if (request.content.find(query[""expected_body""].front()) == + std::string::npos) { + return std::move(failed_response); + } + } + + if (query.find(""expected_headers"") != query.end()) { + for (const auto& header : query[""expected_headers""]) { + if (header.find("":"") == std::string::npos) + return std::move(failed_response); + std::string key = header.substr(0, header.find("":"")); + std::string value = header.substr(header.find("":"") + 1); + if (request.headers.find(key) == request.headers.end() || + request.headers.at(key) != value) { + return std::move(failed_response); + } + } + } + + DCHECK(base::StartsWith(relative_path, ""/"", base::CompareCase::SENSITIVE)); + std::string request_path = relative_path.substr(1); + base::FilePath file_path(server_root.AppendASCII(request_path)); + std::string file_contents; + if (!base::ReadFileToString(file_path, &file_contents)) { + file_path = file_path.AppendASCII(""index.html""); + if (!base::ReadFileToString(file_path, &file_contents)) + return nullptr; + } + + if (request.method == METHOD_HEAD) + file_contents = """"; + + if (!UpdateReplacedText(query, &file_contents)) + return std::move(failed_response); + + base::FilePath::StringPieceType mock_headers_extension; + #if defined(OS_WIN) + base::string16 temp = base::ASCIIToUTF16(kMockHttpHeadersExtension); + mock_headers_extension = temp; +#else + mock_headers_extension = kMockHttpHeadersExtension; +#endif + + base::FilePath headers_path(file_path.AddExtension(mock_headers_extension)); + + if (base::PathExists(headers_path)) { + std::string headers_contents; + + if (!base::ReadFileToString(headers_path, &headers_contents) || + !UpdateReplacedText(query, &headers_contents)) { + return nullptr; + } + + return std::make_unique(headers_contents, file_contents); + } + + std::unique_ptr http_response(new BasicHttpResponse); + http_response->set_code(HTTP_OK); + + if (request.headers.find(""Range"") != request.headers.end()) { + std::vector ranges; + + if (HttpUtil::ParseRangeHeader(request.headers.at(""Range""), &ranges) && + ranges.size() == 1) { + ranges[0].ComputeBounds(file_contents.size()); + size_t start = ranges[0].first_byte_position(); + size_t end = ranges[0].last_byte_position(); + + http_response->set_code(HTTP_PARTIAL_CONTENT); + http_response->AddCustomHeader( + ""Content-Range"", + base::StringPrintf(""bytes %"" PRIuS ""-%"" PRIuS ""/%"" PRIuS, start, end, + file_contents.size())); + + file_contents = file_contents.substr(start, end - start + 1); + } + } + + http_response->set_content_type(GetContentType(file_path)); + http_response->AddCustomHeader(""Accept-Ranges"", ""bytes""); + http_response->AddCustomHeader(""ETag"", ""'"" + file_path.MaybeAsASCII() + ""'""); + http_response->set_content(file_contents); + return std::move(http_response); +} +","@@ -120,6 +120,25 @@ void GetFilePathWithReplacements(const std::string& original_file_path, + *replacement_path = new_file_path; + } + ++// Returns false if there were errors, otherwise true. ++bool UpdateReplacedText(const RequestQuery& query, std::string* data) { ++ auto replace_text = query.find(""replace_text""); ++ if (replace_text == query.end()) ++ return true; ++ ++ for (const auto& replacement : replace_text->second) { ++ if (replacement.find("":"") == std::string::npos) ++ return false; ++ std::string find; ++ std::string with; ++ base::Base64Decode(replacement.substr(0, replacement.find("":"")), &find); ++ base::Base64Decode(replacement.substr(replacement.find("":"") + 1), &with); ++ base::ReplaceSubstringsAfterOffset(data, 0, find, with); ++ } ++ ++ return true; ++} ++ + // Handles |request| by serving a file from under |server_root|. + std::unique_ptr HandleFileRequest( + const base::FilePath& server_root, +@@ -180,17 +199,8 @@ std::unique_ptr HandleFileRequest( + if (request.method == METHOD_HEAD) + file_contents = """"; + +- if (query.find(""replace_text"") != query.end()) { +- for (const auto& replacement : query[""replace_text""]) { +- if (replacement.find("":"") == std::string::npos) +- return std::move(failed_response); +- std::string find; +- std::string with; +- base::Base64Decode(replacement.substr(0, replacement.find("":"")), &find); +- base::Base64Decode(replacement.substr(replacement.find("":"") + 1), &with); +- base::ReplaceSubstringsAfterOffset(&file_contents, 0, find, with); +- } +- } ++ if (!UpdateReplacedText(query, &file_contents)) ++ return std::move(failed_response); + + base::FilePath::StringPieceType mock_headers_extension; + #if defined(OS_WIN) +@@ -205,8 +215,10 @@ std::unique_ptr HandleFileRequest( + if (base::PathExists(headers_path)) { + std::string headers_contents; + +- if (!base::ReadFileToString(headers_path, &headers_contents)) ++ if (!base::ReadFileToString(headers_path, &headers_contents) || ++ !UpdateReplacedText(query, &headers_contents)) { + return nullptr; ++ } + + return std::make_unique(headers_contents, file_contents); + }",960,1291,2048 +8972,"get_upnp_rules_state_list(int max_rules_number_target) +{ + /*char ifname[IFNAMSIZ];*/ + int proto; + unsigned short iport; + unsigned int timestamp; + struct rule_state * tmp; + struct rule_state * list = 0; + struct rule_state * * p; + int i = 0; + time_t current_time; + + /*ifname[0] = '\0';*/ + tmp = malloc(sizeof(struct rule_state)); + if(!tmp) + return 0; + current_time = upnp_time(); + nextruletoclean_timestamp = 0; + while(get_redirect_rule_by_index(i, /*ifname*/0, &tmp->eport, 0, 0, + &iport, &proto, 0, 0, 0,0, ×tamp, + &tmp->packets, &tmp->bytes) >= 0) + { + tmp->to_remove = 0; + if(timestamp > 0) { + /* need to remove this port mapping ? */ + if(timestamp <= (unsigned int)current_time) + tmp->to_remove = 1; + else if((nextruletoclean_timestamp <= (unsigned int)current_time) + || (timestamp < nextruletoclean_timestamp)) + nextruletoclean_timestamp = timestamp; + } + tmp->proto = (short)proto; + /* add tmp to list */ + tmp->next = list; + list = tmp; + /* prepare next iteration */ + i++; + tmp = malloc(sizeof(struct rule_state)); + if(!tmp) + break; + } +#ifdef PCP_PEER + i=0; + while(get_peer_rule_by_index(i, /*ifname*/0, &tmp->eport, 0, 0, + &iport, &proto, 0, 0, 0,0,0, ×tamp, + &tmp->packets, &tmp->bytes) >= 0) + { + tmp->to_remove = 0; + if(timestamp > 0) { + /* need to remove this port mapping ? */ + if(timestamp <= (unsigned int)current_time) + tmp->to_remove = 1; + else if((nextruletoclean_timestamp <= (unsigned int)current_time) + || (timestamp < nextruletoclean_timestamp)) + nextruletoclean_timestamp = timestamp; + } + tmp->proto = (short)proto; + /* add tmp to list */ + tmp->next = list; + list = tmp; + /* prepare next iteration */ + i++; + tmp = malloc(sizeof(struct rule_state)); + if(!tmp) + break; + } +#endif + free(tmp); + /* remove the redirections that need to be removed */ + for(p = &list, tmp = list; tmp; tmp = *p) + { + if(tmp->to_remove) + { + syslog(LOG_NOTICE, ""remove port mapping %hu %s because it has expired"", + tmp->eport, proto_itoa(tmp->proto)); + _upnp_delete_redir(tmp->eport, tmp->proto); + *p = tmp->next; + free(tmp); + i--; + } else { + p = &(tmp->next); + } + } + /* return empty list if not enough redirections */ + if(i<=max_rules_number_target) + while(list) + { + tmp = list; + list = tmp->next; + free(tmp); + } + /* return list */ + return list; +} +",0,"get_upnp_rules_state_list(int max_rules_number_target) +{ + /*char ifname[IFNAMSIZ];*/ + int proto; + unsigned short iport; + unsigned int timestamp; + struct rule_state * tmp; + struct rule_state * list = 0; + struct rule_state * * p; + int i = 0; + time_t current_time; + + /*ifname[0] = '\0';*/ + tmp = malloc(sizeof(struct rule_state)); + if(!tmp) + return 0; + current_time = upnp_time(); + nextruletoclean_timestamp = 0; + while(get_redirect_rule_by_index(i, /*ifname*/0, &tmp->eport, 0, 0, + &iport, &proto, 0, 0, 0,0, ×tamp, + &tmp->packets, &tmp->bytes) >= 0) + { + tmp->to_remove = 0; + if(timestamp > 0) { + /* need to remove this port mapping ? */ + if(timestamp <= (unsigned int)current_time) + tmp->to_remove = 1; + else if((nextruletoclean_timestamp <= (unsigned int)current_time) + || (timestamp < nextruletoclean_timestamp)) + nextruletoclean_timestamp = timestamp; + } + tmp->proto = (short)proto; + /* add tmp to list */ + tmp->next = list; + list = tmp; + /* prepare next iteration */ + i++; + tmp = malloc(sizeof(struct rule_state)); + if(!tmp) + break; + } +#ifdef PCP_PEER + i=0; + while(get_peer_rule_by_index(i, /*ifname*/0, &tmp->eport, 0, 0, + &iport, &proto, 0, 0, 0,0,0, ×tamp, + &tmp->packets, &tmp->bytes) >= 0) + { + tmp->to_remove = 0; + if(timestamp > 0) { + /* need to remove this port mapping ? */ + if(timestamp <= (unsigned int)current_time) + tmp->to_remove = 1; + else if((nextruletoclean_timestamp <= (unsigned int)current_time) + || (timestamp < nextruletoclean_timestamp)) + nextruletoclean_timestamp = timestamp; + } + tmp->proto = (short)proto; + /* add tmp to list */ + tmp->next = list; + list = tmp; + /* prepare next iteration */ + i++; + tmp = malloc(sizeof(struct rule_state)); + if(!tmp) + break; + } +#endif + free(tmp); + /* remove the redirections that need to be removed */ + for(p = &list, tmp = list; tmp; tmp = *p) + { + if(tmp->to_remove) + { + syslog(LOG_NOTICE, ""remove port mapping %hu %s because it has expired"", + tmp->eport, proto_itoa(tmp->proto)); + _upnp_delete_redir(tmp->eport, tmp->proto); + *p = tmp->next; + free(tmp); + i--; + } else { + p = &(tmp->next); + } + } + /* return empty list if not enough redirections */ + if(i<=max_rules_number_target) + while(list) + { + tmp = list; + list = tmp->next; + free(tmp); + } + /* return list */ + return list; +} +","@@ -356,6 +356,10 @@ upnp_redirect(const char * rhost, unsigned short eport, + ""%hu->%s:%hu %s"", eport, iaddr, iport, protocol); + return -3; + } ++ ++ if (desc == NULL) ++ desc = """"; /* assume empty description */ ++ + /* IGDv1 (WANIPConnection:1 Service Template Version 1.01 / Nov 12, 2001) + * - 2.2.20.PortMappingDescription : + * Overwriting Previous / Existing Port Mappings:",744,1075,2048 +712,"int smp_fetch_cookie(const struct arg *args, struct sample *smp, const char *kw, void *private) +{ + struct http_txn *txn; + struct hdr_idx *idx; + struct hdr_ctx *ctx = smp->ctx.a[2]; + const struct http_msg *msg; + const char *hdr_name; + int hdr_name_len; + char *sol; + int occ = 0; + int found = 0; + + if (!args || args->type != ARGT_STR) + return 0; + + if (!ctx) { + /* first call */ + ctx = &static_hdr_ctx; + ctx->idx = 0; + smp->ctx.a[2] = ctx; + } + + CHECK_HTTP_MESSAGE_FIRST(); + + txn = smp->strm->txn; + idx = &smp->strm->txn->hdr_idx; + + if ((smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ) { + msg = &txn->req; + hdr_name = ""Cookie""; + hdr_name_len = 6; + } else { + msg = &txn->rsp; + hdr_name = ""Set-Cookie""; + hdr_name_len = 10; + } + + if (!occ && !(smp->opt & SMP_OPT_ITERATE)) + /* no explicit occurrence and single fetch => last cookie by default */ + occ = -1; + + /* OK so basically here, either we want only one value and it's the + * last one, or we want to iterate over all of them and we fetch the + * next one. + */ + + sol = msg->chn->buf->p; + if (!(smp->flags & SMP_F_NOT_LAST)) { + /* search for the header from the beginning, we must first initialize + * the search parameters. + */ + smp->ctx.a[0] = NULL; + ctx->idx = 0; + } + + smp->flags |= SMP_F_VOL_HDR; + + while (1) { + /* Note: smp->ctx.a[0] == NULL every time we need to fetch a new header */ + if (!smp->ctx.a[0]) { + if (!http_find_header2(hdr_name, hdr_name_len, sol, idx, ctx)) + goto out; + + if (ctx->vlen < args->data.str.len + 1) + continue; + + smp->ctx.a[0] = ctx->line + ctx->val; + smp->ctx.a[1] = smp->ctx.a[0] + ctx->vlen; + } + + smp->data.type = SMP_T_STR; + smp->flags |= SMP_F_CONST; + smp->ctx.a[0] = extract_cookie_value(smp->ctx.a[0], smp->ctx.a[1], + args->data.str.str, args->data.str.len, + (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ, + &smp->data.u.str.str, + &smp->data.u.str.len); + if (smp->ctx.a[0]) { + found = 1; + if (occ >= 0) { + /* one value was returned into smp->data.u.str.{str,len} */ + smp->flags |= SMP_F_NOT_LAST; + return 1; + } + } + /* if we're looking for last occurrence, let's loop */ + } + /* all cookie headers and values were scanned. If we're looking for the + * last occurrence, we may return it now. + */ + out: + smp->flags &= ~SMP_F_NOT_LAST; + return found; +} +",0,"int smp_fetch_cookie(const struct arg *args, struct sample *smp, const char *kw, void *private) +{ + struct http_txn *txn; + struct hdr_idx *idx; + struct hdr_ctx *ctx = smp->ctx.a[2]; + const struct http_msg *msg; + const char *hdr_name; + int hdr_name_len; + char *sol; + int occ = 0; + int found = 0; + + if (!args || args->type != ARGT_STR) + return 0; + + if (!ctx) { + /* first call */ + ctx = &static_hdr_ctx; + ctx->idx = 0; + smp->ctx.a[2] = ctx; + } + + CHECK_HTTP_MESSAGE_FIRST(); + + txn = smp->strm->txn; + idx = &smp->strm->txn->hdr_idx; + + if ((smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ) { + msg = &txn->req; + hdr_name = ""Cookie""; + hdr_name_len = 6; + } else { + msg = &txn->rsp; + hdr_name = ""Set-Cookie""; + hdr_name_len = 10; + } + + if (!occ && !(smp->opt & SMP_OPT_ITERATE)) + /* no explicit occurrence and single fetch => last cookie by default */ + occ = -1; + + /* OK so basically here, either we want only one value and it's the + * last one, or we want to iterate over all of them and we fetch the + * next one. + */ + + sol = msg->chn->buf->p; + if (!(smp->flags & SMP_F_NOT_LAST)) { + /* search for the header from the beginning, we must first initialize + * the search parameters. + */ + smp->ctx.a[0] = NULL; + ctx->idx = 0; + } + + smp->flags |= SMP_F_VOL_HDR; + + while (1) { + /* Note: smp->ctx.a[0] == NULL every time we need to fetch a new header */ + if (!smp->ctx.a[0]) { + if (!http_find_header2(hdr_name, hdr_name_len, sol, idx, ctx)) + goto out; + + if (ctx->vlen < args->data.str.len + 1) + continue; + + smp->ctx.a[0] = ctx->line + ctx->val; + smp->ctx.a[1] = smp->ctx.a[0] + ctx->vlen; + } + + smp->data.type = SMP_T_STR; + smp->flags |= SMP_F_CONST; + smp->ctx.a[0] = extract_cookie_value(smp->ctx.a[0], smp->ctx.a[1], + args->data.str.str, args->data.str.len, + (smp->opt & SMP_OPT_DIR) == SMP_OPT_DIR_REQ, + &smp->data.u.str.str, + &smp->data.u.str.len); + if (smp->ctx.a[0]) { + found = 1; + if (occ >= 0) { + /* one value was returned into smp->data.u.str.{str,len} */ + smp->flags |= SMP_F_NOT_LAST; + return 1; + } + } + /* if we're looking for last occurrence, let's loop */ + } + /* all cookie headers and values were scanned. If we're looking for the + * last occurrence, we may return it now. + */ + out: + smp->flags &= ~SMP_F_NOT_LAST; + return found; +} +","@@ -7724,6 +7724,15 @@ void check_request_for_cacheability(struct stream *s, struct channel *chn) + } + } + ++ /* Don't use the cache and don't try to store if we found the ++ * Authorization header */ ++ val = http_header_match2(cur_ptr, cur_end, ""Authorization"", 13); ++ if (val) { ++ txn->flags &= ~TX_CACHEABLE & ~TX_CACHE_COOK; ++ txn->flags |= TX_CACHE_IGNORE; ++ continue; ++ } ++ + val = http_header_match2(cur_ptr, cur_end, ""Cache-control"", 13); + if (!val) + continue;",778,1109,2048 +18651,"void FrameLoader::Load(const FrameLoadRequest& passed_request, + FrameLoadType frame_load_type, + HistoryItem* history_item, + HistoryLoadType history_load_type) { + DCHECK(frame_->GetDocument()); + + if (IsBackForwardLoadType(frame_load_type) && !frame_->IsNavigationAllowed()) + return; + + if (in_stop_all_loaders_) + return; + + FrameLoadRequest request(passed_request); + request.GetResourceRequest().SetHasUserGesture( + Frame::HasTransientUserActivation(frame_)); + + if (!PrepareRequestForThisFrame(request)) + return; + + Frame* target_frame = request.Form() + ? nullptr + : frame_->FindFrameForNavigation( + AtomicString(request.FrameName()), *frame_, + request.GetResourceRequest().Url()); + + NavigationPolicy policy = NavigationPolicyForRequest(request); + if (target_frame && target_frame != frame_ && + ShouldNavigateTargetFrame(policy)) { + if (target_frame->IsLocalFrame() && + !ToLocalFrame(target_frame)->IsNavigationAllowed()) { + return; + } + + bool was_in_same_page = target_frame->GetPage() == frame_->GetPage(); + + request.SetFrameName(""_self""); + target_frame->Navigate(request); + Page* page = target_frame->GetPage(); + if (!was_in_same_page && page) + page->GetChromeClient().Focus(); + return; + } + + SetReferrerForFrameRequest(request); + + if (!target_frame && !request.FrameName().IsEmpty()) { + if (policy == kNavigationPolicyDownload) { + Client()->DownloadURL(request.GetResourceRequest(), String()); + return; // Navigation/download will be handled by the client. + } else if (ShouldNavigateTargetFrame(policy)) { + request.GetResourceRequest().SetFrameType( + network::mojom::RequestContextFrameType::kAuxiliary); + CreateWindowForRequest(request, *frame_, policy); + return; // Navigation will be handled by the new frame/window. + } + } + + if (!frame_->IsNavigationAllowed()) + return; + + const KURL& url = request.GetResourceRequest().Url(); + FrameLoadType new_load_type = (frame_load_type == kFrameLoadTypeStandard) + ? DetermineFrameLoadType(request) + : frame_load_type; + bool same_document_history_navigation = + IsBackForwardLoadType(new_load_type) && + history_load_type == kHistorySameDocumentLoad; + bool same_document_navigation = + policy == kNavigationPolicyCurrentTab && + ShouldPerformFragmentNavigation(request.Form(), + request.GetResourceRequest().HttpMethod(), + new_load_type, url); + + if (same_document_history_navigation || same_document_navigation) { + DCHECK(history_item || !same_document_history_navigation); + scoped_refptr state_object = + same_document_history_navigation ? history_item->StateObject() + : nullptr; + + if (!same_document_history_navigation) { + document_loader_->SetNavigationType(DetermineNavigationType( + new_load_type, false, request.TriggeringEvent())); + if (ShouldTreatURLAsSameAsCurrent(url)) + new_load_type = kFrameLoadTypeReplaceCurrentItem; + } + + LoadInSameDocument(url, state_object, new_load_type, history_item, + request.ClientRedirect(), request.OriginDocument()); + return; + } + + if (request.GetResourceRequest().IsSameDocumentNavigation()) + return; + + StartLoad(request, new_load_type, policy, history_item); +} +",1,"void FrameLoader::Load(const FrameLoadRequest& passed_request, + FrameLoadType frame_load_type, + HistoryItem* history_item, + HistoryLoadType history_load_type) { + DCHECK(frame_->GetDocument()); + + if (IsBackForwardLoadType(frame_load_type) && !frame_->IsNavigationAllowed()) + return; + + if (in_stop_all_loaders_) + return; + + FrameLoadRequest request(passed_request); + request.GetResourceRequest().SetHasUserGesture( + Frame::HasTransientUserActivation(frame_)); + + if (!PrepareRequestForThisFrame(request)) + return; + + Frame* target_frame = request.Form() + ? nullptr + : frame_->FindFrameForNavigation( + AtomicString(request.FrameName()), *frame_, + request.GetResourceRequest().Url()); + + NavigationPolicy policy = NavigationPolicyForRequest(request); + if (target_frame && target_frame != frame_ && + ShouldNavigateTargetFrame(policy)) { + if (target_frame->IsLocalFrame() && + !ToLocalFrame(target_frame)->IsNavigationAllowed()) { + return; + } + + bool was_in_same_page = target_frame->GetPage() == frame_->GetPage(); + + request.SetFrameName(""_self""); + target_frame->Navigate(request); + Page* page = target_frame->GetPage(); + if (!was_in_same_page && page) + page->GetChromeClient().Focus(nullptr); + return; + } + + SetReferrerForFrameRequest(request); + + if (!target_frame && !request.FrameName().IsEmpty()) { + if (policy == kNavigationPolicyDownload) { + Client()->DownloadURL(request.GetResourceRequest(), String()); + return; // Navigation/download will be handled by the client. + } else if (ShouldNavigateTargetFrame(policy)) { + request.GetResourceRequest().SetFrameType( + network::mojom::RequestContextFrameType::kAuxiliary); + CreateWindowForRequest(request, *frame_, policy); + return; // Navigation will be handled by the new frame/window. + } + } + + if (!frame_->IsNavigationAllowed()) + return; + + const KURL& url = request.GetResourceRequest().Url(); + FrameLoadType new_load_type = (frame_load_type == kFrameLoadTypeStandard) + ? DetermineFrameLoadType(request) + : frame_load_type; + bool same_document_history_navigation = + IsBackForwardLoadType(new_load_type) && + history_load_type == kHistorySameDocumentLoad; + bool same_document_navigation = + policy == kNavigationPolicyCurrentTab && + ShouldPerformFragmentNavigation(request.Form(), + request.GetResourceRequest().HttpMethod(), + new_load_type, url); + + if (same_document_history_navigation || same_document_navigation) { + DCHECK(history_item || !same_document_history_navigation); + scoped_refptr state_object = + same_document_history_navigation ? history_item->StateObject() + : nullptr; + + if (!same_document_history_navigation) { + document_loader_->SetNavigationType(DetermineNavigationType( + new_load_type, false, request.TriggeringEvent())); + if (ShouldTreatURLAsSameAsCurrent(url)) + new_load_type = kFrameLoadTypeReplaceCurrentItem; + } + + LoadInSameDocument(url, state_object, new_load_type, history_item, + request.ClientRedirect(), request.OriginDocument()); + return; + } + + if (request.GetResourceRequest().IsSameDocumentNavigation()) + return; + + StartLoad(request, new_load_type, policy, history_item); +} +","@@ -903,7 +903,7 @@ void FrameLoader::Load(const FrameLoadRequest& passed_request, + target_frame->Navigate(request); + Page* page = target_frame->GetPage(); + if (!was_in_same_page && page) +- page->GetChromeClient().Focus(); ++ page->GetChromeClient().Focus(nullptr); + return; + } + ",722,1053,2048 +761,"apprentice_magic_strength(const struct magic *m) +{ +#define MULT 10 + size_t val = 2 * MULT; /* baseline strength */ + + switch (m->type) { + case FILE_DEFAULT: /* make sure this sorts last */ + if (m->factor_op != FILE_FACTOR_OP_NONE) + abort(); + return 0; + + case FILE_BYTE: + val += 1 * MULT; + break; + + case FILE_SHORT: + case FILE_LESHORT: + case FILE_BESHORT: + val += 2 * MULT; + break; + + case FILE_LONG: + case FILE_LELONG: + case FILE_BELONG: + case FILE_MELONG: + val += 4 * MULT; + break; + + case FILE_PSTRING: + case FILE_STRING: + val += m->vallen * MULT; + break; + + case FILE_BESTRING16: + case FILE_LESTRING16: + val += m->vallen * MULT / 2; + break; + + case FILE_SEARCH: + case FILE_REGEX: + val += m->vallen * MAX(MULT / m->vallen, 1); + break; + + case FILE_DATE: + case FILE_LEDATE: + case FILE_BEDATE: + case FILE_MEDATE: + case FILE_LDATE: + case FILE_LELDATE: + case FILE_BELDATE: + case FILE_MELDATE: + case FILE_FLOAT: + case FILE_BEFLOAT: + case FILE_LEFLOAT: + val += 4 * MULT; + break; + + case FILE_QUAD: + case FILE_BEQUAD: + case FILE_LEQUAD: + case FILE_QDATE: + case FILE_LEQDATE: + case FILE_BEQDATE: + case FILE_QLDATE: + case FILE_LEQLDATE: + case FILE_BEQLDATE: + case FILE_QWDATE: + case FILE_LEQWDATE: + case FILE_BEQWDATE: + case FILE_DOUBLE: + case FILE_BEDOUBLE: + case FILE_LEDOUBLE: + val += 8 * MULT; + break; + + case FILE_INDIRECT: + case FILE_NAME: + case FILE_USE: + break; + + default: + val = 0; + (void)fprintf(stderr, ""Bad type %d\n"", m->type); + abort(); + } + + switch (m->reln) { + case 'x': /* matches anything penalize */ + case '!': /* matches almost anything penalize */ + val = 0; + break; + + case '=': /* Exact match, prefer */ + val += MULT; + break; + + case '>': + case '<': /* comparison match reduce strength */ + val -= 2 * MULT; + break; + + case '^': + case '&': /* masking bits, we could count them too */ + val -= MULT; + break; + + default: + (void)fprintf(stderr, ""Bad relation %c\n"", m->reln); + abort(); + } + + if (val == 0) /* ensure we only return 0 for FILE_DEFAULT */ + val = 1; + + switch (m->factor_op) { + case FILE_FACTOR_OP_NONE: + break; + case FILE_FACTOR_OP_PLUS: + val += m->factor; + break; + case FILE_FACTOR_OP_MINUS: + val -= m->factor; + break; + case FILE_FACTOR_OP_TIMES: + val *= m->factor; + break; + case FILE_FACTOR_OP_DIV: + val /= m->factor; + break; + default: + abort(); + } + + /* + * Magic entries with no description get a bonus because they depend + * on subsequent magic entries to print something. + */ + if (m->desc[0] == '\0') + val++; + return val; +} +",0,"apprentice_magic_strength(const struct magic *m) +{ +#define MULT 10 + size_t val = 2 * MULT; /* baseline strength */ + + switch (m->type) { + case FILE_DEFAULT: /* make sure this sorts last */ + if (m->factor_op != FILE_FACTOR_OP_NONE) + abort(); + return 0; + + case FILE_BYTE: + val += 1 * MULT; + break; + + case FILE_SHORT: + case FILE_LESHORT: + case FILE_BESHORT: + val += 2 * MULT; + break; + + case FILE_LONG: + case FILE_LELONG: + case FILE_BELONG: + case FILE_MELONG: + val += 4 * MULT; + break; + + case FILE_PSTRING: + case FILE_STRING: + val += m->vallen * MULT; + break; + + case FILE_BESTRING16: + case FILE_LESTRING16: + val += m->vallen * MULT / 2; + break; + + case FILE_SEARCH: + case FILE_REGEX: + val += m->vallen * MAX(MULT / m->vallen, 1); + break; + + case FILE_DATE: + case FILE_LEDATE: + case FILE_BEDATE: + case FILE_MEDATE: + case FILE_LDATE: + case FILE_LELDATE: + case FILE_BELDATE: + case FILE_MELDATE: + case FILE_FLOAT: + case FILE_BEFLOAT: + case FILE_LEFLOAT: + val += 4 * MULT; + break; + + case FILE_QUAD: + case FILE_BEQUAD: + case FILE_LEQUAD: + case FILE_QDATE: + case FILE_LEQDATE: + case FILE_BEQDATE: + case FILE_QLDATE: + case FILE_LEQLDATE: + case FILE_BEQLDATE: + case FILE_QWDATE: + case FILE_LEQWDATE: + case FILE_BEQWDATE: + case FILE_DOUBLE: + case FILE_BEDOUBLE: + case FILE_LEDOUBLE: + val += 8 * MULT; + break; + + case FILE_INDIRECT: + case FILE_NAME: + case FILE_USE: + break; + + default: + val = 0; + (void)fprintf(stderr, ""Bad type %d\n"", m->type); + abort(); + } + + switch (m->reln) { + case 'x': /* matches anything penalize */ + case '!': /* matches almost anything penalize */ + val = 0; + break; + + case '=': /* Exact match, prefer */ + val += MULT; + break; + + case '>': + case '<': /* comparison match reduce strength */ + val -= 2 * MULT; + break; + + case '^': + case '&': /* masking bits, we could count them too */ + val -= MULT; + break; + + default: + (void)fprintf(stderr, ""Bad relation %c\n"", m->reln); + abort(); + } + + if (val == 0) /* ensure we only return 0 for FILE_DEFAULT */ + val = 1; + + switch (m->factor_op) { + case FILE_FACTOR_OP_NONE: + break; + case FILE_FACTOR_OP_PLUS: + val += m->factor; + break; + case FILE_FACTOR_OP_MINUS: + val -= m->factor; + break; + case FILE_FACTOR_OP_TIMES: + val *= m->factor; + break; + case FILE_FACTOR_OP_DIV: + val /= m->factor; + break; + default: + abort(); + } + + /* + * Magic entries with no description get a bonus because they depend + * on subsequent magic entries to print something. + */ + if (m->desc[0] == '\0') + val++; + return val; +} +","@@ -1197,7 +1197,6 @@ apprentice_load(struct magic_set *ms, const char *fn, int action) + if ((filearr = CAST(char **, + erealloc(filearr, mlen))) == NULL) { + file_oomem(ms, mlen); +- efree(mfn); + php_stream_closedir(dir); + errs++; + goto out;",741,1072,2048 +17934,"void sctp_assoc_update(struct sctp_association *asoc, + struct sctp_association *new) +{ + struct sctp_transport *trans; + struct list_head *pos, *temp; + + /* Copy in new parameters of peer. */ + asoc->c = new->c; + asoc->peer.rwnd = new->peer.rwnd; + asoc->peer.sack_needed = new->peer.sack_needed; + asoc->peer.i = new->peer.i; + sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL, + asoc->peer.i.initial_tsn, GFP_ATOMIC); + + /* Remove any peer addresses not present in the new association. */ + list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) { + trans = list_entry(pos, struct sctp_transport, transports); + if (!sctp_assoc_lookup_paddr(new, &trans->ipaddr)) { + sctp_assoc_rm_peer(asoc, trans); + continue; + } + + if (asoc->state >= SCTP_STATE_ESTABLISHED) + sctp_transport_reset(trans); + } + + /* If the case is A (association restart), use + * initial_tsn as next_tsn. If the case is B, use + * current next_tsn in case data sent to peer + * has been discarded and needs retransmission. + */ + if (asoc->state >= SCTP_STATE_ESTABLISHED) { + asoc->next_tsn = new->next_tsn; + asoc->ctsn_ack_point = new->ctsn_ack_point; + asoc->adv_peer_ack_point = new->adv_peer_ack_point; + + /* Reinitialize SSN for both local streams + * and peer's streams. + */ + sctp_ssnmap_clear(asoc->ssnmap); + + /* Flush the ULP reassembly and ordered queue. + * Any data there will now be stale and will + * cause problems. + */ + sctp_ulpq_flush(&asoc->ulpq); + + /* reset the overall association error count so + * that the restarted association doesn't get torn + * down on the next retransmission timer. + */ + asoc->overall_error_count = 0; + + } else { + /* Add any peer addresses from the new association. */ + list_for_each_entry(trans, &new->peer.transport_addr_list, + transports) { + if (!sctp_assoc_lookup_paddr(asoc, &trans->ipaddr)) + sctp_assoc_add_peer(asoc, &trans->ipaddr, + GFP_ATOMIC, trans->state); + } + + asoc->ctsn_ack_point = asoc->next_tsn - 1; + asoc->adv_peer_ack_point = asoc->ctsn_ack_point; + if (!asoc->ssnmap) { + /* Move the ssnmap. */ + asoc->ssnmap = new->ssnmap; + new->ssnmap = NULL; + } + + if (!asoc->assoc_id) { + /* get a new association id since we don't have one + * yet. + */ + sctp_assoc_set_id(asoc, GFP_ATOMIC); + } + } + + /* SCTP-AUTH: Save the peer parameters from the new associations + * and also move the association shared keys over + */ + kfree(asoc->peer.peer_random); + asoc->peer.peer_random = new->peer.peer_random; + new->peer.peer_random = NULL; + + kfree(asoc->peer.peer_chunks); + asoc->peer.peer_chunks = new->peer.peer_chunks; + new->peer.peer_chunks = NULL; + + kfree(asoc->peer.peer_hmacs); + asoc->peer.peer_hmacs = new->peer.peer_hmacs; + new->peer.peer_hmacs = NULL; + + sctp_auth_key_put(asoc->asoc_shared_key); + sctp_auth_asoc_init_active_key(asoc, GFP_ATOMIC); +} +",1,"void sctp_assoc_update(struct sctp_association *asoc, + struct sctp_association *new) +{ + struct sctp_transport *trans; + struct list_head *pos, *temp; + + /* Copy in new parameters of peer. */ + asoc->c = new->c; + asoc->peer.rwnd = new->peer.rwnd; + asoc->peer.sack_needed = new->peer.sack_needed; + asoc->peer.auth_capable = new->peer.auth_capable; + asoc->peer.i = new->peer.i; + sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL, + asoc->peer.i.initial_tsn, GFP_ATOMIC); + + /* Remove any peer addresses not present in the new association. */ + list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) { + trans = list_entry(pos, struct sctp_transport, transports); + if (!sctp_assoc_lookup_paddr(new, &trans->ipaddr)) { + sctp_assoc_rm_peer(asoc, trans); + continue; + } + + if (asoc->state >= SCTP_STATE_ESTABLISHED) + sctp_transport_reset(trans); + } + + /* If the case is A (association restart), use + * initial_tsn as next_tsn. If the case is B, use + * current next_tsn in case data sent to peer + * has been discarded and needs retransmission. + */ + if (asoc->state >= SCTP_STATE_ESTABLISHED) { + asoc->next_tsn = new->next_tsn; + asoc->ctsn_ack_point = new->ctsn_ack_point; + asoc->adv_peer_ack_point = new->adv_peer_ack_point; + + /* Reinitialize SSN for both local streams + * and peer's streams. + */ + sctp_ssnmap_clear(asoc->ssnmap); + + /* Flush the ULP reassembly and ordered queue. + * Any data there will now be stale and will + * cause problems. + */ + sctp_ulpq_flush(&asoc->ulpq); + + /* reset the overall association error count so + * that the restarted association doesn't get torn + * down on the next retransmission timer. + */ + asoc->overall_error_count = 0; + + } else { + /* Add any peer addresses from the new association. */ + list_for_each_entry(trans, &new->peer.transport_addr_list, + transports) { + if (!sctp_assoc_lookup_paddr(asoc, &trans->ipaddr)) + sctp_assoc_add_peer(asoc, &trans->ipaddr, + GFP_ATOMIC, trans->state); + } + + asoc->ctsn_ack_point = asoc->next_tsn - 1; + asoc->adv_peer_ack_point = asoc->ctsn_ack_point; + if (!asoc->ssnmap) { + /* Move the ssnmap. */ + asoc->ssnmap = new->ssnmap; + new->ssnmap = NULL; + } + + if (!asoc->assoc_id) { + /* get a new association id since we don't have one + * yet. + */ + sctp_assoc_set_id(asoc, GFP_ATOMIC); + } + } + + /* SCTP-AUTH: Save the peer parameters from the new associations + * and also move the association shared keys over + */ + kfree(asoc->peer.peer_random); + asoc->peer.peer_random = new->peer.peer_random; + new->peer.peer_random = NULL; + + kfree(asoc->peer.peer_chunks); + asoc->peer.peer_chunks = new->peer.peer_chunks; + new->peer.peer_chunks = NULL; + + kfree(asoc->peer.peer_hmacs); + asoc->peer.peer_hmacs = new->peer.peer_hmacs; + new->peer.peer_hmacs = NULL; + + sctp_auth_key_put(asoc->asoc_shared_key); + sctp_auth_asoc_init_active_key(asoc, GFP_ATOMIC); +} +","@@ -1097,6 +1097,7 @@ void sctp_assoc_update(struct sctp_association *asoc, + asoc->c = new->c; + asoc->peer.rwnd = new->peer.rwnd; + asoc->peer.sack_needed = new->peer.sack_needed; ++ asoc->peer.auth_capable = new->peer.auth_capable; + asoc->peer.i = new->peer.i; + sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL, + asoc->peer.i.initial_tsn, GFP_ATOMIC);",853,1184,2048 +605,"static void xhci_process_commands(XHCIState *xhci) +{ + XHCITRB trb; + TRBType type; + XHCIEvent event = {ER_COMMAND_COMPLETE, CC_SUCCESS}; + dma_addr_t addr; + unsigned int i, slotid = 0; + + DPRINTF(""xhci_process_commands()\n""); + if (!xhci_running(xhci)) { + DPRINTF(""xhci_process_commands() called while xHC stopped or paused\n""); + return; + } + + xhci->crcr_low |= CRCR_CRR; + + while ((type = xhci_ring_fetch(xhci, &xhci->cmd_ring, &trb, &addr))) { + event.ptr = addr; + switch (type) { + case CR_ENABLE_SLOT: + for (i = 0; i < xhci->numslots; i++) { + if (!xhci->slots[i].enabled) { + break; + } + } + if (i >= xhci->numslots) { + DPRINTF(""xhci: no device slots available\n""); + event.ccode = CC_NO_SLOTS_ERROR; + } else { + slotid = i+1; + event.ccode = xhci_enable_slot(xhci, slotid); + } + break; + case CR_DISABLE_SLOT: + slotid = xhci_get_slot(xhci, &event, &trb); + if (slotid) { + event.ccode = xhci_disable_slot(xhci, slotid); + } + break; + case CR_ADDRESS_DEVICE: + slotid = xhci_get_slot(xhci, &event, &trb); + if (slotid) { + event.ccode = xhci_address_slot(xhci, slotid, trb.parameter, + trb.control & TRB_CR_BSR); + } + break; + case CR_CONFIGURE_ENDPOINT: + slotid = xhci_get_slot(xhci, &event, &trb); + if (slotid) { + event.ccode = xhci_configure_slot(xhci, slotid, trb.parameter, + trb.control & TRB_CR_DC); + } + break; + case CR_EVALUATE_CONTEXT: + slotid = xhci_get_slot(xhci, &event, &trb); + if (slotid) { + event.ccode = xhci_evaluate_slot(xhci, slotid, trb.parameter); + } + break; + case CR_STOP_ENDPOINT: + slotid = xhci_get_slot(xhci, &event, &trb); + if (slotid) { + unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT) + & TRB_CR_EPID_MASK; + event.ccode = xhci_stop_ep(xhci, slotid, epid); + } + break; + case CR_RESET_ENDPOINT: + slotid = xhci_get_slot(xhci, &event, &trb); + if (slotid) { + unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT) + & TRB_CR_EPID_MASK; + event.ccode = xhci_reset_ep(xhci, slotid, epid); + } + break; + case CR_SET_TR_DEQUEUE: + slotid = xhci_get_slot(xhci, &event, &trb); + if (slotid) { + unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT) + & TRB_CR_EPID_MASK; + unsigned int streamid = (trb.status >> 16) & 0xffff; + event.ccode = xhci_set_ep_dequeue(xhci, slotid, + epid, streamid, + trb.parameter); + } + break; + case CR_RESET_DEVICE: + slotid = xhci_get_slot(xhci, &event, &trb); + if (slotid) { + event.ccode = xhci_reset_slot(xhci, slotid); + } + break; + case CR_GET_PORT_BANDWIDTH: + event.ccode = xhci_get_port_bandwidth(xhci, trb.parameter); + break; + case CR_VENDOR_VIA_CHALLENGE_RESPONSE: + xhci_via_challenge(xhci, trb.parameter); + break; + case CR_VENDOR_NEC_FIRMWARE_REVISION: + event.type = 48; /* NEC reply */ + event.length = 0x3025; + break; + case CR_VENDOR_NEC_CHALLENGE_RESPONSE: + { + uint32_t chi = trb.parameter >> 32; + uint32_t clo = trb.parameter; + uint32_t val = xhci_nec_challenge(chi, clo); + event.length = val & 0xFFFF; + event.epid = val >> 16; + slotid = val >> 24; + event.type = 48; /* NEC reply */ + } + break; + default: + trace_usb_xhci_unimplemented(""command"", type); + event.ccode = CC_TRB_ERROR; + break; + } + event.slotid = slotid; + xhci_event(xhci, &event, 0); + } +} +",0,"static void xhci_process_commands(XHCIState *xhci) +{ + XHCITRB trb; + TRBType type; + XHCIEvent event = {ER_COMMAND_COMPLETE, CC_SUCCESS}; + dma_addr_t addr; + unsigned int i, slotid = 0; + + DPRINTF(""xhci_process_commands()\n""); + if (!xhci_running(xhci)) { + DPRINTF(""xhci_process_commands() called while xHC stopped or paused\n""); + return; + } + + xhci->crcr_low |= CRCR_CRR; + + while ((type = xhci_ring_fetch(xhci, &xhci->cmd_ring, &trb, &addr))) { + event.ptr = addr; + switch (type) { + case CR_ENABLE_SLOT: + for (i = 0; i < xhci->numslots; i++) { + if (!xhci->slots[i].enabled) { + break; + } + } + if (i >= xhci->numslots) { + DPRINTF(""xhci: no device slots available\n""); + event.ccode = CC_NO_SLOTS_ERROR; + } else { + slotid = i+1; + event.ccode = xhci_enable_slot(xhci, slotid); + } + break; + case CR_DISABLE_SLOT: + slotid = xhci_get_slot(xhci, &event, &trb); + if (slotid) { + event.ccode = xhci_disable_slot(xhci, slotid); + } + break; + case CR_ADDRESS_DEVICE: + slotid = xhci_get_slot(xhci, &event, &trb); + if (slotid) { + event.ccode = xhci_address_slot(xhci, slotid, trb.parameter, + trb.control & TRB_CR_BSR); + } + break; + case CR_CONFIGURE_ENDPOINT: + slotid = xhci_get_slot(xhci, &event, &trb); + if (slotid) { + event.ccode = xhci_configure_slot(xhci, slotid, trb.parameter, + trb.control & TRB_CR_DC); + } + break; + case CR_EVALUATE_CONTEXT: + slotid = xhci_get_slot(xhci, &event, &trb); + if (slotid) { + event.ccode = xhci_evaluate_slot(xhci, slotid, trb.parameter); + } + break; + case CR_STOP_ENDPOINT: + slotid = xhci_get_slot(xhci, &event, &trb); + if (slotid) { + unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT) + & TRB_CR_EPID_MASK; + event.ccode = xhci_stop_ep(xhci, slotid, epid); + } + break; + case CR_RESET_ENDPOINT: + slotid = xhci_get_slot(xhci, &event, &trb); + if (slotid) { + unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT) + & TRB_CR_EPID_MASK; + event.ccode = xhci_reset_ep(xhci, slotid, epid); + } + break; + case CR_SET_TR_DEQUEUE: + slotid = xhci_get_slot(xhci, &event, &trb); + if (slotid) { + unsigned int epid = (trb.control >> TRB_CR_EPID_SHIFT) + & TRB_CR_EPID_MASK; + unsigned int streamid = (trb.status >> 16) & 0xffff; + event.ccode = xhci_set_ep_dequeue(xhci, slotid, + epid, streamid, + trb.parameter); + } + break; + case CR_RESET_DEVICE: + slotid = xhci_get_slot(xhci, &event, &trb); + if (slotid) { + event.ccode = xhci_reset_slot(xhci, slotid); + } + break; + case CR_GET_PORT_BANDWIDTH: + event.ccode = xhci_get_port_bandwidth(xhci, trb.parameter); + break; + case CR_VENDOR_VIA_CHALLENGE_RESPONSE: + xhci_via_challenge(xhci, trb.parameter); + break; + case CR_VENDOR_NEC_FIRMWARE_REVISION: + event.type = 48; /* NEC reply */ + event.length = 0x3025; + break; + case CR_VENDOR_NEC_CHALLENGE_RESPONSE: + { + uint32_t chi = trb.parameter >> 32; + uint32_t clo = trb.parameter; + uint32_t val = xhci_nec_challenge(chi, clo); + event.length = val & 0xFFFF; + event.epid = val >> 16; + slotid = val >> 24; + event.type = 48; /* NEC reply */ + } + break; + default: + trace_usb_xhci_unimplemented(""command"", type); + event.ccode = CC_TRB_ERROR; + break; + } + event.slotid = slotid; + xhci_event(xhci, &event, 0); + } +} +","@@ -390,6 +390,7 @@ struct XHCIEPContext { + dma_addr_t pctx; + unsigned int max_psize; + uint32_t state; ++ uint32_t kick_active; + + /* streams */ + unsigned int max_pstreams; +@@ -2131,6 +2132,9 @@ static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid, + return; + } + ++ if (epctx->kick_active) { ++ return; ++ } + xhci_kick_epctx(epctx, streamid); + } + +@@ -2146,6 +2150,7 @@ static void xhci_kick_epctx(XHCIEPContext *epctx, unsigned int streamid) + int i; + + trace_usb_xhci_ep_kick(epctx->slotid, epctx->epid, streamid); ++ assert(!epctx->kick_active); + + /* If the device has been detached, but the guest has not noticed this + yet the 2 above checks will succeed, but we must NOT continue */ +@@ -2217,6 +2222,7 @@ static void xhci_kick_epctx(XHCIEPContext *epctx, unsigned int streamid) + } + assert(ring->dequeue != 0); + ++ epctx->kick_active++; + while (1) { + length = xhci_ring_chain_length(xhci, ring); + if (length <= 0) { +@@ -2253,6 +2259,7 @@ static void xhci_kick_epctx(XHCIEPContext *epctx, unsigned int streamid) + break; + } + } ++ epctx->kick_active--; + + ep = xhci_epid_to_usbep(epctx); + if (ep) {",1081,1412,2048 +18794,"status_t BnGraphicBufferConsumer::onTransact( + uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) +{ + switch(code) { + case ACQUIRE_BUFFER: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + BufferItem item; + int64_t presentWhen = data.readInt64(); + status_t result = acquireBuffer(&item, presentWhen); + status_t err = reply->write(item); + if (err) return err; + reply->writeInt32(result); + return NO_ERROR; + } break; + case DETACH_BUFFER: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + int slot = data.readInt32(); + int result = detachBuffer(slot); + reply->writeInt32(result); + return NO_ERROR; + } break; + case ATTACH_BUFFER: { + + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + sp buffer = new GraphicBuffer(); + data.read(*buffer.get()); + int slot; + int result = attachBuffer(&slot, buffer); + reply->writeInt32(slot); + reply->writeInt32(result); + return NO_ERROR; + } break; + case RELEASE_BUFFER: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + int buf = data.readInt32(); + uint64_t frameNumber = data.readInt64(); + sp releaseFence = new Fence(); + status_t err = data.read(*releaseFence); + if (err) return err; + status_t result = releaseBuffer(buf, frameNumber, + EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, releaseFence); + reply->writeInt32(result); + return NO_ERROR; + } break; + case CONSUMER_CONNECT: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + sp consumer = IConsumerListener::asInterface( data.readStrongBinder() ); + bool controlledByApp = data.readInt32(); + status_t result = consumerConnect(consumer, controlledByApp); + reply->writeInt32(result); + return NO_ERROR; + } break; + case CONSUMER_DISCONNECT: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + status_t result = consumerDisconnect(); + reply->writeInt32(result); + return NO_ERROR; + } break; + case GET_RELEASED_BUFFERS: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + uint64_t slotMask; + status_t result = getReleasedBuffers(&slotMask); + reply->writeInt64(slotMask); + reply->writeInt32(result); + return NO_ERROR; + } break; + case SET_DEFAULT_BUFFER_SIZE: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + uint32_t w = data.readInt32(); + uint32_t h = data.readInt32(); + status_t result = setDefaultBufferSize(w, h); + reply->writeInt32(result); + return NO_ERROR; + } break; + case SET_DEFAULT_MAX_BUFFER_COUNT: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + uint32_t bufferCount = data.readInt32(); + status_t result = setDefaultMaxBufferCount(bufferCount); + reply->writeInt32(result); + return NO_ERROR; + } break; + case DISABLE_ASYNC_BUFFER: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + status_t result = disableAsyncBuffer(); + reply->writeInt32(result); + return NO_ERROR; + } break; + case SET_MAX_ACQUIRED_BUFFER_COUNT: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + uint32_t maxAcquiredBuffers = data.readInt32(); + status_t result = setMaxAcquiredBufferCount(maxAcquiredBuffers); + reply->writeInt32(result); + return NO_ERROR; + } break; + case SET_CONSUMER_NAME: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + setConsumerName( data.readString8() ); + return NO_ERROR; + } break; + case SET_DEFAULT_BUFFER_FORMAT: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + uint32_t defaultFormat = data.readInt32(); + status_t result = setDefaultBufferFormat(defaultFormat); + reply->writeInt32(result); + return NO_ERROR; + } break; + case SET_CONSUMER_USAGE_BITS: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + uint32_t usage = data.readInt32(); + status_t result = setConsumerUsageBits(usage); + reply->writeInt32(result); + return NO_ERROR; + } break; + case SET_TRANSFORM_HINT: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + uint32_t hint = data.readInt32(); + status_t result = setTransformHint(hint); + reply->writeInt32(result); + return NO_ERROR; + } break; + case DUMP: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + String8 result = data.readString8(); + String8 prefix = data.readString8(); + static_cast(this)->dump(result, prefix); + reply->writeString8(result); + return NO_ERROR; + } + } + return BBinder::onTransact(code, data, reply, flags); +} +",1,"status_t BnGraphicBufferConsumer::onTransact( + uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) +{ + switch(code) { + case ACQUIRE_BUFFER: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + BufferItem item; + int64_t presentWhen = data.readInt64(); + status_t result = acquireBuffer(&item, presentWhen); + status_t err = reply->write(item); + if (err) return err; + reply->writeInt32(result); + return NO_ERROR; + } break; + case DETACH_BUFFER: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + int slot = data.readInt32(); + int result = detachBuffer(slot); + reply->writeInt32(result); + return NO_ERROR; + } break; + case ATTACH_BUFFER: { + + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + sp buffer = new GraphicBuffer(); + data.read(*buffer.get()); + int slot = -1; + int result = attachBuffer(&slot, buffer); + reply->writeInt32(slot); + reply->writeInt32(result); + return NO_ERROR; + } break; + case RELEASE_BUFFER: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + int buf = data.readInt32(); + uint64_t frameNumber = data.readInt64(); + sp releaseFence = new Fence(); + status_t err = data.read(*releaseFence); + if (err) return err; + status_t result = releaseBuffer(buf, frameNumber, + EGL_NO_DISPLAY, EGL_NO_SYNC_KHR, releaseFence); + reply->writeInt32(result); + return NO_ERROR; + } break; + case CONSUMER_CONNECT: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + sp consumer = IConsumerListener::asInterface( data.readStrongBinder() ); + bool controlledByApp = data.readInt32(); + status_t result = consumerConnect(consumer, controlledByApp); + reply->writeInt32(result); + return NO_ERROR; + } break; + case CONSUMER_DISCONNECT: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + status_t result = consumerDisconnect(); + reply->writeInt32(result); + return NO_ERROR; + } break; + case GET_RELEASED_BUFFERS: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + uint64_t slotMask; + status_t result = getReleasedBuffers(&slotMask); + reply->writeInt64(slotMask); + reply->writeInt32(result); + return NO_ERROR; + } break; + case SET_DEFAULT_BUFFER_SIZE: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + uint32_t w = data.readInt32(); + uint32_t h = data.readInt32(); + status_t result = setDefaultBufferSize(w, h); + reply->writeInt32(result); + return NO_ERROR; + } break; + case SET_DEFAULT_MAX_BUFFER_COUNT: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + uint32_t bufferCount = data.readInt32(); + status_t result = setDefaultMaxBufferCount(bufferCount); + reply->writeInt32(result); + return NO_ERROR; + } break; + case DISABLE_ASYNC_BUFFER: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + status_t result = disableAsyncBuffer(); + reply->writeInt32(result); + return NO_ERROR; + } break; + case SET_MAX_ACQUIRED_BUFFER_COUNT: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + uint32_t maxAcquiredBuffers = data.readInt32(); + status_t result = setMaxAcquiredBufferCount(maxAcquiredBuffers); + reply->writeInt32(result); + return NO_ERROR; + } break; + case SET_CONSUMER_NAME: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + setConsumerName( data.readString8() ); + return NO_ERROR; + } break; + case SET_DEFAULT_BUFFER_FORMAT: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + uint32_t defaultFormat = data.readInt32(); + status_t result = setDefaultBufferFormat(defaultFormat); + reply->writeInt32(result); + return NO_ERROR; + } break; + case SET_CONSUMER_USAGE_BITS: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + uint32_t usage = data.readInt32(); + status_t result = setConsumerUsageBits(usage); + reply->writeInt32(result); + return NO_ERROR; + } break; + case SET_TRANSFORM_HINT: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + uint32_t hint = data.readInt32(); + status_t result = setTransformHint(hint); + reply->writeInt32(result); + return NO_ERROR; + } break; + case DUMP: { + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + String8 result = data.readString8(); + String8 prefix = data.readString8(); + static_cast(this)->dump(result, prefix); + reply->writeString8(result); + return NO_ERROR; + } + } + return BBinder::onTransact(code, data, reply, flags); +} +","@@ -444,7 +444,7 @@ + + CHECK_INTERFACE(IGraphicBufferConsumer, data, reply); + sp buffer = new GraphicBuffer(); + data.read(*buffer.get()); +- int slot; ++ int slot = -1; + int result = attachBuffer(&slot, buffer); + reply->writeInt32(slot); + reply->writeInt32(result); +",1071,1402,2048 +9319,"int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask, + u16 index) +{ + struct xps_dev_maps *dev_maps, *new_dev_maps = NULL; + int i, cpu, tci, numa_node_id = -2; + int maps_sz, num_tc = 1, tc = 0; + struct xps_map *map, *new_map; + bool active = false; + + if (dev->num_tc) { + num_tc = dev->num_tc; + tc = netdev_txq_to_tc(dev, index); + if (tc < 0) + return -EINVAL; + } + + maps_sz = XPS_DEV_MAPS_SIZE(num_tc); + if (maps_sz < L1_CACHE_BYTES) + maps_sz = L1_CACHE_BYTES; + + mutex_lock(&xps_map_mutex); + + dev_maps = xmap_dereference(dev->xps_maps); + + /* allocate memory for queue storage */ + for_each_cpu_and(cpu, cpu_online_mask, mask) { + if (!new_dev_maps) + new_dev_maps = kzalloc(maps_sz, GFP_KERNEL); + if (!new_dev_maps) { + mutex_unlock(&xps_map_mutex); + return -ENOMEM; + } + + tci = cpu * num_tc + tc; + map = dev_maps ? xmap_dereference(dev_maps->cpu_map[tci]) : + NULL; + + map = expand_xps_map(map, cpu, index); + if (!map) + goto error; + + RCU_INIT_POINTER(new_dev_maps->cpu_map[tci], map); + } + + if (!new_dev_maps) + goto out_no_new_maps; + + for_each_possible_cpu(cpu) { + /* copy maps belonging to foreign traffic classes */ + for (i = tc, tci = cpu * num_tc; dev_maps && i--; tci++) { + /* fill in the new device map from the old device map */ + map = xmap_dereference(dev_maps->cpu_map[tci]); + RCU_INIT_POINTER(new_dev_maps->cpu_map[tci], map); + } + + /* We need to explicitly update tci as prevous loop + * could break out early if dev_maps is NULL. + */ + tci = cpu * num_tc + tc; + + if (cpumask_test_cpu(cpu, mask) && cpu_online(cpu)) { + /* add queue to CPU maps */ + int pos = 0; + + map = xmap_dereference(new_dev_maps->cpu_map[tci]); + while ((pos < map->len) && (map->queues[pos] != index)) + pos++; + + if (pos == map->len) + map->queues[map->len++] = index; +#ifdef CONFIG_NUMA + if (numa_node_id == -2) + numa_node_id = cpu_to_node(cpu); + else if (numa_node_id != cpu_to_node(cpu)) + numa_node_id = -1; +#endif + } else if (dev_maps) { + /* fill in the new device map from the old device map */ + map = xmap_dereference(dev_maps->cpu_map[tci]); + RCU_INIT_POINTER(new_dev_maps->cpu_map[tci], map); + } + + /* copy maps belonging to foreign traffic classes */ + for (i = num_tc - tc, tci++; dev_maps && --i; tci++) { + /* fill in the new device map from the old device map */ + map = xmap_dereference(dev_maps->cpu_map[tci]); + RCU_INIT_POINTER(new_dev_maps->cpu_map[tci], map); + } + } + + rcu_assign_pointer(dev->xps_maps, new_dev_maps); + + /* Cleanup old maps */ + if (!dev_maps) + goto out_no_old_maps; + + for_each_possible_cpu(cpu) { + for (i = num_tc, tci = cpu * num_tc; i--; tci++) { + new_map = xmap_dereference(new_dev_maps->cpu_map[tci]); + map = xmap_dereference(dev_maps->cpu_map[tci]); + if (map && map != new_map) + kfree_rcu(map, rcu); + } + } + + kfree_rcu(dev_maps, rcu); + +out_no_old_maps: + dev_maps = new_dev_maps; + active = true; + +out_no_new_maps: + /* update Tx queue numa node */ + netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index), + (numa_node_id >= 0) ? numa_node_id : + NUMA_NO_NODE); + + if (!dev_maps) + goto out_no_maps; + + /* removes queue from unused CPUs */ + for_each_possible_cpu(cpu) { + for (i = tc, tci = cpu * num_tc; i--; tci++) + active |= remove_xps_queue(dev_maps, tci, index); + if (!cpumask_test_cpu(cpu, mask) || !cpu_online(cpu)) + active |= remove_xps_queue(dev_maps, tci, index); + for (i = num_tc - tc, tci++; --i; tci++) + active |= remove_xps_queue(dev_maps, tci, index); + } + + /* free map if not active */ + if (!active) { + RCU_INIT_POINTER(dev->xps_maps, NULL); + kfree_rcu(dev_maps, rcu); + } + +out_no_maps: + mutex_unlock(&xps_map_mutex); + + return 0; +error: + /* remove any maps that we added */ + for_each_possible_cpu(cpu) { + for (i = num_tc, tci = cpu * num_tc; i--; tci++) { + new_map = xmap_dereference(new_dev_maps->cpu_map[tci]); + map = dev_maps ? + xmap_dereference(dev_maps->cpu_map[tci]) : + NULL; + if (new_map && new_map != map) + kfree(new_map); + } + } + + mutex_unlock(&xps_map_mutex); + + kfree(new_dev_maps); + return -ENOMEM; +} +",0,"int netif_set_xps_queue(struct net_device *dev, const struct cpumask *mask, + u16 index) +{ + struct xps_dev_maps *dev_maps, *new_dev_maps = NULL; + int i, cpu, tci, numa_node_id = -2; + int maps_sz, num_tc = 1, tc = 0; + struct xps_map *map, *new_map; + bool active = false; + + if (dev->num_tc) { + num_tc = dev->num_tc; + tc = netdev_txq_to_tc(dev, index); + if (tc < 0) + return -EINVAL; + } + + maps_sz = XPS_DEV_MAPS_SIZE(num_tc); + if (maps_sz < L1_CACHE_BYTES) + maps_sz = L1_CACHE_BYTES; + + mutex_lock(&xps_map_mutex); + + dev_maps = xmap_dereference(dev->xps_maps); + + /* allocate memory for queue storage */ + for_each_cpu_and(cpu, cpu_online_mask, mask) { + if (!new_dev_maps) + new_dev_maps = kzalloc(maps_sz, GFP_KERNEL); + if (!new_dev_maps) { + mutex_unlock(&xps_map_mutex); + return -ENOMEM; + } + + tci = cpu * num_tc + tc; + map = dev_maps ? xmap_dereference(dev_maps->cpu_map[tci]) : + NULL; + + map = expand_xps_map(map, cpu, index); + if (!map) + goto error; + + RCU_INIT_POINTER(new_dev_maps->cpu_map[tci], map); + } + + if (!new_dev_maps) + goto out_no_new_maps; + + for_each_possible_cpu(cpu) { + /* copy maps belonging to foreign traffic classes */ + for (i = tc, tci = cpu * num_tc; dev_maps && i--; tci++) { + /* fill in the new device map from the old device map */ + map = xmap_dereference(dev_maps->cpu_map[tci]); + RCU_INIT_POINTER(new_dev_maps->cpu_map[tci], map); + } + + /* We need to explicitly update tci as prevous loop + * could break out early if dev_maps is NULL. + */ + tci = cpu * num_tc + tc; + + if (cpumask_test_cpu(cpu, mask) && cpu_online(cpu)) { + /* add queue to CPU maps */ + int pos = 0; + + map = xmap_dereference(new_dev_maps->cpu_map[tci]); + while ((pos < map->len) && (map->queues[pos] != index)) + pos++; + + if (pos == map->len) + map->queues[map->len++] = index; +#ifdef CONFIG_NUMA + if (numa_node_id == -2) + numa_node_id = cpu_to_node(cpu); + else if (numa_node_id != cpu_to_node(cpu)) + numa_node_id = -1; +#endif + } else if (dev_maps) { + /* fill in the new device map from the old device map */ + map = xmap_dereference(dev_maps->cpu_map[tci]); + RCU_INIT_POINTER(new_dev_maps->cpu_map[tci], map); + } + + /* copy maps belonging to foreign traffic classes */ + for (i = num_tc - tc, tci++; dev_maps && --i; tci++) { + /* fill in the new device map from the old device map */ + map = xmap_dereference(dev_maps->cpu_map[tci]); + RCU_INIT_POINTER(new_dev_maps->cpu_map[tci], map); + } + } + + rcu_assign_pointer(dev->xps_maps, new_dev_maps); + + /* Cleanup old maps */ + if (!dev_maps) + goto out_no_old_maps; + + for_each_possible_cpu(cpu) { + for (i = num_tc, tci = cpu * num_tc; i--; tci++) { + new_map = xmap_dereference(new_dev_maps->cpu_map[tci]); + map = xmap_dereference(dev_maps->cpu_map[tci]); + if (map && map != new_map) + kfree_rcu(map, rcu); + } + } + + kfree_rcu(dev_maps, rcu); + +out_no_old_maps: + dev_maps = new_dev_maps; + active = true; + +out_no_new_maps: + /* update Tx queue numa node */ + netdev_queue_numa_node_write(netdev_get_tx_queue(dev, index), + (numa_node_id >= 0) ? numa_node_id : + NUMA_NO_NODE); + + if (!dev_maps) + goto out_no_maps; + + /* removes queue from unused CPUs */ + for_each_possible_cpu(cpu) { + for (i = tc, tci = cpu * num_tc; i--; tci++) + active |= remove_xps_queue(dev_maps, tci, index); + if (!cpumask_test_cpu(cpu, mask) || !cpu_online(cpu)) + active |= remove_xps_queue(dev_maps, tci, index); + for (i = num_tc - tc, tci++; --i; tci++) + active |= remove_xps_queue(dev_maps, tci, index); + } + + /* free map if not active */ + if (!active) { + RCU_INIT_POINTER(dev->xps_maps, NULL); + kfree_rcu(dev_maps, rcu); + } + +out_no_maps: + mutex_unlock(&xps_map_mutex); + + return 0; +error: + /* remove any maps that we added */ + for_each_possible_cpu(cpu) { + for (i = num_tc, tci = cpu * num_tc; i--; tci++) { + new_map = xmap_dereference(new_dev_maps->cpu_map[tci]); + map = dev_maps ? + xmap_dereference(dev_maps->cpu_map[tci]) : + NULL; + if (new_map && new_map != map) + kfree(new_map); + } + } + + mutex_unlock(&xps_map_mutex); + + kfree(new_dev_maps); + return -ENOMEM; +} +","@@ -1147,9 +1147,8 @@ static int dev_alloc_name_ns(struct net *net, + return ret; + } + +-static int dev_get_valid_name(struct net *net, +- struct net_device *dev, +- const char *name) ++int dev_get_valid_name(struct net *net, struct net_device *dev, ++ const char *name) + { + BUG_ON(!net); + +@@ -1165,6 +1164,7 @@ static int dev_get_valid_name(struct net *net, + + return 0; + } ++EXPORT_SYMBOL(dev_get_valid_name); + + /** + * dev_change_name - change name of a device",1273,1604,2048 +135,"void Splash::strokeNarrow(SplashPath *path) { + SplashPipe pipe; + SplashXPath *xPath; + SplashXPathSeg *seg; + int x0, x1, x2, x3, y0, y1, x, y, t; + SplashCoord dx, dy, dxdy; + SplashClipResult clipRes; + int nClipRes[3]; + int i; + + nClipRes[0] = nClipRes[1] = nClipRes[2] = 0; + + xPath = new SplashXPath(path, state->matrix, state->flatness, gFalse); + + pipeInit(&pipe, 0, 0, state->strokePattern, NULL, state->strokeAlpha, + gFalse, gFalse); + + for (i = 0, seg = xPath->segs; i < xPath->length; ++i, ++seg) { + + x0 = splashFloor(seg->x0); + x1 = splashFloor(seg->x1); + y0 = splashFloor(seg->y0); + y1 = splashFloor(seg->y1); + + if (y0 == y1) { + if (x0 > x1) { + t = x0; x0 = x1; x1 = t; + } + if ((clipRes = state->clip->testSpan(x0, x1, y0)) + != splashClipAllOutside) { + drawSpan(&pipe, x0, x1, y0, clipRes == splashClipAllInside); + } + + } else if (splashAbs(seg->dxdy) > 1) { + dx = seg->x1 - seg->x0; + dy = seg->y1 - seg->y0; + dxdy = seg->dxdy; + if (y0 > y1) { + t = y0; y0 = y1; y1 = t; + t = x0; x0 = x1; x1 = t; + dx = -dx; + dy = -dy; + } + if ((clipRes = state->clip->testRect(x0 <= x1 ? x0 : x1, y0, + x0 <= x1 ? x1 : x0, y1)) + != splashClipAllOutside) { + if (dx > 0) { + x2 = x0; + x3 = splashFloor(seg->x0 + ((SplashCoord)y0 + 1 - seg->y0) * dxdy); + drawSpan(&pipe, x2, (x2 <= x3 - 1) ? x3 - 1 : x2, y0, + clipRes == splashClipAllInside); + x2 = x3; + for (y = y0 + 1; y <= y1 - 1; ++y) { + x3 = splashFloor(seg->x0 + ((SplashCoord)y + 1 - seg->y0) * dxdy); + drawSpan(&pipe, x2, x3 - 1, y, clipRes == splashClipAllInside); + x2 = x3; + } + drawSpan(&pipe, x2, x2 <= x1 ? x1 : x2, y1, + clipRes == splashClipAllInside); + } else { + x2 = x0; + x3 = splashFloor(seg->x0 + ((SplashCoord)y0 + 1 - seg->y0) * dxdy); + drawSpan(&pipe, (x3 + 1 <= x2) ? x3 + 1 : x2, x2, y0, + clipRes == splashClipAllInside); + x2 = x3; + for (y = y0 + 1; y <= y1 - 1; ++y) { + x3 = splashFloor(seg->x0 + ((SplashCoord)y + 1 - seg->y0) * dxdy); + drawSpan(&pipe, x3 + 1, x2, y, clipRes == splashClipAllInside); + x2 = x3; + } + drawSpan(&pipe, x1, (x1 <= x2) ? x2 : x1, y1, + clipRes == splashClipAllInside); + } + } + + } else { + dxdy = seg->dxdy; + if (y0 > y1) { + t = x0; x0 = x1; x1 = t; + t = y0; y0 = y1; y1 = t; + } + if ((clipRes = state->clip->testRect(x0 <= x1 ? x0 : x1, y0, + x0 <= x1 ? x1 : x0, y1)) + != splashClipAllOutside) { + drawPixel(&pipe, x0, y0, clipRes == splashClipAllInside); + for (y = y0 + 1; y <= y1 - 1; ++y) { + x = splashFloor(seg->x0 + ((SplashCoord)y - seg->y0) * dxdy); + drawPixel(&pipe, x, y, clipRes == splashClipAllInside); + } + drawPixel(&pipe, x1, y1, clipRes == splashClipAllInside); + } + } + ++nClipRes[clipRes]; + } + if (nClipRes[splashClipPartial] || + (nClipRes[splashClipAllInside] && nClipRes[splashClipAllOutside])) { + opClipRes = splashClipPartial; + } else if (nClipRes[splashClipAllInside]) { + opClipRes = splashClipAllInside; + } else { + opClipRes = splashClipAllOutside; + } + + delete xPath; +} +",0,"void Splash::strokeNarrow(SplashPath *path) { + SplashPipe pipe; + SplashXPath *xPath; + SplashXPathSeg *seg; + int x0, x1, x2, x3, y0, y1, x, y, t; + SplashCoord dx, dy, dxdy; + SplashClipResult clipRes; + int nClipRes[3]; + int i; + + nClipRes[0] = nClipRes[1] = nClipRes[2] = 0; + + xPath = new SplashXPath(path, state->matrix, state->flatness, gFalse); + + pipeInit(&pipe, 0, 0, state->strokePattern, NULL, state->strokeAlpha, + gFalse, gFalse); + + for (i = 0, seg = xPath->segs; i < xPath->length; ++i, ++seg) { + + x0 = splashFloor(seg->x0); + x1 = splashFloor(seg->x1); + y0 = splashFloor(seg->y0); + y1 = splashFloor(seg->y1); + + if (y0 == y1) { + if (x0 > x1) { + t = x0; x0 = x1; x1 = t; + } + if ((clipRes = state->clip->testSpan(x0, x1, y0)) + != splashClipAllOutside) { + drawSpan(&pipe, x0, x1, y0, clipRes == splashClipAllInside); + } + + } else if (splashAbs(seg->dxdy) > 1) { + dx = seg->x1 - seg->x0; + dy = seg->y1 - seg->y0; + dxdy = seg->dxdy; + if (y0 > y1) { + t = y0; y0 = y1; y1 = t; + t = x0; x0 = x1; x1 = t; + dx = -dx; + dy = -dy; + } + if ((clipRes = state->clip->testRect(x0 <= x1 ? x0 : x1, y0, + x0 <= x1 ? x1 : x0, y1)) + != splashClipAllOutside) { + if (dx > 0) { + x2 = x0; + x3 = splashFloor(seg->x0 + ((SplashCoord)y0 + 1 - seg->y0) * dxdy); + drawSpan(&pipe, x2, (x2 <= x3 - 1) ? x3 - 1 : x2, y0, + clipRes == splashClipAllInside); + x2 = x3; + for (y = y0 + 1; y <= y1 - 1; ++y) { + x3 = splashFloor(seg->x0 + ((SplashCoord)y + 1 - seg->y0) * dxdy); + drawSpan(&pipe, x2, x3 - 1, y, clipRes == splashClipAllInside); + x2 = x3; + } + drawSpan(&pipe, x2, x2 <= x1 ? x1 : x2, y1, + clipRes == splashClipAllInside); + } else { + x2 = x0; + x3 = splashFloor(seg->x0 + ((SplashCoord)y0 + 1 - seg->y0) * dxdy); + drawSpan(&pipe, (x3 + 1 <= x2) ? x3 + 1 : x2, x2, y0, + clipRes == splashClipAllInside); + x2 = x3; + for (y = y0 + 1; y <= y1 - 1; ++y) { + x3 = splashFloor(seg->x0 + ((SplashCoord)y + 1 - seg->y0) * dxdy); + drawSpan(&pipe, x3 + 1, x2, y, clipRes == splashClipAllInside); + x2 = x3; + } + drawSpan(&pipe, x1, (x1 <= x2) ? x2 : x1, y1, + clipRes == splashClipAllInside); + } + } + + } else { + dxdy = seg->dxdy; + if (y0 > y1) { + t = x0; x0 = x1; x1 = t; + t = y0; y0 = y1; y1 = t; + } + if ((clipRes = state->clip->testRect(x0 <= x1 ? x0 : x1, y0, + x0 <= x1 ? x1 : x0, y1)) + != splashClipAllOutside) { + drawPixel(&pipe, x0, y0, clipRes == splashClipAllInside); + for (y = y0 + 1; y <= y1 - 1; ++y) { + x = splashFloor(seg->x0 + ((SplashCoord)y - seg->y0) * dxdy); + drawPixel(&pipe, x, y, clipRes == splashClipAllInside); + } + drawPixel(&pipe, x1, y1, clipRes == splashClipAllInside); + } + } + ++nClipRes[clipRes]; + } + if (nClipRes[splashClipPartial] || + (nClipRes[splashClipAllInside] && nClipRes[splashClipAllOutside])) { + opClipRes = splashClipPartial; + } else if (nClipRes[splashClipAllInside]) { + opClipRes = splashClipAllInside; + } else { + opClipRes = splashClipAllOutside; + } + + delete xPath; +} +","@@ -11,7 +11,7 @@ + // All changes made under the Poppler project to this file are licensed + // under GPL version 2 or later + // +-// Copyright (C) 2005-2008 Albert Astals Cid ++// Copyright (C) 2005-2009 Albert Astals Cid + // Copyright (C) 2005 Marco Pesenti Gritti + // + // To see a description of the changes please see the Changelog file that +@@ -2001,7 +2001,7 @@ SplashError Splash::fillImageMask(SplashImageMaskSource src, void *srcData, + xq = w % scaledWidth; + + // allocate pixel buffer +- pixBuf = (SplashColorPtr)gmalloc((yp + 1) * w); ++ pixBuf = (SplashColorPtr)gmallocn((yp + 1), w); + + // initialize the pixel pipe + pipeInit(&pipe, 0, 0, state->fillPattern, NULL, state->fillAlpha, +@@ -2301,9 +2301,9 @@ SplashError Splash::drawImage(SplashImageSource src, void *srcData, + xq = w % scaledWidth; + + // allocate pixel buffers +- colorBuf = (SplashColorPtr)gmalloc((yp + 1) * w * nComps); ++ colorBuf = (SplashColorPtr)gmallocn3((yp + 1), w, nComps); + if (srcAlpha) { +- alphaBuf = (Guchar *)gmalloc((yp + 1) * w); ++ alphaBuf = (Guchar *)gmallocn((yp + 1), w); + } else { + alphaBuf = NULL; + }",1238,1569,2048 +1959,"static void tcp_v6_send_response(struct sk_buff *skb, u32 seq, u32 ack, u32 win, + u32 ts, struct tcp_md5sig_key *key, int rst) +{ + struct tcphdr *th = tcp_hdr(skb), *t1; + struct sk_buff *buff; + struct flowi6 fl6; + struct net *net = dev_net(skb_dst(skb)->dev); + struct sock *ctl_sk = net->ipv6.tcp_sk; + unsigned int tot_len = sizeof(struct tcphdr); + struct dst_entry *dst; + __be32 *topt; + + if (ts) + tot_len += TCPOLEN_TSTAMP_ALIGNED; +#ifdef CONFIG_TCP_MD5SIG + if (key) + tot_len += TCPOLEN_MD5SIG_ALIGNED; +#endif + + buff = alloc_skb(MAX_HEADER + sizeof(struct ipv6hdr) + tot_len, + GFP_ATOMIC); + if (buff == NULL) + return; + + skb_reserve(buff, MAX_HEADER + sizeof(struct ipv6hdr) + tot_len); + + t1 = (struct tcphdr *) skb_push(buff, tot_len); + skb_reset_transport_header(buff); + + /* Swap the send and the receive. */ + memset(t1, 0, sizeof(*t1)); + t1->dest = th->source; + t1->source = th->dest; + t1->doff = tot_len / 4; + t1->seq = htonl(seq); + t1->ack_seq = htonl(ack); + t1->ack = !rst || !th->ack; + t1->rst = rst; + t1->window = htons(win); + + topt = (__be32 *)(t1 + 1); + + if (ts) { + *topt++ = htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | + (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP); + *topt++ = htonl(tcp_time_stamp); + *topt++ = htonl(ts); + } + +#ifdef CONFIG_TCP_MD5SIG + if (key) { + *topt++ = htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | + (TCPOPT_MD5SIG << 8) | TCPOLEN_MD5SIG); + tcp_v6_md5_hash_hdr((__u8 *)topt, key, + &ipv6_hdr(skb)->saddr, + &ipv6_hdr(skb)->daddr, t1); + } +#endif + + memset(&fl6, 0, sizeof(fl6)); + ipv6_addr_copy(&fl6.daddr, &ipv6_hdr(skb)->saddr); + ipv6_addr_copy(&fl6.saddr, &ipv6_hdr(skb)->daddr); + + buff->ip_summed = CHECKSUM_PARTIAL; + buff->csum = 0; + + __tcp_v6_send_check(buff, &fl6.saddr, &fl6.daddr); + + fl6.flowi6_proto = IPPROTO_TCP; + fl6.flowi6_oif = inet6_iif(skb); + fl6.fl6_dport = t1->dest; + fl6.fl6_sport = t1->source; + security_skb_classify_flow(skb, flowi6_to_flowi(&fl6)); + + /* Pass a socket to ip6_dst_lookup either it is for RST + * Underlying function will use this to retrieve the network + * namespace + */ + dst = ip6_dst_lookup_flow(ctl_sk, &fl6, NULL, false); + if (!IS_ERR(dst)) { + skb_dst_set(buff, dst); + ip6_xmit(ctl_sk, buff, &fl6, NULL); + TCP_INC_STATS_BH(net, TCP_MIB_OUTSEGS); + if (rst) + TCP_INC_STATS_BH(net, TCP_MIB_OUTRSTS); + return; + } + + kfree_skb(buff); +} +",0,"static void tcp_v6_send_response(struct sk_buff *skb, u32 seq, u32 ack, u32 win, + u32 ts, struct tcp_md5sig_key *key, int rst) +{ + struct tcphdr *th = tcp_hdr(skb), *t1; + struct sk_buff *buff; + struct flowi6 fl6; + struct net *net = dev_net(skb_dst(skb)->dev); + struct sock *ctl_sk = net->ipv6.tcp_sk; + unsigned int tot_len = sizeof(struct tcphdr); + struct dst_entry *dst; + __be32 *topt; + + if (ts) + tot_len += TCPOLEN_TSTAMP_ALIGNED; +#ifdef CONFIG_TCP_MD5SIG + if (key) + tot_len += TCPOLEN_MD5SIG_ALIGNED; +#endif + + buff = alloc_skb(MAX_HEADER + sizeof(struct ipv6hdr) + tot_len, + GFP_ATOMIC); + if (buff == NULL) + return; + + skb_reserve(buff, MAX_HEADER + sizeof(struct ipv6hdr) + tot_len); + + t1 = (struct tcphdr *) skb_push(buff, tot_len); + skb_reset_transport_header(buff); + + /* Swap the send and the receive. */ + memset(t1, 0, sizeof(*t1)); + t1->dest = th->source; + t1->source = th->dest; + t1->doff = tot_len / 4; + t1->seq = htonl(seq); + t1->ack_seq = htonl(ack); + t1->ack = !rst || !th->ack; + t1->rst = rst; + t1->window = htons(win); + + topt = (__be32 *)(t1 + 1); + + if (ts) { + *topt++ = htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | + (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP); + *topt++ = htonl(tcp_time_stamp); + *topt++ = htonl(ts); + } + +#ifdef CONFIG_TCP_MD5SIG + if (key) { + *topt++ = htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | + (TCPOPT_MD5SIG << 8) | TCPOLEN_MD5SIG); + tcp_v6_md5_hash_hdr((__u8 *)topt, key, + &ipv6_hdr(skb)->saddr, + &ipv6_hdr(skb)->daddr, t1); + } +#endif + + memset(&fl6, 0, sizeof(fl6)); + ipv6_addr_copy(&fl6.daddr, &ipv6_hdr(skb)->saddr); + ipv6_addr_copy(&fl6.saddr, &ipv6_hdr(skb)->daddr); + + buff->ip_summed = CHECKSUM_PARTIAL; + buff->csum = 0; + + __tcp_v6_send_check(buff, &fl6.saddr, &fl6.daddr); + + fl6.flowi6_proto = IPPROTO_TCP; + fl6.flowi6_oif = inet6_iif(skb); + fl6.fl6_dport = t1->dest; + fl6.fl6_sport = t1->source; + security_skb_classify_flow(skb, flowi6_to_flowi(&fl6)); + + /* Pass a socket to ip6_dst_lookup either it is for RST + * Underlying function will use this to retrieve the network + * namespace + */ + dst = ip6_dst_lookup_flow(ctl_sk, &fl6, NULL, false); + if (!IS_ERR(dst)) { + skb_dst_set(buff, dst); + ip6_xmit(ctl_sk, buff, &fl6, NULL); + TCP_INC_STATS_BH(net, TCP_MIB_OUTSEGS); + if (rst) + TCP_INC_STATS_BH(net, TCP_MIB_OUTRSTS); + return; + } + + kfree_skb(buff); +} +","@@ -1469,7 +1469,7 @@ static struct sock * tcp_v6_syn_recv_sock(struct sock *sk, struct sk_buff *skb, + + First: no IPv4 options. + */ +- newinet->opt = NULL; ++ newinet->inet_opt = NULL; + newnp->ipv6_fl_list = NULL; + + /* Clone RX bits */",837,1168,2048 +7907,"static int nntp_msg_open(struct Context *ctx, struct Message *msg, int msgno) +{ + struct NntpData *nntp_data = ctx->data; + struct Header *hdr = ctx->hdrs[msgno]; + char article[16]; + + /* try to get article from cache */ + struct NntpAcache *acache = &nntp_data->acache[hdr->index % NNTP_ACACHE_LEN]; + if (acache->path) + { + if (acache->index == hdr->index) + { + msg->fp = mutt_file_fopen(acache->path, ""r""); + if (msg->fp) + return 0; + } + /* clear previous entry */ + else + { + unlink(acache->path); + FREE(&acache->path); + } + } + snprintf(article, sizeof(article), ""%d"", NHDR(hdr)->article_num); + msg->fp = mutt_bcache_get(nntp_data->bcache, article); + if (msg->fp) + { + if (NHDR(hdr)->parsed) + return 0; + } + else + { + char buf[PATH_MAX]; + /* don't try to fetch article from removed newsgroup */ + if (nntp_data->deleted) + return -1; + + /* create new cache file */ + const char *fetch_msg = _(""Fetching message...""); + mutt_message(fetch_msg); + msg->fp = mutt_bcache_put(nntp_data->bcache, article); + if (!msg->fp) + { + mutt_mktemp(buf, sizeof(buf)); + acache->path = mutt_str_strdup(buf); + acache->index = hdr->index; + msg->fp = mutt_file_fopen(acache->path, ""w+""); + if (!msg->fp) + { + mutt_perror(acache->path); + unlink(acache->path); + FREE(&acache->path); + return -1; + } + } + + /* fetch message to cache file */ + snprintf(buf, sizeof(buf), ""ARTICLE %s\r\n"", + NHDR(hdr)->article_num ? article : hdr->env->message_id); + const int rc = nntp_fetch_lines(nntp_data, buf, sizeof(buf), fetch_msg, + fetch_tempfile, msg->fp); + if (rc) + { + mutt_file_fclose(&msg->fp); + if (acache->path) + { + unlink(acache->path); + FREE(&acache->path); + } + if (rc > 0) + { + if (mutt_str_strncmp(NHDR(hdr)->article_num ? ""423"" : ""430"", buf, 3) == 0) + { + mutt_error(_(""Article %d not found on the server.""), + NHDR(hdr)->article_num ? article : hdr->env->message_id); + } + else + mutt_error(""ARTICLE: %s"", buf); + } + return -1; + } + + if (!acache->path) + mutt_bcache_commit(nntp_data->bcache, article); + } + + /* replace envelope with new one + * hash elements must be updated because pointers will be changed */ + if (ctx->id_hash && hdr->env->message_id) + mutt_hash_delete(ctx->id_hash, hdr->env->message_id, hdr); + if (ctx->subj_hash && hdr->env->real_subj) + mutt_hash_delete(ctx->subj_hash, hdr->env->real_subj, hdr); + + mutt_env_free(&hdr->env); + hdr->env = mutt_rfc822_read_header(msg->fp, hdr, 0, 0); + + if (ctx->id_hash && hdr->env->message_id) + mutt_hash_insert(ctx->id_hash, hdr->env->message_id, hdr); + if (ctx->subj_hash && hdr->env->real_subj) + mutt_hash_insert(ctx->subj_hash, hdr->env->real_subj, hdr); + + /* fix content length */ + fseek(msg->fp, 0, SEEK_END); + hdr->content->length = ftell(msg->fp) - hdr->content->offset; + + /* this is called in neomutt before the open which fetches the message, + * which is probably wrong, but we just call it again here to handle + * the problem instead of fixing it */ + NHDR(hdr)->parsed = true; + mutt_parse_mime_message(ctx, hdr); + + /* these would normally be updated in mx_update_context(), but the + * full headers aren't parsed with overview, so the information wasn't + * available then */ + if (WithCrypto) + hdr->security = crypt_query(hdr->content); + + rewind(msg->fp); + mutt_clear_error(); + return 0; +} +",0,"static int nntp_msg_open(struct Context *ctx, struct Message *msg, int msgno) +{ + struct NntpData *nntp_data = ctx->data; + struct Header *hdr = ctx->hdrs[msgno]; + char article[16]; + + /* try to get article from cache */ + struct NntpAcache *acache = &nntp_data->acache[hdr->index % NNTP_ACACHE_LEN]; + if (acache->path) + { + if (acache->index == hdr->index) + { + msg->fp = mutt_file_fopen(acache->path, ""r""); + if (msg->fp) + return 0; + } + /* clear previous entry */ + else + { + unlink(acache->path); + FREE(&acache->path); + } + } + snprintf(article, sizeof(article), ""%d"", NHDR(hdr)->article_num); + msg->fp = mutt_bcache_get(nntp_data->bcache, article); + if (msg->fp) + { + if (NHDR(hdr)->parsed) + return 0; + } + else + { + char buf[PATH_MAX]; + /* don't try to fetch article from removed newsgroup */ + if (nntp_data->deleted) + return -1; + + /* create new cache file */ + const char *fetch_msg = _(""Fetching message...""); + mutt_message(fetch_msg); + msg->fp = mutt_bcache_put(nntp_data->bcache, article); + if (!msg->fp) + { + mutt_mktemp(buf, sizeof(buf)); + acache->path = mutt_str_strdup(buf); + acache->index = hdr->index; + msg->fp = mutt_file_fopen(acache->path, ""w+""); + if (!msg->fp) + { + mutt_perror(acache->path); + unlink(acache->path); + FREE(&acache->path); + return -1; + } + } + + /* fetch message to cache file */ + snprintf(buf, sizeof(buf), ""ARTICLE %s\r\n"", + NHDR(hdr)->article_num ? article : hdr->env->message_id); + const int rc = nntp_fetch_lines(nntp_data, buf, sizeof(buf), fetch_msg, + fetch_tempfile, msg->fp); + if (rc) + { + mutt_file_fclose(&msg->fp); + if (acache->path) + { + unlink(acache->path); + FREE(&acache->path); + } + if (rc > 0) + { + if (mutt_str_strncmp(NHDR(hdr)->article_num ? ""423"" : ""430"", buf, 3) == 0) + { + mutt_error(_(""Article %d not found on the server.""), + NHDR(hdr)->article_num ? article : hdr->env->message_id); + } + else + mutt_error(""ARTICLE: %s"", buf); + } + return -1; + } + + if (!acache->path) + mutt_bcache_commit(nntp_data->bcache, article); + } + + /* replace envelope with new one + * hash elements must be updated because pointers will be changed */ + if (ctx->id_hash && hdr->env->message_id) + mutt_hash_delete(ctx->id_hash, hdr->env->message_id, hdr); + if (ctx->subj_hash && hdr->env->real_subj) + mutt_hash_delete(ctx->subj_hash, hdr->env->real_subj, hdr); + + mutt_env_free(&hdr->env); + hdr->env = mutt_rfc822_read_header(msg->fp, hdr, 0, 0); + + if (ctx->id_hash && hdr->env->message_id) + mutt_hash_insert(ctx->id_hash, hdr->env->message_id, hdr); + if (ctx->subj_hash && hdr->env->real_subj) + mutt_hash_insert(ctx->subj_hash, hdr->env->real_subj, hdr); + + /* fix content length */ + fseek(msg->fp, 0, SEEK_END); + hdr->content->length = ftell(msg->fp) - hdr->content->offset; + + /* this is called in neomutt before the open which fetches the message, + * which is probably wrong, but we just call it again here to handle + * the problem instead of fixing it */ + NHDR(hdr)->parsed = true; + mutt_parse_mime_message(ctx, hdr); + + /* these would normally be updated in mx_update_context(), but the + * full headers aren't parsed with overview, so the information wasn't + * available then */ + if (WithCrypto) + hdr->security = crypt_query(hdr->content); + + rewind(msg->fp); + mutt_clear_error(); + return 0; +} +","@@ -1288,6 +1288,8 @@ static int nntp_fetch_headers(struct Context *ctx, void *hc, anum_t first, + fc.last = last; + fc.restore = restore; + fc.messages = mutt_mem_calloc(last - first + 1, sizeof(unsigned char)); ++ if (fc.messages == NULL) ++ return -1; + #ifdef USE_HCACHE + fc.hc = hc; + #endif",1040,1371,2048 diff --git a/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_1024_to_2048.pkl b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_1024_to_2048.pkl new file mode 100644 index 0000000000000000000000000000000000000000..762d11d4e3cdda3af5f766a5e404bf152ba93868 --- /dev/null +++ b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_1024_to_2048.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:91845b5c819b47ea5c1a0a81da3484592a8dbafcb1a57a8802a5c0a0761c884d +size 5944671 diff --git a/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_11000_to_15000.csv b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_11000_to_15000.csv new file mode 100644 index 0000000000000000000000000000000000000000..8613e9c909fb646cd55fce42d11fac2553cb41e0 --- /dev/null +++ b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_11000_to_15000.csv @@ -0,0 +1,4954 @@ +idx,func_before,vul,func_after,patch,code_token_length,total_token_length,max_tokens_setting +18302,"rsvp_obj_print(netdissect_options *ndo, + const u_char *pptr, u_int plen, const u_char *tptr, + const char *ident, u_int tlen, + const struct rsvp_common_header *rsvp_com_header) +{ + const struct rsvp_object_header *rsvp_obj_header; + const u_char *obj_tptr; + union { + const struct rsvp_obj_integrity_t *rsvp_obj_integrity; + const struct rsvp_obj_frr_t *rsvp_obj_frr; + } obj_ptr; + + u_short rsvp_obj_len,rsvp_obj_ctype,obj_tlen,intserv_serv_tlen; + int hexdump,processed,padbytes,error_code,error_value,i,sigcheck; + union { + float f; + uint32_t i; + } bw; + uint8_t namelen; + + u_int action, subchannel; + + while(tlen>=sizeof(struct rsvp_object_header)) { + /* did we capture enough for fully decoding the object header ? */ + ND_TCHECK2(*tptr, sizeof(struct rsvp_object_header)); + + rsvp_obj_header = (const struct rsvp_object_header *)tptr; + rsvp_obj_len=EXTRACT_16BITS(rsvp_obj_header->length); + rsvp_obj_ctype=rsvp_obj_header->ctype; + + if(rsvp_obj_len % 4) { + ND_PRINT((ndo, ""%sERROR: object header size %u not a multiple of 4"", ident, rsvp_obj_len)); + return -1; + } + if(rsvp_obj_len < sizeof(struct rsvp_object_header)) { + ND_PRINT((ndo, ""%sERROR: object header too short %u < %lu"", ident, rsvp_obj_len, + (unsigned long)sizeof(const struct rsvp_object_header))); + return -1; + } + + ND_PRINT((ndo, ""%s%s Object (%u) Flags: [%s"", + ident, + tok2str(rsvp_obj_values, + ""Unknown"", + rsvp_obj_header->class_num), + rsvp_obj_header->class_num, + ((rsvp_obj_header->class_num) & 0x80) ? ""ignore"" : ""reject"")); + + if (rsvp_obj_header->class_num > 128) + ND_PRINT((ndo, "" %s"", + ((rsvp_obj_header->class_num) & 0x40) ? ""and forward"" : ""silently"")); + + ND_PRINT((ndo, "" if unknown], Class-Type: %s (%u), length: %u"", + tok2str(rsvp_ctype_values, + ""Unknown"", + ((rsvp_obj_header->class_num)<<8)+rsvp_obj_ctype), + rsvp_obj_ctype, + rsvp_obj_len)); + + if(tlen < rsvp_obj_len) { + ND_PRINT((ndo, ""%sERROR: object goes past end of objects TLV"", ident)); + return -1; + } + + obj_tptr=tptr+sizeof(struct rsvp_object_header); + obj_tlen=rsvp_obj_len-sizeof(struct rsvp_object_header); + + /* did we capture enough for fully decoding the object ? */ + if (!ND_TTEST2(*tptr, rsvp_obj_len)) + return -1; + hexdump=FALSE; + + switch(rsvp_obj_header->class_num) { + case RSVP_OBJ_SESSION: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_IPV4: + if (obj_tlen < 8) + return -1; + ND_PRINT((ndo, ""%s IPv4 DestAddress: %s, Protocol ID: 0x%02x"", + ident, + ipaddr_string(ndo, obj_tptr), + *(obj_tptr + sizeof(struct in_addr)))); + ND_PRINT((ndo, ""%s Flags: [0x%02x], DestPort %u"", + ident, + *(obj_tptr+5), + EXTRACT_16BITS(obj_tptr + 6))); + obj_tlen-=8; + obj_tptr+=8; + break; + case RSVP_CTYPE_IPV6: + if (obj_tlen < 20) + return -1; + ND_PRINT((ndo, ""%s IPv6 DestAddress: %s, Protocol ID: 0x%02x"", + ident, + ip6addr_string(ndo, obj_tptr), + *(obj_tptr + sizeof(struct in6_addr)))); + ND_PRINT((ndo, ""%s Flags: [0x%02x], DestPort %u"", + ident, + *(obj_tptr+sizeof(struct in6_addr)+1), + EXTRACT_16BITS(obj_tptr + sizeof(struct in6_addr) + 2))); + obj_tlen-=20; + obj_tptr+=20; + break; + + case RSVP_CTYPE_TUNNEL_IPV6: + if (obj_tlen < 36) + return -1; + ND_PRINT((ndo, ""%s IPv6 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s"", + ident, + ip6addr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr+18), + ip6addr_string(ndo, obj_tptr + 20))); + obj_tlen-=36; + obj_tptr+=36; + break; + + case RSVP_CTYPE_14: /* IPv6 p2mp LSP Tunnel */ + if (obj_tlen < 26) + return -1; + ND_PRINT((ndo, ""%s IPv6 P2MP LSP ID: 0x%08x, Tunnel ID: 0x%04x, Extended Tunnel ID: %s"", + ident, + EXTRACT_32BITS(obj_tptr), + EXTRACT_16BITS(obj_tptr+6), + ip6addr_string(ndo, obj_tptr + 8))); + obj_tlen-=26; + obj_tptr+=26; + break; + case RSVP_CTYPE_13: /* IPv4 p2mp LSP Tunnel */ + if (obj_tlen < 12) + return -1; + ND_PRINT((ndo, ""%s IPv4 P2MP LSP ID: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s"", + ident, + ipaddr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr+6), + ipaddr_string(ndo, obj_tptr + 8))); + obj_tlen-=12; + obj_tptr+=12; + break; + case RSVP_CTYPE_TUNNEL_IPV4: + case RSVP_CTYPE_UNI_IPV4: + if (obj_tlen < 12) + return -1; + ND_PRINT((ndo, ""%s IPv4 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s"", + ident, + ipaddr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr+6), + ipaddr_string(ndo, obj_tptr + 8))); + obj_tlen-=12; + obj_tptr+=12; + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_CONFIRM: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_IPV4: + if (obj_tlen < sizeof(struct in_addr)) + return -1; + ND_PRINT((ndo, ""%s IPv4 Receiver Address: %s"", + ident, + ipaddr_string(ndo, obj_tptr))); + obj_tlen-=sizeof(struct in_addr); + obj_tptr+=sizeof(struct in_addr); + break; + case RSVP_CTYPE_IPV6: + if (obj_tlen < sizeof(struct in6_addr)) + return -1; + ND_PRINT((ndo, ""%s IPv6 Receiver Address: %s"", + ident, + ip6addr_string(ndo, obj_tptr))); + obj_tlen-=sizeof(struct in6_addr); + obj_tptr+=sizeof(struct in6_addr); + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_NOTIFY_REQ: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_IPV4: + if (obj_tlen < sizeof(struct in_addr)) + return -1; + ND_PRINT((ndo, ""%s IPv4 Notify Node Address: %s"", + ident, + ipaddr_string(ndo, obj_tptr))); + obj_tlen-=sizeof(struct in_addr); + obj_tptr+=sizeof(struct in_addr); + break; + case RSVP_CTYPE_IPV6: + if (obj_tlen < sizeof(struct in6_addr)) + return-1; + ND_PRINT((ndo, ""%s IPv6 Notify Node Address: %s"", + ident, + ip6addr_string(ndo, obj_tptr))); + obj_tlen-=sizeof(struct in6_addr); + obj_tptr+=sizeof(struct in6_addr); + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_SUGGESTED_LABEL: /* fall through */ + case RSVP_OBJ_UPSTREAM_LABEL: /* fall through */ + case RSVP_OBJ_RECOVERY_LABEL: /* fall through */ + case RSVP_OBJ_LABEL: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + while(obj_tlen >= 4 ) { + ND_PRINT((ndo, ""%s Label: %u"", ident, EXTRACT_32BITS(obj_tptr))); + obj_tlen-=4; + obj_tptr+=4; + } + break; + case RSVP_CTYPE_2: + if (obj_tlen < 4) + return-1; + ND_PRINT((ndo, ""%s Generalized Label: %u"", + ident, + EXTRACT_32BITS(obj_tptr))); + obj_tlen-=4; + obj_tptr+=4; + break; + case RSVP_CTYPE_3: + if (obj_tlen < 12) + return-1; + ND_PRINT((ndo, ""%s Waveband ID: %u%s Start Label: %u, Stop Label: %u"", + ident, + EXTRACT_32BITS(obj_tptr), + ident, + EXTRACT_32BITS(obj_tptr+4), + EXTRACT_32BITS(obj_tptr + 8))); + obj_tlen-=12; + obj_tptr+=12; + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_STYLE: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + if (obj_tlen < 4) + return-1; + ND_PRINT((ndo, ""%s Reservation Style: %s, Flags: [0x%02x]"", + ident, + tok2str(rsvp_resstyle_values, + ""Unknown"", + EXTRACT_24BITS(obj_tptr+1)), + *(obj_tptr))); + obj_tlen-=4; + obj_tptr+=4; + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_SENDER_TEMPLATE: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_IPV4: + if (obj_tlen < 8) + return-1; + ND_PRINT((ndo, ""%s Source Address: %s, Source Port: %u"", + ident, + ipaddr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr + 6))); + obj_tlen-=8; + obj_tptr+=8; + break; + case RSVP_CTYPE_IPV6: + if (obj_tlen < 20) + return-1; + ND_PRINT((ndo, ""%s Source Address: %s, Source Port: %u"", + ident, + ip6addr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr + 18))); + obj_tlen-=20; + obj_tptr+=20; + break; + case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */ + if (obj_tlen < 40) + return-1; + ND_PRINT((ndo, ""%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x"" + ""%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x"", + ident, + ip6addr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr+18), + ident, + ip6addr_string(ndo, obj_tptr+20), + EXTRACT_16BITS(obj_tptr + 38))); + obj_tlen-=40; + obj_tptr+=40; + break; + case RSVP_CTYPE_TUNNEL_IPV4: + if (obj_tlen < 8) + return-1; + ND_PRINT((ndo, ""%s IPv4 Tunnel Sender Address: %s, LSP-ID: 0x%04x"", + ident, + ipaddr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr + 6))); + obj_tlen-=8; + obj_tptr+=8; + break; + case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */ + if (obj_tlen < 16) + return-1; + ND_PRINT((ndo, ""%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x"" + ""%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x"", + ident, + ipaddr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr+6), + ident, + ipaddr_string(ndo, obj_tptr+8), + EXTRACT_16BITS(obj_tptr + 12))); + obj_tlen-=16; + obj_tptr+=16; + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_LABEL_REQ: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + while(obj_tlen >= 4 ) { + ND_PRINT((ndo, ""%s L3 Protocol ID: %s"", + ident, + tok2str(ethertype_values, + ""Unknown Protocol (0x%04x)"", + EXTRACT_16BITS(obj_tptr + 2)))); + obj_tlen-=4; + obj_tptr+=4; + } + break; + case RSVP_CTYPE_2: + if (obj_tlen < 12) + return-1; + ND_PRINT((ndo, ""%s L3 Protocol ID: %s"", + ident, + tok2str(ethertype_values, + ""Unknown Protocol (0x%04x)"", + EXTRACT_16BITS(obj_tptr + 2)))); + ND_PRINT((ndo, "",%s merge capability"",((*(obj_tptr + 4)) & 0x80) ? ""no"" : """" )); + ND_PRINT((ndo, ""%s Minimum VPI/VCI: %u/%u"", + ident, + (EXTRACT_16BITS(obj_tptr+4))&0xfff, + (EXTRACT_16BITS(obj_tptr + 6)) & 0xfff)); + ND_PRINT((ndo, ""%s Maximum VPI/VCI: %u/%u"", + ident, + (EXTRACT_16BITS(obj_tptr+8))&0xfff, + (EXTRACT_16BITS(obj_tptr + 10)) & 0xfff)); + obj_tlen-=12; + obj_tptr+=12; + break; + case RSVP_CTYPE_3: + if (obj_tlen < 12) + return-1; + ND_PRINT((ndo, ""%s L3 Protocol ID: %s"", + ident, + tok2str(ethertype_values, + ""Unknown Protocol (0x%04x)"", + EXTRACT_16BITS(obj_tptr + 2)))); + ND_PRINT((ndo, ""%s Minimum/Maximum DLCI: %u/%u, %s%s bit DLCI"", + ident, + (EXTRACT_32BITS(obj_tptr+4))&0x7fffff, + (EXTRACT_32BITS(obj_tptr+8))&0x7fffff, + (((EXTRACT_16BITS(obj_tptr+4)>>7)&3) == 0 ) ? ""10"" : """", + (((EXTRACT_16BITS(obj_tptr + 4) >> 7) & 3) == 2 ) ? ""23"" : """")); + obj_tlen-=12; + obj_tptr+=12; + break; + case RSVP_CTYPE_4: + if (obj_tlen < 4) + return-1; + ND_PRINT((ndo, ""%s LSP Encoding Type: %s (%u)"", + ident, + tok2str(gmpls_encoding_values, + ""Unknown"", + *obj_tptr), + *obj_tptr)); + ND_PRINT((ndo, ""%s Switching Type: %s (%u), Payload ID: %s (0x%04x)"", + ident, + tok2str(gmpls_switch_cap_values, + ""Unknown"", + *(obj_tptr+1)), + *(obj_tptr+1), + tok2str(gmpls_payload_values, + ""Unknown"", + EXTRACT_16BITS(obj_tptr+2)), + EXTRACT_16BITS(obj_tptr + 2))); + obj_tlen-=4; + obj_tptr+=4; + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_RRO: + case RSVP_OBJ_ERO: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_IPV4: + while(obj_tlen >= 4 ) { + u_char length; + + ND_TCHECK2(*obj_tptr, 4); + length = *(obj_tptr + 1); + ND_PRINT((ndo, ""%s Subobject Type: %s, length %u"", + ident, + tok2str(rsvp_obj_xro_values, + ""Unknown %u"", + RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)), + length)); + + if (length == 0) { /* prevent infinite loops */ + ND_PRINT((ndo, ""%s ERROR: zero length ERO subtype"", ident)); + break; + } + + switch(RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)) { + u_char prefix_length; + + case RSVP_OBJ_XRO_IPV4: + if (length != 8) { + ND_PRINT((ndo, "" ERROR: length != 8"")); + goto invalid; + } + ND_TCHECK2(*obj_tptr, 8); + prefix_length = *(obj_tptr+6); + if (prefix_length != 32) { + ND_PRINT((ndo, "" ERROR: Prefix length %u != 32"", + prefix_length)); + goto invalid; + } + ND_PRINT((ndo, "", %s, %s/%u, Flags: [%s]"", + RSVP_OBJ_XRO_MASK_LOOSE(*obj_tptr) ? ""Loose"" : ""Strict"", + ipaddr_string(ndo, obj_tptr+2), + *(obj_tptr+6), + bittok2str(rsvp_obj_rro_flag_values, + ""none"", + *(obj_tptr + 7)))); /* rfc3209 says that this field is rsvd. */ + break; + case RSVP_OBJ_XRO_LABEL: + if (length != 8) { + ND_PRINT((ndo, "" ERROR: length != 8"")); + goto invalid; + } + ND_TCHECK2(*obj_tptr, 8); + ND_PRINT((ndo, "", Flags: [%s] (%#x), Class-Type: %s (%u), %u"", + bittok2str(rsvp_obj_rro_label_flag_values, + ""none"", + *(obj_tptr+2)), + *(obj_tptr+2), + tok2str(rsvp_ctype_values, + ""Unknown"", + *(obj_tptr+3) + 256*RSVP_OBJ_RRO), + *(obj_tptr+3), + EXTRACT_32BITS(obj_tptr + 4))); + } + obj_tlen-=*(obj_tptr+1); + obj_tptr+=*(obj_tptr+1); + } + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_HELLO: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + case RSVP_CTYPE_2: + if (obj_tlen < 8) + return-1; + ND_PRINT((ndo, ""%s Source Instance: 0x%08x, Destination Instance: 0x%08x"", + ident, + EXTRACT_32BITS(obj_tptr), + EXTRACT_32BITS(obj_tptr + 4))); + obj_tlen-=8; + obj_tptr+=8; + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_RESTART_CAPABILITY: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + if (obj_tlen < 8) + return-1; + ND_PRINT((ndo, ""%s Restart Time: %ums, Recovery Time: %ums"", + ident, + EXTRACT_32BITS(obj_tptr), + EXTRACT_32BITS(obj_tptr + 4))); + obj_tlen-=8; + obj_tptr+=8; + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_SESSION_ATTRIBUTE: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_TUNNEL_IPV4: + if (obj_tlen < 4) + return-1; + namelen = *(obj_tptr+3); + if (obj_tlen < 4+namelen) + return-1; + ND_PRINT((ndo, ""%s Session Name: "", ident)); + for (i = 0; i < namelen; i++) + safeputchar(ndo, *(obj_tptr + 4 + i)); + ND_PRINT((ndo, ""%s Setup Priority: %u, Holding Priority: %u, Flags: [%s] (%#x)"", + ident, + (int)*obj_tptr, + (int)*(obj_tptr+1), + bittok2str(rsvp_session_attribute_flag_values, + ""none"", + *(obj_tptr+2)), + *(obj_tptr + 2))); + obj_tlen-=4+*(obj_tptr+3); + obj_tptr+=4+*(obj_tptr+3); + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_GENERALIZED_UNI: + switch(rsvp_obj_ctype) { + int subobj_type,af,subobj_len,total_subobj_len; + + case RSVP_CTYPE_1: + + if (obj_tlen < 4) + return-1; + + /* read variable length subobjects */ + total_subobj_len = obj_tlen; + while(total_subobj_len > 0) { + /* If RFC 3476 Section 3.1 defined that a sub-object of the + * GENERALIZED_UNI RSVP object must have the Length field as + * a multiple of 4, instead of the check below it would be + * better to test total_subobj_len only once before the loop. + * So long as it does not define it and this while loop does + * not implement such a requirement, let's accept that within + * each iteration subobj_len may happen to be a multiple of 1 + * and test it and total_subobj_len respectively. + */ + if (total_subobj_len < 4) + goto invalid; + subobj_len = EXTRACT_16BITS(obj_tptr); + subobj_type = (EXTRACT_16BITS(obj_tptr+2))>>8; + af = (EXTRACT_16BITS(obj_tptr+2))&0x00FF; + + ND_PRINT((ndo, ""%s Subobject Type: %s (%u), AF: %s (%u), length: %u"", + ident, + tok2str(rsvp_obj_generalized_uni_values, ""Unknown"", subobj_type), + subobj_type, + tok2str(af_values, ""Unknown"", af), af, + subobj_len)); + + /* In addition to what is explained above, the same spec does not + * explicitly say that the same Length field includes the 4-octet + * sub-object header, but as long as this while loop implements it + * as it does include, let's keep the check below consistent with + * the rest of the code. + */ + if(subobj_len < 4 || subobj_len > total_subobj_len) + goto invalid; + + switch(subobj_type) { + case RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS: + case RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS: + + switch(af) { + case AFNUM_INET: + if (subobj_len < 8) + return -1; + ND_PRINT((ndo, ""%s UNI IPv4 TNA address: %s"", + ident, ipaddr_string(ndo, obj_tptr + 4))); + break; + case AFNUM_INET6: + if (subobj_len < 20) + return -1; + ND_PRINT((ndo, ""%s UNI IPv6 TNA address: %s"", + ident, ip6addr_string(ndo, obj_tptr + 4))); + break; + case AFNUM_NSAP: + if (subobj_len) { + /* unless we have a TLV parser lets just hexdump */ + hexdump=TRUE; + } + break; + } + break; + + case RSVP_GEN_UNI_SUBOBJ_DIVERSITY: + if (subobj_len) { + /* unless we have a TLV parser lets just hexdump */ + hexdump=TRUE; + } + break; + + case RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL: + if (subobj_len < 16) { + return -1; + } + + ND_PRINT((ndo, ""%s U-bit: %x, Label type: %u, Logical port id: %u, Label: %u"", + ident, + ((EXTRACT_32BITS(obj_tptr+4))>>31), + ((EXTRACT_32BITS(obj_tptr+4))&0xFF), + EXTRACT_32BITS(obj_tptr+8), + EXTRACT_32BITS(obj_tptr + 12))); + break; + + case RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL: + if (subobj_len < 8) { + return -1; + } + + ND_PRINT((ndo, ""%s Service level: %u"", + ident, (EXTRACT_32BITS(obj_tptr + 4)) >> 24)); + break; + + default: + hexdump=TRUE; + break; + } + total_subobj_len-=subobj_len; + obj_tptr+=subobj_len; + obj_tlen+=subobj_len; + } + + if (total_subobj_len) { + /* unless we have a TLV parser lets just hexdump */ + hexdump=TRUE; + } + break; + + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_RSVP_HOP: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */ + case RSVP_CTYPE_IPV4: + if (obj_tlen < 8) + return-1; + ND_PRINT((ndo, ""%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x"", + ident, + ipaddr_string(ndo, obj_tptr), + EXTRACT_32BITS(obj_tptr + 4))); + obj_tlen-=8; + obj_tptr+=8; + if (obj_tlen) + hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */ + break; + case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */ + case RSVP_CTYPE_IPV6: + if (obj_tlen < 20) + return-1; + ND_PRINT((ndo, ""%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x"", + ident, + ip6addr_string(ndo, obj_tptr), + EXTRACT_32BITS(obj_tptr + 16))); + obj_tlen-=20; + obj_tptr+=20; + hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */ + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_TIME_VALUES: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + if (obj_tlen < 4) + return-1; + ND_PRINT((ndo, ""%s Refresh Period: %ums"", + ident, + EXTRACT_32BITS(obj_tptr))); + obj_tlen-=4; + obj_tptr+=4; + break; + default: + hexdump=TRUE; + } + break; + + /* those three objects do share the same semantics */ + case RSVP_OBJ_SENDER_TSPEC: + case RSVP_OBJ_ADSPEC: + case RSVP_OBJ_FLOWSPEC: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_2: + if (obj_tlen < 4) + return-1; + ND_PRINT((ndo, ""%s Msg-Version: %u, length: %u"", + ident, + (*obj_tptr & 0xf0) >> 4, + EXTRACT_16BITS(obj_tptr + 2) << 2)); + obj_tptr+=4; /* get to the start of the service header */ + obj_tlen-=4; + + while (obj_tlen >= 4) { + intserv_serv_tlen=EXTRACT_16BITS(obj_tptr+2)<<2; + ND_PRINT((ndo, ""%s Service Type: %s (%u), break bit %s set, Service length: %u"", + ident, + tok2str(rsvp_intserv_service_type_values,""unknown"",*(obj_tptr)), + *(obj_tptr), + (*(obj_tptr+1)&0x80) ? """" : ""not"", + intserv_serv_tlen)); + + obj_tptr+=4; /* get to the start of the parameter list */ + obj_tlen-=4; + + while (intserv_serv_tlen>=4) { + processed = rsvp_intserv_print(ndo, obj_tptr, obj_tlen); + if (processed == 0) + break; + obj_tlen-=processed; + intserv_serv_tlen-=processed; + obj_tptr+=processed; + } + } + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_FILTERSPEC: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_IPV4: + if (obj_tlen < 8) + return-1; + ND_PRINT((ndo, ""%s Source Address: %s, Source Port: %u"", + ident, + ipaddr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr + 6))); + obj_tlen-=8; + obj_tptr+=8; + break; + case RSVP_CTYPE_IPV6: + if (obj_tlen < 20) + return-1; + ND_PRINT((ndo, ""%s Source Address: %s, Source Port: %u"", + ident, + ip6addr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr + 18))); + obj_tlen-=20; + obj_tptr+=20; + break; + case RSVP_CTYPE_3: + if (obj_tlen < 20) + return-1; + ND_PRINT((ndo, ""%s Source Address: %s, Flow Label: %u"", + ident, + ip6addr_string(ndo, obj_tptr), + EXTRACT_24BITS(obj_tptr + 17))); + obj_tlen-=20; + obj_tptr+=20; + break; + case RSVP_CTYPE_TUNNEL_IPV6: + if (obj_tlen < 20) + return-1; + ND_PRINT((ndo, ""%s Source Address: %s, LSP-ID: 0x%04x"", + ident, + ipaddr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr + 18))); + obj_tlen-=20; + obj_tptr+=20; + break; + case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */ + if (obj_tlen < 40) + return-1; + ND_PRINT((ndo, ""%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x"" + ""%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x"", + ident, + ip6addr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr+18), + ident, + ip6addr_string(ndo, obj_tptr+20), + EXTRACT_16BITS(obj_tptr + 38))); + obj_tlen-=40; + obj_tptr+=40; + break; + case RSVP_CTYPE_TUNNEL_IPV4: + if (obj_tlen < 8) + return-1; + ND_PRINT((ndo, ""%s Source Address: %s, LSP-ID: 0x%04x"", + ident, + ipaddr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr + 6))); + obj_tlen-=8; + obj_tptr+=8; + break; + case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */ + if (obj_tlen < 16) + return-1; + ND_PRINT((ndo, ""%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x"" + ""%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x"", + ident, + ipaddr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr+6), + ident, + ipaddr_string(ndo, obj_tptr+8), + EXTRACT_16BITS(obj_tptr + 12))); + obj_tlen-=16; + obj_tptr+=16; + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_FASTREROUTE: + /* the differences between c-type 1 and 7 are minor */ + obj_ptr.rsvp_obj_frr = (const struct rsvp_obj_frr_t *)obj_tptr; + + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: /* new style */ + if (obj_tlen < sizeof(struct rsvp_obj_frr_t)) + return-1; + bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth); + ND_PRINT((ndo, ""%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps"", + ident, + (int)obj_ptr.rsvp_obj_frr->setup_prio, + (int)obj_ptr.rsvp_obj_frr->hold_prio, + (int)obj_ptr.rsvp_obj_frr->hop_limit, + bw.f * 8 / 1000000)); + ND_PRINT((ndo, ""%s Include-any: 0x%08x, Exclude-any: 0x%08x, Include-all: 0x%08x"", + ident, + EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any), + EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any), + EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_all))); + obj_tlen-=sizeof(struct rsvp_obj_frr_t); + obj_tptr+=sizeof(struct rsvp_obj_frr_t); + break; + + case RSVP_CTYPE_TUNNEL_IPV4: /* old style */ + if (obj_tlen < 16) + return-1; + bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth); + ND_PRINT((ndo, ""%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps"", + ident, + (int)obj_ptr.rsvp_obj_frr->setup_prio, + (int)obj_ptr.rsvp_obj_frr->hold_prio, + (int)obj_ptr.rsvp_obj_frr->hop_limit, + bw.f * 8 / 1000000)); + ND_PRINT((ndo, ""%s Include Colors: 0x%08x, Exclude Colors: 0x%08x"", + ident, + EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any), + EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any))); + obj_tlen-=16; + obj_tptr+=16; + break; + + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_DETOUR: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_TUNNEL_IPV4: + while(obj_tlen >= 8) { + ND_PRINT((ndo, ""%s PLR-ID: %s, Avoid-Node-ID: %s"", + ident, + ipaddr_string(ndo, obj_tptr), + ipaddr_string(ndo, obj_tptr + 4))); + obj_tlen-=8; + obj_tptr+=8; + } + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_CLASSTYPE: + case RSVP_OBJ_CLASSTYPE_OLD: /* fall through */ + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + ND_PRINT((ndo, ""%s CT: %u"", + ident, + EXTRACT_32BITS(obj_tptr) & 0x7)); + obj_tlen-=4; + obj_tptr+=4; + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_ERROR_SPEC: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */ + case RSVP_CTYPE_IPV4: + if (obj_tlen < 8) + return-1; + error_code=*(obj_tptr+5); + error_value=EXTRACT_16BITS(obj_tptr+6); + ND_PRINT((ndo, ""%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)"", + ident, + ipaddr_string(ndo, obj_tptr), + *(obj_tptr+4), + ident, + tok2str(rsvp_obj_error_code_values,""unknown"",error_code), + error_code)); + switch (error_code) { + case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING: + ND_PRINT((ndo, "", Error Value: %s (%u)"", + tok2str(rsvp_obj_error_code_routing_values,""unknown"",error_value), + error_value)); + break; + case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE: /* fall through */ + case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD: + ND_PRINT((ndo, "", Error Value: %s (%u)"", + tok2str(rsvp_obj_error_code_diffserv_te_values,""unknown"",error_value), + error_value)); + break; + default: + ND_PRINT((ndo, "", Unknown Error Value (%u)"", error_value)); + break; + } + obj_tlen-=8; + obj_tptr+=8; + break; + case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */ + case RSVP_CTYPE_IPV6: + if (obj_tlen < 20) + return-1; + error_code=*(obj_tptr+17); + error_value=EXTRACT_16BITS(obj_tptr+18); + ND_PRINT((ndo, ""%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)"", + ident, + ip6addr_string(ndo, obj_tptr), + *(obj_tptr+16), + ident, + tok2str(rsvp_obj_error_code_values,""unknown"",error_code), + error_code)); + + switch (error_code) { + case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING: + ND_PRINT((ndo, "", Error Value: %s (%u)"", + tok2str(rsvp_obj_error_code_routing_values,""unknown"",error_value), + error_value)); + break; + default: + break; + } + obj_tlen-=20; + obj_tptr+=20; + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_PROPERTIES: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + if (obj_tlen < 4) + return-1; + padbytes = EXTRACT_16BITS(obj_tptr+2); + ND_PRINT((ndo, ""%s TLV count: %u, padding bytes: %u"", + ident, + EXTRACT_16BITS(obj_tptr), + padbytes)); + obj_tlen-=4; + obj_tptr+=4; + /* loop through as long there is anything longer than the TLV header (2) */ + while(obj_tlen >= 2 + padbytes) { + ND_PRINT((ndo, ""%s %s TLV (0x%02x), length: %u"", /* length includes header */ + ident, + tok2str(rsvp_obj_prop_tlv_values,""unknown"",*obj_tptr), + *obj_tptr, + *(obj_tptr + 1))); + if (obj_tlen < *(obj_tptr+1)) + return-1; + if (*(obj_tptr+1) < 2) + return -1; + print_unknown_data(ndo, obj_tptr + 2, ""\n\t\t"", *(obj_tptr + 1) - 2); + obj_tlen-=*(obj_tptr+1); + obj_tptr+=*(obj_tptr+1); + } + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_MESSAGE_ID: /* fall through */ + case RSVP_OBJ_MESSAGE_ID_ACK: /* fall through */ + case RSVP_OBJ_MESSAGE_ID_LIST: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + case RSVP_CTYPE_2: + if (obj_tlen < 8) + return-1; + ND_PRINT((ndo, ""%s Flags [0x%02x], epoch: %u"", + ident, + *obj_tptr, + EXTRACT_24BITS(obj_tptr + 1))); + obj_tlen-=4; + obj_tptr+=4; + /* loop through as long there are no messages left */ + while(obj_tlen >= 4) { + ND_PRINT((ndo, ""%s Message-ID 0x%08x (%u)"", + ident, + EXTRACT_32BITS(obj_tptr), + EXTRACT_32BITS(obj_tptr))); + obj_tlen-=4; + obj_tptr+=4; + } + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_INTEGRITY: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + if (obj_tlen < sizeof(struct rsvp_obj_integrity_t)) + return-1; + obj_ptr.rsvp_obj_integrity = (const struct rsvp_obj_integrity_t *)obj_tptr; + ND_PRINT((ndo, ""%s Key-ID 0x%04x%08x, Sequence 0x%08x%08x, Flags [%s]"", + ident, + EXTRACT_16BITS(obj_ptr.rsvp_obj_integrity->key_id), + EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->key_id+2), + EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence), + EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence+4), + bittok2str(rsvp_obj_integrity_flag_values, + ""none"", + obj_ptr.rsvp_obj_integrity->flags))); + ND_PRINT((ndo, ""%s MD5-sum 0x%08x%08x%08x%08x "", + ident, + EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest), + EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+4), + EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+8), + EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest + 12))); + + sigcheck = signature_verify(ndo, pptr, plen, + obj_ptr.rsvp_obj_integrity->digest, + rsvp_clear_checksum, + rsvp_com_header); + ND_PRINT((ndo, "" (%s)"", tok2str(signature_check_values, ""Unknown"", sigcheck))); + + obj_tlen+=sizeof(struct rsvp_obj_integrity_t); + obj_tptr+=sizeof(struct rsvp_obj_integrity_t); + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_ADMIN_STATUS: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + if (obj_tlen < 4) + return-1; + ND_PRINT((ndo, ""%s Flags [%s]"", ident, + bittok2str(rsvp_obj_admin_status_flag_values, ""none"", + EXTRACT_32BITS(obj_tptr)))); + obj_tlen-=4; + obj_tptr+=4; + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_LABEL_SET: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + if (obj_tlen < 4) + return-1; + action = (EXTRACT_16BITS(obj_tptr)>>8); + + ND_PRINT((ndo, ""%s Action: %s (%u), Label type: %u"", ident, + tok2str(rsvp_obj_label_set_action_values, ""Unknown"", action), + action, ((EXTRACT_32BITS(obj_tptr) & 0x7F)))); + + switch (action) { + case LABEL_SET_INCLUSIVE_RANGE: + case LABEL_SET_EXCLUSIVE_RANGE: /* fall through */ + + /* only a couple of subchannels are expected */ + if (obj_tlen < 12) + return -1; + ND_PRINT((ndo, ""%s Start range: %u, End range: %u"", ident, + EXTRACT_32BITS(obj_tptr+4), + EXTRACT_32BITS(obj_tptr + 8))); + obj_tlen-=12; + obj_tptr+=12; + break; + + default: + obj_tlen-=4; + obj_tptr+=4; + subchannel = 1; + while(obj_tlen >= 4 ) { + ND_PRINT((ndo, ""%s Subchannel #%u: %u"", ident, subchannel, + EXTRACT_32BITS(obj_tptr))); + obj_tptr+=4; + obj_tlen-=4; + subchannel++; + } + break; + } + break; + default: + hexdump=TRUE; + } + + case RSVP_OBJ_S2L: + switch (rsvp_obj_ctype) { + case RSVP_CTYPE_IPV4: + if (obj_tlen < 4) + return-1; + ND_PRINT((ndo, ""%s Sub-LSP destination address: %s"", + ident, ipaddr_string(ndo, obj_tptr))); + + obj_tlen-=4; + obj_tptr+=4; + break; + case RSVP_CTYPE_IPV6: + if (obj_tlen < 16) + return-1; + ND_PRINT((ndo, ""%s Sub-LSP destination address: %s"", + ident, ip6addr_string(ndo, obj_tptr))); + + obj_tlen-=16; + obj_tptr+=16; + break; + default: + hexdump=TRUE; + } + + /* + * FIXME those are the defined objects that lack a decoder + * you are welcome to contribute code ;-) + */ + + case RSVP_OBJ_SCOPE: + case RSVP_OBJ_POLICY_DATA: + case RSVP_OBJ_ACCEPT_LABEL_SET: + case RSVP_OBJ_PROTECTION: + default: + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, obj_tptr, ""\n\t "", obj_tlen); /* FIXME indentation */ + break; + } + /* do we also want to see a hex dump ? */ + if (ndo->ndo_vflag > 1 || hexdump == TRUE) + print_unknown_data(ndo, tptr + sizeof(struct rsvp_object_header), ""\n\t "", /* FIXME indentation */ + rsvp_obj_len - sizeof(struct rsvp_object_header)); + + tptr+=rsvp_obj_len; + tlen-=rsvp_obj_len; + } + return 0; +invalid: + ND_PRINT((ndo, ""%s"", istr)); + return -1; +trunc: + ND_PRINT((ndo, ""\n\t\t"")); + ND_PRINT((ndo, ""%s"", tstr)); + return -1; +} +",1,"rsvp_obj_print(netdissect_options *ndo, + const u_char *pptr, u_int plen, const u_char *tptr, + const char *ident, u_int tlen, + const struct rsvp_common_header *rsvp_com_header) +{ + const struct rsvp_object_header *rsvp_obj_header; + const u_char *obj_tptr; + union { + const struct rsvp_obj_integrity_t *rsvp_obj_integrity; + const struct rsvp_obj_frr_t *rsvp_obj_frr; + } obj_ptr; + + u_short rsvp_obj_len,rsvp_obj_ctype,obj_tlen,intserv_serv_tlen; + int hexdump,processed,padbytes,error_code,error_value,i,sigcheck; + union { + float f; + uint32_t i; + } bw; + uint8_t namelen; + + u_int action, subchannel; + + while(tlen>=sizeof(struct rsvp_object_header)) { + /* did we capture enough for fully decoding the object header ? */ + ND_TCHECK2(*tptr, sizeof(struct rsvp_object_header)); + + rsvp_obj_header = (const struct rsvp_object_header *)tptr; + rsvp_obj_len=EXTRACT_16BITS(rsvp_obj_header->length); + rsvp_obj_ctype=rsvp_obj_header->ctype; + + if(rsvp_obj_len % 4) { + ND_PRINT((ndo, ""%sERROR: object header size %u not a multiple of 4"", ident, rsvp_obj_len)); + return -1; + } + if(rsvp_obj_len < sizeof(struct rsvp_object_header)) { + ND_PRINT((ndo, ""%sERROR: object header too short %u < %lu"", ident, rsvp_obj_len, + (unsigned long)sizeof(const struct rsvp_object_header))); + return -1; + } + + ND_PRINT((ndo, ""%s%s Object (%u) Flags: [%s"", + ident, + tok2str(rsvp_obj_values, + ""Unknown"", + rsvp_obj_header->class_num), + rsvp_obj_header->class_num, + ((rsvp_obj_header->class_num) & 0x80) ? ""ignore"" : ""reject"")); + + if (rsvp_obj_header->class_num > 128) + ND_PRINT((ndo, "" %s"", + ((rsvp_obj_header->class_num) & 0x40) ? ""and forward"" : ""silently"")); + + ND_PRINT((ndo, "" if unknown], Class-Type: %s (%u), length: %u"", + tok2str(rsvp_ctype_values, + ""Unknown"", + ((rsvp_obj_header->class_num)<<8)+rsvp_obj_ctype), + rsvp_obj_ctype, + rsvp_obj_len)); + + if(tlen < rsvp_obj_len) { + ND_PRINT((ndo, ""%sERROR: object goes past end of objects TLV"", ident)); + return -1; + } + + obj_tptr=tptr+sizeof(struct rsvp_object_header); + obj_tlen=rsvp_obj_len-sizeof(struct rsvp_object_header); + + /* did we capture enough for fully decoding the object ? */ + if (!ND_TTEST2(*tptr, rsvp_obj_len)) + return -1; + hexdump=FALSE; + + switch(rsvp_obj_header->class_num) { + case RSVP_OBJ_SESSION: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_IPV4: + if (obj_tlen < 8) + return -1; + ND_PRINT((ndo, ""%s IPv4 DestAddress: %s, Protocol ID: 0x%02x"", + ident, + ipaddr_string(ndo, obj_tptr), + *(obj_tptr + sizeof(struct in_addr)))); + ND_PRINT((ndo, ""%s Flags: [0x%02x], DestPort %u"", + ident, + *(obj_tptr+5), + EXTRACT_16BITS(obj_tptr + 6))); + obj_tlen-=8; + obj_tptr+=8; + break; + case RSVP_CTYPE_IPV6: + if (obj_tlen < 20) + return -1; + ND_PRINT((ndo, ""%s IPv6 DestAddress: %s, Protocol ID: 0x%02x"", + ident, + ip6addr_string(ndo, obj_tptr), + *(obj_tptr + sizeof(struct in6_addr)))); + ND_PRINT((ndo, ""%s Flags: [0x%02x], DestPort %u"", + ident, + *(obj_tptr+sizeof(struct in6_addr)+1), + EXTRACT_16BITS(obj_tptr + sizeof(struct in6_addr) + 2))); + obj_tlen-=20; + obj_tptr+=20; + break; + + case RSVP_CTYPE_TUNNEL_IPV6: + if (obj_tlen < 36) + return -1; + ND_PRINT((ndo, ""%s IPv6 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s"", + ident, + ip6addr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr+18), + ip6addr_string(ndo, obj_tptr + 20))); + obj_tlen-=36; + obj_tptr+=36; + break; + + case RSVP_CTYPE_14: /* IPv6 p2mp LSP Tunnel */ + if (obj_tlen < 26) + return -1; + ND_PRINT((ndo, ""%s IPv6 P2MP LSP ID: 0x%08x, Tunnel ID: 0x%04x, Extended Tunnel ID: %s"", + ident, + EXTRACT_32BITS(obj_tptr), + EXTRACT_16BITS(obj_tptr+6), + ip6addr_string(ndo, obj_tptr + 8))); + obj_tlen-=26; + obj_tptr+=26; + break; + case RSVP_CTYPE_13: /* IPv4 p2mp LSP Tunnel */ + if (obj_tlen < 12) + return -1; + ND_PRINT((ndo, ""%s IPv4 P2MP LSP ID: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s"", + ident, + ipaddr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr+6), + ipaddr_string(ndo, obj_tptr + 8))); + obj_tlen-=12; + obj_tptr+=12; + break; + case RSVP_CTYPE_TUNNEL_IPV4: + case RSVP_CTYPE_UNI_IPV4: + if (obj_tlen < 12) + return -1; + ND_PRINT((ndo, ""%s IPv4 Tunnel EndPoint: %s, Tunnel ID: 0x%04x, Extended Tunnel ID: %s"", + ident, + ipaddr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr+6), + ipaddr_string(ndo, obj_tptr + 8))); + obj_tlen-=12; + obj_tptr+=12; + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_CONFIRM: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_IPV4: + if (obj_tlen < sizeof(struct in_addr)) + return -1; + ND_PRINT((ndo, ""%s IPv4 Receiver Address: %s"", + ident, + ipaddr_string(ndo, obj_tptr))); + obj_tlen-=sizeof(struct in_addr); + obj_tptr+=sizeof(struct in_addr); + break; + case RSVP_CTYPE_IPV6: + if (obj_tlen < sizeof(struct in6_addr)) + return -1; + ND_PRINT((ndo, ""%s IPv6 Receiver Address: %s"", + ident, + ip6addr_string(ndo, obj_tptr))); + obj_tlen-=sizeof(struct in6_addr); + obj_tptr+=sizeof(struct in6_addr); + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_NOTIFY_REQ: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_IPV4: + if (obj_tlen < sizeof(struct in_addr)) + return -1; + ND_PRINT((ndo, ""%s IPv4 Notify Node Address: %s"", + ident, + ipaddr_string(ndo, obj_tptr))); + obj_tlen-=sizeof(struct in_addr); + obj_tptr+=sizeof(struct in_addr); + break; + case RSVP_CTYPE_IPV6: + if (obj_tlen < sizeof(struct in6_addr)) + return-1; + ND_PRINT((ndo, ""%s IPv6 Notify Node Address: %s"", + ident, + ip6addr_string(ndo, obj_tptr))); + obj_tlen-=sizeof(struct in6_addr); + obj_tptr+=sizeof(struct in6_addr); + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_SUGGESTED_LABEL: /* fall through */ + case RSVP_OBJ_UPSTREAM_LABEL: /* fall through */ + case RSVP_OBJ_RECOVERY_LABEL: /* fall through */ + case RSVP_OBJ_LABEL: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + while(obj_tlen >= 4 ) { + ND_PRINT((ndo, ""%s Label: %u"", ident, EXTRACT_32BITS(obj_tptr))); + obj_tlen-=4; + obj_tptr+=4; + } + break; + case RSVP_CTYPE_2: + if (obj_tlen < 4) + return-1; + ND_PRINT((ndo, ""%s Generalized Label: %u"", + ident, + EXTRACT_32BITS(obj_tptr))); + obj_tlen-=4; + obj_tptr+=4; + break; + case RSVP_CTYPE_3: + if (obj_tlen < 12) + return-1; + ND_PRINT((ndo, ""%s Waveband ID: %u%s Start Label: %u, Stop Label: %u"", + ident, + EXTRACT_32BITS(obj_tptr), + ident, + EXTRACT_32BITS(obj_tptr+4), + EXTRACT_32BITS(obj_tptr + 8))); + obj_tlen-=12; + obj_tptr+=12; + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_STYLE: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + if (obj_tlen < 4) + return-1; + ND_PRINT((ndo, ""%s Reservation Style: %s, Flags: [0x%02x]"", + ident, + tok2str(rsvp_resstyle_values, + ""Unknown"", + EXTRACT_24BITS(obj_tptr+1)), + *(obj_tptr))); + obj_tlen-=4; + obj_tptr+=4; + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_SENDER_TEMPLATE: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_IPV4: + if (obj_tlen < 8) + return-1; + ND_PRINT((ndo, ""%s Source Address: %s, Source Port: %u"", + ident, + ipaddr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr + 6))); + obj_tlen-=8; + obj_tptr+=8; + break; + case RSVP_CTYPE_IPV6: + if (obj_tlen < 20) + return-1; + ND_PRINT((ndo, ""%s Source Address: %s, Source Port: %u"", + ident, + ip6addr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr + 18))); + obj_tlen-=20; + obj_tptr+=20; + break; + case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */ + if (obj_tlen < 40) + return-1; + ND_PRINT((ndo, ""%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x"" + ""%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x"", + ident, + ip6addr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr+18), + ident, + ip6addr_string(ndo, obj_tptr+20), + EXTRACT_16BITS(obj_tptr + 38))); + obj_tlen-=40; + obj_tptr+=40; + break; + case RSVP_CTYPE_TUNNEL_IPV4: + if (obj_tlen < 8) + return-1; + ND_PRINT((ndo, ""%s IPv4 Tunnel Sender Address: %s, LSP-ID: 0x%04x"", + ident, + ipaddr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr + 6))); + obj_tlen-=8; + obj_tptr+=8; + break; + case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */ + if (obj_tlen < 16) + return-1; + ND_PRINT((ndo, ""%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x"" + ""%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x"", + ident, + ipaddr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr+6), + ident, + ipaddr_string(ndo, obj_tptr+8), + EXTRACT_16BITS(obj_tptr + 12))); + obj_tlen-=16; + obj_tptr+=16; + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_LABEL_REQ: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + while(obj_tlen >= 4 ) { + ND_PRINT((ndo, ""%s L3 Protocol ID: %s"", + ident, + tok2str(ethertype_values, + ""Unknown Protocol (0x%04x)"", + EXTRACT_16BITS(obj_tptr + 2)))); + obj_tlen-=4; + obj_tptr+=4; + } + break; + case RSVP_CTYPE_2: + if (obj_tlen < 12) + return-1; + ND_PRINT((ndo, ""%s L3 Protocol ID: %s"", + ident, + tok2str(ethertype_values, + ""Unknown Protocol (0x%04x)"", + EXTRACT_16BITS(obj_tptr + 2)))); + ND_PRINT((ndo, "",%s merge capability"",((*(obj_tptr + 4)) & 0x80) ? ""no"" : """" )); + ND_PRINT((ndo, ""%s Minimum VPI/VCI: %u/%u"", + ident, + (EXTRACT_16BITS(obj_tptr+4))&0xfff, + (EXTRACT_16BITS(obj_tptr + 6)) & 0xfff)); + ND_PRINT((ndo, ""%s Maximum VPI/VCI: %u/%u"", + ident, + (EXTRACT_16BITS(obj_tptr+8))&0xfff, + (EXTRACT_16BITS(obj_tptr + 10)) & 0xfff)); + obj_tlen-=12; + obj_tptr+=12; + break; + case RSVP_CTYPE_3: + if (obj_tlen < 12) + return-1; + ND_PRINT((ndo, ""%s L3 Protocol ID: %s"", + ident, + tok2str(ethertype_values, + ""Unknown Protocol (0x%04x)"", + EXTRACT_16BITS(obj_tptr + 2)))); + ND_PRINT((ndo, ""%s Minimum/Maximum DLCI: %u/%u, %s%s bit DLCI"", + ident, + (EXTRACT_32BITS(obj_tptr+4))&0x7fffff, + (EXTRACT_32BITS(obj_tptr+8))&0x7fffff, + (((EXTRACT_16BITS(obj_tptr+4)>>7)&3) == 0 ) ? ""10"" : """", + (((EXTRACT_16BITS(obj_tptr + 4) >> 7) & 3) == 2 ) ? ""23"" : """")); + obj_tlen-=12; + obj_tptr+=12; + break; + case RSVP_CTYPE_4: + if (obj_tlen < 4) + return-1; + ND_PRINT((ndo, ""%s LSP Encoding Type: %s (%u)"", + ident, + tok2str(gmpls_encoding_values, + ""Unknown"", + *obj_tptr), + *obj_tptr)); + ND_PRINT((ndo, ""%s Switching Type: %s (%u), Payload ID: %s (0x%04x)"", + ident, + tok2str(gmpls_switch_cap_values, + ""Unknown"", + *(obj_tptr+1)), + *(obj_tptr+1), + tok2str(gmpls_payload_values, + ""Unknown"", + EXTRACT_16BITS(obj_tptr+2)), + EXTRACT_16BITS(obj_tptr + 2))); + obj_tlen-=4; + obj_tptr+=4; + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_RRO: + case RSVP_OBJ_ERO: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_IPV4: + while(obj_tlen >= 4 ) { + u_char length; + + ND_TCHECK2(*obj_tptr, 4); + length = *(obj_tptr + 1); + ND_PRINT((ndo, ""%s Subobject Type: %s, length %u"", + ident, + tok2str(rsvp_obj_xro_values, + ""Unknown %u"", + RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)), + length)); + + if (length == 0) { /* prevent infinite loops */ + ND_PRINT((ndo, ""%s ERROR: zero length ERO subtype"", ident)); + break; + } + + switch(RSVP_OBJ_XRO_MASK_SUBOBJ(*obj_tptr)) { + u_char prefix_length; + + case RSVP_OBJ_XRO_IPV4: + if (length != 8) { + ND_PRINT((ndo, "" ERROR: length != 8"")); + goto invalid; + } + ND_TCHECK2(*obj_tptr, 8); + prefix_length = *(obj_tptr+6); + if (prefix_length != 32) { + ND_PRINT((ndo, "" ERROR: Prefix length %u != 32"", + prefix_length)); + goto invalid; + } + ND_PRINT((ndo, "", %s, %s/%u, Flags: [%s]"", + RSVP_OBJ_XRO_MASK_LOOSE(*obj_tptr) ? ""Loose"" : ""Strict"", + ipaddr_string(ndo, obj_tptr+2), + *(obj_tptr+6), + bittok2str(rsvp_obj_rro_flag_values, + ""none"", + *(obj_tptr + 7)))); /* rfc3209 says that this field is rsvd. */ + break; + case RSVP_OBJ_XRO_LABEL: + if (length != 8) { + ND_PRINT((ndo, "" ERROR: length != 8"")); + goto invalid; + } + ND_TCHECK2(*obj_tptr, 8); + ND_PRINT((ndo, "", Flags: [%s] (%#x), Class-Type: %s (%u), %u"", + bittok2str(rsvp_obj_rro_label_flag_values, + ""none"", + *(obj_tptr+2)), + *(obj_tptr+2), + tok2str(rsvp_ctype_values, + ""Unknown"", + *(obj_tptr+3) + 256*RSVP_OBJ_RRO), + *(obj_tptr+3), + EXTRACT_32BITS(obj_tptr + 4))); + } + obj_tlen-=*(obj_tptr+1); + obj_tptr+=*(obj_tptr+1); + } + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_HELLO: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + case RSVP_CTYPE_2: + if (obj_tlen < 8) + return-1; + ND_PRINT((ndo, ""%s Source Instance: 0x%08x, Destination Instance: 0x%08x"", + ident, + EXTRACT_32BITS(obj_tptr), + EXTRACT_32BITS(obj_tptr + 4))); + obj_tlen-=8; + obj_tptr+=8; + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_RESTART_CAPABILITY: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + if (obj_tlen < 8) + return-1; + ND_PRINT((ndo, ""%s Restart Time: %ums, Recovery Time: %ums"", + ident, + EXTRACT_32BITS(obj_tptr), + EXTRACT_32BITS(obj_tptr + 4))); + obj_tlen-=8; + obj_tptr+=8; + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_SESSION_ATTRIBUTE: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_TUNNEL_IPV4: + if (obj_tlen < 4) + return-1; + namelen = *(obj_tptr+3); + if (obj_tlen < 4+namelen) + return-1; + ND_PRINT((ndo, ""%s Session Name: "", ident)); + for (i = 0; i < namelen; i++) + safeputchar(ndo, *(obj_tptr + 4 + i)); + ND_PRINT((ndo, ""%s Setup Priority: %u, Holding Priority: %u, Flags: [%s] (%#x)"", + ident, + (int)*obj_tptr, + (int)*(obj_tptr+1), + bittok2str(rsvp_session_attribute_flag_values, + ""none"", + *(obj_tptr+2)), + *(obj_tptr + 2))); + obj_tlen-=4+*(obj_tptr+3); + obj_tptr+=4+*(obj_tptr+3); + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_GENERALIZED_UNI: + switch(rsvp_obj_ctype) { + int subobj_type,af,subobj_len,total_subobj_len; + + case RSVP_CTYPE_1: + + if (obj_tlen < 4) + return-1; + + /* read variable length subobjects */ + total_subobj_len = obj_tlen; + while(total_subobj_len > 0) { + /* If RFC 3476 Section 3.1 defined that a sub-object of the + * GENERALIZED_UNI RSVP object must have the Length field as + * a multiple of 4, instead of the check below it would be + * better to test total_subobj_len only once before the loop. + * So long as it does not define it and this while loop does + * not implement such a requirement, let's accept that within + * each iteration subobj_len may happen to be a multiple of 1 + * and test it and total_subobj_len respectively. + */ + if (total_subobj_len < 4) + goto invalid; + subobj_len = EXTRACT_16BITS(obj_tptr); + subobj_type = (EXTRACT_16BITS(obj_tptr+2))>>8; + af = (EXTRACT_16BITS(obj_tptr+2))&0x00FF; + + ND_PRINT((ndo, ""%s Subobject Type: %s (%u), AF: %s (%u), length: %u"", + ident, + tok2str(rsvp_obj_generalized_uni_values, ""Unknown"", subobj_type), + subobj_type, + tok2str(af_values, ""Unknown"", af), af, + subobj_len)); + + /* In addition to what is explained above, the same spec does not + * explicitly say that the same Length field includes the 4-octet + * sub-object header, but as long as this while loop implements it + * as it does include, let's keep the check below consistent with + * the rest of the code. + */ + if(subobj_len < 4 || subobj_len > total_subobj_len) + goto invalid; + + switch(subobj_type) { + case RSVP_GEN_UNI_SUBOBJ_SOURCE_TNA_ADDRESS: + case RSVP_GEN_UNI_SUBOBJ_DESTINATION_TNA_ADDRESS: + + switch(af) { + case AFNUM_INET: + if (subobj_len < 8) + return -1; + ND_PRINT((ndo, ""%s UNI IPv4 TNA address: %s"", + ident, ipaddr_string(ndo, obj_tptr + 4))); + break; + case AFNUM_INET6: + if (subobj_len < 20) + return -1; + ND_PRINT((ndo, ""%s UNI IPv6 TNA address: %s"", + ident, ip6addr_string(ndo, obj_tptr + 4))); + break; + case AFNUM_NSAP: + if (subobj_len) { + /* unless we have a TLV parser lets just hexdump */ + hexdump=TRUE; + } + break; + } + break; + + case RSVP_GEN_UNI_SUBOBJ_DIVERSITY: + if (subobj_len) { + /* unless we have a TLV parser lets just hexdump */ + hexdump=TRUE; + } + break; + + case RSVP_GEN_UNI_SUBOBJ_EGRESS_LABEL: + if (subobj_len < 16) { + return -1; + } + + ND_PRINT((ndo, ""%s U-bit: %x, Label type: %u, Logical port id: %u, Label: %u"", + ident, + ((EXTRACT_32BITS(obj_tptr+4))>>31), + ((EXTRACT_32BITS(obj_tptr+4))&0xFF), + EXTRACT_32BITS(obj_tptr+8), + EXTRACT_32BITS(obj_tptr + 12))); + break; + + case RSVP_GEN_UNI_SUBOBJ_SERVICE_LEVEL: + if (subobj_len < 8) { + return -1; + } + + ND_PRINT((ndo, ""%s Service level: %u"", + ident, (EXTRACT_32BITS(obj_tptr + 4)) >> 24)); + break; + + default: + hexdump=TRUE; + break; + } + total_subobj_len-=subobj_len; + obj_tptr+=subobj_len; + obj_tlen+=subobj_len; + } + + if (total_subobj_len) { + /* unless we have a TLV parser lets just hexdump */ + hexdump=TRUE; + } + break; + + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_RSVP_HOP: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */ + case RSVP_CTYPE_IPV4: + if (obj_tlen < 8) + return-1; + ND_PRINT((ndo, ""%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x"", + ident, + ipaddr_string(ndo, obj_tptr), + EXTRACT_32BITS(obj_tptr + 4))); + obj_tlen-=8; + obj_tptr+=8; + if (obj_tlen) + hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */ + break; + case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */ + case RSVP_CTYPE_IPV6: + if (obj_tlen < 20) + return-1; + ND_PRINT((ndo, ""%s Previous/Next Interface: %s, Logical Interface Handle: 0x%08x"", + ident, + ip6addr_string(ndo, obj_tptr), + EXTRACT_32BITS(obj_tptr + 16))); + obj_tlen-=20; + obj_tptr+=20; + hexdump=TRUE; /* unless we have a TLV parser lets just hexdump */ + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_TIME_VALUES: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + if (obj_tlen < 4) + return-1; + ND_PRINT((ndo, ""%s Refresh Period: %ums"", + ident, + EXTRACT_32BITS(obj_tptr))); + obj_tlen-=4; + obj_tptr+=4; + break; + default: + hexdump=TRUE; + } + break; + + /* those three objects do share the same semantics */ + case RSVP_OBJ_SENDER_TSPEC: + case RSVP_OBJ_ADSPEC: + case RSVP_OBJ_FLOWSPEC: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_2: + if (obj_tlen < 4) + return-1; + ND_PRINT((ndo, ""%s Msg-Version: %u, length: %u"", + ident, + (*obj_tptr & 0xf0) >> 4, + EXTRACT_16BITS(obj_tptr + 2) << 2)); + obj_tptr+=4; /* get to the start of the service header */ + obj_tlen-=4; + + while (obj_tlen >= 4) { + intserv_serv_tlen=EXTRACT_16BITS(obj_tptr+2)<<2; + ND_PRINT((ndo, ""%s Service Type: %s (%u), break bit %s set, Service length: %u"", + ident, + tok2str(rsvp_intserv_service_type_values,""unknown"",*(obj_tptr)), + *(obj_tptr), + (*(obj_tptr+1)&0x80) ? """" : ""not"", + intserv_serv_tlen)); + + obj_tptr+=4; /* get to the start of the parameter list */ + obj_tlen-=4; + + while (intserv_serv_tlen>=4) { + processed = rsvp_intserv_print(ndo, obj_tptr, obj_tlen); + if (processed == 0) + break; + obj_tlen-=processed; + intserv_serv_tlen-=processed; + obj_tptr+=processed; + } + } + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_FILTERSPEC: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_IPV4: + if (obj_tlen < 8) + return-1; + ND_PRINT((ndo, ""%s Source Address: %s, Source Port: %u"", + ident, + ipaddr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr + 6))); + obj_tlen-=8; + obj_tptr+=8; + break; + case RSVP_CTYPE_IPV6: + if (obj_tlen < 20) + return-1; + ND_PRINT((ndo, ""%s Source Address: %s, Source Port: %u"", + ident, + ip6addr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr + 18))); + obj_tlen-=20; + obj_tptr+=20; + break; + case RSVP_CTYPE_3: + if (obj_tlen < 20) + return-1; + ND_PRINT((ndo, ""%s Source Address: %s, Flow Label: %u"", + ident, + ip6addr_string(ndo, obj_tptr), + EXTRACT_24BITS(obj_tptr + 17))); + obj_tlen-=20; + obj_tptr+=20; + break; + case RSVP_CTYPE_TUNNEL_IPV6: + if (obj_tlen < 20) + return-1; + ND_PRINT((ndo, ""%s Source Address: %s, LSP-ID: 0x%04x"", + ident, + ipaddr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr + 18))); + obj_tlen-=20; + obj_tptr+=20; + break; + case RSVP_CTYPE_13: /* IPv6 p2mp LSP tunnel */ + if (obj_tlen < 40) + return-1; + ND_PRINT((ndo, ""%s IPv6 Tunnel Sender Address: %s, LSP ID: 0x%04x"" + ""%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x"", + ident, + ip6addr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr+18), + ident, + ip6addr_string(ndo, obj_tptr+20), + EXTRACT_16BITS(obj_tptr + 38))); + obj_tlen-=40; + obj_tptr+=40; + break; + case RSVP_CTYPE_TUNNEL_IPV4: + if (obj_tlen < 8) + return-1; + ND_PRINT((ndo, ""%s Source Address: %s, LSP-ID: 0x%04x"", + ident, + ipaddr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr + 6))); + obj_tlen-=8; + obj_tptr+=8; + break; + case RSVP_CTYPE_12: /* IPv4 p2mp LSP tunnel */ + if (obj_tlen < 16) + return-1; + ND_PRINT((ndo, ""%s IPv4 Tunnel Sender Address: %s, LSP ID: 0x%04x"" + ""%s Sub-Group Originator ID: %s, Sub-Group ID: 0x%04x"", + ident, + ipaddr_string(ndo, obj_tptr), + EXTRACT_16BITS(obj_tptr+6), + ident, + ipaddr_string(ndo, obj_tptr+8), + EXTRACT_16BITS(obj_tptr + 12))); + obj_tlen-=16; + obj_tptr+=16; + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_FASTREROUTE: + /* the differences between c-type 1 and 7 are minor */ + obj_ptr.rsvp_obj_frr = (const struct rsvp_obj_frr_t *)obj_tptr; + + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: /* new style */ + if (obj_tlen < sizeof(struct rsvp_obj_frr_t)) + return-1; + bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth); + ND_PRINT((ndo, ""%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps"", + ident, + (int)obj_ptr.rsvp_obj_frr->setup_prio, + (int)obj_ptr.rsvp_obj_frr->hold_prio, + (int)obj_ptr.rsvp_obj_frr->hop_limit, + bw.f * 8 / 1000000)); + ND_PRINT((ndo, ""%s Include-any: 0x%08x, Exclude-any: 0x%08x, Include-all: 0x%08x"", + ident, + EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any), + EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any), + EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_all))); + obj_tlen-=sizeof(struct rsvp_obj_frr_t); + obj_tptr+=sizeof(struct rsvp_obj_frr_t); + break; + + case RSVP_CTYPE_TUNNEL_IPV4: /* old style */ + if (obj_tlen < 16) + return-1; + bw.i = EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->bandwidth); + ND_PRINT((ndo, ""%s Setup Priority: %u, Holding Priority: %u, Hop-limit: %u, Bandwidth: %.10g Mbps"", + ident, + (int)obj_ptr.rsvp_obj_frr->setup_prio, + (int)obj_ptr.rsvp_obj_frr->hold_prio, + (int)obj_ptr.rsvp_obj_frr->hop_limit, + bw.f * 8 / 1000000)); + ND_PRINT((ndo, ""%s Include Colors: 0x%08x, Exclude Colors: 0x%08x"", + ident, + EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->include_any), + EXTRACT_32BITS(obj_ptr.rsvp_obj_frr->exclude_any))); + obj_tlen-=16; + obj_tptr+=16; + break; + + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_DETOUR: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_TUNNEL_IPV4: + while(obj_tlen >= 8) { + ND_PRINT((ndo, ""%s PLR-ID: %s, Avoid-Node-ID: %s"", + ident, + ipaddr_string(ndo, obj_tptr), + ipaddr_string(ndo, obj_tptr + 4))); + obj_tlen-=8; + obj_tptr+=8; + } + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_CLASSTYPE: + case RSVP_OBJ_CLASSTYPE_OLD: /* fall through */ + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + ND_TCHECK_32BITS(obj_tptr); + ND_PRINT((ndo, ""%s CT: %u"", + ident, + EXTRACT_32BITS(obj_tptr) & 0x7)); + obj_tlen-=4; + obj_tptr+=4; + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_ERROR_SPEC: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_3: /* fall through - FIXME add TLV parser */ + case RSVP_CTYPE_IPV4: + if (obj_tlen < 8) + return-1; + error_code=*(obj_tptr+5); + error_value=EXTRACT_16BITS(obj_tptr+6); + ND_PRINT((ndo, ""%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)"", + ident, + ipaddr_string(ndo, obj_tptr), + *(obj_tptr+4), + ident, + tok2str(rsvp_obj_error_code_values,""unknown"",error_code), + error_code)); + switch (error_code) { + case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING: + ND_PRINT((ndo, "", Error Value: %s (%u)"", + tok2str(rsvp_obj_error_code_routing_values,""unknown"",error_value), + error_value)); + break; + case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE: /* fall through */ + case RSVP_OBJ_ERROR_SPEC_CODE_DIFFSERV_TE_OLD: + ND_PRINT((ndo, "", Error Value: %s (%u)"", + tok2str(rsvp_obj_error_code_diffserv_te_values,""unknown"",error_value), + error_value)); + break; + default: + ND_PRINT((ndo, "", Unknown Error Value (%u)"", error_value)); + break; + } + obj_tlen-=8; + obj_tptr+=8; + break; + case RSVP_CTYPE_4: /* fall through - FIXME add TLV parser */ + case RSVP_CTYPE_IPV6: + if (obj_tlen < 20) + return-1; + error_code=*(obj_tptr+17); + error_value=EXTRACT_16BITS(obj_tptr+18); + ND_PRINT((ndo, ""%s Error Node Address: %s, Flags: [0x%02x]%s Error Code: %s (%u)"", + ident, + ip6addr_string(ndo, obj_tptr), + *(obj_tptr+16), + ident, + tok2str(rsvp_obj_error_code_values,""unknown"",error_code), + error_code)); + + switch (error_code) { + case RSVP_OBJ_ERROR_SPEC_CODE_ROUTING: + ND_PRINT((ndo, "", Error Value: %s (%u)"", + tok2str(rsvp_obj_error_code_routing_values,""unknown"",error_value), + error_value)); + break; + default: + break; + } + obj_tlen-=20; + obj_tptr+=20; + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_PROPERTIES: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + if (obj_tlen < 4) + return-1; + padbytes = EXTRACT_16BITS(obj_tptr+2); + ND_PRINT((ndo, ""%s TLV count: %u, padding bytes: %u"", + ident, + EXTRACT_16BITS(obj_tptr), + padbytes)); + obj_tlen-=4; + obj_tptr+=4; + /* loop through as long there is anything longer than the TLV header (2) */ + while(obj_tlen >= 2 + padbytes) { + ND_PRINT((ndo, ""%s %s TLV (0x%02x), length: %u"", /* length includes header */ + ident, + tok2str(rsvp_obj_prop_tlv_values,""unknown"",*obj_tptr), + *obj_tptr, + *(obj_tptr + 1))); + if (obj_tlen < *(obj_tptr+1)) + return-1; + if (*(obj_tptr+1) < 2) + return -1; + print_unknown_data(ndo, obj_tptr + 2, ""\n\t\t"", *(obj_tptr + 1) - 2); + obj_tlen-=*(obj_tptr+1); + obj_tptr+=*(obj_tptr+1); + } + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_MESSAGE_ID: /* fall through */ + case RSVP_OBJ_MESSAGE_ID_ACK: /* fall through */ + case RSVP_OBJ_MESSAGE_ID_LIST: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + case RSVP_CTYPE_2: + if (obj_tlen < 8) + return-1; + ND_PRINT((ndo, ""%s Flags [0x%02x], epoch: %u"", + ident, + *obj_tptr, + EXTRACT_24BITS(obj_tptr + 1))); + obj_tlen-=4; + obj_tptr+=4; + /* loop through as long there are no messages left */ + while(obj_tlen >= 4) { + ND_PRINT((ndo, ""%s Message-ID 0x%08x (%u)"", + ident, + EXTRACT_32BITS(obj_tptr), + EXTRACT_32BITS(obj_tptr))); + obj_tlen-=4; + obj_tptr+=4; + } + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_INTEGRITY: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + if (obj_tlen < sizeof(struct rsvp_obj_integrity_t)) + return-1; + obj_ptr.rsvp_obj_integrity = (const struct rsvp_obj_integrity_t *)obj_tptr; + ND_PRINT((ndo, ""%s Key-ID 0x%04x%08x, Sequence 0x%08x%08x, Flags [%s]"", + ident, + EXTRACT_16BITS(obj_ptr.rsvp_obj_integrity->key_id), + EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->key_id+2), + EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence), + EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->sequence+4), + bittok2str(rsvp_obj_integrity_flag_values, + ""none"", + obj_ptr.rsvp_obj_integrity->flags))); + ND_PRINT((ndo, ""%s MD5-sum 0x%08x%08x%08x%08x "", + ident, + EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest), + EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+4), + EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest+8), + EXTRACT_32BITS(obj_ptr.rsvp_obj_integrity->digest + 12))); + + sigcheck = signature_verify(ndo, pptr, plen, + obj_ptr.rsvp_obj_integrity->digest, + rsvp_clear_checksum, + rsvp_com_header); + ND_PRINT((ndo, "" (%s)"", tok2str(signature_check_values, ""Unknown"", sigcheck))); + + obj_tlen+=sizeof(struct rsvp_obj_integrity_t); + obj_tptr+=sizeof(struct rsvp_obj_integrity_t); + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_ADMIN_STATUS: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + if (obj_tlen < 4) + return-1; + ND_PRINT((ndo, ""%s Flags [%s]"", ident, + bittok2str(rsvp_obj_admin_status_flag_values, ""none"", + EXTRACT_32BITS(obj_tptr)))); + obj_tlen-=4; + obj_tptr+=4; + break; + default: + hexdump=TRUE; + } + break; + + case RSVP_OBJ_LABEL_SET: + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: + if (obj_tlen < 4) + return-1; + action = (EXTRACT_16BITS(obj_tptr)>>8); + + ND_PRINT((ndo, ""%s Action: %s (%u), Label type: %u"", ident, + tok2str(rsvp_obj_label_set_action_values, ""Unknown"", action), + action, ((EXTRACT_32BITS(obj_tptr) & 0x7F)))); + + switch (action) { + case LABEL_SET_INCLUSIVE_RANGE: + case LABEL_SET_EXCLUSIVE_RANGE: /* fall through */ + + /* only a couple of subchannels are expected */ + if (obj_tlen < 12) + return -1; + ND_PRINT((ndo, ""%s Start range: %u, End range: %u"", ident, + EXTRACT_32BITS(obj_tptr+4), + EXTRACT_32BITS(obj_tptr + 8))); + obj_tlen-=12; + obj_tptr+=12; + break; + + default: + obj_tlen-=4; + obj_tptr+=4; + subchannel = 1; + while(obj_tlen >= 4 ) { + ND_PRINT((ndo, ""%s Subchannel #%u: %u"", ident, subchannel, + EXTRACT_32BITS(obj_tptr))); + obj_tptr+=4; + obj_tlen-=4; + subchannel++; + } + break; + } + break; + default: + hexdump=TRUE; + } + + case RSVP_OBJ_S2L: + switch (rsvp_obj_ctype) { + case RSVP_CTYPE_IPV4: + if (obj_tlen < 4) + return-1; + ND_PRINT((ndo, ""%s Sub-LSP destination address: %s"", + ident, ipaddr_string(ndo, obj_tptr))); + + obj_tlen-=4; + obj_tptr+=4; + break; + case RSVP_CTYPE_IPV6: + if (obj_tlen < 16) + return-1; + ND_PRINT((ndo, ""%s Sub-LSP destination address: %s"", + ident, ip6addr_string(ndo, obj_tptr))); + + obj_tlen-=16; + obj_tptr+=16; + break; + default: + hexdump=TRUE; + } + + /* + * FIXME those are the defined objects that lack a decoder + * you are welcome to contribute code ;-) + */ + + case RSVP_OBJ_SCOPE: + case RSVP_OBJ_POLICY_DATA: + case RSVP_OBJ_ACCEPT_LABEL_SET: + case RSVP_OBJ_PROTECTION: + default: + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, obj_tptr, ""\n\t "", obj_tlen); /* FIXME indentation */ + break; + } + /* do we also want to see a hex dump ? */ + if (ndo->ndo_vflag > 1 || hexdump == TRUE) + print_unknown_data(ndo, tptr + sizeof(struct rsvp_object_header), ""\n\t "", /* FIXME indentation */ + rsvp_obj_len - sizeof(struct rsvp_object_header)); + + tptr+=rsvp_obj_len; + tlen-=rsvp_obj_len; + } + return 0; +invalid: + ND_PRINT((ndo, ""%s"", istr)); + return -1; +trunc: + ND_PRINT((ndo, ""\n\t\t"")); + ND_PRINT((ndo, ""%s"", tstr)); + return -1; +} +","@@ -1555,6 +1555,7 @@ rsvp_obj_print(netdissect_options *ndo, + case RSVP_OBJ_CLASSTYPE_OLD: /* fall through */ + switch(rsvp_obj_ctype) { + case RSVP_CTYPE_1: ++ ND_TCHECK_32BITS(obj_tptr); + ND_PRINT((ndo, ""%s CT: %u"", + ident, + EXTRACT_32BITS(obj_tptr) & 0x7));",10905,11236,15000 +18325,"static void cmdloop(void) +{ + int c; + int usinguid, havepartition, havenamespace, recursive; + static struct buf tag, cmd, arg1, arg2, arg3; + char *p, shut[MAX_MAILBOX_PATH+1], cmdname[100]; + const char *err; + const char * commandmintimer; + double commandmintimerd = 0.0; + struct sync_reserve_list *reserve_list = + sync_reserve_list_create(SYNC_MESSAGE_LIST_HASH_SIZE); + struct applepushserviceargs applepushserviceargs; + + prot_printf(imapd_out, ""* OK [CAPABILITY ""); + capa_response(CAPA_PREAUTH); + prot_printf(imapd_out, ""]""); + if (config_serverinfo) prot_printf(imapd_out, "" %s"", config_servername); + if (config_serverinfo == IMAP_ENUM_SERVERINFO_ON) { + prot_printf(imapd_out, "" Cyrus IMAP %s"", cyrus_version()); + } + prot_printf(imapd_out, "" server ready\r\n""); + + /* clear cancelled flag if present before the next command */ + cmd_cancelled(); + + motd_file(); + + /* Get command timer logging paramater. This string + * is a time in seconds. Any command that takes >= + * this time to execute is logged */ + commandmintimer = config_getstring(IMAPOPT_COMMANDMINTIMER); + cmdtime_settimer(commandmintimer ? 1 : 0); + if (commandmintimer) { + commandmintimerd = atof(commandmintimer); + } + + for (;;) { + /* Release any held index */ + index_release(imapd_index); + + /* Flush any buffered output */ + prot_flush(imapd_out); + if (backend_current) prot_flush(backend_current->out); + + /* command no longer running */ + proc_register(config_ident, imapd_clienthost, imapd_userid, index_mboxname(imapd_index), NULL); + + /* Check for shutdown file */ + if ( !imapd_userisadmin && imapd_userid && + (shutdown_file(shut, sizeof(shut)) || + userdeny(imapd_userid, config_ident, shut, sizeof(shut)))) { + for (p = shut; *p == '['; p++); /* can't have [ be first char */ + prot_printf(imapd_out, ""* BYE [ALERT] %s\r\n"", p); + telemetry_rusage(imapd_userid); + shut_down(0); + } + + signals_poll(); + + if (!proxy_check_input(protin, imapd_in, imapd_out, + backend_current ? backend_current->in : NULL, + NULL, 0)) { + /* No input from client */ + continue; + } + + /* Parse tag */ + c = getword(imapd_in, &tag); + if (c == EOF) { + if ((err = prot_error(imapd_in))!=NULL + && strcmp(err, PROT_EOF_STRING)) { + syslog(LOG_WARNING, ""%s, closing connection"", err); + prot_printf(imapd_out, ""* BYE %s\r\n"", err); + } + goto done; + } + if (c != ' ' || !imparse_isatom(tag.s) || (tag.s[0] == '*' && !tag.s[1])) { + prot_printf(imapd_out, ""* BAD Invalid tag\r\n""); + eatline(imapd_in, c); + continue; + } + + /* Parse command name */ + c = getword(imapd_in, &cmd); + if (!cmd.s[0]) { + prot_printf(imapd_out, ""%s BAD Null command\r\n"", tag.s); + eatline(imapd_in, c); + continue; + } + lcase(cmd.s); + xstrncpy(cmdname, cmd.s, 99); + cmd.s[0] = toupper((unsigned char) cmd.s[0]); + + if (config_getswitch(IMAPOPT_CHATTY)) + syslog(LOG_NOTICE, ""command: %s %s"", tag.s, cmd.s); + + proc_register(config_ident, imapd_clienthost, imapd_userid, index_mboxname(imapd_index), cmd.s); + + /* if we need to force a kick, do so */ + if (referral_kick) { + kick_mupdate(); + referral_kick = 0; + } + + if (plaintextloginalert) { + prot_printf(imapd_out, ""* OK [ALERT] %s\r\n"", + plaintextloginalert); + plaintextloginalert = NULL; + } + + /* Only Authenticate/Enable/Login/Logout/Noop/Capability/Id/Starttls + allowed when not logged in */ + if (!imapd_userid && !strchr(""AELNCIS"", cmd.s[0])) goto nologin; + + /* Start command timer */ + cmdtime_starttimer(); + + /* note that about half the commands (the common ones that don't + hit the mailboxes file) now close the mailboxes file just in + case it was open. */ + switch (cmd.s[0]) { + case 'A': + if (!strcmp(cmd.s, ""Authenticate"")) { + int haveinitresp = 0; + + if (c != ' ') goto missingargs; + c = getword(imapd_in, &arg1); + if (!imparse_isatom(arg1.s)) { + prot_printf(imapd_out, ""%s BAD Invalid authenticate mechanism\r\n"", tag.s); + eatline(imapd_in, c); + continue; + } + if (c == ' ') { + haveinitresp = 1; + c = getword(imapd_in, &arg2); + if (c == EOF) goto missingargs; + } + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + if (imapd_userid) { + prot_printf(imapd_out, ""%s BAD Already authenticated\r\n"", tag.s); + continue; + } + cmd_authenticate(tag.s, arg1.s, haveinitresp ? arg2.s : NULL); + + snmp_increment(AUTHENTICATE_COUNT, 1); + } + else if (!imapd_userid) goto nologin; + else if (!strcmp(cmd.s, ""Append"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + + cmd_append(tag.s, arg1.s, NULL); + + snmp_increment(APPEND_COUNT, 1); + } + else goto badcmd; + break; + + case 'C': + if (!strcmp(cmd.s, ""Capability"")) { + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_capability(tag.s); + + snmp_increment(CAPABILITY_COUNT, 1); + } + else if (!imapd_userid) goto nologin; +#ifdef HAVE_ZLIB + else if (!strcmp(cmd.s, ""Compress"")) { + if (c != ' ') goto missingargs; + c = getword(imapd_in, &arg1); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + cmd_compress(tag.s, arg1.s); + + snmp_increment(COMPRESS_COUNT, 1); + } +#endif /* HAVE_ZLIB */ + else if (!strcmp(cmd.s, ""Check"")) { + if (!imapd_index && !backend_current) goto nomailbox; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + cmd_noop(tag.s, cmd.s); + + snmp_increment(CHECK_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Copy"")) { + if (!imapd_index && !backend_current) goto nomailbox; + usinguid = 0; + if (c != ' ') goto missingargs; + copy: + c = getword(imapd_in, &arg1); + if (c == '\r') goto missingargs; + if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence; + c = getastring(imapd_in, imapd_out, &arg2); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + cmd_copy(tag.s, arg1.s, arg2.s, usinguid, /*ismove*/0); + + snmp_increment(COPY_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Create"")) { + struct dlist *extargs = NULL; + + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + if (c == ' ') { + c = parsecreateargs(&extargs); + if (c == EOF) goto badpartition; + } + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_create(tag.s, arg1.s, extargs, 0); + dlist_free(&extargs); + + snmp_increment(CREATE_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Close"")) { + if (!imapd_index && !backend_current) goto nomailbox; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + cmd_close(tag.s, cmd.s); + + snmp_increment(CLOSE_COUNT, 1); + } + else goto badcmd; + break; + + case 'D': + if (!strcmp(cmd.s, ""Delete"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_delete(tag.s, arg1.s, 0, 0); + + snmp_increment(DELETE_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Deleteacl"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg2); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_setacl(tag.s, arg1.s, arg2.s, NULL); + + snmp_increment(DELETEACL_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Dump"")) { + int uid_start = 0; + + if(c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if(c == ' ') { + c = getastring(imapd_in, imapd_out, &arg2); + if(!imparse_isnumber(arg2.s)) goto extraargs; + uid_start = atoi(arg2.s); + } + + if(c == '\r') c = prot_getc(imapd_in); + if(c != '\n') goto extraargs; + + cmd_dump(tag.s, arg1.s, uid_start); + /* snmp_increment(DUMP_COUNT, 1);*/ + } + else goto badcmd; + break; + + case 'E': + if (!imapd_userid) goto nologin; + else if (!strcmp(cmd.s, ""Enable"")) { + if (c != ' ') goto missingargs; + + cmd_enable(tag.s); + } + else if (!strcmp(cmd.s, ""Expunge"")) { + if (!imapd_index && !backend_current) goto nomailbox; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + cmd_expunge(tag.s, 0); + + snmp_increment(EXPUNGE_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Examine"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + prot_ungetc(c, imapd_in); + + cmd_select(tag.s, cmd.s, arg1.s); + + snmp_increment(EXAMINE_COUNT, 1); + } + else goto badcmd; + break; + + case 'F': + if (!strcmp(cmd.s, ""Fetch"")) { + if (!imapd_index && !backend_current) goto nomailbox; + usinguid = 0; + if (c != ' ') goto missingargs; + fetch: + c = getword(imapd_in, &arg1); + if (c == '\r') goto missingargs; + if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence; + + cmd_fetch(tag.s, arg1.s, usinguid); + + snmp_increment(FETCH_COUNT, 1); + } + else goto badcmd; + break; + + case 'G': + if (!strcmp(cmd.s, ""Getacl"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_getacl(tag.s, arg1.s); + + snmp_increment(GETACL_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Getannotation"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + + cmd_getannotation(tag.s, arg1.s); + + snmp_increment(GETANNOTATION_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Getmetadata"")) { + if (c != ' ') goto missingargs; + + cmd_getmetadata(tag.s); + + snmp_increment(GETANNOTATION_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Getquota"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_getquota(tag.s, arg1.s); + + snmp_increment(GETQUOTA_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Getquotaroot"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_getquotaroot(tag.s, arg1.s); + + snmp_increment(GETQUOTAROOT_COUNT, 1); + } +#ifdef HAVE_SSL + else if (!strcmp(cmd.s, ""Genurlauth"")) { + if (c != ' ') goto missingargs; + + cmd_genurlauth(tag.s); + /* snmp_increment(GENURLAUTH_COUNT, 1);*/ + } +#endif + else goto badcmd; + break; + + case 'I': + if (!strcmp(cmd.s, ""Id"")) { + if (c != ' ') goto missingargs; + cmd_id(tag.s); + + snmp_increment(ID_COUNT, 1); + } + else if (!imapd_userid) goto nologin; + else if (!strcmp(cmd.s, ""Idle"") && idle_enabled()) { + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_idle(tag.s); + + snmp_increment(IDLE_COUNT, 1); + } + else goto badcmd; + break; + + case 'L': + if (!strcmp(cmd.s, ""Login"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if(c != ' ') goto missingargs; + + cmd_login(tag.s, arg1.s); + + snmp_increment(LOGIN_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Logout"")) { + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + snmp_increment(LOGOUT_COUNT, 1); + + /* force any responses from our selected backend */ + if (backend_current) imapd_check(NULL, 0); + + prot_printf(imapd_out, ""* BYE %s\r\n"", + error_message(IMAP_BYE_LOGOUT)); + prot_printf(imapd_out, ""%s OK %s\r\n"", tag.s, + error_message(IMAP_OK_COMPLETED)); + + if (imapd_userid && *imapd_userid) { + telemetry_rusage(imapd_userid); + } + + goto done; + } + else if (!imapd_userid) goto nologin; + else if (!strcmp(cmd.s, ""List"")) { + struct listargs listargs; + + if (c != ' ') goto missingargs; + + memset(&listargs, 0, sizeof(struct listargs)); + listargs.ret = LIST_RET_CHILDREN; + getlistargs(tag.s, &listargs); + if (listargs.pat.count) cmd_list(tag.s, &listargs); + + snmp_increment(LIST_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Lsub"")) { + struct listargs listargs; + + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg2); + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + memset(&listargs, 0, sizeof(struct listargs)); + listargs.cmd = LIST_CMD_LSUB; + listargs.sel = LIST_SEL_SUBSCRIBED; + if (!strcasecmpsafe(imapd_magicplus, ""+dav"")) + listargs.sel |= LIST_SEL_DAV; + listargs.ref = arg1.s; + strarray_append(&listargs.pat, arg2.s); + + cmd_list(tag.s, &listargs); + + snmp_increment(LSUB_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Listrights"")) { + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg2); + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_listrights(tag.s, arg1.s, arg2.s); + + snmp_increment(LISTRIGHTS_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Localappend"")) { + /* create a local-only mailbox */ + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg2); + if (c != ' ') goto missingargs; + + cmd_append(tag.s, arg1.s, *arg2.s ? arg2.s : NULL); + + snmp_increment(APPEND_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Localcreate"")) { + /* create a local-only mailbox */ + struct dlist *extargs = NULL; + + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + if (c == ' ') { + c = parsecreateargs(&extargs); + if (c == EOF) goto badpartition; + } + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_create(tag.s, arg1.s, extargs, 1); + dlist_free(&extargs); + + /* xxxx snmp_increment(CREATE_COUNT, 1); */ + } + else if (!strcmp(cmd.s, ""Localdelete"")) { + /* delete a mailbox locally only */ + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_delete(tag.s, arg1.s, 1, 1); + + /* xxxx snmp_increment(DELETE_COUNT, 1); */ + } + else goto badcmd; + break; + + case 'M': + if (!strcmp(cmd.s, ""Myrights"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_myrights(tag.s, arg1.s); + + /* xxxx snmp_increment(MYRIGHTS_COUNT, 1); */ + } + else if (!strcmp(cmd.s, ""Mupdatepush"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if(c == EOF) goto missingargs; + if(c == '\r') c = prot_getc(imapd_in); + if(c != '\n') goto extraargs; + cmd_mupdatepush(tag.s, arg1.s); + + /* xxxx snmp_increment(MUPDATEPUSH_COUNT, 1); */ + } + else if (!strcmp(cmd.s, ""Move"")) { + if (!imapd_index && !backend_current) goto nomailbox; + usinguid = 0; + if (c != ' ') goto missingargs; + move: + c = getword(imapd_in, &arg1); + if (c == '\r') goto missingargs; + if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence; + c = getastring(imapd_in, imapd_out, &arg2); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + cmd_copy(tag.s, arg1.s, arg2.s, usinguid, /*ismove*/1); + + snmp_increment(COPY_COUNT, 1); + } else goto badcmd; + break; + + case 'N': + if (!strcmp(cmd.s, ""Noop"")) { + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + cmd_noop(tag.s, cmd.s); + + /* xxxx snmp_increment(NOOP_COUNT, 1); */ + } + else if (!imapd_userid) goto nologin; + else if (!strcmp(cmd.s, ""Namespace"")) { + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_namespace(tag.s); + + /* xxxx snmp_increment(NAMESPACE_COUNT, 1); */ + } + else goto badcmd; + break; + + case 'R': + if (!strcmp(cmd.s, ""Rename"")) { + havepartition = 0; + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg2); + if (c == EOF) goto missingargs; + if (c == ' ') { + havepartition = 1; + c = getword(imapd_in, &arg3); + if (!imparse_isatom(arg3.s)) goto badpartition; + } + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_rename(tag.s, arg1.s, arg2.s, havepartition ? arg3.s : 0); + + /* xxxx snmp_increment(RENAME_COUNT, 1); */ + } else if(!strcmp(cmd.s, ""Reconstruct"")) { + recursive = 0; + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if(c == ' ') { + /* Optional RECURSEIVE argument */ + c = getword(imapd_in, &arg2); + if(!imparse_isatom(arg2.s)) + goto extraargs; + else if(!strcasecmp(arg2.s, ""RECURSIVE"")) + recursive = 1; + else + goto extraargs; + } + if(c == '\r') c = prot_getc(imapd_in); + if(c != '\n') goto extraargs; + cmd_reconstruct(tag.s, arg1.s, recursive); + + /* snmp_increment(RECONSTRUCT_COUNT, 1); */ + } + else if (!strcmp(cmd.s, ""Rlist"")) { + struct listargs listargs; + + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg2); + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + memset(&listargs, 0, sizeof(struct listargs)); + listargs.sel = LIST_SEL_REMOTE; + listargs.ret = LIST_RET_CHILDREN; + listargs.ref = arg1.s; + strarray_append(&listargs.pat, arg2.s); + + cmd_list(tag.s, &listargs); + +/* snmp_increment(LIST_COUNT, 1); */ + } + else if (!strcmp(cmd.s, ""Rlsub"")) { + struct listargs listargs; + + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg2); + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + memset(&listargs, 0, sizeof(struct listargs)); + listargs.cmd = LIST_CMD_LSUB; + listargs.sel = LIST_SEL_REMOTE | LIST_SEL_SUBSCRIBED; + listargs.ref = arg1.s; + strarray_append(&listargs.pat, arg2.s); + + cmd_list(tag.s, &listargs); + +/* snmp_increment(LSUB_COUNT, 1); */ + } +#ifdef HAVE_SSL + else if (!strcmp(cmd.s, ""Resetkey"")) { + int have_mbox = 0, have_mech = 0; + + if (c == ' ') { + have_mbox = 1; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + if (c == ' ') { + have_mech = 1; + c = getword(imapd_in, &arg2); + } + } + + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_resetkey(tag.s, have_mbox ? arg1.s : 0, + have_mech ? arg2.s : 0); + /* snmp_increment(RESETKEY_COUNT, 1);*/ + } +#endif + else goto badcmd; + break; + + case 'S': + if (!strcmp(cmd.s, ""Starttls"")) { + if (!tls_enabled()) { + /* we don't support starttls */ + goto badcmd; + } + + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + /* XXX discard any input pipelined after STARTTLS */ + prot_flush(imapd_in); + + /* if we've already done SASL fail */ + if (imapd_userid != NULL) { + prot_printf(imapd_out, + ""%s BAD Can't Starttls after authentication\r\n"", tag.s); + continue; + } + + /* if we've already done COMPRESS fail */ + if (imapd_compress_done == 1) { + prot_printf(imapd_out, + ""%s BAD Can't Starttls after Compress\r\n"", tag.s); + continue; + } + + /* check if already did a successful tls */ + if (imapd_starttls_done == 1) { + prot_printf(imapd_out, + ""%s BAD Already did a successful Starttls\r\n"", + tag.s); + continue; + } + cmd_starttls(tag.s, 0); + + snmp_increment(STARTTLS_COUNT, 1); + continue; + } + if (!imapd_userid) { + goto nologin; + } else if (!strcmp(cmd.s, ""Store"")) { + if (!imapd_index && !backend_current) goto nomailbox; + usinguid = 0; + if (c != ' ') goto missingargs; + store: + c = getword(imapd_in, &arg1); + if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence; + + cmd_store(tag.s, arg1.s, usinguid); + + snmp_increment(STORE_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Select"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + prot_ungetc(c, imapd_in); + + cmd_select(tag.s, cmd.s, arg1.s); + + snmp_increment(SELECT_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Search"")) { + if (!imapd_index && !backend_current) goto nomailbox; + usinguid = 0; + if (c != ' ') goto missingargs; + search: + + cmd_search(tag.s, usinguid); + + snmp_increment(SEARCH_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Subscribe"")) { + if (c != ' ') goto missingargs; + havenamespace = 0; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == ' ') { + havenamespace = 1; + c = getastring(imapd_in, imapd_out, &arg2); + } + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + if (havenamespace) { + cmd_changesub(tag.s, arg1.s, arg2.s, 1); + } + else { + cmd_changesub(tag.s, (char *)0, arg1.s, 1); + } + snmp_increment(SUBSCRIBE_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Setacl"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg2); + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg3); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_setacl(tag.s, arg1.s, arg2.s, arg3.s); + + snmp_increment(SETACL_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Setannotation"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + + cmd_setannotation(tag.s, arg1.s); + + snmp_increment(SETANNOTATION_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Setmetadata"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + + cmd_setmetadata(tag.s, arg1.s); + + snmp_increment(SETANNOTATION_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Setquota"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + cmd_setquota(tag.s, arg1.s); + + snmp_increment(SETQUOTA_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Sort"")) { + if (!imapd_index && !backend_current) goto nomailbox; + usinguid = 0; + if (c != ' ') goto missingargs; + sort: + cmd_sort(tag.s, usinguid); + + snmp_increment(SORT_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Status"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + cmd_status(tag.s, arg1.s); + + snmp_increment(STATUS_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Scan"")) { + struct listargs listargs; + + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg2); + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg3); + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + memset(&listargs, 0, sizeof(struct listargs)); + listargs.ref = arg1.s; + strarray_append(&listargs.pat, arg2.s); + listargs.scan = arg3.s; + + cmd_list(tag.s, &listargs); + + snmp_increment(SCAN_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Syncapply"")) { + struct dlist *kl = sync_parseline(imapd_in); + + if (kl) { + cmd_syncapply(tag.s, kl, reserve_list); + dlist_free(&kl); + } + else goto extraargs; + } + else if (!strcmp(cmd.s, ""Syncget"")) { + struct dlist *kl = sync_parseline(imapd_in); + + if (kl) { + cmd_syncget(tag.s, kl); + dlist_free(&kl); + } + else goto extraargs; + } + else if (!strcmp(cmd.s, ""Syncrestart"")) { + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + /* just clear the GUID cache */ + cmd_syncrestart(tag.s, &reserve_list, 1); + } + else if (!strcmp(cmd.s, ""Syncrestore"")) { + struct dlist *kl = sync_parseline(imapd_in); + + if (kl) { + cmd_syncrestore(tag.s, kl, reserve_list); + dlist_free(&kl); + } + else goto extraargs; + } + else goto badcmd; + break; + + case 'T': + if (!strcmp(cmd.s, ""Thread"")) { + if (!imapd_index && !backend_current) goto nomailbox; + usinguid = 0; + if (c != ' ') goto missingargs; + thread: + cmd_thread(tag.s, usinguid); + + snmp_increment(THREAD_COUNT, 1); + } + else goto badcmd; + break; + + case 'U': + if (!strcmp(cmd.s, ""Uid"")) { + if (!imapd_index && !backend_current) goto nomailbox; + usinguid = 1; + if (c != ' ') goto missingargs; + c = getword(imapd_in, &arg1); + if (c != ' ') goto missingargs; + lcase(arg1.s); + xstrncpy(cmdname, arg1.s, 99); + if (!strcmp(arg1.s, ""fetch"")) { + goto fetch; + } + else if (!strcmp(arg1.s, ""store"")) { + goto store; + } + else if (!strcmp(arg1.s, ""search"")) { + goto search; + } + else if (!strcmp(arg1.s, ""sort"")) { + goto sort; + } + else if (!strcmp(arg1.s, ""thread"")) { + goto thread; + } + else if (!strcmp(arg1.s, ""copy"")) { + goto copy; + } + else if (!strcmp(arg1.s, ""move"")) { + goto move; + } + else if (!strcmp(arg1.s, ""xmove"")) { + goto move; + } + else if (!strcmp(arg1.s, ""expunge"")) { + c = getword(imapd_in, &arg1); + if (!imparse_issequence(arg1.s)) goto badsequence; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_expunge(tag.s, arg1.s); + + snmp_increment(EXPUNGE_COUNT, 1); + } + else if (!strcmp(arg1.s, ""xrunannotator"")) { + goto xrunannotator; + } + else { + prot_printf(imapd_out, ""%s BAD Unrecognized UID subcommand\r\n"", tag.s); + eatline(imapd_in, c); + } + } + else if (!strcmp(cmd.s, ""Unsubscribe"")) { + if (c != ' ') goto missingargs; + havenamespace = 0; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == ' ') { + havenamespace = 1; + c = getastring(imapd_in, imapd_out, &arg2); + } + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + if (havenamespace) { + cmd_changesub(tag.s, arg1.s, arg2.s, 0); + } + else { + cmd_changesub(tag.s, (char *)0, arg1.s, 0); + } + + snmp_increment(UNSUBSCRIBE_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Unselect"")) { + if (!imapd_index && !backend_current) goto nomailbox; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + cmd_close(tag.s, cmd.s); + + snmp_increment(UNSELECT_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Undump"")) { + if(c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + + /* we want to get a list at this point */ + if(c != ' ') goto missingargs; + + cmd_undump(tag.s, arg1.s); + /* snmp_increment(UNDUMP_COUNT, 1);*/ + } +#ifdef HAVE_SSL + else if (!strcmp(cmd.s, ""Urlfetch"")) { + if (c != ' ') goto missingargs; + + cmd_urlfetch(tag.s); + /* snmp_increment(URLFETCH_COUNT, 1);*/ + } +#endif + else goto badcmd; + break; + + case 'X': + if (!strcmp(cmd.s, ""Xbackup"")) { + int havechannel = 0; + + if (!config_getswitch(IMAPOPT_XBACKUP_ENABLED)) + goto badcmd; + + /* user */ + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + + /* channel */ + if (c == ' ') { + havechannel = 1; + c = getword(imapd_in, &arg2); + if (c == EOF) goto missingargs; + } + + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + cmd_xbackup(tag.s, arg1.s, havechannel ? arg2.s : NULL); + + } + else if (!strcmp(cmd.s, ""Xconvfetch"")) { + cmd_xconvfetch(tag.s); + + } + else if (!strcmp(cmd.s, ""Xconvmultisort"")) { + if (c != ' ') goto missingargs; + if (!imapd_index && !backend_current) goto nomailbox; + cmd_xconvmultisort(tag.s); + + } + else if (!strcmp(cmd.s, ""Xconvsort"")) { + if (c != ' ') goto missingargs; + if (!imapd_index && !backend_current) goto nomailbox; + cmd_xconvsort(tag.s, 0); + + } + else if (!strcmp(cmd.s, ""Xconvupdates"")) { + if (c != ' ') goto missingargs; + if (!imapd_index && !backend_current) goto nomailbox; + cmd_xconvsort(tag.s, 1); + + } + else if (!strcmp(cmd.s, ""Xfer"")) { + int havepartition = 0; + + /* Mailbox */ + if(c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + + /* Dest Server */ + if(c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg2); + + if(c == ' ') { + /* Dest Partition */ + c = getastring(imapd_in, imapd_out, &arg3); + if (!imparse_isatom(arg3.s)) goto badpartition; + havepartition = 1; + } + + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + cmd_xfer(tag.s, arg1.s, arg2.s, + (havepartition ? arg3.s : NULL)); + /* snmp_increment(XFER_COUNT, 1);*/ + } + else if (!strcmp(cmd.s, ""Xconvmeta"")) { + cmd_xconvmeta(tag.s); + } + else if (!strcmp(cmd.s, ""Xlist"")) { + struct listargs listargs; + + if (c != ' ') goto missingargs; + + memset(&listargs, 0, sizeof(struct listargs)); + listargs.cmd = LIST_CMD_XLIST; + listargs.ret = LIST_RET_CHILDREN | LIST_RET_SPECIALUSE; + getlistargs(tag.s, &listargs); + if (listargs.pat.count) cmd_list(tag.s, &listargs); + + snmp_increment(LIST_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Xmove"")) { + if (!imapd_index && !backend_current) goto nomailbox; + usinguid = 0; + if (c != ' ') goto missingargs; + goto move; + } + else if (!strcmp(cmd.s, ""Xrunannotator"")) { + if (!imapd_index && !backend_current) goto nomailbox; + usinguid = 0; + if (c != ' ') goto missingargs; + xrunannotator: + c = getword(imapd_in, &arg1); + if (!arg1.len || !imparse_issequence(arg1.s)) goto badsequence; + cmd_xrunannotator(tag.s, arg1.s, usinguid); + } + else if (!strcmp(cmd.s, ""Xsnippets"")) { + if (c != ' ') goto missingargs; + if (!imapd_index && !backend_current) goto nomailbox; + cmd_xsnippets(tag.s); + + } + else if (!strcmp(cmd.s, ""Xstats"")) { + cmd_xstats(tag.s, c); + } + else if (!strcmp(cmd.s, ""Xwarmup"")) { + /* XWARMUP doesn't need a mailbox to be selected */ + if (c != ' ') goto missingargs; + cmd_xwarmup(tag.s); + } + else if (!strcmp(cmd.s, ""Xkillmy"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_xkillmy(tag.s, arg1.s); + } + else if (!strcmp(cmd.s, ""Xforever"")) { + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_xforever(tag.s); + } + else if (!strcmp(cmd.s, ""Xmeid"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_xmeid(tag.s, arg1.s); + } + + else if (apns_enabled && !strcmp(cmd.s, ""Xapplepushservice"")) { + if (c != ' ') goto missingargs; + + memset(&applepushserviceargs, 0, sizeof(struct applepushserviceargs)); + + do { + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto aps_missingargs; + + if (!strcmp(arg1.s, ""mailboxes"")) { + c = prot_getc(imapd_in); + if (c != '(') + goto aps_missingargs; + + c = prot_getc(imapd_in); + if (c != ')') { + prot_ungetc(c, imapd_in); + do { + c = getastring(imapd_in, imapd_out, &arg2); + if (c == EOF) break; + strarray_push(&applepushserviceargs.mailboxes, arg2.s); + } while (c == ' '); + } + + if (c != ')') + goto aps_missingargs; + c = prot_getc(imapd_in); + } + + else { + c = getastring(imapd_in, imapd_out, &arg2); + + if (!strcmp(arg1.s, ""aps-version"")) { + if (!imparse_isnumber(arg2.s)) goto aps_extraargs; + applepushserviceargs.aps_version = atoi(arg2.s); + } + else if (!strcmp(arg1.s, ""aps-account-id"")) + buf_copy(&applepushserviceargs.aps_account_id, &arg2); + else if (!strcmp(arg1.s, ""aps-device-token"")) + buf_copy(&applepushserviceargs.aps_device_token, &arg2); + else if (!strcmp(arg1.s, ""aps-subtopic"")) + buf_copy(&applepushserviceargs.aps_subtopic, &arg2); + else + goto aps_extraargs; + } + } while (c == ' '); + + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto aps_extraargs; + + cmd_xapplepushservice(tag.s, &applepushserviceargs); + } + + else goto badcmd; + break; + + default: + badcmd: + prot_printf(imapd_out, ""%s BAD Unrecognized command\r\n"", tag.s); + eatline(imapd_in, c); + } + + /* End command timer - don't log ""idle"" commands */ + if (commandmintimer && strcmp(""idle"", cmdname)) { + double cmdtime, nettime; + const char *mboxname = index_mboxname(imapd_index); + if (!mboxname) mboxname = """"; + cmdtime_endtimer(&cmdtime, &nettime); + if (cmdtime >= commandmintimerd) { + syslog(LOG_NOTICE, ""cmdtimer: '%s' '%s' '%s' '%f' '%f' '%f'"", + imapd_userid ? imapd_userid : """", cmdname, mboxname, + cmdtime, nettime, cmdtime + nettime); + } + } + continue; + + nologin: + prot_printf(imapd_out, ""%s BAD Please login first\r\n"", tag.s); + eatline(imapd_in, c); + continue; + + nomailbox: + prot_printf(imapd_out, + ""%s BAD Please select a mailbox first\r\n"", tag.s); + eatline(imapd_in, c); + continue; + + aps_missingargs: + buf_free(&applepushserviceargs.aps_account_id); + buf_free(&applepushserviceargs.aps_device_token); + buf_free(&applepushserviceargs.aps_subtopic); + strarray_fini(&applepushserviceargs.mailboxes); + + missingargs: + prot_printf(imapd_out, + ""%s BAD Missing required argument to %s\r\n"", tag.s, cmd.s); + eatline(imapd_in, c); + continue; + + aps_extraargs: + buf_free(&applepushserviceargs.aps_account_id); + buf_free(&applepushserviceargs.aps_device_token); + buf_free(&applepushserviceargs.aps_subtopic); + strarray_fini(&applepushserviceargs.mailboxes); + + extraargs: + prot_printf(imapd_out, + ""%s BAD Unexpected extra arguments to %s\r\n"", tag.s, cmd.s); + eatline(imapd_in, c); + continue; + + badsequence: + prot_printf(imapd_out, + ""%s BAD Invalid sequence in %s\r\n"", tag.s, cmd.s); + eatline(imapd_in, c); + continue; + + badpartition: + prot_printf(imapd_out, + ""%s BAD Invalid partition name in %s\r\n"", tag.s, cmd.s); + eatline(imapd_in, c); + continue; + } + +done: + cmd_syncrestart(NULL, &reserve_list, 0); +} +",1,"static void cmdloop(void) +{ + int c; + int usinguid, havepartition, havenamespace, recursive; + static struct buf tag, cmd, arg1, arg2, arg3; + char *p, shut[MAX_MAILBOX_PATH+1], cmdname[100]; + const char *err; + const char * commandmintimer; + double commandmintimerd = 0.0; + struct sync_reserve_list *reserve_list = + sync_reserve_list_create(SYNC_MESSAGE_LIST_HASH_SIZE); + struct applepushserviceargs applepushserviceargs; + + prot_printf(imapd_out, ""* OK [CAPABILITY ""); + capa_response(CAPA_PREAUTH); + prot_printf(imapd_out, ""]""); + if (config_serverinfo) prot_printf(imapd_out, "" %s"", config_servername); + if (config_serverinfo == IMAP_ENUM_SERVERINFO_ON) { + prot_printf(imapd_out, "" Cyrus IMAP %s"", cyrus_version()); + } + prot_printf(imapd_out, "" server ready\r\n""); + + /* clear cancelled flag if present before the next command */ + cmd_cancelled(); + + motd_file(); + + /* Get command timer logging paramater. This string + * is a time in seconds. Any command that takes >= + * this time to execute is logged */ + commandmintimer = config_getstring(IMAPOPT_COMMANDMINTIMER); + cmdtime_settimer(commandmintimer ? 1 : 0); + if (commandmintimer) { + commandmintimerd = atof(commandmintimer); + } + + for (;;) { + /* Release any held index */ + index_release(imapd_index); + + /* Flush any buffered output */ + prot_flush(imapd_out); + if (backend_current) prot_flush(backend_current->out); + + /* command no longer running */ + proc_register(config_ident, imapd_clienthost, imapd_userid, index_mboxname(imapd_index), NULL); + + /* Check for shutdown file */ + if ( !imapd_userisadmin && imapd_userid && + (shutdown_file(shut, sizeof(shut)) || + userdeny(imapd_userid, config_ident, shut, sizeof(shut)))) { + for (p = shut; *p == '['; p++); /* can't have [ be first char */ + prot_printf(imapd_out, ""* BYE [ALERT] %s\r\n"", p); + telemetry_rusage(imapd_userid); + shut_down(0); + } + + signals_poll(); + + if (!proxy_check_input(protin, imapd_in, imapd_out, + backend_current ? backend_current->in : NULL, + NULL, 0)) { + /* No input from client */ + continue; + } + + /* Parse tag */ + c = getword(imapd_in, &tag); + if (c == EOF) { + if ((err = prot_error(imapd_in))!=NULL + && strcmp(err, PROT_EOF_STRING)) { + syslog(LOG_WARNING, ""%s, closing connection"", err); + prot_printf(imapd_out, ""* BYE %s\r\n"", err); + } + goto done; + } + if (c != ' ' || !imparse_isatom(tag.s) || (tag.s[0] == '*' && !tag.s[1])) { + prot_printf(imapd_out, ""* BAD Invalid tag\r\n""); + eatline(imapd_in, c); + continue; + } + + /* Parse command name */ + c = getword(imapd_in, &cmd); + if (!cmd.s[0]) { + prot_printf(imapd_out, ""%s BAD Null command\r\n"", tag.s); + eatline(imapd_in, c); + continue; + } + lcase(cmd.s); + xstrncpy(cmdname, cmd.s, 99); + cmd.s[0] = toupper((unsigned char) cmd.s[0]); + + if (config_getswitch(IMAPOPT_CHATTY)) + syslog(LOG_NOTICE, ""command: %s %s"", tag.s, cmd.s); + + proc_register(config_ident, imapd_clienthost, imapd_userid, index_mboxname(imapd_index), cmd.s); + + /* if we need to force a kick, do so */ + if (referral_kick) { + kick_mupdate(); + referral_kick = 0; + } + + if (plaintextloginalert) { + prot_printf(imapd_out, ""* OK [ALERT] %s\r\n"", + plaintextloginalert); + plaintextloginalert = NULL; + } + + /* Only Authenticate/Enable/Login/Logout/Noop/Capability/Id/Starttls + allowed when not logged in */ + if (!imapd_userid && !strchr(""AELNCIS"", cmd.s[0])) goto nologin; + + /* Start command timer */ + cmdtime_starttimer(); + + /* note that about half the commands (the common ones that don't + hit the mailboxes file) now close the mailboxes file just in + case it was open. */ + switch (cmd.s[0]) { + case 'A': + if (!strcmp(cmd.s, ""Authenticate"")) { + int haveinitresp = 0; + + if (c != ' ') goto missingargs; + c = getword(imapd_in, &arg1); + if (!imparse_isatom(arg1.s)) { + prot_printf(imapd_out, ""%s BAD Invalid authenticate mechanism\r\n"", tag.s); + eatline(imapd_in, c); + continue; + } + if (c == ' ') { + haveinitresp = 1; + c = getword(imapd_in, &arg2); + if (c == EOF) goto missingargs; + } + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + if (imapd_userid) { + prot_printf(imapd_out, ""%s BAD Already authenticated\r\n"", tag.s); + continue; + } + cmd_authenticate(tag.s, arg1.s, haveinitresp ? arg2.s : NULL); + + snmp_increment(AUTHENTICATE_COUNT, 1); + } + else if (!imapd_userid) goto nologin; + else if (!strcmp(cmd.s, ""Append"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + + cmd_append(tag.s, arg1.s, NULL); + + snmp_increment(APPEND_COUNT, 1); + } + else goto badcmd; + break; + + case 'C': + if (!strcmp(cmd.s, ""Capability"")) { + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_capability(tag.s); + + snmp_increment(CAPABILITY_COUNT, 1); + } + else if (!imapd_userid) goto nologin; +#ifdef HAVE_ZLIB + else if (!strcmp(cmd.s, ""Compress"")) { + if (c != ' ') goto missingargs; + c = getword(imapd_in, &arg1); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + cmd_compress(tag.s, arg1.s); + + snmp_increment(COMPRESS_COUNT, 1); + } +#endif /* HAVE_ZLIB */ + else if (!strcmp(cmd.s, ""Check"")) { + if (!imapd_index && !backend_current) goto nomailbox; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + cmd_noop(tag.s, cmd.s); + + snmp_increment(CHECK_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Copy"")) { + if (!imapd_index && !backend_current) goto nomailbox; + usinguid = 0; + if (c != ' ') goto missingargs; + copy: + c = getword(imapd_in, &arg1); + if (c == '\r') goto missingargs; + if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence; + c = getastring(imapd_in, imapd_out, &arg2); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + cmd_copy(tag.s, arg1.s, arg2.s, usinguid, /*ismove*/0); + + snmp_increment(COPY_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Create"")) { + struct dlist *extargs = NULL; + + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + if (c == ' ') { + c = parsecreateargs(&extargs); + if (c == EOF) goto badpartition; + } + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_create(tag.s, arg1.s, extargs, 0); + dlist_free(&extargs); + + snmp_increment(CREATE_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Close"")) { + if (!imapd_index && !backend_current) goto nomailbox; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + cmd_close(tag.s, cmd.s); + + snmp_increment(CLOSE_COUNT, 1); + } + else goto badcmd; + break; + + case 'D': + if (!strcmp(cmd.s, ""Delete"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_delete(tag.s, arg1.s, 0, 0); + + snmp_increment(DELETE_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Deleteacl"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg2); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_setacl(tag.s, arg1.s, arg2.s, NULL); + + snmp_increment(DELETEACL_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Dump"")) { + int uid_start = 0; + + if(c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if(c == ' ') { + c = getastring(imapd_in, imapd_out, &arg2); + if(!imparse_isnumber(arg2.s)) goto extraargs; + uid_start = atoi(arg2.s); + } + + if(c == '\r') c = prot_getc(imapd_in); + if(c != '\n') goto extraargs; + + cmd_dump(tag.s, arg1.s, uid_start); + /* snmp_increment(DUMP_COUNT, 1);*/ + } + else goto badcmd; + break; + + case 'E': + if (!imapd_userid) goto nologin; + else if (!strcmp(cmd.s, ""Enable"")) { + if (c != ' ') goto missingargs; + + cmd_enable(tag.s); + } + else if (!strcmp(cmd.s, ""Expunge"")) { + if (!imapd_index && !backend_current) goto nomailbox; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + cmd_expunge(tag.s, 0); + + snmp_increment(EXPUNGE_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Examine"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + prot_ungetc(c, imapd_in); + + cmd_select(tag.s, cmd.s, arg1.s); + + snmp_increment(EXAMINE_COUNT, 1); + } + else goto badcmd; + break; + + case 'F': + if (!strcmp(cmd.s, ""Fetch"")) { + if (!imapd_index && !backend_current) goto nomailbox; + usinguid = 0; + if (c != ' ') goto missingargs; + fetch: + c = getword(imapd_in, &arg1); + if (c == '\r') goto missingargs; + if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence; + + cmd_fetch(tag.s, arg1.s, usinguid); + + snmp_increment(FETCH_COUNT, 1); + } + else goto badcmd; + break; + + case 'G': + if (!strcmp(cmd.s, ""Getacl"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_getacl(tag.s, arg1.s); + + snmp_increment(GETACL_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Getannotation"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + + cmd_getannotation(tag.s, arg1.s); + + snmp_increment(GETANNOTATION_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Getmetadata"")) { + if (c != ' ') goto missingargs; + + cmd_getmetadata(tag.s); + + snmp_increment(GETANNOTATION_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Getquota"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_getquota(tag.s, arg1.s); + + snmp_increment(GETQUOTA_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Getquotaroot"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_getquotaroot(tag.s, arg1.s); + + snmp_increment(GETQUOTAROOT_COUNT, 1); + } +#ifdef HAVE_SSL + else if (!strcmp(cmd.s, ""Genurlauth"")) { + if (c != ' ') goto missingargs; + + cmd_genurlauth(tag.s); + /* snmp_increment(GENURLAUTH_COUNT, 1);*/ + } +#endif + else goto badcmd; + break; + + case 'I': + if (!strcmp(cmd.s, ""Id"")) { + if (c != ' ') goto missingargs; + cmd_id(tag.s); + + snmp_increment(ID_COUNT, 1); + } + else if (!imapd_userid) goto nologin; + else if (!strcmp(cmd.s, ""Idle"") && idle_enabled()) { + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_idle(tag.s); + + snmp_increment(IDLE_COUNT, 1); + } + else goto badcmd; + break; + + case 'L': + if (!strcmp(cmd.s, ""Login"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if(c != ' ') goto missingargs; + + cmd_login(tag.s, arg1.s); + + snmp_increment(LOGIN_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Logout"")) { + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + snmp_increment(LOGOUT_COUNT, 1); + + /* force any responses from our selected backend */ + if (backend_current) imapd_check(NULL, 0); + + prot_printf(imapd_out, ""* BYE %s\r\n"", + error_message(IMAP_BYE_LOGOUT)); + prot_printf(imapd_out, ""%s OK %s\r\n"", tag.s, + error_message(IMAP_OK_COMPLETED)); + + if (imapd_userid && *imapd_userid) { + telemetry_rusage(imapd_userid); + } + + goto done; + } + else if (!imapd_userid) goto nologin; + else if (!strcmp(cmd.s, ""List"")) { + struct listargs listargs; + + if (c != ' ') goto missingargs; + + memset(&listargs, 0, sizeof(struct listargs)); + listargs.ret = LIST_RET_CHILDREN; + getlistargs(tag.s, &listargs); + if (listargs.pat.count) cmd_list(tag.s, &listargs); + + snmp_increment(LIST_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Lsub"")) { + struct listargs listargs; + + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg2); + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + memset(&listargs, 0, sizeof(struct listargs)); + listargs.cmd = LIST_CMD_LSUB; + listargs.sel = LIST_SEL_SUBSCRIBED; + if (!strcasecmpsafe(imapd_magicplus, ""+dav"")) + listargs.sel |= LIST_SEL_DAV; + listargs.ref = arg1.s; + strarray_append(&listargs.pat, arg2.s); + + cmd_list(tag.s, &listargs); + + snmp_increment(LSUB_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Listrights"")) { + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg2); + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_listrights(tag.s, arg1.s, arg2.s); + + snmp_increment(LISTRIGHTS_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Localappend"")) { + /* create a local-only mailbox */ + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg2); + if (c != ' ') goto missingargs; + + cmd_append(tag.s, arg1.s, *arg2.s ? arg2.s : NULL); + + snmp_increment(APPEND_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Localcreate"")) { + /* create a local-only mailbox */ + struct dlist *extargs = NULL; + + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + if (c == ' ') { + c = parsecreateargs(&extargs); + if (c == EOF) goto badpartition; + } + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_create(tag.s, arg1.s, extargs, 1); + dlist_free(&extargs); + + /* xxxx snmp_increment(CREATE_COUNT, 1); */ + } + else if (!strcmp(cmd.s, ""Localdelete"")) { + /* delete a mailbox locally only */ + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_delete(tag.s, arg1.s, 1, 1); + + /* xxxx snmp_increment(DELETE_COUNT, 1); */ + } + else goto badcmd; + break; + + case 'M': + if (!strcmp(cmd.s, ""Myrights"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_myrights(tag.s, arg1.s); + + /* xxxx snmp_increment(MYRIGHTS_COUNT, 1); */ + } + else if (!strcmp(cmd.s, ""Mupdatepush"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if(c == EOF) goto missingargs; + if(c == '\r') c = prot_getc(imapd_in); + if(c != '\n') goto extraargs; + cmd_mupdatepush(tag.s, arg1.s); + + /* xxxx snmp_increment(MUPDATEPUSH_COUNT, 1); */ + } + else if (!strcmp(cmd.s, ""Move"")) { + if (!imapd_index && !backend_current) goto nomailbox; + usinguid = 0; + if (c != ' ') goto missingargs; + move: + c = getword(imapd_in, &arg1); + if (c == '\r') goto missingargs; + if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence; + c = getastring(imapd_in, imapd_out, &arg2); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + cmd_copy(tag.s, arg1.s, arg2.s, usinguid, /*ismove*/1); + + snmp_increment(COPY_COUNT, 1); + } else goto badcmd; + break; + + case 'N': + if (!strcmp(cmd.s, ""Noop"")) { + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + cmd_noop(tag.s, cmd.s); + + /* xxxx snmp_increment(NOOP_COUNT, 1); */ + } + else if (!imapd_userid) goto nologin; + else if (!strcmp(cmd.s, ""Namespace"")) { + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_namespace(tag.s); + + /* xxxx snmp_increment(NAMESPACE_COUNT, 1); */ + } + else goto badcmd; + break; + + case 'R': + if (!strcmp(cmd.s, ""Rename"")) { + havepartition = 0; + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg2); + if (c == EOF) goto missingargs; + if (c == ' ') { + havepartition = 1; + c = getword(imapd_in, &arg3); + if (!imparse_isatom(arg3.s)) goto badpartition; + } + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_rename(tag.s, arg1.s, arg2.s, havepartition ? arg3.s : 0); + + /* xxxx snmp_increment(RENAME_COUNT, 1); */ + } else if(!strcmp(cmd.s, ""Reconstruct"")) { + recursive = 0; + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if(c == ' ') { + /* Optional RECURSEIVE argument */ + c = getword(imapd_in, &arg2); + if(!imparse_isatom(arg2.s)) + goto extraargs; + else if(!strcasecmp(arg2.s, ""RECURSIVE"")) + recursive = 1; + else + goto extraargs; + } + if(c == '\r') c = prot_getc(imapd_in); + if(c != '\n') goto extraargs; + cmd_reconstruct(tag.s, arg1.s, recursive); + + /* snmp_increment(RECONSTRUCT_COUNT, 1); */ + } + else if (!strcmp(cmd.s, ""Rlist"")) { + struct listargs listargs; + + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg2); + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + memset(&listargs, 0, sizeof(struct listargs)); + listargs.sel = LIST_SEL_REMOTE; + listargs.ret = LIST_RET_CHILDREN; + listargs.ref = arg1.s; + strarray_append(&listargs.pat, arg2.s); + + cmd_list(tag.s, &listargs); + +/* snmp_increment(LIST_COUNT, 1); */ + } + else if (!strcmp(cmd.s, ""Rlsub"")) { + struct listargs listargs; + + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg2); + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + memset(&listargs, 0, sizeof(struct listargs)); + listargs.cmd = LIST_CMD_LSUB; + listargs.sel = LIST_SEL_REMOTE | LIST_SEL_SUBSCRIBED; + listargs.ref = arg1.s; + strarray_append(&listargs.pat, arg2.s); + + cmd_list(tag.s, &listargs); + +/* snmp_increment(LSUB_COUNT, 1); */ + } +#ifdef HAVE_SSL + else if (!strcmp(cmd.s, ""Resetkey"")) { + int have_mbox = 0, have_mech = 0; + + if (c == ' ') { + have_mbox = 1; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + if (c == ' ') { + have_mech = 1; + c = getword(imapd_in, &arg2); + } + } + + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_resetkey(tag.s, have_mbox ? arg1.s : 0, + have_mech ? arg2.s : 0); + /* snmp_increment(RESETKEY_COUNT, 1);*/ + } +#endif + else goto badcmd; + break; + + case 'S': + if (!strcmp(cmd.s, ""Starttls"")) { + if (!tls_enabled()) { + /* we don't support starttls */ + goto badcmd; + } + + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + /* XXX discard any input pipelined after STARTTLS */ + prot_flush(imapd_in); + + /* if we've already done SASL fail */ + if (imapd_userid != NULL) { + prot_printf(imapd_out, + ""%s BAD Can't Starttls after authentication\r\n"", tag.s); + continue; + } + + /* if we've already done COMPRESS fail */ + if (imapd_compress_done == 1) { + prot_printf(imapd_out, + ""%s BAD Can't Starttls after Compress\r\n"", tag.s); + continue; + } + + /* check if already did a successful tls */ + if (imapd_starttls_done == 1) { + prot_printf(imapd_out, + ""%s BAD Already did a successful Starttls\r\n"", + tag.s); + continue; + } + cmd_starttls(tag.s, 0); + + snmp_increment(STARTTLS_COUNT, 1); + continue; + } + if (!imapd_userid) { + goto nologin; + } else if (!strcmp(cmd.s, ""Store"")) { + if (!imapd_index && !backend_current) goto nomailbox; + usinguid = 0; + if (c != ' ') goto missingargs; + store: + c = getword(imapd_in, &arg1); + if (c != ' ' || !imparse_issequence(arg1.s)) goto badsequence; + + cmd_store(tag.s, arg1.s, usinguid); + + snmp_increment(STORE_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Select"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + prot_ungetc(c, imapd_in); + + cmd_select(tag.s, cmd.s, arg1.s); + + snmp_increment(SELECT_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Search"")) { + if (!imapd_index && !backend_current) goto nomailbox; + usinguid = 0; + if (c != ' ') goto missingargs; + search: + + cmd_search(tag.s, usinguid); + + snmp_increment(SEARCH_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Subscribe"")) { + if (c != ' ') goto missingargs; + havenamespace = 0; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == ' ') { + havenamespace = 1; + c = getastring(imapd_in, imapd_out, &arg2); + } + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + if (havenamespace) { + cmd_changesub(tag.s, arg1.s, arg2.s, 1); + } + else { + cmd_changesub(tag.s, (char *)0, arg1.s, 1); + } + snmp_increment(SUBSCRIBE_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Setacl"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg2); + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg3); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_setacl(tag.s, arg1.s, arg2.s, arg3.s); + + snmp_increment(SETACL_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Setannotation"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + + cmd_setannotation(tag.s, arg1.s); + + snmp_increment(SETANNOTATION_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Setmetadata"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + + cmd_setmetadata(tag.s, arg1.s); + + snmp_increment(SETANNOTATION_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Setquota"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + cmd_setquota(tag.s, arg1.s); + + snmp_increment(SETQUOTA_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Sort"")) { + if (!imapd_index && !backend_current) goto nomailbox; + usinguid = 0; + if (c != ' ') goto missingargs; + sort: + cmd_sort(tag.s, usinguid); + + snmp_increment(SORT_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Status"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + cmd_status(tag.s, arg1.s); + + snmp_increment(STATUS_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Scan"")) { + struct listargs listargs; + + c = getastring(imapd_in, imapd_out, &arg1); + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg2); + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg3); + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + memset(&listargs, 0, sizeof(struct listargs)); + listargs.ref = arg1.s; + strarray_append(&listargs.pat, arg2.s); + listargs.scan = arg3.s; + + cmd_list(tag.s, &listargs); + + snmp_increment(SCAN_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Syncapply"")) { + if (!imapd_userisadmin) goto badcmd; + + struct dlist *kl = sync_parseline(imapd_in); + + if (kl) { + cmd_syncapply(tag.s, kl, reserve_list); + dlist_free(&kl); + } + else goto extraargs; + } + else if (!strcmp(cmd.s, ""Syncget"")) { + if (!imapd_userisadmin) goto badcmd; + + struct dlist *kl = sync_parseline(imapd_in); + + if (kl) { + cmd_syncget(tag.s, kl); + dlist_free(&kl); + } + else goto extraargs; + } + else if (!strcmp(cmd.s, ""Syncrestart"")) { + if (!imapd_userisadmin) goto badcmd; + + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + /* just clear the GUID cache */ + cmd_syncrestart(tag.s, &reserve_list, 1); + } + else if (!strcmp(cmd.s, ""Syncrestore"")) { + if (!imapd_userisadmin) goto badcmd; + + struct dlist *kl = sync_parseline(imapd_in); + + if (kl) { + cmd_syncrestore(tag.s, kl, reserve_list); + dlist_free(&kl); + } + else goto extraargs; + } + else goto badcmd; + break; + + case 'T': + if (!strcmp(cmd.s, ""Thread"")) { + if (!imapd_index && !backend_current) goto nomailbox; + usinguid = 0; + if (c != ' ') goto missingargs; + thread: + cmd_thread(tag.s, usinguid); + + snmp_increment(THREAD_COUNT, 1); + } + else goto badcmd; + break; + + case 'U': + if (!strcmp(cmd.s, ""Uid"")) { + if (!imapd_index && !backend_current) goto nomailbox; + usinguid = 1; + if (c != ' ') goto missingargs; + c = getword(imapd_in, &arg1); + if (c != ' ') goto missingargs; + lcase(arg1.s); + xstrncpy(cmdname, arg1.s, 99); + if (!strcmp(arg1.s, ""fetch"")) { + goto fetch; + } + else if (!strcmp(arg1.s, ""store"")) { + goto store; + } + else if (!strcmp(arg1.s, ""search"")) { + goto search; + } + else if (!strcmp(arg1.s, ""sort"")) { + goto sort; + } + else if (!strcmp(arg1.s, ""thread"")) { + goto thread; + } + else if (!strcmp(arg1.s, ""copy"")) { + goto copy; + } + else if (!strcmp(arg1.s, ""move"")) { + goto move; + } + else if (!strcmp(arg1.s, ""xmove"")) { + goto move; + } + else if (!strcmp(arg1.s, ""expunge"")) { + c = getword(imapd_in, &arg1); + if (!imparse_issequence(arg1.s)) goto badsequence; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_expunge(tag.s, arg1.s); + + snmp_increment(EXPUNGE_COUNT, 1); + } + else if (!strcmp(arg1.s, ""xrunannotator"")) { + goto xrunannotator; + } + else { + prot_printf(imapd_out, ""%s BAD Unrecognized UID subcommand\r\n"", tag.s); + eatline(imapd_in, c); + } + } + else if (!strcmp(cmd.s, ""Unsubscribe"")) { + if (c != ' ') goto missingargs; + havenamespace = 0; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == ' ') { + havenamespace = 1; + c = getastring(imapd_in, imapd_out, &arg2); + } + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + if (havenamespace) { + cmd_changesub(tag.s, arg1.s, arg2.s, 0); + } + else { + cmd_changesub(tag.s, (char *)0, arg1.s, 0); + } + + snmp_increment(UNSUBSCRIBE_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Unselect"")) { + if (!imapd_index && !backend_current) goto nomailbox; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + cmd_close(tag.s, cmd.s); + + snmp_increment(UNSELECT_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Undump"")) { + if(c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + + /* we want to get a list at this point */ + if(c != ' ') goto missingargs; + + cmd_undump(tag.s, arg1.s); + /* snmp_increment(UNDUMP_COUNT, 1);*/ + } +#ifdef HAVE_SSL + else if (!strcmp(cmd.s, ""Urlfetch"")) { + if (c != ' ') goto missingargs; + + cmd_urlfetch(tag.s); + /* snmp_increment(URLFETCH_COUNT, 1);*/ + } +#endif + else goto badcmd; + break; + + case 'X': + if (!strcmp(cmd.s, ""Xbackup"")) { + int havechannel = 0; + + if (!config_getswitch(IMAPOPT_XBACKUP_ENABLED)) + goto badcmd; + + /* user */ + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + + /* channel */ + if (c == ' ') { + havechannel = 1; + c = getword(imapd_in, &arg2); + if (c == EOF) goto missingargs; + } + + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + cmd_xbackup(tag.s, arg1.s, havechannel ? arg2.s : NULL); + + } + else if (!strcmp(cmd.s, ""Xconvfetch"")) { + cmd_xconvfetch(tag.s); + + } + else if (!strcmp(cmd.s, ""Xconvmultisort"")) { + if (c != ' ') goto missingargs; + if (!imapd_index && !backend_current) goto nomailbox; + cmd_xconvmultisort(tag.s); + + } + else if (!strcmp(cmd.s, ""Xconvsort"")) { + if (c != ' ') goto missingargs; + if (!imapd_index && !backend_current) goto nomailbox; + cmd_xconvsort(tag.s, 0); + + } + else if (!strcmp(cmd.s, ""Xconvupdates"")) { + if (c != ' ') goto missingargs; + if (!imapd_index && !backend_current) goto nomailbox; + cmd_xconvsort(tag.s, 1); + + } + else if (!strcmp(cmd.s, ""Xfer"")) { + int havepartition = 0; + + /* Mailbox */ + if(c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + + /* Dest Server */ + if(c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg2); + + if(c == ' ') { + /* Dest Partition */ + c = getastring(imapd_in, imapd_out, &arg3); + if (!imparse_isatom(arg3.s)) goto badpartition; + havepartition = 1; + } + + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + cmd_xfer(tag.s, arg1.s, arg2.s, + (havepartition ? arg3.s : NULL)); + /* snmp_increment(XFER_COUNT, 1);*/ + } + else if (!strcmp(cmd.s, ""Xconvmeta"")) { + cmd_xconvmeta(tag.s); + } + else if (!strcmp(cmd.s, ""Xlist"")) { + struct listargs listargs; + + if (c != ' ') goto missingargs; + + memset(&listargs, 0, sizeof(struct listargs)); + listargs.cmd = LIST_CMD_XLIST; + listargs.ret = LIST_RET_CHILDREN | LIST_RET_SPECIALUSE; + getlistargs(tag.s, &listargs); + if (listargs.pat.count) cmd_list(tag.s, &listargs); + + snmp_increment(LIST_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Xmove"")) { + if (!imapd_index && !backend_current) goto nomailbox; + usinguid = 0; + if (c != ' ') goto missingargs; + goto move; + } + else if (!strcmp(cmd.s, ""Xrunannotator"")) { + if (!imapd_index && !backend_current) goto nomailbox; + usinguid = 0; + if (c != ' ') goto missingargs; + xrunannotator: + c = getword(imapd_in, &arg1); + if (!arg1.len || !imparse_issequence(arg1.s)) goto badsequence; + cmd_xrunannotator(tag.s, arg1.s, usinguid); + } + else if (!strcmp(cmd.s, ""Xsnippets"")) { + if (c != ' ') goto missingargs; + if (!imapd_index && !backend_current) goto nomailbox; + cmd_xsnippets(tag.s); + + } + else if (!strcmp(cmd.s, ""Xstats"")) { + cmd_xstats(tag.s, c); + } + else if (!strcmp(cmd.s, ""Xwarmup"")) { + /* XWARMUP doesn't need a mailbox to be selected */ + if (c != ' ') goto missingargs; + cmd_xwarmup(tag.s); + } + else if (!strcmp(cmd.s, ""Xkillmy"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_xkillmy(tag.s, arg1.s); + } + else if (!strcmp(cmd.s, ""Xforever"")) { + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_xforever(tag.s); + } + else if (!strcmp(cmd.s, ""Xmeid"")) { + if (c != ' ') goto missingargs; + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto missingargs; + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + cmd_xmeid(tag.s, arg1.s); + } + + else if (apns_enabled && !strcmp(cmd.s, ""Xapplepushservice"")) { + if (c != ' ') goto missingargs; + + memset(&applepushserviceargs, 0, sizeof(struct applepushserviceargs)); + + do { + c = getastring(imapd_in, imapd_out, &arg1); + if (c == EOF) goto aps_missingargs; + + if (!strcmp(arg1.s, ""mailboxes"")) { + c = prot_getc(imapd_in); + if (c != '(') + goto aps_missingargs; + + c = prot_getc(imapd_in); + if (c != ')') { + prot_ungetc(c, imapd_in); + do { + c = getastring(imapd_in, imapd_out, &arg2); + if (c == EOF) break; + strarray_push(&applepushserviceargs.mailboxes, arg2.s); + } while (c == ' '); + } + + if (c != ')') + goto aps_missingargs; + c = prot_getc(imapd_in); + } + + else { + c = getastring(imapd_in, imapd_out, &arg2); + + if (!strcmp(arg1.s, ""aps-version"")) { + if (!imparse_isnumber(arg2.s)) goto aps_extraargs; + applepushserviceargs.aps_version = atoi(arg2.s); + } + else if (!strcmp(arg1.s, ""aps-account-id"")) + buf_copy(&applepushserviceargs.aps_account_id, &arg2); + else if (!strcmp(arg1.s, ""aps-device-token"")) + buf_copy(&applepushserviceargs.aps_device_token, &arg2); + else if (!strcmp(arg1.s, ""aps-subtopic"")) + buf_copy(&applepushserviceargs.aps_subtopic, &arg2); + else + goto aps_extraargs; + } + } while (c == ' '); + + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto aps_extraargs; + + cmd_xapplepushservice(tag.s, &applepushserviceargs); + } + + else goto badcmd; + break; + + default: + badcmd: + prot_printf(imapd_out, ""%s BAD Unrecognized command\r\n"", tag.s); + eatline(imapd_in, c); + } + + /* End command timer - don't log ""idle"" commands */ + if (commandmintimer && strcmp(""idle"", cmdname)) { + double cmdtime, nettime; + const char *mboxname = index_mboxname(imapd_index); + if (!mboxname) mboxname = """"; + cmdtime_endtimer(&cmdtime, &nettime); + if (cmdtime >= commandmintimerd) { + syslog(LOG_NOTICE, ""cmdtimer: '%s' '%s' '%s' '%f' '%f' '%f'"", + imapd_userid ? imapd_userid : """", cmdname, mboxname, + cmdtime, nettime, cmdtime + nettime); + } + } + continue; + + nologin: + prot_printf(imapd_out, ""%s BAD Please login first\r\n"", tag.s); + eatline(imapd_in, c); + continue; + + nomailbox: + prot_printf(imapd_out, + ""%s BAD Please select a mailbox first\r\n"", tag.s); + eatline(imapd_in, c); + continue; + + aps_missingargs: + buf_free(&applepushserviceargs.aps_account_id); + buf_free(&applepushserviceargs.aps_device_token); + buf_free(&applepushserviceargs.aps_subtopic); + strarray_fini(&applepushserviceargs.mailboxes); + + missingargs: + prot_printf(imapd_out, + ""%s BAD Missing required argument to %s\r\n"", tag.s, cmd.s); + eatline(imapd_in, c); + continue; + + aps_extraargs: + buf_free(&applepushserviceargs.aps_account_id); + buf_free(&applepushserviceargs.aps_device_token); + buf_free(&applepushserviceargs.aps_subtopic); + strarray_fini(&applepushserviceargs.mailboxes); + + extraargs: + prot_printf(imapd_out, + ""%s BAD Unexpected extra arguments to %s\r\n"", tag.s, cmd.s); + eatline(imapd_in, c); + continue; + + badsequence: + prot_printf(imapd_out, + ""%s BAD Invalid sequence in %s\r\n"", tag.s, cmd.s); + eatline(imapd_in, c); + continue; + + badpartition: + prot_printf(imapd_out, + ""%s BAD Invalid partition name in %s\r\n"", tag.s, cmd.s); + eatline(imapd_in, c); + continue; + } + +done: + cmd_syncrestart(NULL, &reserve_list, 0); +} +","@@ -2062,6 +2062,8 @@ static void cmdloop(void) + snmp_increment(SCAN_COUNT, 1); + } + else if (!strcmp(cmd.s, ""Syncapply"")) { ++ if (!imapd_userisadmin) goto badcmd; ++ + struct dlist *kl = sync_parseline(imapd_in); + + if (kl) { +@@ -2071,6 +2073,8 @@ static void cmdloop(void) + else goto extraargs; + } + else if (!strcmp(cmd.s, ""Syncget"")) { ++ if (!imapd_userisadmin) goto badcmd; ++ + struct dlist *kl = sync_parseline(imapd_in); + + if (kl) { +@@ -2080,13 +2084,17 @@ static void cmdloop(void) + else goto extraargs; + } + else if (!strcmp(cmd.s, ""Syncrestart"")) { ++ if (!imapd_userisadmin) goto badcmd; ++ + if (c == '\r') c = prot_getc(imapd_in); + if (c != '\n') goto extraargs; + + /* just clear the GUID cache */ + cmd_syncrestart(tag.s, &reserve_list, 1); + } + else if (!strcmp(cmd.s, ""Syncrestore"")) { ++ if (!imapd_userisadmin) goto badcmd; ++ + struct dlist *kl = sync_parseline(imapd_in); + + if (kl) {",11262,11593,15000 diff --git a/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_11000_to_15000.pkl b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_11000_to_15000.pkl new file mode 100644 index 0000000000000000000000000000000000000000..b3b834b858fe67aa6359fa98079524f5fa35799c --- /dev/null +++ b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_11000_to_15000.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:658d1ffcfe1b6ba422766ef034cf43645047948a1427e723b061c746a40dda8e +size 191494 diff --git a/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_2048_to_4096.csv b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_2048_to_4096.csv new file mode 100644 index 0000000000000000000000000000000000000000..1bebdf7d102bdc621e125cc50d5b4395bc977a18 --- /dev/null +++ b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_2048_to_4096.csv @@ -0,0 +1,90914 @@ +idx,func_before,vul,func_after,patch,code_token_length,total_token_length,max_tokens_setting +17808,"int ssl3_client_hello(SSL *s) +{ + unsigned char *buf; + unsigned char *p, *d; + int i; + unsigned long l; + int al = 0; +#ifndef OPENSSL_NO_COMP + int j; + SSL_COMP *comp; +#endif + + buf = (unsigned char *)s->init_buf->data; + if (s->state == SSL3_ST_CW_CLNT_HELLO_A) { + SSL_SESSION *sess = s->session; + if ((sess == NULL) || + (sess->ssl_version != s->version) || + !sess->session_id_length || (sess->not_resumable)) { + if (!ssl_get_new_session(s, 0)) + goto err; + } + if (s->method->version == DTLS_ANY_VERSION) { + /* Determine which DTLS version to use */ + int options = s->options; + /* If DTLS 1.2 disabled correct the version number */ + if (options & SSL_OP_NO_DTLSv1_2) { + if (tls1_suiteb(s)) { + SSLerr(SSL_F_SSL3_CLIENT_HELLO, + SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE); + goto err; + } + /* + * Disabling all versions is silly: return an error. + */ + if (options & SSL_OP_NO_DTLSv1) { + SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_WRONG_SSL_VERSION); + goto err; + } + /* + * Update method so we don't use any DTLS 1.2 features. + */ + s->method = DTLSv1_client_method(); + s->version = DTLS1_VERSION; + } else { + /* + * We only support one version: update method + */ + if (options & SSL_OP_NO_DTLSv1) + s->method = DTLSv1_2_client_method(); + s->version = DTLS1_2_VERSION; + } + s->client_version = s->version; + } + /* else use the pre-loaded session */ + + p = s->s3->client_random; + + /* + * for DTLS if client_random is initialized, reuse it, we are + * required to use same upon reply to HelloVerify + */ + if (SSL_IS_DTLS(s)) { + size_t idx; + i = 1; + for (idx = 0; idx < sizeof(s->s3->client_random); idx++) { + if (p[idx]) { + i = 0; + break; + } + } + } else + i = 1; + + if (i) + ssl_fill_hello_random(s, 0, p, sizeof(s->s3->client_random)); + + /* Do the message type and length last */ + d = p = ssl_handshake_start(s); + /*- + * version indicates the negotiated version: for example from + * an SSLv2/v3 compatible client hello). The client_version + * field is the maximum version we permit and it is also + * used in RSA encrypted premaster secrets. Some servers can + * choke if we initially report a higher version then + * renegotiate to a lower one in the premaster secret. This + * didn't happen with TLS 1.0 as most servers supported it + * but it can with TLS 1.1 or later if the server only supports + * 1.0. + * + * Possible scenario with previous logic: + * 1. Client hello indicates TLS 1.2 + * 2. Server hello says TLS 1.0 + * 3. RSA encrypted premaster secret uses 1.2. + * 4. Handhaked proceeds using TLS 1.0. + * 5. Server sends hello request to renegotiate. + * 6. Client hello indicates TLS v1.0 as we now + * know that is maximum server supports. + * 7. Server chokes on RSA encrypted premaster secret + * containing version 1.0. + * + * For interoperability it should be OK to always use the + * maximum version we support in client hello and then rely + * on the checking of version to ensure the servers isn't + * being inconsistent: for example initially negotiating with + * TLS 1.0 and renegotiating with TLS 1.2. We do this by using + * client_version in client hello and not resetting it to + * the negotiated version. + */ + *(p++) = s->client_version >> 8; + *(p++) = s->client_version & 0xff; + + /* Random stuff */ + memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE); + p += SSL3_RANDOM_SIZE; + + /* Session ID */ + if (s->new_session) + i = 0; + else + i = s->session->session_id_length; + *(p++) = i; + if (i != 0) { + if (i > (int)sizeof(s->session->session_id)) { + SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); + goto err; + } + memcpy(p, s->session->session_id, i); + p += i; + } + + /* cookie stuff for DTLS */ + if (SSL_IS_DTLS(s)) { + if (s->d1->cookie_len > sizeof(s->d1->cookie)) { + SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); + goto err; + } + *(p++) = s->d1->cookie_len; + memcpy(p, s->d1->cookie, s->d1->cookie_len); + p += s->d1->cookie_len; + } + + /* Ciphers supported */ + i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &(p[2]), 0); + if (i == 0) { + SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_NO_CIPHERS_AVAILABLE); + goto err; + } +#ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH + /* + * Some servers hang if client hello > 256 bytes as hack workaround + * chop number of supported ciphers to keep it well below this if we + * use TLS v1.2 + */ + if (TLS1_get_version(s) >= TLS1_2_VERSION + && i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH) + i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1; +#endif + s2n(i, p); + p += i; + + /* COMPRESSION */ +#ifdef OPENSSL_NO_COMP + *(p++) = 1; +#else + + if (!ssl_allow_compression(s) || !s->ctx->comp_methods) + j = 0; + else + j = sk_SSL_COMP_num(s->ctx->comp_methods); + *(p++) = 1 + j; + for (i = 0; i < j; i++) { + comp = sk_SSL_COMP_value(s->ctx->comp_methods, i); + *(p++) = comp->id; + } +#endif + *(p++) = 0; /* Add the NULL method */ + +#ifndef OPENSSL_NO_TLSEXT + /* TLS extensions */ + if (ssl_prepare_clienthello_tlsext(s) <= 0) { + SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT); + goto err; + } + if ((p = + ssl_add_clienthello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH, + &al)) == NULL) { + ssl3_send_alert(s, SSL3_AL_FATAL, al); + SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); + goto err; + } +#endif + + l = p - d; + ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l); + s->state = SSL3_ST_CW_CLNT_HELLO_B; + } + + /* SSL3_ST_CW_CLNT_HELLO_B */ + return ssl_do_write(s); + err: + return (-1); +} +",1,"int ssl3_client_hello(SSL *s) +{ + unsigned char *buf; + unsigned char *p, *d; + int i; + unsigned long l; + int al = 0; +#ifndef OPENSSL_NO_COMP + int j; + SSL_COMP *comp; +#endif + + buf = (unsigned char *)s->init_buf->data; + if (s->state == SSL3_ST_CW_CLNT_HELLO_A) { + SSL_SESSION *sess = s->session; + if ((sess == NULL) || + (sess->ssl_version != s->version) || + !sess->session_id_length || (sess->not_resumable)) { + if (!ssl_get_new_session(s, 0)) + goto err; + } + if (s->method->version == DTLS_ANY_VERSION) { + /* Determine which DTLS version to use */ + int options = s->options; + /* If DTLS 1.2 disabled correct the version number */ + if (options & SSL_OP_NO_DTLSv1_2) { + if (tls1_suiteb(s)) { + SSLerr(SSL_F_SSL3_CLIENT_HELLO, + SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE); + goto err; + } + /* + * Disabling all versions is silly: return an error. + */ + if (options & SSL_OP_NO_DTLSv1) { + SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_WRONG_SSL_VERSION); + goto err; + } + /* + * Update method so we don't use any DTLS 1.2 features. + */ + s->method = DTLSv1_client_method(); + s->version = DTLS1_VERSION; + } else { + /* + * We only support one version: update method + */ + if (options & SSL_OP_NO_DTLSv1) + s->method = DTLSv1_2_client_method(); + s->version = DTLS1_2_VERSION; + } + s->client_version = s->version; + } + /* else use the pre-loaded session */ + + p = s->s3->client_random; + + /* + * for DTLS if client_random is initialized, reuse it, we are + * required to use same upon reply to HelloVerify + */ + if (SSL_IS_DTLS(s)) { + size_t idx; + i = 1; + for (idx = 0; idx < sizeof(s->s3->client_random); idx++) { + if (p[idx]) { + i = 0; + break; + } + } + } else + i = 1; + + if (i && ssl_fill_hello_random(s, 0, p, + sizeof(s->s3->client_random)) <= 0) + goto err; + + /* Do the message type and length last */ + d = p = ssl_handshake_start(s); + /*- + * version indicates the negotiated version: for example from + * an SSLv2/v3 compatible client hello). The client_version + * field is the maximum version we permit and it is also + * used in RSA encrypted premaster secrets. Some servers can + * choke if we initially report a higher version then + * renegotiate to a lower one in the premaster secret. This + * didn't happen with TLS 1.0 as most servers supported it + * but it can with TLS 1.1 or later if the server only supports + * 1.0. + * + * Possible scenario with previous logic: + * 1. Client hello indicates TLS 1.2 + * 2. Server hello says TLS 1.0 + * 3. RSA encrypted premaster secret uses 1.2. + * 4. Handhaked proceeds using TLS 1.0. + * 5. Server sends hello request to renegotiate. + * 6. Client hello indicates TLS v1.0 as we now + * know that is maximum server supports. + * 7. Server chokes on RSA encrypted premaster secret + * containing version 1.0. + * + * For interoperability it should be OK to always use the + * maximum version we support in client hello and then rely + * on the checking of version to ensure the servers isn't + * being inconsistent: for example initially negotiating with + * TLS 1.0 and renegotiating with TLS 1.2. We do this by using + * client_version in client hello and not resetting it to + * the negotiated version. + */ + *(p++) = s->client_version >> 8; + *(p++) = s->client_version & 0xff; + + /* Random stuff */ + memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE); + p += SSL3_RANDOM_SIZE; + + /* Session ID */ + if (s->new_session) + i = 0; + else + i = s->session->session_id_length; + *(p++) = i; + if (i != 0) { + if (i > (int)sizeof(s->session->session_id)) { + SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); + goto err; + } + memcpy(p, s->session->session_id, i); + p += i; + } + + /* cookie stuff for DTLS */ + if (SSL_IS_DTLS(s)) { + if (s->d1->cookie_len > sizeof(s->d1->cookie)) { + SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); + goto err; + } + *(p++) = s->d1->cookie_len; + memcpy(p, s->d1->cookie, s->d1->cookie_len); + p += s->d1->cookie_len; + } + + /* Ciphers supported */ + i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &(p[2]), 0); + if (i == 0) { + SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_NO_CIPHERS_AVAILABLE); + goto err; + } +#ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH + /* + * Some servers hang if client hello > 256 bytes as hack workaround + * chop number of supported ciphers to keep it well below this if we + * use TLS v1.2 + */ + if (TLS1_get_version(s) >= TLS1_2_VERSION + && i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH) + i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1; +#endif + s2n(i, p); + p += i; + + /* COMPRESSION */ +#ifdef OPENSSL_NO_COMP + *(p++) = 1; +#else + + if (!ssl_allow_compression(s) || !s->ctx->comp_methods) + j = 0; + else + j = sk_SSL_COMP_num(s->ctx->comp_methods); + *(p++) = 1 + j; + for (i = 0; i < j; i++) { + comp = sk_SSL_COMP_value(s->ctx->comp_methods, i); + *(p++) = comp->id; + } +#endif + *(p++) = 0; /* Add the NULL method */ + +#ifndef OPENSSL_NO_TLSEXT + /* TLS extensions */ + if (ssl_prepare_clienthello_tlsext(s) <= 0) { + SSLerr(SSL_F_SSL3_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT); + goto err; + } + if ((p = + ssl_add_clienthello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH, + &al)) == NULL) { + ssl3_send_alert(s, SSL3_AL_FATAL, al); + SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR); + goto err; + } +#endif + + l = p - d; + ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l); + s->state = SSL3_ST_CW_CLNT_HELLO_B; + } + + /* SSL3_ST_CW_CLNT_HELLO_B */ + return ssl_do_write(s); + err: + return (-1); +} +","@@ -719,8 +719,9 @@ int ssl3_client_hello(SSL *s) + } else + i = 1; + +- if (i) +- ssl_fill_hello_random(s, 0, p, sizeof(s->s3->client_random)); ++ if (i && ssl_fill_hello_random(s, 0, p, ++ sizeof(s->s3->client_random)) <= 0) ++ goto err; + + /* Do the message type and length last */ + d = p = ssl_handshake_start(s);",1773,2104,4096 +1011,"void http_msg_analyzer(struct http_msg *msg, struct hdr_idx *idx) +{ + enum ht_state state; /* updated only when leaving the FSM */ + register char *ptr, *end; /* request pointers, to avoid dereferences */ + struct buffer *buf; + + state = msg->msg_state; + buf = msg->chn->buf; + ptr = buf->p + msg->next; + end = buf->p + buf->i; + + if (unlikely(ptr >= end)) + goto http_msg_ood; + + switch (state) { + /* + * First, states that are specific to the response only. + * We check them first so that request and headers are + * closer to each other (accessed more often). + */ + case HTTP_MSG_RPBEFORE: + http_msg_rpbefore: + if (likely(HTTP_IS_TOKEN(*ptr))) { + /* we have a start of message, but we have to check + * first if we need to remove some CRLF. We can only + * do this when o=0. + */ + if (unlikely(ptr != buf->p)) { + if (buf->o) + goto http_msg_ood; + /* Remove empty leading lines, as recommended by RFC2616. */ + bi_fast_delete(buf, ptr - buf->p); + } + msg->sol = 0; + msg->sl.st.l = 0; /* used in debug mode */ + hdr_idx_init(idx); + state = HTTP_MSG_RPVER; + goto http_msg_rpver; + } + + if (unlikely(!HTTP_IS_CRLF(*ptr))) + goto http_msg_invalid; + + if (unlikely(*ptr == '\n')) + EAT_AND_JUMP_OR_RETURN(http_msg_rpbefore, HTTP_MSG_RPBEFORE); + EAT_AND_JUMP_OR_RETURN(http_msg_rpbefore_cr, HTTP_MSG_RPBEFORE_CR); + /* stop here */ + + case HTTP_MSG_RPBEFORE_CR: + http_msg_rpbefore_cr: + EXPECT_LF_HERE(ptr, http_msg_invalid); + EAT_AND_JUMP_OR_RETURN(http_msg_rpbefore, HTTP_MSG_RPBEFORE); + /* stop here */ + + case HTTP_MSG_RPVER: + http_msg_rpver: + case HTTP_MSG_RPVER_SP: + case HTTP_MSG_RPCODE: + case HTTP_MSG_RPCODE_SP: + case HTTP_MSG_RPREASON: + ptr = (char *)http_parse_stsline(msg, + state, ptr, end, + &msg->next, &msg->msg_state); + if (unlikely(!ptr)) + return; + + /* we have a full response and we know that we have either a CR + * or an LF at . + */ + hdr_idx_set_start(idx, msg->sl.st.l, *ptr == '\r'); + + msg->sol = ptr - buf->p; + if (likely(*ptr == '\r')) + EAT_AND_JUMP_OR_RETURN(http_msg_rpline_end, HTTP_MSG_RPLINE_END); + goto http_msg_rpline_end; + + case HTTP_MSG_RPLINE_END: + http_msg_rpline_end: + /* msg->sol must point to the first of CR or LF. */ + EXPECT_LF_HERE(ptr, http_msg_invalid); + EAT_AND_JUMP_OR_RETURN(http_msg_hdr_first, HTTP_MSG_HDR_FIRST); + /* stop here */ + + /* + * Second, states that are specific to the request only + */ + case HTTP_MSG_RQBEFORE: + http_msg_rqbefore: + if (likely(HTTP_IS_TOKEN(*ptr))) { + /* we have a start of message, but we have to check + * first if we need to remove some CRLF. We can only + * do this when o=0. + */ + if (likely(ptr != buf->p)) { + if (buf->o) + goto http_msg_ood; + /* Remove empty leading lines, as recommended by RFC2616. */ + bi_fast_delete(buf, ptr - buf->p); + } + msg->sol = 0; + msg->sl.rq.l = 0; /* used in debug mode */ + state = HTTP_MSG_RQMETH; + goto http_msg_rqmeth; + } + + if (unlikely(!HTTP_IS_CRLF(*ptr))) + goto http_msg_invalid; + + if (unlikely(*ptr == '\n')) + EAT_AND_JUMP_OR_RETURN(http_msg_rqbefore, HTTP_MSG_RQBEFORE); + EAT_AND_JUMP_OR_RETURN(http_msg_rqbefore_cr, HTTP_MSG_RQBEFORE_CR); + /* stop here */ + + case HTTP_MSG_RQBEFORE_CR: + http_msg_rqbefore_cr: + EXPECT_LF_HERE(ptr, http_msg_invalid); + EAT_AND_JUMP_OR_RETURN(http_msg_rqbefore, HTTP_MSG_RQBEFORE); + /* stop here */ + + case HTTP_MSG_RQMETH: + http_msg_rqmeth: + case HTTP_MSG_RQMETH_SP: + case HTTP_MSG_RQURI: + case HTTP_MSG_RQURI_SP: + case HTTP_MSG_RQVER: + ptr = (char *)http_parse_reqline(msg, + state, ptr, end, + &msg->next, &msg->msg_state); + if (unlikely(!ptr)) + return; + + /* we have a full request and we know that we have either a CR + * or an LF at . + */ + hdr_idx_set_start(idx, msg->sl.rq.l, *ptr == '\r'); + + msg->sol = ptr - buf->p; + if (likely(*ptr == '\r')) + EAT_AND_JUMP_OR_RETURN(http_msg_rqline_end, HTTP_MSG_RQLINE_END); + goto http_msg_rqline_end; + + case HTTP_MSG_RQLINE_END: + http_msg_rqline_end: + /* check for HTTP/0.9 request : no version information available. + * msg->sol must point to the first of CR or LF. + */ + if (unlikely(msg->sl.rq.v_l == 0)) + goto http_msg_last_lf; + + EXPECT_LF_HERE(ptr, http_msg_invalid); + EAT_AND_JUMP_OR_RETURN(http_msg_hdr_first, HTTP_MSG_HDR_FIRST); + /* stop here */ + + /* + * Common states below + */ + case HTTP_MSG_HDR_FIRST: + http_msg_hdr_first: + msg->sol = ptr - buf->p; + if (likely(!HTTP_IS_CRLF(*ptr))) { + goto http_msg_hdr_name; + } + + if (likely(*ptr == '\r')) + EAT_AND_JUMP_OR_RETURN(http_msg_last_lf, HTTP_MSG_LAST_LF); + goto http_msg_last_lf; + + case HTTP_MSG_HDR_NAME: + http_msg_hdr_name: + /* assumes msg->sol points to the first char */ + if (likely(HTTP_IS_TOKEN(*ptr))) + EAT_AND_JUMP_OR_RETURN(http_msg_hdr_name, HTTP_MSG_HDR_NAME); + + if (likely(*ptr == ':')) + EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l1_sp, HTTP_MSG_HDR_L1_SP); + + if (likely(msg->err_pos < -1) || *ptr == '\n') + goto http_msg_invalid; + + if (msg->err_pos == -1) /* capture error pointer */ + msg->err_pos = ptr - buf->p; /* >= 0 now */ + + /* and we still accept this non-token character */ + EAT_AND_JUMP_OR_RETURN(http_msg_hdr_name, HTTP_MSG_HDR_NAME); + + case HTTP_MSG_HDR_L1_SP: + http_msg_hdr_l1_sp: + /* assumes msg->sol points to the first char */ + if (likely(HTTP_IS_SPHT(*ptr))) + EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l1_sp, HTTP_MSG_HDR_L1_SP); + + /* header value can be basically anything except CR/LF */ + msg->sov = ptr - buf->p; + + if (likely(!HTTP_IS_CRLF(*ptr))) { + goto http_msg_hdr_val; + } + + if (likely(*ptr == '\r')) + EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l1_lf, HTTP_MSG_HDR_L1_LF); + goto http_msg_hdr_l1_lf; + + case HTTP_MSG_HDR_L1_LF: + http_msg_hdr_l1_lf: + EXPECT_LF_HERE(ptr, http_msg_invalid); + EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l1_lws, HTTP_MSG_HDR_L1_LWS); + + case HTTP_MSG_HDR_L1_LWS: + http_msg_hdr_l1_lws: + if (likely(HTTP_IS_SPHT(*ptr))) { + /* replace HT,CR,LF with spaces */ + for (; buf->p + msg->sov < ptr; msg->sov++) + buf->p[msg->sov] = ' '; + goto http_msg_hdr_l1_sp; + } + /* we had a header consisting only in spaces ! */ + msg->eol = msg->sov; + goto http_msg_complete_header; + + case HTTP_MSG_HDR_VAL: + http_msg_hdr_val: + /* assumes msg->sol points to the first char, and msg->sov + * points to the first character of the value. + */ + if (likely(!HTTP_IS_CRLF(*ptr))) + EAT_AND_JUMP_OR_RETURN(http_msg_hdr_val, HTTP_MSG_HDR_VAL); + + msg->eol = ptr - buf->p; + /* Note: we could also copy eol into ->eoh so that we have the + * real header end in case it ends with lots of LWS, but is this + * really needed ? + */ + if (likely(*ptr == '\r')) + EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l2_lf, HTTP_MSG_HDR_L2_LF); + goto http_msg_hdr_l2_lf; + + case HTTP_MSG_HDR_L2_LF: + http_msg_hdr_l2_lf: + EXPECT_LF_HERE(ptr, http_msg_invalid); + EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l2_lws, HTTP_MSG_HDR_L2_LWS); + + case HTTP_MSG_HDR_L2_LWS: + http_msg_hdr_l2_lws: + if (unlikely(HTTP_IS_SPHT(*ptr))) { + /* LWS: replace HT,CR,LF with spaces */ + for (; buf->p + msg->eol < ptr; msg->eol++) + buf->p[msg->eol] = ' '; + goto http_msg_hdr_val; + } + http_msg_complete_header: + /* + * It was a new header, so the last one is finished. + * Assumes msg->sol points to the first char, msg->sov points + * to the first character of the value and msg->eol to the + * first CR or LF so we know how the line ends. We insert last + * header into the index. + */ + if (unlikely(hdr_idx_add(msg->eol - msg->sol, buf->p[msg->eol] == '\r', + idx, idx->tail) < 0)) + goto http_msg_invalid; + + msg->sol = ptr - buf->p; + if (likely(!HTTP_IS_CRLF(*ptr))) { + goto http_msg_hdr_name; + } + + if (likely(*ptr == '\r')) + EAT_AND_JUMP_OR_RETURN(http_msg_last_lf, HTTP_MSG_LAST_LF); + goto http_msg_last_lf; + + case HTTP_MSG_LAST_LF: + http_msg_last_lf: + /* Assumes msg->sol points to the first of either CR or LF. + * Sets ->sov and ->next to the total header length, ->eoh to + * the last CRLF, and ->eol to the last CRLF length (1 or 2). + */ + EXPECT_LF_HERE(ptr, http_msg_invalid); + ptr++; + msg->sov = msg->next = ptr - buf->p; + msg->eoh = msg->sol; + msg->sol = 0; + msg->eol = msg->sov - msg->eoh; + msg->msg_state = HTTP_MSG_BODY; + return; + + case HTTP_MSG_ERROR: + /* this may only happen if we call http_msg_analyser() twice with an error */ + break; + + default: +#ifdef DEBUG_FULL + fprintf(stderr, ""FIXME !!!! impossible state at %s:%d = %d\n"", __FILE__, __LINE__, state); + exit(1); +#endif + ; + } + http_msg_ood: + /* out of data */ + msg->msg_state = state; + msg->next = ptr - buf->p; + return; + + http_msg_invalid: + /* invalid message */ + msg->msg_state = HTTP_MSG_ERROR; + msg->next = ptr - buf->p; + return; +} +",0,"void http_msg_analyzer(struct http_msg *msg, struct hdr_idx *idx) +{ + enum ht_state state; /* updated only when leaving the FSM */ + register char *ptr, *end; /* request pointers, to avoid dereferences */ + struct buffer *buf; + + state = msg->msg_state; + buf = msg->chn->buf; + ptr = buf->p + msg->next; + end = buf->p + buf->i; + + if (unlikely(ptr >= end)) + goto http_msg_ood; + + switch (state) { + /* + * First, states that are specific to the response only. + * We check them first so that request and headers are + * closer to each other (accessed more often). + */ + case HTTP_MSG_RPBEFORE: + http_msg_rpbefore: + if (likely(HTTP_IS_TOKEN(*ptr))) { + /* we have a start of message, but we have to check + * first if we need to remove some CRLF. We can only + * do this when o=0. + */ + if (unlikely(ptr != buf->p)) { + if (buf->o) + goto http_msg_ood; + /* Remove empty leading lines, as recommended by RFC2616. */ + bi_fast_delete(buf, ptr - buf->p); + } + msg->sol = 0; + msg->sl.st.l = 0; /* used in debug mode */ + hdr_idx_init(idx); + state = HTTP_MSG_RPVER; + goto http_msg_rpver; + } + + if (unlikely(!HTTP_IS_CRLF(*ptr))) + goto http_msg_invalid; + + if (unlikely(*ptr == '\n')) + EAT_AND_JUMP_OR_RETURN(http_msg_rpbefore, HTTP_MSG_RPBEFORE); + EAT_AND_JUMP_OR_RETURN(http_msg_rpbefore_cr, HTTP_MSG_RPBEFORE_CR); + /* stop here */ + + case HTTP_MSG_RPBEFORE_CR: + http_msg_rpbefore_cr: + EXPECT_LF_HERE(ptr, http_msg_invalid); + EAT_AND_JUMP_OR_RETURN(http_msg_rpbefore, HTTP_MSG_RPBEFORE); + /* stop here */ + + case HTTP_MSG_RPVER: + http_msg_rpver: + case HTTP_MSG_RPVER_SP: + case HTTP_MSG_RPCODE: + case HTTP_MSG_RPCODE_SP: + case HTTP_MSG_RPREASON: + ptr = (char *)http_parse_stsline(msg, + state, ptr, end, + &msg->next, &msg->msg_state); + if (unlikely(!ptr)) + return; + + /* we have a full response and we know that we have either a CR + * or an LF at . + */ + hdr_idx_set_start(idx, msg->sl.st.l, *ptr == '\r'); + + msg->sol = ptr - buf->p; + if (likely(*ptr == '\r')) + EAT_AND_JUMP_OR_RETURN(http_msg_rpline_end, HTTP_MSG_RPLINE_END); + goto http_msg_rpline_end; + + case HTTP_MSG_RPLINE_END: + http_msg_rpline_end: + /* msg->sol must point to the first of CR or LF. */ + EXPECT_LF_HERE(ptr, http_msg_invalid); + EAT_AND_JUMP_OR_RETURN(http_msg_hdr_first, HTTP_MSG_HDR_FIRST); + /* stop here */ + + /* + * Second, states that are specific to the request only + */ + case HTTP_MSG_RQBEFORE: + http_msg_rqbefore: + if (likely(HTTP_IS_TOKEN(*ptr))) { + /* we have a start of message, but we have to check + * first if we need to remove some CRLF. We can only + * do this when o=0. + */ + if (likely(ptr != buf->p)) { + if (buf->o) + goto http_msg_ood; + /* Remove empty leading lines, as recommended by RFC2616. */ + bi_fast_delete(buf, ptr - buf->p); + } + msg->sol = 0; + msg->sl.rq.l = 0; /* used in debug mode */ + state = HTTP_MSG_RQMETH; + goto http_msg_rqmeth; + } + + if (unlikely(!HTTP_IS_CRLF(*ptr))) + goto http_msg_invalid; + + if (unlikely(*ptr == '\n')) + EAT_AND_JUMP_OR_RETURN(http_msg_rqbefore, HTTP_MSG_RQBEFORE); + EAT_AND_JUMP_OR_RETURN(http_msg_rqbefore_cr, HTTP_MSG_RQBEFORE_CR); + /* stop here */ + + case HTTP_MSG_RQBEFORE_CR: + http_msg_rqbefore_cr: + EXPECT_LF_HERE(ptr, http_msg_invalid); + EAT_AND_JUMP_OR_RETURN(http_msg_rqbefore, HTTP_MSG_RQBEFORE); + /* stop here */ + + case HTTP_MSG_RQMETH: + http_msg_rqmeth: + case HTTP_MSG_RQMETH_SP: + case HTTP_MSG_RQURI: + case HTTP_MSG_RQURI_SP: + case HTTP_MSG_RQVER: + ptr = (char *)http_parse_reqline(msg, + state, ptr, end, + &msg->next, &msg->msg_state); + if (unlikely(!ptr)) + return; + + /* we have a full request and we know that we have either a CR + * or an LF at . + */ + hdr_idx_set_start(idx, msg->sl.rq.l, *ptr == '\r'); + + msg->sol = ptr - buf->p; + if (likely(*ptr == '\r')) + EAT_AND_JUMP_OR_RETURN(http_msg_rqline_end, HTTP_MSG_RQLINE_END); + goto http_msg_rqline_end; + + case HTTP_MSG_RQLINE_END: + http_msg_rqline_end: + /* check for HTTP/0.9 request : no version information available. + * msg->sol must point to the first of CR or LF. + */ + if (unlikely(msg->sl.rq.v_l == 0)) + goto http_msg_last_lf; + + EXPECT_LF_HERE(ptr, http_msg_invalid); + EAT_AND_JUMP_OR_RETURN(http_msg_hdr_first, HTTP_MSG_HDR_FIRST); + /* stop here */ + + /* + * Common states below + */ + case HTTP_MSG_HDR_FIRST: + http_msg_hdr_first: + msg->sol = ptr - buf->p; + if (likely(!HTTP_IS_CRLF(*ptr))) { + goto http_msg_hdr_name; + } + + if (likely(*ptr == '\r')) + EAT_AND_JUMP_OR_RETURN(http_msg_last_lf, HTTP_MSG_LAST_LF); + goto http_msg_last_lf; + + case HTTP_MSG_HDR_NAME: + http_msg_hdr_name: + /* assumes msg->sol points to the first char */ + if (likely(HTTP_IS_TOKEN(*ptr))) + EAT_AND_JUMP_OR_RETURN(http_msg_hdr_name, HTTP_MSG_HDR_NAME); + + if (likely(*ptr == ':')) + EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l1_sp, HTTP_MSG_HDR_L1_SP); + + if (likely(msg->err_pos < -1) || *ptr == '\n') + goto http_msg_invalid; + + if (msg->err_pos == -1) /* capture error pointer */ + msg->err_pos = ptr - buf->p; /* >= 0 now */ + + /* and we still accept this non-token character */ + EAT_AND_JUMP_OR_RETURN(http_msg_hdr_name, HTTP_MSG_HDR_NAME); + + case HTTP_MSG_HDR_L1_SP: + http_msg_hdr_l1_sp: + /* assumes msg->sol points to the first char */ + if (likely(HTTP_IS_SPHT(*ptr))) + EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l1_sp, HTTP_MSG_HDR_L1_SP); + + /* header value can be basically anything except CR/LF */ + msg->sov = ptr - buf->p; + + if (likely(!HTTP_IS_CRLF(*ptr))) { + goto http_msg_hdr_val; + } + + if (likely(*ptr == '\r')) + EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l1_lf, HTTP_MSG_HDR_L1_LF); + goto http_msg_hdr_l1_lf; + + case HTTP_MSG_HDR_L1_LF: + http_msg_hdr_l1_lf: + EXPECT_LF_HERE(ptr, http_msg_invalid); + EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l1_lws, HTTP_MSG_HDR_L1_LWS); + + case HTTP_MSG_HDR_L1_LWS: + http_msg_hdr_l1_lws: + if (likely(HTTP_IS_SPHT(*ptr))) { + /* replace HT,CR,LF with spaces */ + for (; buf->p + msg->sov < ptr; msg->sov++) + buf->p[msg->sov] = ' '; + goto http_msg_hdr_l1_sp; + } + /* we had a header consisting only in spaces ! */ + msg->eol = msg->sov; + goto http_msg_complete_header; + + case HTTP_MSG_HDR_VAL: + http_msg_hdr_val: + /* assumes msg->sol points to the first char, and msg->sov + * points to the first character of the value. + */ + if (likely(!HTTP_IS_CRLF(*ptr))) + EAT_AND_JUMP_OR_RETURN(http_msg_hdr_val, HTTP_MSG_HDR_VAL); + + msg->eol = ptr - buf->p; + /* Note: we could also copy eol into ->eoh so that we have the + * real header end in case it ends with lots of LWS, but is this + * really needed ? + */ + if (likely(*ptr == '\r')) + EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l2_lf, HTTP_MSG_HDR_L2_LF); + goto http_msg_hdr_l2_lf; + + case HTTP_MSG_HDR_L2_LF: + http_msg_hdr_l2_lf: + EXPECT_LF_HERE(ptr, http_msg_invalid); + EAT_AND_JUMP_OR_RETURN(http_msg_hdr_l2_lws, HTTP_MSG_HDR_L2_LWS); + + case HTTP_MSG_HDR_L2_LWS: + http_msg_hdr_l2_lws: + if (unlikely(HTTP_IS_SPHT(*ptr))) { + /* LWS: replace HT,CR,LF with spaces */ + for (; buf->p + msg->eol < ptr; msg->eol++) + buf->p[msg->eol] = ' '; + goto http_msg_hdr_val; + } + http_msg_complete_header: + /* + * It was a new header, so the last one is finished. + * Assumes msg->sol points to the first char, msg->sov points + * to the first character of the value and msg->eol to the + * first CR or LF so we know how the line ends. We insert last + * header into the index. + */ + if (unlikely(hdr_idx_add(msg->eol - msg->sol, buf->p[msg->eol] == '\r', + idx, idx->tail) < 0)) + goto http_msg_invalid; + + msg->sol = ptr - buf->p; + if (likely(!HTTP_IS_CRLF(*ptr))) { + goto http_msg_hdr_name; + } + + if (likely(*ptr == '\r')) + EAT_AND_JUMP_OR_RETURN(http_msg_last_lf, HTTP_MSG_LAST_LF); + goto http_msg_last_lf; + + case HTTP_MSG_LAST_LF: + http_msg_last_lf: + /* Assumes msg->sol points to the first of either CR or LF. + * Sets ->sov and ->next to the total header length, ->eoh to + * the last CRLF, and ->eol to the last CRLF length (1 or 2). + */ + EXPECT_LF_HERE(ptr, http_msg_invalid); + ptr++; + msg->sov = msg->next = ptr - buf->p; + msg->eoh = msg->sol; + msg->sol = 0; + msg->eol = msg->sov - msg->eoh; + msg->msg_state = HTTP_MSG_BODY; + return; + + case HTTP_MSG_ERROR: + /* this may only happen if we call http_msg_analyser() twice with an error */ + break; + + default: +#ifdef DEBUG_FULL + fprintf(stderr, ""FIXME !!!! impossible state at %s:%d = %d\n"", __FILE__, __LINE__, state); + exit(1); +#endif + ; + } + http_msg_ood: + /* out of data */ + msg->msg_state = state; + msg->next = ptr - buf->p; + return; + + http_msg_invalid: + /* invalid message */ + msg->msg_state = HTTP_MSG_ERROR; + msg->next = ptr - buf->p; + return; +} +","@@ -4886,8 +4886,8 @@ void http_end_txn_clean_session(struct session *s) + s->req->cons->conn_retries = 0; /* used for logging too */ + s->req->cons->exp = TICK_ETERNITY; + s->req->cons->flags &= SI_FL_DONT_WAKE; /* we're in the context of process_session */ +- s->req->flags &= ~(CF_SHUTW|CF_SHUTW_NOW|CF_AUTO_CONNECT|CF_WRITE_ERROR|CF_STREAMER|CF_STREAMER_FAST|CF_NEVER_WAIT|CF_WAKE_CONNECT); +- s->rep->flags &= ~(CF_SHUTR|CF_SHUTR_NOW|CF_READ_ATTACHED|CF_READ_ERROR|CF_READ_NOEXP|CF_STREAMER|CF_STREAMER_FAST|CF_WRITE_PARTIAL|CF_NEVER_WAIT); ++ s->req->flags &= ~(CF_SHUTW|CF_SHUTW_NOW|CF_AUTO_CONNECT|CF_WRITE_ERROR|CF_STREAMER|CF_STREAMER_FAST|CF_NEVER_WAIT|CF_WAKE_CONNECT|CF_WROTE_DATA); ++ s->rep->flags &= ~(CF_SHUTR|CF_SHUTR_NOW|CF_READ_ATTACHED|CF_READ_ERROR|CF_READ_NOEXP|CF_STREAMER|CF_STREAMER_FAST|CF_WRITE_PARTIAL|CF_NEVER_WAIT|CF_WROTE_DATA); + s->flags &= ~(SN_DIRECT|SN_ASSIGNED|SN_ADDR_SET|SN_BE_ASSIGNED|SN_FORCE_PRST|SN_IGNORE_PRST); + s->flags &= ~(SN_CURR_SESS|SN_REDIRECTABLE|SN_SRV_REUSED); + +@@ -5430,7 +5430,7 @@ int http_request_forward_body(struct session *s, struct channel *req, int an_bit + * such as last chunk of data or trailers. + */ + b_adv(req->buf, msg->next); +- if (unlikely(!(s->rep->flags & CF_READ_ATTACHED))) ++ if (unlikely(!(s->req->flags & CF_WROTE_DATA))) + msg->sov -= msg->next; + msg->next = 0; + +@@ -5482,7 +5482,7 @@ int http_request_forward_body(struct session *s, struct channel *req, int an_bit + missing_data: + /* we may have some pending data starting at req->buf->p */ + b_adv(req->buf, msg->next); +- if (unlikely(!(s->rep->flags & CF_READ_ATTACHED))) ++ if (unlikely(!(s->req->flags & CF_WROTE_DATA))) + msg->sov -= msg->next + MIN(msg->chunk_len, req->buf->i); + + msg->next = 0;",2669,3000,4096 +18032,"MagickExport MagickBooleanType DrawPrimitive(Image *image, + const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, + ExceptionInfo *exception) +{ + CacheView + *image_view; + + 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); + } + if ((IsGrayColorspace(image->colorspace) != MagickFalse) && + ((IsPixelInfoGray(&draw_info->fill) == MagickFalse) || + (IsPixelInfoGray(&draw_info->stroke) == MagickFalse))) + (void) SetImageColorspace(image,sRGBColorspace,exception); + 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 AlphaPrimitive: + { + if (image->alpha_trait == UndefinedPixelTrait) + (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); + switch (primitive_info->method) + { + case PointMethod: + default: + { + PixelInfo + pixel; + + register Quantum + *q; + + q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); + if (q == (Quantum *) NULL) + break; + GetFillColor(draw_info,x,y,&pixel,exception); + SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); + (void) SyncCacheViewAuthenticPixels(image_view,exception); + break; + } + case ReplaceMethod: + { + MagickBooleanType + sync; + + PixelInfo + pixel, + target; + + (void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target, + exception); + GetPixelInfo(image,&pixel); + for (y=0; y < (ssize_t) image->rows; y++) + { + register Quantum + *magick_restrict q; + + q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, + exception); + if (q == (Quantum *) NULL) + break; + for (x=0; x < (ssize_t) image->columns; x++) + { + GetPixelInfoPixel(image,q,&pixel); + if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse) + { + q+=GetPixelChannels(image); + continue; + } + GetFillColor(draw_info,x,y,&pixel,exception); + SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); + q+=GetPixelChannels(image); + } + sync=SyncCacheViewAuthenticPixels(image_view,exception); + if (sync == MagickFalse) + break; + } + break; + } + case FloodfillMethod: + case FillToBorderMethod: + { + ChannelType + channel_mask; + + PixelInfo + target; + + (void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y, + &target,exception); + if (primitive_info->method == FillToBorderMethod) + { + target.red=(double) draw_info->border_color.red; + target.green=(double) draw_info->border_color.green; + target.blue=(double) draw_info->border_color.blue; + } + channel_mask=SetImageChannelMask(image,AlphaChannel); + status&=FloodfillPaintImage(image,draw_info,&target,x,y, + primitive_info->method == FloodfillMethod ? MagickFalse : + MagickTrue,exception); + (void) SetImageChannelMask(image,channel_mask); + break; + } + case ResetMethod: + { + MagickBooleanType + sync; + + PixelInfo + pixel; + + for (y=0; y < (ssize_t) image->rows; y++) + { + register Quantum + *magick_restrict q; + + q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, + exception); + if (q == (Quantum *) NULL) + break; + for (x=0; x < (ssize_t) image->columns; x++) + { + GetFillColor(draw_info,x,y,&pixel,exception); + SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); + q+=GetPixelChannels(image); + } + sync=SyncCacheViewAuthenticPixels(image_view,exception); + if (sync == MagickFalse) + break; + } + break; + } + } + break; + } + case ColorPrimitive: + { + switch (primitive_info->method) + { + case PointMethod: + default: + { + PixelInfo + pixel; + + register Quantum + *q; + + q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); + if (q == (Quantum *) NULL) + break; + GetPixelInfo(image,&pixel); + GetFillColor(draw_info,x,y,&pixel,exception); + SetPixelViaPixelInfo(image,&pixel,q); + (void) SyncCacheViewAuthenticPixels(image_view,exception); + break; + } + case ReplaceMethod: + { + MagickBooleanType + sync; + + PixelInfo + pixel, + target; + + (void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target, + exception); + for (y=0; y < (ssize_t) image->rows; y++) + { + register Quantum + *magick_restrict q; + + q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, + exception); + if (q == (Quantum *) NULL) + break; + for (x=0; x < (ssize_t) image->columns; x++) + { + GetPixelInfoPixel(image,q,&pixel); + if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse) + { + q+=GetPixelChannels(image); + continue; + } + GetFillColor(draw_info,x,y,&pixel,exception); + SetPixelViaPixelInfo(image,&pixel,q); + q+=GetPixelChannels(image); + } + sync=SyncCacheViewAuthenticPixels(image_view,exception); + if (sync == MagickFalse) + break; + } + break; + } + case FloodfillMethod: + case FillToBorderMethod: + { + PixelInfo + target; + + (void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y, + &target,exception); + if (primitive_info->method == FillToBorderMethod) + { + target.red=(double) draw_info->border_color.red; + target.green=(double) draw_info->border_color.green; + target.blue=(double) draw_info->border_color.blue; + } + status&=FloodfillPaintImage(image,draw_info,&target,x,y, + primitive_info->method == FloodfillMethod ? MagickFalse : + MagickTrue,exception); + break; + } + case ResetMethod: + { + MagickBooleanType + sync; + + PixelInfo + pixel; + + GetPixelInfo(image,&pixel); + for (y=0; y < (ssize_t) image->rows; y++) + { + register Quantum + *magick_restrict q; + + q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, + exception); + if (q == (Quantum *) NULL) + break; + for (x=0; x < (ssize_t) image->columns; x++) + { + GetFillColor(draw_info,x,y,&pixel,exception); + SetPixelViaPixelInfo(image,&pixel,q); + q+=GetPixelChannels(image); + } + sync=SyncCacheViewAuthenticPixels(image_view,exception); + if (sync == MagickFalse) + break; + } + break; + } + } + break; + } + case ImagePrimitive: + { + AffineMatrix + affine; + + char + composite_geometry[MagickPathExtent]; + + 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, + exception); + else + { + (void) CopyMagickString(clone_info->filename,primitive_info->text, + MagickPathExtent); + composite_image=ReadImage(clone_info,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))) + { + /* + Resize image. + */ + (void) FormatLocaleString(composite_geometry,MagickPathExtent, + ""%gx%g!"",primitive_info[1].point.x,primitive_info[1].point.y); + composite_image->filter=image->filter; + (void) TransformImage(&composite_image,(char *) NULL, + composite_geometry,exception); + } + if (composite_image->alpha_trait == UndefinedPixelTrait) + (void) SetImageAlphaChannel(composite_image,OpaqueAlphaChannel, + exception); + if (draw_info->alpha != OpaqueAlpha) + (void) SetImageAlpha(composite_image,draw_info->alpha,exception); + SetGeometry(image,&geometry); + image->gravity=draw_info->gravity; + geometry.x=x; + geometry.y=y; + (void) FormatLocaleString(composite_geometry,MagickPathExtent, + ""%.20gx%.20g%+.20g%+.20g"",(double) composite_image->columns,(double) + composite_image->rows,(double) geometry.x,(double) geometry.y); + (void) ParseGravityGeometry(image,composite_geometry,&geometry,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,exception); + else + (void) CompositeImage(image,composite_image,draw_info->compose, + MagickTrue,geometry.x,geometry.y,exception); + composite_image=DestroyImage(composite_image); + break; + } + case PointPrimitive: + { + PixelInfo + fill_color; + + register Quantum + *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 == (Quantum *) NULL) + break; + GetFillColor(draw_info,x,y,&fill_color,exception); + CompositePixelOver(image,&fill_color,(double) fill_color.alpha,q, + (double) GetPixelAlpha(image,q),q); + (void) SyncCacheViewAuthenticPixels(image_view,exception); + break; + } + case TextPrimitive: + { + char + geometry[MagickPathExtent]; + + 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,MagickPathExtent,""%+f%+f"", + primitive_info->point.x,primitive_info->point.y); + (void) CloneString(&clone_info->geometry,geometry); + status&=AnnotateImage(image,clone_info,exception); + clone_info=DestroyDrawInfo(clone_info); + 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) && + (draw_info->dash_pattern[0] != 0.0) && + ((scale*draw_info->stroke_width) >= MagickEpsilon) && + (draw_info->stroke.alpha != (Quantum) TransparentAlpha)) + { + /* + Draw dash polygon. + */ + clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); + clone_info->stroke_width=0.0; + clone_info->stroke.alpha=(Quantum) TransparentAlpha; + status&=DrawPolygonPrimitive(image,clone_info,primitive_info, + exception); + clone_info=DestroyDrawInfo(clone_info); + (void) DrawDashPolygon(draw_info,primitive_info,image,exception); + break; + } + mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0; + if ((mid > 1.0) && + ((draw_info->stroke.alpha != (Quantum) TransparentAlpha) || + (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; + if ((((draw_info->linecap == RoundCap) || + (closed_path != MagickFalse)) && + (draw_info->linejoin == RoundJoin)) || + (primitive_info[i].primitive != UndefinedPrimitive)) + { + (void) DrawPolygonPrimitive(image,draw_info,primitive_info, + exception); + break; + } + clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); + clone_info->stroke_width=0.0; + clone_info->stroke.alpha=(Quantum) TransparentAlpha; + status&=DrawPolygonPrimitive(image,clone_info,primitive_info, + exception); + clone_info=DestroyDrawInfo(clone_info); + status&=DrawStrokePolygon(image,draw_info,primitive_info,exception); + break; + } + status&=DrawPolygonPrimitive(image,draw_info,primitive_info,exception); + break; + } + } + image_view=DestroyCacheView(image_view); + if (image->debug != MagickFalse) + (void) LogMagickEvent(DrawEvent,GetMagickModule(),"" end draw-primitive""); + return(status != 0 ? MagickTrue : MagickFalse); +} +",1,"MagickExport MagickBooleanType DrawPrimitive(Image *image, + const DrawInfo *draw_info,const PrimitiveInfo *primitive_info, + ExceptionInfo *exception) +{ + CacheView + *image_view; + + 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); + } + if ((IsGrayColorspace(image->colorspace) != MagickFalse) && + ((IsPixelInfoGray(&draw_info->fill) == MagickFalse) || + (IsPixelInfoGray(&draw_info->stroke) == MagickFalse))) + (void) SetImageColorspace(image,sRGBColorspace,exception); + 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 AlphaPrimitive: + { + if (image->alpha_trait == UndefinedPixelTrait) + (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); + switch (primitive_info->method) + { + case PointMethod: + default: + { + PixelInfo + pixel; + + register Quantum + *q; + + q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); + if (q == (Quantum *) NULL) + break; + GetFillColor(draw_info,x,y,&pixel,exception); + SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); + (void) SyncCacheViewAuthenticPixels(image_view,exception); + break; + } + case ReplaceMethod: + { + MagickBooleanType + sync; + + PixelInfo + pixel, + target; + + (void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target, + exception); + GetPixelInfo(image,&pixel); + for (y=0; y < (ssize_t) image->rows; y++) + { + register Quantum + *magick_restrict q; + + q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, + exception); + if (q == (Quantum *) NULL) + break; + for (x=0; x < (ssize_t) image->columns; x++) + { + GetPixelInfoPixel(image,q,&pixel); + if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse) + { + q+=GetPixelChannels(image); + continue; + } + GetFillColor(draw_info,x,y,&pixel,exception); + SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); + q+=GetPixelChannels(image); + } + sync=SyncCacheViewAuthenticPixels(image_view,exception); + if (sync == MagickFalse) + break; + } + break; + } + case FloodfillMethod: + case FillToBorderMethod: + { + ChannelType + channel_mask; + + PixelInfo + target; + + (void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y, + &target,exception); + if (primitive_info->method == FillToBorderMethod) + { + target.red=(double) draw_info->border_color.red; + target.green=(double) draw_info->border_color.green; + target.blue=(double) draw_info->border_color.blue; + } + channel_mask=SetImageChannelMask(image,AlphaChannel); + status&=FloodfillPaintImage(image,draw_info,&target,x,y, + primitive_info->method == FloodfillMethod ? MagickFalse : + MagickTrue,exception); + (void) SetImageChannelMask(image,channel_mask); + break; + } + case ResetMethod: + { + MagickBooleanType + sync; + + PixelInfo + pixel; + + for (y=0; y < (ssize_t) image->rows; y++) + { + register Quantum + *magick_restrict q; + + q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, + exception); + if (q == (Quantum *) NULL) + break; + for (x=0; x < (ssize_t) image->columns; x++) + { + GetFillColor(draw_info,x,y,&pixel,exception); + SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q); + q+=GetPixelChannels(image); + } + sync=SyncCacheViewAuthenticPixels(image_view,exception); + if (sync == MagickFalse) + break; + } + break; + } + } + break; + } + case ColorPrimitive: + { + switch (primitive_info->method) + { + case PointMethod: + default: + { + PixelInfo + pixel; + + register Quantum + *q; + + q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception); + if (q == (Quantum *) NULL) + break; + GetPixelInfo(image,&pixel); + GetFillColor(draw_info,x,y,&pixel,exception); + SetPixelViaPixelInfo(image,&pixel,q); + (void) SyncCacheViewAuthenticPixels(image_view,exception); + break; + } + case ReplaceMethod: + { + MagickBooleanType + sync; + + PixelInfo + pixel, + target; + + (void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target, + exception); + for (y=0; y < (ssize_t) image->rows; y++) + { + register Quantum + *magick_restrict q; + + q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, + exception); + if (q == (Quantum *) NULL) + break; + for (x=0; x < (ssize_t) image->columns; x++) + { + GetPixelInfoPixel(image,q,&pixel); + if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse) + { + q+=GetPixelChannels(image); + continue; + } + GetFillColor(draw_info,x,y,&pixel,exception); + SetPixelViaPixelInfo(image,&pixel,q); + q+=GetPixelChannels(image); + } + sync=SyncCacheViewAuthenticPixels(image_view,exception); + if (sync == MagickFalse) + break; + } + break; + } + case FloodfillMethod: + case FillToBorderMethod: + { + PixelInfo + target; + + (void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y, + &target,exception); + if (primitive_info->method == FillToBorderMethod) + { + target.red=(double) draw_info->border_color.red; + target.green=(double) draw_info->border_color.green; + target.blue=(double) draw_info->border_color.blue; + } + status&=FloodfillPaintImage(image,draw_info,&target,x,y, + primitive_info->method == FloodfillMethod ? MagickFalse : + MagickTrue,exception); + break; + } + case ResetMethod: + { + MagickBooleanType + sync; + + PixelInfo + pixel; + + GetPixelInfo(image,&pixel); + for (y=0; y < (ssize_t) image->rows; y++) + { + register Quantum + *magick_restrict q; + + q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, + exception); + if (q == (Quantum *) NULL) + break; + for (x=0; x < (ssize_t) image->columns; x++) + { + GetFillColor(draw_info,x,y,&pixel,exception); + SetPixelViaPixelInfo(image,&pixel,q); + q+=GetPixelChannels(image); + } + sync=SyncCacheViewAuthenticPixels(image_view,exception); + if (sync == MagickFalse) + break; + } + break; + } + } + break; + } + case ImagePrimitive: + { + AffineMatrix + affine; + + char + composite_geometry[MagickPathExtent]; + + 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, + exception); + else + { + (void) CopyMagickString(clone_info->filename,primitive_info->text, + MagickPathExtent); + composite_image=ReadImage(clone_info,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))) + { + /* + Resize image. + */ + (void) FormatLocaleString(composite_geometry,MagickPathExtent, + ""%gx%g!"",primitive_info[1].point.x,primitive_info[1].point.y); + composite_image->filter=image->filter; + (void) TransformImage(&composite_image,(char *) NULL, + composite_geometry,exception); + } + if (composite_image->alpha_trait == UndefinedPixelTrait) + (void) SetImageAlphaChannel(composite_image,OpaqueAlphaChannel, + exception); + if (draw_info->alpha != OpaqueAlpha) + (void) SetImageAlpha(composite_image,draw_info->alpha,exception); + SetGeometry(image,&geometry); + image->gravity=draw_info->gravity; + geometry.x=x; + geometry.y=y; + (void) FormatLocaleString(composite_geometry,MagickPathExtent, + ""%.20gx%.20g%+.20g%+.20g"",(double) composite_image->columns,(double) + composite_image->rows,(double) geometry.x,(double) geometry.y); + (void) ParseGravityGeometry(image,composite_geometry,&geometry,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,exception); + else + (void) CompositeImage(image,composite_image,draw_info->compose, + MagickTrue,geometry.x,geometry.y,exception); + composite_image=DestroyImage(composite_image); + break; + } + case PointPrimitive: + { + PixelInfo + fill_color; + + register Quantum + *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 == (Quantum *) NULL) + break; + GetFillColor(draw_info,x,y,&fill_color,exception); + CompositePixelOver(image,&fill_color,(double) fill_color.alpha,q, + (double) GetPixelAlpha(image,q),q); + (void) SyncCacheViewAuthenticPixels(image_view,exception); + break; + } + case TextPrimitive: + { + char + geometry[MagickPathExtent]; + + 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,MagickPathExtent,""%+f%+f"", + primitive_info->point.x,primitive_info->point.y); + (void) CloneString(&clone_info->geometry,geometry); + status&=AnnotateImage(image,clone_info,exception); + clone_info=DestroyDrawInfo(clone_info); + 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) && + (draw_info->dash_pattern[0] != 0.0) && + ((scale*draw_info->stroke_width) >= MagickEpsilon) && + (draw_info->stroke.alpha != (Quantum) TransparentAlpha)) + { + /* + Draw dash polygon. + */ + clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); + clone_info->stroke_width=0.0; + clone_info->stroke.alpha=(MagickRealType) TransparentAlpha; + status&=DrawPolygonPrimitive(image,clone_info,primitive_info, + exception); + clone_info=DestroyDrawInfo(clone_info); + (void) DrawDashPolygon(draw_info,primitive_info,image,exception); + break; + } + mid=ExpandAffine(&draw_info->affine)*draw_info->stroke_width/2.0; + if ((mid > 1.0) && + ((draw_info->stroke.alpha != (Quantum) TransparentAlpha) || + (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; + if ((((draw_info->linecap == RoundCap) || + (closed_path != MagickFalse)) && + (draw_info->linejoin == RoundJoin)) || + (primitive_info[i].primitive != UndefinedPrimitive)) + { + (void) DrawPolygonPrimitive(image,draw_info,primitive_info, + exception); + break; + } + clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); + clone_info->stroke_width=0.0; + clone_info->stroke.alpha=(MagickRealType) TransparentAlpha; + status&=DrawPolygonPrimitive(image,clone_info,primitive_info, + exception); + clone_info=DestroyDrawInfo(clone_info); + status&=DrawStrokePolygon(image,draw_info,primitive_info,exception); + break; + } + status&=DrawPolygonPrimitive(image,draw_info,primitive_info,exception); + break; + } + } + image_view=DestroyCacheView(image_view); + if (image->debug != MagickFalse) + (void) LogMagickEvent(DrawEvent,GetMagickModule(),"" end draw-primitive""); + return(status != 0 ? MagickTrue : MagickFalse); +} +","@@ -1417,7 +1417,7 @@ MagickExport MagickBooleanType DrawClipPath(Image *image, + return(MagickFalse); + (void) QueryColorCompliance(""#0000"",AllCompliance, + &clip_mask->background_color,exception); +- clip_mask->background_color.alpha=(Quantum) TransparentAlpha; ++ clip_mask->background_color.alpha=(MagickRealType) TransparentAlpha; + (void) SetImageBackgroundColor(clip_mask,exception); + if (image->debug != MagickFalse) + (void) LogMagickEvent(DrawEvent,GetMagickModule(),""\nbegin clip-path %s"", +@@ -1541,7 +1541,7 @@ static MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info, + status=MagickTrue; + maximum_length=0.0; + total_length=0.0; +- for (i=1; (i < number_vertices) && (length >= 0.0); i++) ++ 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; +@@ -1794,7 +1794,7 @@ MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info, + /* + Interpret graphic primitive. + */ +- GetNextToken(q,&q,extent,keyword); ++ GetNextToken(q,&q,MagickPathExtent,keyword); + if (*keyword == '\0') + break; + if (*keyword == '#') +@@ -2104,7 +2104,7 @@ MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info, + GetNextToken(q,&q,extent,token); + weight=ParseCommandOption(MagickWeightOptions,MagickFalse,token); + if (weight == -1) +- weight=StringToUnsignedLong(token); ++ weight=(ssize_t) StringToUnsignedLong(token); + graphic_context[n]->weight=(size_t) weight; + break; + } +@@ -2353,7 +2353,8 @@ MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info, + (void) SetImageArtifact(image,key,token); + (void) FormatLocaleString(key,MagickPathExtent,""%s-type"",name); + (void) SetImageArtifact(image,key,type); +- (void) FormatLocaleString(key,MagickPathExtent,""%s-geometry"",name); ++ (void) FormatLocaleString(key,MagickPathExtent,""%s-geometry"", ++ name); + (void) FormatLocaleString(geometry,MagickPathExtent, + ""%gx%g%+.15g%+.15g"", + MagickMax(fabs(bounds.x2-bounds.x1+1.0),1.0), +@@ -4608,7 +4609,7 @@ MagickExport MagickBooleanType DrawPrimitive(Image *image, + */ + clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); + clone_info->stroke_width=0.0; +- clone_info->stroke.alpha=(Quantum) TransparentAlpha; ++ clone_info->stroke.alpha=(MagickRealType) TransparentAlpha; + status&=DrawPolygonPrimitive(image,clone_info,primitive_info, + exception); + clone_info=DestroyDrawInfo(clone_info); +@@ -4643,7 +4644,7 @@ MagickExport MagickBooleanType DrawPrimitive(Image *image, + } + clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); + clone_info->stroke_width=0.0; +- clone_info->stroke.alpha=(Quantum) TransparentAlpha; ++ clone_info->stroke.alpha=(MagickRealType) TransparentAlpha; + status&=DrawPolygonPrimitive(image,clone_info,primitive_info, + exception); + clone_info=DestroyDrawInfo(clone_info); +@@ -4743,7 +4744,7 @@ static MagickBooleanType DrawStrokePolygon(Image *image, + if (clone_info->stroke_pattern != (Image *) NULL) + clone_info->fill_pattern=CloneImage(clone_info->stroke_pattern,0,0, + MagickTrue,exception); +- clone_info->stroke.alpha=(Quantum) TransparentAlpha; ++ clone_info->stroke.alpha=(MagickRealType) TransparentAlpha; + clone_info->stroke_width=0.0; + clone_info->fill_rule=NonZeroRule; + status=MagickTrue; +@@ -4858,7 +4859,7 @@ MagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info) + draw_info->miterlimit=10; + draw_info->decorate=NoDecoration; + draw_info->pointsize=12.0; +- draw_info->undercolor.alpha=(Quantum) TransparentAlpha; ++ draw_info->undercolor.alpha=(MagickRealType) TransparentAlpha; + draw_info->compose=OverCompositeOp; + draw_info->render=MagickTrue; + draw_info->debug=IsEventLogging(); +@@ -4925,7 +4926,7 @@ MagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info) + + weight=ParseCommandOption(MagickWeightOptions,MagickFalse,option); + if (weight == -1) +- weight=StringToUnsignedLong(option); ++ weight=(ssize_t) StringToUnsignedLong(option); + draw_info->weight=(size_t) weight; + } + exception=DestroyExceptionInfo(exception); +@@ -6021,17 +6022,29 @@ static PrimitiveInfo *TraceStrokePolygon(const DrawInfo *draw_info, + } + if (q >= (ssize_t) (max_strokes-6*BezierQuantum-360)) + { +- max_strokes+=6*BezierQuantum+360; +- path_p=(PointInfo *) ResizeQuantumMemory(path_p,(size_t) max_strokes, +- sizeof(*path_p)); +- path_q=(PointInfo *) ResizeQuantumMemory(path_q,(size_t) max_strokes, +- sizeof(*path_q)); +- if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL)) +- { +- polygon_primitive=(PrimitiveInfo *) +- RelinquishMagickMemory(polygon_primitive); +- return((PrimitiveInfo *) NULL); +- } ++ 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)",3421,3752,4096 +15382,"bool GLES2Implementation::GetHelper(GLenum pname, GLint* params) { + + switch (pname) { + case GL_ACTIVE_TEXTURE: + *params = active_texture_unit_ + GL_TEXTURE0; + return true; + case GL_ARRAY_BUFFER_BINDING: + *params = bound_array_buffer_; + return true; + case GL_ELEMENT_ARRAY_BUFFER_BINDING: + *params = vertex_array_object_manager_->bound_element_array_buffer(); + return true; + case GL_FRAMEBUFFER_BINDING: + *params = bound_framebuffer_; + return true; + case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS: + *params = capabilities_.max_combined_texture_image_units; + return true; + case GL_MAX_CUBE_MAP_TEXTURE_SIZE: + *params = capabilities_.max_cube_map_texture_size; + return true; + case GL_MAX_FRAGMENT_UNIFORM_VECTORS: + *params = capabilities_.max_fragment_uniform_vectors; + return true; + case GL_MAX_RENDERBUFFER_SIZE: + *params = capabilities_.max_renderbuffer_size; + return true; + case GL_MAX_TEXTURE_IMAGE_UNITS: + *params = capabilities_.max_texture_image_units; + return true; + case GL_MAX_TEXTURE_SIZE: + *params = capabilities_.max_texture_size; + return true; + case GL_MAX_VARYING_VECTORS: + *params = capabilities_.max_varying_vectors; + return true; + case GL_MAX_VERTEX_ATTRIBS: + *params = capabilities_.max_vertex_attribs; + return true; + case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS: + *params = capabilities_.max_vertex_texture_image_units; + return true; + case GL_MAX_VERTEX_UNIFORM_VECTORS: + *params = capabilities_.max_vertex_uniform_vectors; + return true; + case GL_MAX_VIEWPORT_DIMS: + if (capabilities_.max_viewport_width > 0 && + capabilities_.max_viewport_height > 0) { + params[0] = capabilities_.max_viewport_width; + params[1] = capabilities_.max_viewport_height; + return true; + } + return false; + case GL_NUM_COMPRESSED_TEXTURE_FORMATS: + *params = capabilities_.num_compressed_texture_formats; + return true; + case GL_NUM_SHADER_BINARY_FORMATS: + *params = capabilities_.num_shader_binary_formats; + return true; + case GL_RENDERBUFFER_BINDING: + *params = bound_renderbuffer_; + return true; + case GL_TEXTURE_BINDING_2D: + *params = texture_units_[active_texture_unit_].bound_texture_2d; + return true; + case GL_TEXTURE_BINDING_CUBE_MAP: + *params = texture_units_[active_texture_unit_].bound_texture_cube_map; + return true; + + case GL_TEXTURE_BINDING_EXTERNAL_OES: + *params = texture_units_[active_texture_unit_].bound_texture_external_oes; + return true; + case GL_TEXTURE_BINDING_RECTANGLE_ARB: + *params = + texture_units_[active_texture_unit_].bound_texture_rectangle_arb; + return true; + case GL_PIXEL_PACK_TRANSFER_BUFFER_BINDING_CHROMIUM: + *params = bound_pixel_pack_transfer_buffer_id_; + return true; + case GL_PIXEL_UNPACK_TRANSFER_BUFFER_BINDING_CHROMIUM: + *params = bound_pixel_unpack_transfer_buffer_id_; + return true; + case GL_READ_FRAMEBUFFER_BINDING: + if (capabilities_.major_version >= 3 || + IsChromiumFramebufferMultisampleAvailable()) { + *params = bound_read_framebuffer_; + return true; + } + break; + case GL_TIMESTAMP_EXT: + *params = base::saturated_cast( + (base::TimeTicks::Now() - base::TimeTicks()).InMicroseconds() * + base::Time::kNanosecondsPerMicrosecond); + return true; + case GL_GPU_DISJOINT_EXT: + *params = static_cast(query_tracker_->CheckAndResetDisjoint()); + return true; + + case GL_VIEWPORT: + if (state_.viewport_width > 0 && state_.viewport_height > 0 && + capabilities_.max_viewport_width > 0 && + capabilities_.max_viewport_height > 0) { + params[0] = state_.viewport_x; + params[1] = state_.viewport_y; + params[2] = + std::min(state_.viewport_width, capabilities_.max_viewport_width); + params[3] = + std::min(state_.viewport_height, capabilities_.max_viewport_height); + return true; + } + return false; + + case GL_ALIASED_LINE_WIDTH_RANGE: + case GL_ALIASED_POINT_SIZE_RANGE: + case GL_ALPHA_BITS: + case GL_BLEND: + case GL_BLEND_COLOR: + case GL_BLEND_DST_ALPHA: + case GL_BLEND_DST_RGB: + case GL_BLEND_EQUATION_ALPHA: + case GL_BLEND_EQUATION_RGB: + case GL_BLEND_SRC_ALPHA: + case GL_BLEND_SRC_RGB: + case GL_BLUE_BITS: + case GL_COLOR_CLEAR_VALUE: + case GL_COLOR_WRITEMASK: + case GL_COMPRESSED_TEXTURE_FORMATS: + case GL_CULL_FACE: + case GL_CULL_FACE_MODE: + case GL_CURRENT_PROGRAM: + case GL_DEPTH_BITS: + case GL_DEPTH_CLEAR_VALUE: + case GL_DEPTH_FUNC: + case GL_DEPTH_RANGE: + case GL_DEPTH_TEST: + case GL_DEPTH_WRITEMASK: + case GL_DITHER: + case GL_FRONT_FACE: + case GL_GENERATE_MIPMAP_HINT: + case GL_GREEN_BITS: + case GL_IMPLEMENTATION_COLOR_READ_FORMAT: + case GL_IMPLEMENTATION_COLOR_READ_TYPE: + case GL_LINE_WIDTH: + case GL_PACK_ALIGNMENT: + case GL_POLYGON_OFFSET_FACTOR: + case GL_POLYGON_OFFSET_FILL: + case GL_POLYGON_OFFSET_UNITS: + case GL_RED_BITS: + case GL_SAMPLE_ALPHA_TO_COVERAGE: + case GL_SAMPLE_BUFFERS: + case GL_SAMPLE_COVERAGE: + case GL_SAMPLE_COVERAGE_INVERT: + case GL_SAMPLE_COVERAGE_VALUE: + case GL_SAMPLES: + case GL_SCISSOR_BOX: + case GL_SCISSOR_TEST: + case GL_SHADER_BINARY_FORMATS: + case GL_SHADER_COMPILER: + case GL_STENCIL_BACK_FAIL: + case GL_STENCIL_BACK_FUNC: + case GL_STENCIL_BACK_PASS_DEPTH_FAIL: + case GL_STENCIL_BACK_PASS_DEPTH_PASS: + case GL_STENCIL_BACK_REF: + case GL_STENCIL_BACK_VALUE_MASK: + case GL_STENCIL_BACK_WRITEMASK: + case GL_STENCIL_BITS: + case GL_STENCIL_CLEAR_VALUE: + case GL_STENCIL_FAIL: + case GL_STENCIL_FUNC: + case GL_STENCIL_PASS_DEPTH_FAIL: + case GL_STENCIL_PASS_DEPTH_PASS: + case GL_STENCIL_REF: + case GL_STENCIL_TEST: + case GL_STENCIL_VALUE_MASK: + case GL_STENCIL_WRITEMASK: + case GL_SUBPIXEL_BITS: + case GL_UNPACK_ALIGNMENT: + return false; + default: + break; + } + + if (capabilities_.major_version < 3) { + return false; + } + + switch (pname) { + case GL_COPY_READ_BUFFER_BINDING: + *params = bound_copy_read_buffer_; + return true; + case GL_COPY_WRITE_BUFFER_BINDING: + *params = bound_copy_write_buffer_; + return true; + case GL_MAJOR_VERSION: + *params = capabilities_.major_version; + return true; + case GL_MAX_3D_TEXTURE_SIZE: + *params = capabilities_.max_3d_texture_size; + return true; + case GL_MAX_ARRAY_TEXTURE_LAYERS: + *params = capabilities_.max_array_texture_layers; + return true; + case GL_MAX_COLOR_ATTACHMENTS: + *params = capabilities_.max_color_attachments; + return true; + case GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS: + *params = static_cast( + capabilities_.max_combined_fragment_uniform_components); + return true; + case GL_MAX_COMBINED_UNIFORM_BLOCKS: + *params = capabilities_.max_combined_uniform_blocks; + return true; + case GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS: + *params = static_cast( + capabilities_.max_combined_vertex_uniform_components); + return true; + case GL_MAX_DRAW_BUFFERS: + *params = capabilities_.max_draw_buffers; + return true; + case GL_MAX_ELEMENT_INDEX: + *params = static_cast(capabilities_.max_element_index); + return true; + case GL_MAX_ELEMENTS_INDICES: + *params = capabilities_.max_elements_indices; + return true; + case GL_MAX_ELEMENTS_VERTICES: + *params = capabilities_.max_elements_vertices; + return true; + case GL_MAX_FRAGMENT_INPUT_COMPONENTS: + *params = capabilities_.max_fragment_input_components; + return true; + case GL_MAX_FRAGMENT_UNIFORM_BLOCKS: + *params = capabilities_.max_fragment_uniform_blocks; + return true; + case GL_MAX_FRAGMENT_UNIFORM_COMPONENTS: + *params = capabilities_.max_fragment_uniform_components; + return true; + case GL_MAX_PROGRAM_TEXEL_OFFSET: + *params = capabilities_.max_program_texel_offset; + return true; + case GL_MAX_SAMPLES: + *params = capabilities_.max_samples; + return true; + case GL_MAX_SERVER_WAIT_TIMEOUT: + *params = static_cast(capabilities_.max_server_wait_timeout); + return true; + case GL_MAX_TEXTURE_LOD_BIAS: + *params = static_cast(capabilities_.max_texture_lod_bias); + return true; + case GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS: + *params = capabilities_.max_transform_feedback_interleaved_components; + return true; + case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS: + *params = capabilities_.max_transform_feedback_separate_attribs; + return true; + case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS: + *params = capabilities_.max_transform_feedback_separate_components; + return true; + case GL_MAX_UNIFORM_BLOCK_SIZE: + *params = static_cast(capabilities_.max_uniform_block_size); + return true; + case GL_MAX_UNIFORM_BUFFER_BINDINGS: + *params = capabilities_.max_uniform_buffer_bindings; + return true; + case GL_MAX_VARYING_COMPONENTS: + *params = capabilities_.max_varying_components; + return true; + case GL_MAX_VERTEX_OUTPUT_COMPONENTS: + *params = capabilities_.max_vertex_output_components; + return true; + case GL_MAX_VERTEX_UNIFORM_BLOCKS: + *params = capabilities_.max_vertex_uniform_blocks; + return true; + case GL_MAX_VERTEX_UNIFORM_COMPONENTS: + *params = capabilities_.max_vertex_uniform_components; + return true; + case GL_MIN_PROGRAM_TEXEL_OFFSET: + *params = capabilities_.min_program_texel_offset; + return true; + case GL_MINOR_VERSION: + *params = capabilities_.minor_version; + return true; + case GL_NUM_EXTENSIONS: + UpdateCachedExtensionsIfNeeded(); + *params = cached_extensions_.size(); + return true; + case GL_NUM_PROGRAM_BINARY_FORMATS: + *params = capabilities_.num_program_binary_formats; + return true; + case GL_PACK_SKIP_PIXELS: + *params = pack_skip_pixels_; + return true; + case GL_PACK_SKIP_ROWS: + *params = pack_skip_rows_; + return true; + case GL_PIXEL_PACK_BUFFER_BINDING: + *params = bound_pixel_pack_buffer_; + return true; + case GL_PIXEL_UNPACK_BUFFER_BINDING: + *params = bound_pixel_unpack_buffer_; + return true; + case GL_TRANSFORM_FEEDBACK_BUFFER_BINDING: + *params = bound_transform_feedback_buffer_; + return true; + case GL_UNIFORM_BUFFER_BINDING: + *params = bound_uniform_buffer_; + return true; + case GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT: + *params = capabilities_.uniform_buffer_offset_alignment; + return true; + case GL_UNPACK_SKIP_IMAGES: + *params = unpack_skip_images_; + return true; + case GL_UNPACK_SKIP_PIXELS: + *params = unpack_skip_pixels_; + return true; + case GL_UNPACK_SKIP_ROWS: + *params = unpack_skip_rows_; + return true; + + case GL_DRAW_BUFFER0: + case GL_DRAW_BUFFER1: + case GL_DRAW_BUFFER2: + case GL_DRAW_BUFFER3: + case GL_DRAW_BUFFER4: + case GL_DRAW_BUFFER5: + case GL_DRAW_BUFFER6: + case GL_DRAW_BUFFER7: + case GL_DRAW_BUFFER8: + case GL_DRAW_BUFFER9: + case GL_DRAW_BUFFER10: + case GL_DRAW_BUFFER11: + case GL_DRAW_BUFFER12: + case GL_DRAW_BUFFER13: + case GL_DRAW_BUFFER14: + case GL_DRAW_BUFFER15: + case GL_DRAW_FRAMEBUFFER_BINDING: + case GL_FRAGMENT_SHADER_DERIVATIVE_HINT: + case GL_PACK_ROW_LENGTH: + case GL_PRIMITIVE_RESTART_FIXED_INDEX: + case GL_PROGRAM_BINARY_FORMATS: + case GL_RASTERIZER_DISCARD: + case GL_READ_BUFFER: + case GL_READ_FRAMEBUFFER_BINDING: + case GL_SAMPLER_BINDING: + case GL_TEXTURE_BINDING_2D_ARRAY: + case GL_TEXTURE_BINDING_3D: + case GL_TRANSFORM_FEEDBACK_BINDING: + case GL_TRANSFORM_FEEDBACK_ACTIVE: + case GL_TRANSFORM_FEEDBACK_PAUSED: + case GL_TRANSFORM_FEEDBACK_BUFFER_SIZE: + case GL_TRANSFORM_FEEDBACK_BUFFER_START: + case GL_UNIFORM_BUFFER_SIZE: + case GL_UNIFORM_BUFFER_START: + case GL_UNPACK_IMAGE_HEIGHT: + case GL_UNPACK_ROW_LENGTH: + case GL_VERTEX_ARRAY_BINDING: + return false; + default: + break; + } + + if (capabilities_.minor_version < 1) { + return false; + } + + switch (pname) { + case GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS: + *params = capabilities_.max_atomic_counter_buffer_bindings; + return true; + case GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS: + *params = capabilities_.max_shader_storage_buffer_bindings; + return true; + case GL_ATOMIC_COUNTER_BUFFER_BINDING: + *params = bound_atomic_counter_buffer_; + return true; + case GL_SHADER_STORAGE_BUFFER_BINDING: + *params = bound_shader_storage_buffer_; + return true; + case GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT: + *params = capabilities_.shader_storage_buffer_offset_alignment; + return true; + + case GL_ATOMIC_COUNTER_BUFFER_SIZE: + case GL_ATOMIC_COUNTER_BUFFER_START: + case GL_SHADER_STORAGE_BUFFER_SIZE: + case GL_SHADER_STORAGE_BUFFER_START: + return false; + default: + return false; + } +} +",0,"bool GLES2Implementation::GetHelper(GLenum pname, GLint* params) { + + switch (pname) { + case GL_ACTIVE_TEXTURE: + *params = active_texture_unit_ + GL_TEXTURE0; + return true; + case GL_ARRAY_BUFFER_BINDING: + *params = bound_array_buffer_; + return true; + case GL_ELEMENT_ARRAY_BUFFER_BINDING: + *params = vertex_array_object_manager_->bound_element_array_buffer(); + return true; + case GL_FRAMEBUFFER_BINDING: + *params = bound_framebuffer_; + return true; + case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS: + *params = capabilities_.max_combined_texture_image_units; + return true; + case GL_MAX_CUBE_MAP_TEXTURE_SIZE: + *params = capabilities_.max_cube_map_texture_size; + return true; + case GL_MAX_FRAGMENT_UNIFORM_VECTORS: + *params = capabilities_.max_fragment_uniform_vectors; + return true; + case GL_MAX_RENDERBUFFER_SIZE: + *params = capabilities_.max_renderbuffer_size; + return true; + case GL_MAX_TEXTURE_IMAGE_UNITS: + *params = capabilities_.max_texture_image_units; + return true; + case GL_MAX_TEXTURE_SIZE: + *params = capabilities_.max_texture_size; + return true; + case GL_MAX_VARYING_VECTORS: + *params = capabilities_.max_varying_vectors; + return true; + case GL_MAX_VERTEX_ATTRIBS: + *params = capabilities_.max_vertex_attribs; + return true; + case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS: + *params = capabilities_.max_vertex_texture_image_units; + return true; + case GL_MAX_VERTEX_UNIFORM_VECTORS: + *params = capabilities_.max_vertex_uniform_vectors; + return true; + case GL_MAX_VIEWPORT_DIMS: + if (capabilities_.max_viewport_width > 0 && + capabilities_.max_viewport_height > 0) { + params[0] = capabilities_.max_viewport_width; + params[1] = capabilities_.max_viewport_height; + return true; + } + return false; + case GL_NUM_COMPRESSED_TEXTURE_FORMATS: + *params = capabilities_.num_compressed_texture_formats; + return true; + case GL_NUM_SHADER_BINARY_FORMATS: + *params = capabilities_.num_shader_binary_formats; + return true; + case GL_RENDERBUFFER_BINDING: + *params = bound_renderbuffer_; + return true; + case GL_TEXTURE_BINDING_2D: + *params = texture_units_[active_texture_unit_].bound_texture_2d; + return true; + case GL_TEXTURE_BINDING_CUBE_MAP: + *params = texture_units_[active_texture_unit_].bound_texture_cube_map; + return true; + + case GL_TEXTURE_BINDING_EXTERNAL_OES: + *params = texture_units_[active_texture_unit_].bound_texture_external_oes; + return true; + case GL_TEXTURE_BINDING_RECTANGLE_ARB: + *params = + texture_units_[active_texture_unit_].bound_texture_rectangle_arb; + return true; + case GL_PIXEL_PACK_TRANSFER_BUFFER_BINDING_CHROMIUM: + *params = bound_pixel_pack_transfer_buffer_id_; + return true; + case GL_PIXEL_UNPACK_TRANSFER_BUFFER_BINDING_CHROMIUM: + *params = bound_pixel_unpack_transfer_buffer_id_; + return true; + case GL_READ_FRAMEBUFFER_BINDING: + if (capabilities_.major_version >= 3 || + IsChromiumFramebufferMultisampleAvailable()) { + *params = bound_read_framebuffer_; + return true; + } + break; + case GL_TIMESTAMP_EXT: + *params = base::saturated_cast( + (base::TimeTicks::Now() - base::TimeTicks()).InMicroseconds() * + base::Time::kNanosecondsPerMicrosecond); + return true; + case GL_GPU_DISJOINT_EXT: + *params = static_cast(query_tracker_->CheckAndResetDisjoint()); + return true; + + case GL_VIEWPORT: + if (state_.viewport_width > 0 && state_.viewport_height > 0 && + capabilities_.max_viewport_width > 0 && + capabilities_.max_viewport_height > 0) { + params[0] = state_.viewport_x; + params[1] = state_.viewport_y; + params[2] = + std::min(state_.viewport_width, capabilities_.max_viewport_width); + params[3] = + std::min(state_.viewport_height, capabilities_.max_viewport_height); + return true; + } + return false; + + case GL_ALIASED_LINE_WIDTH_RANGE: + case GL_ALIASED_POINT_SIZE_RANGE: + case GL_ALPHA_BITS: + case GL_BLEND: + case GL_BLEND_COLOR: + case GL_BLEND_DST_ALPHA: + case GL_BLEND_DST_RGB: + case GL_BLEND_EQUATION_ALPHA: + case GL_BLEND_EQUATION_RGB: + case GL_BLEND_SRC_ALPHA: + case GL_BLEND_SRC_RGB: + case GL_BLUE_BITS: + case GL_COLOR_CLEAR_VALUE: + case GL_COLOR_WRITEMASK: + case GL_COMPRESSED_TEXTURE_FORMATS: + case GL_CULL_FACE: + case GL_CULL_FACE_MODE: + case GL_CURRENT_PROGRAM: + case GL_DEPTH_BITS: + case GL_DEPTH_CLEAR_VALUE: + case GL_DEPTH_FUNC: + case GL_DEPTH_RANGE: + case GL_DEPTH_TEST: + case GL_DEPTH_WRITEMASK: + case GL_DITHER: + case GL_FRONT_FACE: + case GL_GENERATE_MIPMAP_HINT: + case GL_GREEN_BITS: + case GL_IMPLEMENTATION_COLOR_READ_FORMAT: + case GL_IMPLEMENTATION_COLOR_READ_TYPE: + case GL_LINE_WIDTH: + case GL_PACK_ALIGNMENT: + case GL_POLYGON_OFFSET_FACTOR: + case GL_POLYGON_OFFSET_FILL: + case GL_POLYGON_OFFSET_UNITS: + case GL_RED_BITS: + case GL_SAMPLE_ALPHA_TO_COVERAGE: + case GL_SAMPLE_BUFFERS: + case GL_SAMPLE_COVERAGE: + case GL_SAMPLE_COVERAGE_INVERT: + case GL_SAMPLE_COVERAGE_VALUE: + case GL_SAMPLES: + case GL_SCISSOR_BOX: + case GL_SCISSOR_TEST: + case GL_SHADER_BINARY_FORMATS: + case GL_SHADER_COMPILER: + case GL_STENCIL_BACK_FAIL: + case GL_STENCIL_BACK_FUNC: + case GL_STENCIL_BACK_PASS_DEPTH_FAIL: + case GL_STENCIL_BACK_PASS_DEPTH_PASS: + case GL_STENCIL_BACK_REF: + case GL_STENCIL_BACK_VALUE_MASK: + case GL_STENCIL_BACK_WRITEMASK: + case GL_STENCIL_BITS: + case GL_STENCIL_CLEAR_VALUE: + case GL_STENCIL_FAIL: + case GL_STENCIL_FUNC: + case GL_STENCIL_PASS_DEPTH_FAIL: + case GL_STENCIL_PASS_DEPTH_PASS: + case GL_STENCIL_REF: + case GL_STENCIL_TEST: + case GL_STENCIL_VALUE_MASK: + case GL_STENCIL_WRITEMASK: + case GL_SUBPIXEL_BITS: + case GL_UNPACK_ALIGNMENT: + return false; + default: + break; + } + + if (capabilities_.major_version < 3) { + return false; + } + + switch (pname) { + case GL_COPY_READ_BUFFER_BINDING: + *params = bound_copy_read_buffer_; + return true; + case GL_COPY_WRITE_BUFFER_BINDING: + *params = bound_copy_write_buffer_; + return true; + case GL_MAJOR_VERSION: + *params = capabilities_.major_version; + return true; + case GL_MAX_3D_TEXTURE_SIZE: + *params = capabilities_.max_3d_texture_size; + return true; + case GL_MAX_ARRAY_TEXTURE_LAYERS: + *params = capabilities_.max_array_texture_layers; + return true; + case GL_MAX_COLOR_ATTACHMENTS: + *params = capabilities_.max_color_attachments; + return true; + case GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS: + *params = static_cast( + capabilities_.max_combined_fragment_uniform_components); + return true; + case GL_MAX_COMBINED_UNIFORM_BLOCKS: + *params = capabilities_.max_combined_uniform_blocks; + return true; + case GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS: + *params = static_cast( + capabilities_.max_combined_vertex_uniform_components); + return true; + case GL_MAX_DRAW_BUFFERS: + *params = capabilities_.max_draw_buffers; + return true; + case GL_MAX_ELEMENT_INDEX: + *params = static_cast(capabilities_.max_element_index); + return true; + case GL_MAX_ELEMENTS_INDICES: + *params = capabilities_.max_elements_indices; + return true; + case GL_MAX_ELEMENTS_VERTICES: + *params = capabilities_.max_elements_vertices; + return true; + case GL_MAX_FRAGMENT_INPUT_COMPONENTS: + *params = capabilities_.max_fragment_input_components; + return true; + case GL_MAX_FRAGMENT_UNIFORM_BLOCKS: + *params = capabilities_.max_fragment_uniform_blocks; + return true; + case GL_MAX_FRAGMENT_UNIFORM_COMPONENTS: + *params = capabilities_.max_fragment_uniform_components; + return true; + case GL_MAX_PROGRAM_TEXEL_OFFSET: + *params = capabilities_.max_program_texel_offset; + return true; + case GL_MAX_SAMPLES: + *params = capabilities_.max_samples; + return true; + case GL_MAX_SERVER_WAIT_TIMEOUT: + *params = static_cast(capabilities_.max_server_wait_timeout); + return true; + case GL_MAX_TEXTURE_LOD_BIAS: + *params = static_cast(capabilities_.max_texture_lod_bias); + return true; + case GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS: + *params = capabilities_.max_transform_feedback_interleaved_components; + return true; + case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS: + *params = capabilities_.max_transform_feedback_separate_attribs; + return true; + case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS: + *params = capabilities_.max_transform_feedback_separate_components; + return true; + case GL_MAX_UNIFORM_BLOCK_SIZE: + *params = static_cast(capabilities_.max_uniform_block_size); + return true; + case GL_MAX_UNIFORM_BUFFER_BINDINGS: + *params = capabilities_.max_uniform_buffer_bindings; + return true; + case GL_MAX_VARYING_COMPONENTS: + *params = capabilities_.max_varying_components; + return true; + case GL_MAX_VERTEX_OUTPUT_COMPONENTS: + *params = capabilities_.max_vertex_output_components; + return true; + case GL_MAX_VERTEX_UNIFORM_BLOCKS: + *params = capabilities_.max_vertex_uniform_blocks; + return true; + case GL_MAX_VERTEX_UNIFORM_COMPONENTS: + *params = capabilities_.max_vertex_uniform_components; + return true; + case GL_MIN_PROGRAM_TEXEL_OFFSET: + *params = capabilities_.min_program_texel_offset; + return true; + case GL_MINOR_VERSION: + *params = capabilities_.minor_version; + return true; + case GL_NUM_EXTENSIONS: + UpdateCachedExtensionsIfNeeded(); + *params = cached_extensions_.size(); + return true; + case GL_NUM_PROGRAM_BINARY_FORMATS: + *params = capabilities_.num_program_binary_formats; + return true; + case GL_PACK_SKIP_PIXELS: + *params = pack_skip_pixels_; + return true; + case GL_PACK_SKIP_ROWS: + *params = pack_skip_rows_; + return true; + case GL_PIXEL_PACK_BUFFER_BINDING: + *params = bound_pixel_pack_buffer_; + return true; + case GL_PIXEL_UNPACK_BUFFER_BINDING: + *params = bound_pixel_unpack_buffer_; + return true; + case GL_TRANSFORM_FEEDBACK_BUFFER_BINDING: + *params = bound_transform_feedback_buffer_; + return true; + case GL_UNIFORM_BUFFER_BINDING: + *params = bound_uniform_buffer_; + return true; + case GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT: + *params = capabilities_.uniform_buffer_offset_alignment; + return true; + case GL_UNPACK_SKIP_IMAGES: + *params = unpack_skip_images_; + return true; + case GL_UNPACK_SKIP_PIXELS: + *params = unpack_skip_pixels_; + return true; + case GL_UNPACK_SKIP_ROWS: + *params = unpack_skip_rows_; + return true; + + case GL_DRAW_BUFFER0: + case GL_DRAW_BUFFER1: + case GL_DRAW_BUFFER2: + case GL_DRAW_BUFFER3: + case GL_DRAW_BUFFER4: + case GL_DRAW_BUFFER5: + case GL_DRAW_BUFFER6: + case GL_DRAW_BUFFER7: + case GL_DRAW_BUFFER8: + case GL_DRAW_BUFFER9: + case GL_DRAW_BUFFER10: + case GL_DRAW_BUFFER11: + case GL_DRAW_BUFFER12: + case GL_DRAW_BUFFER13: + case GL_DRAW_BUFFER14: + case GL_DRAW_BUFFER15: + case GL_DRAW_FRAMEBUFFER_BINDING: + case GL_FRAGMENT_SHADER_DERIVATIVE_HINT: + case GL_PACK_ROW_LENGTH: + case GL_PRIMITIVE_RESTART_FIXED_INDEX: + case GL_PROGRAM_BINARY_FORMATS: + case GL_RASTERIZER_DISCARD: + case GL_READ_BUFFER: + case GL_READ_FRAMEBUFFER_BINDING: + case GL_SAMPLER_BINDING: + case GL_TEXTURE_BINDING_2D_ARRAY: + case GL_TEXTURE_BINDING_3D: + case GL_TRANSFORM_FEEDBACK_BINDING: + case GL_TRANSFORM_FEEDBACK_ACTIVE: + case GL_TRANSFORM_FEEDBACK_PAUSED: + case GL_TRANSFORM_FEEDBACK_BUFFER_SIZE: + case GL_TRANSFORM_FEEDBACK_BUFFER_START: + case GL_UNIFORM_BUFFER_SIZE: + case GL_UNIFORM_BUFFER_START: + case GL_UNPACK_IMAGE_HEIGHT: + case GL_UNPACK_ROW_LENGTH: + case GL_VERTEX_ARRAY_BINDING: + return false; + default: + break; + } + + if (capabilities_.minor_version < 1) { + return false; + } + + switch (pname) { + case GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS: + *params = capabilities_.max_atomic_counter_buffer_bindings; + return true; + case GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS: + *params = capabilities_.max_shader_storage_buffer_bindings; + return true; + case GL_ATOMIC_COUNTER_BUFFER_BINDING: + *params = bound_atomic_counter_buffer_; + return true; + case GL_SHADER_STORAGE_BUFFER_BINDING: + *params = bound_shader_storage_buffer_; + return true; + case GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT: + *params = capabilities_.shader_storage_buffer_offset_alignment; + return true; + + case GL_ATOMIC_COUNTER_BUFFER_SIZE: + case GL_ATOMIC_COUNTER_BUFFER_START: + case GL_SHADER_STORAGE_BUFFER_SIZE: + case GL_SHADER_STORAGE_BUFFER_START: + return false; + default: + return false; + } +} +","@@ -6078,6 +6078,7 @@ void GLES2Implementation::BeginQueryEXT(GLenum target, GLuint id) { + case GL_LATENCY_QUERY_CHROMIUM: + case GL_ASYNC_PIXEL_PACK_COMPLETED_CHROMIUM: + case GL_GET_ERROR_QUERY_CHROMIUM: ++ case GL_PROGRAM_COMPLETION_QUERY_CHROMIUM: + break; + case GL_READBACK_SHADOW_COPIES_UPDATED_CHROMIUM: + case GL_COMMANDS_COMPLETED_CHROMIUM:",2977,3308,4096 +16465,"static int accessPayload( + BtCursor *pCur, /* Cursor pointing to entry to read from */ + u32 offset, /* Begin reading this far into payload */ + u32 amt, /* Read this many bytes */ + unsigned char *pBuf, /* Write the bytes into this buffer */ + int eOp /* zero to read. non-zero to write. */ +){ + unsigned char *aPayload; + int rc = SQLITE_OK; + int iIdx = 0; + MemPage *pPage = pCur->pPage; /* Btree page of current entry */ + BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */ +#ifdef SQLITE_DIRECT_OVERFLOW_READ + unsigned char * const pBufStart = pBuf; /* Start of original out buffer */ +#endif + + assert( pPage ); + assert( eOp==0 || eOp==1 ); + assert( pCur->eState==CURSOR_VALID ); + assert( pCur->ixnCell ); + assert( cursorHoldsMutex(pCur) ); + + getCellInfo(pCur); + aPayload = pCur->info.pPayload; + assert( offset+amt <= pCur->info.nPayload ); + + assert( aPayload > pPage->aData ); + if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){ + /* Trying to read or write past the end of the data is an error. The + ** conditional above is really: + ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] + ** but is recast into its current form to avoid integer overflow problems + */ + return SQLITE_CORRUPT_PAGE(pPage); + } + + /* Check if data must be read/written to/from the btree page itself. */ + if( offsetinfo.nLocal ){ + int a = amt; + if( a+offset>pCur->info.nLocal ){ + a = pCur->info.nLocal - offset; + } + rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage); + offset = 0; + pBuf += a; + amt -= a; + }else{ + offset -= pCur->info.nLocal; + } + + + if( rc==SQLITE_OK && amt>0 ){ + const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */ + Pgno nextPage; + + nextPage = get4byte(&aPayload[pCur->info.nLocal]); + + /* If the BtCursor.aOverflow[] has not been allocated, allocate it now. + ** + ** The aOverflow[] array is sized at one entry for each overflow page + ** in the overflow chain. The page number of the first overflow page is + ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array + ** means ""not yet known"" (the cache is lazily populated). + */ + if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){ + int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize; + if( pCur->aOverflow==0 + || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow) + ){ + Pgno *aNew = (Pgno*)sqlite3Realloc( + pCur->aOverflow, nOvfl*2*sizeof(Pgno) + ); + if( aNew==0 ){ + return SQLITE_NOMEM_BKPT; + }else{ + pCur->aOverflow = aNew; + } + } + memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno)); + pCur->curFlags |= BTCF_ValidOvfl; + }else{ + /* If the overflow page-list cache has been allocated and the + ** entry for the first required overflow page is valid, skip + ** directly to it. + */ + if( pCur->aOverflow[offset/ovflSize] ){ + iIdx = (offset/ovflSize); + nextPage = pCur->aOverflow[iIdx]; + offset = (offset%ovflSize); + } + } + + assert( rc==SQLITE_OK && amt>0 ); + while( nextPage ){ + /* If required, populate the overflow page-list cache. */ + assert( pCur->aOverflow[iIdx]==0 + || pCur->aOverflow[iIdx]==nextPage + || CORRUPT_DB ); + pCur->aOverflow[iIdx] = nextPage; + + if( offset>=ovflSize ){ + /* The only reason to read this page is to obtain the page + ** number for the next page in the overflow chain. The page + ** data is not required. So first try to lookup the overflow + ** page-list cache, if any, then fall back to the getOverflowPage() + ** function. + */ + assert( pCur->curFlags & BTCF_ValidOvfl ); + assert( pCur->pBtree->db==pBt->db ); + if( pCur->aOverflow[iIdx+1] ){ + nextPage = pCur->aOverflow[iIdx+1]; + }else{ + rc = getOverflowPage(pBt, nextPage, 0, &nextPage); + } + offset -= ovflSize; + }else{ + /* Need to read this page properly. It contains some of the + ** range of data that is being read (eOp==0) or written (eOp!=0). + */ + int a = amt; + if( a + offset > ovflSize ){ + a = ovflSize - offset; + } + +#ifdef SQLITE_DIRECT_OVERFLOW_READ + /* If all the following are true: + ** + ** 1) this is a read operation, and + ** 2) data is required from the start of this overflow page, and + ** 3) there are no dirty pages in the page-cache + ** 4) the database is file-backed, and + ** 5) the page is not in the WAL file + ** 6) at least 4 bytes have already been read into the output buffer + ** + ** then data can be read directly from the database file into the + ** output buffer, bypassing the page-cache altogether. This speeds + ** up loading large records that span many overflow pages. + */ + if( eOp==0 /* (1) */ + && offset==0 /* (2) */ + && sqlite3PagerDirectReadOk(pBt->pPager, nextPage) /* (3,4,5) */ + && &pBuf[-4]>=pBufStart /* (6) */ + ){ + sqlite3_file *fd = sqlite3PagerFile(pBt->pPager); + u8 aSave[4]; + u8 *aWrite = &pBuf[-4]; + assert( aWrite>=pBufStart ); /* due to (6) */ + memcpy(aSave, aWrite, 4); + rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1)); + nextPage = get4byte(aWrite); + memcpy(aWrite, aSave, 4); + }else +#endif + + { + DbPage *pDbPage; + rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage, + (eOp==0 ? PAGER_GET_READONLY : 0) + ); + if( rc==SQLITE_OK ){ + aPayload = sqlite3PagerGetData(pDbPage); + nextPage = get4byte(aPayload); + rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage); + sqlite3PagerUnref(pDbPage); + offset = 0; + } + } + amt -= a; + if( amt==0 ) return rc; + pBuf += a; + } + if( rc ) break; + iIdx++; + } + } + + if( rc==SQLITE_OK && amt>0 ){ + /* Overflow chain ends prematurely */ + return SQLITE_CORRUPT_PAGE(pPage); + } + return rc; +} +",0,"static int accessPayload( + BtCursor *pCur, /* Cursor pointing to entry to read from */ + u32 offset, /* Begin reading this far into payload */ + u32 amt, /* Read this many bytes */ + unsigned char *pBuf, /* Write the bytes into this buffer */ + int eOp /* zero to read. non-zero to write. */ +){ + unsigned char *aPayload; + int rc = SQLITE_OK; + int iIdx = 0; + MemPage *pPage = pCur->pPage; /* Btree page of current entry */ + BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */ +#ifdef SQLITE_DIRECT_OVERFLOW_READ + unsigned char * const pBufStart = pBuf; /* Start of original out buffer */ +#endif + + assert( pPage ); + assert( eOp==0 || eOp==1 ); + assert( pCur->eState==CURSOR_VALID ); + assert( pCur->ixnCell ); + assert( cursorHoldsMutex(pCur) ); + + getCellInfo(pCur); + aPayload = pCur->info.pPayload; + assert( offset+amt <= pCur->info.nPayload ); + + assert( aPayload > pPage->aData ); + if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){ + /* Trying to read or write past the end of the data is an error. The + ** conditional above is really: + ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] + ** but is recast into its current form to avoid integer overflow problems + */ + return SQLITE_CORRUPT_PAGE(pPage); + } + + /* Check if data must be read/written to/from the btree page itself. */ + if( offsetinfo.nLocal ){ + int a = amt; + if( a+offset>pCur->info.nLocal ){ + a = pCur->info.nLocal - offset; + } + rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage); + offset = 0; + pBuf += a; + amt -= a; + }else{ + offset -= pCur->info.nLocal; + } + + + if( rc==SQLITE_OK && amt>0 ){ + const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */ + Pgno nextPage; + + nextPage = get4byte(&aPayload[pCur->info.nLocal]); + + /* If the BtCursor.aOverflow[] has not been allocated, allocate it now. + ** + ** The aOverflow[] array is sized at one entry for each overflow page + ** in the overflow chain. The page number of the first overflow page is + ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array + ** means ""not yet known"" (the cache is lazily populated). + */ + if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){ + int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize; + if( pCur->aOverflow==0 + || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow) + ){ + Pgno *aNew = (Pgno*)sqlite3Realloc( + pCur->aOverflow, nOvfl*2*sizeof(Pgno) + ); + if( aNew==0 ){ + return SQLITE_NOMEM_BKPT; + }else{ + pCur->aOverflow = aNew; + } + } + memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno)); + pCur->curFlags |= BTCF_ValidOvfl; + }else{ + /* If the overflow page-list cache has been allocated and the + ** entry for the first required overflow page is valid, skip + ** directly to it. + */ + if( pCur->aOverflow[offset/ovflSize] ){ + iIdx = (offset/ovflSize); + nextPage = pCur->aOverflow[iIdx]; + offset = (offset%ovflSize); + } + } + + assert( rc==SQLITE_OK && amt>0 ); + while( nextPage ){ + /* If required, populate the overflow page-list cache. */ + assert( pCur->aOverflow[iIdx]==0 + || pCur->aOverflow[iIdx]==nextPage + || CORRUPT_DB ); + pCur->aOverflow[iIdx] = nextPage; + + if( offset>=ovflSize ){ + /* The only reason to read this page is to obtain the page + ** number for the next page in the overflow chain. The page + ** data is not required. So first try to lookup the overflow + ** page-list cache, if any, then fall back to the getOverflowPage() + ** function. + */ + assert( pCur->curFlags & BTCF_ValidOvfl ); + assert( pCur->pBtree->db==pBt->db ); + if( pCur->aOverflow[iIdx+1] ){ + nextPage = pCur->aOverflow[iIdx+1]; + }else{ + rc = getOverflowPage(pBt, nextPage, 0, &nextPage); + } + offset -= ovflSize; + }else{ + /* Need to read this page properly. It contains some of the + ** range of data that is being read (eOp==0) or written (eOp!=0). + */ + int a = amt; + if( a + offset > ovflSize ){ + a = ovflSize - offset; + } + +#ifdef SQLITE_DIRECT_OVERFLOW_READ + /* If all the following are true: + ** + ** 1) this is a read operation, and + ** 2) data is required from the start of this overflow page, and + ** 3) there are no dirty pages in the page-cache + ** 4) the database is file-backed, and + ** 5) the page is not in the WAL file + ** 6) at least 4 bytes have already been read into the output buffer + ** + ** then data can be read directly from the database file into the + ** output buffer, bypassing the page-cache altogether. This speeds + ** up loading large records that span many overflow pages. + */ + if( eOp==0 /* (1) */ + && offset==0 /* (2) */ + && sqlite3PagerDirectReadOk(pBt->pPager, nextPage) /* (3,4,5) */ + && &pBuf[-4]>=pBufStart /* (6) */ + ){ + sqlite3_file *fd = sqlite3PagerFile(pBt->pPager); + u8 aSave[4]; + u8 *aWrite = &pBuf[-4]; + assert( aWrite>=pBufStart ); /* due to (6) */ + memcpy(aSave, aWrite, 4); + rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1)); + nextPage = get4byte(aWrite); + memcpy(aWrite, aSave, 4); + }else +#endif + + { + DbPage *pDbPage; + rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage, + (eOp==0 ? PAGER_GET_READONLY : 0) + ); + if( rc==SQLITE_OK ){ + aPayload = sqlite3PagerGetData(pDbPage); + nextPage = get4byte(aPayload); + rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage); + sqlite3PagerUnref(pDbPage); + offset = 0; + } + } + amt -= a; + if( amt==0 ) return rc; + pBuf += a; + } + if( rc ) break; + iIdx++; + } + } + + if( rc==SQLITE_OK && amt>0 ){ + /* Overflow chain ends prematurely */ + return SQLITE_CORRUPT_PAGE(pPage); + } + return rc; +} +","@@ -31668,7 +31668,7 @@ SQLITE_PRIVATE VList *sqlite3VListAdd( + assert( pIn==0 || pIn[0]>=3 ); /* Verify ok to add new elements */ + if( pIn==0 || pIn[1]+nInt > pIn[0] ){ + /* Enlarge the allocation */ +- int nAlloc = (pIn ? pIn[0]*2 : 10) + nInt; ++ sqlite3_int64 nAlloc = (pIn ? 2*(sqlite3_int64)pIn[0] : 10) + nInt; + VList *pOut = sqlite3DbRealloc(db, pIn, nAlloc*sizeof(int)); + if( pOut==0 ) return pIn; + if( pIn==0 ) pOut[1] = 2; +@@ -76266,9 +76266,11 @@ static int growOpArray(Vdbe *v, int nOp){ + ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current + ** size of the op array or add 1KB of space, whichever is smaller. */ + #ifdef SQLITE_TEST_REALLOC_STRESS +- int nNew = (v->nOpAlloc>=512 ? v->nOpAlloc*2 : v->nOpAlloc+nOp); ++ sqlite3_int64 nNew = (v->nOpAlloc>=512 ? 2*(sqlite3_int64)v->nOpAlloc ++ : (sqlite3_int64)v->nOpAlloc+nOp); + #else +- int nNew = (v->nOpAlloc ? v->nOpAlloc*2 : (int)(1024/sizeof(Op))); ++ sqlite3_int64 nNew = (v->nOpAlloc ? 2*(sqlite3_int64)v->nOpAlloc ++ : (sqlite3_int64)1024/sizeof(Op)); + UNUSED_PARAMETER(nOp); + #endif + +@@ -77055,7 +77057,7 @@ SQLITE_PRIVATE void sqlite3VdbeScanStatus( + LogEst nEst, /* Estimated number of output rows */ + const char *zName /* Name of table or index being scanned */ + ){ +- int nByte = (p->nScan+1) * sizeof(ScanStatus); ++ sqlite3_int64 nByte = (p->nScan+1) * sizeof(ScanStatus); + ScanStatus *aNew; + aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte); + if( aNew ){ +@@ -92025,7 +92027,7 @@ static int vdbePmaReadBlob( + /* Extend the p->aAlloc[] allocation if required. */ + if( p->nAllocnAlloc*2); ++ sqlite3_int64 nNew = MAX(128, 2*(sqlite3_int64)p->nAlloc); + while( nByte>nNew ) nNew = nNew*2; + aNew = sqlite3Realloc(p->aAlloc, nNew); + if( !aNew ) return SQLITE_NOMEM_BKPT; +@@ -93317,7 +93319,7 @@ SQLITE_PRIVATE int sqlite3VdbeSorterWrite( + if( nMin>pSorter->nMemory ){ + u8 *aNew; + int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory; +- int nNew = pSorter->nMemory * 2; ++ sqlite3_int64 nNew = 2 * (sqlite3_int64)pSorter->nMemory; + while( nNew < nMin ) nNew = nNew*2; + if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize; + if( nNew < nMin ) nNew = nMin; +@@ -98229,7 +98231,7 @@ SQLITE_PRIVATE ExprList *sqlite3ExprListAppend( + }else if( (pList->nExpr & (pList->nExpr-1))==0 ){ + ExprList *pNew; + pNew = sqlite3DbRealloc(db, pList, +- sizeof(*pList)+(2*pList->nExpr - 1)*sizeof(pList->a[0])); ++ sizeof(*pList)+(2*(sqlite3_int64)pList->nExpr-1)*sizeof(pList->a[0])); + if( pNew==0 ){ + goto no_mem; + } +@@ -110336,9 +110338,9 @@ SQLITE_PRIVATE void *sqlite3ArrayAllocate( + int *pIdx /* Write the index of a new slot here */ + ){ + char *z; +- int n = *pnEntry; ++ sqlite3_int64 n = *pnEntry; + if( (n & (n-1))==0 ){ +- int sz = (n==0) ? 1 : 2*n; ++ sqlite3_int64 sz = (n==0) ? 1 : 2*n; + void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry); + if( pNew==0 ){ + *pIdx = -1; +@@ -110459,7 +110461,7 @@ SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge( + /* Allocate additional space if needed */ + if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){ + SrcList *pNew; +- int nAlloc = pSrc->nSrc*2+nExtra; ++ sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra; + sqlite3 *db = pParse->db; + + if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){ +@@ -111215,7 +111217,7 @@ SQLITE_PRIVATE With *sqlite3WithAdd( + } + + if( pWith ){ +- int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte); ++ sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte); + pNew = sqlite3DbRealloc(db, pWith, nByte); + }else{ + pNew = sqlite3DbMallocZero(db, sizeof(*pWith)); +@@ -134301,9 +134303,13 @@ SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){ + ** string will be freed automatically when the table is + ** deleted. + */ +-static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){ +- int nBytes = sizeof(char *)*(2+pTable->nModuleArg); ++static void addModuleArgument(Parse *pParse, Table *pTable, char *zArg){ ++ sqlite3_int64 nBytes = sizeof(char *)*(2+pTable->nModuleArg); + char **azModuleArg; ++ sqlite3 *db = pParse->db; ++ if( pTable->nModuleArg+3>=db->aLimit[SQLITE_LIMIT_COLUMN] ){ ++ sqlite3ErrorMsg(pParse, ""too many columns on %s"", pTable->zName); ++ } + azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes); + if( azModuleArg==0 ){ + sqlite3DbFree(db, zArg); +@@ -134338,9 +134344,9 @@ SQLITE_PRIVATE void sqlite3VtabBeginParse( + db = pParse->db; + + assert( pTable->nModuleArg==0 ); +- addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName)); +- addModuleArgument(db, pTable, 0); +- addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName)); ++ addModuleArgument(pParse, pTable, sqlite3NameFromToken(db, pModuleName)); ++ addModuleArgument(pParse, pTable, 0); ++ addModuleArgument(pParse, pTable, sqlite3DbStrDup(db, pTable->zName)); + assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0) + || (pParse->sNameToken.z==pName1->z && pName2->z==0) + ); +@@ -134373,7 +134379,7 @@ static void addArgumentToVtab(Parse *pParse){ + const char *z = (const char*)pParse->sArg.z; + int n = pParse->sArg.n; + sqlite3 *db = pParse->db; +- addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n)); ++ addModuleArgument(pParse, pParse->pNewTable, sqlite3DbStrNDup(db, z, n)); + } + } + +@@ -134662,7 +134668,8 @@ static int growVTrans(sqlite3 *db){ + /* Grow the sqlite3.aVTrans array if required */ + if( (db->nVTrans%ARRAY_INCR)==0 ){ + VTable **aVTrans; +- int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR); ++ sqlite3_int64 nBytes = sizeof(sqlite3_vtab*)* ++ ((sqlite3_int64)db->nVTrans + ARRAY_INCR); + aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes); + if( !aVTrans ){ + return SQLITE_NOMEM_BKPT; +@@ -135158,9 +135165,9 @@ SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *pParse, Module *pMod){ + pTab->pSchema = db->aDb[0].pSchema; + assert( pTab->nModuleArg==0 ); + pTab->iPKey = -1; +- addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName)); +- addModuleArgument(db, pTab, 0); +- addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName)); ++ addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName)); ++ addModuleArgument(pParse, pTab, 0); ++ addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName)); + rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr); + if( rc ){ + sqlite3ErrorMsg(pParse, ""%s"", zErr); +@@ -153996,7 +154003,7 @@ static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){ + pStart = 0; + }else if( pBuf==0 ){ + sqlite3BeginBenignMalloc(); +- pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */ ++ pStart = sqlite3Malloc( sz*(sqlite3_int64)cnt ); /* IMP: R-61949-35727 */ + sqlite3EndBenignMalloc(); + if( pStart ) cnt = sqlite3MallocSize(pStart)/sz; + }else{ +@@ -168038,8 +168045,8 @@ SQLITE_PRIVATE int sqlite3Fts3InitTokenizer( + int iArg = 0; + z = &z[n+1]; + while( zzInput = sqlite3_malloc(nByte+1); ++ pCsr->zInput = sqlite3_malloc64(nByte+1); + if( pCsr->zInput==0 ){ + rc = SQLITE_NOMEM; + }else{ +@@ -170808,8 +170815,9 @@ SQLITE_PRIVATE int sqlite3Fts3SegReaderPending( + } + + if( nElem>0 ){ +- int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *); +- pReader = (Fts3SegReader *)sqlite3_malloc(nByte); ++ sqlite3_int64 nByte; ++ nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *); ++ pReader = (Fts3SegReader *)sqlite3_malloc64(nByte); + if( !pReader ){ + rc = SQLITE_NOMEM; + }else{ +@@ -172421,7 +172429,7 @@ static void fts3InsertDocsize( + int rc; /* Result code from subfunctions */ + + if( *pRC ) return; +- pBlob = sqlite3_malloc( 10*p->nColumn ); ++ pBlob = sqlite3_malloc64( 10*(sqlite3_int64)p->nColumn ); + if( pBlob==0 ){ + *pRC = SQLITE_NOMEM; + return; +@@ -172471,7 +172479,7 @@ static void fts3UpdateDocTotals( + const int nStat = p->nColumn+2; + + if( *pRC ) return; +- a = sqlite3_malloc( (sizeof(u32)+10)*nStat ); ++ a = sqlite3_malloc64( (sizeof(u32)+10)*(sqlite3_int64)nStat ); + if( a==0 ){ + *pRC = SQLITE_NOMEM; + return; +@@ -172592,8 +172600,8 @@ static int fts3DoRebuild(Fts3Table *p){ + } + + if( rc==SQLITE_OK ){ +- int nByte = sizeof(u32) * (p->nColumn+1)*3; +- aSz = (u32 *)sqlite3_malloc(nByte); ++ sqlite3_int64 nByte = sizeof(u32) * ((sqlite3_int64)p->nColumn+1)*3; ++ aSz = (u32 *)sqlite3_malloc64(nByte); + if( aSz==0 ){ + rc = SQLITE_NOMEM; + }else{ +@@ -172659,12 +172667,12 @@ static int fts3IncrmergeCsr( + ){ + int rc; /* Return Code */ + sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */ +- int nByte; /* Bytes allocated at pCsr->apSegment[] */ ++ sqlite3_int64 nByte; /* Bytes allocated at pCsr->apSegment[] */ + + /* Allocate space for the Fts3MultiSegReader.aCsr[] array */ + memset(pCsr, 0, sizeof(*pCsr)); + nByte = sizeof(Fts3SegReader *) * nSeg; +- pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte); ++ pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc64(nByte); + + if( pCsr->apSegment==0 ){ + rc = SQLITE_NOMEM; +@@ -174644,7 +174652,7 @@ SQLITE_PRIVATE int sqlite3Fts3UpdateMethod( + } + + /* Allocate space to hold the change in document sizes */ +- aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 ); ++ aSzDel = sqlite3_malloc64(sizeof(aSzDel[0])*((sqlite3_int64)p->nColumn+1)*2); + if( aSzDel==0 ){ + rc = SQLITE_NOMEM; + goto update_out; +@@ -174900,10 +174908,11 @@ struct StrBuffer { + */ + static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){ + MatchinfoBuffer *pRet; +- int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer); +- int nStr = (int)strlen(zMatchinfo); ++ sqlite3_int64 nByte = sizeof(u32) * (2*(sqlite3_int64)nElem + 1) ++ + sizeof(MatchinfoBuffer); ++ sqlite3_int64 nStr = strlen(zMatchinfo); + +- pRet = sqlite3_malloc(nByte + nStr+1); ++ pRet = sqlite3_malloc64(nByte + nStr+1); + if( pRet ){ + memset(pRet, 0, nByte); + pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet; +@@ -184388,7 +184397,7 @@ static GeoPoly *geopolyParseJson(const unsigned char *z, int *pRc){ + GeoPoly *pOut; + int x = 1; + s.nVertex--; /* Remove the redundant vertex at the end */ +- pOut = sqlite3_malloc64( GEOPOLY_SZ(s.nVertex) ); ++ pOut = sqlite3_malloc64( GEOPOLY_SZ((sqlite3_int64)s.nVertex) ); + x = 1; + if( pOut==0 ) goto parse_json_err; + pOut->nVertex = s.nVertex; +@@ -184774,7 +184783,7 @@ static GeoPoly *geopolyBBox( + if( pRc ) *pRc = SQLITE_OK; + if( aCoord==0 ){ + geopolyBboxFill: +- pOut = sqlite3_realloc(p, GEOPOLY_SZ(4)); ++ pOut = sqlite3_realloc64(p, GEOPOLY_SZ(4)); + if( pOut==0 ){ + sqlite3_free(p); + if( context ) sqlite3_result_error_nomem(context); +@@ -185170,9 +185179,9 @@ static GeoSegment *geopolySortSegmentsByYAndC(GeoSegment *pList){ + ** Determine the overlap between two polygons + */ + static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2){ +- int nVertex = p1->nVertex + p2->nVertex + 2; ++ sqlite3_int64 nVertex = p1->nVertex + p2->nVertex + 2; + GeoOverlap *p; +- int nByte; ++ sqlite3_int64 nByte; + GeoEvent *pThisEvent; + double rX; + int rc = 0; +@@ -185184,7 +185193,7 @@ static int geopolyOverlap(GeoPoly *p1, GeoPoly *p2){ + nByte = sizeof(GeoEvent)*nVertex*2 + + sizeof(GeoSegment)*nVertex + + sizeof(GeoOverlap); +- p = sqlite3_malloc( nByte ); ++ p = sqlite3_malloc64( nByte ); + if( p==0 ) return -1; + p->aEvent = (GeoEvent*)&p[1]; + p->aSegment = (GeoSegment*)&p->aEvent[nVertex*2]; +@@ -185343,18 +185352,18 @@ static int geopolyInit( + ){ + int rc = SQLITE_OK; + Rtree *pRtree; +- int nDb; /* Length of string argv[1] */ +- int nName; /* Length of string argv[2] */ ++ sqlite3_int64 nDb; /* Length of string argv[1] */ ++ sqlite3_int64 nName; /* Length of string argv[2] */ + sqlite3_str *pSql; + char *zSql; + int ii; + + sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1); + + /* Allocate the sqlite3_vtab structure */ +- nDb = (int)strlen(argv[1]); +- nName = (int)strlen(argv[2]); +- pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2); ++ nDb = strlen(argv[1]); ++ nName = strlen(argv[2]); ++ pRtree = (Rtree *)sqlite3_malloc64(sizeof(Rtree)+nDb+nName+2); + if( !pRtree ){ + return SQLITE_NOMEM; + } +@@ -218315,7 +218324,7 @@ static int fts5UnicodeCreate( + + p->eRemoveDiacritic = FTS5_REMOVE_DIACRITICS_SIMPLE; + p->nFold = 64; +- p->aFold = sqlite3_malloc(p->nFold * sizeof(char)); ++ p->aFold = sqlite3_malloc64(p->nFold * sizeof(char)); + if( p->aFold==0 ){ + rc = SQLITE_NOMEM; + } +@@ -221434,7 +221443,7 @@ SQLITE_API int sqlite3_stmt_init( + #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_STMTVTAB) */ + + /************** End of stmt.c ************************************************/ +-#if __LINE__!=221437 ++#if __LINE__!=221446 + #undef SQLITE_SOURCE_ID + #define SQLITE_SOURCE_ID ""2019-02-25 16:06:06 bd49a8271d650fa89e446b42e513b595a717b9212c91dd384aab871fc1d0alt2"" + #endif",1829,2160,4096 +17787,"static bool ldb_dn_explode(struct ldb_dn *dn) +{ + char *p, *ex_name = NULL, *ex_value = NULL, *data, *d, *dt, *t; + bool trim = true; + bool in_extended = true; + bool in_ex_name = false; + bool in_ex_value = false; + bool in_attr = false; + bool in_value = false; + bool in_quote = false; + bool is_oid = false; + bool escape = false; + unsigned int x; + size_t l = 0; + int ret; + char *parse_dn; + bool is_index; + + if ( ! dn || dn->invalid) return false; + + if (dn->components) { + return true; + } + + if (dn->ext_linearized) { + parse_dn = dn->ext_linearized; + } else { + parse_dn = dn->linearized; + } + + if ( ! parse_dn ) { + return false; + } + + is_index = (strncmp(parse_dn, ""DN=@INDEX:"", 10) == 0); + + /* Empty DNs */ + if (parse_dn[0] == '\0') { + return true; + } + + /* Special DNs case */ + if (dn->special) { + return true; + } + + /* make sure we free this if allocated previously before replacing */ + LDB_FREE(dn->components); + dn->comp_num = 0; + + LDB_FREE(dn->ext_components); + dn->ext_comp_num = 0; + + /* in the common case we have 3 or more components */ + /* make sure all components are zeroed, other functions depend on it */ + dn->components = talloc_zero_array(dn, struct ldb_dn_component, 3); + if ( ! dn->components) { + return false; + } + + /* Components data space is allocated here once */ + data = talloc_array(dn->components, char, strlen(parse_dn) + 1); + if (!data) { + return false; + } + + p = parse_dn; + t = NULL; + d = dt = data; + + while (*p) { + if (in_extended) { + + if (!in_ex_name && !in_ex_value) { + + if (p[0] == '<') { + p++; + ex_name = d; + in_ex_name = true; + continue; + } else if (p[0] == '\0') { + p++; + continue; + } else { + in_extended = false; + in_attr = true; + dt = d; + + continue; + } + } + + if (in_ex_name && *p == '=') { + *d++ = '\0'; + p++; + ex_value = d; + in_ex_name = false; + in_ex_value = true; + continue; + } + + if (in_ex_value && *p == '>') { + const struct ldb_dn_extended_syntax *ext_syntax; + struct ldb_val ex_val = { + .data = (uint8_t *)ex_value, + .length = d - ex_value + }; + + *d++ = '\0'; + p++; + in_ex_value = false; + + /* Process name and ex_value */ + + dn->ext_components = talloc_realloc(dn, + dn->ext_components, + struct ldb_dn_ext_component, + dn->ext_comp_num + 1); + if ( ! dn->ext_components) { + /* ouch ! */ + goto failed; + } + + ext_syntax = ldb_dn_extended_syntax_by_name(dn->ldb, ex_name); + if (!ext_syntax) { + /* We don't know about this type of extended DN */ + goto failed; + } + + dn->ext_components[dn->ext_comp_num].name = talloc_strdup(dn->ext_components, ex_name); + if (!dn->ext_components[dn->ext_comp_num].name) { + /* ouch */ + goto failed; + } + ret = ext_syntax->read_fn(dn->ldb, dn->ext_components, + &ex_val, &dn->ext_components[dn->ext_comp_num].value); + if (ret != LDB_SUCCESS) { + ldb_dn_mark_invalid(dn); + goto failed; + } + + dn->ext_comp_num++; + + if (*p == '\0') { + /* We have reached the end (extended component only)! */ + talloc_free(data); + return true; + + } else if (*p == ';') { + p++; + continue; + } else { + ldb_dn_mark_invalid(dn); + goto failed; + } + } + + *d++ = *p++; + continue; + } + if (in_attr) { + if (trim) { + if (*p == ' ') { + p++; + continue; + } + + /* first char */ + trim = false; + + if (!isascii(*p)) { + /* attr names must be ascii only */ + ldb_dn_mark_invalid(dn); + goto failed; + } + + if (isdigit(*p)) { + is_oid = true; + } else + if ( ! isalpha(*p)) { + /* not a digit nor an alpha, + * invalid attribute name */ + ldb_dn_mark_invalid(dn); + goto failed; + } + + /* Copy this character across from parse_dn, + * now we have trimmed out spaces */ + *d++ = *p++; + continue; + } + + if (*p == ' ') { + p++; + /* valid only if we are at the end */ + trim = true; + continue; + } + + if (trim && (*p != '=')) { + /* spaces/tabs are not allowed */ + ldb_dn_mark_invalid(dn); + goto failed; + } + + if (*p == '=') { + /* attribute terminated */ + in_attr = false; + in_value = true; + trim = true; + l = 0; + + /* Terminate this string in d + * (which is a copy of parse_dn + * with spaces trimmed) */ + *d++ = '\0'; + dn->components[dn->comp_num].name = talloc_strdup(dn->components, dt); + if ( ! dn->components[dn->comp_num].name) { + /* ouch */ + goto failed; + } + + dt = d; + + p++; + continue; + } + + if (!isascii(*p)) { + /* attr names must be ascii only */ + ldb_dn_mark_invalid(dn); + goto failed; + } + + if (is_oid && ( ! (isdigit(*p) || (*p == '.')))) { + /* not a digit nor a dot, + * invalid attribute oid */ + ldb_dn_mark_invalid(dn); + goto failed; + } else + if ( ! (isalpha(*p) || isdigit(*p) || (*p == '-'))) { + /* not ALPHA, DIGIT or HYPHEN */ + ldb_dn_mark_invalid(dn); + goto failed; + } + + *d++ = *p++; + continue; + } + + if (in_value) { + if (in_quote) { + if (*p == '\""') { + if (p[-1] != '\\') { + p++; + in_quote = false; + continue; + } + } + *d++ = *p++; + l++; + continue; + } + + if (trim) { + if (*p == ' ') { + p++; + continue; + } + + /* first char */ + trim = false; + + if (*p == '\""') { + in_quote = true; + p++; + continue; + } + } + + switch (*p) { + + /* TODO: support ber encoded values + case '#': + */ + + case ',': + if (escape) { + *d++ = *p++; + l++; + escape = false; + continue; + } + /* ok found value terminator */ + + if ( t ) { + /* trim back */ + d -= (p - t); + l -= (p - t); + } + + in_attr = true; + in_value = false; + trim = true; + + p++; + *d++ = '\0'; + dn->components[dn->comp_num].value.data = (uint8_t *)talloc_strdup(dn->components, dt); + dn->components[dn->comp_num].value.length = l; + if ( ! dn->components[dn->comp_num].value.data) { + /* ouch ! */ + goto failed; + } + + dt = d; + + dn->components, + struct ldb_dn_component, + dn->comp_num + 1); + if ( ! dn->components) { + /* ouch ! */ + goto failed; + } + /* make sure all components are zeroed, other functions depend on this */ + memset(&dn->components[dn->comp_num], '\0', sizeof(struct ldb_dn_component)); + } + + continue; + + case '+': + case '=': + /* to main compatibility with earlier + versions of ldb indexing, we have to + accept the base64 encoded binary index + values, which contain a '+' or '=' + which should normally be escaped */ + if (is_index) { + if ( t ) t = NULL; + *d++ = *p++; + l++; + break; + } + /* fall through */ + case '\""': + case '<': + case '>': + case ';': + /* a string with not escaped specials is invalid (tested) */ + if ( ! escape) { + ldb_dn_mark_invalid(dn); + goto failed; + } + escape = false; + + *d++ = *p++; + l++; + + if ( t ) t = NULL; + break; + + case '\\': + if ( ! escape) { + escape = true; + p++; + continue; + } + escape = false; + + *d++ = *p++; + l++; + + if ( t ) t = NULL; + break; + + default: + if (escape) { + if (isxdigit(p[0]) && isxdigit(p[1])) { + if (sscanf(p, ""%02x"", &x) != 1) { + /* invalid escaping sequence */ + ldb_dn_mark_invalid(dn); + goto failed; + } + p += 2; + *d++ = (unsigned char)x; + } else { + *d++ = *p++; + } + + escape = false; + l++; + if ( t ) t = NULL; + break; + } + + if (*p == ' ') { + if ( ! t) t = p; + } else { + if ( t ) t = NULL; + } + + *d++ = *p++; + l++; + + break; + } + + } + } +",1,"static bool ldb_dn_explode(struct ldb_dn *dn) +{ + char *p, *ex_name = NULL, *ex_value = NULL, *data, *d, *dt, *t; + bool trim = true; + bool in_extended = true; + bool in_ex_name = false; + bool in_ex_value = false; + bool in_attr = false; + bool in_value = false; + bool in_quote = false; + bool is_oid = false; + bool escape = false; + unsigned int x; + size_t l = 0; + int ret; + char *parse_dn; + bool is_index; + + if ( ! dn || dn->invalid) return false; + + if (dn->components) { + return true; + } + + if (dn->ext_linearized) { + parse_dn = dn->ext_linearized; + } else { + parse_dn = dn->linearized; + } + + if ( ! parse_dn ) { + return false; + } + + is_index = (strncmp(parse_dn, ""DN=@INDEX:"", 10) == 0); + + /* Empty DNs */ + if (parse_dn[0] == '\0') { + return true; + } + + /* Special DNs case */ + if (dn->special) { + return true; + } + + /* make sure we free this if allocated previously before replacing */ + LDB_FREE(dn->components); + dn->comp_num = 0; + + LDB_FREE(dn->ext_components); + dn->ext_comp_num = 0; + + /* in the common case we have 3 or more components */ + /* make sure all components are zeroed, other functions depend on it */ + dn->components = talloc_zero_array(dn, struct ldb_dn_component, 3); + if ( ! dn->components) { + return false; + } + + /* Components data space is allocated here once */ + data = talloc_array(dn->components, char, strlen(parse_dn) + 1); + if (!data) { + return false; + } + + p = parse_dn; + t = NULL; + d = dt = data; + + while (*p) { + if (in_extended) { + + if (!in_ex_name && !in_ex_value) { + + if (p[0] == '<') { + p++; + ex_name = d; + in_ex_name = true; + continue; + } else if (p[0] == '\0') { + p++; + continue; + } else { + in_extended = false; + in_attr = true; + dt = d; + + continue; + } + } + + if (in_ex_name && *p == '=') { + *d++ = '\0'; + p++; + ex_value = d; + in_ex_name = false; + in_ex_value = true; + continue; + } + + if (in_ex_value && *p == '>') { + const struct ldb_dn_extended_syntax *ext_syntax; + struct ldb_val ex_val = { + .data = (uint8_t *)ex_value, + .length = d - ex_value + }; + + *d++ = '\0'; + p++; + in_ex_value = false; + + /* Process name and ex_value */ + + dn->ext_components = talloc_realloc(dn, + dn->ext_components, + struct ldb_dn_ext_component, + dn->ext_comp_num + 1); + if ( ! dn->ext_components) { + /* ouch ! */ + goto failed; + } + + ext_syntax = ldb_dn_extended_syntax_by_name(dn->ldb, ex_name); + if (!ext_syntax) { + /* We don't know about this type of extended DN */ + goto failed; + } + + dn->ext_components[dn->ext_comp_num].name = talloc_strdup(dn->ext_components, ex_name); + if (!dn->ext_components[dn->ext_comp_num].name) { + /* ouch */ + goto failed; + } + ret = ext_syntax->read_fn(dn->ldb, dn->ext_components, + &ex_val, &dn->ext_components[dn->ext_comp_num].value); + if (ret != LDB_SUCCESS) { + ldb_dn_mark_invalid(dn); + goto failed; + } + + dn->ext_comp_num++; + + if (*p == '\0') { + /* We have reached the end (extended component only)! */ + talloc_free(data); + return true; + + } else if (*p == ';') { + p++; + continue; + } else { + ldb_dn_mark_invalid(dn); + goto failed; + } + } + + *d++ = *p++; + continue; + } + if (in_attr) { + if (trim) { + if (*p == ' ') { + p++; + continue; + } + + /* first char */ + trim = false; + + if (!isascii(*p)) { + /* attr names must be ascii only */ + ldb_dn_mark_invalid(dn); + goto failed; + } + + if (isdigit(*p)) { + is_oid = true; + } else + if ( ! isalpha(*p)) { + /* not a digit nor an alpha, + * invalid attribute name */ + ldb_dn_mark_invalid(dn); + goto failed; + } + + /* Copy this character across from parse_dn, + * now we have trimmed out spaces */ + *d++ = *p++; + continue; + } + + if (*p == ' ') { + p++; + /* valid only if we are at the end */ + trim = true; + continue; + } + + if (trim && (*p != '=')) { + /* spaces/tabs are not allowed */ + ldb_dn_mark_invalid(dn); + goto failed; + } + + if (*p == '=') { + /* attribute terminated */ + in_attr = false; + in_value = true; + trim = true; + l = 0; + + /* Terminate this string in d + * (which is a copy of parse_dn + * with spaces trimmed) */ + *d++ = '\0'; + dn->components[dn->comp_num].name = talloc_strdup(dn->components, dt); + if ( ! dn->components[dn->comp_num].name) { + /* ouch */ + goto failed; + } + + dt = d; + + p++; + continue; + } + + if (!isascii(*p)) { + /* attr names must be ascii only */ + ldb_dn_mark_invalid(dn); + goto failed; + } + + if (is_oid && ( ! (isdigit(*p) || (*p == '.')))) { + /* not a digit nor a dot, + * invalid attribute oid */ + ldb_dn_mark_invalid(dn); + goto failed; + } else + if ( ! (isalpha(*p) || isdigit(*p) || (*p == '-'))) { + /* not ALPHA, DIGIT or HYPHEN */ + ldb_dn_mark_invalid(dn); + goto failed; + } + + *d++ = *p++; + continue; + } + + if (in_value) { + if (in_quote) { + if (*p == '\""') { + if (p[-1] != '\\') { + p++; + in_quote = false; + continue; + } + } + *d++ = *p++; + l++; + continue; + } + + if (trim) { + if (*p == ' ') { + p++; + continue; + } + + /* first char */ + trim = false; + + if (*p == '\""') { + in_quote = true; + p++; + continue; + } + } + + switch (*p) { + + /* TODO: support ber encoded values + case '#': + */ + + case ',': + if (escape) { + *d++ = *p++; + l++; + escape = false; + continue; + } + /* ok found value terminator */ + + if ( t ) { + /* trim back */ + d -= (p - t); + l -= (p - t); + } + + in_attr = true; + in_value = false; + trim = true; + + p++; + *d++ = '\0'; + dn->components[dn->comp_num].value.data = \ + (uint8_t *)talloc_memdup(dn->components, dt, l + 1); + dn->components[dn->comp_num].value.length = l; + if ( ! dn->components[dn->comp_num].value.data) { + /* ouch ! */ + goto failed; + } + talloc_set_name_const(dn->components[dn->comp_num].value.data, + (const char *)dn->components[dn->comp_num].value.data); + + dt = d; + + dn->components, + struct ldb_dn_component, + dn->comp_num + 1); + if ( ! dn->components) { + /* ouch ! */ + goto failed; + } + /* make sure all components are zeroed, other functions depend on this */ + memset(&dn->components[dn->comp_num], '\0', sizeof(struct ldb_dn_component)); + } + + continue; + + case '+': + case '=': + /* to main compatibility with earlier + versions of ldb indexing, we have to + accept the base64 encoded binary index + values, which contain a '+' or '=' + which should normally be escaped */ + if (is_index) { + if ( t ) t = NULL; + *d++ = *p++; + l++; + break; + } + /* fall through */ + case '\""': + case '<': + case '>': + case ';': + /* a string with not escaped specials is invalid (tested) */ + if ( ! escape) { + ldb_dn_mark_invalid(dn); + goto failed; + } + escape = false; + + *d++ = *p++; + l++; + + if ( t ) t = NULL; + break; + + case '\\': + if ( ! escape) { + escape = true; + p++; + continue; + } + escape = false; + + *d++ = *p++; + l++; + + if ( t ) t = NULL; + break; + + default: + if (escape) { + if (isxdigit(p[0]) && isxdigit(p[1])) { + if (sscanf(p, ""%02x"", &x) != 1) { + /* invalid escaping sequence */ + ldb_dn_mark_invalid(dn); + goto failed; + } + p += 2; + *d++ = (unsigned char)x; + } else { + *d++ = *p++; + } + + escape = false; + l++; + if ( t ) t = NULL; + break; + } + + if (*p == ' ') { + if ( ! t) t = p; + } else { + if ( t ) t = NULL; + } + + *d++ = *p++; + l++; + + break; + } + + } + } +","@@ -586,12 +586,15 @@ static bool ldb_dn_explode(struct ldb_dn *dn) + + p++; + *d++ = '\0'; +- dn->components[dn->comp_num].value.data = (uint8_t *)talloc_strdup(dn->components, dt); ++ dn->components[dn->comp_num].value.data = \ ++ (uint8_t *)talloc_memdup(dn->components, dt, l + 1); + dn->components[dn->comp_num].value.length = l; + if ( ! dn->components[dn->comp_num].value.data) { + /* ouch ! */ + goto failed; + } ++ talloc_set_name_const(dn->components[dn->comp_num].value.data, ++ (const char *)dn->components[dn->comp_num].value.data); + + dt = d; + +@@ -707,11 +710,13 @@ static bool ldb_dn_explode(struct ldb_dn *dn) + *d++ = '\0'; + dn->components[dn->comp_num].value.length = l; + dn->components[dn->comp_num].value.data = +- (uint8_t *)talloc_strdup(dn->components, dt); ++ (uint8_t *)talloc_memdup(dn->components, dt, l + 1); + if ( ! dn->components[dn->comp_num].value.data) { + /* ouch */ + goto failed; + } ++ talloc_set_name_const(dn->components[dn->comp_num].value.data, ++ (const char *)dn->components[dn->comp_num].value.data); + + dn->comp_num++;",2371,2702,4096 +18106,"lldp_private_8021_print(netdissect_options *ndo, + const u_char *tptr, u_int tlv_len) +{ + int subtype, hexdump = FALSE; + u_int sublen; + u_int tval; + uint8_t i; + + if (tlv_len < 4) { + return hexdump; + } + subtype = *(tptr+3); + + ND_PRINT((ndo, ""\n\t %s Subtype (%u)"", + tok2str(lldp_8021_subtype_values, ""unknown"", subtype), + subtype)); + + switch (subtype) { + case LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID: + if (tlv_len < 6) { + return hexdump; + } + ND_PRINT((ndo, ""\n\t port vlan id (PVID): %u"", + EXTRACT_16BITS(tptr + 4))); + break; + case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID: + if (tlv_len < 7) { + return hexdump; + } + ND_PRINT((ndo, ""\n\t port and protocol vlan id (PPVID): %u, flags [%s] (0x%02x)"", + EXTRACT_16BITS(tptr+5), + bittok2str(lldp_8021_port_protocol_id_values, ""none"", *(tptr+4)), + *(tptr + 4))); + break; + case LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME: + if (tlv_len < 6) { + return hexdump; + } + ND_PRINT((ndo, ""\n\t vlan id (VID): %u"", EXTRACT_16BITS(tptr + 4))); + if (tlv_len < 7) { + return hexdump; + } + sublen = *(tptr+6); + if (tlv_len < 7+sublen) { + return hexdump; + } + ND_PRINT((ndo, ""\n\t vlan name: "")); + safeputs(ndo, tptr + 7, sublen); + break; + case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY: + if (tlv_len < 5) { + return hexdump; + } + sublen = *(tptr+4); + if (tlv_len < 5+sublen) { + return hexdump; + } + ND_PRINT((ndo, ""\n\t protocol identity: "")); + safeputs(ndo, tptr + 5, sublen); + break; + case LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION: + if(tlv_len> i) & 0x01)); + tval=*(tptr+5); + ND_PRINT((ndo, ""\n\t Pre-Priority Ready Indicator"")); + ND_PRINT((ndo, ""\n\t Priority : 0 1 2 3 4 5 6 7"")); + ND_PRINT((ndo, ""\n\t Value : "")); + for(i=0;i> i) & 0x01)); + break; + + case LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION: + if(tlv_len> 7, (tval >> 6) & 0x02, (tval >> 3) & 0x07, tval & 0x07)); + + /*Print Priority Assignment Table*/ + print_ets_priority_assignment_table(ndo, tptr + 5); + + /*Print TC Bandwidth Table*/ + print_tc_bandwidth_table(ndo, tptr + 9); + + /* Print TSA Assignment Table */ + print_tsa_assignment_table(ndo, tptr + 17); + + break; + + case LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION: + if(tlv_len> 7, (tval >> 6) & 0x01, (tval >> 4) & 0x03, (tval & 0x0f))); + ND_PRINT((ndo, ""\n\t PFC Enable"")); + tval=*(tptr+5); + ND_PRINT((ndo, ""\n\t Priority : 0 1 2 3 4 5 6 7"")); + ND_PRINT((ndo, ""\n\t Value : "")); + for(i=0;i> i) & 0x01)); + break; + + case LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY: + if(tlv_len> 5, (tval >> 3) & 0x03, (tval & 0x07))); + ND_PRINT((ndo, ""Protocol ID: %d"", EXTRACT_16BITS(tptr + i + 5))); + i=i+3; + } + break; + case LLDP_PRIVATE_8021_SUBTYPE_EVB: + if(tlv_len> 3, (tval >> 2) & 0x01, (tval >> 1) & 0x01, tval & 0x01)); + ND_PRINT((ndo, ""\n\t EVB Station Status"")); + tval=*(tptr+5); + ND_PRINT((ndo, ""\n\t RES: %d, SGID: %d, RRREQ: %d,RRSTAT: %d"", + tval >> 4, (tval >> 3) & 0x01, (tval >> 2) & 0x01, tval & 0x03)); + tval=*(tptr+6); + ND_PRINT((ndo, ""\n\t R: %d, RTE: %d, "",tval >> 5, tval & 0x1f)); + tval=*(tptr+7); + ND_PRINT((ndo, ""EVB Mode: %s [%d]"", + tok2str(lldp_evb_mode_values, ""unknown"", tval >> 6), tval >> 6)); + ND_PRINT((ndo, ""\n\t ROL: %d, RWD: %d, "", (tval >> 5) & 0x01, tval & 0x1f)); + tval=*(tptr+8); + ND_PRINT((ndo, ""RES: %d, ROL: %d, RKA: %d"", tval >> 6, (tval >> 5) & 0x01, tval & 0x1f)); + break; + + case LLDP_PRIVATE_8021_SUBTYPE_CDCP: + if(tlv_len> 7, (tval >> 4) & 0x07, (tval >> 3) & 0x01)); + ND_PRINT((ndo, ""ChnCap: %d"", EXTRACT_16BITS(tptr + 6) & 0x0fff)); + sublen=tlv_len-8; + if(sublen%3!=0) { + return hexdump; + } + i=0; + while(i> 12, tval & 0x000fff)); + i=i+3; + } + break; + + default: + hexdump = TRUE; + break; + } + + return hexdump; +} +",1,"lldp_private_8021_print(netdissect_options *ndo, + const u_char *tptr, u_int tlv_len) +{ + int subtype, hexdump = FALSE; + u_int sublen; + u_int tval; + u_int i; + + if (tlv_len < 4) { + return hexdump; + } + subtype = *(tptr+3); + + ND_PRINT((ndo, ""\n\t %s Subtype (%u)"", + tok2str(lldp_8021_subtype_values, ""unknown"", subtype), + subtype)); + + switch (subtype) { + case LLDP_PRIVATE_8021_SUBTYPE_PORT_VLAN_ID: + if (tlv_len < 6) { + return hexdump; + } + ND_PRINT((ndo, ""\n\t port vlan id (PVID): %u"", + EXTRACT_16BITS(tptr + 4))); + break; + case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_VLAN_ID: + if (tlv_len < 7) { + return hexdump; + } + ND_PRINT((ndo, ""\n\t port and protocol vlan id (PPVID): %u, flags [%s] (0x%02x)"", + EXTRACT_16BITS(tptr+5), + bittok2str(lldp_8021_port_protocol_id_values, ""none"", *(tptr+4)), + *(tptr + 4))); + break; + case LLDP_PRIVATE_8021_SUBTYPE_VLAN_NAME: + if (tlv_len < 6) { + return hexdump; + } + ND_PRINT((ndo, ""\n\t vlan id (VID): %u"", EXTRACT_16BITS(tptr + 4))); + if (tlv_len < 7) { + return hexdump; + } + sublen = *(tptr+6); + if (tlv_len < 7+sublen) { + return hexdump; + } + ND_PRINT((ndo, ""\n\t vlan name: "")); + safeputs(ndo, tptr + 7, sublen); + break; + case LLDP_PRIVATE_8021_SUBTYPE_PROTOCOL_IDENTITY: + if (tlv_len < 5) { + return hexdump; + } + sublen = *(tptr+4); + if (tlv_len < 5+sublen) { + return hexdump; + } + ND_PRINT((ndo, ""\n\t protocol identity: "")); + safeputs(ndo, tptr + 5, sublen); + break; + case LLDP_PRIVATE_8021_SUBTYPE_CONGESTION_NOTIFICATION: + if(tlv_len> i) & 0x01)); + tval=*(tptr+5); + ND_PRINT((ndo, ""\n\t Pre-Priority Ready Indicator"")); + ND_PRINT((ndo, ""\n\t Priority : 0 1 2 3 4 5 6 7"")); + ND_PRINT((ndo, ""\n\t Value : "")); + for(i=0;i> i) & 0x01)); + break; + + case LLDP_PRIVATE_8021_SUBTYPE_ETS_CONFIGURATION: + if(tlv_len> 7, (tval >> 6) & 0x02, (tval >> 3) & 0x07, tval & 0x07)); + + /*Print Priority Assignment Table*/ + print_ets_priority_assignment_table(ndo, tptr + 5); + + /*Print TC Bandwidth Table*/ + print_tc_bandwidth_table(ndo, tptr + 9); + + /* Print TSA Assignment Table */ + print_tsa_assignment_table(ndo, tptr + 17); + + break; + + case LLDP_PRIVATE_8021_SUBTYPE_ETS_RECOMMENDATION: + if(tlv_len> 7, (tval >> 6) & 0x01, (tval >> 4) & 0x03, (tval & 0x0f))); + ND_PRINT((ndo, ""\n\t PFC Enable"")); + tval=*(tptr+5); + ND_PRINT((ndo, ""\n\t Priority : 0 1 2 3 4 5 6 7"")); + ND_PRINT((ndo, ""\n\t Value : "")); + for(i=0;i> i) & 0x01)); + break; + + case LLDP_PRIVATE_8021_SUBTYPE_APPLICATION_PRIORITY: + if(tlv_len> 5, (tval >> 3) & 0x03, (tval & 0x07), + EXTRACT_16BITS(tptr + i + 5))); + i=i+3; + } + break; + case LLDP_PRIVATE_8021_SUBTYPE_EVB: + if(tlv_len> 3, (tval >> 2) & 0x01, (tval >> 1) & 0x01, tval & 0x01)); + ND_PRINT((ndo, ""\n\t EVB Station Status"")); + tval=*(tptr+5); + ND_PRINT((ndo, ""\n\t RES: %d, SGID: %d, RRREQ: %d,RRSTAT: %d"", + tval >> 4, (tval >> 3) & 0x01, (tval >> 2) & 0x01, tval & 0x03)); + tval=*(tptr+6); + ND_PRINT((ndo, ""\n\t R: %d, RTE: %d, "",tval >> 5, tval & 0x1f)); + tval=*(tptr+7); + ND_PRINT((ndo, ""EVB Mode: %s [%d]"", + tok2str(lldp_evb_mode_values, ""unknown"", tval >> 6), tval >> 6)); + ND_PRINT((ndo, ""\n\t ROL: %d, RWD: %d, "", (tval >> 5) & 0x01, tval & 0x1f)); + tval=*(tptr+8); + ND_PRINT((ndo, ""RES: %d, ROL: %d, RKA: %d"", tval >> 6, (tval >> 5) & 0x01, tval & 0x1f)); + break; + + case LLDP_PRIVATE_8021_SUBTYPE_CDCP: + if(tlv_len> 7, (tval >> 4) & 0x07, (tval >> 3) & 0x01)); + ND_PRINT((ndo, ""ChnCap: %d"", EXTRACT_16BITS(tptr + 6) & 0x0fff)); + sublen=tlv_len-8; + if(sublen%3!=0) { + return hexdump; + } + i=0; + while(i> 12, tval & 0x000fff)); + i=i+3; + } + break; + + default: + hexdump = TRUE; + break; + } + + return hexdump; +} +","@@ -651,7 +651,7 @@ lldp_private_8021_print(netdissect_options *ndo, + int subtype, hexdump = FALSE; + u_int sublen; + u_int tval; +- uint8_t i; ++ u_int i; + + if (tlv_len < 4) { + return hexdump; +@@ -787,9 +787,9 @@ lldp_private_8021_print(netdissect_options *ndo, + ND_PRINT((ndo, ""\n\t Application Priority Table"")); + while(i> 5, (tval >> 3) & 0x03, (tval & 0x07))); +- ND_PRINT((ndo, ""Protocol ID: %d"", EXTRACT_16BITS(tptr + i + 5))); ++ ND_PRINT((ndo, ""\n\t Priority: %u, RES: %u, Sel: %u, Protocol ID: %u"", ++ tval >> 5, (tval >> 3) & 0x03, (tval & 0x07), ++ EXTRACT_16BITS(tptr + i + 5))); + i=i+3; + } + break;",2428,2759,4096 +18076,"static void gmc_mmx(uint8_t *dst, uint8_t *src, + int stride, int h, int ox, int oy, + int dxx, int dxy, int dyx, int dyy, + int shift, int r, int width, int height) +{ + const int w = 8; + const int ix = ox >> (16 + shift); + const int iy = oy >> (16 + shift); + const int oxs = ox >> 4; + const int oys = oy >> 4; + const int dxxs = dxx >> 4; + const int dxys = dxy >> 4; + const int dyxs = dyx >> 4; + const int dyys = dyy >> 4; + const uint16_t r4[4] = { r, r, r, r }; + const uint16_t dxy4[4] = { dxys, dxys, dxys, dxys }; + const uint16_t dyy4[4] = { dyys, dyys, dyys, dyys }; + const uint64_t shift2 = 2 * shift; +#define MAX_STRIDE 4096U +#define MAX_H 8U + uint8_t edge_buf[(MAX_H + 1) * MAX_STRIDE]; + int x, y; + + const int dxw = (dxx - (1 << (16 + shift))) * (w - 1); + const int dyh = (dyy - (1 << (16 + shift))) * (h - 1); + const int dxh = dxy * (h - 1); + const int dyw = dyx * (w - 1); + int need_emu = (unsigned) ix >= width - w || + (unsigned) iy >= height - h; + + if ( // non-constant fullpel offset (3% of blocks) + ((ox ^ (ox + dxw)) | (ox ^ (ox + dxh)) | (ox ^ (ox + dxw + dxh)) | + (oy ^ (oy + dyw)) | (oy ^ (oy + dyh)) | (oy ^ (oy + dyw + dyh))) >> (16 + shift) || + (dxx | dxy | dyx | dyy) & 15 || + (need_emu && (h > MAX_H || stride > MAX_STRIDE))) { + ff_gmc_c(dst, src, stride, h, ox, oy, dxx, dxy, dyx, dyy, + shift, r, width, height); + return; + } + + src += ix + iy * stride; + if (need_emu) { + ff_emulated_edge_mc_8(edge_buf, src, stride, stride, w + 1, h + 1, ix, iy, width, height); + src = edge_buf; + } + + __asm__ volatile ( + ""movd %0, %%mm6 \n\t"" + ""pxor %%mm7, %%mm7 \n\t"" + ""punpcklwd %%mm6, %%mm6 \n\t"" + ""punpcklwd %%mm6, %%mm6 \n\t"" + :: ""r"" (1 << shift)); + + for (x = 0; x < w; x += 4) { + uint16_t dx4[4] = { oxs - dxys + dxxs * (x + 0), + oxs - dxys + dxxs * (x + 1), + oxs - dxys + dxxs * (x + 2), + oxs - dxys + dxxs * (x + 3) }; + uint16_t dy4[4] = { oys - dyys + dyxs * (x + 0), + oys - dyys + dyxs * (x + 1), + oys - dyys + dyxs * (x + 2), + oys - dyys + dyxs * (x + 3) }; + + for (y = 0; y < h; y++) { + __asm__ volatile ( + ""movq %0, %%mm4 \n\t"" + ""movq %1, %%mm5 \n\t"" + ""paddw %2, %%mm4 \n\t"" + ""paddw %3, %%mm5 \n\t"" + ""movq %%mm4, %0 \n\t"" + ""movq %%mm5, %1 \n\t"" + ""psrlw $12, %%mm4 \n\t"" + ""psrlw $12, %%mm5 \n\t"" + : ""+m"" (*dx4), ""+m"" (*dy4) + : ""m"" (*dxy4), ""m"" (*dyy4)); + + __asm__ volatile ( + ""movq %%mm6, %%mm2 \n\t"" + ""movq %%mm6, %%mm1 \n\t"" + ""psubw %%mm4, %%mm2 \n\t"" + ""psubw %%mm5, %%mm1 \n\t"" + ""movq %%mm2, %%mm0 \n\t"" + ""movq %%mm4, %%mm3 \n\t"" + ""pmullw %%mm1, %%mm0 \n\t"" // (s - dx) * (s - dy) + ""pmullw %%mm5, %%mm3 \n\t"" // dx * dy + ""pmullw %%mm5, %%mm2 \n\t"" // (s - dx) * dy + ""pmullw %%mm4, %%mm1 \n\t"" // dx * (s - dy) + + ""movd %4, %%mm5 \n\t"" + ""movd %3, %%mm4 \n\t"" + ""punpcklbw %%mm7, %%mm5 \n\t"" + ""punpcklbw %%mm7, %%mm4 \n\t"" + ""pmullw %%mm5, %%mm3 \n\t"" // src[1, 1] * dx * dy + ""pmullw %%mm4, %%mm2 \n\t"" // src[0, 1] * (s - dx) * dy + + ""movd %2, %%mm5 \n\t"" + ""movd %1, %%mm4 \n\t"" + ""punpcklbw %%mm7, %%mm5 \n\t"" + ""punpcklbw %%mm7, %%mm4 \n\t"" + ""pmullw %%mm5, %%mm1 \n\t"" // src[1, 0] * dx * (s - dy) + ""pmullw %%mm4, %%mm0 \n\t"" // src[0, 0] * (s - dx) * (s - dy) + ""paddw %5, %%mm1 \n\t"" + ""paddw %%mm3, %%mm2 \n\t"" + ""paddw %%mm1, %%mm0 \n\t"" + ""paddw %%mm2, %%mm0 \n\t"" + + ""psrlw %6, %%mm0 \n\t"" + ""packuswb %%mm0, %%mm0 \n\t"" + ""movd %%mm0, %0 \n\t"" + + : ""=m"" (dst[x + y * stride]) + : ""m"" (src[0]), ""m"" (src[1]), + ""m"" (src[stride]), ""m"" (src[stride + 1]), + ""m"" (*r4), ""m"" (shift2)); + src += stride; + } + src += 4 - h * stride; + } +} +",1,"static void gmc_mmx(uint8_t *dst, uint8_t *src, + int stride, int h, int ox, int oy, + int dxx, int dxy, int dyx, int dyy, + int shift, int r, int width, int height) +{ + const int w = 8; + const int ix = ox >> (16 + shift); + const int iy = oy >> (16 + shift); + const int oxs = ox >> 4; + const int oys = oy >> 4; + const int dxxs = dxx >> 4; + const int dxys = dxy >> 4; + const int dyxs = dyx >> 4; + const int dyys = dyy >> 4; + const uint16_t r4[4] = { r, r, r, r }; + const uint16_t dxy4[4] = { dxys, dxys, dxys, dxys }; + const uint16_t dyy4[4] = { dyys, dyys, dyys, dyys }; + const uint64_t shift2 = 2 * shift; +#define MAX_STRIDE 4096U +#define MAX_H 8U + uint8_t edge_buf[(MAX_H + 1) * MAX_STRIDE]; + int x, y; + + const int dxw = (dxx - (1 << (16 + shift))) * (w - 1); + const int dyh = (dyy - (1 << (16 + shift))) * (h - 1); + const int dxh = dxy * (h - 1); + const int dyw = dyx * (w - 1); + int need_emu = (unsigned) ix >= width - w || width < w || + (unsigned) iy >= height - h || height< h + ; + + if ( // non-constant fullpel offset (3% of blocks) + ((ox ^ (ox + dxw)) | (ox ^ (ox + dxh)) | (ox ^ (ox + dxw + dxh)) | + (oy ^ (oy + dyw)) | (oy ^ (oy + dyh)) | (oy ^ (oy + dyw + dyh))) >> (16 + shift) || + (dxx | dxy | dyx | dyy) & 15 || + (need_emu && (h > MAX_H || stride > MAX_STRIDE))) { + ff_gmc_c(dst, src, stride, h, ox, oy, dxx, dxy, dyx, dyy, + shift, r, width, height); + return; + } + + src += ix + iy * stride; + if (need_emu) { + ff_emulated_edge_mc_8(edge_buf, src, stride, stride, w + 1, h + 1, ix, iy, width, height); + src = edge_buf; + } + + __asm__ volatile ( + ""movd %0, %%mm6 \n\t"" + ""pxor %%mm7, %%mm7 \n\t"" + ""punpcklwd %%mm6, %%mm6 \n\t"" + ""punpcklwd %%mm6, %%mm6 \n\t"" + :: ""r"" (1 << shift)); + + for (x = 0; x < w; x += 4) { + uint16_t dx4[4] = { oxs - dxys + dxxs * (x + 0), + oxs - dxys + dxxs * (x + 1), + oxs - dxys + dxxs * (x + 2), + oxs - dxys + dxxs * (x + 3) }; + uint16_t dy4[4] = { oys - dyys + dyxs * (x + 0), + oys - dyys + dyxs * (x + 1), + oys - dyys + dyxs * (x + 2), + oys - dyys + dyxs * (x + 3) }; + + for (y = 0; y < h; y++) { + __asm__ volatile ( + ""movq %0, %%mm4 \n\t"" + ""movq %1, %%mm5 \n\t"" + ""paddw %2, %%mm4 \n\t"" + ""paddw %3, %%mm5 \n\t"" + ""movq %%mm4, %0 \n\t"" + ""movq %%mm5, %1 \n\t"" + ""psrlw $12, %%mm4 \n\t"" + ""psrlw $12, %%mm5 \n\t"" + : ""+m"" (*dx4), ""+m"" (*dy4) + : ""m"" (*dxy4), ""m"" (*dyy4)); + + __asm__ volatile ( + ""movq %%mm6, %%mm2 \n\t"" + ""movq %%mm6, %%mm1 \n\t"" + ""psubw %%mm4, %%mm2 \n\t"" + ""psubw %%mm5, %%mm1 \n\t"" + ""movq %%mm2, %%mm0 \n\t"" + ""movq %%mm4, %%mm3 \n\t"" + ""pmullw %%mm1, %%mm0 \n\t"" // (s - dx) * (s - dy) + ""pmullw %%mm5, %%mm3 \n\t"" // dx * dy + ""pmullw %%mm5, %%mm2 \n\t"" // (s - dx) * dy + ""pmullw %%mm4, %%mm1 \n\t"" // dx * (s - dy) + + ""movd %4, %%mm5 \n\t"" + ""movd %3, %%mm4 \n\t"" + ""punpcklbw %%mm7, %%mm5 \n\t"" + ""punpcklbw %%mm7, %%mm4 \n\t"" + ""pmullw %%mm5, %%mm3 \n\t"" // src[1, 1] * dx * dy + ""pmullw %%mm4, %%mm2 \n\t"" // src[0, 1] * (s - dx) * dy + + ""movd %2, %%mm5 \n\t"" + ""movd %1, %%mm4 \n\t"" + ""punpcklbw %%mm7, %%mm5 \n\t"" + ""punpcklbw %%mm7, %%mm4 \n\t"" + ""pmullw %%mm5, %%mm1 \n\t"" // src[1, 0] * dx * (s - dy) + ""pmullw %%mm4, %%mm0 \n\t"" // src[0, 0] * (s - dx) * (s - dy) + ""paddw %5, %%mm1 \n\t"" + ""paddw %%mm3, %%mm2 \n\t"" + ""paddw %%mm1, %%mm0 \n\t"" + ""paddw %%mm2, %%mm0 \n\t"" + + ""psrlw %6, %%mm0 \n\t"" + ""packuswb %%mm0, %%mm0 \n\t"" + ""movd %%mm0, %0 \n\t"" + + : ""=m"" (dst[x + y * stride]) + : ""m"" (src[0]), ""m"" (src[1]), + ""m"" (src[stride]), ""m"" (src[stride + 1]), + ""m"" (*r4), ""m"" (shift2)); + src += stride; + } + src += 4 - h * stride; + } +} +","@@ -52,8 +52,9 @@ static void gmc_mmx(uint8_t *dst, uint8_t *src, + const int dyh = (dyy - (1 << (16 + shift))) * (h - 1); + const int dxh = dxy * (h - 1); + const int dyw = dyx * (w - 1); +- int need_emu = (unsigned) ix >= width - w || +- (unsigned) iy >= height - h; ++ int need_emu = (unsigned) ix >= width - w || width < w || ++ (unsigned) iy >= height - h || height< h ++ ; + + if ( // non-constant fullpel offset (3% of blocks) + ((ox ^ (ox + dxw)) | (ox ^ (ox + dxh)) | (ox ^ (ox + dxw + dxh)) |",1775,2106,4096 +4169,"tcp_sacktag_write_queue(struct sock *sk, const struct sk_buff *ack_skb, + u32 prior_snd_una) +{ + const struct inet_connection_sock *icsk = inet_csk(sk); + struct tcp_sock *tp = tcp_sk(sk); + const unsigned char *ptr = (skb_transport_header(ack_skb) + + TCP_SKB_CB(ack_skb)->sacked); + struct tcp_sack_block_wire *sp_wire = (struct tcp_sack_block_wire *)(ptr+2); + struct tcp_sack_block sp[TCP_NUM_SACKS]; + struct tcp_sack_block *cache; + struct tcp_sacktag_state state; + struct sk_buff *skb; + int num_sacks = min(TCP_NUM_SACKS, (ptr[1] - TCPOLEN_SACK_BASE) >> 3); + int used_sacks; + int found_dup_sack = 0; + int i, j; + int first_sack_index; + + state.flag = 0; + state.reord = tp->packets_out; + + if (!tp->sacked_out) { + if (WARN_ON(tp->fackets_out)) + tp->fackets_out = 0; + tcp_highest_sack_reset(sk); + } + + found_dup_sack = tcp_check_dsack(sk, ack_skb, sp_wire, + num_sacks, prior_snd_una); + if (found_dup_sack) + state.flag |= FLAG_DSACKING_ACK; + + /* Eliminate too old ACKs, but take into + * account more or less fresh ones, they can + * contain valid SACK info. + */ + if (before(TCP_SKB_CB(ack_skb)->ack_seq, prior_snd_una - tp->max_window)) + return 0; + + if (!tp->packets_out) + goto out; + + used_sacks = 0; + first_sack_index = 0; + for (i = 0; i < num_sacks; i++) { + int dup_sack = !i && found_dup_sack; + + sp[used_sacks].start_seq = get_unaligned_be32(&sp_wire[i].start_seq); + sp[used_sacks].end_seq = get_unaligned_be32(&sp_wire[i].end_seq); + + if (!tcp_is_sackblock_valid(tp, dup_sack, + sp[used_sacks].start_seq, + sp[used_sacks].end_seq)) { + int mib_idx; + + if (dup_sack) { + if (!tp->undo_marker) + mib_idx = LINUX_MIB_TCPDSACKIGNOREDNOUNDO; + else + mib_idx = LINUX_MIB_TCPDSACKIGNOREDOLD; + } else { + /* Don't count olds caused by ACK reordering */ + if ((TCP_SKB_CB(ack_skb)->ack_seq != tp->snd_una) && + !after(sp[used_sacks].end_seq, tp->snd_una)) + continue; + mib_idx = LINUX_MIB_TCPSACKDISCARD; + } + + NET_INC_STATS_BH(sock_net(sk), mib_idx); + if (i == 0) + first_sack_index = -1; + continue; + } + + /* Ignore very old stuff early */ + if (!after(sp[used_sacks].end_seq, prior_snd_una)) + continue; + + used_sacks++; + } + + /* order SACK blocks to allow in order walk of the retrans queue */ + for (i = used_sacks - 1; i > 0; i--) { + for (j = 0; j < i; j++) { + if (after(sp[j].start_seq, sp[j + 1].start_seq)) { + swap(sp[j], sp[j + 1]); + + /* Track where the first SACK block goes to */ + if (j == first_sack_index) + first_sack_index = j + 1; + } + } + } + + skb = tcp_write_queue_head(sk); + state.fack_count = 0; + i = 0; + + if (!tp->sacked_out) { + /* It's already past, so skip checking against it */ + cache = tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache); + } else { + cache = tp->recv_sack_cache; + /* Skip empty blocks in at head of the cache */ + while (tcp_sack_cache_ok(tp, cache) && !cache->start_seq && + !cache->end_seq) + cache++; + } + + while (i < used_sacks) { + u32 start_seq = sp[i].start_seq; + u32 end_seq = sp[i].end_seq; + int dup_sack = (found_dup_sack && (i == first_sack_index)); + struct tcp_sack_block *next_dup = NULL; + + if (found_dup_sack && ((i + 1) == first_sack_index)) + next_dup = &sp[i + 1]; + + /* Event ""B"" in the comment above. */ + if (after(end_seq, tp->high_seq)) + state.flag |= FLAG_DATA_LOST; + + /* Skip too early cached blocks */ + while (tcp_sack_cache_ok(tp, cache) && + !before(start_seq, cache->end_seq)) + cache++; + + /* Can skip some work by looking recv_sack_cache? */ + if (tcp_sack_cache_ok(tp, cache) && !dup_sack && + after(end_seq, cache->start_seq)) { + + /* Head todo? */ + if (before(start_seq, cache->start_seq)) { + skb = tcp_sacktag_skip(skb, sk, &state, + start_seq); + skb = tcp_sacktag_walk(skb, sk, next_dup, + &state, + start_seq, + cache->start_seq, + dup_sack); + } + + /* Rest of the block already fully processed? */ + if (!after(end_seq, cache->end_seq)) + goto advance_sp; + + skb = tcp_maybe_skipping_dsack(skb, sk, next_dup, + &state, + cache->end_seq); + + /* ...tail remains todo... */ + if (tcp_highest_sack_seq(tp) == cache->end_seq) { + /* ...but better entrypoint exists! */ + skb = tcp_highest_sack(sk); + if (skb == NULL) + break; + state.fack_count = tp->fackets_out; + cache++; + goto walk; + } + + skb = tcp_sacktag_skip(skb, sk, &state, cache->end_seq); + /* Check overlap against next cached too (past this one already) */ + cache++; + continue; + } + + if (!before(start_seq, tcp_highest_sack_seq(tp))) { + skb = tcp_highest_sack(sk); + if (skb == NULL) + break; + state.fack_count = tp->fackets_out; + } + skb = tcp_sacktag_skip(skb, sk, &state, start_seq); + +walk: + skb = tcp_sacktag_walk(skb, sk, next_dup, &state, + start_seq, end_seq, dup_sack); + +advance_sp: + /* SACK enhanced FRTO (RFC4138, Appendix B): Clearing correct + * due to in-order walk + */ + if (after(end_seq, tp->frto_highmark)) + state.flag &= ~FLAG_ONLY_ORIG_SACKED; + + i++; + } + + /* Clear the head of the cache sack blocks so we can skip it next time */ + for (i = 0; i < ARRAY_SIZE(tp->recv_sack_cache) - used_sacks; i++) { + tp->recv_sack_cache[i].start_seq = 0; + tp->recv_sack_cache[i].end_seq = 0; + } + for (j = 0; j < used_sacks; j++) + tp->recv_sack_cache[i++] = sp[j]; + + tcp_mark_lost_retrans(sk); + + tcp_verify_left_out(tp); + + if ((state.reord < tp->fackets_out) && + ((icsk->icsk_ca_state != TCP_CA_Loss) || tp->undo_marker) && + (!tp->frto_highmark || after(tp->snd_una, tp->frto_highmark))) + tcp_update_reordering(sk, tp->fackets_out - state.reord, 0); + +out: + +#if FASTRETRANS_DEBUG > 0 + WARN_ON((int)tp->sacked_out < 0); + WARN_ON((int)tp->lost_out < 0); + WARN_ON((int)tp->retrans_out < 0); + WARN_ON((int)tcp_packets_in_flight(tp) < 0); +#endif + return state.flag; +} +",0,"tcp_sacktag_write_queue(struct sock *sk, const struct sk_buff *ack_skb, + u32 prior_snd_una) +{ + const struct inet_connection_sock *icsk = inet_csk(sk); + struct tcp_sock *tp = tcp_sk(sk); + const unsigned char *ptr = (skb_transport_header(ack_skb) + + TCP_SKB_CB(ack_skb)->sacked); + struct tcp_sack_block_wire *sp_wire = (struct tcp_sack_block_wire *)(ptr+2); + struct tcp_sack_block sp[TCP_NUM_SACKS]; + struct tcp_sack_block *cache; + struct tcp_sacktag_state state; + struct sk_buff *skb; + int num_sacks = min(TCP_NUM_SACKS, (ptr[1] - TCPOLEN_SACK_BASE) >> 3); + int used_sacks; + int found_dup_sack = 0; + int i, j; + int first_sack_index; + + state.flag = 0; + state.reord = tp->packets_out; + + if (!tp->sacked_out) { + if (WARN_ON(tp->fackets_out)) + tp->fackets_out = 0; + tcp_highest_sack_reset(sk); + } + + found_dup_sack = tcp_check_dsack(sk, ack_skb, sp_wire, + num_sacks, prior_snd_una); + if (found_dup_sack) + state.flag |= FLAG_DSACKING_ACK; + + /* Eliminate too old ACKs, but take into + * account more or less fresh ones, they can + * contain valid SACK info. + */ + if (before(TCP_SKB_CB(ack_skb)->ack_seq, prior_snd_una - tp->max_window)) + return 0; + + if (!tp->packets_out) + goto out; + + used_sacks = 0; + first_sack_index = 0; + for (i = 0; i < num_sacks; i++) { + int dup_sack = !i && found_dup_sack; + + sp[used_sacks].start_seq = get_unaligned_be32(&sp_wire[i].start_seq); + sp[used_sacks].end_seq = get_unaligned_be32(&sp_wire[i].end_seq); + + if (!tcp_is_sackblock_valid(tp, dup_sack, + sp[used_sacks].start_seq, + sp[used_sacks].end_seq)) { + int mib_idx; + + if (dup_sack) { + if (!tp->undo_marker) + mib_idx = LINUX_MIB_TCPDSACKIGNOREDNOUNDO; + else + mib_idx = LINUX_MIB_TCPDSACKIGNOREDOLD; + } else { + /* Don't count olds caused by ACK reordering */ + if ((TCP_SKB_CB(ack_skb)->ack_seq != tp->snd_una) && + !after(sp[used_sacks].end_seq, tp->snd_una)) + continue; + mib_idx = LINUX_MIB_TCPSACKDISCARD; + } + + NET_INC_STATS_BH(sock_net(sk), mib_idx); + if (i == 0) + first_sack_index = -1; + continue; + } + + /* Ignore very old stuff early */ + if (!after(sp[used_sacks].end_seq, prior_snd_una)) + continue; + + used_sacks++; + } + + /* order SACK blocks to allow in order walk of the retrans queue */ + for (i = used_sacks - 1; i > 0; i--) { + for (j = 0; j < i; j++) { + if (after(sp[j].start_seq, sp[j + 1].start_seq)) { + swap(sp[j], sp[j + 1]); + + /* Track where the first SACK block goes to */ + if (j == first_sack_index) + first_sack_index = j + 1; + } + } + } + + skb = tcp_write_queue_head(sk); + state.fack_count = 0; + i = 0; + + if (!tp->sacked_out) { + /* It's already past, so skip checking against it */ + cache = tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache); + } else { + cache = tp->recv_sack_cache; + /* Skip empty blocks in at head of the cache */ + while (tcp_sack_cache_ok(tp, cache) && !cache->start_seq && + !cache->end_seq) + cache++; + } + + while (i < used_sacks) { + u32 start_seq = sp[i].start_seq; + u32 end_seq = sp[i].end_seq; + int dup_sack = (found_dup_sack && (i == first_sack_index)); + struct tcp_sack_block *next_dup = NULL; + + if (found_dup_sack && ((i + 1) == first_sack_index)) + next_dup = &sp[i + 1]; + + /* Event ""B"" in the comment above. */ + if (after(end_seq, tp->high_seq)) + state.flag |= FLAG_DATA_LOST; + + /* Skip too early cached blocks */ + while (tcp_sack_cache_ok(tp, cache) && + !before(start_seq, cache->end_seq)) + cache++; + + /* Can skip some work by looking recv_sack_cache? */ + if (tcp_sack_cache_ok(tp, cache) && !dup_sack && + after(end_seq, cache->start_seq)) { + + /* Head todo? */ + if (before(start_seq, cache->start_seq)) { + skb = tcp_sacktag_skip(skb, sk, &state, + start_seq); + skb = tcp_sacktag_walk(skb, sk, next_dup, + &state, + start_seq, + cache->start_seq, + dup_sack); + } + + /* Rest of the block already fully processed? */ + if (!after(end_seq, cache->end_seq)) + goto advance_sp; + + skb = tcp_maybe_skipping_dsack(skb, sk, next_dup, + &state, + cache->end_seq); + + /* ...tail remains todo... */ + if (tcp_highest_sack_seq(tp) == cache->end_seq) { + /* ...but better entrypoint exists! */ + skb = tcp_highest_sack(sk); + if (skb == NULL) + break; + state.fack_count = tp->fackets_out; + cache++; + goto walk; + } + + skb = tcp_sacktag_skip(skb, sk, &state, cache->end_seq); + /* Check overlap against next cached too (past this one already) */ + cache++; + continue; + } + + if (!before(start_seq, tcp_highest_sack_seq(tp))) { + skb = tcp_highest_sack(sk); + if (skb == NULL) + break; + state.fack_count = tp->fackets_out; + } + skb = tcp_sacktag_skip(skb, sk, &state, start_seq); + +walk: + skb = tcp_sacktag_walk(skb, sk, next_dup, &state, + start_seq, end_seq, dup_sack); + +advance_sp: + /* SACK enhanced FRTO (RFC4138, Appendix B): Clearing correct + * due to in-order walk + */ + if (after(end_seq, tp->frto_highmark)) + state.flag &= ~FLAG_ONLY_ORIG_SACKED; + + i++; + } + + /* Clear the head of the cache sack blocks so we can skip it next time */ + for (i = 0; i < ARRAY_SIZE(tp->recv_sack_cache) - used_sacks; i++) { + tp->recv_sack_cache[i].start_seq = 0; + tp->recv_sack_cache[i].end_seq = 0; + } + for (j = 0; j < used_sacks; j++) + tp->recv_sack_cache[i++] = sp[j]; + + tcp_mark_lost_retrans(sk); + + tcp_verify_left_out(tp); + + if ((state.reord < tp->fackets_out) && + ((icsk->icsk_ca_state != TCP_CA_Loss) || tp->undo_marker) && + (!tp->frto_highmark || after(tp->snd_una, tp->frto_highmark))) + tcp_update_reordering(sk, tp->fackets_out - state.reord, 0); + +out: + +#if FASTRETRANS_DEBUG > 0 + WARN_ON((int)tp->sacked_out < 0); + WARN_ON((int)tp->lost_out < 0); + WARN_ON((int)tp->retrans_out < 0); + WARN_ON((int)tcp_packets_in_flight(tp) < 0); +#endif + return state.flag; +} +","@@ -5811,6 +5811,8 @@ int tcp_rcv_state_process(struct sock *sk, struct sk_buff *skb, + goto discard; + + if (th->syn) { ++ if (th->fin) ++ goto discard; + if (icsk->icsk_af_ops->conn_request(sk, skb) < 0) + return 1; + ",1884,2215,4096 +18103,"vtp_print (netdissect_options *ndo, + const u_char *pptr, u_int length) +{ + int type, len, tlv_len, tlv_value, mgmtd_len; + const u_char *tptr; + const struct vtp_vlan_ *vtp_vlan; + + if (length < VTP_HEADER_LEN) + goto trunc; + + tptr = pptr; + + ND_TCHECK2(*tptr, VTP_HEADER_LEN); + + type = *(tptr+1); + ND_PRINT((ndo, ""VTPv%u, Message %s (0x%02x), length %u"", + *tptr, + tok2str(vtp_message_type_values,""Unknown message type"", type), + type, + length)); + + /* In non-verbose mode, just print version and message type */ + if (ndo->ndo_vflag < 1) { + return; + } + + /* verbose mode print all fields */ + ND_PRINT((ndo, ""\n\tDomain name: "")); + mgmtd_len = *(tptr + 3); + if (mgmtd_len < 1 || mgmtd_len > 32) { + ND_PRINT((ndo, "" [invalid MgmtD Len %d]"", mgmtd_len)); + return; + } + fn_printzp(ndo, tptr + 4, mgmtd_len, NULL); + ND_PRINT((ndo, "", %s: %u"", + tok2str(vtp_header_values, ""Unknown"", type), + *(tptr+2))); + + tptr += VTP_HEADER_LEN; + + switch (type) { + + case VTP_SUMMARY_ADV: + + /* + * SUMMARY ADVERTISEMENT + * + * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Version | Code | Followers | MgmtD Len | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Management Domain Name (zero-padded to 32 bytes) | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Configuration revision number | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Updater Identity IP address | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Update Timestamp (12 bytes) | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | MD5 digest (16 bytes) | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * + */ + + ND_TCHECK2(*tptr, 8); + ND_PRINT((ndo, ""\n\t Config Rev %x, Updater %s"", + EXTRACT_32BITS(tptr), + ipaddr_string(ndo, tptr+4))); + tptr += 8; + ND_TCHECK2(*tptr, VTP_UPDATE_TIMESTAMP_LEN); + ND_PRINT((ndo, "", Timestamp 0x%08x 0x%08x 0x%08x"", + EXTRACT_32BITS(tptr), + EXTRACT_32BITS(tptr + 4), + EXTRACT_32BITS(tptr + 8))); + tptr += VTP_UPDATE_TIMESTAMP_LEN; + ND_TCHECK2(*tptr, VTP_MD5_DIGEST_LEN); + ND_PRINT((ndo, "", MD5 digest: %08x%08x%08x%08x"", + EXTRACT_32BITS(tptr), + EXTRACT_32BITS(tptr + 4), + EXTRACT_32BITS(tptr + 8), + EXTRACT_32BITS(tptr + 12))); + tptr += VTP_MD5_DIGEST_LEN; + break; + + case VTP_SUBSET_ADV: + + /* + * SUBSET ADVERTISEMENT + * + * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Version | Code | Seq number | MgmtD Len | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Management Domain Name (zero-padded to 32 bytes) | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Configuration revision number | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | VLAN info field 1 | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | ................ | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | VLAN info field N | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * + */ + + ND_PRINT((ndo, "", Config Rev %x"", EXTRACT_32BITS(tptr))); + + /* + * VLAN INFORMATION + * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | V info len | Status | VLAN type | VLAN name len | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | ISL vlan id | MTU size | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | 802.10 index (SAID) | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | VLAN name | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * + */ + + tptr += 4; + while (tptr < (pptr+length)) { + + len = *tptr; + if (len == 0) + break; + + ND_TCHECK2(*tptr, len); + + vtp_vlan = (const struct vtp_vlan_*)tptr; + ND_TCHECK(*vtp_vlan); + ND_PRINT((ndo, ""\n\tVLAN info status %s, type %s, VLAN-id %u, MTU %u, SAID 0x%08x, Name "", + tok2str(vtp_vlan_status,""Unknown"",vtp_vlan->status), + tok2str(vtp_vlan_type_values,""Unknown"",vtp_vlan->type), + EXTRACT_16BITS(&vtp_vlan->vlanid), + EXTRACT_16BITS(&vtp_vlan->mtu), + EXTRACT_32BITS(&vtp_vlan->index))); + fn_printzp(ndo, tptr + VTP_VLAN_INFO_OFFSET, vtp_vlan->name_len, NULL); + + /* + * Vlan names are aligned to 32-bit boundaries. + */ + len -= VTP_VLAN_INFO_OFFSET + 4*((vtp_vlan->name_len + 3)/4); + tptr += VTP_VLAN_INFO_OFFSET + 4*((vtp_vlan->name_len + 3)/4); + + /* TLV information follows */ + + while (len > 0) { + + /* + * Cisco specs says 2 bytes for type + 2 bytes for length, take only 1 + * See: http://www.cisco.com/univercd/cc/td/doc/product/lan/trsrb/frames.htm + */ + type = *tptr; + tlv_len = *(tptr+1); + + ND_PRINT((ndo, ""\n\t\t%s (0x%04x) TLV"", + tok2str(vtp_vlan_tlv_values, ""Unknown"", type), + type)); + + /* + * infinite loop check + */ + if (type == 0 || tlv_len == 0) { + return; + } + + ND_TCHECK2(*tptr, tlv_len * 2 +2); + + tlv_value = EXTRACT_16BITS(tptr+2); + + switch (type) { + case VTP_VLAN_STE_HOP_COUNT: + ND_PRINT((ndo, "", %u"", tlv_value)); + break; + + case VTP_VLAN_PRUNING: + ND_PRINT((ndo, "", %s (%u)"", + tlv_value == 1 ? ""Enabled"" : ""Disabled"", + tlv_value)); + break; + + case VTP_VLAN_STP_TYPE: + ND_PRINT((ndo, "", %s (%u)"", + tok2str(vtp_stp_type_values, ""Unknown"", tlv_value), + tlv_value)); + break; + + case VTP_VLAN_BRIDGE_TYPE: + ND_PRINT((ndo, "", %s (%u)"", + tlv_value == 1 ? ""SRB"" : ""SRT"", + tlv_value)); + break; + + case VTP_VLAN_BACKUP_CRF_MODE: + ND_PRINT((ndo, "", %s (%u)"", + tlv_value == 1 ? ""Backup"" : ""Not backup"", + tlv_value)); + break; + + /* + * FIXME those are the defined TLVs that lack a decoder + * you are welcome to contribute code ;-) + */ + + case VTP_VLAN_SOURCE_ROUTING_RING_NUMBER: + case VTP_VLAN_SOURCE_ROUTING_BRIDGE_NUMBER: + case VTP_VLAN_PARENT_VLAN: + case VTP_VLAN_TRANS_BRIDGED_VLAN: + case VTP_VLAN_ARP_HOP_COUNT: + default: + print_unknown_data(ndo, tptr, ""\n\t\t "", 2 + tlv_len*2); + break; + } + len -= 2 + tlv_len*2; + tptr += 2 + tlv_len*2; + } + } + break; + + case VTP_ADV_REQUEST: + + /* + * ADVERTISEMENT REQUEST + * + * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Version | Code | Reserved | MgmtD Len | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Management Domain Name (zero-padded to 32 bytes) | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Start value | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * + */ + + ND_TCHECK2(*tptr, 4); + ND_PRINT((ndo, ""\n\tStart value: %u"", EXTRACT_32BITS(tptr))); + break; + + case VTP_JOIN_MESSAGE: + + /* FIXME - Could not find message format */ + break; + + default: + break; + } + + return; + + trunc: + ND_PRINT((ndo, ""[|vtp]"")); +} +",1,"vtp_print (netdissect_options *ndo, + const u_char *pptr, u_int length) +{ + int type, len, tlv_len, tlv_value, mgmtd_len; + const u_char *tptr; + const struct vtp_vlan_ *vtp_vlan; + + if (length < VTP_HEADER_LEN) + goto trunc; + + tptr = pptr; + + ND_TCHECK2(*tptr, VTP_HEADER_LEN); + + type = *(tptr+1); + ND_PRINT((ndo, ""VTPv%u, Message %s (0x%02x), length %u"", + *tptr, + tok2str(vtp_message_type_values,""Unknown message type"", type), + type, + length)); + + /* In non-verbose mode, just print version and message type */ + if (ndo->ndo_vflag < 1) { + return; + } + + /* verbose mode print all fields */ + ND_PRINT((ndo, ""\n\tDomain name: "")); + mgmtd_len = *(tptr + 3); + if (mgmtd_len < 1 || mgmtd_len > 32) { + ND_PRINT((ndo, "" [invalid MgmtD Len %d]"", mgmtd_len)); + return; + } + fn_printzp(ndo, tptr + 4, mgmtd_len, NULL); + ND_PRINT((ndo, "", %s: %u"", + tok2str(vtp_header_values, ""Unknown"", type), + *(tptr+2))); + + tptr += VTP_HEADER_LEN; + + switch (type) { + + case VTP_SUMMARY_ADV: + + /* + * SUMMARY ADVERTISEMENT + * + * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Version | Code | Followers | MgmtD Len | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Management Domain Name (zero-padded to 32 bytes) | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Configuration revision number | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Updater Identity IP address | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Update Timestamp (12 bytes) | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | MD5 digest (16 bytes) | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * + */ + + ND_TCHECK2(*tptr, 8); + ND_PRINT((ndo, ""\n\t Config Rev %x, Updater %s"", + EXTRACT_32BITS(tptr), + ipaddr_string(ndo, tptr+4))); + tptr += 8; + ND_TCHECK2(*tptr, VTP_UPDATE_TIMESTAMP_LEN); + ND_PRINT((ndo, "", Timestamp 0x%08x 0x%08x 0x%08x"", + EXTRACT_32BITS(tptr), + EXTRACT_32BITS(tptr + 4), + EXTRACT_32BITS(tptr + 8))); + tptr += VTP_UPDATE_TIMESTAMP_LEN; + ND_TCHECK2(*tptr, VTP_MD5_DIGEST_LEN); + ND_PRINT((ndo, "", MD5 digest: %08x%08x%08x%08x"", + EXTRACT_32BITS(tptr), + EXTRACT_32BITS(tptr + 4), + EXTRACT_32BITS(tptr + 8), + EXTRACT_32BITS(tptr + 12))); + tptr += VTP_MD5_DIGEST_LEN; + break; + + case VTP_SUBSET_ADV: + + /* + * SUBSET ADVERTISEMENT + * + * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Version | Code | Seq number | MgmtD Len | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Management Domain Name (zero-padded to 32 bytes) | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Configuration revision number | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | VLAN info field 1 | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | ................ | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | VLAN info field N | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * + */ + + ND_TCHECK_32BITS(tptr); + ND_PRINT((ndo, "", Config Rev %x"", EXTRACT_32BITS(tptr))); + + /* + * VLAN INFORMATION + * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | V info len | Status | VLAN type | VLAN name len | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | ISL vlan id | MTU size | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | 802.10 index (SAID) | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | VLAN name | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * + */ + + tptr += 4; + while (tptr < (pptr+length)) { + + ND_TCHECK_8BITS(tptr); + len = *tptr; + if (len == 0) + break; + + ND_TCHECK2(*tptr, len); + + vtp_vlan = (const struct vtp_vlan_*)tptr; + ND_TCHECK(*vtp_vlan); + ND_PRINT((ndo, ""\n\tVLAN info status %s, type %s, VLAN-id %u, MTU %u, SAID 0x%08x, Name "", + tok2str(vtp_vlan_status,""Unknown"",vtp_vlan->status), + tok2str(vtp_vlan_type_values,""Unknown"",vtp_vlan->type), + EXTRACT_16BITS(&vtp_vlan->vlanid), + EXTRACT_16BITS(&vtp_vlan->mtu), + EXTRACT_32BITS(&vtp_vlan->index))); + fn_printzp(ndo, tptr + VTP_VLAN_INFO_OFFSET, vtp_vlan->name_len, NULL); + + /* + * Vlan names are aligned to 32-bit boundaries. + */ + len -= VTP_VLAN_INFO_OFFSET + 4*((vtp_vlan->name_len + 3)/4); + tptr += VTP_VLAN_INFO_OFFSET + 4*((vtp_vlan->name_len + 3)/4); + + /* TLV information follows */ + + while (len > 0) { + + /* + * Cisco specs says 2 bytes for type + 2 bytes for length, take only 1 + * See: http://www.cisco.com/univercd/cc/td/doc/product/lan/trsrb/frames.htm + */ + type = *tptr; + tlv_len = *(tptr+1); + + ND_PRINT((ndo, ""\n\t\t%s (0x%04x) TLV"", + tok2str(vtp_vlan_tlv_values, ""Unknown"", type), + type)); + + /* + * infinite loop check + */ + if (type == 0 || tlv_len == 0) { + return; + } + + ND_TCHECK2(*tptr, tlv_len * 2 +2); + + tlv_value = EXTRACT_16BITS(tptr+2); + + switch (type) { + case VTP_VLAN_STE_HOP_COUNT: + ND_PRINT((ndo, "", %u"", tlv_value)); + break; + + case VTP_VLAN_PRUNING: + ND_PRINT((ndo, "", %s (%u)"", + tlv_value == 1 ? ""Enabled"" : ""Disabled"", + tlv_value)); + break; + + case VTP_VLAN_STP_TYPE: + ND_PRINT((ndo, "", %s (%u)"", + tok2str(vtp_stp_type_values, ""Unknown"", tlv_value), + tlv_value)); + break; + + case VTP_VLAN_BRIDGE_TYPE: + ND_PRINT((ndo, "", %s (%u)"", + tlv_value == 1 ? ""SRB"" : ""SRT"", + tlv_value)); + break; + + case VTP_VLAN_BACKUP_CRF_MODE: + ND_PRINT((ndo, "", %s (%u)"", + tlv_value == 1 ? ""Backup"" : ""Not backup"", + tlv_value)); + break; + + /* + * FIXME those are the defined TLVs that lack a decoder + * you are welcome to contribute code ;-) + */ + + case VTP_VLAN_SOURCE_ROUTING_RING_NUMBER: + case VTP_VLAN_SOURCE_ROUTING_BRIDGE_NUMBER: + case VTP_VLAN_PARENT_VLAN: + case VTP_VLAN_TRANS_BRIDGED_VLAN: + case VTP_VLAN_ARP_HOP_COUNT: + default: + print_unknown_data(ndo, tptr, ""\n\t\t "", 2 + tlv_len*2); + break; + } + len -= 2 + tlv_len*2; + tptr += 2 + tlv_len*2; + } + } + break; + + case VTP_ADV_REQUEST: + + /* + * ADVERTISEMENT REQUEST + * + * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Version | Code | Reserved | MgmtD Len | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Management Domain Name (zero-padded to 32 bytes) | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Start value | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * + */ + + ND_TCHECK2(*tptr, 4); + ND_PRINT((ndo, ""\n\tStart value: %u"", EXTRACT_32BITS(tptr))); + break; + + case VTP_JOIN_MESSAGE: + + /* FIXME - Could not find message format */ + break; + + default: + break; + } + + return; + + trunc: + ND_PRINT((ndo, ""[|vtp]"")); +} +","@@ -223,6 +223,7 @@ vtp_print (netdissect_options *ndo, + * + */ + ++ ND_TCHECK_32BITS(tptr); + ND_PRINT((ndo, "", Config Rev %x"", EXTRACT_32BITS(tptr))); + + /* +@@ -243,6 +244,7 @@ vtp_print (netdissect_options *ndo, + tptr += 4; + while (tptr < (pptr+length)) { + ++ ND_TCHECK_8BITS(tptr); + len = *tptr; + if (len == 0) + break;",2461,2792,4096 +6806,"static int do_ip_getsockopt(struct sock *sk, int level, int optname, + char __user *optval, int __user *optlen, unsigned int flags) +{ + struct inet_sock *inet = inet_sk(sk); + bool needs_rtnl = getsockopt_needs_rtnl(optname); + int val, err = 0; + int len; + + if (level != SOL_IP) + return -EOPNOTSUPP; + + if (ip_mroute_opt(optname)) + return ip_mroute_getsockopt(sk, optname, optval, optlen); + + if (get_user(len, optlen)) + return -EFAULT; + if (len < 0) + return -EINVAL; + + if (needs_rtnl) + rtnl_lock(); + lock_sock(sk); + + switch (optname) { + case IP_OPTIONS: + { + unsigned char optbuf[sizeof(struct ip_options)+40]; + struct ip_options *opt = (struct ip_options *)optbuf; + struct ip_options_rcu *inet_opt; + + inet_opt = rcu_dereference_protected(inet->inet_opt, + lockdep_sock_is_held(sk)); + opt->optlen = 0; + if (inet_opt) + memcpy(optbuf, &inet_opt->opt, + sizeof(struct ip_options) + + inet_opt->opt.optlen); + release_sock(sk); + + if (opt->optlen == 0) + return put_user(0, optlen); + + ip_options_undo(opt); + + len = min_t(unsigned int, len, opt->optlen); + if (put_user(len, optlen)) + return -EFAULT; + if (copy_to_user(optval, opt->__data, len)) + return -EFAULT; + return 0; + } + case IP_PKTINFO: + val = (inet->cmsg_flags & IP_CMSG_PKTINFO) != 0; + break; + case IP_RECVTTL: + val = (inet->cmsg_flags & IP_CMSG_TTL) != 0; + break; + case IP_RECVTOS: + val = (inet->cmsg_flags & IP_CMSG_TOS) != 0; + break; + case IP_RECVOPTS: + val = (inet->cmsg_flags & IP_CMSG_RECVOPTS) != 0; + break; + case IP_RETOPTS: + val = (inet->cmsg_flags & IP_CMSG_RETOPTS) != 0; + break; + case IP_PASSSEC: + val = (inet->cmsg_flags & IP_CMSG_PASSSEC) != 0; + break; + case IP_RECVORIGDSTADDR: + val = (inet->cmsg_flags & IP_CMSG_ORIGDSTADDR) != 0; + break; + case IP_CHECKSUM: + val = (inet->cmsg_flags & IP_CMSG_CHECKSUM) != 0; + break; + case IP_RECVFRAGSIZE: + val = (inet->cmsg_flags & IP_CMSG_RECVFRAGSIZE) != 0; + break; + case IP_TOS: + val = inet->tos; + break; + case IP_TTL: + { + struct net *net = sock_net(sk); + val = (inet->uc_ttl == -1 ? + net->ipv4.sysctl_ip_default_ttl : + inet->uc_ttl); + break; + } + case IP_HDRINCL: + val = inet->hdrincl; + break; + case IP_NODEFRAG: + val = inet->nodefrag; + break; + case IP_BIND_ADDRESS_NO_PORT: + val = inet->bind_address_no_port; + break; + case IP_MTU_DISCOVER: + val = inet->pmtudisc; + break; + case IP_MTU: + { + struct dst_entry *dst; + val = 0; + dst = sk_dst_get(sk); + if (dst) { + val = dst_mtu(dst); + dst_release(dst); + } + if (!val) { + release_sock(sk); + return -ENOTCONN; + } + break; + } + case IP_RECVERR: + val = inet->recverr; + break; + case IP_MULTICAST_TTL: + val = inet->mc_ttl; + break; + case IP_MULTICAST_LOOP: + val = inet->mc_loop; + break; + case IP_UNICAST_IF: + val = (__force int)htonl((__u32) inet->uc_index); + break; + case IP_MULTICAST_IF: + { + struct in_addr addr; + len = min_t(unsigned int, len, sizeof(struct in_addr)); + addr.s_addr = inet->mc_addr; + release_sock(sk); + + if (put_user(len, optlen)) + return -EFAULT; + if (copy_to_user(optval, &addr, len)) + return -EFAULT; + return 0; + } + case IP_MSFILTER: + { + struct ip_msfilter msf; + + if (len < IP_MSFILTER_SIZE(0)) { + err = -EINVAL; + goto out; + } + if (copy_from_user(&msf, optval, IP_MSFILTER_SIZE(0))) { + err = -EFAULT; + goto out; + } + err = ip_mc_msfget(sk, &msf, + (struct ip_msfilter __user *)optval, optlen); + goto out; + } + case MCAST_MSFILTER: + { + struct group_filter gsf; + + if (len < GROUP_FILTER_SIZE(0)) { + err = -EINVAL; + goto out; + } + if (copy_from_user(&gsf, optval, GROUP_FILTER_SIZE(0))) { + err = -EFAULT; + goto out; + } + err = ip_mc_gsfget(sk, &gsf, + (struct group_filter __user *)optval, + optlen); + goto out; + } + case IP_MULTICAST_ALL: + val = inet->mc_all; + break; + case IP_PKTOPTIONS: + { + struct msghdr msg; + + release_sock(sk); + + if (sk->sk_type != SOCK_STREAM) + return -ENOPROTOOPT; + + msg.msg_control = (__force void *) optval; + msg.msg_controllen = len; + msg.msg_flags = flags; + + if (inet->cmsg_flags & IP_CMSG_PKTINFO) { + struct in_pktinfo info; + + info.ipi_addr.s_addr = inet->inet_rcv_saddr; + info.ipi_spec_dst.s_addr = inet->inet_rcv_saddr; + info.ipi_ifindex = inet->mc_index; + put_cmsg(&msg, SOL_IP, IP_PKTINFO, sizeof(info), &info); + } + if (inet->cmsg_flags & IP_CMSG_TTL) { + int hlim = inet->mc_ttl; + put_cmsg(&msg, SOL_IP, IP_TTL, sizeof(hlim), &hlim); + } + if (inet->cmsg_flags & IP_CMSG_TOS) { + int tos = inet->rcv_tos; + put_cmsg(&msg, SOL_IP, IP_TOS, sizeof(tos), &tos); + } + len -= msg.msg_controllen; + return put_user(len, optlen); + } + case IP_FREEBIND: + val = inet->freebind; + break; + case IP_TRANSPARENT: + val = inet->transparent; + break; + case IP_MINTTL: + val = inet->min_ttl; + break; + default: + release_sock(sk); + return -ENOPROTOOPT; + } + release_sock(sk); + + if (len < sizeof(int) && len > 0 && val >= 0 && val <= 255) { + unsigned char ucval = (unsigned char)val; + len = 1; + if (put_user(len, optlen)) + return -EFAULT; + if (copy_to_user(optval, &ucval, 1)) + return -EFAULT; + } else { + len = min_t(unsigned int, sizeof(int), len); + if (put_user(len, optlen)) + return -EFAULT; + if (copy_to_user(optval, &val, len)) + return -EFAULT; + } + return 0; + +out: + release_sock(sk); + if (needs_rtnl) + rtnl_unlock(); + return err; +} +",0,"static int do_ip_getsockopt(struct sock *sk, int level, int optname, + char __user *optval, int __user *optlen, unsigned int flags) +{ + struct inet_sock *inet = inet_sk(sk); + bool needs_rtnl = getsockopt_needs_rtnl(optname); + int val, err = 0; + int len; + + if (level != SOL_IP) + return -EOPNOTSUPP; + + if (ip_mroute_opt(optname)) + return ip_mroute_getsockopt(sk, optname, optval, optlen); + + if (get_user(len, optlen)) + return -EFAULT; + if (len < 0) + return -EINVAL; + + if (needs_rtnl) + rtnl_lock(); + lock_sock(sk); + + switch (optname) { + case IP_OPTIONS: + { + unsigned char optbuf[sizeof(struct ip_options)+40]; + struct ip_options *opt = (struct ip_options *)optbuf; + struct ip_options_rcu *inet_opt; + + inet_opt = rcu_dereference_protected(inet->inet_opt, + lockdep_sock_is_held(sk)); + opt->optlen = 0; + if (inet_opt) + memcpy(optbuf, &inet_opt->opt, + sizeof(struct ip_options) + + inet_opt->opt.optlen); + release_sock(sk); + + if (opt->optlen == 0) + return put_user(0, optlen); + + ip_options_undo(opt); + + len = min_t(unsigned int, len, opt->optlen); + if (put_user(len, optlen)) + return -EFAULT; + if (copy_to_user(optval, opt->__data, len)) + return -EFAULT; + return 0; + } + case IP_PKTINFO: + val = (inet->cmsg_flags & IP_CMSG_PKTINFO) != 0; + break; + case IP_RECVTTL: + val = (inet->cmsg_flags & IP_CMSG_TTL) != 0; + break; + case IP_RECVTOS: + val = (inet->cmsg_flags & IP_CMSG_TOS) != 0; + break; + case IP_RECVOPTS: + val = (inet->cmsg_flags & IP_CMSG_RECVOPTS) != 0; + break; + case IP_RETOPTS: + val = (inet->cmsg_flags & IP_CMSG_RETOPTS) != 0; + break; + case IP_PASSSEC: + val = (inet->cmsg_flags & IP_CMSG_PASSSEC) != 0; + break; + case IP_RECVORIGDSTADDR: + val = (inet->cmsg_flags & IP_CMSG_ORIGDSTADDR) != 0; + break; + case IP_CHECKSUM: + val = (inet->cmsg_flags & IP_CMSG_CHECKSUM) != 0; + break; + case IP_RECVFRAGSIZE: + val = (inet->cmsg_flags & IP_CMSG_RECVFRAGSIZE) != 0; + break; + case IP_TOS: + val = inet->tos; + break; + case IP_TTL: + { + struct net *net = sock_net(sk); + val = (inet->uc_ttl == -1 ? + net->ipv4.sysctl_ip_default_ttl : + inet->uc_ttl); + break; + } + case IP_HDRINCL: + val = inet->hdrincl; + break; + case IP_NODEFRAG: + val = inet->nodefrag; + break; + case IP_BIND_ADDRESS_NO_PORT: + val = inet->bind_address_no_port; + break; + case IP_MTU_DISCOVER: + val = inet->pmtudisc; + break; + case IP_MTU: + { + struct dst_entry *dst; + val = 0; + dst = sk_dst_get(sk); + if (dst) { + val = dst_mtu(dst); + dst_release(dst); + } + if (!val) { + release_sock(sk); + return -ENOTCONN; + } + break; + } + case IP_RECVERR: + val = inet->recverr; + break; + case IP_MULTICAST_TTL: + val = inet->mc_ttl; + break; + case IP_MULTICAST_LOOP: + val = inet->mc_loop; + break; + case IP_UNICAST_IF: + val = (__force int)htonl((__u32) inet->uc_index); + break; + case IP_MULTICAST_IF: + { + struct in_addr addr; + len = min_t(unsigned int, len, sizeof(struct in_addr)); + addr.s_addr = inet->mc_addr; + release_sock(sk); + + if (put_user(len, optlen)) + return -EFAULT; + if (copy_to_user(optval, &addr, len)) + return -EFAULT; + return 0; + } + case IP_MSFILTER: + { + struct ip_msfilter msf; + + if (len < IP_MSFILTER_SIZE(0)) { + err = -EINVAL; + goto out; + } + if (copy_from_user(&msf, optval, IP_MSFILTER_SIZE(0))) { + err = -EFAULT; + goto out; + } + err = ip_mc_msfget(sk, &msf, + (struct ip_msfilter __user *)optval, optlen); + goto out; + } + case MCAST_MSFILTER: + { + struct group_filter gsf; + + if (len < GROUP_FILTER_SIZE(0)) { + err = -EINVAL; + goto out; + } + if (copy_from_user(&gsf, optval, GROUP_FILTER_SIZE(0))) { + err = -EFAULT; + goto out; + } + err = ip_mc_gsfget(sk, &gsf, + (struct group_filter __user *)optval, + optlen); + goto out; + } + case IP_MULTICAST_ALL: + val = inet->mc_all; + break; + case IP_PKTOPTIONS: + { + struct msghdr msg; + + release_sock(sk); + + if (sk->sk_type != SOCK_STREAM) + return -ENOPROTOOPT; + + msg.msg_control = (__force void *) optval; + msg.msg_controllen = len; + msg.msg_flags = flags; + + if (inet->cmsg_flags & IP_CMSG_PKTINFO) { + struct in_pktinfo info; + + info.ipi_addr.s_addr = inet->inet_rcv_saddr; + info.ipi_spec_dst.s_addr = inet->inet_rcv_saddr; + info.ipi_ifindex = inet->mc_index; + put_cmsg(&msg, SOL_IP, IP_PKTINFO, sizeof(info), &info); + } + if (inet->cmsg_flags & IP_CMSG_TTL) { + int hlim = inet->mc_ttl; + put_cmsg(&msg, SOL_IP, IP_TTL, sizeof(hlim), &hlim); + } + if (inet->cmsg_flags & IP_CMSG_TOS) { + int tos = inet->rcv_tos; + put_cmsg(&msg, SOL_IP, IP_TOS, sizeof(tos), &tos); + } + len -= msg.msg_controllen; + return put_user(len, optlen); + } + case IP_FREEBIND: + val = inet->freebind; + break; + case IP_TRANSPARENT: + val = inet->transparent; + break; + case IP_MINTTL: + val = inet->min_ttl; + break; + default: + release_sock(sk); + return -ENOPROTOOPT; + } + release_sock(sk); + + if (len < sizeof(int) && len > 0 && val >= 0 && val <= 255) { + unsigned char ucval = (unsigned char)val; + len = 1; + if (put_user(len, optlen)) + return -EFAULT; + if (copy_to_user(optval, &ucval, 1)) + return -EFAULT; + } else { + len = min_t(unsigned int, sizeof(int), len); + if (put_user(len, optlen)) + return -EFAULT; + if (copy_to_user(optval, &val, len)) + return -EFAULT; + } + return 0; + +out: + release_sock(sk); + if (needs_rtnl) + rtnl_unlock(); + return err; +} +","@@ -116,10 +116,10 @@ static void ip_cmsg_recv_checksum(struct msghdr *msg, struct sk_buff *skb, + if (skb->ip_summed != CHECKSUM_COMPLETE) + return; + +- if (offset != 0) +- csum = csum_sub(csum, +- csum_partial(skb_transport_header(skb) + tlen, +- offset, 0)); ++ if (offset != 0) { ++ int tend_off = skb_transport_offset(skb) + tlen; ++ csum = csum_sub(csum, skb_checksum(skb, tend_off, offset, 0)); ++ } + + put_cmsg(msg, SOL_IP, IP_CHECKSUM, sizeof(__wsum), &csum); + }",1776,2107,4096 +18108,"icmp_print(netdissect_options *ndo, const u_char *bp, u_int plen, const u_char *bp2, + int fragmented) +{ + char *cp; + const struct icmp *dp; + const struct icmp_ext_t *ext_dp; + const struct ip *ip; + const char *str, *fmt; + const struct ip *oip; + const struct udphdr *ouh; + const uint8_t *obj_tptr; + uint32_t raw_label; + const u_char *snapend_save; + const struct icmp_mpls_ext_object_header_t *icmp_mpls_ext_object_header; + u_int hlen, dport, mtu, obj_tlen, obj_class_num, obj_ctype; + char buf[MAXHOSTNAMELEN + 100]; + struct cksum_vec vec[1]; + + dp = (const struct icmp *)bp; + ext_dp = (const struct icmp_ext_t *)bp; + ip = (const struct ip *)bp2; + str = buf; + + ND_TCHECK(dp->icmp_code); + switch (dp->icmp_type) { + + case ICMP_ECHO: + case ICMP_ECHOREPLY: + ND_TCHECK(dp->icmp_seq); + (void)snprintf(buf, sizeof(buf), ""echo %s, id %u, seq %u"", + dp->icmp_type == ICMP_ECHO ? + ""request"" : ""reply"", + EXTRACT_16BITS(&dp->icmp_id), + EXTRACT_16BITS(&dp->icmp_seq)); + break; + + case ICMP_UNREACH: + ND_TCHECK(dp->icmp_ip.ip_dst); + switch (dp->icmp_code) { + + case ICMP_UNREACH_PROTOCOL: + ND_TCHECK(dp->icmp_ip.ip_p); + (void)snprintf(buf, sizeof(buf), + ""%s protocol %d unreachable"", + ipaddr_string(ndo, &dp->icmp_ip.ip_dst), + dp->icmp_ip.ip_p); + break; + + case ICMP_UNREACH_PORT: + ND_TCHECK(dp->icmp_ip.ip_p); + oip = &dp->icmp_ip; + hlen = IP_HL(oip) * 4; + ouh = (const struct udphdr *)(((const u_char *)oip) + hlen); + ND_TCHECK(ouh->uh_dport); + dport = EXTRACT_16BITS(&ouh->uh_dport); + switch (oip->ip_p) { + + case IPPROTO_TCP: + (void)snprintf(buf, sizeof(buf), + ""%s tcp port %s unreachable"", + ipaddr_string(ndo, &oip->ip_dst), + tcpport_string(ndo, dport)); + break; + + case IPPROTO_UDP: + (void)snprintf(buf, sizeof(buf), + ""%s udp port %s unreachable"", + ipaddr_string(ndo, &oip->ip_dst), + udpport_string(ndo, dport)); + break; + + default: + (void)snprintf(buf, sizeof(buf), + ""%s protocol %d port %d unreachable"", + ipaddr_string(ndo, &oip->ip_dst), + oip->ip_p, dport); + break; + } + break; + + case ICMP_UNREACH_NEEDFRAG: + { + register const struct mtu_discovery *mp; + mp = (const struct mtu_discovery *)(const u_char *)&dp->icmp_void; + mtu = EXTRACT_16BITS(&mp->nexthopmtu); + if (mtu) { + (void)snprintf(buf, sizeof(buf), + ""%s unreachable - need to frag (mtu %d)"", + ipaddr_string(ndo, &dp->icmp_ip.ip_dst), mtu); + } else { + (void)snprintf(buf, sizeof(buf), + ""%s unreachable - need to frag"", + ipaddr_string(ndo, &dp->icmp_ip.ip_dst)); + } + } + break; + + default: + fmt = tok2str(unreach2str, ""#%d %%s unreachable"", + dp->icmp_code); + (void)snprintf(buf, sizeof(buf), fmt, + ipaddr_string(ndo, &dp->icmp_ip.ip_dst)); + break; + } + break; + + case ICMP_REDIRECT: + ND_TCHECK(dp->icmp_ip.ip_dst); + fmt = tok2str(type2str, ""redirect-#%d %%s to net %%s"", + dp->icmp_code); + (void)snprintf(buf, sizeof(buf), fmt, + ipaddr_string(ndo, &dp->icmp_ip.ip_dst), + ipaddr_string(ndo, &dp->icmp_gwaddr)); + break; + + case ICMP_ROUTERADVERT: + { + register const struct ih_rdiscovery *ihp; + register const struct id_rdiscovery *idp; + u_int lifetime, num, size; + + (void)snprintf(buf, sizeof(buf), ""router advertisement""); + cp = buf + strlen(buf); + + ihp = (const struct ih_rdiscovery *)&dp->icmp_void; + ND_TCHECK(*ihp); + (void)strncpy(cp, "" lifetime "", sizeof(buf) - (cp - buf)); + cp = buf + strlen(buf); + lifetime = EXTRACT_16BITS(&ihp->ird_lifetime); + if (lifetime < 60) { + (void)snprintf(cp, sizeof(buf) - (cp - buf), ""%u"", + lifetime); + } else if (lifetime < 60 * 60) { + (void)snprintf(cp, sizeof(buf) - (cp - buf), ""%u:%02u"", + lifetime / 60, lifetime % 60); + } else { + (void)snprintf(cp, sizeof(buf) - (cp - buf), + ""%u:%02u:%02u"", + lifetime / 3600, + (lifetime % 3600) / 60, + lifetime % 60); + } + cp = buf + strlen(buf); + + num = ihp->ird_addrnum; + (void)snprintf(cp, sizeof(buf) - (cp - buf), "" %d:"", num); + cp = buf + strlen(buf); + + size = ihp->ird_addrsiz; + if (size != 2) { + (void)snprintf(cp, sizeof(buf) - (cp - buf), + "" [size %d]"", size); + break; + } + idp = (const struct id_rdiscovery *)&dp->icmp_data; + while (num-- > 0) { + ND_TCHECK(*idp); + (void)snprintf(cp, sizeof(buf) - (cp - buf), "" {%s %u}"", + ipaddr_string(ndo, &idp->ird_addr), + EXTRACT_32BITS(&idp->ird_pref)); + cp = buf + strlen(buf); + ++idp; + } + } + break; + + case ICMP_TIMXCEED: + ND_TCHECK(dp->icmp_ip.ip_dst); + switch (dp->icmp_code) { + + case ICMP_TIMXCEED_INTRANS: + str = ""time exceeded in-transit""; + break; + + case ICMP_TIMXCEED_REASS: + str = ""ip reassembly time exceeded""; + break; + + default: + (void)snprintf(buf, sizeof(buf), ""time exceeded-#%d"", + dp->icmp_code); + break; + } + break; + + case ICMP_PARAMPROB: + if (dp->icmp_code) + (void)snprintf(buf, sizeof(buf), + ""parameter problem - code %d"", dp->icmp_code); + else { + ND_TCHECK(dp->icmp_pptr); + (void)snprintf(buf, sizeof(buf), + ""parameter problem - octet %d"", dp->icmp_pptr); + } + break; + + case ICMP_MASKREPLY: + ND_TCHECK(dp->icmp_mask); + (void)snprintf(buf, sizeof(buf), ""address mask is 0x%08x"", + EXTRACT_32BITS(&dp->icmp_mask)); + break; + + case ICMP_TSTAMP: + ND_TCHECK(dp->icmp_seq); + (void)snprintf(buf, sizeof(buf), + ""time stamp query id %u seq %u"", + EXTRACT_16BITS(&dp->icmp_id), + EXTRACT_16BITS(&dp->icmp_seq)); + break; + + case ICMP_TSTAMPREPLY: + ND_TCHECK(dp->icmp_ttime); + (void)snprintf(buf, sizeof(buf), + ""time stamp reply id %u seq %u: org %s"", + EXTRACT_16BITS(&dp->icmp_id), + EXTRACT_16BITS(&dp->icmp_seq), + icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_otime))); + + (void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),"", recv %s"", + icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_rtime))); + (void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),"", xmit %s"", + icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_ttime))); + break; + + default: + str = tok2str(icmp2str, ""type-#%d"", dp->icmp_type); + break; + } + ND_PRINT((ndo, ""ICMP %s, length %u"", str, plen)); + if (ndo->ndo_vflag && !fragmented) { /* don't attempt checksumming if this is a frag */ + uint16_t sum, icmp_sum; + + if (ND_TTEST2(*bp, plen)) { + vec[0].ptr = (const uint8_t *)(const void *)dp; + vec[0].len = plen; + sum = in_cksum(vec, 1); + if (sum != 0) { + icmp_sum = EXTRACT_16BITS(&dp->icmp_cksum); + ND_PRINT((ndo, "" (wrong icmp cksum %x (->%x)!)"", + icmp_sum, + in_cksum_shouldbe(icmp_sum, sum))); + } + } + } + + /* + * print the remnants of the IP packet. + * save the snaplength as this may get overidden in the IP printer. + */ + if (ndo->ndo_vflag >= 1 && ICMP_ERRTYPE(dp->icmp_type)) { + bp += 8; + ND_PRINT((ndo, ""\n\t"")); + ip = (const struct ip *)bp; + snapend_save = ndo->ndo_snapend; + ip_print(ndo, bp, EXTRACT_16BITS(&ip->ip_len)); + ndo->ndo_snapend = snapend_save; + } + + /* + * Attempt to decode the MPLS extensions only for some ICMP types. + */ + if (ndo->ndo_vflag >= 1 && plen > ICMP_EXTD_MINLEN && ICMP_MPLS_EXT_TYPE(dp->icmp_type)) { + + ND_TCHECK(*ext_dp); + + /* + * Check first if the mpls extension header shows a non-zero length. + * If the length field is not set then silently verify the checksum + * to check if an extension header is present. This is expedient, + * however not all implementations set the length field proper. + */ + if (!ext_dp->icmp_length) { + vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res; + vec[0].len = plen - ICMP_EXTD_MINLEN; + if (in_cksum(vec, 1)) { + return; + } + } + + ND_PRINT((ndo, ""\n\tMPLS extension v%u"", + ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res)))); + + /* + * Sanity checking of the header. + */ + if (ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res)) != + ICMP_MPLS_EXT_VERSION) { + ND_PRINT((ndo, "" packet not supported"")); + return; + } + + hlen = plen - ICMP_EXTD_MINLEN; + vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res; + vec[0].len = hlen; + ND_PRINT((ndo, "", checksum 0x%04x (%scorrect), length %u"", + EXTRACT_16BITS(ext_dp->icmp_ext_checksum), + in_cksum(vec, 1) ? ""in"" : """", + hlen)); + + hlen -= 4; /* subtract common header size */ + obj_tptr = (const uint8_t *)ext_dp->icmp_ext_data; + + while (hlen > sizeof(struct icmp_mpls_ext_object_header_t)) { + + icmp_mpls_ext_object_header = (const struct icmp_mpls_ext_object_header_t *)obj_tptr; + ND_TCHECK(*icmp_mpls_ext_object_header); + obj_tlen = EXTRACT_16BITS(icmp_mpls_ext_object_header->length); + obj_class_num = icmp_mpls_ext_object_header->class_num; + obj_ctype = icmp_mpls_ext_object_header->ctype; + obj_tptr += sizeof(struct icmp_mpls_ext_object_header_t); + + ND_PRINT((ndo, ""\n\t %s Object (%u), Class-Type: %u, length %u"", + tok2str(icmp_mpls_ext_obj_values,""unknown"",obj_class_num), + obj_class_num, + obj_ctype, + obj_tlen)); + + hlen-=sizeof(struct icmp_mpls_ext_object_header_t); /* length field includes tlv header */ + + /* infinite loop protection */ + if ((obj_class_num == 0) || + (obj_tlen < sizeof(struct icmp_mpls_ext_object_header_t))) { + return; + } + obj_tlen-=sizeof(struct icmp_mpls_ext_object_header_t); + + switch (obj_class_num) { + case 1: + switch(obj_ctype) { + case 1: + ND_TCHECK2(*obj_tptr, 4); + raw_label = EXTRACT_32BITS(obj_tptr); + ND_PRINT((ndo, ""\n\t label %u, exp %u"", MPLS_LABEL(raw_label), MPLS_EXP(raw_label))); + if (MPLS_STACK(raw_label)) + ND_PRINT((ndo, "", [S]"")); + ND_PRINT((ndo, "", ttl %u"", MPLS_TTL(raw_label))); + break; + default: + print_unknown_data(ndo, obj_tptr, ""\n\t "", obj_tlen); + } + break; + + /* + * FIXME those are the defined objects that lack a decoder + * you are welcome to contribute code ;-) + */ + case 2: + default: + print_unknown_data(ndo, obj_tptr, ""\n\t "", obj_tlen); + break; + } + if (hlen < obj_tlen) + break; + hlen -= obj_tlen; + obj_tptr += obj_tlen; + } + } + + return; +trunc: + ND_PRINT((ndo, ""[|icmp]"")); +} +",1,"icmp_print(netdissect_options *ndo, const u_char *bp, u_int plen, const u_char *bp2, + int fragmented) +{ + char *cp; + const struct icmp *dp; + const struct icmp_ext_t *ext_dp; + const struct ip *ip; + const char *str, *fmt; + const struct ip *oip; + const struct udphdr *ouh; + const uint8_t *obj_tptr; + uint32_t raw_label; + const u_char *snapend_save; + const struct icmp_mpls_ext_object_header_t *icmp_mpls_ext_object_header; + u_int hlen, dport, mtu, obj_tlen, obj_class_num, obj_ctype; + char buf[MAXHOSTNAMELEN + 100]; + struct cksum_vec vec[1]; + + dp = (const struct icmp *)bp; + ext_dp = (const struct icmp_ext_t *)bp; + ip = (const struct ip *)bp2; + str = buf; + + ND_TCHECK(dp->icmp_code); + switch (dp->icmp_type) { + + case ICMP_ECHO: + case ICMP_ECHOREPLY: + ND_TCHECK(dp->icmp_seq); + (void)snprintf(buf, sizeof(buf), ""echo %s, id %u, seq %u"", + dp->icmp_type == ICMP_ECHO ? + ""request"" : ""reply"", + EXTRACT_16BITS(&dp->icmp_id), + EXTRACT_16BITS(&dp->icmp_seq)); + break; + + case ICMP_UNREACH: + ND_TCHECK(dp->icmp_ip.ip_dst); + switch (dp->icmp_code) { + + case ICMP_UNREACH_PROTOCOL: + ND_TCHECK(dp->icmp_ip.ip_p); + (void)snprintf(buf, sizeof(buf), + ""%s protocol %d unreachable"", + ipaddr_string(ndo, &dp->icmp_ip.ip_dst), + dp->icmp_ip.ip_p); + break; + + case ICMP_UNREACH_PORT: + ND_TCHECK(dp->icmp_ip.ip_p); + oip = &dp->icmp_ip; + hlen = IP_HL(oip) * 4; + ouh = (const struct udphdr *)(((const u_char *)oip) + hlen); + ND_TCHECK(ouh->uh_dport); + dport = EXTRACT_16BITS(&ouh->uh_dport); + switch (oip->ip_p) { + + case IPPROTO_TCP: + (void)snprintf(buf, sizeof(buf), + ""%s tcp port %s unreachable"", + ipaddr_string(ndo, &oip->ip_dst), + tcpport_string(ndo, dport)); + break; + + case IPPROTO_UDP: + (void)snprintf(buf, sizeof(buf), + ""%s udp port %s unreachable"", + ipaddr_string(ndo, &oip->ip_dst), + udpport_string(ndo, dport)); + break; + + default: + (void)snprintf(buf, sizeof(buf), + ""%s protocol %d port %d unreachable"", + ipaddr_string(ndo, &oip->ip_dst), + oip->ip_p, dport); + break; + } + break; + + case ICMP_UNREACH_NEEDFRAG: + { + register const struct mtu_discovery *mp; + mp = (const struct mtu_discovery *)(const u_char *)&dp->icmp_void; + mtu = EXTRACT_16BITS(&mp->nexthopmtu); + if (mtu) { + (void)snprintf(buf, sizeof(buf), + ""%s unreachable - need to frag (mtu %d)"", + ipaddr_string(ndo, &dp->icmp_ip.ip_dst), mtu); + } else { + (void)snprintf(buf, sizeof(buf), + ""%s unreachable - need to frag"", + ipaddr_string(ndo, &dp->icmp_ip.ip_dst)); + } + } + break; + + default: + fmt = tok2str(unreach2str, ""#%d %%s unreachable"", + dp->icmp_code); + (void)snprintf(buf, sizeof(buf), fmt, + ipaddr_string(ndo, &dp->icmp_ip.ip_dst)); + break; + } + break; + + case ICMP_REDIRECT: + ND_TCHECK(dp->icmp_ip.ip_dst); + fmt = tok2str(type2str, ""redirect-#%d %%s to net %%s"", + dp->icmp_code); + (void)snprintf(buf, sizeof(buf), fmt, + ipaddr_string(ndo, &dp->icmp_ip.ip_dst), + ipaddr_string(ndo, &dp->icmp_gwaddr)); + break; + + case ICMP_ROUTERADVERT: + { + register const struct ih_rdiscovery *ihp; + register const struct id_rdiscovery *idp; + u_int lifetime, num, size; + + (void)snprintf(buf, sizeof(buf), ""router advertisement""); + cp = buf + strlen(buf); + + ihp = (const struct ih_rdiscovery *)&dp->icmp_void; + ND_TCHECK(*ihp); + (void)strncpy(cp, "" lifetime "", sizeof(buf) - (cp - buf)); + cp = buf + strlen(buf); + lifetime = EXTRACT_16BITS(&ihp->ird_lifetime); + if (lifetime < 60) { + (void)snprintf(cp, sizeof(buf) - (cp - buf), ""%u"", + lifetime); + } else if (lifetime < 60 * 60) { + (void)snprintf(cp, sizeof(buf) - (cp - buf), ""%u:%02u"", + lifetime / 60, lifetime % 60); + } else { + (void)snprintf(cp, sizeof(buf) - (cp - buf), + ""%u:%02u:%02u"", + lifetime / 3600, + (lifetime % 3600) / 60, + lifetime % 60); + } + cp = buf + strlen(buf); + + num = ihp->ird_addrnum; + (void)snprintf(cp, sizeof(buf) - (cp - buf), "" %d:"", num); + cp = buf + strlen(buf); + + size = ihp->ird_addrsiz; + if (size != 2) { + (void)snprintf(cp, sizeof(buf) - (cp - buf), + "" [size %d]"", size); + break; + } + idp = (const struct id_rdiscovery *)&dp->icmp_data; + while (num-- > 0) { + ND_TCHECK(*idp); + (void)snprintf(cp, sizeof(buf) - (cp - buf), "" {%s %u}"", + ipaddr_string(ndo, &idp->ird_addr), + EXTRACT_32BITS(&idp->ird_pref)); + cp = buf + strlen(buf); + ++idp; + } + } + break; + + case ICMP_TIMXCEED: + ND_TCHECK(dp->icmp_ip.ip_dst); + switch (dp->icmp_code) { + + case ICMP_TIMXCEED_INTRANS: + str = ""time exceeded in-transit""; + break; + + case ICMP_TIMXCEED_REASS: + str = ""ip reassembly time exceeded""; + break; + + default: + (void)snprintf(buf, sizeof(buf), ""time exceeded-#%d"", + dp->icmp_code); + break; + } + break; + + case ICMP_PARAMPROB: + if (dp->icmp_code) + (void)snprintf(buf, sizeof(buf), + ""parameter problem - code %d"", dp->icmp_code); + else { + ND_TCHECK(dp->icmp_pptr); + (void)snprintf(buf, sizeof(buf), + ""parameter problem - octet %d"", dp->icmp_pptr); + } + break; + + case ICMP_MASKREPLY: + ND_TCHECK(dp->icmp_mask); + (void)snprintf(buf, sizeof(buf), ""address mask is 0x%08x"", + EXTRACT_32BITS(&dp->icmp_mask)); + break; + + case ICMP_TSTAMP: + ND_TCHECK(dp->icmp_seq); + (void)snprintf(buf, sizeof(buf), + ""time stamp query id %u seq %u"", + EXTRACT_16BITS(&dp->icmp_id), + EXTRACT_16BITS(&dp->icmp_seq)); + break; + + case ICMP_TSTAMPREPLY: + ND_TCHECK(dp->icmp_ttime); + (void)snprintf(buf, sizeof(buf), + ""time stamp reply id %u seq %u: org %s"", + EXTRACT_16BITS(&dp->icmp_id), + EXTRACT_16BITS(&dp->icmp_seq), + icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_otime))); + + (void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),"", recv %s"", + icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_rtime))); + (void)snprintf(buf+strlen(buf),sizeof(buf)-strlen(buf),"", xmit %s"", + icmp_tstamp_print(EXTRACT_32BITS(&dp->icmp_ttime))); + break; + + default: + str = tok2str(icmp2str, ""type-#%d"", dp->icmp_type); + break; + } + ND_PRINT((ndo, ""ICMP %s, length %u"", str, plen)); + if (ndo->ndo_vflag && !fragmented) { /* don't attempt checksumming if this is a frag */ + uint16_t sum, icmp_sum; + + if (ND_TTEST2(*bp, plen)) { + vec[0].ptr = (const uint8_t *)(const void *)dp; + vec[0].len = plen; + sum = in_cksum(vec, 1); + if (sum != 0) { + icmp_sum = EXTRACT_16BITS(&dp->icmp_cksum); + ND_PRINT((ndo, "" (wrong icmp cksum %x (->%x)!)"", + icmp_sum, + in_cksum_shouldbe(icmp_sum, sum))); + } + } + } + + /* + * print the remnants of the IP packet. + * save the snaplength as this may get overidden in the IP printer. + */ + if (ndo->ndo_vflag >= 1 && ICMP_ERRTYPE(dp->icmp_type)) { + bp += 8; + ND_PRINT((ndo, ""\n\t"")); + ip = (const struct ip *)bp; + snapend_save = ndo->ndo_snapend; + ip_print(ndo, bp, EXTRACT_16BITS(&ip->ip_len)); + ndo->ndo_snapend = snapend_save; + } + + /* + * Attempt to decode the MPLS extensions only for some ICMP types. + */ + if (ndo->ndo_vflag >= 1 && plen > ICMP_EXTD_MINLEN && ICMP_MPLS_EXT_TYPE(dp->icmp_type)) { + + ND_TCHECK(*ext_dp); + + /* + * Check first if the mpls extension header shows a non-zero length. + * If the length field is not set then silently verify the checksum + * to check if an extension header is present. This is expedient, + * however not all implementations set the length field proper. + */ + if (!ext_dp->icmp_length && + ND_TTEST2(ext_dp->icmp_ext_version_res, plen - ICMP_EXTD_MINLEN)) { + vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res; + vec[0].len = plen - ICMP_EXTD_MINLEN; + if (in_cksum(vec, 1)) { + return; + } + } + + ND_PRINT((ndo, ""\n\tMPLS extension v%u"", + ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res)))); + + /* + * Sanity checking of the header. + */ + if (ICMP_MPLS_EXT_EXTRACT_VERSION(*(ext_dp->icmp_ext_version_res)) != + ICMP_MPLS_EXT_VERSION) { + ND_PRINT((ndo, "" packet not supported"")); + return; + } + + hlen = plen - ICMP_EXTD_MINLEN; + if (ND_TTEST2(ext_dp->icmp_ext_version_res, hlen)) { + vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res; + vec[0].len = hlen; + ND_PRINT((ndo, "", checksum 0x%04x (%scorrect), length %u"", + EXTRACT_16BITS(ext_dp->icmp_ext_checksum), + in_cksum(vec, 1) ? ""in"" : """", + hlen)); + } + + hlen -= 4; /* subtract common header size */ + obj_tptr = (const uint8_t *)ext_dp->icmp_ext_data; + + while (hlen > sizeof(struct icmp_mpls_ext_object_header_t)) { + + icmp_mpls_ext_object_header = (const struct icmp_mpls_ext_object_header_t *)obj_tptr; + ND_TCHECK(*icmp_mpls_ext_object_header); + obj_tlen = EXTRACT_16BITS(icmp_mpls_ext_object_header->length); + obj_class_num = icmp_mpls_ext_object_header->class_num; + obj_ctype = icmp_mpls_ext_object_header->ctype; + obj_tptr += sizeof(struct icmp_mpls_ext_object_header_t); + + ND_PRINT((ndo, ""\n\t %s Object (%u), Class-Type: %u, length %u"", + tok2str(icmp_mpls_ext_obj_values,""unknown"",obj_class_num), + obj_class_num, + obj_ctype, + obj_tlen)); + + hlen-=sizeof(struct icmp_mpls_ext_object_header_t); /* length field includes tlv header */ + + /* infinite loop protection */ + if ((obj_class_num == 0) || + (obj_tlen < sizeof(struct icmp_mpls_ext_object_header_t))) { + return; + } + obj_tlen-=sizeof(struct icmp_mpls_ext_object_header_t); + + switch (obj_class_num) { + case 1: + switch(obj_ctype) { + case 1: + ND_TCHECK2(*obj_tptr, 4); + raw_label = EXTRACT_32BITS(obj_tptr); + ND_PRINT((ndo, ""\n\t label %u, exp %u"", MPLS_LABEL(raw_label), MPLS_EXP(raw_label))); + if (MPLS_STACK(raw_label)) + ND_PRINT((ndo, "", [S]"")); + ND_PRINT((ndo, "", ttl %u"", MPLS_TTL(raw_label))); + break; + default: + print_unknown_data(ndo, obj_tptr, ""\n\t "", obj_tlen); + } + break; + + /* + * FIXME those are the defined objects that lack a decoder + * you are welcome to contribute code ;-) + */ + case 2: + default: + print_unknown_data(ndo, obj_tptr, ""\n\t "", obj_tlen); + break; + } + if (hlen < obj_tlen) + break; + hlen -= obj_tlen; + obj_tptr += obj_tlen; + } + } + + return; +trunc: + ND_PRINT((ndo, ""[|icmp]"")); +} +","@@ -598,7 +598,8 @@ icmp_print(netdissect_options *ndo, const u_char *bp, u_int plen, const u_char * + * to check if an extension header is present. This is expedient, + * however not all implementations set the length field proper. + */ +- if (!ext_dp->icmp_length) { ++ if (!ext_dp->icmp_length && ++ ND_TTEST2(ext_dp->icmp_ext_version_res, plen - ICMP_EXTD_MINLEN)) { + vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res; + vec[0].len = plen - ICMP_EXTD_MINLEN; + if (in_cksum(vec, 1)) { +@@ -619,12 +620,14 @@ icmp_print(netdissect_options *ndo, const u_char *bp, u_int plen, const u_char * + } + + hlen = plen - ICMP_EXTD_MINLEN; +- vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res; +- vec[0].len = hlen; +- ND_PRINT((ndo, "", checksum 0x%04x (%scorrect), length %u"", +- EXTRACT_16BITS(ext_dp->icmp_ext_checksum), +- in_cksum(vec, 1) ? ""in"" : """", +- hlen)); ++ if (ND_TTEST2(ext_dp->icmp_ext_version_res, hlen)) { ++ vec[0].ptr = (const uint8_t *)(const void *)&ext_dp->icmp_ext_version_res; ++ vec[0].len = hlen; ++ ND_PRINT((ndo, "", checksum 0x%04x (%scorrect), length %u"", ++ EXTRACT_16BITS(ext_dp->icmp_ext_checksum), ++ in_cksum(vec, 1) ? ""in"" : """", ++ hlen)); ++ } + + hlen -= 4; /* subtract common header size */ + obj_tptr = (const uint8_t *)ext_dp->icmp_ext_data;",3266,3597,4096 +18154,"ModuleExport MagickBooleanType ReadPSDLayers(Image *image, + const ImageInfo *image_info,const PSDInfo *psd_info, + const MagickBooleanType skip_layers,ExceptionInfo *exception) +{ + char + type[4]; + + LayerInfo + *layer_info; + + MagickSizeType + size; + + MagickBooleanType + status; + + register ssize_t + i; + + ssize_t + count, + j, + number_layers; + + size=GetPSDSize(psd_info,image); + if (size == 0) + { + /* + Skip layers & masks. + */ + (void) ReadBlobLong(image); + count=ReadBlob(image,4,(unsigned char *) type); + ReversePSDString(image,type,4); + status=MagickFalse; + if ((count == 0) || (LocaleNCompare(type,""8BIM"",4) != 0)) + return(MagickTrue); + else + { + count=ReadBlob(image,4,(unsigned char *) type); + ReversePSDString(image,type,4); + if ((count != 0) && (LocaleNCompare(type,""Lr16"",4) == 0)) + size=GetPSDSize(psd_info,image); + else + return(MagickTrue); + } + } + status=MagickTrue; + if (size != 0) + { + layer_info=(LayerInfo *) NULL; + number_layers=(short) ReadBlobShort(image); + + if (number_layers < 0) + { + /* + The first alpha channel in the merged result contains the + transparency data for the merged result. + */ + number_layers=MagickAbsoluteValue(number_layers); + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" negative layer count corrected for""); + image->alpha_trait=BlendPixelTrait; + } + + /* + We only need to know if the image has an alpha channel + */ + if (skip_layers != MagickFalse) + return(MagickTrue); + + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" image contains %.20g layers"",(double) number_layers); + + if (number_layers == 0) + ThrowBinaryException(CorruptImageError,""InvalidNumberOfLayers"", + image->filename); + + layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, + sizeof(*layer_info)); + if (layer_info == (LayerInfo *) NULL) + { + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" allocation of LayerInfo failed""); + ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", + image->filename); + } + (void) ResetMagickMemory(layer_info,0,(size_t) number_layers* + sizeof(*layer_info)); + + for (i=0; i < number_layers; i++) + { + ssize_t + x, + y; + + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" reading layer #%.20g"",(double) i+1); + layer_info[i].page.y=ReadBlobSignedLong(image); + layer_info[i].page.x=ReadBlobSignedLong(image); + y=ReadBlobSignedLong(image); + x=ReadBlobSignedLong(image); + layer_info[i].page.width=(size_t) (x-layer_info[i].page.x); + layer_info[i].page.height=(size_t) (y-layer_info[i].page.y); + layer_info[i].channels=ReadBlobShort(image); + if (layer_info[i].channels > MaxPSDChannels) + { + layer_info=DestroyLayerInfo(layer_info,number_layers); + ThrowBinaryException(CorruptImageError,""MaximumChannelsExceeded"", + image->filename); + } + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g"", + (double) layer_info[i].page.x,(double) layer_info[i].page.y, + (double) layer_info[i].page.height,(double) + layer_info[i].page.width,(double) layer_info[i].channels); + for (j=0; j < (ssize_t) layer_info[i].channels; j++) + { + layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); + layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, + image); + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" channel[%.20g]: type=%.20g, size=%.20g"",(double) j, + (double) layer_info[i].channel_info[j].type, + (double) layer_info[i].channel_info[j].size); + } + count=ReadBlob(image,4,(unsigned char *) type); + ReversePSDString(image,type,4); + if ((count == 0) || (LocaleNCompare(type,""8BIM"",4) != 0)) + { + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" layer type was %.4s instead of 8BIM"", type); + layer_info=DestroyLayerInfo(layer_info,number_layers); + ThrowBinaryException(CorruptImageError,""ImproperImageHeader"", + image->filename); + } + count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); + ReversePSDString(image,layer_info[i].blendkey,4); + layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) + ReadBlobByte(image)); + layer_info[i].clipping=(unsigned char) ReadBlobByte(image); + layer_info[i].flags=(unsigned char) ReadBlobByte(image); + layer_info[i].visible=!(layer_info[i].flags & 0x02); + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s"", + layer_info[i].blendkey,(double) layer_info[i].opacity, + layer_info[i].clipping ? ""true"" : ""false"",layer_info[i].flags, + layer_info[i].visible ? ""true"" : ""false""); + (void) ReadBlobByte(image); /* filler */ + + size=ReadBlobLong(image); + if (size != 0) + { + MagickSizeType + combined_length, + length; + + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" layer contains additional info""); + length=ReadBlobLong(image); + combined_length=length+4; + if (length != 0) + { + /* + Layer mask info. + */ + layer_info[i].mask.page.y=ReadBlobSignedLong(image); + layer_info[i].mask.page.x=ReadBlobSignedLong(image); + layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)- + layer_info[i].mask.page.y); + layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)- + layer_info[i].mask.page.x); + layer_info[i].mask.background=(unsigned char) ReadBlobByte( + image); + layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); + if (!(layer_info[i].mask.flags & 0x01)) + { + layer_info[i].mask.page.y=layer_info[i].mask.page.y- + layer_info[i].page.y; + layer_info[i].mask.page.x=layer_info[i].mask.page.x- + layer_info[i].page.x; + } + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g"", + (double) layer_info[i].mask.page.x,(double) + layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width, + (double) layer_info[i].mask.page.height,(double) + ((MagickOffsetType) length)-18); + /* + Skip over the rest of the layer mask information. + */ + if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) + { + layer_info=DestroyLayerInfo(layer_info,number_layers); + ThrowBinaryException(CorruptImageError,""UnexpectedEndOfFile"", + image->filename); + } + } + length=ReadBlobLong(image); + combined_length+=length+4; + if (length != 0) + { + /* + Layer blending ranges info. + */ + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" layer blending ranges: length=%.20g"",(double) + ((MagickOffsetType) length)); + /* + We read it, but don't use it... + */ + for (j=0; j < (ssize_t) length; j+=8) + { + size_t blend_source=ReadBlobLong(image); + size_t blend_dest=ReadBlobLong(image); + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" source(%x), dest(%x)"",(unsigned int) + blend_source,(unsigned int) blend_dest); + } + } + /* + Layer name. + */ + length=(MagickSizeType) ReadBlobByte(image); + combined_length+=length+1; + if (length > 0) + (void) ReadBlob(image,(size_t) length++,layer_info[i].name); + layer_info[i].name[length]='\0'; + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" layer name: %s"",layer_info[i].name); + if ((length % 4) != 0) + { + length=4-(length % 4); + combined_length+=length; + /* Skip over the padding of the layer name */ + if (DiscardBlobBytes(image,length) == MagickFalse) + { + layer_info=DestroyLayerInfo(layer_info,number_layers); + ThrowBinaryException(CorruptImageError, + ""UnexpectedEndOfFile"",image->filename); + } + } + length=(MagickSizeType) size-combined_length; + if (length > 0) + { + unsigned char + *info; + + layer_info[i].info=AcquireStringInfo((const size_t) length); + info=GetStringInfoDatum(layer_info[i].info); + (void) ReadBlob(image,(const size_t) length,info); + } + } + } + + for (i=0; i < number_layers; i++) + { + if ((layer_info[i].page.width == 0) || + (layer_info[i].page.height == 0)) + { + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" layer data is empty""); + if (layer_info[i].info != (StringInfo *) NULL) + layer_info[i].info=DestroyStringInfo(layer_info[i].info); + continue; + } + + /* + Allocate layered image. + */ + layer_info[i].image=CloneImage(image,layer_info[i].page.width, + layer_info[i].page.height,MagickFalse,exception); + if (layer_info[i].image == (Image *) NULL) + { + layer_info=DestroyLayerInfo(layer_info,number_layers); + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" allocation of image for layer %.20g failed"",(double) i); + ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", + image->filename); + } + + if (layer_info[i].info != (StringInfo *) NULL) + { + (void) SetImageProfile(layer_info[i].image,""psd:additional-info"", + layer_info[i].info,exception); + layer_info[i].info=DestroyStringInfo(layer_info[i].info); + } + } + + if (image_info->ping == MagickFalse) + { + for (i=0; i < number_layers; i++) + { + if (layer_info[i].image == (Image *) NULL) + { + for (j=0; j < layer_info[i].channels; j++) + { + if (DiscardBlobBytes(image,(MagickSizeType) + layer_info[i].channel_info[j].size) == MagickFalse) + { + layer_info=DestroyLayerInfo(layer_info,number_layers); + ThrowBinaryException(CorruptImageError, + ""UnexpectedEndOfFile"",image->filename); + } + } + continue; + } + + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" reading data for layer %.20g"",(double) i); + + status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i], + exception); + if (status == MagickFalse) + break; + + status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType) + number_layers); + if (status == MagickFalse) + break; + } + } + + if (status != MagickFalse) + { + for (i=0; i < number_layers; i++) + { + if (layer_info[i].image == (Image *) NULL) + { + for (j=i; j < number_layers - 1; j++) + layer_info[j] = layer_info[j+1]; + number_layers--; + i--; + } + } + + if (number_layers > 0) + { + for (i=0; i < number_layers; i++) + { + if (i > 0) + layer_info[i].image->previous=layer_info[i-1].image; + if (i < (number_layers-1)) + layer_info[i].image->next=layer_info[i+1].image; + layer_info[i].image->page=layer_info[i].page; + } + image->next=layer_info[0].image; + layer_info[0].image->previous=image; + } + layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); + } + else + layer_info=DestroyLayerInfo(layer_info,number_layers); + } + + return(status); +} +",1,"ModuleExport MagickBooleanType ReadPSDLayers(Image *image, + const ImageInfo *image_info,const PSDInfo *psd_info, + const MagickBooleanType skip_layers,ExceptionInfo *exception) +{ + char + type[4]; + + LayerInfo + *layer_info; + + MagickSizeType + size; + + MagickBooleanType + status; + + register ssize_t + i; + + ssize_t + count, + j, + number_layers; + + size=GetPSDSize(psd_info,image); + if (size == 0) + { + /* + Skip layers & masks. + */ + (void) ReadBlobLong(image); + count=ReadBlob(image,4,(unsigned char *) type); + ReversePSDString(image,type,4); + status=MagickFalse; + if ((count == 0) || (LocaleNCompare(type,""8BIM"",4) != 0)) + return(MagickTrue); + else + { + count=ReadBlob(image,4,(unsigned char *) type); + ReversePSDString(image,type,4); + if ((count != 0) && (LocaleNCompare(type,""Lr16"",4) == 0)) + size=GetPSDSize(psd_info,image); + else + return(MagickTrue); + } + } + status=MagickTrue; + if (size != 0) + { + layer_info=(LayerInfo *) NULL; + number_layers=(short) ReadBlobShort(image); + + if (number_layers < 0) + { + /* + The first alpha channel in the merged result contains the + transparency data for the merged result. + */ + number_layers=MagickAbsoluteValue(number_layers); + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" negative layer count corrected for""); + image->alpha_trait=BlendPixelTrait; + } + + /* + We only need to know if the image has an alpha channel + */ + if (skip_layers != MagickFalse) + return(MagickTrue); + + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" image contains %.20g layers"",(double) number_layers); + + if (number_layers == 0) + ThrowBinaryException(CorruptImageError,""InvalidNumberOfLayers"", + image->filename); + + layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, + sizeof(*layer_info)); + if (layer_info == (LayerInfo *) NULL) + { + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" allocation of LayerInfo failed""); + ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", + image->filename); + } + (void) ResetMagickMemory(layer_info,0,(size_t) number_layers* + sizeof(*layer_info)); + + for (i=0; i < number_layers; i++) + { + ssize_t + x, + y; + + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" reading layer #%.20g"",(double) i+1); + layer_info[i].page.y=ReadBlobSignedLong(image); + layer_info[i].page.x=ReadBlobSignedLong(image); + y=ReadBlobSignedLong(image); + x=ReadBlobSignedLong(image); + layer_info[i].page.width=(size_t) (x-layer_info[i].page.x); + layer_info[i].page.height=(size_t) (y-layer_info[i].page.y); + layer_info[i].channels=ReadBlobShort(image); + if (layer_info[i].channels > MaxPSDChannels) + { + layer_info=DestroyLayerInfo(layer_info,number_layers); + ThrowBinaryException(CorruptImageError,""MaximumChannelsExceeded"", + image->filename); + } + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g"", + (double) layer_info[i].page.x,(double) layer_info[i].page.y, + (double) layer_info[i].page.height,(double) + layer_info[i].page.width,(double) layer_info[i].channels); + for (j=0; j < (ssize_t) layer_info[i].channels; j++) + { + layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); + layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, + image); + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" channel[%.20g]: type=%.20g, size=%.20g"",(double) j, + (double) layer_info[i].channel_info[j].type, + (double) layer_info[i].channel_info[j].size); + } + count=ReadBlob(image,4,(unsigned char *) type); + ReversePSDString(image,type,4); + if ((count == 0) || (LocaleNCompare(type,""8BIM"",4) != 0)) + { + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" layer type was %.4s instead of 8BIM"", type); + layer_info=DestroyLayerInfo(layer_info,number_layers); + ThrowBinaryException(CorruptImageError,""ImproperImageHeader"", + image->filename); + } + count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); + ReversePSDString(image,layer_info[i].blendkey,4); + layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) + ReadBlobByte(image)); + layer_info[i].clipping=(unsigned char) ReadBlobByte(image); + layer_info[i].flags=(unsigned char) ReadBlobByte(image); + layer_info[i].visible=!(layer_info[i].flags & 0x02); + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s"", + layer_info[i].blendkey,(double) layer_info[i].opacity, + layer_info[i].clipping ? ""true"" : ""false"",layer_info[i].flags, + layer_info[i].visible ? ""true"" : ""false""); + (void) ReadBlobByte(image); /* filler */ + + size=ReadBlobLong(image); + if (size != 0) + { + MagickSizeType + combined_length, + length; + + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" layer contains additional info""); + length=ReadBlobLong(image); + combined_length=length+4; + if (length != 0) + { + /* + Layer mask info. + */ + layer_info[i].mask.page.y=ReadBlobSignedLong(image); + layer_info[i].mask.page.x=ReadBlobSignedLong(image); + layer_info[i].mask.page.height=(size_t) (ReadBlobLong(image)- + layer_info[i].mask.page.y); + layer_info[i].mask.page.width=(size_t) (ReadBlobLong(image)- + layer_info[i].mask.page.x); + layer_info[i].mask.background=(unsigned char) ReadBlobByte( + image); + layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); + if (!(layer_info[i].mask.flags & 0x01)) + { + layer_info[i].mask.page.y=layer_info[i].mask.page.y- + layer_info[i].page.y; + layer_info[i].mask.page.x=layer_info[i].mask.page.x- + layer_info[i].page.x; + } + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g"", + (double) layer_info[i].mask.page.x,(double) + layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width, + (double) layer_info[i].mask.page.height,(double) + ((MagickOffsetType) length)-18); + /* + Skip over the rest of the layer mask information. + */ + if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) + { + layer_info=DestroyLayerInfo(layer_info,number_layers); + ThrowBinaryException(CorruptImageError,""UnexpectedEndOfFile"", + image->filename); + } + } + length=ReadBlobLong(image); + combined_length+=length+4; + if (length != 0) + { + /* + Layer blending ranges info. + */ + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" layer blending ranges: length=%.20g"",(double) + ((MagickOffsetType) length)); + /* + We read it, but don't use it... + */ + for (j=0; j < (ssize_t) length; j+=8) + { + size_t blend_source=ReadBlobLong(image); + size_t blend_dest=ReadBlobLong(image); + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" source(%x), dest(%x)"",(unsigned int) + blend_source,(unsigned int) blend_dest); + } + } + /* + Layer name. + */ + length=(MagickSizeType) (unsigned char) ReadBlobByte(image); + combined_length+=length+1; + if (length > 0) + (void) ReadBlob(image,(size_t) length++,layer_info[i].name); + layer_info[i].name[length]='\0'; + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" layer name: %s"",layer_info[i].name); + if ((length % 4) != 0) + { + length=4-(length % 4); + combined_length+=length; + /* Skip over the padding of the layer name */ + if (DiscardBlobBytes(image,length) == MagickFalse) + { + layer_info=DestroyLayerInfo(layer_info,number_layers); + ThrowBinaryException(CorruptImageError, + ""UnexpectedEndOfFile"",image->filename); + } + } + length=(MagickSizeType) size-combined_length; + if (length > 0) + { + unsigned char + *info; + + layer_info[i].info=AcquireStringInfo((const size_t) length); + info=GetStringInfoDatum(layer_info[i].info); + (void) ReadBlob(image,(const size_t) length,info); + } + } + } + + for (i=0; i < number_layers; i++) + { + if ((layer_info[i].page.width == 0) || + (layer_info[i].page.height == 0)) + { + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" layer data is empty""); + if (layer_info[i].info != (StringInfo *) NULL) + layer_info[i].info=DestroyStringInfo(layer_info[i].info); + continue; + } + + /* + Allocate layered image. + */ + layer_info[i].image=CloneImage(image,layer_info[i].page.width, + layer_info[i].page.height,MagickFalse,exception); + if (layer_info[i].image == (Image *) NULL) + { + layer_info=DestroyLayerInfo(layer_info,number_layers); + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" allocation of image for layer %.20g failed"",(double) i); + ThrowBinaryException(ResourceLimitError,""MemoryAllocationFailed"", + image->filename); + } + + if (layer_info[i].info != (StringInfo *) NULL) + { + (void) SetImageProfile(layer_info[i].image,""psd:additional-info"", + layer_info[i].info,exception); + layer_info[i].info=DestroyStringInfo(layer_info[i].info); + } + } + + if (image_info->ping == MagickFalse) + { + for (i=0; i < number_layers; i++) + { + if (layer_info[i].image == (Image *) NULL) + { + for (j=0; j < layer_info[i].channels; j++) + { + if (DiscardBlobBytes(image,(MagickSizeType) + layer_info[i].channel_info[j].size) == MagickFalse) + { + layer_info=DestroyLayerInfo(layer_info,number_layers); + ThrowBinaryException(CorruptImageError, + ""UnexpectedEndOfFile"",image->filename); + } + } + continue; + } + + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" reading data for layer %.20g"",(double) i); + + status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i], + exception); + if (status == MagickFalse) + break; + + status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType) + number_layers); + if (status == MagickFalse) + break; + } + } + + if (status != MagickFalse) + { + for (i=0; i < number_layers; i++) + { + if (layer_info[i].image == (Image *) NULL) + { + for (j=i; j < number_layers - 1; j++) + layer_info[j] = layer_info[j+1]; + number_layers--; + i--; + } + } + + if (number_layers > 0) + { + for (i=0; i < number_layers; i++) + { + if (i > 0) + layer_info[i].image->previous=layer_info[i-1].image; + if (i < (number_layers-1)) + layer_info[i].image->next=layer_info[i+1].image; + layer_info[i].image->page=layer_info[i].page; + } + image->next=layer_info[0].image; + layer_info[0].image->previous=image; + } + layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); + } + else + layer_info=DestroyLayerInfo(layer_info,number_layers); + } + + return(status); +} +","@@ -1691,7 +1691,7 @@ ModuleExport MagickBooleanType ReadPSDLayers(Image *image, + /* + Layer name. + */ +- length=(MagickSizeType) ReadBlobByte(image); ++ length=(MagickSizeType) (unsigned char) ReadBlobByte(image); + combined_length+=length+1; + if (length > 0) + (void) ReadBlob(image,(size_t) length++,layer_info[i].name);",3251,3582,4096 +18336,"static Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ +#define RMT_EQUAL_RGB 1 +#define RMT_NONE 0 +#define RMT_RAW 2 +#define RT_STANDARD 1 +#define RT_ENCODED 2 +#define RT_FORMAT_RGB 3 + + typedef struct _SUNInfo + { + unsigned int + magic, + width, + height, + depth, + length, + type, + maptype, + maplength; + } SUNInfo; + + Image + *image; + + int + bit; + + MagickBooleanType + status; + + MagickSizeType + number_pixels; + + register Quantum + *q; + + register ssize_t + i, + x; + + register unsigned char + *p; + + size_t + bytes_per_line, + extent, + height, + length; + + ssize_t + count, + y; + + SUNInfo + sun_info; + + unsigned char + *sun_data, + *sun_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,exception); + status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); + if (status == MagickFalse) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + /* + Read SUN raster header. + */ + (void) ResetMagickMemory(&sun_info,0,sizeof(sun_info)); + sun_info.magic=ReadBlobMSBLong(image); + do + { + /* + Verify SUN identifier. + */ + if (sun_info.magic != 0x59a66a95) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + sun_info.width=ReadBlobMSBLong(image); + sun_info.height=ReadBlobMSBLong(image); + sun_info.depth=ReadBlobMSBLong(image); + sun_info.length=ReadBlobMSBLong(image); + sun_info.type=ReadBlobMSBLong(image); + sun_info.maptype=ReadBlobMSBLong(image); + sun_info.maplength=ReadBlobMSBLong(image); + extent=sun_info.height*sun_info.width; + if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) && + (sun_info.type != RT_FORMAT_RGB)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + if ((sun_info.depth == 0) || (sun_info.depth > 32)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) && + (sun_info.maptype != RMT_RAW)) + ThrowReaderException(CoderError,""ColormapTypeNotSupported""); + image->columns=sun_info.width; + image->rows=sun_info.height; + image->depth=sun_info.depth <= 8 ? sun_info.depth : + MAGICKCORE_QUANTUM_DEPTH; + if (sun_info.depth < 24) + { + size_t + one; + + image->colors=sun_info.maplength; + one=1; + if (sun_info.maptype == RMT_NONE) + image->colors=one << sun_info.depth; + if (sun_info.maptype == RMT_EQUAL_RGB) + image->colors=sun_info.maplength/3; + if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + } + switch (sun_info.maptype) + { + case RMT_NONE: + break; + case RMT_EQUAL_RGB: + { + unsigned char + *sun_colormap; + + /* + Read SUN raster colormap. + */ + sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, + sizeof(*sun_colormap)); + if (sun_colormap == (unsigned char *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + count=ReadBlob(image,image->colors,sun_colormap); + if (count != (ssize_t) image->colors) + ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); + for (i=0; i < (ssize_t) image->colors; i++) + image->colormap[i].red=(MagickRealType) ScaleCharToQuantum( + sun_colormap[i]); + count=ReadBlob(image,image->colors,sun_colormap); + if (count != (ssize_t) image->colors) + ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); + for (i=0; i < (ssize_t) image->colors; i++) + image->colormap[i].green=(MagickRealType) ScaleCharToQuantum( + sun_colormap[i]); + count=ReadBlob(image,image->colors,sun_colormap); + if (count != (ssize_t) image->colors) + ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); + for (i=0; i < (ssize_t) image->colors; i++) + image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum( + sun_colormap[i]); + sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); + break; + } + case RMT_RAW: + { + unsigned char + *sun_colormap; + + /* + Read SUN raster colormap. + */ + sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength, + sizeof(*sun_colormap)); + if (sun_colormap == (unsigned char *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + count=ReadBlob(image,sun_info.maplength,sun_colormap); + if (count != (ssize_t) sun_info.maplength) + ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); + sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); + break; + } + default: + ThrowReaderException(CoderError,""ColormapTypeNotSupported""); + } + image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait : + UndefinedPixelTrait; + image->columns=sun_info.width; + image->rows=sun_info.height; + if (image_info->ping != MagickFalse) + { + (void) CloseBlob(image); + return(GetFirstImageInList(image)); + } + status=SetImageExtent(image,image->columns,image->rows,exception); + if (status == MagickFalse) + return(DestroyImageList(image)); + if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) != + sun_info.length || !sun_info.length) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + number_pixels=(MagickSizeType) image->columns*image->rows; + if ((sun_info.type != RT_ENCODED) && + ((number_pixels*sun_info.depth) > (8*sun_info.length))) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + bytes_per_line=sun_info.width*sun_info.depth; + sun_data=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax( + sun_info.length,bytes_per_line*sun_info.width),sizeof(*sun_data)); + if (sun_data == (unsigned char *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + count=(ssize_t) ReadBlob(image,sun_info.length,sun_data); + if (count != (ssize_t) sun_info.length) + ThrowReaderException(CorruptImageError,""UnableToReadImageData""); + height=sun_info.height; + if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) || + ((bytes_per_line/sun_info.depth) != sun_info.width)) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + bytes_per_line+=15; + bytes_per_line<<=1; + if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15)) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + bytes_per_line>>=4; + sun_pixels=(unsigned char *) AcquireQuantumMemory(height, + bytes_per_line*sizeof(*sun_pixels)); + if (sun_pixels == (unsigned char *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + if (sun_info.type == RT_ENCODED) + (void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line* + height); + sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); + /* + Convert SUN raster image to pixel packets. + */ + p=sun_pixels; + if (sun_info.depth == 1) + for (y=0; y < (ssize_t) image->rows; y++) + { + q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); + if (q == (Quantum *) NULL) + break; + for (x=0; x < ((ssize_t) image->columns-7); x+=8) + { + for (bit=7; bit >= 0; bit--) + { + SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01), + q); + q+=GetPixelChannels(image); + } + p++; + } + if ((image->columns % 8) != 0) + { + for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--) + { + SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : + 0x01),q); + q+=GetPixelChannels(image); + } + p++; + } + if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0) + p++; + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + } + else + if (image->storage_class == PseudoClass) + { + if (bytes_per_line == 0) + bytes_per_line=image->columns; + length=image->rows*(image->columns+image->columns % 2); + if (((sun_info.type == RT_ENCODED) && + (length > (bytes_per_line*image->rows))) || + ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) + ThrowReaderException(CorruptImageError,""UnableToReadImageData""); + for (y=0; y < (ssize_t) image->rows; y++) + { + 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); + q+=GetPixelChannels(image); + } + if ((image->columns % 2) != 0) + p++; + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + } + } + else + { + size_t + bytes_per_pixel; + + bytes_per_pixel=3; + if (image->alpha_trait != UndefinedPixelTrait) + bytes_per_pixel++; + if (bytes_per_line == 0) + bytes_per_line=bytes_per_pixel*image->columns; + length=image->rows*(bytes_per_line+bytes_per_line % 2); + if (((sun_info.type == RT_ENCODED) && + (length > (bytes_per_line*image->rows))) || + ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) + ThrowReaderException(CorruptImageError,""UnableToReadImageData""); + for (y=0; y < (ssize_t) image->rows; y++) + { + q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); + if (q == (Quantum *) NULL) + break; + for (x=0; x < (ssize_t) image->columns; x++) + { + if (image->alpha_trait != UndefinedPixelTrait) + SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); + if (sun_info.type == RT_STANDARD) + { + SetPixelBlue(image,ScaleCharToQuantum(*p++),q); + SetPixelGreen(image,ScaleCharToQuantum(*p++),q); + SetPixelRed(image,ScaleCharToQuantum(*p++),q); + } + else + { + SetPixelRed(image,ScaleCharToQuantum(*p++),q); + SetPixelGreen(image,ScaleCharToQuantum(*p++),q); + SetPixelBlue(image,ScaleCharToQuantum(*p++),q); + } + if (image->colors != 0) + { + SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t) + GetPixelRed(image,q)].red),q); + SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t) + GetPixelGreen(image,q)].green),q); + SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t) + GetPixelBlue(image,q)].blue),q); + } + q+=GetPixelChannels(image); + } + if (((bytes_per_pixel*image->columns) % 2) != 0) + p++; + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + } + } + if (image->storage_class == PseudoClass) + (void) SyncImage(image,exception); + sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels); + 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; + sun_info.magic=ReadBlobMSBLong(image); + if (sun_info.magic == 0x59a66a95) + { + /* + 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 (sun_info.magic == 0x59a66a95); + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +",1,"static Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ +#define RMT_EQUAL_RGB 1 +#define RMT_NONE 0 +#define RMT_RAW 2 +#define RT_STANDARD 1 +#define RT_ENCODED 2 +#define RT_FORMAT_RGB 3 + + typedef struct _SUNInfo + { + unsigned int + magic, + width, + height, + depth, + length, + type, + maptype, + maplength; + } SUNInfo; + + Image + *image; + + int + bit; + + MagickBooleanType + status; + + MagickSizeType + number_pixels; + + register Quantum + *q; + + register ssize_t + i, + x; + + register unsigned char + *p; + + size_t + bytes_per_line, + extent, + height, + length; + + ssize_t + count, + y; + + SUNInfo + sun_info; + + unsigned char + *sun_data, + *sun_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,exception); + status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); + if (status == MagickFalse) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + /* + Read SUN raster header. + */ + (void) ResetMagickMemory(&sun_info,0,sizeof(sun_info)); + sun_info.magic=ReadBlobMSBLong(image); + do + { + /* + Verify SUN identifier. + */ + if (sun_info.magic != 0x59a66a95) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + sun_info.width=ReadBlobMSBLong(image); + sun_info.height=ReadBlobMSBLong(image); + sun_info.depth=ReadBlobMSBLong(image); + sun_info.length=ReadBlobMSBLong(image); + sun_info.type=ReadBlobMSBLong(image); + sun_info.maptype=ReadBlobMSBLong(image); + sun_info.maplength=ReadBlobMSBLong(image); + extent=sun_info.height*sun_info.width; + if ((sun_info.height != 0) && (sun_info.width != extent/sun_info.height)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + if ((sun_info.type != RT_STANDARD) && (sun_info.type != RT_ENCODED) && + (sun_info.type != RT_FORMAT_RGB)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + if ((sun_info.maptype == RMT_NONE) && (sun_info.maplength != 0)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + if ((sun_info.depth == 0) || (sun_info.depth > 32)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + if ((sun_info.maptype != RMT_NONE) && (sun_info.maptype != RMT_EQUAL_RGB) && + (sun_info.maptype != RMT_RAW)) + ThrowReaderException(CoderError,""ColormapTypeNotSupported""); + image->columns=sun_info.width; + image->rows=sun_info.height; + image->depth=sun_info.depth <= 8 ? sun_info.depth : + MAGICKCORE_QUANTUM_DEPTH; + if (sun_info.depth < 24) + { + size_t + one; + + image->colors=sun_info.maplength; + one=1; + if (sun_info.maptype == RMT_NONE) + image->colors=one << sun_info.depth; + if (sun_info.maptype == RMT_EQUAL_RGB) + image->colors=sun_info.maplength/3; + if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + } + switch (sun_info.maptype) + { + case RMT_NONE: + break; + case RMT_EQUAL_RGB: + { + unsigned char + *sun_colormap; + + /* + Read SUN raster colormap. + */ + sun_colormap=(unsigned char *) AcquireQuantumMemory(image->colors, + sizeof(*sun_colormap)); + if (sun_colormap == (unsigned char *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + count=ReadBlob(image,image->colors,sun_colormap); + if (count != (ssize_t) image->colors) + ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); + for (i=0; i < (ssize_t) image->colors; i++) + image->colormap[i].red=(MagickRealType) ScaleCharToQuantum( + sun_colormap[i]); + count=ReadBlob(image,image->colors,sun_colormap); + if (count != (ssize_t) image->colors) + ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); + for (i=0; i < (ssize_t) image->colors; i++) + image->colormap[i].green=(MagickRealType) ScaleCharToQuantum( + sun_colormap[i]); + count=ReadBlob(image,image->colors,sun_colormap); + if (count != (ssize_t) image->colors) + ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); + for (i=0; i < (ssize_t) image->colors; i++) + image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum( + sun_colormap[i]); + sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); + break; + } + case RMT_RAW: + { + unsigned char + *sun_colormap; + + /* + Read SUN raster colormap. + */ + sun_colormap=(unsigned char *) AcquireQuantumMemory(sun_info.maplength, + sizeof(*sun_colormap)); + if (sun_colormap == (unsigned char *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + count=ReadBlob(image,sun_info.maplength,sun_colormap); + if (count != (ssize_t) sun_info.maplength) + ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); + sun_colormap=(unsigned char *) RelinquishMagickMemory(sun_colormap); + break; + } + default: + ThrowReaderException(CoderError,""ColormapTypeNotSupported""); + } + image->alpha_trait=sun_info.depth == 32 ? BlendPixelTrait : + UndefinedPixelTrait; + image->columns=sun_info.width; + image->rows=sun_info.height; + if (image_info->ping != MagickFalse) + { + (void) CloseBlob(image); + return(GetFirstImageInList(image)); + } + status=SetImageExtent(image,image->columns,image->rows,exception); + if (status == MagickFalse) + return(DestroyImageList(image)); + if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) != + sun_info.length || !sun_info.length) + ThrowReaderException(ResourceLimitError,""ImproperImageHeader""); + number_pixels=(MagickSizeType) image->columns*image->rows; + if ((sun_info.type != RT_ENCODED) && + ((number_pixels*sun_info.depth) > (8*sun_info.length))) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + bytes_per_line=sun_info.width*sun_info.depth; + sun_data=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax( + sun_info.length,bytes_per_line*sun_info.width),sizeof(*sun_data)); + if (sun_data == (unsigned char *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + count=(ssize_t) ReadBlob(image,sun_info.length,sun_data); + if (count != (ssize_t) sun_info.length) + ThrowReaderException(CorruptImageError,""UnableToReadImageData""); + height=sun_info.height; + if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) || + ((bytes_per_line/sun_info.depth) != sun_info.width)) + ThrowReaderException(ResourceLimitError,""ImproperImageHeader""); + bytes_per_line+=15; + bytes_per_line<<=1; + if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15)) + ThrowReaderException(ResourceLimitError,""ImproperImageHeader""); + bytes_per_line>>=4; + sun_pixels=(unsigned char *) AcquireQuantumMemory(height, + bytes_per_line*sizeof(*sun_pixels)); + if (sun_pixels == (unsigned char *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + if (sun_info.type == RT_ENCODED) + (void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line* + height); + else + { + if (sun_info.length > (height*bytes_per_line)) + ThrowReaderException(ResourceLimitError,""ImproperImageHeader""); + (void) CopyMagickMemory(sun_pixels,sun_data,sun_info.length); + } + sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); + /* + Convert SUN raster image to pixel packets. + */ + p=sun_pixels; + if (sun_info.depth == 1) + for (y=0; y < (ssize_t) image->rows; y++) + { + q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); + if (q == (Quantum *) NULL) + break; + for (x=0; x < ((ssize_t) image->columns-7); x+=8) + { + for (bit=7; bit >= 0; bit--) + { + SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : 0x01), + q); + q+=GetPixelChannels(image); + } + p++; + } + if ((image->columns % 8) != 0) + { + for (bit=7; bit >= (int) (8-(image->columns % 8)); bit--) + { + SetPixelIndex(image,(Quantum) ((*p) & (0x01 << bit) ? 0x00 : + 0x01),q); + q+=GetPixelChannels(image); + } + p++; + } + if ((((image->columns/8)+(image->columns % 8 ? 1 : 0)) % 2) != 0) + p++; + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + } + else + if (image->storage_class == PseudoClass) + { + if (bytes_per_line == 0) + bytes_per_line=image->columns; + length=image->rows*(image->columns+image->columns % 2); + if (((sun_info.type == RT_ENCODED) && + (length > (bytes_per_line*image->rows))) || + ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) + ThrowReaderException(CorruptImageError,""UnableToReadImageData""); + for (y=0; y < (ssize_t) image->rows; y++) + { + 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); + q+=GetPixelChannels(image); + } + if ((image->columns % 2) != 0) + p++; + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + } + } + else + { + size_t + bytes_per_pixel; + + bytes_per_pixel=3; + if (image->alpha_trait != UndefinedPixelTrait) + bytes_per_pixel++; + if (bytes_per_line == 0) + bytes_per_line=bytes_per_pixel*image->columns; + length=image->rows*(bytes_per_line+bytes_per_line % 2); + if (((sun_info.type == RT_ENCODED) && + (length > (bytes_per_line*image->rows))) || + ((sun_info.type != RT_ENCODED) && (length > sun_info.length))) + ThrowReaderException(CorruptImageError,""UnableToReadImageData""); + for (y=0; y < (ssize_t) image->rows; y++) + { + q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); + if (q == (Quantum *) NULL) + break; + for (x=0; x < (ssize_t) image->columns; x++) + { + if (image->alpha_trait != UndefinedPixelTrait) + SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); + if (sun_info.type == RT_STANDARD) + { + SetPixelBlue(image,ScaleCharToQuantum(*p++),q); + SetPixelGreen(image,ScaleCharToQuantum(*p++),q); + SetPixelRed(image,ScaleCharToQuantum(*p++),q); + } + else + { + SetPixelRed(image,ScaleCharToQuantum(*p++),q); + SetPixelGreen(image,ScaleCharToQuantum(*p++),q); + SetPixelBlue(image,ScaleCharToQuantum(*p++),q); + } + if (image->colors != 0) + { + SetPixelRed(image,ClampToQuantum(image->colormap[(ssize_t) + GetPixelRed(image,q)].red),q); + SetPixelGreen(image,ClampToQuantum(image->colormap[(ssize_t) + GetPixelGreen(image,q)].green),q); + SetPixelBlue(image,ClampToQuantum(image->colormap[(ssize_t) + GetPixelBlue(image,q)].blue),q); + } + q+=GetPixelChannels(image); + } + if (((bytes_per_pixel*image->columns) % 2) != 0) + p++; + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + } + } + if (image->storage_class == PseudoClass) + (void) SyncImage(image,exception); + sun_pixels=(unsigned char *) RelinquishMagickMemory(sun_pixels); + 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; + sun_info.magic=ReadBlobMSBLong(image); + if (sun_info.magic == 0x59a66a95) + { + /* + 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 (sun_info.magic == 0x59a66a95); + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +","@@ -408,7 +408,7 @@ static Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception) + return(DestroyImageList(image)); + if ((sun_info.length*sizeof(*sun_data))/sizeof(*sun_data) != + sun_info.length || !sun_info.length) +- ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); ++ ThrowReaderException(ResourceLimitError,""ImproperImageHeader""); + number_pixels=(MagickSizeType) image->columns*image->rows; + if ((sun_info.type != RT_ENCODED) && + ((number_pixels*sun_info.depth) > (8*sun_info.length))) +@@ -424,11 +424,11 @@ static Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception) + height=sun_info.height; + if ((height == 0) || (sun_info.width == 0) || (sun_info.depth == 0) || + ((bytes_per_line/sun_info.depth) != sun_info.width)) +- ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); ++ ThrowReaderException(ResourceLimitError,""ImproperImageHeader""); + bytes_per_line+=15; + bytes_per_line<<=1; + if ((bytes_per_line >> 1) != (sun_info.width*sun_info.depth+15)) +- ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); ++ ThrowReaderException(ResourceLimitError,""ImproperImageHeader""); + bytes_per_line>>=4; + sun_pixels=(unsigned char *) AcquireQuantumMemory(height, + bytes_per_line*sizeof(*sun_pixels)); +@@ -437,6 +437,12 @@ static Image *ReadSUNImage(const ImageInfo *image_info,ExceptionInfo *exception) + if (sun_info.type == RT_ENCODED) + (void) DecodeImage(sun_data,sun_info.length,sun_pixels,bytes_per_line* + height); ++ else ++ { ++ if (sun_info.length > (height*bytes_per_line)) ++ ThrowReaderException(ResourceLimitError,""ImproperImageHeader""); ++ (void) CopyMagickMemory(sun_pixels,sun_data,sun_info.length); ++ } + sun_data=(unsigned char *) RelinquishMagickMemory(sun_data); + /* + Convert SUN raster image to pixel packets.",3542,3873,4096 +8568,"cupsdWriteClient(cupsd_client_t *con) /* I - Client connection */ +{ + int bytes, /* Number of bytes written */ + field_col; /* Current column */ + char *bufptr, /* Pointer into buffer */ + *bufend; /* Pointer to end of buffer */ + ipp_state_t ipp_state; /* IPP state value */ + + + cupsdLogClient(con, CUPSD_LOG_DEBUG, ""con->http=%p"", con->http); + cupsdLogClient(con, CUPSD_LOG_DEBUG, + ""cupsdWriteClient "" + ""error=%d, "" + ""used=%d, "" + ""state=%s, "" + ""data_encoding=HTTP_ENCODING_%s, "" + ""data_remaining="" CUPS_LLFMT "", "" + ""response=%p(%s), "" + ""pipe_pid=%d, "" + ""file=%d"", + httpError(con->http), (int)httpGetReady(con->http), + httpStateString(httpGetState(con->http)), + httpIsChunked(con->http) ? ""CHUNKED"" : ""LENGTH"", + CUPS_LLCAST httpGetLength2(con->http), + con->response, + con->response ? ippStateString(ippGetState(con->request)) : """", + con->pipe_pid, con->file); + + if (httpGetState(con->http) != HTTP_STATE_GET_SEND && + httpGetState(con->http) != HTTP_STATE_POST_SEND) + { + /* + * If we get called in the wrong state, then something went wrong with the + * connection and we need to shut it down... + */ + + cupsdLogClient(con, CUPSD_LOG_DEBUG, ""Closing on unexpected HTTP write state %s."", + httpStateString(httpGetState(con->http))); + cupsdCloseClient(con); + return; + } + + if (con->pipe_pid) + { + /* + * Make sure we select on the CGI output... + */ + + cupsdAddSelect(con->file, (cupsd_selfunc_t)write_pipe, NULL, con); + + cupsdLogClient(con, CUPSD_LOG_DEBUG, ""Waiting for CGI data.""); + + if (!con->file_ready) + { + /* + * Try again later when there is CGI output available... + */ + + cupsdRemoveSelect(httpGetFd(con->http)); + return; + } + + con->file_ready = 0; + } + + bytes = (ssize_t)(sizeof(con->header) - (size_t)con->header_used); + + if (!con->pipe_pid && bytes > (ssize_t)httpGetRemaining(con->http)) + { + /* + * Limit GET bytes to original size of file (STR #3265)... + */ + + bytes = (ssize_t)httpGetRemaining(con->http); + } + + if (con->response && con->response->state != IPP_STATE_DATA) + { + size_t wused = httpGetPending(con->http); /* Previous write buffer use */ + + do + { + /* + * Write a single attribute or the IPP message header... + */ + + ipp_state = ippWrite(con->http, con->response); + + /* + * If the write buffer has been flushed, stop buffering up attributes... + */ + + if (httpGetPending(con->http) <= wused) + break; + } + while (ipp_state != IPP_STATE_DATA && ipp_state != IPP_STATE_ERROR); + + cupsdLogClient(con, CUPSD_LOG_DEBUG, + ""Writing IPP response, ipp_state=%s, old "" + ""wused="" CUPS_LLFMT "", new wused="" CUPS_LLFMT, + ippStateString(ipp_state), + CUPS_LLCAST wused, CUPS_LLCAST httpGetPending(con->http)); + + if (httpGetPending(con->http) > 0) + httpFlushWrite(con->http); + + bytes = ipp_state != IPP_STATE_ERROR && + (con->file >= 0 || ipp_state != IPP_STATE_DATA); + + cupsdLogClient(con, CUPSD_LOG_DEBUG, + ""bytes=%d, http_state=%d, data_remaining="" CUPS_LLFMT, + (int)bytes, httpGetState(con->http), + CUPS_LLCAST httpGetLength2(con->http)); + } + else if ((bytes = read(con->file, con->header + con->header_used, (size_t)bytes)) > 0) + { + con->header_used += bytes; + + if (con->pipe_pid && !con->got_fields) + { + /* + * Inspect the data for Content-Type and other fields. + */ + + for (bufptr = con->header, bufend = con->header + con->header_used, + field_col = 0; + !con->got_fields && bufptr < bufend; + bufptr ++) + { + if (*bufptr == '\n') + { + /* + * Send line to client... + */ + + if (bufptr > con->header && bufptr[-1] == '\r') + bufptr[-1] = '\0'; + *bufptr++ = '\0'; + + cupsdLogClient(con, CUPSD_LOG_DEBUG, ""Script header: %s"", con->header); + + if (!con->sent_header) + { + /* + * Handle redirection and CGI status codes... + */ + + http_field_t field; /* HTTP field */ + char *value = strchr(con->header, ':'); + /* Value of field */ + + if (value) + { + *value++ = '\0'; + while (isspace(*value & 255)) + value ++; + } + + field = httpFieldValue(con->header); + + if (field != HTTP_FIELD_UNKNOWN && value) + { + httpSetField(con->http, field, value); + + if (field == HTTP_FIELD_LOCATION) + { + con->pipe_status = HTTP_STATUS_SEE_OTHER; + con->sent_header = 2; + } + else + con->sent_header = 1; + } + else if (!_cups_strcasecmp(con->header, ""Status"") && value) + { + con->pipe_status = (http_status_t)atoi(value); + con->sent_header = 2; + } + else if (!_cups_strcasecmp(con->header, ""Set-Cookie"") && value) + { + httpSetCookie(con->http, value); + con->sent_header = 1; + } + } + + /* + * Update buffer... + */ + + con->header_used -= bufptr - con->header; + + if (con->header_used > 0) + memmove(con->header, bufptr, (size_t)con->header_used); + + bufptr = con->header - 1; + + /* + * See if the line was empty... + */ + + if (field_col == 0) + { + con->got_fields = 1; + + if (httpGetVersion(con->http) == HTTP_VERSION_1_1 && + !httpGetField(con->http, HTTP_FIELD_CONTENT_LENGTH)[0]) + httpSetLength(con->http, 0); + + cupsdLogClient(con, CUPSD_LOG_DEBUG, ""Sending status %d for CGI."", con->pipe_status); + + if (con->pipe_status == HTTP_STATUS_OK) + { + if (!cupsdSendHeader(con, con->pipe_status, NULL, CUPSD_AUTH_NONE)) + { + cupsdCloseClient(con); + return; + } + } + else + { + if (!cupsdSendError(con, con->pipe_status, CUPSD_AUTH_NONE)) + { + cupsdCloseClient(con); + return; + } + } + } + else + field_col = 0; + } + else if (*bufptr != '\r') + field_col ++; + } + + if (!con->got_fields) + return; + } + + if (con->header_used > 0) + { + if (httpWrite2(con->http, con->header, (size_t)con->header_used) < 0) + { + cupsdLogClient(con, CUPSD_LOG_DEBUG, ""Closing for error %d (%s)"", + httpError(con->http), strerror(httpError(con->http))); + cupsdCloseClient(con); + return; + } + + if (httpIsChunked(con->http)) + httpFlushWrite(con->http); + + con->bytes += con->header_used; + + if (httpGetState(con->http) == HTTP_STATE_WAITING) + bytes = 0; + else + bytes = con->header_used; + + con->header_used = 0; + } + } + + if (bytes <= 0 || + (httpGetState(con->http) != HTTP_STATE_GET_SEND && + httpGetState(con->http) != HTTP_STATE_POST_SEND)) + { + if (!con->sent_header && con->pipe_pid) + cupsdSendError(con, HTTP_STATUS_SERVER_ERROR, CUPSD_AUTH_NONE); + else + { + cupsdLogRequest(con, HTTP_STATUS_OK); + + if (httpIsChunked(con->http) && (!con->pipe_pid || con->sent_header > 0)) + { + cupsdLogClient(con, CUPSD_LOG_DEBUG, ""Sending 0-length chunk.""); + + if (httpWrite2(con->http, """", 0) < 0) + { + cupsdLogClient(con, CUPSD_LOG_DEBUG, ""Closing for error %d (%s)"", + httpError(con->http), strerror(httpError(con->http))); + cupsdCloseClient(con); + return; + } + } + + cupsdLogClient(con, CUPSD_LOG_DEBUG, ""Flushing write buffer.""); + httpFlushWrite(con->http); + cupsdLogClient(con, CUPSD_LOG_DEBUG, ""New state is %s"", httpStateString(httpGetState(con->http))); + } + + cupsdAddSelect(httpGetFd(con->http), (cupsd_selfunc_t)cupsdReadClient, NULL, con); + + cupsdLogClient(con, CUPSD_LOG_DEBUG, ""Waiting for request.""); + + if (con->file >= 0) + { + cupsdRemoveSelect(con->file); + + if (con->pipe_pid) + cupsdEndProcess(con->pipe_pid, 0); + + close(con->file); + con->file = -1; + con->pipe_pid = 0; + } + + if (con->filename) + { + unlink(con->filename); + cupsdClearString(&con->filename); + } + + if (con->request) + { + ippDelete(con->request); + con->request = NULL; + } + + if (con->response) + { + ippDelete(con->response); + con->response = NULL; + } + + cupsdClearString(&con->command); + cupsdClearString(&con->options); + cupsdClearString(&con->query_string); + + if (!httpGetKeepAlive(con->http)) + { + cupsdLogClient(con, CUPSD_LOG_DEBUG, + ""Closing because Keep-Alive is disabled.""); + cupsdCloseClient(con); + return; + } + else + { + cupsArrayRemove(ActiveClients, con); + cupsdSetBusyState(); + } + } +} +",0,"cupsdWriteClient(cupsd_client_t *con) /* I - Client connection */ +{ + int bytes, /* Number of bytes written */ + field_col; /* Current column */ + char *bufptr, /* Pointer into buffer */ + *bufend; /* Pointer to end of buffer */ + ipp_state_t ipp_state; /* IPP state value */ + + + cupsdLogClient(con, CUPSD_LOG_DEBUG, ""con->http=%p"", con->http); + cupsdLogClient(con, CUPSD_LOG_DEBUG, + ""cupsdWriteClient "" + ""error=%d, "" + ""used=%d, "" + ""state=%s, "" + ""data_encoding=HTTP_ENCODING_%s, "" + ""data_remaining="" CUPS_LLFMT "", "" + ""response=%p(%s), "" + ""pipe_pid=%d, "" + ""file=%d"", + httpError(con->http), (int)httpGetReady(con->http), + httpStateString(httpGetState(con->http)), + httpIsChunked(con->http) ? ""CHUNKED"" : ""LENGTH"", + CUPS_LLCAST httpGetLength2(con->http), + con->response, + con->response ? ippStateString(ippGetState(con->request)) : """", + con->pipe_pid, con->file); + + if (httpGetState(con->http) != HTTP_STATE_GET_SEND && + httpGetState(con->http) != HTTP_STATE_POST_SEND) + { + /* + * If we get called in the wrong state, then something went wrong with the + * connection and we need to shut it down... + */ + + cupsdLogClient(con, CUPSD_LOG_DEBUG, ""Closing on unexpected HTTP write state %s."", + httpStateString(httpGetState(con->http))); + cupsdCloseClient(con); + return; + } + + if (con->pipe_pid) + { + /* + * Make sure we select on the CGI output... + */ + + cupsdAddSelect(con->file, (cupsd_selfunc_t)write_pipe, NULL, con); + + cupsdLogClient(con, CUPSD_LOG_DEBUG, ""Waiting for CGI data.""); + + if (!con->file_ready) + { + /* + * Try again later when there is CGI output available... + */ + + cupsdRemoveSelect(httpGetFd(con->http)); + return; + } + + con->file_ready = 0; + } + + bytes = (ssize_t)(sizeof(con->header) - (size_t)con->header_used); + + if (!con->pipe_pid && bytes > (ssize_t)httpGetRemaining(con->http)) + { + /* + * Limit GET bytes to original size of file (STR #3265)... + */ + + bytes = (ssize_t)httpGetRemaining(con->http); + } + + if (con->response && con->response->state != IPP_STATE_DATA) + { + size_t wused = httpGetPending(con->http); /* Previous write buffer use */ + + do + { + /* + * Write a single attribute or the IPP message header... + */ + + ipp_state = ippWrite(con->http, con->response); + + /* + * If the write buffer has been flushed, stop buffering up attributes... + */ + + if (httpGetPending(con->http) <= wused) + break; + } + while (ipp_state != IPP_STATE_DATA && ipp_state != IPP_STATE_ERROR); + + cupsdLogClient(con, CUPSD_LOG_DEBUG, + ""Writing IPP response, ipp_state=%s, old "" + ""wused="" CUPS_LLFMT "", new wused="" CUPS_LLFMT, + ippStateString(ipp_state), + CUPS_LLCAST wused, CUPS_LLCAST httpGetPending(con->http)); + + if (httpGetPending(con->http) > 0) + httpFlushWrite(con->http); + + bytes = ipp_state != IPP_STATE_ERROR && + (con->file >= 0 || ipp_state != IPP_STATE_DATA); + + cupsdLogClient(con, CUPSD_LOG_DEBUG, + ""bytes=%d, http_state=%d, data_remaining="" CUPS_LLFMT, + (int)bytes, httpGetState(con->http), + CUPS_LLCAST httpGetLength2(con->http)); + } + else if ((bytes = read(con->file, con->header + con->header_used, (size_t)bytes)) > 0) + { + con->header_used += bytes; + + if (con->pipe_pid && !con->got_fields) + { + /* + * Inspect the data for Content-Type and other fields. + */ + + for (bufptr = con->header, bufend = con->header + con->header_used, + field_col = 0; + !con->got_fields && bufptr < bufend; + bufptr ++) + { + if (*bufptr == '\n') + { + /* + * Send line to client... + */ + + if (bufptr > con->header && bufptr[-1] == '\r') + bufptr[-1] = '\0'; + *bufptr++ = '\0'; + + cupsdLogClient(con, CUPSD_LOG_DEBUG, ""Script header: %s"", con->header); + + if (!con->sent_header) + { + /* + * Handle redirection and CGI status codes... + */ + + http_field_t field; /* HTTP field */ + char *value = strchr(con->header, ':'); + /* Value of field */ + + if (value) + { + *value++ = '\0'; + while (isspace(*value & 255)) + value ++; + } + + field = httpFieldValue(con->header); + + if (field != HTTP_FIELD_UNKNOWN && value) + { + httpSetField(con->http, field, value); + + if (field == HTTP_FIELD_LOCATION) + { + con->pipe_status = HTTP_STATUS_SEE_OTHER; + con->sent_header = 2; + } + else + con->sent_header = 1; + } + else if (!_cups_strcasecmp(con->header, ""Status"") && value) + { + con->pipe_status = (http_status_t)atoi(value); + con->sent_header = 2; + } + else if (!_cups_strcasecmp(con->header, ""Set-Cookie"") && value) + { + httpSetCookie(con->http, value); + con->sent_header = 1; + } + } + + /* + * Update buffer... + */ + + con->header_used -= bufptr - con->header; + + if (con->header_used > 0) + memmove(con->header, bufptr, (size_t)con->header_used); + + bufptr = con->header - 1; + + /* + * See if the line was empty... + */ + + if (field_col == 0) + { + con->got_fields = 1; + + if (httpGetVersion(con->http) == HTTP_VERSION_1_1 && + !httpGetField(con->http, HTTP_FIELD_CONTENT_LENGTH)[0]) + httpSetLength(con->http, 0); + + cupsdLogClient(con, CUPSD_LOG_DEBUG, ""Sending status %d for CGI."", con->pipe_status); + + if (con->pipe_status == HTTP_STATUS_OK) + { + if (!cupsdSendHeader(con, con->pipe_status, NULL, CUPSD_AUTH_NONE)) + { + cupsdCloseClient(con); + return; + } + } + else + { + if (!cupsdSendError(con, con->pipe_status, CUPSD_AUTH_NONE)) + { + cupsdCloseClient(con); + return; + } + } + } + else + field_col = 0; + } + else if (*bufptr != '\r') + field_col ++; + } + + if (!con->got_fields) + return; + } + + if (con->header_used > 0) + { + if (httpWrite2(con->http, con->header, (size_t)con->header_used) < 0) + { + cupsdLogClient(con, CUPSD_LOG_DEBUG, ""Closing for error %d (%s)"", + httpError(con->http), strerror(httpError(con->http))); + cupsdCloseClient(con); + return; + } + + if (httpIsChunked(con->http)) + httpFlushWrite(con->http); + + con->bytes += con->header_used; + + if (httpGetState(con->http) == HTTP_STATE_WAITING) + bytes = 0; + else + bytes = con->header_used; + + con->header_used = 0; + } + } + + if (bytes <= 0 || + (httpGetState(con->http) != HTTP_STATE_GET_SEND && + httpGetState(con->http) != HTTP_STATE_POST_SEND)) + { + if (!con->sent_header && con->pipe_pid) + cupsdSendError(con, HTTP_STATUS_SERVER_ERROR, CUPSD_AUTH_NONE); + else + { + cupsdLogRequest(con, HTTP_STATUS_OK); + + if (httpIsChunked(con->http) && (!con->pipe_pid || con->sent_header > 0)) + { + cupsdLogClient(con, CUPSD_LOG_DEBUG, ""Sending 0-length chunk.""); + + if (httpWrite2(con->http, """", 0) < 0) + { + cupsdLogClient(con, CUPSD_LOG_DEBUG, ""Closing for error %d (%s)"", + httpError(con->http), strerror(httpError(con->http))); + cupsdCloseClient(con); + return; + } + } + + cupsdLogClient(con, CUPSD_LOG_DEBUG, ""Flushing write buffer.""); + httpFlushWrite(con->http); + cupsdLogClient(con, CUPSD_LOG_DEBUG, ""New state is %s"", httpStateString(httpGetState(con->http))); + } + + cupsdAddSelect(httpGetFd(con->http), (cupsd_selfunc_t)cupsdReadClient, NULL, con); + + cupsdLogClient(con, CUPSD_LOG_DEBUG, ""Waiting for request.""); + + if (con->file >= 0) + { + cupsdRemoveSelect(con->file); + + if (con->pipe_pid) + cupsdEndProcess(con->pipe_pid, 0); + + close(con->file); + con->file = -1; + con->pipe_pid = 0; + } + + if (con->filename) + { + unlink(con->filename); + cupsdClearString(&con->filename); + } + + if (con->request) + { + ippDelete(con->request); + con->request = NULL; + } + + if (con->response) + { + ippDelete(con->response); + con->response = NULL; + } + + cupsdClearString(&con->command); + cupsdClearString(&con->options); + cupsdClearString(&con->query_string); + + if (!httpGetKeepAlive(con->http)) + { + cupsdLogClient(con, CUPSD_LOG_DEBUG, + ""Closing because Keep-Alive is disabled.""); + cupsdCloseClient(con); + return; + } + else + { + cupsArrayRemove(ActiveClients, con); + cupsdSetBusyState(); + } + } +} +","@@ -3890,9 +3890,6 @@ valid_host(cupsd_client_t *con) /* I - Client connection */ + + return (!_cups_strcasecmp(con->clientname, ""localhost"") || + !_cups_strcasecmp(con->clientname, ""localhost."") || +-#ifdef __linux +- !_cups_strcasecmp(con->clientname, ""localhost.localdomain"") || +-#endif /* __linux */ + !strcmp(con->clientname, ""127.0.0.1"") || + !strcmp(con->clientname, ""[::1]"")); + }",2430,2761,4096 +18220,"static int flv_write_packet(AVFormatContext *s, AVPacket *pkt) +{ + AVIOContext *pb = s->pb; + AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar; + FLVContext *flv = s->priv_data; + FLVStreamContext *sc = s->streams[pkt->stream_index]->priv_data; + unsigned ts; + int size = pkt->size; + uint8_t *data = NULL; + int flags = -1, flags_size, ret; + int64_t cur_offset = avio_tell(pb); + + if (par->codec_id == AV_CODEC_ID_VP6F || par->codec_id == AV_CODEC_ID_VP6A || + par->codec_id == AV_CODEC_ID_VP6 || par->codec_id == AV_CODEC_ID_AAC) + flags_size = 2; + else if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) + flags_size = 5; + else + flags_size = 1; + + if (par->codec_id == AV_CODEC_ID_AAC || par->codec_id == AV_CODEC_ID_H264 + || par->codec_id == AV_CODEC_ID_MPEG4) { + int side_size = 0; + uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size); + if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) { + av_free(par->extradata); + par->extradata = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE); + if (!par->extradata) { + par->extradata_size = 0; + return AVERROR(ENOMEM); + } + memcpy(par->extradata, side, side_size); + par->extradata_size = side_size; + flv_write_codec_header(s, par, pkt->dts); + } + } + + if (flv->delay == AV_NOPTS_VALUE) + flv->delay = -pkt->dts; + + if (pkt->dts < -flv->delay) { + av_log(s, AV_LOG_WARNING, + ""Packets are not in the proper order with respect to DTS\n""); + return AVERROR(EINVAL); + } + + ts = pkt->dts; + + if (s->event_flags & AVSTREAM_EVENT_FLAG_METADATA_UPDATED) { + write_metadata(s, ts); + s->event_flags &= ~AVSTREAM_EVENT_FLAG_METADATA_UPDATED; + } + + avio_write_marker(pb, av_rescale(ts, AV_TIME_BASE, 1000), + pkt->flags & AV_PKT_FLAG_KEY && (flv->video_par ? par->codec_type == AVMEDIA_TYPE_VIDEO : 1) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT); + + switch (par->codec_type) { + case AVMEDIA_TYPE_VIDEO: + avio_w8(pb, FLV_TAG_TYPE_VIDEO); + + flags = ff_codec_get_tag(flv_video_codec_ids, par->codec_id); + + flags |= pkt->flags & AV_PKT_FLAG_KEY ? FLV_FRAME_KEY : FLV_FRAME_INTER; + break; + case AVMEDIA_TYPE_AUDIO: + flags = get_audio_flags(s, par); + + av_assert0(size); + + avio_w8(pb, FLV_TAG_TYPE_AUDIO); + break; + case AVMEDIA_TYPE_SUBTITLE: + case AVMEDIA_TYPE_DATA: + avio_w8(pb, FLV_TAG_TYPE_META); + break; + default: + return AVERROR(EINVAL); + } + + if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) { + /* check if extradata looks like mp4 formatted */ + if (par->extradata_size > 0 && *(uint8_t*)par->extradata != 1) + if ((ret = ff_avc_parse_nal_units_buf(pkt->data, &data, &size)) < 0) + return ret; + } else if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 && + (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) { + if (!s->streams[pkt->stream_index]->nb_frames) { + av_log(s, AV_LOG_ERROR, ""Malformed AAC bitstream detected: "" + ""use the audio bitstream filter 'aac_adtstoasc' to fix it "" + ""('-bsf:a aac_adtstoasc' option with ffmpeg)\n""); + return AVERROR_INVALIDDATA; + } + av_log(s, AV_LOG_WARNING, ""aac bitstream error\n""); + } + + /* check Speex packet duration */ + if (par->codec_id == AV_CODEC_ID_SPEEX && ts - sc->last_ts > 160) + av_log(s, AV_LOG_WARNING, ""Warning: Speex stream has more than "" + ""8 frames per packet. Adobe Flash "" + ""Player cannot handle this!\n""); + + if (sc->last_ts < ts) + sc->last_ts = ts; + + if (size + flags_size >= 1<<24) { + av_log(s, AV_LOG_ERROR, ""Too large packet with size %u >= %u\n"", + size + flags_size, 1<<24); + return AVERROR(EINVAL); + } + + avio_wb24(pb, size + flags_size); + put_timestamp(pb, ts); + avio_wb24(pb, flv->reserved); + + if (par->codec_type == AVMEDIA_TYPE_DATA || + par->codec_type == AVMEDIA_TYPE_SUBTITLE ) { + int data_size; + int64_t metadata_size_pos = avio_tell(pb); + if (par->codec_id == AV_CODEC_ID_TEXT) { + avio_w8(pb, AMF_DATA_TYPE_STRING); + put_amf_string(pb, ""onTextData""); + avio_w8(pb, AMF_DATA_TYPE_MIXEDARRAY); + avio_wb32(pb, 2); + put_amf_string(pb, ""type""); + avio_w8(pb, AMF_DATA_TYPE_STRING); + put_amf_string(pb, ""Text""); + put_amf_string(pb, ""text""); + avio_w8(pb, AMF_DATA_TYPE_STRING); + put_amf_string(pb, pkt->data); + put_amf_string(pb, """"); + avio_w8(pb, AMF_END_OF_OBJECT); + } else { + avio_write(pb, data ? data : pkt->data, size); + } + /* write total size of tag */ + data_size = avio_tell(pb) - metadata_size_pos; + avio_seek(pb, metadata_size_pos - 10, SEEK_SET); + avio_wb24(pb, data_size); + avio_seek(pb, data_size + 10 - 3, SEEK_CUR); + avio_wb32(pb, data_size + 11); + } else { + av_assert1(flags>=0); + avio_w8(pb,flags); + if (par->codec_id == AV_CODEC_ID_VP6) + avio_w8(pb,0); + if (par->codec_id == AV_CODEC_ID_VP6F || par->codec_id == AV_CODEC_ID_VP6A) { + if (par->extradata_size) + avio_w8(pb, par->extradata[0]); + else + avio_w8(pb, ((FFALIGN(par->width, 16) - par->width) << 4) | + (FFALIGN(par->height, 16) - par->height)); + } else if (par->codec_id == AV_CODEC_ID_AAC) + avio_w8(pb, 1); // AAC raw + else if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) { + avio_w8(pb, 1); // AVC NALU + avio_wb24(pb, pkt->pts - pkt->dts); + } + + avio_write(pb, data ? data : pkt->data, size); + + avio_wb32(pb, size + flags_size + 11); // previous tag size + flv->duration = FFMAX(flv->duration, + pkt->pts + flv->delay + pkt->duration); + } + + if (flv->flags & FLV_ADD_KEYFRAME_INDEX) { + switch (par->codec_type) { + case AVMEDIA_TYPE_VIDEO: + flv->videosize += (avio_tell(pb) - cur_offset); + flv->lasttimestamp = flv->acurframeindex / flv->framerate; + if (pkt->flags & AV_PKT_FLAG_KEY) { + double ts = flv->acurframeindex / flv->framerate; + int64_t pos = cur_offset; + + flv->lastkeyframetimestamp = flv->acurframeindex / flv->framerate; + flv->lastkeyframelocation = pos; + flv_append_keyframe_info(s, flv, ts, pos); + } + flv->acurframeindex++; + break; + + case AVMEDIA_TYPE_AUDIO: + flv->audiosize += (avio_tell(pb) - cur_offset); + break; + + default: + av_log(s, AV_LOG_WARNING, ""par->codec_type is type = [%d]\n"", par->codec_type); + break; + } + } + + av_free(data); + + return pb->error; +} +",1,"static int flv_write_packet(AVFormatContext *s, AVPacket *pkt) +{ + AVIOContext *pb = s->pb; + AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar; + FLVContext *flv = s->priv_data; + FLVStreamContext *sc = s->streams[pkt->stream_index]->priv_data; + unsigned ts; + int size = pkt->size; + uint8_t *data = NULL; + int flags = -1, flags_size, ret; + int64_t cur_offset = avio_tell(pb); + + if (par->codec_type == AVMEDIA_TYPE_AUDIO && !pkt->size) { + av_log(s, AV_LOG_WARNING, ""Empty audio Packet\n""); + return AVERROR(EINVAL); + } + + if (par->codec_id == AV_CODEC_ID_VP6F || par->codec_id == AV_CODEC_ID_VP6A || + par->codec_id == AV_CODEC_ID_VP6 || par->codec_id == AV_CODEC_ID_AAC) + flags_size = 2; + else if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) + flags_size = 5; + else + flags_size = 1; + + if (par->codec_id == AV_CODEC_ID_AAC || par->codec_id == AV_CODEC_ID_H264 + || par->codec_id == AV_CODEC_ID_MPEG4) { + int side_size = 0; + uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size); + if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) { + av_free(par->extradata); + par->extradata = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE); + if (!par->extradata) { + par->extradata_size = 0; + return AVERROR(ENOMEM); + } + memcpy(par->extradata, side, side_size); + par->extradata_size = side_size; + flv_write_codec_header(s, par, pkt->dts); + } + } + + if (flv->delay == AV_NOPTS_VALUE) + flv->delay = -pkt->dts; + + if (pkt->dts < -flv->delay) { + av_log(s, AV_LOG_WARNING, + ""Packets are not in the proper order with respect to DTS\n""); + return AVERROR(EINVAL); + } + + ts = pkt->dts; + + if (s->event_flags & AVSTREAM_EVENT_FLAG_METADATA_UPDATED) { + write_metadata(s, ts); + s->event_flags &= ~AVSTREAM_EVENT_FLAG_METADATA_UPDATED; + } + + avio_write_marker(pb, av_rescale(ts, AV_TIME_BASE, 1000), + pkt->flags & AV_PKT_FLAG_KEY && (flv->video_par ? par->codec_type == AVMEDIA_TYPE_VIDEO : 1) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT); + + switch (par->codec_type) { + case AVMEDIA_TYPE_VIDEO: + avio_w8(pb, FLV_TAG_TYPE_VIDEO); + + flags = ff_codec_get_tag(flv_video_codec_ids, par->codec_id); + + flags |= pkt->flags & AV_PKT_FLAG_KEY ? FLV_FRAME_KEY : FLV_FRAME_INTER; + break; + case AVMEDIA_TYPE_AUDIO: + flags = get_audio_flags(s, par); + + av_assert0(size); + + avio_w8(pb, FLV_TAG_TYPE_AUDIO); + break; + case AVMEDIA_TYPE_SUBTITLE: + case AVMEDIA_TYPE_DATA: + avio_w8(pb, FLV_TAG_TYPE_META); + break; + default: + return AVERROR(EINVAL); + } + + if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) { + /* check if extradata looks like mp4 formatted */ + if (par->extradata_size > 0 && *(uint8_t*)par->extradata != 1) + if ((ret = ff_avc_parse_nal_units_buf(pkt->data, &data, &size)) < 0) + return ret; + } else if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 && + (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) { + if (!s->streams[pkt->stream_index]->nb_frames) { + av_log(s, AV_LOG_ERROR, ""Malformed AAC bitstream detected: "" + ""use the audio bitstream filter 'aac_adtstoasc' to fix it "" + ""('-bsf:a aac_adtstoasc' option with ffmpeg)\n""); + return AVERROR_INVALIDDATA; + } + av_log(s, AV_LOG_WARNING, ""aac bitstream error\n""); + } + + /* check Speex packet duration */ + if (par->codec_id == AV_CODEC_ID_SPEEX && ts - sc->last_ts > 160) + av_log(s, AV_LOG_WARNING, ""Warning: Speex stream has more than "" + ""8 frames per packet. Adobe Flash "" + ""Player cannot handle this!\n""); + + if (sc->last_ts < ts) + sc->last_ts = ts; + + if (size + flags_size >= 1<<24) { + av_log(s, AV_LOG_ERROR, ""Too large packet with size %u >= %u\n"", + size + flags_size, 1<<24); + return AVERROR(EINVAL); + } + + avio_wb24(pb, size + flags_size); + put_timestamp(pb, ts); + avio_wb24(pb, flv->reserved); + + if (par->codec_type == AVMEDIA_TYPE_DATA || + par->codec_type == AVMEDIA_TYPE_SUBTITLE ) { + int data_size; + int64_t metadata_size_pos = avio_tell(pb); + if (par->codec_id == AV_CODEC_ID_TEXT) { + avio_w8(pb, AMF_DATA_TYPE_STRING); + put_amf_string(pb, ""onTextData""); + avio_w8(pb, AMF_DATA_TYPE_MIXEDARRAY); + avio_wb32(pb, 2); + put_amf_string(pb, ""type""); + avio_w8(pb, AMF_DATA_TYPE_STRING); + put_amf_string(pb, ""Text""); + put_amf_string(pb, ""text""); + avio_w8(pb, AMF_DATA_TYPE_STRING); + put_amf_string(pb, pkt->data); + put_amf_string(pb, """"); + avio_w8(pb, AMF_END_OF_OBJECT); + } else { + avio_write(pb, data ? data : pkt->data, size); + } + /* write total size of tag */ + data_size = avio_tell(pb) - metadata_size_pos; + avio_seek(pb, metadata_size_pos - 10, SEEK_SET); + avio_wb24(pb, data_size); + avio_seek(pb, data_size + 10 - 3, SEEK_CUR); + avio_wb32(pb, data_size + 11); + } else { + av_assert1(flags>=0); + avio_w8(pb,flags); + if (par->codec_id == AV_CODEC_ID_VP6) + avio_w8(pb,0); + if (par->codec_id == AV_CODEC_ID_VP6F || par->codec_id == AV_CODEC_ID_VP6A) { + if (par->extradata_size) + avio_w8(pb, par->extradata[0]); + else + avio_w8(pb, ((FFALIGN(par->width, 16) - par->width) << 4) | + (FFALIGN(par->height, 16) - par->height)); + } else if (par->codec_id == AV_CODEC_ID_AAC) + avio_w8(pb, 1); // AAC raw + else if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) { + avio_w8(pb, 1); // AVC NALU + avio_wb24(pb, pkt->pts - pkt->dts); + } + + avio_write(pb, data ? data : pkt->data, size); + + avio_wb32(pb, size + flags_size + 11); // previous tag size + flv->duration = FFMAX(flv->duration, + pkt->pts + flv->delay + pkt->duration); + } + + if (flv->flags & FLV_ADD_KEYFRAME_INDEX) { + switch (par->codec_type) { + case AVMEDIA_TYPE_VIDEO: + flv->videosize += (avio_tell(pb) - cur_offset); + flv->lasttimestamp = flv->acurframeindex / flv->framerate; + if (pkt->flags & AV_PKT_FLAG_KEY) { + double ts = flv->acurframeindex / flv->framerate; + int64_t pos = cur_offset; + + flv->lastkeyframetimestamp = flv->acurframeindex / flv->framerate; + flv->lastkeyframelocation = pos; + flv_append_keyframe_info(s, flv, ts, pos); + } + flv->acurframeindex++; + break; + + case AVMEDIA_TYPE_AUDIO: + flv->audiosize += (avio_tell(pb) - cur_offset); + break; + + default: + av_log(s, AV_LOG_WARNING, ""par->codec_type is type = [%d]\n"", par->codec_type); + break; + } + } + + av_free(data); + + return pb->error; +} +","@@ -883,6 +883,11 @@ static int flv_write_packet(AVFormatContext *s, AVPacket *pkt) + int flags = -1, flags_size, ret; + int64_t cur_offset = avio_tell(pb); + ++ if (par->codec_type == AVMEDIA_TYPE_AUDIO && !pkt->size) { ++ av_log(s, AV_LOG_WARNING, ""Empty audio Packet\n""); ++ return AVERROR(EINVAL); ++ } ++ + if (par->codec_id == AV_CODEC_ID_VP6F || par->codec_id == AV_CODEC_ID_VP6A || + par->codec_id == AV_CODEC_ID_VP6 || par->codec_id == AV_CODEC_ID_AAC) + flags_size = 2;",2098,2429,4096 +8344,"vips__foreign_convert_saveable( VipsImage *in, VipsImage **ready, + VipsSaveable saveable, VipsBandFormat *format, VipsCoding *coding, + VipsArrayDouble *background ) +{ + /* in holds a reference to the output of our chain as we build it. + */ + g_object_ref( in ); + + /* For coded images, can this class save the coding we are in now? + * Nothing to do. + */ + if( in->Coding != VIPS_CODING_NONE && + coding[in->Coding] ) { + *ready = in; + return( 0 ); + } + + /* For uncoded images, if this saver supports ANY bands and this + * format we have nothing to do. + */ + if( in->Coding == VIPS_CODING_NONE && + saveable == VIPS_SAVEABLE_ANY && + format[in->BandFmt] == in->BandFmt ) { + *ready = in; + return( 0 ); + } + + /* Otherwise ... we need to decode and then (possibly) recode at the + * end. + */ + + /* If this is an VIPS_CODING_LABQ, we can go straight to RGB. + */ + if( in->Coding == VIPS_CODING_LABQ ) { + VipsImage *out; + + if( vips_LabQ2sRGB( in, &out, NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + + /* If this is an VIPS_CODING_RAD, we unpack to float. This could be + * scRGB or XYZ. + */ + if( in->Coding == VIPS_CODING_RAD ) { + VipsImage *out; + + if( vips_rad2float( in, &out, NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + + /* If the saver supports RAD, we need to go to scRGB or XYZ. + */ + if( coding[VIPS_CODING_RAD] ) { + if( in->Type != VIPS_INTERPRETATION_scRGB && + in->Type != VIPS_INTERPRETATION_XYZ ) { + VipsImage *out; + + if( vips_colourspace( in, &out, + VIPS_INTERPRETATION_scRGB, NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + } + + /* If this image is CMYK and the saver is RGB-only, use lcms to try to + * import to XYZ. This will only work if the image has an embedded + * profile. + */ + if( in->Type == VIPS_INTERPRETATION_CMYK && + in->Bands >= 4 && + (saveable == VIPS_SAVEABLE_RGB || + saveable == VIPS_SAVEABLE_RGBA || + saveable == VIPS_SAVEABLE_RGBA_ONLY) ) { + VipsImage *out; + + if( vips_icc_import( in, &out, + ""pcs"", VIPS_PCS_XYZ, + NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + + /* We've imported to PCS, we must remove the embedded profile, + * since it no longer matches the image. + * + * For example, when converting CMYK JPG to RGB PNG, we need + * to remove the CMYK profile on import, or the png writer will + * try to attach it when we write the image as RGB. + */ + vips_image_remove( in, VIPS_META_ICC_NAME ); + } + + /* If this is something other than CMYK or RAD, eg. maybe a LAB image, + * we need to transform to RGB. + */ + if( !coding[VIPS_CODING_RAD] && + in->Bands >= 3 && + in->Type != VIPS_INTERPRETATION_CMYK && + vips_colourspace_issupported( in ) && + (saveable == VIPS_SAVEABLE_RGB || + saveable == VIPS_SAVEABLE_RGBA || + saveable == VIPS_SAVEABLE_RGBA_ONLY || + saveable == VIPS_SAVEABLE_RGB_CMYK) ) { + VipsImage *out; + VipsInterpretation interpretation; + + /* Do we make RGB or RGB16? We don't want to squash a 16-bit + * RGB down to 8 bits if the saver supports 16. + */ + if( vips_band_format_is8bit( format[in->BandFmt] ) ) + interpretation = VIPS_INTERPRETATION_sRGB; + else + interpretation = VIPS_INTERPRETATION_RGB16; + + if( vips_colourspace( in, &out, interpretation, NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + + /* VIPS_SAVEABLE_RGBA_ONLY does not support 1 or 2 bands ... convert + * to sRGB. + */ + if( !coding[VIPS_CODING_RAD] && + in->Bands < 3 && + vips_colourspace_issupported( in ) && + saveable == VIPS_SAVEABLE_RGBA_ONLY ) { + VipsImage *out; + VipsInterpretation interpretation; + + /* Do we make RGB or RGB16? We don't want to squash a 16-bit + * RGB down to 8 bits if the saver supports 16. + */ + if( vips_band_format_is8bit( format[in->BandFmt] ) ) + interpretation = VIPS_INTERPRETATION_sRGB; + else + interpretation = VIPS_INTERPRETATION_RGB16; + + if( vips_colourspace( in, &out, interpretation, NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + + /* Get the bands right. We must do this after all colourspace + * transforms, since they can change the number of bands. + */ + if( in->Coding == VIPS_CODING_NONE ) { + /* Do we need to flatten out an alpha channel? There needs to + * be an alpha there now, and this writer needs to not support + * alpha. + */ + if( (in->Bands == 2 || + (in->Bands == 4 && + in->Type != VIPS_INTERPRETATION_CMYK)) && + (saveable == VIPS_SAVEABLE_MONO || + saveable == VIPS_SAVEABLE_RGB || + saveable == VIPS_SAVEABLE_RGB_CMYK) ) { + VipsImage *out; + + if( vips_flatten( in, &out, + ""background"", background, + NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + + /* Other alpha removal strategies ... just drop the extra + * bands. + */ + + else if( in->Bands > 3 && + (saveable == VIPS_SAVEABLE_RGB || + (saveable == VIPS_SAVEABLE_RGB_CMYK && + in->Type != VIPS_INTERPRETATION_CMYK)) ) { + VipsImage *out; + + /* Don't let 4 bands though unless the image really is + * a CMYK. + * + * Consider a RGBA png being saved as JPG. We can + * write CMYK jpg, but we mustn't do that for RGBA + * images. + */ + if( vips_extract_band( in, &out, 0, + ""n"", 3, + NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + else if( in->Bands > 4 && + ((saveable == VIPS_SAVEABLE_RGB_CMYK && + in->Type == VIPS_INTERPRETATION_CMYK) || + saveable == VIPS_SAVEABLE_RGBA || + saveable == VIPS_SAVEABLE_RGBA_ONLY) ) { + VipsImage *out; + + if( vips_extract_band( in, &out, 0, + ""n"", 4, + NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + else if( in->Bands > 1 && + saveable == VIPS_SAVEABLE_MONO ) { + VipsImage *out; + + if( vips_extract_band( in, &out, 0, NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + + /* Else we have VIPS_SAVEABLE_ANY and we don't chop bands down. + */ + } + + /* Handle the ushort interpretations. + * + * RGB16 and GREY16 use 0-65535 for black-white. If we have an image + * tagged like this, and it has more than 8 bits (we leave crazy uchar + * images tagged as RGB16 alone), we'll need to get it ready for the + * saver. + */ + if( (in->Type == VIPS_INTERPRETATION_RGB16 || + in->Type == VIPS_INTERPRETATION_GREY16) && + !vips_band_format_is8bit( in->BandFmt ) ) { + /* If the saver supports ushort, cast to ushort. It may be + * float at the moment, for example. + * + * If the saver does not support ushort, automatically shift + * it down. This is the behaviour we want for saving an RGB16 + * image as JPG, for example. + */ + if( format[VIPS_FORMAT_USHORT] == VIPS_FORMAT_USHORT ) { + VipsImage *out; + + if( vips_cast( in, &out, VIPS_FORMAT_USHORT, NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + else { + VipsImage *out; + + if( vips_rshift_const1( in, &out, 8, NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + + /* That could have produced an int image ... make sure + * we are now uchar. + */ + if( vips_cast( in, &out, VIPS_FORMAT_UCHAR, NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + } + + /* Cast to the output format. + */ + { + VipsImage *out; + + if( vips_cast( in, &out, format[in->BandFmt], NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + + /* Does this class want a coded image? Search the coding table for the + * first one. + */ + if( coding[VIPS_CODING_NONE] ) { + /* Already NONE, nothing to do. + */ + } + else if( coding[VIPS_CODING_LABQ] ) { + VipsImage *out; + + if( vips_Lab2LabQ( in, &out, NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + else if( coding[VIPS_CODING_RAD] ) { + VipsImage *out; + + if( vips_float2rad( in, &out, NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + + *ready = in; + + return( 0 ); +} +",0,"vips__foreign_convert_saveable( VipsImage *in, VipsImage **ready, + VipsSaveable saveable, VipsBandFormat *format, VipsCoding *coding, + VipsArrayDouble *background ) +{ + /* in holds a reference to the output of our chain as we build it. + */ + g_object_ref( in ); + + /* For coded images, can this class save the coding we are in now? + * Nothing to do. + */ + if( in->Coding != VIPS_CODING_NONE && + coding[in->Coding] ) { + *ready = in; + return( 0 ); + } + + /* For uncoded images, if this saver supports ANY bands and this + * format we have nothing to do. + */ + if( in->Coding == VIPS_CODING_NONE && + saveable == VIPS_SAVEABLE_ANY && + format[in->BandFmt] == in->BandFmt ) { + *ready = in; + return( 0 ); + } + + /* Otherwise ... we need to decode and then (possibly) recode at the + * end. + */ + + /* If this is an VIPS_CODING_LABQ, we can go straight to RGB. + */ + if( in->Coding == VIPS_CODING_LABQ ) { + VipsImage *out; + + if( vips_LabQ2sRGB( in, &out, NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + + /* If this is an VIPS_CODING_RAD, we unpack to float. This could be + * scRGB or XYZ. + */ + if( in->Coding == VIPS_CODING_RAD ) { + VipsImage *out; + + if( vips_rad2float( in, &out, NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + + /* If the saver supports RAD, we need to go to scRGB or XYZ. + */ + if( coding[VIPS_CODING_RAD] ) { + if( in->Type != VIPS_INTERPRETATION_scRGB && + in->Type != VIPS_INTERPRETATION_XYZ ) { + VipsImage *out; + + if( vips_colourspace( in, &out, + VIPS_INTERPRETATION_scRGB, NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + } + + /* If this image is CMYK and the saver is RGB-only, use lcms to try to + * import to XYZ. This will only work if the image has an embedded + * profile. + */ + if( in->Type == VIPS_INTERPRETATION_CMYK && + in->Bands >= 4 && + (saveable == VIPS_SAVEABLE_RGB || + saveable == VIPS_SAVEABLE_RGBA || + saveable == VIPS_SAVEABLE_RGBA_ONLY) ) { + VipsImage *out; + + if( vips_icc_import( in, &out, + ""pcs"", VIPS_PCS_XYZ, + NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + + /* We've imported to PCS, we must remove the embedded profile, + * since it no longer matches the image. + * + * For example, when converting CMYK JPG to RGB PNG, we need + * to remove the CMYK profile on import, or the png writer will + * try to attach it when we write the image as RGB. + */ + vips_image_remove( in, VIPS_META_ICC_NAME ); + } + + /* If this is something other than CMYK or RAD, eg. maybe a LAB image, + * we need to transform to RGB. + */ + if( !coding[VIPS_CODING_RAD] && + in->Bands >= 3 && + in->Type != VIPS_INTERPRETATION_CMYK && + vips_colourspace_issupported( in ) && + (saveable == VIPS_SAVEABLE_RGB || + saveable == VIPS_SAVEABLE_RGBA || + saveable == VIPS_SAVEABLE_RGBA_ONLY || + saveable == VIPS_SAVEABLE_RGB_CMYK) ) { + VipsImage *out; + VipsInterpretation interpretation; + + /* Do we make RGB or RGB16? We don't want to squash a 16-bit + * RGB down to 8 bits if the saver supports 16. + */ + if( vips_band_format_is8bit( format[in->BandFmt] ) ) + interpretation = VIPS_INTERPRETATION_sRGB; + else + interpretation = VIPS_INTERPRETATION_RGB16; + + if( vips_colourspace( in, &out, interpretation, NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + + /* VIPS_SAVEABLE_RGBA_ONLY does not support 1 or 2 bands ... convert + * to sRGB. + */ + if( !coding[VIPS_CODING_RAD] && + in->Bands < 3 && + vips_colourspace_issupported( in ) && + saveable == VIPS_SAVEABLE_RGBA_ONLY ) { + VipsImage *out; + VipsInterpretation interpretation; + + /* Do we make RGB or RGB16? We don't want to squash a 16-bit + * RGB down to 8 bits if the saver supports 16. + */ + if( vips_band_format_is8bit( format[in->BandFmt] ) ) + interpretation = VIPS_INTERPRETATION_sRGB; + else + interpretation = VIPS_INTERPRETATION_RGB16; + + if( vips_colourspace( in, &out, interpretation, NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + + /* Get the bands right. We must do this after all colourspace + * transforms, since they can change the number of bands. + */ + if( in->Coding == VIPS_CODING_NONE ) { + /* Do we need to flatten out an alpha channel? There needs to + * be an alpha there now, and this writer needs to not support + * alpha. + */ + if( (in->Bands == 2 || + (in->Bands == 4 && + in->Type != VIPS_INTERPRETATION_CMYK)) && + (saveable == VIPS_SAVEABLE_MONO || + saveable == VIPS_SAVEABLE_RGB || + saveable == VIPS_SAVEABLE_RGB_CMYK) ) { + VipsImage *out; + + if( vips_flatten( in, &out, + ""background"", background, + NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + + /* Other alpha removal strategies ... just drop the extra + * bands. + */ + + else if( in->Bands > 3 && + (saveable == VIPS_SAVEABLE_RGB || + (saveable == VIPS_SAVEABLE_RGB_CMYK && + in->Type != VIPS_INTERPRETATION_CMYK)) ) { + VipsImage *out; + + /* Don't let 4 bands though unless the image really is + * a CMYK. + * + * Consider a RGBA png being saved as JPG. We can + * write CMYK jpg, but we mustn't do that for RGBA + * images. + */ + if( vips_extract_band( in, &out, 0, + ""n"", 3, + NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + else if( in->Bands > 4 && + ((saveable == VIPS_SAVEABLE_RGB_CMYK && + in->Type == VIPS_INTERPRETATION_CMYK) || + saveable == VIPS_SAVEABLE_RGBA || + saveable == VIPS_SAVEABLE_RGBA_ONLY) ) { + VipsImage *out; + + if( vips_extract_band( in, &out, 0, + ""n"", 4, + NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + else if( in->Bands > 1 && + saveable == VIPS_SAVEABLE_MONO ) { + VipsImage *out; + + if( vips_extract_band( in, &out, 0, NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + + /* Else we have VIPS_SAVEABLE_ANY and we don't chop bands down. + */ + } + + /* Handle the ushort interpretations. + * + * RGB16 and GREY16 use 0-65535 for black-white. If we have an image + * tagged like this, and it has more than 8 bits (we leave crazy uchar + * images tagged as RGB16 alone), we'll need to get it ready for the + * saver. + */ + if( (in->Type == VIPS_INTERPRETATION_RGB16 || + in->Type == VIPS_INTERPRETATION_GREY16) && + !vips_band_format_is8bit( in->BandFmt ) ) { + /* If the saver supports ushort, cast to ushort. It may be + * float at the moment, for example. + * + * If the saver does not support ushort, automatically shift + * it down. This is the behaviour we want for saving an RGB16 + * image as JPG, for example. + */ + if( format[VIPS_FORMAT_USHORT] == VIPS_FORMAT_USHORT ) { + VipsImage *out; + + if( vips_cast( in, &out, VIPS_FORMAT_USHORT, NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + else { + VipsImage *out; + + if( vips_rshift_const1( in, &out, 8, NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + + /* That could have produced an int image ... make sure + * we are now uchar. + */ + if( vips_cast( in, &out, VIPS_FORMAT_UCHAR, NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + } + + /* Cast to the output format. + */ + { + VipsImage *out; + + if( vips_cast( in, &out, format[in->BandFmt], NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + + /* Does this class want a coded image? Search the coding table for the + * first one. + */ + if( coding[VIPS_CODING_NONE] ) { + /* Already NONE, nothing to do. + */ + } + else if( coding[VIPS_CODING_LABQ] ) { + VipsImage *out; + + if( vips_Lab2LabQ( in, &out, NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + else if( coding[VIPS_CODING_RAD] ) { + VipsImage *out; + + if( vips_float2rad( in, &out, NULL ) ) { + g_object_unref( in ); + return( -1 ); + } + g_object_unref( in ); + + in = out; + } + + *ready = in; + + return( 0 ); +} +","@@ -18,6 +18,8 @@ + * - transform cmyk->rgb if there's an embedded profile + * 16/6/17 + * - add page_height ++ * 5/3/18 ++ * - block _start if one start fails, see #893 + */ + + /* +@@ -796,6 +798,11 @@ vips_foreign_load_start( VipsImage *out, void *a, void *b ) + VipsForeignLoad *load = VIPS_FOREIGN_LOAD( b ); + VipsForeignLoadClass *class = VIPS_FOREIGN_LOAD_GET_CLASS( load ); + ++ /* If this start has failed before in another thread, we can fail now. ++ */ ++ if( load->error ) ++ return( NULL ); ++ + if( !load->real ) { + if( !(load->real = vips_foreign_load_temp( load )) ) + return( NULL ); +@@ -819,19 +826,25 @@ vips_foreign_load_start( VipsImage *out, void *a, void *b ) + g_object_set_qdata( G_OBJECT( load->real ), + vips__foreign_load_operation, load ); + +- if( class->load( load ) || +- vips_image_pio_input( load->real ) ) +- return( NULL ); +- +- /* ->header() read the header into @out, load has read the ++ /* Load the image and check the result. ++ * ++ * ->header() read the header into @out, load has read the + * image into @real. They must match exactly in size, bands, + * format and coding for the copy to work. + * + * Some versions of ImageMagick give different results between + * Ping and Load for some formats, for example. ++ * ++ * If the load fails, we need to stop + */ +- if( !vips_foreign_load_iscompat( load->real, out ) ) ++ if( class->load( load ) || ++ vips_image_pio_input( load->real ) || ++ vips_foreign_load_iscompat( load->real, out ) ) { ++ vips_operation_invalidate( VIPS_OPERATION( load ) ); ++ load->error = TRUE; ++ + return( NULL ); ++ } + + /* We have to tell vips that out depends on real. We've set + * the demand hint below, but not given an input there.",2722,3053,4096 +18247,"kadm5_create_principal_3(void *server_handle, + kadm5_principal_ent_t entry, long mask, + int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, + char *password) +{ + krb5_db_entry *kdb; + osa_princ_ent_rec adb; + kadm5_policy_ent_rec polent; + krb5_boolean have_polent = FALSE; + krb5_timestamp now; + krb5_tl_data *tl_data_tail; + unsigned int ret; + kadm5_server_handle_t handle = server_handle; + krb5_keyblock *act_mkey; + krb5_kvno act_kvno; + int new_n_ks_tuple = 0; + krb5_key_salt_tuple *new_ks_tuple = NULL; + + CHECK_HANDLE(server_handle); + + krb5_clear_error_message(handle->context); + + check_1_6_dummy(entry, mask, n_ks_tuple, ks_tuple, &password); + + /* + * Argument sanity checking, and opening up the DB + */ + if (entry == NULL) + return EINVAL; + if(!(mask & KADM5_PRINCIPAL) || (mask & KADM5_MOD_NAME) || + (mask & KADM5_MOD_TIME) || (mask & KADM5_LAST_PWD_CHANGE) || + (mask & KADM5_MKVNO) || (mask & KADM5_AUX_ATTRIBUTES) || + (mask & KADM5_LAST_SUCCESS) || (mask & KADM5_LAST_FAILED) || + (mask & KADM5_FAIL_AUTH_COUNT)) + return KADM5_BAD_MASK; + if ((mask & KADM5_KEY_DATA) && entry->n_key_data != 0) + return KADM5_BAD_MASK; + if((mask & KADM5_POLICY) && entry->policy == NULL) + return KADM5_BAD_MASK; + if((mask & KADM5_POLICY) && (mask & KADM5_POLICY_CLR)) + return KADM5_BAD_MASK; + if((mask & ~ALL_PRINC_MASK)) + return KADM5_BAD_MASK; + + /* + * Check to see if the principal exists + */ + ret = kdb_get_entry(handle, entry->principal, &kdb, &adb); + + switch(ret) { + case KADM5_UNK_PRINC: + break; + case 0: + kdb_free_entry(handle, kdb, &adb); + return KADM5_DUP; + default: + return ret; + } + + kdb = calloc(1, sizeof(*kdb)); + if (kdb == NULL) + return ENOMEM; + memset(&adb, 0, sizeof(osa_princ_ent_rec)); + + /* + * If a policy was specified, load it. + * If we can not find the one specified return an error + */ + if ((mask & KADM5_POLICY)) { + ret = get_policy(handle, entry->policy, &polent, &have_polent); + if (ret) + goto cleanup; + } + if (password) { + ret = passwd_check(handle, password, have_polent ? &polent : NULL, + entry->principal); + if (ret) + goto cleanup; + } + /* + * Start populating the various DB fields, using the + * ""defaults"" for fields that were not specified by the + * mask. + */ + if ((ret = krb5_timeofday(handle->context, &now))) + goto cleanup; + + kdb->magic = KRB5_KDB_MAGIC_NUMBER; + kdb->len = KRB5_KDB_V1_BASE_LENGTH; /* gag me with a chainsaw */ + + if ((mask & KADM5_ATTRIBUTES)) + kdb->attributes = entry->attributes; + else + kdb->attributes = handle->params.flags; + + if ((mask & KADM5_MAX_LIFE)) + kdb->max_life = entry->max_life; + else + kdb->max_life = handle->params.max_life; + + if (mask & KADM5_MAX_RLIFE) + kdb->max_renewable_life = entry->max_renewable_life; + else + kdb->max_renewable_life = handle->params.max_rlife; + + if ((mask & KADM5_PRINC_EXPIRE_TIME)) + kdb->expiration = entry->princ_expire_time; + else + kdb->expiration = handle->params.expiration; + + kdb->pw_expiration = 0; + if (have_polent) { + if(polent.pw_max_life) + kdb->pw_expiration = ts_incr(now, polent.pw_max_life); + else + kdb->pw_expiration = 0; + } + if ((mask & KADM5_PW_EXPIRATION)) + kdb->pw_expiration = entry->pw_expiration; + + kdb->last_success = 0; + kdb->last_failed = 0; + kdb->fail_auth_count = 0; + + /* this is kind of gross, but in order to free the tl data, I need + to free the entire kdb entry, and that will try to free the + principal. */ + + ret = krb5_copy_principal(handle->context, entry->principal, &kdb->princ); + if (ret) + goto cleanup; + + if ((ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now))) + goto cleanup; + + if (mask & KADM5_TL_DATA) { + /* splice entry->tl_data onto the front of kdb->tl_data */ + for (tl_data_tail = entry->tl_data; tl_data_tail; + tl_data_tail = tl_data_tail->tl_data_next) + { + ret = krb5_dbe_update_tl_data(handle->context, kdb, tl_data_tail); + if( ret ) + goto cleanup; + } + } + + /* + * We need to have setup the TL data, so we have strings, so we can + * check enctype policy, which is why we check/initialize ks_tuple + * this late. + */ + ret = apply_keysalt_policy(handle, entry->policy, n_ks_tuple, ks_tuple, + &new_n_ks_tuple, &new_ks_tuple); + if (ret) + goto cleanup; + + /* initialize the keys */ + + ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey); + if (ret) + goto cleanup; + + if (mask & KADM5_KEY_DATA) { + /* The client requested no keys for this principal. */ + assert(entry->n_key_data == 0); + } else if (password) { + ret = krb5_dbe_cpw(handle->context, act_mkey, new_ks_tuple, + new_n_ks_tuple, password, + (mask & KADM5_KVNO)?entry->kvno:1, + FALSE, kdb); + } else { + /* Null password means create with random key (new in 1.8). */ + ret = krb5_dbe_crk(handle->context, &master_keyblock, + new_ks_tuple, new_n_ks_tuple, FALSE, kdb); + } + if (ret) + goto cleanup; + + /* Record the master key VNO used to encrypt this entry's keys */ + ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno); + if (ret) + goto cleanup; + + ret = k5_kadm5_hook_create(handle->context, handle->hook_handles, + KADM5_HOOK_STAGE_PRECOMMIT, entry, mask, + new_n_ks_tuple, new_ks_tuple, password); + if (ret) + goto cleanup; + + /* populate the admin-server-specific fields. In the OV server, + this used to be in a separate database. Since there's already + marshalling code for the admin fields, to keep things simple, + I'm going to keep it, and make all the admin stuff occupy a + single tl_data record, */ + + adb.admin_history_kvno = INITIAL_HIST_KVNO; + if (mask & KADM5_POLICY) { + adb.aux_attributes = KADM5_POLICY; + + /* this does *not* need to be strdup'ed, because adb is xdr */ + /* encoded in osa_adb_create_princ, and not ever freed */ + + adb.policy = entry->policy; + } + + /* In all cases key and the principal data is set, let the database provider know */ + kdb->mask = mask | KADM5_KEY_DATA | KADM5_PRINCIPAL ; + + /* store the new db entry */ + ret = kdb_put_entry(handle, kdb, &adb); + + (void) k5_kadm5_hook_create(handle->context, handle->hook_handles, + KADM5_HOOK_STAGE_POSTCOMMIT, entry, mask, + new_n_ks_tuple, new_ks_tuple, password); + +cleanup: + free(new_ks_tuple); + krb5_db_free_principal(handle->context, kdb); + if (have_polent) + (void) kadm5_free_policy_ent(handle->lhandle, &polent); + return ret; +} +",1,"kadm5_create_principal_3(void *server_handle, + kadm5_principal_ent_t entry, long mask, + int n_ks_tuple, krb5_key_salt_tuple *ks_tuple, + char *password) +{ + krb5_db_entry *kdb; + osa_princ_ent_rec adb; + kadm5_policy_ent_rec polent; + krb5_boolean have_polent = FALSE; + krb5_timestamp now; + krb5_tl_data *tl_data_tail; + unsigned int ret; + kadm5_server_handle_t handle = server_handle; + krb5_keyblock *act_mkey; + krb5_kvno act_kvno; + int new_n_ks_tuple = 0; + krb5_key_salt_tuple *new_ks_tuple = NULL; + + CHECK_HANDLE(server_handle); + + krb5_clear_error_message(handle->context); + + check_1_6_dummy(entry, mask, n_ks_tuple, ks_tuple, &password); + + /* + * Argument sanity checking, and opening up the DB + */ + if (entry == NULL) + return EINVAL; + if(!(mask & KADM5_PRINCIPAL) || (mask & KADM5_MOD_NAME) || + (mask & KADM5_MOD_TIME) || (mask & KADM5_LAST_PWD_CHANGE) || + (mask & KADM5_MKVNO) || (mask & KADM5_AUX_ATTRIBUTES) || + (mask & KADM5_LAST_SUCCESS) || (mask & KADM5_LAST_FAILED) || + (mask & KADM5_FAIL_AUTH_COUNT)) + return KADM5_BAD_MASK; + if ((mask & KADM5_KEY_DATA) && entry->n_key_data != 0) + return KADM5_BAD_MASK; + if((mask & KADM5_POLICY) && entry->policy == NULL) + return KADM5_BAD_MASK; + if((mask & KADM5_POLICY) && (mask & KADM5_POLICY_CLR)) + return KADM5_BAD_MASK; + if((mask & ~ALL_PRINC_MASK)) + return KADM5_BAD_MASK; + if (mask & KADM5_TL_DATA) { + for (tl_data_tail = entry->tl_data; tl_data_tail != NULL; + tl_data_tail = tl_data_tail->tl_data_next) { + if (tl_data_tail->tl_data_type < 256) + return KADM5_BAD_TL_TYPE; + } + } + + /* + * Check to see if the principal exists + */ + ret = kdb_get_entry(handle, entry->principal, &kdb, &adb); + + switch(ret) { + case KADM5_UNK_PRINC: + break; + case 0: + kdb_free_entry(handle, kdb, &adb); + return KADM5_DUP; + default: + return ret; + } + + kdb = calloc(1, sizeof(*kdb)); + if (kdb == NULL) + return ENOMEM; + memset(&adb, 0, sizeof(osa_princ_ent_rec)); + + /* + * If a policy was specified, load it. + * If we can not find the one specified return an error + */ + if ((mask & KADM5_POLICY)) { + ret = get_policy(handle, entry->policy, &polent, &have_polent); + if (ret) + goto cleanup; + } + if (password) { + ret = passwd_check(handle, password, have_polent ? &polent : NULL, + entry->principal); + if (ret) + goto cleanup; + } + /* + * Start populating the various DB fields, using the + * ""defaults"" for fields that were not specified by the + * mask. + */ + if ((ret = krb5_timeofday(handle->context, &now))) + goto cleanup; + + kdb->magic = KRB5_KDB_MAGIC_NUMBER; + kdb->len = KRB5_KDB_V1_BASE_LENGTH; /* gag me with a chainsaw */ + + if ((mask & KADM5_ATTRIBUTES)) + kdb->attributes = entry->attributes; + else + kdb->attributes = handle->params.flags; + + if ((mask & KADM5_MAX_LIFE)) + kdb->max_life = entry->max_life; + else + kdb->max_life = handle->params.max_life; + + if (mask & KADM5_MAX_RLIFE) + kdb->max_renewable_life = entry->max_renewable_life; + else + kdb->max_renewable_life = handle->params.max_rlife; + + if ((mask & KADM5_PRINC_EXPIRE_TIME)) + kdb->expiration = entry->princ_expire_time; + else + kdb->expiration = handle->params.expiration; + + kdb->pw_expiration = 0; + if (have_polent) { + if(polent.pw_max_life) + kdb->pw_expiration = ts_incr(now, polent.pw_max_life); + else + kdb->pw_expiration = 0; + } + if ((mask & KADM5_PW_EXPIRATION)) + kdb->pw_expiration = entry->pw_expiration; + + kdb->last_success = 0; + kdb->last_failed = 0; + kdb->fail_auth_count = 0; + + /* this is kind of gross, but in order to free the tl data, I need + to free the entire kdb entry, and that will try to free the + principal. */ + + ret = krb5_copy_principal(handle->context, entry->principal, &kdb->princ); + if (ret) + goto cleanup; + + if ((ret = krb5_dbe_update_last_pwd_change(handle->context, kdb, now))) + goto cleanup; + + if (mask & KADM5_TL_DATA) { + /* splice entry->tl_data onto the front of kdb->tl_data */ + for (tl_data_tail = entry->tl_data; tl_data_tail; + tl_data_tail = tl_data_tail->tl_data_next) + { + ret = krb5_dbe_update_tl_data(handle->context, kdb, tl_data_tail); + if( ret ) + goto cleanup; + } + } + + /* + * We need to have setup the TL data, so we have strings, so we can + * check enctype policy, which is why we check/initialize ks_tuple + * this late. + */ + ret = apply_keysalt_policy(handle, entry->policy, n_ks_tuple, ks_tuple, + &new_n_ks_tuple, &new_ks_tuple); + if (ret) + goto cleanup; + + /* initialize the keys */ + + ret = kdb_get_active_mkey(handle, &act_kvno, &act_mkey); + if (ret) + goto cleanup; + + if (mask & KADM5_KEY_DATA) { + /* The client requested no keys for this principal. */ + assert(entry->n_key_data == 0); + } else if (password) { + ret = krb5_dbe_cpw(handle->context, act_mkey, new_ks_tuple, + new_n_ks_tuple, password, + (mask & KADM5_KVNO)?entry->kvno:1, + FALSE, kdb); + } else { + /* Null password means create with random key (new in 1.8). */ + ret = krb5_dbe_crk(handle->context, &master_keyblock, + new_ks_tuple, new_n_ks_tuple, FALSE, kdb); + } + if (ret) + goto cleanup; + + /* Record the master key VNO used to encrypt this entry's keys */ + ret = krb5_dbe_update_mkvno(handle->context, kdb, act_kvno); + if (ret) + goto cleanup; + + ret = k5_kadm5_hook_create(handle->context, handle->hook_handles, + KADM5_HOOK_STAGE_PRECOMMIT, entry, mask, + new_n_ks_tuple, new_ks_tuple, password); + if (ret) + goto cleanup; + + /* populate the admin-server-specific fields. In the OV server, + this used to be in a separate database. Since there's already + marshalling code for the admin fields, to keep things simple, + I'm going to keep it, and make all the admin stuff occupy a + single tl_data record, */ + + adb.admin_history_kvno = INITIAL_HIST_KVNO; + if (mask & KADM5_POLICY) { + adb.aux_attributes = KADM5_POLICY; + + /* this does *not* need to be strdup'ed, because adb is xdr */ + /* encoded in osa_adb_create_princ, and not ever freed */ + + adb.policy = entry->policy; + } + + /* In all cases key and the principal data is set, let the database provider know */ + kdb->mask = mask | KADM5_KEY_DATA | KADM5_PRINCIPAL ; + + /* store the new db entry */ + ret = kdb_put_entry(handle, kdb, &adb); + + (void) k5_kadm5_hook_create(handle->context, handle->hook_handles, + KADM5_HOOK_STAGE_POSTCOMMIT, entry, mask, + new_n_ks_tuple, new_ks_tuple, password); + +cleanup: + free(new_ks_tuple); + krb5_db_free_principal(handle->context, kdb); + if (have_polent) + (void) kadm5_free_policy_ent(handle->lhandle, &polent); + return ret; +} +","@@ -330,6 +330,13 @@ kadm5_create_principal_3(void *server_handle, + return KADM5_BAD_MASK; + if((mask & ~ALL_PRINC_MASK)) + return KADM5_BAD_MASK; ++ if (mask & KADM5_TL_DATA) { ++ for (tl_data_tail = entry->tl_data; tl_data_tail != NULL; ++ tl_data_tail = tl_data_tail->tl_data_next) { ++ if (tl_data_tail->tl_data_type < 256) ++ return KADM5_BAD_TL_TYPE; ++ } ++ } + + /* + * Check to see if the principal exists",1975,2306,4096 +5031,"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; +} +/* }}} */ +",0,"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; +} +/* }}} */ +","@@ -418,7 +418,7 @@ int phar_parse_zipfile(php_stream *fp, char *fname, int fname_len, char *alias, + 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) { ++ if (read != entry.uncompressed_filesize || read <= 8) { + php_stream_close(sigfile); + efree(sig); + PHAR_ZIP_FAIL(""signature cannot be read"");",3742,4073,4096 +9072,"static MagickBooleanType LoadLocaleCache(SplayTreeInfo *cache,const char *xml, + const char *filename,const char *locale,const size_t depth,ExceptionInfo *exception) +{ + char + keyword[MagickLocaleExtent], + message[MagickLocaleExtent], + tag[MagickLocaleExtent], + *token; + + const char + *q; + + FatalErrorHandler + fatal_handler; + + LocaleInfo + *locale_info; + + MagickStatusType + status; + + register char + *p; + + size_t + extent; + + /* + Read the locale configure file. + */ + (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), + ""Loading locale configure file \""%s\"" ..."",filename); + if (xml == (const char *) NULL) + return(MagickFalse); + status=MagickTrue; + locale_info=(LocaleInfo *) NULL; + *tag='\0'; + *message='\0'; + *keyword='\0'; + fatal_handler=SetFatalErrorHandler(LocaleFatalErrorHandler); + token=AcquireString(xml); + extent=strlen(token)+MagickPathExtent; + for (q=(char *) xml; *q != '\0'; ) + { + /* + Interpret XML. + */ + GetNextToken(q,&q,extent,token); + if (*token == '\0') + break; + (void) CopyMagickString(keyword,token,MagickLocaleExtent); + if (LocaleNCompare(keyword,"""",2) != 0) && (*q != '\0')) + { + GetNextToken(q,&q,extent,token); + while (isspace((int) ((unsigned char) *q)) != 0) + q++; + } + continue; + } + if (LocaleNCompare(keyword,""""); + else + if (strncmp(xml,""""); + if (xml != (char *) NULL) + { + ParseProcessingInstructions(root,c,(size_t) (xml-c)); + xml++; + } + } + else + if (*xml == '<') + xml=strchr(xml,'>'); + else + if ((*(xml++) == '%') && (root->standalone == MagickFalse)) + break; + } + predefined_entitites=(char **) RelinquishMagickMemory(predefined_entitites); + return(MagickTrue); +} +",0,"static MagickBooleanType ParseInternalDoctype(XMLTreeRoot *root,char *xml, + size_t length,ExceptionInfo *exception) +{ + char + *c, + **entities, + *n, + **predefined_entitites, + q, + *t, + *v; + + register ssize_t + i; + + ssize_t + j; + + n=(char *) NULL; + predefined_entitites=(char **) AcquireMagickMemory(sizeof(sentinel)); + if (predefined_entitites == (char **) NULL) + ThrowFatalException(ResourceLimitError,""MemoryAllocationFailed""); + (void) CopyMagickMemory(predefined_entitites,sentinel,sizeof(sentinel)); + for (xml[length]='\0'; xml != (char *) NULL; ) + { + while ((*xml != '\0') && (*xml != '<') && (*xml != '%')) + xml++; + if (*xml == '\0') + break; + if (strncmp(xml,""'); + continue; + } + entities=(*c == '%') ? predefined_entitites : root->entities; + for (i=0; entities[i] != (char *) NULL; i++) ; + entities=(char **) ResizeQuantumMemory(entities,(size_t) (i+3), + sizeof(*entities)); + if (entities == (char **) NULL) + ThrowFatalException(ResourceLimitFatalError,""MemoryAllocationFailed""); + if (*c == '%') + predefined_entitites=entities; + else + root->entities=entities; + xml++; + *xml='\0'; + xml=strchr(v,q); + if (xml != (char *) NULL) + { + *xml='\0'; + xml++; + } + entities[i+1]=ParseEntities(v,predefined_entitites,'%'); + entities[i+2]=(char *) NULL; + if (ValidateEntities(n,entities[i+1],entities) != MagickFalse) + entities[i]=n; + else + { + if (entities[i+1] != v) + entities[i+1]=DestroyString(entities[i+1]); + (void) ThrowMagickException(exception,GetMagickModule(), + OptionWarning,""ParseError"",""circular entity declaration &%s"",n); + predefined_entitites=(char **) RelinquishMagickMemory( + predefined_entitites); + return(MagickFalse); + } + } + else + if (strncmp(xml,""""); + if (*xml == '>') + continue; + *xml='\0'; + i=0; + while ((root->attributes[i] != (char **) NULL) && + (n != (char *) NULL) && + (strcmp(n,root->attributes[i][0]) != 0)) + i++; + while ((*(n=xml+strspn(xml+1,XMLWhitespace)+1) != '\0') && + (*n != '>')) + { + xml=n+strcspn(n,XMLWhitespace); + if (*xml != '\0') + *xml='\0'; + else + { + (void) ThrowMagickException(exception,GetMagickModule(), + OptionWarning,""ParseError"",""malformed "")-1; + if (*c == ' ') + continue; + v=(char *) NULL; + } + else + if (((*xml == '""') || (*xml == '\'')) && + ((xml=strchr(v=xml+1,*xml)) != (char *) NULL)) + *xml='\0'; + else + { + (void) ThrowMagickException(exception,GetMagickModule(), + OptionWarning,""ParseError"",""malformed attributes[i] == (char **) NULL) + { + /* + New attribute tag. + */ + if (i == 0) + root->attributes=(char ***) AcquireQuantumMemory(2, + sizeof(*root->attributes)); + else + root->attributes=(char ***) ResizeQuantumMemory( + root->attributes,(size_t) (i+2), + sizeof(*root->attributes)); + if (root->attributes == (char ***) NULL) + ThrowFatalException(ResourceLimitFatalError, + ""MemoryAllocationFailed""); + root->attributes[i]=(char **) AcquireQuantumMemory(2, + sizeof(**root->attributes)); + if (root->attributes[i] == (char **) NULL) + ThrowFatalException(ResourceLimitFatalError, + ""MemoryAllocationFailed""); + root->attributes[i][0]=ConstantString(t); + root->attributes[i][1]=(char *) NULL; + root->attributes[i+1]=(char **) NULL; + } + for (j=1; root->attributes[i][j] != (char *) NULL; j+=3) ; + root->attributes[i]=(char **) ResizeQuantumMemory( + root->attributes[i],(size_t) (j+4),sizeof(**root->attributes)); + if (root->attributes[i] == (char **) NULL) + ThrowFatalException(ResourceLimitFatalError, + ""MemoryAllocationFailed""); + root->attributes[i][j+3]=(char *) NULL; + root->attributes[i][j+2]=ConstantString(c); + root->attributes[i][j+1]=(char *) NULL; + if (v != (char *) NULL) + root->attributes[i][j+1]=ParseEntities(v,root->entities,*c); + root->attributes[i][j]=ConstantString(n); + } + } + else + if (strncmp(xml, """"); + else + if (strncmp(xml,""""); + if (xml != (char *) NULL) + { + ParseProcessingInstructions(root,c,(size_t) (xml-c)); + xml++; + } + } + else + if (*xml == '<') + xml=strchr(xml,'>'); + else + if ((*(xml++) == '%') && (root->standalone == MagickFalse)) + break; + } + predefined_entitites=(char **) RelinquishMagickMemory(predefined_entitites); + return(MagickTrue); +} +","@@ -2140,7 +2140,10 @@ MagickExport XMLTreeInfo *NewXMLTree(const char *xml,ExceptionInfo *exception) + if ((ignore_depth == 0) && (IsSkipTag(tag) == MagickFalse)) + ParseOpenTag(root,tag,attributes); + else +- ignore_depth++; ++ { ++ ignore_depth++; ++ (void) DestroyXMLTreeAttributes(attributes); ++ } + *p=c; + } + else",1865,2196,4096 +6800,"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); + 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; + } + ut64 v2, handler_type, handler_addr; + int t; + if (MC > 0) { + 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; + 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) { + 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; + 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 ( + "" "" + "" -> "" + ""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; + 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 tries_size = r_read_le16 (ff2 + 6); + ut32 insns_size = r_read_le32 (ff2 + 12); + ut64 prolog_size = 2 + 2 + 2 + 2 + 4 + 4; + if (tries_size > 0) { + } + sym->paddr = MC + prolog_size;// + 0x10; + sym->vaddr = MC + prolog_size;// + 0x10; + sym->size = insns_size * 2; + 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); + 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; +} +",0,"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); + 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; + } + ut64 v2, handler_type, handler_addr; + int t; + if (MC > 0) { + 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; + 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) { + 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; + 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 ( + "" "" + "" -> "" + ""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; + 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 tries_size = r_read_le16 (ff2 + 6); + ut32 insns_size = r_read_le32 (ff2 + 12); + ut64 prolog_size = 2 + 2 + 2 + 2 + 4 + 4; + if (tries_size > 0) { + } + sym->paddr = MC + prolog_size;// + 0x10; + sym->vaddr = MC + prolog_size;// + 0x10; + sym->size = insns_size * 2; + 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); + 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; +} +","@@ -377,6 +377,9 @@ static void dex_parse_debug_item(RBinFile *binfile, RBinDexObj *bin, + --parameters_size; + } + ++ if (p4 <= 0) { ++ return; ++ } + ut8 opcode = *(p4++) & 0xff; + while (keep) { + switch (opcode) {",2560,2891,4096 +7320,"MagickExport MagickBooleanType ProfileImage(Image *image,const char *name, + const void *datum,const size_t length, + const MagickBooleanType magick_unused(clone)) +{ +#define ProfileImageTag ""Profile/Image"" +#define ThrowProfileException(severity,tag,context) \ +{ \ + if (source_profile != (cmsHPROFILE) NULL) \ + (void) cmsCloseProfile(source_profile); \ + if (target_profile != (cmsHPROFILE) NULL) \ + (void) cmsCloseProfile(target_profile); \ + ThrowBinaryException(severity,tag,context); \ +} + + MagickBooleanType + status; + + StringInfo + *profile; + + magick_unreferenced(clone); + + assert(image != (Image *) NULL); + assert(image->signature == MagickSignature); + if (image->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); + assert(name != (const char *) NULL); + if ((datum == (const void *) NULL) || (length == 0)) + { + char + *next; + + /* + Delete image profile(s). + */ + ResetImageProfileIterator(image); + for (next=GetNextImageProfile(image); next != (const char *) NULL; ) + { + if (IsOptionMember(next,name) != MagickFalse) + { + (void) DeleteImageProfile(image,next); + ResetImageProfileIterator(image); + } + next=GetNextImageProfile(image); + } + return(MagickTrue); + } + /* + Add a ICC, IPTC, or generic profile to the image. + */ + status=MagickTrue; + profile=AcquireStringInfo((size_t) length); + SetStringInfoDatum(profile,(unsigned char *) datum); + if ((LocaleCompare(name,""icc"") != 0) && (LocaleCompare(name,""icm"") != 0)) + status=SetImageProfile(image,name,profile); + else + { + const StringInfo + *icc_profile; + + icc_profile=GetImageProfile(image,""icc""); + if ((icc_profile != (const StringInfo *) NULL) && + (CompareStringInfo(icc_profile,profile) == 0)) + { + const char + *value; + + value=GetImageProperty(image,""exif:ColorSpace""); + (void) value; + if (LocaleCompare(value,""1"") != 0) + (void) SetsRGBImageProfile(image); + value=GetImageProperty(image,""exif:InteroperabilityIndex""); + if (LocaleCompare(value,""R98."") != 0) + (void) SetsRGBImageProfile(image); + /* Future. + value=GetImageProperty(image,""exif:InteroperabilityIndex""); + if (LocaleCompare(value,""R03."") != 0) + (void) SetAdobeRGB1998ImageProfile(image); + */ + icc_profile=GetImageProfile(image,""icc""); + } + if ((icc_profile != (const StringInfo *) NULL) && + (CompareStringInfo(icc_profile,profile) == 0)) + { + profile=DestroyStringInfo(profile); + return(MagickTrue); + } +#if !defined(MAGICKCORE_LCMS_DELEGATE) + (void) ThrowMagickException(&image->exception,GetMagickModule(), + MissingDelegateWarning,""DelegateLibrarySupportNotBuiltIn"",""`%s' (LCMS)"", + image->filename); +#else + { + cmsHPROFILE + source_profile; + + /* + Transform pixel colors as defined by the color profiles. + */ + cmsSetLogErrorHandler(LCMSExceptionHandler); + source_profile=cmsOpenProfileFromMemTHR((cmsContext) image, + GetStringInfoDatum(profile),(cmsUInt32Number) + GetStringInfoLength(profile)); + if (source_profile == (cmsHPROFILE) NULL) + ThrowBinaryException(ResourceLimitError, + ""ColorspaceColorProfileMismatch"",name); + if ((cmsGetDeviceClass(source_profile) != cmsSigLinkClass) && + (icc_profile == (StringInfo *) NULL)) + status=SetImageProfile(image,name,profile); + else + { + CacheView + *image_view; + + ColorspaceType + source_colorspace, + target_colorspace; + + cmsColorSpaceSignature + signature; + + cmsHPROFILE + target_profile; + + cmsHTRANSFORM + *magick_restrict transform; + + cmsUInt32Number + flags, + source_type, + target_type; + + ExceptionInfo + *exception; + + int + intent; + + MagickBooleanType + status; + + MagickOffsetType + progress; + + size_t + source_channels, + target_channels; + + ssize_t + y; + + unsigned short + **magick_restrict source_pixels, + **magick_restrict target_pixels; + + exception=(&image->exception); + target_profile=(cmsHPROFILE) NULL; + if (icc_profile != (StringInfo *) NULL) + { + target_profile=source_profile; + source_profile=cmsOpenProfileFromMemTHR((cmsContext) image, + GetStringInfoDatum(icc_profile),(cmsUInt32Number) + GetStringInfoLength(icc_profile)); + if (source_profile == (cmsHPROFILE) NULL) + ThrowProfileException(ResourceLimitError, + ""ColorspaceColorProfileMismatch"",name); + } + switch (cmsGetColorSpace(source_profile)) + { + case cmsSigCmykData: + { + source_colorspace=CMYKColorspace; + source_type=(cmsUInt32Number) TYPE_CMYK_16; + source_channels=4; + break; + } + case cmsSigGrayData: + { + source_colorspace=GRAYColorspace; + source_type=(cmsUInt32Number) TYPE_GRAY_16; + source_channels=1; + break; + } + case cmsSigLabData: + { + source_colorspace=LabColorspace; + source_type=(cmsUInt32Number) TYPE_Lab_16; + source_channels=3; + break; + } + case cmsSigLuvData: + { + source_colorspace=YUVColorspace; + source_type=(cmsUInt32Number) TYPE_YUV_16; + source_channels=3; + break; + } + case cmsSigRgbData: + { + source_colorspace=sRGBColorspace; + source_type=(cmsUInt32Number) TYPE_RGB_16; + source_channels=3; + break; + } + case cmsSigXYZData: + { + source_colorspace=XYZColorspace; + source_type=(cmsUInt32Number) TYPE_XYZ_16; + source_channels=3; + break; + } + case cmsSigYCbCrData: + { + source_colorspace=YCbCrColorspace; + source_type=(cmsUInt32Number) TYPE_YCbCr_16; + source_channels=3; + break; + } + default: + { + source_colorspace=UndefinedColorspace; + source_type=(cmsUInt32Number) TYPE_RGB_16; + source_channels=3; + break; + } + } + signature=cmsGetPCS(source_profile); + if (target_profile != (cmsHPROFILE) NULL) + signature=cmsGetColorSpace(target_profile); + switch (signature) + { + case cmsSigCmykData: + { + target_colorspace=CMYKColorspace; + target_type=(cmsUInt32Number) TYPE_CMYK_16; + target_channels=4; + break; + } + case cmsSigLabData: + { + target_colorspace=LabColorspace; + target_type=(cmsUInt32Number) TYPE_Lab_16; + target_channels=3; + break; + } + case cmsSigGrayData: + { + target_colorspace=GRAYColorspace; + target_type=(cmsUInt32Number) TYPE_GRAY_16; + target_channels=1; + break; + } + case cmsSigLuvData: + { + target_colorspace=YUVColorspace; + target_type=(cmsUInt32Number) TYPE_YUV_16; + target_channels=3; + break; + } + case cmsSigRgbData: + { + target_colorspace=sRGBColorspace; + target_type=(cmsUInt32Number) TYPE_RGB_16; + target_channels=3; + break; + } + case cmsSigXYZData: + { + target_colorspace=XYZColorspace; + target_type=(cmsUInt32Number) TYPE_XYZ_16; + target_channels=3; + break; + } + case cmsSigYCbCrData: + { + target_colorspace=YCbCrColorspace; + target_type=(cmsUInt32Number) TYPE_YCbCr_16; + target_channels=3; + break; + } + default: + { + target_colorspace=UndefinedColorspace; + target_type=(cmsUInt32Number) TYPE_RGB_16; + target_channels=3; + break; + } + } + if ((source_colorspace == UndefinedColorspace) || + (target_colorspace == UndefinedColorspace)) + ThrowProfileException(ImageError,""ColorspaceColorProfileMismatch"", + name); + if ((source_colorspace == GRAYColorspace) && + (SetImageGray(image,exception) == MagickFalse)) + ThrowProfileException(ImageError,""ColorspaceColorProfileMismatch"", + name); + if ((source_colorspace == CMYKColorspace) && + (image->colorspace != CMYKColorspace)) + ThrowProfileException(ImageError,""ColorspaceColorProfileMismatch"", + name); + if ((source_colorspace == XYZColorspace) && + (image->colorspace != XYZColorspace)) + ThrowProfileException(ImageError,""ColorspaceColorProfileMismatch"", + name); + if ((source_colorspace == YCbCrColorspace) && + (image->colorspace != YCbCrColorspace)) + ThrowProfileException(ImageError,""ColorspaceColorProfileMismatch"", + name); + if ((source_colorspace != CMYKColorspace) && + (source_colorspace != GRAYColorspace) && + (source_colorspace != LabColorspace) && + (source_colorspace != XYZColorspace) && + (source_colorspace != YCbCrColorspace) && + (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)) + ThrowProfileException(ImageError,""ColorspaceColorProfileMismatch"", + name); + switch (image->rendering_intent) + { + case AbsoluteIntent: intent=INTENT_ABSOLUTE_COLORIMETRIC; break; + case PerceptualIntent: intent=INTENT_PERCEPTUAL; break; + case RelativeIntent: intent=INTENT_RELATIVE_COLORIMETRIC; break; + case SaturationIntent: intent=INTENT_SATURATION; break; + default: intent=INTENT_PERCEPTUAL; break; + } + flags=cmsFLAGS_HIGHRESPRECALC; +#if defined(cmsFLAGS_BLACKPOINTCOMPENSATION) + if (image->black_point_compensation != MagickFalse) + flags|=cmsFLAGS_BLACKPOINTCOMPENSATION; +#endif + transform=AcquireTransformThreadSet(image,source_profile, + source_type,target_profile,target_type,intent,flags); + if (transform == (cmsHTRANSFORM *) NULL) + ThrowProfileException(ImageError,""UnableToCreateColorTransform"", + name); + /* + Transform image as dictated by the source & target image profiles. + */ + source_pixels=AcquirePixelThreadSet(image->columns,source_channels); + target_pixels=AcquirePixelThreadSet(image->columns,target_channels); + if ((source_pixels == (unsigned short **) NULL) || + (target_pixels == (unsigned short **) NULL)) + { + transform=DestroyTransformThreadSet(transform); + ThrowProfileException(ResourceLimitError, + ""MemoryAllocationFailed"",image->filename); + } + if (SetImageStorageClass(image,DirectClass) == MagickFalse) + { + target_pixels=DestroyPixelThreadSet(target_pixels); + source_pixels=DestroyPixelThreadSet(source_pixels); + transform=DestroyTransformThreadSet(transform); + if (source_profile != (cmsHPROFILE) NULL) + (void) cmsCloseProfile(source_profile); + if (target_profile != (cmsHPROFILE) NULL) + (void) cmsCloseProfile(target_profile); + return(MagickFalse); + } + if (target_colorspace == CMYKColorspace) + (void) SetImageColorspace(image,target_colorspace); + status=MagickTrue; + progress=0; + image_view=AcquireAuthenticCacheView(image,exception); +#if defined(MAGICKCORE_OPENMP_SUPPORT) + #pragma omp parallel for schedule(static,4) shared(status) \ + magick_threads(image,image,image->rows,1) +#endif + for (y=0; y < (ssize_t) image->rows; y++) + { + const int + id = GetOpenMPThreadId(); + + MagickBooleanType + sync; + + register IndexPacket + *magick_restrict indexes; + + register ssize_t + x; + + register PixelPacket + *magick_restrict q; + + register unsigned short + *p; + + 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); + p=source_pixels[id]; + for (x=0; x < (ssize_t) image->columns; x++) + { + *p++=ScaleQuantumToShort(GetPixelRed(q)); + if (source_channels > 1) + { + *p++=ScaleQuantumToShort(GetPixelGreen(q)); + *p++=ScaleQuantumToShort(GetPixelBlue(q)); + } + if (source_channels > 3) + *p++=ScaleQuantumToShort(GetPixelIndex(indexes+x)); + q++; + } + cmsDoTransform(transform[id],source_pixels[id],target_pixels[id], + (unsigned int) image->columns); + p=target_pixels[id]; + q-=image->columns; + for (x=0; x < (ssize_t) image->columns; x++) + { + SetPixelRed(q,ScaleShortToQuantum(*p)); + SetPixelGreen(q,GetPixelRed(q)); + SetPixelBlue(q,GetPixelRed(q)); + p++; + if (target_channels > 1) + { + SetPixelGreen(q,ScaleShortToQuantum(*p)); + p++; + SetPixelBlue(q,ScaleShortToQuantum(*p)); + p++; + } + if (target_channels > 3) + { + SetPixelIndex(indexes+x,ScaleShortToQuantum(*p)); + p++; + } + q++; + } + sync=SyncCacheViewAuthenticPixels(image_view,exception); + if (sync == MagickFalse) + status=MagickFalse; + if (image->progress_monitor != (MagickProgressMonitor) NULL) + { + MagickBooleanType + proceed; + +#if defined(MAGICKCORE_OPENMP_SUPPORT) + #pragma omp critical (MagickCore_ProfileImage) +#endif + proceed=SetImageProgress(image,ProfileImageTag,progress++, + image->rows); + if (proceed == MagickFalse) + status=MagickFalse; + } + } + image_view=DestroyCacheView(image_view); + (void) SetImageColorspace(image,target_colorspace); + switch (signature) + { + case cmsSigRgbData: + { + image->type=image->matte == MagickFalse ? TrueColorType : + TrueColorMatteType; + break; + } + case cmsSigCmykData: + { + image->type=image->matte == MagickFalse ? ColorSeparationType : + ColorSeparationMatteType; + break; + } + case cmsSigGrayData: + { + image->type=image->matte == MagickFalse ? GrayscaleType : + GrayscaleMatteType; + break; + } + default: + break; + } + target_pixels=DestroyPixelThreadSet(target_pixels); + source_pixels=DestroyPixelThreadSet(source_pixels); + transform=DestroyTransformThreadSet(transform); + if (cmsGetDeviceClass(source_profile) != cmsSigLinkClass) + status=SetImageProfile(image,name,profile); + if (target_profile != (cmsHPROFILE) NULL) + (void) cmsCloseProfile(target_profile); + } + (void) cmsCloseProfile(source_profile); + } +#endif + } + profile=DestroyStringInfo(profile); + return(status); +} +",0,"MagickExport MagickBooleanType ProfileImage(Image *image,const char *name, + const void *datum,const size_t length, + const MagickBooleanType magick_unused(clone)) +{ +#define ProfileImageTag ""Profile/Image"" +#define ThrowProfileException(severity,tag,context) \ +{ \ + if (source_profile != (cmsHPROFILE) NULL) \ + (void) cmsCloseProfile(source_profile); \ + if (target_profile != (cmsHPROFILE) NULL) \ + (void) cmsCloseProfile(target_profile); \ + ThrowBinaryException(severity,tag,context); \ +} + + MagickBooleanType + status; + + StringInfo + *profile; + + magick_unreferenced(clone); + + assert(image != (Image *) NULL); + assert(image->signature == MagickSignature); + if (image->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); + assert(name != (const char *) NULL); + if ((datum == (const void *) NULL) || (length == 0)) + { + char + *next; + + /* + Delete image profile(s). + */ + ResetImageProfileIterator(image); + for (next=GetNextImageProfile(image); next != (const char *) NULL; ) + { + if (IsOptionMember(next,name) != MagickFalse) + { + (void) DeleteImageProfile(image,next); + ResetImageProfileIterator(image); + } + next=GetNextImageProfile(image); + } + return(MagickTrue); + } + /* + Add a ICC, IPTC, or generic profile to the image. + */ + status=MagickTrue; + profile=AcquireStringInfo((size_t) length); + SetStringInfoDatum(profile,(unsigned char *) datum); + if ((LocaleCompare(name,""icc"") != 0) && (LocaleCompare(name,""icm"") != 0)) + status=SetImageProfile(image,name,profile); + else + { + const StringInfo + *icc_profile; + + icc_profile=GetImageProfile(image,""icc""); + if ((icc_profile != (const StringInfo *) NULL) && + (CompareStringInfo(icc_profile,profile) == 0)) + { + const char + *value; + + value=GetImageProperty(image,""exif:ColorSpace""); + (void) value; + if (LocaleCompare(value,""1"") != 0) + (void) SetsRGBImageProfile(image); + value=GetImageProperty(image,""exif:InteroperabilityIndex""); + if (LocaleCompare(value,""R98."") != 0) + (void) SetsRGBImageProfile(image); + /* Future. + value=GetImageProperty(image,""exif:InteroperabilityIndex""); + if (LocaleCompare(value,""R03."") != 0) + (void) SetAdobeRGB1998ImageProfile(image); + */ + icc_profile=GetImageProfile(image,""icc""); + } + if ((icc_profile != (const StringInfo *) NULL) && + (CompareStringInfo(icc_profile,profile) == 0)) + { + profile=DestroyStringInfo(profile); + return(MagickTrue); + } +#if !defined(MAGICKCORE_LCMS_DELEGATE) + (void) ThrowMagickException(&image->exception,GetMagickModule(), + MissingDelegateWarning,""DelegateLibrarySupportNotBuiltIn"",""`%s' (LCMS)"", + image->filename); +#else + { + cmsHPROFILE + source_profile; + + /* + Transform pixel colors as defined by the color profiles. + */ + cmsSetLogErrorHandler(LCMSExceptionHandler); + source_profile=cmsOpenProfileFromMemTHR((cmsContext) image, + GetStringInfoDatum(profile),(cmsUInt32Number) + GetStringInfoLength(profile)); + if (source_profile == (cmsHPROFILE) NULL) + ThrowBinaryException(ResourceLimitError, + ""ColorspaceColorProfileMismatch"",name); + if ((cmsGetDeviceClass(source_profile) != cmsSigLinkClass) && + (icc_profile == (StringInfo *) NULL)) + status=SetImageProfile(image,name,profile); + else + { + CacheView + *image_view; + + ColorspaceType + source_colorspace, + target_colorspace; + + cmsColorSpaceSignature + signature; + + cmsHPROFILE + target_profile; + + cmsHTRANSFORM + *magick_restrict transform; + + cmsUInt32Number + flags, + source_type, + target_type; + + ExceptionInfo + *exception; + + int + intent; + + MagickBooleanType + status; + + MagickOffsetType + progress; + + size_t + source_channels, + target_channels; + + ssize_t + y; + + unsigned short + **magick_restrict source_pixels, + **magick_restrict target_pixels; + + exception=(&image->exception); + target_profile=(cmsHPROFILE) NULL; + if (icc_profile != (StringInfo *) NULL) + { + target_profile=source_profile; + source_profile=cmsOpenProfileFromMemTHR((cmsContext) image, + GetStringInfoDatum(icc_profile),(cmsUInt32Number) + GetStringInfoLength(icc_profile)); + if (source_profile == (cmsHPROFILE) NULL) + ThrowProfileException(ResourceLimitError, + ""ColorspaceColorProfileMismatch"",name); + } + switch (cmsGetColorSpace(source_profile)) + { + case cmsSigCmykData: + { + source_colorspace=CMYKColorspace; + source_type=(cmsUInt32Number) TYPE_CMYK_16; + source_channels=4; + break; + } + case cmsSigGrayData: + { + source_colorspace=GRAYColorspace; + source_type=(cmsUInt32Number) TYPE_GRAY_16; + source_channels=1; + break; + } + case cmsSigLabData: + { + source_colorspace=LabColorspace; + source_type=(cmsUInt32Number) TYPE_Lab_16; + source_channels=3; + break; + } + case cmsSigLuvData: + { + source_colorspace=YUVColorspace; + source_type=(cmsUInt32Number) TYPE_YUV_16; + source_channels=3; + break; + } + case cmsSigRgbData: + { + source_colorspace=sRGBColorspace; + source_type=(cmsUInt32Number) TYPE_RGB_16; + source_channels=3; + break; + } + case cmsSigXYZData: + { + source_colorspace=XYZColorspace; + source_type=(cmsUInt32Number) TYPE_XYZ_16; + source_channels=3; + break; + } + case cmsSigYCbCrData: + { + source_colorspace=YCbCrColorspace; + source_type=(cmsUInt32Number) TYPE_YCbCr_16; + source_channels=3; + break; + } + default: + { + source_colorspace=UndefinedColorspace; + source_type=(cmsUInt32Number) TYPE_RGB_16; + source_channels=3; + break; + } + } + signature=cmsGetPCS(source_profile); + if (target_profile != (cmsHPROFILE) NULL) + signature=cmsGetColorSpace(target_profile); + switch (signature) + { + case cmsSigCmykData: + { + target_colorspace=CMYKColorspace; + target_type=(cmsUInt32Number) TYPE_CMYK_16; + target_channels=4; + break; + } + case cmsSigLabData: + { + target_colorspace=LabColorspace; + target_type=(cmsUInt32Number) TYPE_Lab_16; + target_channels=3; + break; + } + case cmsSigGrayData: + { + target_colorspace=GRAYColorspace; + target_type=(cmsUInt32Number) TYPE_GRAY_16; + target_channels=1; + break; + } + case cmsSigLuvData: + { + target_colorspace=YUVColorspace; + target_type=(cmsUInt32Number) TYPE_YUV_16; + target_channels=3; + break; + } + case cmsSigRgbData: + { + target_colorspace=sRGBColorspace; + target_type=(cmsUInt32Number) TYPE_RGB_16; + target_channels=3; + break; + } + case cmsSigXYZData: + { + target_colorspace=XYZColorspace; + target_type=(cmsUInt32Number) TYPE_XYZ_16; + target_channels=3; + break; + } + case cmsSigYCbCrData: + { + target_colorspace=YCbCrColorspace; + target_type=(cmsUInt32Number) TYPE_YCbCr_16; + target_channels=3; + break; + } + default: + { + target_colorspace=UndefinedColorspace; + target_type=(cmsUInt32Number) TYPE_RGB_16; + target_channels=3; + break; + } + } + if ((source_colorspace == UndefinedColorspace) || + (target_colorspace == UndefinedColorspace)) + ThrowProfileException(ImageError,""ColorspaceColorProfileMismatch"", + name); + if ((source_colorspace == GRAYColorspace) && + (SetImageGray(image,exception) == MagickFalse)) + ThrowProfileException(ImageError,""ColorspaceColorProfileMismatch"", + name); + if ((source_colorspace == CMYKColorspace) && + (image->colorspace != CMYKColorspace)) + ThrowProfileException(ImageError,""ColorspaceColorProfileMismatch"", + name); + if ((source_colorspace == XYZColorspace) && + (image->colorspace != XYZColorspace)) + ThrowProfileException(ImageError,""ColorspaceColorProfileMismatch"", + name); + if ((source_colorspace == YCbCrColorspace) && + (image->colorspace != YCbCrColorspace)) + ThrowProfileException(ImageError,""ColorspaceColorProfileMismatch"", + name); + if ((source_colorspace != CMYKColorspace) && + (source_colorspace != GRAYColorspace) && + (source_colorspace != LabColorspace) && + (source_colorspace != XYZColorspace) && + (source_colorspace != YCbCrColorspace) && + (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)) + ThrowProfileException(ImageError,""ColorspaceColorProfileMismatch"", + name); + switch (image->rendering_intent) + { + case AbsoluteIntent: intent=INTENT_ABSOLUTE_COLORIMETRIC; break; + case PerceptualIntent: intent=INTENT_PERCEPTUAL; break; + case RelativeIntent: intent=INTENT_RELATIVE_COLORIMETRIC; break; + case SaturationIntent: intent=INTENT_SATURATION; break; + default: intent=INTENT_PERCEPTUAL; break; + } + flags=cmsFLAGS_HIGHRESPRECALC; +#if defined(cmsFLAGS_BLACKPOINTCOMPENSATION) + if (image->black_point_compensation != MagickFalse) + flags|=cmsFLAGS_BLACKPOINTCOMPENSATION; +#endif + transform=AcquireTransformThreadSet(image,source_profile, + source_type,target_profile,target_type,intent,flags); + if (transform == (cmsHTRANSFORM *) NULL) + ThrowProfileException(ImageError,""UnableToCreateColorTransform"", + name); + /* + Transform image as dictated by the source & target image profiles. + */ + source_pixels=AcquirePixelThreadSet(image->columns,source_channels); + target_pixels=AcquirePixelThreadSet(image->columns,target_channels); + if ((source_pixels == (unsigned short **) NULL) || + (target_pixels == (unsigned short **) NULL)) + { + transform=DestroyTransformThreadSet(transform); + ThrowProfileException(ResourceLimitError, + ""MemoryAllocationFailed"",image->filename); + } + if (SetImageStorageClass(image,DirectClass) == MagickFalse) + { + target_pixels=DestroyPixelThreadSet(target_pixels); + source_pixels=DestroyPixelThreadSet(source_pixels); + transform=DestroyTransformThreadSet(transform); + if (source_profile != (cmsHPROFILE) NULL) + (void) cmsCloseProfile(source_profile); + if (target_profile != (cmsHPROFILE) NULL) + (void) cmsCloseProfile(target_profile); + return(MagickFalse); + } + if (target_colorspace == CMYKColorspace) + (void) SetImageColorspace(image,target_colorspace); + status=MagickTrue; + progress=0; + image_view=AcquireAuthenticCacheView(image,exception); +#if defined(MAGICKCORE_OPENMP_SUPPORT) + #pragma omp parallel for schedule(static,4) shared(status) \ + magick_threads(image,image,image->rows,1) +#endif + for (y=0; y < (ssize_t) image->rows; y++) + { + const int + id = GetOpenMPThreadId(); + + MagickBooleanType + sync; + + register IndexPacket + *magick_restrict indexes; + + register ssize_t + x; + + register PixelPacket + *magick_restrict q; + + register unsigned short + *p; + + 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); + p=source_pixels[id]; + for (x=0; x < (ssize_t) image->columns; x++) + { + *p++=ScaleQuantumToShort(GetPixelRed(q)); + if (source_channels > 1) + { + *p++=ScaleQuantumToShort(GetPixelGreen(q)); + *p++=ScaleQuantumToShort(GetPixelBlue(q)); + } + if (source_channels > 3) + *p++=ScaleQuantumToShort(GetPixelIndex(indexes+x)); + q++; + } + cmsDoTransform(transform[id],source_pixels[id],target_pixels[id], + (unsigned int) image->columns); + p=target_pixels[id]; + q-=image->columns; + for (x=0; x < (ssize_t) image->columns; x++) + { + SetPixelRed(q,ScaleShortToQuantum(*p)); + SetPixelGreen(q,GetPixelRed(q)); + SetPixelBlue(q,GetPixelRed(q)); + p++; + if (target_channels > 1) + { + SetPixelGreen(q,ScaleShortToQuantum(*p)); + p++; + SetPixelBlue(q,ScaleShortToQuantum(*p)); + p++; + } + if (target_channels > 3) + { + SetPixelIndex(indexes+x,ScaleShortToQuantum(*p)); + p++; + } + q++; + } + sync=SyncCacheViewAuthenticPixels(image_view,exception); + if (sync == MagickFalse) + status=MagickFalse; + if (image->progress_monitor != (MagickProgressMonitor) NULL) + { + MagickBooleanType + proceed; + +#if defined(MAGICKCORE_OPENMP_SUPPORT) + #pragma omp critical (MagickCore_ProfileImage) +#endif + proceed=SetImageProgress(image,ProfileImageTag,progress++, + image->rows); + if (proceed == MagickFalse) + status=MagickFalse; + } + } + image_view=DestroyCacheView(image_view); + (void) SetImageColorspace(image,target_colorspace); + switch (signature) + { + case cmsSigRgbData: + { + image->type=image->matte == MagickFalse ? TrueColorType : + TrueColorMatteType; + break; + } + case cmsSigCmykData: + { + image->type=image->matte == MagickFalse ? ColorSeparationType : + ColorSeparationMatteType; + break; + } + case cmsSigGrayData: + { + image->type=image->matte == MagickFalse ? GrayscaleType : + GrayscaleMatteType; + break; + } + default: + break; + } + target_pixels=DestroyPixelThreadSet(target_pixels); + source_pixels=DestroyPixelThreadSet(source_pixels); + transform=DestroyTransformThreadSet(transform); + if (cmsGetDeviceClass(source_profile) != cmsSigLinkClass) + status=SetImageProfile(image,name,profile); + if (target_profile != (cmsHPROFILE) NULL) + (void) cmsCloseProfile(target_profile); + } + (void) cmsCloseProfile(source_profile); + } +#endif + } + profile=DestroyStringInfo(profile); + return(status); +} +","@@ -1444,7 +1444,8 @@ static void WriteTo8BimProfile(Image *image,const char *name, + count=(ssize_t) value; + if ((count & 0x01) != 0) + count++; +- if ((p > (datum+length-count)) || (count > (ssize_t) length)) ++ if ((count < 0) || (p > (datum+length-count)) || ++ (count > (ssize_t) length)) + break; + if (id != profile_id) + p+=count;",3571,3902,4096 +3205,"static struct xfrm_state * pfkey_msg2xfrm_state(struct net *net, + const struct sadb_msg *hdr, + void * const *ext_hdrs) +{ + struct xfrm_state *x; + const struct sadb_lifetime *lifetime; + const struct sadb_sa *sa; + const struct sadb_key *key; + const struct sadb_x_sec_ctx *sec_ctx; + uint16_t proto; + int err; + + + sa = ext_hdrs[SADB_EXT_SA - 1]; + if (!sa || + !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], + ext_hdrs[SADB_EXT_ADDRESS_DST-1])) + return ERR_PTR(-EINVAL); + if (hdr->sadb_msg_satype == SADB_SATYPE_ESP && + !ext_hdrs[SADB_EXT_KEY_ENCRYPT-1]) + return ERR_PTR(-EINVAL); + if (hdr->sadb_msg_satype == SADB_SATYPE_AH && + !ext_hdrs[SADB_EXT_KEY_AUTH-1]) + return ERR_PTR(-EINVAL); + if (!!ext_hdrs[SADB_EXT_LIFETIME_HARD-1] != + !!ext_hdrs[SADB_EXT_LIFETIME_SOFT-1]) + return ERR_PTR(-EINVAL); + + proto = pfkey_satype2proto(hdr->sadb_msg_satype); + if (proto == 0) + return ERR_PTR(-EINVAL); + + /* default error is no buffer space */ + err = -ENOBUFS; + + /* RFC2367: + + Only SADB_SASTATE_MATURE SAs may be submitted in an SADB_ADD message. + SADB_SASTATE_LARVAL SAs are created by SADB_GETSPI and it is not + sensible to add a new SA in the DYING or SADB_SASTATE_DEAD state. + Therefore, the sadb_sa_state field of all submitted SAs MUST be + SADB_SASTATE_MATURE and the kernel MUST return an error if this is + not true. + + However, KAME setkey always uses SADB_SASTATE_LARVAL. + Hence, we have to _ignore_ sadb_sa_state, which is also reasonable. + */ + if (sa->sadb_sa_auth > SADB_AALG_MAX || + (hdr->sadb_msg_satype == SADB_X_SATYPE_IPCOMP && + sa->sadb_sa_encrypt > SADB_X_CALG_MAX) || + sa->sadb_sa_encrypt > SADB_EALG_MAX) + return ERR_PTR(-EINVAL); + key = ext_hdrs[SADB_EXT_KEY_AUTH - 1]; + if (key != NULL && + sa->sadb_sa_auth != SADB_X_AALG_NULL && + ((key->sadb_key_bits+7) / 8 == 0 || + (key->sadb_key_bits+7) / 8 > key->sadb_key_len * sizeof(uint64_t))) + return ERR_PTR(-EINVAL); + key = ext_hdrs[SADB_EXT_KEY_ENCRYPT-1]; + if (key != NULL && + sa->sadb_sa_encrypt != SADB_EALG_NULL && + ((key->sadb_key_bits+7) / 8 == 0 || + (key->sadb_key_bits+7) / 8 > key->sadb_key_len * sizeof(uint64_t))) + return ERR_PTR(-EINVAL); + + x = xfrm_state_alloc(net); + if (x == NULL) + return ERR_PTR(-ENOBUFS); + + x->id.proto = proto; + x->id.spi = sa->sadb_sa_spi; + x->props.replay_window = sa->sadb_sa_replay; + if (sa->sadb_sa_flags & SADB_SAFLAGS_NOECN) + x->props.flags |= XFRM_STATE_NOECN; + if (sa->sadb_sa_flags & SADB_SAFLAGS_DECAP_DSCP) + x->props.flags |= XFRM_STATE_DECAP_DSCP; + if (sa->sadb_sa_flags & SADB_SAFLAGS_NOPMTUDISC) + x->props.flags |= XFRM_STATE_NOPMTUDISC; + + lifetime = ext_hdrs[SADB_EXT_LIFETIME_HARD - 1]; + if (lifetime != NULL) { + x->lft.hard_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations); + x->lft.hard_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes); + x->lft.hard_add_expires_seconds = lifetime->sadb_lifetime_addtime; + x->lft.hard_use_expires_seconds = lifetime->sadb_lifetime_usetime; + } + lifetime = ext_hdrs[SADB_EXT_LIFETIME_SOFT - 1]; + if (lifetime != NULL) { + x->lft.soft_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations); + x->lft.soft_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes); + x->lft.soft_add_expires_seconds = lifetime->sadb_lifetime_addtime; + x->lft.soft_use_expires_seconds = lifetime->sadb_lifetime_usetime; + } + + sec_ctx = ext_hdrs[SADB_X_EXT_SEC_CTX - 1]; + if (sec_ctx != NULL) { + struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx); + + if (!uctx) + goto out; + + err = security_xfrm_state_alloc(x, uctx); + kfree(uctx); + + if (err) + goto out; + } + + key = ext_hdrs[SADB_EXT_KEY_AUTH - 1]; + if (sa->sadb_sa_auth) { + int keysize = 0; + struct xfrm_algo_desc *a = xfrm_aalg_get_byid(sa->sadb_sa_auth); + if (!a || !a->pfkey_supported) { + err = -ENOSYS; + goto out; + } + if (key) + keysize = (key->sadb_key_bits + 7) / 8; + x->aalg = kmalloc(sizeof(*x->aalg) + keysize, GFP_KERNEL); + if (!x->aalg) + goto out; + strcpy(x->aalg->alg_name, a->name); + x->aalg->alg_key_len = 0; + if (key) { + x->aalg->alg_key_len = key->sadb_key_bits; + memcpy(x->aalg->alg_key, key+1, keysize); + } + x->aalg->alg_trunc_len = a->uinfo.auth.icv_truncbits; + x->props.aalgo = sa->sadb_sa_auth; + /* x->algo.flags = sa->sadb_sa_flags; */ + } + if (sa->sadb_sa_encrypt) { + if (hdr->sadb_msg_satype == SADB_X_SATYPE_IPCOMP) { + struct xfrm_algo_desc *a = xfrm_calg_get_byid(sa->sadb_sa_encrypt); + if (!a || !a->pfkey_supported) { + err = -ENOSYS; + goto out; + } + x->calg = kmalloc(sizeof(*x->calg), GFP_KERNEL); + if (!x->calg) + goto out; + strcpy(x->calg->alg_name, a->name); + x->props.calgo = sa->sadb_sa_encrypt; + } else { + int keysize = 0; + struct xfrm_algo_desc *a = xfrm_ealg_get_byid(sa->sadb_sa_encrypt); + if (!a || !a->pfkey_supported) { + err = -ENOSYS; + goto out; + } + key = (struct sadb_key*) ext_hdrs[SADB_EXT_KEY_ENCRYPT-1]; + if (key) + keysize = (key->sadb_key_bits + 7) / 8; + x->ealg = kmalloc(sizeof(*x->ealg) + keysize, GFP_KERNEL); + if (!x->ealg) + goto out; + strcpy(x->ealg->alg_name, a->name); + x->ealg->alg_key_len = 0; + if (key) { + x->ealg->alg_key_len = key->sadb_key_bits; + memcpy(x->ealg->alg_key, key+1, keysize); + } + x->props.ealgo = sa->sadb_sa_encrypt; + } + } + /* x->algo.flags = sa->sadb_sa_flags; */ + + x->props.family = pfkey_sadb_addr2xfrm_addr((struct sadb_address *) ext_hdrs[SADB_EXT_ADDRESS_SRC-1], + &x->props.saddr); + if (!x->props.family) { + err = -EAFNOSUPPORT; + goto out; + } + pfkey_sadb_addr2xfrm_addr((struct sadb_address *) ext_hdrs[SADB_EXT_ADDRESS_DST-1], + &x->id.daddr); + + if (ext_hdrs[SADB_X_EXT_SA2-1]) { + const struct sadb_x_sa2 *sa2 = ext_hdrs[SADB_X_EXT_SA2-1]; + int mode = pfkey_mode_to_xfrm(sa2->sadb_x_sa2_mode); + if (mode < 0) { + err = -EINVAL; + goto out; + } + x->props.mode = mode; + x->props.reqid = sa2->sadb_x_sa2_reqid; + } + + if (ext_hdrs[SADB_EXT_ADDRESS_PROXY-1]) { + const struct sadb_address *addr = ext_hdrs[SADB_EXT_ADDRESS_PROXY-1]; + + /* Nobody uses this, but we try. */ + x->sel.family = pfkey_sadb_addr2xfrm_addr(addr, &x->sel.saddr); + x->sel.prefixlen_s = addr->sadb_address_prefixlen; + } + + if (!x->sel.family) + x->sel.family = x->props.family; + + if (ext_hdrs[SADB_X_EXT_NAT_T_TYPE-1]) { + const struct sadb_x_nat_t_type* n_type; + struct xfrm_encap_tmpl *natt; + + x->encap = kmalloc(sizeof(*x->encap), GFP_KERNEL); + if (!x->encap) + goto out; + + natt = x->encap; + n_type = ext_hdrs[SADB_X_EXT_NAT_T_TYPE-1]; + natt->encap_type = n_type->sadb_x_nat_t_type_type; + + if (ext_hdrs[SADB_X_EXT_NAT_T_SPORT-1]) { + const struct sadb_x_nat_t_port *n_port = + ext_hdrs[SADB_X_EXT_NAT_T_SPORT-1]; + natt->encap_sport = n_port->sadb_x_nat_t_port_port; + } + if (ext_hdrs[SADB_X_EXT_NAT_T_DPORT-1]) { + const struct sadb_x_nat_t_port *n_port = + ext_hdrs[SADB_X_EXT_NAT_T_DPORT-1]; + natt->encap_dport = n_port->sadb_x_nat_t_port_port; + } + memset(&natt->encap_oa, 0, sizeof(natt->encap_oa)); + } + + err = xfrm_init_state(x); + if (err) + goto out; + + x->km.seq = hdr->sadb_msg_seq; + return x; + +out: + x->km.state = XFRM_STATE_DEAD; + xfrm_state_put(x); + return ERR_PTR(err); +} +",0,"static struct xfrm_state * pfkey_msg2xfrm_state(struct net *net, + const struct sadb_msg *hdr, + void * const *ext_hdrs) +{ + struct xfrm_state *x; + const struct sadb_lifetime *lifetime; + const struct sadb_sa *sa; + const struct sadb_key *key; + const struct sadb_x_sec_ctx *sec_ctx; + uint16_t proto; + int err; + + + sa = ext_hdrs[SADB_EXT_SA - 1]; + if (!sa || + !present_and_same_family(ext_hdrs[SADB_EXT_ADDRESS_SRC-1], + ext_hdrs[SADB_EXT_ADDRESS_DST-1])) + return ERR_PTR(-EINVAL); + if (hdr->sadb_msg_satype == SADB_SATYPE_ESP && + !ext_hdrs[SADB_EXT_KEY_ENCRYPT-1]) + return ERR_PTR(-EINVAL); + if (hdr->sadb_msg_satype == SADB_SATYPE_AH && + !ext_hdrs[SADB_EXT_KEY_AUTH-1]) + return ERR_PTR(-EINVAL); + if (!!ext_hdrs[SADB_EXT_LIFETIME_HARD-1] != + !!ext_hdrs[SADB_EXT_LIFETIME_SOFT-1]) + return ERR_PTR(-EINVAL); + + proto = pfkey_satype2proto(hdr->sadb_msg_satype); + if (proto == 0) + return ERR_PTR(-EINVAL); + + /* default error is no buffer space */ + err = -ENOBUFS; + + /* RFC2367: + + Only SADB_SASTATE_MATURE SAs may be submitted in an SADB_ADD message. + SADB_SASTATE_LARVAL SAs are created by SADB_GETSPI and it is not + sensible to add a new SA in the DYING or SADB_SASTATE_DEAD state. + Therefore, the sadb_sa_state field of all submitted SAs MUST be + SADB_SASTATE_MATURE and the kernel MUST return an error if this is + not true. + + However, KAME setkey always uses SADB_SASTATE_LARVAL. + Hence, we have to _ignore_ sadb_sa_state, which is also reasonable. + */ + if (sa->sadb_sa_auth > SADB_AALG_MAX || + (hdr->sadb_msg_satype == SADB_X_SATYPE_IPCOMP && + sa->sadb_sa_encrypt > SADB_X_CALG_MAX) || + sa->sadb_sa_encrypt > SADB_EALG_MAX) + return ERR_PTR(-EINVAL); + key = ext_hdrs[SADB_EXT_KEY_AUTH - 1]; + if (key != NULL && + sa->sadb_sa_auth != SADB_X_AALG_NULL && + ((key->sadb_key_bits+7) / 8 == 0 || + (key->sadb_key_bits+7) / 8 > key->sadb_key_len * sizeof(uint64_t))) + return ERR_PTR(-EINVAL); + key = ext_hdrs[SADB_EXT_KEY_ENCRYPT-1]; + if (key != NULL && + sa->sadb_sa_encrypt != SADB_EALG_NULL && + ((key->sadb_key_bits+7) / 8 == 0 || + (key->sadb_key_bits+7) / 8 > key->sadb_key_len * sizeof(uint64_t))) + return ERR_PTR(-EINVAL); + + x = xfrm_state_alloc(net); + if (x == NULL) + return ERR_PTR(-ENOBUFS); + + x->id.proto = proto; + x->id.spi = sa->sadb_sa_spi; + x->props.replay_window = sa->sadb_sa_replay; + if (sa->sadb_sa_flags & SADB_SAFLAGS_NOECN) + x->props.flags |= XFRM_STATE_NOECN; + if (sa->sadb_sa_flags & SADB_SAFLAGS_DECAP_DSCP) + x->props.flags |= XFRM_STATE_DECAP_DSCP; + if (sa->sadb_sa_flags & SADB_SAFLAGS_NOPMTUDISC) + x->props.flags |= XFRM_STATE_NOPMTUDISC; + + lifetime = ext_hdrs[SADB_EXT_LIFETIME_HARD - 1]; + if (lifetime != NULL) { + x->lft.hard_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations); + x->lft.hard_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes); + x->lft.hard_add_expires_seconds = lifetime->sadb_lifetime_addtime; + x->lft.hard_use_expires_seconds = lifetime->sadb_lifetime_usetime; + } + lifetime = ext_hdrs[SADB_EXT_LIFETIME_SOFT - 1]; + if (lifetime != NULL) { + x->lft.soft_packet_limit = _KEY2X(lifetime->sadb_lifetime_allocations); + x->lft.soft_byte_limit = _KEY2X(lifetime->sadb_lifetime_bytes); + x->lft.soft_add_expires_seconds = lifetime->sadb_lifetime_addtime; + x->lft.soft_use_expires_seconds = lifetime->sadb_lifetime_usetime; + } + + sec_ctx = ext_hdrs[SADB_X_EXT_SEC_CTX - 1]; + if (sec_ctx != NULL) { + struct xfrm_user_sec_ctx *uctx = pfkey_sadb2xfrm_user_sec_ctx(sec_ctx); + + if (!uctx) + goto out; + + err = security_xfrm_state_alloc(x, uctx); + kfree(uctx); + + if (err) + goto out; + } + + key = ext_hdrs[SADB_EXT_KEY_AUTH - 1]; + if (sa->sadb_sa_auth) { + int keysize = 0; + struct xfrm_algo_desc *a = xfrm_aalg_get_byid(sa->sadb_sa_auth); + if (!a || !a->pfkey_supported) { + err = -ENOSYS; + goto out; + } + if (key) + keysize = (key->sadb_key_bits + 7) / 8; + x->aalg = kmalloc(sizeof(*x->aalg) + keysize, GFP_KERNEL); + if (!x->aalg) + goto out; + strcpy(x->aalg->alg_name, a->name); + x->aalg->alg_key_len = 0; + if (key) { + x->aalg->alg_key_len = key->sadb_key_bits; + memcpy(x->aalg->alg_key, key+1, keysize); + } + x->aalg->alg_trunc_len = a->uinfo.auth.icv_truncbits; + x->props.aalgo = sa->sadb_sa_auth; + /* x->algo.flags = sa->sadb_sa_flags; */ + } + if (sa->sadb_sa_encrypt) { + if (hdr->sadb_msg_satype == SADB_X_SATYPE_IPCOMP) { + struct xfrm_algo_desc *a = xfrm_calg_get_byid(sa->sadb_sa_encrypt); + if (!a || !a->pfkey_supported) { + err = -ENOSYS; + goto out; + } + x->calg = kmalloc(sizeof(*x->calg), GFP_KERNEL); + if (!x->calg) + goto out; + strcpy(x->calg->alg_name, a->name); + x->props.calgo = sa->sadb_sa_encrypt; + } else { + int keysize = 0; + struct xfrm_algo_desc *a = xfrm_ealg_get_byid(sa->sadb_sa_encrypt); + if (!a || !a->pfkey_supported) { + err = -ENOSYS; + goto out; + } + key = (struct sadb_key*) ext_hdrs[SADB_EXT_KEY_ENCRYPT-1]; + if (key) + keysize = (key->sadb_key_bits + 7) / 8; + x->ealg = kmalloc(sizeof(*x->ealg) + keysize, GFP_KERNEL); + if (!x->ealg) + goto out; + strcpy(x->ealg->alg_name, a->name); + x->ealg->alg_key_len = 0; + if (key) { + x->ealg->alg_key_len = key->sadb_key_bits; + memcpy(x->ealg->alg_key, key+1, keysize); + } + x->props.ealgo = sa->sadb_sa_encrypt; + } + } + /* x->algo.flags = sa->sadb_sa_flags; */ + + x->props.family = pfkey_sadb_addr2xfrm_addr((struct sadb_address *) ext_hdrs[SADB_EXT_ADDRESS_SRC-1], + &x->props.saddr); + if (!x->props.family) { + err = -EAFNOSUPPORT; + goto out; + } + pfkey_sadb_addr2xfrm_addr((struct sadb_address *) ext_hdrs[SADB_EXT_ADDRESS_DST-1], + &x->id.daddr); + + if (ext_hdrs[SADB_X_EXT_SA2-1]) { + const struct sadb_x_sa2 *sa2 = ext_hdrs[SADB_X_EXT_SA2-1]; + int mode = pfkey_mode_to_xfrm(sa2->sadb_x_sa2_mode); + if (mode < 0) { + err = -EINVAL; + goto out; + } + x->props.mode = mode; + x->props.reqid = sa2->sadb_x_sa2_reqid; + } + + if (ext_hdrs[SADB_EXT_ADDRESS_PROXY-1]) { + const struct sadb_address *addr = ext_hdrs[SADB_EXT_ADDRESS_PROXY-1]; + + /* Nobody uses this, but we try. */ + x->sel.family = pfkey_sadb_addr2xfrm_addr(addr, &x->sel.saddr); + x->sel.prefixlen_s = addr->sadb_address_prefixlen; + } + + if (!x->sel.family) + x->sel.family = x->props.family; + + if (ext_hdrs[SADB_X_EXT_NAT_T_TYPE-1]) { + const struct sadb_x_nat_t_type* n_type; + struct xfrm_encap_tmpl *natt; + + x->encap = kmalloc(sizeof(*x->encap), GFP_KERNEL); + if (!x->encap) + goto out; + + natt = x->encap; + n_type = ext_hdrs[SADB_X_EXT_NAT_T_TYPE-1]; + natt->encap_type = n_type->sadb_x_nat_t_type_type; + + if (ext_hdrs[SADB_X_EXT_NAT_T_SPORT-1]) { + const struct sadb_x_nat_t_port *n_port = + ext_hdrs[SADB_X_EXT_NAT_T_SPORT-1]; + natt->encap_sport = n_port->sadb_x_nat_t_port_port; + } + if (ext_hdrs[SADB_X_EXT_NAT_T_DPORT-1]) { + const struct sadb_x_nat_t_port *n_port = + ext_hdrs[SADB_X_EXT_NAT_T_DPORT-1]; + natt->encap_dport = n_port->sadb_x_nat_t_port_port; + } + memset(&natt->encap_oa, 0, sizeof(natt->encap_oa)); + } + + err = xfrm_init_state(x); + if (err) + goto out; + + x->km.seq = hdr->sadb_msg_seq; + return x; + +out: + x->km.state = XFRM_STATE_DEAD; + xfrm_state_put(x); + return ERR_PTR(err); +} +","@@ -2694,6 +2694,7 @@ static int key_notify_policy_flush(const struct km_event *c) + hdr->sadb_msg_pid = c->portid; + hdr->sadb_msg_version = PF_KEY_V2; + hdr->sadb_msg_errno = (uint8_t) 0; ++ hdr->sadb_msg_satype = SADB_SATYPE_UNSPEC; + hdr->sadb_msg_len = (sizeof(struct sadb_msg) / sizeof(uint64_t)); + pfkey_broadcast(skb_out, GFP_ATOMIC, BROADCAST_ALL, NULL, c->net); + return 0;",2469,2800,4096 +18092,"static int mboxlist_do_find(struct find_rock *rock, const strarray_t *patterns) +{ + const char *userid = rock->userid; + int isadmin = rock->isadmin; + + int crossdomains = config_getswitch(IMAPOPT_CROSSDOMAINS); + char inbox[MAX_MAILBOX_BUFFER]; + size_t inboxlen = 0; + size_t prefixlen, len; + size_t domainlen = 0; + size_t userlen = userid ? strlen(userid) : 0; + char domainpat[MAX_MAILBOX_BUFFER]; /* do intra-domain fetches only */ + char commonpat[MAX_MAILBOX_BUFFER]; + int r = 0; + int i; + const char *p; + + if (patterns->count < 1) return 0; /* nothing to do */ + + for (i = 0; i < patterns->count; i++) { + glob *g = glob_init(strarray_nth(patterns, i), rock->namespace->hier_sep); + ptrarray_append(&rock->globs, g); + } + + if (config_virtdomains && userid && (p = strchr(userid, '@'))) { + userlen = p - userid; + domainlen = strlen(p); /* includes separator */ + snprintf(domainpat, sizeof(domainpat), ""%s!"", p+1); + } + else + domainpat[0] = '\0'; + + /* calculate the inbox (with trailing .INBOX. for later use) */ + if (userid && (!(p = strchr(userid, rock->namespace->hier_sep)) || + ((p - userid) > (int)userlen)) && + strlen(userid)+7 < MAX_MAILBOX_BUFFER) { + char *t, *tmpuser = NULL; + const char *inboxuser; + + if (domainlen) + snprintf(inbox, sizeof(inbox), ""%s!"", userid+userlen+1); + if (rock->namespace->hier_sep == '/' && (p = strchr(userid, '.'))) { + tmpuser = xmalloc(userlen); + memcpy(tmpuser, userid, userlen); + t = tmpuser + (p - userid); + while(t < (tmpuser + userlen)) { + if (*t == '.') + *t = '^'; + t++; + } + inboxuser = tmpuser; + } else + inboxuser = userid; + snprintf(inbox+domainlen, sizeof(inbox)-domainlen, + ""user.%.*s.INBOX."", (int)userlen, inboxuser); + free(tmpuser); + inboxlen = strlen(inbox) - 7; + } + else { + userid = 0; + } + + /* Find the common search prefix of all patterns */ + const char *firstpat = strarray_nth(patterns, 0); + for (prefixlen = 0; firstpat[prefixlen]; prefixlen++) { + if (prefixlen >= MAX_MAILBOX_NAME) { + r = IMAP_MAILBOX_BADNAME; + goto done; + } + char c = firstpat[prefixlen]; + for (i = 1; i < patterns->count; i++) { + const char *pat = strarray_nth(patterns, i); + if (pat[prefixlen] != c) break; + } + if (i < patterns->count) break; + if (c == '*' || c == '%' || c == '?') break; + commonpat[prefixlen] = c; + } + commonpat[prefixlen] = '\0'; + + if (patterns->count == 1) { + /* Skip pattern which matches shared namespace prefix */ + if (!strcmp(firstpat+prefixlen, ""%"")) + rock->singlepercent = 2; + /* output prefix regardless */ + if (!strcmp(firstpat+prefixlen, ""*%"")) + rock->singlepercent = 1; + } + + /* + * Personal (INBOX) namespace (only if not admin) + */ + if (userid && !isadmin) { + /* first the INBOX */ + rock->mb_category = MBNAME_INBOX; + r = cyrusdb_forone(rock->db, inbox, inboxlen, &find_p, &find_cb, rock, NULL); + if (r == CYRUSDB_DONE) r = 0; + if (r) goto done; + + if (rock->namespace->isalt) { + /* do exact INBOX subs before resetting the namebuffer */ + rock->mb_category = MBNAME_INBOXSUB; + r = cyrusdb_foreach(rock->db, inbox, inboxlen+7, &find_p, &find_cb, rock, NULL); + if (r == CYRUSDB_DONE) r = 0; + if (r) goto done; + + /* reset the the namebuffer */ + r = (*rock->proc)(NULL, rock->procrock); + if (r) goto done; + } + + /* iterate through all the mailboxes under the user's inbox */ + rock->mb_category = MBNAME_OWNER; + r = cyrusdb_foreach(rock->db, inbox, inboxlen+1, &find_p, &find_cb, rock, NULL); + if (r == CYRUSDB_DONE) r = 0; + if (r) goto done; + + /* ""Alt Prefix"" folders */ + if (rock->namespace->isalt) { + /* reset the the namebuffer */ + r = (*rock->proc)(NULL, rock->procrock); + if (r) goto done; + + rock->mb_category = MBNAME_ALTINBOX; + + /* special case user.foo.INBOX. If we're singlepercent == 2, this could + return DONE, in which case we don't need to foreach the rest of the + altprefix space */ + r = cyrusdb_forone(rock->db, inbox, inboxlen+6, &find_p, &find_cb, rock, NULL); + if (r == CYRUSDB_DONE) goto skipalt; + if (r) goto done; + + /* special case any other altprefix stuff */ + rock->mb_category = MBNAME_ALTPREFIX; + r = cyrusdb_foreach(rock->db, inbox, inboxlen+1, &find_p, &find_cb, rock, NULL); + skipalt: /* we got a done, so skip out of the foreach early */ + if (r == CYRUSDB_DONE) r = 0; + if (r) goto done; + } + } + + /* + * Other Users namespace + * + * If ""Other Users*"" can match pattern, search for those mailboxes next + */ + if (isadmin || rock->namespace->accessible[NAMESPACE_USER]) { + len = strlen(rock->namespace->prefix[NAMESPACE_USER]); + if (len) len--; // trailing separator + + if (!strncmp(rock->namespace->prefix[NAMESPACE_USER], commonpat, MIN(len, prefixlen))) { + if (prefixlen < len) { + /* we match all users */ + strlcpy(domainpat+domainlen, ""user."", sizeof(domainpat)-domainlen); + } + else { + /* just those in this prefix */ + strlcpy(domainpat+domainlen, ""user."", sizeof(domainpat)-domainlen); + strlcpy(domainpat+domainlen+5, commonpat+len+1, sizeof(domainpat)-domainlen-5); + } + + rock->mb_category = MBNAME_OTHERUSER; + + /* because of how domains work, with crossdomains or admin you can't prefix at all :( */ + size_t thislen = (isadmin || crossdomains) ? 0 : strlen(domainpat); + + /* reset the the namebuffer */ + r = (*rock->proc)(NULL, rock->procrock); + if (r) goto done; + + r = mboxlist_find_category(rock, domainpat, thislen); + if (r) goto done; + } + } + + /* + * Shared namespace + * + * search for all remaining mailboxes. + * just bother looking at the ones that have the same pattern prefix. + */ + if (isadmin || rock->namespace->accessible[NAMESPACE_SHARED]) { + len = strlen(rock->namespace->prefix[NAMESPACE_SHARED]); + if (len) len--; // trailing separator + + if (!strncmp(rock->namespace->prefix[NAMESPACE_SHARED], commonpat, MIN(len, prefixlen))) { + rock->mb_category = MBNAME_SHARED; + + /* reset the the namebuffer */ + r = (*rock->proc)(NULL, rock->procrock); + if (r) goto done; + + /* iterate through all the non-user folders on the server */ + r = mboxlist_find_category(rock, domainpat, domainlen); + if (r) goto done; + } + } + + /* finish with a reset call always */ + r = (*rock->proc)(NULL, rock->procrock); + + done: + for (i = 0; i < rock->globs.count; i++) { + glob *g = ptrarray_nth(&rock->globs, i); + glob_free(&g); + } + ptrarray_fini(&rock->globs); + + return r; +} +",1,"static int mboxlist_do_find(struct find_rock *rock, const strarray_t *patterns) +{ + const char *userid = rock->userid; + int isadmin = rock->isadmin; + + int crossdomains = config_getswitch(IMAPOPT_CROSSDOMAINS); + char inbox[MAX_MAILBOX_BUFFER]; + size_t inboxlen = 0; + size_t prefixlen, len; + size_t domainlen = 0; + size_t userlen = userid ? strlen(userid) : 0; + char domainpat[MAX_MAILBOX_BUFFER]; /* do intra-domain fetches only */ + char commonpat[MAX_MAILBOX_BUFFER]; + int r = 0; + int i; + const char *p; + + if (patterns->count < 1) return 0; /* nothing to do */ + + for (i = 0; i < patterns->count; i++) { + glob *g = glob_init(strarray_nth(patterns, i), rock->namespace->hier_sep); + ptrarray_append(&rock->globs, g); + } + + if (config_virtdomains && userid && (p = strchr(userid, '@'))) { + userlen = p - userid; + domainlen = strlen(p); /* includes separator */ + snprintf(domainpat, sizeof(domainpat), ""%s!"", p+1); + } + else + domainpat[0] = '\0'; + + /* calculate the inbox (with trailing .INBOX. for later use) */ + if (userid && (!(p = strchr(userid, rock->namespace->hier_sep)) || + ((p - userid) > (int)userlen)) && + strlen(userid)+7 < MAX_MAILBOX_BUFFER) { + char *t, *tmpuser = NULL; + const char *inboxuser; + + if (domainlen) + snprintf(inbox, sizeof(inbox), ""%s!"", userid+userlen+1); + if (rock->namespace->hier_sep == '/' && (p = strchr(userid, '.'))) { + tmpuser = xmalloc(userlen); + memcpy(tmpuser, userid, userlen); + t = tmpuser + (p - userid); + while(t < (tmpuser + userlen)) { + if (*t == '.') + *t = '^'; + t++; + } + inboxuser = tmpuser; + } else + inboxuser = userid; + snprintf(inbox+domainlen, sizeof(inbox)-domainlen, + ""user.%.*s.INBOX."", (int)userlen, inboxuser); + free(tmpuser); + inboxlen = strlen(inbox) - 7; + } + else { + userid = 0; + } + + /* Find the common search prefix of all patterns */ + const char *firstpat = strarray_nth(patterns, 0); + for (prefixlen = 0; firstpat[prefixlen]; prefixlen++) { + if (prefixlen >= MAX_MAILBOX_NAME) { + r = IMAP_MAILBOX_BADNAME; + goto done; + } + char c = firstpat[prefixlen]; + for (i = 1; i < patterns->count; i++) { + const char *pat = strarray_nth(patterns, i); + if (pat[prefixlen] != c) break; + } + if (i < patterns->count) break; + if (c == '*' || c == '%' || c == '?') break; + commonpat[prefixlen] = c; + } + commonpat[prefixlen] = '\0'; + + if (patterns->count == 1) { + /* Skip pattern which matches shared namespace prefix */ + if (!strcmp(firstpat+prefixlen, ""%"")) + rock->singlepercent = 2; + /* output prefix regardless */ + if (!strcmp(firstpat+prefixlen, ""*%"")) + rock->singlepercent = 1; + } + + /* + * Personal (INBOX) namespace (only if not admin) + */ + if (userid && !isadmin) { + /* first the INBOX */ + rock->mb_category = MBNAME_INBOX; + r = cyrusdb_forone(rock->db, inbox, inboxlen, &find_p, &find_cb, rock, NULL); + if (r == CYRUSDB_DONE) r = 0; + if (r) goto done; + + if (rock->namespace->isalt) { + /* do exact INBOX subs before resetting the namebuffer */ + rock->mb_category = MBNAME_INBOXSUB; + r = cyrusdb_foreach(rock->db, inbox, inboxlen+7, &find_p, &find_cb, rock, NULL); + if (r == CYRUSDB_DONE) r = 0; + if (r) goto done; + + /* reset the the namebuffer */ + r = (*rock->proc)(NULL, rock->procrock); + if (r) goto done; + } + + /* iterate through all the mailboxes under the user's inbox */ + rock->mb_category = MBNAME_OWNER; + r = cyrusdb_foreach(rock->db, inbox, inboxlen+1, &find_p, &find_cb, rock, NULL); + if (r == CYRUSDB_DONE) r = 0; + if (r) goto done; + + /* ""Alt Prefix"" folders */ + if (rock->namespace->isalt) { + /* reset the the namebuffer */ + r = (*rock->proc)(NULL, rock->procrock); + if (r) goto done; + + rock->mb_category = MBNAME_ALTINBOX; + + /* special case user.foo.INBOX. If we're singlepercent == 2, this could + return DONE, in which case we don't need to foreach the rest of the + altprefix space */ + r = cyrusdb_forone(rock->db, inbox, inboxlen+6, &find_p, &find_cb, rock, NULL); + if (r == CYRUSDB_DONE) goto skipalt; + if (r) goto done; + + /* special case any other altprefix stuff */ + rock->mb_category = MBNAME_ALTPREFIX; + r = cyrusdb_foreach(rock->db, inbox, inboxlen+1, &find_p, &find_cb, rock, NULL); + skipalt: /* we got a done, so skip out of the foreach early */ + if (r == CYRUSDB_DONE) r = 0; + if (r) goto done; + } + } + + /* + * Other Users namespace + * + * If ""Other Users*"" can match pattern, search for those mailboxes next + */ + if (isadmin || rock->namespace->accessible[NAMESPACE_USER]) { + len = strlen(rock->namespace->prefix[NAMESPACE_USER]); + if (len) len--; // trailing separator + + if (!strncmp(rock->namespace->prefix[NAMESPACE_USER], commonpat, MIN(len, prefixlen))) { + if (prefixlen <= len) { + /* we match all users */ + strlcpy(domainpat+domainlen, ""user."", sizeof(domainpat)-domainlen); + } + else { + /* just those in this prefix */ + strlcpy(domainpat+domainlen, ""user."", sizeof(domainpat)-domainlen); + strlcpy(domainpat+domainlen+5, commonpat+len+1, sizeof(domainpat)-domainlen-5); + } + + rock->mb_category = MBNAME_OTHERUSER; + + /* because of how domains work, with crossdomains or admin you can't prefix at all :( */ + size_t thislen = (isadmin || crossdomains) ? 0 : strlen(domainpat); + + /* reset the the namebuffer */ + r = (*rock->proc)(NULL, rock->procrock); + if (r) goto done; + + r = mboxlist_find_category(rock, domainpat, thislen); + if (r) goto done; + } + } + + /* + * Shared namespace + * + * search for all remaining mailboxes. + * just bother looking at the ones that have the same pattern prefix. + */ + if (isadmin || rock->namespace->accessible[NAMESPACE_SHARED]) { + len = strlen(rock->namespace->prefix[NAMESPACE_SHARED]); + if (len) len--; // trailing separator + + if (!strncmp(rock->namespace->prefix[NAMESPACE_SHARED], commonpat, MIN(len, prefixlen))) { + rock->mb_category = MBNAME_SHARED; + + /* reset the the namebuffer */ + r = (*rock->proc)(NULL, rock->procrock); + if (r) goto done; + + /* iterate through all the non-user folders on the server */ + r = mboxlist_find_category(rock, domainpat, domainlen); + if (r) goto done; + } + } + + /* finish with a reset call always */ + r = (*rock->proc)(NULL, rock->procrock); + + done: + for (i = 0; i < rock->globs.count; i++) { + glob *g = ptrarray_nth(&rock->globs, i); + glob_free(&g); + } + ptrarray_fini(&rock->globs); + + return r; +} +","@@ -2851,7 +2851,7 @@ static int mboxlist_do_find(struct find_rock *rock, const strarray_t *patterns) + if (len) len--; // trailing separator + + if (!strncmp(rock->namespace->prefix[NAMESPACE_USER], commonpat, MIN(len, prefixlen))) { +- if (prefixlen < len) { ++ if (prefixlen <= len) { + /* we match all users */ + strlcpy(domainpat+domainlen, ""user."", sizeof(domainpat)-domainlen); + }",1956,2287,4096 +8250,"doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, + size_t size, off_t fsize, int mach, int strtab, int *flags, + uint16_t *notecount) +{ + Elf32_Shdr sh32; + Elf64_Shdr sh64; + int stripped = 1, has_debug_info = 0; + size_t nbadcap = 0; + void *nbuf; + off_t noff, coff, name_off; + uint64_t cap_hw1 = 0; /* SunOS 5.x hardware capabilities */ + uint64_t cap_sf1 = 0; /* SunOS 5.x software capabilities */ + char name[50]; + ssize_t namesize; + + if (size != xsh_sizeof) { + if (file_printf(ms, "", corrupted section header size"") == -1) + return -1; + return 0; + } + + /* Read offset of name section to be able to read section names later */ + if (pread(fd, xsh_addr, xsh_sizeof, CAST(off_t, (off + size * strtab))) + < CAST(ssize_t, xsh_sizeof)) { + if (file_printf(ms, "", missing section headers"") == -1) + return -1; + return 0; + } + name_off = xsh_offset; + + for ( ; num; num--) { + /* Read the name of this section. */ + if ((namesize = pread(fd, name, sizeof(name) - 1, + name_off + xsh_name)) == -1) { + file_badread(ms); + return -1; + } + name[namesize] = '\0'; + if (strcmp(name, "".debug_info"") == 0) { + has_debug_info = 1; + stripped = 0; + } + + if (pread(fd, xsh_addr, xsh_sizeof, off) < + CAST(ssize_t, xsh_sizeof)) { + file_badread(ms); + return -1; + } + off += size; + + /* Things we can determine before we seek */ + switch (xsh_type) { + case SHT_SYMTAB: +#if 0 + case SHT_DYNSYM: +#endif + stripped = 0; + break; + default: + if (fsize != SIZE_UNKNOWN && xsh_offset > fsize) { + /* Perhaps warn here */ + continue; + } + break; + } + + + /* Things we can determine when we seek */ + switch (xsh_type) { + case SHT_NOTE: + if (CAST(uintmax_t, (xsh_size + xsh_offset)) > + CAST(uintmax_t, fsize)) { + if (file_printf(ms, + "", note offset/size %#"" INTMAX_T_FORMAT + ""x+%#"" INTMAX_T_FORMAT ""x exceeds"" + "" file size %#"" INTMAX_T_FORMAT ""x"", + CAST(uintmax_t, xsh_offset), + CAST(uintmax_t, xsh_size), + CAST(uintmax_t, fsize)) == -1) + return -1; + return 0; + } + if ((nbuf = malloc(xsh_size)) == NULL) { + file_error(ms, errno, ""Cannot allocate memory"" + "" for note""); + return -1; + } + if (pread(fd, nbuf, xsh_size, xsh_offset) < + CAST(ssize_t, xsh_size)) { + file_badread(ms); + free(nbuf); + return -1; + } + + noff = 0; + for (;;) { + if (noff >= CAST(off_t, xsh_size)) + break; + noff = donote(ms, nbuf, CAST(size_t, noff), + xsh_size, clazz, swap, 4, flags, notecount, + fd, 0, 0, 0); + if (noff == 0) + break; + } + free(nbuf); + break; + case SHT_SUNW_cap: + switch (mach) { + case EM_SPARC: + case EM_SPARCV9: + case EM_IA_64: + case EM_386: + case EM_AMD64: + break; + default: + goto skip; + } + + if (nbadcap > 5) + break; + if (lseek(fd, xsh_offset, SEEK_SET) + == CAST(off_t, -1)) { + file_badseek(ms); + return -1; + } + coff = 0; + for (;;) { + Elf32_Cap cap32; + Elf64_Cap cap64; + char cbuf[/*CONSTCOND*/ + MAX(sizeof(cap32), sizeof(cap64))]; + if ((coff += xcap_sizeof) > + CAST(off_t, xsh_size)) + break; + if (read(fd, cbuf, CAST(size_t, xcap_sizeof)) != + CAST(ssize_t, xcap_sizeof)) { + file_badread(ms); + return -1; + } + if (cbuf[0] == 'A') { +#ifdef notyet + char *p = cbuf + 1; + uint32_t len, tag; + memcpy(&len, p, sizeof(len)); + p += 4; + len = getu32(swap, len); + if (memcmp(""gnu"", p, 3) != 0) { + if (file_printf(ms, + "", unknown capability %.3s"", p) + == -1) + return -1; + break; + } + p += strlen(p) + 1; + tag = *p++; + memcpy(&len, p, sizeof(len)); + p += 4; + len = getu32(swap, len); + if (tag != 1) { + if (file_printf(ms, "", unknown gnu"" + "" capability tag %d"", tag) + == -1) + return -1; + break; + } +#endif + break; + } + memcpy(xcap_addr, cbuf, xcap_sizeof); + switch (xcap_tag) { + case CA_SUNW_NULL: + break; + case CA_SUNW_HW_1: + cap_hw1 |= xcap_val; + break; + case CA_SUNW_SF_1: + cap_sf1 |= xcap_val; + break; + default: + if (file_printf(ms, + "", with unknown capability "" + ""%#"" INT64_T_FORMAT ""x = %#"" + INT64_T_FORMAT ""x"", + CAST(unsigned long long, xcap_tag), + CAST(unsigned long long, xcap_val)) + == -1) + return -1; + if (nbadcap++ > 2) + coff = xsh_size; + break; + } + } + /*FALLTHROUGH*/ + skip: + default: + break; + } + } + + if (has_debug_info) { + if (file_printf(ms, "", with debug_info"") == -1) + return -1; + } + if (file_printf(ms, "", %sstripped"", stripped ? """" : ""not "") == -1) + return -1; + if (cap_hw1) { + const cap_desc_t *cdp; + switch (mach) { + case EM_SPARC: + case EM_SPARC32PLUS: + case EM_SPARCV9: + cdp = cap_desc_sparc; + break; + case EM_386: + case EM_IA_64: + case EM_AMD64: + cdp = cap_desc_386; + break; + default: + cdp = NULL; + break; + } + if (file_printf(ms, "", uses"") == -1) + return -1; + if (cdp) { + while (cdp->cd_name) { + if (cap_hw1 & cdp->cd_mask) { + if (file_printf(ms, + "" %s"", cdp->cd_name) == -1) + return -1; + cap_hw1 &= ~cdp->cd_mask; + } + ++cdp; + } + if (cap_hw1) + if (file_printf(ms, + "" unknown hardware capability %#"" + INT64_T_FORMAT ""x"", + CAST(unsigned long long, cap_hw1)) == -1) + return -1; + } else { + if (file_printf(ms, + "" hardware capability %#"" INT64_T_FORMAT ""x"", + CAST(unsigned long long, cap_hw1)) == -1) + return -1; + } + } + if (cap_sf1) { + if (cap_sf1 & SF1_SUNW_FPUSED) { + if (file_printf(ms, + (cap_sf1 & SF1_SUNW_FPKNWN) + ? "", uses frame pointer"" + : "", not known to use frame pointer"") == -1) + return -1; + } + cap_sf1 &= ~SF1_SUNW_MASK; + if (cap_sf1) + if (file_printf(ms, + "", with unknown software capability %#"" + INT64_T_FORMAT ""x"", + CAST(unsigned long long, cap_sf1)) == -1) + return -1; + } + return 0; +} +",0,"doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, + size_t size, off_t fsize, int mach, int strtab, int *flags, + uint16_t *notecount) +{ + Elf32_Shdr sh32; + Elf64_Shdr sh64; + int stripped = 1, has_debug_info = 0; + size_t nbadcap = 0; + void *nbuf; + off_t noff, coff, name_off; + uint64_t cap_hw1 = 0; /* SunOS 5.x hardware capabilities */ + uint64_t cap_sf1 = 0; /* SunOS 5.x software capabilities */ + char name[50]; + ssize_t namesize; + + if (size != xsh_sizeof) { + if (file_printf(ms, "", corrupted section header size"") == -1) + return -1; + return 0; + } + + /* Read offset of name section to be able to read section names later */ + if (pread(fd, xsh_addr, xsh_sizeof, CAST(off_t, (off + size * strtab))) + < CAST(ssize_t, xsh_sizeof)) { + if (file_printf(ms, "", missing section headers"") == -1) + return -1; + return 0; + } + name_off = xsh_offset; + + for ( ; num; num--) { + /* Read the name of this section. */ + if ((namesize = pread(fd, name, sizeof(name) - 1, + name_off + xsh_name)) == -1) { + file_badread(ms); + return -1; + } + name[namesize] = '\0'; + if (strcmp(name, "".debug_info"") == 0) { + has_debug_info = 1; + stripped = 0; + } + + if (pread(fd, xsh_addr, xsh_sizeof, off) < + CAST(ssize_t, xsh_sizeof)) { + file_badread(ms); + return -1; + } + off += size; + + /* Things we can determine before we seek */ + switch (xsh_type) { + case SHT_SYMTAB: +#if 0 + case SHT_DYNSYM: +#endif + stripped = 0; + break; + default: + if (fsize != SIZE_UNKNOWN && xsh_offset > fsize) { + /* Perhaps warn here */ + continue; + } + break; + } + + + /* Things we can determine when we seek */ + switch (xsh_type) { + case SHT_NOTE: + if (CAST(uintmax_t, (xsh_size + xsh_offset)) > + CAST(uintmax_t, fsize)) { + if (file_printf(ms, + "", note offset/size %#"" INTMAX_T_FORMAT + ""x+%#"" INTMAX_T_FORMAT ""x exceeds"" + "" file size %#"" INTMAX_T_FORMAT ""x"", + CAST(uintmax_t, xsh_offset), + CAST(uintmax_t, xsh_size), + CAST(uintmax_t, fsize)) == -1) + return -1; + return 0; + } + if ((nbuf = malloc(xsh_size)) == NULL) { + file_error(ms, errno, ""Cannot allocate memory"" + "" for note""); + return -1; + } + if (pread(fd, nbuf, xsh_size, xsh_offset) < + CAST(ssize_t, xsh_size)) { + file_badread(ms); + free(nbuf); + return -1; + } + + noff = 0; + for (;;) { + if (noff >= CAST(off_t, xsh_size)) + break; + noff = donote(ms, nbuf, CAST(size_t, noff), + xsh_size, clazz, swap, 4, flags, notecount, + fd, 0, 0, 0); + if (noff == 0) + break; + } + free(nbuf); + break; + case SHT_SUNW_cap: + switch (mach) { + case EM_SPARC: + case EM_SPARCV9: + case EM_IA_64: + case EM_386: + case EM_AMD64: + break; + default: + goto skip; + } + + if (nbadcap > 5) + break; + if (lseek(fd, xsh_offset, SEEK_SET) + == CAST(off_t, -1)) { + file_badseek(ms); + return -1; + } + coff = 0; + for (;;) { + Elf32_Cap cap32; + Elf64_Cap cap64; + char cbuf[/*CONSTCOND*/ + MAX(sizeof(cap32), sizeof(cap64))]; + if ((coff += xcap_sizeof) > + CAST(off_t, xsh_size)) + break; + if (read(fd, cbuf, CAST(size_t, xcap_sizeof)) != + CAST(ssize_t, xcap_sizeof)) { + file_badread(ms); + return -1; + } + if (cbuf[0] == 'A') { +#ifdef notyet + char *p = cbuf + 1; + uint32_t len, tag; + memcpy(&len, p, sizeof(len)); + p += 4; + len = getu32(swap, len); + if (memcmp(""gnu"", p, 3) != 0) { + if (file_printf(ms, + "", unknown capability %.3s"", p) + == -1) + return -1; + break; + } + p += strlen(p) + 1; + tag = *p++; + memcpy(&len, p, sizeof(len)); + p += 4; + len = getu32(swap, len); + if (tag != 1) { + if (file_printf(ms, "", unknown gnu"" + "" capability tag %d"", tag) + == -1) + return -1; + break; + } +#endif + break; + } + memcpy(xcap_addr, cbuf, xcap_sizeof); + switch (xcap_tag) { + case CA_SUNW_NULL: + break; + case CA_SUNW_HW_1: + cap_hw1 |= xcap_val; + break; + case CA_SUNW_SF_1: + cap_sf1 |= xcap_val; + break; + default: + if (file_printf(ms, + "", with unknown capability "" + ""%#"" INT64_T_FORMAT ""x = %#"" + INT64_T_FORMAT ""x"", + CAST(unsigned long long, xcap_tag), + CAST(unsigned long long, xcap_val)) + == -1) + return -1; + if (nbadcap++ > 2) + coff = xsh_size; + break; + } + } + /*FALLTHROUGH*/ + skip: + default: + break; + } + } + + if (has_debug_info) { + if (file_printf(ms, "", with debug_info"") == -1) + return -1; + } + if (file_printf(ms, "", %sstripped"", stripped ? """" : ""not "") == -1) + return -1; + if (cap_hw1) { + const cap_desc_t *cdp; + switch (mach) { + case EM_SPARC: + case EM_SPARC32PLUS: + case EM_SPARCV9: + cdp = cap_desc_sparc; + break; + case EM_386: + case EM_IA_64: + case EM_AMD64: + cdp = cap_desc_386; + break; + default: + cdp = NULL; + break; + } + if (file_printf(ms, "", uses"") == -1) + return -1; + if (cdp) { + while (cdp->cd_name) { + if (cap_hw1 & cdp->cd_mask) { + if (file_printf(ms, + "" %s"", cdp->cd_name) == -1) + return -1; + cap_hw1 &= ~cdp->cd_mask; + } + ++cdp; + } + if (cap_hw1) + if (file_printf(ms, + "" unknown hardware capability %#"" + INT64_T_FORMAT ""x"", + CAST(unsigned long long, cap_hw1)) == -1) + return -1; + } else { + if (file_printf(ms, + "" hardware capability %#"" INT64_T_FORMAT ""x"", + CAST(unsigned long long, cap_hw1)) == -1) + return -1; + } + } + if (cap_sf1) { + if (cap_sf1 & SF1_SUNW_FPUSED) { + if (file_printf(ms, + (cap_sf1 & SF1_SUNW_FPKNWN) + ? "", uses frame pointer"" + : "", not known to use frame pointer"") == -1) + return -1; + } + cap_sf1 &= ~SF1_SUNW_MASK; + if (cap_sf1) + if (file_printf(ms, + "", with unknown software capability %#"" + INT64_T_FORMAT ""x"", + CAST(unsigned long long, cap_sf1)) == -1) + return -1; + } + return 0; +} +","@@ -27,7 +27,7 @@ + #include ""file.h"" + + #ifndef lint +-FILE_RCSID(""@(#)$File: readelf.c,v 1.142 2018/05/24 18:08:01 christos Exp $"") ++FILE_RCSID(""@(#)$File: readelf.c,v 1.143 2018/06/09 16:00:06 christos Exp $"") + #endif + + #ifdef BUILTIN_ELF +@@ -842,7 +842,8 @@ do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, + + cname = (unsigned char *) + &nbuf[doff + prpsoffsets(i)]; +- for (cp = cname; *cp && isprint(*cp); cp++) ++ for (cp = cname; cp < nbuf + size && *cp ++ && isprint(*cp); cp++) + continue; + /* + * Linux apparently appends a space at the end",2057,2388,4096 +7515,"hfs_ext_find_extent_record_attr(HFS_INFO * hfs, uint32_t cnid, + TSK_FS_ATTR * a_attr, unsigned char dataForkQ) +{ + TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info); + uint16_t nodesize; /* size of nodes (all, regardless of the name) */ + uint32_t cur_node; /* node id of the current node */ + char *node = NULL; + uint8_t is_done; + uint8_t desiredType; + + tsk_error_reset(); + + if (tsk_verbose) + tsk_fprintf(stderr, + ""hfs_ext_find_extent_record_attr: Looking for extents for file %"" + PRIu32 "" %s\n"", cnid, + dataForkQ ? ""data fork"" : ""resource fork""); + + if (!hfs->has_extents_file) { + return 0; + } + + desiredType = + dataForkQ ? HFS_EXT_KEY_TYPE_DATA : HFS_EXT_KEY_TYPE_RSRC; + + if (hfs->extents_file == NULL) { + ssize_t cnt; + + if ((hfs->extents_file = + tsk_fs_file_open_meta(fs, NULL, + HFS_EXTENTS_FILE_ID)) == NULL) { + return 1; + } + + /* cache the data attribute */ + hfs->extents_attr = + tsk_fs_attrlist_get(hfs->extents_file->meta->attr, + TSK_FS_ATTR_TYPE_DEFAULT); + if (!hfs->extents_attr) { + tsk_error_errstr2_concat + ("" - Default Attribute not found in Extents File""); + return 1; + } + + cnt = tsk_fs_attr_read(hfs->extents_attr, 14, + (char *) &(hfs->extents_header), + sizeof(hfs_btree_header_record), 0); + if (cnt != sizeof(hfs_btree_header_record)) { + if (cnt >= 0) { + tsk_error_reset(); + tsk_error_set_errno(TSK_ERR_FS_READ); + } + tsk_error_set_errstr2 + (""hfs_ext_find_extent_record_attr: Error reading header""); + return 1; + } + } + + nodesize = tsk_getu16(fs->endian, hfs->extents_header.nodesize); + if ((node = (char *) tsk_malloc(nodesize)) == NULL) { + return 1; + } + + /* start at root node */ + cur_node = tsk_getu32(fs->endian, hfs->extents_header.rootNode); + + /* if the root node is zero, then the extents btree is empty */ + /* if no files have overflow extents, the Extents B-tree still + exists on disk, but is an empty B-tree containing only + the header node */ + if (cur_node == 0) { + if (tsk_verbose) + tsk_fprintf(stderr, ""hfs_ext_find_extent_record: "" + ""empty extents btree\n""); + free(node); + return 0; + } + + if (tsk_verbose) + tsk_fprintf(stderr, ""hfs_ext_find_extent_record: starting at "" + ""root node %"" PRIu32 ""; nodesize = %"" + PRIu16 ""\n"", cur_node, nodesize); + + /* Recurse down to the needed leaf nodes and then go forward */ + is_done = 0; + while (is_done == 0) { + TSK_OFF_T cur_off; /* start address of cur_node */ + uint16_t num_rec; /* number of records in this node */ + ssize_t cnt; + hfs_btree_node *node_desc; + + if (cur_node > tsk_getu32(fs->endian, + hfs->extents_header.totalNodes)) { + tsk_error_set_errno(TSK_ERR_FS_GENFS); + tsk_error_set_errstr + (""hfs_ext_find_extent_record_attr: Node %d too large for file"", + cur_node); + free(node); + return 1; + } + + cur_off = (TSK_OFF_T)cur_node * nodesize; + if (tsk_verbose) + tsk_fprintf(stderr, + ""hfs_ext_find_extent_record: reading node %"" PRIu32 + "" at offset %"" PRIuOFF ""\n"", cur_node, cur_off); + + cnt = tsk_fs_attr_read(hfs->extents_attr, cur_off, + node, nodesize, 0); + if (cnt != nodesize) { + if (cnt >= 0) { + tsk_error_reset(); + tsk_error_set_errno(TSK_ERR_FS_READ); + } + tsk_error_set_errstr2 + (""hfs_ext_find_extent_record_attr: Error reading node %d at offset %"" + PRIuOFF, cur_node, cur_off); + free(node); + return 1; + } + + if (nodesize < sizeof(hfs_btree_node)) { + tsk_error_set_errno(TSK_ERR_FS_GENFS); + tsk_error_set_errstr + (""hfs_ext_find_extent_record_attr: Node size %d is too small to be valid"", nodesize); + free(node); + return 1; + } + node_desc = (hfs_btree_node *) node; + num_rec = tsk_getu16(fs->endian, node_desc->num_rec); + + if (num_rec == 0) { + tsk_error_set_errno(TSK_ERR_FS_GENFS); + tsk_error_set_errstr + (""hfs_ext_find_extent_record: zero records in node %"" + PRIu32, cur_node); + free(node); + return 1; + } + + + /* With an index node, find the record with the largest key that is smaller + * to or equal to cnid */ + if (node_desc->type == HFS_BT_NODE_TYPE_IDX) { + uint32_t next_node = 0; + int rec; + + if (tsk_verbose) + tsk_fprintf(stderr, + ""hfs_ext_find_extent_record: Index node %"" PRIu32 + "" @ %"" PRIu64 "" has %"" PRIu16 "" records\n"", cur_node, + cur_off, num_rec); + + for (rec = 0; rec < num_rec; ++rec) { + int cmp; + size_t rec_off; + hfs_btree_key_ext *key; + + rec_off = + tsk_getu16(fs->endian, + &node[nodesize - (rec + 1) * 2]); + if (rec_off + sizeof(hfs_btree_key_ext) > nodesize) { + tsk_error_set_errno(TSK_ERR_FS_GENFS); + tsk_error_set_errstr + (""hfs_ext_find_extent_record_attr: offset of record %d in index node %d too large (%d vs %"" + PRIu16 "")"", rec, cur_node, (int) rec_off, + nodesize); + free(node); + return 1; + } + key = (hfs_btree_key_ext *) & node[rec_off]; + + cmp = hfs_ext_compare_keys(hfs, cnid, key); + + if (tsk_verbose) + tsk_fprintf(stderr, + ""hfs_ext_find_extent_record: record %"" PRIu16 + "" ; keylen %"" PRIu16 "" (FileId: %"" PRIu32 + "", ForkType: %"" PRIu8 "", StartBlk: %"" PRIu32 + ""); compare: %d\n"", rec, tsk_getu16(fs->endian, + key->key_len), tsk_getu32(fs->endian, + key->file_id), key->fork_type, + tsk_getu32(fs->endian, key->start_block), cmp); + + /* save the info from this record unless it is bigger than cnid */ + if ((cmp <= 0) || (next_node == 0)) { + hfs_btree_index_record *idx_rec; + int keylen = + 2 + hfs_get_idxkeylen(hfs, tsk_getu16(fs->endian, + key->key_len), &(hfs->extents_header)); + if (rec_off + keylen > nodesize) { + tsk_error_set_errno(TSK_ERR_FS_GENFS); + tsk_error_set_errstr + (""hfs_ext_find_extent_record_attr: offset and keylenth of record %d in index node %d too large (%d vs %"" + PRIu16 "")"", rec, cur_node, + (int) rec_off + keylen, nodesize); + free(node); + return 1; + } + idx_rec = + (hfs_btree_index_record *) & node[rec_off + + keylen]; + next_node = tsk_getu32(fs->endian, idx_rec->childNode); + } + + if (cmp > 0) { + break; + } + } + + if (next_node == 0) { + if (tsk_verbose) + tsk_fprintf(stderr, + ""hfs_ext_find_extent_record_attr: did not find any keys for %d in index node %d"", + cnid, cur_node); + is_done = 1; + break; + } + cur_node = next_node; + } + + /* with a leaf, we process until we are past cnid. We move right too if we can */ + else if (node_desc->type == HFS_BT_NODE_TYPE_LEAF) { + int rec; + + if (tsk_verbose) + tsk_fprintf(stderr, + ""hfs_ext_find_extent_record: Leaf node %"" PRIu32 "" @ %"" + PRIu64 "" has %"" PRIu16 "" records\n"", cur_node, cur_off, + num_rec); + + for (rec = 0; rec < num_rec; ++rec) { + size_t rec_off; + hfs_btree_key_ext *key; + uint32_t rec_cnid; + hfs_extents *extents; + TSK_OFF_T ext_off = 0; + int keylen; + TSK_FS_ATTR_RUN *attr_run; + + rec_off = + tsk_getu16(fs->endian, + &node[nodesize - (rec + 1) * 2]); + if (rec_off > nodesize) { + tsk_error_set_errno(TSK_ERR_FS_GENFS); + tsk_error_set_errstr + (""hfs_ext_find_extent_record_attr: offset of record %d in leaf node %d too large (%d vs %"" + PRIu16 "")"", rec, cur_node, (int) rec_off, + nodesize); + free(node); + return 1; + } + key = (hfs_btree_key_ext *) & node[rec_off]; + + if (tsk_verbose) + tsk_fprintf(stderr, + ""hfs_ext_find_extent_record: record %"" PRIu16 + ""; keylen %"" PRIu16 "" (%"" PRIu32 + "", %"" PRIu8 "", %"" PRIu32 "")\n"", rec, + tsk_getu16(fs->endian, key->key_len), + tsk_getu32(fs->endian, key->file_id), + key->fork_type, tsk_getu32(fs->endian, + key->start_block)); + + rec_cnid = tsk_getu32(fs->endian, key->file_id); + + + if (rec_cnid < cnid) { + continue; + } + if (rec_cnid > cnid) { + is_done = 1; + break; + } + + + if (key->fork_type != desiredType) { + if (dataForkQ) { + is_done = 1; + break; + } + else + continue; + } + + keylen = 2 + tsk_getu16(fs->endian, key->key_len); + if (rec_off + keylen + sizeof(hfs_extents) > nodesize) { + tsk_error_set_errno(TSK_ERR_FS_GENFS); + tsk_error_set_errstr + (""hfs_ext_find_extent_record_attr: offset and keylenth of record %d in leaf node %d too large (%d vs %"" + PRIu16 "")"", rec, cur_node, (int) rec_off + keylen, + nodesize); + free(node); + return 1; + } + + ext_off = tsk_getu32(fs->endian, key->start_block); + + extents = (hfs_extents *) & node[rec_off + keylen]; + + attr_run = + hfs_extents_to_attr(fs, extents->extents, ext_off); + if ((attr_run == NULL) && (tsk_error_get_errno() != 0)) { + tsk_error_errstr2_concat + ("" - hfs_ext_find_extent_record_attr""); + free(node); + return 1; + } + + if (tsk_fs_attr_add_run(fs, a_attr, attr_run)) { + tsk_error_errstr2_concat + ("" - hfs_ext_find_extent_record_attr""); + free(node); + return 1; + } + } + cur_node = tsk_getu32(fs->endian, node_desc->flink); + if (cur_node == 0) { + is_done = 1; + break; + } + } + else { + tsk_error_set_errno(TSK_ERR_FS_GENFS); + tsk_error_set_errstr(""hfs_ext_find_extent_record: btree node %"" + PRIu32 "" (%"" PRIuOFF "") is neither index nor leaf (%"" PRIu8 + "")"", cur_node, cur_off, node_desc->type); + free(node); + return 1; + } + } + free(node); + return 0; +} +",0,"hfs_ext_find_extent_record_attr(HFS_INFO * hfs, uint32_t cnid, + TSK_FS_ATTR * a_attr, unsigned char dataForkQ) +{ + TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info); + uint16_t nodesize; /* size of nodes (all, regardless of the name) */ + uint32_t cur_node; /* node id of the current node */ + char *node = NULL; + uint8_t is_done; + uint8_t desiredType; + + tsk_error_reset(); + + if (tsk_verbose) + tsk_fprintf(stderr, + ""hfs_ext_find_extent_record_attr: Looking for extents for file %"" + PRIu32 "" %s\n"", cnid, + dataForkQ ? ""data fork"" : ""resource fork""); + + if (!hfs->has_extents_file) { + return 0; + } + + desiredType = + dataForkQ ? HFS_EXT_KEY_TYPE_DATA : HFS_EXT_KEY_TYPE_RSRC; + + if (hfs->extents_file == NULL) { + ssize_t cnt; + + if ((hfs->extents_file = + tsk_fs_file_open_meta(fs, NULL, + HFS_EXTENTS_FILE_ID)) == NULL) { + return 1; + } + + /* cache the data attribute */ + hfs->extents_attr = + tsk_fs_attrlist_get(hfs->extents_file->meta->attr, + TSK_FS_ATTR_TYPE_DEFAULT); + if (!hfs->extents_attr) { + tsk_error_errstr2_concat + ("" - Default Attribute not found in Extents File""); + return 1; + } + + cnt = tsk_fs_attr_read(hfs->extents_attr, 14, + (char *) &(hfs->extents_header), + sizeof(hfs_btree_header_record), 0); + if (cnt != sizeof(hfs_btree_header_record)) { + if (cnt >= 0) { + tsk_error_reset(); + tsk_error_set_errno(TSK_ERR_FS_READ); + } + tsk_error_set_errstr2 + (""hfs_ext_find_extent_record_attr: Error reading header""); + return 1; + } + } + + nodesize = tsk_getu16(fs->endian, hfs->extents_header.nodesize); + if ((node = (char *) tsk_malloc(nodesize)) == NULL) { + return 1; + } + + /* start at root node */ + cur_node = tsk_getu32(fs->endian, hfs->extents_header.rootNode); + + /* if the root node is zero, then the extents btree is empty */ + /* if no files have overflow extents, the Extents B-tree still + exists on disk, but is an empty B-tree containing only + the header node */ + if (cur_node == 0) { + if (tsk_verbose) + tsk_fprintf(stderr, ""hfs_ext_find_extent_record: "" + ""empty extents btree\n""); + free(node); + return 0; + } + + if (tsk_verbose) + tsk_fprintf(stderr, ""hfs_ext_find_extent_record: starting at "" + ""root node %"" PRIu32 ""; nodesize = %"" + PRIu16 ""\n"", cur_node, nodesize); + + /* Recurse down to the needed leaf nodes and then go forward */ + is_done = 0; + while (is_done == 0) { + TSK_OFF_T cur_off; /* start address of cur_node */ + uint16_t num_rec; /* number of records in this node */ + ssize_t cnt; + hfs_btree_node *node_desc; + + if (cur_node > tsk_getu32(fs->endian, + hfs->extents_header.totalNodes)) { + tsk_error_set_errno(TSK_ERR_FS_GENFS); + tsk_error_set_errstr + (""hfs_ext_find_extent_record_attr: Node %d too large for file"", + cur_node); + free(node); + return 1; + } + + cur_off = (TSK_OFF_T)cur_node * nodesize; + if (tsk_verbose) + tsk_fprintf(stderr, + ""hfs_ext_find_extent_record: reading node %"" PRIu32 + "" at offset %"" PRIuOFF ""\n"", cur_node, cur_off); + + cnt = tsk_fs_attr_read(hfs->extents_attr, cur_off, + node, nodesize, 0); + if (cnt != nodesize) { + if (cnt >= 0) { + tsk_error_reset(); + tsk_error_set_errno(TSK_ERR_FS_READ); + } + tsk_error_set_errstr2 + (""hfs_ext_find_extent_record_attr: Error reading node %d at offset %"" + PRIuOFF, cur_node, cur_off); + free(node); + return 1; + } + + if (nodesize < sizeof(hfs_btree_node)) { + tsk_error_set_errno(TSK_ERR_FS_GENFS); + tsk_error_set_errstr + (""hfs_ext_find_extent_record_attr: Node size %d is too small to be valid"", nodesize); + free(node); + return 1; + } + node_desc = (hfs_btree_node *) node; + num_rec = tsk_getu16(fs->endian, node_desc->num_rec); + + if (num_rec == 0) { + tsk_error_set_errno(TSK_ERR_FS_GENFS); + tsk_error_set_errstr + (""hfs_ext_find_extent_record: zero records in node %"" + PRIu32, cur_node); + free(node); + return 1; + } + + + /* With an index node, find the record with the largest key that is smaller + * to or equal to cnid */ + if (node_desc->type == HFS_BT_NODE_TYPE_IDX) { + uint32_t next_node = 0; + int rec; + + if (tsk_verbose) + tsk_fprintf(stderr, + ""hfs_ext_find_extent_record: Index node %"" PRIu32 + "" @ %"" PRIu64 "" has %"" PRIu16 "" records\n"", cur_node, + cur_off, num_rec); + + for (rec = 0; rec < num_rec; ++rec) { + int cmp; + size_t rec_off; + hfs_btree_key_ext *key; + + rec_off = + tsk_getu16(fs->endian, + &node[nodesize - (rec + 1) * 2]); + if (rec_off + sizeof(hfs_btree_key_ext) > nodesize) { + tsk_error_set_errno(TSK_ERR_FS_GENFS); + tsk_error_set_errstr + (""hfs_ext_find_extent_record_attr: offset of record %d in index node %d too large (%d vs %"" + PRIu16 "")"", rec, cur_node, (int) rec_off, + nodesize); + free(node); + return 1; + } + key = (hfs_btree_key_ext *) & node[rec_off]; + + cmp = hfs_ext_compare_keys(hfs, cnid, key); + + if (tsk_verbose) + tsk_fprintf(stderr, + ""hfs_ext_find_extent_record: record %"" PRIu16 + "" ; keylen %"" PRIu16 "" (FileId: %"" PRIu32 + "", ForkType: %"" PRIu8 "", StartBlk: %"" PRIu32 + ""); compare: %d\n"", rec, tsk_getu16(fs->endian, + key->key_len), tsk_getu32(fs->endian, + key->file_id), key->fork_type, + tsk_getu32(fs->endian, key->start_block), cmp); + + /* save the info from this record unless it is bigger than cnid */ + if ((cmp <= 0) || (next_node == 0)) { + hfs_btree_index_record *idx_rec; + int keylen = + 2 + hfs_get_idxkeylen(hfs, tsk_getu16(fs->endian, + key->key_len), &(hfs->extents_header)); + if (rec_off + keylen > nodesize) { + tsk_error_set_errno(TSK_ERR_FS_GENFS); + tsk_error_set_errstr + (""hfs_ext_find_extent_record_attr: offset and keylenth of record %d in index node %d too large (%d vs %"" + PRIu16 "")"", rec, cur_node, + (int) rec_off + keylen, nodesize); + free(node); + return 1; + } + idx_rec = + (hfs_btree_index_record *) & node[rec_off + + keylen]; + next_node = tsk_getu32(fs->endian, idx_rec->childNode); + } + + if (cmp > 0) { + break; + } + } + + if (next_node == 0) { + if (tsk_verbose) + tsk_fprintf(stderr, + ""hfs_ext_find_extent_record_attr: did not find any keys for %d in index node %d"", + cnid, cur_node); + is_done = 1; + break; + } + cur_node = next_node; + } + + /* with a leaf, we process until we are past cnid. We move right too if we can */ + else if (node_desc->type == HFS_BT_NODE_TYPE_LEAF) { + int rec; + + if (tsk_verbose) + tsk_fprintf(stderr, + ""hfs_ext_find_extent_record: Leaf node %"" PRIu32 "" @ %"" + PRIu64 "" has %"" PRIu16 "" records\n"", cur_node, cur_off, + num_rec); + + for (rec = 0; rec < num_rec; ++rec) { + size_t rec_off; + hfs_btree_key_ext *key; + uint32_t rec_cnid; + hfs_extents *extents; + TSK_OFF_T ext_off = 0; + int keylen; + TSK_FS_ATTR_RUN *attr_run; + + rec_off = + tsk_getu16(fs->endian, + &node[nodesize - (rec + 1) * 2]); + if (rec_off > nodesize) { + tsk_error_set_errno(TSK_ERR_FS_GENFS); + tsk_error_set_errstr + (""hfs_ext_find_extent_record_attr: offset of record %d in leaf node %d too large (%d vs %"" + PRIu16 "")"", rec, cur_node, (int) rec_off, + nodesize); + free(node); + return 1; + } + key = (hfs_btree_key_ext *) & node[rec_off]; + + if (tsk_verbose) + tsk_fprintf(stderr, + ""hfs_ext_find_extent_record: record %"" PRIu16 + ""; keylen %"" PRIu16 "" (%"" PRIu32 + "", %"" PRIu8 "", %"" PRIu32 "")\n"", rec, + tsk_getu16(fs->endian, key->key_len), + tsk_getu32(fs->endian, key->file_id), + key->fork_type, tsk_getu32(fs->endian, + key->start_block)); + + rec_cnid = tsk_getu32(fs->endian, key->file_id); + + + if (rec_cnid < cnid) { + continue; + } + if (rec_cnid > cnid) { + is_done = 1; + break; + } + + + if (key->fork_type != desiredType) { + if (dataForkQ) { + is_done = 1; + break; + } + else + continue; + } + + keylen = 2 + tsk_getu16(fs->endian, key->key_len); + if (rec_off + keylen + sizeof(hfs_extents) > nodesize) { + tsk_error_set_errno(TSK_ERR_FS_GENFS); + tsk_error_set_errstr + (""hfs_ext_find_extent_record_attr: offset and keylenth of record %d in leaf node %d too large (%d vs %"" + PRIu16 "")"", rec, cur_node, (int) rec_off + keylen, + nodesize); + free(node); + return 1; + } + + ext_off = tsk_getu32(fs->endian, key->start_block); + + extents = (hfs_extents *) & node[rec_off + keylen]; + + attr_run = + hfs_extents_to_attr(fs, extents->extents, ext_off); + if ((attr_run == NULL) && (tsk_error_get_errno() != 0)) { + tsk_error_errstr2_concat + ("" - hfs_ext_find_extent_record_attr""); + free(node); + return 1; + } + + if (tsk_fs_attr_add_run(fs, a_attr, attr_run)) { + tsk_error_errstr2_concat + ("" - hfs_ext_find_extent_record_attr""); + free(node); + return 1; + } + } + cur_node = tsk_getu32(fs->endian, node_desc->flink); + if (cur_node == 0) { + is_done = 1; + break; + } + } + else { + tsk_error_set_errno(TSK_ERR_FS_GENFS); + tsk_error_set_errstr(""hfs_ext_find_extent_record: btree node %"" + PRIu32 "" (%"" PRIuOFF "") is neither index nor leaf (%"" PRIu8 + "")"", cur_node, cur_off, node_desc->type); + free(node); + return 1; + } + } + free(node); + return 0; +} +","@@ -956,11 +956,12 @@ hfs_cat_traverse(HFS_INFO * hfs, + key = (hfs_btree_key_cat *) & node[rec_off]; + + keylen = 2 + tsk_getu16(hfs->fs_info.endian, key->key_len); +- if ((keylen) > nodesize) { ++ ++ if (keylen >= nodesize - rec_off) { + tsk_error_set_errno(TSK_ERR_FS_GENFS); + tsk_error_set_errstr + (""hfs_cat_traverse: length of key %d in index node %d too large (%d vs %"" +- PRIu16 "")"", rec, cur_node, keylen, nodesize); ++ PRIu16 "")"", rec, cur_node, keylen, (nodesize - rec_off)); + free(node); + return 1; + }",3002,3333,4096 +7900,"static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) +{ + int64_t pos = avio_tell(pb); + char compressor_name[32] = { 0 }; + int avid = 0; + + int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422) + || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422) + || track->par->codec_id == AV_CODEC_ID_V308 + || track->par->codec_id == AV_CODEC_ID_V408 + || track->par->codec_id == AV_CODEC_ID_V410 + || track->par->codec_id == AV_CODEC_ID_V210); + + avio_wb32(pb, 0); /* size */ + if (mov->encryption_scheme != MOV_ENC_NONE) { + ffio_wfourcc(pb, ""encv""); + } else { + avio_wl32(pb, track->tag); // store it byteswapped + } + avio_wb32(pb, 0); /* Reserved */ + avio_wb16(pb, 0); /* Reserved */ + avio_wb16(pb, 1); /* Data-reference index */ + + if (uncompressed_ycbcr) { + avio_wb16(pb, 2); /* Codec stream version */ + } else { + avio_wb16(pb, 0); /* Codec stream version */ + } + avio_wb16(pb, 0); /* Codec stream revision (=0) */ + if (track->mode == MODE_MOV) { + ffio_wfourcc(pb, ""FFMP""); /* Vendor */ + if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) { + avio_wb32(pb, 0); /* Temporal Quality */ + avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/ + } else { + avio_wb32(pb, 0x200); /* Temporal Quality = normal */ + avio_wb32(pb, 0x200); /* Spatial Quality = normal */ + } + } else { + avio_wb32(pb, 0); /* Reserved */ + avio_wb32(pb, 0); /* Reserved */ + avio_wb32(pb, 0); /* Reserved */ + } + avio_wb16(pb, track->par->width); /* Video width */ + avio_wb16(pb, track->height); /* Video height */ + avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */ + avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */ + avio_wb32(pb, 0); /* Data size (= 0) */ + avio_wb16(pb, 1); /* Frame count (= 1) */ + + /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */ + find_compressor(compressor_name, 32, track); + avio_w8(pb, strlen(compressor_name)); + avio_write(pb, compressor_name, 31); + + if (track->mode == MODE_MOV && + (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210)) + avio_wb16(pb, 0x18); + else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample) + avio_wb16(pb, track->par->bits_per_coded_sample | + (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0)); + else + avio_wb16(pb, 0x18); /* Reserved */ + + if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) { + int pal_size = 1 << track->par->bits_per_coded_sample; + int i; + avio_wb16(pb, 0); /* Color table ID */ + avio_wb32(pb, 0); /* Color table seed */ + avio_wb16(pb, 0x8000); /* Color table flags */ + avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */ + for (i = 0; i < pal_size; i++) { + uint32_t rgb = track->palette[i]; + uint16_t r = (rgb >> 16) & 0xff; + uint16_t g = (rgb >> 8) & 0xff; + uint16_t b = rgb & 0xff; + avio_wb16(pb, 0); + avio_wb16(pb, (r << 8) | r); + avio_wb16(pb, (g << 8) | g); + avio_wb16(pb, (b << 8) | b); + } + } else + avio_wb16(pb, 0xffff); /* Reserved */ + + if (track->tag == MKTAG('m','p','4','v')) + mov_write_esds_tag(pb, track); + else if (track->par->codec_id == AV_CODEC_ID_H263) + mov_write_d263_tag(pb); + else if (track->par->codec_id == AV_CODEC_ID_AVUI || + track->par->codec_id == AV_CODEC_ID_SVQ3) { + mov_write_extradata_tag(pb, track); + avio_wb32(pb, 0); + } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) { + mov_write_avid_tag(pb, track); + avid = 1; + } else if (track->par->codec_id == AV_CODEC_ID_HEVC) + mov_write_hvcc_tag(pb, track); + else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) { + mov_write_avcc_tag(pb, track); + if (track->mode == MODE_IPOD) + mov_write_uuid_tag_ipod(pb); + } else if (track->par->codec_id == AV_CODEC_ID_VP9) { + mov_write_vpcc_tag(mov->fc, pb, track); + } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0) + mov_write_dvc1_tag(pb, track); + else if (track->par->codec_id == AV_CODEC_ID_VP6F || + track->par->codec_id == AV_CODEC_ID_VP6A) { + /* Don't write any potential extradata here - the cropping + * is signalled via the normal width/height fields. */ + } else if (track->par->codec_id == AV_CODEC_ID_R10K) { + if (track->par->codec_tag == MKTAG('R','1','0','k')) + mov_write_dpxe_tag(pb, track); + } else if (track->vos_len > 0) + mov_write_glbl_tag(pb, track); + + if (track->par->codec_id != AV_CODEC_ID_H264 && + track->par->codec_id != AV_CODEC_ID_MPEG4 && + track->par->codec_id != AV_CODEC_ID_DNXHD) { + int field_order = track->par->field_order; + +#if FF_API_LAVF_AVCTX + FF_DISABLE_DEPRECATION_WARNINGS + if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN) + field_order = track->st->codec->field_order; + FF_ENABLE_DEPRECATION_WARNINGS +#endif + + if (field_order != AV_FIELD_UNKNOWN) + mov_write_fiel_tag(pb, track, field_order); + } + + if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) { + if (track->mode == MODE_MOV) + mov_write_gama_tag(pb, track, mov->gamma); + else + av_log(mov->fc, AV_LOG_WARNING, ""Not writing 'gama' atom. Format is not MOV.\n""); + } + if (mov->flags & FF_MOV_FLAG_WRITE_COLR) { + if (track->mode == MODE_MOV || track->mode == MODE_MP4) + mov_write_colr_tag(pb, track); + else + av_log(mov->fc, AV_LOG_WARNING, ""Not writing 'colr' atom. Format is not MOV or MP4.\n""); + } + + if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) { + AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL); + AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL); + + if (stereo_3d) + mov_write_st3d_tag(pb, stereo_3d); + if (spherical_mapping) + mov_write_sv3d_tag(mov->fc, pb, spherical_mapping); + } + + if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) { + mov_write_pasp_tag(pb, track); + } + + if (uncompressed_ycbcr){ + mov_write_clap_tag(pb, track); + } + + if (mov->encryption_scheme != MOV_ENC_NONE) { + ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid); + } + + /* extra padding for avid stsd */ + /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */ + if (avid) + avio_wb32(pb, 0); + + return update_size(pb, pos); +} +",0,"static int mov_write_video_tag(AVIOContext *pb, MOVMuxContext *mov, MOVTrack *track) +{ + int64_t pos = avio_tell(pb); + char compressor_name[32] = { 0 }; + int avid = 0; + + int uncompressed_ycbcr = ((track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_UYVY422) + || (track->par->codec_id == AV_CODEC_ID_RAWVIDEO && track->par->format == AV_PIX_FMT_YUYV422) + || track->par->codec_id == AV_CODEC_ID_V308 + || track->par->codec_id == AV_CODEC_ID_V408 + || track->par->codec_id == AV_CODEC_ID_V410 + || track->par->codec_id == AV_CODEC_ID_V210); + + avio_wb32(pb, 0); /* size */ + if (mov->encryption_scheme != MOV_ENC_NONE) { + ffio_wfourcc(pb, ""encv""); + } else { + avio_wl32(pb, track->tag); // store it byteswapped + } + avio_wb32(pb, 0); /* Reserved */ + avio_wb16(pb, 0); /* Reserved */ + avio_wb16(pb, 1); /* Data-reference index */ + + if (uncompressed_ycbcr) { + avio_wb16(pb, 2); /* Codec stream version */ + } else { + avio_wb16(pb, 0); /* Codec stream version */ + } + avio_wb16(pb, 0); /* Codec stream revision (=0) */ + if (track->mode == MODE_MOV) { + ffio_wfourcc(pb, ""FFMP""); /* Vendor */ + if (track->par->codec_id == AV_CODEC_ID_RAWVIDEO || uncompressed_ycbcr) { + avio_wb32(pb, 0); /* Temporal Quality */ + avio_wb32(pb, 0x400); /* Spatial Quality = lossless*/ + } else { + avio_wb32(pb, 0x200); /* Temporal Quality = normal */ + avio_wb32(pb, 0x200); /* Spatial Quality = normal */ + } + } else { + avio_wb32(pb, 0); /* Reserved */ + avio_wb32(pb, 0); /* Reserved */ + avio_wb32(pb, 0); /* Reserved */ + } + avio_wb16(pb, track->par->width); /* Video width */ + avio_wb16(pb, track->height); /* Video height */ + avio_wb32(pb, 0x00480000); /* Horizontal resolution 72dpi */ + avio_wb32(pb, 0x00480000); /* Vertical resolution 72dpi */ + avio_wb32(pb, 0); /* Data size (= 0) */ + avio_wb16(pb, 1); /* Frame count (= 1) */ + + /* FIXME not sure, ISO 14496-1 draft where it shall be set to 0 */ + find_compressor(compressor_name, 32, track); + avio_w8(pb, strlen(compressor_name)); + avio_write(pb, compressor_name, 31); + + if (track->mode == MODE_MOV && + (track->par->codec_id == AV_CODEC_ID_V410 || track->par->codec_id == AV_CODEC_ID_V210)) + avio_wb16(pb, 0x18); + else if (track->mode == MODE_MOV && track->par->bits_per_coded_sample) + avio_wb16(pb, track->par->bits_per_coded_sample | + (track->par->format == AV_PIX_FMT_GRAY8 ? 0x20 : 0)); + else + avio_wb16(pb, 0x18); /* Reserved */ + + if (track->mode == MODE_MOV && track->par->format == AV_PIX_FMT_PAL8) { + int pal_size = 1 << track->par->bits_per_coded_sample; + int i; + avio_wb16(pb, 0); /* Color table ID */ + avio_wb32(pb, 0); /* Color table seed */ + avio_wb16(pb, 0x8000); /* Color table flags */ + avio_wb16(pb, pal_size - 1); /* Color table size (zero-relative) */ + for (i = 0; i < pal_size; i++) { + uint32_t rgb = track->palette[i]; + uint16_t r = (rgb >> 16) & 0xff; + uint16_t g = (rgb >> 8) & 0xff; + uint16_t b = rgb & 0xff; + avio_wb16(pb, 0); + avio_wb16(pb, (r << 8) | r); + avio_wb16(pb, (g << 8) | g); + avio_wb16(pb, (b << 8) | b); + } + } else + avio_wb16(pb, 0xffff); /* Reserved */ + + if (track->tag == MKTAG('m','p','4','v')) + mov_write_esds_tag(pb, track); + else if (track->par->codec_id == AV_CODEC_ID_H263) + mov_write_d263_tag(pb); + else if (track->par->codec_id == AV_CODEC_ID_AVUI || + track->par->codec_id == AV_CODEC_ID_SVQ3) { + mov_write_extradata_tag(pb, track); + avio_wb32(pb, 0); + } else if (track->par->codec_id == AV_CODEC_ID_DNXHD) { + mov_write_avid_tag(pb, track); + avid = 1; + } else if (track->par->codec_id == AV_CODEC_ID_HEVC) + mov_write_hvcc_tag(pb, track); + else if (track->par->codec_id == AV_CODEC_ID_H264 && !TAG_IS_AVCI(track->tag)) { + mov_write_avcc_tag(pb, track); + if (track->mode == MODE_IPOD) + mov_write_uuid_tag_ipod(pb); + } else if (track->par->codec_id == AV_CODEC_ID_VP9) { + mov_write_vpcc_tag(mov->fc, pb, track); + } else if (track->par->codec_id == AV_CODEC_ID_VC1 && track->vos_len > 0) + mov_write_dvc1_tag(pb, track); + else if (track->par->codec_id == AV_CODEC_ID_VP6F || + track->par->codec_id == AV_CODEC_ID_VP6A) { + /* Don't write any potential extradata here - the cropping + * is signalled via the normal width/height fields. */ + } else if (track->par->codec_id == AV_CODEC_ID_R10K) { + if (track->par->codec_tag == MKTAG('R','1','0','k')) + mov_write_dpxe_tag(pb, track); + } else if (track->vos_len > 0) + mov_write_glbl_tag(pb, track); + + if (track->par->codec_id != AV_CODEC_ID_H264 && + track->par->codec_id != AV_CODEC_ID_MPEG4 && + track->par->codec_id != AV_CODEC_ID_DNXHD) { + int field_order = track->par->field_order; + +#if FF_API_LAVF_AVCTX + FF_DISABLE_DEPRECATION_WARNINGS + if (field_order != track->st->codec->field_order && track->st->codec->field_order != AV_FIELD_UNKNOWN) + field_order = track->st->codec->field_order; + FF_ENABLE_DEPRECATION_WARNINGS +#endif + + if (field_order != AV_FIELD_UNKNOWN) + mov_write_fiel_tag(pb, track, field_order); + } + + if (mov->flags & FF_MOV_FLAG_WRITE_GAMA) { + if (track->mode == MODE_MOV) + mov_write_gama_tag(pb, track, mov->gamma); + else + av_log(mov->fc, AV_LOG_WARNING, ""Not writing 'gama' atom. Format is not MOV.\n""); + } + if (mov->flags & FF_MOV_FLAG_WRITE_COLR) { + if (track->mode == MODE_MOV || track->mode == MODE_MP4) + mov_write_colr_tag(pb, track); + else + av_log(mov->fc, AV_LOG_WARNING, ""Not writing 'colr' atom. Format is not MOV or MP4.\n""); + } + + if (track->mode == MODE_MP4 && mov->fc->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL) { + AVStereo3D* stereo_3d = (AVStereo3D*) av_stream_get_side_data(track->st, AV_PKT_DATA_STEREO3D, NULL); + AVSphericalMapping* spherical_mapping = (AVSphericalMapping*)av_stream_get_side_data(track->st, AV_PKT_DATA_SPHERICAL, NULL); + + if (stereo_3d) + mov_write_st3d_tag(pb, stereo_3d); + if (spherical_mapping) + mov_write_sv3d_tag(mov->fc, pb, spherical_mapping); + } + + if (track->par->sample_aspect_ratio.den && track->par->sample_aspect_ratio.num) { + mov_write_pasp_tag(pb, track); + } + + if (uncompressed_ycbcr){ + mov_write_clap_tag(pb, track); + } + + if (mov->encryption_scheme != MOV_ENC_NONE) { + ff_mov_cenc_write_sinf_tag(track, pb, mov->encryption_kid); + } + + /* extra padding for avid stsd */ + /* https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html#//apple_ref/doc/uid/TP40000939-CH204-61112 */ + if (avid) + avio_wb32(pb, 0); + + return update_size(pb, pos); +} +","@@ -1022,7 +1022,7 @@ static int mov_write_audio_tag(AVFormatContext *s, AVIOContext *pb, MOVMuxContex + uint32_t tag = track->tag; + + if (track->mode == MODE_MOV) { +- if (track->timescale > UINT16_MAX) { ++ if (track->timescale > UINT16_MAX || !track->par->channels) { + if (mov_get_lpcm_flags(track->par->codec_id)) + tag = AV_RL32(""lpcm""); + version = 2;",2301,2632,4096 +18790,"void btm_sec_pin_code_request (UINT8 *p_bda) +{ + + tBTM_SEC_DEV_REC *p_dev_rec; + tBTM_CB *p_cb = &btm_cb; + +#ifdef PORCHE_PAIRING_CONFLICT + UINT8 default_pin_code_len = 4; + PIN_CODE default_pin_code = {0x30, 0x30, 0x30, 0x30}; +#endif + BTM_TRACE_EVENT (""btm_sec_pin_code_request() State: %s, BDA:%04x%08x"", + btm_pair_state_descr(btm_cb.pairing_state), + (p_bda[0]<<8)+p_bda[1], (p_bda[2]<<24)+(p_bda[3]<<16)+(p_bda[4]<<8)+p_bda[5] ); + + if (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) + { + + if ( (memcmp (p_bda, btm_cb.pairing_bda, BD_ADDR_LEN) == 0) && + (btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_AUTH_COMPLETE) ) + { + /* fake this out - porshe carkit issue - */ + if(! btm_cb.pin_code_len_saved) + { + btsnd_hcic_pin_code_neg_reply (p_bda); + return; + } + else + { + btsnd_hcic_pin_code_req_reply (p_bda, btm_cb.pin_code_len_saved, p_cb->pin_code); + return; + } + } + else if ((btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_PIN_REQ) + || memcmp (p_bda, btm_cb.pairing_bda, BD_ADDR_LEN) != 0) + { + + BTM_TRACE_WARNING (""btm_sec_pin_code_request() rejected - state: %s"", + btm_pair_state_descr(btm_cb.pairing_state)); + +#ifdef PORCHE_PAIRING_CONFLICT + /* reply pin code again due to counter in_rand when local initiates pairing */ + BTM_TRACE_EVENT (""btm_sec_pin_code_request from remote dev. for local initiated pairing""); + if(! btm_cb.pin_code_len_saved) + { + btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); + btsnd_hcic_pin_code_req_reply (p_bda, default_pin_code_len, default_pin_code); + } + else + { + btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); + btsnd_hcic_pin_code_req_reply (p_bda, btm_cb.pin_code_len_saved, p_cb->pin_code); + } +#else + btsnd_hcic_pin_code_neg_reply (p_bda); +#endif + return; + } + } + + p_dev_rec = btm_find_or_alloc_dev (p_bda); + /* received PIN code request. must be non-sm4 */ + p_dev_rec->sm4 = BTM_SM4_KNOWN; + + if (btm_cb.pairing_state == BTM_PAIR_STATE_IDLE) + { + memcpy (btm_cb.pairing_bda, p_bda, BD_ADDR_LEN); + + btm_cb.pairing_flags = BTM_PAIR_FLAGS_PEER_STARTED_DD; + /* Make sure we reset the trusted mask to help against attacks */ + BTM_SEC_CLR_TRUSTED_DEVICE(p_dev_rec->trusted_mask); + } + + if (!p_cb->pairing_disabled && (p_cb->cfg.pin_type == HCI_PIN_TYPE_FIXED)) + { + BTM_TRACE_EVENT (""btm_sec_pin_code_request fixed pin replying""); + btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); + btsnd_hcic_pin_code_req_reply (p_bda, p_cb->cfg.pin_code_len, p_cb->cfg.pin_code); + return; + } + + /* Use the connecting device's CoD for the connection */ + if ( (!memcmp (p_bda, p_cb->connecting_bda, BD_ADDR_LEN)) + && (p_cb->connecting_dc[0] || p_cb->connecting_dc[1] || p_cb->connecting_dc[2]) ) + memcpy (p_dev_rec->dev_class, p_cb->connecting_dc, DEV_CLASS_LEN); + + /* We could have started connection after asking user for the PIN code */ + if (btm_cb.pin_code_len != 0) + { + + BTM_TRACE_EVENT (""btm_sec_pin_code_request bonding sending reply""); + btsnd_hcic_pin_code_req_reply (p_bda, btm_cb.pin_code_len, p_cb->pin_code); + +#ifdef PORCHE_PAIRING_CONFLICT + btm_cb.pin_code_len_saved = btm_cb.pin_code_len; +#endif + /* Mark that we forwarded received from the user PIN code */ + btm_cb.pin_code_len = 0; + + /* We can change mode back right away, that other connection being established */ + /* is not forced to be secure - found a FW issue, so we can not do this + btm_restore_mode(); */ + + btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); + } + + /* If pairing disabled OR (no PIN callback and not bonding) */ + /* OR we could not allocate entry in the database reject pairing request */ + else if (p_cb->pairing_disabled + || (p_cb->api.p_pin_callback == NULL) + + /* OR Microsoft keyboard can for some reason try to establish connection */ + /* the only thing we can do here is to shut it up. Normally we will be originator */ + /* for keyboard bonding */ + || (!p_dev_rec->is_originator + && ((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) == BTM_COD_MAJOR_PERIPHERAL) + && (p_dev_rec->dev_class[2] & BTM_COD_MINOR_KEYBOARD)) ) + { + BTM_TRACE_WARNING(""btm_sec_pin_code_request(): Pairing disabled:%d; PIN callback:%x, Dev Rec:%x!"", + p_cb->pairing_disabled, p_cb->api.p_pin_callback, p_dev_rec); + + btsnd_hcic_pin_code_neg_reply (p_bda); + } + + /* Notify upper layer of PIN request and start expiration timer */ + else + { + btm_cb.pin_code_len_saved = 0; + btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_LOCAL_PIN); + /* Pin code request can not come at the same time as connection request */ + memcpy (p_cb->connecting_bda, p_bda, BD_ADDR_LEN); + memcpy (p_cb->connecting_dc, p_dev_rec->dev_class, DEV_CLASS_LEN); + + /* Check if the name is known */ + /* Even if name is not known we might not be able to get one */ + /* this is the case when we are already getting something from the */ + /* device, so HCI level is flow controlled */ + /* Also cannot send remote name request while paging, i.e. connection is not completed */ + if (p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN) + { + BTM_TRACE_EVENT (""btm_sec_pin_code_request going for callback""); + + btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD; + if (p_cb->api.p_pin_callback) + (*p_cb->api.p_pin_callback) (p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name); + } + else + { + BTM_TRACE_EVENT (""btm_sec_pin_code_request going for remote name""); + + /* We received PIN code request for the device with unknown name */ + /* it is not user friendly just to ask for the PIN without name */ + /* try to get name at first */ + if (!btsnd_hcic_rmt_name_req (p_dev_rec->bd_addr, + HCI_PAGE_SCAN_REP_MODE_R1, + HCI_MANDATARY_PAGE_SCAN_MODE, 0)) + { + p_dev_rec->sec_flags |= BTM_SEC_NAME_KNOWN; + p_dev_rec->sec_bd_name[0] = 'f'; + p_dev_rec->sec_bd_name[1] = '0'; + BTM_TRACE_ERROR (""can not send rmt_name_req?? fake a name and call callback""); + + btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD; + if (p_cb->api.p_pin_callback) + (*p_cb->api.p_pin_callback) (p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name); + } + } + } + + return; +} +",1,"void btm_sec_pin_code_request (UINT8 *p_bda) +{ + + tBTM_SEC_DEV_REC *p_dev_rec; + tBTM_CB *p_cb = &btm_cb; + + BTM_TRACE_EVENT (""btm_sec_pin_code_request() State: %s, BDA:%04x%08x"", + btm_pair_state_descr(btm_cb.pairing_state), + (p_bda[0]<<8)+p_bda[1], (p_bda[2]<<24)+(p_bda[3]<<16)+(p_bda[4]<<8)+p_bda[5] ); + + if (btm_cb.pairing_state != BTM_PAIR_STATE_IDLE) + { + + if ( (memcmp (p_bda, btm_cb.pairing_bda, BD_ADDR_LEN) == 0) && + (btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_AUTH_COMPLETE) ) + { + btsnd_hcic_pin_code_neg_reply (p_bda); + return; + } + else if ((btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_PIN_REQ) + || memcmp (p_bda, btm_cb.pairing_bda, BD_ADDR_LEN) != 0) + { + + BTM_TRACE_WARNING (""btm_sec_pin_code_request() rejected - state: %s"", + btm_pair_state_descr(btm_cb.pairing_state)); + + btsnd_hcic_pin_code_neg_reply (p_bda); + return; + } + } + + p_dev_rec = btm_find_or_alloc_dev (p_bda); + /* received PIN code request. must be non-sm4 */ + p_dev_rec->sm4 = BTM_SM4_KNOWN; + + if (btm_cb.pairing_state == BTM_PAIR_STATE_IDLE) + { + memcpy (btm_cb.pairing_bda, p_bda, BD_ADDR_LEN); + + btm_cb.pairing_flags = BTM_PAIR_FLAGS_PEER_STARTED_DD; + /* Make sure we reset the trusted mask to help against attacks */ + BTM_SEC_CLR_TRUSTED_DEVICE(p_dev_rec->trusted_mask); + } + + if (!p_cb->pairing_disabled && (p_cb->cfg.pin_type == HCI_PIN_TYPE_FIXED)) + { + BTM_TRACE_EVENT (""btm_sec_pin_code_request fixed pin replying""); + btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); + btsnd_hcic_pin_code_req_reply (p_bda, p_cb->cfg.pin_code_len, p_cb->cfg.pin_code); + return; + } + + /* Use the connecting device's CoD for the connection */ + if ( (!memcmp (p_bda, p_cb->connecting_bda, BD_ADDR_LEN)) + && (p_cb->connecting_dc[0] || p_cb->connecting_dc[1] || p_cb->connecting_dc[2]) ) + memcpy (p_dev_rec->dev_class, p_cb->connecting_dc, DEV_CLASS_LEN); + + /* We could have started connection after asking user for the PIN code */ + if (btm_cb.pin_code_len != 0) + { + + BTM_TRACE_EVENT (""btm_sec_pin_code_request bonding sending reply""); + btsnd_hcic_pin_code_req_reply (p_bda, btm_cb.pin_code_len, p_cb->pin_code); + + /* Mark that we forwarded received from the user PIN code */ + btm_cb.pin_code_len = 0; + + /* We can change mode back right away, that other connection being established */ + /* is not forced to be secure - found a FW issue, so we can not do this + btm_restore_mode(); */ + + btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); + } + + /* If pairing disabled OR (no PIN callback and not bonding) */ + /* OR we could not allocate entry in the database reject pairing request */ + else if (p_cb->pairing_disabled + || (p_cb->api.p_pin_callback == NULL) + + /* OR Microsoft keyboard can for some reason try to establish connection */ + /* the only thing we can do here is to shut it up. Normally we will be originator */ + /* for keyboard bonding */ + || (!p_dev_rec->is_originator + && ((p_dev_rec->dev_class[1] & BTM_COD_MAJOR_CLASS_MASK) == BTM_COD_MAJOR_PERIPHERAL) + && (p_dev_rec->dev_class[2] & BTM_COD_MINOR_KEYBOARD)) ) + { + BTM_TRACE_WARNING(""btm_sec_pin_code_request(): Pairing disabled:%d; PIN callback:%x, Dev Rec:%x!"", + p_cb->pairing_disabled, p_cb->api.p_pin_callback, p_dev_rec); + + btsnd_hcic_pin_code_neg_reply (p_bda); + } + + /* Notify upper layer of PIN request and start expiration timer */ + else + { + btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_LOCAL_PIN); + /* Pin code request can not come at the same time as connection request */ + memcpy (p_cb->connecting_bda, p_bda, BD_ADDR_LEN); + memcpy (p_cb->connecting_dc, p_dev_rec->dev_class, DEV_CLASS_LEN); + + /* Check if the name is known */ + /* Even if name is not known we might not be able to get one */ + /* this is the case when we are already getting something from the */ + /* device, so HCI level is flow controlled */ + /* Also cannot send remote name request while paging, i.e. connection is not completed */ + if (p_dev_rec->sec_flags & BTM_SEC_NAME_KNOWN) + { + BTM_TRACE_EVENT (""btm_sec_pin_code_request going for callback""); + + btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD; + if (p_cb->api.p_pin_callback) + (*p_cb->api.p_pin_callback) (p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name); + } + else + { + BTM_TRACE_EVENT (""btm_sec_pin_code_request going for remote name""); + + /* We received PIN code request for the device with unknown name */ + /* it is not user friendly just to ask for the PIN without name */ + /* try to get name at first */ + if (!btsnd_hcic_rmt_name_req (p_dev_rec->bd_addr, + HCI_PAGE_SCAN_REP_MODE_R1, + HCI_MANDATARY_PAGE_SCAN_MODE, 0)) + { + p_dev_rec->sec_flags |= BTM_SEC_NAME_KNOWN; + p_dev_rec->sec_bd_name[0] = 'f'; + p_dev_rec->sec_bd_name[1] = '0'; + BTM_TRACE_ERROR (""can not send rmt_name_req?? fake a name and call callback""); + + btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD; + if (p_cb->api.p_pin_callback) + (*p_cb->api.p_pin_callback) (p_bda, p_dev_rec->dev_class, p_dev_rec->sec_bd_name); + } + } + } + + return; +} +","@@ -1074,13 +1074,6 @@ + + btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); + btm_cb.acl_disc_reason = HCI_SUCCESS; + +-#ifdef PORCHE_PAIRING_CONFLICT +- BTM_TRACE_EVENT(""BTM_PINCodeReply(): Saving pin_len: %d btm_cb.pin_code_len: %d"", pin_len, btm_cb.pin_code_len); +- /* if this was not pre-fetched, save the PIN */ +- if (btm_cb.pin_code_len == 0) +- memcpy (btm_cb.pin_code, p_pin, pin_len); +- btm_cb.pin_code_len_saved = pin_len; +-#endif + btsnd_hcic_pin_code_req_reply (bd_addr, pin_len, p_pin); + } + +@@ -5057,10 +5050,6 @@ + + tBTM_SEC_DEV_REC *p_dev_rec; + tBTM_CB *p_cb = &btm_cb; + +-#ifdef PORCHE_PAIRING_CONFLICT +- UINT8 default_pin_code_len = 4; +- PIN_CODE default_pin_code = {0x30, 0x30, 0x30, 0x30}; +-#endif + BTM_TRACE_EVENT (""btm_sec_pin_code_request() State: %s, BDA:%04x%08x"", + btm_pair_state_descr(btm_cb.pairing_state), + (p_bda[0]<<8)+p_bda[1], (p_bda[2]<<24)+(p_bda[3]<<16)+(p_bda[4]<<8)+p_bda[5] ); +@@ -5070,18 +5059,8 @@ + + if ( (memcmp (p_bda, btm_cb.pairing_bda, BD_ADDR_LEN) == 0) && + (btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_AUTH_COMPLETE) ) + { +- /* fake this out - porshe carkit issue - */ +-// btm_cb.pairing_state = BTM_PAIR_STATE_IDLE; +- if(! btm_cb.pin_code_len_saved) +- { +- btsnd_hcic_pin_code_neg_reply (p_bda); +- return; +- } +- else +- { +- btsnd_hcic_pin_code_req_reply (p_bda, btm_cb.pin_code_len_saved, p_cb->pin_code); +- return; +- } ++ btsnd_hcic_pin_code_neg_reply (p_bda); ++ return; + } + else if ((btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_PIN_REQ) + || memcmp (p_bda, btm_cb.pairing_bda, BD_ADDR_LEN) != 0) +@@ -5089,22 +5068,7 @@ + + BTM_TRACE_WARNING (""btm_sec_pin_code_request() rejected - state: %s"", + btm_pair_state_descr(btm_cb.pairing_state)); + +-#ifdef PORCHE_PAIRING_CONFLICT +- /* reply pin code again due to counter in_rand when local initiates pairing */ +- BTM_TRACE_EVENT (""btm_sec_pin_code_request from remote dev. for local initiated pairing""); +- if(! btm_cb.pin_code_len_saved) +- { +- btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); +- btsnd_hcic_pin_code_req_reply (p_bda, default_pin_code_len, default_pin_code); +- } +- else +- { +- btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); +- btsnd_hcic_pin_code_req_reply (p_bda, btm_cb.pin_code_len_saved, p_cb->pin_code); +- } +-#else + btsnd_hcic_pin_code_neg_reply (p_bda); +-#endif + return; + } + } +@@ -5141,10 +5105,6 @@ + + BTM_TRACE_EVENT (""btm_sec_pin_code_request bonding sending reply""); + btsnd_hcic_pin_code_req_reply (p_bda, btm_cb.pin_code_len, p_cb->pin_code); + +-#ifdef PORCHE_PAIRING_CONFLICT +- btm_cb.pin_code_len_saved = btm_cb.pin_code_len; +-#endif +- + /* Mark that we forwarded received from the user PIN code */ + btm_cb.pin_code_len = 0; + +@@ -5175,7 +5135,6 @@ + + /* Notify upper layer of PIN request and start expiration timer */ + else + { +- btm_cb.pin_code_len_saved = 0; + btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_LOCAL_PIN); + /* Pin code request can not come at the same time as connection request */ + memcpy (p_cb->connecting_bda, p_bda, BD_ADDR_LEN); +",1791,2122,4096 +11457,"bool TestingAutomationProvider::OnMessageReceived( + const IPC::Message& message) { + bool handled = true; + bool deserialize_success = true; + IPC_BEGIN_MESSAGE_MAP_EX(TestingAutomationProvider, + message, + deserialize_success) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_CloseBrowser, CloseBrowser) + IPC_MESSAGE_HANDLER(AutomationMsg_CloseBrowserRequestAsync, + CloseBrowserAsync) + IPC_MESSAGE_HANDLER(AutomationMsg_ActivateTab, ActivateTab) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_AppendTab, AppendTab) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_AppendBackgroundTab, + AppendBackgroundTab) + IPC_MESSAGE_HANDLER(AutomationMsg_ActiveTabIndex, GetActiveTabIndex) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_CloseTab, CloseTab) + IPC_MESSAGE_HANDLER(AutomationMsg_GetCookies, GetCookies) + IPC_MESSAGE_HANDLER(AutomationMsg_SetCookie, SetCookie) + IPC_MESSAGE_HANDLER(AutomationMsg_DeleteCookie, DeleteCookie) + IPC_MESSAGE_HANDLER(AutomationMsg_ShowCollectedCookiesDialog, + ShowCollectedCookiesDialog) + IPC_MESSAGE_HANDLER_DELAY_REPLY( + AutomationMsg_NavigateToURLBlockUntilNavigationsComplete, + NavigateToURLBlockUntilNavigationsComplete) + IPC_MESSAGE_HANDLER(AutomationMsg_NavigationAsync, NavigationAsync) + IPC_MESSAGE_HANDLER(AutomationMsg_NavigationAsyncWithDisposition, + NavigationAsyncWithDisposition) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_Reload, Reload) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_SetAuth, SetAuth) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_CancelAuth, CancelAuth) + IPC_MESSAGE_HANDLER(AutomationMsg_NeedsAuth, NeedsAuth) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_RedirectsFrom, + GetRedirectsFrom) + IPC_MESSAGE_HANDLER(AutomationMsg_BrowserWindowCount, GetBrowserWindowCount) + IPC_MESSAGE_HANDLER(AutomationMsg_NormalBrowserWindowCount, + GetNormalBrowserWindowCount) + IPC_MESSAGE_HANDLER(AutomationMsg_BrowserWindow, GetBrowserWindow) + IPC_MESSAGE_HANDLER(AutomationMsg_GetBrowserLocale, GetBrowserLocale) + IPC_MESSAGE_HANDLER(AutomationMsg_LastActiveBrowserWindow, + GetLastActiveBrowserWindow) + IPC_MESSAGE_HANDLER(AutomationMsg_ActiveWindow, GetActiveWindow) + IPC_MESSAGE_HANDLER(AutomationMsg_FindTabbedBrowserWindow, + FindTabbedBrowserWindow) + IPC_MESSAGE_HANDLER(AutomationMsg_IsWindowActive, IsWindowActive) + IPC_MESSAGE_HANDLER(AutomationMsg_ActivateWindow, ActivateWindow) + IPC_MESSAGE_HANDLER(AutomationMsg_IsWindowMaximized, IsWindowMaximized) + IPC_MESSAGE_HANDLER(AutomationMsg_WindowExecuteCommandAsync, + ExecuteBrowserCommandAsync) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_WindowExecuteCommand, + ExecuteBrowserCommand) + IPC_MESSAGE_HANDLER(AutomationMsg_TerminateSession, TerminateSession) + IPC_MESSAGE_HANDLER(AutomationMsg_WindowViewBounds, WindowGetViewBounds) + IPC_MESSAGE_HANDLER(AutomationMsg_GetWindowBounds, GetWindowBounds) + IPC_MESSAGE_HANDLER(AutomationMsg_SetWindowBounds, SetWindowBounds) + IPC_MESSAGE_HANDLER(AutomationMsg_SetWindowVisible, SetWindowVisible) + IPC_MESSAGE_HANDLER(AutomationMsg_WindowClick, WindowSimulateClick) + IPC_MESSAGE_HANDLER(AutomationMsg_WindowMouseMove, WindowSimulateMouseMove) + IPC_MESSAGE_HANDLER(AutomationMsg_WindowKeyPress, WindowSimulateKeyPress) + IPC_MESSAGE_HANDLER(AutomationMsg_TabCount, GetTabCount) + IPC_MESSAGE_HANDLER(AutomationMsg_Type, GetType) + IPC_MESSAGE_HANDLER(AutomationMsg_IsBrowserInApplicationMode, + IsBrowserInApplicationMode) + IPC_MESSAGE_HANDLER(AutomationMsg_Tab, GetTab) + IPC_MESSAGE_HANDLER(AutomationMsg_TabProcessID, GetTabProcessID) + IPC_MESSAGE_HANDLER(AutomationMsg_TabTitle, GetTabTitle) + IPC_MESSAGE_HANDLER(AutomationMsg_TabIndex, GetTabIndex) + IPC_MESSAGE_HANDLER(AutomationMsg_TabURL, GetTabURL) + IPC_MESSAGE_HANDLER(AutomationMsg_ShelfVisibility, GetShelfVisibility) + IPC_MESSAGE_HANDLER(AutomationMsg_IsFullscreen, IsFullscreen) + IPC_MESSAGE_HANDLER(AutomationMsg_IsFullscreenBubbleVisible, + GetFullscreenBubbleVisibility) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_DomOperation, + ExecuteJavascript) + IPC_MESSAGE_HANDLER(AutomationMsg_ConstrainedWindowCount, + GetConstrainedWindowCount) +#if defined(TOOLKIT_VIEWS) + IPC_MESSAGE_HANDLER(AutomationMsg_GetFocusedViewID, GetFocusedViewID) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_WaitForFocusedViewIDToChange, + WaitForFocusedViewIDToChange) + IPC_MESSAGE_HANDLER(AutomationMsg_StartTrackingPopupMenus, + StartTrackingPopupMenus) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_WaitForPopupMenuToOpen, + WaitForPopupMenuToOpen) +#endif // defined(TOOLKIT_VIEWS) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_InspectElement, + HandleInspectElementRequest) + IPC_MESSAGE_HANDLER(AutomationMsg_DownloadDirectory, GetDownloadDirectory) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_OpenNewBrowserWindowOfType, + OpenNewBrowserWindowOfType) + IPC_MESSAGE_HANDLER(AutomationMsg_WindowForBrowser, GetWindowForBrowser) + IPC_MESSAGE_HANDLER(AutomationMsg_BrowserForWindow, GetBrowserForWindow) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_ShowInterstitialPage, + ShowInterstitialPage) + IPC_MESSAGE_HANDLER(AutomationMsg_HideInterstitialPage, + HideInterstitialPage) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_WaitForTabToBeRestored, + WaitForTabToBeRestored) + IPC_MESSAGE_HANDLER(AutomationMsg_GetSecurityState, GetSecurityState) + IPC_MESSAGE_HANDLER(AutomationMsg_GetPageType, GetPageType) + IPC_MESSAGE_HANDLER(AutomationMsg_GetMetricEventDuration, + GetMetricEventDuration) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_ActionOnSSLBlockingPage, + ActionOnSSLBlockingPage) + IPC_MESSAGE_HANDLER(AutomationMsg_BringBrowserToFront, BringBrowserToFront) + IPC_MESSAGE_HANDLER(AutomationMsg_IsMenuCommandEnabled, + IsMenuCommandEnabled) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_PrintNow, PrintNow) + IPC_MESSAGE_HANDLER(AutomationMsg_SavePage, SavePage) + IPC_MESSAGE_HANDLER(AutomationMsg_OpenFindInPage, + HandleOpenFindInPageRequest) + IPC_MESSAGE_HANDLER(AutomationMsg_FindWindowVisibility, + GetFindWindowVisibility) + IPC_MESSAGE_HANDLER(AutomationMsg_FindWindowLocation, + HandleFindWindowLocationRequest) + IPC_MESSAGE_HANDLER(AutomationMsg_BookmarkBarVisibility, + GetBookmarkBarVisibility) + IPC_MESSAGE_HANDLER(AutomationMsg_GetBookmarksAsJSON, + GetBookmarksAsJSON) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_WaitForBookmarkModelToLoad, + WaitForBookmarkModelToLoad) + IPC_MESSAGE_HANDLER(AutomationMsg_AddBookmarkGroup, + AddBookmarkGroup) + IPC_MESSAGE_HANDLER(AutomationMsg_AddBookmarkURL, + AddBookmarkURL) + IPC_MESSAGE_HANDLER(AutomationMsg_ReparentBookmark, + ReparentBookmark) + IPC_MESSAGE_HANDLER(AutomationMsg_SetBookmarkTitle, + SetBookmarkTitle) + IPC_MESSAGE_HANDLER(AutomationMsg_SetBookmarkURL, + SetBookmarkURL) + IPC_MESSAGE_HANDLER(AutomationMsg_RemoveBookmark, + RemoveBookmark) + IPC_MESSAGE_HANDLER(AutomationMsg_GetInfoBarCount, GetInfoBarCount) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_ClickInfoBarAccept, + ClickInfoBarAccept) + IPC_MESSAGE_HANDLER(AutomationMsg_GetLastNavigationTime, + GetLastNavigationTime) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_WaitForNavigation, + WaitForNavigation) + IPC_MESSAGE_HANDLER(AutomationMsg_SetIntPreference, SetIntPreference) + IPC_MESSAGE_HANDLER(AutomationMsg_ShowingAppModalDialog, + GetShowingAppModalDialog) + IPC_MESSAGE_HANDLER(AutomationMsg_ClickAppModalDialogButton, + ClickAppModalDialogButton) + IPC_MESSAGE_HANDLER(AutomationMsg_SetStringPreference, SetStringPreference) + IPC_MESSAGE_HANDLER(AutomationMsg_GetBooleanPreference, + GetBooleanPreference) + IPC_MESSAGE_HANDLER(AutomationMsg_SetBooleanPreference, + SetBooleanPreference) + IPC_MESSAGE_HANDLER_DELAY_REPLY( + AutomationMsg_WaitForBrowserWindowCountToBecome, + WaitForBrowserWindowCountToBecome) + IPC_MESSAGE_HANDLER_DELAY_REPLY( + AutomationMsg_WaitForAppModalDialogToBeShown, + WaitForAppModalDialogToBeShown) + IPC_MESSAGE_HANDLER_DELAY_REPLY( + AutomationMsg_GoBackBlockUntilNavigationsComplete, + GoBackBlockUntilNavigationsComplete) + IPC_MESSAGE_HANDLER_DELAY_REPLY( + AutomationMsg_GoForwardBlockUntilNavigationsComplete, + GoForwardBlockUntilNavigationsComplete) + IPC_MESSAGE_HANDLER(AutomationMsg_SavePackageShouldPromptUser, + SavePackageShouldPromptUser) + IPC_MESSAGE_HANDLER(AutomationMsg_WindowTitle, GetWindowTitle) + IPC_MESSAGE_HANDLER(AutomationMsg_SetShelfVisibility, SetShelfVisibility) + IPC_MESSAGE_HANDLER(AutomationMsg_BlockedPopupCount, GetBlockedPopupCount) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_SendJSONRequest, + SendJSONRequest) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_WaitForTabCountToBecome, + WaitForTabCountToBecome) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_WaitForInfoBarCount, + WaitForInfoBarCount) + IPC_MESSAGE_HANDLER(AutomationMsg_GetPageCurrentEncoding, + GetPageCurrentEncoding) + IPC_MESSAGE_HANDLER(AutomationMsg_ShutdownSessionService, + ShutdownSessionService) + IPC_MESSAGE_HANDLER(AutomationMsg_SetContentSetting, SetContentSetting) + IPC_MESSAGE_HANDLER(AutomationMsg_LoadBlockedPlugins, LoadBlockedPlugins) + IPC_MESSAGE_HANDLER(AutomationMsg_ResetToDefaultTheme, ResetToDefaultTheme) + IPC_MESSAGE_HANDLER_DELAY_REPLY( + AutomationMsg_WaitForProcessLauncherThreadToGoIdle, + WaitForProcessLauncherThreadToGoIdle) + IPC_MESSAGE_HANDLER(AutomationMsg_GetParentBrowserOfTab, + GetParentBrowserOfTab) + + IPC_MESSAGE_UNHANDLED( + handled = AutomationProvider::OnMessageReceived(message)) + IPC_END_MESSAGE_MAP_EX() + if (!deserialize_success) + OnMessageDeserializationFailure(); + return handled; +} +",0,"bool TestingAutomationProvider::OnMessageReceived( + const IPC::Message& message) { + bool handled = true; + bool deserialize_success = true; + IPC_BEGIN_MESSAGE_MAP_EX(TestingAutomationProvider, + message, + deserialize_success) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_CloseBrowser, CloseBrowser) + IPC_MESSAGE_HANDLER(AutomationMsg_CloseBrowserRequestAsync, + CloseBrowserAsync) + IPC_MESSAGE_HANDLER(AutomationMsg_ActivateTab, ActivateTab) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_AppendTab, AppendTab) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_AppendBackgroundTab, + AppendBackgroundTab) + IPC_MESSAGE_HANDLER(AutomationMsg_ActiveTabIndex, GetActiveTabIndex) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_CloseTab, CloseTab) + IPC_MESSAGE_HANDLER(AutomationMsg_GetCookies, GetCookies) + IPC_MESSAGE_HANDLER(AutomationMsg_SetCookie, SetCookie) + IPC_MESSAGE_HANDLER(AutomationMsg_DeleteCookie, DeleteCookie) + IPC_MESSAGE_HANDLER(AutomationMsg_ShowCollectedCookiesDialog, + ShowCollectedCookiesDialog) + IPC_MESSAGE_HANDLER_DELAY_REPLY( + AutomationMsg_NavigateToURLBlockUntilNavigationsComplete, + NavigateToURLBlockUntilNavigationsComplete) + IPC_MESSAGE_HANDLER(AutomationMsg_NavigationAsync, NavigationAsync) + IPC_MESSAGE_HANDLER(AutomationMsg_NavigationAsyncWithDisposition, + NavigationAsyncWithDisposition) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_Reload, Reload) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_SetAuth, SetAuth) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_CancelAuth, CancelAuth) + IPC_MESSAGE_HANDLER(AutomationMsg_NeedsAuth, NeedsAuth) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_RedirectsFrom, + GetRedirectsFrom) + IPC_MESSAGE_HANDLER(AutomationMsg_BrowserWindowCount, GetBrowserWindowCount) + IPC_MESSAGE_HANDLER(AutomationMsg_NormalBrowserWindowCount, + GetNormalBrowserWindowCount) + IPC_MESSAGE_HANDLER(AutomationMsg_BrowserWindow, GetBrowserWindow) + IPC_MESSAGE_HANDLER(AutomationMsg_GetBrowserLocale, GetBrowserLocale) + IPC_MESSAGE_HANDLER(AutomationMsg_LastActiveBrowserWindow, + GetLastActiveBrowserWindow) + IPC_MESSAGE_HANDLER(AutomationMsg_ActiveWindow, GetActiveWindow) + IPC_MESSAGE_HANDLER(AutomationMsg_FindTabbedBrowserWindow, + FindTabbedBrowserWindow) + IPC_MESSAGE_HANDLER(AutomationMsg_IsWindowActive, IsWindowActive) + IPC_MESSAGE_HANDLER(AutomationMsg_ActivateWindow, ActivateWindow) + IPC_MESSAGE_HANDLER(AutomationMsg_IsWindowMaximized, IsWindowMaximized) + IPC_MESSAGE_HANDLER(AutomationMsg_WindowExecuteCommandAsync, + ExecuteBrowserCommandAsync) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_WindowExecuteCommand, + ExecuteBrowserCommand) + IPC_MESSAGE_HANDLER(AutomationMsg_TerminateSession, TerminateSession) + IPC_MESSAGE_HANDLER(AutomationMsg_WindowViewBounds, WindowGetViewBounds) + IPC_MESSAGE_HANDLER(AutomationMsg_GetWindowBounds, GetWindowBounds) + IPC_MESSAGE_HANDLER(AutomationMsg_SetWindowBounds, SetWindowBounds) + IPC_MESSAGE_HANDLER(AutomationMsg_SetWindowVisible, SetWindowVisible) + IPC_MESSAGE_HANDLER(AutomationMsg_WindowClick, WindowSimulateClick) + IPC_MESSAGE_HANDLER(AutomationMsg_WindowMouseMove, WindowSimulateMouseMove) + IPC_MESSAGE_HANDLER(AutomationMsg_WindowKeyPress, WindowSimulateKeyPress) + IPC_MESSAGE_HANDLER(AutomationMsg_TabCount, GetTabCount) + IPC_MESSAGE_HANDLER(AutomationMsg_Type, GetType) + IPC_MESSAGE_HANDLER(AutomationMsg_IsBrowserInApplicationMode, + IsBrowserInApplicationMode) + IPC_MESSAGE_HANDLER(AutomationMsg_Tab, GetTab) + IPC_MESSAGE_HANDLER(AutomationMsg_TabProcessID, GetTabProcessID) + IPC_MESSAGE_HANDLER(AutomationMsg_TabTitle, GetTabTitle) + IPC_MESSAGE_HANDLER(AutomationMsg_TabIndex, GetTabIndex) + IPC_MESSAGE_HANDLER(AutomationMsg_TabURL, GetTabURL) + IPC_MESSAGE_HANDLER(AutomationMsg_ShelfVisibility, GetShelfVisibility) + IPC_MESSAGE_HANDLER(AutomationMsg_IsFullscreen, IsFullscreen) + IPC_MESSAGE_HANDLER(AutomationMsg_IsFullscreenBubbleVisible, + GetFullscreenBubbleVisibility) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_DomOperation, + ExecuteJavascript) + IPC_MESSAGE_HANDLER(AutomationMsg_ConstrainedWindowCount, + GetConstrainedWindowCount) +#if defined(TOOLKIT_VIEWS) + IPC_MESSAGE_HANDLER(AutomationMsg_GetFocusedViewID, GetFocusedViewID) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_WaitForFocusedViewIDToChange, + WaitForFocusedViewIDToChange) + IPC_MESSAGE_HANDLER(AutomationMsg_StartTrackingPopupMenus, + StartTrackingPopupMenus) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_WaitForPopupMenuToOpen, + WaitForPopupMenuToOpen) +#endif // defined(TOOLKIT_VIEWS) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_InspectElement, + HandleInspectElementRequest) + IPC_MESSAGE_HANDLER(AutomationMsg_DownloadDirectory, GetDownloadDirectory) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_OpenNewBrowserWindowOfType, + OpenNewBrowserWindowOfType) + IPC_MESSAGE_HANDLER(AutomationMsg_WindowForBrowser, GetWindowForBrowser) + IPC_MESSAGE_HANDLER(AutomationMsg_BrowserForWindow, GetBrowserForWindow) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_ShowInterstitialPage, + ShowInterstitialPage) + IPC_MESSAGE_HANDLER(AutomationMsg_HideInterstitialPage, + HideInterstitialPage) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_WaitForTabToBeRestored, + WaitForTabToBeRestored) + IPC_MESSAGE_HANDLER(AutomationMsg_GetSecurityState, GetSecurityState) + IPC_MESSAGE_HANDLER(AutomationMsg_GetPageType, GetPageType) + IPC_MESSAGE_HANDLER(AutomationMsg_GetMetricEventDuration, + GetMetricEventDuration) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_ActionOnSSLBlockingPage, + ActionOnSSLBlockingPage) + IPC_MESSAGE_HANDLER(AutomationMsg_BringBrowserToFront, BringBrowserToFront) + IPC_MESSAGE_HANDLER(AutomationMsg_IsMenuCommandEnabled, + IsMenuCommandEnabled) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_PrintNow, PrintNow) + IPC_MESSAGE_HANDLER(AutomationMsg_SavePage, SavePage) + IPC_MESSAGE_HANDLER(AutomationMsg_OpenFindInPage, + HandleOpenFindInPageRequest) + IPC_MESSAGE_HANDLER(AutomationMsg_FindWindowVisibility, + GetFindWindowVisibility) + IPC_MESSAGE_HANDLER(AutomationMsg_FindWindowLocation, + HandleFindWindowLocationRequest) + IPC_MESSAGE_HANDLER(AutomationMsg_BookmarkBarVisibility, + GetBookmarkBarVisibility) + IPC_MESSAGE_HANDLER(AutomationMsg_GetBookmarksAsJSON, + GetBookmarksAsJSON) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_WaitForBookmarkModelToLoad, + WaitForBookmarkModelToLoad) + IPC_MESSAGE_HANDLER(AutomationMsg_AddBookmarkGroup, + AddBookmarkGroup) + IPC_MESSAGE_HANDLER(AutomationMsg_AddBookmarkURL, + AddBookmarkURL) + IPC_MESSAGE_HANDLER(AutomationMsg_ReparentBookmark, + ReparentBookmark) + IPC_MESSAGE_HANDLER(AutomationMsg_SetBookmarkTitle, + SetBookmarkTitle) + IPC_MESSAGE_HANDLER(AutomationMsg_SetBookmarkURL, + SetBookmarkURL) + IPC_MESSAGE_HANDLER(AutomationMsg_RemoveBookmark, + RemoveBookmark) + IPC_MESSAGE_HANDLER(AutomationMsg_GetInfoBarCount, GetInfoBarCount) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_ClickInfoBarAccept, + ClickInfoBarAccept) + IPC_MESSAGE_HANDLER(AutomationMsg_GetLastNavigationTime, + GetLastNavigationTime) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_WaitForNavigation, + WaitForNavigation) + IPC_MESSAGE_HANDLER(AutomationMsg_SetIntPreference, SetIntPreference) + IPC_MESSAGE_HANDLER(AutomationMsg_ShowingAppModalDialog, + GetShowingAppModalDialog) + IPC_MESSAGE_HANDLER(AutomationMsg_ClickAppModalDialogButton, + ClickAppModalDialogButton) + IPC_MESSAGE_HANDLER(AutomationMsg_SetStringPreference, SetStringPreference) + IPC_MESSAGE_HANDLER(AutomationMsg_GetBooleanPreference, + GetBooleanPreference) + IPC_MESSAGE_HANDLER(AutomationMsg_SetBooleanPreference, + SetBooleanPreference) + IPC_MESSAGE_HANDLER_DELAY_REPLY( + AutomationMsg_WaitForBrowserWindowCountToBecome, + WaitForBrowserWindowCountToBecome) + IPC_MESSAGE_HANDLER_DELAY_REPLY( + AutomationMsg_WaitForAppModalDialogToBeShown, + WaitForAppModalDialogToBeShown) + IPC_MESSAGE_HANDLER_DELAY_REPLY( + AutomationMsg_GoBackBlockUntilNavigationsComplete, + GoBackBlockUntilNavigationsComplete) + IPC_MESSAGE_HANDLER_DELAY_REPLY( + AutomationMsg_GoForwardBlockUntilNavigationsComplete, + GoForwardBlockUntilNavigationsComplete) + IPC_MESSAGE_HANDLER(AutomationMsg_SavePackageShouldPromptUser, + SavePackageShouldPromptUser) + IPC_MESSAGE_HANDLER(AutomationMsg_WindowTitle, GetWindowTitle) + IPC_MESSAGE_HANDLER(AutomationMsg_SetShelfVisibility, SetShelfVisibility) + IPC_MESSAGE_HANDLER(AutomationMsg_BlockedPopupCount, GetBlockedPopupCount) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_SendJSONRequest, + SendJSONRequest) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_WaitForTabCountToBecome, + WaitForTabCountToBecome) + IPC_MESSAGE_HANDLER_DELAY_REPLY(AutomationMsg_WaitForInfoBarCount, + WaitForInfoBarCount) + IPC_MESSAGE_HANDLER(AutomationMsg_GetPageCurrentEncoding, + GetPageCurrentEncoding) + IPC_MESSAGE_HANDLER(AutomationMsg_ShutdownSessionService, + ShutdownSessionService) + IPC_MESSAGE_HANDLER(AutomationMsg_SetContentSetting, SetContentSetting) + IPC_MESSAGE_HANDLER(AutomationMsg_LoadBlockedPlugins, LoadBlockedPlugins) + IPC_MESSAGE_HANDLER(AutomationMsg_ResetToDefaultTheme, ResetToDefaultTheme) + IPC_MESSAGE_HANDLER_DELAY_REPLY( + AutomationMsg_WaitForProcessLauncherThreadToGoIdle, + WaitForProcessLauncherThreadToGoIdle) + IPC_MESSAGE_HANDLER(AutomationMsg_GetParentBrowserOfTab, + GetParentBrowserOfTab) + + IPC_MESSAGE_UNHANDLED( + handled = AutomationProvider::OnMessageReceived(message)) + IPC_END_MESSAGE_MAP_EX() + if (!deserialize_success) + OnMessageDeserializationFailure(); + return handled; +} +","@@ -4473,7 +4473,7 @@ void TestingAutomationProvider::GetExtensionsInfo( + extension_value->SetString(""public_key"", extension->public_key()); + extension_value->SetString(""description"", extension->description()); + extension_value->SetString(""background_url"", +- extension->background_url().spec()); ++ extension->GetBackgroundURL().spec()); + extension_value->SetString(""options_url"", + extension->options_url().spec()); + extension_value->Set(""host_permissions"",",2071,2402,4096 +3795,"sctp_disposition_t sctp_sf_do_5_1D_ce(struct net *net, + const struct sctp_endpoint *ep, + const struct sctp_association *asoc, + const sctp_subtype_t type, void *arg, + sctp_cmd_seq_t *commands) +{ + struct sctp_chunk *chunk = arg; + struct sctp_association *new_asoc; + sctp_init_chunk_t *peer_init; + struct sctp_chunk *repl; + struct sctp_ulpevent *ev, *ai_ev = NULL; + int error = 0; + struct sctp_chunk *err_chk_p; + struct sock *sk; + + /* If the packet is an OOTB packet which is temporarily on the + * control endpoint, respond with an ABORT. + */ + if (ep == sctp_sk(net->sctp.ctl_sock)->ep) { + SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES); + return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); + } + + /* Make sure that the COOKIE_ECHO chunk has a valid length. + * In this case, we check that we have enough for at least a + * chunk header. More detailed verification is done + * in sctp_unpack_cookie(). + */ + if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t))) + return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); + + /* If the endpoint is not listening or if the number of associations + * on the TCP-style socket exceed the max backlog, respond with an + * ABORT. + */ + sk = ep->base.sk; + if (!sctp_sstate(sk, LISTENING) || + (sctp_style(sk, TCP) && sk_acceptq_is_full(sk))) + return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); + + /* ""Decode"" the chunk. We have no optional parameters so we + * are in good shape. + */ + chunk->subh.cookie_hdr = + (struct sctp_signed_cookie *)chunk->skb->data; + if (!pskb_pull(chunk->skb, ntohs(chunk->chunk_hdr->length) - + sizeof(sctp_chunkhdr_t))) + goto nomem; + + /* 5.1 D) Upon reception of the COOKIE ECHO chunk, Endpoint + * ""Z"" will reply with a COOKIE ACK chunk after building a TCB + * and moving to the ESTABLISHED state. + */ + new_asoc = sctp_unpack_cookie(ep, asoc, chunk, GFP_ATOMIC, &error, + &err_chk_p); + + /* FIXME: + * If the re-build failed, what is the proper error path + * from here? + * + * [We should abort the association. --piggy] + */ + if (!new_asoc) { + /* FIXME: Several errors are possible. A bad cookie should + * be silently discarded, but think about logging it too. + */ + switch (error) { + case -SCTP_IERROR_NOMEM: + goto nomem; + + case -SCTP_IERROR_STALE_COOKIE: + sctp_send_stale_cookie_err(net, ep, asoc, chunk, commands, + err_chk_p); + return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); + + case -SCTP_IERROR_BAD_SIG: + default: + return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); + } + } + + + /* Delay state machine commands until later. + * + * Re-build the bind address for the association is done in + * the sctp_unpack_cookie() already. + */ + /* This is a brand-new association, so these are not yet side + * effects--it is safe to run them here. + */ + peer_init = &chunk->subh.cookie_hdr->c.peer_init[0]; + + if (!sctp_process_init(new_asoc, chunk, + &chunk->subh.cookie_hdr->c.peer_addr, + peer_init, GFP_ATOMIC)) + goto nomem_init; + + /* SCTP-AUTH: Now that we've populate required fields in + * sctp_process_init, set up the assocaition shared keys as + * necessary so that we can potentially authenticate the ACK + */ + error = sctp_auth_asoc_init_active_key(new_asoc, GFP_ATOMIC); + if (error) + goto nomem_init; + + /* SCTP-AUTH: auth_chunk pointer is only set when the cookie-echo + * is supposed to be authenticated and we have to do delayed + * authentication. We've just recreated the association using + * the information in the cookie and now it's much easier to + * do the authentication. + */ + if (chunk->auth_chunk) { + struct sctp_chunk auth; + sctp_ierror_t ret; + + /* Make sure that we and the peer are AUTH capable */ + if (!net->sctp.auth_enable || !new_asoc->peer.auth_capable) { + sctp_association_free(new_asoc); + return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); + } + + /* set-up our fake chunk so that we can process it */ + auth.skb = chunk->auth_chunk; + auth.asoc = chunk->asoc; + auth.sctp_hdr = chunk->sctp_hdr; + auth.chunk_hdr = (sctp_chunkhdr_t *)skb_push(chunk->auth_chunk, + sizeof(sctp_chunkhdr_t)); + skb_pull(chunk->auth_chunk, sizeof(sctp_chunkhdr_t)); + auth.transport = chunk->transport; + + ret = sctp_sf_authenticate(net, ep, new_asoc, type, &auth); + if (ret != SCTP_IERROR_NO_ERROR) { + sctp_association_free(new_asoc); + return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); + } + } + + repl = sctp_make_cookie_ack(new_asoc, chunk); + if (!repl) + goto nomem_init; + + /* RFC 2960 5.1 Normal Establishment of an Association + * + * D) IMPLEMENTATION NOTE: An implementation may choose to + * send the Communication Up notification to the SCTP user + * upon reception of a valid COOKIE ECHO chunk. + */ + ev = sctp_ulpevent_make_assoc_change(new_asoc, 0, SCTP_COMM_UP, 0, + new_asoc->c.sinit_num_ostreams, + new_asoc->c.sinit_max_instreams, + NULL, GFP_ATOMIC); + if (!ev) + goto nomem_ev; + + /* Sockets API Draft Section 5.3.1.6 + * When a peer sends a Adaptation Layer Indication parameter , SCTP + * delivers this notification to inform the application that of the + * peers requested adaptation layer. + */ + if (new_asoc->peer.adaptation_ind) { + ai_ev = sctp_ulpevent_make_adaptation_indication(new_asoc, + GFP_ATOMIC); + if (!ai_ev) + goto nomem_aiev; + } + + /* Add all the state machine commands now since we've created + * everything. This way we don't introduce memory corruptions + * during side-effect processing and correclty count established + * associations. + */ + sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc)); + sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, + SCTP_STATE(SCTP_STATE_ESTABLISHED)); + SCTP_INC_STATS(net, SCTP_MIB_CURRESTAB); + SCTP_INC_STATS(net, SCTP_MIB_PASSIVEESTABS); + sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_START, SCTP_NULL()); + + if (new_asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE]) + sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START, + SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE)); + + /* This will send the COOKIE ACK */ + sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl)); + + /* Queue the ASSOC_CHANGE event */ + sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev)); + + /* Send up the Adaptation Layer Indication event */ + if (ai_ev) + sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, + SCTP_ULPEVENT(ai_ev)); + + return SCTP_DISPOSITION_CONSUME; + +nomem_aiev: + sctp_ulpevent_free(ev); +nomem_ev: + sctp_chunk_free(repl); +nomem_init: + sctp_association_free(new_asoc); +nomem: + return SCTP_DISPOSITION_NOMEM; +} +",0,"sctp_disposition_t sctp_sf_do_5_1D_ce(struct net *net, + const struct sctp_endpoint *ep, + const struct sctp_association *asoc, + const sctp_subtype_t type, void *arg, + sctp_cmd_seq_t *commands) +{ + struct sctp_chunk *chunk = arg; + struct sctp_association *new_asoc; + sctp_init_chunk_t *peer_init; + struct sctp_chunk *repl; + struct sctp_ulpevent *ev, *ai_ev = NULL; + int error = 0; + struct sctp_chunk *err_chk_p; + struct sock *sk; + + /* If the packet is an OOTB packet which is temporarily on the + * control endpoint, respond with an ABORT. + */ + if (ep == sctp_sk(net->sctp.ctl_sock)->ep) { + SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES); + return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); + } + + /* Make sure that the COOKIE_ECHO chunk has a valid length. + * In this case, we check that we have enough for at least a + * chunk header. More detailed verification is done + * in sctp_unpack_cookie(). + */ + if (!sctp_chunk_length_valid(chunk, sizeof(sctp_chunkhdr_t))) + return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); + + /* If the endpoint is not listening or if the number of associations + * on the TCP-style socket exceed the max backlog, respond with an + * ABORT. + */ + sk = ep->base.sk; + if (!sctp_sstate(sk, LISTENING) || + (sctp_style(sk, TCP) && sk_acceptq_is_full(sk))) + return sctp_sf_tabort_8_4_8(net, ep, asoc, type, arg, commands); + + /* ""Decode"" the chunk. We have no optional parameters so we + * are in good shape. + */ + chunk->subh.cookie_hdr = + (struct sctp_signed_cookie *)chunk->skb->data; + if (!pskb_pull(chunk->skb, ntohs(chunk->chunk_hdr->length) - + sizeof(sctp_chunkhdr_t))) + goto nomem; + + /* 5.1 D) Upon reception of the COOKIE ECHO chunk, Endpoint + * ""Z"" will reply with a COOKIE ACK chunk after building a TCB + * and moving to the ESTABLISHED state. + */ + new_asoc = sctp_unpack_cookie(ep, asoc, chunk, GFP_ATOMIC, &error, + &err_chk_p); + + /* FIXME: + * If the re-build failed, what is the proper error path + * from here? + * + * [We should abort the association. --piggy] + */ + if (!new_asoc) { + /* FIXME: Several errors are possible. A bad cookie should + * be silently discarded, but think about logging it too. + */ + switch (error) { + case -SCTP_IERROR_NOMEM: + goto nomem; + + case -SCTP_IERROR_STALE_COOKIE: + sctp_send_stale_cookie_err(net, ep, asoc, chunk, commands, + err_chk_p); + return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); + + case -SCTP_IERROR_BAD_SIG: + default: + return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); + } + } + + + /* Delay state machine commands until later. + * + * Re-build the bind address for the association is done in + * the sctp_unpack_cookie() already. + */ + /* This is a brand-new association, so these are not yet side + * effects--it is safe to run them here. + */ + peer_init = &chunk->subh.cookie_hdr->c.peer_init[0]; + + if (!sctp_process_init(new_asoc, chunk, + &chunk->subh.cookie_hdr->c.peer_addr, + peer_init, GFP_ATOMIC)) + goto nomem_init; + + /* SCTP-AUTH: Now that we've populate required fields in + * sctp_process_init, set up the assocaition shared keys as + * necessary so that we can potentially authenticate the ACK + */ + error = sctp_auth_asoc_init_active_key(new_asoc, GFP_ATOMIC); + if (error) + goto nomem_init; + + /* SCTP-AUTH: auth_chunk pointer is only set when the cookie-echo + * is supposed to be authenticated and we have to do delayed + * authentication. We've just recreated the association using + * the information in the cookie and now it's much easier to + * do the authentication. + */ + if (chunk->auth_chunk) { + struct sctp_chunk auth; + sctp_ierror_t ret; + + /* Make sure that we and the peer are AUTH capable */ + if (!net->sctp.auth_enable || !new_asoc->peer.auth_capable) { + sctp_association_free(new_asoc); + return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); + } + + /* set-up our fake chunk so that we can process it */ + auth.skb = chunk->auth_chunk; + auth.asoc = chunk->asoc; + auth.sctp_hdr = chunk->sctp_hdr; + auth.chunk_hdr = (sctp_chunkhdr_t *)skb_push(chunk->auth_chunk, + sizeof(sctp_chunkhdr_t)); + skb_pull(chunk->auth_chunk, sizeof(sctp_chunkhdr_t)); + auth.transport = chunk->transport; + + ret = sctp_sf_authenticate(net, ep, new_asoc, type, &auth); + if (ret != SCTP_IERROR_NO_ERROR) { + sctp_association_free(new_asoc); + return sctp_sf_pdiscard(net, ep, asoc, type, arg, commands); + } + } + + repl = sctp_make_cookie_ack(new_asoc, chunk); + if (!repl) + goto nomem_init; + + /* RFC 2960 5.1 Normal Establishment of an Association + * + * D) IMPLEMENTATION NOTE: An implementation may choose to + * send the Communication Up notification to the SCTP user + * upon reception of a valid COOKIE ECHO chunk. + */ + ev = sctp_ulpevent_make_assoc_change(new_asoc, 0, SCTP_COMM_UP, 0, + new_asoc->c.sinit_num_ostreams, + new_asoc->c.sinit_max_instreams, + NULL, GFP_ATOMIC); + if (!ev) + goto nomem_ev; + + /* Sockets API Draft Section 5.3.1.6 + * When a peer sends a Adaptation Layer Indication parameter , SCTP + * delivers this notification to inform the application that of the + * peers requested adaptation layer. + */ + if (new_asoc->peer.adaptation_ind) { + ai_ev = sctp_ulpevent_make_adaptation_indication(new_asoc, + GFP_ATOMIC); + if (!ai_ev) + goto nomem_aiev; + } + + /* Add all the state machine commands now since we've created + * everything. This way we don't introduce memory corruptions + * during side-effect processing and correclty count established + * associations. + */ + sctp_add_cmd_sf(commands, SCTP_CMD_NEW_ASOC, SCTP_ASOC(new_asoc)); + sctp_add_cmd_sf(commands, SCTP_CMD_NEW_STATE, + SCTP_STATE(SCTP_STATE_ESTABLISHED)); + SCTP_INC_STATS(net, SCTP_MIB_CURRESTAB); + SCTP_INC_STATS(net, SCTP_MIB_PASSIVEESTABS); + sctp_add_cmd_sf(commands, SCTP_CMD_HB_TIMERS_START, SCTP_NULL()); + + if (new_asoc->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE]) + sctp_add_cmd_sf(commands, SCTP_CMD_TIMER_START, + SCTP_TO(SCTP_EVENT_TIMEOUT_AUTOCLOSE)); + + /* This will send the COOKIE ACK */ + sctp_add_cmd_sf(commands, SCTP_CMD_REPLY, SCTP_CHUNK(repl)); + + /* Queue the ASSOC_CHANGE event */ + sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, SCTP_ULPEVENT(ev)); + + /* Send up the Adaptation Layer Indication event */ + if (ai_ev) + sctp_add_cmd_sf(commands, SCTP_CMD_EVENT_ULP, + SCTP_ULPEVENT(ai_ev)); + + return SCTP_DISPOSITION_CONSUME; + +nomem_aiev: + sctp_ulpevent_free(ev); +nomem_ev: + sctp_chunk_free(repl); +nomem_init: + sctp_association_free(new_asoc); +nomem: + return SCTP_DISPOSITION_NOMEM; +} +","@@ -170,6 +170,9 @@ sctp_chunk_length_valid(struct sctp_chunk *chunk, + { + __u16 chunk_length = ntohs(chunk->chunk_hdr->length); + ++ /* Previously already marked? */ ++ if (unlikely(chunk->pdiscard)) ++ return 0; + if (unlikely(chunk_length < required_length)) + return 0; + ",1906,2237,4096 +18176,"void ZLIB_INTERNAL inflate_fast(strm, start) +z_streamp strm; +unsigned start; /* inflate()'s starting value for strm->avail_out */ +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *in; /* local strm->next_in */ + z_const unsigned char FAR *last; /* have enough input while in < last */ + unsigned char FAR *out; /* local strm->next_out */ + unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ + unsigned char FAR *end; /* while out < end, enough space available */ +#ifdef INFLATE_STRICT + unsigned dmax; /* maximum distance from zlib header */ +#endif + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned wnext; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ + unsigned long hold; /* local strm->hold */ + unsigned bits; /* local strm->bits */ + code const FAR *lcode; /* local strm->lencode */ + code const FAR *dcode; /* local strm->distcode */ + unsigned lmask; /* mask for first level of length codes */ + unsigned dmask; /* mask for first level of distance codes */ + code here; /* retrieved table entry */ + unsigned op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + unsigned len; /* match length, unused bytes */ + unsigned dist; /* match distance */ + unsigned char FAR *from; /* where to copy match from */ + + /* copy state to local variables */ + state = (struct inflate_state FAR *)strm->state; + in = strm->next_in - OFF; + last = in + (strm->avail_in - 5); + out = strm->next_out - OFF; + beg = out - (start - strm->avail_out); + end = out + (strm->avail_out - 257); + #ifdef INFLATE_STRICT + dmax = state->dmax; +#endif + wsize = state->wsize; + whave = state->whave; + wnext = state->wnext; + window = state->window; + hold = state->hold; + bits = state->bits; + lcode = state->lencode; + dcode = state->distcode; + lmask = (1U << state->lenbits) - 1; + dmask = (1U << state->distbits) - 1; + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + do { + if (bits < 15) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + here = lcode[hold & lmask]; + dolen: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op == 0) { /* literal */ + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + ""inflate: literal '%c'\n"" : + ""inflate: literal 0x%02x\n"", here.val)); + PUP(out) = (unsigned char)(here.val); + } + else if (op & 16) { /* length base */ + len = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + len += (unsigned)hold & ((1U << op) - 1); + hold >>= op; + bits -= op; + } + Tracevv((stderr, ""inflate: length %u\n"", len)); + if (bits < 15) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + here = dcode[hold & dmask]; + dodist: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op & 16) { /* distance base */ + dist = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + if (bits < op) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + } + dist += (unsigned)hold & ((1U << op) - 1); +#ifdef INFLATE_STRICT + if (dist > dmax) { + strm->msg = (char *)""invalid distance too far back""; + state->mode = BAD; + break; + } +#endif + hold >>= op; + bits -= op; + Tracevv((stderr, ""inflate: distance %u\n"", dist)); + op = (unsigned)(out - beg); /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state->sane) { + strm->msg = + (char *)""invalid distance too far back""; + state->mode = BAD; + break; + } + #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + if (len <= op - whave) { + do { + PUP(out) = 0; + } while (--len); + continue; + } + len -= op - whave; + do { + PUP(out) = 0; + } while (--op > whave); + if (op == 0) { + from = out - dist; + do { + PUP(out) = PUP(from); + } while (--len); + continue; + } + #endif + } + from = window - OFF; + if (wnext == 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = out - dist; /* rest from output */ + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = window - OFF; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = out - dist; /* rest from output */ + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = out - dist; /* rest from output */ + } + } + while (len > 2) { + PUP(out) = PUP(from); + PUP(out) = PUP(from); + PUP(out) = PUP(from); + len -= 3; + } + if (len) { + PUP(out) = PUP(from); + if (len > 1) + PUP(out) = PUP(from); + } + } + else { + from = out - dist; /* copy direct from output */ + do { /* minimum length is three */ + PUP(out) = PUP(from); + PUP(out) = PUP(from); + PUP(out) = PUP(from); + len -= 3; + } while (len > 2); + if (len) { + PUP(out) = PUP(from); + if (len > 1) + PUP(out) = PUP(from); + } + } + } + else if ((op & 64) == 0) { /* 2nd level distance code */ + here = dcode[here.val + (hold & ((1U << op) - 1))]; + goto dodist; + } + else { + strm->msg = (char *)""invalid distance code""; + state->mode = BAD; + break; + } + } + else if ((op & 64) == 0) { /* 2nd level length code */ + here = lcode[here.val + (hold & ((1U << op) - 1))]; + goto dolen; + } + else if (op & 32) { /* end-of-block */ + Tracevv((stderr, ""inflate: end of block\n"")); + state->mode = TYPE; + break; + } + else { + strm->msg = (char *)""invalid literal/length code""; + state->mode = BAD; + break; + } + } while (in < last && out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + in -= len; + bits -= len << 3; + hold &= (1U << bits) - 1; + + /* update state and return */ + strm->next_in = in + OFF; + strm->next_out = out + OFF; + strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); + strm->avail_out = (unsigned)(out < end ? + 257 + (end - out) : 257 - (out - end)); + state->hold = hold; + state->bits = bits; + return; +} +",1,"void ZLIB_INTERNAL inflate_fast(strm, start) +z_streamp strm; +unsigned start; /* inflate()'s starting value for strm->avail_out */ +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *in; /* local strm->next_in */ + z_const unsigned char FAR *last; /* have enough input while in < last */ + unsigned char FAR *out; /* local strm->next_out */ + unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ + unsigned char FAR *end; /* while out < end, enough space available */ +#ifdef INFLATE_STRICT + unsigned dmax; /* maximum distance from zlib header */ +#endif + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned wnext; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ + unsigned long hold; /* local strm->hold */ + unsigned bits; /* local strm->bits */ + code const FAR *lcode; /* local strm->lencode */ + code const FAR *dcode; /* local strm->distcode */ + unsigned lmask; /* mask for first level of length codes */ + unsigned dmask; /* mask for first level of distance codes */ + code here; /* retrieved table entry */ + unsigned op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + unsigned len; /* match length, unused bytes */ + unsigned dist; /* match distance */ + unsigned char FAR *from; /* where to copy match from */ + + /* copy state to local variables */ + state = (struct inflate_state FAR *)strm->state; + in = strm->next_in; + last = in + (strm->avail_in - 5); + out = strm->next_out; + beg = out - (start - strm->avail_out); + end = out + (strm->avail_out - 257); + #ifdef INFLATE_STRICT + dmax = state->dmax; +#endif + wsize = state->wsize; + whave = state->whave; + wnext = state->wnext; + window = state->window; + hold = state->hold; + bits = state->bits; + lcode = state->lencode; + dcode = state->distcode; + lmask = (1U << state->lenbits) - 1; + dmask = (1U << state->distbits) - 1; + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + do { + if (bits < 15) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + hold += (unsigned long)(*in++) << bits; + bits += 8; + } + here = lcode[hold & lmask]; + dolen: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op == 0) { /* literal */ + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + ""inflate: literal '%c'\n"" : + ""inflate: literal 0x%02x\n"", here.val)); + *out++ = (unsigned char)(here.val); + } + else if (op & 16) { /* length base */ + len = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + } + len += (unsigned)hold & ((1U << op) - 1); + hold >>= op; + bits -= op; + } + Tracevv((stderr, ""inflate: length %u\n"", len)); + if (bits < 15) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + hold += (unsigned long)(*in++) << bits; + bits += 8; + } + here = dcode[hold & dmask]; + dodist: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op & 16) { /* distance base */ + dist = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + if (bits < op) { + hold += (unsigned long)(*in++) << bits; + bits += 8; + } + } + dist += (unsigned)hold & ((1U << op) - 1); +#ifdef INFLATE_STRICT + if (dist > dmax) { + strm->msg = (char *)""invalid distance too far back""; + state->mode = BAD; + break; + } +#endif + hold >>= op; + bits -= op; + Tracevv((stderr, ""inflate: distance %u\n"", dist)); + op = (unsigned)(out - beg); /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state->sane) { + strm->msg = + (char *)""invalid distance too far back""; + state->mode = BAD; + break; + } + #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + if (len <= op - whave) { + do { + *out++ = 0; + } while (--len); + continue; + } + len -= op - whave; + do { + *out++ = 0; + } while (--op > whave); + if (op == 0) { + from = out - dist; + do { + *out++ = *from++; + } while (--len); + continue; + } + #endif + } + from = window; + if (wnext == 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + *out++ = *from++; + } while (--op); + from = out - dist; /* rest from output */ + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + *out++ = *from++; + } while (--op); + from = window; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + *out++ = *from++; + } while (--op); + from = out - dist; /* rest from output */ + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + *out++ = *from++; + } while (--op); + from = out - dist; /* rest from output */ + } + } + while (len > 2) { + *out++ = *from++; + *out++ = *from++; + *out++ = *from++; + len -= 3; + } + if (len) { + *out++ = *from++; + if (len > 1) + *out++ = *from++; + } + } + else { + from = out - dist; /* copy direct from output */ + do { /* minimum length is three */ + *out++ = *from++; + *out++ = *from++; + *out++ = *from++; + len -= 3; + } while (len > 2); + if (len) { + *out++ = *from++; + if (len > 1) + *out++ = *from++; + } + } + } + else if ((op & 64) == 0) { /* 2nd level distance code */ + here = dcode[here.val + (hold & ((1U << op) - 1))]; + goto dodist; + } + else { + strm->msg = (char *)""invalid distance code""; + state->mode = BAD; + break; + } + } + else if ((op & 64) == 0) { /* 2nd level length code */ + here = lcode[here.val + (hold & ((1U << op) - 1))]; + goto dolen; + } + else if (op & 32) { /* end-of-block */ + Tracevv((stderr, ""inflate: end of block\n"")); + state->mode = TYPE; + break; + } + else { + strm->msg = (char *)""invalid literal/length code""; + state->mode = BAD; + break; + } + } while (in < last && out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + in -= len; + bits -= len << 3; + hold &= (1U << bits) - 1; + + /* update state and return */ + strm->next_in = in; + strm->next_out = out; + strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); + strm->avail_out = (unsigned)(out < end ? + 257 + (end - out) : 257 - (out - end)); + state->hold = hold; + state->bits = bits; + return; +} +","@@ -10,25 +10,6 @@ + + #ifndef ASMINF + +-/* Allow machine dependent optimization for post-increment or pre-increment. +- Based on testing to date, +- Pre-increment preferred for: +- - PowerPC G3 (Adler) +- - MIPS R5000 (Randers-Pehrson) +- Post-increment preferred for: +- - none +- No measurable difference: +- - Pentium III (Anderson) +- - M68060 (Nikl) +- */ +-#ifdef POSTINC +-# define OFF 0 +-# define PUP(a) *(a)++ +-#else +-# define OFF 1 +-# define PUP(a) *++(a) +-#endif +- + /* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is +@@ -96,9 +77,9 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */ + + /* copy state to local variables */ + state = (struct inflate_state FAR *)strm->state; +- in = strm->next_in - OFF; ++ in = strm->next_in; + last = in + (strm->avail_in - 5); +- out = strm->next_out - OFF; ++ out = strm->next_out; + beg = out - (start - strm->avail_out); + end = out + (strm->avail_out - 257); + #ifdef INFLATE_STRICT +@@ -119,9 +100,9 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */ + input data or output space */ + do { + if (bits < 15) { +- hold += (unsigned long)(PUP(in)) << bits; ++ hold += (unsigned long)(*in++) << bits; + bits += 8; +- hold += (unsigned long)(PUP(in)) << bits; ++ hold += (unsigned long)(*in++) << bits; + bits += 8; + } + here = lcode[hold & lmask]; +@@ -134,14 +115,14 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */ + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + ""inflate: literal '%c'\n"" : + ""inflate: literal 0x%02x\n"", here.val)); +- PUP(out) = (unsigned char)(here.val); ++ *out++ = (unsigned char)(here.val); + } + else if (op & 16) { /* length base */ + len = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { +- hold += (unsigned long)(PUP(in)) << bits; ++ hold += (unsigned long)(*in++) << bits; + bits += 8; + } + len += (unsigned)hold & ((1U << op) - 1); +@@ -150,9 +131,9 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */ + } + Tracevv((stderr, ""inflate: length %u\n"", len)); + if (bits < 15) { +- hold += (unsigned long)(PUP(in)) << bits; ++ hold += (unsigned long)(*in++) << bits; + bits += 8; +- hold += (unsigned long)(PUP(in)) << bits; ++ hold += (unsigned long)(*in++) << bits; + bits += 8; + } + here = dcode[hold & dmask]; +@@ -165,10 +146,10 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */ + dist = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (bits < op) { +- hold += (unsigned long)(PUP(in)) << bits; ++ hold += (unsigned long)(*in++) << bits; + bits += 8; + if (bits < op) { +- hold += (unsigned long)(PUP(in)) << bits; ++ hold += (unsigned long)(*in++) << bits; + bits += 8; + } + } +@@ -196,30 +177,30 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */ + #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + if (len <= op - whave) { + do { +- PUP(out) = 0; ++ *out++ = 0; + } while (--len); + continue; + } + len -= op - whave; + do { +- PUP(out) = 0; ++ *out++ = 0; + } while (--op > whave); + if (op == 0) { + from = out - dist; + do { +- PUP(out) = PUP(from); ++ *out++ = *from++; + } while (--len); + continue; + } + #endif + } +- from = window - OFF; ++ from = window; + if (wnext == 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { +- PUP(out) = PUP(from); ++ *out++ = *from++; + } while (--op); + from = out - dist; /* rest from output */ + } +@@ -230,14 +211,14 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */ + if (op < len) { /* some from end of window */ + len -= op; + do { +- PUP(out) = PUP(from); ++ *out++ = *from++; + } while (--op); +- from = window - OFF; ++ from = window; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { +- PUP(out) = PUP(from); ++ *out++ = *from++; + } while (--op); + from = out - dist; /* rest from output */ + } +@@ -248,35 +229,35 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */ + if (op < len) { /* some from window */ + len -= op; + do { +- PUP(out) = PUP(from); ++ *out++ = *from++; + } while (--op); + from = out - dist; /* rest from output */ + } + } + while (len > 2) { +- PUP(out) = PUP(from); +- PUP(out) = PUP(from); +- PUP(out) = PUP(from); ++ *out++ = *from++; ++ *out++ = *from++; ++ *out++ = *from++; + len -= 3; + } + if (len) { +- PUP(out) = PUP(from); ++ *out++ = *from++; + if (len > 1) +- PUP(out) = PUP(from); ++ *out++ = *from++; + } + } + else { + from = out - dist; /* copy direct from output */ + do { /* minimum length is three */ +- PUP(out) = PUP(from); +- PUP(out) = PUP(from); +- PUP(out) = PUP(from); ++ *out++ = *from++; ++ *out++ = *from++; ++ *out++ = *from++; + len -= 3; + } while (len > 2); + if (len) { +- PUP(out) = PUP(from); ++ *out++ = *from++; + if (len > 1) +- PUP(out) = PUP(from); ++ *out++ = *from++; + } + } + } +@@ -313,8 +294,8 @@ unsigned start; /* inflate()'s starting value for strm->avail_out */ + hold &= (1U << bits) - 1; + + /* update state and return */ +- strm->next_in = in + OFF; +- strm->next_out = out + OFF; ++ strm->next_in = in; ++ strm->next_out = out; + strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); + strm->avail_out = (unsigned)(out < end ? + 257 + (end - out) : 257 - (out - end));",2288,2619,4096 +6109,"activate_files (ActivateParameters *parameters) +{ + NautilusFile *file; + NautilusWindow *window; + NautilusWindowOpenFlags flags; + g_autoptr (GList) open_in_app_parameters = NULL; + g_autoptr (GList) unhandled_open_in_app_uris = NULL; + ApplicationLaunchParameters *one_parameters; + int count; + g_autofree char *old_working_dir = NULL; + GdkScreen *screen; + gint num_apps; + gint num_unhandled; + gint num_files; + gboolean open_files; + gboolean closed_window; + g_autoptr (GQueue) launch_desktop_files = NULL; + g_autoptr (GQueue) launch_files = NULL; + g_autoptr (GQueue) launch_in_terminal_files = NULL; + g_autoptr (GQueue) open_in_app_uris = NULL; + g_autoptr (GQueue) open_in_view_files = NULL; + GList *l; + ActivationAction action; + LaunchLocation *location; + + launch_desktop_files = g_queue_new (); + launch_files = g_queue_new (); + launch_in_terminal_files = g_queue_new (); + open_in_view_files = g_queue_new (); + open_in_app_uris = g_queue_new (); + + for (l = parameters->locations; l != NULL; l = l->next) + { + location = l->data; + file = location->file; + + if (file_was_cancelled (file)) + { + continue; + } + + action = get_activation_action (file); + if (action == ACTIVATION_ACTION_ASK) + { + /* Special case for executable text files, since it might be + * dangerous & unexpected to launch these. + */ + pause_activation_timed_cancel (parameters); + action = get_executable_text_file_action (parameters->parent_window, file); + unpause_activation_timed_cancel (parameters); + } + + switch (action) + { + case ACTIVATION_ACTION_LAUNCH_DESKTOP_FILE: + { + g_queue_push_tail (launch_desktop_files, file); + } + break; + + case ACTIVATION_ACTION_LAUNCH: + { + g_queue_push_tail (launch_files, file); + } + break; + + case ACTIVATION_ACTION_LAUNCH_IN_TERMINAL: + { + g_queue_push_tail (launch_in_terminal_files, file); + } + break; + + case ACTIVATION_ACTION_OPEN_IN_VIEW: + { + g_queue_push_tail (open_in_view_files, file); + } + break; + + case ACTIVATION_ACTION_OPEN_IN_APPLICATION: + { + g_queue_push_tail (open_in_app_uris, location->uri); + } + break; + + case ACTIVATION_ACTION_DO_NOTHING: + { + } + break; + + case ACTIVATION_ACTION_EXTRACT: + { + /* Extraction of files should be handled in the view */ + g_assert_not_reached (); + } + break; + + case ACTIVATION_ACTION_ASK: + { + g_assert_not_reached (); + } + break; + } + } + + for (l = g_queue_peek_head_link (launch_desktop_files); l != NULL; l = l->next) + { + file = NAUTILUS_FILE (l->data); + + activate_desktop_file (parameters, file); + } + + if (parameters->activation_directory && + (!g_queue_is_empty (launch_files) || + !g_queue_is_empty (launch_in_terminal_files))) + { + old_working_dir = g_get_current_dir (); + g_chdir (parameters->activation_directory); + } + + screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window)); + for (l = g_queue_peek_head_link (launch_files); l != NULL; l = l->next) + { + g_autofree char *uri = NULL; + g_autofree char *executable_path = NULL; + g_autofree char *quoted_path = NULL; + + file = NAUTILUS_FILE (l->data); + + uri = nautilus_file_get_activation_uri (file); + executable_path = g_filename_from_uri (uri, NULL, NULL); + quoted_path = g_shell_quote (executable_path); + + DEBUG (""Launching file path %s"", quoted_path); + + nautilus_launch_application_from_command (screen, quoted_path, FALSE, NULL); + } + + for (l = g_queue_peek_head_link (launch_in_terminal_files); l != NULL; l = l->next) + { + g_autofree char *uri = NULL; + g_autofree char *executable_path = NULL; + g_autofree char *quoted_path = NULL; + + file = NAUTILUS_FILE (l->data); + + uri = nautilus_file_get_activation_uri (file); + executable_path = g_filename_from_uri (uri, NULL, NULL); + quoted_path = g_shell_quote (executable_path); + + DEBUG (""Launching in terminal file quoted path %s"", quoted_path); + + nautilus_launch_application_from_command (screen, quoted_path, TRUE, NULL); + } + + if (old_working_dir != NULL) + { + g_chdir (old_working_dir); + } + + count = g_queue_get_length (open_in_view_files); + + flags = parameters->flags; + if (count > 1) + { + if ((parameters->flags & NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW) == 0) + { + /* if CLOSE_BEHIND is set and we have a directory to be activated, we + * will first have to open a new window and after that we can open the + * rest of files in tabs */ + if ((parameters->flags & NAUTILUS_WINDOW_OPEN_FLAG_CLOSE_BEHIND) != 0) + { + flags |= NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW; + } + else + { + flags |= NAUTILUS_WINDOW_OPEN_FLAG_NEW_TAB; + } + } + else + { + flags |= NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW; + } + } + else + { + /* if we want to close the window and activate a single directory, then we will need + * the NEW_WINDOW flag set */ + if ((parameters->flags & NAUTILUS_WINDOW_OPEN_FLAG_CLOSE_BEHIND) != 0) + { + flags |= NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW; + } + } + + if (parameters->slot != NULL && + (!parameters->user_confirmation || + confirm_multiple_windows (parameters->parent_window, count, + (flags & NAUTILUS_WINDOW_OPEN_FLAG_NEW_TAB) != 0))) + { + if ((flags & NAUTILUS_WINDOW_OPEN_FLAG_NEW_TAB) != 0 && + g_settings_get_enum (nautilus_preferences, NAUTILUS_PREFERENCES_NEW_TAB_POSITION) == + NAUTILUS_NEW_TAB_POSITION_AFTER_CURRENT_TAB) + { + /* When inserting N tabs after the current one, + * we first open tab N, then tab N-1, ..., then tab 0. + * Each of them is appended to the current tab, i.e. + * prepended to the list of tabs to open. + */ + g_queue_reverse (open_in_view_files); + } + + closed_window = FALSE; + + for (l = g_queue_peek_head_link (open_in_view_files); l != NULL; l = l->next) + { + g_autofree char *uri = NULL; + g_autoptr (GFile) location = NULL; + g_autoptr (GFile) location_with_permissions = NULL; + /* The ui should ask for navigation or object windows + * depending on what the current one is */ + file = NAUTILUS_FILE (l->data); + uri = nautilus_file_get_activation_uri (file); + location = g_file_new_for_uri (uri); + if (g_file_is_native (location) && + (nautilus_file_is_in_admin (file) || + !nautilus_file_can_read (file) || + !nautilus_file_can_execute (file))) + { + g_autofree gchar *file_path = NULL; + + g_free (uri); + + file_path = g_file_get_path (location); + uri = g_strconcat (""admin://"", file_path, NULL); + } + + location_with_permissions = g_file_new_for_uri (uri); + /* FIXME: we need to pass the parent_window, but we only use it for the current active window, + * which nautilus-application should take care of. However is not working and creating regressions + * in some cases. Until we figure out what's going on, continue to use the parameters->slot + * to make splicit the window we want to use for activating the files */ + nautilus_application_open_location_full (NAUTILUS_APPLICATION (g_application_get_default ()), + location_with_permissions, flags, NULL, NULL, parameters->slot); + + /* close only the window from which the action was launched and then open + * tabs/windows (depending on parameters->flags) */ + if (!closed_window && (flags & NAUTILUS_WINDOW_OPEN_FLAG_CLOSE_BEHIND) != 0) + { + flags &= (~NAUTILUS_WINDOW_OPEN_FLAG_CLOSE_BEHIND); + + /* if NEW_WINDOW is set, we want all files in new windows, not in tabs */ + if ((parameters->flags & NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW) == 0) + { + flags &= (~NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW); + flags |= NAUTILUS_WINDOW_OPEN_FLAG_NEW_TAB; + } + + closed_window = TRUE; + } + } + } + + if (open_in_app_uris != NULL) + { + open_in_app_parameters = make_activation_parameters (g_queue_peek_head_link (open_in_app_uris), + &unhandled_open_in_app_uris); + } + + num_apps = g_list_length (open_in_app_parameters); + num_unhandled = g_list_length (unhandled_open_in_app_uris); + num_files = g_queue_get_length (open_in_app_uris); + open_files = TRUE; + + if (g_queue_is_empty (open_in_app_uris) && + (!parameters->user_confirmation || + num_files + num_unhandled > SILENT_OPEN_LIMIT) && + num_apps > 1) + { + GtkDialog *dialog; + char *prompt; + g_autofree char *detail = NULL; + int response; + + pause_activation_timed_cancel (parameters); + + prompt = _(""Are you sure you want to open all files?""); + detail = g_strdup_printf (ngettext (""This will open %d separate application."", + ""This will open %d separate applications."", num_apps), num_apps); + dialog = eel_show_yes_no_dialog (prompt, detail, + _(""_OK""), _(""_Cancel""), + parameters->parent_window); + response = gtk_dialog_run (dialog); + gtk_widget_destroy (GTK_WIDGET (dialog)); + + unpause_activation_timed_cancel (parameters); + + if (response != GTK_RESPONSE_YES) + { + open_files = FALSE; + } + } + + if (open_files) + { + for (l = open_in_app_parameters; l != NULL; l = l->next) + { + one_parameters = l->data; + + nautilus_launch_application_by_uri (one_parameters->application, + one_parameters->uris, + parameters->parent_window); + application_launch_parameters_free (one_parameters); + } + + for (l = unhandled_open_in_app_uris; l != NULL; l = l->next) + { + char *uri = l->data; + + /* this does not block */ + application_unhandled_uri (parameters, uri); + } + } + + window = NULL; + if (parameters->slot != NULL) + { + window = nautilus_window_slot_get_window (parameters->slot); + } + + if (open_in_app_parameters != NULL || + unhandled_open_in_app_uris != NULL) + { + if ((parameters->flags & NAUTILUS_WINDOW_OPEN_FLAG_CLOSE_BEHIND) != 0 && + window != NULL) + { + nautilus_window_close (window); + } + } + + activation_parameters_free (parameters); +} +",0,"activate_files (ActivateParameters *parameters) +{ + NautilusFile *file; + NautilusWindow *window; + NautilusWindowOpenFlags flags; + g_autoptr (GList) open_in_app_parameters = NULL; + g_autoptr (GList) unhandled_open_in_app_uris = NULL; + ApplicationLaunchParameters *one_parameters; + int count; + g_autofree char *old_working_dir = NULL; + GdkScreen *screen; + gint num_apps; + gint num_unhandled; + gint num_files; + gboolean open_files; + gboolean closed_window; + g_autoptr (GQueue) launch_desktop_files = NULL; + g_autoptr (GQueue) launch_files = NULL; + g_autoptr (GQueue) launch_in_terminal_files = NULL; + g_autoptr (GQueue) open_in_app_uris = NULL; + g_autoptr (GQueue) open_in_view_files = NULL; + GList *l; + ActivationAction action; + LaunchLocation *location; + + launch_desktop_files = g_queue_new (); + launch_files = g_queue_new (); + launch_in_terminal_files = g_queue_new (); + open_in_view_files = g_queue_new (); + open_in_app_uris = g_queue_new (); + + for (l = parameters->locations; l != NULL; l = l->next) + { + location = l->data; + file = location->file; + + if (file_was_cancelled (file)) + { + continue; + } + + action = get_activation_action (file); + if (action == ACTIVATION_ACTION_ASK) + { + /* Special case for executable text files, since it might be + * dangerous & unexpected to launch these. + */ + pause_activation_timed_cancel (parameters); + action = get_executable_text_file_action (parameters->parent_window, file); + unpause_activation_timed_cancel (parameters); + } + + switch (action) + { + case ACTIVATION_ACTION_LAUNCH_DESKTOP_FILE: + { + g_queue_push_tail (launch_desktop_files, file); + } + break; + + case ACTIVATION_ACTION_LAUNCH: + { + g_queue_push_tail (launch_files, file); + } + break; + + case ACTIVATION_ACTION_LAUNCH_IN_TERMINAL: + { + g_queue_push_tail (launch_in_terminal_files, file); + } + break; + + case ACTIVATION_ACTION_OPEN_IN_VIEW: + { + g_queue_push_tail (open_in_view_files, file); + } + break; + + case ACTIVATION_ACTION_OPEN_IN_APPLICATION: + { + g_queue_push_tail (open_in_app_uris, location->uri); + } + break; + + case ACTIVATION_ACTION_DO_NOTHING: + { + } + break; + + case ACTIVATION_ACTION_EXTRACT: + { + /* Extraction of files should be handled in the view */ + g_assert_not_reached (); + } + break; + + case ACTIVATION_ACTION_ASK: + { + g_assert_not_reached (); + } + break; + } + } + + for (l = g_queue_peek_head_link (launch_desktop_files); l != NULL; l = l->next) + { + file = NAUTILUS_FILE (l->data); + + activate_desktop_file (parameters, file); + } + + if (parameters->activation_directory && + (!g_queue_is_empty (launch_files) || + !g_queue_is_empty (launch_in_terminal_files))) + { + old_working_dir = g_get_current_dir (); + g_chdir (parameters->activation_directory); + } + + screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window)); + for (l = g_queue_peek_head_link (launch_files); l != NULL; l = l->next) + { + g_autofree char *uri = NULL; + g_autofree char *executable_path = NULL; + g_autofree char *quoted_path = NULL; + + file = NAUTILUS_FILE (l->data); + + uri = nautilus_file_get_activation_uri (file); + executable_path = g_filename_from_uri (uri, NULL, NULL); + quoted_path = g_shell_quote (executable_path); + + DEBUG (""Launching file path %s"", quoted_path); + + nautilus_launch_application_from_command (screen, quoted_path, FALSE, NULL); + } + + for (l = g_queue_peek_head_link (launch_in_terminal_files); l != NULL; l = l->next) + { + g_autofree char *uri = NULL; + g_autofree char *executable_path = NULL; + g_autofree char *quoted_path = NULL; + + file = NAUTILUS_FILE (l->data); + + uri = nautilus_file_get_activation_uri (file); + executable_path = g_filename_from_uri (uri, NULL, NULL); + quoted_path = g_shell_quote (executable_path); + + DEBUG (""Launching in terminal file quoted path %s"", quoted_path); + + nautilus_launch_application_from_command (screen, quoted_path, TRUE, NULL); + } + + if (old_working_dir != NULL) + { + g_chdir (old_working_dir); + } + + count = g_queue_get_length (open_in_view_files); + + flags = parameters->flags; + if (count > 1) + { + if ((parameters->flags & NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW) == 0) + { + /* if CLOSE_BEHIND is set and we have a directory to be activated, we + * will first have to open a new window and after that we can open the + * rest of files in tabs */ + if ((parameters->flags & NAUTILUS_WINDOW_OPEN_FLAG_CLOSE_BEHIND) != 0) + { + flags |= NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW; + } + else + { + flags |= NAUTILUS_WINDOW_OPEN_FLAG_NEW_TAB; + } + } + else + { + flags |= NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW; + } + } + else + { + /* if we want to close the window and activate a single directory, then we will need + * the NEW_WINDOW flag set */ + if ((parameters->flags & NAUTILUS_WINDOW_OPEN_FLAG_CLOSE_BEHIND) != 0) + { + flags |= NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW; + } + } + + if (parameters->slot != NULL && + (!parameters->user_confirmation || + confirm_multiple_windows (parameters->parent_window, count, + (flags & NAUTILUS_WINDOW_OPEN_FLAG_NEW_TAB) != 0))) + { + if ((flags & NAUTILUS_WINDOW_OPEN_FLAG_NEW_TAB) != 0 && + g_settings_get_enum (nautilus_preferences, NAUTILUS_PREFERENCES_NEW_TAB_POSITION) == + NAUTILUS_NEW_TAB_POSITION_AFTER_CURRENT_TAB) + { + /* When inserting N tabs after the current one, + * we first open tab N, then tab N-1, ..., then tab 0. + * Each of them is appended to the current tab, i.e. + * prepended to the list of tabs to open. + */ + g_queue_reverse (open_in_view_files); + } + + closed_window = FALSE; + + for (l = g_queue_peek_head_link (open_in_view_files); l != NULL; l = l->next) + { + g_autofree char *uri = NULL; + g_autoptr (GFile) location = NULL; + g_autoptr (GFile) location_with_permissions = NULL; + /* The ui should ask for navigation or object windows + * depending on what the current one is */ + file = NAUTILUS_FILE (l->data); + uri = nautilus_file_get_activation_uri (file); + location = g_file_new_for_uri (uri); + if (g_file_is_native (location) && + (nautilus_file_is_in_admin (file) || + !nautilus_file_can_read (file) || + !nautilus_file_can_execute (file))) + { + g_autofree gchar *file_path = NULL; + + g_free (uri); + + file_path = g_file_get_path (location); + uri = g_strconcat (""admin://"", file_path, NULL); + } + + location_with_permissions = g_file_new_for_uri (uri); + /* FIXME: we need to pass the parent_window, but we only use it for the current active window, + * which nautilus-application should take care of. However is not working and creating regressions + * in some cases. Until we figure out what's going on, continue to use the parameters->slot + * to make splicit the window we want to use for activating the files */ + nautilus_application_open_location_full (NAUTILUS_APPLICATION (g_application_get_default ()), + location_with_permissions, flags, NULL, NULL, parameters->slot); + + /* close only the window from which the action was launched and then open + * tabs/windows (depending on parameters->flags) */ + if (!closed_window && (flags & NAUTILUS_WINDOW_OPEN_FLAG_CLOSE_BEHIND) != 0) + { + flags &= (~NAUTILUS_WINDOW_OPEN_FLAG_CLOSE_BEHIND); + + /* if NEW_WINDOW is set, we want all files in new windows, not in tabs */ + if ((parameters->flags & NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW) == 0) + { + flags &= (~NAUTILUS_WINDOW_OPEN_FLAG_NEW_WINDOW); + flags |= NAUTILUS_WINDOW_OPEN_FLAG_NEW_TAB; + } + + closed_window = TRUE; + } + } + } + + if (open_in_app_uris != NULL) + { + open_in_app_parameters = make_activation_parameters (g_queue_peek_head_link (open_in_app_uris), + &unhandled_open_in_app_uris); + } + + num_apps = g_list_length (open_in_app_parameters); + num_unhandled = g_list_length (unhandled_open_in_app_uris); + num_files = g_queue_get_length (open_in_app_uris); + open_files = TRUE; + + if (g_queue_is_empty (open_in_app_uris) && + (!parameters->user_confirmation || + num_files + num_unhandled > SILENT_OPEN_LIMIT) && + num_apps > 1) + { + GtkDialog *dialog; + char *prompt; + g_autofree char *detail = NULL; + int response; + + pause_activation_timed_cancel (parameters); + + prompt = _(""Are you sure you want to open all files?""); + detail = g_strdup_printf (ngettext (""This will open %d separate application."", + ""This will open %d separate applications."", num_apps), num_apps); + dialog = eel_show_yes_no_dialog (prompt, detail, + _(""_OK""), _(""_Cancel""), + parameters->parent_window); + response = gtk_dialog_run (dialog); + gtk_widget_destroy (GTK_WIDGET (dialog)); + + unpause_activation_timed_cancel (parameters); + + if (response != GTK_RESPONSE_YES) + { + open_files = FALSE; + } + } + + if (open_files) + { + for (l = open_in_app_parameters; l != NULL; l = l->next) + { + one_parameters = l->data; + + nautilus_launch_application_by_uri (one_parameters->application, + one_parameters->uris, + parameters->parent_window); + application_launch_parameters_free (one_parameters); + } + + for (l = unhandled_open_in_app_uris; l != NULL; l = l->next) + { + char *uri = l->data; + + /* this does not block */ + application_unhandled_uri (parameters, uri); + } + } + + window = NULL; + if (parameters->slot != NULL) + { + window = nautilus_window_slot_get_window (parameters->slot); + } + + if (open_in_app_parameters != NULL || + unhandled_open_in_app_uris != NULL) + { + if ((parameters->flags & NAUTILUS_WINDOW_OPEN_FLAG_CLOSE_BEHIND) != 0 && + window != NULL) + { + nautilus_window_close (window); + } + } + + activation_parameters_free (parameters); +} +","@@ -42,6 +42,7 @@ + #include ""nautilus-program-choosing.h"" + #include ""nautilus-global-preferences.h"" + #include ""nautilus-signaller.h"" ++#include ""nautilus-metadata.h"" + + #define DEBUG_FLAG NAUTILUS_DEBUG_MIME + #include ""nautilus-debug.h"" +@@ -221,7 +222,6 @@ struct + #define RESPONSE_RUN 1000 + #define RESPONSE_DISPLAY 1001 + #define RESPONSE_RUN_IN_TERMINAL 1002 +-#define RESPONSE_MARK_TRUSTED 1003 + + #define SILENT_WINDOW_OPEN_LIMIT 5 + #define SILENT_OPEN_LIMIT 5 +@@ -1517,24 +1517,35 @@ untrusted_launcher_response_callback (GtkDialog *dialog, + + switch (response_id) + { +- case RESPONSE_RUN: ++ case GTK_RESPONSE_OK: + { ++ file = nautilus_file_get_location (parameters->file); ++ ++ /* We need to do this in order to prevent malicious desktop files ++ * with the executable bit already set. ++ * See https://bugzilla.gnome.org/show_bug.cgi?id=777991 ++ */ ++ nautilus_file_set_metadata (parameters->file, NAUTILUS_METADATA_KEY_DESKTOP_FILE_TRUSTED, ++ NULL, ++ ""yes""); ++ ++ nautilus_file_mark_desktop_file_executable (file, ++ parameters->parent_window, ++ TRUE, ++ NULL, NULL); ++ ++ /* Need to force a reload of the attributes so is_trusted is marked ++ * correctly. Not sure why the general monitor doesn't fire in this ++ * case when setting the metadata ++ */ ++ nautilus_file_invalidate_all_attributes (parameters->file); ++ + screen = gtk_widget_get_screen (GTK_WIDGET (parameters->parent_window)); + uri = nautilus_file_get_uri (parameters->file); + DEBUG (""Launching untrusted launcher %s"", uri); + nautilus_launch_desktop_file (screen, uri, NULL, + parameters->parent_window); + g_free (uri); +- } +- break; +- +- case RESPONSE_MARK_TRUSTED: +- { +- file = nautilus_file_get_location (parameters->file); +- nautilus_file_mark_desktop_file_trusted (file, +- parameters->parent_window, +- TRUE, +- NULL, NULL); + g_object_unref (file); + } + break; +@@ -1590,17 +1601,16 @@ activate_desktop_file (ActivateParameters *parameters, + ""text"", primary, + ""secondary-text"", secondary, + NULL); ++ + gtk_dialog_add_button (GTK_DIALOG (dialog), +- _(""_Launch Anyway""), RESPONSE_RUN); ++ _(""_Cancel""), GTK_RESPONSE_CANCEL); ++ ++ gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_CANCEL); + if (nautilus_file_can_set_permissions (file)) + { + gtk_dialog_add_button (GTK_DIALOG (dialog), +- _(""Mark as _Trusted""), RESPONSE_MARK_TRUSTED); ++ _(""Trust and _Launch""), GTK_RESPONSE_OK); + } +- gtk_dialog_add_button (GTK_DIALOG (dialog), +- _(""_Cancel""), GTK_RESPONSE_CANCEL); +- gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_CANCEL); +- + g_signal_connect (dialog, ""response"", + G_CALLBACK (untrusted_launcher_response_callback), + parameters_desktop);",2549,2880,4096 +18030,"static ssize_t hfi1_file_write(struct file *fp, const char __user *data, + size_t count, loff_t *offset) +{ + const struct hfi1_cmd __user *ucmd; + struct hfi1_filedata *fd = fp->private_data; + struct hfi1_ctxtdata *uctxt = fd->uctxt; + struct hfi1_cmd cmd; + struct hfi1_user_info uinfo; + struct hfi1_tid_info tinfo; + unsigned long addr; + ssize_t consumed = 0, copy = 0, ret = 0; + void *dest = NULL; + __u64 user_val = 0; + int uctxt_required = 1; + int must_be_root = 0; + + if (count < sizeof(cmd)) { + ret = -EINVAL; + goto bail; + } + + ucmd = (const struct hfi1_cmd __user *)data; + if (copy_from_user(&cmd, ucmd, sizeof(cmd))) { + ret = -EFAULT; + goto bail; + } + + consumed = sizeof(cmd); + + switch (cmd.type) { + case HFI1_CMD_ASSIGN_CTXT: + uctxt_required = 0; /* assigned user context not required */ + copy = sizeof(uinfo); + dest = &uinfo; + break; + case HFI1_CMD_SDMA_STATUS_UPD: + case HFI1_CMD_CREDIT_UPD: + copy = 0; + break; + case HFI1_CMD_TID_UPDATE: + case HFI1_CMD_TID_FREE: + case HFI1_CMD_TID_INVAL_READ: + copy = sizeof(tinfo); + dest = &tinfo; + break; + case HFI1_CMD_USER_INFO: + case HFI1_CMD_RECV_CTRL: + case HFI1_CMD_POLL_TYPE: + case HFI1_CMD_ACK_EVENT: + case HFI1_CMD_CTXT_INFO: + case HFI1_CMD_SET_PKEY: + case HFI1_CMD_CTXT_RESET: + copy = 0; + user_val = cmd.addr; + break; + case HFI1_CMD_EP_INFO: + case HFI1_CMD_EP_ERASE_CHIP: + case HFI1_CMD_EP_ERASE_RANGE: + case HFI1_CMD_EP_READ_RANGE: + case HFI1_CMD_EP_WRITE_RANGE: + uctxt_required = 0; /* assigned user context not required */ + must_be_root = 1; /* validate user */ + copy = 0; + break; + default: + ret = -EINVAL; + goto bail; + } + + /* If the command comes with user data, copy it. */ + if (copy) { + if (copy_from_user(dest, (void __user *)cmd.addr, copy)) { + ret = -EFAULT; + goto bail; + } + consumed += copy; + } + + /* + * Make sure there is a uctxt when needed. + */ + if (uctxt_required && !uctxt) { + ret = -EINVAL; + goto bail; + } + + /* only root can do these operations */ + if (must_be_root && !capable(CAP_SYS_ADMIN)) { + ret = -EPERM; + goto bail; + } + + switch (cmd.type) { + case HFI1_CMD_ASSIGN_CTXT: + ret = assign_ctxt(fp, &uinfo); + if (ret < 0) + goto bail; + ret = setup_ctxt(fp); + if (ret) + goto bail; + ret = user_init(fp); + break; + case HFI1_CMD_CTXT_INFO: + ret = get_ctxt_info(fp, (void __user *)(unsigned long) + user_val, cmd.len); + break; + case HFI1_CMD_USER_INFO: + ret = get_base_info(fp, (void __user *)(unsigned long) + user_val, cmd.len); + break; + case HFI1_CMD_SDMA_STATUS_UPD: + break; + case HFI1_CMD_CREDIT_UPD: + if (uctxt && uctxt->sc) + sc_return_credits(uctxt->sc); + break; + case HFI1_CMD_TID_UPDATE: + ret = hfi1_user_exp_rcv_setup(fp, &tinfo); + if (!ret) { + /* + * Copy the number of tidlist entries we used + * and the length of the buffer we registered. + * These fields are adjacent in the structure so + * we can copy them at the same time. + */ + addr = (unsigned long)cmd.addr + + offsetof(struct hfi1_tid_info, tidcnt); + if (copy_to_user((void __user *)addr, &tinfo.tidcnt, + sizeof(tinfo.tidcnt) + + sizeof(tinfo.length))) + ret = -EFAULT; + } + break; + case HFI1_CMD_TID_INVAL_READ: + ret = hfi1_user_exp_rcv_invalid(fp, &tinfo); + if (ret) + break; + addr = (unsigned long)cmd.addr + + offsetof(struct hfi1_tid_info, tidcnt); + if (copy_to_user((void __user *)addr, &tinfo.tidcnt, + sizeof(tinfo.tidcnt))) + ret = -EFAULT; + break; + case HFI1_CMD_TID_FREE: + ret = hfi1_user_exp_rcv_clear(fp, &tinfo); + if (ret) + break; + addr = (unsigned long)cmd.addr + + offsetof(struct hfi1_tid_info, tidcnt); + if (copy_to_user((void __user *)addr, &tinfo.tidcnt, + sizeof(tinfo.tidcnt))) + ret = -EFAULT; + break; + case HFI1_CMD_RECV_CTRL: + ret = manage_rcvq(uctxt, fd->subctxt, (int)user_val); + break; + case HFI1_CMD_POLL_TYPE: + uctxt->poll_type = (typeof(uctxt->poll_type))user_val; + break; + case HFI1_CMD_ACK_EVENT: + ret = user_event_ack(uctxt, fd->subctxt, user_val); + break; + case HFI1_CMD_SET_PKEY: + if (HFI1_CAP_IS_USET(PKEY_CHECK)) + ret = set_ctxt_pkey(uctxt, fd->subctxt, user_val); + else + ret = -EPERM; + break; + case HFI1_CMD_CTXT_RESET: { + struct send_context *sc; + struct hfi1_devdata *dd; + + if (!uctxt || !uctxt->dd || !uctxt->sc) { + ret = -EINVAL; + break; + } + /* + * There is no protection here. User level has to + * guarantee that no one will be writing to the send + * context while it is being re-initialized. + * If user level breaks that guarantee, it will break + * it's own context and no one else's. + */ + dd = uctxt->dd; + sc = uctxt->sc; + /* + * Wait until the interrupt handler has marked the + * context as halted or frozen. Report error if we time + * out. + */ + wait_event_interruptible_timeout( + sc->halt_wait, (sc->flags & SCF_HALTED), + msecs_to_jiffies(SEND_CTXT_HALT_TIMEOUT)); + if (!(sc->flags & SCF_HALTED)) { + ret = -ENOLCK; + break; + } + /* + * If the send context was halted due to a Freeze, + * wait until the device has been ""unfrozen"" before + * resetting the context. + */ + if (sc->flags & SCF_FROZEN) { + wait_event_interruptible_timeout( + dd->event_queue, + !(ACCESS_ONCE(dd->flags) & HFI1_FROZEN), + msecs_to_jiffies(SEND_CTXT_HALT_TIMEOUT)); + if (dd->flags & HFI1_FROZEN) { + ret = -ENOLCK; + break; + } + if (dd->flags & HFI1_FORCED_FREEZE) { + /* + * Don't allow context reset if we are into + * forced freeze + */ + ret = -ENODEV; + break; + } + sc_disable(sc); + ret = sc_enable(sc); + hfi1_rcvctrl(dd, HFI1_RCVCTRL_CTXT_ENB, + uctxt->ctxt); + } else { + ret = sc_restart(sc); + } + if (!ret) + sc_return_credits(sc); + break; + } + case HFI1_CMD_EP_INFO: + case HFI1_CMD_EP_ERASE_CHIP: + case HFI1_CMD_EP_ERASE_RANGE: + case HFI1_CMD_EP_READ_RANGE: + case HFI1_CMD_EP_WRITE_RANGE: + ret = handle_eprom_command(fp, &cmd); + break; + } + + if (ret >= 0) + ret = consumed; +bail: + return ret; +} +",1,"static ssize_t hfi1_file_write(struct file *fp, const char __user *data, + size_t count, loff_t *offset) +{ + const struct hfi1_cmd __user *ucmd; + struct hfi1_filedata *fd = fp->private_data; + struct hfi1_ctxtdata *uctxt = fd->uctxt; + struct hfi1_cmd cmd; + struct hfi1_user_info uinfo; + struct hfi1_tid_info tinfo; + unsigned long addr; + ssize_t consumed = 0, copy = 0, ret = 0; + void *dest = NULL; + __u64 user_val = 0; + int uctxt_required = 1; + int must_be_root = 0; + + /* FIXME: This interface cannot continue out of staging */ + if (WARN_ON_ONCE(!ib_safe_file_access(fp))) + return -EACCES; + + if (count < sizeof(cmd)) { + ret = -EINVAL; + goto bail; + } + + ucmd = (const struct hfi1_cmd __user *)data; + if (copy_from_user(&cmd, ucmd, sizeof(cmd))) { + ret = -EFAULT; + goto bail; + } + + consumed = sizeof(cmd); + + switch (cmd.type) { + case HFI1_CMD_ASSIGN_CTXT: + uctxt_required = 0; /* assigned user context not required */ + copy = sizeof(uinfo); + dest = &uinfo; + break; + case HFI1_CMD_SDMA_STATUS_UPD: + case HFI1_CMD_CREDIT_UPD: + copy = 0; + break; + case HFI1_CMD_TID_UPDATE: + case HFI1_CMD_TID_FREE: + case HFI1_CMD_TID_INVAL_READ: + copy = sizeof(tinfo); + dest = &tinfo; + break; + case HFI1_CMD_USER_INFO: + case HFI1_CMD_RECV_CTRL: + case HFI1_CMD_POLL_TYPE: + case HFI1_CMD_ACK_EVENT: + case HFI1_CMD_CTXT_INFO: + case HFI1_CMD_SET_PKEY: + case HFI1_CMD_CTXT_RESET: + copy = 0; + user_val = cmd.addr; + break; + case HFI1_CMD_EP_INFO: + case HFI1_CMD_EP_ERASE_CHIP: + case HFI1_CMD_EP_ERASE_RANGE: + case HFI1_CMD_EP_READ_RANGE: + case HFI1_CMD_EP_WRITE_RANGE: + uctxt_required = 0; /* assigned user context not required */ + must_be_root = 1; /* validate user */ + copy = 0; + break; + default: + ret = -EINVAL; + goto bail; + } + + /* If the command comes with user data, copy it. */ + if (copy) { + if (copy_from_user(dest, (void __user *)cmd.addr, copy)) { + ret = -EFAULT; + goto bail; + } + consumed += copy; + } + + /* + * Make sure there is a uctxt when needed. + */ + if (uctxt_required && !uctxt) { + ret = -EINVAL; + goto bail; + } + + /* only root can do these operations */ + if (must_be_root && !capable(CAP_SYS_ADMIN)) { + ret = -EPERM; + goto bail; + } + + switch (cmd.type) { + case HFI1_CMD_ASSIGN_CTXT: + ret = assign_ctxt(fp, &uinfo); + if (ret < 0) + goto bail; + ret = setup_ctxt(fp); + if (ret) + goto bail; + ret = user_init(fp); + break; + case HFI1_CMD_CTXT_INFO: + ret = get_ctxt_info(fp, (void __user *)(unsigned long) + user_val, cmd.len); + break; + case HFI1_CMD_USER_INFO: + ret = get_base_info(fp, (void __user *)(unsigned long) + user_val, cmd.len); + break; + case HFI1_CMD_SDMA_STATUS_UPD: + break; + case HFI1_CMD_CREDIT_UPD: + if (uctxt && uctxt->sc) + sc_return_credits(uctxt->sc); + break; + case HFI1_CMD_TID_UPDATE: + ret = hfi1_user_exp_rcv_setup(fp, &tinfo); + if (!ret) { + /* + * Copy the number of tidlist entries we used + * and the length of the buffer we registered. + * These fields are adjacent in the structure so + * we can copy them at the same time. + */ + addr = (unsigned long)cmd.addr + + offsetof(struct hfi1_tid_info, tidcnt); + if (copy_to_user((void __user *)addr, &tinfo.tidcnt, + sizeof(tinfo.tidcnt) + + sizeof(tinfo.length))) + ret = -EFAULT; + } + break; + case HFI1_CMD_TID_INVAL_READ: + ret = hfi1_user_exp_rcv_invalid(fp, &tinfo); + if (ret) + break; + addr = (unsigned long)cmd.addr + + offsetof(struct hfi1_tid_info, tidcnt); + if (copy_to_user((void __user *)addr, &tinfo.tidcnt, + sizeof(tinfo.tidcnt))) + ret = -EFAULT; + break; + case HFI1_CMD_TID_FREE: + ret = hfi1_user_exp_rcv_clear(fp, &tinfo); + if (ret) + break; + addr = (unsigned long)cmd.addr + + offsetof(struct hfi1_tid_info, tidcnt); + if (copy_to_user((void __user *)addr, &tinfo.tidcnt, + sizeof(tinfo.tidcnt))) + ret = -EFAULT; + break; + case HFI1_CMD_RECV_CTRL: + ret = manage_rcvq(uctxt, fd->subctxt, (int)user_val); + break; + case HFI1_CMD_POLL_TYPE: + uctxt->poll_type = (typeof(uctxt->poll_type))user_val; + break; + case HFI1_CMD_ACK_EVENT: + ret = user_event_ack(uctxt, fd->subctxt, user_val); + break; + case HFI1_CMD_SET_PKEY: + if (HFI1_CAP_IS_USET(PKEY_CHECK)) + ret = set_ctxt_pkey(uctxt, fd->subctxt, user_val); + else + ret = -EPERM; + break; + case HFI1_CMD_CTXT_RESET: { + struct send_context *sc; + struct hfi1_devdata *dd; + + if (!uctxt || !uctxt->dd || !uctxt->sc) { + ret = -EINVAL; + break; + } + /* + * There is no protection here. User level has to + * guarantee that no one will be writing to the send + * context while it is being re-initialized. + * If user level breaks that guarantee, it will break + * it's own context and no one else's. + */ + dd = uctxt->dd; + sc = uctxt->sc; + /* + * Wait until the interrupt handler has marked the + * context as halted or frozen. Report error if we time + * out. + */ + wait_event_interruptible_timeout( + sc->halt_wait, (sc->flags & SCF_HALTED), + msecs_to_jiffies(SEND_CTXT_HALT_TIMEOUT)); + if (!(sc->flags & SCF_HALTED)) { + ret = -ENOLCK; + break; + } + /* + * If the send context was halted due to a Freeze, + * wait until the device has been ""unfrozen"" before + * resetting the context. + */ + if (sc->flags & SCF_FROZEN) { + wait_event_interruptible_timeout( + dd->event_queue, + !(ACCESS_ONCE(dd->flags) & HFI1_FROZEN), + msecs_to_jiffies(SEND_CTXT_HALT_TIMEOUT)); + if (dd->flags & HFI1_FROZEN) { + ret = -ENOLCK; + break; + } + if (dd->flags & HFI1_FORCED_FREEZE) { + /* + * Don't allow context reset if we are into + * forced freeze + */ + ret = -ENODEV; + break; + } + sc_disable(sc); + ret = sc_enable(sc); + hfi1_rcvctrl(dd, HFI1_RCVCTRL_CTXT_ENB, + uctxt->ctxt); + } else { + ret = sc_restart(sc); + } + if (!ret) + sc_return_credits(sc); + break; + } + case HFI1_CMD_EP_INFO: + case HFI1_CMD_EP_ERASE_CHIP: + case HFI1_CMD_EP_ERASE_RANGE: + case HFI1_CMD_EP_READ_RANGE: + case HFI1_CMD_EP_WRITE_RANGE: + ret = handle_eprom_command(fp, &cmd); + break; + } + + if (ret >= 0) + ret = consumed; +bail: + return ret; +} +","@@ -49,6 +49,8 @@ + #include + #include + ++#include ++ + #include ""hfi.h"" + #include ""pio.h"" + #include ""device.h"" +@@ -190,6 +192,10 @@ static ssize_t hfi1_file_write(struct file *fp, const char __user *data, + int uctxt_required = 1; + int must_be_root = 0; + ++ /* FIXME: This interface cannot continue out of staging */ ++ if (WARN_ON_ONCE(!ib_safe_file_access(fp))) ++ return -EACCES; ++ + if (count < sizeof(cmd)) { + ret = -EINVAL; + goto bail;",1906,2237,4096 +18276,"MagickExport MagickBooleanType AnnotateImage(Image *image, + const DrawInfo *draw_info) +{ + char + *p, + primitive[MaxTextExtent], + *text, + **textlist; + + DrawInfo + *annotate, + *annotate_info; + + GeometryInfo + geometry_info; + + MagickBooleanType + status; + + PointInfo + offset; + + RectangleInfo + geometry; + + register ssize_t + i; + + TypeMetric + metrics; + + size_t + height, + number_lines; + + assert(image != (Image *) NULL); + assert(image->signature == MagickCoreSignature); + if (image->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); + assert(draw_info != (DrawInfo *) NULL); + assert(draw_info->signature == MagickCoreSignature); + if (draw_info->text == (char *) NULL) + return(MagickFalse); + if (*draw_info->text == '\0') + return(MagickTrue); + annotate=CloneDrawInfo((ImageInfo *) NULL,draw_info); + text=annotate->text; + annotate->text=(char *) NULL; + annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); + number_lines=1; + for (p=text; *p != '\0'; p++) + if (*p == '\n') + number_lines++; + textlist=AcquireQuantumMemory(number_lines+1,sizeof(*textlist)); + if (textlist == (char **) NULL) + { + annotate_info=DestroyDrawInfo(annotate_info); + annotate=DestroyDrawInfo(annotate); + return(MagickFalse); + } + p=text; + for (i=0; i < number_lines; i++) + { + char + *q; + + textlist[i]=p; + for (q=p; *q != '\0'; q++) + if ((*q == '\r') || (*q == '\n')) + break; + if (*q == '\r') + { + *q='\0'; + q++; + } + *q='\0'; + p=q+1; + } + textlist[i]=(char *) NULL; + SetGeometry(image,&geometry); + SetGeometryInfo(&geometry_info); + if (annotate_info->geometry != (char *) NULL) + { + (void) ParsePageGeometry(image,annotate_info->geometry,&geometry, + &image->exception); + (void) ParseGeometry(annotate_info->geometry,&geometry_info); + } + if (SetImageStorageClass(image,DirectClass) == MagickFalse) + { + annotate_info=DestroyDrawInfo(annotate_info); + annotate=DestroyDrawInfo(annotate); + textlist=(char **) RelinquishMagickMemory(textlist); + return(MagickFalse); + } + if (IsGrayColorspace(image->colorspace) != MagickFalse) + (void) SetImageColorspace(image,sRGBColorspace); + status=MagickTrue; + (void) memset(&metrics,0,sizeof(metrics)); + for (i=0; textlist[i] != (char *) NULL; i++) + { + if (*textlist[i] == '\0') + continue; + /* + Position text relative to image. + */ + annotate_info->affine.tx=geometry_info.xi-image->page.x; + annotate_info->affine.ty=geometry_info.psi-image->page.y; + (void) CloneString(&annotate->text,textlist[i]); + if ((metrics.width == 0) || (annotate->gravity != NorthWestGravity)) + (void) GetTypeMetrics(image,annotate,&metrics); + height=(ssize_t) (metrics.ascent-metrics.descent+ + draw_info->interline_spacing+0.5); + switch (annotate->gravity) + { + case UndefinedGravity: + default: + { + offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height; + offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height; + break; + } + case NorthWestGravity: + { + offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i* + annotate_info->affine.ry*height+annotate_info->affine.ry* + (metrics.ascent+metrics.descent); + offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i* + annotate_info->affine.sy*height+annotate_info->affine.sy* + metrics.ascent; + break; + } + case NorthGravity: + { + offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+ + geometry.width/2.0+i*annotate_info->affine.ry*height- + annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry* + (metrics.ascent+metrics.descent); + offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i* + annotate_info->affine.sy*height+annotate_info->affine.sy* + metrics.ascent-annotate_info->affine.rx*metrics.width/2.0; + break; + } + case NorthEastGravity: + { + offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+ + geometry.width+i*annotate_info->affine.ry*height- + annotate_info->affine.sx*metrics.width+annotate_info->affine.ry* + (metrics.ascent+metrics.descent)-1.0; + offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i* + annotate_info->affine.sy*height+annotate_info->affine.sy* + metrics.ascent-annotate_info->affine.rx*metrics.width; + break; + } + case WestGravity: + { + offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i* + annotate_info->affine.ry*height+annotate_info->affine.ry* + (metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0; + offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+ + geometry.height/2.0+i*annotate_info->affine.sy*height+ + annotate_info->affine.sy*(metrics.ascent+metrics.descent- + (number_lines-1.0)*height)/2.0; + break; + } + case StaticGravity: + case CenterGravity: + { + offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+ + geometry.width/2.0+i*annotate_info->affine.ry*height- + annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry* + (metrics.ascent+metrics.descent-(number_lines-1)*height)/2.0; + offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+ + geometry.height/2.0+i*annotate_info->affine.sy*height- + annotate_info->affine.rx*metrics.width/2.0+annotate_info->affine.sy* + (metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0; + break; + } + case EastGravity: + { + offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+ + geometry.width+i*annotate_info->affine.ry*height- + annotate_info->affine.sx*metrics.width+annotate_info->affine.ry* + (metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0-1.0; + offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+ + geometry.height/2.0+i*annotate_info->affine.sy*height- + annotate_info->affine.rx*metrics.width+annotate_info->affine.sy* + (metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0; + break; + } + case SouthWestGravity: + { + offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i* + annotate_info->affine.ry*height-annotate_info->affine.ry* + (number_lines-1.0)*height; + offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+ + geometry.height+i*annotate_info->affine.sy*height- + annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent; + break; + } + case SouthGravity: + { + offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+ + geometry.width/2.0+i*annotate_info->affine.ry*height- + annotate_info->affine.sx*metrics.width/2.0-annotate_info->affine.ry* + (number_lines-1.0)*height/2.0; + offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+ + geometry.height+i*annotate_info->affine.sy*height- + annotate_info->affine.rx*metrics.width/2.0-annotate_info->affine.sy* + (number_lines-1.0)*height+metrics.descent; + break; + } + case SouthEastGravity: + { + offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+ + geometry.width+i*annotate_info->affine.ry*height- + annotate_info->affine.sx*metrics.width-annotate_info->affine.ry* + (number_lines-1.0)*height-1.0; + offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+ + geometry.height+i*annotate_info->affine.sy*height- + annotate_info->affine.rx*metrics.width-annotate_info->affine.sy* + (number_lines-1.0)*height+metrics.descent; + break; + } + } + switch (annotate->align) + { + case LeftAlign: + { + offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height; + offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height; + break; + } + case CenterAlign: + { + offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height- + annotate_info->affine.sx*metrics.width/2.0; + offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height- + annotate_info->affine.rx*metrics.width/2.0; + break; + } + case RightAlign: + { + offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height- + annotate_info->affine.sx*metrics.width; + offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height- + annotate_info->affine.rx*metrics.width; + break; + } + default: + break; + } + if (draw_info->undercolor.opacity != TransparentOpacity) + { + DrawInfo + *undercolor_info; + + /* + Text box. + */ + undercolor_info=CloneDrawInfo((ImageInfo *) NULL,(DrawInfo *) NULL); + undercolor_info->fill=draw_info->undercolor; + undercolor_info->affine=draw_info->affine; + undercolor_info->affine.tx=offset.x-draw_info->affine.ry*metrics.ascent; + undercolor_info->affine.ty=offset.y-draw_info->affine.sy*metrics.ascent; + (void) FormatLocaleString(primitive,MaxTextExtent, + ""rectangle 0.0,0.0 %g,%g"",metrics.origin.x,(double) height); + (void) CloneString(&undercolor_info->primitive,primitive); + (void) DrawImage(image,undercolor_info); + (void) DestroyDrawInfo(undercolor_info); + } + annotate_info->affine.tx=offset.x; + annotate_info->affine.ty=offset.y; + (void) FormatLocaleString(primitive,MaxTextExtent,""stroke-width %g "" + ""line 0,0 %g,0"",metrics.underline_thickness,metrics.width); + if (annotate->decorate == OverlineDecoration) + { + annotate_info->affine.ty-=(draw_info->affine.sy*(metrics.ascent+ + metrics.descent-metrics.underline_position)); + (void) CloneString(&annotate_info->primitive,primitive); + (void) DrawImage(image,annotate_info); + } + else + if (annotate->decorate == UnderlineDecoration) + { + annotate_info->affine.ty-=(draw_info->affine.sy* + metrics.underline_position); + (void) CloneString(&annotate_info->primitive,primitive); + (void) DrawImage(image,annotate_info); + } + /* + Annotate image with text. + */ + status=RenderType(image,annotate,&offset,&metrics); + if (status == MagickFalse) + break; + if (annotate->decorate == LineThroughDecoration) + { + annotate_info->affine.ty-=(draw_info->affine.sy*(height+ + metrics.underline_position+metrics.descent)/2.0); + (void) CloneString(&annotate_info->primitive,primitive); + (void) DrawImage(image,annotate_info); + } + } + /* + Relinquish resources. + */ + annotate_info=DestroyDrawInfo(annotate_info); + annotate=DestroyDrawInfo(annotate); + textlist=(char **) RelinquishMagickMemory(textlist); + return(status); + } +",1,"MagickExport MagickBooleanType AnnotateImage(Image *image, + const DrawInfo *draw_info) +{ + char + *p, + primitive[MaxTextExtent], + *text, + **textlist; + + DrawInfo + *annotate, + *annotate_info; + + GeometryInfo + geometry_info; + + MagickBooleanType + status; + + PointInfo + offset; + + RectangleInfo + geometry; + + register ssize_t + i; + + TypeMetric + metrics; + + size_t + height, + number_lines; + + assert(image != (Image *) NULL); + assert(image->signature == MagickCoreSignature); + if (image->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); + assert(draw_info != (DrawInfo *) NULL); + assert(draw_info->signature == MagickCoreSignature); + if (draw_info->text == (char *) NULL) + return(MagickFalse); + if (*draw_info->text == '\0') + return(MagickTrue); + annotate=CloneDrawInfo((ImageInfo *) NULL,draw_info); + text=annotate->text; + annotate->text=(char *) NULL; + annotate_info=CloneDrawInfo((ImageInfo *) NULL,draw_info); + number_lines=1; + for (p=text; *p != '\0'; p++) + if (*p == '\n') + number_lines++; + textlist=AcquireQuantumMemory(number_lines+1,sizeof(*textlist)); + if (textlist == (char **) NULL) + { + annotate_info=DestroyDrawInfo(annotate_info); + annotate=DestroyDrawInfo(annotate); + text=DestroyString(text); + return(MagickFalse); + } + p=text; + for (i=0; i < number_lines; i++) + { + char + *q; + + textlist[i]=p; + for (q=p; *q != '\0'; q++) + if ((*q == '\r') || (*q == '\n')) + break; + if (*q == '\r') + { + *q='\0'; + q++; + } + *q='\0'; + p=q+1; + } + textlist[i]=(char *) NULL; + SetGeometry(image,&geometry); + SetGeometryInfo(&geometry_info); + if (annotate_info->geometry != (char *) NULL) + { + (void) ParsePageGeometry(image,annotate_info->geometry,&geometry, + &image->exception); + (void) ParseGeometry(annotate_info->geometry,&geometry_info); + } + if (SetImageStorageClass(image,DirectClass) == MagickFalse) + { + annotate_info=DestroyDrawInfo(annotate_info); + annotate=DestroyDrawInfo(annotate); + textlist=(char **) RelinquishMagickMemory(textlist); + text=DestroyString(text); + return(MagickFalse); + } + if (IsGrayColorspace(image->colorspace) != MagickFalse) + (void) SetImageColorspace(image,sRGBColorspace); + status=MagickTrue; + (void) memset(&metrics,0,sizeof(metrics)); + for (i=0; textlist[i] != (char *) NULL; i++) + { + if (*textlist[i] == '\0') + continue; + /* + Position text relative to image. + */ + annotate_info->affine.tx=geometry_info.xi-image->page.x; + annotate_info->affine.ty=geometry_info.psi-image->page.y; + (void) CloneString(&annotate->text,textlist[i]); + if ((metrics.width == 0) || (annotate->gravity != NorthWestGravity)) + (void) GetTypeMetrics(image,annotate,&metrics); + height=(ssize_t) (metrics.ascent-metrics.descent+ + draw_info->interline_spacing+0.5); + switch (annotate->gravity) + { + case UndefinedGravity: + default: + { + offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height; + offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height; + break; + } + case NorthWestGravity: + { + offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i* + annotate_info->affine.ry*height+annotate_info->affine.ry* + (metrics.ascent+metrics.descent); + offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i* + annotate_info->affine.sy*height+annotate_info->affine.sy* + metrics.ascent; + break; + } + case NorthGravity: + { + offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+ + geometry.width/2.0+i*annotate_info->affine.ry*height- + annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry* + (metrics.ascent+metrics.descent); + offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i* + annotate_info->affine.sy*height+annotate_info->affine.sy* + metrics.ascent-annotate_info->affine.rx*metrics.width/2.0; + break; + } + case NorthEastGravity: + { + offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+ + geometry.width+i*annotate_info->affine.ry*height- + annotate_info->affine.sx*metrics.width+annotate_info->affine.ry* + (metrics.ascent+metrics.descent)-1.0; + offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+i* + annotate_info->affine.sy*height+annotate_info->affine.sy* + metrics.ascent-annotate_info->affine.rx*metrics.width; + break; + } + case WestGravity: + { + offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i* + annotate_info->affine.ry*height+annotate_info->affine.ry* + (metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0; + offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+ + geometry.height/2.0+i*annotate_info->affine.sy*height+ + annotate_info->affine.sy*(metrics.ascent+metrics.descent- + (number_lines-1.0)*height)/2.0; + break; + } + case StaticGravity: + case CenterGravity: + { + offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+ + geometry.width/2.0+i*annotate_info->affine.ry*height- + annotate_info->affine.sx*metrics.width/2.0+annotate_info->affine.ry* + (metrics.ascent+metrics.descent-(number_lines-1)*height)/2.0; + offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+ + geometry.height/2.0+i*annotate_info->affine.sy*height- + annotate_info->affine.rx*metrics.width/2.0+annotate_info->affine.sy* + (metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0; + break; + } + case EastGravity: + { + offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+ + geometry.width+i*annotate_info->affine.ry*height- + annotate_info->affine.sx*metrics.width+annotate_info->affine.ry* + (metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0-1.0; + offset.y=(geometry.height == 0 ? -1.0 : 1.0)*annotate_info->affine.ty+ + geometry.height/2.0+i*annotate_info->affine.sy*height- + annotate_info->affine.rx*metrics.width+annotate_info->affine.sy* + (metrics.ascent+metrics.descent-(number_lines-1.0)*height)/2.0; + break; + } + case SouthWestGravity: + { + offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+i* + annotate_info->affine.ry*height-annotate_info->affine.ry* + (number_lines-1.0)*height; + offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+ + geometry.height+i*annotate_info->affine.sy*height- + annotate_info->affine.sy*(number_lines-1.0)*height+metrics.descent; + break; + } + case SouthGravity: + { + offset.x=(geometry.width == 0 ? -1.0 : 1.0)*annotate_info->affine.tx+ + geometry.width/2.0+i*annotate_info->affine.ry*height- + annotate_info->affine.sx*metrics.width/2.0-annotate_info->affine.ry* + (number_lines-1.0)*height/2.0; + offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+ + geometry.height+i*annotate_info->affine.sy*height- + annotate_info->affine.rx*metrics.width/2.0-annotate_info->affine.sy* + (number_lines-1.0)*height+metrics.descent; + break; + } + case SouthEastGravity: + { + offset.x=(geometry.width == 0 ? 1.0 : -1.0)*annotate_info->affine.tx+ + geometry.width+i*annotate_info->affine.ry*height- + annotate_info->affine.sx*metrics.width-annotate_info->affine.ry* + (number_lines-1.0)*height-1.0; + offset.y=(geometry.height == 0 ? 1.0 : -1.0)*annotate_info->affine.ty+ + geometry.height+i*annotate_info->affine.sy*height- + annotate_info->affine.rx*metrics.width-annotate_info->affine.sy* + (number_lines-1.0)*height+metrics.descent; + break; + } + } + switch (annotate->align) + { + case LeftAlign: + { + offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height; + offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height; + break; + } + case CenterAlign: + { + offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height- + annotate_info->affine.sx*metrics.width/2.0; + offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height- + annotate_info->affine.rx*metrics.width/2.0; + break; + } + case RightAlign: + { + offset.x=annotate_info->affine.tx+i*annotate_info->affine.ry*height- + annotate_info->affine.sx*metrics.width; + offset.y=annotate_info->affine.ty+i*annotate_info->affine.sy*height- + annotate_info->affine.rx*metrics.width; + break; + } + default: + break; + } + if (draw_info->undercolor.opacity != TransparentOpacity) + { + DrawInfo + *undercolor_info; + + /* + Text box. + */ + undercolor_info=CloneDrawInfo((ImageInfo *) NULL,(DrawInfo *) NULL); + undercolor_info->fill=draw_info->undercolor; + undercolor_info->affine=draw_info->affine; + undercolor_info->affine.tx=offset.x-draw_info->affine.ry*metrics.ascent; + undercolor_info->affine.ty=offset.y-draw_info->affine.sy*metrics.ascent; + (void) FormatLocaleString(primitive,MaxTextExtent, + ""rectangle 0.0,0.0 %g,%g"",metrics.origin.x,(double) height); + (void) CloneString(&undercolor_info->primitive,primitive); + (void) DrawImage(image,undercolor_info); + (void) DestroyDrawInfo(undercolor_info); + } + annotate_info->affine.tx=offset.x; + annotate_info->affine.ty=offset.y; + (void) FormatLocaleString(primitive,MaxTextExtent,""stroke-width %g "" + ""line 0,0 %g,0"",metrics.underline_thickness,metrics.width); + if (annotate->decorate == OverlineDecoration) + { + annotate_info->affine.ty-=(draw_info->affine.sy*(metrics.ascent+ + metrics.descent-metrics.underline_position)); + (void) CloneString(&annotate_info->primitive,primitive); + (void) DrawImage(image,annotate_info); + } + else + if (annotate->decorate == UnderlineDecoration) + { + annotate_info->affine.ty-=(draw_info->affine.sy* + metrics.underline_position); + (void) CloneString(&annotate_info->primitive,primitive); + (void) DrawImage(image,annotate_info); + } + /* + Annotate image with text. + */ + status=RenderType(image,annotate,&offset,&metrics); + if (status == MagickFalse) + break; + if (annotate->decorate == LineThroughDecoration) + { + annotate_info->affine.ty-=(draw_info->affine.sy*(height+ + metrics.underline_position+metrics.descent)/2.0); + (void) CloneString(&annotate_info->primitive,primitive); + (void) DrawImage(image,annotate_info); + } + } + /* + Relinquish resources. + */ + annotate_info=DestroyDrawInfo(annotate_info); + annotate=DestroyDrawInfo(annotate); + textlist=(char **) RelinquishMagickMemory(textlist); + text=DestroyString(text); + return(status); + } +","@@ -266,6 +266,7 @@ MagickExport MagickBooleanType AnnotateImage(Image *image, + { + annotate_info=DestroyDrawInfo(annotate_info); + annotate=DestroyDrawInfo(annotate); ++ text=DestroyString(text); + return(MagickFalse); + } + p=text; +@@ -300,6 +301,7 @@ MagickExport MagickBooleanType AnnotateImage(Image *image, + annotate_info=DestroyDrawInfo(annotate_info); + annotate=DestroyDrawInfo(annotate); + textlist=(char **) RelinquishMagickMemory(textlist); ++ text=DestroyString(text); + return(MagickFalse); + } + if (IsGrayColorspace(image->colorspace) != MagickFalse) +@@ -517,6 +519,7 @@ MagickExport MagickBooleanType AnnotateImage(Image *image, + annotate_info=DestroyDrawInfo(annotate_info); + annotate=DestroyDrawInfo(annotate); + textlist=(char **) RelinquishMagickMemory(textlist); ++ text=DestroyString(text); + return(status); + } + ",3134,3465,4096 +17821,"int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, + unsigned char *limit, int *al) +{ + unsigned short type; + unsigned short size; + unsigned short len; + unsigned char *data = *p; + int renegotiate_seen = 0; + int sigalg_seen = 0; + + s->servername_done = 0; + s->tlsext_status_type = -1; +# ifndef OPENSSL_NO_NEXTPROTONEG + s->s3->next_proto_neg_seen = 0; +# endif + +# ifndef OPENSSL_NO_HEARTBEATS + s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED | + SSL_TLSEXT_HB_DONT_SEND_REQUESTS); +# endif + +# ifndef OPENSSL_NO_EC + if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG) + ssl_check_for_safari(s, data, limit); +# endif /* !OPENSSL_NO_EC */ + +# ifndef OPENSSL_NO_SRP + if (s->srp_ctx.login != NULL) { + OPENSSL_free(s->srp_ctx.login); + s->srp_ctx.login = NULL; + } +# endif + + s->srtp_profile = NULL; + + if (data == limit) + goto ri_check; + + if (limit - data < 2) + goto err; + + n2s(data, len); + + if (limit - data != len) + goto err; + + while (limit - data >= 4) { + n2s(data, type); + n2s(data, size); + + if (limit - data < size) + goto err; +# if 0 + fprintf(stderr, ""Received extension type %d size %d\n"", type, size); +# endif + if (s->tlsext_debug_cb) + s->tlsext_debug_cb(s, 0, type, data, size, s->tlsext_debug_arg); +/*- + * The servername extension is treated as follows: + * + * - Only the hostname type is supported with a maximum length of 255. + * - The servername is rejected if too long or if it contains zeros, + * in which case an fatal alert is generated. + * - The servername field is maintained together with the session cache. + * - When a session is resumed, the servername call back invoked in order + * to allow the application to position itself to the right context. + * - The servername is acknowledged if it is new for a session or when + * it is identical to a previously used for the same session. + * Applications can control the behaviour. They can at any time + * set a 'desirable' servername for a new SSL object. This can be the + * case for example with HTTPS when a Host: header field is received and + * a renegotiation is requested. In this case, a possible servername + * presented in the new client hello is only acknowledged if it matches + * the value of the Host: field. + * - Applications must use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION + * if they provide for changing an explicit servername context for the + * session, i.e. when the session has been established with a servername + * extension. + * - On session reconnect, the servername extension may be absent. + * + */ + + if (type == TLSEXT_TYPE_server_name) { + unsigned char *sdata; + int servname_type; + int dsize; + + if (size < 2) + goto err; + n2s(data, dsize); + size -= 2; + if (dsize > size) + goto err; + + sdata = data; + while (dsize > 3) { + servname_type = *(sdata++); + n2s(sdata, len); + dsize -= 3; + + if (len > dsize) + goto err; + + if (s->servername_done == 0) + switch (servname_type) { + case TLSEXT_NAMETYPE_host_name: + if (!s->hit) { + if (s->session->tlsext_hostname) + goto err; + + if (len > TLSEXT_MAXLEN_host_name) { + *al = TLS1_AD_UNRECOGNIZED_NAME; + return 0; + } + if ((s->session->tlsext_hostname = + OPENSSL_malloc(len + 1)) == NULL) { + *al = TLS1_AD_INTERNAL_ERROR; + return 0; + } + memcpy(s->session->tlsext_hostname, sdata, len); + s->session->tlsext_hostname[len] = '\0'; + if (strlen(s->session->tlsext_hostname) != len) { + OPENSSL_free(s->session->tlsext_hostname); + s->session->tlsext_hostname = NULL; + *al = TLS1_AD_UNRECOGNIZED_NAME; + return 0; + } + s->servername_done = 1; + + } else + s->servername_done = s->session->tlsext_hostname + && strlen(s->session->tlsext_hostname) == len + && strncmp(s->session->tlsext_hostname, + (char *)sdata, len) == 0; + + break; + + default: + break; + } + + dsize -= len; + } + if (dsize != 0) + goto err; + + } +# ifndef OPENSSL_NO_SRP + else if (type == TLSEXT_TYPE_srp) { + if (size == 0 || ((len = data[0])) != (size - 1)) + goto err; + if (s->srp_ctx.login != NULL) + goto err; + if ((s->srp_ctx.login = OPENSSL_malloc(len + 1)) == NULL) + return -1; + memcpy(s->srp_ctx.login, &data[1], len); + s->srp_ctx.login[len] = '\0'; + + if (strlen(s->srp_ctx.login) != len) + goto err; + } +# endif + +# ifndef OPENSSL_NO_EC + else if (type == TLSEXT_TYPE_ec_point_formats) { + unsigned char *sdata = data; + int ecpointformatlist_length = *(sdata++); + + if (ecpointformatlist_length != size - 1) + goto err; + if (!s->hit) { + if (s->session->tlsext_ecpointformatlist) { + OPENSSL_free(s->session->tlsext_ecpointformatlist); + s->session->tlsext_ecpointformatlist = NULL; + } + s->session->tlsext_ecpointformatlist_length = 0; + if ((s->session->tlsext_ecpointformatlist = + OPENSSL_malloc(ecpointformatlist_length)) == NULL) { + *al = TLS1_AD_INTERNAL_ERROR; + return 0; + } + s->session->tlsext_ecpointformatlist_length = + ecpointformatlist_length; + memcpy(s->session->tlsext_ecpointformatlist, sdata, + ecpointformatlist_length); + } +# if 0 + fprintf(stderr, + ""ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) "", + s->session->tlsext_ecpointformatlist_length); + sdata = s->session->tlsext_ecpointformatlist; + for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) + fprintf(stderr, ""%i "", *(sdata++)); + fprintf(stderr, ""\n""); +# endif + } else if (type == TLSEXT_TYPE_elliptic_curves) { + unsigned char *sdata = data; + int ellipticcurvelist_length = (*(sdata++) << 8); + ellipticcurvelist_length += (*(sdata++)); + + if (ellipticcurvelist_length != size - 2 || + ellipticcurvelist_length < 1 || + /* Each NamedCurve is 2 bytes. */ + ellipticcurvelist_length & 1) + goto err; + + if (!s->hit) { + if (s->session->tlsext_ellipticcurvelist) + goto err; + + s->session->tlsext_ellipticcurvelist_length = 0; + if ((s->session->tlsext_ellipticcurvelist = + OPENSSL_malloc(ellipticcurvelist_length)) == NULL) { + *al = TLS1_AD_INTERNAL_ERROR; + return 0; + } + s->session->tlsext_ellipticcurvelist_length = + ellipticcurvelist_length; + memcpy(s->session->tlsext_ellipticcurvelist, sdata, + ellipticcurvelist_length); + } +# if 0 + fprintf(stderr, + ""ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) "", + s->session->tlsext_ellipticcurvelist_length); + sdata = s->session->tlsext_ellipticcurvelist; + for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++) + fprintf(stderr, ""%i "", *(sdata++)); + fprintf(stderr, ""\n""); +# endif + } +# endif /* OPENSSL_NO_EC */ +# ifdef TLSEXT_TYPE_opaque_prf_input + else if (type == TLSEXT_TYPE_opaque_prf_input && + s->version != DTLS1_VERSION) { + unsigned char *sdata = data; + + if (size < 2) { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + n2s(sdata, s->s3->client_opaque_prf_input_len); + if (s->s3->client_opaque_prf_input_len != size - 2) { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + + if (s->s3->client_opaque_prf_input != NULL) { + /* shouldn't really happen */ + OPENSSL_free(s->s3->client_opaque_prf_input); + } + + /* dummy byte just to get non-NULL */ + if (s->s3->client_opaque_prf_input_len == 0) + s->s3->client_opaque_prf_input = OPENSSL_malloc(1); + else + s->s3->client_opaque_prf_input = + BUF_memdup(sdata, s->s3->client_opaque_prf_input_len); + if (s->s3->client_opaque_prf_input == NULL) { + *al = TLS1_AD_INTERNAL_ERROR; + return 0; + } + } +# endif + else if (type == TLSEXT_TYPE_session_ticket) { + if (s->tls_session_ticket_ext_cb && + !s->tls_session_ticket_ext_cb(s, data, size, + s->tls_session_ticket_ext_cb_arg)) + { + *al = TLS1_AD_INTERNAL_ERROR; + return 0; + } + } else if (type == TLSEXT_TYPE_renegotiate) { + if (!ssl_parse_clienthello_renegotiate_ext(s, data, size, al)) + return 0; + renegotiate_seen = 1; + } else if (type == TLSEXT_TYPE_signature_algorithms) { + int dsize; + if (sigalg_seen || size < 2) + goto err; + sigalg_seen = 1; + n2s(data, dsize); + size -= 2; + if (dsize != size || dsize & 1) + goto err; + if (!tls1_process_sigalgs(s, data, dsize)) + goto err; + } else if (type == TLSEXT_TYPE_status_request && + s->version != DTLS1_VERSION) { + + if (size < 5) + goto err; + + s->tlsext_status_type = *data++; + size--; + if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) { + const unsigned char *sdata; + int dsize; + /* Read in responder_id_list */ + n2s(data, dsize); + size -= 2; + if (dsize > size) + goto err; + while (dsize > 0) { + OCSP_RESPID *id; + int idsize; + && !(s->tlsext_ocsp_ids = + sk_OCSP_RESPID_new_null())) { + OCSP_RESPID_free(id); + *al = SSL_AD_INTERNAL_ERROR; + return 0; + } + if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) { + OCSP_RESPID_free(id); + *al = SSL_AD_INTERNAL_ERROR; + return 0; + } + } + + OCSP_RESPID_free(id); + goto err; + } + if (!s->tlsext_ocsp_ids + && !(s->tlsext_ocsp_ids = + sk_OCSP_RESPID_new_null())) { + OCSP_RESPID_free(id); + *al = SSL_AD_INTERNAL_ERROR; + return 0; + } + if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) { + OCSP_RESPID_free(id); + *al = SSL_AD_INTERNAL_ERROR; + goto err; + sdata = data; + if (dsize > 0) { + if (s->tlsext_ocsp_exts) { + sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts, + X509_EXTENSION_free); + } + + s->tlsext_ocsp_exts = + d2i_X509_EXTENSIONS(NULL, &sdata, dsize); + if (!s->tlsext_ocsp_exts || (data + dsize != sdata)) + goto err; + } + } + /* + * We don't know what to do with any other type * so ignore it. + */ + else + s->tlsext_status_type = -1; + } +# ifndef OPENSSL_NO_HEARTBEATS + else if (type == TLSEXT_TYPE_heartbeat) { + switch (data[0]) { + case 0x01: /* Client allows us to send HB requests */ + s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; + break; + case 0x02: /* Client doesn't accept HB requests */ + s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; + s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS; + break; + default: + *al = SSL_AD_ILLEGAL_PARAMETER; + return 0; + } + } +# endif +# ifndef OPENSSL_NO_NEXTPROTONEG + else if (type == TLSEXT_TYPE_next_proto_neg && + s->s3->tmp.finish_md_len == 0) { + /*- + * We shouldn't accept this extension on a + * renegotiation. + * + * s->new_session will be set on renegotiation, but we + * probably shouldn't rely that it couldn't be set on + * the initial renegotation too in certain cases (when + * there's some other reason to disallow resuming an + * earlier session -- the current code won't be doing + * anything like that, but this might change). + * + * A valid sign that there's been a previous handshake + * in this connection is if s->s3->tmp.finish_md_len > + * 0. (We are talking about a check that will happen + * in the Hello protocol round, well before a new + * Finished message could have been computed.) + */ + s->s3->next_proto_neg_seen = 1; + } +# endif + + /* session ticket processed earlier */ +# ifndef OPENSSL_NO_SRTP + else if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s) + && type == TLSEXT_TYPE_use_srtp) { + if (ssl_parse_clienthello_use_srtp_ext(s, data, size, al)) + return 0; + } +# endif + + data += size; + } + + /* Spurious data on the end */ + if (data != limit) + goto err; + + *p = data; + + ri_check: + + /* Need RI if renegotiating */ + + if (!renegotiate_seen && s->renegotiate && + !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { + *al = SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT, + SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); + return 0; + } + + return 1; +err: + *al = SSL_AD_DECODE_ERROR; + return 0; +} +",1,"int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, + unsigned char *limit, int *al) +{ + unsigned short type; + unsigned short size; + unsigned short len; + unsigned char *data = *p; + int renegotiate_seen = 0; + int sigalg_seen = 0; + + s->servername_done = 0; + s->tlsext_status_type = -1; +# ifndef OPENSSL_NO_NEXTPROTONEG + s->s3->next_proto_neg_seen = 0; +# endif + +# ifndef OPENSSL_NO_HEARTBEATS + s->tlsext_heartbeat &= ~(SSL_TLSEXT_HB_ENABLED | + SSL_TLSEXT_HB_DONT_SEND_REQUESTS); +# endif + +# ifndef OPENSSL_NO_EC + if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG) + ssl_check_for_safari(s, data, limit); +# endif /* !OPENSSL_NO_EC */ + +# ifndef OPENSSL_NO_SRP + if (s->srp_ctx.login != NULL) { + OPENSSL_free(s->srp_ctx.login); + s->srp_ctx.login = NULL; + } +# endif + + s->srtp_profile = NULL; + + if (data == limit) + goto ri_check; + + if (limit - data < 2) + goto err; + + n2s(data, len); + + if (limit - data != len) + goto err; + + while (limit - data >= 4) { + n2s(data, type); + n2s(data, size); + + if (limit - data < size) + goto err; +# if 0 + fprintf(stderr, ""Received extension type %d size %d\n"", type, size); +# endif + if (s->tlsext_debug_cb) + s->tlsext_debug_cb(s, 0, type, data, size, s->tlsext_debug_arg); +/*- + * The servername extension is treated as follows: + * + * - Only the hostname type is supported with a maximum length of 255. + * - The servername is rejected if too long or if it contains zeros, + * in which case an fatal alert is generated. + * - The servername field is maintained together with the session cache. + * - When a session is resumed, the servername call back invoked in order + * to allow the application to position itself to the right context. + * - The servername is acknowledged if it is new for a session or when + * it is identical to a previously used for the same session. + * Applications can control the behaviour. They can at any time + * set a 'desirable' servername for a new SSL object. This can be the + * case for example with HTTPS when a Host: header field is received and + * a renegotiation is requested. In this case, a possible servername + * presented in the new client hello is only acknowledged if it matches + * the value of the Host: field. + * - Applications must use SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION + * if they provide for changing an explicit servername context for the + * session, i.e. when the session has been established with a servername + * extension. + * - On session reconnect, the servername extension may be absent. + * + */ + + if (type == TLSEXT_TYPE_server_name) { + unsigned char *sdata; + int servname_type; + int dsize; + + if (size < 2) + goto err; + n2s(data, dsize); + size -= 2; + if (dsize > size) + goto err; + + sdata = data; + while (dsize > 3) { + servname_type = *(sdata++); + n2s(sdata, len); + dsize -= 3; + + if (len > dsize) + goto err; + + if (s->servername_done == 0) + switch (servname_type) { + case TLSEXT_NAMETYPE_host_name: + if (!s->hit) { + if (s->session->tlsext_hostname) + goto err; + + if (len > TLSEXT_MAXLEN_host_name) { + *al = TLS1_AD_UNRECOGNIZED_NAME; + return 0; + } + if ((s->session->tlsext_hostname = + OPENSSL_malloc(len + 1)) == NULL) { + *al = TLS1_AD_INTERNAL_ERROR; + return 0; + } + memcpy(s->session->tlsext_hostname, sdata, len); + s->session->tlsext_hostname[len] = '\0'; + if (strlen(s->session->tlsext_hostname) != len) { + OPENSSL_free(s->session->tlsext_hostname); + s->session->tlsext_hostname = NULL; + *al = TLS1_AD_UNRECOGNIZED_NAME; + return 0; + } + s->servername_done = 1; + + } else + s->servername_done = s->session->tlsext_hostname + && strlen(s->session->tlsext_hostname) == len + && strncmp(s->session->tlsext_hostname, + (char *)sdata, len) == 0; + + break; + + default: + break; + } + + dsize -= len; + } + if (dsize != 0) + goto err; + + } +# ifndef OPENSSL_NO_SRP + else if (type == TLSEXT_TYPE_srp) { + if (size == 0 || ((len = data[0])) != (size - 1)) + goto err; + if (s->srp_ctx.login != NULL) + goto err; + if ((s->srp_ctx.login = OPENSSL_malloc(len + 1)) == NULL) + return -1; + memcpy(s->srp_ctx.login, &data[1], len); + s->srp_ctx.login[len] = '\0'; + + if (strlen(s->srp_ctx.login) != len) + goto err; + } +# endif + +# ifndef OPENSSL_NO_EC + else if (type == TLSEXT_TYPE_ec_point_formats) { + unsigned char *sdata = data; + int ecpointformatlist_length = *(sdata++); + + if (ecpointformatlist_length != size - 1) + goto err; + if (!s->hit) { + if (s->session->tlsext_ecpointformatlist) { + OPENSSL_free(s->session->tlsext_ecpointformatlist); + s->session->tlsext_ecpointformatlist = NULL; + } + s->session->tlsext_ecpointformatlist_length = 0; + if ((s->session->tlsext_ecpointformatlist = + OPENSSL_malloc(ecpointformatlist_length)) == NULL) { + *al = TLS1_AD_INTERNAL_ERROR; + return 0; + } + s->session->tlsext_ecpointformatlist_length = + ecpointformatlist_length; + memcpy(s->session->tlsext_ecpointformatlist, sdata, + ecpointformatlist_length); + } +# if 0 + fprintf(stderr, + ""ssl_parse_clienthello_tlsext s->session->tlsext_ecpointformatlist (length=%i) "", + s->session->tlsext_ecpointformatlist_length); + sdata = s->session->tlsext_ecpointformatlist; + for (i = 0; i < s->session->tlsext_ecpointformatlist_length; i++) + fprintf(stderr, ""%i "", *(sdata++)); + fprintf(stderr, ""\n""); +# endif + } else if (type == TLSEXT_TYPE_elliptic_curves) { + unsigned char *sdata = data; + int ellipticcurvelist_length = (*(sdata++) << 8); + ellipticcurvelist_length += (*(sdata++)); + + if (ellipticcurvelist_length != size - 2 || + ellipticcurvelist_length < 1 || + /* Each NamedCurve is 2 bytes. */ + ellipticcurvelist_length & 1) + goto err; + + if (!s->hit) { + if (s->session->tlsext_ellipticcurvelist) + goto err; + + s->session->tlsext_ellipticcurvelist_length = 0; + if ((s->session->tlsext_ellipticcurvelist = + OPENSSL_malloc(ellipticcurvelist_length)) == NULL) { + *al = TLS1_AD_INTERNAL_ERROR; + return 0; + } + s->session->tlsext_ellipticcurvelist_length = + ellipticcurvelist_length; + memcpy(s->session->tlsext_ellipticcurvelist, sdata, + ellipticcurvelist_length); + } +# if 0 + fprintf(stderr, + ""ssl_parse_clienthello_tlsext s->session->tlsext_ellipticcurvelist (length=%i) "", + s->session->tlsext_ellipticcurvelist_length); + sdata = s->session->tlsext_ellipticcurvelist; + for (i = 0; i < s->session->tlsext_ellipticcurvelist_length; i++) + fprintf(stderr, ""%i "", *(sdata++)); + fprintf(stderr, ""\n""); +# endif + } +# endif /* OPENSSL_NO_EC */ +# ifdef TLSEXT_TYPE_opaque_prf_input + else if (type == TLSEXT_TYPE_opaque_prf_input && + s->version != DTLS1_VERSION) { + unsigned char *sdata = data; + + if (size < 2) { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + n2s(sdata, s->s3->client_opaque_prf_input_len); + if (s->s3->client_opaque_prf_input_len != size - 2) { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + + if (s->s3->client_opaque_prf_input != NULL) { + /* shouldn't really happen */ + OPENSSL_free(s->s3->client_opaque_prf_input); + } + + /* dummy byte just to get non-NULL */ + if (s->s3->client_opaque_prf_input_len == 0) + s->s3->client_opaque_prf_input = OPENSSL_malloc(1); + else + s->s3->client_opaque_prf_input = + BUF_memdup(sdata, s->s3->client_opaque_prf_input_len); + if (s->s3->client_opaque_prf_input == NULL) { + *al = TLS1_AD_INTERNAL_ERROR; + return 0; + } + } +# endif + else if (type == TLSEXT_TYPE_session_ticket) { + if (s->tls_session_ticket_ext_cb && + !s->tls_session_ticket_ext_cb(s, data, size, + s->tls_session_ticket_ext_cb_arg)) + { + *al = TLS1_AD_INTERNAL_ERROR; + return 0; + } + } else if (type == TLSEXT_TYPE_renegotiate) { + if (!ssl_parse_clienthello_renegotiate_ext(s, data, size, al)) + return 0; + renegotiate_seen = 1; + } else if (type == TLSEXT_TYPE_signature_algorithms) { + int dsize; + if (sigalg_seen || size < 2) + goto err; + sigalg_seen = 1; + n2s(data, dsize); + size -= 2; + if (dsize != size || dsize & 1) + goto err; + if (!tls1_process_sigalgs(s, data, dsize)) + goto err; + } else if (type == TLSEXT_TYPE_status_request && + s->version != DTLS1_VERSION) { + + if (size < 5) + goto err; + + s->tlsext_status_type = *data++; + size--; + if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) { + const unsigned char *sdata; + int dsize; + /* Read in responder_id_list */ + n2s(data, dsize); + size -= 2; + if (dsize > size) + goto err; + + /* + * We remove any OCSP_RESPIDs from a previous handshake + * to prevent unbounded memory growth - CVE-2016-6304 + */ + sk_OCSP_RESPID_pop_free(s->tlsext_ocsp_ids, + OCSP_RESPID_free); + if (dsize > 0) { + s->tlsext_ocsp_ids = sk_OCSP_RESPID_new_null(); + if (s->tlsext_ocsp_ids == NULL) { + *al = SSL_AD_INTERNAL_ERROR; + return 0; + } + } else { + s->tlsext_ocsp_ids = NULL; + } + + while (dsize > 0) { + OCSP_RESPID *id; + int idsize; + && !(s->tlsext_ocsp_ids = + sk_OCSP_RESPID_new_null())) { + OCSP_RESPID_free(id); + *al = SSL_AD_INTERNAL_ERROR; + return 0; + } + if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) { + OCSP_RESPID_free(id); + *al = SSL_AD_INTERNAL_ERROR; + return 0; + } + } + + OCSP_RESPID_free(id); + goto err; + } + if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) { + OCSP_RESPID_free(id); + *al = SSL_AD_INTERNAL_ERROR; + goto err; + sdata = data; + if (dsize > 0) { + if (s->tlsext_ocsp_exts) { + sk_X509_EXTENSION_pop_free(s->tlsext_ocsp_exts, + X509_EXTENSION_free); + } + + s->tlsext_ocsp_exts = + d2i_X509_EXTENSIONS(NULL, &sdata, dsize); + if (!s->tlsext_ocsp_exts || (data + dsize != sdata)) + goto err; + } + } + /* + * We don't know what to do with any other type * so ignore it. + */ + else + s->tlsext_status_type = -1; + } +# ifndef OPENSSL_NO_HEARTBEATS + else if (type == TLSEXT_TYPE_heartbeat) { + switch (data[0]) { + case 0x01: /* Client allows us to send HB requests */ + s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; + break; + case 0x02: /* Client doesn't accept HB requests */ + s->tlsext_heartbeat |= SSL_TLSEXT_HB_ENABLED; + s->tlsext_heartbeat |= SSL_TLSEXT_HB_DONT_SEND_REQUESTS; + break; + default: + *al = SSL_AD_ILLEGAL_PARAMETER; + return 0; + } + } +# endif +# ifndef OPENSSL_NO_NEXTPROTONEG + else if (type == TLSEXT_TYPE_next_proto_neg && + s->s3->tmp.finish_md_len == 0) { + /*- + * We shouldn't accept this extension on a + * renegotiation. + * + * s->new_session will be set on renegotiation, but we + * probably shouldn't rely that it couldn't be set on + * the initial renegotation too in certain cases (when + * there's some other reason to disallow resuming an + * earlier session -- the current code won't be doing + * anything like that, but this might change). + * + * A valid sign that there's been a previous handshake + * in this connection is if s->s3->tmp.finish_md_len > + * 0. (We are talking about a check that will happen + * in the Hello protocol round, well before a new + * Finished message could have been computed.) + */ + s->s3->next_proto_neg_seen = 1; + } +# endif + + /* session ticket processed earlier */ +# ifndef OPENSSL_NO_SRTP + else if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s) + && type == TLSEXT_TYPE_use_srtp) { + if (ssl_parse_clienthello_use_srtp_ext(s, data, size, al)) + return 0; + } +# endif + + data += size; + } + + /* Spurious data on the end */ + if (data != limit) + goto err; + + *p = data; + + ri_check: + + /* Need RI if renegotiating */ + + if (!renegotiate_seen && s->renegotiate && + !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { + *al = SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT, + SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); + return 0; + } + + return 1; +err: + *al = SSL_AD_DECODE_ERROR; + return 0; +} +","@@ -1284,6 +1284,23 @@ int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, + size -= 2; + if (dsize > size) + goto err; ++ ++ /* ++ * We remove any OCSP_RESPIDs from a previous handshake ++ * to prevent unbounded memory growth - CVE-2016-6304 ++ */ ++ sk_OCSP_RESPID_pop_free(s->tlsext_ocsp_ids, ++ OCSP_RESPID_free); ++ if (dsize > 0) { ++ s->tlsext_ocsp_ids = sk_OCSP_RESPID_new_null(); ++ if (s->tlsext_ocsp_ids == NULL) { ++ *al = SSL_AD_INTERNAL_ERROR; ++ return 0; ++ } ++ } else { ++ s->tlsext_ocsp_ids = NULL; ++ } ++ + while (dsize > 0) { + OCSP_RESPID *id; + int idsize; +@@ -1303,13 +1320,6 @@ int ssl_parse_clienthello_tlsext(SSL *s, unsigned char **p, + OCSP_RESPID_free(id); + goto err; + } +- if (!s->tlsext_ocsp_ids +- && !(s->tlsext_ocsp_ids = +- sk_OCSP_RESPID_new_null())) { +- OCSP_RESPID_free(id); +- *al = SSL_AD_INTERNAL_ERROR; +- return 0; +- } + if (!sk_OCSP_RESPID_push(s->tlsext_ocsp_ids, id)) { + OCSP_RESPID_free(id); + *al = SSL_AD_INTERNAL_ERROR;",3709,4040,4096 +1616,"PhotoDataUtils::Import2WayExif ( const TIFF_Manager & exif, SXMPMeta * xmp, int iptcDigestState ) +{ + const bool nativeEndian = exif.IsNativeEndian(); + + bool found, foundFromXMP; + TIFF_Manager::TagInfo tagInfo; + XMP_OptionBits flags; + + ImportTIFF_StandardMappings ( kTIFF_PrimaryIFD, exif, xmp ); + ImportTIFF_StandardMappings ( kTIFF_ExifIFD, exif, xmp ); + ImportTIFF_StandardMappings ( kTIFF_GPSInfoIFD, exif, xmp ); + + + #if SupportOldExifProperties + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_CameraOwnerName, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_ASCIIType) && (tagInfo.count > 0) ) { + ImportSingleTIFF ( tagInfo, nativeEndian, xmp, kXMP_NS_EXIF_Aux, ""OwnerName"" ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_BodySerialNumber, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_ASCIIType) && (tagInfo.count > 0) ) { + ImportSingleTIFF ( tagInfo, nativeEndian, xmp, kXMP_NS_EXIF_Aux, ""SerialNumber"" ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_LensModel, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_ASCIIType) && (tagInfo.count > 0) ) { + ImportSingleTIFF ( tagInfo, nativeEndian, xmp, kXMP_NS_EXIF_Aux, ""Lens"" ); + } + + found = xmp->GetProperty ( kXMP_NS_ExifEX, ""LensSpecification"", 0, &flags ); + if ( found && XMP_PropIsArray(flags) ) { + std::string fullStr, oneItem; + size_t count = (size_t) xmp->CountArrayItems ( kXMP_NS_ExifEX, ""LensSpecification"" ); + if ( count > 0 ) { + (void) xmp->GetArrayItem ( kXMP_NS_ExifEX, ""LensSpecification"", 1, &fullStr, 0 ); + for ( size_t i = 2; i <= count; ++i ) { + fullStr += ' '; + (void) xmp->GetArrayItem ( kXMP_NS_ExifEX, ""LensSpecification"", i, &oneItem, 0 ); + fullStr += oneItem; + } + } + xmp->SetProperty ( kXMP_NS_EXIF_Aux, ""LensInfo"", fullStr.c_str(), kXMP_DeleteExisting ); + } + + #endif + + + found = exif.GetTag ( kTIFF_GPSInfoIFD, kTIFF_GPSAltitude, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_RationalType) && (tagInfo.count == 1) ) { + + XMP_Uns32 num = exif.GetUns32 ( tagInfo.dataPtr ); + XMP_Uns32 denom = exif.GetUns32 ( (XMP_Uns8*)tagInfo.dataPtr + 4 ); + + bool fixXMP = false; + bool numNeg = num >> 31; + bool denomNeg = denom >> 31; + + if ( denomNeg ) { // The denominator looks negative, shift the sign to the numerator. + denom = -denom; + num = -num; + numNeg = num >> 31; + fixXMP = true; + } + + if ( numNeg ) { // The numerator looks negative, fix the XMP. + xmp->SetProperty ( kXMP_NS_EXIF, ""GPSAltitudeRef"", ""1"" ); + num = -num; + fixXMP = true; + } + + if ( fixXMP ) { + char buffer [32]; + snprintf ( buffer, sizeof(buffer), ""%lu/%lu"", (unsigned long) num, (unsigned long) denom ); // AUDIT: Using sizeof(buffer) is safe. + xmp->SetProperty ( kXMP_NS_EXIF, ""GPSAltitude"", buffer ); + } + + } + + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_DateTimeOriginal, &tagInfo ); + foundFromXMP = xmp->DoesPropertyExist ( kXMP_NS_EXIF, ""DateTimeOriginal"" ); + + if ( found && (! foundFromXMP) && (tagInfo.type == kTIFF_ASCIIType) ) { + ImportTIFF_Date ( exif, tagInfo, xmp, kXMP_NS_EXIF, ""DateTimeOriginal"" ); + } + + found = exif.GetTag ( kTIFF_PrimaryIFD, kTIFF_DateTime, &tagInfo ); + foundFromXMP = xmp->DoesPropertyExist ( kXMP_NS_XMP, ""ModifyDate"" ); + + if ( found && (! foundFromXMP) && (tagInfo.type == kTIFF_ASCIIType) ) { + ImportTIFF_Date ( exif, tagInfo, xmp, kXMP_NS_XMP, ""ModifyDate"" ); + } + + + ImportTIFF_PhotographicSensitivity ( exif, xmp ); + + found = exif.GetTag ( kTIFF_PrimaryIFD, kTIFF_Artist, &tagInfo ); + foundFromXMP = xmp->DoesPropertyExist ( kXMP_NS_DC, ""creator"" ); + if ( (! found) && (! foundFromXMP) ) { + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_CameraOwnerName, &tagInfo ); + if ( found ) { + std::string xmpValue ( (char*)tagInfo.dataPtr, tagInfo.dataLen ); + xmp->AppendArrayItem ( kXMP_NS_DC, ""creator"", kXMP_PropArrayIsOrdered, xmpValue.c_str() ); + } + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_ExifVersion, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_UndefinedType) && (tagInfo.count == 4) ) { + char str[5]; + + *((XMP_Uns32*)str) = GetUns32AsIs ( tagInfo.dataPtr ); + str[4] = 0; + xmp->SetProperty ( kXMP_NS_EXIF, ""ExifVersion"", str ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_FlashpixVersion, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_UndefinedType) && (tagInfo.count == 4) ) { + char str[5]; + + *((XMP_Uns32*)str) = GetUns32AsIs ( tagInfo.dataPtr ); + str[4] = 0; + xmp->SetProperty ( kXMP_NS_EXIF, ""FlashpixVersion"", str ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_ComponentsConfiguration, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_UndefinedType) && (tagInfo.count == 4) ) { + ImportArrayTIFF_Byte ( tagInfo, xmp, kXMP_NS_EXIF, ""ComponentsConfiguration"" ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_UserComment, &tagInfo ); + if ( found ) { + ImportTIFF_EncodedString ( exif, tagInfo, xmp, kXMP_NS_EXIF, ""UserComment"", true /* isLangAlt */ ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_OECF, &tagInfo ); + if ( found ) { + ImportConversionTable ( tagInfo, nativeEndian, xmp, kXMP_NS_EXIF, ""OECF"" ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_Flash, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_ShortType) && (tagInfo.count == 1) ) { + ImportTIFF_Flash ( tagInfo, nativeEndian, xmp, kXMP_NS_EXIF, ""Flash"" ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_SpatialFrequencyResponse, &tagInfo ); + if ( found ) { + ImportConversionTable ( tagInfo, nativeEndian, xmp, kXMP_NS_EXIF, ""SpatialFrequencyResponse"" ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_FileSource, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_UndefinedType) && (tagInfo.count == 1) ) { + ImportSingleTIFF_Byte ( tagInfo, xmp, kXMP_NS_EXIF, ""FileSource"" ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_SceneType, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_UndefinedType) && (tagInfo.count == 1) ) { + ImportSingleTIFF_Byte ( tagInfo, xmp, kXMP_NS_EXIF, ""SceneType"" ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_CFAPattern, &tagInfo ); + if ( found ) { + ImportTIFF_CFATable ( tagInfo, nativeEndian, xmp, kXMP_NS_EXIF, ""CFAPattern"" ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_DeviceSettingDescription, &tagInfo ); + if ( found ) { + ImportTIFF_DSDTable ( exif, tagInfo, xmp, kXMP_NS_EXIF, ""DeviceSettingDescription"" ); + } + + + found = exif.GetTag ( kTIFF_GPSInfoIFD, kTIFF_GPSVersionID, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_ByteType) && (tagInfo.count == 4) ) { + const XMP_Uns8 * binValue = (const XMP_Uns8 *) tagInfo.dataPtr; + char strOut[20];// ! Value could be up to 16 bytes: ""255.255.255.255"" plus nul. + snprintf ( strOut, sizeof(strOut), ""%u.%u.%u.%u"", // AUDIT: Use of sizeof(strOut) is safe. + binValue[0], binValue[1], binValue[2], binValue[3] ); + xmp->SetProperty ( kXMP_NS_EXIF, ""GPSVersionID"", strOut ); + } + + found = exif.GetTag ( kTIFF_GPSInfoIFD, kTIFF_GPSLatitude, &tagInfo ); + if ( found ) { + ImportTIFF_GPSCoordinate ( exif, tagInfo, xmp, kXMP_NS_EXIF, ""GPSLatitude"" ); + } + + found = exif.GetTag ( kTIFF_GPSInfoIFD, kTIFF_GPSLongitude, &tagInfo ); + if ( found ) { + ImportTIFF_GPSCoordinate ( exif, tagInfo, xmp, kXMP_NS_EXIF, ""GPSLongitude"" ); + } + + found = exif.GetTag ( kTIFF_GPSInfoIFD, kTIFF_GPSTimeStamp, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_RationalType) && (tagInfo.count == 3) ) { + ImportTIFF_GPSTimeStamp ( exif, tagInfo, xmp, kXMP_NS_EXIF, ""GPSTimeStamp"" ); + } + + found = exif.GetTag ( kTIFF_GPSInfoIFD, kTIFF_GPSDestLatitude, &tagInfo ); + if ( found ) { + ImportTIFF_GPSCoordinate ( exif, tagInfo, xmp, kXMP_NS_EXIF, ""GPSDestLatitude"" ); + } + + found = exif.GetTag ( kTIFF_GPSInfoIFD, kTIFF_GPSDestLongitude, &tagInfo ); + if ( found ) { + ImportTIFF_GPSCoordinate ( exif, tagInfo, xmp, kXMP_NS_EXIF, ""GPSDestLongitude"" ); + } + + found = exif.GetTag ( kTIFF_GPSInfoIFD, kTIFF_GPSProcessingMethod, &tagInfo ); + if ( found ) { + ImportTIFF_EncodedString ( exif, tagInfo, xmp, kXMP_NS_EXIF, ""GPSProcessingMethod"" ); + } + + found = exif.GetTag ( kTIFF_GPSInfoIFD, kTIFF_GPSAreaInformation, &tagInfo ); + if ( found ) { + ImportTIFF_EncodedString ( exif, tagInfo, xmp, kXMP_NS_EXIF, ""GPSAreaInformation"" ); + } + +} // PhotoDataUtils::Import2WayExif +",0,"PhotoDataUtils::Import2WayExif ( const TIFF_Manager & exif, SXMPMeta * xmp, int iptcDigestState ) +{ + const bool nativeEndian = exif.IsNativeEndian(); + + bool found, foundFromXMP; + TIFF_Manager::TagInfo tagInfo; + XMP_OptionBits flags; + + ImportTIFF_StandardMappings ( kTIFF_PrimaryIFD, exif, xmp ); + ImportTIFF_StandardMappings ( kTIFF_ExifIFD, exif, xmp ); + ImportTIFF_StandardMappings ( kTIFF_GPSInfoIFD, exif, xmp ); + + + #if SupportOldExifProperties + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_CameraOwnerName, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_ASCIIType) && (tagInfo.count > 0) ) { + ImportSingleTIFF ( tagInfo, nativeEndian, xmp, kXMP_NS_EXIF_Aux, ""OwnerName"" ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_BodySerialNumber, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_ASCIIType) && (tagInfo.count > 0) ) { + ImportSingleTIFF ( tagInfo, nativeEndian, xmp, kXMP_NS_EXIF_Aux, ""SerialNumber"" ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_LensModel, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_ASCIIType) && (tagInfo.count > 0) ) { + ImportSingleTIFF ( tagInfo, nativeEndian, xmp, kXMP_NS_EXIF_Aux, ""Lens"" ); + } + + found = xmp->GetProperty ( kXMP_NS_ExifEX, ""LensSpecification"", 0, &flags ); + if ( found && XMP_PropIsArray(flags) ) { + std::string fullStr, oneItem; + size_t count = (size_t) xmp->CountArrayItems ( kXMP_NS_ExifEX, ""LensSpecification"" ); + if ( count > 0 ) { + (void) xmp->GetArrayItem ( kXMP_NS_ExifEX, ""LensSpecification"", 1, &fullStr, 0 ); + for ( size_t i = 2; i <= count; ++i ) { + fullStr += ' '; + (void) xmp->GetArrayItem ( kXMP_NS_ExifEX, ""LensSpecification"", i, &oneItem, 0 ); + fullStr += oneItem; + } + } + xmp->SetProperty ( kXMP_NS_EXIF_Aux, ""LensInfo"", fullStr.c_str(), kXMP_DeleteExisting ); + } + + #endif + + + found = exif.GetTag ( kTIFF_GPSInfoIFD, kTIFF_GPSAltitude, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_RationalType) && (tagInfo.count == 1) ) { + + XMP_Uns32 num = exif.GetUns32 ( tagInfo.dataPtr ); + XMP_Uns32 denom = exif.GetUns32 ( (XMP_Uns8*)tagInfo.dataPtr + 4 ); + + bool fixXMP = false; + bool numNeg = num >> 31; + bool denomNeg = denom >> 31; + + if ( denomNeg ) { // The denominator looks negative, shift the sign to the numerator. + denom = -denom; + num = -num; + numNeg = num >> 31; + fixXMP = true; + } + + if ( numNeg ) { // The numerator looks negative, fix the XMP. + xmp->SetProperty ( kXMP_NS_EXIF, ""GPSAltitudeRef"", ""1"" ); + num = -num; + fixXMP = true; + } + + if ( fixXMP ) { + char buffer [32]; + snprintf ( buffer, sizeof(buffer), ""%lu/%lu"", (unsigned long) num, (unsigned long) denom ); // AUDIT: Using sizeof(buffer) is safe. + xmp->SetProperty ( kXMP_NS_EXIF, ""GPSAltitude"", buffer ); + } + + } + + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_DateTimeOriginal, &tagInfo ); + foundFromXMP = xmp->DoesPropertyExist ( kXMP_NS_EXIF, ""DateTimeOriginal"" ); + + if ( found && (! foundFromXMP) && (tagInfo.type == kTIFF_ASCIIType) ) { + ImportTIFF_Date ( exif, tagInfo, xmp, kXMP_NS_EXIF, ""DateTimeOriginal"" ); + } + + found = exif.GetTag ( kTIFF_PrimaryIFD, kTIFF_DateTime, &tagInfo ); + foundFromXMP = xmp->DoesPropertyExist ( kXMP_NS_XMP, ""ModifyDate"" ); + + if ( found && (! foundFromXMP) && (tagInfo.type == kTIFF_ASCIIType) ) { + ImportTIFF_Date ( exif, tagInfo, xmp, kXMP_NS_XMP, ""ModifyDate"" ); + } + + + ImportTIFF_PhotographicSensitivity ( exif, xmp ); + + found = exif.GetTag ( kTIFF_PrimaryIFD, kTIFF_Artist, &tagInfo ); + foundFromXMP = xmp->DoesPropertyExist ( kXMP_NS_DC, ""creator"" ); + if ( (! found) && (! foundFromXMP) ) { + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_CameraOwnerName, &tagInfo ); + if ( found ) { + std::string xmpValue ( (char*)tagInfo.dataPtr, tagInfo.dataLen ); + xmp->AppendArrayItem ( kXMP_NS_DC, ""creator"", kXMP_PropArrayIsOrdered, xmpValue.c_str() ); + } + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_ExifVersion, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_UndefinedType) && (tagInfo.count == 4) ) { + char str[5]; + + *((XMP_Uns32*)str) = GetUns32AsIs ( tagInfo.dataPtr ); + str[4] = 0; + xmp->SetProperty ( kXMP_NS_EXIF, ""ExifVersion"", str ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_FlashpixVersion, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_UndefinedType) && (tagInfo.count == 4) ) { + char str[5]; + + *((XMP_Uns32*)str) = GetUns32AsIs ( tagInfo.dataPtr ); + str[4] = 0; + xmp->SetProperty ( kXMP_NS_EXIF, ""FlashpixVersion"", str ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_ComponentsConfiguration, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_UndefinedType) && (tagInfo.count == 4) ) { + ImportArrayTIFF_Byte ( tagInfo, xmp, kXMP_NS_EXIF, ""ComponentsConfiguration"" ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_UserComment, &tagInfo ); + if ( found ) { + ImportTIFF_EncodedString ( exif, tagInfo, xmp, kXMP_NS_EXIF, ""UserComment"", true /* isLangAlt */ ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_OECF, &tagInfo ); + if ( found ) { + ImportConversionTable ( tagInfo, nativeEndian, xmp, kXMP_NS_EXIF, ""OECF"" ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_Flash, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_ShortType) && (tagInfo.count == 1) ) { + ImportTIFF_Flash ( tagInfo, nativeEndian, xmp, kXMP_NS_EXIF, ""Flash"" ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_SpatialFrequencyResponse, &tagInfo ); + if ( found ) { + ImportConversionTable ( tagInfo, nativeEndian, xmp, kXMP_NS_EXIF, ""SpatialFrequencyResponse"" ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_FileSource, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_UndefinedType) && (tagInfo.count == 1) ) { + ImportSingleTIFF_Byte ( tagInfo, xmp, kXMP_NS_EXIF, ""FileSource"" ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_SceneType, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_UndefinedType) && (tagInfo.count == 1) ) { + ImportSingleTIFF_Byte ( tagInfo, xmp, kXMP_NS_EXIF, ""SceneType"" ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_CFAPattern, &tagInfo ); + if ( found ) { + ImportTIFF_CFATable ( tagInfo, nativeEndian, xmp, kXMP_NS_EXIF, ""CFAPattern"" ); + } + + found = exif.GetTag ( kTIFF_ExifIFD, kTIFF_DeviceSettingDescription, &tagInfo ); + if ( found ) { + ImportTIFF_DSDTable ( exif, tagInfo, xmp, kXMP_NS_EXIF, ""DeviceSettingDescription"" ); + } + + + found = exif.GetTag ( kTIFF_GPSInfoIFD, kTIFF_GPSVersionID, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_ByteType) && (tagInfo.count == 4) ) { + const XMP_Uns8 * binValue = (const XMP_Uns8 *) tagInfo.dataPtr; + char strOut[20];// ! Value could be up to 16 bytes: ""255.255.255.255"" plus nul. + snprintf ( strOut, sizeof(strOut), ""%u.%u.%u.%u"", // AUDIT: Use of sizeof(strOut) is safe. + binValue[0], binValue[1], binValue[2], binValue[3] ); + xmp->SetProperty ( kXMP_NS_EXIF, ""GPSVersionID"", strOut ); + } + + found = exif.GetTag ( kTIFF_GPSInfoIFD, kTIFF_GPSLatitude, &tagInfo ); + if ( found ) { + ImportTIFF_GPSCoordinate ( exif, tagInfo, xmp, kXMP_NS_EXIF, ""GPSLatitude"" ); + } + + found = exif.GetTag ( kTIFF_GPSInfoIFD, kTIFF_GPSLongitude, &tagInfo ); + if ( found ) { + ImportTIFF_GPSCoordinate ( exif, tagInfo, xmp, kXMP_NS_EXIF, ""GPSLongitude"" ); + } + + found = exif.GetTag ( kTIFF_GPSInfoIFD, kTIFF_GPSTimeStamp, &tagInfo ); + if ( found && (tagInfo.type == kTIFF_RationalType) && (tagInfo.count == 3) ) { + ImportTIFF_GPSTimeStamp ( exif, tagInfo, xmp, kXMP_NS_EXIF, ""GPSTimeStamp"" ); + } + + found = exif.GetTag ( kTIFF_GPSInfoIFD, kTIFF_GPSDestLatitude, &tagInfo ); + if ( found ) { + ImportTIFF_GPSCoordinate ( exif, tagInfo, xmp, kXMP_NS_EXIF, ""GPSDestLatitude"" ); + } + + found = exif.GetTag ( kTIFF_GPSInfoIFD, kTIFF_GPSDestLongitude, &tagInfo ); + if ( found ) { + ImportTIFF_GPSCoordinate ( exif, tagInfo, xmp, kXMP_NS_EXIF, ""GPSDestLongitude"" ); + } + + found = exif.GetTag ( kTIFF_GPSInfoIFD, kTIFF_GPSProcessingMethod, &tagInfo ); + if ( found ) { + ImportTIFF_EncodedString ( exif, tagInfo, xmp, kXMP_NS_EXIF, ""GPSProcessingMethod"" ); + } + + found = exif.GetTag ( kTIFF_GPSInfoIFD, kTIFF_GPSAreaInformation, &tagInfo ); + if ( found ) { + ImportTIFF_EncodedString ( exif, tagInfo, xmp, kXMP_NS_EXIF, ""GPSAreaInformation"" ); + } + +} // PhotoDataUtils::Import2WayExif +","@@ -233,7 +233,7 @@ static XMP_Uns32 GatherInt ( const char * strPtr, size_t count ) + + static size_t TrimTrailingSpaces ( char * firstChar, size_t origLen ) + { +- if ( origLen == 0 ) return 0; ++ if ( !firstChar || origLen == 0 ) return 0; + + char * lastChar = firstChar + origLen - 1; + if ( (*lastChar != ' ') && (*lastChar != 0) ) return origLen; // Nothing to do.",2920,3251,4096 +18174,"MagickExport XMLTreeInfo *NewXMLTree(const char *xml,ExceptionInfo *exception) +{ + char + **attribute, + **attributes, + *tag, + *utf8; + + int + c, + terminal; + + MagickBooleanType + status; + + register char + *p; + + register ssize_t + i; + + size_t + ignore_depth, + length; + + ssize_t + j, + l; + + XMLTreeRoot + *root; + + /* + Convert xml-string to UTF8. + */ + if ((xml == (const char *) NULL) || (strlen(xml) == 0)) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, + ""ParseError"",""root tag missing""); + return((XMLTreeInfo *) NULL); + } + root=(XMLTreeRoot *) NewXMLTreeTag((char *) NULL); + length=strlen(xml); + utf8=ConvertUTF16ToUTF8(xml,&length); + if (utf8 == (char *) NULL) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, + ""ParseError"",""UTF16 to UTF8 failed""); + return((XMLTreeInfo *) NULL); + } + terminal=utf8[length-1]; + utf8[length-1]='\0'; + p=utf8; + while ((*p != '\0') && (*p != '<')) + p++; + if (*p == '\0') + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, + ""ParseError"",""root tag missing""); + utf8=DestroyString(utf8); + return((XMLTreeInfo *) NULL); + } + attribute=(char **) NULL; + l=0; + ignore_depth=0; + for (p++; ; p++) + { + attributes=(char **) sentinel; + tag=p; + c=(*p); + if ((isalpha((int) ((unsigned char) *p)) !=0) || (*p == '_') || + (*p == ':') || (c < '\0')) + { + /* + Tag. + */ + if (root->node == (XMLTreeInfo *) NULL) + { + (void) ThrowMagickException(exception,GetMagickModule(), + OptionWarning,""ParseError"",""root tag missing""); + utf8=DestroyString(utf8); + return(&root->root); + } + p+=strcspn(p,XMLWhitespace ""/>""); + while (isspace((int) ((unsigned char) *p)) != 0) + *p++='\0'; + if (ignore_depth == 0) + { + if ((*p != '\0') && (*p != '/') && (*p != '>')) + { + /* + Find tag in default attributes list. + */ + i=0; + while ((root->attributes[i] != (char **) NULL) && + (strcmp(root->attributes[i][0],tag) != 0)) + i++; + attribute=root->attributes[i]; + } + for (l=0; (*p != '\0') && (*p != '/') && (*p != '>'); l+=2) + { + /* + Attribute. + */ + if (l == 0) + attributes=(char **) AcquireQuantumMemory(4, + sizeof(*attributes)); + else + attributes=(char **) ResizeQuantumMemory(attributes, + (size_t) (l+4),sizeof(*attributes)); + if (attributes == (char **) NULL) + { + (void) ThrowMagickException(exception,GetMagickModule(), + ResourceLimitError,""MemoryAllocationFailed"",""`%s'"",""""); + utf8=DestroyString(utf8); + return(&root->root); + } + attributes[l+2]=(char *) NULL; + attributes[l+1]=(char *) NULL; + attributes[l]=p; + p+=strcspn(p,XMLWhitespace ""=/>""); + if ((*p != '=') && (isspace((int) ((unsigned char) *p)) == 0)) + attributes[l]=ConstantString(""""); + else + { + *p++='\0'; + p+=strspn(p,XMLWhitespace ""=""); + c=(*p); + if ((c == '""') || (c == '\'')) + { + /* + Attributes value. + */ + p++; + attributes[l+1]=p; + while ((*p != '\0') && (*p != c)) + p++; + if (*p != '\0') + *p++='\0'; + else + { + attributes[l]=ConstantString(""""); + attributes[l+1]=ConstantString(""""); + (void) DestroyXMLTreeAttributes(attributes); + (void) ThrowMagickException(exception, + GetMagickModule(),OptionWarning,""ParseError"", + ""missing %c"",c); + utf8=DestroyString(utf8); + return(&root->root); + } + j=1; + while ((attribute != (char **) NULL) && + (attribute[j] != (char *) NULL) && + (strcmp(attribute[j],attributes[l]) != 0)) + j+=3; + attributes[l+1]=ParseEntities(attributes[l+1], + root->entities,(attribute != (char **) NULL) && + (attribute[j] != (char *) NULL) ? *attribute[j+2] : + ' '); + } + attributes[l]=ConstantString(attributes[l]); + } + while (isspace((int) ((unsigned char) *p)) != 0) + p++; + } + } + else + { + while((*p != '\0') && (*p != '/') && (*p != '>')) + p++; + } + if (*p == '/') + { + /* + Self closing tag. + */ + *p++='\0'; + if (((*p != '\0') && (*p != '>')) || + ((*p == '\0') && (terminal != '>'))) + { + if (l != 0) + (void) DestroyXMLTreeAttributes(attributes); + (void) ThrowMagickException(exception,GetMagickModule(), + OptionWarning,""ParseError"",""missing >""); + utf8=DestroyString(utf8); + return(&root->root); + } + if ((ignore_depth == 0) && (IsSkipTag(tag) == MagickFalse)) + { + ParseOpenTag(root,tag,attributes); + (void) ParseCloseTag(root,tag,exception); + } + } + else + { + c=(*p); + if ((*p == '>') || ((*p == '\0') && (terminal == '>'))) + { + *p='\0'; + if ((ignore_depth == 0) && (IsSkipTag(tag) == MagickFalse)) + ParseOpenTag(root,tag,attributes); + else + ignore_depth++; + *p=c; + } + else + { + if (l != 0) + (void) DestroyXMLTreeAttributes(attributes); + (void) ThrowMagickException(exception,GetMagickModule(), + OptionWarning,""ParseError"",""missing >""); + utf8=DestroyString(utf8); + return(&root->root); + } + } + } + else + if (*p == '/') + { + /* + Close tag. + */ + tag=p+1; + p+=strcspn(tag,XMLWhitespace "">"")+1; + c=(*p); + if ((c == '\0') && (terminal != '>')) + { + (void) ThrowMagickException(exception,GetMagickModule(), + OptionWarning,""ParseError"",""missing >""); + utf8=DestroyString(utf8); + return(&root->root); + } + *p='\0'; + if (ignore_depth == 0 && ParseCloseTag(root,tag,exception) != + (XMLTreeInfo *) NULL) + { + utf8=DestroyString(utf8); + return(&root->root); + } + if (ignore_depth > 0) + ignore_depth--; + *p=c; + if (isspace((int) ((unsigned char) *p)) != 0) + p+=strspn(p,XMLWhitespace); + } + else + if (strncmp(p,""!--"",3) == 0) + { + /* + Comment. + */ + p=strstr(p+3,""--""); + if ((p == (char *) NULL) || ((*(p+=2) != '>') && (*p != '\0')) || + ((*p == '\0') && (terminal != '>'))) + { + (void) ThrowMagickException(exception,GetMagickModule(), + OptionWarning,""ParseError"",""unclosed %3d "" + ""| SWITCH_PAGE (Attr code page) |"", + *codepage_attr); + off += 2; + break; + case 0x01: /* END */ + /* BEWARE + * The Attribute END token means either "">"" or ""/>"" + * and as a consequence both must be treated separately. + * This is done in the TAG state parser. + */ + off++; + DebugLog((""ATTR: level = %u, Return: len = %u\n"", + level, off - offset)); + return (off - offset); + case 0x02: /* ENTITY */ + ent = tvb_get_guintvar (tvb, off+1, &len); + proto_tree_add_text (tree, tvb, off, 1+len, + "" %3d | Attr | A %3d "" + ""| ENTITY "" + ""| %s'&#%u;'"", + level, *codepage_attr, Indent (level), ent); + off += 1+len; + break; + case 0x03: /* STR_I */ + len = tvb_strsize (tvb, off+1); + proto_tree_add_text (tree, tvb, off, 1+len, + "" %3d | Attr | A %3d "" + ""| STR_I (Inline string) "" + ""| %s\'%s\'"", + level, *codepage_attr, Indent (level), + tvb_format_text (tvb, off+1, len-1)); + off += 1+len; + break; + case 0x04: /* LITERAL */ + /* ALWAYS means the start of a new attribute, + * and may only contain the NAME of the attribute. + */ + idx = tvb_get_guintvar (tvb, off+1, &len); + str_len = tvb_strsize (tvb, str_tbl+idx); + attr_save_known = 0; + attr_save_literal = tvb_format_text (tvb, + str_tbl+idx, str_len-1); + proto_tree_add_text (tree, tvb, off, 1+len, + "" %3d | Attr | A %3d "" + ""| LITERAL (Literal Attribute) "" + ""| %s<%s />"", + level, *codepage_attr, Indent (level), + attr_save_literal); + off += 1+len; + break; + case 0x40: /* EXT_I_0 */ + case 0x41: /* EXT_I_1 */ + case 0x42: /* EXT_I_2 */ + /* Extension tokens */ + len = tvb_strsize (tvb, off+1); + proto_tree_add_text (tree, tvb, off, 1+len, + "" %3d | Attr | A %3d "" + ""| EXT_I_%1x (Extension Token) "" + ""| %s(%s: \'%s\')"", + level, *codepage_attr, peek & 0x0f, Indent (level), + map_token (map->global, 0, peek), + tvb_format_text (tvb, off+1, len-1)); + off += 1+len; + break; + /* 0x43 impossible in ATTR state */ + /* 0x44 impossible in ATTR state */ + case 0x80: /* EXT_T_0 */ + case 0x81: /* EXT_T_1 */ + case 0x82: /* EXT_T_2 */ + /* Extension tokens */ + idx = tvb_get_guintvar (tvb, off+1, &len); + { char *s; + + if (map->ext_t[peek & 0x03]) + s = (map->ext_t[peek & 0x03])(tvb, idx, str_tbl); + else + s = wmem_strdup_printf(wmem_packet_scope(), ""EXT_T_%1x (%s)"", peek & 0x03, + map_token (map->global, 0, peek)); + + proto_tree_add_text (tree, tvb, off, 1+len, + "" %3d | Tag | T %3d "" + ""| EXT_T_%1x (Extension Token) "" + ""| %s%s)"", + level, *codepage_attr, peek & 0x0f, Indent (level), + s); + } + off += 1+len; + break; + case 0x83: /* STR_T */ + idx = tvb_get_guintvar (tvb, off+1, &len); + str_len = tvb_strsize (tvb, str_tbl+idx); + proto_tree_add_text (tree, tvb, off, 1+len, + "" %3d | Attr | A %3d "" + ""| STR_T (Tableref string) "" + ""| %s\'%s\'"", + level, *codepage_attr, Indent (level), + tvb_format_text (tvb, str_tbl+idx, str_len-1)); + off += 1+len; + break; + /* 0x84 impossible in ATTR state */ + case 0xC0: /* EXT_0 */ + case 0xC1: /* EXT_1 */ + case 0xC2: /* EXT_2 */ + /* Extension tokens */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Attr | A %3d "" + ""| EXT_%1x (Extension Token) "" + ""| %s(%s)"", + level, *codepage_attr, peek & 0x0f, Indent (level), + map_token (map->global, 0, peek)); + off++; + break; + case 0xC3: /* OPAQUE - WBXML 1.1 and newer */ + if (tvb_get_guint8 (tvb, 0)) { /* WBXML 1.x (x > 0) */ + char *str; + if (attr_save_known) { /* Knwon attribute */ + if (map->opaque_binary_attr) { + str = map->opaque_binary_attr(tvb, off + 1, + attr_save_known, *codepage_attr, &len); + } else { + str = default_opaque_binary_attr(tvb, off + 1, + attr_save_known, *codepage_attr, &len); + } + } else { /* lITERAL attribute */ + if (map->opaque_literal_tag) { + str = map->opaque_literal_attr(tvb, off + 1, + attr_save_literal, *codepage_attr, &len); + } else { + str = default_opaque_literal_attr(tvb, off + 1, + attr_save_literal, *codepage_attr, &len); + } + } + proto_tree_add_text (tree, tvb, off, 1 + len, + "" %3d | Attr | A %3d "" + ""| OPAQUE (Opaque data) "" + ""| %s%s"", + level, *codepage_attr, Indent (level), str); + off += 1 + len; + } else { /* WBXML 1.0 - RESERVED_2 token (invalid) */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Attr | A %3d "" + ""| RESERVED_2 (Invalid Token!) "" + ""| WBXML 1.0 parsing stops here."", + level, *codepage_attr); + /* Stop processing as it is impossible to parse now */ + off = tvb_len; + DebugLog((""ATTR: level = %u, Return: len = %u\n"", + level, off - offset)); + return (off - offset); + } + break; + /* 0xC4 impossible in ATTR state */ + default: + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Attr | A %3d "" + ""| %-10s (Invalid Token!) "" + ""| WBXML parsing stops here."", + level, *codepage_attr, + val_to_str_ext (peek, &vals_wbxml1x_global_tokens_ext, ""(unknown 0x%x)"")); + /* Move to end of buffer */ + off = tvb_len; + break; + } else { /* Known atribute token */ + if (peek & 0x80) { /* attrValue */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Attr | A %3d "" + ""| Known attrValue 0x%02X "" + ""| %s%s"", + level, *codepage_attr, peek & 0x7f, Indent (level), + map_token (map->attrValue, *codepage_attr, peek)); + off++; + } else { /* attrStart */ + attr_save_known = peek & 0x7f; + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Attr | A %3d "" + ""| Known attrStart 0x%02X "" + ""| %s%s"", + level, *codepage_attr, attr_save_known, Indent (level), + map_token (map->attrStart, *codepage_attr, peek)); + off++; + } + } + } /* End WHILE */ + DebugLog((""ATTR: level = %u, Return: len = %u (end of function body)\n"", + level, off - offset)); + return (off - offset); +} +",1,"parse_wbxml_attribute_list_defined (proto_tree *tree, tvbuff_t *tvb, + guint32 offset, guint32 str_tbl, guint8 level, guint8 *codepage_attr, + const wbxml_decoding *map) + { + guint32 tvb_len = tvb_reported_length (tvb); + guint32 off = offset, last_off; + guint32 len; + guint str_len; + guint32 ent; + guint32 idx; + guint8 peek; + guint8 attr_save_known = 0; /* Will contain peek & 0x3F (attr identity) */ + const char *attr_save_literal = NULL; /* Will contain the LITERAL attr identity */ + + DebugLog((""parse_wbxml_attr_defined (level = %u, offset = %u)\n"", + level, offset)); + /* Parse attributes */ + last_off = off; + while (off < tvb_len) { + peek = tvb_get_guint8 (tvb, off); + DebugLog((""ATTR: (top of while) level = %3u, peek = 0x%02X, "" + ""off = %u, tvb_len = %u\n"", level, peek, off, tvb_len)); + if ((peek & 0x3F) < 5) switch (peek) { /* Global tokens + in state = ATTR */ + case 0x00: /* SWITCH_PAGE */ + *codepage_attr = tvb_get_guint8 (tvb, off+1); + proto_tree_add_text (tree, tvb, off, 2, + "" | Attr | A -->%3d "" + ""| SWITCH_PAGE (Attr code page) |"", + *codepage_attr); + off += 2; + break; + case 0x01: /* END */ + /* BEWARE + * The Attribute END token means either "">"" or ""/>"" + * and as a consequence both must be treated separately. + * This is done in the TAG state parser. + */ + off++; + DebugLog((""ATTR: level = %u, Return: len = %u\n"", + level, off - offset)); + return (off - offset); + case 0x02: /* ENTITY */ + ent = tvb_get_guintvar (tvb, off+1, &len); + proto_tree_add_text (tree, tvb, off, 1+len, + "" %3d | Attr | A %3d "" + ""| ENTITY "" + ""| %s'&#%u;'"", + level, *codepage_attr, Indent (level), ent); + off += 1+len; + break; + case 0x03: /* STR_I */ + len = tvb_strsize (tvb, off+1); + proto_tree_add_text (tree, tvb, off, 1+len, + "" %3d | Attr | A %3d "" + ""| STR_I (Inline string) "" + ""| %s\'%s\'"", + level, *codepage_attr, Indent (level), + tvb_format_text (tvb, off+1, len-1)); + off += 1+len; + break; + case 0x04: /* LITERAL */ + /* ALWAYS means the start of a new attribute, + * and may only contain the NAME of the attribute. + */ + idx = tvb_get_guintvar (tvb, off+1, &len); + str_len = tvb_strsize (tvb, str_tbl+idx); + attr_save_known = 0; + attr_save_literal = tvb_format_text (tvb, + str_tbl+idx, str_len-1); + proto_tree_add_text (tree, tvb, off, 1+len, + "" %3d | Attr | A %3d "" + ""| LITERAL (Literal Attribute) "" + ""| %s<%s />"", + level, *codepage_attr, Indent (level), + attr_save_literal); + off += 1+len; + break; + case 0x40: /* EXT_I_0 */ + case 0x41: /* EXT_I_1 */ + case 0x42: /* EXT_I_2 */ + /* Extension tokens */ + len = tvb_strsize (tvb, off+1); + proto_tree_add_text (tree, tvb, off, 1+len, + "" %3d | Attr | A %3d "" + ""| EXT_I_%1x (Extension Token) "" + ""| %s(%s: \'%s\')"", + level, *codepage_attr, peek & 0x0f, Indent (level), + map_token (map->global, 0, peek), + tvb_format_text (tvb, off+1, len-1)); + off += 1+len; + break; + /* 0x43 impossible in ATTR state */ + /* 0x44 impossible in ATTR state */ + case 0x80: /* EXT_T_0 */ + case 0x81: /* EXT_T_1 */ + case 0x82: /* EXT_T_2 */ + /* Extension tokens */ + idx = tvb_get_guintvar (tvb, off+1, &len); + { char *s; + + if (map->ext_t[peek & 0x03]) + s = (map->ext_t[peek & 0x03])(tvb, idx, str_tbl); + else + s = wmem_strdup_printf(wmem_packet_scope(), ""EXT_T_%1x (%s)"", peek & 0x03, + map_token (map->global, 0, peek)); + + proto_tree_add_text (tree, tvb, off, 1+len, + "" %3d | Tag | T %3d "" + ""| EXT_T_%1x (Extension Token) "" + ""| %s%s)"", + level, *codepage_attr, peek & 0x0f, Indent (level), + s); + } + off += 1+len; + break; + case 0x83: /* STR_T */ + idx = tvb_get_guintvar (tvb, off+1, &len); + str_len = tvb_strsize (tvb, str_tbl+idx); + proto_tree_add_text (tree, tvb, off, 1+len, + "" %3d | Attr | A %3d "" + ""| STR_T (Tableref string) "" + ""| %s\'%s\'"", + level, *codepage_attr, Indent (level), + tvb_format_text (tvb, str_tbl+idx, str_len-1)); + off += 1+len; + break; + /* 0x84 impossible in ATTR state */ + case 0xC0: /* EXT_0 */ + case 0xC1: /* EXT_1 */ + case 0xC2: /* EXT_2 */ + /* Extension tokens */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Attr | A %3d "" + ""| EXT_%1x (Extension Token) "" + ""| %s(%s)"", + level, *codepage_attr, peek & 0x0f, Indent (level), + map_token (map->global, 0, peek)); + off++; + break; + case 0xC3: /* OPAQUE - WBXML 1.1 and newer */ + if (tvb_get_guint8 (tvb, 0)) { /* WBXML 1.x (x > 0) */ + char *str; + if (attr_save_known) { /* Knwon attribute */ + if (map->opaque_binary_attr) { + str = map->opaque_binary_attr(tvb, off + 1, + attr_save_known, *codepage_attr, &len); + } else { + str = default_opaque_binary_attr(tvb, off + 1, + attr_save_known, *codepage_attr, &len); + } + } else { /* lITERAL attribute */ + if (map->opaque_literal_tag) { + str = map->opaque_literal_attr(tvb, off + 1, + attr_save_literal, *codepage_attr, &len); + } else { + str = default_opaque_literal_attr(tvb, off + 1, + attr_save_literal, *codepage_attr, &len); + } + } + proto_tree_add_text (tree, tvb, off, 1 + len, + "" %3d | Attr | A %3d "" + ""| OPAQUE (Opaque data) "" + ""| %s%s"", + level, *codepage_attr, Indent (level), str); + off += 1 + len; + } else { /* WBXML 1.0 - RESERVED_2 token (invalid) */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Attr | A %3d "" + ""| RESERVED_2 (Invalid Token!) "" + ""| WBXML 1.0 parsing stops here."", + level, *codepage_attr); + /* Stop processing as it is impossible to parse now */ + off = tvb_len; + DebugLog((""ATTR: level = %u, Return: len = %u\n"", + level, off - offset)); + return (off - offset); + } + break; + /* 0xC4 impossible in ATTR state */ + default: + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Attr | A %3d "" + ""| %-10s (Invalid Token!) "" + ""| WBXML parsing stops here."", + level, *codepage_attr, + val_to_str_ext (peek, &vals_wbxml1x_global_tokens_ext, ""(unknown 0x%x)"")); + /* Move to end of buffer */ + off = tvb_len; + break; + } else { /* Known atribute token */ + if (peek & 0x80) { /* attrValue */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Attr | A %3d "" + ""| Known attrValue 0x%02X "" + ""| %s%s"", + level, *codepage_attr, peek & 0x7f, Indent (level), + map_token (map->attrValue, *codepage_attr, peek)); + off++; + } else { /* attrStart */ + attr_save_known = peek & 0x7f; + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Attr | A %3d "" + ""| Known attrStart 0x%02X "" + ""| %s%s"", + level, *codepage_attr, attr_save_known, Indent (level), + map_token (map->attrStart, *codepage_attr, peek)); + off++; + } + } + if (off < last_off) { + THROW(ReportedBoundsError); + } + last_off = off; + } /* End WHILE */ + DebugLog((""ATTR: level = %u, Return: len = %u (end of function body)\n"", + level, off - offset)); + return (off - offset); +} +","@@ -7304,7 +7304,7 @@ parse_wbxml_tag_defined (proto_tree *tree, tvbuff_t *tvb, guint32 offset, + const wbxml_decoding *map) + { + guint32 tvb_len = tvb_reported_length (tvb); +- guint32 off = offset; ++ guint32 off = offset, last_off; + guint32 len; + guint str_len; + guint32 ent; +@@ -7323,6 +7323,7 @@ parse_wbxml_tag_defined (proto_tree *tree, tvbuff_t *tvb, guint32 offset, + tag_save_literal = NULL; /* Prevents compiler warning */ + + DebugLog((""parse_wbxml_tag_defined (level = %u, offset = %u)\n"", *level, offset)); ++ last_off = off; + while (off < tvb_len) { + peek = tvb_get_guint8 (tvb, off); + DebugLog((""STAG: (top of while) level = %3u, peek = 0x%02X, off = %u, tvb_len = %u\n"", *level, peek, off, tvb_len)); +@@ -7694,6 +7695,10 @@ parse_wbxml_tag_defined (proto_tree *tree, tvbuff_t *tvb, guint32 offset, + /* TODO: Do I have to reset code page here? */ + } + } /* if (tag & 0x3F) >= 5 */ ++ if (off < last_off) { ++ THROW(ReportedBoundsError); ++ } ++ last_off = off; + } /* while */ + DebugLog((""STAG: level = %u, Return: len = %u (end of function body)\n"", *level, off - offset)); + return (off - offset); +@@ -7711,7 +7716,7 @@ parse_wbxml_tag (proto_tree *tree, tvbuff_t *tvb, guint32 offset, + guint8 *codepage_stag, guint8 *codepage_attr) + { + guint32 tvb_len = tvb_reported_length (tvb); +- guint32 off = offset; ++ guint32 off = offset, last_off; + guint32 len; + guint str_len; + guint32 ent; +@@ -7732,6 +7737,7 @@ parse_wbxml_tag (proto_tree *tree, tvbuff_t *tvb, guint32 offset, + tag_save_literal = NULL; /* Prevents compiler warning */ + + DebugLog((""parse_wbxml_tag (level = %u, offset = %u)\n"", *level, offset)); ++ last_off = off; + while (off < tvb_len) { + peek = tvb_get_guint8 (tvb, off); + DebugLog((""STAG: (top of while) level = %3u, peek = 0x%02X, off = %u, tvb_len = %u\n"", *level, peek, off, tvb_len)); +@@ -8091,6 +8097,10 @@ parse_wbxml_tag (proto_tree *tree, tvbuff_t *tvb, guint32 offset, + /* TODO: Do I have to reset code page here? */ + } + } /* if (tag & 0x3F) >= 5 */ ++ if (off < last_off) { ++ THROW(ReportedBoundsError); ++ } ++ last_off = off; + } /* while */ + DebugLog((""STAG: level = %u, Return: len = %u (end of function body)\n"", + *level, off - offset)); +@@ -8126,7 +8136,7 @@ parse_wbxml_attribute_list_defined (proto_tree *tree, tvbuff_t *tvb, + const wbxml_decoding *map) + { + guint32 tvb_len = tvb_reported_length (tvb); +- guint32 off = offset; ++ guint32 off = offset, last_off; + guint32 len; + guint str_len; + guint32 ent; +@@ -8138,6 +8148,7 @@ parse_wbxml_attribute_list_defined (proto_tree *tree, tvbuff_t *tvb, + DebugLog((""parse_wbxml_attr_defined (level = %u, offset = %u)\n"", + level, offset)); + /* Parse attributes */ ++ last_off = off; + while (off < tvb_len) { + peek = tvb_get_guint8 (tvb, off); + DebugLog((""ATTR: (top of while) level = %3u, peek = 0x%02X, "" +@@ -8330,6 +8341,10 @@ parse_wbxml_attribute_list_defined (proto_tree *tree, tvbuff_t *tvb, + off++; + } + } ++ if (off < last_off) { ++ THROW(ReportedBoundsError); ++ } ++ last_off = off; + } /* End WHILE */ + DebugLog((""ATTR: level = %u, Return: len = %u (end of function body)\n"", + level, off - offset)); +@@ -8350,7 +8365,7 @@ parse_wbxml_attribute_list (proto_tree *tree, tvbuff_t *tvb, + guint32 offset, guint32 str_tbl, guint8 level, guint8 *codepage_attr) + { + guint32 tvb_len = tvb_reported_length (tvb); +- guint32 off = offset; ++ guint32 off = offset, last_off; + guint32 len; + guint str_len; + guint32 ent; +@@ -8359,6 +8374,7 @@ parse_wbxml_attribute_list (proto_tree *tree, tvbuff_t *tvb, + + DebugLog((""parse_wbxml_attr (level = %u, offset = %u)\n"", level, offset)); + /* Parse attributes */ ++ last_off = off; + while (off < tvb_len) { + peek = tvb_get_guint8 (tvb, off); + DebugLog((""ATTR: (top of while) level = %3u, peek = 0x%02X, "" +@@ -8516,6 +8532,10 @@ parse_wbxml_attribute_list (proto_tree *tree, tvbuff_t *tvb, + off++; + } + } ++ if (off < last_off) { ++ THROW(ReportedBoundsError); ++ } ++ last_off = off; + } /* End WHILE */ + DebugLog((""ATTR: level = %u, Return: len = %u (end of function body)\n"", + level, off - offset));",2516,2847,4096 +8247,"int WriteRiffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode) +{ + int do_rf64 = 0, write_junk = 1, table_length = 0; + ChunkHeader ds64hdr, datahdr, fmthdr; + RiffChunkHeader riffhdr; + DS64Chunk ds64_chunk; + CS64Chunk cs64_chunk; + JunkChunk junkchunk; + WaveHeader wavhdr; + uint32_t bcount; + + int64_t total_data_bytes, total_riff_bytes; + int num_channels = WavpackGetNumChannels (wpc); + int32_t channel_mask = WavpackGetChannelMask (wpc); + int32_t sample_rate = WavpackGetSampleRate (wpc); + int bytes_per_sample = WavpackGetBytesPerSample (wpc); + int bits_per_sample = WavpackGetBitsPerSample (wpc); + int format = WavpackGetFloatNormExp (wpc) ? 3 : 1; + int wavhdrsize = 16; + + if (format == 3 && WavpackGetFloatNormExp (wpc) != 127) { + error_line (""can't create valid RIFF wav header for non-normalized floating data!""); + return FALSE; + } + + if (total_samples == -1) + total_samples = 0x7ffff000 / (bytes_per_sample * num_channels); + + total_data_bytes = total_samples * bytes_per_sample * num_channels; + + if (total_data_bytes > 0xff000000) { + if (debug_logging_mode) + error_line (""total_data_bytes = %lld, so rf64"", total_data_bytes); + write_junk = 0; + do_rf64 = 1; + } + else if (debug_logging_mode) + error_line (""total_data_bytes = %lld, so riff"", total_data_bytes); + + CLEAR (wavhdr); + + wavhdr.FormatTag = format; + wavhdr.NumChannels = num_channels; + wavhdr.SampleRate = sample_rate; + wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample; + wavhdr.BlockAlign = bytes_per_sample * num_channels; + wavhdr.BitsPerSample = bits_per_sample; + + if (num_channels > 2 || channel_mask != 0x5 - num_channels) { + wavhdrsize = sizeof (wavhdr); + wavhdr.cbSize = 22; + wavhdr.ValidBitsPerSample = bits_per_sample; + wavhdr.SubFormat = format; + wavhdr.ChannelMask = channel_mask; + wavhdr.FormatTag = 0xfffe; + wavhdr.BitsPerSample = bytes_per_sample * 8; + wavhdr.GUID [4] = 0x10; + wavhdr.GUID [6] = 0x80; + wavhdr.GUID [9] = 0xaa; + wavhdr.GUID [11] = 0x38; + wavhdr.GUID [12] = 0x9b; + wavhdr.GUID [13] = 0x71; + } + + strncpy (riffhdr.ckID, do_rf64 ? ""RF64"" : ""RIFF"", sizeof (riffhdr.ckID)); + strncpy (riffhdr.formType, ""WAVE"", sizeof (riffhdr.formType)); + total_riff_bytes = sizeof (riffhdr) + wavhdrsize + sizeof (datahdr) + ((total_data_bytes + 1) & ~(int64_t)1); + if (do_rf64) total_riff_bytes += sizeof (ds64hdr) + sizeof (ds64_chunk); + total_riff_bytes += table_length * sizeof (CS64Chunk); + if (write_junk) total_riff_bytes += sizeof (junkchunk); + strncpy (fmthdr.ckID, ""fmt "", sizeof (fmthdr.ckID)); + strncpy (datahdr.ckID, ""data"", sizeof (datahdr.ckID)); + fmthdr.ckSize = wavhdrsize; + + if (write_junk) { + CLEAR (junkchunk); + strncpy (junkchunk.ckID, ""junk"", sizeof (junkchunk.ckID)); + junkchunk.ckSize = sizeof (junkchunk) - 8; + WavpackNativeToLittleEndian (&junkchunk, ChunkHeaderFormat); + } + + if (do_rf64) { + strncpy (ds64hdr.ckID, ""ds64"", sizeof (ds64hdr.ckID)); + ds64hdr.ckSize = sizeof (ds64_chunk) + (table_length * sizeof (CS64Chunk)); + CLEAR (ds64_chunk); + ds64_chunk.riffSize64 = total_riff_bytes; + ds64_chunk.dataSize64 = total_data_bytes; + ds64_chunk.sampleCount64 = total_samples; + ds64_chunk.tableLength = table_length; + riffhdr.ckSize = (uint32_t) -1; + datahdr.ckSize = (uint32_t) -1; + WavpackNativeToLittleEndian (&ds64hdr, ChunkHeaderFormat); + WavpackNativeToLittleEndian (&ds64_chunk, DS64ChunkFormat); + } + else { + riffhdr.ckSize = (uint32_t) total_riff_bytes; + datahdr.ckSize = (uint32_t) total_data_bytes; + } + + + if (table_length) { + strncpy (cs64_chunk.ckID, ""dmmy"", sizeof (cs64_chunk.ckID)); + cs64_chunk.chunkSize64 = 12345678; + WavpackNativeToLittleEndian (&cs64_chunk, CS64ChunkFormat); + } + + + WavpackNativeToLittleEndian (&riffhdr, ChunkHeaderFormat); + WavpackNativeToLittleEndian (&fmthdr, ChunkHeaderFormat); + WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat); + WavpackNativeToLittleEndian (&datahdr, ChunkHeaderFormat); + + if (!DoWriteFile (outfile, &riffhdr, sizeof (riffhdr), &bcount) || bcount != sizeof (riffhdr) || + (do_rf64 && (!DoWriteFile (outfile, &ds64hdr, sizeof (ds64hdr), &bcount) || bcount != sizeof (ds64hdr))) || + (do_rf64 && (!DoWriteFile (outfile, &ds64_chunk, sizeof (ds64_chunk), &bcount) || bcount != sizeof (ds64_chunk)))) { + error_line (""can't write .WAV data, disk probably full!""); + return FALSE; + } + + + while (table_length--) + if (!DoWriteFile (outfile, &cs64_chunk, sizeof (cs64_chunk), &bcount) || bcount != sizeof (cs64_chunk)) { + error_line (""can't write .WAV data, disk probably full!""); + return FALSE; + } + + + if ((write_junk && (!DoWriteFile (outfile, &junkchunk, sizeof (junkchunk), &bcount) || bcount != sizeof (junkchunk))) || + !DoWriteFile (outfile, &fmthdr, sizeof (fmthdr), &bcount) || bcount != sizeof (fmthdr) || + !DoWriteFile (outfile, &wavhdr, wavhdrsize, &bcount) || bcount != wavhdrsize || + !DoWriteFile (outfile, &datahdr, sizeof (datahdr), &bcount) || bcount != sizeof (datahdr)) { + error_line (""can't write .WAV data, disk probably full!""); + return FALSE; + } + + return TRUE; +} +",0,"int WriteRiffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode) +{ + int do_rf64 = 0, write_junk = 1, table_length = 0; + ChunkHeader ds64hdr, datahdr, fmthdr; + RiffChunkHeader riffhdr; + DS64Chunk ds64_chunk; + CS64Chunk cs64_chunk; + JunkChunk junkchunk; + WaveHeader wavhdr; + uint32_t bcount; + + int64_t total_data_bytes, total_riff_bytes; + int num_channels = WavpackGetNumChannels (wpc); + int32_t channel_mask = WavpackGetChannelMask (wpc); + int32_t sample_rate = WavpackGetSampleRate (wpc); + int bytes_per_sample = WavpackGetBytesPerSample (wpc); + int bits_per_sample = WavpackGetBitsPerSample (wpc); + int format = WavpackGetFloatNormExp (wpc) ? 3 : 1; + int wavhdrsize = 16; + + if (format == 3 && WavpackGetFloatNormExp (wpc) != 127) { + error_line (""can't create valid RIFF wav header for non-normalized floating data!""); + return FALSE; + } + + if (total_samples == -1) + total_samples = 0x7ffff000 / (bytes_per_sample * num_channels); + + total_data_bytes = total_samples * bytes_per_sample * num_channels; + + if (total_data_bytes > 0xff000000) { + if (debug_logging_mode) + error_line (""total_data_bytes = %lld, so rf64"", total_data_bytes); + write_junk = 0; + do_rf64 = 1; + } + else if (debug_logging_mode) + error_line (""total_data_bytes = %lld, so riff"", total_data_bytes); + + CLEAR (wavhdr); + + wavhdr.FormatTag = format; + wavhdr.NumChannels = num_channels; + wavhdr.SampleRate = sample_rate; + wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample; + wavhdr.BlockAlign = bytes_per_sample * num_channels; + wavhdr.BitsPerSample = bits_per_sample; + + if (num_channels > 2 || channel_mask != 0x5 - num_channels) { + wavhdrsize = sizeof (wavhdr); + wavhdr.cbSize = 22; + wavhdr.ValidBitsPerSample = bits_per_sample; + wavhdr.SubFormat = format; + wavhdr.ChannelMask = channel_mask; + wavhdr.FormatTag = 0xfffe; + wavhdr.BitsPerSample = bytes_per_sample * 8; + wavhdr.GUID [4] = 0x10; + wavhdr.GUID [6] = 0x80; + wavhdr.GUID [9] = 0xaa; + wavhdr.GUID [11] = 0x38; + wavhdr.GUID [12] = 0x9b; + wavhdr.GUID [13] = 0x71; + } + + strncpy (riffhdr.ckID, do_rf64 ? ""RF64"" : ""RIFF"", sizeof (riffhdr.ckID)); + strncpy (riffhdr.formType, ""WAVE"", sizeof (riffhdr.formType)); + total_riff_bytes = sizeof (riffhdr) + wavhdrsize + sizeof (datahdr) + ((total_data_bytes + 1) & ~(int64_t)1); + if (do_rf64) total_riff_bytes += sizeof (ds64hdr) + sizeof (ds64_chunk); + total_riff_bytes += table_length * sizeof (CS64Chunk); + if (write_junk) total_riff_bytes += sizeof (junkchunk); + strncpy (fmthdr.ckID, ""fmt "", sizeof (fmthdr.ckID)); + strncpy (datahdr.ckID, ""data"", sizeof (datahdr.ckID)); + fmthdr.ckSize = wavhdrsize; + + if (write_junk) { + CLEAR (junkchunk); + strncpy (junkchunk.ckID, ""junk"", sizeof (junkchunk.ckID)); + junkchunk.ckSize = sizeof (junkchunk) - 8; + WavpackNativeToLittleEndian (&junkchunk, ChunkHeaderFormat); + } + + if (do_rf64) { + strncpy (ds64hdr.ckID, ""ds64"", sizeof (ds64hdr.ckID)); + ds64hdr.ckSize = sizeof (ds64_chunk) + (table_length * sizeof (CS64Chunk)); + CLEAR (ds64_chunk); + ds64_chunk.riffSize64 = total_riff_bytes; + ds64_chunk.dataSize64 = total_data_bytes; + ds64_chunk.sampleCount64 = total_samples; + ds64_chunk.tableLength = table_length; + riffhdr.ckSize = (uint32_t) -1; + datahdr.ckSize = (uint32_t) -1; + WavpackNativeToLittleEndian (&ds64hdr, ChunkHeaderFormat); + WavpackNativeToLittleEndian (&ds64_chunk, DS64ChunkFormat); + } + else { + riffhdr.ckSize = (uint32_t) total_riff_bytes; + datahdr.ckSize = (uint32_t) total_data_bytes; + } + + + if (table_length) { + strncpy (cs64_chunk.ckID, ""dmmy"", sizeof (cs64_chunk.ckID)); + cs64_chunk.chunkSize64 = 12345678; + WavpackNativeToLittleEndian (&cs64_chunk, CS64ChunkFormat); + } + + + WavpackNativeToLittleEndian (&riffhdr, ChunkHeaderFormat); + WavpackNativeToLittleEndian (&fmthdr, ChunkHeaderFormat); + WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat); + WavpackNativeToLittleEndian (&datahdr, ChunkHeaderFormat); + + if (!DoWriteFile (outfile, &riffhdr, sizeof (riffhdr), &bcount) || bcount != sizeof (riffhdr) || + (do_rf64 && (!DoWriteFile (outfile, &ds64hdr, sizeof (ds64hdr), &bcount) || bcount != sizeof (ds64hdr))) || + (do_rf64 && (!DoWriteFile (outfile, &ds64_chunk, sizeof (ds64_chunk), &bcount) || bcount != sizeof (ds64_chunk)))) { + error_line (""can't write .WAV data, disk probably full!""); + return FALSE; + } + + + while (table_length--) + if (!DoWriteFile (outfile, &cs64_chunk, sizeof (cs64_chunk), &bcount) || bcount != sizeof (cs64_chunk)) { + error_line (""can't write .WAV data, disk probably full!""); + return FALSE; + } + + + if ((write_junk && (!DoWriteFile (outfile, &junkchunk, sizeof (junkchunk), &bcount) || bcount != sizeof (junkchunk))) || + !DoWriteFile (outfile, &fmthdr, sizeof (fmthdr), &bcount) || bcount != sizeof (fmthdr) || + !DoWriteFile (outfile, &wavhdr, wavhdrsize, &bcount) || bcount != wavhdrsize || + !DoWriteFile (outfile, &datahdr, sizeof (datahdr), &bcount) || bcount != sizeof (datahdr)) { + error_line (""can't write .WAV data, disk probably full!""); + return FALSE; + } + + return TRUE; +} +","@@ -286,7 +286,14 @@ int ParseRiffHeaderConfig (FILE *infile, char *infilename, char *fourcc, Wavpack + else { // just copy unknown chunks to output file + + int bytes_to_copy = (chunk_header.ckSize + 1) & ~1L; +- char *buff = malloc (bytes_to_copy); ++ char *buff; ++ ++ if (bytes_to_copy < 0 || bytes_to_copy > 4194304) { ++ error_line (""%s is not a valid .WAV file!"", infilename); ++ return WAVPACK_SOFT_ERROR; ++ } ++ ++ buff = malloc (bytes_to_copy); + + if (debug_logging_mode) + error_line (""extra unknown chunk \""%c%c%c%c\"" of %d bytes"",",1728,2059,4096 +980,"select_and_cluster(void) +{ + peer_t *p; + llist_t *item; + int i, j; + int size = 3 * G.peer_cnt; + /* for selection algorithm */ + point_t point[size]; + unsigned num_points, num_candidates; + double low, high; + unsigned num_falsetickers; + /* for cluster algorithm */ + survivor_t survivor[size]; + unsigned num_survivors; + + /* Selection */ + + num_points = 0; + item = G.ntp_peers; + while (item != NULL) { + double rd, offset; + + p = (peer_t *) item->data; + rd = root_distance(p); + offset = p->filter_offset; + if (!fit(p, rd)) { + item = item->link; + continue; + } + + VERB5 bb_error_msg(""interval: [%f %f %f] %s"", + offset - rd, + offset, + offset + rd, + p->p_dotted + ); + point[num_points].p = p; + point[num_points].type = -1; + point[num_points].edge = offset - rd; + point[num_points].opt_rd = rd; + num_points++; + point[num_points].p = p; + point[num_points].type = 0; + point[num_points].edge = offset; + point[num_points].opt_rd = rd; + num_points++; + point[num_points].p = p; + point[num_points].type = 1; + point[num_points].edge = offset + rd; + point[num_points].opt_rd = rd; + num_points++; + item = item->link; + } + num_candidates = num_points / 3; + if (num_candidates == 0) { + VERB3 bb_error_msg(""no valid datapoints%s"", "", no peer selected""); + return NULL; + } + qsort(point, num_points, sizeof(point[0]), compare_point_edge); + + /* Start with the assumption that there are no falsetickers. + * Attempt to find a nonempty intersection interval containing + * the midpoints of all truechimers. + * If a nonempty interval cannot be found, increase the number + * of assumed falsetickers by one and try again. + * If a nonempty interval is found and the number of falsetickers + * is less than the number of truechimers, a majority has been found + * and the midpoint of each truechimer represents + * the candidates available to the cluster algorithm. + */ + num_falsetickers = 0; + while (1) { + int c; + unsigned num_midpoints = 0; + + low = 1 << 9; + high = - (1 << 9); + c = 0; + for (i = 0; i < num_points; i++) { + /* We want to do: + * if (point[i].type == -1) c++; + * if (point[i].type == 1) c--; + * and it's simpler to do it this way: + */ + c -= point[i].type; + if (c >= num_candidates - num_falsetickers) { + /* If it was c++ and it got big enough... */ + low = point[i].edge; + break; + } + if (point[i].type == 0) + num_midpoints++; + } + c = 0; + for (i = num_points-1; i >= 0; i--) { + c += point[i].type; + if (c >= num_candidates - num_falsetickers) { + high = point[i].edge; + break; + } + if (point[i].type == 0) + num_midpoints++; + } + /* If the number of midpoints is greater than the number + * of allowed falsetickers, the intersection contains at + * least one truechimer with no midpoint - bad. + * Also, interval should be nonempty. + */ + if (num_midpoints <= num_falsetickers && low < high) + break; + num_falsetickers++; + if (num_falsetickers * 2 >= num_candidates) { + VERB3 bb_error_msg(""falsetickers:%d, candidates:%d%s"", + num_falsetickers, num_candidates, + "", no peer selected""); + return NULL; + } + } + VERB4 bb_error_msg(""selected interval: [%f, %f]; candidates:%d falsetickers:%d"", + low, high, num_candidates, num_falsetickers); + + /* Clustering */ + + /* Construct a list of survivors (p, metric) + * from the chime list, where metric is dominated + * first by stratum and then by root distance. + * All other things being equal, this is the order of preference. + */ + num_survivors = 0; + for (i = 0; i < num_points; i++) { + if (point[i].edge < low || point[i].edge > high) + continue; + p = point[i].p; + survivor[num_survivors].p = p; + /* x.opt_rd == root_distance(p); */ + survivor[num_survivors].metric = MAXDIST * p->lastpkt_stratum + point[i].opt_rd; + VERB5 bb_error_msg(""survivor[%d] metric:%f peer:%s"", + num_survivors, survivor[num_survivors].metric, p->p_dotted); + num_survivors++; + } + /* There must be at least MIN_SELECTED survivors to satisfy the + * correctness assertions. Ordinarily, the Byzantine criteria + * require four survivors, but for the demonstration here, one + * is acceptable. + */ + if (num_survivors < MIN_SELECTED) { + VERB3 bb_error_msg(""survivors:%d%s"", + num_survivors, + "", no peer selected""); + return NULL; + } + + qsort(survivor, num_survivors, sizeof(survivor[0]), compare_survivor_metric); + + /* For each association p in turn, calculate the selection + * jitter p->sjitter as the square root of the sum of squares + * (p->offset - q->offset) over all q associations. The idea is + * to repeatedly discard the survivor with maximum selection + * jitter until a termination condition is met. + */ + while (1) { + unsigned max_idx = max_idx; + double max_selection_jitter = max_selection_jitter; + double min_jitter = min_jitter; + + if (num_survivors <= MIN_CLUSTERED) { + VERB4 bb_error_msg(""num_survivors %d <= %d, not discarding more"", + num_survivors, MIN_CLUSTERED); + break; + } + + /* To make sure a few survivors are left + * for the clustering algorithm to chew on, + * we stop if the number of survivors + * is less than or equal to MIN_CLUSTERED (3). + */ + for (i = 0; i < num_survivors; i++) { + double selection_jitter_sq; + + p = survivor[i].p; + if (i == 0 || p->filter_jitter < min_jitter) + min_jitter = p->filter_jitter; + + selection_jitter_sq = 0; + for (j = 0; j < num_survivors; j++) { + peer_t *q = survivor[j].p; + selection_jitter_sq += SQUARE(p->filter_offset - q->filter_offset); + } + if (i == 0 || selection_jitter_sq > max_selection_jitter) { + max_selection_jitter = selection_jitter_sq; + max_idx = i; + } + VERB6 bb_error_msg(""survivor %d selection_jitter^2:%f"", + i, selection_jitter_sq); + } + max_selection_jitter = SQRT(max_selection_jitter / num_survivors); + VERB5 bb_error_msg(""max_selection_jitter (at %d):%f min_jitter:%f"", + max_idx, max_selection_jitter, min_jitter); + + /* If the maximum selection jitter is less than the + * minimum peer jitter, then tossing out more survivors + * will not lower the minimum peer jitter, so we might + * as well stop. + */ + if (max_selection_jitter < min_jitter) { + VERB4 bb_error_msg(""max_selection_jitter:%f < min_jitter:%f, num_survivors:%d, not discarding more"", + max_selection_jitter, min_jitter, num_survivors); + break; + } + + /* Delete survivor[max_idx] from the list + * and go around again. + */ + VERB6 bb_error_msg(""dropping survivor %d"", max_idx); + num_survivors--; + while (max_idx < num_survivors) { + survivor[max_idx] = survivor[max_idx + 1]; + max_idx++; + } + } + + if (0) { + /* Combine the offsets of the clustering algorithm survivors + * using a weighted average with weight determined by the root + * distance. Compute the selection jitter as the weighted RMS + * difference between the first survivor and the remaining + * survivors. In some cases the inherent clock jitter can be + * reduced by not using this algorithm, especially when frequent + * clockhopping is involved. bbox: thus we don't do it. + */ + double x, y, z, w; + y = z = w = 0; + for (i = 0; i < num_survivors; i++) { + p = survivor[i].p; + x = root_distance(p); + y += 1 / x; + z += p->filter_offset / x; + w += SQUARE(p->filter_offset - survivor[0].p->filter_offset) / x; + } + } + + /* Pick the best clock. If the old system peer is on the list + * and at the same stratum as the first survivor on the list, + * then don't do a clock hop. Otherwise, select the first + * survivor on the list as the new system peer. + */ + p = survivor[0].p; + if (G.last_update_peer + && G.last_update_peer->lastpkt_stratum <= p->lastpkt_stratum + ) { + /* Starting from 1 is ok here */ + for (i = 1; i < num_survivors; i++) { + if (G.last_update_peer == survivor[i].p) { + VERB5 bb_error_msg(""keeping old synced peer""); + p = G.last_update_peer; + goto keep_old; + } + } + } + G.last_update_peer = p; + keep_old: + VERB4 bb_error_msg(""selected peer %s filter_offset:%+f age:%f"", + p->p_dotted, + p->filter_offset, + G.cur_time - p->lastpkt_recv_time + ); + return p; +} +",0,"select_and_cluster(void) +{ + peer_t *p; + llist_t *item; + int i, j; + int size = 3 * G.peer_cnt; + /* for selection algorithm */ + point_t point[size]; + unsigned num_points, num_candidates; + double low, high; + unsigned num_falsetickers; + /* for cluster algorithm */ + survivor_t survivor[size]; + unsigned num_survivors; + + /* Selection */ + + num_points = 0; + item = G.ntp_peers; + while (item != NULL) { + double rd, offset; + + p = (peer_t *) item->data; + rd = root_distance(p); + offset = p->filter_offset; + if (!fit(p, rd)) { + item = item->link; + continue; + } + + VERB5 bb_error_msg(""interval: [%f %f %f] %s"", + offset - rd, + offset, + offset + rd, + p->p_dotted + ); + point[num_points].p = p; + point[num_points].type = -1; + point[num_points].edge = offset - rd; + point[num_points].opt_rd = rd; + num_points++; + point[num_points].p = p; + point[num_points].type = 0; + point[num_points].edge = offset; + point[num_points].opt_rd = rd; + num_points++; + point[num_points].p = p; + point[num_points].type = 1; + point[num_points].edge = offset + rd; + point[num_points].opt_rd = rd; + num_points++; + item = item->link; + } + num_candidates = num_points / 3; + if (num_candidates == 0) { + VERB3 bb_error_msg(""no valid datapoints%s"", "", no peer selected""); + return NULL; + } + qsort(point, num_points, sizeof(point[0]), compare_point_edge); + + /* Start with the assumption that there are no falsetickers. + * Attempt to find a nonempty intersection interval containing + * the midpoints of all truechimers. + * If a nonempty interval cannot be found, increase the number + * of assumed falsetickers by one and try again. + * If a nonempty interval is found and the number of falsetickers + * is less than the number of truechimers, a majority has been found + * and the midpoint of each truechimer represents + * the candidates available to the cluster algorithm. + */ + num_falsetickers = 0; + while (1) { + int c; + unsigned num_midpoints = 0; + + low = 1 << 9; + high = - (1 << 9); + c = 0; + for (i = 0; i < num_points; i++) { + /* We want to do: + * if (point[i].type == -1) c++; + * if (point[i].type == 1) c--; + * and it's simpler to do it this way: + */ + c -= point[i].type; + if (c >= num_candidates - num_falsetickers) { + /* If it was c++ and it got big enough... */ + low = point[i].edge; + break; + } + if (point[i].type == 0) + num_midpoints++; + } + c = 0; + for (i = num_points-1; i >= 0; i--) { + c += point[i].type; + if (c >= num_candidates - num_falsetickers) { + high = point[i].edge; + break; + } + if (point[i].type == 0) + num_midpoints++; + } + /* If the number of midpoints is greater than the number + * of allowed falsetickers, the intersection contains at + * least one truechimer with no midpoint - bad. + * Also, interval should be nonempty. + */ + if (num_midpoints <= num_falsetickers && low < high) + break; + num_falsetickers++; + if (num_falsetickers * 2 >= num_candidates) { + VERB3 bb_error_msg(""falsetickers:%d, candidates:%d%s"", + num_falsetickers, num_candidates, + "", no peer selected""); + return NULL; + } + } + VERB4 bb_error_msg(""selected interval: [%f, %f]; candidates:%d falsetickers:%d"", + low, high, num_candidates, num_falsetickers); + + /* Clustering */ + + /* Construct a list of survivors (p, metric) + * from the chime list, where metric is dominated + * first by stratum and then by root distance. + * All other things being equal, this is the order of preference. + */ + num_survivors = 0; + for (i = 0; i < num_points; i++) { + if (point[i].edge < low || point[i].edge > high) + continue; + p = point[i].p; + survivor[num_survivors].p = p; + /* x.opt_rd == root_distance(p); */ + survivor[num_survivors].metric = MAXDIST * p->lastpkt_stratum + point[i].opt_rd; + VERB5 bb_error_msg(""survivor[%d] metric:%f peer:%s"", + num_survivors, survivor[num_survivors].metric, p->p_dotted); + num_survivors++; + } + /* There must be at least MIN_SELECTED survivors to satisfy the + * correctness assertions. Ordinarily, the Byzantine criteria + * require four survivors, but for the demonstration here, one + * is acceptable. + */ + if (num_survivors < MIN_SELECTED) { + VERB3 bb_error_msg(""survivors:%d%s"", + num_survivors, + "", no peer selected""); + return NULL; + } + + qsort(survivor, num_survivors, sizeof(survivor[0]), compare_survivor_metric); + + /* For each association p in turn, calculate the selection + * jitter p->sjitter as the square root of the sum of squares + * (p->offset - q->offset) over all q associations. The idea is + * to repeatedly discard the survivor with maximum selection + * jitter until a termination condition is met. + */ + while (1) { + unsigned max_idx = max_idx; + double max_selection_jitter = max_selection_jitter; + double min_jitter = min_jitter; + + if (num_survivors <= MIN_CLUSTERED) { + VERB4 bb_error_msg(""num_survivors %d <= %d, not discarding more"", + num_survivors, MIN_CLUSTERED); + break; + } + + /* To make sure a few survivors are left + * for the clustering algorithm to chew on, + * we stop if the number of survivors + * is less than or equal to MIN_CLUSTERED (3). + */ + for (i = 0; i < num_survivors; i++) { + double selection_jitter_sq; + + p = survivor[i].p; + if (i == 0 || p->filter_jitter < min_jitter) + min_jitter = p->filter_jitter; + + selection_jitter_sq = 0; + for (j = 0; j < num_survivors; j++) { + peer_t *q = survivor[j].p; + selection_jitter_sq += SQUARE(p->filter_offset - q->filter_offset); + } + if (i == 0 || selection_jitter_sq > max_selection_jitter) { + max_selection_jitter = selection_jitter_sq; + max_idx = i; + } + VERB6 bb_error_msg(""survivor %d selection_jitter^2:%f"", + i, selection_jitter_sq); + } + max_selection_jitter = SQRT(max_selection_jitter / num_survivors); + VERB5 bb_error_msg(""max_selection_jitter (at %d):%f min_jitter:%f"", + max_idx, max_selection_jitter, min_jitter); + + /* If the maximum selection jitter is less than the + * minimum peer jitter, then tossing out more survivors + * will not lower the minimum peer jitter, so we might + * as well stop. + */ + if (max_selection_jitter < min_jitter) { + VERB4 bb_error_msg(""max_selection_jitter:%f < min_jitter:%f, num_survivors:%d, not discarding more"", + max_selection_jitter, min_jitter, num_survivors); + break; + } + + /* Delete survivor[max_idx] from the list + * and go around again. + */ + VERB6 bb_error_msg(""dropping survivor %d"", max_idx); + num_survivors--; + while (max_idx < num_survivors) { + survivor[max_idx] = survivor[max_idx + 1]; + max_idx++; + } + } + + if (0) { + /* Combine the offsets of the clustering algorithm survivors + * using a weighted average with weight determined by the root + * distance. Compute the selection jitter as the weighted RMS + * difference between the first survivor and the remaining + * survivors. In some cases the inherent clock jitter can be + * reduced by not using this algorithm, especially when frequent + * clockhopping is involved. bbox: thus we don't do it. + */ + double x, y, z, w; + y = z = w = 0; + for (i = 0; i < num_survivors; i++) { + p = survivor[i].p; + x = root_distance(p); + y += 1 / x; + z += p->filter_offset / x; + w += SQUARE(p->filter_offset - survivor[0].p->filter_offset) / x; + } + } + + /* Pick the best clock. If the old system peer is on the list + * and at the same stratum as the first survivor on the list, + * then don't do a clock hop. Otherwise, select the first + * survivor on the list as the new system peer. + */ + p = survivor[0].p; + if (G.last_update_peer + && G.last_update_peer->lastpkt_stratum <= p->lastpkt_stratum + ) { + /* Starting from 1 is ok here */ + for (i = 1; i < num_survivors; i++) { + if (G.last_update_peer == survivor[i].p) { + VERB5 bb_error_msg(""keeping old synced peer""); + p = G.last_update_peer; + goto keep_old; + } + } + } + G.last_update_peer = p; + keep_old: + VERB4 bb_error_msg(""selected peer %s filter_offset:%+f age:%f"", + p->p_dotted, + p->filter_offset, + G.cur_time - p->lastpkt_recv_time + ); + return p; +} +","@@ -2051,6 +2051,13 @@ recv_and_process_client_pkt(void /*int fd*/) + goto bail; + } + ++ /* Respond only to client and symmetric active packets */ ++ if ((msg.m_status & MODE_MASK) != MODE_CLIENT ++ && (msg.m_status & MODE_MASK) != MODE_SYM_ACT ++ ) { ++ goto bail; ++ } ++ + query_status = msg.m_status; + query_xmttime = msg.m_xmttime;",2419,2750,4096 +17909,"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; + int exthdrlen; + int dst_exthdrlen; + int hh_len; + int mtu; + 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 + */ + + cork->length += length; + if (length > mtu) { + int proto = sk->sk_protocol; + if (dontfrag && (proto == IPPROTO_UDP || proto == IPPROTO_RAW)){ + ipv6_local_rxpmtu(sk, fl6, mtu-exthdrlen); + return -EMSGSIZE; + } + + if (proto == 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 = skb_peek_tail(&sk->sk_write_queue)) == NULL) + 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); + + 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->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; +} +",1,"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 + */ + + cork->length += length; + if (length > mtu) { + int proto = sk->sk_protocol; + if (dontfrag && (proto == IPPROTO_UDP || proto == IPPROTO_RAW)){ + ipv6_local_rxpmtu(sk, fl6, mtu-exthdrlen); + return -EMSGSIZE; + } + + if (proto == 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 = skb_peek_tail(&sk->sk_write_queue)) == NULL) + 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->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; +} +","@@ -1093,11 +1093,12 @@ static inline struct ipv6_rt_hdr *ip6_rthdr_dup(struct ipv6_rt_hdr *src, + return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL; + } + +-static void ip6_append_data_mtu(int *mtu, ++static void ip6_append_data_mtu(unsigned int *mtu, + int *maxfraglen, + unsigned int fragheaderlen, + struct sk_buff *skb, +- struct rt6_info *rt) ++ struct rt6_info *rt, ++ bool pmtuprobe) + { + if (!(rt->dst.flags & DST_XFRM_TUNNEL)) { + if (skb == NULL) { +@@ -1109,7 +1110,9 @@ static void ip6_append_data_mtu(int *mtu, + * this fragment is not first, the headers + * space is regarded as data space. + */ +- *mtu = dst_mtu(rt->dst.path); ++ *mtu = min(*mtu, pmtuprobe ? ++ rt->dst.dev->mtu : ++ dst_mtu(rt->dst.path)); + } + *maxfraglen = ((*mtu - fragheaderlen) & ~7) + + fragheaderlen - sizeof(struct frag_hdr); +@@ -1126,11 +1129,10 @@ int ip6_append_data(struct sock *sk, int getfrag(void *from, char *to, + struct ipv6_pinfo *np = inet6_sk(sk); + struct inet_cork *cork; + struct sk_buff *skb, *skb_prev = NULL; +- unsigned int maxfraglen, fragheaderlen; ++ unsigned int maxfraglen, fragheaderlen, mtu; + int exthdrlen; + int dst_exthdrlen; + int hh_len; +- int mtu; + int copy; + int err; + int offset = 0; +@@ -1287,7 +1289,9 @@ int ip6_append_data(struct sock *sk, int getfrag(void *from, char *to, + /* update mtu and maxfraglen if necessary */ + if (skb == NULL || skb_prev == NULL) + ip6_append_data_mtu(&mtu, &maxfraglen, +- fragheaderlen, skb, rt); ++ fragheaderlen, skb, rt, ++ np->pmtudisc == ++ IPV6_PMTUDISC_PROBE); + + skb_prev = skb; + ",2971,3302,4096 +17835,"int ssl23_get_client_hello(SSL *s) + { + char buf_space[11]; /* Request this many bytes in initial read. + * We can detect SSL 3.0/TLS 1.0 Client Hellos + * ('type == 3') correctly only when the following + * is in a single record, which is not guaranteed by + * the protocol specification: + * Byte Content + * 0 type \ + * 1/2 version > record header + * 3/4 length / + * 5 msg_type \ + * 6-8 length > Client Hello message + * 9/10 client_version / + */ + char *buf= &(buf_space[0]); + unsigned char *p,*d,*d_len,*dd; + unsigned int i; + unsigned int csl,sil,cl; + int n=0,j; + int type=0; + int v[2]; + + if (s->state == SSL23_ST_SR_CLNT_HELLO_A) + { + /* read the initial header */ + v[0]=v[1]=0; + + if (!ssl3_setup_buffers(s)) goto err; + + n=ssl23_read_bytes(s, sizeof buf_space); + if (n != sizeof buf_space) return(n); /* n == -1 || n == 0 */ + + p=s->packet; + + memcpy(buf,p,n); + + if ((p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO)) + { + /* + * SSLv2 header + */ + if ((p[3] == 0x00) && (p[4] == 0x02)) + { + v[0]=p[3]; v[1]=p[4]; + /* SSLv2 */ + if (!(s->options & SSL_OP_NO_SSLv2)) + type=1; + } + else if (p[3] == SSL3_VERSION_MAJOR) + { + v[0]=p[3]; v[1]=p[4]; + /* SSLv3/TLSv1 */ + if (p[4] >= TLS1_VERSION_MINOR) + { + if (!(s->options & SSL_OP_NO_TLSv1)) + { + s->version=TLS1_VERSION; + /* type=2; */ /* done later to survive restarts */ + s->state=SSL23_ST_SR_CLNT_HELLO_B; + } + else if (!(s->options & SSL_OP_NO_SSLv3)) + { + s->version=SSL3_VERSION; + /* type=2; */ + s->state=SSL23_ST_SR_CLNT_HELLO_B; + } + else if (!(s->options & SSL_OP_NO_SSLv2)) + { + type=1; + } + } + else if (!(s->options & SSL_OP_NO_SSLv3)) + { + s->version=SSL3_VERSION; + /* type=2; */ + s->state=SSL23_ST_SR_CLNT_HELLO_B; + } + else if (!(s->options & SSL_OP_NO_SSLv2)) + type=1; + + } + } + else if ((p[0] == SSL3_RT_HANDSHAKE) && + (p[1] == SSL3_VERSION_MAJOR) && + (p[5] == SSL3_MT_CLIENT_HELLO) && + ((p[3] == 0 && p[4] < 5 /* silly record length? */) + || (p[9] >= p[1]))) + { + /* + * SSLv3 or tls1 header + */ + + v[0]=p[1]; /* major version (= SSL3_VERSION_MAJOR) */ + /* We must look at client_version inside the Client Hello message + * to get the correct minor version. + * However if we have only a pathologically small fragment of the + * Client Hello message, this would be difficult, and we'd have + * to read more records to find out. + * No known SSL 3.0 client fragments ClientHello like this, + * so we simply reject such connections to avoid + * protocol version downgrade attacks. */ + if (p[3] == 0 && p[4] < 6) + { + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_SMALL); + goto err; + } + /* if major version number > 3 set minor to a value + * which will use the highest version 3 we support. + * If TLS 2.0 ever appears we will need to revise + * this.... + */ + if (p[9] > SSL3_VERSION_MAJOR) + v[1]=0xff; + else + v[1]=p[10]; /* minor version according to client_version */ + if (v[1] >= TLS1_VERSION_MINOR) + { + if (!(s->options & SSL_OP_NO_TLSv1)) + { + s->version=TLS1_VERSION; + type=3; + } + else if (!(s->options & SSL_OP_NO_SSLv3)) + { + s->version=SSL3_VERSION; + type=3; + } + } + else + { + /* client requests SSL 3.0 */ + if (!(s->options & SSL_OP_NO_SSLv3)) + { + s->version=SSL3_VERSION; + type=3; + } + else if (!(s->options & SSL_OP_NO_TLSv1)) + { + /* we won't be able to use TLS of course, + * but this will send an appropriate alert */ + s->version=TLS1_VERSION; + type=3; + } + } + } + else if ((strncmp(""GET "", (char *)p,4) == 0) || + (strncmp(""POST "",(char *)p,5) == 0) || + (strncmp(""HEAD "",(char *)p,5) == 0) || + (strncmp(""PUT "", (char *)p,4) == 0)) + { + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTP_REQUEST); + goto err; + } + else if (strncmp(""CONNECT"",(char *)p,7) == 0) + { + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTPS_PROXY_REQUEST); + goto err; + } + } + +#ifdef OPENSSL_FIPS + if (FIPS_mode() && (s->version < TLS1_VERSION)) + { + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO, + SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE); + goto err; + } +#endif + + /* ensure that TLS_MAX_VERSION is up-to-date */ + OPENSSL_assert(s->version <= TLS_MAX_VERSION); + + if (s->state == SSL23_ST_SR_CLNT_HELLO_B) + { + /* we have SSLv3/TLSv1 in an SSLv2 header + * (other cases skip this state) */ + + type=2; + p=s->packet; + v[0] = p[3]; /* == SSL3_VERSION_MAJOR */ + v[1] = p[4]; + + /* An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2 + * header is sent directly on the wire, not wrapped as a TLS + * record. It's format is: + * Byte Content + * 0-1 msg_length + * 2 msg_type + * 3-4 version + * 5-6 cipher_spec_length + * 7-8 session_id_length + * 9-10 challenge_length + * ... ... + */ + n=((p[0]&0x7f)<<8)|p[1]; + if (n > (1024*4)) + { + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_LARGE); + goto err; + } + if (n < 9) + { + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH); + goto err; + } + + j=ssl23_read_bytes(s,n+2); + /* We previously read 11 bytes, so if j > 0, we must have + * j == n+2 == s->packet_length. We have at least 11 valid + * packet bytes. */ + if (j <= 0) return(j); + + ssl3_finish_mac(s, s->packet+2, s->packet_length-2); + if (s->msg_callback) + s->msg_callback(0, SSL2_VERSION, 0, s->packet+2, s->packet_length-2, s, s->msg_callback_arg); /* CLIENT-HELLO */ + + p=s->packet; + p+=5; + n2s(p,csl); + n2s(p,sil); + n2s(p,cl); + d=(unsigned char *)s->init_buf->data; + if ((csl+sil+cl+11) != s->packet_length) + { + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH); + goto err; + } + + /* record header: msg_type ... */ + *(d++) = SSL3_MT_CLIENT_HELLO; + /* ... and length (actual value will be written later) */ + d_len = d; + d += 3; + + /* client_version */ + *(d++) = SSL3_VERSION_MAJOR; /* == v[0] */ + *(d++) = v[1]; + + /* lets populate the random area */ + /* get the challenge_length */ + i=(cl > SSL3_RANDOM_SIZE)?SSL3_RANDOM_SIZE:cl; + memset(d,0,SSL3_RANDOM_SIZE); + memcpy(&(d[SSL3_RANDOM_SIZE-i]),&(p[csl+sil]),i); + d+=SSL3_RANDOM_SIZE; + + /* no session-id reuse */ + *(d++)=0; + + /* ciphers */ + j=0; + dd=d; + d+=2; + for (i=0; iinit_buf->data) - 4; + l2n3((long)i, d_len); + + /* get the data reused from the init_buf */ + s->s3->tmp.reuse_message=1; + s->s3->tmp.message_type=SSL3_MT_CLIENT_HELLO; + s->s3->tmp.message_size=i; + } + + /* imaginary new state (for program structure): */ + /* s->state = SSL23_SR_CLNT_HELLO_C */ + + if (type == 1) + { +#ifdef OPENSSL_NO_SSL2 + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL); + goto err; +#else + /* we are talking sslv2 */ + /* we need to clean up the SSLv3/TLSv1 setup and put in the + * sslv2 stuff. */ + + if (s->s2 == NULL) + { + if (!ssl2_new(s)) + goto err; + } + else + ssl2_clear(s); + + if (s->s3 != NULL) ssl3_free(s); + + if (!BUF_MEM_grow_clean(s->init_buf, + SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)) + { + goto err; + } + + s->state=SSL2_ST_GET_CLIENT_HELLO_A; + if (s->options & SSL_OP_NO_TLSv1 && s->options & SSL_OP_NO_SSLv3) + s->s2->ssl2_rollback=0; + else + /* reject SSL 2.0 session if client supports SSL 3.0 or TLS 1.0 + * (SSL 3.0 draft/RFC 2246, App. E.2) */ + s->s2->ssl2_rollback=1; + + /* setup the n bytes we have read so we get them from + * the sslv2 buffer */ + s->rstate=SSL_ST_READ_HEADER; + s->packet_length=n; + s->packet= &(s->s2->rbuf[0]); + memcpy(s->packet,buf,n); + s->s2->rbuf_left=n; + s->s2->rbuf_offs=0; + + s->method=SSLv2_server_method(); + s->handshake_func=s->method->ssl_accept; +#endif + } + + if ((type == 2) || (type == 3)) + { + /* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style) */ + s->method = ssl23_get_server_method(s->version); + if (s->method == NULL) + { + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL); + goto err; + } + + if (!ssl_init_wbio_buffer(s,1)) goto err; + + if (type == 3) + { + /* put the 'n' bytes we have read into the input buffer + * for SSLv3 */ + s->rstate=SSL_ST_READ_HEADER; + s->packet_length=n; + s->packet= &(s->s3->rbuf.buf[0]); + memcpy(s->packet,buf,n); + s->s3->rbuf.left=n; + s->s3->rbuf.offset=0; + } + else + { + s->packet_length=0; + s->s3->rbuf.left=0; + s->s3->rbuf.offset=0; + } +#if 0 /* ssl3_get_client_hello does this */ + s->client_version=(v[0]<<8)|v[1]; +#endif + s->handshake_func=s->method->ssl_accept; + } + + if ((type < 1) || (type > 3)) + { + /* bad, very bad */ + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNKNOWN_PROTOCOL); + goto err; + } + s->init_num=0; + + if (buf != buf_space) OPENSSL_free(buf); + return(SSL_accept(s)); +err: + if (buf != buf_space) OPENSSL_free(buf); + return(-1); + } +",1,"int ssl23_get_client_hello(SSL *s) + { + char buf_space[11]; /* Request this many bytes in initial read. + * We can detect SSL 3.0/TLS 1.0 Client Hellos + * ('type == 3') correctly only when the following + * is in a single record, which is not guaranteed by + * the protocol specification: + * Byte Content + * 0 type \ + * 1/2 version > record header + * 3/4 length / + * 5 msg_type \ + * 6-8 length > Client Hello message + * 9/10 client_version / + */ + char *buf= &(buf_space[0]); + unsigned char *p,*d,*d_len,*dd; + unsigned int i; + unsigned int csl,sil,cl; + int n=0,j; + int type=0; + int v[2]; + + if (s->state == SSL23_ST_SR_CLNT_HELLO_A) + { + /* read the initial header */ + v[0]=v[1]=0; + + if (!ssl3_setup_buffers(s)) goto err; + + n=ssl23_read_bytes(s, sizeof buf_space); + if (n != sizeof buf_space) return(n); /* n == -1 || n == 0 */ + + p=s->packet; + + memcpy(buf,p,n); + + if ((p[0] & 0x80) && (p[2] == SSL2_MT_CLIENT_HELLO)) + { + /* + * SSLv2 header + */ + if ((p[3] == 0x00) && (p[4] == 0x02)) + { + v[0]=p[3]; v[1]=p[4]; + /* SSLv2 */ + if (!(s->options & SSL_OP_NO_SSLv2)) + type=1; + } + else if (p[3] == SSL3_VERSION_MAJOR) + { + v[0]=p[3]; v[1]=p[4]; + /* SSLv3/TLSv1 */ + if (p[4] >= TLS1_VERSION_MINOR) + { + if (!(s->options & SSL_OP_NO_TLSv1)) + { + s->version=TLS1_VERSION; + /* type=2; */ /* done later to survive restarts */ + s->state=SSL23_ST_SR_CLNT_HELLO_B; + } + else if (!(s->options & SSL_OP_NO_SSLv3)) + { + s->version=SSL3_VERSION; + /* type=2; */ + s->state=SSL23_ST_SR_CLNT_HELLO_B; + } + else if (!(s->options & SSL_OP_NO_SSLv2)) + { + type=1; + } + } + else if (!(s->options & SSL_OP_NO_SSLv3)) + { + s->version=SSL3_VERSION; + /* type=2; */ + s->state=SSL23_ST_SR_CLNT_HELLO_B; + } + else if (!(s->options & SSL_OP_NO_SSLv2)) + type=1; + + } + } + else if ((p[0] == SSL3_RT_HANDSHAKE) && + (p[1] == SSL3_VERSION_MAJOR) && + (p[5] == SSL3_MT_CLIENT_HELLO) && + ((p[3] == 0 && p[4] < 5 /* silly record length? */) + || (p[9] >= p[1]))) + { + /* + * SSLv3 or tls1 header + */ + + v[0]=p[1]; /* major version (= SSL3_VERSION_MAJOR) */ + /* We must look at client_version inside the Client Hello message + * to get the correct minor version. + * However if we have only a pathologically small fragment of the + * Client Hello message, this would be difficult, and we'd have + * to read more records to find out. + * No known SSL 3.0 client fragments ClientHello like this, + * so we simply reject such connections to avoid + * protocol version downgrade attacks. */ + if (p[3] == 0 && p[4] < 6) + { + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_SMALL); + goto err; + } + /* if major version number > 3 set minor to a value + * which will use the highest version 3 we support. + * If TLS 2.0 ever appears we will need to revise + * this.... + */ + if (p[9] > SSL3_VERSION_MAJOR) + v[1]=0xff; + else + v[1]=p[10]; /* minor version according to client_version */ + if (v[1] >= TLS1_VERSION_MINOR) + { + if (!(s->options & SSL_OP_NO_TLSv1)) + { + s->version=TLS1_VERSION; + type=3; + } + else if (!(s->options & SSL_OP_NO_SSLv3)) + { + s->version=SSL3_VERSION; + type=3; + } + } + else + { + /* client requests SSL 3.0 */ + if (!(s->options & SSL_OP_NO_SSLv3)) + { + s->version=SSL3_VERSION; + type=3; + } + else if (!(s->options & SSL_OP_NO_TLSv1)) + { + /* we won't be able to use TLS of course, + * but this will send an appropriate alert */ + s->version=TLS1_VERSION; + type=3; + } + } + } + else if ((strncmp(""GET "", (char *)p,4) == 0) || + (strncmp(""POST "",(char *)p,5) == 0) || + (strncmp(""HEAD "",(char *)p,5) == 0) || + (strncmp(""PUT "", (char *)p,4) == 0)) + { + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTP_REQUEST); + goto err; + } + else if (strncmp(""CONNECT"",(char *)p,7) == 0) + { + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_HTTPS_PROXY_REQUEST); + goto err; + } + } + +#ifdef OPENSSL_FIPS + if (FIPS_mode() && (s->version < TLS1_VERSION)) + { + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO, + SSL_R_ONLY_TLS_ALLOWED_IN_FIPS_MODE); + goto err; + } +#endif + + /* ensure that TLS_MAX_VERSION is up-to-date */ + OPENSSL_assert(s->version <= TLS_MAX_VERSION); + + if (s->state == SSL23_ST_SR_CLNT_HELLO_B) + { + /* we have SSLv3/TLSv1 in an SSLv2 header + * (other cases skip this state) */ + + type=2; + p=s->packet; + v[0] = p[3]; /* == SSL3_VERSION_MAJOR */ + v[1] = p[4]; + + /* An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2 + * header is sent directly on the wire, not wrapped as a TLS + * record. It's format is: + * Byte Content + * 0-1 msg_length + * 2 msg_type + * 3-4 version + * 5-6 cipher_spec_length + * 7-8 session_id_length + * 9-10 challenge_length + * ... ... + */ + n=((p[0]&0x7f)<<8)|p[1]; + if (n > (1024*4)) + { + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_TOO_LARGE); + goto err; + } + if (n < 9) + { + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH); + goto err; + } + + j=ssl23_read_bytes(s,n+2); + /* We previously read 11 bytes, so if j > 0, we must have + * j == n+2 == s->packet_length. We have at least 11 valid + * packet bytes. */ + if (j <= 0) return(j); + + ssl3_finish_mac(s, s->packet+2, s->packet_length-2); + if (s->msg_callback) + s->msg_callback(0, SSL2_VERSION, 0, s->packet+2, s->packet_length-2, s, s->msg_callback_arg); /* CLIENT-HELLO */ + + p=s->packet; + p+=5; + n2s(p,csl); + n2s(p,sil); + n2s(p,cl); + d=(unsigned char *)s->init_buf->data; + if ((csl+sil+cl+11) != s->packet_length) + { + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_RECORD_LENGTH_MISMATCH); + goto err; + } + + /* record header: msg_type ... */ + *(d++) = SSL3_MT_CLIENT_HELLO; + /* ... and length (actual value will be written later) */ + d_len = d; + d += 3; + + /* client_version */ + *(d++) = SSL3_VERSION_MAJOR; /* == v[0] */ + *(d++) = v[1]; + + /* lets populate the random area */ + /* get the challenge_length */ + i=(cl > SSL3_RANDOM_SIZE)?SSL3_RANDOM_SIZE:cl; + memset(d,0,SSL3_RANDOM_SIZE); + memcpy(&(d[SSL3_RANDOM_SIZE-i]),&(p[csl+sil]),i); + d+=SSL3_RANDOM_SIZE; + + /* no session-id reuse */ + *(d++)=0; + + /* ciphers */ + j=0; + dd=d; + d+=2; + for (i=0; iinit_buf->data) - 4; + l2n3((long)i, d_len); + + /* get the data reused from the init_buf */ + s->s3->tmp.reuse_message=1; + s->s3->tmp.message_type=SSL3_MT_CLIENT_HELLO; + s->s3->tmp.message_size=i; + } + + /* imaginary new state (for program structure): */ + /* s->state = SSL23_SR_CLNT_HELLO_C */ + + if (type == 1) + { +#ifdef OPENSSL_NO_SSL2 + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL); + goto err; +#else + /* we are talking sslv2 */ + /* we need to clean up the SSLv3/TLSv1 setup and put in the + * sslv2 stuff. */ + + if (s->s2 == NULL) + { + if (!ssl2_new(s)) + goto err; + } + else + ssl2_clear(s); + + if (s->s3 != NULL) ssl3_free(s); + + if (!BUF_MEM_grow_clean(s->init_buf, + SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER)) + { + goto err; + } + + s->state=SSL2_ST_GET_CLIENT_HELLO_A; + if (s->options & SSL_OP_NO_TLSv1 && s->options & SSL_OP_NO_SSLv3) + s->s2->ssl2_rollback=0; + else + /* reject SSL 2.0 session if client supports SSL 3.0 or TLS 1.0 + * (SSL 3.0 draft/RFC 2246, App. E.2) */ + s->s2->ssl2_rollback=1; + + /* setup the n bytes we have read so we get them from + * the sslv2 buffer */ + s->rstate=SSL_ST_READ_HEADER; + s->packet_length=n; + s->packet= &(s->s2->rbuf[0]); + memcpy(s->packet,buf,n); + s->s2->rbuf_left=n; + s->s2->rbuf_offs=0; + + s->method=SSLv2_server_method(); + s->handshake_func=s->method->ssl_accept; +#endif + } + + if ((type == 2) || (type == 3)) + { + /* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style) */ + const SSL_METHOD *new_method; + new_method = ssl23_get_server_method(s->version); + if (new_method == NULL) + { + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL); + goto err; + } + s->method = new_method; + + if (!ssl_init_wbio_buffer(s,1)) goto err; + + if (type == 3) + { + /* put the 'n' bytes we have read into the input buffer + * for SSLv3 */ + s->rstate=SSL_ST_READ_HEADER; + s->packet_length=n; + s->packet= &(s->s3->rbuf.buf[0]); + memcpy(s->packet,buf,n); + s->s3->rbuf.left=n; + s->s3->rbuf.offset=0; + } + else + { + s->packet_length=0; + s->s3->rbuf.left=0; + s->s3->rbuf.offset=0; + } +#if 0 /* ssl3_get_client_hello does this */ + s->client_version=(v[0]<<8)|v[1]; +#endif + s->handshake_func=s->method->ssl_accept; + } + + if ((type < 1) || (type > 3)) + { + /* bad, very bad */ + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNKNOWN_PROTOCOL); + goto err; + } + s->init_num=0; + + if (buf != buf_space) OPENSSL_free(buf); + return(SSL_accept(s)); +err: + if (buf != buf_space) OPENSSL_free(buf); + return(-1); + } +","@@ -559,12 +559,14 @@ int ssl23_get_client_hello(SSL *s) + if ((type == 2) || (type == 3)) + { + /* we have SSLv3/TLSv1 (type 2: SSL2 style, type 3: SSL3/TLS style) */ +- s->method = ssl23_get_server_method(s->version); +- if (s->method == NULL) ++ const SSL_METHOD *new_method; ++ new_method = ssl23_get_server_method(s->version); ++ if (new_method == NULL) + { + SSLerr(SSL_F_SSL23_GET_CLIENT_HELLO,SSL_R_UNSUPPORTED_PROTOCOL); + goto err; + } ++ s->method = new_method; + + if (!ssl_init_wbio_buffer(s,1)) goto err;",3305,3636,4096 +17440,"void btm_sec_rmt_name_request_complete (UINT8 *p_bd_addr, UINT8 *p_bd_name, UINT8 status) +{ + tBTM_SEC_DEV_REC *p_dev_rec; + int i; + DEV_CLASS dev_class; + UINT8 old_sec_state; + + BTM_TRACE_EVENT (""btm_sec_rmt_name_request_complete""); + if (((p_bd_addr == NULL) && !BTM_ACL_IS_CONNECTED(btm_cb.connecting_bda)) + || ((p_bd_addr != NULL) && !BTM_ACL_IS_CONNECTED(p_bd_addr))) + { + btm_acl_resubmit_page(); + } + + /* If remote name request failed, p_bd_addr is null and we need to search */ + /* based on state assuming that we are doing 1 at a time */ + if (p_bd_addr) + p_dev_rec = btm_find_dev (p_bd_addr); + else + { + p_dev_rec = &btm_cb.sec_dev_rec[0]; + + for (i = 0; i < BTM_SEC_MAX_DEVICE_RECORDS; i++, p_dev_rec++) + { + if ((p_dev_rec->sec_flags & BTM_SEC_IN_USE) + && (p_dev_rec->sec_state == BTM_SEC_STATE_GETTING_NAME)) + { + p_bd_addr = p_dev_rec->bd_addr; + break; + } + } + + if (i == BTM_SEC_MAX_DEVICE_RECORDS) + p_dev_rec = NULL; + } + + + /* Commenting out trace due to obf/compilation problems. + */ +#if (BT_USE_TRACES == TRUE) + if (!p_bd_name) + p_bd_name = (UINT8 *)""""; + + if (p_dev_rec) + { + BTM_TRACE_EVENT (""Security Manager: rmt_name_complete PairState: %s RemName: %s status: %d State:%d p_dev_rec: 0x%08x "", + btm_pair_state_descr (btm_cb.pairing_state), p_bd_name, + status, p_dev_rec->sec_state, p_dev_rec); + } + else + { + BTM_TRACE_EVENT (""Security Manager: rmt_name_complete PairState: %s RemName: %s status: %d"", + btm_pair_state_descr (btm_cb.pairing_state), p_bd_name, + status); + } +#endif + + if (p_dev_rec) + { + old_sec_state = p_dev_rec->sec_state; + if (status == HCI_SUCCESS) + { + BCM_STRNCPY_S ((char *)p_dev_rec->sec_bd_name, sizeof (p_dev_rec->sec_bd_name), (char *)p_bd_name, BTM_MAX_REM_BD_NAME_LEN); + p_dev_rec->sec_flags |= BTM_SEC_NAME_KNOWN; + BTM_TRACE_EVENT (""setting BTM_SEC_NAME_KNOWN sec_flags:0x%x"", p_dev_rec->sec_flags); + } + else + { + /* Notify all clients waiting for name to be resolved even if it failed so clients can continue */ + p_dev_rec->sec_bd_name[0] = 0; + } + + if (p_dev_rec->sec_state == BTM_SEC_STATE_GETTING_NAME) + p_dev_rec->sec_state = BTM_SEC_STATE_IDLE; + + /* Notify all clients waiting for name to be resolved */ + for (i = 0;i < BTM_SEC_MAX_RMT_NAME_CALLBACKS; i++) + { + if (btm_cb.p_rmt_name_callback[i] && p_bd_addr) + (*btm_cb.p_rmt_name_callback[i])(p_bd_addr, p_dev_rec->dev_class, + p_dev_rec->sec_bd_name); + } + } + else + { + dev_class[0] = 0; + dev_class[1] = 0; + dev_class[2] = 0; + + /* Notify all clients waiting for name to be resolved even if not found so clients can continue */ + for (i = 0;i < BTM_SEC_MAX_RMT_NAME_CALLBACKS; i++) + { + if (btm_cb.p_rmt_name_callback[i] && p_bd_addr) + (*btm_cb.p_rmt_name_callback[i])(p_bd_addr, dev_class, (UINT8 *)""""); + } + + return; + } + + /* If we were delaying asking UI for a PIN because name was not resolved, ask now */ + if ( (btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_LOCAL_PIN) && p_bd_addr + && (memcmp (btm_cb.pairing_bda, p_bd_addr, BD_ADDR_LEN) == 0) ) + { + BTM_TRACE_EVENT (""btm_sec_rmt_name_request_complete() delayed pin now being requested flags:0x%x, (p_pin_callback=0x%p)"", btm_cb.pairing_flags, btm_cb.api.p_pin_callback); + + if (((btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) == 0) && + ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_PIN_REQD) == 0) && + btm_cb.api.p_pin_callback) + { + BTM_TRACE_EVENT (""btm_sec_rmt_name_request_complete() calling pin_callback""); + btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD; + (*btm_cb.api.p_pin_callback) (p_dev_rec->bd_addr, p_dev_rec->dev_class, p_bd_name); + } + + /* Set the same state again to force the timer to be restarted */ + btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_LOCAL_PIN); + return; + } + + /* Check if we were delaying bonding because name was not resolved */ + if ( btm_cb.pairing_state == BTM_PAIR_STATE_GET_REM_NAME) + { + if (p_bd_addr && memcmp (btm_cb.pairing_bda, p_bd_addr, BD_ADDR_LEN) == 0) + { + BTM_TRACE_EVENT (""btm_sec_rmt_name_request_complete() continue bonding sm4: 0x%04x, status:0x%x"", p_dev_rec->sm4, status); + if(btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_CANCEL_DD) + { + btm_sec_bond_cancel_complete(); + return; + } + + if (status != HCI_SUCCESS) + { + btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE); + + if (btm_cb.api.p_auth_complete_callback) + (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr, p_dev_rec->dev_class, + p_dev_rec->sec_bd_name, status); + return; + } + + /* if peer is very old legacy devices, HCI_RMT_HOST_SUP_FEAT_NOTIFY_EVT is not reported */ + if (BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4)) + { + /* set the KNOWN flag only if BTM_PAIR_FLAGS_REJECTED_CONNECT is not set.*/ + /* If it is set, there may be a race condition */ + BTM_TRACE_DEBUG (""btm_sec_rmt_name_request_complete IS_SM4_UNKNOWN Flags:0x%04x"", + btm_cb.pairing_flags); + if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) == 0) + { + p_dev_rec->sm4 |= BTM_SM4_KNOWN; + } + } + + BTM_TRACE_DEBUG(""%s, SM4 Value: %x, Legacy:%d,IS SM4:%d, Unknown:%d"",__FUNCTION__, + p_dev_rec->sm4, BTM_SEC_IS_SM4_LEGACY(p_dev_rec->sm4), + BTM_SEC_IS_SM4(p_dev_rec->sm4),BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4)); + + /* BT 2.1 or carkit, bring up the connection to force the peer to request PIN. + ** Else prefetch (btm_sec_check_prefetch_pin will do the prefetching if needed) + */ + if ((p_dev_rec->sm4 != BTM_SM4_KNOWN) || !btm_sec_check_prefetch_pin(p_dev_rec)) + { + /* if we rejected incoming connection request, we have to wait HCI_Connection_Complete event */ + /* before originating */ + if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) + { + BTM_TRACE_WARNING (""btm_sec_rmt_name_request_complete: waiting HCI_Connection_Complete after rejecting connection""); + } + /* Both we and the peer are 2.1 - continue to create connection */ + else if (btm_sec_dd_create_conn(p_dev_rec) != BTM_CMD_STARTED) + { + BTM_TRACE_WARNING (""btm_sec_rmt_name_request_complete: failed to start connection""); + + btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE); + + if (btm_cb.api.p_auth_complete_callback) + (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr, p_dev_rec->dev_class, + p_dev_rec->sec_bd_name, HCI_ERR_MEMORY_FULL); + } + } + return; + } + else + { + BTM_TRACE_WARNING (""btm_sec_rmt_name_request_complete: wrong BDA, retry with pairing BDA""); + + BTM_ReadRemoteDeviceName (btm_cb.pairing_bda, NULL, BT_TRANSPORT_BR_EDR); + return; + } + } + + /* check if we were delaying link_key_callback because name was not resolved */ + if (p_dev_rec->link_key_not_sent) + { + /* If HCI connection complete has not arrived, wait for it */ + if (p_dev_rec->hci_handle == BTM_SEC_INVALID_HANDLE) + return; + + p_dev_rec->link_key_not_sent = FALSE; + btm_send_link_key_notif(p_dev_rec); + + /* If its not us who perform authentication, we should tell stackserver */ + /* that some authentication has been completed */ + /* This is required when different entities receive link notification and auth complete */ + if (!(p_dev_rec->security_required & BTM_SEC_OUT_AUTHENTICATE)) + { + if (btm_cb.api.p_auth_complete_callback) + (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr, + p_dev_rec->dev_class, + p_dev_rec->sec_bd_name, HCI_SUCCESS); + + } + } + + /* If this is a bonding procedure can disconnect the link now */ + if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) + && (p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED)) + { + BTM_TRACE_WARNING (""btm_sec_rmt_name_request_complete (none/ce)""); + p_dev_rec->security_required &= ~(BTM_SEC_OUT_AUTHENTICATE); + l2cu_start_post_bond_timer(p_dev_rec->hci_handle); + return; + } + + if (old_sec_state != BTM_SEC_STATE_GETTING_NAME) + return; + + /* If get name failed, notify the waiting layer */ + if (status != HCI_SUCCESS) + { + btm_sec_dev_rec_cback_event (p_dev_rec, BTM_ERR_PROCESSING, FALSE); + return; + } + + if (p_dev_rec->sm4 & BTM_SM4_REQ_PEND) + { + BTM_TRACE_EVENT (""waiting for remote features!!""); + return; + } + + /* Remote Name succeeded, execute the next security procedure, if any */ + status = (UINT8)btm_sec_execute_procedure (p_dev_rec); + + /* If result is pending reply from the user or from the device is pending */ + if (status == BTM_CMD_STARTED) + return; + + /* There is no next procedure or start of procedure failed, notify the waiting layer */ + btm_sec_dev_rec_cback_event (p_dev_rec, status, FALSE); +} +",0,"void btm_sec_rmt_name_request_complete (UINT8 *p_bd_addr, UINT8 *p_bd_name, UINT8 status) +{ + tBTM_SEC_DEV_REC *p_dev_rec; + int i; + DEV_CLASS dev_class; + UINT8 old_sec_state; + + BTM_TRACE_EVENT (""btm_sec_rmt_name_request_complete""); + if (((p_bd_addr == NULL) && !BTM_ACL_IS_CONNECTED(btm_cb.connecting_bda)) + || ((p_bd_addr != NULL) && !BTM_ACL_IS_CONNECTED(p_bd_addr))) + { + btm_acl_resubmit_page(); + } + + /* If remote name request failed, p_bd_addr is null and we need to search */ + /* based on state assuming that we are doing 1 at a time */ + if (p_bd_addr) + p_dev_rec = btm_find_dev (p_bd_addr); + else + { + p_dev_rec = &btm_cb.sec_dev_rec[0]; + + for (i = 0; i < BTM_SEC_MAX_DEVICE_RECORDS; i++, p_dev_rec++) + { + if ((p_dev_rec->sec_flags & BTM_SEC_IN_USE) + && (p_dev_rec->sec_state == BTM_SEC_STATE_GETTING_NAME)) + { + p_bd_addr = p_dev_rec->bd_addr; + break; + } + } + + if (i == BTM_SEC_MAX_DEVICE_RECORDS) + p_dev_rec = NULL; + } + + + /* Commenting out trace due to obf/compilation problems. + */ +#if (BT_USE_TRACES == TRUE) + if (!p_bd_name) + p_bd_name = (UINT8 *)""""; + + if (p_dev_rec) + { + BTM_TRACE_EVENT (""Security Manager: rmt_name_complete PairState: %s RemName: %s status: %d State:%d p_dev_rec: 0x%08x "", + btm_pair_state_descr (btm_cb.pairing_state), p_bd_name, + status, p_dev_rec->sec_state, p_dev_rec); + } + else + { + BTM_TRACE_EVENT (""Security Manager: rmt_name_complete PairState: %s RemName: %s status: %d"", + btm_pair_state_descr (btm_cb.pairing_state), p_bd_name, + status); + } +#endif + + if (p_dev_rec) + { + old_sec_state = p_dev_rec->sec_state; + if (status == HCI_SUCCESS) + { + BCM_STRNCPY_S ((char *)p_dev_rec->sec_bd_name, sizeof (p_dev_rec->sec_bd_name), (char *)p_bd_name, BTM_MAX_REM_BD_NAME_LEN); + p_dev_rec->sec_flags |= BTM_SEC_NAME_KNOWN; + BTM_TRACE_EVENT (""setting BTM_SEC_NAME_KNOWN sec_flags:0x%x"", p_dev_rec->sec_flags); + } + else + { + /* Notify all clients waiting for name to be resolved even if it failed so clients can continue */ + p_dev_rec->sec_bd_name[0] = 0; + } + + if (p_dev_rec->sec_state == BTM_SEC_STATE_GETTING_NAME) + p_dev_rec->sec_state = BTM_SEC_STATE_IDLE; + + /* Notify all clients waiting for name to be resolved */ + for (i = 0;i < BTM_SEC_MAX_RMT_NAME_CALLBACKS; i++) + { + if (btm_cb.p_rmt_name_callback[i] && p_bd_addr) + (*btm_cb.p_rmt_name_callback[i])(p_bd_addr, p_dev_rec->dev_class, + p_dev_rec->sec_bd_name); + } + } + else + { + dev_class[0] = 0; + dev_class[1] = 0; + dev_class[2] = 0; + + /* Notify all clients waiting for name to be resolved even if not found so clients can continue */ + for (i = 0;i < BTM_SEC_MAX_RMT_NAME_CALLBACKS; i++) + { + if (btm_cb.p_rmt_name_callback[i] && p_bd_addr) + (*btm_cb.p_rmt_name_callback[i])(p_bd_addr, dev_class, (UINT8 *)""""); + } + + return; + } + + /* If we were delaying asking UI for a PIN because name was not resolved, ask now */ + if ( (btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_LOCAL_PIN) && p_bd_addr + && (memcmp (btm_cb.pairing_bda, p_bd_addr, BD_ADDR_LEN) == 0) ) + { + BTM_TRACE_EVENT (""btm_sec_rmt_name_request_complete() delayed pin now being requested flags:0x%x, (p_pin_callback=0x%p)"", btm_cb.pairing_flags, btm_cb.api.p_pin_callback); + + if (((btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) == 0) && + ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_PIN_REQD) == 0) && + btm_cb.api.p_pin_callback) + { + BTM_TRACE_EVENT (""btm_sec_rmt_name_request_complete() calling pin_callback""); + btm_cb.pairing_flags |= BTM_PAIR_FLAGS_PIN_REQD; + (*btm_cb.api.p_pin_callback) (p_dev_rec->bd_addr, p_dev_rec->dev_class, p_bd_name); + } + + /* Set the same state again to force the timer to be restarted */ + btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_LOCAL_PIN); + return; + } + + /* Check if we were delaying bonding because name was not resolved */ + if ( btm_cb.pairing_state == BTM_PAIR_STATE_GET_REM_NAME) + { + if (p_bd_addr && memcmp (btm_cb.pairing_bda, p_bd_addr, BD_ADDR_LEN) == 0) + { + BTM_TRACE_EVENT (""btm_sec_rmt_name_request_complete() continue bonding sm4: 0x%04x, status:0x%x"", p_dev_rec->sm4, status); + if(btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_CANCEL_DD) + { + btm_sec_bond_cancel_complete(); + return; + } + + if (status != HCI_SUCCESS) + { + btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE); + + if (btm_cb.api.p_auth_complete_callback) + (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr, p_dev_rec->dev_class, + p_dev_rec->sec_bd_name, status); + return; + } + + /* if peer is very old legacy devices, HCI_RMT_HOST_SUP_FEAT_NOTIFY_EVT is not reported */ + if (BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4)) + { + /* set the KNOWN flag only if BTM_PAIR_FLAGS_REJECTED_CONNECT is not set.*/ + /* If it is set, there may be a race condition */ + BTM_TRACE_DEBUG (""btm_sec_rmt_name_request_complete IS_SM4_UNKNOWN Flags:0x%04x"", + btm_cb.pairing_flags); + if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) == 0) + { + p_dev_rec->sm4 |= BTM_SM4_KNOWN; + } + } + + BTM_TRACE_DEBUG(""%s, SM4 Value: %x, Legacy:%d,IS SM4:%d, Unknown:%d"",__FUNCTION__, + p_dev_rec->sm4, BTM_SEC_IS_SM4_LEGACY(p_dev_rec->sm4), + BTM_SEC_IS_SM4(p_dev_rec->sm4),BTM_SEC_IS_SM4_UNKNOWN(p_dev_rec->sm4)); + + /* BT 2.1 or carkit, bring up the connection to force the peer to request PIN. + ** Else prefetch (btm_sec_check_prefetch_pin will do the prefetching if needed) + */ + if ((p_dev_rec->sm4 != BTM_SM4_KNOWN) || !btm_sec_check_prefetch_pin(p_dev_rec)) + { + /* if we rejected incoming connection request, we have to wait HCI_Connection_Complete event */ + /* before originating */ + if (btm_cb.pairing_flags & BTM_PAIR_FLAGS_REJECTED_CONNECT) + { + BTM_TRACE_WARNING (""btm_sec_rmt_name_request_complete: waiting HCI_Connection_Complete after rejecting connection""); + } + /* Both we and the peer are 2.1 - continue to create connection */ + else if (btm_sec_dd_create_conn(p_dev_rec) != BTM_CMD_STARTED) + { + BTM_TRACE_WARNING (""btm_sec_rmt_name_request_complete: failed to start connection""); + + btm_sec_change_pairing_state (BTM_PAIR_STATE_IDLE); + + if (btm_cb.api.p_auth_complete_callback) + (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr, p_dev_rec->dev_class, + p_dev_rec->sec_bd_name, HCI_ERR_MEMORY_FULL); + } + } + return; + } + else + { + BTM_TRACE_WARNING (""btm_sec_rmt_name_request_complete: wrong BDA, retry with pairing BDA""); + + BTM_ReadRemoteDeviceName (btm_cb.pairing_bda, NULL, BT_TRANSPORT_BR_EDR); + return; + } + } + + /* check if we were delaying link_key_callback because name was not resolved */ + if (p_dev_rec->link_key_not_sent) + { + /* If HCI connection complete has not arrived, wait for it */ + if (p_dev_rec->hci_handle == BTM_SEC_INVALID_HANDLE) + return; + + p_dev_rec->link_key_not_sent = FALSE; + btm_send_link_key_notif(p_dev_rec); + + /* If its not us who perform authentication, we should tell stackserver */ + /* that some authentication has been completed */ + /* This is required when different entities receive link notification and auth complete */ + if (!(p_dev_rec->security_required & BTM_SEC_OUT_AUTHENTICATE)) + { + if (btm_cb.api.p_auth_complete_callback) + (*btm_cb.api.p_auth_complete_callback) (p_dev_rec->bd_addr, + p_dev_rec->dev_class, + p_dev_rec->sec_bd_name, HCI_SUCCESS); + + } + } + + /* If this is a bonding procedure can disconnect the link now */ + if ((btm_cb.pairing_flags & BTM_PAIR_FLAGS_WE_STARTED_DD) + && (p_dev_rec->sec_flags & BTM_SEC_AUTHENTICATED)) + { + BTM_TRACE_WARNING (""btm_sec_rmt_name_request_complete (none/ce)""); + p_dev_rec->security_required &= ~(BTM_SEC_OUT_AUTHENTICATE); + l2cu_start_post_bond_timer(p_dev_rec->hci_handle); + return; + } + + if (old_sec_state != BTM_SEC_STATE_GETTING_NAME) + return; + + /* If get name failed, notify the waiting layer */ + if (status != HCI_SUCCESS) + { + btm_sec_dev_rec_cback_event (p_dev_rec, BTM_ERR_PROCESSING, FALSE); + return; + } + + if (p_dev_rec->sm4 & BTM_SM4_REQ_PEND) + { + BTM_TRACE_EVENT (""waiting for remote features!!""); + return; + } + + /* Remote Name succeeded, execute the next security procedure, if any */ + status = (UINT8)btm_sec_execute_procedure (p_dev_rec); + + /* If result is pending reply from the user or from the device is pending */ + if (status == BTM_CMD_STARTED) + return; + + /* There is no next procedure or start of procedure failed, notify the waiting layer */ + btm_sec_dev_rec_cback_event (p_dev_rec, status, FALSE); +} +","@@ -1074,13 +1074,6 @@ + + btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); + btm_cb.acl_disc_reason = HCI_SUCCESS; + +-#ifdef PORCHE_PAIRING_CONFLICT +- BTM_TRACE_EVENT(""BTM_PINCodeReply(): Saving pin_len: %d btm_cb.pin_code_len: %d"", pin_len, btm_cb.pin_code_len); +- /* if this was not pre-fetched, save the PIN */ +- if (btm_cb.pin_code_len == 0) +- memcpy (btm_cb.pin_code, p_pin, pin_len); +- btm_cb.pin_code_len_saved = pin_len; +-#endif + btsnd_hcic_pin_code_req_reply (bd_addr, pin_len, p_pin); + } + +@@ -5057,10 +5050,6 @@ + + tBTM_SEC_DEV_REC *p_dev_rec; + tBTM_CB *p_cb = &btm_cb; + +-#ifdef PORCHE_PAIRING_CONFLICT +- UINT8 default_pin_code_len = 4; +- PIN_CODE default_pin_code = {0x30, 0x30, 0x30, 0x30}; +-#endif + BTM_TRACE_EVENT (""btm_sec_pin_code_request() State: %s, BDA:%04x%08x"", + btm_pair_state_descr(btm_cb.pairing_state), + (p_bda[0]<<8)+p_bda[1], (p_bda[2]<<24)+(p_bda[3]<<16)+(p_bda[4]<<8)+p_bda[5] ); +@@ -5070,18 +5059,8 @@ + + if ( (memcmp (p_bda, btm_cb.pairing_bda, BD_ADDR_LEN) == 0) && + (btm_cb.pairing_state == BTM_PAIR_STATE_WAIT_AUTH_COMPLETE) ) + { +- /* fake this out - porshe carkit issue - */ +-// btm_cb.pairing_state = BTM_PAIR_STATE_IDLE; +- if(! btm_cb.pin_code_len_saved) +- { +- btsnd_hcic_pin_code_neg_reply (p_bda); +- return; +- } +- else +- { +- btsnd_hcic_pin_code_req_reply (p_bda, btm_cb.pin_code_len_saved, p_cb->pin_code); +- return; +- } ++ btsnd_hcic_pin_code_neg_reply (p_bda); ++ return; + } + else if ((btm_cb.pairing_state != BTM_PAIR_STATE_WAIT_PIN_REQ) + || memcmp (p_bda, btm_cb.pairing_bda, BD_ADDR_LEN) != 0) +@@ -5089,22 +5068,7 @@ + + BTM_TRACE_WARNING (""btm_sec_pin_code_request() rejected - state: %s"", + btm_pair_state_descr(btm_cb.pairing_state)); + +-#ifdef PORCHE_PAIRING_CONFLICT +- /* reply pin code again due to counter in_rand when local initiates pairing */ +- BTM_TRACE_EVENT (""btm_sec_pin_code_request from remote dev. for local initiated pairing""); +- if(! btm_cb.pin_code_len_saved) +- { +- btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); +- btsnd_hcic_pin_code_req_reply (p_bda, default_pin_code_len, default_pin_code); +- } +- else +- { +- btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_AUTH_COMPLETE); +- btsnd_hcic_pin_code_req_reply (p_bda, btm_cb.pin_code_len_saved, p_cb->pin_code); +- } +-#else + btsnd_hcic_pin_code_neg_reply (p_bda); +-#endif + return; + } + } +@@ -5141,10 +5105,6 @@ + + BTM_TRACE_EVENT (""btm_sec_pin_code_request bonding sending reply""); + btsnd_hcic_pin_code_req_reply (p_bda, btm_cb.pin_code_len, p_cb->pin_code); + +-#ifdef PORCHE_PAIRING_CONFLICT +- btm_cb.pin_code_len_saved = btm_cb.pin_code_len; +-#endif +- + /* Mark that we forwarded received from the user PIN code */ + btm_cb.pin_code_len = 0; + +@@ -5175,7 +5135,6 @@ + + /* Notify upper layer of PIN request and start expiration timer */ + else + { +- btm_cb.pin_code_len_saved = 0; + btm_sec_change_pairing_state (BTM_PAIR_STATE_WAIT_LOCAL_PIN); + /* Pin code request can not come at the same time as connection request */ + memcpy (p_cb->connecting_bda, p_bda, BD_ADDR_LEN); +",2374,2705,4096 +18787,"status_t BnDrm::onTransact( + uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) { + switch (code) { + case INIT_CHECK: + { + CHECK_INTERFACE(IDrm, data, reply); + reply->writeInt32(initCheck()); + return OK; + } + + case IS_CRYPTO_SUPPORTED: + { + CHECK_INTERFACE(IDrm, data, reply); + uint8_t uuid[16]; + data.read(uuid, sizeof(uuid)); + String8 mimeType = data.readString8(); + reply->writeInt32(isCryptoSchemeSupported(uuid, mimeType)); + + return OK; + } + + case CREATE_PLUGIN: + { + CHECK_INTERFACE(IDrm, data, reply); + uint8_t uuid[16]; + data.read(uuid, sizeof(uuid)); + reply->writeInt32(createPlugin(uuid)); + return OK; + } + + case DESTROY_PLUGIN: + { + CHECK_INTERFACE(IDrm, data, reply); + reply->writeInt32(destroyPlugin()); + return OK; + } + + case OPEN_SESSION: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId; + status_t result = openSession(sessionId); + writeVector(reply, sessionId); + reply->writeInt32(result); + return OK; + } + + case CLOSE_SESSION: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId; + readVector(data, sessionId); + reply->writeInt32(closeSession(sessionId)); + return OK; + } + + case GET_KEY_REQUEST: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId, initData; + + readVector(data, sessionId); + readVector(data, initData); + String8 mimeType = data.readString8(); + DrmPlugin::KeyType keyType = (DrmPlugin::KeyType)data.readInt32(); + + KeyedVector optionalParameters; + uint32_t count = data.readInt32(); + for (size_t i = 0; i < count; ++i) { + String8 key, value; + key = data.readString8(); + value = data.readString8(); + optionalParameters.add(key, value); + } + + + Vector request; + String8 defaultUrl; + DrmPlugin::KeyRequestType keyRequestType; + + status_t result = getKeyRequest(sessionId, initData, mimeType, + keyType, optionalParameters, request, defaultUrl, + &keyRequestType); + + writeVector(reply, request); + reply->writeString8(defaultUrl); + reply->writeInt32(static_cast(keyRequestType)); + reply->writeInt32(result); + return OK; + } + + case PROVIDE_KEY_RESPONSE: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId, response, keySetId; + readVector(data, sessionId); + readVector(data, response); + uint32_t result = provideKeyResponse(sessionId, response, keySetId); + writeVector(reply, keySetId); + reply->writeInt32(result); + return OK; + } + + case REMOVE_KEYS: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector keySetId; + readVector(data, keySetId); + reply->writeInt32(removeKeys(keySetId)); + return OK; + } + + case RESTORE_KEYS: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId, keySetId; + readVector(data, sessionId); + readVector(data, keySetId); + reply->writeInt32(restoreKeys(sessionId, keySetId)); + return OK; + } + + case QUERY_KEY_STATUS: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId; + readVector(data, sessionId); + KeyedVector infoMap; + status_t result = queryKeyStatus(sessionId, infoMap); + size_t count = infoMap.size(); + reply->writeInt32(count); + for (size_t i = 0; i < count; ++i) { + reply->writeString8(infoMap.keyAt(i)); + reply->writeString8(infoMap.valueAt(i)); + } + reply->writeInt32(result); + return OK; + } + + case GET_PROVISION_REQUEST: + { + CHECK_INTERFACE(IDrm, data, reply); + String8 certType = data.readString8(); + String8 certAuthority = data.readString8(); + + Vector request; + String8 defaultUrl; + status_t result = getProvisionRequest(certType, certAuthority, + request, defaultUrl); + writeVector(reply, request); + reply->writeString8(defaultUrl); + reply->writeInt32(result); + return OK; + } + + case PROVIDE_PROVISION_RESPONSE: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector response; + Vector certificate; + Vector wrappedKey; + readVector(data, response); + status_t result = provideProvisionResponse(response, certificate, wrappedKey); + writeVector(reply, certificate); + writeVector(reply, wrappedKey); + reply->writeInt32(result); + return OK; + } + + case UNPROVISION_DEVICE: + { + CHECK_INTERFACE(IDrm, data, reply); + status_t result = unprovisionDevice(); + reply->writeInt32(result); + return OK; + } + + case GET_SECURE_STOPS: + { + CHECK_INTERFACE(IDrm, data, reply); + List > secureStops; + status_t result = getSecureStops(secureStops); + size_t count = secureStops.size(); + reply->writeInt32(count); + List >::iterator iter = secureStops.begin(); + while(iter != secureStops.end()) { + size_t size = iter->size(); + reply->writeInt32(size); + reply->write(iter->array(), iter->size()); + iter++; + } + reply->writeInt32(result); + return OK; + } + + case GET_SECURE_STOP: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector ssid, secureStop; + readVector(data, ssid); + status_t result = getSecureStop(ssid, secureStop); + writeVector(reply, secureStop); + reply->writeInt32(result); + return OK; + } + + case RELEASE_SECURE_STOPS: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector ssRelease; + readVector(data, ssRelease); + reply->writeInt32(releaseSecureStops(ssRelease)); + return OK; + } + + case RELEASE_ALL_SECURE_STOPS: + { + CHECK_INTERFACE(IDrm, data, reply); + reply->writeInt32(releaseAllSecureStops()); + return OK; + } + + case GET_PROPERTY_STRING: + { + CHECK_INTERFACE(IDrm, data, reply); + String8 name = data.readString8(); + String8 value; + status_t result = getPropertyString(name, value); + reply->writeString8(value); + reply->writeInt32(result); + return OK; + } + + case GET_PROPERTY_BYTE_ARRAY: + { + CHECK_INTERFACE(IDrm, data, reply); + String8 name = data.readString8(); + Vector value; + status_t result = getPropertyByteArray(name, value); + writeVector(reply, value); + reply->writeInt32(result); + return OK; + } + + case SET_PROPERTY_STRING: + { + CHECK_INTERFACE(IDrm, data, reply); + String8 name = data.readString8(); + String8 value = data.readString8(); + reply->writeInt32(setPropertyString(name, value)); + return OK; + } + + case SET_PROPERTY_BYTE_ARRAY: + { + CHECK_INTERFACE(IDrm, data, reply); + String8 name = data.readString8(); + Vector value; + readVector(data, value); + reply->writeInt32(setPropertyByteArray(name, value)); + return OK; + } + + case SET_CIPHER_ALGORITHM: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId; + readVector(data, sessionId); + String8 algorithm = data.readString8(); + reply->writeInt32(setCipherAlgorithm(sessionId, algorithm)); + return OK; + } + + case SET_MAC_ALGORITHM: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId; + readVector(data, sessionId); + String8 algorithm = data.readString8(); + reply->writeInt32(setMacAlgorithm(sessionId, algorithm)); + return OK; + } + + case ENCRYPT: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId, keyId, input, iv, output; + readVector(data, sessionId); + readVector(data, keyId); + readVector(data, input); + readVector(data, iv); + uint32_t result = encrypt(sessionId, keyId, input, iv, output); + writeVector(reply, output); + reply->writeInt32(result); + return OK; + } + + case DECRYPT: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId, keyId, input, iv, output; + readVector(data, sessionId); + readVector(data, keyId); + readVector(data, input); + readVector(data, iv); + uint32_t result = decrypt(sessionId, keyId, input, iv, output); + writeVector(reply, output); + reply->writeInt32(result); + return OK; + } + + case SIGN: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId, keyId, message, signature; + readVector(data, sessionId); + readVector(data, keyId); + readVector(data, message); + uint32_t result = sign(sessionId, keyId, message, signature); + writeVector(reply, signature); + reply->writeInt32(result); + return OK; + } + + case VERIFY: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId, keyId, message, signature; + readVector(data, sessionId); + readVector(data, keyId); + readVector(data, message); + readVector(data, signature); + bool match; + uint32_t result = verify(sessionId, keyId, message, signature, match); + reply->writeInt32(match); + reply->writeInt32(result); + return OK; + } + + case SIGN_RSA: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId, message, wrappedKey, signature; + readVector(data, sessionId); + String8 algorithm = data.readString8(); + readVector(data, message); + readVector(data, wrappedKey); + uint32_t result = signRSA(sessionId, algorithm, message, wrappedKey, signature); + writeVector(reply, signature); + reply->writeInt32(result); + return OK; + } + + case SET_LISTENER: { + CHECK_INTERFACE(IDrm, data, reply); + sp listener = + interface_cast(data.readStrongBinder()); + reply->writeInt32(setListener(listener)); + return NO_ERROR; + } break; + + default: + return BBinder::onTransact(code, data, reply, flags); + } +} +",1,"status_t BnDrm::onTransact( + uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) { + switch (code) { + case INIT_CHECK: + { + CHECK_INTERFACE(IDrm, data, reply); + reply->writeInt32(initCheck()); + return OK; + } + + case IS_CRYPTO_SUPPORTED: + { + CHECK_INTERFACE(IDrm, data, reply); + uint8_t uuid[16]; + data.read(uuid, sizeof(uuid)); + String8 mimeType = data.readString8(); + reply->writeInt32(isCryptoSchemeSupported(uuid, mimeType)); + + return OK; + } + + case CREATE_PLUGIN: + { + CHECK_INTERFACE(IDrm, data, reply); + uint8_t uuid[16]; + data.read(uuid, sizeof(uuid)); + reply->writeInt32(createPlugin(uuid)); + return OK; + } + + case DESTROY_PLUGIN: + { + CHECK_INTERFACE(IDrm, data, reply); + reply->writeInt32(destroyPlugin()); + return OK; + } + + case OPEN_SESSION: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId; + status_t result = openSession(sessionId); + writeVector(reply, sessionId); + reply->writeInt32(result); + return OK; + } + + case CLOSE_SESSION: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId; + readVector(data, sessionId); + reply->writeInt32(closeSession(sessionId)); + return OK; + } + + case GET_KEY_REQUEST: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId, initData; + + readVector(data, sessionId); + readVector(data, initData); + String8 mimeType = data.readString8(); + DrmPlugin::KeyType keyType = (DrmPlugin::KeyType)data.readInt32(); + + KeyedVector optionalParameters; + uint32_t count = data.readInt32(); + for (size_t i = 0; i < count; ++i) { + String8 key, value; + key = data.readString8(); + value = data.readString8(); + optionalParameters.add(key, value); + } + + + Vector request; + String8 defaultUrl; + DrmPlugin::KeyRequestType keyRequestType = DrmPlugin::kKeyRequestType_Unknown; + + status_t result = getKeyRequest(sessionId, initData, mimeType, + keyType, optionalParameters, request, defaultUrl, + &keyRequestType); + + writeVector(reply, request); + reply->writeString8(defaultUrl); + reply->writeInt32(static_cast(keyRequestType)); + reply->writeInt32(result); + return OK; + } + + case PROVIDE_KEY_RESPONSE: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId, response, keySetId; + readVector(data, sessionId); + readVector(data, response); + uint32_t result = provideKeyResponse(sessionId, response, keySetId); + writeVector(reply, keySetId); + reply->writeInt32(result); + return OK; + } + + case REMOVE_KEYS: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector keySetId; + readVector(data, keySetId); + reply->writeInt32(removeKeys(keySetId)); + return OK; + } + + case RESTORE_KEYS: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId, keySetId; + readVector(data, sessionId); + readVector(data, keySetId); + reply->writeInt32(restoreKeys(sessionId, keySetId)); + return OK; + } + + case QUERY_KEY_STATUS: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId; + readVector(data, sessionId); + KeyedVector infoMap; + status_t result = queryKeyStatus(sessionId, infoMap); + size_t count = infoMap.size(); + reply->writeInt32(count); + for (size_t i = 0; i < count; ++i) { + reply->writeString8(infoMap.keyAt(i)); + reply->writeString8(infoMap.valueAt(i)); + } + reply->writeInt32(result); + return OK; + } + + case GET_PROVISION_REQUEST: + { + CHECK_INTERFACE(IDrm, data, reply); + String8 certType = data.readString8(); + String8 certAuthority = data.readString8(); + + Vector request; + String8 defaultUrl; + status_t result = getProvisionRequest(certType, certAuthority, + request, defaultUrl); + writeVector(reply, request); + reply->writeString8(defaultUrl); + reply->writeInt32(result); + return OK; + } + + case PROVIDE_PROVISION_RESPONSE: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector response; + Vector certificate; + Vector wrappedKey; + readVector(data, response); + status_t result = provideProvisionResponse(response, certificate, wrappedKey); + writeVector(reply, certificate); + writeVector(reply, wrappedKey); + reply->writeInt32(result); + return OK; + } + + case UNPROVISION_DEVICE: + { + CHECK_INTERFACE(IDrm, data, reply); + status_t result = unprovisionDevice(); + reply->writeInt32(result); + return OK; + } + + case GET_SECURE_STOPS: + { + CHECK_INTERFACE(IDrm, data, reply); + List > secureStops; + status_t result = getSecureStops(secureStops); + size_t count = secureStops.size(); + reply->writeInt32(count); + List >::iterator iter = secureStops.begin(); + while(iter != secureStops.end()) { + size_t size = iter->size(); + reply->writeInt32(size); + reply->write(iter->array(), iter->size()); + iter++; + } + reply->writeInt32(result); + return OK; + } + + case GET_SECURE_STOP: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector ssid, secureStop; + readVector(data, ssid); + status_t result = getSecureStop(ssid, secureStop); + writeVector(reply, secureStop); + reply->writeInt32(result); + return OK; + } + + case RELEASE_SECURE_STOPS: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector ssRelease; + readVector(data, ssRelease); + reply->writeInt32(releaseSecureStops(ssRelease)); + return OK; + } + + case RELEASE_ALL_SECURE_STOPS: + { + CHECK_INTERFACE(IDrm, data, reply); + reply->writeInt32(releaseAllSecureStops()); + return OK; + } + + case GET_PROPERTY_STRING: + { + CHECK_INTERFACE(IDrm, data, reply); + String8 name = data.readString8(); + String8 value; + status_t result = getPropertyString(name, value); + reply->writeString8(value); + reply->writeInt32(result); + return OK; + } + + case GET_PROPERTY_BYTE_ARRAY: + { + CHECK_INTERFACE(IDrm, data, reply); + String8 name = data.readString8(); + Vector value; + status_t result = getPropertyByteArray(name, value); + writeVector(reply, value); + reply->writeInt32(result); + return OK; + } + + case SET_PROPERTY_STRING: + { + CHECK_INTERFACE(IDrm, data, reply); + String8 name = data.readString8(); + String8 value = data.readString8(); + reply->writeInt32(setPropertyString(name, value)); + return OK; + } + + case SET_PROPERTY_BYTE_ARRAY: + { + CHECK_INTERFACE(IDrm, data, reply); + String8 name = data.readString8(); + Vector value; + readVector(data, value); + reply->writeInt32(setPropertyByteArray(name, value)); + return OK; + } + + case SET_CIPHER_ALGORITHM: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId; + readVector(data, sessionId); + String8 algorithm = data.readString8(); + reply->writeInt32(setCipherAlgorithm(sessionId, algorithm)); + return OK; + } + + case SET_MAC_ALGORITHM: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId; + readVector(data, sessionId); + String8 algorithm = data.readString8(); + reply->writeInt32(setMacAlgorithm(sessionId, algorithm)); + return OK; + } + + case ENCRYPT: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId, keyId, input, iv, output; + readVector(data, sessionId); + readVector(data, keyId); + readVector(data, input); + readVector(data, iv); + uint32_t result = encrypt(sessionId, keyId, input, iv, output); + writeVector(reply, output); + reply->writeInt32(result); + return OK; + } + + case DECRYPT: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId, keyId, input, iv, output; + readVector(data, sessionId); + readVector(data, keyId); + readVector(data, input); + readVector(data, iv); + uint32_t result = decrypt(sessionId, keyId, input, iv, output); + writeVector(reply, output); + reply->writeInt32(result); + return OK; + } + + case SIGN: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId, keyId, message, signature; + readVector(data, sessionId); + readVector(data, keyId); + readVector(data, message); + uint32_t result = sign(sessionId, keyId, message, signature); + writeVector(reply, signature); + reply->writeInt32(result); + return OK; + } + + case VERIFY: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId, keyId, message, signature; + readVector(data, sessionId); + readVector(data, keyId); + readVector(data, message); + readVector(data, signature); + bool match; + uint32_t result = verify(sessionId, keyId, message, signature, match); + reply->writeInt32(match); + reply->writeInt32(result); + return OK; + } + + case SIGN_RSA: + { + CHECK_INTERFACE(IDrm, data, reply); + Vector sessionId, message, wrappedKey, signature; + readVector(data, sessionId); + String8 algorithm = data.readString8(); + readVector(data, message); + readVector(data, wrappedKey); + uint32_t result = signRSA(sessionId, algorithm, message, wrappedKey, signature); + writeVector(reply, signature); + reply->writeInt32(result); + return OK; + } + + case SET_LISTENER: { + CHECK_INTERFACE(IDrm, data, reply); + sp listener = + interface_cast(data.readStrongBinder()); + reply->writeInt32(setListener(listener)); + return NO_ERROR; + } break; + + default: + return BBinder::onTransact(code, data, reply, flags); + } +} +","@@ -658,7 +658,7 @@ + + + Vector request; + String8 defaultUrl; +- DrmPlugin::KeyRequestType keyRequestType; ++ DrmPlugin::KeyRequestType keyRequestType = DrmPlugin::kKeyRequestType_Unknown; + + status_t result = getKeyRequest(sessionId, initData, mimeType, + keyType, optionalParameters, request, defaultUrl, +",2277,2608,4096 +18289,"static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, + struct bpf_insn *insn, + struct bpf_reg_state *dst_reg, + struct bpf_reg_state src_reg) +{ + struct bpf_reg_state *regs = cur_regs(env); + u8 opcode = BPF_OP(insn->code); + bool src_known, dst_known; + s64 smin_val, smax_val; + u64 umin_val, umax_val; + u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; + + if (insn_bitness == 32) { + /* Relevant for 32-bit RSH: Information can propagate towards + * LSB, so it isn't sufficient to only truncate the output to + * 32 bits. + */ + coerce_reg_to_size(dst_reg, 4); + coerce_reg_to_size(&src_reg, 4); + } + + smin_val = src_reg.smin_value; + smax_val = src_reg.smax_value; + umin_val = src_reg.umin_value; + umax_val = src_reg.umax_value; + src_known = tnum_is_const(src_reg.var_off); + dst_known = tnum_is_const(dst_reg->var_off); + + if ((src_known && (smin_val != smax_val || umin_val != umax_val)) || + smin_val > smax_val || umin_val > umax_val) { + /* Taint dst register if offset had invalid bounds derived from + * e.g. dead branches. + */ + __mark_reg_unknown(dst_reg); + return 0; + } + + if (!src_known && + opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { + __mark_reg_unknown(dst_reg); + return 0; + } + + switch (opcode) { + case BPF_ADD: + if (signed_add_overflows(dst_reg->smin_value, smin_val) || + signed_add_overflows(dst_reg->smax_value, smax_val)) { + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + } else { + dst_reg->smin_value += smin_val; + dst_reg->smax_value += smax_val; + } + if (dst_reg->umin_value + umin_val < umin_val || + dst_reg->umax_value + umax_val < umax_val) { + dst_reg->umin_value = 0; + dst_reg->umax_value = U64_MAX; + } else { + dst_reg->umin_value += umin_val; + dst_reg->umax_value += umax_val; + } + dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); + break; + case BPF_SUB: + if (signed_sub_overflows(dst_reg->smin_value, smax_val) || + signed_sub_overflows(dst_reg->smax_value, smin_val)) { + /* Overflow possible, we know nothing */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + } else { + dst_reg->smin_value -= smax_val; + dst_reg->smax_value -= smin_val; + } + if (dst_reg->umin_value < umax_val) { + /* Overflow possible, we know nothing */ + dst_reg->umin_value = 0; + dst_reg->umax_value = U64_MAX; + } else { + /* Cannot overflow (as long as bounds are consistent) */ + dst_reg->umin_value -= umax_val; + dst_reg->umax_value -= umin_val; + } + dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); + break; + case BPF_MUL: + dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); + if (smin_val < 0 || dst_reg->smin_value < 0) { + /* Ain't nobody got time to multiply that sign */ + __mark_reg_unbounded(dst_reg); + __update_reg_bounds(dst_reg); + break; + } + /* Both values are positive, so we can work with unsigned and + * copy the result to signed (unless it exceeds S64_MAX). + */ + if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { + /* Potential overflow, we know nothing */ + __mark_reg_unbounded(dst_reg); + /* (except what we can learn from the var_off) */ + __update_reg_bounds(dst_reg); + break; + } + dst_reg->umin_value *= umin_val; + dst_reg->umax_value *= umax_val; + if (dst_reg->umax_value > S64_MAX) { + /* Overflow possible, we know nothing */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + } else { + dst_reg->smin_value = dst_reg->umin_value; + dst_reg->smax_value = dst_reg->umax_value; + } + break; + case BPF_AND: + if (src_known && dst_known) { + __mark_reg_known(dst_reg, dst_reg->var_off.value & + src_reg.var_off.value); + break; + } + /* We get our minimum from the var_off, since that's inherently + * bitwise. Our maximum is the minimum of the operands' maxima. + */ + dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); + dst_reg->umin_value = dst_reg->var_off.value; + dst_reg->umax_value = min(dst_reg->umax_value, umax_val); + if (dst_reg->smin_value < 0 || smin_val < 0) { + /* Lose signed bounds when ANDing negative numbers, + * ain't nobody got time for that. + */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + } else { + /* ANDing two positives gives a positive, so safe to + * cast result into s64. + */ + dst_reg->smin_value = dst_reg->umin_value; + dst_reg->smax_value = dst_reg->umax_value; + } + /* We may learn something more from the var_off */ + __update_reg_bounds(dst_reg); + break; + case BPF_OR: + if (src_known && dst_known) { + __mark_reg_known(dst_reg, dst_reg->var_off.value | + src_reg.var_off.value); + break; + } + /* We get our maximum from the var_off, and our minimum is the + * maximum of the operands' minima + */ + dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); + dst_reg->umin_value = max(dst_reg->umin_value, umin_val); + dst_reg->umax_value = dst_reg->var_off.value | + dst_reg->var_off.mask; + if (dst_reg->smin_value < 0 || smin_val < 0) { + /* Lose signed bounds when ORing negative numbers, + * ain't nobody got time for that. + */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + } else { + /* ORing two positives gives a positive, so safe to + * cast result into s64. + */ + dst_reg->smin_value = dst_reg->umin_value; + dst_reg->smax_value = dst_reg->umax_value; + } + /* We may learn something more from the var_off */ + __update_reg_bounds(dst_reg); + break; + case BPF_LSH: + if (umax_val >= insn_bitness) { + /* Shifts greater than 31 or 63 are undefined. + * This includes shifts by a negative number. + */ + mark_reg_unknown(env, regs, insn->dst_reg); + break; + } + /* We lose all sign bit information (except what we can pick + * up from var_off) + */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + /* If we might shift our top bit out, then we know nothing */ + if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { + dst_reg->umin_value = 0; + dst_reg->umax_value = U64_MAX; + } else { + dst_reg->umin_value <<= umin_val; + dst_reg->umax_value <<= umax_val; + } + dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); + /* We may learn something more from the var_off */ + __update_reg_bounds(dst_reg); + break; + case BPF_RSH: + if (umax_val >= insn_bitness) { + /* Shifts greater than 31 or 63 are undefined. + * This includes shifts by a negative number. + */ + mark_reg_unknown(env, regs, insn->dst_reg); + break; + } + /* BPF_RSH is an unsigned shift. If the value in dst_reg might + * be negative, then either: + * 1) src_reg might be zero, so the sign bit of the result is + * unknown, so we lose our signed bounds + * 2) it's known negative, thus the unsigned bounds capture the + * signed bounds + * 3) the signed bounds cross zero, so they tell us nothing + * about the result + * If the value in dst_reg is known nonnegative, then again the + * unsigned bounts capture the signed bounds. + * Thus, in all cases it suffices to blow away our signed bounds + * and rely on inferring new ones from the unsigned bounds and + * var_off of the result. + */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); + dst_reg->umin_value >>= umax_val; + dst_reg->umax_value >>= umin_val; + /* We may learn something more from the var_off */ + __update_reg_bounds(dst_reg); + break; + case BPF_ARSH: + if (umax_val >= insn_bitness) { + /* Shifts greater than 31 or 63 are undefined. + * This includes shifts by a negative number. + */ + mark_reg_unknown(env, regs, insn->dst_reg); + break; + } + + /* Upon reaching here, src_known is true and + * umax_val is equal to umin_val. + */ + dst_reg->smin_value >>= umin_val; + dst_reg->smax_value >>= umin_val; + dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val); + + /* blow away the dst_reg umin_value/umax_value and rely on + * dst_reg var_off to refine the result. + */ + dst_reg->umin_value = 0; + dst_reg->umax_value = U64_MAX; + __update_reg_bounds(dst_reg); + break; + default: + mark_reg_unknown(env, regs, insn->dst_reg); + break; + } + + if (BPF_CLASS(insn->code) != BPF_ALU64) { + /* 32-bit ALU ops are (32,32)->32 */ + coerce_reg_to_size(dst_reg, 4); + } + + __reg_deduce_bounds(dst_reg); + __reg_bound_offset(dst_reg); + return 0; +} +",1,"static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, + struct bpf_insn *insn, + struct bpf_reg_state *dst_reg, + struct bpf_reg_state src_reg) +{ + struct bpf_reg_state *regs = cur_regs(env); + u8 opcode = BPF_OP(insn->code); + bool src_known, dst_known; + s64 smin_val, smax_val; + u64 umin_val, umax_val; + u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; + u32 dst = insn->dst_reg; + int ret; + + if (insn_bitness == 32) { + /* Relevant for 32-bit RSH: Information can propagate towards + * LSB, so it isn't sufficient to only truncate the output to + * 32 bits. + */ + coerce_reg_to_size(dst_reg, 4); + coerce_reg_to_size(&src_reg, 4); + } + + smin_val = src_reg.smin_value; + smax_val = src_reg.smax_value; + umin_val = src_reg.umin_value; + umax_val = src_reg.umax_value; + src_known = tnum_is_const(src_reg.var_off); + dst_known = tnum_is_const(dst_reg->var_off); + + if ((src_known && (smin_val != smax_val || umin_val != umax_val)) || + smin_val > smax_val || umin_val > umax_val) { + /* Taint dst register if offset had invalid bounds derived from + * e.g. dead branches. + */ + __mark_reg_unknown(dst_reg); + return 0; + } + + if (!src_known && + opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { + __mark_reg_unknown(dst_reg); + return 0; + } + + switch (opcode) { + case BPF_ADD: + ret = sanitize_val_alu(env, insn); + if (ret < 0) { + verbose(env, ""R%d tried to add from different pointers or scalars\n"", dst); + return ret; + } + if (signed_add_overflows(dst_reg->smin_value, smin_val) || + signed_add_overflows(dst_reg->smax_value, smax_val)) { + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + } else { + dst_reg->smin_value += smin_val; + dst_reg->smax_value += smax_val; + } + if (dst_reg->umin_value + umin_val < umin_val || + dst_reg->umax_value + umax_val < umax_val) { + dst_reg->umin_value = 0; + dst_reg->umax_value = U64_MAX; + } else { + dst_reg->umin_value += umin_val; + dst_reg->umax_value += umax_val; + } + dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); + break; + case BPF_SUB: + ret = sanitize_val_alu(env, insn); + if (ret < 0) { + verbose(env, ""R%d tried to sub from different pointers or scalars\n"", dst); + return ret; + } + if (signed_sub_overflows(dst_reg->smin_value, smax_val) || + signed_sub_overflows(dst_reg->smax_value, smin_val)) { + /* Overflow possible, we know nothing */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + } else { + dst_reg->smin_value -= smax_val; + dst_reg->smax_value -= smin_val; + } + if (dst_reg->umin_value < umax_val) { + /* Overflow possible, we know nothing */ + dst_reg->umin_value = 0; + dst_reg->umax_value = U64_MAX; + } else { + /* Cannot overflow (as long as bounds are consistent) */ + dst_reg->umin_value -= umax_val; + dst_reg->umax_value -= umin_val; + } + dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); + break; + case BPF_MUL: + dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); + if (smin_val < 0 || dst_reg->smin_value < 0) { + /* Ain't nobody got time to multiply that sign */ + __mark_reg_unbounded(dst_reg); + __update_reg_bounds(dst_reg); + break; + } + /* Both values are positive, so we can work with unsigned and + * copy the result to signed (unless it exceeds S64_MAX). + */ + if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { + /* Potential overflow, we know nothing */ + __mark_reg_unbounded(dst_reg); + /* (except what we can learn from the var_off) */ + __update_reg_bounds(dst_reg); + break; + } + dst_reg->umin_value *= umin_val; + dst_reg->umax_value *= umax_val; + if (dst_reg->umax_value > S64_MAX) { + /* Overflow possible, we know nothing */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + } else { + dst_reg->smin_value = dst_reg->umin_value; + dst_reg->smax_value = dst_reg->umax_value; + } + break; + case BPF_AND: + if (src_known && dst_known) { + __mark_reg_known(dst_reg, dst_reg->var_off.value & + src_reg.var_off.value); + break; + } + /* We get our minimum from the var_off, since that's inherently + * bitwise. Our maximum is the minimum of the operands' maxima. + */ + dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); + dst_reg->umin_value = dst_reg->var_off.value; + dst_reg->umax_value = min(dst_reg->umax_value, umax_val); + if (dst_reg->smin_value < 0 || smin_val < 0) { + /* Lose signed bounds when ANDing negative numbers, + * ain't nobody got time for that. + */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + } else { + /* ANDing two positives gives a positive, so safe to + * cast result into s64. + */ + dst_reg->smin_value = dst_reg->umin_value; + dst_reg->smax_value = dst_reg->umax_value; + } + /* We may learn something more from the var_off */ + __update_reg_bounds(dst_reg); + break; + case BPF_OR: + if (src_known && dst_known) { + __mark_reg_known(dst_reg, dst_reg->var_off.value | + src_reg.var_off.value); + break; + } + /* We get our maximum from the var_off, and our minimum is the + * maximum of the operands' minima + */ + dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); + dst_reg->umin_value = max(dst_reg->umin_value, umin_val); + dst_reg->umax_value = dst_reg->var_off.value | + dst_reg->var_off.mask; + if (dst_reg->smin_value < 0 || smin_val < 0) { + /* Lose signed bounds when ORing negative numbers, + * ain't nobody got time for that. + */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + } else { + /* ORing two positives gives a positive, so safe to + * cast result into s64. + */ + dst_reg->smin_value = dst_reg->umin_value; + dst_reg->smax_value = dst_reg->umax_value; + } + /* We may learn something more from the var_off */ + __update_reg_bounds(dst_reg); + break; + case BPF_LSH: + if (umax_val >= insn_bitness) { + /* Shifts greater than 31 or 63 are undefined. + * This includes shifts by a negative number. + */ + mark_reg_unknown(env, regs, insn->dst_reg); + break; + } + /* We lose all sign bit information (except what we can pick + * up from var_off) + */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + /* If we might shift our top bit out, then we know nothing */ + if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { + dst_reg->umin_value = 0; + dst_reg->umax_value = U64_MAX; + } else { + dst_reg->umin_value <<= umin_val; + dst_reg->umax_value <<= umax_val; + } + dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); + /* We may learn something more from the var_off */ + __update_reg_bounds(dst_reg); + break; + case BPF_RSH: + if (umax_val >= insn_bitness) { + /* Shifts greater than 31 or 63 are undefined. + * This includes shifts by a negative number. + */ + mark_reg_unknown(env, regs, insn->dst_reg); + break; + } + /* BPF_RSH is an unsigned shift. If the value in dst_reg might + * be negative, then either: + * 1) src_reg might be zero, so the sign bit of the result is + * unknown, so we lose our signed bounds + * 2) it's known negative, thus the unsigned bounds capture the + * signed bounds + * 3) the signed bounds cross zero, so they tell us nothing + * about the result + * If the value in dst_reg is known nonnegative, then again the + * unsigned bounts capture the signed bounds. + * Thus, in all cases it suffices to blow away our signed bounds + * and rely on inferring new ones from the unsigned bounds and + * var_off of the result. + */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); + dst_reg->umin_value >>= umax_val; + dst_reg->umax_value >>= umin_val; + /* We may learn something more from the var_off */ + __update_reg_bounds(dst_reg); + break; + case BPF_ARSH: + if (umax_val >= insn_bitness) { + /* Shifts greater than 31 or 63 are undefined. + * This includes shifts by a negative number. + */ + mark_reg_unknown(env, regs, insn->dst_reg); + break; + } + + /* Upon reaching here, src_known is true and + * umax_val is equal to umin_val. + */ + dst_reg->smin_value >>= umin_val; + dst_reg->smax_value >>= umin_val; + dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val); + + /* blow away the dst_reg umin_value/umax_value and rely on + * dst_reg var_off to refine the result. + */ + dst_reg->umin_value = 0; + dst_reg->umax_value = U64_MAX; + __update_reg_bounds(dst_reg); + break; + default: + mark_reg_unknown(env, regs, insn->dst_reg); + break; + } + + if (BPF_CLASS(insn->code) != BPF_ALU64) { + /* 32-bit ALU ops are (32,32)->32 */ + coerce_reg_to_size(dst_reg, 4); + } + + __reg_deduce_bounds(dst_reg); + __reg_bound_offset(dst_reg); + return 0; +} +","@@ -3103,6 +3103,40 @@ static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, + } + } + ++static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, ++ const struct bpf_insn *insn) ++{ ++ return env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K; ++} ++ ++static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, ++ u32 alu_state, u32 alu_limit) ++{ ++ /* If we arrived here from different branches with different ++ * state or limits to sanitize, then this won't work. ++ */ ++ if (aux->alu_state && ++ (aux->alu_state != alu_state || ++ aux->alu_limit != alu_limit)) ++ return -EACCES; ++ ++ /* Corresponding fixup done in fixup_bpf_calls(). */ ++ aux->alu_state = alu_state; ++ aux->alu_limit = alu_limit; ++ return 0; ++} ++ ++static int sanitize_val_alu(struct bpf_verifier_env *env, ++ struct bpf_insn *insn) ++{ ++ struct bpf_insn_aux_data *aux = cur_aux(env); ++ ++ if (can_skip_alu_sanitation(env, insn)) ++ return 0; ++ ++ return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); ++} ++ + static int sanitize_ptr_alu(struct bpf_verifier_env *env, + struct bpf_insn *insn, + const struct bpf_reg_state *ptr_reg, +@@ -3117,7 +3151,7 @@ static int sanitize_ptr_alu(struct bpf_verifier_env *env, + struct bpf_reg_state tmp; + bool ret; + +- if (env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K) ++ if (can_skip_alu_sanitation(env, insn)) + return 0; + + /* We already marked aux for masking from non-speculative +@@ -3133,19 +3167,8 @@ static int sanitize_ptr_alu(struct bpf_verifier_env *env, + + if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg)) + return 0; +- +- /* If we arrived here from different branches with different +- * limits to sanitize, then this won't work. +- */ +- if (aux->alu_state && +- (aux->alu_state != alu_state || +- aux->alu_limit != alu_limit)) ++ if (update_alu_sanitation_state(aux, alu_state, alu_limit)) + return -EACCES; +- +- /* Corresponding fixup done in fixup_bpf_calls(). */ +- aux->alu_state = alu_state; +- aux->alu_limit = alu_limit; +- + do_sim: + /* Simulate and find potential out-of-bounds access under + * speculative execution from truncation as a result of +@@ -3418,6 +3441,8 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, + s64 smin_val, smax_val; + u64 umin_val, umax_val; + u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; ++ u32 dst = insn->dst_reg; ++ int ret; + + if (insn_bitness == 32) { + /* Relevant for 32-bit RSH: Information can propagate towards +@@ -3452,6 +3477,11 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, + + switch (opcode) { + case BPF_ADD: ++ ret = sanitize_val_alu(env, insn); ++ if (ret < 0) { ++ verbose(env, ""R%d tried to add from different pointers or scalars\n"", dst); ++ return ret; ++ } + if (signed_add_overflows(dst_reg->smin_value, smin_val) || + signed_add_overflows(dst_reg->smax_value, smax_val)) { + dst_reg->smin_value = S64_MIN; +@@ -3471,6 +3501,11 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, + dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); + break; + case BPF_SUB: ++ ret = sanitize_val_alu(env, insn); ++ if (ret < 0) { ++ verbose(env, ""R%d tried to sub from different pointers or scalars\n"", dst); ++ return ret; ++ } + if (signed_sub_overflows(dst_reg->smin_value, smax_val) || + signed_sub_overflows(dst_reg->smax_value, smin_val)) { + /* Overflow possible, we know nothing */",2655,2986,4096 +17939,"static u_char *php_parserr(u_char *cp, querybuf *answer, int type_to_fetch, int store, int raw, zval **subarray) + { + u_short type, class, dlen; + u_long ttl; + long n, i; + u_short s; + u_char *tp, *p; + char name[MAXHOSTNAMELEN]; + int have_v6_break = 0, in_v6_break = 0; + + *subarray = NULL; + + n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, sizeof(name) - 2); + if (n < 0) { + return NULL; + } + cp += n; + + GETSHORT(type, cp); + GETSHORT(class, cp); + GETLONG(ttl, cp); + GETSHORT(dlen, cp); + if (type_to_fetch != T_ANY && type != type_to_fetch) { + cp += dlen; + return cp; + } + + if (!store) { + cp += dlen; + return cp; + } + + ALLOC_INIT_ZVAL(*subarray); + array_init(*subarray); + + add_assoc_string(*subarray, ""host"", name, 1); + add_assoc_string(*subarray, ""class"", ""IN"", 1); + add_assoc_long(*subarray, ""ttl"", ttl); + + if (raw) { + add_assoc_long(*subarray, ""type"", type); + add_assoc_stringl(*subarray, ""data"", (char*) cp, (uint) dlen, 1); + cp += dlen; + return cp; + } + + switch (type) { + case DNS_T_A: + add_assoc_string(*subarray, ""type"", ""A"", 1); + snprintf(name, sizeof(name), ""%d.%d.%d.%d"", cp[0], cp[1], cp[2], cp[3]); + add_assoc_string(*subarray, ""ip"", name, 1); + cp += dlen; + break; + case DNS_T_MX: + add_assoc_string(*subarray, ""type"", ""MX"", 1); + GETSHORT(n, cp); + add_assoc_long(*subarray, ""pri"", n); + /* no break; */ + case DNS_T_CNAME: + if (type == DNS_T_CNAME) { + add_assoc_string(*subarray, ""type"", ""CNAME"", 1); + } + /* no break; */ + case DNS_T_NS: + if (type == DNS_T_NS) { + add_assoc_string(*subarray, ""type"", ""NS"", 1); + } + /* no break; */ + case DNS_T_PTR: + if (type == DNS_T_PTR) { + add_assoc_string(*subarray, ""type"", ""PTR"", 1); + } + n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2); + if (n < 0) { + return NULL; + } + cp += n; + add_assoc_string(*subarray, ""target"", name, 1); + break; + case DNS_T_HINFO: + /* See RFC 1010 for values */ + add_assoc_string(*subarray, ""type"", ""HINFO"", 1); + n = *cp & 0xFF; + cp++; + add_assoc_stringl(*subarray, ""cpu"", (char*)cp, n, 1); + cp += n; + n = *cp & 0xFF; + cp++; + add_assoc_stringl(*subarray, ""os"", (char*)cp, n, 1); + cp += n; + break; + case DNS_T_TXT: + { + int ll = 0; + zval *entries = NULL; + + add_assoc_string(*subarray, ""type"", ""TXT"", 1); + tp = emalloc(dlen + 1); + + MAKE_STD_ZVAL(entries); + array_init(entries); + + while (ll < dlen) { + n = cp[ll]; + if ((ll + n) >= dlen) { + n = dlen - (ll + 1); + } + memcpy(tp + ll , cp + ll + 1, n); + add_next_index_stringl(entries, cp + ll + 1, n, 1); + ll = ll + n + 1; + } + tp[dlen] = '\0'; + cp += dlen; + + add_assoc_stringl(*subarray, ""txt"", tp, (dlen>0)?dlen - 1:0, 0); + add_assoc_zval(*subarray, ""entries"", entries); + } + break; + case DNS_T_SOA: + add_assoc_string(*subarray, ""type"", ""SOA"", 1); + n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) -2); + if (n < 0) { + return NULL; + } + cp += n; + add_assoc_string(*subarray, ""mname"", name, 1); + n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) -2); + if (n < 0) { + return NULL; + } + cp += n; + add_assoc_string(*subarray, ""rname"", name, 1); + GETLONG(n, cp); + add_assoc_long(*subarray, ""serial"", n); + GETLONG(n, cp); + add_assoc_long(*subarray, ""refresh"", n); + GETLONG(n, cp); + add_assoc_long(*subarray, ""retry"", n); + GETLONG(n, cp); + add_assoc_long(*subarray, ""expire"", n); + GETLONG(n, cp); + add_assoc_long(*subarray, ""minimum-ttl"", n); + break; + case DNS_T_AAAA: + tp = (u_char*)name; + for(i=0; i < 8; i++) { + GETSHORT(s, cp); + if (s != 0) { + if (tp > (u_char *)name) { + in_v6_break = 0; + tp[0] = ':'; + tp++; + } + tp += sprintf((char*)tp,""%x"",s); + } else { + if (!have_v6_break) { + have_v6_break = 1; + in_v6_break = 1; + tp[0] = ':'; + tp++; + } else if (!in_v6_break) { + tp[0] = ':'; + tp++; + tp[0] = '0'; + tp++; + } + } + } + if (have_v6_break && in_v6_break) { + tp[0] = ':'; + tp++; + } + tp[0] = '\0'; + add_assoc_string(*subarray, ""type"", ""AAAA"", 1); + add_assoc_string(*subarray, ""ipv6"", name, 1); + break; + case DNS_T_A6: + p = cp; + add_assoc_string(*subarray, ""type"", ""A6"", 1); + n = ((int)cp[0]) & 0xFF; + cp++; + add_assoc_long(*subarray, ""masklen"", n); + tp = (u_char*)name; + if (n > 15) { + have_v6_break = 1; + in_v6_break = 1; + tp[0] = ':'; + tp++; + } + if (n % 16 > 8) { + /* Partial short */ + if (cp[0] != 0) { + if (tp > (u_char *)name) { + in_v6_break = 0; + tp[0] = ':'; + tp++; + } + sprintf((char*)tp, ""%x"", cp[0] & 0xFF); + } else { + if (!have_v6_break) { + have_v6_break = 1; + in_v6_break = 1; + tp[0] = ':'; + tp++; + } else if (!in_v6_break) { + tp[0] = ':'; + tp++; + tp[0] = '0'; + tp++; + } + } + cp++; + } + for (i = (n + 8) / 16; i < 8; i++) { + GETSHORT(s, cp); + if (s != 0) { + if (tp > (u_char *)name) { + in_v6_break = 0; + tp[0] = ':'; + tp++; + } + tp += sprintf((char*)tp,""%x"",s); + } else { + if (!have_v6_break) { + have_v6_break = 1; + in_v6_break = 1; + tp[0] = ':'; + tp++; + } else if (!in_v6_break) { + tp[0] = ':'; + tp++; + tp[0] = '0'; + tp++; + } + } + } + if (have_v6_break && in_v6_break) { + tp[0] = ':'; + tp++; + } + tp[0] = '\0'; + add_assoc_string(*subarray, ""ipv6"", name, 1); + if (cp < p + dlen) { + n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2); + if (n < 0) { + return NULL; + } + cp += n; + add_assoc_string(*subarray, ""chain"", name, 1); + } + break; + case DNS_T_SRV: + add_assoc_string(*subarray, ""type"", ""SRV"", 1); + GETSHORT(n, cp); + add_assoc_long(*subarray, ""pri"", n); + GETSHORT(n, cp); + add_assoc_long(*subarray, ""weight"", n); + GETSHORT(n, cp); + add_assoc_long(*subarray, ""port"", n); + n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2); + if (n < 0) { + return NULL; + } + cp += n; + add_assoc_string(*subarray, ""target"", name, 1); + break; + case DNS_T_NAPTR: + add_assoc_string(*subarray, ""type"", ""NAPTR"", 1); + GETSHORT(n, cp); + add_assoc_long(*subarray, ""order"", n); + GETSHORT(n, cp); + add_assoc_long(*subarray, ""pref"", n); + n = (cp[0] & 0xFF); + add_assoc_stringl(*subarray, ""flags"", (char*)++cp, n, 1); + cp += n; + n = (cp[0] & 0xFF); + add_assoc_stringl(*subarray, ""services"", (char*)++cp, n, 1); + cp += n; + n = (cp[0] & 0xFF); + add_assoc_stringl(*subarray, ""regex"", (char*)++cp, n, 1); + cp += n; + n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2); + if (n < 0) { + return NULL; + } + cp += n; + add_assoc_string(*subarray, ""replacement"", name, 1); + break; + default: + zval_ptr_dtor(subarray); + *subarray = NULL; + cp += dlen; + break; + } + + return cp; +} +",1,"static u_char *php_parserr(u_char *cp, querybuf *answer, int type_to_fetch, int store, int raw, zval **subarray) +static u_char *php_parserr(u_char *cp, u_char *end, querybuf *answer, int type_to_fetch, int store, int raw, zval **subarray) + { + u_short type, class, dlen; + u_long ttl; + long n, i; + u_short s; + u_char *tp, *p; + char name[MAXHOSTNAMELEN]; + int have_v6_break = 0, in_v6_break = 0; + + *subarray = NULL; + + n = dn_expand(answer->qb2, end, cp, name, sizeof(name) - 2); + if (n < 0) { + return NULL; + } + cp += n; + + CHECKCP(10); + GETSHORT(type, cp); + GETSHORT(class, cp); + GETLONG(ttl, cp); + GETSHORT(dlen, cp); + CHECKCP(dlen); + if (type_to_fetch != T_ANY && type != type_to_fetch) { + cp += dlen; + return cp; + } + + if (!store) { + cp += dlen; + return cp; + } + + ALLOC_INIT_ZVAL(*subarray); + array_init(*subarray); + + add_assoc_string(*subarray, ""host"", name, 1); + add_assoc_string(*subarray, ""class"", ""IN"", 1); + add_assoc_long(*subarray, ""ttl"", ttl); + + if (raw) { + add_assoc_long(*subarray, ""type"", type); + add_assoc_stringl(*subarray, ""data"", (char*) cp, (uint) dlen, 1); + cp += dlen; + return cp; + } + + switch (type) { + case DNS_T_A: + CHECKCP(4); + add_assoc_string(*subarray, ""type"", ""A"", 1); + snprintf(name, sizeof(name), ""%d.%d.%d.%d"", cp[0], cp[1], cp[2], cp[3]); + add_assoc_string(*subarray, ""ip"", name, 1); + cp += dlen; + break; + case DNS_T_MX: + CHECKCP(2); + add_assoc_string(*subarray, ""type"", ""MX"", 1); + GETSHORT(n, cp); + add_assoc_long(*subarray, ""pri"", n); + /* no break; */ + case DNS_T_CNAME: + if (type == DNS_T_CNAME) { + add_assoc_string(*subarray, ""type"", ""CNAME"", 1); + } + /* no break; */ + case DNS_T_NS: + if (type == DNS_T_NS) { + add_assoc_string(*subarray, ""type"", ""NS"", 1); + } + /* no break; */ + case DNS_T_PTR: + if (type == DNS_T_PTR) { + add_assoc_string(*subarray, ""type"", ""PTR"", 1); + } + n = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2); + if (n < 0) { + return NULL; + } + cp += n; + add_assoc_string(*subarray, ""target"", name, 1); + break; + case DNS_T_HINFO: + /* See RFC 1010 for values */ + add_assoc_string(*subarray, ""type"", ""HINFO"", 1); + CHECKCP(1); + n = *cp & 0xFF; + cp++; + CHECKCP(n); + add_assoc_stringl(*subarray, ""cpu"", (char*)cp, n, 1); + cp += n; + CHECKCP(1); + n = *cp & 0xFF; + cp++; + CHECKCP(n); + add_assoc_stringl(*subarray, ""os"", (char*)cp, n, 1); + cp += n; + break; + case DNS_T_TXT: + { + int l1 = 0, l2 = 0; + zval *entries = NULL; + + add_assoc_string(*subarray, ""type"", ""TXT"", 1); + tp = emalloc(dlen + 1); + + MAKE_STD_ZVAL(entries); + array_init(entries); + + while (l1 < dlen) { + n = cp[l1]; + if ((l1 + n) >= dlen) { + n = dlen - (l1 + 1); + } + if (n) { + memcpy(tp + l2 , cp + l1 + 1, n); + add_next_index_stringl(entries, cp + l1 + 1, n, 1); + } + l1 = l1 + n + 1; + l2 = l2 + n; + } + tp[l2] = '\0'; + cp += dlen; + + add_assoc_stringl(*subarray, ""txt"", tp, l2, 0); + add_assoc_zval(*subarray, ""entries"", entries); + } + break; + case DNS_T_SOA: + add_assoc_string(*subarray, ""type"", ""SOA"", 1); + n = dn_expand(answer->qb2, end, cp, name, (sizeof name) -2); + if (n < 0) { + return NULL; + } + cp += n; + add_assoc_string(*subarray, ""mname"", name, 1); + n = dn_expand(answer->qb2, end, cp, name, (sizeof name) -2); + if (n < 0) { + return NULL; + } + cp += n; + add_assoc_string(*subarray, ""rname"", name, 1); + CHECKCP(5*4); + GETLONG(n, cp); + add_assoc_long(*subarray, ""serial"", n); + GETLONG(n, cp); + add_assoc_long(*subarray, ""refresh"", n); + GETLONG(n, cp); + add_assoc_long(*subarray, ""retry"", n); + GETLONG(n, cp); + add_assoc_long(*subarray, ""expire"", n); + GETLONG(n, cp); + add_assoc_long(*subarray, ""minimum-ttl"", n); + break; + case DNS_T_AAAA: + tp = (u_char*)name; + CHECKCP(8*2); + for(i=0; i < 8; i++) { + GETSHORT(s, cp); + if (s != 0) { + if (tp > (u_char *)name) { + in_v6_break = 0; + tp[0] = ':'; + tp++; + } + tp += sprintf((char*)tp,""%x"",s); + } else { + if (!have_v6_break) { + have_v6_break = 1; + in_v6_break = 1; + tp[0] = ':'; + tp++; + } else if (!in_v6_break) { + tp[0] = ':'; + tp++; + tp[0] = '0'; + tp++; + } + } + } + if (have_v6_break && in_v6_break) { + tp[0] = ':'; + tp++; + } + tp[0] = '\0'; + add_assoc_string(*subarray, ""type"", ""AAAA"", 1); + add_assoc_string(*subarray, ""ipv6"", name, 1); + break; + case DNS_T_A6: + p = cp; + add_assoc_string(*subarray, ""type"", ""A6"", 1); + CHECKCP(1); + n = ((int)cp[0]) & 0xFF; + cp++; + add_assoc_long(*subarray, ""masklen"", n); + tp = (u_char*)name; + if (n > 15) { + have_v6_break = 1; + in_v6_break = 1; + tp[0] = ':'; + tp++; + } + if (n % 16 > 8) { + /* Partial short */ + if (cp[0] != 0) { + if (tp > (u_char *)name) { + in_v6_break = 0; + tp[0] = ':'; + tp++; + } + sprintf((char*)tp, ""%x"", cp[0] & 0xFF); + } else { + if (!have_v6_break) { + have_v6_break = 1; + in_v6_break = 1; + tp[0] = ':'; + tp++; + } else if (!in_v6_break) { + tp[0] = ':'; + tp++; + tp[0] = '0'; + tp++; + } + } + cp++; + } + for (i = (n + 8) / 16; i < 8; i++) { + CHECKCP(2); + GETSHORT(s, cp); + if (s != 0) { + if (tp > (u_char *)name) { + in_v6_break = 0; + tp[0] = ':'; + tp++; + } + tp += sprintf((char*)tp,""%x"",s); + } else { + if (!have_v6_break) { + have_v6_break = 1; + in_v6_break = 1; + tp[0] = ':'; + tp++; + } else if (!in_v6_break) { + tp[0] = ':'; + tp++; + tp[0] = '0'; + tp++; + } + } + } + if (have_v6_break && in_v6_break) { + tp[0] = ':'; + tp++; + } + tp[0] = '\0'; + add_assoc_string(*subarray, ""ipv6"", name, 1); + if (cp < p + dlen) { + n = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2); + if (n < 0) { + return NULL; + } + cp += n; + add_assoc_string(*subarray, ""chain"", name, 1); + } + break; + case DNS_T_SRV: + CHECKCP(3*2); + add_assoc_string(*subarray, ""type"", ""SRV"", 1); + GETSHORT(n, cp); + add_assoc_long(*subarray, ""pri"", n); + GETSHORT(n, cp); + add_assoc_long(*subarray, ""weight"", n); + GETSHORT(n, cp); + add_assoc_long(*subarray, ""port"", n); + n = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2); + if (n < 0) { + return NULL; + } + cp += n; + add_assoc_string(*subarray, ""target"", name, 1); + break; + case DNS_T_NAPTR: + CHECKCP(2*2); + add_assoc_string(*subarray, ""type"", ""NAPTR"", 1); + GETSHORT(n, cp); + add_assoc_long(*subarray, ""order"", n); + GETSHORT(n, cp); + add_assoc_long(*subarray, ""pref"", n); + + CHECKCP(1); + n = (cp[0] & 0xFF); + cp++; + CHECKCP(n); + add_assoc_stringl(*subarray, ""flags"", (char*)cp, n, 1); + cp += n; + + CHECKCP(1); + n = (cp[0] & 0xFF); + cp++; + CHECKCP(n); + add_assoc_stringl(*subarray, ""services"", (char*)cp, n, 1); + cp += n; + + CHECKCP(1); + n = (cp[0] & 0xFF); + cp++; + CHECKCP(n); + add_assoc_stringl(*subarray, ""regex"", (char*)cp, n, 1); + cp += n; + + n = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2); + if (n < 0) { + return NULL; + } + cp += n; + add_assoc_string(*subarray, ""replacement"", name, 1); + break; + default: + zval_ptr_dtor(subarray); + *subarray = NULL; + cp += dlen; + break; + } + + return cp; +} +","@@ -412,8 +412,14 @@ PHP_FUNCTION(dns_check_record) + + #if HAVE_FULL_DNS_FUNCS + ++#define CHECKCP(n) do { \ ++ if (cp + n > end) { \ ++ return NULL; \ ++ } \ ++} while (0) ++ + /* {{{ php_parserr */ +-static u_char *php_parserr(u_char *cp, querybuf *answer, int type_to_fetch, int store, int raw, zval **subarray) ++static u_char *php_parserr(u_char *cp, u_char *end, querybuf *answer, int type_to_fetch, int store, int raw, zval **subarray) + { + u_short type, class, dlen; + u_long ttl; +@@ -425,16 +431,18 @@ static u_char *php_parserr(u_char *cp, querybuf *answer, int type_to_fetch, int + + *subarray = NULL; + +- n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, sizeof(name) - 2); ++ n = dn_expand(answer->qb2, end, cp, name, sizeof(name) - 2); + if (n < 0) { + return NULL; + } + cp += n; + ++ CHECKCP(10); + GETSHORT(type, cp); + GETSHORT(class, cp); + GETLONG(ttl, cp); + GETSHORT(dlen, cp); ++ CHECKCP(dlen); + if (type_to_fetch != T_ANY && type != type_to_fetch) { + cp += dlen; + return cp; +@@ -461,12 +469,14 @@ static u_char *php_parserr(u_char *cp, querybuf *answer, int type_to_fetch, int + + switch (type) { + case DNS_T_A: ++ CHECKCP(4); + add_assoc_string(*subarray, ""type"", ""A"", 1); + snprintf(name, sizeof(name), ""%d.%d.%d.%d"", cp[0], cp[1], cp[2], cp[3]); + add_assoc_string(*subarray, ""ip"", name, 1); + cp += dlen; + break; + case DNS_T_MX: ++ CHECKCP(2); + add_assoc_string(*subarray, ""type"", ""MX"", 1); + GETSHORT(n, cp); + add_assoc_long(*subarray, ""pri"", n); +@@ -485,7 +495,7 @@ static u_char *php_parserr(u_char *cp, querybuf *answer, int type_to_fetch, int + if (type == DNS_T_PTR) { + add_assoc_string(*subarray, ""type"", ""PTR"", 1); + } +- n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2); ++ n = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2); + if (n < 0) { + return NULL; + } +@@ -495,18 +505,22 @@ static u_char *php_parserr(u_char *cp, querybuf *answer, int type_to_fetch, int + case DNS_T_HINFO: + /* See RFC 1010 for values */ + add_assoc_string(*subarray, ""type"", ""HINFO"", 1); ++ CHECKCP(1); + n = *cp & 0xFF; + cp++; ++ CHECKCP(n); + add_assoc_stringl(*subarray, ""cpu"", (char*)cp, n, 1); + cp += n; ++ CHECKCP(1); + n = *cp & 0xFF; + cp++; ++ CHECKCP(n); + add_assoc_stringl(*subarray, ""os"", (char*)cp, n, 1); + cp += n; + break; + case DNS_T_TXT: + { +- int ll = 0; ++ int l1 = 0, l2 = 0; + zval *entries = NULL; + + add_assoc_string(*subarray, ""type"", ""TXT"", 1); +@@ -515,37 +529,41 @@ static u_char *php_parserr(u_char *cp, querybuf *answer, int type_to_fetch, int + MAKE_STD_ZVAL(entries); + array_init(entries); + +- while (ll < dlen) { +- n = cp[ll]; +- if ((ll + n) >= dlen) { ++ while (l1 < dlen) { ++ n = cp[l1]; ++ if ((l1 + n) >= dlen) { + // Invalid chunk length, truncate +- n = dlen - (ll + 1); ++ n = dlen - (l1 + 1); ++ } ++ if (n) { ++ memcpy(tp + l2 , cp + l1 + 1, n); ++ add_next_index_stringl(entries, cp + l1 + 1, n, 1); + } +- memcpy(tp + ll , cp + ll + 1, n); +- add_next_index_stringl(entries, cp + ll + 1, n, 1); +- ll = ll + n + 1; ++ l1 = l1 + n + 1; ++ l2 = l2 + n; + } +- tp[dlen] = '\0'; ++ tp[l2] = '\0'; + cp += dlen; + +- add_assoc_stringl(*subarray, ""txt"", tp, (dlen>0)?dlen - 1:0, 0); ++ add_assoc_stringl(*subarray, ""txt"", tp, l2, 0); + add_assoc_zval(*subarray, ""entries"", entries); + } + break; + case DNS_T_SOA: + add_assoc_string(*subarray, ""type"", ""SOA"", 1); +- n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) -2); ++ n = dn_expand(answer->qb2, end, cp, name, (sizeof name) -2); + if (n < 0) { + return NULL; + } + cp += n; + add_assoc_string(*subarray, ""mname"", name, 1); +- n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) -2); ++ n = dn_expand(answer->qb2, end, cp, name, (sizeof name) -2); + if (n < 0) { + return NULL; + } + cp += n; + add_assoc_string(*subarray, ""rname"", name, 1); ++ CHECKCP(5*4); + GETLONG(n, cp); + add_assoc_long(*subarray, ""serial"", n); + GETLONG(n, cp); +@@ -559,6 +577,7 @@ static u_char *php_parserr(u_char *cp, querybuf *answer, int type_to_fetch, int + break; + case DNS_T_AAAA: + tp = (u_char*)name; ++ CHECKCP(8*2); + for(i=0; i < 8; i++) { + GETSHORT(s, cp); + if (s != 0) { +@@ -593,6 +612,7 @@ static u_char *php_parserr(u_char *cp, querybuf *answer, int type_to_fetch, int + case DNS_T_A6: + p = cp; + add_assoc_string(*subarray, ""type"", ""A6"", 1); ++ CHECKCP(1); + n = ((int)cp[0]) & 0xFF; + cp++; + add_assoc_long(*subarray, ""masklen"", n); +@@ -628,6 +648,7 @@ static u_char *php_parserr(u_char *cp, querybuf *answer, int type_to_fetch, int + cp++; + } + for (i = (n + 8) / 16; i < 8; i++) { ++ CHECKCP(2); + GETSHORT(s, cp); + if (s != 0) { + if (tp > (u_char *)name) { +@@ -657,7 +678,7 @@ static u_char *php_parserr(u_char *cp, querybuf *answer, int type_to_fetch, int + tp[0] = '\0'; + add_assoc_string(*subarray, ""ipv6"", name, 1); + if (cp < p + dlen) { +- n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2); ++ n = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2); + if (n < 0) { + return NULL; + } +@@ -666,36 +687,51 @@ static u_char *php_parserr(u_char *cp, querybuf *answer, int type_to_fetch, int + } + break; + case DNS_T_SRV: ++ CHECKCP(3*2); + add_assoc_string(*subarray, ""type"", ""SRV"", 1); + GETSHORT(n, cp); + add_assoc_long(*subarray, ""pri"", n); + GETSHORT(n, cp); + add_assoc_long(*subarray, ""weight"", n); + GETSHORT(n, cp); + add_assoc_long(*subarray, ""port"", n); +- n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2); ++ n = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2); + if (n < 0) { + return NULL; + } + cp += n; + add_assoc_string(*subarray, ""target"", name, 1); + break; + case DNS_T_NAPTR: ++ CHECKCP(2*2); + add_assoc_string(*subarray, ""type"", ""NAPTR"", 1); + GETSHORT(n, cp); + add_assoc_long(*subarray, ""order"", n); + GETSHORT(n, cp); + add_assoc_long(*subarray, ""pref"", n); ++ ++ CHECKCP(1); + n = (cp[0] & 0xFF); +- add_assoc_stringl(*subarray, ""flags"", (char*)++cp, n, 1); ++ cp++; ++ CHECKCP(n); ++ add_assoc_stringl(*subarray, ""flags"", (char*)cp, n, 1); + cp += n; ++ ++ CHECKCP(1); + n = (cp[0] & 0xFF); +- add_assoc_stringl(*subarray, ""services"", (char*)++cp, n, 1); ++ cp++; ++ CHECKCP(n); ++ add_assoc_stringl(*subarray, ""services"", (char*)cp, n, 1); + cp += n; ++ ++ CHECKCP(1); + n = (cp[0] & 0xFF); +- add_assoc_stringl(*subarray, ""regex"", (char*)++cp, n, 1); ++ cp++; ++ CHECKCP(n); ++ add_assoc_stringl(*subarray, ""regex"", (char*)cp, n, 1); + cp += n; +- n = dn_expand(answer->qb2, answer->qb2+65536, cp, name, (sizeof name) - 2); ++ ++ n = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2); + if (n < 0) { + return NULL; + } +@@ -888,7 +924,7 @@ PHP_FUNCTION(dns_get_record) + while (an-- && cp && cp < end) { + zval *retval; + +- cp = php_parserr(cp, &answer, type_to_fetch, store_results, raw, &retval); ++ cp = php_parserr(cp, end, &answer, type_to_fetch, store_results, raw, &retval); + if (retval != NULL && store_results) { + add_next_index_zval(return_value, retval); + } +@@ -901,7 +937,7 @@ PHP_FUNCTION(dns_get_record) + while (ns-- > 0 && cp && cp < end) { + zval *retval = NULL; + +- cp = php_parserr(cp, &answer, DNS_T_ANY, authns != NULL, raw, &retval); ++ cp = php_parserr(cp, end, &answer, DNS_T_ANY, authns != NULL, raw, &retval); + if (retval != NULL) { + add_next_index_zval(authns, retval); + } +@@ -913,7 +949,7 @@ PHP_FUNCTION(dns_get_record) + while (ar-- > 0 && cp && cp < end) { + zval *retval = NULL; + +- cp = php_parserr(cp, &answer, DNS_T_ANY, 1, raw, &retval); ++ cp = php_parserr(cp, end, &answer, DNS_T_ANY, 1, raw, &retval); + if (retval != NULL) { + add_next_index_zval(addtl, retval); + }",2634,2965,4096 +18026,"static inline unsigned int get_next_char( + enum entity_charset charset, + const unsigned char *str, + size_t str_len, + size_t *cursor, + int *status) +{ + size_t pos = *cursor; + unsigned int this_char = 0; + + *status = SUCCESS; + assert(pos <= str_len); + + if (!CHECK_LEN(pos, 1)) + MB_FAILURE(pos, 1); + + switch (charset) { + case cs_utf_8: + { + /* We'll follow strategy 2. from section 3.6.1 of UTR #36: + * ""In a reported illegal byte sequence, do not include any + * non-initial byte that encodes a valid character or is a leading + * byte for a valid sequence."" */ + unsigned char c; + c = str[pos]; + if (c < 0x80) { + this_char = c; + pos++; + } else if (c < 0xc2) { + MB_FAILURE(pos, 1); + } else if (c < 0xe0) { + if (!CHECK_LEN(pos, 2)) + MB_FAILURE(pos, 1); + + if (!utf8_trail(str[pos + 1])) { + MB_FAILURE(pos, utf8_lead(str[pos + 1]) ? 1 : 2); + } + this_char = ((c & 0x1f) << 6) | (str[pos + 1] & 0x3f); + if (this_char < 0x80) { /* non-shortest form */ + MB_FAILURE(pos, 2); + } + pos += 2; + } else if (c < 0xf0) { + size_t avail = str_len - pos; + + if (avail < 3 || + !utf8_trail(str[pos + 1]) || !utf8_trail(str[pos + 2])) { + if (avail < 2 || utf8_lead(str[pos + 1])) + MB_FAILURE(pos, 1); + else if (avail < 3 || utf8_lead(str[pos + 2])) + MB_FAILURE(pos, 2); + else + MB_FAILURE(pos, 3); + } + + this_char = ((c & 0x0f) << 12) | ((str[pos + 1] & 0x3f) << 6) | (str[pos + 2] & 0x3f); + if (this_char < 0x800) { /* non-shortest form */ + MB_FAILURE(pos, 3); + } else if (this_char >= 0xd800 && this_char <= 0xdfff) { /* surrogate */ + MB_FAILURE(pos, 3); + } + pos += 3; + } else if (c < 0xf5) { + size_t avail = str_len - pos; + + if (avail < 4 || + !utf8_trail(str[pos + 1]) || !utf8_trail(str[pos + 2]) || + !utf8_trail(str[pos + 3])) { + if (avail < 2 || utf8_lead(str[pos + 1])) + MB_FAILURE(pos, 1); + else if (avail < 3 || utf8_lead(str[pos + 2])) + MB_FAILURE(pos, 2); + else if (avail < 4 || utf8_lead(str[pos + 3])) + MB_FAILURE(pos, 3); + else + MB_FAILURE(pos, 4); + } + this_char = ((c & 0x07) << 18) | ((str[pos + 1] & 0x3f) << 12) | ((str[pos + 2] & 0x3f) << 6) | (str[pos + 3] & 0x3f); + if (this_char < 0x10000 || this_char > 0x10FFFF) { /* non-shortest form or outside range */ + MB_FAILURE(pos, 4); + } + pos += 4; + } else { + MB_FAILURE(pos, 1); + } + } + break; + + case cs_big5: + /* reference http://demo.icu-project.org/icu-bin/convexp?conv=big5 */ + { + unsigned char c = str[pos]; + if (c >= 0x81 && c <= 0xFE) { + unsigned char next; + if (!CHECK_LEN(pos, 2)) + MB_FAILURE(pos, 1); + + next = str[pos + 1]; + + if ((next >= 0x40 && next <= 0x7E) || + (next >= 0xA1 && next <= 0xFE)) { + this_char = (c << 8) | next; + } else { + MB_FAILURE(pos, 1); + } + pos += 2; + } else { + this_char = c; + pos += 1; + } + } + break; + + case cs_big5hkscs: + { + unsigned char c = str[pos]; + if (c >= 0x81 && c <= 0xFE) { + unsigned char next; + if (!CHECK_LEN(pos, 2)) + MB_FAILURE(pos, 1); + + next = str[pos + 1]; + + if ((next >= 0x40 && next <= 0x7E) || + (next >= 0xA1 && next <= 0xFE)) { + this_char = (c << 8) | next; + } else if (next != 0x80 && next != 0xFF) { + MB_FAILURE(pos, 1); + } else { + MB_FAILURE(pos, 2); + } + pos += 2; + } else { + this_char = c; + pos += 1; + } + } + break; + + case cs_gb2312: /* EUC-CN */ + { + unsigned char c = str[pos]; + if (c >= 0xA1 && c <= 0xFE) { + unsigned char next; + if (!CHECK_LEN(pos, 2)) + MB_FAILURE(pos, 1); + + next = str[pos + 1]; + + if (gb2312_trail(next)) { + this_char = (c << 8) | next; + } else if (gb2312_lead(next)) { + MB_FAILURE(pos, 1); + } else { + MB_FAILURE(pos, 2); + } + pos += 2; + } else if (gb2312_lead(c)) { + this_char = c; + pos += 1; + } else { + MB_FAILURE(pos, 1); + } + } + break; + + case cs_sjis: + { + unsigned char c = str[pos]; + if ((c >= 0x81 && c <= 0x9F) || (c >= 0xE0 && c <= 0xFC)) { + unsigned char next; + if (!CHECK_LEN(pos, 2)) + MB_FAILURE(pos, 1); + + next = str[pos + 1]; + + if (sjis_trail(next)) { + this_char = (c << 8) | next; + } else if (sjis_lead(next)) { + MB_FAILURE(pos, 1); + } else { + MB_FAILURE(pos, 2); + } + pos += 2; + } else if (c < 0x80 || (c >= 0xA1 && c <= 0xDF)) { + this_char = c; + pos += 1; + } else { + MB_FAILURE(pos, 1); + } + } + break; + + case cs_eucjp: + { + unsigned char c = str[pos]; + + if (c >= 0xA1 && c <= 0xFE) { + unsigned next; + if (!CHECK_LEN(pos, 2)) + MB_FAILURE(pos, 1); + next = str[pos + 1]; + + if (next >= 0xA1 && next <= 0xFE) { + /* this a jis kanji char */ + this_char = (c << 8) | next; + } else { + MB_FAILURE(pos, (next != 0xA0 && next != 0xFF) ? 1 : 2); + } + pos += 2; + } else if (c == 0x8E) { + unsigned next; + if (!CHECK_LEN(pos, 2)) + MB_FAILURE(pos, 1); + + next = str[pos + 1]; + if (next >= 0xA1 && next <= 0xDF) { + /* JIS X 0201 kana */ + this_char = (c << 8) | next; + } else { + MB_FAILURE(pos, (next != 0xA0 && next != 0xFF) ? 1 : 2); + } + pos += 2; + } else if (c == 0x8F) { + size_t avail = str_len - pos; + + if (avail < 3 || !(str[pos + 1] >= 0xA1 && str[pos + 1] <= 0xFE) || + !(str[pos + 2] >= 0xA1 && str[pos + 2] <= 0xFE)) { + if (avail < 2 || (str[pos + 1] != 0xA0 && str[pos + 1] != 0xFF)) + MB_FAILURE(pos, 1); + else if (avail < 3 || (str[pos + 2] != 0xA0 && str[pos + 2] != 0xFF)) + MB_FAILURE(pos, 2); + else + MB_FAILURE(pos, 3); + } else { + /* JIS X 0212 hojo-kanji */ + this_char = (c << 16) | (str[pos + 1] << 8) | str[pos + 2]; + } + pos += 3; + } else if (c != 0xA0 && c != 0xFF) { + /* character encoded in 1 code unit */ + this_char = c; + pos += 1; + } else { + MB_FAILURE(pos, 1); + } + } + break; + default: + /* single-byte charsets */ + this_char = str[pos++]; + break; + } + + *cursor = pos; + return this_char; +} +",1,"static inline unsigned int get_next_char( + enum entity_charset charset, + const unsigned char *str, + size_t str_len, + size_t *cursor, + int *status) +{ + size_t pos = *cursor; + unsigned int this_char = 0; + + *status = SUCCESS; + assert(pos <= str_len); + + if (!CHECK_LEN(pos, 1)) + MB_FAILURE(pos, 1); + + switch (charset) { + case cs_utf_8: + { + /* We'll follow strategy 2. from section 3.6.1 of UTR #36: + * ""In a reported illegal byte sequence, do not include any + * non-initial byte that encodes a valid character or is a leading + * byte for a valid sequence."" */ + unsigned char c; + c = str[pos]; + if (c < 0x80) { + this_char = c; + pos++; + } else if (c < 0xc2) { + MB_FAILURE(pos, 1); + } else if (c < 0xe0) { + if (!CHECK_LEN(pos, 2)) + MB_FAILURE(pos, 1); + + if (!utf8_trail(str[pos + 1])) { + MB_FAILURE(pos, utf8_lead(str[pos + 1]) ? 1 : 2); + } + this_char = ((c & 0x1f) << 6) | (str[pos + 1] & 0x3f); + if (this_char < 0x80) { /* non-shortest form */ + MB_FAILURE(pos, 2); + } + pos += 2; + } else if (c < 0xf0) { + size_t avail = str_len - pos; + + if (avail < 3 || + !utf8_trail(str[pos + 1]) || !utf8_trail(str[pos + 2])) { + if (avail < 2 || utf8_lead(str[pos + 1])) + MB_FAILURE(pos, 1); + else if (avail < 3 || utf8_lead(str[pos + 2])) + MB_FAILURE(pos, 2); + else + MB_FAILURE(pos, 3); + } + + this_char = ((c & 0x0f) << 12) | ((str[pos + 1] & 0x3f) << 6) | (str[pos + 2] & 0x3f); + if (this_char < 0x800) { /* non-shortest form */ + MB_FAILURE(pos, 3); + } else if (this_char >= 0xd800 && this_char <= 0xdfff) { /* surrogate */ + MB_FAILURE(pos, 3); + } + pos += 3; + } else if (c < 0xf5) { + size_t avail = str_len - pos; + + if (avail < 4 || + !utf8_trail(str[pos + 1]) || !utf8_trail(str[pos + 2]) || + !utf8_trail(str[pos + 3])) { + if (avail < 2 || utf8_lead(str[pos + 1])) + MB_FAILURE(pos, 1); + else if (avail < 3 || utf8_lead(str[pos + 2])) + MB_FAILURE(pos, 2); + else if (avail < 4 || utf8_lead(str[pos + 3])) + MB_FAILURE(pos, 3); + else + MB_FAILURE(pos, 4); + } + + this_char = ((c & 0x07) << 18) | ((str[pos + 1] & 0x3f) << 12) | ((str[pos + 2] & 0x3f) << 6) | (str[pos + 3] & 0x3f); + if (this_char < 0x10000 || this_char > 0x10FFFF) { /* non-shortest form or outside range */ + MB_FAILURE(pos, 4); + } + pos += 4; + } else { + MB_FAILURE(pos, 1); + } + } + break; + + case cs_big5: + /* reference http://demo.icu-project.org/icu-bin/convexp?conv=big5 */ + { + unsigned char c = str[pos]; + if (c >= 0x81 && c <= 0xFE) { + unsigned char next; + if (!CHECK_LEN(pos, 2)) + MB_FAILURE(pos, 1); + + next = str[pos + 1]; + + if ((next >= 0x40 && next <= 0x7E) || + (next >= 0xA1 && next <= 0xFE)) { + this_char = (c << 8) | next; + } else { + MB_FAILURE(pos, 1); + } + pos += 2; + } else { + this_char = c; + pos += 1; + } + } + break; + + case cs_big5hkscs: + { + unsigned char c = str[pos]; + if (c >= 0x81 && c <= 0xFE) { + unsigned char next; + if (!CHECK_LEN(pos, 2)) + MB_FAILURE(pos, 1); + + next = str[pos + 1]; + + if ((next >= 0x40 && next <= 0x7E) || + (next >= 0xA1 && next <= 0xFE)) { + this_char = (c << 8) | next; + } else if (next != 0x80 && next != 0xFF) { + MB_FAILURE(pos, 1); + } else { + MB_FAILURE(pos, 2); + } + pos += 2; + } else { + this_char = c; + pos += 1; + } + } + break; + + case cs_gb2312: /* EUC-CN */ + { + unsigned char c = str[pos]; + if (c >= 0xA1 && c <= 0xFE) { + unsigned char next; + if (!CHECK_LEN(pos, 2)) + MB_FAILURE(pos, 1); + + next = str[pos + 1]; + + if (gb2312_trail(next)) { + this_char = (c << 8) | next; + } else if (gb2312_lead(next)) { + MB_FAILURE(pos, 1); + } else { + MB_FAILURE(pos, 2); + } + pos += 2; + } else if (gb2312_lead(c)) { + this_char = c; + pos += 1; + } else { + MB_FAILURE(pos, 1); + } + } + break; + + case cs_sjis: + { + unsigned char c = str[pos]; + if ((c >= 0x81 && c <= 0x9F) || (c >= 0xE0 && c <= 0xFC)) { + unsigned char next; + if (!CHECK_LEN(pos, 2)) + MB_FAILURE(pos, 1); + + next = str[pos + 1]; + + if (sjis_trail(next)) { + this_char = (c << 8) | next; + } else if (sjis_lead(next)) { + MB_FAILURE(pos, 1); + } else { + MB_FAILURE(pos, 2); + } + pos += 2; + } else if (c < 0x80 || (c >= 0xA1 && c <= 0xDF)) { + this_char = c; + pos += 1; + } else { + MB_FAILURE(pos, 1); + } + } + break; + + case cs_eucjp: + { + unsigned char c = str[pos]; + + if (c >= 0xA1 && c <= 0xFE) { + unsigned next; + if (!CHECK_LEN(pos, 2)) + MB_FAILURE(pos, 1); + next = str[pos + 1]; + + if (next >= 0xA1 && next <= 0xFE) { + /* this a jis kanji char */ + this_char = (c << 8) | next; + } else { + MB_FAILURE(pos, (next != 0xA0 && next != 0xFF) ? 1 : 2); + } + pos += 2; + } else if (c == 0x8E) { + unsigned next; + if (!CHECK_LEN(pos, 2)) + MB_FAILURE(pos, 1); + + next = str[pos + 1]; + if (next >= 0xA1 && next <= 0xDF) { + /* JIS X 0201 kana */ + this_char = (c << 8) | next; + } else { + MB_FAILURE(pos, (next != 0xA0 && next != 0xFF) ? 1 : 2); + } + pos += 2; + } else if (c == 0x8F) { + size_t avail = str_len - pos; + + if (avail < 3 || !(str[pos + 1] >= 0xA1 && str[pos + 1] <= 0xFE) || + !(str[pos + 2] >= 0xA1 && str[pos + 2] <= 0xFE)) { + if (avail < 2 || (str[pos + 1] != 0xA0 && str[pos + 1] != 0xFF)) + MB_FAILURE(pos, 1); + else if (avail < 3 || (str[pos + 2] != 0xA0 && str[pos + 2] != 0xFF)) + MB_FAILURE(pos, 2); + else + MB_FAILURE(pos, 3); + } else { + /* JIS X 0212 hojo-kanji */ + this_char = (c << 16) | (str[pos + 1] << 8) | str[pos + 2]; + } + pos += 3; + } else if (c != 0xA0 && c != 0xFF) { + /* character encoded in 1 code unit */ + this_char = c; + pos += 1; + } else { + MB_FAILURE(pos, 1); + } + } + break; + default: + /* single-byte charsets */ + this_char = str[pos++]; + break; + } + + *cursor = pos; + return this_char; +} +","@@ -163,7 +163,7 @@ static inline unsigned int get_next_char( + else + MB_FAILURE(pos, 4); + } +- ++ + this_char = ((c & 0x07) << 18) | ((str[pos + 1] & 0x3f) << 12) | ((str[pos + 2] & 0x3f) << 6) | (str[pos + 3] & 0x3f); + if (this_char < 0x10000 || this_char > 0x10FFFF) { /* non-shortest form or outside range */ + MB_FAILURE(pos, 4); +@@ -437,7 +437,7 @@ static enum entity_charset determine_charset(char *charset_hint TSRMLS_DC) + + if (charset_hint) { + int found = 0; +- ++ + /* now walk the charset map and look for the codeset */ + for (i = 0; charset_map[i].codeset; i++) { + if (len == strlen(charset_map[i].codeset) && strncasecmp(charset_hint, charset_map[i].codeset, len) == 0) { +@@ -545,7 +545,7 @@ static inline unsigned char unimap_bsearch(const uni_to_enc *table, unsigned cod + return 0; + + code_key = (unsigned short) code_key_a; +- ++ + while (l <= h) { + m = l + (h - l) / 2; + if (code_key < m->un_code_point) +@@ -571,7 +571,7 @@ static inline int map_from_unicode(unsigned code, enum entity_charset charset, u + /* identity mapping of code points to unicode */ + if (code > 0xFF) { + return FAILURE; +- } ++ } + *res = code; + break; + +@@ -590,7 +590,7 @@ static inline int map_from_unicode(unsigned code, enum entity_charset charset, u + return FAILURE; + } + break; +- ++ + case cs_8859_15: + if (code < 0xA4 || (code > 0xBE && code <= 0xFF)) { + *res = code; +@@ -634,7 +634,7 @@ static inline int map_from_unicode(unsigned code, enum entity_charset charset, u + case cs_cp866: + table = unimap_cp866; + table_size = sizeof(unimap_cp866) / sizeof(*unimap_cp866); +- ++ + table_over_7F: + if (code <= 0x7F) { + *res = code; +@@ -710,7 +710,7 @@ static inline int unicode_cp_is_allowed(unsigned uni_cp, int document_type) + * Not sure this is the relevant part for HTML 5, though. I opted to + * disallow the characters that would result in a parse error when + * preprocessing of the input stream. See also section 8.1.3. +- * ++ * + * It's unclear if XHTML 1.0 allows C1 characters. I'll opt to apply to + * XHTML 1.0 the same rules as for XML 1.0. + * See . +@@ -774,7 +774,7 @@ static inline int numeric_entity_is_allowed(unsigned uni_cp, int document_type) + /* {{{ process_numeric_entity + * Auxiliary function to traverse_for_entities. + * On input, *buf should point to the first character after # and on output, it's the last +- * byte read, no matter if there was success or insuccess. ++ * byte read, no matter if there was success or insuccess. + */ + static inline int process_numeric_entity(const char **buf, unsigned *code_point) + { +@@ -784,7 +784,7 @@ static inline int process_numeric_entity(const char **buf, unsigned *code_point) + + if (hexadecimal && (**buf != '\0')) + (*buf)++; +- ++ + /* strtol allows whitespace and other stuff in the beginning + * we're not interested */ + if ((hexadecimal && !isxdigit(**buf)) || +@@ -969,7 +969,7 @@ static void traverse_for_entities( + goto invalid_code; + + /* are we allowed to decode this entity in this document type? +- * HTML 5 is the only that has a character that cannot be used in ++ * HTML 5 is the only that has a character that cannot be used in + * a numeric entity but is allowed literally (U+000D). The + * unoptimized version would be ... || !numeric_entity_is_allowed(code) */ + if (!unicode_cp_is_allowed(code, doctype) || +@@ -996,9 +996,9 @@ static void traverse_for_entities( + } + } + } +- ++ + assert(*next == ';'); +- ++ + if (((code == '\'' && !(flags & ENT_HTML_QUOTE_SINGLE)) || + (code == '""' && !(flags & ENT_HTML_QUOTE_DOUBLE))) + /* && code2 == '\0' always true for current maps */) +@@ -1026,7 +1026,7 @@ static void traverse_for_entities( + *(q++) = *p; + } + } +- ++ + *q = '\0'; + *retlen = (size_t)(q - ret); + } +@@ -1066,7 +1066,7 @@ static entity_table_opt determine_entity_table(int all, int doctype) + entity_table_opt retval = {NULL}; + + assert(!(doctype == ENT_HTML_DOC_XML1 && all)); +- ++ + if (all) { + retval.ms_table = (doctype == ENT_HTML_DOC_HTML5) ? + entity_ms_table_html5 : entity_ms_table_html4; +@@ -1111,13 +1111,13 @@ PHPAPI char *php_unescape_html_entities(unsigned char *old, size_t oldlen, size_ + if (retlen == 0) { + goto empty_source; + } +- ++ + inverse_map = unescape_inverse_map(all, flags); +- ++ + /* replace numeric entities */ + traverse_for_entities(old, oldlen, ret, &retlen, all, flags, inverse_map, charset); + +-empty_source: ++empty_source: + *newlen = retlen; + return ret; + } +@@ -1141,7 +1141,7 @@ static inline void find_entity_for_char( + { + unsigned stage1_idx = ENT_STAGE1_INDEX(k); + const entity_stage3_row *c; +- ++ + if (stage1_idx > 0x1D) { + *entity = NULL; + *entity_len = 0; +@@ -1162,7 +1162,7 @@ static inline void find_entity_for_char( + if (!(*cursor < oldlen)) + goto no_suitable_2nd; + +- next_char = get_next_char(charset, old, oldlen, cursor, &status); ++ next_char = get_next_char(charset, old, oldlen, cursor, &status); + + if (status == FAILURE) + goto no_suitable_2nd; +@@ -1187,7 +1187,7 @@ static inline void find_entity_for_char( + *entity = (const unsigned char *) + c->data.multicodepoint_table[0].leading_entry.default_entity; + *entity_len = c->data.multicodepoint_table[0].leading_entry.default_entity_len; +- } ++ } + } + /* }}} */ + +@@ -1255,7 +1255,7 @@ PHPAPI char *php_escape_html_entities_ex(unsigned char *old, size_t oldlen, size + + /* initial estimate */ + if (oldlen < 64) { +- maxlen = 128; ++ maxlen = 128; + } else { + maxlen = 2 * oldlen; + if (maxlen < oldlen) { +@@ -1444,6 +1444,10 @@ static void php_html_entities(INTERNAL_FUNCTION_PARAMETERS, int all) + } + + replaced = php_escape_html_entities_ex(str, str_len, &new_len, all, (int) flags, hint_charset, double_encode TSRMLS_CC); ++ if (new_len > INT_MAX) { ++ efree(replaced); ++ RETURN_FALSE; ++ } + RETVAL_STRINGL(replaced, (int)new_len, 0); + } + /* }}} */ +@@ -1577,7 +1581,7 @@ static inline void write_s3row_data( + } else { + spe_cp = uni_cp; + } +- ++ + written_k2 = write_octet_sequence(&key[written_k1], charset, spe_cp); + memcpy(&entity[1], mcpr[i].normal_entry.entity, l); + entity[l + 1] = ';'; +@@ -1615,7 +1619,7 @@ PHP_FUNCTION(get_html_translation_table) + LIMIT_ALL(all, doctype, charset); + + array_init(return_value); +- ++ + entity_table = determine_entity_table(all, doctype); + if (all && !CHARSET_UNICODE_COMPAT(charset)) { + to_uni_table = enc_to_uni_index[charset];",2349,2680,4096 +9058,"static void cexp(JF, js_Ast *exp) +{ + int then, end; + int n; + + switch (exp->type) { + case EXP_STRING: + emitline(J, F, exp); + emitstring(J, F, OP_STRING, exp->string); + break; + case EXP_NUMBER: + emitline(J, F, exp); + emitnumber(J, F, exp->number); + break; + case EXP_UNDEF: + emitline(J, F, exp); + emit(J, F, OP_UNDEF); + break; + case EXP_NULL: + emitline(J, F, exp); + emit(J, F, OP_NULL); + break; + case EXP_TRUE: + emitline(J, F, exp); + emit(J, F, OP_TRUE); + break; + case EXP_FALSE: + emitline(J, F, exp); + emit(J, F, OP_FALSE); + break; + case EXP_THIS: + emitline(J, F, exp); + emit(J, F, OP_THIS); + break; + + case EXP_REGEXP: + emitline(J, F, exp); + emit(J, F, OP_NEWREGEXP); + emitarg(J, F, addstring(J, F, exp->string)); + emitarg(J, F, exp->number); + break; + + case EXP_OBJECT: + emitline(J, F, exp); + emit(J, F, OP_NEWOBJECT); + cobject(J, F, exp->a); + break; + + case EXP_ARRAY: + emitline(J, F, exp); + emit(J, F, OP_NEWARRAY); + carray(J, F, exp->a); + break; + + case EXP_FUN: + emitline(J, F, exp); + emitfunction(J, F, newfun(J, exp->line, exp->a, exp->b, exp->c, 0, F->strict)); + break; + + case EXP_IDENTIFIER: + emitline(J, F, exp); + emitlocal(J, F, OP_GETLOCAL, OP_GETVAR, exp); + break; + + case EXP_INDEX: + cexp(J, F, exp->a); + cexp(J, F, exp->b); + emitline(J, F, exp); + emit(J, F, OP_GETPROP); + break; + + case EXP_MEMBER: + cexp(J, F, exp->a); + emitline(J, F, exp); + emitstring(J, F, OP_GETPROP_S, exp->b->string); + break; + + case EXP_CALL: + ccall(J, F, exp->a, exp->b); + break; + + case EXP_NEW: + cexp(J, F, exp->a); + n = cargs(J, F, exp->b); + emitline(J, F, exp); + emit(J, F, OP_NEW); + emitarg(J, F, n); + break; + + case EXP_DELETE: + cdelete(J, F, exp); + break; + + case EXP_PREINC: + cassignop1(J, F, exp->a); + emitline(J, F, exp); + emit(J, F, OP_INC); + cassignop2(J, F, exp->a, 0); + break; + + case EXP_PREDEC: + cassignop1(J, F, exp->a); + emitline(J, F, exp); + emit(J, F, OP_DEC); + cassignop2(J, F, exp->a, 0); + break; + + case EXP_POSTINC: + cassignop1(J, F, exp->a); + emitline(J, F, exp); + emit(J, F, OP_POSTINC); + cassignop2(J, F, exp->a, 1); + emit(J, F, OP_POP); + break; + + case EXP_POSTDEC: + cassignop1(J, F, exp->a); + emitline(J, F, exp); + emit(J, F, OP_POSTDEC); + cassignop2(J, F, exp->a, 1); + emit(J, F, OP_POP); + break; + + case EXP_VOID: + cexp(J, F, exp->a); + emitline(J, F, exp); + emit(J, F, OP_POP); + emit(J, F, OP_UNDEF); + break; + + case EXP_TYPEOF: ctypeof(J, F, exp); break; + case EXP_POS: cunary(J, F, exp, OP_POS); break; + case EXP_NEG: cunary(J, F, exp, OP_NEG); break; + case EXP_BITNOT: cunary(J, F, exp, OP_BITNOT); break; + case EXP_LOGNOT: cunary(J, F, exp, OP_LOGNOT); break; + + case EXP_BITOR: cbinary(J, F, exp, OP_BITOR); break; + case EXP_BITXOR: cbinary(J, F, exp, OP_BITXOR); break; + case EXP_BITAND: cbinary(J, F, exp, OP_BITAND); break; + case EXP_EQ: cbinary(J, F, exp, OP_EQ); break; + case EXP_NE: cbinary(J, F, exp, OP_NE); break; + case EXP_STRICTEQ: cbinary(J, F, exp, OP_STRICTEQ); break; + case EXP_STRICTNE: cbinary(J, F, exp, OP_STRICTNE); break; + case EXP_LT: cbinary(J, F, exp, OP_LT); break; + case EXP_GT: cbinary(J, F, exp, OP_GT); break; + case EXP_LE: cbinary(J, F, exp, OP_LE); break; + case EXP_GE: cbinary(J, F, exp, OP_GE); break; + case EXP_INSTANCEOF: cbinary(J, F, exp, OP_INSTANCEOF); break; + case EXP_IN: cbinary(J, F, exp, OP_IN); break; + case EXP_SHL: cbinary(J, F, exp, OP_SHL); break; + case EXP_SHR: cbinary(J, F, exp, OP_SHR); break; + case EXP_USHR: cbinary(J, F, exp, OP_USHR); break; + case EXP_ADD: cbinary(J, F, exp, OP_ADD); break; + case EXP_SUB: cbinary(J, F, exp, OP_SUB); break; + case EXP_MUL: cbinary(J, F, exp, OP_MUL); break; + case EXP_DIV: cbinary(J, F, exp, OP_DIV); break; + case EXP_MOD: cbinary(J, F, exp, OP_MOD); break; + + case EXP_ASS: cassign(J, F, exp); break; + case EXP_ASS_MUL: cassignop(J, F, exp, OP_MUL); break; + case EXP_ASS_DIV: cassignop(J, F, exp, OP_DIV); break; + case EXP_ASS_MOD: cassignop(J, F, exp, OP_MOD); break; + case EXP_ASS_ADD: cassignop(J, F, exp, OP_ADD); break; + case EXP_ASS_SUB: cassignop(J, F, exp, OP_SUB); break; + case EXP_ASS_SHL: cassignop(J, F, exp, OP_SHL); break; + case EXP_ASS_SHR: cassignop(J, F, exp, OP_SHR); break; + case EXP_ASS_USHR: cassignop(J, F, exp, OP_USHR); break; + case EXP_ASS_BITAND: cassignop(J, F, exp, OP_BITAND); break; + case EXP_ASS_BITXOR: cassignop(J, F, exp, OP_BITXOR); break; + case EXP_ASS_BITOR: cassignop(J, F, exp, OP_BITOR); break; + + case EXP_COMMA: + cexp(J, F, exp->a); + emitline(J, F, exp); + emit(J, F, OP_POP); + cexp(J, F, exp->b); + break; + + case EXP_LOGOR: + cexp(J, F, exp->a); + emitline(J, F, exp); + emit(J, F, OP_DUP); + end = emitjump(J, F, OP_JTRUE); + emit(J, F, OP_POP); + cexp(J, F, exp->b); + label(J, F, end); + break; + + case EXP_LOGAND: + cexp(J, F, exp->a); + emitline(J, F, exp); + emit(J, F, OP_DUP); + end = emitjump(J, F, OP_JFALSE); + emit(J, F, OP_POP); + cexp(J, F, exp->b); + label(J, F, end); + break; + + case EXP_COND: + cexp(J, F, exp->a); + emitline(J, F, exp); + then = emitjump(J, F, OP_JTRUE); + cexp(J, F, exp->c); + end = emitjump(J, F, OP_JUMP); + label(J, F, then); + cexp(J, F, exp->b); + label(J, F, end); + break; + + default: + jsC_error(J, exp, ""unknown expression: (%s)"", jsP_aststring(exp->type)); + } +} +",0,"static void cexp(JF, js_Ast *exp) +{ + int then, end; + int n; + + switch (exp->type) { + case EXP_STRING: + emitline(J, F, exp); + emitstring(J, F, OP_STRING, exp->string); + break; + case EXP_NUMBER: + emitline(J, F, exp); + emitnumber(J, F, exp->number); + break; + case EXP_UNDEF: + emitline(J, F, exp); + emit(J, F, OP_UNDEF); + break; + case EXP_NULL: + emitline(J, F, exp); + emit(J, F, OP_NULL); + break; + case EXP_TRUE: + emitline(J, F, exp); + emit(J, F, OP_TRUE); + break; + case EXP_FALSE: + emitline(J, F, exp); + emit(J, F, OP_FALSE); + break; + case EXP_THIS: + emitline(J, F, exp); + emit(J, F, OP_THIS); + break; + + case EXP_REGEXP: + emitline(J, F, exp); + emit(J, F, OP_NEWREGEXP); + emitarg(J, F, addstring(J, F, exp->string)); + emitarg(J, F, exp->number); + break; + + case EXP_OBJECT: + emitline(J, F, exp); + emit(J, F, OP_NEWOBJECT); + cobject(J, F, exp->a); + break; + + case EXP_ARRAY: + emitline(J, F, exp); + emit(J, F, OP_NEWARRAY); + carray(J, F, exp->a); + break; + + case EXP_FUN: + emitline(J, F, exp); + emitfunction(J, F, newfun(J, exp->line, exp->a, exp->b, exp->c, 0, F->strict)); + break; + + case EXP_IDENTIFIER: + emitline(J, F, exp); + emitlocal(J, F, OP_GETLOCAL, OP_GETVAR, exp); + break; + + case EXP_INDEX: + cexp(J, F, exp->a); + cexp(J, F, exp->b); + emitline(J, F, exp); + emit(J, F, OP_GETPROP); + break; + + case EXP_MEMBER: + cexp(J, F, exp->a); + emitline(J, F, exp); + emitstring(J, F, OP_GETPROP_S, exp->b->string); + break; + + case EXP_CALL: + ccall(J, F, exp->a, exp->b); + break; + + case EXP_NEW: + cexp(J, F, exp->a); + n = cargs(J, F, exp->b); + emitline(J, F, exp); + emit(J, F, OP_NEW); + emitarg(J, F, n); + break; + + case EXP_DELETE: + cdelete(J, F, exp); + break; + + case EXP_PREINC: + cassignop1(J, F, exp->a); + emitline(J, F, exp); + emit(J, F, OP_INC); + cassignop2(J, F, exp->a, 0); + break; + + case EXP_PREDEC: + cassignop1(J, F, exp->a); + emitline(J, F, exp); + emit(J, F, OP_DEC); + cassignop2(J, F, exp->a, 0); + break; + + case EXP_POSTINC: + cassignop1(J, F, exp->a); + emitline(J, F, exp); + emit(J, F, OP_POSTINC); + cassignop2(J, F, exp->a, 1); + emit(J, F, OP_POP); + break; + + case EXP_POSTDEC: + cassignop1(J, F, exp->a); + emitline(J, F, exp); + emit(J, F, OP_POSTDEC); + cassignop2(J, F, exp->a, 1); + emit(J, F, OP_POP); + break; + + case EXP_VOID: + cexp(J, F, exp->a); + emitline(J, F, exp); + emit(J, F, OP_POP); + emit(J, F, OP_UNDEF); + break; + + case EXP_TYPEOF: ctypeof(J, F, exp); break; + case EXP_POS: cunary(J, F, exp, OP_POS); break; + case EXP_NEG: cunary(J, F, exp, OP_NEG); break; + case EXP_BITNOT: cunary(J, F, exp, OP_BITNOT); break; + case EXP_LOGNOT: cunary(J, F, exp, OP_LOGNOT); break; + + case EXP_BITOR: cbinary(J, F, exp, OP_BITOR); break; + case EXP_BITXOR: cbinary(J, F, exp, OP_BITXOR); break; + case EXP_BITAND: cbinary(J, F, exp, OP_BITAND); break; + case EXP_EQ: cbinary(J, F, exp, OP_EQ); break; + case EXP_NE: cbinary(J, F, exp, OP_NE); break; + case EXP_STRICTEQ: cbinary(J, F, exp, OP_STRICTEQ); break; + case EXP_STRICTNE: cbinary(J, F, exp, OP_STRICTNE); break; + case EXP_LT: cbinary(J, F, exp, OP_LT); break; + case EXP_GT: cbinary(J, F, exp, OP_GT); break; + case EXP_LE: cbinary(J, F, exp, OP_LE); break; + case EXP_GE: cbinary(J, F, exp, OP_GE); break; + case EXP_INSTANCEOF: cbinary(J, F, exp, OP_INSTANCEOF); break; + case EXP_IN: cbinary(J, F, exp, OP_IN); break; + case EXP_SHL: cbinary(J, F, exp, OP_SHL); break; + case EXP_SHR: cbinary(J, F, exp, OP_SHR); break; + case EXP_USHR: cbinary(J, F, exp, OP_USHR); break; + case EXP_ADD: cbinary(J, F, exp, OP_ADD); break; + case EXP_SUB: cbinary(J, F, exp, OP_SUB); break; + case EXP_MUL: cbinary(J, F, exp, OP_MUL); break; + case EXP_DIV: cbinary(J, F, exp, OP_DIV); break; + case EXP_MOD: cbinary(J, F, exp, OP_MOD); break; + + case EXP_ASS: cassign(J, F, exp); break; + case EXP_ASS_MUL: cassignop(J, F, exp, OP_MUL); break; + case EXP_ASS_DIV: cassignop(J, F, exp, OP_DIV); break; + case EXP_ASS_MOD: cassignop(J, F, exp, OP_MOD); break; + case EXP_ASS_ADD: cassignop(J, F, exp, OP_ADD); break; + case EXP_ASS_SUB: cassignop(J, F, exp, OP_SUB); break; + case EXP_ASS_SHL: cassignop(J, F, exp, OP_SHL); break; + case EXP_ASS_SHR: cassignop(J, F, exp, OP_SHR); break; + case EXP_ASS_USHR: cassignop(J, F, exp, OP_USHR); break; + case EXP_ASS_BITAND: cassignop(J, F, exp, OP_BITAND); break; + case EXP_ASS_BITXOR: cassignop(J, F, exp, OP_BITXOR); break; + case EXP_ASS_BITOR: cassignop(J, F, exp, OP_BITOR); break; + + case EXP_COMMA: + cexp(J, F, exp->a); + emitline(J, F, exp); + emit(J, F, OP_POP); + cexp(J, F, exp->b); + break; + + case EXP_LOGOR: + cexp(J, F, exp->a); + emitline(J, F, exp); + emit(J, F, OP_DUP); + end = emitjump(J, F, OP_JTRUE); + emit(J, F, OP_POP); + cexp(J, F, exp->b); + label(J, F, end); + break; + + case EXP_LOGAND: + cexp(J, F, exp->a); + emitline(J, F, exp); + emit(J, F, OP_DUP); + end = emitjump(J, F, OP_JFALSE); + emit(J, F, OP_POP); + cexp(J, F, exp->b); + label(J, F, end); + break; + + case EXP_COND: + cexp(J, F, exp->a); + emitline(J, F, exp); + then = emitjump(J, F, OP_JTRUE); + cexp(J, F, exp->c); + end = emitjump(J, F, OP_JUMP); + label(J, F, then); + cexp(J, F, exp->b); + label(J, F, end); + break; + + default: + jsC_error(J, exp, ""unknown expression: (%s)"", jsP_aststring(exp->type)); + } +} +","@@ -1023,6 +1023,7 @@ static void ctrycatchfinally(JF, js_Ast *trystm, js_Ast *catchvar, js_Ast *catch + emitstring(J, F, OP_CATCH, catchvar->string); + cstm(J, F, catchstm); + emit(J, F, OP_ENDCATCH); ++ emit(J, F, OP_ENDTRY); + L3 = emitjump(J, F, OP_JUMP); /* skip past the try block to the finally block */ + } + label(J, F, L1);",1932,2263,4096 +9504,"doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, + size_t size, off_t fsize, int mach, int strtab, int *flags, + uint16_t *notecount) +{ + Elf32_Shdr sh32; + Elf64_Shdr sh64; + int stripped = 1; + size_t nbadcap = 0; + void *nbuf; + off_t noff, coff, name_off; + uint64_t cap_hw1 = 0; /* SunOS 5.x hardware capabilites */ + uint64_t cap_sf1 = 0; /* SunOS 5.x software capabilites */ + char name[50]; + ssize_t namesize; + + if (size != xsh_sizeof) { + if (file_printf(ms, "", corrupted section header size"") == -1) + return -1; + return 0; + } + + /* Read offset of name section to be able to read section names later */ + if (pread(fd, xsh_addr, xsh_sizeof, CAST(off_t, (off + size * strtab))) + < (ssize_t)xsh_sizeof) { + file_badread(ms); + return -1; + } + name_off = xsh_offset; + + for ( ; num; num--) { + /* Read the name of this section. */ + if ((namesize = pread(fd, name, sizeof(name) - 1, name_off + xsh_name)) == -1) { + file_badread(ms); + return -1; + } + name[namesize] = '\0'; + if (strcmp(name, "".debug_info"") == 0) + stripped = 0; + + if (pread(fd, xsh_addr, xsh_sizeof, off) < (ssize_t)xsh_sizeof) { + file_badread(ms); + return -1; + } + off += size; + + /* Things we can determine before we seek */ + switch (xsh_type) { + case SHT_SYMTAB: +#if 0 + case SHT_DYNSYM: +#endif + stripped = 0; + break; + default: + if (fsize != SIZE_UNKNOWN && xsh_offset > fsize) { + /* Perhaps warn here */ + continue; + } + break; + } + + + /* Things we can determine when we seek */ + switch (xsh_type) { + case SHT_NOTE: + if ((uintmax_t)(xsh_size + xsh_offset) > + (uintmax_t)fsize) { + if (file_printf(ms, + "", note offset/size 0x%"" INTMAX_T_FORMAT + ""x+0x%"" INTMAX_T_FORMAT ""x exceeds"" + "" file size 0x%"" INTMAX_T_FORMAT ""x"", + (uintmax_t)xsh_offset, (uintmax_t)xsh_size, + (uintmax_t)fsize) == -1) + return -1; + return 0; + } + if ((nbuf = malloc(xsh_size)) == NULL) { + file_error(ms, errno, ""Cannot allocate memory"" + "" for note""); + return -1; + } + if (pread(fd, nbuf, xsh_size, xsh_offset) < + (ssize_t)xsh_size) { + file_badread(ms); + free(nbuf); + return -1; + } + + noff = 0; + for (;;) { + if (noff >= (off_t)xsh_size) + break; + noff = donote(ms, nbuf, (size_t)noff, + xsh_size, clazz, swap, 4, flags, notecount, + fd, 0, 0, 0); + if (noff == 0) + break; + } + free(nbuf); + break; + case SHT_SUNW_cap: + switch (mach) { + case EM_SPARC: + case EM_SPARCV9: + case EM_IA_64: + case EM_386: + case EM_AMD64: + break; + default: + goto skip; + } + + if (nbadcap > 5) + break; + if (lseek(fd, xsh_offset, SEEK_SET) == (off_t)-1) { + file_badseek(ms); + return -1; + } + coff = 0; + for (;;) { + Elf32_Cap cap32; + Elf64_Cap cap64; + char cbuf[/*CONSTCOND*/ + MAX(sizeof cap32, sizeof cap64)]; + if ((coff += xcap_sizeof) > (off_t)xsh_size) + break; + if (read(fd, cbuf, (size_t)xcap_sizeof) != + (ssize_t)xcap_sizeof) { + file_badread(ms); + return -1; + } + if (cbuf[0] == 'A') { +#ifdef notyet + char *p = cbuf + 1; + uint32_t len, tag; + memcpy(&len, p, sizeof(len)); + p += 4; + len = getu32(swap, len); + if (memcmp(""gnu"", p, 3) != 0) { + if (file_printf(ms, + "", unknown capability %.3s"", p) + == -1) + return -1; + break; + } + p += strlen(p) + 1; + tag = *p++; + memcpy(&len, p, sizeof(len)); + p += 4; + len = getu32(swap, len); + if (tag != 1) { + if (file_printf(ms, "", unknown gnu"" + "" capability tag %d"", tag) + == -1) + return -1; + break; + } +#endif + break; + } + (void)memcpy(xcap_addr, cbuf, xcap_sizeof); + switch (xcap_tag) { + case CA_SUNW_NULL: + break; + case CA_SUNW_HW_1: + cap_hw1 |= xcap_val; + break; + case CA_SUNW_SF_1: + cap_sf1 |= xcap_val; + break; + default: + if (file_printf(ms, + "", with unknown capability "" + ""0x%"" INT64_T_FORMAT ""x = 0x%"" + INT64_T_FORMAT ""x"", + (unsigned long long)xcap_tag, + (unsigned long long)xcap_val) == -1) + return -1; + if (nbadcap++ > 2) + coff = xsh_size; + break; + } + } + /*FALLTHROUGH*/ + skip: + default: + break; + } + } + + if (file_printf(ms, "", %sstripped"", stripped ? """" : ""not "") == -1) + return -1; + if (cap_hw1) { + const cap_desc_t *cdp; + switch (mach) { + case EM_SPARC: + case EM_SPARC32PLUS: + case EM_SPARCV9: + cdp = cap_desc_sparc; + break; + case EM_386: + case EM_IA_64: + case EM_AMD64: + cdp = cap_desc_386; + break; + default: + cdp = NULL; + break; + } + if (file_printf(ms, "", uses"") == -1) + return -1; + if (cdp) { + while (cdp->cd_name) { + if (cap_hw1 & cdp->cd_mask) { + if (file_printf(ms, + "" %s"", cdp->cd_name) == -1) + return -1; + cap_hw1 &= ~cdp->cd_mask; + } + ++cdp; + } + if (cap_hw1) + if (file_printf(ms, + "" unknown hardware capability 0x%"" + INT64_T_FORMAT ""x"", + (unsigned long long)cap_hw1) == -1) + return -1; + } else { + if (file_printf(ms, + "" hardware capability 0x%"" INT64_T_FORMAT ""x"", + (unsigned long long)cap_hw1) == -1) + return -1; + } + } + if (cap_sf1) { + if (cap_sf1 & SF1_SUNW_FPUSED) { + if (file_printf(ms, + (cap_sf1 & SF1_SUNW_FPKNWN) + ? "", uses frame pointer"" + : "", not known to use frame pointer"") == -1) + return -1; + } + cap_sf1 &= ~SF1_SUNW_MASK; + if (cap_sf1) + if (file_printf(ms, + "", with unknown software capability 0x%"" + INT64_T_FORMAT ""x"", + (unsigned long long)cap_sf1) == -1) + return -1; + } + return 0; +} +",0,"doshn(struct magic_set *ms, int clazz, int swap, int fd, off_t off, int num, + size_t size, off_t fsize, int mach, int strtab, int *flags, + uint16_t *notecount) +{ + Elf32_Shdr sh32; + Elf64_Shdr sh64; + int stripped = 1; + size_t nbadcap = 0; + void *nbuf; + off_t noff, coff, name_off; + uint64_t cap_hw1 = 0; /* SunOS 5.x hardware capabilites */ + uint64_t cap_sf1 = 0; /* SunOS 5.x software capabilites */ + char name[50]; + ssize_t namesize; + + if (size != xsh_sizeof) { + if (file_printf(ms, "", corrupted section header size"") == -1) + return -1; + return 0; + } + + /* Read offset of name section to be able to read section names later */ + if (pread(fd, xsh_addr, xsh_sizeof, CAST(off_t, (off + size * strtab))) + < (ssize_t)xsh_sizeof) { + file_badread(ms); + return -1; + } + name_off = xsh_offset; + + for ( ; num; num--) { + /* Read the name of this section. */ + if ((namesize = pread(fd, name, sizeof(name) - 1, name_off + xsh_name)) == -1) { + file_badread(ms); + return -1; + } + name[namesize] = '\0'; + if (strcmp(name, "".debug_info"") == 0) + stripped = 0; + + if (pread(fd, xsh_addr, xsh_sizeof, off) < (ssize_t)xsh_sizeof) { + file_badread(ms); + return -1; + } + off += size; + + /* Things we can determine before we seek */ + switch (xsh_type) { + case SHT_SYMTAB: +#if 0 + case SHT_DYNSYM: +#endif + stripped = 0; + break; + default: + if (fsize != SIZE_UNKNOWN && xsh_offset > fsize) { + /* Perhaps warn here */ + continue; + } + break; + } + + + /* Things we can determine when we seek */ + switch (xsh_type) { + case SHT_NOTE: + if ((uintmax_t)(xsh_size + xsh_offset) > + (uintmax_t)fsize) { + if (file_printf(ms, + "", note offset/size 0x%"" INTMAX_T_FORMAT + ""x+0x%"" INTMAX_T_FORMAT ""x exceeds"" + "" file size 0x%"" INTMAX_T_FORMAT ""x"", + (uintmax_t)xsh_offset, (uintmax_t)xsh_size, + (uintmax_t)fsize) == -1) + return -1; + return 0; + } + if ((nbuf = malloc(xsh_size)) == NULL) { + file_error(ms, errno, ""Cannot allocate memory"" + "" for note""); + return -1; + } + if (pread(fd, nbuf, xsh_size, xsh_offset) < + (ssize_t)xsh_size) { + file_badread(ms); + free(nbuf); + return -1; + } + + noff = 0; + for (;;) { + if (noff >= (off_t)xsh_size) + break; + noff = donote(ms, nbuf, (size_t)noff, + xsh_size, clazz, swap, 4, flags, notecount, + fd, 0, 0, 0); + if (noff == 0) + break; + } + free(nbuf); + break; + case SHT_SUNW_cap: + switch (mach) { + case EM_SPARC: + case EM_SPARCV9: + case EM_IA_64: + case EM_386: + case EM_AMD64: + break; + default: + goto skip; + } + + if (nbadcap > 5) + break; + if (lseek(fd, xsh_offset, SEEK_SET) == (off_t)-1) { + file_badseek(ms); + return -1; + } + coff = 0; + for (;;) { + Elf32_Cap cap32; + Elf64_Cap cap64; + char cbuf[/*CONSTCOND*/ + MAX(sizeof cap32, sizeof cap64)]; + if ((coff += xcap_sizeof) > (off_t)xsh_size) + break; + if (read(fd, cbuf, (size_t)xcap_sizeof) != + (ssize_t)xcap_sizeof) { + file_badread(ms); + return -1; + } + if (cbuf[0] == 'A') { +#ifdef notyet + char *p = cbuf + 1; + uint32_t len, tag; + memcpy(&len, p, sizeof(len)); + p += 4; + len = getu32(swap, len); + if (memcmp(""gnu"", p, 3) != 0) { + if (file_printf(ms, + "", unknown capability %.3s"", p) + == -1) + return -1; + break; + } + p += strlen(p) + 1; + tag = *p++; + memcpy(&len, p, sizeof(len)); + p += 4; + len = getu32(swap, len); + if (tag != 1) { + if (file_printf(ms, "", unknown gnu"" + "" capability tag %d"", tag) + == -1) + return -1; + break; + } +#endif + break; + } + (void)memcpy(xcap_addr, cbuf, xcap_sizeof); + switch (xcap_tag) { + case CA_SUNW_NULL: + break; + case CA_SUNW_HW_1: + cap_hw1 |= xcap_val; + break; + case CA_SUNW_SF_1: + cap_sf1 |= xcap_val; + break; + default: + if (file_printf(ms, + "", with unknown capability "" + ""0x%"" INT64_T_FORMAT ""x = 0x%"" + INT64_T_FORMAT ""x"", + (unsigned long long)xcap_tag, + (unsigned long long)xcap_val) == -1) + return -1; + if (nbadcap++ > 2) + coff = xsh_size; + break; + } + } + /*FALLTHROUGH*/ + skip: + default: + break; + } + } + + if (file_printf(ms, "", %sstripped"", stripped ? """" : ""not "") == -1) + return -1; + if (cap_hw1) { + const cap_desc_t *cdp; + switch (mach) { + case EM_SPARC: + case EM_SPARC32PLUS: + case EM_SPARCV9: + cdp = cap_desc_sparc; + break; + case EM_386: + case EM_IA_64: + case EM_AMD64: + cdp = cap_desc_386; + break; + default: + cdp = NULL; + break; + } + if (file_printf(ms, "", uses"") == -1) + return -1; + if (cdp) { + while (cdp->cd_name) { + if (cap_hw1 & cdp->cd_mask) { + if (file_printf(ms, + "" %s"", cdp->cd_name) == -1) + return -1; + cap_hw1 &= ~cdp->cd_mask; + } + ++cdp; + } + if (cap_hw1) + if (file_printf(ms, + "" unknown hardware capability 0x%"" + INT64_T_FORMAT ""x"", + (unsigned long long)cap_hw1) == -1) + return -1; + } else { + if (file_printf(ms, + "" hardware capability 0x%"" INT64_T_FORMAT ""x"", + (unsigned long long)cap_hw1) == -1) + return -1; + } + } + if (cap_sf1) { + if (cap_sf1 & SF1_SUNW_FPUSED) { + if (file_printf(ms, + (cap_sf1 & SF1_SUNW_FPKNWN) + ? "", uses frame pointer"" + : "", not known to use frame pointer"") == -1) + return -1; + } + cap_sf1 &= ~SF1_SUNW_MASK; + if (cap_sf1) + if (file_printf(ms, + "", with unknown software capability 0x%"" + INT64_T_FORMAT ""x"", + (unsigned long long)cap_sf1) == -1) + return -1; + } + return 0; +} +","@@ -27,7 +27,7 @@ + #include ""file.h"" + + #ifndef lint +-FILE_RCSID(""@(#)$File: readelf.c,v 1.126 2015/11/16 16:03:45 christos Exp $"") ++FILE_RCSID(""@(#)$File: readelf.c,v 1.127 2015/11/18 12:29:29 christos Exp $"") + #endif + + #ifdef BUILTIN_ELF +@@ -509,12 +509,26 @@ do_bid_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type, + size_t noff, size_t doff, int *flags) + { + if (namesz == 4 && strcmp((char *)&nbuf[noff], ""GNU"") == 0 && +- type == NT_GNU_BUILD_ID && (descsz == 16 || descsz == 20)) { ++ type == NT_GNU_BUILD_ID && (descsz >= 4 || descsz <= 20)) { + uint8_t desc[20]; ++ const char *btype; + uint32_t i; + *flags |= FLAGS_DID_BUILD_ID; +- if (file_printf(ms, "", BuildID[%s]="", descsz == 16 ? ""md5/uuid"" : +- ""sha1"") == -1) ++ switch (descsz) { ++ case 8: ++ btype = ""xxHash""; ++ break; ++ case 16: ++ btype = ""md5/uuid""; ++ break; ++ case 20: ++ btype = ""sha1""; ++ break; ++ default: ++ btype = ""unknown""; ++ break; ++ } ++ if (file_printf(ms, "", BuildID[%s]="", btype) == -1) + return 1; + (void)memcpy(desc, &nbuf[doff], descsz); + for (i = 0; i < descsz; i++)",1993,2324,4096 +11051,"bool WebPage::blockZoom(const Platform::IntPoint& documentTargetPoint) +{ + if (!d->m_mainFrame->view() || !d->isUserScalable()) + return false; + + Node* node = d->bestNodeForZoomUnderPoint(documentTargetPoint); + if (!node) + return false; + + IntRect nodeRect = d->rectForNode(node); + IntRect blockRect; + bool endOfBlockZoomMode = d->compareNodesForBlockZoom(d->m_currentBlockZoomAdjustedNode.get(), node); + const double oldScale = d->m_transformationMatrix->m11(); + double newScale = 0; + const double margin = endOfBlockZoomMode ? 0 : blockZoomMargin * 2 * oldScale; + bool isFirstZoom = false; + + if (endOfBlockZoomMode) { + IntRect rect = d->blockZoomRectForNode(node); + blockRect = IntRect(0, rect.y(), d->transformedContentsSize().width(), d->transformedContentsSize().height() - rect.y()); + d->m_shouldReflowBlock = false; + } else { + Node* tempBlockZoomAdjustedNode = d->m_currentBlockZoomAdjustedNode.get(); + blockRect = d->blockZoomRectForNode(node); + + if (!node->hasTagName(HTMLNames::imgTag)) { + IntRect tRect = d->mapFromTransformed(blockRect); + int blockArea = tRect.width() * tRect.height(); + int pageArea = d->contentsSize().width() * d->contentsSize().height(); + double blockToPageRatio = static_cast(pageArea - blockArea) / pageArea; + if (blockToPageRatio < minimumExpandingRatio) { + d->m_currentBlockZoomAdjustedNode = tempBlockZoomAdjustedNode; + return false; + } + } + + if (blockRect.isEmpty() || !blockRect.width() || !blockRect.height()) + return false; + + if (!d->m_currentBlockZoomNode.get()) + isFirstZoom = true; + + d->m_currentBlockZoomNode = node; + d->m_shouldReflowBlock = true; + } + + newScale = std::min(d->newScaleForBlockZoomRect(blockRect, oldScale, margin), d->maxBlockZoomScale()); + newScale = std::max(newScale, minimumScale()); + +#if ENABLE(VIEWPORT_REFLOW) + if (d->m_currentBlockZoomNode && d->m_shouldReflowBlock && settings()->textReflowMode() != WebSettings::TextReflowDisabled) { + RenderObject* renderer = d->m_currentBlockZoomNode->renderer(); + if (renderer && renderer->isText()) { + double newFontSize = renderer->style()->fontSize() * newScale; + if (newFontSize < d->m_webSettings->defaultFontSize()) { + newScale = std::min(static_cast(d->m_webSettings->defaultFontSize()) / renderer->style()->fontSize(), d->maxBlockZoomScale()); + newScale = std::max(newScale, minimumScale()); + } + blockRect.setWidth(oldScale * static_cast(d->transformedActualVisibleSize().width()) / newScale); + newScale = std::min(d->newScaleForBlockZoomRect(blockRect, oldScale, margin), d->maxBlockZoomScale()); + newScale = std::max(newScale, minimumScale()); // Still, it's not allowed to be smaller than minimum scale. + } + } +#endif + + double newBlockHeight = d->mapFromTransformed(blockRect).height(); + double newBlockWidth = d->mapFromTransformed(blockRect).width(); + double scaledViewportWidth = static_cast(d->actualVisibleSize().width()) * oldScale / newScale; + double scaledViewportHeight = static_cast(d->actualVisibleSize().height()) * oldScale / newScale; + double dx = std::max(0.0, (scaledViewportWidth - newBlockWidth) / 2.0); + double dy = std::max(0.0, (scaledViewportHeight - newBlockHeight) / 2.0); + + RenderObject* renderer = d->m_currentBlockZoomAdjustedNode->renderer(); + FloatPoint anchor; + FloatPoint topLeftPoint(d->mapFromTransformed(blockRect).location()); + if (renderer && renderer->isText()) { + ETextAlign textAlign = renderer->style()->textAlign(); + switch (textAlign) { + case CENTER: + case WEBKIT_CENTER: + anchor = FloatPoint(nodeRect.x() + (nodeRect.width() - scaledViewportWidth) / 2, topLeftPoint.y()); + break; + case LEFT: + case WEBKIT_LEFT: + anchor = topLeftPoint; + break; + case RIGHT: + case WEBKIT_RIGHT: + anchor = FloatPoint(nodeRect.x() + nodeRect.width() - scaledViewportWidth, topLeftPoint.y()); + break; + case TAAUTO: + case JUSTIFY: + default: + if (renderer->style()->isLeftToRightDirection()) + anchor = topLeftPoint; + else + anchor = FloatPoint(nodeRect.x() + nodeRect.width() - scaledViewportWidth, topLeftPoint.y()); + break; + } + } else + anchor = renderer->style()->isLeftToRightDirection() ? topLeftPoint : FloatPoint(nodeRect.x() + nodeRect.width() - scaledViewportWidth, topLeftPoint.y()); + + if (newBlockHeight <= scaledViewportHeight) { + d->m_finalBlockPoint = FloatPoint(anchor.x() - dx, anchor.y() - dy); + } else { + d->m_finalBlockPoint = FloatPoint(anchor.x() - dx, anchor.y() - 3); + } + +#if ENABLE(VIEWPORT_REFLOW) + if (settings()->textReflowMode() != WebSettings::TextReflowDisabled) { + d->m_finalBlockPoint = FloatPoint(anchor.x() - dx, anchor.y() - 3); + d->m_finalBlockPointReflowOffset = FloatPoint(-dx, -3); + } +#endif + + FloatRect br(anchor, FloatSize(scaledViewportWidth, scaledViewportHeight)); + if (!br.contains(IntPoint(documentTargetPoint))) { + d->m_finalBlockPointReflowOffset.move(0, (documentTargetPoint.y() - scaledViewportHeight / 2) - d->m_finalBlockPoint.y()); + d->m_finalBlockPoint = FloatPoint(d->m_finalBlockPoint.x(), documentTargetPoint.y() - scaledViewportHeight / 2); + } + + if (d->m_finalBlockPoint.x() < 0) { + d->m_finalBlockPoint.setX(0); + d->m_finalBlockPointReflowOffset.setX(0); + } else if (d->m_finalBlockPoint.x() + scaledViewportWidth > d->contentsSize().width()) { + d->m_finalBlockPoint.setX(d->contentsSize().width() - scaledViewportWidth); + d->m_finalBlockPointReflowOffset.setX(0); + } + + if (d->m_finalBlockPoint.y() < 0) { + d->m_finalBlockPoint.setY(0); + d->m_finalBlockPointReflowOffset.setY(0); + } else if (d->m_finalBlockPoint.y() + scaledViewportHeight > d->contentsSize().height()) { + d->m_finalBlockPoint.setY(d->contentsSize().height() - scaledViewportHeight); + d->m_finalBlockPointReflowOffset.setY(0); + } + + if (!endOfBlockZoomMode && abs(newScale - oldScale) / oldScale < minimumExpandingRatio) { + const double minimumDisplacement = minimumExpandingRatio * webkitThreadViewportAccessor()->documentViewportSize().width(); + if (oldScale == d->minimumScale() || (distanceBetweenPoints(d->scrollPosition(), roundUntransformedPoint(d->m_finalBlockPoint)) < minimumDisplacement && abs(newScale - oldScale) / oldScale < 0.10)) { + if (isFirstZoom) { + d->resetBlockZoom(); + return false; + } + blockZoom(documentTargetPoint); + return true; + } + } + + d->m_blockZoomFinalScale = newScale; + + d->m_userPerformedManualZoom = true; + d->m_userPerformedManualScroll = true; + d->m_client->animateBlockZoom(d->m_blockZoomFinalScale, d->m_finalBlockPoint); + + return true; +} +",0,"bool WebPage::blockZoom(const Platform::IntPoint& documentTargetPoint) +{ + if (!d->m_mainFrame->view() || !d->isUserScalable()) + return false; + + Node* node = d->bestNodeForZoomUnderPoint(documentTargetPoint); + if (!node) + return false; + + IntRect nodeRect = d->rectForNode(node); + IntRect blockRect; + bool endOfBlockZoomMode = d->compareNodesForBlockZoom(d->m_currentBlockZoomAdjustedNode.get(), node); + const double oldScale = d->m_transformationMatrix->m11(); + double newScale = 0; + const double margin = endOfBlockZoomMode ? 0 : blockZoomMargin * 2 * oldScale; + bool isFirstZoom = false; + + if (endOfBlockZoomMode) { + IntRect rect = d->blockZoomRectForNode(node); + blockRect = IntRect(0, rect.y(), d->transformedContentsSize().width(), d->transformedContentsSize().height() - rect.y()); + d->m_shouldReflowBlock = false; + } else { + Node* tempBlockZoomAdjustedNode = d->m_currentBlockZoomAdjustedNode.get(); + blockRect = d->blockZoomRectForNode(node); + + if (!node->hasTagName(HTMLNames::imgTag)) { + IntRect tRect = d->mapFromTransformed(blockRect); + int blockArea = tRect.width() * tRect.height(); + int pageArea = d->contentsSize().width() * d->contentsSize().height(); + double blockToPageRatio = static_cast(pageArea - blockArea) / pageArea; + if (blockToPageRatio < minimumExpandingRatio) { + d->m_currentBlockZoomAdjustedNode = tempBlockZoomAdjustedNode; + return false; + } + } + + if (blockRect.isEmpty() || !blockRect.width() || !blockRect.height()) + return false; + + if (!d->m_currentBlockZoomNode.get()) + isFirstZoom = true; + + d->m_currentBlockZoomNode = node; + d->m_shouldReflowBlock = true; + } + + newScale = std::min(d->newScaleForBlockZoomRect(blockRect, oldScale, margin), d->maxBlockZoomScale()); + newScale = std::max(newScale, minimumScale()); + +#if ENABLE(VIEWPORT_REFLOW) + if (d->m_currentBlockZoomNode && d->m_shouldReflowBlock && settings()->textReflowMode() != WebSettings::TextReflowDisabled) { + RenderObject* renderer = d->m_currentBlockZoomNode->renderer(); + if (renderer && renderer->isText()) { + double newFontSize = renderer->style()->fontSize() * newScale; + if (newFontSize < d->m_webSettings->defaultFontSize()) { + newScale = std::min(static_cast(d->m_webSettings->defaultFontSize()) / renderer->style()->fontSize(), d->maxBlockZoomScale()); + newScale = std::max(newScale, minimumScale()); + } + blockRect.setWidth(oldScale * static_cast(d->transformedActualVisibleSize().width()) / newScale); + newScale = std::min(d->newScaleForBlockZoomRect(blockRect, oldScale, margin), d->maxBlockZoomScale()); + newScale = std::max(newScale, minimumScale()); // Still, it's not allowed to be smaller than minimum scale. + } + } +#endif + + double newBlockHeight = d->mapFromTransformed(blockRect).height(); + double newBlockWidth = d->mapFromTransformed(blockRect).width(); + double scaledViewportWidth = static_cast(d->actualVisibleSize().width()) * oldScale / newScale; + double scaledViewportHeight = static_cast(d->actualVisibleSize().height()) * oldScale / newScale; + double dx = std::max(0.0, (scaledViewportWidth - newBlockWidth) / 2.0); + double dy = std::max(0.0, (scaledViewportHeight - newBlockHeight) / 2.0); + + RenderObject* renderer = d->m_currentBlockZoomAdjustedNode->renderer(); + FloatPoint anchor; + FloatPoint topLeftPoint(d->mapFromTransformed(blockRect).location()); + if (renderer && renderer->isText()) { + ETextAlign textAlign = renderer->style()->textAlign(); + switch (textAlign) { + case CENTER: + case WEBKIT_CENTER: + anchor = FloatPoint(nodeRect.x() + (nodeRect.width() - scaledViewportWidth) / 2, topLeftPoint.y()); + break; + case LEFT: + case WEBKIT_LEFT: + anchor = topLeftPoint; + break; + case RIGHT: + case WEBKIT_RIGHT: + anchor = FloatPoint(nodeRect.x() + nodeRect.width() - scaledViewportWidth, topLeftPoint.y()); + break; + case TAAUTO: + case JUSTIFY: + default: + if (renderer->style()->isLeftToRightDirection()) + anchor = topLeftPoint; + else + anchor = FloatPoint(nodeRect.x() + nodeRect.width() - scaledViewportWidth, topLeftPoint.y()); + break; + } + } else + anchor = renderer->style()->isLeftToRightDirection() ? topLeftPoint : FloatPoint(nodeRect.x() + nodeRect.width() - scaledViewportWidth, topLeftPoint.y()); + + if (newBlockHeight <= scaledViewportHeight) { + d->m_finalBlockPoint = FloatPoint(anchor.x() - dx, anchor.y() - dy); + } else { + d->m_finalBlockPoint = FloatPoint(anchor.x() - dx, anchor.y() - 3); + } + +#if ENABLE(VIEWPORT_REFLOW) + if (settings()->textReflowMode() != WebSettings::TextReflowDisabled) { + d->m_finalBlockPoint = FloatPoint(anchor.x() - dx, anchor.y() - 3); + d->m_finalBlockPointReflowOffset = FloatPoint(-dx, -3); + } +#endif + + FloatRect br(anchor, FloatSize(scaledViewportWidth, scaledViewportHeight)); + if (!br.contains(IntPoint(documentTargetPoint))) { + d->m_finalBlockPointReflowOffset.move(0, (documentTargetPoint.y() - scaledViewportHeight / 2) - d->m_finalBlockPoint.y()); + d->m_finalBlockPoint = FloatPoint(d->m_finalBlockPoint.x(), documentTargetPoint.y() - scaledViewportHeight / 2); + } + + if (d->m_finalBlockPoint.x() < 0) { + d->m_finalBlockPoint.setX(0); + d->m_finalBlockPointReflowOffset.setX(0); + } else if (d->m_finalBlockPoint.x() + scaledViewportWidth > d->contentsSize().width()) { + d->m_finalBlockPoint.setX(d->contentsSize().width() - scaledViewportWidth); + d->m_finalBlockPointReflowOffset.setX(0); + } + + if (d->m_finalBlockPoint.y() < 0) { + d->m_finalBlockPoint.setY(0); + d->m_finalBlockPointReflowOffset.setY(0); + } else if (d->m_finalBlockPoint.y() + scaledViewportHeight > d->contentsSize().height()) { + d->m_finalBlockPoint.setY(d->contentsSize().height() - scaledViewportHeight); + d->m_finalBlockPointReflowOffset.setY(0); + } + + if (!endOfBlockZoomMode && abs(newScale - oldScale) / oldScale < minimumExpandingRatio) { + const double minimumDisplacement = minimumExpandingRatio * webkitThreadViewportAccessor()->documentViewportSize().width(); + if (oldScale == d->minimumScale() || (distanceBetweenPoints(d->scrollPosition(), roundUntransformedPoint(d->m_finalBlockPoint)) < minimumDisplacement && abs(newScale - oldScale) / oldScale < 0.10)) { + if (isFirstZoom) { + d->resetBlockZoom(); + return false; + } + blockZoom(documentTargetPoint); + return true; + } + } + + d->m_blockZoomFinalScale = newScale; + + d->m_userPerformedManualZoom = true; + d->m_userPerformedManualScroll = true; + d->m_client->animateBlockZoom(d->m_blockZoomFinalScale, d->m_finalBlockPoint); + + return true; +} +","@@ -4058,11 +4058,6 @@ bool WebPage::touchEvent(const Platform::TouchEvent& event) + return d->dispatchTouchEventToFullScreenPlugin(pluginView, event); + + Platform::TouchEvent tEvent = event; +- for (unsigned i = 0; i < event.m_points.size(); i++) { +- tEvent.m_points[i].m_pos = d->mapFromTransformed(tEvent.m_points[i].m_pos); +- tEvent.m_points[i].m_screenPos = tEvent.m_points[i].m_screenPos; +- } +- + if (event.isSingleTap()) + d->m_pluginMayOpenNewTab = true; + else if (tEvent.m_type == Platform::TouchEvent::TouchStart || tEvent.m_type == Platform::TouchEvent::TouchCancel) +@@ -4132,10 +4127,7 @@ void WebPage::touchPointAsMouseEvent(const Platform::TouchPoint& point, unsigned + + d->m_lastUserEventTimestamp = currentTime(); + +- Platform::TouchPoint tPoint = point; +- tPoint.m_pos = d->mapFromTransformed(tPoint.m_pos); +- +- d->m_touchEventHandler->handleTouchPoint(tPoint, modifiers); ++ d->m_touchEventHandler->handleTouchPoint(point, modifiers); + } + + void WebPage::playSoundIfAnchorIsTarget() const +@@ -4165,13 +4157,13 @@ bool WebPagePrivate::dispatchTouchEventToFullScreenPlugin(PluginView* plugin, co + if (npTouchEvent.size) { + npTouchEvent.points = new NPTouchPoint[npTouchEvent.size]; + for (int i = 0; i < npTouchEvent.size; i++) { +- npTouchEvent.points[i].touchId = event.m_points[i].m_id; +- npTouchEvent.points[i].clientX = event.m_points[i].m_screenPos.x(); +- npTouchEvent.points[i].clientY = event.m_points[i].m_screenPos.y(); +- npTouchEvent.points[i].screenX = event.m_points[i].m_screenPos.x(); +- npTouchEvent.points[i].screenY = event.m_points[i].m_screenPos.y(); +- npTouchEvent.points[i].pageX = event.m_points[i].m_pos.x(); +- npTouchEvent.points[i].pageY = event.m_points[i].m_pos.y(); ++ npTouchEvent.points[i].touchId = event.m_points[i].id(); ++ npTouchEvent.points[i].clientX = event.m_points[i].screenPosition().x(); ++ npTouchEvent.points[i].clientY = event.m_points[i].screenPosition().y(); ++ npTouchEvent.points[i].screenX = event.m_points[i].screenPosition().x(); ++ npTouchEvent.points[i].screenY = event.m_points[i].screenPosition().y(); ++ npTouchEvent.points[i].pageX = event.m_points[i].pixelViewportPosition().x(); ++ npTouchEvent.points[i].pageY = event.m_points[i].pixelViewportPosition().y(); + } + } + +@@ -4193,7 +4185,7 @@ bool WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin(PluginView + NPEvent npEvent; + NPMouseEvent mouse; + +- switch (point.m_state) { ++ switch (point.state()) { + case Platform::TouchPoint::TouchPressed: + mouse.type = MOUSE_BUTTON_DOWN; + break; +@@ -4207,8 +4199,8 @@ bool WebPagePrivate::dispatchTouchPointAsMouseEventToFullScreenPlugin(PluginView + return true; + } + +- mouse.x = point.m_screenPos.x(); +- mouse.y = point.m_screenPos.y(); ++ mouse.x = point.screenPosition().x(); ++ mouse.y = point.screenPosition().y(); + mouse.button = mouse.type != MOUSE_BUTTON_UP; + mouse.flags = 0; + npEvent.type = NP_MouseEvent;",1799,2130,4096 +15911,"void GLES2DecoderImpl::DoCopyTexImage2D( + GLenum target, + GLint level, + GLenum internal_format, + GLint x, + GLint y, + GLsizei width, + GLsizei height, + GLint border) { + const char* func_name = ""glCopyTexImage2D""; + DCHECK(!ShouldDeferReads()); + TextureRef* texture_ref = texture_manager()->GetTextureInfoForTarget( + &state_, target); + if (!texture_ref) { + LOCAL_SET_GL_ERROR( + GL_INVALID_OPERATION, func_name, ""unknown texture for target""); + return; + } + Texture* texture = texture_ref->texture(); + if (texture->IsImmutable()) { + LOCAL_SET_GL_ERROR( + GL_INVALID_OPERATION, func_name, ""texture is immutable""); + return; + } + if (!texture_manager()->ValidForTarget(target, level, width, height, 1) || + border != 0) { + LOCAL_SET_GL_ERROR( + GL_INVALID_VALUE, func_name, ""dimensions out of range""); + return; + } + + if (!CheckBoundReadFramebufferValid(func_name, + GL_INVALID_FRAMEBUFFER_OPERATION)) { + return; + } + + GLenum read_format = GetBoundReadFramebufferInternalFormat(); + GLenum read_type = GetBoundReadFramebufferTextureType(); + if (!ValidateCopyTexFormat(func_name, internal_format, + read_format, read_type)) { + return; + } + + uint32_t pixels_size = 0; + GLenum format = + TextureManager::ExtractFormatFromStorageFormat(internal_format); + GLenum type = TextureManager::ExtractTypeFromStorageFormat(internal_format); + bool internal_format_unsized = internal_format == format; + if (internal_format_unsized && feature_info_->IsWebGL2OrES3Context()) { + DCHECK(type == GL_UNSIGNED_BYTE); + switch (internal_format) { + case GL_RGB: + case GL_RGBA: + case GL_LUMINANCE_ALPHA: + case GL_LUMINANCE: + case GL_ALPHA: + case GL_BGRA_EXT: + break; + default: + format = GL_NONE; + break; + } + } + if (!format || !type) { + LOCAL_SET_GL_ERROR( + GL_INVALID_OPERATION, + func_name, ""Invalid unsized internal format.""); + return; + } + + DCHECK(texture_manager()->ValidateTextureParameters( + GetErrorState(), func_name, true, format, type, internal_format, level)); + + if (!GLES2Util::ComputeImageDataSizes(width, height, 1, format, type, + state_.unpack_alignment, &pixels_size, + nullptr, nullptr)) { + LOCAL_SET_GL_ERROR(GL_OUT_OF_MEMORY, func_name, ""dimensions too large""); + return; + } + + if (FormsTextureCopyingFeedbackLoop(texture_ref, level, 0)) { + LOCAL_SET_GL_ERROR( + GL_INVALID_OPERATION, + func_name, ""source and destination textures are the same""); + return; + } + + LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER(func_name); + ScopedResolvedFramebufferBinder binder(this, false, true); + gfx::Size size = GetBoundReadFramebufferSize(); + + if (texture->IsAttachedToFramebuffer()) { + framebuffer_state_.clear_state_dirty = true; + } + + bool requires_luma_blit = + CopyTexImageResourceManager::CopyTexImageRequiresBlit(feature_info_.get(), + format); + if (requires_luma_blit && + !InitializeCopyTexImageBlitter(func_name)) { + return; + } + + bool reset_source_texture_base_level_max_level = false; + GLint attached_texture_level = -1; + Framebuffer* framebuffer = GetBoundReadFramebuffer(); + if (framebuffer) { + const Framebuffer::Attachment* attachment = + framebuffer->GetReadBufferAttachment(); + if (attachment->IsTexture(texture_ref)) { + DCHECK(attachment->IsTextureAttachment()); + attached_texture_level = attachment->level(); + DCHECK_GE(attached_texture_level, 0); + if (attached_texture_level != texture->base_level()) + reset_source_texture_base_level_max_level = true; + } + } + if (reset_source_texture_base_level_max_level) { + api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, + attached_texture_level); + api()->glTexParameteriFn(target, GL_TEXTURE_MAX_LEVEL, + attached_texture_level); + } + + gfx::Rect src(x, y, width, height); + const gfx::Rect dst(0, 0, size.width(), size.height()); + src.Intersect(dst); + + GLenum final_internal_format = TextureManager::AdjustTexInternalFormat( + feature_info_.get(), internal_format); + if (workarounds().force_int_or_srgb_cube_texture_complete && + texture->target() == GL_TEXTURE_CUBE_MAP && + (GLES2Util::IsIntegerFormat(final_internal_format) || + GLES2Util::GetColorEncodingFromInternalFormat(final_internal_format) == + GL_SRGB)) { + TextureManager::DoTexImageArguments args = { + target, + level, + final_internal_format, + width, + height, + 1, + border, + format, + type, + nullptr, + pixels_size, + 0, + TextureManager::DoTexImageArguments::kTexImage2D}; + texture_manager()->WorkaroundCopyTexImageCubeMap( + &texture_state_, &state_, &framebuffer_state_, texture_ref, func_name, + args); + } + + if (src.x() != x || src.y() != y || + src.width() != width || src.height() != height || + final_internal_format == GL_BGRA_EXT) { + { + + std::unique_ptr zero(new char[pixels_size]); + memset(zero.get(), 0, pixels_size); + ScopedPixelUnpackState reset_restore(&state_); + api()->glTexImage2DFn(target, level, final_internal_format, width, height, + border, format, type, zero.get()); + } + + if (!src.IsEmpty()) { + GLint destX = src.x() - x; + GLint destY = src.y() - y; + if (requires_luma_blit) { + copy_tex_image_blit_->DoCopyTexSubImageToLUMACompatibilityTexture( + this, texture->service_id(), texture->target(), target, format, + type, level, destX, destY, 0, + src.x(), src.y(), src.width(), src.height(), + GetBoundReadFramebufferServiceId(), + GetBoundReadFramebufferInternalFormat()); + } else { + api()->glCopyTexSubImage2DFn(target, level, destX, destY, src.x(), + src.y(), src.width(), src.height()); + } + } + } else { + if (workarounds().init_two_cube_map_levels_before_copyteximage && + texture->target() == GL_TEXTURE_CUBE_MAP && + target != GL_TEXTURE_CUBE_MAP_POSITIVE_X) { + for (int i = 0; i < 2; ++i) { + TextureManager::DoTexImageArguments args = { + target, i, final_internal_format, width, height, 1, border, + format, type, nullptr, pixels_size, 0, + TextureManager::DoTexImageArguments::kTexImage2D }; + texture_manager()->WorkaroundCopyTexImageCubeMap(&texture_state_, + &state_, &framebuffer_state_, texture_ref, func_name, args); + } + } + + GLuint source_texture_service_id = 0; + GLenum source_texture_target = 0; + uint32_t channels_exist = GLES2Util::GetChannelsForFormat(read_format); + bool use_workaround = NeedsCopyTextureImageWorkaround( + final_internal_format, channels_exist, &source_texture_service_id, + &source_texture_target); + if (requires_luma_blit) { + copy_tex_image_blit_->DoCopyTexImage2DToLUMACompatibilityTexture( + this, texture->service_id(), texture->target(), target, format, + type, level, internal_format, x, y, width, height, + GetBoundReadFramebufferServiceId(), + GetBoundReadFramebufferInternalFormat()); + } else if (use_workaround) { + GLenum dest_texture_target = target; + GLenum framebuffer_target = GetReadFramebufferTarget(); + + GLenum temp_internal_format = 0; + if (channels_exist == GLES2Util::kRGBA) { + temp_internal_format = GL_RGBA; + } else if (channels_exist == GLES2Util::kRGB) { + temp_internal_format = GL_RGB; + } else { + NOTREACHED(); + } + + if (workarounds().clear_pixel_unpack_buffer_before_copyteximage) + state_.PushTextureUnpackState(); + GLuint temp_texture; + { + api()->glGenTexturesFn(1, &temp_texture); + ScopedTextureBinder binder(&state_, temp_texture, + source_texture_target); + api()->glCopyTexImage2DFn(source_texture_target, 0, + temp_internal_format, x, y, width, height, + border); + + api()->glFramebufferTexture2DEXTFn( + framebuffer_target, GL_COLOR_ATTACHMENT0, source_texture_target, + temp_texture, 0); + } + + DCHECK_EQ(static_cast(GL_TEXTURE_2D), dest_texture_target); + api()->glCopyTexImage2DFn(dest_texture_target, level, + final_internal_format, 0, 0, width, height, 0); + + api()->glFramebufferTexture2DEXTFn( + framebuffer_target, GL_COLOR_ATTACHMENT0, source_texture_target, + source_texture_service_id, 0); + if (workarounds().clear_pixel_unpack_buffer_before_copyteximage) + state_.RestoreUnpackState(); + + api()->glDeleteTexturesFn(1, &temp_texture); + } else { + if (workarounds().init_one_cube_map_level_before_copyteximage && + texture->target() == GL_TEXTURE_CUBE_MAP && + target != GL_TEXTURE_CUBE_MAP_POSITIVE_X) { + TextureManager::DoTexImageArguments args = { + target, level, final_internal_format, width, height, 1, border, + format, type, nullptr, pixels_size, 0, + TextureManager::DoTexImageArguments::kTexImage2D }; + texture_manager()->WorkaroundCopyTexImageCubeMap(&texture_state_, + &state_, &framebuffer_state_, texture_ref, func_name, args); + } + if (workarounds().clear_pixel_unpack_buffer_before_copyteximage) + state_.PushTextureUnpackState(); + api()->glCopyTexImage2DFn(target, level, final_internal_format, x, y, + width, height, border); + if (workarounds().clear_pixel_unpack_buffer_before_copyteximage) + state_.RestoreUnpackState(); + } + } + if (reset_source_texture_base_level_max_level) { + api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, + texture->base_level()); + api()->glTexParameteriFn(target, GL_TEXTURE_MAX_LEVEL, + texture->max_level()); + } + GLenum error = LOCAL_PEEK_GL_ERROR(func_name); + if (error == GL_NO_ERROR) { + texture_manager()->SetLevelInfo(texture_ref, target, level, internal_format, + width, height, 1, border, format, + type, gfx::Rect(width, height)); + texture->ApplyFormatWorkarounds(feature_info_.get()); + } + + ExitCommandProcessingEarly(); +} +",0,"void GLES2DecoderImpl::DoCopyTexImage2D( + GLenum target, + GLint level, + GLenum internal_format, + GLint x, + GLint y, + GLsizei width, + GLsizei height, + GLint border) { + const char* func_name = ""glCopyTexImage2D""; + DCHECK(!ShouldDeferReads()); + TextureRef* texture_ref = texture_manager()->GetTextureInfoForTarget( + &state_, target); + if (!texture_ref) { + LOCAL_SET_GL_ERROR( + GL_INVALID_OPERATION, func_name, ""unknown texture for target""); + return; + } + Texture* texture = texture_ref->texture(); + if (texture->IsImmutable()) { + LOCAL_SET_GL_ERROR( + GL_INVALID_OPERATION, func_name, ""texture is immutable""); + return; + } + if (!texture_manager()->ValidForTarget(target, level, width, height, 1) || + border != 0) { + LOCAL_SET_GL_ERROR( + GL_INVALID_VALUE, func_name, ""dimensions out of range""); + return; + } + + if (!CheckBoundReadFramebufferValid(func_name, + GL_INVALID_FRAMEBUFFER_OPERATION)) { + return; + } + + GLenum read_format = GetBoundReadFramebufferInternalFormat(); + GLenum read_type = GetBoundReadFramebufferTextureType(); + if (!ValidateCopyTexFormat(func_name, internal_format, + read_format, read_type)) { + return; + } + + uint32_t pixels_size = 0; + GLenum format = + TextureManager::ExtractFormatFromStorageFormat(internal_format); + GLenum type = TextureManager::ExtractTypeFromStorageFormat(internal_format); + bool internal_format_unsized = internal_format == format; + if (internal_format_unsized && feature_info_->IsWebGL2OrES3Context()) { + DCHECK(type == GL_UNSIGNED_BYTE); + switch (internal_format) { + case GL_RGB: + case GL_RGBA: + case GL_LUMINANCE_ALPHA: + case GL_LUMINANCE: + case GL_ALPHA: + case GL_BGRA_EXT: + break; + default: + format = GL_NONE; + break; + } + } + if (!format || !type) { + LOCAL_SET_GL_ERROR( + GL_INVALID_OPERATION, + func_name, ""Invalid unsized internal format.""); + return; + } + + DCHECK(texture_manager()->ValidateTextureParameters( + GetErrorState(), func_name, true, format, type, internal_format, level)); + + if (!GLES2Util::ComputeImageDataSizes(width, height, 1, format, type, + state_.unpack_alignment, &pixels_size, + nullptr, nullptr)) { + LOCAL_SET_GL_ERROR(GL_OUT_OF_MEMORY, func_name, ""dimensions too large""); + return; + } + + if (FormsTextureCopyingFeedbackLoop(texture_ref, level, 0)) { + LOCAL_SET_GL_ERROR( + GL_INVALID_OPERATION, + func_name, ""source and destination textures are the same""); + return; + } + + LOCAL_COPY_REAL_GL_ERRORS_TO_WRAPPER(func_name); + ScopedResolvedFramebufferBinder binder(this, false, true); + gfx::Size size = GetBoundReadFramebufferSize(); + + if (texture->IsAttachedToFramebuffer()) { + framebuffer_state_.clear_state_dirty = true; + } + + bool requires_luma_blit = + CopyTexImageResourceManager::CopyTexImageRequiresBlit(feature_info_.get(), + format); + if (requires_luma_blit && + !InitializeCopyTexImageBlitter(func_name)) { + return; + } + + bool reset_source_texture_base_level_max_level = false; + GLint attached_texture_level = -1; + Framebuffer* framebuffer = GetBoundReadFramebuffer(); + if (framebuffer) { + const Framebuffer::Attachment* attachment = + framebuffer->GetReadBufferAttachment(); + if (attachment->IsTexture(texture_ref)) { + DCHECK(attachment->IsTextureAttachment()); + attached_texture_level = attachment->level(); + DCHECK_GE(attached_texture_level, 0); + if (attached_texture_level != texture->base_level()) + reset_source_texture_base_level_max_level = true; + } + } + if (reset_source_texture_base_level_max_level) { + api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, + attached_texture_level); + api()->glTexParameteriFn(target, GL_TEXTURE_MAX_LEVEL, + attached_texture_level); + } + + gfx::Rect src(x, y, width, height); + const gfx::Rect dst(0, 0, size.width(), size.height()); + src.Intersect(dst); + + GLenum final_internal_format = TextureManager::AdjustTexInternalFormat( + feature_info_.get(), internal_format); + if (workarounds().force_int_or_srgb_cube_texture_complete && + texture->target() == GL_TEXTURE_CUBE_MAP && + (GLES2Util::IsIntegerFormat(final_internal_format) || + GLES2Util::GetColorEncodingFromInternalFormat(final_internal_format) == + GL_SRGB)) { + TextureManager::DoTexImageArguments args = { + target, + level, + final_internal_format, + width, + height, + 1, + border, + format, + type, + nullptr, + pixels_size, + 0, + TextureManager::DoTexImageArguments::kTexImage2D}; + texture_manager()->WorkaroundCopyTexImageCubeMap( + &texture_state_, &state_, &framebuffer_state_, texture_ref, func_name, + args); + } + + if (src.x() != x || src.y() != y || + src.width() != width || src.height() != height || + final_internal_format == GL_BGRA_EXT) { + { + + std::unique_ptr zero(new char[pixels_size]); + memset(zero.get(), 0, pixels_size); + ScopedPixelUnpackState reset_restore(&state_); + api()->glTexImage2DFn(target, level, final_internal_format, width, height, + border, format, type, zero.get()); + } + + if (!src.IsEmpty()) { + GLint destX = src.x() - x; + GLint destY = src.y() - y; + if (requires_luma_blit) { + copy_tex_image_blit_->DoCopyTexSubImageToLUMACompatibilityTexture( + this, texture->service_id(), texture->target(), target, format, + type, level, destX, destY, 0, + src.x(), src.y(), src.width(), src.height(), + GetBoundReadFramebufferServiceId(), + GetBoundReadFramebufferInternalFormat()); + } else { + api()->glCopyTexSubImage2DFn(target, level, destX, destY, src.x(), + src.y(), src.width(), src.height()); + } + } + } else { + if (workarounds().init_two_cube_map_levels_before_copyteximage && + texture->target() == GL_TEXTURE_CUBE_MAP && + target != GL_TEXTURE_CUBE_MAP_POSITIVE_X) { + for (int i = 0; i < 2; ++i) { + TextureManager::DoTexImageArguments args = { + target, i, final_internal_format, width, height, 1, border, + format, type, nullptr, pixels_size, 0, + TextureManager::DoTexImageArguments::kTexImage2D }; + texture_manager()->WorkaroundCopyTexImageCubeMap(&texture_state_, + &state_, &framebuffer_state_, texture_ref, func_name, args); + } + } + + GLuint source_texture_service_id = 0; + GLenum source_texture_target = 0; + uint32_t channels_exist = GLES2Util::GetChannelsForFormat(read_format); + bool use_workaround = NeedsCopyTextureImageWorkaround( + final_internal_format, channels_exist, &source_texture_service_id, + &source_texture_target); + if (requires_luma_blit) { + copy_tex_image_blit_->DoCopyTexImage2DToLUMACompatibilityTexture( + this, texture->service_id(), texture->target(), target, format, + type, level, internal_format, x, y, width, height, + GetBoundReadFramebufferServiceId(), + GetBoundReadFramebufferInternalFormat()); + } else if (use_workaround) { + GLenum dest_texture_target = target; + GLenum framebuffer_target = GetReadFramebufferTarget(); + + GLenum temp_internal_format = 0; + if (channels_exist == GLES2Util::kRGBA) { + temp_internal_format = GL_RGBA; + } else if (channels_exist == GLES2Util::kRGB) { + temp_internal_format = GL_RGB; + } else { + NOTREACHED(); + } + + if (workarounds().clear_pixel_unpack_buffer_before_copyteximage) + state_.PushTextureUnpackState(); + GLuint temp_texture; + { + api()->glGenTexturesFn(1, &temp_texture); + ScopedTextureBinder binder(&state_, temp_texture, + source_texture_target); + api()->glCopyTexImage2DFn(source_texture_target, 0, + temp_internal_format, x, y, width, height, + border); + + api()->glFramebufferTexture2DEXTFn( + framebuffer_target, GL_COLOR_ATTACHMENT0, source_texture_target, + temp_texture, 0); + } + + DCHECK_EQ(static_cast(GL_TEXTURE_2D), dest_texture_target); + api()->glCopyTexImage2DFn(dest_texture_target, level, + final_internal_format, 0, 0, width, height, 0); + + api()->glFramebufferTexture2DEXTFn( + framebuffer_target, GL_COLOR_ATTACHMENT0, source_texture_target, + source_texture_service_id, 0); + if (workarounds().clear_pixel_unpack_buffer_before_copyteximage) + state_.RestoreUnpackState(); + + api()->glDeleteTexturesFn(1, &temp_texture); + } else { + if (workarounds().init_one_cube_map_level_before_copyteximage && + texture->target() == GL_TEXTURE_CUBE_MAP && + target != GL_TEXTURE_CUBE_MAP_POSITIVE_X) { + TextureManager::DoTexImageArguments args = { + target, level, final_internal_format, width, height, 1, border, + format, type, nullptr, pixels_size, 0, + TextureManager::DoTexImageArguments::kTexImage2D }; + texture_manager()->WorkaroundCopyTexImageCubeMap(&texture_state_, + &state_, &framebuffer_state_, texture_ref, func_name, args); + } + if (workarounds().clear_pixel_unpack_buffer_before_copyteximage) + state_.PushTextureUnpackState(); + api()->glCopyTexImage2DFn(target, level, final_internal_format, x, y, + width, height, border); + if (workarounds().clear_pixel_unpack_buffer_before_copyteximage) + state_.RestoreUnpackState(); + } + } + if (reset_source_texture_base_level_max_level) { + api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, + texture->base_level()); + api()->glTexParameteriFn(target, GL_TEXTURE_MAX_LEVEL, + texture->max_level()); + } + GLenum error = LOCAL_PEEK_GL_ERROR(func_name); + if (error == GL_NO_ERROR) { + texture_manager()->SetLevelInfo(texture_ref, target, level, internal_format, + width, height, 1, border, format, + type, gfx::Rect(width, height)); + texture->ApplyFormatWorkarounds(feature_info_.get()); + } + + ExitCommandProcessingEarly(); +} +","@@ -11384,29 +11384,24 @@ void GLES2DecoderImpl::GetTexParameterImpl( + return; + } + break; +- // Get the level information from the texture to avoid a Mac driver +- // bug where they store the levels in int16_t, making values bigger +- // than 2^15-1 overflow in the negative range. + case GL_TEXTURE_BASE_LEVEL: +- if (workarounds().use_shadowed_tex_level_params) { +- if (fparams) { +- fparams[0] = static_cast(texture->base_level()); +- } else { +- iparams[0] = texture->base_level(); +- } +- return; ++ // Use shadowed value in case it's clamped; also because older MacOSX ++ // stores the value on int16_t (see https://crbug.com/610153). ++ if (fparams) { ++ fparams[0] = static_cast(texture->unclamped_base_level()); ++ } else { ++ iparams[0] = texture->unclamped_base_level(); + } +- break; ++ return; + case GL_TEXTURE_MAX_LEVEL: +- if (workarounds().use_shadowed_tex_level_params) { +- if (fparams) { +- fparams[0] = static_cast(texture->max_level()); +- } else { +- iparams[0] = texture->max_level(); +- } +- return; ++ // Use shadowed value in case it's clamped; also because older MacOSX ++ // stores the value on int16_t (see https://crbug.com/610153). ++ if (fparams) { ++ fparams[0] = static_cast(texture->unclamped_max_level()); ++ } else { ++ iparams[0] = texture->unclamped_max_level(); + } +- break; ++ return; + case GL_TEXTURE_SWIZZLE_R: + if (fparams) { + fparams[0] = static_cast(texture->swizzle_r()); +@@ -17573,25 +17568,6 @@ void GLES2DecoderImpl::TexStorageImpl(GLenum target, + compatibility_internal_format = format_info->decompressed_internal_format; + } + +- if (workarounds().reset_base_mipmap_level_before_texstorage && +- texture->base_level() > 0) +- api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, 0); +- +- // TODO(zmo): We might need to emulate TexStorage using TexImage or +- // CompressedTexImage on Mac OSX where we expose ES3 APIs when the underlying +- // driver is lower than 4.2 and ARB_texture_storage extension doesn't exist. +- if (dimension == ContextState::k2D) { +- api()->glTexStorage2DEXTFn(target, levels, compatibility_internal_format, +- width, height); +- } else { +- api()->glTexStorage3DFn(target, levels, compatibility_internal_format, +- width, height, depth); +- } +- if (workarounds().reset_base_mipmap_level_before_texstorage && +- texture->base_level() > 0) +- api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, +- texture->base_level()); +- + { + GLsizei level_width = width; + GLsizei level_height = height; +@@ -17620,6 +17596,29 @@ void GLES2DecoderImpl::TexStorageImpl(GLenum target, + texture->ApplyFormatWorkarounds(feature_info_.get()); + texture->SetImmutable(true); + } ++ ++ if (workarounds().reset_base_mipmap_level_before_texstorage && ++ texture->base_level() > 0) ++ api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, 0); ++ ++ // TODO(zmo): We might need to emulate TexStorage using TexImage or ++ // CompressedTexImage on Mac OSX where we expose ES3 APIs when the underlying ++ // driver is lower than 4.2 and ARB_texture_storage extension doesn't exist. ++ if (dimension == ContextState::k2D) { ++ api()->glTexStorage2DEXTFn(target, levels, compatibility_internal_format, ++ width, height); ++ } else { ++ api()->glTexStorage3DFn(target, levels, compatibility_internal_format, ++ width, height, depth); ++ } ++ if (workarounds().reset_base_mipmap_level_before_texstorage && ++ texture->base_level() > 0) { ++ // Note base_level is already clamped due to texture->SetImmutable(true). ++ // This is necessary for certain NVidia Linux drivers; otherwise they ++ // may trigger segmentation fault. See https://crbug.com/877874. ++ api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, ++ texture->base_level()); ++ } + } + + void GLES2DecoderImpl::DoTexStorage2DEXT(GLenum target,",2377,2708,4096 +10,"PHPAPI char *php_pcre_replace_impl(pcre_cache_entry *pce, char *subject, int subject_len, zval *replace_val, + int is_callable_replace, int *result_len, int limit, int *replace_count TSRMLS_DC) +{ + pcre_extra *extra = pce->extra;/* Holds results of studying */ + pcre_extra extra_data; /* Used locally for exec options */ + int exoptions = 0; /* Execution options */ + int count = 0; /* Count of matched subpatterns */ + int *offsets; /* Array of subpattern offsets */ + char **subpat_names; /* Array for named subpatterns */ + int num_subpats; /* Number of captured subpatterns */ + int size_offsets; /* Size of the offsets array */ + int new_len; /* Length of needed storage */ + int alloc_len; /* Actual allocated length */ + int eval_result_len=0; /* Length of the eval'ed or + function-returned string */ + int match_len; /* Length of the current match */ + int backref; /* Backreference number */ + int eval; /* If the replacement string should be eval'ed */ + int start_offset; /* Where the new search starts */ + int g_notempty=0; /* If the match should not be empty */ + int replace_len=0; /* Length of replacement string */ + char *result, /* Result of replacement */ + *replace=NULL, /* Replacement string */ + *new_buf, /* Temporary buffer for re-allocation */ + *walkbuf, /* Location of current replacement in the result */ + *walk, /* Used to walk the replacement string */ + *match, /* The current match */ + *piece, /* The current piece of subject */ + *replace_end=NULL, /* End of replacement string */ + *eval_result, /* Result of eval or custom function */ + walk_last; /* Last walked character */ + int rc; + + if (extra == NULL) { + extra_data.flags = PCRE_EXTRA_MATCH_LIMIT | PCRE_EXTRA_MATCH_LIMIT_RECURSION; + extra = &extra_data; + } + extra->match_limit = PCRE_G(backtrack_limit); + extra->match_limit_recursion = PCRE_G(recursion_limit); + + eval = pce->preg_options & PREG_REPLACE_EVAL; + if (is_callable_replace) { + if (eval) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Modifier /e cannot be used with replacement callback""); + return NULL; + } + } else { + replace = Z_STRVAL_P(replace_val); + replace_len = Z_STRLEN_P(replace_val); + replace_end = replace + replace_len; + } + + /* Calculate the size of the offsets array, and allocate memory for it. */ + rc = pcre_fullinfo(pce->re, extra, PCRE_INFO_CAPTURECOUNT, &num_subpats); + if (rc < 0) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Internal pcre_fullinfo() error %d"", rc); + return NULL; + } + num_subpats++; + size_offsets = num_subpats * 3; + + /* + * Build a mapping from subpattern numbers to their names. We will always + * allocate the table, even though there may be no named subpatterns. This + * avoids somewhat more complicated logic in the inner loops. + */ + subpat_names = make_subpats_table(num_subpats, pce TSRMLS_CC); + if (!subpat_names) { + return NULL; + } + + offsets = (int *)safe_emalloc(size_offsets, sizeof(int), 0); + + alloc_len = 2 * subject_len + 1; + result = safe_emalloc(alloc_len, sizeof(char), 0); + + /* Initialize */ + match = NULL; + *result_len = 0; + start_offset = 0; + PCRE_G(error_code) = PHP_PCRE_NO_ERROR; + + while (1) { + /* Execute the regular expression. */ + count = pcre_exec(pce->re, extra, subject, subject_len, start_offset, + exoptions|g_notempty, offsets, size_offsets); + + /* the string was already proved to be valid UTF-8 */ + exoptions |= PCRE_NO_UTF8_CHECK; + + /* Check for too many substrings condition. */ + if (count == 0) { + php_error_docref(NULL TSRMLS_CC,E_NOTICE, ""Matched, but too many substrings""); + count = size_offsets/3; + } + + piece = subject + start_offset; + + if (count > 0 && (limit == -1 || limit > 0)) { + if (replace_count) { + ++*replace_count; + } + /* Set the match location in subject */ + match = subject + offsets[0]; + + new_len = *result_len + offsets[0] - start_offset; /* part before the match */ + + /* If evaluating, do it and add the return string's length */ + if (eval) { + eval_result_len = preg_do_eval(replace, replace_len, subject, + offsets, count, &eval_result TSRMLS_CC); + new_len += eval_result_len; + } else if (is_callable_replace) { + /* Use custom function to get replacement string and its length. */ + eval_result_len = preg_do_repl_func(replace_val, subject, offsets, subpat_names, count, &eval_result TSRMLS_CC); + new_len += eval_result_len; + } else { /* do regular substitution */ + walk = replace; + walk_last = 0; + while (walk < replace_end) { + if ('\\' == *walk || '$' == *walk) { + if (walk_last == '\\') { + walk++; + walk_last = 0; + continue; + } + if (preg_get_backref(&walk, &backref)) { + if (backref < count) + new_len += offsets[(backref<<1)+1] - offsets[backref<<1]; + continue; + } + } + new_len++; + walk++; + walk_last = walk[-1]; + } + } + + if (new_len + 1 > alloc_len) { + alloc_len = 1 + alloc_len + 2 * new_len; + new_buf = emalloc(alloc_len); + memcpy(new_buf, result, *result_len); + efree(result); + result = new_buf; + } + /* copy the part of the string before the match */ + memcpy(&result[*result_len], piece, match-piece); + *result_len += match-piece; + + /* copy replacement and backrefs */ + walkbuf = result + *result_len; + + /* If evaluating or using custom function, copy result to the buffer + * and clean up. */ + if (eval || is_callable_replace) { + memcpy(walkbuf, eval_result, eval_result_len); + *result_len += eval_result_len; + STR_FREE(eval_result); + } else { /* do regular backreference copying */ + walk = replace; + walk_last = 0; + while (walk < replace_end) { + if ('\\' == *walk || '$' == *walk) { + if (walk_last == '\\') { + *(walkbuf-1) = *walk++; + walk_last = 0; + continue; + } + if (preg_get_backref(&walk, &backref)) { + if (backref < count) { + match_len = offsets[(backref<<1)+1] - offsets[backref<<1]; + memcpy(walkbuf, subject + offsets[backref<<1], match_len); + walkbuf += match_len; + } + continue; + } + } + *walkbuf++ = *walk++; + walk_last = walk[-1]; + } + *walkbuf = '\0'; + /* increment the result length by how much we've added to the string */ + *result_len += walkbuf - (result + *result_len); + } + + if (limit != -1) + limit--; + + } else if (count == PCRE_ERROR_NOMATCH || limit == 0) { + /* If we previously set PCRE_NOTEMPTY after a null match, + this is not necessarily the end. We need to advance + the start offset, and continue. Fudge the offset values + to achieve this, unless we're already at the end of the string. */ + if (g_notempty != 0 && start_offset < subject_len) { + offsets[0] = start_offset; + offsets[1] = start_offset + 1; + memcpy(&result[*result_len], piece, 1); + (*result_len)++; + } else { + new_len = *result_len + subject_len - start_offset; + if (new_len + 1 > alloc_len) { + alloc_len = new_len + 1; /* now we know exactly how long it is */ + new_buf = safe_emalloc(alloc_len, sizeof(char), 0); + memcpy(new_buf, result, *result_len); + efree(result); + result = new_buf; + } + /* stick that last bit of string on our output */ + memcpy(&result[*result_len], piece, subject_len - start_offset); + *result_len += subject_len - start_offset; + result[*result_len] = '\0'; + break; + } + } else { + pcre_handle_exec_error(count TSRMLS_CC); + efree(result); + result = NULL; + break; + } + + /* If we have matched an empty string, mimic what Perl's /g options does. + This turns out to be rather cunning. First we set PCRE_NOTEMPTY and try + the match again at the same point. If this fails (picked up above) we + advance to the next character. */ + g_notempty = (offsets[1] == offsets[0])? PCRE_NOTEMPTY | PCRE_ANCHORED : 0; + + /* Advance to the next piece. */ + start_offset = offsets[1]; + } + + efree(offsets); + efree(subpat_names); + + return result; +} +",0,"PHPAPI char *php_pcre_replace_impl(pcre_cache_entry *pce, char *subject, int subject_len, zval *replace_val, + int is_callable_replace, int *result_len, int limit, int *replace_count TSRMLS_DC) +{ + pcre_extra *extra = pce->extra;/* Holds results of studying */ + pcre_extra extra_data; /* Used locally for exec options */ + int exoptions = 0; /* Execution options */ + int count = 0; /* Count of matched subpatterns */ + int *offsets; /* Array of subpattern offsets */ + char **subpat_names; /* Array for named subpatterns */ + int num_subpats; /* Number of captured subpatterns */ + int size_offsets; /* Size of the offsets array */ + int new_len; /* Length of needed storage */ + int alloc_len; /* Actual allocated length */ + int eval_result_len=0; /* Length of the eval'ed or + function-returned string */ + int match_len; /* Length of the current match */ + int backref; /* Backreference number */ + int eval; /* If the replacement string should be eval'ed */ + int start_offset; /* Where the new search starts */ + int g_notempty=0; /* If the match should not be empty */ + int replace_len=0; /* Length of replacement string */ + char *result, /* Result of replacement */ + *replace=NULL, /* Replacement string */ + *new_buf, /* Temporary buffer for re-allocation */ + *walkbuf, /* Location of current replacement in the result */ + *walk, /* Used to walk the replacement string */ + *match, /* The current match */ + *piece, /* The current piece of subject */ + *replace_end=NULL, /* End of replacement string */ + *eval_result, /* Result of eval or custom function */ + walk_last; /* Last walked character */ + int rc; + + if (extra == NULL) { + extra_data.flags = PCRE_EXTRA_MATCH_LIMIT | PCRE_EXTRA_MATCH_LIMIT_RECURSION; + extra = &extra_data; + } + extra->match_limit = PCRE_G(backtrack_limit); + extra->match_limit_recursion = PCRE_G(recursion_limit); + + eval = pce->preg_options & PREG_REPLACE_EVAL; + if (is_callable_replace) { + if (eval) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Modifier /e cannot be used with replacement callback""); + return NULL; + } + } else { + replace = Z_STRVAL_P(replace_val); + replace_len = Z_STRLEN_P(replace_val); + replace_end = replace + replace_len; + } + + /* Calculate the size of the offsets array, and allocate memory for it. */ + rc = pcre_fullinfo(pce->re, extra, PCRE_INFO_CAPTURECOUNT, &num_subpats); + if (rc < 0) { + php_error_docref(NULL TSRMLS_CC, E_WARNING, ""Internal pcre_fullinfo() error %d"", rc); + return NULL; + } + num_subpats++; + size_offsets = num_subpats * 3; + + /* + * Build a mapping from subpattern numbers to their names. We will always + * allocate the table, even though there may be no named subpatterns. This + * avoids somewhat more complicated logic in the inner loops. + */ + subpat_names = make_subpats_table(num_subpats, pce TSRMLS_CC); + if (!subpat_names) { + return NULL; + } + + offsets = (int *)safe_emalloc(size_offsets, sizeof(int), 0); + + alloc_len = 2 * subject_len + 1; + result = safe_emalloc(alloc_len, sizeof(char), 0); + + /* Initialize */ + match = NULL; + *result_len = 0; + start_offset = 0; + PCRE_G(error_code) = PHP_PCRE_NO_ERROR; + + while (1) { + /* Execute the regular expression. */ + count = pcre_exec(pce->re, extra, subject, subject_len, start_offset, + exoptions|g_notempty, offsets, size_offsets); + + /* the string was already proved to be valid UTF-8 */ + exoptions |= PCRE_NO_UTF8_CHECK; + + /* Check for too many substrings condition. */ + if (count == 0) { + php_error_docref(NULL TSRMLS_CC,E_NOTICE, ""Matched, but too many substrings""); + count = size_offsets/3; + } + + piece = subject + start_offset; + + if (count > 0 && (limit == -1 || limit > 0)) { + if (replace_count) { + ++*replace_count; + } + /* Set the match location in subject */ + match = subject + offsets[0]; + + new_len = *result_len + offsets[0] - start_offset; /* part before the match */ + + /* If evaluating, do it and add the return string's length */ + if (eval) { + eval_result_len = preg_do_eval(replace, replace_len, subject, + offsets, count, &eval_result TSRMLS_CC); + new_len += eval_result_len; + } else if (is_callable_replace) { + /* Use custom function to get replacement string and its length. */ + eval_result_len = preg_do_repl_func(replace_val, subject, offsets, subpat_names, count, &eval_result TSRMLS_CC); + new_len += eval_result_len; + } else { /* do regular substitution */ + walk = replace; + walk_last = 0; + while (walk < replace_end) { + if ('\\' == *walk || '$' == *walk) { + if (walk_last == '\\') { + walk++; + walk_last = 0; + continue; + } + if (preg_get_backref(&walk, &backref)) { + if (backref < count) + new_len += offsets[(backref<<1)+1] - offsets[backref<<1]; + continue; + } + } + new_len++; + walk++; + walk_last = walk[-1]; + } + } + + if (new_len + 1 > alloc_len) { + alloc_len = 1 + alloc_len + 2 * new_len; + new_buf = emalloc(alloc_len); + memcpy(new_buf, result, *result_len); + efree(result); + result = new_buf; + } + /* copy the part of the string before the match */ + memcpy(&result[*result_len], piece, match-piece); + *result_len += match-piece; + + /* copy replacement and backrefs */ + walkbuf = result + *result_len; + + /* If evaluating or using custom function, copy result to the buffer + * and clean up. */ + if (eval || is_callable_replace) { + memcpy(walkbuf, eval_result, eval_result_len); + *result_len += eval_result_len; + STR_FREE(eval_result); + } else { /* do regular backreference copying */ + walk = replace; + walk_last = 0; + while (walk < replace_end) { + if ('\\' == *walk || '$' == *walk) { + if (walk_last == '\\') { + *(walkbuf-1) = *walk++; + walk_last = 0; + continue; + } + if (preg_get_backref(&walk, &backref)) { + if (backref < count) { + match_len = offsets[(backref<<1)+1] - offsets[backref<<1]; + memcpy(walkbuf, subject + offsets[backref<<1], match_len); + walkbuf += match_len; + } + continue; + } + } + *walkbuf++ = *walk++; + walk_last = walk[-1]; + } + *walkbuf = '\0'; + /* increment the result length by how much we've added to the string */ + *result_len += walkbuf - (result + *result_len); + } + + if (limit != -1) + limit--; + + } else if (count == PCRE_ERROR_NOMATCH || limit == 0) { + /* If we previously set PCRE_NOTEMPTY after a null match, + this is not necessarily the end. We need to advance + the start offset, and continue. Fudge the offset values + to achieve this, unless we're already at the end of the string. */ + if (g_notempty != 0 && start_offset < subject_len) { + offsets[0] = start_offset; + offsets[1] = start_offset + 1; + memcpy(&result[*result_len], piece, 1); + (*result_len)++; + } else { + new_len = *result_len + subject_len - start_offset; + if (new_len + 1 > alloc_len) { + alloc_len = new_len + 1; /* now we know exactly how long it is */ + new_buf = safe_emalloc(alloc_len, sizeof(char), 0); + memcpy(new_buf, result, *result_len); + efree(result); + result = new_buf; + } + /* stick that last bit of string on our output */ + memcpy(&result[*result_len], piece, subject_len - start_offset); + *result_len += subject_len - start_offset; + result[*result_len] = '\0'; + break; + } + } else { + pcre_handle_exec_error(count TSRMLS_CC); + efree(result); + result = NULL; + break; + } + + /* If we have matched an empty string, mimic what Perl's /g options does. + This turns out to be rather cunning. First we set PCRE_NOTEMPTY and try + the match again at the same point. If this fails (picked up above) we + advance to the next character. */ + g_notempty = (offsets[1] == offsets[0])? PCRE_NOTEMPTY | PCRE_ANCHORED : 0; + + /* Advance to the next piece. */ + start_offset = offsets[1]; + } + + efree(offsets); + efree(subpat_names); + + return result; +} +","@@ -640,7 +640,7 @@ PHPAPI void php_pcre_match_impl(pcre_cache_entry *pce, char *subject, int subjec + } + + offsets = (int *)safe_emalloc(size_offsets, sizeof(int), 0); +- ++ memset(offsets, 0, size_offsets*sizeof(int)); + /* Allocate match sets array and initialize the values. */ + if (global && subpats && subpats_order == PREG_PATTERN_ORDER) { + match_sets = (zval **)safe_emalloc(num_subpats, sizeof(zval *), 0);",2279,2610,4096 +5234,"static INT AirPDcapScanForKeys( + PAIRPDCAP_CONTEXT ctx, + const guint8 *data, + const guint mac_header_len, + const guint tot_len, + AIRPDCAP_SEC_ASSOCIATION_ID id +) +{ + const UCHAR *addr; + guint bodyLength; + PAIRPDCAP_SEC_ASSOCIATION sta_sa; + PAIRPDCAP_SEC_ASSOCIATION sa; + guint offset = 0; + const guint8 dot1x_header[] = { + 0xAA, /* DSAP=SNAP */ + 0xAA, /* SSAP=SNAP */ + 0x03, /* Control field=Unnumbered frame */ + 0x00, 0x00, 0x00, /* Org. code=encaps. Ethernet */ + 0x88, 0x8E /* Type: 802.1X authentication */ + }; + const guint8 bt_dot1x_header[] = { + 0xAA, /* DSAP=SNAP */ + 0xAA, /* SSAP=SNAP */ + 0x03, /* Control field=Unnumbered frame */ + 0x00, 0x19, 0x58, /* Org. code=Bluetooth SIG */ + 0x00, 0x03 /* Type: Bluetooth Security */ + }; + const guint8 tdls_header[] = { + 0xAA, /* DSAP=SNAP */ + 0xAA, /* SSAP=SNAP */ + 0x03, /* Control field=Unnumbered frame */ + 0x00, 0x00, 0x00, /* Org. code=encaps. Ethernet */ + 0x89, 0x0D, /* Type: 802.11 - Fast Roaming Remote Request */ + 0x02, /* Payload Type: TDLS */ + 0X0C /* Action Category: TDLS */ + }; + + const EAPOL_RSN_KEY *pEAPKey; +#ifdef _DEBUG +#define MSGBUF_LEN 255 + CHAR msgbuf[MSGBUF_LEN]; +#endif + AIRPDCAP_DEBUG_TRACE_START(""AirPDcapScanForKeys""); + + /* cache offset in the packet data */ + offset = mac_header_len; + + /* check if the packet has an LLC header and the packet is 802.1X authentication (IEEE 802.1X-2004, pg. 24) */ + if (memcmp(data+offset, dot1x_header, 8) == 0 || memcmp(data+offset, bt_dot1x_header, 8) == 0) { + + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""Authentication: EAPOL packet"", AIRPDCAP_DEBUG_LEVEL_3); + + /* skip LLC header */ + offset+=8; + + /* check if the packet is a EAPOL-Key (0x03) (IEEE 802.1X-2004, pg. 25) */ + if (data[offset+1]!=3) { + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""Not EAPOL-Key"", AIRPDCAP_DEBUG_LEVEL_3); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + /* get and check the body length (IEEE 802.1X-2004, pg. 25) */ + bodyLength=pntoh16(data+offset+2); + if ((tot_len-offset-4) < bodyLength) { /* Only check if frame is long enough for eapol header, ignore tailing garbage, see bug 9065 */ + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""EAPOL body too short"", AIRPDCAP_DEBUG_LEVEL_3); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + /* skip EAPOL MPDU and go to the first byte of the body */ + offset+=4; + + pEAPKey = (const EAPOL_RSN_KEY *) (data+offset); + + /* check if the key descriptor type is valid (IEEE 802.1X-2004, pg. 27) */ + if (/*pEAPKey->type!=0x1 &&*/ /* RC4 Key Descriptor Type (deprecated) */ + pEAPKey->type != AIRPDCAP_RSN_WPA2_KEY_DESCRIPTOR && /* IEEE 802.11 Key Descriptor Type (WPA2) */ + pEAPKey->type != AIRPDCAP_RSN_WPA_KEY_DESCRIPTOR) /* 254 = RSN_KEY_DESCRIPTOR - WPA, */ + { + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""Not valid key descriptor type"", AIRPDCAP_DEBUG_LEVEL_3); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + /* start with descriptor body */ + offset+=1; + + /* search for a cached Security Association for current BSSID and AP */ + sa = AirPDcapGetSaPtr(ctx, &id); + if (sa == NULL){ + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""No SA for BSSID found"", AIRPDCAP_DEBUG_LEVEL_3); + return AIRPDCAP_RET_REQ_DATA; + } + + /* It could be a Pairwise Key exchange, check */ + if (AirPDcapRsna4WHandshake(ctx, data, sa, offset, tot_len) == AIRPDCAP_RET_SUCCESS_HANDSHAKE) + return AIRPDCAP_RET_SUCCESS_HANDSHAKE; + + if (mac_header_len + GROUP_KEY_PAYLOAD_LEN_MIN > tot_len) { + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""Message too short for Group Key"", AIRPDCAP_DEBUG_LEVEL_3); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + /* Verify the bitfields: Key = 0(groupwise) Mic = 1 Ack = 1 Secure = 1 */ + if (AIRPDCAP_EAP_KEY(data[offset+1])!=0 || + AIRPDCAP_EAP_ACK(data[offset+1])!=1 || + AIRPDCAP_EAP_MIC(data[offset]) != 1 || + AIRPDCAP_EAP_SEC(data[offset]) != 1){ + + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""Key bitfields not correct for Group Key"", AIRPDCAP_DEBUG_LEVEL_3); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + /* force STA address to be the broadcast MAC so we create an SA for the groupkey */ + memcpy(id.sta, broadcast_mac, AIRPDCAP_MAC_LEN); + + /* get the Security Association structure for the broadcast MAC and AP */ + sa = AirPDcapGetSaPtr(ctx, &id); + if (sa == NULL){ + return AIRPDCAP_RET_REQ_DATA; + } + + /* Get the SA for the STA, since we need its pairwise key to decrpyt the group key */ + + /* get STA address */ + if ( (addr=AirPDcapGetStaAddress((const AIRPDCAP_MAC_FRAME_ADDR4 *)(data))) != NULL) { + memcpy(id.sta, addr, AIRPDCAP_MAC_LEN); +#ifdef _DEBUG + g_snprintf(msgbuf, MSGBUF_LEN, ""ST_MAC: %2X.%2X.%2X.%2X.%2X.%2X\t"", id.sta[0],id.sta[1],id.sta[2],id.sta[3],id.sta[4],id.sta[5]); +#endif + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", msgbuf, AIRPDCAP_DEBUG_LEVEL_3); + } else { + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""SA not found"", AIRPDCAP_DEBUG_LEVEL_5); + return AIRPDCAP_RET_REQ_DATA; + } + + sta_sa = AirPDcapGetSaPtr(ctx, &id); + if (sta_sa == NULL){ + return AIRPDCAP_RET_REQ_DATA; + } + + /* Try to extract the group key and install it in the SA */ + return (AirPDcapDecryptWPABroadcastKey(pEAPKey, sta_sa->wpa.ptk+16, sa, tot_len-offset+1)); + + } else if (memcmp(data+offset, tdls_header, 10) == 0) { + const guint8 *initiator, *responder; + guint8 action; + guint status, offset_rsne = 0, offset_fte = 0, offset_link = 0, offset_timeout = 0; + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""Authentication: TDLS Action Frame"", AIRPDCAP_DEBUG_LEVEL_3); + + /* skip LLC header */ + offset+=10; + + /* check if the packet is a TDLS response or confirm */ + action = data[offset]; + if (action!=1 && action!=2) { + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""Not Response nor confirm"", AIRPDCAP_DEBUG_LEVEL_3); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + /* check status */ + offset++; + status=pntoh16(data+offset); + if (status!=0) { + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""TDLS setup not successfull"", AIRPDCAP_DEBUG_LEVEL_3); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + /* skip Token + capabilities */ + offset+=5; + + /* search for RSN, Fast BSS Transition, Link Identifier and Timeout Interval IEs */ + + while(offset < (tot_len - 2)) { + if (data[offset] == 48) { + offset_rsne = offset; + } else if (data[offset] == 55) { + offset_fte = offset; + } else if (data[offset] == 56) { + offset_timeout = offset; + } else if (data[offset] == 101) { + offset_link = offset; + } + + if (tot_len < offset + data[offset + 1] + 2) { + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + offset += data[offset + 1] + 2; + } + + if (offset_rsne == 0 || offset_fte == 0 || + offset_timeout == 0 || offset_link == 0) + { + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""Cannot Find all necessary IEs"", AIRPDCAP_DEBUG_LEVEL_3); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""Found RSNE/Fast BSS/Timeout Interval/Link IEs"", AIRPDCAP_DEBUG_LEVEL_3); + + /* Will create a Security Association between 2 STA. Need to get both MAC address */ + initiator = &data[offset_link + 8]; + responder = &data[offset_link + 14]; + + if (memcmp(initiator, responder, AIRPDCAP_MAC_LEN) < 0) { + memcpy(id.sta, initiator, AIRPDCAP_MAC_LEN); + memcpy(id.bssid, responder, AIRPDCAP_MAC_LEN); + } else { + memcpy(id.sta, responder, AIRPDCAP_MAC_LEN); + memcpy(id.bssid, initiator, AIRPDCAP_MAC_LEN); + } + + sa = AirPDcapGetSaPtr(ctx, &id); + if (sa == NULL){ + return AIRPDCAP_RET_REQ_DATA; + } + + if (sa->validKey) { + if (memcmp(sa->wpa.nonce, data + offset_fte + 52, AIRPDCAP_WPA_NONCE_LEN) == 0) { + /* Already have valid key for this SA, no need to redo key derivation */ + return AIRPDCAP_RET_SUCCESS_HANDSHAKE; + } else { + /* We are opening a new session with the same two STA, save previous sa */ + AIRPDCAP_SEC_ASSOCIATION *tmp_sa = g_new(AIRPDCAP_SEC_ASSOCIATION, 1); + memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION)); + sa->next=tmp_sa; + sa->validKey = FALSE; + } + } + + if (AirPDcapTDLSDeriveKey(sa, data, offset_rsne, offset_fte, offset_timeout, offset_link, action) + == AIRPDCAP_RET_SUCCESS) { + AIRPDCAP_DEBUG_TRACE_END(""AirPDcapScanForKeys""); + return AIRPDCAP_RET_SUCCESS_HANDSHAKE; + } + } else { + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""Skipping: not an EAPOL packet"", AIRPDCAP_DEBUG_LEVEL_3); + } + + AIRPDCAP_DEBUG_TRACE_END(""AirPDcapScanForKeys""); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; +} +",0,"static INT AirPDcapScanForKeys( + PAIRPDCAP_CONTEXT ctx, + const guint8 *data, + const guint mac_header_len, + const guint tot_len, + AIRPDCAP_SEC_ASSOCIATION_ID id +) +{ + const UCHAR *addr; + guint bodyLength; + PAIRPDCAP_SEC_ASSOCIATION sta_sa; + PAIRPDCAP_SEC_ASSOCIATION sa; + guint offset = 0; + const guint8 dot1x_header[] = { + 0xAA, /* DSAP=SNAP */ + 0xAA, /* SSAP=SNAP */ + 0x03, /* Control field=Unnumbered frame */ + 0x00, 0x00, 0x00, /* Org. code=encaps. Ethernet */ + 0x88, 0x8E /* Type: 802.1X authentication */ + }; + const guint8 bt_dot1x_header[] = { + 0xAA, /* DSAP=SNAP */ + 0xAA, /* SSAP=SNAP */ + 0x03, /* Control field=Unnumbered frame */ + 0x00, 0x19, 0x58, /* Org. code=Bluetooth SIG */ + 0x00, 0x03 /* Type: Bluetooth Security */ + }; + const guint8 tdls_header[] = { + 0xAA, /* DSAP=SNAP */ + 0xAA, /* SSAP=SNAP */ + 0x03, /* Control field=Unnumbered frame */ + 0x00, 0x00, 0x00, /* Org. code=encaps. Ethernet */ + 0x89, 0x0D, /* Type: 802.11 - Fast Roaming Remote Request */ + 0x02, /* Payload Type: TDLS */ + 0X0C /* Action Category: TDLS */ + }; + + const EAPOL_RSN_KEY *pEAPKey; +#ifdef _DEBUG +#define MSGBUF_LEN 255 + CHAR msgbuf[MSGBUF_LEN]; +#endif + AIRPDCAP_DEBUG_TRACE_START(""AirPDcapScanForKeys""); + + /* cache offset in the packet data */ + offset = mac_header_len; + + /* check if the packet has an LLC header and the packet is 802.1X authentication (IEEE 802.1X-2004, pg. 24) */ + if (memcmp(data+offset, dot1x_header, 8) == 0 || memcmp(data+offset, bt_dot1x_header, 8) == 0) { + + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""Authentication: EAPOL packet"", AIRPDCAP_DEBUG_LEVEL_3); + + /* skip LLC header */ + offset+=8; + + /* check if the packet is a EAPOL-Key (0x03) (IEEE 802.1X-2004, pg. 25) */ + if (data[offset+1]!=3) { + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""Not EAPOL-Key"", AIRPDCAP_DEBUG_LEVEL_3); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + /* get and check the body length (IEEE 802.1X-2004, pg. 25) */ + bodyLength=pntoh16(data+offset+2); + if ((tot_len-offset-4) < bodyLength) { /* Only check if frame is long enough for eapol header, ignore tailing garbage, see bug 9065 */ + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""EAPOL body too short"", AIRPDCAP_DEBUG_LEVEL_3); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + /* skip EAPOL MPDU and go to the first byte of the body */ + offset+=4; + + pEAPKey = (const EAPOL_RSN_KEY *) (data+offset); + + /* check if the key descriptor type is valid (IEEE 802.1X-2004, pg. 27) */ + if (/*pEAPKey->type!=0x1 &&*/ /* RC4 Key Descriptor Type (deprecated) */ + pEAPKey->type != AIRPDCAP_RSN_WPA2_KEY_DESCRIPTOR && /* IEEE 802.11 Key Descriptor Type (WPA2) */ + pEAPKey->type != AIRPDCAP_RSN_WPA_KEY_DESCRIPTOR) /* 254 = RSN_KEY_DESCRIPTOR - WPA, */ + { + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""Not valid key descriptor type"", AIRPDCAP_DEBUG_LEVEL_3); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + /* start with descriptor body */ + offset+=1; + + /* search for a cached Security Association for current BSSID and AP */ + sa = AirPDcapGetSaPtr(ctx, &id); + if (sa == NULL){ + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""No SA for BSSID found"", AIRPDCAP_DEBUG_LEVEL_3); + return AIRPDCAP_RET_REQ_DATA; + } + + /* It could be a Pairwise Key exchange, check */ + if (AirPDcapRsna4WHandshake(ctx, data, sa, offset, tot_len) == AIRPDCAP_RET_SUCCESS_HANDSHAKE) + return AIRPDCAP_RET_SUCCESS_HANDSHAKE; + + if (mac_header_len + GROUP_KEY_PAYLOAD_LEN_MIN > tot_len) { + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""Message too short for Group Key"", AIRPDCAP_DEBUG_LEVEL_3); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + /* Verify the bitfields: Key = 0(groupwise) Mic = 1 Ack = 1 Secure = 1 */ + if (AIRPDCAP_EAP_KEY(data[offset+1])!=0 || + AIRPDCAP_EAP_ACK(data[offset+1])!=1 || + AIRPDCAP_EAP_MIC(data[offset]) != 1 || + AIRPDCAP_EAP_SEC(data[offset]) != 1){ + + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""Key bitfields not correct for Group Key"", AIRPDCAP_DEBUG_LEVEL_3); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + /* force STA address to be the broadcast MAC so we create an SA for the groupkey */ + memcpy(id.sta, broadcast_mac, AIRPDCAP_MAC_LEN); + + /* get the Security Association structure for the broadcast MAC and AP */ + sa = AirPDcapGetSaPtr(ctx, &id); + if (sa == NULL){ + return AIRPDCAP_RET_REQ_DATA; + } + + /* Get the SA for the STA, since we need its pairwise key to decrpyt the group key */ + + /* get STA address */ + if ( (addr=AirPDcapGetStaAddress((const AIRPDCAP_MAC_FRAME_ADDR4 *)(data))) != NULL) { + memcpy(id.sta, addr, AIRPDCAP_MAC_LEN); +#ifdef _DEBUG + g_snprintf(msgbuf, MSGBUF_LEN, ""ST_MAC: %2X.%2X.%2X.%2X.%2X.%2X\t"", id.sta[0],id.sta[1],id.sta[2],id.sta[3],id.sta[4],id.sta[5]); +#endif + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", msgbuf, AIRPDCAP_DEBUG_LEVEL_3); + } else { + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""SA not found"", AIRPDCAP_DEBUG_LEVEL_5); + return AIRPDCAP_RET_REQ_DATA; + } + + sta_sa = AirPDcapGetSaPtr(ctx, &id); + if (sta_sa == NULL){ + return AIRPDCAP_RET_REQ_DATA; + } + + /* Try to extract the group key and install it in the SA */ + return (AirPDcapDecryptWPABroadcastKey(pEAPKey, sta_sa->wpa.ptk+16, sa, tot_len-offset+1)); + + } else if (memcmp(data+offset, tdls_header, 10) == 0) { + const guint8 *initiator, *responder; + guint8 action; + guint status, offset_rsne = 0, offset_fte = 0, offset_link = 0, offset_timeout = 0; + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""Authentication: TDLS Action Frame"", AIRPDCAP_DEBUG_LEVEL_3); + + /* skip LLC header */ + offset+=10; + + /* check if the packet is a TDLS response or confirm */ + action = data[offset]; + if (action!=1 && action!=2) { + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""Not Response nor confirm"", AIRPDCAP_DEBUG_LEVEL_3); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + /* check status */ + offset++; + status=pntoh16(data+offset); + if (status!=0) { + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""TDLS setup not successfull"", AIRPDCAP_DEBUG_LEVEL_3); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + /* skip Token + capabilities */ + offset+=5; + + /* search for RSN, Fast BSS Transition, Link Identifier and Timeout Interval IEs */ + + while(offset < (tot_len - 2)) { + if (data[offset] == 48) { + offset_rsne = offset; + } else if (data[offset] == 55) { + offset_fte = offset; + } else if (data[offset] == 56) { + offset_timeout = offset; + } else if (data[offset] == 101) { + offset_link = offset; + } + + if (tot_len < offset + data[offset + 1] + 2) { + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + offset += data[offset + 1] + 2; + } + + if (offset_rsne == 0 || offset_fte == 0 || + offset_timeout == 0 || offset_link == 0) + { + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""Cannot Find all necessary IEs"", AIRPDCAP_DEBUG_LEVEL_3); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""Found RSNE/Fast BSS/Timeout Interval/Link IEs"", AIRPDCAP_DEBUG_LEVEL_3); + + /* Will create a Security Association between 2 STA. Need to get both MAC address */ + initiator = &data[offset_link + 8]; + responder = &data[offset_link + 14]; + + if (memcmp(initiator, responder, AIRPDCAP_MAC_LEN) < 0) { + memcpy(id.sta, initiator, AIRPDCAP_MAC_LEN); + memcpy(id.bssid, responder, AIRPDCAP_MAC_LEN); + } else { + memcpy(id.sta, responder, AIRPDCAP_MAC_LEN); + memcpy(id.bssid, initiator, AIRPDCAP_MAC_LEN); + } + + sa = AirPDcapGetSaPtr(ctx, &id); + if (sa == NULL){ + return AIRPDCAP_RET_REQ_DATA; + } + + if (sa->validKey) { + if (memcmp(sa->wpa.nonce, data + offset_fte + 52, AIRPDCAP_WPA_NONCE_LEN) == 0) { + /* Already have valid key for this SA, no need to redo key derivation */ + return AIRPDCAP_RET_SUCCESS_HANDSHAKE; + } else { + /* We are opening a new session with the same two STA, save previous sa */ + AIRPDCAP_SEC_ASSOCIATION *tmp_sa = g_new(AIRPDCAP_SEC_ASSOCIATION, 1); + memcpy(tmp_sa, sa, sizeof(AIRPDCAP_SEC_ASSOCIATION)); + sa->next=tmp_sa; + sa->validKey = FALSE; + } + } + + if (AirPDcapTDLSDeriveKey(sa, data, offset_rsne, offset_fte, offset_timeout, offset_link, action) + == AIRPDCAP_RET_SUCCESS) { + AIRPDCAP_DEBUG_TRACE_END(""AirPDcapScanForKeys""); + return AIRPDCAP_RET_SUCCESS_HANDSHAKE; + } + } else { + AIRPDCAP_DEBUG_PRINT_LINE(""AirPDcapScanForKeys"", ""Skipping: not an EAPOL packet"", AIRPDCAP_DEBUG_LEVEL_3); + } + + AIRPDCAP_DEBUG_TRACE_END(""AirPDcapScanForKeys""); + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; +} +","@@ -351,7 +351,9 @@ AirPDcapDecryptWPABroadcastKey(const EAPOL_RSN_KEY *pEAPKey, guint8 *decryption_ + } + } + +- if (key_bytes_len < GROUP_KEY_MIN_LEN || key_bytes_len > eapol_len - sizeof(EAPOL_RSN_KEY)) { ++ if ((key_bytes_len < GROUP_KEY_MIN_LEN) || ++ (eapol_len < sizeof(EAPOL_RSN_KEY)) || ++ (key_bytes_len > eapol_len - sizeof(EAPOL_RSN_KEY))) { + return AIRPDCAP_RET_NO_VALID_HANDSHAKE; + } + ",2887,3218,4096 +398,"_dbus_poll (DBusPollFD *fds, + int n_fds, + int timeout_milliseconds) +{ +#define USE_CHRIS_IMPL 0 + +#if USE_CHRIS_IMPL + +#define DBUS_POLL_CHAR_BUFFER_SIZE 2000 + char msg[DBUS_POLL_CHAR_BUFFER_SIZE]; + char *msgp; + + int ret = 0; + int i; + struct timeval tv; + int ready; + +#define DBUS_STACK_WSAEVENTS 256 + WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS]; + WSAEVENT *pEvents = NULL; + if (n_fds > DBUS_STACK_WSAEVENTS) + pEvents = calloc(sizeof(WSAEVENT), n_fds); + else + pEvents = eventsOnStack; + + +#ifdef DBUS_ENABLE_VERBOSE_MODE + msgp = msg; + msgp += sprintf (msgp, ""WSAEventSelect: to=%d\n\t"", timeout_milliseconds); + for (i = 0; i < n_fds; i++) + { + DBusPollFD *fdp = &fds[i]; + + + if (fdp->events & _DBUS_POLLIN) + msgp += sprintf (msgp, ""R:%d "", fdp->fd); + + if (fdp->events & _DBUS_POLLOUT) + msgp += sprintf (msgp, ""W:%d "", fdp->fd); + + msgp += sprintf (msgp, ""E:%d\n\t"", fdp->fd); + + if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE) + { + _dbus_assert_not_reached (""buffer overflow in _dbus_poll""); + } + } + + msgp += sprintf (msgp, ""\n""); + _dbus_verbose (""%s"",msg); +#endif + for (i = 0; i < n_fds; i++) + { + DBusPollFD *fdp = &fds[i]; + WSAEVENT ev; + long lNetworkEvents = FD_OOB; + + ev = WSACreateEvent(); + + if (fdp->events & _DBUS_POLLIN) + lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE; + + if (fdp->events & _DBUS_POLLOUT) + lNetworkEvents |= FD_WRITE | FD_CONNECT; + + WSAEventSelect(fdp->fd, ev, lNetworkEvents); + + pEvents[i] = ev; + } + + + ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE); + + if (DBUS_SOCKET_API_RETURNS_ERROR (ready)) + { + DBUS_SOCKET_SET_ERRNO (); + if (errno != WSAEWOULDBLOCK) + _dbus_verbose (""WSAWaitForMultipleEvents: failed: %s\n"", _dbus_strerror_from_errno ()); + ret = -1; + } + else if (ready == WSA_WAIT_TIMEOUT) + { + _dbus_verbose (""WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n""); + ret = 0; + } + else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds)) + { + msgp = msg; + msgp += sprintf (msgp, ""WSAWaitForMultipleEvents: =%d\n\t"", ready); + + for (i = 0; i < n_fds; i++) + { + DBusPollFD *fdp = &fds[i]; + WSANETWORKEVENTS ne; + + fdp->revents = 0; + + WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne); + + if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE)) + fdp->revents |= _DBUS_POLLIN; + + if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT)) + fdp->revents |= _DBUS_POLLOUT; + + if (ne.lNetworkEvents & (FD_OOB)) + fdp->revents |= _DBUS_POLLERR; + + if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE)) + msgp += sprintf (msgp, ""R:%d "", fdp->fd); + + if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT)) + msgp += sprintf (msgp, ""W:%d "", fdp->fd); + + if (ne.lNetworkEvents & (FD_OOB)) + msgp += sprintf (msgp, ""E:%d "", fdp->fd); + + msgp += sprintf (msgp, ""lNetworkEvents:%d "", ne.lNetworkEvents); + + if(ne.lNetworkEvents) + ret++; + + WSAEventSelect(fdp->fd, pEvents[i], 0); + } + + msgp += sprintf (msgp, ""\n""); + _dbus_verbose (""%s"",msg); + } + else + { + _dbus_verbose (""WSAWaitForMultipleEvents: failed for unknown reason!""); + ret = -1; + } + + for(i = 0; i < n_fds; i++) + { + WSACloseEvent(pEvents[i]); + } + + if (n_fds > DBUS_STACK_WSAEVENTS) + free(pEvents); + + return ret; + +#else /* USE_CHRIS_IMPL */ + +#define DBUS_POLL_CHAR_BUFFER_SIZE 2000 + char msg[DBUS_POLL_CHAR_BUFFER_SIZE]; + char *msgp; + + fd_set read_set, write_set, err_set; + int max_fd = 0; + int i; + struct timeval tv; + int ready; + + FD_ZERO (&read_set); + FD_ZERO (&write_set); + FD_ZERO (&err_set); + + +#ifdef DBUS_ENABLE_VERBOSE_MODE + msgp = msg; + msgp += sprintf (msgp, ""select: to=%d\n\t"", timeout_milliseconds); + for (i = 0; i < n_fds; i++) + { + DBusPollFD *fdp = &fds[i]; + + + if (fdp->events & _DBUS_POLLIN) + msgp += sprintf (msgp, ""R:%d "", fdp->fd); + + if (fdp->events & _DBUS_POLLOUT) + msgp += sprintf (msgp, ""W:%d "", fdp->fd); + + msgp += sprintf (msgp, ""E:%d\n\t"", fdp->fd); + + if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE) + { + _dbus_assert_not_reached (""buffer overflow in _dbus_poll""); + } + } + + msgp += sprintf (msgp, ""\n""); + _dbus_verbose (""%s"",msg); +#endif + for (i = 0; i < n_fds; i++) + { + DBusPollFD *fdp = &fds[i]; + + if (fdp->events & _DBUS_POLLIN) + FD_SET (fdp->fd, &read_set); + + if (fdp->events & _DBUS_POLLOUT) + FD_SET (fdp->fd, &write_set); + + FD_SET (fdp->fd, &err_set); + + max_fd = MAX (max_fd, fdp->fd); + } + + tv.tv_sec = timeout_milliseconds < 0 ? 1 : timeout_milliseconds / 1000; + tv.tv_usec = timeout_milliseconds < 0 ? 0 : (timeout_milliseconds % 1000) * 1000; + + ready = select (max_fd + 1, &read_set, &write_set, &err_set, &tv); + + if (DBUS_SOCKET_API_RETURNS_ERROR (ready)) + { + DBUS_SOCKET_SET_ERRNO (); + if (errno != WSAEWOULDBLOCK) + _dbus_verbose (""select: failed: %s\n"", _dbus_strerror_from_errno ()); + } + else if (ready == 0) + _dbus_verbose (""select: = 0\n""); + else + if (ready > 0) + { +#ifdef DBUS_ENABLE_VERBOSE_MODE + msgp = msg; + msgp += sprintf (msgp, ""select: = %d:\n\t"", ready); + + for (i = 0; i < n_fds; i++) + { + DBusPollFD *fdp = &fds[i]; + + if (FD_ISSET (fdp->fd, &read_set)) + msgp += sprintf (msgp, ""R:%d "", fdp->fd); + + if (FD_ISSET (fdp->fd, &write_set)) + msgp += sprintf (msgp, ""W:%d "", fdp->fd); + + if (FD_ISSET (fdp->fd, &err_set)) + msgp += sprintf (msgp, ""E:%d\n\t"", fdp->fd); + } + msgp += sprintf (msgp, ""\n""); + _dbus_verbose (""%s"",msg); +#endif + + for (i = 0; i < n_fds; i++) + { + DBusPollFD *fdp = &fds[i]; + + fdp->revents = 0; + + if (FD_ISSET (fdp->fd, &read_set)) + fdp->revents |= _DBUS_POLLIN; + + if (FD_ISSET (fdp->fd, &write_set)) + fdp->revents |= _DBUS_POLLOUT; + + if (FD_ISSET (fdp->fd, &err_set)) + fdp->revents |= _DBUS_POLLERR; + } + } + return ready; +#endif /* USE_CHRIS_IMPL */ +} +",0,"_dbus_poll (DBusPollFD *fds, + int n_fds, + int timeout_milliseconds) +{ +#define USE_CHRIS_IMPL 0 + +#if USE_CHRIS_IMPL + +#define DBUS_POLL_CHAR_BUFFER_SIZE 2000 + char msg[DBUS_POLL_CHAR_BUFFER_SIZE]; + char *msgp; + + int ret = 0; + int i; + struct timeval tv; + int ready; + +#define DBUS_STACK_WSAEVENTS 256 + WSAEVENT eventsOnStack[DBUS_STACK_WSAEVENTS]; + WSAEVENT *pEvents = NULL; + if (n_fds > DBUS_STACK_WSAEVENTS) + pEvents = calloc(sizeof(WSAEVENT), n_fds); + else + pEvents = eventsOnStack; + + +#ifdef DBUS_ENABLE_VERBOSE_MODE + msgp = msg; + msgp += sprintf (msgp, ""WSAEventSelect: to=%d\n\t"", timeout_milliseconds); + for (i = 0; i < n_fds; i++) + { + DBusPollFD *fdp = &fds[i]; + + + if (fdp->events & _DBUS_POLLIN) + msgp += sprintf (msgp, ""R:%d "", fdp->fd); + + if (fdp->events & _DBUS_POLLOUT) + msgp += sprintf (msgp, ""W:%d "", fdp->fd); + + msgp += sprintf (msgp, ""E:%d\n\t"", fdp->fd); + + if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE) + { + _dbus_assert_not_reached (""buffer overflow in _dbus_poll""); + } + } + + msgp += sprintf (msgp, ""\n""); + _dbus_verbose (""%s"",msg); +#endif + for (i = 0; i < n_fds; i++) + { + DBusPollFD *fdp = &fds[i]; + WSAEVENT ev; + long lNetworkEvents = FD_OOB; + + ev = WSACreateEvent(); + + if (fdp->events & _DBUS_POLLIN) + lNetworkEvents |= FD_READ | FD_ACCEPT | FD_CLOSE; + + if (fdp->events & _DBUS_POLLOUT) + lNetworkEvents |= FD_WRITE | FD_CONNECT; + + WSAEventSelect(fdp->fd, ev, lNetworkEvents); + + pEvents[i] = ev; + } + + + ready = WSAWaitForMultipleEvents (n_fds, pEvents, FALSE, timeout_milliseconds, FALSE); + + if (DBUS_SOCKET_API_RETURNS_ERROR (ready)) + { + DBUS_SOCKET_SET_ERRNO (); + if (errno != WSAEWOULDBLOCK) + _dbus_verbose (""WSAWaitForMultipleEvents: failed: %s\n"", _dbus_strerror_from_errno ()); + ret = -1; + } + else if (ready == WSA_WAIT_TIMEOUT) + { + _dbus_verbose (""WSAWaitForMultipleEvents: WSA_WAIT_TIMEOUT\n""); + ret = 0; + } + else if (ready >= WSA_WAIT_EVENT_0 && ready < (int)(WSA_WAIT_EVENT_0 + n_fds)) + { + msgp = msg; + msgp += sprintf (msgp, ""WSAWaitForMultipleEvents: =%d\n\t"", ready); + + for (i = 0; i < n_fds; i++) + { + DBusPollFD *fdp = &fds[i]; + WSANETWORKEVENTS ne; + + fdp->revents = 0; + + WSAEnumNetworkEvents(fdp->fd, pEvents[i], &ne); + + if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE)) + fdp->revents |= _DBUS_POLLIN; + + if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT)) + fdp->revents |= _DBUS_POLLOUT; + + if (ne.lNetworkEvents & (FD_OOB)) + fdp->revents |= _DBUS_POLLERR; + + if (ne.lNetworkEvents & (FD_READ | FD_ACCEPT | FD_CLOSE)) + msgp += sprintf (msgp, ""R:%d "", fdp->fd); + + if (ne.lNetworkEvents & (FD_WRITE | FD_CONNECT)) + msgp += sprintf (msgp, ""W:%d "", fdp->fd); + + if (ne.lNetworkEvents & (FD_OOB)) + msgp += sprintf (msgp, ""E:%d "", fdp->fd); + + msgp += sprintf (msgp, ""lNetworkEvents:%d "", ne.lNetworkEvents); + + if(ne.lNetworkEvents) + ret++; + + WSAEventSelect(fdp->fd, pEvents[i], 0); + } + + msgp += sprintf (msgp, ""\n""); + _dbus_verbose (""%s"",msg); + } + else + { + _dbus_verbose (""WSAWaitForMultipleEvents: failed for unknown reason!""); + ret = -1; + } + + for(i = 0; i < n_fds; i++) + { + WSACloseEvent(pEvents[i]); + } + + if (n_fds > DBUS_STACK_WSAEVENTS) + free(pEvents); + + return ret; + +#else /* USE_CHRIS_IMPL */ + +#define DBUS_POLL_CHAR_BUFFER_SIZE 2000 + char msg[DBUS_POLL_CHAR_BUFFER_SIZE]; + char *msgp; + + fd_set read_set, write_set, err_set; + int max_fd = 0; + int i; + struct timeval tv; + int ready; + + FD_ZERO (&read_set); + FD_ZERO (&write_set); + FD_ZERO (&err_set); + + +#ifdef DBUS_ENABLE_VERBOSE_MODE + msgp = msg; + msgp += sprintf (msgp, ""select: to=%d\n\t"", timeout_milliseconds); + for (i = 0; i < n_fds; i++) + { + DBusPollFD *fdp = &fds[i]; + + + if (fdp->events & _DBUS_POLLIN) + msgp += sprintf (msgp, ""R:%d "", fdp->fd); + + if (fdp->events & _DBUS_POLLOUT) + msgp += sprintf (msgp, ""W:%d "", fdp->fd); + + msgp += sprintf (msgp, ""E:%d\n\t"", fdp->fd); + + if (msgp >= msg + DBUS_POLL_CHAR_BUFFER_SIZE) + { + _dbus_assert_not_reached (""buffer overflow in _dbus_poll""); + } + } + + msgp += sprintf (msgp, ""\n""); + _dbus_verbose (""%s"",msg); +#endif + for (i = 0; i < n_fds; i++) + { + DBusPollFD *fdp = &fds[i]; + + if (fdp->events & _DBUS_POLLIN) + FD_SET (fdp->fd, &read_set); + + if (fdp->events & _DBUS_POLLOUT) + FD_SET (fdp->fd, &write_set); + + FD_SET (fdp->fd, &err_set); + + max_fd = MAX (max_fd, fdp->fd); + } + + tv.tv_sec = timeout_milliseconds < 0 ? 1 : timeout_milliseconds / 1000; + tv.tv_usec = timeout_milliseconds < 0 ? 0 : (timeout_milliseconds % 1000) * 1000; + + ready = select (max_fd + 1, &read_set, &write_set, &err_set, &tv); + + if (DBUS_SOCKET_API_RETURNS_ERROR (ready)) + { + DBUS_SOCKET_SET_ERRNO (); + if (errno != WSAEWOULDBLOCK) + _dbus_verbose (""select: failed: %s\n"", _dbus_strerror_from_errno ()); + } + else if (ready == 0) + _dbus_verbose (""select: = 0\n""); + else + if (ready > 0) + { +#ifdef DBUS_ENABLE_VERBOSE_MODE + msgp = msg; + msgp += sprintf (msgp, ""select: = %d:\n\t"", ready); + + for (i = 0; i < n_fds; i++) + { + DBusPollFD *fdp = &fds[i]; + + if (FD_ISSET (fdp->fd, &read_set)) + msgp += sprintf (msgp, ""R:%d "", fdp->fd); + + if (FD_ISSET (fdp->fd, &write_set)) + msgp += sprintf (msgp, ""W:%d "", fdp->fd); + + if (FD_ISSET (fdp->fd, &err_set)) + msgp += sprintf (msgp, ""E:%d\n\t"", fdp->fd); + } + msgp += sprintf (msgp, ""\n""); + _dbus_verbose (""%s"",msg); +#endif + + for (i = 0; i < n_fds; i++) + { + DBusPollFD *fdp = &fds[i]; + + fdp->revents = 0; + + if (FD_ISSET (fdp->fd, &read_set)) + fdp->revents |= _DBUS_POLLIN; + + if (FD_ISSET (fdp->fd, &write_set)) + fdp->revents |= _DBUS_POLLOUT; + + if (FD_ISSET (fdp->fd, &err_set)) + fdp->revents |= _DBUS_POLLERR; + } + } + return ready; +#endif /* USE_CHRIS_IMPL */ +} +","@@ -538,9 +538,12 @@ int _dbus_printf_string_upper_bound (const char *format, + char buf[1024]; + int bufsize; + int len; ++ va_list args_copy; + + bufsize = sizeof (buf); +- len = _vsnprintf (buf, bufsize - 1, format, args); ++ DBUS_VA_COPY (args_copy, args); ++ len = _vsnprintf (buf, bufsize - 1, format, args_copy); ++ va_end (args_copy); + + while (len == -1) /* try again */ + { +@@ -553,7 +556,9 @@ int _dbus_printf_string_upper_bound (const char *format, + if (p == NULL) + return -1; + +- len = _vsnprintf (p, bufsize - 1, format, args); ++ DBUS_VA_COPY (args_copy, args); ++ len = _vsnprintf (p, bufsize - 1, format, args_copy); ++ va_end (args_copy); + free (p); + }",2058,2389,4096 +3822,"static void prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12) +{ + struct vcpu_vmx *vmx = to_vmx(vcpu); + u32 exec_control; + + vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector); + vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector); + vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector); + vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector); + vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector); + vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector); + vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector); + vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector); + vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit); + vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit); + vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit); + vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit); + vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit); + vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit); + vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit); + vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit); + vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit); + vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit); + vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes); + vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes); + vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes); + vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes); + vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes); + vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes); + vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes); + vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes); + vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base); + vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base); + vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base); + vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base); + vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base); + vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base); + vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base); + vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base); + vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base); + vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base); + + vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl); + vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, + vmcs12->vm_entry_intr_info_field); + vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, + vmcs12->vm_entry_exception_error_code); + vmcs_write32(VM_ENTRY_INSTRUCTION_LEN, + vmcs12->vm_entry_instruction_len); + vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, + vmcs12->guest_interruptibility_info); + vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs); + kvm_set_dr(vcpu, 7, vmcs12->guest_dr7); + vmx_set_rflags(vcpu, vmcs12->guest_rflags); + vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, + vmcs12->guest_pending_dbg_exceptions); + vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp); + vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip); + + vmcs_write64(VMCS_LINK_POINTER, -1ull); + + vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, + (vmcs_config.pin_based_exec_ctrl | + vmcs12->pin_based_vm_exec_control)); + + if (vmcs12->pin_based_vm_exec_control & PIN_BASED_VMX_PREEMPTION_TIMER) + vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, + vmcs12->vmx_preemption_timer_value); + + /* + * Whether page-faults are trapped is determined by a combination of + * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF. + * If enable_ept, L0 doesn't care about page faults and we should + * set all of these to L1's desires. However, if !enable_ept, L0 does + * care about (at least some) page faults, and because it is not easy + * (if at all possible?) to merge L0 and L1's desires, we simply ask + * to exit on each and every L2 page fault. This is done by setting + * MASK=MATCH=0 and (see below) EB.PF=1. + * Note that below we don't need special code to set EB.PF beyond the + * ""or""ing of the EB of vmcs01 and vmcs12, because when enable_ept, + * vmcs01's EB.PF is 0 so the ""or"" will take vmcs12's value, and when + * !enable_ept, EB.PF is 1, so the ""or"" will always be 1. + * + * A problem with this approach (when !enable_ept) is that L1 may be + * injected with more page faults than it asked for. This could have + * caused problems, but in practice existing hypervisors don't care. + * To fix this, we will need to emulate the PFEC checking (on the L1 + * page tables), using walk_addr(), when injecting PFs to L1. + */ + vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, + enable_ept ? vmcs12->page_fault_error_code_mask : 0); + vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, + enable_ept ? vmcs12->page_fault_error_code_match : 0); + + if (cpu_has_secondary_exec_ctrls()) { + u32 exec_control = vmx_secondary_exec_control(vmx); + if (!vmx->rdtscp_enabled) + exec_control &= ~SECONDARY_EXEC_RDTSCP; + /* Take the following fields only from vmcs12 */ + exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES; + if (nested_cpu_has(vmcs12, + CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)) + exec_control |= vmcs12->secondary_vm_exec_control; + + if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) { + /* + * Translate L1 physical address to host physical + * address for vmcs02. Keep the page pinned, so this + * physical address remains valid. We keep a reference + * to it so we can release it later. + */ + if (vmx->nested.apic_access_page) /* shouldn't happen */ + nested_release_page(vmx->nested.apic_access_page); + vmx->nested.apic_access_page = + nested_get_page(vcpu, vmcs12->apic_access_addr); + /* + * If translation failed, no matter: This feature asks + * to exit when accessing the given address, and if it + * can never be accessed, this feature won't do + * anything anyway. + */ + if (!vmx->nested.apic_access_page) + exec_control &= + ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES; + else + vmcs_write64(APIC_ACCESS_ADDR, + page_to_phys(vmx->nested.apic_access_page)); + } + + vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control); + } + + + /* + * Set host-state according to L0's settings (vmcs12 is irrelevant here) + * Some constant fields are set here by vmx_set_constant_host_state(). + * Other fields are different per CPU, and will be set later when + * vmx_vcpu_load() is called, and when vmx_save_host_state() is called. + */ + vmx_set_constant_host_state(vmx); + + /* + * HOST_RSP is normally set correctly in vmx_vcpu_run() just before + * entry, but only if the current (host) sp changed from the value + * we wrote last (vmx->host_rsp). This cache is no longer relevant + * if we switch vmcs, and rather than hold a separate cache per vmcs, + * here we just force the write to happen on entry. + */ + vmx->host_rsp = 0; + + exec_control = vmx_exec_control(vmx); /* L0's desires */ + exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING; + exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING; + exec_control &= ~CPU_BASED_TPR_SHADOW; + exec_control |= vmcs12->cpu_based_vm_exec_control; + /* + * Merging of IO and MSR bitmaps not currently supported. + * Rather, exit every time. + */ + exec_control &= ~CPU_BASED_USE_MSR_BITMAPS; + exec_control &= ~CPU_BASED_USE_IO_BITMAPS; + exec_control |= CPU_BASED_UNCOND_IO_EXITING; + + vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control); + + /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the + * bitwise-or of what L1 wants to trap for L2, and what we want to + * trap. Note that CR0.TS also needs updating - we do this later. + */ + update_exception_bitmap(vcpu); + vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask; + vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits); + + /* L2->L1 exit controls are emulated - the hardware exit is to L0 so + * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER + * bits are further modified by vmx_set_efer() below. + */ + vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl); + + /* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are + * emulated by vmx_set_efer(), below. + */ + vmcs_write32(VM_ENTRY_CONTROLS, + (vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER & + ~VM_ENTRY_IA32E_MODE) | + (vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE)); + + if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT) + vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat); + else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) + vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat); + + + set_cr4_guest_host_mask(vmx); + + if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING) + vmcs_write64(TSC_OFFSET, + vmx->nested.vmcs01_tsc_offset + vmcs12->tsc_offset); + else + vmcs_write64(TSC_OFFSET, vmx->nested.vmcs01_tsc_offset); + + if (enable_vpid) { + /* + * Trivially support vpid by letting L2s share their parent + * L1's vpid. TODO: move to a more elaborate solution, giving + * each L2 its own vpid and exposing the vpid feature to L1. + */ + vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid); + vmx_flush_tlb(vcpu); + } + + if (nested_cpu_has_ept(vmcs12)) { + kvm_mmu_unload(vcpu); + nested_ept_init_mmu_context(vcpu); + } + + if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER) + vcpu->arch.efer = vmcs12->guest_ia32_efer; + else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) + vcpu->arch.efer |= (EFER_LMA | EFER_LME); + else + vcpu->arch.efer &= ~(EFER_LMA | EFER_LME); + /* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */ + vmx_set_efer(vcpu, vcpu->arch.efer); + + /* + * This sets GUEST_CR0 to vmcs12->guest_cr0, with possibly a modified + * TS bit (for lazy fpu) and bits which we consider mandatory enabled. + * The CR0_READ_SHADOW is what L2 should have expected to read given + * the specifications by L1; It's not enough to take + * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we + * have more bits than L1 expected. + */ + vmx_set_cr0(vcpu, vmcs12->guest_cr0); + vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12)); + + vmx_set_cr4(vcpu, vmcs12->guest_cr4); + vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12)); + + /* shadow page tables on either EPT or shadow page tables */ + kvm_set_cr3(vcpu, vmcs12->guest_cr3); + kvm_mmu_reset_context(vcpu); + + /* + * L1 may access the L2's PDPTR, so save them to construct vmcs12 + */ + if (enable_ept) { + vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0); + vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1); + vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2); + vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3); + } + + kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp); + kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip); +} +",0,"static void prepare_vmcs02(struct kvm_vcpu *vcpu, struct vmcs12 *vmcs12) +{ + struct vcpu_vmx *vmx = to_vmx(vcpu); + u32 exec_control; + + vmcs_write16(GUEST_ES_SELECTOR, vmcs12->guest_es_selector); + vmcs_write16(GUEST_CS_SELECTOR, vmcs12->guest_cs_selector); + vmcs_write16(GUEST_SS_SELECTOR, vmcs12->guest_ss_selector); + vmcs_write16(GUEST_DS_SELECTOR, vmcs12->guest_ds_selector); + vmcs_write16(GUEST_FS_SELECTOR, vmcs12->guest_fs_selector); + vmcs_write16(GUEST_GS_SELECTOR, vmcs12->guest_gs_selector); + vmcs_write16(GUEST_LDTR_SELECTOR, vmcs12->guest_ldtr_selector); + vmcs_write16(GUEST_TR_SELECTOR, vmcs12->guest_tr_selector); + vmcs_write32(GUEST_ES_LIMIT, vmcs12->guest_es_limit); + vmcs_write32(GUEST_CS_LIMIT, vmcs12->guest_cs_limit); + vmcs_write32(GUEST_SS_LIMIT, vmcs12->guest_ss_limit); + vmcs_write32(GUEST_DS_LIMIT, vmcs12->guest_ds_limit); + vmcs_write32(GUEST_FS_LIMIT, vmcs12->guest_fs_limit); + vmcs_write32(GUEST_GS_LIMIT, vmcs12->guest_gs_limit); + vmcs_write32(GUEST_LDTR_LIMIT, vmcs12->guest_ldtr_limit); + vmcs_write32(GUEST_TR_LIMIT, vmcs12->guest_tr_limit); + vmcs_write32(GUEST_GDTR_LIMIT, vmcs12->guest_gdtr_limit); + vmcs_write32(GUEST_IDTR_LIMIT, vmcs12->guest_idtr_limit); + vmcs_write32(GUEST_ES_AR_BYTES, vmcs12->guest_es_ar_bytes); + vmcs_write32(GUEST_CS_AR_BYTES, vmcs12->guest_cs_ar_bytes); + vmcs_write32(GUEST_SS_AR_BYTES, vmcs12->guest_ss_ar_bytes); + vmcs_write32(GUEST_DS_AR_BYTES, vmcs12->guest_ds_ar_bytes); + vmcs_write32(GUEST_FS_AR_BYTES, vmcs12->guest_fs_ar_bytes); + vmcs_write32(GUEST_GS_AR_BYTES, vmcs12->guest_gs_ar_bytes); + vmcs_write32(GUEST_LDTR_AR_BYTES, vmcs12->guest_ldtr_ar_bytes); + vmcs_write32(GUEST_TR_AR_BYTES, vmcs12->guest_tr_ar_bytes); + vmcs_writel(GUEST_ES_BASE, vmcs12->guest_es_base); + vmcs_writel(GUEST_CS_BASE, vmcs12->guest_cs_base); + vmcs_writel(GUEST_SS_BASE, vmcs12->guest_ss_base); + vmcs_writel(GUEST_DS_BASE, vmcs12->guest_ds_base); + vmcs_writel(GUEST_FS_BASE, vmcs12->guest_fs_base); + vmcs_writel(GUEST_GS_BASE, vmcs12->guest_gs_base); + vmcs_writel(GUEST_LDTR_BASE, vmcs12->guest_ldtr_base); + vmcs_writel(GUEST_TR_BASE, vmcs12->guest_tr_base); + vmcs_writel(GUEST_GDTR_BASE, vmcs12->guest_gdtr_base); + vmcs_writel(GUEST_IDTR_BASE, vmcs12->guest_idtr_base); + + vmcs_write64(GUEST_IA32_DEBUGCTL, vmcs12->guest_ia32_debugctl); + vmcs_write32(VM_ENTRY_INTR_INFO_FIELD, + vmcs12->vm_entry_intr_info_field); + vmcs_write32(VM_ENTRY_EXCEPTION_ERROR_CODE, + vmcs12->vm_entry_exception_error_code); + vmcs_write32(VM_ENTRY_INSTRUCTION_LEN, + vmcs12->vm_entry_instruction_len); + vmcs_write32(GUEST_INTERRUPTIBILITY_INFO, + vmcs12->guest_interruptibility_info); + vmcs_write32(GUEST_SYSENTER_CS, vmcs12->guest_sysenter_cs); + kvm_set_dr(vcpu, 7, vmcs12->guest_dr7); + vmx_set_rflags(vcpu, vmcs12->guest_rflags); + vmcs_writel(GUEST_PENDING_DBG_EXCEPTIONS, + vmcs12->guest_pending_dbg_exceptions); + vmcs_writel(GUEST_SYSENTER_ESP, vmcs12->guest_sysenter_esp); + vmcs_writel(GUEST_SYSENTER_EIP, vmcs12->guest_sysenter_eip); + + vmcs_write64(VMCS_LINK_POINTER, -1ull); + + vmcs_write32(PIN_BASED_VM_EXEC_CONTROL, + (vmcs_config.pin_based_exec_ctrl | + vmcs12->pin_based_vm_exec_control)); + + if (vmcs12->pin_based_vm_exec_control & PIN_BASED_VMX_PREEMPTION_TIMER) + vmcs_write32(VMX_PREEMPTION_TIMER_VALUE, + vmcs12->vmx_preemption_timer_value); + + /* + * Whether page-faults are trapped is determined by a combination of + * 3 settings: PFEC_MASK, PFEC_MATCH and EXCEPTION_BITMAP.PF. + * If enable_ept, L0 doesn't care about page faults and we should + * set all of these to L1's desires. However, if !enable_ept, L0 does + * care about (at least some) page faults, and because it is not easy + * (if at all possible?) to merge L0 and L1's desires, we simply ask + * to exit on each and every L2 page fault. This is done by setting + * MASK=MATCH=0 and (see below) EB.PF=1. + * Note that below we don't need special code to set EB.PF beyond the + * ""or""ing of the EB of vmcs01 and vmcs12, because when enable_ept, + * vmcs01's EB.PF is 0 so the ""or"" will take vmcs12's value, and when + * !enable_ept, EB.PF is 1, so the ""or"" will always be 1. + * + * A problem with this approach (when !enable_ept) is that L1 may be + * injected with more page faults than it asked for. This could have + * caused problems, but in practice existing hypervisors don't care. + * To fix this, we will need to emulate the PFEC checking (on the L1 + * page tables), using walk_addr(), when injecting PFs to L1. + */ + vmcs_write32(PAGE_FAULT_ERROR_CODE_MASK, + enable_ept ? vmcs12->page_fault_error_code_mask : 0); + vmcs_write32(PAGE_FAULT_ERROR_CODE_MATCH, + enable_ept ? vmcs12->page_fault_error_code_match : 0); + + if (cpu_has_secondary_exec_ctrls()) { + u32 exec_control = vmx_secondary_exec_control(vmx); + if (!vmx->rdtscp_enabled) + exec_control &= ~SECONDARY_EXEC_RDTSCP; + /* Take the following fields only from vmcs12 */ + exec_control &= ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES; + if (nested_cpu_has(vmcs12, + CPU_BASED_ACTIVATE_SECONDARY_CONTROLS)) + exec_control |= vmcs12->secondary_vm_exec_control; + + if (exec_control & SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES) { + /* + * Translate L1 physical address to host physical + * address for vmcs02. Keep the page pinned, so this + * physical address remains valid. We keep a reference + * to it so we can release it later. + */ + if (vmx->nested.apic_access_page) /* shouldn't happen */ + nested_release_page(vmx->nested.apic_access_page); + vmx->nested.apic_access_page = + nested_get_page(vcpu, vmcs12->apic_access_addr); + /* + * If translation failed, no matter: This feature asks + * to exit when accessing the given address, and if it + * can never be accessed, this feature won't do + * anything anyway. + */ + if (!vmx->nested.apic_access_page) + exec_control &= + ~SECONDARY_EXEC_VIRTUALIZE_APIC_ACCESSES; + else + vmcs_write64(APIC_ACCESS_ADDR, + page_to_phys(vmx->nested.apic_access_page)); + } + + vmcs_write32(SECONDARY_VM_EXEC_CONTROL, exec_control); + } + + + /* + * Set host-state according to L0's settings (vmcs12 is irrelevant here) + * Some constant fields are set here by vmx_set_constant_host_state(). + * Other fields are different per CPU, and will be set later when + * vmx_vcpu_load() is called, and when vmx_save_host_state() is called. + */ + vmx_set_constant_host_state(vmx); + + /* + * HOST_RSP is normally set correctly in vmx_vcpu_run() just before + * entry, but only if the current (host) sp changed from the value + * we wrote last (vmx->host_rsp). This cache is no longer relevant + * if we switch vmcs, and rather than hold a separate cache per vmcs, + * here we just force the write to happen on entry. + */ + vmx->host_rsp = 0; + + exec_control = vmx_exec_control(vmx); /* L0's desires */ + exec_control &= ~CPU_BASED_VIRTUAL_INTR_PENDING; + exec_control &= ~CPU_BASED_VIRTUAL_NMI_PENDING; + exec_control &= ~CPU_BASED_TPR_SHADOW; + exec_control |= vmcs12->cpu_based_vm_exec_control; + /* + * Merging of IO and MSR bitmaps not currently supported. + * Rather, exit every time. + */ + exec_control &= ~CPU_BASED_USE_MSR_BITMAPS; + exec_control &= ~CPU_BASED_USE_IO_BITMAPS; + exec_control |= CPU_BASED_UNCOND_IO_EXITING; + + vmcs_write32(CPU_BASED_VM_EXEC_CONTROL, exec_control); + + /* EXCEPTION_BITMAP and CR0_GUEST_HOST_MASK should basically be the + * bitwise-or of what L1 wants to trap for L2, and what we want to + * trap. Note that CR0.TS also needs updating - we do this later. + */ + update_exception_bitmap(vcpu); + vcpu->arch.cr0_guest_owned_bits &= ~vmcs12->cr0_guest_host_mask; + vmcs_writel(CR0_GUEST_HOST_MASK, ~vcpu->arch.cr0_guest_owned_bits); + + /* L2->L1 exit controls are emulated - the hardware exit is to L0 so + * we should use its exit controls. Note that VM_EXIT_LOAD_IA32_EFER + * bits are further modified by vmx_set_efer() below. + */ + vmcs_write32(VM_EXIT_CONTROLS, vmcs_config.vmexit_ctrl); + + /* vmcs12's VM_ENTRY_LOAD_IA32_EFER and VM_ENTRY_IA32E_MODE are + * emulated by vmx_set_efer(), below. + */ + vmcs_write32(VM_ENTRY_CONTROLS, + (vmcs12->vm_entry_controls & ~VM_ENTRY_LOAD_IA32_EFER & + ~VM_ENTRY_IA32E_MODE) | + (vmcs_config.vmentry_ctrl & ~VM_ENTRY_IA32E_MODE)); + + if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_PAT) + vmcs_write64(GUEST_IA32_PAT, vmcs12->guest_ia32_pat); + else if (vmcs_config.vmentry_ctrl & VM_ENTRY_LOAD_IA32_PAT) + vmcs_write64(GUEST_IA32_PAT, vmx->vcpu.arch.pat); + + + set_cr4_guest_host_mask(vmx); + + if (vmcs12->cpu_based_vm_exec_control & CPU_BASED_USE_TSC_OFFSETING) + vmcs_write64(TSC_OFFSET, + vmx->nested.vmcs01_tsc_offset + vmcs12->tsc_offset); + else + vmcs_write64(TSC_OFFSET, vmx->nested.vmcs01_tsc_offset); + + if (enable_vpid) { + /* + * Trivially support vpid by letting L2s share their parent + * L1's vpid. TODO: move to a more elaborate solution, giving + * each L2 its own vpid and exposing the vpid feature to L1. + */ + vmcs_write16(VIRTUAL_PROCESSOR_ID, vmx->vpid); + vmx_flush_tlb(vcpu); + } + + if (nested_cpu_has_ept(vmcs12)) { + kvm_mmu_unload(vcpu); + nested_ept_init_mmu_context(vcpu); + } + + if (vmcs12->vm_entry_controls & VM_ENTRY_LOAD_IA32_EFER) + vcpu->arch.efer = vmcs12->guest_ia32_efer; + else if (vmcs12->vm_entry_controls & VM_ENTRY_IA32E_MODE) + vcpu->arch.efer |= (EFER_LMA | EFER_LME); + else + vcpu->arch.efer &= ~(EFER_LMA | EFER_LME); + /* Note: modifies VM_ENTRY/EXIT_CONTROLS and GUEST/HOST_IA32_EFER */ + vmx_set_efer(vcpu, vcpu->arch.efer); + + /* + * This sets GUEST_CR0 to vmcs12->guest_cr0, with possibly a modified + * TS bit (for lazy fpu) and bits which we consider mandatory enabled. + * The CR0_READ_SHADOW is what L2 should have expected to read given + * the specifications by L1; It's not enough to take + * vmcs12->cr0_read_shadow because on our cr0_guest_host_mask we we + * have more bits than L1 expected. + */ + vmx_set_cr0(vcpu, vmcs12->guest_cr0); + vmcs_writel(CR0_READ_SHADOW, nested_read_cr0(vmcs12)); + + vmx_set_cr4(vcpu, vmcs12->guest_cr4); + vmcs_writel(CR4_READ_SHADOW, nested_read_cr4(vmcs12)); + + /* shadow page tables on either EPT or shadow page tables */ + kvm_set_cr3(vcpu, vmcs12->guest_cr3); + kvm_mmu_reset_context(vcpu); + + /* + * L1 may access the L2's PDPTR, so save them to construct vmcs12 + */ + if (enable_ept) { + vmcs_write64(GUEST_PDPTR0, vmcs12->guest_pdptr0); + vmcs_write64(GUEST_PDPTR1, vmcs12->guest_pdptr1); + vmcs_write64(GUEST_PDPTR2, vmcs12->guest_pdptr2); + vmcs_write64(GUEST_PDPTR3, vmcs12->guest_pdptr3); + } + + kvm_register_write(vcpu, VCPU_REGS_RSP, vmcs12->guest_rsp); + kvm_register_write(vcpu, VCPU_REGS_RIP, vmcs12->guest_rip); +} +","@@ -712,6 +712,7 @@ static void nested_release_page_clean(struct page *page) + kvm_release_page_clean(page); + } + ++static unsigned long nested_ept_get_cr3(struct kvm_vcpu *vcpu); + static u64 construct_eptp(unsigned long root_hpa); + static void kvm_cpu_vmxon(u64 addr); + static void kvm_cpu_vmxoff(void); +@@ -2161,6 +2162,7 @@ static u32 nested_vmx_pinbased_ctls_low, nested_vmx_pinbased_ctls_high; + static u32 nested_vmx_exit_ctls_low, nested_vmx_exit_ctls_high; + static u32 nested_vmx_entry_ctls_low, nested_vmx_entry_ctls_high; + static u32 nested_vmx_misc_low, nested_vmx_misc_high; ++static u32 nested_vmx_ept_caps; + static __init void nested_vmx_setup_ctls_msrs(void) + { + /* +@@ -6279,6 +6281,74 @@ static int handle_vmptrst(struct kvm_vcpu *vcpu) + return 1; + } + ++/* Emulate the INVEPT instruction */ ++static int handle_invept(struct kvm_vcpu *vcpu) ++{ ++ u32 vmx_instruction_info, types; ++ unsigned long type; ++ gva_t gva; ++ struct x86_exception e; ++ struct { ++ u64 eptp, gpa; ++ } operand; ++ u64 eptp_mask = ((1ull << 51) - 1) & PAGE_MASK; ++ ++ if (!(nested_vmx_secondary_ctls_high & SECONDARY_EXEC_ENABLE_EPT) || ++ !(nested_vmx_ept_caps & VMX_EPT_INVEPT_BIT)) { ++ kvm_queue_exception(vcpu, UD_VECTOR); ++ return 1; ++ } ++ ++ if (!nested_vmx_check_permission(vcpu)) ++ return 1; ++ ++ if (!kvm_read_cr0_bits(vcpu, X86_CR0_PE)) { ++ kvm_queue_exception(vcpu, UD_VECTOR); ++ return 1; ++ } ++ ++ vmx_instruction_info = vmcs_read32(VMX_INSTRUCTION_INFO); ++ type = kvm_register_read(vcpu, (vmx_instruction_info >> 28) & 0xf); ++ ++ types = (nested_vmx_ept_caps >> VMX_EPT_EXTENT_SHIFT) & 6; ++ ++ if (!(types & (1UL << type))) { ++ nested_vmx_failValid(vcpu, ++ VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID); ++ return 1; ++ } ++ ++ /* According to the Intel VMX instruction reference, the memory ++ * operand is read even if it isn't needed (e.g., for type==global) ++ */ ++ if (get_vmx_mem_address(vcpu, vmcs_readl(EXIT_QUALIFICATION), ++ vmx_instruction_info, &gva)) ++ return 1; ++ if (kvm_read_guest_virt(&vcpu->arch.emulate_ctxt, gva, &operand, ++ sizeof(operand), &e)) { ++ kvm_inject_page_fault(vcpu, &e); ++ return 1; ++ } ++ ++ switch (type) { ++ case VMX_EPT_EXTENT_CONTEXT: ++ if ((operand.eptp & eptp_mask) != ++ (nested_ept_get_cr3(vcpu) & eptp_mask)) ++ break; ++ case VMX_EPT_EXTENT_GLOBAL: ++ kvm_mmu_sync_roots(vcpu); ++ kvm_mmu_flush_tlb(vcpu); ++ nested_vmx_succeed(vcpu); ++ break; ++ default: ++ BUG_ON(1); ++ break; ++ } ++ ++ skip_emulated_instruction(vcpu); ++ return 1; ++} ++ + /* + * The exit handlers return 1 if the exit was handled fully and guest execution + * may resume. Otherwise they set the kvm_run parameter to indicate what needs +@@ -6323,6 +6393,7 @@ static int (*const kvm_vmx_exit_handlers[])(struct kvm_vcpu *vcpu) = { + [EXIT_REASON_PAUSE_INSTRUCTION] = handle_pause, + [EXIT_REASON_MWAIT_INSTRUCTION] = handle_invalid_op, + [EXIT_REASON_MONITOR_INSTRUCTION] = handle_invalid_op, ++ [EXIT_REASON_INVEPT] = handle_invept, + }; + + static const int kvm_vmx_max_exit_handlers = +@@ -6549,6 +6620,7 @@ static bool nested_vmx_exit_handled(struct kvm_vcpu *vcpu) + case EXIT_REASON_VMPTRST: case EXIT_REASON_VMREAD: + case EXIT_REASON_VMRESUME: case EXIT_REASON_VMWRITE: + case EXIT_REASON_VMOFF: case EXIT_REASON_VMON: ++ case EXIT_REASON_INVEPT: + /* + * VMX instructions trap unconditionally. This allows L1 to + * emulate them for its L2 guest, i.e., allows 3-level nesting!",3361,3692,4096 +1575,"static void vmxnet3_activate_device(VMXNET3State *s) +{ + int i; + static const uint32_t VMXNET3_DEF_TX_THRESHOLD = 1; + hwaddr qdescr_table_pa; + uint64_t pa; + uint32_t size; + + /* Verify configuration consistency */ + if (!vmxnet3_verify_driver_magic(s->drv_shmem)) { + VMW_ERPRN(""Device configuration received from driver is invalid""); + return; + } + + vmxnet3_adjust_by_guest_type(s); + vmxnet3_update_features(s); + vmxnet3_update_pm_state(s); + vmxnet3_setup_rx_filtering(s); + /* Cache fields from shared memory */ + s->mtu = VMXNET3_READ_DRV_SHARED32(s->drv_shmem, devRead.misc.mtu); + VMW_CFPRN(""MTU is %u"", s->mtu); + + s->max_rx_frags = + VMXNET3_READ_DRV_SHARED16(s->drv_shmem, devRead.misc.maxNumRxSG); + + if (s->max_rx_frags == 0) { + s->max_rx_frags = 1; + } + + VMW_CFPRN(""Max RX fragments is %u"", s->max_rx_frags); + + s->event_int_idx = + VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.intrConf.eventIntrIdx); + assert(vmxnet3_verify_intx(s, s->event_int_idx)); + VMW_CFPRN(""Events interrupt line is %u"", s->event_int_idx); + + s->auto_int_masking = + VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.intrConf.autoMask); + VMW_CFPRN(""Automatic interrupt masking is %d"", (int)s->auto_int_masking); + + s->txq_num = + VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numTxQueues); + s->rxq_num = + VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numRxQueues); + + VMW_CFPRN(""Number of TX/RX queues %u/%u"", s->txq_num, s->rxq_num); + vmxnet3_validate_queues(s); + + qdescr_table_pa = + VMXNET3_READ_DRV_SHARED64(s->drv_shmem, devRead.misc.queueDescPA); + VMW_CFPRN(""TX queues descriptors table is at 0x%"" PRIx64, qdescr_table_pa); + + /* + * Worst-case scenario is a packet that holds all TX rings space so + * we calculate total size of all TX rings for max TX fragments number + */ + s->max_tx_frags = 0; + + /* TX queues */ + for (i = 0; i < s->txq_num; i++) { + hwaddr qdescr_pa = + qdescr_table_pa + i * sizeof(struct Vmxnet3_TxQueueDesc); + + /* Read interrupt number for this TX queue */ + s->txq_descr[i].intr_idx = + VMXNET3_READ_TX_QUEUE_DESCR8(qdescr_pa, conf.intrIdx); + assert(vmxnet3_verify_intx(s, s->txq_descr[i].intr_idx)); + + VMW_CFPRN(""TX Queue %d interrupt: %d"", i, s->txq_descr[i].intr_idx); + + /* Read rings memory locations for TX queues */ + pa = VMXNET3_READ_TX_QUEUE_DESCR64(qdescr_pa, conf.txRingBasePA); + size = VMXNET3_READ_TX_QUEUE_DESCR32(qdescr_pa, conf.txRingSize); + + vmxnet3_ring_init(&s->txq_descr[i].tx_ring, pa, size, + sizeof(struct Vmxnet3_TxDesc), false); + VMXNET3_RING_DUMP(VMW_CFPRN, ""TX"", i, &s->txq_descr[i].tx_ring); + + s->max_tx_frags += size; + + /* TXC ring */ + pa = VMXNET3_READ_TX_QUEUE_DESCR64(qdescr_pa, conf.compRingBasePA); + size = VMXNET3_READ_TX_QUEUE_DESCR32(qdescr_pa, conf.compRingSize); + vmxnet3_ring_init(&s->txq_descr[i].comp_ring, pa, size, + sizeof(struct Vmxnet3_TxCompDesc), true); + VMXNET3_RING_DUMP(VMW_CFPRN, ""TXC"", i, &s->txq_descr[i].comp_ring); + + s->txq_descr[i].tx_stats_pa = + qdescr_pa + offsetof(struct Vmxnet3_TxQueueDesc, stats); + + memset(&s->txq_descr[i].txq_stats, 0, + sizeof(s->txq_descr[i].txq_stats)); + + /* Fill device-managed parameters for queues */ + VMXNET3_WRITE_TX_QUEUE_DESCR32(qdescr_pa, + ctrl.txThreshold, + VMXNET3_DEF_TX_THRESHOLD); + } + + /* Preallocate TX packet wrapper */ + VMW_CFPRN(""Max TX fragments is %u"", s->max_tx_frags); + vmxnet_tx_pkt_init(&s->tx_pkt, s->max_tx_frags, s->peer_has_vhdr); + vmxnet_rx_pkt_init(&s->rx_pkt, s->peer_has_vhdr); + + /* Read rings memory locations for RX queues */ + for (i = 0; i < s->rxq_num; i++) { + int j; + hwaddr qd_pa = + qdescr_table_pa + s->txq_num * sizeof(struct Vmxnet3_TxQueueDesc) + + i * sizeof(struct Vmxnet3_RxQueueDesc); + + /* Read interrupt number for this RX queue */ + s->rxq_descr[i].intr_idx = + VMXNET3_READ_TX_QUEUE_DESCR8(qd_pa, conf.intrIdx); + assert(vmxnet3_verify_intx(s, s->rxq_descr[i].intr_idx)); + + VMW_CFPRN(""RX Queue %d interrupt: %d"", i, s->rxq_descr[i].intr_idx); + + /* Read rings memory locations */ + for (j = 0; j < VMXNET3_RX_RINGS_PER_QUEUE; j++) { + /* RX rings */ + pa = VMXNET3_READ_RX_QUEUE_DESCR64(qd_pa, conf.rxRingBasePA[j]); + size = VMXNET3_READ_RX_QUEUE_DESCR32(qd_pa, conf.rxRingSize[j]); + vmxnet3_ring_init(&s->rxq_descr[i].rx_ring[j], pa, size, + sizeof(struct Vmxnet3_RxDesc), false); + VMW_CFPRN(""RX queue %d:%d: Base: %"" PRIx64 "", Size: %d"", + i, j, pa, size); + } + + /* RXC ring */ + pa = VMXNET3_READ_RX_QUEUE_DESCR64(qd_pa, conf.compRingBasePA); + size = VMXNET3_READ_RX_QUEUE_DESCR32(qd_pa, conf.compRingSize); + vmxnet3_ring_init(&s->rxq_descr[i].comp_ring, pa, size, + sizeof(struct Vmxnet3_RxCompDesc), true); + VMW_CFPRN(""RXC queue %d: Base: %"" PRIx64 "", Size: %d"", i, pa, size); + + s->rxq_descr[i].rx_stats_pa = + qd_pa + offsetof(struct Vmxnet3_RxQueueDesc, stats); + memset(&s->rxq_descr[i].rxq_stats, 0, + sizeof(s->rxq_descr[i].rxq_stats)); + } + + vmxnet3_validate_interrupts(s); + + /* Make sure everything is in place before device activation */ + smp_wmb(); + + vmxnet3_reset_mac(s); + + s->device_active = true; +} +",0,"static void vmxnet3_activate_device(VMXNET3State *s) +{ + int i; + static const uint32_t VMXNET3_DEF_TX_THRESHOLD = 1; + hwaddr qdescr_table_pa; + uint64_t pa; + uint32_t size; + + /* Verify configuration consistency */ + if (!vmxnet3_verify_driver_magic(s->drv_shmem)) { + VMW_ERPRN(""Device configuration received from driver is invalid""); + return; + } + + vmxnet3_adjust_by_guest_type(s); + vmxnet3_update_features(s); + vmxnet3_update_pm_state(s); + vmxnet3_setup_rx_filtering(s); + /* Cache fields from shared memory */ + s->mtu = VMXNET3_READ_DRV_SHARED32(s->drv_shmem, devRead.misc.mtu); + VMW_CFPRN(""MTU is %u"", s->mtu); + + s->max_rx_frags = + VMXNET3_READ_DRV_SHARED16(s->drv_shmem, devRead.misc.maxNumRxSG); + + if (s->max_rx_frags == 0) { + s->max_rx_frags = 1; + } + + VMW_CFPRN(""Max RX fragments is %u"", s->max_rx_frags); + + s->event_int_idx = + VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.intrConf.eventIntrIdx); + assert(vmxnet3_verify_intx(s, s->event_int_idx)); + VMW_CFPRN(""Events interrupt line is %u"", s->event_int_idx); + + s->auto_int_masking = + VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.intrConf.autoMask); + VMW_CFPRN(""Automatic interrupt masking is %d"", (int)s->auto_int_masking); + + s->txq_num = + VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numTxQueues); + s->rxq_num = + VMXNET3_READ_DRV_SHARED8(s->drv_shmem, devRead.misc.numRxQueues); + + VMW_CFPRN(""Number of TX/RX queues %u/%u"", s->txq_num, s->rxq_num); + vmxnet3_validate_queues(s); + + qdescr_table_pa = + VMXNET3_READ_DRV_SHARED64(s->drv_shmem, devRead.misc.queueDescPA); + VMW_CFPRN(""TX queues descriptors table is at 0x%"" PRIx64, qdescr_table_pa); + + /* + * Worst-case scenario is a packet that holds all TX rings space so + * we calculate total size of all TX rings for max TX fragments number + */ + s->max_tx_frags = 0; + + /* TX queues */ + for (i = 0; i < s->txq_num; i++) { + hwaddr qdescr_pa = + qdescr_table_pa + i * sizeof(struct Vmxnet3_TxQueueDesc); + + /* Read interrupt number for this TX queue */ + s->txq_descr[i].intr_idx = + VMXNET3_READ_TX_QUEUE_DESCR8(qdescr_pa, conf.intrIdx); + assert(vmxnet3_verify_intx(s, s->txq_descr[i].intr_idx)); + + VMW_CFPRN(""TX Queue %d interrupt: %d"", i, s->txq_descr[i].intr_idx); + + /* Read rings memory locations for TX queues */ + pa = VMXNET3_READ_TX_QUEUE_DESCR64(qdescr_pa, conf.txRingBasePA); + size = VMXNET3_READ_TX_QUEUE_DESCR32(qdescr_pa, conf.txRingSize); + + vmxnet3_ring_init(&s->txq_descr[i].tx_ring, pa, size, + sizeof(struct Vmxnet3_TxDesc), false); + VMXNET3_RING_DUMP(VMW_CFPRN, ""TX"", i, &s->txq_descr[i].tx_ring); + + s->max_tx_frags += size; + + /* TXC ring */ + pa = VMXNET3_READ_TX_QUEUE_DESCR64(qdescr_pa, conf.compRingBasePA); + size = VMXNET3_READ_TX_QUEUE_DESCR32(qdescr_pa, conf.compRingSize); + vmxnet3_ring_init(&s->txq_descr[i].comp_ring, pa, size, + sizeof(struct Vmxnet3_TxCompDesc), true); + VMXNET3_RING_DUMP(VMW_CFPRN, ""TXC"", i, &s->txq_descr[i].comp_ring); + + s->txq_descr[i].tx_stats_pa = + qdescr_pa + offsetof(struct Vmxnet3_TxQueueDesc, stats); + + memset(&s->txq_descr[i].txq_stats, 0, + sizeof(s->txq_descr[i].txq_stats)); + + /* Fill device-managed parameters for queues */ + VMXNET3_WRITE_TX_QUEUE_DESCR32(qdescr_pa, + ctrl.txThreshold, + VMXNET3_DEF_TX_THRESHOLD); + } + + /* Preallocate TX packet wrapper */ + VMW_CFPRN(""Max TX fragments is %u"", s->max_tx_frags); + vmxnet_tx_pkt_init(&s->tx_pkt, s->max_tx_frags, s->peer_has_vhdr); + vmxnet_rx_pkt_init(&s->rx_pkt, s->peer_has_vhdr); + + /* Read rings memory locations for RX queues */ + for (i = 0; i < s->rxq_num; i++) { + int j; + hwaddr qd_pa = + qdescr_table_pa + s->txq_num * sizeof(struct Vmxnet3_TxQueueDesc) + + i * sizeof(struct Vmxnet3_RxQueueDesc); + + /* Read interrupt number for this RX queue */ + s->rxq_descr[i].intr_idx = + VMXNET3_READ_TX_QUEUE_DESCR8(qd_pa, conf.intrIdx); + assert(vmxnet3_verify_intx(s, s->rxq_descr[i].intr_idx)); + + VMW_CFPRN(""RX Queue %d interrupt: %d"", i, s->rxq_descr[i].intr_idx); + + /* Read rings memory locations */ + for (j = 0; j < VMXNET3_RX_RINGS_PER_QUEUE; j++) { + /* RX rings */ + pa = VMXNET3_READ_RX_QUEUE_DESCR64(qd_pa, conf.rxRingBasePA[j]); + size = VMXNET3_READ_RX_QUEUE_DESCR32(qd_pa, conf.rxRingSize[j]); + vmxnet3_ring_init(&s->rxq_descr[i].rx_ring[j], pa, size, + sizeof(struct Vmxnet3_RxDesc), false); + VMW_CFPRN(""RX queue %d:%d: Base: %"" PRIx64 "", Size: %d"", + i, j, pa, size); + } + + /* RXC ring */ + pa = VMXNET3_READ_RX_QUEUE_DESCR64(qd_pa, conf.compRingBasePA); + size = VMXNET3_READ_RX_QUEUE_DESCR32(qd_pa, conf.compRingSize); + vmxnet3_ring_init(&s->rxq_descr[i].comp_ring, pa, size, + sizeof(struct Vmxnet3_RxCompDesc), true); + VMW_CFPRN(""RXC queue %d: Base: %"" PRIx64 "", Size: %d"", i, pa, size); + + s->rxq_descr[i].rx_stats_pa = + qd_pa + offsetof(struct Vmxnet3_RxQueueDesc, stats); + memset(&s->rxq_descr[i].rxq_stats, 0, + sizeof(s->rxq_descr[i].rxq_stats)); + } + + vmxnet3_validate_interrupts(s); + + /* Make sure everything is in place before device activation */ + smp_wmb(); + + vmxnet3_reset_mac(s); + + s->device_active = true; +} +","@@ -2391,6 +2391,8 @@ static int vmxnet3_post_load(void *opaque, int version_id) + } + } + ++ vmxnet3_validate_interrupts(s); ++ + return 0; + }",1730,2061,4096 +18749,"static void ProcessExifDir(unsigned char * DirStart, unsigned char * OffsetBase, + unsigned ExifLength, int NestingLevel) +{ + int de; + int a; + int NumDirEntries; + unsigned ThumbnailOffset = 0; + unsigned ThumbnailSize = 0; + char IndentString[25]; + + printf(""ProcessExifDir""); + if (NestingLevel > 4){ + ErrNonfatal(""Maximum directory nesting exceeded (corrupt exif header)"", 0,0); + return; + } + + memset(IndentString, ' ', 25); + IndentString[NestingLevel * 4] = '\0'; + + + NumDirEntries = Get16u(DirStart); + #define DIR_ENTRY_ADDR(Start, Entry) (Start+2+12*(Entry)) + + { + unsigned char * DirEnd; + DirEnd = DIR_ENTRY_ADDR(DirStart, NumDirEntries); + if (DirEnd+4 > (OffsetBase+ExifLength)){ + if (DirEnd+2 == OffsetBase+ExifLength || DirEnd == OffsetBase+ExifLength){ + }else{ + ErrNonfatal(""Illegally sized exif subdirectory (%d entries)"",NumDirEntries,0); + return; + } + } + if (DumpExifMap){ + printf(""Map: %05d-%05d: Directory\n"",(int)(DirStart-OffsetBase), (int)(DirEnd+4-OffsetBase)); + } + + + } + + if (ShowTags){ + printf(""(dir has %d entries)\n"",NumDirEntries); + } + + for (de=0;de= NUM_FORMATS) { + ErrNonfatal(""Illegal number format %d for tag %04x"", Format, Tag); + continue; + } + + if ((unsigned)Components > 0x10000){ + ErrNonfatal(""Illegal number of components %d for tag %04x"", Components, Tag); + continue; + } + + ByteCount = Components * BytesPerFormat[Format]; + + if (ByteCount > 4){ + + unsigned OffsetVal; + OffsetVal = Get32u(DirEntry+8); + if (OffsetVal+ByteCount > ExifLength){ + ErrNonfatal(""Illegal value pointer for tag %04x"", Tag,0); + continue; + } + ValuePtr = OffsetBase+OffsetVal; + + if (OffsetVal > ImageInfo.LargestExifOffset){ + ImageInfo.LargestExifOffset = OffsetVal; + } + + if (DumpExifMap){ + printf(""Map: %05d-%05d: Data for tag %04x\n"",OffsetVal, OffsetVal+ByteCount, Tag); + } + }else{ + ValuePtr = DirEntry+8; + } + + if (Tag == TAG_MAKER_NOTE){ + if (ShowTags){ + printf(""%s Maker note: "",IndentString); + } + ProcessMakerNote(ValuePtr, ByteCount, OffsetBase, ExifLength); + continue; + } + + if (ShowTags){ + for (a=0;;a++){ + if (a >= (int)TAG_TABLE_SIZE){ + printf(""%s"", IndentString); + printf("" Unknown Tag %04x Value = "", Tag); + break; + } + if (TagTable[a].Tag == Tag){ + printf(""%s"", IndentString); + printf("" %s = "",TagTable[a].Desc); + break; + } + } + + switch(Format){ + case FMT_BYTE: + if(ByteCount>1){ + printf(""%.*ls\n"", ByteCount/2, (wchar_t *)ValuePtr); + }else{ + PrintFormatNumber(ValuePtr, Format, ByteCount); + printf(""\n""); + } + break; + + case FMT_UNDEFINED: + + case FMT_STRING: + { + printf(""\""%s\"""", ValuePtr); + } + break; + + default: + PrintFormatNumber(ValuePtr, Format, ByteCount); + printf(""\n""); + } + } + + switch(Tag){ + + case TAG_MAKE: + strncpy(ImageInfo.CameraMake, (char *)ValuePtr, ByteCount < 31 ? ByteCount : 31); + break; + + case TAG_MODEL: + strncpy(ImageInfo.CameraModel, (char *)ValuePtr, ByteCount < 39 ? ByteCount : 39); + break; + + case TAG_SUBSEC_TIME: + strlcpy(ImageInfo.SubSecTime, (char *)ValuePtr, sizeof(ImageInfo.SubSecTime)); + break; + + case TAG_SUBSEC_TIME_ORIG: + strlcpy(ImageInfo.SubSecTimeOrig, (char *)ValuePtr, + sizeof(ImageInfo.SubSecTimeOrig)); + break; + + case TAG_SUBSEC_TIME_DIG: + strlcpy(ImageInfo.SubSecTimeDig, (char *)ValuePtr, + sizeof(ImageInfo.SubSecTimeDig)); + break; + + case TAG_DATETIME_DIGITIZED: + strlcpy(ImageInfo.DigitizedTime, (char *)ValuePtr, + sizeof(ImageInfo.DigitizedTime)); + + if (ImageInfo.numDateTimeTags >= MAX_DATE_COPIES){ + ErrNonfatal(""More than %d date fields! This is nuts"", MAX_DATE_COPIES, 0); + break; + } + ImageInfo.DateTimeOffsets[ImageInfo.numDateTimeTags++] = + (char *)ValuePtr - (char *)OffsetBase; + break; + + case TAG_DATETIME_ORIGINAL: + strncpy(ImageInfo.DateTime, (char *)ValuePtr, 19); + + case TAG_DATETIME: + if (!isdigit(ImageInfo.DateTime[0])){ + strncpy(ImageInfo.DateTime, (char *)ValuePtr, 19); + } + + if (ImageInfo.numDateTimeTags >= MAX_DATE_COPIES){ + ErrNonfatal(""More than %d date fields! This is nuts"", MAX_DATE_COPIES, 0); + break; + } + ImageInfo.DateTimeOffsets[ImageInfo.numDateTimeTags++] = + (char *)ValuePtr - (char *)OffsetBase; + break; + + case TAG_WINXP_COMMENT: + if (ImageInfo.Comments[0]){ // We already have a jpeg comment. + if (ShowTags) printf(""Windows XP commend and other comment in header\n""); + break; // Already have a windows comment, skip this one. + } + + if (ByteCount > 1){ + if (ByteCount > MAX_COMMENT_SIZE) ByteCount = MAX_COMMENT_SIZE; + memcpy(ImageInfo.Comments, ValuePtr, ByteCount); + ImageInfo.CommentWidchars = ByteCount/2; + } + break; + + case TAG_USERCOMMENT: + if (ImageInfo.Comments[0]){ // We already have a jpeg comment. + if (ShowTags) printf(""Multiple comments in exif header\n""); + break; // Already have a windows comment, skip this one. + } + + for (a=ByteCount;;){ + a--; + if ((ValuePtr)[a] == ' '){ + (ValuePtr)[a] = '\0'; + }else{ + break; + } + if (a == 0) break; + } + + { + int msiz = ExifLength - (ValuePtr-OffsetBase); + if (msiz > ByteCount) msiz = ByteCount; + if (msiz > MAX_COMMENT_SIZE - 1) msiz = MAX_COMMENT_SIZE - 1; + if (msiz > 5 && memcmp(ValuePtr, ""ASCII"", 5) == 0) { + for (a = 5; a < 10 && a < msiz; a++) { + int c = (ValuePtr)[a]; + if (c != '\0' && c != ' ') { + strncpy(ImageInfo.Comments, + (char *)ValuePtr + a, msiz - a); + break; + } + } + } else { + strncpy(ImageInfo.Comments, (char *)ValuePtr, msiz); + } + } + break; + + case TAG_FNUMBER: + ImageInfo.ApertureFNumber = (float)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_APERTURE: + case TAG_MAXAPERTURE: + if (ImageInfo.ApertureFNumber == 0){ + ImageInfo.ApertureFNumber + = (float)exp(ConvertAnyFormat(ValuePtr, Format)*log(2)*0.5); + } + break; + + case TAG_FOCALLENGTH: + ImageInfo.FocalLength.num = Get32u(ValuePtr); + ImageInfo.FocalLength.denom = Get32u(4+(char *)ValuePtr); + break; + + case TAG_SUBJECT_DISTANCE: + ImageInfo.Distance = (float)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_EXPOSURETIME: + ImageInfo.ExposureTime = (float)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_SHUTTERSPEED: + if (ImageInfo.ExposureTime == 0){ + ImageInfo.ExposureTime + = (float)(1/exp(ConvertAnyFormat(ValuePtr, Format)*log(2))); + } + break; + + + case TAG_FLASH: + ImageInfo.FlashUsed=(int)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_ORIENTATION: + if (NumOrientations >= 2){ + ErrNonfatal(""More than two orientation tags!"",0,0); + break; + } + OrientationPtr[NumOrientations] = ValuePtr; + OrientationNumFormat[NumOrientations] = Format; + if (NumOrientations == 0){ + ImageInfo.Orientation = (int)ConvertAnyFormat(ValuePtr, Format); + } + if (ImageInfo.Orientation < 0 || ImageInfo.Orientation > 8){ + ErrNonfatal(""Undefined rotation value %d"", ImageInfo.Orientation, 0); + ImageInfo.Orientation = 0; + } + NumOrientations += 1; + break; + + case TAG_EXIF_IMAGELENGTH: + case TAG_EXIF_IMAGEWIDTH: + a = (int)ConvertAnyFormat(ValuePtr, Format); + if (ExifImageWidth < a) ExifImageWidth = a; + break; + + case TAG_FOCAL_PLANE_XRES: + FocalplaneXRes = ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_FOCAL_PLANE_UNITS: + switch((int)ConvertAnyFormat(ValuePtr, Format)){ + case 1: FocalplaneUnits = 25.4; break; // inch + case 2: + FocalplaneUnits = 25.4; + break; + + case 3: FocalplaneUnits = 10; break; // centimeter + case 4: FocalplaneUnits = 1; break; // millimeter + case 5: FocalplaneUnits = .001; break; // micrometer + } + break; + + case TAG_EXPOSURE_BIAS: + ImageInfo.ExposureBias = (float)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_WHITEBALANCE: + ImageInfo.Whitebalance = (int)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_LIGHT_SOURCE: + ImageInfo.LightSource = (int)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_METERING_MODE: + ImageInfo.MeteringMode = (int)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_EXPOSURE_PROGRAM: + ImageInfo.ExposureProgram = (int)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_EXPOSURE_INDEX: + if (ImageInfo.ISOequivalent == 0){ + ImageInfo.ISOequivalent = (int)ConvertAnyFormat(ValuePtr, Format); + } + break; + + case TAG_EXPOSURE_MODE: + ImageInfo.ExposureMode = (int)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_ISO_EQUIVALENT: + ImageInfo.ISOequivalent = (int)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_DIGITALZOOMRATIO: + ImageInfo.DigitalZoomRatio = (float)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_THUMBNAIL_OFFSET: + ThumbnailOffset = (unsigned)ConvertAnyFormat(ValuePtr, Format); + DirWithThumbnailPtrs = DirStart; + break; + + case TAG_THUMBNAIL_LENGTH: + ThumbnailSize = (unsigned)ConvertAnyFormat(ValuePtr, Format); + ImageInfo.ThumbnailSizeOffset = ValuePtr-OffsetBase; + break; + + case TAG_EXIF_OFFSET: + if (ShowTags) printf(""%s Exif Dir:"",IndentString); + + case TAG_INTEROP_OFFSET: + if (Tag == TAG_INTEROP_OFFSET && ShowTags) printf(""%s Interop Dir:"",IndentString); + { + unsigned char * SubdirStart; + SubdirStart = OffsetBase + Get32u(ValuePtr); + if (SubdirStart < OffsetBase || SubdirStart > OffsetBase+ExifLength){ + ErrNonfatal(""Illegal exif or interop ofset directory link"",0,0); + }else{ + ProcessExifDir(SubdirStart, OffsetBase, ExifLength, NestingLevel+1); + } + continue; + } + break; + + case TAG_GPSINFO: + if (ShowTags) printf(""%s GPS info dir:"",IndentString); + { + unsigned char * SubdirStart; + SubdirStart = OffsetBase + Get32u(ValuePtr); + if (SubdirStart < OffsetBase || SubdirStart > OffsetBase+ExifLength){ + ErrNonfatal(""Illegal GPS directory link"",0,0); + }else{ + ProcessGpsInfo(SubdirStart, ByteCount, OffsetBase, ExifLength); + } + continue; + } + break; + + case TAG_FOCALLENGTH_35MM: + ImageInfo.FocalLength35mmEquiv = (unsigned)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_DISTANCE_RANGE: + ImageInfo.DistanceRange = (int)ConvertAnyFormat(ValuePtr, Format); + break; + } + } + + + { + unsigned char * SubdirStart; + unsigned Offset; + + if (DIR_ENTRY_ADDR(DirStart, NumDirEntries) + 4 <= OffsetBase+ExifLength){ + printf(""DirStart %p offset from dirstart %d"", DirStart, 2+12*NumDirEntries); + Offset = Get32u(DirStart+2+12*NumDirEntries); + if (Offset){ + SubdirStart = OffsetBase + Offset; + if (SubdirStart > OffsetBase+ExifLength || SubdirStart < OffsetBase){ + printf(""SubdirStart %p OffsetBase %p ExifLength %d Offset %d"", + SubdirStart, OffsetBase, ExifLength, Offset); + if (SubdirStart > OffsetBase && SubdirStart < OffsetBase+ExifLength+20){ + if (ShowTags) printf(""Thumbnail removed with Jhead 1.3 or earlier\n""); + }else{ + ErrNonfatal(""Illegal subdirectory link"",0,0); + } + }else{ + if (SubdirStart <= OffsetBase+ExifLength){ + if (ShowTags) printf(""%s Continued directory "",IndentString); + ProcessExifDir(SubdirStart, OffsetBase, ExifLength, NestingLevel+1); + } + } + if (Offset > ImageInfo.LargestExifOffset){ + ImageInfo.LargestExifOffset = Offset; + } + } + }else{ + } + } + + if (ThumbnailOffset){ + ImageInfo.ThumbnailAtEnd = FALSE; + + if (DumpExifMap){ + printf(""Map: %05d-%05d: Thumbnail\n"",ThumbnailOffset, ThumbnailOffset+ThumbnailSize); + } + + if (ThumbnailOffset <= ExifLength){ + if (ThumbnailSize > ExifLength-ThumbnailOffset){ + ThumbnailSize = ExifLength-ThumbnailOffset; + if (ShowTags) printf(""Thumbnail incorrectly placed in header\n""); + + } + ImageInfo.ThumbnailOffset = ThumbnailOffset; + ImageInfo.ThumbnailSize = ThumbnailSize; + + if (ShowTags){ + printf(""Thumbnail size: %d bytes\n"",ThumbnailSize); + } + } + } + printf(""returning from ProcessExifDir""); +} +",1,"static void ProcessExifDir(unsigned char * DirStart, unsigned char * OffsetBase, + unsigned ExifLength, int NestingLevel) +{ + int de; + int a; + int NumDirEntries; + unsigned ThumbnailOffset = 0; + unsigned ThumbnailSize = 0; + char IndentString[25]; + + printf(""ProcessExifDir""); + if (NestingLevel > 4){ + ErrNonfatal(""Maximum directory nesting exceeded (corrupt exif header)"", 0,0); + return; + } + + memset(IndentString, ' ', 25); + IndentString[NestingLevel * 4] = '\0'; + + + NumDirEntries = Get16u(DirStart); + #define DIR_ENTRY_ADDR(Start, Entry) (Start+2+12*(Entry)) + + { + unsigned char * DirEnd; + DirEnd = DIR_ENTRY_ADDR(DirStart, NumDirEntries); + if (DirEnd+4 > (OffsetBase+ExifLength)){ + if (DirEnd+2 == OffsetBase+ExifLength || DirEnd == OffsetBase+ExifLength){ + }else{ + ErrNonfatal(""Illegally sized exif subdirectory (%d entries)"",NumDirEntries,0); + return; + } + } + if (DumpExifMap){ + printf(""Map: %05d-%05d: Directory\n"",(int)(DirStart-OffsetBase), (int)(DirEnd+4-OffsetBase)); + } + + + } + + if (ShowTags){ + printf(""(dir has %d entries)\n"",NumDirEntries); + } + + for (de=0;de= NUM_FORMATS) { + ErrNonfatal(""Illegal number format %d for tag %04x"", Format, Tag); + continue; + } + + if ((unsigned)Components > 0x10000){ + ErrNonfatal(""Illegal number of components %d for tag %04x"", Components, Tag); + continue; + } + + ByteCount = Components * BytesPerFormat[Format]; + + if (ByteCount > 4){ + + unsigned OffsetVal; + OffsetVal = Get32u(DirEntry+8); + if (OffsetVal > UINT32_MAX - ByteCount || OffsetVal+ByteCount > ExifLength){ + ErrNonfatal(""Illegal value pointer for tag %04x"", Tag,0); + continue; + } + ValuePtr = OffsetBase+OffsetVal; + + if (OffsetVal > ImageInfo.LargestExifOffset){ + ImageInfo.LargestExifOffset = OffsetVal; + } + + if (DumpExifMap){ + printf(""Map: %05d-%05d: Data for tag %04x\n"",OffsetVal, OffsetVal+ByteCount, Tag); + } + }else{ + ValuePtr = DirEntry+8; + } + + if (Tag == TAG_MAKER_NOTE){ + if (ShowTags){ + printf(""%s Maker note: "",IndentString); + } + ProcessMakerNote(ValuePtr, ByteCount, OffsetBase, ExifLength); + continue; + } + + if (ShowTags){ + for (a=0;;a++){ + if (a >= (int)TAG_TABLE_SIZE){ + printf(""%s"", IndentString); + printf("" Unknown Tag %04x Value = "", Tag); + break; + } + if (TagTable[a].Tag == Tag){ + printf(""%s"", IndentString); + printf("" %s = "",TagTable[a].Desc); + break; + } + } + + switch(Format){ + case FMT_BYTE: + if(ByteCount>1){ + printf(""%.*ls\n"", ByteCount/2, (wchar_t *)ValuePtr); + }else{ + PrintFormatNumber(ValuePtr, Format, ByteCount); + printf(""\n""); + } + break; + + case FMT_UNDEFINED: + + case FMT_STRING: + { + printf(""\""%s\"""", ValuePtr); + } + break; + + default: + PrintFormatNumber(ValuePtr, Format, ByteCount); + printf(""\n""); + } + } + + switch(Tag){ + + case TAG_MAKE: + strncpy(ImageInfo.CameraMake, (char *)ValuePtr, ByteCount < 31 ? ByteCount : 31); + break; + + case TAG_MODEL: + strncpy(ImageInfo.CameraModel, (char *)ValuePtr, ByteCount < 39 ? ByteCount : 39); + break; + + case TAG_SUBSEC_TIME: + strlcpy(ImageInfo.SubSecTime, (char *)ValuePtr, sizeof(ImageInfo.SubSecTime)); + break; + + case TAG_SUBSEC_TIME_ORIG: + strlcpy(ImageInfo.SubSecTimeOrig, (char *)ValuePtr, + sizeof(ImageInfo.SubSecTimeOrig)); + break; + + case TAG_SUBSEC_TIME_DIG: + strlcpy(ImageInfo.SubSecTimeDig, (char *)ValuePtr, + sizeof(ImageInfo.SubSecTimeDig)); + break; + + case TAG_DATETIME_DIGITIZED: + strlcpy(ImageInfo.DigitizedTime, (char *)ValuePtr, + sizeof(ImageInfo.DigitizedTime)); + + if (ImageInfo.numDateTimeTags >= MAX_DATE_COPIES){ + ErrNonfatal(""More than %d date fields! This is nuts"", MAX_DATE_COPIES, 0); + break; + } + ImageInfo.DateTimeOffsets[ImageInfo.numDateTimeTags++] = + (char *)ValuePtr - (char *)OffsetBase; + break; + + case TAG_DATETIME_ORIGINAL: + strncpy(ImageInfo.DateTime, (char *)ValuePtr, 19); + + case TAG_DATETIME: + if (!isdigit(ImageInfo.DateTime[0])){ + strncpy(ImageInfo.DateTime, (char *)ValuePtr, 19); + } + + if (ImageInfo.numDateTimeTags >= MAX_DATE_COPIES){ + ErrNonfatal(""More than %d date fields! This is nuts"", MAX_DATE_COPIES, 0); + break; + } + ImageInfo.DateTimeOffsets[ImageInfo.numDateTimeTags++] = + (char *)ValuePtr - (char *)OffsetBase; + break; + + case TAG_WINXP_COMMENT: + if (ImageInfo.Comments[0]){ // We already have a jpeg comment. + if (ShowTags) printf(""Windows XP commend and other comment in header\n""); + break; // Already have a windows comment, skip this one. + } + + if (ByteCount > 1){ + if (ByteCount > MAX_COMMENT_SIZE) ByteCount = MAX_COMMENT_SIZE; + memcpy(ImageInfo.Comments, ValuePtr, ByteCount); + ImageInfo.CommentWidchars = ByteCount/2; + } + break; + + case TAG_USERCOMMENT: + if (ImageInfo.Comments[0]){ // We already have a jpeg comment. + if (ShowTags) printf(""Multiple comments in exif header\n""); + break; // Already have a windows comment, skip this one. + } + + for (a=ByteCount;;){ + a--; + if ((ValuePtr)[a] == ' '){ + (ValuePtr)[a] = '\0'; + }else{ + break; + } + if (a == 0) break; + } + + { + int msiz = ExifLength - (ValuePtr-OffsetBase); + if (msiz > ByteCount) msiz = ByteCount; + if (msiz > MAX_COMMENT_SIZE - 1) msiz = MAX_COMMENT_SIZE - 1; + if (msiz > 5 && memcmp(ValuePtr, ""ASCII"", 5) == 0) { + for (a = 5; a < 10 && a < msiz; a++) { + int c = (ValuePtr)[a]; + if (c != '\0' && c != ' ') { + strncpy(ImageInfo.Comments, + (char *)ValuePtr + a, msiz - a); + break; + } + } + } else { + strncpy(ImageInfo.Comments, (char *)ValuePtr, msiz); + } + } + break; + + case TAG_FNUMBER: + ImageInfo.ApertureFNumber = (float)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_APERTURE: + case TAG_MAXAPERTURE: + if (ImageInfo.ApertureFNumber == 0){ + ImageInfo.ApertureFNumber + = (float)exp(ConvertAnyFormat(ValuePtr, Format)*log(2)*0.5); + } + break; + + case TAG_FOCALLENGTH: + ImageInfo.FocalLength.num = Get32u(ValuePtr); + ImageInfo.FocalLength.denom = Get32u(4+(char *)ValuePtr); + break; + + case TAG_SUBJECT_DISTANCE: + ImageInfo.Distance = (float)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_EXPOSURETIME: + ImageInfo.ExposureTime = (float)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_SHUTTERSPEED: + if (ImageInfo.ExposureTime == 0){ + ImageInfo.ExposureTime + = (float)(1/exp(ConvertAnyFormat(ValuePtr, Format)*log(2))); + } + break; + + + case TAG_FLASH: + ImageInfo.FlashUsed=(int)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_ORIENTATION: + if (NumOrientations >= 2){ + ErrNonfatal(""More than two orientation tags!"",0,0); + break; + } + OrientationPtr[NumOrientations] = ValuePtr; + OrientationNumFormat[NumOrientations] = Format; + if (NumOrientations == 0){ + ImageInfo.Orientation = (int)ConvertAnyFormat(ValuePtr, Format); + } + if (ImageInfo.Orientation < 0 || ImageInfo.Orientation > 8){ + ErrNonfatal(""Undefined rotation value %d"", ImageInfo.Orientation, 0); + ImageInfo.Orientation = 0; + } + NumOrientations += 1; + break; + + case TAG_EXIF_IMAGELENGTH: + case TAG_EXIF_IMAGEWIDTH: + a = (int)ConvertAnyFormat(ValuePtr, Format); + if (ExifImageWidth < a) ExifImageWidth = a; + break; + + case TAG_FOCAL_PLANE_XRES: + FocalplaneXRes = ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_FOCAL_PLANE_UNITS: + switch((int)ConvertAnyFormat(ValuePtr, Format)){ + case 1: FocalplaneUnits = 25.4; break; // inch + case 2: + FocalplaneUnits = 25.4; + break; + + case 3: FocalplaneUnits = 10; break; // centimeter + case 4: FocalplaneUnits = 1; break; // millimeter + case 5: FocalplaneUnits = .001; break; // micrometer + } + break; + + case TAG_EXPOSURE_BIAS: + ImageInfo.ExposureBias = (float)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_WHITEBALANCE: + ImageInfo.Whitebalance = (int)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_LIGHT_SOURCE: + ImageInfo.LightSource = (int)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_METERING_MODE: + ImageInfo.MeteringMode = (int)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_EXPOSURE_PROGRAM: + ImageInfo.ExposureProgram = (int)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_EXPOSURE_INDEX: + if (ImageInfo.ISOequivalent == 0){ + ImageInfo.ISOequivalent = (int)ConvertAnyFormat(ValuePtr, Format); + } + break; + + case TAG_EXPOSURE_MODE: + ImageInfo.ExposureMode = (int)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_ISO_EQUIVALENT: + ImageInfo.ISOequivalent = (int)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_DIGITALZOOMRATIO: + ImageInfo.DigitalZoomRatio = (float)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_THUMBNAIL_OFFSET: + ThumbnailOffset = (unsigned)ConvertAnyFormat(ValuePtr, Format); + DirWithThumbnailPtrs = DirStart; + break; + + case TAG_THUMBNAIL_LENGTH: + ThumbnailSize = (unsigned)ConvertAnyFormat(ValuePtr, Format); + ImageInfo.ThumbnailSizeOffset = ValuePtr-OffsetBase; + break; + + case TAG_EXIF_OFFSET: + if (ShowTags) printf(""%s Exif Dir:"",IndentString); + + case TAG_INTEROP_OFFSET: + if (Tag == TAG_INTEROP_OFFSET && ShowTags) printf(""%s Interop Dir:"",IndentString); + { + unsigned char * SubdirStart; + SubdirStart = OffsetBase + Get32u(ValuePtr); + if (SubdirStart < OffsetBase || SubdirStart > OffsetBase+ExifLength){ + ErrNonfatal(""Illegal exif or interop ofset directory link"",0,0); + }else{ + ProcessExifDir(SubdirStart, OffsetBase, ExifLength, NestingLevel+1); + } + continue; + } + break; + + case TAG_GPSINFO: + if (ShowTags) printf(""%s GPS info dir:"",IndentString); + { + unsigned char * SubdirStart; + SubdirStart = OffsetBase + Get32u(ValuePtr); + if (SubdirStart < OffsetBase || SubdirStart > OffsetBase+ExifLength){ + ErrNonfatal(""Illegal GPS directory link"",0,0); + }else{ + ProcessGpsInfo(SubdirStart, ByteCount, OffsetBase, ExifLength); + } + continue; + } + break; + + case TAG_FOCALLENGTH_35MM: + ImageInfo.FocalLength35mmEquiv = (unsigned)ConvertAnyFormat(ValuePtr, Format); + break; + + case TAG_DISTANCE_RANGE: + ImageInfo.DistanceRange = (int)ConvertAnyFormat(ValuePtr, Format); + break; + } + } + + + { + unsigned char * SubdirStart; + unsigned Offset; + + if (DIR_ENTRY_ADDR(DirStart, NumDirEntries) + 4 <= OffsetBase+ExifLength){ + printf(""DirStart %p offset from dirstart %d"", DirStart, 2+12*NumDirEntries); + Offset = Get32u(DirStart+2+12*NumDirEntries); + if (Offset){ + SubdirStart = OffsetBase + Offset; + if (SubdirStart > OffsetBase+ExifLength || SubdirStart < OffsetBase){ + printf(""SubdirStart %p OffsetBase %p ExifLength %d Offset %d"", + SubdirStart, OffsetBase, ExifLength, Offset); + if (SubdirStart > OffsetBase && SubdirStart < OffsetBase+ExifLength+20){ + if (ShowTags) printf(""Thumbnail removed with Jhead 1.3 or earlier\n""); + }else{ + ErrNonfatal(""Illegal subdirectory link"",0,0); + } + }else{ + if (SubdirStart <= OffsetBase+ExifLength){ + if (ShowTags) printf(""%s Continued directory "",IndentString); + ProcessExifDir(SubdirStart, OffsetBase, ExifLength, NestingLevel+1); + } + } + if (Offset > ImageInfo.LargestExifOffset){ + ImageInfo.LargestExifOffset = Offset; + } + } + }else{ + } + } + + if (ThumbnailOffset){ + ImageInfo.ThumbnailAtEnd = FALSE; + + if (DumpExifMap){ + printf(""Map: %05d-%05d: Thumbnail\n"",ThumbnailOffset, ThumbnailOffset+ThumbnailSize); + } + + if (ThumbnailOffset <= ExifLength){ + if (ThumbnailSize > ExifLength-ThumbnailOffset){ + ThumbnailSize = ExifLength-ThumbnailOffset; + if (ShowTags) printf(""Thumbnail incorrectly placed in header\n""); + + } + ImageInfo.ThumbnailOffset = ThumbnailOffset; + ImageInfo.ThumbnailSize = ThumbnailSize; + + if (ShowTags){ + printf(""Thumbnail size: %d bytes\n"",ThumbnailSize); + } + } + } + printf(""returning from ProcessExifDir""); +} +","@@ -614,7 +614,7 @@ + + unsigned OffsetVal; + OffsetVal = Get32u(DirEntry+8); + // If its bigger than 4 bytes, the dir entry contains an offset. +- if (OffsetVal+ByteCount > ExifLength){ ++ if (OffsetVal > UINT32_MAX - ByteCount || OffsetVal+ByteCount > ExifLength){ + // Bogus pointer offset and / or bytecount value + ErrNonfatal(""Illegal value pointer for tag %04x"", Tag,0); + continue; +",3256,3587,4096 +17840,"ecc_decrypt_raw (gcry_sexp_t *r_plain, gcry_sexp_t s_data, gcry_sexp_t keyparms) +{ + unsigned int nbits; + gpg_err_code_t rc; + struct pk_encoding_ctx ctx; + gcry_sexp_t l1 = NULL; + gcry_mpi_t data_e = NULL; + ECC_secret_key sk; + gcry_mpi_t mpi_g = NULL; + char *curvename = NULL; + mpi_ec_t ec = NULL; + mpi_point_struct kG; + mpi_point_struct R; + gcry_mpi_t r = NULL; + int flags = 0; + + memset (&sk, 0, sizeof sk); + point_init (&kG); + point_init (&R); + + _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_DECRYPT, + (nbits = ecc_get_nbits (keyparms))); + + /* Look for flags. */ + l1 = sexp_find_token (keyparms, ""flags"", 0); + if (l1) + { + rc = _gcry_pk_util_parse_flaglist (l1, &flags, NULL); + if (rc) + goto leave; + } + sexp_release (l1); + l1 = NULL; + + /* + * Extract the data. + */ + rc = _gcry_pk_util_preparse_encval (s_data, ecc_names, &l1, &ctx); + if (rc) + goto leave; + rc = sexp_extract_param (l1, NULL, ""e"", &data_e, NULL); + if (rc) + goto leave; + if (DBG_CIPHER) + log_printmpi (""ecc_decrypt d_e"", data_e); + if (mpi_is_opaque (data_e)) + { + rc = GPG_ERR_INV_DATA; + goto leave; + } + + /* + * Extract the key. + */ + rc = sexp_extract_param (keyparms, NULL, ""-p?a?b?g?n?h?+d"", + &sk.E.p, &sk.E.a, &sk.E.b, &mpi_g, &sk.E.n, + &sk.E.h, &sk.d, NULL); + if (rc) + goto leave; + if (mpi_g) + { + point_init (&sk.E.G); + rc = _gcry_ecc_os2ec (&sk.E.G, mpi_g); + if (rc) + goto leave; + } + /* Add missing parameters using the optional curve parameter. */ + sexp_release (l1); + l1 = sexp_find_token (keyparms, ""curve"", 5); + if (l1) + { + curvename = sexp_nth_string (l1, 1); + if (curvename) + { + rc = _gcry_ecc_fill_in_curve (0, curvename, &sk.E, NULL); + if (rc) + goto leave; + } + } + /* Guess required fields if a curve parameter has not been given. */ + if (!curvename) + { + sk.E.model = MPI_EC_WEIERSTRASS; + sk.E.dialect = ECC_DIALECT_STANDARD; + if (!sk.E.h) + sk.E.h = mpi_const (MPI_C_ONE); + } + if (DBG_CIPHER) + { + log_debug (""ecc_decrypt info: %s/%s\n"", + _gcry_ecc_model2str (sk.E.model), + _gcry_ecc_dialect2str (sk.E.dialect)); + if (sk.E.name) + log_debug (""ecc_decrypt name: %s\n"", sk.E.name); + log_printmpi (""ecc_decrypt p"", sk.E.p); + log_printmpi (""ecc_decrypt a"", sk.E.a); + log_printmpi (""ecc_decrypt b"", sk.E.b); + log_printpnt (""ecc_decrypt g"", &sk.E.G, NULL); + log_printmpi (""ecc_decrypt n"", sk.E.n); + log_printmpi (""ecc_decrypt h"", sk.E.h); + if (!fips_mode ()) + log_printmpi (""ecc_decrypt d"", sk.d); + } + if (!sk.E.p || !sk.E.a || !sk.E.b || !sk.E.G.x || !sk.E.n || !sk.E.h || !sk.d) + { + rc = GPG_ERR_NO_OBJ; + goto leave; + } + + + ec = _gcry_mpi_ec_p_internal_new (sk.E.model, sk.E.dialect, flags, + sk.E.p, sk.E.a, sk.E.b); + + /* + * Compute the plaintext. + */ + if (ec->model == MPI_EC_MONTGOMERY) + rc = _gcry_ecc_mont_decodepoint (data_e, ec, &kG); + else + rc = _gcry_ecc_os2ec (&kG, data_e); + if (rc) + goto leave; + + if (DBG_CIPHER) + log_printpnt (""ecc_decrypt kG"", &kG, NULL); + + if (!(flags & PUBKEY_FLAG_DJB_TWEAK) + /* For X25519, by its definition, validation should not be done. */ + && !_gcry_mpi_ec_curve_point (&kG, ec)) + { + rc = GPG_ERR_INV_DATA; + goto leave; + y = mpi_new (0); + + if (_gcry_mpi_ec_get_affine (x, y, &R, ec)) + { + rc = GPG_ERR_INV_DATA; + goto leave; + /* + * Note for X25519. + * + * By the definition of X25519, this is the case where X25519 + * returns 0, mapping infinity to zero. However, we + * deliberately let it return an error. + * + * For X25519 ECDH, comming here means that it might be + * decrypted by anyone with the shared secret of 0 (the result + * of this function could be always 0 by other scalar values, + * other than the private key of SK.D). + * + * So, it looks like an encrypted message but it can be + * decrypted by anyone, or at least something wrong + * happens. Recipient should not proceed as if it were + * properly encrypted message. + * + * This handling is needed for our major usage of GnuPG, + * where it does the One-Pass Diffie-Hellman method, + * C(1, 1, ECC CDH), with an ephemeral key. + */ + } + + if (y) + r = _gcry_ecc_ec2os (x, y, sk.E.p); + else + { + unsigned char *rawmpi; + unsigned int rawmpilen; + + rawmpi = _gcry_mpi_get_buffer_extra (x, nbits/8, -1, + &rawmpilen, NULL); + if (!rawmpi) + { + rc = gpg_err_code_from_syserror (); + goto leave; + } + else + { + rawmpi[0] = 0x40; + rawmpilen++; + r = mpi_new (0); + mpi_set_opaque (r, rawmpi, rawmpilen*8); + } + } + if (!r) + rc = gpg_err_code_from_syserror (); + else + rc = 0; + mpi_free (x); + mpi_free (y); + } + if (DBG_CIPHER) + log_printmpi (""ecc_decrypt res"", r); + + if (!rc) + rc = sexp_build (r_plain, NULL, ""(value %m)"", r); + + leave: + point_free (&R); + point_free (&kG); + _gcry_mpi_release (r); + _gcry_mpi_release (sk.E.p); + _gcry_mpi_release (sk.E.a); + _gcry_mpi_release (sk.E.b); + _gcry_mpi_release (mpi_g); + point_free (&sk.E.G); + _gcry_mpi_release (sk.E.n); + _gcry_mpi_release (sk.E.h); + _gcry_mpi_release (sk.d); + _gcry_mpi_release (data_e); + xfree (curvename); + sexp_release (l1); + _gcry_mpi_ec_free (ec); + _gcry_pk_util_free_encoding_ctx (&ctx); + if (DBG_CIPHER) + log_debug (""ecc_decrypt => %s\n"", gpg_strerror (rc)); + return rc; +} +",1,"ecc_decrypt_raw (gcry_sexp_t *r_plain, gcry_sexp_t s_data, gcry_sexp_t keyparms) +{ + unsigned int nbits; + gpg_err_code_t rc; + struct pk_encoding_ctx ctx; + gcry_sexp_t l1 = NULL; + gcry_mpi_t data_e = NULL; + ECC_secret_key sk; + gcry_mpi_t mpi_g = NULL; + char *curvename = NULL; + mpi_ec_t ec = NULL; + mpi_point_struct kG; + mpi_point_struct R; + gcry_mpi_t r = NULL; + int flags = 0; + + memset (&sk, 0, sizeof sk); + point_init (&kG); + point_init (&R); + + _gcry_pk_util_init_encoding_ctx (&ctx, PUBKEY_OP_DECRYPT, + (nbits = ecc_get_nbits (keyparms))); + + /* Look for flags. */ + l1 = sexp_find_token (keyparms, ""flags"", 0); + if (l1) + { + rc = _gcry_pk_util_parse_flaglist (l1, &flags, NULL); + if (rc) + goto leave; + } + sexp_release (l1); + l1 = NULL; + + /* + * Extract the data. + */ + rc = _gcry_pk_util_preparse_encval (s_data, ecc_names, &l1, &ctx); + if (rc) + goto leave; + rc = sexp_extract_param (l1, NULL, ""e"", &data_e, NULL); + if (rc) + goto leave; + if (DBG_CIPHER) + log_printmpi (""ecc_decrypt d_e"", data_e); + if (mpi_is_opaque (data_e)) + { + rc = GPG_ERR_INV_DATA; + goto leave; + } + + /* + * Extract the key. + */ + rc = sexp_extract_param (keyparms, NULL, ""-p?a?b?g?n?h?+d"", + &sk.E.p, &sk.E.a, &sk.E.b, &mpi_g, &sk.E.n, + &sk.E.h, &sk.d, NULL); + if (rc) + goto leave; + if (mpi_g) + { + point_init (&sk.E.G); + rc = _gcry_ecc_os2ec (&sk.E.G, mpi_g); + if (rc) + goto leave; + } + /* Add missing parameters using the optional curve parameter. */ + sexp_release (l1); + l1 = sexp_find_token (keyparms, ""curve"", 5); + if (l1) + { + curvename = sexp_nth_string (l1, 1); + if (curvename) + { + rc = _gcry_ecc_fill_in_curve (0, curvename, &sk.E, NULL); + if (rc) + goto leave; + } + } + /* Guess required fields if a curve parameter has not been given. */ + if (!curvename) + { + sk.E.model = MPI_EC_WEIERSTRASS; + sk.E.dialect = ECC_DIALECT_STANDARD; + if (!sk.E.h) + sk.E.h = mpi_const (MPI_C_ONE); + } + if (DBG_CIPHER) + { + log_debug (""ecc_decrypt info: %s/%s\n"", + _gcry_ecc_model2str (sk.E.model), + _gcry_ecc_dialect2str (sk.E.dialect)); + if (sk.E.name) + log_debug (""ecc_decrypt name: %s\n"", sk.E.name); + log_printmpi (""ecc_decrypt p"", sk.E.p); + log_printmpi (""ecc_decrypt a"", sk.E.a); + log_printmpi (""ecc_decrypt b"", sk.E.b); + log_printpnt (""ecc_decrypt g"", &sk.E.G, NULL); + log_printmpi (""ecc_decrypt n"", sk.E.n); + log_printmpi (""ecc_decrypt h"", sk.E.h); + if (!fips_mode ()) + log_printmpi (""ecc_decrypt d"", sk.d); + } + if (!sk.E.p || !sk.E.a || !sk.E.b || !sk.E.G.x || !sk.E.n || !sk.E.h || !sk.d) + { + rc = GPG_ERR_NO_OBJ; + goto leave; + } + + + ec = _gcry_mpi_ec_p_internal_new (sk.E.model, sk.E.dialect, flags, + sk.E.p, sk.E.a, sk.E.b); + + /* + * Compute the plaintext. + */ + if (ec->model == MPI_EC_MONTGOMERY) + rc = _gcry_ecc_mont_decodepoint (data_e, ec, &kG); + else + rc = _gcry_ecc_os2ec (&kG, data_e); + if (rc) + goto leave; + + if (DBG_CIPHER) + log_printpnt (""ecc_decrypt kG"", &kG, NULL); + + if ((flags & PUBKEY_FLAG_DJB_TWEAK)) + { + /* For X25519, by its definition, validation should not be done. */ + /* (Instead, we do output check.) + * + * However, to mitigate secret key leak from our implementation, + * we also do input validation here. For constant-time + * implementation, we can remove this input validation. + */ + if (_gcry_mpi_ec_bad_point (&kG, ec)) + { + rc = GPG_ERR_INV_DATA; + goto leave; + } + } + else if (!_gcry_mpi_ec_curve_point (&kG, ec)) + { + rc = GPG_ERR_INV_DATA; + goto leave; + y = mpi_new (0); + + if (_gcry_mpi_ec_get_affine (x, y, &R, ec)) + { + rc = GPG_ERR_INV_DATA; + goto leave; + /* + * Note for X25519. + * + * By the definition of X25519, this is the case where X25519 + * returns 0, mapping infinity to zero. However, we + * deliberately let it return an error. + * + * For X25519 ECDH, comming here means that it might be + * decrypted by anyone with the shared secret of 0 (the result + * of this function could be always 0 by other scalar values, + * other than the private key of SK.D). + * + * So, it looks like an encrypted message but it can be + * decrypted by anyone, or at least something wrong + * happens. Recipient should not proceed as if it were + * properly encrypted message. + * + * This handling is needed for our major usage of GnuPG, + * where it does the One-Pass Diffie-Hellman method, + * C(1, 1, ECC CDH), with an ephemeral key. + */ + } + + if (y) + r = _gcry_ecc_ec2os (x, y, sk.E.p); + else + { + unsigned char *rawmpi; + unsigned int rawmpilen; + + rawmpi = _gcry_mpi_get_buffer_extra (x, nbits/8, -1, + &rawmpilen, NULL); + if (!rawmpi) + { + rc = gpg_err_code_from_syserror (); + goto leave; + } + else + { + rawmpi[0] = 0x40; + rawmpilen++; + r = mpi_new (0); + mpi_set_opaque (r, rawmpi, rawmpilen*8); + } + } + if (!r) + rc = gpg_err_code_from_syserror (); + else + rc = 0; + mpi_free (x); + mpi_free (y); + } + if (DBG_CIPHER) + log_printmpi (""ecc_decrypt res"", r); + + if (!rc) + rc = sexp_build (r_plain, NULL, ""(value %m)"", r); + + leave: + point_free (&R); + point_free (&kG); + _gcry_mpi_release (r); + _gcry_mpi_release (sk.E.p); + _gcry_mpi_release (sk.E.a); + _gcry_mpi_release (sk.E.b); + _gcry_mpi_release (mpi_g); + point_free (&sk.E.G); + _gcry_mpi_release (sk.E.n); + _gcry_mpi_release (sk.E.h); + _gcry_mpi_release (sk.d); + _gcry_mpi_release (data_e); + xfree (curvename); + sexp_release (l1); + _gcry_mpi_ec_free (ec); + _gcry_pk_util_free_encoding_ctx (&ctx); + if (DBG_CIPHER) + log_debug (""ecc_decrypt => %s\n"", gpg_strerror (rc)); + return rc; +} +","@@ -1628,9 +1628,22 @@ ecc_decrypt_raw (gcry_sexp_t *r_plain, gcry_sexp_t s_data, gcry_sexp_t keyparms) + if (DBG_CIPHER) + log_printpnt (""ecc_decrypt kG"", &kG, NULL); + +- if (!(flags & PUBKEY_FLAG_DJB_TWEAK) ++ if ((flags & PUBKEY_FLAG_DJB_TWEAK)) ++ { + /* For X25519, by its definition, validation should not be done. */ +- && !_gcry_mpi_ec_curve_point (&kG, ec)) ++ /* (Instead, we do output check.) ++ * ++ * However, to mitigate secret key leak from our implementation, ++ * we also do input validation here. For constant-time ++ * implementation, we can remove this input validation. ++ */ ++ if (_gcry_mpi_ec_bad_point (&kG, ec)) ++ { ++ rc = GPG_ERR_INV_DATA; ++ goto leave; ++ } ++ } ++ else if (!_gcry_mpi_ec_curve_point (&kG, ec)) + { + rc = GPG_ERR_INV_DATA; + goto leave;",1842,2173,4096 +18053,"SAPI_API int sapi_header_op(sapi_header_op_enum op, void *arg TSRMLS_DC) +{ + sapi_header_struct sapi_header; + char *colon_offset; + char *header_line; + uint header_line_len; + int http_response_code; + + if (SG(headers_sent) && !SG(request_info).no_headers) { + const char *output_start_filename = php_output_get_start_filename(TSRMLS_C); + int output_start_lineno = php_output_get_start_lineno(TSRMLS_C); + + if (output_start_filename) { + sapi_module.sapi_error(E_WARNING, ""Cannot modify header information - headers already sent by (output started at %s:%d)"", + output_start_filename, output_start_lineno); + } else { + sapi_module.sapi_error(E_WARNING, ""Cannot modify header information - headers already sent""); + } + return FAILURE; + } + + switch (op) { + case SAPI_HEADER_SET_STATUS: + sapi_update_response_code((int)(zend_intptr_t) arg TSRMLS_CC); + return SUCCESS; + + case SAPI_HEADER_ADD: + case SAPI_HEADER_REPLACE: + case SAPI_HEADER_DELETE: { + sapi_header_line *p = arg; + + if (!p->line || !p->line_len) { + return FAILURE; + } + header_line = p->line; + header_line_len = p->line_len; + http_response_code = p->response_code; + break; + } + + case SAPI_HEADER_DELETE_ALL: + if (sapi_module.header_handler) { + sapi_module.header_handler(&sapi_header, op, &SG(sapi_headers) TSRMLS_CC); + } + zend_llist_clean(&SG(sapi_headers).headers); + return SUCCESS; + + default: + return FAILURE; + } + + header_line = estrndup(header_line, header_line_len); + + /* cut off trailing spaces, linefeeds and carriage-returns */ + if (header_line_len && isspace(header_line[header_line_len-1])) { + do { + header_line_len--; + } while(header_line_len && isspace(header_line[header_line_len-1])); + header_line[header_line_len]='\0'; + } + + if (op == SAPI_HEADER_DELETE) { + if (strchr(header_line, ':')) { + efree(header_line); + sapi_module.sapi_error(E_WARNING, ""Header to delete may not contain colon.""); + return FAILURE; + } + if (sapi_module.header_handler) { + sapi_header.header = header_line; + sapi_header.header_len = header_line_len; + sapi_module.header_handler(&sapi_header, op, &SG(sapi_headers) TSRMLS_CC); + } + sapi_remove_header(&SG(sapi_headers).headers, header_line, header_line_len); + efree(header_line); + return SUCCESS; + } else { + /* new line/NUL character safety check */ + int i; + for (i = 0; i < header_line_len; i++) { + /* RFC 2616 allows new lines if followed by SP or HT */ + int illegal_break = + (header_line[i+1] != ' ' && header_line[i+1] != '\t') + && ( + header_line[i] == '\n' + || (header_line[i] == '\r' && header_line[i+1] != '\n')); + if (illegal_break) { + efree(header_line); + sapi_module.sapi_error(E_WARNING, ""Header may not contain "" + ""more than a single header, new line detected""); + return FAILURE; + } + if (header_line[i] == '\0') { + efree(header_line); + sapi_module.sapi_error(E_WARNING, ""Header may not contain NUL bytes""); + return FAILURE; + } + } + } + + sapi_header.header = header_line; + sapi_header.header_len = header_line_len; + + /* Check the header for a few cases that we have special support for in SAPI */ + if (header_line_len>=5 + && !strncasecmp(header_line, ""HTTP/"", 5)) { + /* filter out the response code */ + sapi_update_response_code(sapi_extract_response_code(header_line) TSRMLS_CC); + /* sapi_update_response_code doesn't free the status line if the code didn't change */ + if (SG(sapi_headers).http_status_line) { + efree(SG(sapi_headers).http_status_line); + } + SG(sapi_headers).http_status_line = header_line; + return SUCCESS; + } else { + colon_offset = strchr(header_line, ':'); + if (colon_offset) { + *colon_offset = 0; + if (!STRCASECMP(header_line, ""Content-Type"")) { + char *ptr = colon_offset+1, *mimetype = NULL, *newheader; + size_t len = header_line_len - (ptr - header_line), newlen; + while (*ptr == ' ') { + ptr++; + len--; + } + + /* Disable possible output compression for images */ + if (!strncmp(ptr, ""image/"", sizeof(""image/"")-1)) { + zend_alter_ini_entry(""zlib.output_compression"", sizeof(""zlib.output_compression""), ""0"", sizeof(""0"") - 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME); + } + + mimetype = estrdup(ptr); + newlen = sapi_apply_default_charset(&mimetype, len TSRMLS_CC); + if (!SG(sapi_headers).mimetype){ + SG(sapi_headers).mimetype = estrdup(mimetype); + } + + if (newlen != 0) { + newlen += sizeof(""Content-type: ""); + newheader = emalloc(newlen); + PHP_STRLCPY(newheader, ""Content-type: "", newlen, sizeof(""Content-type: "")-1); + strlcat(newheader, mimetype, newlen); + sapi_header.header = newheader; + sapi_header.header_len = newlen - 1; + efree(header_line); + } + efree(mimetype); + SG(sapi_headers).send_default_content_type = 0; + } else if (!STRCASECMP(header_line, ""Content-Length"")) { + /* Script is setting Content-length. The script cannot reasonably + * know the size of the message body after compression, so it's best + * do disable compression altogether. This contributes to making scripts + * portable between setups that have and don't have zlib compression + * enabled globally. See req #44164 */ + zend_alter_ini_entry(""zlib.output_compression"", sizeof(""zlib.output_compression""), + ""0"", sizeof(""0"") - 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME); + } else if (!STRCASECMP(header_line, ""Location"")) { + if ((SG(sapi_headers).http_response_code < 300 || + SG(sapi_headers).http_response_code > 399) && + SG(sapi_headers).http_response_code != 201) { + /* Return a Found Redirect if one is not already specified */ + if (http_response_code) { /* user specified redirect code */ + sapi_update_response_code(http_response_code TSRMLS_CC); + } else if (SG(request_info).proto_num > 1000 && + SG(request_info).request_method && + strcmp(SG(request_info).request_method, ""HEAD"") && + strcmp(SG(request_info).request_method, ""GET"")) { + sapi_update_response_code(303 TSRMLS_CC); + } else { + sapi_update_response_code(302 TSRMLS_CC); + } + } + } else if (!STRCASECMP(header_line, ""WWW-Authenticate"")) { /* HTTP Authentication */ + sapi_update_response_code(401 TSRMLS_CC); /* authentication-required */ + } + if (sapi_header.header==header_line) { + *colon_offset = ':'; + } + } + } + if (http_response_code) { + sapi_update_response_code(http_response_code TSRMLS_CC); + } + sapi_header_add_op(op, &sapi_header TSRMLS_CC); + return SUCCESS; +} +",1,"SAPI_API int sapi_header_op(sapi_header_op_enum op, void *arg TSRMLS_DC) +{ + sapi_header_struct sapi_header; + char *colon_offset; + char *header_line; + uint header_line_len; + int http_response_code; + + if (SG(headers_sent) && !SG(request_info).no_headers) { + const char *output_start_filename = php_output_get_start_filename(TSRMLS_C); + int output_start_lineno = php_output_get_start_lineno(TSRMLS_C); + + if (output_start_filename) { + sapi_module.sapi_error(E_WARNING, ""Cannot modify header information - headers already sent by (output started at %s:%d)"", + output_start_filename, output_start_lineno); + } else { + sapi_module.sapi_error(E_WARNING, ""Cannot modify header information - headers already sent""); + } + return FAILURE; + } + + switch (op) { + case SAPI_HEADER_SET_STATUS: + sapi_update_response_code((int)(zend_intptr_t) arg TSRMLS_CC); + return SUCCESS; + + case SAPI_HEADER_ADD: + case SAPI_HEADER_REPLACE: + case SAPI_HEADER_DELETE: { + sapi_header_line *p = arg; + + if (!p->line || !p->line_len) { + return FAILURE; + } + header_line = p->line; + header_line_len = p->line_len; + http_response_code = p->response_code; + break; + } + + case SAPI_HEADER_DELETE_ALL: + if (sapi_module.header_handler) { + sapi_module.header_handler(&sapi_header, op, &SG(sapi_headers) TSRMLS_CC); + } + zend_llist_clean(&SG(sapi_headers).headers); + return SUCCESS; + + default: + return FAILURE; + } + + header_line = estrndup(header_line, header_line_len); + + /* cut off trailing spaces, linefeeds and carriage-returns */ + if (header_line_len && isspace(header_line[header_line_len-1])) { + do { + header_line_len--; + } while(header_line_len && isspace(header_line[header_line_len-1])); + header_line[header_line_len]='\0'; + } + + if (op == SAPI_HEADER_DELETE) { + if (strchr(header_line, ':')) { + efree(header_line); + sapi_module.sapi_error(E_WARNING, ""Header to delete may not contain colon.""); + return FAILURE; + } + if (sapi_module.header_handler) { + sapi_header.header = header_line; + sapi_header.header_len = header_line_len; + sapi_module.header_handler(&sapi_header, op, &SG(sapi_headers) TSRMLS_CC); + } + sapi_remove_header(&SG(sapi_headers).headers, header_line, header_line_len); + efree(header_line); + return SUCCESS; + } else { + /* new line/NUL character safety check */ + int i; + for (i = 0; i < header_line_len; i++) { + /* RFC 7230 ch. 3.2.4 deprecates folding support */ + if (header_line[i] == '\n' || header_line[i] == '\r') { + efree(header_line); + sapi_module.sapi_error(E_WARNING, ""Header may not contain "" + ""more than a single header, new line detected""); + return FAILURE; + } + if (header_line[i] == '\0') { + efree(header_line); + sapi_module.sapi_error(E_WARNING, ""Header may not contain NUL bytes""); + return FAILURE; + } + } + } + + sapi_header.header = header_line; + sapi_header.header_len = header_line_len; + + /* Check the header for a few cases that we have special support for in SAPI */ + if (header_line_len>=5 + && !strncasecmp(header_line, ""HTTP/"", 5)) { + /* filter out the response code */ + sapi_update_response_code(sapi_extract_response_code(header_line) TSRMLS_CC); + /* sapi_update_response_code doesn't free the status line if the code didn't change */ + if (SG(sapi_headers).http_status_line) { + efree(SG(sapi_headers).http_status_line); + } + SG(sapi_headers).http_status_line = header_line; + return SUCCESS; + } else { + colon_offset = strchr(header_line, ':'); + if (colon_offset) { + *colon_offset = 0; + if (!STRCASECMP(header_line, ""Content-Type"")) { + char *ptr = colon_offset+1, *mimetype = NULL, *newheader; + size_t len = header_line_len - (ptr - header_line), newlen; + while (*ptr == ' ') { + ptr++; + len--; + } + + /* Disable possible output compression for images */ + if (!strncmp(ptr, ""image/"", sizeof(""image/"")-1)) { + zend_alter_ini_entry(""zlib.output_compression"", sizeof(""zlib.output_compression""), ""0"", sizeof(""0"") - 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME); + } + + mimetype = estrdup(ptr); + newlen = sapi_apply_default_charset(&mimetype, len TSRMLS_CC); + if (!SG(sapi_headers).mimetype){ + SG(sapi_headers).mimetype = estrdup(mimetype); + } + + if (newlen != 0) { + newlen += sizeof(""Content-type: ""); + newheader = emalloc(newlen); + PHP_STRLCPY(newheader, ""Content-type: "", newlen, sizeof(""Content-type: "")-1); + strlcat(newheader, mimetype, newlen); + sapi_header.header = newheader; + sapi_header.header_len = newlen - 1; + efree(header_line); + } + efree(mimetype); + SG(sapi_headers).send_default_content_type = 0; + } else if (!STRCASECMP(header_line, ""Content-Length"")) { + /* Script is setting Content-length. The script cannot reasonably + * know the size of the message body after compression, so it's best + * do disable compression altogether. This contributes to making scripts + * portable between setups that have and don't have zlib compression + * enabled globally. See req #44164 */ + zend_alter_ini_entry(""zlib.output_compression"", sizeof(""zlib.output_compression""), + ""0"", sizeof(""0"") - 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME); + } else if (!STRCASECMP(header_line, ""Location"")) { + if ((SG(sapi_headers).http_response_code < 300 || + SG(sapi_headers).http_response_code > 399) && + SG(sapi_headers).http_response_code != 201) { + /* Return a Found Redirect if one is not already specified */ + if (http_response_code) { /* user specified redirect code */ + sapi_update_response_code(http_response_code TSRMLS_CC); + } else if (SG(request_info).proto_num > 1000 && + SG(request_info).request_method && + strcmp(SG(request_info).request_method, ""HEAD"") && + strcmp(SG(request_info).request_method, ""GET"")) { + sapi_update_response_code(303 TSRMLS_CC); + } else { + sapi_update_response_code(302 TSRMLS_CC); + } + } + } else if (!STRCASECMP(header_line, ""WWW-Authenticate"")) { /* HTTP Authentication */ + sapi_update_response_code(401 TSRMLS_CC); /* authentication-required */ + } + if (sapi_header.header==header_line) { + *colon_offset = ':'; + } + } + } + if (http_response_code) { + sapi_update_response_code(http_response_code TSRMLS_CC); + } + sapi_header_add_op(op, &sapi_header TSRMLS_CC); + return SUCCESS; +} +","@@ -743,13 +743,8 @@ SAPI_API int sapi_header_op(sapi_header_op_enum op, void *arg TSRMLS_DC) + /* new line/NUL character safety check */ + int i; + for (i = 0; i < header_line_len; i++) { +- /* RFC 2616 allows new lines if followed by SP or HT */ +- int illegal_break = +- (header_line[i+1] != ' ' && header_line[i+1] != '\t') +- && ( +- header_line[i] == '\n' +- || (header_line[i] == '\r' && header_line[i+1] != '\n')); +- if (illegal_break) { ++ /* RFC 7230 ch. 3.2.4 deprecates folding support */ ++ if (header_line[i] == '\n' || header_line[i] == '\r') { + efree(header_line); + sapi_module.sapi_error(E_WARNING, ""Header may not contain "" + ""more than a single header, new line detected"");",1765,2096,4096 +17613,"IMPEG2D_ERROR_CODES_T impeg2d_process_video_bit_stream(dec_state_t *ps_dec) +{ + stream_t *ps_stream; + UWORD32 u4_next_bits, u4_start_code_found; + IMPEG2D_ERROR_CODES_T e_error; + + ps_stream = &ps_dec->s_bit_stream; + impeg2d_next_start_code(ps_dec); + /* If the stream is MPEG-2 compliant stream */ + u4_start_code_found = 0; + + if(ps_dec->u2_is_mpeg2) + { + /* MPEG2 decoding starts */ + while((u4_start_code_found == 0) && (ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset)) + { + u4_next_bits = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); + + if(u4_next_bits == SEQUENCE_HEADER_CODE) + { + if(ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset) + { + e_error = impeg2d_dec_seq_hdr(ps_dec); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + return e_error; + } + + u4_start_code_found = 0; + + } + else + { + return IMPEG2D_BITSTREAM_BUFF_EXCEEDED_ERR; + } + + + if(ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset) + { + IMPEG2D_ERROR_CODES_T e_error; + e_error = impeg2d_dec_seq_ext(ps_dec); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + return e_error; + } + u4_start_code_found = 0; + + } + else + { + return IMPEG2D_BITSTREAM_BUFF_EXCEEDED_ERR; + } + } + else if((u4_next_bits == USER_DATA_START_CODE) || (u4_next_bits == EXTENSION_START_CODE)) + { + if(ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset) + { + impeg2d_dec_seq_ext_data(ps_dec); + u4_start_code_found = 0; + + } + + } + else if((ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset) + && (u4_next_bits == GOP_START_CODE)) + { + impeg2d_dec_grp_of_pic_hdr(ps_dec); + impeg2d_dec_user_data(ps_dec); + u4_start_code_found = 0; + + } + else if((ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset) + && (u4_next_bits == PICTURE_START_CODE)) + { + ps_dec->i4_pic_count++; + + e_error = impeg2d_dec_pic_hdr(ps_dec); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + return e_error; + } + e_error = impeg2d_dec_pic_coding_ext(ps_dec); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + return e_error; + } + e_error = impeg2d_dec_pic_ext_data(ps_dec); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + return e_error; + } + e_error = impeg2d_pre_pic_dec_proc(ps_dec); + if ((IMPEG2D_ERROR_CODES_T) IVD_ERROR_NONE != e_error) + { + return e_error; + } + impeg2d_dec_pic_data(ps_dec); + impeg2d_post_pic_dec_proc(ps_dec); + u4_start_code_found = 1; + } + else + + { + FLUSH_BITS(ps_dec->s_bit_stream.u4_offset, ps_dec->s_bit_stream.u4_buf, ps_dec->s_bit_stream.u4_buf_nxt, 8, ps_dec->s_bit_stream.pu4_buf_aligned); + + } + if(u4_start_code_found == 0) + { + impeg2d_next_start_code(ps_dec); + /* In case a dec_pic_data call has not been made, the number of + * bytes consumed in the previous header decode has to be + * consumed. Not consuming it will result in zero bytes consumed + * loops in case there are multiple headers and the second + * or a future header has a resolution change/other error where + * the bytes of the last header are not consumed. + */ + ps_dec->i4_bytes_consumed = (ps_dec->s_bit_stream.u4_offset + 7) >> 3; + ps_dec->i4_bytes_consumed -= ((size_t)ps_dec->s_bit_stream.pv_bs_buf & 3); + } + } + if((u4_start_code_found == 0) && (ps_dec->s_bit_stream.u4_offset > ps_dec->s_bit_stream.u4_max_offset)) + { + return IMPEG2D_FRM_HDR_START_CODE_NOT_FOUND; + } + + } + /* If the stream is MPEG-1 compliant stream */ + else + { + while((u4_start_code_found == 0) && (ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset)) + { + u4_next_bits = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); + + if(impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) == SEQUENCE_HEADER_CODE) + { + if(ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset) + { + e_error = impeg2d_dec_seq_hdr(ps_dec); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + return e_error; + } + + u4_start_code_found = 0; + } + else + { + return IMPEG2D_BITSTREAM_BUFF_EXCEEDED_ERR; + } + } + else if((ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset) && (u4_next_bits == EXTENSION_START_CODE || u4_next_bits == USER_DATA_START_CODE)) + { + impeg2d_flush_ext_and_user_data(ps_dec); + u4_start_code_found = 0; + } + + + else if ((impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) == GOP_START_CODE) + && (ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset)) + { + impeg2d_dec_grp_of_pic_hdr(ps_dec); + impeg2d_flush_ext_and_user_data(ps_dec); + u4_start_code_found = 0; + } + else if ((impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) == PICTURE_START_CODE) + && (ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset)) + { + ps_dec->i4_pic_count++; + + e_error = impeg2d_dec_pic_hdr(ps_dec); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + return e_error; + } + impeg2d_flush_ext_and_user_data(ps_dec); + impeg2d_pre_pic_dec_proc(ps_dec); + impeg2d_dec_pic_data(ps_dec); + impeg2d_post_pic_dec_proc(ps_dec); + u4_start_code_found = 1; + } + else + { + FLUSH_BITS(ps_dec->s_bit_stream.u4_offset, ps_dec->s_bit_stream.u4_buf, ps_dec->s_bit_stream.u4_buf_nxt, 8, ps_dec->s_bit_stream.pu4_buf_aligned); + } + impeg2d_next_start_code(ps_dec); + if (0 == u4_start_code_found) + { + /* In case a dec_pic_data call has not been made, the number of + * bytes consumed in the previous header decode has to be + * consumed. Not consuming it will result in zero bytes consumed + * loops in case there are multiple headers and the second + * or a future header has a resolution change/other error where + * the bytes of the last header are not consumed. + */ + ps_dec->i4_bytes_consumed = (ps_dec->s_bit_stream.u4_offset + 7) >> 3; + ps_dec->i4_bytes_consumed -= ((size_t)ps_dec->s_bit_stream.pv_bs_buf & 3); + } + } + if((u4_start_code_found == 0) && (ps_dec->s_bit_stream.u4_offset > ps_dec->s_bit_stream.u4_max_offset)) + { + return IMPEG2D_FRM_HDR_START_CODE_NOT_FOUND; + } + } + + return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; +} +",0,"IMPEG2D_ERROR_CODES_T impeg2d_process_video_bit_stream(dec_state_t *ps_dec) +{ + stream_t *ps_stream; + UWORD32 u4_next_bits, u4_start_code_found; + IMPEG2D_ERROR_CODES_T e_error; + + ps_stream = &ps_dec->s_bit_stream; + impeg2d_next_start_code(ps_dec); + /* If the stream is MPEG-2 compliant stream */ + u4_start_code_found = 0; + + if(ps_dec->u2_is_mpeg2) + { + /* MPEG2 decoding starts */ + while((u4_start_code_found == 0) && (ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset)) + { + u4_next_bits = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); + + if(u4_next_bits == SEQUENCE_HEADER_CODE) + { + if(ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset) + { + e_error = impeg2d_dec_seq_hdr(ps_dec); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + return e_error; + } + + u4_start_code_found = 0; + + } + else + { + return IMPEG2D_BITSTREAM_BUFF_EXCEEDED_ERR; + } + + + if(ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset) + { + IMPEG2D_ERROR_CODES_T e_error; + e_error = impeg2d_dec_seq_ext(ps_dec); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + return e_error; + } + u4_start_code_found = 0; + + } + else + { + return IMPEG2D_BITSTREAM_BUFF_EXCEEDED_ERR; + } + } + else if((u4_next_bits == USER_DATA_START_CODE) || (u4_next_bits == EXTENSION_START_CODE)) + { + if(ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset) + { + impeg2d_dec_seq_ext_data(ps_dec); + u4_start_code_found = 0; + + } + + } + else if((ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset) + && (u4_next_bits == GOP_START_CODE)) + { + impeg2d_dec_grp_of_pic_hdr(ps_dec); + impeg2d_dec_user_data(ps_dec); + u4_start_code_found = 0; + + } + else if((ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset) + && (u4_next_bits == PICTURE_START_CODE)) + { + ps_dec->i4_pic_count++; + + e_error = impeg2d_dec_pic_hdr(ps_dec); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + return e_error; + } + e_error = impeg2d_dec_pic_coding_ext(ps_dec); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + return e_error; + } + e_error = impeg2d_dec_pic_ext_data(ps_dec); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + return e_error; + } + e_error = impeg2d_pre_pic_dec_proc(ps_dec); + if ((IMPEG2D_ERROR_CODES_T) IVD_ERROR_NONE != e_error) + { + return e_error; + } + impeg2d_dec_pic_data(ps_dec); + impeg2d_post_pic_dec_proc(ps_dec); + u4_start_code_found = 1; + } + else + + { + FLUSH_BITS(ps_dec->s_bit_stream.u4_offset, ps_dec->s_bit_stream.u4_buf, ps_dec->s_bit_stream.u4_buf_nxt, 8, ps_dec->s_bit_stream.pu4_buf_aligned); + + } + if(u4_start_code_found == 0) + { + impeg2d_next_start_code(ps_dec); + /* In case a dec_pic_data call has not been made, the number of + * bytes consumed in the previous header decode has to be + * consumed. Not consuming it will result in zero bytes consumed + * loops in case there are multiple headers and the second + * or a future header has a resolution change/other error where + * the bytes of the last header are not consumed. + */ + ps_dec->i4_bytes_consumed = (ps_dec->s_bit_stream.u4_offset + 7) >> 3; + ps_dec->i4_bytes_consumed -= ((size_t)ps_dec->s_bit_stream.pv_bs_buf & 3); + } + } + if((u4_start_code_found == 0) && (ps_dec->s_bit_stream.u4_offset > ps_dec->s_bit_stream.u4_max_offset)) + { + return IMPEG2D_FRM_HDR_START_CODE_NOT_FOUND; + } + + } + /* If the stream is MPEG-1 compliant stream */ + else + { + while((u4_start_code_found == 0) && (ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset)) + { + u4_next_bits = impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN); + + if(impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) == SEQUENCE_HEADER_CODE) + { + if(ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset) + { + e_error = impeg2d_dec_seq_hdr(ps_dec); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + return e_error; + } + + u4_start_code_found = 0; + } + else + { + return IMPEG2D_BITSTREAM_BUFF_EXCEEDED_ERR; + } + } + else if((ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset) && (u4_next_bits == EXTENSION_START_CODE || u4_next_bits == USER_DATA_START_CODE)) + { + impeg2d_flush_ext_and_user_data(ps_dec); + u4_start_code_found = 0; + } + + + else if ((impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) == GOP_START_CODE) + && (ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset)) + { + impeg2d_dec_grp_of_pic_hdr(ps_dec); + impeg2d_flush_ext_and_user_data(ps_dec); + u4_start_code_found = 0; + } + else if ((impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) == PICTURE_START_CODE) + && (ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset)) + { + ps_dec->i4_pic_count++; + + e_error = impeg2d_dec_pic_hdr(ps_dec); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + return e_error; + } + impeg2d_flush_ext_and_user_data(ps_dec); + impeg2d_pre_pic_dec_proc(ps_dec); + impeg2d_dec_pic_data(ps_dec); + impeg2d_post_pic_dec_proc(ps_dec); + u4_start_code_found = 1; + } + else + { + FLUSH_BITS(ps_dec->s_bit_stream.u4_offset, ps_dec->s_bit_stream.u4_buf, ps_dec->s_bit_stream.u4_buf_nxt, 8, ps_dec->s_bit_stream.pu4_buf_aligned); + } + impeg2d_next_start_code(ps_dec); + if (0 == u4_start_code_found) + { + /* In case a dec_pic_data call has not been made, the number of + * bytes consumed in the previous header decode has to be + * consumed. Not consuming it will result in zero bytes consumed + * loops in case there are multiple headers and the second + * or a future header has a resolution change/other error where + * the bytes of the last header are not consumed. + */ + ps_dec->i4_bytes_consumed = (ps_dec->s_bit_stream.u4_offset + 7) >> 3; + ps_dec->i4_bytes_consumed -= ((size_t)ps_dec->s_bit_stream.pv_bs_buf & 3); + } + } + if((u4_start_code_found == 0) && (ps_dec->s_bit_stream.u4_offset > ps_dec->s_bit_stream.u4_max_offset)) + { + return IMPEG2D_FRM_HDR_START_CODE_NOT_FOUND; + } + } + + return (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; +} +","@@ -712,6 +712,11 @@ + + + if(ps_dec->u2_is_mpeg2 == 0) + { ++ if (ps_dec->u2_forw_f_code < 1 || ps_dec->u2_forw_f_code > 7 || ++ ps_dec->u2_back_f_code < 1 || ps_dec->u2_back_f_code > 7) ++ { ++ return IMPEG2D_UNKNOWN_ERROR; ++ } + ps_dec->au2_f_code[0][0] = ps_dec->au2_f_code[0][1] = ps_dec->u2_forw_f_code; + ps_dec->au2_f_code[1][0] = ps_dec->au2_f_code[1][1] = ps_dec->u2_back_f_code; + } +",1804,2135,4096 +18862,"IMPEG2D_ERROR_CODES_T impeg2d_dec_p_b_slice(dec_state_t *ps_dec) +{ + WORD16 *pi2_vld_out; + UWORD32 i; + yuv_buf_t *ps_cur_frm_buf = &ps_dec->s_cur_frm_buf; + + UWORD32 u4_frm_offset = 0; + const dec_mb_params_t *ps_dec_mb_params; + IMPEG2D_ERROR_CODES_T e_error = (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; + + pi2_vld_out = ps_dec->ai2_vld_buf; + memset(ps_dec->ai2_pred_mv,0,sizeof(ps_dec->ai2_pred_mv)); + + ps_dec->u2_prev_intra_mb = 0; + ps_dec->u2_first_mb = 1; + + ps_dec->u2_picture_width = ps_dec->u2_frame_width; + + if(ps_dec->u2_picture_structure != FRAME_PICTURE) + { + ps_dec->u2_picture_width <<= 1; + if(ps_dec->u2_picture_structure == BOTTOM_FIELD) + { + u4_frm_offset = ps_dec->u2_frame_width; + } + } + + + do + { + UWORD32 u4_x_offset, u4_y_offset; + + + UWORD32 u4_x_dst_offset = 0; + UWORD32 u4_y_dst_offset = 0; + UWORD8 *pu1_out_p; + UWORD8 *pu1_pred; + WORD32 u4_pred_strd; + + IMPEG2D_TRACE_MB_START(ps_dec->u2_mb_x, ps_dec->u2_mb_y); + + + + if(ps_dec->e_pic_type == B_PIC) + impeg2d_dec_pnb_mb_params(ps_dec); + else + impeg2d_dec_p_mb_params(ps_dec); + + IMPEG2D_TRACE_MB_START(ps_dec->u2_mb_x, ps_dec->u2_mb_y); + + u4_x_dst_offset = u4_frm_offset + (ps_dec->u2_mb_x << 4); + u4_y_dst_offset = (ps_dec->u2_mb_y << 4) * ps_dec->u2_picture_width; + pu1_out_p = ps_cur_frm_buf->pu1_y + u4_x_dst_offset + u4_y_dst_offset; + if(ps_dec->u2_prev_intra_mb == 0) + { + UWORD32 offset_x, offset_y, stride; + UWORD16 index = (ps_dec->u2_motion_type); + /*only for non intra mb's*/ + if(ps_dec->e_mb_pred == BIDIRECT) + { + ps_dec_mb_params = &ps_dec->ps_func_bi_direct[index]; + } + else + { + ps_dec_mb_params = &ps_dec->ps_func_forw_or_back[index]; + } + + stride = ps_dec->u2_picture_width; + + offset_x = u4_frm_offset + (ps_dec->u2_mb_x << 4); + + offset_y = (ps_dec->u2_mb_y << 4); + + ps_dec->s_dest_buf.pu1_y = ps_cur_frm_buf->pu1_y + offset_y * stride + offset_x; + + stride = stride >> 1; + + ps_dec->s_dest_buf.pu1_u = ps_cur_frm_buf->pu1_u + (offset_y >> 1) * stride + + (offset_x >> 1); + + ps_dec->s_dest_buf.pu1_v = ps_cur_frm_buf->pu1_v + (offset_y >> 1) * stride + + (offset_x >> 1); + + PROFILE_DISABLE_MC_IF0 + ps_dec_mb_params->pf_mc(ps_dec); + + } + for(i = 0; i < NUM_LUMA_BLKS; ++i) + { + if((ps_dec->u2_cbp & (1 << (BLOCKS_IN_MB - 1 - i))) != 0) + { + e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix, + ps_dec->u2_prev_intra_mb, Y_LUMA, 0); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + return e_error; + } + + u4_x_offset = gai2_impeg2_blk_x_off[i]; + + if(ps_dec->u2_field_dct == 0) + u4_y_offset = gai2_impeg2_blk_y_off_frm[i] ; + else + u4_y_offset = gai2_impeg2_blk_y_off_fld[i] ; + + + + + + IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows); + + PROFILE_DISABLE_IDCT_IF0 + { + WORD32 idx; + if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows)) + idx = 0; + else + idx = 1; + + if(0 == ps_dec->u2_prev_intra_mb) + { + pu1_pred = pu1_out_p + u4_y_offset * ps_dec->u2_picture_width + u4_x_offset; + u4_pred_strd = ps_dec->u2_picture_width << ps_dec->u2_field_dct; + } + else + { + pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf; + u4_pred_strd = 8; + } + + ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out, + ps_dec->ai2_idct_stg1, + pu1_pred, + pu1_out_p + u4_y_offset * ps_dec->u2_picture_width + u4_x_offset, + 8, + u4_pred_strd, + ps_dec->u2_picture_width << ps_dec->u2_field_dct, + ~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows); + } + } + + } + + /* For U and V blocks, divide the x and y offsets by 2. */ + u4_x_dst_offset >>= 1; + u4_y_dst_offset >>= 2; + + + /* In case of chrominance blocks the DCT will be frame DCT */ + /* i = 0, U component and i = 1 is V componet */ + if((ps_dec->u2_cbp & 0x02) != 0) + { + pu1_out_p = ps_cur_frm_buf->pu1_u + u4_x_dst_offset + u4_y_dst_offset; + e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix, + ps_dec->u2_prev_intra_mb, U_CHROMA, 0); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + return e_error; + } + + + IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows); + + PROFILE_DISABLE_IDCT_IF0 + { + WORD32 idx; + if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows)) + idx = 0; + else + idx = 1; + + if(0 == ps_dec->u2_prev_intra_mb) + { + pu1_pred = pu1_out_p; + u4_pred_strd = ps_dec->u2_picture_width >> 1; + } + else + { + pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf; + u4_pred_strd = 8; + } + + ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out, + ps_dec->ai2_idct_stg1, + pu1_pred, + pu1_out_p, + 8, + u4_pred_strd, + ps_dec->u2_picture_width >> 1, + ~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows); + + } + + } + + + if((ps_dec->u2_cbp & 0x01) != 0) + { + pu1_out_p = ps_cur_frm_buf->pu1_v + u4_x_dst_offset + u4_y_dst_offset; + e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix, + ps_dec->u2_prev_intra_mb, V_CHROMA, 0); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + return e_error; + } + + + IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows); + + PROFILE_DISABLE_IDCT_IF0 + { + WORD32 idx; + if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows)) + idx = 0; + else + idx = 1; + if(0 == ps_dec->u2_prev_intra_mb) + { + pu1_pred = pu1_out_p; + u4_pred_strd = ps_dec->u2_picture_width >> 1; + } + else + { + pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf; + u4_pred_strd = 8; + } + + ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out, + ps_dec->ai2_idct_stg1, + pu1_pred, + pu1_out_p, + 8, + u4_pred_strd, + ps_dec->u2_picture_width >> 1, + ~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows); + + } + } + + + ps_dec->u2_num_mbs_left--; + ps_dec->u2_first_mb = 0; + ps_dec->u2_mb_x++; + + if(ps_dec->s_bit_stream.u4_offset > ps_dec->s_bit_stream.u4_max_offset) + { + return IMPEG2D_BITSTREAM_BUFF_EXCEEDED_ERR; + } + else if (ps_dec->u2_mb_x == ps_dec->u2_num_horiz_mb) + { + ps_dec->u2_mb_x = 0; + ps_dec->u2_mb_y++; + + } + } + while(ps_dec->u2_num_mbs_left != 0 && impeg2d_bit_stream_nxt(&ps_dec->s_bit_stream,23) != 0x0); + return e_error; +} +",1,"IMPEG2D_ERROR_CODES_T impeg2d_dec_p_b_slice(dec_state_t *ps_dec) +{ + WORD16 *pi2_vld_out; + UWORD32 i; + yuv_buf_t *ps_cur_frm_buf = &ps_dec->s_cur_frm_buf; + + UWORD32 u4_frm_offset = 0; + const dec_mb_params_t *ps_dec_mb_params; + IMPEG2D_ERROR_CODES_T e_error = (IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE; + + pi2_vld_out = ps_dec->ai2_vld_buf; + memset(ps_dec->ai2_pred_mv,0,sizeof(ps_dec->ai2_pred_mv)); + + ps_dec->u2_prev_intra_mb = 0; + ps_dec->u2_first_mb = 1; + + ps_dec->u2_picture_width = ps_dec->u2_frame_width; + + if(ps_dec->u2_picture_structure != FRAME_PICTURE) + { + ps_dec->u2_picture_width <<= 1; + if(ps_dec->u2_picture_structure == BOTTOM_FIELD) + { + u4_frm_offset = ps_dec->u2_frame_width; + } + } + + + do + { + UWORD32 u4_x_offset, u4_y_offset; + WORD32 ret; + + + UWORD32 u4_x_dst_offset = 0; + UWORD32 u4_y_dst_offset = 0; + UWORD8 *pu1_out_p; + UWORD8 *pu1_pred; + WORD32 u4_pred_strd; + + IMPEG2D_TRACE_MB_START(ps_dec->u2_mb_x, ps_dec->u2_mb_y); + + + + if(ps_dec->e_pic_type == B_PIC) + ret = impeg2d_dec_pnb_mb_params(ps_dec); + else + ret = impeg2d_dec_p_mb_params(ps_dec); + + if(ret) + return IMPEG2D_MB_TEX_DECODE_ERR; + IMPEG2D_TRACE_MB_START(ps_dec->u2_mb_x, ps_dec->u2_mb_y); + + u4_x_dst_offset = u4_frm_offset + (ps_dec->u2_mb_x << 4); + u4_y_dst_offset = (ps_dec->u2_mb_y << 4) * ps_dec->u2_picture_width; + pu1_out_p = ps_cur_frm_buf->pu1_y + u4_x_dst_offset + u4_y_dst_offset; + if(ps_dec->u2_prev_intra_mb == 0) + { + UWORD32 offset_x, offset_y, stride; + UWORD16 index = (ps_dec->u2_motion_type); + /*only for non intra mb's*/ + if(ps_dec->e_mb_pred == BIDIRECT) + { + ps_dec_mb_params = &ps_dec->ps_func_bi_direct[index]; + } + else + { + ps_dec_mb_params = &ps_dec->ps_func_forw_or_back[index]; + } + + stride = ps_dec->u2_picture_width; + + offset_x = u4_frm_offset + (ps_dec->u2_mb_x << 4); + + offset_y = (ps_dec->u2_mb_y << 4); + + ps_dec->s_dest_buf.pu1_y = ps_cur_frm_buf->pu1_y + offset_y * stride + offset_x; + + stride = stride >> 1; + + ps_dec->s_dest_buf.pu1_u = ps_cur_frm_buf->pu1_u + (offset_y >> 1) * stride + + (offset_x >> 1); + + ps_dec->s_dest_buf.pu1_v = ps_cur_frm_buf->pu1_v + (offset_y >> 1) * stride + + (offset_x >> 1); + + PROFILE_DISABLE_MC_IF0 + ps_dec_mb_params->pf_mc(ps_dec); + + } + for(i = 0; i < NUM_LUMA_BLKS; ++i) + { + if((ps_dec->u2_cbp & (1 << (BLOCKS_IN_MB - 1 - i))) != 0) + { + e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix, + ps_dec->u2_prev_intra_mb, Y_LUMA, 0); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + return e_error; + } + + u4_x_offset = gai2_impeg2_blk_x_off[i]; + + if(ps_dec->u2_field_dct == 0) + u4_y_offset = gai2_impeg2_blk_y_off_frm[i] ; + else + u4_y_offset = gai2_impeg2_blk_y_off_fld[i] ; + + + + + + IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows); + + PROFILE_DISABLE_IDCT_IF0 + { + WORD32 idx; + if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows)) + idx = 0; + else + idx = 1; + + if(0 == ps_dec->u2_prev_intra_mb) + { + pu1_pred = pu1_out_p + u4_y_offset * ps_dec->u2_picture_width + u4_x_offset; + u4_pred_strd = ps_dec->u2_picture_width << ps_dec->u2_field_dct; + } + else + { + pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf; + u4_pred_strd = 8; + } + + ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out, + ps_dec->ai2_idct_stg1, + pu1_pred, + pu1_out_p + u4_y_offset * ps_dec->u2_picture_width + u4_x_offset, + 8, + u4_pred_strd, + ps_dec->u2_picture_width << ps_dec->u2_field_dct, + ~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows); + } + } + + } + + /* For U and V blocks, divide the x and y offsets by 2. */ + u4_x_dst_offset >>= 1; + u4_y_dst_offset >>= 2; + + + /* In case of chrominance blocks the DCT will be frame DCT */ + /* i = 0, U component and i = 1 is V componet */ + if((ps_dec->u2_cbp & 0x02) != 0) + { + pu1_out_p = ps_cur_frm_buf->pu1_u + u4_x_dst_offset + u4_y_dst_offset; + e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix, + ps_dec->u2_prev_intra_mb, U_CHROMA, 0); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + return e_error; + } + + + IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows); + + PROFILE_DISABLE_IDCT_IF0 + { + WORD32 idx; + if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows)) + idx = 0; + else + idx = 1; + + if(0 == ps_dec->u2_prev_intra_mb) + { + pu1_pred = pu1_out_p; + u4_pred_strd = ps_dec->u2_picture_width >> 1; + } + else + { + pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf; + u4_pred_strd = 8; + } + + ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out, + ps_dec->ai2_idct_stg1, + pu1_pred, + pu1_out_p, + 8, + u4_pred_strd, + ps_dec->u2_picture_width >> 1, + ~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows); + + } + + } + + + if((ps_dec->u2_cbp & 0x01) != 0) + { + pu1_out_p = ps_cur_frm_buf->pu1_v + u4_x_dst_offset + u4_y_dst_offset; + e_error = ps_dec->pf_vld_inv_quant(ps_dec, pi2_vld_out, ps_dec->pu1_inv_scan_matrix, + ps_dec->u2_prev_intra_mb, V_CHROMA, 0); + if ((IMPEG2D_ERROR_CODES_T)IVD_ERROR_NONE != e_error) + { + return e_error; + } + + + IMPEG2D_IDCT_INP_STATISTICS(pi2_vld_out, ps_dec->u4_non_zero_cols, ps_dec->u4_non_zero_rows); + + PROFILE_DISABLE_IDCT_IF0 + { + WORD32 idx; + if(1 == (ps_dec->u4_non_zero_cols | ps_dec->u4_non_zero_rows)) + idx = 0; + else + idx = 1; + if(0 == ps_dec->u2_prev_intra_mb) + { + pu1_pred = pu1_out_p; + u4_pred_strd = ps_dec->u2_picture_width >> 1; + } + else + { + pu1_pred = (UWORD8 *)gau1_impeg2_zerobuf; + u4_pred_strd = 8; + } + + ps_dec->pf_idct_recon[idx * 2 + ps_dec->i4_last_value_one](pi2_vld_out, + ps_dec->ai2_idct_stg1, + pu1_pred, + pu1_out_p, + 8, + u4_pred_strd, + ps_dec->u2_picture_width >> 1, + ~ps_dec->u4_non_zero_cols, ~ps_dec->u4_non_zero_rows); + + } + } + + + ps_dec->u2_num_mbs_left--; + ps_dec->u2_first_mb = 0; + ps_dec->u2_mb_x++; + + if(ps_dec->s_bit_stream.u4_offset > ps_dec->s_bit_stream.u4_max_offset) + { + return IMPEG2D_BITSTREAM_BUFF_EXCEEDED_ERR; + } + else if (ps_dec->u2_mb_x == ps_dec->u2_num_horiz_mb) + { + ps_dec->u2_mb_x = 0; + ps_dec->u2_mb_y++; + + } + } + while(ps_dec->u2_num_mbs_left != 0 && impeg2d_bit_stream_nxt(&ps_dec->s_bit_stream,23) != 0x0); + return e_error; +} +","@@ -60,7 +60,7 @@ + + * + * Values Returned : None + *******************************************************************************/ +-void impeg2d_dec_p_mb_params(dec_state_t *ps_dec) ++WORD32 impeg2d_dec_p_mb_params(dec_state_t *ps_dec) + { + stream_t *ps_stream = &ps_dec->s_bit_stream; + UWORD16 u2_mb_addr_incr; +@@ -180,6 +180,8 @@ + + ps_dec->e_mb_pred = (e_pred_direction_t)refPic; + ps_dec_mb_params = &ps_dec->ps_func_forw_or_back[index]; + ps_dec->s_mb_type = ps_dec_mb_params->s_mb_type; ++ if(NULL == ps_dec_mb_params->pf_func_mb_params) ++ return -1; + ps_dec_mb_params->pf_func_mb_params(ps_dec); + + } +@@ -223,6 +225,7 @@ + + ps_dec->u2_cbp = 0; + } + } ++ return 0; + } + + +@@ -237,7 +240,7 @@ + + * + * Values Returned : None + *******************************************************************************/ +-void impeg2d_dec_pnb_mb_params(dec_state_t *ps_dec) ++WORD32 impeg2d_dec_pnb_mb_params(dec_state_t *ps_dec) + { + stream_t *ps_stream = &ps_dec->s_bit_stream; + UWORD16 u2_mb_addr_incr; +@@ -373,6 +376,8 @@ + + ps_dec->e_mb_pred = BIDIRECT; + ps_dec_mb_params = &ps_dec->ps_func_bi_direct[u2_index]; + ps_dec->s_mb_type = ps_dec_mb_params->s_mb_type; ++ if(NULL == ps_dec_mb_params->pf_func_mb_params) ++ return -1; + ps_dec_mb_params->pf_func_mb_params(ps_dec); + } + else if(u2_mb_type & MB_FORW_OR_BACK) +@@ -384,6 +389,8 @@ + + ps_dec->e_mb_pred = (e_pred_direction_t)u2_refPic; + ps_dec_mb_params = &ps_dec->ps_func_forw_or_back[u2_index]; + ps_dec->s_mb_type = ps_dec_mb_params->s_mb_type; ++ if(NULL == ps_dec_mb_params->pf_func_mb_params) ++ return -1; + ps_dec_mb_params->pf_func_mb_params(ps_dec); + + } +@@ -427,6 +434,7 @@ + + ps_dec->u2_cbp = 0; + } + } ++ return 0; + } + + /******************************************************************************* +@@ -469,7 +477,7 @@ + + do + { + UWORD32 u4_x_offset, u4_y_offset; +- ++ WORD32 ret; + + + UWORD32 u4_x_dst_offset = 0; +@@ -482,10 +490,12 @@ + + + + if(ps_dec->e_pic_type == B_PIC) +- impeg2d_dec_pnb_mb_params(ps_dec); ++ ret = impeg2d_dec_pnb_mb_params(ps_dec); + else +- impeg2d_dec_p_mb_params(ps_dec); ++ ret = impeg2d_dec_p_mb_params(ps_dec); + ++ if(ret) ++ return IMPEG2D_MB_TEX_DECODE_ERR; + IMPEG2D_TRACE_MB_START(ps_dec->u2_mb_x, ps_dec->u2_mb_y); + + u4_x_dst_offset = u4_frm_offset + (ps_dec->u2_mb_x << 4); +",2282,2613,4096 +2211,"static unsigned long scan_swap_map(struct swap_info_struct *si, + unsigned char usage) +{ + unsigned long offset; + unsigned long scan_base; + unsigned long last_in_cluster = 0; + int latency_ration = LATENCY_LIMIT; + int found_free_cluster = 0; + + /* + * We try to cluster swap pages by allocating them sequentially + * in swap. Once we've allocated SWAPFILE_CLUSTER pages this + * way, however, we resort to first-free allocation, starting + * a new cluster. This prevents us from scattering swap pages + * all over the entire swap partition, so that we reduce + * overall disk seek times between swap pages. -- sct + * But we do now try to find an empty cluster. -Andrea + * And we let swap pages go all over an SSD partition. Hugh + */ + + si->flags += SWP_SCANNING; + scan_base = offset = si->cluster_next; + + if (unlikely(!si->cluster_nr--)) { + if (si->pages - si->inuse_pages < SWAPFILE_CLUSTER) { + si->cluster_nr = SWAPFILE_CLUSTER - 1; + goto checks; + } + if (si->flags & SWP_DISCARDABLE) { + /* + * Start range check on racing allocations, in case + * they overlap the cluster we eventually decide on + * (we scan without swap_lock to allow preemption). + * It's hardly conceivable that cluster_nr could be + * wrapped during our scan, but don't depend on it. + */ + if (si->lowest_alloc) + goto checks; + si->lowest_alloc = si->max; + si->highest_alloc = 0; + } + spin_unlock(&swap_lock); + + /* + * If seek is expensive, start searching for new cluster from + * start of partition, to minimize the span of allocated swap. + * But if seek is cheap, search from our current position, so + * that swap is allocated from all over the partition: if the + * Flash Translation Layer only remaps within limited zones, + * we don't want to wear out the first zone too quickly. + */ + if (!(si->flags & SWP_SOLIDSTATE)) + scan_base = offset = si->lowest_bit; + last_in_cluster = offset + SWAPFILE_CLUSTER - 1; + + /* Locate the first empty (unaligned) cluster */ + for (; last_in_cluster <= si->highest_bit; offset++) { + if (si->swap_map[offset]) + last_in_cluster = offset + SWAPFILE_CLUSTER; + else if (offset == last_in_cluster) { + spin_lock(&swap_lock); + offset -= SWAPFILE_CLUSTER - 1; + si->cluster_next = offset; + si->cluster_nr = SWAPFILE_CLUSTER - 1; + found_free_cluster = 1; + goto checks; + } + if (unlikely(--latency_ration < 0)) { + cond_resched(); + latency_ration = LATENCY_LIMIT; + } + } + + offset = si->lowest_bit; + last_in_cluster = offset + SWAPFILE_CLUSTER - 1; + + /* Locate the first empty (unaligned) cluster */ + for (; last_in_cluster < scan_base; offset++) { + if (si->swap_map[offset]) + last_in_cluster = offset + SWAPFILE_CLUSTER; + else if (offset == last_in_cluster) { + spin_lock(&swap_lock); + offset -= SWAPFILE_CLUSTER - 1; + si->cluster_next = offset; + si->cluster_nr = SWAPFILE_CLUSTER - 1; + found_free_cluster = 1; + goto checks; + } + if (unlikely(--latency_ration < 0)) { + cond_resched(); + latency_ration = LATENCY_LIMIT; + } + } + + offset = scan_base; + spin_lock(&swap_lock); + si->cluster_nr = SWAPFILE_CLUSTER - 1; + si->lowest_alloc = 0; + } + +checks: + if (!(si->flags & SWP_WRITEOK)) + goto no_page; + if (!si->highest_bit) + goto no_page; + if (offset > si->highest_bit) + scan_base = offset = si->lowest_bit; + + /* reuse swap entry of cache-only swap if not busy. */ + if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) { + int swap_was_freed; + spin_unlock(&swap_lock); + swap_was_freed = __try_to_reclaim_swap(si, offset); + spin_lock(&swap_lock); + /* entry was freed successfully, try to use this again */ + if (swap_was_freed) + goto checks; + goto scan; /* check next one */ + } + + if (si->swap_map[offset]) + goto scan; + + if (offset == si->lowest_bit) + si->lowest_bit++; + if (offset == si->highest_bit) + si->highest_bit--; + si->inuse_pages++; + if (si->inuse_pages == si->pages) { + si->lowest_bit = si->max; + si->highest_bit = 0; + } + si->swap_map[offset] = usage; + si->cluster_next = offset + 1; + si->flags -= SWP_SCANNING; + + if (si->lowest_alloc) { + /* + * Only set when SWP_DISCARDABLE, and there's a scan + * for a free cluster in progress or just completed. + */ + if (found_free_cluster) { + /* + * To optimize wear-levelling, discard the + * old data of the cluster, taking care not to + * discard any of its pages that have already + * been allocated by racing tasks (offset has + * already stepped over any at the beginning). + */ + if (offset < si->highest_alloc && + si->lowest_alloc <= last_in_cluster) + last_in_cluster = si->lowest_alloc - 1; + si->flags |= SWP_DISCARDING; + spin_unlock(&swap_lock); + + if (offset < last_in_cluster) + discard_swap_cluster(si, offset, + last_in_cluster - offset + 1); + + spin_lock(&swap_lock); + si->lowest_alloc = 0; + si->flags &= ~SWP_DISCARDING; + + smp_mb(); /* wake_up_bit advises this */ + wake_up_bit(&si->flags, ilog2(SWP_DISCARDING)); + + } else if (si->flags & SWP_DISCARDING) { + /* + * Delay using pages allocated by racing tasks + * until the whole discard has been issued. We + * could defer that delay until swap_writepage, + * but it's easier to keep this self-contained. + */ + spin_unlock(&swap_lock); + wait_on_bit(&si->flags, ilog2(SWP_DISCARDING), + wait_for_discard, TASK_UNINTERRUPTIBLE); + spin_lock(&swap_lock); + } else { + /* + * Note pages allocated by racing tasks while + * scan for a free cluster is in progress, so + * that its final discard can exclude them. + */ + if (offset < si->lowest_alloc) + si->lowest_alloc = offset; + if (offset > si->highest_alloc) + si->highest_alloc = offset; + } + } + return offset; + +scan: + spin_unlock(&swap_lock); + while (++offset <= si->highest_bit) { + if (!si->swap_map[offset]) { + spin_lock(&swap_lock); + goto checks; + } + if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) { + spin_lock(&swap_lock); + goto checks; + } + if (unlikely(--latency_ration < 0)) { + cond_resched(); + latency_ration = LATENCY_LIMIT; + } + } + offset = si->lowest_bit; + while (++offset < scan_base) { + if (!si->swap_map[offset]) { + spin_lock(&swap_lock); + goto checks; + } + if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) { + spin_lock(&swap_lock); + goto checks; + } + if (unlikely(--latency_ration < 0)) { + cond_resched(); + latency_ration = LATENCY_LIMIT; + } + } + spin_lock(&swap_lock); + +no_page: + si->flags -= SWP_SCANNING; + return 0; +} +",0,"static unsigned long scan_swap_map(struct swap_info_struct *si, + unsigned char usage) +{ + unsigned long offset; + unsigned long scan_base; + unsigned long last_in_cluster = 0; + int latency_ration = LATENCY_LIMIT; + int found_free_cluster = 0; + + /* + * We try to cluster swap pages by allocating them sequentially + * in swap. Once we've allocated SWAPFILE_CLUSTER pages this + * way, however, we resort to first-free allocation, starting + * a new cluster. This prevents us from scattering swap pages + * all over the entire swap partition, so that we reduce + * overall disk seek times between swap pages. -- sct + * But we do now try to find an empty cluster. -Andrea + * And we let swap pages go all over an SSD partition. Hugh + */ + + si->flags += SWP_SCANNING; + scan_base = offset = si->cluster_next; + + if (unlikely(!si->cluster_nr--)) { + if (si->pages - si->inuse_pages < SWAPFILE_CLUSTER) { + si->cluster_nr = SWAPFILE_CLUSTER - 1; + goto checks; + } + if (si->flags & SWP_DISCARDABLE) { + /* + * Start range check on racing allocations, in case + * they overlap the cluster we eventually decide on + * (we scan without swap_lock to allow preemption). + * It's hardly conceivable that cluster_nr could be + * wrapped during our scan, but don't depend on it. + */ + if (si->lowest_alloc) + goto checks; + si->lowest_alloc = si->max; + si->highest_alloc = 0; + } + spin_unlock(&swap_lock); + + /* + * If seek is expensive, start searching for new cluster from + * start of partition, to minimize the span of allocated swap. + * But if seek is cheap, search from our current position, so + * that swap is allocated from all over the partition: if the + * Flash Translation Layer only remaps within limited zones, + * we don't want to wear out the first zone too quickly. + */ + if (!(si->flags & SWP_SOLIDSTATE)) + scan_base = offset = si->lowest_bit; + last_in_cluster = offset + SWAPFILE_CLUSTER - 1; + + /* Locate the first empty (unaligned) cluster */ + for (; last_in_cluster <= si->highest_bit; offset++) { + if (si->swap_map[offset]) + last_in_cluster = offset + SWAPFILE_CLUSTER; + else if (offset == last_in_cluster) { + spin_lock(&swap_lock); + offset -= SWAPFILE_CLUSTER - 1; + si->cluster_next = offset; + si->cluster_nr = SWAPFILE_CLUSTER - 1; + found_free_cluster = 1; + goto checks; + } + if (unlikely(--latency_ration < 0)) { + cond_resched(); + latency_ration = LATENCY_LIMIT; + } + } + + offset = si->lowest_bit; + last_in_cluster = offset + SWAPFILE_CLUSTER - 1; + + /* Locate the first empty (unaligned) cluster */ + for (; last_in_cluster < scan_base; offset++) { + if (si->swap_map[offset]) + last_in_cluster = offset + SWAPFILE_CLUSTER; + else if (offset == last_in_cluster) { + spin_lock(&swap_lock); + offset -= SWAPFILE_CLUSTER - 1; + si->cluster_next = offset; + si->cluster_nr = SWAPFILE_CLUSTER - 1; + found_free_cluster = 1; + goto checks; + } + if (unlikely(--latency_ration < 0)) { + cond_resched(); + latency_ration = LATENCY_LIMIT; + } + } + + offset = scan_base; + spin_lock(&swap_lock); + si->cluster_nr = SWAPFILE_CLUSTER - 1; + si->lowest_alloc = 0; + } + +checks: + if (!(si->flags & SWP_WRITEOK)) + goto no_page; + if (!si->highest_bit) + goto no_page; + if (offset > si->highest_bit) + scan_base = offset = si->lowest_bit; + + /* reuse swap entry of cache-only swap if not busy. */ + if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) { + int swap_was_freed; + spin_unlock(&swap_lock); + swap_was_freed = __try_to_reclaim_swap(si, offset); + spin_lock(&swap_lock); + /* entry was freed successfully, try to use this again */ + if (swap_was_freed) + goto checks; + goto scan; /* check next one */ + } + + if (si->swap_map[offset]) + goto scan; + + if (offset == si->lowest_bit) + si->lowest_bit++; + if (offset == si->highest_bit) + si->highest_bit--; + si->inuse_pages++; + if (si->inuse_pages == si->pages) { + si->lowest_bit = si->max; + si->highest_bit = 0; + } + si->swap_map[offset] = usage; + si->cluster_next = offset + 1; + si->flags -= SWP_SCANNING; + + if (si->lowest_alloc) { + /* + * Only set when SWP_DISCARDABLE, and there's a scan + * for a free cluster in progress or just completed. + */ + if (found_free_cluster) { + /* + * To optimize wear-levelling, discard the + * old data of the cluster, taking care not to + * discard any of its pages that have already + * been allocated by racing tasks (offset has + * already stepped over any at the beginning). + */ + if (offset < si->highest_alloc && + si->lowest_alloc <= last_in_cluster) + last_in_cluster = si->lowest_alloc - 1; + si->flags |= SWP_DISCARDING; + spin_unlock(&swap_lock); + + if (offset < last_in_cluster) + discard_swap_cluster(si, offset, + last_in_cluster - offset + 1); + + spin_lock(&swap_lock); + si->lowest_alloc = 0; + si->flags &= ~SWP_DISCARDING; + + smp_mb(); /* wake_up_bit advises this */ + wake_up_bit(&si->flags, ilog2(SWP_DISCARDING)); + + } else if (si->flags & SWP_DISCARDING) { + /* + * Delay using pages allocated by racing tasks + * until the whole discard has been issued. We + * could defer that delay until swap_writepage, + * but it's easier to keep this self-contained. + */ + spin_unlock(&swap_lock); + wait_on_bit(&si->flags, ilog2(SWP_DISCARDING), + wait_for_discard, TASK_UNINTERRUPTIBLE); + spin_lock(&swap_lock); + } else { + /* + * Note pages allocated by racing tasks while + * scan for a free cluster is in progress, so + * that its final discard can exclude them. + */ + if (offset < si->lowest_alloc) + si->lowest_alloc = offset; + if (offset > si->highest_alloc) + si->highest_alloc = offset; + } + } + return offset; + +scan: + spin_unlock(&swap_lock); + while (++offset <= si->highest_bit) { + if (!si->swap_map[offset]) { + spin_lock(&swap_lock); + goto checks; + } + if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) { + spin_lock(&swap_lock); + goto checks; + } + if (unlikely(--latency_ration < 0)) { + cond_resched(); + latency_ration = LATENCY_LIMIT; + } + } + offset = si->lowest_bit; + while (++offset < scan_base) { + if (!si->swap_map[offset]) { + spin_lock(&swap_lock); + goto checks; + } + if (vm_swap_full() && si->swap_map[offset] == SWAP_HAS_CACHE) { + spin_lock(&swap_lock); + goto checks; + } + if (unlikely(--latency_ration < 0)) { + cond_resched(); + latency_ration = LATENCY_LIMIT; + } + } + spin_lock(&swap_lock); + +no_page: + si->flags -= SWP_SCANNING; + return 0; +} +","@@ -932,9 +932,7 @@ static inline int unuse_pmd_range(struct vm_area_struct *vma, pud_t *pud, + pmd = pmd_offset(pud, addr); + do { + next = pmd_addr_end(addr, end); +- if (unlikely(pmd_trans_huge(*pmd))) +- continue; +- if (pmd_none_or_clear_bad(pmd)) ++ if (pmd_none_or_trans_huge_or_clear_bad(pmd)) + continue; + ret = unuse_pte_range(vma, pmd, addr, next, entry, page); + if (ret)",1861,2192,4096 +5346,"static int rtnl_newlink(struct sk_buff *skb, struct nlmsghdr *nlh) +{ + struct net *net = sock_net(skb->sk); + const struct rtnl_link_ops *ops; + const struct rtnl_link_ops *m_ops = NULL; + struct net_device *dev; + struct net_device *master_dev = NULL; + struct ifinfomsg *ifm; + char kind[MODULE_NAME_LEN]; + char ifname[IFNAMSIZ]; + struct nlattr *tb[IFLA_MAX+1]; + struct nlattr *linkinfo[IFLA_INFO_MAX+1]; + unsigned char name_assign_type = NET_NAME_USER; + int err; + +#ifdef CONFIG_MODULES +replay: +#endif + err = nlmsg_parse(nlh, sizeof(*ifm), tb, IFLA_MAX, ifla_policy); + if (err < 0) + return err; + + if (tb[IFLA_IFNAME]) + nla_strlcpy(ifname, tb[IFLA_IFNAME], IFNAMSIZ); + else + ifname[0] = '\0'; + + ifm = nlmsg_data(nlh); + if (ifm->ifi_index > 0) + dev = __dev_get_by_index(net, ifm->ifi_index); + else { + if (ifname[0]) + dev = __dev_get_by_name(net, ifname); + else + dev = NULL; + } + + if (dev) { + master_dev = netdev_master_upper_dev_get(dev); + if (master_dev) + m_ops = master_dev->rtnl_link_ops; + } + + err = validate_linkmsg(dev, tb); + if (err < 0) + return err; + + if (tb[IFLA_LINKINFO]) { + err = nla_parse_nested(linkinfo, IFLA_INFO_MAX, + tb[IFLA_LINKINFO], ifla_info_policy); + if (err < 0) + return err; + } else + memset(linkinfo, 0, sizeof(linkinfo)); + + if (linkinfo[IFLA_INFO_KIND]) { + nla_strlcpy(kind, linkinfo[IFLA_INFO_KIND], sizeof(kind)); + ops = rtnl_link_ops_get(kind); + } else { + kind[0] = '\0'; + ops = NULL; + } + + if (1) { + struct nlattr *attr[ops ? ops->maxtype + 1 : 1]; + struct nlattr *slave_attr[m_ops ? m_ops->slave_maxtype + 1 : 1]; + struct nlattr **data = NULL; + struct nlattr **slave_data = NULL; + struct net *dest_net, *link_net = NULL; + + if (ops) { + if (ops->maxtype && linkinfo[IFLA_INFO_DATA]) { + err = nla_parse_nested(attr, ops->maxtype, + linkinfo[IFLA_INFO_DATA], + ops->policy); + if (err < 0) + return err; + data = attr; + } + if (ops->validate) { + err = ops->validate(tb, data); + if (err < 0) + return err; + } + } + + if (m_ops) { + if (m_ops->slave_maxtype && + linkinfo[IFLA_INFO_SLAVE_DATA]) { + err = nla_parse_nested(slave_attr, + m_ops->slave_maxtype, + linkinfo[IFLA_INFO_SLAVE_DATA], + m_ops->slave_policy); + if (err < 0) + return err; + slave_data = slave_attr; + } + if (m_ops->slave_validate) { + err = m_ops->slave_validate(tb, slave_data); + if (err < 0) + return err; + } + } + + if (dev) { + int status = 0; + + if (nlh->nlmsg_flags & NLM_F_EXCL) + return -EEXIST; + if (nlh->nlmsg_flags & NLM_F_REPLACE) + return -EOPNOTSUPP; + + if (linkinfo[IFLA_INFO_DATA]) { + if (!ops || ops != dev->rtnl_link_ops || + !ops->changelink) + return -EOPNOTSUPP; + + err = ops->changelink(dev, tb, data); + if (err < 0) + return err; + status |= DO_SETLINK_NOTIFY; + } + + if (linkinfo[IFLA_INFO_SLAVE_DATA]) { + if (!m_ops || !m_ops->slave_changelink) + return -EOPNOTSUPP; + + err = m_ops->slave_changelink(master_dev, dev, + tb, slave_data); + if (err < 0) + return err; + status |= DO_SETLINK_NOTIFY; + } + + return do_setlink(skb, dev, ifm, tb, ifname, status); + } + + if (!(nlh->nlmsg_flags & NLM_F_CREATE)) { + if (ifm->ifi_index == 0 && tb[IFLA_GROUP]) + return rtnl_group_changelink(skb, net, + nla_get_u32(tb[IFLA_GROUP]), + ifm, tb); + return -ENODEV; + } + + if (tb[IFLA_MAP] || tb[IFLA_MASTER] || tb[IFLA_PROTINFO]) + return -EOPNOTSUPP; + + if (!ops) { +#ifdef CONFIG_MODULES + if (kind[0]) { + __rtnl_unlock(); + request_module(""rtnl-link-%s"", kind); + rtnl_lock(); + ops = rtnl_link_ops_get(kind); + if (ops) + goto replay; + } +#endif + return -EOPNOTSUPP; + } + + if (!ops->setup) + return -EOPNOTSUPP; + + if (!ifname[0]) { + snprintf(ifname, IFNAMSIZ, ""%s%%d"", ops->kind); + name_assign_type = NET_NAME_ENUM; + } + + dest_net = rtnl_link_get_net(net, tb); + if (IS_ERR(dest_net)) + return PTR_ERR(dest_net); + + err = -EPERM; + if (!netlink_ns_capable(skb, dest_net->user_ns, CAP_NET_ADMIN)) + goto out; + + if (tb[IFLA_LINK_NETNSID]) { + int id = nla_get_s32(tb[IFLA_LINK_NETNSID]); + + link_net = get_net_ns_by_id(dest_net, id); + if (!link_net) { + err = -EINVAL; + goto out; + } + err = -EPERM; + if (!netlink_ns_capable(skb, link_net->user_ns, CAP_NET_ADMIN)) + goto out; + } + + dev = rtnl_create_link(link_net ? : dest_net, ifname, + name_assign_type, ops, tb); + if (IS_ERR(dev)) { + err = PTR_ERR(dev); + goto out; + } + + dev->ifindex = ifm->ifi_index; + + if (ops->newlink) { + err = ops->newlink(link_net ? : net, dev, tb, data); + /* Drivers should call free_netdev() in ->destructor + * and unregister it on failure after registration + * so that device could be finally freed in rtnl_unlock. + */ + if (err < 0) { + /* If device is not registered at all, free it now */ + if (dev->reg_state == NETREG_UNINITIALIZED) + free_netdev(dev); + goto out; + } + } else { + err = register_netdevice(dev); + if (err < 0) { + free_netdev(dev); + goto out; + } + } + err = rtnl_configure_link(dev, ifm); + if (err < 0) + goto out_unregister; + if (link_net) { + err = dev_change_net_namespace(dev, dest_net, ifname); + if (err < 0) + goto out_unregister; + } +out: + if (link_net) + put_net(link_net); + put_net(dest_net); + return err; +out_unregister: + if (ops->newlink) { + LIST_HEAD(list_kill); + + ops->dellink(dev, &list_kill); + unregister_netdevice_many(&list_kill); + } else { + unregister_netdevice(dev); + } + goto out; + } +} +",0,"static int rtnl_newlink(struct sk_buff *skb, struct nlmsghdr *nlh) +{ + struct net *net = sock_net(skb->sk); + const struct rtnl_link_ops *ops; + const struct rtnl_link_ops *m_ops = NULL; + struct net_device *dev; + struct net_device *master_dev = NULL; + struct ifinfomsg *ifm; + char kind[MODULE_NAME_LEN]; + char ifname[IFNAMSIZ]; + struct nlattr *tb[IFLA_MAX+1]; + struct nlattr *linkinfo[IFLA_INFO_MAX+1]; + unsigned char name_assign_type = NET_NAME_USER; + int err; + +#ifdef CONFIG_MODULES +replay: +#endif + err = nlmsg_parse(nlh, sizeof(*ifm), tb, IFLA_MAX, ifla_policy); + if (err < 0) + return err; + + if (tb[IFLA_IFNAME]) + nla_strlcpy(ifname, tb[IFLA_IFNAME], IFNAMSIZ); + else + ifname[0] = '\0'; + + ifm = nlmsg_data(nlh); + if (ifm->ifi_index > 0) + dev = __dev_get_by_index(net, ifm->ifi_index); + else { + if (ifname[0]) + dev = __dev_get_by_name(net, ifname); + else + dev = NULL; + } + + if (dev) { + master_dev = netdev_master_upper_dev_get(dev); + if (master_dev) + m_ops = master_dev->rtnl_link_ops; + } + + err = validate_linkmsg(dev, tb); + if (err < 0) + return err; + + if (tb[IFLA_LINKINFO]) { + err = nla_parse_nested(linkinfo, IFLA_INFO_MAX, + tb[IFLA_LINKINFO], ifla_info_policy); + if (err < 0) + return err; + } else + memset(linkinfo, 0, sizeof(linkinfo)); + + if (linkinfo[IFLA_INFO_KIND]) { + nla_strlcpy(kind, linkinfo[IFLA_INFO_KIND], sizeof(kind)); + ops = rtnl_link_ops_get(kind); + } else { + kind[0] = '\0'; + ops = NULL; + } + + if (1) { + struct nlattr *attr[ops ? ops->maxtype + 1 : 1]; + struct nlattr *slave_attr[m_ops ? m_ops->slave_maxtype + 1 : 1]; + struct nlattr **data = NULL; + struct nlattr **slave_data = NULL; + struct net *dest_net, *link_net = NULL; + + if (ops) { + if (ops->maxtype && linkinfo[IFLA_INFO_DATA]) { + err = nla_parse_nested(attr, ops->maxtype, + linkinfo[IFLA_INFO_DATA], + ops->policy); + if (err < 0) + return err; + data = attr; + } + if (ops->validate) { + err = ops->validate(tb, data); + if (err < 0) + return err; + } + } + + if (m_ops) { + if (m_ops->slave_maxtype && + linkinfo[IFLA_INFO_SLAVE_DATA]) { + err = nla_parse_nested(slave_attr, + m_ops->slave_maxtype, + linkinfo[IFLA_INFO_SLAVE_DATA], + m_ops->slave_policy); + if (err < 0) + return err; + slave_data = slave_attr; + } + if (m_ops->slave_validate) { + err = m_ops->slave_validate(tb, slave_data); + if (err < 0) + return err; + } + } + + if (dev) { + int status = 0; + + if (nlh->nlmsg_flags & NLM_F_EXCL) + return -EEXIST; + if (nlh->nlmsg_flags & NLM_F_REPLACE) + return -EOPNOTSUPP; + + if (linkinfo[IFLA_INFO_DATA]) { + if (!ops || ops != dev->rtnl_link_ops || + !ops->changelink) + return -EOPNOTSUPP; + + err = ops->changelink(dev, tb, data); + if (err < 0) + return err; + status |= DO_SETLINK_NOTIFY; + } + + if (linkinfo[IFLA_INFO_SLAVE_DATA]) { + if (!m_ops || !m_ops->slave_changelink) + return -EOPNOTSUPP; + + err = m_ops->slave_changelink(master_dev, dev, + tb, slave_data); + if (err < 0) + return err; + status |= DO_SETLINK_NOTIFY; + } + + return do_setlink(skb, dev, ifm, tb, ifname, status); + } + + if (!(nlh->nlmsg_flags & NLM_F_CREATE)) { + if (ifm->ifi_index == 0 && tb[IFLA_GROUP]) + return rtnl_group_changelink(skb, net, + nla_get_u32(tb[IFLA_GROUP]), + ifm, tb); + return -ENODEV; + } + + if (tb[IFLA_MAP] || tb[IFLA_MASTER] || tb[IFLA_PROTINFO]) + return -EOPNOTSUPP; + + if (!ops) { +#ifdef CONFIG_MODULES + if (kind[0]) { + __rtnl_unlock(); + request_module(""rtnl-link-%s"", kind); + rtnl_lock(); + ops = rtnl_link_ops_get(kind); + if (ops) + goto replay; + } +#endif + return -EOPNOTSUPP; + } + + if (!ops->setup) + return -EOPNOTSUPP; + + if (!ifname[0]) { + snprintf(ifname, IFNAMSIZ, ""%s%%d"", ops->kind); + name_assign_type = NET_NAME_ENUM; + } + + dest_net = rtnl_link_get_net(net, tb); + if (IS_ERR(dest_net)) + return PTR_ERR(dest_net); + + err = -EPERM; + if (!netlink_ns_capable(skb, dest_net->user_ns, CAP_NET_ADMIN)) + goto out; + + if (tb[IFLA_LINK_NETNSID]) { + int id = nla_get_s32(tb[IFLA_LINK_NETNSID]); + + link_net = get_net_ns_by_id(dest_net, id); + if (!link_net) { + err = -EINVAL; + goto out; + } + err = -EPERM; + if (!netlink_ns_capable(skb, link_net->user_ns, CAP_NET_ADMIN)) + goto out; + } + + dev = rtnl_create_link(link_net ? : dest_net, ifname, + name_assign_type, ops, tb); + if (IS_ERR(dev)) { + err = PTR_ERR(dev); + goto out; + } + + dev->ifindex = ifm->ifi_index; + + if (ops->newlink) { + err = ops->newlink(link_net ? : net, dev, tb, data); + /* Drivers should call free_netdev() in ->destructor + * and unregister it on failure after registration + * so that device could be finally freed in rtnl_unlock. + */ + if (err < 0) { + /* If device is not registered at all, free it now */ + if (dev->reg_state == NETREG_UNINITIALIZED) + free_netdev(dev); + goto out; + } + } else { + err = register_netdevice(dev); + if (err < 0) { + free_netdev(dev); + goto out; + } + } + err = rtnl_configure_link(dev, ifm); + if (err < 0) + goto out_unregister; + if (link_net) { + err = dev_change_net_namespace(dev, dest_net, ifname); + if (err < 0) + goto out_unregister; + } +out: + if (link_net) + put_net(link_net); + put_net(dest_net); + return err; +out_unregister: + if (ops->newlink) { + LIST_HEAD(list_kill); + + ops->dellink(dev, &list_kill); + unregister_netdevice_many(&list_kill); + } else { + unregister_netdevice(dev); + } + goto out; + } +} +","@@ -1180,14 +1180,16 @@ static noinline_for_stack int rtnl_fill_vfinfo(struct sk_buff *skb, + + static int rtnl_fill_link_ifmap(struct sk_buff *skb, struct net_device *dev) + { +- struct rtnl_link_ifmap map = { +- .mem_start = dev->mem_start, +- .mem_end = dev->mem_end, +- .base_addr = dev->base_addr, +- .irq = dev->irq, +- .dma = dev->dma, +- .port = dev->if_port, +- }; ++ struct rtnl_link_ifmap map; ++ ++ memset(&map, 0, sizeof(map)); ++ map.mem_start = dev->mem_start; ++ map.mem_end = dev->mem_end; ++ map.base_addr = dev->base_addr; ++ map.irq = dev->irq; ++ map.dma = dev->dma; ++ map.port = dev->if_port; ++ + if (nla_put(skb, IFLA_MAP, sizeof(map), &map)) + return -EMSGSIZE; + ",1817,2148,4096 +873,"static void ssh_detect_bugs(Ssh ssh, char *vstring) +{ + char *imp; /* pointer to implementation part */ + imp = vstring; + imp += strcspn(imp, ""-""); + if (*imp) imp++; + imp += strcspn(imp, ""-""); + if (*imp) imp++; + + ssh->remote_bugs = 0; + + /* + * General notes on server version strings: + * - Not all servers reporting ""Cisco-1.25"" have all the bugs listed + * here -- in particular, we've heard of one that's perfectly happy + * with SSH1_MSG_IGNOREs -- but this string never seems to change, + * so we can't distinguish them. + */ + if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON || + (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO && + (!strcmp(imp, ""1.2.18"") || !strcmp(imp, ""1.2.19"") || + !strcmp(imp, ""1.2.20"") || !strcmp(imp, ""1.2.21"") || + !strcmp(imp, ""1.2.22"") || !strcmp(imp, ""Cisco-1.25"") || + !strcmp(imp, ""OSU_1.4alpha3"") || !strcmp(imp, ""OSU_1.5alpha4"")))) { + /* + * These versions don't support SSH1_MSG_IGNORE, so we have + * to use a different defence against password length + * sniffing. + */ + ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE; + logevent(""We believe remote version has SSH-1 ignore bug""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON || + (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO && + (!strcmp(imp, ""Cisco-1.25"") || !strcmp(imp, ""OSU_1.4alpha3"")))) { + /* + * These versions need a plain password sent; they can't + * handle having a null and a random length of data after + * the password. + */ + ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD; + logevent(""We believe remote version needs a plain SSH-1 password""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON || + (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO && + (!strcmp(imp, ""Cisco-1.25"")))) { + /* + * These versions apparently have no clue whatever about + * RSA authentication and will panic and die if they see + * an AUTH_RSA message. + */ + ssh->remote_bugs |= BUG_CHOKES_ON_RSA; + logevent(""We believe remote version can't handle SSH-1 RSA authentication""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON || + (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO && + !wc_match(""* VShell"", imp) && + (wc_match(""2.1.0*"", imp) || wc_match(""2.0.*"", imp) || + wc_match(""2.2.0*"", imp) || wc_match(""2.3.0*"", imp) || + wc_match(""2.1 *"", imp)))) { + /* + * These versions have the HMAC bug. + */ + ssh->remote_bugs |= BUG_SSH2_HMAC; + logevent(""We believe remote version has SSH-2 HMAC bug""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON || + (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO && + !wc_match(""* VShell"", imp) && + (wc_match(""2.0.0*"", imp) || wc_match(""2.0.10*"", imp) ))) { + /* + * These versions have the key-derivation bug (failing to + * include the literal shared secret in the hashes that + * generate the keys). + */ + ssh->remote_bugs |= BUG_SSH2_DERIVEKEY; + logevent(""We believe remote version has SSH-2 key-derivation bug""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON || + (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO && + (wc_match(""OpenSSH_2.[5-9]*"", imp) || + wc_match(""OpenSSH_3.[0-2]*"", imp) || + wc_match(""mod_sftp/0.[0-8]*"", imp) || + wc_match(""mod_sftp/0.9.[0-8]"", imp)))) { + /* + * These versions have the SSH-2 RSA padding bug. + */ + ssh->remote_bugs |= BUG_SSH2_RSA_PADDING; + logevent(""We believe remote version has SSH-2 RSA padding bug""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON || + (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO && + wc_match(""OpenSSH_2.[0-2]*"", imp))) { + /* + * These versions have the SSH-2 session-ID bug in + * public-key authentication. + */ + ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID; + logevent(""We believe remote version has SSH-2 public-key-session-ID bug""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON || + (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO && + (wc_match(""DigiSSH_2.0"", imp) || + wc_match(""OpenSSH_2.[0-4]*"", imp) || + wc_match(""OpenSSH_2.5.[0-3]*"", imp) || + wc_match(""Sun_SSH_1.0"", imp) || + wc_match(""Sun_SSH_1.0.1"", imp) || + /* All versions <= 1.2.6 (they changed their format in 1.2.7) */ + wc_match(""WeOnlyDo-*"", imp)))) { + /* + * These versions have the SSH-2 rekey bug. + */ + ssh->remote_bugs |= BUG_SSH2_REKEY; + logevent(""We believe remote version has SSH-2 rekey bug""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON || + (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO && + (wc_match(""1.36_sshlib GlobalSCAPE"", imp) || + wc_match(""1.36 sshlib: GlobalScape"", imp)))) { + /* + * This version ignores our makpkt and needs to be throttled. + */ + ssh->remote_bugs |= BUG_SSH2_MAXPKT; + logevent(""We believe remote version ignores SSH-2 maximum packet size""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) { + /* + * Servers that don't support SSH2_MSG_IGNORE. Currently, + * none detected automatically. + */ + ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE; + logevent(""We believe remote version has SSH-2 ignore bug""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON || + (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO && + (wc_match(""OpenSSH_2.[235]*"", imp)))) { + /* + * These versions only support the original (pre-RFC4419) + * SSH-2 GEX request, and disconnect with a protocol error if + * we use the newer version. + */ + ssh->remote_bugs |= BUG_SSH2_OLDGEX; + logevent(""We believe remote version has outdated SSH-2 GEX""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) { + /* + * Servers that don't support our winadj request for one + * reason or another. Currently, none detected automatically. + */ + ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ; + logevent(""We believe remote version has winadj bug""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON || + (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO && + (wc_match(""OpenSSH_[2-5].*"", imp) || + wc_match(""OpenSSH_6.[0-6]*"", imp) || + wc_match(""dropbear_0.[2-4][0-9]*"", imp) || + wc_match(""dropbear_0.5[01]*"", imp)))) { + /* + * These versions have the SSH-2 channel request bug. + * OpenSSH 6.7 and above do not: + * https://bugzilla.mindrot.org/show_bug.cgi?id=1818 + * dropbear_0.52 and above do not: + * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c + */ + ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY; + logevent(""We believe remote version has SSH-2 channel request bug""); + } +} +",0,"static void ssh_detect_bugs(Ssh ssh, char *vstring) +{ + char *imp; /* pointer to implementation part */ + imp = vstring; + imp += strcspn(imp, ""-""); + if (*imp) imp++; + imp += strcspn(imp, ""-""); + if (*imp) imp++; + + ssh->remote_bugs = 0; + + /* + * General notes on server version strings: + * - Not all servers reporting ""Cisco-1.25"" have all the bugs listed + * here -- in particular, we've heard of one that's perfectly happy + * with SSH1_MSG_IGNOREs -- but this string never seems to change, + * so we can't distinguish them. + */ + if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON || + (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO && + (!strcmp(imp, ""1.2.18"") || !strcmp(imp, ""1.2.19"") || + !strcmp(imp, ""1.2.20"") || !strcmp(imp, ""1.2.21"") || + !strcmp(imp, ""1.2.22"") || !strcmp(imp, ""Cisco-1.25"") || + !strcmp(imp, ""OSU_1.4alpha3"") || !strcmp(imp, ""OSU_1.5alpha4"")))) { + /* + * These versions don't support SSH1_MSG_IGNORE, so we have + * to use a different defence against password length + * sniffing. + */ + ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE; + logevent(""We believe remote version has SSH-1 ignore bug""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON || + (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO && + (!strcmp(imp, ""Cisco-1.25"") || !strcmp(imp, ""OSU_1.4alpha3"")))) { + /* + * These versions need a plain password sent; they can't + * handle having a null and a random length of data after + * the password. + */ + ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD; + logevent(""We believe remote version needs a plain SSH-1 password""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON || + (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO && + (!strcmp(imp, ""Cisco-1.25"")))) { + /* + * These versions apparently have no clue whatever about + * RSA authentication and will panic and die if they see + * an AUTH_RSA message. + */ + ssh->remote_bugs |= BUG_CHOKES_ON_RSA; + logevent(""We believe remote version can't handle SSH-1 RSA authentication""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON || + (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO && + !wc_match(""* VShell"", imp) && + (wc_match(""2.1.0*"", imp) || wc_match(""2.0.*"", imp) || + wc_match(""2.2.0*"", imp) || wc_match(""2.3.0*"", imp) || + wc_match(""2.1 *"", imp)))) { + /* + * These versions have the HMAC bug. + */ + ssh->remote_bugs |= BUG_SSH2_HMAC; + logevent(""We believe remote version has SSH-2 HMAC bug""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON || + (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO && + !wc_match(""* VShell"", imp) && + (wc_match(""2.0.0*"", imp) || wc_match(""2.0.10*"", imp) ))) { + /* + * These versions have the key-derivation bug (failing to + * include the literal shared secret in the hashes that + * generate the keys). + */ + ssh->remote_bugs |= BUG_SSH2_DERIVEKEY; + logevent(""We believe remote version has SSH-2 key-derivation bug""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON || + (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO && + (wc_match(""OpenSSH_2.[5-9]*"", imp) || + wc_match(""OpenSSH_3.[0-2]*"", imp) || + wc_match(""mod_sftp/0.[0-8]*"", imp) || + wc_match(""mod_sftp/0.9.[0-8]"", imp)))) { + /* + * These versions have the SSH-2 RSA padding bug. + */ + ssh->remote_bugs |= BUG_SSH2_RSA_PADDING; + logevent(""We believe remote version has SSH-2 RSA padding bug""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON || + (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO && + wc_match(""OpenSSH_2.[0-2]*"", imp))) { + /* + * These versions have the SSH-2 session-ID bug in + * public-key authentication. + */ + ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID; + logevent(""We believe remote version has SSH-2 public-key-session-ID bug""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON || + (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO && + (wc_match(""DigiSSH_2.0"", imp) || + wc_match(""OpenSSH_2.[0-4]*"", imp) || + wc_match(""OpenSSH_2.5.[0-3]*"", imp) || + wc_match(""Sun_SSH_1.0"", imp) || + wc_match(""Sun_SSH_1.0.1"", imp) || + /* All versions <= 1.2.6 (they changed their format in 1.2.7) */ + wc_match(""WeOnlyDo-*"", imp)))) { + /* + * These versions have the SSH-2 rekey bug. + */ + ssh->remote_bugs |= BUG_SSH2_REKEY; + logevent(""We believe remote version has SSH-2 rekey bug""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON || + (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO && + (wc_match(""1.36_sshlib GlobalSCAPE"", imp) || + wc_match(""1.36 sshlib: GlobalScape"", imp)))) { + /* + * This version ignores our makpkt and needs to be throttled. + */ + ssh->remote_bugs |= BUG_SSH2_MAXPKT; + logevent(""We believe remote version ignores SSH-2 maximum packet size""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) { + /* + * Servers that don't support SSH2_MSG_IGNORE. Currently, + * none detected automatically. + */ + ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE; + logevent(""We believe remote version has SSH-2 ignore bug""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON || + (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO && + (wc_match(""OpenSSH_2.[235]*"", imp)))) { + /* + * These versions only support the original (pre-RFC4419) + * SSH-2 GEX request, and disconnect with a protocol error if + * we use the newer version. + */ + ssh->remote_bugs |= BUG_SSH2_OLDGEX; + logevent(""We believe remote version has outdated SSH-2 GEX""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) { + /* + * Servers that don't support our winadj request for one + * reason or another. Currently, none detected automatically. + */ + ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ; + logevent(""We believe remote version has winadj bug""); + } + + if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON || + (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO && + (wc_match(""OpenSSH_[2-5].*"", imp) || + wc_match(""OpenSSH_6.[0-6]*"", imp) || + wc_match(""dropbear_0.[2-4][0-9]*"", imp) || + wc_match(""dropbear_0.5[01]*"", imp)))) { + /* + * These versions have the SSH-2 channel request bug. + * OpenSSH 6.7 and above do not: + * https://bugzilla.mindrot.org/show_bug.cgi?id=1818 + * dropbear_0.52 and above do not: + * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c + */ + ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY; + logevent(""We believe remote version has SSH-2 channel request bug""); + } +} +","@@ -573,10 +573,7 @@ struct ssh_channel { + } v; + union { + struct ssh_agent_channel { +- unsigned char *message; +- unsigned char msglen[4]; +- unsigned lensofar, totallen; +- int outstanding_requests; ++ bufchain inbuffer; + agent_pending_query *pending; + } a; + struct ssh_x11_channel { +@@ -3780,6 +3777,8 @@ static void ssh_throttle_conn(Ssh ssh, int adjust) + } + } + ++static void ssh_agentf_try_forward(struct ssh_channel *c); ++ + /* + * Throttle or unthrottle _all_ local data streams (for when sends + * on the SSH connection itself back up). +@@ -3806,7 +3805,12 @@ static void ssh_throttle_all(Ssh ssh, int enable, int bufsize) + x11_override_throttle(c->u.x11.xconn, enable); + break; + case CHAN_AGENT: +- /* Agent channels require no buffer management. */ ++ /* Agent forwarding channels are buffer-managed by ++ * checking ssh->throttled_all in ssh_agentf_try_forward. ++ * So at the moment we _un_throttle again, we must make an ++ * attempt to do something. */ ++ if (!enable) ++ ssh_agentf_try_forward(c); + break; + case CHAN_SOCKDATA: + pfd_override_throttle(c->u.pfd.pf, enable); +@@ -3848,29 +3852,113 @@ static void ssh_dialog_callback(void *sshv, int ret) + ssh_process_queued_incoming_data(ssh); + } + +-static void ssh_agentf_callback(void *cv, void *reply, int replylen) ++static void ssh_agentf_got_response(struct ssh_channel *c, ++ void *reply, int replylen) + { +- struct ssh_channel *c = (struct ssh_channel *)cv; +- const void *sentreply = reply; +- + c->u.a.pending = NULL; +- c->u.a.outstanding_requests--; +- if (!sentreply) { +- /* Fake SSH_AGENT_FAILURE. */ +- sentreply = ""\0\0\0\1\5""; ++ ++ if (!reply) { ++ /* The real agent didn't send any kind of reply at all for ++ * some reason, so fake an SSH_AGENT_FAILURE. */ ++ reply = ""\0\0\0\1\5""; + replylen = 5; + } +- ssh_send_channel_data(c, sentreply, replylen); +- if (reply) +- sfree(reply); ++ ++ ssh_send_channel_data(c, reply, replylen); ++} ++ ++static void ssh_agentf_callback(void *cv, void *reply, int replylen); ++ ++static void ssh_agentf_try_forward(struct ssh_channel *c) ++{ ++ unsigned datalen, lengthfield, messagelen; ++ unsigned char *message; ++ unsigned char msglen[4]; ++ void *reply; ++ int replylen; ++ + /* +- * If we've already seen an incoming EOF but haven't sent an +- * outgoing one, this may be the moment to send it. ++ * Don't try to parallelise agent requests. Wait for each one to ++ * return before attempting the next. + */ +- if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF)) ++ if (c->u.a.pending) ++ return; ++ ++ /* ++ * If the outgoing side of the channel connection is currently ++ * throttled (for any reason, either that channel's window size or ++ * the entire SSH connection being throttled), don't submit any ++ * new forwarded requests to the real agent. This causes the input ++ * side of the agent forwarding not to be emptied, exerting the ++ * required back-pressure on the remote client, and encouraging it ++ * to read our responses before sending too many more requests. ++ */ ++ if (c->ssh->throttled_all || ++ (c->ssh->version == 2 && c->v.v2.remwindow == 0)) ++ return; ++ ++ while (1) { ++ /* ++ * Try to extract a complete message from the input buffer. ++ */ ++ datalen = bufchain_size(&c->u.a.inbuffer); ++ if (datalen < 4) ++ break; /* not even a length field available yet */ ++ ++ bufchain_fetch(&c->u.a.inbuffer, msglen, 4); ++ lengthfield = GET_32BIT(msglen); ++ if (lengthfield > datalen - 4) ++ break; /* a whole message is not yet available */ ++ ++ messagelen = lengthfield + 4; ++ ++ message = snewn(messagelen, unsigned char); ++ bufchain_fetch(&c->u.a.inbuffer, message, messagelen); ++ bufchain_consume(&c->u.a.inbuffer, messagelen); ++ c->u.a.pending = agent_query( ++ message, messagelen, &reply, &replylen, ssh_agentf_callback, c); ++ sfree(message); ++ ++ if (c->u.a.pending) ++ return; /* agent_query promised to reply in due course */ ++ ++ /* ++ * If the agent gave us an answer immediately, pass it ++ * straight on and go round this loop again. ++ */ ++ ssh_agentf_got_response(c, reply, replylen); ++ } ++ ++ /* ++ * If we get here (i.e. we left the above while loop via 'break' ++ * rather than 'return'), that means we've determined that the ++ * input buffer for the agent forwarding connection doesn't ++ * contain a complete request. ++ * ++ * So if there's potentially more data to come, we can return now, ++ * and wait for the remote client to send it. But if the remote ++ * has sent EOF, it would be a mistake to do that, because we'd be ++ * waiting a long time. So this is the moment to check for EOF, ++ * and respond appropriately. ++ */ ++ if (c->closes & CLOSES_RCVD_EOF) + sshfwd_write_eof(c); + } + ++static void ssh_agentf_callback(void *cv, void *reply, int replylen) ++{ ++ struct ssh_channel *c = (struct ssh_channel *)cv; ++ ++ ssh_agentf_got_response(c, reply, replylen); ++ sfree(reply); ++ ++ /* ++ * Now try to extract and send further messages from the channel's ++ * input-side buffer. ++ */ ++ ssh_agentf_try_forward(c); ++} ++ + /* + * Client-initiated disconnection. Send a DISCONNECT if `wire_reason' + * non-NULL, otherwise just close the connection. `client_reason' == NULL +@@ -5553,10 +5641,8 @@ static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin) + c->remoteid = remoteid; + c->halfopen = FALSE; + c->type = CHAN_AGENT; /* identify channel type */ +- c->u.a.lensofar = 0; +- c->u.a.message = NULL; + c->u.a.pending = NULL; +- c->u.a.outstanding_requests = 0; ++ bufchain_init(&c->u.a.inbuffer); + send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION, + PKT_INT, c->remoteid, PKT_INT, c->localid, + PKT_END); +@@ -5697,42 +5783,18 @@ static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin) + static int ssh_agent_channel_data(struct ssh_channel *c, char *data, + int length) + { +- while (length > 0) { +- if (c->u.a.lensofar < 4) { +- unsigned int l = min(4 - c->u.a.lensofar, (unsigned)length); +- memcpy(c->u.a.msglen + c->u.a.lensofar, data, l); +- data += l; +- length -= l; +- c->u.a.lensofar += l; +- } +- if (c->u.a.lensofar == 4) { +- c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen); +- c->u.a.message = snewn(c->u.a.totallen, unsigned char); +- memcpy(c->u.a.message, c->u.a.msglen, 4); +- } +- if (c->u.a.lensofar >= 4 && length > 0) { +- unsigned int l = min(c->u.a.totallen - c->u.a.lensofar, +- (unsigned)length); +- memcpy(c->u.a.message + c->u.a.lensofar, data, l); +- data += l; +- length -= l; +- c->u.a.lensofar += l; +- } +- if (c->u.a.lensofar == c->u.a.totallen) { +- void *reply; +- int replylen; +- c->u.a.outstanding_requests++; +- c->u.a.pending = agent_query( +- c->u.a.message, c->u.a.totallen, &reply, &replylen, +- ssh_agentf_callback, c); +- if (!c->u.a.pending) +- ssh_agentf_callback(c, reply, replylen); +- sfree(c->u.a.message); +- c->u.a.message = NULL; +- c->u.a.lensofar = 0; +- } +- } +- return 0; /* agent channels never back up */ ++ bufchain_add(&c->u.a.inbuffer, data, length); ++ ssh_agentf_try_forward(c); ++ ++ /* ++ * We exert back-pressure on an agent forwarding client if and ++ * only if we're waiting for the response to an asynchronous agent ++ * request. This prevents the client running out of window while ++ * receiving the _first_ message, but means that if any message ++ * takes time to process, the client will be discouraged from ++ * sending an endless stream of further ones after it. ++ */ ++ return (c->u.a.pending ? bufchain_size(&c->u.a.inbuffer) : 0); + } + + static int ssh_channel_data(struct ssh_channel *c, int is_stderr, +@@ -7733,8 +7795,9 @@ static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c) + x11_unthrottle(c->u.x11.xconn); + break; + case CHAN_AGENT: +- /* agent sockets are request/response and need no +- * buffer management */ ++ /* Now that we've successfully sent all the outgoing ++ * replies we had, try to process more incoming data. */ ++ ssh_agentf_try_forward(c); + break; + case CHAN_SOCKDATA: + pfd_unthrottle(c->u.pfd.pf); +@@ -8160,7 +8223,8 @@ static void ssh_channel_close_local(struct ssh_channel *c, char const *reason) + case CHAN_AGENT: + if (c->u.a.pending) + agent_cancel_query(c->u.a.pending); +- sfree(c->u.a.message); ++ bufchain_clear(&c->u.a.inbuffer); ++ msg = ""Agent-forwarding connection closed""; + break; + case CHAN_SOCKDATA: + assert(c->u.pfd.pf != NULL); +@@ -8248,10 +8312,10 @@ static void ssh_channel_got_eof(struct ssh_channel *c) + assert(c->u.x11.xconn != NULL); + x11_send_eof(c->u.x11.xconn); + } else if (c->type == CHAN_AGENT) { +- if (c->u.a.outstanding_requests == 0) { +- /* Manufacture an outgoing EOF in response to the incoming one. */ +- sshfwd_write_eof(c); +- } ++ /* Just call try_forward, which will respond to the EOF now if ++ * appropriate, or wait until the queue of outstanding ++ * requests is dealt with if not */ ++ ssh_agentf_try_forward(c); + } else if (c->type == CHAN_SOCKDATA) { + assert(c->u.pfd.pf != NULL); + pfd_send_eof(c->u.pfd.pf); +@@ -8805,10 +8869,8 @@ static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin) + error = ""Agent forwarding is not enabled""; + else { + c->type = CHAN_AGENT; /* identify channel type */ +- c->u.a.lensofar = 0; +- c->u.a.message = NULL; ++ bufchain_init(&c->u.a.inbuffer); + c->u.a.pending = NULL; +- c->u.a.outstanding_requests = 0; + } + } else { + error = ""Unsupported channel type requested"";",2156,2487,4096 +430,"void DCTStream::transformDataUnit(Gushort *quantTable, + int dataIn[64], Guchar dataOut[64]) { + int v0, v1, v2, v3, v4, v5, v6, v7, t; + int *p; + int i; + + for (i = 0; i < 64; ++i) { + dataIn[i] *= quantTable[i]; + } + + for (i = 0; i < 64; i += 8) { + p = dataIn + i; + + if (p[1] == 0 && p[2] == 0 && p[3] == 0 && + p[4] == 0 && p[5] == 0 && p[6] == 0 && p[7] == 0) { + t = (dctSqrt2 * p[0] + 512) >> 10; + p[0] = t; + p[1] = t; + p[2] = t; + p[3] = t; + p[4] = t; + p[5] = t; + p[6] = t; + p[7] = t; + continue; + } + + v0 = (dctSqrt2 * p[0] + 128) >> 8; + v1 = (dctSqrt2 * p[4] + 128) >> 8; + v2 = p[2]; + v3 = p[6]; + v4 = (dctSqrt1d2 * (p[1] - p[7]) + 128) >> 8; + v7 = (dctSqrt1d2 * (p[1] + p[7]) + 128) >> 8; + v5 = p[3] << 4; + v6 = p[5] << 4; + + t = (v0 - v1+ 1) >> 1; + v0 = (v0 + v1 + 1) >> 1; + v1 = t; + t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8; + v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8; + v3 = t; + t = (v4 - v6 + 1) >> 1; + v4 = (v4 + v6 + 1) >> 1; + v6 = t; + t = (v7 + v5 + 1) >> 1; + v5 = (v7 - v5 + 1) >> 1; + v7 = t; + + t = (v0 - v3 + 1) >> 1; + v0 = (v0 + v3 + 1) >> 1; + v3 = t; + t = (v1 - v2 + 1) >> 1; + v1 = (v1 + v2 + 1) >> 1; + v2 = t; + t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12; + v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12; + v7 = t; + t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12; + v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12; + v6 = t; + + p[0] = v0 + v7; + p[7] = v0 - v7; + p[1] = v1 + v6; + p[6] = v1 - v6; + p[2] = v2 + v5; + p[5] = v2 - v5; + p[3] = v3 + v4; + p[4] = v3 - v4; + } + + for (i = 0; i < 8; ++i) { + p = dataIn + i; + + if (p[1*8] == 0 && p[2*8] == 0 && p[3*8] == 0 && + p[4*8] == 0 && p[5*8] == 0 && p[6*8] == 0 && p[7*8] == 0) { + t = (dctSqrt2 * dataIn[i+0] + 8192) >> 14; + p[0*8] = t; + p[1*8] = t; + p[2*8] = t; + p[3*8] = t; + p[4*8] = t; + p[5*8] = t; + p[6*8] = t; + p[7*8] = t; + continue; + } + + v0 = (dctSqrt2 * p[0*8] + 2048) >> 12; + v1 = (dctSqrt2 * p[4*8] + 2048) >> 12; + v2 = p[2*8]; + v3 = p[6*8]; + v4 = (dctSqrt1d2 * (p[1*8] - p[7*8]) + 2048) >> 12; + v7 = (dctSqrt1d2 * (p[1*8] + p[7*8]) + 2048) >> 12; + v5 = p[3*8]; + v6 = p[5*8]; + + t = (v0 - v1 + 1) >> 1; + v0 = (v0 + v1 + 1) >> 1; + v1 = t; + t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12; + v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12; + v3 = t; + t = (v4 - v6 + 1) >> 1; + v4 = (v4 + v6 + 1) >> 1; + v6 = t; + t = (v7 + v5 + 1) >> 1; + v5 = (v7 - v5 + 1) >> 1; + v7 = t; + + t = (v0 - v3 + 1) >> 1; + v0 = (v0 + v3 + 1) >> 1; + v3 = t; + t = (v1 - v2 + 1) >> 1; + v1 = (v1 + v2 + 1) >> 1; + v2 = t; + t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12; + v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12; + v7 = t; + t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12; + v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12; + v6 = t; + + p[0*8] = v0 + v7; + p[7*8] = v0 - v7; + p[1*8] = v1 + v6; + p[6*8] = v1 - v6; + p[2*8] = v2 + v5; + p[5*8] = v2 - v5; + p[3*8] = v3 + v4; + p[4*8] = v3 - v4; + } + + for (i = 0; i < 64; ++i) { + dataOut[i] = dctClip[dctClipOffset + 128 + ((dataIn[i] + 8) >> 4)]; + } +} +",0,"void DCTStream::transformDataUnit(Gushort *quantTable, + int dataIn[64], Guchar dataOut[64]) { + int v0, v1, v2, v3, v4, v5, v6, v7, t; + int *p; + int i; + + for (i = 0; i < 64; ++i) { + dataIn[i] *= quantTable[i]; + } + + for (i = 0; i < 64; i += 8) { + p = dataIn + i; + + if (p[1] == 0 && p[2] == 0 && p[3] == 0 && + p[4] == 0 && p[5] == 0 && p[6] == 0 && p[7] == 0) { + t = (dctSqrt2 * p[0] + 512) >> 10; + p[0] = t; + p[1] = t; + p[2] = t; + p[3] = t; + p[4] = t; + p[5] = t; + p[6] = t; + p[7] = t; + continue; + } + + v0 = (dctSqrt2 * p[0] + 128) >> 8; + v1 = (dctSqrt2 * p[4] + 128) >> 8; + v2 = p[2]; + v3 = p[6]; + v4 = (dctSqrt1d2 * (p[1] - p[7]) + 128) >> 8; + v7 = (dctSqrt1d2 * (p[1] + p[7]) + 128) >> 8; + v5 = p[3] << 4; + v6 = p[5] << 4; + + t = (v0 - v1+ 1) >> 1; + v0 = (v0 + v1 + 1) >> 1; + v1 = t; + t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8; + v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8; + v3 = t; + t = (v4 - v6 + 1) >> 1; + v4 = (v4 + v6 + 1) >> 1; + v6 = t; + t = (v7 + v5 + 1) >> 1; + v5 = (v7 - v5 + 1) >> 1; + v7 = t; + + t = (v0 - v3 + 1) >> 1; + v0 = (v0 + v3 + 1) >> 1; + v3 = t; + t = (v1 - v2 + 1) >> 1; + v1 = (v1 + v2 + 1) >> 1; + v2 = t; + t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12; + v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12; + v7 = t; + t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12; + v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12; + v6 = t; + + p[0] = v0 + v7; + p[7] = v0 - v7; + p[1] = v1 + v6; + p[6] = v1 - v6; + p[2] = v2 + v5; + p[5] = v2 - v5; + p[3] = v3 + v4; + p[4] = v3 - v4; + } + + for (i = 0; i < 8; ++i) { + p = dataIn + i; + + if (p[1*8] == 0 && p[2*8] == 0 && p[3*8] == 0 && + p[4*8] == 0 && p[5*8] == 0 && p[6*8] == 0 && p[7*8] == 0) { + t = (dctSqrt2 * dataIn[i+0] + 8192) >> 14; + p[0*8] = t; + p[1*8] = t; + p[2*8] = t; + p[3*8] = t; + p[4*8] = t; + p[5*8] = t; + p[6*8] = t; + p[7*8] = t; + continue; + } + + v0 = (dctSqrt2 * p[0*8] + 2048) >> 12; + v1 = (dctSqrt2 * p[4*8] + 2048) >> 12; + v2 = p[2*8]; + v3 = p[6*8]; + v4 = (dctSqrt1d2 * (p[1*8] - p[7*8]) + 2048) >> 12; + v7 = (dctSqrt1d2 * (p[1*8] + p[7*8]) + 2048) >> 12; + v5 = p[3*8]; + v6 = p[5*8]; + + t = (v0 - v1 + 1) >> 1; + v0 = (v0 + v1 + 1) >> 1; + v1 = t; + t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12; + v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12; + v3 = t; + t = (v4 - v6 + 1) >> 1; + v4 = (v4 + v6 + 1) >> 1; + v6 = t; + t = (v7 + v5 + 1) >> 1; + v5 = (v7 - v5 + 1) >> 1; + v7 = t; + + t = (v0 - v3 + 1) >> 1; + v0 = (v0 + v3 + 1) >> 1; + v3 = t; + t = (v1 - v2 + 1) >> 1; + v1 = (v1 + v2 + 1) >> 1; + v2 = t; + t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12; + v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12; + v7 = t; + t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12; + v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12; + v6 = t; + + p[0*8] = v0 + v7; + p[7*8] = v0 - v7; + p[1*8] = v1 + v6; + p[6*8] = v1 - v6; + p[2*8] = v2 + v5; + p[5*8] = v2 - v5; + p[3*8] = v3 + v4; + p[4*8] = v3 - v4; + } + + for (i = 0; i < 64; ++i) { + dataOut[i] = dctClip[dctClipOffset + 128 + ((dataIn[i] + 8) >> 4)]; + } +} +","@@ -14,7 +14,7 @@ + // under GPL version 2 or later + // + // Copyright (C) 2005 Jeff Muizelaar +-// Copyright (C) 2006-2010, 2012 Albert Astals Cid ++// Copyright (C) 2006-2010, 2012, 2013 Albert Astals Cid + // Copyright (C) 2007 Krzysztof Kowalczyk + // Copyright (C) 2008 Julien Rebetez + // Copyright (C) 2009 Carlos Garcia Campos +@@ -1712,8 +1712,9 @@ int CCITTFaxStream::lookChar() { + for (i = 0; i < columns && codingLine[i] < columns; ++i) { + refLine[i] = codingLine[i]; + } +- refLine[i++] = columns; +- refLine[i] = columns; ++ for (; i < columns + 2; ++i) { ++ refLine[i] = columns; ++ } + codingLine[0] = 0; + a0i = 0; + b1i = 0;",1885,2216,4096 +18792,"WORD32 ih264d_cavlc_4x4res_block_totalcoeff_11to16(UWORD32 u4_isdc, + UWORD32 u4_total_coeff_trail_one, /*!pu4_buffer; + + UWORD32 u4_bitstream_offset = ps_bitstrm->u4_ofst; + UWORD32 u4_trailing_ones = u4_total_coeff_trail_one & 0xFFFF; + UWORD32 u4_total_coeff = u4_total_coeff_trail_one >> 16; + WORD16 i2_level_arr[16]; + + tu_sblk4x4_coeff_data_t *ps_tu_4x4; + WORD16 *pi2_coeff_data; + dec_struct_t *ps_dec = (dec_struct_t *)ps_bitstrm->pv_codec_handle; + + ps_tu_4x4 = (tu_sblk4x4_coeff_data_t *)ps_dec->pv_parse_tu_coeff_data; + ps_tu_4x4->u2_sig_coeff_map = 0; + pi2_coeff_data = &ps_tu_4x4->ai2_level[0]; + + i = u4_total_coeff - 1; + if(u4_trailing_ones) + { + /*********************************************************************/ + /* Decode Trailing Ones */ + /* read the sign of T1's and put them in level array */ + /*********************************************************************/ + UWORD32 u4_signs, u4_cnt = u4_trailing_ones; + WORD16 (*ppi2_trlone_lkup)[3] = + (WORD16 (*)[3])gai2_ih264d_trailing_one_level; + WORD16 *pi2_trlone_lkup; + + GETBITS(u4_signs, u4_bitstream_offset, pu4_bitstrm_buf, u4_cnt); + + pi2_trlone_lkup = ppi2_trlone_lkup[(1 << u4_cnt) - 2 + u4_signs]; + + while(u4_cnt--) + i2_level_arr[i--] = *pi2_trlone_lkup++; + } + + /****************************************************************/ + /* Decoding Levels Begins */ + /****************************************************************/ + if(i >= 0) + { + /****************************************************************/ + /* First level is decoded outside the loop as it has lot of */ + /* special cases. */ + /****************************************************************/ + UWORD32 u4_lev_suffix, u4_suffix_len, u4_lev_suffix_size; + UWORD16 u2_lev_code, u2_abs_value; + UWORD32 u4_lev_prefix; + + if(u4_trailing_ones < 3) + { + /*********************************************************/ + /* u4_suffix_len = 1 */ + /*********************************************************/ + /***************************************************************/ + /* Find leading zeros in next 32 bits */ + /***************************************************************/ + FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset, + pu4_bitstrm_buf); + + u4_lev_suffix_size = + (15 <= u4_lev_prefix) ? (u4_lev_prefix - 3) : 1; + + GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf, + u4_lev_suffix_size); + u2_lev_code = 2 + (MIN(u4_lev_prefix,15) << 1) + u4_lev_suffix; + + if(16 <= u4_lev_prefix) + { + u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096); + } + } + else + { + /*********************************************************/ + /*u4_suffix_len = 0 */ + /*********************************************************/ + /***************************************************************/ + /* Find leading zeros in next 32 bits */ + /***************************************************************/ + FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset, + pu4_bitstrm_buf); + + /*********************************************************/ + /* Special decoding case when trailing ones are 3 */ + /*********************************************************/ + u2_lev_code = MIN(15, u4_lev_prefix); + + u2_lev_code += (3 == u4_trailing_ones) ? 0 : (2); + + if(14 == u4_lev_prefix) + u4_lev_suffix_size = 4; + else if(15 <= u4_lev_prefix) + { + u2_lev_code += 15; + u4_lev_suffix_size = (u4_lev_prefix - 3); + } + else + u4_lev_suffix_size = 0; + + if(16 <= u4_lev_prefix) + { + u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096); + } + if(u4_lev_suffix_size) + { + GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf, + u4_lev_suffix_size); + u2_lev_code += u4_lev_suffix; + } + } + + u2_abs_value = (u2_lev_code + 2) >> 1; + /*********************************************************/ + /* If Level code is odd, level is negative else positive */ + /*********************************************************/ + i2_level_arr[i--] = (u2_lev_code & 1) ? -u2_abs_value : u2_abs_value; + + u4_suffix_len = (u2_abs_value > 3) ? 2 : 1; + + /*********************************************************/ + /* Now loop over the remaining levels */ + /*********************************************************/ + while(i >= 0) + { + + /***************************************************************/ + /* Find leading zeros in next 32 bits */ + /***************************************************************/ + FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset, + pu4_bitstrm_buf); + + u4_lev_suffix_size = + (15 <= u4_lev_prefix) ? + (u4_lev_prefix - 3) : u4_suffix_len; + + /*********************************************************/ + /* Compute level code using prefix and suffix */ + /*********************************************************/ + GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf, + u4_lev_suffix_size); + u2_lev_code = (MIN(15,u4_lev_prefix) << u4_suffix_len) + + u4_lev_suffix; + + if(16 <= u4_lev_prefix) + { + u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096); + } + u2_abs_value = (u2_lev_code + 2) >> 1; + + /*********************************************************/ + /* If Level code is odd, level is negative else positive */ + /*********************************************************/ + i2_level_arr[i--] = + (u2_lev_code & 1) ? -u2_abs_value : u2_abs_value; + + /*********************************************************/ + /* Increment suffix length if required */ + /*********************************************************/ + u4_suffix_len += + (u4_suffix_len < 6) ? + (u2_abs_value + > (3 + << (u4_suffix_len + - 1))) : + 0; + } + + /****************************************************************/ + /* Decoding Levels Ends */ + /****************************************************************/ + } + + if(u4_total_coeff < (16 - u4_isdc)) + { + UWORD32 u4_index; + const UWORD8 (*ppu1_total_zero_lkup)[16] = + (const UWORD8 (*)[16])gau1_ih264d_table_total_zero_11to15; + + NEXTBITS(u4_index, u4_bitstream_offset, pu4_bitstrm_buf, 4); + u4_total_zeroes = ppu1_total_zero_lkup[u4_total_coeff - 11][u4_index]; + + FLUSHBITS(u4_bitstream_offset, (u4_total_zeroes >> 4)); + u4_total_zeroes &= 0xf; + } + else + u4_total_zeroes = 0; + + /**************************************************************/ + /* Decode the runs and form the coefficient buffer */ + /**************************************************************/ + { + const UWORD8 *pu1_table_runbefore; + UWORD32 u4_run; + WORD32 k; + UWORD32 u4_scan_pos = u4_total_coeff + u4_total_zeroes - 1 + u4_isdc; + WORD32 u4_zeroes_left = u4_total_zeroes; + k = u4_total_coeff - 1; + + /**************************************************************/ + /* Decoding Runs for 0 < zeros left <=6 */ + /**************************************************************/ + pu1_table_runbefore = (UWORD8 *)gau1_ih264d_table_run_before; + while((u4_zeroes_left > 0) && k) + { + UWORD32 u4_code; + NEXTBITS(u4_code, u4_bitstream_offset, pu4_bitstrm_buf, 3); + + u4_code = pu1_table_runbefore[u4_code + (u4_zeroes_left << 3)]; + u4_run = u4_code >> 2; + + FLUSHBITS(u4_bitstream_offset, (u4_code & 0x03)); + SET_BIT(ps_tu_4x4->u2_sig_coeff_map, u4_scan_pos); + *pi2_coeff_data++ = i2_level_arr[k--]; + u4_zeroes_left -= u4_run; + u4_scan_pos -= (u4_run + 1); + } + /**************************************************************/ + /* Decoding Runs End */ + /**************************************************************/ + + /**************************************************************/ + /* Copy the remaining coefficients */ + /**************************************************************/ + if(u4_zeroes_left < 0) + return -1; + while(k >= 0) + { + SET_BIT(ps_tu_4x4->u2_sig_coeff_map, u4_scan_pos); + *pi2_coeff_data++ = i2_level_arr[k--]; + u4_scan_pos--; + } + } + + { + WORD32 offset; + offset = (UWORD8 *)pi2_coeff_data - (UWORD8 *)ps_tu_4x4; + offset = ALIGN4(offset); + ps_dec->pv_parse_tu_coeff_data = (void *)((UWORD8 *)ps_dec->pv_parse_tu_coeff_data + offset); + } + + ps_bitstrm->u4_ofst = u4_bitstream_offset; + return 0; +} +",1,"WORD32 ih264d_cavlc_4x4res_block_totalcoeff_11to16(UWORD32 u4_isdc, + UWORD32 u4_total_coeff_trail_one, /*!pu4_buffer; + + UWORD32 u4_bitstream_offset = ps_bitstrm->u4_ofst; + UWORD32 u4_trailing_ones = u4_total_coeff_trail_one & 0xFFFF; + UWORD32 u4_total_coeff = u4_total_coeff_trail_one >> 16; + // To avoid error check at 4x4 level, allocating for 3 extra levels(16+3) + // since u4_trailing_ones can at the max be 3. This will be required when + // u4_total_coeff is less than u4_trailing_ones + WORD16 ai2_level_arr[19];// + WORD16 *i2_level_arr = &ai2_level_arr[3]; + + tu_sblk4x4_coeff_data_t *ps_tu_4x4; + WORD16 *pi2_coeff_data; + dec_struct_t *ps_dec = (dec_struct_t *)ps_bitstrm->pv_codec_handle; + + ps_tu_4x4 = (tu_sblk4x4_coeff_data_t *)ps_dec->pv_parse_tu_coeff_data; + ps_tu_4x4->u2_sig_coeff_map = 0; + pi2_coeff_data = &ps_tu_4x4->ai2_level[0]; + + i = u4_total_coeff - 1; + if(u4_trailing_ones) + { + /*********************************************************************/ + /* Decode Trailing Ones */ + /* read the sign of T1's and put them in level array */ + /*********************************************************************/ + UWORD32 u4_signs, u4_cnt = u4_trailing_ones; + WORD16 (*ppi2_trlone_lkup)[3] = + (WORD16 (*)[3])gai2_ih264d_trailing_one_level; + WORD16 *pi2_trlone_lkup; + + GETBITS(u4_signs, u4_bitstream_offset, pu4_bitstrm_buf, u4_cnt); + + pi2_trlone_lkup = ppi2_trlone_lkup[(1 << u4_cnt) - 2 + u4_signs]; + + while(u4_cnt--) + i2_level_arr[i--] = *pi2_trlone_lkup++; + } + + /****************************************************************/ + /* Decoding Levels Begins */ + /****************************************************************/ + if(i >= 0) + { + /****************************************************************/ + /* First level is decoded outside the loop as it has lot of */ + /* special cases. */ + /****************************************************************/ + UWORD32 u4_lev_suffix, u4_suffix_len, u4_lev_suffix_size; + UWORD16 u2_lev_code, u2_abs_value; + UWORD32 u4_lev_prefix; + + if(u4_trailing_ones < 3) + { + /*********************************************************/ + /* u4_suffix_len = 1 */ + /*********************************************************/ + /***************************************************************/ + /* Find leading zeros in next 32 bits */ + /***************************************************************/ + FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset, + pu4_bitstrm_buf); + + u4_lev_suffix_size = + (15 <= u4_lev_prefix) ? (u4_lev_prefix - 3) : 1; + + GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf, + u4_lev_suffix_size); + u2_lev_code = 2 + (MIN(u4_lev_prefix,15) << 1) + u4_lev_suffix; + + if(16 <= u4_lev_prefix) + { + u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096); + } + } + else + { + /*********************************************************/ + /*u4_suffix_len = 0 */ + /*********************************************************/ + /***************************************************************/ + /* Find leading zeros in next 32 bits */ + /***************************************************************/ + FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset, + pu4_bitstrm_buf); + + /*********************************************************/ + /* Special decoding case when trailing ones are 3 */ + /*********************************************************/ + u2_lev_code = MIN(15, u4_lev_prefix); + + u2_lev_code += (3 == u4_trailing_ones) ? 0 : (2); + + if(14 == u4_lev_prefix) + u4_lev_suffix_size = 4; + else if(15 <= u4_lev_prefix) + { + u2_lev_code += 15; + u4_lev_suffix_size = (u4_lev_prefix - 3); + } + else + u4_lev_suffix_size = 0; + + if(16 <= u4_lev_prefix) + { + u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096); + } + if(u4_lev_suffix_size) + { + GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf, + u4_lev_suffix_size); + u2_lev_code += u4_lev_suffix; + } + } + + u2_abs_value = (u2_lev_code + 2) >> 1; + /*********************************************************/ + /* If Level code is odd, level is negative else positive */ + /*********************************************************/ + i2_level_arr[i--] = (u2_lev_code & 1) ? -u2_abs_value : u2_abs_value; + + u4_suffix_len = (u2_abs_value > 3) ? 2 : 1; + + /*********************************************************/ + /* Now loop over the remaining levels */ + /*********************************************************/ + while(i >= 0) + { + + /***************************************************************/ + /* Find leading zeros in next 32 bits */ + /***************************************************************/ + FIND_ONE_IN_STREAM_32(u4_lev_prefix, u4_bitstream_offset, + pu4_bitstrm_buf); + + u4_lev_suffix_size = + (15 <= u4_lev_prefix) ? + (u4_lev_prefix - 3) : u4_suffix_len; + + /*********************************************************/ + /* Compute level code using prefix and suffix */ + /*********************************************************/ + GETBITS(u4_lev_suffix, u4_bitstream_offset, pu4_bitstrm_buf, + u4_lev_suffix_size); + u2_lev_code = (MIN(15,u4_lev_prefix) << u4_suffix_len) + + u4_lev_suffix; + + if(16 <= u4_lev_prefix) + { + u2_lev_code += ((1 << (u4_lev_prefix - 3)) - 4096); + } + u2_abs_value = (u2_lev_code + 2) >> 1; + + /*********************************************************/ + /* If Level code is odd, level is negative else positive */ + /*********************************************************/ + i2_level_arr[i--] = + (u2_lev_code & 1) ? -u2_abs_value : u2_abs_value; + + /*********************************************************/ + /* Increment suffix length if required */ + /*********************************************************/ + u4_suffix_len += + (u4_suffix_len < 6) ? + (u2_abs_value + > (3 + << (u4_suffix_len + - 1))) : + 0; + } + + /****************************************************************/ + /* Decoding Levels Ends */ + /****************************************************************/ + } + + if(u4_total_coeff < (16 - u4_isdc)) + { + UWORD32 u4_index; + const UWORD8 (*ppu1_total_zero_lkup)[16] = + (const UWORD8 (*)[16])gau1_ih264d_table_total_zero_11to15; + + NEXTBITS(u4_index, u4_bitstream_offset, pu4_bitstrm_buf, 4); + u4_total_zeroes = ppu1_total_zero_lkup[u4_total_coeff - 11][u4_index]; + + FLUSHBITS(u4_bitstream_offset, (u4_total_zeroes >> 4)); + u4_total_zeroes &= 0xf; + } + else + u4_total_zeroes = 0; + + /**************************************************************/ + /* Decode the runs and form the coefficient buffer */ + /**************************************************************/ + { + const UWORD8 *pu1_table_runbefore; + UWORD32 u4_run; + WORD32 k; + UWORD32 u4_scan_pos = u4_total_coeff + u4_total_zeroes - 1 + u4_isdc; + WORD32 u4_zeroes_left = u4_total_zeroes; + k = u4_total_coeff - 1; + + /**************************************************************/ + /* Decoding Runs for 0 < zeros left <=6 */ + /**************************************************************/ + pu1_table_runbefore = (UWORD8 *)gau1_ih264d_table_run_before; + while((u4_zeroes_left > 0) && k) + { + UWORD32 u4_code; + NEXTBITS(u4_code, u4_bitstream_offset, pu4_bitstrm_buf, 3); + + u4_code = pu1_table_runbefore[u4_code + (u4_zeroes_left << 3)]; + u4_run = u4_code >> 2; + + FLUSHBITS(u4_bitstream_offset, (u4_code & 0x03)); + SET_BIT(ps_tu_4x4->u2_sig_coeff_map, u4_scan_pos); + *pi2_coeff_data++ = i2_level_arr[k--]; + u4_zeroes_left -= u4_run; + u4_scan_pos -= (u4_run + 1); + } + /**************************************************************/ + /* Decoding Runs End */ + /**************************************************************/ + + /**************************************************************/ + /* Copy the remaining coefficients */ + /**************************************************************/ + if(u4_zeroes_left < 0) + return -1; + while(k >= 0) + { + SET_BIT(ps_tu_4x4->u2_sig_coeff_map, u4_scan_pos); + *pi2_coeff_data++ = i2_level_arr[k--]; + u4_scan_pos--; + } + } + + { + WORD32 offset; + offset = (UWORD8 *)pi2_coeff_data - (UWORD8 *)ps_tu_4x4; + offset = ALIGN4(offset); + ps_dec->pv_parse_tu_coeff_data = (void *)((UWORD8 *)ps_dec->pv_parse_tu_coeff_data + offset); + } + + ps_bitstrm->u4_ofst = u4_bitstream_offset; + return 0; +} +","@@ -443,7 +443,11 @@ + + UWORD32 u4_bitstream_offset = ps_bitstrm->u4_ofst; + UWORD32 u4_trailing_ones = u4_total_coeff_trail_one & 0xFFFF; + UWORD32 u4_total_coeff = u4_total_coeff_trail_one >> 16; +- WORD16 i2_level_arr[16]; ++ // To avoid error check at 4x4 level, allocating for 3 extra levels(16+3) ++ // since u4_trailing_ones can at the max be 3. This will be required when ++ // u4_total_coeff is less than u4_trailing_ones ++ WORD16 ai2_level_arr[19]; ++ WORD16 *i2_level_arr = &ai2_level_arr[3]; + + tu_sblk4x4_coeff_data_t *ps_tu_4x4; + WORD16 *pi2_coeff_data; +@@ -721,7 +725,11 @@ + + UWORD32 u4_bitstream_offset = ps_bitstrm->u4_ofst; + UWORD32 u4_trailing_ones = u4_total_coeff_trail_one & 0xFFFF; + UWORD32 u4_total_coeff = u4_total_coeff_trail_one >> 16; +- WORD16 i2_level_arr[16]; ++ // To avoid error check at 4x4 level, allocating for 3 extra levels(16+3) ++ // since u4_trailing_ones can at the max be 3. This will be required when ++ // u4_total_coeff is less than u4_trailing_ones ++ WORD16 ai2_level_arr[19];// ++ WORD16 *i2_level_arr = &ai2_level_arr[3]; + + tu_sblk4x4_coeff_data_t *ps_tu_4x4; + WORD16 *pi2_coeff_data; +@@ -993,7 +1001,11 @@ + + UWORD32 u4_bitstream_offset = ps_bitstrm->u4_ofst; + UWORD32 u4_trailing_ones = u4_total_coeff_trail_one & 0xFFFF; + UWORD32 u4_total_coeff = u4_total_coeff_trail_one >> 16; +- WORD16 i2_level_arr[4]; ++ // To avoid error check at 4x4 level, allocating for 3 extra levels(4+3) ++ // since u4_trailing_ones can at the max be 3. This will be required when ++ // u4_total_coeff is less than u4_trailing_ones ++ WORD16 ai2_level_arr[7];// ++ WORD16 *i2_level_arr = &ai2_level_arr[3]; + + tu_sblk4x4_coeff_data_t *ps_tu_4x4; + WORD16 *pi2_coeff_data; +",2228,2559,4096 +3241,"static int dispatch_rw_block_io(struct xen_blkif *blkif, + struct blkif_request *req, + struct pending_req *pending_req) +{ + struct phys_req preq; + struct seg_buf *seg = pending_req->seg; + unsigned int nseg; + struct bio *bio = NULL; + struct bio **biolist = pending_req->biolist; + int i, nbio = 0; + int operation; + struct blk_plug plug; + bool drain = false; + struct grant_page **pages = pending_req->segments; + unsigned short req_operation; + + req_operation = req->operation == BLKIF_OP_INDIRECT ? + req->u.indirect.indirect_op : req->operation; + if ((req->operation == BLKIF_OP_INDIRECT) && + (req_operation != BLKIF_OP_READ) && + (req_operation != BLKIF_OP_WRITE)) { + pr_debug(DRV_PFX ""Invalid indirect operation (%u)\n"", + req_operation); + goto fail_response; + } + + switch (req_operation) { + case BLKIF_OP_READ: + blkif->st_rd_req++; + operation = READ; + break; + case BLKIF_OP_WRITE: + blkif->st_wr_req++; + operation = WRITE_ODIRECT; + break; + case BLKIF_OP_WRITE_BARRIER: + drain = true; + case BLKIF_OP_FLUSH_DISKCACHE: + blkif->st_f_req++; + operation = WRITE_FLUSH; + break; + default: + operation = 0; /* make gcc happy */ + goto fail_response; + break; + } + + /* Check that the number of segments is sane. */ + nseg = req->operation == BLKIF_OP_INDIRECT ? + req->u.indirect.nr_segments : req->u.rw.nr_segments; + + if (unlikely(nseg == 0 && operation != WRITE_FLUSH) || + unlikely((req->operation != BLKIF_OP_INDIRECT) && + (nseg > BLKIF_MAX_SEGMENTS_PER_REQUEST)) || + unlikely((req->operation == BLKIF_OP_INDIRECT) && + (nseg > MAX_INDIRECT_SEGMENTS))) { + pr_debug(DRV_PFX ""Bad number of segments in request (%d)\n"", + nseg); + /* Haven't submitted any bio's yet. */ + goto fail_response; + } + + preq.nr_sects = 0; + + pending_req->blkif = blkif; + pending_req->id = req->u.rw.id; + pending_req->operation = req_operation; + pending_req->status = BLKIF_RSP_OKAY; + pending_req->nr_pages = nseg; + + if (req->operation != BLKIF_OP_INDIRECT) { + preq.dev = req->u.rw.handle; + preq.sector_number = req->u.rw.sector_number; + for (i = 0; i < nseg; i++) { + pages[i]->gref = req->u.rw.seg[i].gref; + seg[i].nsec = req->u.rw.seg[i].last_sect - + req->u.rw.seg[i].first_sect + 1; + seg[i].offset = (req->u.rw.seg[i].first_sect << 9); + if ((req->u.rw.seg[i].last_sect >= (PAGE_SIZE >> 9)) || + (req->u.rw.seg[i].last_sect < + req->u.rw.seg[i].first_sect)) + goto fail_response; + preq.nr_sects += seg[i].nsec; + } + } else { + preq.dev = req->u.indirect.handle; + preq.sector_number = req->u.indirect.sector_number; + if (xen_blkbk_parse_indirect(req, pending_req, seg, &preq)) + goto fail_response; + } + + if (xen_vbd_translate(&preq, blkif, operation) != 0) { + pr_debug(DRV_PFX ""access denied: %s of [%llu,%llu] on dev=%04x\n"", + operation == READ ? ""read"" : ""write"", + preq.sector_number, + preq.sector_number + preq.nr_sects, + blkif->vbd.pdevice); + goto fail_response; + } + + /* + * This check _MUST_ be done after xen_vbd_translate as the preq.bdev + * is set there. + */ + for (i = 0; i < nseg; i++) { + if (((int)preq.sector_number|(int)seg[i].nsec) & + ((bdev_logical_block_size(preq.bdev) >> 9) - 1)) { + pr_debug(DRV_PFX ""Misaligned I/O request from domain %d"", + blkif->domid); + goto fail_response; + } + } + + /* Wait on all outstanding I/O's and once that has been completed + * issue the WRITE_FLUSH. + */ + if (drain) + xen_blk_drain_io(pending_req->blkif); + + /* + * If we have failed at this point, we need to undo the M2P override, + * set gnttab_set_unmap_op on all of the grant references and perform + * the hypercall to unmap the grants - that is all done in + * xen_blkbk_unmap. + */ + if (xen_blkbk_map_seg(pending_req)) + goto fail_flush; + + /* + * This corresponding xen_blkif_put is done in __end_block_io_op, or + * below (in ""!bio"") if we are handling a BLKIF_OP_DISCARD. + */ + xen_blkif_get(blkif); + + for (i = 0; i < nseg; i++) { + while ((bio == NULL) || + (bio_add_page(bio, + pages[i]->page, + seg[i].nsec << 9, + seg[i].offset) == 0)) { + + bio = bio_alloc(GFP_KERNEL, nseg-i); + if (unlikely(bio == NULL)) + goto fail_put_bio; + + biolist[nbio++] = bio; + bio->bi_bdev = preq.bdev; + bio->bi_private = pending_req; + bio->bi_end_io = end_block_io_op; + bio->bi_sector = preq.sector_number; + } + + preq.sector_number += seg[i].nsec; + } + + /* This will be hit if the operation was a flush or discard. */ + if (!bio) { + BUG_ON(operation != WRITE_FLUSH); + + bio = bio_alloc(GFP_KERNEL, 0); + if (unlikely(bio == NULL)) + goto fail_put_bio; + + biolist[nbio++] = bio; + bio->bi_bdev = preq.bdev; + bio->bi_private = pending_req; + bio->bi_end_io = end_block_io_op; + } + + atomic_set(&pending_req->pendcnt, nbio); + blk_start_plug(&plug); + + for (i = 0; i < nbio; i++) + submit_bio(operation, biolist[i]); + + /* Let the I/Os go.. */ + blk_finish_plug(&plug); + + if (operation == READ) + blkif->st_rd_sect += preq.nr_sects; + else if (operation & WRITE) + blkif->st_wr_sect += preq.nr_sects; + + return 0; + + fail_flush: + xen_blkbk_unmap(blkif, pending_req->segments, + pending_req->nr_pages); + fail_response: + /* Haven't submitted any bio's yet. */ + make_response(blkif, req->u.rw.id, req_operation, BLKIF_RSP_ERROR); + free_req(blkif, pending_req); + msleep(1); /* back off a bit */ + return -EIO; + + fail_put_bio: + for (i = 0; i < nbio; i++) + bio_put(biolist[i]); + atomic_set(&pending_req->pendcnt, 1); + __end_block_io_op(pending_req, -EINVAL); + msleep(1); /* back off a bit */ + return -EIO; +} +",0,"static int dispatch_rw_block_io(struct xen_blkif *blkif, + struct blkif_request *req, + struct pending_req *pending_req) +{ + struct phys_req preq; + struct seg_buf *seg = pending_req->seg; + unsigned int nseg; + struct bio *bio = NULL; + struct bio **biolist = pending_req->biolist; + int i, nbio = 0; + int operation; + struct blk_plug plug; + bool drain = false; + struct grant_page **pages = pending_req->segments; + unsigned short req_operation; + + req_operation = req->operation == BLKIF_OP_INDIRECT ? + req->u.indirect.indirect_op : req->operation; + if ((req->operation == BLKIF_OP_INDIRECT) && + (req_operation != BLKIF_OP_READ) && + (req_operation != BLKIF_OP_WRITE)) { + pr_debug(DRV_PFX ""Invalid indirect operation (%u)\n"", + req_operation); + goto fail_response; + } + + switch (req_operation) { + case BLKIF_OP_READ: + blkif->st_rd_req++; + operation = READ; + break; + case BLKIF_OP_WRITE: + blkif->st_wr_req++; + operation = WRITE_ODIRECT; + break; + case BLKIF_OP_WRITE_BARRIER: + drain = true; + case BLKIF_OP_FLUSH_DISKCACHE: + blkif->st_f_req++; + operation = WRITE_FLUSH; + break; + default: + operation = 0; /* make gcc happy */ + goto fail_response; + break; + } + + /* Check that the number of segments is sane. */ + nseg = req->operation == BLKIF_OP_INDIRECT ? + req->u.indirect.nr_segments : req->u.rw.nr_segments; + + if (unlikely(nseg == 0 && operation != WRITE_FLUSH) || + unlikely((req->operation != BLKIF_OP_INDIRECT) && + (nseg > BLKIF_MAX_SEGMENTS_PER_REQUEST)) || + unlikely((req->operation == BLKIF_OP_INDIRECT) && + (nseg > MAX_INDIRECT_SEGMENTS))) { + pr_debug(DRV_PFX ""Bad number of segments in request (%d)\n"", + nseg); + /* Haven't submitted any bio's yet. */ + goto fail_response; + } + + preq.nr_sects = 0; + + pending_req->blkif = blkif; + pending_req->id = req->u.rw.id; + pending_req->operation = req_operation; + pending_req->status = BLKIF_RSP_OKAY; + pending_req->nr_pages = nseg; + + if (req->operation != BLKIF_OP_INDIRECT) { + preq.dev = req->u.rw.handle; + preq.sector_number = req->u.rw.sector_number; + for (i = 0; i < nseg; i++) { + pages[i]->gref = req->u.rw.seg[i].gref; + seg[i].nsec = req->u.rw.seg[i].last_sect - + req->u.rw.seg[i].first_sect + 1; + seg[i].offset = (req->u.rw.seg[i].first_sect << 9); + if ((req->u.rw.seg[i].last_sect >= (PAGE_SIZE >> 9)) || + (req->u.rw.seg[i].last_sect < + req->u.rw.seg[i].first_sect)) + goto fail_response; + preq.nr_sects += seg[i].nsec; + } + } else { + preq.dev = req->u.indirect.handle; + preq.sector_number = req->u.indirect.sector_number; + if (xen_blkbk_parse_indirect(req, pending_req, seg, &preq)) + goto fail_response; + } + + if (xen_vbd_translate(&preq, blkif, operation) != 0) { + pr_debug(DRV_PFX ""access denied: %s of [%llu,%llu] on dev=%04x\n"", + operation == READ ? ""read"" : ""write"", + preq.sector_number, + preq.sector_number + preq.nr_sects, + blkif->vbd.pdevice); + goto fail_response; + } + + /* + * This check _MUST_ be done after xen_vbd_translate as the preq.bdev + * is set there. + */ + for (i = 0; i < nseg; i++) { + if (((int)preq.sector_number|(int)seg[i].nsec) & + ((bdev_logical_block_size(preq.bdev) >> 9) - 1)) { + pr_debug(DRV_PFX ""Misaligned I/O request from domain %d"", + blkif->domid); + goto fail_response; + } + } + + /* Wait on all outstanding I/O's and once that has been completed + * issue the WRITE_FLUSH. + */ + if (drain) + xen_blk_drain_io(pending_req->blkif); + + /* + * If we have failed at this point, we need to undo the M2P override, + * set gnttab_set_unmap_op on all of the grant references and perform + * the hypercall to unmap the grants - that is all done in + * xen_blkbk_unmap. + */ + if (xen_blkbk_map_seg(pending_req)) + goto fail_flush; + + /* + * This corresponding xen_blkif_put is done in __end_block_io_op, or + * below (in ""!bio"") if we are handling a BLKIF_OP_DISCARD. + */ + xen_blkif_get(blkif); + + for (i = 0; i < nseg; i++) { + while ((bio == NULL) || + (bio_add_page(bio, + pages[i]->page, + seg[i].nsec << 9, + seg[i].offset) == 0)) { + + bio = bio_alloc(GFP_KERNEL, nseg-i); + if (unlikely(bio == NULL)) + goto fail_put_bio; + + biolist[nbio++] = bio; + bio->bi_bdev = preq.bdev; + bio->bi_private = pending_req; + bio->bi_end_io = end_block_io_op; + bio->bi_sector = preq.sector_number; + } + + preq.sector_number += seg[i].nsec; + } + + /* This will be hit if the operation was a flush or discard. */ + if (!bio) { + BUG_ON(operation != WRITE_FLUSH); + + bio = bio_alloc(GFP_KERNEL, 0); + if (unlikely(bio == NULL)) + goto fail_put_bio; + + biolist[nbio++] = bio; + bio->bi_bdev = preq.bdev; + bio->bi_private = pending_req; + bio->bi_end_io = end_block_io_op; + } + + atomic_set(&pending_req->pendcnt, nbio); + blk_start_plug(&plug); + + for (i = 0; i < nbio; i++) + submit_bio(operation, biolist[i]); + + /* Let the I/Os go.. */ + blk_finish_plug(&plug); + + if (operation == READ) + blkif->st_rd_sect += preq.nr_sects; + else if (operation & WRITE) + blkif->st_wr_sect += preq.nr_sects; + + return 0; + + fail_flush: + xen_blkbk_unmap(blkif, pending_req->segments, + pending_req->nr_pages); + fail_response: + /* Haven't submitted any bio's yet. */ + make_response(blkif, req->u.rw.id, req_operation, BLKIF_RSP_ERROR); + free_req(blkif, pending_req); + msleep(1); /* back off a bit */ + return -EIO; + + fail_put_bio: + for (i = 0; i < nbio; i++) + bio_put(biolist[i]); + atomic_set(&pending_req->pendcnt, 1); + __end_block_io_op(pending_req, -EINVAL); + msleep(1); /* back off a bit */ + return -EIO; +} +","@@ -876,7 +876,18 @@ static int dispatch_discard_io(struct xen_blkif *blkif, + int status = BLKIF_RSP_OKAY; + struct block_device *bdev = blkif->vbd.bdev; + unsigned long secure; ++ struct phys_req preq; ++ ++ preq.sector_number = req->u.discard.sector_number; ++ preq.nr_sects = req->u.discard.nr_sectors; + ++ err = xen_vbd_translate(&preq, blkif, WRITE); ++ if (err) { ++ pr_warn(DRV_PFX ""access denied: DISCARD [%llu->%llu] on dev=%04x\n"", ++ preq.sector_number, ++ preq.sector_number + preq.nr_sects, blkif->vbd.pdevice); ++ goto fail_response; ++ } + blkif->st_ds_req++; + + xen_blkif_get(blkif); +@@ -887,7 +898,7 @@ static int dispatch_discard_io(struct xen_blkif *blkif, + err = blkdev_issue_discard(bdev, req->u.discard.sector_number, + req->u.discard.nr_sectors, + GFP_KERNEL, secure); +- ++fail_response: + if (err == -EOPNOTSUPP) { + pr_debug(DRV_PFX ""discard op failed, not supported\n""); + status = BLKIF_RSP_EOPNOTSUPP;",1779,2110,4096 +85,"void ArthurOutputDev::updateFont(GfxState *state) +{ + GfxFont *gfxFont; + GfxFontType fontType; + SplashOutFontFileID *id; + SplashFontFile *fontFile; + SplashFontSrc *fontsrc; + FoFiTrueType *ff; + Ref embRef; + Object refObj, strObj; + GooString *fileName; + char *tmpBuf; + int tmpBufLen; + Gushort *codeToGID; + DisplayFontParam *dfp; + double *textMat; + double m11, m12, m21, m22, fontSize; + SplashCoord mat[4]; + int substIdx, n; + int faceIndex = 0; + SplashCoord matrix[6]; + + m_needFontUpdate = false; + m_font = NULL; + fileName = NULL; + tmpBuf = NULL; + substIdx = -1; + + if (!(gfxFont = state->getFont())) { + goto err1; + } + fontType = gfxFont->getType(); + if (fontType == fontType3) { + goto err1; + } + + id = new SplashOutFontFileID(gfxFont->getID()); + if ((fontFile = m_fontEngine->getFontFile(id))) { + delete id; + + } else { + + if (gfxFont->getEmbeddedFontID(&embRef)) { + tmpBuf = gfxFont->readEmbFontFile(xref, &tmpBufLen); + if (! tmpBuf) + goto err2; + } else if (!(fileName = gfxFont->getExtFontFile())) { + + dfp = NULL; + if (gfxFont->getName()) { + dfp = globalParams->getDisplayFont(gfxFont); + } + if (!dfp) { + error(-1, ""Couldn't find a font for '%s'"", + gfxFont->getName() ? gfxFont->getName()->getCString() + : ""(unnamed)""); + goto err2; + } + switch (dfp->kind) { + case displayFontT1: + fileName = dfp->t1.fileName; + fontType = gfxFont->isCIDFont() ? fontCIDType0 : fontType1; + break; + case displayFontTT: + fileName = dfp->tt.fileName; + fontType = gfxFont->isCIDFont() ? fontCIDType2 : fontTrueType; + faceIndex = dfp->tt.faceIndex; + break; + } + } + + fontsrc = new SplashFontSrc; + if (fileName) + fontsrc->setFile(fileName, gFalse); + else + fontsrc->setBuf(tmpBuf, tmpBufLen, gFalse); + + switch (fontType) { + case fontType1: + if (!(fontFile = m_fontEngine->loadType1Font( + id, + fontsrc, + ((Gfx8BitFont *)gfxFont)->getEncoding()))) { + error(-1, ""Couldn't create a font for '%s'"", + gfxFont->getName() ? gfxFont->getName()->getCString() + : ""(unnamed)""); + goto err2; + } + break; + case fontType1C: + if (!(fontFile = m_fontEngine->loadType1CFont( + id, + fontsrc, + ((Gfx8BitFont *)gfxFont)->getEncoding()))) { + error(-1, ""Couldn't create a font for '%s'"", + gfxFont->getName() ? gfxFont->getName()->getCString() + : ""(unnamed)""); + goto err2; + } + break; + case fontType1COT: + if (!(fontFile = m_fontEngine->loadOpenTypeT1CFont( + id, + fontsrc, + ((Gfx8BitFont *)gfxFont)->getEncoding()))) { + error(-1, ""Couldn't create a font for '%s'"", + gfxFont->getName() ? gfxFont->getName()->getCString() + : ""(unnamed)""); + goto err2; + } + break; + case fontTrueType: + case fontTrueTypeOT: + if (fileName) + ff = FoFiTrueType::load(fileName->getCString()); + else + ff = FoFiTrueType::make(tmpBuf, tmpBufLen); + if (ff) { + codeToGID = ((Gfx8BitFont *)gfxFont)->getCodeToGIDMap(ff); + n = 256; + delete ff; + } else { + codeToGID = NULL; + n = 0; + } + if (!(fontFile = m_fontEngine->loadTrueTypeFont( + id, + fontsrc, + codeToGID, n))) { + error(-1, ""Couldn't create a font for '%s'"", + gfxFont->getName() ? gfxFont->getName()->getCString() + : ""(unnamed)""); + goto err2; + } + break; + case fontCIDType0: + case fontCIDType0C: + if (!(fontFile = m_fontEngine->loadCIDFont( + id, + fontsrc))) { + error(-1, ""Couldn't create a font for '%s'"", + gfxFont->getName() ? gfxFont->getName()->getCString() + : ""(unnamed)""); + goto err2; + } + break; + case fontCIDType0COT: + if (!(fontFile = m_fontEngine->loadOpenTypeCFFFont( + id, + fontsrc))) { + error(-1, ""Couldn't create a font for '%s'"", + gfxFont->getName() ? gfxFont->getName()->getCString() + : ""(unnamed)""); + goto err2; + } + break; + case fontCIDType2: + case fontCIDType2OT: + codeToGID = NULL; + n = 0; + if (((GfxCIDFont *)gfxFont)->getCIDToGID()) { + n = ((GfxCIDFont *)gfxFont)->getCIDToGIDLen(); + if (n) { + codeToGID = (Gushort *)gmallocn(n, sizeof(Gushort)); + memcpy(codeToGID, ((GfxCIDFont *)gfxFont)->getCIDToGID(), + n * sizeof(Gushort)); + } + } else { + if (fileName) + ff = FoFiTrueType::load(fileName->getCString()); + else + ff = FoFiTrueType::make(tmpBuf, tmpBufLen); + if (! ff) + goto err2; + codeToGID = ((GfxCIDFont *)gfxFont)->getCodeToGIDMap(ff, &n); + delete ff; + } + if (!(fontFile = m_fontEngine->loadTrueTypeFont( + id, + fontsrc, + codeToGID, n, faceIndex))) { + error(-1, ""Couldn't create a font for '%s'"", + gfxFont->getName() ? gfxFont->getName()->getCString() + : ""(unnamed)""); + goto err2; + } + break; + default: + goto err2; + } + } + + textMat = state->getTextMat(); + fontSize = state->getFontSize(); + m11 = textMat[0] * fontSize * state->getHorizScaling(); + m12 = textMat[1] * fontSize * state->getHorizScaling(); + m21 = textMat[2] * fontSize; + m22 = textMat[3] * fontSize; + + { + QMatrix painterMatrix = m_painter->worldMatrix(); + matrix[0] = painterMatrix.m11(); + matrix[1] = painterMatrix.m12(); + matrix[2] = painterMatrix.m21(); + matrix[3] = painterMatrix.m22(); + matrix[4] = painterMatrix.dx(); + matrix[5] = painterMatrix.dy(); + } + + mat[0] = m11; mat[1] = -m12; + mat[2] = m21; mat[3] = -m22; + m_font = m_fontEngine->getFont(fontFile, mat, matrix); + + return; + + err2: + delete id; + err1: + return; +} +",0,"void ArthurOutputDev::updateFont(GfxState *state) +{ + GfxFont *gfxFont; + GfxFontType fontType; + SplashOutFontFileID *id; + SplashFontFile *fontFile; + SplashFontSrc *fontsrc; + FoFiTrueType *ff; + Ref embRef; + Object refObj, strObj; + GooString *fileName; + char *tmpBuf; + int tmpBufLen; + Gushort *codeToGID; + DisplayFontParam *dfp; + double *textMat; + double m11, m12, m21, m22, fontSize; + SplashCoord mat[4]; + int substIdx, n; + int faceIndex = 0; + SplashCoord matrix[6]; + + m_needFontUpdate = false; + m_font = NULL; + fileName = NULL; + tmpBuf = NULL; + substIdx = -1; + + if (!(gfxFont = state->getFont())) { + goto err1; + } + fontType = gfxFont->getType(); + if (fontType == fontType3) { + goto err1; + } + + id = new SplashOutFontFileID(gfxFont->getID()); + if ((fontFile = m_fontEngine->getFontFile(id))) { + delete id; + + } else { + + if (gfxFont->getEmbeddedFontID(&embRef)) { + tmpBuf = gfxFont->readEmbFontFile(xref, &tmpBufLen); + if (! tmpBuf) + goto err2; + } else if (!(fileName = gfxFont->getExtFontFile())) { + + dfp = NULL; + if (gfxFont->getName()) { + dfp = globalParams->getDisplayFont(gfxFont); + } + if (!dfp) { + error(-1, ""Couldn't find a font for '%s'"", + gfxFont->getName() ? gfxFont->getName()->getCString() + : ""(unnamed)""); + goto err2; + } + switch (dfp->kind) { + case displayFontT1: + fileName = dfp->t1.fileName; + fontType = gfxFont->isCIDFont() ? fontCIDType0 : fontType1; + break; + case displayFontTT: + fileName = dfp->tt.fileName; + fontType = gfxFont->isCIDFont() ? fontCIDType2 : fontTrueType; + faceIndex = dfp->tt.faceIndex; + break; + } + } + + fontsrc = new SplashFontSrc; + if (fileName) + fontsrc->setFile(fileName, gFalse); + else + fontsrc->setBuf(tmpBuf, tmpBufLen, gFalse); + + switch (fontType) { + case fontType1: + if (!(fontFile = m_fontEngine->loadType1Font( + id, + fontsrc, + ((Gfx8BitFont *)gfxFont)->getEncoding()))) { + error(-1, ""Couldn't create a font for '%s'"", + gfxFont->getName() ? gfxFont->getName()->getCString() + : ""(unnamed)""); + goto err2; + } + break; + case fontType1C: + if (!(fontFile = m_fontEngine->loadType1CFont( + id, + fontsrc, + ((Gfx8BitFont *)gfxFont)->getEncoding()))) { + error(-1, ""Couldn't create a font for '%s'"", + gfxFont->getName() ? gfxFont->getName()->getCString() + : ""(unnamed)""); + goto err2; + } + break; + case fontType1COT: + if (!(fontFile = m_fontEngine->loadOpenTypeT1CFont( + id, + fontsrc, + ((Gfx8BitFont *)gfxFont)->getEncoding()))) { + error(-1, ""Couldn't create a font for '%s'"", + gfxFont->getName() ? gfxFont->getName()->getCString() + : ""(unnamed)""); + goto err2; + } + break; + case fontTrueType: + case fontTrueTypeOT: + if (fileName) + ff = FoFiTrueType::load(fileName->getCString()); + else + ff = FoFiTrueType::make(tmpBuf, tmpBufLen); + if (ff) { + codeToGID = ((Gfx8BitFont *)gfxFont)->getCodeToGIDMap(ff); + n = 256; + delete ff; + } else { + codeToGID = NULL; + n = 0; + } + if (!(fontFile = m_fontEngine->loadTrueTypeFont( + id, + fontsrc, + codeToGID, n))) { + error(-1, ""Couldn't create a font for '%s'"", + gfxFont->getName() ? gfxFont->getName()->getCString() + : ""(unnamed)""); + goto err2; + } + break; + case fontCIDType0: + case fontCIDType0C: + if (!(fontFile = m_fontEngine->loadCIDFont( + id, + fontsrc))) { + error(-1, ""Couldn't create a font for '%s'"", + gfxFont->getName() ? gfxFont->getName()->getCString() + : ""(unnamed)""); + goto err2; + } + break; + case fontCIDType0COT: + if (!(fontFile = m_fontEngine->loadOpenTypeCFFFont( + id, + fontsrc))) { + error(-1, ""Couldn't create a font for '%s'"", + gfxFont->getName() ? gfxFont->getName()->getCString() + : ""(unnamed)""); + goto err2; + } + break; + case fontCIDType2: + case fontCIDType2OT: + codeToGID = NULL; + n = 0; + if (((GfxCIDFont *)gfxFont)->getCIDToGID()) { + n = ((GfxCIDFont *)gfxFont)->getCIDToGIDLen(); + if (n) { + codeToGID = (Gushort *)gmallocn(n, sizeof(Gushort)); + memcpy(codeToGID, ((GfxCIDFont *)gfxFont)->getCIDToGID(), + n * sizeof(Gushort)); + } + } else { + if (fileName) + ff = FoFiTrueType::load(fileName->getCString()); + else + ff = FoFiTrueType::make(tmpBuf, tmpBufLen); + if (! ff) + goto err2; + codeToGID = ((GfxCIDFont *)gfxFont)->getCodeToGIDMap(ff, &n); + delete ff; + } + if (!(fontFile = m_fontEngine->loadTrueTypeFont( + id, + fontsrc, + codeToGID, n, faceIndex))) { + error(-1, ""Couldn't create a font for '%s'"", + gfxFont->getName() ? gfxFont->getName()->getCString() + : ""(unnamed)""); + goto err2; + } + break; + default: + goto err2; + } + } + + textMat = state->getTextMat(); + fontSize = state->getFontSize(); + m11 = textMat[0] * fontSize * state->getHorizScaling(); + m12 = textMat[1] * fontSize * state->getHorizScaling(); + m21 = textMat[2] * fontSize; + m22 = textMat[3] * fontSize; + + { + QMatrix painterMatrix = m_painter->worldMatrix(); + matrix[0] = painterMatrix.m11(); + matrix[1] = painterMatrix.m12(); + matrix[2] = painterMatrix.m21(); + matrix[3] = painterMatrix.m22(); + matrix[4] = painterMatrix.dx(); + matrix[5] = painterMatrix.dy(); + } + + mat[0] = m11; mat[1] = -m12; + mat[2] = m21; mat[3] = -m22; + m_font = m_fontEngine->getFont(fontFile, mat, matrix); + + return; + + err2: + delete id; + err1: + return; +} +","@@ -14,7 +14,7 @@ + // under GPL version 2 or later + // + // Copyright (C) 2005 Brad Hards +-// Copyright (C) 2005-2008 Albert Astals Cid ++// Copyright (C) 2005-2009 Albert Astals Cid + // Copyright (C) 2008 Pino Toscano + // + // To see a description of the changes please see the Changelog file that +@@ -751,7 +751,7 @@ void ArthurOutputDev::drawImage(GfxState *state, Object *ref, Stream *str, + QMatrix matrix; + int is_identity_transform; + +- buffer = (unsigned char *)gmalloc (width * height * 4); ++ buffer = (unsigned char *)gmallocn3(width, height, 4); + + /* TODO: Do we want to cache these? */ + imgStr = new ImageStream(str, width,",1720,2051,4096 +17789,"gs_call_interp(i_ctx_t **pi_ctx_p, ref * pref, int user_errors, + int *pexit_code, ref * perror_object) +{ + ref *epref = pref; + ref doref; + ref *perrordict; + ref error_name; + int code, ccode; + ref saref; + i_ctx_t *i_ctx_p = *pi_ctx_p; + int *gc_signal = &imemory_system->gs_lib_ctx->gcsignal; + + *pexit_code = 0; + *gc_signal = 0; + ialloc_reset_requested(idmemory); +again: + /* Avoid a dangling error object that might get traced by a future GC. */ + make_null(perror_object); + o_stack.requested = e_stack.requested = d_stack.requested = 0; + while (*gc_signal) { /* Some routine below triggered a GC. */ + gs_gc_root_t epref_root; + + *gc_signal = 0; + /* Make sure that doref will get relocated properly if */ + /* a garbage collection happens with epref == &doref. */ + gs_register_ref_root(imemory_system, &epref_root, + (void **)&epref, ""gs_call_interp(epref)""); + code = interp_reclaim(pi_ctx_p, -1); + i_ctx_p = *pi_ctx_p; + gs_unregister_root(imemory_system, &epref_root, + ""gs_call_interp(epref)""); + if (code < 0) + return code; + } + code = interp(pi_ctx_p, epref, perror_object); + i_ctx_p = *pi_ctx_p; + if (!r_has_type(&i_ctx_p->error_object, t__invalid)) { + *perror_object = i_ctx_p->error_object; + make_t(&i_ctx_p->error_object, t__invalid); + } + /* Prevent a dangling reference to the GC signal in ticks_left */ + /* in the frame of interp, but be prepared to do a GC if */ + /* an allocation in this routine asks for it. */ + *gc_signal = 0; + set_gc_signal(i_ctx_p, 1); + if (esp < esbot) /* popped guard entry */ + esp = esbot; + switch (code) { + case gs_error_Fatal: + *pexit_code = 255; + return code; + case gs_error_Quit: + *perror_object = osp[-1]; + *pexit_code = code = osp->value.intval; + osp -= 2; + return + (code == 0 ? gs_error_Quit : + code < 0 && code > -100 ? code : gs_error_Fatal); + case gs_error_InterpreterExit: + return 0; + case gs_error_ExecStackUnderflow: +/****** WRONG -- must keep mark blocks intact ******/ + ref_stack_pop_block(&e_stack); + doref = *perror_object; + epref = &doref; + goto again; + case gs_error_VMreclaim: + /* Do the GC and continue. */ + /* We ignore the return value here, if it fails here + * we'll call it again having jumped to the ""again"" label. + * Where, assuming it fails again, we'll handle the error. + */ + (void)interp_reclaim(pi_ctx_p, + (osp->value.intval == 2 ? + avm_global : avm_local)); + i_ctx_p = *pi_ctx_p; + make_oper(&doref, 0, zpop); + epref = &doref; + goto again; + case gs_error_NeedInput: + case gs_error_interrupt: + return code; + } + /* Adjust osp in case of operand stack underflow */ + if (osp < osbot - 1) + osp = osbot - 1; + /* We have to handle stack over/underflow specially, because */ + /* we might be able to recover by adding or removing a block. */ + switch (code) { + case gs_error_dictstackoverflow: + /* We don't have to handle this specially: */ + /* The only places that could generate it */ + /* use check_dstack, which does a ref_stack_extend, */ + /* so if` we get this error, it's a real one. */ + if (osp >= ostop) { + if ((ccode = ref_stack_extend(&o_stack, 1)) < 0) + return ccode; + } + /* Skip system dictionaries for CET 20-02-02 */ + ccode = copy_stack(i_ctx_p, &d_stack, min_dstack_size, &saref); + if (ccode < 0) + return ccode; + ref_stack_pop_to(&d_stack, min_dstack_size); + dict_set_top(); + *++osp = saref; + break; + case gs_error_dictstackunderflow: + if (ref_stack_pop_block(&d_stack) >= 0) { + dict_set_top(); + doref = *perror_object; + epref = &doref; + goto again; + } + break; + case gs_error_execstackoverflow: + /* We don't have to handle this specially: */ + /* The only places that could generate it */ + /* use check_estack, which does a ref_stack_extend, */ + /* so if we get this error, it's a real one. */ + if (osp >= ostop) { + if ((ccode = ref_stack_extend(&o_stack, 1)) < 0) + return ccode; + } + ccode = copy_stack(i_ctx_p, &e_stack, 0, &saref); + if (ccode < 0) + return ccode; + { + uint count = ref_stack_count(&e_stack); + uint limit = ref_stack_max_count(&e_stack) - ES_HEADROOM; + + if (count > limit) { + /* + * If there is an e-stack mark within MIN_BLOCK_ESTACK of + * the new top, cut the stack back to remove the mark. + */ + int skip = count - limit; + int i; + + for (i = skip; i < skip + MIN_BLOCK_ESTACK; ++i) { + const ref *ep = ref_stack_index(&e_stack, i); + + if (r_has_type_attrs(ep, t_null, a_executable)) { + skip = i + 1; + break; + } + } + pop_estack(i_ctx_p, skip); + } + } + *++osp = saref; + break; + case gs_error_stackoverflow: + if (ref_stack_extend(&o_stack, o_stack.requested) >= 0) { /* We can't just re-execute the object, because */ + /* it might be a procedure being pushed as a */ + /* literal. We check for this case specially. */ + doref = *perror_object; + if (r_is_proc(&doref)) { + *++osp = doref; + make_null_proc(&doref); + } + epref = &doref; + goto again; + } + ccode = copy_stack(i_ctx_p, &o_stack, 0, &saref); + if (ccode < 0) + return ccode; + ref_stack_clear(&o_stack); + *++osp = saref; + break; + case gs_error_stackunderflow: + if (ref_stack_pop_block(&o_stack) >= 0) { + doref = *perror_object; + epref = &doref; + goto again; + } + break; + } + if (user_errors < 0) + return code; + if (gs_errorname(i_ctx_p, code, &error_name) < 0) + return code; /* out-of-range error code! */ + /* + * For greater Adobe compatibility, only the standard PostScript errors + * are defined in errordict; the rest are in gserrordict. + */ + if (dict_find_string(systemdict, ""errordict"", &perrordict) <= 0 || + (dict_find(perrordict, &error_name, &epref) <= 0 && + (dict_find_string(systemdict, ""gserrordict"", &perrordict) <= 0 || + dict_find(perrordict, &error_name, &epref) <= 0)) + ) + return code; /* error name not in errordict??? */ + doref = *epref; + epref = &doref; + /* Push the error object on the operand stack if appropriate. */ + if (!GS_ERROR_IS_INTERRUPT(code)) { + /* Replace the error object if within an oparray or .errorexec. */ + *++osp = *perror_object; + errorexec_find(i_ctx_p, osp); + } + goto again; +} +",1,"gs_call_interp(i_ctx_t **pi_ctx_p, ref * pref, int user_errors, + int *pexit_code, ref * perror_object) +{ + ref *epref = pref; + ref doref; + ref *perrordict; + ref error_name; + int code, ccode; + ref saref; + i_ctx_t *i_ctx_p = *pi_ctx_p; + int *gc_signal = &imemory_system->gs_lib_ctx->gcsignal; + + *pexit_code = 0; + *gc_signal = 0; + ialloc_reset_requested(idmemory); +again: + /* Avoid a dangling error object that might get traced by a future GC. */ + make_null(perror_object); + o_stack.requested = e_stack.requested = d_stack.requested = 0; + while (*gc_signal) { /* Some routine below triggered a GC. */ + gs_gc_root_t epref_root; + + *gc_signal = 0; + /* Make sure that doref will get relocated properly if */ + /* a garbage collection happens with epref == &doref. */ + gs_register_ref_root(imemory_system, &epref_root, + (void **)&epref, ""gs_call_interp(epref)""); + code = interp_reclaim(pi_ctx_p, -1); + i_ctx_p = *pi_ctx_p; + gs_unregister_root(imemory_system, &epref_root, + ""gs_call_interp(epref)""); + if (code < 0) + return code; + } + code = interp(pi_ctx_p, epref, perror_object); + i_ctx_p = *pi_ctx_p; + if (!r_has_type(&i_ctx_p->error_object, t__invalid)) { + *perror_object = i_ctx_p->error_object; + make_t(&i_ctx_p->error_object, t__invalid); + } + /* Prevent a dangling reference to the GC signal in ticks_left */ + /* in the frame of interp, but be prepared to do a GC if */ + /* an allocation in this routine asks for it. */ + *gc_signal = 0; + set_gc_signal(i_ctx_p, 1); + if (esp < esbot) /* popped guard entry */ + esp = esbot; + switch (code) { + case gs_error_Fatal: + *pexit_code = 255; + return code; + case gs_error_Quit: + *perror_object = osp[-1]; + *pexit_code = code = osp->value.intval; + osp -= 2; + return + (code == 0 ? gs_error_Quit : + code < 0 && code > -100 ? code : gs_error_Fatal); + case gs_error_InterpreterExit: + return 0; + case gs_error_ExecStackUnderflow: +/****** WRONG -- must keep mark blocks intact ******/ + ref_stack_pop_block(&e_stack); + doref = *perror_object; + epref = &doref; + goto again; + case gs_error_VMreclaim: + /* Do the GC and continue. */ + /* We ignore the return value here, if it fails here + * we'll call it again having jumped to the ""again"" label. + * Where, assuming it fails again, we'll handle the error. + */ + (void)interp_reclaim(pi_ctx_p, + (osp->value.intval == 2 ? + avm_global : avm_local)); + i_ctx_p = *pi_ctx_p; + make_oper(&doref, 0, zpop); + epref = &doref; + goto again; + case gs_error_NeedInput: + case gs_error_interrupt: + return code; + } + /* Adjust osp in case of operand stack underflow */ + if (osp < osbot - 1) + osp = osbot - 1; + /* We have to handle stack over/underflow specially, because */ + /* we might be able to recover by adding or removing a block. */ + switch (code) { + case gs_error_dictstackoverflow: + /* We don't have to handle this specially: */ + /* The only places that could generate it */ + /* use check_dstack, which does a ref_stack_extend, */ + /* so if` we get this error, it's a real one. */ + if (osp >= ostop) { + if ((ccode = ref_stack_extend(&o_stack, 1)) < 0) + return ccode; + } + /* Skip system dictionaries for CET 20-02-02 */ + ccode = copy_stack(i_ctx_p, &d_stack, min_dstack_size, &saref); + if (ccode < 0) + return ccode; + ref_stack_pop_to(&d_stack, min_dstack_size); + dict_set_top(); + *++osp = saref; + break; + case gs_error_dictstackunderflow: + if (ref_stack_pop_block(&d_stack) >= 0) { + dict_set_top(); + doref = *perror_object; + epref = &doref; + goto again; + } + break; + case gs_error_execstackoverflow: + /* We don't have to handle this specially: */ + /* The only places that could generate it */ + /* use check_estack, which does a ref_stack_extend, */ + /* so if we get this error, it's a real one. */ + if (osp >= ostop) { + if ((ccode = ref_stack_extend(&o_stack, 1)) < 0) + return ccode; + } + ccode = copy_stack(i_ctx_p, &e_stack, 0, &saref); + if (ccode < 0) + return ccode; + { + uint count = ref_stack_count(&e_stack); + uint limit = ref_stack_max_count(&e_stack) - ES_HEADROOM; + + if (count > limit) { + /* + * If there is an e-stack mark within MIN_BLOCK_ESTACK of + * the new top, cut the stack back to remove the mark. + */ + int skip = count - limit; + int i; + + for (i = skip; i < skip + MIN_BLOCK_ESTACK; ++i) { + const ref *ep = ref_stack_index(&e_stack, i); + + if (r_has_type_attrs(ep, t_null, a_executable)) { + skip = i + 1; + break; + } + } + pop_estack(i_ctx_p, skip); + } + } + *++osp = saref; + break; + case gs_error_stackoverflow: + if (ref_stack_extend(&o_stack, o_stack.requested) >= 0) { /* We can't just re-execute the object, because */ + /* it might be a procedure being pushed as a */ + /* literal. We check for this case specially. */ + doref = *perror_object; + if (r_is_proc(&doref)) { + *++osp = doref; + make_null_proc(&doref); + } + epref = &doref; + goto again; + } + ccode = copy_stack(i_ctx_p, &o_stack, 0, &saref); + if (ccode < 0) + return ccode; + ref_stack_clear(&o_stack); + *++osp = saref; + break; + case gs_error_stackunderflow: + if (ref_stack_pop_block(&o_stack) >= 0) { + doref = *perror_object; + epref = &doref; + goto again; + } + break; + } + if (user_errors < 0) + return code; + if (gs_errorname(i_ctx_p, code, &error_name) < 0) + return code; /* out-of-range error code! */ + /* + * For greater Adobe compatibility, only the standard PostScript errors + * are defined in errordict; the rest are in gserrordict. + */ + if (dict_find_string(systemdict, ""errordict"", &perrordict) <= 0 || + (dict_find(perrordict, &error_name, &epref) <= 0 && + (dict_find_string(systemdict, ""gserrordict"", &perrordict) <= 0 || + dict_find(perrordict, &error_name, &epref) <= 0)) + ) + return code; /* error name not in errordict??? */ + doref = *epref; + epref = &doref; + /* Push the error object on the operand stack if appropriate. */ + if (!GS_ERROR_IS_INTERRUPT(code)) { + /* Replace the error object if within an oparray or .errorexec. */ + osp++; + if (osp >= ostop) { + *pexit_code = gs_error_Fatal; + return_error(gs_error_Fatal); + } + *osp = *perror_object; + errorexec_find(i_ctx_p, osp); + } + goto again; +} +","@@ -676,7 +676,12 @@ again: + /* Push the error object on the operand stack if appropriate. */ + if (!GS_ERROR_IS_INTERRUPT(code)) { + /* Replace the error object if within an oparray or .errorexec. */ +- *++osp = *perror_object; ++ osp++; ++ if (osp >= ostop) { ++ *pexit_code = gs_error_Fatal; ++ return_error(gs_error_Fatal); ++ } ++ *osp = *perror_object; + errorexec_find(i_ctx_p, osp); + } + goto again;",1906,2237,4096 +7796,"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; +} +",0,"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; +} +","@@ -740,11 +740,11 @@ construct_mac_tlv(struct sc_card *card, unsigned char *apdu_buf, size_t data_tlv + memcpy(mac_tlv + 2, &mac[mac_len - 16], 8); + } + else { +- unsigned char iv[8] = { 0 }; ++ 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, 8); ++ memset(iv, 0x00, sizeof iv); + des_encrypt_cbc(exdata->sk_mac, 8, iv, tmp, 8, mac_tlv + 2); + } + +@@ -903,9 +903,9 @@ epass2003_sm_wrap_apdu(struct sc_card *card, struct sc_apdu *plain, struct sc_ap + * SW12(TLV)=0x99|0x02|SW1+SW2 + * MAC(TLV)=0x8e|0x08|MAC */ + static int +-decrypt_response(struct sc_card *card, unsigned char *in, unsigned char *out, size_t * out_len) ++decrypt_response(struct sc_card *card, unsigned char *in, size_t inlen, unsigned char *out, size_t * out_len) + { +- size_t in_len; ++ size_t cipher_len; + size_t i; + unsigned char iv[16] = { 0 }; + unsigned char plaintext[4096] = { 0 }; +@@ -922,37 +922,40 @@ decrypt_response(struct sc_card *card, unsigned char *in, unsigned char *out, si + + /* parse cipher length */ + if (0x01 == in[2] && 0x82 != in[1]) { +- in_len = in[1]; ++ cipher_len = in[1]; + i = 3; + } + else if (0x01 == in[3] && 0x81 == in[1]) { +- in_len = in[2]; ++ cipher_len = in[2]; + i = 4; + } + else if (0x01 == in[4] && 0x82 == in[1]) { +- in_len = in[2] * 0x100; +- in_len += in[3]; ++ 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], in_len - 1, plaintext); ++ 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], in_len - 1, plaintext); ++ des3_decrypt_cbc(exdata->sk_enc, 16, iv, &in[i], cipher_len - 1, plaintext); + + /* unpadding */ +- while (0x80 != plaintext[in_len - 2] && (in_len - 2 > 0)) +- in_len--; ++ while (0x80 != plaintext[cipher_len - 2] && (cipher_len - 2 > 0)) ++ cipher_len--; + +- if (2 == in_len) ++ if (2 == cipher_len) + return -1; + +- memcpy(out, plaintext, in_len - 2); +- *out_len = in_len - 2; ++ memcpy(out, plaintext, cipher_len - 2); ++ *out_len = cipher_len - 2; + return 0; + } + +@@ -974,7 +977,7 @@ epass2003_sm_unwrap_apdu(struct sc_card *card, struct sc_apdu *sm, struct sc_apd + r = sc_check_sw(card, sm->sw1, sm->sw2); + if (r == SC_SUCCESS) { + if (exdata->sm) { +- if (0 != decrypt_response(card, sm->resp, plain->resp, &len)) ++ if (0 != decrypt_response(card, sm->resp, sm->resplen, plain->resp, &len)) + return SC_ERROR_CARD_CMD_FAILED; + } + else {",2080,2411,4096 +18333,"static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ + Image + *image; + + MagickBooleanType + has_merged_image, + skip_layers; + + MagickOffsetType + offset; + + MagickSizeType + length; + + MagickBooleanType + status; + + PSDInfo + psd_info; + + register ssize_t + i; + + ssize_t + count; + + unsigned char + *data; + + /* + 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 image header. + */ + image->endian=MSBEndian; + count=ReadBlob(image,4,(unsigned char *) psd_info.signature); + psd_info.version=ReadBlobMSBShort(image); + if ((count == 0) || (LocaleNCompare(psd_info.signature,""8BPS"",4) != 0) || + ((psd_info.version != 1) && (psd_info.version != 2))) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + (void) ReadBlob(image,6,psd_info.reserved); + psd_info.channels=ReadBlobMSBShort(image); + if (psd_info.channels > MaxPSDChannels) + ThrowReaderException(CorruptImageError,""MaximumChannelsExceeded""); + psd_info.rows=ReadBlobMSBLong(image); + psd_info.columns=ReadBlobMSBLong(image); + if ((psd_info.version == 1) && ((psd_info.rows > 30000) || + (psd_info.columns > 30000))) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + psd_info.depth=ReadBlobMSBShort(image); + if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + psd_info.mode=ReadBlobMSBShort(image); + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s"", + (double) psd_info.columns,(double) psd_info.rows,(double) + psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) + psd_info.mode)); + /* + Initialize image. + */ + image->depth=psd_info.depth; + image->columns=psd_info.columns; + image->rows=psd_info.rows; + status=SetImageExtent(image,image->columns,image->rows,exception); + if (status == MagickFalse) + return(DestroyImageList(image)); + if (SetImageBackgroundColor(image,exception) == MagickFalse) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + if (psd_info.mode == LabMode) + SetImageColorspace(image,LabColorspace,exception); + if (psd_info.mode == CMYKMode) + { + SetImageColorspace(image,CMYKColorspace,exception); + image->alpha_trait=psd_info.channels > 4 ? BlendPixelTrait : + UndefinedPixelTrait; + } + else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || + (psd_info.mode == DuotoneMode)) + { + status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536, + exception); + if (status == MagickFalse) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Image colormap allocated""); + SetImageColorspace(image,GRAYColorspace,exception); + image->alpha_trait=psd_info.channels > 1 ? BlendPixelTrait : + UndefinedPixelTrait; + } + else + image->alpha_trait=psd_info.channels > 3 ? BlendPixelTrait : + UndefinedPixelTrait; + /* + Read PSD raster colormap only present for indexed and duotone images. + */ + length=ReadBlobMSBLong(image); + if (length != 0) + { + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" reading colormap""); + if (psd_info.mode == DuotoneMode) + { + /* + Duotone image data; the format of this data is undocumented. + */ + data=(unsigned char *) AcquireQuantumMemory((size_t) length, + sizeof(*data)); + if (data == (unsigned char *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + (void) ReadBlob(image,(size_t) length,data); + data=(unsigned char *) RelinquishMagickMemory(data); + } + else + { + size_t + number_colors; + + /* + Read PSD raster colormap. + */ + number_colors=length/3; + if (number_colors > 65536) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + if (AcquireImageColormap(image,number_colors,exception) == MagickFalse) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + for (i=0; i < (ssize_t) image->colors; i++) + image->colormap[i].red=ScaleCharToQuantum((unsigned char) + ReadBlobByte(image)); + for (i=0; i < (ssize_t) image->colors; i++) + image->colormap[i].green=ScaleCharToQuantum((unsigned char) + ReadBlobByte(image)); + for (i=0; i < (ssize_t) image->colors; i++) + image->colormap[i].blue=ScaleCharToQuantum((unsigned char) + ReadBlobByte(image)); + image->alpha_trait=UndefinedPixelTrait; + } + } + has_merged_image=MagickTrue; + length=ReadBlobMSBLong(image); + if (length != 0) + { + unsigned char + *blocks; + + /* + Image resources block. + */ + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" reading image resource blocks - %.20g bytes"",(double) + ((MagickOffsetType) length)); + blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, + sizeof(*blocks)); + if (blocks == (unsigned char *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + count=ReadBlob(image,(size_t) length,blocks); + if ((count != (ssize_t) length) || + (LocaleNCompare((char *) blocks,""8BIM"",4) != 0)) + { + blocks=(unsigned char *) RelinquishMagickMemory(blocks); + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + } + ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image, + exception); + blocks=(unsigned char *) RelinquishMagickMemory(blocks); + } + /* + Layer and mask block. + */ + length=GetPSDSize(&psd_info,image); + if (length == 8) + { + length=ReadBlobMSBLong(image); + length=ReadBlobMSBLong(image); + } + offset=TellBlob(image); + skip_layers=MagickFalse; + if ((image_info->number_scenes == 1) && (image_info->scene == 0) && + (has_merged_image != MagickFalse)) + { + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" read composite only""); + skip_layers=MagickTrue; + } + if (length == 0) + { + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" image has no layers""); + } + else + { + if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) != + MagickTrue) + { + (void) CloseBlob(image); + image=DestroyImageList(image); + return((Image *) NULL); + } + + /* + Skip the rest of the layer and mask information. + */ + SeekBlob(image,offset+length,SEEK_SET); + } + /* + If we are only ""pinging"" the image, then we're done - so return. + */ + if (image_info->ping != MagickFalse) + { + (void) CloseBlob(image); + return(GetFirstImageInList(image)); + } + /* + Read the precombined layer, present for PSD < 4 compatibility. + */ + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" reading the precombined layer""); + if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1)) + has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image, + &psd_info,exception); + if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) && + (length != 0)) + { + SeekBlob(image,offset,SEEK_SET); + status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception); + if (status != MagickTrue) + { + (void) CloseBlob(image); + image=DestroyImageList(image); + return((Image *) NULL); + } + } + if ((has_merged_image == MagickFalse) && (GetImageListLength(image) > 1)) + { + Image + *merged; + + SetImageAlphaChannel(image,TransparentAlphaChannel,exception); + image->background_color.alpha=TransparentAlpha; + image->background_color.alpha_trait=BlendPixelTrait; + merged=MergeImageLayers(image,FlattenLayer,exception); + ReplaceImageInList(&image,merged); + } + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +",1,"static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ + Image + *image; + + MagickBooleanType + has_merged_image, + skip_layers; + + MagickOffsetType + offset; + + MagickSizeType + length; + + MagickBooleanType + status; + + PSDInfo + psd_info; + + register ssize_t + i; + + ssize_t + count; + + unsigned char + *data; + + /* + 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 image header. + */ + image->endian=MSBEndian; + count=ReadBlob(image,4,(unsigned char *) psd_info.signature); + psd_info.version=ReadBlobMSBShort(image); + if ((count == 0) || (LocaleNCompare(psd_info.signature,""8BPS"",4) != 0) || + ((psd_info.version != 1) && (psd_info.version != 2))) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + (void) ReadBlob(image,6,psd_info.reserved); + psd_info.channels=ReadBlobMSBShort(image); + if (psd_info.channels > MaxPSDChannels) + ThrowReaderException(CorruptImageError,""MaximumChannelsExceeded""); + psd_info.rows=ReadBlobMSBLong(image); + psd_info.columns=ReadBlobMSBLong(image); + if ((psd_info.version == 1) && ((psd_info.rows > 30000) || + (psd_info.columns > 30000))) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + psd_info.depth=ReadBlobMSBShort(image); + if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + psd_info.mode=ReadBlobMSBShort(image); + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s"", + (double) psd_info.columns,(double) psd_info.rows,(double) + psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) + psd_info.mode)); + /* + Initialize image. + */ + image->depth=psd_info.depth; + image->columns=psd_info.columns; + image->rows=psd_info.rows; + status=SetImageExtent(image,image->columns,image->rows,exception); + if (status == MagickFalse) + return(DestroyImageList(image)); + if (SetImageBackgroundColor(image,exception) == MagickFalse) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + if (psd_info.mode == LabMode) + SetImageColorspace(image,LabColorspace,exception); + if (psd_info.mode == CMYKMode) + { + SetImageColorspace(image,CMYKColorspace,exception); + image->alpha_trait=psd_info.channels > 4 ? BlendPixelTrait : + UndefinedPixelTrait; + } + else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || + (psd_info.mode == DuotoneMode)) + { + status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536, + exception); + if (status == MagickFalse) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Image colormap allocated""); + SetImageColorspace(image,GRAYColorspace,exception); + image->alpha_trait=psd_info.channels > 1 ? BlendPixelTrait : + UndefinedPixelTrait; + } + else + image->alpha_trait=psd_info.channels > 3 ? BlendPixelTrait : + UndefinedPixelTrait; + /* + Read PSD raster colormap only present for indexed and duotone images. + */ + length=ReadBlobMSBLong(image); + if (length != 0) + { + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" reading colormap""); + if (psd_info.mode == DuotoneMode) + { + /* + Duotone image data; the format of this data is undocumented. + */ + data=(unsigned char *) AcquireQuantumMemory((size_t) length, + sizeof(*data)); + if (data == (unsigned char *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + (void) ReadBlob(image,(size_t) length,data); + data=(unsigned char *) RelinquishMagickMemory(data); + } + else + { + size_t + number_colors; + + /* + Read PSD raster colormap. + */ + number_colors=length/3; + if (number_colors > 65536) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + if (AcquireImageColormap(image,number_colors,exception) == MagickFalse) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + for (i=0; i < (ssize_t) image->colors; i++) + image->colormap[i].red=ScaleCharToQuantum((unsigned char) + ReadBlobByte(image)); + for (i=0; i < (ssize_t) image->colors; i++) + image->colormap[i].green=ScaleCharToQuantum((unsigned char) + ReadBlobByte(image)); + for (i=0; i < (ssize_t) image->colors; i++) + image->colormap[i].blue=ScaleCharToQuantum((unsigned char) + ReadBlobByte(image)); + image->alpha_trait=UndefinedPixelTrait; + } + } + if ((image->depth == 1) && (image->storage_class != PseudoClass)) + ThrowReaderException(CorruptImageError, ""ImproperImageHeader""); + has_merged_image=MagickTrue; + length=ReadBlobMSBLong(image); + if (length != 0) + { + unsigned char + *blocks; + + /* + Image resources block. + */ + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" reading image resource blocks - %.20g bytes"",(double) + ((MagickOffsetType) length)); + blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, + sizeof(*blocks)); + if (blocks == (unsigned char *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + count=ReadBlob(image,(size_t) length,blocks); + if ((count != (ssize_t) length) || + (LocaleNCompare((char *) blocks,""8BIM"",4) != 0)) + { + blocks=(unsigned char *) RelinquishMagickMemory(blocks); + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + } + ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image, + exception); + blocks=(unsigned char *) RelinquishMagickMemory(blocks); + } + /* + Layer and mask block. + */ + length=GetPSDSize(&psd_info,image); + if (length == 8) + { + length=ReadBlobMSBLong(image); + length=ReadBlobMSBLong(image); + } + offset=TellBlob(image); + skip_layers=MagickFalse; + if ((image_info->number_scenes == 1) && (image_info->scene == 0) && + (has_merged_image != MagickFalse)) + { + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" read composite only""); + skip_layers=MagickTrue; + } + if (length == 0) + { + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" image has no layers""); + } + else + { + if (ReadPSDLayers(image,image_info,&psd_info,skip_layers,exception) != + MagickTrue) + { + (void) CloseBlob(image); + image=DestroyImageList(image); + return((Image *) NULL); + } + + /* + Skip the rest of the layer and mask information. + */ + SeekBlob(image,offset+length,SEEK_SET); + } + /* + If we are only ""pinging"" the image, then we're done - so return. + */ + if (image_info->ping != MagickFalse) + { + (void) CloseBlob(image); + return(GetFirstImageInList(image)); + } + /* + Read the precombined layer, present for PSD < 4 compatibility. + */ + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" reading the precombined layer""); + if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1)) + has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image, + &psd_info,exception); + if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) && + (length != 0)) + { + SeekBlob(image,offset,SEEK_SET); + status=ReadPSDLayers(image,image_info,&psd_info,MagickFalse,exception); + if (status != MagickTrue) + { + (void) CloseBlob(image); + image=DestroyImageList(image); + return((Image *) NULL); + } + } + if ((has_merged_image == MagickFalse) && (GetImageListLength(image) > 1)) + { + Image + *merged; + + SetImageAlphaChannel(image,TransparentAlphaChannel,exception); + image->background_color.alpha=TransparentAlpha; + image->background_color.alpha_trait=BlendPixelTrait; + merged=MergeImageLayers(image,FlattenLayer,exception); + ReplaceImageInList(&image,merged); + } + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +","@@ -1908,6 +1908,8 @@ static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) + image->alpha_trait=UndefinedPixelTrait; + } + } ++ if ((image->depth == 1) && (image->storage_class != PseudoClass)) ++ ThrowReaderException(CorruptImageError, ""ImproperImageHeader""); + has_merged_image=MagickTrue; + length=ReadBlobMSBLong(image); + if (length != 0)",2366,2697,4096 +18178,"MagickExport MagickBooleanType SetImageProperty(Image *image, + const char *property,const char *value,ExceptionInfo *exception) +{ + MagickBooleanType + status; + + MagickStatusType + flags; + + assert(image != (Image *) NULL); + assert(image->signature == MagickCoreSignature); + if (image->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); + if (image->properties == (void *) NULL) + image->properties=NewSplayTree(CompareSplayTreeString, + RelinquishMagickMemory,RelinquishMagickMemory); /* create splay-tree */ + if (value == (const char *) NULL) + return(DeleteImageProperty(image,property)); /* delete if NULL */ + status=MagickTrue; + if (strlen(property) <= 1) + { + /* + Do not 'set' single letter properties - read only shorthand. + */ + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + + /* FUTURE: binary chars or quotes in key should produce a error */ + /* Set attributes with known names or special prefixes + return result is found, or break to set a free form properity + */ + switch (*property) + { +#if 0 /* Percent escape's sets values with this prefix: for later use + Throwing an exception causes this setting to fail */ + case '8': + { + if (LocaleNCompare(""8bim:"",property,5) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + break; + } +#endif + case 'B': + case 'b': + { + if (LocaleCompare(""background"",property) == 0) + { + (void) QueryColorCompliance(value,AllCompliance, + &image->background_color,exception); + /* check for FUTURE: value exception?? */ + /* also add user input to splay tree */ + } + break; /* not an attribute, add as a property */ + } + case 'C': + case 'c': + { + if (LocaleCompare(""channels"",property) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + if (LocaleCompare(""colorspace"",property) == 0) + { + ssize_t + colorspace; + + colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse, + value); + if (colorspace < 0) + return(MagickFalse); /* FUTURE: value exception?? */ + return(SetImageColorspace(image,(ColorspaceType) colorspace,exception)); + } + if (LocaleCompare(""compose"",property) == 0) + { + ssize_t + compose; + + compose=ParseCommandOption(MagickComposeOptions,MagickFalse,value); + if (compose < 0) + return(MagickFalse); /* FUTURE: value exception?? */ + image->compose=(CompositeOperator) compose; + return(MagickTrue); + } + if (LocaleCompare(""compress"",property) == 0) + { + ssize_t + compression; + + compression=ParseCommandOption(MagickCompressOptions,MagickFalse, + value); + if (compression < 0) + return(MagickFalse); /* FUTURE: value exception?? */ + image->compression=(CompressionType) compression; + return(MagickTrue); + } + break; /* not an attribute, add as a property */ + } + case 'D': + case 'd': + { + if (LocaleCompare(""delay"",property) == 0) + { + GeometryInfo + geometry_info; + + flags=ParseGeometry(value,&geometry_info); + if ((flags & GreaterValue) != 0) + { + if (image->delay > (size_t) floor(geometry_info.rho+0.5)) + image->delay=(size_t) floor(geometry_info.rho+0.5); + } + else + if ((flags & LessValue) != 0) + { + if (image->delay < (size_t) floor(geometry_info.rho+0.5)) + image->delay=(ssize_t) + floor(geometry_info.sigma+0.5); + } + else + image->delay=(size_t) floor(geometry_info.rho+0.5); + if ((flags & SigmaValue) != 0) + image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5); + return(MagickTrue); + } + if (LocaleCompare(""delay_units"",property) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + if (LocaleCompare(""density"",property) == 0) + { + GeometryInfo + geometry_info; + + flags=ParseGeometry(value,&geometry_info); + image->resolution.x=geometry_info.rho; + image->resolution.y=geometry_info.sigma; + if ((flags & SigmaValue) == 0) + image->resolution.y=image->resolution.x; + return(MagickTrue); + } + if (LocaleCompare(""depth"",property) == 0) + { + image->depth=StringToUnsignedLong(value); + return(MagickTrue); + } + if (LocaleCompare(""dispose"",property) == 0) + { + ssize_t + dispose; + + dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse,value); + if (dispose < 0) + return(MagickFalse); /* FUTURE: value exception?? */ + image->dispose=(DisposeType) dispose; + return(MagickTrue); + } + break; /* not an attribute, add as a property */ + } +#if 0 /* Percent escape's sets values with this prefix: for later use + Throwing an exception causes this setting to fail */ + case 'E': + case 'e': + { + if (LocaleNCompare(""exif:"",property,5) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + break; /* not an attribute, add as a property */ + } + case 'F': + case 'f': + { + if (LocaleNCompare(""fx:"",property,3) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + break; /* not an attribute, add as a property */ + } +#endif + case 'G': + case 'g': + { + if (LocaleCompare(""gamma"",property) == 0) + { + image->gamma=StringToDouble(value,(char **) NULL); + return(MagickTrue); + } + if (LocaleCompare(""gravity"",property) == 0) + { + ssize_t + gravity; + + gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,value); + if (gravity < 0) + return(MagickFalse); /* FUTURE: value exception?? */ + image->gravity=(GravityType) gravity; + return(MagickTrue); + } + break; /* not an attribute, add as a property */ + } + case 'H': + case 'h': + { + if (LocaleCompare(""height"",property) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + break; /* not an attribute, add as a property */ + } + case 'I': + case 'i': + { + if (LocaleCompare(""intensity"",property) == 0) + { + ssize_t + intensity; + + intensity=ParseCommandOption(MagickIntentOptions,MagickFalse,value); + if (intensity < 0) + return(MagickFalse); + image->intensity=(PixelIntensityMethod) intensity; + return(MagickTrue); + } + if (LocaleCompare(""intent"",property) == 0) + { + ssize_t + rendering_intent; + + rendering_intent=ParseCommandOption(MagickIntentOptions,MagickFalse, + value); + if (rendering_intent < 0) + return(MagickFalse); /* FUTURE: value exception?? */ + image->rendering_intent=(RenderingIntent) rendering_intent; + return(MagickTrue); + } + if (LocaleCompare(""interpolate"",property) == 0) + { + ssize_t + interpolate; + + interpolate=ParseCommandOption(MagickInterpolateOptions,MagickFalse, + value); + if (interpolate < 0) + return(MagickFalse); /* FUTURE: value exception?? */ + image->interpolate=(PixelInterpolateMethod) interpolate; + return(MagickTrue); + } +#if 0 /* Percent escape's sets values with this prefix: for later use + Throwing an exception causes this setting to fail */ + if (LocaleNCompare(""iptc:"",property,5) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } +#endif + break; /* not an attribute, add as a property */ + } + case 'K': + case 'k': + if (LocaleCompare(""kurtosis"",property) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + break; /* not an attribute, add as a property */ + case 'L': + case 'l': + { + if (LocaleCompare(""loop"",property) == 0) + { + image->iterations=StringToUnsignedLong(value); + return(MagickTrue); + } + break; /* not an attribute, add as a property */ + } + case 'M': + case 'm': + if ((LocaleCompare(""magick"",property) == 0) || + (LocaleCompare(""max"",property) == 0) || + (LocaleCompare(""mean"",property) == 0) || + (LocaleCompare(""min"",property) == 0) || + (LocaleCompare(""min"",property) == 0)) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + break; /* not an attribute, add as a property */ + case 'O': + case 'o': + if (LocaleCompare(""opaque"",property) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + break; /* not an attribute, add as a property */ + case 'P': + case 'p': + { + if (LocaleCompare(""page"",property) == 0) + { + char + *geometry; + + geometry=GetPageGeometry(value); + flags=ParseAbsoluteGeometry(geometry,&image->page); + geometry=DestroyString(geometry); + return(MagickTrue); + } +#if 0 /* Percent escape's sets values with this prefix: for later use + Throwing an exception causes this setting to fail */ + if (LocaleNCompare(""pixel:"",property,6) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } +#endif + if (LocaleCompare(""profile"",property) == 0) + { + ImageInfo + *image_info; + + StringInfo + *profile; + + image_info=AcquireImageInfo(); + (void) CopyMagickString(image_info->filename,value,MagickPathExtent); + (void) SetImageInfo(image_info,1,exception); + profile=FileToStringInfo(image_info->filename,~0UL,exception); + if (profile != (StringInfo *) NULL) + status=SetImageProfile(image,image_info->magick,profile,exception); + image_info=DestroyImageInfo(image_info); + return(MagickTrue); + } + break; /* not an attribute, add as a property */ + } + case 'R': + case 'r': + { + if (LocaleCompare(""rendering-intent"",property) == 0) + { + ssize_t + rendering_intent; + + rendering_intent=ParseCommandOption(MagickIntentOptions,MagickFalse, + value); + if (rendering_intent < 0) + return(MagickFalse); /* FUTURE: value exception?? */ + image->rendering_intent=(RenderingIntent) rendering_intent; + return(MagickTrue); + } + break; /* not an attribute, add as a property */ + } + case 'S': + case 's': + if ((LocaleCompare(""size"",property) == 0) || + (LocaleCompare(""skewness"",property) == 0) || + (LocaleCompare(""scenes"",property) == 0) || + (LocaleCompare(""standard-deviation"",property) == 0)) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + break; /* not an attribute, add as a property */ + case 'T': + case 't': + { + if (LocaleCompare(""tile-offset"",property) == 0) + { + char + *geometry; + + geometry=GetPageGeometry(value); + flags=ParseAbsoluteGeometry(geometry,&image->tile_offset); + geometry=DestroyString(geometry); + return(MagickTrue); + } + break; /* not an attribute, add as a property */ + } + case 'U': + case 'u': + { + if (LocaleCompare(""units"",property) == 0) + { + ssize_t + units; + + units=ParseCommandOption(MagickResolutionOptions,MagickFalse,value); + if (units < 0) + return(MagickFalse); /* FUTURE: value exception?? */ + image->units=(ResolutionType) units; + return(MagickTrue); + } + break; /* not an attribute, add as a property */ + } + case 'V': + case 'v': + { + if (LocaleCompare(""version"",property) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + break; /* not an attribute, add as a property */ + } + case 'W': + case 'w': + { + if (LocaleCompare(""width"",property) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + break; /* not an attribute, add as a property */ + } +#if 0 /* Percent escape's sets values with this prefix: for later use + Throwing an exception causes this setting to fail */ + case 'X': + case 'x': + { + if (LocaleNCompare(""xmp:"",property,4) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + break; /* not an attribute, add as a property */ + } +#endif + } + /* Default: not an attribute, add as a property */ + status=AddValueToSplayTree((SplayTreeInfo *) image->properties, + ConstantString(property),ConstantString(value)); + /* FUTURE: error if status is bad? */ + return(status); +} +",1,"MagickExport MagickBooleanType SetImageProperty(Image *image, + const char *property,const char *value,ExceptionInfo *exception) +{ + MagickBooleanType + status; + + MagickStatusType + flags; + + assert(image != (Image *) NULL); + assert(image->signature == MagickCoreSignature); + if (image->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); + if (image->properties == (void *) NULL) + image->properties=NewSplayTree(CompareSplayTreeString, + RelinquishMagickMemory,RelinquishMagickMemory); /* create splay-tree */ + if (value == (const char *) NULL) + return(DeleteImageProperty(image,property)); /* delete if NULL */ + status=MagickTrue; + if (strlen(property) <= 1) + { + /* + Do not 'set' single letter properties - read only shorthand. + */ + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + + /* FUTURE: binary chars or quotes in key should produce a error */ + /* Set attributes with known names or special prefixes + return result is found, or break to set a free form properity + */ + switch (*property) + { +#if 0 /* Percent escape's sets values with this prefix: for later use + Throwing an exception causes this setting to fail */ + case '8': + { + if (LocaleNCompare(""8bim:"",property,5) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + break; + } +#endif + case 'B': + case 'b': + { + if (LocaleCompare(""background"",property) == 0) + { + (void) QueryColorCompliance(value,AllCompliance, + &image->background_color,exception); + /* check for FUTURE: value exception?? */ + /* also add user input to splay tree */ + } + break; /* not an attribute, add as a property */ + } + case 'C': + case 'c': + { + if (LocaleCompare(""channels"",property) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + if (LocaleCompare(""colorspace"",property) == 0) + { + ssize_t + colorspace; + + colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse, + value); + if (colorspace < 0) + return(MagickFalse); /* FUTURE: value exception?? */ + return(SetImageColorspace(image,(ColorspaceType) colorspace,exception)); + } + if (LocaleCompare(""compose"",property) == 0) + { + ssize_t + compose; + + compose=ParseCommandOption(MagickComposeOptions,MagickFalse,value); + if (compose < 0) + return(MagickFalse); /* FUTURE: value exception?? */ + image->compose=(CompositeOperator) compose; + return(MagickTrue); + } + if (LocaleCompare(""compress"",property) == 0) + { + ssize_t + compression; + + compression=ParseCommandOption(MagickCompressOptions,MagickFalse, + value); + if (compression < 0) + return(MagickFalse); /* FUTURE: value exception?? */ + image->compression=(CompressionType) compression; + return(MagickTrue); + } + break; /* not an attribute, add as a property */ + } + case 'D': + case 'd': + { + if (LocaleCompare(""delay"",property) == 0) + { + GeometryInfo + geometry_info; + + flags=ParseGeometry(value,&geometry_info); + if ((flags & GreaterValue) != 0) + { + if (image->delay > (size_t) floor(geometry_info.rho+0.5)) + image->delay=(size_t) floor(geometry_info.rho+0.5); + } + else + if ((flags & LessValue) != 0) + { + if (image->delay < (size_t) floor(geometry_info.rho+0.5)) + image->delay=(ssize_t) + floor(geometry_info.sigma+0.5); + } + else + image->delay=(size_t) floor(geometry_info.rho+0.5); + if ((flags & SigmaValue) != 0) + image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5); + return(MagickTrue); + } + if (LocaleCompare(""delay_units"",property) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + if (LocaleCompare(""density"",property) == 0) + { + GeometryInfo + geometry_info; + + flags=ParseGeometry(value,&geometry_info); + image->resolution.x=geometry_info.rho; + image->resolution.y=geometry_info.sigma; + if ((flags & SigmaValue) == 0) + image->resolution.y=image->resolution.x; + return(MagickTrue); + } + if (LocaleCompare(""depth"",property) == 0) + { + image->depth=StringToUnsignedLong(value); + return(MagickTrue); + } + if (LocaleCompare(""dispose"",property) == 0) + { + ssize_t + dispose; + + dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse,value); + if (dispose < 0) + return(MagickFalse); /* FUTURE: value exception?? */ + image->dispose=(DisposeType) dispose; + return(MagickTrue); + } + break; /* not an attribute, add as a property */ + } +#if 0 /* Percent escape's sets values with this prefix: for later use + Throwing an exception causes this setting to fail */ + case 'E': + case 'e': + { + if (LocaleNCompare(""exif:"",property,5) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + break; /* not an attribute, add as a property */ + } + case 'F': + case 'f': + { + if (LocaleNCompare(""fx:"",property,3) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + break; /* not an attribute, add as a property */ + } +#endif + case 'G': + case 'g': + { + if (LocaleCompare(""gamma"",property) == 0) + { + image->gamma=StringToDouble(value,(char **) NULL); + return(MagickTrue); + } + if (LocaleCompare(""gravity"",property) == 0) + { + ssize_t + gravity; + + gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,value); + if (gravity < 0) + return(MagickFalse); /* FUTURE: value exception?? */ + image->gravity=(GravityType) gravity; + return(MagickTrue); + } + break; /* not an attribute, add as a property */ + } + case 'H': + case 'h': + { + if (LocaleCompare(""height"",property) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + break; /* not an attribute, add as a property */ + } + case 'I': + case 'i': + { + if (LocaleCompare(""intensity"",property) == 0) + { + ssize_t + intensity; + + intensity=ParseCommandOption(MagickIntentOptions,MagickFalse,value); + if (intensity < 0) + return(MagickFalse); + image->intensity=(PixelIntensityMethod) intensity; + return(MagickTrue); + } + if (LocaleCompare(""intent"",property) == 0) + { + ssize_t + rendering_intent; + + rendering_intent=ParseCommandOption(MagickIntentOptions,MagickFalse, + value); + if (rendering_intent < 0) + return(MagickFalse); /* FUTURE: value exception?? */ + image->rendering_intent=(RenderingIntent) rendering_intent; + return(MagickTrue); + } + if (LocaleCompare(""interpolate"",property) == 0) + { + ssize_t + interpolate; + + interpolate=ParseCommandOption(MagickInterpolateOptions,MagickFalse, + value); + if (interpolate < 0) + return(MagickFalse); /* FUTURE: value exception?? */ + image->interpolate=(PixelInterpolateMethod) interpolate; + return(MagickTrue); + } +#if 0 /* Percent escape's sets values with this prefix: for later use + Throwing an exception causes this setting to fail */ + if (LocaleNCompare(""iptc:"",property,5) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } +#endif + break; /* not an attribute, add as a property */ + } + case 'K': + case 'k': + if (LocaleCompare(""kurtosis"",property) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + break; /* not an attribute, add as a property */ + case 'L': + case 'l': + { + if (LocaleCompare(""loop"",property) == 0) + { + image->iterations=StringToUnsignedLong(value); + return(MagickTrue); + } + break; /* not an attribute, add as a property */ + } + case 'M': + case 'm': + if ((LocaleCompare(""magick"",property) == 0) || + (LocaleCompare(""max"",property) == 0) || + (LocaleCompare(""mean"",property) == 0) || + (LocaleCompare(""min"",property) == 0) || + (LocaleCompare(""min"",property) == 0)) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + break; /* not an attribute, add as a property */ + case 'O': + case 'o': + if (LocaleCompare(""opaque"",property) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + break; /* not an attribute, add as a property */ + case 'P': + case 'p': + { + if (LocaleCompare(""page"",property) == 0) + { + char + *geometry; + + geometry=GetPageGeometry(value); + flags=ParseAbsoluteGeometry(geometry,&image->page); + geometry=DestroyString(geometry); + return(MagickTrue); + } +#if 0 /* Percent escape's sets values with this prefix: for later use + Throwing an exception causes this setting to fail */ + if (LocaleNCompare(""pixel:"",property,6) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } +#endif + if (LocaleCompare(""profile"",property) == 0) + { + ImageInfo + *image_info; + + StringInfo + *profile; + + image_info=AcquireImageInfo(); + (void) CopyMagickString(image_info->filename,value,MagickPathExtent); + (void) SetImageInfo(image_info,1,exception); + profile=FileToStringInfo(image_info->filename,~0UL,exception); + if (profile != (StringInfo *) NULL) + status=SetImageProfile(image,image_info->magick,profile,exception); + image_info=DestroyImageInfo(image_info); + return(MagickTrue); + } + break; /* not an attribute, add as a property */ + } + case 'R': + case 'r': + { + if (LocaleCompare(""rendering-intent"",property) == 0) + { + ssize_t + rendering_intent; + + rendering_intent=ParseCommandOption(MagickIntentOptions,MagickFalse, + value); + if (rendering_intent < 0) + return(MagickFalse); /* FUTURE: value exception?? */ + image->rendering_intent=(RenderingIntent) rendering_intent; + return(MagickTrue); + } + break; /* not an attribute, add as a property */ + } + case 'S': + case 's': + if ((LocaleCompare(""size"",property) == 0) || + (LocaleCompare(""skewness"",property) == 0) || + (LocaleCompare(""scenes"",property) == 0) || + (LocaleCompare(""standard-deviation"",property) == 0)) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + break; /* not an attribute, add as a property */ + case 'T': + case 't': + { + if (LocaleCompare(""tile-offset"",property) == 0) + { + char + *geometry; + + geometry=GetPageGeometry(value); + flags=ParseAbsoluteGeometry(geometry,&image->tile_offset); + geometry=DestroyString(geometry); + return(MagickTrue); + } + break; /* not an attribute, add as a property */ + } + case 'U': + case 'u': + { + if (LocaleCompare(""units"",property) == 0) + { + ssize_t + units; + + units=ParseCommandOption(MagickResolutionOptions,MagickFalse,value); + if (units < 0) + return(MagickFalse); /* FUTURE: value exception?? */ + image->units=(ResolutionType) units; + return(MagickTrue); + } + break; /* not an attribute, add as a property */ + } + case 'V': + case 'v': + { + if (LocaleCompare(""version"",property) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + break; /* not an attribute, add as a property */ + } + case 'W': + case 'w': + { + if (LocaleCompare(""width"",property) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + break; /* not an attribute, add as a property */ + } +#if 0 /* Percent escape's sets values with this prefix: for later use + Throwing an exception causes this setting to fail */ + case 'X': + case 'x': + { + if (LocaleNCompare(""xmp:"",property,4) == 0) + { + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse); + } + break; /* not an attribute, add as a property */ + } +#endif + } + /* Default: not an attribute, add as a property */ + status=AddValueToSplayTree((SplayTreeInfo *) image->properties, + ConstantString(property),ConstantString(value)); + /* FUTURE: error if status is bad? */ + return(status); +} +","@@ -213,7 +213,7 @@ MagickExport MagickBooleanType CloneImageProperties(Image *image, + % + % DefineImageProperty() associates an assignment string of the form + % ""key=value"" with an artifact or options. It is equivelent to +-% SetImageProperty() ++% SetImageProperty(). + % + % The format of the DefineImageProperty method is: + % +@@ -3962,7 +3962,7 @@ MagickExport MagickBooleanType SetImageProperty(Image *image, + { + /* + Do not 'set' single letter properties - read only shorthand. +- */ ++ */ + (void) ThrowMagickException(exception,GetMagickModule(),OptionError, + ""SetReadOnlyProperty"",""`%s'"",property); + return(MagickFalse);",3591,3922,4096 +18113," _WM_ParseNewHmi(uint8_t *hmi_data, uint32_t hmi_size) { + uint32_t hmi_tmp = 0; + uint8_t *hmi_base = hmi_data; + uint16_t hmi_bpm = 0; + uint16_t hmi_division = 0; + + uint32_t *hmi_track_offset = NULL; + uint32_t i = 0; + uint32_t j = 0; + uint8_t *hmi_addr = NULL; + uint32_t *hmi_track_header_length = NULL; + struct _mdi *hmi_mdi = NULL; + uint32_t tempo_f = 5000000.0; + uint32_t *hmi_track_end = NULL; + uint8_t hmi_tracks_ended = 0; + uint8_t *hmi_running_event = NULL; + uint32_t setup_ret = 0; + uint32_t *hmi_delta = NULL; + + uint32_t smallest_delta = 0; + uint32_t subtract_delta = 0; + + uint32_t sample_count = 0; + float sample_count_f = 0; + float sample_remainder = 0; + + float samples_per_delta_f = 0.0; + + struct _note { + uint32_t length; + uint8_t channel; + } *note; + + UNUSED(hmi_size); + + if (memcmp(hmi_data, ""HMI-MIDISONG061595"", 18)) { + _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, NULL, 0); + return NULL; + } + + hmi_bpm = hmi_data[212]; + + hmi_division = 60; + + hmi_track_cnt = hmi_data[228]; + + hmi_mdi = _WM_initMDI(); + + _WM_midi_setup_divisions(hmi_mdi, hmi_division); + + if ((_WM_MixerOptions & WM_MO_ROUNDTEMPO)) { + tempo_f = (float) (60000000 / hmi_bpm) + 0.5f; + } else { + tempo_f = (float) (60000000 / hmi_bpm); + } + samples_per_delta_f = _WM_GetSamplesPerTick(hmi_division, (uint32_t)tempo_f); + + _WM_midi_setup_tempo(hmi_mdi, (uint32_t)tempo_f); + + hmi_track_offset = (uint32_t *)malloc(sizeof(uint32_t) * hmi_track_cnt); + hmi_track_header_length = malloc(sizeof(uint32_t) * hmi_track_cnt); + hmi_track_end = malloc(sizeof(uint32_t) * hmi_track_cnt); + hmi_delta = malloc(sizeof(uint32_t) * hmi_track_cnt); + note = malloc(sizeof(struct _note) * 128 * hmi_track_cnt); + hmi_running_event = malloc(sizeof(uint8_t) * 128 * hmi_track_cnt); + + hmi_data += 370; + + smallest_delta = 0xffffffff; + + if (hmi_size < (370 + (hmi_track_cnt * 17))) { + _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, ""file too short"", 0); + goto _hmi_end; + } + + hmi_track_offset[0] = *hmi_data; // To keep Xcode happy + + for (i = 0; i < hmi_track_cnt; i++) { + hmi_track_offset[i] = *hmi_data++; + hmi_track_offset[i] += (*hmi_data++ << 8); + hmi_track_offset[i] += (*hmi_data++ << 16); + hmi_track_offset[i] += (*hmi_data++ << 24); + + if (hmi_size < (hmi_track_offset[i] + 0x5a + 4)) { + _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, ""file too short"", 0); + goto _hmi_end; + } + + hmi_addr = hmi_base + hmi_track_offset[i]; + + if (memcmp(hmi_addr, ""HMI-MIDITRACK"", 13)) { + _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, NULL, 0); + goto _hmi_end; + } + + hmi_track_header_length[i] = hmi_addr[0x57]; + hmi_track_header_length[i] += (hmi_addr[0x58] << 8); + hmi_track_header_length[i] += (hmi_addr[0x59] << 16); + hmi_track_header_length[i] += (hmi_addr[0x5a] << 24); + + hmi_addr += hmi_track_header_length[i]; + hmi_track_offset[i] += hmi_track_header_length[i]; + + hmi_delta[i] = 0; + if (*hmi_addr > 0x7f) { + do { + hmi_delta[i] = (hmi_delta[i] << 7) + (*hmi_addr & 0x7f); + hmi_addr++; + hmi_track_offset[i]++; + } while (*hmi_addr > 0x7f); + } + hmi_delta[i] = (hmi_delta[i] << 7) + (*hmi_addr & 0x7f); + hmi_track_offset[i]++; + hmi_addr++; + + if (hmi_delta[i] < smallest_delta) { + smallest_delta = hmi_delta[i]; + } + + hmi_track_end[i] = 0; + hmi_running_event[i] = 0; + + for (j = 0; j < 128; j++) { + hmi_tmp = (128 * i) + j; + note[hmi_tmp].length = 0; + note[hmi_tmp].channel = 0; + } + } + + subtract_delta = smallest_delta; + sample_count_f= (((float) smallest_delta * samples_per_delta_f) + sample_remainder); + + sample_count = (uint32_t) sample_count_f; + sample_remainder = sample_count_f - (float) sample_count; + + hmi_mdi->events[hmi_mdi->event_count - 1].samples_to_next += sample_count; + hmi_mdi->extra_info.approx_total_samples += sample_count; + + while (hmi_tracks_ended < hmi_track_cnt) { + smallest_delta = 0; + for (i = 0; i < hmi_track_cnt; i++) { + if (hmi_track_end[i]) continue; + + for (j = 0; j < 128; j++) { + hmi_tmp = (128 * i) + j; + if (note[hmi_tmp].length) { + note[hmi_tmp].length -= subtract_delta; + if (note[hmi_tmp].length) { + if ((!smallest_delta) || (smallest_delta > note[hmi_tmp].length)) { + smallest_delta = note[hmi_tmp].length; + } + } else { + _WM_midi_setup_noteoff(hmi_mdi, note[hmi_tmp].channel, j, 0); + } + } + } + + if (hmi_delta[i]) { + hmi_delta[i] -= subtract_delta; + if (hmi_delta[i]) { + if ((!smallest_delta) || (smallest_delta > hmi_delta[i])) { + smallest_delta = hmi_delta[i]; + } + continue; + } + } + + do { + hmi_data = hmi_base + hmi_track_offset[i]; + hmi_delta[i] = 0; + + if (hmi_data[0] == 0xfe) { + if (hmi_data[1] == 0x10) { + hmi_tmp = (hmi_data[4] + 5); + hmi_data += hmi_tmp; + hmi_track_offset[i] += hmi_tmp; + } else if (hmi_data[1] == 0x15) { + hmi_data += 4; + hmi_track_offset[i] += 4; + } + hmi_data += 4; + hmi_track_offset[i] += 4; + } else { + if ((setup_ret = _WM_SetupMidiEvent(hmi_mdi,hmi_data,hmi_running_event[i])) == 0) { + goto _hmi_end; + } + if ((hmi_data[0] == 0xff) && (hmi_data[1] == 0x2f) && (hmi_data[2] == 0x00)) { + hmi_track_end[i] = 1; + hmi_tracks_ended++; + for(j = 0; j < 128; j++) { + hmi_tmp = (128 * i) + j; + if (note[hmi_tmp].length) { + _WM_midi_setup_noteoff(hmi_mdi, note[hmi_tmp].channel, j, 0); + note[hmi_tmp].length = 0; + } + } + goto _hmi_next_track; + } + if ((*hmi_data == 0xF0) || (*hmi_data == 0xF7)) { + hmi_running_event[i] = 0; + } else if (*hmi_data < 0xF0) { + if (*hmi_data >= 0x80) { + hmi_running_event[i] = *hmi_data; + } + } + if ((hmi_running_event[i] & 0xf0) == 0x90) { + if (*hmi_data > 127) { + hmi_tmp = hmi_data[1]; + } else { + hmi_tmp = *hmi_data; + } + hmi_tmp += (i * 128); + + note[hmi_tmp].channel = hmi_running_event[i] & 0xf; + + hmi_data += setup_ret; + hmi_track_offset[i] += setup_ret; + + note[hmi_tmp].length = 0; + if (*hmi_data > 0x7f) { + do { + note[hmi_tmp].length = (note[hmi_tmp].length << 7) | (*hmi_data & 0x7F); + hmi_data++; + hmi_track_offset[i]++; + } while (*hmi_data > 0x7F); + } + note[hmi_tmp].length = (note[hmi_tmp].length << 7) | (*hmi_data & 0x7F); + hmi_data++; + hmi_track_offset[i]++; + + if (note[hmi_tmp].length) { + if ((!smallest_delta) || (smallest_delta > note[hmi_tmp].length)) { + smallest_delta = note[hmi_tmp].length; + } + } else { + _WM_midi_setup_noteoff(hmi_mdi, note[hmi_tmp].channel, j, 0); + } + + } else { + hmi_data += setup_ret; + hmi_track_offset[i] += setup_ret; + } + } + + if (*hmi_data > 0x7f) { + do { + hmi_delta[i] = (hmi_delta[i] << 7) | (*hmi_data & 0x7F); + hmi_data++; + hmi_track_offset[i]++; + } while (*hmi_data > 0x7F); + } + hmi_delta[i] = (hmi_delta[i] << 7) | (*hmi_data & 0x7F); + hmi_data++; + hmi_track_offset[i]++; + } while (!hmi_delta[i]); + if ((!smallest_delta) || (smallest_delta > hmi_delta[i])) { + smallest_delta = hmi_delta[i]; + } + + _hmi_next_track: + hmi_tmp = 0; + UNUSED(hmi_tmp); + } + + subtract_delta = smallest_delta; + sample_count_f= (((float) smallest_delta * samples_per_delta_f) + sample_remainder); + + sample_count = (uint32_t) sample_count_f; + sample_remainder = sample_count_f - (float) sample_count; + + hmi_mdi->events[hmi_mdi->event_count - 1].samples_to_next += sample_count; + hmi_mdi->extra_info.approx_total_samples += sample_count; + } + + if ((hmi_mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width, _WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy)) == NULL) { + _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, ""to init reverb"", 0); + goto _hmi_end; + } + + hmi_mdi->extra_info.current_sample = 0; + hmi_mdi->current_event = &hmi_mdi->events[0]; + hmi_mdi->samples_to_mix = 0; + hmi_mdi->note = NULL; + + _WM_ResetToStart(hmi_mdi); + +_hmi_end: + free(hmi_track_offset); + free(hmi_track_header_length); + free(hmi_track_end); + free(hmi_delta); + free(note); + free(hmi_running_event); + + if (hmi_mdi->reverb) return (hmi_mdi); + _WM_freeMDI(hmi_mdi); + return 0; +} +",1," _WM_ParseNewHmi(uint8_t *hmi_data, uint32_t hmi_size) { + uint32_t hmi_tmp = 0; + uint8_t *hmi_base = hmi_data; + uint32_t data_siz; + uint16_t hmi_bpm = 0; + uint16_t hmi_division = 0; + + uint32_t *hmi_track_offset = NULL; + uint32_t i = 0; + uint32_t j = 0; + uint8_t *hmi_addr = NULL; + uint32_t *hmi_track_header_length = NULL; + struct _mdi *hmi_mdi = NULL; + uint32_t tempo_f = 5000000.0; + uint32_t *hmi_track_end = NULL; + uint8_t hmi_tracks_ended = 0; + uint8_t *hmi_running_event = NULL; + uint32_t setup_ret = 0; + uint32_t *hmi_delta = NULL; + + uint32_t smallest_delta = 0; + uint32_t subtract_delta = 0; + + uint32_t sample_count = 0; + float sample_count_f = 0; + float sample_remainder = 0; + + float samples_per_delta_f = 0.0; + + struct _note { + uint32_t length; + uint8_t channel; + } *note; + + + if (memcmp(hmi_data, ""HMI-MIDISONG061595"", 18)) { + _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, NULL, 0); + return NULL; + } + + hmi_bpm = hmi_data[212]; + + hmi_division = 60; + + hmi_track_cnt = hmi_data[228]; + + hmi_mdi = _WM_initMDI(); + + _WM_midi_setup_divisions(hmi_mdi, hmi_division); + + if ((_WM_MixerOptions & WM_MO_ROUNDTEMPO)) { + tempo_f = (float) (60000000 / hmi_bpm) + 0.5f; + } else { + tempo_f = (float) (60000000 / hmi_bpm); + } + samples_per_delta_f = _WM_GetSamplesPerTick(hmi_division, (uint32_t)tempo_f); + + _WM_midi_setup_tempo(hmi_mdi, (uint32_t)tempo_f); + + hmi_track_offset = (uint32_t *)malloc(sizeof(uint32_t) * hmi_track_cnt); + hmi_track_header_length = malloc(sizeof(uint32_t) * hmi_track_cnt); + hmi_track_end = malloc(sizeof(uint32_t) * hmi_track_cnt); + hmi_delta = malloc(sizeof(uint32_t) * hmi_track_cnt); + note = malloc(sizeof(struct _note) * 128 * hmi_track_cnt); + hmi_running_event = malloc(sizeof(uint8_t) * 128 * hmi_track_cnt); + + hmi_data += 370; + + smallest_delta = 0xffffffff; + + if (hmi_size < (370 + (hmi_track_cnt * 17))) { + _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, ""file too short"", 0); + goto _hmi_end; + } + + hmi_track_offset[0] = *hmi_data; // To keep Xcode happy + + for (i = 0; i < hmi_track_cnt; i++) { + hmi_track_offset[i] = *hmi_data++; + hmi_track_offset[i] += (*hmi_data++ << 8); + hmi_track_offset[i] += (*hmi_data++ << 16); + hmi_track_offset[i] += (*hmi_data++ << 24); + + if (hmi_size < (hmi_track_offset[i] + 0x5a + 4)) { + _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, ""file too short"", 0); + goto _hmi_end; + } + + hmi_addr = hmi_base + hmi_track_offset[i]; + + if (memcmp(hmi_addr, ""HMI-MIDITRACK"", 13)) { + _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, NULL, 0); + goto _hmi_end; + } + + hmi_track_header_length[i] = hmi_addr[0x57]; + hmi_track_header_length[i] += (hmi_addr[0x58] << 8); + hmi_track_header_length[i] += (hmi_addr[0x59] << 16); + hmi_track_header_length[i] += (hmi_addr[0x5a] << 24); + + hmi_addr += hmi_track_header_length[i]; + hmi_track_offset[i] += hmi_track_header_length[i]; + + hmi_delta[i] = 0; + if (*hmi_addr > 0x7f) { + do { + hmi_delta[i] = (hmi_delta[i] << 7) + (*hmi_addr & 0x7f); + hmi_addr++; + hmi_track_offset[i]++; + } while (*hmi_addr > 0x7f); + } + hmi_delta[i] = (hmi_delta[i] << 7) + (*hmi_addr & 0x7f); + hmi_track_offset[i]++; + hmi_addr++; + + if (hmi_delta[i] < smallest_delta) { + smallest_delta = hmi_delta[i]; + } + + hmi_track_end[i] = 0; + hmi_running_event[i] = 0; + + for (j = 0; j < 128; j++) { + hmi_tmp = (128 * i) + j; + note[hmi_tmp].length = 0; + note[hmi_tmp].channel = 0; + } + } + + subtract_delta = smallest_delta; + sample_count_f= (((float) smallest_delta * samples_per_delta_f) + sample_remainder); + + sample_count = (uint32_t) sample_count_f; + sample_remainder = sample_count_f - (float) sample_count; + + hmi_mdi->events[hmi_mdi->event_count - 1].samples_to_next += sample_count; + hmi_mdi->extra_info.approx_total_samples += sample_count; + + while (hmi_tracks_ended < hmi_track_cnt) { + smallest_delta = 0; + for (i = 0; i < hmi_track_cnt; i++) { + if (hmi_track_end[i]) continue; + + for (j = 0; j < 128; j++) { + hmi_tmp = (128 * i) + j; + if (note[hmi_tmp].length) { + note[hmi_tmp].length -= subtract_delta; + if (note[hmi_tmp].length) { + if ((!smallest_delta) || (smallest_delta > note[hmi_tmp].length)) { + smallest_delta = note[hmi_tmp].length; + } + } else { + _WM_midi_setup_noteoff(hmi_mdi, note[hmi_tmp].channel, j, 0); + } + } + } + + if (hmi_delta[i]) { + hmi_delta[i] -= subtract_delta; + if (hmi_delta[i]) { + if ((!smallest_delta) || (smallest_delta > hmi_delta[i])) { + smallest_delta = hmi_delta[i]; + } + continue; + } + } + + do { + hmi_data = hmi_base + hmi_track_offset[i]; + hmi_delta[i] = 0; + if (hmi_track_offset[i] >= hmi_size) { + _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, ""file too short"", 0); + goto _hmi_end; + } + data_siz = hmi_size - hmi_track_offset[i]; + + if (hmi_data[0] == 0xfe) { + if (hmi_data[1] == 0x10) { + hmi_tmp = (hmi_data[4] + 5); + hmi_data += hmi_tmp; + hmi_track_offset[i] += hmi_tmp; + hmi_tmp += 4; + } else if (hmi_data[1] == 0x15) { + hmi_data += 4; + hmi_track_offset[i] += 4; + hmi_tmp = 8; + } else { + hmi_tmp = 4; + } + hmi_data += 4; + hmi_track_offset[i] += 4; + if (hmi_tmp > data_siz) { + _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, ""file too short"", 0); + goto _hmi_end; + } + data_siz -= hmi_tmp; + } else { + if ((setup_ret = _WM_SetupMidiEvent(hmi_mdi,hmi_data,data_siz,hmi_running_event[i])) == 0) { + goto _hmi_end; + } + if ((hmi_data[0] == 0xff) && (hmi_data[1] == 0x2f) && (hmi_data[2] == 0x00)) { + hmi_track_end[i] = 1; + hmi_tracks_ended++; + for(j = 0; j < 128; j++) { + hmi_tmp = (128 * i) + j; + if (note[hmi_tmp].length) { + _WM_midi_setup_noteoff(hmi_mdi, note[hmi_tmp].channel, j, 0); + note[hmi_tmp].length = 0; + } + } + goto _hmi_next_track; + } + if ((*hmi_data == 0xF0) || (*hmi_data == 0xF7)) { + hmi_running_event[i] = 0; + } else if (*hmi_data < 0xF0) { + if (*hmi_data >= 0x80) { + hmi_running_event[i] = *hmi_data; + } + } + if ((hmi_running_event[i] & 0xf0) == 0x90) { + if (*hmi_data > 127) { + hmi_tmp = hmi_data[1]; + } else { + hmi_tmp = *hmi_data; + } + hmi_tmp += (i * 128); + + note[hmi_tmp].channel = hmi_running_event[i] & 0xf; + + hmi_data += setup_ret; + hmi_track_offset[i] += setup_ret; + data_siz -= setup_ret; + + note[hmi_tmp].length = 0; + if (data_siz && *hmi_data > 0x7f) { + do { + if (!data_siz) break; + note[hmi_tmp].length = (note[hmi_tmp].length << 7) | (*hmi_data & 0x7F); + hmi_data++; + data_siz--; + hmi_track_offset[i]++; + } while (*hmi_data > 0x7F); + } + if (!data_siz) { + _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, ""file too short"", 0); + goto _hmi_end; + } + note[hmi_tmp].length = (note[hmi_tmp].length << 7) | (*hmi_data & 0x7F); + hmi_data++; + data_siz--; + hmi_track_offset[i]++; + + if (note[hmi_tmp].length) { + if ((!smallest_delta) || (smallest_delta > note[hmi_tmp].length)) { + smallest_delta = note[hmi_tmp].length; + } + } else { + _WM_midi_setup_noteoff(hmi_mdi, note[hmi_tmp].channel, j, 0); + } + + } else { + hmi_data += setup_ret; + hmi_track_offset[i] += setup_ret; + data_siz -= setup_ret; + } + } + + if (data_siz && *hmi_data > 0x7f) { + do { + if (!data_siz) break; + hmi_delta[i] = (hmi_delta[i] << 7) | (*hmi_data & 0x7F); + hmi_data++; + data_siz--; + hmi_track_offset[i]++; + } while (*hmi_data > 0x7F); + } + if (!data_siz) { + _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, ""file too short"", 0); + goto _hmi_end; + } + hmi_delta[i] = (hmi_delta[i] << 7) | (*hmi_data & 0x7F); + hmi_data++; + data_siz--; + hmi_track_offset[i]++; + } while (!hmi_delta[i]); + if ((!smallest_delta) || (smallest_delta > hmi_delta[i])) { + smallest_delta = hmi_delta[i]; + } + + _hmi_next_track: + hmi_tmp = 0; + UNUSED(hmi_tmp); + } + + subtract_delta = smallest_delta; + sample_count_f= (((float) smallest_delta * samples_per_delta_f) + sample_remainder); + + sample_count = (uint32_t) sample_count_f; + sample_remainder = sample_count_f - (float) sample_count; + + hmi_mdi->events[hmi_mdi->event_count - 1].samples_to_next += sample_count; + hmi_mdi->extra_info.approx_total_samples += sample_count; + } + + if ((hmi_mdi->reverb = _WM_init_reverb(_WM_SampleRate, _WM_reverb_room_width, _WM_reverb_room_length, _WM_reverb_listen_posx, _WM_reverb_listen_posy)) == NULL) { + _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_MEM, ""to init reverb"", 0); + goto _hmi_end; + } + + hmi_mdi->extra_info.current_sample = 0; + hmi_mdi->current_event = &hmi_mdi->events[0]; + hmi_mdi->samples_to_mix = 0; + hmi_mdi->note = NULL; + + _WM_ResetToStart(hmi_mdi); + +_hmi_end: + free(hmi_track_offset); + free(hmi_track_header_length); + free(hmi_track_end); + free(hmi_delta); + free(note); + free(hmi_running_event); + + if (hmi_mdi->reverb) return (hmi_mdi); + _WM_freeMDI(hmi_mdi); + return 0; +} +","@@ -42,10 +42,10 @@ struct _mdi * + _WM_ParseNewHmi(uint8_t *hmi_data, uint32_t hmi_size) { + uint32_t hmi_tmp = 0; + uint8_t *hmi_base = hmi_data; ++ uint32_t data_siz; + uint16_t hmi_bpm = 0; + uint16_t hmi_division = 0; + +-// uint32_t hmi_duration_secs = 0; + uint32_t hmi_track_cnt = 0; + uint32_t *hmi_track_offset = NULL; + uint32_t i = 0; +@@ -74,8 +74,6 @@ _WM_ParseNewHmi(uint8_t *hmi_data, uint32_t hmi_size) { + uint8_t channel; + } *note; + +- //FIXME: This needs to be used for sanity check. +- UNUSED(hmi_size); + + if (memcmp(hmi_data, ""HMI-MIDISONG061595"", 18)) { + _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, NULL, 0); +@@ -216,21 +214,35 @@ _WM_ParseNewHmi(uint8_t *hmi_data, uint32_t hmi_size) { + do { + hmi_data = hmi_base + hmi_track_offset[i]; + hmi_delta[i] = 0; ++ if (hmi_track_offset[i] >= hmi_size) { ++ _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, ""file too short"", 0); ++ goto _hmi_end; ++ } ++ data_siz = hmi_size - hmi_track_offset[i]; + + if (hmi_data[0] == 0xfe) { + // HMI only event of some sort. + if (hmi_data[1] == 0x10) { + hmi_tmp = (hmi_data[4] + 5); + hmi_data += hmi_tmp; + hmi_track_offset[i] += hmi_tmp; ++ hmi_tmp += 4; + } else if (hmi_data[1] == 0x15) { + hmi_data += 4; + hmi_track_offset[i] += 4; ++ hmi_tmp = 8; ++ } else { ++ hmi_tmp = 4; + } + hmi_data += 4; + hmi_track_offset[i] += 4; ++ if (hmi_tmp > data_siz) { ++ _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, ""file too short"", 0); ++ goto _hmi_end; ++ } ++ data_siz -= hmi_tmp; + } else { +- if ((setup_ret = _WM_SetupMidiEvent(hmi_mdi,hmi_data,hmi_running_event[i])) == 0) { ++ if ((setup_ret = _WM_SetupMidiEvent(hmi_mdi,hmi_data,data_siz,hmi_running_event[i])) == 0) { + goto _hmi_end; + } + if ((hmi_data[0] == 0xff) && (hmi_data[1] == 0x2f) && (hmi_data[2] == 0x00)) { +@@ -269,17 +281,25 @@ _WM_ParseNewHmi(uint8_t *hmi_data, uint32_t hmi_size) { + + hmi_data += setup_ret; + hmi_track_offset[i] += setup_ret; ++ data_siz -= setup_ret; + + note[hmi_tmp].length = 0; +- if (*hmi_data > 0x7f) { ++ if (data_siz && *hmi_data > 0x7f) { + do { ++ if (!data_siz) break; + note[hmi_tmp].length = (note[hmi_tmp].length << 7) | (*hmi_data & 0x7F); + hmi_data++; ++ data_siz--; + hmi_track_offset[i]++; + } while (*hmi_data > 0x7F); + } ++ if (!data_siz) { ++ _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, ""file too short"", 0); ++ goto _hmi_end; ++ } + note[hmi_tmp].length = (note[hmi_tmp].length << 7) | (*hmi_data & 0x7F); + hmi_data++; ++ data_siz--; + hmi_track_offset[i]++; + + if (note[hmi_tmp].length) { +@@ -293,20 +313,28 @@ _WM_ParseNewHmi(uint8_t *hmi_data, uint32_t hmi_size) { + } else { + hmi_data += setup_ret; + hmi_track_offset[i] += setup_ret; ++ data_siz -= setup_ret; + } + } + + // get track delta + // hmi_delta[i] = 0; // set at start of loop +- if (*hmi_data > 0x7f) { ++ if (data_siz && *hmi_data > 0x7f) { + do { ++ if (!data_siz) break; + hmi_delta[i] = (hmi_delta[i] << 7) | (*hmi_data & 0x7F); + hmi_data++; ++ data_siz--; + hmi_track_offset[i]++; + } while (*hmi_data > 0x7F); + } ++ if (!data_siz) { ++ _WM_GLOBAL_ERROR(__FUNCTION__, __LINE__, WM_ERR_NOT_HMI, ""file too short"", 0); ++ goto _hmi_end; ++ } + hmi_delta[i] = (hmi_delta[i] << 7) | (*hmi_data & 0x7F); + hmi_data++; ++ data_siz--; + hmi_track_offset[i]++; + } while (!hmi_delta[i]); + if ((!smallest_delta) || (smallest_delta > hmi_delta[i])) {",2992,3323,4096 +5170,"zisofs_read_data(struct archive_read *a, + const void **buff, size_t *size, int64_t *offset) +{ + struct iso9660 *iso9660; + struct zisofs *zisofs; + const unsigned char *p; + size_t avail; + ssize_t bytes_read; + size_t uncompressed_size; + int r; + + iso9660 = (struct iso9660 *)(a->format->data); + zisofs = &iso9660->entry_zisofs; + + p = __archive_read_ahead(a, 1, &bytes_read); + if (bytes_read <= 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + ""Truncated zisofs file body""); + return (ARCHIVE_FATAL); + } + if (bytes_read > iso9660->entry_bytes_remaining) + bytes_read = (ssize_t)iso9660->entry_bytes_remaining; + avail = bytes_read; + uncompressed_size = 0; + + if (!zisofs->initialized) { + size_t ceil, xsize; + + /* Allocate block pointers buffer. */ + ceil = (size_t)((zisofs->pz_uncompressed_size + + (((int64_t)1) << zisofs->pz_log2_bs) - 1) + >> zisofs->pz_log2_bs); + xsize = (ceil + 1) * 4; + if (zisofs->block_pointers_alloc < xsize) { + size_t alloc; + + if (zisofs->block_pointers != NULL) + free(zisofs->block_pointers); + alloc = ((xsize >> 10) + 1) << 10; + zisofs->block_pointers = malloc(alloc); + if (zisofs->block_pointers == NULL) { + archive_set_error(&a->archive, ENOMEM, + ""No memory for zisofs decompression""); + return (ARCHIVE_FATAL); + } + zisofs->block_pointers_alloc = alloc; + } + zisofs->block_pointers_size = xsize; + + /* Allocate uncompressed data buffer. */ + xsize = (size_t)1UL << zisofs->pz_log2_bs; + if (zisofs->uncompressed_buffer_size < xsize) { + if (zisofs->uncompressed_buffer != NULL) + free(zisofs->uncompressed_buffer); + zisofs->uncompressed_buffer = malloc(xsize); + if (zisofs->uncompressed_buffer == NULL) { + archive_set_error(&a->archive, ENOMEM, + ""No memory for zisofs decompression""); + return (ARCHIVE_FATAL); + } + } + zisofs->uncompressed_buffer_size = xsize; + + /* + * Read the file header, and check the magic code of zisofs. + */ + if (zisofs->header_avail < sizeof(zisofs->header)) { + xsize = sizeof(zisofs->header) - zisofs->header_avail; + if (avail < xsize) + xsize = avail; + memcpy(zisofs->header + zisofs->header_avail, p, xsize); + zisofs->header_avail += xsize; + avail -= xsize; + p += xsize; + } + if (!zisofs->header_passed && + zisofs->header_avail == sizeof(zisofs->header)) { + int err = 0; + + if (memcmp(zisofs->header, zisofs_magic, + sizeof(zisofs_magic)) != 0) + err = 1; + if (archive_le32dec(zisofs->header + 8) + != zisofs->pz_uncompressed_size) + err = 1; + if (zisofs->header[12] != 4) + err = 1; + if (zisofs->header[13] != zisofs->pz_log2_bs) + err = 1; + if (err) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + ""Illegal zisofs file body""); + return (ARCHIVE_FATAL); + } + zisofs->header_passed = 1; + } + /* + * Read block pointers. + */ + if (zisofs->header_passed && + zisofs->block_pointers_avail < zisofs->block_pointers_size) { + xsize = zisofs->block_pointers_size + - zisofs->block_pointers_avail; + if (avail < xsize) + xsize = avail; + memcpy(zisofs->block_pointers + + zisofs->block_pointers_avail, p, xsize); + zisofs->block_pointers_avail += xsize; + avail -= xsize; + p += xsize; + if (zisofs->block_pointers_avail + == zisofs->block_pointers_size) { + /* We've got all block pointers and initialize + * related variables. */ + zisofs->block_off = 0; + zisofs->block_avail = 0; + /* Complete a initialization */ + zisofs->initialized = 1; + } + } + + if (!zisofs->initialized) + goto next_data; /* We need more data. */ + } + + /* + * Get block offsets from block pointers. + */ + if (zisofs->block_avail == 0) { + uint32_t bst, bed; + + if (zisofs->block_off + 4 >= zisofs->block_pointers_size) { + /* There isn't a pair of offsets. */ + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + ""Illegal zisofs block pointers""); + return (ARCHIVE_FATAL); + } + bst = archive_le32dec( + zisofs->block_pointers + zisofs->block_off); + if (bst != zisofs->pz_offset + (bytes_read - avail)) { + /* TODO: Should we seek offset of current file + * by bst ? */ + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + ""Illegal zisofs block pointers(cannot seek)""); + return (ARCHIVE_FATAL); + } + bed = archive_le32dec( + zisofs->block_pointers + zisofs->block_off + 4); + if (bed < bst) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + ""Illegal zisofs block pointers""); + return (ARCHIVE_FATAL); + } + zisofs->block_avail = bed - bst; + zisofs->block_off += 4; + + /* Initialize compression library for new block. */ + if (zisofs->stream_valid) + r = inflateReset(&zisofs->stream); + else + r = inflateInit(&zisofs->stream); + if (r != Z_OK) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + ""Can't initialize zisofs decompression.""); + return (ARCHIVE_FATAL); + } + zisofs->stream_valid = 1; + zisofs->stream.total_in = 0; + zisofs->stream.total_out = 0; + } + + /* + * Make uncompressed data. + */ + if (zisofs->block_avail == 0) { + memset(zisofs->uncompressed_buffer, 0, + zisofs->uncompressed_buffer_size); + uncompressed_size = zisofs->uncompressed_buffer_size; + } else { + zisofs->stream.next_in = (Bytef *)(uintptr_t)(const void *)p; + if (avail > zisofs->block_avail) + zisofs->stream.avail_in = zisofs->block_avail; + else + zisofs->stream.avail_in = (uInt)avail; + zisofs->stream.next_out = zisofs->uncompressed_buffer; + zisofs->stream.avail_out = + (uInt)zisofs->uncompressed_buffer_size; + + r = inflate(&zisofs->stream, 0); + switch (r) { + case Z_OK: /* Decompressor made some progress.*/ + case Z_STREAM_END: /* Found end of stream. */ + break; + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + ""zisofs decompression failed (%d)"", r); + return (ARCHIVE_FATAL); + } + uncompressed_size = + zisofs->uncompressed_buffer_size - zisofs->stream.avail_out; + avail -= zisofs->stream.next_in - p; + zisofs->block_avail -= (uint32_t)(zisofs->stream.next_in - p); + } +next_data: + bytes_read -= avail; + *buff = zisofs->uncompressed_buffer; + *size = uncompressed_size; + *offset = iso9660->entry_sparse_offset; + iso9660->entry_sparse_offset += uncompressed_size; + iso9660->entry_bytes_remaining -= bytes_read; + iso9660->current_position += bytes_read; + zisofs->pz_offset += (uint32_t)bytes_read; + iso9660->entry_bytes_unconsumed += bytes_read; + + return (ARCHIVE_OK); +} +",0,"zisofs_read_data(struct archive_read *a, + const void **buff, size_t *size, int64_t *offset) +{ + struct iso9660 *iso9660; + struct zisofs *zisofs; + const unsigned char *p; + size_t avail; + ssize_t bytes_read; + size_t uncompressed_size; + int r; + + iso9660 = (struct iso9660 *)(a->format->data); + zisofs = &iso9660->entry_zisofs; + + p = __archive_read_ahead(a, 1, &bytes_read); + if (bytes_read <= 0) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, + ""Truncated zisofs file body""); + return (ARCHIVE_FATAL); + } + if (bytes_read > iso9660->entry_bytes_remaining) + bytes_read = (ssize_t)iso9660->entry_bytes_remaining; + avail = bytes_read; + uncompressed_size = 0; + + if (!zisofs->initialized) { + size_t ceil, xsize; + + /* Allocate block pointers buffer. */ + ceil = (size_t)((zisofs->pz_uncompressed_size + + (((int64_t)1) << zisofs->pz_log2_bs) - 1) + >> zisofs->pz_log2_bs); + xsize = (ceil + 1) * 4; + if (zisofs->block_pointers_alloc < xsize) { + size_t alloc; + + if (zisofs->block_pointers != NULL) + free(zisofs->block_pointers); + alloc = ((xsize >> 10) + 1) << 10; + zisofs->block_pointers = malloc(alloc); + if (zisofs->block_pointers == NULL) { + archive_set_error(&a->archive, ENOMEM, + ""No memory for zisofs decompression""); + return (ARCHIVE_FATAL); + } + zisofs->block_pointers_alloc = alloc; + } + zisofs->block_pointers_size = xsize; + + /* Allocate uncompressed data buffer. */ + xsize = (size_t)1UL << zisofs->pz_log2_bs; + if (zisofs->uncompressed_buffer_size < xsize) { + if (zisofs->uncompressed_buffer != NULL) + free(zisofs->uncompressed_buffer); + zisofs->uncompressed_buffer = malloc(xsize); + if (zisofs->uncompressed_buffer == NULL) { + archive_set_error(&a->archive, ENOMEM, + ""No memory for zisofs decompression""); + return (ARCHIVE_FATAL); + } + } + zisofs->uncompressed_buffer_size = xsize; + + /* + * Read the file header, and check the magic code of zisofs. + */ + if (zisofs->header_avail < sizeof(zisofs->header)) { + xsize = sizeof(zisofs->header) - zisofs->header_avail; + if (avail < xsize) + xsize = avail; + memcpy(zisofs->header + zisofs->header_avail, p, xsize); + zisofs->header_avail += xsize; + avail -= xsize; + p += xsize; + } + if (!zisofs->header_passed && + zisofs->header_avail == sizeof(zisofs->header)) { + int err = 0; + + if (memcmp(zisofs->header, zisofs_magic, + sizeof(zisofs_magic)) != 0) + err = 1; + if (archive_le32dec(zisofs->header + 8) + != zisofs->pz_uncompressed_size) + err = 1; + if (zisofs->header[12] != 4) + err = 1; + if (zisofs->header[13] != zisofs->pz_log2_bs) + err = 1; + if (err) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + ""Illegal zisofs file body""); + return (ARCHIVE_FATAL); + } + zisofs->header_passed = 1; + } + /* + * Read block pointers. + */ + if (zisofs->header_passed && + zisofs->block_pointers_avail < zisofs->block_pointers_size) { + xsize = zisofs->block_pointers_size + - zisofs->block_pointers_avail; + if (avail < xsize) + xsize = avail; + memcpy(zisofs->block_pointers + + zisofs->block_pointers_avail, p, xsize); + zisofs->block_pointers_avail += xsize; + avail -= xsize; + p += xsize; + if (zisofs->block_pointers_avail + == zisofs->block_pointers_size) { + /* We've got all block pointers and initialize + * related variables. */ + zisofs->block_off = 0; + zisofs->block_avail = 0; + /* Complete a initialization */ + zisofs->initialized = 1; + } + } + + if (!zisofs->initialized) + goto next_data; /* We need more data. */ + } + + /* + * Get block offsets from block pointers. + */ + if (zisofs->block_avail == 0) { + uint32_t bst, bed; + + if (zisofs->block_off + 4 >= zisofs->block_pointers_size) { + /* There isn't a pair of offsets. */ + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + ""Illegal zisofs block pointers""); + return (ARCHIVE_FATAL); + } + bst = archive_le32dec( + zisofs->block_pointers + zisofs->block_off); + if (bst != zisofs->pz_offset + (bytes_read - avail)) { + /* TODO: Should we seek offset of current file + * by bst ? */ + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + ""Illegal zisofs block pointers(cannot seek)""); + return (ARCHIVE_FATAL); + } + bed = archive_le32dec( + zisofs->block_pointers + zisofs->block_off + 4); + if (bed < bst) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_FILE_FORMAT, + ""Illegal zisofs block pointers""); + return (ARCHIVE_FATAL); + } + zisofs->block_avail = bed - bst; + zisofs->block_off += 4; + + /* Initialize compression library for new block. */ + if (zisofs->stream_valid) + r = inflateReset(&zisofs->stream); + else + r = inflateInit(&zisofs->stream); + if (r != Z_OK) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + ""Can't initialize zisofs decompression.""); + return (ARCHIVE_FATAL); + } + zisofs->stream_valid = 1; + zisofs->stream.total_in = 0; + zisofs->stream.total_out = 0; + } + + /* + * Make uncompressed data. + */ + if (zisofs->block_avail == 0) { + memset(zisofs->uncompressed_buffer, 0, + zisofs->uncompressed_buffer_size); + uncompressed_size = zisofs->uncompressed_buffer_size; + } else { + zisofs->stream.next_in = (Bytef *)(uintptr_t)(const void *)p; + if (avail > zisofs->block_avail) + zisofs->stream.avail_in = zisofs->block_avail; + else + zisofs->stream.avail_in = (uInt)avail; + zisofs->stream.next_out = zisofs->uncompressed_buffer; + zisofs->stream.avail_out = + (uInt)zisofs->uncompressed_buffer_size; + + r = inflate(&zisofs->stream, 0); + switch (r) { + case Z_OK: /* Decompressor made some progress.*/ + case Z_STREAM_END: /* Found end of stream. */ + break; + default: + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + ""zisofs decompression failed (%d)"", r); + return (ARCHIVE_FATAL); + } + uncompressed_size = + zisofs->uncompressed_buffer_size - zisofs->stream.avail_out; + avail -= zisofs->stream.next_in - p; + zisofs->block_avail -= (uint32_t)(zisofs->stream.next_in - p); + } +next_data: + bytes_read -= avail; + *buff = zisofs->uncompressed_buffer; + *size = uncompressed_size; + *offset = iso9660->entry_sparse_offset; + iso9660->entry_sparse_offset += uncompressed_size; + iso9660->entry_bytes_remaining -= bytes_read; + iso9660->current_position += bytes_read; + zisofs->pz_offset += (uint32_t)bytes_read; + iso9660->entry_bytes_unconsumed += bytes_read; + + return (ARCHIVE_OK); +} +","@@ -1091,7 +1091,7 @@ choose_volume(struct archive_read *a, struct iso9660 *iso9660) + /* This condition is unlikely; by way of caution. */ + vd = &(iso9660->joliet); + +- skipsize = LOGICAL_BLOCK_SIZE * vd->location; ++ skipsize = LOGICAL_BLOCK_SIZE * (int64_t)vd->location; + skipsize = __archive_read_consume(a, skipsize); + if (skipsize < 0) + return ((int)skipsize); +@@ -1129,7 +1129,7 @@ choose_volume(struct archive_read *a, struct iso9660 *iso9660) + && iso9660->seenJoliet) { + /* Switch reading data from primary to joliet. */ + vd = &(iso9660->joliet); +- skipsize = LOGICAL_BLOCK_SIZE * vd->location; ++ skipsize = LOGICAL_BLOCK_SIZE * (int64_t)vd->location; + skipsize -= iso9660->current_position; + skipsize = __archive_read_consume(a, skipsize); + if (skipsize < 0)",2069,2400,4096 +18227,"static bool r_bin_mdmp_init_directory_entry(struct r_bin_mdmp_obj *obj, struct minidump_directory *entry) { + int i; + + struct minidump_handle_operation_list *handle_operation_list; + struct minidump_memory_list *memory_list; + struct minidump_memory64_list *memory64_list; + struct minidump_memory_info_list *memory_info_list; + struct minidump_module_list *module_list; + struct minidump_thread_list *thread_list; + struct minidump_thread_ex_list *thread_ex_list; + struct minidump_thread_info_list *thread_info_list; + struct minidump_unloaded_module_list *unloaded_module_list; + + struct avrf_handle_operation *handle_operations; + struct minidump_memory_descriptor *memories; + struct minidump_memory_descriptor64 *memories64; + struct minidump_memory_info *memory_infos; + struct minidump_module *modules; + struct minidump_thread *threads; + struct minidump_thread_ex *ex_threads; + struct minidump_thread_info *thread_infos; + struct minidump_unloaded_module *unloaded_modules; + + /* We could confirm data sizes but a malcious MDMP will always get around + ** this! But we can ensure that the data is not outside of the file */ + if (entry->location.rva + entry->location.data_size > obj->b->length) { + eprintf(""[ERROR] Size Mismatch - Stream data is larger than file size!\n""); + return false; + } + + switch (entry->stream_type) { + case THREAD_LIST_STREAM: + thread_list = (struct minidump_thread_list *)(obj->b->buf + entry->location.rva); + + sdb_set (obj->kv, ""mdmp_thread.format"", ""ddddq?? "" + ""ThreadId SuspendCount PriorityClass Priority "" + ""Teb (mdmp_memory_descriptor)Stack "" + ""(mdmp_location_descriptor)ThreadContext"", 0); + sdb_num_set (obj->kv, ""mdmp_thread_list.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_thread_list.format"", + sdb_fmt (""d[%i]? "" + ""NumberOfThreads (mdmp_thread)Threads"", + thread_list->number_of_threads), + 0); + + /* TODO: Not yet fully parsed or utilised */ + for (i = 0; i < thread_list->number_of_threads; i++) { + threads = (struct minidump_thread *)(&(thread_list->threads)); + r_list_append (obj->streams.threads, &(threads[i])); + } + break; + case MODULE_LIST_STREAM: + module_list = (struct minidump_module_list *)(obj->b->buf + entry->location.rva); + + sdb_set (obj->kv, ""mdmp_module.format"", ""qddtd???qq "" + ""BaseOfImage SizeOfImage CheckSum "" + ""TimeDateStamp ModuleNameRVA "" + ""(mdmp_vs_fixedfileinfo)VersionInfo "" + ""(mdmp_location_descriptor)CvRecord "" + ""(mdmp_location_descriptor)MiscRecord "" + ""Reserved0 Reserved1"", 0); + sdb_num_set (obj->kv, ""mdmp_module_list.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_module_list.format"", + sdb_fmt (""d[%i]? "" + ""NumberOfModule (mdmp_module)Modules"", + module_list->number_of_modules, + 0), + 0); + + for (i = 0; i < module_list->number_of_modules; i++) { + modules = (struct minidump_module *)(&(module_list->modules)); + r_list_append(obj->streams.modules, &(modules[i])); + } + break; + case MEMORY_LIST_STREAM: + memory_list = (struct minidump_memory_list *)(obj->b->buf + entry->location.rva); + + sdb_num_set (obj->kv, ""mdmp_memory_list.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_memory_list.format"", + sdb_fmt (""d[%i]? "" + ""NumberOfMemoryRanges "" + ""(mdmp_memory_descriptor)MemoryRanges "", + memory_list->number_of_memory_ranges, + 0), + 0); + + for (i = 0; i < memory_list->number_of_memory_ranges; i++) { + memories = (struct minidump_memory_descriptor *)(&(memory_list->memory_ranges)); + r_list_append (obj->streams.memories, &(memories[i])); + } + break; + case EXCEPTION_STREAM: + /* TODO: Not yet fully parsed or utilised */ + obj->streams.exception = (struct minidump_exception_stream *)(obj->b->buf + entry->location.rva); + + sdb_set (obj->kv, ""mdmp_exception.format"", ""[4]E[4]Eqqdd[15]q "" + ""(mdmp_exception_code)ExceptionCode "" + ""(mdmp_exception_flags)ExceptionFlags "" + ""ExceptionRecord ExceptionAddress "" + ""NumberParameters __UnusedAlignment "" + ""ExceptionInformation"", 0); + sdb_num_set (obj->kv, ""mdmp_exception_stream.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_exception_stream.format"", ""dd?? "" + ""ThreadId __Alignment "" + ""(mdmp_exception)ExceptionRecord "" + ""(mdmp_location_descriptor)ThreadContext"", 0); + + break; + case SYSTEM_INFO_STREAM: + obj->streams.system_info = (struct minidump_system_info *)(obj->b->buf + entry->location.rva); + + sdb_num_set (obj->kv, ""mdmp_system_info.offset"", + entry->location.rva, 0); + /* TODO: We need E as a byte! */ + sdb_set (obj->kv, ""mdmp_system_info.format"", ""[2]EwwbBddd[4]Ed[2]Ew[2]q "" + ""(mdmp_processor_architecture)ProcessorArchitecture "" + ""ProcessorLevel ProcessorRevision NumberOfProcessors "" + ""(mdmp_product_type)ProductType "" + ""MajorVersion MinorVersion BuildNumber (mdmp_platform_id)PlatformId "" + ""CsdVersionRva (mdmp_suite_mask)SuiteMask Reserved2 ProcessorFeatures"", 0); + + break; + case THREAD_EX_LIST_STREAM: + /* TODO: Not yet fully parsed or utilised */ + thread_ex_list = (struct minidump_thread_ex_list *)(obj->b->buf + entry->location.rva); + + sdb_set (obj->kv, ""mdmp_thread_ex.format"", ""ddddq??? "" + ""ThreadId SuspendCount PriorityClass Priority "" + ""Teb (mdmp_memory_descriptor)Stack "" + ""(mdmp_location_descriptor)ThreadContext "" + ""(mdmp_memory_descriptor)BackingStore"", 0); + sdb_num_set (obj->kv, ""mdmp_thread_ex_list.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_thread_ex_list.format"", + sdb_fmt (""d[%i]? NumberOfThreads "" + ""(mdmp_thread_ex)Threads"", + thread_ex_list->number_of_threads, 0), + 0); + + for (i = 0; i < thread_ex_list->number_of_threads; i++) { + ex_threads = (struct minidump_thread_ex *)(&(thread_ex_list->threads)); + r_list_append (obj->streams.ex_threads, &(ex_threads[i])); + } + break; + case MEMORY_64_LIST_STREAM: + memory64_list = (struct minidump_memory64_list *)(obj->b->buf + entry->location.rva); + + sdb_num_set (obj->kv, ""mdmp_memory64_list.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_memory64_list.format"", + sdb_fmt (""qq[%i]? NumberOfMemoryRanges "" + ""BaseRva "" + ""(mdmp_memory_descriptor64)MemoryRanges"", + memory64_list->number_of_memory_ranges), + 0); + + obj->streams.memories64.base_rva = memory64_list->base_rva; + for (i = 0; i < memory64_list->number_of_memory_ranges; i++) { + memories64 = (struct minidump_memory_descriptor64 *)(&(memory64_list->memory_ranges)); + r_list_append (obj->streams.memories64.memories, &(memories64[i])); + } + break; + case COMMENT_STREAM_A: + /* TODO: Not yet fully parsed or utilised */ + obj->streams.comments_a = obj->b->buf + entry->location.rva; + + sdb_num_set (obj->kv, ""mdmp_comment_stream_a.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_comment_stream_a.format"", + ""s CommentA"", 0); + + break; + case COMMENT_STREAM_W: + /* TODO: Not yet fully parsed or utilised */ + obj->streams.comments_w = obj->b->buf + entry->location.rva; + + sdb_num_set (obj->kv, ""mdmp_comment_stream_w.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_comment_stream_w.format"", + ""s CommentW"", 0); + + break; + case HANDLE_DATA_STREAM: + /* TODO: Not yet fully parsed or utilised */ + obj->streams.handle_data = (struct minidump_handle_data_stream *)(obj->b->buf + entry->location.rva); + + sdb_num_set (obj->kv, ""mdmp_handle_data_stream.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_handle_data_stream.format"", ""dddd "" + ""SizeOfHeader SizeOfDescriptor "" + ""NumberOfDescriptors Reserved"", 0); + break; + case FUNCTION_TABLE_STREAM: + /* TODO: Not yet fully parsed or utilised */ + obj->streams.function_table = (struct minidump_function_table_stream *)(obj->b->buf + entry->location.rva); + + sdb_num_set (obj->kv, ""mdmp_function_table_stream.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_function_table_stream.format"", ""dddddd "" + ""SizeOfHeader SizeOfDescriptor SizeOfNativeDescriptor "" + ""SizeOfFunctionEntry NumberOfDescriptors SizeOfAlignPad"", + 0); + break; + case UNLOADED_MODULE_LIST_STREAM: + /* TODO: Not yet fully parsed or utilised */ + unloaded_module_list = (struct minidump_unloaded_module_list *)(obj->b->buf + entry->location.rva); + + sdb_set (obj->kv, ""mdmp_unloaded_module.format"", ""qddtd "" + ""BaseOfImage SizeOfImage CheckSum TimeDateStamp "" + ""ModuleNameRva"", 0); + sdb_num_set (obj->kv, ""mdmp_unloaded_module_list.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_unloaded_module_list.format"", ""ddd "" + ""SizeOfHeader SizeOfEntry NumberOfEntries"", 0); + + for (i = 0; i < unloaded_module_list->number_of_entries; i++) { + unloaded_modules = (struct minidump_unloaded_module *)((ut8 *)&unloaded_module_list + sizeof (struct minidump_unloaded_module_list)); + r_list_append (obj->streams.unloaded_modules, &(unloaded_modules[i])); + } + break; + case MISC_INFO_STREAM: + /* TODO: Not yet fully parsed or utilised */ + obj->streams.misc_info.misc_info_1 = (struct minidump_misc_info *)(obj->b->buf + entry->location.rva); + + /* TODO: Handle different sizes */ + sdb_num_set (obj->kv, ""mdmp_misc_info.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_misc_info.format"", ""d[4]Bdtttddddd "" + ""SizeOfInfo (mdmp_misc1_flags)Flags1 ProcessId "" + ""ProcessCreateTime ProcessUserTime ProcessKernelTime "" + ""ProcessorMaxMhz ProcessorCurrentMhz "" + ""ProcessorMhzLimit ProcessorMaxIdleState "" + ""ProcessorCurrentIdleState"", 0); + + break; + case MEMORY_INFO_LIST_STREAM: + memory_info_list = (struct minidump_memory_info_list *)(obj->b->buf + entry->location.rva); + + sdb_set (obj->kv, ""mdmp_memory_info.format"", + ""qq[4]Edq[4]E[4]E[4]Ed BaseAddress AllocationBase "" + ""(mdmp_page_protect)AllocationProtect __Alignment1 RegionSize "" + ""(mdmp_mem_state)State (mdmp_page_protect)Protect "" + ""(mdmp_mem_type)Type __Alignment2"", 0); + sdb_num_set (obj->kv, ""mdmp_memory_info_list.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_memory_info_list.format"", + sdb_fmt (""ddq[%i]? SizeOfHeader SizeOfEntry "" + ""NumberOfEntries (mdmp_memory_info)MemoryInfo"", + memory_info_list->number_of_entries), + 0); + + for (i = 0; i < memory_info_list->number_of_entries; i++) { + memory_infos = (struct minidump_memory_info *)((ut8 *)memory_info_list + sizeof (struct minidump_memory_info_list)); + r_list_append (obj->streams.memory_infos, &(memory_infos[i])); + } + break; + case THREAD_INFO_LIST_STREAM: + /* TODO: Not yet fully parsed or utilised */ + thread_info_list = (struct minidump_thread_info_list *)(obj->b->buf + entry->location.rva); + + sdb_set (obj->kv, ""mdmp_thread_info.format"", ""ddddttttqq "" + ""ThreadId DumpFlags DumpError ExitStatus CreateTime "" + ""ExitTime KernelTime UserTime StartAddress Affinity"", + 0); + sdb_num_set (obj->kv, ""mdmp_thread_info_list.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_thread_info_list.format"", ""ddd "" + ""SizeOfHeader SizeOfEntry NumberOfEntries"", 0); + + for (i = 0; i < thread_info_list->number_of_entries; i++) { + thread_infos = (struct minidump_thread_info *)((ut8 *)thread_info_list + sizeof (struct minidump_thread_info_list)); + r_list_append (obj->streams.thread_infos, &(thread_infos[i])); + } + break; + case HANDLE_OPERATION_LIST_STREAM: + /* TODO: Not yet fully parsed or utilised */ + handle_operation_list = (struct minidump_handle_operation_list *)(obj->b->buf + entry->location.rva); + + sdb_num_set (obj->kv, ""mdmp_handle_operation_list.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_handle_operation_list.format"", ""dddd "" + ""SizeOfHeader SizeOfEntry NumberOfEntries Reserved"", 0); + + for (i = 0; i < handle_operation_list->number_of_entries; i++) { + handle_operations = (struct avrf_handle_operation *)((ut8 *)handle_operation_list + sizeof (struct minidump_handle_operation_list)); + r_list_append (obj->streams.operations, &(handle_operations[i])); + } + + break; + case LAST_RESERVED_STREAM: + /* TODO: Not yet fully parsed or utilised */ + break; + case UNUSED_STREAM: + case RESERVED_STREAM_0: + case RESERVED_STREAM_1: + /* Silently ignore reserved streams */ + break; + default: + eprintf (""[WARN] Invalid or unsupported enumeration encountered %i\n"", entry->stream_type); + return false; + } + return true; +} +",1,"static bool r_bin_mdmp_init_directory_entry(struct r_bin_mdmp_obj *obj, struct minidump_directory *entry) { + int i; + + struct minidump_handle_operation_list *handle_operation_list; + struct minidump_memory_list *memory_list; + struct minidump_memory64_list *memory64_list; + struct minidump_memory_info_list *memory_info_list; + struct minidump_module_list *module_list; + struct minidump_thread_list *thread_list; + struct minidump_thread_ex_list *thread_ex_list; + struct minidump_thread_info_list *thread_info_list; + struct minidump_unloaded_module_list *unloaded_module_list; + + struct avrf_handle_operation *handle_operations; + struct minidump_memory_descriptor *memories; + struct minidump_memory_descriptor64 *memories64; + struct minidump_memory_info *memory_infos; + struct minidump_module *modules; + struct minidump_thread *threads; + struct minidump_thread_ex *ex_threads; + struct minidump_thread_info *thread_infos; + struct minidump_unloaded_module *unloaded_modules; + + /* We could confirm data sizes but a malcious MDMP will always get around + ** this! But we can ensure that the data is not outside of the file */ + if (entry->location.rva + entry->location.data_size > obj->b->length) { + eprintf (""[ERROR] Size Mismatch - Stream data is larger than file size!\n""); + return false; + } + + switch (entry->stream_type) { + case THREAD_LIST_STREAM: + thread_list = (struct minidump_thread_list *)(obj->b->buf + entry->location.rva); + + sdb_set (obj->kv, ""mdmp_thread.format"", ""ddddq?? "" + ""ThreadId SuspendCount PriorityClass Priority "" + ""Teb (mdmp_memory_descriptor)Stack "" + ""(mdmp_location_descriptor)ThreadContext"", 0); + sdb_num_set (obj->kv, ""mdmp_thread_list.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_thread_list.format"", + sdb_fmt (""d[%i]? "" + ""NumberOfThreads (mdmp_thread)Threads"", + thread_list->number_of_threads), + 0); + + /* TODO: Not yet fully parsed or utilised */ + for (i = 0; i < thread_list->number_of_threads; i++) { + threads = (struct minidump_thread *)(&(thread_list->threads)); + r_list_append (obj->streams.threads, &(threads[i])); + } + break; + case MODULE_LIST_STREAM: + module_list = (struct minidump_module_list *)(obj->b->buf + entry->location.rva); + + sdb_set (obj->kv, ""mdmp_module.format"", ""qddtd???qq "" + ""BaseOfImage SizeOfImage CheckSum "" + ""TimeDateStamp ModuleNameRVA "" + ""(mdmp_vs_fixedfileinfo)VersionInfo "" + ""(mdmp_location_descriptor)CvRecord "" + ""(mdmp_location_descriptor)MiscRecord "" + ""Reserved0 Reserved1"", 0); + sdb_num_set (obj->kv, ""mdmp_module_list.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_module_list.format"", + sdb_fmt (""d[%i]? "" + ""NumberOfModule (mdmp_module)Modules"", + module_list->number_of_modules, + 0), + 0); + + for (i = 0; i < module_list->number_of_modules; i++) { + modules = (struct minidump_module *)(&(module_list->modules)); + r_list_append(obj->streams.modules, &(modules[i])); + } + break; + case MEMORY_LIST_STREAM: + memory_list = (struct minidump_memory_list *)(obj->b->buf + entry->location.rva); + + sdb_num_set (obj->kv, ""mdmp_memory_list.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_memory_list.format"", + sdb_fmt (""d[%i]? "" + ""NumberOfMemoryRanges "" + ""(mdmp_memory_descriptor)MemoryRanges "", + memory_list->number_of_memory_ranges, + 0), + 0); + + for (i = 0; i < memory_list->number_of_memory_ranges; i++) { + memories = (struct minidump_memory_descriptor *)(&(memory_list->memory_ranges)); + r_list_append (obj->streams.memories, &(memories[i])); + } + break; + case EXCEPTION_STREAM: + /* TODO: Not yet fully parsed or utilised */ + obj->streams.exception = (struct minidump_exception_stream *)(obj->b->buf + entry->location.rva); + + sdb_set (obj->kv, ""mdmp_exception.format"", ""[4]E[4]Eqqdd[15]q "" + ""(mdmp_exception_code)ExceptionCode "" + ""(mdmp_exception_flags)ExceptionFlags "" + ""ExceptionRecord ExceptionAddress "" + ""NumberParameters __UnusedAlignment "" + ""ExceptionInformation"", 0); + sdb_num_set (obj->kv, ""mdmp_exception_stream.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_exception_stream.format"", ""dd?? "" + ""ThreadId __Alignment "" + ""(mdmp_exception)ExceptionRecord "" + ""(mdmp_location_descriptor)ThreadContext"", 0); + + break; + case SYSTEM_INFO_STREAM: + obj->streams.system_info = (struct minidump_system_info *)(obj->b->buf + entry->location.rva); + + sdb_num_set (obj->kv, ""mdmp_system_info.offset"", + entry->location.rva, 0); + /* TODO: We need E as a byte! */ + sdb_set (obj->kv, ""mdmp_system_info.format"", ""[2]EwwbBddd[4]Ed[2]Ew[2]q "" + ""(mdmp_processor_architecture)ProcessorArchitecture "" + ""ProcessorLevel ProcessorRevision NumberOfProcessors "" + ""(mdmp_product_type)ProductType "" + ""MajorVersion MinorVersion BuildNumber (mdmp_platform_id)PlatformId "" + ""CsdVersionRva (mdmp_suite_mask)SuiteMask Reserved2 ProcessorFeatures"", 0); + + break; + case THREAD_EX_LIST_STREAM: + /* TODO: Not yet fully parsed or utilised */ + thread_ex_list = (struct minidump_thread_ex_list *)(obj->b->buf + entry->location.rva); + + sdb_set (obj->kv, ""mdmp_thread_ex.format"", ""ddddq??? "" + ""ThreadId SuspendCount PriorityClass Priority "" + ""Teb (mdmp_memory_descriptor)Stack "" + ""(mdmp_location_descriptor)ThreadContext "" + ""(mdmp_memory_descriptor)BackingStore"", 0); + sdb_num_set (obj->kv, ""mdmp_thread_ex_list.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_thread_ex_list.format"", + sdb_fmt (""d[%i]? NumberOfThreads "" + ""(mdmp_thread_ex)Threads"", + thread_ex_list->number_of_threads, 0), + 0); + + for (i = 0; i < thread_ex_list->number_of_threads; i++) { + ex_threads = (struct minidump_thread_ex *)(&(thread_ex_list->threads)); + r_list_append (obj->streams.ex_threads, &(ex_threads[i])); + } + break; + case MEMORY_64_LIST_STREAM: + memory64_list = (struct minidump_memory64_list *)(obj->b->buf + entry->location.rva); + + sdb_num_set (obj->kv, ""mdmp_memory64_list.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_memory64_list.format"", + sdb_fmt (""qq[%i]? NumberOfMemoryRanges "" + ""BaseRva "" + ""(mdmp_memory_descriptor64)MemoryRanges"", + memory64_list->number_of_memory_ranges), + 0); + + obj->streams.memories64.base_rva = memory64_list->base_rva; + for (i = 0; i < memory64_list->number_of_memory_ranges; i++) { + memories64 = (struct minidump_memory_descriptor64 *)(&(memory64_list->memory_ranges)); + r_list_append (obj->streams.memories64.memories, &(memories64[i])); + } + break; + case COMMENT_STREAM_A: + /* TODO: Not yet fully parsed or utilised */ + obj->streams.comments_a = obj->b->buf + entry->location.rva; + + sdb_num_set (obj->kv, ""mdmp_comment_stream_a.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_comment_stream_a.format"", + ""s CommentA"", 0); + + break; + case COMMENT_STREAM_W: + /* TODO: Not yet fully parsed or utilised */ + obj->streams.comments_w = obj->b->buf + entry->location.rva; + + sdb_num_set (obj->kv, ""mdmp_comment_stream_w.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_comment_stream_w.format"", + ""s CommentW"", 0); + + break; + case HANDLE_DATA_STREAM: + /* TODO: Not yet fully parsed or utilised */ + obj->streams.handle_data = (struct minidump_handle_data_stream *)(obj->b->buf + entry->location.rva); + + sdb_num_set (obj->kv, ""mdmp_handle_data_stream.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_handle_data_stream.format"", ""dddd "" + ""SizeOfHeader SizeOfDescriptor "" + ""NumberOfDescriptors Reserved"", 0); + break; + case FUNCTION_TABLE_STREAM: + /* TODO: Not yet fully parsed or utilised */ + obj->streams.function_table = (struct minidump_function_table_stream *)(obj->b->buf + entry->location.rva); + + sdb_num_set (obj->kv, ""mdmp_function_table_stream.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_function_table_stream.format"", ""dddddd "" + ""SizeOfHeader SizeOfDescriptor SizeOfNativeDescriptor "" + ""SizeOfFunctionEntry NumberOfDescriptors SizeOfAlignPad"", + 0); + break; + case UNLOADED_MODULE_LIST_STREAM: + /* TODO: Not yet fully parsed or utilised */ + unloaded_module_list = (struct minidump_unloaded_module_list *)(obj->b->buf + entry->location.rva); + + sdb_set (obj->kv, ""mdmp_unloaded_module.format"", ""qddtd "" + ""BaseOfImage SizeOfImage CheckSum TimeDateStamp "" + ""ModuleNameRva"", 0); + sdb_num_set (obj->kv, ""mdmp_unloaded_module_list.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_unloaded_module_list.format"", ""ddd "" + ""SizeOfHeader SizeOfEntry NumberOfEntries"", 0); + + for (i = 0; i < unloaded_module_list->number_of_entries; i++) { + unloaded_modules = (struct minidump_unloaded_module *)((ut8 *)&unloaded_module_list + sizeof (struct minidump_unloaded_module_list)); + r_list_append (obj->streams.unloaded_modules, &(unloaded_modules[i])); + } + break; + case MISC_INFO_STREAM: + /* TODO: Not yet fully parsed or utilised */ + obj->streams.misc_info.misc_info_1 = (struct minidump_misc_info *)(obj->b->buf + entry->location.rva); + + /* TODO: Handle different sizes */ + sdb_num_set (obj->kv, ""mdmp_misc_info.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_misc_info.format"", ""d[4]Bdtttddddd "" + ""SizeOfInfo (mdmp_misc1_flags)Flags1 ProcessId "" + ""ProcessCreateTime ProcessUserTime ProcessKernelTime "" + ""ProcessorMaxMhz ProcessorCurrentMhz "" + ""ProcessorMhzLimit ProcessorMaxIdleState "" + ""ProcessorCurrentIdleState"", 0); + + break; + case MEMORY_INFO_LIST_STREAM: + memory_info_list = (struct minidump_memory_info_list *)(obj->b->buf + entry->location.rva); + + sdb_set (obj->kv, ""mdmp_memory_info.format"", + ""qq[4]Edq[4]E[4]E[4]Ed BaseAddress AllocationBase "" + ""(mdmp_page_protect)AllocationProtect __Alignment1 RegionSize "" + ""(mdmp_mem_state)State (mdmp_page_protect)Protect "" + ""(mdmp_mem_type)Type __Alignment2"", 0); + sdb_num_set (obj->kv, ""mdmp_memory_info_list.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_memory_info_list.format"", + sdb_fmt (""ddq[%i]? SizeOfHeader SizeOfEntry "" + ""NumberOfEntries (mdmp_memory_info)MemoryInfo"", + memory_info_list->number_of_entries), + 0); + + for (i = 0; i < memory_info_list->number_of_entries; i++) { + memory_infos = (struct minidump_memory_info *)((ut8 *)memory_info_list + sizeof (struct minidump_memory_info_list)); + r_list_append (obj->streams.memory_infos, &(memory_infos[i])); + } + break; + case THREAD_INFO_LIST_STREAM: + /* TODO: Not yet fully parsed or utilised */ + thread_info_list = (struct minidump_thread_info_list *)(obj->b->buf + entry->location.rva); + + sdb_set (obj->kv, ""mdmp_thread_info.format"", ""ddddttttqq "" + ""ThreadId DumpFlags DumpError ExitStatus CreateTime "" + ""ExitTime KernelTime UserTime StartAddress Affinity"", + 0); + sdb_num_set (obj->kv, ""mdmp_thread_info_list.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_thread_info_list.format"", ""ddd "" + ""SizeOfHeader SizeOfEntry NumberOfEntries"", 0); + + for (i = 0; i < thread_info_list->number_of_entries; i++) { + thread_infos = (struct minidump_thread_info *)((ut8 *)thread_info_list + sizeof (struct minidump_thread_info_list)); + r_list_append (obj->streams.thread_infos, &(thread_infos[i])); + } + break; + case HANDLE_OPERATION_LIST_STREAM: + /* TODO: Not yet fully parsed or utilised */ + handle_operation_list = (struct minidump_handle_operation_list *)(obj->b->buf + entry->location.rva); + + sdb_num_set (obj->kv, ""mdmp_handle_operation_list.offset"", + entry->location.rva, 0); + sdb_set (obj->kv, ""mdmp_handle_operation_list.format"", ""dddd "" + ""SizeOfHeader SizeOfEntry NumberOfEntries Reserved"", 0); + + for (i = 0; i < handle_operation_list->number_of_entries; i++) { + handle_operations = (struct avrf_handle_operation *)((ut8 *)handle_operation_list + sizeof (struct minidump_handle_operation_list)); + r_list_append (obj->streams.operations, &(handle_operations[i])); + } + + break; + case LAST_RESERVED_STREAM: + /* TODO: Not yet fully parsed or utilised */ + break; + case UNUSED_STREAM: + case RESERVED_STREAM_0: + case RESERVED_STREAM_1: + /* Silently ignore reserved streams */ + break; + default: + eprintf (""[WARN] Invalid or unsupported enumeration encountered %i\n"", entry->stream_type); + return false; + } + return true; +} +","@@ -362,7 +362,7 @@ static bool r_bin_mdmp_init_directory_entry(struct r_bin_mdmp_obj *obj, struct m + /* We could confirm data sizes but a malcious MDMP will always get around + ** this! But we can ensure that the data is not outside of the file */ + if (entry->location.rva + entry->location.data_size > obj->b->length) { +- eprintf(""[ERROR] Size Mismatch - Stream data is larger than file size!\n""); ++ eprintf (""[ERROR] Size Mismatch - Stream data is larger than file size!\n""); + return false; + } + +@@ -646,10 +646,7 @@ static bool r_bin_mdmp_init_directory_entry(struct r_bin_mdmp_obj *obj, struct m + + static bool r_bin_mdmp_init_directory(struct r_bin_mdmp_obj *obj) { + int i; +- ut8 *directory_base; +- struct minidump_directory *entry; +- +- directory_base = obj->b->buf + obj->hdr->stream_directory_rva; ++ struct minidump_directory entry; + + sdb_num_set (obj->kv, ""mdmp_directory.offset"", + obj->hdr->stream_directory_rva, 0); +@@ -658,9 +655,13 @@ static bool r_bin_mdmp_init_directory(struct r_bin_mdmp_obj *obj) { + ""(mdmp_location_descriptor)Location"", 0); + + /* Parse each entry in the directory */ ++ ut64 rvadir = obj->hdr->stream_directory_rva; + for (i = 0; i < (int)obj->hdr->number_of_streams; i++) { +- entry = (struct minidump_directory *)(directory_base + (i * sizeof (struct minidump_directory))); +- r_bin_mdmp_init_directory_entry (obj, entry); ++ ut32 delta = i * sizeof (struct minidump_directory); ++ int r = r_buf_read_at (obj->b, rvadir + delta, (ut8*) &entry, sizeof (struct minidump_directory)); ++ if (r) { ++ r_bin_mdmp_init_directory_entry (obj, &entry); ++ } + } + + return true;",3517,3848,4096 +227,"void FoFiType1C::convertToType1(char *psName, const char **newEncoding, GBool ascii, + FoFiOutputFunc outputFunc, + void *outputStream) { + int psNameLen; + Type1CEexecBuf eb; + Type1CIndex subrIdx; + Type1CIndexVal val; + GooString *buf; + char buf2[256]; + const char **enc; + GBool ok; + int i; + + if (psName) { + psNameLen = strlen(psName); + } else { + psName = name->getCString(); + psNameLen = name->getLength(); + } + + ok = gTrue; + (*outputFunc)(outputStream, ""%!FontType1-1.0: "", 17); + (*outputFunc)(outputStream, psName, psNameLen); + if (topDict.versionSID != 0) { + getString(topDict.versionSID, buf2, &ok); + (*outputFunc)(outputStream, buf2, strlen(buf2)); + } + (*outputFunc)(outputStream, ""\n"", 1); + (*outputFunc)(outputStream, ""12 dict begin\n"", 14); + (*outputFunc)(outputStream, ""/FontInfo 10 dict dup begin\n"", 28); + if (topDict.versionSID != 0) { + (*outputFunc)(outputStream, ""/version "", 9); + writePSString(buf2, outputFunc, outputStream); + (*outputFunc)(outputStream, "" readonly def\n"", 14); + } + if (topDict.noticeSID != 0) { + getString(topDict.noticeSID, buf2, &ok); + (*outputFunc)(outputStream, ""/Notice "", 8); + writePSString(buf2, outputFunc, outputStream); + (*outputFunc)(outputStream, "" readonly def\n"", 14); + } + if (topDict.copyrightSID != 0) { + getString(topDict.copyrightSID, buf2, &ok); + (*outputFunc)(outputStream, ""/Copyright "", 11); + writePSString(buf2, outputFunc, outputStream); + (*outputFunc)(outputStream, "" readonly def\n"", 14); + } + if (topDict.fullNameSID != 0) { + getString(topDict.fullNameSID, buf2, &ok); + (*outputFunc)(outputStream, ""/FullName "", 10); + writePSString(buf2, outputFunc, outputStream); + (*outputFunc)(outputStream, "" readonly def\n"", 14); + } + if (topDict.familyNameSID != 0) { + getString(topDict.familyNameSID, buf2, &ok); + (*outputFunc)(outputStream, ""/FamilyName "", 12); + writePSString(buf2, outputFunc, outputStream); + (*outputFunc)(outputStream, "" readonly def\n"", 14); + } + if (topDict.weightSID != 0) { + getString(topDict.weightSID, buf2, &ok); + (*outputFunc)(outputStream, ""/Weight "", 8); + writePSString(buf2, outputFunc, outputStream); + (*outputFunc)(outputStream, "" readonly def\n"", 14); + } + if (topDict.isFixedPitch) { + (*outputFunc)(outputStream, ""/isFixedPitch true def\n"", 23); + } else { + (*outputFunc)(outputStream, ""/isFixedPitch false def\n"", 24); + } + buf = GooString::format(""/ItalicAngle {0:.4g} def\n"", topDict.italicAngle); + (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); + delete buf; + buf = GooString::format(""/UnderlinePosition {0:.4g} def\n"", + topDict.underlinePosition); + (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); + delete buf; + buf = GooString::format(""/UnderlineThickness {0:.4g} def\n"", + topDict.underlineThickness); + (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); + delete buf; + (*outputFunc)(outputStream, ""end readonly def\n"", 17); + (*outputFunc)(outputStream, ""/FontName /"", 11); + (*outputFunc)(outputStream, psName, psNameLen); + (*outputFunc)(outputStream, "" def\n"", 5); + buf = GooString::format(""/PaintType {0:d} def\n"", topDict.paintType); + (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); + delete buf; + (*outputFunc)(outputStream, ""/FontType 1 def\n"", 16); + buf = GooString::format(""/FontMatrix [{0:.8g} {1:.8g} {2:.8g} {3:.8g} {4:.8g} {5:.8g}] readonly def\n"", + topDict.fontMatrix[0], topDict.fontMatrix[1], + topDict.fontMatrix[2], topDict.fontMatrix[3], + topDict.fontMatrix[4], topDict.fontMatrix[5]); + (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); + delete buf; + buf = GooString::format(""/FontBBox [{0:.4g} {1:.4g} {2:.4g} {3:.4g}] readonly def\n"", + topDict.fontBBox[0], topDict.fontBBox[1], + topDict.fontBBox[2], topDict.fontBBox[3]); + (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); + delete buf; + buf = GooString::format(""/StrokeWidth {0:.4g} def\n"", topDict.strokeWidth); + (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); + delete buf; + if (topDict.uniqueID != 0) { + buf = GooString::format(""/UniqueID {0:d} def\n"", topDict.uniqueID); + (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); + delete buf; + } + + (*outputFunc)(outputStream, ""/Encoding "", 10); + if (!newEncoding && encoding == fofiType1StandardEncoding) { + (*outputFunc)(outputStream, ""StandardEncoding def\n"", 21); + } else { + (*outputFunc)(outputStream, ""256 array\n"", 10); + (*outputFunc)(outputStream, + ""0 1 255 {1 index exch /.notdef put} for\n"", 40); + enc = newEncoding ? newEncoding : (const char **)encoding; + for (i = 0; i < 256; ++i) { + if (enc[i]) { + buf = GooString::format(""dup {0:d} /{1:s} put\n"", i, enc[i]); + (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); + delete buf; + } + } + (*outputFunc)(outputStream, ""readonly def\n"", 13); + } + (*outputFunc)(outputStream, ""currentdict end\n"", 16); + + (*outputFunc)(outputStream, ""currentfile eexec\n"", 18); + eb.outputFunc = outputFunc; + eb.outputStream = outputStream; + eb.ascii = ascii; + eb.r1 = 55665; + eb.line = 0; + + eexecWrite(&eb, ""\x83\xca\x73\xd5""); + eexecWrite(&eb, ""dup /Private 32 dict dup begin\n""); + eexecWrite(&eb, ""/RD {string currentfile exch readstring pop}"" + "" executeonly def\n""); + eexecWrite(&eb, ""/ND {noaccess def} executeonly def\n""); + eexecWrite(&eb, ""/NP {noaccess put} executeonly def\n""); + eexecWrite(&eb, ""/MinFeature {16 16} def\n""); + eexecWrite(&eb, ""/password 5839 def\n""); + if (privateDicts[0].nBlueValues) { + eexecWrite(&eb, ""/BlueValues [""); + for (i = 0; i < privateDicts[0].nBlueValues; ++i) { + buf = GooString::format(""{0:s}{1:d}"", + i > 0 ? "" "" : """", privateDicts[0].blueValues[i]); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + eexecWrite(&eb, ""] def\n""); + } + if (privateDicts[0].nOtherBlues) { + eexecWrite(&eb, ""/OtherBlues [""); + for (i = 0; i < privateDicts[0].nOtherBlues; ++i) { + buf = GooString::format(""{0:s}{1:d}"", + i > 0 ? "" "" : """", privateDicts[0].otherBlues[i]); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + eexecWrite(&eb, ""] def\n""); + } + if (privateDicts[0].nFamilyBlues) { + eexecWrite(&eb, ""/FamilyBlues [""); + for (i = 0; i < privateDicts[0].nFamilyBlues; ++i) { + buf = GooString::format(""{0:s}{1:d}"", + i > 0 ? "" "" : """", privateDicts[0].familyBlues[i]); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + eexecWrite(&eb, ""] def\n""); + } + if (privateDicts[0].nFamilyOtherBlues) { + eexecWrite(&eb, ""/FamilyOtherBlues [""); + for (i = 0; i < privateDicts[0].nFamilyOtherBlues; ++i) { + buf = GooString::format(""{0:s}{1:d}"", i > 0 ? "" "" : """", + privateDicts[0].familyOtherBlues[i]); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + eexecWrite(&eb, ""] def\n""); + } + if (privateDicts[0].blueScale != 0.039625) { + buf = GooString::format(""/BlueScale {0:.4g} def\n"", + privateDicts[0].blueScale); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + if (privateDicts[0].blueShift != 7) { + buf = GooString::format(""/BlueShift {0:d} def\n"", privateDicts[0].blueShift); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + if (privateDicts[0].blueFuzz != 1) { + buf = GooString::format(""/BlueFuzz {0:d} def\n"", privateDicts[0].blueFuzz); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + if (privateDicts[0].hasStdHW) { + buf = GooString::format(""/StdHW [{0:.4g}] def\n"", privateDicts[0].stdHW); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + if (privateDicts[0].hasStdVW) { + buf = GooString::format(""/StdVW [{0:.4g}] def\n"", privateDicts[0].stdVW); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + if (privateDicts[0].nStemSnapH) { + eexecWrite(&eb, ""/StemSnapH [""); + for (i = 0; i < privateDicts[0].nStemSnapH; ++i) { + buf = GooString::format(""{0:s}{1:.4g}"", + i > 0 ? "" "" : """", privateDicts[0].stemSnapH[i]); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + eexecWrite(&eb, ""] def\n""); + } + if (privateDicts[0].nStemSnapV) { + eexecWrite(&eb, ""/StemSnapV [""); + for (i = 0; i < privateDicts[0].nStemSnapV; ++i) { + buf = GooString::format(""{0:s}{1:.4g}"", + i > 0 ? "" "" : """", privateDicts[0].stemSnapV[i]); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + eexecWrite(&eb, ""] def\n""); + } + if (privateDicts[0].hasForceBold) { + buf = GooString::format(""/ForceBold {0:s} def\n"", + privateDicts[0].forceBold ? ""true"" : ""false""); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + if (privateDicts[0].forceBoldThreshold != 0) { + buf = GooString::format(""/ForceBoldThreshold {0:.4g} def\n"", + privateDicts[0].forceBoldThreshold); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + if (privateDicts[0].languageGroup != 0) { + buf = GooString::format(""/LanguageGroup {0:d} def\n"", + privateDicts[0].languageGroup); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + if (privateDicts[0].expansionFactor != 0.06) { + buf = GooString::format(""/ExpansionFactor {0:.4g} def\n"", + privateDicts[0].expansionFactor); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + + ok = gTrue; + getIndex(privateDicts[0].subrsOffset, &subrIdx, &ok); + if (!ok) { + subrIdx.pos = -1; + } + + buf = GooString::format(""2 index /CharStrings {0:d} dict dup begin\n"", + nGlyphs); + eexecWrite(&eb, buf->getCString()); + delete buf; + for (i = 0; i < nGlyphs; ++i) { + ok = gTrue; + getIndexVal(&charStringsIdx, i, &val, &ok); + if (ok && i < charsetLength) { + getString(charset[i], buf2, &ok); + if (ok) { + eexecCvtGlyph(&eb, buf2, val.pos, val.len, &subrIdx, &privateDicts[0]); + } + } + } + eexecWrite(&eb, ""end\n""); + eexecWrite(&eb, ""end\n""); + eexecWrite(&eb, ""readonly put\n""); + eexecWrite(&eb, ""noaccess put\n""); + eexecWrite(&eb, ""dup /FontName get exch definefont pop\n""); + eexecWrite(&eb, ""mark currentfile closefile\n""); + + if (ascii && eb.line > 0) { + (*outputFunc)(outputStream, ""\n"", 1); + } + for (i = 0; i < 8; ++i) { + (*outputFunc)(outputStream, ""0000000000000000000000000000000000000000000000000000000000000000\n"", 65); + } + (*outputFunc)(outputStream, ""cleartomark\n"", 12); +} +",0,"void FoFiType1C::convertToType1(char *psName, const char **newEncoding, GBool ascii, + FoFiOutputFunc outputFunc, + void *outputStream) { + int psNameLen; + Type1CEexecBuf eb; + Type1CIndex subrIdx; + Type1CIndexVal val; + GooString *buf; + char buf2[256]; + const char **enc; + GBool ok; + int i; + + if (psName) { + psNameLen = strlen(psName); + } else { + psName = name->getCString(); + psNameLen = name->getLength(); + } + + ok = gTrue; + (*outputFunc)(outputStream, ""%!FontType1-1.0: "", 17); + (*outputFunc)(outputStream, psName, psNameLen); + if (topDict.versionSID != 0) { + getString(topDict.versionSID, buf2, &ok); + (*outputFunc)(outputStream, buf2, strlen(buf2)); + } + (*outputFunc)(outputStream, ""\n"", 1); + (*outputFunc)(outputStream, ""12 dict begin\n"", 14); + (*outputFunc)(outputStream, ""/FontInfo 10 dict dup begin\n"", 28); + if (topDict.versionSID != 0) { + (*outputFunc)(outputStream, ""/version "", 9); + writePSString(buf2, outputFunc, outputStream); + (*outputFunc)(outputStream, "" readonly def\n"", 14); + } + if (topDict.noticeSID != 0) { + getString(topDict.noticeSID, buf2, &ok); + (*outputFunc)(outputStream, ""/Notice "", 8); + writePSString(buf2, outputFunc, outputStream); + (*outputFunc)(outputStream, "" readonly def\n"", 14); + } + if (topDict.copyrightSID != 0) { + getString(topDict.copyrightSID, buf2, &ok); + (*outputFunc)(outputStream, ""/Copyright "", 11); + writePSString(buf2, outputFunc, outputStream); + (*outputFunc)(outputStream, "" readonly def\n"", 14); + } + if (topDict.fullNameSID != 0) { + getString(topDict.fullNameSID, buf2, &ok); + (*outputFunc)(outputStream, ""/FullName "", 10); + writePSString(buf2, outputFunc, outputStream); + (*outputFunc)(outputStream, "" readonly def\n"", 14); + } + if (topDict.familyNameSID != 0) { + getString(topDict.familyNameSID, buf2, &ok); + (*outputFunc)(outputStream, ""/FamilyName "", 12); + writePSString(buf2, outputFunc, outputStream); + (*outputFunc)(outputStream, "" readonly def\n"", 14); + } + if (topDict.weightSID != 0) { + getString(topDict.weightSID, buf2, &ok); + (*outputFunc)(outputStream, ""/Weight "", 8); + writePSString(buf2, outputFunc, outputStream); + (*outputFunc)(outputStream, "" readonly def\n"", 14); + } + if (topDict.isFixedPitch) { + (*outputFunc)(outputStream, ""/isFixedPitch true def\n"", 23); + } else { + (*outputFunc)(outputStream, ""/isFixedPitch false def\n"", 24); + } + buf = GooString::format(""/ItalicAngle {0:.4g} def\n"", topDict.italicAngle); + (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); + delete buf; + buf = GooString::format(""/UnderlinePosition {0:.4g} def\n"", + topDict.underlinePosition); + (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); + delete buf; + buf = GooString::format(""/UnderlineThickness {0:.4g} def\n"", + topDict.underlineThickness); + (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); + delete buf; + (*outputFunc)(outputStream, ""end readonly def\n"", 17); + (*outputFunc)(outputStream, ""/FontName /"", 11); + (*outputFunc)(outputStream, psName, psNameLen); + (*outputFunc)(outputStream, "" def\n"", 5); + buf = GooString::format(""/PaintType {0:d} def\n"", topDict.paintType); + (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); + delete buf; + (*outputFunc)(outputStream, ""/FontType 1 def\n"", 16); + buf = GooString::format(""/FontMatrix [{0:.8g} {1:.8g} {2:.8g} {3:.8g} {4:.8g} {5:.8g}] readonly def\n"", + topDict.fontMatrix[0], topDict.fontMatrix[1], + topDict.fontMatrix[2], topDict.fontMatrix[3], + topDict.fontMatrix[4], topDict.fontMatrix[5]); + (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); + delete buf; + buf = GooString::format(""/FontBBox [{0:.4g} {1:.4g} {2:.4g} {3:.4g}] readonly def\n"", + topDict.fontBBox[0], topDict.fontBBox[1], + topDict.fontBBox[2], topDict.fontBBox[3]); + (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); + delete buf; + buf = GooString::format(""/StrokeWidth {0:.4g} def\n"", topDict.strokeWidth); + (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); + delete buf; + if (topDict.uniqueID != 0) { + buf = GooString::format(""/UniqueID {0:d} def\n"", topDict.uniqueID); + (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); + delete buf; + } + + (*outputFunc)(outputStream, ""/Encoding "", 10); + if (!newEncoding && encoding == fofiType1StandardEncoding) { + (*outputFunc)(outputStream, ""StandardEncoding def\n"", 21); + } else { + (*outputFunc)(outputStream, ""256 array\n"", 10); + (*outputFunc)(outputStream, + ""0 1 255 {1 index exch /.notdef put} for\n"", 40); + enc = newEncoding ? newEncoding : (const char **)encoding; + for (i = 0; i < 256; ++i) { + if (enc[i]) { + buf = GooString::format(""dup {0:d} /{1:s} put\n"", i, enc[i]); + (*outputFunc)(outputStream, buf->getCString(), buf->getLength()); + delete buf; + } + } + (*outputFunc)(outputStream, ""readonly def\n"", 13); + } + (*outputFunc)(outputStream, ""currentdict end\n"", 16); + + (*outputFunc)(outputStream, ""currentfile eexec\n"", 18); + eb.outputFunc = outputFunc; + eb.outputStream = outputStream; + eb.ascii = ascii; + eb.r1 = 55665; + eb.line = 0; + + eexecWrite(&eb, ""\x83\xca\x73\xd5""); + eexecWrite(&eb, ""dup /Private 32 dict dup begin\n""); + eexecWrite(&eb, ""/RD {string currentfile exch readstring pop}"" + "" executeonly def\n""); + eexecWrite(&eb, ""/ND {noaccess def} executeonly def\n""); + eexecWrite(&eb, ""/NP {noaccess put} executeonly def\n""); + eexecWrite(&eb, ""/MinFeature {16 16} def\n""); + eexecWrite(&eb, ""/password 5839 def\n""); + if (privateDicts[0].nBlueValues) { + eexecWrite(&eb, ""/BlueValues [""); + for (i = 0; i < privateDicts[0].nBlueValues; ++i) { + buf = GooString::format(""{0:s}{1:d}"", + i > 0 ? "" "" : """", privateDicts[0].blueValues[i]); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + eexecWrite(&eb, ""] def\n""); + } + if (privateDicts[0].nOtherBlues) { + eexecWrite(&eb, ""/OtherBlues [""); + for (i = 0; i < privateDicts[0].nOtherBlues; ++i) { + buf = GooString::format(""{0:s}{1:d}"", + i > 0 ? "" "" : """", privateDicts[0].otherBlues[i]); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + eexecWrite(&eb, ""] def\n""); + } + if (privateDicts[0].nFamilyBlues) { + eexecWrite(&eb, ""/FamilyBlues [""); + for (i = 0; i < privateDicts[0].nFamilyBlues; ++i) { + buf = GooString::format(""{0:s}{1:d}"", + i > 0 ? "" "" : """", privateDicts[0].familyBlues[i]); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + eexecWrite(&eb, ""] def\n""); + } + if (privateDicts[0].nFamilyOtherBlues) { + eexecWrite(&eb, ""/FamilyOtherBlues [""); + for (i = 0; i < privateDicts[0].nFamilyOtherBlues; ++i) { + buf = GooString::format(""{0:s}{1:d}"", i > 0 ? "" "" : """", + privateDicts[0].familyOtherBlues[i]); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + eexecWrite(&eb, ""] def\n""); + } + if (privateDicts[0].blueScale != 0.039625) { + buf = GooString::format(""/BlueScale {0:.4g} def\n"", + privateDicts[0].blueScale); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + if (privateDicts[0].blueShift != 7) { + buf = GooString::format(""/BlueShift {0:d} def\n"", privateDicts[0].blueShift); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + if (privateDicts[0].blueFuzz != 1) { + buf = GooString::format(""/BlueFuzz {0:d} def\n"", privateDicts[0].blueFuzz); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + if (privateDicts[0].hasStdHW) { + buf = GooString::format(""/StdHW [{0:.4g}] def\n"", privateDicts[0].stdHW); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + if (privateDicts[0].hasStdVW) { + buf = GooString::format(""/StdVW [{0:.4g}] def\n"", privateDicts[0].stdVW); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + if (privateDicts[0].nStemSnapH) { + eexecWrite(&eb, ""/StemSnapH [""); + for (i = 0; i < privateDicts[0].nStemSnapH; ++i) { + buf = GooString::format(""{0:s}{1:.4g}"", + i > 0 ? "" "" : """", privateDicts[0].stemSnapH[i]); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + eexecWrite(&eb, ""] def\n""); + } + if (privateDicts[0].nStemSnapV) { + eexecWrite(&eb, ""/StemSnapV [""); + for (i = 0; i < privateDicts[0].nStemSnapV; ++i) { + buf = GooString::format(""{0:s}{1:.4g}"", + i > 0 ? "" "" : """", privateDicts[0].stemSnapV[i]); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + eexecWrite(&eb, ""] def\n""); + } + if (privateDicts[0].hasForceBold) { + buf = GooString::format(""/ForceBold {0:s} def\n"", + privateDicts[0].forceBold ? ""true"" : ""false""); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + if (privateDicts[0].forceBoldThreshold != 0) { + buf = GooString::format(""/ForceBoldThreshold {0:.4g} def\n"", + privateDicts[0].forceBoldThreshold); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + if (privateDicts[0].languageGroup != 0) { + buf = GooString::format(""/LanguageGroup {0:d} def\n"", + privateDicts[0].languageGroup); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + if (privateDicts[0].expansionFactor != 0.06) { + buf = GooString::format(""/ExpansionFactor {0:.4g} def\n"", + privateDicts[0].expansionFactor); + eexecWrite(&eb, buf->getCString()); + delete buf; + } + + ok = gTrue; + getIndex(privateDicts[0].subrsOffset, &subrIdx, &ok); + if (!ok) { + subrIdx.pos = -1; + } + + buf = GooString::format(""2 index /CharStrings {0:d} dict dup begin\n"", + nGlyphs); + eexecWrite(&eb, buf->getCString()); + delete buf; + for (i = 0; i < nGlyphs; ++i) { + ok = gTrue; + getIndexVal(&charStringsIdx, i, &val, &ok); + if (ok && i < charsetLength) { + getString(charset[i], buf2, &ok); + if (ok) { + eexecCvtGlyph(&eb, buf2, val.pos, val.len, &subrIdx, &privateDicts[0]); + } + } + } + eexecWrite(&eb, ""end\n""); + eexecWrite(&eb, ""end\n""); + eexecWrite(&eb, ""readonly put\n""); + eexecWrite(&eb, ""noaccess put\n""); + eexecWrite(&eb, ""dup /FontName get exch definefont pop\n""); + eexecWrite(&eb, ""mark currentfile closefile\n""); + + if (ascii && eb.line > 0) { + (*outputFunc)(outputStream, ""\n"", 1); + } + for (i = 0; i < 8; ++i) { + (*outputFunc)(outputStream, ""0000000000000000000000000000000000000000000000000000000000000000\n"", 65); + } + (*outputFunc)(outputStream, ""cleartomark\n"", 12); +} +","@@ -898,6 +898,9 @@ void FoFiType1C::convertToType0(char *psName, int *codeMap, int nCodes, + } + } + ++ if (fd >= nFDs) ++ continue; ++ + // font dictionary (unencrypted section) + (*outputFunc)(outputStream, ""16 dict begin\n"", 14); + (*outputFunc)(outputStream, ""/FontName /"", 11);",3525,3856,4096 +17931,"static int isofs_read_inode(struct inode *inode) + { + struct super_block *sb = inode->i_sb; + struct isofs_sb_info *sbi = ISOFS_SB(sb); + unsigned long bufsize = ISOFS_BUFFER_SIZE(inode); + unsigned long block; + int high_sierra = sbi->s_high_sierra; + struct buffer_head *bh = NULL; + struct iso_directory_record *de; + struct iso_directory_record *tmpde = NULL; + unsigned int de_len; + unsigned long offset; + struct iso_inode_info *ei = ISOFS_I(inode); + int ret = -EIO; + + block = ei->i_iget5_block; + bh = sb_bread(inode->i_sb, block); + if (!bh) + goto out_badread; + + offset = ei->i_iget5_offset; + + de = (struct iso_directory_record *) (bh->b_data + offset); + de_len = *(unsigned char *) de; + + if (offset + de_len > bufsize) { + int frag1 = bufsize - offset; + + tmpde = kmalloc(de_len, GFP_KERNEL); + if (tmpde == NULL) { + printk(KERN_INFO ""%s: out of memory\n"", __func__); + ret = -ENOMEM; + goto fail; + } + memcpy(tmpde, bh->b_data + offset, frag1); + brelse(bh); + bh = sb_bread(inode->i_sb, ++block); + if (!bh) + goto out_badread; + memcpy((char *)tmpde+frag1, bh->b_data, de_len - frag1); + de = tmpde; + } + + inode->i_ino = isofs_get_ino(ei->i_iget5_block, + ei->i_iget5_offset, + ISOFS_BUFFER_BITS(inode)); + + /* Assume it is a normal-format file unless told otherwise */ + ei->i_file_format = isofs_file_normal; + + if (de->flags[-high_sierra] & 2) { + if (sbi->s_dmode != ISOFS_INVALID_MODE) + inode->i_mode = S_IFDIR | sbi->s_dmode; + else + inode->i_mode = S_IFDIR | S_IRUGO | S_IXUGO; + set_nlink(inode, 1); /* + * Set to 1. We know there are 2, but + * the find utility tries to optimize + * if it is 2, and it screws up. It is + * easier to give 1 which tells find to + * do it the hard way. + */ + } else { + if (sbi->s_fmode != ISOFS_INVALID_MODE) { + inode->i_mode = S_IFREG | sbi->s_fmode; + } else { + /* + * Set default permissions: r-x for all. The disc + * could be shared with DOS machines so virtually + * anything could be a valid executable. + */ + inode->i_mode = S_IFREG | S_IRUGO | S_IXUGO; + } + set_nlink(inode, 1); + } + inode->i_uid = sbi->s_uid; + inode->i_gid = sbi->s_gid; + inode->i_blocks = 0; + + ei->i_format_parm[0] = 0; + ei->i_format_parm[1] = 0; + ei->i_format_parm[2] = 0; + + ei->i_section_size = isonum_733(de->size); + if (de->flags[-high_sierra] & 0x80) { + ret = isofs_read_level3_size(inode); + if (ret < 0) + goto fail; + ret = -EIO; + } else { + ei->i_next_section_block = 0; + ei->i_next_section_offset = 0; + inode->i_size = isonum_733(de->size); + } + + /* + * Some dipshit decided to store some other bit of information + * in the high byte of the file length. Truncate size in case + * this CDROM was mounted with the cruft option. + */ + + if (sbi->s_cruft) + inode->i_size &= 0x00ffffff; + + if (de->interleave[0]) { + printk(KERN_DEBUG ""ISOFS: Interleaved files not (yet) supported.\n""); + inode->i_size = 0; + } + + /* I have no idea what file_unit_size is used for, so + we will flag it for now */ + if (de->file_unit_size[0] != 0) { + printk(KERN_DEBUG ""ISOFS: File unit size != 0 for ISO file (%ld).\n"", + inode->i_ino); + } + + /* I have no idea what other flag bits are used for, so + we will flag it for now */ +#ifdef DEBUG + if((de->flags[-high_sierra] & ~2)!= 0){ + printk(KERN_DEBUG ""ISOFS: Unusual flag settings for ISO file "" + ""(%ld %x).\n"", + inode->i_ino, de->flags[-high_sierra]); + } +#endif + + inode->i_mtime.tv_sec = + inode->i_atime.tv_sec = + inode->i_ctime.tv_sec = iso_date(de->date, high_sierra); + inode->i_mtime.tv_nsec = + inode->i_atime.tv_nsec = + inode->i_ctime.tv_nsec = 0; + + ei->i_first_extent = (isonum_733(de->extent) + + isonum_711(de->ext_attr_length)); + + /* Set the number of blocks for stat() - should be done before RR */ + inode->i_blocks = (inode->i_size + 511) >> 9; + + /* + * Now test for possible Rock Ridge extensions which will override + * some of these numbers in the inode structure. + */ + + if (!high_sierra) { + parse_rock_ridge_inode(de, inode); + /* if we want uid/gid set, override the rock ridge setting */ + if (sbi->s_uid_set) + inode->i_uid = sbi->s_uid; + if (sbi->s_gid_set) + inode->i_gid = sbi->s_gid; + } + /* Now set final access rights if overriding rock ridge setting */ + if (S_ISDIR(inode->i_mode) && sbi->s_overriderockperm && + sbi->s_dmode != ISOFS_INVALID_MODE) + inode->i_mode = S_IFDIR | sbi->s_dmode; + if (S_ISREG(inode->i_mode) && sbi->s_overriderockperm && + sbi->s_fmode != ISOFS_INVALID_MODE) + inode->i_mode = S_IFREG | sbi->s_fmode; + + /* Install the inode operations vector */ + if (S_ISREG(inode->i_mode)) { + inode->i_fop = &generic_ro_fops; + switch (ei->i_file_format) { +#ifdef CONFIG_ZISOFS + case isofs_file_compressed: + inode->i_data.a_ops = &zisofs_aops; + break; +#endif + default: + inode->i_data.a_ops = &isofs_aops; + break; + } + } else if (S_ISDIR(inode->i_mode)) { + inode->i_op = &isofs_dir_inode_operations; + inode->i_fop = &isofs_dir_operations; + } else if (S_ISLNK(inode->i_mode)) { + inode->i_op = &page_symlink_inode_operations; + inode->i_data.a_ops = &isofs_symlink_aops; + } else + /* XXX - parse_rock_ridge_inode() had already set i_rdev. */ + init_special_inode(inode, inode->i_mode, inode->i_rdev); + + ret = 0; +out: + kfree(tmpde); + if (bh) + brelse(bh); + return ret; + +out_badread: + printk(KERN_WARNING ""ISOFS: unable to read i-node block\n""); +fail: + goto out; +} +",1,"static int isofs_read_inode(struct inode *inode) +static int isofs_read_inode(struct inode *inode, int relocated) + { + struct super_block *sb = inode->i_sb; + struct isofs_sb_info *sbi = ISOFS_SB(sb); + unsigned long bufsize = ISOFS_BUFFER_SIZE(inode); + unsigned long block; + int high_sierra = sbi->s_high_sierra; + struct buffer_head *bh = NULL; + struct iso_directory_record *de; + struct iso_directory_record *tmpde = NULL; + unsigned int de_len; + unsigned long offset; + struct iso_inode_info *ei = ISOFS_I(inode); + int ret = -EIO; + + block = ei->i_iget5_block; + bh = sb_bread(inode->i_sb, block); + if (!bh) + goto out_badread; + + offset = ei->i_iget5_offset; + + de = (struct iso_directory_record *) (bh->b_data + offset); + de_len = *(unsigned char *) de; + + if (offset + de_len > bufsize) { + int frag1 = bufsize - offset; + + tmpde = kmalloc(de_len, GFP_KERNEL); + if (tmpde == NULL) { + printk(KERN_INFO ""%s: out of memory\n"", __func__); + ret = -ENOMEM; + goto fail; + } + memcpy(tmpde, bh->b_data + offset, frag1); + brelse(bh); + bh = sb_bread(inode->i_sb, ++block); + if (!bh) + goto out_badread; + memcpy((char *)tmpde+frag1, bh->b_data, de_len - frag1); + de = tmpde; + } + + inode->i_ino = isofs_get_ino(ei->i_iget5_block, + ei->i_iget5_offset, + ISOFS_BUFFER_BITS(inode)); + + /* Assume it is a normal-format file unless told otherwise */ + ei->i_file_format = isofs_file_normal; + + if (de->flags[-high_sierra] & 2) { + if (sbi->s_dmode != ISOFS_INVALID_MODE) + inode->i_mode = S_IFDIR | sbi->s_dmode; + else + inode->i_mode = S_IFDIR | S_IRUGO | S_IXUGO; + set_nlink(inode, 1); /* + * Set to 1. We know there are 2, but + * the find utility tries to optimize + * if it is 2, and it screws up. It is + * easier to give 1 which tells find to + * do it the hard way. + */ + } else { + if (sbi->s_fmode != ISOFS_INVALID_MODE) { + inode->i_mode = S_IFREG | sbi->s_fmode; + } else { + /* + * Set default permissions: r-x for all. The disc + * could be shared with DOS machines so virtually + * anything could be a valid executable. + */ + inode->i_mode = S_IFREG | S_IRUGO | S_IXUGO; + } + set_nlink(inode, 1); + } + inode->i_uid = sbi->s_uid; + inode->i_gid = sbi->s_gid; + inode->i_blocks = 0; + + ei->i_format_parm[0] = 0; + ei->i_format_parm[1] = 0; + ei->i_format_parm[2] = 0; + + ei->i_section_size = isonum_733(de->size); + if (de->flags[-high_sierra] & 0x80) { + ret = isofs_read_level3_size(inode); + if (ret < 0) + goto fail; + ret = -EIO; + } else { + ei->i_next_section_block = 0; + ei->i_next_section_offset = 0; + inode->i_size = isonum_733(de->size); + } + + /* + * Some dipshit decided to store some other bit of information + * in the high byte of the file length. Truncate size in case + * this CDROM was mounted with the cruft option. + */ + + if (sbi->s_cruft) + inode->i_size &= 0x00ffffff; + + if (de->interleave[0]) { + printk(KERN_DEBUG ""ISOFS: Interleaved files not (yet) supported.\n""); + inode->i_size = 0; + } + + /* I have no idea what file_unit_size is used for, so + we will flag it for now */ + if (de->file_unit_size[0] != 0) { + printk(KERN_DEBUG ""ISOFS: File unit size != 0 for ISO file (%ld).\n"", + inode->i_ino); + } + + /* I have no idea what other flag bits are used for, so + we will flag it for now */ +#ifdef DEBUG + if((de->flags[-high_sierra] & ~2)!= 0){ + printk(KERN_DEBUG ""ISOFS: Unusual flag settings for ISO file "" + ""(%ld %x).\n"", + inode->i_ino, de->flags[-high_sierra]); + } +#endif + + inode->i_mtime.tv_sec = + inode->i_atime.tv_sec = + inode->i_ctime.tv_sec = iso_date(de->date, high_sierra); + inode->i_mtime.tv_nsec = + inode->i_atime.tv_nsec = + inode->i_ctime.tv_nsec = 0; + + ei->i_first_extent = (isonum_733(de->extent) + + isonum_711(de->ext_attr_length)); + + /* Set the number of blocks for stat() - should be done before RR */ + inode->i_blocks = (inode->i_size + 511) >> 9; + + /* + * Now test for possible Rock Ridge extensions which will override + * some of these numbers in the inode structure. + */ + + if (!high_sierra) { + parse_rock_ridge_inode(de, inode, relocated); + /* if we want uid/gid set, override the rock ridge setting */ + if (sbi->s_uid_set) + inode->i_uid = sbi->s_uid; + if (sbi->s_gid_set) + inode->i_gid = sbi->s_gid; + } + /* Now set final access rights if overriding rock ridge setting */ + if (S_ISDIR(inode->i_mode) && sbi->s_overriderockperm && + sbi->s_dmode != ISOFS_INVALID_MODE) + inode->i_mode = S_IFDIR | sbi->s_dmode; + if (S_ISREG(inode->i_mode) && sbi->s_overriderockperm && + sbi->s_fmode != ISOFS_INVALID_MODE) + inode->i_mode = S_IFREG | sbi->s_fmode; + + /* Install the inode operations vector */ + if (S_ISREG(inode->i_mode)) { + inode->i_fop = &generic_ro_fops; + switch (ei->i_file_format) { +#ifdef CONFIG_ZISOFS + case isofs_file_compressed: + inode->i_data.a_ops = &zisofs_aops; + break; +#endif + default: + inode->i_data.a_ops = &isofs_aops; + break; + } + } else if (S_ISDIR(inode->i_mode)) { + inode->i_op = &isofs_dir_inode_operations; + inode->i_fop = &isofs_dir_operations; + } else if (S_ISLNK(inode->i_mode)) { + inode->i_op = &page_symlink_inode_operations; + inode->i_data.a_ops = &isofs_symlink_aops; + } else + /* XXX - parse_rock_ridge_inode() had already set i_rdev. */ + init_special_inode(inode, inode->i_mode, inode->i_rdev); + + ret = 0; +out: + kfree(tmpde); + if (bh) + brelse(bh); + return ret; + +out_badread: + printk(KERN_WARNING ""ISOFS: unable to read i-node block\n""); +fail: + goto out; +} +","@@ -61,7 +61,7 @@ static void isofs_put_super(struct super_block *sb) + return; + } + +-static int isofs_read_inode(struct inode *); ++static int isofs_read_inode(struct inode *, int relocated); + static int isofs_statfs (struct dentry *, struct kstatfs *); + + static struct kmem_cache *isofs_inode_cachep; +@@ -1259,7 +1259,7 @@ static int isofs_read_level3_size(struct inode *inode) + goto out; + } + +-static int isofs_read_inode(struct inode *inode) ++static int isofs_read_inode(struct inode *inode, int relocated) + { + struct super_block *sb = inode->i_sb; + struct isofs_sb_info *sbi = ISOFS_SB(sb); +@@ -1404,7 +1404,7 @@ static int isofs_read_inode(struct inode *inode) + */ + + if (!high_sierra) { +- parse_rock_ridge_inode(de, inode); ++ parse_rock_ridge_inode(de, inode, relocated); + /* if we want uid/gid set, override the rock ridge setting */ + if (sbi->s_uid_set) + inode->i_uid = sbi->s_uid; +@@ -1483,9 +1483,10 @@ static int isofs_iget5_set(struct inode *ino, void *data) + * offset that point to the underlying meta-data for the inode. The + * code below is otherwise similar to the iget() code in + * include/linux/fs.h */ +-struct inode *isofs_iget(struct super_block *sb, +- unsigned long block, +- unsigned long offset) ++struct inode *__isofs_iget(struct super_block *sb, ++ unsigned long block, ++ unsigned long offset, ++ int relocated) + { + unsigned long hashval; + struct inode *inode; +@@ -1507,7 +1508,7 @@ struct inode *isofs_iget(struct super_block *sb, + return ERR_PTR(-ENOMEM); + + if (inode->i_state & I_NEW) { +- ret = isofs_read_inode(inode); ++ ret = isofs_read_inode(inode, relocated); + if (ret < 0) { + iget_failed(inode); + inode = ERR_PTR(ret);",1779,2110,4096 +17794," irc_server_gnutls_callback (void *data, gnutls_session_t tls_session, + const gnutls_datum_t *req_ca, int nreq, + const gnutls_pk_algorithm_t *pk_algos, + int pk_algos_len, gnutls_retr_st *answer) + { + struct t_irc_server *server; + gnutls_retr_st tls_struct; + const gnutls_datum_t *cert_list; + gnutls_datum_t filedatum; + unsigned int cert_list_len, status; + time_t cert_time; + char *cert_path0, *cert_path1, *cert_path2, *cert_str, *hostname; + const char *weechat_dir; + int rc, ret, i, j, hostname_match; +#if LIBGNUTLS_VERSION_NUMBER >= 0x010706 + gnutls_datum_t cinfo; + int rinfo; +#endif + + /* make C compiler happy */ + (void) req_ca; + (void) nreq; + (void) pk_algos; + (void) pk_algos_len; + + rc = 0; + + if (!data) + return -1; + + server = (struct t_irc_server *) data; + hostname = server->current_address; + hostname = server->current_address; + hostname_match = 0; + + weechat_printf (server->buffer, + _(""gnutls: connected using %d-bit Diffie-Hellman shared "" + ""secret exchange""), + IRC_SERVER_OPTION_INTEGER (server, + IRC_SERVER_OPTION_SSL_DHKEY_SIZE)); + if (gnutls_certificate_verify_peers2 (tls_session, &status) < 0) + { + weechat_printf (server->buffer, + _(""%sgnutls: error while checking peer's certificate""), + weechat_prefix (""error"")); + rc = -1; + } + else + { + /* some checks */ + if (status & GNUTLS_CERT_INVALID) + { + weechat_printf (server->buffer, + _(""%sgnutls: peer's certificate is NOT trusted""), + weechat_prefix (""error"")); + rc = -1; + } + else + { + weechat_printf (server->buffer, + _(""gnutls: peer's certificate is trusted"")); + } + if (status & GNUTLS_CERT_SIGNER_NOT_FOUND) + { + weechat_printf (server->buffer, + _(""%sgnutls: peer's certificate issuer is unknown""), + weechat_prefix (""error"")); + rc = -1; + } + if (status & GNUTLS_CERT_REVOKED) + { + weechat_printf (server->buffer, + _(""%sgnutls: the certificate has been revoked""), + weechat_prefix (""error"")); + rc = -1; + } + /* check certificates */ + if (gnutls_x509_crt_init (&cert_temp) >= 0) + { + cert_list = gnutls_certificate_get_peers (tls_session, &cert_list_len); + if (cert_list) + { + weechat_printf (server->buffer, + NG_(""gnutls: receiving %d certificate"", + ""gnutls: receiving %d certificates"", + cert_list_len), + cert_list_len); + for (i = 0, j = (int) cert_list_len; i < j; i++) + { + if (gnutls_x509_crt_import (cert_temp, &cert_list[i], GNUTLS_X509_FMT_DER) >= 0) + { + /* checking if hostname matches in the first certificate */ + if (i == 0 && gnutls_x509_crt_check_hostname (cert_temp, hostname) != 0) + { + hostname_match = 1; + } + #if LIBGNUTLS_VERSION_NUMBER >= 0x010706 + /* displaying infos about certificate */ + #if LIBGNUTLS_VERSION_NUMBER < 0x020400 + rinfo = gnutls_x509_crt_print (cert_temp, GNUTLS_X509_CRT_ONELINE, &cinfo); + #else + rinfo = gnutls_x509_crt_print (cert_temp, GNUTLS_CRT_PRINT_ONELINE, &cinfo); + #endif + if (rinfo == 0) + { + weechat_printf (server->buffer, + _("" - certificate[%d] info:""), i + 1); + weechat_printf (server->buffer, + "" - %s"", cinfo.data); + gnutls_free (cinfo.data); + } + #endif + /* check expiration date */ + cert_time = gnutls_x509_crt_get_expiration_time (cert_temp); + if (cert_time < time(NULL)) + { + weechat_printf (server->buffer, + _(""%sgnutls: certificate has expired""), + weechat_prefix (""error"")); + rc = -1; + } + /* check expiration date */ + cert_time = gnutls_x509_crt_get_activation_time (cert_temp); + if (cert_time > time(NULL)) + { + weechat_printf (server->buffer, + _(""%sgnutls: certificate is not yet activated""), + weechat_prefix (""error"")); + rc = -1; + } + } + } + if (hostname_match == 0) + { + weechat_printf (server->buffer, + _(""%sgnutls: the hostname in the "" + ""certificate does NOT match \""%s\""""), + weechat_prefix (""error""), hostname); + rc = -1; + } + } + } + } + /* using client certificate if it exists */ + cert_path0 = (char *) IRC_SERVER_OPTION_STRING(server, + IRC_SERVER_OPTION_SSL_CERT); + if (cert_path0 && cert_path0[0]) + { + weechat_dir = weechat_info_get (""weechat_dir"", """"); + cert_path1 = weechat_string_replace (cert_path0, ""%h"", weechat_dir); + cert_path2 = (cert_path1) ? + weechat_string_expand_home (cert_path1) : NULL; + if (cert_path2) + { + cert_str = weechat_file_get_content (cert_path2); + if (cert_str) + { + weechat_printf (server->buffer, + _(""gnutls: sending one certificate"")); + filedatum.data = (unsigned char *) cert_str; + filedatum.size = strlen (cert_str); + /* certificate */ + gnutls_x509_crt_init (&server->tls_cert); + gnutls_x509_crt_import (server->tls_cert, &filedatum, + GNUTLS_X509_FMT_PEM); + /* key */ + gnutls_x509_privkey_init (&server->tls_cert_key); + ret = gnutls_x509_privkey_import (server->tls_cert_key, + &filedatum, + GNUTLS_X509_FMT_PEM); + if (ret < 0) + { + ret = gnutls_x509_privkey_import_pkcs8 (server->tls_cert_key, + &filedatum, + GNUTLS_X509_FMT_PEM, + NULL, + GNUTLS_PKCS_PLAIN); + } + if (ret < 0) + { + weechat_printf (server->buffer, + _(""%sgnutls: invalid certificate \""%s\"", "" + ""error: %s""), + weechat_prefix (""error""), cert_path2, + gnutls_strerror (ret)); + rc = -1; + } + else + { + tls_struct.type = GNUTLS_CRT_X509; + tls_struct.ncerts = 1; + tls_struct.deinit_all = 0; + tls_struct.cert.x509 = &server->tls_cert; + tls_struct.key.x509 = server->tls_cert_key; + #if LIBGNUTLS_VERSION_NUMBER >= 0x010706 + /* client certificate info */ + #if LIBGNUTLS_VERSION_NUMBER < 0x020400 + rinfo = gnutls_x509_crt_print (server->tls_cert, + GNUTLS_X509_CRT_ONELINE, + &cinfo); + #else + rinfo = gnutls_x509_crt_print (server->tls_cert, + GNUTLS_CRT_PRINT_ONELINE, + &cinfo); + #endif + if (rinfo == 0) + { + weechat_printf (server->buffer, + _("" - client certificate info (%s):""), + cert_path2); + weechat_printf (server->buffer, "" - %s"", cinfo.data); + gnutls_free (cinfo.data); + } + #endif + memcpy (answer, &tls_struct, sizeof (gnutls_retr_st)); + free (cert_str); + } + } + else + { + weechat_printf (server->buffer, + _(""%sgnutls: unable to read certifcate \""%s\""""), + weechat_prefix (""error""), cert_path2); + } + } + if (cert_path1) + free (cert_path1); + if (cert_path2) + free (cert_path2); + } + + /* an error should stop the handshake unless the user doesn't care */ + return rc; +} +",1," irc_server_gnutls_callback (void *data, gnutls_session_t tls_session, + const gnutls_datum_t *req_ca, int nreq, + const gnutls_pk_algorithm_t *pk_algos, + int pk_algos_len, gnutls_retr_st *answer, + int action) + { + struct t_irc_server *server; + gnutls_retr_st tls_struct; + const gnutls_datum_t *cert_list; + gnutls_datum_t filedatum; + unsigned int cert_list_len, status; + time_t cert_time; + char *cert_path0, *cert_path1, *cert_path2, *cert_str, *hostname; + const char *weechat_dir; + int rc, ret, i, j, hostname_match; +#if LIBGNUTLS_VERSION_NUMBER >= 0x010706 + gnutls_datum_t cinfo; + int rinfo; +#endif + + /* make C compiler happy */ + (void) req_ca; + (void) nreq; + (void) pk_algos; + (void) pk_algos_len; + + rc = 0; + + if (!data) + return -1; + + server = (struct t_irc_server *) data; + hostname = server->current_address; + hostname = server->current_address; + hostname_match = 0; + + if (action == WEECHAT_HOOK_CONNECT_GNUTLS_CB_VERIFY_CERT) + { + weechat_printf (server->buffer, + _(""gnutls: connected using %d-bit Diffie-Hellman shared "" + ""secret exchange""), + IRC_SERVER_OPTION_INTEGER (server, + IRC_SERVER_OPTION_SSL_DHKEY_SIZE)); + if (gnutls_certificate_verify_peers2 (tls_session, &status) < 0) + { + weechat_printf (server->buffer, + _(""%sgnutls: error while checking peer's certificate""), + weechat_prefix (""error"")); + rc = -1; + } + else + { + /* some checks */ + if (status & GNUTLS_CERT_INVALID) + { + weechat_printf (server->buffer, + _(""%sgnutls: peer's certificate is NOT trusted""), + weechat_prefix (""error"")); + rc = -1; + } + else + { + weechat_printf (server->buffer, + _(""gnutls: peer's certificate is trusted"")); + } + if (status & GNUTLS_CERT_SIGNER_NOT_FOUND) + { + weechat_printf (server->buffer, + _(""%sgnutls: peer's certificate issuer is unknown""), + weechat_prefix (""error"")); + rc = -1; + } + if (status & GNUTLS_CERT_REVOKED) + { + weechat_printf (server->buffer, + _(""%sgnutls: the certificate has been revoked""), + weechat_prefix (""error"")); + rc = -1; + } + + /* check certificates */ + if (gnutls_x509_crt_init (&cert_temp) >= 0) + { + cert_list = gnutls_certificate_get_peers (tls_session, &cert_list_len); + if (cert_list) + { + weechat_printf (server->buffer, + NG_(""gnutls: receiving %d certificate"", + ""gnutls: receiving %d certificates"", + cert_list_len), + cert_list_len); + for (i = 0, j = (int) cert_list_len; i < j; i++) + { + if (gnutls_x509_crt_import (cert_temp, &cert_list[i], GNUTLS_X509_FMT_DER) >= 0) + { + /* checking if hostname matches in the first certificate */ + if ((i == 0) && (gnutls_x509_crt_check_hostname (cert_temp, hostname) != 0)) + { + hostname_match = 1; + } + #if LIBGNUTLS_VERSION_NUMBER >= 0x010706 + /* displaying infos about certificate */ + #if LIBGNUTLS_VERSION_NUMBER < 0x020400 + rinfo = gnutls_x509_crt_print (cert_temp, GNUTLS_X509_CRT_ONELINE, &cinfo); + #else + rinfo = gnutls_x509_crt_print (cert_temp, GNUTLS_CRT_PRINT_ONELINE, &cinfo); + #endif + if (rinfo == 0) + { + weechat_printf (server->buffer, + _("" - certificate[%d] info:""), i + 1); + weechat_printf (server->buffer, + "" - %s"", cinfo.data); + gnutls_free (cinfo.data); + } + #endif + /* check expiration date */ + cert_time = gnutls_x509_crt_get_expiration_time (cert_temp); + if (cert_time < time (NULL)) + { + weechat_printf (server->buffer, + _(""%sgnutls: certificate has expired""), + weechat_prefix (""error"")); + rc = -1; + } + /* check activation date */ + cert_time = gnutls_x509_crt_get_activation_time (cert_temp); + if (cert_time > time (NULL)) + { + weechat_printf (server->buffer, + _(""%sgnutls: certificate is not yet activated""), + weechat_prefix (""error"")); + rc = -1; + } + } + } + if (hostname_match == 0) + { + weechat_printf (server->buffer, + _(""%sgnutls: the hostname in the "" + ""certificate does NOT match \""%s\""""), + weechat_prefix (""error""), hostname); + rc = -1; + } + } + } + } + } + else if (action == WEECHAT_HOOK_CONNECT_GNUTLS_CB_SET_CERT) + { + /* using client certificate if it exists */ + cert_path0 = (char *) IRC_SERVER_OPTION_STRING(server, + IRC_SERVER_OPTION_SSL_CERT); + if (cert_path0 && cert_path0[0]) + { + weechat_dir = weechat_info_get (""weechat_dir"", """"); + cert_path1 = weechat_string_replace (cert_path0, ""%h"", weechat_dir); + cert_path2 = (cert_path1) ? + weechat_string_expand_home (cert_path1) : NULL; + + if (cert_path2) + { + cert_str = weechat_file_get_content (cert_path2); + if (cert_str) + { + weechat_printf (server->buffer, + _(""gnutls: sending one certificate"")); + + filedatum.data = (unsigned char *) cert_str; + filedatum.size = strlen (cert_str); + + /* certificate */ + gnutls_x509_crt_init (&server->tls_cert); + gnutls_x509_crt_import (server->tls_cert, &filedatum, + GNUTLS_X509_FMT_PEM); + + /* key */ + gnutls_x509_privkey_init (&server->tls_cert_key); + ret = gnutls_x509_privkey_import (server->tls_cert_key, + &filedatum, + GNUTLS_X509_FMT_PEM); + if (ret < 0) + { + ret = gnutls_x509_privkey_import_pkcs8 (server->tls_cert_key, + &filedatum, + GNUTLS_X509_FMT_PEM, + NULL, + GNUTLS_PKCS_PLAIN); + } + if (ret < 0) + { + weechat_printf (server->buffer, + _(""%sgnutls: invalid certificate \""%s\"", "" + ""error: %s""), + weechat_prefix (""error""), cert_path2, + gnutls_strerror (ret)); + rc = -1; + } + else + { + tls_struct.type = GNUTLS_CRT_X509; + tls_struct.ncerts = 1; + tls_struct.deinit_all = 0; + tls_struct.cert.x509 = &server->tls_cert; + tls_struct.key.x509 = server->tls_cert_key; + #if LIBGNUTLS_VERSION_NUMBER >= 0x010706 + /* client certificate info */ + #if LIBGNUTLS_VERSION_NUMBER < 0x020400 + rinfo = gnutls_x509_crt_print (server->tls_cert, + GNUTLS_X509_CRT_ONELINE, + &cinfo); + #else + rinfo = gnutls_x509_crt_print (server->tls_cert, + GNUTLS_CRT_PRINT_ONELINE, + &cinfo); + #endif + if (rinfo == 0) + { + weechat_printf (server->buffer, + _("" - client certificate info (%s):""), + cert_path2); + weechat_printf (server->buffer, "" - %s"", cinfo.data); + gnutls_free (cinfo.data); + } + #endif + memcpy (answer, &tls_struct, sizeof (gnutls_retr_st)); + free (cert_str); + } + } + else + { + weechat_printf (server->buffer, + _(""%sgnutls: unable to read certifcate \""%s\""""), + weechat_prefix (""error""), cert_path2); + } + } + + if (cert_path1) + free (cert_path1); + if (cert_path2) + free (cert_path2); + } + } + + /* an error should stop the handshake unless the user doesn't care */ + return rc; +} +","@@ -2805,7 +2805,8 @@ int + irc_server_gnutls_callback (void *data, gnutls_session_t tls_session, + const gnutls_datum_t *req_ca, int nreq, + const gnutls_pk_algorithm_t *pk_algos, +- int pk_algos_len, gnutls_retr_st *answer) ++ int pk_algos_len, gnutls_retr_st *answer, ++ int action) + { + struct t_irc_server *server; + gnutls_retr_st tls_struct; +@@ -2837,207 +2838,212 @@ irc_server_gnutls_callback (void *data, gnutls_session_t tls_session, + hostname = server->current_address; + hostname_match = 0; + +- weechat_printf (server->buffer, +- _(""gnutls: connected using %d-bit Diffie-Hellman shared "" +- ""secret exchange""), +- IRC_SERVER_OPTION_INTEGER (server, +- IRC_SERVER_OPTION_SSL_DHKEY_SIZE)); +- if (gnutls_certificate_verify_peers2 (tls_session, &status) < 0) ++ if (action == WEECHAT_HOOK_CONNECT_GNUTLS_CB_VERIFY_CERT) + { + weechat_printf (server->buffer, +- _(""%sgnutls: error while checking peer's certificate""), +- weechat_prefix (""error"")); +- rc = -1; +- } +- else +- { +- /* some checks */ +- if (status & GNUTLS_CERT_INVALID) ++ _(""gnutls: connected using %d-bit Diffie-Hellman shared "" ++ ""secret exchange""), ++ IRC_SERVER_OPTION_INTEGER (server, ++ IRC_SERVER_OPTION_SSL_DHKEY_SIZE)); ++ if (gnutls_certificate_verify_peers2 (tls_session, &status) < 0) + { + weechat_printf (server->buffer, +- _(""%sgnutls: peer's certificate is NOT trusted""), ++ _(""%sgnutls: error while checking peer's certificate""), + weechat_prefix (""error"")); + rc = -1; + } + else + { +- weechat_printf (server->buffer, +- _(""gnutls: peer's certificate is trusted"")); +- } +- if (status & GNUTLS_CERT_SIGNER_NOT_FOUND) +- { +- weechat_printf (server->buffer, +- _(""%sgnutls: peer's certificate issuer is unknown""), +- weechat_prefix (""error"")); +- rc = -1; +- } +- if (status & GNUTLS_CERT_REVOKED) +- { +- weechat_printf (server->buffer, +- _(""%sgnutls: the certificate has been revoked""), +- weechat_prefix (""error"")); +- rc = -1; +- } +- +- /* check certificates */ +- if (gnutls_x509_crt_init (&cert_temp) >= 0) +- { +- cert_list = gnutls_certificate_get_peers (tls_session, &cert_list_len); +- if (cert_list) ++ /* some checks */ ++ if (status & GNUTLS_CERT_INVALID) ++ { ++ weechat_printf (server->buffer, ++ _(""%sgnutls: peer's certificate is NOT trusted""), ++ weechat_prefix (""error"")); ++ rc = -1; ++ } ++ else ++ { ++ weechat_printf (server->buffer, ++ _(""gnutls: peer's certificate is trusted"")); ++ } ++ if (status & GNUTLS_CERT_SIGNER_NOT_FOUND) + { + weechat_printf (server->buffer, +- NG_(""gnutls: receiving %d certificate"", +- ""gnutls: receiving %d certificates"", +- cert_list_len), +- cert_list_len); +- for (i = 0, j = (int) cert_list_len; i < j; i++) ++ _(""%sgnutls: peer's certificate issuer is unknown""), ++ weechat_prefix (""error"")); ++ rc = -1; ++ } ++ if (status & GNUTLS_CERT_REVOKED) ++ { ++ weechat_printf (server->buffer, ++ _(""%sgnutls: the certificate has been revoked""), ++ weechat_prefix (""error"")); ++ rc = -1; ++ } ++ ++ /* check certificates */ ++ if (gnutls_x509_crt_init (&cert_temp) >= 0) ++ { ++ cert_list = gnutls_certificate_get_peers (tls_session, &cert_list_len); ++ if (cert_list) + { +- if (gnutls_x509_crt_import (cert_temp, &cert_list[i], GNUTLS_X509_FMT_DER) >= 0) ++ weechat_printf (server->buffer, ++ NG_(""gnutls: receiving %d certificate"", ++ ""gnutls: receiving %d certificates"", ++ cert_list_len), ++ cert_list_len); ++ for (i = 0, j = (int) cert_list_len; i < j; i++) + { +- /* checking if hostname matches in the first certificate */ +- if (i == 0 && gnutls_x509_crt_check_hostname (cert_temp, hostname) != 0) ++ if (gnutls_x509_crt_import (cert_temp, &cert_list[i], GNUTLS_X509_FMT_DER) >= 0) + { +- hostname_match = 1; +- } ++ /* checking if hostname matches in the first certificate */ ++ if ((i == 0) && (gnutls_x509_crt_check_hostname (cert_temp, hostname) != 0)) ++ { ++ hostname_match = 1; ++ } + #if LIBGNUTLS_VERSION_NUMBER >= 0x010706 +- /* displaying infos about certificate */ ++ /* displaying infos about certificate */ + #if LIBGNUTLS_VERSION_NUMBER < 0x020400 +- rinfo = gnutls_x509_crt_print (cert_temp, GNUTLS_X509_CRT_ONELINE, &cinfo); ++ rinfo = gnutls_x509_crt_print (cert_temp, GNUTLS_X509_CRT_ONELINE, &cinfo); + #else +- rinfo = gnutls_x509_crt_print (cert_temp, GNUTLS_CRT_PRINT_ONELINE, &cinfo); ++ rinfo = gnutls_x509_crt_print (cert_temp, GNUTLS_CRT_PRINT_ONELINE, &cinfo); + #endif +- if (rinfo == 0) +- { +- weechat_printf (server->buffer, +- _("" - certificate[%d] info:""), i + 1); +- weechat_printf (server->buffer, +- "" - %s"", cinfo.data); +- gnutls_free (cinfo.data); +- } ++ if (rinfo == 0) ++ { ++ weechat_printf (server->buffer, ++ _("" - certificate[%d] info:""), i + 1); ++ weechat_printf (server->buffer, ++ "" - %s"", cinfo.data); ++ gnutls_free (cinfo.data); ++ } + #endif +- /* check expiration date */ +- cert_time = gnutls_x509_crt_get_expiration_time (cert_temp); +- if (cert_time < time(NULL)) +- { +- weechat_printf (server->buffer, +- _(""%sgnutls: certificate has expired""), +- weechat_prefix (""error"")); +- rc = -1; +- } +- /* check expiration date */ +- cert_time = gnutls_x509_crt_get_activation_time (cert_temp); +- if (cert_time > time(NULL)) +- { +- weechat_printf (server->buffer, +- _(""%sgnutls: certificate is not yet activated""), +- weechat_prefix (""error"")); +- rc = -1; ++ /* check expiration date */ ++ cert_time = gnutls_x509_crt_get_expiration_time (cert_temp); ++ if (cert_time < time (NULL)) ++ { ++ weechat_printf (server->buffer, ++ _(""%sgnutls: certificate has expired""), ++ weechat_prefix (""error"")); ++ rc = -1; ++ } ++ /* check activation date */ ++ cert_time = gnutls_x509_crt_get_activation_time (cert_temp); ++ if (cert_time > time (NULL)) ++ { ++ weechat_printf (server->buffer, ++ _(""%sgnutls: certificate is not yet activated""), ++ weechat_prefix (""error"")); ++ rc = -1; ++ } + } + } +- } +- if (hostname_match == 0) +- { +- weechat_printf (server->buffer, +- _(""%sgnutls: the hostname in the "" +- ""certificate does NOT match \""%s\""""), +- weechat_prefix (""error""), hostname); +- rc = -1; ++ if (hostname_match == 0) ++ { ++ weechat_printf (server->buffer, ++ _(""%sgnutls: the hostname in the "" ++ ""certificate does NOT match \""%s\""""), ++ weechat_prefix (""error""), hostname); ++ rc = -1; ++ } + } + } + } + } +- +- /* using client certificate if it exists */ +- cert_path0 = (char *) IRC_SERVER_OPTION_STRING(server, +- IRC_SERVER_OPTION_SSL_CERT); +- if (cert_path0 && cert_path0[0]) ++ else if (action == WEECHAT_HOOK_CONNECT_GNUTLS_CB_SET_CERT) + { +- weechat_dir = weechat_info_get (""weechat_dir"", """"); +- cert_path1 = weechat_string_replace (cert_path0, ""%h"", weechat_dir); +- cert_path2 = (cert_path1) ? +- weechat_string_expand_home (cert_path1) : NULL; +- +- if (cert_path2) ++ /* using client certificate if it exists */ ++ cert_path0 = (char *) IRC_SERVER_OPTION_STRING(server, ++ IRC_SERVER_OPTION_SSL_CERT); ++ if (cert_path0 && cert_path0[0]) + { +- cert_str = weechat_file_get_content (cert_path2); +- if (cert_str) ++ weechat_dir = weechat_info_get (""weechat_dir"", """"); ++ cert_path1 = weechat_string_replace (cert_path0, ""%h"", weechat_dir); ++ cert_path2 = (cert_path1) ? ++ weechat_string_expand_home (cert_path1) : NULL; ++ ++ if (cert_path2) + { +- weechat_printf (server->buffer, +- _(""gnutls: sending one certificate"")); +- +- filedatum.data = (unsigned char *) cert_str; +- filedatum.size = strlen (cert_str); +- +- /* certificate */ +- gnutls_x509_crt_init (&server->tls_cert); +- gnutls_x509_crt_import (server->tls_cert, &filedatum, +- GNUTLS_X509_FMT_PEM); +- +- /* key */ +- gnutls_x509_privkey_init (&server->tls_cert_key); +- ret = gnutls_x509_privkey_import (server->tls_cert_key, +- &filedatum, +- GNUTLS_X509_FMT_PEM); +- if (ret < 0) +- { +- ret = gnutls_x509_privkey_import_pkcs8 (server->tls_cert_key, +- &filedatum, +- GNUTLS_X509_FMT_PEM, +- NULL, +- GNUTLS_PKCS_PLAIN); +- } +- if (ret < 0) ++ cert_str = weechat_file_get_content (cert_path2); ++ if (cert_str) + { + weechat_printf (server->buffer, +- _(""%sgnutls: invalid certificate \""%s\"", "" +- ""error: %s""), +- weechat_prefix (""error""), cert_path2, +- gnutls_strerror (ret)); +- rc = -1; +- } +- else +- { +- tls_struct.type = GNUTLS_CRT_X509; +- tls_struct.ncerts = 1; +- tls_struct.deinit_all = 0; +- tls_struct.cert.x509 = &server->tls_cert; +- tls_struct.key.x509 = server->tls_cert_key; ++ _(""gnutls: sending one certificate"")); ++ ++ filedatum.data = (unsigned char *) cert_str; ++ filedatum.size = strlen (cert_str); ++ ++ /* certificate */ ++ gnutls_x509_crt_init (&server->tls_cert); ++ gnutls_x509_crt_import (server->tls_cert, &filedatum, ++ GNUTLS_X509_FMT_PEM); ++ ++ /* key */ ++ gnutls_x509_privkey_init (&server->tls_cert_key); ++ ret = gnutls_x509_privkey_import (server->tls_cert_key, ++ &filedatum, ++ GNUTLS_X509_FMT_PEM); ++ if (ret < 0) ++ { ++ ret = gnutls_x509_privkey_import_pkcs8 (server->tls_cert_key, ++ &filedatum, ++ GNUTLS_X509_FMT_PEM, ++ NULL, ++ GNUTLS_PKCS_PLAIN); ++ } ++ if (ret < 0) ++ { ++ weechat_printf (server->buffer, ++ _(""%sgnutls: invalid certificate \""%s\"", "" ++ ""error: %s""), ++ weechat_prefix (""error""), cert_path2, ++ gnutls_strerror (ret)); ++ rc = -1; ++ } ++ else ++ { ++ tls_struct.type = GNUTLS_CRT_X509; ++ tls_struct.ncerts = 1; ++ tls_struct.deinit_all = 0; ++ tls_struct.cert.x509 = &server->tls_cert; ++ tls_struct.key.x509 = server->tls_cert_key; + #if LIBGNUTLS_VERSION_NUMBER >= 0x010706 +- /* client certificate info */ ++ /* client certificate info */ + #if LIBGNUTLS_VERSION_NUMBER < 0x020400 +- rinfo = gnutls_x509_crt_print (server->tls_cert, +- GNUTLS_X509_CRT_ONELINE, +- &cinfo); ++ rinfo = gnutls_x509_crt_print (server->tls_cert, ++ GNUTLS_X509_CRT_ONELINE, ++ &cinfo); + #else +- rinfo = gnutls_x509_crt_print (server->tls_cert, +- GNUTLS_CRT_PRINT_ONELINE, +- &cinfo); ++ rinfo = gnutls_x509_crt_print (server->tls_cert, ++ GNUTLS_CRT_PRINT_ONELINE, ++ &cinfo); + #endif +- if (rinfo == 0) +- { +- weechat_printf (server->buffer, +- _("" - client certificate info (%s):""), +- cert_path2); +- weechat_printf (server->buffer, "" - %s"", cinfo.data); +- gnutls_free (cinfo.data); +- } ++ if (rinfo == 0) ++ { ++ weechat_printf (server->buffer, ++ _("" - client certificate info (%s):""), ++ cert_path2); ++ weechat_printf (server->buffer, "" - %s"", cinfo.data); ++ gnutls_free (cinfo.data); ++ } + #endif +- memcpy (answer, &tls_struct, sizeof (gnutls_retr_st)); +- free (cert_str); ++ memcpy (answer, &tls_struct, sizeof (gnutls_retr_st)); ++ free (cert_str); ++ } ++ } ++ else ++ { ++ weechat_printf (server->buffer, ++ _(""%sgnutls: unable to read certifcate \""%s\""""), ++ weechat_prefix (""error""), cert_path2); + } + } +- else +- { +- weechat_printf (server->buffer, +- _(""%sgnutls: unable to read certifcate \""%s\""""), +- weechat_prefix (""error""), cert_path2); +- } ++ ++ if (cert_path1) ++ free (cert_path1); ++ if (cert_path2) ++ free (cert_path2); + } +- +- if (cert_path1) +- free (cert_path1); +- if (cert_path2) +- free (cert_path2); + } + + /* an error should stop the handshake unless the user doesn't care */",2060,2391,4096 +18299,"babel_print_v2(netdissect_options *ndo, + const u_char *cp, u_int length) +{ + u_int i; + u_short bodylen; + u_char v4_prefix[16] = + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0, 0, 0, 0 }; + u_char v6_prefix[16] = {0}; + + ND_TCHECK2(*cp, 4); + if (length < 4) + goto invalid; + bodylen = EXTRACT_16BITS(cp + 2); + ND_PRINT((ndo, "" (%u)"", bodylen)); + + /* Process the TLVs in the body */ + i = 0; + while(i < bodylen) { + const u_char *message; + u_int type, len; + + message = cp + 4 + i; + + ND_TCHECK2(*message, 1); + if((type = message[0]) == MESSAGE_PAD1) { + ND_PRINT((ndo, ndo->ndo_vflag ? ""\n\tPad 1"" : "" pad1"")); + i += 1; + continue; + } + + ND_TCHECK2(*message, 2); + ICHECK(i, 2); + len = message[1]; + + ND_TCHECK2(*message, 2 + len); + ICHECK(i, 2 + len); + + switch(type) { + case MESSAGE_PADN: { + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" padN"")); + else + ND_PRINT((ndo, ""\n\tPad %d"", len + 2)); + } + break; + + case MESSAGE_ACK_REQ: { + u_short nonce, interval; + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" ack-req"")); + else { + ND_PRINT((ndo, ""\n\tAcknowledgment Request "")); + if(len < 6) goto invalid; + nonce = EXTRACT_16BITS(message + 4); + interval = EXTRACT_16BITS(message + 6); + ND_PRINT((ndo, ""%04x %s"", nonce, format_interval(interval))); + } + } + break; + + case MESSAGE_ACK: { + u_short nonce; + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" ack"")); + else { + ND_PRINT((ndo, ""\n\tAcknowledgment "")); + if(len < 2) goto invalid; + nonce = EXTRACT_16BITS(message + 2); + ND_PRINT((ndo, ""%04x"", nonce)); + } + } + break; + + case MESSAGE_HELLO: { + u_short seqno, interval; + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" hello"")); + else { + ND_PRINT((ndo, ""\n\tHello "")); + if(len < 6) goto invalid; + seqno = EXTRACT_16BITS(message + 4); + interval = EXTRACT_16BITS(message + 6); + ND_PRINT((ndo, ""seqno %u interval %s"", seqno, format_interval(interval))); + /* Extra data. */ + if(len > 6) + subtlvs_print(ndo, message + 8, message + 2 + len, type); + } + } + break; + + case MESSAGE_IHU: { + unsigned short txcost, interval; + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" ihu"")); + else { + u_char address[16]; + int rc; + ND_PRINT((ndo, ""\n\tIHU "")); + if(len < 6) goto invalid; + txcost = EXTRACT_16BITS(message + 4); + interval = EXTRACT_16BITS(message + 6); + rc = network_address(message[2], message + 8, len - 6, address); + if(rc < 0) { ND_PRINT((ndo, ""%s"", tstr)); break; } + ND_PRINT((ndo, ""%s txcost %u interval %s"", + format_address(ndo, address), txcost, format_interval(interval))); + /* Extra data. */ + if((u_int)rc < len - 6) + subtlvs_print(ndo, message + 8 + rc, message + 2 + len, + type); + } + } + break; + + case MESSAGE_ROUTER_ID: { + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" router-id"")); + else { + ND_PRINT((ndo, ""\n\tRouter Id"")); + if(len < 10) goto invalid; + ND_PRINT((ndo, "" %s"", format_id(message + 4))); + } + } + break; + + case MESSAGE_NH: { + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" nh"")); + else { + int rc; + u_char nh[16]; + ND_PRINT((ndo, ""\n\tNext Hop"")); + if(len < 2) goto invalid; + rc = network_address(message[2], message + 4, len - 2, nh); + if(rc < 0) goto invalid; + ND_PRINT((ndo, "" %s"", format_address(ndo, nh))); + } + } + break; + + case MESSAGE_UPDATE: { + if (!ndo->ndo_vflag) { + ND_PRINT((ndo, "" update"")); + if(len < 1) + ND_PRINT((ndo, ""/truncated"")); + else + ND_PRINT((ndo, ""%s%s%s"", + (message[3] & 0x80) ? ""/prefix"": """", + (message[3] & 0x40) ? ""/id"" : """", + (message[3] & 0x3f) ? ""/unknown"" : """")); + } else { + u_short interval, seqno, metric; + u_char plen; + int rc; + u_char prefix[16]; + ND_PRINT((ndo, ""\n\tUpdate"")); + if(len < 10) goto invalid; + plen = message[4] + (message[2] == 1 ? 96 : 0); + rc = network_prefix(message[2], message[4], message[5], + message + 12, + message[2] == 1 ? v4_prefix : v6_prefix, + len - 10, prefix); + if(rc < 0) goto invalid; + interval = EXTRACT_16BITS(message + 6); + seqno = EXTRACT_16BITS(message + 8); + metric = EXTRACT_16BITS(message + 10); + ND_PRINT((ndo, ""%s%s%s %s metric %u seqno %u interval %s"", + (message[3] & 0x80) ? ""/prefix"": """", + (message[3] & 0x40) ? ""/id"" : """", + (message[3] & 0x3f) ? ""/unknown"" : """", + format_prefix(ndo, prefix, plen), + metric, seqno, format_interval_update(interval))); + if(message[3] & 0x80) { + if(message[2] == 1) + memcpy(v4_prefix, prefix, 16); + else + memcpy(v6_prefix, prefix, 16); + } + /* extra data? */ + if((u_int)rc < len - 10) + subtlvs_print(ndo, message + 12 + rc, message + 2 + len, type); + } + } + break; + + case MESSAGE_REQUEST: { + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" request"")); + else { + int rc; + u_char prefix[16], plen; + ND_PRINT((ndo, ""\n\tRequest "")); + if(len < 2) goto invalid; + plen = message[3] + (message[2] == 1 ? 96 : 0); + rc = network_prefix(message[2], message[3], 0, + message + 4, NULL, len - 2, prefix); + if(rc < 0) goto invalid; + ND_PRINT((ndo, ""for %s"", + message[2] == 0 ? ""any"" : format_prefix(ndo, prefix, plen))); + } + } + break; + + case MESSAGE_MH_REQUEST : { + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" mh-request"")); + else { + int rc; + u_short seqno; + u_char prefix[16], plen; + ND_PRINT((ndo, ""\n\tMH-Request "")); + if(len < 14) goto invalid; + seqno = EXTRACT_16BITS(message + 4); + rc = network_prefix(message[2], message[3], 0, + message + 16, NULL, len - 14, prefix); + if(rc < 0) goto invalid; + plen = message[3] + (message[2] == 1 ? 96 : 0); + ND_PRINT((ndo, ""(%u hops) for %s seqno %u id %s"", + message[6], format_prefix(ndo, prefix, plen), + seqno, format_id(message + 8))); + } + } + break; + case MESSAGE_TSPC : + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" tspc"")); + else { + ND_PRINT((ndo, ""\n\tTS/PC "")); + if(len < 6) goto invalid; + ND_PRINT((ndo, ""timestamp %u packetcounter %u"", EXTRACT_32BITS (message + 4), + EXTRACT_16BITS(message + 2))); + } + break; + case MESSAGE_HMAC : { + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" hmac"")); + else { + unsigned j; + ND_PRINT((ndo, ""\n\tHMAC "")); + if(len < 18) goto invalid; + ND_PRINT((ndo, ""key-id %u digest-%u "", EXTRACT_16BITS(message + 2), len - 2)); + for (j = 0; j < len - 2; j++) + ND_PRINT((ndo, ""%02X"", message[4 + j])); + } + } + break; + + case MESSAGE_UPDATE_SRC_SPECIFIC : { + if(!ndo->ndo_vflag) { + ND_PRINT((ndo, "" ss-update"")); + } else { + u_char prefix[16], src_prefix[16]; + u_short interval, seqno, metric; + u_char ae, plen, src_plen, omitted; + int rc; + int parsed_len = 10; + ND_PRINT((ndo, ""\n\tSS-Update"")); + if(len < 10) goto invalid; + ae = message[2]; + src_plen = message[3]; + plen = message[4]; + omitted = message[5]; + interval = EXTRACT_16BITS(message + 6); + seqno = EXTRACT_16BITS(message + 8); + metric = EXTRACT_16BITS(message + 10); + rc = network_prefix(ae, plen, omitted, message + 2 + parsed_len, + ae == 1 ? v4_prefix : v6_prefix, + len - parsed_len, prefix); + if(rc < 0) goto invalid; + if(ae == 1) + plen += 96; + parsed_len += rc; + rc = network_prefix(ae, src_plen, 0, message + 2 + parsed_len, + NULL, len - parsed_len, src_prefix); + if(rc < 0) goto invalid; + if(ae == 1) + src_plen += 96; + parsed_len += rc; + + ND_PRINT((ndo, "" %s from"", format_prefix(ndo, prefix, plen))); + ND_PRINT((ndo, "" %s metric %u seqno %u interval %s"", + format_prefix(ndo, src_prefix, src_plen), + metric, seqno, format_interval_update(interval))); + /* extra data? */ + if((u_int)parsed_len < len) + subtlvs_print(ndo, message + 2 + parsed_len, + message + 2 + len, type); + } + } + break; + + case MESSAGE_REQUEST_SRC_SPECIFIC : { + if(!ndo->ndo_vflag) + ND_PRINT((ndo, "" ss-request"")); + else { + int rc, parsed_len = 3; + u_char ae, plen, src_plen, prefix[16], src_prefix[16]; + ND_PRINT((ndo, ""\n\tSS-Request "")); + if(len < 3) goto invalid; + ae = message[2]; + plen = message[3]; + src_plen = message[4]; + rc = network_prefix(ae, plen, 0, message + 2 + parsed_len, + NULL, len - parsed_len, prefix); + if(rc < 0) goto invalid; + if(ae == 1) + plen += 96; + parsed_len += rc; + rc = network_prefix(ae, src_plen, 0, message + 2 + parsed_len, + NULL, len - parsed_len, src_prefix); + if(rc < 0) goto invalid; + if(ae == 1) + src_plen += 96; + parsed_len += rc; + if(ae == 0) { + ND_PRINT((ndo, ""for any"")); + } else { + ND_PRINT((ndo, ""for (%s, "", format_prefix(ndo, prefix, plen))); + ND_PRINT((ndo, ""%s)"", format_prefix(ndo, src_prefix, src_plen))); + } + } + } + break; + + case MESSAGE_MH_REQUEST_SRC_SPECIFIC : { + if(!ndo->ndo_vflag) + ND_PRINT((ndo, "" ss-mh-request"")); + else { + int rc, parsed_len = 14; + u_short seqno; + u_char ae, plen, src_plen, prefix[16], src_prefix[16], hopc; + const u_char *router_id = NULL; + ND_PRINT((ndo, ""\n\tSS-MH-Request "")); + if(len < 14) goto invalid; + ae = message[2]; + plen = message[3]; + seqno = EXTRACT_16BITS(message + 4); + hopc = message[6]; + src_plen = message[7]; + router_id = message + 8; + rc = network_prefix(ae, plen, 0, message + 2 + parsed_len, + NULL, len - parsed_len, prefix); + if(rc < 0) goto invalid; + if(ae == 1) + plen += 96; + parsed_len += rc; + rc = network_prefix(ae, src_plen, 0, message + 2 + parsed_len, + NULL, len - parsed_len, src_prefix); + if(rc < 0) goto invalid; + if(ae == 1) + src_plen += 96; + ND_PRINT((ndo, ""(%u hops) for (%s, "", + hopc, format_prefix(ndo, prefix, plen))); + ND_PRINT((ndo, ""%s) seqno %u id %s"", + format_prefix(ndo, src_prefix, src_plen), + seqno, format_id(router_id))); + } + } + break; + + default: + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" unknown"")); + else + ND_PRINT((ndo, ""\n\tUnknown message type %d"", type)); + } + i += len + 2; + } + return; + + trunc: + ND_PRINT((ndo, "" %s"", tstr)); + return; + + invalid: + ND_PRINT((ndo, ""%s"", istr)); + return; +} +",1,"babel_print_v2(netdissect_options *ndo, + const u_char *cp, u_int length) +{ + u_int i; + u_short bodylen; + u_char v4_prefix[16] = + {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0, 0, 0, 0 }; + u_char v6_prefix[16] = {0}; + + ND_TCHECK2(*cp, 4); + if (length < 4) + goto invalid; + bodylen = EXTRACT_16BITS(cp + 2); + ND_PRINT((ndo, "" (%u)"", bodylen)); + + /* Process the TLVs in the body */ + i = 0; + while(i < bodylen) { + const u_char *message; + u_int type, len; + + message = cp + 4 + i; + + ND_TCHECK2(*message, 1); + if((type = message[0]) == MESSAGE_PAD1) { + ND_PRINT((ndo, ndo->ndo_vflag ? ""\n\tPad 1"" : "" pad1"")); + i += 1; + continue; + } + + ND_TCHECK2(*message, 2); + ICHECK(i, 2); + len = message[1]; + + ND_TCHECK2(*message, 2 + len); + ICHECK(i, 2 + len); + + switch(type) { + case MESSAGE_PADN: { + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" padN"")); + else + ND_PRINT((ndo, ""\n\tPad %d"", len + 2)); + } + break; + + case MESSAGE_ACK_REQ: { + u_short nonce, interval; + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" ack-req"")); + else { + ND_PRINT((ndo, ""\n\tAcknowledgment Request "")); + if(len < 6) goto invalid; + nonce = EXTRACT_16BITS(message + 4); + interval = EXTRACT_16BITS(message + 6); + ND_PRINT((ndo, ""%04x %s"", nonce, format_interval(interval))); + } + } + break; + + case MESSAGE_ACK: { + u_short nonce; + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" ack"")); + else { + ND_PRINT((ndo, ""\n\tAcknowledgment "")); + if(len < 2) goto invalid; + nonce = EXTRACT_16BITS(message + 2); + ND_PRINT((ndo, ""%04x"", nonce)); + } + } + break; + + case MESSAGE_HELLO: { + u_short seqno, interval; + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" hello"")); + else { + ND_PRINT((ndo, ""\n\tHello "")); + if(len < 6) goto invalid; + seqno = EXTRACT_16BITS(message + 4); + interval = EXTRACT_16BITS(message + 6); + ND_PRINT((ndo, ""seqno %u interval %s"", seqno, format_interval(interval))); + /* Extra data. */ + if(len > 6) + subtlvs_print(ndo, message + 8, message + 2 + len, type); + } + } + break; + + case MESSAGE_IHU: { + unsigned short txcost, interval; + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" ihu"")); + else { + u_char address[16]; + int rc; + ND_PRINT((ndo, ""\n\tIHU "")); + if(len < 6) goto invalid; + txcost = EXTRACT_16BITS(message + 4); + interval = EXTRACT_16BITS(message + 6); + rc = network_address(message[2], message + 8, len - 6, address); + if(rc < 0) { ND_PRINT((ndo, ""%s"", tstr)); break; } + ND_PRINT((ndo, ""%s txcost %u interval %s"", + format_address(ndo, address), txcost, format_interval(interval))); + /* Extra data. */ + if((u_int)rc < len - 6) + subtlvs_print(ndo, message + 8 + rc, message + 2 + len, + type); + } + } + break; + + case MESSAGE_ROUTER_ID: { + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" router-id"")); + else { + ND_PRINT((ndo, ""\n\tRouter Id"")); + if(len < 10) goto invalid; + ND_PRINT((ndo, "" %s"", format_id(message + 4))); + } + } + break; + + case MESSAGE_NH: { + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" nh"")); + else { + int rc; + u_char nh[16]; + ND_PRINT((ndo, ""\n\tNext Hop"")); + if(len < 2) goto invalid; + rc = network_address(message[2], message + 4, len - 2, nh); + if(rc < 0) goto invalid; + ND_PRINT((ndo, "" %s"", format_address(ndo, nh))); + } + } + break; + + case MESSAGE_UPDATE: { + if (!ndo->ndo_vflag) { + ND_PRINT((ndo, "" update"")); + if(len < 10) + ND_PRINT((ndo, ""/truncated"")); + else + ND_PRINT((ndo, ""%s%s%s"", + (message[3] & 0x80) ? ""/prefix"": """", + (message[3] & 0x40) ? ""/id"" : """", + (message[3] & 0x3f) ? ""/unknown"" : """")); + } else { + u_short interval, seqno, metric; + u_char plen; + int rc; + u_char prefix[16]; + ND_PRINT((ndo, ""\n\tUpdate"")); + if(len < 10) goto invalid; + plen = message[4] + (message[2] == 1 ? 96 : 0); + rc = network_prefix(message[2], message[4], message[5], + message + 12, + message[2] == 1 ? v4_prefix : v6_prefix, + len - 10, prefix); + if(rc < 0) goto invalid; + interval = EXTRACT_16BITS(message + 6); + seqno = EXTRACT_16BITS(message + 8); + metric = EXTRACT_16BITS(message + 10); + ND_PRINT((ndo, ""%s%s%s %s metric %u seqno %u interval %s"", + (message[3] & 0x80) ? ""/prefix"": """", + (message[3] & 0x40) ? ""/id"" : """", + (message[3] & 0x3f) ? ""/unknown"" : """", + format_prefix(ndo, prefix, plen), + metric, seqno, format_interval_update(interval))); + if(message[3] & 0x80) { + if(message[2] == 1) + memcpy(v4_prefix, prefix, 16); + else + memcpy(v6_prefix, prefix, 16); + } + /* extra data? */ + if((u_int)rc < len - 10) + subtlvs_print(ndo, message + 12 + rc, message + 2 + len, type); + } + } + break; + + case MESSAGE_REQUEST: { + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" request"")); + else { + int rc; + u_char prefix[16], plen; + ND_PRINT((ndo, ""\n\tRequest "")); + if(len < 2) goto invalid; + plen = message[3] + (message[2] == 1 ? 96 : 0); + rc = network_prefix(message[2], message[3], 0, + message + 4, NULL, len - 2, prefix); + if(rc < 0) goto invalid; + ND_PRINT((ndo, ""for %s"", + message[2] == 0 ? ""any"" : format_prefix(ndo, prefix, plen))); + } + } + break; + + case MESSAGE_MH_REQUEST : { + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" mh-request"")); + else { + int rc; + u_short seqno; + u_char prefix[16], plen; + ND_PRINT((ndo, ""\n\tMH-Request "")); + if(len < 14) goto invalid; + seqno = EXTRACT_16BITS(message + 4); + rc = network_prefix(message[2], message[3], 0, + message + 16, NULL, len - 14, prefix); + if(rc < 0) goto invalid; + plen = message[3] + (message[2] == 1 ? 96 : 0); + ND_PRINT((ndo, ""(%u hops) for %s seqno %u id %s"", + message[6], format_prefix(ndo, prefix, plen), + seqno, format_id(message + 8))); + } + } + break; + case MESSAGE_TSPC : + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" tspc"")); + else { + ND_PRINT((ndo, ""\n\tTS/PC "")); + if(len < 6) goto invalid; + ND_PRINT((ndo, ""timestamp %u packetcounter %u"", EXTRACT_32BITS (message + 4), + EXTRACT_16BITS(message + 2))); + } + break; + case MESSAGE_HMAC : { + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" hmac"")); + else { + unsigned j; + ND_PRINT((ndo, ""\n\tHMAC "")); + if(len < 18) goto invalid; + ND_PRINT((ndo, ""key-id %u digest-%u "", EXTRACT_16BITS(message + 2), len - 2)); + for (j = 0; j < len - 2; j++) + ND_PRINT((ndo, ""%02X"", message[4 + j])); + } + } + break; + + case MESSAGE_UPDATE_SRC_SPECIFIC : { + if(!ndo->ndo_vflag) { + ND_PRINT((ndo, "" ss-update"")); + } else { + u_char prefix[16], src_prefix[16]; + u_short interval, seqno, metric; + u_char ae, plen, src_plen, omitted; + int rc; + int parsed_len = 10; + ND_PRINT((ndo, ""\n\tSS-Update"")); + if(len < 10) goto invalid; + ae = message[2]; + src_plen = message[3]; + plen = message[4]; + omitted = message[5]; + interval = EXTRACT_16BITS(message + 6); + seqno = EXTRACT_16BITS(message + 8); + metric = EXTRACT_16BITS(message + 10); + rc = network_prefix(ae, plen, omitted, message + 2 + parsed_len, + ae == 1 ? v4_prefix : v6_prefix, + len - parsed_len, prefix); + if(rc < 0) goto invalid; + if(ae == 1) + plen += 96; + parsed_len += rc; + rc = network_prefix(ae, src_plen, 0, message + 2 + parsed_len, + NULL, len - parsed_len, src_prefix); + if(rc < 0) goto invalid; + if(ae == 1) + src_plen += 96; + parsed_len += rc; + + ND_PRINT((ndo, "" %s from"", format_prefix(ndo, prefix, plen))); + ND_PRINT((ndo, "" %s metric %u seqno %u interval %s"", + format_prefix(ndo, src_prefix, src_plen), + metric, seqno, format_interval_update(interval))); + /* extra data? */ + if((u_int)parsed_len < len) + subtlvs_print(ndo, message + 2 + parsed_len, + message + 2 + len, type); + } + } + break; + + case MESSAGE_REQUEST_SRC_SPECIFIC : { + if(!ndo->ndo_vflag) + ND_PRINT((ndo, "" ss-request"")); + else { + int rc, parsed_len = 3; + u_char ae, plen, src_plen, prefix[16], src_prefix[16]; + ND_PRINT((ndo, ""\n\tSS-Request "")); + if(len < 3) goto invalid; + ae = message[2]; + plen = message[3]; + src_plen = message[4]; + rc = network_prefix(ae, plen, 0, message + 2 + parsed_len, + NULL, len - parsed_len, prefix); + if(rc < 0) goto invalid; + if(ae == 1) + plen += 96; + parsed_len += rc; + rc = network_prefix(ae, src_plen, 0, message + 2 + parsed_len, + NULL, len - parsed_len, src_prefix); + if(rc < 0) goto invalid; + if(ae == 1) + src_plen += 96; + parsed_len += rc; + if(ae == 0) { + ND_PRINT((ndo, ""for any"")); + } else { + ND_PRINT((ndo, ""for (%s, "", format_prefix(ndo, prefix, plen))); + ND_PRINT((ndo, ""%s)"", format_prefix(ndo, src_prefix, src_plen))); + } + } + } + break; + + case MESSAGE_MH_REQUEST_SRC_SPECIFIC : { + if(!ndo->ndo_vflag) + ND_PRINT((ndo, "" ss-mh-request"")); + else { + int rc, parsed_len = 14; + u_short seqno; + u_char ae, plen, src_plen, prefix[16], src_prefix[16], hopc; + const u_char *router_id = NULL; + ND_PRINT((ndo, ""\n\tSS-MH-Request "")); + if(len < 14) goto invalid; + ae = message[2]; + plen = message[3]; + seqno = EXTRACT_16BITS(message + 4); + hopc = message[6]; + src_plen = message[7]; + router_id = message + 8; + rc = network_prefix(ae, plen, 0, message + 2 + parsed_len, + NULL, len - parsed_len, prefix); + if(rc < 0) goto invalid; + if(ae == 1) + plen += 96; + parsed_len += rc; + rc = network_prefix(ae, src_plen, 0, message + 2 + parsed_len, + NULL, len - parsed_len, src_prefix); + if(rc < 0) goto invalid; + if(ae == 1) + src_plen += 96; + ND_PRINT((ndo, ""(%u hops) for (%s, "", + hopc, format_prefix(ndo, prefix, plen))); + ND_PRINT((ndo, ""%s) seqno %u id %s"", + format_prefix(ndo, src_prefix, src_plen), + seqno, format_id(router_id))); + } + } + break; + + default: + if (!ndo->ndo_vflag) + ND_PRINT((ndo, "" unknown"")); + else + ND_PRINT((ndo, ""\n\tUnknown message type %d"", type)); + } + i += len + 2; + } + return; + + trunc: + ND_PRINT((ndo, "" %s"", tstr)); + return; + + invalid: + ND_PRINT((ndo, ""%s"", istr)); + return; +} +","@@ -480,7 +480,7 @@ babel_print_v2(netdissect_options *ndo, + case MESSAGE_UPDATE: { + if (!ndo->ndo_vflag) { + ND_PRINT((ndo, "" update"")); +- if(len < 1) ++ if(len < 10) + ND_PRINT((ndo, ""/truncated"")); + else + ND_PRINT((ndo, ""%s%s%s"",",3481,3812,4096 +15325,"void DesktopWindowTreeHostX11::InitX11Window( + const Widget::InitParams& params) { + unsigned long attribute_mask = CWBackPixel | CWBitGravity; + XSetWindowAttributes swa; + memset(&swa, 0, sizeof(swa)); + swa.background_pixmap = x11::None; + swa.bit_gravity = NorthWestGravity; + + int background_color; + + const views::LinuxUI* linux_ui = views::LinuxUI::instance(); + if (linux_ui && content_window()) { + ui::NativeTheme::ColorId target_color; + switch (params.type) { + case Widget::InitParams::TYPE_BUBBLE: + target_color = ui::NativeTheme::kColorId_BubbleBackground; + break; + case Widget::InitParams::TYPE_TOOLTIP: + target_color = ui::NativeTheme::kColorId_TooltipBackground; + break; + default: + target_color = ui::NativeTheme::kColorId_WindowBackground; + break; + } + + ui::NativeTheme* theme = linux_ui->GetNativeTheme(content_window()); + background_color = theme->GetSystemColor(target_color); + } else { + background_color = WhitePixel(xdisplay_, DefaultScreen(xdisplay_)); + } + swa.background_pixel = background_color; + + XAtom window_type; + switch (params.type) { + case Widget::InitParams::TYPE_MENU: + swa.override_redirect = x11::True; + window_type = gfx::GetAtom(""_NET_WM_WINDOW_TYPE_MENU""); + break; + case Widget::InitParams::TYPE_TOOLTIP: + swa.override_redirect = x11::True; + window_type = gfx::GetAtom(""_NET_WM_WINDOW_TYPE_TOOLTIP""); + break; + case Widget::InitParams::TYPE_POPUP: + swa.override_redirect = x11::True; + window_type = gfx::GetAtom(""_NET_WM_WINDOW_TYPE_NOTIFICATION""); + break; + case Widget::InitParams::TYPE_DRAG: + swa.override_redirect = x11::True; + window_type = gfx::GetAtom(""_NET_WM_WINDOW_TYPE_DND""); + break; + default: + window_type = gfx::GetAtom(""_NET_WM_WINDOW_TYPE_NORMAL""); + break; + } + if (!activatable_) + swa.override_redirect = x11::True; + + override_redirect_ = swa.override_redirect == x11::True; + if (override_redirect_) + attribute_mask |= CWOverrideRedirect; + + bool enable_transparent_visuals; + switch (params.opacity) { + case Widget::InitParams::OPAQUE_WINDOW: + enable_transparent_visuals = false; + break; + case Widget::InitParams::TRANSLUCENT_WINDOW: + enable_transparent_visuals = true; + break; + case Widget::InitParams::INFER_OPACITY: + default: + enable_transparent_visuals = params.type == Widget::InitParams::TYPE_DRAG; + } + + Visual* visual = CopyFromParent; + int depth = CopyFromParent; + Colormap colormap = CopyFromParent; + ui::XVisualManager::GetInstance()->ChooseVisualForWindow( + enable_transparent_visuals, &visual, &depth, &colormap, + &use_argb_visual_); + + if (colormap != CopyFromParent) { + attribute_mask |= CWColormap; + swa.colormap = colormap; + } + + attribute_mask |= CWBorderPixel; + swa.border_pixel = 0; + + bounds_in_pixels_ = ToPixelRect(params.bounds); + bounds_in_pixels_.set_size(AdjustSize(bounds_in_pixels_.size())); + xwindow_ = XCreateWindow(xdisplay_, x_root_window_, bounds_in_pixels_.x(), + bounds_in_pixels_.y(), bounds_in_pixels_.width(), + bounds_in_pixels_.height(), + 0, // border width + depth, InputOutput, visual, attribute_mask, &swa); + if (ui::PlatformEventSource::GetInstance()) + ui::PlatformEventSource::GetInstance()->AddPlatformEventDispatcher(this); + open_windows().push_front(xwindow_); + + + long event_mask = ButtonPressMask | ButtonReleaseMask | FocusChangeMask | + KeyPressMask | KeyReleaseMask | + EnterWindowMask | LeaveWindowMask | + ExposureMask | VisibilityChangeMask | + StructureNotifyMask | PropertyChangeMask | + PointerMotionMask; + xwindow_events_ = + std::make_unique(xwindow_, event_mask); + XFlush(xdisplay_); + + if (ui::IsXInput2Available()) + ui::TouchFactory::GetInstance()->SetupXI2ForXWindow(xwindow_); + + XAtom protocols[2]; + protocols[0] = gfx::GetAtom(""WM_DELETE_WINDOW""); + protocols[1] = gfx::GetAtom(""_NET_WM_PING""); + XSetWMProtocols(xdisplay_, xwindow_, protocols, 2); + + XSetWMProperties(xdisplay_, xwindow_, nullptr, nullptr, nullptr, 0, nullptr, + nullptr, nullptr); + + static_assert(sizeof(long) >= sizeof(pid_t), + ""pid_t should not be larger than long""); + long pid = getpid(); + XChangeProperty(xdisplay_, xwindow_, gfx::GetAtom(""_NET_WM_PID""), XA_CARDINAL, + 32, PropModeReplace, reinterpret_cast(&pid), + 1); + + XChangeProperty(xdisplay_, xwindow_, gfx::GetAtom(""_NET_WM_WINDOW_TYPE""), + XA_ATOM, 32, PropModeReplace, + reinterpret_cast(&window_type), 1); + + + if ((params.type == Widget::InitParams::TYPE_POPUP || + params.type == Widget::InitParams::TYPE_BUBBLE) && + !params.force_show_in_taskbar) { + window_properties_.insert(gfx::GetAtom(""_NET_WM_STATE_SKIP_TASKBAR"")); + } + + is_always_on_top_ = params.keep_on_top; + if (is_always_on_top_) + window_properties_.insert(gfx::GetAtom(""_NET_WM_STATE_ABOVE"")); + + workspace_ = base::nullopt; + if (params.visible_on_all_workspaces) { + window_properties_.insert(gfx::GetAtom(""_NET_WM_STATE_STICKY"")); + ui::SetIntProperty(xwindow_, ""_NET_WM_DESKTOP"", ""CARDINAL"", kAllDesktops); + } else if (!params.workspace.empty()) { + int workspace; + if (base::StringToInt(params.workspace, &workspace)) + ui::SetIntProperty(xwindow_, ""_NET_WM_DESKTOP"", ""CARDINAL"", workspace); + } + + if (!params.wm_class_name.empty() || !params.wm_class_class.empty()) { + ui::SetWindowClassHint( + xdisplay_, xwindow_, params.wm_class_name, params.wm_class_class); + } + + const char* wm_role_name = nullptr; + if (!params.wm_role_name.empty()) { + wm_role_name = params.wm_role_name.c_str(); + } else { + switch (params.type) { + case Widget::InitParams::TYPE_POPUP: + wm_role_name = kX11WindowRolePopup; + break; + case Widget::InitParams::TYPE_BUBBLE: + wm_role_name = kX11WindowRoleBubble; + break; + default: + break; + } + } + if (wm_role_name) + ui::SetWindowRole(xdisplay_, xwindow_, std::string(wm_role_name)); + + if (params.remove_standard_frame) { + ui::SetHideTitlebarWhenMaximizedProperty(xwindow_, + ui::HIDE_TITLEBAR_WHEN_MAXIMIZED); + } + + if (views::LinuxUI::instance() && + views::LinuxUI::instance()->PreferDarkTheme()) { + const unsigned char kDarkGtkThemeVariant[] = ""dark""; + XChangeProperty(xdisplay_, xwindow_, gfx::GetAtom(""_GTK_THEME_VARIANT""), + gfx::GetAtom(""UTF8_STRING""), 8, PropModeReplace, + kDarkGtkThemeVariant, base::size(kDarkGtkThemeVariant) - 1); + } + + ui::SetIntProperty(xwindow_, ""_NET_WM_BYPASS_COMPOSITOR"", ""CARDINAL"", 2); + + if (params.parent && params.parent->GetHost()) { + XID parent_xid = + params.parent->GetHost()->GetAcceleratedWidget(); + window_parent_ = GetHostForXID(parent_xid); + DCHECK(window_parent_); + window_parent_->window_children_.insert(this); + } + + gfx::ImageSkia* window_icon = + ViewsDelegate::GetInstance() + ? ViewsDelegate::GetInstance()->GetDefaultWindowIcon() + : nullptr; + if (window_icon) { + SetWindowIcons(gfx::ImageSkia(), *window_icon); + } + CreateCompositor(viz::FrameSinkId(), + params.type == Widget::InitParams::TYPE_TOOLTIP); + OnAcceleratedWidgetAvailable(); +} +",0,"void DesktopWindowTreeHostX11::InitX11Window( + const Widget::InitParams& params) { + unsigned long attribute_mask = CWBackPixel | CWBitGravity; + XSetWindowAttributes swa; + memset(&swa, 0, sizeof(swa)); + swa.background_pixmap = x11::None; + swa.bit_gravity = NorthWestGravity; + + int background_color; + + const views::LinuxUI* linux_ui = views::LinuxUI::instance(); + if (linux_ui && content_window()) { + ui::NativeTheme::ColorId target_color; + switch (params.type) { + case Widget::InitParams::TYPE_BUBBLE: + target_color = ui::NativeTheme::kColorId_BubbleBackground; + break; + case Widget::InitParams::TYPE_TOOLTIP: + target_color = ui::NativeTheme::kColorId_TooltipBackground; + break; + default: + target_color = ui::NativeTheme::kColorId_WindowBackground; + break; + } + + ui::NativeTheme* theme = linux_ui->GetNativeTheme(content_window()); + background_color = theme->GetSystemColor(target_color); + } else { + background_color = WhitePixel(xdisplay_, DefaultScreen(xdisplay_)); + } + swa.background_pixel = background_color; + + XAtom window_type; + switch (params.type) { + case Widget::InitParams::TYPE_MENU: + swa.override_redirect = x11::True; + window_type = gfx::GetAtom(""_NET_WM_WINDOW_TYPE_MENU""); + break; + case Widget::InitParams::TYPE_TOOLTIP: + swa.override_redirect = x11::True; + window_type = gfx::GetAtom(""_NET_WM_WINDOW_TYPE_TOOLTIP""); + break; + case Widget::InitParams::TYPE_POPUP: + swa.override_redirect = x11::True; + window_type = gfx::GetAtom(""_NET_WM_WINDOW_TYPE_NOTIFICATION""); + break; + case Widget::InitParams::TYPE_DRAG: + swa.override_redirect = x11::True; + window_type = gfx::GetAtom(""_NET_WM_WINDOW_TYPE_DND""); + break; + default: + window_type = gfx::GetAtom(""_NET_WM_WINDOW_TYPE_NORMAL""); + break; + } + if (!activatable_) + swa.override_redirect = x11::True; + + override_redirect_ = swa.override_redirect == x11::True; + if (override_redirect_) + attribute_mask |= CWOverrideRedirect; + + bool enable_transparent_visuals; + switch (params.opacity) { + case Widget::InitParams::OPAQUE_WINDOW: + enable_transparent_visuals = false; + break; + case Widget::InitParams::TRANSLUCENT_WINDOW: + enable_transparent_visuals = true; + break; + case Widget::InitParams::INFER_OPACITY: + default: + enable_transparent_visuals = params.type == Widget::InitParams::TYPE_DRAG; + } + + Visual* visual = CopyFromParent; + int depth = CopyFromParent; + Colormap colormap = CopyFromParent; + ui::XVisualManager::GetInstance()->ChooseVisualForWindow( + enable_transparent_visuals, &visual, &depth, &colormap, + &use_argb_visual_); + + if (colormap != CopyFromParent) { + attribute_mask |= CWColormap; + swa.colormap = colormap; + } + + attribute_mask |= CWBorderPixel; + swa.border_pixel = 0; + + bounds_in_pixels_ = ToPixelRect(params.bounds); + bounds_in_pixels_.set_size(AdjustSize(bounds_in_pixels_.size())); + xwindow_ = XCreateWindow(xdisplay_, x_root_window_, bounds_in_pixels_.x(), + bounds_in_pixels_.y(), bounds_in_pixels_.width(), + bounds_in_pixels_.height(), + 0, // border width + depth, InputOutput, visual, attribute_mask, &swa); + if (ui::PlatformEventSource::GetInstance()) + ui::PlatformEventSource::GetInstance()->AddPlatformEventDispatcher(this); + open_windows().push_front(xwindow_); + + + long event_mask = ButtonPressMask | ButtonReleaseMask | FocusChangeMask | + KeyPressMask | KeyReleaseMask | + EnterWindowMask | LeaveWindowMask | + ExposureMask | VisibilityChangeMask | + StructureNotifyMask | PropertyChangeMask | + PointerMotionMask; + xwindow_events_ = + std::make_unique(xwindow_, event_mask); + XFlush(xdisplay_); + + if (ui::IsXInput2Available()) + ui::TouchFactory::GetInstance()->SetupXI2ForXWindow(xwindow_); + + XAtom protocols[2]; + protocols[0] = gfx::GetAtom(""WM_DELETE_WINDOW""); + protocols[1] = gfx::GetAtom(""_NET_WM_PING""); + XSetWMProtocols(xdisplay_, xwindow_, protocols, 2); + + XSetWMProperties(xdisplay_, xwindow_, nullptr, nullptr, nullptr, 0, nullptr, + nullptr, nullptr); + + static_assert(sizeof(long) >= sizeof(pid_t), + ""pid_t should not be larger than long""); + long pid = getpid(); + XChangeProperty(xdisplay_, xwindow_, gfx::GetAtom(""_NET_WM_PID""), XA_CARDINAL, + 32, PropModeReplace, reinterpret_cast(&pid), + 1); + + XChangeProperty(xdisplay_, xwindow_, gfx::GetAtom(""_NET_WM_WINDOW_TYPE""), + XA_ATOM, 32, PropModeReplace, + reinterpret_cast(&window_type), 1); + + + if ((params.type == Widget::InitParams::TYPE_POPUP || + params.type == Widget::InitParams::TYPE_BUBBLE) && + !params.force_show_in_taskbar) { + window_properties_.insert(gfx::GetAtom(""_NET_WM_STATE_SKIP_TASKBAR"")); + } + + is_always_on_top_ = params.keep_on_top; + if (is_always_on_top_) + window_properties_.insert(gfx::GetAtom(""_NET_WM_STATE_ABOVE"")); + + workspace_ = base::nullopt; + if (params.visible_on_all_workspaces) { + window_properties_.insert(gfx::GetAtom(""_NET_WM_STATE_STICKY"")); + ui::SetIntProperty(xwindow_, ""_NET_WM_DESKTOP"", ""CARDINAL"", kAllDesktops); + } else if (!params.workspace.empty()) { + int workspace; + if (base::StringToInt(params.workspace, &workspace)) + ui::SetIntProperty(xwindow_, ""_NET_WM_DESKTOP"", ""CARDINAL"", workspace); + } + + if (!params.wm_class_name.empty() || !params.wm_class_class.empty()) { + ui::SetWindowClassHint( + xdisplay_, xwindow_, params.wm_class_name, params.wm_class_class); + } + + const char* wm_role_name = nullptr; + if (!params.wm_role_name.empty()) { + wm_role_name = params.wm_role_name.c_str(); + } else { + switch (params.type) { + case Widget::InitParams::TYPE_POPUP: + wm_role_name = kX11WindowRolePopup; + break; + case Widget::InitParams::TYPE_BUBBLE: + wm_role_name = kX11WindowRoleBubble; + break; + default: + break; + } + } + if (wm_role_name) + ui::SetWindowRole(xdisplay_, xwindow_, std::string(wm_role_name)); + + if (params.remove_standard_frame) { + ui::SetHideTitlebarWhenMaximizedProperty(xwindow_, + ui::HIDE_TITLEBAR_WHEN_MAXIMIZED); + } + + if (views::LinuxUI::instance() && + views::LinuxUI::instance()->PreferDarkTheme()) { + const unsigned char kDarkGtkThemeVariant[] = ""dark""; + XChangeProperty(xdisplay_, xwindow_, gfx::GetAtom(""_GTK_THEME_VARIANT""), + gfx::GetAtom(""UTF8_STRING""), 8, PropModeReplace, + kDarkGtkThemeVariant, base::size(kDarkGtkThemeVariant) - 1); + } + + ui::SetIntProperty(xwindow_, ""_NET_WM_BYPASS_COMPOSITOR"", ""CARDINAL"", 2); + + if (params.parent && params.parent->GetHost()) { + XID parent_xid = + params.parent->GetHost()->GetAcceleratedWidget(); + window_parent_ = GetHostForXID(parent_xid); + DCHECK(window_parent_); + window_parent_->window_children_.insert(this); + } + + gfx::ImageSkia* window_icon = + ViewsDelegate::GetInstance() + ? ViewsDelegate::GetInstance()->GetDefaultWindowIcon() + : nullptr; + if (window_icon) { + SetWindowIcons(gfx::ImageSkia(), *window_icon); + } + CreateCompositor(viz::FrameSinkId(), + params.type == Widget::InitParams::TYPE_TOOLTIP); + OnAcceleratedWidgetAvailable(); +} +","@@ -855,10 +855,13 @@ bool DesktopWindowTreeHostX11::IsAlwaysOnTop() const { + } + + void DesktopWindowTreeHostX11::SetVisible(bool visible) { ++ if (is_compositor_set_visible_ == visible) ++ return; ++ ++ is_compositor_set_visible_ = visible; + if (compositor()) + compositor()->SetVisible(visible); +- if (IsVisible() != visible) +- native_widget_delegate_->OnNativeWidgetVisibilityChanged(visible); ++ native_widget_delegate_->OnNativeWidgetVisibilityChanged(visible); + } + + void DesktopWindowTreeHostX11::SetVisibleOnAllWorkspaces(bool always_visible) {",1887,2218,4096 +17811," FT_Bitmap_Convert( FT_Library library, + const FT_Bitmap *source, + FT_Bitmap *target, + FT_Int alignment ) + { + FT_Error error = FT_Err_Ok; + FT_Memory memory; + + FT_Int source_pitch, target_pitch; + + + if ( !library ) + return FT_THROW( Invalid_Library_Handle ); + + memory = library->memory; + + switch ( source->pixel_mode ) + { + case FT_PIXEL_MODE_MONO: + case FT_PIXEL_MODE_GRAY: + case FT_PIXEL_MODE_GRAY2: + case FT_PIXEL_MODE_GRAY4: + case FT_PIXEL_MODE_LCD: + case FT_PIXEL_MODE_LCD_V: + case FT_PIXEL_MODE_LCD_V: + case FT_PIXEL_MODE_BGRA: + { + FT_Int pad, old_target_pitch; + FT_Long old_size; + + + old_target_pitch = target->pitch; + old_target_pitch = -old_target_pitch; + + old_size = target->rows * old_target_pitch; + + target->pixel_mode = FT_PIXEL_MODE_GRAY; + target->rows = source->rows; + target->width = source->width; + + pad = 0; + if ( alignment > 0 ) + { + pad = source->width % alignment; + if ( pad != 0 ) + pad = alignment - pad; + } + + target_pitch = source->width + pad; + + if ( target_pitch > 0 && + (FT_ULong)target->rows > FT_ULONG_MAX / target_pitch ) + return FT_THROW( Invalid_Argument ); + + if ( target->rows * target_pitch > old_size && + FT_QREALLOC( target->buffer, + old_size, target->rows * target_pitch ) ) + return error; + + target->pitch = target->pitch < 0 ? -target_pitch : target_pitch; + } + break; + + default: + error = FT_THROW( Invalid_Argument ); + } + + source_pitch = source->pitch; + if ( source_pitch < 0 ) + source_pitch = -source_pitch; + + switch ( source->pixel_mode ) + { + case FT_PIXEL_MODE_MONO: + { + FT_Byte* s = source->buffer; + FT_Byte* t = target->buffer; + FT_Int i; + + + target->num_grays = 2; + + for ( i = source->rows; i > 0; i-- ) + { + FT_Byte* ss = s; + FT_Byte* tt = t; + FT_Int j; + + + /* get the full bytes */ + for ( j = source->width >> 3; j > 0; j-- ) + { + FT_Int val = ss[0]; /* avoid a byte->int cast on each line */ + + + tt[0] = (FT_Byte)( ( val & 0x80 ) >> 7 ); + tt[1] = (FT_Byte)( ( val & 0x40 ) >> 6 ); + tt[2] = (FT_Byte)( ( val & 0x20 ) >> 5 ); + tt[3] = (FT_Byte)( ( val & 0x10 ) >> 4 ); + tt[4] = (FT_Byte)( ( val & 0x08 ) >> 3 ); + tt[5] = (FT_Byte)( ( val & 0x04 ) >> 2 ); + tt[6] = (FT_Byte)( ( val & 0x02 ) >> 1 ); + tt[7] = (FT_Byte)( val & 0x01 ); + + tt += 8; + ss += 1; + } + + /* get remaining pixels (if any) */ + j = source->width & 7; + if ( j > 0 ) + { + FT_Int val = *ss; + + + for ( ; j > 0; j-- ) + { + tt[0] = (FT_Byte)( ( val & 0x80 ) >> 7); + val <<= 1; + tt += 1; + } + } + + s += source_pitch; + t += target_pitch; + } + } + break; + + + case FT_PIXEL_MODE_GRAY: + case FT_PIXEL_MODE_LCD: + case FT_PIXEL_MODE_LCD_V: + { + FT_Int width = source->width; + FT_Byte* s = source->buffer; + FT_Byte* t = target->buffer; + FT_Int i; + + + target->num_grays = 256; + + for ( i = source->rows; i > 0; i-- ) + { + FT_ARRAY_COPY( t, s, width ); + + s += source_pitch; + t += target_pitch; + } + } + break; + + + case FT_PIXEL_MODE_GRAY2: + { + FT_Byte* s = source->buffer; + FT_Byte* t = target->buffer; + FT_Int i; + + + target->num_grays = 4; + + for ( i = source->rows; i > 0; i-- ) + { + FT_Byte* ss = s; + FT_Byte* tt = t; + FT_Int j; + + + /* get the full bytes */ + for ( j = source->width >> 2; j > 0; j-- ) + { + FT_Int val = ss[0]; + + + tt[0] = (FT_Byte)( ( val & 0xC0 ) >> 6 ); + tt[1] = (FT_Byte)( ( val & 0x30 ) >> 4 ); + tt[2] = (FT_Byte)( ( val & 0x0C ) >> 2 ); + tt[3] = (FT_Byte)( ( val & 0x03 ) ); + + ss += 1; + tt += 4; + } + + j = source->width & 3; + if ( j > 0 ) + { + FT_Int val = ss[0]; + + + for ( ; j > 0; j-- ) + { + tt[0] = (FT_Byte)( ( val & 0xC0 ) >> 6 ); + val <<= 2; + tt += 1; + } + } + + s += source_pitch; + t += target_pitch; + } + } + break; + + + case FT_PIXEL_MODE_GRAY4: + { + FT_Byte* s = source->buffer; + FT_Byte* t = target->buffer; + FT_Int i; + + + target->num_grays = 16; + + for ( i = source->rows; i > 0; i-- ) + { + FT_Byte* ss = s; + FT_Byte* tt = t; + FT_Int j; + + + /* get the full bytes */ + for ( j = source->width >> 1; j > 0; j-- ) + { + FT_Int val = ss[0]; + + + tt[0] = (FT_Byte)( ( val & 0xF0 ) >> 4 ); + tt[1] = (FT_Byte)( ( val & 0x0F ) ); + + ss += 1; + tt += 2; + } + + if ( source->width & 1 ) + tt[0] = (FT_Byte)( ( ss[0] & 0xF0 ) >> 4 ); + + s += source_pitch; + t += target_pitch; + } + } + break; + + + case FT_PIXEL_MODE_BGRA: + { + FT_Byte* s = source->buffer; + FT_Byte* t = target->buffer; + FT_Int i; + + + target->num_grays = 256; + + for ( i = source->rows; i > 0; i-- ) + { + FT_Byte* ss = s; + FT_Byte* tt = t; + FT_Int j; + + + for ( j = source->width; j > 0; j-- ) + { + tt[0] = ft_gray_for_premultiplied_srgb_bgra( ss ); + + ss += 4; + tt += 1; + } + + s += source_pitch; + t += target_pitch; + } + } + break; + + default: + ; + } + + return error; + } +",1," FT_Bitmap_Convert( FT_Library library, + const FT_Bitmap *source, + FT_Bitmap *target, + FT_Int alignment ) + { + FT_Error error = FT_Err_Ok; + FT_Memory memory; + + FT_Int source_pitch, target_pitch; + + + if ( !library ) + return FT_THROW( Invalid_Library_Handle ); + + memory = library->memory; + + switch ( source->pixel_mode ) + { + case FT_PIXEL_MODE_MONO: + case FT_PIXEL_MODE_GRAY: + case FT_PIXEL_MODE_GRAY2: + case FT_PIXEL_MODE_GRAY4: + case FT_PIXEL_MODE_LCD: + case FT_PIXEL_MODE_LCD_V: + case FT_PIXEL_MODE_LCD_V: + case FT_PIXEL_MODE_BGRA: + { + FT_Int pad, old_target_pitch; + FT_ULong old_size; + + + old_target_pitch = target->pitch; + old_target_pitch = -old_target_pitch; + + old_size = target->rows * old_target_pitch; + + target->pixel_mode = FT_PIXEL_MODE_GRAY; + target->rows = source->rows; + target->width = source->width; + + pad = 0; + if ( alignment > 0 ) + { + pad = source->width % alignment; + if ( pad != 0 ) + pad = alignment - pad; + } + + target_pitch = source->width + pad; + + if ( target_pitch > 0 && + (FT_ULong)target->rows > FT_ULONG_MAX / target_pitch ) + return FT_THROW( Invalid_Argument ); + + if ( target->rows * target_pitch > old_size && + FT_QREALLOC( target->buffer, + old_size, target->rows * target_pitch ) ) + return error; + + target->pitch = target->pitch < 0 ? -target_pitch : target_pitch; + } + break; + + default: + error = FT_THROW( Invalid_Argument ); + } + + source_pitch = source->pitch; + if ( source_pitch < 0 ) + source_pitch = -source_pitch; + + switch ( source->pixel_mode ) + { + case FT_PIXEL_MODE_MONO: + { + FT_Byte* s = source->buffer; + FT_Byte* t = target->buffer; + FT_Int i; + + + target->num_grays = 2; + + for ( i = source->rows; i > 0; i-- ) + { + FT_Byte* ss = s; + FT_Byte* tt = t; + FT_Int j; + + + /* get the full bytes */ + for ( j = source->width >> 3; j > 0; j-- ) + { + FT_Int val = ss[0]; /* avoid a byte->int cast on each line */ + + + tt[0] = (FT_Byte)( ( val & 0x80 ) >> 7 ); + tt[1] = (FT_Byte)( ( val & 0x40 ) >> 6 ); + tt[2] = (FT_Byte)( ( val & 0x20 ) >> 5 ); + tt[3] = (FT_Byte)( ( val & 0x10 ) >> 4 ); + tt[4] = (FT_Byte)( ( val & 0x08 ) >> 3 ); + tt[5] = (FT_Byte)( ( val & 0x04 ) >> 2 ); + tt[6] = (FT_Byte)( ( val & 0x02 ) >> 1 ); + tt[7] = (FT_Byte)( val & 0x01 ); + + tt += 8; + ss += 1; + } + + /* get remaining pixels (if any) */ + j = source->width & 7; + if ( j > 0 ) + { + FT_Int val = *ss; + + + for ( ; j > 0; j-- ) + { + tt[0] = (FT_Byte)( ( val & 0x80 ) >> 7); + val <<= 1; + tt += 1; + } + } + + s += source_pitch; + t += target_pitch; + } + } + break; + + + case FT_PIXEL_MODE_GRAY: + case FT_PIXEL_MODE_LCD: + case FT_PIXEL_MODE_LCD_V: + { + FT_Int width = source->width; + FT_Byte* s = source->buffer; + FT_Byte* t = target->buffer; + FT_Int i; + + + target->num_grays = 256; + + for ( i = source->rows; i > 0; i-- ) + { + FT_ARRAY_COPY( t, s, width ); + + s += source_pitch; + t += target_pitch; + } + } + break; + + + case FT_PIXEL_MODE_GRAY2: + { + FT_Byte* s = source->buffer; + FT_Byte* t = target->buffer; + FT_Int i; + + + target->num_grays = 4; + + for ( i = source->rows; i > 0; i-- ) + { + FT_Byte* ss = s; + FT_Byte* tt = t; + FT_Int j; + + + /* get the full bytes */ + for ( j = source->width >> 2; j > 0; j-- ) + { + FT_Int val = ss[0]; + + + tt[0] = (FT_Byte)( ( val & 0xC0 ) >> 6 ); + tt[1] = (FT_Byte)( ( val & 0x30 ) >> 4 ); + tt[2] = (FT_Byte)( ( val & 0x0C ) >> 2 ); + tt[3] = (FT_Byte)( ( val & 0x03 ) ); + + ss += 1; + tt += 4; + } + + j = source->width & 3; + if ( j > 0 ) + { + FT_Int val = ss[0]; + + + for ( ; j > 0; j-- ) + { + tt[0] = (FT_Byte)( ( val & 0xC0 ) >> 6 ); + val <<= 2; + tt += 1; + } + } + + s += source_pitch; + t += target_pitch; + } + } + break; + + + case FT_PIXEL_MODE_GRAY4: + { + FT_Byte* s = source->buffer; + FT_Byte* t = target->buffer; + FT_Int i; + + + target->num_grays = 16; + + for ( i = source->rows; i > 0; i-- ) + { + FT_Byte* ss = s; + FT_Byte* tt = t; + FT_Int j; + + + /* get the full bytes */ + for ( j = source->width >> 1; j > 0; j-- ) + { + FT_Int val = ss[0]; + + + tt[0] = (FT_Byte)( ( val & 0xF0 ) >> 4 ); + tt[1] = (FT_Byte)( ( val & 0x0F ) ); + + ss += 1; + tt += 2; + } + + if ( source->width & 1 ) + tt[0] = (FT_Byte)( ( ss[0] & 0xF0 ) >> 4 ); + + s += source_pitch; + t += target_pitch; + } + } + break; + + + case FT_PIXEL_MODE_BGRA: + { + FT_Byte* s = source->buffer; + FT_Byte* t = target->buffer; + FT_Int i; + + + target->num_grays = 256; + + for ( i = source->rows; i > 0; i-- ) + { + FT_Byte* ss = s; + FT_Byte* tt = t; + FT_Int j; + + + for ( j = source->width; j > 0; j-- ) + { + tt[0] = ft_gray_for_premultiplied_srgb_bgra( ss ); + + ss += 4; + tt += 1; + } + + s += source_pitch; + t += target_pitch; + } + } + break; + + default: + ; + } + + return error; + } +","@@ -62,7 +62,7 @@ + + if ( pitch < 0 ) + pitch = -pitch; +- size = (FT_ULong)( pitch * source->rows ); ++ size = (FT_ULong)pitch * source->rows; + + if ( target->buffer ) + { +@@ -72,7 +72,7 @@ + + if ( target_pitch < 0 ) + target_pitch = -target_pitch; +- target_size = (FT_ULong)( target_pitch * target->rows ); ++ target_size = (FT_ULong)target_pitch * target->rows; + + if ( target_size != size ) + (void)FT_QREALLOC( target->buffer, target_size, size ); +@@ -109,7 +109,7 @@ + int pitch; + int new_pitch; + FT_UInt bpp; +- FT_Int i, width, height; ++ FT_UInt i, width, height; + unsigned char* buffer = NULL; + + +@@ -147,17 +147,17 @@ + if ( ypixels == 0 && new_pitch <= pitch ) + { + /* zero the padding */ +- FT_Int bit_width = pitch * 8; +- FT_Int bit_last = ( width + xpixels ) * bpp; ++ FT_UInt bit_width = pitch * 8; ++ FT_UInt bit_last = ( width + xpixels ) * bpp; + + + if ( bit_last < bit_width ) + { + FT_Byte* line = bitmap->buffer + ( bit_last >> 3 ); + FT_Byte* end = bitmap->buffer + pitch; +- FT_Int shift = bit_last & 7; ++ FT_UInt shift = bit_last & 7; + FT_UInt mask = 0xFF00U >> shift; +- FT_Int count = height; ++ FT_UInt count = height; + + + for ( ; count > 0; count--, line += pitch, end += pitch ) +@@ -186,7 +186,7 @@ + /* thus take care of the flow direction */ + if ( bitmap->pitch > 0 ) + { +- FT_Int len = ( width * bpp + 7 ) >> 3; ++ FT_UInt len = ( width * bpp + 7 ) >> 3; + + + for ( i = 0; i < bitmap->rows; i++ ) +@@ -195,7 +195,7 @@ + } + else + { +- FT_Int len = ( width * bpp + 7 ) >> 3; ++ FT_UInt len = ( width * bpp + 7 ) >> 3; + + + for ( i = 0; i < bitmap->rows; i++ ) +@@ -226,7 +226,8 @@ + { + FT_Error error; + unsigned char* p; +- FT_Int i, x, y, pitch; ++ FT_Int i, x, pitch; ++ FT_UInt y; + FT_Int xstr, ystr; + + +@@ -451,8 +452,8 @@ + case FT_PIXEL_MODE_LCD_V: + case FT_PIXEL_MODE_BGRA: + { +- FT_Int pad, old_target_pitch; +- FT_Long old_size; ++ FT_Int pad, old_target_pitch; ++ FT_ULong old_size; + + + old_target_pitch = target->pitch;",1809,2140,4096 +4286,"int md_run(struct mddev *mddev) +{ + int err; + struct md_rdev *rdev; + struct md_personality *pers; + + if (list_empty(&mddev->disks)) + /* cannot run an array with no devices.. */ + return -EINVAL; + + if (mddev->pers) + return -EBUSY; + /* Cannot run until previous stop completes properly */ + if (mddev->sysfs_active) + return -EBUSY; + + /* + * Analyze all RAID superblock(s) + */ + if (!mddev->raid_disks) { + if (!mddev->persistent) + return -EINVAL; + analyze_sbs(mddev); + } + + if (mddev->level != LEVEL_NONE) + request_module(""md-level-%d"", mddev->level); + else if (mddev->clevel[0]) + request_module(""md-%s"", mddev->clevel); + + /* + * Drop all container device buffers, from now on + * the only valid external interface is through the md + * device. + */ + rdev_for_each(rdev, mddev) { + if (test_bit(Faulty, &rdev->flags)) + continue; + sync_blockdev(rdev->bdev); + invalidate_bdev(rdev->bdev); + + /* perform some consistency tests on the device. + * We don't want the data to overlap the metadata, + * Internal Bitmap issues have been handled elsewhere. + */ + if (rdev->meta_bdev) { + /* Nothing to check */; + } else if (rdev->data_offset < rdev->sb_start) { + if (mddev->dev_sectors && + rdev->data_offset + mddev->dev_sectors + > rdev->sb_start) { + printk(""md: %s: data overlaps metadata\n"", + mdname(mddev)); + return -EINVAL; + } + } else { + if (rdev->sb_start + rdev->sb_size/512 + > rdev->data_offset) { + printk(""md: %s: metadata overlaps data\n"", + mdname(mddev)); + return -EINVAL; + } + } + sysfs_notify_dirent_safe(rdev->sysfs_state); + } + + if (mddev->bio_set == NULL) + mddev->bio_set = bioset_create(BIO_POOL_SIZE, 0); + + spin_lock(&pers_lock); + pers = find_pers(mddev->level, mddev->clevel); + if (!pers || !try_module_get(pers->owner)) { + spin_unlock(&pers_lock); + if (mddev->level != LEVEL_NONE) + printk(KERN_WARNING ""md: personality for level %d is not loaded!\n"", + mddev->level); + else + printk(KERN_WARNING ""md: personality for level %s is not loaded!\n"", + mddev->clevel); + return -EINVAL; + } + spin_unlock(&pers_lock); + if (mddev->level != pers->level) { + mddev->level = pers->level; + mddev->new_level = pers->level; + } + strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel)); + + if (mddev->reshape_position != MaxSector && + pers->start_reshape == NULL) { + /* This personality cannot handle reshaping... */ + module_put(pers->owner); + return -EINVAL; + } + + if (pers->sync_request) { + /* Warn if this is a potentially silly + * configuration. + */ + char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE]; + struct md_rdev *rdev2; + int warned = 0; + + rdev_for_each(rdev, mddev) + rdev_for_each(rdev2, mddev) { + if (rdev < rdev2 && + rdev->bdev->bd_contains == + rdev2->bdev->bd_contains) { + printk(KERN_WARNING + ""%s: WARNING: %s appears to be"" + "" on the same physical disk as"" + "" %s.\n"", + mdname(mddev), + bdevname(rdev->bdev,b), + bdevname(rdev2->bdev,b2)); + warned = 1; + } + } + + if (warned) + printk(KERN_WARNING + ""True protection against single-disk"" + "" failure might be compromised.\n""); + } + + mddev->recovery = 0; + /* may be over-ridden by personality */ + mddev->resync_max_sectors = mddev->dev_sectors; + + mddev->ok_start_degraded = start_dirty_degraded; + + if (start_readonly && mddev->ro == 0) + mddev->ro = 2; /* read-only, but switch on first write */ + + err = pers->run(mddev); + if (err) + printk(KERN_ERR ""md: pers->run() failed ...\n""); + else if (pers->size(mddev, 0, 0) < mddev->array_sectors) { + WARN_ONCE(!mddev->external_size, ""%s: default size too small,"" + "" but 'external_size' not in effect?\n"", __func__); + printk(KERN_ERR + ""md: invalid array_size %llu > default size %llu\n"", + (unsigned long long)mddev->array_sectors / 2, + (unsigned long long)pers->size(mddev, 0, 0) / 2); + err = -EINVAL; + } + if (err == 0 && pers->sync_request && + (mddev->bitmap_info.file || mddev->bitmap_info.offset)) { + struct bitmap *bitmap; + + bitmap = bitmap_create(mddev, -1); + if (IS_ERR(bitmap)) { + err = PTR_ERR(bitmap); + printk(KERN_ERR ""%s: failed to create bitmap (%d)\n"", + mdname(mddev), err); + } else + mddev->bitmap = bitmap; + + } + if (err) { + mddev_detach(mddev); + if (mddev->private) + pers->free(mddev, mddev->private); + mddev->private = NULL; + module_put(pers->owner); + bitmap_destroy(mddev); + return err; + } + if (mddev->queue) { + mddev->queue->backing_dev_info.congested_data = mddev; + mddev->queue->backing_dev_info.congested_fn = md_congested; + blk_queue_merge_bvec(mddev->queue, md_mergeable_bvec); + } + if (pers->sync_request) { + if (mddev->kobj.sd && + sysfs_create_group(&mddev->kobj, &md_redundancy_group)) + printk(KERN_WARNING + ""md: cannot register extra attributes for %s\n"", + mdname(mddev)); + mddev->sysfs_action = sysfs_get_dirent_safe(mddev->kobj.sd, ""sync_action""); + } else if (mddev->ro == 2) /* auto-readonly not meaningful */ + mddev->ro = 0; + + atomic_set(&mddev->writes_pending,0); + atomic_set(&mddev->max_corr_read_errors, + MD_DEFAULT_MAX_CORRECTED_READ_ERRORS); + mddev->safemode = 0; + mddev->safemode_timer.function = md_safemode_timeout; + mddev->safemode_timer.data = (unsigned long) mddev; + mddev->safemode_delay = (200 * HZ)/1000 +1; /* 200 msec delay */ + mddev->in_sync = 1; + smp_wmb(); + spin_lock(&mddev->lock); + mddev->pers = pers; + mddev->ready = 1; + spin_unlock(&mddev->lock); + rdev_for_each(rdev, mddev) + if (rdev->raid_disk >= 0) + if (sysfs_link_rdev(mddev, rdev)) + /* failure here is OK */; + + set_bit(MD_RECOVERY_NEEDED, &mddev->recovery); + + if (mddev->flags & MD_UPDATE_SB_FLAGS) + md_update_sb(mddev, 0); + + md_new_event(mddev); + sysfs_notify_dirent_safe(mddev->sysfs_state); + sysfs_notify_dirent_safe(mddev->sysfs_action); + sysfs_notify(&mddev->kobj, NULL, ""degraded""); + return 0; +} +",0,"int md_run(struct mddev *mddev) +{ + int err; + struct md_rdev *rdev; + struct md_personality *pers; + + if (list_empty(&mddev->disks)) + /* cannot run an array with no devices.. */ + return -EINVAL; + + if (mddev->pers) + return -EBUSY; + /* Cannot run until previous stop completes properly */ + if (mddev->sysfs_active) + return -EBUSY; + + /* + * Analyze all RAID superblock(s) + */ + if (!mddev->raid_disks) { + if (!mddev->persistent) + return -EINVAL; + analyze_sbs(mddev); + } + + if (mddev->level != LEVEL_NONE) + request_module(""md-level-%d"", mddev->level); + else if (mddev->clevel[0]) + request_module(""md-%s"", mddev->clevel); + + /* + * Drop all container device buffers, from now on + * the only valid external interface is through the md + * device. + */ + rdev_for_each(rdev, mddev) { + if (test_bit(Faulty, &rdev->flags)) + continue; + sync_blockdev(rdev->bdev); + invalidate_bdev(rdev->bdev); + + /* perform some consistency tests on the device. + * We don't want the data to overlap the metadata, + * Internal Bitmap issues have been handled elsewhere. + */ + if (rdev->meta_bdev) { + /* Nothing to check */; + } else if (rdev->data_offset < rdev->sb_start) { + if (mddev->dev_sectors && + rdev->data_offset + mddev->dev_sectors + > rdev->sb_start) { + printk(""md: %s: data overlaps metadata\n"", + mdname(mddev)); + return -EINVAL; + } + } else { + if (rdev->sb_start + rdev->sb_size/512 + > rdev->data_offset) { + printk(""md: %s: metadata overlaps data\n"", + mdname(mddev)); + return -EINVAL; + } + } + sysfs_notify_dirent_safe(rdev->sysfs_state); + } + + if (mddev->bio_set == NULL) + mddev->bio_set = bioset_create(BIO_POOL_SIZE, 0); + + spin_lock(&pers_lock); + pers = find_pers(mddev->level, mddev->clevel); + if (!pers || !try_module_get(pers->owner)) { + spin_unlock(&pers_lock); + if (mddev->level != LEVEL_NONE) + printk(KERN_WARNING ""md: personality for level %d is not loaded!\n"", + mddev->level); + else + printk(KERN_WARNING ""md: personality for level %s is not loaded!\n"", + mddev->clevel); + return -EINVAL; + } + spin_unlock(&pers_lock); + if (mddev->level != pers->level) { + mddev->level = pers->level; + mddev->new_level = pers->level; + } + strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel)); + + if (mddev->reshape_position != MaxSector && + pers->start_reshape == NULL) { + /* This personality cannot handle reshaping... */ + module_put(pers->owner); + return -EINVAL; + } + + if (pers->sync_request) { + /* Warn if this is a potentially silly + * configuration. + */ + char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE]; + struct md_rdev *rdev2; + int warned = 0; + + rdev_for_each(rdev, mddev) + rdev_for_each(rdev2, mddev) { + if (rdev < rdev2 && + rdev->bdev->bd_contains == + rdev2->bdev->bd_contains) { + printk(KERN_WARNING + ""%s: WARNING: %s appears to be"" + "" on the same physical disk as"" + "" %s.\n"", + mdname(mddev), + bdevname(rdev->bdev,b), + bdevname(rdev2->bdev,b2)); + warned = 1; + } + } + + if (warned) + printk(KERN_WARNING + ""True protection against single-disk"" + "" failure might be compromised.\n""); + } + + mddev->recovery = 0; + /* may be over-ridden by personality */ + mddev->resync_max_sectors = mddev->dev_sectors; + + mddev->ok_start_degraded = start_dirty_degraded; + + if (start_readonly && mddev->ro == 0) + mddev->ro = 2; /* read-only, but switch on first write */ + + err = pers->run(mddev); + if (err) + printk(KERN_ERR ""md: pers->run() failed ...\n""); + else if (pers->size(mddev, 0, 0) < mddev->array_sectors) { + WARN_ONCE(!mddev->external_size, ""%s: default size too small,"" + "" but 'external_size' not in effect?\n"", __func__); + printk(KERN_ERR + ""md: invalid array_size %llu > default size %llu\n"", + (unsigned long long)mddev->array_sectors / 2, + (unsigned long long)pers->size(mddev, 0, 0) / 2); + err = -EINVAL; + } + if (err == 0 && pers->sync_request && + (mddev->bitmap_info.file || mddev->bitmap_info.offset)) { + struct bitmap *bitmap; + + bitmap = bitmap_create(mddev, -1); + if (IS_ERR(bitmap)) { + err = PTR_ERR(bitmap); + printk(KERN_ERR ""%s: failed to create bitmap (%d)\n"", + mdname(mddev), err); + } else + mddev->bitmap = bitmap; + + } + if (err) { + mddev_detach(mddev); + if (mddev->private) + pers->free(mddev, mddev->private); + mddev->private = NULL; + module_put(pers->owner); + bitmap_destroy(mddev); + return err; + } + if (mddev->queue) { + mddev->queue->backing_dev_info.congested_data = mddev; + mddev->queue->backing_dev_info.congested_fn = md_congested; + blk_queue_merge_bvec(mddev->queue, md_mergeable_bvec); + } + if (pers->sync_request) { + if (mddev->kobj.sd && + sysfs_create_group(&mddev->kobj, &md_redundancy_group)) + printk(KERN_WARNING + ""md: cannot register extra attributes for %s\n"", + mdname(mddev)); + mddev->sysfs_action = sysfs_get_dirent_safe(mddev->kobj.sd, ""sync_action""); + } else if (mddev->ro == 2) /* auto-readonly not meaningful */ + mddev->ro = 0; + + atomic_set(&mddev->writes_pending,0); + atomic_set(&mddev->max_corr_read_errors, + MD_DEFAULT_MAX_CORRECTED_READ_ERRORS); + mddev->safemode = 0; + mddev->safemode_timer.function = md_safemode_timeout; + mddev->safemode_timer.data = (unsigned long) mddev; + mddev->safemode_delay = (200 * HZ)/1000 +1; /* 200 msec delay */ + mddev->in_sync = 1; + smp_wmb(); + spin_lock(&mddev->lock); + mddev->pers = pers; + mddev->ready = 1; + spin_unlock(&mddev->lock); + rdev_for_each(rdev, mddev) + if (rdev->raid_disk >= 0) + if (sysfs_link_rdev(mddev, rdev)) + /* failure here is OK */; + + set_bit(MD_RECOVERY_NEEDED, &mddev->recovery); + + if (mddev->flags & MD_UPDATE_SB_FLAGS) + md_update_sb(mddev, 0); + + md_new_event(mddev); + sysfs_notify_dirent_safe(mddev->sysfs_state); + sysfs_notify_dirent_safe(mddev->sysfs_action); + sysfs_notify(&mddev->kobj, NULL, ""degraded""); + return 0; +} +","@@ -5759,7 +5759,7 @@ static int get_bitmap_file(struct mddev *mddev, void __user * arg) + char *ptr; + int err; + +- file = kmalloc(sizeof(*file), GFP_NOIO); ++ file = kzalloc(sizeof(*file), GFP_NOIO); + if (!file) + return -ENOMEM; + ",1828,2159,4096 +17016,"xsltParsePreprocessStylesheetTree(xsltCompilerCtxtPtr cctxt, xmlNodePtr node) +{ + xmlNodePtr deleteNode, cur, txt, textNode = NULL; + xmlDocPtr doc; + xsltStylesheetPtr style; + int internalize = 0, findSpaceAttr; + int xsltStylesheetElemDepth; + xmlAttrPtr attr; + xmlChar *value; + const xmlChar *name, *nsNameXSLT = NULL; + int strictWhitespace, inXSLText = 0; +#ifdef XSLT_REFACTORED_XSLT_NSCOMP + xsltNsMapPtr nsMapItem; +#endif + + if ((cctxt == NULL) || (cctxt->style == NULL) || + (node == NULL) || (node->type != XML_ELEMENT_NODE)) + return(-1); + + doc = node->doc; + if (doc == NULL) + goto internal_err; + + style = cctxt->style; + if ((style->dict != NULL) && (doc->dict == style->dict)) + internalize = 1; + else + style->internalized = 0; + + /* + * Init value of xml:space. Since this might be an embedded + * stylesheet, this is needed to be performed on the element + * where the stylesheet is rooted at, taking xml:space of + * ancestors into account. + */ + if (! cctxt->simplified) + xsltStylesheetElemDepth = cctxt->depth +1; + else + xsltStylesheetElemDepth = 0; + + if (xmlNodeGetSpacePreserve(node) != 1) + cctxt->inode->preserveWhitespace = 0; + else + cctxt->inode->preserveWhitespace = 1; + + /* + * Eval if we should keep the old incorrect behaviour. + */ + strictWhitespace = (cctxt->strict != 0) ? 1 : 0; + + nsNameXSLT = xsltConstNamespaceNameXSLT; + + deleteNode = NULL; + cur = node; + while (cur != NULL) { + if (deleteNode != NULL) { + +#ifdef WITH_XSLT_DEBUG_BLANKS + xsltGenericDebug(xsltGenericDebugContext, + ""xsltParsePreprocessStylesheetTree: removing node\n""); +#endif + xmlUnlinkNode(deleteNode); + xmlFreeNode(deleteNode); + deleteNode = NULL; + } + if (cur->type == XML_ELEMENT_NODE) { + + /* + * Clear the PSVI field. + */ + cur->psvi = NULL; + + xsltCompilerNodePush(cctxt, cur); + + inXSLText = 0; + textNode = NULL; + findSpaceAttr = 1; + cctxt->inode->stripWhitespace = 0; + /* + * TODO: I'd love to use a string pointer comparison here :-/ + */ + if (IS_XSLT_ELEM(cur)) { +#ifdef XSLT_REFACTORED_XSLT_NSCOMP + if (cur->ns->href != nsNameXSLT) { + nsMapItem = xsltNewNamespaceMapItem(cctxt, + doc, cur->ns, cur); + if (nsMapItem == NULL) + goto internal_err; + cur->ns->href = nsNameXSLT; + } +#endif + + if (cur->name == NULL) + goto process_attributes; + /* + * Mark the XSLT element for later recognition. + * TODO: Using the marker is still too dangerous, since if + * the parsing mechanism leaves out an XSLT element, then + * this might hit the transformation-mechanism, which + * will break if it doesn't expect such a marker. + */ + /* cur->psvi = (void *) xsltXSLTElemMarker; */ + + /* + * XSLT 2.0: ""Any whitespace text node whose parent is + * one of the following elements is removed from the "" + * tree, regardless of any xml:space attributes:..."" + * xsl:apply-imports, + * xsl:apply-templates, + * xsl:attribute-set, + * xsl:call-template, + * xsl:choose, + * xsl:stylesheet, xsl:transform. + * XSLT 2.0: xsl:analyze-string, + * xsl:character-map, + * xsl:next-match + * + * TODO: I'd love to use a string pointer comparison here :-/ + */ + name = cur->name; + switch (*name) { + case 't': + if ((name[0] == 't') && (name[1] == 'e') && + (name[2] == 'x') && (name[3] == 't') && + (name[4] == 0)) + { + /* + * Process the xsl:text element. + * ---------------------------- + * Mark it for later recognition. + */ + cur->psvi = (void *) xsltXSLTTextMarker; + /* + * For stylesheets, the set of + * whitespace-preserving element names + * consists of just xsl:text. + */ + findSpaceAttr = 0; + cctxt->inode->preserveWhitespace = 1; + inXSLText = 1; + } + break; + case 'c': + if (xmlStrEqual(name, BAD_CAST ""choose"") || + xmlStrEqual(name, BAD_CAST ""call-template"")) + cctxt->inode->stripWhitespace = 1; + break; + case 'a': + if (xmlStrEqual(name, BAD_CAST ""apply-templates"") || + xmlStrEqual(name, BAD_CAST ""apply-imports"") || + xmlStrEqual(name, BAD_CAST ""attribute-set"")) + + cctxt->inode->stripWhitespace = 1; + break; + default: + if (xsltStylesheetElemDepth == cctxt->depth) { + /* + * This is a xsl:stylesheet/xsl:transform. + */ + cctxt->inode->stripWhitespace = 1; + break; + } + + if ((cur->prev != NULL) && + (cur->prev->type == XML_TEXT_NODE)) + { + /* + * XSLT 2.0 : ""Any whitespace text node whose + * following-sibling node is an xsl:param or + * xsl:sort element is removed from the tree, + * regardless of any xml:space attributes."" + */ + if (((*name == 'p') || (*name == 's')) && + (xmlStrEqual(name, BAD_CAST ""param"") || + xmlStrEqual(name, BAD_CAST ""sort""))) + { + do { + if (IS_BLANK_NODE(cur->prev)) { + txt = cur->prev; + xmlUnlinkNode(txt); + xmlFreeNode(txt); + } else { + /* + * This will result in a content + * error, when hitting the parsing + * functions. + */ + break; + } + } while (cur->prev); + } + } + break; + } + } + +process_attributes: + /* + * Process attributes. + * ------------------ + */ + if (cur->properties != NULL) { + if (cur->children == NULL) + findSpaceAttr = 0; + attr = cur->properties; + do { +#ifdef XSLT_REFACTORED_XSLT_NSCOMP + if ((attr->ns) && (attr->ns->href != nsNameXSLT) && + xmlStrEqual(attr->ns->href, nsNameXSLT)) + { + nsMapItem = xsltNewNamespaceMapItem(cctxt, + doc, attr->ns, cur); + if (nsMapItem == NULL) + goto internal_err; + attr->ns->href = nsNameXSLT; + } +#endif + if (internalize) { + /* + * Internalize the attribute's value; the goal is to + * speed up operations and minimize used space by + * compiled stylesheets. + */ + txt = attr->children; + /* + * NOTE that this assumes only one + * text-node in the attribute's content. + */ + if ((txt != NULL) && (txt->content != NULL) && + (!xmlDictOwns(style->dict, txt->content))) + { + value = (xmlChar *) xmlDictLookup(style->dict, + txt->content, -1); + xmlNodeSetContent(txt, NULL); + txt->content = value; + } + } + /* + * Process xml:space attributes. + * ---------------------------- + */ + if ((findSpaceAttr != 0) && + (attr->ns != NULL) && + (attr->name != NULL) && + (attr->name[0] == 's') && + (attr->ns->prefix != NULL) && + (attr->ns->prefix[0] == 'x') && + (attr->ns->prefix[1] == 'm') && + (attr->ns->prefix[2] == 'l') && + (attr->ns->prefix[3] == 0)) + { + value = xmlGetNsProp(cur, BAD_CAST ""space"", + XML_XML_NAMESPACE); + if (value != NULL) { + if (xmlStrEqual(value, BAD_CAST ""preserve"")) { + cctxt->inode->preserveWhitespace = 1; + } else if (xmlStrEqual(value, BAD_CAST ""default"")) { + cctxt->inode->preserveWhitespace = 0; + } else { + /* Invalid value for xml:space. */ + xsltTransformError(NULL, style, cur, + ""Attribute xml:space: Invalid value.\n""); + cctxt->style->warnings++; + } + findSpaceAttr = 0; + xmlFree(value); + } + + } + attr = attr->next; + } while (attr != NULL); + } + /* + * We'll descend into the children of element nodes only. + */ + if (cur->children != NULL) { + cur = cur->children; + continue; + } + } else if ((cur->type == XML_TEXT_NODE) || + (cur->type == XML_CDATA_SECTION_NODE)) + { + /* + * Merge adjacent text/CDATA-section-nodes + * --------------------------------------- + * In order to avoid breaking of existing stylesheets, + * if the old behaviour is wanted (strictWhitespace == 0), + * then we *won't* merge adjacent text-nodes + * (except in xsl:text); this will ensure that whitespace-only + * text nodes are (incorrectly) not stripped in some cases. + * + * Example: : zoo + * Corrent (strict) result: zoo + * Incorrect (old) result : zoo + * + * NOTE that we *will* merge adjacent text-nodes if + * they are in xsl:text. + * Example, the following: + * zoo + * will result in both cases in: + * zoo + */ + cur->type = XML_TEXT_NODE; + if ((strictWhitespace != 0) || (inXSLText != 0)) { + /* + * New behaviour; merge nodes. + */ + if (textNode == NULL) + textNode = cur; + else { + if (cur->content != NULL) + xmlNodeAddContent(textNode, cur->content); + deleteNode = cur; + } + if ((cur->next == NULL) || + (cur->next->type == XML_ELEMENT_NODE)) + goto end_of_text; + else + goto next_sibling; + } else { + /* + * Old behaviour. + */ + if (textNode == NULL) + textNode = cur; + goto end_of_text; + } + } else if ((cur->type == XML_COMMENT_NODE) || + (cur->type == XML_PI_NODE)) + { + /* + * Remove processing instructions and comments. + */ + deleteNode = cur; + if ((cur->next == NULL) || + (cur->next->type == XML_ELEMENT_NODE)) + goto end_of_text; + else + goto next_sibling; + } else { + textNode = NULL; + /* + * Invalid node-type for this data-model. + */ + xsltTransformError(NULL, style, cur, + ""Invalid type of node for the XSLT data model.\n""); + cctxt->style->errors++; + goto next_sibling; + } + +end_of_text: + if (textNode) { + value = textNode->content; + /* + * At this point all adjacent text/CDATA-section nodes + * have been merged. + * + * Strip whitespace-only text-nodes. + * (cctxt->inode->stripWhitespace) + */ + if ((value == NULL) || (*value == 0) || + (((cctxt->inode->stripWhitespace) || + (! cctxt->inode->preserveWhitespace)) && + IS_BLANK(*value) && + xsltIsBlank(value))) + { + if (textNode != cur) { + xmlUnlinkNode(textNode); + xmlFreeNode(textNode); + } else + deleteNode = textNode; + textNode = NULL; + goto next_sibling; + } + /* + * Convert CDATA-section nodes to text-nodes. + * TODO: Can this produce problems? + */ + if (textNode->type != XML_TEXT_NODE) { + textNode->type = XML_TEXT_NODE; + textNode->name = xmlStringText; + } + if (internalize && + (textNode->content != NULL) && + (!xmlDictOwns(style->dict, textNode->content))) + { + /* + * Internalize the string. + */ + value = (xmlChar *) xmlDictLookup(style->dict, + textNode->content, -1); + xmlNodeSetContent(textNode, NULL); + textNode->content = value; + } + textNode = NULL; + /* + * Note that ""disable-output-escaping"" of the xsl:text + * element will be applied at a later level, when + * XSLT elements are processed. + */ + } + +next_sibling: + if (cur->type == XML_ELEMENT_NODE) { + xsltCompilerNodePop(cctxt, cur); + } + if (cur == node) + break; + if (cur->next != NULL) { + cur = cur->next; + } else { + cur = cur->parent; + inXSLText = 0; + goto next_sibling; + }; + } + if (deleteNode != NULL) { +#ifdef WITH_XSLT_DEBUG_PARSING + xsltGenericDebug(xsltGenericDebugContext, + ""xsltParsePreprocessStylesheetTree: removing node\n""); +#endif + xmlUnlinkNode(deleteNode); + xmlFreeNode(deleteNode); + } + return(0); + +internal_err: + return(-1); +} +",0,"xsltParsePreprocessStylesheetTree(xsltCompilerCtxtPtr cctxt, xmlNodePtr node) +{ + xmlNodePtr deleteNode, cur, txt, textNode = NULL; + xmlDocPtr doc; + xsltStylesheetPtr style; + int internalize = 0, findSpaceAttr; + int xsltStylesheetElemDepth; + xmlAttrPtr attr; + xmlChar *value; + const xmlChar *name, *nsNameXSLT = NULL; + int strictWhitespace, inXSLText = 0; +#ifdef XSLT_REFACTORED_XSLT_NSCOMP + xsltNsMapPtr nsMapItem; +#endif + + if ((cctxt == NULL) || (cctxt->style == NULL) || + (node == NULL) || (node->type != XML_ELEMENT_NODE)) + return(-1); + + doc = node->doc; + if (doc == NULL) + goto internal_err; + + style = cctxt->style; + if ((style->dict != NULL) && (doc->dict == style->dict)) + internalize = 1; + else + style->internalized = 0; + + /* + * Init value of xml:space. Since this might be an embedded + * stylesheet, this is needed to be performed on the element + * where the stylesheet is rooted at, taking xml:space of + * ancestors into account. + */ + if (! cctxt->simplified) + xsltStylesheetElemDepth = cctxt->depth +1; + else + xsltStylesheetElemDepth = 0; + + if (xmlNodeGetSpacePreserve(node) != 1) + cctxt->inode->preserveWhitespace = 0; + else + cctxt->inode->preserveWhitespace = 1; + + /* + * Eval if we should keep the old incorrect behaviour. + */ + strictWhitespace = (cctxt->strict != 0) ? 1 : 0; + + nsNameXSLT = xsltConstNamespaceNameXSLT; + + deleteNode = NULL; + cur = node; + while (cur != NULL) { + if (deleteNode != NULL) { + +#ifdef WITH_XSLT_DEBUG_BLANKS + xsltGenericDebug(xsltGenericDebugContext, + ""xsltParsePreprocessStylesheetTree: removing node\n""); +#endif + xmlUnlinkNode(deleteNode); + xmlFreeNode(deleteNode); + deleteNode = NULL; + } + if (cur->type == XML_ELEMENT_NODE) { + + /* + * Clear the PSVI field. + */ + cur->psvi = NULL; + + xsltCompilerNodePush(cctxt, cur); + + inXSLText = 0; + textNode = NULL; + findSpaceAttr = 1; + cctxt->inode->stripWhitespace = 0; + /* + * TODO: I'd love to use a string pointer comparison here :-/ + */ + if (IS_XSLT_ELEM(cur)) { +#ifdef XSLT_REFACTORED_XSLT_NSCOMP + if (cur->ns->href != nsNameXSLT) { + nsMapItem = xsltNewNamespaceMapItem(cctxt, + doc, cur->ns, cur); + if (nsMapItem == NULL) + goto internal_err; + cur->ns->href = nsNameXSLT; + } +#endif + + if (cur->name == NULL) + goto process_attributes; + /* + * Mark the XSLT element for later recognition. + * TODO: Using the marker is still too dangerous, since if + * the parsing mechanism leaves out an XSLT element, then + * this might hit the transformation-mechanism, which + * will break if it doesn't expect such a marker. + */ + /* cur->psvi = (void *) xsltXSLTElemMarker; */ + + /* + * XSLT 2.0: ""Any whitespace text node whose parent is + * one of the following elements is removed from the "" + * tree, regardless of any xml:space attributes:..."" + * xsl:apply-imports, + * xsl:apply-templates, + * xsl:attribute-set, + * xsl:call-template, + * xsl:choose, + * xsl:stylesheet, xsl:transform. + * XSLT 2.0: xsl:analyze-string, + * xsl:character-map, + * xsl:next-match + * + * TODO: I'd love to use a string pointer comparison here :-/ + */ + name = cur->name; + switch (*name) { + case 't': + if ((name[0] == 't') && (name[1] == 'e') && + (name[2] == 'x') && (name[3] == 't') && + (name[4] == 0)) + { + /* + * Process the xsl:text element. + * ---------------------------- + * Mark it for later recognition. + */ + cur->psvi = (void *) xsltXSLTTextMarker; + /* + * For stylesheets, the set of + * whitespace-preserving element names + * consists of just xsl:text. + */ + findSpaceAttr = 0; + cctxt->inode->preserveWhitespace = 1; + inXSLText = 1; + } + break; + case 'c': + if (xmlStrEqual(name, BAD_CAST ""choose"") || + xmlStrEqual(name, BAD_CAST ""call-template"")) + cctxt->inode->stripWhitespace = 1; + break; + case 'a': + if (xmlStrEqual(name, BAD_CAST ""apply-templates"") || + xmlStrEqual(name, BAD_CAST ""apply-imports"") || + xmlStrEqual(name, BAD_CAST ""attribute-set"")) + + cctxt->inode->stripWhitespace = 1; + break; + default: + if (xsltStylesheetElemDepth == cctxt->depth) { + /* + * This is a xsl:stylesheet/xsl:transform. + */ + cctxt->inode->stripWhitespace = 1; + break; + } + + if ((cur->prev != NULL) && + (cur->prev->type == XML_TEXT_NODE)) + { + /* + * XSLT 2.0 : ""Any whitespace text node whose + * following-sibling node is an xsl:param or + * xsl:sort element is removed from the tree, + * regardless of any xml:space attributes."" + */ + if (((*name == 'p') || (*name == 's')) && + (xmlStrEqual(name, BAD_CAST ""param"") || + xmlStrEqual(name, BAD_CAST ""sort""))) + { + do { + if (IS_BLANK_NODE(cur->prev)) { + txt = cur->prev; + xmlUnlinkNode(txt); + xmlFreeNode(txt); + } else { + /* + * This will result in a content + * error, when hitting the parsing + * functions. + */ + break; + } + } while (cur->prev); + } + } + break; + } + } + +process_attributes: + /* + * Process attributes. + * ------------------ + */ + if (cur->properties != NULL) { + if (cur->children == NULL) + findSpaceAttr = 0; + attr = cur->properties; + do { +#ifdef XSLT_REFACTORED_XSLT_NSCOMP + if ((attr->ns) && (attr->ns->href != nsNameXSLT) && + xmlStrEqual(attr->ns->href, nsNameXSLT)) + { + nsMapItem = xsltNewNamespaceMapItem(cctxt, + doc, attr->ns, cur); + if (nsMapItem == NULL) + goto internal_err; + attr->ns->href = nsNameXSLT; + } +#endif + if (internalize) { + /* + * Internalize the attribute's value; the goal is to + * speed up operations and minimize used space by + * compiled stylesheets. + */ + txt = attr->children; + /* + * NOTE that this assumes only one + * text-node in the attribute's content. + */ + if ((txt != NULL) && (txt->content != NULL) && + (!xmlDictOwns(style->dict, txt->content))) + { + value = (xmlChar *) xmlDictLookup(style->dict, + txt->content, -1); + xmlNodeSetContent(txt, NULL); + txt->content = value; + } + } + /* + * Process xml:space attributes. + * ---------------------------- + */ + if ((findSpaceAttr != 0) && + (attr->ns != NULL) && + (attr->name != NULL) && + (attr->name[0] == 's') && + (attr->ns->prefix != NULL) && + (attr->ns->prefix[0] == 'x') && + (attr->ns->prefix[1] == 'm') && + (attr->ns->prefix[2] == 'l') && + (attr->ns->prefix[3] == 0)) + { + value = xmlGetNsProp(cur, BAD_CAST ""space"", + XML_XML_NAMESPACE); + if (value != NULL) { + if (xmlStrEqual(value, BAD_CAST ""preserve"")) { + cctxt->inode->preserveWhitespace = 1; + } else if (xmlStrEqual(value, BAD_CAST ""default"")) { + cctxt->inode->preserveWhitespace = 0; + } else { + /* Invalid value for xml:space. */ + xsltTransformError(NULL, style, cur, + ""Attribute xml:space: Invalid value.\n""); + cctxt->style->warnings++; + } + findSpaceAttr = 0; + xmlFree(value); + } + + } + attr = attr->next; + } while (attr != NULL); + } + /* + * We'll descend into the children of element nodes only. + */ + if (cur->children != NULL) { + cur = cur->children; + continue; + } + } else if ((cur->type == XML_TEXT_NODE) || + (cur->type == XML_CDATA_SECTION_NODE)) + { + /* + * Merge adjacent text/CDATA-section-nodes + * --------------------------------------- + * In order to avoid breaking of existing stylesheets, + * if the old behaviour is wanted (strictWhitespace == 0), + * then we *won't* merge adjacent text-nodes + * (except in xsl:text); this will ensure that whitespace-only + * text nodes are (incorrectly) not stripped in some cases. + * + * Example: : zoo + * Corrent (strict) result: zoo + * Incorrect (old) result : zoo + * + * NOTE that we *will* merge adjacent text-nodes if + * they are in xsl:text. + * Example, the following: + * zoo + * will result in both cases in: + * zoo + */ + cur->type = XML_TEXT_NODE; + if ((strictWhitespace != 0) || (inXSLText != 0)) { + /* + * New behaviour; merge nodes. + */ + if (textNode == NULL) + textNode = cur; + else { + if (cur->content != NULL) + xmlNodeAddContent(textNode, cur->content); + deleteNode = cur; + } + if ((cur->next == NULL) || + (cur->next->type == XML_ELEMENT_NODE)) + goto end_of_text; + else + goto next_sibling; + } else { + /* + * Old behaviour. + */ + if (textNode == NULL) + textNode = cur; + goto end_of_text; + } + } else if ((cur->type == XML_COMMENT_NODE) || + (cur->type == XML_PI_NODE)) + { + /* + * Remove processing instructions and comments. + */ + deleteNode = cur; + if ((cur->next == NULL) || + (cur->next->type == XML_ELEMENT_NODE)) + goto end_of_text; + else + goto next_sibling; + } else { + textNode = NULL; + /* + * Invalid node-type for this data-model. + */ + xsltTransformError(NULL, style, cur, + ""Invalid type of node for the XSLT data model.\n""); + cctxt->style->errors++; + goto next_sibling; + } + +end_of_text: + if (textNode) { + value = textNode->content; + /* + * At this point all adjacent text/CDATA-section nodes + * have been merged. + * + * Strip whitespace-only text-nodes. + * (cctxt->inode->stripWhitespace) + */ + if ((value == NULL) || (*value == 0) || + (((cctxt->inode->stripWhitespace) || + (! cctxt->inode->preserveWhitespace)) && + IS_BLANK(*value) && + xsltIsBlank(value))) + { + if (textNode != cur) { + xmlUnlinkNode(textNode); + xmlFreeNode(textNode); + } else + deleteNode = textNode; + textNode = NULL; + goto next_sibling; + } + /* + * Convert CDATA-section nodes to text-nodes. + * TODO: Can this produce problems? + */ + if (textNode->type != XML_TEXT_NODE) { + textNode->type = XML_TEXT_NODE; + textNode->name = xmlStringText; + } + if (internalize && + (textNode->content != NULL) && + (!xmlDictOwns(style->dict, textNode->content))) + { + /* + * Internalize the string. + */ + value = (xmlChar *) xmlDictLookup(style->dict, + textNode->content, -1); + xmlNodeSetContent(textNode, NULL); + textNode->content = value; + } + textNode = NULL; + /* + * Note that ""disable-output-escaping"" of the xsl:text + * element will be applied at a later level, when + * XSLT elements are processed. + */ + } + +next_sibling: + if (cur->type == XML_ELEMENT_NODE) { + xsltCompilerNodePop(cctxt, cur); + } + if (cur == node) + break; + if (cur->next != NULL) { + cur = cur->next; + } else { + cur = cur->parent; + inXSLText = 0; + goto next_sibling; + }; + } + if (deleteNode != NULL) { +#ifdef WITH_XSLT_DEBUG_PARSING + xsltGenericDebug(xsltGenericDebugContext, + ""xsltParsePreprocessStylesheetTree: removing node\n""); +#endif + xmlUnlinkNode(deleteNode); + xmlFreeNode(deleteNode); + } + return(0); + +internal_err: + return(-1); +} +","@@ -5382,7 +5382,6 @@ xsltParseStylesheetTemplate(xsltStylesheetPtr style, xmlNodePtr template) { + prop = xmlGetNsProp(template, (const xmlChar *)""name"", NULL); + if (prop != NULL) { + const xmlChar *URI; +- xsltTemplatePtr cur; + + /* + * TODO: Don't use xsltGetQNameURI(). +@@ -5405,19 +5404,6 @@ xsltParseStylesheetTemplate(xsltStylesheetPtr style, xmlNodePtr template) { + ret->nameURI = xmlDictLookup(style->dict, BAD_CAST URI, -1); + else + ret->nameURI = NULL; +- cur = ret->next; +- while (cur != NULL) { +- if ((URI != NULL && xmlStrEqual(cur->name, ret->name) && +- xmlStrEqual(cur->nameURI, URI) ) || +- (URI == NULL && cur->nameURI == NULL && +- xmlStrEqual(cur->name, ret->name))) { +- xsltTransformError(NULL, style, template, +- ""xsl:template: error duplicate name '%s'\n"", ret->name); +- style->errors++; +- goto error; +- } +- cur = cur->next; +- } + } + } + ",3295,3626,4096 +3341,"static int parse_options (char *options, struct super_block *sb, + unsigned int *inum, unsigned long *journal_devnum, + ext3_fsblk_t *n_blocks_count, int is_remount) +{ + struct ext3_sb_info *sbi = EXT3_SB(sb); + char * p; + substring_t args[MAX_OPT_ARGS]; + int data_opt = 0; + int option; + kuid_t uid; + kgid_t gid; +#ifdef CONFIG_QUOTA + int qfmt; +#endif + + if (!options) + return 1; + + while ((p = strsep (&options, "","")) != NULL) { + int token; + if (!*p) + continue; + /* + * Initialize args struct so we know whether arg was + * found; some options take optional arguments. + */ + args[0].to = args[0].from = NULL; + token = match_token(p, tokens, args); + switch (token) { + case Opt_bsd_df: + clear_opt (sbi->s_mount_opt, MINIX_DF); + break; + case Opt_minix_df: + set_opt (sbi->s_mount_opt, MINIX_DF); + break; + case Opt_grpid: + set_opt (sbi->s_mount_opt, GRPID); + break; + case Opt_nogrpid: + clear_opt (sbi->s_mount_opt, GRPID); + break; + case Opt_resuid: + if (match_int(&args[0], &option)) + return 0; + uid = make_kuid(current_user_ns(), option); + if (!uid_valid(uid)) { + ext3_msg(sb, KERN_ERR, ""Invalid uid value %d"", option); + return 0; + + } + sbi->s_resuid = uid; + break; + case Opt_resgid: + if (match_int(&args[0], &option)) + return 0; + gid = make_kgid(current_user_ns(), option); + if (!gid_valid(gid)) { + ext3_msg(sb, KERN_ERR, ""Invalid gid value %d"", option); + return 0; + } + sbi->s_resgid = gid; + break; + case Opt_sb: + /* handled by get_sb_block() instead of here */ + /* *sb_block = match_int(&args[0]); */ + break; + case Opt_err_panic: + clear_opt (sbi->s_mount_opt, ERRORS_CONT); + clear_opt (sbi->s_mount_opt, ERRORS_RO); + set_opt (sbi->s_mount_opt, ERRORS_PANIC); + break; + case Opt_err_ro: + clear_opt (sbi->s_mount_opt, ERRORS_CONT); + clear_opt (sbi->s_mount_opt, ERRORS_PANIC); + set_opt (sbi->s_mount_opt, ERRORS_RO); + break; + case Opt_err_cont: + clear_opt (sbi->s_mount_opt, ERRORS_RO); + clear_opt (sbi->s_mount_opt, ERRORS_PANIC); + set_opt (sbi->s_mount_opt, ERRORS_CONT); + break; + case Opt_nouid32: + set_opt (sbi->s_mount_opt, NO_UID32); + break; + case Opt_nocheck: + clear_opt (sbi->s_mount_opt, CHECK); + break; + case Opt_debug: + set_opt (sbi->s_mount_opt, DEBUG); + break; + case Opt_oldalloc: + ext3_msg(sb, KERN_WARNING, + ""Ignoring deprecated oldalloc option""); + break; + case Opt_orlov: + ext3_msg(sb, KERN_WARNING, + ""Ignoring deprecated orlov option""); + break; +#ifdef CONFIG_EXT3_FS_XATTR + case Opt_user_xattr: + set_opt (sbi->s_mount_opt, XATTR_USER); + break; + case Opt_nouser_xattr: + clear_opt (sbi->s_mount_opt, XATTR_USER); + break; +#else + case Opt_user_xattr: + case Opt_nouser_xattr: + ext3_msg(sb, KERN_INFO, + ""(no)user_xattr options not supported""); + break; +#endif +#ifdef CONFIG_EXT3_FS_POSIX_ACL + case Opt_acl: + set_opt(sbi->s_mount_opt, POSIX_ACL); + break; + case Opt_noacl: + clear_opt(sbi->s_mount_opt, POSIX_ACL); + break; +#else + case Opt_acl: + case Opt_noacl: + ext3_msg(sb, KERN_INFO, + ""(no)acl options not supported""); + break; +#endif + case Opt_reservation: + set_opt(sbi->s_mount_opt, RESERVATION); + break; + case Opt_noreservation: + clear_opt(sbi->s_mount_opt, RESERVATION); + break; + case Opt_journal_update: + /* @@@ FIXME */ + /* Eventually we will want to be able to create + a journal file here. For now, only allow the + user to specify an existing inode to be the + journal file. */ + if (is_remount) { + ext3_msg(sb, KERN_ERR, ""error: cannot specify "" + ""journal on remount""); + return 0; + } + set_opt (sbi->s_mount_opt, UPDATE_JOURNAL); + break; + case Opt_journal_inum: + if (is_remount) { + ext3_msg(sb, KERN_ERR, ""error: cannot specify "" + ""journal on remount""); + return 0; + } + if (match_int(&args[0], &option)) + return 0; + *inum = option; + break; + case Opt_journal_dev: + if (is_remount) { + ext3_msg(sb, KERN_ERR, ""error: cannot specify "" + ""journal on remount""); + return 0; + } + if (match_int(&args[0], &option)) + return 0; + *journal_devnum = option; + break; + case Opt_noload: + set_opt (sbi->s_mount_opt, NOLOAD); + break; + case Opt_commit: + if (match_int(&args[0], &option)) + return 0; + if (option < 0) + return 0; + if (option == 0) + option = JBD_DEFAULT_MAX_COMMIT_AGE; + sbi->s_commit_interval = HZ * option; + break; + case Opt_data_journal: + data_opt = EXT3_MOUNT_JOURNAL_DATA; + goto datacheck; + case Opt_data_ordered: + data_opt = EXT3_MOUNT_ORDERED_DATA; + goto datacheck; + case Opt_data_writeback: + data_opt = EXT3_MOUNT_WRITEBACK_DATA; + datacheck: + if (is_remount) { + if (test_opt(sb, DATA_FLAGS) == data_opt) + break; + ext3_msg(sb, KERN_ERR, + ""error: cannot change "" + ""data mode on remount. The filesystem "" + ""is mounted in data=%s mode and you "" + ""try to remount it in data=%s mode."", + data_mode_string(test_opt(sb, + DATA_FLAGS)), + data_mode_string(data_opt)); + return 0; + } else { + clear_opt(sbi->s_mount_opt, DATA_FLAGS); + sbi->s_mount_opt |= data_opt; + } + break; + case Opt_data_err_abort: + set_opt(sbi->s_mount_opt, DATA_ERR_ABORT); + break; + case Opt_data_err_ignore: + clear_opt(sbi->s_mount_opt, DATA_ERR_ABORT); + break; +#ifdef CONFIG_QUOTA + case Opt_usrjquota: + if (!set_qf_name(sb, USRQUOTA, &args[0])) + return 0; + break; + case Opt_grpjquota: + if (!set_qf_name(sb, GRPQUOTA, &args[0])) + return 0; + break; + case Opt_offusrjquota: + if (!clear_qf_name(sb, USRQUOTA)) + return 0; + break; + case Opt_offgrpjquota: + if (!clear_qf_name(sb, GRPQUOTA)) + return 0; + break; + case Opt_jqfmt_vfsold: + qfmt = QFMT_VFS_OLD; + goto set_qf_format; + case Opt_jqfmt_vfsv0: + qfmt = QFMT_VFS_V0; + goto set_qf_format; + case Opt_jqfmt_vfsv1: + qfmt = QFMT_VFS_V1; +set_qf_format: + if (sb_any_quota_loaded(sb) && + sbi->s_jquota_fmt != qfmt) { + ext3_msg(sb, KERN_ERR, ""error: cannot change "" + ""journaled quota options when "" + ""quota turned on.""); + return 0; + } + sbi->s_jquota_fmt = qfmt; + break; + case Opt_quota: + case Opt_usrquota: + set_opt(sbi->s_mount_opt, QUOTA); + set_opt(sbi->s_mount_opt, USRQUOTA); + break; + case Opt_grpquota: + set_opt(sbi->s_mount_opt, QUOTA); + set_opt(sbi->s_mount_opt, GRPQUOTA); + break; + case Opt_noquota: + if (sb_any_quota_loaded(sb)) { + ext3_msg(sb, KERN_ERR, ""error: cannot change "" + ""quota options when quota turned on.""); + return 0; + } + clear_opt(sbi->s_mount_opt, QUOTA); + clear_opt(sbi->s_mount_opt, USRQUOTA); + clear_opt(sbi->s_mount_opt, GRPQUOTA); + break; +#else + case Opt_quota: + case Opt_usrquota: + case Opt_grpquota: + ext3_msg(sb, KERN_ERR, + ""error: quota options not supported.""); + break; + case Opt_usrjquota: + case Opt_grpjquota: + case Opt_offusrjquota: + case Opt_offgrpjquota: + case Opt_jqfmt_vfsold: + case Opt_jqfmt_vfsv0: + case Opt_jqfmt_vfsv1: + ext3_msg(sb, KERN_ERR, + ""error: journaled quota options not "" + ""supported.""); + break; + case Opt_noquota: + break; +#endif + case Opt_abort: + set_opt(sbi->s_mount_opt, ABORT); + break; + case Opt_nobarrier: + clear_opt(sbi->s_mount_opt, BARRIER); + break; + case Opt_barrier: + if (args[0].from) { + if (match_int(&args[0], &option)) + return 0; + } else + option = 1; /* No argument, default to 1 */ + if (option) + set_opt(sbi->s_mount_opt, BARRIER); + else + clear_opt(sbi->s_mount_opt, BARRIER); + break; + case Opt_ignore: + break; + case Opt_resize: + if (!is_remount) { + ext3_msg(sb, KERN_ERR, + ""error: resize option only available "" + ""for remount""); + return 0; + } + if (match_int(&args[0], &option) != 0) + return 0; + *n_blocks_count = option; + break; + case Opt_nobh: + ext3_msg(sb, KERN_WARNING, + ""warning: ignoring deprecated nobh option""); + break; + case Opt_bh: + ext3_msg(sb, KERN_WARNING, + ""warning: ignoring deprecated bh option""); + break; + default: + ext3_msg(sb, KERN_ERR, + ""error: unrecognized mount option \""%s\"" "" + ""or missing value"", p); + return 0; + } + } +#ifdef CONFIG_QUOTA + if (sbi->s_qf_names[USRQUOTA] || sbi->s_qf_names[GRPQUOTA]) { + if (test_opt(sb, USRQUOTA) && sbi->s_qf_names[USRQUOTA]) + clear_opt(sbi->s_mount_opt, USRQUOTA); + if (test_opt(sb, GRPQUOTA) && sbi->s_qf_names[GRPQUOTA]) + clear_opt(sbi->s_mount_opt, GRPQUOTA); + + if (test_opt(sb, GRPQUOTA) || test_opt(sb, USRQUOTA)) { + ext3_msg(sb, KERN_ERR, ""error: old and new quota "" + ""format mixing.""); + return 0; + } + + if (!sbi->s_jquota_fmt) { + ext3_msg(sb, KERN_ERR, ""error: journaled quota format "" + ""not specified.""); + return 0; + } + } else { + if (sbi->s_jquota_fmt) { + ext3_msg(sb, KERN_ERR, ""error: journaled quota format "" + ""specified with no journaling "" + ""enabled.""); + return 0; + } + } +#endif + return 1; +} +",0,"static int parse_options (char *options, struct super_block *sb, + unsigned int *inum, unsigned long *journal_devnum, + ext3_fsblk_t *n_blocks_count, int is_remount) +{ + struct ext3_sb_info *sbi = EXT3_SB(sb); + char * p; + substring_t args[MAX_OPT_ARGS]; + int data_opt = 0; + int option; + kuid_t uid; + kgid_t gid; +#ifdef CONFIG_QUOTA + int qfmt; +#endif + + if (!options) + return 1; + + while ((p = strsep (&options, "","")) != NULL) { + int token; + if (!*p) + continue; + /* + * Initialize args struct so we know whether arg was + * found; some options take optional arguments. + */ + args[0].to = args[0].from = NULL; + token = match_token(p, tokens, args); + switch (token) { + case Opt_bsd_df: + clear_opt (sbi->s_mount_opt, MINIX_DF); + break; + case Opt_minix_df: + set_opt (sbi->s_mount_opt, MINIX_DF); + break; + case Opt_grpid: + set_opt (sbi->s_mount_opt, GRPID); + break; + case Opt_nogrpid: + clear_opt (sbi->s_mount_opt, GRPID); + break; + case Opt_resuid: + if (match_int(&args[0], &option)) + return 0; + uid = make_kuid(current_user_ns(), option); + if (!uid_valid(uid)) { + ext3_msg(sb, KERN_ERR, ""Invalid uid value %d"", option); + return 0; + + } + sbi->s_resuid = uid; + break; + case Opt_resgid: + if (match_int(&args[0], &option)) + return 0; + gid = make_kgid(current_user_ns(), option); + if (!gid_valid(gid)) { + ext3_msg(sb, KERN_ERR, ""Invalid gid value %d"", option); + return 0; + } + sbi->s_resgid = gid; + break; + case Opt_sb: + /* handled by get_sb_block() instead of here */ + /* *sb_block = match_int(&args[0]); */ + break; + case Opt_err_panic: + clear_opt (sbi->s_mount_opt, ERRORS_CONT); + clear_opt (sbi->s_mount_opt, ERRORS_RO); + set_opt (sbi->s_mount_opt, ERRORS_PANIC); + break; + case Opt_err_ro: + clear_opt (sbi->s_mount_opt, ERRORS_CONT); + clear_opt (sbi->s_mount_opt, ERRORS_PANIC); + set_opt (sbi->s_mount_opt, ERRORS_RO); + break; + case Opt_err_cont: + clear_opt (sbi->s_mount_opt, ERRORS_RO); + clear_opt (sbi->s_mount_opt, ERRORS_PANIC); + set_opt (sbi->s_mount_opt, ERRORS_CONT); + break; + case Opt_nouid32: + set_opt (sbi->s_mount_opt, NO_UID32); + break; + case Opt_nocheck: + clear_opt (sbi->s_mount_opt, CHECK); + break; + case Opt_debug: + set_opt (sbi->s_mount_opt, DEBUG); + break; + case Opt_oldalloc: + ext3_msg(sb, KERN_WARNING, + ""Ignoring deprecated oldalloc option""); + break; + case Opt_orlov: + ext3_msg(sb, KERN_WARNING, + ""Ignoring deprecated orlov option""); + break; +#ifdef CONFIG_EXT3_FS_XATTR + case Opt_user_xattr: + set_opt (sbi->s_mount_opt, XATTR_USER); + break; + case Opt_nouser_xattr: + clear_opt (sbi->s_mount_opt, XATTR_USER); + break; +#else + case Opt_user_xattr: + case Opt_nouser_xattr: + ext3_msg(sb, KERN_INFO, + ""(no)user_xattr options not supported""); + break; +#endif +#ifdef CONFIG_EXT3_FS_POSIX_ACL + case Opt_acl: + set_opt(sbi->s_mount_opt, POSIX_ACL); + break; + case Opt_noacl: + clear_opt(sbi->s_mount_opt, POSIX_ACL); + break; +#else + case Opt_acl: + case Opt_noacl: + ext3_msg(sb, KERN_INFO, + ""(no)acl options not supported""); + break; +#endif + case Opt_reservation: + set_opt(sbi->s_mount_opt, RESERVATION); + break; + case Opt_noreservation: + clear_opt(sbi->s_mount_opt, RESERVATION); + break; + case Opt_journal_update: + /* @@@ FIXME */ + /* Eventually we will want to be able to create + a journal file here. For now, only allow the + user to specify an existing inode to be the + journal file. */ + if (is_remount) { + ext3_msg(sb, KERN_ERR, ""error: cannot specify "" + ""journal on remount""); + return 0; + } + set_opt (sbi->s_mount_opt, UPDATE_JOURNAL); + break; + case Opt_journal_inum: + if (is_remount) { + ext3_msg(sb, KERN_ERR, ""error: cannot specify "" + ""journal on remount""); + return 0; + } + if (match_int(&args[0], &option)) + return 0; + *inum = option; + break; + case Opt_journal_dev: + if (is_remount) { + ext3_msg(sb, KERN_ERR, ""error: cannot specify "" + ""journal on remount""); + return 0; + } + if (match_int(&args[0], &option)) + return 0; + *journal_devnum = option; + break; + case Opt_noload: + set_opt (sbi->s_mount_opt, NOLOAD); + break; + case Opt_commit: + if (match_int(&args[0], &option)) + return 0; + if (option < 0) + return 0; + if (option == 0) + option = JBD_DEFAULT_MAX_COMMIT_AGE; + sbi->s_commit_interval = HZ * option; + break; + case Opt_data_journal: + data_opt = EXT3_MOUNT_JOURNAL_DATA; + goto datacheck; + case Opt_data_ordered: + data_opt = EXT3_MOUNT_ORDERED_DATA; + goto datacheck; + case Opt_data_writeback: + data_opt = EXT3_MOUNT_WRITEBACK_DATA; + datacheck: + if (is_remount) { + if (test_opt(sb, DATA_FLAGS) == data_opt) + break; + ext3_msg(sb, KERN_ERR, + ""error: cannot change "" + ""data mode on remount. The filesystem "" + ""is mounted in data=%s mode and you "" + ""try to remount it in data=%s mode."", + data_mode_string(test_opt(sb, + DATA_FLAGS)), + data_mode_string(data_opt)); + return 0; + } else { + clear_opt(sbi->s_mount_opt, DATA_FLAGS); + sbi->s_mount_opt |= data_opt; + } + break; + case Opt_data_err_abort: + set_opt(sbi->s_mount_opt, DATA_ERR_ABORT); + break; + case Opt_data_err_ignore: + clear_opt(sbi->s_mount_opt, DATA_ERR_ABORT); + break; +#ifdef CONFIG_QUOTA + case Opt_usrjquota: + if (!set_qf_name(sb, USRQUOTA, &args[0])) + return 0; + break; + case Opt_grpjquota: + if (!set_qf_name(sb, GRPQUOTA, &args[0])) + return 0; + break; + case Opt_offusrjquota: + if (!clear_qf_name(sb, USRQUOTA)) + return 0; + break; + case Opt_offgrpjquota: + if (!clear_qf_name(sb, GRPQUOTA)) + return 0; + break; + case Opt_jqfmt_vfsold: + qfmt = QFMT_VFS_OLD; + goto set_qf_format; + case Opt_jqfmt_vfsv0: + qfmt = QFMT_VFS_V0; + goto set_qf_format; + case Opt_jqfmt_vfsv1: + qfmt = QFMT_VFS_V1; +set_qf_format: + if (sb_any_quota_loaded(sb) && + sbi->s_jquota_fmt != qfmt) { + ext3_msg(sb, KERN_ERR, ""error: cannot change "" + ""journaled quota options when "" + ""quota turned on.""); + return 0; + } + sbi->s_jquota_fmt = qfmt; + break; + case Opt_quota: + case Opt_usrquota: + set_opt(sbi->s_mount_opt, QUOTA); + set_opt(sbi->s_mount_opt, USRQUOTA); + break; + case Opt_grpquota: + set_opt(sbi->s_mount_opt, QUOTA); + set_opt(sbi->s_mount_opt, GRPQUOTA); + break; + case Opt_noquota: + if (sb_any_quota_loaded(sb)) { + ext3_msg(sb, KERN_ERR, ""error: cannot change "" + ""quota options when quota turned on.""); + return 0; + } + clear_opt(sbi->s_mount_opt, QUOTA); + clear_opt(sbi->s_mount_opt, USRQUOTA); + clear_opt(sbi->s_mount_opt, GRPQUOTA); + break; +#else + case Opt_quota: + case Opt_usrquota: + case Opt_grpquota: + ext3_msg(sb, KERN_ERR, + ""error: quota options not supported.""); + break; + case Opt_usrjquota: + case Opt_grpjquota: + case Opt_offusrjquota: + case Opt_offgrpjquota: + case Opt_jqfmt_vfsold: + case Opt_jqfmt_vfsv0: + case Opt_jqfmt_vfsv1: + ext3_msg(sb, KERN_ERR, + ""error: journaled quota options not "" + ""supported.""); + break; + case Opt_noquota: + break; +#endif + case Opt_abort: + set_opt(sbi->s_mount_opt, ABORT); + break; + case Opt_nobarrier: + clear_opt(sbi->s_mount_opt, BARRIER); + break; + case Opt_barrier: + if (args[0].from) { + if (match_int(&args[0], &option)) + return 0; + } else + option = 1; /* No argument, default to 1 */ + if (option) + set_opt(sbi->s_mount_opt, BARRIER); + else + clear_opt(sbi->s_mount_opt, BARRIER); + break; + case Opt_ignore: + break; + case Opt_resize: + if (!is_remount) { + ext3_msg(sb, KERN_ERR, + ""error: resize option only available "" + ""for remount""); + return 0; + } + if (match_int(&args[0], &option) != 0) + return 0; + *n_blocks_count = option; + break; + case Opt_nobh: + ext3_msg(sb, KERN_WARNING, + ""warning: ignoring deprecated nobh option""); + break; + case Opt_bh: + ext3_msg(sb, KERN_WARNING, + ""warning: ignoring deprecated bh option""); + break; + default: + ext3_msg(sb, KERN_ERR, + ""error: unrecognized mount option \""%s\"" "" + ""or missing value"", p); + return 0; + } + } +#ifdef CONFIG_QUOTA + if (sbi->s_qf_names[USRQUOTA] || sbi->s_qf_names[GRPQUOTA]) { + if (test_opt(sb, USRQUOTA) && sbi->s_qf_names[USRQUOTA]) + clear_opt(sbi->s_mount_opt, USRQUOTA); + if (test_opt(sb, GRPQUOTA) && sbi->s_qf_names[GRPQUOTA]) + clear_opt(sbi->s_mount_opt, GRPQUOTA); + + if (test_opt(sb, GRPQUOTA) || test_opt(sb, USRQUOTA)) { + ext3_msg(sb, KERN_ERR, ""error: old and new quota "" + ""format mixing.""); + return 0; + } + + if (!sbi->s_jquota_fmt) { + ext3_msg(sb, KERN_ERR, ""error: journaled quota format "" + ""not specified.""); + return 0; + } + } else { + if (sbi->s_jquota_fmt) { + ext3_msg(sb, KERN_ERR, ""error: journaled quota format "" + ""specified with no journaling "" + ""enabled.""); + return 0; + } + } +#endif + return 1; +} +","@@ -353,7 +353,7 @@ static struct block_device *ext3_blkdev_get(dev_t dev, struct super_block *sb) + return bdev; + + fail: +- ext3_msg(sb, ""error: failed to open journal device %s: %ld"", ++ ext3_msg(sb, KERN_ERR, ""error: failed to open journal device %s: %ld"", + __bdevname(dev, b), PTR_ERR(bdev)); + + return NULL; +@@ -887,7 +887,7 @@ static ext3_fsblk_t get_sb_block(void **data, struct super_block *sb) + /*todo: use simple_strtoll with >32bit ext3 */ + sb_block = simple_strtoul(options, &options, 0); + if (*options && *options != ',') { +- ext3_msg(sb, ""error: invalid sb specification: %s"", ++ ext3_msg(sb, KERN_ERR, ""error: invalid sb specification: %s"", + (char *) *data); + return 1; + }",2878,3209,4096 +18329,"void CL_Init( void ) { + Com_Printf( ""----- Client Initialization -----\n"" ); + + Con_Init (); + + if(!com_fullyInitialized) + { + CL_ClearState(); + clc.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED + cl_oldGameSet = qfalse; + } + + cls.realtime = 0; + + CL_InitInput (); + + cl_noprint = Cvar_Get( ""cl_noprint"", ""0"", 0 ); +#ifdef UPDATE_SERVER_NAME + cl_motd = Cvar_Get (""cl_motd"", ""1"", 0); +#endif + + cl_timeout = Cvar_Get (""cl_timeout"", ""200"", 0); + + cl_timeNudge = Cvar_Get (""cl_timeNudge"", ""0"", CVAR_TEMP ); + cl_shownet = Cvar_Get (""cl_shownet"", ""0"", CVAR_TEMP ); + cl_showSend = Cvar_Get (""cl_showSend"", ""0"", CVAR_TEMP ); + cl_showTimeDelta = Cvar_Get (""cl_showTimeDelta"", ""0"", CVAR_TEMP ); + cl_freezeDemo = Cvar_Get (""cl_freezeDemo"", ""0"", CVAR_TEMP ); + rcon_client_password = Cvar_Get (""rconPassword"", """", CVAR_TEMP ); + cl_activeAction = Cvar_Get( ""activeAction"", """", CVAR_TEMP ); + + cl_timedemo = Cvar_Get (""timedemo"", ""0"", 0); + cl_timedemoLog = Cvar_Get (""cl_timedemoLog"", """", CVAR_ARCHIVE); + cl_autoRecordDemo = Cvar_Get (""cl_autoRecordDemo"", ""0"", CVAR_ARCHIVE); + cl_aviFrameRate = Cvar_Get (""cl_aviFrameRate"", ""25"", CVAR_ARCHIVE); + cl_aviMotionJpeg = Cvar_Get (""cl_aviMotionJpeg"", ""1"", CVAR_ARCHIVE); + cl_forceavidemo = Cvar_Get (""cl_forceavidemo"", ""0"", 0); + + rconAddress = Cvar_Get (""rconAddress"", """", 0); + + cl_yawspeed = Cvar_Get (""cl_yawspeed"", ""140"", CVAR_ARCHIVE); + cl_pitchspeed = Cvar_Get (""cl_pitchspeed"", ""140"", CVAR_ARCHIVE); + cl_anglespeedkey = Cvar_Get (""cl_anglespeedkey"", ""1.5"", 0); + + cl_maxpackets = Cvar_Get (""cl_maxpackets"", ""30"", CVAR_ARCHIVE ); + cl_packetdup = Cvar_Get (""cl_packetdup"", ""1"", CVAR_ARCHIVE ); + + cl_run = Cvar_Get (""cl_run"", ""1"", CVAR_ARCHIVE); + cl_sensitivity = Cvar_Get (""sensitivity"", ""5"", CVAR_ARCHIVE); + cl_mouseAccel = Cvar_Get (""cl_mouseAccel"", ""0"", CVAR_ARCHIVE); + cl_freelook = Cvar_Get( ""cl_freelook"", ""1"", CVAR_ARCHIVE ); + + cl_mouseAccelStyle = Cvar_Get( ""cl_mouseAccelStyle"", ""0"", CVAR_ARCHIVE ); + cl_mouseAccelOffset = Cvar_Get( ""cl_mouseAccelOffset"", ""5"", CVAR_ARCHIVE ); + Cvar_CheckRange(cl_mouseAccelOffset, 0.001f, 50000.0f, qfalse); + + cl_showMouseRate = Cvar_Get (""cl_showmouserate"", ""0"", 0); + + cl_allowDownload = Cvar_Get (""cl_allowDownload"", ""0"", CVAR_ARCHIVE); + #ifdef USE_CURL_DLOPEN + cl_cURLLib = Cvar_Get(""cl_cURLLib"", DEFAULT_CURL_LIB, CVAR_ARCHIVE); + #endif + + cl_conXOffset = Cvar_Get (""cl_conXOffset"", ""0"", 0); +#ifdef __APPLE__ + cl_inGameVideo = Cvar_Get (""r_inGameVideo"", ""0"", CVAR_ARCHIVE); +#else + cl_inGameVideo = Cvar_Get (""r_inGameVideo"", ""1"", CVAR_ARCHIVE); +#endif + + cl_serverStatusResendTime = Cvar_Get (""cl_serverStatusResendTime"", ""750"", 0); + + Cvar_Get (""cg_autoswitch"", ""1"", CVAR_ARCHIVE); + + m_pitch = Cvar_Get (""m_pitch"", ""0.022"", CVAR_ARCHIVE); + m_yaw = Cvar_Get (""m_yaw"", ""0.022"", CVAR_ARCHIVE); + m_forward = Cvar_Get (""m_forward"", ""0.25"", CVAR_ARCHIVE); + m_side = Cvar_Get (""m_side"", ""0.25"", CVAR_ARCHIVE); +#ifdef __APPLE__ + m_filter = Cvar_Get (""m_filter"", ""1"", CVAR_ARCHIVE); +#else + m_filter = Cvar_Get (""m_filter"", ""0"", CVAR_ARCHIVE); +#endif + + j_pitch = Cvar_Get (""j_pitch"", ""0.022"", CVAR_ARCHIVE); + j_yaw = Cvar_Get (""j_yaw"", ""-0.022"", CVAR_ARCHIVE); + j_forward = Cvar_Get (""j_forward"", ""-0.25"", CVAR_ARCHIVE); + j_side = Cvar_Get (""j_side"", ""0.25"", CVAR_ARCHIVE); + j_up = Cvar_Get (""j_up"", ""0"", CVAR_ARCHIVE); + + j_pitch_axis = Cvar_Get (""j_pitch_axis"", ""3"", CVAR_ARCHIVE); + j_yaw_axis = Cvar_Get (""j_yaw_axis"", ""2"", CVAR_ARCHIVE); + j_forward_axis = Cvar_Get (""j_forward_axis"", ""1"", CVAR_ARCHIVE); + j_side_axis = Cvar_Get (""j_side_axis"", ""0"", CVAR_ARCHIVE); + j_up_axis = Cvar_Get (""j_up_axis"", ""4"", CVAR_ARCHIVE); + + Cvar_CheckRange(j_pitch_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); + Cvar_CheckRange(j_yaw_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); + Cvar_CheckRange(j_forward_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); + Cvar_CheckRange(j_side_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); + Cvar_CheckRange(j_up_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); + + cl_motdString = Cvar_Get( ""cl_motdString"", """", CVAR_ROM ); + + Cvar_Get( ""cl_maxPing"", ""800"", CVAR_ARCHIVE ); + + cl_lanForcePackets = Cvar_Get (""cl_lanForcePackets"", ""1"", CVAR_ARCHIVE); + + cl_guidServerUniq = Cvar_Get (""cl_guidServerUniq"", ""1"", CVAR_ARCHIVE); + + cl_consoleKeys = Cvar_Get( ""cl_consoleKeys"", ""~ ` 0x7e 0x60"", CVAR_ARCHIVE); + + Cvar_Get (""name"", ""UnnamedPlayer"", CVAR_USERINFO | CVAR_ARCHIVE ); + cl_rate = Cvar_Get (""rate"", ""25000"", CVAR_USERINFO | CVAR_ARCHIVE ); + Cvar_Get (""snaps"", ""20"", CVAR_USERINFO | CVAR_ARCHIVE ); + Cvar_Get (""model"", ""sarge"", CVAR_USERINFO | CVAR_ARCHIVE ); + Cvar_Get (""headmodel"", ""sarge"", CVAR_USERINFO | CVAR_ARCHIVE ); + Cvar_Get (""team_model"", ""james"", CVAR_USERINFO | CVAR_ARCHIVE ); + Cvar_Get (""team_headmodel"", ""*james"", CVAR_USERINFO | CVAR_ARCHIVE ); + Cvar_Get (""g_redTeam"", ""Stroggs"", CVAR_SERVERINFO | CVAR_ARCHIVE); + Cvar_Get (""g_blueTeam"", ""Pagans"", CVAR_SERVERINFO | CVAR_ARCHIVE); + Cvar_Get (""color1"", ""4"", CVAR_USERINFO | CVAR_ARCHIVE ); + Cvar_Get (""color2"", ""5"", CVAR_USERINFO | CVAR_ARCHIVE ); + Cvar_Get (""handicap"", ""100"", CVAR_USERINFO | CVAR_ARCHIVE ); + Cvar_Get (""teamtask"", ""0"", CVAR_USERINFO ); + Cvar_Get (""sex"", ""male"", CVAR_USERINFO | CVAR_ARCHIVE ); + Cvar_Get (""cl_anonymous"", ""0"", CVAR_USERINFO | CVAR_ARCHIVE ); + + Cvar_Get (""password"", """", CVAR_USERINFO); + Cvar_Get (""cg_predictItems"", ""1"", CVAR_USERINFO | CVAR_ARCHIVE ); + +#ifdef USE_MUMBLE + cl_useMumble = Cvar_Get (""cl_useMumble"", ""0"", CVAR_ARCHIVE | CVAR_LATCH); + cl_mumbleScale = Cvar_Get (""cl_mumbleScale"", ""0.0254"", CVAR_ARCHIVE); +#endif + +#ifdef USE_VOIP + cl_voipSend = Cvar_Get (""cl_voipSend"", ""0"", 0); + cl_voipSendTarget = Cvar_Get (""cl_voipSendTarget"", ""spatial"", 0); + cl_voipGainDuringCapture = Cvar_Get (""cl_voipGainDuringCapture"", ""0.2"", CVAR_ARCHIVE); + cl_voipCaptureMult = Cvar_Get (""cl_voipCaptureMult"", ""2.0"", CVAR_ARCHIVE); + cl_voipUseVAD = Cvar_Get (""cl_voipUseVAD"", ""0"", CVAR_ARCHIVE); + cl_voipVADThreshold = Cvar_Get (""cl_voipVADThreshold"", ""0.25"", CVAR_ARCHIVE); + cl_voipShowMeter = Cvar_Get (""cl_voipShowMeter"", ""1"", CVAR_ARCHIVE); + + cl_voip = Cvar_Get (""cl_voip"", ""1"", CVAR_ARCHIVE); + Cvar_CheckRange( cl_voip, 0, 1, qtrue ); + cl_voipProtocol = Cvar_Get (""cl_voipProtocol"", cl_voip->integer ? ""opus"" : """", CVAR_USERINFO | CVAR_ROM); +#endif + + + Cvar_Get (""cg_viewsize"", ""100"", CVAR_ARCHIVE ); + Cvar_Get (""cg_stereoSeparation"", ""0"", CVAR_ROM); + + Cmd_AddCommand (""cmd"", CL_ForwardToServer_f); + Cmd_AddCommand (""configstrings"", CL_Configstrings_f); + Cmd_AddCommand (""clientinfo"", CL_Clientinfo_f); + Cmd_AddCommand (""snd_restart"", CL_Snd_Restart_f); + Cmd_AddCommand (""vid_restart"", CL_Vid_Restart_f); + Cmd_AddCommand (""disconnect"", CL_Disconnect_f); + Cmd_AddCommand (""record"", CL_Record_f); + Cmd_AddCommand (""demo"", CL_PlayDemo_f); + Cmd_SetCommandCompletionFunc( ""demo"", CL_CompleteDemoName ); + Cmd_AddCommand (""cinematic"", CL_PlayCinematic_f); + Cmd_AddCommand (""stoprecord"", CL_StopRecord_f); + Cmd_AddCommand (""connect"", CL_Connect_f); + Cmd_AddCommand (""reconnect"", CL_Reconnect_f); + Cmd_AddCommand (""localservers"", CL_LocalServers_f); + Cmd_AddCommand (""globalservers"", CL_GlobalServers_f); + Cmd_AddCommand (""rcon"", CL_Rcon_f); + Cmd_SetCommandCompletionFunc( ""rcon"", CL_CompleteRcon ); + Cmd_AddCommand (""ping"", CL_Ping_f ); + Cmd_AddCommand (""serverstatus"", CL_ServerStatus_f ); + Cmd_AddCommand (""showip"", CL_ShowIP_f ); + Cmd_AddCommand (""fs_openedList"", CL_OpenedPK3List_f ); + Cmd_AddCommand (""fs_referencedList"", CL_ReferencedPK3List_f ); + Cmd_AddCommand (""model"", CL_SetModel_f ); + Cmd_AddCommand (""video"", CL_Video_f ); + Cmd_AddCommand (""stopvideo"", CL_StopVideo_f ); + if( !com_dedicated->integer ) { + Cmd_AddCommand (""sayto"", CL_Sayto_f ); + Cmd_SetCommandCompletionFunc( ""sayto"", CL_CompletePlayerName ); + } + CL_InitRef(); + + SCR_Init (); + + + Cvar_Set( ""cl_running"", ""1"" ); + + CL_GenerateQKey(); + Cvar_Get( ""cl_guid"", """", CVAR_USERINFO | CVAR_ROM ); + CL_UpdateGUID( NULL, 0 ); + + Com_Printf( ""----- Client Initialization Complete -----\n"" ); +} +",1,"void CL_Init( void ) { + Com_Printf( ""----- Client Initialization -----\n"" ); + + Con_Init (); + + if(!com_fullyInitialized) + { + CL_ClearState(); + clc.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED + cl_oldGameSet = qfalse; + } + + cls.realtime = 0; + + CL_InitInput (); + + cl_noprint = Cvar_Get( ""cl_noprint"", ""0"", 0 ); +#ifdef UPDATE_SERVER_NAME + cl_motd = Cvar_Get (""cl_motd"", ""1"", 0); +#endif + + cl_timeout = Cvar_Get (""cl_timeout"", ""200"", 0); + + cl_timeNudge = Cvar_Get (""cl_timeNudge"", ""0"", CVAR_TEMP ); + cl_shownet = Cvar_Get (""cl_shownet"", ""0"", CVAR_TEMP ); + cl_showSend = Cvar_Get (""cl_showSend"", ""0"", CVAR_TEMP ); + cl_showTimeDelta = Cvar_Get (""cl_showTimeDelta"", ""0"", CVAR_TEMP ); + cl_freezeDemo = Cvar_Get (""cl_freezeDemo"", ""0"", CVAR_TEMP ); + rcon_client_password = Cvar_Get (""rconPassword"", """", CVAR_TEMP ); + cl_activeAction = Cvar_Get( ""activeAction"", """", CVAR_TEMP ); + + cl_timedemo = Cvar_Get (""timedemo"", ""0"", 0); + cl_timedemoLog = Cvar_Get (""cl_timedemoLog"", """", CVAR_ARCHIVE); + cl_autoRecordDemo = Cvar_Get (""cl_autoRecordDemo"", ""0"", CVAR_ARCHIVE); + cl_aviFrameRate = Cvar_Get (""cl_aviFrameRate"", ""25"", CVAR_ARCHIVE); + cl_aviMotionJpeg = Cvar_Get (""cl_aviMotionJpeg"", ""1"", CVAR_ARCHIVE); + cl_forceavidemo = Cvar_Get (""cl_forceavidemo"", ""0"", 0); + + rconAddress = Cvar_Get (""rconAddress"", """", 0); + + cl_yawspeed = Cvar_Get (""cl_yawspeed"", ""140"", CVAR_ARCHIVE); + cl_pitchspeed = Cvar_Get (""cl_pitchspeed"", ""140"", CVAR_ARCHIVE); + cl_anglespeedkey = Cvar_Get (""cl_anglespeedkey"", ""1.5"", 0); + + cl_maxpackets = Cvar_Get (""cl_maxpackets"", ""30"", CVAR_ARCHIVE ); + cl_packetdup = Cvar_Get (""cl_packetdup"", ""1"", CVAR_ARCHIVE ); + + cl_run = Cvar_Get (""cl_run"", ""1"", CVAR_ARCHIVE); + cl_sensitivity = Cvar_Get (""sensitivity"", ""5"", CVAR_ARCHIVE); + cl_mouseAccel = Cvar_Get (""cl_mouseAccel"", ""0"", CVAR_ARCHIVE); + cl_freelook = Cvar_Get( ""cl_freelook"", ""1"", CVAR_ARCHIVE ); + + cl_mouseAccelStyle = Cvar_Get( ""cl_mouseAccelStyle"", ""0"", CVAR_ARCHIVE ); + cl_mouseAccelOffset = Cvar_Get( ""cl_mouseAccelOffset"", ""5"", CVAR_ARCHIVE ); + Cvar_CheckRange(cl_mouseAccelOffset, 0.001f, 50000.0f, qfalse); + + cl_showMouseRate = Cvar_Get (""cl_showmouserate"", ""0"", 0); + + cl_allowDownload = Cvar_Get (""cl_allowDownload"", ""0"", CVAR_ARCHIVE); + #ifdef USE_CURL_DLOPEN + cl_cURLLib = Cvar_Get(""cl_cURLLib"", DEFAULT_CURL_LIB, CVAR_ARCHIVE | CVAR_PROTECTED); + #endif + + cl_conXOffset = Cvar_Get (""cl_conXOffset"", ""0"", 0); +#ifdef __APPLE__ + cl_inGameVideo = Cvar_Get (""r_inGameVideo"", ""0"", CVAR_ARCHIVE); +#else + cl_inGameVideo = Cvar_Get (""r_inGameVideo"", ""1"", CVAR_ARCHIVE); +#endif + + cl_serverStatusResendTime = Cvar_Get (""cl_serverStatusResendTime"", ""750"", 0); + + Cvar_Get (""cg_autoswitch"", ""1"", CVAR_ARCHIVE); + + m_pitch = Cvar_Get (""m_pitch"", ""0.022"", CVAR_ARCHIVE); + m_yaw = Cvar_Get (""m_yaw"", ""0.022"", CVAR_ARCHIVE); + m_forward = Cvar_Get (""m_forward"", ""0.25"", CVAR_ARCHIVE); + m_side = Cvar_Get (""m_side"", ""0.25"", CVAR_ARCHIVE); +#ifdef __APPLE__ + m_filter = Cvar_Get (""m_filter"", ""1"", CVAR_ARCHIVE); +#else + m_filter = Cvar_Get (""m_filter"", ""0"", CVAR_ARCHIVE); +#endif + + j_pitch = Cvar_Get (""j_pitch"", ""0.022"", CVAR_ARCHIVE); + j_yaw = Cvar_Get (""j_yaw"", ""-0.022"", CVAR_ARCHIVE); + j_forward = Cvar_Get (""j_forward"", ""-0.25"", CVAR_ARCHIVE); + j_side = Cvar_Get (""j_side"", ""0.25"", CVAR_ARCHIVE); + j_up = Cvar_Get (""j_up"", ""0"", CVAR_ARCHIVE); + + j_pitch_axis = Cvar_Get (""j_pitch_axis"", ""3"", CVAR_ARCHIVE); + j_yaw_axis = Cvar_Get (""j_yaw_axis"", ""2"", CVAR_ARCHIVE); + j_forward_axis = Cvar_Get (""j_forward_axis"", ""1"", CVAR_ARCHIVE); + j_side_axis = Cvar_Get (""j_side_axis"", ""0"", CVAR_ARCHIVE); + j_up_axis = Cvar_Get (""j_up_axis"", ""4"", CVAR_ARCHIVE); + + Cvar_CheckRange(j_pitch_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); + Cvar_CheckRange(j_yaw_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); + Cvar_CheckRange(j_forward_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); + Cvar_CheckRange(j_side_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); + Cvar_CheckRange(j_up_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); + + cl_motdString = Cvar_Get( ""cl_motdString"", """", CVAR_ROM ); + + Cvar_Get( ""cl_maxPing"", ""800"", CVAR_ARCHIVE ); + + cl_lanForcePackets = Cvar_Get (""cl_lanForcePackets"", ""1"", CVAR_ARCHIVE); + + cl_guidServerUniq = Cvar_Get (""cl_guidServerUniq"", ""1"", CVAR_ARCHIVE); + + cl_consoleKeys = Cvar_Get( ""cl_consoleKeys"", ""~ ` 0x7e 0x60"", CVAR_ARCHIVE); + + Cvar_Get (""name"", ""UnnamedPlayer"", CVAR_USERINFO | CVAR_ARCHIVE ); + cl_rate = Cvar_Get (""rate"", ""25000"", CVAR_USERINFO | CVAR_ARCHIVE ); + Cvar_Get (""snaps"", ""20"", CVAR_USERINFO | CVAR_ARCHIVE ); + Cvar_Get (""model"", ""sarge"", CVAR_USERINFO | CVAR_ARCHIVE ); + Cvar_Get (""headmodel"", ""sarge"", CVAR_USERINFO | CVAR_ARCHIVE ); + Cvar_Get (""team_model"", ""james"", CVAR_USERINFO | CVAR_ARCHIVE ); + Cvar_Get (""team_headmodel"", ""*james"", CVAR_USERINFO | CVAR_ARCHIVE ); + Cvar_Get (""g_redTeam"", ""Stroggs"", CVAR_SERVERINFO | CVAR_ARCHIVE); + Cvar_Get (""g_blueTeam"", ""Pagans"", CVAR_SERVERINFO | CVAR_ARCHIVE); + Cvar_Get (""color1"", ""4"", CVAR_USERINFO | CVAR_ARCHIVE ); + Cvar_Get (""color2"", ""5"", CVAR_USERINFO | CVAR_ARCHIVE ); + Cvar_Get (""handicap"", ""100"", CVAR_USERINFO | CVAR_ARCHIVE ); + Cvar_Get (""teamtask"", ""0"", CVAR_USERINFO ); + Cvar_Get (""sex"", ""male"", CVAR_USERINFO | CVAR_ARCHIVE ); + Cvar_Get (""cl_anonymous"", ""0"", CVAR_USERINFO | CVAR_ARCHIVE ); + + Cvar_Get (""password"", """", CVAR_USERINFO); + Cvar_Get (""cg_predictItems"", ""1"", CVAR_USERINFO | CVAR_ARCHIVE ); + +#ifdef USE_MUMBLE + cl_useMumble = Cvar_Get (""cl_useMumble"", ""0"", CVAR_ARCHIVE | CVAR_LATCH); + cl_mumbleScale = Cvar_Get (""cl_mumbleScale"", ""0.0254"", CVAR_ARCHIVE); +#endif + +#ifdef USE_VOIP + cl_voipSend = Cvar_Get (""cl_voipSend"", ""0"", 0); + cl_voipSendTarget = Cvar_Get (""cl_voipSendTarget"", ""spatial"", 0); + cl_voipGainDuringCapture = Cvar_Get (""cl_voipGainDuringCapture"", ""0.2"", CVAR_ARCHIVE); + cl_voipCaptureMult = Cvar_Get (""cl_voipCaptureMult"", ""2.0"", CVAR_ARCHIVE); + cl_voipUseVAD = Cvar_Get (""cl_voipUseVAD"", ""0"", CVAR_ARCHIVE); + cl_voipVADThreshold = Cvar_Get (""cl_voipVADThreshold"", ""0.25"", CVAR_ARCHIVE); + cl_voipShowMeter = Cvar_Get (""cl_voipShowMeter"", ""1"", CVAR_ARCHIVE); + + cl_voip = Cvar_Get (""cl_voip"", ""1"", CVAR_ARCHIVE); + Cvar_CheckRange( cl_voip, 0, 1, qtrue ); + cl_voipProtocol = Cvar_Get (""cl_voipProtocol"", cl_voip->integer ? ""opus"" : """", CVAR_USERINFO | CVAR_ROM); +#endif + + + Cvar_Get (""cg_viewsize"", ""100"", CVAR_ARCHIVE ); + Cvar_Get (""cg_stereoSeparation"", ""0"", CVAR_ROM); + + Cmd_AddCommand (""cmd"", CL_ForwardToServer_f); + Cmd_AddCommand (""configstrings"", CL_Configstrings_f); + Cmd_AddCommand (""clientinfo"", CL_Clientinfo_f); + Cmd_AddCommand (""snd_restart"", CL_Snd_Restart_f); + Cmd_AddCommand (""vid_restart"", CL_Vid_Restart_f); + Cmd_AddCommand (""disconnect"", CL_Disconnect_f); + Cmd_AddCommand (""record"", CL_Record_f); + Cmd_AddCommand (""demo"", CL_PlayDemo_f); + Cmd_SetCommandCompletionFunc( ""demo"", CL_CompleteDemoName ); + Cmd_AddCommand (""cinematic"", CL_PlayCinematic_f); + Cmd_AddCommand (""stoprecord"", CL_StopRecord_f); + Cmd_AddCommand (""connect"", CL_Connect_f); + Cmd_AddCommand (""reconnect"", CL_Reconnect_f); + Cmd_AddCommand (""localservers"", CL_LocalServers_f); + Cmd_AddCommand (""globalservers"", CL_GlobalServers_f); + Cmd_AddCommand (""rcon"", CL_Rcon_f); + Cmd_SetCommandCompletionFunc( ""rcon"", CL_CompleteRcon ); + Cmd_AddCommand (""ping"", CL_Ping_f ); + Cmd_AddCommand (""serverstatus"", CL_ServerStatus_f ); + Cmd_AddCommand (""showip"", CL_ShowIP_f ); + Cmd_AddCommand (""fs_openedList"", CL_OpenedPK3List_f ); + Cmd_AddCommand (""fs_referencedList"", CL_ReferencedPK3List_f ); + Cmd_AddCommand (""model"", CL_SetModel_f ); + Cmd_AddCommand (""video"", CL_Video_f ); + Cmd_AddCommand (""stopvideo"", CL_StopVideo_f ); + if( !com_dedicated->integer ) { + Cmd_AddCommand (""sayto"", CL_Sayto_f ); + Cmd_SetCommandCompletionFunc( ""sayto"", CL_CompletePlayerName ); + } + CL_InitRef(); + + SCR_Init (); + + + Cvar_Set( ""cl_running"", ""1"" ); + + CL_GenerateQKey(); + Cvar_Get( ""cl_guid"", """", CVAR_USERINFO | CVAR_ROM ); + CL_UpdateGUID( NULL, 0 ); + + Com_Printf( ""----- Client Initialization Complete -----\n"" ); +} +","@@ -3200,7 +3200,7 @@ void CL_InitRef( void ) { + Com_Printf( ""----- Initializing Renderer ----\n"" ); + + #ifdef USE_RENDERER_DLOPEN +- cl_renderer = Cvar_Get(""cl_renderer"", ""opengl2"", CVAR_ARCHIVE | CVAR_LATCH); ++ cl_renderer = Cvar_Get(""cl_renderer"", ""opengl2"", CVAR_ARCHIVE | CVAR_LATCH | CVAR_PROTECTED); + + Com_sprintf(dllName, sizeof(dllName), ""renderer_%s_"" ARCH_STRING DLL_EXT, cl_renderer->string); + +@@ -3551,7 +3551,7 @@ void CL_Init( void ) { + + cl_allowDownload = Cvar_Get (""cl_allowDownload"", ""0"", CVAR_ARCHIVE); + #ifdef USE_CURL_DLOPEN +- cl_cURLLib = Cvar_Get(""cl_cURLLib"", DEFAULT_CURL_LIB, CVAR_ARCHIVE); ++ cl_cURLLib = Cvar_Get(""cl_cURLLib"", DEFAULT_CURL_LIB, CVAR_ARCHIVE | CVAR_PROTECTED); + #endif + + cl_conXOffset = Cvar_Get (""cl_conXOffset"", ""0"", 0);",2595,2926,4096 +18090,"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; +} +",1,"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; + bool do_vnet = 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); + do_vnet = true; + } + 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; + do_vnet = false; + } + } + } 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; + do_vnet = false; + } + } + 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 (do_vnet) { + 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; +} +","@@ -2191,6 +2191,7 @@ static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev, + struct timespec ts; + __u32 ts_status; + bool is_drop_n_account = false; ++ bool do_vnet = 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 +@@ -2241,8 +2242,10 @@ static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev, + netoff = TPACKET_ALIGN(po->tp_hdrlen + + (maclen < 16 ? 16 : maclen)) + + po->tp_reserve; +- if (po->has_vnet_hdr) ++ if (po->has_vnet_hdr) { + netoff += sizeof(struct virtio_net_hdr); ++ do_vnet = true; ++ } + macoff = netoff - maclen; + } + if (po->tp_version <= TPACKET_V2) { +@@ -2259,8 +2262,10 @@ static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev, + skb_set_owner_r(copy_skb, sk); + } + snaplen = po->rx_ring.frame_size - macoff; +- if ((int)snaplen < 0) ++ if ((int)snaplen < 0) { + snaplen = 0; ++ do_vnet = false; ++ } + } + } else if (unlikely(macoff + snaplen > + GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len)) { +@@ -2273,6 +2278,7 @@ static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev, + if (unlikely((int)snaplen < 0)) { + snaplen = 0; + macoff = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len; ++ do_vnet = false; + } + } + spin_lock(&sk->sk_receive_queue.lock); +@@ -2298,7 +2304,7 @@ static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev, + } + spin_unlock(&sk->sk_receive_queue.lock); + +- if (po->has_vnet_hdr) { ++ if (do_vnet) { + if (virtio_net_hdr_from_skb(skb, h.raw + macoff - + sizeof(struct virtio_net_hdr), + vio_le(), true)) {",2093,2424,4096 +4001,"static int __init do_floppy_init(void) +{ + int i, unit, drive, err; + + set_debugt(); + interruptjiffies = resultjiffies = jiffies; + +#if defined(CONFIG_PPC) + if (check_legacy_ioport(FDC1)) + return -ENODEV; +#endif + + raw_cmd = NULL; + + floppy_wq = alloc_ordered_workqueue(""floppy"", 0); + if (!floppy_wq) + return -ENOMEM; + + for (drive = 0; drive < N_DRIVE; drive++) { + disks[drive] = alloc_disk(1); + if (!disks[drive]) { + err = -ENOMEM; + goto out_put_disk; + } + + disks[drive]->queue = blk_init_queue(do_fd_request, &floppy_lock); + if (!disks[drive]->queue) { + err = -ENOMEM; + goto out_put_disk; + } + + blk_queue_max_hw_sectors(disks[drive]->queue, 64); + disks[drive]->major = FLOPPY_MAJOR; + disks[drive]->first_minor = TOMINOR(drive); + disks[drive]->fops = &floppy_fops; + sprintf(disks[drive]->disk_name, ""fd%d"", drive); + + init_timer(&motor_off_timer[drive]); + motor_off_timer[drive].data = drive; + motor_off_timer[drive].function = motor_off_callback; + } + + err = register_blkdev(FLOPPY_MAJOR, ""fd""); + if (err) + goto out_put_disk; + + err = platform_driver_register(&floppy_driver); + if (err) + goto out_unreg_blkdev; + + blk_register_region(MKDEV(FLOPPY_MAJOR, 0), 256, THIS_MODULE, + floppy_find, NULL, NULL); + + for (i = 0; i < 256; i++) + if (ITYPE(i)) + floppy_sizes[i] = floppy_type[ITYPE(i)].size; + else + floppy_sizes[i] = MAX_DISK_SIZE << 1; + + reschedule_timeout(MAXTIMEOUT, ""floppy init""); + config_types(); + + for (i = 0; i < N_FDC; i++) { + fdc = i; + memset(FDCS, 0, sizeof(*FDCS)); + FDCS->dtr = -1; + FDCS->dor = 0x4; +#if defined(__sparc__) || defined(__mc68000__) + /*sparcs/sun3x don't have a DOR reset which we can fall back on to */ +#ifdef __mc68000__ + if (MACH_IS_SUN3X) +#endif + FDCS->version = FDC_82072A; +#endif + } + + use_virtual_dma = can_use_virtual_dma & 1; + fdc_state[0].address = FDC1; + if (fdc_state[0].address == -1) { + cancel_delayed_work(&fd_timeout); + err = -ENODEV; + goto out_unreg_region; + } +#if N_FDC > 1 + fdc_state[1].address = FDC2; +#endif + + fdc = 0; /* reset fdc in case of unexpected interrupt */ + err = floppy_grab_irq_and_dma(); + if (err) { + cancel_delayed_work(&fd_timeout); + err = -EBUSY; + goto out_unreg_region; + } + + /* initialise drive state */ + for (drive = 0; drive < N_DRIVE; drive++) { + memset(UDRS, 0, sizeof(*UDRS)); + memset(UDRWE, 0, sizeof(*UDRWE)); + set_bit(FD_DISK_NEWCHANGE_BIT, &UDRS->flags); + set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags); + set_bit(FD_VERIFY_BIT, &UDRS->flags); + UDRS->fd_device = -1; + floppy_track_buffer = NULL; + max_buffer_sectors = 0; + } + /* + * Small 10 msec delay to let through any interrupt that + * initialization might have triggered, to not + * confuse detection: + */ + msleep(10); + + for (i = 0; i < N_FDC; i++) { + fdc = i; + FDCS->driver_version = FD_DRIVER_VERSION; + for (unit = 0; unit < 4; unit++) + FDCS->track[unit] = 0; + if (FDCS->address == -1) + continue; + FDCS->rawcmd = 2; + if (user_reset_fdc(-1, FD_RESET_ALWAYS, false)) { + /* free ioports reserved by floppy_grab_irq_and_dma() */ + floppy_release_regions(fdc); + FDCS->address = -1; + FDCS->version = FDC_NONE; + continue; + } + /* Try to determine the floppy controller type */ + FDCS->version = get_fdc_version(); + if (FDCS->version == FDC_NONE) { + /* free ioports reserved by floppy_grab_irq_and_dma() */ + floppy_release_regions(fdc); + FDCS->address = -1; + continue; + } + if (can_use_virtual_dma == 2 && FDCS->version < FDC_82072A) + can_use_virtual_dma = 0; + + have_no_fdc = 0; + /* Not all FDCs seem to be able to handle the version command + * properly, so force a reset for the standard FDC clones, + * to avoid interrupt garbage. + */ + user_reset_fdc(-1, FD_RESET_ALWAYS, false); + } + fdc = 0; + cancel_delayed_work(&fd_timeout); + current_drive = 0; + initialized = true; + if (have_no_fdc) { + DPRINT(""no floppy controllers found\n""); + err = have_no_fdc; + goto out_release_dma; + } + + for (drive = 0; drive < N_DRIVE; drive++) { + if (!floppy_available(drive)) + continue; + + floppy_device[drive].name = floppy_device_name; + floppy_device[drive].id = drive; + floppy_device[drive].dev.release = floppy_device_release; + + err = platform_device_register(&floppy_device[drive]); + if (err) + goto out_remove_drives; + + err = device_create_file(&floppy_device[drive].dev, + &dev_attr_cmos); + if (err) + goto out_unreg_platform_dev; + + /* to be cleaned up... */ + disks[drive]->private_data = (void *)(long)drive; + disks[drive]->flags |= GENHD_FL_REMOVABLE; + disks[drive]->driverfs_dev = &floppy_device[drive].dev; + add_disk(disks[drive]); + } + + return 0; + +out_unreg_platform_dev: + platform_device_unregister(&floppy_device[drive]); +out_remove_drives: + while (drive--) { + if (floppy_available(drive)) { + del_gendisk(disks[drive]); + device_remove_file(&floppy_device[drive].dev, &dev_attr_cmos); + platform_device_unregister(&floppy_device[drive]); + } + } +out_release_dma: + if (atomic_read(&usage_count)) + floppy_release_irq_and_dma(); +out_unreg_region: + blk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256); + platform_driver_unregister(&floppy_driver); +out_unreg_blkdev: + unregister_blkdev(FLOPPY_MAJOR, ""fd""); +out_put_disk: + destroy_workqueue(floppy_wq); + for (drive = 0; drive < N_DRIVE; drive++) { + if (!disks[drive]) + break; + if (disks[drive]->queue) { + del_timer_sync(&motor_off_timer[drive]); + blk_cleanup_queue(disks[drive]->queue); + disks[drive]->queue = NULL; + } + put_disk(disks[drive]); + } + return err; +} +",0,"static int __init do_floppy_init(void) +{ + int i, unit, drive, err; + + set_debugt(); + interruptjiffies = resultjiffies = jiffies; + +#if defined(CONFIG_PPC) + if (check_legacy_ioport(FDC1)) + return -ENODEV; +#endif + + raw_cmd = NULL; + + floppy_wq = alloc_ordered_workqueue(""floppy"", 0); + if (!floppy_wq) + return -ENOMEM; + + for (drive = 0; drive < N_DRIVE; drive++) { + disks[drive] = alloc_disk(1); + if (!disks[drive]) { + err = -ENOMEM; + goto out_put_disk; + } + + disks[drive]->queue = blk_init_queue(do_fd_request, &floppy_lock); + if (!disks[drive]->queue) { + err = -ENOMEM; + goto out_put_disk; + } + + blk_queue_max_hw_sectors(disks[drive]->queue, 64); + disks[drive]->major = FLOPPY_MAJOR; + disks[drive]->first_minor = TOMINOR(drive); + disks[drive]->fops = &floppy_fops; + sprintf(disks[drive]->disk_name, ""fd%d"", drive); + + init_timer(&motor_off_timer[drive]); + motor_off_timer[drive].data = drive; + motor_off_timer[drive].function = motor_off_callback; + } + + err = register_blkdev(FLOPPY_MAJOR, ""fd""); + if (err) + goto out_put_disk; + + err = platform_driver_register(&floppy_driver); + if (err) + goto out_unreg_blkdev; + + blk_register_region(MKDEV(FLOPPY_MAJOR, 0), 256, THIS_MODULE, + floppy_find, NULL, NULL); + + for (i = 0; i < 256; i++) + if (ITYPE(i)) + floppy_sizes[i] = floppy_type[ITYPE(i)].size; + else + floppy_sizes[i] = MAX_DISK_SIZE << 1; + + reschedule_timeout(MAXTIMEOUT, ""floppy init""); + config_types(); + + for (i = 0; i < N_FDC; i++) { + fdc = i; + memset(FDCS, 0, sizeof(*FDCS)); + FDCS->dtr = -1; + FDCS->dor = 0x4; +#if defined(__sparc__) || defined(__mc68000__) + /*sparcs/sun3x don't have a DOR reset which we can fall back on to */ +#ifdef __mc68000__ + if (MACH_IS_SUN3X) +#endif + FDCS->version = FDC_82072A; +#endif + } + + use_virtual_dma = can_use_virtual_dma & 1; + fdc_state[0].address = FDC1; + if (fdc_state[0].address == -1) { + cancel_delayed_work(&fd_timeout); + err = -ENODEV; + goto out_unreg_region; + } +#if N_FDC > 1 + fdc_state[1].address = FDC2; +#endif + + fdc = 0; /* reset fdc in case of unexpected interrupt */ + err = floppy_grab_irq_and_dma(); + if (err) { + cancel_delayed_work(&fd_timeout); + err = -EBUSY; + goto out_unreg_region; + } + + /* initialise drive state */ + for (drive = 0; drive < N_DRIVE; drive++) { + memset(UDRS, 0, sizeof(*UDRS)); + memset(UDRWE, 0, sizeof(*UDRWE)); + set_bit(FD_DISK_NEWCHANGE_BIT, &UDRS->flags); + set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags); + set_bit(FD_VERIFY_BIT, &UDRS->flags); + UDRS->fd_device = -1; + floppy_track_buffer = NULL; + max_buffer_sectors = 0; + } + /* + * Small 10 msec delay to let through any interrupt that + * initialization might have triggered, to not + * confuse detection: + */ + msleep(10); + + for (i = 0; i < N_FDC; i++) { + fdc = i; + FDCS->driver_version = FD_DRIVER_VERSION; + for (unit = 0; unit < 4; unit++) + FDCS->track[unit] = 0; + if (FDCS->address == -1) + continue; + FDCS->rawcmd = 2; + if (user_reset_fdc(-1, FD_RESET_ALWAYS, false)) { + /* free ioports reserved by floppy_grab_irq_and_dma() */ + floppy_release_regions(fdc); + FDCS->address = -1; + FDCS->version = FDC_NONE; + continue; + } + /* Try to determine the floppy controller type */ + FDCS->version = get_fdc_version(); + if (FDCS->version == FDC_NONE) { + /* free ioports reserved by floppy_grab_irq_and_dma() */ + floppy_release_regions(fdc); + FDCS->address = -1; + continue; + } + if (can_use_virtual_dma == 2 && FDCS->version < FDC_82072A) + can_use_virtual_dma = 0; + + have_no_fdc = 0; + /* Not all FDCs seem to be able to handle the version command + * properly, so force a reset for the standard FDC clones, + * to avoid interrupt garbage. + */ + user_reset_fdc(-1, FD_RESET_ALWAYS, false); + } + fdc = 0; + cancel_delayed_work(&fd_timeout); + current_drive = 0; + initialized = true; + if (have_no_fdc) { + DPRINT(""no floppy controllers found\n""); + err = have_no_fdc; + goto out_release_dma; + } + + for (drive = 0; drive < N_DRIVE; drive++) { + if (!floppy_available(drive)) + continue; + + floppy_device[drive].name = floppy_device_name; + floppy_device[drive].id = drive; + floppy_device[drive].dev.release = floppy_device_release; + + err = platform_device_register(&floppy_device[drive]); + if (err) + goto out_remove_drives; + + err = device_create_file(&floppy_device[drive].dev, + &dev_attr_cmos); + if (err) + goto out_unreg_platform_dev; + + /* to be cleaned up... */ + disks[drive]->private_data = (void *)(long)drive; + disks[drive]->flags |= GENHD_FL_REMOVABLE; + disks[drive]->driverfs_dev = &floppy_device[drive].dev; + add_disk(disks[drive]); + } + + return 0; + +out_unreg_platform_dev: + platform_device_unregister(&floppy_device[drive]); +out_remove_drives: + while (drive--) { + if (floppy_available(drive)) { + del_gendisk(disks[drive]); + device_remove_file(&floppy_device[drive].dev, &dev_attr_cmos); + platform_device_unregister(&floppy_device[drive]); + } + } +out_release_dma: + if (atomic_read(&usage_count)) + floppy_release_irq_and_dma(); +out_unreg_region: + blk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256); + platform_driver_unregister(&floppy_driver); +out_unreg_blkdev: + unregister_blkdev(FLOPPY_MAJOR, ""fd""); +out_put_disk: + destroy_workqueue(floppy_wq); + for (drive = 0; drive < N_DRIVE; drive++) { + if (!disks[drive]) + break; + if (disks[drive]->queue) { + del_timer_sync(&motor_off_timer[drive]); + blk_cleanup_queue(disks[drive]->queue); + disks[drive]->queue = NULL; + } + put_disk(disks[drive]); + } + return err; +} +","@@ -3067,7 +3067,10 @@ static int raw_cmd_copyout(int cmd, void __user *param, + int ret; + + while (ptr) { +- ret = copy_to_user(param, ptr, sizeof(*ptr)); ++ struct floppy_raw_cmd cmd = *ptr; ++ cmd.next = NULL; ++ cmd.kernel_data = NULL; ++ ret = copy_to_user(param, &cmd, sizeof(cmd)); + if (ret) + return -EFAULT; + param += sizeof(struct floppy_raw_cmd);",1768,2099,4096 +17847,"static int phar_build(zend_object_iterator *iter, void *puser TSRMLS_DC) /* {{{ */ +{ + zval **value; + zend_uchar key_type; + zend_bool close_fp = 1; + ulong int_key; + struct _phar_t *p_obj = (struct _phar_t*) puser; + uint str_key_len, base_len = p_obj->l, fname_len; + phar_entry_data *data; + php_stream *fp; + size_t contents_len; + char *fname, *error = NULL, *base = p_obj->b, *opened, *save = NULL, *temp = NULL; + phar_zstr key; + char *str_key; + zend_class_entry *ce = p_obj->c; + phar_archive_object *phar_obj = p_obj->p; + char *str = ""[stream]""; + + iter->funcs->get_current_data(iter, &value TSRMLS_CC); + + if (EG(exception)) { + return ZEND_HASH_APPLY_STOP; + } + + if (!value) { + /* failure in get_current_data */ + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Iterator %v returned no value"", ce->name); + return ZEND_HASH_APPLY_STOP; + } + + switch (Z_TYPE_PP(value)) { +#if PHP_VERSION_ID >= 60000 + case IS_UNICODE: + zval_unicode_to_string(*(value) TSRMLS_CC); + /* break intentionally omitted */ +#endif + case IS_STRING: + break; + case IS_RESOURCE: + php_stream_from_zval_no_verify(fp, value); + + if (!fp) { + zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, ""Iterator %v returned an invalid stream handle"", ce->name); + return ZEND_HASH_APPLY_STOP; + } + + if (iter->funcs->get_current_key) { + key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC); + + if (EG(exception)) { + return ZEND_HASH_APPLY_STOP; + } + + if (key_type == HASH_KEY_IS_LONG) { + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Iterator %v returned an invalid key (must return a string)"", ce->name); + return ZEND_HASH_APPLY_STOP; + } + + if (key_type > 9) { /* IS_UNICODE == 10 */ +#if PHP_VERSION_ID < 60000 +/* this can never happen, but fixes a compile warning */ + spprintf(&str_key, 0, ""%s"", key); +#else + spprintf(&str_key, 0, ""%v"", key); + ezfree(key); +#endif + } else { + PHAR_STR(key, str_key); + } + + save = str_key; + + if (str_key[str_key_len - 1] == '\0') { + str_key_len--; + } + + } else { + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Iterator %v returned an invalid key (must return a string)"", ce->name); + return ZEND_HASH_APPLY_STOP; + } + + close_fp = 0; + opened = (char *) estrndup(str, sizeof(""[stream]"") - 1); + goto after_open_fp; + case IS_OBJECT: + if (instanceof_function(Z_OBJCE_PP(value), spl_ce_SplFileInfo TSRMLS_CC)) { + char *test = NULL; + zval dummy; + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(*value TSRMLS_CC); + + if (!base_len) { + zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, ""Iterator %v returns an SplFileInfo object, so base directory must be specified"", ce->name); + return ZEND_HASH_APPLY_STOP; + } + + switch (intern->type) { + case SPL_FS_DIR: +#if PHP_VERSION_ID >= 60000 + test = spl_filesystem_object_get_path(intern, NULL, NULL TSRMLS_CC).s; +#elif PHP_VERSION_ID >= 50300 + test = spl_filesystem_object_get_path(intern, NULL TSRMLS_CC); +#else + test = intern->path; +#endif + fname_len = spprintf(&fname, 0, ""%s%c%s"", test, DEFAULT_SLASH, intern->u.dir.entry.d_name); + php_stat(fname, fname_len, FS_IS_DIR, &dummy TSRMLS_CC); + + if (Z_BVAL(dummy)) { + /* ignore directories */ + efree(fname); + return ZEND_HASH_APPLY_KEEP; + } + + test = expand_filepath(fname, NULL TSRMLS_CC); + efree(fname); + + if (test) { + fname = test; + fname_len = strlen(fname); + } else { + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Could not resolve file path""); + return ZEND_HASH_APPLY_STOP; + } + + save = fname; + goto phar_spl_fileinfo; + case SPL_FS_INFO: + case SPL_FS_FILE: +#if PHP_VERSION_ID >= 60000 + if (intern->file_name_type == IS_UNICODE) { + zval zv; + + INIT_ZVAL(zv); + Z_UNIVAL(zv) = intern->file_name; + Z_UNILEN(zv) = intern->file_name_len; + Z_TYPE(zv) = IS_UNICODE; + + zval_copy_ctor(&zv); + zval_unicode_to_string(&zv TSRMLS_CC); + fname = expand_filepath(Z_STRVAL(zv), NULL TSRMLS_CC); + ezfree(Z_UNIVAL(zv)); + } else { + fname = expand_filepath(intern->file_name.s, NULL TSRMLS_CC); + } +#else + fname = expand_filepath(intern->file_name, NULL TSRMLS_CC); +#endif + if (!fname) { + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Could not resolve file path""); + return ZEND_HASH_APPLY_STOP; + } + + fname_len = strlen(fname); + save = fname; + goto phar_spl_fileinfo; + } + } + /* fall-through */ + default: + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Iterator %v returned an invalid value (must return a string)"", ce->name); + return ZEND_HASH_APPLY_STOP; + } + + fname = Z_STRVAL_PP(value); + fname_len = Z_STRLEN_PP(value); + +phar_spl_fileinfo: + if (base_len) { + temp = expand_filepath(base, NULL TSRMLS_CC); + if (!temp) { + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Could not resolve file path""); + if (save) { + efree(save); + } + return ZEND_HASH_APPLY_STOP; + } + base = temp; + base_len = strlen(base); + + if (strstr(fname, base)) { + str_key_len = fname_len - base_len; + + if (str_key_len <= 0) { + if (save) { + efree(save); + efree(temp); + } + return ZEND_HASH_APPLY_KEEP; + } + + str_key = fname + base_len; + + if (*str_key == '/' || *str_key == '\\') { + str_key++; + str_key_len--; + } + + } else { + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Iterator %v returned a path \""%s\"" that is not in the base directory \""%s\"""", ce->name, fname, base); + + if (save) { + efree(save); + efree(temp); + } + + return ZEND_HASH_APPLY_STOP; + } + } else { + if (iter->funcs->get_current_key) { + key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC); + + if (EG(exception)) { + return ZEND_HASH_APPLY_STOP; + } + + if (key_type == HASH_KEY_IS_LONG) { + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Iterator %v returned an invalid key (must return a string)"", ce->name); + return ZEND_HASH_APPLY_STOP; + } + + if (key_type > 9) { /* IS_UNICODE == 10 */ +#if PHP_VERSION_ID < 60000 +/* this can never happen, but fixes a compile warning */ + spprintf(&str_key, 0, ""%s"", key); +#else + spprintf(&str_key, 0, ""%v"", key); + ezfree(key); +#endif + } else { + PHAR_STR(key, str_key); + } + + save = str_key; + + if (str_key[str_key_len - 1] == '\0') str_key_len--; + } else { + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Iterator %v returned an invalid key (must return a string)"", ce->name); + return ZEND_HASH_APPLY_STOP; + } + } +#if PHP_API_VERSION < 20100412 + if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Iterator %v returned a path \""%s\"" that safe mode prevents opening"", ce->name, fname); + + if (save) { + efree(save); + } + + if (temp) { + efree(temp); + } + + return ZEND_HASH_APPLY_STOP; + } +#endif + + if (php_check_open_basedir(fname TSRMLS_CC)) { + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Iterator %v returned a path \""%s\"" that open_basedir prevents opening"", ce->name, fname); + + if (save) { + efree(save); + } + + if (temp) { + efree(temp); + } + + return ZEND_HASH_APPLY_STOP; + } + + /* try to open source file, then create internal phar file and copy contents */ + fp = php_stream_open_wrapper(fname, ""rb"", STREAM_MUST_SEEK|0, &opened); + + if (!fp) { + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Iterator %v returned a file that could not be opened \""%s\"""", ce->name, fname); + + if (save) { + efree(save); + } + + if (temp) { + efree(temp); + } + + return ZEND_HASH_APPLY_STOP; + } +after_open_fp: + if (str_key_len >= sizeof("".phar"")-1 && !memcmp(str_key, "".phar"", sizeof("".phar"")-1)) { + /* silently skip any files that would be added to the magic .phar directory */ + if (save) { + efree(save); + } + + if (temp) { + efree(temp); + } + + if (opened) { + efree(opened); + } + + if (close_fp) { + php_stream_close(fp); + } + + return ZEND_HASH_APPLY_KEEP; + } + + if (!(data = phar_get_or_create_entry_data(phar_obj->arc.archive->fname, phar_obj->arc.archive->fname_len, str_key, str_key_len, ""w+b"", 0, &error, 1 TSRMLS_CC))) { + zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, ""Entry %s cannot be created: %s"", str_key, error); + efree(error); + + if (save) { + efree(save); + } + + if (opened) { + efree(opened); + } + + if (temp) { + efree(temp); + } + + if (close_fp) { + php_stream_close(fp); + } + + return ZEND_HASH_APPLY_STOP; + + } else { + if (error) { + efree(error); + } + /* convert to PHAR_UFP */ + if (data->internal_file->fp_type == PHAR_MOD) { + php_stream_close(data->internal_file->fp); + } + + data->internal_file->fp = NULL; + data->internal_file->fp_type = PHAR_UFP; + data->internal_file->offset_abs = data->internal_file->offset = php_stream_tell(p_obj->fp); + data->fp = NULL; + phar_stream_copy_to_stream(fp, p_obj->fp, PHP_STREAM_COPY_ALL, &contents_len); + data->internal_file->uncompressed_filesize = data->internal_file->compressed_filesize = + php_stream_tell(p_obj->fp) - data->internal_file->offset; + } + + if (close_fp) { + php_stream_close(fp); + } + + add_assoc_string(p_obj->ret, str_key, opened, 0); + + if (save) { + efree(save); + } + + if (temp) { + efree(temp); + } + + data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len; + phar_entry_delref(data TSRMLS_CC); + + return ZEND_HASH_APPLY_KEEP; +} +/* }}} */ +",1,"static int phar_build(zend_object_iterator *iter, void *puser TSRMLS_DC) /* {{{ */ +{ + zval **value; + zend_uchar key_type; + zend_bool close_fp = 1; + ulong int_key; + struct _phar_t *p_obj = (struct _phar_t*) puser; + uint str_key_len, base_len = p_obj->l, fname_len; + phar_entry_data *data; + php_stream *fp; + size_t contents_len; + char *fname, *error = NULL, *base = p_obj->b, *opened, *save = NULL, *temp = NULL; + phar_zstr key; + char *str_key; + zend_class_entry *ce = p_obj->c; + phar_archive_object *phar_obj = p_obj->p; + char *str = ""[stream]""; + + iter->funcs->get_current_data(iter, &value TSRMLS_CC); + + if (EG(exception)) { + return ZEND_HASH_APPLY_STOP; + } + + if (!value) { + /* failure in get_current_data */ + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Iterator %v returned no value"", ce->name); + return ZEND_HASH_APPLY_STOP; + } + + switch (Z_TYPE_PP(value)) { +#if PHP_VERSION_ID >= 60000 + case IS_UNICODE: + zval_unicode_to_string(*(value) TSRMLS_CC); + /* break intentionally omitted */ +#endif + case IS_STRING: + break; + case IS_RESOURCE: + php_stream_from_zval_no_verify(fp, value); + + if (!fp) { + zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, ""Iterator %v returned an invalid stream handle"", ce->name); + return ZEND_HASH_APPLY_STOP; + } + + if (iter->funcs->get_current_key) { + key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC); + + if (EG(exception)) { + return ZEND_HASH_APPLY_STOP; + } + + if (key_type == HASH_KEY_IS_LONG) { + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Iterator %v returned an invalid key (must return a string)"", ce->name); + return ZEND_HASH_APPLY_STOP; + } + + if (key_type > 9) { /* IS_UNICODE == 10 */ +#if PHP_VERSION_ID < 60000 +/* this can never happen, but fixes a compile warning */ + spprintf(&str_key, 0, ""%s"", key); +#else + spprintf(&str_key, 0, ""%v"", key); + ezfree(key); +#endif + } else { + PHAR_STR(key, str_key); + } + + save = str_key; + + if (str_key[str_key_len - 1] == '\0') { + str_key_len--; + } + + } else { + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Iterator %v returned an invalid key (must return a string)"", ce->name); + return ZEND_HASH_APPLY_STOP; + } + + close_fp = 0; + opened = (char *) estrndup(str, sizeof(""[stream]"") - 1); + goto after_open_fp; + case IS_OBJECT: + if (instanceof_function(Z_OBJCE_PP(value), spl_ce_SplFileInfo TSRMLS_CC)) { + char *test = NULL; + zval dummy; + spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(*value TSRMLS_CC); + + if (!base_len) { + zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, ""Iterator %v returns an SplFileInfo object, so base directory must be specified"", ce->name); + return ZEND_HASH_APPLY_STOP; + } + + switch (intern->type) { + case SPL_FS_DIR: +#if PHP_VERSION_ID >= 60000 + test = spl_filesystem_object_get_path(intern, NULL, NULL TSRMLS_CC).s; +#elif PHP_VERSION_ID >= 50300 + test = spl_filesystem_object_get_path(intern, NULL TSRMLS_CC); +#else + test = intern->path; +#endif + fname_len = spprintf(&fname, 0, ""%s%c%s"", test, DEFAULT_SLASH, intern->u.dir.entry.d_name); + php_stat(fname, fname_len, FS_IS_DIR, &dummy TSRMLS_CC); + + if (Z_BVAL(dummy)) { + /* ignore directories */ + efree(fname); + return ZEND_HASH_APPLY_KEEP; + } + + test = expand_filepath(fname, NULL TSRMLS_CC); + efree(fname); + + if (test) { + fname = test; + fname_len = strlen(fname); + } else { + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Could not resolve file path""); + return ZEND_HASH_APPLY_STOP; + } + + save = fname; + goto phar_spl_fileinfo; + case SPL_FS_INFO: + case SPL_FS_FILE: +#if PHP_VERSION_ID >= 60000 + if (intern->file_name_type == IS_UNICODE) { + zval zv; + + INIT_ZVAL(zv); + Z_UNIVAL(zv) = intern->file_name; + Z_UNILEN(zv) = intern->file_name_len; + Z_TYPE(zv) = IS_UNICODE; + + zval_copy_ctor(&zv); + zval_unicode_to_string(&zv TSRMLS_CC); + fname = expand_filepath(Z_STRVAL(zv), NULL TSRMLS_CC); + ezfree(Z_UNIVAL(zv)); + } else { + fname = expand_filepath(intern->file_name.s, NULL TSRMLS_CC); + } +#else + fname = expand_filepath(intern->file_name, NULL TSRMLS_CC); +#endif + if (!fname) { + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Could not resolve file path""); + return ZEND_HASH_APPLY_STOP; + } + + fname_len = strlen(fname); + save = fname; + goto phar_spl_fileinfo; + } + } + /* fall-through */ + default: + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Iterator %v returned an invalid value (must return a string)"", ce->name); + return ZEND_HASH_APPLY_STOP; + } + + fname = Z_STRVAL_PP(value); + fname_len = Z_STRLEN_PP(value); + +phar_spl_fileinfo: + if (base_len) { + temp = expand_filepath(base, NULL TSRMLS_CC); + if (!temp) { + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Could not resolve file path""); + if (save) { + efree(save); + } + return ZEND_HASH_APPLY_STOP; + } + + base = temp; + base_len = strlen(base); + + if (strstr(fname, base)) { + str_key_len = fname_len - base_len; + + if (str_key_len <= 0) { + if (save) { + efree(save); + efree(temp); + } + return ZEND_HASH_APPLY_KEEP; + } + + str_key = fname + base_len; + + if (*str_key == '/' || *str_key == '\\') { + str_key++; + str_key_len--; + } + + } else { + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Iterator %v returned a path \""%s\"" that is not in the base directory \""%s\"""", ce->name, fname, base); + + if (save) { + efree(save); + efree(temp); + } + + return ZEND_HASH_APPLY_STOP; + } + } else { + if (iter->funcs->get_current_key) { + key_type = iter->funcs->get_current_key(iter, &key, &str_key_len, &int_key TSRMLS_CC); + + if (EG(exception)) { + return ZEND_HASH_APPLY_STOP; + } + + if (key_type == HASH_KEY_IS_LONG) { + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Iterator %v returned an invalid key (must return a string)"", ce->name); + return ZEND_HASH_APPLY_STOP; + } + + if (key_type > 9) { /* IS_UNICODE == 10 */ +#if PHP_VERSION_ID < 60000 +/* this can never happen, but fixes a compile warning */ + spprintf(&str_key, 0, ""%s"", key); +#else + spprintf(&str_key, 0, ""%v"", key); + ezfree(key); +#endif + } else { + PHAR_STR(key, str_key); + } + + save = str_key; + + if (str_key[str_key_len - 1] == '\0') str_key_len--; + } else { + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Iterator %v returned an invalid key (must return a string)"", ce->name); + return ZEND_HASH_APPLY_STOP; + } + } +#if PHP_API_VERSION < 20100412 + if (PG(safe_mode) && (!php_checkuid(fname, NULL, CHECKUID_ALLOW_ONLY_FILE))) { + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Iterator %v returned a path \""%s\"" that safe mode prevents opening"", ce->name, fname); + + if (save) { + efree(save); + } + + if (temp) { + efree(temp); + } + + return ZEND_HASH_APPLY_STOP; + } +#endif + + if (php_check_open_basedir(fname TSRMLS_CC)) { + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Iterator %v returned a path \""%s\"" that open_basedir prevents opening"", ce->name, fname); + + if (save) { + efree(save); + } + + if (temp) { + efree(temp); + } + + return ZEND_HASH_APPLY_STOP; + } + + /* try to open source file, then create internal phar file and copy contents */ + fp = php_stream_open_wrapper(fname, ""rb"", STREAM_MUST_SEEK|0, &opened); + + if (!fp) { + zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, ""Iterator %v returned a file that could not be opened \""%s\"""", ce->name, fname); + + if (save) { + efree(save); + } + + if (temp) { + efree(temp); + } + + return ZEND_HASH_APPLY_STOP; + } +after_open_fp: + if (str_key_len >= sizeof("".phar"")-1 && !memcmp(str_key, "".phar"", sizeof("".phar"")-1)) { + /* silently skip any files that would be added to the magic .phar directory */ + if (save) { + efree(save); + } + + if (temp) { + efree(temp); + } + + if (opened) { + efree(opened); + } + + if (close_fp) { + php_stream_close(fp); + } + + return ZEND_HASH_APPLY_KEEP; + } + + if (!(data = phar_get_or_create_entry_data(phar_obj->arc.archive->fname, phar_obj->arc.archive->fname_len, str_key, str_key_len, ""w+b"", 0, &error, 1 TSRMLS_CC))) { + zend_throw_exception_ex(spl_ce_BadMethodCallException, 0 TSRMLS_CC, ""Entry %s cannot be created: %s"", str_key, error); + efree(error); + + if (save) { + efree(save); + } + + if (opened) { + efree(opened); + } + + if (temp) { + efree(temp); + } + + if (close_fp) { + php_stream_close(fp); + } + + return ZEND_HASH_APPLY_STOP; + + } else { + if (error) { + efree(error); + } + /* convert to PHAR_UFP */ + if (data->internal_file->fp_type == PHAR_MOD) { + php_stream_close(data->internal_file->fp); + } + + data->internal_file->fp = NULL; + data->internal_file->fp_type = PHAR_UFP; + data->internal_file->offset_abs = data->internal_file->offset = php_stream_tell(p_obj->fp); + data->fp = NULL; + phar_stream_copy_to_stream(fp, p_obj->fp, PHP_STREAM_COPY_ALL, &contents_len); + data->internal_file->uncompressed_filesize = data->internal_file->compressed_filesize = + php_stream_tell(p_obj->fp) - data->internal_file->offset; + } + + if (close_fp) { + php_stream_close(fp); + } + + add_assoc_string(p_obj->ret, str_key, opened, 0); + + if (save) { + efree(save); + } + + if (temp) { + efree(temp); + } + + data->internal_file->compressed_filesize = data->internal_file->uncompressed_filesize = contents_len; + phar_entry_delref(data TSRMLS_CC); + + return ZEND_HASH_APPLY_KEEP; +} +/* }}} */ +","@@ -1269,7 +1269,7 @@ PHP_METHOD(Phar, __construct) + INIT_PZVAL(&arg2); + ZVAL_LONG(&arg2, flags); + +- zend_call_method_with_2_params(&zobj, Z_OBJCE_P(zobj), ++ zend_call_method_with_2_params(&zobj, Z_OBJCE_P(zobj), + &spl_ce_RecursiveDirectoryIterator->constructor, ""__construct"", NULL, &arg1, &arg2); + + if (!phar_data->is_persistent) { +@@ -1293,7 +1293,7 @@ PHP_METHOD(Phar, getSupportedSignatures) + if (zend_parse_parameters_none() == FAILURE) { + return; + } +- ++ + array_init(return_value); + + add_next_index_stringl(return_value, ""MD5"", 3, 1); +@@ -1320,7 +1320,7 @@ PHP_METHOD(Phar, getSupportedCompression) + if (zend_parse_parameters_none() == FAILURE) { + return; + } +- ++ + array_init(return_value); + phar_request_initialize(TSRMLS_C); + +@@ -1608,7 +1608,7 @@ phar_spl_fileinfo: + } + return ZEND_HASH_APPLY_STOP; + } +- ++ + base = temp; + base_len = strlen(base); + +@@ -1805,7 +1805,7 @@ after_open_fp: + /* {{{ proto array Phar::buildFromDirectory(string base_dir[, string regex]) + * Construct a phar archive from an existing directory, recursively. + * Optional second parameter is a regular expression for filtering directory contents. +- * ++ * + * Return value is an array mapping phar index to actual files added. + */ + PHP_METHOD(Phar, buildFromDirectory) +@@ -1845,7 +1845,7 @@ PHP_METHOD(Phar, buildFromDirectory) + ZVAL_LONG(&arg2, SPL_FILE_DIR_SKIPDOTS|SPL_FILE_DIR_UNIXPATHS); + #endif + +- zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator, ++ zend_call_method_with_2_params(&iter, spl_ce_RecursiveDirectoryIterator, + &spl_ce_RecursiveDirectoryIterator->constructor, ""__construct"", NULL, &arg, &arg2); + + if (EG(exception)) { +@@ -1862,7 +1862,7 @@ PHP_METHOD(Phar, buildFromDirectory) + RETURN_FALSE; + } + +- zend_call_method_with_1_params(&iteriter, spl_ce_RecursiveIteratorIterator, ++ zend_call_method_with_1_params(&iteriter, spl_ce_RecursiveIteratorIterator, + &spl_ce_RecursiveIteratorIterator->constructor, ""__construct"", NULL, iter); + + if (EG(exception)) { +@@ -1887,7 +1887,7 @@ PHP_METHOD(Phar, buildFromDirectory) + INIT_PZVAL(&arg2); + ZVAL_STRINGL(&arg2, regex, regex_len, 0); + +- zend_call_method_with_2_params(®exiter, spl_ce_RegexIterator, ++ zend_call_method_with_2_params(®exiter, spl_ce_RegexIterator, + &spl_ce_RegexIterator->constructor, ""__construct"", NULL, iteriter, &arg2); + } + +@@ -2008,7 +2008,7 @@ PHP_METHOD(Phar, buildFromIterator) + PHP_METHOD(Phar, count) + { + PHAR_ARCHIVE_OBJECT(); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -2173,7 +2173,7 @@ static zval *phar_rename_archive(phar_archive_data *phar, char *ext, zend_bool c + spprintf(&newname, 0, ""%s.%s"", strtok(basename, "".""), ext); + efree(basename); + +- ++ + + basepath = estrndup(oldpath, (strlen(oldpath) - oldname_len)); + phar->fname_len = spprintf(&newpath, 0, ""%s%s"", basepath, newname); +@@ -2419,7 +2419,9 @@ no_copy: + zend_hash_destroy(&(phar->manifest)); + zend_hash_destroy(&(phar->mounted_dirs)); + zend_hash_destroy(&(phar->virtual_dirs)); +- php_stream_close(phar->fp); ++ if (phar->fp) { ++ php_stream_close(phar->fp); ++ } + efree(phar->fname); + efree(phar); + return NULL; +@@ -2639,7 +2641,7 @@ PHP_METHOD(Phar, convertToData) + PHP_METHOD(Phar, isCompressed) + { + PHAR_ARCHIVE_OBJECT(); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -2663,7 +2665,7 @@ PHP_METHOD(Phar, isWritable) + { + php_stream_statbuf ssb; + PHAR_ARCHIVE_OBJECT(); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -2741,7 +2743,7 @@ PHP_METHOD(Phar, delete) + PHP_METHOD(Phar, getAlias) + { + PHAR_ARCHIVE_OBJECT(); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -2758,7 +2760,7 @@ PHP_METHOD(Phar, getAlias) + PHP_METHOD(Phar, getPath) + { + PHAR_ARCHIVE_OBJECT(); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -2874,7 +2876,7 @@ valid_alias: + PHP_METHOD(Phar, getVersion) + { + PHAR_ARCHIVE_OBJECT(); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -2889,7 +2891,7 @@ PHP_METHOD(Phar, getVersion) + PHP_METHOD(Phar, startBuffering) + { + PHAR_ARCHIVE_OBJECT(); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -2904,7 +2906,7 @@ PHP_METHOD(Phar, startBuffering) + PHP_METHOD(Phar, isBuffering) + { + PHAR_ARCHIVE_OBJECT(); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -2921,7 +2923,7 @@ PHP_METHOD(Phar, stopBuffering) + char *error; + + PHAR_ARCHIVE_OBJECT(); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -3156,7 +3158,7 @@ PHP_METHOD(Phar, setSignatureAlgorithm) + PHP_METHOD(Phar, getSignature) + { + PHAR_ARCHIVE_OBJECT(); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -3200,7 +3202,7 @@ PHP_METHOD(Phar, getSignature) + PHP_METHOD(Phar, getModified) + { + PHAR_ARCHIVE_OBJECT(); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -3462,7 +3464,7 @@ PHP_METHOD(Phar, decompressFiles) + { + char *error; + PHAR_ARCHIVE_OBJECT(); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -3983,7 +3985,7 @@ PHP_METHOD(Phar, getStub) + phar_entry_info *stub; + + PHAR_ARCHIVE_OBJECT(); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -4086,7 +4088,7 @@ PHP_METHOD(Phar, hasMetadata) + PHP_METHOD(Phar, getMetadata) + { + PHAR_ARCHIVE_OBJECT(); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -4544,7 +4546,7 @@ PHP_METHOD(PharFileInfo, __construct) + INIT_PZVAL(&arg1); + ZVAL_STRINGL(&arg1, fname, fname_len, 0); + +- zend_call_method_with_1_params(&zobj, Z_OBJCE_P(zobj), ++ zend_call_method_with_1_params(&zobj, Z_OBJCE_P(zobj), + &spl_ce_SplFileInfo->constructor, ""__construct"", NULL, &arg1); + } + /* }}} */ +@@ -4582,7 +4584,7 @@ PHP_METHOD(PharFileInfo, __destruct) + PHP_METHOD(PharFileInfo, getCompressedSize) + { + PHAR_ENTRY_OBJECT(); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -4624,7 +4626,7 @@ PHP_METHOD(PharFileInfo, isCompressed) + PHP_METHOD(PharFileInfo, getCRC32) + { + PHAR_ENTRY_OBJECT(); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -4650,7 +4652,7 @@ PHP_METHOD(PharFileInfo, getCRC32) + PHP_METHOD(PharFileInfo, isCRCChecked) + { + PHAR_ENTRY_OBJECT(); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -4665,7 +4667,7 @@ PHP_METHOD(PharFileInfo, isCRCChecked) + PHP_METHOD(PharFileInfo, getPharFlags) + { + PHAR_ENTRY_OBJECT(); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -4743,7 +4745,7 @@ PHP_METHOD(PharFileInfo, chmod) + PHP_METHOD(PharFileInfo, hasMetadata) + { + PHAR_ENTRY_OBJECT(); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -4758,7 +4760,7 @@ PHP_METHOD(PharFileInfo, hasMetadata) + PHP_METHOD(PharFileInfo, getMetadata) + { + PHAR_ENTRY_OBJECT(); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -4839,7 +4841,7 @@ PHP_METHOD(PharFileInfo, delMetadata) + char *error; + + PHAR_ENTRY_OBJECT(); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -4897,7 +4899,7 @@ PHP_METHOD(PharFileInfo, getContent) + phar_entry_info *link; + + PHAR_ENTRY_OBJECT(); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + } +@@ -5071,7 +5073,7 @@ PHP_METHOD(PharFileInfo, decompress) + { + char *error; + PHAR_ENTRY_OBJECT(); +- ++ + if (zend_parse_parameters_none() == FAILURE) { + return; + }",2934,3265,4096 +9633,"static void AppLayerProtoDetectPrintProbingParsers(AppLayerProtoDetectProbingParser *pp) +{ + SCEnter(); + + AppLayerProtoDetectProbingParserPort *pp_port = NULL; + AppLayerProtoDetectProbingParserElement *pp_pe = NULL; + + printf(""\nProtocol Detection Configuration\n""); + + for ( ; pp != NULL; pp = pp->next) { + /* print ip protocol */ + if (pp->ipproto == IPPROTO_TCP) + printf(""IPProto: TCP\n""); + else if (pp->ipproto == IPPROTO_UDP) + printf(""IPProto: UDP\n""); + else + printf(""IPProto: %""PRIu8""\n"", pp->ipproto); + + pp_port = pp->port; + for ( ; pp_port != NULL; pp_port = pp_port->next) { + if (pp_port->dp != NULL) { + printf("" Port: %""PRIu16 ""\n"", pp_port->port); + + printf("" Destination port: (max-depth: %""PRIu16 "", "" + ""mask - %""PRIu32"")\n"", + pp_port->dp_max_depth, + pp_port->alproto_mask); + pp_pe = pp_port->dp; + for ( ; pp_pe != NULL; pp_pe = pp_pe->next) { + + if (pp_pe->alproto == ALPROTO_HTTP) + printf("" alproto: ALPROTO_HTTP\n""); + else if (pp_pe->alproto == ALPROTO_FTP) + printf("" alproto: ALPROTO_FTP\n""); + else if (pp_pe->alproto == ALPROTO_FTPDATA) + printf("" alproto: ALPROTO_FTPDATA\n""); + else if (pp_pe->alproto == ALPROTO_SMTP) + printf("" alproto: ALPROTO_SMTP\n""); + else if (pp_pe->alproto == ALPROTO_TLS) + printf("" alproto: ALPROTO_TLS\n""); + else if (pp_pe->alproto == ALPROTO_SSH) + printf("" alproto: ALPROTO_SSH\n""); + else if (pp_pe->alproto == ALPROTO_IMAP) + printf("" alproto: ALPROTO_IMAP\n""); + else if (pp_pe->alproto == ALPROTO_MSN) + printf("" alproto: ALPROTO_MSN\n""); + else if (pp_pe->alproto == ALPROTO_JABBER) + printf("" alproto: ALPROTO_JABBER\n""); + else if (pp_pe->alproto == ALPROTO_SMB) + printf("" alproto: ALPROTO_SMB\n""); + else if (pp_pe->alproto == ALPROTO_SMB2) + printf("" alproto: ALPROTO_SMB2\n""); + else if (pp_pe->alproto == ALPROTO_DCERPC) + printf("" alproto: ALPROTO_DCERPC\n""); + else if (pp_pe->alproto == ALPROTO_IRC) + printf("" alproto: ALPROTO_IRC\n""); + else if (pp_pe->alproto == ALPROTO_DNS) + printf("" alproto: ALPROTO_DNS\n""); + else if (pp_pe->alproto == ALPROTO_MODBUS) + printf("" alproto: ALPROTO_MODBUS\n""); + else if (pp_pe->alproto == ALPROTO_ENIP) + printf("" alproto: ALPROTO_ENIP\n""); + else if (pp_pe->alproto == ALPROTO_NFS) + printf("" alproto: ALPROTO_NFS\n""); + else if (pp_pe->alproto == ALPROTO_NTP) + printf("" alproto: ALPROTO_NTP\n""); + else if (pp_pe->alproto == ALPROTO_TFTP) + printf("" alproto: ALPROTO_TFTP\n""); + else if (pp_pe->alproto == ALPROTO_IKEV2) + printf("" alproto: ALPROTO_IKEV2\n""); + else if (pp_pe->alproto == ALPROTO_KRB5) + printf("" alproto: ALPROTO_KRB5\n""); + else if (pp_pe->alproto == ALPROTO_DHCP) + printf("" alproto: ALPROTO_DHCP\n""); + else if (pp_pe->alproto == ALPROTO_TEMPLATE_RUST) + printf("" alproto: ALPROTO_TEMPLATE_RUST\n""); + else if (pp_pe->alproto == ALPROTO_TEMPLATE) + printf("" alproto: ALPROTO_TEMPLATE\n""); + else if (pp_pe->alproto == ALPROTO_DNP3) + printf("" alproto: ALPROTO_DNP3\n""); + else + printf(""impossible\n""); + + printf("" port: %""PRIu16 ""\n"", pp_pe->port); + printf("" mask: %""PRIu32 ""\n"", pp_pe->alproto_mask); + printf("" min_depth: %""PRIu32 ""\n"", pp_pe->min_depth); + printf("" max_depth: %""PRIu32 ""\n"", pp_pe->max_depth); + + printf(""\n""); + } + } + + if (pp_port->sp == NULL) { + continue; + } + + printf("" Source port: (max-depth: %""PRIu16 "", "" + ""mask - %""PRIu32"")\n"", + pp_port->sp_max_depth, + pp_port->alproto_mask); + pp_pe = pp_port->sp; + for ( ; pp_pe != NULL; pp_pe = pp_pe->next) { + + if (pp_pe->alproto == ALPROTO_HTTP) + printf("" alproto: ALPROTO_HTTP\n""); + else if (pp_pe->alproto == ALPROTO_FTP) + printf("" alproto: ALPROTO_FTP\n""); + else if (pp_pe->alproto == ALPROTO_FTPDATA) + printf("" alproto: ALPROTO_FTPDATA\n""); + else if (pp_pe->alproto == ALPROTO_SMTP) + printf("" alproto: ALPROTO_SMTP\n""); + else if (pp_pe->alproto == ALPROTO_TLS) + printf("" alproto: ALPROTO_TLS\n""); + else if (pp_pe->alproto == ALPROTO_SSH) + printf("" alproto: ALPROTO_SSH\n""); + else if (pp_pe->alproto == ALPROTO_IMAP) + printf("" alproto: ALPROTO_IMAP\n""); + else if (pp_pe->alproto == ALPROTO_MSN) + printf("" alproto: ALPROTO_MSN\n""); + else if (pp_pe->alproto == ALPROTO_JABBER) + printf("" alproto: ALPROTO_JABBER\n""); + else if (pp_pe->alproto == ALPROTO_SMB) + printf("" alproto: ALPROTO_SMB\n""); + else if (pp_pe->alproto == ALPROTO_SMB2) + printf("" alproto: ALPROTO_SMB2\n""); + else if (pp_pe->alproto == ALPROTO_DCERPC) + printf("" alproto: ALPROTO_DCERPC\n""); + else if (pp_pe->alproto == ALPROTO_IRC) + printf("" alproto: ALPROTO_IRC\n""); + else if (pp_pe->alproto == ALPROTO_DNS) + printf("" alproto: ALPROTO_DNS\n""); + else if (pp_pe->alproto == ALPROTO_MODBUS) + printf("" alproto: ALPROTO_MODBUS\n""); + else if (pp_pe->alproto == ALPROTO_ENIP) + printf("" alproto: ALPROTO_ENIP\n""); + else if (pp_pe->alproto == ALPROTO_NFS) + printf("" alproto: ALPROTO_NFS\n""); + else if (pp_pe->alproto == ALPROTO_NTP) + printf("" alproto: ALPROTO_NTP\n""); + else if (pp_pe->alproto == ALPROTO_TFTP) + printf("" alproto: ALPROTO_TFTP\n""); + else if (pp_pe->alproto == ALPROTO_IKEV2) + printf("" alproto: ALPROTO_IKEV2\n""); + else if (pp_pe->alproto == ALPROTO_KRB5) + printf("" alproto: ALPROTO_KRB5\n""); + else if (pp_pe->alproto == ALPROTO_DHCP) + printf("" alproto: ALPROTO_DHCP\n""); + else if (pp_pe->alproto == ALPROTO_TEMPLATE_RUST) + printf("" alproto: ALPROTO_TEMPLATE_RUST\n""); + else if (pp_pe->alproto == ALPROTO_TEMPLATE) + printf("" alproto: ALPROTO_TEMPLATE\n""); + else if (pp_pe->alproto == ALPROTO_DNP3) + printf("" alproto: ALPROTO_DNP3\n""); + else + printf(""impossible\n""); + + printf("" port: %""PRIu16 ""\n"", pp_pe->port); + printf("" mask: %""PRIu32 ""\n"", pp_pe->alproto_mask); + printf("" min_depth: %""PRIu32 ""\n"", pp_pe->min_depth); + printf("" max_depth: %""PRIu32 ""\n"", pp_pe->max_depth); + + printf(""\n""); + } + } + } + + SCReturn; +} +",0,"static void AppLayerProtoDetectPrintProbingParsers(AppLayerProtoDetectProbingParser *pp) +{ + SCEnter(); + + AppLayerProtoDetectProbingParserPort *pp_port = NULL; + AppLayerProtoDetectProbingParserElement *pp_pe = NULL; + + printf(""\nProtocol Detection Configuration\n""); + + for ( ; pp != NULL; pp = pp->next) { + /* print ip protocol */ + if (pp->ipproto == IPPROTO_TCP) + printf(""IPProto: TCP\n""); + else if (pp->ipproto == IPPROTO_UDP) + printf(""IPProto: UDP\n""); + else + printf(""IPProto: %""PRIu8""\n"", pp->ipproto); + + pp_port = pp->port; + for ( ; pp_port != NULL; pp_port = pp_port->next) { + if (pp_port->dp != NULL) { + printf("" Port: %""PRIu16 ""\n"", pp_port->port); + + printf("" Destination port: (max-depth: %""PRIu16 "", "" + ""mask - %""PRIu32"")\n"", + pp_port->dp_max_depth, + pp_port->alproto_mask); + pp_pe = pp_port->dp; + for ( ; pp_pe != NULL; pp_pe = pp_pe->next) { + + if (pp_pe->alproto == ALPROTO_HTTP) + printf("" alproto: ALPROTO_HTTP\n""); + else if (pp_pe->alproto == ALPROTO_FTP) + printf("" alproto: ALPROTO_FTP\n""); + else if (pp_pe->alproto == ALPROTO_FTPDATA) + printf("" alproto: ALPROTO_FTPDATA\n""); + else if (pp_pe->alproto == ALPROTO_SMTP) + printf("" alproto: ALPROTO_SMTP\n""); + else if (pp_pe->alproto == ALPROTO_TLS) + printf("" alproto: ALPROTO_TLS\n""); + else if (pp_pe->alproto == ALPROTO_SSH) + printf("" alproto: ALPROTO_SSH\n""); + else if (pp_pe->alproto == ALPROTO_IMAP) + printf("" alproto: ALPROTO_IMAP\n""); + else if (pp_pe->alproto == ALPROTO_MSN) + printf("" alproto: ALPROTO_MSN\n""); + else if (pp_pe->alproto == ALPROTO_JABBER) + printf("" alproto: ALPROTO_JABBER\n""); + else if (pp_pe->alproto == ALPROTO_SMB) + printf("" alproto: ALPROTO_SMB\n""); + else if (pp_pe->alproto == ALPROTO_SMB2) + printf("" alproto: ALPROTO_SMB2\n""); + else if (pp_pe->alproto == ALPROTO_DCERPC) + printf("" alproto: ALPROTO_DCERPC\n""); + else if (pp_pe->alproto == ALPROTO_IRC) + printf("" alproto: ALPROTO_IRC\n""); + else if (pp_pe->alproto == ALPROTO_DNS) + printf("" alproto: ALPROTO_DNS\n""); + else if (pp_pe->alproto == ALPROTO_MODBUS) + printf("" alproto: ALPROTO_MODBUS\n""); + else if (pp_pe->alproto == ALPROTO_ENIP) + printf("" alproto: ALPROTO_ENIP\n""); + else if (pp_pe->alproto == ALPROTO_NFS) + printf("" alproto: ALPROTO_NFS\n""); + else if (pp_pe->alproto == ALPROTO_NTP) + printf("" alproto: ALPROTO_NTP\n""); + else if (pp_pe->alproto == ALPROTO_TFTP) + printf("" alproto: ALPROTO_TFTP\n""); + else if (pp_pe->alproto == ALPROTO_IKEV2) + printf("" alproto: ALPROTO_IKEV2\n""); + else if (pp_pe->alproto == ALPROTO_KRB5) + printf("" alproto: ALPROTO_KRB5\n""); + else if (pp_pe->alproto == ALPROTO_DHCP) + printf("" alproto: ALPROTO_DHCP\n""); + else if (pp_pe->alproto == ALPROTO_TEMPLATE_RUST) + printf("" alproto: ALPROTO_TEMPLATE_RUST\n""); + else if (pp_pe->alproto == ALPROTO_TEMPLATE) + printf("" alproto: ALPROTO_TEMPLATE\n""); + else if (pp_pe->alproto == ALPROTO_DNP3) + printf("" alproto: ALPROTO_DNP3\n""); + else + printf(""impossible\n""); + + printf("" port: %""PRIu16 ""\n"", pp_pe->port); + printf("" mask: %""PRIu32 ""\n"", pp_pe->alproto_mask); + printf("" min_depth: %""PRIu32 ""\n"", pp_pe->min_depth); + printf("" max_depth: %""PRIu32 ""\n"", pp_pe->max_depth); + + printf(""\n""); + } + } + + if (pp_port->sp == NULL) { + continue; + } + + printf("" Source port: (max-depth: %""PRIu16 "", "" + ""mask - %""PRIu32"")\n"", + pp_port->sp_max_depth, + pp_port->alproto_mask); + pp_pe = pp_port->sp; + for ( ; pp_pe != NULL; pp_pe = pp_pe->next) { + + if (pp_pe->alproto == ALPROTO_HTTP) + printf("" alproto: ALPROTO_HTTP\n""); + else if (pp_pe->alproto == ALPROTO_FTP) + printf("" alproto: ALPROTO_FTP\n""); + else if (pp_pe->alproto == ALPROTO_FTPDATA) + printf("" alproto: ALPROTO_FTPDATA\n""); + else if (pp_pe->alproto == ALPROTO_SMTP) + printf("" alproto: ALPROTO_SMTP\n""); + else if (pp_pe->alproto == ALPROTO_TLS) + printf("" alproto: ALPROTO_TLS\n""); + else if (pp_pe->alproto == ALPROTO_SSH) + printf("" alproto: ALPROTO_SSH\n""); + else if (pp_pe->alproto == ALPROTO_IMAP) + printf("" alproto: ALPROTO_IMAP\n""); + else if (pp_pe->alproto == ALPROTO_MSN) + printf("" alproto: ALPROTO_MSN\n""); + else if (pp_pe->alproto == ALPROTO_JABBER) + printf("" alproto: ALPROTO_JABBER\n""); + else if (pp_pe->alproto == ALPROTO_SMB) + printf("" alproto: ALPROTO_SMB\n""); + else if (pp_pe->alproto == ALPROTO_SMB2) + printf("" alproto: ALPROTO_SMB2\n""); + else if (pp_pe->alproto == ALPROTO_DCERPC) + printf("" alproto: ALPROTO_DCERPC\n""); + else if (pp_pe->alproto == ALPROTO_IRC) + printf("" alproto: ALPROTO_IRC\n""); + else if (pp_pe->alproto == ALPROTO_DNS) + printf("" alproto: ALPROTO_DNS\n""); + else if (pp_pe->alproto == ALPROTO_MODBUS) + printf("" alproto: ALPROTO_MODBUS\n""); + else if (pp_pe->alproto == ALPROTO_ENIP) + printf("" alproto: ALPROTO_ENIP\n""); + else if (pp_pe->alproto == ALPROTO_NFS) + printf("" alproto: ALPROTO_NFS\n""); + else if (pp_pe->alproto == ALPROTO_NTP) + printf("" alproto: ALPROTO_NTP\n""); + else if (pp_pe->alproto == ALPROTO_TFTP) + printf("" alproto: ALPROTO_TFTP\n""); + else if (pp_pe->alproto == ALPROTO_IKEV2) + printf("" alproto: ALPROTO_IKEV2\n""); + else if (pp_pe->alproto == ALPROTO_KRB5) + printf("" alproto: ALPROTO_KRB5\n""); + else if (pp_pe->alproto == ALPROTO_DHCP) + printf("" alproto: ALPROTO_DHCP\n""); + else if (pp_pe->alproto == ALPROTO_TEMPLATE_RUST) + printf("" alproto: ALPROTO_TEMPLATE_RUST\n""); + else if (pp_pe->alproto == ALPROTO_TEMPLATE) + printf("" alproto: ALPROTO_TEMPLATE\n""); + else if (pp_pe->alproto == ALPROTO_DNP3) + printf("" alproto: ALPROTO_DNP3\n""); + else + printf(""impossible\n""); + + printf("" port: %""PRIu16 ""\n"", pp_pe->port); + printf("" mask: %""PRIu32 ""\n"", pp_pe->alproto_mask); + printf("" min_depth: %""PRIu32 ""\n"", pp_pe->min_depth); + printf("" max_depth: %""PRIu32 ""\n"", pp_pe->max_depth); + + printf(""\n""); + } + } + } + + SCReturn; +} +","@@ -1361,6 +1361,7 @@ AppProto AppLayerProtoDetectGetProto(AppLayerProtoDetectThreadCtx *tctx, + (direction & STREAM_TOSERVER) ? ""toserver"" : ""toclient""); + + AppProto alproto = ALPROTO_UNKNOWN; ++ AppProto pm_alproto = ALPROTO_UNKNOWN; + + if (!FLOW_IS_PM_DONE(f, direction)) { + AppProto pm_results[ALPROTO_MAX]; +@@ -1371,7 +1372,15 @@ AppProto AppLayerProtoDetectGetProto(AppLayerProtoDetectThreadCtx *tctx, + pm_results); + if (pm_matches > 0) { + alproto = pm_results[0]; +- goto end; ++ ++ /* HACK: if detected protocol is dcerpc/udp, we run PP as well ++ * to avoid misdetecting DNS as DCERPC. */ ++ if (!(ipproto == IPPROTO_UDP && alproto == ALPROTO_DCERPC)) ++ goto end; ++ ++ pm_alproto = alproto; ++ ++ /* fall through */ + } + } + +@@ -1388,6 +1397,9 @@ AppProto AppLayerProtoDetectGetProto(AppLayerProtoDetectThreadCtx *tctx, + } + + end: ++ if (alproto == ALPROTO_UNKNOWN) ++ alproto = pm_alproto; ++ + SCReturnUInt(alproto); + } + ",2001,2332,4096 +17867,"static int ape_read_header(AVFormatContext * s, AVFormatParameters * ap) +{ + AVIOContext *pb = s->pb; + APEContext *ape = s->priv_data; + AVStream *st; + uint32_t tag; + int i; + int total_blocks; + int64_t pts; + + /* TODO: Skip any leading junk such as id3v2 tags */ + ape->junklength = 0; + + tag = avio_rl32(pb); + if (tag != MKTAG('M', 'A', 'C', ' ')) + return -1; + + ape->fileversion = avio_rl16(pb); + + if (ape->fileversion < APE_MIN_VERSION || ape->fileversion > APE_MAX_VERSION) { + av_log(s, AV_LOG_ERROR, ""Unsupported file version - %d.%02d\n"", ape->fileversion / 1000, (ape->fileversion % 1000) / 10); + return -1; + } + + if (ape->fileversion >= 3980) { + ape->padding1 = avio_rl16(pb); + ape->descriptorlength = avio_rl32(pb); + ape->headerlength = avio_rl32(pb); + ape->seektablelength = avio_rl32(pb); + ape->wavheaderlength = avio_rl32(pb); + ape->audiodatalength = avio_rl32(pb); + ape->audiodatalength_high = avio_rl32(pb); + ape->wavtaillength = avio_rl32(pb); + avio_read(pb, ape->md5, 16); + + /* Skip any unknown bytes at the end of the descriptor. + This is for future compatibility */ + if (ape->descriptorlength > 52) + avio_seek(pb, ape->descriptorlength - 52, SEEK_CUR); + + /* Read header data */ + ape->compressiontype = avio_rl16(pb); + ape->formatflags = avio_rl16(pb); + ape->blocksperframe = avio_rl32(pb); + ape->finalframeblocks = avio_rl32(pb); + ape->totalframes = avio_rl32(pb); + ape->bps = avio_rl16(pb); + ape->channels = avio_rl16(pb); + ape->samplerate = avio_rl32(pb); + } else { + ape->descriptorlength = 0; + ape->headerlength = 32; + + ape->compressiontype = avio_rl16(pb); + ape->formatflags = avio_rl16(pb); + ape->channels = avio_rl16(pb); + ape->samplerate = avio_rl32(pb); + ape->wavheaderlength = avio_rl32(pb); + ape->wavtaillength = avio_rl32(pb); + ape->totalframes = avio_rl32(pb); + ape->finalframeblocks = avio_rl32(pb); + + if (ape->formatflags & MAC_FORMAT_FLAG_HAS_PEAK_LEVEL) { + avio_seek(pb, 4, SEEK_CUR); /* Skip the peak level */ + ape->headerlength += 4; + } + + if (ape->formatflags & MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS) { + ape->seektablelength = avio_rl32(pb); + ape->headerlength += 4; + ape->seektablelength *= sizeof(int32_t); + } else + ape->seektablelength = ape->totalframes * sizeof(int32_t); + + if (ape->formatflags & MAC_FORMAT_FLAG_8_BIT) + ape->bps = 8; + else if (ape->formatflags & MAC_FORMAT_FLAG_24_BIT) + ape->bps = 24; + else + ape->bps = 16; + + if (ape->fileversion >= 3950) + ape->blocksperframe = 73728 * 4; + else if (ape->fileversion >= 3900 || (ape->fileversion >= 3800 && ape->compressiontype >= 4000)) + ape->blocksperframe = 73728; + else + ape->blocksperframe = 9216; + + /* Skip any stored wav header */ + if (!(ape->formatflags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER)) + avio_seek(pb, ape->wavheaderlength, SEEK_CUR); + } + + if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){ + av_log(s, AV_LOG_ERROR, ""Too many frames: %d\n"", ape->totalframes); + return -1; + } + ape->frames = av_malloc(ape->totalframes * sizeof(APEFrame)); + if(!ape->frames) + return AVERROR(ENOMEM); + ape->firstframe = ape->junklength + ape->descriptorlength + ape->headerlength + ape->seektablelength + ape->wavheaderlength; + ape->currentframe = 0; + + + ape->totalsamples = ape->finalframeblocks; + if (ape->totalframes > 1) + ape->totalsamples += ape->blocksperframe * (ape->totalframes - 1); + + if (ape->seektablelength > 0) { + ape->seektable = av_malloc(ape->seektablelength); + for (i = 0; i < ape->seektablelength / sizeof(uint32_t); i++) + ape->seektable[i] = avio_rl32(pb); + } + + ape->frames[0].pos = ape->firstframe; + ape->frames[0].nblocks = ape->blocksperframe; + ape->frames[0].skip = 0; + for (i = 1; i < ape->totalframes; i++) { + ape->frames[i].pos = ape->seektable[i]; //ape->frames[i-1].pos + ape->blocksperframe; + ape->frames[i].nblocks = ape->blocksperframe; + ape->frames[i - 1].size = ape->frames[i].pos - ape->frames[i - 1].pos; + ape->frames[i].skip = (ape->frames[i].pos - ape->frames[0].pos) & 3; + } + ape->frames[ape->totalframes - 1].size = ape->finalframeblocks * 4; + ape->frames[ape->totalframes - 1].nblocks = ape->finalframeblocks; + + for (i = 0; i < ape->totalframes; i++) { + if(ape->frames[i].skip){ + ape->frames[i].pos -= ape->frames[i].skip; + ape->frames[i].size += ape->frames[i].skip; + } + ape->frames[i].size = (ape->frames[i].size + 3) & ~3; + } + + + ape_dumpinfo(s, ape); + + /* try to read APE tags */ + if (!url_is_streamed(pb)) { + ff_ape_parse_tag(s); + avio_seek(pb, 0, SEEK_SET); + } + + av_log(s, AV_LOG_DEBUG, ""Decoding file - v%d.%02d, compression level %d\n"", ape->fileversion / 1000, (ape->fileversion % 1000) / 10, ape->compressiontype); + + /* now we are ready: build format streams */ + st = av_new_stream(s, 0); + if (!st) + return -1; + + total_blocks = (ape->totalframes == 0) ? 0 : ((ape->totalframes - 1) * ape->blocksperframe) + ape->finalframeblocks; + + st->codec->codec_type = AVMEDIA_TYPE_AUDIO; + st->codec->codec_id = CODEC_ID_APE; + st->codec->codec_tag = MKTAG('A', 'P', 'E', ' '); + st->codec->channels = ape->channels; + st->codec->sample_rate = ape->samplerate; + st->codec->bits_per_coded_sample = ape->bps; + st->codec->frame_size = MAC_SUBFRAME_SIZE; + + st->nb_frames = ape->totalframes; + st->start_time = 0; + st->duration = total_blocks / MAC_SUBFRAME_SIZE; + av_set_pts_info(st, 64, MAC_SUBFRAME_SIZE, ape->samplerate); + + st->codec->extradata = av_malloc(APE_EXTRADATA_SIZE); + st->codec->extradata_size = APE_EXTRADATA_SIZE; + AV_WL16(st->codec->extradata + 0, ape->fileversion); + AV_WL16(st->codec->extradata + 2, ape->compressiontype); + AV_WL16(st->codec->extradata + 4, ape->formatflags); + + pts = 0; + for (i = 0; i < ape->totalframes; i++) { + ape->frames[i].pts = pts; + av_add_index_entry(st, ape->frames[i].pos, ape->frames[i].pts, 0, 0, AVINDEX_KEYFRAME); + pts += ape->blocksperframe / MAC_SUBFRAME_SIZE; + } + + return 0; +} +",1,"static int ape_read_header(AVFormatContext * s, AVFormatParameters * ap) +{ + AVIOContext *pb = s->pb; + APEContext *ape = s->priv_data; + AVStream *st; + uint32_t tag; + int i; + int total_blocks; + int64_t pts; + + /* TODO: Skip any leading junk such as id3v2 tags */ + ape->junklength = 0; + + tag = avio_rl32(pb); + if (tag != MKTAG('M', 'A', 'C', ' ')) + return -1; + + ape->fileversion = avio_rl16(pb); + + if (ape->fileversion < APE_MIN_VERSION || ape->fileversion > APE_MAX_VERSION) { + av_log(s, AV_LOG_ERROR, ""Unsupported file version - %d.%02d\n"", ape->fileversion / 1000, (ape->fileversion % 1000) / 10); + return -1; + } + + if (ape->fileversion >= 3980) { + ape->padding1 = avio_rl16(pb); + ape->descriptorlength = avio_rl32(pb); + ape->headerlength = avio_rl32(pb); + ape->seektablelength = avio_rl32(pb); + ape->wavheaderlength = avio_rl32(pb); + ape->audiodatalength = avio_rl32(pb); + ape->audiodatalength_high = avio_rl32(pb); + ape->wavtaillength = avio_rl32(pb); + avio_read(pb, ape->md5, 16); + + /* Skip any unknown bytes at the end of the descriptor. + This is for future compatibility */ + if (ape->descriptorlength > 52) + avio_seek(pb, ape->descriptorlength - 52, SEEK_CUR); + + /* Read header data */ + ape->compressiontype = avio_rl16(pb); + ape->formatflags = avio_rl16(pb); + ape->blocksperframe = avio_rl32(pb); + ape->finalframeblocks = avio_rl32(pb); + ape->totalframes = avio_rl32(pb); + ape->bps = avio_rl16(pb); + ape->channels = avio_rl16(pb); + ape->samplerate = avio_rl32(pb); + } else { + ape->descriptorlength = 0; + ape->headerlength = 32; + + ape->compressiontype = avio_rl16(pb); + ape->formatflags = avio_rl16(pb); + ape->channels = avio_rl16(pb); + ape->samplerate = avio_rl32(pb); + ape->wavheaderlength = avio_rl32(pb); + ape->wavtaillength = avio_rl32(pb); + ape->totalframes = avio_rl32(pb); + ape->finalframeblocks = avio_rl32(pb); + + if (ape->formatflags & MAC_FORMAT_FLAG_HAS_PEAK_LEVEL) { + avio_seek(pb, 4, SEEK_CUR); /* Skip the peak level */ + ape->headerlength += 4; + } + + if (ape->formatflags & MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS) { + ape->seektablelength = avio_rl32(pb); + ape->headerlength += 4; + ape->seektablelength *= sizeof(int32_t); + } else + ape->seektablelength = ape->totalframes * sizeof(int32_t); + + if (ape->formatflags & MAC_FORMAT_FLAG_8_BIT) + ape->bps = 8; + else if (ape->formatflags & MAC_FORMAT_FLAG_24_BIT) + ape->bps = 24; + else + ape->bps = 16; + + if (ape->fileversion >= 3950) + ape->blocksperframe = 73728 * 4; + else if (ape->fileversion >= 3900 || (ape->fileversion >= 3800 && ape->compressiontype >= 4000)) + ape->blocksperframe = 73728; + else + ape->blocksperframe = 9216; + + /* Skip any stored wav header */ + if (!(ape->formatflags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER)) + avio_seek(pb, ape->wavheaderlength, SEEK_CUR); + } + + if(!ape->totalframes){ + av_log(s, AV_LOG_ERROR, ""No frames in the file!\n""); + return AVERROR(EINVAL); + } + if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){ + av_log(s, AV_LOG_ERROR, ""Too many frames: %d\n"", ape->totalframes); + return -1; + } + ape->frames = av_malloc(ape->totalframes * sizeof(APEFrame)); + if(!ape->frames) + return AVERROR(ENOMEM); + ape->firstframe = ape->junklength + ape->descriptorlength + ape->headerlength + ape->seektablelength + ape->wavheaderlength; + ape->currentframe = 0; + + + ape->totalsamples = ape->finalframeblocks; + if (ape->totalframes > 1) + ape->totalsamples += ape->blocksperframe * (ape->totalframes - 1); + + if (ape->seektablelength > 0) { + ape->seektable = av_malloc(ape->seektablelength); + for (i = 0; i < ape->seektablelength / sizeof(uint32_t); i++) + ape->seektable[i] = avio_rl32(pb); + } + + ape->frames[0].pos = ape->firstframe; + ape->frames[0].nblocks = ape->blocksperframe; + ape->frames[0].skip = 0; + for (i = 1; i < ape->totalframes; i++) { + ape->frames[i].pos = ape->seektable[i]; //ape->frames[i-1].pos + ape->blocksperframe; + ape->frames[i].nblocks = ape->blocksperframe; + ape->frames[i - 1].size = ape->frames[i].pos - ape->frames[i - 1].pos; + ape->frames[i].skip = (ape->frames[i].pos - ape->frames[0].pos) & 3; + } + ape->frames[ape->totalframes - 1].size = ape->finalframeblocks * 4; + ape->frames[ape->totalframes - 1].nblocks = ape->finalframeblocks; + + for (i = 0; i < ape->totalframes; i++) { + if(ape->frames[i].skip){ + ape->frames[i].pos -= ape->frames[i].skip; + ape->frames[i].size += ape->frames[i].skip; + } + ape->frames[i].size = (ape->frames[i].size + 3) & ~3; + } + + + ape_dumpinfo(s, ape); + + /* try to read APE tags */ + if (!url_is_streamed(pb)) { + ff_ape_parse_tag(s); + avio_seek(pb, 0, SEEK_SET); + } + + av_log(s, AV_LOG_DEBUG, ""Decoding file - v%d.%02d, compression level %d\n"", ape->fileversion / 1000, (ape->fileversion % 1000) / 10, ape->compressiontype); + + /* now we are ready: build format streams */ + st = av_new_stream(s, 0); + if (!st) + return -1; + + total_blocks = (ape->totalframes == 0) ? 0 : ((ape->totalframes - 1) * ape->blocksperframe) + ape->finalframeblocks; + + st->codec->codec_type = AVMEDIA_TYPE_AUDIO; + st->codec->codec_id = CODEC_ID_APE; + st->codec->codec_tag = MKTAG('A', 'P', 'E', ' '); + st->codec->channels = ape->channels; + st->codec->sample_rate = ape->samplerate; + st->codec->bits_per_coded_sample = ape->bps; + st->codec->frame_size = MAC_SUBFRAME_SIZE; + + st->nb_frames = ape->totalframes; + st->start_time = 0; + st->duration = total_blocks / MAC_SUBFRAME_SIZE; + av_set_pts_info(st, 64, MAC_SUBFRAME_SIZE, ape->samplerate); + + st->codec->extradata = av_malloc(APE_EXTRADATA_SIZE); + st->codec->extradata_size = APE_EXTRADATA_SIZE; + AV_WL16(st->codec->extradata + 0, ape->fileversion); + AV_WL16(st->codec->extradata + 2, ape->compressiontype); + AV_WL16(st->codec->extradata + 4, ape->formatflags); + + pts = 0; + for (i = 0; i < ape->totalframes; i++) { + ape->frames[i].pts = pts; + av_add_index_entry(st, ape->frames[i].pos, ape->frames[i].pts, 0, 0, AVINDEX_KEYFRAME); + pts += ape->blocksperframe / MAC_SUBFRAME_SIZE; + } + + return 0; +} +","@@ -242,6 +242,10 @@ static int ape_read_header(AVFormatContext * s, AVFormatParameters * ap) + avio_seek(pb, ape->wavheaderlength, SEEK_CUR); + } + ++ if(!ape->totalframes){ ++ av_log(s, AV_LOG_ERROR, ""No frames in the file!\n""); ++ return AVERROR(EINVAL); ++ } + if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){ + av_log(s, AV_LOG_ERROR, ""Too many frames: %d\n"", ape->totalframes); + return -1;",2073,2404,4096 +18723,"xsltStylePreCompute(xsltStylesheetPtr style, xmlNodePtr inst) { + /* + * URGENT TODO: Normally inst->psvi Should never be reserved here, + * BUT: since if we include the same stylesheet from + * multiple imports, then the stylesheet will be parsed + * again. We simply must not try to compute the stylesheet again. + * TODO: Get to the point where we don't need to query the + * namespace- and local-name of the node, but can evaluate this + * using cctxt->style->inode->category; + */ + if ((inst == NULL) || (inst->type != XML_ELEMENT_NODE) || + (inst->psvi != NULL)) + return; + + if (IS_XSLT_ELEM(inst)) { + xsltStylePreCompPtr cur; + + if (IS_XSLT_NAME(inst, ""apply-templates"")) { + xsltCheckInstructionElement(style, inst); + xsltApplyTemplatesComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""with-param"")) { + xsltCheckParentElement(style, inst, BAD_CAST ""apply-templates"", + BAD_CAST ""call-template""); + xsltWithParamComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""value-of"")) { + xsltCheckInstructionElement(style, inst); + xsltValueOfComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""copy"")) { + xsltCheckInstructionElement(style, inst); + xsltCopyComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""copy-of"")) { + xsltCheckInstructionElement(style, inst); + xsltCopyOfComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""if"")) { + xsltCheckInstructionElement(style, inst); + xsltIfComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""when"")) { + xsltCheckParentElement(style, inst, BAD_CAST ""choose"", NULL); + xsltWhenComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""choose"")) { + xsltCheckInstructionElement(style, inst); + xsltChooseComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""for-each"")) { + xsltCheckInstructionElement(style, inst); + xsltForEachComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""apply-imports"")) { + xsltCheckInstructionElement(style, inst); + xsltApplyImportsComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""attribute"")) { + xmlNodePtr parent = inst->parent; + + if ((parent == NULL) || (parent->ns == NULL) || + ((parent->ns != inst->ns) && + (!xmlStrEqual(parent->ns->href, inst->ns->href))) || + (!xmlStrEqual(parent->name, BAD_CAST ""attribute-set""))) { + xsltCheckInstructionElement(style, inst); + } + xsltAttributeComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""element"")) { + xsltCheckInstructionElement(style, inst); + xsltElementComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""text"")) { + xsltCheckInstructionElement(style, inst); + xsltTextComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""sort"")) { + xsltCheckParentElement(style, inst, BAD_CAST ""apply-templates"", + BAD_CAST ""for-each""); + xsltSortComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""comment"")) { + xsltCheckInstructionElement(style, inst); + xsltCommentComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""number"")) { + xsltCheckInstructionElement(style, inst); + xsltNumberComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""processing-instruction"")) { + xsltCheckInstructionElement(style, inst); + xsltProcessingInstructionComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""call-template"")) { + xsltCheckInstructionElement(style, inst); + xsltCallTemplateComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""param"")) { + if (xsltCheckTopLevelElement(style, inst, 0) == 0) + xsltCheckInstructionElement(style, inst); + xsltParamComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""variable"")) { + if (xsltCheckTopLevelElement(style, inst, 0) == 0) + xsltCheckInstructionElement(style, inst); + xsltVariableComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""otherwise"")) { + xsltCheckParentElement(style, inst, BAD_CAST ""choose"", NULL); + xsltCheckInstructionElement(style, inst); + return; + } else if (IS_XSLT_NAME(inst, ""template"")) { + xsltCheckTopLevelElement(style, inst, 1); + return; + } else if (IS_XSLT_NAME(inst, ""output"")) { + xsltCheckTopLevelElement(style, inst, 1); + return; + } else if (IS_XSLT_NAME(inst, ""preserve-space"")) { + xsltCheckTopLevelElement(style, inst, 1); + return; + } else if (IS_XSLT_NAME(inst, ""strip-space"")) { + xsltCheckTopLevelElement(style, inst, 1); + return; + } else if ((IS_XSLT_NAME(inst, ""stylesheet"")) || + (IS_XSLT_NAME(inst, ""transform""))) { + xmlNodePtr parent = inst->parent; + + if ((parent == NULL) || (parent->type != XML_DOCUMENT_NODE)) { + xsltTransformError(NULL, style, inst, + ""element %s only allowed only as root element\n"", + inst->name); + style->errors++; + } + return; + } else if (IS_XSLT_NAME(inst, ""key"")) { + xsltCheckTopLevelElement(style, inst, 1); + return; + } else if (IS_XSLT_NAME(inst, ""message"")) { + xsltCheckInstructionElement(style, inst); + return; + } else if (IS_XSLT_NAME(inst, ""attribute-set"")) { + xsltCheckTopLevelElement(style, inst, 1); + return; + } else if (IS_XSLT_NAME(inst, ""namespace-alias"")) { + xsltCheckTopLevelElement(style, inst, 1); + return; + } else if (IS_XSLT_NAME(inst, ""include"")) { + xsltCheckTopLevelElement(style, inst, 1); + return; + } else if (IS_XSLT_NAME(inst, ""import"")) { + xsltCheckTopLevelElement(style, inst, 1); + return; + } else if (IS_XSLT_NAME(inst, ""decimal-format"")) { + xsltCheckTopLevelElement(style, inst, 1); + return; + } else if (IS_XSLT_NAME(inst, ""fallback"")) { + xsltCheckInstructionElement(style, inst); + return; + } else if (IS_XSLT_NAME(inst, ""document"")) { + xsltCheckInstructionElement(style, inst); + inst->psvi = (void *) xsltDocumentComp(style, inst, + (xsltTransformFunction) xsltDocumentElem); + } else { + xsltTransformError(NULL, style, inst, + ""xsltStylePreCompute: unknown xsl:%s\n"", inst->name); + if (style != NULL) style->warnings++; + } + + cur = (xsltStylePreCompPtr) inst->psvi; + /* + * A ns-list is build for every XSLT item in the + * node-tree. This is needed for XPath expressions. + */ + if (cur != NULL) { + int i = 0; + + cur->nsList = xmlGetNsList(inst->doc, inst); + if (cur->nsList != NULL) { + while (cur->nsList[i] != NULL) + i++; + } + cur->nsNr = i; + } + } else { + inst->psvi = + (void *) xsltPreComputeExtModuleElement(style, inst); + + /* + * Unknown element, maybe registered at the context + * level. Mark it for later recognition. + */ + if (inst->psvi == NULL) + inst->psvi = (void *) xsltExtMarker; + } +} +",1,"xsltStylePreCompute(xsltStylesheetPtr style, xmlNodePtr inst) { + /* + * URGENT TODO: Normally inst->psvi Should never be reserved here, + * BUT: since if we include the same stylesheet from + * multiple imports, then the stylesheet will be parsed + * again. We simply must not try to compute the stylesheet again. + * TODO: Get to the point where we don't need to query the + * namespace- and local-name of the node, but can evaluate this + * using cctxt->style->inode->category; + */ + if ((inst == NULL) || (inst->type != XML_ELEMENT_NODE) || + (inst->psvi != NULL)) + return; + + if (IS_XSLT_ELEM(inst)) { + xsltStylePreCompPtr cur; + + if (IS_XSLT_NAME(inst, ""apply-templates"")) { + xsltCheckInstructionElement(style, inst); + xsltApplyTemplatesComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""with-param"")) { + xsltCheckParentElement(style, inst, BAD_CAST ""apply-templates"", + BAD_CAST ""call-template""); + xsltWithParamComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""value-of"")) { + xsltCheckInstructionElement(style, inst); + xsltValueOfComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""copy"")) { + xsltCheckInstructionElement(style, inst); + xsltCopyComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""copy-of"")) { + xsltCheckInstructionElement(style, inst); + xsltCopyOfComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""if"")) { + xsltCheckInstructionElement(style, inst); + xsltIfComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""when"")) { + xsltCheckParentElement(style, inst, BAD_CAST ""choose"", NULL); + xsltWhenComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""choose"")) { + xsltCheckInstructionElement(style, inst); + xsltChooseComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""for-each"")) { + xsltCheckInstructionElement(style, inst); + xsltForEachComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""apply-imports"")) { + xsltCheckInstructionElement(style, inst); + xsltApplyImportsComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""attribute"")) { + xmlNodePtr parent = inst->parent; + + if ((parent == NULL) || + (parent->type != XML_ELEMENT_NODE) || (parent->ns == NULL) || + ((parent->ns != inst->ns) && + (!xmlStrEqual(parent->ns->href, inst->ns->href))) || + (!xmlStrEqual(parent->name, BAD_CAST ""attribute-set""))) { + xsltCheckInstructionElement(style, inst); + } + xsltAttributeComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""element"")) { + xsltCheckInstructionElement(style, inst); + xsltElementComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""text"")) { + xsltCheckInstructionElement(style, inst); + xsltTextComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""sort"")) { + xsltCheckParentElement(style, inst, BAD_CAST ""apply-templates"", + BAD_CAST ""for-each""); + xsltSortComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""comment"")) { + xsltCheckInstructionElement(style, inst); + xsltCommentComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""number"")) { + xsltCheckInstructionElement(style, inst); + xsltNumberComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""processing-instruction"")) { + xsltCheckInstructionElement(style, inst); + xsltProcessingInstructionComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""call-template"")) { + xsltCheckInstructionElement(style, inst); + xsltCallTemplateComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""param"")) { + if (xsltCheckTopLevelElement(style, inst, 0) == 0) + xsltCheckInstructionElement(style, inst); + xsltParamComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""variable"")) { + if (xsltCheckTopLevelElement(style, inst, 0) == 0) + xsltCheckInstructionElement(style, inst); + xsltVariableComp(style, inst); + } else if (IS_XSLT_NAME(inst, ""otherwise"")) { + xsltCheckParentElement(style, inst, BAD_CAST ""choose"", NULL); + xsltCheckInstructionElement(style, inst); + return; + } else if (IS_XSLT_NAME(inst, ""template"")) { + xsltCheckTopLevelElement(style, inst, 1); + return; + } else if (IS_XSLT_NAME(inst, ""output"")) { + xsltCheckTopLevelElement(style, inst, 1); + return; + } else if (IS_XSLT_NAME(inst, ""preserve-space"")) { + xsltCheckTopLevelElement(style, inst, 1); + return; + } else if (IS_XSLT_NAME(inst, ""strip-space"")) { + xsltCheckTopLevelElement(style, inst, 1); + return; + } else if ((IS_XSLT_NAME(inst, ""stylesheet"")) || + (IS_XSLT_NAME(inst, ""transform""))) { + xmlNodePtr parent = inst->parent; + + if ((parent == NULL) || (parent->type != XML_DOCUMENT_NODE)) { + xsltTransformError(NULL, style, inst, + ""element %s only allowed only as root element\n"", + inst->name); + style->errors++; + } + return; + } else if (IS_XSLT_NAME(inst, ""key"")) { + xsltCheckTopLevelElement(style, inst, 1); + return; + } else if (IS_XSLT_NAME(inst, ""message"")) { + xsltCheckInstructionElement(style, inst); + return; + } else if (IS_XSLT_NAME(inst, ""attribute-set"")) { + xsltCheckTopLevelElement(style, inst, 1); + return; + } else if (IS_XSLT_NAME(inst, ""namespace-alias"")) { + xsltCheckTopLevelElement(style, inst, 1); + return; + } else if (IS_XSLT_NAME(inst, ""include"")) { + xsltCheckTopLevelElement(style, inst, 1); + return; + } else if (IS_XSLT_NAME(inst, ""import"")) { + xsltCheckTopLevelElement(style, inst, 1); + return; + } else if (IS_XSLT_NAME(inst, ""decimal-format"")) { + xsltCheckTopLevelElement(style, inst, 1); + return; + } else if (IS_XSLT_NAME(inst, ""fallback"")) { + xsltCheckInstructionElement(style, inst); + return; + } else if (IS_XSLT_NAME(inst, ""document"")) { + xsltCheckInstructionElement(style, inst); + inst->psvi = (void *) xsltDocumentComp(style, inst, + (xsltTransformFunction) xsltDocumentElem); + } else { + xsltTransformError(NULL, style, inst, + ""xsltStylePreCompute: unknown xsl:%s\n"", inst->name); + if (style != NULL) style->warnings++; + } + + cur = (xsltStylePreCompPtr) inst->psvi; + /* + * A ns-list is build for every XSLT item in the + * node-tree. This is needed for XPath expressions. + */ + if (cur != NULL) { + int i = 0; + + cur->nsList = xmlGetNsList(inst->doc, inst); + if (cur->nsList != NULL) { + while (cur->nsList[i] != NULL) + i++; + } + cur->nsNr = i; + } + } else { + inst->psvi = + (void *) xsltPreComputeExtModuleElement(style, inst); + + /* + * Unknown element, maybe registered at the context + * level. Mark it for later recognition. + */ + if (inst->psvi == NULL) + inst->psvi = (void *) xsltExtMarker; + } +} +","@@ -949,6 +949,8 @@ xsltElementComp(xsltStylesheetPtr style, xmlNodePtr inst) { + #ifdef XSLT_REFACTORED + comp->nsPrefix = prefix; + comp->name = name; ++#else ++ (void)name; /* Suppress unused variable warning. */ + #endif + } else if (prefix != NULL) { + xsltTransformError(NULL, style, inst, +@@ -1074,6 +1076,8 @@ xsltAttributeComp(xsltStylesheetPtr style, xmlNodePtr inst) { + #ifdef XSLT_REFACTORED + comp->nsPrefix = prefix; + comp->name = name; ++#else ++ (void)name; /* Suppress unused variable warning. */ + #endif + } else { + xsltTransformError(NULL, style, inst, +@@ -1301,7 +1305,8 @@ xsltGetQNameProperty(xsltStylesheetPtr style, xmlNodePtr inst, + if (prop == NULL) { + style->errors++; + } else { +- *localName = prop; ++ if (localName) ++ *localName = prop; + if (hasProp) + *hasProp = 1; + if (URI != NULL) { +@@ -2245,7 +2250,8 @@ xsltStylePreCompute(xsltStylesheetPtr style, xmlNodePtr inst) { + } else if (IS_XSLT_NAME(inst, ""attribute"")) { + xmlNodePtr parent = inst->parent; + +- if ((parent == NULL) || (parent->ns == NULL) || ++ if ((parent == NULL) || ++ (parent->type != XML_ELEMENT_NODE) || (parent->ns == NULL) || + ((parent->ns != inst->ns) && + (!xmlStrEqual(parent->ns->href, inst->ns->href))) || + (!xmlStrEqual(parent->name, BAD_CAST ""attribute-set""))) {",1878,2209,4096 +18373,"void MigrationTest::SetUpVersion74Database() { + sql::Connection connection; + ASSERT_TRUE(connection.Open(GetDatabasePath())); + ASSERT_TRUE(connection.BeginTransaction()); + ASSERT_TRUE(connection.Execute( + ""CREATE TABLE share_version (id VARCHAR(128) primary key, data INT);"" + ""INSERT INTO 'share_version' VALUES('nick@chromium.org',74);"" + ""CREATE TABLE models (model_id BLOB primary key, last_download_timestamp"" + "" INT, initial_sync_ended BOOLEAN default 0);"" + ""INSERT INTO 'models' VALUES(X'C2881000',694,1);"" + ""CREATE TABLE 'share_info' (id TEXT primary key, name TEXT, store_birthd"" + ""ay TEXT, db_create_version TEXT, db_create_time INT, next_id INT de"" + ""fault -2, cache_guid TEXT , notification_state BLOB, autofill_migra"" + ""tion_state INT default 0, bookmarks_added_during_autofill_migration"" + "" INT default 0, autofill_migration_time INT default 0, autofill_ent"" + ""ries_added_during_migration INT default 0, autofill_profiles_added_"" + ""during_migration INT default 0);"" + ""INSERT INTO 'share_info' VALUES('nick@chromium.org','nick@chromium.org'"" + "",'c27e9f59-08ca-46f8-b0cc-f16a2ed778bb','Unknown',1263522064,-65542"" + "",'9010788312004066376x-6609234393368420856x',NULL,0,0,0,0,0);"" + ""CREATE TABLE 'metas'(metahandle bigint primary key ON CONFLICT FAIL,bas"" + ""e_version bigint default -1,server_version bigint default 0,mtime b"" + ""igint default 0,server_mtime bigint default 0,ctime bigint default "" + ""0,server_ctime bigint default 0,server_position_in_parent bigint de"" + ""fault 0,local_external_id bigint default 0,id varchar(255) default "" + ""'r',parent_id varchar(255) default 'r',server_parent_id varchar(255"" + "") default 'r',prev_id varchar(255) default 'r',next_id varchar(255)"" + "" default 'r',is_unsynced bit default 0,is_unapplied_update bit defa"" + ""ult 0,is_del bit default 0,is_dir bit default 0,server_is_dir bit d"" + ""efault 0,server_is_del bit default 0,non_unique_name varchar,server"" + ""_non_unique_name varchar(255),unique_server_tag varchar,unique_clie"" + ""nt_tag varchar,specifics blob,server_specifics blob);"" + ""INSERT INTO 'metas' VALUES(1,-1,0,"" LEGACY_PROTO_TIME_VALS(1) + "",0,0,'r','r','r','r','r',0,0,0,1,0,0,NULL,NULL,NULL,NULL,X'',X'"" + ""');"" + ""INSERT INTO 'metas' VALUES(2,669,669,"" LEGACY_PROTO_TIME_VALS(2) + "",-2097152,4,'s_ID_2','s_ID"" + ""_9','s_ID_9','s_ID_2','s_ID_2',0,0,1,0,0,1,'Deleted Item','Deleted "" + ""Item',NULL,NULL,X'C28810220A16687474703A2F2F7777772E676F6F676C652E6"" + ""36F6D2F12084141534741534741',X'C28810260A17687474703A2F2F7777772E67"" + ""6F6F676C652E636F6D2F32120B4153414447414447414447');"" + ""INSERT INTO 'metas' VALUES(4,681,681,"" LEGACY_PROTO_TIME_VALS(4) + "",-3145728,3,'s_ID_4','s_ID"" + ""_9','s_ID_9','s_ID_4','s_ID_4',0,0,1,0,0,1,'Welcome to Chromium','W"" + ""elcome to Chromium',NULL,NULL,X'C28810350A31687474703A2F2F7777772E6"" + ""76F6F676C652E636F6D2F6368726F6D652F696E746C2F656E2F77656C636F6D652E"" + ""68746D6C1200',X'C28810350A31687474703A2F2F7777772E676F6F676C652E636"" + ""F6D2F6368726F6D652F696E746C2F656E2F77656C636F6D652E68746D6C1200');"" + ""INSERT INTO 'metas' VALUES(5,677,677,"" LEGACY_PROTO_TIME_VALS(5) + "",1048576,7,'s_ID_5','s_ID_"" + ""9','s_ID_9','s_ID_5','s_ID_5',0,0,1,0,0,1,'Google','Google',NULL,NU"" + ""LL,X'C28810220A16687474703A2F2F7777772E676F6F676C652E636F6D2F120841"" + ""47415347415347',X'C28810220A16687474703A2F2F7777772E676F6F676C652E6"" + ""36F6D2F12084147464447415347');"" + ""INSERT INTO 'metas' VALUES(6,694,694,"" LEGACY_PROTO_TIME_VALS(6) + "",-4194304,6,'s_ID_6','s_ID"" + ""_9','s_ID_9','r','r',0,0,0,1,1,0,'The Internet','The Internet',NULL"" + "",NULL,X'C2881000',X'C2881000');"" + ""INSERT INTO 'metas' VALUES(7,663,663,"" LEGACY_PROTO_TIME_VALS(7) + "",1048576,0,'s_ID_7','r','r"" + ""','r','r',0,0,0,1,1,0,'Google Chrome','Google Chrome','google_chrom"" + ""e',NULL,NULL,NULL);"" + ""INSERT INTO 'metas' VALUES(8,664,664,"" LEGACY_PROTO_TIME_VALS(8) + "",1048576,0,'s_ID_8','s_ID_"" + ""7','s_ID_7','r','r',0,0,0,1,1,0,'Bookmarks','Bookmarks','google_chr"" + ""ome_bookmarks',NULL,X'C2881000',X'C2881000');"" + ""INSERT INTO 'metas' VALUES(9,665,665,"" LEGACY_PROTO_TIME_VALS(9) + "",1048576,1,'s_ID_9','s_ID_"" + ""8','s_ID_8','r','s_ID_10',0,0,0,1,1,0,'Bookmark Bar','Bookmark Bar'"" + "",'bookmark_bar',NULL,X'C2881000',X'C2881000');"" + ""INSERT INTO 'metas' VALUES(10,666,666,"" LEGACY_PROTO_TIME_VALS(10) + "",2097152,2,'s_ID_10','s_I"" + ""D_8','s_ID_8','s_ID_9','r',0,0,0,1,1,0,'Other Bookmarks','Other Boo"" + ""kmarks','other_bookmarks',NULL,X'C2881000',X'C2881000');"" + ""INSERT INTO 'metas' VALUES(11,683,683,"" LEGACY_PROTO_TIME_VALS(11) + "",-1048576,8,'s_ID_11','s_"" + ""ID_6','s_ID_6','r','s_ID_13',0,0,0,0,0,0,'Home (The Chromium Projec"" + ""ts)','Home (The Chromium Projects)',NULL,NULL,X'C28810220A186874747"" + ""03A2F2F6465762E6368726F6D69756D2E6F72672F1206414741545741',X'C28810"" + ""290A1D687474703A2F2F6465762E6368726F6D69756D2E6F72672F6F74686572120"" + ""84146414756415346');"" + ""INSERT INTO 'metas' VALUES(12,685,685,"" LEGACY_PROTO_TIME_VALS(12) + "",0,9,'s_ID_12','s_ID_6','"" + ""s_ID_6','s_ID_13','s_ID_14',0,0,0,1,1,0,'Extra Bookmarks','Extra Bo"" + ""okmarks',NULL,NULL,X'C2881000',X'C2881000');"" + ""INSERT INTO 'metas' VALUES(13,687,687,"" LEGACY_PROTO_TIME_VALS(13) + "",-917504,10,'s_ID_13','s_"" + ""ID_6','s_ID_6','s_ID_11','s_ID_12',0,0,0,0,0,0,'ICANN | Internet Co"" + ""rporation for Assigned Names and Numbers','ICANN | Internet Corpora"" + ""tion for Assigned Names and Numbers',NULL,NULL,X'C28810240A15687474"" + ""703A2F2F7777772E6963616E6E2E636F6D2F120B504E474158463041414646',X'C"" + ""28810200A15687474703A2F2F7777772E6963616E6E2E636F6D2F12074441414641"" + ""5346');"" + ""INSERT INTO 'metas' VALUES(14,692,692,"" LEGACY_PROTO_TIME_VALS(14) + "",1048576,11,'s_ID_14','s_"" + ""ID_6','s_ID_6','s_ID_12','r',0,0,0,0,0,0,'The WebKit Open Source Pr"" + ""oject','The WebKit Open Source Project',NULL,NULL,X'C288101A0A12687"" + ""474703A2F2F7765626B69742E6F72672F1204504E4758',X'C288101C0A13687474"" + ""703A2F2F7765626B69742E6F72672F781205504E473259');"" + )); + ASSERT_TRUE(connection.CommitTransaction()); +} +",1,"void MigrationTest::SetUpVersion74Database() { + sql::Connection connection; + ASSERT_TRUE(connection.Open(GetDatabasePath())); + ASSERT_TRUE(connection.BeginTransaction()); + ASSERT_TRUE(connection.Execute( + ""CREATE TABLE share_version (id VARCHAR(128) primary key, data INT);"" + ""INSERT INTO 'share_version' VALUES('nick@chromium.org',74);"" + ""CREATE TABLE models (model_id BLOB primary key, last_download_timestamp"" + "" INT, initial_sync_ended BOOLEAN default 0);"" + ""INSERT INTO 'models' VALUES(X'C2881000',694,1);"" + ""CREATE TABLE 'share_info' (id TEXT primary key, name TEXT, store_birthd"" + ""ay TEXT, db_create_version TEXT, db_create_time INT, next_id INT de"" + ""fault -2, cache_guid TEXT , notification_state BLOB, autofill_migra"" + ""tion_state INT default 0, bookmarks_added_during_autofill_migration"" + "" INT default 0, autofill_migration_time INT default 0, autofill_ent"" + ""ries_added_during_migration INT default 0, autofill_profiles_added_"" + ""during_migration INT default 0);"" + ""INSERT INTO 'share_info' VALUES('nick@chromium.org','nick@chromium.org'"" + "",'c27e9f59-08ca-46f8-b0cc-f16a2ed778bb','Unknown',1263522064,-65542"" + "",'9010788312004066376x-6609234393368420856x',NULL,0,0,0,0,0);"" + ""CREATE TABLE 'metas'(metahandle bigint primary key ON CONFLICT FAIL,bas"" + ""e_version bigint default -1,server_version bigint default 0,mtime b"" + ""igint default 0,server_mtime bigint default 0,ctime bigint default "" + ""0,server_ctime bigint default 0,server_position_in_parent bigint de"" + ""fault 0,local_external_id bigint default 0,id varchar(255) default "" + ""'r',parent_id varchar(255) default 'r',server_parent_id varchar(255"" + "") default 'r',prev_id varchar(255) default 'r',next_id varchar(255)"" + "" default 'r',is_unsynced bit default 0,is_unapplied_update bit defa"" + ""ult 0,is_del bit default 0,is_dir bit default 0,server_is_dir bit d"" + ""efault 0,server_is_del bit default 0,non_unique_name varchar,server"" + ""_non_unique_name varchar(255),unique_server_tag varchar,unique_clie"" + ""nt_tag varchar,specifics blob,server_specifics blob);"" + ""INSERT INTO 'metas' VALUES(1,-1,0,129079956640320000,0,1290799566403200"" + ""00,0,0,0,'r','r','r','r','r',0,0,0,1,0,0,NULL,NULL,NULL,NULL,X'',X'"" + ""');"" + ""INSERT INTO 'metas' VALUES(2,669,669,128976886618480000,128976886618480"" + ""000,128976886618480000,128976886618480000,-2097152,4,'s_ID_2','s_ID"" + ""_9','s_ID_9','s_ID_2','s_ID_2',0,0,1,0,0,1,'Deleted Item','Deleted "" + ""Item',NULL,NULL,X'C28810220A16687474703A2F2F7777772E676F6F676C652E6"" + ""36F6D2F12084141534741534741',X'C28810260A17687474703A2F2F7777772E67"" + ""6F6F676C652E636F6D2F32120B4153414447414447414447');"" + ""INSERT INTO 'metas' VALUES(4,681,681,129002163642690000,129002163642690"" + ""000,129002163642690000,129002163642690000,-3145728,3,'s_ID_4','s_ID"" + ""_9','s_ID_9','s_ID_4','s_ID_4',0,0,1,0,0,1,'Welcome to Chromium','W"" + ""elcome to Chromium',NULL,NULL,X'C28810350A31687474703A2F2F7777772E6"" + ""76F6F676C652E636F6D2F6368726F6D652F696E746C2F656E2F77656C636F6D652E"" + ""68746D6C1200',X'C28810350A31687474703A2F2F7777772E676F6F676C652E636"" + ""F6D2F6368726F6D652F696E746C2F656E2F77656C636F6D652E68746D6C1200');"" + ""INSERT INTO 'metas' VALUES(5,677,677,129001555500000000,129001555500000"" + ""000,129001555500000000,129001555500000000,1048576,7,'s_ID_5','s_ID_"" + ""9','s_ID_9','s_ID_5','s_ID_5',0,0,1,0,0,1,'Google','Google',NULL,NU"" + ""LL,X'C28810220A16687474703A2F2F7777772E676F6F676C652E636F6D2F120841"" + ""47415347415347',X'C28810220A16687474703A2F2F7777772E676F6F676C652E6"" + ""36F6D2F12084147464447415347');"" + ""INSERT INTO 'metas' VALUES(6,694,694,129053976170000000,129053976170000"" + ""000,129053976170000000,129053976170000000,-4194304,6,'s_ID_6','s_ID"" + ""_9','s_ID_9','r','r',0,0,0,1,1,0,'The Internet','The Internet',NULL"" + "",NULL,X'C2881000',X'C2881000');"" + ""INSERT INTO 'metas' VALUES(7,663,663,128976864758480000,128976864758480"" + ""000,128976864758480000,128976864758480000,1048576,0,'s_ID_7','r','r"" + ""','r','r',0,0,0,1,1,0,'Google Chrome','Google Chrome','google_chrom"" + ""e',NULL,NULL,NULL);"" + ""INSERT INTO 'metas' VALUES(8,664,664,128976864758480000,128976864758480"" + ""000,128976864758480000,128976864758480000,1048576,0,'s_ID_8','s_ID_"" + ""7','s_ID_7','r','r',0,0,0,1,1,0,'Bookmarks','Bookmarks','google_chr"" + ""ome_bookmarks',NULL,X'C2881000',X'C2881000');"" + ""INSERT INTO 'metas' VALUES(9,665,665,128976864758480000,128976864758480"" + ""000,128976864758480000,128976864758480000,1048576,1,'s_ID_9','s_ID_"" + ""8','s_ID_8','r','s_ID_10',0,0,0,1,1,0,'Bookmark Bar','Bookmark Bar'"" + "",'bookmark_bar',NULL,X'C2881000',X'C2881000');"" + ""INSERT INTO 'metas' VALUES(10,666,666,128976864758480000,12897686475848"" + ""0000,128976864758480000,128976864758480000,2097152,2,'s_ID_10','s_I"" + ""D_8','s_ID_8','s_ID_9','r',0,0,0,1,1,0,'Other Bookmarks','Other Boo"" + ""kmarks','other_bookmarks',NULL,X'C2881000',X'C2881000');"" + ""INSERT INTO 'metas' VALUES(11,683,683,129079956948440000,12907995694844"" + ""0000,129079956948440000,129079956948440000,-1048576,8,'s_ID_11','s_"" + ""ID_6','s_ID_6','r','s_ID_13',0,0,0,0,0,0,'Home (The Chromium Projec"" + ""ts)','Home (The Chromium Projects)',NULL,NULL,X'C28810220A186874747"" + ""03A2F2F6465762E6368726F6D69756D2E6F72672F1206414741545741',X'C28810"" + ""290A1D687474703A2F2F6465762E6368726F6D69756D2E6F72672F6F74686572120"" + ""84146414756415346');"" + ""INSERT INTO 'metas' VALUES(12,685,685,129079957513650000,12907995751365"" + ""0000,129079957513650000,129079957513650000,0,9,'s_ID_12','s_ID_6','"" + ""s_ID_6','s_ID_13','s_ID_14',0,0,0,1,1,0,'Extra Bookmarks','Extra Bo"" + ""okmarks',NULL,NULL,X'C2881000',X'C2881000');"" + ""INSERT INTO 'metas' VALUES(13,687,687,129079957985300000,12907995798530"" + ""0000,129079957985300000,129079957985300000,-917504,10,'s_ID_13','s_"" + ""ID_6','s_ID_6','s_ID_11','s_ID_12',0,0,0,0,0,0,'ICANN | Internet Co"" + ""rporation for Assigned Names and Numbers','ICANN | Internet Corpora"" + ""tion for Assigned Names and Numbers',NULL,NULL,X'C28810240A15687474"" + ""703A2F2F7777772E6963616E6E2E636F6D2F120B504E474158463041414646',X'C"" + ""28810200A15687474703A2F2F7777772E6963616E6E2E636F6D2F12074441414641"" + ""5346');"" + ""INSERT INTO 'metas' VALUES(14,692,692,129079958383000000,12907995838300"" + ""0000,129079958383000000,129079958383000000,1048576,11,'s_ID_14','s_"" + ""ID_6','s_ID_6','s_ID_12','r',0,0,0,0,0,0,'The WebKit Open Source Pr"" + ""oject','The WebKit Open Source Project',NULL,NULL,X'C288101A0A12687"" + ""474703A2F2F7765626B69742E6F72672F1204504E4758',X'C288101C0A13687474"" + ""703A2F2F7765626B69742E6F72672F781205504E473259');"" + )); + ASSERT_TRUE(connection.CommitTransaction()); +} +","@@ -18,8 +18,6 @@ + #include ""chrome/browser/sync/syncable/directory_manager.h"" + #include ""chrome/browser/sync/syncable/syncable-inl.h"" + #include ""chrome/browser/sync/syncable/syncable.h"" +-#include ""chrome/browser/sync/util/sqlite_utils.h"" +-#include ""chrome/browser/sync/util/time.h"" + #include ""sql/connection.h"" + #include ""sql/statement.h"" + #include ""testing/gtest/include/gtest/gtest-param-test.h"" +@@ -52,7 +50,6 @@ class MigrationTest : public testing::TestWithParam { + void SetUpVersion73Database(); + void SetUpVersion74Database(); + void SetUpVersion75Database(); +- void SetUpVersion76Database(); + + void SetUpCurrentDatabaseAndCheckVersion() { + SetUpVersion70Database(); // Prepopulates data. +@@ -72,227 +69,6 @@ class MigrationTest : public testing::TestWithParam { + + class DirectoryBackingStoreTest : public MigrationTest {}; + +-#if defined(OS_WIN) +- +-// On Windows, we used to store timestamps in FILETIME format. +-#define LEGACY_META_PROTO_TIMES_1 129079956640320000 +-#define LEGACY_META_PROTO_TIMES_2 128976886618480000 +-#define LEGACY_META_PROTO_TIMES_4 129002163642690000 +-#define LEGACY_META_PROTO_TIMES_5 129001555500000000 +-#define LEGACY_META_PROTO_TIMES_6 129053976170000000 +-#define LEGACY_META_PROTO_TIMES_7 128976864758480000 +-#define LEGACY_META_PROTO_TIMES_8 128976864758480000 +-#define LEGACY_META_PROTO_TIMES_9 128976864758480000 +-#define LEGACY_META_PROTO_TIMES_10 128976864758480000 +-#define LEGACY_META_PROTO_TIMES_11 129079956948440000 +-#define LEGACY_META_PROTO_TIMES_12 129079957513650000 +-#define LEGACY_META_PROTO_TIMES_13 129079957985300000 +-#define LEGACY_META_PROTO_TIMES_14 129079958383000000 +- +-// Generated via: +-// +-// ruby -ane '$F[1].sub!(""LEGACY_"", """"); $F[2] = Integer($F[2]) / 10000 - 11644473600000; print ""#{$F[0]} #{$F[1]} #{$F[2]}\n""' +-// +-// Magic numbers taken from +-// http://stackoverflow.com/questions/5398557/java-library-for-dealing-with-win32-filetime . +- +-// Now we store them in Java format (ms since the Unix epoch). +-#define META_PROTO_TIMES_1 1263522064032 +-#define META_PROTO_TIMES_2 1253215061848 +-#define META_PROTO_TIMES_4 1255742764269 +-#define META_PROTO_TIMES_5 1255681950000 +-#define META_PROTO_TIMES_6 1260924017000 +-#define META_PROTO_TIMES_7 1253212875848 +-#define META_PROTO_TIMES_8 1253212875848 +-#define META_PROTO_TIMES_9 1253212875848 +-#define META_PROTO_TIMES_10 1253212875848 +-#define META_PROTO_TIMES_11 1263522094844 +-#define META_PROTO_TIMES_12 1263522151365 +-#define META_PROTO_TIMES_13 1263522198530 +-#define META_PROTO_TIMES_14 1263522238300 +- +-#else +- +-// On other platforms, we used to store timestamps in time_t format (s +-// since the Unix epoch). +-#define LEGACY_META_PROTO_TIMES_1 1263522064 +-#define LEGACY_META_PROTO_TIMES_2 1253215061 +-#define LEGACY_META_PROTO_TIMES_4 1255742764 +-#define LEGACY_META_PROTO_TIMES_5 1255681950 +-#define LEGACY_META_PROTO_TIMES_6 1260924017 +-#define LEGACY_META_PROTO_TIMES_7 1253212875 +-#define LEGACY_META_PROTO_TIMES_8 1253212875 +-#define LEGACY_META_PROTO_TIMES_9 1253212875 +-#define LEGACY_META_PROTO_TIMES_10 1253212875 +-#define LEGACY_META_PROTO_TIMES_11 1263522094 +-#define LEGACY_META_PROTO_TIMES_12 1263522151 +-#define LEGACY_META_PROTO_TIMES_13 1263522198 +-#define LEGACY_META_PROTO_TIMES_14 1263522238 +- +-// Now we store them in Java format (ms since the Unix epoch). +-#define META_PROTO_TIMES_1 1263522064000 +-#define META_PROTO_TIMES_2 1253215061000 +-#define META_PROTO_TIMES_4 1255742764000 +-#define META_PROTO_TIMES_5 1255681950000 +-#define META_PROTO_TIMES_6 1260924017000 +-#define META_PROTO_TIMES_7 1253212875000 +-#define META_PROTO_TIMES_8 1253212875000 +-#define META_PROTO_TIMES_9 1253212875000 +-#define META_PROTO_TIMES_10 1253212875000 +-#define META_PROTO_TIMES_11 1263522094000 +-#define META_PROTO_TIMES_12 1263522151000 +-#define META_PROTO_TIMES_13 1263522198000 +-#define META_PROTO_TIMES_14 1263522238000 +- +-#endif +- +-// Helper macros for the database dumps in the SetUpVersion*Database +-// functions. +-#define LEGACY_META_PROTO_TIMES(x) LEGACY_META_PROTO_TIMES_##x +-#define META_PROTO_TIMES(x) META_PROTO_TIMES_##x +-#define STR(s) #s +-#define XSTR(s) STR(s) +-#define LEGACY_PROTO_TIME_VALS(x) \ +- XSTR(LEGACY_META_PROTO_TIMES(x)) "","" \ +- XSTR(LEGACY_META_PROTO_TIMES(x)) "","" \ +- XSTR(LEGACY_META_PROTO_TIMES(x)) "","" \ +- XSTR(LEGACY_META_PROTO_TIMES(x)) +- +-namespace { +- +-// Helper functions for testing. +- +-// Returns a map from metahandle -> expected legacy time (in proto +-// format). +-std::map GetExpectedLegacyMetaProtoTimes() { +- std::map expected_legacy_meta_proto_times; +- expected_legacy_meta_proto_times[1] = LEGACY_META_PROTO_TIMES(1); +- expected_legacy_meta_proto_times[2] = LEGACY_META_PROTO_TIMES(2); +- expected_legacy_meta_proto_times[4] = LEGACY_META_PROTO_TIMES(4); +- expected_legacy_meta_proto_times[5] = LEGACY_META_PROTO_TIMES(5); +- expected_legacy_meta_proto_times[6] = LEGACY_META_PROTO_TIMES(6); +- expected_legacy_meta_proto_times[7] = LEGACY_META_PROTO_TIMES(7); +- expected_legacy_meta_proto_times[8] = LEGACY_META_PROTO_TIMES(8); +- expected_legacy_meta_proto_times[9] = LEGACY_META_PROTO_TIMES(9); +- expected_legacy_meta_proto_times[10] = LEGACY_META_PROTO_TIMES(10); +- expected_legacy_meta_proto_times[11] = LEGACY_META_PROTO_TIMES(11); +- expected_legacy_meta_proto_times[12] = LEGACY_META_PROTO_TIMES(12); +- expected_legacy_meta_proto_times[13] = LEGACY_META_PROTO_TIMES(13); +- expected_legacy_meta_proto_times[14] = LEGACY_META_PROTO_TIMES(14); +- return expected_legacy_meta_proto_times; +-} +- +-// Returns a map from metahandle -> expected time (in proto format). +-std::map GetExpectedMetaProtoTimes() { +- std::map expected_meta_proto_times; +- expected_meta_proto_times[1] = META_PROTO_TIMES(1); +- expected_meta_proto_times[2] = META_PROTO_TIMES(2); +- expected_meta_proto_times[4] = META_PROTO_TIMES(4); +- expected_meta_proto_times[5] = META_PROTO_TIMES(5); +- expected_meta_proto_times[6] = META_PROTO_TIMES(6); +- expected_meta_proto_times[7] = META_PROTO_TIMES(7); +- expected_meta_proto_times[8] = META_PROTO_TIMES(8); +- expected_meta_proto_times[9] = META_PROTO_TIMES(9); +- expected_meta_proto_times[10] = META_PROTO_TIMES(10); +- expected_meta_proto_times[11] = META_PROTO_TIMES(11); +- expected_meta_proto_times[12] = META_PROTO_TIMES(12); +- expected_meta_proto_times[13] = META_PROTO_TIMES(13); +- expected_meta_proto_times[14] = META_PROTO_TIMES(14); +- return expected_meta_proto_times; +-} +- +-// Returns a map from metahandle -> expected time (as a Time object). +-std::map GetExpectedMetaTimes() { +- std::map expected_meta_times; +- const std::map& expected_meta_proto_times = +- GetExpectedMetaProtoTimes(); +- for (std::map::const_iterator it = +- expected_meta_proto_times.begin(); +- it != expected_meta_proto_times.end(); ++it) { +- expected_meta_times[it->first] = +- browser_sync::ProtoTimeToTime(it->second); +- } +- return expected_meta_times; +-} +- +-// Extracts a map from metahandle -> time (in proto format) from the +-// given database. +-std::map GetMetaProtoTimes(sqlite3* db_handle) { +- sqlite_utils::SQLStatement statement; +- statement.prepare( +- db_handle, +- ""SELECT metahandle, mtime, server_mtime, ctime, server_ctime FROM metas""); +- EXPECT_EQ(5, statement.column_count()); +- std::map meta_times; +- while (true) { +- int query_result = statement.step(); +- if (query_result != SQLITE_ROW) { +- EXPECT_EQ(SQLITE_DONE, query_result); +- break; +- } +- int64 metahandle = statement.column_int64(0); +- int64 mtime = statement.column_int64(1); +- int64 server_mtime = statement.column_int64(2); +- int64 ctime = statement.column_int64(3); +- int64 server_ctime = statement.column_int64(4); +- EXPECT_EQ(mtime, server_mtime); +- EXPECT_EQ(mtime, ctime); +- EXPECT_EQ(mtime, server_ctime); +- meta_times[metahandle] = mtime; +- } +- return meta_times; +-} +- +-::testing::AssertionResult AssertTimesMatch(const char* t1_expr, +- const char* t2_expr, +- const base::Time& t1, +- const base::Time& t2) { +- if (t1 == t2) +- return ::testing::AssertionSuccess(); +- +- return ::testing::AssertionFailure() +- << t1_expr << "" and "" << t2_expr +- << "" (internal values: "" << t1.ToInternalValue() +- << "" and "" << t2.ToInternalValue() +- << "") (proto time: "" << browser_sync::TimeToProtoTime(t1) +- << "" and "" << browser_sync::TimeToProtoTime(t2) +- << "") do not match""; +-} +- +-// Expect that all time fields of the given entry kernel will be the +-// given time. +-void ExpectTime(const EntryKernel& entry_kernel, +- const base::Time& expected_time) { +- EXPECT_PRED_FORMAT2(AssertTimesMatch, +- expected_time, entry_kernel.ref(CTIME)); +- EXPECT_PRED_FORMAT2(AssertTimesMatch, +- expected_time, entry_kernel.ref(SERVER_CTIME)); +- EXPECT_PRED_FORMAT2(AssertTimesMatch, +- expected_time, entry_kernel.ref(MTIME)); +- EXPECT_PRED_FORMAT2(AssertTimesMatch, +- expected_time, entry_kernel.ref(SERVER_MTIME)); +-} +- +-// Expect that all the entries in |index| have times matching those in +-// the given map (from metahandle to expect time). +-void ExpectTimes(const MetahandlesIndex& index, +- const std::map& expected_times) { +- for (MetahandlesIndex::const_iterator it = index.begin(); +- it != index.end(); ++it) { +- int64 meta_handle = (*it)->ref(META_HANDLE); +- SCOPED_TRACE(meta_handle); +- std::map::const_iterator it2 = +- expected_times.find(meta_handle); +- if (it2 == expected_times.end()) { +- ADD_FAILURE() << ""Could not find expected time for "" << meta_handle; +- continue; +- } +- ExpectTime(**it, it2->second); +- } +-} +- +-} // namespace +- + void MigrationTest::SetUpVersion67Database() { + // This is a version 67 database dump whose contents were backformed from + // the contents of the version 68 database dump (the v68 migration was +@@ -324,68 +100,68 @@ void MigrationTest::SetUpVersion67Database() { + ""bookmark_url varchar,server_bookmark_url varchar,"" + ""singleton_tag varchar,bookmark_favicon blob,"" + ""server_bookmark_favicon blob);"" +- ""INSERT INTO metas VALUES(1,-1,0,"" LEGACY_PROTO_TIME_VALS(1) +- "",0,0,'r','r','r','r','r',0,0,0,1,0,0,0,0,NULL,"" ++ ""INSERT INTO metas VALUES(1,-1,0,129079956640320000,0,"" ++ ""129079956640320000,0,0,0,'r','r','r','r','r',0,0,0,1,0,0,0,0,NULL,"" + ""NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);"" +- ""INSERT INTO metas VALUES(2,669,669,"" LEGACY_PROTO_TIME_VALS(2) +- "",-2097152,"" ++ ""INSERT INTO metas VALUES(2,669,669,128976886618480000,"" ++ ""128976886618480000,128976886618480000,128976886618480000,-2097152,"" + ""4,'s_ID_2','s_ID_9','s_ID_9','s_ID_2','s_ID_2',0,0,1,0,1,0,1,1,"" + ""'Deleted Item',NULL,'Deleted Item','Deleted Item','Deleted Item',"" + ""'http://www.google.com/','http://www.google.com/2',NULL,'AASGASGA',"" + ""'ASADGADGADG');"" +- ""INSERT INTO metas VALUES(4,681,681,"" LEGACY_PROTO_TIME_VALS(4) +- "",-3145728,"" ++ ""INSERT INTO metas VALUES(4,681,681,129002163642690000,"" ++ ""129002163642690000,129002163642690000,129002163642690000,-3145728,"" + ""3,'s_ID_4','s_ID_9','s_ID_9','s_ID_4','s_ID_4',0,0,1,0,1,0,1,1,"" + ""'Welcome to Chromium',NULL,'Welcome to Chromium',"" + ""'Welcome to Chromium','Welcome to Chromium',"" + ""'http://www.google.com/chrome/intl/en/welcome.html',"" + ""'http://www.google.com/chrome/intl/en/welcome.html',NULL,NULL,"" + ""NULL);"" +- ""INSERT INTO metas VALUES(5,677,677,"" LEGACY_PROTO_TIME_VALS(5) +- "",1048576,"" ++ ""INSERT INTO metas VALUES(5,677,677,129001555500000000,"" ++ ""129001555500000000,129001555500000000,129001555500000000,1048576,"" + ""7,'s_ID_5','s_ID_9','s_ID_9','s_ID_5','s_ID_5',0,0,1,0,1,0,1,1,"" + ""'Google',NULL,'Google','Google','Google','http://www.google.com/',"" + ""'http://www.google.com/',NULL,'AGASGASG','AGFDGASG');"" +- ""INSERT INTO metas VALUES(6,694,694,"" LEGACY_PROTO_TIME_VALS(6) +- "",-4194304,"" ++ ""INSERT INTO metas VALUES(6,694,694,129053976170000000,"" ++ ""129053976170000000,129053976170000000,129053976170000000,-4194304,"" + ""6,'s_ID_6','s_ID_9','s_ID_9','r','r',0,0,0,1,1,1,0,1,"" + ""'The Internet',NULL,'The Internet','The Internet',"" + ""'The Internet',NULL,NULL,NULL,NULL,NULL);"" +- ""INSERT INTO metas VALUES(7,663,663,"" LEGACY_PROTO_TIME_VALS(7) +- "","" ++ ""INSERT INTO metas VALUES(7,663,663,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,"" + ""1048576,0,'s_ID_7','r','r','r','r',0,0,0,1,1,1,0,1,"" + ""'Google Chrome',NULL,'Google Chrome','Google Chrome',"" + ""'Google Chrome',NULL,NULL,'google_chrome',NULL,NULL);"" +- ""INSERT INTO metas VALUES(8,664,664,"" LEGACY_PROTO_TIME_VALS(8) +- "",1048576,"" ++ ""INSERT INTO metas VALUES(8,664,664,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,1048576,"" + ""0,'s_ID_8','s_ID_7','s_ID_7','r','r',0,0,0,1,1,1,0,1,'Bookmarks',"" + ""NULL,'Bookmarks','Bookmarks','Bookmarks',NULL,NULL,"" + ""'google_chrome_bookmarks',NULL,NULL);"" +- ""INSERT INTO metas VALUES(9,665,665,"" LEGACY_PROTO_TIME_VALS(9) +- "","" ++ ""INSERT INTO metas VALUES(9,665,665,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,"" + ""1048576,1,'s_ID_9','s_ID_8','s_ID_8','r','s_ID_10',0,0,0,1,1,1,0,"" + ""1,'Bookmark Bar',NULL,'Bookmark Bar','Bookmark Bar','Bookmark Bar',"" + ""NULL,NULL,'bookmark_bar',NULL,NULL);"" +- ""INSERT INTO metas VALUES(10,666,666,"" LEGACY_PROTO_TIME_VALS(10) +- "",2097152,"" ++ ""INSERT INTO metas VALUES(10,666,666,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,2097152,"" + ""2,'s_ID_10','s_ID_8','s_ID_8','s_ID_9','r',0,0,0,1,1,1,0,1,"" + ""'Other Bookmarks',NULL,'Other Bookmarks','Other Bookmarks',"" + ""'Other Bookmarks',NULL,NULL,'other_bookmarks',"" + ""NULL,NULL);"" +- ""INSERT INTO metas VALUES(11,683,683,"" LEGACY_PROTO_TIME_VALS(11) +- "",-1048576,"" ++ ""INSERT INTO metas VALUES(11,683,683,129079956948440000,"" ++ ""129079956948440000,129079956948440000,129079956948440000,-1048576,"" + ""8,'s_ID_11','s_ID_6','s_ID_6','r','s_ID_13',0,0,0,0,1,0,0,1,"" + ""'Home (The Chromium Projects)',NULL,'Home (The Chromium Projects)',"" + ""'Home (The Chromium Projects)','Home (The Chromium Projects)',"" + ""'http://dev.chromium.org/','http://dev.chromium.org/other',NULL,"" + ""'AGATWA','AFAGVASF');"" +- ""INSERT INTO metas VALUES(12,685,685,"" LEGACY_PROTO_TIME_VALS(12) +- "",0,9,"" ++ ""INSERT INTO metas VALUES(12,685,685,129079957513650000,"" ++ ""129079957513650000,129079957513650000,129079957513650000,0,9,"" + ""'s_ID_12','s_ID_6','s_ID_6','s_ID_13','s_ID_14',0,0,0,1,1,1,0,1,"" + ""'Extra Bookmarks',NULL,'Extra Bookmarks','Extra Bookmarks',"" + ""'Extra Bookmarks',NULL,NULL,NULL,NULL,NULL);"" +- ""INSERT INTO metas VALUES(13,687,687,"" LEGACY_PROTO_TIME_VALS(13) +- "",-917504,"" ++ ""INSERT INTO metas VALUES(13,687,687,129079957985300000,"" ++ ""129079957985300000,129079957985300000,129079957985300000,-917504,"" + ""10,'s_ID_13','s_ID_6','s_ID_6','s_ID_11','s_ID_12',0,0,0,0,1,0,0,"" + ""1,'ICANN | Internet Corporation for Assigned Names and Numbers',"" + ""'ICANN Internet Corporation for Assigned Names and Numbers',"" +@@ -394,8 +170,8 @@ void MigrationTest::SetUpVersion67Database() { + ""'ICANN | Internet Corporation for Assigned Names and Numbers',"" + ""'http://www.icann.com/','http://www.icann.com/',NULL,"" + ""'PNGAXF0AAFF','DAAFASF');"" +- ""INSERT INTO metas VALUES(14,692,692,"" LEGACY_PROTO_TIME_VALS(14) +- "",1048576,"" ++ ""INSERT INTO metas VALUES(14,692,692,129079958383000000,"" ++ ""129079958383000000,129079958383000000,129079958383000000,1048576,"" + ""11,'s_ID_14','s_ID_6','s_ID_6','s_ID_12','r',0,0,0,0,1,0,0,1,"" + ""'The WebKit Open Source Project',NULL,"" + ""'The WebKit Open Source Project','The WebKit Open Source Project',"" +@@ -446,68 +222,68 @@ void MigrationTest::SetUpVersion68Database() { + ""bookmark_url varchar,server_bookmark_url varchar,"" + ""singleton_tag varchar,bookmark_favicon blob,"" + ""server_bookmark_favicon blob);"" +- ""INSERT INTO metas VALUES(1,-1,0,"" LEGACY_PROTO_TIME_VALS(1) +- "",0,0,'r','r','r','r','r',0,0,0,1,0,0,0,0,NULL,"" ++ ""INSERT INTO metas VALUES(1,-1,0,129079956640320000,0,"" ++ ""129079956640320000,0,0,0,'r','r','r','r','r',0,0,0,1,0,0,0,0,NULL,"" + ""NULL,NULL,NULL,NULL,NULL,NULL);"" +- ""INSERT INTO metas VALUES(2,669,669,"" LEGACY_PROTO_TIME_VALS(2) +- "",-2097152,"" ++ ""INSERT INTO metas VALUES(2,669,669,128976886618480000,"" ++ ""128976886618480000,128976886618480000,128976886618480000,-2097152,"" + ""4,'s_ID_2','s_ID_9','s_ID_9','s_ID_2','s_ID_2',0,0,1,0,1,0,1,1,"" + ""'Deleted Item','Deleted Item','http://www.google.com/',"" + ""'http://www.google.com/2',NULL,'AASGASGA','ASADGADGADG');"" +- ""INSERT INTO metas VALUES(4,681,681,"" LEGACY_PROTO_TIME_VALS(4) +- "",-3145728,"" ++ ""INSERT INTO metas VALUES(4,681,681,129002163642690000,"" ++ ""129002163642690000,129002163642690000,129002163642690000,-3145728,"" + ""3,'s_ID_4','s_ID_9','s_ID_9','s_ID_4','s_ID_4',0,0,1,0,1,0,1,1,"" + ""'Welcome to Chromium','Welcome to Chromium',"" + ""'http://www.google.com/chrome/intl/en/welcome.html',"" + ""'http://www.google.com/chrome/intl/en/welcome.html',NULL,NULL,"" + ""NULL);"" +- ""INSERT INTO metas VALUES(5,677,677,"" LEGACY_PROTO_TIME_VALS(5) +- "",1048576,"" ++ ""INSERT INTO metas VALUES(5,677,677,129001555500000000,"" ++ ""129001555500000000,129001555500000000,129001555500000000,1048576,"" + ""7,'s_ID_5','s_ID_9','s_ID_9','s_ID_5','s_ID_5',0,0,1,0,1,0,1,1,"" + ""'Google','Google','http://www.google.com/',"" + ""'http://www.google.com/',NULL,'AGASGASG','AGFDGASG');"" +- ""INSERT INTO metas VALUES(6,694,694,"" LEGACY_PROTO_TIME_VALS(6) +- "",-4194304,"" ++ ""INSERT INTO metas VALUES(6,694,694,129053976170000000,"" ++ ""129053976170000000,129053976170000000,129053976170000000,-4194304,"" + ""6,'s_ID_6','s_ID_9','s_ID_9','r','r',0,0,0,1,1,1,0,1,"" + ""'The Internet','The Internet',NULL,NULL,NULL,NULL,NULL);"" +- ""INSERT INTO metas VALUES(7,663,663,"" LEGACY_PROTO_TIME_VALS(7) +- "","" ++ ""INSERT INTO metas VALUES(7,663,663,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,"" + ""1048576,0,'s_ID_7','r','r','r','r',0,0,0,1,1,1,0,1,"" + ""'Google Chrome','Google Chrome',NULL,NULL,'google_chrome',NULL,"" + ""NULL);"" +- ""INSERT INTO metas VALUES(8,664,664,"" LEGACY_PROTO_TIME_VALS(8) +- "",1048576,"" ++ ""INSERT INTO metas VALUES(8,664,664,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,1048576,"" + ""0,'s_ID_8','s_ID_7','s_ID_7','r','r',0,0,0,1,1,1,0,1,'Bookmarks',"" + ""'Bookmarks',NULL,NULL,'google_chrome_bookmarks',NULL,NULL);"" +- ""INSERT INTO metas VALUES(9,665,665,"" LEGACY_PROTO_TIME_VALS(9) +- "","" ++ ""INSERT INTO metas VALUES(9,665,665,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,"" + ""1048576,1,'s_ID_9','s_ID_8','s_ID_8','r','s_ID_10',0,0,0,1,1,1,0,"" + ""1,'Bookmark Bar','Bookmark Bar',NULL,NULL,'bookmark_bar',NULL,"" + ""NULL);"" +- ""INSERT INTO metas VALUES(10,666,666,"" LEGACY_PROTO_TIME_VALS(10) +- "",2097152,"" ++ ""INSERT INTO metas VALUES(10,666,666,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,2097152,"" + ""2,'s_ID_10','s_ID_8','s_ID_8','s_ID_9','r',0,0,0,1,1,1,0,1,"" + ""'Other Bookmarks','Other Bookmarks',NULL,NULL,'other_bookmarks',"" + ""NULL,NULL);"" +- ""INSERT INTO metas VALUES(11,683,683,"" LEGACY_PROTO_TIME_VALS(11) +- "",-1048576,"" ++ ""INSERT INTO metas VALUES(11,683,683,129079956948440000,"" ++ ""129079956948440000,129079956948440000,129079956948440000,-1048576,"" + ""8,'s_ID_11','s_ID_6','s_ID_6','r','s_ID_13',0,0,0,0,1,0,0,1,"" + ""'Home (The Chromium Projects)','Home (The Chromium Projects)',"" + ""'http://dev.chromium.org/','http://dev.chromium.org/other',NULL,"" + ""'AGATWA','AFAGVASF');"" +- ""INSERT INTO metas VALUES(12,685,685,"" LEGACY_PROTO_TIME_VALS(12) +- "",0,9,"" ++ ""INSERT INTO metas VALUES(12,685,685,129079957513650000,"" ++ ""129079957513650000,129079957513650000,129079957513650000,0,9,"" + ""'s_ID_12','s_ID_6','s_ID_6','s_ID_13','s_ID_14',0,0,0,1,1,1,0,1,"" + ""'Extra Bookmarks','Extra Bookmarks',NULL,NULL,NULL,NULL,NULL);"" +- ""INSERT INTO metas VALUES(13,687,687,"" LEGACY_PROTO_TIME_VALS(13) +- "",-917504,"" ++ ""INSERT INTO metas VALUES(13,687,687,129079957985300000,"" ++ ""129079957985300000,129079957985300000,129079957985300000,-917504,"" + ""10,'s_ID_13','s_ID_6','s_ID_6','s_ID_11','s_ID_12',0,0,0,0,1,0,0,"" + ""1,'ICANN | Internet Corporation for Assigned Names and Numbers',"" + ""'ICANN | Internet Corporation for Assigned Names and Numbers',"" + ""'http://www.icann.com/','http://www.icann.com/',NULL,"" + ""'PNGAXF0AAFF','DAAFASF');"" +- ""INSERT INTO metas VALUES(14,692,692,"" LEGACY_PROTO_TIME_VALS(14) +- "",1048576,"" ++ ""INSERT INTO metas VALUES(14,692,692,129079958383000000,"" ++ ""129079958383000000,129079958383000000,129079958383000000,1048576,"" + ""11,'s_ID_14','s_ID_6','s_ID_6','s_ID_12','r',0,0,0,0,1,0,0,1,"" + ""'The WebKit Open Source Project','The WebKit Open Source Project',"" + ""'http://webkit.org/','http://webkit.org/x',NULL,'PNGX','PNG2Y');"" +@@ -551,19 +327,19 @@ void MigrationTest::SetUpVersion69Database() { + ""singleton_tag varchar,bookmark_favicon blob,"" + ""server_bookmark_favicon blob, specifics blob, "" + ""server_specifics blob);"" +- ""INSERT INTO metas VALUES(1,-1,0,"" LEGACY_PROTO_TIME_VALS(1) +- "",0,0,'r','r','r','r','r',0,0,0,1,0,0,0,0,NULL,NULL,NULL,NULL,NULL,"" ++ ""INSERT INTO metas VALUES(1,-1,0,129079956640320000,0,129079956640320000,"" ++ ""0,0,0,'r','r','r','r','r',0,0,0,1,0,0,0,0,NULL,NULL,NULL,NULL,NULL,"" + ""NULL,NULL,X'',X'');"" +- ""INSERT INTO metas VALUES(2,669,669,"" LEGACY_PROTO_TIME_VALS(2) +- "",-2097152,"" ++ ""INSERT INTO metas VALUES(2,669,669,128976886618480000,"" ++ ""128976886618480000,128976886618480000,128976886618480000,-2097152,"" + ""4,'s_ID_2','s_ID_9','s_ID_9','s_ID_2','s_ID_2',0,0,1,0,1,0,1,1,"" + ""'Deleted Item','Deleted Item','http://www.google.com/',"" + ""'http://www.google.com/2',NULL,'AASGASGA','ASADGADGADG',"" + ""X'C28810220A16687474703A2F2F7777772E676F6F676C652E636F6D2F120841415"" + ""34741534741',X'C28810260A17687474703A2F2F7777772E676F6F676C652E636F"" + ""6D2F32120B4153414447414447414447');"" +- ""INSERT INTO metas VALUES(4,681,681,"" LEGACY_PROTO_TIME_VALS(4) +- "",-3145728,"" ++ ""INSERT INTO metas VALUES(4,681,681,129002163642690000,"" ++ ""129002163642690000,129002163642690000,129002163642690000,-3145728,"" + ""3,'s_ID_4','s_ID_9','s_ID_9','s_ID_4','s_ID_4',0,0,1,0,1,0,1,1,"" + ""'Welcome to Chromium','Welcome to Chromium',"" + ""'http://www.google.com/chrome/intl/en/welcome.html',"" +@@ -572,61 +348,61 @@ void MigrationTest::SetUpVersion69Database() { + ""D652F696E746C2F656E2F77656C636F6D652E68746D6C1200',X'C28810350A3168"" + ""7474703A2F2F7777772E676F6F676C652E636F6D2F6368726F6D652F696E746C2F6"" + ""56E2F77656C636F6D652E68746D6C1200');"" +- ""INSERT INTO metas VALUES(5,677,677,"" LEGACY_PROTO_TIME_VALS(5) +- "",1048576,7,"" ++ ""INSERT INTO metas VALUES(5,677,677,129001555500000000,"" ++ ""129001555500000000,129001555500000000,129001555500000000,1048576,7,"" + ""'s_ID_5','s_ID_9','s_ID_9','s_ID_5','s_ID_5',0,0,1,0,1,0,1,1,"" + ""'Google','Google','http://www.google.com/',"" + ""'http://www.google.com/',NULL,'AGASGASG','AGFDGASG',X'C28810220A166"" + ""87474703A2F2F7777772E676F6F676C652E636F6D2F12084147415347415347',X'"" + ""C28810220A16687474703A2F2F7777772E676F6F676C652E636F6D2F12084147464"" + ""447415347');"" +- ""INSERT INTO metas VALUES(6,694,694,"" LEGACY_PROTO_TIME_VALS(6) +- "",-4194304,6"" ++ ""INSERT INTO metas VALUES(6,694,694,129053976170000000,"" ++ ""129053976170000000,129053976170000000,129053976170000000,-4194304,6"" + "",'s_ID_6','s_ID_9','s_ID_9','r','r',0,0,0,1,1,1,0,1,'The Internet',"" + ""'The Internet',NULL,NULL,NULL,NULL,NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO metas VALUES(7,663,663,"" LEGACY_PROTO_TIME_VALS(7) +- "",1048576,0,"" ++ ""INSERT INTO metas VALUES(7,663,663,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,1048576,0,"" + ""'s_ID_7','r','r','r','r',0,0,0,1,1,1,0,1,'Google Chrome',"" + ""'Google Chrome',NULL,NULL,'google_chrome',NULL,NULL,NULL,NULL);"" +- ""INSERT INTO metas VALUES(8,664,664,"" LEGACY_PROTO_TIME_VALS(8) +- "",1048576,0,"" ++ ""INSERT INTO metas VALUES(8,664,664,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,1048576,0,"" + ""'s_ID_8','s_ID_7','s_ID_7','r','r',0,0,0,1,1,1,0,1,'Bookmarks',"" + ""'Bookmarks',NULL,NULL,'google_chrome_bookmarks',NULL,NULL,"" + ""X'C2881000',X'C2881000');"" +- ""INSERT INTO metas VALUES(9,665,665,"" LEGACY_PROTO_TIME_VALS(9) +- "",1048576,1,"" ++ ""INSERT INTO metas VALUES(9,665,665,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,1048576,1,"" + ""'s_ID_9','s_ID_8','s_ID_8','r','s_ID_10',0,0,0,1,1,1,0,1,"" + ""'Bookmark Bar','Bookmark Bar',NULL,NULL,'bookmark_bar',NULL,NULL,"" + ""X'C2881000',X'C2881000');"" +- ""INSERT INTO metas VALUES(10,666,666,"" LEGACY_PROTO_TIME_VALS(10) +- "",2097152,2,"" ++ ""INSERT INTO metas VALUES(10,666,666,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,2097152,2,"" + ""'s_ID_10','s_ID_8','s_ID_8','s_ID_9','r',0,0,0,1,1,1,0,1,"" + ""'Other Bookmarks','Other Bookmarks',NULL,NULL,'other_bookmarks',"" + ""NULL,NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO metas VALUES(11,683,683,"" LEGACY_PROTO_TIME_VALS(11) +- "",-1048576,"" ++ ""INSERT INTO metas VALUES(11,683,683,129079956948440000,"" ++ ""129079956948440000,129079956948440000,129079956948440000,-1048576,"" + ""8,'s_ID_11','s_ID_6','s_ID_6','r','s_ID_13',0,0,0,0,1,0,0,1,"" + ""'Home (The Chromium Projects)','Home (The Chromium Projects)',"" + ""'http://dev.chromium.org/','http://dev.chromium.org/other',NULL,"" + ""'AGATWA','AFAGVASF',X'C28810220A18687474703A2F2F6465762E6368726F6D6"" + ""9756D2E6F72672F1206414741545741',X'C28810290A1D687474703A2F2F646576"" + ""2E6368726F6D69756D2E6F72672F6F7468657212084146414756415346');"" +- ""INSERT INTO metas VALUES(12,685,685,"" LEGACY_PROTO_TIME_VALS(12) +- "",0,9,"" ++ ""INSERT INTO metas VALUES(12,685,685,129079957513650000,"" ++ ""129079957513650000,129079957513650000,129079957513650000,0,9,"" + ""'s_ID_12','s_ID_6','s_ID_6','s_ID_13','s_ID_14',0,0,0,1,1,1,0,1,"" + ""'Extra Bookmarks','Extra Bookmarks',NULL,NULL,NULL,NULL,NULL,"" + ""X'C2881000',X'C2881000');"" +- ""INSERT INTO metas VALUES(13,687,687,"" LEGACY_PROTO_TIME_VALS(13) +- "",-917504,"" ++ ""INSERT INTO metas VALUES(13,687,687,129079957985300000,"" ++ ""129079957985300000,129079957985300000,129079957985300000,-917504,"" + ""10,'s_ID_13','s_ID_6','s_ID_6','s_ID_11','s_ID_12',0,0,0,0,1,0,0,"" + ""1,'ICANN | Internet Corporation for Assigned Names and Numbers',"" + ""'ICANN | Internet Corporation for Assigned Names and Numbers',"" + ""'http://www.icann.com/','http://www.icann.com/',NULL,'PNGAXF0AAFF',"" + ""'DAAFASF',X'C28810240A15687474703A2F2F7777772E6963616E6E2E636F6D2F1"" + ""20B504E474158463041414646',X'C28810200A15687474703A2F2F7777772E6963"" + ""616E6E2E636F6D2F120744414146415346');"" +- ""INSERT INTO metas VALUES(14,692,692,"" LEGACY_PROTO_TIME_VALS(14) +- "",1048576,11,"" ++ ""INSERT INTO metas VALUES(14,692,692,129079958383000000,"" ++ ""129079958383000000,129079958383000000,129079958383000000,1048576,11,"" + ""'s_ID_14','s_ID_6','s_ID_6','s_ID_12','r',0,0,0,0,1,0,0,1,"" + ""'The WebKit Open Source Project','The WebKit Open Source Project',"" + ""'http://webkit.org/','http://webkit.org/x',NULL,'PNGX','PNG2Y',"" +@@ -680,73 +456,74 @@ void MigrationTest::SetUpVersion70Database() { + ""non_unique_name varchar,server_non_unique_name varchar(255),"" + ""unique_server_tag varchar,unique_client_tag varchar,"" + ""specifics blob,server_specifics blob);"" +- ""INSERT INTO metas VALUES(1,-1,0,"" LEGACY_PROTO_TIME_VALS(1) +- "",0,0,'r','r','r','r','r',0,0,0,1,0,0,NULL,NULL,NULL,NULL,X'',X'');"" +- ""INSERT INTO metas VALUES(2,669,669,"" LEGACY_PROTO_TIME_VALS(2) "","" ++ ""INSERT INTO metas VALUES(1,-1,0,129079956640320000,0,129079956640320000,"" ++ ""0,0,0,'r','r','r','r','r',0,0,0,1,0,0,NULL,NULL,NULL,NULL,X'',X'');"" ++ ""INSERT INTO metas VALUES(2,669,669,128976886618480000,"" ++ ""128976886618480000,128976886618480000,128976886618480000,"" + ""-2097152,4,'s_ID_2','s_ID_9','s_ID_9','s_ID_2','s_ID_2',0,0,1,0,0,"" + ""1,'Deleted Item','Deleted Item',NULL,NULL,X'C28810220A16687474703A"" + ""2F2F7777772E676F6F676C652E636F6D2F12084141534741534741',X'C2881026"" + ""0A17687474703A2F2F7777772E676F6F676C652E636F6D2F32120B415341444741"" + ""4447414447');"" +- ""INSERT INTO metas VALUES(4,681,681,"" LEGACY_PROTO_TIME_VALS(4) +- "",-3145728,"" ++ ""INSERT INTO metas VALUES(4,681,681,129002163642690000,"" ++ ""129002163642690000,129002163642690000,129002163642690000,-3145728,"" + ""3,'s_ID_4','s_ID_9','s_ID_9','s_ID_4','s_ID_4',0,0,1,0,0,1,"" + ""'Welcome to Chromium','Welcome to Chromium',NULL,NULL,X'C28810350A"" + ""31687474703A2F2F7777772E676F6F676C652E636F6D2F6368726F6D652F696E74"" + ""6C2F656E2F77656C636F6D652E68746D6C1200',X'C28810350A31687474703A2F"" + ""2F7777772E676F6F676C652E636F6D2F6368726F6D652F696E746C2F656E2F7765"" + ""6C636F6D652E68746D6C1200');"" +- ""INSERT INTO metas VALUES(5,677,677,"" LEGACY_PROTO_TIME_VALS(5) +- "",1048576,7,"" ++ ""INSERT INTO metas VALUES(5,677,677,129001555500000000,"" ++ ""129001555500000000,129001555500000000,129001555500000000,1048576,7,"" + ""'s_ID_5','s_ID_9','s_ID_9','s_ID_5','s_ID_5',0,0,1,0,0,1,'Google',"" + ""'Google',NULL,NULL,X'C28810220A16687474703A2F2F7777772E676F6F676C6"" + ""52E636F6D2F12084147415347415347',X'C28810220A16687474703A2F2F77777"" + ""72E676F6F676C652E636F6D2F12084147464447415347');"" +- ""INSERT INTO metas VALUES(6,694,694,"" LEGACY_PROTO_TIME_VALS(6) +- "",-4194304,"" ++ ""INSERT INTO metas VALUES(6,694,694,129053976170000000,"" ++ ""129053976170000000,129053976170000000,129053976170000000,-4194304,"" + ""6,'s_ID_6','s_ID_9','s_ID_9','r','r',0,0,0,1,1,0,'The Internet',"" + ""'The Internet',NULL,NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO metas VALUES(7,663,663,"" LEGACY_PROTO_TIME_VALS(7) +- "",1048576,0,"" ++ ""INSERT INTO metas VALUES(7,663,663,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,1048576,0,"" + ""'s_ID_7','r','r','r','r',0,0,0,1,1,0,'Google Chrome',"" + ""'Google Chrome','google_chrome',NULL,NULL,NULL);"" +- ""INSERT INTO metas VALUES(8,664,664,"" LEGACY_PROTO_TIME_VALS(8) +- "",1048576,0,"" ++ ""INSERT INTO metas VALUES(8,664,664,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,1048576,0,"" + ""'s_ID_8','s_ID_7','s_ID_7','r','r',0,0,0,1,1,0,'Bookmarks',"" + ""'Bookmarks','google_chrome_bookmarks',NULL,X'C2881000',"" + ""X'C2881000');"" +- ""INSERT INTO metas VALUES(9,665,665,"" LEGACY_PROTO_TIME_VALS(9) +- "",1048576,"" ++ ""INSERT INTO metas VALUES(9,665,665,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,1048576,"" + ""1,'s_ID_9','s_ID_8','s_ID_8','r','s_ID_10',0,0,0,1,1,0,"" + ""'Bookmark Bar','Bookmark Bar','bookmark_bar',NULL,X'C2881000',"" + ""X'C2881000');"" +- ""INSERT INTO metas VALUES(10,666,666,"" LEGACY_PROTO_TIME_VALS(10) +- "","" ++ ""INSERT INTO metas VALUES(10,666,666,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,"" + ""2097152,2,'s_ID_10','s_ID_8','s_ID_8','s_ID_9','r',0,0,0,1,1,0,"" + ""'Other Bookmarks','Other Bookmarks','other_bookmarks',NULL,"" + ""X'C2881000',X'C2881000');"" +- ""INSERT INTO metas VALUES(11,683,683,"" LEGACY_PROTO_TIME_VALS(11) +- "",-1048576,"" ++ ""INSERT INTO metas VALUES(11,683,683,129079956948440000,"" ++ ""129079956948440000,129079956948440000,129079956948440000,-1048576,"" + ""8,'s_ID_11','s_ID_6','s_ID_6','r','s_ID_13',0,0,0,0,0,0,"" + ""'Home (The Chromium Projects)','Home (The Chromium Projects)',"" + ""NULL,NULL,X'C28810220A18687474703A2F2F6465762E6368726F6D69756D2E6F"" + ""72672F1206414741545741',X'C28810290A1D687474703A2F2F6465762E636872"" + ""6F6D69756D2E6F72672F6F7468657212084146414756415346');"" +- ""INSERT INTO metas VALUES(12,685,685,"" LEGACY_PROTO_TIME_VALS(12) +- "",0,9,"" ++ ""INSERT INTO metas VALUES(12,685,685,129079957513650000,"" ++ ""129079957513650000,129079957513650000,129079957513650000,0,9,"" + ""'s_ID_12','s_ID_6','s_ID_6','s_ID_13','s_ID_14',0,0,0,1,1,0,"" + ""'Extra Bookmarks','Extra Bookmarks',NULL,NULL,X'C2881000',"" + ""X'C2881000');"" +- ""INSERT INTO metas VALUES(13,687,687,"" LEGACY_PROTO_TIME_VALS(13) +- "",-917504,"" ++ ""INSERT INTO metas VALUES(13,687,687,129079957985300000,"" ++ ""129079957985300000,129079957985300000,129079957985300000,-917504,"" + ""10,'s_ID_13','s_ID_6','s_ID_6','s_ID_11','s_ID_12',0,0,0,0,0,0,"" + ""'ICANN | Internet Corporation for Assigned Names and Numbers',"" + ""'ICANN | Internet Corporation for Assigned Names and Numbers',"" + ""NULL,NULL,X'C28810240A15687474703A2F2F7777772E6963616E6E2E636F6D2F"" + ""120B504E474158463041414646',X'C28810200A15687474703A2F2F7777772E69"" + ""63616E6E2E636F6D2F120744414146415346');"" +- ""INSERT INTO metas VALUES(14,692,692,"" LEGACY_PROTO_TIME_VALS(14) +- "",1048576,"" ++ ""INSERT INTO metas VALUES(14,692,692,129079958383000000,"" ++ ""129079958383000000,129079958383000000,129079958383000000,1048576,"" + ""11,'s_ID_14','s_ID_6','s_ID_6','s_ID_12','r',0,0,0,0,0,0,"" + ""'The WebKit Open Source Project','The WebKit Open Source Project',"" + ""NULL,NULL,X'C288101A0A12687474703A2F2F7765626B69742E6F72672F120450"" +@@ -778,73 +555,73 @@ void MigrationTest::SetUpVersion71Database() { + ""non_unique_name varchar,server_non_unique_name varchar(255),"" + ""unique_server_tag varchar,unique_client_tag varchar,specifics blob,"" + ""server_specifics blob);"" +- ""INSERT INTO 'metas' VALUES(1,-1,0,"" LEGACY_PROTO_TIME_VALS(1) +- "",0,0,'r','r','r','r','r',0,0,0,1,0,0,NULL,NULL,"" ++ ""INSERT INTO 'metas' VALUES(1,-1,0,129079956640320000,0,"" ++ ""129079956640320000,0,0,0,'r','r','r','r','r',0,0,0,1,0,0,NULL,NULL,"" + ""NULL,NULL,X'',X'');"" +- ""INSERT INTO 'metas' VALUES(2,669,669,"" LEGACY_PROTO_TIME_VALS(2) +- "",-2097152,4,"" ++ ""INSERT INTO 'metas' VALUES(2,669,669,128976886618480000,"" ++ ""128976886618480000,128976886618480000,128976886618480000,-2097152,4,"" + ""'s_ID_2','s_ID_9','s_ID_9','s_ID_2','s_ID_2',0,0,1,0,0,1,"" + ""'Deleted Item','Deleted Item',NULL,NULL,X'C28810220A16687474703A2F2F"" + ""7777772E676F6F676C652E636F6D2F12084141534741534741',X'C28810260A1768"" + ""7474703A2F2F7777772E676F6F676C652E636F6D2F32120B41534144474144474144"" + ""47');"" +- ""INSERT INTO 'metas' VALUES(4,681,681,"" LEGACY_PROTO_TIME_VALS(4) +- "",-3145728,3,"" ++ ""INSERT INTO 'metas' VALUES(4,681,681,129002163642690000,"" ++ ""129002163642690000,129002163642690000,129002163642690000,-3145728,3,"" + ""'s_ID_4','s_ID_9','s_ID_9','s_ID_4','s_ID_4',0,0,1,0,0,1,"" + ""'Welcome to Chromium','Welcome to Chromium',NULL,NULL,X'C28810350A31"" + ""687474703A2F2F7777772E676F6F676C652E636F6D2F6368726F6D652F696E746C2F"" + ""656E2F77656C636F6D652E68746D6C1200',X'C28810350A31687474703A2F2F7777"" + ""772E676F6F676C652E636F6D2F6368726F6D652F696E746C2F656E2F77656C636F6D"" + ""652E68746D6C1200');"" +- ""INSERT INTO 'metas' VALUES(5,677,677,"" LEGACY_PROTO_TIME_VALS(5) +- "",1048576,7,"" ++ ""INSERT INTO 'metas' VALUES(5,677,677,129001555500000000,"" ++ ""129001555500000000,129001555500000000,129001555500000000,1048576,7,"" + ""'s_ID_5','s_ID_9','s_ID_9','s_ID_5','s_ID_5',0,0,1,0,0,1,'Google',"" + ""'Google',NULL,NULL,X'C28810220A16687474703A2F2F7777772E676F6F676C652"" + ""E636F6D2F12084147415347415347',X'C28810220A16687474703A2F2F7777772E6"" + ""76F6F676C652E636F6D2F12084147464447415347');"" +- ""INSERT INTO 'metas' VALUES(6,694,694,"" LEGACY_PROTO_TIME_VALS(6) +- "",-4194304,6,"" ++ ""INSERT INTO 'metas' VALUES(6,694,694,129053976170000000,"" ++ ""129053976170000000,129053976170000000,129053976170000000,-4194304,6,"" + ""'s_ID_6','s_ID_9','s_ID_9','r','r',0,0,0,1,1,0,'The Internet',"" + ""'The Internet',NULL,NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(7,663,663,"" LEGACY_PROTO_TIME_VALS(7) +- "",1048576,0,"" ++ ""INSERT INTO 'metas' VALUES(7,663,663,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,1048576,0,"" + ""'s_ID_7','r','r','r','r',0,0,0,1,1,0,'Google Chrome','Google Chrome'"" + "",'google_chrome',NULL,NULL,NULL);"" +- ""INSERT INTO 'metas' VALUES(8,664,664,"" LEGACY_PROTO_TIME_VALS(8) +- "",1048576,0,"" ++ ""INSERT INTO 'metas' VALUES(8,664,664,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,1048576,0,"" + ""'s_ID_8','s_ID_7','s_ID_7','r','r',0,0,0,1,1,0,'Bookmarks',"" + ""'Bookmarks','google_chrome_bookmarks',NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(9,665,665,"" LEGACY_PROTO_TIME_VALS(9) +- "",1048576,1,"" ++ ""INSERT INTO 'metas' VALUES(9,665,665,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,1048576,1,"" + ""'s_ID_9','s_ID_8','s_ID_8','r','s_ID_10',0,0,0,1,1,0,'Bookmark Bar',"" + ""'Bookmark Bar','bookmark_bar',NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(10,666,666,"" LEGACY_PROTO_TIME_VALS(10) +- "",2097152,2,"" ++ ""INSERT INTO 'metas' VALUES(10,666,666,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,2097152,2,"" + ""'s_ID_10','s_ID_8','s_ID_8','s_ID_9','r',0,0,0,1,1,0,"" + ""'Other Bookmarks','Other Bookmarks','other_bookmarks',NULL,"" + ""X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(11,683,683,"" LEGACY_PROTO_TIME_VALS(11) +- "",-1048576,8,"" ++ ""INSERT INTO 'metas' VALUES(11,683,683,129079956948440000,"" ++ ""129079956948440000,129079956948440000,129079956948440000,-1048576,8,"" + ""'s_ID_11','s_ID_6','s_ID_6','r','s_ID_13',0,0,0,0,0,0,"" + ""'Home (The Chromium Projects)','Home (The Chromium Projects)',NULL,"" + ""NULL,X'C28810220A18687474703A2F2F6465762E6368726F6D69756D2E6F72672F1"" + ""206414741545741',X'C28810290A1D687474703A2F2F6465762E6368726F6D69756"" + ""D2E6F72672F6F7468657212084146414756415346');"" +- ""INSERT INTO 'metas' VALUES(12,685,685,"" LEGACY_PROTO_TIME_VALS(12) +- "",0,9,"" ++ ""INSERT INTO 'metas' VALUES(12,685,685,129079957513650000,"" ++ ""129079957513650000,129079957513650000,129079957513650000,0,9,"" + ""'s_ID_12','s_ID_6','s_ID_6','s_ID_13','s_ID_14',0,0,0,1,1,0,"" + ""'Extra Bookmarks','Extra Bookmarks',NULL,NULL,X'C2881000',"" + ""X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(13,687,687,"" LEGACY_PROTO_TIME_VALS(13) +- "",-917504,10,"" ++ ""INSERT INTO 'metas' VALUES(13,687,687,129079957985300000,"" ++ ""129079957985300000,129079957985300000,129079957985300000,-917504,10,"" + ""'s_ID_13','s_ID_6','s_ID_6','s_ID_11','s_ID_12',0,0,0,0,0,0,"" + ""'ICANN | Internet Corporation for Assigned Names and Numbers',"" + ""'ICANN | Internet Corporation for Assigned Names and Numbers',NULL,"" + ""NULL,X'C28810240A15687474703A2F2F7777772E6963616E6E2E636F6D2F120B504"" + ""E474158463041414646',X'C28810200A15687474703A2F2F7777772E6963616E6E2"" + ""E636F6D2F120744414146415346');"" +- ""INSERT INTO 'metas' VALUES(14,692,692,"" LEGACY_PROTO_TIME_VALS(14) +- "",1048576,11,"" ++ ""INSERT INTO 'metas' VALUES(14,692,692,129079958383000000,"" ++ ""129079958383000000,129079958383000000,129079958383000000,1048576,11,"" + ""'s_ID_14','s_ID_6','s_ID_6','s_ID_12','r',0,0,0,0,0,0,"" + ""'The WebKit Open Source Project','The WebKit Open Source Project',"" + ""NULL,NULL,""""X'C288101A0A12687474703A2F2F7765626B69742E6F72672F120450"" +@@ -882,73 +659,73 @@ void MigrationTest::SetUpVersion72Database() { + ""non_unique_name varchar,server_non_unique_name varchar(255),"" + ""unique_server_tag varchar,unique_client_tag varchar,specifics blob,"" + ""server_specifics blob);"" +- ""INSERT INTO 'metas' VALUES(1,-1,0,"" LEGACY_PROTO_TIME_VALS(1) +- "",0,0,'r','r','r','r','r',0,0,0,1,0,0,NULL,NULL,"" ++ ""INSERT INTO 'metas' VALUES(1,-1,0,129079956640320000,0,"" ++ ""129079956640320000,0,0,0,'r','r','r','r','r',0,0,0,1,0,0,NULL,NULL,"" + ""NULL,NULL,X'',X'');"" +- ""INSERT INTO 'metas' VALUES(2,669,669,"" LEGACY_PROTO_TIME_VALS(2) +- "",-2097152,4,"" ++ ""INSERT INTO 'metas' VALUES(2,669,669,128976886618480000,"" ++ ""128976886618480000,128976886618480000,128976886618480000,-2097152,4,"" + ""'s_ID_2','s_ID_9','s_ID_9','s_ID_2','s_ID_2',0,0,1,0,0,1,"" + ""'Deleted Item','Deleted Item',NULL,NULL,X'C28810220A16687474703A2F2F"" + ""7777772E676F6F676C652E636F6D2F12084141534741534741',X'C28810260A1768"" + ""7474703A2F2F7777772E676F6F676C652E636F6D2F32120B41534144474144474144"" + ""47');"" +- ""INSERT INTO 'metas' VALUES(4,681,681,"" LEGACY_PROTO_TIME_VALS(4) +- "",-3145728,3,"" ++ ""INSERT INTO 'metas' VALUES(4,681,681,129002163642690000,"" ++ ""129002163642690000,129002163642690000,129002163642690000,-3145728,3,"" + ""'s_ID_4','s_ID_9','s_ID_9','s_ID_4','s_ID_4',0,0,1,0,0,1,"" + ""'Welcome to Chromium','Welcome to Chromium',NULL,NULL,X'C28810350A31"" + ""687474703A2F2F7777772E676F6F676C652E636F6D2F6368726F6D652F696E746C2F"" + ""656E2F77656C636F6D652E68746D6C1200',X'C28810350A31687474703A2F2F7777"" + ""772E676F6F676C652E636F6D2F6368726F6D652F696E746C2F656E2F77656C636F6D"" + ""652E68746D6C1200');"" +- ""INSERT INTO 'metas' VALUES(5,677,677,"" LEGACY_PROTO_TIME_VALS(5) +- "",1048576,7,"" ++ ""INSERT INTO 'metas' VALUES(5,677,677,129001555500000000,"" ++ ""129001555500000000,129001555500000000,129001555500000000,1048576,7,"" + ""'s_ID_5','s_ID_9','s_ID_9','s_ID_5','s_ID_5',0,0,1,0,0,1,'Google',"" + ""'Google',NULL,NULL,X'C28810220A16687474703A2F2F7777772E676F6F676C652"" + ""E636F6D2F12084147415347415347',X'C28810220A16687474703A2F2F7777772E6"" + ""76F6F676C652E636F6D2F12084147464447415347');"" +- ""INSERT INTO 'metas' VALUES(6,694,694,"" LEGACY_PROTO_TIME_VALS(6) +- "",-4194304,6,"" ++ ""INSERT INTO 'metas' VALUES(6,694,694,129053976170000000,"" ++ ""129053976170000000,129053976170000000,129053976170000000,-4194304,6,"" + ""'s_ID_6','s_ID_9','s_ID_9','r','r',0,0,0,1,1,0,'The Internet',"" + ""'The Internet',NULL,NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(7,663,663,"" LEGACY_PROTO_TIME_VALS(7) +- "",1048576,0,"" ++ ""INSERT INTO 'metas' VALUES(7,663,663,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,1048576,0,"" + ""'s_ID_7','r','r','r','r',0,0,0,1,1,0,'Google Chrome','Google Chrome'"" + "",'google_chrome',NULL,NULL,NULL);"" +- ""INSERT INTO 'metas' VALUES(8,664,664,"" LEGACY_PROTO_TIME_VALS(8) +- "",1048576,0,"" ++ ""INSERT INTO 'metas' VALUES(8,664,664,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,1048576,0,"" + ""'s_ID_8','s_ID_7','s_ID_7','r','r',0,0,0,1,1,0,'Bookmarks',"" + ""'Bookmarks','google_chrome_bookmarks',NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(9,665,665,"" LEGACY_PROTO_TIME_VALS(9) +- "",1048576,1,"" ++ ""INSERT INTO 'metas' VALUES(9,665,665,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,1048576,1,"" + ""'s_ID_9','s_ID_8','s_ID_8','r','s_ID_10',0,0,0,1,1,0,'Bookmark Bar',"" + ""'Bookmark Bar','bookmark_bar',NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(10,666,666,"" LEGACY_PROTO_TIME_VALS(10) +- "",2097152,2,"" ++ ""INSERT INTO 'metas' VALUES(10,666,666,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,2097152,2,"" + ""'s_ID_10','s_ID_8','s_ID_8','s_ID_9','r',0,0,0,1,1,0,"" + ""'Other Bookmarks','Other Bookmarks','other_bookmarks',NULL,"" + ""X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(11,683,683,"" LEGACY_PROTO_TIME_VALS(11) +- "",-1048576,8,"" ++ ""INSERT INTO 'metas' VALUES(11,683,683,129079956948440000,"" ++ ""129079956948440000,129079956948440000,129079956948440000,-1048576,8,"" + ""'s_ID_11','s_ID_6','s_ID_6','r','s_ID_13',0,0,0,0,0,0,"" + ""'Home (The Chromium Projects)','Home (The Chromium Projects)',NULL,"" + ""NULL,X'C28810220A18687474703A2F2F6465762E6368726F6D69756D2E6F72672F1"" + ""206414741545741',X'C28810290A1D687474703A2F2F6465762E6368726F6D69756"" + ""D2E6F72672F6F7468657212084146414756415346');"" +- ""INSERT INTO 'metas' VALUES(12,685,685,"" LEGACY_PROTO_TIME_VALS(12) +- "",0,9,"" ++ ""INSERT INTO 'metas' VALUES(12,685,685,129079957513650000,"" ++ ""129079957513650000,129079957513650000,129079957513650000,0,9,"" + ""'s_ID_12','s_ID_6','s_ID_6','s_ID_13','s_ID_14',0,0,0,1,1,0,"" + ""'Extra Bookmarks','Extra Bookmarks',NULL,NULL,X'C2881000',"" + ""X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(13,687,687,"" LEGACY_PROTO_TIME_VALS(13) +- "",-917504,10,"" ++ ""INSERT INTO 'metas' VALUES(13,687,687,129079957985300000,"" ++ ""129079957985300000,129079957985300000,129079957985300000,-917504,10,"" + ""'s_ID_13','s_ID_6','s_ID_6','s_ID_11','s_ID_12',0,0,0,0,0,0,"" + ""'ICANN | Internet Corporation for Assigned Names and Numbers',"" + ""'ICANN | Internet Corporation for Assigned Names and Numbers',NULL,"" + ""NULL,X'C28810240A15687474703A2F2F7777772E6963616E6E2E636F6D2F120B504"" + ""E474158463041414646',X'C28810200A15687474703A2F2F7777772E6963616E6E2"" + ""E636F6D2F120744414146415346');"" +- ""INSERT INTO 'metas' VALUES(14,692,692,"" LEGACY_PROTO_TIME_VALS(14) +- "",1048576,11,"" ++ ""INSERT INTO 'metas' VALUES(14,692,692,129079958383000000,"" ++ ""129079958383000000,129079958383000000,129079958383000000,1048576,11,"" + ""'s_ID_14','s_ID_6','s_ID_6','s_ID_12','r',0,0,0,0,0,0,"" + ""'The WebKit Open Source Project','The WebKit Open Source Project',"" + ""NULL,NULL,""""X'C288101A0A12687474703A2F2F7765626B69742E6F72672F120450"" +@@ -986,73 +763,73 @@ void MigrationTest::SetUpVersion73Database() { + ""non_unique_name varchar,server_non_unique_name varchar(255),"" + ""unique_server_tag varchar,unique_client_tag varchar,specifics blob,"" + ""server_specifics blob);"" +- ""INSERT INTO 'metas' VALUES(1,-1,0,"" LEGACY_PROTO_TIME_VALS(1) +- "",0,0,'r','r','r','r','r',0,0,0,1,0,0,NULL,NULL,"" ++ ""INSERT INTO 'metas' VALUES(1,-1,0,129079956640320000,0,"" ++ ""129079956640320000,0,0,0,'r','r','r','r','r',0,0,0,1,0,0,NULL,NULL,"" + ""NULL,NULL,X'',X'');"" +- ""INSERT INTO 'metas' VALUES(2,669,669,"" LEGACY_PROTO_TIME_VALS(2) +- "",-2097152,4,"" ++ ""INSERT INTO 'metas' VALUES(2,669,669,128976886618480000,"" ++ ""128976886618480000,128976886618480000,128976886618480000,-2097152,4,"" + ""'s_ID_2','s_ID_9','s_ID_9','s_ID_2','s_ID_2',0,0,1,0,0,1,"" + ""'Deleted Item','Deleted Item',NULL,NULL,X'C28810220A16687474703A2F2F"" + ""7777772E676F6F676C652E636F6D2F12084141534741534741',X'C28810260A1768"" + ""7474703A2F2F7777772E676F6F676C652E636F6D2F32120B41534144474144474144"" + ""47');"" +- ""INSERT INTO 'metas' VALUES(4,681,681,"" LEGACY_PROTO_TIME_VALS(4) +- "",-3145728,3,"" ++ ""INSERT INTO 'metas' VALUES(4,681,681,129002163642690000,"" ++ ""129002163642690000,129002163642690000,129002163642690000,-3145728,3,"" + ""'s_ID_4','s_ID_9','s_ID_9','s_ID_4','s_ID_4',0,0,1,0,0,1,"" + ""'Welcome to Chromium','Welcome to Chromium',NULL,NULL,X'C28810350A31"" + ""687474703A2F2F7777772E676F6F676C652E636F6D2F6368726F6D652F696E746C2F"" + ""656E2F77656C636F6D652E68746D6C1200',X'C28810350A31687474703A2F2F7777"" + ""772E676F6F676C652E636F6D2F6368726F6D652F696E746C2F656E2F77656C636F6D"" + ""652E68746D6C1200');"" +- ""INSERT INTO 'metas' VALUES(5,677,677,"" LEGACY_PROTO_TIME_VALS(5) +- "",1048576,7,"" ++ ""INSERT INTO 'metas' VALUES(5,677,677,129001555500000000,"" ++ ""129001555500000000,129001555500000000,129001555500000000,1048576,7,"" + ""'s_ID_5','s_ID_9','s_ID_9','s_ID_5','s_ID_5',0,0,1,0,0,1,'Google',"" + ""'Google',NULL,NULL,X'C28810220A16687474703A2F2F7777772E676F6F676C652"" + ""E636F6D2F12084147415347415347',X'C28810220A16687474703A2F2F7777772E6"" + ""76F6F676C652E636F6D2F12084147464447415347');"" +- ""INSERT INTO 'metas' VALUES(6,694,694,"" LEGACY_PROTO_TIME_VALS(6) +- "",-4194304,6,"" ++ ""INSERT INTO 'metas' VALUES(6,694,694,129053976170000000,"" ++ ""129053976170000000,129053976170000000,129053976170000000,-4194304,6,"" + ""'s_ID_6','s_ID_9','s_ID_9','r','r',0,0,0,1,1,0,'The Internet',"" + ""'The Internet',NULL,NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(7,663,663,"" LEGACY_PROTO_TIME_VALS(7) +- "",1048576,0,"" ++ ""INSERT INTO 'metas' VALUES(7,663,663,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,1048576,0,"" + ""'s_ID_7','r','r','r','r',0,0,0,1,1,0,'Google Chrome','Google Chrome'"" + "",'google_chrome',NULL,NULL,NULL);"" +- ""INSERT INTO 'metas' VALUES(8,664,664,"" LEGACY_PROTO_TIME_VALS(8) +- "",1048576,0,"" ++ ""INSERT INTO 'metas' VALUES(8,664,664,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,1048576,0,"" + ""'s_ID_8','s_ID_7','s_ID_7','r','r',0,0,0,1,1,0,'Bookmarks',"" + ""'Bookmarks','google_chrome_bookmarks',NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(9,665,665,"" LEGACY_PROTO_TIME_VALS(9) +- "",1048576,1,"" ++ ""INSERT INTO 'metas' VALUES(9,665,665,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,1048576,1,"" + ""'s_ID_9','s_ID_8','s_ID_8','r','s_ID_10',0,0,0,1,1,0,'Bookmark Bar',"" + ""'Bookmark Bar','bookmark_bar',NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(10,666,666,"" LEGACY_PROTO_TIME_VALS(10) +- "",2097152,2,"" ++ ""INSERT INTO 'metas' VALUES(10,666,666,128976864758480000,"" ++ ""128976864758480000,128976864758480000,128976864758480000,2097152,2,"" + ""'s_ID_10','s_ID_8','s_ID_8','s_ID_9','r',0,0,0,1,1,0,"" + ""'Other Bookmarks','Other Bookmarks','other_bookmarks',NULL,"" + ""X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(11,683,683,"" LEGACY_PROTO_TIME_VALS(11) +- "",-1048576,8,"" ++ ""INSERT INTO 'metas' VALUES(11,683,683,129079956948440000,"" ++ ""129079956948440000,129079956948440000,129079956948440000,-1048576,8,"" + ""'s_ID_11','s_ID_6','s_ID_6','r','s_ID_13',0,0,0,0,0,0,"" + ""'Home (The Chromium Projects)','Home (The Chromium Projects)',NULL,"" + ""NULL,X'C28810220A18687474703A2F2F6465762E6368726F6D69756D2E6F72672F1"" + ""206414741545741',X'C28810290A1D687474703A2F2F6465762E6368726F6D69756"" + ""D2E6F72672F6F7468657212084146414756415346');"" +- ""INSERT INTO 'metas' VALUES(12,685,685,"" LEGACY_PROTO_TIME_VALS(12) +- "",0,9,"" ++ ""INSERT INTO 'metas' VALUES(12,685,685,129079957513650000,"" ++ ""129079957513650000,129079957513650000,129079957513650000,0,9,"" + ""'s_ID_12','s_ID_6','s_ID_6','s_ID_13','s_ID_14',0,0,0,1,1,0,"" + ""'Extra Bookmarks','Extra Bookmarks',NULL,NULL,X'C2881000',"" + ""X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(13,687,687,"" LEGACY_PROTO_TIME_VALS(13) +- "",-917504,10,"" ++ ""INSERT INTO 'metas' VALUES(13,687,687,129079957985300000,"" ++ ""129079957985300000,129079957985300000,129079957985300000,-917504,10,"" + ""'s_ID_13','s_ID_6','s_ID_6','s_ID_11','s_ID_12',0,0,0,0,0,0,"" + ""'ICANN | Internet Corporation for Assigned Names and Numbers',"" + ""'ICANN | Internet Corporation for Assigned Names and Numbers',NULL,"" + ""NULL,X'C28810240A15687474703A2F2F7777772E6963616E6E2E636F6D2F120B504"" + ""E474158463041414646',X'C28810200A15687474703A2F2F7777772E6963616E6E2"" + ""E636F6D2F120744414146415346');"" +- ""INSERT INTO 'metas' VALUES(14,692,692,"" LEGACY_PROTO_TIME_VALS(14) +- "",1048576,11,"" ++ ""INSERT INTO 'metas' VALUES(14,692,692,129079958383000000,"" ++ ""129079958383000000,129079958383000000,129079958383000000,1048576,11,"" + ""'s_ID_14','s_ID_6','s_ID_6','s_ID_12','r',0,0,0,0,0,0,"" + ""'The WebKit Open Source Project','The WebKit Open Source Project',"" + ""NULL,NULL,""""X'C288101A0A12687474703A2F2F7765626B69742E6F72672F120450"" +@@ -1103,69 +880,69 @@ void MigrationTest::SetUpVersion74Database() { + ""efault 0,server_is_del bit default 0,non_unique_name varchar,server"" + ""_non_unique_name varchar(255),unique_server_tag varchar,unique_clie"" + ""nt_tag varchar,specifics blob,server_specifics blob);"" +- ""INSERT INTO 'metas' VALUES(1,-1,0,"" LEGACY_PROTO_TIME_VALS(1) +- "",0,0,'r','r','r','r','r',0,0,0,1,0,0,NULL,NULL,NULL,NULL,X'',X'"" ++ ""INSERT INTO 'metas' VALUES(1,-1,0,129079956640320000,0,1290799566403200"" ++ ""00,0,0,0,'r','r','r','r','r',0,0,0,1,0,0,NULL,NULL,NULL,NULL,X'',X'"" + ""');"" +- ""INSERT INTO 'metas' VALUES(2,669,669,"" LEGACY_PROTO_TIME_VALS(2) +- "",-2097152,4,'s_ID_2','s_ID"" ++ ""INSERT INTO 'metas' VALUES(2,669,669,128976886618480000,128976886618480"" ++ ""000,128976886618480000,128976886618480000,-2097152,4,'s_ID_2','s_ID"" + ""_9','s_ID_9','s_ID_2','s_ID_2',0,0,1,0,0,1,'Deleted Item','Deleted "" + ""Item',NULL,NULL,X'C28810220A16687474703A2F2F7777772E676F6F676C652E6"" + ""36F6D2F12084141534741534741',X'C28810260A17687474703A2F2F7777772E67"" + ""6F6F676C652E636F6D2F32120B4153414447414447414447');"" +- ""INSERT INTO 'metas' VALUES(4,681,681,"" LEGACY_PROTO_TIME_VALS(4) +- "",-3145728,3,'s_ID_4','s_ID"" ++ ""INSERT INTO 'metas' VALUES(4,681,681,129002163642690000,129002163642690"" ++ ""000,129002163642690000,129002163642690000,-3145728,3,'s_ID_4','s_ID"" + ""_9','s_ID_9','s_ID_4','s_ID_4',0,0,1,0,0,1,'Welcome to Chromium','W"" + ""elcome to Chromium',NULL,NULL,X'C28810350A31687474703A2F2F7777772E6"" + ""76F6F676C652E636F6D2F6368726F6D652F696E746C2F656E2F77656C636F6D652E"" + ""68746D6C1200',X'C28810350A31687474703A2F2F7777772E676F6F676C652E636"" + ""F6D2F6368726F6D652F696E746C2F656E2F77656C636F6D652E68746D6C1200');"" +- ""INSERT INTO 'metas' VALUES(5,677,677,"" LEGACY_PROTO_TIME_VALS(5) +- "",1048576,7,'s_ID_5','s_ID_"" ++ ""INSERT INTO 'metas' VALUES(5,677,677,129001555500000000,129001555500000"" ++ ""000,129001555500000000,129001555500000000,1048576,7,'s_ID_5','s_ID_"" + ""9','s_ID_9','s_ID_5','s_ID_5',0,0,1,0,0,1,'Google','Google',NULL,NU"" + ""LL,X'C28810220A16687474703A2F2F7777772E676F6F676C652E636F6D2F120841"" + ""47415347415347',X'C28810220A16687474703A2F2F7777772E676F6F676C652E6"" + ""36F6D2F12084147464447415347');"" +- ""INSERT INTO 'metas' VALUES(6,694,694,"" LEGACY_PROTO_TIME_VALS(6) +- "",-4194304,6,'s_ID_6','s_ID"" ++ ""INSERT INTO 'metas' VALUES(6,694,694,129053976170000000,129053976170000"" ++ ""000,129053976170000000,129053976170000000,-4194304,6,'s_ID_6','s_ID"" + ""_9','s_ID_9','r','r',0,0,0,1,1,0,'The Internet','The Internet',NULL"" + "",NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(7,663,663,"" LEGACY_PROTO_TIME_VALS(7) +- "",1048576,0,'s_ID_7','r','r"" ++ ""INSERT INTO 'metas' VALUES(7,663,663,128976864758480000,128976864758480"" ++ ""000,128976864758480000,128976864758480000,1048576,0,'s_ID_7','r','r"" + ""','r','r',0,0,0,1,1,0,'Google Chrome','Google Chrome','google_chrom"" + ""e',NULL,NULL,NULL);"" +- ""INSERT INTO 'metas' VALUES(8,664,664,"" LEGACY_PROTO_TIME_VALS(8) +- "",1048576,0,'s_ID_8','s_ID_"" ++ ""INSERT INTO 'metas' VALUES(8,664,664,128976864758480000,128976864758480"" ++ ""000,128976864758480000,128976864758480000,1048576,0,'s_ID_8','s_ID_"" + ""7','s_ID_7','r','r',0,0,0,1,1,0,'Bookmarks','Bookmarks','google_chr"" + ""ome_bookmarks',NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(9,665,665,"" LEGACY_PROTO_TIME_VALS(9) +- "",1048576,1,'s_ID_9','s_ID_"" ++ ""INSERT INTO 'metas' VALUES(9,665,665,128976864758480000,128976864758480"" ++ ""000,128976864758480000,128976864758480000,1048576,1,'s_ID_9','s_ID_"" + ""8','s_ID_8','r','s_ID_10',0,0,0,1,1,0,'Bookmark Bar','Bookmark Bar'"" + "",'bookmark_bar',NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(10,666,666,"" LEGACY_PROTO_TIME_VALS(10) +- "",2097152,2,'s_ID_10','s_I"" ++ ""INSERT INTO 'metas' VALUES(10,666,666,128976864758480000,12897686475848"" ++ ""0000,128976864758480000,128976864758480000,2097152,2,'s_ID_10','s_I"" + ""D_8','s_ID_8','s_ID_9','r',0,0,0,1,1,0,'Other Bookmarks','Other Boo"" + ""kmarks','other_bookmarks',NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(11,683,683,"" LEGACY_PROTO_TIME_VALS(11) +- "",-1048576,8,'s_ID_11','s_"" ++ ""INSERT INTO 'metas' VALUES(11,683,683,129079956948440000,12907995694844"" ++ ""0000,129079956948440000,129079956948440000,-1048576,8,'s_ID_11','s_"" + ""ID_6','s_ID_6','r','s_ID_13',0,0,0,0,0,0,'Home (The Chromium Projec"" + ""ts)','Home (The Chromium Projects)',NULL,NULL,X'C28810220A186874747"" + ""03A2F2F6465762E6368726F6D69756D2E6F72672F1206414741545741',X'C28810"" + ""290A1D687474703A2F2F6465762E6368726F6D69756D2E6F72672F6F74686572120"" + ""84146414756415346');"" +- ""INSERT INTO 'metas' VALUES(12,685,685,"" LEGACY_PROTO_TIME_VALS(12) +- "",0,9,'s_ID_12','s_ID_6','"" ++ ""INSERT INTO 'metas' VALUES(12,685,685,129079957513650000,12907995751365"" ++ ""0000,129079957513650000,129079957513650000,0,9,'s_ID_12','s_ID_6','"" + ""s_ID_6','s_ID_13','s_ID_14',0,0,0,1,1,0,'Extra Bookmarks','Extra Bo"" + ""okmarks',NULL,NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(13,687,687,"" LEGACY_PROTO_TIME_VALS(13) +- "",-917504,10,'s_ID_13','s_"" ++ ""INSERT INTO 'metas' VALUES(13,687,687,129079957985300000,12907995798530"" ++ ""0000,129079957985300000,129079957985300000,-917504,10,'s_ID_13','s_"" + ""ID_6','s_ID_6','s_ID_11','s_ID_12',0,0,0,0,0,0,'ICANN | Internet Co"" + ""rporation for Assigned Names and Numbers','ICANN | Internet Corpora"" + ""tion for Assigned Names and Numbers',NULL,NULL,X'C28810240A15687474"" + ""703A2F2F7777772E6963616E6E2E636F6D2F120B504E474158463041414646',X'C"" + ""28810200A15687474703A2F2F7777772E6963616E6E2E636F6D2F12074441414641"" + ""5346');"" +- ""INSERT INTO 'metas' VALUES(14,692,692,"" LEGACY_PROTO_TIME_VALS(14) +- "",1048576,11,'s_ID_14','s_"" ++ ""INSERT INTO 'metas' VALUES(14,692,692,129079958383000000,12907995838300"" ++ ""0000,129079958383000000,129079958383000000,1048576,11,'s_ID_14','s_"" + ""ID_6','s_ID_6','s_ID_12','r',0,0,0,0,0,0,'The WebKit Open Source Pr"" + ""oject','The WebKit Open Source Project',NULL,NULL,X'C288101A0A12687"" + ""474703A2F2F7765626B69742E6F72672F1204504E4758',X'C288101C0A13687474"" +@@ -1206,72 +983,72 @@ void MigrationTest::SetUpVersion75Database() { + ""dir bit default 0,server_is_del bit default 0,non_unique_name varc"" + ""har,server_non_unique_name varchar(255),unique_server_tag varchar,"" + ""unique_client_tag varchar,specifics blob,server_specifics blob);"" +- ""INSERT INTO 'metas' VALUES(1,-1,0,"" LEGACY_PROTO_TIME_VALS(1) +- "",0,0,'r','r','r','r','r',0,0,0,1,0,0,NULL,NULL,NULL,NUL"" ++ ""INSERT INTO 'metas' VALUES(1,-1,0,129079956640320000,0,129079956640"" ++ ""320000,0,0,0,'r','r','r','r','r',0,0,0,1,0,0,NULL,NULL,NULL,NUL"" + ""L,X'',X'');"" +- ""INSERT INTO 'metas' VALUES(2,669,669,"" LEGACY_PROTO_TIME_VALS(2) +- "",-2097152,4,'s_ID_"" ++ ""INSERT INTO 'metas' VALUES(2,669,669,128976886618480000,12897688661"" ++ ""8480000,128976886618480000,128976886618480000,-2097152,4,'s_ID_"" + ""2','s_ID_9','s_ID_9','s_ID_2','s_ID_2',0,0,1,0,0,1,'Deleted Ite"" + ""m','Deleted Item',NULL,NULL,X'C28810220A16687474703A2F2F7777772"" + ""E676F6F676C652E636F6D2F12084141534741534741',X'C28810260A176874"" + ""74703A2F2F7777772E676F6F676C652E636F6D2F32120B41534144474144474"" + ""14447');"" +- ""INSERT INTO 'metas' VALUES(4,681,681,"" LEGACY_PROTO_TIME_VALS(4) +- "",-3145728,3,'s_ID_"" ++ ""INSERT INTO 'metas' VALUES(4,681,681,129002163642690000,12900216364"" ++ ""2690000,129002163642690000,129002163642690000,-3145728,3,'s_ID_"" + ""4','s_ID_9','s_ID_9','s_ID_4','s_ID_4',0,0,1,0,0,1,'Welcome to "" + ""Chromium','Welcome to Chromium',NULL,NULL,X'C28810350A316874747"" + ""03A2F2F7777772E676F6F676C652E636F6D2F6368726F6D652F696E746C2F65"" + ""6E2F77656C636F6D652E68746D6C1200',X'C28810350A31687474703A2F2F7"" + ""777772E676F6F676C652E636F6D2F6368726F6D652F696E746C2F656E2F7765"" + ""6C636F6D652E68746D6C1200');"" +- ""INSERT INTO 'metas' VALUES(5,677,677,"" LEGACY_PROTO_TIME_VALS(5) +- "",1048576,7,'s_ID_5"" ++ ""INSERT INTO 'metas' VALUES(5,677,677,129001555500000000,12900155550"" ++ ""0000000,129001555500000000,129001555500000000,1048576,7,'s_ID_5"" + ""','s_ID_9','s_ID_9','s_ID_5','s_ID_5',0,0,1,0,0,1,'Google','Goo"" + ""gle',NULL,NULL,X'C28810220A16687474703A2F2F7777772E676F6F676C65"" + ""2E636F6D2F12084147415347415347',X'C28810220A16687474703A2F2F777"" + ""7772E676F6F676C652E636F6D2F12084147464447415347');"" +- ""INSERT INTO 'metas' VALUES(6,694,694,"" LEGACY_PROTO_TIME_VALS(6) +- "",-4194304,6,'s_ID_"" ++ ""INSERT INTO 'metas' VALUES(6,694,694,129053976170000000,12905397617"" ++ ""0000000,129053976170000000,129053976170000000,-4194304,6,'s_ID_"" + ""6','s_ID_9','s_ID_9','r','r',0,0,0,1,1,0,'The Internet','The In"" + ""ternet',NULL,NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(7,663,663,"" LEGACY_PROTO_TIME_VALS(7) +- "",1048576,0,'s_ID_7"" ++ ""INSERT INTO 'metas' VALUES(7,663,663,128976864758480000,12897686475"" ++ ""8480000,128976864758480000,128976864758480000,1048576,0,'s_ID_7"" + ""','r','r','r','r',0,0,0,1,1,0,'Google Chrome','Google Chrome','"" + ""google_chrome',NULL,NULL,NULL);"" +- ""INSERT INTO 'metas' VALUES(8,664,664,"" LEGACY_PROTO_TIME_VALS(8) +- "",1048576,0,'s_ID_8"" ++ ""INSERT INTO 'metas' VALUES(8,664,664,128976864758480000,12897686475"" ++ ""8480000,128976864758480000,128976864758480000,1048576,0,'s_ID_8"" + ""','s_ID_7','s_ID_7','r','r',0,0,0,1,1,0,'Bookmarks','Bookmarks'"" + "",'google_chrome_bookmarks',NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(9,665,665,"" LEGACY_PROTO_TIME_VALS(9) +- "",1048576,1,'s_ID_9"" ++ ""INSERT INTO 'metas' VALUES(9,665,665,128976864758480000,12897686475"" ++ ""8480000,128976864758480000,128976864758480000,1048576,1,'s_ID_9"" + ""','s_ID_8','s_ID_8','r','s_ID_10',0,0,0,1,1,0,'Bookmark Bar','B"" + ""ookmark Bar','bookmark_bar',NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(10,666,666,"" LEGACY_PROTO_TIME_VALS(10) +- "",2097152,2,'s_ID_"" ++ ""INSERT INTO 'metas' VALUES(10,666,666,128976864758480000,1289768647"" ++ ""58480000,128976864758480000,128976864758480000,2097152,2,'s_ID_"" + ""10','s_ID_8','s_ID_8','s_ID_9','r',0,0,0,1,1,0,'Other Bookmarks"" + ""','Other Bookmarks','other_bookmarks',NULL,X'C2881000',X'C28810"" + ""00');"" +- ""INSERT INTO 'metas' VALUES(11,683,683,"" LEGACY_PROTO_TIME_VALS(11) +- "",-1048576,8,'s_ID"" ++ ""INSERT INTO 'metas' VALUES(11,683,683,129079956948440000,1290799569"" ++ ""48440000,129079956948440000,129079956948440000,-1048576,8,'s_ID"" + ""_11','s_ID_6','s_ID_6','r','s_ID_13',0,0,0,0,0,0,'Home (The Chr"" + ""omium Projects)','Home (The Chromium Projects)',NULL,NULL,X'C28"" + ""810220A18687474703A2F2F6465762E6368726F6D69756D2E6F72672F120641"" + ""4741545741',X'C28810290A1D687474703A2F2F6465762E6368726F6D69756"" + ""D2E6F72672F6F7468657212084146414756415346');"" +- ""INSERT INTO 'metas' VALUES(12,685,685,"" LEGACY_PROTO_TIME_VALS(12) +- "",0,9,'s_ID_12','s"" ++ ""INSERT INTO 'metas' VALUES(12,685,685,129079957513650000,1290799575"" ++ ""13650000,129079957513650000,129079957513650000,0,9,'s_ID_12','s"" + ""_ID_6','s_ID_6','s_ID_13','s_ID_14',0,0,0,1,1,0,'Extra Bookmark"" + ""s','Extra Bookmarks',NULL,NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(13,687,687,"" LEGACY_PROTO_TIME_VALS(13) +- "",-917504,10,'s_ID"" ++ ""INSERT INTO 'metas' VALUES(13,687,687,129079957985300000,1290799579"" ++ ""85300000,129079957985300000,129079957985300000,-917504,10,'s_ID"" + ""_13','s_ID_6','s_ID_6','s_ID_11','s_ID_12',0,0,0,0,0,0,'ICANN |"" + "" Internet Corporation for Assigned Names and Numbers','ICANN | "" + ""Internet Corporation for Assigned Names and Numbers',NULL,NULL,"" + ""X'C28810240A15687474703A2F2F7777772E6963616E6E2E636F6D2F120B504"" + ""E474158463041414646',X'C28810200A15687474703A2F2F7777772E696361"" + ""6E6E2E636F6D2F120744414146415346');"" +- ""INSERT INTO 'metas' VALUES(14,692,692,"" LEGACY_PROTO_TIME_VALS(14) +- "",1048576,11,'s_ID"" ++ ""INSERT INTO 'metas' VALUES(14,692,692,129079958383000000,1290799583"" ++ ""83000000,129079958383000000,129079958383000000,1048576,11,'s_ID"" + ""_14','s_ID_6','s_ID_6','s_ID_12','r',0,0,0,0,0,0,'The WebKit Op"" + ""en Source Project','The WebKit Open Source Project',NULL,NULL,X"" + ""'C288101A0A12687474703A2F2F7765626B69742E6F72672F1204504E4758',"" +@@ -1281,104 +1058,6 @@ void MigrationTest::SetUpVersion75Database() { + ASSERT_TRUE(connection.CommitTransaction()); + } + +-void MigrationTest::SetUpVersion76Database() { +- sql::Connection connection; +- ASSERT_TRUE(connection.Open(GetDatabasePath())); +- ASSERT_TRUE(connection.BeginTransaction()); +- ASSERT_TRUE(connection.Execute( +- ""CREATE TABLE share_version (id VARCHAR(128) primary key, data INT);"" +- ""INSERT INTO 'share_version' VALUES('nick@chromium.org',76);"" +- ""CREATE TABLE models (model_id BLOB primary key, progress_marker BLOB, in"" +- ""itial_sync_ended BOOLEAN default 0);"" +- ""INSERT INTO 'models' VALUES(X'C2881000',X'0888810218B605',1);"" +- ""CREATE TABLE 'metas'(metahandle bigint primary key ON CONFLICT FAIL,base"" +- ""_version bigint default -1,server_version bigint default 0,mtime big"" +- ""int default 0,server_mtime bigint default 0,ctime bigint default 0,s"" +- ""erver_ctime bigint default 0,server_position_in_parent bigint defaul"" +- ""t 0,local_external_id bigint default 0,id varchar(255) default 'r',p"" +- ""arent_id varchar(255) default 'r',server_parent_id varchar(255) defa"" +- ""ult 'r',prev_id varchar(255) default 'r',next_id varchar(255) defaul"" +- ""t 'r',is_unsynced bit default 0,is_unapplied_update bit default 0,is"" +- ""_del bit default 0,is_dir bit default 0,server_is_dir bit default 0,"" +- ""server_is_del bit default 0,non_unique_name varchar,server_non_uniqu"" +- ""e_name varchar(255),unique_server_tag varchar,unique_client_tag varc"" +- ""har,specifics blob,server_specifics blob);"" +- ""INSERT INTO 'metas' VALUES(1,-1,0,"" LEGACY_PROTO_TIME_VALS(1) +- "",0,0,'r','r','r','r','r',0,0,0,1,0,0,NULL,NULL,NULL,NULL,X'',X'')"" +- "";"" +- ""INSERT INTO 'metas' VALUES(2,669,669,"" LEGACY_PROTO_TIME_VALS(2) +- "",-2097152,4,'s_ID_2','s_ID_9"" +- ""','s_ID_9','s_ID_2','s_ID_2',0,0,1,0,0,1,'Deleted Item','Deleted Ite"" +- ""m',NULL,NULL,X'C28810220A16687474703A2F2F7777772E676F6F676C652E636F6"" +- ""D2F12084141534741534741',X'C28810260A17687474703A2F2F7777772E676F6F6"" +- ""76C652E636F6D2F32120B4153414447414447414447');"" +- ""INSERT INTO 'metas' VALUES(4,681,681,"" LEGACY_PROTO_TIME_VALS(4) +- "",-3145728,3,'s_ID_4','s_ID_9"" +- ""','s_ID_9','s_ID_4','s_ID_4',0,0,1,0,0,1,'Welcome to Chromium','Welc"" +- ""ome to Chromium',NULL,NULL,X'C28810350A31687474703A2F2F7777772E676F6"" +- ""F676C652E636F6D2F6368726F6D652F696E746C2F656E2F77656C636F6D652E68746"" +- ""D6C1200',X'C28810350A31687474703A2F2F7777772E676F6F676C652E636F6D2F6"" +- ""368726F6D652F696E746C2F656E2F77656C636F6D652E68746D6C1200');"" +- ""INSERT INTO 'metas' VALUES(5,677,677,"" LEGACY_PROTO_TIME_VALS(5) +- "",1048576,7,'s_ID_5','s_ID_9'"" +- "",'s_ID_9','s_ID_5','s_ID_5',0,0,1,0,0,1,'Google','Google',NULL,NULL,"" +- ""X'C28810220A16687474703A2F2F7777772E676F6F676C652E636F6D2F1208414741"" +- ""5347415347',X'C28810220A16687474703A2F2F7777772E676F6F676C652E636F6D"" +- ""2F12084147464447415347');"" +- ""INSERT INTO 'metas' VALUES(6,694,694,"" LEGACY_PROTO_TIME_VALS(6) +- "",-4194304,6,'s_ID_6','s_ID_9"" +- ""','s_ID_9','r','r',0,0,0,1,1,0,'The Internet','The Internet',NULL,NU"" +- ""LL,X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(7,663,663,"" LEGACY_PROTO_TIME_VALS(7) +- "",1048576,0,'s_ID_7','r','r',"" +- ""'r','r',0,0,0,1,1,0,'Google Chrome','Google Chrome','google_chrome',"" +- ""NULL,NULL,NULL);"" +- ""INSERT INTO 'metas' VALUES(8,664,664,"" LEGACY_PROTO_TIME_VALS(8) +- "",1048576,0,'s_ID_8','s_ID_7'"" +- "",'s_ID_7','r','r',0,0,0,1,1,0,'Bookmarks','Bookmarks','google_chrome"" +- ""_bookmarks',NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(9,665,665,"" LEGACY_PROTO_TIME_VALS(9) +- "",1048576,1,'s_ID_9','s_ID_8'"" +- "",'s_ID_8','r','s_ID_10',0,0,0,1,1,0,'Bookmark Bar','Bookmark Bar','b"" +- ""ookmark_bar',NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(10,666,666,"" LEGACY_PROTO_TIME_VALS(10) +- "",2097152,2,'s_ID_10','s_ID_"" +- ""8','s_ID_8','s_ID_9','r',0,0,0,1,1,0,'Other Bookmarks','Other Bookma"" +- ""rks','other_bookmarks',NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(11,683,683,"" LEGACY_PROTO_TIME_VALS(11) +- "",-1048576,8,'s_ID_11','s_ID"" +- ""_6','s_ID_6','r','s_ID_13',0,0,0,0,0,0,'Home (The Chromium Projects)"" +- ""','Home (The Chromium Projects)',NULL,NULL,X'C28810220A18687474703A2"" +- ""F2F6465762E6368726F6D69756D2E6F72672F1206414741545741',X'C28810290A1"" +- ""D687474703A2F2F6465762E6368726F6D69756D2E6F72672F6F74686572120841464"" +- ""14756415346');"" +- ""INSERT INTO 'metas' VALUES(12,685,685,"" LEGACY_PROTO_TIME_VALS(12) +- "",0,9,'s_ID_12','s_ID_6','s_"" +- ""ID_6','s_ID_13','s_ID_14',0,0,0,1,1,0,'Extra Bookmarks','Extra Bookm"" +- ""arks',NULL,NULL,X'C2881000',X'C2881000');"" +- ""INSERT INTO 'metas' VALUES(13,687,687,"" LEGACY_PROTO_TIME_VALS(13) +- "",-917504,10,'s_ID_13','s_ID"" +- ""_6','s_ID_6','s_ID_11','s_ID_12',0,0,0,0,0,0,'ICANN | Internet Corpo"" +- ""ration for Assigned Names and Numbers','ICANN | Internet Corporation"" +- "" for Assigned Names and Numbers',NULL,NULL,X'C28810240A15687474703A2"" +- ""F2F7777772E6963616E6E2E636F6D2F120B504E474158463041414646',X'C288102"" +- ""00A15687474703A2F2F7777772E6963616E6E2E636F6D2F120744414146415346');"" +- ""INSERT INTO 'metas' VALUES(14,692,692,"" LEGACY_PROTO_TIME_VALS(14) +- "",1048576,11,'s_ID_14','s_ID"" +- ""_6','s_ID_6','s_ID_12','r',0,0,0,0,0,0,'The WebKit Open Source Proje"" +- ""ct','The WebKit Open Source Project',NULL,NULL,X'C288101A0A126874747"" +- ""03A2F2F7765626B69742E6F72672F1204504E4758',X'C288101C0A13687474703A2"" +- ""F2F7765626B69742E6F72672F781205504E473259');"" +- ""CREATE TABLE 'share_info' (id TEXT primary key, name TEXT, store_birthda"" +- ""y TEXT, db_create_version TEXT, db_create_time INT, next_id INT defa"" +- ""ult -2, cache_guid TEXT , notification_state BLOB);"" +- ""INSERT INTO 'share_info' VALUES('nick@chromium.org','nick@chromium.org',"" +- ""'c27e9f59-08ca-46f8-b0cc-f16a2ed778bb','Unknown',1263522064,-65542,'"" +- ""9010788312004066376x-6609234393368420856x',NULL);"" +- )); +- ASSERT_TRUE(connection.CommitTransaction()); +-} +- + TEST_F(DirectoryBackingStoreTest, MigrateVersion67To68) { + SetUpVersion67Database(); + +@@ -1698,37 +1377,6 @@ TEST_F(DirectoryBackingStoreTest, MigrateVersion75To76) { + ""autofill_profiles_added_during_migration"")); + } + +-TEST_F(DirectoryBackingStoreTest, MigrateVersion76To77) { +- SetUpVersion76Database(); +- +- scoped_ptr dbs( +- new DirectoryBackingStore(GetUsername(), GetDatabasePath())); +- dbs->BeginLoad(); +- ASSERT_FALSE(dbs->needs_column_refresh_); +- +- EXPECT_EQ(GetExpectedLegacyMetaProtoTimes(), +- GetMetaProtoTimes(dbs->load_dbhandle_)); +- // Since we the proto times are expected to be in a legacy format, +- // they may not be compatible with ProtoTimeToTime, so we don't call +- // ExpectTimes(). +- +- ASSERT_TRUE(dbs->MigrateVersion76To77()); +- ASSERT_EQ(77, dbs->GetVersion()); +- +- EXPECT_EQ(GetExpectedMetaProtoTimes(), +- GetMetaProtoTimes(dbs->load_dbhandle_)); +- +- { +- MetahandlesIndex index; +- STLElementDeleter index_deleter(&index); +- dbs->LoadEntries(&index); +- ExpectTimes(index, GetExpectedMetaTimes()); +- } +- +- dbs->EndLoad(); +- ASSERT_FALSE(dbs->needs_column_refresh_); +-} +- + TEST_P(MigrationTest, ToCurrentVersion) { + switch (GetParam()) { + case 67: +@@ -1758,9 +1406,6 @@ TEST_P(MigrationTest, ToCurrentVersion) { + case 75: + SetUpVersion75Database(); + break; +- case 76: +- SetUpVersion76Database(); +- break; + default: + // If you see this error, it may mean that you've increased the + // database version number but you haven't finished adding unit tests +@@ -1771,13 +1416,11 @@ TEST_P(MigrationTest, ToCurrentVersion) { + // 2. Set a breakpoint in this function and run the unit test. + // 3. Allow this test to run to completion (step out of the call), + // without allowing ~MigrationTest to execute. +- // 4. Examine this->temp_dir_ to determine the location of the ++ // 4. Examine this->scoped_dir_ to determine the location of the + // test database (it is currently of the version you need). +- // 5. Dump this using the sqlite3 command line tool: ++ // 5. Dump this using the sqlite command line tool: + // > .output foo_dump.sql + // > .dump +- // 6. Replace the timestamp columns with META_PROTO_TIMES(x) (or +- // LEGACY_META_PROTO_TIMES(x) if before Version 77). + FAIL() << ""Need to supply database dump for version "" << GetParam(); + } + +@@ -1870,11 +1513,6 @@ TEST_P(MigrationTest, ToCurrentVersion) { + MetahandlesIndex index; + STLElementDeleter index_deleter(&index); + dbs->LoadEntries(&index); +- +- EXPECT_EQ(GetExpectedMetaProtoTimes(), +- GetMetaProtoTimes(dbs->load_dbhandle_)); +- ExpectTimes(index, GetExpectedMetaTimes()); +- + dbs->EndLoad(); + + MetahandlesIndex::iterator it = index.begin();",3048,3379,4096 +10810,"static bool LookupAltName(const String& name, String& altName) +{ + struct FontCodepage { + const WCHAR* name; + int codePage; + }; + + struct NamePair { + const WCHAR* name; + FontCodepage altNameCodepage; + }; + + const int japaneseCodepage = 932; + const int simplifiedChineseCodepage = 936; + const int koreanCodepage = 949; + const int traditionalChineseCodepage = 950; + + static const NamePair namePairs[] = { + {L""\xFF2D\xFF33 \xFF30\x30B4\x30B7\x30C3\x30AF"", {L""MS PGothic"", japaneseCodepage}}, + {L""ms pgothic"", {L""\xFF2D\xFF33 \xFF30\x30B4\x30B7\x30C3\x30AF"", japaneseCodepage}}, + {L""\xFF2D\xFF33 \xFF30\x660E\x671D"", {L""MS PMincho"", japaneseCodepage}}, + {L""ms pmincho"", {L""\xFF2D\xFF33 \xFF30\x660E\x671D"", japaneseCodepage}}, + {L""\xFF2D\xFF33 \x30B4\x30B7\x30C3\x30AF"", {L""MS Gothic"", japaneseCodepage}}, + {L""ms gothic"", {L""\xFF2D\xFF33 \x30B4\x30B7\x30C3\x30AF"", japaneseCodepage}}, + {L""\xFF2D\xFF33 \x660E\x671D"", {L""MS Mincho"", japaneseCodepage}}, + {L""ms mincho"", {L""\xFF2D\xFF33 \x660E\x671D"", japaneseCodepage}}, + {L""\x30E1\x30A4\x30EA\x30AA"", {L""Meiryo"", japaneseCodepage}}, + {L""meiryo"", {L""\x30E1\x30A4\x30EA\x30AA"", japaneseCodepage}}, + {L""\xBC14\xD0D5"", {L""Batang"", koreanCodepage}}, + {L""batang"", {L""\xBC14\xD0D5"", koreanCodepage}}, + {L""\xBC14\xD0D5\xCCB4"", {L""Batangche"", koreanCodepage}}, + {L""batangche"", {L""\xBC14\xD0D5\xCCB4"", koreanCodepage}}, + {L""\xAD74\xB9BC"", {L""Gulim"", koreanCodepage}}, + {L""gulim"", {L""\xAD74\xB9BC"", koreanCodepage}}, + {L""\xAD74\xB9BC\xCCB4"", {L""Gulimche"", koreanCodepage}}, + {L""gulimche"", {L""\xAD74\xB9BC\xCCB4"", koreanCodepage}}, + {L""\xB3CB\xC6C0"", {L""Dotum"", koreanCodepage}}, + {L""dotum"", {L""\xB3CB\xC6C0"", koreanCodepage}}, + {L""\xB3CB\xC6C0\xCCB4"", {L""Dotumche"", koreanCodepage}}, + {L""dotumche"", {L""\xB3CB\xC6C0\xCCB4"", koreanCodepage}}, + {L""\xAD81\xC11C"", {L""Gungsuh"", koreanCodepage}}, + {L""gungsuh"", {L""\xAD81\xC11C"", koreanCodepage}}, + {L""\xAD81\xC11C\xCCB4"", {L""Gungsuhche"", koreanCodepage}}, + {L""gungsuhche"", {L""\xAD81\xC11C\xCCB4"", koreanCodepage}}, + {L""\xB9D1\xC740 \xACE0\xB515"", {L""Malgun Gothic"", koreanCodepage}}, + {L""malgun gothic"", {L""\xB9D1\xC740 \xACE0\xB515"", koreanCodepage}}, + {L""\x5B8B\x4F53"", {L""SimSun"", simplifiedChineseCodepage}}, + {L""simsun"", {L""\x5B8B\x4F53"", simplifiedChineseCodepage}}, + {L""\x5B8B\x4F53-ExtB"", {L""SimSun-ExtB"", simplifiedChineseCodepage}}, + {L""simsun-extb"", {L""\x5B8B\x4F53-extb"", simplifiedChineseCodepage}}, + {L""\x9ED1\x4F53"", {L""SimHei"", simplifiedChineseCodepage}}, + {L""simhei"", {L""\x9ED1\x4F53"", simplifiedChineseCodepage}}, + {L""\x65B0\x5B8B\x4F53"", {L""NSimSun"", simplifiedChineseCodepage}}, + {L""nsimsun"", {L""\x65B0\x5B8B\x4F53"", simplifiedChineseCodepage}}, + {L""\x5FAE\x8F6F\x96C5\x9ED1"", {L""Microsoft Yahei"", simplifiedChineseCodepage}}, + {L""microsoft yahei"", {L""\x5FAE\x8F6F\x96C5\x9ED1"", simplifiedChineseCodepage}}, + {L""\x4EFF\x5B8B"", {L""FangSong"", simplifiedChineseCodepage}}, + {L""fangsong"", {L""\x4EFF\x5B8B"", simplifiedChineseCodepage}}, + {L""\x6977\x4F53"", {L""KaiTi"", simplifiedChineseCodepage}}, + {L""kaiti"", {L""\x6977\x4F53"", simplifiedChineseCodepage}}, + {L""\x4EFF\x5B8B_GB2312"", {L""FangSong_GB2312"", simplifiedChineseCodepage}}, + {L""fangsong_gb2312"", {L""\x4EFF\x5B8B_gb2312"", simplifiedChineseCodepage}}, + {L""\x6977\x4F53"", {L""KaiTi_GB2312"", simplifiedChineseCodepage}}, + {L""kaiti_gb2312"", {L""\x6977\x4F53_gb2312"", simplifiedChineseCodepage}}, + {L""\x65B0\x7D30\x660E\x9AD4"", {L""PMingLiu"", traditionalChineseCodepage}}, + {L""pmingliu"", {L""\x65B0\x7D30\x660E\x9AD4"", traditionalChineseCodepage}}, + {L""\x65B0\x7D30\x660E\x9AD4-ExtB"", {L""PMingLiu-ExtB"", traditionalChineseCodepage}}, + {L""pmingliu-extb"", {L""\x65B0\x7D30\x660E\x9AD4-extb"", traditionalChineseCodepage}}, + {L""\x7D30\x660E\x9AD4"", {L""MingLiu"", traditionalChineseCodepage}}, + {L""mingliu"", {L""\x7D30\x660E\x9AD4"", traditionalChineseCodepage}}, + {L""\x7D30\x660E\x9AD4-ExtB"", {L""MingLiu-ExtB"", traditionalChineseCodepage}}, + {L""mingliu-extb"", {L""x65B0\x7D30\x660E\x9AD4-extb"", traditionalChineseCodepage}}, + {L""\x5FAE\x8EDF\x6B63\x9ED1\x9AD4"", {L""Microsoft JhengHei"", traditionalChineseCodepage}}, + {L""microsoft jhengHei"", {L""\x5FAE\x8EDF\x6B63\x9ED1\x9AD4"", traditionalChineseCodepage}}, + {L""\x6A19\x6977\x9AD4"", {L""DFKai-SB"", traditionalChineseCodepage}}, + {L""dfkai-sb"", {L""\x6A19\x6977\x9AD4"", traditionalChineseCodepage}}, + {L""\x6587\x6cc9\x9a5b\x6b63\x9ed1"", {L""WenQuanYi Zen Hei"", traditionalChineseCodepage}}, + {L""wenquanyi zen hei"", {L""\x6587\x6cc9\x9a5b\x6b63\x9ed1"", traditionalChineseCodepage}}, + {L""\x6587\x6cc9\x9a7f\x6b63\x9ed1"", {L""WenQuanYi Zen Hei"", simplifiedChineseCodepage}}, + {L""wenquanyi zen hei"", {L""\x6587\x6cc9\x9a7f\x6b63\x9ed1"", simplifiedChineseCodepage}}, + {L""\x6587\x9f0e\x0050\x004c\x7d30\x4e0a\x6d77\x5b8b\x0055\x006e\x0069"", + {L""AR PL ShanHeiSun Uni"", traditionalChineseCodepage}}, + {L""ar pl shanheisun uni"", + {L""\x6587\x9f0e\x0050\x004c\x7d30\x4e0a\x6d77\x5b8b\x0055\x006e\x0069"", traditionalChineseCodepage}}, + {L""\x6587\x9f0e\x0050\x004c\x7ec6\x4e0a\x6d77\x5b8b\x0055\x006e\x0069"", + {L""AR PL ShanHeiSun Uni"", simplifiedChineseCodepage}}, + {L""ar pl shanheisun uni"", + {L""\x6587\x9f0e\x0050\x004c\x7ec6\x4e0a\x6d77\x5b8b\x0055\x006e\x0069"", simplifiedChineseCodepage}}, + {L""\x6587\x0050\x004C\x4E2D\x6977\x0055\x006E\x0069"", {L""AR PL ZenKai Uni"", traditionalChineseCodepage}}, + {L""ar pl zenkai uni"", {L""\x6587\x0050\x004C\x4E2D\x6977\x0055\x006E\x0069"", traditionalChineseCodepage}}, + {L""\x6587\x0050\x004C\x4E2D\x6977\x0055\x006E\x0069"", {L""AR PL ZenKai Uni"", simplifiedChineseCodepage}}, + {L""ar pl zenkai uni"", {L""\x6587\x0050\x004C\x4E2D\x6977\x0055\x006E\x0069"", simplifiedChineseCodepage}}, + }; + + typedef HashMap NameMap; + static NameMap* fontNameMap = 0; + + if (!fontNameMap) { + fontNameMap = new NameMap; + for (size_t i = 0; i < WTF_ARRAY_LENGTH(namePairs); ++i) + fontNameMap->set(String(namePairs[i].name), &(namePairs[i].altNameCodepage)); + } + + bool isAscii = false; + String n; + if (name.containsOnlyASCII()) { + isAscii = true; + n = name.lower(); + } else + n = name; + + NameMap::iterator iter = fontNameMap->find(n); + if (iter == fontNameMap->end()) + return false; + + static int systemCp = ::GetACP(); + int fontCp = iter->value->codePage; + + if ((isAscii && systemCp == fontCp) || (!isAscii && systemCp != fontCp)) { + altName = String(iter->value->name); + return true; + } + + return false; +} +",0,"static bool LookupAltName(const String& name, String& altName) +{ + struct FontCodepage { + const WCHAR* name; + int codePage; + }; + + struct NamePair { + const WCHAR* name; + FontCodepage altNameCodepage; + }; + + const int japaneseCodepage = 932; + const int simplifiedChineseCodepage = 936; + const int koreanCodepage = 949; + const int traditionalChineseCodepage = 950; + + static const NamePair namePairs[] = { + {L""\xFF2D\xFF33 \xFF30\x30B4\x30B7\x30C3\x30AF"", {L""MS PGothic"", japaneseCodepage}}, + {L""ms pgothic"", {L""\xFF2D\xFF33 \xFF30\x30B4\x30B7\x30C3\x30AF"", japaneseCodepage}}, + {L""\xFF2D\xFF33 \xFF30\x660E\x671D"", {L""MS PMincho"", japaneseCodepage}}, + {L""ms pmincho"", {L""\xFF2D\xFF33 \xFF30\x660E\x671D"", japaneseCodepage}}, + {L""\xFF2D\xFF33 \x30B4\x30B7\x30C3\x30AF"", {L""MS Gothic"", japaneseCodepage}}, + {L""ms gothic"", {L""\xFF2D\xFF33 \x30B4\x30B7\x30C3\x30AF"", japaneseCodepage}}, + {L""\xFF2D\xFF33 \x660E\x671D"", {L""MS Mincho"", japaneseCodepage}}, + {L""ms mincho"", {L""\xFF2D\xFF33 \x660E\x671D"", japaneseCodepage}}, + {L""\x30E1\x30A4\x30EA\x30AA"", {L""Meiryo"", japaneseCodepage}}, + {L""meiryo"", {L""\x30E1\x30A4\x30EA\x30AA"", japaneseCodepage}}, + {L""\xBC14\xD0D5"", {L""Batang"", koreanCodepage}}, + {L""batang"", {L""\xBC14\xD0D5"", koreanCodepage}}, + {L""\xBC14\xD0D5\xCCB4"", {L""Batangche"", koreanCodepage}}, + {L""batangche"", {L""\xBC14\xD0D5\xCCB4"", koreanCodepage}}, + {L""\xAD74\xB9BC"", {L""Gulim"", koreanCodepage}}, + {L""gulim"", {L""\xAD74\xB9BC"", koreanCodepage}}, + {L""\xAD74\xB9BC\xCCB4"", {L""Gulimche"", koreanCodepage}}, + {L""gulimche"", {L""\xAD74\xB9BC\xCCB4"", koreanCodepage}}, + {L""\xB3CB\xC6C0"", {L""Dotum"", koreanCodepage}}, + {L""dotum"", {L""\xB3CB\xC6C0"", koreanCodepage}}, + {L""\xB3CB\xC6C0\xCCB4"", {L""Dotumche"", koreanCodepage}}, + {L""dotumche"", {L""\xB3CB\xC6C0\xCCB4"", koreanCodepage}}, + {L""\xAD81\xC11C"", {L""Gungsuh"", koreanCodepage}}, + {L""gungsuh"", {L""\xAD81\xC11C"", koreanCodepage}}, + {L""\xAD81\xC11C\xCCB4"", {L""Gungsuhche"", koreanCodepage}}, + {L""gungsuhche"", {L""\xAD81\xC11C\xCCB4"", koreanCodepage}}, + {L""\xB9D1\xC740 \xACE0\xB515"", {L""Malgun Gothic"", koreanCodepage}}, + {L""malgun gothic"", {L""\xB9D1\xC740 \xACE0\xB515"", koreanCodepage}}, + {L""\x5B8B\x4F53"", {L""SimSun"", simplifiedChineseCodepage}}, + {L""simsun"", {L""\x5B8B\x4F53"", simplifiedChineseCodepage}}, + {L""\x5B8B\x4F53-ExtB"", {L""SimSun-ExtB"", simplifiedChineseCodepage}}, + {L""simsun-extb"", {L""\x5B8B\x4F53-extb"", simplifiedChineseCodepage}}, + {L""\x9ED1\x4F53"", {L""SimHei"", simplifiedChineseCodepage}}, + {L""simhei"", {L""\x9ED1\x4F53"", simplifiedChineseCodepage}}, + {L""\x65B0\x5B8B\x4F53"", {L""NSimSun"", simplifiedChineseCodepage}}, + {L""nsimsun"", {L""\x65B0\x5B8B\x4F53"", simplifiedChineseCodepage}}, + {L""\x5FAE\x8F6F\x96C5\x9ED1"", {L""Microsoft Yahei"", simplifiedChineseCodepage}}, + {L""microsoft yahei"", {L""\x5FAE\x8F6F\x96C5\x9ED1"", simplifiedChineseCodepage}}, + {L""\x4EFF\x5B8B"", {L""FangSong"", simplifiedChineseCodepage}}, + {L""fangsong"", {L""\x4EFF\x5B8B"", simplifiedChineseCodepage}}, + {L""\x6977\x4F53"", {L""KaiTi"", simplifiedChineseCodepage}}, + {L""kaiti"", {L""\x6977\x4F53"", simplifiedChineseCodepage}}, + {L""\x4EFF\x5B8B_GB2312"", {L""FangSong_GB2312"", simplifiedChineseCodepage}}, + {L""fangsong_gb2312"", {L""\x4EFF\x5B8B_gb2312"", simplifiedChineseCodepage}}, + {L""\x6977\x4F53"", {L""KaiTi_GB2312"", simplifiedChineseCodepage}}, + {L""kaiti_gb2312"", {L""\x6977\x4F53_gb2312"", simplifiedChineseCodepage}}, + {L""\x65B0\x7D30\x660E\x9AD4"", {L""PMingLiu"", traditionalChineseCodepage}}, + {L""pmingliu"", {L""\x65B0\x7D30\x660E\x9AD4"", traditionalChineseCodepage}}, + {L""\x65B0\x7D30\x660E\x9AD4-ExtB"", {L""PMingLiu-ExtB"", traditionalChineseCodepage}}, + {L""pmingliu-extb"", {L""\x65B0\x7D30\x660E\x9AD4-extb"", traditionalChineseCodepage}}, + {L""\x7D30\x660E\x9AD4"", {L""MingLiu"", traditionalChineseCodepage}}, + {L""mingliu"", {L""\x7D30\x660E\x9AD4"", traditionalChineseCodepage}}, + {L""\x7D30\x660E\x9AD4-ExtB"", {L""MingLiu-ExtB"", traditionalChineseCodepage}}, + {L""mingliu-extb"", {L""x65B0\x7D30\x660E\x9AD4-extb"", traditionalChineseCodepage}}, + {L""\x5FAE\x8EDF\x6B63\x9ED1\x9AD4"", {L""Microsoft JhengHei"", traditionalChineseCodepage}}, + {L""microsoft jhengHei"", {L""\x5FAE\x8EDF\x6B63\x9ED1\x9AD4"", traditionalChineseCodepage}}, + {L""\x6A19\x6977\x9AD4"", {L""DFKai-SB"", traditionalChineseCodepage}}, + {L""dfkai-sb"", {L""\x6A19\x6977\x9AD4"", traditionalChineseCodepage}}, + {L""\x6587\x6cc9\x9a5b\x6b63\x9ed1"", {L""WenQuanYi Zen Hei"", traditionalChineseCodepage}}, + {L""wenquanyi zen hei"", {L""\x6587\x6cc9\x9a5b\x6b63\x9ed1"", traditionalChineseCodepage}}, + {L""\x6587\x6cc9\x9a7f\x6b63\x9ed1"", {L""WenQuanYi Zen Hei"", simplifiedChineseCodepage}}, + {L""wenquanyi zen hei"", {L""\x6587\x6cc9\x9a7f\x6b63\x9ed1"", simplifiedChineseCodepage}}, + {L""\x6587\x9f0e\x0050\x004c\x7d30\x4e0a\x6d77\x5b8b\x0055\x006e\x0069"", + {L""AR PL ShanHeiSun Uni"", traditionalChineseCodepage}}, + {L""ar pl shanheisun uni"", + {L""\x6587\x9f0e\x0050\x004c\x7d30\x4e0a\x6d77\x5b8b\x0055\x006e\x0069"", traditionalChineseCodepage}}, + {L""\x6587\x9f0e\x0050\x004c\x7ec6\x4e0a\x6d77\x5b8b\x0055\x006e\x0069"", + {L""AR PL ShanHeiSun Uni"", simplifiedChineseCodepage}}, + {L""ar pl shanheisun uni"", + {L""\x6587\x9f0e\x0050\x004c\x7ec6\x4e0a\x6d77\x5b8b\x0055\x006e\x0069"", simplifiedChineseCodepage}}, + {L""\x6587\x0050\x004C\x4E2D\x6977\x0055\x006E\x0069"", {L""AR PL ZenKai Uni"", traditionalChineseCodepage}}, + {L""ar pl zenkai uni"", {L""\x6587\x0050\x004C\x4E2D\x6977\x0055\x006E\x0069"", traditionalChineseCodepage}}, + {L""\x6587\x0050\x004C\x4E2D\x6977\x0055\x006E\x0069"", {L""AR PL ZenKai Uni"", simplifiedChineseCodepage}}, + {L""ar pl zenkai uni"", {L""\x6587\x0050\x004C\x4E2D\x6977\x0055\x006E\x0069"", simplifiedChineseCodepage}}, + }; + + typedef HashMap NameMap; + static NameMap* fontNameMap = 0; + + if (!fontNameMap) { + fontNameMap = new NameMap; + for (size_t i = 0; i < WTF_ARRAY_LENGTH(namePairs); ++i) + fontNameMap->set(String(namePairs[i].name), &(namePairs[i].altNameCodepage)); + } + + bool isAscii = false; + String n; + if (name.containsOnlyASCII()) { + isAscii = true; + n = name.lower(); + } else + n = name; + + NameMap::iterator iter = fontNameMap->find(n); + if (iter == fontNameMap->end()) + return false; + + static int systemCp = ::GetACP(); + int fontCp = iter->value->codePage; + + if ((isAscii && systemCp == fontCp) || (!isAscii && systemCp != fontCp)) { + altName = String(iter->value->name); + return true; + } + + return false; +} +","@@ -37,8 +37,8 @@ + #include ""core/platform/graphics/SimpleFontData.h"" + #include ""core/platform/graphics/chromium/FontPlatformDataChromiumWin.h"" + #include ""core/platform/graphics/chromium/FontUtilsChromiumWin.h"" +-#include ""core/platform/win/HWndDC.h"" + #include ""platform/LayoutTestSupport.h"" ++#include ""platform/win/HWndDC.h"" + #include ""wtf/HashMap.h"" + #include ""wtf/HashSet.h"" + #include ""wtf/text/StringHash.h""",2942,3273,4096 +6271,"static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception) +{ + const char + *option; + + Image + *image; + + int + jp2_status; + + MagickBooleanType + status; + + opj_codec_t + *jp2_codec; + + opj_codestream_index_t + *codestream_index = (opj_codestream_index_t *) NULL; + + opj_dparameters_t + parameters; + + opj_image_t + *jp2_image; + + opj_stream_t + *jp2_stream; + + register ssize_t + i; + + ssize_t + y; + + unsigned char + sans[4]; + + /* + 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); + } + /* + Initialize JP2 codec. + */ + if (ReadBlob(image,4,sans) != 4) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + (void) SeekBlob(image,SEEK_SET,0); + if (LocaleCompare(image_info->magick,""JPT"") == 0) + jp2_codec=opj_create_decompress(OPJ_CODEC_JPT); + else + if (IsJ2K(sans,4) != MagickFalse) + jp2_codec=opj_create_decompress(OPJ_CODEC_J2K); + else + jp2_codec=opj_create_decompress(OPJ_CODEC_JP2); + opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception); + opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception); + opj_set_default_decoder_parameters(¶meters); + option=GetImageOption(image_info,""jp2:reduce-factor""); + if (option != (const char *) NULL) + parameters.cp_reduce=StringToInteger(option); + option=GetImageOption(image_info,""jp2:quality-layers""); + if (option == (const char *) NULL) + option=GetImageOption(image_info,""jp2:layer-number""); + if (option != (const char *) NULL) + parameters.cp_layer=StringToInteger(option); + if (opj_setup_decoder(jp2_codec,¶meters) == 0) + { + opj_destroy_codec(jp2_codec); + ThrowReaderException(DelegateError,""UnableToManageJP2Stream""); + } + jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_TRUE); + opj_stream_set_read_function(jp2_stream,JP2ReadHandler); + opj_stream_set_write_function(jp2_stream,JP2WriteHandler); + opj_stream_set_seek_function(jp2_stream,JP2SeekHandler); + opj_stream_set_skip_function(jp2_stream,JP2SkipHandler); + opj_stream_set_user_data(jp2_stream,image,NULL); + opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image)); + if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0) + { + opj_stream_destroy(jp2_stream); + opj_destroy_codec(jp2_codec); + ThrowReaderException(DelegateError,""UnableToDecodeImageFile""); + } + jp2_status=1; + if ((image->columns != 0) && (image->rows != 0)) + { + /* + Extract an area from the image. + */ + jp2_status=opj_set_decode_area(jp2_codec,jp2_image, + (OPJ_INT32) image->extract_info.x,(OPJ_INT32) image->extract_info.y, + (OPJ_INT32) image->extract_info.x+(ssize_t) image->columns, + (OPJ_INT32) image->extract_info.y+(ssize_t) image->rows); + if (jp2_status == 0) + { + opj_stream_destroy(jp2_stream); + opj_destroy_codec(jp2_codec); + opj_image_destroy(jp2_image); + ThrowReaderException(DelegateError,""UnableToDecodeImageFile""); + } + } + if ((image_info->number_scenes != 0) && (image_info->scene != 0)) + jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image, + (unsigned int) image_info->scene-1); + else + if (image->ping == MagickFalse) + { + jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image); + if (jp2_status != 0) + jp2_status=opj_end_decompress(jp2_codec,jp2_stream); + } + if (jp2_status == 0) + { + opj_stream_destroy(jp2_stream); + opj_destroy_codec(jp2_codec); + opj_image_destroy(jp2_image); + ThrowReaderException(DelegateError,""UnableToDecodeImageFile""); + } + opj_stream_destroy(jp2_stream); + for (i=0; i < (ssize_t) jp2_image->numcomps; i++) + { + if ((jp2_image->comps[0].dx == 0) || (jp2_image->comps[0].dy == 0) || + (jp2_image->comps[0].dx != jp2_image->comps[i].dx) || + (jp2_image->comps[0].dy != jp2_image->comps[i].dy) || + (jp2_image->comps[0].prec != jp2_image->comps[i].prec) || + (jp2_image->comps[0].sgnd != jp2_image->comps[i].sgnd) || + ((image->ping == MagickFalse) && (jp2_image->comps[i].data == NULL))) + { + opj_destroy_codec(jp2_codec); + opj_image_destroy(jp2_image); + ThrowReaderException(CoderError,""IrregularChannelGeometryNotSupported"") + } + } + /* + Convert JP2 image. + */ + image->columns=(size_t) jp2_image->comps[0].w; + image->rows=(size_t) jp2_image->comps[0].h; + image->depth=jp2_image->comps[0].prec; + status=SetImageExtent(image,image->columns,image->rows); + if (status == MagickFalse) + { + InheritException(exception,&image->exception); + return(DestroyImageList(image)); + } + image->compression=JPEG2000Compression; + if (jp2_image->color_space == 2) + { + SetImageColorspace(image,GRAYColorspace); + if (jp2_image->numcomps > 1) + image->matte=MagickTrue; + } + else + if (jp2_image->color_space == 3) + SetImageColorspace(image,Rec601YCbCrColorspace); + if (jp2_image->numcomps > 3) + image->matte=MagickTrue; + if (jp2_image->icc_profile_buf != (unsigned char *) NULL) + { + StringInfo + *profile; + + profile=BlobToStringInfo(jp2_image->icc_profile_buf, + jp2_image->icc_profile_len); + if (profile != (StringInfo *) NULL) + SetImageProfile(image,""icc"",profile); + } + if (image->ping != MagickFalse) + { + opj_destroy_codec(jp2_codec); + opj_image_destroy(jp2_image); + opj_destroy_cstr_index(&codestream_index); + return(GetFirstImageInList(image)); + } + for (y=0; y < (ssize_t) image->rows; y++) + { + register PixelPacket + *magick_restrict q; + + register ssize_t + x; + + q=GetAuthenticPixels(image,0,y,image->columns,1,exception); + if (q == (PixelPacket *) NULL) + break; + for (x=0; x < (ssize_t) image->columns; x++) + { + register ssize_t + i; + + for (i=0; i < (ssize_t) jp2_image->numcomps; i++) + { + double + pixel, + scale; + + scale=QuantumRange/(double) ((1UL << jp2_image->comps[i].prec)-1); + pixel=scale*(jp2_image->comps[i].data[y/jp2_image->comps[i].dy* + image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx]+ + (jp2_image->comps[i].sgnd ? 1UL << (jp2_image->comps[i].prec-1) : 0)); + switch (i) + { + case 0: + { + q->red=ClampToQuantum(pixel); + q->green=q->red; + q->blue=q->red; + q->opacity=OpaqueOpacity; + break; + } + case 1: + { + if (jp2_image->numcomps == 2) + { + q->opacity=ClampToQuantum(QuantumRange-pixel); + break; + } + q->green=ClampToQuantum(pixel); + break; + } + case 2: + { + q->blue=ClampToQuantum(pixel); + break; + } + case 3: + { + q->opacity=ClampToQuantum(QuantumRange-pixel); + break; + } + } + } + q++; + } + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + /* + Free resources. + */ + opj_destroy_codec(jp2_codec); + opj_image_destroy(jp2_image); + opj_destroy_cstr_index(&codestream_index); + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +",0,"static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception) +{ + const char + *option; + + Image + *image; + + int + jp2_status; + + MagickBooleanType + status; + + opj_codec_t + *jp2_codec; + + opj_codestream_index_t + *codestream_index = (opj_codestream_index_t *) NULL; + + opj_dparameters_t + parameters; + + opj_image_t + *jp2_image; + + opj_stream_t + *jp2_stream; + + register ssize_t + i; + + ssize_t + y; + + unsigned char + sans[4]; + + /* + 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); + } + /* + Initialize JP2 codec. + */ + if (ReadBlob(image,4,sans) != 4) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + (void) SeekBlob(image,SEEK_SET,0); + if (LocaleCompare(image_info->magick,""JPT"") == 0) + jp2_codec=opj_create_decompress(OPJ_CODEC_JPT); + else + if (IsJ2K(sans,4) != MagickFalse) + jp2_codec=opj_create_decompress(OPJ_CODEC_J2K); + else + jp2_codec=opj_create_decompress(OPJ_CODEC_JP2); + opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception); + opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception); + opj_set_default_decoder_parameters(¶meters); + option=GetImageOption(image_info,""jp2:reduce-factor""); + if (option != (const char *) NULL) + parameters.cp_reduce=StringToInteger(option); + option=GetImageOption(image_info,""jp2:quality-layers""); + if (option == (const char *) NULL) + option=GetImageOption(image_info,""jp2:layer-number""); + if (option != (const char *) NULL) + parameters.cp_layer=StringToInteger(option); + if (opj_setup_decoder(jp2_codec,¶meters) == 0) + { + opj_destroy_codec(jp2_codec); + ThrowReaderException(DelegateError,""UnableToManageJP2Stream""); + } + jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_TRUE); + opj_stream_set_read_function(jp2_stream,JP2ReadHandler); + opj_stream_set_write_function(jp2_stream,JP2WriteHandler); + opj_stream_set_seek_function(jp2_stream,JP2SeekHandler); + opj_stream_set_skip_function(jp2_stream,JP2SkipHandler); + opj_stream_set_user_data(jp2_stream,image,NULL); + opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image)); + if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0) + { + opj_stream_destroy(jp2_stream); + opj_destroy_codec(jp2_codec); + ThrowReaderException(DelegateError,""UnableToDecodeImageFile""); + } + jp2_status=1; + if ((image->columns != 0) && (image->rows != 0)) + { + /* + Extract an area from the image. + */ + jp2_status=opj_set_decode_area(jp2_codec,jp2_image, + (OPJ_INT32) image->extract_info.x,(OPJ_INT32) image->extract_info.y, + (OPJ_INT32) image->extract_info.x+(ssize_t) image->columns, + (OPJ_INT32) image->extract_info.y+(ssize_t) image->rows); + if (jp2_status == 0) + { + opj_stream_destroy(jp2_stream); + opj_destroy_codec(jp2_codec); + opj_image_destroy(jp2_image); + ThrowReaderException(DelegateError,""UnableToDecodeImageFile""); + } + } + if ((image_info->number_scenes != 0) && (image_info->scene != 0)) + jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image, + (unsigned int) image_info->scene-1); + else + if (image->ping == MagickFalse) + { + jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image); + if (jp2_status != 0) + jp2_status=opj_end_decompress(jp2_codec,jp2_stream); + } + if (jp2_status == 0) + { + opj_stream_destroy(jp2_stream); + opj_destroy_codec(jp2_codec); + opj_image_destroy(jp2_image); + ThrowReaderException(DelegateError,""UnableToDecodeImageFile""); + } + opj_stream_destroy(jp2_stream); + for (i=0; i < (ssize_t) jp2_image->numcomps; i++) + { + if ((jp2_image->comps[0].dx == 0) || (jp2_image->comps[0].dy == 0) || + (jp2_image->comps[0].dx != jp2_image->comps[i].dx) || + (jp2_image->comps[0].dy != jp2_image->comps[i].dy) || + (jp2_image->comps[0].prec != jp2_image->comps[i].prec) || + (jp2_image->comps[0].sgnd != jp2_image->comps[i].sgnd) || + ((image->ping == MagickFalse) && (jp2_image->comps[i].data == NULL))) + { + opj_destroy_codec(jp2_codec); + opj_image_destroy(jp2_image); + ThrowReaderException(CoderError,""IrregularChannelGeometryNotSupported"") + } + } + /* + Convert JP2 image. + */ + image->columns=(size_t) jp2_image->comps[0].w; + image->rows=(size_t) jp2_image->comps[0].h; + image->depth=jp2_image->comps[0].prec; + status=SetImageExtent(image,image->columns,image->rows); + if (status == MagickFalse) + { + InheritException(exception,&image->exception); + return(DestroyImageList(image)); + } + image->compression=JPEG2000Compression; + if (jp2_image->color_space == 2) + { + SetImageColorspace(image,GRAYColorspace); + if (jp2_image->numcomps > 1) + image->matte=MagickTrue; + } + else + if (jp2_image->color_space == 3) + SetImageColorspace(image,Rec601YCbCrColorspace); + if (jp2_image->numcomps > 3) + image->matte=MagickTrue; + if (jp2_image->icc_profile_buf != (unsigned char *) NULL) + { + StringInfo + *profile; + + profile=BlobToStringInfo(jp2_image->icc_profile_buf, + jp2_image->icc_profile_len); + if (profile != (StringInfo *) NULL) + SetImageProfile(image,""icc"",profile); + } + if (image->ping != MagickFalse) + { + opj_destroy_codec(jp2_codec); + opj_image_destroy(jp2_image); + opj_destroy_cstr_index(&codestream_index); + return(GetFirstImageInList(image)); + } + for (y=0; y < (ssize_t) image->rows; y++) + { + register PixelPacket + *magick_restrict q; + + register ssize_t + x; + + q=GetAuthenticPixels(image,0,y,image->columns,1,exception); + if (q == (PixelPacket *) NULL) + break; + for (x=0; x < (ssize_t) image->columns; x++) + { + register ssize_t + i; + + for (i=0; i < (ssize_t) jp2_image->numcomps; i++) + { + double + pixel, + scale; + + scale=QuantumRange/(double) ((1UL << jp2_image->comps[i].prec)-1); + pixel=scale*(jp2_image->comps[i].data[y/jp2_image->comps[i].dy* + image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx]+ + (jp2_image->comps[i].sgnd ? 1UL << (jp2_image->comps[i].prec-1) : 0)); + switch (i) + { + case 0: + { + q->red=ClampToQuantum(pixel); + q->green=q->red; + q->blue=q->red; + q->opacity=OpaqueOpacity; + break; + } + case 1: + { + if (jp2_image->numcomps == 2) + { + q->opacity=ClampToQuantum(QuantumRange-pixel); + break; + } + q->green=ClampToQuantum(pixel); + break; + } + case 2: + { + q->blue=ClampToQuantum(pixel); + break; + } + case 3: + { + q->opacity=ClampToQuantum(QuantumRange-pixel); + break; + } + } + } + q++; + } + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + /* + Free resources. + */ + opj_destroy_codec(jp2_codec); + opj_image_destroy(jp2_image); + opj_destroy_cstr_index(&codestream_index); + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +","@@ -924,7 +924,7 @@ static MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image) + ¶meters.subsampling_dx,¶meters.subsampling_dy); + property=GetImageProperty(image,""comment""); + if (property != (const char *) NULL) +- parameters.cp_comment=property; ++ parameters.cp_comment=(char *) property; + channels=3; + jp2_colorspace=OPJ_CLRSPC_SRGB; + if (image->colorspace == YUVColorspace)",2314,2645,4096 +9622,"parse_cmdline(int argc, char **argv) +{ + int c; + bool reopen_log = false; + int signum; + struct utsname uname_buf; + int longindex; + int curind; + bool bad_option = false; + unsigned facility; + mode_t new_umask_val; + + struct option long_options[] = { + {""use-file"", required_argument, NULL, 'f'}, +#if defined _WITH_VRRP_ && defined _WITH_LVS_ + {""vrrp"", no_argument, NULL, 'P'}, + {""check"", no_argument, NULL, 'C'}, +#endif +#ifdef _WITH_BFD_ + {""no_bfd"", no_argument, NULL, 'B'}, +#endif + {""all"", no_argument, NULL, 3 }, + {""log-console"", no_argument, NULL, 'l'}, + {""log-detail"", no_argument, NULL, 'D'}, + {""log-facility"", required_argument, NULL, 'S'}, + {""log-file"", optional_argument, NULL, 'g'}, + {""flush-log-file"", no_argument, NULL, 2 }, + {""no-syslog"", no_argument, NULL, 'G'}, + {""umask"", required_argument, NULL, 'u'}, +#ifdef _WITH_VRRP_ + {""release-vips"", no_argument, NULL, 'X'}, + {""dont-release-vrrp"", no_argument, NULL, 'V'}, +#endif +#ifdef _WITH_LVS_ + {""dont-release-ipvs"", no_argument, NULL, 'I'}, +#endif + {""dont-respawn"", no_argument, NULL, 'R'}, + {""dont-fork"", no_argument, NULL, 'n'}, + {""dump-conf"", no_argument, NULL, 'd'}, + {""pid"", required_argument, NULL, 'p'}, +#ifdef _WITH_VRRP_ + {""vrrp_pid"", required_argument, NULL, 'r'}, +#endif +#ifdef _WITH_LVS_ + {""checkers_pid"", required_argument, NULL, 'c'}, + {""address-monitoring"", no_argument, NULL, 'a'}, +#endif +#ifdef _WITH_BFD_ + {""bfd_pid"", required_argument, NULL, 'b'}, +#endif +#ifdef _WITH_SNMP_ + {""snmp"", no_argument, NULL, 'x'}, + {""snmp-agent-socket"", required_argument, NULL, 'A'}, +#endif + {""core-dump"", no_argument, NULL, 'm'}, + {""core-dump-pattern"", optional_argument, NULL, 'M'}, +#ifdef _MEM_CHECK_LOG_ + {""mem-check-log"", no_argument, NULL, 'L'}, +#endif +#if HAVE_DECL_CLONE_NEWNET + {""namespace"", required_argument, NULL, 's'}, +#endif + {""config-id"", required_argument, NULL, 'i'}, + {""signum"", required_argument, NULL, 4 }, + {""config-test"", optional_argument, NULL, 't'}, +#ifdef _WITH_PERF_ + {""perf"", optional_argument, NULL, 5 }, +#endif +#ifdef WITH_DEBUG_OPTIONS + {""debug"", optional_argument, NULL, 6 }, +#endif + {""version"", no_argument, NULL, 'v'}, + {""help"", no_argument, NULL, 'h'}, + + {NULL, 0, NULL, 0 } + }; + + /* Unfortunately, if a short option is used, getopt_long() doesn't change the value + * of longindex, so we need to ensure that before calling getopt_long(), longindex + * is set to a known invalid value */ + curind = optind; + while (longindex = -1, (c = getopt_long(argc, argv, "":vhlndu:DRS:f:p:i:mM::g::Gt::"" +#if defined _WITH_VRRP_ && defined _WITH_LVS_ + ""PC"" +#endif +#ifdef _WITH_VRRP_ + ""r:VX"" +#endif +#ifdef _WITH_LVS_ + ""ac:I"" +#endif +#ifdef _WITH_BFD_ + ""Bb:"" +#endif +#ifdef _WITH_SNMP_ + ""xA:"" +#endif +#ifdef _MEM_CHECK_LOG_ + ""L"" +#endif +#if HAVE_DECL_CLONE_NEWNET + ""s:"" +#endif + , long_options, &longindex)) != -1) { + + /* Check for an empty option argument. For example --use-file= returns + * a 0 length option, which we don't want */ + if (longindex >= 0 && long_options[longindex].has_arg == required_argument && optarg && !optarg[0]) { + c = ':'; + optarg = NULL; + } + + switch (c) { + case 'v': + fprintf(stderr, ""%s"", version_string); +#ifdef GIT_COMMIT + fprintf(stderr, "", git commit %s"", GIT_COMMIT); +#endif + fprintf(stderr, ""\n\n%s\n\n"", COPYRIGHT_STRING); + fprintf(stderr, ""Built with kernel headers for Linux %d.%d.%d\n"", + (LINUX_VERSION_CODE >> 16) & 0xff, + (LINUX_VERSION_CODE >> 8) & 0xff, + (LINUX_VERSION_CODE ) & 0xff); + uname(&uname_buf); + fprintf(stderr, ""Running on %s %s %s\n\n"", uname_buf.sysname, uname_buf.release, uname_buf.version); + fprintf(stderr, ""configure options: %s\n\n"", KEEPALIVED_CONFIGURE_OPTIONS); + fprintf(stderr, ""Config options: %s\n\n"", CONFIGURATION_OPTIONS); + fprintf(stderr, ""System options: %s\n"", SYSTEM_OPTIONS); + exit(0); + break; + case 'h': + usage(argv[0]); + exit(0); + break; + case 'l': + __set_bit(LOG_CONSOLE_BIT, &debug); + reopen_log = true; + break; + case 'n': + __set_bit(DONT_FORK_BIT, &debug); + break; + case 'd': + __set_bit(DUMP_CONF_BIT, &debug); + break; +#ifdef _WITH_VRRP_ + case 'V': + __set_bit(DONT_RELEASE_VRRP_BIT, &debug); + break; +#endif +#ifdef _WITH_LVS_ + case 'I': + __set_bit(DONT_RELEASE_IPVS_BIT, &debug); + break; +#endif + case 'D': + if (__test_bit(LOG_DETAIL_BIT, &debug)) + __set_bit(LOG_EXTRA_DETAIL_BIT, &debug); + else + __set_bit(LOG_DETAIL_BIT, &debug); + break; + case 'R': + __set_bit(DONT_RESPAWN_BIT, &debug); + break; +#ifdef _WITH_VRRP_ + case 'X': + __set_bit(RELEASE_VIPS_BIT, &debug); + break; +#endif + case 'S': + if (!read_unsigned(optarg, &facility, 0, LOG_FACILITY_MAX, false)) + fprintf(stderr, ""Invalid log facility '%s'\n"", optarg); + else { + log_facility = LOG_FACILITY[facility].facility; + reopen_log = true; + } + break; + case 'g': + if (optarg && optarg[0]) + log_file_name = optarg; + else + log_file_name = ""/tmp/keepalived.log""; + open_log_file(log_file_name, NULL, NULL, NULL); + break; + case 'G': + __set_bit(NO_SYSLOG_BIT, &debug); + reopen_log = true; + break; + case 'u': + new_umask_val = set_umask(optarg); + if (umask_cmdline) + umask_val = new_umask_val; + break; + case 't': + __set_bit(CONFIG_TEST_BIT, &debug); + __set_bit(DONT_RESPAWN_BIT, &debug); + __set_bit(DONT_FORK_BIT, &debug); + __set_bit(NO_SYSLOG_BIT, &debug); + if (optarg && optarg[0]) { + int fd = open(optarg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); + if (fd == -1) { + fprintf(stderr, ""Unable to open config-test log file %s\n"", optarg); + exit(EXIT_FAILURE); + } + dup2(fd, STDERR_FILENO); + close(fd); + } + break; + case 'f': + conf_file = optarg; + break; + case 2: /* --flush-log-file */ + set_flush_log_file(); + break; +#if defined _WITH_VRRP_ && defined _WITH_LVS_ + case 'P': + __clear_bit(DAEMON_CHECKERS, &daemon_mode); + break; + case 'C': + __clear_bit(DAEMON_VRRP, &daemon_mode); + break; +#endif +#ifdef _WITH_BFD_ + case 'B': + __clear_bit(DAEMON_BFD, &daemon_mode); + break; +#endif + case 'p': + main_pidfile = optarg; + break; +#ifdef _WITH_LVS_ + case 'c': + checkers_pidfile = optarg; + break; + case 'a': + __set_bit(LOG_ADDRESS_CHANGES, &debug); + break; +#endif +#ifdef _WITH_VRRP_ + case 'r': + vrrp_pidfile = optarg; + break; +#endif +#ifdef _WITH_BFD_ + case 'b': + bfd_pidfile = optarg; + break; +#endif +#ifdef _WITH_SNMP_ + case 'x': + snmp = 1; + break; + case 'A': + snmp_socket = optarg; + break; +#endif + case 'M': + set_core_dump_pattern = true; + if (optarg && optarg[0]) + core_dump_pattern = optarg; + /* ... falls through ... */ + case 'm': + create_core_dump = true; + break; +#ifdef _MEM_CHECK_LOG_ + case 'L': + __set_bit(MEM_CHECK_LOG_BIT, &debug); + break; +#endif +#if HAVE_DECL_CLONE_NEWNET + case 's': + override_namespace = MALLOC(strlen(optarg) + 1); + strcpy(override_namespace, optarg); + break; +#endif + case 'i': + FREE_PTR(config_id); + config_id = MALLOC(strlen(optarg) + 1); + strcpy(config_id, optarg); + break; + case 4: /* --signum */ + signum = get_signum(optarg); + if (signum == -1) { + fprintf(stderr, ""Unknown sigfunc %s\n"", optarg); + exit(1); + } + + printf(""%d\n"", signum); + exit(0); + break; + case 3: /* --all */ + __set_bit(RUN_ALL_CHILDREN, &daemon_mode); +#ifdef _WITH_VRRP_ + __set_bit(DAEMON_VRRP, &daemon_mode); +#endif +#ifdef _WITH_LVS_ + __set_bit(DAEMON_CHECKERS, &daemon_mode); +#endif +#ifdef _WITH_BFD_ + __set_bit(DAEMON_BFD, &daemon_mode); +#endif + break; +#ifdef _WITH_PERF_ + case 5: + if (optarg && optarg[0]) { + if (!strcmp(optarg, ""run"")) + perf_run = PERF_RUN; + else if (!strcmp(optarg, ""all"")) + perf_run = PERF_ALL; + else if (!strcmp(optarg, ""end"")) + perf_run = PERF_END; + else + log_message(LOG_INFO, ""Unknown perf start point %s"", optarg); + } + else + perf_run = PERF_RUN; + + break; +#endif +#ifdef WITH_DEBUG_OPTIONS + case 6: + set_debug_options(optarg && optarg[0] ? optarg : NULL); + break; +#endif + case '?': + if (optopt && argv[curind][1] != '-') + fprintf(stderr, ""Unknown option -%c\n"", optopt); + else + fprintf(stderr, ""Unknown option %s\n"", argv[curind]); + bad_option = true; + break; + case ':': + if (optopt && argv[curind][1] != '-') + fprintf(stderr, ""Missing parameter for option -%c\n"", optopt); + else + fprintf(stderr, ""Missing parameter for option --%s\n"", long_options[longindex].name); + bad_option = true; + break; + default: + exit(1); + break; + } + curind = optind; + } + + if (optind < argc) { + printf(""Unexpected argument(s): ""); + while (optind < argc) + printf(""%s "", argv[optind++]); + printf(""\n""); + } + + if (bad_option) + exit(1); + + return reopen_log; +} +",0,"parse_cmdline(int argc, char **argv) +{ + int c; + bool reopen_log = false; + int signum; + struct utsname uname_buf; + int longindex; + int curind; + bool bad_option = false; + unsigned facility; + mode_t new_umask_val; + + struct option long_options[] = { + {""use-file"", required_argument, NULL, 'f'}, +#if defined _WITH_VRRP_ && defined _WITH_LVS_ + {""vrrp"", no_argument, NULL, 'P'}, + {""check"", no_argument, NULL, 'C'}, +#endif +#ifdef _WITH_BFD_ + {""no_bfd"", no_argument, NULL, 'B'}, +#endif + {""all"", no_argument, NULL, 3 }, + {""log-console"", no_argument, NULL, 'l'}, + {""log-detail"", no_argument, NULL, 'D'}, + {""log-facility"", required_argument, NULL, 'S'}, + {""log-file"", optional_argument, NULL, 'g'}, + {""flush-log-file"", no_argument, NULL, 2 }, + {""no-syslog"", no_argument, NULL, 'G'}, + {""umask"", required_argument, NULL, 'u'}, +#ifdef _WITH_VRRP_ + {""release-vips"", no_argument, NULL, 'X'}, + {""dont-release-vrrp"", no_argument, NULL, 'V'}, +#endif +#ifdef _WITH_LVS_ + {""dont-release-ipvs"", no_argument, NULL, 'I'}, +#endif + {""dont-respawn"", no_argument, NULL, 'R'}, + {""dont-fork"", no_argument, NULL, 'n'}, + {""dump-conf"", no_argument, NULL, 'd'}, + {""pid"", required_argument, NULL, 'p'}, +#ifdef _WITH_VRRP_ + {""vrrp_pid"", required_argument, NULL, 'r'}, +#endif +#ifdef _WITH_LVS_ + {""checkers_pid"", required_argument, NULL, 'c'}, + {""address-monitoring"", no_argument, NULL, 'a'}, +#endif +#ifdef _WITH_BFD_ + {""bfd_pid"", required_argument, NULL, 'b'}, +#endif +#ifdef _WITH_SNMP_ + {""snmp"", no_argument, NULL, 'x'}, + {""snmp-agent-socket"", required_argument, NULL, 'A'}, +#endif + {""core-dump"", no_argument, NULL, 'm'}, + {""core-dump-pattern"", optional_argument, NULL, 'M'}, +#ifdef _MEM_CHECK_LOG_ + {""mem-check-log"", no_argument, NULL, 'L'}, +#endif +#if HAVE_DECL_CLONE_NEWNET + {""namespace"", required_argument, NULL, 's'}, +#endif + {""config-id"", required_argument, NULL, 'i'}, + {""signum"", required_argument, NULL, 4 }, + {""config-test"", optional_argument, NULL, 't'}, +#ifdef _WITH_PERF_ + {""perf"", optional_argument, NULL, 5 }, +#endif +#ifdef WITH_DEBUG_OPTIONS + {""debug"", optional_argument, NULL, 6 }, +#endif + {""version"", no_argument, NULL, 'v'}, + {""help"", no_argument, NULL, 'h'}, + + {NULL, 0, NULL, 0 } + }; + + /* Unfortunately, if a short option is used, getopt_long() doesn't change the value + * of longindex, so we need to ensure that before calling getopt_long(), longindex + * is set to a known invalid value */ + curind = optind; + while (longindex = -1, (c = getopt_long(argc, argv, "":vhlndu:DRS:f:p:i:mM::g::Gt::"" +#if defined _WITH_VRRP_ && defined _WITH_LVS_ + ""PC"" +#endif +#ifdef _WITH_VRRP_ + ""r:VX"" +#endif +#ifdef _WITH_LVS_ + ""ac:I"" +#endif +#ifdef _WITH_BFD_ + ""Bb:"" +#endif +#ifdef _WITH_SNMP_ + ""xA:"" +#endif +#ifdef _MEM_CHECK_LOG_ + ""L"" +#endif +#if HAVE_DECL_CLONE_NEWNET + ""s:"" +#endif + , long_options, &longindex)) != -1) { + + /* Check for an empty option argument. For example --use-file= returns + * a 0 length option, which we don't want */ + if (longindex >= 0 && long_options[longindex].has_arg == required_argument && optarg && !optarg[0]) { + c = ':'; + optarg = NULL; + } + + switch (c) { + case 'v': + fprintf(stderr, ""%s"", version_string); +#ifdef GIT_COMMIT + fprintf(stderr, "", git commit %s"", GIT_COMMIT); +#endif + fprintf(stderr, ""\n\n%s\n\n"", COPYRIGHT_STRING); + fprintf(stderr, ""Built with kernel headers for Linux %d.%d.%d\n"", + (LINUX_VERSION_CODE >> 16) & 0xff, + (LINUX_VERSION_CODE >> 8) & 0xff, + (LINUX_VERSION_CODE ) & 0xff); + uname(&uname_buf); + fprintf(stderr, ""Running on %s %s %s\n\n"", uname_buf.sysname, uname_buf.release, uname_buf.version); + fprintf(stderr, ""configure options: %s\n\n"", KEEPALIVED_CONFIGURE_OPTIONS); + fprintf(stderr, ""Config options: %s\n\n"", CONFIGURATION_OPTIONS); + fprintf(stderr, ""System options: %s\n"", SYSTEM_OPTIONS); + exit(0); + break; + case 'h': + usage(argv[0]); + exit(0); + break; + case 'l': + __set_bit(LOG_CONSOLE_BIT, &debug); + reopen_log = true; + break; + case 'n': + __set_bit(DONT_FORK_BIT, &debug); + break; + case 'd': + __set_bit(DUMP_CONF_BIT, &debug); + break; +#ifdef _WITH_VRRP_ + case 'V': + __set_bit(DONT_RELEASE_VRRP_BIT, &debug); + break; +#endif +#ifdef _WITH_LVS_ + case 'I': + __set_bit(DONT_RELEASE_IPVS_BIT, &debug); + break; +#endif + case 'D': + if (__test_bit(LOG_DETAIL_BIT, &debug)) + __set_bit(LOG_EXTRA_DETAIL_BIT, &debug); + else + __set_bit(LOG_DETAIL_BIT, &debug); + break; + case 'R': + __set_bit(DONT_RESPAWN_BIT, &debug); + break; +#ifdef _WITH_VRRP_ + case 'X': + __set_bit(RELEASE_VIPS_BIT, &debug); + break; +#endif + case 'S': + if (!read_unsigned(optarg, &facility, 0, LOG_FACILITY_MAX, false)) + fprintf(stderr, ""Invalid log facility '%s'\n"", optarg); + else { + log_facility = LOG_FACILITY[facility].facility; + reopen_log = true; + } + break; + case 'g': + if (optarg && optarg[0]) + log_file_name = optarg; + else + log_file_name = ""/tmp/keepalived.log""; + open_log_file(log_file_name, NULL, NULL, NULL); + break; + case 'G': + __set_bit(NO_SYSLOG_BIT, &debug); + reopen_log = true; + break; + case 'u': + new_umask_val = set_umask(optarg); + if (umask_cmdline) + umask_val = new_umask_val; + break; + case 't': + __set_bit(CONFIG_TEST_BIT, &debug); + __set_bit(DONT_RESPAWN_BIT, &debug); + __set_bit(DONT_FORK_BIT, &debug); + __set_bit(NO_SYSLOG_BIT, &debug); + if (optarg && optarg[0]) { + int fd = open(optarg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); + if (fd == -1) { + fprintf(stderr, ""Unable to open config-test log file %s\n"", optarg); + exit(EXIT_FAILURE); + } + dup2(fd, STDERR_FILENO); + close(fd); + } + break; + case 'f': + conf_file = optarg; + break; + case 2: /* --flush-log-file */ + set_flush_log_file(); + break; +#if defined _WITH_VRRP_ && defined _WITH_LVS_ + case 'P': + __clear_bit(DAEMON_CHECKERS, &daemon_mode); + break; + case 'C': + __clear_bit(DAEMON_VRRP, &daemon_mode); + break; +#endif +#ifdef _WITH_BFD_ + case 'B': + __clear_bit(DAEMON_BFD, &daemon_mode); + break; +#endif + case 'p': + main_pidfile = optarg; + break; +#ifdef _WITH_LVS_ + case 'c': + checkers_pidfile = optarg; + break; + case 'a': + __set_bit(LOG_ADDRESS_CHANGES, &debug); + break; +#endif +#ifdef _WITH_VRRP_ + case 'r': + vrrp_pidfile = optarg; + break; +#endif +#ifdef _WITH_BFD_ + case 'b': + bfd_pidfile = optarg; + break; +#endif +#ifdef _WITH_SNMP_ + case 'x': + snmp = 1; + break; + case 'A': + snmp_socket = optarg; + break; +#endif + case 'M': + set_core_dump_pattern = true; + if (optarg && optarg[0]) + core_dump_pattern = optarg; + /* ... falls through ... */ + case 'm': + create_core_dump = true; + break; +#ifdef _MEM_CHECK_LOG_ + case 'L': + __set_bit(MEM_CHECK_LOG_BIT, &debug); + break; +#endif +#if HAVE_DECL_CLONE_NEWNET + case 's': + override_namespace = MALLOC(strlen(optarg) + 1); + strcpy(override_namespace, optarg); + break; +#endif + case 'i': + FREE_PTR(config_id); + config_id = MALLOC(strlen(optarg) + 1); + strcpy(config_id, optarg); + break; + case 4: /* --signum */ + signum = get_signum(optarg); + if (signum == -1) { + fprintf(stderr, ""Unknown sigfunc %s\n"", optarg); + exit(1); + } + + printf(""%d\n"", signum); + exit(0); + break; + case 3: /* --all */ + __set_bit(RUN_ALL_CHILDREN, &daemon_mode); +#ifdef _WITH_VRRP_ + __set_bit(DAEMON_VRRP, &daemon_mode); +#endif +#ifdef _WITH_LVS_ + __set_bit(DAEMON_CHECKERS, &daemon_mode); +#endif +#ifdef _WITH_BFD_ + __set_bit(DAEMON_BFD, &daemon_mode); +#endif + break; +#ifdef _WITH_PERF_ + case 5: + if (optarg && optarg[0]) { + if (!strcmp(optarg, ""run"")) + perf_run = PERF_RUN; + else if (!strcmp(optarg, ""all"")) + perf_run = PERF_ALL; + else if (!strcmp(optarg, ""end"")) + perf_run = PERF_END; + else + log_message(LOG_INFO, ""Unknown perf start point %s"", optarg); + } + else + perf_run = PERF_RUN; + + break; +#endif +#ifdef WITH_DEBUG_OPTIONS + case 6: + set_debug_options(optarg && optarg[0] ? optarg : NULL); + break; +#endif + case '?': + if (optopt && argv[curind][1] != '-') + fprintf(stderr, ""Unknown option -%c\n"", optopt); + else + fprintf(stderr, ""Unknown option %s\n"", argv[curind]); + bad_option = true; + break; + case ':': + if (optopt && argv[curind][1] != '-') + fprintf(stderr, ""Missing parameter for option -%c\n"", optopt); + else + fprintf(stderr, ""Missing parameter for option --%s\n"", long_options[longindex].name); + bad_option = true; + break; + default: + exit(1); + break; + } + curind = optind; + } + + if (optind < argc) { + printf(""Unexpected argument(s): ""); + while (optind < argc) + printf(""%s "", argv[optind++]); + printf(""\n""); + } + + if (bad_option) + exit(1); + + return reopen_log; +} +","@@ -882,7 +882,7 @@ set_umask(const char *optarg) + + if (*endptr || umask_long < 0 || umask_long & ~0777L) { + fprintf(stderr, ""Invalid --umask option %s"", optarg); +- return; ++ return 0; + } + + umask_val = umask_long & 0777;",2827,3158,4096 +1934,"int ip_options_compile(struct net *net, + struct ip_options * opt, struct sk_buff * skb) +{ + int l; + unsigned char * iph; + unsigned char * optptr; + int optlen; + unsigned char * pp_ptr = NULL; + struct rtable *rt = NULL; + + if (skb != NULL) { + rt = skb_rtable(skb); + optptr = (unsigned char *)&(ip_hdr(skb)[1]); + } else + optptr = opt->__data; + iph = optptr - sizeof(struct iphdr); + + for (l = opt->optlen; l > 0; ) { + switch (*optptr) { + case IPOPT_END: + for (optptr++, l--; l>0; optptr++, l--) { + if (*optptr != IPOPT_END) { + *optptr = IPOPT_END; + opt->is_changed = 1; + } + } + goto eol; + case IPOPT_NOOP: + l--; + optptr++; + continue; + } + optlen = optptr[1]; + if (optlen<2 || optlen>l) { + pp_ptr = optptr; + goto error; + } + switch (*optptr) { + case IPOPT_SSRR: + case IPOPT_LSRR: + if (optlen < 3) { + pp_ptr = optptr + 1; + goto error; + } + if (optptr[2] < 4) { + pp_ptr = optptr + 2; + goto error; + } + /* NB: cf RFC-1812 5.2.4.1 */ + if (opt->srr) { + pp_ptr = optptr; + goto error; + } + if (!skb) { + if (optptr[2] != 4 || optlen < 7 || ((optlen-3) & 3)) { + pp_ptr = optptr + 1; + goto error; + } + memcpy(&opt->faddr, &optptr[3], 4); + if (optlen > 7) + memmove(&optptr[3], &optptr[7], optlen-7); + } + opt->is_strictroute = (optptr[0] == IPOPT_SSRR); + opt->srr = optptr - iph; + break; + case IPOPT_RR: + if (opt->rr) { + pp_ptr = optptr; + goto error; + } + if (optlen < 3) { + pp_ptr = optptr + 1; + goto error; + } + if (optptr[2] < 4) { + pp_ptr = optptr + 2; + goto error; + } + if (optptr[2] <= optlen) { + if (optptr[2]+3 > optlen) { + pp_ptr = optptr + 2; + goto error; + } + if (rt) { + memcpy(&optptr[optptr[2]-1], &rt->rt_spec_dst, 4); + opt->is_changed = 1; + } + optptr[2] += 4; + opt->rr_needaddr = 1; + } + opt->rr = optptr - iph; + break; + case IPOPT_TIMESTAMP: + if (opt->ts) { + pp_ptr = optptr; + goto error; + } + if (optlen < 4) { + pp_ptr = optptr + 1; + goto error; + } + if (optptr[2] < 5) { + pp_ptr = optptr + 2; + goto error; + } + if (optptr[2] <= optlen) { + __be32 *timeptr = NULL; + if (optptr[2]+3 > optptr[1]) { + pp_ptr = optptr + 2; + goto error; + } + switch (optptr[3]&0xF) { + case IPOPT_TS_TSONLY: + opt->ts = optptr - iph; + if (skb) + timeptr = (__be32*)&optptr[optptr[2]-1]; + opt->ts_needtime = 1; + optptr[2] += 4; + break; + case IPOPT_TS_TSANDADDR: + if (optptr[2]+7 > optptr[1]) { + pp_ptr = optptr + 2; + goto error; + } + opt->ts = optptr - iph; + if (rt) { + memcpy(&optptr[optptr[2]-1], &rt->rt_spec_dst, 4); + timeptr = (__be32*)&optptr[optptr[2]+3]; + } + opt->ts_needaddr = 1; + opt->ts_needtime = 1; + optptr[2] += 8; + break; + case IPOPT_TS_PRESPEC: + if (optptr[2]+7 > optptr[1]) { + pp_ptr = optptr + 2; + goto error; + } + opt->ts = optptr - iph; + { + __be32 addr; + memcpy(&addr, &optptr[optptr[2]-1], 4); + if (inet_addr_type(net, addr) == RTN_UNICAST) + break; + if (skb) + timeptr = (__be32*)&optptr[optptr[2]+3]; + } + opt->ts_needtime = 1; + optptr[2] += 8; + break; + default: + if (!skb && !capable(CAP_NET_RAW)) { + pp_ptr = optptr + 3; + goto error; + } + break; + } + if (timeptr) { + struct timespec tv; + __be32 midtime; + getnstimeofday(&tv); + midtime = htonl((tv.tv_sec % 86400) * MSEC_PER_SEC + tv.tv_nsec / NSEC_PER_MSEC); + memcpy(timeptr, &midtime, sizeof(__be32)); + opt->is_changed = 1; + } + } else { + unsigned overflow = optptr[3]>>4; + if (overflow == 15) { + pp_ptr = optptr + 3; + goto error; + } + opt->ts = optptr - iph; + if (skb) { + optptr[3] = (optptr[3]&0xF)|((overflow+1)<<4); + opt->is_changed = 1; + } + } + break; + case IPOPT_RA: + if (optlen < 4) { + pp_ptr = optptr + 1; + goto error; + } + if (optptr[2] == 0 && optptr[3] == 0) + opt->router_alert = optptr - iph; + break; + case IPOPT_CIPSO: + if ((!skb && !capable(CAP_NET_RAW)) || opt->cipso) { + pp_ptr = optptr; + goto error; + } + opt->cipso = optptr - iph; + if (cipso_v4_validate(skb, &optptr)) { + pp_ptr = optptr; + goto error; + } + break; + case IPOPT_SEC: + case IPOPT_SID: + default: + if (!skb && !capable(CAP_NET_RAW)) { + pp_ptr = optptr; + goto error; + } + break; + } + l -= optlen; + optptr += optlen; + } + +eol: + if (!pp_ptr) + return 0; + +error: + if (skb) { + icmp_send(skb, ICMP_PARAMETERPROB, 0, htonl((pp_ptr-iph)<<24)); + } + return -EINVAL; +} +",0,"int ip_options_compile(struct net *net, + struct ip_options * opt, struct sk_buff * skb) +{ + int l; + unsigned char * iph; + unsigned char * optptr; + int optlen; + unsigned char * pp_ptr = NULL; + struct rtable *rt = NULL; + + if (skb != NULL) { + rt = skb_rtable(skb); + optptr = (unsigned char *)&(ip_hdr(skb)[1]); + } else + optptr = opt->__data; + iph = optptr - sizeof(struct iphdr); + + for (l = opt->optlen; l > 0; ) { + switch (*optptr) { + case IPOPT_END: + for (optptr++, l--; l>0; optptr++, l--) { + if (*optptr != IPOPT_END) { + *optptr = IPOPT_END; + opt->is_changed = 1; + } + } + goto eol; + case IPOPT_NOOP: + l--; + optptr++; + continue; + } + optlen = optptr[1]; + if (optlen<2 || optlen>l) { + pp_ptr = optptr; + goto error; + } + switch (*optptr) { + case IPOPT_SSRR: + case IPOPT_LSRR: + if (optlen < 3) { + pp_ptr = optptr + 1; + goto error; + } + if (optptr[2] < 4) { + pp_ptr = optptr + 2; + goto error; + } + /* NB: cf RFC-1812 5.2.4.1 */ + if (opt->srr) { + pp_ptr = optptr; + goto error; + } + if (!skb) { + if (optptr[2] != 4 || optlen < 7 || ((optlen-3) & 3)) { + pp_ptr = optptr + 1; + goto error; + } + memcpy(&opt->faddr, &optptr[3], 4); + if (optlen > 7) + memmove(&optptr[3], &optptr[7], optlen-7); + } + opt->is_strictroute = (optptr[0] == IPOPT_SSRR); + opt->srr = optptr - iph; + break; + case IPOPT_RR: + if (opt->rr) { + pp_ptr = optptr; + goto error; + } + if (optlen < 3) { + pp_ptr = optptr + 1; + goto error; + } + if (optptr[2] < 4) { + pp_ptr = optptr + 2; + goto error; + } + if (optptr[2] <= optlen) { + if (optptr[2]+3 > optlen) { + pp_ptr = optptr + 2; + goto error; + } + if (rt) { + memcpy(&optptr[optptr[2]-1], &rt->rt_spec_dst, 4); + opt->is_changed = 1; + } + optptr[2] += 4; + opt->rr_needaddr = 1; + } + opt->rr = optptr - iph; + break; + case IPOPT_TIMESTAMP: + if (opt->ts) { + pp_ptr = optptr; + goto error; + } + if (optlen < 4) { + pp_ptr = optptr + 1; + goto error; + } + if (optptr[2] < 5) { + pp_ptr = optptr + 2; + goto error; + } + if (optptr[2] <= optlen) { + __be32 *timeptr = NULL; + if (optptr[2]+3 > optptr[1]) { + pp_ptr = optptr + 2; + goto error; + } + switch (optptr[3]&0xF) { + case IPOPT_TS_TSONLY: + opt->ts = optptr - iph; + if (skb) + timeptr = (__be32*)&optptr[optptr[2]-1]; + opt->ts_needtime = 1; + optptr[2] += 4; + break; + case IPOPT_TS_TSANDADDR: + if (optptr[2]+7 > optptr[1]) { + pp_ptr = optptr + 2; + goto error; + } + opt->ts = optptr - iph; + if (rt) { + memcpy(&optptr[optptr[2]-1], &rt->rt_spec_dst, 4); + timeptr = (__be32*)&optptr[optptr[2]+3]; + } + opt->ts_needaddr = 1; + opt->ts_needtime = 1; + optptr[2] += 8; + break; + case IPOPT_TS_PRESPEC: + if (optptr[2]+7 > optptr[1]) { + pp_ptr = optptr + 2; + goto error; + } + opt->ts = optptr - iph; + { + __be32 addr; + memcpy(&addr, &optptr[optptr[2]-1], 4); + if (inet_addr_type(net, addr) == RTN_UNICAST) + break; + if (skb) + timeptr = (__be32*)&optptr[optptr[2]+3]; + } + opt->ts_needtime = 1; + optptr[2] += 8; + break; + default: + if (!skb && !capable(CAP_NET_RAW)) { + pp_ptr = optptr + 3; + goto error; + } + break; + } + if (timeptr) { + struct timespec tv; + __be32 midtime; + getnstimeofday(&tv); + midtime = htonl((tv.tv_sec % 86400) * MSEC_PER_SEC + tv.tv_nsec / NSEC_PER_MSEC); + memcpy(timeptr, &midtime, sizeof(__be32)); + opt->is_changed = 1; + } + } else { + unsigned overflow = optptr[3]>>4; + if (overflow == 15) { + pp_ptr = optptr + 3; + goto error; + } + opt->ts = optptr - iph; + if (skb) { + optptr[3] = (optptr[3]&0xF)|((overflow+1)<<4); + opt->is_changed = 1; + } + } + break; + case IPOPT_RA: + if (optlen < 4) { + pp_ptr = optptr + 1; + goto error; + } + if (optptr[2] == 0 && optptr[3] == 0) + opt->router_alert = optptr - iph; + break; + case IPOPT_CIPSO: + if ((!skb && !capable(CAP_NET_RAW)) || opt->cipso) { + pp_ptr = optptr; + goto error; + } + opt->cipso = optptr - iph; + if (cipso_v4_validate(skb, &optptr)) { + pp_ptr = optptr; + goto error; + } + break; + case IPOPT_SEC: + case IPOPT_SID: + default: + if (!skb && !capable(CAP_NET_RAW)) { + pp_ptr = optptr; + goto error; + } + break; + } + l -= optlen; + optptr += optlen; + } + +eol: + if (!pp_ptr) + return 0; + +error: + if (skb) { + icmp_send(skb, ICMP_PARAMETERPROB, 0, htonl((pp_ptr-iph)<<24)); + } + return -EINVAL; +} +","@@ -36,7 +36,7 @@ + * saddr is address of outgoing interface. + */ + +-void ip_options_build(struct sk_buff * skb, struct ip_options * opt, ++void ip_options_build(struct sk_buff *skb, struct ip_options *opt, + __be32 daddr, struct rtable *rt, int is_frag) + { + unsigned char *iph = skb_network_header(skb); +@@ -83,9 +83,9 @@ void ip_options_build(struct sk_buff * skb, struct ip_options * opt, + * NOTE: dopt cannot point to skb. + */ + +-int ip_options_echo(struct ip_options * dopt, struct sk_buff * skb) ++int ip_options_echo(struct ip_options *dopt, struct sk_buff *skb) + { +- struct ip_options *sopt; ++ const struct ip_options *sopt; + unsigned char *sptr, *dptr; + int soffset, doffset; + int optlen; +@@ -95,10 +95,8 @@ int ip_options_echo(struct ip_options * dopt, struct sk_buff * skb) + + sopt = &(IPCB(skb)->opt); + +- if (sopt->optlen == 0) { +- dopt->optlen = 0; ++ if (sopt->optlen == 0) + return 0; +- } + + sptr = skb_network_header(skb); + dptr = dopt->__data; +@@ -157,7 +155,7 @@ int ip_options_echo(struct ip_options * dopt, struct sk_buff * skb) + dopt->optlen += optlen; + } + if (sopt->srr) { +- unsigned char * start = sptr+sopt->srr; ++ unsigned char *start = sptr+sopt->srr; + __be32 faddr; + + optlen = start[1]; +@@ -499,19 +497,19 @@ void ip_options_undo(struct ip_options * opt) + } + } + +-static struct ip_options *ip_options_get_alloc(const int optlen) ++static struct ip_options_rcu *ip_options_get_alloc(const int optlen) + { +- return kzalloc(sizeof(struct ip_options) + ((optlen + 3) & ~3), ++ return kzalloc(sizeof(struct ip_options_rcu) + ((optlen + 3) & ~3), + GFP_KERNEL); + } + +-static int ip_options_get_finish(struct net *net, struct ip_options **optp, +- struct ip_options *opt, int optlen) ++static int ip_options_get_finish(struct net *net, struct ip_options_rcu **optp, ++ struct ip_options_rcu *opt, int optlen) + { + while (optlen & 3) +- opt->__data[optlen++] = IPOPT_END; +- opt->optlen = optlen; +- if (optlen && ip_options_compile(net, opt, NULL)) { ++ opt->opt.__data[optlen++] = IPOPT_END; ++ opt->opt.optlen = optlen; ++ if (optlen && ip_options_compile(net, &opt->opt, NULL)) { + kfree(opt); + return -EINVAL; + } +@@ -520,29 +518,29 @@ static int ip_options_get_finish(struct net *net, struct ip_options **optp, + return 0; + } + +-int ip_options_get_from_user(struct net *net, struct ip_options **optp, ++int ip_options_get_from_user(struct net *net, struct ip_options_rcu **optp, + unsigned char __user *data, int optlen) + { +- struct ip_options *opt = ip_options_get_alloc(optlen); ++ struct ip_options_rcu *opt = ip_options_get_alloc(optlen); + + if (!opt) + return -ENOMEM; +- if (optlen && copy_from_user(opt->__data, data, optlen)) { ++ if (optlen && copy_from_user(opt->opt.__data, data, optlen)) { + kfree(opt); + return -EFAULT; + } + return ip_options_get_finish(net, optp, opt, optlen); + } + +-int ip_options_get(struct net *net, struct ip_options **optp, ++int ip_options_get(struct net *net, struct ip_options_rcu **optp, + unsigned char *data, int optlen) + { +- struct ip_options *opt = ip_options_get_alloc(optlen); ++ struct ip_options_rcu *opt = ip_options_get_alloc(optlen); + + if (!opt) + return -ENOMEM; + if (optlen) +- memcpy(opt->__data, data, optlen); ++ memcpy(opt->opt.__data, data, optlen); + return ip_options_get_finish(net, optp, opt, optlen); + } + ",1733,2064,4096 +17528,"WORD32 impeg2d_dec_pnb_mb_params(dec_state_t *ps_dec) +{ + stream_t *ps_stream = &ps_dec->s_bit_stream; + UWORD16 u2_mb_addr_incr; + UWORD16 u2_total_len; + UWORD16 u2_len; + UWORD16 u2_mb_type; + UWORD32 u4_next_word; + const dec_mb_params_t *ps_dec_mb_params; + if(impeg2d_bit_stream_nxt(ps_stream,1) == 1) + { + impeg2d_bit_stream_flush(ps_stream,1); + + } + else + { + u2_mb_addr_incr = impeg2d_get_mb_addr_incr(ps_stream); + + if(ps_dec->u2_first_mb) + { + /****************************************************************/ + /* Section 6.3.17 */ + /* The first MB of a slice cannot be skipped */ + /* But the mb_addr_incr can be > 1, because at the beginning of */ + /* a slice, it indicates the offset from the last MB in the */ + /* previous row. Hence for the first slice in a row, the */ + /* mb_addr_incr needs to be 1. */ + /****************************************************************/ + /* MB_x is set to zero whenever MB_y changes. */ + ps_dec->u2_mb_x = u2_mb_addr_incr - 1; + /* For error resilience */ + ps_dec->u2_mb_x = MIN(ps_dec->u2_mb_x, (ps_dec->u2_num_horiz_mb - 1)); + + /****************************************************************/ + /* mb_addr_incr is forced to 1 because in this decoder it is used */ + /* more as an indicator of the number of MBs skipped than the */ + /* as defined by the standard (Section 6.3.17) */ + /****************************************************************/ + u2_mb_addr_incr = 1; + ps_dec->u2_first_mb = 0; + } + else + { + /****************************************************************/ + /* In MPEG-2, the last MB of the row cannot be skipped and the */ + /* mb_addr_incr cannot be such that it will take the current MB */ + /* beyond the current row */ + /* In MPEG-1, the slice could start and end anywhere and is not */ + /* restricted to a row like in MPEG-2. Hence this check should */ + /* not be done for MPEG-1 streams. */ + /****************************************************************/ + if(ps_dec->u2_is_mpeg2 && + ((ps_dec->u2_mb_x + u2_mb_addr_incr) > ps_dec->u2_num_horiz_mb)) + { + u2_mb_addr_incr = ps_dec->u2_num_horiz_mb - ps_dec->u2_mb_x; + } + + if ((u2_mb_addr_incr - 1) > ps_dec->u2_num_mbs_left) + { + /* If the number of skip MBs are more than the number of MBs + * left, indicate error. + */ + return IV_FAIL; + } + + impeg2d_dec_skip_mbs(ps_dec, (UWORD16)(u2_mb_addr_incr - 1)); + } + + } + u4_next_word = (UWORD16)impeg2d_bit_stream_nxt(ps_stream,16); + /*-----------------------------------------------------------------------*/ + /* MB type */ + /*-----------------------------------------------------------------------*/ + { + u2_mb_type = ps_dec->pu2_mb_type[BITS((UWORD16)u4_next_word,15,10)]; + u2_len = BITS(u2_mb_type,15,8); + u2_total_len = u2_len; + u4_next_word = (UWORD16)LSW((UWORD16)u4_next_word << u2_len); + } + /*-----------------------------------------------------------------------*/ + /* motion type */ + /*-----------------------------------------------------------------------*/ + { + WORD32 i4_motion_type = ps_dec->u2_motion_type; + + if((u2_mb_type & MB_FORW_OR_BACK) && ps_dec->u2_read_motion_type) + { + ps_dec->u2_motion_type = BITS((UWORD16)u4_next_word,15,14); + u2_total_len += MB_MOTION_TYPE_LEN; + u4_next_word = (UWORD16)LSW((UWORD16)u4_next_word << MB_MOTION_TYPE_LEN); + i4_motion_type = ps_dec->u2_motion_type; + + } + + + if ((u2_mb_type & MB_FORW_OR_BACK) && + ((i4_motion_type == 0) || + (i4_motion_type == 3) || + (i4_motion_type == 4) || + (i4_motion_type >= 7))) + { + i4_motion_type = 1; + } + + } + /*-----------------------------------------------------------------------*/ + /* dct type */ + /*-----------------------------------------------------------------------*/ + { + if((u2_mb_type & MB_CODED) && ps_dec->u2_read_dct_type) + { + ps_dec->u2_field_dct = BIT((UWORD16)u4_next_word,15); + u2_total_len += MB_DCT_TYPE_LEN; + u4_next_word = (UWORD16)LSW((UWORD16)u4_next_word << MB_DCT_TYPE_LEN); + } + } + /*-----------------------------------------------------------------------*/ + /* Quant scale code */ + /*-----------------------------------------------------------------------*/ + if(u2_mb_type & MB_QUANT) + { + UWORD16 u2_quant_scale_code; + u2_quant_scale_code = BITS((UWORD16)u4_next_word,15,11); + + ps_dec->u1_quant_scale = (ps_dec->u2_q_scale_type) ? + gau1_impeg2_non_linear_quant_scale[u2_quant_scale_code] : (u2_quant_scale_code << 1); + u2_total_len += MB_QUANT_SCALE_CODE_LEN; + } + impeg2d_bit_stream_flush(ps_stream,u2_total_len); + /*-----------------------------------------------------------------------*/ + /* Set the function pointers */ + /*-----------------------------------------------------------------------*/ + ps_dec->u2_coded_mb = (UWORD16)(u2_mb_type & MB_CODED); + + if(u2_mb_type & MB_BIDRECT) + { + UWORD16 u2_index = (ps_dec->u2_motion_type); + + ps_dec->u2_prev_intra_mb = 0; + ps_dec->e_mb_pred = BIDIRECT; + ps_dec_mb_params = &ps_dec->ps_func_bi_direct[u2_index]; + ps_dec->s_mb_type = ps_dec_mb_params->s_mb_type; + if(NULL == ps_dec_mb_params->pf_func_mb_params) + return -1; + ps_dec_mb_params->pf_func_mb_params(ps_dec); + } + else if(u2_mb_type & MB_FORW_OR_BACK) + { + + UWORD16 u2_refPic = !(u2_mb_type & MB_MV_FORW); + UWORD16 u2_index = (ps_dec->u2_motion_type); + ps_dec->u2_prev_intra_mb = 0; + ps_dec->e_mb_pred = (e_pred_direction_t)u2_refPic; + ps_dec_mb_params = &ps_dec->ps_func_forw_or_back[u2_index]; + ps_dec->s_mb_type = ps_dec_mb_params->s_mb_type; + if(NULL == ps_dec_mb_params->pf_func_mb_params) + return -1; + ps_dec_mb_params->pf_func_mb_params(ps_dec); + + } + else if(u2_mb_type & MB_TYPE_INTRA) + { + ps_dec->u2_prev_intra_mb = 1; + impeg2d_dec_intra_mb(ps_dec); + + } + else + { + ps_dec->u2_prev_intra_mb =0; + ps_dec->e_mb_pred = FORW; + ps_dec->u2_motion_type = 0; + impeg2d_dec_0mv_coded_mb(ps_dec); + } + + /*-----------------------------------------------------------------------*/ + /* decode cbp */ + /*-----------------------------------------------------------------------*/ + if((u2_mb_type & MB_TYPE_INTRA)) + { + ps_dec->u2_cbp = 0x3f; + ps_dec->u2_prev_intra_mb = 1; + } + else + { + ps_dec->u2_prev_intra_mb = 0; + ps_dec->u2_def_dc_pred[Y_LUMA] = 128 << ps_dec->u2_intra_dc_precision; + ps_dec->u2_def_dc_pred[U_CHROMA] = 128 << ps_dec->u2_intra_dc_precision; + ps_dec->u2_def_dc_pred[V_CHROMA] = 128 << ps_dec->u2_intra_dc_precision; + if((ps_dec->u2_coded_mb)) + { + UWORD16 cbpValue; + cbpValue = gau2_impeg2d_cbp_code[impeg2d_bit_stream_nxt(ps_stream,MB_CBP_LEN)]; + ps_dec->u2_cbp = cbpValue & 0xFF; + impeg2d_bit_stream_flush(ps_stream,(cbpValue >> 8) & 0x0FF); + } + else + { + ps_dec->u2_cbp = 0; + } + } + return 0; +} +",0,"WORD32 impeg2d_dec_pnb_mb_params(dec_state_t *ps_dec) +{ + stream_t *ps_stream = &ps_dec->s_bit_stream; + UWORD16 u2_mb_addr_incr; + UWORD16 u2_total_len; + UWORD16 u2_len; + UWORD16 u2_mb_type; + UWORD32 u4_next_word; + const dec_mb_params_t *ps_dec_mb_params; + if(impeg2d_bit_stream_nxt(ps_stream,1) == 1) + { + impeg2d_bit_stream_flush(ps_stream,1); + + } + else + { + u2_mb_addr_incr = impeg2d_get_mb_addr_incr(ps_stream); + + if(ps_dec->u2_first_mb) + { + /****************************************************************/ + /* Section 6.3.17 */ + /* The first MB of a slice cannot be skipped */ + /* But the mb_addr_incr can be > 1, because at the beginning of */ + /* a slice, it indicates the offset from the last MB in the */ + /* previous row. Hence for the first slice in a row, the */ + /* mb_addr_incr needs to be 1. */ + /****************************************************************/ + /* MB_x is set to zero whenever MB_y changes. */ + ps_dec->u2_mb_x = u2_mb_addr_incr - 1; + /* For error resilience */ + ps_dec->u2_mb_x = MIN(ps_dec->u2_mb_x, (ps_dec->u2_num_horiz_mb - 1)); + + /****************************************************************/ + /* mb_addr_incr is forced to 1 because in this decoder it is used */ + /* more as an indicator of the number of MBs skipped than the */ + /* as defined by the standard (Section 6.3.17) */ + /****************************************************************/ + u2_mb_addr_incr = 1; + ps_dec->u2_first_mb = 0; + } + else + { + /****************************************************************/ + /* In MPEG-2, the last MB of the row cannot be skipped and the */ + /* mb_addr_incr cannot be such that it will take the current MB */ + /* beyond the current row */ + /* In MPEG-1, the slice could start and end anywhere and is not */ + /* restricted to a row like in MPEG-2. Hence this check should */ + /* not be done for MPEG-1 streams. */ + /****************************************************************/ + if(ps_dec->u2_is_mpeg2 && + ((ps_dec->u2_mb_x + u2_mb_addr_incr) > ps_dec->u2_num_horiz_mb)) + { + u2_mb_addr_incr = ps_dec->u2_num_horiz_mb - ps_dec->u2_mb_x; + } + + if ((u2_mb_addr_incr - 1) > ps_dec->u2_num_mbs_left) + { + /* If the number of skip MBs are more than the number of MBs + * left, indicate error. + */ + return IV_FAIL; + } + + impeg2d_dec_skip_mbs(ps_dec, (UWORD16)(u2_mb_addr_incr - 1)); + } + + } + u4_next_word = (UWORD16)impeg2d_bit_stream_nxt(ps_stream,16); + /*-----------------------------------------------------------------------*/ + /* MB type */ + /*-----------------------------------------------------------------------*/ + { + u2_mb_type = ps_dec->pu2_mb_type[BITS((UWORD16)u4_next_word,15,10)]; + u2_len = BITS(u2_mb_type,15,8); + u2_total_len = u2_len; + u4_next_word = (UWORD16)LSW((UWORD16)u4_next_word << u2_len); + } + /*-----------------------------------------------------------------------*/ + /* motion type */ + /*-----------------------------------------------------------------------*/ + { + WORD32 i4_motion_type = ps_dec->u2_motion_type; + + if((u2_mb_type & MB_FORW_OR_BACK) && ps_dec->u2_read_motion_type) + { + ps_dec->u2_motion_type = BITS((UWORD16)u4_next_word,15,14); + u2_total_len += MB_MOTION_TYPE_LEN; + u4_next_word = (UWORD16)LSW((UWORD16)u4_next_word << MB_MOTION_TYPE_LEN); + i4_motion_type = ps_dec->u2_motion_type; + + } + + + if ((u2_mb_type & MB_FORW_OR_BACK) && + ((i4_motion_type == 0) || + (i4_motion_type == 3) || + (i4_motion_type == 4) || + (i4_motion_type >= 7))) + { + i4_motion_type = 1; + } + + } + /*-----------------------------------------------------------------------*/ + /* dct type */ + /*-----------------------------------------------------------------------*/ + { + if((u2_mb_type & MB_CODED) && ps_dec->u2_read_dct_type) + { + ps_dec->u2_field_dct = BIT((UWORD16)u4_next_word,15); + u2_total_len += MB_DCT_TYPE_LEN; + u4_next_word = (UWORD16)LSW((UWORD16)u4_next_word << MB_DCT_TYPE_LEN); + } + } + /*-----------------------------------------------------------------------*/ + /* Quant scale code */ + /*-----------------------------------------------------------------------*/ + if(u2_mb_type & MB_QUANT) + { + UWORD16 u2_quant_scale_code; + u2_quant_scale_code = BITS((UWORD16)u4_next_word,15,11); + + ps_dec->u1_quant_scale = (ps_dec->u2_q_scale_type) ? + gau1_impeg2_non_linear_quant_scale[u2_quant_scale_code] : (u2_quant_scale_code << 1); + u2_total_len += MB_QUANT_SCALE_CODE_LEN; + } + impeg2d_bit_stream_flush(ps_stream,u2_total_len); + /*-----------------------------------------------------------------------*/ + /* Set the function pointers */ + /*-----------------------------------------------------------------------*/ + ps_dec->u2_coded_mb = (UWORD16)(u2_mb_type & MB_CODED); + + if(u2_mb_type & MB_BIDRECT) + { + UWORD16 u2_index = (ps_dec->u2_motion_type); + + ps_dec->u2_prev_intra_mb = 0; + ps_dec->e_mb_pred = BIDIRECT; + ps_dec_mb_params = &ps_dec->ps_func_bi_direct[u2_index]; + ps_dec->s_mb_type = ps_dec_mb_params->s_mb_type; + if(NULL == ps_dec_mb_params->pf_func_mb_params) + return -1; + ps_dec_mb_params->pf_func_mb_params(ps_dec); + } + else if(u2_mb_type & MB_FORW_OR_BACK) + { + + UWORD16 u2_refPic = !(u2_mb_type & MB_MV_FORW); + UWORD16 u2_index = (ps_dec->u2_motion_type); + ps_dec->u2_prev_intra_mb = 0; + ps_dec->e_mb_pred = (e_pred_direction_t)u2_refPic; + ps_dec_mb_params = &ps_dec->ps_func_forw_or_back[u2_index]; + ps_dec->s_mb_type = ps_dec_mb_params->s_mb_type; + if(NULL == ps_dec_mb_params->pf_func_mb_params) + return -1; + ps_dec_mb_params->pf_func_mb_params(ps_dec); + + } + else if(u2_mb_type & MB_TYPE_INTRA) + { + ps_dec->u2_prev_intra_mb = 1; + impeg2d_dec_intra_mb(ps_dec); + + } + else + { + ps_dec->u2_prev_intra_mb =0; + ps_dec->e_mb_pred = FORW; + ps_dec->u2_motion_type = 0; + impeg2d_dec_0mv_coded_mb(ps_dec); + } + + /*-----------------------------------------------------------------------*/ + /* decode cbp */ + /*-----------------------------------------------------------------------*/ + if((u2_mb_type & MB_TYPE_INTRA)) + { + ps_dec->u2_cbp = 0x3f; + ps_dec->u2_prev_intra_mb = 1; + } + else + { + ps_dec->u2_prev_intra_mb = 0; + ps_dec->u2_def_dc_pred[Y_LUMA] = 128 << ps_dec->u2_intra_dc_precision; + ps_dec->u2_def_dc_pred[U_CHROMA] = 128 << ps_dec->u2_intra_dc_precision; + ps_dec->u2_def_dc_pred[V_CHROMA] = 128 << ps_dec->u2_intra_dc_precision; + if((ps_dec->u2_coded_mb)) + { + UWORD16 cbpValue; + cbpValue = gau2_impeg2d_cbp_code[impeg2d_bit_stream_nxt(ps_stream,MB_CBP_LEN)]; + ps_dec->u2_cbp = cbpValue & 0xFF; + impeg2d_bit_stream_flush(ps_stream,(cbpValue >> 8) & 0x0FF); + } + else + { + ps_dec->u2_cbp = 0; + } + } + return 0; +} +","@@ -510,6 +510,12 @@ + + + if(ret) + return IMPEG2D_MB_TEX_DECODE_ERR; ++ ++ if(0 >= ps_dec->u2_num_mbs_left) ++ { ++ break; ++ } ++ + IMPEG2D_TRACE_MB_START(ps_dec->u2_mb_x, ps_dec->u2_mb_y); + + u4_x_dst_offset = u4_frm_offset + (ps_dec->u2_mb_x << 4); +",1931,2262,4096 +18177,"static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile) +{ + jpc_dec_tcomp_t *tcomp; + int compno; + int rlvlno; + jpc_dec_rlvl_t *rlvl; + jpc_dec_band_t *band; + jpc_dec_prc_t *prc; + int bndno; + jpc_tsfb_band_t *bnd; + int bandno; + jpc_dec_ccp_t *ccp; + int prccnt; + jpc_dec_cblk_t *cblk; + int cblkcnt; + uint_fast32_t tlprcxstart; + uint_fast32_t tlprcystart; + uint_fast32_t brprcxend; + uint_fast32_t brprcyend; + uint_fast32_t tlcbgxstart; + uint_fast32_t tlcbgystart; + uint_fast32_t brcbgxend; + uint_fast32_t brcbgyend; + uint_fast32_t cbgxstart; + uint_fast32_t cbgystart; + uint_fast32_t cbgxend; + uint_fast32_t cbgyend; + uint_fast32_t tlcblkxstart; + uint_fast32_t tlcblkystart; + uint_fast32_t brcblkxend; + uint_fast32_t brcblkyend; + uint_fast32_t cblkxstart; + uint_fast32_t cblkystart; + uint_fast32_t cblkxend; + uint_fast32_t cblkyend; + uint_fast32_t tmpxstart; + uint_fast32_t tmpystart; + uint_fast32_t tmpxend; + uint_fast32_t tmpyend; + jpc_dec_cp_t *cp; + jpc_tsfb_band_t bnds[64]; + jpc_pchg_t *pchg; + int pchgno; + jpc_dec_cmpt_t *cmpt; + + cp = tile->cp; + tile->realmode = 0; + if (cp->mctid == JPC_MCT_ICT) { + tile->realmode = 1; + } + + for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < + dec->numcomps; ++compno, ++tcomp, ++cmpt) { + ccp = &tile->cp->ccps[compno]; + if (ccp->qmfbid == JPC_COX_INS) { + tile->realmode = 1; + } + tcomp->numrlvls = ccp->numrlvls; + if (!(tcomp->rlvls = jas_alloc2(tcomp->numrlvls, + sizeof(jpc_dec_rlvl_t)))) { + return -1; + } + if (!(tcomp->data = jas_seq2d_create(JPC_CEILDIV(tile->xstart, + cmpt->hstep), JPC_CEILDIV(tile->ystart, cmpt->vstep), + JPC_CEILDIV(tile->xend, cmpt->hstep), JPC_CEILDIV(tile->yend, + cmpt->vstep)))) { + return -1; + } + if (!(tcomp->tsfb = jpc_cod_gettsfb(ccp->qmfbid, + tcomp->numrlvls - 1))) { + return -1; + } + { + jpc_tsfb_getbands(tcomp->tsfb, jas_seq2d_xstart(tcomp->data), + jas_seq2d_ystart(tcomp->data), jas_seq2d_xend(tcomp->data), + jas_seq2d_yend(tcomp->data), bnds); + } + for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; + ++rlvlno, ++rlvl) { + rlvl->bands = 0; + rlvl->xstart = JPC_CEILDIVPOW2(tcomp->xstart, + tcomp->numrlvls - 1 - rlvlno); + rlvl->ystart = JPC_CEILDIVPOW2(tcomp->ystart, + tcomp->numrlvls - 1 - rlvlno); + rlvl->xend = JPC_CEILDIVPOW2(tcomp->xend, + tcomp->numrlvls - 1 - rlvlno); + rlvl->yend = JPC_CEILDIVPOW2(tcomp->yend, + tcomp->numrlvls - 1 - rlvlno); + rlvl->prcwidthexpn = ccp->prcwidthexpns[rlvlno]; + rlvl->prcheightexpn = ccp->prcheightexpns[rlvlno]; + tlprcxstart = JPC_FLOORDIVPOW2(rlvl->xstart, + rlvl->prcwidthexpn) << rlvl->prcwidthexpn; + tlprcystart = JPC_FLOORDIVPOW2(rlvl->ystart, + rlvl->prcheightexpn) << rlvl->prcheightexpn; + brprcxend = JPC_CEILDIVPOW2(rlvl->xend, + rlvl->prcwidthexpn) << rlvl->prcwidthexpn; + brprcyend = JPC_CEILDIVPOW2(rlvl->yend, + rlvl->prcheightexpn) << rlvl->prcheightexpn; + rlvl->numhprcs = (brprcxend - tlprcxstart) >> + rlvl->prcwidthexpn; + rlvl->numvprcs = (brprcyend - tlprcystart) >> + rlvl->prcheightexpn; + rlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs; + + if (rlvl->xstart >= rlvl->xend || rlvl->ystart >= rlvl->yend) { + rlvl->bands = 0; + rlvl->numprcs = 0; + rlvl->numhprcs = 0; + rlvl->numvprcs = 0; + continue; + } + if (!rlvlno) { + tlcbgxstart = tlprcxstart; + tlcbgystart = tlprcystart; + brcbgxend = brprcxend; + brcbgyend = brprcyend; + rlvl->cbgwidthexpn = rlvl->prcwidthexpn; + rlvl->cbgheightexpn = rlvl->prcheightexpn; + } else { + tlcbgxstart = JPC_CEILDIVPOW2(tlprcxstart, 1); + tlcbgystart = JPC_CEILDIVPOW2(tlprcystart, 1); + brcbgxend = JPC_CEILDIVPOW2(brprcxend, 1); + brcbgyend = JPC_CEILDIVPOW2(brprcyend, 1); + rlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1; + rlvl->cbgheightexpn = rlvl->prcheightexpn - 1; + } + rlvl->cblkwidthexpn = JAS_MIN(ccp->cblkwidthexpn, + rlvl->cbgwidthexpn); + rlvl->cblkheightexpn = JAS_MIN(ccp->cblkheightexpn, + rlvl->cbgheightexpn); + + rlvl->numbands = (!rlvlno) ? 1 : 3; + if (!(rlvl->bands = jas_alloc2(rlvl->numbands, + sizeof(jpc_dec_band_t)))) { + return -1; + } + for (bandno = 0, band = rlvl->bands; + bandno < rlvl->numbands; ++bandno, ++band) { + bndno = (!rlvlno) ? 0 : (3 * (rlvlno - 1) + + bandno + 1); + bnd = &bnds[bndno]; + + band->orient = bnd->orient; + band->stepsize = ccp->stepsizes[bndno]; + band->analgain = JPC_NOMINALGAIN(ccp->qmfbid, + tcomp->numrlvls - 1, rlvlno, band->orient); + band->absstepsize = jpc_calcabsstepsize(band->stepsize, + cmpt->prec + band->analgain); + band->numbps = ccp->numguardbits + + JPC_QCX_GETEXPN(band->stepsize) - 1; + band->roishift = (ccp->roishift + band->numbps >= JPC_PREC) ? + (JPC_PREC - 1 - band->numbps) : ccp->roishift; + band->data = 0; + band->prcs = 0; + if (bnd->xstart == bnd->xend || bnd->ystart == bnd->yend) { + continue; + } + if (!(band->data = jas_seq2d_create(0, 0, 0, 0))) { + return -1; + } + jas_seq2d_bindsub(band->data, tcomp->data, bnd->locxstart, + bnd->locystart, bnd->locxend, bnd->locyend); + jas_seq2d_setshift(band->data, bnd->xstart, bnd->ystart); + + assert(rlvl->numprcs); + + if (!(band->prcs = jas_alloc2(rlvl->numprcs, + sizeof(jpc_dec_prc_t)))) { + return -1; + } + +/************************************************/ + cbgxstart = tlcbgxstart; + cbgystart = tlcbgystart; + for (prccnt = rlvl->numprcs, prc = band->prcs; + prccnt > 0; --prccnt, ++prc) { + cbgxend = cbgxstart + (1 << rlvl->cbgwidthexpn); + cbgyend = cbgystart + (1 << rlvl->cbgheightexpn); + prc->xstart = JAS_MAX(cbgxstart, JAS_CAST(uint_fast32_t, + jas_seq2d_xstart(band->data))); + prc->ystart = JAS_MAX(cbgystart, JAS_CAST(uint_fast32_t, + jas_seq2d_ystart(band->data))); + prc->xend = JAS_MIN(cbgxend, JAS_CAST(uint_fast32_t, + jas_seq2d_xend(band->data))); + prc->yend = JAS_MIN(cbgyend, JAS_CAST(uint_fast32_t, + jas_seq2d_yend(band->data))); + if (prc->xend > prc->xstart && prc->yend > prc->ystart) { + tlcblkxstart = JPC_FLOORDIVPOW2(prc->xstart, + rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn; + tlcblkystart = JPC_FLOORDIVPOW2(prc->ystart, + rlvl->cblkheightexpn) << rlvl->cblkheightexpn; + brcblkxend = JPC_CEILDIVPOW2(prc->xend, + rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn; + brcblkyend = JPC_CEILDIVPOW2(prc->yend, + rlvl->cblkheightexpn) << rlvl->cblkheightexpn; + prc->numhcblks = (brcblkxend - tlcblkxstart) >> + rlvl->cblkwidthexpn; + prc->numvcblks = (brcblkyend - tlcblkystart) >> + rlvl->cblkheightexpn; + prc->numcblks = prc->numhcblks * prc->numvcblks; + assert(prc->numcblks > 0); + + if (!(prc->incltagtree = jpc_tagtree_create( + prc->numhcblks, prc->numvcblks))) { + return -1; + } + if (!(prc->numimsbstagtree = jpc_tagtree_create( + prc->numhcblks, prc->numvcblks))) { + return -1; + } + if (!(prc->cblks = jas_alloc2(prc->numcblks, + sizeof(jpc_dec_cblk_t)))) { + return -1; + } + + cblkxstart = cbgxstart; + cblkystart = cbgystart; + for (cblkcnt = prc->numcblks, cblk = prc->cblks; + cblkcnt > 0;) { + cblkxend = cblkxstart + (1 << rlvl->cblkwidthexpn); + cblkyend = cblkystart + (1 << rlvl->cblkheightexpn); + tmpxstart = JAS_MAX(cblkxstart, prc->xstart); + tmpystart = JAS_MAX(cblkystart, prc->ystart); + tmpxend = JAS_MIN(cblkxend, prc->xend); + tmpyend = JAS_MIN(cblkyend, prc->yend); + if (tmpxend > tmpxstart && tmpyend > tmpystart) { + cblk->firstpassno = -1; + cblk->mqdec = 0; + cblk->nulldec = 0; + cblk->flags = 0; + cblk->numpasses = 0; + cblk->segs.head = 0; + cblk->segs.tail = 0; + cblk->curseg = 0; + cblk->numimsbs = 0; + cblk->numlenbits = 3; + cblk->flags = 0; + if (!(cblk->data = jas_seq2d_create(0, 0, 0, + 0))) { + return -1; + } + jas_seq2d_bindsub(cblk->data, band->data, + tmpxstart, tmpystart, tmpxend, tmpyend); + ++cblk; + --cblkcnt; + } + cblkxstart += 1 << rlvl->cblkwidthexpn; + if (cblkxstart >= cbgxend) { + cblkxstart = cbgxstart; + cblkystart += 1 << rlvl->cblkheightexpn; + } + } + + } else { + prc->cblks = 0; + prc->incltagtree = 0; + prc->numimsbstagtree = 0; + } + cbgxstart += 1 << rlvl->cbgwidthexpn; + if (cbgxstart >= brcbgxend) { + cbgxstart = tlcbgxstart; + cbgystart += 1 << rlvl->cbgheightexpn; + } + + } +/********************************************/ + } + } + } + + if (!(tile->pi = jpc_dec_pi_create(dec, tile))) { + return -1; + } + + for (pchgno = 0; pchgno < jpc_pchglist_numpchgs(tile->cp->pchglist); + ++pchgno) { + pchg = jpc_pchg_copy(jpc_pchglist_get(tile->cp->pchglist, pchgno)); + assert(pchg); + jpc_pi_addpchg(tile->pi, pchg); + } + jpc_pi_init(tile->pi); + + return 0; +} +",1,"static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile) +{ + jpc_dec_tcomp_t *tcomp; + int compno; + int rlvlno; + jpc_dec_rlvl_t *rlvl; + jpc_dec_band_t *band; + jpc_dec_prc_t *prc; + int bndno; + jpc_tsfb_band_t *bnd; + int bandno; + jpc_dec_ccp_t *ccp; + int prccnt; + jpc_dec_cblk_t *cblk; + int cblkcnt; + uint_fast32_t tlprcxstart; + uint_fast32_t tlprcystart; + uint_fast32_t brprcxend; + uint_fast32_t brprcyend; + uint_fast32_t tlcbgxstart; + uint_fast32_t tlcbgystart; + uint_fast32_t brcbgxend; + uint_fast32_t brcbgyend; + uint_fast32_t cbgxstart; + uint_fast32_t cbgystart; + uint_fast32_t cbgxend; + uint_fast32_t cbgyend; + uint_fast32_t tlcblkxstart; + uint_fast32_t tlcblkystart; + uint_fast32_t brcblkxend; + uint_fast32_t brcblkyend; + uint_fast32_t cblkxstart; + uint_fast32_t cblkystart; + uint_fast32_t cblkxend; + uint_fast32_t cblkyend; + uint_fast32_t tmpxstart; + uint_fast32_t tmpystart; + uint_fast32_t tmpxend; + uint_fast32_t tmpyend; + jpc_dec_cp_t *cp; + jpc_tsfb_band_t bnds[JPC_MAXBANDS]; + jpc_pchg_t *pchg; + int pchgno; + jpc_dec_cmpt_t *cmpt; + + cp = tile->cp; + tile->realmode = 0; + if (cp->mctid == JPC_MCT_ICT) { + tile->realmode = 1; + } + + for (compno = 0, tcomp = tile->tcomps, cmpt = dec->cmpts; compno < + dec->numcomps; ++compno, ++tcomp, ++cmpt) { + ccp = &tile->cp->ccps[compno]; + if (ccp->qmfbid == JPC_COX_INS) { + tile->realmode = 1; + } + tcomp->numrlvls = ccp->numrlvls; + if (!(tcomp->rlvls = jas_alloc2(tcomp->numrlvls, + sizeof(jpc_dec_rlvl_t)))) { + return -1; + } + if (!(tcomp->data = jas_seq2d_create(JPC_CEILDIV(tile->xstart, + cmpt->hstep), JPC_CEILDIV(tile->ystart, cmpt->vstep), + JPC_CEILDIV(tile->xend, cmpt->hstep), JPC_CEILDIV(tile->yend, + cmpt->vstep)))) { + return -1; + } + if (!(tcomp->tsfb = jpc_cod_gettsfb(ccp->qmfbid, + tcomp->numrlvls - 1))) { + return -1; + } + { + jpc_tsfb_getbands(tcomp->tsfb, jas_seq2d_xstart(tcomp->data), + jas_seq2d_ystart(tcomp->data), jas_seq2d_xend(tcomp->data), + jas_seq2d_yend(tcomp->data), bnds); + } + for (rlvlno = 0, rlvl = tcomp->rlvls; rlvlno < tcomp->numrlvls; + ++rlvlno, ++rlvl) { + rlvl->bands = 0; + rlvl->xstart = JPC_CEILDIVPOW2(tcomp->xstart, + tcomp->numrlvls - 1 - rlvlno); + rlvl->ystart = JPC_CEILDIVPOW2(tcomp->ystart, + tcomp->numrlvls - 1 - rlvlno); + rlvl->xend = JPC_CEILDIVPOW2(tcomp->xend, + tcomp->numrlvls - 1 - rlvlno); + rlvl->yend = JPC_CEILDIVPOW2(tcomp->yend, + tcomp->numrlvls - 1 - rlvlno); + rlvl->prcwidthexpn = ccp->prcwidthexpns[rlvlno]; + rlvl->prcheightexpn = ccp->prcheightexpns[rlvlno]; + tlprcxstart = JPC_FLOORDIVPOW2(rlvl->xstart, + rlvl->prcwidthexpn) << rlvl->prcwidthexpn; + tlprcystart = JPC_FLOORDIVPOW2(rlvl->ystart, + rlvl->prcheightexpn) << rlvl->prcheightexpn; + brprcxend = JPC_CEILDIVPOW2(rlvl->xend, + rlvl->prcwidthexpn) << rlvl->prcwidthexpn; + brprcyend = JPC_CEILDIVPOW2(rlvl->yend, + rlvl->prcheightexpn) << rlvl->prcheightexpn; + rlvl->numhprcs = (brprcxend - tlprcxstart) >> + rlvl->prcwidthexpn; + rlvl->numvprcs = (brprcyend - tlprcystart) >> + rlvl->prcheightexpn; + rlvl->numprcs = rlvl->numhprcs * rlvl->numvprcs; + + if (rlvl->xstart >= rlvl->xend || rlvl->ystart >= rlvl->yend) { + rlvl->bands = 0; + rlvl->numprcs = 0; + rlvl->numhprcs = 0; + rlvl->numvprcs = 0; + continue; + } + if (!rlvlno) { + tlcbgxstart = tlprcxstart; + tlcbgystart = tlprcystart; + brcbgxend = brprcxend; + brcbgyend = brprcyend; + rlvl->cbgwidthexpn = rlvl->prcwidthexpn; + rlvl->cbgheightexpn = rlvl->prcheightexpn; + } else { + tlcbgxstart = JPC_CEILDIVPOW2(tlprcxstart, 1); + tlcbgystart = JPC_CEILDIVPOW2(tlprcystart, 1); + brcbgxend = JPC_CEILDIVPOW2(brprcxend, 1); + brcbgyend = JPC_CEILDIVPOW2(brprcyend, 1); + rlvl->cbgwidthexpn = rlvl->prcwidthexpn - 1; + rlvl->cbgheightexpn = rlvl->prcheightexpn - 1; + } + rlvl->cblkwidthexpn = JAS_MIN(ccp->cblkwidthexpn, + rlvl->cbgwidthexpn); + rlvl->cblkheightexpn = JAS_MIN(ccp->cblkheightexpn, + rlvl->cbgheightexpn); + + rlvl->numbands = (!rlvlno) ? 1 : 3; + if (!(rlvl->bands = jas_alloc2(rlvl->numbands, + sizeof(jpc_dec_band_t)))) { + return -1; + } + for (bandno = 0, band = rlvl->bands; + bandno < rlvl->numbands; ++bandno, ++band) { + bndno = (!rlvlno) ? 0 : (3 * (rlvlno - 1) + + bandno + 1); + bnd = &bnds[bndno]; + + band->orient = bnd->orient; + band->stepsize = ccp->stepsizes[bndno]; + band->analgain = JPC_NOMINALGAIN(ccp->qmfbid, + tcomp->numrlvls - 1, rlvlno, band->orient); + band->absstepsize = jpc_calcabsstepsize(band->stepsize, + cmpt->prec + band->analgain); + band->numbps = ccp->numguardbits + + JPC_QCX_GETEXPN(band->stepsize) - 1; + band->roishift = (ccp->roishift + band->numbps >= JPC_PREC) ? + (JPC_PREC - 1 - band->numbps) : ccp->roishift; + band->data = 0; + band->prcs = 0; + if (bnd->xstart == bnd->xend || bnd->ystart == bnd->yend) { + continue; + } + if (!(band->data = jas_seq2d_create(0, 0, 0, 0))) { + return -1; + } + jas_seq2d_bindsub(band->data, tcomp->data, bnd->locxstart, + bnd->locystart, bnd->locxend, bnd->locyend); + jas_seq2d_setshift(band->data, bnd->xstart, bnd->ystart); + + assert(rlvl->numprcs); + + if (!(band->prcs = jas_alloc2(rlvl->numprcs, + sizeof(jpc_dec_prc_t)))) { + return -1; + } + +/************************************************/ + cbgxstart = tlcbgxstart; + cbgystart = tlcbgystart; + for (prccnt = rlvl->numprcs, prc = band->prcs; + prccnt > 0; --prccnt, ++prc) { + cbgxend = cbgxstart + (1 << rlvl->cbgwidthexpn); + cbgyend = cbgystart + (1 << rlvl->cbgheightexpn); + prc->xstart = JAS_MAX(cbgxstart, JAS_CAST(uint_fast32_t, + jas_seq2d_xstart(band->data))); + prc->ystart = JAS_MAX(cbgystart, JAS_CAST(uint_fast32_t, + jas_seq2d_ystart(band->data))); + prc->xend = JAS_MIN(cbgxend, JAS_CAST(uint_fast32_t, + jas_seq2d_xend(band->data))); + prc->yend = JAS_MIN(cbgyend, JAS_CAST(uint_fast32_t, + jas_seq2d_yend(band->data))); + if (prc->xend > prc->xstart && prc->yend > prc->ystart) { + tlcblkxstart = JPC_FLOORDIVPOW2(prc->xstart, + rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn; + tlcblkystart = JPC_FLOORDIVPOW2(prc->ystart, + rlvl->cblkheightexpn) << rlvl->cblkheightexpn; + brcblkxend = JPC_CEILDIVPOW2(prc->xend, + rlvl->cblkwidthexpn) << rlvl->cblkwidthexpn; + brcblkyend = JPC_CEILDIVPOW2(prc->yend, + rlvl->cblkheightexpn) << rlvl->cblkheightexpn; + prc->numhcblks = (brcblkxend - tlcblkxstart) >> + rlvl->cblkwidthexpn; + prc->numvcblks = (brcblkyend - tlcblkystart) >> + rlvl->cblkheightexpn; + prc->numcblks = prc->numhcblks * prc->numvcblks; + assert(prc->numcblks > 0); + + if (!(prc->incltagtree = jpc_tagtree_create( + prc->numhcblks, prc->numvcblks))) { + return -1; + } + if (!(prc->numimsbstagtree = jpc_tagtree_create( + prc->numhcblks, prc->numvcblks))) { + return -1; + } + if (!(prc->cblks = jas_alloc2(prc->numcblks, + sizeof(jpc_dec_cblk_t)))) { + return -1; + } + + cblkxstart = cbgxstart; + cblkystart = cbgystart; + for (cblkcnt = prc->numcblks, cblk = prc->cblks; + cblkcnt > 0;) { + cblkxend = cblkxstart + (1 << rlvl->cblkwidthexpn); + cblkyend = cblkystart + (1 << rlvl->cblkheightexpn); + tmpxstart = JAS_MAX(cblkxstart, prc->xstart); + tmpystart = JAS_MAX(cblkystart, prc->ystart); + tmpxend = JAS_MIN(cblkxend, prc->xend); + tmpyend = JAS_MIN(cblkyend, prc->yend); + if (tmpxend > tmpxstart && tmpyend > tmpystart) { + cblk->firstpassno = -1; + cblk->mqdec = 0; + cblk->nulldec = 0; + cblk->flags = 0; + cblk->numpasses = 0; + cblk->segs.head = 0; + cblk->segs.tail = 0; + cblk->curseg = 0; + cblk->numimsbs = 0; + cblk->numlenbits = 3; + cblk->flags = 0; + if (!(cblk->data = jas_seq2d_create(0, 0, 0, + 0))) { + return -1; + } + jas_seq2d_bindsub(cblk->data, band->data, + tmpxstart, tmpystart, tmpxend, tmpyend); + ++cblk; + --cblkcnt; + } + cblkxstart += 1 << rlvl->cblkwidthexpn; + if (cblkxstart >= cbgxend) { + cblkxstart = cbgxstart; + cblkystart += 1 << rlvl->cblkheightexpn; + } + } + + } else { + prc->cblks = 0; + prc->incltagtree = 0; + prc->numimsbstagtree = 0; + } + cbgxstart += 1 << rlvl->cbgwidthexpn; + if (cbgxstart >= brcbgxend) { + cbgxstart = tlcbgxstart; + cbgystart += 1 << rlvl->cbgheightexpn; + } + + } +/********************************************/ + } + } + } + + if (!(tile->pi = jpc_dec_pi_create(dec, tile))) { + return -1; + } + + for (pchgno = 0; pchgno < jpc_pchglist_numpchgs(tile->cp->pchglist); + ++pchgno) { + pchg = jpc_pchg_copy(jpc_pchglist_get(tile->cp->pchglist, pchgno)); + assert(pchg); + jpc_pi_addpchg(tile->pi, pchg); + } + jpc_pi_init(tile->pi); + + return 0; +} +","@@ -712,7 +712,7 @@ static int jpc_dec_tileinit(jpc_dec_t *dec, jpc_dec_tile_t *tile) + uint_fast32_t tmpxend; + uint_fast32_t tmpyend; + jpc_dec_cp_t *cp; +- jpc_tsfb_band_t bnds[64]; ++ jpc_tsfb_band_t bnds[JPC_MAXBANDS]; + jpc_pchg_t *pchg; + int pchgno; + jpc_dec_cmpt_t *cmpt;",3622,3953,4096 +5194,"gdImagePtr gdImageCreateFromGd2PartCtx (gdIOCtx * in, int srcx, int srcy, int w, int h) +{ + int scx, scy, ecx, ecy, fsx, fsy; + int nc, ncx, ncy, cs, cx, cy; + int x, y, ylo, yhi, xlo, xhi; + int dstart, dpos; + int i; + /* 2.0.12: unsigned is correct; fixes problems with color munging. Thanks to Steven Brown. */ + unsigned int ch; + int vers, fmt; + t_chunk_info *chunkIdx = NULL; + unsigned char *chunkBuf = NULL; + int chunkNum; + int chunkMax = 0; + uLongf chunkLen; + int chunkPos = 0; + int compMax; + char *compBuf = NULL; + + gdImagePtr im; + + if (w<1 || h <1) { + return 0; + } + + /* The next few lines are basically copied from gd2CreateFromFile + * we change the file size, so don't want to use the code directly. + * but we do need to know the file size. + */ + if (_gd2GetHeader(in, &fsx, &fsy, &cs, &vers, &fmt, &ncx, &ncy, &chunkIdx) != 1) { + goto fail1; + } + + GD2_DBG(php_gd_error(""File size is %dx%d"", fsx, fsy)); + + /* This is the difference - make a file based on size of chunks. */ + if (gd2_truecolor(fmt)) { + im = gdImageCreateTrueColor(w, h); + } else { + im = gdImageCreate(w, h); + } + if (im == NULL) { + goto fail1; + } + + if (!_gdGetColors(in, im, vers == 2)) { + goto fail2; + } + GD2_DBG(php_gd_error(""Image palette completed: %d colours"", im->colorsTotal)); + + /* Process the header info */ + nc = ncx * ncy; + + if (gd2_compressed(fmt)) { + /* Find the maximum compressed chunk size. */ + compMax = 0; + for (i = 0; (i < nc); i++) { + if (chunkIdx[i].size > compMax) { + compMax = chunkIdx[i].size; + } + } + compMax++; + + if (im->trueColor) { + chunkMax = cs * cs * 4; + } else { + chunkMax = cs * cs; + } + if (chunkMax <= 0) { + goto fail2; + } + + chunkBuf = gdCalloc(chunkMax, 1); + compBuf = gdCalloc(compMax, 1); + } + + /* Work out start/end chunks */ + scx = srcx / cs; + scy = srcy / cs; + if (scx < 0) { + scx = 0; + } + if (scy < 0) { + scy = 0; + } + + ecx = (srcx + w) / cs; + ecy = (srcy + h) / cs; + if (ecx >= ncx) { + ecx = ncx - 1; + } + if (ecy >= ncy) { + ecy = ncy - 1; + } + + /* Remember file position of image data. */ + dstart = gdTell(in); + GD2_DBG(php_gd_error(""Data starts at %d"", dstart)); + + /* Loop through the chunks. */ + for (cy = scy; (cy <= ecy); cy++) { + ylo = cy * cs; + yhi = ylo + cs; + if (yhi > fsy) { + yhi = fsy; + } + + for (cx = scx; cx <= ecx; cx++) { + + xlo = cx * cs; + xhi = xlo + cs; + if (xhi > fsx) { + xhi = fsx; + } + + GD2_DBG(php_gd_error(""Processing Chunk (%d, %d), from %d to %d"", cx, cy, ylo, yhi)); + + if (!gd2_compressed(fmt)) { + GD2_DBG(php_gd_error(""Using raw format data"")); + if (im->trueColor) { + dpos = (cy * (cs * fsx) * 4 + cx * cs * (yhi - ylo) * 4) + dstart; + } else { + dpos = cy * (cs * fsx) + cx * cs * (yhi - ylo) + dstart; + } + + /* gd 2.0.11: gdSeek returns TRUE on success, not 0. Longstanding bug. 01/16/03 */ + if (!gdSeek(in, dpos)) { + php_gd_error_ex(E_WARNING, ""Error from seek: %d"", errno); + goto fail2; + } + GD2_DBG(php_gd_error(""Reading (%d, %d) from position %d"", cx, cy, dpos - dstart)); + } else { + chunkNum = cx + cy * ncx; + + chunkLen = chunkMax; + if (!_gd2ReadChunk (chunkIdx[chunkNum].offset, compBuf, chunkIdx[chunkNum].size, (char *)chunkBuf, &chunkLen, in)) { + php_gd_error(""Error reading comproessed chunk""); + goto fail2; + } + chunkPos = 0; + GD2_DBG(php_gd_error(""Reading (%d, %d) from chunk %d"", cx, cy, chunkNum)); + } + + GD2_DBG(php_gd_error("" into (%d, %d) - (%d, %d)"", xlo, ylo, xhi, yhi)); + + for (y = ylo; (y < yhi); y++) { + for (x = xlo; x < xhi; x++) { + if (!gd2_compressed(fmt)) { + if (im->trueColor) { + if (!gdGetInt((int *)&ch, in)) { + ch = 0; + } + } else { + ch = gdGetC(in); + if ((int)ch == EOF) { + ch = 0; + } + } + } else { + if (im->trueColor) { + ch = chunkBuf[chunkPos++]; + ch = (ch << 8) + chunkBuf[chunkPos++]; + ch = (ch << 8) + chunkBuf[chunkPos++]; + ch = (ch << 8) + chunkBuf[chunkPos++]; + } else { + ch = chunkBuf[chunkPos++]; + } + } + + /* Only use a point that is in the image. */ + if ((x >= srcx) && (x < (srcx + w)) && (x < fsx) && (x >= 0) && (y >= srcy) && (y < (srcy + h)) && (y < fsy) && (y >= 0)) { + if (im->trueColor) { + im->tpixels[y - srcy][x - srcx] = ch; + } else { + im->pixels[y - srcy][x - srcx] = ch; + } + } + } + } + } + } + + if (chunkBuf) { + gdFree(chunkBuf); + } + if (compBuf) { + gdFree(compBuf); + } + if (chunkIdx) { + gdFree(chunkIdx); + } + + return im; + +fail2: + gdImageDestroy(im); +fail1: + if (chunkBuf) { + gdFree(chunkBuf); + } + if (compBuf) { + gdFree(compBuf); + } + if (chunkIdx) { + gdFree(chunkIdx); + } + + return 0; +} +",0,"gdImagePtr gdImageCreateFromGd2PartCtx (gdIOCtx * in, int srcx, int srcy, int w, int h) +{ + int scx, scy, ecx, ecy, fsx, fsy; + int nc, ncx, ncy, cs, cx, cy; + int x, y, ylo, yhi, xlo, xhi; + int dstart, dpos; + int i; + /* 2.0.12: unsigned is correct; fixes problems with color munging. Thanks to Steven Brown. */ + unsigned int ch; + int vers, fmt; + t_chunk_info *chunkIdx = NULL; + unsigned char *chunkBuf = NULL; + int chunkNum; + int chunkMax = 0; + uLongf chunkLen; + int chunkPos = 0; + int compMax; + char *compBuf = NULL; + + gdImagePtr im; + + if (w<1 || h <1) { + return 0; + } + + /* The next few lines are basically copied from gd2CreateFromFile + * we change the file size, so don't want to use the code directly. + * but we do need to know the file size. + */ + if (_gd2GetHeader(in, &fsx, &fsy, &cs, &vers, &fmt, &ncx, &ncy, &chunkIdx) != 1) { + goto fail1; + } + + GD2_DBG(php_gd_error(""File size is %dx%d"", fsx, fsy)); + + /* This is the difference - make a file based on size of chunks. */ + if (gd2_truecolor(fmt)) { + im = gdImageCreateTrueColor(w, h); + } else { + im = gdImageCreate(w, h); + } + if (im == NULL) { + goto fail1; + } + + if (!_gdGetColors(in, im, vers == 2)) { + goto fail2; + } + GD2_DBG(php_gd_error(""Image palette completed: %d colours"", im->colorsTotal)); + + /* Process the header info */ + nc = ncx * ncy; + + if (gd2_compressed(fmt)) { + /* Find the maximum compressed chunk size. */ + compMax = 0; + for (i = 0; (i < nc); i++) { + if (chunkIdx[i].size > compMax) { + compMax = chunkIdx[i].size; + } + } + compMax++; + + if (im->trueColor) { + chunkMax = cs * cs * 4; + } else { + chunkMax = cs * cs; + } + if (chunkMax <= 0) { + goto fail2; + } + + chunkBuf = gdCalloc(chunkMax, 1); + compBuf = gdCalloc(compMax, 1); + } + + /* Work out start/end chunks */ + scx = srcx / cs; + scy = srcy / cs; + if (scx < 0) { + scx = 0; + } + if (scy < 0) { + scy = 0; + } + + ecx = (srcx + w) / cs; + ecy = (srcy + h) / cs; + if (ecx >= ncx) { + ecx = ncx - 1; + } + if (ecy >= ncy) { + ecy = ncy - 1; + } + + /* Remember file position of image data. */ + dstart = gdTell(in); + GD2_DBG(php_gd_error(""Data starts at %d"", dstart)); + + /* Loop through the chunks. */ + for (cy = scy; (cy <= ecy); cy++) { + ylo = cy * cs; + yhi = ylo + cs; + if (yhi > fsy) { + yhi = fsy; + } + + for (cx = scx; cx <= ecx; cx++) { + + xlo = cx * cs; + xhi = xlo + cs; + if (xhi > fsx) { + xhi = fsx; + } + + GD2_DBG(php_gd_error(""Processing Chunk (%d, %d), from %d to %d"", cx, cy, ylo, yhi)); + + if (!gd2_compressed(fmt)) { + GD2_DBG(php_gd_error(""Using raw format data"")); + if (im->trueColor) { + dpos = (cy * (cs * fsx) * 4 + cx * cs * (yhi - ylo) * 4) + dstart; + } else { + dpos = cy * (cs * fsx) + cx * cs * (yhi - ylo) + dstart; + } + + /* gd 2.0.11: gdSeek returns TRUE on success, not 0. Longstanding bug. 01/16/03 */ + if (!gdSeek(in, dpos)) { + php_gd_error_ex(E_WARNING, ""Error from seek: %d"", errno); + goto fail2; + } + GD2_DBG(php_gd_error(""Reading (%d, %d) from position %d"", cx, cy, dpos - dstart)); + } else { + chunkNum = cx + cy * ncx; + + chunkLen = chunkMax; + if (!_gd2ReadChunk (chunkIdx[chunkNum].offset, compBuf, chunkIdx[chunkNum].size, (char *)chunkBuf, &chunkLen, in)) { + php_gd_error(""Error reading comproessed chunk""); + goto fail2; + } + chunkPos = 0; + GD2_DBG(php_gd_error(""Reading (%d, %d) from chunk %d"", cx, cy, chunkNum)); + } + + GD2_DBG(php_gd_error("" into (%d, %d) - (%d, %d)"", xlo, ylo, xhi, yhi)); + + for (y = ylo; (y < yhi); y++) { + for (x = xlo; x < xhi; x++) { + if (!gd2_compressed(fmt)) { + if (im->trueColor) { + if (!gdGetInt((int *)&ch, in)) { + ch = 0; + } + } else { + ch = gdGetC(in); + if ((int)ch == EOF) { + ch = 0; + } + } + } else { + if (im->trueColor) { + ch = chunkBuf[chunkPos++]; + ch = (ch << 8) + chunkBuf[chunkPos++]; + ch = (ch << 8) + chunkBuf[chunkPos++]; + ch = (ch << 8) + chunkBuf[chunkPos++]; + } else { + ch = chunkBuf[chunkPos++]; + } + } + + /* Only use a point that is in the image. */ + if ((x >= srcx) && (x < (srcx + w)) && (x < fsx) && (x >= 0) && (y >= srcy) && (y < (srcy + h)) && (y < fsy) && (y >= 0)) { + if (im->trueColor) { + im->tpixels[y - srcy][x - srcx] = ch; + } else { + im->pixels[y - srcy][x - srcx] = ch; + } + } + } + } + } + } + + if (chunkBuf) { + gdFree(chunkBuf); + } + if (compBuf) { + gdFree(compBuf); + } + if (chunkIdx) { + gdFree(chunkIdx); + } + + return im; + +fail2: + gdImageDestroy(im); +fail1: + if (chunkBuf) { + gdFree(chunkBuf); + } + if (compBuf) { + gdFree(compBuf); + } + if (chunkIdx) { + gdFree(chunkIdx); + } + + return 0; +} +","@@ -138,11 +138,18 @@ static int _gd2GetHeader(gdIOCtxPtr in, int *sx, int *sy, int *cs, int *vers, in + if (gd2_compressed(*fmt)) { + nc = (*ncx) * (*ncy); + GD2_DBG(php_gd_error(""Reading %d chunk index entries"", nc)); ++ if (overflow2(sidx, nc)) { ++ goto fail1; ++ } + sidx = sizeof(t_chunk_info) * nc; + if (sidx <= 0) { + goto fail1; + } + cidx = gdCalloc(sidx, 1); ++ if (cidx == NULL) { ++ goto fail1; ++ } ++ + for (i = 0; i < nc; i++) { + if (gdGetInt(&cidx[i].offset, in) != 1) { + gdFree(cidx);",1768,2099,4096 +6472,"static int iw_prepare_processing(struct iw_context *ctx, int w, int h) +{ + int i,j; + int output_maxcolorcode_int; + int strategy1, strategy2; + int flag; + + if(ctx->output_profile==0) { + iw_set_error(ctx,""Output profile not set""); + return 0; + } + + if(!ctx->prng) { + ctx->prng = iwpvt_prng_create(ctx); + } + + if(ctx->randomize) { + ctx->random_seed = iwpvt_util_randomize(ctx->prng); + } + + if(ctx->req.out_true_valid) { + ctx->resize_settings[IW_DIMENSION_H].out_true_size = ctx->req.out_true_width; + ctx->resize_settings[IW_DIMENSION_V].out_true_size = ctx->req.out_true_height; + } + else { + ctx->resize_settings[IW_DIMENSION_H].out_true_size = (double)w; + ctx->resize_settings[IW_DIMENSION_V].out_true_size = (double)h; + } + + if(!iw_check_image_dimensions(ctx,ctx->img1.width,ctx->img1.height)) { + return 0; + } + if(!iw_check_image_dimensions(ctx,w,h)) { + return 0; + } + + if(ctx->to_grayscale) { + prepare_grayscale(ctx); + } + + init_channel_info(ctx); + + ctx->img2.width = w; + ctx->img2.height = h; + + if(ctx->input_start_x<0) ctx->input_start_x=0; + if(ctx->input_start_y<0) ctx->input_start_y=0; + if(ctx->input_start_x>ctx->img1.width-1) ctx->input_start_x=ctx->img1.width-1; + if(ctx->input_start_y>ctx->img1.height-1) ctx->input_start_x=ctx->img1.height-1; + if(ctx->input_w<0) ctx->input_w = ctx->img1.width - ctx->input_start_x; + if(ctx->input_h<0) ctx->input_h = ctx->img1.height - ctx->input_start_y; + if(ctx->input_w<1) ctx->input_w = 1; + if(ctx->input_h<1) ctx->input_h = 1; + if(ctx->input_w>(ctx->img1.width-ctx->input_start_x)) ctx->input_w=ctx->img1.width-ctx->input_start_x; + if(ctx->input_h>(ctx->img1.height-ctx->input_start_y)) ctx->input_h=ctx->img1.height-ctx->input_start_y; + + if(ctx->req.output_cs_valid) { + ctx->img2cs = ctx->req.output_cs; + + if(ctx->output_profile&IW_PROFILE_ALWAYSLINEAR) { + if(ctx->img2cs.cstype!=IW_CSTYPE_LINEAR) { + iw_warning(ctx,""Forcing output colorspace to linear; required by the output format.""); + iw_make_linear_csdescr(&ctx->img2cs); + } + } + } + else { + if(ctx->output_profile&IW_PROFILE_ALWAYSLINEAR) { + iw_make_linear_csdescr(&ctx->img2cs); + } + else { + iw_make_srgb_csdescr_2(&ctx->img2cs); + } + } + + if(ctx->img1.sampletype!=IW_SAMPLETYPE_FLOATINGPOINT) { + ctx->input_maxcolorcode_int = (1 << ctx->img1.bit_depth)-1; + ctx->input_maxcolorcode = (double)ctx->input_maxcolorcode_int; + + for(i=0;iimg1_ci[i].maxcolorcode_int<=0) { + ctx->img1_ci[i].maxcolorcode_int = ctx->input_maxcolorcode_int; + } + ctx->img1_ci[i].maxcolorcode_dbl = (double)ctx->img1_ci[i].maxcolorcode_int; + + if(ctx->img1_ci[i].maxcolorcode_int != ctx->input_maxcolorcode_int) { + ctx->support_reduced_input_bitdepths = 1; + } + } + } + + if(ctx->support_reduced_input_bitdepths || + ctx->img1.sampletype==IW_SAMPLETYPE_FLOATINGPOINT) + { + for(i=0;iimg1_numchannels_physical;i++) { + ctx->img1_ci[i].disable_fast_get_sample=1; + } + } + + for(i=0;i<2;i++) { // horizontal, vertical + for(j=0;j<3;j++) { // red, green, blue + if(fabs(ctx->resize_settings[i].channel_offset[j])>0.00001) { + ctx->resize_settings[i].use_offset=1; + } + } + } + + if(ctx->to_grayscale && + (ctx->resize_settings[IW_DIMENSION_H].use_offset || + ctx->resize_settings[IW_DIMENSION_V].use_offset) ) + { + iw_warning(ctx,""Disabling channel offset, due to grayscale output.""); + ctx->resize_settings[IW_DIMENSION_H].use_offset=0; + ctx->resize_settings[IW_DIMENSION_V].use_offset=0; + } + + decide_how_to_apply_bkgd(ctx); + + for(i=0;i<2;i++) { + if(ctx->resize_settings[i].use_offset || + (ctx->apply_bkgd && + ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_EARLY && + ctx->resize_settings[i].edge_policy==IW_EDGE_POLICY_TRANSPARENT)) + { + ctx->resize_settings[i].disable_rrctx_cache=1; + } + } + + decide_strategy(ctx,&strategy1,&strategy2); + + switch(strategy1) { // input-to-intermediate + case IW_STRAT1_RGBA_RGBA: + ctx->intermed_imgtype = IW_IMGTYPE_RGBA; + break; + case IW_STRAT1_GA_RGBA: + ctx->intermed_imgtype = IW_IMGTYPE_RGBA; + ctx->intermed_ci[0].corresponding_input_channel=0; + ctx->intermed_ci[1].corresponding_input_channel=0; + ctx->intermed_ci[2].corresponding_input_channel=0; + ctx->intermed_ci[3].corresponding_input_channel=1; + break; + case IW_STRAT1_RGB_RGB: + case IW_STRAT1_RGBA_RGB: + ctx->intermed_imgtype = IW_IMGTYPE_RGB; + break; + case IW_STRAT1_G_RGB: + case IW_STRAT1_GA_RGB: + ctx->intermed_imgtype = IW_IMGTYPE_RGB; + ctx->intermed_ci[0].corresponding_input_channel=0; + ctx->intermed_ci[1].corresponding_input_channel=0; + ctx->intermed_ci[2].corresponding_input_channel=0; + break; + case IW_STRAT1_RGBA_GA: + ctx->intermed_imgtype = IW_IMGTYPE_GRAYA; + ctx->intermed_ci[0].cvt_to_grayscale=1; + ctx->intermed_ci[0].corresponding_input_channel=0; + ctx->intermed_ci[1].corresponding_input_channel=3; + break; + case IW_STRAT1_GA_GA: + ctx->intermed_imgtype = IW_IMGTYPE_GRAYA; + break; + case IW_STRAT1_RGB_G: + ctx->intermed_imgtype = IW_IMGTYPE_GRAY; + ctx->intermed_ci[0].cvt_to_grayscale=1; + ctx->intermed_ci[0].corresponding_input_channel=0; + break; + case IW_STRAT1_G_G: + ctx->intermed_imgtype = IW_IMGTYPE_GRAY; + ctx->intermed_ci[0].corresponding_input_channel=0; + break; + default: + iw_set_errorf(ctx,""Internal error, unknown strategy %d"",strategy1); + return 0; + } + + ctx->intermed_numchannels = iw_imgtype_num_channels(ctx->intermed_imgtype); + ctx->intermed_alpha_channel_index = iw_imgtype_alpha_channel_index(ctx->intermed_imgtype); + + for(i=0;iintermed_numchannels;i++) { + ctx->intermed_ci[i].corresponding_output_channel = i; + } + + switch(strategy2) { // intermediate-to-output + case IW_STRAT2_RGBA_RGBA: + ctx->img2.imgtype = IW_IMGTYPE_RGBA; + break; + case IW_STRAT2_RGB_RGB: + ctx->img2.imgtype = IW_IMGTYPE_RGB; + break; + case IW_STRAT2_RGBA_RGB: + ctx->img2.imgtype = IW_IMGTYPE_RGB; + ctx->intermed_ci[3].corresponding_output_channel= -1; + break; + case IW_STRAT2_GA_GA: + ctx->img2.imgtype = IW_IMGTYPE_GRAYA; + break; + case IW_STRAT2_G_G: + ctx->img2.imgtype = IW_IMGTYPE_GRAY; + break; + case IW_STRAT2_GA_G: + ctx->img2.imgtype = IW_IMGTYPE_GRAY; + ctx->intermed_ci[1].corresponding_output_channel= -1; + break; + default: + iw_set_error(ctx,""Internal error""); + return 0; + } + + ctx->img2_numchannels = iw_imgtype_num_channels(ctx->img2.imgtype); + + iw_set_intermed_channeltypes(ctx); + iw_set_out_channeltypes(ctx); + + if(IW_IMGTYPE_HAS_ALPHA(ctx->intermed_imgtype)) { + for(i=0;iintermed_numchannels;i++) { + if(ctx->intermed_ci[i].channeltype!=IW_CHANNELTYPE_ALPHA) + ctx->intermed_ci[i].need_unassoc_alpha_processing = 1; + } + } + + + decide_output_bit_depth(ctx); + + if(ctx->img2.sampletype==IW_SAMPLETYPE_FLOATINGPOINT) { + flag=0; + for(i=0;ireq.color_count[i]) flag=1; + } + if(flag) { + iw_warning(ctx,""Posterization is not supported with floating point output.""); + } + } + else { + output_maxcolorcode_int = (1 << ctx->img2.bit_depth)-1; + + for(i=0;iimg2_numchannels;i++) { + ctx->img2_ci[i].maxcolorcode_int = output_maxcolorcode_int; + } + + if((ctx->output_profile&IW_PROFILE_REDUCEDBITDEPTHS)) { + for(i=0;iimg2_numchannels;i++) { + int mccr; + mccr = ctx->req.output_maxcolorcode[ctx->img2_ci[i].channeltype]; + if(mccr>0) { + if(mccr>output_maxcolorcode_int) mccr=output_maxcolorcode_int; + ctx->img2_ci[i].maxcolorcode_int = mccr; + } + } + } + + for(i=0;iimg2_numchannels;i++) { + if(ctx->img2_ci[i].maxcolorcode_int != output_maxcolorcode_int) { + ctx->reduced_output_maxcolor_flag = 1; + ctx->disable_output_lookup_tables = 1; + } + + ctx->img2_ci[i].maxcolorcode_dbl = (double)ctx->img2_ci[i].maxcolorcode_int; + } + } + + for(i=0;iimg2_numchannels;i++) { + ctx->img2_ci[i].color_count = ctx->req.color_count[ctx->img2_ci[i].channeltype]; + if(ctx->img2_ci[i].color_count) { + iw_restrict_to_range(2,ctx->img2_ci[i].maxcolorcode_int,&ctx->img2_ci[i].color_count); + } + if(ctx->img2_ci[i].color_count==1+ctx->img2_ci[i].maxcolorcode_int) { + ctx->img2_ci[i].color_count = 0; + } + + ctx->img2_ci[i].ditherfamily = ctx->ditherfamily_by_channeltype[ctx->img2_ci[i].channeltype]; + ctx->img2_ci[i].dithersubtype = ctx->dithersubtype_by_channeltype[ctx->img2_ci[i].channeltype]; + } + + for(i=0;iimg2_numchannels;i++) { + if(ctx->img2_ci[i].ditherfamily==IW_DITHERFAMILY_ERRDIFF) { + ctx->uses_errdiffdither=1; + } + } + + if(!ctx->support_reduced_input_bitdepths && ctx->img1.sampletype==IW_SAMPLETYPE_UINT) { + iw_make_x_to_linear_table(ctx,&ctx->input_color_corr_table,&ctx->img1,&ctx->img1cs); + } + + if(ctx->img1_bkgd_label_set) { + for(i=0;i<3;i++) { + ctx->img1_bkgd_label_lin.c[i] = x_to_linear_sample(ctx->img1_bkgd_label_inputcs.c[i],&ctx->img1cs); + } + ctx->img1_bkgd_label_lin.c[3] = ctx->img1_bkgd_label_inputcs.c[3]; + } + + if(ctx->apply_bkgd) { + prepare_apply_bkgd(ctx); + } + + if(ctx->req.output_rendering_intent==IW_INTENT_UNKNOWN) { + ctx->img2.rendering_intent = ctx->img1.rendering_intent; + } + else { + ctx->img2.rendering_intent = ctx->req.output_rendering_intent; + } + + if(ctx->resize_settings[IW_DIMENSION_H].family==IW_RESIZETYPE_AUTO) { + iw_set_auto_resizetype(ctx,ctx->input_w,ctx->img2.width,IW_DIMENSION_H); + } + if(ctx->resize_settings[IW_DIMENSION_V].family==IW_RESIZETYPE_AUTO) { + iw_set_auto_resizetype(ctx,ctx->input_h,ctx->img2.height,IW_DIMENSION_V); + } + + if(IW_IMGTYPE_HAS_ALPHA(ctx->img2.imgtype)) { + if(!ctx->opt_strip_alpha) { + ctx->opt_palette = 0; + ctx->opt_binary_trns = 0; + } + } + + return 1; +} +",0,"static int iw_prepare_processing(struct iw_context *ctx, int w, int h) +{ + int i,j; + int output_maxcolorcode_int; + int strategy1, strategy2; + int flag; + + if(ctx->output_profile==0) { + iw_set_error(ctx,""Output profile not set""); + return 0; + } + + if(!ctx->prng) { + ctx->prng = iwpvt_prng_create(ctx); + } + + if(ctx->randomize) { + ctx->random_seed = iwpvt_util_randomize(ctx->prng); + } + + if(ctx->req.out_true_valid) { + ctx->resize_settings[IW_DIMENSION_H].out_true_size = ctx->req.out_true_width; + ctx->resize_settings[IW_DIMENSION_V].out_true_size = ctx->req.out_true_height; + } + else { + ctx->resize_settings[IW_DIMENSION_H].out_true_size = (double)w; + ctx->resize_settings[IW_DIMENSION_V].out_true_size = (double)h; + } + + if(!iw_check_image_dimensions(ctx,ctx->img1.width,ctx->img1.height)) { + return 0; + } + if(!iw_check_image_dimensions(ctx,w,h)) { + return 0; + } + + if(ctx->to_grayscale) { + prepare_grayscale(ctx); + } + + init_channel_info(ctx); + + ctx->img2.width = w; + ctx->img2.height = h; + + if(ctx->input_start_x<0) ctx->input_start_x=0; + if(ctx->input_start_y<0) ctx->input_start_y=0; + if(ctx->input_start_x>ctx->img1.width-1) ctx->input_start_x=ctx->img1.width-1; + if(ctx->input_start_y>ctx->img1.height-1) ctx->input_start_x=ctx->img1.height-1; + if(ctx->input_w<0) ctx->input_w = ctx->img1.width - ctx->input_start_x; + if(ctx->input_h<0) ctx->input_h = ctx->img1.height - ctx->input_start_y; + if(ctx->input_w<1) ctx->input_w = 1; + if(ctx->input_h<1) ctx->input_h = 1; + if(ctx->input_w>(ctx->img1.width-ctx->input_start_x)) ctx->input_w=ctx->img1.width-ctx->input_start_x; + if(ctx->input_h>(ctx->img1.height-ctx->input_start_y)) ctx->input_h=ctx->img1.height-ctx->input_start_y; + + if(ctx->req.output_cs_valid) { + ctx->img2cs = ctx->req.output_cs; + + if(ctx->output_profile&IW_PROFILE_ALWAYSLINEAR) { + if(ctx->img2cs.cstype!=IW_CSTYPE_LINEAR) { + iw_warning(ctx,""Forcing output colorspace to linear; required by the output format.""); + iw_make_linear_csdescr(&ctx->img2cs); + } + } + } + else { + if(ctx->output_profile&IW_PROFILE_ALWAYSLINEAR) { + iw_make_linear_csdescr(&ctx->img2cs); + } + else { + iw_make_srgb_csdescr_2(&ctx->img2cs); + } + } + + if(ctx->img1.sampletype!=IW_SAMPLETYPE_FLOATINGPOINT) { + ctx->input_maxcolorcode_int = (1 << ctx->img1.bit_depth)-1; + ctx->input_maxcolorcode = (double)ctx->input_maxcolorcode_int; + + for(i=0;iimg1_ci[i].maxcolorcode_int<=0) { + ctx->img1_ci[i].maxcolorcode_int = ctx->input_maxcolorcode_int; + } + ctx->img1_ci[i].maxcolorcode_dbl = (double)ctx->img1_ci[i].maxcolorcode_int; + + if(ctx->img1_ci[i].maxcolorcode_int != ctx->input_maxcolorcode_int) { + ctx->support_reduced_input_bitdepths = 1; + } + } + } + + if(ctx->support_reduced_input_bitdepths || + ctx->img1.sampletype==IW_SAMPLETYPE_FLOATINGPOINT) + { + for(i=0;iimg1_numchannels_physical;i++) { + ctx->img1_ci[i].disable_fast_get_sample=1; + } + } + + for(i=0;i<2;i++) { // horizontal, vertical + for(j=0;j<3;j++) { // red, green, blue + if(fabs(ctx->resize_settings[i].channel_offset[j])>0.00001) { + ctx->resize_settings[i].use_offset=1; + } + } + } + + if(ctx->to_grayscale && + (ctx->resize_settings[IW_DIMENSION_H].use_offset || + ctx->resize_settings[IW_DIMENSION_V].use_offset) ) + { + iw_warning(ctx,""Disabling channel offset, due to grayscale output.""); + ctx->resize_settings[IW_DIMENSION_H].use_offset=0; + ctx->resize_settings[IW_DIMENSION_V].use_offset=0; + } + + decide_how_to_apply_bkgd(ctx); + + for(i=0;i<2;i++) { + if(ctx->resize_settings[i].use_offset || + (ctx->apply_bkgd && + ctx->apply_bkgd_strategy==IW_BKGD_STRATEGY_EARLY && + ctx->resize_settings[i].edge_policy==IW_EDGE_POLICY_TRANSPARENT)) + { + ctx->resize_settings[i].disable_rrctx_cache=1; + } + } + + decide_strategy(ctx,&strategy1,&strategy2); + + switch(strategy1) { // input-to-intermediate + case IW_STRAT1_RGBA_RGBA: + ctx->intermed_imgtype = IW_IMGTYPE_RGBA; + break; + case IW_STRAT1_GA_RGBA: + ctx->intermed_imgtype = IW_IMGTYPE_RGBA; + ctx->intermed_ci[0].corresponding_input_channel=0; + ctx->intermed_ci[1].corresponding_input_channel=0; + ctx->intermed_ci[2].corresponding_input_channel=0; + ctx->intermed_ci[3].corresponding_input_channel=1; + break; + case IW_STRAT1_RGB_RGB: + case IW_STRAT1_RGBA_RGB: + ctx->intermed_imgtype = IW_IMGTYPE_RGB; + break; + case IW_STRAT1_G_RGB: + case IW_STRAT1_GA_RGB: + ctx->intermed_imgtype = IW_IMGTYPE_RGB; + ctx->intermed_ci[0].corresponding_input_channel=0; + ctx->intermed_ci[1].corresponding_input_channel=0; + ctx->intermed_ci[2].corresponding_input_channel=0; + break; + case IW_STRAT1_RGBA_GA: + ctx->intermed_imgtype = IW_IMGTYPE_GRAYA; + ctx->intermed_ci[0].cvt_to_grayscale=1; + ctx->intermed_ci[0].corresponding_input_channel=0; + ctx->intermed_ci[1].corresponding_input_channel=3; + break; + case IW_STRAT1_GA_GA: + ctx->intermed_imgtype = IW_IMGTYPE_GRAYA; + break; + case IW_STRAT1_RGB_G: + ctx->intermed_imgtype = IW_IMGTYPE_GRAY; + ctx->intermed_ci[0].cvt_to_grayscale=1; + ctx->intermed_ci[0].corresponding_input_channel=0; + break; + case IW_STRAT1_G_G: + ctx->intermed_imgtype = IW_IMGTYPE_GRAY; + ctx->intermed_ci[0].corresponding_input_channel=0; + break; + default: + iw_set_errorf(ctx,""Internal error, unknown strategy %d"",strategy1); + return 0; + } + + ctx->intermed_numchannels = iw_imgtype_num_channels(ctx->intermed_imgtype); + ctx->intermed_alpha_channel_index = iw_imgtype_alpha_channel_index(ctx->intermed_imgtype); + + for(i=0;iintermed_numchannels;i++) { + ctx->intermed_ci[i].corresponding_output_channel = i; + } + + switch(strategy2) { // intermediate-to-output + case IW_STRAT2_RGBA_RGBA: + ctx->img2.imgtype = IW_IMGTYPE_RGBA; + break; + case IW_STRAT2_RGB_RGB: + ctx->img2.imgtype = IW_IMGTYPE_RGB; + break; + case IW_STRAT2_RGBA_RGB: + ctx->img2.imgtype = IW_IMGTYPE_RGB; + ctx->intermed_ci[3].corresponding_output_channel= -1; + break; + case IW_STRAT2_GA_GA: + ctx->img2.imgtype = IW_IMGTYPE_GRAYA; + break; + case IW_STRAT2_G_G: + ctx->img2.imgtype = IW_IMGTYPE_GRAY; + break; + case IW_STRAT2_GA_G: + ctx->img2.imgtype = IW_IMGTYPE_GRAY; + ctx->intermed_ci[1].corresponding_output_channel= -1; + break; + default: + iw_set_error(ctx,""Internal error""); + return 0; + } + + ctx->img2_numchannels = iw_imgtype_num_channels(ctx->img2.imgtype); + + iw_set_intermed_channeltypes(ctx); + iw_set_out_channeltypes(ctx); + + if(IW_IMGTYPE_HAS_ALPHA(ctx->intermed_imgtype)) { + for(i=0;iintermed_numchannels;i++) { + if(ctx->intermed_ci[i].channeltype!=IW_CHANNELTYPE_ALPHA) + ctx->intermed_ci[i].need_unassoc_alpha_processing = 1; + } + } + + + decide_output_bit_depth(ctx); + + if(ctx->img2.sampletype==IW_SAMPLETYPE_FLOATINGPOINT) { + flag=0; + for(i=0;ireq.color_count[i]) flag=1; + } + if(flag) { + iw_warning(ctx,""Posterization is not supported with floating point output.""); + } + } + else { + output_maxcolorcode_int = (1 << ctx->img2.bit_depth)-1; + + for(i=0;iimg2_numchannels;i++) { + ctx->img2_ci[i].maxcolorcode_int = output_maxcolorcode_int; + } + + if((ctx->output_profile&IW_PROFILE_REDUCEDBITDEPTHS)) { + for(i=0;iimg2_numchannels;i++) { + int mccr; + mccr = ctx->req.output_maxcolorcode[ctx->img2_ci[i].channeltype]; + if(mccr>0) { + if(mccr>output_maxcolorcode_int) mccr=output_maxcolorcode_int; + ctx->img2_ci[i].maxcolorcode_int = mccr; + } + } + } + + for(i=0;iimg2_numchannels;i++) { + if(ctx->img2_ci[i].maxcolorcode_int != output_maxcolorcode_int) { + ctx->reduced_output_maxcolor_flag = 1; + ctx->disable_output_lookup_tables = 1; + } + + ctx->img2_ci[i].maxcolorcode_dbl = (double)ctx->img2_ci[i].maxcolorcode_int; + } + } + + for(i=0;iimg2_numchannels;i++) { + ctx->img2_ci[i].color_count = ctx->req.color_count[ctx->img2_ci[i].channeltype]; + if(ctx->img2_ci[i].color_count) { + iw_restrict_to_range(2,ctx->img2_ci[i].maxcolorcode_int,&ctx->img2_ci[i].color_count); + } + if(ctx->img2_ci[i].color_count==1+ctx->img2_ci[i].maxcolorcode_int) { + ctx->img2_ci[i].color_count = 0; + } + + ctx->img2_ci[i].ditherfamily = ctx->ditherfamily_by_channeltype[ctx->img2_ci[i].channeltype]; + ctx->img2_ci[i].dithersubtype = ctx->dithersubtype_by_channeltype[ctx->img2_ci[i].channeltype]; + } + + for(i=0;iimg2_numchannels;i++) { + if(ctx->img2_ci[i].ditherfamily==IW_DITHERFAMILY_ERRDIFF) { + ctx->uses_errdiffdither=1; + } + } + + if(!ctx->support_reduced_input_bitdepths && ctx->img1.sampletype==IW_SAMPLETYPE_UINT) { + iw_make_x_to_linear_table(ctx,&ctx->input_color_corr_table,&ctx->img1,&ctx->img1cs); + } + + if(ctx->img1_bkgd_label_set) { + for(i=0;i<3;i++) { + ctx->img1_bkgd_label_lin.c[i] = x_to_linear_sample(ctx->img1_bkgd_label_inputcs.c[i],&ctx->img1cs); + } + ctx->img1_bkgd_label_lin.c[3] = ctx->img1_bkgd_label_inputcs.c[3]; + } + + if(ctx->apply_bkgd) { + prepare_apply_bkgd(ctx); + } + + if(ctx->req.output_rendering_intent==IW_INTENT_UNKNOWN) { + ctx->img2.rendering_intent = ctx->img1.rendering_intent; + } + else { + ctx->img2.rendering_intent = ctx->req.output_rendering_intent; + } + + if(ctx->resize_settings[IW_DIMENSION_H].family==IW_RESIZETYPE_AUTO) { + iw_set_auto_resizetype(ctx,ctx->input_w,ctx->img2.width,IW_DIMENSION_H); + } + if(ctx->resize_settings[IW_DIMENSION_V].family==IW_RESIZETYPE_AUTO) { + iw_set_auto_resizetype(ctx,ctx->input_h,ctx->img2.height,IW_DIMENSION_V); + } + + if(IW_IMGTYPE_HAS_ALPHA(ctx->img2.imgtype)) { + if(!ctx->opt_strip_alpha) { + ctx->opt_palette = 0; + ctx->opt_binary_trns = 0; + } + } + + return 1; +} +","@@ -922,8 +922,6 @@ static int iw_process_cols_to_intermediate(struct iw_context *ctx, int channel, + return retval; + } + +-// 'handle_alpha_flag' must be set if an alpha channel exists and this is not +-// the alpha channel. + static int iw_process_rows_intermediate_to_final(struct iw_context *ctx, int intermed_channel, + const struct iw_csdescr *out_csdescr) + { +@@ -951,13 +949,27 @@ static int iw_process_rows_intermediate_to_final(struct iw_context *ctx, int int + iw_tmpsample *out_pix = NULL; + int num_in_pix; + int num_out_pix; ++ struct iw_channelinfo_out default_ci_out; + + num_in_pix = ctx->intermed_canvas_width; + num_out_pix = ctx->img2.width; + + int_ci = &ctx->intermed_ci[intermed_channel]; + output_channel = int_ci->corresponding_output_channel; +- out_ci = &ctx->img2_ci[output_channel]; ++ if(output_channel>=0) { ++ out_ci = &ctx->img2_ci[output_channel]; ++ } ++ else { ++ // If there is no output channelinfo struct, create a temporary one to ++ // use. ++ // TODO: This is admittedly ugly, but we use these settings for a few ++ // things even when there is no corresponding output channel, and I ++ // don't remember exactly why. ++ iw_zeromem(&default_ci_out, sizeof(struct iw_channelinfo_out)); ++ default_ci_out.channeltype = IW_CHANNELTYPE_NONALPHA; ++ out_ci = &default_ci_out; ++ } ++ + is_alpha_channel = (int_ci->channeltype==IW_CHANNELTYPE_ALPHA); + bkgd_has_transparency = iw_bkgd_has_transparency(ctx); + ",3081,3412,4096 +7479,"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; + int save_point = temp_alloc_save(f); + float *buf2 = (float *) temp_alloc(f, n2 * sizeof(*buf2)); + float *u=NULL,*v=NULL; + float *A = f->A[blocktype]; + + + + + + + + { + 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; + } + } + + + u = buffer; + v = buf2; + + { + 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; + } + } + + ld = ilog(n) - 1; // ilog is off-by-one from normal definitions + + + + 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); + + 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; + } + } + + imdct_step3_inner_s_loop_ld654(n >> 5, u, n2-1, A, n); + + + { + uint16 *bitrev = f->bit_reverse[blocktype]; + + 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; + } + } + + + assert(v == buf2); + + { + 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; + } + } + + + + + + { + 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); +} +",0,"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; + int save_point = temp_alloc_save(f); + float *buf2 = (float *) temp_alloc(f, n2 * sizeof(*buf2)); + float *u=NULL,*v=NULL; + float *A = f->A[blocktype]; + + + + + + + + { + 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; + } + } + + + u = buffer; + v = buf2; + + { + 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; + } + } + + ld = ilog(n) - 1; // ilog is off-by-one from normal definitions + + + + 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); + + 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; + } + } + + imdct_step3_inner_s_loop_ld654(n >> 5, u, n2-1, A, n); + + + { + uint16 *bitrev = f->bit_reverse[blocktype]; + + 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; + } + } + + + assert(v == buf2); + + { + 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; + } + } + + + + + + { + 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); +} +","@@ -3,9 +3,9 @@ + // + // Original version written by Sean Barrett in 2007. + // +-// Originally sponsored by RAD Game Tools. Seeking sponsored +-// by Phillip Bennefall, Marc Andersen, Aaron Baker, Elias Software, +-// Aras Pranckevicius, and Sean Barrett. ++// Originally sponsored by RAD Game Tools. Seeking implementation ++// sponsored by Phillip Bennefall, Marc Andersen, Aaron Baker, ++// Elias Software, Aras Pranckevicius, and Sean Barrett. + // + // LICENSE + // +@@ -32,6 +32,7 @@ + // 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 +@@ -2042,14 +2043,19 @@ static int residue_decode(vorb *f, Codebook *book, float *target, int offset, in + 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; +- int n_read = r->end - r->begin; ++ 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 +@@ -4077,7 +4083,10 @@ static int start_decoder(vorb *f) + int i,max_part_read=0; + for (i=0; i < f->residue_count; ++i) { + Residue *r = f->residue_config + i; +- int n_read = r->end - r->begin; ++ 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; +@@ -4088,6 +4097,8 @@ static int start_decoder(vorb *f) + 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; +@@ -5351,6 +5362,8 @@ int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, in + #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;",2402,2733,4096 +4849,"static void dump_vmcs(void) +{ + u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS); + u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS); + u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL); + u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL); + u32 secondary_exec_control = 0; + unsigned long cr4 = vmcs_readl(GUEST_CR4); + u64 efer = vmcs_read64(GUEST_IA32_EFER); + int i, n; + + if (cpu_has_secondary_exec_ctrls()) + secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL); + + pr_err(""*** Guest State ***\n""); + pr_err(""CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n"", + vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW), + vmcs_readl(CR0_GUEST_HOST_MASK)); + pr_err(""CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n"", + cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK)); + pr_err(""CR3 = 0x%016lx\n"", vmcs_readl(GUEST_CR3)); + if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) && + (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA)) + { + pr_err(""PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n"", + vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1)); + pr_err(""PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n"", + vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3)); + } + pr_err(""RSP = 0x%016lx RIP = 0x%016lx\n"", + vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP)); + pr_err(""RFLAGS=0x%08lx DR7 = 0x%016lx\n"", + vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7)); + pr_err(""Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n"", + vmcs_readl(GUEST_SYSENTER_ESP), + vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP)); + vmx_dump_sel(""CS: "", GUEST_CS_SELECTOR); + vmx_dump_sel(""DS: "", GUEST_DS_SELECTOR); + vmx_dump_sel(""SS: "", GUEST_SS_SELECTOR); + vmx_dump_sel(""ES: "", GUEST_ES_SELECTOR); + vmx_dump_sel(""FS: "", GUEST_FS_SELECTOR); + vmx_dump_sel(""GS: "", GUEST_GS_SELECTOR); + vmx_dump_dtsel(""GDTR:"", GUEST_GDTR_LIMIT); + vmx_dump_sel(""LDTR:"", GUEST_LDTR_SELECTOR); + vmx_dump_dtsel(""IDTR:"", GUEST_IDTR_LIMIT); + vmx_dump_sel(""TR: "", GUEST_TR_SELECTOR); + if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) || + (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER))) + pr_err(""EFER = 0x%016llx PAT = 0x%016llx\n"", + efer, vmcs_read64(GUEST_IA32_PAT)); + pr_err(""DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n"", + vmcs_read64(GUEST_IA32_DEBUGCTL), + vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS)); + if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL) + pr_err(""PerfGlobCtl = 0x%016llx\n"", + vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL)); + if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS) + pr_err(""BndCfgS = 0x%016llx\n"", vmcs_read64(GUEST_BNDCFGS)); + pr_err(""Interruptibility = %08x ActivityState = %08x\n"", + vmcs_read32(GUEST_INTERRUPTIBILITY_INFO), + vmcs_read32(GUEST_ACTIVITY_STATE)); + if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) + pr_err(""InterruptStatus = %04x\n"", + vmcs_read16(GUEST_INTR_STATUS)); + + pr_err(""*** Host State ***\n""); + pr_err(""RIP = 0x%016lx RSP = 0x%016lx\n"", + vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP)); + pr_err(""CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n"", + vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR), + vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR), + vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR), + vmcs_read16(HOST_TR_SELECTOR)); + pr_err(""FSBase=%016lx GSBase=%016lx TRBase=%016lx\n"", + vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE), + vmcs_readl(HOST_TR_BASE)); + pr_err(""GDTBase=%016lx IDTBase=%016lx\n"", + vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE)); + pr_err(""CR0=%016lx CR3=%016lx CR4=%016lx\n"", + vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3), + vmcs_readl(HOST_CR4)); + pr_err(""Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n"", + vmcs_readl(HOST_IA32_SYSENTER_ESP), + vmcs_read32(HOST_IA32_SYSENTER_CS), + vmcs_readl(HOST_IA32_SYSENTER_EIP)); + if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER)) + pr_err(""EFER = 0x%016llx PAT = 0x%016llx\n"", + vmcs_read64(HOST_IA32_EFER), + vmcs_read64(HOST_IA32_PAT)); + if (vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL) + pr_err(""PerfGlobCtl = 0x%016llx\n"", + vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL)); + + pr_err(""*** Control State ***\n""); + pr_err(""PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n"", + pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control); + pr_err(""EntryControls=%08x ExitControls=%08x\n"", vmentry_ctl, vmexit_ctl); + pr_err(""ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n"", + vmcs_read32(EXCEPTION_BITMAP), + vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK), + vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH)); + pr_err(""VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n"", + vmcs_read32(VM_ENTRY_INTR_INFO_FIELD), + vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE), + vmcs_read32(VM_ENTRY_INSTRUCTION_LEN)); + pr_err(""VMExit: intr_info=%08x errcode=%08x ilen=%08x\n"", + vmcs_read32(VM_EXIT_INTR_INFO), + vmcs_read32(VM_EXIT_INTR_ERROR_CODE), + vmcs_read32(VM_EXIT_INSTRUCTION_LEN)); + pr_err("" reason=%08x qualification=%016lx\n"", + vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION)); + pr_err(""IDTVectoring: info=%08x errcode=%08x\n"", + vmcs_read32(IDT_VECTORING_INFO_FIELD), + vmcs_read32(IDT_VECTORING_ERROR_CODE)); + pr_err(""TSC Offset = 0x%016llx\n"", vmcs_read64(TSC_OFFSET)); + if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING) + pr_err(""TSC Multiplier = 0x%016llx\n"", + vmcs_read64(TSC_MULTIPLIER)); + if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) + pr_err(""TPR Threshold = 0x%02x\n"", vmcs_read32(TPR_THRESHOLD)); + if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR) + pr_err(""PostedIntrVec = 0x%02x\n"", vmcs_read16(POSTED_INTR_NV)); + if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT)) + pr_err(""EPT pointer = 0x%016llx\n"", vmcs_read64(EPT_POINTER)); + n = vmcs_read32(CR3_TARGET_COUNT); + for (i = 0; i + 1 < n; i += 4) + pr_err(""CR3 target%u=%016lx target%u=%016lx\n"", + i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2), + i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2)); + if (i < n) + pr_err(""CR3 target%u=%016lx\n"", + i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2)); + if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING) + pr_err(""PLE Gap=%08x Window=%08x\n"", + vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW)); + if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID) + pr_err(""Virtual processor ID = 0x%04x\n"", + vmcs_read16(VIRTUAL_PROCESSOR_ID)); +} +",0,"static void dump_vmcs(void) +{ + u32 vmentry_ctl = vmcs_read32(VM_ENTRY_CONTROLS); + u32 vmexit_ctl = vmcs_read32(VM_EXIT_CONTROLS); + u32 cpu_based_exec_ctrl = vmcs_read32(CPU_BASED_VM_EXEC_CONTROL); + u32 pin_based_exec_ctrl = vmcs_read32(PIN_BASED_VM_EXEC_CONTROL); + u32 secondary_exec_control = 0; + unsigned long cr4 = vmcs_readl(GUEST_CR4); + u64 efer = vmcs_read64(GUEST_IA32_EFER); + int i, n; + + if (cpu_has_secondary_exec_ctrls()) + secondary_exec_control = vmcs_read32(SECONDARY_VM_EXEC_CONTROL); + + pr_err(""*** Guest State ***\n""); + pr_err(""CR0: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n"", + vmcs_readl(GUEST_CR0), vmcs_readl(CR0_READ_SHADOW), + vmcs_readl(CR0_GUEST_HOST_MASK)); + pr_err(""CR4: actual=0x%016lx, shadow=0x%016lx, gh_mask=%016lx\n"", + cr4, vmcs_readl(CR4_READ_SHADOW), vmcs_readl(CR4_GUEST_HOST_MASK)); + pr_err(""CR3 = 0x%016lx\n"", vmcs_readl(GUEST_CR3)); + if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT) && + (cr4 & X86_CR4_PAE) && !(efer & EFER_LMA)) + { + pr_err(""PDPTR0 = 0x%016llx PDPTR1 = 0x%016llx\n"", + vmcs_read64(GUEST_PDPTR0), vmcs_read64(GUEST_PDPTR1)); + pr_err(""PDPTR2 = 0x%016llx PDPTR3 = 0x%016llx\n"", + vmcs_read64(GUEST_PDPTR2), vmcs_read64(GUEST_PDPTR3)); + } + pr_err(""RSP = 0x%016lx RIP = 0x%016lx\n"", + vmcs_readl(GUEST_RSP), vmcs_readl(GUEST_RIP)); + pr_err(""RFLAGS=0x%08lx DR7 = 0x%016lx\n"", + vmcs_readl(GUEST_RFLAGS), vmcs_readl(GUEST_DR7)); + pr_err(""Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n"", + vmcs_readl(GUEST_SYSENTER_ESP), + vmcs_read32(GUEST_SYSENTER_CS), vmcs_readl(GUEST_SYSENTER_EIP)); + vmx_dump_sel(""CS: "", GUEST_CS_SELECTOR); + vmx_dump_sel(""DS: "", GUEST_DS_SELECTOR); + vmx_dump_sel(""SS: "", GUEST_SS_SELECTOR); + vmx_dump_sel(""ES: "", GUEST_ES_SELECTOR); + vmx_dump_sel(""FS: "", GUEST_FS_SELECTOR); + vmx_dump_sel(""GS: "", GUEST_GS_SELECTOR); + vmx_dump_dtsel(""GDTR:"", GUEST_GDTR_LIMIT); + vmx_dump_sel(""LDTR:"", GUEST_LDTR_SELECTOR); + vmx_dump_dtsel(""IDTR:"", GUEST_IDTR_LIMIT); + vmx_dump_sel(""TR: "", GUEST_TR_SELECTOR); + if ((vmexit_ctl & (VM_EXIT_SAVE_IA32_PAT | VM_EXIT_SAVE_IA32_EFER)) || + (vmentry_ctl & (VM_ENTRY_LOAD_IA32_PAT | VM_ENTRY_LOAD_IA32_EFER))) + pr_err(""EFER = 0x%016llx PAT = 0x%016llx\n"", + efer, vmcs_read64(GUEST_IA32_PAT)); + pr_err(""DebugCtl = 0x%016llx DebugExceptions = 0x%016lx\n"", + vmcs_read64(GUEST_IA32_DEBUGCTL), + vmcs_readl(GUEST_PENDING_DBG_EXCEPTIONS)); + if (vmentry_ctl & VM_ENTRY_LOAD_IA32_PERF_GLOBAL_CTRL) + pr_err(""PerfGlobCtl = 0x%016llx\n"", + vmcs_read64(GUEST_IA32_PERF_GLOBAL_CTRL)); + if (vmentry_ctl & VM_ENTRY_LOAD_BNDCFGS) + pr_err(""BndCfgS = 0x%016llx\n"", vmcs_read64(GUEST_BNDCFGS)); + pr_err(""Interruptibility = %08x ActivityState = %08x\n"", + vmcs_read32(GUEST_INTERRUPTIBILITY_INFO), + vmcs_read32(GUEST_ACTIVITY_STATE)); + if (secondary_exec_control & SECONDARY_EXEC_VIRTUAL_INTR_DELIVERY) + pr_err(""InterruptStatus = %04x\n"", + vmcs_read16(GUEST_INTR_STATUS)); + + pr_err(""*** Host State ***\n""); + pr_err(""RIP = 0x%016lx RSP = 0x%016lx\n"", + vmcs_readl(HOST_RIP), vmcs_readl(HOST_RSP)); + pr_err(""CS=%04x SS=%04x DS=%04x ES=%04x FS=%04x GS=%04x TR=%04x\n"", + vmcs_read16(HOST_CS_SELECTOR), vmcs_read16(HOST_SS_SELECTOR), + vmcs_read16(HOST_DS_SELECTOR), vmcs_read16(HOST_ES_SELECTOR), + vmcs_read16(HOST_FS_SELECTOR), vmcs_read16(HOST_GS_SELECTOR), + vmcs_read16(HOST_TR_SELECTOR)); + pr_err(""FSBase=%016lx GSBase=%016lx TRBase=%016lx\n"", + vmcs_readl(HOST_FS_BASE), vmcs_readl(HOST_GS_BASE), + vmcs_readl(HOST_TR_BASE)); + pr_err(""GDTBase=%016lx IDTBase=%016lx\n"", + vmcs_readl(HOST_GDTR_BASE), vmcs_readl(HOST_IDTR_BASE)); + pr_err(""CR0=%016lx CR3=%016lx CR4=%016lx\n"", + vmcs_readl(HOST_CR0), vmcs_readl(HOST_CR3), + vmcs_readl(HOST_CR4)); + pr_err(""Sysenter RSP=%016lx CS:RIP=%04x:%016lx\n"", + vmcs_readl(HOST_IA32_SYSENTER_ESP), + vmcs_read32(HOST_IA32_SYSENTER_CS), + vmcs_readl(HOST_IA32_SYSENTER_EIP)); + if (vmexit_ctl & (VM_EXIT_LOAD_IA32_PAT | VM_EXIT_LOAD_IA32_EFER)) + pr_err(""EFER = 0x%016llx PAT = 0x%016llx\n"", + vmcs_read64(HOST_IA32_EFER), + vmcs_read64(HOST_IA32_PAT)); + if (vmexit_ctl & VM_EXIT_LOAD_IA32_PERF_GLOBAL_CTRL) + pr_err(""PerfGlobCtl = 0x%016llx\n"", + vmcs_read64(HOST_IA32_PERF_GLOBAL_CTRL)); + + pr_err(""*** Control State ***\n""); + pr_err(""PinBased=%08x CPUBased=%08x SecondaryExec=%08x\n"", + pin_based_exec_ctrl, cpu_based_exec_ctrl, secondary_exec_control); + pr_err(""EntryControls=%08x ExitControls=%08x\n"", vmentry_ctl, vmexit_ctl); + pr_err(""ExceptionBitmap=%08x PFECmask=%08x PFECmatch=%08x\n"", + vmcs_read32(EXCEPTION_BITMAP), + vmcs_read32(PAGE_FAULT_ERROR_CODE_MASK), + vmcs_read32(PAGE_FAULT_ERROR_CODE_MATCH)); + pr_err(""VMEntry: intr_info=%08x errcode=%08x ilen=%08x\n"", + vmcs_read32(VM_ENTRY_INTR_INFO_FIELD), + vmcs_read32(VM_ENTRY_EXCEPTION_ERROR_CODE), + vmcs_read32(VM_ENTRY_INSTRUCTION_LEN)); + pr_err(""VMExit: intr_info=%08x errcode=%08x ilen=%08x\n"", + vmcs_read32(VM_EXIT_INTR_INFO), + vmcs_read32(VM_EXIT_INTR_ERROR_CODE), + vmcs_read32(VM_EXIT_INSTRUCTION_LEN)); + pr_err("" reason=%08x qualification=%016lx\n"", + vmcs_read32(VM_EXIT_REASON), vmcs_readl(EXIT_QUALIFICATION)); + pr_err(""IDTVectoring: info=%08x errcode=%08x\n"", + vmcs_read32(IDT_VECTORING_INFO_FIELD), + vmcs_read32(IDT_VECTORING_ERROR_CODE)); + pr_err(""TSC Offset = 0x%016llx\n"", vmcs_read64(TSC_OFFSET)); + if (secondary_exec_control & SECONDARY_EXEC_TSC_SCALING) + pr_err(""TSC Multiplier = 0x%016llx\n"", + vmcs_read64(TSC_MULTIPLIER)); + if (cpu_based_exec_ctrl & CPU_BASED_TPR_SHADOW) + pr_err(""TPR Threshold = 0x%02x\n"", vmcs_read32(TPR_THRESHOLD)); + if (pin_based_exec_ctrl & PIN_BASED_POSTED_INTR) + pr_err(""PostedIntrVec = 0x%02x\n"", vmcs_read16(POSTED_INTR_NV)); + if ((secondary_exec_control & SECONDARY_EXEC_ENABLE_EPT)) + pr_err(""EPT pointer = 0x%016llx\n"", vmcs_read64(EPT_POINTER)); + n = vmcs_read32(CR3_TARGET_COUNT); + for (i = 0; i + 1 < n; i += 4) + pr_err(""CR3 target%u=%016lx target%u=%016lx\n"", + i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2), + i + 1, vmcs_readl(CR3_TARGET_VALUE0 + i * 2 + 2)); + if (i < n) + pr_err(""CR3 target%u=%016lx\n"", + i, vmcs_readl(CR3_TARGET_VALUE0 + i * 2)); + if (secondary_exec_control & SECONDARY_EXEC_PAUSE_LOOP_EXITING) + pr_err(""PLE Gap=%08x Window=%08x\n"", + vmcs_read32(PLE_GAP), vmcs_read32(PLE_WINDOW)); + if (secondary_exec_control & SECONDARY_EXEC_ENABLE_VPID) + pr_err(""Virtual processor ID = 0x%04x\n"", + vmcs_read16(VIRTUAL_PROCESSOR_ID)); +} +","@@ -1389,10 +1389,10 @@ static inline bool nested_cpu_has_posted_intr(struct vmcs12 *vmcs12) + return vmcs12->pin_based_vm_exec_control & PIN_BASED_POSTED_INTR; + } + +-static inline bool is_exception(u32 intr_info) ++static inline bool is_nmi(u32 intr_info) + { + return (intr_info & (INTR_INFO_INTR_TYPE_MASK | INTR_INFO_VALID_MASK)) +- == (INTR_TYPE_HARD_EXCEPTION | INTR_INFO_VALID_MASK); ++ == (INTR_TYPE_NMI_INTR | INTR_INFO_VALID_MASK); + } + + static void nested_vmx_vmexit(struct kvm_vcpu *vcpu, u32 exit_reason, +@@ -5728,7 +5728,7 @@ static int handle_exception(struct kvm_vcpu *vcpu) + if (is_machine_check(intr_info)) + return handle_machine_check(vcpu); + +- if ((intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR) ++ if (is_nmi(intr_info)) + return 1; /* already handled by vmx_vcpu_run() */ + + if (is_no_device(intr_info)) { +@@ -8170,7 +8170,7 @@ static bool nested_vmx_exit_handled(struct kvm_vcpu *vcpu) + + switch (exit_reason) { + case EXIT_REASON_EXCEPTION_NMI: +- if (!is_exception(intr_info)) ++ if (is_nmi(intr_info)) + return false; + else if (is_page_fault(intr_info)) + return enable_ept; +@@ -8765,8 +8765,7 @@ static void vmx_complete_atomic_exit(struct vcpu_vmx *vmx) + kvm_machine_check(); + + /* We need to handle NMIs before interrupts are enabled */ +- if ((exit_intr_info & INTR_INFO_INTR_TYPE_MASK) == INTR_TYPE_NMI_INTR && +- (exit_intr_info & INTR_INFO_VALID_MASK)) { ++ if (is_nmi(exit_intr_info)) { + kvm_before_handle_nmi(&vmx->vcpu); + asm(""int $2""); + kvm_after_handle_nmi(&vmx->vcpu);",2427,2758,4096 +9063,"static int hls_coding_unit(HEVCContext *s, int x0, int y0, int log2_cb_size) +{ + int cb_size = 1 << log2_cb_size; + HEVCLocalContext *lc = s->HEVClc; + int log2_min_cb_size = s->ps.sps->log2_min_cb_size; + int length = cb_size >> log2_min_cb_size; + int min_cb_width = s->ps.sps->min_cb_width; + int x_cb = x0 >> log2_min_cb_size; + int y_cb = y0 >> log2_min_cb_size; + int idx = log2_cb_size - 2; + int qp_block_mask = (1<<(s->ps.sps->log2_ctb_size - s->ps.pps->diff_cu_qp_delta_depth)) - 1; + int x, y, ret; + + lc->cu.x = x0; + lc->cu.y = y0; + lc->cu.pred_mode = MODE_INTRA; + lc->cu.part_mode = PART_2Nx2N; + lc->cu.intra_split_flag = 0; + + SAMPLE_CTB(s->skip_flag, x_cb, y_cb) = 0; + for (x = 0; x < 4; x++) + lc->pu.intra_pred_mode[x] = 1; + if (s->ps.pps->transquant_bypass_enable_flag) { + lc->cu.cu_transquant_bypass_flag = ff_hevc_cu_transquant_bypass_flag_decode(s); + if (lc->cu.cu_transquant_bypass_flag) + set_deblocking_bypass(s, x0, y0, log2_cb_size); + } else + lc->cu.cu_transquant_bypass_flag = 0; + + if (s->sh.slice_type != HEVC_SLICE_I) { + uint8_t skip_flag = ff_hevc_skip_flag_decode(s, x0, y0, x_cb, y_cb); + + x = y_cb * min_cb_width + x_cb; + for (y = 0; y < length; y++) { + memset(&s->skip_flag[x], skip_flag, length); + x += min_cb_width; + } + lc->cu.pred_mode = skip_flag ? MODE_SKIP : MODE_INTER; + } else { + x = y_cb * min_cb_width + x_cb; + for (y = 0; y < length; y++) { + memset(&s->skip_flag[x], 0, length); + x += min_cb_width; + } + } + + if (SAMPLE_CTB(s->skip_flag, x_cb, y_cb)) { + hls_prediction_unit(s, x0, y0, cb_size, cb_size, log2_cb_size, 0, idx); + intra_prediction_unit_default_value(s, x0, y0, log2_cb_size); + + if (!s->sh.disable_deblocking_filter_flag) + ff_hevc_deblocking_boundary_strengths(s, x0, y0, log2_cb_size); + } else { + int pcm_flag = 0; + + if (s->sh.slice_type != HEVC_SLICE_I) + lc->cu.pred_mode = ff_hevc_pred_mode_decode(s); + if (lc->cu.pred_mode != MODE_INTRA || + log2_cb_size == s->ps.sps->log2_min_cb_size) { + lc->cu.part_mode = ff_hevc_part_mode_decode(s, log2_cb_size); + lc->cu.intra_split_flag = lc->cu.part_mode == PART_NxN && + lc->cu.pred_mode == MODE_INTRA; + } + + if (lc->cu.pred_mode == MODE_INTRA) { + if (lc->cu.part_mode == PART_2Nx2N && s->ps.sps->pcm_enabled_flag && + log2_cb_size >= s->ps.sps->pcm.log2_min_pcm_cb_size && + log2_cb_size <= s->ps.sps->pcm.log2_max_pcm_cb_size) { + pcm_flag = ff_hevc_pcm_flag_decode(s); + } + if (pcm_flag) { + intra_prediction_unit_default_value(s, x0, y0, log2_cb_size); + ret = hls_pcm_sample(s, x0, y0, log2_cb_size); + if (s->ps.sps->pcm.loop_filter_disable_flag) + set_deblocking_bypass(s, x0, y0, log2_cb_size); + + if (ret < 0) + return ret; + } else { + intra_prediction_unit(s, x0, y0, log2_cb_size); + } + } else { + intra_prediction_unit_default_value(s, x0, y0, log2_cb_size); + switch (lc->cu.part_mode) { + case PART_2Nx2N: + hls_prediction_unit(s, x0, y0, cb_size, cb_size, log2_cb_size, 0, idx); + break; + case PART_2NxN: + hls_prediction_unit(s, x0, y0, cb_size, cb_size / 2, log2_cb_size, 0, idx); + hls_prediction_unit(s, x0, y0 + cb_size / 2, cb_size, cb_size / 2, log2_cb_size, 1, idx); + break; + case PART_Nx2N: + hls_prediction_unit(s, x0, y0, cb_size / 2, cb_size, log2_cb_size, 0, idx - 1); + hls_prediction_unit(s, x0 + cb_size / 2, y0, cb_size / 2, cb_size, log2_cb_size, 1, idx - 1); + break; + case PART_2NxnU: + hls_prediction_unit(s, x0, y0, cb_size, cb_size / 4, log2_cb_size, 0, idx); + hls_prediction_unit(s, x0, y0 + cb_size / 4, cb_size, cb_size * 3 / 4, log2_cb_size, 1, idx); + break; + case PART_2NxnD: + hls_prediction_unit(s, x0, y0, cb_size, cb_size * 3 / 4, log2_cb_size, 0, idx); + hls_prediction_unit(s, x0, y0 + cb_size * 3 / 4, cb_size, cb_size / 4, log2_cb_size, 1, idx); + break; + case PART_nLx2N: + hls_prediction_unit(s, x0, y0, cb_size / 4, cb_size, log2_cb_size, 0, idx - 2); + hls_prediction_unit(s, x0 + cb_size / 4, y0, cb_size * 3 / 4, cb_size, log2_cb_size, 1, idx - 2); + break; + case PART_nRx2N: + hls_prediction_unit(s, x0, y0, cb_size * 3 / 4, cb_size, log2_cb_size, 0, idx - 2); + hls_prediction_unit(s, x0 + cb_size * 3 / 4, y0, cb_size / 4, cb_size, log2_cb_size, 1, idx - 2); + break; + case PART_NxN: + hls_prediction_unit(s, x0, y0, cb_size / 2, cb_size / 2, log2_cb_size, 0, idx - 1); + hls_prediction_unit(s, x0 + cb_size / 2, y0, cb_size / 2, cb_size / 2, log2_cb_size, 1, idx - 1); + hls_prediction_unit(s, x0, y0 + cb_size / 2, cb_size / 2, cb_size / 2, log2_cb_size, 2, idx - 1); + hls_prediction_unit(s, x0 + cb_size / 2, y0 + cb_size / 2, cb_size / 2, cb_size / 2, log2_cb_size, 3, idx - 1); + break; + } + } + + if (!pcm_flag) { + int rqt_root_cbf = 1; + + if (lc->cu.pred_mode != MODE_INTRA && + !(lc->cu.part_mode == PART_2Nx2N && lc->pu.merge_flag)) { + rqt_root_cbf = ff_hevc_no_residual_syntax_flag_decode(s); + } + if (rqt_root_cbf) { + const static int cbf[2] = { 0 }; + lc->cu.max_trafo_depth = lc->cu.pred_mode == MODE_INTRA ? + s->ps.sps->max_transform_hierarchy_depth_intra + lc->cu.intra_split_flag : + s->ps.sps->max_transform_hierarchy_depth_inter; + ret = hls_transform_tree(s, x0, y0, x0, y0, x0, y0, + log2_cb_size, + log2_cb_size, 0, 0, cbf, cbf); + if (ret < 0) + return ret; + } else { + if (!s->sh.disable_deblocking_filter_flag) + ff_hevc_deblocking_boundary_strengths(s, x0, y0, log2_cb_size); + } + } + } + + if (s->ps.pps->cu_qp_delta_enabled_flag && lc->tu.is_cu_qp_delta_coded == 0) + ff_hevc_set_qPy(s, x0, y0, log2_cb_size); + + x = y_cb * min_cb_width + x_cb; + for (y = 0; y < length; y++) { + memset(&s->qp_y_tab[x], lc->qp_y, length); + x += min_cb_width; + } + + if(((x0 + (1<qPy_pred = lc->qp_y; + } + + set_ct_depth(s, x0, y0, log2_cb_size, lc->ct_depth); + + return 0; +} +",0,"static int hls_coding_unit(HEVCContext *s, int x0, int y0, int log2_cb_size) +{ + int cb_size = 1 << log2_cb_size; + HEVCLocalContext *lc = s->HEVClc; + int log2_min_cb_size = s->ps.sps->log2_min_cb_size; + int length = cb_size >> log2_min_cb_size; + int min_cb_width = s->ps.sps->min_cb_width; + int x_cb = x0 >> log2_min_cb_size; + int y_cb = y0 >> log2_min_cb_size; + int idx = log2_cb_size - 2; + int qp_block_mask = (1<<(s->ps.sps->log2_ctb_size - s->ps.pps->diff_cu_qp_delta_depth)) - 1; + int x, y, ret; + + lc->cu.x = x0; + lc->cu.y = y0; + lc->cu.pred_mode = MODE_INTRA; + lc->cu.part_mode = PART_2Nx2N; + lc->cu.intra_split_flag = 0; + + SAMPLE_CTB(s->skip_flag, x_cb, y_cb) = 0; + for (x = 0; x < 4; x++) + lc->pu.intra_pred_mode[x] = 1; + if (s->ps.pps->transquant_bypass_enable_flag) { + lc->cu.cu_transquant_bypass_flag = ff_hevc_cu_transquant_bypass_flag_decode(s); + if (lc->cu.cu_transquant_bypass_flag) + set_deblocking_bypass(s, x0, y0, log2_cb_size); + } else + lc->cu.cu_transquant_bypass_flag = 0; + + if (s->sh.slice_type != HEVC_SLICE_I) { + uint8_t skip_flag = ff_hevc_skip_flag_decode(s, x0, y0, x_cb, y_cb); + + x = y_cb * min_cb_width + x_cb; + for (y = 0; y < length; y++) { + memset(&s->skip_flag[x], skip_flag, length); + x += min_cb_width; + } + lc->cu.pred_mode = skip_flag ? MODE_SKIP : MODE_INTER; + } else { + x = y_cb * min_cb_width + x_cb; + for (y = 0; y < length; y++) { + memset(&s->skip_flag[x], 0, length); + x += min_cb_width; + } + } + + if (SAMPLE_CTB(s->skip_flag, x_cb, y_cb)) { + hls_prediction_unit(s, x0, y0, cb_size, cb_size, log2_cb_size, 0, idx); + intra_prediction_unit_default_value(s, x0, y0, log2_cb_size); + + if (!s->sh.disable_deblocking_filter_flag) + ff_hevc_deblocking_boundary_strengths(s, x0, y0, log2_cb_size); + } else { + int pcm_flag = 0; + + if (s->sh.slice_type != HEVC_SLICE_I) + lc->cu.pred_mode = ff_hevc_pred_mode_decode(s); + if (lc->cu.pred_mode != MODE_INTRA || + log2_cb_size == s->ps.sps->log2_min_cb_size) { + lc->cu.part_mode = ff_hevc_part_mode_decode(s, log2_cb_size); + lc->cu.intra_split_flag = lc->cu.part_mode == PART_NxN && + lc->cu.pred_mode == MODE_INTRA; + } + + if (lc->cu.pred_mode == MODE_INTRA) { + if (lc->cu.part_mode == PART_2Nx2N && s->ps.sps->pcm_enabled_flag && + log2_cb_size >= s->ps.sps->pcm.log2_min_pcm_cb_size && + log2_cb_size <= s->ps.sps->pcm.log2_max_pcm_cb_size) { + pcm_flag = ff_hevc_pcm_flag_decode(s); + } + if (pcm_flag) { + intra_prediction_unit_default_value(s, x0, y0, log2_cb_size); + ret = hls_pcm_sample(s, x0, y0, log2_cb_size); + if (s->ps.sps->pcm.loop_filter_disable_flag) + set_deblocking_bypass(s, x0, y0, log2_cb_size); + + if (ret < 0) + return ret; + } else { + intra_prediction_unit(s, x0, y0, log2_cb_size); + } + } else { + intra_prediction_unit_default_value(s, x0, y0, log2_cb_size); + switch (lc->cu.part_mode) { + case PART_2Nx2N: + hls_prediction_unit(s, x0, y0, cb_size, cb_size, log2_cb_size, 0, idx); + break; + case PART_2NxN: + hls_prediction_unit(s, x0, y0, cb_size, cb_size / 2, log2_cb_size, 0, idx); + hls_prediction_unit(s, x0, y0 + cb_size / 2, cb_size, cb_size / 2, log2_cb_size, 1, idx); + break; + case PART_Nx2N: + hls_prediction_unit(s, x0, y0, cb_size / 2, cb_size, log2_cb_size, 0, idx - 1); + hls_prediction_unit(s, x0 + cb_size / 2, y0, cb_size / 2, cb_size, log2_cb_size, 1, idx - 1); + break; + case PART_2NxnU: + hls_prediction_unit(s, x0, y0, cb_size, cb_size / 4, log2_cb_size, 0, idx); + hls_prediction_unit(s, x0, y0 + cb_size / 4, cb_size, cb_size * 3 / 4, log2_cb_size, 1, idx); + break; + case PART_2NxnD: + hls_prediction_unit(s, x0, y0, cb_size, cb_size * 3 / 4, log2_cb_size, 0, idx); + hls_prediction_unit(s, x0, y0 + cb_size * 3 / 4, cb_size, cb_size / 4, log2_cb_size, 1, idx); + break; + case PART_nLx2N: + hls_prediction_unit(s, x0, y0, cb_size / 4, cb_size, log2_cb_size, 0, idx - 2); + hls_prediction_unit(s, x0 + cb_size / 4, y0, cb_size * 3 / 4, cb_size, log2_cb_size, 1, idx - 2); + break; + case PART_nRx2N: + hls_prediction_unit(s, x0, y0, cb_size * 3 / 4, cb_size, log2_cb_size, 0, idx - 2); + hls_prediction_unit(s, x0 + cb_size * 3 / 4, y0, cb_size / 4, cb_size, log2_cb_size, 1, idx - 2); + break; + case PART_NxN: + hls_prediction_unit(s, x0, y0, cb_size / 2, cb_size / 2, log2_cb_size, 0, idx - 1); + hls_prediction_unit(s, x0 + cb_size / 2, y0, cb_size / 2, cb_size / 2, log2_cb_size, 1, idx - 1); + hls_prediction_unit(s, x0, y0 + cb_size / 2, cb_size / 2, cb_size / 2, log2_cb_size, 2, idx - 1); + hls_prediction_unit(s, x0 + cb_size / 2, y0 + cb_size / 2, cb_size / 2, cb_size / 2, log2_cb_size, 3, idx - 1); + break; + } + } + + if (!pcm_flag) { + int rqt_root_cbf = 1; + + if (lc->cu.pred_mode != MODE_INTRA && + !(lc->cu.part_mode == PART_2Nx2N && lc->pu.merge_flag)) { + rqt_root_cbf = ff_hevc_no_residual_syntax_flag_decode(s); + } + if (rqt_root_cbf) { + const static int cbf[2] = { 0 }; + lc->cu.max_trafo_depth = lc->cu.pred_mode == MODE_INTRA ? + s->ps.sps->max_transform_hierarchy_depth_intra + lc->cu.intra_split_flag : + s->ps.sps->max_transform_hierarchy_depth_inter; + ret = hls_transform_tree(s, x0, y0, x0, y0, x0, y0, + log2_cb_size, + log2_cb_size, 0, 0, cbf, cbf); + if (ret < 0) + return ret; + } else { + if (!s->sh.disable_deblocking_filter_flag) + ff_hevc_deblocking_boundary_strengths(s, x0, y0, log2_cb_size); + } + } + } + + if (s->ps.pps->cu_qp_delta_enabled_flag && lc->tu.is_cu_qp_delta_coded == 0) + ff_hevc_set_qPy(s, x0, y0, log2_cb_size); + + x = y_cb * min_cb_width + x_cb; + for (y = 0; y < length; y++) { + memset(&s->qp_y_tab[x], lc->qp_y, length); + x += min_cb_width; + } + + if(((x0 + (1<qPy_pred = lc->qp_y; + } + + set_ct_depth(s, x0, y0, log2_cb_size, lc->ct_depth); + + return 0; +} +","@@ -488,6 +488,11 @@ static int hls_slice_header(HEVCContext *s) + + // Coded parameters + sh->first_slice_in_pic_flag = get_bits1(gb); ++ if (s->ref && sh->first_slice_in_pic_flag) { ++ av_log(s->avctx, AV_LOG_ERROR, ""Two slices reporting being the first in the same frame.\n""); ++ return 1; // This slice will be skiped later, do not corrupt state ++ } ++ + if ((IS_IDR(s) || IS_BLA(s)) && sh->first_slice_in_pic_flag) { + s->seq_decode = (s->seq_decode + 1) & 0xff; + s->max_ra = INT_MAX; +@@ -2918,6 +2923,11 @@ static int decode_nal_unit(HEVCContext *s, const H2645NAL *nal) + ret = hls_slice_header(s); + if (ret < 0) + return ret; ++ if (ret == 1) { ++ ret = AVERROR_INVALIDDATA; ++ goto fail; ++ } ++ + + if ( + (s->avctx->skip_frame >= AVDISCARD_BIDIR && s->sh.slice_type == HEVC_SLICE_B) || +@@ -2927,10 +2937,6 @@ static int decode_nal_unit(HEVCContext *s, const H2645NAL *nal) + } + + if (s->sh.first_slice_in_pic_flag) { +- if (s->ref) { +- av_log(s->avctx, AV_LOG_ERROR, ""Two slices reporting being the first in the same frame.\n""); +- goto fail; +- } + if (s->max_ra == INT_MAX) { + if (s->nal_unit_type == HEVC_NAL_CRA_NUT || IS_BLA(s)) { + s->max_ra = s->poc;",2255,2586,4096 +18074," static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, + struct bpf_insn *insn, + struct bpf_reg_state *dst_reg, + struct bpf_reg_state src_reg) +{ + struct bpf_reg_state *regs = cur_regs(env); + u8 opcode = BPF_OP(insn->code); + bool src_known, dst_known; + s64 smin_val, smax_val; + u64 umin_val, umax_val; + + if (BPF_CLASS(insn->code) != BPF_ALU64) { + /* 32-bit ALU ops are (32,32)->64 */ + coerce_reg_to_size(dst_reg, 4); + coerce_reg_to_size(&src_reg, 4); + } + smin_val = src_reg.smin_value; + smax_val = src_reg.smax_value; + umin_val = src_reg.umin_value; + umax_val = src_reg.umax_value; + src_known = tnum_is_const(src_reg.var_off); + dst_known = tnum_is_const(dst_reg->var_off); + + switch (opcode) { + case BPF_ADD: + if (signed_add_overflows(dst_reg->smin_value, smin_val) || + signed_add_overflows(dst_reg->smax_value, smax_val)) { + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + } else { + dst_reg->smin_value += smin_val; + dst_reg->smax_value += smax_val; + } + if (dst_reg->umin_value + umin_val < umin_val || + dst_reg->umax_value + umax_val < umax_val) { + dst_reg->umin_value = 0; + dst_reg->umax_value = U64_MAX; + } else { + dst_reg->umin_value += umin_val; + dst_reg->umax_value += umax_val; + } + dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); + break; + case BPF_SUB: + if (signed_sub_overflows(dst_reg->smin_value, smax_val) || + signed_sub_overflows(dst_reg->smax_value, smin_val)) { + /* Overflow possible, we know nothing */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + } else { + dst_reg->smin_value -= smax_val; + dst_reg->smax_value -= smin_val; + } + if (dst_reg->umin_value < umax_val) { + /* Overflow possible, we know nothing */ + dst_reg->umin_value = 0; + dst_reg->umax_value = U64_MAX; + } else { + /* Cannot overflow (as long as bounds are consistent) */ + dst_reg->umin_value -= umax_val; + dst_reg->umax_value -= umin_val; + } + dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); + break; + case BPF_MUL: + dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); + if (smin_val < 0 || dst_reg->smin_value < 0) { + /* Ain't nobody got time to multiply that sign */ + __mark_reg_unbounded(dst_reg); + __update_reg_bounds(dst_reg); + break; + } + /* Both values are positive, so we can work with unsigned and + * copy the result to signed (unless it exceeds S64_MAX). + */ + if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { + /* Potential overflow, we know nothing */ + __mark_reg_unbounded(dst_reg); + /* (except what we can learn from the var_off) */ + __update_reg_bounds(dst_reg); + break; + } + dst_reg->umin_value *= umin_val; + dst_reg->umax_value *= umax_val; + if (dst_reg->umax_value > S64_MAX) { + /* Overflow possible, we know nothing */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + } else { + dst_reg->smin_value = dst_reg->umin_value; + dst_reg->smax_value = dst_reg->umax_value; + } + break; + case BPF_AND: + if (src_known && dst_known) { + __mark_reg_known(dst_reg, dst_reg->var_off.value & + src_reg.var_off.value); + break; + } + /* We get our minimum from the var_off, since that's inherently + * bitwise. Our maximum is the minimum of the operands' maxima. + */ + dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); + dst_reg->umin_value = dst_reg->var_off.value; + dst_reg->umax_value = min(dst_reg->umax_value, umax_val); + if (dst_reg->smin_value < 0 || smin_val < 0) { + /* Lose signed bounds when ANDing negative numbers, + * ain't nobody got time for that. + */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + } else { + /* ANDing two positives gives a positive, so safe to + * cast result into s64. + */ + dst_reg->smin_value = dst_reg->umin_value; + dst_reg->smax_value = dst_reg->umax_value; + } + /* We may learn something more from the var_off */ + __update_reg_bounds(dst_reg); + break; + case BPF_OR: + if (src_known && dst_known) { + __mark_reg_known(dst_reg, dst_reg->var_off.value | + src_reg.var_off.value); + break; + } + /* We get our maximum from the var_off, and our minimum is the + * maximum of the operands' minima + */ + dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); + dst_reg->umin_value = max(dst_reg->umin_value, umin_val); + dst_reg->umax_value = dst_reg->var_off.value | + dst_reg->var_off.mask; + if (dst_reg->smin_value < 0 || smin_val < 0) { + /* Lose signed bounds when ORing negative numbers, + * ain't nobody got time for that. + */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + } else { + /* ORing two positives gives a positive, so safe to + * cast result into s64. + */ + dst_reg->smin_value = dst_reg->umin_value; + dst_reg->smax_value = dst_reg->umax_value; + } + /* We may learn something more from the var_off */ + __update_reg_bounds(dst_reg); + break; + case BPF_LSH: + if (umax_val > 63) { + /* Shifts greater than 63 are undefined. This includes + * shifts by a negative number. + */ + mark_reg_unknown(env, regs, insn->dst_reg); + break; + } + /* We lose all sign bit information (except what we can pick + * up from var_off) + */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + /* If we might shift our top bit out, then we know nothing */ + if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { + dst_reg->umin_value = 0; + dst_reg->umax_value = U64_MAX; + } else { + dst_reg->umin_value <<= umin_val; + dst_reg->umax_value <<= umax_val; + } + if (src_known) + dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); + else + dst_reg->var_off = tnum_lshift(tnum_unknown, umin_val); + /* We may learn something more from the var_off */ + __update_reg_bounds(dst_reg); + break; + case BPF_RSH: + if (umax_val > 63) { + /* Shifts greater than 63 are undefined. This includes + * shifts by a negative number. + */ + mark_reg_unknown(env, regs, insn->dst_reg); + break; + } + /* BPF_RSH is an unsigned shift. If the value in dst_reg might + * be negative, then either: + * 1) src_reg might be zero, so the sign bit of the result is + * unknown, so we lose our signed bounds + * 2) it's known negative, thus the unsigned bounds capture the + * signed bounds + * 3) the signed bounds cross zero, so they tell us nothing + * about the result + * If the value in dst_reg is known nonnegative, then again the + * unsigned bounts capture the signed bounds. + * Thus, in all cases it suffices to blow away our signed bounds + * and rely on inferring new ones from the unsigned bounds and + * var_off of the result. + */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + if (src_known) + dst_reg->var_off = tnum_rshift(dst_reg->var_off, + umin_val); + else + dst_reg->var_off = tnum_rshift(tnum_unknown, umin_val); + dst_reg->umin_value >>= umax_val; + dst_reg->umax_value >>= umin_val; + /* We may learn something more from the var_off */ + __update_reg_bounds(dst_reg); + break; + default: + mark_reg_unknown(env, regs, insn->dst_reg); + break; + } + + __reg_deduce_bounds(dst_reg); + __reg_bound_offset(dst_reg); + return 0; +} +",1," static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, + struct bpf_insn *insn, + struct bpf_reg_state *dst_reg, + struct bpf_reg_state src_reg) +{ + struct bpf_reg_state *regs = cur_regs(env); + u8 opcode = BPF_OP(insn->code); + bool src_known, dst_known; + s64 smin_val, smax_val; + u64 umin_val, umax_val; + u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; + + smin_val = src_reg.smin_value; + smax_val = src_reg.smax_value; + umin_val = src_reg.umin_value; + umax_val = src_reg.umax_value; + src_known = tnum_is_const(src_reg.var_off); + dst_known = tnum_is_const(dst_reg->var_off); + + switch (opcode) { + case BPF_ADD: + if (signed_add_overflows(dst_reg->smin_value, smin_val) || + signed_add_overflows(dst_reg->smax_value, smax_val)) { + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + } else { + dst_reg->smin_value += smin_val; + dst_reg->smax_value += smax_val; + } + if (dst_reg->umin_value + umin_val < umin_val || + dst_reg->umax_value + umax_val < umax_val) { + dst_reg->umin_value = 0; + dst_reg->umax_value = U64_MAX; + } else { + dst_reg->umin_value += umin_val; + dst_reg->umax_value += umax_val; + } + dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); + break; + case BPF_SUB: + if (signed_sub_overflows(dst_reg->smin_value, smax_val) || + signed_sub_overflows(dst_reg->smax_value, smin_val)) { + /* Overflow possible, we know nothing */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + } else { + dst_reg->smin_value -= smax_val; + dst_reg->smax_value -= smin_val; + } + if (dst_reg->umin_value < umax_val) { + /* Overflow possible, we know nothing */ + dst_reg->umin_value = 0; + dst_reg->umax_value = U64_MAX; + } else { + /* Cannot overflow (as long as bounds are consistent) */ + dst_reg->umin_value -= umax_val; + dst_reg->umax_value -= umin_val; + } + dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); + break; + case BPF_MUL: + dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); + if (smin_val < 0 || dst_reg->smin_value < 0) { + /* Ain't nobody got time to multiply that sign */ + __mark_reg_unbounded(dst_reg); + __update_reg_bounds(dst_reg); + break; + } + /* Both values are positive, so we can work with unsigned and + * copy the result to signed (unless it exceeds S64_MAX). + */ + if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { + /* Potential overflow, we know nothing */ + __mark_reg_unbounded(dst_reg); + /* (except what we can learn from the var_off) */ + __update_reg_bounds(dst_reg); + break; + } + dst_reg->umin_value *= umin_val; + dst_reg->umax_value *= umax_val; + if (dst_reg->umax_value > S64_MAX) { + /* Overflow possible, we know nothing */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + } else { + dst_reg->smin_value = dst_reg->umin_value; + dst_reg->smax_value = dst_reg->umax_value; + } + break; + case BPF_AND: + if (src_known && dst_known) { + __mark_reg_known(dst_reg, dst_reg->var_off.value & + src_reg.var_off.value); + break; + } + /* We get our minimum from the var_off, since that's inherently + * bitwise. Our maximum is the minimum of the operands' maxima. + */ + dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); + dst_reg->umin_value = dst_reg->var_off.value; + dst_reg->umax_value = min(dst_reg->umax_value, umax_val); + if (dst_reg->smin_value < 0 || smin_val < 0) { + /* Lose signed bounds when ANDing negative numbers, + * ain't nobody got time for that. + */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + } else { + /* ANDing two positives gives a positive, so safe to + * cast result into s64. + */ + dst_reg->smin_value = dst_reg->umin_value; + dst_reg->smax_value = dst_reg->umax_value; + } + /* We may learn something more from the var_off */ + __update_reg_bounds(dst_reg); + break; + case BPF_OR: + if (src_known && dst_known) { + __mark_reg_known(dst_reg, dst_reg->var_off.value | + src_reg.var_off.value); + break; + } + /* We get our maximum from the var_off, and our minimum is the + * maximum of the operands' minima + */ + dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); + dst_reg->umin_value = max(dst_reg->umin_value, umin_val); + dst_reg->umax_value = dst_reg->var_off.value | + dst_reg->var_off.mask; + if (dst_reg->smin_value < 0 || smin_val < 0) { + /* Lose signed bounds when ORing negative numbers, + * ain't nobody got time for that. + */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + } else { + /* ORing two positives gives a positive, so safe to + * cast result into s64. + */ + dst_reg->smin_value = dst_reg->umin_value; + dst_reg->smax_value = dst_reg->umax_value; + } + /* We may learn something more from the var_off */ + __update_reg_bounds(dst_reg); + break; + case BPF_LSH: + if (umax_val >= insn_bitness) { + /* Shifts greater than 31 or 63 are undefined. + * This includes shifts by a negative number. + */ + mark_reg_unknown(env, regs, insn->dst_reg); + break; + } + /* We lose all sign bit information (except what we can pick + * up from var_off) + */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + /* If we might shift our top bit out, then we know nothing */ + if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { + dst_reg->umin_value = 0; + dst_reg->umax_value = U64_MAX; + } else { + dst_reg->umin_value <<= umin_val; + dst_reg->umax_value <<= umax_val; + } + if (src_known) + dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); + else + dst_reg->var_off = tnum_lshift(tnum_unknown, umin_val); + /* We may learn something more from the var_off */ + __update_reg_bounds(dst_reg); + break; + case BPF_RSH: + if (umax_val >= insn_bitness) { + /* Shifts greater than 31 or 63 are undefined. + * This includes shifts by a negative number. + */ + mark_reg_unknown(env, regs, insn->dst_reg); + break; + } + /* BPF_RSH is an unsigned shift. If the value in dst_reg might + * be negative, then either: + * 1) src_reg might be zero, so the sign bit of the result is + * unknown, so we lose our signed bounds + * 2) it's known negative, thus the unsigned bounds capture the + * signed bounds + * 3) the signed bounds cross zero, so they tell us nothing + * about the result + * If the value in dst_reg is known nonnegative, then again the + * unsigned bounts capture the signed bounds. + * Thus, in all cases it suffices to blow away our signed bounds + * and rely on inferring new ones from the unsigned bounds and + * var_off of the result. + */ + dst_reg->smin_value = S64_MIN; + dst_reg->smax_value = S64_MAX; + if (src_known) + dst_reg->var_off = tnum_rshift(dst_reg->var_off, + umin_val); + else + dst_reg->var_off = tnum_rshift(tnum_unknown, umin_val); + dst_reg->umin_value >>= umax_val; + dst_reg->umax_value >>= umin_val; + /* We may learn something more from the var_off */ + __update_reg_bounds(dst_reg); + break; + default: + mark_reg_unknown(env, regs, insn->dst_reg); + break; + } + + if (BPF_CLASS(insn->code) != BPF_ALU64) { + /* 32-bit ALU ops are (32,32)->32 */ + coerce_reg_to_size(dst_reg, 4); + coerce_reg_to_size(&src_reg, 4); + } + + __reg_deduce_bounds(dst_reg); + __reg_bound_offset(dst_reg); + return 0; +} +","@@ -2017,6 +2017,10 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, + return 0; + } + ++/* WARNING: This function does calculations on 64-bit values, but the actual ++ * execution may occur on 32-bit values. Therefore, things like bitshifts ++ * need extra checks in the 32-bit case. ++ */ + static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, + struct bpf_insn *insn, + struct bpf_reg_state *dst_reg, +@@ -2027,12 +2031,8 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, + bool src_known, dst_known; + s64 smin_val, smax_val; + u64 umin_val, umax_val; ++ u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; + +- if (BPF_CLASS(insn->code) != BPF_ALU64) { +- /* 32-bit ALU ops are (32,32)->64 */ +- coerce_reg_to_size(dst_reg, 4); +- coerce_reg_to_size(&src_reg, 4); +- } + smin_val = src_reg.smin_value; + smax_val = src_reg.smax_value; + umin_val = src_reg.umin_value; +@@ -2168,9 +2168,9 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, + __update_reg_bounds(dst_reg); + break; + case BPF_LSH: +- if (umax_val > 63) { +- /* Shifts greater than 63 are undefined. This includes +- * shifts by a negative number. ++ if (umax_val >= insn_bitness) { ++ /* Shifts greater than 31 or 63 are undefined. ++ * This includes shifts by a negative number. + */ + mark_reg_unknown(env, regs, insn->dst_reg); + break; +@@ -2196,9 +2196,9 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, + __update_reg_bounds(dst_reg); + break; + case BPF_RSH: +- if (umax_val > 63) { +- /* Shifts greater than 63 are undefined. This includes +- * shifts by a negative number. ++ if (umax_val >= insn_bitness) { ++ /* Shifts greater than 31 or 63 are undefined. ++ * This includes shifts by a negative number. + */ + mark_reg_unknown(env, regs, insn->dst_reg); + break; +@@ -2234,6 +2234,12 @@ static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, + break; + } + ++ if (BPF_CLASS(insn->code) != BPF_ALU64) { ++ /* 32-bit ALU ops are (32,32)->32 */ ++ coerce_reg_to_size(dst_reg, 4); ++ coerce_reg_to_size(&src_reg, 4); ++ } ++ + __reg_deduce_bounds(dst_reg); + __reg_bound_offset(dst_reg); + return 0;",2284,2615,4096 +9644,"MagickExport Image *HoughLineImage(const Image *image,const size_t width, + const size_t height,const size_t threshold,ExceptionInfo *exception) +{ +#define HoughLineImageTag ""HoughLine/Image"" + + CacheView + *image_view; + + char + message[MagickPathExtent], + path[MagickPathExtent]; + + const char + *artifact; + + double + hough_height; + + Image + *lines_image = NULL; + + ImageInfo + *image_info; + + int + file; + + MagickBooleanType + status; + + MagickOffsetType + progress; + + MatrixInfo + *accumulator; + + PointInfo + center; + + register ssize_t + y; + + size_t + accumulator_height, + accumulator_width, + line_count; + + /* + Create the accumulator. + */ + assert(image != (const 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); + accumulator_width=180; + hough_height=((sqrt(2.0)*(double) (image->rows > image->columns ? + image->rows : image->columns))/2.0); + accumulator_height=(size_t) (2.0*hough_height); + accumulator=AcquireMatrixInfo(accumulator_width,accumulator_height, + sizeof(double),exception); + if (accumulator == (MatrixInfo *) NULL) + ThrowImageException(ResourceLimitError,""MemoryAllocationFailed""); + if (NullMatrix(accumulator) == MagickFalse) + { + accumulator=DestroyMatrixInfo(accumulator); + ThrowImageException(ResourceLimitError,""MemoryAllocationFailed""); + } + /* + Populate the accumulator. + */ + status=MagickTrue; + progress=0; + center.x=(double) image->columns/2.0; + center.y=(double) image->rows/2.0; + image_view=AcquireVirtualCacheView(image,exception); + for (y=0; y < (ssize_t) image->rows; y++) + { + register const Quantum + *magick_restrict p; + + register ssize_t + x; + + if (status == MagickFalse) + continue; + p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); + if (p == (Quantum *) NULL) + { + status=MagickFalse; + continue; + } + for (x=0; x < (ssize_t) image->columns; x++) + { + if (GetPixelIntensity(image,p) > (QuantumRange/2.0)) + { + register ssize_t + i; + + for (i=0; i < 180; i++) + { + double + count, + radius; + + radius=(((double) x-center.x)*cos(DegreesToRadians((double) i)))+ + (((double) y-center.y)*sin(DegreesToRadians((double) i))); + (void) GetMatrixElement(accumulator,i,(ssize_t) + MagickRound(radius+hough_height),&count); + count++; + (void) SetMatrixElement(accumulator,i,(ssize_t) + MagickRound(radius+hough_height),&count); + } + } + p+=GetPixelChannels(image); + } + if (image->progress_monitor != (MagickProgressMonitor) NULL) + { + MagickBooleanType + proceed; + +#if defined(MAGICKCORE_OPENMP_SUPPORT) + #pragma omp atomic +#endif + progress++; + proceed=SetImageProgress(image,CannyEdgeImageTag,progress,image->rows); + if (proceed == MagickFalse) + status=MagickFalse; + } + } + image_view=DestroyCacheView(image_view); + if (status == MagickFalse) + { + accumulator=DestroyMatrixInfo(accumulator); + return((Image *) NULL); + } + /* + Generate line segments from accumulator. + */ + file=AcquireUniqueFileResource(path); + if (file == -1) + { + accumulator=DestroyMatrixInfo(accumulator); + return((Image *) NULL); + } + (void) FormatLocaleString(message,MagickPathExtent, + ""# Hough line transform: %.20gx%.20g%+.20g\n"",(double) width, + (double) height,(double) threshold); + if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) + status=MagickFalse; + (void) FormatLocaleString(message,MagickPathExtent, + ""viewbox 0 0 %.20g %.20g\n"",(double) image->columns,(double) image->rows); + if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) + status=MagickFalse; + (void) FormatLocaleString(message,MagickPathExtent, + ""# x1,y1 x2,y2 # count angle distance\n""); + if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) + status=MagickFalse; + line_count=image->columns > image->rows ? image->columns/4 : image->rows/4; + if (threshold != 0) + line_count=threshold; + for (y=0; y < (ssize_t) accumulator_height; y++) + { + register ssize_t + x; + + for (x=0; x < (ssize_t) accumulator_width; x++) + { + double + count; + + (void) GetMatrixElement(accumulator,x,y,&count); + if (count >= (double) line_count) + { + double + maxima; + + SegmentInfo + line; + + ssize_t + v; + + /* + Is point a local maxima? + */ + maxima=count; + for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++) + { + ssize_t + u; + + for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++) + { + if ((u != 0) || (v !=0)) + { + (void) GetMatrixElement(accumulator,x+u,y+v,&count); + if (count > maxima) + { + maxima=count; + break; + } + } + } + if (u < (ssize_t) (width/2)) + break; + } + (void) GetMatrixElement(accumulator,x,y,&count); + if (maxima > count) + continue; + if ((x >= 45) && (x <= 135)) + { + /* + y = (r-x cos(t))/sin(t) + */ + line.x1=0.0; + line.y1=((double) (y-(accumulator_height/2.0))-((line.x1- + (image->columns/2.0))*cos(DegreesToRadians((double) x))))/ + sin(DegreesToRadians((double) x))+(image->rows/2.0); + line.x2=(double) image->columns; + line.y2=((double) (y-(accumulator_height/2.0))-((line.x2- + (image->columns/2.0))*cos(DegreesToRadians((double) x))))/ + sin(DegreesToRadians((double) x))+(image->rows/2.0); + } + else + { + /* + x = (r-y cos(t))/sin(t) + */ + line.y1=0.0; + line.x1=((double) (y-(accumulator_height/2.0))-((line.y1- + (image->rows/2.0))*sin(DegreesToRadians((double) x))))/ + cos(DegreesToRadians((double) x))+(image->columns/2.0); + line.y2=(double) image->rows; + line.x2=((double) (y-(accumulator_height/2.0))-((line.y2- + (image->rows/2.0))*sin(DegreesToRadians((double) x))))/ + cos(DegreesToRadians((double) x))+(image->columns/2.0); + } + (void) FormatLocaleString(message,MagickPathExtent, + ""line %g,%g %g,%g # %g %g %g\n"",line.x1,line.y1,line.x2,line.y2, + maxima,(double) x,(double) y); + if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) + status=MagickFalse; + } + } + } + (void) close(file); + /* + Render lines to image canvas. + */ + image_info=AcquireImageInfo(); + image_info->background_color=image->background_color; + (void) FormatLocaleString(image_info->filename,MagickPathExtent,""%s"",path); + artifact=GetImageArtifact(image,""background""); + if (artifact != (const char *) NULL) + (void) SetImageOption(image_info,""background"",artifact); + artifact=GetImageArtifact(image,""fill""); + if (artifact != (const char *) NULL) + (void) SetImageOption(image_info,""fill"",artifact); + artifact=GetImageArtifact(image,""stroke""); + if (artifact != (const char *) NULL) + (void) SetImageOption(image_info,""stroke"",artifact); + artifact=GetImageArtifact(image,""strokewidth""); + if (artifact != (const char *) NULL) + (void) SetImageOption(image_info,""strokewidth"",artifact); + lines_image=RenderHoughLines(image_info,image->columns,image->rows,exception); + artifact=GetImageArtifact(image,""hough-lines:accumulator""); + if ((lines_image != (Image *) NULL) && + (IsStringTrue(artifact) != MagickFalse)) + { + Image + *accumulator_image; + + accumulator_image=MatrixToImage(accumulator,exception); + if (accumulator_image != (Image *) NULL) + AppendImageToList(&lines_image,accumulator_image); + } + /* + Free resources. + */ + accumulator=DestroyMatrixInfo(accumulator); + image_info=DestroyImageInfo(image_info); + (void) RelinquishUniqueFileResource(path); + return(GetFirstImageInList(lines_image)); +} +",0,"MagickExport Image *HoughLineImage(const Image *image,const size_t width, + const size_t height,const size_t threshold,ExceptionInfo *exception) +{ +#define HoughLineImageTag ""HoughLine/Image"" + + CacheView + *image_view; + + char + message[MagickPathExtent], + path[MagickPathExtent]; + + const char + *artifact; + + double + hough_height; + + Image + *lines_image = NULL; + + ImageInfo + *image_info; + + int + file; + + MagickBooleanType + status; + + MagickOffsetType + progress; + + MatrixInfo + *accumulator; + + PointInfo + center; + + register ssize_t + y; + + size_t + accumulator_height, + accumulator_width, + line_count; + + /* + Create the accumulator. + */ + assert(image != (const 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); + accumulator_width=180; + hough_height=((sqrt(2.0)*(double) (image->rows > image->columns ? + image->rows : image->columns))/2.0); + accumulator_height=(size_t) (2.0*hough_height); + accumulator=AcquireMatrixInfo(accumulator_width,accumulator_height, + sizeof(double),exception); + if (accumulator == (MatrixInfo *) NULL) + ThrowImageException(ResourceLimitError,""MemoryAllocationFailed""); + if (NullMatrix(accumulator) == MagickFalse) + { + accumulator=DestroyMatrixInfo(accumulator); + ThrowImageException(ResourceLimitError,""MemoryAllocationFailed""); + } + /* + Populate the accumulator. + */ + status=MagickTrue; + progress=0; + center.x=(double) image->columns/2.0; + center.y=(double) image->rows/2.0; + image_view=AcquireVirtualCacheView(image,exception); + for (y=0; y < (ssize_t) image->rows; y++) + { + register const Quantum + *magick_restrict p; + + register ssize_t + x; + + if (status == MagickFalse) + continue; + p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); + if (p == (Quantum *) NULL) + { + status=MagickFalse; + continue; + } + for (x=0; x < (ssize_t) image->columns; x++) + { + if (GetPixelIntensity(image,p) > (QuantumRange/2.0)) + { + register ssize_t + i; + + for (i=0; i < 180; i++) + { + double + count, + radius; + + radius=(((double) x-center.x)*cos(DegreesToRadians((double) i)))+ + (((double) y-center.y)*sin(DegreesToRadians((double) i))); + (void) GetMatrixElement(accumulator,i,(ssize_t) + MagickRound(radius+hough_height),&count); + count++; + (void) SetMatrixElement(accumulator,i,(ssize_t) + MagickRound(radius+hough_height),&count); + } + } + p+=GetPixelChannels(image); + } + if (image->progress_monitor != (MagickProgressMonitor) NULL) + { + MagickBooleanType + proceed; + +#if defined(MAGICKCORE_OPENMP_SUPPORT) + #pragma omp atomic +#endif + progress++; + proceed=SetImageProgress(image,CannyEdgeImageTag,progress,image->rows); + if (proceed == MagickFalse) + status=MagickFalse; + } + } + image_view=DestroyCacheView(image_view); + if (status == MagickFalse) + { + accumulator=DestroyMatrixInfo(accumulator); + return((Image *) NULL); + } + /* + Generate line segments from accumulator. + */ + file=AcquireUniqueFileResource(path); + if (file == -1) + { + accumulator=DestroyMatrixInfo(accumulator); + return((Image *) NULL); + } + (void) FormatLocaleString(message,MagickPathExtent, + ""# Hough line transform: %.20gx%.20g%+.20g\n"",(double) width, + (double) height,(double) threshold); + if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) + status=MagickFalse; + (void) FormatLocaleString(message,MagickPathExtent, + ""viewbox 0 0 %.20g %.20g\n"",(double) image->columns,(double) image->rows); + if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) + status=MagickFalse; + (void) FormatLocaleString(message,MagickPathExtent, + ""# x1,y1 x2,y2 # count angle distance\n""); + if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) + status=MagickFalse; + line_count=image->columns > image->rows ? image->columns/4 : image->rows/4; + if (threshold != 0) + line_count=threshold; + for (y=0; y < (ssize_t) accumulator_height; y++) + { + register ssize_t + x; + + for (x=0; x < (ssize_t) accumulator_width; x++) + { + double + count; + + (void) GetMatrixElement(accumulator,x,y,&count); + if (count >= (double) line_count) + { + double + maxima; + + SegmentInfo + line; + + ssize_t + v; + + /* + Is point a local maxima? + */ + maxima=count; + for (v=(-((ssize_t) height/2)); v <= (((ssize_t) height/2)); v++) + { + ssize_t + u; + + for (u=(-((ssize_t) width/2)); u <= (((ssize_t) width/2)); u++) + { + if ((u != 0) || (v !=0)) + { + (void) GetMatrixElement(accumulator,x+u,y+v,&count); + if (count > maxima) + { + maxima=count; + break; + } + } + } + if (u < (ssize_t) (width/2)) + break; + } + (void) GetMatrixElement(accumulator,x,y,&count); + if (maxima > count) + continue; + if ((x >= 45) && (x <= 135)) + { + /* + y = (r-x cos(t))/sin(t) + */ + line.x1=0.0; + line.y1=((double) (y-(accumulator_height/2.0))-((line.x1- + (image->columns/2.0))*cos(DegreesToRadians((double) x))))/ + sin(DegreesToRadians((double) x))+(image->rows/2.0); + line.x2=(double) image->columns; + line.y2=((double) (y-(accumulator_height/2.0))-((line.x2- + (image->columns/2.0))*cos(DegreesToRadians((double) x))))/ + sin(DegreesToRadians((double) x))+(image->rows/2.0); + } + else + { + /* + x = (r-y cos(t))/sin(t) + */ + line.y1=0.0; + line.x1=((double) (y-(accumulator_height/2.0))-((line.y1- + (image->rows/2.0))*sin(DegreesToRadians((double) x))))/ + cos(DegreesToRadians((double) x))+(image->columns/2.0); + line.y2=(double) image->rows; + line.x2=((double) (y-(accumulator_height/2.0))-((line.y2- + (image->rows/2.0))*sin(DegreesToRadians((double) x))))/ + cos(DegreesToRadians((double) x))+(image->columns/2.0); + } + (void) FormatLocaleString(message,MagickPathExtent, + ""line %g,%g %g,%g # %g %g %g\n"",line.x1,line.y1,line.x2,line.y2, + maxima,(double) x,(double) y); + if (write(file,message,strlen(message)) != (ssize_t) strlen(message)) + status=MagickFalse; + } + } + } + (void) close(file); + /* + Render lines to image canvas. + */ + image_info=AcquireImageInfo(); + image_info->background_color=image->background_color; + (void) FormatLocaleString(image_info->filename,MagickPathExtent,""%s"",path); + artifact=GetImageArtifact(image,""background""); + if (artifact != (const char *) NULL) + (void) SetImageOption(image_info,""background"",artifact); + artifact=GetImageArtifact(image,""fill""); + if (artifact != (const char *) NULL) + (void) SetImageOption(image_info,""fill"",artifact); + artifact=GetImageArtifact(image,""stroke""); + if (artifact != (const char *) NULL) + (void) SetImageOption(image_info,""stroke"",artifact); + artifact=GetImageArtifact(image,""strokewidth""); + if (artifact != (const char *) NULL) + (void) SetImageOption(image_info,""strokewidth"",artifact); + lines_image=RenderHoughLines(image_info,image->columns,image->rows,exception); + artifact=GetImageArtifact(image,""hough-lines:accumulator""); + if ((lines_image != (Image *) NULL) && + (IsStringTrue(artifact) != MagickFalse)) + { + Image + *accumulator_image; + + accumulator_image=MatrixToImage(accumulator,exception); + if (accumulator_image != (Image *) NULL) + AppendImageToList(&lines_image,accumulator_image); + } + /* + Free resources. + */ + accumulator=DestroyMatrixInfo(accumulator); + image_info=DestroyImageInfo(image_info); + (void) RelinquishUniqueFileResource(path); + return(GetFirstImageInList(lines_image)); +} +","@@ -2288,7 +2288,7 @@ MagickExport Image *MeanShiftImage(const Image *image,const size_t width, + } + } + } +- gamma=1.0/count; ++ gamma=PerceptibleReciprocal(count); + mean_location.x=gamma*sum_location.x; + mean_location.y=gamma*sum_location.y; + mean_pixel.red=gamma*sum_pixel.red;",2231,2562,4096 +17998,"static long vfio_pci_ioctl(void *device_data, + unsigned int cmd, unsigned long arg) +{ + struct vfio_pci_device *vdev = device_data; + unsigned long minsz; + + if (cmd == VFIO_DEVICE_GET_INFO) { + struct vfio_device_info info; + + minsz = offsetofend(struct vfio_device_info, num_irqs); + + if (copy_from_user(&info, (void __user *)arg, minsz)) + return -EFAULT; + + if (info.argsz < minsz) + return -EINVAL; + + info.flags = VFIO_DEVICE_FLAGS_PCI; + + if (vdev->reset_works) + info.flags |= VFIO_DEVICE_FLAGS_RESET; + + info.num_regions = VFIO_PCI_NUM_REGIONS + vdev->num_regions; + info.num_irqs = VFIO_PCI_NUM_IRQS; + + return copy_to_user((void __user *)arg, &info, minsz) ? + -EFAULT : 0; + + } else if (cmd == VFIO_DEVICE_GET_REGION_INFO) { + struct pci_dev *pdev = vdev->pdev; + struct vfio_region_info info; + struct vfio_info_cap caps = { .buf = NULL, .size = 0 }; + int i, ret; + + minsz = offsetofend(struct vfio_region_info, offset); + + if (copy_from_user(&info, (void __user *)arg, minsz)) + return -EFAULT; + + if (info.argsz < minsz) + return -EINVAL; + + switch (info.index) { + case VFIO_PCI_CONFIG_REGION_INDEX: + info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index); + info.size = pdev->cfg_size; + info.flags = VFIO_REGION_INFO_FLAG_READ | + VFIO_REGION_INFO_FLAG_WRITE; + break; + case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX: + info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index); + info.size = pci_resource_len(pdev, info.index); + if (!info.size) { + info.flags = 0; + break; + } + + info.flags = VFIO_REGION_INFO_FLAG_READ | + VFIO_REGION_INFO_FLAG_WRITE; + if (vdev->bar_mmap_supported[info.index]) { + info.flags |= VFIO_REGION_INFO_FLAG_MMAP; + if (info.index == vdev->msix_bar) { + ret = msix_sparse_mmap_cap(vdev, &caps); + if (ret) + return ret; + } + } + + break; + case VFIO_PCI_ROM_REGION_INDEX: + { + void __iomem *io; + size_t size; + + info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index); + info.flags = 0; + + /* Report the BAR size, not the ROM size */ + info.size = pci_resource_len(pdev, info.index); + if (!info.size) { + /* Shadow ROMs appear as PCI option ROMs */ + if (pdev->resource[PCI_ROM_RESOURCE].flags & + IORESOURCE_ROM_SHADOW) + info.size = 0x20000; + else + break; + } + + /* Is it really there? */ + io = pci_map_rom(pdev, &size); + if (!io || !size) { + info.size = 0; + break; + } + pci_unmap_rom(pdev, io); + + info.flags = VFIO_REGION_INFO_FLAG_READ; + break; + } + case VFIO_PCI_VGA_REGION_INDEX: + if (!vdev->has_vga) + return -EINVAL; + + info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index); + info.size = 0xc0000; + info.flags = VFIO_REGION_INFO_FLAG_READ | + VFIO_REGION_INFO_FLAG_WRITE; + + break; + default: + if (info.index >= + VFIO_PCI_NUM_REGIONS + vdev->num_regions) + return -EINVAL; + + i = info.index - VFIO_PCI_NUM_REGIONS; + + info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index); + info.size = vdev->region[i].size; + info.flags = vdev->region[i].flags; + + ret = region_type_cap(vdev, &caps, + vdev->region[i].type, + vdev->region[i].subtype); + if (ret) + return ret; + } + + if (caps.size) { + info.flags |= VFIO_REGION_INFO_FLAG_CAPS; + if (info.argsz < sizeof(info) + caps.size) { + info.argsz = sizeof(info) + caps.size; + info.cap_offset = 0; + } else { + vfio_info_cap_shift(&caps, sizeof(info)); + if (copy_to_user((void __user *)arg + + sizeof(info), caps.buf, + caps.size)) { + kfree(caps.buf); + return -EFAULT; + } + info.cap_offset = sizeof(info); + } + + kfree(caps.buf); + } + + return copy_to_user((void __user *)arg, &info, minsz) ? + -EFAULT : 0; + + } else if (cmd == VFIO_DEVICE_GET_IRQ_INFO) { + struct vfio_irq_info info; + + minsz = offsetofend(struct vfio_irq_info, count); + + if (copy_from_user(&info, (void __user *)arg, minsz)) + return -EFAULT; + + if (info.argsz < minsz || info.index >= VFIO_PCI_NUM_IRQS) + return -EINVAL; + + switch (info.index) { + case VFIO_PCI_INTX_IRQ_INDEX ... VFIO_PCI_MSIX_IRQ_INDEX: + case VFIO_PCI_REQ_IRQ_INDEX: + break; + case VFIO_PCI_ERR_IRQ_INDEX: + if (pci_is_pcie(vdev->pdev)) + break; + /* pass thru to return error */ + default: + return -EINVAL; + } + + info.flags = VFIO_IRQ_INFO_EVENTFD; + + info.count = vfio_pci_get_irq_count(vdev, info.index); + + if (info.index == VFIO_PCI_INTX_IRQ_INDEX) + info.flags |= (VFIO_IRQ_INFO_MASKABLE | + VFIO_IRQ_INFO_AUTOMASKED); + else + info.flags |= VFIO_IRQ_INFO_NORESIZE; + + return copy_to_user((void __user *)arg, &info, minsz) ? + -EFAULT : 0; + + } else if (cmd == VFIO_DEVICE_SET_IRQS) { + struct vfio_irq_set hdr; + u8 *data = NULL; + int ret = 0; + + minsz = offsetofend(struct vfio_irq_set, count); + + if (copy_from_user(&hdr, (void __user *)arg, minsz)) + return -EFAULT; + + if (hdr.argsz < minsz || hdr.index >= VFIO_PCI_NUM_IRQS || + hdr.flags & ~(VFIO_IRQ_SET_DATA_TYPE_MASK | + VFIO_IRQ_SET_ACTION_TYPE_MASK)) + return -EINVAL; + + if (!(hdr.flags & VFIO_IRQ_SET_DATA_NONE)) { + size_t size; + int max = vfio_pci_get_irq_count(vdev, hdr.index); + + if (hdr.flags & VFIO_IRQ_SET_DATA_BOOL) + size = sizeof(uint8_t); + else if (hdr.flags & VFIO_IRQ_SET_DATA_EVENTFD) + size = sizeof(int32_t); + else + return -EINVAL; + + if (hdr.argsz - minsz < hdr.count * size || + hdr.start >= max || hdr.start + hdr.count > max) + return -EINVAL; + + data = memdup_user((void __user *)(arg + minsz), + hdr.count * size); + if (IS_ERR(data)) + return PTR_ERR(data); + } + + mutex_lock(&vdev->igate); + + ret = vfio_pci_set_irqs_ioctl(vdev, hdr.flags, hdr.index, + hdr.start, hdr.count, data); + + mutex_unlock(&vdev->igate); + kfree(data); + + return ret; + + } else if (cmd == VFIO_DEVICE_RESET) { + return vdev->reset_works ? + pci_try_reset_function(vdev->pdev) : -EINVAL; + + } else if (cmd == VFIO_DEVICE_GET_PCI_HOT_RESET_INFO) { + struct vfio_pci_hot_reset_info hdr; + struct vfio_pci_fill_info fill = { 0 }; + struct vfio_pci_dependent_device *devices = NULL; + bool slot = false; + int ret = 0; + + minsz = offsetofend(struct vfio_pci_hot_reset_info, count); + + if (copy_from_user(&hdr, (void __user *)arg, minsz)) + return -EFAULT; + + if (hdr.argsz < minsz) + return -EINVAL; + + hdr.flags = 0; + + /* Can we do a slot or bus reset or neither? */ + if (!pci_probe_reset_slot(vdev->pdev->slot)) + slot = true; + else if (pci_probe_reset_bus(vdev->pdev->bus)) + return -ENODEV; + + /* How many devices are affected? */ + ret = vfio_pci_for_each_slot_or_bus(vdev->pdev, + vfio_pci_count_devs, + &fill.max, slot); + if (ret) + return ret; + + WARN_ON(!fill.max); /* Should always be at least one */ + + /* + * If there's enough space, fill it now, otherwise return + * -ENOSPC and the number of devices affected. + */ + if (hdr.argsz < sizeof(hdr) + (fill.max * sizeof(*devices))) { + ret = -ENOSPC; + hdr.count = fill.max; + goto reset_info_exit; + } + + devices = kcalloc(fill.max, sizeof(*devices), GFP_KERNEL); + if (!devices) + return -ENOMEM; + + fill.devices = devices; + + ret = vfio_pci_for_each_slot_or_bus(vdev->pdev, + vfio_pci_fill_devs, + &fill, slot); + + /* + * If a device was removed between counting and filling, + * we may come up short of fill.max. If a device was + * added, we'll have a return of -EAGAIN above. + */ + if (!ret) + hdr.count = fill.cur; + +reset_info_exit: + if (copy_to_user((void __user *)arg, &hdr, minsz)) + ret = -EFAULT; + + if (!ret) { + if (copy_to_user((void __user *)(arg + minsz), devices, + hdr.count * sizeof(*devices))) + ret = -EFAULT; + } + + kfree(devices); + return ret; + + } else if (cmd == VFIO_DEVICE_PCI_HOT_RESET) { + struct vfio_pci_hot_reset hdr; + int32_t *group_fds; + struct vfio_pci_group_entry *groups; + struct vfio_pci_group_info info; + bool slot = false; + int i, count = 0, ret = 0; + + minsz = offsetofend(struct vfio_pci_hot_reset, count); + + if (copy_from_user(&hdr, (void __user *)arg, minsz)) + return -EFAULT; + + if (hdr.argsz < minsz || hdr.flags) + return -EINVAL; + + /* Can we do a slot or bus reset or neither? */ + if (!pci_probe_reset_slot(vdev->pdev->slot)) + slot = true; + else if (pci_probe_reset_bus(vdev->pdev->bus)) + return -ENODEV; + + /* + * We can't let userspace give us an arbitrarily large + * buffer to copy, so verify how many we think there + * could be. Note groups can have multiple devices so + * one group per device is the max. + */ + ret = vfio_pci_for_each_slot_or_bus(vdev->pdev, + vfio_pci_count_devs, + &count, slot); + if (ret) + return ret; + + /* Somewhere between 1 and count is OK */ + if (!hdr.count || hdr.count > count) + return -EINVAL; + + group_fds = kcalloc(hdr.count, sizeof(*group_fds), GFP_KERNEL); + groups = kcalloc(hdr.count, sizeof(*groups), GFP_KERNEL); + if (!group_fds || !groups) { + kfree(group_fds); + kfree(groups); + return -ENOMEM; + } + + if (copy_from_user(group_fds, (void __user *)(arg + minsz), + hdr.count * sizeof(*group_fds))) { + kfree(group_fds); + kfree(groups); + return -EFAULT; + } + + /* + * For each group_fd, get the group through the vfio external + * user interface and store the group and iommu ID. This + * ensures the group is held across the reset. + */ + for (i = 0; i < hdr.count; i++) { + struct vfio_group *group; + struct fd f = fdget(group_fds[i]); + if (!f.file) { + ret = -EBADF; + break; + } + + group = vfio_group_get_external_user(f.file); + fdput(f); + if (IS_ERR(group)) { + ret = PTR_ERR(group); + break; + } + + groups[i].group = group; + groups[i].id = vfio_external_user_iommu_id(group); + } + + kfree(group_fds); + + /* release reference to groups on error */ + if (ret) + goto hot_reset_release; + + info.count = hdr.count; + info.groups = groups; + + /* + * Test whether all the affected devices are contained + * by the set of groups provided by the user. + */ + ret = vfio_pci_for_each_slot_or_bus(vdev->pdev, + vfio_pci_validate_devs, + &info, slot); + if (!ret) + /* User has access, do the reset */ + ret = slot ? pci_try_reset_slot(vdev->pdev->slot) : + pci_try_reset_bus(vdev->pdev->bus); + +hot_reset_release: + for (i--; i >= 0; i--) + vfio_group_put_external_user(groups[i].group); + + kfree(groups); + return ret; + } + + return -ENOTTY; +} +",1,"static long vfio_pci_ioctl(void *device_data, + unsigned int cmd, unsigned long arg) +{ + struct vfio_pci_device *vdev = device_data; + unsigned long minsz; + + if (cmd == VFIO_DEVICE_GET_INFO) { + struct vfio_device_info info; + + minsz = offsetofend(struct vfio_device_info, num_irqs); + + if (copy_from_user(&info, (void __user *)arg, minsz)) + return -EFAULT; + + if (info.argsz < minsz) + return -EINVAL; + + info.flags = VFIO_DEVICE_FLAGS_PCI; + + if (vdev->reset_works) + info.flags |= VFIO_DEVICE_FLAGS_RESET; + + info.num_regions = VFIO_PCI_NUM_REGIONS + vdev->num_regions; + info.num_irqs = VFIO_PCI_NUM_IRQS; + + return copy_to_user((void __user *)arg, &info, minsz) ? + -EFAULT : 0; + + } else if (cmd == VFIO_DEVICE_GET_REGION_INFO) { + struct pci_dev *pdev = vdev->pdev; + struct vfio_region_info info; + struct vfio_info_cap caps = { .buf = NULL, .size = 0 }; + int i, ret; + + minsz = offsetofend(struct vfio_region_info, offset); + + if (copy_from_user(&info, (void __user *)arg, minsz)) + return -EFAULT; + + if (info.argsz < minsz) + return -EINVAL; + + switch (info.index) { + case VFIO_PCI_CONFIG_REGION_INDEX: + info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index); + info.size = pdev->cfg_size; + info.flags = VFIO_REGION_INFO_FLAG_READ | + VFIO_REGION_INFO_FLAG_WRITE; + break; + case VFIO_PCI_BAR0_REGION_INDEX ... VFIO_PCI_BAR5_REGION_INDEX: + info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index); + info.size = pci_resource_len(pdev, info.index); + if (!info.size) { + info.flags = 0; + break; + } + + info.flags = VFIO_REGION_INFO_FLAG_READ | + VFIO_REGION_INFO_FLAG_WRITE; + if (vdev->bar_mmap_supported[info.index]) { + info.flags |= VFIO_REGION_INFO_FLAG_MMAP; + if (info.index == vdev->msix_bar) { + ret = msix_sparse_mmap_cap(vdev, &caps); + if (ret) + return ret; + } + } + + break; + case VFIO_PCI_ROM_REGION_INDEX: + { + void __iomem *io; + size_t size; + + info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index); + info.flags = 0; + + /* Report the BAR size, not the ROM size */ + info.size = pci_resource_len(pdev, info.index); + if (!info.size) { + /* Shadow ROMs appear as PCI option ROMs */ + if (pdev->resource[PCI_ROM_RESOURCE].flags & + IORESOURCE_ROM_SHADOW) + info.size = 0x20000; + else + break; + } + + /* Is it really there? */ + io = pci_map_rom(pdev, &size); + if (!io || !size) { + info.size = 0; + break; + } + pci_unmap_rom(pdev, io); + + info.flags = VFIO_REGION_INFO_FLAG_READ; + break; + } + case VFIO_PCI_VGA_REGION_INDEX: + if (!vdev->has_vga) + return -EINVAL; + + info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index); + info.size = 0xc0000; + info.flags = VFIO_REGION_INFO_FLAG_READ | + VFIO_REGION_INFO_FLAG_WRITE; + + break; + default: + if (info.index >= + VFIO_PCI_NUM_REGIONS + vdev->num_regions) + return -EINVAL; + + i = info.index - VFIO_PCI_NUM_REGIONS; + + info.offset = VFIO_PCI_INDEX_TO_OFFSET(info.index); + info.size = vdev->region[i].size; + info.flags = vdev->region[i].flags; + + ret = region_type_cap(vdev, &caps, + vdev->region[i].type, + vdev->region[i].subtype); + if (ret) + return ret; + } + + if (caps.size) { + info.flags |= VFIO_REGION_INFO_FLAG_CAPS; + if (info.argsz < sizeof(info) + caps.size) { + info.argsz = sizeof(info) + caps.size; + info.cap_offset = 0; + } else { + vfio_info_cap_shift(&caps, sizeof(info)); + if (copy_to_user((void __user *)arg + + sizeof(info), caps.buf, + caps.size)) { + kfree(caps.buf); + return -EFAULT; + } + info.cap_offset = sizeof(info); + } + + kfree(caps.buf); + } + + return copy_to_user((void __user *)arg, &info, minsz) ? + -EFAULT : 0; + + } else if (cmd == VFIO_DEVICE_GET_IRQ_INFO) { + struct vfio_irq_info info; + + minsz = offsetofend(struct vfio_irq_info, count); + + if (copy_from_user(&info, (void __user *)arg, minsz)) + return -EFAULT; + + if (info.argsz < minsz || info.index >= VFIO_PCI_NUM_IRQS) + return -EINVAL; + + switch (info.index) { + case VFIO_PCI_INTX_IRQ_INDEX ... VFIO_PCI_MSIX_IRQ_INDEX: + case VFIO_PCI_REQ_IRQ_INDEX: + break; + case VFIO_PCI_ERR_IRQ_INDEX: + if (pci_is_pcie(vdev->pdev)) + break; + /* pass thru to return error */ + default: + return -EINVAL; + } + + info.flags = VFIO_IRQ_INFO_EVENTFD; + + info.count = vfio_pci_get_irq_count(vdev, info.index); + + if (info.index == VFIO_PCI_INTX_IRQ_INDEX) + info.flags |= (VFIO_IRQ_INFO_MASKABLE | + VFIO_IRQ_INFO_AUTOMASKED); + else + info.flags |= VFIO_IRQ_INFO_NORESIZE; + + return copy_to_user((void __user *)arg, &info, minsz) ? + -EFAULT : 0; + + } else if (cmd == VFIO_DEVICE_SET_IRQS) { + struct vfio_irq_set hdr; + size_t size; + u8 *data = NULL; + int max, ret = 0; + + minsz = offsetofend(struct vfio_irq_set, count); + + if (copy_from_user(&hdr, (void __user *)arg, minsz)) + return -EFAULT; + + if (hdr.argsz < minsz || hdr.index >= VFIO_PCI_NUM_IRQS || + hdr.count >= (U32_MAX - hdr.start) || + hdr.flags & ~(VFIO_IRQ_SET_DATA_TYPE_MASK | + VFIO_IRQ_SET_ACTION_TYPE_MASK)) + return -EINVAL; + + max = vfio_pci_get_irq_count(vdev, hdr.index); + if (hdr.start >= max || hdr.start + hdr.count > max) + return -EINVAL; + + switch (hdr.flags & VFIO_IRQ_SET_DATA_TYPE_MASK) { + case VFIO_IRQ_SET_DATA_NONE: + size = 0; + break; + case VFIO_IRQ_SET_DATA_BOOL: + size = sizeof(uint8_t); + break; + case VFIO_IRQ_SET_DATA_EVENTFD: + size = sizeof(int32_t); + break; + default: + return -EINVAL; + } + + if (size) { + if (hdr.argsz - minsz < hdr.count * size) + return -EINVAL; + + data = memdup_user((void __user *)(arg + minsz), + hdr.count * size); + if (IS_ERR(data)) + return PTR_ERR(data); + } + + mutex_lock(&vdev->igate); + + ret = vfio_pci_set_irqs_ioctl(vdev, hdr.flags, hdr.index, + hdr.start, hdr.count, data); + + mutex_unlock(&vdev->igate); + kfree(data); + + return ret; + + } else if (cmd == VFIO_DEVICE_RESET) { + return vdev->reset_works ? + pci_try_reset_function(vdev->pdev) : -EINVAL; + + } else if (cmd == VFIO_DEVICE_GET_PCI_HOT_RESET_INFO) { + struct vfio_pci_hot_reset_info hdr; + struct vfio_pci_fill_info fill = { 0 }; + struct vfio_pci_dependent_device *devices = NULL; + bool slot = false; + int ret = 0; + + minsz = offsetofend(struct vfio_pci_hot_reset_info, count); + + if (copy_from_user(&hdr, (void __user *)arg, minsz)) + return -EFAULT; + + if (hdr.argsz < minsz) + return -EINVAL; + + hdr.flags = 0; + + /* Can we do a slot or bus reset or neither? */ + if (!pci_probe_reset_slot(vdev->pdev->slot)) + slot = true; + else if (pci_probe_reset_bus(vdev->pdev->bus)) + return -ENODEV; + + /* How many devices are affected? */ + ret = vfio_pci_for_each_slot_or_bus(vdev->pdev, + vfio_pci_count_devs, + &fill.max, slot); + if (ret) + return ret; + + WARN_ON(!fill.max); /* Should always be at least one */ + + /* + * If there's enough space, fill it now, otherwise return + * -ENOSPC and the number of devices affected. + */ + if (hdr.argsz < sizeof(hdr) + (fill.max * sizeof(*devices))) { + ret = -ENOSPC; + hdr.count = fill.max; + goto reset_info_exit; + } + + devices = kcalloc(fill.max, sizeof(*devices), GFP_KERNEL); + if (!devices) + return -ENOMEM; + + fill.devices = devices; + + ret = vfio_pci_for_each_slot_or_bus(vdev->pdev, + vfio_pci_fill_devs, + &fill, slot); + + /* + * If a device was removed between counting and filling, + * we may come up short of fill.max. If a device was + * added, we'll have a return of -EAGAIN above. + */ + if (!ret) + hdr.count = fill.cur; + +reset_info_exit: + if (copy_to_user((void __user *)arg, &hdr, minsz)) + ret = -EFAULT; + + if (!ret) { + if (copy_to_user((void __user *)(arg + minsz), devices, + hdr.count * sizeof(*devices))) + ret = -EFAULT; + } + + kfree(devices); + return ret; + + } else if (cmd == VFIO_DEVICE_PCI_HOT_RESET) { + struct vfio_pci_hot_reset hdr; + int32_t *group_fds; + struct vfio_pci_group_entry *groups; + struct vfio_pci_group_info info; + bool slot = false; + int i, count = 0, ret = 0; + + minsz = offsetofend(struct vfio_pci_hot_reset, count); + + if (copy_from_user(&hdr, (void __user *)arg, minsz)) + return -EFAULT; + + if (hdr.argsz < minsz || hdr.flags) + return -EINVAL; + + /* Can we do a slot or bus reset or neither? */ + if (!pci_probe_reset_slot(vdev->pdev->slot)) + slot = true; + else if (pci_probe_reset_bus(vdev->pdev->bus)) + return -ENODEV; + + /* + * We can't let userspace give us an arbitrarily large + * buffer to copy, so verify how many we think there + * could be. Note groups can have multiple devices so + * one group per device is the max. + */ + ret = vfio_pci_for_each_slot_or_bus(vdev->pdev, + vfio_pci_count_devs, + &count, slot); + if (ret) + return ret; + + /* Somewhere between 1 and count is OK */ + if (!hdr.count || hdr.count > count) + return -EINVAL; + + group_fds = kcalloc(hdr.count, sizeof(*group_fds), GFP_KERNEL); + groups = kcalloc(hdr.count, sizeof(*groups), GFP_KERNEL); + if (!group_fds || !groups) { + kfree(group_fds); + kfree(groups); + return -ENOMEM; + } + + if (copy_from_user(group_fds, (void __user *)(arg + minsz), + hdr.count * sizeof(*group_fds))) { + kfree(group_fds); + kfree(groups); + return -EFAULT; + } + + /* + * For each group_fd, get the group through the vfio external + * user interface and store the group and iommu ID. This + * ensures the group is held across the reset. + */ + for (i = 0; i < hdr.count; i++) { + struct vfio_group *group; + struct fd f = fdget(group_fds[i]); + if (!f.file) { + ret = -EBADF; + break; + } + + group = vfio_group_get_external_user(f.file); + fdput(f); + if (IS_ERR(group)) { + ret = PTR_ERR(group); + break; + } + + groups[i].group = group; + groups[i].id = vfio_external_user_iommu_id(group); + } + + kfree(group_fds); + + /* release reference to groups on error */ + if (ret) + goto hot_reset_release; + + info.count = hdr.count; + info.groups = groups; + + /* + * Test whether all the affected devices are contained + * by the set of groups provided by the user. + */ + ret = vfio_pci_for_each_slot_or_bus(vdev->pdev, + vfio_pci_validate_devs, + &info, slot); + if (!ret) + /* User has access, do the reset */ + ret = slot ? pci_try_reset_slot(vdev->pdev->slot) : + pci_try_reset_bus(vdev->pdev->bus); + +hot_reset_release: + for (i--; i >= 0; i--) + vfio_group_put_external_user(groups[i].group); + + kfree(groups); + return ret; + } + + return -ENOTTY; +} +","@@ -829,32 +829,41 @@ static long vfio_pci_ioctl(void *device_data, + + } else if (cmd == VFIO_DEVICE_SET_IRQS) { + struct vfio_irq_set hdr; ++ size_t size; + u8 *data = NULL; +- int ret = 0; ++ int max, ret = 0; + + minsz = offsetofend(struct vfio_irq_set, count); + + if (copy_from_user(&hdr, (void __user *)arg, minsz)) + return -EFAULT; + + if (hdr.argsz < minsz || hdr.index >= VFIO_PCI_NUM_IRQS || ++ hdr.count >= (U32_MAX - hdr.start) || + hdr.flags & ~(VFIO_IRQ_SET_DATA_TYPE_MASK | + VFIO_IRQ_SET_ACTION_TYPE_MASK)) + return -EINVAL; + +- if (!(hdr.flags & VFIO_IRQ_SET_DATA_NONE)) { +- size_t size; +- int max = vfio_pci_get_irq_count(vdev, hdr.index); ++ max = vfio_pci_get_irq_count(vdev, hdr.index); ++ if (hdr.start >= max || hdr.start + hdr.count > max) ++ return -EINVAL; + +- if (hdr.flags & VFIO_IRQ_SET_DATA_BOOL) +- size = sizeof(uint8_t); +- else if (hdr.flags & VFIO_IRQ_SET_DATA_EVENTFD) +- size = sizeof(int32_t); +- else +- return -EINVAL; ++ switch (hdr.flags & VFIO_IRQ_SET_DATA_TYPE_MASK) { ++ case VFIO_IRQ_SET_DATA_NONE: ++ size = 0; ++ break; ++ case VFIO_IRQ_SET_DATA_BOOL: ++ size = sizeof(uint8_t); ++ break; ++ case VFIO_IRQ_SET_DATA_EVENTFD: ++ size = sizeof(int32_t); ++ break; ++ default: ++ return -EINVAL; ++ } + +- if (hdr.argsz - minsz < hdr.count * size || +- hdr.start >= max || hdr.start + hdr.count > max) ++ if (size) { ++ if (hdr.argsz - minsz < hdr.count * size) + return -EINVAL; + + data = memdup_user((void __user *)(arg + minsz),",3046,3377,4096 +36,"static inline void cached_cmyk_conv(unsigned char *restrict const pr, unsigned char *restrict const pg, unsigned char *restrict const pb, + unsigned int *restrict const C, unsigned int *restrict const M, unsigned int *restrict const Y, unsigned int *restrict const K, + unsigned int c, unsigned int m, unsigned int y, unsigned int k) +{ +#ifdef SLOWCMYK + unsigned int r, g, b; + unsigned int cm, c1m, cm1, c1m1, c1m1y, c1m1y1, c1my, c1my1, cm1y, cm1y1, cmy, cmy1; + unsigned int x0, x1; + + if (c == *C && m == *M && y == *Y && k == *K) + { + /* Nothing to do */ + } + else if (k == 0 && c == 0 && m == 0 && y == 0) + { + *C = 0; + *M = 0; + *Y = 0; + *K = 0; + *pr = *pg = *pb = 255; + } + else if (k == 255) + { + *C = 0; + *M = 0; + *Y = 0; + *K = 255; + *pr = *pg = *pb = 0; + } + else + { + *C = c; + *M = m; + *Y = y; + *K = k; + c += c>>7; + m += m>>7; + y += y>>7; + k += k>>7; + y >>= 1; /* Ditch 1 bit of Y to avoid overflow */ + cm = c * m; + c1m = (m<<8) - cm; + cm1 = (c<<8) - cm; + c1m1 = ((256 - m)<<8) - cm1; + c1m1y = c1m1 * y; + c1m1y1 = (c1m1<<7) - c1m1y; + c1my = c1m * y; + c1my1 = (c1m<<7) - c1my; + cm1y = cm1 * y; + cm1y1 = (cm1<<7) - cm1y; + cmy = cm * y; + cmy1 = (cm<<7) - cmy; + + /* this is a matrix multiplication, unrolled for performance */ + x1 = c1m1y1 * k; /* 0 0 0 1 */ + x0 = (c1m1y1<<8) - x1; /* 0 0 0 0 */ + x1 = x1>>8; /* From 23 fractional bits to 15 */ + r = g = b = x0; + r += 35 * x1; /* 0.1373f */ + g += 31 * x1; /* 0.1216f */ + b += 32 * x1; /* 0.1255f */ + + x1 = c1m1y * k; /* 0 0 1 1 */ + x0 = (c1m1y<<8) - x1; /* 0 0 1 0 */ + x1 >>= 8; /* From 23 fractional bits to 15 */ + r += 28 * x1; /* 0.1098f */ + g += 26 * x1; /* 0.1020f */ + r += x0; + x0 >>= 8; /* From 23 fractional bits to 15 */ + g += 243 * x0; /* 0.9490f */ + + x1 = c1my1 * k; /* 0 1 0 1 */ + x0 = (c1my1<<8) - x1; /* 0 1 0 0 */ + x1 >>= 8; /* From 23 fractional bits to 15 */ + x0 >>= 8; /* From 23 fractional bits to 15 */ + r += 36 * x1; /* 0.1412f */ + r += 237 * x0; /* 0.9255f */ + b += 141 * x0; /* 0.5490f */ + + x1 = c1my * k; /* 0 1 1 1 */ + x0 = (c1my<<8) - x1; /* 0 1 1 0 */ + x1 >>= 8; /* From 23 fractional bits to 15 */ + x0 >>= 8; /* From 23 fractional bits to 15 */ + r += 34 * x1; /* 0.1333f */ + r += 238 * x0; /* 0.9294f */ + g += 28 * x0; /* 0.1098f */ + b += 36 * x0; /* 0.1412f */ + + x1 = cm1y1 * k; /* 1 0 0 1 */ + x0 = (cm1y1<<8) - x1; /* 1 0 0 0 */ + x1 >>= 8; /* From 23 fractional bits to 15 */ + x0 >>= 8; /* From 23 fractional bits to 15 */ + g += 15 * x1; /* 0.0588f */ + b += 36 * x1; /* 0.1412f */ + g += 174 * x0; /* 0.6784f */ + b += 240 * x0; /* 0.9373f */ + + x1 = cm1y * k; /* 1 0 1 1 */ + x0 = (cm1y<<8) - x1; /* 1 0 1 0 */ + x1 >>= 8; /* From 23 fractional bits to 15 */ + x0 >>= 8; /* From 23 fractional bits to 15 */ + g += 19 * x1; /* 0.0745f */ + g += 167 * x0; /* 0.6510f */ + b += 80 * x0; /* 0.3137f */ + + x1 = cmy1 * k; /* 1 1 0 1 */ + x0 = (cmy1<<8) - x1; /* 1 1 0 0 */ + x1 >>= 8; /* From 23 fractional bits to 15 */ + x0 >>= 8; /* From 23 fractional bits to 15 */ + b += 2 * x1; /* 0.0078f */ + r += 46 * x0; /* 0.1804f */ + g += 49 * x0; /* 0.1922f */ + b += 147 * x0; /* 0.5725f */ + + x0 = cmy * (256-k); /* 1 1 1 0 */ + x0 >>= 8; /* From 23 fractional bits to 15 */ + r += 54 * x0; /* 0.2118f */ + g += 54 * x0; /* 0.2119f */ + b += 57 * x0; /* 0.2235f */ + + r -= (r>>8); + g -= (g>>8); + b -= (b>>8); + *pr = r>>23; + *pg = g>>23; + *pb = b>>23; + } +#else + *pr = 255 - (unsigned char)fz_mini(c + k, 255); + *pg = 255 - (unsigned char)fz_mini(m + k, 255); + *pb = 255 - (unsigned char)fz_mini(y + k, 255); +#endif +} +",0,"static inline void cached_cmyk_conv(unsigned char *restrict const pr, unsigned char *restrict const pg, unsigned char *restrict const pb, + unsigned int *restrict const C, unsigned int *restrict const M, unsigned int *restrict const Y, unsigned int *restrict const K, + unsigned int c, unsigned int m, unsigned int y, unsigned int k) +{ +#ifdef SLOWCMYK + unsigned int r, g, b; + unsigned int cm, c1m, cm1, c1m1, c1m1y, c1m1y1, c1my, c1my1, cm1y, cm1y1, cmy, cmy1; + unsigned int x0, x1; + + if (c == *C && m == *M && y == *Y && k == *K) + { + /* Nothing to do */ + } + else if (k == 0 && c == 0 && m == 0 && y == 0) + { + *C = 0; + *M = 0; + *Y = 0; + *K = 0; + *pr = *pg = *pb = 255; + } + else if (k == 255) + { + *C = 0; + *M = 0; + *Y = 0; + *K = 255; + *pr = *pg = *pb = 0; + } + else + { + *C = c; + *M = m; + *Y = y; + *K = k; + c += c>>7; + m += m>>7; + y += y>>7; + k += k>>7; + y >>= 1; /* Ditch 1 bit of Y to avoid overflow */ + cm = c * m; + c1m = (m<<8) - cm; + cm1 = (c<<8) - cm; + c1m1 = ((256 - m)<<8) - cm1; + c1m1y = c1m1 * y; + c1m1y1 = (c1m1<<7) - c1m1y; + c1my = c1m * y; + c1my1 = (c1m<<7) - c1my; + cm1y = cm1 * y; + cm1y1 = (cm1<<7) - cm1y; + cmy = cm * y; + cmy1 = (cm<<7) - cmy; + + /* this is a matrix multiplication, unrolled for performance */ + x1 = c1m1y1 * k; /* 0 0 0 1 */ + x0 = (c1m1y1<<8) - x1; /* 0 0 0 0 */ + x1 = x1>>8; /* From 23 fractional bits to 15 */ + r = g = b = x0; + r += 35 * x1; /* 0.1373f */ + g += 31 * x1; /* 0.1216f */ + b += 32 * x1; /* 0.1255f */ + + x1 = c1m1y * k; /* 0 0 1 1 */ + x0 = (c1m1y<<8) - x1; /* 0 0 1 0 */ + x1 >>= 8; /* From 23 fractional bits to 15 */ + r += 28 * x1; /* 0.1098f */ + g += 26 * x1; /* 0.1020f */ + r += x0; + x0 >>= 8; /* From 23 fractional bits to 15 */ + g += 243 * x0; /* 0.9490f */ + + x1 = c1my1 * k; /* 0 1 0 1 */ + x0 = (c1my1<<8) - x1; /* 0 1 0 0 */ + x1 >>= 8; /* From 23 fractional bits to 15 */ + x0 >>= 8; /* From 23 fractional bits to 15 */ + r += 36 * x1; /* 0.1412f */ + r += 237 * x0; /* 0.9255f */ + b += 141 * x0; /* 0.5490f */ + + x1 = c1my * k; /* 0 1 1 1 */ + x0 = (c1my<<8) - x1; /* 0 1 1 0 */ + x1 >>= 8; /* From 23 fractional bits to 15 */ + x0 >>= 8; /* From 23 fractional bits to 15 */ + r += 34 * x1; /* 0.1333f */ + r += 238 * x0; /* 0.9294f */ + g += 28 * x0; /* 0.1098f */ + b += 36 * x0; /* 0.1412f */ + + x1 = cm1y1 * k; /* 1 0 0 1 */ + x0 = (cm1y1<<8) - x1; /* 1 0 0 0 */ + x1 >>= 8; /* From 23 fractional bits to 15 */ + x0 >>= 8; /* From 23 fractional bits to 15 */ + g += 15 * x1; /* 0.0588f */ + b += 36 * x1; /* 0.1412f */ + g += 174 * x0; /* 0.6784f */ + b += 240 * x0; /* 0.9373f */ + + x1 = cm1y * k; /* 1 0 1 1 */ + x0 = (cm1y<<8) - x1; /* 1 0 1 0 */ + x1 >>= 8; /* From 23 fractional bits to 15 */ + x0 >>= 8; /* From 23 fractional bits to 15 */ + g += 19 * x1; /* 0.0745f */ + g += 167 * x0; /* 0.6510f */ + b += 80 * x0; /* 0.3137f */ + + x1 = cmy1 * k; /* 1 1 0 1 */ + x0 = (cmy1<<8) - x1; /* 1 1 0 0 */ + x1 >>= 8; /* From 23 fractional bits to 15 */ + x0 >>= 8; /* From 23 fractional bits to 15 */ + b += 2 * x1; /* 0.0078f */ + r += 46 * x0; /* 0.1804f */ + g += 49 * x0; /* 0.1922f */ + b += 147 * x0; /* 0.5725f */ + + x0 = cmy * (256-k); /* 1 1 1 0 */ + x0 >>= 8; /* From 23 fractional bits to 15 */ + r += 54 * x0; /* 0.2118f */ + g += 54 * x0; /* 0.2119f */ + b += 57 * x0; /* 0.2235f */ + + r -= (r>>8); + g -= (g>>8); + b -= (b>>8); + *pr = r>>23; + *pg = g>>23; + *pb = b>>23; + } +#else + *pr = 255 - (unsigned char)fz_mini(c + k, 255); + *pg = 255 - (unsigned char)fz_mini(m + k, 255); + *pb = 255 - (unsigned char)fz_mini(y + k, 255); +#endif +} +","@@ -3663,6 +3663,7 @@ void fz_init_cached_color_converter(fz_context *ctx, fz_color_converter *cc, fz_ + fz_drop_color_converter(ctx, &cached->base); + fz_drop_hash_table(ctx, cached->hash); + fz_free(ctx, cached); ++ cc->opaque = NULL; + fz_rethrow(ctx); + } + }",1965,2296,4096 +2266,"raptor_rdfxml_start_element_handler(void *user_data, + raptor_xml_element* xml_element) +{ + raptor_parser* rdf_parser; + raptor_rdfxml_parser* rdf_xml_parser; + raptor_rdfxml_element* element; + int ns_attributes_count = 0; + raptor_qname** named_attrs = NULL; + int i; + int count_bumped = 0; + + rdf_parser = (raptor_parser*)user_data; + rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context; + + if(rdf_parser->failed) + return; + + raptor_rdfxml_update_document_locator(rdf_parser); + + /* Create new element structure */ + element = RAPTOR_CALLOC(raptor_rdfxml_element*, 1, sizeof(*element)); + if(!element) { + raptor_parser_fatal_error(rdf_parser, ""Out of memory""); + rdf_parser->failed = 1; + return; + } + element->world = rdf_parser->world; + element->xml_element = xml_element; + + raptor_rdfxml_element_push(rdf_xml_parser, element); + + named_attrs = raptor_xml_element_get_attributes(xml_element); + ns_attributes_count = raptor_xml_element_get_attributes_count(xml_element); + + /* RDF-specific processing of attributes */ + if(ns_attributes_count) { + raptor_qname** new_named_attrs; + int offset = 0; + raptor_rdfxml_element* parent_element; + + parent_element = element->parent; + + /* Allocate new array to move namespaced-attributes to if + * rdf processing is performed + */ + new_named_attrs = RAPTOR_CALLOC(raptor_qname**, ns_attributes_count, + sizeof(raptor_qname*)); + if(!new_named_attrs) { + raptor_parser_fatal_error(rdf_parser, ""Out of memory""); + rdf_parser->failed = 1; + return; + } + + for(i = 0; i < ns_attributes_count; i++) { + raptor_qname* attr = named_attrs[i]; + + /* If: + * 1 We are handling RDF content and RDF processing is allowed on + * this element + * OR + * 2 We are not handling RDF content and + * this element is at the top level (top level Desc. / typedNode) + * i.e. we have no parent + * then handle the RDF attributes + */ + if((parent_element && + rdf_content_type_info[parent_element->child_content_type].rdf_processing) || + !parent_element) { + + /* Save pointers to some RDF M&S attributes */ + + /* If RDF namespace-prefixed attributes */ + if(attr->nspace && attr->nspace->is_rdf_ms) { + const unsigned char *attr_name = attr->local_name; + int j; + + for(j = 0; j <= RDF_NS_LAST; j++) + if(!strcmp((const char*)attr_name, + raptor_rdf_ns_terms_info[j].name)) { + element->rdf_attr[j] = attr->value; + element->rdf_attr_count++; + /* Delete it if it was stored elsewhere */ +#ifdef RAPTOR_DEBUG_VERBOSE + RAPTOR_DEBUG3(""Found RDF namespace attribute '%s' URI %s\n"", + (char*)attr_name, attr->value); +#endif + /* make sure value isn't deleted from qname structure */ + attr->value = NULL; + raptor_free_qname(attr); + attr = NULL; + break; + } + } /* end if RDF namespaced-prefixed attributes */ + + if(!attr) + continue; + + /* If non namespace-prefixed RDF attributes found on an element */ + if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES) && + !attr->nspace) { + const unsigned char *attr_name = attr->local_name; + int j; + + for(j = 0; j <= RDF_NS_LAST; j++) + if(!strcmp((const char*)attr_name, + raptor_rdf_ns_terms_info[j].name)) { + element->rdf_attr[j] = attr->value; + element->rdf_attr_count++; + if(!raptor_rdf_ns_terms_info[j].allowed_unprefixed_on_attribute) + raptor_parser_warning(rdf_parser, + ""Using rdf attribute '%s' without the RDF namespace has been deprecated."", + attr_name); + + /* Delete it if it was stored elsewhere */ + /* make sure value isn't deleted from qname structure */ + attr->value = NULL; + raptor_free_qname(attr); + attr = NULL; + break; + } + } /* end if non-namespace prefixed RDF attributes */ + + if(!attr) + continue; + + } /* end if leave literal XML alone */ + + if(attr) + new_named_attrs[offset++] = attr; + } + + /* new attribute count is set from attributes that haven't been skipped */ + ns_attributes_count = offset; + if(!ns_attributes_count) { + /* all attributes were deleted so delete the new array */ + RAPTOR_FREE(raptor_qname_array, new_named_attrs); + new_named_attrs = NULL; + } + + RAPTOR_FREE(raptor_qname_array, named_attrs); + named_attrs = new_named_attrs; + raptor_xml_element_set_attributes(xml_element, + named_attrs, ns_attributes_count); + } /* end if ns_attributes_count */ + + + /* start from unknown; if we have a parent, it may set this */ + element->state = RAPTOR_STATE_UNKNOWN; + element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_UNKNOWN; + + if(element->parent && + element->parent->child_content_type != RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_UNKNOWN) { + element->content_type = element->parent->child_content_type; + + if(element->parent->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE && + element->content_type != RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_COLLECTION && + element->content_type != RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION) { + raptor_qname* parent_el_name; + parent_el_name = raptor_xml_element_get_name(element->parent->xml_element); + /* If parent has an rdf:resource, this element should not be here */ + raptor_parser_error(rdf_parser, + ""property element '%s' has multiple object node elements, skipping."", + parent_el_name->local_name); + element->state = RAPTOR_STATE_SKIPPING; + element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PRESERVED; + + } else { + if(!element->parent->child_state) { + raptor_parser_fatal_error(rdf_parser, + ""%s: Internal error: no parent element child_state set"", + __func__); + return; + } + + element->state = element->parent->child_state; + element->parent->xml_element->content_element_seen++; + count_bumped++; + + /* leave literal XML alone */ + if(!rdf_content_type_info[element->content_type].cdata_allowed) { + if(element->parent->xml_element->content_element_seen && + element->parent->xml_element->content_cdata_seen) { + raptor_qname* parent_el_name; + + parent_el_name = raptor_xml_element_get_name(element->parent->xml_element); + /* Uh oh - mixed content, the parent element has cdata too */ + raptor_parser_warning(rdf_parser, ""element '%s' has mixed content."", + parent_el_name->local_name); + } + + /* If there is some existing all-whitespace content cdata + * before this node element, delete it + */ + if(element->parent->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTIES && + element->parent->xml_element->content_element_seen && + element->parent->content_cdata_all_whitespace && + element->parent->xml_element->content_cdata_length) { + + element->parent->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE; + + raptor_free_stringbuffer(element->parent->xml_element->content_cdata_sb); + element->parent->xml_element->content_cdata_sb = NULL; + element->parent->xml_element->content_cdata_length = 0; + } + + } /* end if leave literal XML alone */ + + } /* end if parent has no rdf:resource */ + + } /* end if element->parent */ + + +#ifdef RAPTOR_DEBUG_VERBOSE + RAPTOR_DEBUG2(""Using content type %s\n"", + rdf_content_type_info[element->content_type].name); + + fprintf(stderr, ""raptor_rdfxml_start_element_handler: Start ns-element: ""); + raptor_print_xml_element(xml_element, stderr); +#endif + + + /* Check for non namespaced stuff when not in a parseType literal, other */ + if(rdf_content_type_info[element->content_type].rdf_processing) { + const raptor_namespace* ns; + + ns = raptor_xml_element_get_name(xml_element)->nspace; + /* The element */ + + /* If has no namespace or the namespace has no name (xmlns="""") */ + if((!ns || (ns && !raptor_namespace_get_uri(ns))) && element->parent) { + raptor_qname* parent_el_name; + + parent_el_name = raptor_xml_element_get_name(element->parent->xml_element); + + raptor_parser_error(rdf_parser, + ""Using an element '%s' without a namespace is forbidden."", + parent_el_name->local_name); + element->state = RAPTOR_STATE_SKIPPING; + /* Remove count above so that parent thinks this is empty */ + if(count_bumped) + element->parent->xml_element->content_element_seen--; + element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PRESERVED; + } + + + /* Check for any remaining non-namespaced attributes */ + if(named_attrs) { + for(i = 0; i < ns_attributes_count; i++) { + raptor_qname *attr = named_attrs[i]; + /* Check if any attributes are non-namespaced */ + if(!attr->nspace || + (attr->nspace && !raptor_namespace_get_uri(attr->nspace))) { + raptor_parser_error(rdf_parser, + ""Using an attribute '%s' without a namespace is forbidden."", + attr->local_name); + raptor_free_qname(attr); + named_attrs[i] = NULL; + } + } + } + } + + + if(element->rdf_attr[RDF_NS_aboutEach] || + element->rdf_attr[RDF_NS_aboutEachPrefix]) { + raptor_parser_warning(rdf_parser, + ""element '%s' has aboutEach / aboutEachPrefix, skipping."", + raptor_xml_element_get_name(xml_element)->local_name); + element->state = RAPTOR_STATE_SKIPPING; + /* Remove count above so that parent thinks this is empty */ + if(count_bumped) + element->parent->xml_element->content_element_seen--; + element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PRESERVED; + } + + /* Right, now ready to enter the grammar */ + raptor_rdfxml_start_element_grammar(rdf_parser, element); + + return; +} +",0,"raptor_rdfxml_start_element_handler(void *user_data, + raptor_xml_element* xml_element) +{ + raptor_parser* rdf_parser; + raptor_rdfxml_parser* rdf_xml_parser; + raptor_rdfxml_element* element; + int ns_attributes_count = 0; + raptor_qname** named_attrs = NULL; + int i; + int count_bumped = 0; + + rdf_parser = (raptor_parser*)user_data; + rdf_xml_parser = (raptor_rdfxml_parser*)rdf_parser->context; + + if(rdf_parser->failed) + return; + + raptor_rdfxml_update_document_locator(rdf_parser); + + /* Create new element structure */ + element = RAPTOR_CALLOC(raptor_rdfxml_element*, 1, sizeof(*element)); + if(!element) { + raptor_parser_fatal_error(rdf_parser, ""Out of memory""); + rdf_parser->failed = 1; + return; + } + element->world = rdf_parser->world; + element->xml_element = xml_element; + + raptor_rdfxml_element_push(rdf_xml_parser, element); + + named_attrs = raptor_xml_element_get_attributes(xml_element); + ns_attributes_count = raptor_xml_element_get_attributes_count(xml_element); + + /* RDF-specific processing of attributes */ + if(ns_attributes_count) { + raptor_qname** new_named_attrs; + int offset = 0; + raptor_rdfxml_element* parent_element; + + parent_element = element->parent; + + /* Allocate new array to move namespaced-attributes to if + * rdf processing is performed + */ + new_named_attrs = RAPTOR_CALLOC(raptor_qname**, ns_attributes_count, + sizeof(raptor_qname*)); + if(!new_named_attrs) { + raptor_parser_fatal_error(rdf_parser, ""Out of memory""); + rdf_parser->failed = 1; + return; + } + + for(i = 0; i < ns_attributes_count; i++) { + raptor_qname* attr = named_attrs[i]; + + /* If: + * 1 We are handling RDF content and RDF processing is allowed on + * this element + * OR + * 2 We are not handling RDF content and + * this element is at the top level (top level Desc. / typedNode) + * i.e. we have no parent + * then handle the RDF attributes + */ + if((parent_element && + rdf_content_type_info[parent_element->child_content_type].rdf_processing) || + !parent_element) { + + /* Save pointers to some RDF M&S attributes */ + + /* If RDF namespace-prefixed attributes */ + if(attr->nspace && attr->nspace->is_rdf_ms) { + const unsigned char *attr_name = attr->local_name; + int j; + + for(j = 0; j <= RDF_NS_LAST; j++) + if(!strcmp((const char*)attr_name, + raptor_rdf_ns_terms_info[j].name)) { + element->rdf_attr[j] = attr->value; + element->rdf_attr_count++; + /* Delete it if it was stored elsewhere */ +#ifdef RAPTOR_DEBUG_VERBOSE + RAPTOR_DEBUG3(""Found RDF namespace attribute '%s' URI %s\n"", + (char*)attr_name, attr->value); +#endif + /* make sure value isn't deleted from qname structure */ + attr->value = NULL; + raptor_free_qname(attr); + attr = NULL; + break; + } + } /* end if RDF namespaced-prefixed attributes */ + + if(!attr) + continue; + + /* If non namespace-prefixed RDF attributes found on an element */ + if(RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES) && + !attr->nspace) { + const unsigned char *attr_name = attr->local_name; + int j; + + for(j = 0; j <= RDF_NS_LAST; j++) + if(!strcmp((const char*)attr_name, + raptor_rdf_ns_terms_info[j].name)) { + element->rdf_attr[j] = attr->value; + element->rdf_attr_count++; + if(!raptor_rdf_ns_terms_info[j].allowed_unprefixed_on_attribute) + raptor_parser_warning(rdf_parser, + ""Using rdf attribute '%s' without the RDF namespace has been deprecated."", + attr_name); + + /* Delete it if it was stored elsewhere */ + /* make sure value isn't deleted from qname structure */ + attr->value = NULL; + raptor_free_qname(attr); + attr = NULL; + break; + } + } /* end if non-namespace prefixed RDF attributes */ + + if(!attr) + continue; + + } /* end if leave literal XML alone */ + + if(attr) + new_named_attrs[offset++] = attr; + } + + /* new attribute count is set from attributes that haven't been skipped */ + ns_attributes_count = offset; + if(!ns_attributes_count) { + /* all attributes were deleted so delete the new array */ + RAPTOR_FREE(raptor_qname_array, new_named_attrs); + new_named_attrs = NULL; + } + + RAPTOR_FREE(raptor_qname_array, named_attrs); + named_attrs = new_named_attrs; + raptor_xml_element_set_attributes(xml_element, + named_attrs, ns_attributes_count); + } /* end if ns_attributes_count */ + + + /* start from unknown; if we have a parent, it may set this */ + element->state = RAPTOR_STATE_UNKNOWN; + element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_UNKNOWN; + + if(element->parent && + element->parent->child_content_type != RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_UNKNOWN) { + element->content_type = element->parent->child_content_type; + + if(element->parent->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE && + element->content_type != RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_COLLECTION && + element->content_type != RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_DAML_COLLECTION) { + raptor_qname* parent_el_name; + parent_el_name = raptor_xml_element_get_name(element->parent->xml_element); + /* If parent has an rdf:resource, this element should not be here */ + raptor_parser_error(rdf_parser, + ""property element '%s' has multiple object node elements, skipping."", + parent_el_name->local_name); + element->state = RAPTOR_STATE_SKIPPING; + element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PRESERVED; + + } else { + if(!element->parent->child_state) { + raptor_parser_fatal_error(rdf_parser, + ""%s: Internal error: no parent element child_state set"", + __func__); + return; + } + + element->state = element->parent->child_state; + element->parent->xml_element->content_element_seen++; + count_bumped++; + + /* leave literal XML alone */ + if(!rdf_content_type_info[element->content_type].cdata_allowed) { + if(element->parent->xml_element->content_element_seen && + element->parent->xml_element->content_cdata_seen) { + raptor_qname* parent_el_name; + + parent_el_name = raptor_xml_element_get_name(element->parent->xml_element); + /* Uh oh - mixed content, the parent element has cdata too */ + raptor_parser_warning(rdf_parser, ""element '%s' has mixed content."", + parent_el_name->local_name); + } + + /* If there is some existing all-whitespace content cdata + * before this node element, delete it + */ + if(element->parent->content_type == RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PROPERTIES && + element->parent->xml_element->content_element_seen && + element->parent->content_cdata_all_whitespace && + element->parent->xml_element->content_cdata_length) { + + element->parent->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_RESOURCE; + + raptor_free_stringbuffer(element->parent->xml_element->content_cdata_sb); + element->parent->xml_element->content_cdata_sb = NULL; + element->parent->xml_element->content_cdata_length = 0; + } + + } /* end if leave literal XML alone */ + + } /* end if parent has no rdf:resource */ + + } /* end if element->parent */ + + +#ifdef RAPTOR_DEBUG_VERBOSE + RAPTOR_DEBUG2(""Using content type %s\n"", + rdf_content_type_info[element->content_type].name); + + fprintf(stderr, ""raptor_rdfxml_start_element_handler: Start ns-element: ""); + raptor_print_xml_element(xml_element, stderr); +#endif + + + /* Check for non namespaced stuff when not in a parseType literal, other */ + if(rdf_content_type_info[element->content_type].rdf_processing) { + const raptor_namespace* ns; + + ns = raptor_xml_element_get_name(xml_element)->nspace; + /* The element */ + + /* If has no namespace or the namespace has no name (xmlns="""") */ + if((!ns || (ns && !raptor_namespace_get_uri(ns))) && element->parent) { + raptor_qname* parent_el_name; + + parent_el_name = raptor_xml_element_get_name(element->parent->xml_element); + + raptor_parser_error(rdf_parser, + ""Using an element '%s' without a namespace is forbidden."", + parent_el_name->local_name); + element->state = RAPTOR_STATE_SKIPPING; + /* Remove count above so that parent thinks this is empty */ + if(count_bumped) + element->parent->xml_element->content_element_seen--; + element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PRESERVED; + } + + + /* Check for any remaining non-namespaced attributes */ + if(named_attrs) { + for(i = 0; i < ns_attributes_count; i++) { + raptor_qname *attr = named_attrs[i]; + /* Check if any attributes are non-namespaced */ + if(!attr->nspace || + (attr->nspace && !raptor_namespace_get_uri(attr->nspace))) { + raptor_parser_error(rdf_parser, + ""Using an attribute '%s' without a namespace is forbidden."", + attr->local_name); + raptor_free_qname(attr); + named_attrs[i] = NULL; + } + } + } + } + + + if(element->rdf_attr[RDF_NS_aboutEach] || + element->rdf_attr[RDF_NS_aboutEachPrefix]) { + raptor_parser_warning(rdf_parser, + ""element '%s' has aboutEach / aboutEachPrefix, skipping."", + raptor_xml_element_get_name(xml_element)->local_name); + element->state = RAPTOR_STATE_SKIPPING; + /* Remove count above so that parent thinks this is empty */ + if(count_bumped) + element->parent->xml_element->content_element_seen--; + element->content_type = RAPTOR_RDFXML_ELEMENT_CONTENT_TYPE_PRESERVED; + } + + /* Right, now ready to enter the grammar */ + raptor_rdfxml_start_element_grammar(rdf_parser, element); + + return; +} +","@@ -1004,6 +1004,9 @@ raptor_rdfxml_parse_start(raptor_parser* rdf_parser) + raptor_sax2_set_option(rdf_xml_parser->sax2, + RAPTOR_OPTION_NO_FILE, NULL, + RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE)); ++ raptor_sax2_set_option(rdf_xml_parser->sax2, ++ RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES, NULL, ++ RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES)); + if(rdf_parser->uri_filter) + raptor_sax2_set_uri_filter(rdf_xml_parser->sax2, rdf_parser->uri_filter, + rdf_parser->uri_filter_user_data);",2385,2716,4096 +18789,"status_t BnOMX::onTransact( + uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) { + switch (code) { + case LIVES_LOCALLY: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + node_id node = (node_id)data.readInt32(); + pid_t pid = (pid_t)data.readInt32(); + reply->writeInt32(livesLocally(node, pid)); + + return OK; + } + + case LIST_NODES: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + List list; + listNodes(&list); + + reply->writeInt32(list.size()); + for (List::iterator it = list.begin(); + it != list.end(); ++it) { + ComponentInfo &cur = *it; + + reply->writeString8(cur.mName); + reply->writeInt32(cur.mRoles.size()); + for (List::iterator role_it = cur.mRoles.begin(); + role_it != cur.mRoles.end(); ++role_it) { + reply->writeString8(*role_it); + } + } + + return NO_ERROR; + } + + case ALLOCATE_NODE: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + const char *name = data.readCString(); + + sp observer = + interface_cast(data.readStrongBinder()); + + node_id node; + + status_t err = allocateNode(name, observer, &node); + reply->writeInt32(err); + if (err == OK) { + reply->writeInt32((int32_t)node); + } + + return NO_ERROR; + } + + case FREE_NODE: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + + reply->writeInt32(freeNode(node)); + + return NO_ERROR; + } + + case SEND_COMMAND: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + + OMX_COMMANDTYPE cmd = + static_cast(data.readInt32()); + + OMX_S32 param = data.readInt32(); + reply->writeInt32(sendCommand(node, cmd, param)); + + return NO_ERROR; + } + + case GET_PARAMETER: + case SET_PARAMETER: + case GET_CONFIG: + case SET_CONFIG: + case SET_INTERNAL_OPTION: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_INDEXTYPE index = static_cast(data.readInt32()); + + size_t size = data.readInt64(); + + void *params = malloc(size); + data.read(params, size); + + status_t err; + switch (code) { + case GET_PARAMETER: + err = getParameter(node, index, params, size); + break; + case SET_PARAMETER: + err = setParameter(node, index, params, size); + break; + case GET_CONFIG: + err = getConfig(node, index, params, size); + break; + case SET_CONFIG: + err = setConfig(node, index, params, size); + break; + case SET_INTERNAL_OPTION: + { + InternalOptionType type = + (InternalOptionType)data.readInt32(); + + err = setInternalOption(node, index, type, params, size); + break; + } + + default: + TRESPASS(); + } + + reply->writeInt32(err); + + if ((code == GET_PARAMETER || code == GET_CONFIG) && err == OK) { + reply->write(params, size); + } + + free(params); + params = NULL; + + return NO_ERROR; + } + + case GET_STATE: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_STATETYPE state = OMX_StateInvalid; + + status_t err = getState(node, &state); + reply->writeInt32(state); + reply->writeInt32(err); + + return NO_ERROR; + } + + case ENABLE_GRAPHIC_BUFFERS: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + OMX_BOOL enable = (OMX_BOOL)data.readInt32(); + + status_t err = enableGraphicBuffers(node, port_index, enable); + reply->writeInt32(err); + + return NO_ERROR; + } + + case GET_GRAPHIC_BUFFER_USAGE: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + + OMX_U32 usage = 0; + status_t err = getGraphicBufferUsage(node, port_index, &usage); + reply->writeInt32(err); + reply->writeInt32(usage); + + return NO_ERROR; + } + + case USE_BUFFER: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + sp params = + interface_cast(data.readStrongBinder()); + + buffer_id buffer; + status_t err = useBuffer(node, port_index, params, &buffer); + reply->writeInt32(err); + + if (err == OK) { + reply->writeInt32((int32_t)buffer); + } + + return NO_ERROR; + } + + case USE_GRAPHIC_BUFFER: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + sp graphicBuffer = new GraphicBuffer(); + data.read(*graphicBuffer); + + buffer_id buffer; + status_t err = useGraphicBuffer( + node, port_index, graphicBuffer, &buffer); + reply->writeInt32(err); + + if (err == OK) { + reply->writeInt32((int32_t)buffer); + } + + return NO_ERROR; + } + + case UPDATE_GRAPHIC_BUFFER_IN_META: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + sp graphicBuffer = new GraphicBuffer(); + data.read(*graphicBuffer); + buffer_id buffer = (buffer_id)data.readInt32(); + + status_t err = updateGraphicBufferInMeta( + node, port_index, graphicBuffer, buffer); + reply->writeInt32(err); + + return NO_ERROR; + } + + case CREATE_INPUT_SURFACE: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + + sp bufferProducer; + status_t err = createInputSurface(node, port_index, + &bufferProducer); + + reply->writeInt32(err); + + if (err == OK) { + reply->writeStrongBinder(bufferProducer->asBinder()); + } + + return NO_ERROR; + } + + case SIGNAL_END_OF_INPUT_STREAM: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + + status_t err = signalEndOfInputStream(node); + reply->writeInt32(err); + + return NO_ERROR; + } + + case STORE_META_DATA_IN_BUFFERS: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + OMX_BOOL enable = (OMX_BOOL)data.readInt32(); + + status_t err = storeMetaDataInBuffers(node, port_index, enable); + reply->writeInt32(err); + + return NO_ERROR; + } + + case PREPARE_FOR_ADAPTIVE_PLAYBACK: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + OMX_BOOL enable = (OMX_BOOL)data.readInt32(); + OMX_U32 max_width = data.readInt32(); + OMX_U32 max_height = data.readInt32(); + + status_t err = prepareForAdaptivePlayback( + node, port_index, enable, max_width, max_height); + reply->writeInt32(err); + + return NO_ERROR; + } + + case CONFIGURE_VIDEO_TUNNEL_MODE: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + + OMX_BOOL tunneled = (OMX_BOOL)data.readInt32(); + OMX_U32 audio_hw_sync = data.readInt32(); + + native_handle_t *sideband_handle; + status_t err = configureVideoTunnelMode( + node, port_index, tunneled, audio_hw_sync, &sideband_handle); + reply->writeInt32(err); + reply->writeNativeHandle(sideband_handle); + + return NO_ERROR; + } + + case ALLOC_BUFFER: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + if (!isSecure(node) || port_index != 0 /* kPortIndexInput */) { + ALOGE(""b/24310423""); + reply->writeInt32(INVALID_OPERATION); + return NO_ERROR; + } + + size_t size = data.readInt64(); + + buffer_id buffer; + void *buffer_data; + status_t err = allocateBuffer( + node, port_index, size, &buffer, &buffer_data); + reply->writeInt32(err); + + if (err == OK) { + reply->writeInt32((int32_t)buffer); + reply->writeInt64((uintptr_t)buffer_data); + } + + return NO_ERROR; + } + + case ALLOC_BUFFER_WITH_BACKUP: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + sp params = + interface_cast(data.readStrongBinder()); + + buffer_id buffer; + status_t err = allocateBufferWithBackup( + node, port_index, params, &buffer); + + reply->writeInt32(err); + + if (err == OK) { + reply->writeInt32((int32_t)buffer); + } + + return NO_ERROR; + } + + case FREE_BUFFER: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + buffer_id buffer = (buffer_id)data.readInt32(); + reply->writeInt32(freeBuffer(node, port_index, buffer)); + + return NO_ERROR; + } + + case FILL_BUFFER: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + buffer_id buffer = (buffer_id)data.readInt32(); + reply->writeInt32(fillBuffer(node, buffer)); + + return NO_ERROR; + } + + case EMPTY_BUFFER: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + buffer_id buffer = (buffer_id)data.readInt32(); + OMX_U32 range_offset = data.readInt32(); + OMX_U32 range_length = data.readInt32(); + OMX_U32 flags = data.readInt32(); + OMX_TICKS timestamp = data.readInt64(); + + reply->writeInt32( + emptyBuffer( + node, buffer, range_offset, range_length, + flags, timestamp)); + + return NO_ERROR; + } + + case GET_EXTENSION_INDEX: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + const char *parameter_name = data.readCString(); + + OMX_INDEXTYPE index; + status_t err = getExtensionIndex(node, parameter_name, &index); + + reply->writeInt32(err); + + if (err == OK) { + reply->writeInt32(index); + } + + return OK; + } + + default: + return BBinder::onTransact(code, data, reply, flags); + } +} +",1,"status_t BnOMX::onTransact( + uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) { + switch (code) { + case LIVES_LOCALLY: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + node_id node = (node_id)data.readInt32(); + pid_t pid = (pid_t)data.readInt32(); + reply->writeInt32(livesLocally(node, pid)); + + return OK; + } + + case LIST_NODES: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + List list; + listNodes(&list); + + reply->writeInt32(list.size()); + for (List::iterator it = list.begin(); + it != list.end(); ++it) { + ComponentInfo &cur = *it; + + reply->writeString8(cur.mName); + reply->writeInt32(cur.mRoles.size()); + for (List::iterator role_it = cur.mRoles.begin(); + role_it != cur.mRoles.end(); ++role_it) { + reply->writeString8(*role_it); + } + } + + return NO_ERROR; + } + + case ALLOCATE_NODE: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + const char *name = data.readCString(); + + sp observer = + interface_cast(data.readStrongBinder()); + + node_id node; + + status_t err = allocateNode(name, observer, &node); + reply->writeInt32(err); + if (err == OK) { + reply->writeInt32((int32_t)node); + } + + return NO_ERROR; + } + + case FREE_NODE: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + + reply->writeInt32(freeNode(node)); + + return NO_ERROR; + } + + case SEND_COMMAND: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + + OMX_COMMANDTYPE cmd = + static_cast(data.readInt32()); + + OMX_S32 param = data.readInt32(); + reply->writeInt32(sendCommand(node, cmd, param)); + + return NO_ERROR; + } + + case GET_PARAMETER: + case SET_PARAMETER: + case GET_CONFIG: + case SET_CONFIG: + case SET_INTERNAL_OPTION: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_INDEXTYPE index = static_cast(data.readInt32()); + + size_t size = data.readInt64(); + + void *params = malloc(size); + data.read(params, size); + + status_t err; + switch (code) { + case GET_PARAMETER: + err = getParameter(node, index, params, size); + break; + case SET_PARAMETER: + err = setParameter(node, index, params, size); + break; + case GET_CONFIG: + err = getConfig(node, index, params, size); + break; + case SET_CONFIG: + err = setConfig(node, index, params, size); + break; + case SET_INTERNAL_OPTION: + { + InternalOptionType type = + (InternalOptionType)data.readInt32(); + + err = setInternalOption(node, index, type, params, size); + break; + } + + default: + TRESPASS(); + } + + reply->writeInt32(err); + + if ((code == GET_PARAMETER || code == GET_CONFIG) && err == OK) { + reply->write(params, size); + } + + free(params); + params = NULL; + + return NO_ERROR; + } + + case GET_STATE: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_STATETYPE state = OMX_StateInvalid; + + status_t err = getState(node, &state); + reply->writeInt32(state); + reply->writeInt32(err); + + return NO_ERROR; + } + + case ENABLE_GRAPHIC_BUFFERS: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + OMX_BOOL enable = (OMX_BOOL)data.readInt32(); + + status_t err = enableGraphicBuffers(node, port_index, enable); + reply->writeInt32(err); + + return NO_ERROR; + } + + case GET_GRAPHIC_BUFFER_USAGE: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + + OMX_U32 usage = 0; + status_t err = getGraphicBufferUsage(node, port_index, &usage); + reply->writeInt32(err); + reply->writeInt32(usage); + + return NO_ERROR; + } + + case USE_BUFFER: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + sp params = + interface_cast(data.readStrongBinder()); + + buffer_id buffer; + status_t err = useBuffer(node, port_index, params, &buffer); + reply->writeInt32(err); + + if (err == OK) { + reply->writeInt32((int32_t)buffer); + } + + return NO_ERROR; + } + + case USE_GRAPHIC_BUFFER: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + sp graphicBuffer = new GraphicBuffer(); + data.read(*graphicBuffer); + + buffer_id buffer; + status_t err = useGraphicBuffer( + node, port_index, graphicBuffer, &buffer); + reply->writeInt32(err); + + if (err == OK) { + reply->writeInt32((int32_t)buffer); + } + + return NO_ERROR; + } + + case UPDATE_GRAPHIC_BUFFER_IN_META: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + sp graphicBuffer = new GraphicBuffer(); + data.read(*graphicBuffer); + buffer_id buffer = (buffer_id)data.readInt32(); + + status_t err = updateGraphicBufferInMeta( + node, port_index, graphicBuffer, buffer); + reply->writeInt32(err); + + return NO_ERROR; + } + + case CREATE_INPUT_SURFACE: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + + sp bufferProducer; + status_t err = createInputSurface(node, port_index, + &bufferProducer); + + reply->writeInt32(err); + + if (err == OK) { + reply->writeStrongBinder(bufferProducer->asBinder()); + } + + return NO_ERROR; + } + + case SIGNAL_END_OF_INPUT_STREAM: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + + status_t err = signalEndOfInputStream(node); + reply->writeInt32(err); + + return NO_ERROR; + } + + case STORE_META_DATA_IN_BUFFERS: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + OMX_BOOL enable = (OMX_BOOL)data.readInt32(); + + status_t err = storeMetaDataInBuffers(node, port_index, enable); + reply->writeInt32(err); + + return NO_ERROR; + } + + case PREPARE_FOR_ADAPTIVE_PLAYBACK: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + OMX_BOOL enable = (OMX_BOOL)data.readInt32(); + OMX_U32 max_width = data.readInt32(); + OMX_U32 max_height = data.readInt32(); + + status_t err = prepareForAdaptivePlayback( + node, port_index, enable, max_width, max_height); + reply->writeInt32(err); + + return NO_ERROR; + } + + case CONFIGURE_VIDEO_TUNNEL_MODE: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + + OMX_BOOL tunneled = (OMX_BOOL)data.readInt32(); + OMX_U32 audio_hw_sync = data.readInt32(); + + native_handle_t *sideband_handle = NULL; + status_t err = configureVideoTunnelMode( + node, port_index, tunneled, audio_hw_sync, &sideband_handle); + reply->writeInt32(err); + if(err == OK){ + reply->writeNativeHandle(sideband_handle); + } + + return NO_ERROR; + } + + case ALLOC_BUFFER: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + if (!isSecure(node) || port_index != 0 /* kPortIndexInput */) { + ALOGE(""b/24310423""); + reply->writeInt32(INVALID_OPERATION); + return NO_ERROR; + } + + size_t size = data.readInt64(); + + buffer_id buffer; + void *buffer_data; + status_t err = allocateBuffer( + node, port_index, size, &buffer, &buffer_data); + reply->writeInt32(err); + + if (err == OK) { + reply->writeInt32((int32_t)buffer); + reply->writeInt64((uintptr_t)buffer_data); + } + + return NO_ERROR; + } + + case ALLOC_BUFFER_WITH_BACKUP: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + sp params = + interface_cast(data.readStrongBinder()); + + buffer_id buffer; + status_t err = allocateBufferWithBackup( + node, port_index, params, &buffer); + + reply->writeInt32(err); + + if (err == OK) { + reply->writeInt32((int32_t)buffer); + } + + return NO_ERROR; + } + + case FREE_BUFFER: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + OMX_U32 port_index = data.readInt32(); + buffer_id buffer = (buffer_id)data.readInt32(); + reply->writeInt32(freeBuffer(node, port_index, buffer)); + + return NO_ERROR; + } + + case FILL_BUFFER: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + buffer_id buffer = (buffer_id)data.readInt32(); + reply->writeInt32(fillBuffer(node, buffer)); + + return NO_ERROR; + } + + case EMPTY_BUFFER: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + buffer_id buffer = (buffer_id)data.readInt32(); + OMX_U32 range_offset = data.readInt32(); + OMX_U32 range_length = data.readInt32(); + OMX_U32 flags = data.readInt32(); + OMX_TICKS timestamp = data.readInt64(); + + reply->writeInt32( + emptyBuffer( + node, buffer, range_offset, range_length, + flags, timestamp)); + + return NO_ERROR; + } + + case GET_EXTENSION_INDEX: + { + CHECK_OMX_INTERFACE(IOMX, data, reply); + + node_id node = (node_id)data.readInt32(); + const char *parameter_name = data.readCString(); + + OMX_INDEXTYPE index; + status_t err = getExtensionIndex(node, parameter_name, &index); + + reply->writeInt32(err); + + if (err == OK) { + reply->writeInt32(index); + } + + return OK; + } + + default: + return BBinder::onTransact(code, data, reply, flags); + } +} +","@@ -381,7 +381,7 @@ + + remote()->transact(CONFIGURE_VIDEO_TUNNEL_MODE, data, &reply); + + status_t err = reply.readInt32(); +- if (sidebandHandle) { ++ if (err == OK && sidebandHandle) { + *sidebandHandle = (native_handle_t *)reply.readNativeHandle(); + } + return err; +@@ -833,11 +833,13 @@ + + OMX_BOOL tunneled = (OMX_BOOL)data.readInt32(); + OMX_U32 audio_hw_sync = data.readInt32(); + +- native_handle_t *sideband_handle; ++ native_handle_t *sideband_handle = NULL; + status_t err = configureVideoTunnelMode( + node, port_index, tunneled, audio_hw_sync, &sideband_handle); + reply->writeInt32(err); +- reply->writeNativeHandle(sideband_handle); ++ if(err == OK){ ++ reply->writeNativeHandle(sideband_handle); ++ } + + return NO_ERROR; + } +",2601,2932,4096 +1318,"unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *buf, + unsigned char *limit, int *al) +{ + int extdatalen = 0; + unsigned char *orig = buf; + unsigned char *ret = buf; +# ifndef OPENSSL_NO_EC + /* See if we support any ECC ciphersuites */ + int using_ecc = 0; + if (s->version >= TLS1_VERSION || SSL_IS_DTLS(s)) { + int i; + unsigned long alg_k, alg_a; + STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s); + + for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++) { + SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i); + + alg_k = c->algorithm_mkey; + alg_a = c->algorithm_auth; + if ((alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe) + || (alg_a & SSL_aECDSA))) { + using_ecc = 1; + break; + } + } + } +# endif + + /* don't add extensions for SSLv3 unless doing secure renegotiation */ + if (s->client_version == SSL3_VERSION && !s->s3->send_connection_binding) + return orig; + + ret += 2; + + if (ret >= limit) + return NULL; /* this really never occurs, but ... */ + + if (s->tlsext_hostname != NULL) { + /* Add TLS extension servername to the Client Hello message */ + unsigned long size_str; + long lenmax; + + /*- + * check for enough space. + * 4 for the servername type and entension length + * 2 for servernamelist length + * 1 for the hostname type + * 2 for hostname length + * + hostname length + */ + + if ((lenmax = limit - ret - 9) < 0 + || (size_str = + strlen(s->tlsext_hostname)) > (unsigned long)lenmax) + return NULL; + + /* extension type and length */ + s2n(TLSEXT_TYPE_server_name, ret); + s2n(size_str + 5, ret); + + /* length of servername list */ + s2n(size_str + 3, ret); + + /* hostname type, length and hostname */ + *(ret++) = (unsigned char)TLSEXT_NAMETYPE_host_name; + s2n(size_str, ret); + memcpy(ret, s->tlsext_hostname, size_str); + ret += size_str; + } + + /* Add RI if renegotiating */ + if (s->renegotiate) { + int el; + + if (!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0)) { + SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); + return NULL; + } + + if ((limit - ret - 4 - el) < 0) + return NULL; + + s2n(TLSEXT_TYPE_renegotiate, ret); + s2n(el, ret); + + if (!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el)) { + SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); + return NULL; + } + + ret += el; + } +# ifndef OPENSSL_NO_SRP + /* Add SRP username if there is one */ + if (s->srp_ctx.login != NULL) { /* Add TLS extension SRP username to the + * Client Hello message */ + + int login_len = strlen(s->srp_ctx.login); + if (login_len > 255 || login_len == 0) { + SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); + return NULL; + } + + /*- + * check for enough space. + * 4 for the srp type type and entension length + * 1 for the srp user identity + * + srp user identity length + */ + if ((limit - ret - 5 - login_len) < 0) + return NULL; + + /* fill in the extension */ + s2n(TLSEXT_TYPE_srp, ret); + s2n(login_len + 1, ret); + (*ret++) = (unsigned char)login_len; + memcpy(ret, s->srp_ctx.login, login_len); + ret += login_len; + } +# endif + +# ifndef OPENSSL_NO_EC + if (using_ecc) { + /* + * Add TLS extension ECPointFormats to the ClientHello message + */ + long lenmax; + const unsigned char *pcurves, *pformats; + size_t num_curves, num_formats, curves_list_len; + + tls1_get_formatlist(s, &pformats, &num_formats); + + if ((lenmax = limit - ret - 5) < 0) + return NULL; + if (num_formats > (size_t)lenmax) + return NULL; + if (num_formats > 255) { + SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); + return NULL; + } + + s2n(TLSEXT_TYPE_ec_point_formats, ret); + /* The point format list has 1-byte length. */ + s2n(num_formats + 1, ret); + *(ret++) = (unsigned char)num_formats; + memcpy(ret, pformats, num_formats); + ret += num_formats; + + /* + * Add TLS extension EllipticCurves to the ClientHello message + */ + pcurves = s->tlsext_ellipticcurvelist; + if (!tls1_get_curvelist(s, 0, &pcurves, &num_curves)) + return NULL; + + if ((lenmax = limit - ret - 6) < 0) + return NULL; + if (num_curves > (size_t)lenmax / 2) + return NULL; + if (num_curves > 65532 / 2) { + SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); + return NULL; + } + curves_list_len = 2 * num_curves; + s2n(TLSEXT_TYPE_elliptic_curves, ret); + s2n(curves_list_len + 2, ret); + s2n(curves_list_len, ret); + memcpy(ret, pcurves, curves_list_len); + ret += curves_list_len; + } +# endif /* OPENSSL_NO_EC */ + + if (!(SSL_get_options(s) & SSL_OP_NO_TICKET)) { + int ticklen; + if (!s->new_session && s->session && s->session->tlsext_tick) + ticklen = s->session->tlsext_ticklen; + else if (s->session && s->tlsext_session_ticket && + s->tlsext_session_ticket->data) { + ticklen = s->tlsext_session_ticket->length; + s->session->tlsext_tick = OPENSSL_malloc(ticklen); + if (!s->session->tlsext_tick) + return NULL; + memcpy(s->session->tlsext_tick, + s->tlsext_session_ticket->data, ticklen); + s->session->tlsext_ticklen = ticklen; + } else + ticklen = 0; + if (ticklen == 0 && s->tlsext_session_ticket && + s->tlsext_session_ticket->data == NULL) + goto skip_ext; + /* + * Check for enough room 2 for extension type, 2 for len rest for + * ticket + */ + if ((long)(limit - ret - 4 - ticklen) < 0) + return NULL; + s2n(TLSEXT_TYPE_session_ticket, ret); + s2n(ticklen, ret); + if (ticklen) { + memcpy(ret, s->session->tlsext_tick, ticklen); + ret += ticklen; + } + } + skip_ext: + + if (SSL_CLIENT_USE_SIGALGS(s)) { + size_t salglen; + const unsigned char *salg; + salglen = tls12_get_psigalgs(s, &salg); + if ((size_t)(limit - ret) < salglen + 6) + return NULL; + s2n(TLSEXT_TYPE_signature_algorithms, ret); + s2n(salglen + 2, ret); + s2n(salglen, ret); + memcpy(ret, salg, salglen); + ret += salglen; + } +# ifdef TLSEXT_TYPE_opaque_prf_input + if (s->s3->client_opaque_prf_input != NULL) { + size_t col = s->s3->client_opaque_prf_input_len; + + if ((long)(limit - ret - 6 - col < 0)) + return NULL; + if (col > 0xFFFD) /* can't happen */ + return NULL; + + s2n(TLSEXT_TYPE_opaque_prf_input, ret); + s2n(col + 2, ret); + s2n(col, ret); + memcpy(ret, s->s3->client_opaque_prf_input, col); + ret += col; + } +# endif + + if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) { + int i; + long extlen, idlen, itmp; + OCSP_RESPID *id; + + idlen = 0; + for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) { + id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i); + itmp = i2d_OCSP_RESPID(id, NULL); + if (itmp <= 0) + return NULL; + idlen += itmp + 2; + } + + if (s->tlsext_ocsp_exts) { + extlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL); + if (extlen < 0) + return NULL; + } else + extlen = 0; + + if ((long)(limit - ret - 7 - extlen - idlen) < 0) + return NULL; + s2n(TLSEXT_TYPE_status_request, ret); + if (extlen + idlen > 0xFFF0) + return NULL; + s2n(extlen + idlen + 5, ret); + *(ret++) = TLSEXT_STATUSTYPE_ocsp; + s2n(idlen, ret); + for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) { + /* save position of id len */ + unsigned char *q = ret; + id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i); + /* skip over id len */ + ret += 2; + itmp = i2d_OCSP_RESPID(id, &ret); + /* write id len */ + s2n(itmp, q); + } + s2n(extlen, ret); + if (extlen > 0) + i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret); + } +# ifndef OPENSSL_NO_HEARTBEATS + /* Add Heartbeat extension */ + if ((limit - ret - 4 - 1) < 0) + return NULL; + s2n(TLSEXT_TYPE_heartbeat, ret); + s2n(1, ret); + /*- + * Set mode: + * 1: peer may send requests + * 2: peer not allowed to send requests + */ + if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS) + *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS; + else + *(ret++) = SSL_TLSEXT_HB_ENABLED; +# endif + +# ifndef OPENSSL_NO_NEXTPROTONEG + if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len) { + /* + * The client advertises an emtpy extension to indicate its support + * for Next Protocol Negotiation + */ + if (limit - ret - 4 < 0) + return NULL; + s2n(TLSEXT_TYPE_next_proto_neg, ret); + s2n(0, ret); + } +# endif + + if (s->alpn_client_proto_list && !s->s3->tmp.finish_md_len) { + if ((size_t)(limit - ret) < 6 + s->alpn_client_proto_list_len) + return NULL; + s2n(TLSEXT_TYPE_application_layer_protocol_negotiation, ret); + s2n(2 + s->alpn_client_proto_list_len, ret); + s2n(s->alpn_client_proto_list_len, ret); + memcpy(ret, s->alpn_client_proto_list, s->alpn_client_proto_list_len); + ret += s->alpn_client_proto_list_len; + s->cert->alpn_sent = 1; + } +# ifndef OPENSSL_NO_SRTP + if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s)) { + int el; + + ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0); + + if ((limit - ret - 4 - el) < 0) + return NULL; + + s2n(TLSEXT_TYPE_use_srtp, ret); + s2n(el, ret); + + if (ssl_add_clienthello_use_srtp_ext(s, ret, &el, el)) { + SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); + return NULL; + } + ret += el; + } +# endif + custom_ext_init(&s->cert->cli_ext); + /* Add custom TLS Extensions to ClientHello */ + if (!custom_ext_add(s, 0, &ret, limit, al)) + return NULL; + + /* + * Add padding to workaround bugs in F5 terminators. See + * https://tools.ietf.org/html/draft-agl-tls-padding-03 NB: because this + * code works out the length of all existing extensions it MUST always + * appear last. + */ + if (s->options & SSL_OP_TLSEXT_PADDING) { + int hlen = ret - (unsigned char *)s->init_buf->data; + /* + * The code in s23_clnt.c to build ClientHello messages includes the + * 5-byte record header in the buffer, while the code in s3_clnt.c + * does not. + */ + if (s->state == SSL23_ST_CW_CLNT_HELLO_A) + hlen -= 5; + if (hlen > 0xff && hlen < 0x200) { + hlen = 0x200 - hlen; + if (hlen >= 4) + hlen -= 4; + else + hlen = 0; + + s2n(TLSEXT_TYPE_padding, ret); + s2n(hlen, ret); + memset(ret, 0, hlen); + ret += hlen; + } + } + + if ((extdatalen = ret - orig - 2) == 0) + return orig; + + s2n(extdatalen, orig); + return ret; +} +",0,"unsigned char *ssl_add_clienthello_tlsext(SSL *s, unsigned char *buf, + unsigned char *limit, int *al) +{ + int extdatalen = 0; + unsigned char *orig = buf; + unsigned char *ret = buf; +# ifndef OPENSSL_NO_EC + /* See if we support any ECC ciphersuites */ + int using_ecc = 0; + if (s->version >= TLS1_VERSION || SSL_IS_DTLS(s)) { + int i; + unsigned long alg_k, alg_a; + STACK_OF(SSL_CIPHER) *cipher_stack = SSL_get_ciphers(s); + + for (i = 0; i < sk_SSL_CIPHER_num(cipher_stack); i++) { + SSL_CIPHER *c = sk_SSL_CIPHER_value(cipher_stack, i); + + alg_k = c->algorithm_mkey; + alg_a = c->algorithm_auth; + if ((alg_k & (SSL_kEECDH | SSL_kECDHr | SSL_kECDHe) + || (alg_a & SSL_aECDSA))) { + using_ecc = 1; + break; + } + } + } +# endif + + /* don't add extensions for SSLv3 unless doing secure renegotiation */ + if (s->client_version == SSL3_VERSION && !s->s3->send_connection_binding) + return orig; + + ret += 2; + + if (ret >= limit) + return NULL; /* this really never occurs, but ... */ + + if (s->tlsext_hostname != NULL) { + /* Add TLS extension servername to the Client Hello message */ + unsigned long size_str; + long lenmax; + + /*- + * check for enough space. + * 4 for the servername type and entension length + * 2 for servernamelist length + * 1 for the hostname type + * 2 for hostname length + * + hostname length + */ + + if ((lenmax = limit - ret - 9) < 0 + || (size_str = + strlen(s->tlsext_hostname)) > (unsigned long)lenmax) + return NULL; + + /* extension type and length */ + s2n(TLSEXT_TYPE_server_name, ret); + s2n(size_str + 5, ret); + + /* length of servername list */ + s2n(size_str + 3, ret); + + /* hostname type, length and hostname */ + *(ret++) = (unsigned char)TLSEXT_NAMETYPE_host_name; + s2n(size_str, ret); + memcpy(ret, s->tlsext_hostname, size_str); + ret += size_str; + } + + /* Add RI if renegotiating */ + if (s->renegotiate) { + int el; + + if (!ssl_add_clienthello_renegotiate_ext(s, 0, &el, 0)) { + SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); + return NULL; + } + + if ((limit - ret - 4 - el) < 0) + return NULL; + + s2n(TLSEXT_TYPE_renegotiate, ret); + s2n(el, ret); + + if (!ssl_add_clienthello_renegotiate_ext(s, ret, &el, el)) { + SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); + return NULL; + } + + ret += el; + } +# ifndef OPENSSL_NO_SRP + /* Add SRP username if there is one */ + if (s->srp_ctx.login != NULL) { /* Add TLS extension SRP username to the + * Client Hello message */ + + int login_len = strlen(s->srp_ctx.login); + if (login_len > 255 || login_len == 0) { + SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); + return NULL; + } + + /*- + * check for enough space. + * 4 for the srp type type and entension length + * 1 for the srp user identity + * + srp user identity length + */ + if ((limit - ret - 5 - login_len) < 0) + return NULL; + + /* fill in the extension */ + s2n(TLSEXT_TYPE_srp, ret); + s2n(login_len + 1, ret); + (*ret++) = (unsigned char)login_len; + memcpy(ret, s->srp_ctx.login, login_len); + ret += login_len; + } +# endif + +# ifndef OPENSSL_NO_EC + if (using_ecc) { + /* + * Add TLS extension ECPointFormats to the ClientHello message + */ + long lenmax; + const unsigned char *pcurves, *pformats; + size_t num_curves, num_formats, curves_list_len; + + tls1_get_formatlist(s, &pformats, &num_formats); + + if ((lenmax = limit - ret - 5) < 0) + return NULL; + if (num_formats > (size_t)lenmax) + return NULL; + if (num_formats > 255) { + SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); + return NULL; + } + + s2n(TLSEXT_TYPE_ec_point_formats, ret); + /* The point format list has 1-byte length. */ + s2n(num_formats + 1, ret); + *(ret++) = (unsigned char)num_formats; + memcpy(ret, pformats, num_formats); + ret += num_formats; + + /* + * Add TLS extension EllipticCurves to the ClientHello message + */ + pcurves = s->tlsext_ellipticcurvelist; + if (!tls1_get_curvelist(s, 0, &pcurves, &num_curves)) + return NULL; + + if ((lenmax = limit - ret - 6) < 0) + return NULL; + if (num_curves > (size_t)lenmax / 2) + return NULL; + if (num_curves > 65532 / 2) { + SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); + return NULL; + } + curves_list_len = 2 * num_curves; + s2n(TLSEXT_TYPE_elliptic_curves, ret); + s2n(curves_list_len + 2, ret); + s2n(curves_list_len, ret); + memcpy(ret, pcurves, curves_list_len); + ret += curves_list_len; + } +# endif /* OPENSSL_NO_EC */ + + if (!(SSL_get_options(s) & SSL_OP_NO_TICKET)) { + int ticklen; + if (!s->new_session && s->session && s->session->tlsext_tick) + ticklen = s->session->tlsext_ticklen; + else if (s->session && s->tlsext_session_ticket && + s->tlsext_session_ticket->data) { + ticklen = s->tlsext_session_ticket->length; + s->session->tlsext_tick = OPENSSL_malloc(ticklen); + if (!s->session->tlsext_tick) + return NULL; + memcpy(s->session->tlsext_tick, + s->tlsext_session_ticket->data, ticklen); + s->session->tlsext_ticklen = ticklen; + } else + ticklen = 0; + if (ticklen == 0 && s->tlsext_session_ticket && + s->tlsext_session_ticket->data == NULL) + goto skip_ext; + /* + * Check for enough room 2 for extension type, 2 for len rest for + * ticket + */ + if ((long)(limit - ret - 4 - ticklen) < 0) + return NULL; + s2n(TLSEXT_TYPE_session_ticket, ret); + s2n(ticklen, ret); + if (ticklen) { + memcpy(ret, s->session->tlsext_tick, ticklen); + ret += ticklen; + } + } + skip_ext: + + if (SSL_CLIENT_USE_SIGALGS(s)) { + size_t salglen; + const unsigned char *salg; + salglen = tls12_get_psigalgs(s, &salg); + if ((size_t)(limit - ret) < salglen + 6) + return NULL; + s2n(TLSEXT_TYPE_signature_algorithms, ret); + s2n(salglen + 2, ret); + s2n(salglen, ret); + memcpy(ret, salg, salglen); + ret += salglen; + } +# ifdef TLSEXT_TYPE_opaque_prf_input + if (s->s3->client_opaque_prf_input != NULL) { + size_t col = s->s3->client_opaque_prf_input_len; + + if ((long)(limit - ret - 6 - col < 0)) + return NULL; + if (col > 0xFFFD) /* can't happen */ + return NULL; + + s2n(TLSEXT_TYPE_opaque_prf_input, ret); + s2n(col + 2, ret); + s2n(col, ret); + memcpy(ret, s->s3->client_opaque_prf_input, col); + ret += col; + } +# endif + + if (s->tlsext_status_type == TLSEXT_STATUSTYPE_ocsp) { + int i; + long extlen, idlen, itmp; + OCSP_RESPID *id; + + idlen = 0; + for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) { + id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i); + itmp = i2d_OCSP_RESPID(id, NULL); + if (itmp <= 0) + return NULL; + idlen += itmp + 2; + } + + if (s->tlsext_ocsp_exts) { + extlen = i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, NULL); + if (extlen < 0) + return NULL; + } else + extlen = 0; + + if ((long)(limit - ret - 7 - extlen - idlen) < 0) + return NULL; + s2n(TLSEXT_TYPE_status_request, ret); + if (extlen + idlen > 0xFFF0) + return NULL; + s2n(extlen + idlen + 5, ret); + *(ret++) = TLSEXT_STATUSTYPE_ocsp; + s2n(idlen, ret); + for (i = 0; i < sk_OCSP_RESPID_num(s->tlsext_ocsp_ids); i++) { + /* save position of id len */ + unsigned char *q = ret; + id = sk_OCSP_RESPID_value(s->tlsext_ocsp_ids, i); + /* skip over id len */ + ret += 2; + itmp = i2d_OCSP_RESPID(id, &ret); + /* write id len */ + s2n(itmp, q); + } + s2n(extlen, ret); + if (extlen > 0) + i2d_X509_EXTENSIONS(s->tlsext_ocsp_exts, &ret); + } +# ifndef OPENSSL_NO_HEARTBEATS + /* Add Heartbeat extension */ + if ((limit - ret - 4 - 1) < 0) + return NULL; + s2n(TLSEXT_TYPE_heartbeat, ret); + s2n(1, ret); + /*- + * Set mode: + * 1: peer may send requests + * 2: peer not allowed to send requests + */ + if (s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_RECV_REQUESTS) + *(ret++) = SSL_TLSEXT_HB_DONT_SEND_REQUESTS; + else + *(ret++) = SSL_TLSEXT_HB_ENABLED; +# endif + +# ifndef OPENSSL_NO_NEXTPROTONEG + if (s->ctx->next_proto_select_cb && !s->s3->tmp.finish_md_len) { + /* + * The client advertises an emtpy extension to indicate its support + * for Next Protocol Negotiation + */ + if (limit - ret - 4 < 0) + return NULL; + s2n(TLSEXT_TYPE_next_proto_neg, ret); + s2n(0, ret); + } +# endif + + if (s->alpn_client_proto_list && !s->s3->tmp.finish_md_len) { + if ((size_t)(limit - ret) < 6 + s->alpn_client_proto_list_len) + return NULL; + s2n(TLSEXT_TYPE_application_layer_protocol_negotiation, ret); + s2n(2 + s->alpn_client_proto_list_len, ret); + s2n(s->alpn_client_proto_list_len, ret); + memcpy(ret, s->alpn_client_proto_list, s->alpn_client_proto_list_len); + ret += s->alpn_client_proto_list_len; + s->cert->alpn_sent = 1; + } +# ifndef OPENSSL_NO_SRTP + if (SSL_IS_DTLS(s) && SSL_get_srtp_profiles(s)) { + int el; + + ssl_add_clienthello_use_srtp_ext(s, 0, &el, 0); + + if ((limit - ret - 4 - el) < 0) + return NULL; + + s2n(TLSEXT_TYPE_use_srtp, ret); + s2n(el, ret); + + if (ssl_add_clienthello_use_srtp_ext(s, ret, &el, el)) { + SSLerr(SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT, ERR_R_INTERNAL_ERROR); + return NULL; + } + ret += el; + } +# endif + custom_ext_init(&s->cert->cli_ext); + /* Add custom TLS Extensions to ClientHello */ + if (!custom_ext_add(s, 0, &ret, limit, al)) + return NULL; + + /* + * Add padding to workaround bugs in F5 terminators. See + * https://tools.ietf.org/html/draft-agl-tls-padding-03 NB: because this + * code works out the length of all existing extensions it MUST always + * appear last. + */ + if (s->options & SSL_OP_TLSEXT_PADDING) { + int hlen = ret - (unsigned char *)s->init_buf->data; + /* + * The code in s23_clnt.c to build ClientHello messages includes the + * 5-byte record header in the buffer, while the code in s3_clnt.c + * does not. + */ + if (s->state == SSL23_ST_CW_CLNT_HELLO_A) + hlen -= 5; + if (hlen > 0xff && hlen < 0x200) { + hlen = 0x200 - hlen; + if (hlen >= 4) + hlen -= 4; + else + hlen = 0; + + s2n(TLSEXT_TYPE_padding, ret); + s2n(hlen, ret); + memset(ret, 0, hlen); + ret += hlen; + } + } + + if ((extdatalen = ret - orig - 2) == 0) + return orig; + + s2n(extdatalen, orig); + return ret; +} +","@@ -1867,11 +1867,11 @@ static void ssl_check_for_safari(SSL *s, const unsigned char *data, + 0x02, 0x03, /* SHA-1/ECDSA */ + }; + +- if (data >= (limit - 2)) ++ if (limit - data <= 2) + return; + data += 2; + +- if (data > (limit - 4)) ++ if (limit - data < 4) + return; + n2s(data, type); + n2s(data, size); +@@ -1879,7 +1879,7 @@ static void ssl_check_for_safari(SSL *s, const unsigned char *data, + if (type != TLSEXT_TYPE_server_name) + return; + +- if (data + size > limit) ++ if (limit - data < size) + return; + data += size; + +@@ -1887,7 +1887,7 @@ static void ssl_check_for_safari(SSL *s, const unsigned char *data, + const size_t len1 = sizeof(kSafariExtensionsBlock); + const size_t len2 = sizeof(kSafariTLS12ExtensionsBlock); + +- if (data + len1 + len2 != limit) ++ if (limit - data != (int)(len1 + len2)) + return; + if (memcmp(data, kSafariExtensionsBlock, len1) != 0) + return; +@@ -1896,7 +1896,7 @@ static void ssl_check_for_safari(SSL *s, const unsigned char *data, + } else { + const size_t len = sizeof(kSafariExtensionsBlock); + +- if (data + len != limit) ++ if (limit - data != (int)(len)) + return; + if (memcmp(data, kSafariExtensionsBlock, len) != 0) + return; +@@ -2053,19 +2053,19 @@ static int ssl_scan_clienthello_tlsext(SSL *s, unsigned char **p, + if (data == limit) + goto ri_check; + +- if (data > (limit - 2)) ++ if (limit - data < 2) + goto err; + + n2s(data, len); + +- if (data + len != limit) ++ if (limit - data != len) + goto err; + +- while (data <= (limit - 4)) { ++ while (limit - data >= 4) { + n2s(data, type); + n2s(data, size); + +- if (data + size > (limit)) ++ if (limit - data < size) + goto err; + # if 0 + fprintf(stderr, ""Received extension type %d size %d\n"", type, size); +@@ -2472,18 +2472,18 @@ static int ssl_scan_clienthello_custom_tlsext(SSL *s, + if (s->hit || s->cert->srv_ext.meths_count == 0) + return 1; + +- if (data >= limit - 2) ++ if (limit - data <= 2) + return 1; + n2s(data, len); + +- if (data > limit - len) ++ if (limit - data < len) + return 1; + +- while (data <= limit - 4) { ++ while (limit - data >= 4) { + n2s(data, type); + n2s(data, size); + +- if (data + size > limit) ++ if (limit - data < size) + return 1; + if (custom_ext_parse(s, 1 /* server */ , type, data, size, al) <= 0) + return 0; +@@ -2569,20 +2569,20 @@ static int ssl_scan_serverhello_tlsext(SSL *s, unsigned char **p, + SSL_TLSEXT_HB_DONT_SEND_REQUESTS); + # endif + +- if (data >= (d + n - 2)) ++ if ((d + n) - data <= 2) + goto ri_check; + + n2s(data, length); +- if (data + length != d + n) { ++ if ((d + n) - data != length) { + *al = SSL_AD_DECODE_ERROR; + return 0; + } + +- while (data <= (d + n - 4)) { ++ while ((d + n) - data >= 4) { + n2s(data, type); + n2s(data, size); + +- if (data + size > (d + n)) ++ if ((d + n) - data < size) + goto ri_check; + + if (s->tlsext_debug_cb) +@@ -3307,29 +3307,33 @@ int tls1_process_ticket(SSL *s, unsigned char *session_id, int len, + /* Skip past DTLS cookie */ + if (SSL_IS_DTLS(s)) { + i = *(p++); +- p += i; +- if (p >= limit) ++ ++ if (limit - p <= i) + return -1; ++ ++ p += i; + } + /* Skip past cipher list */ + n2s(p, i); +- p += i; +- if (p >= limit) ++ if (limit - p <= i) + return -1; ++ p += i; ++ + /* Skip past compression algorithm list */ + i = *(p++); +- p += i; +- if (p > limit) ++ if (limit - p < i) + return -1; ++ p += i; ++ + /* Now at start of extensions */ +- if ((p + 2) >= limit) ++ if (limit - p <= 2) + return 0; + n2s(p, i); +- while ((p + 4) <= limit) { ++ while (limit - p >= 4) { + unsigned short type, size; + n2s(p, type); + n2s(p, size); +- if (p + size > limit) ++ if (limit - p < size) + return 0; + if (type == TLSEXT_TYPE_session_ticket) { + int r;",3421,3752,4096 +18239,"int tmx_check_pretran(sip_msg_t *msg) +{ + unsigned int chid; + unsigned int slotid; + int dsize; + struct via_param *vbr; + str scallid; + str scseqmet; + str scseqnum; + str sftag; + str svbranch = {NULL, 0}; + pretran_t *it; + + if(_tmx_ptran_table==NULL) { + LM_ERR(""pretran hash table not initialized yet\n""); + return -1; + } + if(get_route_type()!=REQUEST_ROUTE) { + LM_ERR(""invalid usage - not in request route\n""); + return -1; + } + if(msg->first_line.type!=SIP_REQUEST) { + LM_ERR(""invalid usage - not a sip request\n""); + return -1; + } + if(parse_headers(msg, HDR_FROM_F|HDR_VIA1_F|HDR_CALLID_F|HDR_CSEQ_F, 0)<0) { + LM_ERR(""failed to parse required headers\n""); + return -1; + } + if(msg->cseq==NULL || msg->cseq->parsed==NULL) { + LM_ERR(""failed to parse cseq headers\n""); + return -1; + } + if(get_cseq(msg)->method_id==METHOD_ACK + || get_cseq(msg)->method_id==METHOD_CANCEL) { + LM_DBG(""no pre-transaction management for ACK or CANCEL\n""); + return -1; + } + if (msg->via1==0) { + LM_ERR(""failed to get Via header\n""); + return -1; + } + if (parse_from_header(msg)<0 || get_from(msg)->tag_value.len==0) { + LM_ERR(""failed to get From header\n""); + return -1; + } + if (msg->callid==NULL || msg->callid->body.s==NULL) { + LM_ERR(""failed to parse callid headers\n""); + return -1; + } + + vbr = msg->via1->branch; + + scallid = msg->callid->body; + trim(&scallid); + scseqmet = get_cseq(msg)->method; + trim(&scseqmet); + scseqnum = get_cseq(msg)->number; + trim(&scseqnum); + sftag = get_from(msg)->tag_value; + trim(&sftag); + + chid = get_hash1_raw(msg->callid->body.s, msg->callid->body.len); + slotid = chid & (_tmx_ptran_size-1); + + if(unlikely(_tmx_proc_ptran == NULL)) { + _tmx_proc_ptran = (pretran_t*)shm_malloc(sizeof(pretran_t)); + if(_tmx_proc_ptran == NULL) { + LM_ERR(""not enough memory for pretran structure\n""); + return -1; + } + memset(_tmx_proc_ptran, 0, sizeof(pretran_t)); + _tmx_proc_ptran->pid = my_pid(); + } + dsize = scallid.len + scseqnum.len + scseqmet.len + + sftag.len + 4; + if(likely(vbr!=NULL)) { + svbranch = vbr->value; + trim(&svbranch); + dsize += svbranch.len; + } + if(dsize<256) dsize = 256; + + tmx_pretran_unlink(); + + if(dsize > _tmx_proc_ptran->dbuf.len) { + if(_tmx_proc_ptran->dbuf.s) shm_free(_tmx_proc_ptran->dbuf.s); + _tmx_proc_ptran->dbuf.s = (char*)shm_malloc(dsize); + if(_tmx_proc_ptran->dbuf.s==NULL) { + LM_ERR(""not enough memory for pretran data\n""); + return -1; + } + _tmx_proc_ptran->dbuf.len = dsize; + } + _tmx_proc_ptran->hid = chid; + _tmx_proc_ptran->cseqmetid = (get_cseq(msg))->method_id; + + _tmx_proc_ptran->callid.s = _tmx_proc_ptran->dbuf.s; + memcpy(_tmx_proc_ptran->callid.s, scallid.s, scallid.len); + _tmx_proc_ptran->callid.len = scallid.len; + _tmx_proc_ptran->callid.s[_tmx_proc_ptran->callid.len] = '\0'; + + _tmx_proc_ptran->ftag.s = _tmx_proc_ptran->callid.s + + _tmx_proc_ptran->callid.len + 1; + memcpy(_tmx_proc_ptran->ftag.s, sftag.s, sftag.len); + _tmx_proc_ptran->ftag.len = sftag.len; + _tmx_proc_ptran->ftag.s[_tmx_proc_ptran->ftag.len] = '\0'; + + _tmx_proc_ptran->cseqnum.s = _tmx_proc_ptran->ftag.s + + _tmx_proc_ptran->ftag.len + 1; + memcpy(_tmx_proc_ptran->cseqnum.s, scseqnum.s, scseqnum.len); + _tmx_proc_ptran->cseqnum.len = scseqnum.len; + _tmx_proc_ptran->cseqnum.s[_tmx_proc_ptran->cseqnum.len] = '\0'; + + _tmx_proc_ptran->cseqmet.s = _tmx_proc_ptran->cseqnum.s + + _tmx_proc_ptran->cseqnum.len + 1; + memcpy(_tmx_proc_ptran->cseqmet.s, scseqmet.s, scseqmet.len); + _tmx_proc_ptran->cseqmet.len = scseqmet.len; + _tmx_proc_ptran->cseqmet.s[_tmx_proc_ptran->cseqmet.len] = '\0'; + + if(likely(vbr!=NULL)) { + _tmx_proc_ptran->vbranch.s = _tmx_proc_ptran->cseqmet.s + + _tmx_proc_ptran->cseqmet.len + 1; + memcpy(_tmx_proc_ptran->vbranch.s, svbranch.s, svbranch.len); + _tmx_proc_ptran->vbranch.len = svbranch.len; + _tmx_proc_ptran->vbranch.s[_tmx_proc_ptran->vbranch.len] = '\0'; + } else { + _tmx_proc_ptran->vbranch.s = NULL; + _tmx_proc_ptran->vbranch.len = 0; + } + + lock_get(&_tmx_ptran_table[slotid].lock); + it = _tmx_ptran_table[slotid].plist; + tmx_pretran_link_safe(slotid); + for(; it!=NULL; it=it->next) { + if(_tmx_proc_ptran->hid != it->hid + || _tmx_proc_ptran->cseqmetid != it->cseqmetid + || _tmx_proc_ptran->callid.len != it->callid.len + || _tmx_proc_ptran->ftag.len != it->ftag.len + || _tmx_proc_ptran->cseqmet.len != it->cseqmet.len + || _tmx_proc_ptran->cseqnum.len != it->cseqnum.len) + continue; + if(_tmx_proc_ptran->vbranch.s != NULL && it->vbranch.s != NULL) { + if(_tmx_proc_ptran->vbranch.len != it->vbranch.len) + continue; + /* shortcut - check last char in Via branch + * - kamailio/ser adds there branch index => in case of paralel + * forking by previous hop, catch it here quickly */ + if(_tmx_proc_ptran->vbranch.s[it->vbranch.len-1] + != it->vbranch.s[it->vbranch.len-1]) + continue; + if(memcmp(_tmx_proc_ptran->vbranch.s, + it->vbranch.s, it->vbranch.len)!=0) + continue; + /* shall stop by matching magic cookie? + * if (vbr && vbr->value.s && vbr->value.len > MCOOKIE_LEN + * && memcmp(vbr->value.s, MCOOKIE, MCOOKIE_LEN)==0) { + * LM_DBG(""rfc3261 cookie found in Via branch\n""); + * } + */ + } + if(memcmp(_tmx_proc_ptran->callid.s, + it->callid.s, it->callid.len)!=0 + || memcmp(_tmx_proc_ptran->ftag.s, + it->ftag.s, it->ftag.len)!=0 + || memcmp(_tmx_proc_ptran->cseqnum.s, + it->cseqnum.s, it->cseqnum.len)!=0) + continue; + if((it->cseqmetid==METHOD_OTHER || it->cseqmetid==METHOD_UNDEF) + && memcmp(_tmx_proc_ptran->cseqmet.s, + it->cseqmet.s, it->cseqmet.len)!=0) + continue; + LM_DBG(""matched another pre-transaction by pid %d for [%.*s]\n"", + it->pid, it->callid.len, it->callid.s); + lock_release(&_tmx_ptran_table[slotid].lock); + return 1; + } + lock_release(&_tmx_ptran_table[slotid].lock); + return 0; +} +",1,"int tmx_check_pretran(sip_msg_t *msg) +{ + unsigned int chid; + unsigned int slotid; + int dsize; + struct via_param *vbr; + str scallid; + str scseqmet; + str scseqnum; + str sftag; + str svbranch = {NULL, 0}; + pretran_t *it; + + if(_tmx_ptran_table==NULL) { + LM_ERR(""pretran hash table not initialized yet\n""); + return -1; + } + if(get_route_type()!=REQUEST_ROUTE) { + LM_ERR(""invalid usage - not in request route\n""); + return -1; + } + if(msg->first_line.type!=SIP_REQUEST) { + LM_ERR(""invalid usage - not a sip request\n""); + return -1; + } + if(parse_headers(msg, HDR_FROM_F|HDR_VIA1_F|HDR_CALLID_F|HDR_CSEQ_F, 0)<0) { + LM_ERR(""failed to parse required headers\n""); + return -1; + } + if(msg->cseq==NULL || msg->cseq->parsed==NULL) { + LM_ERR(""failed to parse cseq headers\n""); + return -1; + } + if(get_cseq(msg)->method_id==METHOD_ACK + || get_cseq(msg)->method_id==METHOD_CANCEL) { + LM_DBG(""no pre-transaction management for ACK or CANCEL\n""); + return -1; + } + if (msg->via1==0) { + LM_ERR(""failed to get Via header\n""); + return -1; + } + if (parse_from_header(msg)<0 || get_from(msg)->tag_value.len==0) { + LM_ERR(""failed to get From header\n""); + return -1; + } + if (msg->callid==NULL || msg->callid->body.s==NULL) { + LM_ERR(""failed to parse callid headers\n""); + return -1; + } + + vbr = msg->via1->branch; + + scallid = msg->callid->body; + trim(&scallid); + scseqmet = get_cseq(msg)->method; + trim(&scseqmet); + scseqnum = get_cseq(msg)->number; + trim(&scseqnum); + sftag = get_from(msg)->tag_value; + trim(&sftag); + + chid = get_hash1_raw(msg->callid->body.s, msg->callid->body.len); + slotid = chid & (_tmx_ptran_size-1); + + if(unlikely(_tmx_proc_ptran == NULL)) { + _tmx_proc_ptran = (pretran_t*)shm_malloc(sizeof(pretran_t)); + if(_tmx_proc_ptran == NULL) { + LM_ERR(""not enough memory for pretran structure\n""); + return -1; + } + memset(_tmx_proc_ptran, 0, sizeof(pretran_t)); + _tmx_proc_ptran->pid = my_pid(); + } + dsize = scallid.len + scseqnum.len + scseqmet.len + + sftag.len + 4; + if(likely(vbr!=NULL)) { + svbranch = vbr->value; + trim(&svbranch); + dsize += svbranch.len + 1; + } + if(dsize<256) dsize = 256; + + tmx_pretran_unlink(); + + if(dsize > _tmx_proc_ptran->dbuf.len) { + if(_tmx_proc_ptran->dbuf.s) shm_free(_tmx_proc_ptran->dbuf.s); + _tmx_proc_ptran->dbuf.s = (char*)shm_malloc(dsize); + if(_tmx_proc_ptran->dbuf.s==NULL) { + LM_ERR(""not enough memory for pretran data\n""); + return -1; + } + _tmx_proc_ptran->dbuf.len = dsize; + } + _tmx_proc_ptran->hid = chid; + _tmx_proc_ptran->cseqmetid = (get_cseq(msg))->method_id; + + _tmx_proc_ptran->callid.s = _tmx_proc_ptran->dbuf.s; + memcpy(_tmx_proc_ptran->callid.s, scallid.s, scallid.len); + _tmx_proc_ptran->callid.len = scallid.len; + _tmx_proc_ptran->callid.s[_tmx_proc_ptran->callid.len] = '\0'; + + _tmx_proc_ptran->ftag.s = _tmx_proc_ptran->callid.s + + _tmx_proc_ptran->callid.len + 1; + memcpy(_tmx_proc_ptran->ftag.s, sftag.s, sftag.len); + _tmx_proc_ptran->ftag.len = sftag.len; + _tmx_proc_ptran->ftag.s[_tmx_proc_ptran->ftag.len] = '\0'; + + _tmx_proc_ptran->cseqnum.s = _tmx_proc_ptran->ftag.s + + _tmx_proc_ptran->ftag.len + 1; + memcpy(_tmx_proc_ptran->cseqnum.s, scseqnum.s, scseqnum.len); + _tmx_proc_ptran->cseqnum.len = scseqnum.len; + _tmx_proc_ptran->cseqnum.s[_tmx_proc_ptran->cseqnum.len] = '\0'; + + _tmx_proc_ptran->cseqmet.s = _tmx_proc_ptran->cseqnum.s + + _tmx_proc_ptran->cseqnum.len + 1; + memcpy(_tmx_proc_ptran->cseqmet.s, scseqmet.s, scseqmet.len); + _tmx_proc_ptran->cseqmet.len = scseqmet.len; + _tmx_proc_ptran->cseqmet.s[_tmx_proc_ptran->cseqmet.len] = '\0'; + + if(likely(vbr!=NULL)) { + _tmx_proc_ptran->vbranch.s = _tmx_proc_ptran->cseqmet.s + + _tmx_proc_ptran->cseqmet.len + 1; + memcpy(_tmx_proc_ptran->vbranch.s, svbranch.s, svbranch.len); + _tmx_proc_ptran->vbranch.len = svbranch.len; + _tmx_proc_ptran->vbranch.s[_tmx_proc_ptran->vbranch.len] = '\0'; + } else { + _tmx_proc_ptran->vbranch.s = NULL; + _tmx_proc_ptran->vbranch.len = 0; + } + + lock_get(&_tmx_ptran_table[slotid].lock); + it = _tmx_ptran_table[slotid].plist; + tmx_pretran_link_safe(slotid); + for(; it!=NULL; it=it->next) { + if(_tmx_proc_ptran->hid != it->hid + || _tmx_proc_ptran->cseqmetid != it->cseqmetid + || _tmx_proc_ptran->callid.len != it->callid.len + || _tmx_proc_ptran->ftag.len != it->ftag.len + || _tmx_proc_ptran->cseqmet.len != it->cseqmet.len + || _tmx_proc_ptran->cseqnum.len != it->cseqnum.len) + continue; + if(_tmx_proc_ptran->vbranch.s != NULL && it->vbranch.s != NULL) { + if(_tmx_proc_ptran->vbranch.len != it->vbranch.len) + continue; + /* shortcut - check last char in Via branch + * - kamailio/ser adds there branch index => in case of paralel + * forking by previous hop, catch it here quickly */ + if(_tmx_proc_ptran->vbranch.s[it->vbranch.len-1] + != it->vbranch.s[it->vbranch.len-1]) + continue; + if(memcmp(_tmx_proc_ptran->vbranch.s, + it->vbranch.s, it->vbranch.len)!=0) + continue; + /* shall stop by matching magic cookie? + * if (vbr && vbr->value.s && vbr->value.len > MCOOKIE_LEN + * && memcmp(vbr->value.s, MCOOKIE, MCOOKIE_LEN)==0) { + * LM_DBG(""rfc3261 cookie found in Via branch\n""); + * } + */ + } + if(memcmp(_tmx_proc_ptran->callid.s, + it->callid.s, it->callid.len)!=0 + || memcmp(_tmx_proc_ptran->ftag.s, + it->ftag.s, it->ftag.len)!=0 + || memcmp(_tmx_proc_ptran->cseqnum.s, + it->cseqnum.s, it->cseqnum.len)!=0) + continue; + if((it->cseqmetid==METHOD_OTHER || it->cseqmetid==METHOD_UNDEF) + && memcmp(_tmx_proc_ptran->cseqmet.s, + it->cseqmet.s, it->cseqmet.len)!=0) + continue; + LM_DBG(""matched another pre-transaction by pid %d for [%.*s]\n"", + it->pid, it->callid.len, it->callid.s); + lock_release(&_tmx_ptran_table[slotid].lock); + return 1; + } + lock_release(&_tmx_ptran_table[slotid].lock); + return 0; +} +","@@ -260,7 +260,7 @@ int tmx_check_pretran(sip_msg_t *msg) + if(likely(vbr!=NULL)) { + svbranch = vbr->value; + trim(&svbranch); +- dsize += svbranch.len; ++ dsize += svbranch.len + 1; + } + if(dsize<256) dsize = 256; + ",2071,2402,4096 diff --git a/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_2048_to_4096.pkl b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_2048_to_4096.pkl new file mode 100644 index 0000000000000000000000000000000000000000..7a9e83ce00b1fc08ac0b35dd2cc727cb09b07825 --- /dev/null +++ b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_2048_to_4096.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d849478a060e68705ff261d1cc88a6b4ccb1d3b8bf395961f407879e51aca9be +size 2979731 diff --git a/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_4096_to_6144.csv b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_4096_to_6144.csv new file mode 100644 index 0000000000000000000000000000000000000000..d6677fb83d6b149f4f00e5a96b5f245ba45667d2 --- /dev/null +++ b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_4096_to_6144.csv @@ -0,0 +1,44675 @@ +idx,func_before,vul,func_after,patch,code_token_length,total_token_length,max_tokens_setting +18024,"parse_wbxml_tag_defined (proto_tree *tree, tvbuff_t *tvb, guint32 offset, + guint32 str_tbl, guint8 *level, guint8 *codepage_stag, guint8 *codepage_attr, + const wbxml_decoding *map) + { + guint32 tvb_len = tvb_reported_length (tvb); + guint32 off = offset; + guint32 len; + guint str_len; + guint32 ent; + guint32 idx; + guint8 peek; + guint32 tag_len; /* Length of the index (uintvar) from a LITERAL tag */ + guint8 tag_save_known = 0; /* Will contain peek & 0x3F (tag identity) */ + guint8 tag_new_known = 0; /* Will contain peek & 0x3F (tag identity) */ + const char *tag_save_literal; /* Will contain the LITERAL tag identity */ + const char *tag_new_literal; /* Will contain the LITERAL tag identity */ + guint8 parsing_tag_content = FALSE; /* Are we parsing content from a + tag with content: Content + + The initial state is FALSE. + This state will trigger recursion. */ + tag_save_literal = NULL; /* Prevents compiler warning */ + + DebugLog((""parse_wbxml_tag_defined (level = %u, offset = %u)\n"", *level, offset)); + while (off < tvb_len) { + peek = tvb_get_guint8 (tvb, off); + DebugLog((""STAG: (top of while) level = %3u, peek = 0x%02X, off = %u, tvb_len = %u\n"", *level, peek, off, tvb_len)); + if ((peek & 0x3F) < 4) switch (peek) { /* Global tokens in state = STAG + but not the LITERAL tokens */ + case 0x00: /* SWITCH_PAGE */ + *codepage_stag = tvb_get_guint8 (tvb, off+1); + proto_tree_add_text (tree, tvb, off, 2, + "" | Tag | T -->%3d "" + ""| SWITCH_PAGE (Tag code page) "" + ""|"", + *codepage_stag); + off += 2; + break; + case 0x01: /* END: only possible for Tag with Content */ + if (tag_save_known) { /* Known TAG */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| END (Known Tag 0x%02X) "" + ""| %s"", + *level, *codepage_stag, + tag_save_known, Indent (*level), + tag_save_literal); /* We already looked it up! */ + } else { /* Literal TAG */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| END (Literal Tag) "" + ""| %s"", + *level, *codepage_stag, Indent (*level), + tag_save_literal ? tag_save_literal : """"); + } + (*level)--; + off++; + /* Reset code page: not needed as return from recursion */ + DebugLog((""STAG: level = %u, Return: len = %u\n"", *level, off - offset)); + return (off - offset); + case 0x02: /* ENTITY */ + ent = tvb_get_guintvar (tvb, off+1, &len); + proto_tree_add_text (tree, tvb, off, 1+len, + "" %3d | Tag | T %3d "" + ""| ENTITY "" + ""| %s'&#%u;'"", + *level, *codepage_stag, Indent (*level), ent); + off += 1+len; + break; + case 0x03: /* STR_I */ + len = tvb_strsize (tvb, off+1); + proto_tree_add_text (tree, tvb, off, 1+len, + "" %3d | Tag | T %3d "" + ""| STR_I (Inline string) "" + ""| %s\'%s\'"", + *level, *codepage_stag, Indent(*level), + tvb_format_text (tvb, off+1, len-1)); + off += 1+len; + break; + case 0x40: /* EXT_I_0 */ + case 0x41: /* EXT_I_1 */ + case 0x42: /* EXT_I_2 */ + /* Extension tokens */ + len = tvb_strsize (tvb, off+1); + proto_tree_add_text (tree, tvb, off, 1+len, + "" %3d | Tag | T %3d "" + ""| EXT_I_%1x (Extension Token) "" + ""| %s(%s: \'%s\')"", + *level, *codepage_stag, + peek & 0x0f, Indent (*level), + map_token (map->global, 0, peek), + tvb_format_text (tvb, off+1, len-1)); + off += 1+len; + break; + case 0x43: /* PI */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| PI (XML Processing Instruction) "" + ""| %s= tvb_len) { + DebugLog((""STAG: level = %u, ThrowException: len = %u (short frame)\n"", *level, off - offset)); + /* + * TODO - Do we need to free g_malloc()ed memory? + */ + THROW(ReportedBoundsError); + } + proto_tree_add_text (tree, tvb, off-1, 1, + "" %3d | Tag | T %3d "" + ""| END (PI) "" + ""| %s?>"", + *level, *codepage_stag, Indent (*level)); + break; + case 0x80: /* EXT_T_0 */ + case 0x81: /* EXT_T_1 */ + case 0x82: /* EXT_T_2 */ + /* Extension tokens */ + idx = tvb_get_guintvar (tvb, off+1, &len); + { char *s; + if (map->ext_t[peek & 0x03]) + s = (map->ext_t[peek & 0x03])(tvb, idx, str_tbl); + else + s = wmem_strdup_printf(wmem_packet_scope(), ""EXT_T_%1x (%s)"", peek & 0x03, + map_token (map->global, 0, peek)); + proto_tree_add_text (tree, tvb, off, 1+len, + "" %3d | Tag | T %3d "" + ""| EXT_T_%1x (Extension Token) "" + ""| %s%s"", + *level, *codepage_stag, peek & 0x0f, Indent (*level), + s); + } + off += 1+len; + break; + case 0x83: /* STR_T */ + idx = tvb_get_guintvar (tvb, off+1, &len); + str_len = tvb_strsize (tvb, str_tbl+idx); + proto_tree_add_text (tree, tvb, off, 1+len, + "" %3d | Tag | T %3d "" + ""| STR_T (Tableref string) "" + ""| %s\'%s\'"", + *level, *codepage_stag, Indent (*level), + tvb_format_text (tvb, str_tbl+idx, str_len-1)); + off += 1+len; + break; + case 0xC0: /* EXT_0 */ + case 0xC1: /* EXT_1 */ + case 0xC2: /* EXT_2 */ + /* Extension tokens */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| EXT_%1x (Extension Token) "" + ""| %s(%s)"", + *level, *codepage_stag, peek & 0x0f, Indent (*level), + map_token (map->global, 0, peek)); + off++; + break; + case 0xC3: /* OPAQUE - WBXML 1.1 and newer */ + if (tvb_get_guint8 (tvb, 0)) { /* WBXML 1.x (x > 0) */ + char *str; + if (tag_save_known) { /* Knwon tag */ + if (map->opaque_binary_tag) { + str = map->opaque_binary_tag(tvb, off + 1, + tag_save_known, *codepage_stag, &len); + } else { + str = default_opaque_binary_tag(tvb, off + 1, + tag_save_known, *codepage_stag, &len); + } + } else { /* lITERAL tag */ + if (map->opaque_literal_tag) { + str = map->opaque_literal_tag(tvb, off + 1, + tag_save_literal, *codepage_stag, &len); + } else { + str = default_opaque_literal_tag(tvb, off + 1, + tag_save_literal, *codepage_stag, &len); + } + } + proto_tree_add_text (tree, tvb, off, 1 + len, + "" %3d | Tag | T %3d "" + ""| OPAQUE (Opaque data) "" + ""| %s%s"", + *level, *codepage_stag, Indent (*level), str); + off += 1 + len; + } else { /* WBXML 1.0 - RESERVED_2 token (invalid) */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| RESERVED_2 (Invalid Token!) "" + ""| WBXML 1.0 parsing stops here."", + *level, *codepage_stag); + /* Stop processing as it is impossible to parse now */ + off = tvb_len; + DebugLog((""STAG: level = %u, Return: len = %u\n"", *level, off - offset)); + return (off - offset); + } + break; + + /* No default clause, as all cases have been treated */ + } else { /* LITERAL or Known TAG */ + /* We must store the initial tag, and also retrieve the new tag. + * For efficiency reasons, we store the literal tag representation + * for known tags too, so we can easily close the tag without the + * need of a new lookup and avoiding storage of token codepage. + * + * There are 4 possibilities: + * + * 1. Known tag followed by a known tag + * 2. Known tag followed by a LITERAL tag + * 3. LITERAL tag followed by Known tag + * 4. LITERAL tag followed by LITERAL tag + */ + + /* Store the new tag */ + tag_len = 0; + if ((peek & 0x3F) == 4) { /* LITERAL */ + DebugLog((""STAG: LITERAL tag (peek = 0x%02X, off = %u) - TableRef follows!\n"", peek, off)); + idx = tvb_get_guintvar (tvb, off+1, &tag_len); + str_len = tvb_strsize (tvb, str_tbl+idx); + tag_new_literal = (const gchar*)tvb_get_ptr (tvb, str_tbl+idx, str_len); + tag_new_known = 0; /* invalidate known tag_new */ + } else { /* Known tag */ + tag_new_known = peek & 0x3F; + tag_new_literal = map_token (map->tags, *codepage_stag, + tag_new_known); + /* Stored looked up tag name string */ + } + + /* Parsing of TAG starts HERE */ + if (peek & 0x40) { /* Content present */ + /* Content follows + * [!] An explicit END token is expected in these cases! + * ==> Recursion possible if we encounter a tag with content; + * recursion will return at the explicit END token. + */ + if (parsing_tag_content) { /* Recurse */ + DebugLog((""STAG: Tag in Tag - RECURSE! (off = %u)\n"", off)); + /* Do not process the attribute list: + * recursion will take care of it */ + (*level)++; + len = parse_wbxml_tag_defined (tree, tvb, off, str_tbl, + level, codepage_stag, codepage_attr, map); + off += len; + } else { /* Now we will have content to parse */ + /* Save the start tag so we can properly close it later. */ + if ((peek & 0x3F) == 4) { /* Literal tag */ + tag_save_literal = tag_new_literal; + tag_save_known = 0; + } else { /* Known tag */ + tag_save_known = tag_new_known; + tag_save_literal = tag_new_literal; + /* The last statement avoids needless lookups */ + } + /* Process the attribute list if present */ + if (peek & 0x80) { /* Content and Attribute list present */ + if (tag_new_known) { /* Known tag */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| Known Tag 0x%02X (AC) "" + ""| %s<%s"", + *level, *codepage_stag, tag_new_known, + Indent (*level), tag_new_literal); + /* Tag string already looked up earlier! */ + off++; + } else { /* LITERAL tag */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| LITERAL_AC (Literal tag) (AC) "" + ""| %s<%s"", + *level, *codepage_stag, Indent (*level), tag_new_literal); + off += 1 + tag_len; + } + len = parse_wbxml_attribute_list_defined (tree, tvb, + off, str_tbl, *level, codepage_attr, map); + /* Check that there is still room in packet */ + off += len; + if (off >= tvb_len) { + DebugLog((""STAG: level = %u, ThrowException: len = %u (short frame)\n"", + *level, off - offset)); + /* + * TODO - Do we need to free g_malloc()ed memory? + */ + THROW(ReportedBoundsError); + } + proto_tree_add_text (tree, tvb, off-1, 1, + "" %3d | Tag | T %3d "" + ""| END (attribute list) "" + ""| %s>"", + *level, *codepage_stag, Indent (*level)); + } else { /* Content, no Attribute list */ + if (tag_new_known) { /* Known tag */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| Known Tag 0x%02X (.C) "" + ""| %s<%s>"", + *level, *codepage_stag, tag_new_known, + Indent (*level), tag_new_literal); + /* Tag string already looked up earlier! */ + off++; + } else { /* LITERAL tag */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| LITERAL_C (Literal Tag) (.C) "" + ""| %s<%s>"", + *level, *codepage_stag, Indent (*level), + tag_new_literal); + off += 1 + tag_len; + } + } + /* The data that follows in the parsing process + * represents content for the opening tag + * we've just processed in the lines above. + * Next time we encounter a tag with content: recurse + */ + parsing_tag_content = TRUE; + DebugLog((""Tag in Tag - No recursion this time! (off = %u)\n"", off)); + } + } else { /* No Content */ + DebugLog(("" in Tag - No recursion! (off = %u)\n"", off)); + (*level)++; + if (peek & 0x80) { /* No Content, Attribute list present */ + if (tag_new_known) { /* Known tag */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| Known Tag 0x%02X (A.) "" + ""| %s<%s"", + *level, *codepage_stag, tag_new_known, + Indent (*level), tag_new_literal); + /* Tag string already looked up earlier! */ + off++; + len = parse_wbxml_attribute_list_defined (tree, tvb, + off, str_tbl, *level, codepage_attr, map); + /* Check that there is still room in packet */ + off += len; + if (off > tvb_len) { + DebugLog((""STAG: level = %u, ThrowException: len = %u (short frame)\n"", *level, off - offset)); + /* + * TODO - Do we need to free g_malloc()ed memory? + */ + THROW(ReportedBoundsError); + } + proto_tree_add_text (tree, tvb, off-1, 1, + "" %3d | Tag | T %3d "" + ""| END (Known Tag) "" + ""| %s/>"", + *level, *codepage_stag, Indent (*level)); + } else { /* LITERAL tag */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| LITERAL_A (Literal Tag) (A.) "" + ""| %s<%s"", + *level, *codepage_stag, Indent (*level), tag_new_literal); + off += 1 + tag_len; + len = parse_wbxml_attribute_list_defined (tree, tvb, + off, str_tbl, *level, codepage_attr, map); + /* Check that there is still room in packet */ + off += len; + if (off >= tvb_len) { + DebugLog((""STAG: level = %u, ThrowException: len = %u (short frame)\n"", *level, off - offset)); + /* + * TODO - Do we need to free g_malloc()ed memory? + */ + THROW(ReportedBoundsError); + } + proto_tree_add_text (tree, tvb, off-1, 1, + "" %3d | Tag | T %3d "" + ""| END (Literal Tag) "" + ""| %s/>"", + *level, *codepage_stag, Indent (*level)); + } + } else { /* No Content, No Attribute list */ + if (tag_new_known) { /* Known tag */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| Known Tag 0x%02x (..) "" + ""| %s<%s />"", + *level, *codepage_stag, tag_new_known, + Indent (*level), tag_new_literal); + /* Tag string already looked up earlier! */ + off++; + } else { /* LITERAL tag */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| LITERAL (Literal Tag) (..) "" + ""| %s<%s />"", + *level, *codepage_stag, Indent (*level), + tag_new_literal); + off += 1 + tag_len; + } + } + (*level)--; + /* TODO: Do I have to reset code page here? */ + } + } /* if (tag & 0x3F) >= 5 */ + } /* while */ + DebugLog((""STAG: level = %u, Return: len = %u (end of function body)\n"", *level, off - offset)); + return (off - offset); +} +",1,"parse_wbxml_tag_defined (proto_tree *tree, tvbuff_t *tvb, guint32 offset, + guint32 str_tbl, guint8 *level, guint8 *codepage_stag, guint8 *codepage_attr, + const wbxml_decoding *map) + { + guint32 tvb_len = tvb_reported_length (tvb); + guint32 off = offset, last_off; + guint32 len; + guint str_len; + guint32 ent; + guint32 idx; + guint8 peek; + guint32 tag_len; /* Length of the index (uintvar) from a LITERAL tag */ + guint8 tag_save_known = 0; /* Will contain peek & 0x3F (tag identity) */ + guint8 tag_new_known = 0; /* Will contain peek & 0x3F (tag identity) */ + const char *tag_save_literal; /* Will contain the LITERAL tag identity */ + const char *tag_new_literal; /* Will contain the LITERAL tag identity */ + guint8 parsing_tag_content = FALSE; /* Are we parsing content from a + tag with content: Content + + The initial state is FALSE. + This state will trigger recursion. */ + tag_save_literal = NULL; /* Prevents compiler warning */ + + DebugLog((""parse_wbxml_tag_defined (level = %u, offset = %u)\n"", *level, offset)); + last_off = off; + while (off < tvb_len) { + peek = tvb_get_guint8 (tvb, off); + DebugLog((""STAG: (top of while) level = %3u, peek = 0x%02X, off = %u, tvb_len = %u\n"", *level, peek, off, tvb_len)); + if ((peek & 0x3F) < 4) switch (peek) { /* Global tokens in state = STAG + but not the LITERAL tokens */ + case 0x00: /* SWITCH_PAGE */ + *codepage_stag = tvb_get_guint8 (tvb, off+1); + proto_tree_add_text (tree, tvb, off, 2, + "" | Tag | T -->%3d "" + ""| SWITCH_PAGE (Tag code page) "" + ""|"", + *codepage_stag); + off += 2; + break; + case 0x01: /* END: only possible for Tag with Content */ + if (tag_save_known) { /* Known TAG */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| END (Known Tag 0x%02X) "" + ""| %s"", + *level, *codepage_stag, + tag_save_known, Indent (*level), + tag_save_literal); /* We already looked it up! */ + } else { /* Literal TAG */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| END (Literal Tag) "" + ""| %s"", + *level, *codepage_stag, Indent (*level), + tag_save_literal ? tag_save_literal : """"); + } + (*level)--; + off++; + /* Reset code page: not needed as return from recursion */ + DebugLog((""STAG: level = %u, Return: len = %u\n"", *level, off - offset)); + return (off - offset); + case 0x02: /* ENTITY */ + ent = tvb_get_guintvar (tvb, off+1, &len); + proto_tree_add_text (tree, tvb, off, 1+len, + "" %3d | Tag | T %3d "" + ""| ENTITY "" + ""| %s'&#%u;'"", + *level, *codepage_stag, Indent (*level), ent); + off += 1+len; + break; + case 0x03: /* STR_I */ + len = tvb_strsize (tvb, off+1); + proto_tree_add_text (tree, tvb, off, 1+len, + "" %3d | Tag | T %3d "" + ""| STR_I (Inline string) "" + ""| %s\'%s\'"", + *level, *codepage_stag, Indent(*level), + tvb_format_text (tvb, off+1, len-1)); + off += 1+len; + break; + case 0x40: /* EXT_I_0 */ + case 0x41: /* EXT_I_1 */ + case 0x42: /* EXT_I_2 */ + /* Extension tokens */ + len = tvb_strsize (tvb, off+1); + proto_tree_add_text (tree, tvb, off, 1+len, + "" %3d | Tag | T %3d "" + ""| EXT_I_%1x (Extension Token) "" + ""| %s(%s: \'%s\')"", + *level, *codepage_stag, + peek & 0x0f, Indent (*level), + map_token (map->global, 0, peek), + tvb_format_text (tvb, off+1, len-1)); + off += 1+len; + break; + case 0x43: /* PI */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| PI (XML Processing Instruction) "" + ""| %s= tvb_len) { + DebugLog((""STAG: level = %u, ThrowException: len = %u (short frame)\n"", *level, off - offset)); + /* + * TODO - Do we need to free g_malloc()ed memory? + */ + THROW(ReportedBoundsError); + } + proto_tree_add_text (tree, tvb, off-1, 1, + "" %3d | Tag | T %3d "" + ""| END (PI) "" + ""| %s?>"", + *level, *codepage_stag, Indent (*level)); + break; + case 0x80: /* EXT_T_0 */ + case 0x81: /* EXT_T_1 */ + case 0x82: /* EXT_T_2 */ + /* Extension tokens */ + idx = tvb_get_guintvar (tvb, off+1, &len); + { char *s; + if (map->ext_t[peek & 0x03]) + s = (map->ext_t[peek & 0x03])(tvb, idx, str_tbl); + else + s = wmem_strdup_printf(wmem_packet_scope(), ""EXT_T_%1x (%s)"", peek & 0x03, + map_token (map->global, 0, peek)); + proto_tree_add_text (tree, tvb, off, 1+len, + "" %3d | Tag | T %3d "" + ""| EXT_T_%1x (Extension Token) "" + ""| %s%s"", + *level, *codepage_stag, peek & 0x0f, Indent (*level), + s); + } + off += 1+len; + break; + case 0x83: /* STR_T */ + idx = tvb_get_guintvar (tvb, off+1, &len); + str_len = tvb_strsize (tvb, str_tbl+idx); + proto_tree_add_text (tree, tvb, off, 1+len, + "" %3d | Tag | T %3d "" + ""| STR_T (Tableref string) "" + ""| %s\'%s\'"", + *level, *codepage_stag, Indent (*level), + tvb_format_text (tvb, str_tbl+idx, str_len-1)); + off += 1+len; + break; + case 0xC0: /* EXT_0 */ + case 0xC1: /* EXT_1 */ + case 0xC2: /* EXT_2 */ + /* Extension tokens */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| EXT_%1x (Extension Token) "" + ""| %s(%s)"", + *level, *codepage_stag, peek & 0x0f, Indent (*level), + map_token (map->global, 0, peek)); + off++; + break; + case 0xC3: /* OPAQUE - WBXML 1.1 and newer */ + if (tvb_get_guint8 (tvb, 0)) { /* WBXML 1.x (x > 0) */ + char *str; + if (tag_save_known) { /* Knwon tag */ + if (map->opaque_binary_tag) { + str = map->opaque_binary_tag(tvb, off + 1, + tag_save_known, *codepage_stag, &len); + } else { + str = default_opaque_binary_tag(tvb, off + 1, + tag_save_known, *codepage_stag, &len); + } + } else { /* lITERAL tag */ + if (map->opaque_literal_tag) { + str = map->opaque_literal_tag(tvb, off + 1, + tag_save_literal, *codepage_stag, &len); + } else { + str = default_opaque_literal_tag(tvb, off + 1, + tag_save_literal, *codepage_stag, &len); + } + } + proto_tree_add_text (tree, tvb, off, 1 + len, + "" %3d | Tag | T %3d "" + ""| OPAQUE (Opaque data) "" + ""| %s%s"", + *level, *codepage_stag, Indent (*level), str); + off += 1 + len; + } else { /* WBXML 1.0 - RESERVED_2 token (invalid) */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| RESERVED_2 (Invalid Token!) "" + ""| WBXML 1.0 parsing stops here."", + *level, *codepage_stag); + /* Stop processing as it is impossible to parse now */ + off = tvb_len; + DebugLog((""STAG: level = %u, Return: len = %u\n"", *level, off - offset)); + return (off - offset); + } + break; + + /* No default clause, as all cases have been treated */ + } else { /* LITERAL or Known TAG */ + /* We must store the initial tag, and also retrieve the new tag. + * For efficiency reasons, we store the literal tag representation + * for known tags too, so we can easily close the tag without the + * need of a new lookup and avoiding storage of token codepage. + * + * There are 4 possibilities: + * + * 1. Known tag followed by a known tag + * 2. Known tag followed by a LITERAL tag + * 3. LITERAL tag followed by Known tag + * 4. LITERAL tag followed by LITERAL tag + */ + + /* Store the new tag */ + tag_len = 0; + if ((peek & 0x3F) == 4) { /* LITERAL */ + DebugLog((""STAG: LITERAL tag (peek = 0x%02X, off = %u) - TableRef follows!\n"", peek, off)); + idx = tvb_get_guintvar (tvb, off+1, &tag_len); + str_len = tvb_strsize (tvb, str_tbl+idx); + tag_new_literal = (const gchar*)tvb_get_ptr (tvb, str_tbl+idx, str_len); + tag_new_known = 0; /* invalidate known tag_new */ + } else { /* Known tag */ + tag_new_known = peek & 0x3F; + tag_new_literal = map_token (map->tags, *codepage_stag, + tag_new_known); + /* Stored looked up tag name string */ + } + + /* Parsing of TAG starts HERE */ + if (peek & 0x40) { /* Content present */ + /* Content follows + * [!] An explicit END token is expected in these cases! + * ==> Recursion possible if we encounter a tag with content; + * recursion will return at the explicit END token. + */ + if (parsing_tag_content) { /* Recurse */ + DebugLog((""STAG: Tag in Tag - RECURSE! (off = %u)\n"", off)); + /* Do not process the attribute list: + * recursion will take care of it */ + (*level)++; + len = parse_wbxml_tag_defined (tree, tvb, off, str_tbl, + level, codepage_stag, codepage_attr, map); + off += len; + } else { /* Now we will have content to parse */ + /* Save the start tag so we can properly close it later. */ + if ((peek & 0x3F) == 4) { /* Literal tag */ + tag_save_literal = tag_new_literal; + tag_save_known = 0; + } else { /* Known tag */ + tag_save_known = tag_new_known; + tag_save_literal = tag_new_literal; + /* The last statement avoids needless lookups */ + } + /* Process the attribute list if present */ + if (peek & 0x80) { /* Content and Attribute list present */ + if (tag_new_known) { /* Known tag */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| Known Tag 0x%02X (AC) "" + ""| %s<%s"", + *level, *codepage_stag, tag_new_known, + Indent (*level), tag_new_literal); + /* Tag string already looked up earlier! */ + off++; + } else { /* LITERAL tag */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| LITERAL_AC (Literal tag) (AC) "" + ""| %s<%s"", + *level, *codepage_stag, Indent (*level), tag_new_literal); + off += 1 + tag_len; + } + len = parse_wbxml_attribute_list_defined (tree, tvb, + off, str_tbl, *level, codepage_attr, map); + /* Check that there is still room in packet */ + off += len; + if (off >= tvb_len) { + DebugLog((""STAG: level = %u, ThrowException: len = %u (short frame)\n"", + *level, off - offset)); + /* + * TODO - Do we need to free g_malloc()ed memory? + */ + THROW(ReportedBoundsError); + } + proto_tree_add_text (tree, tvb, off-1, 1, + "" %3d | Tag | T %3d "" + ""| END (attribute list) "" + ""| %s>"", + *level, *codepage_stag, Indent (*level)); + } else { /* Content, no Attribute list */ + if (tag_new_known) { /* Known tag */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| Known Tag 0x%02X (.C) "" + ""| %s<%s>"", + *level, *codepage_stag, tag_new_known, + Indent (*level), tag_new_literal); + /* Tag string already looked up earlier! */ + off++; + } else { /* LITERAL tag */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| LITERAL_C (Literal Tag) (.C) "" + ""| %s<%s>"", + *level, *codepage_stag, Indent (*level), + tag_new_literal); + off += 1 + tag_len; + } + } + /* The data that follows in the parsing process + * represents content for the opening tag + * we've just processed in the lines above. + * Next time we encounter a tag with content: recurse + */ + parsing_tag_content = TRUE; + DebugLog((""Tag in Tag - No recursion this time! (off = %u)\n"", off)); + } + } else { /* No Content */ + DebugLog(("" in Tag - No recursion! (off = %u)\n"", off)); + (*level)++; + if (peek & 0x80) { /* No Content, Attribute list present */ + if (tag_new_known) { /* Known tag */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| Known Tag 0x%02X (A.) "" + ""| %s<%s"", + *level, *codepage_stag, tag_new_known, + Indent (*level), tag_new_literal); + /* Tag string already looked up earlier! */ + off++; + len = parse_wbxml_attribute_list_defined (tree, tvb, + off, str_tbl, *level, codepage_attr, map); + /* Check that there is still room in packet */ + off += len; + if (off > tvb_len) { + DebugLog((""STAG: level = %u, ThrowException: len = %u (short frame)\n"", *level, off - offset)); + /* + * TODO - Do we need to free g_malloc()ed memory? + */ + THROW(ReportedBoundsError); + } + proto_tree_add_text (tree, tvb, off-1, 1, + "" %3d | Tag | T %3d "" + ""| END (Known Tag) "" + ""| %s/>"", + *level, *codepage_stag, Indent (*level)); + } else { /* LITERAL tag */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| LITERAL_A (Literal Tag) (A.) "" + ""| %s<%s"", + *level, *codepage_stag, Indent (*level), tag_new_literal); + off += 1 + tag_len; + len = parse_wbxml_attribute_list_defined (tree, tvb, + off, str_tbl, *level, codepage_attr, map); + /* Check that there is still room in packet */ + off += len; + if (off >= tvb_len) { + DebugLog((""STAG: level = %u, ThrowException: len = %u (short frame)\n"", *level, off - offset)); + /* + * TODO - Do we need to free g_malloc()ed memory? + */ + THROW(ReportedBoundsError); + } + proto_tree_add_text (tree, tvb, off-1, 1, + "" %3d | Tag | T %3d "" + ""| END (Literal Tag) "" + ""| %s/>"", + *level, *codepage_stag, Indent (*level)); + } + } else { /* No Content, No Attribute list */ + if (tag_new_known) { /* Known tag */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| Known Tag 0x%02x (..) "" + ""| %s<%s />"", + *level, *codepage_stag, tag_new_known, + Indent (*level), tag_new_literal); + /* Tag string already looked up earlier! */ + off++; + } else { /* LITERAL tag */ + proto_tree_add_text (tree, tvb, off, 1, + "" %3d | Tag | T %3d "" + ""| LITERAL (Literal Tag) (..) "" + ""| %s<%s />"", + *level, *codepage_stag, Indent (*level), + tag_new_literal); + off += 1 + tag_len; + } + } + (*level)--; + /* TODO: Do I have to reset code page here? */ + } + } /* if (tag & 0x3F) >= 5 */ + if (off < last_off) { + THROW(ReportedBoundsError); + } + last_off = off; + } /* while */ + DebugLog((""STAG: level = %u, Return: len = %u (end of function body)\n"", *level, off - offset)); + return (off - offset); +} +","@@ -7304,7 +7304,7 @@ parse_wbxml_tag_defined (proto_tree *tree, tvbuff_t *tvb, guint32 offset, + const wbxml_decoding *map) + { + guint32 tvb_len = tvb_reported_length (tvb); +- guint32 off = offset; ++ guint32 off = offset, last_off; + guint32 len; + guint str_len; + guint32 ent; +@@ -7323,6 +7323,7 @@ parse_wbxml_tag_defined (proto_tree *tree, tvbuff_t *tvb, guint32 offset, + tag_save_literal = NULL; /* Prevents compiler warning */ + + DebugLog((""parse_wbxml_tag_defined (level = %u, offset = %u)\n"", *level, offset)); ++ last_off = off; + while (off < tvb_len) { + peek = tvb_get_guint8 (tvb, off); + DebugLog((""STAG: (top of while) level = %3u, peek = 0x%02X, off = %u, tvb_len = %u\n"", *level, peek, off, tvb_len)); +@@ -7694,6 +7695,10 @@ parse_wbxml_tag_defined (proto_tree *tree, tvbuff_t *tvb, guint32 offset, + /* TODO: Do I have to reset code page here? */ + } + } /* if (tag & 0x3F) >= 5 */ ++ if (off < last_off) { ++ THROW(ReportedBoundsError); ++ } ++ last_off = off; + } /* while */ + DebugLog((""STAG: level = %u, Return: len = %u (end of function body)\n"", *level, off - offset)); + return (off - offset); +@@ -7711,7 +7716,7 @@ parse_wbxml_tag (proto_tree *tree, tvbuff_t *tvb, guint32 offset, + guint8 *codepage_stag, guint8 *codepage_attr) + { + guint32 tvb_len = tvb_reported_length (tvb); +- guint32 off = offset; ++ guint32 off = offset, last_off; + guint32 len; + guint str_len; + guint32 ent; +@@ -7732,6 +7737,7 @@ parse_wbxml_tag (proto_tree *tree, tvbuff_t *tvb, guint32 offset, + tag_save_literal = NULL; /* Prevents compiler warning */ + + DebugLog((""parse_wbxml_tag (level = %u, offset = %u)\n"", *level, offset)); ++ last_off = off; + while (off < tvb_len) { + peek = tvb_get_guint8 (tvb, off); + DebugLog((""STAG: (top of while) level = %3u, peek = 0x%02X, off = %u, tvb_len = %u\n"", *level, peek, off, tvb_len)); +@@ -8091,6 +8097,10 @@ parse_wbxml_tag (proto_tree *tree, tvbuff_t *tvb, guint32 offset, + /* TODO: Do I have to reset code page here? */ + } + } /* if (tag & 0x3F) >= 5 */ ++ if (off < last_off) { ++ THROW(ReportedBoundsError); ++ } ++ last_off = off; + } /* while */ + DebugLog((""STAG: level = %u, Return: len = %u (end of function body)\n"", + *level, off - offset)); +@@ -8126,7 +8136,7 @@ parse_wbxml_attribute_list_defined (proto_tree *tree, tvbuff_t *tvb, + const wbxml_decoding *map) + { + guint32 tvb_len = tvb_reported_length (tvb); +- guint32 off = offset; ++ guint32 off = offset, last_off; + guint32 len; + guint str_len; + guint32 ent; +@@ -8138,6 +8148,7 @@ parse_wbxml_attribute_list_defined (proto_tree *tree, tvbuff_t *tvb, + DebugLog((""parse_wbxml_attr_defined (level = %u, offset = %u)\n"", + level, offset)); + /* Parse attributes */ ++ last_off = off; + while (off < tvb_len) { + peek = tvb_get_guint8 (tvb, off); + DebugLog((""ATTR: (top of while) level = %3u, peek = 0x%02X, "" +@@ -8330,6 +8341,10 @@ parse_wbxml_attribute_list_defined (proto_tree *tree, tvbuff_t *tvb, + off++; + } + } ++ if (off < last_off) { ++ THROW(ReportedBoundsError); ++ } ++ last_off = off; + } /* End WHILE */ + DebugLog((""ATTR: level = %u, Return: len = %u (end of function body)\n"", + level, off - offset)); +@@ -8350,7 +8365,7 @@ parse_wbxml_attribute_list (proto_tree *tree, tvbuff_t *tvb, + guint32 offset, guint32 str_tbl, guint8 level, guint8 *codepage_attr) + { + guint32 tvb_len = tvb_reported_length (tvb); +- guint32 off = offset; ++ guint32 off = offset, last_off; + guint32 len; + guint str_len; + guint32 ent; +@@ -8359,6 +8374,7 @@ parse_wbxml_attribute_list (proto_tree *tree, tvbuff_t *tvb, + + DebugLog((""parse_wbxml_attr (level = %u, offset = %u)\n"", level, offset)); + /* Parse attributes */ ++ last_off = off; + while (off < tvb_len) { + peek = tvb_get_guint8 (tvb, off); + DebugLog((""ATTR: (top of while) level = %3u, peek = 0x%02X, "" +@@ -8516,6 +8532,10 @@ parse_wbxml_attribute_list (proto_tree *tree, tvbuff_t *tvb, + off++; + } + } ++ if (off < last_off) { ++ THROW(ReportedBoundsError); ++ } ++ last_off = off; + } /* End WHILE */ + DebugLog((""ATTR: level = %u, Return: len = %u (end of function body)\n"", + level, off - offset));",4840,5171,6144 +18273,"static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ + Image *image, *image2=NULL, + *rotated_image; + register Quantum *q; + + unsigned int status; + MATHeader MATLAB_HDR; + size_t size; + size_t CellType; + QuantumInfo *quantum_info; + ImageInfo *clone_info; + int i; + ssize_t ldblk; + unsigned char *BImgBuff = NULL; + double MinVal, MaxVal; + unsigned z, z2; + unsigned Frames; + int logging; + int sample_size; + MagickOffsetType filepos=0x80; + + unsigned int (*ReadBlobXXXLong)(Image *image); + unsigned short (*ReadBlobXXXShort)(Image *image); + void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); + void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); + + + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickCoreSignature); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + logging = LogMagickEvent(CoderEvent,GetMagickModule(),""enter""); + + /* + Open image file. + */ + image = AcquireImage(image_info,exception); + image2 = (Image *) NULL; + + status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); + if (status == MagickFalse) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + /* + Read MATLAB image. + */ + quantum_info=(QuantumInfo *) NULL; + clone_info=(ImageInfo *) NULL; + if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + if (strncmp(MATLAB_HDR.identific,""MATLAB"",6) != 0) + { + image=ReadMATImageV4(image_info,image,exception); + if (image == NULL) + { + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + return((Image *) NULL); + } + goto END_OF_READING; + } + MATLAB_HDR.Version = ReadBlobLSBShort(image); + if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + + if (logging) + (void) LogMagickEvent(CoderEvent,GetMagickModule(),"" Endian %c%c"", + MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); + if (!strncmp(MATLAB_HDR.EndianIndicator, ""IM"", 2)) + { + ReadBlobXXXLong = ReadBlobLSBLong; + ReadBlobXXXShort = ReadBlobLSBShort; + ReadBlobDoublesXXX = ReadBlobDoublesLSB; + ReadBlobFloatsXXX = ReadBlobFloatsLSB; + image->endian = LSBEndian; + } + else if (!strncmp(MATLAB_HDR.EndianIndicator, ""MI"", 2)) + { + ReadBlobXXXLong = ReadBlobMSBLong; + ReadBlobXXXShort = ReadBlobMSBShort; + ReadBlobDoublesXXX = ReadBlobDoublesMSB; + ReadBlobFloatsXXX = ReadBlobFloatsMSB; + image->endian = MSBEndian; + } + else + { +MATLAB_KO: + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + } + + filepos = TellBlob(image); + while(!EOFBlob(image)) /* object parser loop */ + { + Frames = 1; + if (filepos != (unsigned int) filepos) + break; + if(SeekBlob(image,filepos,SEEK_SET) != filepos) break; + /* printf(""pos=%X\n"",TellBlob(image)); */ + + MATLAB_HDR.DataType = ReadBlobXXXLong(image); + if(EOFBlob(image)) break; + MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); + if(EOFBlob(image)) break; + if((MagickSizeType) (MATLAB_HDR.ObjectSize+filepos) > GetBlobSize(image)) + goto MATLAB_KO; + filepos += (MagickOffsetType) MATLAB_HDR.ObjectSize + 4 + 4; + + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + clone_info=CloneImageInfo(image_info); + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + image2 = image; +#if defined(MAGICKCORE_ZLIB_DELEGATE) + if(MATLAB_HDR.DataType == miCOMPRESSED) + { + image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception); + if(image2==NULL) continue; + MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ + } +#endif + + if (MATLAB_HDR.DataType != miMATRIX) + { + clone_info=DestroyImageInfo(clone_info); +#if defined(MAGICKCORE_ZLIB_DELEGATE) + if (image2 != image) + DeleteImageFromList(&image2); +#endif + continue; /* skip another objects. */ + } + + MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); + MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); + + MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); + MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; + MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; + + MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); + if(image!=image2) + MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ + MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); + MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); + MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); + MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); + + + switch(MATLAB_HDR.DimFlag) + { + case 8: z2=z=1; break; /* 2D matrix*/ + case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ + (void) ReadBlobXXXLong(image2); + if(z!=3) + { + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + ThrowReaderException(CoderError, + ""MultidimensionalMatricesAreNotSupported""); + } + break; + case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ + if(z!=3 && z!=1) + { + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + ThrowReaderException(CoderError, + ""MultidimensionalMatricesAreNotSupported""); + } + Frames = ReadBlobXXXLong(image2); + if (Frames == 0) + { + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + } + if (AcquireMagickResource(ListLengthResource,Frames) == MagickFalse) + { + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + ThrowReaderException(ResourceLimitError,""ListLengthExceedsLimit""); + } + break; + default: + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + ThrowReaderException(CoderError, ""MultidimensionalMatricesAreNotSupported""); + } + + MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); + MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); + + if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), + ""MATLAB_HDR.StructureClass %d"",MATLAB_HDR.StructureClass); + if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && + MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ + MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ + MATLAB_HDR.StructureClass != mxINT8_CLASS && + MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ + MATLAB_HDR.StructureClass != mxINT16_CLASS && + MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ + MATLAB_HDR.StructureClass != mxINT32_CLASS && + MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ + MATLAB_HDR.StructureClass != mxINT64_CLASS && + MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ + { + if ((image2 != (Image*) NULL) && (image2 != image)) + { + CloseBlob(image2); + DeleteImageFromList(&image2); + } + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + ThrowReaderException(CoderError,""UnsupportedCellTypeInTheMatrix""); + } + + switch (MATLAB_HDR.NameFlag) + { + case 0: + size = ReadBlobXXXLong(image2); /* Object name string size */ + size = 4 * (((size_t) size + 3 + 1) / 4); + (void) SeekBlob(image2, size, SEEK_CUR); + break; + case 1: + case 2: + case 3: + case 4: + (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ + break; + default: + goto MATLAB_KO; + } + + CellType = ReadBlobXXXLong(image2); /* Additional object type */ + if (logging) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + ""MATLAB_HDR.CellType: %.20g"",(double) CellType); + + /* data size */ + if (ReadBlob(image2, 4, (unsigned char *) &size) != 4) + goto MATLAB_KO; + + NEXT_FRAME: + switch (CellType) + { + case miINT8: + case miUINT8: + sample_size = 8; + if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) + image->depth = 1; + else + image->depth = 8; /* Byte type cell */ + ldblk = (ssize_t) MATLAB_HDR.SizeX; + break; + case miINT16: + case miUINT16: + sample_size = 16; + image->depth = 16; /* Word type cell */ + ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); + break; + case miINT32: + case miUINT32: + sample_size = 32; + image->depth = 32; /* Dword type cell */ + ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); + break; + case miINT64: + case miUINT64: + sample_size = 64; + image->depth = 64; /* Qword type cell */ + ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); + break; + case miSINGLE: + sample_size = 32; + image->depth = 32; /* double type cell */ + (void) SetImageOption(clone_info,""quantum:format"",""floating-point""); + if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) + { /* complex float type cell */ + } + ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); + break; + case miDOUBLE: + sample_size = 64; + image->depth = 64; /* double type cell */ + (void) SetImageOption(clone_info,""quantum:format"",""floating-point""); +DisableMSCWarning(4127) + if (sizeof(double) != 8) +RestoreMSCWarning + { + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + ThrowReaderException(CoderError, ""IncompatibleSizeOfDouble""); + } + if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) + { /* complex double type cell */ + } + ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); + break; + default: + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + if (clone_info) + clone_info=DestroyImageInfo(clone_info); + ThrowReaderException(CoderError, ""UnsupportedCellTypeInTheMatrix""); + } + (void) sample_size; + image->columns = MATLAB_HDR.SizeX; + image->rows = MATLAB_HDR.SizeY; + image->colors = GetQuantumRange(image->depth); + if (image->columns == 0 || image->rows == 0) + goto MATLAB_KO; + if((unsigned int)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize) + goto MATLAB_KO; + /* Image is gray when no complex flag is set and 2D Matrix */ + if ((MATLAB_HDR.DimFlag == 8) && + ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) + { + image->type=GrayscaleType; + SetImageColorspace(image,GRAYColorspace,exception); + } + + + /* + If ping is true, then only set image size and colors without + reading any image data. + */ + if (image_info->ping) + { + size_t temp = image->columns; + image->columns = image->rows; + image->rows = temp; + goto done_reading; /* !!!!!! BAD !!!! */ + } + status=SetImageExtent(image,image->columns,image->rows,exception); + if (status == MagickFalse) + { + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + return(DestroyImageList(image)); + } + (void) SetImageBackgroundColor(image,exception); + quantum_info=AcquireQuantumInfo(clone_info,image); + if (quantum_info == (QuantumInfo *) NULL) + { + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + } + + /* ----- Load raster data ----- */ + BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */ + if (BImgBuff == NULL) + { + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + if (quantum_info != (QuantumInfo *) NULL) + quantum_info=DestroyQuantumInfo(quantum_info); + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + } + (void) memset(BImgBuff,0,ldblk*sizeof(double)); + + MinVal = 0; + MaxVal = 0; + if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ + { + CalcMinMax(image2,image_info->endian,MATLAB_HDR.SizeX,MATLAB_HDR.SizeY, + CellType,ldblk,BImgBuff,&quantum_info->minimum, + &quantum_info->maximum); + } + + /* Main loop for reading all scanlines */ + if(z==1) z=0; /* read grey scanlines */ + /* else read color scanlines */ + do + { + for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) + { + q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); + if (q == (Quantum *) NULL) + { + if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), + "" MAT set image pixels returns unexpected NULL on a row %u."", (unsigned)(MATLAB_HDR.SizeY-i-1)); + goto done_reading; /* Skip image rotation, when cannot set image pixels */ + } + if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) + { + if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), + "" MAT cannot read scanrow %u from a file."", (unsigned)(MATLAB_HDR.SizeY-i-1)); + goto ExitLoop; + } + if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) + { + FixLogical((unsigned char *)BImgBuff,ldblk); + if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) + { +ImportQuantumPixelsFailed: + if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), + "" MAT failed to ImportQuantumPixels for a row %u"", (unsigned)(MATLAB_HDR.SizeY-i-1)); + break; + } + } + else + { + if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) + goto ImportQuantumPixelsFailed; + + + if (z<=1 && /* fix only during a last pass z==0 || z==1 */ + (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) + FixSignedValues(image,q,MATLAB_HDR.SizeX); + } + + if (!SyncAuthenticPixels(image,exception)) + { + if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), + "" MAT failed to sync image pixels for a row %u"", (unsigned)(MATLAB_HDR.SizeY-i-1)); + goto ExitLoop; + } + } + } while(z-- >= 2); +ExitLoop: + if (i != (long) MATLAB_HDR.SizeY) + goto END_OF_READING; + + /* Read complex part of numbers here */ + if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) + { /* Find Min and Max Values for complex parts of floats */ + CellType = ReadBlobXXXLong(image2); /* Additional object type */ + i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ + + if (CellType==miDOUBLE || CellType==miSINGLE) + { + CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); + } + + if (CellType==miDOUBLE) + for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) + { + ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); + if (EOFBlob(image) != MagickFalse) + break; + InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal, + exception); + } + + if (CellType==miSINGLE) + for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) + { + ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); + if (EOFBlob(image) != MagickFalse) + break; + InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal, + exception); + } + } + + /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ + if ((MATLAB_HDR.DimFlag == 8) && + ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) + image->type=GrayscaleType; + if (image->depth == 1) + image->type=BilevelType; + + if(image2==image) + image2 = NULL; /* Remove shadow copy to an image before rotation. */ + + /* Rotate image. */ + rotated_image = RotateImage(image, 90.0, exception); + if (rotated_image != (Image *) NULL) + { + /* Remove page offsets added by RotateImage */ + rotated_image->page.x=0; + rotated_image->page.y=0; + rotated_image->colors = image->colors; + DestroyBlob(rotated_image); + rotated_image->blob=ReferenceBlob(image->blob); + AppendImageToList(&image,rotated_image); + DeleteImageFromList(&image); + } + +done_reading: + + if(image2!=NULL) + if(image2!=image) + { + DeleteImageFromList(&image2); + if(clone_info) + { + if(clone_info->file) + { + fclose(clone_info->file); + clone_info->file = NULL; + (void) remove_utf8(clone_info->filename); + } + } + } + if (EOFBlob(image) != MagickFalse) + break; + + /* Allocate next image structure. */ + AcquireNextImage(image_info,image,exception); + if (image->next == (Image *) NULL) break; + image=SyncNextImageInList(image); + image->columns=image->rows=0; + image->colors=0; + + /* row scan buffer is no longer needed */ + RelinquishMagickMemory(BImgBuff); + BImgBuff = NULL; + if (quantum_info != (QuantumInfo *) NULL) + quantum_info=DestroyQuantumInfo(quantum_info); + + if(--Frames>0) + { + z = z2; + if(image2==NULL) image2 = image; + if(!EOFBlob(image) && TellBlob(image)file) + { + fclose(clone_info->file); + clone_info->file = NULL; + (void) remove_utf8(clone_info->filename); + } + } + } + + if (clone_info) + clone_info=DestroyImageInfo(clone_info); + } + +END_OF_READING: + RelinquishMagickMemory(BImgBuff); + if (quantum_info != (QuantumInfo *) NULL) + quantum_info=DestroyQuantumInfo(quantum_info); + CloseBlob(image); + + + { + Image *p; + ssize_t scene=0; + + /* + Rewind list, removing any empty images while rewinding. + */ + p=image; + image=NULL; + while (p != (Image *) NULL) + { + Image *tmp=p; + if ((p->rows == 0) || (p->columns == 0)) { + p=p->previous; + if (tmp == image2) + image2=(Image *) NULL; + DeleteImageFromList(&tmp); + } else { + image=p; + p=p->previous; + } + } + + /* + Fix scene numbers + */ + for (p=image; p != (Image *) NULL; p=p->next) + p->scene=scene++; + } + + if(clone_info != NULL) /* cleanup garbage file from compression */ + { + if(clone_info->file) + { + fclose(clone_info->file); + clone_info->file = NULL; + (void) remove_utf8(clone_info->filename); + } + DestroyImageInfo(clone_info); + clone_info = NULL; + } + if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),""return""); + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + if (image == (Image *) NULL) + ThrowReaderException(CorruptImageError,""ImproperImageHeader"") + return(image); +} +",1,"static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ + Image *image, *image2=NULL, + *rotated_image; + register Quantum *q; + + unsigned int status; + MATHeader MATLAB_HDR; + size_t size; + size_t CellType; + QuantumInfo *quantum_info; + ImageInfo *clone_info; + int i; + ssize_t ldblk; + unsigned char *BImgBuff = NULL; + double MinVal, MaxVal; + unsigned z, z2; + unsigned Frames; + int logging; + int sample_size; + MagickOffsetType filepos=0x80; + + unsigned int (*ReadBlobXXXLong)(Image *image); + unsigned short (*ReadBlobXXXShort)(Image *image); + void (*ReadBlobDoublesXXX)(Image * image, size_t len, double *data); + void (*ReadBlobFloatsXXX)(Image * image, size_t len, float *data); + + + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickCoreSignature); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + logging = LogMagickEvent(CoderEvent,GetMagickModule(),""enter""); + + /* + Open image file. + */ + image = AcquireImage(image_info,exception); + image2 = (Image *) NULL; + + status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception); + if (status == MagickFalse) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + /* + Read MATLAB image. + */ + quantum_info=(QuantumInfo *) NULL; + clone_info=(ImageInfo *) NULL; + if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + if (strncmp(MATLAB_HDR.identific,""MATLAB"",6) != 0) + { + image=ReadMATImageV4(image_info,image,exception); + if (image == NULL) + { + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + return((Image *) NULL); + } + goto END_OF_READING; + } + MATLAB_HDR.Version = ReadBlobLSBShort(image); + if(ReadBlob(image,2,(unsigned char *) &MATLAB_HDR.EndianIndicator) != 2) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + + if (logging) + (void) LogMagickEvent(CoderEvent,GetMagickModule(),"" Endian %c%c"", + MATLAB_HDR.EndianIndicator[0],MATLAB_HDR.EndianIndicator[1]); + if (!strncmp(MATLAB_HDR.EndianIndicator, ""IM"", 2)) + { + ReadBlobXXXLong = ReadBlobLSBLong; + ReadBlobXXXShort = ReadBlobLSBShort; + ReadBlobDoublesXXX = ReadBlobDoublesLSB; + ReadBlobFloatsXXX = ReadBlobFloatsLSB; + image->endian = LSBEndian; + } + else if (!strncmp(MATLAB_HDR.EndianIndicator, ""MI"", 2)) + { + ReadBlobXXXLong = ReadBlobMSBLong; + ReadBlobXXXShort = ReadBlobMSBShort; + ReadBlobDoublesXXX = ReadBlobDoublesMSB; + ReadBlobFloatsXXX = ReadBlobFloatsMSB; + image->endian = MSBEndian; + } + else + { +MATLAB_KO: + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + } + + filepos = TellBlob(image); + while(filepos < GetBlobSize(image) && !EOFBlob(image)) /* object parser loop */ + { + Frames = 1; + if(filepos > GetBlobSize(image) || filepos < 0) + break; + if(SeekBlob(image,filepos,SEEK_SET) != filepos) break; + /* printf(""pos=%X\n"",TellBlob(image)); */ + + MATLAB_HDR.DataType = ReadBlobXXXLong(image); + if(EOFBlob(image)) break; + MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); + if(EOFBlob(image)) break; + if((MagickSizeType) (MATLAB_HDR.ObjectSize+filepos) >= GetBlobSize(image)) + goto MATLAB_KO; + filepos += (MagickOffsetType) MATLAB_HDR.ObjectSize + 4 + 4; + + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + clone_info=CloneImageInfo(image_info); + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + image2 = image; +#if defined(MAGICKCORE_ZLIB_DELEGATE) + if(MATLAB_HDR.DataType == miCOMPRESSED) + { + image2 = decompress_block(image,&MATLAB_HDR.ObjectSize,clone_info,exception); + if(image2==NULL) continue; + MATLAB_HDR.DataType = ReadBlobXXXLong(image2); /* replace compressed object type. */ + } +#endif + + if (MATLAB_HDR.DataType != miMATRIX) + { + clone_info=DestroyImageInfo(clone_info); +#if defined(MAGICKCORE_ZLIB_DELEGATE) + if (image2 != image) + DeleteImageFromList(&image2); +#endif + continue; /* skip another objects. */ + } + + MATLAB_HDR.unknown1 = ReadBlobXXXLong(image2); + MATLAB_HDR.unknown2 = ReadBlobXXXLong(image2); + + MATLAB_HDR.unknown5 = ReadBlobXXXLong(image2); + MATLAB_HDR.StructureClass = MATLAB_HDR.unknown5 & 0xFF; + MATLAB_HDR.StructureFlag = (MATLAB_HDR.unknown5>>8) & 0xFF; + + MATLAB_HDR.unknown3 = ReadBlobXXXLong(image2); + if(image!=image2) + MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); /* ??? don't understand why ?? */ + MATLAB_HDR.unknown4 = ReadBlobXXXLong(image2); + MATLAB_HDR.DimFlag = ReadBlobXXXLong(image2); + MATLAB_HDR.SizeX = ReadBlobXXXLong(image2); + MATLAB_HDR.SizeY = ReadBlobXXXLong(image2); + + + switch(MATLAB_HDR.DimFlag) + { + case 8: z2=z=1; break; /* 2D matrix*/ + case 12: z2=z = ReadBlobXXXLong(image2); /* 3D matrix RGB*/ + (void) ReadBlobXXXLong(image2); + if(z!=3) + { + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + ThrowReaderException(CoderError, + ""MultidimensionalMatricesAreNotSupported""); + } + break; + case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */ + if(z!=3 && z!=1) + { + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + ThrowReaderException(CoderError, + ""MultidimensionalMatricesAreNotSupported""); + } + Frames = ReadBlobXXXLong(image2); + if (Frames == 0) + { + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + } + if (AcquireMagickResource(ListLengthResource,Frames) == MagickFalse) + { + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + ThrowReaderException(ResourceLimitError,""ListLengthExceedsLimit""); + } + break; + default: + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + ThrowReaderException(CoderError, ""MultidimensionalMatricesAreNotSupported""); + } + + MATLAB_HDR.Flag1 = ReadBlobXXXShort(image2); + MATLAB_HDR.NameFlag = ReadBlobXXXShort(image2); + + if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), + ""MATLAB_HDR.StructureClass %d"",MATLAB_HDR.StructureClass); + if (MATLAB_HDR.StructureClass != mxCHAR_CLASS && + MATLAB_HDR.StructureClass != mxSINGLE_CLASS && /* float + complex float */ + MATLAB_HDR.StructureClass != mxDOUBLE_CLASS && /* double + complex double */ + MATLAB_HDR.StructureClass != mxINT8_CLASS && + MATLAB_HDR.StructureClass != mxUINT8_CLASS && /* uint8 + uint8 3D */ + MATLAB_HDR.StructureClass != mxINT16_CLASS && + MATLAB_HDR.StructureClass != mxUINT16_CLASS && /* uint16 + uint16 3D */ + MATLAB_HDR.StructureClass != mxINT32_CLASS && + MATLAB_HDR.StructureClass != mxUINT32_CLASS && /* uint32 + uint32 3D */ + MATLAB_HDR.StructureClass != mxINT64_CLASS && + MATLAB_HDR.StructureClass != mxUINT64_CLASS) /* uint64 + uint64 3D */ + { + if ((image2 != (Image*) NULL) && (image2 != image)) + { + CloseBlob(image2); + DeleteImageFromList(&image2); + } + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + ThrowReaderException(CoderError,""UnsupportedCellTypeInTheMatrix""); + } + + switch (MATLAB_HDR.NameFlag) + { + case 0: + size = ReadBlobXXXLong(image2); /* Object name string size */ + size = 4 * (((size_t) size + 3 + 1) / 4); + (void) SeekBlob(image2, size, SEEK_CUR); + break; + case 1: + case 2: + case 3: + case 4: + (void) ReadBlob(image2, 4, (unsigned char *) &size); /* Object name string */ + break; + default: + goto MATLAB_KO; + } + + CellType = ReadBlobXXXLong(image2); /* Additional object type */ + if (logging) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + ""MATLAB_HDR.CellType: %.20g"",(double) CellType); + + /* data size */ + if (ReadBlob(image2, 4, (unsigned char *) &size) != 4) + goto MATLAB_KO; + + NEXT_FRAME: + switch (CellType) + { + case miINT8: + case miUINT8: + sample_size = 8; + if(MATLAB_HDR.StructureFlag & FLAG_LOGICAL) + image->depth = 1; + else + image->depth = 8; /* Byte type cell */ + ldblk = (ssize_t) MATLAB_HDR.SizeX; + break; + case miINT16: + case miUINT16: + sample_size = 16; + image->depth = 16; /* Word type cell */ + ldblk = (ssize_t) (2 * MATLAB_HDR.SizeX); + break; + case miINT32: + case miUINT32: + sample_size = 32; + image->depth = 32; /* Dword type cell */ + ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); + break; + case miINT64: + case miUINT64: + sample_size = 64; + image->depth = 64; /* Qword type cell */ + ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); + break; + case miSINGLE: + sample_size = 32; + image->depth = 32; /* double type cell */ + (void) SetImageOption(clone_info,""quantum:format"",""floating-point""); + if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) + { /* complex float type cell */ + } + ldblk = (ssize_t) (4 * MATLAB_HDR.SizeX); + break; + case miDOUBLE: + sample_size = 64; + image->depth = 64; /* double type cell */ + (void) SetImageOption(clone_info,""quantum:format"",""floating-point""); +DisableMSCWarning(4127) + if (sizeof(double) != 8) +RestoreMSCWarning + { + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + ThrowReaderException(CoderError, ""IncompatibleSizeOfDouble""); + } + if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) + { /* complex double type cell */ + } + ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX); + break; + default: + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + if (clone_info) + clone_info=DestroyImageInfo(clone_info); + ThrowReaderException(CoderError, ""UnsupportedCellTypeInTheMatrix""); + } + (void) sample_size; + image->columns = MATLAB_HDR.SizeX; + image->rows = MATLAB_HDR.SizeY; + image->colors = GetQuantumRange(image->depth); + if (image->columns == 0 || image->rows == 0) + goto MATLAB_KO; + if((unsigned int)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize) + goto MATLAB_KO; + /* Image is gray when no complex flag is set and 2D Matrix */ + if ((MATLAB_HDR.DimFlag == 8) && + ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) + { + image->type=GrayscaleType; + SetImageColorspace(image,GRAYColorspace,exception); + } + + + /* + If ping is true, then only set image size and colors without + reading any image data. + */ + if (image_info->ping) + { + size_t temp = image->columns; + image->columns = image->rows; + image->rows = temp; + goto done_reading; /* !!!!!! BAD !!!! */ + } + status=SetImageExtent(image,image->columns,image->rows,exception); + if (status == MagickFalse) + { + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + return(DestroyImageList(image)); + } + (void) SetImageBackgroundColor(image,exception); + quantum_info=AcquireQuantumInfo(clone_info,image); + if (quantum_info == (QuantumInfo *) NULL) + { + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + } + + /* ----- Load raster data ----- */ + BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */ + if (BImgBuff == NULL) + { + if (clone_info != (ImageInfo *) NULL) + clone_info=DestroyImageInfo(clone_info); + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + if (quantum_info != (QuantumInfo *) NULL) + quantum_info=DestroyQuantumInfo(quantum_info); + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + } + (void) memset(BImgBuff,0,ldblk*sizeof(double)); + + MinVal = 0; + MaxVal = 0; + if (CellType==miDOUBLE || CellType==miSINGLE) /* Find Min and Max Values for floats */ + { + CalcMinMax(image2,image_info->endian,MATLAB_HDR.SizeX,MATLAB_HDR.SizeY, + CellType,ldblk,BImgBuff,&quantum_info->minimum, + &quantum_info->maximum); + } + + /* Main loop for reading all scanlines */ + if(z==1) z=0; /* read grey scanlines */ + /* else read color scanlines */ + do + { + for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) + { + q=GetAuthenticPixels(image,0,MATLAB_HDR.SizeY-i-1,image->columns,1,exception); + if (q == (Quantum *) NULL) + { + if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), + "" MAT set image pixels returns unexpected NULL on a row %u."", (unsigned)(MATLAB_HDR.SizeY-i-1)); + goto done_reading; /* Skip image rotation, when cannot set image pixels */ + } + if(ReadBlob(image2,ldblk,(unsigned char *)BImgBuff) != (ssize_t) ldblk) + { + if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), + "" MAT cannot read scanrow %u from a file."", (unsigned)(MATLAB_HDR.SizeY-i-1)); + ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); + goto ExitLoop; + } + if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL)) + { + FixLogical((unsigned char *)BImgBuff,ldblk); + if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) + { +ImportQuantumPixelsFailed: + if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), + "" MAT failed to ImportQuantumPixels for a row %u"", (unsigned)(MATLAB_HDR.SizeY-i-1)); + break; + } + } + else + { + if(ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,z2qtype[z],BImgBuff,exception) <= 0) + goto ImportQuantumPixelsFailed; + + + if (z<=1 && /* fix only during a last pass z==0 || z==1 */ + (CellType==miINT8 || CellType==miINT16 || CellType==miINT32 || CellType==miINT64)) + FixSignedValues(image,q,MATLAB_HDR.SizeX); + } + + if (!SyncAuthenticPixels(image,exception)) + { + if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), + "" MAT failed to sync image pixels for a row %u"", (unsigned)(MATLAB_HDR.SizeY-i-1)); + goto ExitLoop; + } + } + } while(z-- >= 2); +ExitLoop: + if (i != (long) MATLAB_HDR.SizeY) + goto END_OF_READING; + + /* Read complex part of numbers here */ + if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX) + { /* Find Min and Max Values for complex parts of floats */ + CellType = ReadBlobXXXLong(image2); /* Additional object type */ + i = ReadBlobXXXLong(image2); /* size of a complex part - toss away*/ + + if (CellType==miDOUBLE || CellType==miSINGLE) + { + CalcMinMax(image2, image_info->endian, MATLAB_HDR.SizeX, MATLAB_HDR.SizeY, CellType, ldblk, BImgBuff, &MinVal, &MaxVal); + } + + if (CellType==miDOUBLE) + for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) + { + ReadBlobDoublesXXX(image2, ldblk, (double *)BImgBuff); + if (EOFBlob(image) != MagickFalse) + break; + InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal, + exception); + } + + if (CellType==miSINGLE) + for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++) + { + ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff); + if (EOFBlob(image) != MagickFalse) + break; + InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal, + exception); + } + } + + /* Image is gray when no complex flag is set and 2D Matrix AGAIN!!! */ + if ((MATLAB_HDR.DimFlag == 8) && + ((MATLAB_HDR.StructureFlag & FLAG_COMPLEX) == 0)) + image->type=GrayscaleType; + if (image->depth == 1) + image->type=BilevelType; + + if(image2==image) + image2 = NULL; /* Remove shadow copy to an image before rotation. */ + + /* Rotate image. */ + rotated_image = RotateImage(image, 90.0, exception); + if (rotated_image != (Image *) NULL) + { + /* Remove page offsets added by RotateImage */ + rotated_image->page.x=0; + rotated_image->page.y=0; + rotated_image->colors = image->colors; + DestroyBlob(rotated_image); + rotated_image->blob=ReferenceBlob(image->blob); + AppendImageToList(&image,rotated_image); + DeleteImageFromList(&image); + } + +done_reading: + + if(image2!=NULL) + if(image2!=image) + { + DeleteImageFromList(&image2); + if(clone_info) + { + if(clone_info->file) + { + fclose(clone_info->file); + clone_info->file = NULL; + (void) remove_utf8(clone_info->filename); + } + } + } + if (EOFBlob(image) != MagickFalse) + break; + + /* Allocate next image structure. */ + AcquireNextImage(image_info,image,exception); + if (image->next == (Image *) NULL) break; + image=SyncNextImageInList(image); + image->columns=image->rows=0; + image->colors=0; + + /* row scan buffer is no longer needed */ + RelinquishMagickMemory(BImgBuff); + BImgBuff = NULL; + if (quantum_info != (QuantumInfo *) NULL) + quantum_info=DestroyQuantumInfo(quantum_info); + + if(--Frames>0) + { + z = z2; + if(image2==NULL) image2 = image; + if(!EOFBlob(image) && TellBlob(image)file) + { + fclose(clone_info->file); + clone_info->file = NULL; + (void) remove_utf8(clone_info->filename); + } + } + } + + if (clone_info) + clone_info=DestroyImageInfo(clone_info); + } + +END_OF_READING: + RelinquishMagickMemory(BImgBuff); + if (quantum_info != (QuantumInfo *) NULL) + quantum_info=DestroyQuantumInfo(quantum_info); + CloseBlob(image); + + + { + Image *p; + ssize_t scene=0; + + /* + Rewind list, removing any empty images while rewinding. + */ + p=image; + image=NULL; + while (p != (Image *) NULL) + { + Image *tmp=p; + if ((p->rows == 0) || (p->columns == 0)) { + p=p->previous; + if (tmp == image2) + image2=(Image *) NULL; + DeleteImageFromList(&tmp); + } else { + image=p; + p=p->previous; + } + } + + /* + Fix scene numbers + */ + for (p=image; p != (Image *) NULL; p=p->next) + p->scene=scene++; + } + + if(clone_info != NULL) /* cleanup garbage file from compression */ + { + if(clone_info->file) + { + fclose(clone_info->file); + clone_info->file = NULL; + (void) remove_utf8(clone_info->filename); + } + DestroyImageInfo(clone_info); + clone_info = NULL; + } + if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(),""return""); + if ((image != image2) && (image2 != (Image *) NULL)) + image2=DestroyImage(image2); + if (image == (Image *) NULL) + ThrowReaderException(CorruptImageError,""ImproperImageHeader"") + return(image); +} +","@@ -641,6 +641,7 @@ static Image *ReadMATImageV4(const ImageInfo *image_info,Image *image, + Object parser loop. + */ + ldblk=ReadBlobLSBLong(image); ++ if(EOFBlob(image)) break; + if ((ldblk > 9999) || (ldblk < 0)) + break; + HDR.Type[3]=ldblk % 10; ldblk /= 10; /* T digit */ +@@ -961,10 +962,10 @@ static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) + } + + filepos = TellBlob(image); +- while(!EOFBlob(image)) /* object parser loop */ ++ while(filepos < GetBlobSize(image) && !EOFBlob(image)) /* object parser loop */ + { + Frames = 1; +- if (filepos != (unsigned int) filepos) ++ if(filepos > GetBlobSize(image) || filepos < 0) + break; + if(SeekBlob(image,filepos,SEEK_SET) != filepos) break; + /* printf(""pos=%X\n"",TellBlob(image)); */ +@@ -973,7 +974,7 @@ static Image *ReadMATImage(const ImageInfo *image_info,ExceptionInfo *exception) + if(EOFBlob(image)) break; + MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image); + if(EOFBlob(image)) break; +- if((MagickSizeType) (MATLAB_HDR.ObjectSize+filepos) > GetBlobSize(image)) ++ if((MagickSizeType) (MATLAB_HDR.ObjectSize+filepos) >= GetBlobSize(image)) + goto MATLAB_KO; + filepos += (MagickOffsetType) MATLAB_HDR.ObjectSize + 4 + 4; + +@@ -1276,6 +1277,7 @@ RestoreMSCWarning + { + if (logging) (void)LogMagickEvent(CoderEvent,GetMagickModule(), + "" MAT cannot read scanrow %u from a file."", (unsigned)(MATLAB_HDR.SizeY-i-1)); ++ ThrowReaderException(CorruptImageError,""UnexpectedEndOfFile""); + goto ExitLoop; + } + if((CellType==miINT8 || CellType==miUINT8) && (MATLAB_HDR.StructureFlag & FLAG_LOGICAL))",5638,5969,6144 +18025,"fp_set_per_packet_inf_from_conv(umts_fp_conversation_info_t *p_conv_data, + tvbuff_t *tvb, packet_info *pinfo, + proto_tree *tree _U_) +{ + fp_info *fpi; + guint8 tfi, c_t; + int offset = 0, i=0, j=0, num_tbs, chan, tb_size, tb_bit_off; + gboolean is_control_frame; + umts_mac_info *macinf; + rlc_info *rlcinf; + guint8 fake_lchid=0; + gint *cur_val=NULL; + + fpi = wmem_new0(wmem_file_scope(), fp_info); + p_add_proto_data(wmem_file_scope(), pinfo, proto_fp, 0, fpi); + + fpi->iface_type = p_conv_data->iface_type; + fpi->division = p_conv_data->division; + fpi->release = 7; /* Set values greater then the checks performed */ + fpi->release_year = 2006; + fpi->release_month = 12; + fpi->channel = p_conv_data->channel; + fpi->dch_crc_present = p_conv_data->dch_crc_present; + /*fpi->paging_indications;*/ + fpi->link_type = FP_Link_Ethernet; + +#if 0 + /*Only do this the first run, signals that we need to reset the RLC fragtable*/ + if (!pinfo->fd->flags.visited && p_conv_data->reset_frag ) { + fpi->reset_frag = p_conv_data->reset_frag; + p_conv_data->reset_frag = FALSE; + } +#endif + /* remember 'lower' UDP layer port information so we can later + * differentiate 'lower' UDP layer from 'user data' UDP layer */ + fpi->srcport = pinfo->srcport; + fpi->destport = pinfo->destport; + + fpi->com_context_id = p_conv_data->com_context_id; + + if (pinfo->link_dir == P2P_DIR_UL) { + fpi->is_uplink = TRUE; + } else { + fpi->is_uplink = FALSE; + } + + is_control_frame = tvb_get_guint8(tvb, offset) & 0x01; + + switch (fpi->channel) { + case CHANNEL_HSDSCH: /* HS-DSCH - High Speed Downlink Shared Channel */ + fpi->hsdsch_entity = p_conv_data->hsdsch_entity; + macinf = wmem_new0(wmem_file_scope(), umts_mac_info); + fpi->hsdsch_macflowd_id = p_conv_data->hsdsch_macdflow_id; + macinf->content[0] = hsdsch_macdflow_id_mac_content_map[p_conv_data->hsdsch_macdflow_id]; /*MAC_CONTENT_PS_DTCH;*/ + macinf->lchid[0] = p_conv_data->hsdsch_macdflow_id; + /*macinf->content[0] = lchId_type_table[p_conv_data->edch_lchId[0]];*/ + p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); + + rlcinf = wmem_new0(wmem_file_scope(), rlc_info); + + /*Figure out RLC_MODE based on MACd-flow-ID, basically MACd-flow-ID = 0 then it's SRB0 == UM else AM*/ + rlcinf->mode[0] = hsdsch_macdflow_id_rlc_map[p_conv_data->hsdsch_macdflow_id]; + + if (fpi->hsdsch_entity == hs /*&& !rlc_is_ciphered(pinfo)*/) { + for (i=0; ihrnti))) != NULL) { + j = 1 << i; + fpi->hsdhsch_macfdlow_is_mux[i] = j & *cur_val; + } else { + fpi->hsdhsch_macfdlow_is_mux[i] = FALSE; + } + + } + } + /* Make configurable ?(available in NBAP?) */ + /* urnti[MAX_RLC_CHANS] */ + /* + switch (p_conv_data->rlc_mode) { + case FP_RLC_TM: + rlcinf->mode[0] = RLC_TM; + break; + case FP_RLC_UM: + rlcinf->mode[0] = RLC_UM; + break; + case FP_RLC_AM: + rlcinf->mode[0] = RLC_AM; + break; + case FP_RLC_MODE_UNKNOWN: + default: + rlcinf->mode[0] = RLC_UNKNOWN_MODE; + break; + }*/ + /* rbid[MAX_RLC_CHANS] */ + /* For RLC re-assembly to work we urnti signaled from NBAP */ + rlcinf->urnti[0] = fpi->com_context_id; + rlcinf->li_size[0] = RLC_LI_7BITS; + rlcinf->ciphered[0] = FALSE; + rlcinf->deciphered[0] = FALSE; + p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); + + + return fpi; + + case CHANNEL_EDCH: + /*Most configuration is now done in the actual dissecting function*/ + macinf = wmem_new0(wmem_file_scope(), umts_mac_info); + rlcinf = wmem_new0(wmem_file_scope(), rlc_info); + fpi->no_ddi_entries = p_conv_data->no_ddi_entries; + for (i=0; ino_ddi_entries; i++) { + fpi->edch_ddi[i] = p_conv_data->edch_ddi[i]; /*Set the DDI value*/ + fpi->edch_macd_pdu_size[i] = p_conv_data->edch_macd_pdu_size[i]; /*Set the size*/ + fpi->edch_lchId[i] = p_conv_data->edch_lchId[i]; /*Set the channel id for this entry*/ + /*macinf->content[i] = lchId_type_table[p_conv_data->edch_lchId[i]]; */ /*Set the proper Content type for the mac layer.*/ + /* rlcinf->mode[i] = lchId_rlc_map[p_conv_data->edch_lchId[i]];*/ /* Set RLC mode by lchid to RLC_MODE map in nbap.h */ + + } + fpi->edch_type = p_conv_data->edch_type; + + /* macinf = wmem_new0(wmem_file_scope(), umts_mac_info); + macinf->content[0] = MAC_CONTENT_PS_DTCH;*/ + p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); + + + /* For RLC re-assembly to work we need a urnti signaled from NBAP */ + rlcinf->urnti[0] = fpi->com_context_id; + /* rlcinf->mode[0] = RLC_AM;*/ + rlcinf->li_size[0] = RLC_LI_7BITS; + rlcinf->ciphered[0] = FALSE; + rlcinf->deciphered[0] = FALSE; + + p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); + + return fpi; + + case CHANNEL_PCH: + fpi->paging_indications = p_conv_data->paging_indications; + fpi->num_chans = p_conv_data->num_dch_in_flow; + /* Set offset to point to first TFI + */ + if (is_control_frame) { + /* control frame, we're done */ + return fpi; + } + /* Set offset to TFI */ + offset = 3; + break; + case CHANNEL_DCH: + fpi->num_chans = p_conv_data->num_dch_in_flow; + if (is_control_frame) { + /* control frame, we're done */ + return fpi; + } + + rlcinf = wmem_new0(wmem_file_scope(), rlc_info); + macinf = wmem_new0(wmem_file_scope(), umts_mac_info); + offset = 2; /*To correctly read the tfi*/ + fakes = 5; /* Reset fake counter. */ + for (chan=0; chan < fpi->num_chans; chan++) { /*Iterate over the what channels*/ + /*Iterate over the transport blocks*/ + /*tfi = tvb_get_guint8(tvb, offset);*/ + /*TFI is 5 bits according to 3GPP TS 25.321, paragraph 6.2.4.4*/ + tfi = tvb_get_bits8(tvb, 3+offset*8, 5); + + /*Figure out the number of tbs and size*/ + num_tbs = (fpi->is_uplink) ? p_conv_data->fp_dch_channel_info[chan].ul_chan_num_tbs[tfi] : p_conv_data->fp_dch_channel_info[chan].dl_chan_num_tbs[tfi]; + tb_size= (fpi->is_uplink) ? p_conv_data->fp_dch_channel_info[i].ul_chan_tf_size[tfi] : p_conv_data->fp_dch_channel_info[i].dl_chan_tf_size[tfi]; + + /*TODO: This stuff has to be reworked!*/ + /*Generates a fake logical channel id for non multiplexed channel*/ + if ( p_conv_data->dchs_in_flow_list[chan] != 31 && (p_conv_data->dchs_in_flow_list[chan] == 24 && + tb_size != 340) ) { + fake_lchid = make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]); + } + tb_bit_off = (2+p_conv_data->num_dch_in_flow)*8; /*Point to the C/T of first TB*/ + /*Set configuration for individual blocks*/ + for (j=0; j < num_tbs && j+chan < MAX_MAC_FRAMES; j++) { + /*Set transport channel id (useful for debugging)*/ + macinf->trchid[j+chan] = p_conv_data->dchs_in_flow_list[chan]; + + /*Transport Channel m31 and 24 might be multiplexed!*/ + if ( p_conv_data->dchs_in_flow_list[chan] == 31 || p_conv_data->dchs_in_flow_list[chan] == 24) { + + /****** MUST FIGURE OUT IF THIS IS REALLY MULTIPLEXED OR NOT*******/ + /*If Trchid == 31 and only on TB, we have no multiplexing*/ + if (0/*p_conv_data->dchs_in_flow_list[chan] == 31 && num_tbs == 1*/) { + macinf->ctmux[j+chan] = FALSE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/ + + macinf->lchid[j+chan] = 1; + + macinf->content[j+chan] = lchId_type_table[1]; /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/ + rlcinf->mode[j+chan] = lchId_rlc_map[1]; /*Based RLC mode on logical channel id*/ + + } + /*Indicate we don't have multiplexing.*/ + else if (p_conv_data->dchs_in_flow_list[chan] == 24 && tb_size != 340) { + macinf->ctmux[j+chan] = FALSE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/ + + /*g_warning(""settin this for %d"", pinfo->num);*/ + macinf->lchid[j+chan] = fake_lchid; + macinf->fake_chid[j+chan] = TRUE; + macinf->content[j+chan] = MAC_CONTENT_PS_DTCH; /*lchId_type_table[fake_lchid];*/ /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/ + rlcinf->mode[j+chan] = RLC_AM;/*lchId_rlc_map[fake_lchid];*/ /*Based RLC mode on logical channel id*/ + } + /*We have multiplexing*/ + else { + macinf->ctmux[j+chan] = TRUE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/ + + /* Peek at C/T, different RLC params for different logical channels */ + /*C/T is 4 bits according to 3GPP TS 25.321, paragraph 9.2.1, from MAC header (not FP)*/ + c_t = tvb_get_bits8(tvb, tb_bit_off/*(2+p_conv_data->num_dch_in_flow)*8*/, 4); /* c_t = tvb_get_guint8(tvb, offset);*/ + macinf->lchid[j+chan] = c_t+1; + + macinf->content[j+chan] = lchId_type_table[c_t+1]; /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/ + rlcinf->mode[j+chan] = lchId_rlc_map[c_t+1]; /*Based RLC mode on logical channel id*/ + } + } else { + fake_lchid = make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]); + macinf->ctmux[j+chan] = FALSE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/ + /*macinf->content[j+chan] = MAC_CONTENT_CS_DTCH;*/ + macinf->content[j+chan] = lchId_type_table[fake_lchid]; + + + rlcinf->mode[j+chan] = lchId_rlc_map[fake_lchid]; + + /*Generate virtual logical channel id*/ + /************************/ + /*TODO: Once proper lchid is always set, this has to be removed*/ + macinf->fake_chid[j+chan] = TRUE; + macinf->lchid[j+chan] = fake_lchid; /*make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]);*/ + /************************/ + } + + /*** Set rlc info ***/ + rlcinf->urnti[j+chan] = p_conv_data->com_context_id; + rlcinf->li_size[j+chan] = RLC_LI_7BITS; +#if 0 + /*If this entry exists, SECRUITY_MODE is completed (signled by RRC)*/ + if ( rrc_ciph_inf && g_tree_lookup(rrc_ciph_inf, GINT_TO_POINTER((gint)p_conv_data->com_context_id)) != NULL ) { + rlcinf->ciphered[j+chan] = TRUE; + } else { + rlcinf->ciphered[j+chan] = FALSE; + } +#endif + rlcinf->ciphered[j+chan] = FALSE; + rlcinf->deciphered[j+chan] = FALSE; + rlcinf->rbid[j+chan] = macinf->lchid[j+chan]; + + + /*Step over this TB and it's C/T flag.*/ + tb_bit_off += tb_size+4; + } + + offset++; + } + p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); + p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); + /* Set offset to point to first TFI + * the Number of TFI's = number of DCH's in the flow + */ + offset = 2; + break; + case CHANNEL_FACH_FDD: + fpi->num_chans = p_conv_data->num_dch_in_flow; + if (is_control_frame) { + /* control frame, we're done */ + return fpi; + } + /* Set offset to point to first TFI + * the Number of TFI's = number of DCH's in the flow + */ + offset = 2; + /* Set MAC data */ + macinf = wmem_new0(wmem_file_scope(), umts_mac_info); + macinf->ctmux[0] = 1; + macinf->content[0] = MAC_CONTENT_DCCH; + p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); + /* Set RLC data */ + rlcinf = wmem_new0(wmem_file_scope(), rlc_info); + /* Make configurable ?(avaliable in NBAP?) */ + /* For RLC re-assembly to work we need to fake urnti */ + rlcinf->urnti[0] = fpi->channel; + rlcinf->mode[0] = RLC_AM; + /* rbid[MAX_RLC_CHANS] */ + rlcinf->li_size[0] = RLC_LI_7BITS; + rlcinf->ciphered[0] = FALSE; + rlcinf->deciphered[0] = FALSE; + p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); + break; + + case CHANNEL_RACH_FDD: + fpi->num_chans = p_conv_data->num_dch_in_flow; + if (is_control_frame) { + /* control frame, we're done */ + return fpi; + } + /* Set offset to point to first TFI + * the Number of TFI's = number of DCH's in the flow + */ + offset = 2; + /* set MAC data */ + macinf = wmem_new0(wmem_file_scope(), umts_mac_info); + rlcinf = wmem_new0(wmem_file_scope(), rlc_info); + for ( chan = 0; chan < fpi->num_chans; chan++ ) { + macinf->ctmux[chan] = 1; + macinf->content[chan] = MAC_CONTENT_DCCH; + rlcinf->urnti[chan] = fpi->com_context_id; /*Note that MAC probably will change this*/ + } + + + + p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); + p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); + break; + case CHANNEL_HSDSCH_COMMON: + rlcinf = wmem_new0(wmem_file_scope(), rlc_info); + macinf = wmem_new0(wmem_file_scope(), umts_mac_info); + p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); + p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); + break; + default: + expert_add_info(pinfo, NULL, &ei_fp_transport_channel_type_unknown); + return NULL; + } + + /* Peek at the packet as the per packet info seems not to take the tfi into account */ + for (i=0; inum_chans; i++) { + tfi = tvb_get_guint8(tvb, offset); + + /*TFI is 5 bits according to 3GPP TS 25.321, paragraph 6.2.4.4*/ + /*tfi = tvb_get_bits8(tvb, offset*8, 5);*/ + if (pinfo->link_dir == P2P_DIR_UL) { + fpi->chan_tf_size[i] = p_conv_data->fp_dch_channel_info[i].ul_chan_tf_size[tfi]; + fpi->chan_num_tbs[i] = p_conv_data->fp_dch_channel_info[i].ul_chan_num_tbs[tfi]; + } else { + fpi->chan_tf_size[i] = p_conv_data->fp_dch_channel_info[i].dl_chan_tf_size[tfi]; + fpi->chan_num_tbs[i] = p_conv_data->fp_dch_channel_info[i].dl_chan_num_tbs[tfi]; + } + offset++; + } + + + return fpi; +} +",1,"fp_set_per_packet_inf_from_conv(umts_fp_conversation_info_t *p_conv_data, + tvbuff_t *tvb, packet_info *pinfo, + proto_tree *tree _U_) +{ + fp_info *fpi; + guint8 tfi, c_t; + int offset = 0, i=0, j=0, num_tbs, chan, tb_size, tb_bit_off; + gboolean is_control_frame; + umts_mac_info *macinf; + rlc_info *rlcinf; + guint8 fake_lchid=0; + gint *cur_val=NULL; + + fpi = wmem_new0(wmem_file_scope(), fp_info); + p_add_proto_data(wmem_file_scope(), pinfo, proto_fp, 0, fpi); + + fpi->iface_type = p_conv_data->iface_type; + fpi->division = p_conv_data->division; + fpi->release = 7; /* Set values greater then the checks performed */ + fpi->release_year = 2006; + fpi->release_month = 12; + fpi->channel = p_conv_data->channel; + fpi->dch_crc_present = p_conv_data->dch_crc_present; + /*fpi->paging_indications;*/ + fpi->link_type = FP_Link_Ethernet; + +#if 0 + /*Only do this the first run, signals that we need to reset the RLC fragtable*/ + if (!pinfo->fd->flags.visited && p_conv_data->reset_frag ) { + fpi->reset_frag = p_conv_data->reset_frag; + p_conv_data->reset_frag = FALSE; + } +#endif + /* remember 'lower' UDP layer port information so we can later + * differentiate 'lower' UDP layer from 'user data' UDP layer */ + fpi->srcport = pinfo->srcport; + fpi->destport = pinfo->destport; + + fpi->com_context_id = p_conv_data->com_context_id; + + if (pinfo->link_dir == P2P_DIR_UL) { + fpi->is_uplink = TRUE; + } else { + fpi->is_uplink = FALSE; + } + + is_control_frame = tvb_get_guint8(tvb, offset) & 0x01; + + switch (fpi->channel) { + case CHANNEL_HSDSCH: /* HS-DSCH - High Speed Downlink Shared Channel */ + fpi->hsdsch_entity = p_conv_data->hsdsch_entity; + macinf = wmem_new0(wmem_file_scope(), umts_mac_info); + fpi->hsdsch_macflowd_id = p_conv_data->hsdsch_macdflow_id; + macinf->content[0] = hsdsch_macdflow_id_mac_content_map[p_conv_data->hsdsch_macdflow_id]; /*MAC_CONTENT_PS_DTCH;*/ + macinf->lchid[0] = p_conv_data->hsdsch_macdflow_id; + /*macinf->content[0] = lchId_type_table[p_conv_data->edch_lchId[0]];*/ + p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); + + rlcinf = wmem_new0(wmem_file_scope(), rlc_info); + + /*Figure out RLC_MODE based on MACd-flow-ID, basically MACd-flow-ID = 0 then it's SRB0 == UM else AM*/ + rlcinf->mode[0] = hsdsch_macdflow_id_rlc_map[p_conv_data->hsdsch_macdflow_id]; + + if (fpi->hsdsch_entity == hs /*&& !rlc_is_ciphered(pinfo)*/) { + for (i=0; ihrnti))) != NULL) { + j = 1 << i; + fpi->hsdhsch_macfdlow_is_mux[i] = j & *cur_val; + } else { + fpi->hsdhsch_macfdlow_is_mux[i] = FALSE; + } + + } + } + /* Make configurable ?(available in NBAP?) */ + /* urnti[MAX_RLC_CHANS] */ + /* + switch (p_conv_data->rlc_mode) { + case FP_RLC_TM: + rlcinf->mode[0] = RLC_TM; + break; + case FP_RLC_UM: + rlcinf->mode[0] = RLC_UM; + break; + case FP_RLC_AM: + rlcinf->mode[0] = RLC_AM; + break; + case FP_RLC_MODE_UNKNOWN: + default: + rlcinf->mode[0] = RLC_UNKNOWN_MODE; + break; + }*/ + /* rbid[MAX_RLC_CHANS] */ + /* For RLC re-assembly to work we urnti signaled from NBAP */ + rlcinf->urnti[0] = fpi->com_context_id; + rlcinf->li_size[0] = RLC_LI_7BITS; + rlcinf->ciphered[0] = FALSE; + rlcinf->deciphered[0] = FALSE; + p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); + + + return fpi; + + case CHANNEL_EDCH: + /*Most configuration is now done in the actual dissecting function*/ + macinf = wmem_new0(wmem_file_scope(), umts_mac_info); + rlcinf = wmem_new0(wmem_file_scope(), rlc_info); + fpi->no_ddi_entries = p_conv_data->no_ddi_entries; + for (i=0; ino_ddi_entries; i++) { + fpi->edch_ddi[i] = p_conv_data->edch_ddi[i]; /*Set the DDI value*/ + fpi->edch_macd_pdu_size[i] = p_conv_data->edch_macd_pdu_size[i]; /*Set the size*/ + fpi->edch_lchId[i] = p_conv_data->edch_lchId[i]; /*Set the channel id for this entry*/ + /*macinf->content[i] = lchId_type_table[p_conv_data->edch_lchId[i]]; */ /*Set the proper Content type for the mac layer.*/ + /* rlcinf->mode[i] = lchId_rlc_map[p_conv_data->edch_lchId[i]];*/ /* Set RLC mode by lchid to RLC_MODE map in nbap.h */ + + } + fpi->edch_type = p_conv_data->edch_type; + + /* macinf = wmem_new0(wmem_file_scope(), umts_mac_info); + macinf->content[0] = MAC_CONTENT_PS_DTCH;*/ + p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); + + + /* For RLC re-assembly to work we need a urnti signaled from NBAP */ + rlcinf->urnti[0] = fpi->com_context_id; + /* rlcinf->mode[0] = RLC_AM;*/ + rlcinf->li_size[0] = RLC_LI_7BITS; + rlcinf->ciphered[0] = FALSE; + rlcinf->deciphered[0] = FALSE; + + p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); + + return fpi; + + case CHANNEL_PCH: + fpi->paging_indications = p_conv_data->paging_indications; + fpi->num_chans = p_conv_data->num_dch_in_flow; + /* Set offset to point to first TFI + */ + if (is_control_frame) { + /* control frame, we're done */ + return fpi; + } + /* Set offset to TFI */ + offset = 3; + break; + case CHANNEL_DCH: + fpi->num_chans = p_conv_data->num_dch_in_flow; + if (is_control_frame) { + /* control frame, we're done */ + return fpi; + } + + rlcinf = wmem_new0(wmem_file_scope(), rlc_info); + macinf = wmem_new0(wmem_file_scope(), umts_mac_info); + offset = 2; /*To correctly read the tfi*/ + fakes = 5; /* Reset fake counter. */ + for (chan=0; chan < fpi->num_chans; chan++) { /*Iterate over the what channels*/ + /*Iterate over the transport blocks*/ + /*tfi = tvb_get_guint8(tvb, offset);*/ + /*TFI is 5 bits according to 3GPP TS 25.321, paragraph 6.2.4.4*/ + tfi = tvb_get_bits8(tvb, 3+offset*8, 5); + + /*Figure out the number of tbs and size*/ + num_tbs = (fpi->is_uplink) ? p_conv_data->fp_dch_channel_info[chan].ul_chan_num_tbs[tfi] : p_conv_data->fp_dch_channel_info[chan].dl_chan_num_tbs[tfi]; + tb_size= (fpi->is_uplink) ? p_conv_data->fp_dch_channel_info[i].ul_chan_tf_size[tfi] : p_conv_data->fp_dch_channel_info[i].dl_chan_tf_size[tfi]; + + /*TODO: This stuff has to be reworked!*/ + /*Generates a fake logical channel id for non multiplexed channel*/ + if ( p_conv_data->dchs_in_flow_list[chan] != 31 && (p_conv_data->dchs_in_flow_list[chan] == 24 && + tb_size != 340) ) { + fake_lchid = make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]); + } + tb_bit_off = (2+p_conv_data->num_dch_in_flow)*8; /*Point to the C/T of first TB*/ + /*Set configuration for individual blocks*/ + for (j=0; j < num_tbs && j+chan < MAX_MAC_FRAMES; j++) { + /*Set transport channel id (useful for debugging)*/ + macinf->trchid[j+chan] = p_conv_data->dchs_in_flow_list[chan]; + + /*Transport Channel m31 and 24 might be multiplexed!*/ + if ( p_conv_data->dchs_in_flow_list[chan] == 31 || p_conv_data->dchs_in_flow_list[chan] == 24) { + + /****** MUST FIGURE OUT IF THIS IS REALLY MULTIPLEXED OR NOT*******/ + /*If Trchid == 31 and only on TB, we have no multiplexing*/ + if (0/*p_conv_data->dchs_in_flow_list[chan] == 31 && num_tbs == 1*/) { + macinf->ctmux[j+chan] = FALSE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/ + + macinf->lchid[j+chan] = 1; + + macinf->content[j+chan] = lchId_type_table[1]; /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/ + rlcinf->mode[j+chan] = lchId_rlc_map[1]; /*Based RLC mode on logical channel id*/ + + } + /*Indicate we don't have multiplexing.*/ + else if (p_conv_data->dchs_in_flow_list[chan] == 24 && tb_size != 340) { + macinf->ctmux[j+chan] = FALSE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/ + + /*g_warning(""settin this for %d"", pinfo->num);*/ + macinf->lchid[j+chan] = fake_lchid; + macinf->fake_chid[j+chan] = TRUE; + macinf->content[j+chan] = MAC_CONTENT_PS_DTCH; /*lchId_type_table[fake_lchid];*/ /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/ + rlcinf->mode[j+chan] = RLC_AM;/*lchId_rlc_map[fake_lchid];*/ /*Based RLC mode on logical channel id*/ + } + /*We have multiplexing*/ + else { + macinf->ctmux[j+chan] = TRUE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/ + + /* Peek at C/T, different RLC params for different logical channels */ + /*C/T is 4 bits according to 3GPP TS 25.321, paragraph 9.2.1, from MAC header (not FP)*/ + c_t = (tvb_get_bits8(tvb, tb_bit_off/*(2+p_conv_data->num_dch_in_flow)*8*/, 4) + 1) % 0xf; /* c_t = tvb_get_guint8(tvb, offset);*/ + macinf->lchid[j+chan] = c_t; + + macinf->content[j+chan] = lchId_type_table[c_t]; /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/ + rlcinf->mode[j+chan] = lchId_rlc_map[c_t]; /*Based RLC mode on logical channel id*/ + } + } else { + fake_lchid = make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]); + macinf->ctmux[j+chan] = FALSE;/*Set TRUE if this channel is multiplexed (ie. C/T flag exists)*/ + /*macinf->content[j+chan] = MAC_CONTENT_CS_DTCH;*/ + macinf->content[j+chan] = lchId_type_table[fake_lchid]; + + + rlcinf->mode[j+chan] = lchId_rlc_map[fake_lchid]; + + /*Generate virtual logical channel id*/ + /************************/ + /*TODO: Once proper lchid is always set, this has to be removed*/ + macinf->fake_chid[j+chan] = TRUE; + macinf->lchid[j+chan] = fake_lchid; /*make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]);*/ + /************************/ + } + + /*** Set rlc info ***/ + rlcinf->urnti[j+chan] = p_conv_data->com_context_id; + rlcinf->li_size[j+chan] = RLC_LI_7BITS; +#if 0 + /*If this entry exists, SECRUITY_MODE is completed (signled by RRC)*/ + if ( rrc_ciph_inf && g_tree_lookup(rrc_ciph_inf, GINT_TO_POINTER((gint)p_conv_data->com_context_id)) != NULL ) { + rlcinf->ciphered[j+chan] = TRUE; + } else { + rlcinf->ciphered[j+chan] = FALSE; + } +#endif + rlcinf->ciphered[j+chan] = FALSE; + rlcinf->deciphered[j+chan] = FALSE; + rlcinf->rbid[j+chan] = macinf->lchid[j+chan]; + + + /*Step over this TB and it's C/T flag.*/ + tb_bit_off += tb_size+4; + } + + offset++; + } + p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); + p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); + /* Set offset to point to first TFI + * the Number of TFI's = number of DCH's in the flow + */ + offset = 2; + break; + case CHANNEL_FACH_FDD: + fpi->num_chans = p_conv_data->num_dch_in_flow; + if (is_control_frame) { + /* control frame, we're done */ + return fpi; + } + /* Set offset to point to first TFI + * the Number of TFI's = number of DCH's in the flow + */ + offset = 2; + /* Set MAC data */ + macinf = wmem_new0(wmem_file_scope(), umts_mac_info); + macinf->ctmux[0] = 1; + macinf->content[0] = MAC_CONTENT_DCCH; + p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); + /* Set RLC data */ + rlcinf = wmem_new0(wmem_file_scope(), rlc_info); + /* Make configurable ?(avaliable in NBAP?) */ + /* For RLC re-assembly to work we need to fake urnti */ + rlcinf->urnti[0] = fpi->channel; + rlcinf->mode[0] = RLC_AM; + /* rbid[MAX_RLC_CHANS] */ + rlcinf->li_size[0] = RLC_LI_7BITS; + rlcinf->ciphered[0] = FALSE; + rlcinf->deciphered[0] = FALSE; + p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); + break; + + case CHANNEL_RACH_FDD: + fpi->num_chans = p_conv_data->num_dch_in_flow; + if (is_control_frame) { + /* control frame, we're done */ + return fpi; + } + /* Set offset to point to first TFI + * the Number of TFI's = number of DCH's in the flow + */ + offset = 2; + /* set MAC data */ + macinf = wmem_new0(wmem_file_scope(), umts_mac_info); + rlcinf = wmem_new0(wmem_file_scope(), rlc_info); + for ( chan = 0; chan < fpi->num_chans; chan++ ) { + macinf->ctmux[chan] = 1; + macinf->content[chan] = MAC_CONTENT_DCCH; + rlcinf->urnti[chan] = fpi->com_context_id; /*Note that MAC probably will change this*/ + } + + + + p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); + p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); + break; + case CHANNEL_HSDSCH_COMMON: + rlcinf = wmem_new0(wmem_file_scope(), rlc_info); + macinf = wmem_new0(wmem_file_scope(), umts_mac_info); + p_add_proto_data(wmem_file_scope(), pinfo, proto_umts_mac, 0, macinf); + p_add_proto_data(wmem_file_scope(), pinfo, proto_rlc, 0, rlcinf); + break; + default: + expert_add_info(pinfo, NULL, &ei_fp_transport_channel_type_unknown); + return NULL; + } + + /* Peek at the packet as the per packet info seems not to take the tfi into account */ + for (i=0; inum_chans; i++) { + tfi = tvb_get_guint8(tvb, offset); + + /*TFI is 5 bits according to 3GPP TS 25.321, paragraph 6.2.4.4*/ + /*tfi = tvb_get_bits8(tvb, offset*8, 5);*/ + if (pinfo->link_dir == P2P_DIR_UL) { + fpi->chan_tf_size[i] = p_conv_data->fp_dch_channel_info[i].ul_chan_tf_size[tfi]; + fpi->chan_num_tbs[i] = p_conv_data->fp_dch_channel_info[i].ul_chan_num_tbs[tfi]; + } else { + fpi->chan_tf_size[i] = p_conv_data->fp_dch_channel_info[i].dl_chan_tf_size[tfi]; + fpi->chan_num_tbs[i] = p_conv_data->fp_dch_channel_info[i].dl_chan_num_tbs[tfi]; + } + offset++; + } + + + return fpi; +} +","@@ -4098,11 +4098,11 @@ fp_set_per_packet_inf_from_conv(umts_fp_conversation_info_t *p_conv_data, + + /* Peek at C/T, different RLC params for different logical channels */ + /*C/T is 4 bits according to 3GPP TS 25.321, paragraph 9.2.1, from MAC header (not FP)*/ +- c_t = tvb_get_bits8(tvb, tb_bit_off/*(2+p_conv_data->num_dch_in_flow)*8*/, 4); /* c_t = tvb_get_guint8(tvb, offset);*/ +- macinf->lchid[j+chan] = c_t+1; ++ c_t = (tvb_get_bits8(tvb, tb_bit_off/*(2+p_conv_data->num_dch_in_flow)*8*/, 4) + 1) % 0xf; /* c_t = tvb_get_guint8(tvb, offset);*/ ++ macinf->lchid[j+chan] = c_t; + +- macinf->content[j+chan] = lchId_type_table[c_t+1]; /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/ +- rlcinf->mode[j+chan] = lchId_rlc_map[c_t+1]; /*Based RLC mode on logical channel id*/ ++ macinf->content[j+chan] = lchId_type_table[c_t]; /*Base MAC content on logical channel id (Table is in packet-nbap.h)*/ ++ rlcinf->mode[j+chan] = lchId_rlc_map[c_t]; /*Based RLC mode on logical channel id*/ + } + } else { + fake_lchid = make_fake_lchid(pinfo, p_conv_data->dchs_in_flow_list[chan]);",4520,4851,6144 +18091,"static Image *ReadWPGImage(const ImageInfo *image_info, + ExceptionInfo *exception) +{ + typedef struct + { + size_t FileId; + MagickOffsetType DataOffset; + unsigned int ProductType; + unsigned int FileType; + unsigned char MajorVersion; + unsigned char MinorVersion; + unsigned int EncryptKey; + unsigned int Reserved; + } WPGHeader; + + typedef struct + { + unsigned char RecType; + size_t RecordLength; + } WPGRecord; + + typedef struct + { + unsigned char Class; + unsigned char RecType; + size_t Extension; + size_t RecordLength; + } WPG2Record; + + typedef struct + { + unsigned HorizontalUnits; + unsigned VerticalUnits; + unsigned char PosSizePrecision; + } WPG2Start; + + typedef struct + { + unsigned int Width; + unsigned int Height; + unsigned int Depth; + unsigned int HorzRes; + unsigned int VertRes; + } WPGBitmapType1; + + typedef struct + { + unsigned int Width; + unsigned int Height; + unsigned char Depth; + unsigned char Compression; + } WPG2BitmapType1; + + typedef struct + { + unsigned int RotAngle; + unsigned int LowLeftX; + unsigned int LowLeftY; + unsigned int UpRightX; + unsigned int UpRightY; + unsigned int Width; + unsigned int Height; + unsigned int Depth; + unsigned int HorzRes; + unsigned int VertRes; + } WPGBitmapType2; + + typedef struct + { + unsigned int StartIndex; + unsigned int NumOfEntries; + } WPGColorMapRec; + + /* + typedef struct { + size_t PS_unknown1; + unsigned int PS_unknown2; + unsigned int PS_unknown3; + } WPGPSl1Record; + */ + + Image + *image; + + unsigned int + status; + + WPGHeader + Header; + + WPGRecord + Rec; + + WPG2Record + Rec2; + + WPG2Start StartWPG; + + WPGBitmapType1 + BitmapHeader1; + + WPG2BitmapType1 + Bitmap2Header1; + + WPGBitmapType2 + BitmapHeader2; + + WPGColorMapRec + WPG_Palette; + + int + i, + bpp, + WPG2Flags; + + ssize_t + ldblk; + + size_t + one; + + unsigned char + *BImgBuff; + + tCTM CTM; /*current transform matrix*/ + + /* + Open image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickSignature); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickSignature); + one=1; + image=AcquireImage(image_info); + image->depth=8; + status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); + if (status == MagickFalse) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + /* + Read WPG image. + */ + Header.FileId=ReadBlobLSBLong(image); + Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image); + Header.ProductType=ReadBlobLSBShort(image); + Header.FileType=ReadBlobLSBShort(image); + Header.MajorVersion=ReadBlobByte(image); + Header.MinorVersion=ReadBlobByte(image); + Header.EncryptKey=ReadBlobLSBShort(image); + Header.Reserved=ReadBlobLSBShort(image); + + if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + if (Header.EncryptKey!=0) + ThrowReaderException(CoderError,""EncryptedWPGImageFileNotSupported""); + + image->columns = 1; + image->rows = 1; + image->colors = 0; + bpp=0; + BitmapHeader2.RotAngle=0; + Rec2.RecordLength = 0; + + switch(Header.FileType) + { + case 1: /* WPG level 1 */ + while(!EOFBlob(image)) /* object parser loop */ + { + (void) SeekBlob(image,Header.DataOffset,SEEK_SET); + if(EOFBlob(image)) + break; + + Rec.RecType=(i=ReadBlobByte(image)); + if(i==EOF) + break; + Rd_WP_DWORD(image,&Rec.RecordLength); + if(EOFBlob(image)) + break; + + Header.DataOffset=TellBlob(image)+Rec.RecordLength; + + switch(Rec.RecType) + { + case 0x0B: /* bitmap type 1 */ + BitmapHeader1.Width=ReadBlobLSBShort(image); + BitmapHeader1.Height=ReadBlobLSBShort(image); + if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + BitmapHeader1.Depth=ReadBlobLSBShort(image); + BitmapHeader1.HorzRes=ReadBlobLSBShort(image); + BitmapHeader1.VertRes=ReadBlobLSBShort(image); + + if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes) + { + image->units=PixelsPerCentimeterResolution; + image->x_resolution=BitmapHeader1.HorzRes/470.0; + image->y_resolution=BitmapHeader1.VertRes/470.0; + } + image->columns=BitmapHeader1.Width; + image->rows=BitmapHeader1.Height; + bpp=BitmapHeader1.Depth; + + goto UnpackRaster; + + case 0x0E: /*Color palette */ + WPG_Palette.StartIndex=ReadBlobLSBShort(image); + WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); + if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) > + (Rec2.RecordLength-2-2) / 3) + ThrowReaderException(CorruptImageError,""InvalidColormapIndex""); + image->colors=WPG_Palette.NumOfEntries; + if (!AcquireImageColormap(image,image->colors)) + goto NoMemory; + for (i=WPG_Palette.StartIndex; + i < (int)WPG_Palette.NumOfEntries; i++) + { + image->colormap[i].red=ScaleCharToQuantum((unsigned char) + ReadBlobByte(image)); + image->colormap[i].green=ScaleCharToQuantum((unsigned char) + ReadBlobByte(image)); + image->colormap[i].blue=ScaleCharToQuantum((unsigned char) + ReadBlobByte(image)); + } + break; + + case 0x11: /* Start PS l1 */ + if(Rec.RecordLength > 8) + image=ExtractPostscript(image,image_info, + TellBlob(image)+8, /* skip PS header in the wpg */ + (ssize_t) Rec.RecordLength-8,exception); + break; + + case 0x14: /* bitmap type 2 */ + BitmapHeader2.RotAngle=ReadBlobLSBShort(image); + BitmapHeader2.LowLeftX=ReadBlobLSBShort(image); + BitmapHeader2.LowLeftY=ReadBlobLSBShort(image); + BitmapHeader2.UpRightX=ReadBlobLSBShort(image); + BitmapHeader2.UpRightY=ReadBlobLSBShort(image); + BitmapHeader2.Width=ReadBlobLSBShort(image); + BitmapHeader2.Height=ReadBlobLSBShort(image); + if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + BitmapHeader2.Depth=ReadBlobLSBShort(image); + BitmapHeader2.HorzRes=ReadBlobLSBShort(image); + BitmapHeader2.VertRes=ReadBlobLSBShort(image); + + image->units=PixelsPerCentimeterResolution; + image->page.width=(unsigned int) + ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0); + image->page.height=(unsigned int) + ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0); + image->page.x=(int) (BitmapHeader2.LowLeftX/470.0); + image->page.y=(int) (BitmapHeader2.LowLeftX/470.0); + if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes) + { + image->x_resolution=BitmapHeader2.HorzRes/470.0; + image->y_resolution=BitmapHeader2.VertRes/470.0; + } + image->columns=BitmapHeader2.Width; + image->rows=BitmapHeader2.Height; + bpp=BitmapHeader2.Depth; + + UnpackRaster: + status=SetImageExtent(image,image->columns,image->rows); + if (status == MagickFalse) + break; + if ((image->colors == 0) && (bpp != 24)) + { + image->colors=one << bpp; + if (!AcquireImageColormap(image,image->colors)) + { + NoMemory: + ThrowReaderException(ResourceLimitError, + ""MemoryAllocationFailed""); + } + /* printf(""Load default colormap \n""); */ + for (i=0; (i < (int) image->colors) && (i < 256); i++) + { + image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red); + image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green); + image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue); + } + } + else + { + if (bpp < 24) + if ( (image->colors < (one << bpp)) && (bpp != 24) ) + image->colormap=(PixelPacket *) ResizeQuantumMemory( + image->colormap,(size_t) (one << bpp), + sizeof(*image->colormap)); + } + + if (bpp == 1) + { + if(image->colormap[0].red==0 && + image->colormap[0].green==0 && + image->colormap[0].blue==0 && + image->colormap[1].red==0 && + image->colormap[1].green==0 && + image->colormap[1].blue==0) + { /* fix crippled monochrome palette */ + image->colormap[1].red = + image->colormap[1].green = + image->colormap[1].blue = QuantumRange; + } + } + + if(UnpackWPGRaster(image,bpp) < 0) + /* The raster cannot be unpacked */ + { + DecompressionFailed: + ThrowReaderException(CoderError,""UnableToDecompressImage""); + } + + if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping) + { + /* flop command */ + if(BitmapHeader2.RotAngle & 0x8000) + { + Image + *flop_image; + + flop_image = FlopImage(image, exception); + if (flop_image != (Image *) NULL) { + DuplicateBlob(flop_image,image); + ReplaceImageInList(&image,flop_image); + } + } + /* flip command */ + if(BitmapHeader2.RotAngle & 0x2000) + { + Image + *flip_image; + + flip_image = FlipImage(image, exception); + if (flip_image != (Image *) NULL) { + DuplicateBlob(flip_image,image); + ReplaceImageInList(&image,flip_image); + } + } + /* rotate command */ + if(BitmapHeader2.RotAngle & 0x0FFF) + { + Image + *rotate_image; + + rotate_image=RotateImage(image,(BitmapHeader2.RotAngle & + 0x0FFF), exception); + if (rotate_image != (Image *) NULL) { + DuplicateBlob(rotate_image,image); + ReplaceImageInList(&image,rotate_image); + } + } + } + + /* Allocate next image structure. */ + AcquireNextImage(image_info,image); + image->depth=8; + if (image->next == (Image *) NULL) + goto Finish; + image=SyncNextImageInList(image); + image->columns=image->rows=1; + image->colors=0; + break; + + case 0x1B: /* Postscript l2 */ + if(Rec.RecordLength>0x3C) + image=ExtractPostscript(image,image_info, + TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */ + (ssize_t) Rec.RecordLength-0x3C,exception); + break; + } + } + break; + + case 2: /* WPG level 2 */ + (void) memset(CTM,0,sizeof(CTM)); + StartWPG.PosSizePrecision = 0; + while(!EOFBlob(image)) /* object parser loop */ + { + (void) SeekBlob(image,Header.DataOffset,SEEK_SET); + if(EOFBlob(image)) + break; + + Rec2.Class=(i=ReadBlobByte(image)); + if(i==EOF) + break; + Rec2.RecType=(i=ReadBlobByte(image)); + if(i==EOF) + break; + Rd_WP_DWORD(image,&Rec2.Extension); + Rd_WP_DWORD(image,&Rec2.RecordLength); + if(EOFBlob(image)) + break; + + Header.DataOffset=TellBlob(image)+Rec2.RecordLength; + + switch(Rec2.RecType) + { + case 1: + StartWPG.HorizontalUnits=ReadBlobLSBShort(image); + StartWPG.VerticalUnits=ReadBlobLSBShort(image); + StartWPG.PosSizePrecision=ReadBlobByte(image); + break; + case 0x0C: /* Color palette */ + WPG_Palette.StartIndex=ReadBlobLSBShort(image); + WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); + if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) > + (Rec2.RecordLength-2-2) / 3) + ThrowReaderException(CorruptImageError,""InvalidColormapIndex""); + image->colors=WPG_Palette.NumOfEntries; + if (AcquireImageColormap(image,image->colors) == MagickFalse) + ThrowReaderException(ResourceLimitError, + ""MemoryAllocationFailed""); + for (i=WPG_Palette.StartIndex; + i < (int)WPG_Palette.NumOfEntries; i++) + { + image->colormap[i].red=ScaleCharToQuantum((char) + ReadBlobByte(image)); + image->colormap[i].green=ScaleCharToQuantum((char) + ReadBlobByte(image)); + image->colormap[i].blue=ScaleCharToQuantum((char) + ReadBlobByte(image)); + (void) ReadBlobByte(image); /*Opacity??*/ + } + break; + case 0x0E: + Bitmap2Header1.Width=ReadBlobLSBShort(image); + Bitmap2Header1.Height=ReadBlobLSBShort(image); + if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + Bitmap2Header1.Depth=ReadBlobByte(image); + Bitmap2Header1.Compression=ReadBlobByte(image); + + if(Bitmap2Header1.Compression > 1) + continue; /*Unknown compression method */ + switch(Bitmap2Header1.Depth) + { + case 1: + bpp=1; + break; + case 2: + bpp=2; + break; + case 3: + bpp=4; + break; + case 4: + bpp=8; + break; + case 8: + bpp=24; + break; + default: + continue; /*Ignore raster with unknown depth*/ + } + image->columns=Bitmap2Header1.Width; + image->rows=Bitmap2Header1.Height; + status=SetImageExtent(image,image->columns,image->rows); + if (status == MagickFalse) + break; + if ((image->colors == 0) && (bpp != 24)) + { + size_t + one; + + one=1; + image->colors=one << bpp; + if (!AcquireImageColormap(image,image->colors)) + goto NoMemory; + } + else + { + if(bpp < 24) + if( image->colors<(one << bpp) && bpp!=24 ) + image->colormap=(PixelPacket *) ResizeQuantumMemory( + image->colormap,(size_t) (one << bpp), + sizeof(*image->colormap)); + } + + + switch(Bitmap2Header1.Compression) + { + case 0: /*Uncompressed raster*/ + { + ldblk=(ssize_t) ((bpp*image->columns+7)/8); + BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) + ldblk+1,sizeof(*BImgBuff)); + if (BImgBuff == (unsigned char *) NULL) + goto NoMemory; + + for(i=0; i< (ssize_t) image->rows; i++) + { + (void) ReadBlob(image,ldblk,BImgBuff); + InsertRow(BImgBuff,i,image,bpp); + } + + if(BImgBuff) + BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); + break; + } + case 1: /*RLE for WPG2 */ + { + if( UnpackWPG2Raster(image,bpp) < 0) + goto DecompressionFailed; + break; + } + } + + if(CTM[0][0]<0 && !image_info->ping) + { /*?? RotAngle=360-RotAngle;*/ + Image + *flop_image; + + flop_image = FlopImage(image, exception); + if (flop_image != (Image *) NULL) { + DuplicateBlob(flop_image,image); + ReplaceImageInList(&image,flop_image); + } + /* Try to change CTM according to Flip - I am not sure, must be checked. + Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0; + Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0; + Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll); + Tx(1,2)=0; Tx(2,2)=1; */ + } + if(CTM[1][1]<0 && !image_info->ping) + { /*?? RotAngle=360-RotAngle;*/ + Image + *flip_image; + + flip_image = FlipImage(image, exception); + if (flip_image != (Image *) NULL) { + DuplicateBlob(flip_image,image); + ReplaceImageInList(&image,flip_image); + } + /* Try to change CTM according to Flip - I am not sure, must be checked. + float_matrix Tx(3,3); + Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0; + Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0; + Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll); + Tx(2,2)=1; */ + } + + + /* Allocate next image structure. */ + AcquireNextImage(image_info,image); + image->depth=8; + if (image->next == (Image *) NULL) + goto Finish; + image=SyncNextImageInList(image); + image->columns=image->rows=1; + image->colors=0; + break; + + case 0x12: /* Postscript WPG2*/ + i=ReadBlobLSBShort(image); + if(Rec2.RecordLength > (unsigned int) i) + image=ExtractPostscript(image,image_info, + TellBlob(image)+i, /*skip PS header in the wpg2*/ + (ssize_t) (Rec2.RecordLength-i-2),exception); + break; + + case 0x1B: /*bitmap rectangle*/ + WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM); + (void) WPG2Flags; + break; + } + } + + break; + + default: + { + ThrowReaderException(CoderError,""DataEncodingSchemeIsNotSupported""); + } + } + + Finish: + (void) CloseBlob(image); + + { + Image + *p; + + ssize_t + scene=0; + + /* + Rewind list, removing any empty images while rewinding. + */ + p=image; + image=NULL; + while (p != (Image *) NULL) + { + Image *tmp=p; + if ((p->rows == 0) || (p->columns == 0)) { + p=p->previous; + DeleteImageFromList(&tmp); + } else { + image=p; + p=p->previous; + } + } + /* + Fix scene numbers. + */ + for (p=image; p != (Image *) NULL; p=p->next) + p->scene=(size_t) scene++; + } + if (image == (Image *) NULL) + ThrowReaderException(CorruptImageError, + ""ImageFileDoesNotContainAnyImageData""); + return(image); +} +",1,"static Image *ReadWPGImage(const ImageInfo *image_info, + ExceptionInfo *exception) +{ + typedef struct + { + size_t FileId; + MagickOffsetType DataOffset; + unsigned int ProductType; + unsigned int FileType; + unsigned char MajorVersion; + unsigned char MinorVersion; + unsigned int EncryptKey; + unsigned int Reserved; + } WPGHeader; + + typedef struct + { + unsigned char RecType; + size_t RecordLength; + } WPGRecord; + + typedef struct + { + unsigned char Class; + unsigned char RecType; + size_t Extension; + size_t RecordLength; + } WPG2Record; + + typedef struct + { + unsigned HorizontalUnits; + unsigned VerticalUnits; + unsigned char PosSizePrecision; + } WPG2Start; + + typedef struct + { + unsigned int Width; + unsigned int Height; + unsigned int Depth; + unsigned int HorzRes; + unsigned int VertRes; + } WPGBitmapType1; + + typedef struct + { + unsigned int Width; + unsigned int Height; + unsigned char Depth; + unsigned char Compression; + } WPG2BitmapType1; + + typedef struct + { + unsigned int RotAngle; + unsigned int LowLeftX; + unsigned int LowLeftY; + unsigned int UpRightX; + unsigned int UpRightY; + unsigned int Width; + unsigned int Height; + unsigned int Depth; + unsigned int HorzRes; + unsigned int VertRes; + } WPGBitmapType2; + + typedef struct + { + unsigned int StartIndex; + unsigned int NumOfEntries; + } WPGColorMapRec; + + /* + typedef struct { + size_t PS_unknown1; + unsigned int PS_unknown2; + unsigned int PS_unknown3; + } WPGPSl1Record; + */ + + Image + *image; + + unsigned int + status; + + WPGHeader + Header; + + WPGRecord + Rec; + + WPG2Record + Rec2; + + WPG2Start StartWPG; + + WPGBitmapType1 + BitmapHeader1; + + WPG2BitmapType1 + Bitmap2Header1; + + WPGBitmapType2 + BitmapHeader2; + + WPGColorMapRec + WPG_Palette; + + int + i, + bpp, + WPG2Flags; + + ssize_t + ldblk; + + size_t + one; + + unsigned char + *BImgBuff; + + tCTM CTM; /*current transform matrix*/ + + /* + Open image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickSignature); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickSignature); + one=1; + image=AcquireImage(image_info); + image->depth=8; + status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); + if (status == MagickFalse) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + /* + Read WPG image. + */ + Header.FileId=ReadBlobLSBLong(image); + Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image); + Header.ProductType=ReadBlobLSBShort(image); + Header.FileType=ReadBlobLSBShort(image); + Header.MajorVersion=ReadBlobByte(image); + Header.MinorVersion=ReadBlobByte(image); + Header.EncryptKey=ReadBlobLSBShort(image); + Header.Reserved=ReadBlobLSBShort(image); + + if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + if (Header.EncryptKey!=0) + ThrowReaderException(CoderError,""EncryptedWPGImageFileNotSupported""); + + image->columns = 1; + image->rows = 1; + image->colors = 0; + bpp=0; + BitmapHeader2.RotAngle=0; + Rec2.RecordLength = 0; + + switch(Header.FileType) + { + case 1: /* WPG level 1 */ + while(!EOFBlob(image)) /* object parser loop */ + { + (void) SeekBlob(image,Header.DataOffset,SEEK_SET); + if(EOFBlob(image)) + break; + + Rec.RecType=(i=ReadBlobByte(image)); + if(i==EOF) + break; + Rd_WP_DWORD(image,&Rec.RecordLength); + if (Rec.RecordLength > GetBlobSize(image)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + if(EOFBlob(image)) + break; + + Header.DataOffset=TellBlob(image)+Rec.RecordLength; + + switch(Rec.RecType) + { + case 0x0B: /* bitmap type 1 */ + BitmapHeader1.Width=ReadBlobLSBShort(image); + BitmapHeader1.Height=ReadBlobLSBShort(image); + if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + BitmapHeader1.Depth=ReadBlobLSBShort(image); + BitmapHeader1.HorzRes=ReadBlobLSBShort(image); + BitmapHeader1.VertRes=ReadBlobLSBShort(image); + + if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes) + { + image->units=PixelsPerCentimeterResolution; + image->x_resolution=BitmapHeader1.HorzRes/470.0; + image->y_resolution=BitmapHeader1.VertRes/470.0; + } + image->columns=BitmapHeader1.Width; + image->rows=BitmapHeader1.Height; + bpp=BitmapHeader1.Depth; + + goto UnpackRaster; + + case 0x0E: /*Color palette */ + WPG_Palette.StartIndex=ReadBlobLSBShort(image); + WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); + if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) > + (Rec2.RecordLength-2-2) / 3) + ThrowReaderException(CorruptImageError,""InvalidColormapIndex""); + image->colors=WPG_Palette.NumOfEntries; + if (!AcquireImageColormap(image,image->colors)) + goto NoMemory; + for (i=WPG_Palette.StartIndex; + i < (int)WPG_Palette.NumOfEntries; i++) + { + image->colormap[i].red=ScaleCharToQuantum((unsigned char) + ReadBlobByte(image)); + image->colormap[i].green=ScaleCharToQuantum((unsigned char) + ReadBlobByte(image)); + image->colormap[i].blue=ScaleCharToQuantum((unsigned char) + ReadBlobByte(image)); + } + break; + + case 0x11: /* Start PS l1 */ + if(Rec.RecordLength > 8) + image=ExtractPostscript(image,image_info, + TellBlob(image)+8, /* skip PS header in the wpg */ + (ssize_t) Rec.RecordLength-8,exception); + break; + + case 0x14: /* bitmap type 2 */ + BitmapHeader2.RotAngle=ReadBlobLSBShort(image); + BitmapHeader2.LowLeftX=ReadBlobLSBShort(image); + BitmapHeader2.LowLeftY=ReadBlobLSBShort(image); + BitmapHeader2.UpRightX=ReadBlobLSBShort(image); + BitmapHeader2.UpRightY=ReadBlobLSBShort(image); + BitmapHeader2.Width=ReadBlobLSBShort(image); + BitmapHeader2.Height=ReadBlobLSBShort(image); + if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + BitmapHeader2.Depth=ReadBlobLSBShort(image); + BitmapHeader2.HorzRes=ReadBlobLSBShort(image); + BitmapHeader2.VertRes=ReadBlobLSBShort(image); + + image->units=PixelsPerCentimeterResolution; + image->page.width=(unsigned int) + ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0); + image->page.height=(unsigned int) + ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0); + image->page.x=(int) (BitmapHeader2.LowLeftX/470.0); + image->page.y=(int) (BitmapHeader2.LowLeftX/470.0); + if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes) + { + image->x_resolution=BitmapHeader2.HorzRes/470.0; + image->y_resolution=BitmapHeader2.VertRes/470.0; + } + image->columns=BitmapHeader2.Width; + image->rows=BitmapHeader2.Height; + bpp=BitmapHeader2.Depth; + + UnpackRaster: + status=SetImageExtent(image,image->columns,image->rows); + if (status == MagickFalse) + break; + if ((image->colors == 0) && (bpp != 24)) + { + image->colors=one << bpp; + if (!AcquireImageColormap(image,image->colors)) + { + NoMemory: + ThrowReaderException(ResourceLimitError, + ""MemoryAllocationFailed""); + } + /* printf(""Load default colormap \n""); */ + for (i=0; (i < (int) image->colors) && (i < 256); i++) + { + image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red); + image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green); + image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue); + } + } + else + { + if (bpp < 24) + if ( (image->colors < (one << bpp)) && (bpp != 24) ) + image->colormap=(PixelPacket *) ResizeQuantumMemory( + image->colormap,(size_t) (one << bpp), + sizeof(*image->colormap)); + } + + if (bpp == 1) + { + if(image->colormap[0].red==0 && + image->colormap[0].green==0 && + image->colormap[0].blue==0 && + image->colormap[1].red==0 && + image->colormap[1].green==0 && + image->colormap[1].blue==0) + { /* fix crippled monochrome palette */ + image->colormap[1].red = + image->colormap[1].green = + image->colormap[1].blue = QuantumRange; + } + } + + if(UnpackWPGRaster(image,bpp) < 0) + /* The raster cannot be unpacked */ + { + DecompressionFailed: + ThrowReaderException(CoderError,""UnableToDecompressImage""); + } + + if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping) + { + /* flop command */ + if(BitmapHeader2.RotAngle & 0x8000) + { + Image + *flop_image; + + flop_image = FlopImage(image, exception); + if (flop_image != (Image *) NULL) { + DuplicateBlob(flop_image,image); + ReplaceImageInList(&image,flop_image); + } + } + /* flip command */ + if(BitmapHeader2.RotAngle & 0x2000) + { + Image + *flip_image; + + flip_image = FlipImage(image, exception); + if (flip_image != (Image *) NULL) { + DuplicateBlob(flip_image,image); + ReplaceImageInList(&image,flip_image); + } + } + /* rotate command */ + if(BitmapHeader2.RotAngle & 0x0FFF) + { + Image + *rotate_image; + + rotate_image=RotateImage(image,(BitmapHeader2.RotAngle & + 0x0FFF), exception); + if (rotate_image != (Image *) NULL) { + DuplicateBlob(rotate_image,image); + ReplaceImageInList(&image,rotate_image); + } + } + } + + /* Allocate next image structure. */ + AcquireNextImage(image_info,image); + image->depth=8; + if (image->next == (Image *) NULL) + goto Finish; + image=SyncNextImageInList(image); + image->columns=image->rows=1; + image->colors=0; + break; + + case 0x1B: /* Postscript l2 */ + if(Rec.RecordLength>0x3C) + image=ExtractPostscript(image,image_info, + TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */ + (ssize_t) Rec.RecordLength-0x3C,exception); + break; + } + } + break; + + case 2: /* WPG level 2 */ + (void) memset(CTM,0,sizeof(CTM)); + StartWPG.PosSizePrecision = 0; + while(!EOFBlob(image)) /* object parser loop */ + { + (void) SeekBlob(image,Header.DataOffset,SEEK_SET); + if(EOFBlob(image)) + break; + + Rec2.Class=(i=ReadBlobByte(image)); + if(i==EOF) + break; + Rec2.RecType=(i=ReadBlobByte(image)); + if(i==EOF) + break; + Rd_WP_DWORD(image,&Rec2.Extension); + Rd_WP_DWORD(image,&Rec2.RecordLength); + if(EOFBlob(image)) + break; + + Header.DataOffset=TellBlob(image)+Rec2.RecordLength; + + switch(Rec2.RecType) + { + case 1: + StartWPG.HorizontalUnits=ReadBlobLSBShort(image); + StartWPG.VerticalUnits=ReadBlobLSBShort(image); + StartWPG.PosSizePrecision=ReadBlobByte(image); + break; + case 0x0C: /* Color palette */ + WPG_Palette.StartIndex=ReadBlobLSBShort(image); + WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); + if ((WPG_Palette.NumOfEntries-WPG_Palette.StartIndex) > + (Rec2.RecordLength-2-2) / 3) + ThrowReaderException(CorruptImageError,""InvalidColormapIndex""); + image->colors=WPG_Palette.NumOfEntries; + if (AcquireImageColormap(image,image->colors) == MagickFalse) + ThrowReaderException(ResourceLimitError, + ""MemoryAllocationFailed""); + for (i=WPG_Palette.StartIndex; + i < (int)WPG_Palette.NumOfEntries; i++) + { + image->colormap[i].red=ScaleCharToQuantum((char) + ReadBlobByte(image)); + image->colormap[i].green=ScaleCharToQuantum((char) + ReadBlobByte(image)); + image->colormap[i].blue=ScaleCharToQuantum((char) + ReadBlobByte(image)); + (void) ReadBlobByte(image); /*Opacity??*/ + } + break; + case 0x0E: + Bitmap2Header1.Width=ReadBlobLSBShort(image); + Bitmap2Header1.Height=ReadBlobLSBShort(image); + if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + Bitmap2Header1.Depth=ReadBlobByte(image); + Bitmap2Header1.Compression=ReadBlobByte(image); + + if(Bitmap2Header1.Compression > 1) + continue; /*Unknown compression method */ + switch(Bitmap2Header1.Depth) + { + case 1: + bpp=1; + break; + case 2: + bpp=2; + break; + case 3: + bpp=4; + break; + case 4: + bpp=8; + break; + case 8: + bpp=24; + break; + default: + continue; /*Ignore raster with unknown depth*/ + } + image->columns=Bitmap2Header1.Width; + image->rows=Bitmap2Header1.Height; + status=SetImageExtent(image,image->columns,image->rows); + if (status == MagickFalse) + break; + if ((image->colors == 0) && (bpp != 24)) + { + size_t + one; + + one=1; + image->colors=one << bpp; + if (!AcquireImageColormap(image,image->colors)) + goto NoMemory; + } + else + { + if(bpp < 24) + if( image->colors<(one << bpp) && bpp!=24 ) + image->colormap=(PixelPacket *) ResizeQuantumMemory( + image->colormap,(size_t) (one << bpp), + sizeof(*image->colormap)); + } + + + switch(Bitmap2Header1.Compression) + { + case 0: /*Uncompressed raster*/ + { + ldblk=(ssize_t) ((bpp*image->columns+7)/8); + BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) + ldblk+1,sizeof(*BImgBuff)); + if (BImgBuff == (unsigned char *) NULL) + goto NoMemory; + + for(i=0; i< (ssize_t) image->rows; i++) + { + (void) ReadBlob(image,ldblk,BImgBuff); + InsertRow(BImgBuff,i,image,bpp); + } + + if(BImgBuff) + BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff); + break; + } + case 1: /*RLE for WPG2 */ + { + if( UnpackWPG2Raster(image,bpp) < 0) + goto DecompressionFailed; + break; + } + } + + if(CTM[0][0]<0 && !image_info->ping) + { /*?? RotAngle=360-RotAngle;*/ + Image + *flop_image; + + flop_image = FlopImage(image, exception); + if (flop_image != (Image *) NULL) { + DuplicateBlob(flop_image,image); + ReplaceImageInList(&image,flop_image); + } + /* Try to change CTM according to Flip - I am not sure, must be checked. + Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0; + Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0; + Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll); + Tx(1,2)=0; Tx(2,2)=1; */ + } + if(CTM[1][1]<0 && !image_info->ping) + { /*?? RotAngle=360-RotAngle;*/ + Image + *flip_image; + + flip_image = FlipImage(image, exception); + if (flip_image != (Image *) NULL) { + DuplicateBlob(flip_image,image); + ReplaceImageInList(&image,flip_image); + } + /* Try to change CTM according to Flip - I am not sure, must be checked. + float_matrix Tx(3,3); + Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0; + Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0; + Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll); + Tx(2,2)=1; */ + } + + + /* Allocate next image structure. */ + AcquireNextImage(image_info,image); + image->depth=8; + if (image->next == (Image *) NULL) + goto Finish; + image=SyncNextImageInList(image); + image->columns=image->rows=1; + image->colors=0; + break; + + case 0x12: /* Postscript WPG2*/ + i=ReadBlobLSBShort(image); + if(Rec2.RecordLength > (unsigned int) i) + image=ExtractPostscript(image,image_info, + TellBlob(image)+i, /*skip PS header in the wpg2*/ + (ssize_t) (Rec2.RecordLength-i-2),exception); + break; + + case 0x1B: /*bitmap rectangle*/ + WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM); + (void) WPG2Flags; + break; + } + } + + break; + + default: + { + ThrowReaderException(CoderError,""DataEncodingSchemeIsNotSupported""); + } + } + + Finish: + (void) CloseBlob(image); + + { + Image + *p; + + ssize_t + scene=0; + + /* + Rewind list, removing any empty images while rewinding. + */ + p=image; + image=NULL; + while (p != (Image *) NULL) + { + Image *tmp=p; + if ((p->rows == 0) || (p->columns == 0)) { + p=p->previous; + DeleteImageFromList(&tmp); + } else { + image=p; + p=p->previous; + } + } + /* + Fix scene numbers. + */ + for (p=image; p != (Image *) NULL; p=p->next) + p->scene=(size_t) scene++; + } + if (image == (Image *) NULL) + ThrowReaderException(CorruptImageError, + ""ImageFileDoesNotContainAnyImageData""); + return(image); +} +","@@ -1045,6 +1045,8 @@ static Image *ReadWPGImage(const ImageInfo *image_info, + if(i==EOF) + break; + Rd_WP_DWORD(image,&Rec.RecordLength); ++ if (Rec.RecordLength > GetBlobSize(image)) ++ ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + if(EOFBlob(image)) + break; + ",4754,5085,6144 +4866,"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 */ +",0,"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 */ +","@@ -819,9 +819,18 @@ static int readContigTilesIntoBuffer (TIFF* in, uint8* buf, + } + } + +- tilebuf = _TIFFmalloc(tile_buffsize); ++ /* Add 3 padding bytes for extractContigSamplesShifted32bits */ ++ if( tile_buffsize > 0xFFFFFFFFU - 3 ) ++ { ++ 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)",4814,5145,6144 +17868,"void parser(void) +{ + char *arg; +#ifndef MINIMAL + char *sitearg; +#endif +#ifdef WITH_RFC2640 + char *narg = NULL; +#endif + size_t n; + +#ifdef IMPLICIT_TLS + (void) tls_init_new_session(); + data_protection_level = CPL_PRIVATE; +#endif + for (;;) { + xferfd = -1; + if (state_needs_update != 0) { + state_needs_update = 0; + setprocessname(""pure-ftpd (IDLE)""); +#ifdef FTPWHO + if (shm_data_cur != NULL) { + ftpwho_lock(); + shm_data_cur->state = FTPWHO_STATE_IDLE; + *shm_data_cur->filename = 0; + ftpwho_unlock(); + } +#endif + } + doreply(); + alarm(idletime * 2); + switch (sfgets()) { + case -1: +#ifdef BORING_MODE + die(421, LOG_INFO, MSG_TIMEOUT); +#else + die(421, LOG_INFO, MSG_TIMEOUT_PARSER); +#endif + case -2: + return; + } +#ifdef DEBUG + if (debug != 0) { + addreply(0, ""%s"", cmd); + } +#endif + n = (size_t) 0U; + while ((isalpha((unsigned char) cmd[n]) || cmd[n] == '@') && + n < cmdsize) { + cmd[n] = (char) tolower((unsigned char) cmd[n]); + n++; + } + if (n >= cmdsize) { /* overparanoid, it should never happen */ + die(421, LOG_WARNING, MSG_LINE_TOO_LONG); + } + if (n == (size_t) 0U) { + nop: + addreply_noformat(500, ""?""); + continue; + } +#ifdef SKIP_COMMAND_TRAILING_SPACES + while (isspace((unsigned char) cmd[n]) && n < cmdsize) { + cmd[n++] = 0; + } + arg = cmd + n; + while (cmd[n] != 0 && n < cmdsize) { + n++; + } + n--; + while (isspace((unsigned char) cmd[n])) { + cmd[n--] = 0; + } +#else + if (cmd[n] == 0) { + arg = cmd + n; + } else if (isspace((unsigned char) cmd[n])) { + cmd[n] = 0; + arg = cmd + n + 1; + } else { + goto nop; + } +#endif + if (logging != 0) { +#ifdef DEBUG + logfile(LOG_DEBUG, MSG_DEBUG_COMMAND "" [%s] [%s]"", + cmd, arg); +#else + logfile(LOG_DEBUG, MSG_DEBUG_COMMAND "" [%s] [%s]"", + cmd, strcmp(cmd, ""pass"") ? arg : ""<*>""); +#endif + } +#ifdef WITH_RFC2640 + narg = charset_client2fs(arg); + arg = narg; +#endif + /* + * antiidle() is called with dummy commands, usually used by clients + * who are wanting extra idle time. We give them some, but not too much. + * When we jump to wayout, the idle timer is not zeroed. It means that + * we didn't issue an 'active' command like RETR. + */ + +#ifndef MINIMAL + if (!strcmp(cmd, ""noop"")) { + antiidle(); + donoop(); + goto wayout; + } +#endif + if (!strcmp(cmd, ""user"")) { +#ifdef WITH_TLS + if (enforce_tls_auth > 1 && tls_cnx == NULL) { + die(421, LOG_WARNING, MSG_TLS_NEEDED); + } +#endif + douser(arg); + } else if (!strcmp(cmd, ""acct"")) { + addreply(202, MSG_WHOAREYOU); + } else if (!strcmp(cmd, ""pass"")) { + if (guest == 0) { + randomdelay(); + } + dopass(arg); + } else if (!strcmp(cmd, ""quit"")) { + addreply(221, MSG_GOODBYE, + (unsigned long long) ((uploaded + 1023ULL) / 1024ULL), + (unsigned long long) ((downloaded + 1023ULL) / 1024ULL)); + return; + } else if (!strcmp(cmd, ""syst"")) { + antiidle(); + addreply_noformat(215, ""UNIX Type: L8""); + goto wayout; +#ifdef WITH_TLS + } else if (enforce_tls_auth > 0 && + !strcmp(cmd, ""auth"") && !strcasecmp(arg, ""tls"")) { + addreply_noformat(234, ""AUTH TLS OK.""); + doreply(); + if (tls_cnx == NULL) { + (void) tls_init_new_session(); + } + goto wayout; + } else if (!strcmp(cmd, ""pbsz"")) { + addreply_noformat(tls_cnx == NULL ? 503 : 200, ""PBSZ=0""); + } else if (!strcmp(cmd, ""prot"")) { + if (tls_cnx == NULL) { + addreply_noformat(503, MSG_PROT_BEFORE_PBSZ); + goto wayout; + } + switch (*arg) { + case 0: + addreply_noformat(503, MSG_MISSING_ARG); + data_protection_level = CPL_NONE; + break; + case 'C': + if (arg[1] == 0) { + addreply(200, MSG_PROT_OK, ""clear""); + data_protection_level = CPL_CLEAR; + break; + } + case 'S': + case 'E': + if (arg[1] == 0) { + addreply(200, MSG_PROT_UNKNOWN_LEVEL, arg, ""private""); + data_protection_level = CPL_PRIVATE; + break; + } + case 'P': + if (arg[1] == 0) { + addreply(200, MSG_PROT_OK, ""private""); + data_protection_level = CPL_PRIVATE; + break; + } + default: + addreply_noformat(534, ""Fallback to [C]""); + data_protection_level = CPL_CLEAR; + break; + } +#endif + } else if (!strcmp(cmd, ""auth"") || !strcmp(cmd, ""adat"")) { + addreply_noformat(500, MSG_AUTH_UNIMPLEMENTED); + } else if (!strcmp(cmd, ""type"")) { + antiidle(); + dotype(arg); + goto wayout; + } else if (!strcmp(cmd, ""mode"")) { + antiidle(); + domode(arg); + goto wayout; +#ifndef MINIMAL + } else if (!strcmp(cmd, ""feat"")) { + dofeat(); + goto wayout; + } else if (!strcmp(cmd, ""opts"")) { + doopts(arg); + goto wayout; +#endif + } else if (!strcmp(cmd, ""stru"")) { + dostru(arg); + goto wayout; +#ifndef MINIMAL + } else if (!strcmp(cmd, ""help"")) { + goto help_site; +#endif +#ifdef DEBUG + } else if (!strcmp(cmd, ""xdbg"")) { + debug++; + addreply(200, MSG_XDBG_OK, debug); + goto wayout; +#endif + } else if (loggedin == 0) { + /* from this point, all commands need authentication */ + addreply_noformat(530, MSG_NOT_LOGGED_IN); + goto wayout; + } else { + if (!strcmp(cmd, ""cwd"") || !strcmp(cmd, ""xcwd"")) { + antiidle(); + docwd(arg); + goto wayout; + } else if (!strcmp(cmd, ""port"")) { + doport(arg); +#ifndef MINIMAL + } else if (!strcmp(cmd, ""eprt"")) { + doeprt(arg); + } else if (!strcmp(cmd, ""esta"") && + disallow_passive == 0 && + STORAGE_FAMILY(force_passive_ip) == 0) { + doesta(); + } else if (!strcmp(cmd, ""estp"")) { + doestp(); +#endif + } else if (disallow_passive == 0 && + (!strcmp(cmd, ""pasv"") || !strcmp(cmd, ""p@sw""))) { + dopasv(0); + } else if (disallow_passive == 0 && + (!strcmp(cmd, ""epsv"") && + (broken_client_compat == 0 || + STORAGE_FAMILY(ctrlconn) == AF_INET6))) { + if (!strcasecmp(arg, ""all"")) { + epsv_all = 1; + addreply_noformat(220, MSG_ACTIVE_DISABLED); + } else if (!strcmp(arg, ""2"") && !v6ready) { + addreply_noformat(522, MSG_ONLY_IPV4); + } else { + dopasv(1); + } +#ifndef MINIMAL + } else if (disallow_passive == 0 && !strcmp(cmd, ""spsv"")) { + dopasv(2); + } else if (!strcmp(cmd, ""allo"")) { + if (*arg == 0) { + addreply_noformat(501, MSG_STAT_FAILURE); + } else { + const off_t size = (off_t) strtoull(arg, NULL, 10); + + if (size < (off_t) 0) { + addreply_noformat(501, MSG_STAT_FAILURE); + } else { + doallo(size); + } + } +#endif + } else if (!strcmp(cmd, ""pwd"") || !strcmp(cmd, ""xpwd"")) { +#ifdef WITH_RFC2640 + char *nwd; +#endif + antiidle(); +#ifdef WITH_RFC2640 + nwd = charset_fs2client(wd); + addreply(257, ""\""%s\"" "" MSG_IS_YOUR_CURRENT_LOCATION, nwd); + free(nwd); +#else + addreply(257, ""\""%s\"" "" MSG_IS_YOUR_CURRENT_LOCATION, wd); +#endif + goto wayout; + } else if (!strcmp(cmd, ""cdup"") || !strcmp(cmd, ""xcup"")) { + docwd(""..""); + } else if (!strcmp(cmd, ""retr"")) { + if (*arg != 0) { +#ifdef WITH_TLS + if (enforce_tls_auth == 3 && + data_protection_level != CPL_PRIVATE) { + addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED); + } + else +#endif + { + doretr(arg); + } + } else { + addreply_noformat(501, MSG_NO_FILE_NAME); + } + } else if (!strcmp(cmd, ""rest"")) { + antiidle(); + if (*arg != 0) { + dorest(arg); + } else { + addreply_noformat(501, MSG_NO_RESTART_POINT); + restartat = (off_t) 0; + } + goto wayout; + } else if (!strcmp(cmd, ""dele"")) { + if (*arg != 0) { + dodele(arg); + } else { + addreply_noformat(501, MSG_NO_FILE_NAME); + } + } else if (!strcmp(cmd, ""stor"")) { + arg = revealextraspc(arg); + if (*arg != 0) { +#ifdef WITH_TLS + if (enforce_tls_auth == 3 && + data_protection_level != CPL_PRIVATE) { + addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED); + } else +#endif + { + dostor(arg, 0, autorename); + } + } else { + addreply_noformat(501, MSG_NO_FILE_NAME); + } + } else if (!strcmp(cmd, ""appe"")) { + arg = revealextraspc(arg); + if (*arg != 0) { +#ifdef WITH_TLS + if (enforce_tls_auth == 3 && + data_protection_level != CPL_PRIVATE) { + addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED); + } else +#endif + { + dostor(arg, 1, 0); + } + } else { + addreply_noformat(501, MSG_NO_FILE_NAME); + } +#ifndef MINIMAL + } else if (!strcmp(cmd, ""stou"")) { +#ifdef WITH_TLS + if (enforce_tls_auth == 3 && + data_protection_level != CPL_PRIVATE) { + addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED); + } else +#endif + { + dostou(); + } +#endif +#ifndef DISABLE_MKD_RMD + } else if (!strcmp(cmd, ""mkd"") || !strcmp(cmd, ""xmkd"")) { + arg = revealextraspc(arg); + if (*arg != 0) { + domkd(arg); + } else { + addreply_noformat(501, MSG_NO_DIRECTORY_NAME); + } + } else if (!strcmp(cmd, ""rmd"") || !strcmp(cmd, ""xrmd"")) { + if (*arg != 0) { + dormd(arg); + } else { + addreply_noformat(550, MSG_NO_DIRECTORY_NAME); + } +#endif +#ifndef MINIMAL + } else if (!strcmp(cmd, ""stat"")) { + if (*arg != 0) { + modern_listings = 0; + donlist(arg, 1, 1, 1, 1); + } else { + addreply_noformat(211, ""http://www.pureftpd.org/""); + } +#endif + } else if (!strcmp(cmd, ""list"")) { +#ifndef MINIMAL + modern_listings = 0; +#endif +#ifdef WITH_TLS + if (enforce_tls_auth == 3 && + data_protection_level != CPL_PRIVATE) { + addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED); + } else +#endif + { + donlist(arg, 0, 1, 0, 1); + } + } else if (!strcmp(cmd, ""nlst"")) { +#ifndef MINIMAL + modern_listings = 0; +#endif +#ifdef WITH_TLS + if (enforce_tls_auth == 3 && + data_protection_level != CPL_PRIVATE) { + addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED); + } else +#endif + { + donlist(arg, 0, 0, 0, broken_client_compat); + } +#ifndef MINIMAL + } else if (!strcmp(cmd, ""mlst"")) { +#ifdef WITH_TLS + if (enforce_tls_auth == 3 && + data_protection_level != CPL_PRIVATE) { + addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED); + } else +#endif + { + domlst(*arg != 0 ? arg : "".""); + } + } else if (!strcmp(cmd, ""mlsd"")) { + modern_listings = 1; +#ifdef WITH_TLS + if (enforce_tls_auth == 3 && + data_protection_level != CPL_PRIVATE) { + addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED); + } else +#endif + { + donlist(arg, 0, 1, 1, 0); + } +#endif + } else if (!strcmp(cmd, ""abor"")) { + addreply_noformat(226, MSG_ABOR_SUCCESS); +#ifndef MINIMAL + } else if (!strcmp(cmd, ""site"")) { + if ((sitearg = arg) != NULL) { + while (*sitearg != 0 && !isspace((unsigned char) *sitearg)) { + sitearg++; + } + if (*sitearg != 0) { + *sitearg++ = 0; + } + } + if (!strcasecmp(arg, ""idle"")) { + if (sitearg == NULL || *sitearg == 0) { + addreply_noformat(501, ""SITE IDLE: "" MSG_MISSING_ARG); + } else { + unsigned long int i = 0; + + i = strtoul(sitearg, &sitearg, 10); + if (sitearg && *sitearg) + addreply(501, MSG_GARBAGE_FOUND "" : %s"", sitearg); + else if (i > MAX_SITE_IDLE) + addreply_noformat(501, MSG_VALUE_TOO_LARGE); + else { + idletime = i; + addreply(200, MSG_IDLE_TIME, idletime); + idletime_noop = (double) idletime * 2.0; + } + } + } else if (!strcasecmp(arg, ""time"")) { + dositetime(); + } else if (!strcasecmp(arg, ""help"")) { + help_site: + + addreply_noformat(214, MSG_SITE_HELP CRLF +# ifdef WITH_DIRALIASES + "" ALIAS"" CRLF +# endif + "" CHMOD"" CRLF "" IDLE"" CRLF "" UTIME""); + addreply_noformat(214, ""Pure-FTPd - http://pureftpd.org/""); + } else if (!strcasecmp(arg, ""chmod"")) { + char *sitearg2; + mode_t mode; + + parsechmod: + if (sitearg == NULL || *sitearg == 0) { + addreply_noformat(501, MSG_MISSING_ARG); + goto chmod_wayout; + } + sitearg2 = sitearg; + while (*sitearg2 != 0 && !isspace((unsigned char) *sitearg2)) { + sitearg2++; + } + while (*sitearg2 != 0 && isspace((unsigned char) *sitearg2)) { + sitearg2++; + } + if (*sitearg2 == 0) { + addreply_noformat(550, MSG_NO_FILE_NAME); + goto chmod_wayout; + } + mode = (mode_t) strtoul(sitearg, NULL, 8); + if (mode > (mode_t) 07777) { + addreply_noformat(501, MSG_BAD_CHMOD); + goto chmod_wayout; + } + dochmod(sitearg2, mode); + chmod_wayout: + (void) 0; + } else if (!strcasecmp(arg, ""utime"")) { + char *sitearg2; + + if (sitearg == NULL || *sitearg == 0) { + addreply_noformat(501, MSG_NO_FILE_NAME); + goto utime_wayout; + } + if ((sitearg2 = strrchr(sitearg, ' ')) == NULL || + sitearg2 == sitearg) { + addreply_noformat(501, MSG_MISSING_ARG); + goto utime_wayout; + } + if (strcasecmp(sitearg2, "" UTC"") != 0) { + addreply_noformat(500, ""UTC Only""); + goto utime_wayout; + } + *sitearg2-- = 0; + if ((sitearg2 = strrchr(sitearg, ' ')) == NULL || + sitearg2 == sitearg) { + utime_no_arg: + addreply_noformat(501, MSG_MISSING_ARG); + goto utime_wayout; + } + *sitearg2-- = 0; + if ((sitearg2 = strrchr(sitearg, ' ')) == NULL || + sitearg2 == sitearg) { + goto utime_no_arg; + } + *sitearg2-- = 0; + if ((sitearg2 = strrchr(sitearg, ' ')) == NULL || + sitearg2 == sitearg) { + goto utime_no_arg; + } + *sitearg2++ = 0; + if (*sitearg2 == 0) { + goto utime_no_arg; + } + doutime(sitearg, sitearg2); + utime_wayout: + (void) 0; +# ifdef WITH_DIRALIASES + } else if (!strcasecmp(arg, ""alias"")) { + if (sitearg == NULL || *sitearg == 0) { + print_aliases(); + } else { + const char *alias; + + if ((alias = lookup_alias(sitearg)) != NULL) { + addreply(214, MSG_ALIASES_ALIAS, sitearg, alias); + } else { + addreply(502, MSG_ALIASES_UNKNOWN, sitearg); + } + } +# endif + } else if (*arg != 0) { + addreply(500, ""SITE %s "" MSG_UNKNOWN_EXTENSION, arg); + } else { + addreply_noformat(500, ""SITE: "" MSG_MISSING_ARG); + } +#endif + } else if (!strcmp(cmd, ""mdtm"")) { + domdtm(arg); + } else if (!strcmp(cmd, ""size"")) { + dosize(arg); +#ifndef MINIMAL + } else if (!strcmp(cmd, ""chmod"")) { + sitearg = arg; + goto parsechmod; +#endif + } else if (!strcmp(cmd, ""rnfr"")) { + if (*arg != 0) { + dornfr(arg); + } else { + addreply_noformat(550, MSG_NO_FILE_NAME); + } + } else if (!strcmp(cmd, ""rnto"")) { + arg = revealextraspc(arg); + if (*arg != 0) { + dornto(arg); + } else { + addreply_noformat(550, MSG_NO_FILE_NAME); + } + } else { + addreply_noformat(500, MSG_UNKNOWN_COMMAND); + } + } + noopidle = (time_t) -1; + wayout: +#ifdef WITH_RFC2640 + free(narg); + narg = NULL; +#endif +#ifdef THROTTLING + if (throttling_delay != 0UL) { + usleep2(throttling_delay); + } +#else + (void) 0; +#endif + } +} +",1,"void parser(void) +{ + char *arg; +#ifndef MINIMAL + char *sitearg; +#endif +#ifdef WITH_RFC2640 + char *narg = NULL; +#endif + size_t n; + +#ifdef IMPLICIT_TLS + (void) tls_init_new_session(); + data_protection_level = CPL_PRIVATE; +#endif + for (;;) { + xferfd = -1; + if (state_needs_update != 0) { + state_needs_update = 0; + setprocessname(""pure-ftpd (IDLE)""); +#ifdef FTPWHO + if (shm_data_cur != NULL) { + ftpwho_lock(); + shm_data_cur->state = FTPWHO_STATE_IDLE; + *shm_data_cur->filename = 0; + ftpwho_unlock(); + } +#endif + } + doreply(); + alarm(idletime * 2); + switch (sfgets()) { + case -1: +#ifdef BORING_MODE + die(421, LOG_INFO, MSG_TIMEOUT); +#else + die(421, LOG_INFO, MSG_TIMEOUT_PARSER); +#endif + case -2: + return; + } +#ifdef DEBUG + if (debug != 0) { + addreply(0, ""%s"", cmd); + } +#endif + n = (size_t) 0U; + while ((isalpha((unsigned char) cmd[n]) || cmd[n] == '@') && + n < cmdsize) { + cmd[n] = (char) tolower((unsigned char) cmd[n]); + n++; + } + if (n >= cmdsize) { /* overparanoid, it should never happen */ + die(421, LOG_WARNING, MSG_LINE_TOO_LONG); + } + if (n == (size_t) 0U) { + nop: + addreply_noformat(500, ""?""); + continue; + } +#ifdef SKIP_COMMAND_TRAILING_SPACES + while (isspace((unsigned char) cmd[n]) && n < cmdsize) { + cmd[n++] = 0; + } + arg = cmd + n; + while (cmd[n] != 0 && n < cmdsize) { + n++; + } + n--; + while (isspace((unsigned char) cmd[n])) { + cmd[n--] = 0; + } +#else + if (cmd[n] == 0) { + arg = cmd + n; + } else if (isspace((unsigned char) cmd[n])) { + cmd[n] = 0; + arg = cmd + n + 1; + } else { + goto nop; + } +#endif + if (logging != 0) { +#ifdef DEBUG + logfile(LOG_DEBUG, MSG_DEBUG_COMMAND "" [%s] [%s]"", + cmd, arg); +#else + logfile(LOG_DEBUG, MSG_DEBUG_COMMAND "" [%s] [%s]"", + cmd, strcmp(cmd, ""pass"") ? arg : ""<*>""); +#endif + } +#ifdef WITH_RFC2640 + narg = charset_client2fs(arg); + arg = narg; +#endif + /* + * antiidle() is called with dummy commands, usually used by clients + * who are wanting extra idle time. We give them some, but not too much. + * When we jump to wayout, the idle timer is not zeroed. It means that + * we didn't issue an 'active' command like RETR. + */ + +#ifndef MINIMAL + if (!strcmp(cmd, ""noop"")) { + antiidle(); + donoop(); + goto wayout; + } +#endif + if (!strcmp(cmd, ""user"")) { +#ifdef WITH_TLS + if (enforce_tls_auth > 1 && tls_cnx == NULL) { + die(421, LOG_WARNING, MSG_TLS_NEEDED); + } +#endif + douser(arg); + } else if (!strcmp(cmd, ""acct"")) { + addreply(202, MSG_WHOAREYOU); + } else if (!strcmp(cmd, ""pass"")) { + if (guest == 0) { + randomdelay(); + } + dopass(arg); + } else if (!strcmp(cmd, ""quit"")) { + addreply(221, MSG_GOODBYE, + (unsigned long long) ((uploaded + 1023ULL) / 1024ULL), + (unsigned long long) ((downloaded + 1023ULL) / 1024ULL)); + return; + } else if (!strcmp(cmd, ""syst"")) { + antiidle(); + addreply_noformat(215, ""UNIX Type: L8""); + goto wayout; +#ifdef WITH_TLS + } else if (enforce_tls_auth > 0 && + !strcmp(cmd, ""auth"") && !strcasecmp(arg, ""tls"")) { + addreply_noformat(234, ""AUTH TLS OK.""); + doreply(); + if (tls_cnx == NULL) { + flush_cmd(); + (void) tls_init_new_session(); + } + goto wayout; + } else if (!strcmp(cmd, ""pbsz"")) { + addreply_noformat(tls_cnx == NULL ? 503 : 200, ""PBSZ=0""); + } else if (!strcmp(cmd, ""prot"")) { + if (tls_cnx == NULL) { + addreply_noformat(503, MSG_PROT_BEFORE_PBSZ); + goto wayout; + } + switch (*arg) { + case 0: + addreply_noformat(503, MSG_MISSING_ARG); + data_protection_level = CPL_NONE; + break; + case 'C': + if (arg[1] == 0) { + addreply(200, MSG_PROT_OK, ""clear""); + data_protection_level = CPL_CLEAR; + break; + } + case 'S': + case 'E': + if (arg[1] == 0) { + addreply(200, MSG_PROT_UNKNOWN_LEVEL, arg, ""private""); + data_protection_level = CPL_PRIVATE; + break; + } + case 'P': + if (arg[1] == 0) { + addreply(200, MSG_PROT_OK, ""private""); + data_protection_level = CPL_PRIVATE; + break; + } + default: + addreply_noformat(534, ""Fallback to [C]""); + data_protection_level = CPL_CLEAR; + break; + } +#endif + } else if (!strcmp(cmd, ""auth"") || !strcmp(cmd, ""adat"")) { + addreply_noformat(500, MSG_AUTH_UNIMPLEMENTED); + } else if (!strcmp(cmd, ""type"")) { + antiidle(); + dotype(arg); + goto wayout; + } else if (!strcmp(cmd, ""mode"")) { + antiidle(); + domode(arg); + goto wayout; +#ifndef MINIMAL + } else if (!strcmp(cmd, ""feat"")) { + dofeat(); + goto wayout; + } else if (!strcmp(cmd, ""opts"")) { + doopts(arg); + goto wayout; +#endif + } else if (!strcmp(cmd, ""stru"")) { + dostru(arg); + goto wayout; +#ifndef MINIMAL + } else if (!strcmp(cmd, ""help"")) { + goto help_site; +#endif +#ifdef DEBUG + } else if (!strcmp(cmd, ""xdbg"")) { + debug++; + addreply(200, MSG_XDBG_OK, debug); + goto wayout; +#endif + } else if (loggedin == 0) { + /* from this point, all commands need authentication */ + addreply_noformat(530, MSG_NOT_LOGGED_IN); + goto wayout; + } else { + if (!strcmp(cmd, ""cwd"") || !strcmp(cmd, ""xcwd"")) { + antiidle(); + docwd(arg); + goto wayout; + } else if (!strcmp(cmd, ""port"")) { + doport(arg); +#ifndef MINIMAL + } else if (!strcmp(cmd, ""eprt"")) { + doeprt(arg); + } else if (!strcmp(cmd, ""esta"") && + disallow_passive == 0 && + STORAGE_FAMILY(force_passive_ip) == 0) { + doesta(); + } else if (!strcmp(cmd, ""estp"")) { + doestp(); +#endif + } else if (disallow_passive == 0 && + (!strcmp(cmd, ""pasv"") || !strcmp(cmd, ""p@sw""))) { + dopasv(0); + } else if (disallow_passive == 0 && + (!strcmp(cmd, ""epsv"") && + (broken_client_compat == 0 || + STORAGE_FAMILY(ctrlconn) == AF_INET6))) { + if (!strcasecmp(arg, ""all"")) { + epsv_all = 1; + addreply_noformat(220, MSG_ACTIVE_DISABLED); + } else if (!strcmp(arg, ""2"") && !v6ready) { + addreply_noformat(522, MSG_ONLY_IPV4); + } else { + dopasv(1); + } +#ifndef MINIMAL + } else if (disallow_passive == 0 && !strcmp(cmd, ""spsv"")) { + dopasv(2); + } else if (!strcmp(cmd, ""allo"")) { + if (*arg == 0) { + addreply_noformat(501, MSG_STAT_FAILURE); + } else { + const off_t size = (off_t) strtoull(arg, NULL, 10); + + if (size < (off_t) 0) { + addreply_noformat(501, MSG_STAT_FAILURE); + } else { + doallo(size); + } + } +#endif + } else if (!strcmp(cmd, ""pwd"") || !strcmp(cmd, ""xpwd"")) { +#ifdef WITH_RFC2640 + char *nwd; +#endif + antiidle(); +#ifdef WITH_RFC2640 + nwd = charset_fs2client(wd); + addreply(257, ""\""%s\"" "" MSG_IS_YOUR_CURRENT_LOCATION, nwd); + free(nwd); +#else + addreply(257, ""\""%s\"" "" MSG_IS_YOUR_CURRENT_LOCATION, wd); +#endif + goto wayout; + } else if (!strcmp(cmd, ""cdup"") || !strcmp(cmd, ""xcup"")) { + docwd(""..""); + } else if (!strcmp(cmd, ""retr"")) { + if (*arg != 0) { +#ifdef WITH_TLS + if (enforce_tls_auth == 3 && + data_protection_level != CPL_PRIVATE) { + addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED); + } + else +#endif + { + doretr(arg); + } + } else { + addreply_noformat(501, MSG_NO_FILE_NAME); + } + } else if (!strcmp(cmd, ""rest"")) { + antiidle(); + if (*arg != 0) { + dorest(arg); + } else { + addreply_noformat(501, MSG_NO_RESTART_POINT); + restartat = (off_t) 0; + } + goto wayout; + } else if (!strcmp(cmd, ""dele"")) { + if (*arg != 0) { + dodele(arg); + } else { + addreply_noformat(501, MSG_NO_FILE_NAME); + } + } else if (!strcmp(cmd, ""stor"")) { + arg = revealextraspc(arg); + if (*arg != 0) { +#ifdef WITH_TLS + if (enforce_tls_auth == 3 && + data_protection_level != CPL_PRIVATE) { + addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED); + } else +#endif + { + dostor(arg, 0, autorename); + } + } else { + addreply_noformat(501, MSG_NO_FILE_NAME); + } + } else if (!strcmp(cmd, ""appe"")) { + arg = revealextraspc(arg); + if (*arg != 0) { +#ifdef WITH_TLS + if (enforce_tls_auth == 3 && + data_protection_level != CPL_PRIVATE) { + addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED); + } else +#endif + { + dostor(arg, 1, 0); + } + } else { + addreply_noformat(501, MSG_NO_FILE_NAME); + } +#ifndef MINIMAL + } else if (!strcmp(cmd, ""stou"")) { +#ifdef WITH_TLS + if (enforce_tls_auth == 3 && + data_protection_level != CPL_PRIVATE) { + addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED); + } else +#endif + { + dostou(); + } +#endif +#ifndef DISABLE_MKD_RMD + } else if (!strcmp(cmd, ""mkd"") || !strcmp(cmd, ""xmkd"")) { + arg = revealextraspc(arg); + if (*arg != 0) { + domkd(arg); + } else { + addreply_noformat(501, MSG_NO_DIRECTORY_NAME); + } + } else if (!strcmp(cmd, ""rmd"") || !strcmp(cmd, ""xrmd"")) { + if (*arg != 0) { + dormd(arg); + } else { + addreply_noformat(550, MSG_NO_DIRECTORY_NAME); + } +#endif +#ifndef MINIMAL + } else if (!strcmp(cmd, ""stat"")) { + if (*arg != 0) { + modern_listings = 0; + donlist(arg, 1, 1, 1, 1); + } else { + addreply_noformat(211, ""http://www.pureftpd.org/""); + } +#endif + } else if (!strcmp(cmd, ""list"")) { +#ifndef MINIMAL + modern_listings = 0; +#endif +#ifdef WITH_TLS + if (enforce_tls_auth == 3 && + data_protection_level != CPL_PRIVATE) { + addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED); + } else +#endif + { + donlist(arg, 0, 1, 0, 1); + } + } else if (!strcmp(cmd, ""nlst"")) { +#ifndef MINIMAL + modern_listings = 0; +#endif +#ifdef WITH_TLS + if (enforce_tls_auth == 3 && + data_protection_level != CPL_PRIVATE) { + addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED); + } else +#endif + { + donlist(arg, 0, 0, 0, broken_client_compat); + } +#ifndef MINIMAL + } else if (!strcmp(cmd, ""mlst"")) { +#ifdef WITH_TLS + if (enforce_tls_auth == 3 && + data_protection_level != CPL_PRIVATE) { + addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED); + } else +#endif + { + domlst(*arg != 0 ? arg : "".""); + } + } else if (!strcmp(cmd, ""mlsd"")) { + modern_listings = 1; +#ifdef WITH_TLS + if (enforce_tls_auth == 3 && + data_protection_level != CPL_PRIVATE) { + addreply_noformat(521, MSG_PROT_PRIVATE_NEEDED); + } else +#endif + { + donlist(arg, 0, 1, 1, 0); + } +#endif + } else if (!strcmp(cmd, ""abor"")) { + addreply_noformat(226, MSG_ABOR_SUCCESS); +#ifndef MINIMAL + } else if (!strcmp(cmd, ""site"")) { + if ((sitearg = arg) != NULL) { + while (*sitearg != 0 && !isspace((unsigned char) *sitearg)) { + sitearg++; + } + if (*sitearg != 0) { + *sitearg++ = 0; + } + } + if (!strcasecmp(arg, ""idle"")) { + if (sitearg == NULL || *sitearg == 0) { + addreply_noformat(501, ""SITE IDLE: "" MSG_MISSING_ARG); + } else { + unsigned long int i = 0; + + i = strtoul(sitearg, &sitearg, 10); + if (sitearg && *sitearg) + addreply(501, MSG_GARBAGE_FOUND "" : %s"", sitearg); + else if (i > MAX_SITE_IDLE) + addreply_noformat(501, MSG_VALUE_TOO_LARGE); + else { + idletime = i; + addreply(200, MSG_IDLE_TIME, idletime); + idletime_noop = (double) idletime * 2.0; + } + } + } else if (!strcasecmp(arg, ""time"")) { + dositetime(); + } else if (!strcasecmp(arg, ""help"")) { + help_site: + + addreply_noformat(214, MSG_SITE_HELP CRLF +# ifdef WITH_DIRALIASES + "" ALIAS"" CRLF +# endif + "" CHMOD"" CRLF "" IDLE"" CRLF "" UTIME""); + addreply_noformat(214, ""Pure-FTPd - http://pureftpd.org/""); + } else if (!strcasecmp(arg, ""chmod"")) { + char *sitearg2; + mode_t mode; + + parsechmod: + if (sitearg == NULL || *sitearg == 0) { + addreply_noformat(501, MSG_MISSING_ARG); + goto chmod_wayout; + } + sitearg2 = sitearg; + while (*sitearg2 != 0 && !isspace((unsigned char) *sitearg2)) { + sitearg2++; + } + while (*sitearg2 != 0 && isspace((unsigned char) *sitearg2)) { + sitearg2++; + } + if (*sitearg2 == 0) { + addreply_noformat(550, MSG_NO_FILE_NAME); + goto chmod_wayout; + } + mode = (mode_t) strtoul(sitearg, NULL, 8); + if (mode > (mode_t) 07777) { + addreply_noformat(501, MSG_BAD_CHMOD); + goto chmod_wayout; + } + dochmod(sitearg2, mode); + chmod_wayout: + (void) 0; + } else if (!strcasecmp(arg, ""utime"")) { + char *sitearg2; + + if (sitearg == NULL || *sitearg == 0) { + addreply_noformat(501, MSG_NO_FILE_NAME); + goto utime_wayout; + } + if ((sitearg2 = strrchr(sitearg, ' ')) == NULL || + sitearg2 == sitearg) { + addreply_noformat(501, MSG_MISSING_ARG); + goto utime_wayout; + } + if (strcasecmp(sitearg2, "" UTC"") != 0) { + addreply_noformat(500, ""UTC Only""); + goto utime_wayout; + } + *sitearg2-- = 0; + if ((sitearg2 = strrchr(sitearg, ' ')) == NULL || + sitearg2 == sitearg) { + utime_no_arg: + addreply_noformat(501, MSG_MISSING_ARG); + goto utime_wayout; + } + *sitearg2-- = 0; + if ((sitearg2 = strrchr(sitearg, ' ')) == NULL || + sitearg2 == sitearg) { + goto utime_no_arg; + } + *sitearg2-- = 0; + if ((sitearg2 = strrchr(sitearg, ' ')) == NULL || + sitearg2 == sitearg) { + goto utime_no_arg; + } + *sitearg2++ = 0; + if (*sitearg2 == 0) { + goto utime_no_arg; + } + doutime(sitearg, sitearg2); + utime_wayout: + (void) 0; +# ifdef WITH_DIRALIASES + } else if (!strcasecmp(arg, ""alias"")) { + if (sitearg == NULL || *sitearg == 0) { + print_aliases(); + } else { + const char *alias; + + if ((alias = lookup_alias(sitearg)) != NULL) { + addreply(214, MSG_ALIASES_ALIAS, sitearg, alias); + } else { + addreply(502, MSG_ALIASES_UNKNOWN, sitearg); + } + } +# endif + } else if (*arg != 0) { + addreply(500, ""SITE %s "" MSG_UNKNOWN_EXTENSION, arg); + } else { + addreply_noformat(500, ""SITE: "" MSG_MISSING_ARG); + } +#endif + } else if (!strcmp(cmd, ""mdtm"")) { + domdtm(arg); + } else if (!strcmp(cmd, ""size"")) { + dosize(arg); +#ifndef MINIMAL + } else if (!strcmp(cmd, ""chmod"")) { + sitearg = arg; + goto parsechmod; +#endif + } else if (!strcmp(cmd, ""rnfr"")) { + if (*arg != 0) { + dornfr(arg); + } else { + addreply_noformat(550, MSG_NO_FILE_NAME); + } + } else if (!strcmp(cmd, ""rnto"")) { + arg = revealextraspc(arg); + if (*arg != 0) { + dornto(arg); + } else { + addreply_noformat(550, MSG_NO_FILE_NAME); + } + } else { + addreply_noformat(500, MSG_UNKNOWN_COMMAND); + } + } + noopidle = (time_t) -1; + wayout: +#ifdef WITH_RFC2640 + free(narg); + narg = NULL; +#endif +#ifdef THROTTLING + if (throttling_delay != 0UL) { + usleep2(throttling_delay); + } +#else + (void) 0; +#endif + } +} +","@@ -57,14 +57,20 @@ static void randomdelay(void) + * -Frank. + */ + ++static size_t scanned; ++static size_t readnbd; ++ ++static void flush_cmd(void) ++{ ++ scanned = readnbd = (size_t) 0U; ++} ++ + int sfgets(void) + { + struct pollfd pfd; + int pollret; + ssize_t readnb; + signed char seen_r = 0; +- static size_t scanned; +- static size_t readnbd; + + if (scanned > (size_t) 0U) { /* support pipelining */ + readnbd -= scanned; +@@ -362,6 +368,7 @@ void parser(void) + addreply_noformat(234, ""AUTH TLS OK.""); + doreply(); + if (tls_cnx == NULL) { ++ flush_cmd(); + (void) tls_init_new_session(); + } + goto wayout;",4785,5116,6144 +7134,"static MagickBooleanType WriteICONImage(const ImageInfo *image_info, + Image *image) +{ + const char + *option; + + IconFile + icon_file; + + IconInfo + icon_info; + + Image + *images, + *next; + + MagickBooleanType + status; + + MagickOffsetType + offset, + scene; + + register const IndexPacket + *indexes; + + register const PixelPacket + *p; + + register ssize_t + i, + x; + + register unsigned char + *q; + + size_t + bytes_per_line, + scanline_pad; + + ssize_t + y; + + unsigned char + bit, + byte, + *pixels; + + /* + Open output image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickSignature); + assert(image != (Image *) NULL); + assert(image->signature == MagickSignature); + (void) LogMagickEvent(CoderEvent,GetMagickModule(),""%s"",image->filename); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); + if (status == MagickFalse) + return(status); + images=(Image *) NULL; + option=GetImageOption(image_info,""icon:auto-resize""); + if (option != (const char *) NULL) + { + images=AutoResizeImage(image,option,&scene,&image->exception); + if (images == (Image *) NULL) + ThrowWriterException(ImageError,""InvalidDimensions""); + } + else + { + scene=0; + next=image; + do + { + if ((image->columns > 256L) || (image->rows > 256L)) + ThrowWriterException(ImageError,""WidthOrHeightExceedsLimit""); + scene++; + next=SyncNextImageInList(next); + } while ((next != (Image *) NULL) && (image_info->adjoin != + MagickFalse)); + } + /* + Dump out a ICON header template to be properly initialized later. + */ + (void) WriteBlobLSBShort(image,0); + (void) WriteBlobLSBShort(image,1); + (void) WriteBlobLSBShort(image,(unsigned char) scene); + (void) ResetMagickMemory(&icon_file,0,sizeof(icon_file)); + (void) ResetMagickMemory(&icon_info,0,sizeof(icon_info)); + scene=0; + next=(images != (Image *) NULL) ? images : image; + do + { + (void) WriteBlobByte(image,icon_file.directory[scene].width); + (void) WriteBlobByte(image,icon_file.directory[scene].height); + (void) WriteBlobByte(image,icon_file.directory[scene].colors); + (void) WriteBlobByte(image,icon_file.directory[scene].reserved); + (void) WriteBlobLSBShort(image,icon_file.directory[scene].planes); + (void) WriteBlobLSBShort(image,icon_file.directory[scene].bits_per_pixel); + (void) WriteBlobLSBLong(image,(unsigned int) + icon_file.directory[scene].size); + (void) WriteBlobLSBLong(image,(unsigned int) + icon_file.directory[scene].offset); + scene++; + next=SyncNextImageInList(next); + } while ((next != (Image *) NULL) && (image_info->adjoin != MagickFalse)); + scene=0; + next=(images != (Image *) NULL) ? images : image; + do + { + if ((next->columns > 255L) && (next->rows > 255L) && + ((next->compression == UndefinedCompression) || + (next->compression == ZipCompression))) + { + Image + *write_image; + + ImageInfo + *write_info; + + size_t + length; + + unsigned char + *png; + + write_image=CloneImage(next,0,0,MagickTrue,&image->exception); + if (write_image == (Image *) NULL) + { + images=DestroyImageList(images); + return(MagickFalse); + } + write_info=CloneImageInfo(image_info); + (void) CopyMagickString(write_info->filename,""PNG:"",MaxTextExtent); + + /* Don't write any ancillary chunks except for gAMA */ + (void) SetImageArtifact(write_image,""png:include-chunk"",""none,gama""); + + /* Only write PNG32 formatted PNG (32-bit RGBA), 8 bits per channel */ + (void) SetImageArtifact(write_image,""png:format"",""png32""); + + png=(unsigned char *) ImageToBlob(write_info,write_image,&length, + &image->exception); + write_image=DestroyImage(write_image); + write_info=DestroyImageInfo(write_info); + if (png == (unsigned char *) NULL) + { + images=DestroyImageList(images); + return(MagickFalse); + } + icon_file.directory[scene].width=0; + icon_file.directory[scene].height=0; + icon_file.directory[scene].colors=0; + icon_file.directory[scene].reserved=0; + icon_file.directory[scene].planes=1; + icon_file.directory[scene].bits_per_pixel=32; + icon_file.directory[scene].size=(size_t) length; + icon_file.directory[scene].offset=(size_t) TellBlob(image); + (void) WriteBlob(image,(size_t) length,png); + png=(unsigned char *) RelinquishMagickMemory(png); + } + else + { + /* + Initialize ICON raster file header. + */ + (void) TransformImageColorspace(image,sRGBColorspace); + icon_info.file_size=14+12+28; + icon_info.offset_bits=icon_info.file_size; + icon_info.compression=BI_RGB; + if ((next->storage_class != DirectClass) && (next->colors > 256)) + (void) SetImageStorageClass(next,DirectClass); + if (next->storage_class == DirectClass) + { + /* + Full color ICON raster. + */ + icon_info.number_colors=0; + icon_info.bits_per_pixel=32; + icon_info.compression=(size_t) BI_RGB; + } + else + { + size_t + one; + + /* + Colormapped ICON raster. + */ + icon_info.bits_per_pixel=8; + if (next->colors <= 256) + icon_info.bits_per_pixel=8; + if (next->colors <= 16) + icon_info.bits_per_pixel=4; + if (next->colors <= 2) + icon_info.bits_per_pixel=1; + one=1; + icon_info.number_colors=one << icon_info.bits_per_pixel; + if (icon_info.number_colors < next->colors) + { + (void) SetImageStorageClass(next,DirectClass); + icon_info.number_colors=0; + icon_info.bits_per_pixel=(unsigned short) 24; + icon_info.compression=(size_t) BI_RGB; + } + else + { + size_t + one; + + one=1; + icon_info.file_size+=3*(one << icon_info.bits_per_pixel); + icon_info.offset_bits+=3*(one << icon_info.bits_per_pixel); + icon_info.file_size+=(one << icon_info.bits_per_pixel); + icon_info.offset_bits+=(one << icon_info.bits_per_pixel); + } + } + bytes_per_line=(((next->columns*icon_info.bits_per_pixel)+31) & + ~31) >> 3; + icon_info.ba_offset=0; + icon_info.width=(ssize_t) next->columns; + icon_info.height=(ssize_t) next->rows; + icon_info.planes=1; + icon_info.image_size=bytes_per_line*next->rows; + icon_info.size=40; + icon_info.size+=(4*icon_info.number_colors); + icon_info.size+=icon_info.image_size; + icon_info.size+=(((icon_info.width+31) & ~31) >> 3)*icon_info.height; + icon_info.file_size+=icon_info.image_size; + icon_info.x_pixels=0; + icon_info.y_pixels=0; + switch (next->units) + { + case UndefinedResolution: + case PixelsPerInchResolution: + { + icon_info.x_pixels=(size_t) (100.0*next->x_resolution/2.54); + icon_info.y_pixels=(size_t) (100.0*next->y_resolution/2.54); + break; + } + case PixelsPerCentimeterResolution: + { + icon_info.x_pixels=(size_t) (100.0*next->x_resolution); + icon_info.y_pixels=(size_t) (100.0*next->y_resolution); + break; + } + } + icon_info.colors_important=icon_info.number_colors; + /* + Convert MIFF to ICON raster pixels. + */ + pixels=(unsigned char *) AcquireQuantumMemory((size_t) + icon_info.image_size,sizeof(*pixels)); + if (pixels == (unsigned char *) NULL) + { + images=DestroyImageList(images); + ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); + } + (void) ResetMagickMemory(pixels,0,(size_t) icon_info.image_size); + switch (icon_info.bits_per_pixel) + { + case 1: + { + size_t + bit, + byte; + + /* + Convert PseudoClass image to a ICON monochrome image. + */ + for (y=0; y < (ssize_t) next->rows; y++) + { + p=GetVirtualPixels(next,0,y,next->columns,1,&next->exception); + if (p == (const PixelPacket *) NULL) + break; + indexes=GetVirtualIndexQueue(next); + q=pixels+(next->rows-y-1)*bytes_per_line; + bit=0; + byte=0; + for (x=0; x < (ssize_t) next->columns; x++) + { + byte<<=1; + byte|=GetPixelIndex(indexes+x) != 0 ? 0x01 : 0x00; + bit++; + if (bit == 8) + { + *q++=(unsigned char) byte; + bit=0; + byte=0; + } + } + if (bit != 0) + *q++=(unsigned char) (byte << (8-bit)); + if (next->previous == (Image *) NULL) + { + status=SetImageProgress(next,SaveImageTag,y,next->rows); + if (status == MagickFalse) + break; + } + } + break; + } + case 4: + { + size_t + nibble, + byte; + + /* + Convert PseudoClass image to a ICON monochrome image. + */ + for (y=0; y < (ssize_t) next->rows; y++) + { + p=GetVirtualPixels(next,0,y,next->columns,1,&next->exception); + if (p == (const PixelPacket *) NULL) + break; + indexes=GetVirtualIndexQueue(next); + q=pixels+(next->rows-y-1)*bytes_per_line; + nibble=0; + byte=0; + for (x=0; x < (ssize_t) next->columns; x++) + { + byte<<=4; + byte|=((size_t) GetPixelIndex(indexes+x) & 0x0f); + nibble++; + if (nibble == 2) + { + *q++=(unsigned char) byte; + nibble=0; + byte=0; + } + } + if (nibble != 0) + *q++=(unsigned char) (byte << 4); + if (next->previous == (Image *) NULL) + { + status=SetImageProgress(next,SaveImageTag,y,next->rows); + if (status == MagickFalse) + break; + } + } + break; + } + case 8: + { + /* + Convert PseudoClass packet to ICON pixel. + */ + for (y=0; y < (ssize_t) next->rows; y++) + { + p=GetVirtualPixels(next,0,y,next->columns,1,&next->exception); + if (p == (const PixelPacket *) NULL) + break; + indexes=GetVirtualIndexQueue(next); + q=pixels+(next->rows-y-1)*bytes_per_line; + for (x=0; x < (ssize_t) next->columns; x++) + *q++=(unsigned char) GetPixelIndex(indexes+x); + if (next->previous == (Image *) NULL) + { + status=SetImageProgress(next,SaveImageTag,y,next->rows); + if (status == MagickFalse) + break; + } + } + break; + } + case 24: + case 32: + { + /* + Convert DirectClass packet to ICON BGR888 or BGRA8888 pixel. + */ + for (y=0; y < (ssize_t) next->rows; y++) + { + p=GetVirtualPixels(next,0,y,next->columns,1,&next->exception); + if (p == (const PixelPacket *) NULL) + break; + q=pixels+(next->rows-y-1)*bytes_per_line; + for (x=0; x < (ssize_t) next->columns; x++) + { + *q++=ScaleQuantumToChar(GetPixelBlue(p)); + *q++=ScaleQuantumToChar(GetPixelGreen(p)); + *q++=ScaleQuantumToChar(GetPixelRed(p)); + if (next->matte == MagickFalse) + *q++=ScaleQuantumToChar(QuantumRange); + else + *q++=ScaleQuantumToChar(GetPixelAlpha(p)); + p++; + } + if (icon_info.bits_per_pixel == 24) + for (x=3L*(ssize_t) next->columns; x < (ssize_t) bytes_per_line; x++) + *q++=0x00; + if (next->previous == (Image *) NULL) + { + status=SetImageProgress(next,SaveImageTag,y,next->rows); + if (status == MagickFalse) + break; + } + } + break; + } + } + /* + Write 40-byte version 3+ bitmap header. + */ + icon_file.directory[scene].width=(unsigned char) icon_info.width; + icon_file.directory[scene].height=(unsigned char) icon_info.height; + icon_file.directory[scene].colors=(unsigned char) + icon_info.number_colors; + icon_file.directory[scene].reserved=0; + icon_file.directory[scene].planes=icon_info.planes; + icon_file.directory[scene].bits_per_pixel=icon_info.bits_per_pixel; + icon_file.directory[scene].size=icon_info.size; + icon_file.directory[scene].offset=(size_t) TellBlob(image); + (void) WriteBlobLSBLong(image,(unsigned int) 40); + (void) WriteBlobLSBLong(image,(unsigned int) icon_info.width); + (void) WriteBlobLSBLong(image,(unsigned int) icon_info.height*2); + (void) WriteBlobLSBShort(image,icon_info.planes); + (void) WriteBlobLSBShort(image,icon_info.bits_per_pixel); + (void) WriteBlobLSBLong(image,(unsigned int) icon_info.compression); + (void) WriteBlobLSBLong(image,(unsigned int) icon_info.image_size); + (void) WriteBlobLSBLong(image,(unsigned int) icon_info.x_pixels); + (void) WriteBlobLSBLong(image,(unsigned int) icon_info.y_pixels); + (void) WriteBlobLSBLong(image,(unsigned int) icon_info.number_colors); + (void) WriteBlobLSBLong(image,(unsigned int) icon_info.colors_important); + if (next->storage_class == PseudoClass) + { + unsigned char + *icon_colormap; + + /* + Dump colormap to file. + */ + icon_colormap=(unsigned char *) AcquireQuantumMemory((size_t) + (1UL << icon_info.bits_per_pixel),4UL*sizeof(*icon_colormap)); + if (icon_colormap == (unsigned char *) NULL) + { + images=DestroyImageList(images); + ThrowWriterException(ResourceLimitError, + ""MemoryAllocationFailed""); + } + q=icon_colormap; + for (i=0; i < (ssize_t) next->colors; i++) + { + *q++=ScaleQuantumToChar(next->colormap[i].blue); + *q++=ScaleQuantumToChar(next->colormap[i].green); + *q++=ScaleQuantumToChar(next->colormap[i].red); + *q++=(unsigned char) 0x0; + } + for ( ; i < (ssize_t) (1UL << icon_info.bits_per_pixel); i++) + { + *q++=(unsigned char) 0x00; + *q++=(unsigned char) 0x00; + *q++=(unsigned char) 0x00; + *q++=(unsigned char) 0x00; + } + (void) WriteBlob(image,(size_t) (4UL*(1UL << + icon_info.bits_per_pixel)),icon_colormap); + icon_colormap=(unsigned char *) RelinquishMagickMemory( + icon_colormap); + } + (void) WriteBlob(image,(size_t) icon_info.image_size,pixels); + pixels=(unsigned char *) RelinquishMagickMemory(pixels); + /* + Write matte mask. + */ + scanline_pad=(((next->columns+31) & ~31)-next->columns) >> 3; + for (y=((ssize_t) next->rows - 1); y >= 0; y--) + { + p=GetVirtualPixels(next,0,y,next->columns,1,&next->exception); + if (p == (const PixelPacket *) NULL) + break; + bit=0; + byte=0; + for (x=0; x < (ssize_t) next->columns; x++) + { + byte<<=1; + if ((next->matte != MagickFalse) && + (GetPixelOpacity(p) == (Quantum) TransparentOpacity)) + byte|=0x01; + bit++; + if (bit == 8) + { + (void) WriteBlobByte(image,(unsigned char) byte); + bit=0; + byte=0; + } + p++; + } + if (bit != 0) + (void) WriteBlobByte(image,(unsigned char) (byte << (8-bit))); + for (i=0; i < (ssize_t) scanline_pad; i++) + (void) WriteBlobByte(image,(unsigned char) 0); + } + } + if (GetNextImageInList(next) == (Image *) NULL) + break; + status=SetImageProgress(next,SaveImagesTag,scene++, + GetImageListLength(next)); + if (status == MagickFalse) + break; + next=SyncNextImageInList(next); + } while ((next != (Image *) NULL) && (image_info->adjoin != MagickFalse)); + offset=SeekBlob(image,0,SEEK_SET); + (void) offset; + (void) WriteBlobLSBShort(image,0); + (void) WriteBlobLSBShort(image,1); + (void) WriteBlobLSBShort(image,(unsigned short) (scene+1)); + scene=0; + next=(images != (Image *) NULL) ? images : image; + do + { + (void) WriteBlobByte(image,icon_file.directory[scene].width); + (void) WriteBlobByte(image,icon_file.directory[scene].height); + (void) WriteBlobByte(image,icon_file.directory[scene].colors); + (void) WriteBlobByte(image,icon_file.directory[scene].reserved); + (void) WriteBlobLSBShort(image,icon_file.directory[scene].planes); + (void) WriteBlobLSBShort(image,icon_file.directory[scene].bits_per_pixel); + (void) WriteBlobLSBLong(image,(unsigned int) + icon_file.directory[scene].size); + (void) WriteBlobLSBLong(image,(unsigned int) + icon_file.directory[scene].offset); + scene++; + next=SyncNextImageInList(next); + } while ((next != (Image *) NULL) && (image_info->adjoin != MagickFalse)); + (void) CloseBlob(image); + images=DestroyImageList(images); + return(MagickTrue); +} +",0,"static MagickBooleanType WriteICONImage(const ImageInfo *image_info, + Image *image) +{ + const char + *option; + + IconFile + icon_file; + + IconInfo + icon_info; + + Image + *images, + *next; + + MagickBooleanType + status; + + MagickOffsetType + offset, + scene; + + register const IndexPacket + *indexes; + + register const PixelPacket + *p; + + register ssize_t + i, + x; + + register unsigned char + *q; + + size_t + bytes_per_line, + scanline_pad; + + ssize_t + y; + + unsigned char + bit, + byte, + *pixels; + + /* + Open output image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickSignature); + assert(image != (Image *) NULL); + assert(image->signature == MagickSignature); + (void) LogMagickEvent(CoderEvent,GetMagickModule(),""%s"",image->filename); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); + if (status == MagickFalse) + return(status); + images=(Image *) NULL; + option=GetImageOption(image_info,""icon:auto-resize""); + if (option != (const char *) NULL) + { + images=AutoResizeImage(image,option,&scene,&image->exception); + if (images == (Image *) NULL) + ThrowWriterException(ImageError,""InvalidDimensions""); + } + else + { + scene=0; + next=image; + do + { + if ((image->columns > 256L) || (image->rows > 256L)) + ThrowWriterException(ImageError,""WidthOrHeightExceedsLimit""); + scene++; + next=SyncNextImageInList(next); + } while ((next != (Image *) NULL) && (image_info->adjoin != + MagickFalse)); + } + /* + Dump out a ICON header template to be properly initialized later. + */ + (void) WriteBlobLSBShort(image,0); + (void) WriteBlobLSBShort(image,1); + (void) WriteBlobLSBShort(image,(unsigned char) scene); + (void) ResetMagickMemory(&icon_file,0,sizeof(icon_file)); + (void) ResetMagickMemory(&icon_info,0,sizeof(icon_info)); + scene=0; + next=(images != (Image *) NULL) ? images : image; + do + { + (void) WriteBlobByte(image,icon_file.directory[scene].width); + (void) WriteBlobByte(image,icon_file.directory[scene].height); + (void) WriteBlobByte(image,icon_file.directory[scene].colors); + (void) WriteBlobByte(image,icon_file.directory[scene].reserved); + (void) WriteBlobLSBShort(image,icon_file.directory[scene].planes); + (void) WriteBlobLSBShort(image,icon_file.directory[scene].bits_per_pixel); + (void) WriteBlobLSBLong(image,(unsigned int) + icon_file.directory[scene].size); + (void) WriteBlobLSBLong(image,(unsigned int) + icon_file.directory[scene].offset); + scene++; + next=SyncNextImageInList(next); + } while ((next != (Image *) NULL) && (image_info->adjoin != MagickFalse)); + scene=0; + next=(images != (Image *) NULL) ? images : image; + do + { + if ((next->columns > 255L) && (next->rows > 255L) && + ((next->compression == UndefinedCompression) || + (next->compression == ZipCompression))) + { + Image + *write_image; + + ImageInfo + *write_info; + + size_t + length; + + unsigned char + *png; + + write_image=CloneImage(next,0,0,MagickTrue,&image->exception); + if (write_image == (Image *) NULL) + { + images=DestroyImageList(images); + return(MagickFalse); + } + write_info=CloneImageInfo(image_info); + (void) CopyMagickString(write_info->filename,""PNG:"",MaxTextExtent); + + /* Don't write any ancillary chunks except for gAMA */ + (void) SetImageArtifact(write_image,""png:include-chunk"",""none,gama""); + + /* Only write PNG32 formatted PNG (32-bit RGBA), 8 bits per channel */ + (void) SetImageArtifact(write_image,""png:format"",""png32""); + + png=(unsigned char *) ImageToBlob(write_info,write_image,&length, + &image->exception); + write_image=DestroyImage(write_image); + write_info=DestroyImageInfo(write_info); + if (png == (unsigned char *) NULL) + { + images=DestroyImageList(images); + return(MagickFalse); + } + icon_file.directory[scene].width=0; + icon_file.directory[scene].height=0; + icon_file.directory[scene].colors=0; + icon_file.directory[scene].reserved=0; + icon_file.directory[scene].planes=1; + icon_file.directory[scene].bits_per_pixel=32; + icon_file.directory[scene].size=(size_t) length; + icon_file.directory[scene].offset=(size_t) TellBlob(image); + (void) WriteBlob(image,(size_t) length,png); + png=(unsigned char *) RelinquishMagickMemory(png); + } + else + { + /* + Initialize ICON raster file header. + */ + (void) TransformImageColorspace(image,sRGBColorspace); + icon_info.file_size=14+12+28; + icon_info.offset_bits=icon_info.file_size; + icon_info.compression=BI_RGB; + if ((next->storage_class != DirectClass) && (next->colors > 256)) + (void) SetImageStorageClass(next,DirectClass); + if (next->storage_class == DirectClass) + { + /* + Full color ICON raster. + */ + icon_info.number_colors=0; + icon_info.bits_per_pixel=32; + icon_info.compression=(size_t) BI_RGB; + } + else + { + size_t + one; + + /* + Colormapped ICON raster. + */ + icon_info.bits_per_pixel=8; + if (next->colors <= 256) + icon_info.bits_per_pixel=8; + if (next->colors <= 16) + icon_info.bits_per_pixel=4; + if (next->colors <= 2) + icon_info.bits_per_pixel=1; + one=1; + icon_info.number_colors=one << icon_info.bits_per_pixel; + if (icon_info.number_colors < next->colors) + { + (void) SetImageStorageClass(next,DirectClass); + icon_info.number_colors=0; + icon_info.bits_per_pixel=(unsigned short) 24; + icon_info.compression=(size_t) BI_RGB; + } + else + { + size_t + one; + + one=1; + icon_info.file_size+=3*(one << icon_info.bits_per_pixel); + icon_info.offset_bits+=3*(one << icon_info.bits_per_pixel); + icon_info.file_size+=(one << icon_info.bits_per_pixel); + icon_info.offset_bits+=(one << icon_info.bits_per_pixel); + } + } + bytes_per_line=(((next->columns*icon_info.bits_per_pixel)+31) & + ~31) >> 3; + icon_info.ba_offset=0; + icon_info.width=(ssize_t) next->columns; + icon_info.height=(ssize_t) next->rows; + icon_info.planes=1; + icon_info.image_size=bytes_per_line*next->rows; + icon_info.size=40; + icon_info.size+=(4*icon_info.number_colors); + icon_info.size+=icon_info.image_size; + icon_info.size+=(((icon_info.width+31) & ~31) >> 3)*icon_info.height; + icon_info.file_size+=icon_info.image_size; + icon_info.x_pixels=0; + icon_info.y_pixels=0; + switch (next->units) + { + case UndefinedResolution: + case PixelsPerInchResolution: + { + icon_info.x_pixels=(size_t) (100.0*next->x_resolution/2.54); + icon_info.y_pixels=(size_t) (100.0*next->y_resolution/2.54); + break; + } + case PixelsPerCentimeterResolution: + { + icon_info.x_pixels=(size_t) (100.0*next->x_resolution); + icon_info.y_pixels=(size_t) (100.0*next->y_resolution); + break; + } + } + icon_info.colors_important=icon_info.number_colors; + /* + Convert MIFF to ICON raster pixels. + */ + pixels=(unsigned char *) AcquireQuantumMemory((size_t) + icon_info.image_size,sizeof(*pixels)); + if (pixels == (unsigned char *) NULL) + { + images=DestroyImageList(images); + ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); + } + (void) ResetMagickMemory(pixels,0,(size_t) icon_info.image_size); + switch (icon_info.bits_per_pixel) + { + case 1: + { + size_t + bit, + byte; + + /* + Convert PseudoClass image to a ICON monochrome image. + */ + for (y=0; y < (ssize_t) next->rows; y++) + { + p=GetVirtualPixels(next,0,y,next->columns,1,&next->exception); + if (p == (const PixelPacket *) NULL) + break; + indexes=GetVirtualIndexQueue(next); + q=pixels+(next->rows-y-1)*bytes_per_line; + bit=0; + byte=0; + for (x=0; x < (ssize_t) next->columns; x++) + { + byte<<=1; + byte|=GetPixelIndex(indexes+x) != 0 ? 0x01 : 0x00; + bit++; + if (bit == 8) + { + *q++=(unsigned char) byte; + bit=0; + byte=0; + } + } + if (bit != 0) + *q++=(unsigned char) (byte << (8-bit)); + if (next->previous == (Image *) NULL) + { + status=SetImageProgress(next,SaveImageTag,y,next->rows); + if (status == MagickFalse) + break; + } + } + break; + } + case 4: + { + size_t + nibble, + byte; + + /* + Convert PseudoClass image to a ICON monochrome image. + */ + for (y=0; y < (ssize_t) next->rows; y++) + { + p=GetVirtualPixels(next,0,y,next->columns,1,&next->exception); + if (p == (const PixelPacket *) NULL) + break; + indexes=GetVirtualIndexQueue(next); + q=pixels+(next->rows-y-1)*bytes_per_line; + nibble=0; + byte=0; + for (x=0; x < (ssize_t) next->columns; x++) + { + byte<<=4; + byte|=((size_t) GetPixelIndex(indexes+x) & 0x0f); + nibble++; + if (nibble == 2) + { + *q++=(unsigned char) byte; + nibble=0; + byte=0; + } + } + if (nibble != 0) + *q++=(unsigned char) (byte << 4); + if (next->previous == (Image *) NULL) + { + status=SetImageProgress(next,SaveImageTag,y,next->rows); + if (status == MagickFalse) + break; + } + } + break; + } + case 8: + { + /* + Convert PseudoClass packet to ICON pixel. + */ + for (y=0; y < (ssize_t) next->rows; y++) + { + p=GetVirtualPixels(next,0,y,next->columns,1,&next->exception); + if (p == (const PixelPacket *) NULL) + break; + indexes=GetVirtualIndexQueue(next); + q=pixels+(next->rows-y-1)*bytes_per_line; + for (x=0; x < (ssize_t) next->columns; x++) + *q++=(unsigned char) GetPixelIndex(indexes+x); + if (next->previous == (Image *) NULL) + { + status=SetImageProgress(next,SaveImageTag,y,next->rows); + if (status == MagickFalse) + break; + } + } + break; + } + case 24: + case 32: + { + /* + Convert DirectClass packet to ICON BGR888 or BGRA8888 pixel. + */ + for (y=0; y < (ssize_t) next->rows; y++) + { + p=GetVirtualPixels(next,0,y,next->columns,1,&next->exception); + if (p == (const PixelPacket *) NULL) + break; + q=pixels+(next->rows-y-1)*bytes_per_line; + for (x=0; x < (ssize_t) next->columns; x++) + { + *q++=ScaleQuantumToChar(GetPixelBlue(p)); + *q++=ScaleQuantumToChar(GetPixelGreen(p)); + *q++=ScaleQuantumToChar(GetPixelRed(p)); + if (next->matte == MagickFalse) + *q++=ScaleQuantumToChar(QuantumRange); + else + *q++=ScaleQuantumToChar(GetPixelAlpha(p)); + p++; + } + if (icon_info.bits_per_pixel == 24) + for (x=3L*(ssize_t) next->columns; x < (ssize_t) bytes_per_line; x++) + *q++=0x00; + if (next->previous == (Image *) NULL) + { + status=SetImageProgress(next,SaveImageTag,y,next->rows); + if (status == MagickFalse) + break; + } + } + break; + } + } + /* + Write 40-byte version 3+ bitmap header. + */ + icon_file.directory[scene].width=(unsigned char) icon_info.width; + icon_file.directory[scene].height=(unsigned char) icon_info.height; + icon_file.directory[scene].colors=(unsigned char) + icon_info.number_colors; + icon_file.directory[scene].reserved=0; + icon_file.directory[scene].planes=icon_info.planes; + icon_file.directory[scene].bits_per_pixel=icon_info.bits_per_pixel; + icon_file.directory[scene].size=icon_info.size; + icon_file.directory[scene].offset=(size_t) TellBlob(image); + (void) WriteBlobLSBLong(image,(unsigned int) 40); + (void) WriteBlobLSBLong(image,(unsigned int) icon_info.width); + (void) WriteBlobLSBLong(image,(unsigned int) icon_info.height*2); + (void) WriteBlobLSBShort(image,icon_info.planes); + (void) WriteBlobLSBShort(image,icon_info.bits_per_pixel); + (void) WriteBlobLSBLong(image,(unsigned int) icon_info.compression); + (void) WriteBlobLSBLong(image,(unsigned int) icon_info.image_size); + (void) WriteBlobLSBLong(image,(unsigned int) icon_info.x_pixels); + (void) WriteBlobLSBLong(image,(unsigned int) icon_info.y_pixels); + (void) WriteBlobLSBLong(image,(unsigned int) icon_info.number_colors); + (void) WriteBlobLSBLong(image,(unsigned int) icon_info.colors_important); + if (next->storage_class == PseudoClass) + { + unsigned char + *icon_colormap; + + /* + Dump colormap to file. + */ + icon_colormap=(unsigned char *) AcquireQuantumMemory((size_t) + (1UL << icon_info.bits_per_pixel),4UL*sizeof(*icon_colormap)); + if (icon_colormap == (unsigned char *) NULL) + { + images=DestroyImageList(images); + ThrowWriterException(ResourceLimitError, + ""MemoryAllocationFailed""); + } + q=icon_colormap; + for (i=0; i < (ssize_t) next->colors; i++) + { + *q++=ScaleQuantumToChar(next->colormap[i].blue); + *q++=ScaleQuantumToChar(next->colormap[i].green); + *q++=ScaleQuantumToChar(next->colormap[i].red); + *q++=(unsigned char) 0x0; + } + for ( ; i < (ssize_t) (1UL << icon_info.bits_per_pixel); i++) + { + *q++=(unsigned char) 0x00; + *q++=(unsigned char) 0x00; + *q++=(unsigned char) 0x00; + *q++=(unsigned char) 0x00; + } + (void) WriteBlob(image,(size_t) (4UL*(1UL << + icon_info.bits_per_pixel)),icon_colormap); + icon_colormap=(unsigned char *) RelinquishMagickMemory( + icon_colormap); + } + (void) WriteBlob(image,(size_t) icon_info.image_size,pixels); + pixels=(unsigned char *) RelinquishMagickMemory(pixels); + /* + Write matte mask. + */ + scanline_pad=(((next->columns+31) & ~31)-next->columns) >> 3; + for (y=((ssize_t) next->rows - 1); y >= 0; y--) + { + p=GetVirtualPixels(next,0,y,next->columns,1,&next->exception); + if (p == (const PixelPacket *) NULL) + break; + bit=0; + byte=0; + for (x=0; x < (ssize_t) next->columns; x++) + { + byte<<=1; + if ((next->matte != MagickFalse) && + (GetPixelOpacity(p) == (Quantum) TransparentOpacity)) + byte|=0x01; + bit++; + if (bit == 8) + { + (void) WriteBlobByte(image,(unsigned char) byte); + bit=0; + byte=0; + } + p++; + } + if (bit != 0) + (void) WriteBlobByte(image,(unsigned char) (byte << (8-bit))); + for (i=0; i < (ssize_t) scanline_pad; i++) + (void) WriteBlobByte(image,(unsigned char) 0); + } + } + if (GetNextImageInList(next) == (Image *) NULL) + break; + status=SetImageProgress(next,SaveImagesTag,scene++, + GetImageListLength(next)); + if (status == MagickFalse) + break; + next=SyncNextImageInList(next); + } while ((next != (Image *) NULL) && (image_info->adjoin != MagickFalse)); + offset=SeekBlob(image,0,SEEK_SET); + (void) offset; + (void) WriteBlobLSBShort(image,0); + (void) WriteBlobLSBShort(image,1); + (void) WriteBlobLSBShort(image,(unsigned short) (scene+1)); + scene=0; + next=(images != (Image *) NULL) ? images : image; + do + { + (void) WriteBlobByte(image,icon_file.directory[scene].width); + (void) WriteBlobByte(image,icon_file.directory[scene].height); + (void) WriteBlobByte(image,icon_file.directory[scene].colors); + (void) WriteBlobByte(image,icon_file.directory[scene].reserved); + (void) WriteBlobLSBShort(image,icon_file.directory[scene].planes); + (void) WriteBlobLSBShort(image,icon_file.directory[scene].bits_per_pixel); + (void) WriteBlobLSBLong(image,(unsigned int) + icon_file.directory[scene].size); + (void) WriteBlobLSBLong(image,(unsigned int) + icon_file.directory[scene].offset); + scene++; + next=SyncNextImageInList(next); + } while ((next != (Image *) NULL) && (image_info->adjoin != MagickFalse)); + (void) CloseBlob(image); + images=DestroyImageList(images); + return(MagickTrue); +} +","@@ -462,6 +462,12 @@ static Image *ReadICONImage(const ImageInfo *image_info, + (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)); ++ } + bytes_per_line=(((image->columns*icon_info.bits_per_pixel)+31) & + ~31) >> 3; + (void) bytes_per_line;",4486,4817,6144 +367,"int ssl3_accept(SSL *s) +{ + BUF_MEM *buf; + unsigned long alg_k, Time = (unsigned long)time(NULL); + void (*cb) (const SSL *ssl, int type, int val) = NULL; + int ret = -1; + int new_state, state, skip = 0; + + RAND_add(&Time, sizeof(Time), 0); + ERR_clear_error(); + clear_sys_error(); + + if (s->info_callback != NULL) + cb = s->info_callback; + else if (s->ctx->info_callback != NULL) + cb = s->ctx->info_callback; + + /* init things to blank */ + s->in_handshake++; + if (!SSL_in_init(s) || SSL_in_before(s)) + SSL_clear(s); + + if (s->cert == NULL) { + SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_NO_CERTIFICATE_SET); + return (-1); + } +#ifndef OPENSSL_NO_HEARTBEATS + /* + * If we're awaiting a HeartbeatResponse, pretend we already got and + * don't await it anymore, because Heartbeats don't make sense during + * handshakes anyway. + */ + if (s->tlsext_hb_pending) { + s->tlsext_hb_pending = 0; + s->tlsext_hb_seq++; + } +#endif + + for (;;) { + state = s->state; + + switch (s->state) { + case SSL_ST_RENEGOTIATE: + s->renegotiate = 1; + /* s->state=SSL_ST_ACCEPT; */ + + case SSL_ST_BEFORE: + case SSL_ST_ACCEPT: + case SSL_ST_BEFORE | SSL_ST_ACCEPT: + case SSL_ST_OK | SSL_ST_ACCEPT: + + s->server = 1; + if (cb != NULL) + cb(s, SSL_CB_HANDSHAKE_START, 1); + + if ((s->version >> 8) != 3) { + SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR); + s->state = SSL_ST_ERR; + return -1; + } + s->type = SSL_ST_ACCEPT; + + if (s->init_buf == NULL) { + if ((buf = BUF_MEM_new()) == NULL) { + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) { + BUF_MEM_free(buf); + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + s->init_buf = buf; + } + + if (!ssl3_setup_buffers(s)) { + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + + s->init_num = 0; + s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY; + s->s3->flags &= ~SSL3_FLAGS_CCS_OK; + /* + * Should have been reset by ssl3_get_finished, too. + */ + s->s3->change_cipher_spec = 0; + + if (s->state != SSL_ST_RENEGOTIATE) { + /* + * Ok, we now need to push on a buffering BIO so that the + * output is sent in a way that TCP likes :-) + */ + if (!ssl_init_wbio_buffer(s, 1)) { + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + + ssl3_init_finished_mac(s); + s->state = SSL3_ST_SR_CLNT_HELLO_A; + s->ctx->stats.sess_accept++; + } else if (!s->s3->send_connection_binding && + !(s->options & + SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { + /* + * Server attempting to renegotiate with client that doesn't + * support secure renegotiation. + */ + SSLerr(SSL_F_SSL3_ACCEPT, + SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); + ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } else { + /* + * s->state == SSL_ST_RENEGOTIATE, we will just send a + * HelloRequest + */ + s->ctx->stats.sess_accept_renegotiate++; + s->state = SSL3_ST_SW_HELLO_REQ_A; + } + break; + + case SSL3_ST_SW_HELLO_REQ_A: + case SSL3_ST_SW_HELLO_REQ_B: + + s->shutdown = 0; + ret = ssl3_send_hello_request(s); + if (ret <= 0) + goto end; + s->s3->tmp.next_state = SSL3_ST_SW_HELLO_REQ_C; + s->state = SSL3_ST_SW_FLUSH; + s->init_num = 0; + + ssl3_init_finished_mac(s); + break; + + case SSL3_ST_SW_HELLO_REQ_C: + s->state = SSL_ST_OK; + break; + + case SSL3_ST_SR_CLNT_HELLO_A: + case SSL3_ST_SR_CLNT_HELLO_B: + case SSL3_ST_SR_CLNT_HELLO_C: + + s->shutdown = 0; + ret = ssl3_get_client_hello(s); + if (ret <= 0) + goto end; +#ifndef OPENSSL_NO_SRP + s->state = SSL3_ST_SR_CLNT_HELLO_D; + case SSL3_ST_SR_CLNT_HELLO_D: + { + int al; + if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) { + /* + * callback indicates firther work to be done + */ + s->rwstate = SSL_X509_LOOKUP; + goto end; + } + if (ret != SSL_ERROR_NONE) { + ssl3_send_alert(s, SSL3_AL_FATAL, al); + /* + * This is not really an error but the only means to for + * a client to detect whether srp is supported. + */ + if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY) + SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_CLIENTHELLO_TLSEXT); + ret = SSL_TLSEXT_ERR_ALERT_FATAL; + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + } +#endif + + s->renegotiate = 2; + s->state = SSL3_ST_SW_SRVR_HELLO_A; + s->init_num = 0; + break; + + case SSL3_ST_SW_SRVR_HELLO_A: + case SSL3_ST_SW_SRVR_HELLO_B: + ret = ssl3_send_server_hello(s); + if (ret <= 0) + goto end; +#ifndef OPENSSL_NO_TLSEXT + if (s->hit) { + if (s->tlsext_ticket_expected) + s->state = SSL3_ST_SW_SESSION_TICKET_A; + else + s->state = SSL3_ST_SW_CHANGE_A; + } +#else + if (s->hit) + s->state = SSL3_ST_SW_CHANGE_A; +#endif + else + s->state = SSL3_ST_SW_CERT_A; + s->init_num = 0; + break; + + case SSL3_ST_SW_CERT_A: + case SSL3_ST_SW_CERT_B: + /* Check if it is anon DH or anon ECDH, */ + /* normal PSK or KRB5 or SRP */ + if (! + (s->s3->tmp. + new_cipher->algorithm_auth & (SSL_aNULL | SSL_aKRB5 | + SSL_aSRP)) +&& !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { + ret = ssl3_send_server_certificate(s); + if (ret <= 0) + goto end; +#ifndef OPENSSL_NO_TLSEXT + if (s->tlsext_status_expected) + s->state = SSL3_ST_SW_CERT_STATUS_A; + else + s->state = SSL3_ST_SW_KEY_EXCH_A; + } else { + skip = 1; + s->state = SSL3_ST_SW_KEY_EXCH_A; + } +#else + } else + skip = 1; + + s->state = SSL3_ST_SW_KEY_EXCH_A; +#endif + s->init_num = 0; + break; + + case SSL3_ST_SW_KEY_EXCH_A: + case SSL3_ST_SW_KEY_EXCH_B: + alg_k = s->s3->tmp.new_cipher->algorithm_mkey; + + /* + * clear this, it may get reset by + * send_server_key_exchange + */ + s->s3->tmp.use_rsa_tmp = 0; + + /* + * only send if a DH key exchange, fortezza or RSA but we have a + * sign only certificate PSK: may send PSK identity hints For + * ECC ciphersuites, we send a serverKeyExchange message only if + * the cipher suite is either ECDH-anon or ECDHE. In other cases, + * the server certificate contains the server's public key for + * key exchange. + */ + if (0 + /* + * PSK: send ServerKeyExchange if PSK identity hint if + * provided + */ +#ifndef OPENSSL_NO_PSK + || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint) +#endif +#ifndef OPENSSL_NO_SRP + /* SRP: send ServerKeyExchange */ + || (alg_k & SSL_kSRP) +#endif + || (alg_k & SSL_kEDH) + || (alg_k & SSL_kEECDH) + || ((alg_k & SSL_kRSA) + && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL + || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) + && EVP_PKEY_size(s->cert->pkeys + [SSL_PKEY_RSA_ENC].privatekey) * + 8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher) + ) + ) + ) + ) { + ret = ssl3_send_server_key_exchange(s); + if (ret <= 0) + goto end; + } else + skip = 1; + + s->state = SSL3_ST_SW_CERT_REQ_A; + s->init_num = 0; + break; + + case SSL3_ST_SW_CERT_REQ_A: + case SSL3_ST_SW_CERT_REQ_B: + if ( /* don't request cert unless asked for it: */ + !(s->verify_mode & SSL_VERIFY_PEER) || + /* + * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert + * during re-negotiation: + */ + ((s->session->peer != NULL) && + (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) || + /* + * never request cert in anonymous ciphersuites (see + * section ""Certificate request"" in SSL 3 drafts and in + * RFC 2246): + */ + ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) && + /* + * ... except when the application insists on + * verification (against the specs, but s3_clnt.c accepts + * this for SSL 3) + */ + !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) || + /* + * never request cert in Kerberos ciphersuites + */ + (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) || + /* don't request certificate for SRP auth */ + (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP) + /* + * With normal PSK Certificates and Certificate Requests + * are omitted + */ + || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { + /* no cert request */ + skip = 1; + s->s3->tmp.cert_request = 0; + s->state = SSL3_ST_SW_SRVR_DONE_A; + if (s->s3->handshake_buffer) { + if (!ssl3_digest_cached_records(s)) { + s->state = SSL_ST_ERR; + return -1; + } + } + } else { + s->s3->tmp.cert_request = 1; + ret = ssl3_send_certificate_request(s); + if (ret <= 0) + goto end; +#ifndef NETSCAPE_HANG_BUG + s->state = SSL3_ST_SW_SRVR_DONE_A; +#else + s->state = SSL3_ST_SW_FLUSH; + s->s3->tmp.next_state = SSL3_ST_SR_CERT_A; +#endif + s->init_num = 0; + } + break; + + case SSL3_ST_SW_SRVR_DONE_A: + case SSL3_ST_SW_SRVR_DONE_B: + ret = ssl3_send_server_done(s); + if (ret <= 0) + goto end; + s->s3->tmp.next_state = SSL3_ST_SR_CERT_A; + s->state = SSL3_ST_SW_FLUSH; + s->init_num = 0; + break; + + case SSL3_ST_SW_FLUSH: + + /* + * This code originally checked to see if any data was pending + * using BIO_CTRL_INFO and then flushed. This caused problems as + * documented in PR#1939. The proposed fix doesn't completely + * resolve this issue as buggy implementations of + * BIO_CTRL_PENDING still exist. So instead we just flush + * unconditionally. + */ + + s->rwstate = SSL_WRITING; + if (BIO_flush(s->wbio) <= 0) { + ret = -1; + goto end; + } + s->rwstate = SSL_NOTHING; + + s->state = s->s3->tmp.next_state; + break; + + case SSL3_ST_SR_CERT_A: + case SSL3_ST_SR_CERT_B: + if (s->s3->tmp.cert_request) { + ret = ssl3_get_client_certificate(s); + if (ret <= 0) + goto end; + } + s->init_num = 0; + s->state = SSL3_ST_SR_KEY_EXCH_A; + break; + + case SSL3_ST_SR_KEY_EXCH_A: + case SSL3_ST_SR_KEY_EXCH_B: + ret = ssl3_get_client_key_exchange(s); + if (ret <= 0) + goto end; + if (ret == 2) { + /* + * For the ECDH ciphersuites when the client sends its ECDH + * pub key in a certificate, the CertificateVerify message is + * not sent. Also for GOST ciphersuites when the client uses + * its key from the certificate for key exchange. + */ +#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->state = SSL3_ST_SR_FINISHED_A; +#else + if (s->s3->next_proto_neg_seen) + s->state = SSL3_ST_SR_NEXT_PROTO_A; + else + s->state = SSL3_ST_SR_FINISHED_A; +#endif + s->init_num = 0; + } else if (SSL_USE_SIGALGS(s)) { + s->state = SSL3_ST_SR_CERT_VRFY_A; + s->init_num = 0; + if (!s->session->peer) + break; + /* + * For sigalgs freeze the handshake buffer at this point and + * digest cached records. + */ + if (!s->s3->handshake_buffer) { + SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR); + s->state = SSL_ST_ERR; + return -1; + } + s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE; + if (!ssl3_digest_cached_records(s)) { + s->state = SSL_ST_ERR; + return -1; + } + } else { + int offset = 0; + int dgst_num; + + s->state = SSL3_ST_SR_CERT_VRFY_A; + s->init_num = 0; + + /* + * We need to get hashes here so if there is a client cert, + * it can be verified FIXME - digest processing for + * CertificateVerify should be generalized. But it is next + * step + */ + if (s->s3->handshake_buffer) { + if (!ssl3_digest_cached_records(s)) { + s->state = SSL_ST_ERR; + return -1; + } + } + for (dgst_num = 0; dgst_num < SSL_MAX_DIGEST; dgst_num++) + if (s->s3->handshake_dgst[dgst_num]) { + int dgst_size; + + s->method->ssl3_enc->cert_verify_mac(s, + EVP_MD_CTX_type + (s-> + s3->handshake_dgst + [dgst_num]), + &(s->s3-> + tmp.cert_verify_md + [offset])); + dgst_size = + EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]); + if (dgst_size < 0) { + s->state = SSL_ST_ERR; + ret = -1; + goto end; + } + offset += dgst_size; + } + } + break; + + case SSL3_ST_SR_CERT_VRFY_A: + case SSL3_ST_SR_CERT_VRFY_B: + ret = ssl3_get_cert_verify(s); + if (ret <= 0) + goto end; + +#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->state = SSL3_ST_SR_FINISHED_A; +#else + if (s->s3->next_proto_neg_seen) + s->state = SSL3_ST_SR_NEXT_PROTO_A; + else + s->state = SSL3_ST_SR_FINISHED_A; +#endif + s->init_num = 0; + break; + +#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) + case SSL3_ST_SR_NEXT_PROTO_A: + case SSL3_ST_SR_NEXT_PROTO_B: + /* + * Enable CCS for NPN. Receiving a CCS clears the flag, so make + * sure not to re-enable it to ban duplicates. This *should* be the + * first time we have received one - but we check anyway to be + * cautious. + * s->s3->change_cipher_spec is set when a CCS is + * processed in s3_pkt.c, and remains set until + * the client's Finished message is read. + */ + if (!s->s3->change_cipher_spec) + s->s3->flags |= SSL3_FLAGS_CCS_OK; + + ret = ssl3_get_next_proto(s); + if (ret <= 0) + goto end; + s->init_num = 0; + s->state = SSL3_ST_SR_FINISHED_A; + break; +#endif + + case SSL3_ST_SR_FINISHED_A: + case SSL3_ST_SR_FINISHED_B: + /* + * Enable CCS for handshakes without NPN. In NPN the CCS flag has + * already been set. Receiving a CCS clears the flag, so make + * sure not to re-enable it to ban duplicates. + * s->s3->change_cipher_spec is set when a CCS is + * processed in s3_pkt.c, and remains set until + * the client's Finished message is read. + */ + if (!s->s3->change_cipher_spec) + s->s3->flags |= SSL3_FLAGS_CCS_OK; + ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A, + SSL3_ST_SR_FINISHED_B); + if (ret <= 0) + goto end; + if (s->hit) + s->state = SSL_ST_OK; +#ifndef OPENSSL_NO_TLSEXT + else if (s->tlsext_ticket_expected) + s->state = SSL3_ST_SW_SESSION_TICKET_A; +#endif + else + s->state = SSL3_ST_SW_CHANGE_A; + s->init_num = 0; + break; + +#ifndef OPENSSL_NO_TLSEXT + case SSL3_ST_SW_SESSION_TICKET_A: + case SSL3_ST_SW_SESSION_TICKET_B: + ret = ssl3_send_newsession_ticket(s); + if (ret <= 0) + goto end; + s->state = SSL3_ST_SW_CHANGE_A; + s->init_num = 0; + break; + + case SSL3_ST_SW_CERT_STATUS_A: + case SSL3_ST_SW_CERT_STATUS_B: + ret = ssl3_send_cert_status(s); + if (ret <= 0) + goto end; + s->state = SSL3_ST_SW_KEY_EXCH_A; + s->init_num = 0; + break; + +#endif + + case SSL3_ST_SW_CHANGE_A: + case SSL3_ST_SW_CHANGE_B: + + s->session->cipher = s->s3->tmp.new_cipher; + if (!s->method->ssl3_enc->setup_key_block(s)) { + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + + ret = ssl3_send_change_cipher_spec(s, + SSL3_ST_SW_CHANGE_A, + SSL3_ST_SW_CHANGE_B); + + if (ret <= 0) + goto end; + s->state = SSL3_ST_SW_FINISHED_A; + s->init_num = 0; + + if (!s->method->ssl3_enc->change_cipher_state(s, + SSL3_CHANGE_CIPHER_SERVER_WRITE)) + { + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + + break; + + case SSL3_ST_SW_FINISHED_A: + case SSL3_ST_SW_FINISHED_B: + ret = ssl3_send_finished(s, + SSL3_ST_SW_FINISHED_A, + SSL3_ST_SW_FINISHED_B, + s->method-> + ssl3_enc->server_finished_label, + s->method-> + ssl3_enc->server_finished_label_len); + if (ret <= 0) + goto end; + s->state = SSL3_ST_SW_FLUSH; + if (s->hit) { +#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A; +#else + if (s->s3->next_proto_neg_seen) { + s->s3->tmp.next_state = SSL3_ST_SR_NEXT_PROTO_A; + } else + s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A; +#endif + } else + s->s3->tmp.next_state = SSL_ST_OK; + s->init_num = 0; + break; + + case SSL_ST_OK: + /* clean a few things up */ + ssl3_cleanup_key_block(s); + + BUF_MEM_free(s->init_buf); + s->init_buf = NULL; + + /* remove buffering on output */ + ssl_free_wbio_buffer(s); + + s->init_num = 0; + + if (s->renegotiate == 2) { /* skipped if we just sent a + * HelloRequest */ + s->renegotiate = 0; + s->new_session = 0; + + ssl_update_cache(s, SSL_SESS_CACHE_SERVER); + + s->ctx->stats.sess_accept_good++; + /* s->server=1; */ + s->handshake_func = ssl3_accept; + + if (cb != NULL) + cb(s, SSL_CB_HANDSHAKE_DONE, 1); + } + + ret = 1; + goto end; + /* break; */ + + case SSL_ST_ERR: + default: + SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNKNOWN_STATE); + ret = -1; + goto end; + /* break; */ + } + + if (!s->s3->tmp.reuse_message && !skip) { + if (s->debug) { + if ((ret = BIO_flush(s->wbio)) <= 0) + goto end; + } + + if ((cb != NULL) && (s->state != state)) { + new_state = s->state; + s->state = state; + cb(s, SSL_CB_ACCEPT_LOOP, 1); + s->state = new_state; + } + } + skip = 0; + } +",0,"int ssl3_accept(SSL *s) +{ + BUF_MEM *buf; + unsigned long alg_k, Time = (unsigned long)time(NULL); + void (*cb) (const SSL *ssl, int type, int val) = NULL; + int ret = -1; + int new_state, state, skip = 0; + + RAND_add(&Time, sizeof(Time), 0); + ERR_clear_error(); + clear_sys_error(); + + if (s->info_callback != NULL) + cb = s->info_callback; + else if (s->ctx->info_callback != NULL) + cb = s->ctx->info_callback; + + /* init things to blank */ + s->in_handshake++; + if (!SSL_in_init(s) || SSL_in_before(s)) + SSL_clear(s); + + if (s->cert == NULL) { + SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_NO_CERTIFICATE_SET); + return (-1); + } +#ifndef OPENSSL_NO_HEARTBEATS + /* + * If we're awaiting a HeartbeatResponse, pretend we already got and + * don't await it anymore, because Heartbeats don't make sense during + * handshakes anyway. + */ + if (s->tlsext_hb_pending) { + s->tlsext_hb_pending = 0; + s->tlsext_hb_seq++; + } +#endif + + for (;;) { + state = s->state; + + switch (s->state) { + case SSL_ST_RENEGOTIATE: + s->renegotiate = 1; + /* s->state=SSL_ST_ACCEPT; */ + + case SSL_ST_BEFORE: + case SSL_ST_ACCEPT: + case SSL_ST_BEFORE | SSL_ST_ACCEPT: + case SSL_ST_OK | SSL_ST_ACCEPT: + + s->server = 1; + if (cb != NULL) + cb(s, SSL_CB_HANDSHAKE_START, 1); + + if ((s->version >> 8) != 3) { + SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR); + s->state = SSL_ST_ERR; + return -1; + } + s->type = SSL_ST_ACCEPT; + + if (s->init_buf == NULL) { + if ((buf = BUF_MEM_new()) == NULL) { + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) { + BUF_MEM_free(buf); + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + s->init_buf = buf; + } + + if (!ssl3_setup_buffers(s)) { + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + + s->init_num = 0; + s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY; + s->s3->flags &= ~SSL3_FLAGS_CCS_OK; + /* + * Should have been reset by ssl3_get_finished, too. + */ + s->s3->change_cipher_spec = 0; + + if (s->state != SSL_ST_RENEGOTIATE) { + /* + * Ok, we now need to push on a buffering BIO so that the + * output is sent in a way that TCP likes :-) + */ + if (!ssl_init_wbio_buffer(s, 1)) { + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + + ssl3_init_finished_mac(s); + s->state = SSL3_ST_SR_CLNT_HELLO_A; + s->ctx->stats.sess_accept++; + } else if (!s->s3->send_connection_binding && + !(s->options & + SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { + /* + * Server attempting to renegotiate with client that doesn't + * support secure renegotiation. + */ + SSLerr(SSL_F_SSL3_ACCEPT, + SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); + ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } else { + /* + * s->state == SSL_ST_RENEGOTIATE, we will just send a + * HelloRequest + */ + s->ctx->stats.sess_accept_renegotiate++; + s->state = SSL3_ST_SW_HELLO_REQ_A; + } + break; + + case SSL3_ST_SW_HELLO_REQ_A: + case SSL3_ST_SW_HELLO_REQ_B: + + s->shutdown = 0; + ret = ssl3_send_hello_request(s); + if (ret <= 0) + goto end; + s->s3->tmp.next_state = SSL3_ST_SW_HELLO_REQ_C; + s->state = SSL3_ST_SW_FLUSH; + s->init_num = 0; + + ssl3_init_finished_mac(s); + break; + + case SSL3_ST_SW_HELLO_REQ_C: + s->state = SSL_ST_OK; + break; + + case SSL3_ST_SR_CLNT_HELLO_A: + case SSL3_ST_SR_CLNT_HELLO_B: + case SSL3_ST_SR_CLNT_HELLO_C: + + s->shutdown = 0; + ret = ssl3_get_client_hello(s); + if (ret <= 0) + goto end; +#ifndef OPENSSL_NO_SRP + s->state = SSL3_ST_SR_CLNT_HELLO_D; + case SSL3_ST_SR_CLNT_HELLO_D: + { + int al; + if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) { + /* + * callback indicates firther work to be done + */ + s->rwstate = SSL_X509_LOOKUP; + goto end; + } + if (ret != SSL_ERROR_NONE) { + ssl3_send_alert(s, SSL3_AL_FATAL, al); + /* + * This is not really an error but the only means to for + * a client to detect whether srp is supported. + */ + if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY) + SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_CLIENTHELLO_TLSEXT); + ret = SSL_TLSEXT_ERR_ALERT_FATAL; + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + } +#endif + + s->renegotiate = 2; + s->state = SSL3_ST_SW_SRVR_HELLO_A; + s->init_num = 0; + break; + + case SSL3_ST_SW_SRVR_HELLO_A: + case SSL3_ST_SW_SRVR_HELLO_B: + ret = ssl3_send_server_hello(s); + if (ret <= 0) + goto end; +#ifndef OPENSSL_NO_TLSEXT + if (s->hit) { + if (s->tlsext_ticket_expected) + s->state = SSL3_ST_SW_SESSION_TICKET_A; + else + s->state = SSL3_ST_SW_CHANGE_A; + } +#else + if (s->hit) + s->state = SSL3_ST_SW_CHANGE_A; +#endif + else + s->state = SSL3_ST_SW_CERT_A; + s->init_num = 0; + break; + + case SSL3_ST_SW_CERT_A: + case SSL3_ST_SW_CERT_B: + /* Check if it is anon DH or anon ECDH, */ + /* normal PSK or KRB5 or SRP */ + if (! + (s->s3->tmp. + new_cipher->algorithm_auth & (SSL_aNULL | SSL_aKRB5 | + SSL_aSRP)) +&& !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { + ret = ssl3_send_server_certificate(s); + if (ret <= 0) + goto end; +#ifndef OPENSSL_NO_TLSEXT + if (s->tlsext_status_expected) + s->state = SSL3_ST_SW_CERT_STATUS_A; + else + s->state = SSL3_ST_SW_KEY_EXCH_A; + } else { + skip = 1; + s->state = SSL3_ST_SW_KEY_EXCH_A; + } +#else + } else + skip = 1; + + s->state = SSL3_ST_SW_KEY_EXCH_A; +#endif + s->init_num = 0; + break; + + case SSL3_ST_SW_KEY_EXCH_A: + case SSL3_ST_SW_KEY_EXCH_B: + alg_k = s->s3->tmp.new_cipher->algorithm_mkey; + + /* + * clear this, it may get reset by + * send_server_key_exchange + */ + s->s3->tmp.use_rsa_tmp = 0; + + /* + * only send if a DH key exchange, fortezza or RSA but we have a + * sign only certificate PSK: may send PSK identity hints For + * ECC ciphersuites, we send a serverKeyExchange message only if + * the cipher suite is either ECDH-anon or ECDHE. In other cases, + * the server certificate contains the server's public key for + * key exchange. + */ + if (0 + /* + * PSK: send ServerKeyExchange if PSK identity hint if + * provided + */ +#ifndef OPENSSL_NO_PSK + || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint) +#endif +#ifndef OPENSSL_NO_SRP + /* SRP: send ServerKeyExchange */ + || (alg_k & SSL_kSRP) +#endif + || (alg_k & SSL_kEDH) + || (alg_k & SSL_kEECDH) + || ((alg_k & SSL_kRSA) + && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL + || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) + && EVP_PKEY_size(s->cert->pkeys + [SSL_PKEY_RSA_ENC].privatekey) * + 8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher) + ) + ) + ) + ) { + ret = ssl3_send_server_key_exchange(s); + if (ret <= 0) + goto end; + } else + skip = 1; + + s->state = SSL3_ST_SW_CERT_REQ_A; + s->init_num = 0; + break; + + case SSL3_ST_SW_CERT_REQ_A: + case SSL3_ST_SW_CERT_REQ_B: + if ( /* don't request cert unless asked for it: */ + !(s->verify_mode & SSL_VERIFY_PEER) || + /* + * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert + * during re-negotiation: + */ + ((s->session->peer != NULL) && + (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) || + /* + * never request cert in anonymous ciphersuites (see + * section ""Certificate request"" in SSL 3 drafts and in + * RFC 2246): + */ + ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) && + /* + * ... except when the application insists on + * verification (against the specs, but s3_clnt.c accepts + * this for SSL 3) + */ + !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) || + /* + * never request cert in Kerberos ciphersuites + */ + (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) || + /* don't request certificate for SRP auth */ + (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP) + /* + * With normal PSK Certificates and Certificate Requests + * are omitted + */ + || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { + /* no cert request */ + skip = 1; + s->s3->tmp.cert_request = 0; + s->state = SSL3_ST_SW_SRVR_DONE_A; + if (s->s3->handshake_buffer) { + if (!ssl3_digest_cached_records(s)) { + s->state = SSL_ST_ERR; + return -1; + } + } + } else { + s->s3->tmp.cert_request = 1; + ret = ssl3_send_certificate_request(s); + if (ret <= 0) + goto end; +#ifndef NETSCAPE_HANG_BUG + s->state = SSL3_ST_SW_SRVR_DONE_A; +#else + s->state = SSL3_ST_SW_FLUSH; + s->s3->tmp.next_state = SSL3_ST_SR_CERT_A; +#endif + s->init_num = 0; + } + break; + + case SSL3_ST_SW_SRVR_DONE_A: + case SSL3_ST_SW_SRVR_DONE_B: + ret = ssl3_send_server_done(s); + if (ret <= 0) + goto end; + s->s3->tmp.next_state = SSL3_ST_SR_CERT_A; + s->state = SSL3_ST_SW_FLUSH; + s->init_num = 0; + break; + + case SSL3_ST_SW_FLUSH: + + /* + * This code originally checked to see if any data was pending + * using BIO_CTRL_INFO and then flushed. This caused problems as + * documented in PR#1939. The proposed fix doesn't completely + * resolve this issue as buggy implementations of + * BIO_CTRL_PENDING still exist. So instead we just flush + * unconditionally. + */ + + s->rwstate = SSL_WRITING; + if (BIO_flush(s->wbio) <= 0) { + ret = -1; + goto end; + } + s->rwstate = SSL_NOTHING; + + s->state = s->s3->tmp.next_state; + break; + + case SSL3_ST_SR_CERT_A: + case SSL3_ST_SR_CERT_B: + if (s->s3->tmp.cert_request) { + ret = ssl3_get_client_certificate(s); + if (ret <= 0) + goto end; + } + s->init_num = 0; + s->state = SSL3_ST_SR_KEY_EXCH_A; + break; + + case SSL3_ST_SR_KEY_EXCH_A: + case SSL3_ST_SR_KEY_EXCH_B: + ret = ssl3_get_client_key_exchange(s); + if (ret <= 0) + goto end; + if (ret == 2) { + /* + * For the ECDH ciphersuites when the client sends its ECDH + * pub key in a certificate, the CertificateVerify message is + * not sent. Also for GOST ciphersuites when the client uses + * its key from the certificate for key exchange. + */ +#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->state = SSL3_ST_SR_FINISHED_A; +#else + if (s->s3->next_proto_neg_seen) + s->state = SSL3_ST_SR_NEXT_PROTO_A; + else + s->state = SSL3_ST_SR_FINISHED_A; +#endif + s->init_num = 0; + } else if (SSL_USE_SIGALGS(s)) { + s->state = SSL3_ST_SR_CERT_VRFY_A; + s->init_num = 0; + if (!s->session->peer) + break; + /* + * For sigalgs freeze the handshake buffer at this point and + * digest cached records. + */ + if (!s->s3->handshake_buffer) { + SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR); + s->state = SSL_ST_ERR; + return -1; + } + s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE; + if (!ssl3_digest_cached_records(s)) { + s->state = SSL_ST_ERR; + return -1; + } + } else { + int offset = 0; + int dgst_num; + + s->state = SSL3_ST_SR_CERT_VRFY_A; + s->init_num = 0; + + /* + * We need to get hashes here so if there is a client cert, + * it can be verified FIXME - digest processing for + * CertificateVerify should be generalized. But it is next + * step + */ + if (s->s3->handshake_buffer) { + if (!ssl3_digest_cached_records(s)) { + s->state = SSL_ST_ERR; + return -1; + } + } + for (dgst_num = 0; dgst_num < SSL_MAX_DIGEST; dgst_num++) + if (s->s3->handshake_dgst[dgst_num]) { + int dgst_size; + + s->method->ssl3_enc->cert_verify_mac(s, + EVP_MD_CTX_type + (s-> + s3->handshake_dgst + [dgst_num]), + &(s->s3-> + tmp.cert_verify_md + [offset])); + dgst_size = + EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]); + if (dgst_size < 0) { + s->state = SSL_ST_ERR; + ret = -1; + goto end; + } + offset += dgst_size; + } + } + break; + + case SSL3_ST_SR_CERT_VRFY_A: + case SSL3_ST_SR_CERT_VRFY_B: + ret = ssl3_get_cert_verify(s); + if (ret <= 0) + goto end; + +#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->state = SSL3_ST_SR_FINISHED_A; +#else + if (s->s3->next_proto_neg_seen) + s->state = SSL3_ST_SR_NEXT_PROTO_A; + else + s->state = SSL3_ST_SR_FINISHED_A; +#endif + s->init_num = 0; + break; + +#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) + case SSL3_ST_SR_NEXT_PROTO_A: + case SSL3_ST_SR_NEXT_PROTO_B: + /* + * Enable CCS for NPN. Receiving a CCS clears the flag, so make + * sure not to re-enable it to ban duplicates. This *should* be the + * first time we have received one - but we check anyway to be + * cautious. + * s->s3->change_cipher_spec is set when a CCS is + * processed in s3_pkt.c, and remains set until + * the client's Finished message is read. + */ + if (!s->s3->change_cipher_spec) + s->s3->flags |= SSL3_FLAGS_CCS_OK; + + ret = ssl3_get_next_proto(s); + if (ret <= 0) + goto end; + s->init_num = 0; + s->state = SSL3_ST_SR_FINISHED_A; + break; +#endif + + case SSL3_ST_SR_FINISHED_A: + case SSL3_ST_SR_FINISHED_B: + /* + * Enable CCS for handshakes without NPN. In NPN the CCS flag has + * already been set. Receiving a CCS clears the flag, so make + * sure not to re-enable it to ban duplicates. + * s->s3->change_cipher_spec is set when a CCS is + * processed in s3_pkt.c, and remains set until + * the client's Finished message is read. + */ + if (!s->s3->change_cipher_spec) + s->s3->flags |= SSL3_FLAGS_CCS_OK; + ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A, + SSL3_ST_SR_FINISHED_B); + if (ret <= 0) + goto end; + if (s->hit) + s->state = SSL_ST_OK; +#ifndef OPENSSL_NO_TLSEXT + else if (s->tlsext_ticket_expected) + s->state = SSL3_ST_SW_SESSION_TICKET_A; +#endif + else + s->state = SSL3_ST_SW_CHANGE_A; + s->init_num = 0; + break; + +#ifndef OPENSSL_NO_TLSEXT + case SSL3_ST_SW_SESSION_TICKET_A: + case SSL3_ST_SW_SESSION_TICKET_B: + ret = ssl3_send_newsession_ticket(s); + if (ret <= 0) + goto end; + s->state = SSL3_ST_SW_CHANGE_A; + s->init_num = 0; + break; + + case SSL3_ST_SW_CERT_STATUS_A: + case SSL3_ST_SW_CERT_STATUS_B: + ret = ssl3_send_cert_status(s); + if (ret <= 0) + goto end; + s->state = SSL3_ST_SW_KEY_EXCH_A; + s->init_num = 0; + break; + +#endif + + case SSL3_ST_SW_CHANGE_A: + case SSL3_ST_SW_CHANGE_B: + + s->session->cipher = s->s3->tmp.new_cipher; + if (!s->method->ssl3_enc->setup_key_block(s)) { + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + + ret = ssl3_send_change_cipher_spec(s, + SSL3_ST_SW_CHANGE_A, + SSL3_ST_SW_CHANGE_B); + + if (ret <= 0) + goto end; + s->state = SSL3_ST_SW_FINISHED_A; + s->init_num = 0; + + if (!s->method->ssl3_enc->change_cipher_state(s, + SSL3_CHANGE_CIPHER_SERVER_WRITE)) + { + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + + break; + + case SSL3_ST_SW_FINISHED_A: + case SSL3_ST_SW_FINISHED_B: + ret = ssl3_send_finished(s, + SSL3_ST_SW_FINISHED_A, + SSL3_ST_SW_FINISHED_B, + s->method-> + ssl3_enc->server_finished_label, + s->method-> + ssl3_enc->server_finished_label_len); + if (ret <= 0) + goto end; + s->state = SSL3_ST_SW_FLUSH; + if (s->hit) { +#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A; +#else + if (s->s3->next_proto_neg_seen) { + s->s3->tmp.next_state = SSL3_ST_SR_NEXT_PROTO_A; + } else + s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A; +#endif + } else + s->s3->tmp.next_state = SSL_ST_OK; + s->init_num = 0; + break; + + case SSL_ST_OK: + /* clean a few things up */ + ssl3_cleanup_key_block(s); + + BUF_MEM_free(s->init_buf); + s->init_buf = NULL; + + /* remove buffering on output */ + ssl_free_wbio_buffer(s); + + s->init_num = 0; + + if (s->renegotiate == 2) { /* skipped if we just sent a + * HelloRequest */ + s->renegotiate = 0; + s->new_session = 0; + + ssl_update_cache(s, SSL_SESS_CACHE_SERVER); + + s->ctx->stats.sess_accept_good++; + /* s->server=1; */ + s->handshake_func = ssl3_accept; + + if (cb != NULL) + cb(s, SSL_CB_HANDSHAKE_DONE, 1); + } + + ret = 1; + goto end; + /* break; */ + + case SSL_ST_ERR: + default: + SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNKNOWN_STATE); + ret = -1; + goto end; + /* break; */ + } + + if (!s->s3->tmp.reuse_message && !skip) { + if (s->debug) { + if ((ret = BIO_flush(s->wbio)) <= 0) + goto end; + } + + if ((cb != NULL) && (s->state != state)) { + new_state = s->state; + s->state = state; + cb(s, SSL_CB_ACCEPT_LOOP, 1); + s->state = new_state; + } + } + skip = 0; + } +","@@ -2780,7 +2780,7 @@ int ssl3_get_client_key_exchange(SSL *s) + + if (s->session->psk_identity != NULL) + OPENSSL_free(s->session->psk_identity); +- s->session->psk_identity = BUF_strdup((char *)p); ++ s->session->psk_identity = BUF_strndup((char *)p, i); + if (s->session->psk_identity == NULL) { + SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE); + goto psk_err; +",5296,5627,6144 +9020,"static int megasas_init_fw(struct megasas_instance *instance) +{ + u32 max_sectors_1; + u32 max_sectors_2, tmp_sectors, msix_enable; + u32 scratch_pad_1, scratch_pad_2, scratch_pad_3, status_reg; + resource_size_t base_addr; + struct megasas_ctrl_info *ctrl_info = NULL; + unsigned long bar_list; + int i, j, loop, fw_msix_count = 0; + struct IOV_111 *iovPtr; + struct fusion_context *fusion; + bool do_adp_reset = true; + + fusion = instance->ctrl_context; + + /* Find first memory bar */ + bar_list = pci_select_bars(instance->pdev, IORESOURCE_MEM); + instance->bar = find_first_bit(&bar_list, BITS_PER_LONG); + if (pci_request_selected_regions(instance->pdev, 1<bar, + ""megasas: LSI"")) { + dev_printk(KERN_DEBUG, &instance->pdev->dev, ""IO memory region busy!\n""); + return -EBUSY; + } + + base_addr = pci_resource_start(instance->pdev, instance->bar); + instance->reg_set = ioremap_nocache(base_addr, 8192); + + if (!instance->reg_set) { + dev_printk(KERN_DEBUG, &instance->pdev->dev, ""Failed to map IO mem\n""); + goto fail_ioremap; + } + + if (instance->adapter_type != MFI_SERIES) + instance->instancet = &megasas_instance_template_fusion; + else { + switch (instance->pdev->device) { + case PCI_DEVICE_ID_LSI_SAS1078R: + case PCI_DEVICE_ID_LSI_SAS1078DE: + instance->instancet = &megasas_instance_template_ppc; + break; + case PCI_DEVICE_ID_LSI_SAS1078GEN2: + case PCI_DEVICE_ID_LSI_SAS0079GEN2: + instance->instancet = &megasas_instance_template_gen2; + break; + case PCI_DEVICE_ID_LSI_SAS0073SKINNY: + case PCI_DEVICE_ID_LSI_SAS0071SKINNY: + instance->instancet = &megasas_instance_template_skinny; + break; + case PCI_DEVICE_ID_LSI_SAS1064R: + case PCI_DEVICE_ID_DELL_PERC5: + default: + instance->instancet = &megasas_instance_template_xscale; + instance->pd_list_not_supported = 1; + break; + } + } + + if (megasas_transition_to_ready(instance, 0)) { + if (instance->adapter_type >= INVADER_SERIES) { + status_reg = instance->instancet->read_fw_status_reg( + instance); + do_adp_reset = status_reg & MFI_RESET_ADAPTER; + } + + if (do_adp_reset) { + atomic_set(&instance->fw_reset_no_pci_access, 1); + instance->instancet->adp_reset + (instance, instance->reg_set); + atomic_set(&instance->fw_reset_no_pci_access, 0); + dev_info(&instance->pdev->dev, + ""FW restarted successfully from %s!\n"", + __func__); + + /*waiting for about 30 second before retry*/ + ssleep(30); + + if (megasas_transition_to_ready(instance, 0)) + goto fail_ready_state; + } else { + goto fail_ready_state; + } + } + + megasas_init_ctrl_params(instance); + + if (megasas_set_dma_mask(instance)) + goto fail_ready_state; + + if (megasas_alloc_ctrl_mem(instance)) + goto fail_alloc_dma_buf; + + if (megasas_alloc_ctrl_dma_buffers(instance)) + goto fail_alloc_dma_buf; + + fusion = instance->ctrl_context; + + if (instance->adapter_type >= VENTURA_SERIES) { + scratch_pad_2 = + megasas_readl(instance, + &instance->reg_set->outbound_scratch_pad_2); + instance->max_raid_mapsize = ((scratch_pad_2 >> + MR_MAX_RAID_MAP_SIZE_OFFSET_SHIFT) & + MR_MAX_RAID_MAP_SIZE_MASK); + } + + /* Check if MSI-X is supported while in ready state */ + msix_enable = (instance->instancet->read_fw_status_reg(instance) & + 0x4000000) >> 0x1a; + if (msix_enable && !msix_disable) { + int irq_flags = PCI_IRQ_MSIX; + + scratch_pad_1 = megasas_readl + (instance, &instance->reg_set->outbound_scratch_pad_1); + /* Check max MSI-X vectors */ + if (fusion) { + if (instance->adapter_type == THUNDERBOLT_SERIES) { + /* Thunderbolt Series*/ + instance->msix_vectors = (scratch_pad_1 + & MR_MAX_REPLY_QUEUES_OFFSET) + 1; + fw_msix_count = instance->msix_vectors; + } else { + instance->msix_vectors = ((scratch_pad_1 + & MR_MAX_REPLY_QUEUES_EXT_OFFSET) + >> MR_MAX_REPLY_QUEUES_EXT_OFFSET_SHIFT) + 1; + + /* + * For Invader series, > 8 MSI-x vectors + * supported by FW/HW implies combined + * reply queue mode is enabled. + * For Ventura series, > 16 MSI-x vectors + * supported by FW/HW implies combined + * reply queue mode is enabled. + */ + switch (instance->adapter_type) { + case INVADER_SERIES: + if (instance->msix_vectors > 8) + instance->msix_combined = true; + break; + case AERO_SERIES: + case VENTURA_SERIES: + if (instance->msix_vectors > 16) + instance->msix_combined = true; + break; + } + + if (rdpq_enable) + instance->is_rdpq = (scratch_pad_1 & MR_RDPQ_MODE_OFFSET) ? + 1 : 0; + fw_msix_count = instance->msix_vectors; + /* Save 1-15 reply post index address to local memory + * Index 0 is already saved from reg offset + * MPI2_REPLY_POST_HOST_INDEX_OFFSET + */ + for (loop = 1; loop < MR_MAX_MSIX_REG_ARRAY; loop++) { + instance->reply_post_host_index_addr[loop] = + (u32 __iomem *) + ((u8 __iomem *)instance->reg_set + + MPI2_SUP_REPLY_POST_HOST_INDEX_OFFSET + + (loop * 0x10)); + } + } + if (msix_vectors) + instance->msix_vectors = min(msix_vectors, + instance->msix_vectors); + } else /* MFI adapters */ + instance->msix_vectors = 1; + /* Don't bother allocating more MSI-X vectors than cpus */ + instance->msix_vectors = min(instance->msix_vectors, + (unsigned int)num_online_cpus()); + if (smp_affinity_enable) + irq_flags |= PCI_IRQ_AFFINITY; + i = pci_alloc_irq_vectors(instance->pdev, 1, + instance->msix_vectors, irq_flags); + if (i > 0) + instance->msix_vectors = i; + else + instance->msix_vectors = 0; + } + /* + * MSI-X host index 0 is common for all adapter. + * It is used for all MPT based Adapters. + */ + if (instance->msix_combined) { + instance->reply_post_host_index_addr[0] = + (u32 *)((u8 *)instance->reg_set + + MPI2_SUP_REPLY_POST_HOST_INDEX_OFFSET); + } else { + instance->reply_post_host_index_addr[0] = + (u32 *)((u8 *)instance->reg_set + + MPI2_REPLY_POST_HOST_INDEX_OFFSET); + } + + if (!instance->msix_vectors) { + i = pci_alloc_irq_vectors(instance->pdev, 1, 1, PCI_IRQ_LEGACY); + if (i < 0) + goto fail_init_adapter; + } + + megasas_setup_reply_map(instance); + + dev_info(&instance->pdev->dev, + ""firmware supports msix\t: (%d)"", fw_msix_count); + dev_info(&instance->pdev->dev, + ""current msix/online cpus\t: (%d/%d)\n"", + instance->msix_vectors, (unsigned int)num_online_cpus()); + dev_info(&instance->pdev->dev, + ""RDPQ mode\t: (%s)\n"", instance->is_rdpq ? ""enabled"" : ""disabled""); + + tasklet_init(&instance->isr_tasklet, instance->instancet->tasklet, + (unsigned long)instance); + + /* + * Below are default value for legacy Firmware. + * non-fusion based controllers + */ + instance->fw_supported_vd_count = MAX_LOGICAL_DRIVES; + instance->fw_supported_pd_count = MAX_PHYSICAL_DEVICES; + /* Get operational params, sge flags, send init cmd to controller */ + if (instance->instancet->init_adapter(instance)) + goto fail_init_adapter; + + if (instance->adapter_type >= VENTURA_SERIES) { + scratch_pad_3 = + megasas_readl(instance, + &instance->reg_set->outbound_scratch_pad_3); + if ((scratch_pad_3 & MR_NVME_PAGE_SIZE_MASK) >= + MR_DEFAULT_NVME_PAGE_SHIFT) + instance->nvme_page_size = + (1 << (scratch_pad_3 & MR_NVME_PAGE_SIZE_MASK)); + + dev_info(&instance->pdev->dev, + ""NVME page size\t: (%d)\n"", instance->nvme_page_size); + } + + if (instance->msix_vectors ? + megasas_setup_irqs_msix(instance, 1) : + megasas_setup_irqs_ioapic(instance)) + goto fail_init_adapter; + + instance->instancet->enable_intr(instance); + + dev_info(&instance->pdev->dev, ""INIT adapter done\n""); + + megasas_setup_jbod_map(instance); + + if (megasas_get_device_list(instance) != SUCCESS) { + dev_err(&instance->pdev->dev, + ""%s: megasas_get_device_list failed\n"", + __func__); + goto fail_get_ld_pd_list; + } + + /* stream detection initialization */ + if (instance->adapter_type >= VENTURA_SERIES) { + fusion->stream_detect_by_ld = + kcalloc(MAX_LOGICAL_DRIVES_EXT, + sizeof(struct LD_STREAM_DETECT *), + GFP_KERNEL); + if (!fusion->stream_detect_by_ld) { + dev_err(&instance->pdev->dev, + ""unable to allocate stream detection for pool of LDs\n""); + goto fail_get_ld_pd_list; + } + for (i = 0; i < MAX_LOGICAL_DRIVES_EXT; ++i) { + fusion->stream_detect_by_ld[i] = + kzalloc(sizeof(struct LD_STREAM_DETECT), + GFP_KERNEL); + if (!fusion->stream_detect_by_ld[i]) { + dev_err(&instance->pdev->dev, + ""unable to allocate stream detect by LD\n ""); + for (j = 0; j < i; ++j) + kfree(fusion->stream_detect_by_ld[j]); + kfree(fusion->stream_detect_by_ld); + fusion->stream_detect_by_ld = NULL; + goto fail_get_ld_pd_list; + } + fusion->stream_detect_by_ld[i]->mru_bit_map + = MR_STREAM_BITMAP; + } + } + + /* + * Compute the max allowed sectors per IO: The controller info has two + * limits on max sectors. Driver should use the minimum of these two. + * + * 1 << stripe_sz_ops.min = max sectors per strip + * + * Note that older firmwares ( < FW ver 30) didn't report information + * to calculate max_sectors_1. So the number ended up as zero always. + */ + tmp_sectors = 0; + ctrl_info = instance->ctrl_info_buf; + + max_sectors_1 = (1 << ctrl_info->stripe_sz_ops.min) * + le16_to_cpu(ctrl_info->max_strips_per_io); + max_sectors_2 = le32_to_cpu(ctrl_info->max_request_size); + + tmp_sectors = min_t(u32, max_sectors_1, max_sectors_2); + + instance->peerIsPresent = ctrl_info->cluster.peerIsPresent; + instance->passive = ctrl_info->cluster.passive; + memcpy(instance->clusterId, ctrl_info->clusterId, sizeof(instance->clusterId)); + instance->UnevenSpanSupport = + ctrl_info->adapterOperations2.supportUnevenSpans; + if (instance->UnevenSpanSupport) { + struct fusion_context *fusion = instance->ctrl_context; + if (MR_ValidateMapInfo(instance, instance->map_id)) + fusion->fast_path_io = 1; + else + fusion->fast_path_io = 0; + + } + if (ctrl_info->host_interface.SRIOV) { + instance->requestorId = ctrl_info->iov.requestorId; + if (instance->pdev->device == PCI_DEVICE_ID_LSI_PLASMA) { + if (!ctrl_info->adapterOperations2.activePassive) + instance->PlasmaFW111 = 1; + + dev_info(&instance->pdev->dev, ""SR-IOV: firmware type: %s\n"", + instance->PlasmaFW111 ? ""1.11"" : ""new""); + + if (instance->PlasmaFW111) { + iovPtr = (struct IOV_111 *) + ((unsigned char *)ctrl_info + IOV_111_OFFSET); + instance->requestorId = iovPtr->requestorId; + } + } + dev_info(&instance->pdev->dev, ""SRIOV: VF requestorId %d\n"", + instance->requestorId); + } + + instance->crash_dump_fw_support = + ctrl_info->adapterOperations3.supportCrashDump; + instance->crash_dump_drv_support = + (instance->crash_dump_fw_support && + instance->crash_dump_buf); + if (instance->crash_dump_drv_support) + megasas_set_crash_dump_params(instance, + MR_CRASH_BUF_TURN_OFF); + + else { + if (instance->crash_dump_buf) + dma_free_coherent(&instance->pdev->dev, + CRASH_DMA_BUF_SIZE, + instance->crash_dump_buf, + instance->crash_dump_h); + instance->crash_dump_buf = NULL; + } + + if (instance->snapdump_wait_time) { + megasas_get_snapdump_properties(instance); + dev_info(&instance->pdev->dev, ""Snap dump wait time\t: %d\n"", + instance->snapdump_wait_time); + } + + dev_info(&instance->pdev->dev, + ""pci id\t\t: (0x%04x)/(0x%04x)/(0x%04x)/(0x%04x)\n"", + le16_to_cpu(ctrl_info->pci.vendor_id), + le16_to_cpu(ctrl_info->pci.device_id), + le16_to_cpu(ctrl_info->pci.sub_vendor_id), + le16_to_cpu(ctrl_info->pci.sub_device_id)); + dev_info(&instance->pdev->dev, ""unevenspan support : %s\n"", + instance->UnevenSpanSupport ? ""yes"" : ""no""); + dev_info(&instance->pdev->dev, ""firmware crash dump : %s\n"", + instance->crash_dump_drv_support ? ""yes"" : ""no""); + dev_info(&instance->pdev->dev, ""jbod sync map : %s\n"", + instance->use_seqnum_jbod_fp ? ""yes"" : ""no""); + + instance->max_sectors_per_req = instance->max_num_sge * + SGE_BUFFER_SIZE / 512; + if (tmp_sectors && (instance->max_sectors_per_req > tmp_sectors)) + instance->max_sectors_per_req = tmp_sectors; + + /* Check for valid throttlequeuedepth module parameter */ + if (throttlequeuedepth && + throttlequeuedepth <= instance->max_scsi_cmds) + instance->throttlequeuedepth = throttlequeuedepth; + else + instance->throttlequeuedepth = + MEGASAS_THROTTLE_QUEUE_DEPTH; + + if ((resetwaittime < 1) || + (resetwaittime > MEGASAS_RESET_WAIT_TIME)) + resetwaittime = MEGASAS_RESET_WAIT_TIME; + + if ((scmd_timeout < 10) || (scmd_timeout > MEGASAS_DEFAULT_CMD_TIMEOUT)) + scmd_timeout = MEGASAS_DEFAULT_CMD_TIMEOUT; + + /* Launch SR-IOV heartbeat timer */ + if (instance->requestorId) { + if (!megasas_sriov_start_heartbeat(instance, 1)) { + megasas_start_timer(instance); + } else { + instance->skip_heartbeat_timer_del = 1; + goto fail_get_ld_pd_list; + } + } + + /* + * Create and start watchdog thread which will monitor + * controller state every 1 sec and trigger OCR when + * it enters fault state + */ + if (instance->adapter_type != MFI_SERIES) + if (megasas_fusion_start_watchdog(instance) != SUCCESS) + goto fail_start_watchdog; + + return 0; + +fail_start_watchdog: + if (instance->requestorId && !instance->skip_heartbeat_timer_del) + del_timer_sync(&instance->sriov_heartbeat_timer); +fail_get_ld_pd_list: + instance->instancet->disable_intr(instance); + megasas_destroy_irqs(instance); +fail_init_adapter: + if (instance->msix_vectors) + pci_free_irq_vectors(instance->pdev); + instance->msix_vectors = 0; +fail_alloc_dma_buf: + megasas_free_ctrl_dma_buffers(instance); + megasas_free_ctrl_mem(instance); +fail_ready_state: + iounmap(instance->reg_set); + +fail_ioremap: + pci_release_selected_regions(instance->pdev, 1<bar); + + dev_err(&instance->pdev->dev, ""Failed from %s %d\n"", + __func__, __LINE__); + return -EINVAL; +} +",0,"static int megasas_init_fw(struct megasas_instance *instance) +{ + u32 max_sectors_1; + u32 max_sectors_2, tmp_sectors, msix_enable; + u32 scratch_pad_1, scratch_pad_2, scratch_pad_3, status_reg; + resource_size_t base_addr; + struct megasas_ctrl_info *ctrl_info = NULL; + unsigned long bar_list; + int i, j, loop, fw_msix_count = 0; + struct IOV_111 *iovPtr; + struct fusion_context *fusion; + bool do_adp_reset = true; + + fusion = instance->ctrl_context; + + /* Find first memory bar */ + bar_list = pci_select_bars(instance->pdev, IORESOURCE_MEM); + instance->bar = find_first_bit(&bar_list, BITS_PER_LONG); + if (pci_request_selected_regions(instance->pdev, 1<bar, + ""megasas: LSI"")) { + dev_printk(KERN_DEBUG, &instance->pdev->dev, ""IO memory region busy!\n""); + return -EBUSY; + } + + base_addr = pci_resource_start(instance->pdev, instance->bar); + instance->reg_set = ioremap_nocache(base_addr, 8192); + + if (!instance->reg_set) { + dev_printk(KERN_DEBUG, &instance->pdev->dev, ""Failed to map IO mem\n""); + goto fail_ioremap; + } + + if (instance->adapter_type != MFI_SERIES) + instance->instancet = &megasas_instance_template_fusion; + else { + switch (instance->pdev->device) { + case PCI_DEVICE_ID_LSI_SAS1078R: + case PCI_DEVICE_ID_LSI_SAS1078DE: + instance->instancet = &megasas_instance_template_ppc; + break; + case PCI_DEVICE_ID_LSI_SAS1078GEN2: + case PCI_DEVICE_ID_LSI_SAS0079GEN2: + instance->instancet = &megasas_instance_template_gen2; + break; + case PCI_DEVICE_ID_LSI_SAS0073SKINNY: + case PCI_DEVICE_ID_LSI_SAS0071SKINNY: + instance->instancet = &megasas_instance_template_skinny; + break; + case PCI_DEVICE_ID_LSI_SAS1064R: + case PCI_DEVICE_ID_DELL_PERC5: + default: + instance->instancet = &megasas_instance_template_xscale; + instance->pd_list_not_supported = 1; + break; + } + } + + if (megasas_transition_to_ready(instance, 0)) { + if (instance->adapter_type >= INVADER_SERIES) { + status_reg = instance->instancet->read_fw_status_reg( + instance); + do_adp_reset = status_reg & MFI_RESET_ADAPTER; + } + + if (do_adp_reset) { + atomic_set(&instance->fw_reset_no_pci_access, 1); + instance->instancet->adp_reset + (instance, instance->reg_set); + atomic_set(&instance->fw_reset_no_pci_access, 0); + dev_info(&instance->pdev->dev, + ""FW restarted successfully from %s!\n"", + __func__); + + /*waiting for about 30 second before retry*/ + ssleep(30); + + if (megasas_transition_to_ready(instance, 0)) + goto fail_ready_state; + } else { + goto fail_ready_state; + } + } + + megasas_init_ctrl_params(instance); + + if (megasas_set_dma_mask(instance)) + goto fail_ready_state; + + if (megasas_alloc_ctrl_mem(instance)) + goto fail_alloc_dma_buf; + + if (megasas_alloc_ctrl_dma_buffers(instance)) + goto fail_alloc_dma_buf; + + fusion = instance->ctrl_context; + + if (instance->adapter_type >= VENTURA_SERIES) { + scratch_pad_2 = + megasas_readl(instance, + &instance->reg_set->outbound_scratch_pad_2); + instance->max_raid_mapsize = ((scratch_pad_2 >> + MR_MAX_RAID_MAP_SIZE_OFFSET_SHIFT) & + MR_MAX_RAID_MAP_SIZE_MASK); + } + + /* Check if MSI-X is supported while in ready state */ + msix_enable = (instance->instancet->read_fw_status_reg(instance) & + 0x4000000) >> 0x1a; + if (msix_enable && !msix_disable) { + int irq_flags = PCI_IRQ_MSIX; + + scratch_pad_1 = megasas_readl + (instance, &instance->reg_set->outbound_scratch_pad_1); + /* Check max MSI-X vectors */ + if (fusion) { + if (instance->adapter_type == THUNDERBOLT_SERIES) { + /* Thunderbolt Series*/ + instance->msix_vectors = (scratch_pad_1 + & MR_MAX_REPLY_QUEUES_OFFSET) + 1; + fw_msix_count = instance->msix_vectors; + } else { + instance->msix_vectors = ((scratch_pad_1 + & MR_MAX_REPLY_QUEUES_EXT_OFFSET) + >> MR_MAX_REPLY_QUEUES_EXT_OFFSET_SHIFT) + 1; + + /* + * For Invader series, > 8 MSI-x vectors + * supported by FW/HW implies combined + * reply queue mode is enabled. + * For Ventura series, > 16 MSI-x vectors + * supported by FW/HW implies combined + * reply queue mode is enabled. + */ + switch (instance->adapter_type) { + case INVADER_SERIES: + if (instance->msix_vectors > 8) + instance->msix_combined = true; + break; + case AERO_SERIES: + case VENTURA_SERIES: + if (instance->msix_vectors > 16) + instance->msix_combined = true; + break; + } + + if (rdpq_enable) + instance->is_rdpq = (scratch_pad_1 & MR_RDPQ_MODE_OFFSET) ? + 1 : 0; + fw_msix_count = instance->msix_vectors; + /* Save 1-15 reply post index address to local memory + * Index 0 is already saved from reg offset + * MPI2_REPLY_POST_HOST_INDEX_OFFSET + */ + for (loop = 1; loop < MR_MAX_MSIX_REG_ARRAY; loop++) { + instance->reply_post_host_index_addr[loop] = + (u32 __iomem *) + ((u8 __iomem *)instance->reg_set + + MPI2_SUP_REPLY_POST_HOST_INDEX_OFFSET + + (loop * 0x10)); + } + } + if (msix_vectors) + instance->msix_vectors = min(msix_vectors, + instance->msix_vectors); + } else /* MFI adapters */ + instance->msix_vectors = 1; + /* Don't bother allocating more MSI-X vectors than cpus */ + instance->msix_vectors = min(instance->msix_vectors, + (unsigned int)num_online_cpus()); + if (smp_affinity_enable) + irq_flags |= PCI_IRQ_AFFINITY; + i = pci_alloc_irq_vectors(instance->pdev, 1, + instance->msix_vectors, irq_flags); + if (i > 0) + instance->msix_vectors = i; + else + instance->msix_vectors = 0; + } + /* + * MSI-X host index 0 is common for all adapter. + * It is used for all MPT based Adapters. + */ + if (instance->msix_combined) { + instance->reply_post_host_index_addr[0] = + (u32 *)((u8 *)instance->reg_set + + MPI2_SUP_REPLY_POST_HOST_INDEX_OFFSET); + } else { + instance->reply_post_host_index_addr[0] = + (u32 *)((u8 *)instance->reg_set + + MPI2_REPLY_POST_HOST_INDEX_OFFSET); + } + + if (!instance->msix_vectors) { + i = pci_alloc_irq_vectors(instance->pdev, 1, 1, PCI_IRQ_LEGACY); + if (i < 0) + goto fail_init_adapter; + } + + megasas_setup_reply_map(instance); + + dev_info(&instance->pdev->dev, + ""firmware supports msix\t: (%d)"", fw_msix_count); + dev_info(&instance->pdev->dev, + ""current msix/online cpus\t: (%d/%d)\n"", + instance->msix_vectors, (unsigned int)num_online_cpus()); + dev_info(&instance->pdev->dev, + ""RDPQ mode\t: (%s)\n"", instance->is_rdpq ? ""enabled"" : ""disabled""); + + tasklet_init(&instance->isr_tasklet, instance->instancet->tasklet, + (unsigned long)instance); + + /* + * Below are default value for legacy Firmware. + * non-fusion based controllers + */ + instance->fw_supported_vd_count = MAX_LOGICAL_DRIVES; + instance->fw_supported_pd_count = MAX_PHYSICAL_DEVICES; + /* Get operational params, sge flags, send init cmd to controller */ + if (instance->instancet->init_adapter(instance)) + goto fail_init_adapter; + + if (instance->adapter_type >= VENTURA_SERIES) { + scratch_pad_3 = + megasas_readl(instance, + &instance->reg_set->outbound_scratch_pad_3); + if ((scratch_pad_3 & MR_NVME_PAGE_SIZE_MASK) >= + MR_DEFAULT_NVME_PAGE_SHIFT) + instance->nvme_page_size = + (1 << (scratch_pad_3 & MR_NVME_PAGE_SIZE_MASK)); + + dev_info(&instance->pdev->dev, + ""NVME page size\t: (%d)\n"", instance->nvme_page_size); + } + + if (instance->msix_vectors ? + megasas_setup_irqs_msix(instance, 1) : + megasas_setup_irqs_ioapic(instance)) + goto fail_init_adapter; + + instance->instancet->enable_intr(instance); + + dev_info(&instance->pdev->dev, ""INIT adapter done\n""); + + megasas_setup_jbod_map(instance); + + if (megasas_get_device_list(instance) != SUCCESS) { + dev_err(&instance->pdev->dev, + ""%s: megasas_get_device_list failed\n"", + __func__); + goto fail_get_ld_pd_list; + } + + /* stream detection initialization */ + if (instance->adapter_type >= VENTURA_SERIES) { + fusion->stream_detect_by_ld = + kcalloc(MAX_LOGICAL_DRIVES_EXT, + sizeof(struct LD_STREAM_DETECT *), + GFP_KERNEL); + if (!fusion->stream_detect_by_ld) { + dev_err(&instance->pdev->dev, + ""unable to allocate stream detection for pool of LDs\n""); + goto fail_get_ld_pd_list; + } + for (i = 0; i < MAX_LOGICAL_DRIVES_EXT; ++i) { + fusion->stream_detect_by_ld[i] = + kzalloc(sizeof(struct LD_STREAM_DETECT), + GFP_KERNEL); + if (!fusion->stream_detect_by_ld[i]) { + dev_err(&instance->pdev->dev, + ""unable to allocate stream detect by LD\n ""); + for (j = 0; j < i; ++j) + kfree(fusion->stream_detect_by_ld[j]); + kfree(fusion->stream_detect_by_ld); + fusion->stream_detect_by_ld = NULL; + goto fail_get_ld_pd_list; + } + fusion->stream_detect_by_ld[i]->mru_bit_map + = MR_STREAM_BITMAP; + } + } + + /* + * Compute the max allowed sectors per IO: The controller info has two + * limits on max sectors. Driver should use the minimum of these two. + * + * 1 << stripe_sz_ops.min = max sectors per strip + * + * Note that older firmwares ( < FW ver 30) didn't report information + * to calculate max_sectors_1. So the number ended up as zero always. + */ + tmp_sectors = 0; + ctrl_info = instance->ctrl_info_buf; + + max_sectors_1 = (1 << ctrl_info->stripe_sz_ops.min) * + le16_to_cpu(ctrl_info->max_strips_per_io); + max_sectors_2 = le32_to_cpu(ctrl_info->max_request_size); + + tmp_sectors = min_t(u32, max_sectors_1, max_sectors_2); + + instance->peerIsPresent = ctrl_info->cluster.peerIsPresent; + instance->passive = ctrl_info->cluster.passive; + memcpy(instance->clusterId, ctrl_info->clusterId, sizeof(instance->clusterId)); + instance->UnevenSpanSupport = + ctrl_info->adapterOperations2.supportUnevenSpans; + if (instance->UnevenSpanSupport) { + struct fusion_context *fusion = instance->ctrl_context; + if (MR_ValidateMapInfo(instance, instance->map_id)) + fusion->fast_path_io = 1; + else + fusion->fast_path_io = 0; + + } + if (ctrl_info->host_interface.SRIOV) { + instance->requestorId = ctrl_info->iov.requestorId; + if (instance->pdev->device == PCI_DEVICE_ID_LSI_PLASMA) { + if (!ctrl_info->adapterOperations2.activePassive) + instance->PlasmaFW111 = 1; + + dev_info(&instance->pdev->dev, ""SR-IOV: firmware type: %s\n"", + instance->PlasmaFW111 ? ""1.11"" : ""new""); + + if (instance->PlasmaFW111) { + iovPtr = (struct IOV_111 *) + ((unsigned char *)ctrl_info + IOV_111_OFFSET); + instance->requestorId = iovPtr->requestorId; + } + } + dev_info(&instance->pdev->dev, ""SRIOV: VF requestorId %d\n"", + instance->requestorId); + } + + instance->crash_dump_fw_support = + ctrl_info->adapterOperations3.supportCrashDump; + instance->crash_dump_drv_support = + (instance->crash_dump_fw_support && + instance->crash_dump_buf); + if (instance->crash_dump_drv_support) + megasas_set_crash_dump_params(instance, + MR_CRASH_BUF_TURN_OFF); + + else { + if (instance->crash_dump_buf) + dma_free_coherent(&instance->pdev->dev, + CRASH_DMA_BUF_SIZE, + instance->crash_dump_buf, + instance->crash_dump_h); + instance->crash_dump_buf = NULL; + } + + if (instance->snapdump_wait_time) { + megasas_get_snapdump_properties(instance); + dev_info(&instance->pdev->dev, ""Snap dump wait time\t: %d\n"", + instance->snapdump_wait_time); + } + + dev_info(&instance->pdev->dev, + ""pci id\t\t: (0x%04x)/(0x%04x)/(0x%04x)/(0x%04x)\n"", + le16_to_cpu(ctrl_info->pci.vendor_id), + le16_to_cpu(ctrl_info->pci.device_id), + le16_to_cpu(ctrl_info->pci.sub_vendor_id), + le16_to_cpu(ctrl_info->pci.sub_device_id)); + dev_info(&instance->pdev->dev, ""unevenspan support : %s\n"", + instance->UnevenSpanSupport ? ""yes"" : ""no""); + dev_info(&instance->pdev->dev, ""firmware crash dump : %s\n"", + instance->crash_dump_drv_support ? ""yes"" : ""no""); + dev_info(&instance->pdev->dev, ""jbod sync map : %s\n"", + instance->use_seqnum_jbod_fp ? ""yes"" : ""no""); + + instance->max_sectors_per_req = instance->max_num_sge * + SGE_BUFFER_SIZE / 512; + if (tmp_sectors && (instance->max_sectors_per_req > tmp_sectors)) + instance->max_sectors_per_req = tmp_sectors; + + /* Check for valid throttlequeuedepth module parameter */ + if (throttlequeuedepth && + throttlequeuedepth <= instance->max_scsi_cmds) + instance->throttlequeuedepth = throttlequeuedepth; + else + instance->throttlequeuedepth = + MEGASAS_THROTTLE_QUEUE_DEPTH; + + if ((resetwaittime < 1) || + (resetwaittime > MEGASAS_RESET_WAIT_TIME)) + resetwaittime = MEGASAS_RESET_WAIT_TIME; + + if ((scmd_timeout < 10) || (scmd_timeout > MEGASAS_DEFAULT_CMD_TIMEOUT)) + scmd_timeout = MEGASAS_DEFAULT_CMD_TIMEOUT; + + /* Launch SR-IOV heartbeat timer */ + if (instance->requestorId) { + if (!megasas_sriov_start_heartbeat(instance, 1)) { + megasas_start_timer(instance); + } else { + instance->skip_heartbeat_timer_del = 1; + goto fail_get_ld_pd_list; + } + } + + /* + * Create and start watchdog thread which will monitor + * controller state every 1 sec and trigger OCR when + * it enters fault state + */ + if (instance->adapter_type != MFI_SERIES) + if (megasas_fusion_start_watchdog(instance) != SUCCESS) + goto fail_start_watchdog; + + return 0; + +fail_start_watchdog: + if (instance->requestorId && !instance->skip_heartbeat_timer_del) + del_timer_sync(&instance->sriov_heartbeat_timer); +fail_get_ld_pd_list: + instance->instancet->disable_intr(instance); + megasas_destroy_irqs(instance); +fail_init_adapter: + if (instance->msix_vectors) + pci_free_irq_vectors(instance->pdev); + instance->msix_vectors = 0; +fail_alloc_dma_buf: + megasas_free_ctrl_dma_buffers(instance); + megasas_free_ctrl_mem(instance); +fail_ready_state: + iounmap(instance->reg_set); + +fail_ioremap: + pci_release_selected_regions(instance->pdev, 1<bar); + + dev_err(&instance->pdev->dev, ""Failed from %s %d\n"", + __func__, __LINE__); + return -EINVAL; +} +","@@ -4188,6 +4188,7 @@ int megasas_alloc_cmds(struct megasas_instance *instance) + if (megasas_create_frame_pool(instance)) { + dev_printk(KERN_DEBUG, &instance->pdev->dev, ""Error creating frame DMA pool\n""); + megasas_free_cmds(instance); ++ return -ENOMEM; + } + + return 0;",3983,4314,6144 +18110,"static MagickBooleanType WritePICTImage(const ImageInfo *image_info, + Image *image) +{ +#define MaxCount 128 +#define PictCropRegionOp 0x01 +#define PictEndOfPictureOp 0xff +#define PictJPEGOp 0x8200 +#define PictInfoOp 0x0C00 +#define PictInfoSize 512 +#define PictPixmapOp 0x9A +#define PictPICTOp 0x98 +#define PictVersion 0x11 + + const StringInfo + *profile; + + double + x_resolution, + y_resolution; + + MagickBooleanType + status; + + MagickOffsetType + offset; + + PICTPixmap + pixmap; + + PICTRectangle + bounds, + crop_rectangle, + destination_rectangle, + frame_rectangle, + size_rectangle, + source_rectangle; + + register const IndexPacket + *indexes; + + register const PixelPacket + *p; + + register ssize_t + i, + x; + + size_t + bytes_per_line, + count, + row_bytes, + storage_class; + + ssize_t + y; + + unsigned char + *buffer, + *packed_scanline, + *scanline; + + + unsigned short + base_address, + transfer_mode; + + /* + 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); + if ((image->columns > 65535L) || (image->rows > 65535L)) + ThrowWriterException(ImageError,""WidthOrHeightExceedsLimit""); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); + if (status == MagickFalse) + return(status); + if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) + (void) TransformImageColorspace(image,sRGBColorspace); + /* + Initialize image info. + */ + size_rectangle.top=0; + size_rectangle.left=0; + size_rectangle.bottom=(short) image->rows; + size_rectangle.right=(short) image->columns; + frame_rectangle=size_rectangle; + crop_rectangle=size_rectangle; + source_rectangle=size_rectangle; + destination_rectangle=size_rectangle; + base_address=0xff; + row_bytes=image->columns; + bounds.top=0; + bounds.left=0; + bounds.bottom=(short) image->rows; + bounds.right=(short) image->columns; + pixmap.version=0; + pixmap.pack_type=0; + pixmap.pack_size=0; + pixmap.pixel_type=0; + pixmap.bits_per_pixel=8; + pixmap.component_count=1; + pixmap.component_size=8; + pixmap.plane_bytes=0; + pixmap.table=0; + pixmap.reserved=0; + transfer_mode=0; + x_resolution=image->x_resolution != 0.0 ? image->x_resolution : + DefaultResolution; + y_resolution=image->y_resolution != 0.0 ? image->y_resolution : + DefaultResolution; + storage_class=image->storage_class; + if (image_info->compression == JPEGCompression) + storage_class=DirectClass; + if (storage_class == DirectClass) + { + pixmap.component_count=image->matte != MagickFalse ? 4 : 3; + pixmap.pixel_type=16; + pixmap.bits_per_pixel=32; + pixmap.pack_type=0x04; + transfer_mode=0x40; + row_bytes=4*image->columns; + } + /* + Allocate memory. + */ + bytes_per_line=image->columns; + if (storage_class == DirectClass) + bytes_per_line*=image->matte != MagickFalse ? 4 : 3; + buffer=(unsigned char *) AcquireQuantumMemory(PictInfoSize,sizeof(*buffer)); + packed_scanline=(unsigned char *) AcquireQuantumMemory((size_t) + (row_bytes+MaxCount),sizeof(*packed_scanline)); + scanline=(unsigned char *) AcquireQuantumMemory(row_bytes,sizeof(*scanline)); + if ((buffer == (unsigned char *) NULL) || + (packed_scanline == (unsigned char *) NULL) || + (scanline == (unsigned char *) NULL)) + ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); + (void) ResetMagickMemory(scanline,0,row_bytes); + (void) ResetMagickMemory(packed_scanline,0,(size_t) (row_bytes+MaxCount)); + /* + Write header, header size, size bounding box, version, and reserved. + */ + (void) ResetMagickMemory(buffer,0,PictInfoSize); + (void) WriteBlob(image,PictInfoSize,buffer); + (void) WriteBlobMSBShort(image,0); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.right); + (void) WriteBlobMSBShort(image,PictVersion); + (void) WriteBlobMSBShort(image,0x02ff); /* version #2 */ + (void) WriteBlobMSBShort(image,PictInfoOp); + (void) WriteBlobMSBLong(image,0xFFFE0000UL); + /* + Write full size of the file, resolution, frame bounding box, and reserved. + */ + (void) WriteBlobMSBShort(image,(unsigned short) x_resolution); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) y_resolution); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.right); + (void) WriteBlobMSBLong(image,0x00000000L); + profile=GetImageProfile(image,""iptc""); + if (profile != (StringInfo *) NULL) + { + (void) WriteBlobMSBShort(image,0xa1); + (void) WriteBlobMSBShort(image,0x1f2); + (void) WriteBlobMSBShort(image,(unsigned short) + (GetStringInfoLength(profile)+4)); + (void) WriteBlobString(image,""8BIM""); + (void) WriteBlob(image,GetStringInfoLength(profile), + GetStringInfoDatum(profile)); + } + profile=GetImageProfile(image,""icc""); + if (profile != (StringInfo *) NULL) + { + (void) WriteBlobMSBShort(image,0xa1); + (void) WriteBlobMSBShort(image,0xe0); + (void) WriteBlobMSBShort(image,(unsigned short) + (GetStringInfoLength(profile)+4)); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlob(image,GetStringInfoLength(profile), + GetStringInfoDatum(profile)); + (void) WriteBlobMSBShort(image,0xa1); + (void) WriteBlobMSBShort(image,0xe0); + (void) WriteBlobMSBShort(image,4); + (void) WriteBlobMSBLong(image,0x00000002UL); + } + /* + Write crop region opcode and crop bounding box. + */ + (void) WriteBlobMSBShort(image,PictCropRegionOp); + (void) WriteBlobMSBShort(image,0xa); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.right); + if (image_info->compression == JPEGCompression) + { + Image + *jpeg_image; + + ImageInfo + *jpeg_info; + + size_t + length; + + unsigned char + *blob; + + jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception); + if (jpeg_image == (Image *) NULL) + { + (void) CloseBlob(image); + return(MagickFalse); + } + jpeg_info=CloneImageInfo(image_info); + (void) CopyMagickString(jpeg_info->magick,""JPEG"",MaxTextExtent); + length=0; + blob=(unsigned char *) ImageToBlob(jpeg_info,jpeg_image,&length, + &image->exception); + jpeg_info=DestroyImageInfo(jpeg_info); + if (blob == (unsigned char *) NULL) + return(MagickFalse); + jpeg_image=DestroyImage(jpeg_image); + (void) WriteBlobMSBShort(image,PictJPEGOp); + (void) WriteBlobMSBLong(image,(unsigned int) length+154); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBLong(image,0x00010000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00010000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x40000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00400000UL); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) image->rows); + (void) WriteBlobMSBShort(image,(unsigned short) image->columns); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,768); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00566A70UL); + (void) WriteBlobMSBLong(image,0x65670000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000001UL); + (void) WriteBlobMSBLong(image,0x00016170UL); + (void) WriteBlobMSBLong(image,0x706C0000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBShort(image,768); + (void) WriteBlobMSBShort(image,(unsigned short) image->columns); + (void) WriteBlobMSBShort(image,(unsigned short) image->rows); + (void) WriteBlobMSBShort(image,(unsigned short) x_resolution); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) y_resolution); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x87AC0001UL); + (void) WriteBlobMSBLong(image,0x0B466F74UL); + (void) WriteBlobMSBLong(image,0x6F202D20UL); + (void) WriteBlobMSBLong(image,0x4A504547UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x0018FFFFUL); + (void) WriteBlob(image,length,blob); + if ((length & 0x01) != 0) + (void) WriteBlobByte(image,'\0'); + blob=(unsigned char *) RelinquishMagickMemory(blob); + } + /* + Write picture opcode, row bytes, and picture bounding box, and version. + */ + if (storage_class == PseudoClass) + (void) WriteBlobMSBShort(image,PictPICTOp); + else + { + (void) WriteBlobMSBShort(image,PictPixmapOp); + (void) WriteBlobMSBLong(image,(size_t) base_address); + } + (void) WriteBlobMSBShort(image,(unsigned short) (row_bytes | 0x8000)); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.top); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.left); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.right); + /* + Write pack type, pack size, resolution, pixel type, and pixel size. + */ + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.version); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.pack_type); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.pack_size); + (void) WriteBlobMSBShort(image,(unsigned short) (x_resolution+0.5)); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) (y_resolution+0.5)); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.pixel_type); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.bits_per_pixel); + /* + Write component count, size, plane bytes, table size, and reserved. + */ + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_count); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_size); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.plane_bytes); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.table); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.reserved); + if (storage_class == PseudoClass) + { + /* + Write image colormap. + */ + (void) WriteBlobMSBLong(image,0x00000000L); /* color seed */ + (void) WriteBlobMSBShort(image,0L); /* color flags */ + (void) WriteBlobMSBShort(image,(unsigned short) (image->colors-1)); + for (i=0; i < (ssize_t) image->colors; i++) + { + (void) WriteBlobMSBShort(image,(unsigned short) i); + (void) WriteBlobMSBShort(image,ScaleQuantumToShort( + image->colormap[i].red)); + (void) WriteBlobMSBShort(image,ScaleQuantumToShort( + image->colormap[i].green)); + (void) WriteBlobMSBShort(image,ScaleQuantumToShort( + image->colormap[i].blue)); + } + } + /* + Write source and destination rectangle. + */ + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.right); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.right); + (void) WriteBlobMSBShort(image,(unsigned short) transfer_mode); + /* + Write picture data. + */ + count=0; + if (storage_class == PseudoClass) + 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); + for (x=0; x < (ssize_t) image->columns; x++) + scanline[x]=(unsigned char) GetPixelIndex(indexes+x); + count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF), + packed_scanline); + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + } + else + if (image_info->compression == JPEGCompression) + { + (void) ResetMagickMemory(scanline,0,row_bytes); + for (y=0; y < (ssize_t) image->rows; y++) + count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF), + packed_scanline); + } + else + { + register unsigned char + *blue, + *green, + *opacity, + *red; + + red=scanline; + green=scanline+image->columns; + blue=scanline+2*image->columns; + opacity=scanline+3*image->columns; + 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; + red=scanline; + green=scanline+image->columns; + blue=scanline+2*image->columns; + if (image->matte != MagickFalse) + { + opacity=scanline; + red=scanline+image->columns; + green=scanline+2*image->columns; + blue=scanline+3*image->columns; + } + for (x=0; x < (ssize_t) image->columns; x++) + { + *red++=ScaleQuantumToChar(GetPixelRed(p)); + *green++=ScaleQuantumToChar(GetPixelGreen(p)); + *blue++=ScaleQuantumToChar(GetPixelBlue(p)); + if (image->matte != MagickFalse) + *opacity++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(p))); + p++; + } + count+=EncodeImage(image,scanline,bytes_per_line,packed_scanline); + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + } + } + if ((count & 0x01) != 0) + (void) WriteBlobByte(image,'\0'); + (void) WriteBlobMSBShort(image,PictEndOfPictureOp); + offset=TellBlob(image); + offset=SeekBlob(image,512,SEEK_SET); + (void) WriteBlobMSBShort(image,(unsigned short) offset); + scanline=(unsigned char *) RelinquishMagickMemory(scanline); + packed_scanline=(unsigned char *) RelinquishMagickMemory(packed_scanline); + buffer=(unsigned char *) RelinquishMagickMemory(buffer); + (void) CloseBlob(image); + return(MagickTrue); +} +",1,"static MagickBooleanType WritePICTImage(const ImageInfo *image_info, + Image *image) +{ +#define MaxCount 128 +#define PictCropRegionOp 0x01 +#define PictEndOfPictureOp 0xff +#define PictJPEGOp 0x8200 +#define PictInfoOp 0x0C00 +#define PictInfoSize 512 +#define PictPixmapOp 0x9A +#define PictPICTOp 0x98 +#define PictVersion 0x11 + + const StringInfo + *profile; + + double + x_resolution, + y_resolution; + + MagickBooleanType + status; + + MagickOffsetType + offset; + + PICTPixmap + pixmap; + + PICTRectangle + bounds, + crop_rectangle, + destination_rectangle, + frame_rectangle, + size_rectangle, + source_rectangle; + + register const IndexPacket + *indexes; + + register const PixelPacket + *p; + + register ssize_t + i, + x; + + size_t + bytes_per_line, + count, + row_bytes, + storage_class; + + ssize_t + y; + + unsigned char + *buffer, + *packed_scanline, + *scanline; + + + unsigned short + base_address, + transfer_mode; + + /* + 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); + if ((image->columns > 65535L) || (image->rows > 65535L)) + ThrowWriterException(ImageError,""WidthOrHeightExceedsLimit""); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); + if (status == MagickFalse) + return(status); + if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) + (void) TransformImageColorspace(image,sRGBColorspace); + /* + Initialize image info. + */ + size_rectangle.top=0; + size_rectangle.left=0; + size_rectangle.bottom=(short) image->rows; + size_rectangle.right=(short) image->columns; + frame_rectangle=size_rectangle; + crop_rectangle=size_rectangle; + source_rectangle=size_rectangle; + destination_rectangle=size_rectangle; + base_address=0xff; + row_bytes=image->columns; + bounds.top=0; + bounds.left=0; + bounds.bottom=(short) image->rows; + bounds.right=(short) image->columns; + pixmap.version=0; + pixmap.pack_type=0; + pixmap.pack_size=0; + pixmap.pixel_type=0; + pixmap.bits_per_pixel=8; + pixmap.component_count=1; + pixmap.component_size=8; + pixmap.plane_bytes=0; + pixmap.table=0; + pixmap.reserved=0; + transfer_mode=0; + x_resolution=image->x_resolution != 0.0 ? image->x_resolution : + DefaultResolution; + y_resolution=image->y_resolution != 0.0 ? image->y_resolution : + DefaultResolution; + storage_class=image->storage_class; + if (image_info->compression == JPEGCompression) + storage_class=DirectClass; + if (storage_class == DirectClass) + { + pixmap.component_count=image->matte != MagickFalse ? 4 : 3; + pixmap.pixel_type=16; + pixmap.bits_per_pixel=32; + pixmap.pack_type=0x04; + transfer_mode=0x40; + row_bytes=4*image->columns; + } + /* + Allocate memory. + */ + bytes_per_line=image->columns; + if (storage_class == DirectClass) + bytes_per_line*=image->matte != MagickFalse ? 4 : 3; + buffer=(unsigned char *) AcquireQuantumMemory(PictInfoSize,sizeof(*buffer)); + packed_scanline=(unsigned char *) AcquireQuantumMemory((size_t) + (row_bytes+MaxCount),sizeof(*packed_scanline)); + scanline=(unsigned char *) AcquireQuantumMemory(row_bytes,sizeof(*scanline)); + if ((buffer == (unsigned char *) NULL) || + (packed_scanline == (unsigned char *) NULL) || + (scanline == (unsigned char *) NULL)) + { + if (scanline != (unsigned char *) NULL) + scanline=(unsigned char *) RelinquishMagickMemory(scanline); + if (packed_scanline != (unsigned char *) NULL) + packed_scanline=(unsigned char *) RelinquishMagickMemory( + packed_scanline); + if (buffer != (unsigned char *) NULL) + buffer=(unsigned char *) RelinquishMagickMemory(buffer); + ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); + } + (void) ResetMagickMemory(scanline,0,row_bytes); + (void) ResetMagickMemory(packed_scanline,0,(size_t) (row_bytes+MaxCount)); + /* + Write header, header size, size bounding box, version, and reserved. + */ + (void) ResetMagickMemory(buffer,0,PictInfoSize); + (void) WriteBlob(image,PictInfoSize,buffer); + (void) WriteBlobMSBShort(image,0); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.right); + (void) WriteBlobMSBShort(image,PictVersion); + (void) WriteBlobMSBShort(image,0x02ff); /* version #2 */ + (void) WriteBlobMSBShort(image,PictInfoOp); + (void) WriteBlobMSBLong(image,0xFFFE0000UL); + /* + Write full size of the file, resolution, frame bounding box, and reserved. + */ + (void) WriteBlobMSBShort(image,(unsigned short) x_resolution); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) y_resolution); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.right); + (void) WriteBlobMSBLong(image,0x00000000L); + profile=GetImageProfile(image,""iptc""); + if (profile != (StringInfo *) NULL) + { + (void) WriteBlobMSBShort(image,0xa1); + (void) WriteBlobMSBShort(image,0x1f2); + (void) WriteBlobMSBShort(image,(unsigned short) + (GetStringInfoLength(profile)+4)); + (void) WriteBlobString(image,""8BIM""); + (void) WriteBlob(image,GetStringInfoLength(profile), + GetStringInfoDatum(profile)); + } + profile=GetImageProfile(image,""icc""); + if (profile != (StringInfo *) NULL) + { + (void) WriteBlobMSBShort(image,0xa1); + (void) WriteBlobMSBShort(image,0xe0); + (void) WriteBlobMSBShort(image,(unsigned short) + (GetStringInfoLength(profile)+4)); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlob(image,GetStringInfoLength(profile), + GetStringInfoDatum(profile)); + (void) WriteBlobMSBShort(image,0xa1); + (void) WriteBlobMSBShort(image,0xe0); + (void) WriteBlobMSBShort(image,4); + (void) WriteBlobMSBLong(image,0x00000002UL); + } + /* + Write crop region opcode and crop bounding box. + */ + (void) WriteBlobMSBShort(image,PictCropRegionOp); + (void) WriteBlobMSBShort(image,0xa); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.right); + if (image_info->compression == JPEGCompression) + { + Image + *jpeg_image; + + ImageInfo + *jpeg_info; + + size_t + length; + + unsigned char + *blob; + + jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception); + if (jpeg_image == (Image *) NULL) + { + (void) CloseBlob(image); + return(MagickFalse); + } + jpeg_info=CloneImageInfo(image_info); + (void) CopyMagickString(jpeg_info->magick,""JPEG"",MaxTextExtent); + length=0; + blob=(unsigned char *) ImageToBlob(jpeg_info,jpeg_image,&length, + &image->exception); + jpeg_info=DestroyImageInfo(jpeg_info); + if (blob == (unsigned char *) NULL) + return(MagickFalse); + jpeg_image=DestroyImage(jpeg_image); + (void) WriteBlobMSBShort(image,PictJPEGOp); + (void) WriteBlobMSBLong(image,(unsigned int) length+154); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBLong(image,0x00010000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00010000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x40000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00400000UL); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) image->rows); + (void) WriteBlobMSBShort(image,(unsigned short) image->columns); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,768); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00566A70UL); + (void) WriteBlobMSBLong(image,0x65670000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000001UL); + (void) WriteBlobMSBLong(image,0x00016170UL); + (void) WriteBlobMSBLong(image,0x706C0000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBShort(image,768); + (void) WriteBlobMSBShort(image,(unsigned short) image->columns); + (void) WriteBlobMSBShort(image,(unsigned short) image->rows); + (void) WriteBlobMSBShort(image,(unsigned short) x_resolution); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) y_resolution); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x87AC0001UL); + (void) WriteBlobMSBLong(image,0x0B466F74UL); + (void) WriteBlobMSBLong(image,0x6F202D20UL); + (void) WriteBlobMSBLong(image,0x4A504547UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x0018FFFFUL); + (void) WriteBlob(image,length,blob); + if ((length & 0x01) != 0) + (void) WriteBlobByte(image,'\0'); + blob=(unsigned char *) RelinquishMagickMemory(blob); + } + /* + Write picture opcode, row bytes, and picture bounding box, and version. + */ + if (storage_class == PseudoClass) + (void) WriteBlobMSBShort(image,PictPICTOp); + else + { + (void) WriteBlobMSBShort(image,PictPixmapOp); + (void) WriteBlobMSBLong(image,(size_t) base_address); + } + (void) WriteBlobMSBShort(image,(unsigned short) (row_bytes | 0x8000)); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.top); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.left); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.right); + /* + Write pack type, pack size, resolution, pixel type, and pixel size. + */ + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.version); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.pack_type); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.pack_size); + (void) WriteBlobMSBShort(image,(unsigned short) (x_resolution+0.5)); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) (y_resolution+0.5)); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.pixel_type); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.bits_per_pixel); + /* + Write component count, size, plane bytes, table size, and reserved. + */ + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_count); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_size); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.plane_bytes); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.table); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.reserved); + if (storage_class == PseudoClass) + { + /* + Write image colormap. + */ + (void) WriteBlobMSBLong(image,0x00000000L); /* color seed */ + (void) WriteBlobMSBShort(image,0L); /* color flags */ + (void) WriteBlobMSBShort(image,(unsigned short) (image->colors-1)); + for (i=0; i < (ssize_t) image->colors; i++) + { + (void) WriteBlobMSBShort(image,(unsigned short) i); + (void) WriteBlobMSBShort(image,ScaleQuantumToShort( + image->colormap[i].red)); + (void) WriteBlobMSBShort(image,ScaleQuantumToShort( + image->colormap[i].green)); + (void) WriteBlobMSBShort(image,ScaleQuantumToShort( + image->colormap[i].blue)); + } + } + /* + Write source and destination rectangle. + */ + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.right); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.right); + (void) WriteBlobMSBShort(image,(unsigned short) transfer_mode); + /* + Write picture data. + */ + count=0; + if (storage_class == PseudoClass) + 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); + for (x=0; x < (ssize_t) image->columns; x++) + scanline[x]=(unsigned char) GetPixelIndex(indexes+x); + count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF), + packed_scanline); + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + } + else + if (image_info->compression == JPEGCompression) + { + (void) ResetMagickMemory(scanline,0,row_bytes); + for (y=0; y < (ssize_t) image->rows; y++) + count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF), + packed_scanline); + } + else + { + register unsigned char + *blue, + *green, + *opacity, + *red; + + red=scanline; + green=scanline+image->columns; + blue=scanline+2*image->columns; + opacity=scanline+3*image->columns; + 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; + red=scanline; + green=scanline+image->columns; + blue=scanline+2*image->columns; + if (image->matte != MagickFalse) + { + opacity=scanline; + red=scanline+image->columns; + green=scanline+2*image->columns; + blue=scanline+3*image->columns; + } + for (x=0; x < (ssize_t) image->columns; x++) + { + *red++=ScaleQuantumToChar(GetPixelRed(p)); + *green++=ScaleQuantumToChar(GetPixelGreen(p)); + *blue++=ScaleQuantumToChar(GetPixelBlue(p)); + if (image->matte != MagickFalse) + *opacity++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(p))); + p++; + } + count+=EncodeImage(image,scanline,bytes_per_line,packed_scanline); + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + } + } + if ((count & 0x01) != 0) + (void) WriteBlobByte(image,'\0'); + (void) WriteBlobMSBShort(image,PictEndOfPictureOp); + offset=TellBlob(image); + offset=SeekBlob(image,512,SEEK_SET); + (void) WriteBlobMSBShort(image,(unsigned short) offset); + scanline=(unsigned char *) RelinquishMagickMemory(scanline); + packed_scanline=(unsigned char *) RelinquishMagickMemory(packed_scanline); + buffer=(unsigned char *) RelinquishMagickMemory(buffer); + (void) CloseBlob(image); + return(MagickTrue); +} +","@@ -1758,7 +1758,16 @@ static MagickBooleanType WritePICTImage(const ImageInfo *image_info, + if ((buffer == (unsigned char *) NULL) || + (packed_scanline == (unsigned char *) NULL) || + (scanline == (unsigned char *) NULL)) +- ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); ++ { ++ if (scanline != (unsigned char *) NULL) ++ scanline=(unsigned char *) RelinquishMagickMemory(scanline); ++ if (packed_scanline != (unsigned char *) NULL) ++ packed_scanline=(unsigned char *) RelinquishMagickMemory( ++ packed_scanline); ++ if (buffer != (unsigned char *) NULL) ++ buffer=(unsigned char *) RelinquishMagickMemory(buffer); ++ ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); ++ } + (void) ResetMagickMemory(scanline,0,row_bytes); + (void) ResetMagickMemory(packed_scanline,0,(size_t) (row_bytes+MaxCount)); + /*",4738,5069,6144 +18123,"static Image *ReadOneJNGImage(MngInfo *mng_info, + const ImageInfo *image_info, ExceptionInfo *exception) +{ + Image + *alpha_image, + *color_image, + *image, + *jng_image; + + ImageInfo + *alpha_image_info, + *color_image_info; + + MagickBooleanType + logging; + + int + unique_filenames; + + ssize_t + y; + + MagickBooleanType + status; + + png_uint_32 + jng_height, + jng_width; + + png_byte + jng_color_type, + jng_image_sample_depth, + jng_image_compression_method, + jng_image_interlace_method, + jng_alpha_sample_depth, + jng_alpha_compression_method, + jng_alpha_filter_method, + jng_alpha_interlace_method; + + register const PixelPacket + *s; + + register ssize_t + i, + x; + + register PixelPacket + *q; + + register unsigned char + *p; + + unsigned int + read_JSEP, + reading_idat; + + size_t + length; + + jng_alpha_compression_method=0; + jng_alpha_sample_depth=8; + jng_color_type=0; + jng_height=0; + jng_width=0; + alpha_image=(Image *) NULL; + color_image=(Image *) NULL; + alpha_image_info=(ImageInfo *) NULL; + color_image_info=(ImageInfo *) NULL; + unique_filenames=0; + + logging=LogMagickEvent(CoderEvent,GetMagickModule(), + "" Enter ReadOneJNGImage()""); + + image=mng_info->image; + + if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) + { + /* + Allocate next image structure. + */ + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" AcquireNextImage()""); + + AcquireNextImage(image_info,image); + + if (GetNextImageInList(image) == (Image *) NULL) + return(DestroyImageList(image)); + + image=SyncNextImageInList(image); + } + mng_info->image=image; + + /* + Signature bytes have already been read. + */ + + read_JSEP=MagickFalse; + reading_idat=MagickFalse; + for (;;) + { + char + type[MaxTextExtent]; + + unsigned char + *chunk; + + unsigned int + count; + + /* + Read a new JNG chunk. + */ + status=SetImageProgress(image,LoadImagesTag,TellBlob(image), + 2*GetBlobSize(image)); + + if (status == MagickFalse) + break; + + type[0]='\0'; + (void) ConcatenateMagickString(type,""errr"",MaxTextExtent); + length=ReadBlobMSBLong(image); + count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Reading JNG chunk type %c%c%c%c, length: %.20g"", + type[0],type[1],type[2],type[3],(double) length); + + if (length > PNG_UINT_31_MAX || count == 0) + ThrowReaderException(CorruptImageError,""CorruptImage""); + + p=NULL; + chunk=(unsigned char *) NULL; + + if (length != 0) + { + chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); + + if (chunk == (unsigned char *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + + for (i=0; i < (ssize_t) length; i++) + chunk[i]=(unsigned char) ReadBlobByte(image); + + p=chunk; + } + + (void) ReadBlobMSBLong(image); /* read crc word */ + + if (memcmp(type,mng_JHDR,4) == 0) + { + if (length == 16) + { + jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | + (p[2] << 8) | p[3]); + jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | + (p[6] << 8) | p[7]); + if ((jng_width == 0) || (jng_height == 0)) + ThrowReaderException(CorruptImageError,""NegativeOrZeroImageSize""); + jng_color_type=p[8]; + jng_image_sample_depth=p[9]; + jng_image_compression_method=p[10]; + jng_image_interlace_method=p[11]; + + image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : + NoInterlace; + + jng_alpha_sample_depth=p[12]; + jng_alpha_compression_method=p[13]; + jng_alpha_filter_method=p[14]; + jng_alpha_interlace_method=p[15]; + + if (logging != MagickFalse) + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" jng_width: %16lu, jng_height: %16lu\n"" + "" jng_color_type: %16d, jng_image_sample_depth: %3d\n"" + "" jng_image_compression_method:%3d"", + (unsigned long) jng_width, (unsigned long) jng_height, + jng_color_type, jng_image_sample_depth, + jng_image_compression_method); + + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" jng_image_interlace_method: %3d"" + "" jng_alpha_sample_depth: %3d"", + jng_image_interlace_method, + jng_alpha_sample_depth); + + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" jng_alpha_compression_method:%3d\n"" + "" jng_alpha_filter_method: %3d\n"" + "" jng_alpha_interlace_method: %3d"", + jng_alpha_compression_method, + jng_alpha_filter_method, + jng_alpha_interlace_method); + } + } + + if (length != 0) + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + continue; + } + + + if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && + ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || + (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) + { + /* + o create color_image + o open color_blob, attached to color_image + o if (color type has alpha) + open alpha_blob, attached to alpha_image + */ + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Creating color_blob.""); + + color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); + + if (color_image_info == (ImageInfo *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + + GetImageInfo(color_image_info); + color_image=AcquireImage(color_image_info); + + if (color_image == (Image *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + + (void) AcquireUniqueFilename(color_image->filename); + unique_filenames++; + status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, + exception); + + if (status == MagickFalse) + { + color_image=DestroyImage(color_image); + return(DestroyImageList(image)); + } + + if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) + { + alpha_image_info=(ImageInfo *) + AcquireMagickMemory(sizeof(ImageInfo)); + + if (alpha_image_info == (ImageInfo *) NULL) + { + color_image=DestroyImage(color_image); + ThrowReaderException(ResourceLimitError, + ""MemoryAllocationFailed""); + } + + GetImageInfo(alpha_image_info); + alpha_image=AcquireImage(alpha_image_info); + + if (alpha_image == (Image *) NULL) + { + alpha_image_info=DestroyImageInfo(alpha_image_info); + color_image=DestroyImage(color_image); + ThrowReaderException(ResourceLimitError, + ""MemoryAllocationFailed""); + } + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Creating alpha_blob.""); + + (void) AcquireUniqueFilename(alpha_image->filename); + unique_filenames++; + status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, + exception); + + if (status == MagickFalse) + { + alpha_image=DestroyImage(alpha_image); + alpha_image_info=DestroyImageInfo(alpha_image_info); + color_image=DestroyImage(color_image); + return(DestroyImageList(image)); + } + + if (jng_alpha_compression_method == 0) + { + unsigned char + data[18]; + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Writing IHDR chunk to alpha_blob.""); + + (void) WriteBlob(alpha_image,8,(const unsigned char *) + ""\211PNG\r\n\032\n""); + + (void) WriteBlobMSBULong(alpha_image,13L); + PNGType(data,mng_IHDR); + LogPNGChunk(logging,mng_IHDR,13L); + PNGLong(data+4,jng_width); + PNGLong(data+8,jng_height); + data[12]=jng_alpha_sample_depth; + data[13]=0; /* color_type gray */ + data[14]=0; /* compression method 0 */ + data[15]=0; /* filter_method 0 */ + data[16]=0; /* interlace_method 0 */ + (void) WriteBlob(alpha_image,17,data); + (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); + } + } + reading_idat=MagickTrue; + } + + if (memcmp(type,mng_JDAT,4) == 0) + { + /* Copy chunk to color_image->blob */ + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Copying JDAT chunk data to color_blob.""); + + (void) WriteBlob(color_image,length,chunk); + if (length != 0) + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + continue; + } + + if (memcmp(type,mng_IDAT,4) == 0) + { + png_byte + data[5]; + + /* Copy IDAT header and chunk data to alpha_image->blob */ + + if (alpha_image != NULL && image_info->ping == MagickFalse) + { + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Copying IDAT chunk data to alpha_blob.""); + + (void) WriteBlobMSBULong(alpha_image,(size_t) length); + PNGType(data,mng_IDAT); + LogPNGChunk(logging,mng_IDAT,length); + (void) WriteBlob(alpha_image,4,data); + (void) WriteBlob(alpha_image,length,chunk); + (void) WriteBlobMSBULong(alpha_image, + crc32(crc32(0,data,4),chunk,(uInt) length)); + } + + if (length != 0) + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + continue; + } + + if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) + { + /* Copy chunk data to alpha_image->blob */ + + if (alpha_image != NULL && image_info->ping == MagickFalse) + { + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Copying JDAA chunk data to alpha_blob.""); + + (void) WriteBlob(alpha_image,length,chunk); + } + + if (length != 0) + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + continue; + } + + if (memcmp(type,mng_JSEP,4) == 0) + { + read_JSEP=MagickTrue; + + if (length != 0) + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + continue; + } + + if (memcmp(type,mng_bKGD,4) == 0) + { + if (length == 2) + { + image->background_color.red=ScaleCharToQuantum(p[1]); + image->background_color.green=image->background_color.red; + image->background_color.blue=image->background_color.red; + } + + if (length == 6) + { + image->background_color.red=ScaleCharToQuantum(p[1]); + image->background_color.green=ScaleCharToQuantum(p[3]); + image->background_color.blue=ScaleCharToQuantum(p[5]); + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + continue; + } + + if (memcmp(type,mng_gAMA,4) == 0) + { + if (length == 4) + image->gamma=((float) mng_get_long(p))*0.00001; + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + continue; + } + + if (memcmp(type,mng_cHRM,4) == 0) + { + if (length == 32) + { + image->chromaticity.white_point.x=0.00001*mng_get_long(p); + image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); + image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); + image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); + image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); + image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); + image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); + image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + continue; + } + + if (memcmp(type,mng_sRGB,4) == 0) + { + if (length == 1) + { + image->rendering_intent= + Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); + image->gamma=1.000f/2.200f; + image->chromaticity.red_primary.x=0.6400f; + image->chromaticity.red_primary.y=0.3300f; + image->chromaticity.green_primary.x=0.3000f; + image->chromaticity.green_primary.y=0.6000f; + image->chromaticity.blue_primary.x=0.1500f; + image->chromaticity.blue_primary.y=0.0600f; + image->chromaticity.white_point.x=0.3127f; + image->chromaticity.white_point.y=0.3290f; + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + continue; + } + + if (memcmp(type,mng_oFFs,4) == 0) + { + if (length > 8) + { + image->page.x=(ssize_t) mng_get_long(p); + image->page.y=(ssize_t) mng_get_long(&p[4]); + + if ((int) p[8] != 0) + { + image->page.x/=10000; + image->page.y/=10000; + } + } + + if (length != 0) + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + continue; + } + + if (memcmp(type,mng_pHYs,4) == 0) + { + if (length > 8) + { + image->x_resolution=(double) mng_get_long(p); + image->y_resolution=(double) mng_get_long(&p[4]); + if ((int) p[8] == PNG_RESOLUTION_METER) + { + image->units=PixelsPerCentimeterResolution; + image->x_resolution=image->x_resolution/100.0f; + image->y_resolution=image->y_resolution/100.0f; + } + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + continue; + } + +#if 0 + if (memcmp(type,mng_iCCP,4) == 0) + { + /* To do: */ + if (length != 0) + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + continue; + } +#endif + + if (length != 0) + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + if (memcmp(type,mng_IEND,4)) + continue; + + break; + } + + + /* IEND found */ + + /* + Finish up reading image data: + + o read main image from color_blob. + + o close color_blob. + + o if (color_type has alpha) + if alpha_encoding is PNG + read secondary image from alpha_blob via ReadPNG + if alpha_encoding is JPEG + read secondary image from alpha_blob via ReadJPEG + + o close alpha_blob. + + o copy intensity of secondary image into + opacity samples of main image. + + o destroy the secondary image. + */ + + if (color_image_info == (ImageInfo *) NULL) + { + assert(color_image == (Image *) NULL); + assert(alpha_image == (Image *) NULL); + return(DestroyImageList(image)); + } + + if (color_image == (Image *) NULL) + { + assert(alpha_image == (Image *) NULL); + return(DestroyImageList(image)); + } + + (void) SeekBlob(color_image,0,SEEK_SET); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Reading jng_image from color_blob.""); + + assert(color_image_info != (ImageInfo *) NULL); + (void) FormatLocaleString(color_image_info->filename,MaxTextExtent,""%s"", + color_image->filename); + + color_image_info->ping=MagickFalse; /* To do: avoid this */ + jng_image=ReadImage(color_image_info,exception); + + (void) RelinquishUniqueFileResource(color_image->filename); + unique_filenames--; + color_image=DestroyImage(color_image); + color_image_info=DestroyImageInfo(color_image_info); + + if (jng_image == (Image *) NULL) + return(DestroyImageList(image)); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Copying jng_image pixels to main image.""); + image->columns=jng_width; + image->rows=jng_height; + length=image->columns*sizeof(PixelPacket); + + status=SetImageExtent(image,image->columns,image->rows); + if (status == MagickFalse) + { + InheritException(exception,&image->exception); + return(DestroyImageList(image)); + } + + for (y=0; y < (ssize_t) image->rows; y++) + { + s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception); + q=GetAuthenticPixels(image,0,y,image->columns,1,exception); + (void) CopyMagickMemory(q,s,length); + + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + } + + jng_image=DestroyImage(jng_image); + + if (image_info->ping == MagickFalse) + { + if (jng_color_type >= 12) + { + if (jng_alpha_compression_method == 0) + { + png_byte + data[5]; + (void) WriteBlobMSBULong(alpha_image,0x00000000L); + PNGType(data,mng_IEND); + LogPNGChunk(logging,mng_IEND,0L); + (void) WriteBlob(alpha_image,4,data); + (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); + } + + (void) SeekBlob(alpha_image,0,SEEK_SET); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Reading opacity from alpha_blob.""); + + (void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent, + ""%s"",alpha_image->filename); + + jng_image=ReadImage(alpha_image_info,exception); + + if (jng_image != (Image *) NULL) + for (y=0; y < (ssize_t) image->rows; y++) + { + s=GetVirtualPixels(jng_image,0,y,image->columns,1, + &image->exception); + q=GetAuthenticPixels(image,0,y,image->columns,1,exception); + + if (image->matte != MagickFalse) + for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) + SetPixelOpacity(q,QuantumRange- + GetPixelRed(s)); + + else + for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) + { + SetPixelAlpha(q,GetPixelRed(s)); + if (GetPixelOpacity(q) != OpaqueOpacity) + image->matte=MagickTrue; + } + + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + } + (void) RelinquishUniqueFileResource(alpha_image->filename); + unique_filenames--; + alpha_image=DestroyImage(alpha_image); + alpha_image_info=DestroyImageInfo(alpha_image_info); + if (jng_image != (Image *) NULL) + jng_image=DestroyImage(jng_image); + } + } + + /* Read the JNG image. */ + + if (mng_info->mng_type == 0) + { + mng_info->mng_width=jng_width; + mng_info->mng_height=jng_height; + } + + if (image->page.width == 0 && image->page.height == 0) + { + image->page.width=jng_width; + image->page.height=jng_height; + } + + if (image->page.x == 0 && image->page.y == 0) + { + image->page.x=mng_info->x_off[mng_info->object_id]; + image->page.y=mng_info->y_off[mng_info->object_id]; + } + + else + { + image->page.y=mng_info->y_off[mng_info->object_id]; + } + + mng_info->image_found++; + status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), + 2*GetBlobSize(image)); + + if (status == MagickFalse) + return(DestroyImageList(image)); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" exit ReadOneJNGImage(); unique_filenames=%d"",unique_filenames); + + return(image); +} +",1,"static Image *ReadOneJNGImage(MngInfo *mng_info, + const ImageInfo *image_info, ExceptionInfo *exception) +{ + Image + *alpha_image, + *color_image, + *image, + *jng_image; + + ImageInfo + *alpha_image_info, + *color_image_info; + + MagickBooleanType + logging; + + int + unique_filenames; + + ssize_t + y; + + MagickBooleanType + status; + + png_uint_32 + jng_height, + jng_width; + + png_byte + jng_color_type, + jng_image_sample_depth, + jng_image_compression_method, + jng_image_interlace_method, + jng_alpha_sample_depth, + jng_alpha_compression_method, + jng_alpha_filter_method, + jng_alpha_interlace_method; + + register const PixelPacket + *s; + + register ssize_t + i, + x; + + register PixelPacket + *q; + + register unsigned char + *p; + + unsigned int + read_JSEP, + reading_idat; + + size_t + length; + + jng_alpha_compression_method=0; + jng_alpha_sample_depth=8; + jng_color_type=0; + jng_height=0; + jng_width=0; + alpha_image=(Image *) NULL; + color_image=(Image *) NULL; + alpha_image_info=(ImageInfo *) NULL; + color_image_info=(ImageInfo *) NULL; + unique_filenames=0; + + logging=LogMagickEvent(CoderEvent,GetMagickModule(), + "" Enter ReadOneJNGImage()""); + + image=mng_info->image; + + if (GetAuthenticPixelQueue(image) != (PixelPacket *) NULL) + { + /* + Allocate next image structure. + */ + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" AcquireNextImage()""); + + AcquireNextImage(image_info,image); + + if (GetNextImageInList(image) == (Image *) NULL) + return(DestroyImageList(image)); + + image=SyncNextImageInList(image); + } + mng_info->image=image; + + /* + Signature bytes have already been read. + */ + + read_JSEP=MagickFalse; + reading_idat=MagickFalse; + for (;;) + { + char + type[MaxTextExtent]; + + unsigned char + *chunk; + + unsigned int + count; + + /* + Read a new JNG chunk. + */ + status=SetImageProgress(image,LoadImagesTag,TellBlob(image), + 2*GetBlobSize(image)); + + if (status == MagickFalse) + break; + + type[0]='\0'; + (void) ConcatenateMagickString(type,""errr"",MaxTextExtent); + length=ReadBlobMSBLong(image); + count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Reading JNG chunk type %c%c%c%c, length: %.20g"", + type[0],type[1],type[2],type[3],(double) length); + + if (length > PNG_UINT_31_MAX || count == 0) + ThrowReaderException(CorruptImageError,""CorruptImage""); + + p=NULL; + chunk=(unsigned char *) NULL; + + if (length != 0) + { + chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); + + if (chunk == (unsigned char *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + + for (i=0; i < (ssize_t) length; i++) + chunk[i]=(unsigned char) ReadBlobByte(image); + + p=chunk; + } + + (void) ReadBlobMSBLong(image); /* read crc word */ + + if (memcmp(type,mng_JHDR,4) == 0) + { + if (length == 16) + { + jng_width=(size_t) ((p[0] << 24) | (p[1] << 16) | + (p[2] << 8) | p[3]); + jng_height=(size_t) ((p[4] << 24) | (p[5] << 16) | + (p[6] << 8) | p[7]); + if ((jng_width == 0) || (jng_height == 0)) + ThrowReaderException(CorruptImageError,""NegativeOrZeroImageSize""); + jng_color_type=p[8]; + jng_image_sample_depth=p[9]; + jng_image_compression_method=p[10]; + jng_image_interlace_method=p[11]; + + image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : + NoInterlace; + + jng_alpha_sample_depth=p[12]; + jng_alpha_compression_method=p[13]; + jng_alpha_filter_method=p[14]; + jng_alpha_interlace_method=p[15]; + + if (logging != MagickFalse) + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" jng_width: %16lu, jng_height: %16lu\n"" + "" jng_color_type: %16d, jng_image_sample_depth: %3d\n"" + "" jng_image_compression_method:%3d"", + (unsigned long) jng_width, (unsigned long) jng_height, + jng_color_type, jng_image_sample_depth, + jng_image_compression_method); + + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" jng_image_interlace_method: %3d"" + "" jng_alpha_sample_depth: %3d"", + jng_image_interlace_method, + jng_alpha_sample_depth); + + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" jng_alpha_compression_method:%3d\n"" + "" jng_alpha_filter_method: %3d\n"" + "" jng_alpha_interlace_method: %3d"", + jng_alpha_compression_method, + jng_alpha_filter_method, + jng_alpha_interlace_method); + } + } + + if (length != 0) + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + continue; + } + + + if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && + ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || + (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) + { + /* + o create color_image + o open color_blob, attached to color_image + o if (color type has alpha) + open alpha_blob, attached to alpha_image + */ + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Creating color_blob.""); + + color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); + + if (color_image_info == (ImageInfo *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + + GetImageInfo(color_image_info); + color_image=AcquireImage(color_image_info); + + if (color_image == (Image *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + + (void) AcquireUniqueFilename(color_image->filename); + unique_filenames++; + status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, + exception); + + if (status == MagickFalse) + { + color_image=DestroyImage(color_image); + return(DestroyImageList(image)); + } + + if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) + { + alpha_image_info=(ImageInfo *) + AcquireMagickMemory(sizeof(ImageInfo)); + + if (alpha_image_info == (ImageInfo *) NULL) + { + color_image=DestroyImage(color_image); + ThrowReaderException(ResourceLimitError, + ""MemoryAllocationFailed""); + } + + GetImageInfo(alpha_image_info); + alpha_image=AcquireImage(alpha_image_info); + + if (alpha_image == (Image *) NULL) + { + alpha_image_info=DestroyImageInfo(alpha_image_info); + color_image=DestroyImage(color_image); + ThrowReaderException(ResourceLimitError, + ""MemoryAllocationFailed""); + } + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Creating alpha_blob.""); + + (void) AcquireUniqueFilename(alpha_image->filename); + unique_filenames++; + status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, + exception); + + if (status == MagickFalse) + { + alpha_image=DestroyImage(alpha_image); + alpha_image_info=DestroyImageInfo(alpha_image_info); + color_image=DestroyImage(color_image); + return(DestroyImageList(image)); + } + + if (jng_alpha_compression_method == 0) + { + unsigned char + data[18]; + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Writing IHDR chunk to alpha_blob.""); + + (void) WriteBlob(alpha_image,8,(const unsigned char *) + ""\211PNG\r\n\032\n""); + + (void) WriteBlobMSBULong(alpha_image,13L); + PNGType(data,mng_IHDR); + LogPNGChunk(logging,mng_IHDR,13L); + PNGLong(data+4,jng_width); + PNGLong(data+8,jng_height); + data[12]=jng_alpha_sample_depth; + data[13]=0; /* color_type gray */ + data[14]=0; /* compression method 0 */ + data[15]=0; /* filter_method 0 */ + data[16]=0; /* interlace_method 0 */ + (void) WriteBlob(alpha_image,17,data); + (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); + } + } + reading_idat=MagickTrue; + } + + if (memcmp(type,mng_JDAT,4) == 0) + { + /* Copy chunk to color_image->blob */ + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Copying JDAT chunk data to color_blob.""); + + if (length != 0) + { + (void) WriteBlob(color_image,length,chunk); + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + } + + continue; + } + + if (memcmp(type,mng_IDAT,4) == 0) + { + png_byte + data[5]; + + /* Copy IDAT header and chunk data to alpha_image->blob */ + + if (alpha_image != NULL && image_info->ping == MagickFalse) + { + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Copying IDAT chunk data to alpha_blob.""); + + (void) WriteBlobMSBULong(alpha_image,(size_t) length); + PNGType(data,mng_IDAT); + LogPNGChunk(logging,mng_IDAT,length); + (void) WriteBlob(alpha_image,4,data); + (void) WriteBlob(alpha_image,length,chunk); + (void) WriteBlobMSBULong(alpha_image, + crc32(crc32(0,data,4),chunk,(uInt) length)); + } + + if (length != 0) + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + continue; + } + + if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) + { + /* Copy chunk data to alpha_image->blob */ + + if (alpha_image != NULL && image_info->ping == MagickFalse) + { + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Copying JDAA chunk data to alpha_blob.""); + + (void) WriteBlob(alpha_image,length,chunk); + } + + if (length != 0) + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + continue; + } + + if (memcmp(type,mng_JSEP,4) == 0) + { + read_JSEP=MagickTrue; + + if (length != 0) + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + continue; + } + + if (memcmp(type,mng_bKGD,4) == 0) + { + if (length == 2) + { + image->background_color.red=ScaleCharToQuantum(p[1]); + image->background_color.green=image->background_color.red; + image->background_color.blue=image->background_color.red; + } + + if (length == 6) + { + image->background_color.red=ScaleCharToQuantum(p[1]); + image->background_color.green=ScaleCharToQuantum(p[3]); + image->background_color.blue=ScaleCharToQuantum(p[5]); + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + continue; + } + + if (memcmp(type,mng_gAMA,4) == 0) + { + if (length == 4) + image->gamma=((float) mng_get_long(p))*0.00001; + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + continue; + } + + if (memcmp(type,mng_cHRM,4) == 0) + { + if (length == 32) + { + image->chromaticity.white_point.x=0.00001*mng_get_long(p); + image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); + image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); + image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); + image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); + image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); + image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); + image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + continue; + } + + if (memcmp(type,mng_sRGB,4) == 0) + { + if (length == 1) + { + image->rendering_intent= + Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); + image->gamma=1.000f/2.200f; + image->chromaticity.red_primary.x=0.6400f; + image->chromaticity.red_primary.y=0.3300f; + image->chromaticity.green_primary.x=0.3000f; + image->chromaticity.green_primary.y=0.6000f; + image->chromaticity.blue_primary.x=0.1500f; + image->chromaticity.blue_primary.y=0.0600f; + image->chromaticity.white_point.x=0.3127f; + image->chromaticity.white_point.y=0.3290f; + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + continue; + } + + if (memcmp(type,mng_oFFs,4) == 0) + { + if (length > 8) + { + image->page.x=(ssize_t) mng_get_long(p); + image->page.y=(ssize_t) mng_get_long(&p[4]); + + if ((int) p[8] != 0) + { + image->page.x/=10000; + image->page.y/=10000; + } + } + + if (length != 0) + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + continue; + } + + if (memcmp(type,mng_pHYs,4) == 0) + { + if (length > 8) + { + image->x_resolution=(double) mng_get_long(p); + image->y_resolution=(double) mng_get_long(&p[4]); + if ((int) p[8] == PNG_RESOLUTION_METER) + { + image->units=PixelsPerCentimeterResolution; + image->x_resolution=image->x_resolution/100.0f; + image->y_resolution=image->y_resolution/100.0f; + } + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + continue; + } + +#if 0 + if (memcmp(type,mng_iCCP,4) == 0) + { + /* To do: */ + if (length != 0) + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + continue; + } +#endif + + if (length != 0) + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + if (memcmp(type,mng_IEND,4)) + continue; + + break; + } + + + /* IEND found */ + + /* + Finish up reading image data: + + o read main image from color_blob. + + o close color_blob. + + o if (color_type has alpha) + if alpha_encoding is PNG + read secondary image from alpha_blob via ReadPNG + if alpha_encoding is JPEG + read secondary image from alpha_blob via ReadJPEG + + o close alpha_blob. + + o copy intensity of secondary image into + opacity samples of main image. + + o destroy the secondary image. + */ + + if (color_image_info == (ImageInfo *) NULL) + { + assert(color_image == (Image *) NULL); + assert(alpha_image == (Image *) NULL); + return(DestroyImageList(image)); + } + + if (color_image == (Image *) NULL) + { + assert(alpha_image == (Image *) NULL); + return(DestroyImageList(image)); + } + + (void) SeekBlob(color_image,0,SEEK_SET); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Reading jng_image from color_blob.""); + + assert(color_image_info != (ImageInfo *) NULL); + (void) FormatLocaleString(color_image_info->filename,MaxTextExtent,""%s"", + color_image->filename); + + color_image_info->ping=MagickFalse; /* To do: avoid this */ + jng_image=ReadImage(color_image_info,exception); + + (void) RelinquishUniqueFileResource(color_image->filename); + unique_filenames--; + color_image=DestroyImage(color_image); + color_image_info=DestroyImageInfo(color_image_info); + + if (jng_image == (Image *) NULL) + return(DestroyImageList(image)); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Copying jng_image pixels to main image.""); + image->columns=jng_width; + image->rows=jng_height; + length=image->columns*sizeof(PixelPacket); + + status=SetImageExtent(image,image->columns,image->rows); + if (status == MagickFalse) + { + InheritException(exception,&image->exception); + return(DestroyImageList(image)); + } + + for (y=0; y < (ssize_t) image->rows; y++) + { + s=GetVirtualPixels(jng_image,0,y,image->columns,1,&image->exception); + q=GetAuthenticPixels(image,0,y,image->columns,1,exception); + (void) CopyMagickMemory(q,s,length); + + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + } + + jng_image=DestroyImage(jng_image); + + if (image_info->ping == MagickFalse) + { + if (jng_color_type >= 12) + { + if (jng_alpha_compression_method == 0) + { + png_byte + data[5]; + (void) WriteBlobMSBULong(alpha_image,0x00000000L); + PNGType(data,mng_IEND); + LogPNGChunk(logging,mng_IEND,0L); + (void) WriteBlob(alpha_image,4,data); + (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); + } + + (void) SeekBlob(alpha_image,0,SEEK_SET); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Reading opacity from alpha_blob.""); + + (void) FormatLocaleString(alpha_image_info->filename,MaxTextExtent, + ""%s"",alpha_image->filename); + + jng_image=ReadImage(alpha_image_info,exception); + + if (jng_image != (Image *) NULL) + for (y=0; y < (ssize_t) image->rows; y++) + { + s=GetVirtualPixels(jng_image,0,y,image->columns,1, + &image->exception); + q=GetAuthenticPixels(image,0,y,image->columns,1,exception); + + if (image->matte != MagickFalse) + for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) + SetPixelOpacity(q,QuantumRange- + GetPixelRed(s)); + + else + for (x=(ssize_t) image->columns; x != 0; x--,q++,s++) + { + SetPixelAlpha(q,GetPixelRed(s)); + if (GetPixelOpacity(q) != OpaqueOpacity) + image->matte=MagickTrue; + } + + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + } + (void) RelinquishUniqueFileResource(alpha_image->filename); + unique_filenames--; + alpha_image=DestroyImage(alpha_image); + alpha_image_info=DestroyImageInfo(alpha_image_info); + if (jng_image != (Image *) NULL) + jng_image=DestroyImage(jng_image); + } + } + + /* Read the JNG image. */ + + if (mng_info->mng_type == 0) + { + mng_info->mng_width=jng_width; + mng_info->mng_height=jng_height; + } + + if (image->page.width == 0 && image->page.height == 0) + { + image->page.width=jng_width; + image->page.height=jng_height; + } + + if (image->page.x == 0 && image->page.y == 0) + { + image->page.x=mng_info->x_off[mng_info->object_id]; + image->page.y=mng_info->y_off[mng_info->object_id]; + } + + else + { + image->page.y=mng_info->y_off[mng_info->object_id]; + } + + mng_info->image_found++; + status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), + 2*GetBlobSize(image)); + + if (status == MagickFalse) + return(DestroyImageList(image)); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" exit ReadOneJNGImage(); unique_filenames=%d"",unique_filenames); + + return(image); +} +","@@ -4477,10 +4477,11 @@ static Image *ReadOneJNGImage(MngInfo *mng_info, + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Copying JDAT chunk data to color_blob.""); + +- (void) WriteBlob(color_image,length,chunk); +- + if (length != 0) +- chunk=(unsigned char *) RelinquishMagickMemory(chunk); ++ { ++ (void) WriteBlob(color_image,length,chunk); ++ chunk=(unsigned char *) RelinquishMagickMemory(chunk); ++ } + + continue; + }",5231,5562,6144 +18798,"WORD32 ihevcd_decode(iv_obj_t *ps_codec_obj, void *pv_api_ip, void *pv_api_op) +{ + WORD32 ret = IV_SUCCESS; + codec_t *ps_codec = (codec_t *)(ps_codec_obj->pv_codec_handle); + ivd_video_decode_ip_t *ps_dec_ip; + ivd_video_decode_op_t *ps_dec_op; + + WORD32 proc_idx = 0; + WORD32 prev_proc_idx = 0; + + /* Initialize error code */ + ps_codec->i4_error_code = 0; + + ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip; + ps_dec_op = (ivd_video_decode_op_t *)pv_api_op; + + { + UWORD32 u4_size = ps_dec_op->u4_size; + memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t)); + ps_dec_op->u4_size = u4_size; //Restore size field + } + if(ps_codec->i4_init_done != 1) + { + ps_dec_op->u4_error_code |= 1 << IVD_FATALERROR; + ps_dec_op->u4_error_code |= IHEVCD_INIT_NOT_DONE; + return IV_FAIL; + } + + if(ps_codec->u4_pic_cnt >= NUM_FRAMES_LIMIT) + { + ps_dec_op->u4_error_code |= 1 << IVD_FATALERROR; + ps_dec_op->u4_error_code |= IHEVCD_NUM_FRAMES_LIMIT_REACHED; + return IV_FAIL; + } + + /* If reset flag is set, flush the existing buffers */ + if(ps_codec->i4_reset_flag) + { + ps_codec->i4_flush_mode = 1; + } + + /*Data memory barries instruction,so that bitstream write by the application is complete*/ + /* In case the decoder is not in flush mode check for input buffer validity */ + if(0 == ps_codec->i4_flush_mode) + { + if(ps_dec_ip->pv_stream_buffer == NULL) + { + ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; + ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL; + return IV_FAIL; + } + if(ps_dec_ip->u4_num_Bytes <= MIN_START_CODE_LEN) + { + if((WORD32)ps_dec_ip->u4_num_Bytes > 0) + ps_dec_op->u4_num_bytes_consumed = ps_dec_ip->u4_num_Bytes; + else + ps_dec_op->u4_num_bytes_consumed = 0; + + ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; + ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV; + return IV_FAIL; + + } + } + +#ifdef APPLY_CONCEALMENT + { + WORD32 num_mbs; + + num_mbs = (ps_codec->i4_wd * ps_codec->i4_ht + 255) >> 8; + /* Reset MB Count at the beginning of every process call */ + ps_codec->mb_count = 0; + memset(ps_codec->mb_map, 0, ((num_mbs + 7) >> 3)); + } +#endif + + if(0 == ps_codec->i4_share_disp_buf && ps_codec->i4_header_mode == 0) + { + UWORD32 i; + if(ps_dec_ip->s_out_buffer.u4_num_bufs == 0) + { + ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; + ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS; + return IV_FAIL; + } + + for(i = 0; i < ps_dec_ip->s_out_buffer.u4_num_bufs; i++) + { + if(ps_dec_ip->s_out_buffer.pu1_bufs[i] == NULL) + { + ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; + ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL; + return IV_FAIL; + } + + if(ps_dec_ip->s_out_buffer.u4_min_out_buf_size[i] == 0) + { + ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; + ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; + return IV_FAIL; + } + } + } + + ps_codec->ps_out_buffer = &ps_dec_ip->s_out_buffer; + ps_codec->u4_ts = ps_dec_ip->u4_ts; + if(ps_codec->i4_flush_mode) + { + + ps_dec_op->u4_pic_wd = ps_codec->i4_disp_wd; + ps_dec_op->u4_pic_ht = ps_codec->i4_disp_ht; + + ps_dec_op->u4_new_seq = 0; + + ps_codec->ps_disp_buf = (pic_buf_t *)ihevc_disp_mgr_get( + (disp_mgr_t *)ps_codec->pv_disp_buf_mgr, &ps_codec->i4_disp_buf_id); + /* In case of non-shared mode, then convert/copy the frame to output buffer */ + /* Only if the codec is in non-shared mode or in shared mode but needs 420P output */ + if((ps_codec->ps_disp_buf) + && ((0 == ps_codec->i4_share_disp_buf) + || (IV_YUV_420P + == ps_codec->e_chroma_fmt))) + { + + process_ctxt_t *ps_proc = &ps_codec->as_process[prev_proc_idx]; + if(0 == ps_proc->i4_init_done) + { + ihevcd_init_proc_ctxt(ps_proc, 0); + } + + /* Output buffer check */ + ret = ihevcd_check_out_buf_size(ps_codec); + RETURN_IF((ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS), ret); + + /* Set remaining number of rows to be processed */ + ret = ihevcd_fmt_conv(ps_codec, &ps_codec->as_process[prev_proc_idx], + ps_dec_ip->s_out_buffer.pu1_bufs[0], + ps_dec_ip->s_out_buffer.pu1_bufs[1], + ps_dec_ip->s_out_buffer.pu1_bufs[2], 0, + ps_codec->i4_disp_ht); + + ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_pic_buf_mgr, + ps_codec->i4_disp_buf_id, BUF_MGR_DISP); + } + + ihevcd_fill_outargs(ps_codec, ps_dec_ip, ps_dec_op); + + if(1 == ps_dec_op->u4_output_present) + { + WORD32 xpos = ps_codec->i4_disp_wd - 32 - LOGO_WD; + WORD32 ypos = ps_codec->i4_disp_ht - 32 - LOGO_HT; + + if(ypos < 0) + ypos = 0; + + if(xpos < 0) + xpos = 0; + + INSERT_LOGO(ps_dec_ip->s_out_buffer.pu1_bufs[0], + ps_dec_ip->s_out_buffer.pu1_bufs[1], + ps_dec_ip->s_out_buffer.pu1_bufs[2], ps_codec->i4_disp_strd, + xpos, + ypos, + ps_codec->e_chroma_fmt, + ps_codec->i4_disp_wd, + ps_codec->i4_disp_ht); + } + + + if(NULL == ps_codec->ps_disp_buf) + { + /* If in flush mode and there are no more buffers to flush, + * check for the reset flag and reset the decoder */ + if(ps_codec->i4_reset_flag) + { + ihevcd_init(ps_codec); + } + return (IV_FAIL); + } + + return (IV_SUCCESS); + + } + /* In case of shared mode, check if there is a free buffer for reconstruction */ + if((0 == ps_codec->i4_header_mode) && (1 == ps_codec->i4_share_disp_buf)) + { + WORD32 buf_status; + buf_status = 1; + if(ps_codec->pv_pic_buf_mgr) + buf_status = ihevc_buf_mgr_check_free((buf_mgr_t *)ps_codec->pv_pic_buf_mgr); + + /* If there is no free buffer, then return with an error code */ + if(0 == buf_status) + { + ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; + ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); + return IV_FAIL; + } + } + ps_codec->i4_bytes_remaining = ps_dec_ip->u4_num_Bytes; + ps_codec->pu1_inp_bitsbuf = (UWORD8 *)ps_dec_ip->pv_stream_buffer; + ps_codec->s_parse.i4_end_of_frame = 0; + + ps_codec->i4_pic_present = 0; + ps_codec->i4_slice_error = 0; + ps_codec->ps_disp_buf = NULL; + + if(ps_codec->i4_num_cores > 1) + { + ithread_set_affinity(0); + } + while(MIN_START_CODE_LEN < ps_codec->i4_bytes_remaining) + { + WORD32 nal_len; + WORD32 nal_ofst; + WORD32 bits_len; + + if(ps_codec->i4_slice_error) + { + slice_header_t *ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)); + WORD32 next_slice_addr = ps_slice_hdr_next->i2_ctb_x + + ps_slice_hdr_next->i2_ctb_y * ps_codec->s_parse.ps_sps->i2_pic_wd_in_ctb; + if(ps_codec->s_parse.i4_next_ctb_indx == next_slice_addr) + ps_codec->i4_slice_error = 0; + } + + if(ps_codec->pu1_bitsbuf_dynamic) + { + ps_codec->pu1_bitsbuf = ps_codec->pu1_bitsbuf_dynamic; + ps_codec->u4_bitsbuf_size = ps_codec->u4_bitsbuf_size_dynamic; + } + else + { + ps_codec->pu1_bitsbuf = ps_codec->pu1_bitsbuf_static; + ps_codec->u4_bitsbuf_size = ps_codec->u4_bitsbuf_size_static; + } + + nal_ofst = ihevcd_nal_search_start_code(ps_codec->pu1_inp_bitsbuf, + ps_codec->i4_bytes_remaining); + + ps_codec->i4_nal_ofst = nal_ofst; + { + WORD32 bytes_remaining = ps_codec->i4_bytes_remaining - nal_ofst; + + bytes_remaining = MIN((UWORD32)bytes_remaining, ps_codec->u4_bitsbuf_size); + ihevcd_nal_remv_emuln_bytes(ps_codec->pu1_inp_bitsbuf + nal_ofst, + ps_codec->pu1_bitsbuf, + bytes_remaining, + &nal_len, &bits_len); + + /* Decoder may read upto 8 extra bytes at the end of frame */ + /* These are not used, but still set them to zero to avoid uninitialized reads */ + if(bits_len < (WORD32)(ps_codec->u4_bitsbuf_size - 8)) + { + memset(ps_codec->pu1_bitsbuf + bits_len, 0, 2 * sizeof(UWORD32)); + } + } + /* This may be used to update the offsets for tiles and entropy sync row offsets */ + ps_codec->i4_num_emln_bytes = nal_len - bits_len; + ps_codec->i4_nal_len = nal_len; + + ihevcd_bits_init(&ps_codec->s_parse.s_bitstrm, ps_codec->pu1_bitsbuf, + bits_len); + + ret = ihevcd_nal_unit(ps_codec); + + /* If the frame is incomplete and + * the bytes remaining is zero or a header is received, + * complete the frame treating it to be in error */ + if(ps_codec->i4_pic_present && + (ps_codec->s_parse.i4_next_ctb_indx != ps_codec->s_parse.ps_sps->i4_pic_size_in_ctb)) + { + if((ps_codec->i4_bytes_remaining - (nal_len + nal_ofst) <= MIN_START_CODE_LEN) || + (ps_codec->i4_header_in_slice_mode)) + { + slice_header_t *ps_slice_hdr_next; + + ps_codec->s_parse.i4_cur_slice_idx--; + if(ps_codec->s_parse.i4_cur_slice_idx < 0) + ps_codec->s_parse.i4_cur_slice_idx = 0; + + ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1)); + ps_slice_hdr_next->i2_ctb_x = 0; + ps_slice_hdr_next->i2_ctb_y = ps_codec->s_parse.ps_sps->i2_pic_ht_in_ctb; + ps_codec->i4_slice_error = 1; + continue; + } + } + + + if(IHEVCD_IGNORE_SLICE == ret) + { + ps_codec->s_parse.i4_cur_slice_idx = MAX(0, (ps_codec->s_parse.i4_cur_slice_idx - 1)); + ps_codec->pu1_inp_bitsbuf += (nal_ofst + nal_len); + ps_codec->i4_bytes_remaining -= (nal_ofst + nal_len); + + continue; + } + + if((IVD_RES_CHANGED == ret) || + (IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED == ret)) + { + break; + } + + /* Update bytes remaining and bytes consumed and input bitstream pointer */ + /* Do not consume the NAL in the following cases */ + /* Slice header reached during header decode mode */ + /* TODO: Next picture's slice reached */ + if(ret != IHEVCD_SLICE_IN_HEADER_MODE) + { + if((0 == ps_codec->i4_slice_error) || + (ps_codec->i4_bytes_remaining - (nal_len + nal_ofst) <= MIN_START_CODE_LEN)) + { + ps_codec->pu1_inp_bitsbuf += (nal_ofst + nal_len); + ps_codec->i4_bytes_remaining -= (nal_ofst + nal_len); + } + if(ret != IHEVCD_SUCCESS) + break; + + if(ps_codec->s_parse.i4_end_of_frame) + break; + } + else + { + ret = IHEVCD_SUCCESS; + break; + } + + /* Allocate dynamic bitstream buffer once SPS is decoded */ + if((ps_codec->u4_allocate_dynamic_done == 0) && ps_codec->i4_sps_done) + { + WORD32 ret; + ret = ihevcd_allocate_dynamic_bufs(ps_codec); + if(ret != IV_SUCCESS) + { + /* Free any dynamic buffers that are allocated */ + ihevcd_free_dynamic_bufs(ps_codec); + ps_codec->i4_error_code = IVD_MEM_ALLOC_FAILED; + ps_dec_op->u4_error_code |= 1 << IVD_FATALERROR; + ps_dec_op->u4_error_code |= IVD_MEM_ALLOC_FAILED; + + return IV_FAIL; + } + } + + BREAK_AFTER_SLICE_NAL(); + } + + if((ps_codec->u4_pic_cnt == 0) && (ret != IHEVCD_SUCCESS)) + { + ps_codec->i4_error_code = ret; + + ihevcd_fill_outargs(ps_codec, ps_dec_ip, ps_dec_op); + return IV_FAIL; + } + + if(1 == ps_codec->i4_pic_present) + { + WORD32 i; + sps_t *ps_sps = ps_codec->s_parse.ps_sps; + ps_codec->i4_first_pic_done = 1; + + /*TODO temporary fix: end_of_frame is checked before adding format conversion to job queue */ + if(ps_codec->i4_num_cores > 1 && ps_codec->s_parse.i4_end_of_frame) + { + + /* Add job queue for format conversion / frame copy for each ctb row */ + /* Only if the codec is in non-shared mode or in shared mode but needs 420P output */ + process_ctxt_t *ps_proc; + + /* i4_num_cores - 1 contexts are currently being used by other threads */ + ps_proc = &ps_codec->as_process[ps_codec->i4_num_cores - 1]; + + if((ps_codec->ps_disp_buf) && + ((0 == ps_codec->i4_share_disp_buf) || (IV_YUV_420P == ps_codec->e_chroma_fmt))) + { + /* If format conversion jobs were not issued in pic_init() add them here */ + if((0 == ps_codec->u4_enable_fmt_conv_ahead) || + (ps_codec->i4_disp_buf_id == ps_proc->i4_cur_pic_buf_id)) + for(i = 0; i < ps_sps->i2_pic_ht_in_ctb; i++) + { + proc_job_t s_job; + IHEVCD_ERROR_T ret; + s_job.i4_cmd = CMD_FMTCONV; + s_job.i2_ctb_cnt = 0; + s_job.i2_ctb_x = 0; + s_job.i2_ctb_y = i; + s_job.i2_slice_idx = 0; + s_job.i4_tu_coeff_data_ofst = 0; + ret = ihevcd_jobq_queue((jobq_t *)ps_codec->s_parse.pv_proc_jobq, + &s_job, sizeof(proc_job_t), 1); + if(ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS) + return (WORD32)ret; + } + } + /* Reached end of frame : Signal terminate */ + /* The terminate flag is checked only after all the jobs are dequeued */ + ret = ihevcd_jobq_terminate((jobq_t *)ps_codec->s_parse.pv_proc_jobq); + + while(1) + { + IHEVCD_ERROR_T ret; + proc_job_t s_job; + process_ctxt_t *ps_proc; + + /* i4_num_cores - 1 contexts are currently being used by other threads */ + ps_proc = &ps_codec->as_process[ps_codec->i4_num_cores - 1]; + + ret = ihevcd_jobq_dequeue((jobq_t *)ps_proc->pv_proc_jobq, &s_job, + sizeof(proc_job_t), 1); + if((IHEVCD_ERROR_T)IHEVCD_SUCCESS != ret) + break; + + ps_proc->i4_ctb_cnt = s_job.i2_ctb_cnt; + ps_proc->i4_ctb_x = s_job.i2_ctb_x; + ps_proc->i4_ctb_y = s_job.i2_ctb_y; + ps_proc->i4_cur_slice_idx = s_job.i2_slice_idx; + + if(CMD_PROCESS == s_job.i4_cmd) + { + ihevcd_init_proc_ctxt(ps_proc, s_job.i4_tu_coeff_data_ofst); + + ihevcd_process(ps_proc); + } + else if(CMD_FMTCONV == s_job.i4_cmd) + { + sps_t *ps_sps = ps_codec->s_parse.ps_sps; + WORD32 num_rows = 1 << ps_sps->i1_log2_ctb_size; + if(0 == ps_proc->i4_init_done) + { + ihevcd_init_proc_ctxt(ps_proc, 0); + } + + num_rows = MIN(num_rows, (ps_codec->i4_disp_ht - (s_job.i2_ctb_y << ps_sps->i1_log2_ctb_size))); + if(num_rows < 0) + num_rows = 0; + + ihevcd_fmt_conv(ps_codec, ps_proc, + ps_dec_ip->s_out_buffer.pu1_bufs[0], + ps_dec_ip->s_out_buffer.pu1_bufs[1], + ps_dec_ip->s_out_buffer.pu1_bufs[2], + s_job.i2_ctb_y << ps_sps->i1_log2_ctb_size, + num_rows); + } + } + } + /* In case of non-shared mode and while running in single core mode, then convert/copy the frame to output buffer */ + /* Only if the codec is in non-shared mode or in shared mode but needs 420P output */ + else if((ps_codec->ps_disp_buf) && ((0 == ps_codec->i4_share_disp_buf) || + (IV_YUV_420P == ps_codec->e_chroma_fmt)) && + (ps_codec->s_parse.i4_end_of_frame)) + { + process_ctxt_t *ps_proc = &ps_codec->as_process[proc_idx]; + /* Set remaining number of rows to be processed */ + ps_codec->s_fmt_conv.i4_num_rows = ps_codec->i4_disp_ht + - ps_codec->s_fmt_conv.i4_cur_row; + if(0 == ps_proc->i4_init_done) + { + ihevcd_init_proc_ctxt(ps_proc, 0); + } + + if(ps_codec->s_fmt_conv.i4_num_rows < 0) + ps_codec->s_fmt_conv.i4_num_rows = 0; + + ret = ihevcd_fmt_conv(ps_codec, ps_proc, + ps_dec_ip->s_out_buffer.pu1_bufs[0], + ps_dec_ip->s_out_buffer.pu1_bufs[1], + ps_dec_ip->s_out_buffer.pu1_bufs[2], + ps_codec->s_fmt_conv.i4_cur_row, + ps_codec->s_fmt_conv.i4_num_rows); + ps_codec->s_fmt_conv.i4_cur_row += ps_codec->s_fmt_conv.i4_num_rows; + + } + + + DEBUG_DUMP_MV_MAP(ps_codec); + + /* Mark MV Buf as needed for reference */ + ihevc_buf_mgr_set_status((buf_mgr_t *)ps_codec->pv_mv_buf_mgr, + ps_codec->as_process[proc_idx].i4_cur_mv_bank_buf_id, + BUF_MGR_REF); + + /* Mark pic buf as needed for reference */ + ihevc_buf_mgr_set_status((buf_mgr_t *)ps_codec->pv_pic_buf_mgr, + ps_codec->as_process[proc_idx].i4_cur_pic_buf_id, + BUF_MGR_REF); + + /* Mark pic buf as needed for display */ + ihevc_buf_mgr_set_status((buf_mgr_t *)ps_codec->pv_pic_buf_mgr, + ps_codec->as_process[proc_idx].i4_cur_pic_buf_id, + BUF_MGR_DISP); + + /* Insert the current picture as short term reference */ + ihevc_dpb_mgr_insert_ref((dpb_mgr_t *)ps_codec->pv_dpb_mgr, + ps_codec->as_process[proc_idx].ps_cur_pic, + ps_codec->as_process[proc_idx].i4_cur_pic_buf_id); + + /* If a frame was displayed (in non-shared mode), then release it from display manager */ + if((0 == ps_codec->i4_share_disp_buf) && (ps_codec->ps_disp_buf)) + ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_pic_buf_mgr, + ps_codec->i4_disp_buf_id, BUF_MGR_DISP); + + /* Wait for threads */ + for(i = 0; i < (ps_codec->i4_num_cores - 1); i++) + { + if(ps_codec->ai4_process_thread_created[i]) + { + ithread_join(ps_codec->apv_process_thread_handle[i], NULL); + ps_codec->ai4_process_thread_created[i] = 0; + } + } + + DEBUG_VALIDATE_PADDED_REGION(&ps_codec->as_process[proc_idx]); + if(ps_codec->u4_pic_cnt > 0) + { + DEBUG_DUMP_PIC_PU(ps_codec); + } + DEBUG_DUMP_PIC_BUFFERS(ps_codec); + + /* Increment the number of pictures decoded */ + ps_codec->u4_pic_cnt++; + } + ihevcd_fill_outargs(ps_codec, ps_dec_ip, ps_dec_op); + + if(1 == ps_dec_op->u4_output_present) + { + WORD32 xpos = ps_codec->i4_disp_wd - 32 - LOGO_WD; + WORD32 ypos = ps_codec->i4_disp_ht - 32 - LOGO_HT; + + if(ypos < 0) + ypos = 0; + + if(xpos < 0) + xpos = 0; + + INSERT_LOGO(ps_dec_ip->s_out_buffer.pu1_bufs[0], + ps_dec_ip->s_out_buffer.pu1_bufs[1], + ps_dec_ip->s_out_buffer.pu1_bufs[2], ps_codec->i4_disp_strd, + xpos, + ypos, + ps_codec->e_chroma_fmt, + ps_codec->i4_disp_wd, + ps_codec->i4_disp_ht); + } + + + return ret; +} +",1,"WORD32 ihevcd_decode(iv_obj_t *ps_codec_obj, void *pv_api_ip, void *pv_api_op) +{ + WORD32 ret = IV_SUCCESS; + codec_t *ps_codec = (codec_t *)(ps_codec_obj->pv_codec_handle); + ivd_video_decode_ip_t *ps_dec_ip; + ivd_video_decode_op_t *ps_dec_op; + + WORD32 proc_idx = 0; + WORD32 prev_proc_idx = 0; + + /* Initialize error code */ + ps_codec->i4_error_code = 0; + + ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip; + ps_dec_op = (ivd_video_decode_op_t *)pv_api_op; + + { + UWORD32 u4_size = ps_dec_op->u4_size; + memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t)); + ps_dec_op->u4_size = u4_size; //Restore size field + } + if(ps_codec->i4_init_done != 1) + { + ps_dec_op->u4_error_code |= 1 << IVD_FATALERROR; + ps_dec_op->u4_error_code |= IHEVCD_INIT_NOT_DONE; + return IV_FAIL; + } + + if(ps_codec->u4_pic_cnt >= NUM_FRAMES_LIMIT) + { + ps_dec_op->u4_error_code |= 1 << IVD_FATALERROR; + ps_dec_op->u4_error_code |= IHEVCD_NUM_FRAMES_LIMIT_REACHED; + return IV_FAIL; + } + + /* If reset flag is set, flush the existing buffers */ + if(ps_codec->i4_reset_flag) + { + ps_codec->i4_flush_mode = 1; + } + + /*Data memory barries instruction,so that bitstream write by the application is complete*/ + /* In case the decoder is not in flush mode check for input buffer validity */ + if(0 == ps_codec->i4_flush_mode) + { + if(ps_dec_ip->pv_stream_buffer == NULL) + { + ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; + ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL; + return IV_FAIL; + } + if(ps_dec_ip->u4_num_Bytes <= MIN_START_CODE_LEN) + { + if((WORD32)ps_dec_ip->u4_num_Bytes > 0) + ps_dec_op->u4_num_bytes_consumed = ps_dec_ip->u4_num_Bytes; + else + ps_dec_op->u4_num_bytes_consumed = 0; + + ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; + ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV; + return IV_FAIL; + + } + } + +#ifdef APPLY_CONCEALMENT + { + WORD32 num_mbs; + + num_mbs = (ps_codec->i4_wd * ps_codec->i4_ht + 255) >> 8; + /* Reset MB Count at the beginning of every process call */ + ps_codec->mb_count = 0; + memset(ps_codec->mb_map, 0, ((num_mbs + 7) >> 3)); + } +#endif + + if(0 == ps_codec->i4_share_disp_buf && ps_codec->i4_header_mode == 0) + { + UWORD32 i; + if(ps_dec_ip->s_out_buffer.u4_num_bufs == 0) + { + ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; + ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS; + return IV_FAIL; + } + + for(i = 0; i < ps_dec_ip->s_out_buffer.u4_num_bufs; i++) + { + if(ps_dec_ip->s_out_buffer.pu1_bufs[i] == NULL) + { + ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; + ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL; + return IV_FAIL; + } + + if(ps_dec_ip->s_out_buffer.u4_min_out_buf_size[i] == 0) + { + ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; + ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUF_SIZE; + return IV_FAIL; + } + } + } + + ps_codec->ps_out_buffer = &ps_dec_ip->s_out_buffer; + ps_codec->u4_ts = ps_dec_ip->u4_ts; + if(ps_codec->i4_flush_mode) + { + + ps_dec_op->u4_pic_wd = ps_codec->i4_disp_wd; + ps_dec_op->u4_pic_ht = ps_codec->i4_disp_ht; + + ps_dec_op->u4_new_seq = 0; + + ps_codec->ps_disp_buf = (pic_buf_t *)ihevc_disp_mgr_get( + (disp_mgr_t *)ps_codec->pv_disp_buf_mgr, &ps_codec->i4_disp_buf_id); + /* In case of non-shared mode, then convert/copy the frame to output buffer */ + /* Only if the codec is in non-shared mode or in shared mode but needs 420P output */ + if((ps_codec->ps_disp_buf) + && ((0 == ps_codec->i4_share_disp_buf) + || (IV_YUV_420P + == ps_codec->e_chroma_fmt))) + { + + process_ctxt_t *ps_proc = &ps_codec->as_process[prev_proc_idx]; + if(0 == ps_proc->i4_init_done) + { + ihevcd_init_proc_ctxt(ps_proc, 0); + } + + /* Output buffer check */ + ret = ihevcd_check_out_buf_size(ps_codec); + RETURN_IF((ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS), ret); + + /* Set remaining number of rows to be processed */ + ret = ihevcd_fmt_conv(ps_codec, &ps_codec->as_process[prev_proc_idx], + ps_dec_ip->s_out_buffer.pu1_bufs[0], + ps_dec_ip->s_out_buffer.pu1_bufs[1], + ps_dec_ip->s_out_buffer.pu1_bufs[2], 0, + ps_codec->i4_disp_ht); + + ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_pic_buf_mgr, + ps_codec->i4_disp_buf_id, BUF_MGR_DISP); + } + + ihevcd_fill_outargs(ps_codec, ps_dec_ip, ps_dec_op); + + if(1 == ps_dec_op->u4_output_present) + { + WORD32 xpos = ps_codec->i4_disp_wd - 32 - LOGO_WD; + WORD32 ypos = ps_codec->i4_disp_ht - 32 - LOGO_HT; + + if(ypos < 0) + ypos = 0; + + if(xpos < 0) + xpos = 0; + + INSERT_LOGO(ps_dec_ip->s_out_buffer.pu1_bufs[0], + ps_dec_ip->s_out_buffer.pu1_bufs[1], + ps_dec_ip->s_out_buffer.pu1_bufs[2], ps_codec->i4_disp_strd, + xpos, + ypos, + ps_codec->e_chroma_fmt, + ps_codec->i4_disp_wd, + ps_codec->i4_disp_ht); + } + + + if(NULL == ps_codec->ps_disp_buf) + { + /* If in flush mode and there are no more buffers to flush, + * check for the reset flag and reset the decoder */ + if(ps_codec->i4_reset_flag) + { + ihevcd_init(ps_codec); + } + return (IV_FAIL); + } + + return (IV_SUCCESS); + + } + /* In case of shared mode, check if there is a free buffer for reconstruction */ + if((0 == ps_codec->i4_header_mode) && (1 == ps_codec->i4_share_disp_buf)) + { + WORD32 buf_status; + buf_status = 1; + if(ps_codec->pv_pic_buf_mgr) + buf_status = ihevc_buf_mgr_check_free((buf_mgr_t *)ps_codec->pv_pic_buf_mgr); + + /* If there is no free buffer, then return with an error code */ + if(0 == buf_status) + { + ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; + ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); + return IV_FAIL; + } + } + ps_codec->i4_bytes_remaining = ps_dec_ip->u4_num_Bytes; + ps_codec->pu1_inp_bitsbuf = (UWORD8 *)ps_dec_ip->pv_stream_buffer; + ps_codec->s_parse.i4_end_of_frame = 0; + + ps_codec->i4_pic_present = 0; + ps_codec->i4_slice_error = 0; + ps_codec->ps_disp_buf = NULL; + + if(ps_codec->i4_num_cores > 1) + { + ithread_set_affinity(0); + } + while(MIN_START_CODE_LEN < ps_codec->i4_bytes_remaining) + { + WORD32 nal_len; + WORD32 nal_ofst; + WORD32 bits_len; + + if(ps_codec->i4_slice_error) + { + slice_header_t *ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)); + WORD32 next_slice_addr = ps_slice_hdr_next->i2_ctb_x + + ps_slice_hdr_next->i2_ctb_y * ps_codec->s_parse.ps_sps->i2_pic_wd_in_ctb; + if(ps_codec->s_parse.i4_next_ctb_indx == next_slice_addr) + ps_codec->i4_slice_error = 0; + } + + if(ps_codec->pu1_bitsbuf_dynamic) + { + ps_codec->pu1_bitsbuf = ps_codec->pu1_bitsbuf_dynamic; + ps_codec->u4_bitsbuf_size = ps_codec->u4_bitsbuf_size_dynamic; + } + else + { + ps_codec->pu1_bitsbuf = ps_codec->pu1_bitsbuf_static; + ps_codec->u4_bitsbuf_size = ps_codec->u4_bitsbuf_size_static; + } + + nal_ofst = ihevcd_nal_search_start_code(ps_codec->pu1_inp_bitsbuf, + ps_codec->i4_bytes_remaining); + + ps_codec->i4_nal_ofst = nal_ofst; + { + WORD32 bytes_remaining = ps_codec->i4_bytes_remaining - nal_ofst; + + bytes_remaining = MIN((UWORD32)bytes_remaining, ps_codec->u4_bitsbuf_size); + ihevcd_nal_remv_emuln_bytes(ps_codec->pu1_inp_bitsbuf + nal_ofst, + ps_codec->pu1_bitsbuf, + bytes_remaining, + &nal_len, &bits_len); + + /* Decoder may read upto 8 extra bytes at the end of frame */ + /* These are not used, but still set them to zero to avoid uninitialized reads */ + if(bits_len < (WORD32)(ps_codec->u4_bitsbuf_size - 8)) + { + memset(ps_codec->pu1_bitsbuf + bits_len, 0, 2 * sizeof(UWORD32)); + } + } + /* This may be used to update the offsets for tiles and entropy sync row offsets */ + ps_codec->i4_num_emln_bytes = nal_len - bits_len; + ps_codec->i4_nal_len = nal_len; + + ihevcd_bits_init(&ps_codec->s_parse.s_bitstrm, ps_codec->pu1_bitsbuf, + bits_len); + + ret = ihevcd_nal_unit(ps_codec); + + /* If the frame is incomplete and + * the bytes remaining is zero or a header is received, + * complete the frame treating it to be in error */ + if(ps_codec->i4_pic_present && + (ps_codec->s_parse.i4_next_ctb_indx != ps_codec->s_parse.ps_sps->i4_pic_size_in_ctb)) + { + if((ps_codec->i4_bytes_remaining - (nal_len + nal_ofst) <= MIN_START_CODE_LEN) || + (ps_codec->i4_header_in_slice_mode)) + { + slice_header_t *ps_slice_hdr_next; + + ps_codec->s_parse.i4_cur_slice_idx--; + if(ps_codec->s_parse.i4_cur_slice_idx < 0) + ps_codec->s_parse.i4_cur_slice_idx = 0; + + ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1)); + ps_slice_hdr_next->i2_ctb_x = 0; + ps_slice_hdr_next->i2_ctb_y = ps_codec->s_parse.ps_sps->i2_pic_ht_in_ctb; + ps_codec->i4_slice_error = 1; + continue; + } + } + + + if(IHEVCD_IGNORE_SLICE == ret) + { + ps_codec->pu1_inp_bitsbuf += (nal_ofst + nal_len); + ps_codec->i4_bytes_remaining -= (nal_ofst + nal_len); + + continue; + } + + if((IVD_RES_CHANGED == ret) || + (IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED == ret)) + { + break; + } + + /* Update bytes remaining and bytes consumed and input bitstream pointer */ + /* Do not consume the NAL in the following cases */ + /* Slice header reached during header decode mode */ + /* TODO: Next picture's slice reached */ + if(ret != IHEVCD_SLICE_IN_HEADER_MODE) + { + if((0 == ps_codec->i4_slice_error) || + (ps_codec->i4_bytes_remaining - (nal_len + nal_ofst) <= MIN_START_CODE_LEN)) + { + ps_codec->pu1_inp_bitsbuf += (nal_ofst + nal_len); + ps_codec->i4_bytes_remaining -= (nal_ofst + nal_len); + } + if(ret != IHEVCD_SUCCESS) + break; + + if(ps_codec->s_parse.i4_end_of_frame) + break; + } + else + { + ret = IHEVCD_SUCCESS; + break; + } + + /* Allocate dynamic bitstream buffer once SPS is decoded */ + if((ps_codec->u4_allocate_dynamic_done == 0) && ps_codec->i4_sps_done) + { + WORD32 ret; + ret = ihevcd_allocate_dynamic_bufs(ps_codec); + if(ret != IV_SUCCESS) + { + /* Free any dynamic buffers that are allocated */ + ihevcd_free_dynamic_bufs(ps_codec); + ps_codec->i4_error_code = IVD_MEM_ALLOC_FAILED; + ps_dec_op->u4_error_code |= 1 << IVD_FATALERROR; + ps_dec_op->u4_error_code |= IVD_MEM_ALLOC_FAILED; + + return IV_FAIL; + } + } + + BREAK_AFTER_SLICE_NAL(); + } + + if((ps_codec->u4_pic_cnt == 0) && (ret != IHEVCD_SUCCESS)) + { + ps_codec->i4_error_code = ret; + + ihevcd_fill_outargs(ps_codec, ps_dec_ip, ps_dec_op); + return IV_FAIL; + } + + if(1 == ps_codec->i4_pic_present) + { + WORD32 i; + sps_t *ps_sps = ps_codec->s_parse.ps_sps; + ps_codec->i4_first_pic_done = 1; + + /*TODO temporary fix: end_of_frame is checked before adding format conversion to job queue */ + if(ps_codec->i4_num_cores > 1 && ps_codec->s_parse.i4_end_of_frame) + { + + /* Add job queue for format conversion / frame copy for each ctb row */ + /* Only if the codec is in non-shared mode or in shared mode but needs 420P output */ + process_ctxt_t *ps_proc; + + /* i4_num_cores - 1 contexts are currently being used by other threads */ + ps_proc = &ps_codec->as_process[ps_codec->i4_num_cores - 1]; + + if((ps_codec->ps_disp_buf) && + ((0 == ps_codec->i4_share_disp_buf) || (IV_YUV_420P == ps_codec->e_chroma_fmt))) + { + /* If format conversion jobs were not issued in pic_init() add them here */ + if((0 == ps_codec->u4_enable_fmt_conv_ahead) || + (ps_codec->i4_disp_buf_id == ps_proc->i4_cur_pic_buf_id)) + for(i = 0; i < ps_sps->i2_pic_ht_in_ctb; i++) + { + proc_job_t s_job; + IHEVCD_ERROR_T ret; + s_job.i4_cmd = CMD_FMTCONV; + s_job.i2_ctb_cnt = 0; + s_job.i2_ctb_x = 0; + s_job.i2_ctb_y = i; + s_job.i2_slice_idx = 0; + s_job.i4_tu_coeff_data_ofst = 0; + ret = ihevcd_jobq_queue((jobq_t *)ps_codec->s_parse.pv_proc_jobq, + &s_job, sizeof(proc_job_t), 1); + if(ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS) + return (WORD32)ret; + } + } + /* Reached end of frame : Signal terminate */ + /* The terminate flag is checked only after all the jobs are dequeued */ + ret = ihevcd_jobq_terminate((jobq_t *)ps_codec->s_parse.pv_proc_jobq); + + while(1) + { + IHEVCD_ERROR_T ret; + proc_job_t s_job; + process_ctxt_t *ps_proc; + + /* i4_num_cores - 1 contexts are currently being used by other threads */ + ps_proc = &ps_codec->as_process[ps_codec->i4_num_cores - 1]; + + ret = ihevcd_jobq_dequeue((jobq_t *)ps_proc->pv_proc_jobq, &s_job, + sizeof(proc_job_t), 1); + if((IHEVCD_ERROR_T)IHEVCD_SUCCESS != ret) + break; + + ps_proc->i4_ctb_cnt = s_job.i2_ctb_cnt; + ps_proc->i4_ctb_x = s_job.i2_ctb_x; + ps_proc->i4_ctb_y = s_job.i2_ctb_y; + ps_proc->i4_cur_slice_idx = s_job.i2_slice_idx; + + if(CMD_PROCESS == s_job.i4_cmd) + { + ihevcd_init_proc_ctxt(ps_proc, s_job.i4_tu_coeff_data_ofst); + + ihevcd_process(ps_proc); + } + else if(CMD_FMTCONV == s_job.i4_cmd) + { + sps_t *ps_sps = ps_codec->s_parse.ps_sps; + WORD32 num_rows = 1 << ps_sps->i1_log2_ctb_size; + if(0 == ps_proc->i4_init_done) + { + ihevcd_init_proc_ctxt(ps_proc, 0); + } + + num_rows = MIN(num_rows, (ps_codec->i4_disp_ht - (s_job.i2_ctb_y << ps_sps->i1_log2_ctb_size))); + if(num_rows < 0) + num_rows = 0; + + ihevcd_fmt_conv(ps_codec, ps_proc, + ps_dec_ip->s_out_buffer.pu1_bufs[0], + ps_dec_ip->s_out_buffer.pu1_bufs[1], + ps_dec_ip->s_out_buffer.pu1_bufs[2], + s_job.i2_ctb_y << ps_sps->i1_log2_ctb_size, + num_rows); + } + } + } + /* In case of non-shared mode and while running in single core mode, then convert/copy the frame to output buffer */ + /* Only if the codec is in non-shared mode or in shared mode but needs 420P output */ + else if((ps_codec->ps_disp_buf) && ((0 == ps_codec->i4_share_disp_buf) || + (IV_YUV_420P == ps_codec->e_chroma_fmt)) && + (ps_codec->s_parse.i4_end_of_frame)) + { + process_ctxt_t *ps_proc = &ps_codec->as_process[proc_idx]; + /* Set remaining number of rows to be processed */ + ps_codec->s_fmt_conv.i4_num_rows = ps_codec->i4_disp_ht + - ps_codec->s_fmt_conv.i4_cur_row; + if(0 == ps_proc->i4_init_done) + { + ihevcd_init_proc_ctxt(ps_proc, 0); + } + + if(ps_codec->s_fmt_conv.i4_num_rows < 0) + ps_codec->s_fmt_conv.i4_num_rows = 0; + + ret = ihevcd_fmt_conv(ps_codec, ps_proc, + ps_dec_ip->s_out_buffer.pu1_bufs[0], + ps_dec_ip->s_out_buffer.pu1_bufs[1], + ps_dec_ip->s_out_buffer.pu1_bufs[2], + ps_codec->s_fmt_conv.i4_cur_row, + ps_codec->s_fmt_conv.i4_num_rows); + ps_codec->s_fmt_conv.i4_cur_row += ps_codec->s_fmt_conv.i4_num_rows; + + } + + + DEBUG_DUMP_MV_MAP(ps_codec); + + /* Mark MV Buf as needed for reference */ + ihevc_buf_mgr_set_status((buf_mgr_t *)ps_codec->pv_mv_buf_mgr, + ps_codec->as_process[proc_idx].i4_cur_mv_bank_buf_id, + BUF_MGR_REF); + + /* Mark pic buf as needed for reference */ + ihevc_buf_mgr_set_status((buf_mgr_t *)ps_codec->pv_pic_buf_mgr, + ps_codec->as_process[proc_idx].i4_cur_pic_buf_id, + BUF_MGR_REF); + + /* Mark pic buf as needed for display */ + ihevc_buf_mgr_set_status((buf_mgr_t *)ps_codec->pv_pic_buf_mgr, + ps_codec->as_process[proc_idx].i4_cur_pic_buf_id, + BUF_MGR_DISP); + + /* Insert the current picture as short term reference */ + ihevc_dpb_mgr_insert_ref((dpb_mgr_t *)ps_codec->pv_dpb_mgr, + ps_codec->as_process[proc_idx].ps_cur_pic, + ps_codec->as_process[proc_idx].i4_cur_pic_buf_id); + + /* If a frame was displayed (in non-shared mode), then release it from display manager */ + if((0 == ps_codec->i4_share_disp_buf) && (ps_codec->ps_disp_buf)) + ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_pic_buf_mgr, + ps_codec->i4_disp_buf_id, BUF_MGR_DISP); + + /* Wait for threads */ + for(i = 0; i < (ps_codec->i4_num_cores - 1); i++) + { + if(ps_codec->ai4_process_thread_created[i]) + { + ithread_join(ps_codec->apv_process_thread_handle[i], NULL); + ps_codec->ai4_process_thread_created[i] = 0; + } + } + + DEBUG_VALIDATE_PADDED_REGION(&ps_codec->as_process[proc_idx]); + if(ps_codec->u4_pic_cnt > 0) + { + DEBUG_DUMP_PIC_PU(ps_codec); + } + DEBUG_DUMP_PIC_BUFFERS(ps_codec); + + /* Increment the number of pictures decoded */ + ps_codec->u4_pic_cnt++; + } + ihevcd_fill_outargs(ps_codec, ps_dec_ip, ps_dec_op); + + if(1 == ps_dec_op->u4_output_present) + { + WORD32 xpos = ps_codec->i4_disp_wd - 32 - LOGO_WD; + WORD32 ypos = ps_codec->i4_disp_ht - 32 - LOGO_HT; + + if(ypos < 0) + ypos = 0; + + if(xpos < 0) + xpos = 0; + + INSERT_LOGO(ps_dec_ip->s_out_buffer.pu1_bufs[0], + ps_dec_ip->s_out_buffer.pu1_bufs[1], + ps_dec_ip->s_out_buffer.pu1_bufs[2], ps_codec->i4_disp_strd, + xpos, + ypos, + ps_codec->e_chroma_fmt, + ps_codec->i4_disp_wd, + ps_codec->i4_disp_ht); + } + + + return ret; +} +","@@ -668,7 +668,6 @@ + + + if(IHEVCD_IGNORE_SLICE == ret) + { +- ps_codec->s_parse.i4_cur_slice_idx = MAX(0, (ps_codec->s_parse.i4_cur_slice_idx - 1)); + ps_codec->pu1_inp_bitsbuf += (nal_ofst + nal_len); + ps_codec->i4_bytes_remaining -= (nal_ofst + nal_len); + +",5119,5450,6144 +18199,"static int mxf_parse_structural_metadata(MXFContext *mxf) +{ + MXFPackage *material_package = NULL; + int i, j, k, ret; + + av_log(mxf->fc, AV_LOG_TRACE, ""metadata sets count %d\n"", mxf->metadata_sets_count); + /* TODO: handle multiple material packages (OP3x) */ + for (i = 0; i < mxf->packages_count; i++) { + material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage); + if (material_package) break; + } + if (!material_package) { + av_log(mxf->fc, AV_LOG_ERROR, ""no material package found\n""); + return AVERROR_INVALIDDATA; + } + + mxf_add_umid_metadata(&mxf->fc->metadata, ""material_package_umid"", material_package); + if (material_package->name && material_package->name[0]) + av_dict_set(&mxf->fc->metadata, ""material_package_name"", material_package->name, 0); + mxf_parse_package_comments(mxf, &mxf->fc->metadata, material_package); + + for (i = 0; i < material_package->tracks_count; i++) { + MXFPackage *source_package = NULL; + MXFTrack *material_track = NULL; + MXFTrack *source_track = NULL; + MXFTrack *temp_track = NULL; + MXFDescriptor *descriptor = NULL; + MXFStructuralComponent *component = NULL; + MXFTimecodeComponent *mxf_tc = NULL; + UID *essence_container_ul = NULL; + const MXFCodecUL *codec_ul = NULL; + const MXFCodecUL *container_ul = NULL; + const MXFCodecUL *pix_fmt_ul = NULL; + AVStream *st; + AVTimecode tc; + int flags; + + if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) { + av_log(mxf->fc, AV_LOG_ERROR, ""could not resolve material track strong ref\n""); + continue; + } + + if ((component = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, TimecodeComponent))) { + mxf_tc = (MXFTimecodeComponent*)component; + flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0; + if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) { + mxf_add_timecode_metadata(&mxf->fc->metadata, ""timecode"", &tc); + } + } + + if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) { + av_log(mxf->fc, AV_LOG_ERROR, ""could not resolve material track sequence strong ref\n""); + continue; + } + + for (j = 0; j < material_track->sequence->structural_components_count; j++) { + component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], TimecodeComponent); + if (!component) + continue; + + mxf_tc = (MXFTimecodeComponent*)component; + flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0; + if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) { + mxf_add_timecode_metadata(&mxf->fc->metadata, ""timecode"", &tc); + break; + } + } + + /* TODO: handle multiple source clips, only finds first valid source clip */ + if(material_track->sequence->structural_components_count > 1) + av_log(mxf->fc, AV_LOG_WARNING, ""material track %d: has %d components\n"", + material_track->track_id, material_track->sequence->structural_components_count); + + for (j = 0; j < material_track->sequence->structural_components_count; j++) { + component = mxf_resolve_sourceclip(mxf, &material_track->sequence->structural_components_refs[j]); + if (!component) + continue; + + source_package = mxf_resolve_source_package(mxf, component->source_package_ul, component->source_package_uid); + if (!source_package) { + av_log(mxf->fc, AV_LOG_TRACE, ""material track %d: no corresponding source package found\n"", material_track->track_id); + continue; + } + for (k = 0; k < source_package->tracks_count; k++) { + if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) { + av_log(mxf->fc, AV_LOG_ERROR, ""could not resolve source track strong ref\n""); + ret = AVERROR_INVALIDDATA; + goto fail_and_free; + } + if (temp_track->track_id == component->source_track_id) { + source_track = temp_track; + break; + } + } + if (!source_track) { + av_log(mxf->fc, AV_LOG_ERROR, ""material track %d: no corresponding source track found\n"", material_track->track_id); + break; + } + + for (k = 0; k < mxf->essence_container_data_count; k++) { + MXFEssenceContainerData *essence_data; + + if (!(essence_data = mxf_resolve_strong_ref(mxf, &mxf->essence_container_data_refs[k], EssenceContainerData))) { + av_log(mxf, AV_LOG_TRACE, ""could not resolve essence container data strong ref\n""); + continue; + } + if (!memcmp(component->source_package_ul, essence_data->package_ul, sizeof(UID)) && !memcmp(component->source_package_uid, essence_data->package_uid, sizeof(UID))) { + source_track->body_sid = essence_data->body_sid; + source_track->index_sid = essence_data->index_sid; + break; + } + } + + if(source_track && component) + break; + } + if (!source_track || !component || !source_package) { + if((ret = mxf_add_metadata_stream(mxf, material_track))) + goto fail_and_free; + continue; + } + + if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) { + av_log(mxf->fc, AV_LOG_ERROR, ""could not resolve source track sequence strong ref\n""); + ret = AVERROR_INVALIDDATA; + goto fail_and_free; + } + + /* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf + * This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */ + if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) { + av_log(mxf->fc, AV_LOG_ERROR, ""material track %d: DataDefinition mismatch\n"", material_track->track_id); + continue; + } + + st = avformat_new_stream(mxf->fc, NULL); + if (!st) { + av_log(mxf->fc, AV_LOG_ERROR, ""could not allocate stream\n""); + ret = AVERROR(ENOMEM); + goto fail_and_free; + } + st->id = material_track->track_id; + st->priv_data = source_track; + + source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType); + descriptor = mxf_resolve_multidescriptor(mxf, source_package->descriptor, source_track->track_id); + + /* A SourceClip from a EssenceGroup may only be a single frame of essence data. The clips duration is then how many + * frames its suppose to repeat for. Descriptor->duration, if present, contains the real duration of the essence data */ + if (descriptor && descriptor->duration != AV_NOPTS_VALUE) + source_track->original_duration = st->duration = FFMIN(descriptor->duration, component->duration); + else + source_track->original_duration = st->duration = component->duration; + + if (st->duration == -1) + st->duration = AV_NOPTS_VALUE; + st->start_time = component->start_position; + if (material_track->edit_rate.num <= 0 || + material_track->edit_rate.den <= 0) { + av_log(mxf->fc, AV_LOG_WARNING, + ""Invalid edit rate (%d/%d) found on stream #%d, "" + ""defaulting to 25/1\n"", + material_track->edit_rate.num, + material_track->edit_rate.den, st->index); + material_track->edit_rate = (AVRational){25, 1}; + } + avpriv_set_pts_info(st, 64, material_track->edit_rate.den, material_track->edit_rate.num); + + /* ensure SourceTrack EditRate == MaterialTrack EditRate since only + * the former is accessible via st->priv_data */ + source_track->edit_rate = material_track->edit_rate; + + PRINT_KEY(mxf->fc, ""data definition ul"", source_track->sequence->data_definition_ul); + codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul); + st->codecpar->codec_type = codec_ul->id; + + if (!descriptor) { + av_log(mxf->fc, AV_LOG_INFO, ""source track %d: stream %d, no descriptor found\n"", source_track->track_id, st->index); + continue; + } + PRINT_KEY(mxf->fc, ""essence codec ul"", descriptor->essence_codec_ul); + PRINT_KEY(mxf->fc, ""essence container ul"", descriptor->essence_container_ul); + essence_container_ul = &descriptor->essence_container_ul; + source_track->wrapping = (mxf->op == OPAtom) ? ClipWrapped : mxf_get_wrapping_kind(essence_container_ul); + if (source_track->wrapping == UnknownWrapped) + av_log(mxf->fc, AV_LOG_INFO, ""wrapping of stream %d is unknown\n"", st->index); + /* HACK: replacing the original key with mxf_encrypted_essence_container + * is not allowed according to s429-6, try to find correct information anyway */ + if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) { + av_log(mxf->fc, AV_LOG_INFO, ""broken encrypted mxf file\n""); + for (k = 0; k < mxf->metadata_sets_count; k++) { + MXFMetadataSet *metadata = mxf->metadata_sets[k]; + if (metadata->type == CryptoContext) { + essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul; + break; + } + } + } + + /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */ + codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul); + st->codecpar->codec_id = (enum AVCodecID)codec_ul->id; + if (st->codecpar->codec_id == AV_CODEC_ID_NONE) { + codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->codec_ul); + st->codecpar->codec_id = (enum AVCodecID)codec_ul->id; + } + + av_log(mxf->fc, AV_LOG_VERBOSE, ""%s: Universal Label: "", + avcodec_get_name(st->codecpar->codec_id)); + for (k = 0; k < 16; k++) { + av_log(mxf->fc, AV_LOG_VERBOSE, ""%.2x"", + descriptor->essence_codec_ul[k]); + if (!(k+1 & 19) || k == 5) + av_log(mxf->fc, AV_LOG_VERBOSE, "".""); + } + av_log(mxf->fc, AV_LOG_VERBOSE, ""\n""); + + mxf_add_umid_metadata(&st->metadata, ""file_package_umid"", source_package); + if (source_package->name && source_package->name[0]) + av_dict_set(&st->metadata, ""file_package_name"", source_package->name, 0); + if (material_track->name && material_track->name[0]) + av_dict_set(&st->metadata, ""track_name"", material_track->name, 0); + + mxf_parse_physical_source_package(mxf, source_track, st); + + if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { + source_track->intra_only = mxf_is_intra_only(descriptor); + container_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, essence_container_ul); + if (st->codecpar->codec_id == AV_CODEC_ID_NONE) + st->codecpar->codec_id = container_ul->id; + st->codecpar->width = descriptor->width; + st->codecpar->height = descriptor->height; /* Field height, not frame height */ + switch (descriptor->frame_layout) { + case FullFrame: + st->codecpar->field_order = AV_FIELD_PROGRESSIVE; + break; + case OneField: + /* Every other line is stored and needs to be duplicated. */ + av_log(mxf->fc, AV_LOG_INFO, ""OneField frame layout isn't currently supported\n""); + break; /* The correct thing to do here is fall through, but by breaking we might be + able to decode some streams at half the vertical resolution, rather than not al all. + It's also for compatibility with the old behavior. */ + case MixedFields: + break; + case SegmentedFrame: + st->codecpar->field_order = AV_FIELD_PROGRESSIVE; + case SeparateFields: + av_log(mxf->fc, AV_LOG_DEBUG, ""video_line_map: (%d, %d), field_dominance: %d\n"", + descriptor->video_line_map[0], descriptor->video_line_map[1], + descriptor->field_dominance); + if ((descriptor->video_line_map[0] > 0) && (descriptor->video_line_map[1] > 0)) { + /* Detect coded field order from VideoLineMap: + * (even, even) => bottom field coded first + * (even, odd) => top field coded first + * (odd, even) => top field coded first + * (odd, odd) => bottom field coded first + */ + if ((descriptor->video_line_map[0] + descriptor->video_line_map[1]) % 2) { + switch (descriptor->field_dominance) { + case MXF_FIELD_DOMINANCE_DEFAULT: + case MXF_FIELD_DOMINANCE_FF: + st->codecpar->field_order = AV_FIELD_TT; + break; + case MXF_FIELD_DOMINANCE_FL: + st->codecpar->field_order = AV_FIELD_TB; + break; + default: + avpriv_request_sample(mxf->fc, + ""Field dominance %d support"", + descriptor->field_dominance); + } + } else { + switch (descriptor->field_dominance) { + case MXF_FIELD_DOMINANCE_DEFAULT: + case MXF_FIELD_DOMINANCE_FF: + st->codecpar->field_order = AV_FIELD_BB; + break; + case MXF_FIELD_DOMINANCE_FL: + st->codecpar->field_order = AV_FIELD_BT; + break; + default: + avpriv_request_sample(mxf->fc, + ""Field dominance %d support"", + descriptor->field_dominance); + } + } + } + /* Turn field height into frame height. */ + st->codecpar->height *= 2; + break; + default: + av_log(mxf->fc, AV_LOG_INFO, ""Unknown frame layout type: %d\n"", descriptor->frame_layout); + } + if (st->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO) { + st->codecpar->format = descriptor->pix_fmt; + if (st->codecpar->format == AV_PIX_FMT_NONE) { + pix_fmt_ul = mxf_get_codec_ul(ff_mxf_pixel_format_uls, + &descriptor->essence_codec_ul); + st->codecpar->format = (enum AVPixelFormat)pix_fmt_ul->id; + if (st->codecpar->format== AV_PIX_FMT_NONE) { + st->codecpar->codec_tag = mxf_get_codec_ul(ff_mxf_codec_tag_uls, + &descriptor->essence_codec_ul)->id; + if (!st->codecpar->codec_tag) { + /* support files created before RP224v10 by defaulting to UYVY422 + if subsampling is 4:2:2 and component depth is 8-bit */ + if (descriptor->horiz_subsampling == 2 && + descriptor->vert_subsampling == 1 && + descriptor->component_depth == 8) { + st->codecpar->format = AV_PIX_FMT_UYVY422; + } + } + } + } + } + st->need_parsing = AVSTREAM_PARSE_HEADERS; + if (material_track->sequence->origin) { + av_dict_set_int(&st->metadata, ""material_track_origin"", material_track->sequence->origin, 0); + } + if (source_track->sequence->origin) { + av_dict_set_int(&st->metadata, ""source_track_origin"", source_track->sequence->origin, 0); + } + if (descriptor->aspect_ratio.num && descriptor->aspect_ratio.den) + st->display_aspect_ratio = descriptor->aspect_ratio; + } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { + container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, essence_container_ul); + /* Only overwrite existing codec ID if it is unset or A-law, which is the default according to SMPTE RP 224. */ + if (st->codecpar->codec_id == AV_CODEC_ID_NONE || (st->codecpar->codec_id == AV_CODEC_ID_PCM_ALAW && (enum AVCodecID)container_ul->id != AV_CODEC_ID_NONE)) + st->codecpar->codec_id = (enum AVCodecID)container_ul->id; + st->codecpar->channels = descriptor->channels; + st->codecpar->bits_per_coded_sample = descriptor->bits_per_sample; + + if (descriptor->sample_rate.den > 0) { + st->codecpar->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den; + avpriv_set_pts_info(st, 64, descriptor->sample_rate.den, descriptor->sample_rate.num); + } else { + av_log(mxf->fc, AV_LOG_WARNING, ""invalid sample rate (%d/%d) "" + ""found for stream #%d, time base forced to 1/48000\n"", + descriptor->sample_rate.num, descriptor->sample_rate.den, + st->index); + avpriv_set_pts_info(st, 64, 1, 48000); + } + + /* if duration is set, rescale it from EditRate to SampleRate */ + if (st->duration != AV_NOPTS_VALUE) + st->duration = av_rescale_q(st->duration, + av_inv_q(material_track->edit_rate), + st->time_base); + + /* TODO: implement AV_CODEC_ID_RAWAUDIO */ + if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16LE) { + if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24) + st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE; + else if (descriptor->bits_per_sample == 32) + st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE; + } else if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE) { + if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24) + st->codecpar->codec_id = AV_CODEC_ID_PCM_S24BE; + else if (descriptor->bits_per_sample == 32) + st->codecpar->codec_id = AV_CODEC_ID_PCM_S32BE; + } else if (st->codecpar->codec_id == AV_CODEC_ID_MP2) { + st->need_parsing = AVSTREAM_PARSE_FULL; + } + } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) { + enum AVMediaType type; + container_ul = mxf_get_codec_ul(mxf_data_essence_container_uls, essence_container_ul); + if (st->codecpar->codec_id == AV_CODEC_ID_NONE) + st->codecpar->codec_id = container_ul->id; + type = avcodec_get_type(st->codecpar->codec_id); + if (type == AVMEDIA_TYPE_SUBTITLE) + st->codecpar->codec_type = type; + if (container_ul->desc) + av_dict_set(&st->metadata, ""data_type"", container_ul->desc, 0); + } + if (descriptor->extradata) { + if (!ff_alloc_extradata(st->codecpar, descriptor->extradata_size)) { + memcpy(st->codecpar->extradata, descriptor->extradata, descriptor->extradata_size); + } + } else if (st->codecpar->codec_id == AV_CODEC_ID_H264) { + int coded_width = mxf_get_codec_ul(mxf_intra_only_picture_coded_width, + &descriptor->essence_codec_ul)->id; + if (coded_width) + st->codecpar->width = coded_width; + ret = ff_generate_avci_extradata(st); + if (ret < 0) + return ret; + } + if (st->codecpar->codec_type != AVMEDIA_TYPE_DATA && source_track->wrapping != FrameWrapped) { + /* TODO: decode timestamps */ + st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS; + } + } + + ret = 0; +fail_and_free: + return ret; +} +",1,"static int mxf_parse_structural_metadata(MXFContext *mxf) +{ + MXFPackage *material_package = NULL; + int i, j, k, ret; + + av_log(mxf->fc, AV_LOG_TRACE, ""metadata sets count %d\n"", mxf->metadata_sets_count); + /* TODO: handle multiple material packages (OP3x) */ + for (i = 0; i < mxf->packages_count; i++) { + material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage); + if (material_package) break; + } + if (!material_package) { + av_log(mxf->fc, AV_LOG_ERROR, ""no material package found\n""); + return AVERROR_INVALIDDATA; + } + + mxf_add_umid_metadata(&mxf->fc->metadata, ""material_package_umid"", material_package); + if (material_package->name && material_package->name[0]) + av_dict_set(&mxf->fc->metadata, ""material_package_name"", material_package->name, 0); + mxf_parse_package_comments(mxf, &mxf->fc->metadata, material_package); + + for (i = 0; i < material_package->tracks_count; i++) { + MXFPackage *source_package = NULL; + MXFTrack *material_track = NULL; + MXFTrack *source_track = NULL; + MXFTrack *temp_track = NULL; + MXFDescriptor *descriptor = NULL; + MXFStructuralComponent *component = NULL; + MXFTimecodeComponent *mxf_tc = NULL; + UID *essence_container_ul = NULL; + const MXFCodecUL *codec_ul = NULL; + const MXFCodecUL *container_ul = NULL; + const MXFCodecUL *pix_fmt_ul = NULL; + AVStream *st; + AVTimecode tc; + int flags; + + if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) { + av_log(mxf->fc, AV_LOG_ERROR, ""could not resolve material track strong ref\n""); + continue; + } + + if ((component = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, TimecodeComponent))) { + mxf_tc = (MXFTimecodeComponent*)component; + flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0; + if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) { + mxf_add_timecode_metadata(&mxf->fc->metadata, ""timecode"", &tc); + } + } + + if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) { + av_log(mxf->fc, AV_LOG_ERROR, ""could not resolve material track sequence strong ref\n""); + continue; + } + + for (j = 0; j < material_track->sequence->structural_components_count; j++) { + component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], TimecodeComponent); + if (!component) + continue; + + mxf_tc = (MXFTimecodeComponent*)component; + flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0; + if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) { + mxf_add_timecode_metadata(&mxf->fc->metadata, ""timecode"", &tc); + break; + } + } + + /* TODO: handle multiple source clips, only finds first valid source clip */ + if(material_track->sequence->structural_components_count > 1) + av_log(mxf->fc, AV_LOG_WARNING, ""material track %d: has %d components\n"", + material_track->track_id, material_track->sequence->structural_components_count); + + for (j = 0; j < material_track->sequence->structural_components_count; j++) { + component = mxf_resolve_sourceclip(mxf, &material_track->sequence->structural_components_refs[j]); + if (!component) + continue; + + source_package = mxf_resolve_source_package(mxf, component->source_package_ul, component->source_package_uid); + if (!source_package) { + av_log(mxf->fc, AV_LOG_TRACE, ""material track %d: no corresponding source package found\n"", material_track->track_id); + continue; + } + for (k = 0; k < source_package->tracks_count; k++) { + if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) { + av_log(mxf->fc, AV_LOG_ERROR, ""could not resolve source track strong ref\n""); + ret = AVERROR_INVALIDDATA; + goto fail_and_free; + } + if (temp_track->track_id == component->source_track_id) { + source_track = temp_track; + break; + } + } + if (!source_track) { + av_log(mxf->fc, AV_LOG_ERROR, ""material track %d: no corresponding source track found\n"", material_track->track_id); + break; + } + + for (k = 0; k < mxf->essence_container_data_count; k++) { + MXFEssenceContainerData *essence_data; + + if (!(essence_data = mxf_resolve_strong_ref(mxf, &mxf->essence_container_data_refs[k], EssenceContainerData))) { + av_log(mxf->fc, AV_LOG_TRACE, ""could not resolve essence container data strong ref\n""); + continue; + } + if (!memcmp(component->source_package_ul, essence_data->package_ul, sizeof(UID)) && !memcmp(component->source_package_uid, essence_data->package_uid, sizeof(UID))) { + source_track->body_sid = essence_data->body_sid; + source_track->index_sid = essence_data->index_sid; + break; + } + } + + if(source_track && component) + break; + } + if (!source_track || !component || !source_package) { + if((ret = mxf_add_metadata_stream(mxf, material_track))) + goto fail_and_free; + continue; + } + + if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) { + av_log(mxf->fc, AV_LOG_ERROR, ""could not resolve source track sequence strong ref\n""); + ret = AVERROR_INVALIDDATA; + goto fail_and_free; + } + + /* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf + * This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */ + if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) { + av_log(mxf->fc, AV_LOG_ERROR, ""material track %d: DataDefinition mismatch\n"", material_track->track_id); + continue; + } + + st = avformat_new_stream(mxf->fc, NULL); + if (!st) { + av_log(mxf->fc, AV_LOG_ERROR, ""could not allocate stream\n""); + ret = AVERROR(ENOMEM); + goto fail_and_free; + } + st->id = material_track->track_id; + st->priv_data = source_track; + + source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType); + descriptor = mxf_resolve_multidescriptor(mxf, source_package->descriptor, source_track->track_id); + + /* A SourceClip from a EssenceGroup may only be a single frame of essence data. The clips duration is then how many + * frames its suppose to repeat for. Descriptor->duration, if present, contains the real duration of the essence data */ + if (descriptor && descriptor->duration != AV_NOPTS_VALUE) + source_track->original_duration = st->duration = FFMIN(descriptor->duration, component->duration); + else + source_track->original_duration = st->duration = component->duration; + + if (st->duration == -1) + st->duration = AV_NOPTS_VALUE; + st->start_time = component->start_position; + if (material_track->edit_rate.num <= 0 || + material_track->edit_rate.den <= 0) { + av_log(mxf->fc, AV_LOG_WARNING, + ""Invalid edit rate (%d/%d) found on stream #%d, "" + ""defaulting to 25/1\n"", + material_track->edit_rate.num, + material_track->edit_rate.den, st->index); + material_track->edit_rate = (AVRational){25, 1}; + } + avpriv_set_pts_info(st, 64, material_track->edit_rate.den, material_track->edit_rate.num); + + /* ensure SourceTrack EditRate == MaterialTrack EditRate since only + * the former is accessible via st->priv_data */ + source_track->edit_rate = material_track->edit_rate; + + PRINT_KEY(mxf->fc, ""data definition ul"", source_track->sequence->data_definition_ul); + codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul); + st->codecpar->codec_type = codec_ul->id; + + if (!descriptor) { + av_log(mxf->fc, AV_LOG_INFO, ""source track %d: stream %d, no descriptor found\n"", source_track->track_id, st->index); + continue; + } + PRINT_KEY(mxf->fc, ""essence codec ul"", descriptor->essence_codec_ul); + PRINT_KEY(mxf->fc, ""essence container ul"", descriptor->essence_container_ul); + essence_container_ul = &descriptor->essence_container_ul; + source_track->wrapping = (mxf->op == OPAtom) ? ClipWrapped : mxf_get_wrapping_kind(essence_container_ul); + if (source_track->wrapping == UnknownWrapped) + av_log(mxf->fc, AV_LOG_INFO, ""wrapping of stream %d is unknown\n"", st->index); + /* HACK: replacing the original key with mxf_encrypted_essence_container + * is not allowed according to s429-6, try to find correct information anyway */ + if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) { + av_log(mxf->fc, AV_LOG_INFO, ""broken encrypted mxf file\n""); + for (k = 0; k < mxf->metadata_sets_count; k++) { + MXFMetadataSet *metadata = mxf->metadata_sets[k]; + if (metadata->type == CryptoContext) { + essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul; + break; + } + } + } + + /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */ + codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul); + st->codecpar->codec_id = (enum AVCodecID)codec_ul->id; + if (st->codecpar->codec_id == AV_CODEC_ID_NONE) { + codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->codec_ul); + st->codecpar->codec_id = (enum AVCodecID)codec_ul->id; + } + + av_log(mxf->fc, AV_LOG_VERBOSE, ""%s: Universal Label: "", + avcodec_get_name(st->codecpar->codec_id)); + for (k = 0; k < 16; k++) { + av_log(mxf->fc, AV_LOG_VERBOSE, ""%.2x"", + descriptor->essence_codec_ul[k]); + if (!(k+1 & 19) || k == 5) + av_log(mxf->fc, AV_LOG_VERBOSE, "".""); + } + av_log(mxf->fc, AV_LOG_VERBOSE, ""\n""); + + mxf_add_umid_metadata(&st->metadata, ""file_package_umid"", source_package); + if (source_package->name && source_package->name[0]) + av_dict_set(&st->metadata, ""file_package_name"", source_package->name, 0); + if (material_track->name && material_track->name[0]) + av_dict_set(&st->metadata, ""track_name"", material_track->name, 0); + + mxf_parse_physical_source_package(mxf, source_track, st); + + if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { + source_track->intra_only = mxf_is_intra_only(descriptor); + container_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, essence_container_ul); + if (st->codecpar->codec_id == AV_CODEC_ID_NONE) + st->codecpar->codec_id = container_ul->id; + st->codecpar->width = descriptor->width; + st->codecpar->height = descriptor->height; /* Field height, not frame height */ + switch (descriptor->frame_layout) { + case FullFrame: + st->codecpar->field_order = AV_FIELD_PROGRESSIVE; + break; + case OneField: + /* Every other line is stored and needs to be duplicated. */ + av_log(mxf->fc, AV_LOG_INFO, ""OneField frame layout isn't currently supported\n""); + break; /* The correct thing to do here is fall through, but by breaking we might be + able to decode some streams at half the vertical resolution, rather than not al all. + It's also for compatibility with the old behavior. */ + case MixedFields: + break; + case SegmentedFrame: + st->codecpar->field_order = AV_FIELD_PROGRESSIVE; + case SeparateFields: + av_log(mxf->fc, AV_LOG_DEBUG, ""video_line_map: (%d, %d), field_dominance: %d\n"", + descriptor->video_line_map[0], descriptor->video_line_map[1], + descriptor->field_dominance); + if ((descriptor->video_line_map[0] > 0) && (descriptor->video_line_map[1] > 0)) { + /* Detect coded field order from VideoLineMap: + * (even, even) => bottom field coded first + * (even, odd) => top field coded first + * (odd, even) => top field coded first + * (odd, odd) => bottom field coded first + */ + if ((descriptor->video_line_map[0] + descriptor->video_line_map[1]) % 2) { + switch (descriptor->field_dominance) { + case MXF_FIELD_DOMINANCE_DEFAULT: + case MXF_FIELD_DOMINANCE_FF: + st->codecpar->field_order = AV_FIELD_TT; + break; + case MXF_FIELD_DOMINANCE_FL: + st->codecpar->field_order = AV_FIELD_TB; + break; + default: + avpriv_request_sample(mxf->fc, + ""Field dominance %d support"", + descriptor->field_dominance); + } + } else { + switch (descriptor->field_dominance) { + case MXF_FIELD_DOMINANCE_DEFAULT: + case MXF_FIELD_DOMINANCE_FF: + st->codecpar->field_order = AV_FIELD_BB; + break; + case MXF_FIELD_DOMINANCE_FL: + st->codecpar->field_order = AV_FIELD_BT; + break; + default: + avpriv_request_sample(mxf->fc, + ""Field dominance %d support"", + descriptor->field_dominance); + } + } + } + /* Turn field height into frame height. */ + st->codecpar->height *= 2; + break; + default: + av_log(mxf->fc, AV_LOG_INFO, ""Unknown frame layout type: %d\n"", descriptor->frame_layout); + } + if (st->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO) { + st->codecpar->format = descriptor->pix_fmt; + if (st->codecpar->format == AV_PIX_FMT_NONE) { + pix_fmt_ul = mxf_get_codec_ul(ff_mxf_pixel_format_uls, + &descriptor->essence_codec_ul); + st->codecpar->format = (enum AVPixelFormat)pix_fmt_ul->id; + if (st->codecpar->format== AV_PIX_FMT_NONE) { + st->codecpar->codec_tag = mxf_get_codec_ul(ff_mxf_codec_tag_uls, + &descriptor->essence_codec_ul)->id; + if (!st->codecpar->codec_tag) { + /* support files created before RP224v10 by defaulting to UYVY422 + if subsampling is 4:2:2 and component depth is 8-bit */ + if (descriptor->horiz_subsampling == 2 && + descriptor->vert_subsampling == 1 && + descriptor->component_depth == 8) { + st->codecpar->format = AV_PIX_FMT_UYVY422; + } + } + } + } + } + st->need_parsing = AVSTREAM_PARSE_HEADERS; + if (material_track->sequence->origin) { + av_dict_set_int(&st->metadata, ""material_track_origin"", material_track->sequence->origin, 0); + } + if (source_track->sequence->origin) { + av_dict_set_int(&st->metadata, ""source_track_origin"", source_track->sequence->origin, 0); + } + if (descriptor->aspect_ratio.num && descriptor->aspect_ratio.den) + st->display_aspect_ratio = descriptor->aspect_ratio; + } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { + container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, essence_container_ul); + /* Only overwrite existing codec ID if it is unset or A-law, which is the default according to SMPTE RP 224. */ + if (st->codecpar->codec_id == AV_CODEC_ID_NONE || (st->codecpar->codec_id == AV_CODEC_ID_PCM_ALAW && (enum AVCodecID)container_ul->id != AV_CODEC_ID_NONE)) + st->codecpar->codec_id = (enum AVCodecID)container_ul->id; + st->codecpar->channels = descriptor->channels; + st->codecpar->bits_per_coded_sample = descriptor->bits_per_sample; + + if (descriptor->sample_rate.den > 0) { + st->codecpar->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den; + avpriv_set_pts_info(st, 64, descriptor->sample_rate.den, descriptor->sample_rate.num); + } else { + av_log(mxf->fc, AV_LOG_WARNING, ""invalid sample rate (%d/%d) "" + ""found for stream #%d, time base forced to 1/48000\n"", + descriptor->sample_rate.num, descriptor->sample_rate.den, + st->index); + avpriv_set_pts_info(st, 64, 1, 48000); + } + + /* if duration is set, rescale it from EditRate to SampleRate */ + if (st->duration != AV_NOPTS_VALUE) + st->duration = av_rescale_q(st->duration, + av_inv_q(material_track->edit_rate), + st->time_base); + + /* TODO: implement AV_CODEC_ID_RAWAUDIO */ + if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16LE) { + if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24) + st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE; + else if (descriptor->bits_per_sample == 32) + st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE; + } else if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE) { + if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24) + st->codecpar->codec_id = AV_CODEC_ID_PCM_S24BE; + else if (descriptor->bits_per_sample == 32) + st->codecpar->codec_id = AV_CODEC_ID_PCM_S32BE; + } else if (st->codecpar->codec_id == AV_CODEC_ID_MP2) { + st->need_parsing = AVSTREAM_PARSE_FULL; + } + } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) { + enum AVMediaType type; + container_ul = mxf_get_codec_ul(mxf_data_essence_container_uls, essence_container_ul); + if (st->codecpar->codec_id == AV_CODEC_ID_NONE) + st->codecpar->codec_id = container_ul->id; + type = avcodec_get_type(st->codecpar->codec_id); + if (type == AVMEDIA_TYPE_SUBTITLE) + st->codecpar->codec_type = type; + if (container_ul->desc) + av_dict_set(&st->metadata, ""data_type"", container_ul->desc, 0); + } + if (descriptor->extradata) { + if (!ff_alloc_extradata(st->codecpar, descriptor->extradata_size)) { + memcpy(st->codecpar->extradata, descriptor->extradata, descriptor->extradata_size); + } + } else if (st->codecpar->codec_id == AV_CODEC_ID_H264) { + int coded_width = mxf_get_codec_ul(mxf_intra_only_picture_coded_width, + &descriptor->essence_codec_ul)->id; + if (coded_width) + st->codecpar->width = coded_width; + ret = ff_generate_avci_extradata(st); + if (ret < 0) + return ret; + } + if (st->codecpar->codec_type != AVMEDIA_TYPE_DATA && source_track->wrapping != FrameWrapped) { + /* TODO: decode timestamps */ + st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS; + } + } + + ret = 0; +fail_and_free: + return ret; +} +","@@ -2155,7 +2155,7 @@ static int mxf_parse_structural_metadata(MXFContext *mxf) + MXFEssenceContainerData *essence_data; + + if (!(essence_data = mxf_resolve_strong_ref(mxf, &mxf->essence_container_data_refs[k], EssenceContainerData))) { +- av_log(mxf, AV_LOG_TRACE, ""could not resolve essence container data strong ref\n""); ++ av_log(mxf->fc, AV_LOG_TRACE, ""could not resolve essence container data strong ref\n""); + continue; + } + if (!memcmp(component->source_package_ul, essence_data->package_ul, sizeof(UID)) && !memcmp(component->source_package_uid, essence_data->package_uid, sizeof(UID))) {",4819,5150,6144 +17961,"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); + + 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) */ +",1,"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; + + /* this interface is presently not 64-bit clean due to the int len argument + and the internal printbuf interface that takes 32-bit int len arguments + so the function limits the maximum string size to INT32_MAX (2GB). + If the function is called with len == -1 then strlen is called to check + the string length is less than INT32_MAX (2GB) */ + if ((len < -1) || (len == -1 && strlen(str) > INT32_MAX)) { + tok->err = json_tokener_error_size; + return NULL; + } + + 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); + + 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) */ +","@@ -81,6 +81,7 @@ static const char* json_tokener_errors[] = { + ""object value separator ',' expected"", + ""invalid string sequence"", + ""expected comment"", ++ ""buffer size overflow"" + }; + + const char *json_tokener_error_desc(enum json_tokener_error jerr) +@@ -243,6 +244,16 @@ struct json_object* json_tokener_parse_ex(struct json_tokener *tok, + tok->char_offset = 0; + tok->err = json_tokener_success; + ++ /* this interface is presently not 64-bit clean due to the int len argument ++ and the internal printbuf interface that takes 32-bit int len arguments ++ so the function limits the maximum string size to INT32_MAX (2GB). ++ If the function is called with len == -1 then strlen is called to check ++ the string length is less than INT32_MAX (2GB) */ ++ if ((len < -1) || (len == -1 && strlen(str) > INT32_MAX)) { ++ tok->err = json_tokener_error_size; ++ return NULL; ++ } ++ + while (PEEK_CHAR(c, tok)) { + + redo_char:",5107,5438,6144 +18191,"static MagickBooleanType WritePICTImage(const ImageInfo *image_info, + Image *image,ExceptionInfo *exception) +{ +#define MaxCount 128 +#define PictCropRegionOp 0x01 +#define PictEndOfPictureOp 0xff +#define PictJPEGOp 0x8200 +#define PictInfoOp 0x0C00 +#define PictInfoSize 512 +#define PictPixmapOp 0x9A +#define PictPICTOp 0x98 +#define PictVersion 0x11 + + const StringInfo + *profile; + + double + x_resolution, + y_resolution; + + MagickBooleanType + status; + + MagickOffsetType + offset; + + PICTPixmap + pixmap; + + PICTRectangle + bounds, + crop_rectangle, + destination_rectangle, + frame_rectangle, + size_rectangle, + source_rectangle; + + register const Quantum + *p; + + register ssize_t + i, + x; + + size_t + bytes_per_line, + count, + storage_class; + + ssize_t + y; + + unsigned char + *buffer, + *packed_scanline, + *scanline; + + unsigned short + base_address, + row_bytes, + transfer_mode; + + /* + 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); + if ((image->columns > 65535L) || (image->rows > 65535L)) + ThrowWriterException(ImageError,""WidthOrHeightExceedsLimit""); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickSignature); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); + if (status == MagickFalse) + return(status); + (void) TransformImageColorspace(image,sRGBColorspace,exception); + /* + Initialize image info. + */ + size_rectangle.top=0; + size_rectangle.left=0; + size_rectangle.bottom=(short) image->rows; + size_rectangle.right=(short) image->columns; + frame_rectangle=size_rectangle; + crop_rectangle=size_rectangle; + source_rectangle=size_rectangle; + destination_rectangle=size_rectangle; + base_address=0xff; + row_bytes=(unsigned short) (image->columns | 0x8000); + bounds.top=0; + bounds.left=0; + bounds.bottom=(short) image->rows; + bounds.right=(short) image->columns; + pixmap.version=0; + pixmap.pack_type=0; + pixmap.pack_size=0; + pixmap.pixel_type=0; + pixmap.bits_per_pixel=8; + pixmap.component_count=1; + pixmap.component_size=8; + pixmap.plane_bytes=0; + pixmap.table=0; + pixmap.reserved=0; + transfer_mode=0; + x_resolution=image->resolution.x != 0.0 ? image->resolution.x : + DefaultResolution; + y_resolution=image->resolution.y != 0.0 ? image->resolution.y : + DefaultResolution; + storage_class=image->storage_class; + if (image_info->compression == JPEGCompression) + storage_class=DirectClass; + if (storage_class == DirectClass) + { + pixmap.component_count=image->alpha_trait != UndefinedPixelTrait ? 4 : 3; + pixmap.pixel_type=16; + pixmap.bits_per_pixel=32; + pixmap.pack_type=0x04; + transfer_mode=0x40; + row_bytes=(unsigned short) ((4*image->columns) | 0x8000); + } + /* + Allocate memory. + */ + bytes_per_line=image->columns; + if (storage_class == DirectClass) + bytes_per_line*=image->alpha_trait != UndefinedPixelTrait ? 4 : 3; + buffer=(unsigned char *) AcquireQuantumMemory(PictInfoSize,sizeof(*buffer)); + packed_scanline=(unsigned char *) AcquireQuantumMemory((size_t) + (row_bytes+MaxCount),sizeof(*packed_scanline)); + scanline=(unsigned char *) AcquireQuantumMemory(row_bytes,sizeof(*scanline)); + if ((buffer == (unsigned char *) NULL) || + (packed_scanline == (unsigned char *) NULL) || + (scanline == (unsigned char *) NULL)) + ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); + (void) ResetMagickMemory(scanline,0,row_bytes); + (void) ResetMagickMemory(packed_scanline,0,(size_t) (row_bytes+MaxCount)); + /* + Write header, header size, size bounding box, version, and reserved. + */ + (void) ResetMagickMemory(buffer,0,PictInfoSize); + (void) WriteBlob(image,PictInfoSize,buffer); + (void) WriteBlobMSBShort(image,0); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.right); + (void) WriteBlobMSBShort(image,PictVersion); + (void) WriteBlobMSBShort(image,0x02ff); /* version #2 */ + (void) WriteBlobMSBShort(image,PictInfoOp); + (void) WriteBlobMSBLong(image,0xFFFE0000UL); + /* + Write full size of the file, resolution, frame bounding box, and reserved. + */ + (void) WriteBlobMSBShort(image,(unsigned short) x_resolution); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) y_resolution); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.right); + (void) WriteBlobMSBLong(image,0x00000000L); + profile=GetImageProfile(image,""iptc""); + if (profile != (StringInfo *) NULL) + { + (void) WriteBlobMSBShort(image,0xa1); + (void) WriteBlobMSBShort(image,0x1f2); + (void) WriteBlobMSBShort(image,(unsigned short) + (GetStringInfoLength(profile)+4)); + (void) WriteBlobString(image,""8BIM""); + (void) WriteBlob(image,GetStringInfoLength(profile), + GetStringInfoDatum(profile)); + } + profile=GetImageProfile(image,""icc""); + if (profile != (StringInfo *) NULL) + { + (void) WriteBlobMSBShort(image,0xa1); + (void) WriteBlobMSBShort(image,0xe0); + (void) WriteBlobMSBShort(image,(unsigned short) + (GetStringInfoLength(profile)+4)); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlob(image,GetStringInfoLength(profile), + GetStringInfoDatum(profile)); + (void) WriteBlobMSBShort(image,0xa1); + (void) WriteBlobMSBShort(image,0xe0); + (void) WriteBlobMSBShort(image,4); + (void) WriteBlobMSBLong(image,0x00000002UL); + } + /* + Write crop region opcode and crop bounding box. + */ + (void) WriteBlobMSBShort(image,PictCropRegionOp); + (void) WriteBlobMSBShort(image,0xa); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.right); + if (image_info->compression == JPEGCompression) + { + Image + *jpeg_image; + + ImageInfo + *jpeg_info; + + size_t + length; + + unsigned char + *blob; + + jpeg_image=CloneImage(image,0,0,MagickTrue,exception); + if (jpeg_image == (Image *) NULL) + { + (void) CloseBlob(image); + return(MagickFalse); + } + jpeg_info=CloneImageInfo(image_info); + (void) CopyMagickString(jpeg_info->magick,""JPEG"",MagickPathExtent); + length=0; + blob=(unsigned char *) ImageToBlob(jpeg_info,jpeg_image,&length, + exception); + jpeg_info=DestroyImageInfo(jpeg_info); + if (blob == (unsigned char *) NULL) + return(MagickFalse); + jpeg_image=DestroyImage(jpeg_image); + (void) WriteBlobMSBShort(image,PictJPEGOp); + (void) WriteBlobMSBLong(image,(unsigned int) length+154); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBLong(image,0x00010000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00010000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x40000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00400000UL); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) image->rows); + (void) WriteBlobMSBShort(image,(unsigned short) image->columns); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,768); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00566A70UL); + (void) WriteBlobMSBLong(image,0x65670000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000001UL); + (void) WriteBlobMSBLong(image,0x00016170UL); + (void) WriteBlobMSBLong(image,0x706C0000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBShort(image,768); + (void) WriteBlobMSBShort(image,(unsigned short) image->columns); + (void) WriteBlobMSBShort(image,(unsigned short) image->rows); + (void) WriteBlobMSBShort(image,(unsigned short) x_resolution); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) y_resolution); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x87AC0001UL); + (void) WriteBlobMSBLong(image,0x0B466F74UL); + (void) WriteBlobMSBLong(image,0x6F202D20UL); + (void) WriteBlobMSBLong(image,0x4A504547UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x0018FFFFUL); + (void) WriteBlob(image,length,blob); + if ((length & 0x01) != 0) + (void) WriteBlobByte(image,'\0'); + blob=(unsigned char *) RelinquishMagickMemory(blob); + } + /* + Write picture opcode, row bytes, and picture bounding box, and version. + */ + if (storage_class == PseudoClass) + (void) WriteBlobMSBShort(image,PictPICTOp); + else + { + (void) WriteBlobMSBShort(image,PictPixmapOp); + (void) WriteBlobMSBLong(image,(size_t) base_address); + } + (void) WriteBlobMSBShort(image,(unsigned short) (row_bytes | 0x8000)); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.top); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.left); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.right); + /* + Write pack type, pack size, resolution, pixel type, and pixel size. + */ + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.version); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.pack_type); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.pack_size); + (void) WriteBlobMSBShort(image,(unsigned short) (x_resolution+0.5)); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) (y_resolution+0.5)); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.pixel_type); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.bits_per_pixel); + /* + Write component count, size, plane bytes, table size, and reserved. + */ + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_count); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_size); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.plane_bytes); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.table); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.reserved); + if (storage_class == PseudoClass) + { + /* + Write image colormap. + */ + (void) WriteBlobMSBLong(image,0x00000000L); /* color seed */ + (void) WriteBlobMSBShort(image,0L); /* color flags */ + (void) WriteBlobMSBShort(image,(unsigned short) (image->colors-1)); + for (i=0; i < (ssize_t) image->colors; i++) + { + (void) WriteBlobMSBShort(image,(unsigned short) i); + (void) WriteBlobMSBShort(image,ScaleQuantumToShort( + image->colormap[i].red)); + (void) WriteBlobMSBShort(image,ScaleQuantumToShort( + image->colormap[i].green)); + (void) WriteBlobMSBShort(image,ScaleQuantumToShort( + image->colormap[i].blue)); + } + } + /* + Write source and destination rectangle. + */ + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.right); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.right); + (void) WriteBlobMSBShort(image,(unsigned short) transfer_mode); + /* + Write picture data. + */ + count=0; + if (storage_class == PseudoClass) + for (y=0; y < (ssize_t) image->rows; y++) + { + p=GetVirtualPixels(image,0,y,image->columns,1,exception); + if (p == (const Quantum *) NULL) + break; + for (x=0; x < (ssize_t) image->columns; x++) + { + scanline[x]=(unsigned char) GetPixelIndex(image,p); + p+=GetPixelChannels(image); + } + count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF), + packed_scanline); + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + } + else + if (image_info->compression == JPEGCompression) + { + (void) ResetMagickMemory(scanline,0,row_bytes); + for (y=0; y < (ssize_t) image->rows; y++) + count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF), + packed_scanline); + } + else + { + register unsigned char + *blue, + *green, + *opacity, + *red; + + red=scanline; + green=scanline+image->columns; + blue=scanline+2*image->columns; + opacity=scanline+3*image->columns; + for (y=0; y < (ssize_t) image->rows; y++) + { + p=GetVirtualPixels(image,0,y,image->columns,1,exception); + if (p == (const Quantum *) NULL) + break; + red=scanline; + green=scanline+image->columns; + blue=scanline+2*image->columns; + if (image->alpha_trait != UndefinedPixelTrait) + { + opacity=scanline; + red=scanline+image->columns; + green=scanline+2*image->columns; + blue=scanline+3*image->columns; + } + for (x=0; x < (ssize_t) image->columns; x++) + { + *red++=ScaleQuantumToChar(GetPixelRed(image,p)); + *green++=ScaleQuantumToChar(GetPixelGreen(image,p)); + *blue++=ScaleQuantumToChar(GetPixelBlue(image,p)); + if (image->alpha_trait != UndefinedPixelTrait) + *opacity++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(image,p))); + p+=GetPixelChannels(image); + } + count+=EncodeImage(image,scanline,bytes_per_line & 0x7FFF, + packed_scanline); + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + } + } + if ((count & 0x01) != 0) + (void) WriteBlobByte(image,'\0'); + (void) WriteBlobMSBShort(image,PictEndOfPictureOp); + offset=TellBlob(image); + offset=SeekBlob(image,512,SEEK_SET); + (void) WriteBlobMSBShort(image,(unsigned short) offset); + scanline=(unsigned char *) RelinquishMagickMemory(scanline); + packed_scanline=(unsigned char *) RelinquishMagickMemory(packed_scanline); + buffer=(unsigned char *) RelinquishMagickMemory(buffer); + (void) CloseBlob(image); + return(MagickTrue); +} +",1,"static MagickBooleanType WritePICTImage(const ImageInfo *image_info, + Image *image,ExceptionInfo *exception) +{ +#define MaxCount 128 +#define PictCropRegionOp 0x01 +#define PictEndOfPictureOp 0xff +#define PictJPEGOp 0x8200 +#define PictInfoOp 0x0C00 +#define PictInfoSize 512 +#define PictPixmapOp 0x9A +#define PictPICTOp 0x98 +#define PictVersion 0x11 + + const StringInfo + *profile; + + double + x_resolution, + y_resolution; + + MagickBooleanType + status; + + MagickOffsetType + offset; + + PICTPixmap + pixmap; + + PICTRectangle + bounds, + crop_rectangle, + destination_rectangle, + frame_rectangle, + size_rectangle, + source_rectangle; + + register const Quantum + *p; + + register ssize_t + i, + x; + + size_t + bytes_per_line, + count, + row_bytes, + storage_class; + + ssize_t + y; + + unsigned char + *buffer, + *packed_scanline, + *scanline; + + unsigned short + base_address, + transfer_mode; + + /* + 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); + if ((image->columns > 65535L) || (image->rows > 65535L)) + ThrowWriterException(ImageError,""WidthOrHeightExceedsLimit""); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickSignature); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); + if (status == MagickFalse) + return(status); + (void) TransformImageColorspace(image,sRGBColorspace,exception); + /* + Initialize image info. + */ + size_rectangle.top=0; + size_rectangle.left=0; + size_rectangle.bottom=(short) image->rows; + size_rectangle.right=(short) image->columns; + frame_rectangle=size_rectangle; + crop_rectangle=size_rectangle; + source_rectangle=size_rectangle; + destination_rectangle=size_rectangle; + base_address=0xff; + row_bytes=image->columns; + bounds.top=0; + bounds.left=0; + bounds.bottom=(short) image->rows; + bounds.right=(short) image->columns; + pixmap.version=0; + pixmap.pack_type=0; + pixmap.pack_size=0; + pixmap.pixel_type=0; + pixmap.bits_per_pixel=8; + pixmap.component_count=1; + pixmap.component_size=8; + pixmap.plane_bytes=0; + pixmap.table=0; + pixmap.reserved=0; + transfer_mode=0; + x_resolution=image->resolution.x != 0.0 ? image->resolution.x : + DefaultResolution; + y_resolution=image->resolution.y != 0.0 ? image->resolution.y : + DefaultResolution; + storage_class=image->storage_class; + if (image_info->compression == JPEGCompression) + storage_class=DirectClass; + if (storage_class == DirectClass) + { + pixmap.component_count=image->alpha_trait != UndefinedPixelTrait ? 4 : 3; + pixmap.pixel_type=16; + pixmap.bits_per_pixel=32; + pixmap.pack_type=0x04; + transfer_mode=0x40; + row_bytes=4*image->columns; + } + /* + Allocate memory. + */ + bytes_per_line=image->columns; + if (storage_class == DirectClass) + bytes_per_line*=image->alpha_trait != UndefinedPixelTrait ? 4 : 3; + buffer=(unsigned char *) AcquireQuantumMemory(PictInfoSize,sizeof(*buffer)); + packed_scanline=(unsigned char *) AcquireQuantumMemory((size_t) + (row_bytes+MaxCount),sizeof(*packed_scanline)); + scanline=(unsigned char *) AcquireQuantumMemory(row_bytes,sizeof(*scanline)); + if ((buffer == (unsigned char *) NULL) || + (packed_scanline == (unsigned char *) NULL) || + (scanline == (unsigned char *) NULL)) + ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); + (void) ResetMagickMemory(scanline,0,row_bytes); + (void) ResetMagickMemory(packed_scanline,0,(size_t) (row_bytes+MaxCount)); + /* + Write header, header size, size bounding box, version, and reserved. + */ + (void) ResetMagickMemory(buffer,0,PictInfoSize); + (void) WriteBlob(image,PictInfoSize,buffer); + (void) WriteBlobMSBShort(image,0); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.right); + (void) WriteBlobMSBShort(image,PictVersion); + (void) WriteBlobMSBShort(image,0x02ff); /* version #2 */ + (void) WriteBlobMSBShort(image,PictInfoOp); + (void) WriteBlobMSBLong(image,0xFFFE0000UL); + /* + Write full size of the file, resolution, frame bounding box, and reserved. + */ + (void) WriteBlobMSBShort(image,(unsigned short) x_resolution); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) y_resolution); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.right); + (void) WriteBlobMSBLong(image,0x00000000L); + profile=GetImageProfile(image,""iptc""); + if (profile != (StringInfo *) NULL) + { + (void) WriteBlobMSBShort(image,0xa1); + (void) WriteBlobMSBShort(image,0x1f2); + (void) WriteBlobMSBShort(image,(unsigned short) + (GetStringInfoLength(profile)+4)); + (void) WriteBlobString(image,""8BIM""); + (void) WriteBlob(image,GetStringInfoLength(profile), + GetStringInfoDatum(profile)); + } + profile=GetImageProfile(image,""icc""); + if (profile != (StringInfo *) NULL) + { + (void) WriteBlobMSBShort(image,0xa1); + (void) WriteBlobMSBShort(image,0xe0); + (void) WriteBlobMSBShort(image,(unsigned short) + (GetStringInfoLength(profile)+4)); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlob(image,GetStringInfoLength(profile), + GetStringInfoDatum(profile)); + (void) WriteBlobMSBShort(image,0xa1); + (void) WriteBlobMSBShort(image,0xe0); + (void) WriteBlobMSBShort(image,4); + (void) WriteBlobMSBLong(image,0x00000002UL); + } + /* + Write crop region opcode and crop bounding box. + */ + (void) WriteBlobMSBShort(image,PictCropRegionOp); + (void) WriteBlobMSBShort(image,0xa); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.right); + if (image_info->compression == JPEGCompression) + { + Image + *jpeg_image; + + ImageInfo + *jpeg_info; + + size_t + length; + + unsigned char + *blob; + + jpeg_image=CloneImage(image,0,0,MagickTrue,exception); + if (jpeg_image == (Image *) NULL) + { + (void) CloseBlob(image); + return(MagickFalse); + } + jpeg_info=CloneImageInfo(image_info); + (void) CopyMagickString(jpeg_info->magick,""JPEG"",MagickPathExtent); + length=0; + blob=(unsigned char *) ImageToBlob(jpeg_info,jpeg_image,&length, + exception); + jpeg_info=DestroyImageInfo(jpeg_info); + if (blob == (unsigned char *) NULL) + return(MagickFalse); + jpeg_image=DestroyImage(jpeg_image); + (void) WriteBlobMSBShort(image,PictJPEGOp); + (void) WriteBlobMSBLong(image,(unsigned int) length+154); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBLong(image,0x00010000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00010000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x40000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00400000UL); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) image->rows); + (void) WriteBlobMSBShort(image,(unsigned short) image->columns); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,768); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00566A70UL); + (void) WriteBlobMSBLong(image,0x65670000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000001UL); + (void) WriteBlobMSBLong(image,0x00016170UL); + (void) WriteBlobMSBLong(image,0x706C0000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBShort(image,768); + (void) WriteBlobMSBShort(image,(unsigned short) image->columns); + (void) WriteBlobMSBShort(image,(unsigned short) image->rows); + (void) WriteBlobMSBShort(image,(unsigned short) x_resolution); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) y_resolution); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x87AC0001UL); + (void) WriteBlobMSBLong(image,0x0B466F74UL); + (void) WriteBlobMSBLong(image,0x6F202D20UL); + (void) WriteBlobMSBLong(image,0x4A504547UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x00000000UL); + (void) WriteBlobMSBLong(image,0x0018FFFFUL); + (void) WriteBlob(image,length,blob); + if ((length & 0x01) != 0) + (void) WriteBlobByte(image,'\0'); + blob=(unsigned char *) RelinquishMagickMemory(blob); + } + /* + Write picture opcode, row bytes, and picture bounding box, and version. + */ + if (storage_class == PseudoClass) + (void) WriteBlobMSBShort(image,PictPICTOp); + else + { + (void) WriteBlobMSBShort(image,PictPixmapOp); + (void) WriteBlobMSBLong(image,(size_t) base_address); + } + (void) WriteBlobMSBShort(image,(unsigned short) (row_bytes | 0x8000)); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.top); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.left); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.right); + /* + Write pack type, pack size, resolution, pixel type, and pixel size. + */ + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.version); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.pack_type); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.pack_size); + (void) WriteBlobMSBShort(image,(unsigned short) (x_resolution+0.5)); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) (y_resolution+0.5)); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.pixel_type); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.bits_per_pixel); + /* + Write component count, size, plane bytes, table size, and reserved. + */ + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_count); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_size); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.plane_bytes); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.table); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.reserved); + if (storage_class == PseudoClass) + { + /* + Write image colormap. + */ + (void) WriteBlobMSBLong(image,0x00000000L); /* color seed */ + (void) WriteBlobMSBShort(image,0L); /* color flags */ + (void) WriteBlobMSBShort(image,(unsigned short) (image->colors-1)); + for (i=0; i < (ssize_t) image->colors; i++) + { + (void) WriteBlobMSBShort(image,(unsigned short) i); + (void) WriteBlobMSBShort(image,ScaleQuantumToShort( + image->colormap[i].red)); + (void) WriteBlobMSBShort(image,ScaleQuantumToShort( + image->colormap[i].green)); + (void) WriteBlobMSBShort(image,ScaleQuantumToShort( + image->colormap[i].blue)); + } + } + /* + Write source and destination rectangle. + */ + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.right); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.right); + (void) WriteBlobMSBShort(image,(unsigned short) transfer_mode); + /* + Write picture data. + */ + count=0; + if (storage_class == PseudoClass) + for (y=0; y < (ssize_t) image->rows; y++) + { + p=GetVirtualPixels(image,0,y,image->columns,1,exception); + if (p == (const Quantum *) NULL) + break; + for (x=0; x < (ssize_t) image->columns; x++) + { + scanline[x]=(unsigned char) GetPixelIndex(image,p); + p+=GetPixelChannels(image); + } + count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF), + packed_scanline); + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + } + else + if (image_info->compression == JPEGCompression) + { + (void) ResetMagickMemory(scanline,0,row_bytes); + for (y=0; y < (ssize_t) image->rows; y++) + count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF), + packed_scanline); + } + else + { + register unsigned char + *blue, + *green, + *opacity, + *red; + + red=scanline; + green=scanline+image->columns; + blue=scanline+2*image->columns; + opacity=scanline+3*image->columns; + for (y=0; y < (ssize_t) image->rows; y++) + { + p=GetVirtualPixels(image,0,y,image->columns,1,exception); + if (p == (const Quantum *) NULL) + break; + red=scanline; + green=scanline+image->columns; + blue=scanline+2*image->columns; + if (image->alpha_trait != UndefinedPixelTrait) + { + opacity=scanline; + red=scanline+image->columns; + green=scanline+2*image->columns; + blue=scanline+3*image->columns; + } + for (x=0; x < (ssize_t) image->columns; x++) + { + *red++=ScaleQuantumToChar(GetPixelRed(image,p)); + *green++=ScaleQuantumToChar(GetPixelGreen(image,p)); + *blue++=ScaleQuantumToChar(GetPixelBlue(image,p)); + if (image->alpha_trait != UndefinedPixelTrait) + *opacity++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(image,p))); + p+=GetPixelChannels(image); + } + count+=EncodeImage(image,scanline,bytes_per_line & 0x7FFF, + packed_scanline); + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + } + } + if ((count & 0x01) != 0) + (void) WriteBlobByte(image,'\0'); + (void) WriteBlobMSBShort(image,PictEndOfPictureOp); + offset=TellBlob(image); + offset=SeekBlob(image,512,SEEK_SET); + (void) WriteBlobMSBShort(image,(unsigned short) offset); + scanline=(unsigned char *) RelinquishMagickMemory(scanline); + packed_scanline=(unsigned char *) RelinquishMagickMemory(packed_scanline); + buffer=(unsigned char *) RelinquishMagickMemory(buffer); + (void) CloseBlob(image); + return(MagickTrue); +} +","@@ -1637,6 +1637,7 @@ static MagickBooleanType WritePICTImage(const ImageInfo *image_info, + size_t + bytes_per_line, + count, ++ row_bytes, + storage_class; + + ssize_t +@@ -1649,7 +1650,6 @@ static MagickBooleanType WritePICTImage(const ImageInfo *image_info, + + unsigned short + base_address, +- row_bytes, + transfer_mode; + + /* +@@ -1681,7 +1681,7 @@ static MagickBooleanType WritePICTImage(const ImageInfo *image_info, + source_rectangle=size_rectangle; + destination_rectangle=size_rectangle; + base_address=0xff; +- row_bytes=(unsigned short) (image->columns | 0x8000); ++ row_bytes=image->columns; + bounds.top=0; + bounds.left=0; + bounds.bottom=(short) image->rows; +@@ -1711,7 +1711,7 @@ static MagickBooleanType WritePICTImage(const ImageInfo *image_info, + pixmap.bits_per_pixel=32; + pixmap.pack_type=0x04; + transfer_mode=0x40; +- row_bytes=(unsigned short) ((4*image->columns) | 0x8000); ++ row_bytes=4*image->columns; + } + /* + Allocate memory.",4775,5106,6144 +18211,"static Image *ReadOneJNGImage(MngInfo *mng_info, + const ImageInfo *image_info, ExceptionInfo *exception) +{ + Image + *alpha_image, + *color_image, + *image, + *jng_image; + + ImageInfo + *alpha_image_info, + *color_image_info; + + MagickBooleanType + logging; + + ssize_t + y; + + MagickBooleanType + status; + + png_uint_32 + jng_height, + jng_width; + + png_byte + jng_color_type, + jng_image_sample_depth, + jng_image_compression_method, + jng_image_interlace_method, + jng_alpha_sample_depth, + jng_alpha_compression_method, + jng_alpha_filter_method, + jng_alpha_interlace_method; + + register const Quantum + *s; + + register ssize_t + i, + x; + + register Quantum + *q; + + register unsigned char + *p; + + unsigned int + read_JSEP, + reading_idat; + + size_t + length; + + jng_alpha_compression_method=0; + jng_alpha_sample_depth=8; + jng_color_type=0; + jng_height=0; + jng_width=0; + alpha_image=(Image *) NULL; + color_image=(Image *) NULL; + alpha_image_info=(ImageInfo *) NULL; + color_image_info=(ImageInfo *) NULL; + + logging=LogMagickEvent(CoderEvent,GetMagickModule(), + "" Enter ReadOneJNGImage()""); + + image=mng_info->image; + + if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) + { + /* + Allocate next image structure. + */ + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" AcquireNextImage()""); + + AcquireNextImage(image_info,image,exception); + + if (GetNextImageInList(image) == (Image *) NULL) + return(DestroyImageList(image)); + + image=SyncNextImageInList(image); + } + mng_info->image=image; + + /* + Signature bytes have already been read. + */ + + read_JSEP=MagickFalse; + reading_idat=MagickFalse; + for (;;) + { + char + type[MagickPathExtent]; + + unsigned char + *chunk; + + unsigned int + count; + + /* + Read a new JNG chunk. + */ + status=SetImageProgress(image,LoadImagesTag,TellBlob(image), + 2*GetBlobSize(image)); + + if (status == MagickFalse) + break; + + type[0]='\0'; + (void) ConcatenateMagickString(type,""errr"",MagickPathExtent); + length=(size_t) ReadBlobMSBLong(image); + count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Reading JNG chunk type %c%c%c%c, length: %.20g"", + type[0],type[1],type[2],type[3],(double) length); + + if (length > PNG_UINT_31_MAX || count == 0) + { + DestroyJNG(NULL,&color_image,&color_image_info, + &alpha_image,&alpha_image_info); + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + } + if (length > GetBlobSize(image)) + { + DestroyJNG(NULL,&color_image,&color_image_info, + &alpha_image,&alpha_image_info); + ThrowReaderException(CorruptImageError, + ""InsufficientImageDataInFile""); + } + + p=NULL; + chunk=(unsigned char *) NULL; + + if (length != 0) + { + chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); + + if (chunk == (unsigned char *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + + for (i=0; i < (ssize_t) length; i++) + { + int + c; + + c=ReadBlobByte(image); + if (c == EOF) + break; + chunk[i]=(unsigned char) c; + } + for ( ; i < (ssize_t) length; i++) + chunk[i]='\0'; + + p=chunk; + } + + (void) ReadBlobMSBLong(image); /* read crc word */ + + if (memcmp(type,mng_JHDR,4) == 0) + { + if (length == 16) + { + jng_width=(png_uint_32)mng_get_long(p); + jng_height=(png_uint_32)mng_get_long(&p[4]); + if ((jng_width == 0) || (jng_height == 0)) + { + DestroyJNG(chunk,&color_image,&color_image_info, + &alpha_image,&alpha_image_info); + ThrowReaderException(CorruptImageError, + ""NegativeOrZeroImageSize""); + } + jng_color_type=p[8]; + jng_image_sample_depth=p[9]; + jng_image_compression_method=p[10]; + jng_image_interlace_method=p[11]; + + image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : + NoInterlace; + + jng_alpha_sample_depth=p[12]; + jng_alpha_compression_method=p[13]; + jng_alpha_filter_method=p[14]; + jng_alpha_interlace_method=p[15]; + + if (logging != MagickFalse) + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" jng_width: %16lu, jng_height: %16lu\n"" + "" jng_color_type: %16d, jng_image_sample_depth: %3d\n"" + "" jng_image_compression_method:%3d"", + (unsigned long) jng_width, (unsigned long) jng_height, + jng_color_type, jng_image_sample_depth, + jng_image_compression_method); + + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" jng_image_interlace_method: %3d"" + "" jng_alpha_sample_depth: %3d"", + jng_image_interlace_method, + jng_alpha_sample_depth); + + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" jng_alpha_compression_method:%3d\n"" + "" jng_alpha_filter_method: %3d\n"" + "" jng_alpha_interlace_method: %3d"", + jng_alpha_compression_method, + jng_alpha_filter_method, + jng_alpha_interlace_method); + } + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + if (jng_width > 65535 || jng_height > 65535 || + (long) jng_width > GetMagickResourceLimit(WidthResource) || + (long) jng_height > GetMagickResourceLimit(HeightResource)) + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" JNG width or height too large: (%lu x %lu)"", + (long) jng_width, (long) jng_height); + DestroyJNG(chunk,&color_image,&color_image_info, + &alpha_image,&alpha_image_info); + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + } + + continue; + } + + + if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && + ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || + (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) + { + /* + o create color_image + o open color_blob, attached to color_image + o if (color type has alpha) + open alpha_blob, attached to alpha_image + */ + + color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); + + if (color_image_info == (ImageInfo *) NULL) + { + DestroyJNG(chunk,&color_image,&color_image_info, + &alpha_image,&alpha_image_info); + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + } + + GetImageInfo(color_image_info); + color_image=AcquireImage(color_image_info,exception); + + if (color_image == (Image *) NULL) + { + DestroyJNG(chunk,&color_image,&color_image_info, + &alpha_image,&alpha_image_info); + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + } + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Creating color_blob.""); + + (void) AcquireUniqueFilename(color_image->filename); + status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, + exception); + + if (status == MagickFalse) + { + DestroyJNG(chunk,&color_image,&color_image_info, + &alpha_image,&alpha_image_info); + return(DestroyImageList(image)); + } + + if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) + { + alpha_image_info=(ImageInfo *) + AcquireMagickMemory(sizeof(ImageInfo)); + + if (alpha_image_info == (ImageInfo *) NULL) + { + DestroyJNG(chunk,&color_image,&color_image_info, + &alpha_image,&alpha_image_info); + ThrowReaderException(ResourceLimitError, + ""MemoryAllocationFailed""); + } + + GetImageInfo(alpha_image_info); + alpha_image=AcquireImage(alpha_image_info,exception); + + if (alpha_image == (Image *) NULL) + { + DestroyJNG(chunk,&color_image,&color_image_info, + &alpha_image,&alpha_image_info); + ThrowReaderException(ResourceLimitError, + ""MemoryAllocationFailed""); + } + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Creating alpha_blob.""); + + (void) AcquireUniqueFilename(alpha_image->filename); + status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, + exception); + + if (status == MagickFalse) + { + DestroyJNG(chunk,&color_image,&color_image_info, + &alpha_image,&alpha_image_info); + return(DestroyImageList(image)); + } + + if (jng_alpha_compression_method == 0) + { + unsigned char + data[18]; + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Writing IHDR chunk to alpha_blob.""); + + (void) WriteBlob(alpha_image,8,(const unsigned char *) + ""\211PNG\r\n\032\n""); + + (void) WriteBlobMSBULong(alpha_image,13L); + PNGType(data,mng_IHDR); + LogPNGChunk(logging,mng_IHDR,13L); + PNGLong(data+4,jng_width); + PNGLong(data+8,jng_height); + data[12]=jng_alpha_sample_depth; + data[13]=0; /* color_type gray */ + data[14]=0; /* compression method 0 */ + data[15]=0; /* filter_method 0 */ + data[16]=0; /* interlace_method 0 */ + (void) WriteBlob(alpha_image,17,data); + (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); + } + } + reading_idat=MagickTrue; + } + + if (memcmp(type,mng_JDAT,4) == 0) + { + /* Copy chunk to color_image->blob */ + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Copying JDAT chunk data to color_blob.""); + + if ((length != 0) && (color_image != (Image *) NULL)) + (void) WriteBlob(color_image,length,chunk); + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + continue; + } + + if (memcmp(type,mng_IDAT,4) == 0) + { + png_byte + data[5]; + + /* Copy IDAT header and chunk data to alpha_image->blob */ + + if (alpha_image != NULL && image_info->ping == MagickFalse) + { + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Copying IDAT chunk data to alpha_blob.""); + + (void) WriteBlobMSBULong(alpha_image,(size_t) length); + PNGType(data,mng_IDAT); + LogPNGChunk(logging,mng_IDAT,length); + (void) WriteBlob(alpha_image,4,data); + (void) WriteBlob(alpha_image,length,chunk); + (void) WriteBlobMSBULong(alpha_image, + crc32(crc32(0,data,4),chunk,(uInt) length)); + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + continue; + } + + if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) + { + /* Copy chunk data to alpha_image->blob */ + + if ((alpha_image != NULL) && (image_info->ping == MagickFalse) && + (length != 0)) + { + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Copying JDAA chunk data to alpha_blob.""); + + (void) WriteBlob(alpha_image,length,chunk); + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + continue; + } + + if (memcmp(type,mng_JSEP,4) == 0) + { + read_JSEP=MagickTrue; + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + continue; + } + + if (memcmp(type,mng_bKGD,4) == 0) + { + if (length == 2) + { + image->background_color.red=ScaleCharToQuantum(p[1]); + image->background_color.green=image->background_color.red; + image->background_color.blue=image->background_color.red; + } + + if (length == 6) + { + image->background_color.red=ScaleCharToQuantum(p[1]); + image->background_color.green=ScaleCharToQuantum(p[3]); + image->background_color.blue=ScaleCharToQuantum(p[5]); + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + continue; + } + + if (memcmp(type,mng_gAMA,4) == 0) + { + if (length == 4) + image->gamma=((float) mng_get_long(p))*0.00001; + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + continue; + } + + if (memcmp(type,mng_cHRM,4) == 0) + { + if (length == 32) + { + image->chromaticity.white_point.x=0.00001*mng_get_long(p); + image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); + image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); + image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); + image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); + image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); + image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); + image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + continue; + } + + if (memcmp(type,mng_sRGB,4) == 0) + { + if (length == 1) + { + image->rendering_intent= + Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); + image->gamma=1.000f/2.200f; + image->chromaticity.red_primary.x=0.6400f; + image->chromaticity.red_primary.y=0.3300f; + image->chromaticity.green_primary.x=0.3000f; + image->chromaticity.green_primary.y=0.6000f; + image->chromaticity.blue_primary.x=0.1500f; + image->chromaticity.blue_primary.y=0.0600f; + image->chromaticity.white_point.x=0.3127f; + image->chromaticity.white_point.y=0.3290f; + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + continue; + } + + if (memcmp(type,mng_oFFs,4) == 0) + { + if (length > 8) + { + image->page.x=(ssize_t) mng_get_long(p); + image->page.y=(ssize_t) mng_get_long(&p[4]); + + if ((int) p[8] != 0) + { + image->page.x/=10000; + image->page.y/=10000; + } + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + continue; + } + + if (memcmp(type,mng_pHYs,4) == 0) + { + if (length > 8) + { + image->resolution.x=(double) mng_get_long(p); + image->resolution.y=(double) mng_get_long(&p[4]); + if ((int) p[8] == PNG_RESOLUTION_METER) + { + image->units=PixelsPerCentimeterResolution; + image->resolution.x=image->resolution.x/100.0f; + image->resolution.y=image->resolution.y/100.0f; + } + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + continue; + } + +#if 0 + if (memcmp(type,mng_iCCP,4) == 0) + { + /* To do: */ + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + continue; + } +#endif + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + if (memcmp(type,mng_IEND,4)) + continue; + + break; + } + + + /* IEND found */ + + /* + Finish up reading image data: + + o read main image from color_blob. + + o close color_blob. + + o if (color_type has alpha) + if alpha_encoding is PNG + read secondary image from alpha_blob via ReadPNG + if alpha_encoding is JPEG + read secondary image from alpha_blob via ReadJPEG + + o close alpha_blob. + + o copy intensity of secondary image into + alpha samples of main image. + + o destroy the secondary image. + */ + + if (color_image_info == (ImageInfo *) NULL) + { + assert(color_image == (Image *) NULL); + assert(alpha_image == (Image *) NULL); + if (color_image != (Image *) NULL) + color_image=DestroyImageList(color_image); + return(DestroyImageList(image)); + } + + if (color_image == (Image *) NULL) + { + assert(alpha_image == (Image *) NULL); + ThrowReaderException(CorruptImageError,""InsufficientImageDataInFile""); + } + + (void) SeekBlob(color_image,0,SEEK_SET); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Reading jng_image from color_blob.""); + + assert(color_image_info != (ImageInfo *) NULL); + (void) FormatLocaleString(color_image_info->filename,MagickPathExtent, + ""jpeg:%s"",color_image->filename); + + color_image_info->ping=MagickFalse; /* To do: avoid this */ + jng_image=ReadImage(color_image_info,exception); + + (void) RelinquishUniqueFileResource(color_image->filename); + color_image=DestroyImage(color_image); + color_image_info=DestroyImageInfo(color_image_info); + + if (jng_image == (Image *) NULL) + { + DestroyJNG(NULL,NULL,NULL,&alpha_image,&alpha_image_info); + return(DestroyImageList(image)); + } + + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Copying jng_image pixels to main image.""); + + image->rows=jng_height; + image->columns=jng_width; + + status=SetImageExtent(image,image->columns,image->rows,exception); + if (status == MagickFalse) + { + DestroyJNG(NULL,&color_image,&color_image_info,&alpha_image, + &alpha_image_info); + jng_image=DestroyImageList(jng_image); + return(DestroyImageList(image)); + } + if ((image->columns != jng_image->columns) || + (image->rows != jng_image->rows)) + { + DestroyJNG(NULL,&color_image,&color_image_info,&alpha_image, + &alpha_image_info); + jng_image=DestroyImageList(jng_image); + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + } + for (y=0; y < (ssize_t) image->rows; y++) + { + s=GetVirtualPixels(jng_image,0,y,image->columns,1,exception); + q=GetAuthenticPixels(image,0,y,image->columns,1,exception); + if ((s == (const Quantum *) NULL) || (q == (Quantum *) NULL)) + break; + for (x=(ssize_t) image->columns; x != 0; x--) + { + SetPixelRed(image,GetPixelRed(jng_image,s),q); + SetPixelGreen(image,GetPixelGreen(jng_image,s),q); + SetPixelBlue(image,GetPixelBlue(jng_image,s),q); + q+=GetPixelChannels(image); + s+=GetPixelChannels(jng_image); + } + + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + } + + jng_image=DestroyImage(jng_image); + + if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) + { + if (jng_alpha_compression_method == 0) + { + png_byte + data[5]; + (void) WriteBlobMSBULong(alpha_image,0x00000000L); + PNGType(data,mng_IEND); + LogPNGChunk(logging,mng_IEND,0L); + (void) WriteBlob(alpha_image,4,data); + (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); + } + + (void) CloseBlob(alpha_image); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Reading alpha from alpha_blob.""); + + (void) FormatLocaleString(alpha_image_info->filename,MagickPathExtent, + ""%s"",alpha_image->filename); + + jng_image=ReadImage(alpha_image_info,exception); + + if (jng_image != (Image *) NULL) + for (y=0; y < (ssize_t) image->rows; y++) + { + s=GetVirtualPixels(jng_image,0,y,image->columns,1,exception); + q=GetAuthenticPixels(image,0,y,image->columns,1,exception); + if ((s == (const Quantum *) NULL) || (q == (Quantum *) NULL)) + break; + + if (image->alpha_trait != UndefinedPixelTrait) + for (x=(ssize_t) image->columns; x != 0; x--) + { + SetPixelAlpha(image,GetPixelRed(jng_image,s),q); + q+=GetPixelChannels(image); + s+=GetPixelChannels(jng_image); + } + + else + for (x=(ssize_t) image->columns; x != 0; x--) + { + SetPixelAlpha(image,GetPixelRed(jng_image,s),q); + if (GetPixelAlpha(image,q) != OpaqueAlpha) + image->alpha_trait=BlendPixelTrait; + q+=GetPixelChannels(image); + s+=GetPixelChannels(jng_image); + } + + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + } + (void) RelinquishUniqueFileResource(alpha_image->filename); + alpha_image=DestroyImage(alpha_image); + alpha_image_info=DestroyImageInfo(alpha_image_info); + if (jng_image != (Image *) NULL) + jng_image=DestroyImage(jng_image); + } + + /* Read the JNG image. */ + + if (mng_info->mng_type == 0) + { + mng_info->mng_width=jng_width; + mng_info->mng_height=jng_height; + } + + if (image->page.width == 0 && image->page.height == 0) + { + image->page.width=jng_width; + image->page.height=jng_height; + } + + if (image->page.x == 0 && image->page.y == 0) + { + image->page.x=mng_info->x_off[mng_info->object_id]; + image->page.y=mng_info->y_off[mng_info->object_id]; + } + + else + { + image->page.y=mng_info->y_off[mng_info->object_id]; + } + + mng_info->image_found++; + status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), + 2*GetBlobSize(image)); + + if (status == MagickFalse) + return(DestroyImageList(image)); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" exit ReadOneJNGImage()""); + + return(image); +} +",1,"static Image *ReadOneJNGImage(MngInfo *mng_info, + const ImageInfo *image_info, ExceptionInfo *exception) +{ + Image + *alpha_image, + *color_image, + *image, + *jng_image; + + ImageInfo + *alpha_image_info, + *color_image_info; + + MagickBooleanType + logging; + + ssize_t + y; + + MagickBooleanType + status; + + png_uint_32 + jng_height, + jng_width; + + png_byte + jng_color_type, + jng_image_sample_depth, + jng_image_compression_method, + jng_image_interlace_method, + jng_alpha_sample_depth, + jng_alpha_compression_method, + jng_alpha_filter_method, + jng_alpha_interlace_method; + + register const Quantum + *s; + + register ssize_t + i, + x; + + register Quantum + *q; + + register unsigned char + *p; + + unsigned int + read_JSEP, + reading_idat; + + size_t + length; + + jng_alpha_compression_method=0; + jng_alpha_sample_depth=8; + jng_color_type=0; + jng_height=0; + jng_width=0; + alpha_image=(Image *) NULL; + color_image=(Image *) NULL; + alpha_image_info=(ImageInfo *) NULL; + color_image_info=(ImageInfo *) NULL; + + logging=LogMagickEvent(CoderEvent,GetMagickModule(), + "" Enter ReadOneJNGImage()""); + + image=mng_info->image; + + if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) + { + /* + Allocate next image structure. + */ + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" AcquireNextImage()""); + + AcquireNextImage(image_info,image,exception); + + if (GetNextImageInList(image) == (Image *) NULL) + return(DestroyImageList(image)); + + image=SyncNextImageInList(image); + } + mng_info->image=image; + + /* + Signature bytes have already been read. + */ + + read_JSEP=MagickFalse; + reading_idat=MagickFalse; + for (;;) + { + char + type[MagickPathExtent]; + + unsigned char + *chunk; + + unsigned int + count; + + /* + Read a new JNG chunk. + */ + status=SetImageProgress(image,LoadImagesTag,TellBlob(image), + 2*GetBlobSize(image)); + + if (status == MagickFalse) + break; + + type[0]='\0'; + (void) ConcatenateMagickString(type,""errr"",MagickPathExtent); + length=(size_t) ReadBlobMSBLong(image); + count=(unsigned int) ReadBlob(image,4,(unsigned char *) type); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Reading JNG chunk type %c%c%c%c, length: %.20g"", + type[0],type[1],type[2],type[3],(double) length); + + if (length > PNG_UINT_31_MAX || count == 0) + { + DestroyJNG(NULL,&color_image,&color_image_info, + &alpha_image,&alpha_image_info); + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + } + if (length > GetBlobSize(image)) + { + DestroyJNG(NULL,&color_image,&color_image_info, + &alpha_image,&alpha_image_info); + ThrowReaderException(CorruptImageError, + ""InsufficientImageDataInFile""); + } + + p=NULL; + chunk=(unsigned char *) NULL; + + if (length != 0) + { + chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); + + if (chunk == (unsigned char *) NULL) + { + DestroyJNG(NULL,&color_image,&color_image_info, + &alpha_image,&alpha_image_info); + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + } + + for (i=0; i < (ssize_t) length; i++) + { + int + c; + + c=ReadBlobByte(image); + if (c == EOF) + break; + chunk[i]=(unsigned char) c; + } + for ( ; i < (ssize_t) length; i++) + chunk[i]='\0'; + + p=chunk; + } + + (void) ReadBlobMSBLong(image); /* read crc word */ + + if (memcmp(type,mng_JHDR,4) == 0) + { + if (length == 16) + { + jng_width=(png_uint_32)mng_get_long(p); + jng_height=(png_uint_32)mng_get_long(&p[4]); + if ((jng_width == 0) || (jng_height == 0)) + { + DestroyJNG(chunk,&color_image,&color_image_info, + &alpha_image,&alpha_image_info); + ThrowReaderException(CorruptImageError, + ""NegativeOrZeroImageSize""); + } + jng_color_type=p[8]; + jng_image_sample_depth=p[9]; + jng_image_compression_method=p[10]; + jng_image_interlace_method=p[11]; + + image->interlace=jng_image_interlace_method != 0 ? PNGInterlace : + NoInterlace; + + jng_alpha_sample_depth=p[12]; + jng_alpha_compression_method=p[13]; + jng_alpha_filter_method=p[14]; + jng_alpha_interlace_method=p[15]; + + if (logging != MagickFalse) + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" jng_width: %16lu, jng_height: %16lu\n"" + "" jng_color_type: %16d, jng_image_sample_depth: %3d\n"" + "" jng_image_compression_method:%3d"", + (unsigned long) jng_width, (unsigned long) jng_height, + jng_color_type, jng_image_sample_depth, + jng_image_compression_method); + + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" jng_image_interlace_method: %3d"" + "" jng_alpha_sample_depth: %3d"", + jng_image_interlace_method, + jng_alpha_sample_depth); + + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" jng_alpha_compression_method:%3d\n"" + "" jng_alpha_filter_method: %3d\n"" + "" jng_alpha_interlace_method: %3d"", + jng_alpha_compression_method, + jng_alpha_filter_method, + jng_alpha_interlace_method); + } + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + if (jng_width > 65535 || jng_height > 65535 || + (long) jng_width > GetMagickResourceLimit(WidthResource) || + (long) jng_height > GetMagickResourceLimit(HeightResource)) + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" JNG width or height too large: (%lu x %lu)"", + (long) jng_width, (long) jng_height); + DestroyJNG(chunk,&color_image,&color_image_info, + &alpha_image,&alpha_image_info); + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + } + + continue; + } + + + if ((reading_idat == MagickFalse) && (read_JSEP == MagickFalse) && + ((memcmp(type,mng_JDAT,4) == 0) || (memcmp(type,mng_JdAA,4) == 0) || + (memcmp(type,mng_IDAT,4) == 0) || (memcmp(type,mng_JDAA,4) == 0))) + { + /* + o create color_image + o open color_blob, attached to color_image + o if (color type has alpha) + open alpha_blob, attached to alpha_image + */ + + color_image_info=(ImageInfo *)AcquireMagickMemory(sizeof(ImageInfo)); + + if (color_image_info == (ImageInfo *) NULL) + { + DestroyJNG(chunk,&color_image,&color_image_info, + &alpha_image,&alpha_image_info); + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + } + + GetImageInfo(color_image_info); + color_image=AcquireImage(color_image_info,exception); + + if (color_image == (Image *) NULL) + { + DestroyJNG(chunk,&color_image,&color_image_info, + &alpha_image,&alpha_image_info); + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + } + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Creating color_blob.""); + + (void) AcquireUniqueFilename(color_image->filename); + status=OpenBlob(color_image_info,color_image,WriteBinaryBlobMode, + exception); + + if (status == MagickFalse) + { + DestroyJNG(chunk,&color_image,&color_image_info, + &alpha_image,&alpha_image_info); + return(DestroyImageList(image)); + } + + if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) + { + alpha_image_info=(ImageInfo *) + AcquireMagickMemory(sizeof(ImageInfo)); + + if (alpha_image_info == (ImageInfo *) NULL) + { + DestroyJNG(chunk,&color_image,&color_image_info, + &alpha_image,&alpha_image_info); + ThrowReaderException(ResourceLimitError, + ""MemoryAllocationFailed""); + } + + GetImageInfo(alpha_image_info); + alpha_image=AcquireImage(alpha_image_info,exception); + + if (alpha_image == (Image *) NULL) + { + DestroyJNG(chunk,&color_image,&color_image_info, + &alpha_image,&alpha_image_info); + ThrowReaderException(ResourceLimitError, + ""MemoryAllocationFailed""); + } + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Creating alpha_blob.""); + + (void) AcquireUniqueFilename(alpha_image->filename); + status=OpenBlob(alpha_image_info,alpha_image,WriteBinaryBlobMode, + exception); + + if (status == MagickFalse) + { + DestroyJNG(chunk,&color_image,&color_image_info, + &alpha_image,&alpha_image_info); + return(DestroyImageList(image)); + } + + if (jng_alpha_compression_method == 0) + { + unsigned char + data[18]; + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Writing IHDR chunk to alpha_blob.""); + + (void) WriteBlob(alpha_image,8,(const unsigned char *) + ""\211PNG\r\n\032\n""); + + (void) WriteBlobMSBULong(alpha_image,13L); + PNGType(data,mng_IHDR); + LogPNGChunk(logging,mng_IHDR,13L); + PNGLong(data+4,jng_width); + PNGLong(data+8,jng_height); + data[12]=jng_alpha_sample_depth; + data[13]=0; /* color_type gray */ + data[14]=0; /* compression method 0 */ + data[15]=0; /* filter_method 0 */ + data[16]=0; /* interlace_method 0 */ + (void) WriteBlob(alpha_image,17,data); + (void) WriteBlobMSBULong(alpha_image,crc32(0,data,17)); + } + } + reading_idat=MagickTrue; + } + + if (memcmp(type,mng_JDAT,4) == 0) + { + /* Copy chunk to color_image->blob */ + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Copying JDAT chunk data to color_blob.""); + + if ((length != 0) && (color_image != (Image *) NULL)) + (void) WriteBlob(color_image,length,chunk); + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + continue; + } + + if (memcmp(type,mng_IDAT,4) == 0) + { + png_byte + data[5]; + + /* Copy IDAT header and chunk data to alpha_image->blob */ + + if (alpha_image != NULL && image_info->ping == MagickFalse) + { + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Copying IDAT chunk data to alpha_blob.""); + + (void) WriteBlobMSBULong(alpha_image,(size_t) length); + PNGType(data,mng_IDAT); + LogPNGChunk(logging,mng_IDAT,length); + (void) WriteBlob(alpha_image,4,data); + (void) WriteBlob(alpha_image,length,chunk); + (void) WriteBlobMSBULong(alpha_image, + crc32(crc32(0,data,4),chunk,(uInt) length)); + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + continue; + } + + if ((memcmp(type,mng_JDAA,4) == 0) || (memcmp(type,mng_JdAA,4) == 0)) + { + /* Copy chunk data to alpha_image->blob */ + + if ((alpha_image != NULL) && (image_info->ping == MagickFalse) && + (length != 0)) + { + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Copying JDAA chunk data to alpha_blob.""); + + (void) WriteBlob(alpha_image,length,chunk); + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + continue; + } + + if (memcmp(type,mng_JSEP,4) == 0) + { + read_JSEP=MagickTrue; + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + continue; + } + + if (memcmp(type,mng_bKGD,4) == 0) + { + if (length == 2) + { + image->background_color.red=ScaleCharToQuantum(p[1]); + image->background_color.green=image->background_color.red; + image->background_color.blue=image->background_color.red; + } + + if (length == 6) + { + image->background_color.red=ScaleCharToQuantum(p[1]); + image->background_color.green=ScaleCharToQuantum(p[3]); + image->background_color.blue=ScaleCharToQuantum(p[5]); + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + continue; + } + + if (memcmp(type,mng_gAMA,4) == 0) + { + if (length == 4) + image->gamma=((float) mng_get_long(p))*0.00001; + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + continue; + } + + if (memcmp(type,mng_cHRM,4) == 0) + { + if (length == 32) + { + image->chromaticity.white_point.x=0.00001*mng_get_long(p); + image->chromaticity.white_point.y=0.00001*mng_get_long(&p[4]); + image->chromaticity.red_primary.x=0.00001*mng_get_long(&p[8]); + image->chromaticity.red_primary.y=0.00001*mng_get_long(&p[12]); + image->chromaticity.green_primary.x=0.00001*mng_get_long(&p[16]); + image->chromaticity.green_primary.y=0.00001*mng_get_long(&p[20]); + image->chromaticity.blue_primary.x=0.00001*mng_get_long(&p[24]); + image->chromaticity.blue_primary.y=0.00001*mng_get_long(&p[28]); + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + continue; + } + + if (memcmp(type,mng_sRGB,4) == 0) + { + if (length == 1) + { + image->rendering_intent= + Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); + image->gamma=1.000f/2.200f; + image->chromaticity.red_primary.x=0.6400f; + image->chromaticity.red_primary.y=0.3300f; + image->chromaticity.green_primary.x=0.3000f; + image->chromaticity.green_primary.y=0.6000f; + image->chromaticity.blue_primary.x=0.1500f; + image->chromaticity.blue_primary.y=0.0600f; + image->chromaticity.white_point.x=0.3127f; + image->chromaticity.white_point.y=0.3290f; + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + continue; + } + + if (memcmp(type,mng_oFFs,4) == 0) + { + if (length > 8) + { + image->page.x=(ssize_t) mng_get_long(p); + image->page.y=(ssize_t) mng_get_long(&p[4]); + + if ((int) p[8] != 0) + { + image->page.x/=10000; + image->page.y/=10000; + } + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + continue; + } + + if (memcmp(type,mng_pHYs,4) == 0) + { + if (length > 8) + { + image->resolution.x=(double) mng_get_long(p); + image->resolution.y=(double) mng_get_long(&p[4]); + if ((int) p[8] == PNG_RESOLUTION_METER) + { + image->units=PixelsPerCentimeterResolution; + image->resolution.x=image->resolution.x/100.0f; + image->resolution.y=image->resolution.y/100.0f; + } + } + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + continue; + } + +#if 0 + if (memcmp(type,mng_iCCP,4) == 0) + { + /* To do: */ + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + continue; + } +#endif + + chunk=(unsigned char *) RelinquishMagickMemory(chunk); + + if (memcmp(type,mng_IEND,4)) + continue; + + break; + } + + + /* IEND found */ + + /* + Finish up reading image data: + + o read main image from color_blob. + + o close color_blob. + + o if (color_type has alpha) + if alpha_encoding is PNG + read secondary image from alpha_blob via ReadPNG + if alpha_encoding is JPEG + read secondary image from alpha_blob via ReadJPEG + + o close alpha_blob. + + o copy intensity of secondary image into + alpha samples of main image. + + o destroy the secondary image. + */ + + if (color_image_info == (ImageInfo *) NULL) + { + assert(color_image == (Image *) NULL); + assert(alpha_image == (Image *) NULL); + if (color_image != (Image *) NULL) + color_image=DestroyImageList(color_image); + return(DestroyImageList(image)); + } + + if (color_image == (Image *) NULL) + { + assert(alpha_image == (Image *) NULL); + ThrowReaderException(CorruptImageError,""InsufficientImageDataInFile""); + } + + (void) SeekBlob(color_image,0,SEEK_SET); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Reading jng_image from color_blob.""); + + assert(color_image_info != (ImageInfo *) NULL); + (void) FormatLocaleString(color_image_info->filename,MagickPathExtent, + ""jpeg:%s"",color_image->filename); + + color_image_info->ping=MagickFalse; /* To do: avoid this */ + jng_image=ReadImage(color_image_info,exception); + + (void) RelinquishUniqueFileResource(color_image->filename); + color_image=DestroyImage(color_image); + color_image_info=DestroyImageInfo(color_image_info); + + if (jng_image == (Image *) NULL) + { + DestroyJNG(NULL,NULL,NULL,&alpha_image,&alpha_image_info); + return(DestroyImageList(image)); + } + + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Copying jng_image pixels to main image.""); + + image->rows=jng_height; + image->columns=jng_width; + + status=SetImageExtent(image,image->columns,image->rows,exception); + if (status == MagickFalse) + { + DestroyJNG(NULL,&color_image,&color_image_info,&alpha_image, + &alpha_image_info); + jng_image=DestroyImageList(jng_image); + return(DestroyImageList(image)); + } + if ((image->columns != jng_image->columns) || + (image->rows != jng_image->rows)) + { + DestroyJNG(NULL,&color_image,&color_image_info,&alpha_image, + &alpha_image_info); + jng_image=DestroyImageList(jng_image); + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + } + for (y=0; y < (ssize_t) image->rows; y++) + { + s=GetVirtualPixels(jng_image,0,y,image->columns,1,exception); + q=GetAuthenticPixels(image,0,y,image->columns,1,exception); + if ((s == (const Quantum *) NULL) || (q == (Quantum *) NULL)) + break; + for (x=(ssize_t) image->columns; x != 0; x--) + { + SetPixelRed(image,GetPixelRed(jng_image,s),q); + SetPixelGreen(image,GetPixelGreen(jng_image,s),q); + SetPixelBlue(image,GetPixelBlue(jng_image,s),q); + q+=GetPixelChannels(image); + s+=GetPixelChannels(jng_image); + } + + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + } + + jng_image=DestroyImage(jng_image); + + if ((image_info->ping == MagickFalse) && (jng_color_type >= 12)) + { + if (jng_alpha_compression_method == 0) + { + png_byte + data[5]; + (void) WriteBlobMSBULong(alpha_image,0x00000000L); + PNGType(data,mng_IEND); + LogPNGChunk(logging,mng_IEND,0L); + (void) WriteBlob(alpha_image,4,data); + (void) WriteBlobMSBULong(alpha_image,crc32(0,data,4)); + } + + (void) CloseBlob(alpha_image); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Reading alpha from alpha_blob.""); + + (void) FormatLocaleString(alpha_image_info->filename,MagickPathExtent, + ""%s"",alpha_image->filename); + + jng_image=ReadImage(alpha_image_info,exception); + + if (jng_image != (Image *) NULL) + for (y=0; y < (ssize_t) image->rows; y++) + { + s=GetVirtualPixels(jng_image,0,y,image->columns,1,exception); + q=GetAuthenticPixels(image,0,y,image->columns,1,exception); + if ((s == (const Quantum *) NULL) || (q == (Quantum *) NULL)) + break; + + if (image->alpha_trait != UndefinedPixelTrait) + for (x=(ssize_t) image->columns; x != 0; x--) + { + SetPixelAlpha(image,GetPixelRed(jng_image,s),q); + q+=GetPixelChannels(image); + s+=GetPixelChannels(jng_image); + } + + else + for (x=(ssize_t) image->columns; x != 0; x--) + { + SetPixelAlpha(image,GetPixelRed(jng_image,s),q); + if (GetPixelAlpha(image,q) != OpaqueAlpha) + image->alpha_trait=BlendPixelTrait; + q+=GetPixelChannels(image); + s+=GetPixelChannels(jng_image); + } + + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + } + (void) RelinquishUniqueFileResource(alpha_image->filename); + alpha_image=DestroyImage(alpha_image); + alpha_image_info=DestroyImageInfo(alpha_image_info); + if (jng_image != (Image *) NULL) + jng_image=DestroyImage(jng_image); + } + + /* Read the JNG image. */ + + if (mng_info->mng_type == 0) + { + mng_info->mng_width=jng_width; + mng_info->mng_height=jng_height; + } + + if (image->page.width == 0 && image->page.height == 0) + { + image->page.width=jng_width; + image->page.height=jng_height; + } + + if (image->page.x == 0 && image->page.y == 0) + { + image->page.x=mng_info->x_off[mng_info->object_id]; + image->page.y=mng_info->y_off[mng_info->object_id]; + } + + else + { + image->page.y=mng_info->y_off[mng_info->object_id]; + } + + mng_info->image_found++; + status=SetImageProgress(image,LoadImagesTag,2*TellBlob(image), + 2*GetBlobSize(image)); + + if (status == MagickFalse) + return(DestroyImageList(image)); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" exit ReadOneJNGImage()""); + + return(image); +} +","@@ -4560,7 +4560,11 @@ static Image *ReadOneJNGImage(MngInfo *mng_info, + chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); + + if (chunk == (unsigned char *) NULL) +- ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); ++ { ++ DestroyJNG(NULL,&color_image,&color_image_info, ++ &alpha_image,&alpha_image_info); ++ ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); ++ } + + for (i=0; i < (ssize_t) length; i++) + { +@@ -4587,13 +4591,12 @@ static Image *ReadOneJNGImage(MngInfo *mng_info, + jng_width=(png_uint_32)mng_get_long(p); + jng_height=(png_uint_32)mng_get_long(&p[4]); + if ((jng_width == 0) || (jng_height == 0)) +- { +- DestroyJNG(chunk,&color_image,&color_image_info, +- &alpha_image,&alpha_image_info); +- +- ThrowReaderException(CorruptImageError, +- ""NegativeOrZeroImageSize""); +- } ++ { ++ DestroyJNG(chunk,&color_image,&color_image_info, ++ &alpha_image,&alpha_image_info); ++ ThrowReaderException(CorruptImageError, ++ ""NegativeOrZeroImageSize""); ++ } + jng_color_type=p[8]; + jng_image_sample_depth=p[9]; + jng_image_compression_method=p[10];",5785,6116,6144 +7732,"static CURLcode create_conn(struct Curl_easy *data, + struct connectdata **in_connect, + bool *async) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn; + struct connectdata *conn_temp = NULL; + bool reuse; + bool connections_available = TRUE; + bool force_reuse = FALSE; + bool waitpipe = FALSE; + size_t max_host_connections = Curl_multi_max_host_connections(data->multi); + size_t max_total_connections = Curl_multi_max_total_connections(data->multi); + + *async = FALSE; + + /************************************************************* + * Check input data + *************************************************************/ + if(!data->change.url) { + result = CURLE_URL_MALFORMAT; + goto out; + } + + /* First, split up the current URL in parts so that we can use the + parts for checking against the already present connections. In order + to not have to modify everything at once, we allocate a temporary + connection data struct and fill in for comparison purposes. */ + conn = allocate_conn(data); + + if(!conn) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + /* We must set the return variable as soon as possible, so that our + parent can cleanup any possible allocs we may have done before + any failure */ + *in_connect = conn; + + result = parseurlandfillconn(data, conn); + if(result) + goto out; + + if(data->set.str[STRING_BEARER]) { + conn->oauth_bearer = strdup(data->set.str[STRING_BEARER]); + if(!conn->oauth_bearer) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + +#ifdef USE_UNIX_SOCKETS + if(data->set.str[STRING_UNIX_SOCKET_PATH]) { + conn->unix_domain_socket = strdup(data->set.str[STRING_UNIX_SOCKET_PATH]); + if(conn->unix_domain_socket == NULL) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + conn->abstract_unix_socket = data->set.abstract_unix_socket; + } +#endif + + /* After the unix socket init but before the proxy vars are used, parse and + initialize the proxy vars */ +#ifndef CURL_DISABLE_PROXY + result = create_conn_helper_init_proxy(conn); + if(result) + goto out; +#endif + + /************************************************************* + * If the protocol is using SSL and HTTP proxy is used, we set + * the tunnel_proxy bit. + *************************************************************/ + if((conn->given->flags&PROTOPT_SSL) && conn->bits.httpproxy) + conn->bits.tunnel_proxy = TRUE; + + /************************************************************* + * Figure out the remote port number and fix it in the URL + *************************************************************/ + result = parse_remote_port(data, conn); + if(result) + goto out; + + /* Check for overridden login details and set them accordingly so they + they are known when protocol->setup_connection is called! */ + result = override_login(data, conn, &conn->user, &conn->passwd, + &conn->options); + if(result) + goto out; + + result = set_login(conn); /* default credentials */ + if(result) + goto out; + + /************************************************************* + * Process the ""connect to"" linked list of hostname/port mappings. + * Do this after the remote port number has been fixed in the URL. + *************************************************************/ + result = parse_connect_to_slist(data, conn, data->set.connect_to); + if(result) + goto out; + + /************************************************************* + * IDN-fix the hostnames + *************************************************************/ + result = fix_hostname(conn, &conn->host); + if(result) + goto out; + if(conn->bits.conn_to_host) { + result = fix_hostname(conn, &conn->conn_to_host); + if(result) + goto out; + } + if(conn->bits.httpproxy) { + result = fix_hostname(conn, &conn->http_proxy.host); + if(result) + goto out; + } + if(conn->bits.socksproxy) { + result = fix_hostname(conn, &conn->socks_proxy.host); + if(result) + goto out; + } + + /************************************************************* + * Check whether the host and the ""connect to host"" are equal. + * Do this after the hostnames have been IDN-fixed. + *************************************************************/ + if(conn->bits.conn_to_host && + strcasecompare(conn->conn_to_host.name, conn->host.name)) { + conn->bits.conn_to_host = FALSE; + } + + /************************************************************* + * Check whether the port and the ""connect to port"" are equal. + * Do this after the remote port number has been fixed in the URL. + *************************************************************/ + if(conn->bits.conn_to_port && conn->conn_to_port == conn->remote_port) { + conn->bits.conn_to_port = FALSE; + } + + /************************************************************* + * If the ""connect to"" feature is used with an HTTP proxy, + * we set the tunnel_proxy bit. + *************************************************************/ + if((conn->bits.conn_to_host || conn->bits.conn_to_port) && + conn->bits.httpproxy) + conn->bits.tunnel_proxy = TRUE; + + /************************************************************* + * Setup internals depending on protocol. Needs to be done after + * we figured out what/if proxy to use. + *************************************************************/ + result = setup_connection_internals(conn); + if(result) + goto out; + + conn->recv[FIRSTSOCKET] = Curl_recv_plain; + conn->send[FIRSTSOCKET] = Curl_send_plain; + conn->recv[SECONDARYSOCKET] = Curl_recv_plain; + conn->send[SECONDARYSOCKET] = Curl_send_plain; + + conn->bits.tcp_fastopen = data->set.tcp_fastopen; + + /*********************************************************************** + * file: is a special case in that it doesn't need a network connection + ***********************************************************************/ +#ifndef CURL_DISABLE_FILE + if(conn->handler->flags & PROTOPT_NONETWORK) { + bool done; + /* this is supposed to be the connect function so we better at least check + that the file is present here! */ + DEBUGASSERT(conn->handler->connect_it); + Curl_persistconninfo(conn); + result = conn->handler->connect_it(conn, &done); + + /* Setup a ""faked"" transfer that'll do nothing */ + if(!result) { + conn->data = data; + conn->bits.tcpconnect[FIRSTSOCKET] = TRUE; /* we are ""connected */ + + result = Curl_conncache_add_conn(data->state.conn_cache, conn); + if(result) + goto out; + + /* + * Setup whatever necessary for a resumed transfer + */ + result = setup_range(data); + if(result) { + DEBUGASSERT(conn->handler->done); + /* we ignore the return code for the protocol-specific DONE */ + (void)conn->handler->done(conn, result, FALSE); + goto out; + } + + Curl_setup_transfer(conn, -1, -1, FALSE, NULL, /* no download */ + -1, NULL); /* no upload */ + } + + /* since we skip do_init() */ + Curl_init_do(data, conn); + + goto out; + } +#endif + + /* Get a cloned copy of the SSL config situation stored in the + connection struct. But to get this going nicely, we must first make + sure that the strings in the master copy are pointing to the correct + strings in the session handle strings array! + + Keep in mind that the pointers in the master copy are pointing to strings + that will be freed as part of the Curl_easy struct, but all cloned + copies will be separately allocated. + */ + data->set.ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH_ORIG]; + data->set.proxy_ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH_PROXY]; + data->set.ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE_ORIG]; + data->set.proxy_ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE_PROXY]; + data->set.ssl.primary.random_file = data->set.str[STRING_SSL_RANDOM_FILE]; + data->set.proxy_ssl.primary.random_file = + data->set.str[STRING_SSL_RANDOM_FILE]; + data->set.ssl.primary.egdsocket = data->set.str[STRING_SSL_EGDSOCKET]; + data->set.proxy_ssl.primary.egdsocket = data->set.str[STRING_SSL_EGDSOCKET]; + data->set.ssl.primary.cipher_list = + data->set.str[STRING_SSL_CIPHER_LIST_ORIG]; + data->set.proxy_ssl.primary.cipher_list = + data->set.str[STRING_SSL_CIPHER_LIST_PROXY]; + data->set.ssl.primary.cipher_list13 = + data->set.str[STRING_SSL_CIPHER13_LIST_ORIG]; + data->set.proxy_ssl.primary.cipher_list13 = + data->set.str[STRING_SSL_CIPHER13_LIST_PROXY]; + + data->set.ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE_ORIG]; + data->set.proxy_ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE_PROXY]; + data->set.ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT_ORIG]; + data->set.proxy_ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT_PROXY]; + data->set.ssl.cert = data->set.str[STRING_CERT_ORIG]; + data->set.proxy_ssl.cert = data->set.str[STRING_CERT_PROXY]; + data->set.ssl.cert_type = data->set.str[STRING_CERT_TYPE_ORIG]; + data->set.proxy_ssl.cert_type = data->set.str[STRING_CERT_TYPE_PROXY]; + data->set.ssl.key = data->set.str[STRING_KEY_ORIG]; + data->set.proxy_ssl.key = data->set.str[STRING_KEY_PROXY]; + data->set.ssl.key_type = data->set.str[STRING_KEY_TYPE_ORIG]; + data->set.proxy_ssl.key_type = data->set.str[STRING_KEY_TYPE_PROXY]; + data->set.ssl.key_passwd = data->set.str[STRING_KEY_PASSWD_ORIG]; + data->set.proxy_ssl.key_passwd = data->set.str[STRING_KEY_PASSWD_PROXY]; + data->set.ssl.primary.clientcert = data->set.str[STRING_CERT_ORIG]; + data->set.proxy_ssl.primary.clientcert = data->set.str[STRING_CERT_PROXY]; +#ifdef USE_TLS_SRP + data->set.ssl.username = data->set.str[STRING_TLSAUTH_USERNAME_ORIG]; + data->set.proxy_ssl.username = data->set.str[STRING_TLSAUTH_USERNAME_PROXY]; + data->set.ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD_ORIG]; + data->set.proxy_ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD_PROXY]; +#endif + + if(!Curl_clone_primary_ssl_config(&data->set.ssl.primary, + &conn->ssl_config)) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + if(!Curl_clone_primary_ssl_config(&data->set.proxy_ssl.primary, + &conn->proxy_ssl_config)) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + prune_dead_connections(data); + + /************************************************************* + * Check the current list of connections to see if we can + * re-use an already existing one or if we have to create a + * new one. + *************************************************************/ + + DEBUGASSERT(conn->user); + DEBUGASSERT(conn->passwd); + + /* reuse_fresh is TRUE if we are told to use a new connection by force, but + we only acknowledge this option if this is not a re-used connection + already (which happens due to follow-location or during a HTTP + authentication phase). */ + if(data->set.reuse_fresh && !data->state.this_is_a_follow) + reuse = FALSE; + else + reuse = ConnectionExists(data, conn, &conn_temp, &force_reuse, &waitpipe); + + /* If we found a reusable connection that is now marked as in use, we may + still want to open a new connection if we are pipelining. */ + if(reuse && !force_reuse && IsPipeliningPossible(data, conn_temp)) { + size_t pipelen = conn_temp->send_pipe.size + conn_temp->recv_pipe.size; + if(pipelen > 0) { + infof(data, ""Found connection %ld, with requests in the pipe (%zu)\n"", + conn_temp->connection_id, pipelen); + + if(Curl_conncache_bundle_size(conn_temp) < max_host_connections && + Curl_conncache_size(data) < max_total_connections) { + /* We want a new connection anyway */ + reuse = FALSE; + + infof(data, ""We can reuse, but we want a new connection anyway\n""); + Curl_conncache_return_conn(conn_temp); + } + } + } + + if(reuse) { + /* + * We already have a connection for this, we got the former connection + * in the conn_temp variable and thus we need to cleanup the one we + * just allocated before we can move along and use the previously + * existing one. + */ + reuse_conn(conn, conn_temp); +#ifdef USE_SSL + free(conn->ssl_extra); +#endif + free(conn); /* we don't need this anymore */ + conn = conn_temp; + *in_connect = conn; + + infof(data, ""Re-using existing connection! (#%ld) with %s %s\n"", + conn->connection_id, + conn->bits.proxy?""proxy"":""host"", + conn->socks_proxy.host.name ? conn->socks_proxy.host.dispname : + conn->http_proxy.host.name ? conn->http_proxy.host.dispname : + conn->host.dispname); + } + else { + /* We have decided that we want a new connection. However, we may not + be able to do that if we have reached the limit of how many + connections we are allowed to open. */ + + if(conn->handler->flags & PROTOPT_ALPN_NPN) { + /* The protocol wants it, so set the bits if enabled in the easy handle + (default) */ + if(data->set.ssl_enable_alpn) + conn->bits.tls_enable_alpn = TRUE; + if(data->set.ssl_enable_npn) + conn->bits.tls_enable_npn = TRUE; + } + + if(waitpipe) + /* There is a connection that *might* become usable for pipelining + ""soon"", and we wait for that */ + connections_available = FALSE; + else { + /* this gets a lock on the conncache */ + struct connectbundle *bundle = + Curl_conncache_find_bundle(conn, data->state.conn_cache); + + if(max_host_connections > 0 && bundle && + (bundle->num_connections >= max_host_connections)) { + struct connectdata *conn_candidate; + + /* The bundle is full. Extract the oldest connection. */ + conn_candidate = Curl_conncache_extract_bundle(data, bundle); + Curl_conncache_unlock(conn); + + if(conn_candidate) + (void)Curl_disconnect(data, conn_candidate, + /* dead_connection */ FALSE); + else { + infof(data, ""No more connections allowed to host: %zu\n"", + max_host_connections); + connections_available = FALSE; + } + } + else + Curl_conncache_unlock(conn); + + } + + if(connections_available && + (max_total_connections > 0) && + (Curl_conncache_size(data) >= max_total_connections)) { + struct connectdata *conn_candidate; + + /* The cache is full. Let's see if we can kill a connection. */ + conn_candidate = Curl_conncache_extract_oldest(data); + if(conn_candidate) + (void)Curl_disconnect(data, conn_candidate, + /* dead_connection */ FALSE); + else { + infof(data, ""No connections available in cache\n""); + connections_available = FALSE; + } + } + + if(!connections_available) { + infof(data, ""No connections available.\n""); + + conn_free(conn); + *in_connect = NULL; + + result = CURLE_NO_CONNECTION_AVAILABLE; + goto out; + } + else { + /* + * This is a brand new connection, so let's store it in the connection + * cache of ours! + */ + result = Curl_conncache_add_conn(data->state.conn_cache, conn); + if(result) + goto out; + } + +#if defined(USE_NTLM) + /* If NTLM is requested in a part of this connection, make sure we don't + assume the state is fine as this is a fresh connection and NTLM is + connection based. */ + if((data->state.authhost.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) && + data->state.authhost.done) { + infof(data, ""NTLM picked AND auth done set, clear picked!\n""); + data->state.authhost.picked = CURLAUTH_NONE; + data->state.authhost.done = FALSE; + } + + if((data->state.authproxy.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) && + data->state.authproxy.done) { + infof(data, ""NTLM-proxy picked AND auth done set, clear picked!\n""); + data->state.authproxy.picked = CURLAUTH_NONE; + data->state.authproxy.done = FALSE; + } +#endif + } + + /* Setup and init stuff before DO starts, in preparing for the transfer. */ + Curl_init_do(data, conn); + + /* + * Setup whatever necessary for a resumed transfer + */ + result = setup_range(data); + if(result) + goto out; + + /* Continue connectdata initialization here. */ + + /* + * Inherit the proper values from the urldata struct AFTER we have arranged + * the persistent connection stuff + */ + conn->seek_func = data->set.seek_func; + conn->seek_client = data->set.seek_client; + + /************************************************************* + * Resolve the address of the server or proxy + *************************************************************/ + result = resolve_server(data, conn, async); + +out: + return result; +} +",0,"static CURLcode create_conn(struct Curl_easy *data, + struct connectdata **in_connect, + bool *async) +{ + CURLcode result = CURLE_OK; + struct connectdata *conn; + struct connectdata *conn_temp = NULL; + bool reuse; + bool connections_available = TRUE; + bool force_reuse = FALSE; + bool waitpipe = FALSE; + size_t max_host_connections = Curl_multi_max_host_connections(data->multi); + size_t max_total_connections = Curl_multi_max_total_connections(data->multi); + + *async = FALSE; + + /************************************************************* + * Check input data + *************************************************************/ + if(!data->change.url) { + result = CURLE_URL_MALFORMAT; + goto out; + } + + /* First, split up the current URL in parts so that we can use the + parts for checking against the already present connections. In order + to not have to modify everything at once, we allocate a temporary + connection data struct and fill in for comparison purposes. */ + conn = allocate_conn(data); + + if(!conn) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + /* We must set the return variable as soon as possible, so that our + parent can cleanup any possible allocs we may have done before + any failure */ + *in_connect = conn; + + result = parseurlandfillconn(data, conn); + if(result) + goto out; + + if(data->set.str[STRING_BEARER]) { + conn->oauth_bearer = strdup(data->set.str[STRING_BEARER]); + if(!conn->oauth_bearer) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + } + +#ifdef USE_UNIX_SOCKETS + if(data->set.str[STRING_UNIX_SOCKET_PATH]) { + conn->unix_domain_socket = strdup(data->set.str[STRING_UNIX_SOCKET_PATH]); + if(conn->unix_domain_socket == NULL) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + conn->abstract_unix_socket = data->set.abstract_unix_socket; + } +#endif + + /* After the unix socket init but before the proxy vars are used, parse and + initialize the proxy vars */ +#ifndef CURL_DISABLE_PROXY + result = create_conn_helper_init_proxy(conn); + if(result) + goto out; +#endif + + /************************************************************* + * If the protocol is using SSL and HTTP proxy is used, we set + * the tunnel_proxy bit. + *************************************************************/ + if((conn->given->flags&PROTOPT_SSL) && conn->bits.httpproxy) + conn->bits.tunnel_proxy = TRUE; + + /************************************************************* + * Figure out the remote port number and fix it in the URL + *************************************************************/ + result = parse_remote_port(data, conn); + if(result) + goto out; + + /* Check for overridden login details and set them accordingly so they + they are known when protocol->setup_connection is called! */ + result = override_login(data, conn, &conn->user, &conn->passwd, + &conn->options); + if(result) + goto out; + + result = set_login(conn); /* default credentials */ + if(result) + goto out; + + /************************************************************* + * Process the ""connect to"" linked list of hostname/port mappings. + * Do this after the remote port number has been fixed in the URL. + *************************************************************/ + result = parse_connect_to_slist(data, conn, data->set.connect_to); + if(result) + goto out; + + /************************************************************* + * IDN-fix the hostnames + *************************************************************/ + result = fix_hostname(conn, &conn->host); + if(result) + goto out; + if(conn->bits.conn_to_host) { + result = fix_hostname(conn, &conn->conn_to_host); + if(result) + goto out; + } + if(conn->bits.httpproxy) { + result = fix_hostname(conn, &conn->http_proxy.host); + if(result) + goto out; + } + if(conn->bits.socksproxy) { + result = fix_hostname(conn, &conn->socks_proxy.host); + if(result) + goto out; + } + + /************************************************************* + * Check whether the host and the ""connect to host"" are equal. + * Do this after the hostnames have been IDN-fixed. + *************************************************************/ + if(conn->bits.conn_to_host && + strcasecompare(conn->conn_to_host.name, conn->host.name)) { + conn->bits.conn_to_host = FALSE; + } + + /************************************************************* + * Check whether the port and the ""connect to port"" are equal. + * Do this after the remote port number has been fixed in the URL. + *************************************************************/ + if(conn->bits.conn_to_port && conn->conn_to_port == conn->remote_port) { + conn->bits.conn_to_port = FALSE; + } + + /************************************************************* + * If the ""connect to"" feature is used with an HTTP proxy, + * we set the tunnel_proxy bit. + *************************************************************/ + if((conn->bits.conn_to_host || conn->bits.conn_to_port) && + conn->bits.httpproxy) + conn->bits.tunnel_proxy = TRUE; + + /************************************************************* + * Setup internals depending on protocol. Needs to be done after + * we figured out what/if proxy to use. + *************************************************************/ + result = setup_connection_internals(conn); + if(result) + goto out; + + conn->recv[FIRSTSOCKET] = Curl_recv_plain; + conn->send[FIRSTSOCKET] = Curl_send_plain; + conn->recv[SECONDARYSOCKET] = Curl_recv_plain; + conn->send[SECONDARYSOCKET] = Curl_send_plain; + + conn->bits.tcp_fastopen = data->set.tcp_fastopen; + + /*********************************************************************** + * file: is a special case in that it doesn't need a network connection + ***********************************************************************/ +#ifndef CURL_DISABLE_FILE + if(conn->handler->flags & PROTOPT_NONETWORK) { + bool done; + /* this is supposed to be the connect function so we better at least check + that the file is present here! */ + DEBUGASSERT(conn->handler->connect_it); + Curl_persistconninfo(conn); + result = conn->handler->connect_it(conn, &done); + + /* Setup a ""faked"" transfer that'll do nothing */ + if(!result) { + conn->data = data; + conn->bits.tcpconnect[FIRSTSOCKET] = TRUE; /* we are ""connected */ + + result = Curl_conncache_add_conn(data->state.conn_cache, conn); + if(result) + goto out; + + /* + * Setup whatever necessary for a resumed transfer + */ + result = setup_range(data); + if(result) { + DEBUGASSERT(conn->handler->done); + /* we ignore the return code for the protocol-specific DONE */ + (void)conn->handler->done(conn, result, FALSE); + goto out; + } + + Curl_setup_transfer(conn, -1, -1, FALSE, NULL, /* no download */ + -1, NULL); /* no upload */ + } + + /* since we skip do_init() */ + Curl_init_do(data, conn); + + goto out; + } +#endif + + /* Get a cloned copy of the SSL config situation stored in the + connection struct. But to get this going nicely, we must first make + sure that the strings in the master copy are pointing to the correct + strings in the session handle strings array! + + Keep in mind that the pointers in the master copy are pointing to strings + that will be freed as part of the Curl_easy struct, but all cloned + copies will be separately allocated. + */ + data->set.ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH_ORIG]; + data->set.proxy_ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH_PROXY]; + data->set.ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE_ORIG]; + data->set.proxy_ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE_PROXY]; + data->set.ssl.primary.random_file = data->set.str[STRING_SSL_RANDOM_FILE]; + data->set.proxy_ssl.primary.random_file = + data->set.str[STRING_SSL_RANDOM_FILE]; + data->set.ssl.primary.egdsocket = data->set.str[STRING_SSL_EGDSOCKET]; + data->set.proxy_ssl.primary.egdsocket = data->set.str[STRING_SSL_EGDSOCKET]; + data->set.ssl.primary.cipher_list = + data->set.str[STRING_SSL_CIPHER_LIST_ORIG]; + data->set.proxy_ssl.primary.cipher_list = + data->set.str[STRING_SSL_CIPHER_LIST_PROXY]; + data->set.ssl.primary.cipher_list13 = + data->set.str[STRING_SSL_CIPHER13_LIST_ORIG]; + data->set.proxy_ssl.primary.cipher_list13 = + data->set.str[STRING_SSL_CIPHER13_LIST_PROXY]; + + data->set.ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE_ORIG]; + data->set.proxy_ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE_PROXY]; + data->set.ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT_ORIG]; + data->set.proxy_ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT_PROXY]; + data->set.ssl.cert = data->set.str[STRING_CERT_ORIG]; + data->set.proxy_ssl.cert = data->set.str[STRING_CERT_PROXY]; + data->set.ssl.cert_type = data->set.str[STRING_CERT_TYPE_ORIG]; + data->set.proxy_ssl.cert_type = data->set.str[STRING_CERT_TYPE_PROXY]; + data->set.ssl.key = data->set.str[STRING_KEY_ORIG]; + data->set.proxy_ssl.key = data->set.str[STRING_KEY_PROXY]; + data->set.ssl.key_type = data->set.str[STRING_KEY_TYPE_ORIG]; + data->set.proxy_ssl.key_type = data->set.str[STRING_KEY_TYPE_PROXY]; + data->set.ssl.key_passwd = data->set.str[STRING_KEY_PASSWD_ORIG]; + data->set.proxy_ssl.key_passwd = data->set.str[STRING_KEY_PASSWD_PROXY]; + data->set.ssl.primary.clientcert = data->set.str[STRING_CERT_ORIG]; + data->set.proxy_ssl.primary.clientcert = data->set.str[STRING_CERT_PROXY]; +#ifdef USE_TLS_SRP + data->set.ssl.username = data->set.str[STRING_TLSAUTH_USERNAME_ORIG]; + data->set.proxy_ssl.username = data->set.str[STRING_TLSAUTH_USERNAME_PROXY]; + data->set.ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD_ORIG]; + data->set.proxy_ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD_PROXY]; +#endif + + if(!Curl_clone_primary_ssl_config(&data->set.ssl.primary, + &conn->ssl_config)) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + if(!Curl_clone_primary_ssl_config(&data->set.proxy_ssl.primary, + &conn->proxy_ssl_config)) { + result = CURLE_OUT_OF_MEMORY; + goto out; + } + + prune_dead_connections(data); + + /************************************************************* + * Check the current list of connections to see if we can + * re-use an already existing one or if we have to create a + * new one. + *************************************************************/ + + DEBUGASSERT(conn->user); + DEBUGASSERT(conn->passwd); + + /* reuse_fresh is TRUE if we are told to use a new connection by force, but + we only acknowledge this option if this is not a re-used connection + already (which happens due to follow-location or during a HTTP + authentication phase). */ + if(data->set.reuse_fresh && !data->state.this_is_a_follow) + reuse = FALSE; + else + reuse = ConnectionExists(data, conn, &conn_temp, &force_reuse, &waitpipe); + + /* If we found a reusable connection that is now marked as in use, we may + still want to open a new connection if we are pipelining. */ + if(reuse && !force_reuse && IsPipeliningPossible(data, conn_temp)) { + size_t pipelen = conn_temp->send_pipe.size + conn_temp->recv_pipe.size; + if(pipelen > 0) { + infof(data, ""Found connection %ld, with requests in the pipe (%zu)\n"", + conn_temp->connection_id, pipelen); + + if(Curl_conncache_bundle_size(conn_temp) < max_host_connections && + Curl_conncache_size(data) < max_total_connections) { + /* We want a new connection anyway */ + reuse = FALSE; + + infof(data, ""We can reuse, but we want a new connection anyway\n""); + Curl_conncache_return_conn(conn_temp); + } + } + } + + if(reuse) { + /* + * We already have a connection for this, we got the former connection + * in the conn_temp variable and thus we need to cleanup the one we + * just allocated before we can move along and use the previously + * existing one. + */ + reuse_conn(conn, conn_temp); +#ifdef USE_SSL + free(conn->ssl_extra); +#endif + free(conn); /* we don't need this anymore */ + conn = conn_temp; + *in_connect = conn; + + infof(data, ""Re-using existing connection! (#%ld) with %s %s\n"", + conn->connection_id, + conn->bits.proxy?""proxy"":""host"", + conn->socks_proxy.host.name ? conn->socks_proxy.host.dispname : + conn->http_proxy.host.name ? conn->http_proxy.host.dispname : + conn->host.dispname); + } + else { + /* We have decided that we want a new connection. However, we may not + be able to do that if we have reached the limit of how many + connections we are allowed to open. */ + + if(conn->handler->flags & PROTOPT_ALPN_NPN) { + /* The protocol wants it, so set the bits if enabled in the easy handle + (default) */ + if(data->set.ssl_enable_alpn) + conn->bits.tls_enable_alpn = TRUE; + if(data->set.ssl_enable_npn) + conn->bits.tls_enable_npn = TRUE; + } + + if(waitpipe) + /* There is a connection that *might* become usable for pipelining + ""soon"", and we wait for that */ + connections_available = FALSE; + else { + /* this gets a lock on the conncache */ + struct connectbundle *bundle = + Curl_conncache_find_bundle(conn, data->state.conn_cache); + + if(max_host_connections > 0 && bundle && + (bundle->num_connections >= max_host_connections)) { + struct connectdata *conn_candidate; + + /* The bundle is full. Extract the oldest connection. */ + conn_candidate = Curl_conncache_extract_bundle(data, bundle); + Curl_conncache_unlock(conn); + + if(conn_candidate) + (void)Curl_disconnect(data, conn_candidate, + /* dead_connection */ FALSE); + else { + infof(data, ""No more connections allowed to host: %zu\n"", + max_host_connections); + connections_available = FALSE; + } + } + else + Curl_conncache_unlock(conn); + + } + + if(connections_available && + (max_total_connections > 0) && + (Curl_conncache_size(data) >= max_total_connections)) { + struct connectdata *conn_candidate; + + /* The cache is full. Let's see if we can kill a connection. */ + conn_candidate = Curl_conncache_extract_oldest(data); + if(conn_candidate) + (void)Curl_disconnect(data, conn_candidate, + /* dead_connection */ FALSE); + else { + infof(data, ""No connections available in cache\n""); + connections_available = FALSE; + } + } + + if(!connections_available) { + infof(data, ""No connections available.\n""); + + conn_free(conn); + *in_connect = NULL; + + result = CURLE_NO_CONNECTION_AVAILABLE; + goto out; + } + else { + /* + * This is a brand new connection, so let's store it in the connection + * cache of ours! + */ + result = Curl_conncache_add_conn(data->state.conn_cache, conn); + if(result) + goto out; + } + +#if defined(USE_NTLM) + /* If NTLM is requested in a part of this connection, make sure we don't + assume the state is fine as this is a fresh connection and NTLM is + connection based. */ + if((data->state.authhost.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) && + data->state.authhost.done) { + infof(data, ""NTLM picked AND auth done set, clear picked!\n""); + data->state.authhost.picked = CURLAUTH_NONE; + data->state.authhost.done = FALSE; + } + + if((data->state.authproxy.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) && + data->state.authproxy.done) { + infof(data, ""NTLM-proxy picked AND auth done set, clear picked!\n""); + data->state.authproxy.picked = CURLAUTH_NONE; + data->state.authproxy.done = FALSE; + } +#endif + } + + /* Setup and init stuff before DO starts, in preparing for the transfer. */ + Curl_init_do(data, conn); + + /* + * Setup whatever necessary for a resumed transfer + */ + result = setup_range(data); + if(result) + goto out; + + /* Continue connectdata initialization here. */ + + /* + * Inherit the proper values from the urldata struct AFTER we have arranged + * the persistent connection stuff + */ + conn->seek_func = data->set.seek_func; + conn->seek_client = data->set.seek_client; + + /************************************************************* + * Resolve the address of the server or proxy + *************************************************************/ + result = resolve_server(data, conn, async); + +out: + return result; +} +","@@ -331,10 +331,12 @@ CURLcode Curl_close(struct Curl_easy *data) + and detach this handle from there. */ + curl_multi_remove_handle(data->multi, data); + +- if(data->multi_easy) ++ if(data->multi_easy) { + /* when curl_easy_perform() is used, it creates its own multi handle to + use and this is the one */ + curl_multi_cleanup(data->multi_easy); ++ data->multi_easy = NULL; ++ } + + /* Destroy the timeout list that is held in the easy handle. It is + /normally/ done by curl_multi_remove_handle() but this is ""just in",3883,4214,6144 +18751,"WORD32 ih264d_mark_err_slice_skip(dec_struct_t * ps_dec, + WORD32 num_mb_skip, + UWORD8 u1_is_idr_slice, + UWORD16 u2_frame_num, + pocstruct_t *ps_cur_poc, + WORD32 prev_slice_err) +{ + WORD32 i2_cur_mb_addr; + UWORD32 u1_num_mbs, u1_num_mbsNby2; + UWORD32 u1_mb_idx = ps_dec->u1_mb_idx; + UWORD32 i2_mb_skip_run; + + UWORD32 u1_num_mbs_next, u1_end_of_row; + const UWORD32 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs; + UWORD32 u1_slice_end; + UWORD32 u1_tfr_n_mb; + UWORD32 u1_decode_nmb; + dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm; + dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice; + UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; + UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; + deblk_mb_t *ps_cur_deblk_mb; + dec_mb_info_t *ps_cur_mb_info; + parse_pmbarams_t *ps_parse_mb_data; + UWORD32 u1_inter_mb_type; + UWORD32 u1_deblk_mb_type; + UWORD16 u2_total_mbs_coded; + UWORD32 u1_mbaff = ps_slice->u1_mbaff_frame_flag; + parse_part_params_t *ps_part_info; + WORD32 ret; + + + if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) + { + ih264d_err_pic_dispbuf_mgr(ps_dec); + return 0; + } + ps_dec->ps_dpb_cmds->u1_long_term_reference_flag = 0; + if(prev_slice_err == 1) + { + /* first slice - missing/header corruption */ + ps_dec->ps_cur_slice->u2_frame_num = u2_frame_num; + + + if(!ps_dec->u1_first_slice_in_stream) + { + ih264d_end_of_pic(ps_dec, u1_is_idr_slice, + ps_dec->ps_cur_slice->u2_frame_num); + ps_dec->s_cur_pic_poc.u2_frame_num = + ps_dec->ps_cur_slice->u2_frame_num; + } + + { + WORD32 i, j, poc = 0; + + ps_dec->ps_cur_slice->u2_first_mb_in_slice = 0; + + ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff; + ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp; + ps_dec->p_motion_compensate = ih264d_motion_compensate_bp; + + if(ps_dec->ps_cur_pic != NULL) + poc = ps_dec->ps_cur_pic->i4_poc + 2; + + j = 0; + for(i = 0; i < MAX_NUM_PIC_PARAMS; i++) + if(ps_dec->ps_pps[i].u1_is_valid == TRUE) + j = i; + { + ps_dec->ps_cur_slice->u1_slice_type = P_SLICE; + ps_dec->ps_cur_slice->u1_nal_ref_idc = 1; + ps_dec->ps_cur_slice->u1_nal_unit_type = 1; + ret = ih264d_start_of_pic(ps_dec, poc, ps_cur_poc, + ps_dec->ps_cur_slice->u2_frame_num, + &ps_dec->ps_pps[j]); + + if(ret != OK) + { + return ret; + } + } + + ps_dec->ps_ref_pic_buf_lx[0][0]->u1_pic_buf_id = 0; + + ps_dec->u4_output_present = 0; + + { + ih264d_get_next_display_field(ps_dec, + ps_dec->ps_out_buffer, + &(ps_dec->s_disp_op)); + /* If error code is non-zero then there is no buffer available for display, + hence avoid format conversion */ + + if(0 != ps_dec->s_disp_op.u4_error_code) + { + ps_dec->u4_fmt_conv_cur_row = ps_dec->s_disp_frame_info.u4_y_ht; + } + else + ps_dec->u4_output_present = 1; + } + + if(ps_dec->u1_separate_parse == 1) + { + if(ps_dec->u4_dec_thread_created == 0) + { + ithread_create(ps_dec->pv_dec_thread_handle, NULL, + (void *)ih264d_decode_picture_thread, + (void *)ps_dec); + + ps_dec->u4_dec_thread_created = 1; + } + + if((ps_dec->u4_num_cores == 3) && + ((ps_dec->u4_app_disable_deblk_frm == 0) || ps_dec->i1_recon_in_thread3_flag) + && (ps_dec->u4_bs_deblk_thread_created == 0)) + { + ps_dec->u4_start_recon_deblk = 0; + ithread_create(ps_dec->pv_bs_deblk_thread_handle, NULL, + (void *)ih264d_recon_deblk_thread, + (void *)ps_dec); + ps_dec->u4_bs_deblk_thread_created = 1; + + } + } + } + } + else + { + + dec_slice_struct_t *ps_parse_cur_slice; + ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + ps_dec->u2_cur_slice_num; + + if(ps_dec->u1_slice_header_done + && ps_parse_cur_slice == ps_dec->ps_parse_cur_slice) + { + u1_num_mbs = ps_dec->u4_num_mbs_cur_nmb; + + if(u1_num_mbs) + { + ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs - 1; + } + else + { + if(ps_dec->u1_separate_parse) + { + ps_cur_mb_info = ps_dec->ps_nmb_info - 1; + } + else + { + ps_cur_mb_info = ps_dec->ps_nmb_info + + ps_dec->u4_num_mbs_prev_nmb - 1; + } + } + + ps_dec->u2_mby = ps_cur_mb_info->u2_mby; + ps_dec->u2_mbx = ps_cur_mb_info->u2_mbx; + + ps_dec->u1_mb_ngbr_availablity = + ps_cur_mb_info->u1_mb_ngbr_availablity; + + ps_dec->pv_parse_tu_coeff_data = ps_dec->pv_prev_mb_parse_tu_coeff_data; + ps_dec->u2_cur_mb_addr--; + ps_dec->i4_submb_ofst -= SUB_BLK_SIZE; + + if(u1_num_mbs) + { + if (ps_dec->u1_pr_sl_type == P_SLICE + || ps_dec->u1_pr_sl_type == B_SLICE) + { + ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs); + ps_dec->ps_part = ps_dec->ps_parse_part_params; + } + + u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1; + u1_end_of_row = (!u1_num_mbs_next) + && (!(u1_mbaff && (u1_num_mbs & 0x01))); + u1_slice_end = 1; + u1_tfr_n_mb = 1; + ps_cur_mb_info->u1_end_of_slice = u1_slice_end; + + if(ps_dec->u1_separate_parse) + { + ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, + u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); + ps_dec->ps_nmb_info += u1_num_mbs; + } + else + { + ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, + u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); + } + ps_dec->u2_total_mbs_coded += u1_num_mbs; + ps_dec->u1_mb_idx = 0; + ps_dec->u4_num_mbs_cur_nmb = 0; + } + + if(ps_dec->u2_total_mbs_coded + >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) + { + ps_dec->u1_pic_decode_done = 1; + return 0; + } + + ps_dec->u2_cur_slice_num++; + ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; + ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; + ps_dec->ps_parse_cur_slice++; + + } + else + { + ps_dec->ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + + ps_dec->u2_cur_slice_num; + } + } + + /******************************************************/ + /* Initializations to new slice */ + /******************************************************/ + { + WORD32 num_entries; + WORD32 size; + UWORD8 *pu1_buf; + + num_entries = MAX_FRAMES; + if((1 >= ps_dec->ps_cur_sps->u1_num_ref_frames) && + (0 == ps_dec->i4_display_delay)) + { + num_entries = 1; + } + num_entries = ((2 * num_entries) + 1); + if(BASE_PROFILE_IDC != ps_dec->ps_cur_sps->u1_profile_idc) + { + num_entries *= 2; + } + size = num_entries * sizeof(void *); + size += PAD_MAP_IDX_POC * sizeof(void *); + + pu1_buf = (UWORD8 *)ps_dec->pv_map_ref_idx_to_poc_buf; + pu1_buf += size * ps_dec->u2_cur_slice_num; + ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc = (volatile void **)pu1_buf; + } + + ps_dec->ps_cur_slice->u2_first_mb_in_slice = ps_dec->u2_total_mbs_coded << u1_mbaff; + ps_dec->ps_cur_slice->i1_slice_alpha_c0_offset = 0; + ps_dec->ps_cur_slice->i1_slice_beta_offset = 0; + + if(ps_dec->ps_cur_slice->u1_field_pic_flag) + ps_dec->u2_prv_frame_num = ps_dec->ps_cur_slice->u2_frame_num; + + ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice = ps_dec->u2_total_mbs_coded << u1_mbaff; + ps_dec->ps_parse_cur_slice->u2_log2Y_crwd = ps_dec->ps_cur_slice->u2_log2Y_crwd; + + + if(ps_dec->u1_separate_parse) + { + ps_dec->ps_parse_cur_slice->pv_tu_coeff_data_start = ps_dec->pv_parse_tu_coeff_data; + } + else + { + ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data; + } + + /******************************************************/ + /* Initializations specific to P slice */ + /******************************************************/ + u1_inter_mb_type = P_MB; + u1_deblk_mb_type = D_INTER_MB; + + ps_dec->ps_cur_slice->u1_slice_type = P_SLICE; + ps_dec->ps_parse_cur_slice->slice_type = P_SLICE; + ps_dec->pf_mvpred_ref_tfr_nby2mb = ih264d_mv_pred_ref_tfr_nby2_pmb; + ps_dec->ps_part = ps_dec->ps_parse_part_params; + + /******************************************************/ + /* Parsing / decoding the slice */ + /******************************************************/ + ps_dec->u1_slice_header_done = 2; + ps_dec->u1_qp = ps_slice->u1_slice_qp; + ih264d_update_qp(ps_dec, 0); + u1_mb_idx = ps_dec->u1_mb_idx; + ps_parse_mb_data = ps_dec->ps_parse_mb_data; + u1_num_mbs = u1_mb_idx; + + u1_slice_end = 0; + u1_tfr_n_mb = 0; + u1_decode_nmb = 0; + u1_num_mbsNby2 = 0; + i2_cur_mb_addr = ps_dec->u2_total_mbs_coded; + i2_mb_skip_run = num_mb_skip; + + while(!u1_slice_end) + { + UWORD8 u1_mb_type; + + if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr) + break; + + ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs; + ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs; + + ps_cur_mb_info->u1_Mux = 0; + ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff); + ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs; + + ps_cur_mb_info->u1_end_of_slice = 0; + + /* Storing Default partition info */ + ps_parse_mb_data->u1_num_part = 1; + ps_parse_mb_data->u1_isI_mb = 0; + + /**************************************************************/ + /* Get the required information for decoding of MB */ + /**************************************************************/ + /* mb_x, mb_y, neighbor availablity, */ + if (u1_mbaff) + ih264d_get_mb_info_cavlc_mbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run); + else + ih264d_get_mb_info_cavlc_nonmbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run); + + /* Set the deblocking parameters for this MB */ + if(ps_dec->u4_app_disable_deblk_frm == 0) + { + ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice, + ps_dec->u1_mb_ngbr_availablity, + ps_dec->u1_cur_mb_fld_dec_flag); + } + + /* Set appropriate flags in ps_cur_mb_info and ps_dec */ + ps_dec->i1_prev_mb_qp_delta = 0; + ps_dec->u1_sub_mb_num = 0; + ps_cur_mb_info->u1_mb_type = MB_SKIP; + ps_cur_mb_info->u1_mb_mc_mode = PRED_16x16; + ps_cur_mb_info->u1_cbp = 0; + + /* Storing Skip partition info */ + ps_part_info = ps_dec->ps_part; + ps_part_info->u1_is_direct = PART_DIRECT_16x16; + ps_part_info->u1_sub_mb_num = 0; + ps_dec->ps_part++; + + /* Update Nnzs */ + ih264d_update_nnz_for_skipmb(ps_dec, ps_cur_mb_info, CAVLC); + + ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type; + ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type; + + i2_mb_skip_run--; + + ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp; + + if (u1_mbaff) + { + ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info); + } + + /**************************************************************/ + /* Get next Macroblock address */ + /**************************************************************/ + i2_cur_mb_addr++; + + u1_num_mbs++; + u1_num_mbsNby2++; + ps_parse_mb_data++; + + /****************************************************************/ + /* Check for End Of Row and other flags that determine when to */ + /* do DMA setup for N/2-Mb, Decode for N-Mb, and Transfer for */ + /* N-Mb */ + /****************************************************************/ + u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1; + u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01))); + u1_slice_end = !i2_mb_skip_run; + u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row + || u1_slice_end; + u1_decode_nmb = u1_tfr_n_mb || u1_slice_end; + ps_cur_mb_info->u1_end_of_slice = u1_slice_end; + + if(u1_decode_nmb) + { + ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs); + u1_num_mbsNby2 = 0; + + ps_parse_mb_data = ps_dec->ps_parse_mb_data; + ps_dec->ps_part = ps_dec->ps_parse_part_params; + + if(ps_dec->u1_separate_parse) + { + ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, + u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); + ps_dec->ps_nmb_info += u1_num_mbs; + } + else + { + ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, + u1_tfr_n_mb, u1_end_of_row); + } + ps_dec->u2_total_mbs_coded += u1_num_mbs; + if(u1_tfr_n_mb) + u1_num_mbs = 0; + u1_mb_idx = u1_num_mbs; + ps_dec->u1_mb_idx = u1_num_mbs; + } + } + + ps_dec->u4_num_mbs_cur_nmb = 0; + ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr + - ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice; + + + H264_DEC_DEBUG_PRINT(""Mbs in slice: %d\n"", ps_dec->ps_cur_slice->u4_mbs_in_slice); + + ps_dec->u2_cur_slice_num++; + + /* incremented here only if first slice is inserted */ + if(ps_dec->u4_first_slice_in_pic != 0) + ps_dec->ps_parse_cur_slice++; + + ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; + ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; + + if(ps_dec->u2_total_mbs_coded + >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) + { + ps_dec->u1_pic_decode_done = 1; + } + + return 0; + +} +",1,"WORD32 ih264d_mark_err_slice_skip(dec_struct_t * ps_dec, + WORD32 num_mb_skip, + UWORD8 u1_is_idr_slice, + UWORD16 u2_frame_num, + pocstruct_t *ps_cur_poc, + WORD32 prev_slice_err) +{ + WORD32 i2_cur_mb_addr; + UWORD32 u1_num_mbs, u1_num_mbsNby2; + UWORD32 u1_mb_idx = ps_dec->u1_mb_idx; + UWORD32 i2_mb_skip_run; + + UWORD32 u1_num_mbs_next, u1_end_of_row; + const UWORD32 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs; + UWORD32 u1_slice_end; + UWORD32 u1_tfr_n_mb; + UWORD32 u1_decode_nmb; + dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm; + dec_slice_params_t * ps_slice = ps_dec->ps_cur_slice; + UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; + UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; + deblk_mb_t *ps_cur_deblk_mb; + dec_mb_info_t *ps_cur_mb_info; + parse_pmbarams_t *ps_parse_mb_data; + UWORD32 u1_inter_mb_type; + UWORD32 u1_deblk_mb_type; + UWORD16 u2_total_mbs_coded; + UWORD32 u1_mbaff = ps_slice->u1_mbaff_frame_flag; + parse_part_params_t *ps_part_info; + WORD32 ret; + + + if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) + { + ih264d_err_pic_dispbuf_mgr(ps_dec); + return 0; + } + ps_dec->ps_dpb_cmds->u1_long_term_reference_flag = 0; + if(prev_slice_err == 1) + { + /* first slice - missing/header corruption */ + ps_dec->ps_cur_slice->u2_frame_num = u2_frame_num; + + + if(!ps_dec->u1_first_slice_in_stream) + { + ih264d_end_of_pic(ps_dec, u1_is_idr_slice, + ps_dec->ps_cur_slice->u2_frame_num); + ps_dec->s_cur_pic_poc.u2_frame_num = + ps_dec->ps_cur_slice->u2_frame_num; + } + + { + WORD32 i, j, poc = 0; + + ps_dec->ps_cur_slice->u2_first_mb_in_slice = 0; + + ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff; + ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp; + ps_dec->p_motion_compensate = ih264d_motion_compensate_bp; + + if(ps_dec->ps_cur_pic != NULL) + poc = ps_dec->ps_cur_pic->i4_poc + 2; + + j = 0; + for(i = 0; i < MAX_NUM_PIC_PARAMS; i++) + if(ps_dec->ps_pps[i].u1_is_valid == TRUE) + j = i; + { + ps_dec->ps_cur_slice->u1_slice_type = P_SLICE; + ps_dec->ps_cur_slice->u1_nal_ref_idc = 1; + ps_dec->ps_cur_slice->u1_nal_unit_type = 1; + ret = ih264d_start_of_pic(ps_dec, poc, ps_cur_poc, + ps_dec->ps_cur_slice->u2_frame_num, + &ps_dec->ps_pps[j]); + + if(ret != OK) + { + return ret; + } + } + + ps_dec->ps_ref_pic_buf_lx[0][0]->u1_pic_buf_id = 0; + + ps_dec->u4_output_present = 0; + + { + ih264d_get_next_display_field(ps_dec, + ps_dec->ps_out_buffer, + &(ps_dec->s_disp_op)); + /* If error code is non-zero then there is no buffer available for display, + hence avoid format conversion */ + + if(0 != ps_dec->s_disp_op.u4_error_code) + { + ps_dec->u4_fmt_conv_cur_row = ps_dec->s_disp_frame_info.u4_y_ht; + } + else + ps_dec->u4_output_present = 1; + } + + if(ps_dec->u1_separate_parse == 1) + { + if(ps_dec->u4_dec_thread_created == 0) + { + ithread_create(ps_dec->pv_dec_thread_handle, NULL, + (void *)ih264d_decode_picture_thread, + (void *)ps_dec); + + ps_dec->u4_dec_thread_created = 1; + } + + if((ps_dec->u4_num_cores == 3) && + ((ps_dec->u4_app_disable_deblk_frm == 0) || ps_dec->i1_recon_in_thread3_flag) + && (ps_dec->u4_bs_deblk_thread_created == 0)) + { + ps_dec->u4_start_recon_deblk = 0; + ithread_create(ps_dec->pv_bs_deblk_thread_handle, NULL, + (void *)ih264d_recon_deblk_thread, + (void *)ps_dec); + ps_dec->u4_bs_deblk_thread_created = 1; + + } + } + } + ps_dec->u4_first_slice_in_pic = 0; + } + else + { + + dec_slice_struct_t *ps_parse_cur_slice; + ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + ps_dec->u2_cur_slice_num; + + if(ps_dec->u1_slice_header_done + && ps_parse_cur_slice == ps_dec->ps_parse_cur_slice) + { + u1_num_mbs = ps_dec->u4_num_mbs_cur_nmb; + + if(u1_num_mbs) + { + ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs - 1; + } + else + { + if(ps_dec->u1_separate_parse) + { + ps_cur_mb_info = ps_dec->ps_nmb_info - 1; + } + else + { + ps_cur_mb_info = ps_dec->ps_nmb_info + + ps_dec->u4_num_mbs_prev_nmb - 1; + } + } + + ps_dec->u2_mby = ps_cur_mb_info->u2_mby; + ps_dec->u2_mbx = ps_cur_mb_info->u2_mbx; + + ps_dec->u1_mb_ngbr_availablity = + ps_cur_mb_info->u1_mb_ngbr_availablity; + + ps_dec->pv_parse_tu_coeff_data = ps_dec->pv_prev_mb_parse_tu_coeff_data; + ps_dec->u2_cur_mb_addr--; + ps_dec->i4_submb_ofst -= SUB_BLK_SIZE; + + if(u1_num_mbs) + { + if (ps_dec->u1_pr_sl_type == P_SLICE + || ps_dec->u1_pr_sl_type == B_SLICE) + { + ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs); + ps_dec->ps_part = ps_dec->ps_parse_part_params; + } + + u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1; + u1_end_of_row = (!u1_num_mbs_next) + && (!(u1_mbaff && (u1_num_mbs & 0x01))); + u1_slice_end = 1; + u1_tfr_n_mb = 1; + ps_cur_mb_info->u1_end_of_slice = u1_slice_end; + + if(ps_dec->u1_separate_parse) + { + ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, + u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); + ps_dec->ps_nmb_info += u1_num_mbs; + } + else + { + ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, + u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); + } + ps_dec->u2_total_mbs_coded += u1_num_mbs; + ps_dec->u1_mb_idx = 0; + ps_dec->u4_num_mbs_cur_nmb = 0; + } + + if(ps_dec->u2_total_mbs_coded + >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) + { + ps_dec->u1_pic_decode_done = 1; + return 0; + } + + ps_dec->u2_cur_slice_num++; + ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; + ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; + ps_dec->ps_parse_cur_slice++; + + } + else + { + ps_dec->ps_parse_cur_slice = ps_dec->ps_dec_slice_buf + + ps_dec->u2_cur_slice_num; + } + } + + /******************************************************/ + /* Initializations to new slice */ + /******************************************************/ + { + WORD32 num_entries; + WORD32 size; + UWORD8 *pu1_buf; + + num_entries = MAX_FRAMES; + if((1 >= ps_dec->ps_cur_sps->u1_num_ref_frames) && + (0 == ps_dec->i4_display_delay)) + { + num_entries = 1; + } + num_entries = ((2 * num_entries) + 1); + if(BASE_PROFILE_IDC != ps_dec->ps_cur_sps->u1_profile_idc) + { + num_entries *= 2; + } + size = num_entries * sizeof(void *); + size += PAD_MAP_IDX_POC * sizeof(void *); + + pu1_buf = (UWORD8 *)ps_dec->pv_map_ref_idx_to_poc_buf; + pu1_buf += size * ps_dec->u2_cur_slice_num; + ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc = (volatile void **)pu1_buf; + } + + ps_dec->ps_cur_slice->u2_first_mb_in_slice = ps_dec->u2_total_mbs_coded << u1_mbaff; + ps_dec->ps_cur_slice->i1_slice_alpha_c0_offset = 0; + ps_dec->ps_cur_slice->i1_slice_beta_offset = 0; + + if(ps_dec->ps_cur_slice->u1_field_pic_flag) + ps_dec->u2_prv_frame_num = ps_dec->ps_cur_slice->u2_frame_num; + + ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice = ps_dec->u2_total_mbs_coded << u1_mbaff; + ps_dec->ps_parse_cur_slice->u2_log2Y_crwd = ps_dec->ps_cur_slice->u2_log2Y_crwd; + + + if(ps_dec->u1_separate_parse) + { + ps_dec->ps_parse_cur_slice->pv_tu_coeff_data_start = ps_dec->pv_parse_tu_coeff_data; + } + else + { + ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data; + } + + /******************************************************/ + /* Initializations specific to P slice */ + /******************************************************/ + u1_inter_mb_type = P_MB; + u1_deblk_mb_type = D_INTER_MB; + + ps_dec->ps_cur_slice->u1_slice_type = P_SLICE; + ps_dec->ps_parse_cur_slice->slice_type = P_SLICE; + ps_dec->pf_mvpred_ref_tfr_nby2mb = ih264d_mv_pred_ref_tfr_nby2_pmb; + ps_dec->ps_part = ps_dec->ps_parse_part_params; + + /******************************************************/ + /* Parsing / decoding the slice */ + /******************************************************/ + ps_dec->u1_slice_header_done = 2; + ps_dec->u1_qp = ps_slice->u1_slice_qp; + ih264d_update_qp(ps_dec, 0); + u1_mb_idx = ps_dec->u1_mb_idx; + ps_parse_mb_data = ps_dec->ps_parse_mb_data; + u1_num_mbs = u1_mb_idx; + + u1_slice_end = 0; + u1_tfr_n_mb = 0; + u1_decode_nmb = 0; + u1_num_mbsNby2 = 0; + i2_cur_mb_addr = ps_dec->u2_total_mbs_coded; + i2_mb_skip_run = num_mb_skip; + + while(!u1_slice_end) + { + UWORD8 u1_mb_type; + + if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr) + break; + + ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs; + ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs; + + ps_cur_mb_info->u1_Mux = 0; + ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff); + ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs; + + ps_cur_mb_info->u1_end_of_slice = 0; + + /* Storing Default partition info */ + ps_parse_mb_data->u1_num_part = 1; + ps_parse_mb_data->u1_isI_mb = 0; + + /**************************************************************/ + /* Get the required information for decoding of MB */ + /**************************************************************/ + /* mb_x, mb_y, neighbor availablity, */ + if (u1_mbaff) + ih264d_get_mb_info_cavlc_mbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run); + else + ih264d_get_mb_info_cavlc_nonmbaff(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, i2_mb_skip_run); + + /* Set the deblocking parameters for this MB */ + if(ps_dec->u4_app_disable_deblk_frm == 0) + { + ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice, + ps_dec->u1_mb_ngbr_availablity, + ps_dec->u1_cur_mb_fld_dec_flag); + } + + /* Set appropriate flags in ps_cur_mb_info and ps_dec */ + ps_dec->i1_prev_mb_qp_delta = 0; + ps_dec->u1_sub_mb_num = 0; + ps_cur_mb_info->u1_mb_type = MB_SKIP; + ps_cur_mb_info->u1_mb_mc_mode = PRED_16x16; + ps_cur_mb_info->u1_cbp = 0; + + /* Storing Skip partition info */ + ps_part_info = ps_dec->ps_part; + ps_part_info->u1_is_direct = PART_DIRECT_16x16; + ps_part_info->u1_sub_mb_num = 0; + ps_dec->ps_part++; + + /* Update Nnzs */ + ih264d_update_nnz_for_skipmb(ps_dec, ps_cur_mb_info, CAVLC); + + ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type; + ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type; + + i2_mb_skip_run--; + + ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp; + + if (u1_mbaff) + { + ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info); + } + + /**************************************************************/ + /* Get next Macroblock address */ + /**************************************************************/ + i2_cur_mb_addr++; + + u1_num_mbs++; + u1_num_mbsNby2++; + ps_parse_mb_data++; + + /****************************************************************/ + /* Check for End Of Row and other flags that determine when to */ + /* do DMA setup for N/2-Mb, Decode for N-Mb, and Transfer for */ + /* N-Mb */ + /****************************************************************/ + u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1; + u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01))); + u1_slice_end = !i2_mb_skip_run; + u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row + || u1_slice_end; + u1_decode_nmb = u1_tfr_n_mb || u1_slice_end; + ps_cur_mb_info->u1_end_of_slice = u1_slice_end; + + if(u1_decode_nmb) + { + ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs); + u1_num_mbsNby2 = 0; + + ps_parse_mb_data = ps_dec->ps_parse_mb_data; + ps_dec->ps_part = ps_dec->ps_parse_part_params; + + if(ps_dec->u1_separate_parse) + { + ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, + u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row); + ps_dec->ps_nmb_info += u1_num_mbs; + } + else + { + ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs, u1_num_mbs_next, + u1_tfr_n_mb, u1_end_of_row); + } + ps_dec->u2_total_mbs_coded += u1_num_mbs; + if(u1_tfr_n_mb) + u1_num_mbs = 0; + u1_mb_idx = u1_num_mbs; + ps_dec->u1_mb_idx = u1_num_mbs; + } + } + + ps_dec->u4_num_mbs_cur_nmb = 0; + ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr + - ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice; + + + H264_DEC_DEBUG_PRINT(""Mbs in slice: %d\n"", ps_dec->ps_cur_slice->u4_mbs_in_slice); + + + /* incremented here only if first slice is inserted */ + if(ps_dec->u4_first_slice_in_pic != 0) + { + ps_dec->ps_parse_cur_slice++; + ps_dec->u2_cur_slice_num++; + } + + ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; + ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; + + if(ps_dec->u2_total_mbs_coded + >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) + { + ps_dec->u1_pic_decode_done = 1; + } + + return 0; + +} +","@@ -1550,6 +1550,7 @@ + + } + } + } ++ ps_dec->u4_first_slice_in_pic = 0; + } + else + { +@@ -1842,11 +1843,13 @@ + + + H264_DEC_DEBUG_PRINT(""Mbs in slice: %d\n"", ps_dec->ps_cur_slice->u4_mbs_in_slice); + +- ps_dec->u2_cur_slice_num++; + + /* incremented here only if first slice is inserted */ + if(ps_dec->u4_first_slice_in_pic != 0) ++ { + ps_dec->ps_parse_cur_slice++; ++ ps_dec->u2_cur_slice_num++; ++ } + + ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; + ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; +",4083,4414,6144 +7948,"static void guess_mv(ERContext *s) +{ + int (*blocklist)[2], (*next_blocklist)[2]; + uint8_t *fixed; + const ptrdiff_t mb_stride = s->mb_stride; + const int mb_width = s->mb_width; + int mb_height = s->mb_height; + int i, depth, num_avail; + int mb_x, mb_y; + ptrdiff_t mot_step, mot_stride; + int blocklist_length, next_blocklist_length; + + if (s->last_pic.f && s->last_pic.f->data[0]) + mb_height = FFMIN(mb_height, (s->last_pic.f->height+15)>>4); + if (s->next_pic.f && s->next_pic.f->data[0]) + mb_height = FFMIN(mb_height, (s->next_pic.f->height+15)>>4); + + blocklist = (int (*)[2])s->er_temp_buffer; + next_blocklist = blocklist + s->mb_stride * s->mb_height; + fixed = (uint8_t *)(next_blocklist + s->mb_stride * s->mb_height); + + set_mv_strides(s, &mot_step, &mot_stride); + + num_avail = 0; + if (s->last_pic.motion_val[0]) + ff_thread_await_progress(s->last_pic.tf, mb_height-1, 0); + for (i = 0; i < mb_width * mb_height; i++) { + const int mb_xy = s->mb_index2xy[i]; + int f = 0; + int error = s->error_status_table[mb_xy]; + + if (IS_INTRA(s->cur_pic.mb_type[mb_xy])) + f = MV_FROZEN; // intra // FIXME check + if (!(error & ER_MV_ERROR)) + f = MV_FROZEN; // inter with undamaged MV + + fixed[mb_xy] = f; + if (f == MV_FROZEN) + num_avail++; + else if(s->last_pic.f->data[0] && s->last_pic.motion_val[0]){ + const int mb_y= mb_xy / s->mb_stride; + const int mb_x= mb_xy % s->mb_stride; + const int mot_index= (mb_x + mb_y*mot_stride) * mot_step; + s->cur_pic.motion_val[0][mot_index][0]= s->last_pic.motion_val[0][mot_index][0]; + s->cur_pic.motion_val[0][mot_index][1]= s->last_pic.motion_val[0][mot_index][1]; + s->cur_pic.ref_index[0][4*mb_xy] = s->last_pic.ref_index[0][4*mb_xy]; + } + } + + if ((!(s->avctx->error_concealment&FF_EC_GUESS_MVS)) || + num_avail <= mb_width / 2) { + for (mb_y = 0; mb_y < mb_height; mb_y++) { + for (mb_x = 0; mb_x < s->mb_width; mb_x++) { + const int mb_xy = mb_x + mb_y * s->mb_stride; + int mv_dir = (s->last_pic.f && s->last_pic.f->data[0]) ? MV_DIR_FORWARD : MV_DIR_BACKWARD; + + if (IS_INTRA(s->cur_pic.mb_type[mb_xy])) + continue; + if (!(s->error_status_table[mb_xy] & ER_MV_ERROR)) + continue; + + s->mv[0][0][0] = 0; + s->mv[0][0][1] = 0; + s->decode_mb(s->opaque, 0, mv_dir, MV_TYPE_16X16, &s->mv, + mb_x, mb_y, 0, 0); + } + } + return; + } + + blocklist_length = 0; + for (mb_y = 0; mb_y < mb_height; mb_y++) { + for (mb_x = 0; mb_x < mb_width; mb_x++) { + const int mb_xy = mb_x + mb_y * mb_stride; + if (fixed[mb_xy] == MV_FROZEN) { + if (mb_x) add_blocklist(blocklist, &blocklist_length, fixed, mb_x - 1, mb_y, mb_xy - 1); + if (mb_y) add_blocklist(blocklist, &blocklist_length, fixed, mb_x, mb_y - 1, mb_xy - mb_stride); + if (mb_x+1 < mb_width) add_blocklist(blocklist, &blocklist_length, fixed, mb_x + 1, mb_y, mb_xy + 1); + if (mb_y+1 < mb_height) add_blocklist(blocklist, &blocklist_length, fixed, mb_x, mb_y + 1, mb_xy + mb_stride); + } + } + } + + for (depth = 0; ; depth++) { + int changed, pass, none_left; + int blocklist_index; + + none_left = 1; + changed = 1; + for (pass = 0; (changed || pass < 2) && pass < 10; pass++) { + int score_sum = 0; + + changed = 0; + for (blocklist_index = 0; blocklist_index < blocklist_length; blocklist_index++) { + const int mb_x = blocklist[blocklist_index][0]; + const int mb_y = blocklist[blocklist_index][1]; + const int mb_xy = mb_x + mb_y * mb_stride; + int mv_predictor[8][2]; + int ref[8]; + int pred_count; + int j; + int best_score; + int best_pred; + int mot_index; + int prev_x, prev_y, prev_ref; + + if ((mb_x ^ mb_y ^ pass) & 1) + continue; + av_assert2(fixed[mb_xy] != MV_FROZEN); + + + av_assert1(!IS_INTRA(s->cur_pic.mb_type[mb_xy])); + av_assert1(s->last_pic.f && s->last_pic.f->data[0]); + + j = 0; + if (mb_x > 0) + j |= fixed[mb_xy - 1]; + if (mb_x + 1 < mb_width) + j |= fixed[mb_xy + 1]; + if (mb_y > 0) + j |= fixed[mb_xy - mb_stride]; + if (mb_y + 1 < mb_height) + j |= fixed[mb_xy + mb_stride]; + + av_assert2(j & MV_FROZEN); + + if (!(j & MV_CHANGED) && pass > 1) + continue; + + none_left = 0; + pred_count = 0; + mot_index = (mb_x + mb_y * mot_stride) * mot_step; + + if (mb_x > 0 && fixed[mb_xy - 1] > 1) { + mv_predictor[pred_count][0] = + s->cur_pic.motion_val[0][mot_index - mot_step][0]; + mv_predictor[pred_count][1] = + s->cur_pic.motion_val[0][mot_index - mot_step][1]; + ref[pred_count] = + s->cur_pic.ref_index[0][4 * (mb_xy - 1)]; + pred_count++; + } + if (mb_x + 1 < mb_width && fixed[mb_xy + 1] > 1) { + mv_predictor[pred_count][0] = + s->cur_pic.motion_val[0][mot_index + mot_step][0]; + mv_predictor[pred_count][1] = + s->cur_pic.motion_val[0][mot_index + mot_step][1]; + ref[pred_count] = + s->cur_pic.ref_index[0][4 * (mb_xy + 1)]; + pred_count++; + } + if (mb_y > 0 && fixed[mb_xy - mb_stride] > 1) { + mv_predictor[pred_count][0] = + s->cur_pic.motion_val[0][mot_index - mot_stride * mot_step][0]; + mv_predictor[pred_count][1] = + s->cur_pic.motion_val[0][mot_index - mot_stride * mot_step][1]; + ref[pred_count] = + s->cur_pic.ref_index[0][4 * (mb_xy - s->mb_stride)]; + pred_count++; + } + if (mb_y + 1 1) { + mv_predictor[pred_count][0] = + s->cur_pic.motion_val[0][mot_index + mot_stride * mot_step][0]; + mv_predictor[pred_count][1] = + s->cur_pic.motion_val[0][mot_index + mot_stride * mot_step][1]; + ref[pred_count] = + s->cur_pic.ref_index[0][4 * (mb_xy + s->mb_stride)]; + pred_count++; + } + if (pred_count == 0) + continue; + + if (pred_count > 1) { + int sum_x = 0, sum_y = 0, sum_r = 0; + int max_x, max_y, min_x, min_y, max_r, min_r; + + for (j = 0; j < pred_count; j++) { + sum_x += mv_predictor[j][0]; + sum_y += mv_predictor[j][1]; + sum_r += ref[j]; + if (j && ref[j] != ref[j - 1]) + goto skip_mean_and_median; + } + + /* mean */ + mv_predictor[pred_count][0] = sum_x / j; + mv_predictor[pred_count][1] = sum_y / j; + ref[pred_count] = sum_r / j; + + /* median */ + if (pred_count >= 3) { + min_y = min_x = min_r = 99999; + max_y = max_x = max_r = -99999; + } else { + min_x = min_y = max_x = max_y = min_r = max_r = 0; + } + for (j = 0; j < pred_count; j++) { + max_x = FFMAX(max_x, mv_predictor[j][0]); + max_y = FFMAX(max_y, mv_predictor[j][1]); + max_r = FFMAX(max_r, ref[j]); + min_x = FFMIN(min_x, mv_predictor[j][0]); + min_y = FFMIN(min_y, mv_predictor[j][1]); + min_r = FFMIN(min_r, ref[j]); + } + mv_predictor[pred_count + 1][0] = sum_x - max_x - min_x; + mv_predictor[pred_count + 1][1] = sum_y - max_y - min_y; + ref[pred_count + 1] = sum_r - max_r - min_r; + + if (pred_count == 4) { + mv_predictor[pred_count + 1][0] /= 2; + mv_predictor[pred_count + 1][1] /= 2; + ref[pred_count + 1] /= 2; + } + pred_count += 2; + } + +skip_mean_and_median: + /* zero MV */ + mv_predictor[pred_count][0] = + mv_predictor[pred_count][1] = + ref[pred_count] = 0; + pred_count++; + + prev_x = s->cur_pic.motion_val[0][mot_index][0]; + prev_y = s->cur_pic.motion_val[0][mot_index][1]; + prev_ref = s->cur_pic.ref_index[0][4 * mb_xy]; + + /* last MV */ + mv_predictor[pred_count][0] = prev_x; + mv_predictor[pred_count][1] = prev_y; + ref[pred_count] = prev_ref; + pred_count++; + + best_pred = 0; + best_score = 256 * 256 * 256 * 64; + for (j = 0; j < pred_count; j++) { + int *linesize = s->cur_pic.f->linesize; + int score = 0; + uint8_t *src = s->cur_pic.f->data[0] + + mb_x * 16 + mb_y * 16 * linesize[0]; + + s->cur_pic.motion_val[0][mot_index][0] = + s->mv[0][0][0] = mv_predictor[j][0]; + s->cur_pic.motion_val[0][mot_index][1] = + s->mv[0][0][1] = mv_predictor[j][1]; + + if (ref[j] < 0) + continue; + + s->decode_mb(s->opaque, ref[j], MV_DIR_FORWARD, + MV_TYPE_16X16, &s->mv, mb_x, mb_y, 0, 0); + + if (mb_x > 0 && fixed[mb_xy - 1] > 1) { + int k; + for (k = 0; k < 16; k++) + score += FFABS(src[k * linesize[0] - 1] - + src[k * linesize[0]]); + } + if (mb_x + 1 < mb_width && fixed[mb_xy + 1] > 1) { + int k; + for (k = 0; k < 16; k++) + score += FFABS(src[k * linesize[0] + 15] - + src[k * linesize[0] + 16]); + } + if (mb_y > 0 && fixed[mb_xy - mb_stride] > 1) { + int k; + for (k = 0; k < 16; k++) + score += FFABS(src[k - linesize[0]] - src[k]); + } + if (mb_y + 1 < mb_height && fixed[mb_xy + mb_stride] > 1) { + int k; + for (k = 0; k < 16; k++) + score += FFABS(src[k + linesize[0] * 15] - + src[k + linesize[0] * 16]); + } + + if (score <= best_score) { // <= will favor the last MV + best_score = score; + best_pred = j; + } + } + score_sum += best_score; + s->mv[0][0][0] = mv_predictor[best_pred][0]; + s->mv[0][0][1] = mv_predictor[best_pred][1]; + + for (i = 0; i < mot_step; i++) + for (j = 0; j < mot_step; j++) { + s->cur_pic.motion_val[0][mot_index + i + j * mot_stride][0] = s->mv[0][0][0]; + s->cur_pic.motion_val[0][mot_index + i + j * mot_stride][1] = s->mv[0][0][1]; + } + + s->decode_mb(s->opaque, ref[best_pred], MV_DIR_FORWARD, + MV_TYPE_16X16, &s->mv, mb_x, mb_y, 0, 0); + + + if (s->mv[0][0][0] != prev_x || s->mv[0][0][1] != prev_y) { + fixed[mb_xy] = MV_CHANGED; + changed++; + } else + fixed[mb_xy] = MV_UNCHANGED; + } + } + + if (none_left) + return; + + next_blocklist_length = 0; + + for (blocklist_index = 0; blocklist_index < blocklist_length; blocklist_index++) { + const int mb_x = blocklist[blocklist_index][0]; + const int mb_y = blocklist[blocklist_index][1]; + const int mb_xy = mb_x + mb_y * mb_stride; + + if (fixed[mb_xy] & (MV_CHANGED|MV_UNCHANGED|MV_FROZEN)) { + fixed[mb_xy] = MV_FROZEN; + if (mb_x > 0) + add_blocklist(next_blocklist, &next_blocklist_length, fixed, mb_x - 1, mb_y, mb_xy - 1); + if (mb_y > 0) + add_blocklist(next_blocklist, &next_blocklist_length, fixed, mb_x, mb_y - 1, mb_xy - mb_stride); + if (mb_x + 1 < mb_width) + add_blocklist(next_blocklist, &next_blocklist_length, fixed, mb_x + 1, mb_y, mb_xy + 1); + if (mb_y + 1 < mb_height) + add_blocklist(next_blocklist, &next_blocklist_length, fixed, mb_x, mb_y + 1, mb_xy + mb_stride); + } + } + av_assert0(next_blocklist_length <= mb_height * mb_width); + FFSWAP(int , blocklist_length, next_blocklist_length); + FFSWAP(void*, blocklist, next_blocklist); + } +} +",0,"static void guess_mv(ERContext *s) +{ + int (*blocklist)[2], (*next_blocklist)[2]; + uint8_t *fixed; + const ptrdiff_t mb_stride = s->mb_stride; + const int mb_width = s->mb_width; + int mb_height = s->mb_height; + int i, depth, num_avail; + int mb_x, mb_y; + ptrdiff_t mot_step, mot_stride; + int blocklist_length, next_blocklist_length; + + if (s->last_pic.f && s->last_pic.f->data[0]) + mb_height = FFMIN(mb_height, (s->last_pic.f->height+15)>>4); + if (s->next_pic.f && s->next_pic.f->data[0]) + mb_height = FFMIN(mb_height, (s->next_pic.f->height+15)>>4); + + blocklist = (int (*)[2])s->er_temp_buffer; + next_blocklist = blocklist + s->mb_stride * s->mb_height; + fixed = (uint8_t *)(next_blocklist + s->mb_stride * s->mb_height); + + set_mv_strides(s, &mot_step, &mot_stride); + + num_avail = 0; + if (s->last_pic.motion_val[0]) + ff_thread_await_progress(s->last_pic.tf, mb_height-1, 0); + for (i = 0; i < mb_width * mb_height; i++) { + const int mb_xy = s->mb_index2xy[i]; + int f = 0; + int error = s->error_status_table[mb_xy]; + + if (IS_INTRA(s->cur_pic.mb_type[mb_xy])) + f = MV_FROZEN; // intra // FIXME check + if (!(error & ER_MV_ERROR)) + f = MV_FROZEN; // inter with undamaged MV + + fixed[mb_xy] = f; + if (f == MV_FROZEN) + num_avail++; + else if(s->last_pic.f->data[0] && s->last_pic.motion_val[0]){ + const int mb_y= mb_xy / s->mb_stride; + const int mb_x= mb_xy % s->mb_stride; + const int mot_index= (mb_x + mb_y*mot_stride) * mot_step; + s->cur_pic.motion_val[0][mot_index][0]= s->last_pic.motion_val[0][mot_index][0]; + s->cur_pic.motion_val[0][mot_index][1]= s->last_pic.motion_val[0][mot_index][1]; + s->cur_pic.ref_index[0][4*mb_xy] = s->last_pic.ref_index[0][4*mb_xy]; + } + } + + if ((!(s->avctx->error_concealment&FF_EC_GUESS_MVS)) || + num_avail <= mb_width / 2) { + for (mb_y = 0; mb_y < mb_height; mb_y++) { + for (mb_x = 0; mb_x < s->mb_width; mb_x++) { + const int mb_xy = mb_x + mb_y * s->mb_stride; + int mv_dir = (s->last_pic.f && s->last_pic.f->data[0]) ? MV_DIR_FORWARD : MV_DIR_BACKWARD; + + if (IS_INTRA(s->cur_pic.mb_type[mb_xy])) + continue; + if (!(s->error_status_table[mb_xy] & ER_MV_ERROR)) + continue; + + s->mv[0][0][0] = 0; + s->mv[0][0][1] = 0; + s->decode_mb(s->opaque, 0, mv_dir, MV_TYPE_16X16, &s->mv, + mb_x, mb_y, 0, 0); + } + } + return; + } + + blocklist_length = 0; + for (mb_y = 0; mb_y < mb_height; mb_y++) { + for (mb_x = 0; mb_x < mb_width; mb_x++) { + const int mb_xy = mb_x + mb_y * mb_stride; + if (fixed[mb_xy] == MV_FROZEN) { + if (mb_x) add_blocklist(blocklist, &blocklist_length, fixed, mb_x - 1, mb_y, mb_xy - 1); + if (mb_y) add_blocklist(blocklist, &blocklist_length, fixed, mb_x, mb_y - 1, mb_xy - mb_stride); + if (mb_x+1 < mb_width) add_blocklist(blocklist, &blocklist_length, fixed, mb_x + 1, mb_y, mb_xy + 1); + if (mb_y+1 < mb_height) add_blocklist(blocklist, &blocklist_length, fixed, mb_x, mb_y + 1, mb_xy + mb_stride); + } + } + } + + for (depth = 0; ; depth++) { + int changed, pass, none_left; + int blocklist_index; + + none_left = 1; + changed = 1; + for (pass = 0; (changed || pass < 2) && pass < 10; pass++) { + int score_sum = 0; + + changed = 0; + for (blocklist_index = 0; blocklist_index < blocklist_length; blocklist_index++) { + const int mb_x = blocklist[blocklist_index][0]; + const int mb_y = blocklist[blocklist_index][1]; + const int mb_xy = mb_x + mb_y * mb_stride; + int mv_predictor[8][2]; + int ref[8]; + int pred_count; + int j; + int best_score; + int best_pred; + int mot_index; + int prev_x, prev_y, prev_ref; + + if ((mb_x ^ mb_y ^ pass) & 1) + continue; + av_assert2(fixed[mb_xy] != MV_FROZEN); + + + av_assert1(!IS_INTRA(s->cur_pic.mb_type[mb_xy])); + av_assert1(s->last_pic.f && s->last_pic.f->data[0]); + + j = 0; + if (mb_x > 0) + j |= fixed[mb_xy - 1]; + if (mb_x + 1 < mb_width) + j |= fixed[mb_xy + 1]; + if (mb_y > 0) + j |= fixed[mb_xy - mb_stride]; + if (mb_y + 1 < mb_height) + j |= fixed[mb_xy + mb_stride]; + + av_assert2(j & MV_FROZEN); + + if (!(j & MV_CHANGED) && pass > 1) + continue; + + none_left = 0; + pred_count = 0; + mot_index = (mb_x + mb_y * mot_stride) * mot_step; + + if (mb_x > 0 && fixed[mb_xy - 1] > 1) { + mv_predictor[pred_count][0] = + s->cur_pic.motion_val[0][mot_index - mot_step][0]; + mv_predictor[pred_count][1] = + s->cur_pic.motion_val[0][mot_index - mot_step][1]; + ref[pred_count] = + s->cur_pic.ref_index[0][4 * (mb_xy - 1)]; + pred_count++; + } + if (mb_x + 1 < mb_width && fixed[mb_xy + 1] > 1) { + mv_predictor[pred_count][0] = + s->cur_pic.motion_val[0][mot_index + mot_step][0]; + mv_predictor[pred_count][1] = + s->cur_pic.motion_val[0][mot_index + mot_step][1]; + ref[pred_count] = + s->cur_pic.ref_index[0][4 * (mb_xy + 1)]; + pred_count++; + } + if (mb_y > 0 && fixed[mb_xy - mb_stride] > 1) { + mv_predictor[pred_count][0] = + s->cur_pic.motion_val[0][mot_index - mot_stride * mot_step][0]; + mv_predictor[pred_count][1] = + s->cur_pic.motion_val[0][mot_index - mot_stride * mot_step][1]; + ref[pred_count] = + s->cur_pic.ref_index[0][4 * (mb_xy - s->mb_stride)]; + pred_count++; + } + if (mb_y + 1 1) { + mv_predictor[pred_count][0] = + s->cur_pic.motion_val[0][mot_index + mot_stride * mot_step][0]; + mv_predictor[pred_count][1] = + s->cur_pic.motion_val[0][mot_index + mot_stride * mot_step][1]; + ref[pred_count] = + s->cur_pic.ref_index[0][4 * (mb_xy + s->mb_stride)]; + pred_count++; + } + if (pred_count == 0) + continue; + + if (pred_count > 1) { + int sum_x = 0, sum_y = 0, sum_r = 0; + int max_x, max_y, min_x, min_y, max_r, min_r; + + for (j = 0; j < pred_count; j++) { + sum_x += mv_predictor[j][0]; + sum_y += mv_predictor[j][1]; + sum_r += ref[j]; + if (j && ref[j] != ref[j - 1]) + goto skip_mean_and_median; + } + + /* mean */ + mv_predictor[pred_count][0] = sum_x / j; + mv_predictor[pred_count][1] = sum_y / j; + ref[pred_count] = sum_r / j; + + /* median */ + if (pred_count >= 3) { + min_y = min_x = min_r = 99999; + max_y = max_x = max_r = -99999; + } else { + min_x = min_y = max_x = max_y = min_r = max_r = 0; + } + for (j = 0; j < pred_count; j++) { + max_x = FFMAX(max_x, mv_predictor[j][0]); + max_y = FFMAX(max_y, mv_predictor[j][1]); + max_r = FFMAX(max_r, ref[j]); + min_x = FFMIN(min_x, mv_predictor[j][0]); + min_y = FFMIN(min_y, mv_predictor[j][1]); + min_r = FFMIN(min_r, ref[j]); + } + mv_predictor[pred_count + 1][0] = sum_x - max_x - min_x; + mv_predictor[pred_count + 1][1] = sum_y - max_y - min_y; + ref[pred_count + 1] = sum_r - max_r - min_r; + + if (pred_count == 4) { + mv_predictor[pred_count + 1][0] /= 2; + mv_predictor[pred_count + 1][1] /= 2; + ref[pred_count + 1] /= 2; + } + pred_count += 2; + } + +skip_mean_and_median: + /* zero MV */ + mv_predictor[pred_count][0] = + mv_predictor[pred_count][1] = + ref[pred_count] = 0; + pred_count++; + + prev_x = s->cur_pic.motion_val[0][mot_index][0]; + prev_y = s->cur_pic.motion_val[0][mot_index][1]; + prev_ref = s->cur_pic.ref_index[0][4 * mb_xy]; + + /* last MV */ + mv_predictor[pred_count][0] = prev_x; + mv_predictor[pred_count][1] = prev_y; + ref[pred_count] = prev_ref; + pred_count++; + + best_pred = 0; + best_score = 256 * 256 * 256 * 64; + for (j = 0; j < pred_count; j++) { + int *linesize = s->cur_pic.f->linesize; + int score = 0; + uint8_t *src = s->cur_pic.f->data[0] + + mb_x * 16 + mb_y * 16 * linesize[0]; + + s->cur_pic.motion_val[0][mot_index][0] = + s->mv[0][0][0] = mv_predictor[j][0]; + s->cur_pic.motion_val[0][mot_index][1] = + s->mv[0][0][1] = mv_predictor[j][1]; + + if (ref[j] < 0) + continue; + + s->decode_mb(s->opaque, ref[j], MV_DIR_FORWARD, + MV_TYPE_16X16, &s->mv, mb_x, mb_y, 0, 0); + + if (mb_x > 0 && fixed[mb_xy - 1] > 1) { + int k; + for (k = 0; k < 16; k++) + score += FFABS(src[k * linesize[0] - 1] - + src[k * linesize[0]]); + } + if (mb_x + 1 < mb_width && fixed[mb_xy + 1] > 1) { + int k; + for (k = 0; k < 16; k++) + score += FFABS(src[k * linesize[0] + 15] - + src[k * linesize[0] + 16]); + } + if (mb_y > 0 && fixed[mb_xy - mb_stride] > 1) { + int k; + for (k = 0; k < 16; k++) + score += FFABS(src[k - linesize[0]] - src[k]); + } + if (mb_y + 1 < mb_height && fixed[mb_xy + mb_stride] > 1) { + int k; + for (k = 0; k < 16; k++) + score += FFABS(src[k + linesize[0] * 15] - + src[k + linesize[0] * 16]); + } + + if (score <= best_score) { // <= will favor the last MV + best_score = score; + best_pred = j; + } + } + score_sum += best_score; + s->mv[0][0][0] = mv_predictor[best_pred][0]; + s->mv[0][0][1] = mv_predictor[best_pred][1]; + + for (i = 0; i < mot_step; i++) + for (j = 0; j < mot_step; j++) { + s->cur_pic.motion_val[0][mot_index + i + j * mot_stride][0] = s->mv[0][0][0]; + s->cur_pic.motion_val[0][mot_index + i + j * mot_stride][1] = s->mv[0][0][1]; + } + + s->decode_mb(s->opaque, ref[best_pred], MV_DIR_FORWARD, + MV_TYPE_16X16, &s->mv, mb_x, mb_y, 0, 0); + + + if (s->mv[0][0][0] != prev_x || s->mv[0][0][1] != prev_y) { + fixed[mb_xy] = MV_CHANGED; + changed++; + } else + fixed[mb_xy] = MV_UNCHANGED; + } + } + + if (none_left) + return; + + next_blocklist_length = 0; + + for (blocklist_index = 0; blocklist_index < blocklist_length; blocklist_index++) { + const int mb_x = blocklist[blocklist_index][0]; + const int mb_y = blocklist[blocklist_index][1]; + const int mb_xy = mb_x + mb_y * mb_stride; + + if (fixed[mb_xy] & (MV_CHANGED|MV_UNCHANGED|MV_FROZEN)) { + fixed[mb_xy] = MV_FROZEN; + if (mb_x > 0) + add_blocklist(next_blocklist, &next_blocklist_length, fixed, mb_x - 1, mb_y, mb_xy - 1); + if (mb_y > 0) + add_blocklist(next_blocklist, &next_blocklist_length, fixed, mb_x, mb_y - 1, mb_xy - mb_stride); + if (mb_x + 1 < mb_width) + add_blocklist(next_blocklist, &next_blocklist_length, fixed, mb_x + 1, mb_y, mb_xy + 1); + if (mb_y + 1 < mb_height) + add_blocklist(next_blocklist, &next_blocklist_length, fixed, mb_x, mb_y + 1, mb_xy + mb_stride); + } + } + av_assert0(next_blocklist_length <= mb_height * mb_width); + FFSWAP(int , blocklist_length, next_blocklist_length); + FFSWAP(void*, blocklist, next_blocklist); + } +} +","@@ -814,8 +814,7 @@ static int er_supported(ERContext *s) + { + if(s->avctx->hwaccel && s->avctx->hwaccel->decode_slice || + !s->cur_pic.f || +- s->cur_pic.field_picture || +- s->avctx->profile == FF_PROFILE_MPEG4_SIMPLE_STUDIO ++ s->cur_pic.field_picture + ) + return 0; + return 1;",3778,4109,6144 +18722," xsltTestCompMatch(xsltTransformContextPtr ctxt, xsltCompMatchPtr comp, + xmlNodePtr node, const xmlChar *mode, + const xmlChar *modeURI) { + int i; + xsltStepOpPtr step, sel = NULL; + xsltStepStates states = {0, 0, NULL}; /* // may require backtrack */ + + if ((comp == NULL) || (node == NULL) || (ctxt == NULL)) { + xsltTransformError(ctxt, NULL, node, + ""xsltTestCompMatch: null arg\n""); + return(-1); + } + if (mode != NULL) { + if (comp->mode == NULL) + return(0); + /* + * both mode strings must be interned on the stylesheet dictionary + */ + if (comp->mode != mode) + return(0); + } else { + if (comp->mode != NULL) + return(0); + } + if (modeURI != NULL) { + if (comp->modeURI == NULL) + return(0); + /* + * both modeURI strings must be interned on the stylesheet dictionary + */ + if (comp->modeURI != modeURI) + return(0); + } else { + if (comp->modeURI != NULL) + return(0); + } + + i = 0; +restart: + for (;i < comp->nbStep;i++) { + step = &comp->steps[i]; + if (step->op != XSLT_OP_PREDICATE) + sel = step; + switch (step->op) { + case XSLT_OP_END: + goto found; + case XSLT_OP_ROOT: + if ((node->type == XML_DOCUMENT_NODE) || +#ifdef LIBXML_DOCB_ENABLED + (node->type == XML_DOCB_DOCUMENT_NODE) || +#endif + (node->type == XML_HTML_DOCUMENT_NODE)) + continue; + if ((node->type == XML_ELEMENT_NODE) && (node->name[0] == ' ')) + continue; + goto rollback; + case XSLT_OP_ELEM: + if (node->type != XML_ELEMENT_NODE) + goto rollback; + if (step->value == NULL) + continue; + if (step->value[0] != node->name[0]) + goto rollback; + if (!xmlStrEqual(step->value, node->name)) + goto rollback; + + /* Namespace test */ + if (node->ns == NULL) { + if (step->value2 != NULL) + goto rollback; + } else if (node->ns->href != NULL) { + if (step->value2 == NULL) + goto rollback; + if (!xmlStrEqual(step->value2, node->ns->href)) + goto rollback; + } + continue; + case XSLT_OP_ATTR: + if (node->type != XML_ATTRIBUTE_NODE) + goto rollback; + if (step->value != NULL) { + if (step->value[0] != node->name[0]) + goto rollback; + if (!xmlStrEqual(step->value, node->name)) + goto rollback; + } + /* Namespace test */ + if (node->ns == NULL) { + if (step->value2 != NULL) + goto rollback; + } else if (step->value2 != NULL) { + if (!xmlStrEqual(step->value2, node->ns->href)) + goto rollback; + } + continue; + case XSLT_OP_PARENT: + if ((node->type == XML_DOCUMENT_NODE) || + (node->type == XML_HTML_DOCUMENT_NODE) || +#ifdef LIBXML_DOCB_ENABLED + (node->type == XML_DOCB_DOCUMENT_NODE) || +#endif + (node->type == XML_NAMESPACE_DECL)) + goto rollback; + node = node->parent; + if (node == NULL) + goto rollback; + if (step->value == NULL) + continue; + if (step->value[0] != node->name[0]) + goto rollback; + if (!xmlStrEqual(step->value, node->name)) + goto rollback; + /* Namespace test */ + if (node->ns == NULL) { + if (step->value2 != NULL) + goto rollback; + } else if (node->ns->href != NULL) { + if (step->value2 == NULL) + goto rollback; + if (!xmlStrEqual(step->value2, node->ns->href)) + goto rollback; + } + continue; + case XSLT_OP_ANCESTOR: + /* TODO: implement coalescing of ANCESTOR/NODE ops */ + if (step->value == NULL) { + step = &comp->steps[i+1]; + if (step->op == XSLT_OP_ROOT) + goto found; + /* added NS, ID and KEY as a result of bug 168208 */ + if ((step->op != XSLT_OP_ELEM) && + (step->op != XSLT_OP_ALL) && + (step->op != XSLT_OP_NS) && + (step->op != XSLT_OP_ID) && + (step->op != XSLT_OP_KEY)) + goto rollback; + } + if (node == NULL) + goto rollback; + if ((node->type == XML_DOCUMENT_NODE) || + (node->type == XML_HTML_DOCUMENT_NODE) || +#ifdef LIBXML_DOCB_ENABLED + (node->type == XML_DOCB_DOCUMENT_NODE) || +#endif + (node->type == XML_NAMESPACE_DECL)) + goto rollback; + node = node->parent; + if ((step->op != XSLT_OP_ELEM) && step->op != XSLT_OP_ALL) { + xsltPatPushState(ctxt, &states, i, node); + continue; + } + i++; + if (step->value == NULL) { + xsltPatPushState(ctxt, &states, i - 1, node); + continue; + } + while (node != NULL) { + if ((node->type == XML_ELEMENT_NODE) && + (step->value[0] == node->name[0]) && + (xmlStrEqual(step->value, node->name))) { + /* Namespace test */ + if (node->ns == NULL) { + if (step->value2 == NULL) + break; + } else if (node->ns->href != NULL) { + if ((step->value2 != NULL) && + (xmlStrEqual(step->value2, node->ns->href))) + break; + } + } + node = node->parent; + } + if (node == NULL) + goto rollback; + xsltPatPushState(ctxt, &states, i - 1, node); + continue; + case XSLT_OP_ID: { + /* TODO Handle IDs decently, must be done differently */ + xmlAttrPtr id; + + if (node->type != XML_ELEMENT_NODE) + goto rollback; + + id = xmlGetID(node->doc, step->value); + if ((id == NULL) || (id->parent != node)) + goto rollback; + break; + } + case XSLT_OP_KEY: { + xmlNodeSetPtr list; + int indx; + + list = xsltGetKey(ctxt, step->value, + step->value3, step->value2); + if (list == NULL) + goto rollback; + for (indx = 0;indx < list->nodeNr;indx++) + if (list->nodeTab[indx] == node) + break; + if (indx >= list->nodeNr) + goto rollback; + break; + } + case XSLT_OP_NS: + if (node->type != XML_ELEMENT_NODE) + goto rollback; + if (node->ns == NULL) { + if (step->value != NULL) + goto rollback; + } else if (node->ns->href != NULL) { + if (step->value == NULL) + goto rollback; + if (!xmlStrEqual(step->value, node->ns->href)) + goto rollback; + } + break; + case XSLT_OP_ALL: + if (node->type != XML_ELEMENT_NODE) + goto rollback; + break; + case XSLT_OP_PREDICATE: { + xmlNodePtr oldNode; + xmlDocPtr doc; + int oldCS, oldCP; + int pos = 0, len = 0; + int isRVT; + /* + * when there is cascading XSLT_OP_PREDICATE, then use a + * direct computation approach. It's not done directly + * at the beginning of the routine to filter out as much + * as possible this costly computation. + */ + if (comp->direct) { + if (states.states != NULL) { + /* Free the rollback states */ + xmlFree(states.states); + } + return(xsltTestCompMatchDirect(ctxt, comp, node, + comp->nsList, comp->nsNr)); + } + + doc = node->doc; + if (XSLT_IS_RES_TREE_FRAG(doc)) + isRVT = 1; + else + isRVT = 0; + /* + * Depending on the last selection, one may need to + * recompute contextSize and proximityPosition. + */ + oldCS = ctxt->xpathCtxt->contextSize; + oldCP = ctxt->xpathCtxt->proximityPosition; + if ((sel != NULL) && + (sel->op == XSLT_OP_ELEM) && + (sel->value != NULL) && + (node->type == XML_ELEMENT_NODE) && + (node->parent != NULL)) { + xmlNodePtr previous; + int nocache = 0; + previous = (xmlNodePtr) + XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr); + if ((previous != NULL) && + (previous->parent == node->parent)) { + /* + * just walk back to adjust the index + */ + int indx = 0; + xmlNodePtr sibling = node; + while (sibling != NULL) { + if (sibling == previous) + break; + if ((sibling->type == XML_ELEMENT_NODE) && + (previous->name != NULL) && + (sibling->name != NULL) && + (previous->name[0] == sibling->name[0]) && + (xmlStrEqual(previous->name, sibling->name))) + { + if ((sel->value2 == NULL) || + ((sibling->ns != NULL) && + (xmlStrEqual(sel->value2, + sibling->ns->href)))) + indx++; + } + sibling = sibling->prev; + } + if (sibling == NULL) { + /* hum going backward in document order ... */ + indx = 0; + sibling = node; + while (sibling != NULL) { + if (sibling == previous) + break; + if ((sibling->type == XML_ELEMENT_NODE) && + (previous->name != NULL) && + (sibling->name != NULL) && + (previous->name[0] == sibling->name[0]) && + (xmlStrEqual(previous->name, sibling->name))) + { + if ((sel->value2 == NULL) || + ((sibling->ns != NULL) && + (xmlStrEqual(sel->value2, + sibling->ns->href)))) + { + indx--; + } + } + sibling = sibling->next; + } + } + if (sibling != NULL) { + pos = XSLT_RUNTIME_EXTRA(ctxt, + sel->indexExtra, ival) + indx; + /* + * If the node is in a Value Tree we need to + * save len, but cannot cache the node! + * (bugs 153137 and 158840) + */ + if (node->doc != NULL) { + len = XSLT_RUNTIME_EXTRA(ctxt, + sel->lenExtra, ival); + if (!isRVT) { + XSLT_RUNTIME_EXTRA(ctxt, + sel->previousExtra, ptr) = node; + XSLT_RUNTIME_EXTRA(ctxt, + sel->indexExtra, ival) = pos; + } + } + } else + pos = 0; + } else { + /* + * recompute the index + */ + xmlNodePtr parent = node->parent; + xmlNodePtr siblings = NULL; + if (parent) siblings = parent->children; + while (siblings != NULL) { + if (siblings->type == XML_ELEMENT_NODE) { + if (siblings == node) { + len++; + pos = len; + } else if ((node->name != NULL) && + (siblings->name != NULL) && + (node->name[0] == siblings->name[0]) && + (xmlStrEqual(node->name, siblings->name))) { + if ((sel->value2 == NULL) || + ((siblings->ns != NULL) && + (xmlStrEqual(sel->value2, + siblings->ns->href)))) + len++; + } + } + siblings = siblings->next; + } + if ((parent == NULL) || (node->doc == NULL)) + nocache = 1; + else { + while (parent->parent != NULL) + parent = parent->parent; + if (((parent->type != XML_DOCUMENT_NODE) && + (parent->type != XML_HTML_DOCUMENT_NODE)) || + (parent != (xmlNodePtr) node->doc)) + nocache = 1; + } + } + if (pos != 0) { + ctxt->xpathCtxt->contextSize = len; + ctxt->xpathCtxt->proximityPosition = pos; + /* + * If the node is in a Value Tree we cannot + * cache it ! + */ + if ((!isRVT) && (node->doc != NULL) && + (nocache == 0)) { + XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr) = + node; + XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) = + pos; + XSLT_RUNTIME_EXTRA(ctxt, sel->lenExtra, ival) = + len; + } + } + } else if ((sel != NULL) && (sel->op == XSLT_OP_ALL) && + (node->type == XML_ELEMENT_NODE)) { + xmlNodePtr previous; + int nocache = 0; + previous = (xmlNodePtr) + XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr); + if ((previous != NULL) && + (previous->parent == node->parent)) { + /* + * just walk back to adjust the index + */ + int indx = 0; + xmlNodePtr sibling = node; + while (sibling != NULL) { + if (sibling == previous) + break; + if (sibling->type == XML_ELEMENT_NODE) + indx++; + sibling = sibling->prev; + } + if (sibling == NULL) { + /* hum going backward in document order ... */ + indx = 0; + sibling = node; + while (sibling != NULL) { + if (sibling == previous) + break; + if (sibling->type == XML_ELEMENT_NODE) + indx--; + sibling = sibling->next; + } + } + if (sibling != NULL) { + pos = XSLT_RUNTIME_EXTRA(ctxt, + sel->indexExtra, ival) + indx; + /* + * If the node is in a Value Tree we cannot + * cache it ! + */ + if ((node->doc != NULL) && !isRVT) { + len = XSLT_RUNTIME_EXTRA(ctxt, + sel->lenExtra, ival); + XSLT_RUNTIME_EXTRA(ctxt, + sel->previousExtra, ptr) = node; + XSLT_RUNTIME_EXTRA(ctxt, + sel->indexExtra, ival) = pos; + } + } else + pos = 0; + } else { + /* + * recompute the index + */ + xmlNodePtr parent = node->parent; + xmlNodePtr siblings = NULL; + if (parent) siblings = parent->children; + while (siblings != NULL) { + if (siblings->type == XML_ELEMENT_NODE) { + len++; + if (siblings == node) { + pos = len; + } + } + siblings = siblings->next; + } + if ((parent == NULL) || (node->doc == NULL)) + nocache = 1; + else { + while (parent->parent != NULL) + parent = parent->parent; + if (((parent->type != XML_DOCUMENT_NODE) && + (parent->type != XML_HTML_DOCUMENT_NODE)) || + (parent != (xmlNodePtr) node->doc)) + nocache = 1; + } + } + if (pos != 0) { + ctxt->xpathCtxt->contextSize = len; + ctxt->xpathCtxt->proximityPosition = pos; + /* + * If the node is in a Value Tree we cannot + * cache it ! + */ + if ((node->doc != NULL) && (nocache == 0) && !isRVT) { + XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr) = + node; + XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) = + pos; + XSLT_RUNTIME_EXTRA(ctxt, sel->lenExtra, ival) = + len; + } + } + } + oldNode = ctxt->node; + ctxt->node = node; + if (step->value == NULL) + goto wrong_index; + if (step->comp == NULL) + goto wrong_index; + if (!xsltEvalXPathPredicate(ctxt, step->comp, comp->nsList, + comp->nsNr)) + goto wrong_index; + + if (pos != 0) { + ctxt->xpathCtxt->contextSize = oldCS; + ctxt->xpathCtxt->proximityPosition = oldCP; + } + ctxt->node = oldNode; + break; +wrong_index: + if (pos != 0) { + ctxt->xpathCtxt->contextSize = oldCS; + ctxt->xpathCtxt->proximityPosition = oldCP; + } + ctxt->node = oldNode; + goto rollback; + } + case XSLT_OP_PI: + if (node->type != XML_PI_NODE) + goto rollback; + if (step->value != NULL) { + if (!xmlStrEqual(step->value, node->name)) + goto rollback; + } + break; + case XSLT_OP_COMMENT: + if (node->type != XML_COMMENT_NODE) + goto rollback; + break; + case XSLT_OP_TEXT: + if ((node->type != XML_TEXT_NODE) && + (node->type != XML_CDATA_SECTION_NODE)) + goto rollback; + break; + case XSLT_OP_NODE: + switch (node->type) { + case XML_ELEMENT_NODE: + case XML_CDATA_SECTION_NODE: + case XML_PI_NODE: + case XML_COMMENT_NODE: + case XML_TEXT_NODE: + break; + default: + goto rollback; + } + break; + } + } +found: + if (states.states != NULL) { + /* Free the rollback states */ + xmlFree(states.states); + } + return(1); +rollback: + /* got an error try to rollback */ + if (states.states == NULL) + return(0); + if (states.nbstates <= 0) { + xmlFree(states.states); + return(0); + } + states.nbstates--; + i = states.states[states.nbstates].step; + node = states.states[states.nbstates].node; +#if 0 + fprintf(stderr, ""Pop: %d, %s\n"", i, node->name); +#endif + goto restart; +} +",1," xsltTestCompMatch(xsltTransformContextPtr ctxt, xsltCompMatchPtr comp, + xmlNodePtr matchNode, const xmlChar *mode, + const xmlChar *modeURI) { + int i; + xmlNodePtr node = matchNode; + xsltStepOpPtr step, sel = NULL; + xsltStepStates states = {0, 0, NULL}; /* // may require backtrack */ + + if ((comp == NULL) || (node == NULL) || (ctxt == NULL)) { + xsltTransformError(ctxt, NULL, node, + ""xsltTestCompMatch: null arg\n""); + return(-1); + } + if (mode != NULL) { + if (comp->mode == NULL) + return(0); + /* + * both mode strings must be interned on the stylesheet dictionary + */ + if (comp->mode != mode) + return(0); + } else { + if (comp->mode != NULL) + return(0); + } + if (modeURI != NULL) { + if (comp->modeURI == NULL) + return(0); + /* + * both modeURI strings must be interned on the stylesheet dictionary + */ + if (comp->modeURI != modeURI) + return(0); + } else { + if (comp->modeURI != NULL) + return(0); + } + + i = 0; +restart: + for (;i < comp->nbStep;i++) { + step = &comp->steps[i]; + if (step->op != XSLT_OP_PREDICATE) + sel = step; + switch (step->op) { + case XSLT_OP_END: + goto found; + case XSLT_OP_ROOT: + if ((node->type == XML_DOCUMENT_NODE) || +#ifdef LIBXML_DOCB_ENABLED + (node->type == XML_DOCB_DOCUMENT_NODE) || +#endif + (node->type == XML_HTML_DOCUMENT_NODE)) + continue; + if ((node->type == XML_ELEMENT_NODE) && (node->name[0] == ' ')) + continue; + goto rollback; + case XSLT_OP_ELEM: + if (node->type != XML_ELEMENT_NODE) + goto rollback; + if (step->value == NULL) + continue; + if (step->value[0] != node->name[0]) + goto rollback; + if (!xmlStrEqual(step->value, node->name)) + goto rollback; + + /* Namespace test */ + if (node->ns == NULL) { + if (step->value2 != NULL) + goto rollback; + } else if (node->ns->href != NULL) { + if (step->value2 == NULL) + goto rollback; + if (!xmlStrEqual(step->value2, node->ns->href)) + goto rollback; + } + continue; + case XSLT_OP_ATTR: + if (node->type != XML_ATTRIBUTE_NODE) + goto rollback; + if (step->value != NULL) { + if (step->value[0] != node->name[0]) + goto rollback; + if (!xmlStrEqual(step->value, node->name)) + goto rollback; + } + /* Namespace test */ + if (node->ns == NULL) { + if (step->value2 != NULL) + goto rollback; + } else if (step->value2 != NULL) { + if (!xmlStrEqual(step->value2, node->ns->href)) + goto rollback; + } + continue; + case XSLT_OP_PARENT: + if ((node->type == XML_DOCUMENT_NODE) || + (node->type == XML_HTML_DOCUMENT_NODE) || +#ifdef LIBXML_DOCB_ENABLED + (node->type == XML_DOCB_DOCUMENT_NODE) || +#endif + (node->type == XML_NAMESPACE_DECL)) + goto rollback; + node = node->parent; + if (node == NULL) + goto rollback; + if (step->value == NULL) + continue; + if (step->value[0] != node->name[0]) + goto rollback; + if (!xmlStrEqual(step->value, node->name)) + goto rollback; + /* Namespace test */ + if (node->ns == NULL) { + if (step->value2 != NULL) + goto rollback; + } else if (node->ns->href != NULL) { + if (step->value2 == NULL) + goto rollback; + if (!xmlStrEqual(step->value2, node->ns->href)) + goto rollback; + } + continue; + case XSLT_OP_ANCESTOR: + /* TODO: implement coalescing of ANCESTOR/NODE ops */ + if (step->value == NULL) { + step = &comp->steps[i+1]; + if (step->op == XSLT_OP_ROOT) + goto found; + /* added NS, ID and KEY as a result of bug 168208 */ + if ((step->op != XSLT_OP_ELEM) && + (step->op != XSLT_OP_ALL) && + (step->op != XSLT_OP_NS) && + (step->op != XSLT_OP_ID) && + (step->op != XSLT_OP_KEY)) + goto rollback; + } + if (node == NULL) + goto rollback; + if ((node->type == XML_DOCUMENT_NODE) || + (node->type == XML_HTML_DOCUMENT_NODE) || +#ifdef LIBXML_DOCB_ENABLED + (node->type == XML_DOCB_DOCUMENT_NODE) || +#endif + (node->type == XML_NAMESPACE_DECL)) + goto rollback; + node = node->parent; + if ((step->op != XSLT_OP_ELEM) && step->op != XSLT_OP_ALL) { + xsltPatPushState(ctxt, &states, i, node); + continue; + } + i++; + if (step->value == NULL) { + xsltPatPushState(ctxt, &states, i - 1, node); + continue; + } + while (node != NULL) { + if ((node->type == XML_ELEMENT_NODE) && + (step->value[0] == node->name[0]) && + (xmlStrEqual(step->value, node->name))) { + /* Namespace test */ + if (node->ns == NULL) { + if (step->value2 == NULL) + break; + } else if (node->ns->href != NULL) { + if ((step->value2 != NULL) && + (xmlStrEqual(step->value2, node->ns->href))) + break; + } + } + node = node->parent; + } + if (node == NULL) + goto rollback; + xsltPatPushState(ctxt, &states, i - 1, node); + continue; + case XSLT_OP_ID: { + /* TODO Handle IDs decently, must be done differently */ + xmlAttrPtr id; + + if (node->type != XML_ELEMENT_NODE) + goto rollback; + + id = xmlGetID(node->doc, step->value); + if ((id == NULL) || (id->parent != node)) + goto rollback; + break; + } + case XSLT_OP_KEY: { + xmlNodeSetPtr list; + int indx; + + list = xsltGetKey(ctxt, step->value, + step->value3, step->value2); + if (list == NULL) + goto rollback; + for (indx = 0;indx < list->nodeNr;indx++) + if (list->nodeTab[indx] == node) + break; + if (indx >= list->nodeNr) + goto rollback; + break; + } + case XSLT_OP_NS: + if (node->type != XML_ELEMENT_NODE) + goto rollback; + if (node->ns == NULL) { + if (step->value != NULL) + goto rollback; + } else if (node->ns->href != NULL) { + if (step->value == NULL) + goto rollback; + if (!xmlStrEqual(step->value, node->ns->href)) + goto rollback; + } + break; + case XSLT_OP_ALL: + if (node->type != XML_ELEMENT_NODE) + goto rollback; + break; + case XSLT_OP_PREDICATE: { + /* + * When there is cascading XSLT_OP_PREDICATE or a predicate + * after an op which hasn't been optimized yet, then use a + * direct computation approach. It's not done directly + * at the beginning of the routine to filter out as much + * as possible this costly computation. + */ + if (comp->direct) { + if (states.states != NULL) { + /* Free the rollback states */ + xmlFree(states.states); + } + return(xsltTestCompMatchDirect(ctxt, comp, matchNode, + comp->nsList, comp->nsNr)); + } + + if (!xsltTestPredicateMatch(ctxt, comp, node, step, sel)) + goto rollback; + + break; + } + case XSLT_OP_PI: + if (node->type != XML_PI_NODE) + goto rollback; + if (step->value != NULL) { + if (!xmlStrEqual(step->value, node->name)) + goto rollback; + } + break; + case XSLT_OP_COMMENT: + if (node->type != XML_COMMENT_NODE) + goto rollback; + break; + case XSLT_OP_TEXT: + if ((node->type != XML_TEXT_NODE) && + (node->type != XML_CDATA_SECTION_NODE)) + goto rollback; + break; + case XSLT_OP_NODE: + switch (node->type) { + case XML_ELEMENT_NODE: + case XML_CDATA_SECTION_NODE: + case XML_PI_NODE: + case XML_COMMENT_NODE: + case XML_TEXT_NODE: + break; + default: + goto rollback; + } + break; + } + } +found: + if (states.states != NULL) { + /* Free the rollback states */ + xmlFree(states.states); + } + return(1); +rollback: + /* got an error try to rollback */ + if (states.states == NULL) + return(0); + if (states.nbstates <= 0) { + xmlFree(states.states); + return(0); + } + states.nbstates--; + i = states.states[states.nbstates].step; + node = states.states[states.nbstates].node; +#if 0 + fprintf(stderr, ""Pop: %d, %s\n"", i, node->name); +#endif + goto restart; +} +","@@ -451,11 +451,14 @@ xsltReverseCompMatch(xsltParserContextPtr ctxt, xsltCompMatchPtr comp) { + xsltCompMatchAdd(ctxt, comp, XSLT_OP_END, NULL, NULL, 0); + + /* +- * detect consecutive XSLT_OP_PREDICATE indicating a direct +- * matching should be done. ++ * Detect consecutive XSLT_OP_PREDICATE and predicates on ops which ++ * haven't been optimized yet indicating a direct matching should be done. + */ + for (i = 0;i < comp->nbStep - 1;i++) { +- if ((comp->steps[i].op == XSLT_OP_PREDICATE) && ++ xsltOp op = comp->steps[i].op; ++ ++ if ((op != XSLT_OP_ELEM) && ++ (op != XSLT_OP_ALL) && + (comp->steps[i + 1].op == XSLT_OP_PREDICATE)) { + + comp->direct = 1; +@@ -620,6 +623,280 @@ xsltTestCompMatchDirect(xsltTransformContextPtr ctxt, xsltCompMatchPtr comp, + return(0); + } + ++/** ++ * xsltTestPredicateMatch: ++ * @ctxt: a XSLT process context ++ * @comp: the precompiled pattern ++ * @node: a node ++ * @step: the predicate step ++ * @sel: the previous step ++ * ++ * Test whether the node matches the predicate ++ * ++ * Returns 1 if it matches, 0 if it doesn't and -1 in case of failure ++ */ ++static int ++xsltTestPredicateMatch(xsltTransformContextPtr ctxt, xsltCompMatchPtr comp, ++ xmlNodePtr node, xsltStepOpPtr step, ++ xsltStepOpPtr sel) { ++ xmlNodePtr oldNode; ++ xmlDocPtr doc; ++ int oldCS, oldCP; ++ int pos = 0, len = 0; ++ int isRVT; ++ int match; ++ ++ if (step->value == NULL) ++ return(0); ++ if (step->comp == NULL) ++ return(0); ++ ++ doc = node->doc; ++ if (XSLT_IS_RES_TREE_FRAG(doc)) ++ isRVT = 1; ++ else ++ isRVT = 0; ++ ++ /* ++ * Recompute contextSize and proximityPosition. ++ * ++ * TODO: Make this work for additional ops. Currently, only XSLT_OP_ELEM ++ * and XSLT_OP_ALL are supported. ++ */ ++ oldCS = ctxt->xpathCtxt->contextSize; ++ oldCP = ctxt->xpathCtxt->proximityPosition; ++ if ((sel != NULL) && ++ (sel->op == XSLT_OP_ELEM) && ++ (sel->value != NULL) && ++ (node->type == XML_ELEMENT_NODE) && ++ (node->parent != NULL)) { ++ xmlNodePtr previous; ++ int nocache = 0; ++ ++ previous = (xmlNodePtr) ++ XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr); ++ if ((previous != NULL) && ++ (previous->parent == node->parent)) { ++ /* ++ * just walk back to adjust the index ++ */ ++ int indx = 0; ++ xmlNodePtr sibling = node; ++ ++ while (sibling != NULL) { ++ if (sibling == previous) ++ break; ++ if ((sibling->type == XML_ELEMENT_NODE) && ++ (previous->name != NULL) && ++ (sibling->name != NULL) && ++ (previous->name[0] == sibling->name[0]) && ++ (xmlStrEqual(previous->name, sibling->name))) ++ { ++ if ((sel->value2 == NULL) || ++ ((sibling->ns != NULL) && ++ (xmlStrEqual(sel->value2, sibling->ns->href)))) ++ indx++; ++ } ++ sibling = sibling->prev; ++ } ++ if (sibling == NULL) { ++ /* hum going backward in document order ... */ ++ indx = 0; ++ sibling = node; ++ while (sibling != NULL) { ++ if (sibling == previous) ++ break; ++ if ((sibling->type == XML_ELEMENT_NODE) && ++ (previous->name != NULL) && ++ (sibling->name != NULL) && ++ (previous->name[0] == sibling->name[0]) && ++ (xmlStrEqual(previous->name, sibling->name))) ++ { ++ if ((sel->value2 == NULL) || ++ ((sibling->ns != NULL) && ++ (xmlStrEqual(sel->value2, ++ sibling->ns->href)))) ++ { ++ indx--; ++ } ++ } ++ sibling = sibling->next; ++ } ++ } ++ if (sibling != NULL) { ++ pos = XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) + indx; ++ /* ++ * If the node is in a Value Tree we need to ++ * save len, but cannot cache the node! ++ * (bugs 153137 and 158840) ++ */ ++ if (node->doc != NULL) { ++ len = XSLT_RUNTIME_EXTRA(ctxt, sel->lenExtra, ival); ++ if (!isRVT) { ++ XSLT_RUNTIME_EXTRA(ctxt, ++ sel->previousExtra, ptr) = node; ++ XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) = pos; ++ } ++ } ++ } else ++ pos = 0; ++ } else { ++ /* ++ * recompute the index ++ */ ++ xmlNodePtr parent = node->parent; ++ xmlNodePtr siblings = NULL; ++ ++ if (parent) siblings = parent->children; ++ ++ while (siblings != NULL) { ++ if (siblings->type == XML_ELEMENT_NODE) { ++ if (siblings == node) { ++ len++; ++ pos = len; ++ } else if ((node->name != NULL) && ++ (siblings->name != NULL) && ++ (node->name[0] == siblings->name[0]) && ++ (xmlStrEqual(node->name, siblings->name))) { ++ if ((sel->value2 == NULL) || ++ ((siblings->ns != NULL) && ++ (xmlStrEqual(sel->value2, siblings->ns->href)))) ++ len++; ++ } ++ } ++ siblings = siblings->next; ++ } ++ if ((parent == NULL) || (node->doc == NULL)) ++ nocache = 1; ++ else { ++ while (parent->parent != NULL) ++ parent = parent->parent; ++ if (((parent->type != XML_DOCUMENT_NODE) && ++ (parent->type != XML_HTML_DOCUMENT_NODE)) || ++ (parent != (xmlNodePtr) node->doc)) ++ nocache = 1; ++ } ++ } ++ if (pos != 0) { ++ ctxt->xpathCtxt->contextSize = len; ++ ctxt->xpathCtxt->proximityPosition = pos; ++ /* ++ * If the node is in a Value Tree we cannot ++ * cache it ! ++ */ ++ if ((!isRVT) && (node->doc != NULL) && ++ (nocache == 0)) { ++ XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr) = node; ++ XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) = pos; ++ XSLT_RUNTIME_EXTRA(ctxt, sel->lenExtra, ival) = len; ++ } ++ } ++ } else if ((sel != NULL) && (sel->op == XSLT_OP_ALL) && ++ (node->type == XML_ELEMENT_NODE)) { ++ xmlNodePtr previous; ++ int nocache = 0; ++ ++ previous = (xmlNodePtr) ++ XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr); ++ if ((previous != NULL) && ++ (previous->parent == node->parent)) { ++ /* ++ * just walk back to adjust the index ++ */ ++ int indx = 0; ++ xmlNodePtr sibling = node; ++ ++ while (sibling != NULL) { ++ if (sibling == previous) ++ break; ++ if (sibling->type == XML_ELEMENT_NODE) ++ indx++; ++ sibling = sibling->prev; ++ } ++ if (sibling == NULL) { ++ /* hum going backward in document order ... */ ++ indx = 0; ++ sibling = node; ++ while (sibling != NULL) { ++ if (sibling == previous) ++ break; ++ if (sibling->type == XML_ELEMENT_NODE) ++ indx--; ++ sibling = sibling->next; ++ } ++ } ++ if (sibling != NULL) { ++ pos = XSLT_RUNTIME_EXTRA(ctxt, ++ sel->indexExtra, ival) + indx; ++ /* ++ * If the node is in a Value Tree we cannot ++ * cache it ! ++ */ ++ if ((node->doc != NULL) && !isRVT) { ++ len = XSLT_RUNTIME_EXTRA(ctxt, sel->lenExtra, ival); ++ XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr) = node; ++ XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) = pos; ++ } ++ } else ++ pos = 0; ++ } else { ++ /* ++ * recompute the index ++ */ ++ xmlNodePtr parent = node->parent; ++ xmlNodePtr siblings = NULL; ++ ++ if (parent) siblings = parent->children; ++ ++ while (siblings != NULL) { ++ if (siblings->type == XML_ELEMENT_NODE) { ++ len++; ++ if (siblings == node) { ++ pos = len; ++ } ++ } ++ siblings = siblings->next; ++ } ++ if ((parent == NULL) || (node->doc == NULL)) ++ nocache = 1; ++ else { ++ while (parent->parent != NULL) ++ parent = parent->parent; ++ if (((parent->type != XML_DOCUMENT_NODE) && ++ (parent->type != XML_HTML_DOCUMENT_NODE)) || ++ (parent != (xmlNodePtr) node->doc)) ++ nocache = 1; ++ } ++ } ++ if (pos != 0) { ++ ctxt->xpathCtxt->contextSize = len; ++ ctxt->xpathCtxt->proximityPosition = pos; ++ /* ++ * If the node is in a Value Tree we cannot ++ * cache it ! ++ */ ++ if ((node->doc != NULL) && (nocache == 0) && !isRVT) { ++ XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr) = node; ++ XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) = pos; ++ XSLT_RUNTIME_EXTRA(ctxt, sel->lenExtra, ival) = len; ++ } ++ } ++ } ++ ++ oldNode = ctxt->node; ++ ctxt->node = node; ++ ++ match = xsltEvalXPathPredicate(ctxt, step->comp, comp->nsList, comp->nsNr); ++ ++ if (pos != 0) { ++ ctxt->xpathCtxt->contextSize = oldCS; ++ ctxt->xpathCtxt->proximityPosition = oldCP; ++ } ++ ctxt->node = oldNode; ++ ++ return match; ++} ++ + /** + * xsltTestCompMatch: + * @ctxt: a XSLT process context +@@ -634,9 +911,10 @@ xsltTestCompMatchDirect(xsltTransformContextPtr ctxt, xsltCompMatchPtr comp, + */ + static int + xsltTestCompMatch(xsltTransformContextPtr ctxt, xsltCompMatchPtr comp, +- xmlNodePtr node, const xmlChar *mode, ++ xmlNodePtr matchNode, const xmlChar *mode, + const xmlChar *modeURI) { + int i; ++ xmlNodePtr node = matchNode; + xsltStepOpPtr step, sel = NULL; + xsltStepStates states = {0, 0, NULL}; /* // may require backtrack */ + +@@ -854,14 +1132,9 @@ xsltTestCompMatch(xsltTransformContextPtr ctxt, xsltCompMatchPtr comp, + goto rollback; + break; + case XSLT_OP_PREDICATE: { +- xmlNodePtr oldNode; +- xmlDocPtr doc; +- int oldCS, oldCP; +- int pos = 0, len = 0; +- int isRVT; +- + /* +- * when there is cascading XSLT_OP_PREDICATE, then use a ++ * When there is cascading XSLT_OP_PREDICATE or a predicate ++ * after an op which hasn't been optimized yet, then use a + * direct computation approach. It's not done directly + * at the beginning of the routine to filter out as much + * as possible this costly computation. +@@ -871,278 +1144,14 @@ xsltTestCompMatch(xsltTransformContextPtr ctxt, xsltCompMatchPtr comp, + /* Free the rollback states */ + xmlFree(states.states); + } +- return(xsltTestCompMatchDirect(ctxt, comp, node, ++ return(xsltTestCompMatchDirect(ctxt, comp, matchNode, + comp->nsList, comp->nsNr)); + } + +- doc = node->doc; +- if (XSLT_IS_RES_TREE_FRAG(doc)) +- isRVT = 1; +- else +- isRVT = 0; +- +- /* +- * Depending on the last selection, one may need to +- * recompute contextSize and proximityPosition. +- */ +- oldCS = ctxt->xpathCtxt->contextSize; +- oldCP = ctxt->xpathCtxt->proximityPosition; +- if ((sel != NULL) && +- (sel->op == XSLT_OP_ELEM) && +- (sel->value != NULL) && +- (node->type == XML_ELEMENT_NODE) && +- (node->parent != NULL)) { +- xmlNodePtr previous; +- int nocache = 0; +- +- previous = (xmlNodePtr) +- XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr); +- if ((previous != NULL) && +- (previous->parent == node->parent)) { +- /* +- * just walk back to adjust the index +- */ +- int indx = 0; +- xmlNodePtr sibling = node; +- +- while (sibling != NULL) { +- if (sibling == previous) +- break; +- if ((sibling->type == XML_ELEMENT_NODE) && +- (previous->name != NULL) && +- (sibling->name != NULL) && +- (previous->name[0] == sibling->name[0]) && +- (xmlStrEqual(previous->name, sibling->name))) +- { +- if ((sel->value2 == NULL) || +- ((sibling->ns != NULL) && +- (xmlStrEqual(sel->value2, +- sibling->ns->href)))) +- indx++; +- } +- sibling = sibling->prev; +- } +- if (sibling == NULL) { +- /* hum going backward in document order ... */ +- indx = 0; +- sibling = node; +- while (sibling != NULL) { +- if (sibling == previous) +- break; +- if ((sibling->type == XML_ELEMENT_NODE) && +- (previous->name != NULL) && +- (sibling->name != NULL) && +- (previous->name[0] == sibling->name[0]) && +- (xmlStrEqual(previous->name, sibling->name))) +- { +- if ((sel->value2 == NULL) || +- ((sibling->ns != NULL) && +- (xmlStrEqual(sel->value2, +- sibling->ns->href)))) +- { +- indx--; +- } +- } +- sibling = sibling->next; +- } +- } +- if (sibling != NULL) { +- pos = XSLT_RUNTIME_EXTRA(ctxt, +- sel->indexExtra, ival) + indx; +- /* +- * If the node is in a Value Tree we need to +- * save len, but cannot cache the node! +- * (bugs 153137 and 158840) +- */ +- if (node->doc != NULL) { +- len = XSLT_RUNTIME_EXTRA(ctxt, +- sel->lenExtra, ival); +- if (!isRVT) { +- XSLT_RUNTIME_EXTRA(ctxt, +- sel->previousExtra, ptr) = node; +- XSLT_RUNTIME_EXTRA(ctxt, +- sel->indexExtra, ival) = pos; +- } +- } +- } else +- pos = 0; +- } else { +- /* +- * recompute the index +- */ +- xmlNodePtr parent = node->parent; +- xmlNodePtr siblings = NULL; +- +- if (parent) siblings = parent->children; +- +- while (siblings != NULL) { +- if (siblings->type == XML_ELEMENT_NODE) { +- if (siblings == node) { +- len++; +- pos = len; +- } else if ((node->name != NULL) && +- (siblings->name != NULL) && +- (node->name[0] == siblings->name[0]) && +- (xmlStrEqual(node->name, siblings->name))) { +- if ((sel->value2 == NULL) || +- ((siblings->ns != NULL) && +- (xmlStrEqual(sel->value2, +- siblings->ns->href)))) +- len++; +- } +- } +- siblings = siblings->next; +- } +- if ((parent == NULL) || (node->doc == NULL)) +- nocache = 1; +- else { +- while (parent->parent != NULL) +- parent = parent->parent; +- if (((parent->type != XML_DOCUMENT_NODE) && +- (parent->type != XML_HTML_DOCUMENT_NODE)) || +- (parent != (xmlNodePtr) node->doc)) +- nocache = 1; +- } +- } +- if (pos != 0) { +- ctxt->xpathCtxt->contextSize = len; +- ctxt->xpathCtxt->proximityPosition = pos; +- /* +- * If the node is in a Value Tree we cannot +- * cache it ! +- */ +- if ((!isRVT) && (node->doc != NULL) && +- (nocache == 0)) { +- XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr) = +- node; +- XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) = +- pos; +- XSLT_RUNTIME_EXTRA(ctxt, sel->lenExtra, ival) = +- len; +- } +- } +- } else if ((sel != NULL) && (sel->op == XSLT_OP_ALL) && +- (node->type == XML_ELEMENT_NODE)) { +- xmlNodePtr previous; +- int nocache = 0; +- +- previous = (xmlNodePtr) +- XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr); +- if ((previous != NULL) && +- (previous->parent == node->parent)) { +- /* +- * just walk back to adjust the index +- */ +- int indx = 0; +- xmlNodePtr sibling = node; +- +- while (sibling != NULL) { +- if (sibling == previous) +- break; +- if (sibling->type == XML_ELEMENT_NODE) +- indx++; +- sibling = sibling->prev; +- } +- if (sibling == NULL) { +- /* hum going backward in document order ... */ +- indx = 0; +- sibling = node; +- while (sibling != NULL) { +- if (sibling == previous) +- break; +- if (sibling->type == XML_ELEMENT_NODE) +- indx--; +- sibling = sibling->next; +- } +- } +- if (sibling != NULL) { +- pos = XSLT_RUNTIME_EXTRA(ctxt, +- sel->indexExtra, ival) + indx; +- /* +- * If the node is in a Value Tree we cannot +- * cache it ! +- */ +- if ((node->doc != NULL) && !isRVT) { +- len = XSLT_RUNTIME_EXTRA(ctxt, +- sel->lenExtra, ival); +- XSLT_RUNTIME_EXTRA(ctxt, +- sel->previousExtra, ptr) = node; +- XSLT_RUNTIME_EXTRA(ctxt, +- sel->indexExtra, ival) = pos; +- } +- } else +- pos = 0; +- } else { +- /* +- * recompute the index +- */ +- xmlNodePtr parent = node->parent; +- xmlNodePtr siblings = NULL; +- +- if (parent) siblings = parent->children; +- +- while (siblings != NULL) { +- if (siblings->type == XML_ELEMENT_NODE) { +- len++; +- if (siblings == node) { +- pos = len; +- } +- } +- siblings = siblings->next; +- } +- if ((parent == NULL) || (node->doc == NULL)) +- nocache = 1; +- else { +- while (parent->parent != NULL) +- parent = parent->parent; +- if (((parent->type != XML_DOCUMENT_NODE) && +- (parent->type != XML_HTML_DOCUMENT_NODE)) || +- (parent != (xmlNodePtr) node->doc)) +- nocache = 1; +- } +- } +- if (pos != 0) { +- ctxt->xpathCtxt->contextSize = len; +- ctxt->xpathCtxt->proximityPosition = pos; +- /* +- * If the node is in a Value Tree we cannot +- * cache it ! +- */ +- if ((node->doc != NULL) && (nocache == 0) && !isRVT) { +- XSLT_RUNTIME_EXTRA(ctxt, sel->previousExtra, ptr) = +- node; +- XSLT_RUNTIME_EXTRA(ctxt, sel->indexExtra, ival) = +- pos; +- XSLT_RUNTIME_EXTRA(ctxt, sel->lenExtra, ival) = +- len; +- } +- } +- } +- oldNode = ctxt->node; +- ctxt->node = node; +- +- if (step->value == NULL) +- goto wrong_index; +- if (step->comp == NULL) +- goto wrong_index; +- +- if (!xsltEvalXPathPredicate(ctxt, step->comp, comp->nsList, +- comp->nsNr)) +- goto wrong_index; ++ if (!xsltTestPredicateMatch(ctxt, comp, node, step, sel)) ++ goto rollback; + +- if (pos != 0) { +- ctxt->xpathCtxt->contextSize = oldCS; +- ctxt->xpathCtxt->proximityPosition = oldCP; +- } +- ctxt->node = oldNode; + break; +-wrong_index: +- if (pos != 0) { +- ctxt->xpathCtxt->contextSize = oldCS; +- ctxt->xpathCtxt->proximityPosition = oldCP; +- } +- ctxt->node = oldNode; +- goto rollback; + } + case XSLT_OP_PI: + if (node->type != XML_PI_NODE) +@@ -1424,6 +1433,7 @@ xsltCompileIdKeyPattern(xsltParserContextPtr ctxt, xmlChar *name, + if (CUR != ',') { + xsltTransformError(NULL, NULL, NULL, + ""xsltCompileIdKeyPattern : , expected\n""); ++ xmlFree(lit); + ctxt->error = 1; + return; + } +@@ -2080,9 +2090,34 @@ xsltAddTemplate(xsltStylesheetPtr style, xsltTemplatePtr cur, + const xmlChar *name = NULL; + float priority; /* the priority */ + +- if ((style == NULL) || (cur == NULL) || (cur->match == NULL)) ++ if ((style == NULL) || (cur == NULL)) + return(-1); + ++ /* Register named template */ ++ if (cur->name != NULL) { ++ if (style->namedTemplates == NULL) { ++ style->namedTemplates = xmlHashCreate(10); ++ if (style->namedTemplates == NULL) ++ return(-1); ++ } ++ else { ++ void *dup = xmlHashLookup2(style->namedTemplates, cur->name, ++ cur->nameURI); ++ if (dup != NULL) { ++ xsltTransformError(NULL, style, NULL, ++ ""xsl:template: error duplicate name '%s'\n"", ++ cur->name); ++ style->errors++; ++ return(-1); ++ } ++ } ++ ++ xmlHashAddEntry2(style->namedTemplates, cur->name, cur->nameURI, cur); ++ } ++ ++ if (cur->match == NULL) ++ return(0); ++ + priority = cur->priority; + pat = xsltCompilePatternInternal(cur->match, style->doc, cur->elem, + style, NULL, 1); +@@ -2552,5 +2587,7 @@ xsltFreeTemplateHashes(xsltStylesheetPtr style) { + xsltFreeCompMatchList(style->piMatch); + if (style->commentMatch != NULL) + xsltFreeCompMatchList(style->commentMatch); ++ if (style->namedTemplates != NULL) ++ xmlHashFree(style->namedTemplates, NULL); + } + ",4338,4669,6144 +17240,"bool venc_dev::venc_set_param(void *paramData,OMX_INDEXTYPE index ) +{ + DEBUG_PRINT_LOW(""venc_set_param:: venc-720p""); + struct v4l2_format fmt; + struct v4l2_requestbuffers bufreq; + int ret; + + switch ((int)index) { + case OMX_IndexParamPortDefinition: + { + OMX_PARAM_PORTDEFINITIONTYPE *portDefn; + portDefn = (OMX_PARAM_PORTDEFINITIONTYPE *) paramData; + DEBUG_PRINT_LOW(""venc_set_param: OMX_IndexParamPortDefinition""); + + if (portDefn->nPortIndex == PORT_INDEX_IN) { + if (!venc_set_encode_framerate(portDefn->format.video.xFramerate, 0)) { + return false; + } + + if (!venc_set_color_format(portDefn->format.video.eColorFormat)) { + return false; + } + if (enable_mv_narrow_searchrange && + (m_sVenc_cfg.input_width * m_sVenc_cfg.input_height) >= + (OMX_CORE_1080P_WIDTH * OMX_CORE_1080P_HEIGHT)) { + if (venc_set_searchrange() == false) { + DEBUG_PRINT_ERROR(""ERROR: Failed to set search range""); + } + } + if (m_sVenc_cfg.input_height != portDefn->format.video.nFrameHeight || + m_sVenc_cfg.input_width != portDefn->format.video.nFrameWidth) { + DEBUG_PRINT_LOW(""Basic parameter has changed""); + m_sVenc_cfg.input_height = portDefn->format.video.nFrameHeight; + m_sVenc_cfg.input_width = portDefn->format.video.nFrameWidth; + fmt.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; + fmt.fmt.pix_mp.height = m_sVenc_cfg.input_height; + fmt.fmt.pix_mp.width = m_sVenc_cfg.input_width; + fmt.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12; + fmt.fmt.pix_mp.colorspace = V4L2_COLORSPACE_BT878; + + if (ioctl(m_nDriver_fd, VIDIOC_S_FMT, &fmt)) { + DEBUG_PRINT_ERROR(""VIDIOC_S_FMT OUTPUT_MPLANE Failed""); + hw_overload = errno == EBUSY; + return false; + } + + m_sInput_buff_property.datasize=fmt.fmt.pix_mp.plane_fmt[0].sizeimage; + bufreq.memory = V4L2_MEMORY_USERPTR; + bufreq.count = portDefn->nBufferCountActual; + bufreq.type=V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; + + if (ioctl(m_nDriver_fd,VIDIOC_REQBUFS, &bufreq)) { + DEBUG_PRINT_ERROR(""VIDIOC_REQBUFS OUTPUT_MPLANE Failed""); + return false; + } + + if (bufreq.count == portDefn->nBufferCountActual) + m_sInput_buff_property.mincount = m_sInput_buff_property.actualcount = bufreq.count; + + if (portDefn->nBufferCountActual >= m_sInput_buff_property.mincount) + m_sInput_buff_property.actualcount = portDefn->nBufferCountActual; + } + + DEBUG_PRINT_LOW(""input: actual: %u, min: %u, count_req: %u"", + (unsigned int)portDefn->nBufferCountActual, (unsigned int)m_sInput_buff_property.mincount, bufreq.count); + if (m_sVenc_cfg.input_width * m_sVenc_cfg.input_height >= 3840 * 2160) { + if (venc_set_perf_mode(V4L2_MPEG_VIDC_VIDEO_PERF_POWER_SAVE) == false) { + DEBUG_PRINT_ERROR(""ERROR: Failed to set Power save mode""); + } + } + } else if (portDefn->nPortIndex == PORT_INDEX_OUT) { + m_sVenc_cfg.dvs_height = portDefn->format.video.nFrameHeight; + m_sVenc_cfg.dvs_width = portDefn->format.video.nFrameWidth; + fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; + fmt.fmt.pix_mp.height = m_sVenc_cfg.dvs_height; + fmt.fmt.pix_mp.width = m_sVenc_cfg.dvs_width; + fmt.fmt.pix_mp.pixelformat = m_sVenc_cfg.codectype; + + if (ioctl(m_nDriver_fd, VIDIOC_S_FMT, &fmt)) { + DEBUG_PRINT_ERROR(""VIDIOC_S_FMT CAPTURE_MPLANE Failed""); + hw_overload = errno == EBUSY; + return false; + } + + m_sOutput_buff_property.datasize = fmt.fmt.pix_mp.plane_fmt[0].sizeimage; + + if (!venc_set_target_bitrate(portDefn->format.video.nBitrate, 0)) { + return false; + } + + m_sOutput_buff_property.actualcount = portDefn->nBufferCountActual; + bufreq.memory = V4L2_MEMORY_USERPTR; + bufreq.count = portDefn->nBufferCountActual; + bufreq.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; + + if (ioctl(m_nDriver_fd,VIDIOC_REQBUFS, &bufreq)) { + DEBUG_PRINT_ERROR(""ERROR: Request for setting o/p buffer count failed: requested: %u, current: %u"", + (unsigned int)portDefn->nBufferCountActual, (unsigned int)m_sOutput_buff_property.actualcount); + return false; + } + + if (bufreq.count == portDefn->nBufferCountActual) + m_sOutput_buff_property.mincount = m_sOutput_buff_property.actualcount = bufreq.count; + + if (portDefn->nBufferCountActual >= m_sOutput_buff_property.mincount) + m_sOutput_buff_property.actualcount = portDefn->nBufferCountActual; + + if (num_planes > 1) + extradata_info.count = m_sOutput_buff_property.actualcount; + + DEBUG_PRINT_LOW(""Output: actual: %u, min: %u, count_req: %u"", + (unsigned int)portDefn->nBufferCountActual, (unsigned int)m_sOutput_buff_property.mincount, bufreq.count); + } else { + DEBUG_PRINT_ERROR(""ERROR: Invalid Port Index for OMX_IndexParamPortDefinition""); + } + + break; + } + case OMX_IndexParamVideoPortFormat: + { + OMX_VIDEO_PARAM_PORTFORMATTYPE *portFmt; + portFmt =(OMX_VIDEO_PARAM_PORTFORMATTYPE *)paramData; + DEBUG_PRINT_LOW(""venc_set_param: OMX_IndexParamVideoPortFormat""); + + if (portFmt->nPortIndex == (OMX_U32) PORT_INDEX_IN) { + if (!venc_set_color_format(portFmt->eColorFormat)) { + return false; + } + } else if (portFmt->nPortIndex == (OMX_U32) PORT_INDEX_OUT) { + if (!venc_set_encode_framerate(portFmt->xFramerate, 0)) { + return false; + } + } else { + DEBUG_PRINT_ERROR(""ERROR: Invalid Port Index for OMX_IndexParamVideoPortFormat""); + } + + break; + } + case OMX_IndexParamVideoBitrate: + { + OMX_VIDEO_PARAM_BITRATETYPE* pParam; + pParam = (OMX_VIDEO_PARAM_BITRATETYPE*)paramData; + DEBUG_PRINT_LOW(""venc_set_param: OMX_IndexParamVideoBitrate""); + + if (pParam->nPortIndex == (OMX_U32) PORT_INDEX_OUT) { + if (!venc_set_target_bitrate(pParam->nTargetBitrate, 0)) { + DEBUG_PRINT_ERROR(""ERROR: Target Bit Rate setting failed""); + return false; + } + + if (!venc_set_ratectrl_cfg(pParam->eControlRate)) { + DEBUG_PRINT_ERROR(""ERROR: Rate Control setting failed""); + return false; + } + } else { + DEBUG_PRINT_ERROR(""ERROR: Invalid Port Index for OMX_IndexParamVideoBitrate""); + } + + break; + } + case OMX_IndexParamVideoMpeg4: + { + OMX_VIDEO_PARAM_MPEG4TYPE* pParam; + OMX_U32 bFrames = 0; + + pParam = (OMX_VIDEO_PARAM_MPEG4TYPE*)paramData; + DEBUG_PRINT_LOW(""venc_set_param: OMX_IndexParamVideoMpeg4""); + + if (pParam->nPortIndex == (OMX_U32) PORT_INDEX_OUT) { + if (!venc_set_voptiming_cfg(pParam->nTimeIncRes)) { + DEBUG_PRINT_ERROR(""ERROR: Request for setting vop_timing failed""); + return false; + } + + m_profile_set = false; + m_level_set = false; + + if (!venc_set_profile_level (pParam->eProfile, pParam->eLevel)) { + DEBUG_PRINT_ERROR(""ERROR: Unsuccessful in updating Profile and level""); + return false; + } else { + if (pParam->eProfile == OMX_VIDEO_MPEG4ProfileAdvancedSimple) { + if (pParam->nBFrames) { + bFrames = pParam->nBFrames; + } + } else { + if (pParam->nBFrames) { + DEBUG_PRINT_ERROR(""Warning: B frames not supported""); + bFrames = 0; + } + } + } + + if (!venc_set_intra_period (pParam->nPFrames,bFrames)) { + DEBUG_PRINT_ERROR(""ERROR: Request for setting intra period failed""); + return false; + } + + if (!venc_set_multislice_cfg(OMX_IndexParamVideoMpeg4,pParam->nSliceHeaderSpacing)) { + DEBUG_PRINT_ERROR(""ERROR: Unsuccessful in updating slice_config""); + return false; + } + } else { + DEBUG_PRINT_ERROR(""ERROR: Invalid Port Index for OMX_IndexParamVideoMpeg4""); + } + + break; + } + case OMX_IndexParamVideoH263: + { + OMX_VIDEO_PARAM_H263TYPE* pParam = (OMX_VIDEO_PARAM_H263TYPE*)paramData; + DEBUG_PRINT_LOW(""venc_set_param: OMX_IndexParamVideoH263""); + OMX_U32 bFrames = 0; + + if (pParam->nPortIndex == (OMX_U32) PORT_INDEX_OUT) { + m_profile_set = false; + m_level_set = false; + + if (!venc_set_profile_level (pParam->eProfile, pParam->eLevel)) { + DEBUG_PRINT_ERROR(""ERROR: Unsuccessful in updating Profile and level""); + return false; + } + + if (pParam->nBFrames) + DEBUG_PRINT_ERROR(""WARNING: B frame not supported for H.263""); + + if (venc_set_intra_period (pParam->nPFrames, bFrames) == false) { + DEBUG_PRINT_ERROR(""ERROR: Request for setting intra period failed""); + return false; + } + } else { + DEBUG_PRINT_ERROR(""ERROR: Invalid Port Index for OMX_IndexParamVideoH263""); + } + + break; + } + case OMX_IndexParamVideoAvc: + { + DEBUG_PRINT_LOW(""venc_set_param:OMX_IndexParamVideoAvc""); + OMX_VIDEO_PARAM_AVCTYPE* pParam = (OMX_VIDEO_PARAM_AVCTYPE*)paramData; + OMX_U32 bFrames = 0; + + if (pParam->nPortIndex == (OMX_U32) PORT_INDEX_OUT) { + DEBUG_PRINT_LOW(""pParam->eProfile :%d ,pParam->eLevel %d"", + pParam->eProfile,pParam->eLevel); + + m_profile_set = false; + m_level_set = false; + + if (!venc_set_profile_level (pParam->eProfile,pParam->eLevel)) { + DEBUG_PRINT_ERROR(""ERROR: Unsuccessful in updating Profile and level %d, %d"", + pParam->eProfile, pParam->eLevel); + return false; + } else { + if ((pParam->eProfile != OMX_VIDEO_AVCProfileBaseline) && + (pParam->eProfile != (OMX_VIDEO_AVCPROFILETYPE) QOMX_VIDEO_AVCProfileConstrainedBaseline)) { + if (pParam->nBFrames) { + bFrames = pParam->nBFrames; + } + } else { + if (pParam->nBFrames) { + DEBUG_PRINT_ERROR(""Warning: B frames not supported""); + bFrames = 0; + } + } + } + + if (!venc_set_intra_period (pParam->nPFrames, bFrames)) { + DEBUG_PRINT_ERROR(""ERROR: Request for setting intra period failed""); + return false; + } + + if (!venc_set_entropy_config (pParam->bEntropyCodingCABAC, pParam->nCabacInitIdc)) { + DEBUG_PRINT_ERROR(""ERROR: Request for setting Entropy failed""); + return false; + } + + if (!venc_set_inloop_filter (pParam->eLoopFilterMode)) { + DEBUG_PRINT_ERROR(""ERROR: Request for setting Inloop filter failed""); + return false; + } + + if (!venc_set_multislice_cfg(OMX_IndexParamVideoAvc, pParam->nSliceHeaderSpacing)) { + DEBUG_PRINT_ERROR(""WARNING: Unsuccessful in updating slice_config""); + return false; + } + } else { + DEBUG_PRINT_ERROR(""ERROR: Invalid Port Index for OMX_IndexParamVideoAvc""); + } + + break; + } + case (OMX_INDEXTYPE)OMX_IndexParamVideoVp8: + { + DEBUG_PRINT_LOW(""venc_set_param:OMX_IndexParamVideoVp8""); + OMX_VIDEO_PARAM_VP8TYPE* pParam = (OMX_VIDEO_PARAM_VP8TYPE*)paramData; + if (!venc_set_profile_level (pParam->eProfile, pParam->eLevel)) { + DEBUG_PRINT_ERROR(""ERROR: Unsuccessful in updating Profile and level %d, %d"", + pParam->eProfile, pParam->eLevel); + return false; + } + if(venc_set_vpx_error_resilience(pParam->bErrorResilientMode) == false) { + DEBUG_PRINT_ERROR(""ERROR: Failed to set vpx error resilience""); + return false; + } + if(!venc_set_ltrmode(1, 1)) { + DEBUG_PRINT_ERROR(""ERROR: Failed to enable ltrmode""); + return false; + } + + if (m_codec == OMX_VIDEO_CodingVP8) { + DEBUG_PRINT_LOW(""Disable Hier-P as LTR is being set""); + if (!venc_set_hier_layers(QOMX_HIERARCHICALCODING_P, 0)) { + DEBUG_PRINT_ERROR(""Disabling Hier P count failed""); + } + } + + break; + } + case (OMX_INDEXTYPE)OMX_IndexParamVideoHevc: + { + DEBUG_PRINT_LOW(""venc_set_param:OMX_IndexParamVideoHevc""); + OMX_VIDEO_PARAM_HEVCTYPE* pParam = (OMX_VIDEO_PARAM_HEVCTYPE*)paramData; + if (!venc_set_profile_level (pParam->eProfile, pParam->eLevel)) { + DEBUG_PRINT_ERROR(""ERROR: Unsuccessful in updating Profile and level %d, %d"", + pParam->eProfile, pParam->eLevel); + return false; + } + if (!venc_set_inloop_filter(OMX_VIDEO_AVCLoopFilterEnable)) + DEBUG_PRINT_HIGH(""WARN: Request for setting Inloop filter failed for HEVC encoder""); + + break; + } + case OMX_IndexParamVideoIntraRefresh: + { + DEBUG_PRINT_LOW(""venc_set_param:OMX_IndexParamVideoIntraRefresh""); + OMX_VIDEO_PARAM_INTRAREFRESHTYPE *intra_refresh = + (OMX_VIDEO_PARAM_INTRAREFRESHTYPE *)paramData; + + if (intra_refresh->nPortIndex == (OMX_U32) PORT_INDEX_OUT) { + if (venc_set_intra_refresh(intra_refresh->eRefreshMode, intra_refresh->nCirMBs) == false) { + DEBUG_PRINT_ERROR(""ERROR: Setting Intra refresh failed""); + return false; + } + } else { + DEBUG_PRINT_ERROR(""ERROR: Invalid Port Index for OMX_IndexParamVideoIntraRefresh""); + } + + break; + } + case OMX_IndexParamVideoErrorCorrection: + { + DEBUG_PRINT_LOW(""venc_set_param:OMX_IndexParamVideoErrorCorrection""); + OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE *error_resilience = + (OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE *)paramData; + + if (error_resilience->nPortIndex == (OMX_U32) PORT_INDEX_OUT) { + if (venc_set_error_resilience(error_resilience) == false) { + DEBUG_PRINT_ERROR(""ERROR: Setting Intra refresh failed""); + return false; + } + } else { + DEBUG_PRINT_ERROR(""ERROR: Invalid Port Index for OMX_IndexParamVideoErrorCorrection""); + } + + break; + } + case OMX_IndexParamVideoProfileLevelCurrent: + { + DEBUG_PRINT_LOW(""venc_set_param:OMX_IndexParamVideoProfileLevelCurrent""); + OMX_VIDEO_PARAM_PROFILELEVELTYPE *profile_level = + (OMX_VIDEO_PARAM_PROFILELEVELTYPE *)paramData; + + if (profile_level->nPortIndex == (OMX_U32) PORT_INDEX_OUT) { + m_profile_set = false; + m_level_set = false; + + if (!venc_set_profile_level (profile_level->eProfile, + profile_level->eLevel)) { + DEBUG_PRINT_ERROR(""WARNING: Unsuccessful in updating Profile and level""); + return false; + } + } else { + DEBUG_PRINT_ERROR(""ERROR: Invalid Port Index for OMX_IndexParamVideoProfileLevelCurrent""); + } + + break; + } + case OMX_IndexParamVideoQuantization: + { + DEBUG_PRINT_LOW(""venc_set_param:OMX_IndexParamVideoQuantization""); + OMX_VIDEO_PARAM_QUANTIZATIONTYPE *session_qp = + (OMX_VIDEO_PARAM_QUANTIZATIONTYPE *)paramData; + if (session_qp->nPortIndex == (OMX_U32) PORT_INDEX_OUT) { + if (venc_set_session_qp (session_qp->nQpI, + session_qp->nQpP, + session_qp->nQpB) == false) { + DEBUG_PRINT_ERROR(""ERROR: Setting Session QP failed""); + return false; + } + } else { + DEBUG_PRINT_ERROR(""ERROR: Invalid Port Index for OMX_IndexParamVideoQuantization""); + } + + break; + } + case QOMX_IndexParamVideoInitialQp: + { + QOMX_EXTNINDEX_VIDEO_INITIALQP * initqp = + (QOMX_EXTNINDEX_VIDEO_INITIALQP *)paramData; + if (initqp->bEnableInitQp) { + DEBUG_PRINT_LOW(""Enable initial QP: %d"", (int)initqp->bEnableInitQp); + if(venc_enable_initial_qp(initqp) == false) { + DEBUG_PRINT_ERROR(""ERROR: Failed to enable initial QP""); + return OMX_ErrorUnsupportedSetting; + } + } else + DEBUG_PRINT_ERROR(""ERROR: setting QOMX_IndexParamVideoEnableInitialQp""); + break; + } + case OMX_QcomIndexParamVideoQPRange: + { + DEBUG_PRINT_LOW(""venc_set_param:OMX_QcomIndexParamVideoQPRange""); + OMX_QCOM_VIDEO_PARAM_QPRANGETYPE *session_qp_range = + (OMX_QCOM_VIDEO_PARAM_QPRANGETYPE *)paramData; + + if(session_qp_range->nPortIndex == (OMX_U32)PORT_INDEX_OUT) { + if(venc_set_session_qp_range (session_qp_range->minQP, + session_qp_range->maxQP) == false) { + DEBUG_PRINT_ERROR(""ERROR: Setting QP Range[%u %u] failed"", + (unsigned int)session_qp_range->minQP, (unsigned int)session_qp_range->maxQP); + return false; + } else { + session_qp_values.minqp = session_qp_range->minQP; + session_qp_values.maxqp = session_qp_range->maxQP; + } + } else { + DEBUG_PRINT_ERROR(""ERROR: Invalid Port Index for OMX_QcomIndexParamVideoQPRange""); + } + + break; + } + case OMX_QcomIndexEnableSliceDeliveryMode: + { + QOMX_EXTNINDEX_PARAMTYPE* pParam = + (QOMX_EXTNINDEX_PARAMTYPE*)paramData; + + if (pParam->nPortIndex == PORT_INDEX_OUT) { + if (venc_set_slice_delivery_mode(pParam->bEnable) == false) { + DEBUG_PRINT_ERROR(""Setting slice delivery mode failed""); + return OMX_ErrorUnsupportedSetting; + } + } else { + DEBUG_PRINT_ERROR(""OMX_QcomIndexEnableSliceDeliveryMode "" + ""called on wrong port(%u)"", (unsigned int)pParam->nPortIndex); + return OMX_ErrorBadPortIndex; + } + + break; + } + case OMX_ExtraDataVideoEncoderSliceInfo: + { + DEBUG_PRINT_LOW(""venc_set_param: OMX_ExtraDataVideoEncoderSliceInfo""); + OMX_BOOL extra_data = *(OMX_BOOL *)(paramData); + + if (venc_set_extradata(OMX_ExtraDataVideoEncoderSliceInfo, extra_data) == false) { + DEBUG_PRINT_ERROR(""ERROR: Setting OMX_ExtraDataVideoEncoderSliceInfo failed""); + return false; + } + + extradata = true; + break; + } + case OMX_ExtraDataVideoEncoderMBInfo: + { + DEBUG_PRINT_LOW(""venc_set_param: OMX_ExtraDataVideoEncoderMBInfo""); + OMX_BOOL extra_data = *(OMX_BOOL *)(paramData); + + if (venc_set_extradata(OMX_ExtraDataVideoEncoderMBInfo, extra_data) == false) { + DEBUG_PRINT_ERROR(""ERROR: Setting OMX_ExtraDataVideoEncoderMBInfo failed""); + return false; + } + + extradata = true; + break; + } + case OMX_QcomIndexParamSequenceHeaderWithIDR: + { + PrependSPSPPSToIDRFramesParams * pParam = + (PrependSPSPPSToIDRFramesParams *)paramData; + + DEBUG_PRINT_LOW(""set inband sps/pps: %d"", pParam->bEnable); + if(venc_set_inband_video_header(pParam->bEnable) == false) { + DEBUG_PRINT_ERROR(""ERROR: set inband sps/pps failed""); + return OMX_ErrorUnsupportedSetting; + } + + break; + } + case OMX_QcomIndexParamH264AUDelimiter: + { + OMX_QCOM_VIDEO_CONFIG_H264_AUD * pParam = + (OMX_QCOM_VIDEO_CONFIG_H264_AUD *)paramData; + + DEBUG_PRINT_LOW(""set AU delimiters: %d"", pParam->bEnable); + if(venc_set_au_delimiter(pParam->bEnable) == false) { + DEBUG_PRINT_ERROR(""ERROR: set H264 AU delimiter failed""); + return OMX_ErrorUnsupportedSetting; + } + + break; + } + case OMX_QcomIndexHierarchicalStructure: + { + QOMX_VIDEO_HIERARCHICALLAYERS* pParam = + (QOMX_VIDEO_HIERARCHICALLAYERS*)paramData; + + if (pParam->nPortIndex == PORT_INDEX_OUT) { + if (!venc_set_hier_layers(pParam->eHierarchicalCodingType, pParam->nNumLayers)) { + DEBUG_PRINT_ERROR(""Setting Hier P count failed""); + return false; + } + } else { + DEBUG_PRINT_ERROR(""OMX_QcomIndexHierarchicalStructure called on wrong port(%d)"", (int)pParam->nPortIndex); + return false; + } + + if (m_codec == OMX_VIDEO_CodingVP8) { + DEBUG_PRINT_LOW(""Disable LTR as HIER-P is being set""); + if(!venc_set_ltrmode(0, 1)) { + DEBUG_PRINT_ERROR(""ERROR: Failed to disable ltrmode""); + } + } + break; + } + case OMX_QcomIndexParamPerfLevel: + { + OMX_QCOM_VIDEO_PARAM_PERF_LEVEL *pParam = + (OMX_QCOM_VIDEO_PARAM_PERF_LEVEL *)paramData; + DEBUG_PRINT_LOW(""Set perf level: %d"", pParam->ePerfLevel); + if(!venc_set_perf_level(pParam->ePerfLevel)) { + DEBUG_PRINT_ERROR(""ERROR: Failed to set perf level to %d"", pParam->ePerfLevel); + return false; + } else { + performance_level.perflevel = (unsigned int) pParam->ePerfLevel; + } + break; + } + case OMX_QcomIndexParamH264VUITimingInfo: + { + OMX_QCOM_VIDEO_PARAM_VUI_TIMING_INFO *pParam = + (OMX_QCOM_VIDEO_PARAM_VUI_TIMING_INFO *)paramData; + DEBUG_PRINT_LOW(""Set VUI timing info: %d"", pParam->bEnable); + if(venc_set_vui_timing_info(pParam->bEnable) == false) { + DEBUG_PRINT_ERROR(""ERROR: Failed to set vui timing info to %d"", pParam->bEnable); + return false; + } else { + vui_timing_info.enabled = (unsigned int) pParam->bEnable; + } + break; + } + case OMX_QcomIndexParamPeakBitrate: + { + OMX_QCOM_VIDEO_PARAM_PEAK_BITRATE *pParam = + (OMX_QCOM_VIDEO_PARAM_PEAK_BITRATE *)paramData; + DEBUG_PRINT_LOW(""Set peak bitrate: %u"", (unsigned int)pParam->nPeakBitrate); + if(venc_set_peak_bitrate(pParam->nPeakBitrate) == false) { + DEBUG_PRINT_ERROR(""ERROR: Failed to set peak bitrate to %u"", (unsigned int)pParam->nPeakBitrate); + return false; + } else { + peak_bitrate.peakbitrate = (unsigned int) pParam->nPeakBitrate; + } + break; + } + case OMX_QcomIndexParamSetMVSearchrange: + { + DEBUG_PRINT_LOW(""venc_set_config: OMX_QcomIndexParamSetMVSearchrange""); + is_searchrange_set = true; + if (!venc_set_searchrange()) { + DEBUG_PRINT_ERROR(""ERROR: Failed to set search range""); + return false; + } + } + break; + case OMX_QcomIndexParamVideoLTRCount: + { + DEBUG_PRINT_LOW(""venc_set_param: OMX_QcomIndexParamVideoLTRCount""); + OMX_QCOM_VIDEO_PARAM_LTRCOUNT_TYPE* pParam = + (OMX_QCOM_VIDEO_PARAM_LTRCOUNT_TYPE*)paramData; + if (pParam->nCount > 0) { + if (venc_set_ltrmode(1, pParam->nCount) == false) { + DEBUG_PRINT_ERROR(""ERROR: Enable LTR mode failed""); + return false; + } + } else { + if (venc_set_ltrmode(0, 0) == false) { + DEBUG_PRINT_ERROR(""ERROR: Disable LTR mode failed""); + return false; + } + } + break; + } + case OMX_QcomIndexParamVideoHybridHierpMode: + { + QOMX_EXTNINDEX_VIDEO_HYBRID_HP_MODE* pParam = + (QOMX_EXTNINDEX_VIDEO_HYBRID_HP_MODE*)paramData; + + if (!venc_set_hybrid_hierp(pParam->nHpLayers)) { + DEBUG_PRINT_ERROR(""Setting hybrid Hier-P mode failed""); + return OMX_ErrorUnsupportedSetting; + } + break; + } + case OMX_IndexParamVideoSliceFMO: + default: + DEBUG_PRINT_ERROR(""ERROR: Unsupported parameter in venc_set_param: %u"", + index); + break; + } + + return true; +} +",0,"bool venc_dev::venc_set_param(void *paramData,OMX_INDEXTYPE index ) +{ + DEBUG_PRINT_LOW(""venc_set_param:: venc-720p""); + struct v4l2_format fmt; + struct v4l2_requestbuffers bufreq; + int ret; + + switch ((int)index) { + case OMX_IndexParamPortDefinition: + { + OMX_PARAM_PORTDEFINITIONTYPE *portDefn; + portDefn = (OMX_PARAM_PORTDEFINITIONTYPE *) paramData; + DEBUG_PRINT_LOW(""venc_set_param: OMX_IndexParamPortDefinition""); + + if (portDefn->nPortIndex == PORT_INDEX_IN) { + if (!venc_set_encode_framerate(portDefn->format.video.xFramerate, 0)) { + return false; + } + + if (!venc_set_color_format(portDefn->format.video.eColorFormat)) { + return false; + } + if (enable_mv_narrow_searchrange && + (m_sVenc_cfg.input_width * m_sVenc_cfg.input_height) >= + (OMX_CORE_1080P_WIDTH * OMX_CORE_1080P_HEIGHT)) { + if (venc_set_searchrange() == false) { + DEBUG_PRINT_ERROR(""ERROR: Failed to set search range""); + } + } + if (m_sVenc_cfg.input_height != portDefn->format.video.nFrameHeight || + m_sVenc_cfg.input_width != portDefn->format.video.nFrameWidth) { + DEBUG_PRINT_LOW(""Basic parameter has changed""); + m_sVenc_cfg.input_height = portDefn->format.video.nFrameHeight; + m_sVenc_cfg.input_width = portDefn->format.video.nFrameWidth; + fmt.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; + fmt.fmt.pix_mp.height = m_sVenc_cfg.input_height; + fmt.fmt.pix_mp.width = m_sVenc_cfg.input_width; + fmt.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12; + fmt.fmt.pix_mp.colorspace = V4L2_COLORSPACE_BT878; + + if (ioctl(m_nDriver_fd, VIDIOC_S_FMT, &fmt)) { + DEBUG_PRINT_ERROR(""VIDIOC_S_FMT OUTPUT_MPLANE Failed""); + hw_overload = errno == EBUSY; + return false; + } + + m_sInput_buff_property.datasize=fmt.fmt.pix_mp.plane_fmt[0].sizeimage; + bufreq.memory = V4L2_MEMORY_USERPTR; + bufreq.count = portDefn->nBufferCountActual; + bufreq.type=V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; + + if (ioctl(m_nDriver_fd,VIDIOC_REQBUFS, &bufreq)) { + DEBUG_PRINT_ERROR(""VIDIOC_REQBUFS OUTPUT_MPLANE Failed""); + return false; + } + + if (bufreq.count == portDefn->nBufferCountActual) + m_sInput_buff_property.mincount = m_sInput_buff_property.actualcount = bufreq.count; + + if (portDefn->nBufferCountActual >= m_sInput_buff_property.mincount) + m_sInput_buff_property.actualcount = portDefn->nBufferCountActual; + } + + DEBUG_PRINT_LOW(""input: actual: %u, min: %u, count_req: %u"", + (unsigned int)portDefn->nBufferCountActual, (unsigned int)m_sInput_buff_property.mincount, bufreq.count); + if (m_sVenc_cfg.input_width * m_sVenc_cfg.input_height >= 3840 * 2160) { + if (venc_set_perf_mode(V4L2_MPEG_VIDC_VIDEO_PERF_POWER_SAVE) == false) { + DEBUG_PRINT_ERROR(""ERROR: Failed to set Power save mode""); + } + } + } else if (portDefn->nPortIndex == PORT_INDEX_OUT) { + m_sVenc_cfg.dvs_height = portDefn->format.video.nFrameHeight; + m_sVenc_cfg.dvs_width = portDefn->format.video.nFrameWidth; + fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; + fmt.fmt.pix_mp.height = m_sVenc_cfg.dvs_height; + fmt.fmt.pix_mp.width = m_sVenc_cfg.dvs_width; + fmt.fmt.pix_mp.pixelformat = m_sVenc_cfg.codectype; + + if (ioctl(m_nDriver_fd, VIDIOC_S_FMT, &fmt)) { + DEBUG_PRINT_ERROR(""VIDIOC_S_FMT CAPTURE_MPLANE Failed""); + hw_overload = errno == EBUSY; + return false; + } + + m_sOutput_buff_property.datasize = fmt.fmt.pix_mp.plane_fmt[0].sizeimage; + + if (!venc_set_target_bitrate(portDefn->format.video.nBitrate, 0)) { + return false; + } + + m_sOutput_buff_property.actualcount = portDefn->nBufferCountActual; + bufreq.memory = V4L2_MEMORY_USERPTR; + bufreq.count = portDefn->nBufferCountActual; + bufreq.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; + + if (ioctl(m_nDriver_fd,VIDIOC_REQBUFS, &bufreq)) { + DEBUG_PRINT_ERROR(""ERROR: Request for setting o/p buffer count failed: requested: %u, current: %u"", + (unsigned int)portDefn->nBufferCountActual, (unsigned int)m_sOutput_buff_property.actualcount); + return false; + } + + if (bufreq.count == portDefn->nBufferCountActual) + m_sOutput_buff_property.mincount = m_sOutput_buff_property.actualcount = bufreq.count; + + if (portDefn->nBufferCountActual >= m_sOutput_buff_property.mincount) + m_sOutput_buff_property.actualcount = portDefn->nBufferCountActual; + + if (num_planes > 1) + extradata_info.count = m_sOutput_buff_property.actualcount; + + DEBUG_PRINT_LOW(""Output: actual: %u, min: %u, count_req: %u"", + (unsigned int)portDefn->nBufferCountActual, (unsigned int)m_sOutput_buff_property.mincount, bufreq.count); + } else { + DEBUG_PRINT_ERROR(""ERROR: Invalid Port Index for OMX_IndexParamPortDefinition""); + } + + break; + } + case OMX_IndexParamVideoPortFormat: + { + OMX_VIDEO_PARAM_PORTFORMATTYPE *portFmt; + portFmt =(OMX_VIDEO_PARAM_PORTFORMATTYPE *)paramData; + DEBUG_PRINT_LOW(""venc_set_param: OMX_IndexParamVideoPortFormat""); + + if (portFmt->nPortIndex == (OMX_U32) PORT_INDEX_IN) { + if (!venc_set_color_format(portFmt->eColorFormat)) { + return false; + } + } else if (portFmt->nPortIndex == (OMX_U32) PORT_INDEX_OUT) { + if (!venc_set_encode_framerate(portFmt->xFramerate, 0)) { + return false; + } + } else { + DEBUG_PRINT_ERROR(""ERROR: Invalid Port Index for OMX_IndexParamVideoPortFormat""); + } + + break; + } + case OMX_IndexParamVideoBitrate: + { + OMX_VIDEO_PARAM_BITRATETYPE* pParam; + pParam = (OMX_VIDEO_PARAM_BITRATETYPE*)paramData; + DEBUG_PRINT_LOW(""venc_set_param: OMX_IndexParamVideoBitrate""); + + if (pParam->nPortIndex == (OMX_U32) PORT_INDEX_OUT) { + if (!venc_set_target_bitrate(pParam->nTargetBitrate, 0)) { + DEBUG_PRINT_ERROR(""ERROR: Target Bit Rate setting failed""); + return false; + } + + if (!venc_set_ratectrl_cfg(pParam->eControlRate)) { + DEBUG_PRINT_ERROR(""ERROR: Rate Control setting failed""); + return false; + } + } else { + DEBUG_PRINT_ERROR(""ERROR: Invalid Port Index for OMX_IndexParamVideoBitrate""); + } + + break; + } + case OMX_IndexParamVideoMpeg4: + { + OMX_VIDEO_PARAM_MPEG4TYPE* pParam; + OMX_U32 bFrames = 0; + + pParam = (OMX_VIDEO_PARAM_MPEG4TYPE*)paramData; + DEBUG_PRINT_LOW(""venc_set_param: OMX_IndexParamVideoMpeg4""); + + if (pParam->nPortIndex == (OMX_U32) PORT_INDEX_OUT) { + if (!venc_set_voptiming_cfg(pParam->nTimeIncRes)) { + DEBUG_PRINT_ERROR(""ERROR: Request for setting vop_timing failed""); + return false; + } + + m_profile_set = false; + m_level_set = false; + + if (!venc_set_profile_level (pParam->eProfile, pParam->eLevel)) { + DEBUG_PRINT_ERROR(""ERROR: Unsuccessful in updating Profile and level""); + return false; + } else { + if (pParam->eProfile == OMX_VIDEO_MPEG4ProfileAdvancedSimple) { + if (pParam->nBFrames) { + bFrames = pParam->nBFrames; + } + } else { + if (pParam->nBFrames) { + DEBUG_PRINT_ERROR(""Warning: B frames not supported""); + bFrames = 0; + } + } + } + + if (!venc_set_intra_period (pParam->nPFrames,bFrames)) { + DEBUG_PRINT_ERROR(""ERROR: Request for setting intra period failed""); + return false; + } + + if (!venc_set_multislice_cfg(OMX_IndexParamVideoMpeg4,pParam->nSliceHeaderSpacing)) { + DEBUG_PRINT_ERROR(""ERROR: Unsuccessful in updating slice_config""); + return false; + } + } else { + DEBUG_PRINT_ERROR(""ERROR: Invalid Port Index for OMX_IndexParamVideoMpeg4""); + } + + break; + } + case OMX_IndexParamVideoH263: + { + OMX_VIDEO_PARAM_H263TYPE* pParam = (OMX_VIDEO_PARAM_H263TYPE*)paramData; + DEBUG_PRINT_LOW(""venc_set_param: OMX_IndexParamVideoH263""); + OMX_U32 bFrames = 0; + + if (pParam->nPortIndex == (OMX_U32) PORT_INDEX_OUT) { + m_profile_set = false; + m_level_set = false; + + if (!venc_set_profile_level (pParam->eProfile, pParam->eLevel)) { + DEBUG_PRINT_ERROR(""ERROR: Unsuccessful in updating Profile and level""); + return false; + } + + if (pParam->nBFrames) + DEBUG_PRINT_ERROR(""WARNING: B frame not supported for H.263""); + + if (venc_set_intra_period (pParam->nPFrames, bFrames) == false) { + DEBUG_PRINT_ERROR(""ERROR: Request for setting intra period failed""); + return false; + } + } else { + DEBUG_PRINT_ERROR(""ERROR: Invalid Port Index for OMX_IndexParamVideoH263""); + } + + break; + } + case OMX_IndexParamVideoAvc: + { + DEBUG_PRINT_LOW(""venc_set_param:OMX_IndexParamVideoAvc""); + OMX_VIDEO_PARAM_AVCTYPE* pParam = (OMX_VIDEO_PARAM_AVCTYPE*)paramData; + OMX_U32 bFrames = 0; + + if (pParam->nPortIndex == (OMX_U32) PORT_INDEX_OUT) { + DEBUG_PRINT_LOW(""pParam->eProfile :%d ,pParam->eLevel %d"", + pParam->eProfile,pParam->eLevel); + + m_profile_set = false; + m_level_set = false; + + if (!venc_set_profile_level (pParam->eProfile,pParam->eLevel)) { + DEBUG_PRINT_ERROR(""ERROR: Unsuccessful in updating Profile and level %d, %d"", + pParam->eProfile, pParam->eLevel); + return false; + } else { + if ((pParam->eProfile != OMX_VIDEO_AVCProfileBaseline) && + (pParam->eProfile != (OMX_VIDEO_AVCPROFILETYPE) QOMX_VIDEO_AVCProfileConstrainedBaseline)) { + if (pParam->nBFrames) { + bFrames = pParam->nBFrames; + } + } else { + if (pParam->nBFrames) { + DEBUG_PRINT_ERROR(""Warning: B frames not supported""); + bFrames = 0; + } + } + } + + if (!venc_set_intra_period (pParam->nPFrames, bFrames)) { + DEBUG_PRINT_ERROR(""ERROR: Request for setting intra period failed""); + return false; + } + + if (!venc_set_entropy_config (pParam->bEntropyCodingCABAC, pParam->nCabacInitIdc)) { + DEBUG_PRINT_ERROR(""ERROR: Request for setting Entropy failed""); + return false; + } + + if (!venc_set_inloop_filter (pParam->eLoopFilterMode)) { + DEBUG_PRINT_ERROR(""ERROR: Request for setting Inloop filter failed""); + return false; + } + + if (!venc_set_multislice_cfg(OMX_IndexParamVideoAvc, pParam->nSliceHeaderSpacing)) { + DEBUG_PRINT_ERROR(""WARNING: Unsuccessful in updating slice_config""); + return false; + } + } else { + DEBUG_PRINT_ERROR(""ERROR: Invalid Port Index for OMX_IndexParamVideoAvc""); + } + + break; + } + case (OMX_INDEXTYPE)OMX_IndexParamVideoVp8: + { + DEBUG_PRINT_LOW(""venc_set_param:OMX_IndexParamVideoVp8""); + OMX_VIDEO_PARAM_VP8TYPE* pParam = (OMX_VIDEO_PARAM_VP8TYPE*)paramData; + if (!venc_set_profile_level (pParam->eProfile, pParam->eLevel)) { + DEBUG_PRINT_ERROR(""ERROR: Unsuccessful in updating Profile and level %d, %d"", + pParam->eProfile, pParam->eLevel); + return false; + } + if(venc_set_vpx_error_resilience(pParam->bErrorResilientMode) == false) { + DEBUG_PRINT_ERROR(""ERROR: Failed to set vpx error resilience""); + return false; + } + if(!venc_set_ltrmode(1, 1)) { + DEBUG_PRINT_ERROR(""ERROR: Failed to enable ltrmode""); + return false; + } + + if (m_codec == OMX_VIDEO_CodingVP8) { + DEBUG_PRINT_LOW(""Disable Hier-P as LTR is being set""); + if (!venc_set_hier_layers(QOMX_HIERARCHICALCODING_P, 0)) { + DEBUG_PRINT_ERROR(""Disabling Hier P count failed""); + } + } + + break; + } + case (OMX_INDEXTYPE)OMX_IndexParamVideoHevc: + { + DEBUG_PRINT_LOW(""venc_set_param:OMX_IndexParamVideoHevc""); + OMX_VIDEO_PARAM_HEVCTYPE* pParam = (OMX_VIDEO_PARAM_HEVCTYPE*)paramData; + if (!venc_set_profile_level (pParam->eProfile, pParam->eLevel)) { + DEBUG_PRINT_ERROR(""ERROR: Unsuccessful in updating Profile and level %d, %d"", + pParam->eProfile, pParam->eLevel); + return false; + } + if (!venc_set_inloop_filter(OMX_VIDEO_AVCLoopFilterEnable)) + DEBUG_PRINT_HIGH(""WARN: Request for setting Inloop filter failed for HEVC encoder""); + + break; + } + case OMX_IndexParamVideoIntraRefresh: + { + DEBUG_PRINT_LOW(""venc_set_param:OMX_IndexParamVideoIntraRefresh""); + OMX_VIDEO_PARAM_INTRAREFRESHTYPE *intra_refresh = + (OMX_VIDEO_PARAM_INTRAREFRESHTYPE *)paramData; + + if (intra_refresh->nPortIndex == (OMX_U32) PORT_INDEX_OUT) { + if (venc_set_intra_refresh(intra_refresh->eRefreshMode, intra_refresh->nCirMBs) == false) { + DEBUG_PRINT_ERROR(""ERROR: Setting Intra refresh failed""); + return false; + } + } else { + DEBUG_PRINT_ERROR(""ERROR: Invalid Port Index for OMX_IndexParamVideoIntraRefresh""); + } + + break; + } + case OMX_IndexParamVideoErrorCorrection: + { + DEBUG_PRINT_LOW(""venc_set_param:OMX_IndexParamVideoErrorCorrection""); + OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE *error_resilience = + (OMX_VIDEO_PARAM_ERRORCORRECTIONTYPE *)paramData; + + if (error_resilience->nPortIndex == (OMX_U32) PORT_INDEX_OUT) { + if (venc_set_error_resilience(error_resilience) == false) { + DEBUG_PRINT_ERROR(""ERROR: Setting Intra refresh failed""); + return false; + } + } else { + DEBUG_PRINT_ERROR(""ERROR: Invalid Port Index for OMX_IndexParamVideoErrorCorrection""); + } + + break; + } + case OMX_IndexParamVideoProfileLevelCurrent: + { + DEBUG_PRINT_LOW(""venc_set_param:OMX_IndexParamVideoProfileLevelCurrent""); + OMX_VIDEO_PARAM_PROFILELEVELTYPE *profile_level = + (OMX_VIDEO_PARAM_PROFILELEVELTYPE *)paramData; + + if (profile_level->nPortIndex == (OMX_U32) PORT_INDEX_OUT) { + m_profile_set = false; + m_level_set = false; + + if (!venc_set_profile_level (profile_level->eProfile, + profile_level->eLevel)) { + DEBUG_PRINT_ERROR(""WARNING: Unsuccessful in updating Profile and level""); + return false; + } + } else { + DEBUG_PRINT_ERROR(""ERROR: Invalid Port Index for OMX_IndexParamVideoProfileLevelCurrent""); + } + + break; + } + case OMX_IndexParamVideoQuantization: + { + DEBUG_PRINT_LOW(""venc_set_param:OMX_IndexParamVideoQuantization""); + OMX_VIDEO_PARAM_QUANTIZATIONTYPE *session_qp = + (OMX_VIDEO_PARAM_QUANTIZATIONTYPE *)paramData; + if (session_qp->nPortIndex == (OMX_U32) PORT_INDEX_OUT) { + if (venc_set_session_qp (session_qp->nQpI, + session_qp->nQpP, + session_qp->nQpB) == false) { + DEBUG_PRINT_ERROR(""ERROR: Setting Session QP failed""); + return false; + } + } else { + DEBUG_PRINT_ERROR(""ERROR: Invalid Port Index for OMX_IndexParamVideoQuantization""); + } + + break; + } + case QOMX_IndexParamVideoInitialQp: + { + QOMX_EXTNINDEX_VIDEO_INITIALQP * initqp = + (QOMX_EXTNINDEX_VIDEO_INITIALQP *)paramData; + if (initqp->bEnableInitQp) { + DEBUG_PRINT_LOW(""Enable initial QP: %d"", (int)initqp->bEnableInitQp); + if(venc_enable_initial_qp(initqp) == false) { + DEBUG_PRINT_ERROR(""ERROR: Failed to enable initial QP""); + return OMX_ErrorUnsupportedSetting; + } + } else + DEBUG_PRINT_ERROR(""ERROR: setting QOMX_IndexParamVideoEnableInitialQp""); + break; + } + case OMX_QcomIndexParamVideoQPRange: + { + DEBUG_PRINT_LOW(""venc_set_param:OMX_QcomIndexParamVideoQPRange""); + OMX_QCOM_VIDEO_PARAM_QPRANGETYPE *session_qp_range = + (OMX_QCOM_VIDEO_PARAM_QPRANGETYPE *)paramData; + + if(session_qp_range->nPortIndex == (OMX_U32)PORT_INDEX_OUT) { + if(venc_set_session_qp_range (session_qp_range->minQP, + session_qp_range->maxQP) == false) { + DEBUG_PRINT_ERROR(""ERROR: Setting QP Range[%u %u] failed"", + (unsigned int)session_qp_range->minQP, (unsigned int)session_qp_range->maxQP); + return false; + } else { + session_qp_values.minqp = session_qp_range->minQP; + session_qp_values.maxqp = session_qp_range->maxQP; + } + } else { + DEBUG_PRINT_ERROR(""ERROR: Invalid Port Index for OMX_QcomIndexParamVideoQPRange""); + } + + break; + } + case OMX_QcomIndexEnableSliceDeliveryMode: + { + QOMX_EXTNINDEX_PARAMTYPE* pParam = + (QOMX_EXTNINDEX_PARAMTYPE*)paramData; + + if (pParam->nPortIndex == PORT_INDEX_OUT) { + if (venc_set_slice_delivery_mode(pParam->bEnable) == false) { + DEBUG_PRINT_ERROR(""Setting slice delivery mode failed""); + return OMX_ErrorUnsupportedSetting; + } + } else { + DEBUG_PRINT_ERROR(""OMX_QcomIndexEnableSliceDeliveryMode "" + ""called on wrong port(%u)"", (unsigned int)pParam->nPortIndex); + return OMX_ErrorBadPortIndex; + } + + break; + } + case OMX_ExtraDataVideoEncoderSliceInfo: + { + DEBUG_PRINT_LOW(""venc_set_param: OMX_ExtraDataVideoEncoderSliceInfo""); + OMX_BOOL extra_data = *(OMX_BOOL *)(paramData); + + if (venc_set_extradata(OMX_ExtraDataVideoEncoderSliceInfo, extra_data) == false) { + DEBUG_PRINT_ERROR(""ERROR: Setting OMX_ExtraDataVideoEncoderSliceInfo failed""); + return false; + } + + extradata = true; + break; + } + case OMX_ExtraDataVideoEncoderMBInfo: + { + DEBUG_PRINT_LOW(""venc_set_param: OMX_ExtraDataVideoEncoderMBInfo""); + OMX_BOOL extra_data = *(OMX_BOOL *)(paramData); + + if (venc_set_extradata(OMX_ExtraDataVideoEncoderMBInfo, extra_data) == false) { + DEBUG_PRINT_ERROR(""ERROR: Setting OMX_ExtraDataVideoEncoderMBInfo failed""); + return false; + } + + extradata = true; + break; + } + case OMX_QcomIndexParamSequenceHeaderWithIDR: + { + PrependSPSPPSToIDRFramesParams * pParam = + (PrependSPSPPSToIDRFramesParams *)paramData; + + DEBUG_PRINT_LOW(""set inband sps/pps: %d"", pParam->bEnable); + if(venc_set_inband_video_header(pParam->bEnable) == false) { + DEBUG_PRINT_ERROR(""ERROR: set inband sps/pps failed""); + return OMX_ErrorUnsupportedSetting; + } + + break; + } + case OMX_QcomIndexParamH264AUDelimiter: + { + OMX_QCOM_VIDEO_CONFIG_H264_AUD * pParam = + (OMX_QCOM_VIDEO_CONFIG_H264_AUD *)paramData; + + DEBUG_PRINT_LOW(""set AU delimiters: %d"", pParam->bEnable); + if(venc_set_au_delimiter(pParam->bEnable) == false) { + DEBUG_PRINT_ERROR(""ERROR: set H264 AU delimiter failed""); + return OMX_ErrorUnsupportedSetting; + } + + break; + } + case OMX_QcomIndexHierarchicalStructure: + { + QOMX_VIDEO_HIERARCHICALLAYERS* pParam = + (QOMX_VIDEO_HIERARCHICALLAYERS*)paramData; + + if (pParam->nPortIndex == PORT_INDEX_OUT) { + if (!venc_set_hier_layers(pParam->eHierarchicalCodingType, pParam->nNumLayers)) { + DEBUG_PRINT_ERROR(""Setting Hier P count failed""); + return false; + } + } else { + DEBUG_PRINT_ERROR(""OMX_QcomIndexHierarchicalStructure called on wrong port(%d)"", (int)pParam->nPortIndex); + return false; + } + + if (m_codec == OMX_VIDEO_CodingVP8) { + DEBUG_PRINT_LOW(""Disable LTR as HIER-P is being set""); + if(!venc_set_ltrmode(0, 1)) { + DEBUG_PRINT_ERROR(""ERROR: Failed to disable ltrmode""); + } + } + break; + } + case OMX_QcomIndexParamPerfLevel: + { + OMX_QCOM_VIDEO_PARAM_PERF_LEVEL *pParam = + (OMX_QCOM_VIDEO_PARAM_PERF_LEVEL *)paramData; + DEBUG_PRINT_LOW(""Set perf level: %d"", pParam->ePerfLevel); + if(!venc_set_perf_level(pParam->ePerfLevel)) { + DEBUG_PRINT_ERROR(""ERROR: Failed to set perf level to %d"", pParam->ePerfLevel); + return false; + } else { + performance_level.perflevel = (unsigned int) pParam->ePerfLevel; + } + break; + } + case OMX_QcomIndexParamH264VUITimingInfo: + { + OMX_QCOM_VIDEO_PARAM_VUI_TIMING_INFO *pParam = + (OMX_QCOM_VIDEO_PARAM_VUI_TIMING_INFO *)paramData; + DEBUG_PRINT_LOW(""Set VUI timing info: %d"", pParam->bEnable); + if(venc_set_vui_timing_info(pParam->bEnable) == false) { + DEBUG_PRINT_ERROR(""ERROR: Failed to set vui timing info to %d"", pParam->bEnable); + return false; + } else { + vui_timing_info.enabled = (unsigned int) pParam->bEnable; + } + break; + } + case OMX_QcomIndexParamPeakBitrate: + { + OMX_QCOM_VIDEO_PARAM_PEAK_BITRATE *pParam = + (OMX_QCOM_VIDEO_PARAM_PEAK_BITRATE *)paramData; + DEBUG_PRINT_LOW(""Set peak bitrate: %u"", (unsigned int)pParam->nPeakBitrate); + if(venc_set_peak_bitrate(pParam->nPeakBitrate) == false) { + DEBUG_PRINT_ERROR(""ERROR: Failed to set peak bitrate to %u"", (unsigned int)pParam->nPeakBitrate); + return false; + } else { + peak_bitrate.peakbitrate = (unsigned int) pParam->nPeakBitrate; + } + break; + } + case OMX_QcomIndexParamSetMVSearchrange: + { + DEBUG_PRINT_LOW(""venc_set_config: OMX_QcomIndexParamSetMVSearchrange""); + is_searchrange_set = true; + if (!venc_set_searchrange()) { + DEBUG_PRINT_ERROR(""ERROR: Failed to set search range""); + return false; + } + } + break; + case OMX_QcomIndexParamVideoLTRCount: + { + DEBUG_PRINT_LOW(""venc_set_param: OMX_QcomIndexParamVideoLTRCount""); + OMX_QCOM_VIDEO_PARAM_LTRCOUNT_TYPE* pParam = + (OMX_QCOM_VIDEO_PARAM_LTRCOUNT_TYPE*)paramData; + if (pParam->nCount > 0) { + if (venc_set_ltrmode(1, pParam->nCount) == false) { + DEBUG_PRINT_ERROR(""ERROR: Enable LTR mode failed""); + return false; + } + } else { + if (venc_set_ltrmode(0, 0) == false) { + DEBUG_PRINT_ERROR(""ERROR: Disable LTR mode failed""); + return false; + } + } + break; + } + case OMX_QcomIndexParamVideoHybridHierpMode: + { + QOMX_EXTNINDEX_VIDEO_HYBRID_HP_MODE* pParam = + (QOMX_EXTNINDEX_VIDEO_HYBRID_HP_MODE*)paramData; + + if (!venc_set_hybrid_hierp(pParam->nHpLayers)) { + DEBUG_PRINT_ERROR(""Setting hybrid Hier-P mode failed""); + return OMX_ErrorUnsupportedSetting; + } + break; + } + case OMX_IndexParamVideoSliceFMO: + default: + DEBUG_PRINT_ERROR(""ERROR: Unsupported parameter in venc_set_param: %u"", + index); + break; + } + + return true; +} +","@@ -681,6 +681,11 @@ + + + int venc_dev::venc_output_log_buffers(const char *buffer_addr, int buffer_len) + { ++ if (venc_handle->is_secure_session()) { ++ DEBUG_PRINT_ERROR(""logging secure output buffers is not allowed!""); ++ return -1; ++ } ++ + if (!m_debug.outfile) { + int size = 0; + if(m_sVenc_cfg.codectype == V4L2_PIX_FMT_MPEG4) { +@@ -764,6 +769,11 @@ + + } + + int venc_dev::venc_input_log_buffers(OMX_BUFFERHEADERTYPE *pbuffer, int fd, int plane_offset) { ++ if (venc_handle->is_secure_session()) { ++ DEBUG_PRINT_ERROR(""logging secure input buffers is not allowed!""); ++ return -1; ++ } ++ + if (!m_debug.infile) { + int size = snprintf(m_debug.infile_name, PROPERTY_VALUE_MAX, ""%s/input_enc_%lu_%lu_%p.yuv"", + m_debug.log_loc, m_sVenc_cfg.input_width, m_sVenc_cfg.input_height, this); +",5613,5944,6144 +17620,"IHEVCD_ERROR_T ihevcd_parse_coding_unit(codec_t *ps_codec, + WORD32 x0, + WORD32 y0, + WORD32 log2_cb_size) +{ + IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; + sps_t *ps_sps; + pps_t *ps_pps; + WORD32 cb_size; + slice_header_t *ps_slice_hdr; + WORD32 skip_flag; + WORD32 pcm_flag; + UWORD32 *pu4_skip_top = ps_codec->s_parse.pu4_skip_cu_top; + UWORD32 u4_skip_left = ps_codec->s_parse.u4_skip_cu_left; + bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm; + tu_t *ps_tu = ps_codec->s_parse.ps_tu; + + WORD32 cu_pos_x; + WORD32 cu_pos_y; + cab_ctxt_t *ps_cabac = &ps_codec->s_parse.s_cabac; + + ASSERT(0 == (x0 % 8)); + ASSERT(0 == (y0 % 8)); + + ps_codec->s_parse.s_cu.i4_tu_cnt = 0; + ps_sps = ps_codec->s_parse.ps_sps; + ps_pps = ps_codec->s_parse.ps_pps; + + cu_pos_x = ps_codec->s_parse.s_cu.i4_pos_x; + cu_pos_y = ps_codec->s_parse.s_cu.i4_pos_y; + + + + ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr; + + + cb_size = 1 << log2_cb_size; + + ps_codec->s_parse.s_cu.i4_cu_transquant_bypass = 0; + + if(ps_pps->i1_transquant_bypass_enable_flag) + { + TRACE_CABAC_CTXT(""cu_transquant_bypass_flag"", ps_cabac->u4_range, IHEVC_CAB_CU_TQ_BYPASS_FLAG); + ps_codec->s_parse.s_cu.i4_cu_transquant_bypass = + ihevcd_cabac_decode_bin(ps_cabac, ps_bitstrm, + IHEVC_CAB_CU_TQ_BYPASS_FLAG); + /* Update transquant_bypass in ps_tu */ + + AEV_TRACE(""cu_transquant_bypass_flag"", ps_codec->s_parse.s_cu.i4_cu_transquant_bypass, + ps_cabac->u4_range); + + if(ps_codec->s_parse.s_cu.i4_cu_transquant_bypass) + { + UWORD8 *pu1_pic_no_loop_filter_flag = ps_codec->s_parse.pu1_pic_no_loop_filter_flag; + UWORD32 u4_mask; + WORD32 i; + WORD32 numbytes_row; + numbytes_row = (ps_sps->i2_pic_width_in_luma_samples + 63) / 64; + pu1_pic_no_loop_filter_flag += (y0 / 8) * numbytes_row; + pu1_pic_no_loop_filter_flag += (x0 / 64); + + /* Generate (cb_size / 8) number of 1s */ + /* i.e (log2_cb_size - 2) number of 1s */ + u4_mask = LSB_ONES((cb_size >> 3)); + for(i = 0; i < (cb_size / 8); i++) + { + *pu1_pic_no_loop_filter_flag |= (u4_mask << (((x0) / 8) % 8)); + pu1_pic_no_loop_filter_flag += numbytes_row; + } + } + } + + { + UWORD32 u4_skip_top = 0; + UWORD32 u4_mask; + UWORD32 u4_top_mask, u4_left_mask; + UWORD32 u4_min_cu_x = x0 / 8; + UWORD32 u4_min_cu_y = y0 / 8; + + pu4_skip_top += (u4_min_cu_x / 32); + + + if(ps_slice_hdr->i1_slice_type != ISLICE) + { + WORD32 ctx_idx_inc; + ctx_idx_inc = 0; + + if((0 != cu_pos_y) || + ((0 != ps_codec->s_parse.i4_ctb_slice_y) && + (0 != ps_codec->s_parse.i4_ctb_tile_y))) + { + u4_skip_top = *pu4_skip_top; + u4_skip_top >>= (u4_min_cu_x % 32); + if(u4_skip_top & 1) + ctx_idx_inc++; + } + + /*****************************************************************/ + /* If cu_pos_x is non-zero then left is available */ + /* If cu_pos_x is zero then ensure both the following are true */ + /* Current CTB is not the first CTB in a tile row */ + /* Current CTB is not the first CTB in a slice */ + /*****************************************************************/ + if((0 != cu_pos_x) || + (((0 != ps_codec->s_parse.i4_ctb_slice_x) || (0 != ps_codec->s_parse.i4_ctb_slice_y)) && + (0 != ps_codec->s_parse.i4_ctb_tile_x))) + { + u4_skip_left >>= (u4_min_cu_y % 32); + if(u4_skip_left & 1) + ctx_idx_inc++; + } + TRACE_CABAC_CTXT(""cu_skip_flag"", ps_cabac->u4_range, (IHEVC_CAB_SKIP_FLAG + ctx_idx_inc)); + skip_flag = ihevcd_cabac_decode_bin(ps_cabac, + ps_bitstrm, + (IHEVC_CAB_SKIP_FLAG + ctx_idx_inc)); + + AEV_TRACE(""cu_skip_flag"", skip_flag, ps_cabac->u4_range); + } + else + skip_flag = 0; + + /* Update top skip_flag */ + u4_skip_top = *pu4_skip_top; + /* Since Max cb_size is 64, maximum of 8 bits will be set or reset */ + /* Also since Coding block will be within 64x64 grid, only 8bits within a WORD32 + * need to be updated. These 8 bits will not cross 8 bit boundaries + */ + u4_mask = LSB_ONES(cb_size / 8); + u4_top_mask = u4_mask << (u4_min_cu_x % 32); + + + if(skip_flag) + { + u4_skip_top |= u4_top_mask; + } + else + { + u4_skip_top &= ~u4_top_mask; + } + *pu4_skip_top = u4_skip_top; + + /* Update left skip_flag */ + u4_skip_left = ps_codec->s_parse.u4_skip_cu_left; + u4_mask = LSB_ONES(cb_size / 8); + u4_left_mask = u4_mask << (u4_min_cu_y % 32); + + if(skip_flag) + { + u4_skip_left |= u4_left_mask; + } + else + { + u4_skip_left &= ~u4_left_mask; + } + ps_codec->s_parse.u4_skip_cu_left = u4_skip_left; + } + ps_codec->s_parse.i4_cu_pcm_flag = 0; + + if(skip_flag) + { + WORD32 ctb_x_base; + WORD32 ctb_y_base; + + ctb_x_base = ps_codec->s_parse.i4_ctb_x << ps_sps->i1_log2_ctb_size; + ctb_y_base = ps_codec->s_parse.i4_ctb_y << ps_sps->i1_log2_ctb_size; + + ps_tu->b1_cb_cbf = 0; + ps_tu->b1_cr_cbf = 0; + ps_tu->b1_y_cbf = 0; + ps_tu->b4_pos_x = ((x0 - ctb_x_base) >> 2); + ps_tu->b4_pos_y = ((y0 - ctb_y_base) >> 2); + ps_tu->b1_transquant_bypass = 0; + ps_tu->b3_size = (log2_cb_size - 2); + ps_tu->b7_qp = ps_codec->s_parse.u4_qp; + ps_tu->b3_chroma_intra_mode_idx = INTRA_PRED_CHROMA_IDX_NONE; + ps_tu->b6_luma_intra_mode = INTRA_PRED_NONE; + + /* Set the first TU in CU flag */ + { + if((ps_codec->s_parse.s_cu.i4_pos_x << 3) == (ps_tu->b4_pos_x << 2) && + (ps_codec->s_parse.s_cu.i4_pos_y << 3) == (ps_tu->b4_pos_y << 2)) + { + ps_tu->b1_first_tu_in_cu = 1; + } + else + { + ps_tu->b1_first_tu_in_cu = 0; + } + } + + ps_codec->s_parse.ps_tu++; + ps_codec->s_parse.s_cu.i4_tu_cnt++; + ps_codec->s_parse.i4_pic_tu_idx++; + + ps_codec->s_parse.s_cu.i4_pred_mode = PRED_MODE_SKIP; + ps_codec->s_parse.s_cu.i4_part_mode = PART_2Nx2N; + { + pu_t *ps_pu = ps_codec->s_parse.ps_pu; + ps_pu->b2_part_idx = 0; + ihevcd_parse_prediction_unit(ps_codec, x0, y0, cb_size, cb_size); + STATS_UPDATE_PU_SKIP_SIZE(ps_pu); + } + } + else + { + WORD32 pred_mode; + WORD32 part_mode; + WORD32 intra_split_flag; + WORD32 is_mincb; + cb_size = (1 << log2_cb_size); + is_mincb = (cb_size == (1 << ps_sps->i1_log2_min_coding_block_size)); + pcm_flag = 0; + if(ps_slice_hdr->i1_slice_type != ISLICE) + { + TRACE_CABAC_CTXT(""pred_mode_flag"", ps_cabac->u4_range, IHEVC_CAB_PRED_MODE); + pred_mode = ihevcd_cabac_decode_bin(ps_cabac, + ps_bitstrm, + IHEVC_CAB_PRED_MODE); + + AEV_TRACE(""pred_mode_flag"", pred_mode, ps_cabac->u4_range); + } + else + { + pred_mode = PRED_MODE_INTRA; + } + + /* If current CU is intra then set corresponging bit in picture level intra map */ + if(PRED_MODE_INTRA == pred_mode) + { + UWORD8 *pu1_pic_intra_flag = ps_codec->s_parse.pu1_pic_intra_flag; + UWORD32 u4_mask; + WORD32 i; + WORD32 numbytes_row; + numbytes_row = (ps_sps->i2_pic_width_in_luma_samples + 63) / 64; + pu1_pic_intra_flag += (y0 / 8) * numbytes_row; + pu1_pic_intra_flag += (x0 / 64); + + /* Generate (cb_size / 8) number of 1s */ + /* i.e (log2_cb_size - 2) number of 1s */ + u4_mask = LSB_ONES((cb_size >> 3)); + for(i = 0; i < (cb_size / 8); i++) + { + *pu1_pic_intra_flag |= (u4_mask << (((x0) / 8) % 8)); + pu1_pic_intra_flag += numbytes_row; + } + } + + ps_codec->s_parse.s_cu.i4_pred_mode = pred_mode; + intra_split_flag = 0; + if((PRED_MODE_INTRA != pred_mode) || + is_mincb) + { + UWORD32 bin; + if(PRED_MODE_INTRA == pred_mode) + { + TRACE_CABAC_CTXT(""part_mode"", ps_cabac->u4_range, IHEVC_CAB_PART_MODE); + bin = ihevcd_cabac_decode_bin(ps_cabac, ps_bitstrm, IHEVC_CAB_PART_MODE); + part_mode = (bin) ? PART_2Nx2N : PART_NxN; + } + else + { + WORD32 amp_enabled = ps_sps->i1_amp_enabled_flag; + + UWORD32 u4_max_bin_cnt = 0; + + + + if(amp_enabled && !is_mincb) + { + part_mode = ihevcd_parse_part_mode_amp(ps_cabac, ps_bitstrm); + } + else + { + WORD32 ctxt_inc = IHEVC_CAB_PART_MODE; + + u4_max_bin_cnt = 2; + if((is_mincb) && (cb_size > 8)) + { + u4_max_bin_cnt++; + } + + part_mode = -1; + TRACE_CABAC_CTXT(""part_mode"", ps_cabac->u4_range, IHEVC_CAB_PART_MODE); + do + { + bin = ihevcd_cabac_decode_bin(ps_cabac, ps_bitstrm, + ctxt_inc++); + part_mode++; + }while(--u4_max_bin_cnt && !bin); + + /* If the last bin was zero, then increment part mode by 1 */ + if(!bin) + part_mode++; + } + + + } + + AEV_TRACE(""part_mode"", part_mode, ps_cabac->u4_range); + + } + else + { + part_mode = 0; + intra_split_flag = 0; + } + ps_codec->s_parse.s_cu.i4_part_mode = part_mode; + + if((PRED_MODE_INTRA == ps_codec->s_parse.s_cu.i4_pred_mode) && + (PART_NxN == ps_codec->s_parse.s_cu.i4_part_mode)) + { + intra_split_flag = 1; + } + ps_codec->s_parse.s_cu.i4_part_mode = part_mode; + ps_codec->s_parse.s_cu.i4_intra_split_flag = intra_split_flag; + if(pred_mode == PRED_MODE_INTRA) + { + ps_codec->s_parse.i4_cu_pcm_flag = 0; + ihevcd_parse_coding_unit_intra(ps_codec, x0, y0, log2_cb_size); + pcm_flag = ps_codec->s_parse.i4_cu_pcm_flag; + + } + else + { + if(part_mode == PART_2Nx2N) + { + pu_t *ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0, y0, cb_size, cb_size); + ps_pu->b2_part_idx = 0; + } + else if(part_mode == PART_2NxN) + { + pu_t *ps_pu = ps_codec->s_parse.ps_pu; + + ihevcd_parse_prediction_unit(ps_codec, x0, y0, cb_size, cb_size / 2); + ps_pu->b2_part_idx = 0; + + ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0, y0 + (cb_size / 2), cb_size, cb_size / 2); + + ps_pu->b2_part_idx = 1; + } + else if(part_mode == PART_Nx2N) + { + pu_t *ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0, y0, cb_size / 2, cb_size); + ps_pu->b2_part_idx = 0; + ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0 + (cb_size / 2), y0, cb_size / 2, cb_size); + + ps_pu->b2_part_idx = 1; + } + else if(part_mode == PART_2NxnU) + { + pu_t *ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0, y0, cb_size, cb_size / 4); + ps_pu->b2_part_idx = 0; + ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0, y0 + (cb_size / 4), cb_size, cb_size * 3 / 4); + + ps_pu->b2_part_idx = 1; + } + else if(part_mode == PART_2NxnD) + { + pu_t *ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0, y0, cb_size, cb_size * 3 / 4); + ps_pu->b2_part_idx = 0; + ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0, y0 + (cb_size * 3 / 4), cb_size, cb_size / 4); + + ps_pu->b2_part_idx = 1; + } + else if(part_mode == PART_nLx2N) + { + pu_t *ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0, y0, cb_size / 4, cb_size); + ps_pu->b2_part_idx = 0; + ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0 + (cb_size / 4), y0, cb_size * 3 / 4, cb_size); + + ps_pu->b2_part_idx = 1; + } + else if(part_mode == PART_nRx2N) + { + pu_t *ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0, y0, cb_size * 3 / 4, cb_size); + ps_pu->b2_part_idx = 0; + ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0 + (cb_size * 3 / 4), y0, cb_size / 4, cb_size); + ps_pu->b2_part_idx = 1; + } + else + { /* PART_NxN */ + pu_t *ps_pu = ps_codec->s_parse.ps_pu; + + ihevcd_parse_prediction_unit(ps_codec, x0, y0, cb_size / 2, cb_size / 2); + ps_pu->b2_part_idx = 0; + ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0 + (cb_size / 2), y0, cb_size / 2, cb_size / 2); + + ps_pu->b2_part_idx = 1; + ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0, y0 + (cb_size / 2), cb_size / 2, cb_size / 2); + + ps_pu->b2_part_idx = 2; + ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0 + (cb_size / 2), y0 + (cb_size / 2), cb_size / 2, cb_size / 2); + + ps_pu->b2_part_idx = 3; + } + } + + if(!pcm_flag) + { + WORD32 no_residual_syntax_flag = 0; + pu_t *ps_pu; + /* Since ps_pu is incremented for each PU parsed, decrement by 1 to + * access last decoded PU + */ + ps_pu = ps_codec->s_parse.ps_pu - 1; + if((PRED_MODE_INTRA != pred_mode) && + (!((part_mode == PART_2Nx2N) && ps_pu->b1_merge_flag))) + { + + TRACE_CABAC_CTXT(""rqt_root_cbf"", ps_cabac->u4_range, IHEVC_CAB_NORES_IDX); + no_residual_syntax_flag = ihevcd_cabac_decode_bin(ps_cabac, + ps_bitstrm, + IHEVC_CAB_NORES_IDX); + + AEV_TRACE(""rqt_root_cbf"", no_residual_syntax_flag, + ps_cabac->u4_range); + /* TODO: HACK FOR COMPLIANCE WITH HM REFERENCE DECODER */ + /*********************************************************/ + /* currently the HM decoder expects qtroot cbf instead of */ + /* no_residue_flag which has opposite meaning */ + /* This will be fixed once the software / spec is fixed */ + /*********************************************************/ + no_residual_syntax_flag = 1 - no_residual_syntax_flag; + } + + if(!no_residual_syntax_flag) + { + + ps_codec->s_parse.s_cu.i4_max_trafo_depth = (pred_mode == PRED_MODE_INTRA) ? + (ps_sps->i1_max_transform_hierarchy_depth_intra + intra_split_flag) : + (ps_sps->i1_max_transform_hierarchy_depth_inter); + ret = ihevcd_parse_transform_tree(ps_codec, x0, y0, x0, y0, + log2_cb_size, 0, 0, + ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[0]); + RETURN_IF((IHEVCD_ERROR_T)IHEVCD_SUCCESS != ret, ret); + } + else + { + WORD32 ctb_x_base; + WORD32 ctb_y_base; + + ctb_x_base = ps_codec->s_parse.i4_ctb_x << ps_sps->i1_log2_ctb_size; + ctb_y_base = ps_codec->s_parse.i4_ctb_y << ps_sps->i1_log2_ctb_size; + + ps_tu = ps_codec->s_parse.ps_tu; + ps_tu->b1_cb_cbf = 0; + ps_tu->b1_cr_cbf = 0; + ps_tu->b1_y_cbf = 0; + ps_tu->b4_pos_x = ((x0 - ctb_x_base) >> 2); + ps_tu->b4_pos_y = ((y0 - ctb_y_base) >> 2); + ps_tu->b1_transquant_bypass = 0; + ps_tu->b3_size = (log2_cb_size - 2); + ps_tu->b7_qp = ps_codec->s_parse.u4_qp; + ps_tu->b3_chroma_intra_mode_idx = INTRA_PRED_CHROMA_IDX_NONE; + ps_tu->b6_luma_intra_mode = ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[0]; + + /* Set the first TU in CU flag */ + { + if((ps_codec->s_parse.s_cu.i4_pos_x << 3) == (ps_tu->b4_pos_x << 2) && + (ps_codec->s_parse.s_cu.i4_pos_y << 3) == (ps_tu->b4_pos_y << 2)) + { + ps_tu->b1_first_tu_in_cu = 1; + } + else + { + ps_tu->b1_first_tu_in_cu = 0; + } + } + ps_codec->s_parse.ps_tu++; + ps_codec->s_parse.s_cu.i4_tu_cnt++; + ps_codec->s_parse.i4_pic_tu_idx++; + + } + } + + } + + + + + return ret; +} +",0,"IHEVCD_ERROR_T ihevcd_parse_coding_unit(codec_t *ps_codec, + WORD32 x0, + WORD32 y0, + WORD32 log2_cb_size) +{ + IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; + sps_t *ps_sps; + pps_t *ps_pps; + WORD32 cb_size; + slice_header_t *ps_slice_hdr; + WORD32 skip_flag; + WORD32 pcm_flag; + UWORD32 *pu4_skip_top = ps_codec->s_parse.pu4_skip_cu_top; + UWORD32 u4_skip_left = ps_codec->s_parse.u4_skip_cu_left; + bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm; + tu_t *ps_tu = ps_codec->s_parse.ps_tu; + + WORD32 cu_pos_x; + WORD32 cu_pos_y; + cab_ctxt_t *ps_cabac = &ps_codec->s_parse.s_cabac; + + ASSERT(0 == (x0 % 8)); + ASSERT(0 == (y0 % 8)); + + ps_codec->s_parse.s_cu.i4_tu_cnt = 0; + ps_sps = ps_codec->s_parse.ps_sps; + ps_pps = ps_codec->s_parse.ps_pps; + + cu_pos_x = ps_codec->s_parse.s_cu.i4_pos_x; + cu_pos_y = ps_codec->s_parse.s_cu.i4_pos_y; + + + + ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr; + + + cb_size = 1 << log2_cb_size; + + ps_codec->s_parse.s_cu.i4_cu_transquant_bypass = 0; + + if(ps_pps->i1_transquant_bypass_enable_flag) + { + TRACE_CABAC_CTXT(""cu_transquant_bypass_flag"", ps_cabac->u4_range, IHEVC_CAB_CU_TQ_BYPASS_FLAG); + ps_codec->s_parse.s_cu.i4_cu_transquant_bypass = + ihevcd_cabac_decode_bin(ps_cabac, ps_bitstrm, + IHEVC_CAB_CU_TQ_BYPASS_FLAG); + /* Update transquant_bypass in ps_tu */ + + AEV_TRACE(""cu_transquant_bypass_flag"", ps_codec->s_parse.s_cu.i4_cu_transquant_bypass, + ps_cabac->u4_range); + + if(ps_codec->s_parse.s_cu.i4_cu_transquant_bypass) + { + UWORD8 *pu1_pic_no_loop_filter_flag = ps_codec->s_parse.pu1_pic_no_loop_filter_flag; + UWORD32 u4_mask; + WORD32 i; + WORD32 numbytes_row; + numbytes_row = (ps_sps->i2_pic_width_in_luma_samples + 63) / 64; + pu1_pic_no_loop_filter_flag += (y0 / 8) * numbytes_row; + pu1_pic_no_loop_filter_flag += (x0 / 64); + + /* Generate (cb_size / 8) number of 1s */ + /* i.e (log2_cb_size - 2) number of 1s */ + u4_mask = LSB_ONES((cb_size >> 3)); + for(i = 0; i < (cb_size / 8); i++) + { + *pu1_pic_no_loop_filter_flag |= (u4_mask << (((x0) / 8) % 8)); + pu1_pic_no_loop_filter_flag += numbytes_row; + } + } + } + + { + UWORD32 u4_skip_top = 0; + UWORD32 u4_mask; + UWORD32 u4_top_mask, u4_left_mask; + UWORD32 u4_min_cu_x = x0 / 8; + UWORD32 u4_min_cu_y = y0 / 8; + + pu4_skip_top += (u4_min_cu_x / 32); + + + if(ps_slice_hdr->i1_slice_type != ISLICE) + { + WORD32 ctx_idx_inc; + ctx_idx_inc = 0; + + if((0 != cu_pos_y) || + ((0 != ps_codec->s_parse.i4_ctb_slice_y) && + (0 != ps_codec->s_parse.i4_ctb_tile_y))) + { + u4_skip_top = *pu4_skip_top; + u4_skip_top >>= (u4_min_cu_x % 32); + if(u4_skip_top & 1) + ctx_idx_inc++; + } + + /*****************************************************************/ + /* If cu_pos_x is non-zero then left is available */ + /* If cu_pos_x is zero then ensure both the following are true */ + /* Current CTB is not the first CTB in a tile row */ + /* Current CTB is not the first CTB in a slice */ + /*****************************************************************/ + if((0 != cu_pos_x) || + (((0 != ps_codec->s_parse.i4_ctb_slice_x) || (0 != ps_codec->s_parse.i4_ctb_slice_y)) && + (0 != ps_codec->s_parse.i4_ctb_tile_x))) + { + u4_skip_left >>= (u4_min_cu_y % 32); + if(u4_skip_left & 1) + ctx_idx_inc++; + } + TRACE_CABAC_CTXT(""cu_skip_flag"", ps_cabac->u4_range, (IHEVC_CAB_SKIP_FLAG + ctx_idx_inc)); + skip_flag = ihevcd_cabac_decode_bin(ps_cabac, + ps_bitstrm, + (IHEVC_CAB_SKIP_FLAG + ctx_idx_inc)); + + AEV_TRACE(""cu_skip_flag"", skip_flag, ps_cabac->u4_range); + } + else + skip_flag = 0; + + /* Update top skip_flag */ + u4_skip_top = *pu4_skip_top; + /* Since Max cb_size is 64, maximum of 8 bits will be set or reset */ + /* Also since Coding block will be within 64x64 grid, only 8bits within a WORD32 + * need to be updated. These 8 bits will not cross 8 bit boundaries + */ + u4_mask = LSB_ONES(cb_size / 8); + u4_top_mask = u4_mask << (u4_min_cu_x % 32); + + + if(skip_flag) + { + u4_skip_top |= u4_top_mask; + } + else + { + u4_skip_top &= ~u4_top_mask; + } + *pu4_skip_top = u4_skip_top; + + /* Update left skip_flag */ + u4_skip_left = ps_codec->s_parse.u4_skip_cu_left; + u4_mask = LSB_ONES(cb_size / 8); + u4_left_mask = u4_mask << (u4_min_cu_y % 32); + + if(skip_flag) + { + u4_skip_left |= u4_left_mask; + } + else + { + u4_skip_left &= ~u4_left_mask; + } + ps_codec->s_parse.u4_skip_cu_left = u4_skip_left; + } + ps_codec->s_parse.i4_cu_pcm_flag = 0; + + if(skip_flag) + { + WORD32 ctb_x_base; + WORD32 ctb_y_base; + + ctb_x_base = ps_codec->s_parse.i4_ctb_x << ps_sps->i1_log2_ctb_size; + ctb_y_base = ps_codec->s_parse.i4_ctb_y << ps_sps->i1_log2_ctb_size; + + ps_tu->b1_cb_cbf = 0; + ps_tu->b1_cr_cbf = 0; + ps_tu->b1_y_cbf = 0; + ps_tu->b4_pos_x = ((x0 - ctb_x_base) >> 2); + ps_tu->b4_pos_y = ((y0 - ctb_y_base) >> 2); + ps_tu->b1_transquant_bypass = 0; + ps_tu->b3_size = (log2_cb_size - 2); + ps_tu->b7_qp = ps_codec->s_parse.u4_qp; + ps_tu->b3_chroma_intra_mode_idx = INTRA_PRED_CHROMA_IDX_NONE; + ps_tu->b6_luma_intra_mode = INTRA_PRED_NONE; + + /* Set the first TU in CU flag */ + { + if((ps_codec->s_parse.s_cu.i4_pos_x << 3) == (ps_tu->b4_pos_x << 2) && + (ps_codec->s_parse.s_cu.i4_pos_y << 3) == (ps_tu->b4_pos_y << 2)) + { + ps_tu->b1_first_tu_in_cu = 1; + } + else + { + ps_tu->b1_first_tu_in_cu = 0; + } + } + + ps_codec->s_parse.ps_tu++; + ps_codec->s_parse.s_cu.i4_tu_cnt++; + ps_codec->s_parse.i4_pic_tu_idx++; + + ps_codec->s_parse.s_cu.i4_pred_mode = PRED_MODE_SKIP; + ps_codec->s_parse.s_cu.i4_part_mode = PART_2Nx2N; + { + pu_t *ps_pu = ps_codec->s_parse.ps_pu; + ps_pu->b2_part_idx = 0; + ihevcd_parse_prediction_unit(ps_codec, x0, y0, cb_size, cb_size); + STATS_UPDATE_PU_SKIP_SIZE(ps_pu); + } + } + else + { + WORD32 pred_mode; + WORD32 part_mode; + WORD32 intra_split_flag; + WORD32 is_mincb; + cb_size = (1 << log2_cb_size); + is_mincb = (cb_size == (1 << ps_sps->i1_log2_min_coding_block_size)); + pcm_flag = 0; + if(ps_slice_hdr->i1_slice_type != ISLICE) + { + TRACE_CABAC_CTXT(""pred_mode_flag"", ps_cabac->u4_range, IHEVC_CAB_PRED_MODE); + pred_mode = ihevcd_cabac_decode_bin(ps_cabac, + ps_bitstrm, + IHEVC_CAB_PRED_MODE); + + AEV_TRACE(""pred_mode_flag"", pred_mode, ps_cabac->u4_range); + } + else + { + pred_mode = PRED_MODE_INTRA; + } + + /* If current CU is intra then set corresponging bit in picture level intra map */ + if(PRED_MODE_INTRA == pred_mode) + { + UWORD8 *pu1_pic_intra_flag = ps_codec->s_parse.pu1_pic_intra_flag; + UWORD32 u4_mask; + WORD32 i; + WORD32 numbytes_row; + numbytes_row = (ps_sps->i2_pic_width_in_luma_samples + 63) / 64; + pu1_pic_intra_flag += (y0 / 8) * numbytes_row; + pu1_pic_intra_flag += (x0 / 64); + + /* Generate (cb_size / 8) number of 1s */ + /* i.e (log2_cb_size - 2) number of 1s */ + u4_mask = LSB_ONES((cb_size >> 3)); + for(i = 0; i < (cb_size / 8); i++) + { + *pu1_pic_intra_flag |= (u4_mask << (((x0) / 8) % 8)); + pu1_pic_intra_flag += numbytes_row; + } + } + + ps_codec->s_parse.s_cu.i4_pred_mode = pred_mode; + intra_split_flag = 0; + if((PRED_MODE_INTRA != pred_mode) || + is_mincb) + { + UWORD32 bin; + if(PRED_MODE_INTRA == pred_mode) + { + TRACE_CABAC_CTXT(""part_mode"", ps_cabac->u4_range, IHEVC_CAB_PART_MODE); + bin = ihevcd_cabac_decode_bin(ps_cabac, ps_bitstrm, IHEVC_CAB_PART_MODE); + part_mode = (bin) ? PART_2Nx2N : PART_NxN; + } + else + { + WORD32 amp_enabled = ps_sps->i1_amp_enabled_flag; + + UWORD32 u4_max_bin_cnt = 0; + + + + if(amp_enabled && !is_mincb) + { + part_mode = ihevcd_parse_part_mode_amp(ps_cabac, ps_bitstrm); + } + else + { + WORD32 ctxt_inc = IHEVC_CAB_PART_MODE; + + u4_max_bin_cnt = 2; + if((is_mincb) && (cb_size > 8)) + { + u4_max_bin_cnt++; + } + + part_mode = -1; + TRACE_CABAC_CTXT(""part_mode"", ps_cabac->u4_range, IHEVC_CAB_PART_MODE); + do + { + bin = ihevcd_cabac_decode_bin(ps_cabac, ps_bitstrm, + ctxt_inc++); + part_mode++; + }while(--u4_max_bin_cnt && !bin); + + /* If the last bin was zero, then increment part mode by 1 */ + if(!bin) + part_mode++; + } + + + } + + AEV_TRACE(""part_mode"", part_mode, ps_cabac->u4_range); + + } + else + { + part_mode = 0; + intra_split_flag = 0; + } + ps_codec->s_parse.s_cu.i4_part_mode = part_mode; + + if((PRED_MODE_INTRA == ps_codec->s_parse.s_cu.i4_pred_mode) && + (PART_NxN == ps_codec->s_parse.s_cu.i4_part_mode)) + { + intra_split_flag = 1; + } + ps_codec->s_parse.s_cu.i4_part_mode = part_mode; + ps_codec->s_parse.s_cu.i4_intra_split_flag = intra_split_flag; + if(pred_mode == PRED_MODE_INTRA) + { + ps_codec->s_parse.i4_cu_pcm_flag = 0; + ihevcd_parse_coding_unit_intra(ps_codec, x0, y0, log2_cb_size); + pcm_flag = ps_codec->s_parse.i4_cu_pcm_flag; + + } + else + { + if(part_mode == PART_2Nx2N) + { + pu_t *ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0, y0, cb_size, cb_size); + ps_pu->b2_part_idx = 0; + } + else if(part_mode == PART_2NxN) + { + pu_t *ps_pu = ps_codec->s_parse.ps_pu; + + ihevcd_parse_prediction_unit(ps_codec, x0, y0, cb_size, cb_size / 2); + ps_pu->b2_part_idx = 0; + + ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0, y0 + (cb_size / 2), cb_size, cb_size / 2); + + ps_pu->b2_part_idx = 1; + } + else if(part_mode == PART_Nx2N) + { + pu_t *ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0, y0, cb_size / 2, cb_size); + ps_pu->b2_part_idx = 0; + ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0 + (cb_size / 2), y0, cb_size / 2, cb_size); + + ps_pu->b2_part_idx = 1; + } + else if(part_mode == PART_2NxnU) + { + pu_t *ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0, y0, cb_size, cb_size / 4); + ps_pu->b2_part_idx = 0; + ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0, y0 + (cb_size / 4), cb_size, cb_size * 3 / 4); + + ps_pu->b2_part_idx = 1; + } + else if(part_mode == PART_2NxnD) + { + pu_t *ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0, y0, cb_size, cb_size * 3 / 4); + ps_pu->b2_part_idx = 0; + ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0, y0 + (cb_size * 3 / 4), cb_size, cb_size / 4); + + ps_pu->b2_part_idx = 1; + } + else if(part_mode == PART_nLx2N) + { + pu_t *ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0, y0, cb_size / 4, cb_size); + ps_pu->b2_part_idx = 0; + ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0 + (cb_size / 4), y0, cb_size * 3 / 4, cb_size); + + ps_pu->b2_part_idx = 1; + } + else if(part_mode == PART_nRx2N) + { + pu_t *ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0, y0, cb_size * 3 / 4, cb_size); + ps_pu->b2_part_idx = 0; + ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0 + (cb_size * 3 / 4), y0, cb_size / 4, cb_size); + ps_pu->b2_part_idx = 1; + } + else + { /* PART_NxN */ + pu_t *ps_pu = ps_codec->s_parse.ps_pu; + + ihevcd_parse_prediction_unit(ps_codec, x0, y0, cb_size / 2, cb_size / 2); + ps_pu->b2_part_idx = 0; + ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0 + (cb_size / 2), y0, cb_size / 2, cb_size / 2); + + ps_pu->b2_part_idx = 1; + ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0, y0 + (cb_size / 2), cb_size / 2, cb_size / 2); + + ps_pu->b2_part_idx = 2; + ps_pu = ps_codec->s_parse.ps_pu; + ihevcd_parse_prediction_unit(ps_codec, x0 + (cb_size / 2), y0 + (cb_size / 2), cb_size / 2, cb_size / 2); + + ps_pu->b2_part_idx = 3; + } + } + + if(!pcm_flag) + { + WORD32 no_residual_syntax_flag = 0; + pu_t *ps_pu; + /* Since ps_pu is incremented for each PU parsed, decrement by 1 to + * access last decoded PU + */ + ps_pu = ps_codec->s_parse.ps_pu - 1; + if((PRED_MODE_INTRA != pred_mode) && + (!((part_mode == PART_2Nx2N) && ps_pu->b1_merge_flag))) + { + + TRACE_CABAC_CTXT(""rqt_root_cbf"", ps_cabac->u4_range, IHEVC_CAB_NORES_IDX); + no_residual_syntax_flag = ihevcd_cabac_decode_bin(ps_cabac, + ps_bitstrm, + IHEVC_CAB_NORES_IDX); + + AEV_TRACE(""rqt_root_cbf"", no_residual_syntax_flag, + ps_cabac->u4_range); + /* TODO: HACK FOR COMPLIANCE WITH HM REFERENCE DECODER */ + /*********************************************************/ + /* currently the HM decoder expects qtroot cbf instead of */ + /* no_residue_flag which has opposite meaning */ + /* This will be fixed once the software / spec is fixed */ + /*********************************************************/ + no_residual_syntax_flag = 1 - no_residual_syntax_flag; + } + + if(!no_residual_syntax_flag) + { + + ps_codec->s_parse.s_cu.i4_max_trafo_depth = (pred_mode == PRED_MODE_INTRA) ? + (ps_sps->i1_max_transform_hierarchy_depth_intra + intra_split_flag) : + (ps_sps->i1_max_transform_hierarchy_depth_inter); + ret = ihevcd_parse_transform_tree(ps_codec, x0, y0, x0, y0, + log2_cb_size, 0, 0, + ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[0]); + RETURN_IF((IHEVCD_ERROR_T)IHEVCD_SUCCESS != ret, ret); + } + else + { + WORD32 ctb_x_base; + WORD32 ctb_y_base; + + ctb_x_base = ps_codec->s_parse.i4_ctb_x << ps_sps->i1_log2_ctb_size; + ctb_y_base = ps_codec->s_parse.i4_ctb_y << ps_sps->i1_log2_ctb_size; + + ps_tu = ps_codec->s_parse.ps_tu; + ps_tu->b1_cb_cbf = 0; + ps_tu->b1_cr_cbf = 0; + ps_tu->b1_y_cbf = 0; + ps_tu->b4_pos_x = ((x0 - ctb_x_base) >> 2); + ps_tu->b4_pos_y = ((y0 - ctb_y_base) >> 2); + ps_tu->b1_transquant_bypass = 0; + ps_tu->b3_size = (log2_cb_size - 2); + ps_tu->b7_qp = ps_codec->s_parse.u4_qp; + ps_tu->b3_chroma_intra_mode_idx = INTRA_PRED_CHROMA_IDX_NONE; + ps_tu->b6_luma_intra_mode = ps_codec->s_parse.s_cu.ai4_intra_luma_pred_mode[0]; + + /* Set the first TU in CU flag */ + { + if((ps_codec->s_parse.s_cu.i4_pos_x << 3) == (ps_tu->b4_pos_x << 2) && + (ps_codec->s_parse.s_cu.i4_pos_y << 3) == (ps_tu->b4_pos_y << 2)) + { + ps_tu->b1_first_tu_in_cu = 1; + } + else + { + ps_tu->b1_first_tu_in_cu = 0; + } + } + ps_codec->s_parse.ps_tu++; + ps_codec->s_parse.s_cu.i4_tu_cnt++; + ps_codec->s_parse.i4_pic_tu_idx++; + + } + } + + } + + + + + return ret; +} +","@@ -2177,6 +2177,98 @@ + + ******************************************************************************* + * + * @brief ++ * Set ctb skip ++ * ++ * @par Description: ++ * During error, sets tu and pu params of a ctb as skip. ++ * ++ * @param[in] ps_codec ++ * Pointer to codec context ++ * ++ * @returns None ++ * ++ * @remarks ++ * ++ * ++ ******************************************************************************* ++ */ ++void ihevcd_set_ctb_skip(codec_t *ps_codec) ++{ ++ tu_t *ps_tu; ++ pu_t *ps_pu; ++ sps_t *ps_sps = ps_codec->s_parse.ps_sps; ++ WORD32 ctb_size = 1 << ps_sps->i1_log2_ctb_size; ++ WORD32 ctb_skip_wd, ctb_skip_ht; ++ WORD32 rows_remaining, cols_remaining; ++ WORD32 tu_abs_x, tu_abs_y; ++ WORD32 numbytes_row = (ps_sps->i2_pic_width_in_luma_samples + 63) / 64; ++ UWORD8 *pu1_pic_intra_flag; ++ UWORD32 u4_mask; ++ WORD32 pu_x,pu_y; ++ ++ /* Set pu wd and ht based on whether the ctb is complete or not */ ++ rows_remaining = ps_sps->i2_pic_height_in_luma_samples ++ - (ps_codec->s_parse.i4_ctb_y << ps_sps->i1_log2_ctb_size); ++ ctb_skip_ht = MIN(ctb_size, rows_remaining); ++ ++ cols_remaining = ps_sps->i2_pic_width_in_luma_samples ++ - (ps_codec->s_parse.i4_ctb_x << ps_sps->i1_log2_ctb_size); ++ ctb_skip_wd = MIN(ctb_size, cols_remaining); ++ ++ ps_codec->s_parse.s_cu.i4_pred_mode = PRED_MODE_SKIP; ++ ps_codec->s_parse.s_cu.i4_part_mode = PART_2Nx2N; ++ ++ for (pu_y = 0; pu_y < ctb_skip_ht ; pu_y += MIN_CU_SIZE) ++ { ++ for (pu_x = 0; pu_x < ctb_skip_wd ; pu_x += MIN_CU_SIZE) ++ { ++ ps_tu = ps_codec->s_parse.ps_tu; ++ ps_tu->b1_cb_cbf = 0; ++ ps_tu->b1_cr_cbf = 0; ++ ps_tu->b1_y_cbf = 0; ++ ps_tu->b4_pos_x = pu_x >> 2; ++ ps_tu->b4_pos_y = pu_y >> 2; ++ ps_tu->b1_transquant_bypass = 0; ++ ps_tu->b3_size = 1; ++ ps_tu->b7_qp = ps_codec->s_parse.u4_qp; ++ ps_tu->b3_chroma_intra_mode_idx = INTRA_PRED_CHROMA_IDX_NONE; ++ ps_tu->b6_luma_intra_mode = INTRA_PRED_NONE; ++ ps_tu->b1_first_tu_in_cu = 1; ++ ++ ps_codec->s_parse.ps_tu++; ++ ps_codec->s_parse.s_cu.i4_tu_cnt++; ++ ps_codec->s_parse.i4_pic_tu_idx++; ++ ++ tu_abs_x = (ps_codec->s_parse.i4_ctb_x << ps_sps->i1_log2_ctb_size) + pu_x; ++ tu_abs_y = (ps_codec->s_parse.i4_ctb_y << ps_sps->i1_log2_ctb_size) + pu_y; ++ pu1_pic_intra_flag = ps_codec->s_parse.pu1_pic_intra_flag; ++ pu1_pic_intra_flag += (tu_abs_y >> 3) * numbytes_row; ++ pu1_pic_intra_flag += (tu_abs_x >> 6); ++ u4_mask = (LSB_ONES((MIN_CU_SIZE >> 3)) << (((tu_abs_x) / 8) % 8)); ++ u4_mask = ~u4_mask; ++ *pu1_pic_intra_flag &= u4_mask; ++ ++ ps_pu = ps_codec->s_parse.ps_pu; ++ ps_pu->b2_part_idx = 0; ++ ps_pu->b4_pos_x = pu_x >> 2; ++ ps_pu->b4_pos_y = pu_y >> 2; ++ ps_pu->b4_wd = 1; ++ ps_pu->b4_ht = 1; ++ ps_pu->b1_intra_flag = 0; ++ ps_pu->b3_part_mode = ps_codec->s_parse.s_cu.i4_part_mode; ++ ps_pu->b1_merge_flag = 1; ++ ps_pu->b3_merge_idx = 0; ++ ++ ps_codec->s_parse.ps_pu++; ++ ps_codec->s_parse.i4_pic_pu_idx++; ++ } ++ } ++} ++ ++/** ++ ******************************************************************************* ++ * ++ * @brief + * Parses Slice data syntax + * + * @par Description: +@@ -2640,19 +2732,8 @@ + + if (ret != (IHEVCD_ERROR_T)IHEVCD_SUCCESS) + { + /* Reset tu and pu parameters, and signal current ctb as skip */ +- WORD32 pu_skip_wd, pu_skip_ht; +- WORD32 rows_remaining, cols_remaining; + WORD32 tu_coeff_data_reset_size; + +- /* Set pu wd and ht based on whether the ctb is complete or not */ +- rows_remaining = ps_sps->i2_pic_height_in_luma_samples +- - (ps_codec->s_parse.i4_ctb_y << ps_sps->i1_log2_ctb_size); +- pu_skip_ht = MIN(ctb_size, rows_remaining); +- +- cols_remaining = ps_sps->i2_pic_width_in_luma_samples +- - (ps_codec->s_parse.i4_ctb_x << ps_sps->i1_log2_ctb_size); +- pu_skip_wd = MIN(ctb_size, cols_remaining); +- + ps_codec->s_parse.ps_tu = ps_tu; + ps_codec->s_parse.s_cu.i4_tu_cnt = i4_tu_cnt; + ps_codec->s_parse.i4_pic_tu_idx = i4_pic_tu_idx; +@@ -2660,41 +2741,11 @@ + + ps_codec->s_parse.ps_pu = ps_pu; + ps_codec->s_parse.i4_pic_pu_idx = i4_pic_pu_idx; + +- ps_tu->b1_cb_cbf = 0; +- ps_tu->b1_cr_cbf = 0; +- ps_tu->b1_y_cbf = 0; +- ps_tu->b4_pos_x = 0; +- ps_tu->b4_pos_y = 0; +- ps_tu->b1_transquant_bypass = 0; +- ps_tu->b3_size = (ps_sps->i1_log2_ctb_size - 2); +- ps_tu->b7_qp = ps_codec->s_parse.u4_qp; +- ps_tu->b3_chroma_intra_mode_idx = INTRA_PRED_CHROMA_IDX_NONE; +- ps_tu->b6_luma_intra_mode = INTRA_PRED_NONE; +- ps_tu->b1_first_tu_in_cu = 1; +- + tu_coeff_data_reset_size = (UWORD8 *)ps_codec->s_parse.pv_tu_coeff_data - pu1_tu_coeff_data; + memset(pu1_tu_coeff_data, 0, tu_coeff_data_reset_size); + ps_codec->s_parse.pv_tu_coeff_data = (void *)pu1_tu_coeff_data; + +- ps_codec->s_parse.ps_tu++; +- ps_codec->s_parse.s_cu.i4_tu_cnt++; +- ps_codec->s_parse.i4_pic_tu_idx++; +- +- ps_codec->s_parse.s_cu.i4_pred_mode = PRED_MODE_SKIP; +- ps_codec->s_parse.s_cu.i4_part_mode = PART_2Nx2N; +- +- ps_pu->b2_part_idx = 0; +- ps_pu->b4_pos_x = 0; +- ps_pu->b4_pos_y = 0; +- ps_pu->b4_wd = (pu_skip_wd >> 2) - 1; +- ps_pu->b4_ht = (pu_skip_ht >> 2) - 1; +- ps_pu->b1_intra_flag = 0; +- ps_pu->b3_part_mode = ps_codec->s_parse.s_cu.i4_part_mode; +- ps_pu->b1_merge_flag = 1; +- ps_pu->b3_merge_idx = 0; +- +- ps_codec->s_parse.ps_pu++; +- ps_codec->s_parse.i4_pic_pu_idx++; ++ ihevcd_set_ctb_skip(ps_codec); + + /* Set slice error to suppress further parsing and + * signal end of slice. +@@ -2706,52 +2757,7 @@ + + } + else + { +- tu_t *ps_tu = ps_codec->s_parse.ps_tu; +- pu_t *ps_pu = ps_codec->s_parse.ps_pu; +- WORD32 pu_skip_wd, pu_skip_ht; +- WORD32 rows_remaining, cols_remaining; +- +- /* Set pu wd and ht based on whether the ctb is complete or not */ +- rows_remaining = ps_sps->i2_pic_height_in_luma_samples +- - (ps_codec->s_parse.i4_ctb_y << ps_sps->i1_log2_ctb_size); +- pu_skip_ht = MIN(ctb_size, rows_remaining); +- +- cols_remaining = ps_sps->i2_pic_width_in_luma_samples +- - (ps_codec->s_parse.i4_ctb_x << ps_sps->i1_log2_ctb_size); +- pu_skip_wd = MIN(ctb_size, cols_remaining); +- +- ps_tu->b1_cb_cbf = 0; +- ps_tu->b1_cr_cbf = 0; +- ps_tu->b1_y_cbf = 0; +- ps_tu->b4_pos_x = 0; +- ps_tu->b4_pos_y = 0; +- ps_tu->b1_transquant_bypass = 0; +- ps_tu->b3_size = (ps_sps->i1_log2_ctb_size - 2); +- ps_tu->b7_qp = ps_codec->s_parse.u4_qp; +- ps_tu->b3_chroma_intra_mode_idx = INTRA_PRED_CHROMA_IDX_NONE; +- ps_tu->b6_luma_intra_mode = INTRA_PRED_NONE; +- ps_tu->b1_first_tu_in_cu = 1; +- +- ps_codec->s_parse.ps_tu++; +- ps_codec->s_parse.s_cu.i4_tu_cnt++; +- ps_codec->s_parse.i4_pic_tu_idx++; +- +- ps_codec->s_parse.s_cu.i4_pred_mode = PRED_MODE_SKIP; +- ps_codec->s_parse.s_cu.i4_part_mode = PART_2Nx2N; +- +- ps_pu->b2_part_idx = 0; +- ps_pu->b4_pos_x = 0; +- ps_pu->b4_pos_y = 0; +- ps_pu->b4_wd = (pu_skip_wd >> 2) - 1; +- ps_pu->b4_ht = (pu_skip_ht >> 2) - 1; +- ps_pu->b1_intra_flag = 0; +- ps_pu->b3_part_mode = ps_codec->s_parse.s_cu.i4_part_mode; +- ps_pu->b1_merge_flag = 1; +- ps_pu->b3_merge_idx = 0; +- +- ps_codec->s_parse.ps_pu++; +- ps_codec->s_parse.i4_pic_pu_idx++; +- ++ ihevcd_set_ctb_skip(ps_codec); + } + + if(0 == ps_codec->i4_slice_error) +",5007,5338,6144 +17978,"int ssl3_accept(SSL *s) + { + BUF_MEM *buf; + unsigned long alg_k,Time=(unsigned long)time(NULL); + void (*cb)(const SSL *ssl,int type,int val)=NULL; + int ret= -1; + int new_state,state,skip=0; + + RAND_add(&Time,sizeof(Time),0); + ERR_clear_error(); + clear_sys_error(); + + if (s->info_callback != NULL) + cb=s->info_callback; + else if (s->ctx->info_callback != NULL) + cb=s->ctx->info_callback; + + /* init things to blank */ + s->in_handshake++; + if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); + + if (s->cert == NULL) + { + SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_NO_CERTIFICATE_SET); + return(-1); + } + +#ifndef OPENSSL_NO_HEARTBEATS + /* If we're awaiting a HeartbeatResponse, pretend we + * already got and don't await it anymore, because + * Heartbeats don't make sense during handshakes anyway. + */ + if (s->tlsext_hb_pending) + { + s->tlsext_hb_pending = 0; + s->tlsext_hb_seq++; + } +#endif + + for (;;) + { + state=s->state; + + switch (s->state) + { + case SSL_ST_RENEGOTIATE: + s->renegotiate=1; + /* s->state=SSL_ST_ACCEPT; */ + + case SSL_ST_BEFORE: + case SSL_ST_ACCEPT: + case SSL_ST_BEFORE|SSL_ST_ACCEPT: + case SSL_ST_OK|SSL_ST_ACCEPT: + + s->server=1; + if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1); + + if ((s->version>>8) != 3) + { + SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR); + return -1; + } + + if (!ssl_security(s, SSL_SECOP_VERSION, 0, + s->version, NULL)) + { + SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_VERSION_TOO_LOW); + return -1; + } + + s->type=SSL_ST_ACCEPT; + + if (s->init_buf == NULL) + { + if ((buf=BUF_MEM_new()) == NULL) + { + ret= -1; + goto end; + } + if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH)) + { + BUF_MEM_free(buf); + ret= -1; + goto end; + } + s->init_buf=buf; + } + + if (!ssl3_setup_buffers(s)) + { + ret= -1; + goto end; + } + + s->init_num=0; + s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY; + s->s3->flags &= ~SSL3_FLAGS_CCS_OK; + /* Should have been reset by ssl3_get_finished, too. */ + s->s3->change_cipher_spec = 0; + + if (s->state != SSL_ST_RENEGOTIATE) + { + /* Ok, we now need to push on a buffering BIO so that + * the output is sent in a way that TCP likes :-) + */ + if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; } + + ssl3_init_finished_mac(s); + s->state=SSL3_ST_SR_CLNT_HELLO_A; + s->ctx->stats.sess_accept++; + } + else if (!s->s3->send_connection_binding && + !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) + { + /* Server attempting to renegotiate with + * client that doesn't support secure + * renegotiation. + */ + SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); + ret = -1; + goto end; + } + else + { + /* s->state == SSL_ST_RENEGOTIATE, + * we will just send a HelloRequest */ + s->ctx->stats.sess_accept_renegotiate++; + s->state=SSL3_ST_SW_HELLO_REQ_A; + } + break; + + case SSL3_ST_SW_HELLO_REQ_A: + case SSL3_ST_SW_HELLO_REQ_B: + + s->shutdown=0; + ret=ssl3_send_hello_request(s); + if (ret <= 0) goto end; + s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C; + s->state=SSL3_ST_SW_FLUSH; + s->init_num=0; + + ssl3_init_finished_mac(s); + break; + + case SSL3_ST_SW_HELLO_REQ_C: + s->state=SSL_ST_OK; + break; + + case SSL3_ST_SR_CLNT_HELLO_A: + case SSL3_ST_SR_CLNT_HELLO_B: + case SSL3_ST_SR_CLNT_HELLO_C: + + ret=ssl3_get_client_hello(s); + if (ret <= 0) goto end; +#ifndef OPENSSL_NO_SRP + s->state = SSL3_ST_SR_CLNT_HELLO_D; + case SSL3_ST_SR_CLNT_HELLO_D: + { + int al; + if ((ret = ssl_check_srp_ext_ClientHello(s,&al)) < 0) + { + /* callback indicates firther work to be done */ + s->rwstate=SSL_X509_LOOKUP; + goto end; + } + if (ret != SSL_ERROR_NONE) + { + ssl3_send_alert(s,SSL3_AL_FATAL,al); + /* This is not really an error but the only means to + for a client to detect whether srp is supported. */ + if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY) + SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_CLIENTHELLO_TLSEXT); + ret = SSL_TLSEXT_ERR_ALERT_FATAL; + ret= -1; + goto end; + } + } +#endif + + s->renegotiate = 2; + s->state=SSL3_ST_SW_SRVR_HELLO_A; + s->init_num=0; + break; + + case SSL3_ST_SW_SRVR_HELLO_A: + case SSL3_ST_SW_SRVR_HELLO_B: + ret=ssl3_send_server_hello(s); + if (ret <= 0) goto end; +#ifndef OPENSSL_NO_TLSEXT + if (s->hit) + { + if (s->tlsext_ticket_expected) + s->state=SSL3_ST_SW_SESSION_TICKET_A; + else + s->state=SSL3_ST_SW_CHANGE_A; + } +#else + if (s->hit) + s->state=SSL3_ST_SW_CHANGE_A; +#endif + else + s->state = SSL3_ST_SW_CERT_A; + s->init_num = 0; + break; + + case SSL3_ST_SW_CERT_A: + case SSL3_ST_SW_CERT_B: + /* Check if it is anon DH or anon ECDH, */ + /* normal PSK or KRB5 or SRP */ + if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aKRB5|SSL_aSRP)) + && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) + { + ret=ssl3_send_server_certificate(s); + if (ret <= 0) goto end; +#ifndef OPENSSL_NO_TLSEXT + if (s->tlsext_status_expected) + s->state=SSL3_ST_SW_CERT_STATUS_A; + else + s->state=SSL3_ST_SW_KEY_EXCH_A; + } + else + { + skip = 1; + s->state=SSL3_ST_SW_KEY_EXCH_A; + } +#else + } + else + skip=1; + + s->state=SSL3_ST_SW_KEY_EXCH_A; +#endif + s->init_num=0; + break; + + case SSL3_ST_SW_KEY_EXCH_A: + case SSL3_ST_SW_KEY_EXCH_B: + alg_k = s->s3->tmp.new_cipher->algorithm_mkey; + + /* clear this, it may get reset by + * send_server_key_exchange */ + if ((s->options & SSL_OP_EPHEMERAL_RSA) +#ifndef OPENSSL_NO_KRB5 + && !(alg_k & SSL_kKRB5) +#endif /* OPENSSL_NO_KRB5 */ + ) + /* option SSL_OP_EPHEMERAL_RSA sends temporary RSA key + * even when forbidden by protocol specs + * (handshake may fail as clients are not required to + * be able to handle this) */ + s->s3->tmp.use_rsa_tmp=1; + else + s->s3->tmp.use_rsa_tmp=0; + + + /* only send if a DH key exchange, fortezza or + * RSA but we have a sign only certificate + * + * PSK: may send PSK identity hints + * + * For ECC ciphersuites, we send a serverKeyExchange + * message only if the cipher suite is either + * ECDH-anon or ECDHE. In other cases, the + * server certificate contains the server's + * public key for key exchange. + */ + if (s->s3->tmp.use_rsa_tmp + /* PSK: send ServerKeyExchange if PSK identity + * hint if provided */ + #ifndef OPENSSL_NO_PSK + || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint) +#endif +#ifndef OPENSSL_NO_SRP + /* SRP: send ServerKeyExchange */ + || (alg_k & SSL_kSRP) +#endif + || (alg_k & SSL_kDHE) + || (alg_k & SSL_kECDHE) + || ((alg_k & SSL_kRSA) + && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL + || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) + && EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher) + ) + ) + ) + ) + { + ret=ssl3_send_server_key_exchange(s); + if (ret <= 0) goto end; + } + else + skip=1; + + s->state=SSL3_ST_SW_CERT_REQ_A; + s->init_num=0; + break; + + case SSL3_ST_SW_CERT_REQ_A: + case SSL3_ST_SW_CERT_REQ_B: + if (/* don't request cert unless asked for it: */ + !(s->verify_mode & SSL_VERIFY_PEER) || + /* if SSL_VERIFY_CLIENT_ONCE is set, + * don't request cert during re-negotiation: */ + ((s->session->peer != NULL) && + (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) || + /* never request cert in anonymous ciphersuites + * (see section ""Certificate request"" in SSL 3 drafts + * and in RFC 2246): */ + ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) && + /* ... except when the application insists on verification + * (against the specs, but s3_clnt.c accepts this for SSL 3) */ + !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) || + /* never request cert in Kerberos ciphersuites */ + (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) || + /* don't request certificate for SRP auth */ + (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP) + /* With normal PSK Certificates and + * Certificate Requests are omitted */ + || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) + { + /* no cert request */ + skip=1; + s->s3->tmp.cert_request=0; + s->state=SSL3_ST_SW_SRVR_DONE_A; + if (s->s3->handshake_buffer) + if (!ssl3_digest_cached_records(s)) + return -1; + } + else + { + s->s3->tmp.cert_request=1; + ret=ssl3_send_certificate_request(s); + if (ret <= 0) goto end; +#ifndef NETSCAPE_HANG_BUG + s->state=SSL3_ST_SW_SRVR_DONE_A; +#else + s->state=SSL3_ST_SW_FLUSH; + s->s3->tmp.next_state=SSL3_ST_SR_CERT_A; +#endif + s->init_num=0; + } + break; + + case SSL3_ST_SW_SRVR_DONE_A: + case SSL3_ST_SW_SRVR_DONE_B: + ret=ssl3_send_server_done(s); + if (ret <= 0) goto end; + s->s3->tmp.next_state=SSL3_ST_SR_CERT_A; + s->state=SSL3_ST_SW_FLUSH; + s->init_num=0; + break; + + case SSL3_ST_SW_FLUSH: + + /* This code originally checked to see if + * any data was pending using BIO_CTRL_INFO + * and then flushed. This caused problems + * as documented in PR#1939. The proposed + * fix doesn't completely resolve this issue + * as buggy implementations of BIO_CTRL_PENDING + * still exist. So instead we just flush + * unconditionally. + */ + + s->rwstate=SSL_WRITING; + if (BIO_flush(s->wbio) <= 0) + { + ret= -1; + goto end; + } + s->rwstate=SSL_NOTHING; + + s->state=s->s3->tmp.next_state; + break; + + case SSL3_ST_SR_CERT_A: + case SSL3_ST_SR_CERT_B: + if (s->s3->tmp.cert_request) + { + ret=ssl3_get_client_certificate(s); + if (ret <= 0) goto end; + } + s->init_num=0; + s->state=SSL3_ST_SR_KEY_EXCH_A; + break; + + case SSL3_ST_SR_KEY_EXCH_A: + case SSL3_ST_SR_KEY_EXCH_B: + ret=ssl3_get_client_key_exchange(s); + if (ret <= 0) + goto end; + if (ret == 2) + { + /* For the ECDH ciphersuites when + * the client sends its ECDH pub key in + * a certificate, the CertificateVerify + * message is not sent. + * Also for GOST ciphersuites when + * the client uses its key from the certificate + * for key exchange. + */ +#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->state=SSL3_ST_SR_FINISHED_A; +#else + if (s->s3->next_proto_neg_seen) + s->state=SSL3_ST_SR_NEXT_PROTO_A; + else + s->state=SSL3_ST_SR_FINISHED_A; +#endif + s->init_num = 0; + } + else if (SSL_USE_SIGALGS(s)) + { + s->state=SSL3_ST_SR_CERT_VRFY_A; + s->init_num=0; + if (!s->session->peer) + break; + /* For sigalgs freeze the handshake buffer + * at this point and digest cached records. + */ + if (!s->s3->handshake_buffer) + { + SSLerr(SSL_F_SSL3_ACCEPT,ERR_R_INTERNAL_ERROR); + return -1; + } + s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE; + if (!ssl3_digest_cached_records(s)) + return -1; + } + else + { + int offset=0; + int dgst_num; + + s->state=SSL3_ST_SR_CERT_VRFY_A; + s->init_num=0; + + /* We need to get hashes here so if there is + * a client cert, it can be verified + * FIXME - digest processing for CertificateVerify + * should be generalized. But it is next step + */ + if (s->s3->handshake_buffer) + if (!ssl3_digest_cached_records(s)) + return -1; + for (dgst_num=0; dgst_nums3->handshake_dgst[dgst_num]) + { + int dgst_size; + + s->method->ssl3_enc->cert_verify_mac(s,EVP_MD_CTX_type(s->s3->handshake_dgst[dgst_num]),&(s->s3->tmp.cert_verify_md[offset])); + dgst_size=EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]); + if (dgst_size < 0) + { + ret = -1; + goto end; + } + offset+=dgst_size; + } + } + break; + + case SSL3_ST_SR_CERT_VRFY_A: + case SSL3_ST_SR_CERT_VRFY_B: + /* + * This *should* be the first time we enable CCS, but be + * extra careful about surrounding code changes. We need + * to set this here because we don't know if we're + * expecting a CertificateVerify or not. + */ + if (!s->s3->change_cipher_spec) + s->s3->flags |= SSL3_FLAGS_CCS_OK; + /* we should decide if we expected this one */ + ret=ssl3_get_cert_verify(s); + if (ret <= 0) goto end; + +#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->state=SSL3_ST_SR_FINISHED_A; +#else + if (s->s3->next_proto_neg_seen) + s->state=SSL3_ST_SR_NEXT_PROTO_A; + else + s->state=SSL3_ST_SR_FINISHED_A; +#endif + s->init_num=0; + break; + +#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) + case SSL3_ST_SR_NEXT_PROTO_A: + case SSL3_ST_SR_NEXT_PROTO_B: + /* + * Enable CCS for resumed handshakes with NPN. + * In a full handshake with NPN, we end up here through + * SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was + * already set. Receiving a CCS clears the flag, so make + * sure not to re-enable it to ban duplicates. + * s->s3->change_cipher_spec is set when a CCS is + * processed in s3_pkt.c, and remains set until + * the client's Finished message is read. + */ + if (!s->s3->change_cipher_spec) + s->s3->flags |= SSL3_FLAGS_CCS_OK; + + ret=ssl3_get_next_proto(s); + if (ret <= 0) goto end; + s->init_num = 0; + s->state=SSL3_ST_SR_FINISHED_A; + break; +#endif + + case SSL3_ST_SR_FINISHED_A: + case SSL3_ST_SR_FINISHED_B: + /* + * Enable CCS for resumed handshakes without NPN. + * In a full handshake, we end up here through + * SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was + * already set. Receiving a CCS clears the flag, so make + * sure not to re-enable it to ban duplicates. + * s->s3->change_cipher_spec is set when a CCS is + * processed in s3_pkt.c, and remains set until + * the client's Finished message is read. + */ + if (!s->s3->change_cipher_spec) + s->s3->flags |= SSL3_FLAGS_CCS_OK; + ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A, + SSL3_ST_SR_FINISHED_B); + if (ret <= 0) goto end; + if (s->hit) + s->state=SSL_ST_OK; +#ifndef OPENSSL_NO_TLSEXT + else if (s->tlsext_ticket_expected) + s->state=SSL3_ST_SW_SESSION_TICKET_A; +#endif + else + s->state=SSL3_ST_SW_CHANGE_A; + s->init_num=0; + break; + +#ifndef OPENSSL_NO_TLSEXT + case SSL3_ST_SW_SESSION_TICKET_A: + case SSL3_ST_SW_SESSION_TICKET_B: + ret=ssl3_send_newsession_ticket(s); + if (ret <= 0) goto end; + s->state=SSL3_ST_SW_CHANGE_A; + s->init_num=0; + break; + + case SSL3_ST_SW_CERT_STATUS_A: + case SSL3_ST_SW_CERT_STATUS_B: + ret=ssl3_send_cert_status(s); + if (ret <= 0) goto end; + s->state=SSL3_ST_SW_KEY_EXCH_A; + s->init_num=0; + break; + +#endif + + case SSL3_ST_SW_CHANGE_A: + case SSL3_ST_SW_CHANGE_B: + + s->session->cipher=s->s3->tmp.new_cipher; + if (!s->method->ssl3_enc->setup_key_block(s)) + { ret= -1; goto end; } + + ret=ssl3_send_change_cipher_spec(s, + SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B); + + if (ret <= 0) goto end; + s->state=SSL3_ST_SW_FINISHED_A; + s->init_num=0; + + if (!s->method->ssl3_enc->change_cipher_state(s, + SSL3_CHANGE_CIPHER_SERVER_WRITE)) + { + ret= -1; + goto end; + } + + break; + + case SSL3_ST_SW_FINISHED_A: + case SSL3_ST_SW_FINISHED_B: + ret=ssl3_send_finished(s, + SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B, + s->method->ssl3_enc->server_finished_label, + s->method->ssl3_enc->server_finished_label_len); + if (ret <= 0) goto end; + s->state=SSL3_ST_SW_FLUSH; + if (s->hit) + { +#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A; +#else + if (s->s3->next_proto_neg_seen) + { + s->s3->tmp.next_state=SSL3_ST_SR_NEXT_PROTO_A; + } + else + s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A; +#endif + } + else + s->s3->tmp.next_state=SSL_ST_OK; + s->init_num=0; + break; + + case SSL_ST_OK: + /* clean a few things up */ + ssl3_cleanup_key_block(s); + + BUF_MEM_free(s->init_buf); + s->init_buf=NULL; + + /* remove buffering on output */ + ssl_free_wbio_buffer(s); + + s->init_num=0; + + if (s->renegotiate == 2) /* skipped if we just sent a HelloRequest */ + { + s->renegotiate=0; + s->new_session=0; + + ssl_update_cache(s,SSL_SESS_CACHE_SERVER); + + s->ctx->stats.sess_accept_good++; + /* s->server=1; */ + s->handshake_func=ssl3_accept; + + if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1); + } + + ret = 1; + goto end; + /* break; */ + + default: + SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE); + ret= -1; + goto end; + /* break; */ + } + + if (!s->s3->tmp.reuse_message && !skip) + { + if (s->debug) + { + if ((ret=BIO_flush(s->wbio)) <= 0) + goto end; + } + + + if ((cb != NULL) && (s->state != state)) + { + new_state=s->state; + s->state=state; + cb(s,SSL_CB_ACCEPT_LOOP,1); + s->state=new_state; + } + } + skip=0; + } +",1,"int ssl3_accept(SSL *s) + { + BUF_MEM *buf; + unsigned long alg_k,Time=(unsigned long)time(NULL); + void (*cb)(const SSL *ssl,int type,int val)=NULL; + int ret= -1; + int new_state,state,skip=0; + + RAND_add(&Time,sizeof(Time),0); + ERR_clear_error(); + clear_sys_error(); + + if (s->info_callback != NULL) + cb=s->info_callback; + else if (s->ctx->info_callback != NULL) + cb=s->ctx->info_callback; + + /* init things to blank */ + s->in_handshake++; + if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); + + if (s->cert == NULL) + { + SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_NO_CERTIFICATE_SET); + return(-1); + } + +#ifndef OPENSSL_NO_HEARTBEATS + /* If we're awaiting a HeartbeatResponse, pretend we + * already got and don't await it anymore, because + * Heartbeats don't make sense during handshakes anyway. + */ + if (s->tlsext_hb_pending) + { + s->tlsext_hb_pending = 0; + s->tlsext_hb_seq++; + } +#endif + + for (;;) + { + state=s->state; + + switch (s->state) + { + case SSL_ST_RENEGOTIATE: + s->renegotiate=1; + /* s->state=SSL_ST_ACCEPT; */ + + case SSL_ST_BEFORE: + case SSL_ST_ACCEPT: + case SSL_ST_BEFORE|SSL_ST_ACCEPT: + case SSL_ST_OK|SSL_ST_ACCEPT: + + s->server=1; + if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1); + + if ((s->version>>8) != 3) + { + SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR); + return -1; + } + + if (!ssl_security(s, SSL_SECOP_VERSION, 0, + s->version, NULL)) + { + SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_VERSION_TOO_LOW); + return -1; + } + + s->type=SSL_ST_ACCEPT; + + if (s->init_buf == NULL) + { + if ((buf=BUF_MEM_new()) == NULL) + { + ret= -1; + goto end; + } + if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH)) + { + BUF_MEM_free(buf); + ret= -1; + goto end; + } + s->init_buf=buf; + } + + if (!ssl3_setup_buffers(s)) + { + ret= -1; + goto end; + } + + s->init_num=0; + s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY; + s->s3->flags &= ~SSL3_FLAGS_CCS_OK; + /* Should have been reset by ssl3_get_finished, too. */ + s->s3->change_cipher_spec = 0; + + if (s->state != SSL_ST_RENEGOTIATE) + { + /* Ok, we now need to push on a buffering BIO so that + * the output is sent in a way that TCP likes :-) + */ + if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; } + + ssl3_init_finished_mac(s); + s->state=SSL3_ST_SR_CLNT_HELLO_A; + s->ctx->stats.sess_accept++; + } + else if (!s->s3->send_connection_binding && + !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) + { + /* Server attempting to renegotiate with + * client that doesn't support secure + * renegotiation. + */ + SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); + ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE); + ret = -1; + goto end; + } + else + { + /* s->state == SSL_ST_RENEGOTIATE, + * we will just send a HelloRequest */ + s->ctx->stats.sess_accept_renegotiate++; + s->state=SSL3_ST_SW_HELLO_REQ_A; + } + break; + + case SSL3_ST_SW_HELLO_REQ_A: + case SSL3_ST_SW_HELLO_REQ_B: + + s->shutdown=0; + ret=ssl3_send_hello_request(s); + if (ret <= 0) goto end; + s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C; + s->state=SSL3_ST_SW_FLUSH; + s->init_num=0; + + ssl3_init_finished_mac(s); + break; + + case SSL3_ST_SW_HELLO_REQ_C: + s->state=SSL_ST_OK; + break; + + case SSL3_ST_SR_CLNT_HELLO_A: + case SSL3_ST_SR_CLNT_HELLO_B: + case SSL3_ST_SR_CLNT_HELLO_C: + + ret=ssl3_get_client_hello(s); + if (ret <= 0) goto end; +#ifndef OPENSSL_NO_SRP + s->state = SSL3_ST_SR_CLNT_HELLO_D; + case SSL3_ST_SR_CLNT_HELLO_D: + { + int al; + if ((ret = ssl_check_srp_ext_ClientHello(s,&al)) < 0) + { + /* callback indicates firther work to be done */ + s->rwstate=SSL_X509_LOOKUP; + goto end; + } + if (ret != SSL_ERROR_NONE) + { + ssl3_send_alert(s,SSL3_AL_FATAL,al); + /* This is not really an error but the only means to + for a client to detect whether srp is supported. */ + if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY) + SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_CLIENTHELLO_TLSEXT); + ret = SSL_TLSEXT_ERR_ALERT_FATAL; + ret= -1; + goto end; + } + } +#endif + + s->renegotiate = 2; + s->state=SSL3_ST_SW_SRVR_HELLO_A; + s->init_num=0; + break; + + case SSL3_ST_SW_SRVR_HELLO_A: + case SSL3_ST_SW_SRVR_HELLO_B: + ret=ssl3_send_server_hello(s); + if (ret <= 0) goto end; +#ifndef OPENSSL_NO_TLSEXT + if (s->hit) + { + if (s->tlsext_ticket_expected) + s->state=SSL3_ST_SW_SESSION_TICKET_A; + else + s->state=SSL3_ST_SW_CHANGE_A; + } +#else + if (s->hit) + s->state=SSL3_ST_SW_CHANGE_A; +#endif + else + s->state = SSL3_ST_SW_CERT_A; + s->init_num = 0; + break; + + case SSL3_ST_SW_CERT_A: + case SSL3_ST_SW_CERT_B: + /* Check if it is anon DH or anon ECDH, */ + /* normal PSK or KRB5 or SRP */ + if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aKRB5|SSL_aSRP)) + && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) + { + ret=ssl3_send_server_certificate(s); + if (ret <= 0) goto end; +#ifndef OPENSSL_NO_TLSEXT + if (s->tlsext_status_expected) + s->state=SSL3_ST_SW_CERT_STATUS_A; + else + s->state=SSL3_ST_SW_KEY_EXCH_A; + } + else + { + skip = 1; + s->state=SSL3_ST_SW_KEY_EXCH_A; + } +#else + } + else + skip=1; + + s->state=SSL3_ST_SW_KEY_EXCH_A; +#endif + s->init_num=0; + break; + + case SSL3_ST_SW_KEY_EXCH_A: + case SSL3_ST_SW_KEY_EXCH_B: + alg_k = s->s3->tmp.new_cipher->algorithm_mkey; + + /* + * clear this, it may get reset by + * send_server_key_exchange + */ + s->s3->tmp.use_rsa_tmp=0; + + + /* only send if a DH key exchange, fortezza or + * RSA but we have a sign only certificate + * + * PSK: may send PSK identity hints + * + * For ECC ciphersuites, we send a serverKeyExchange + * message only if the cipher suite is either + * ECDH-anon or ECDHE. In other cases, the + * server certificate contains the server's + * public key for key exchange. + */ + if ( + /* PSK: send ServerKeyExchange if PSK identity + * hint if provided */ + #ifndef OPENSSL_NO_PSK + || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint) +#endif +#ifndef OPENSSL_NO_SRP + /* SRP: send ServerKeyExchange */ + || (alg_k & SSL_kSRP) +#endif + || (alg_k & SSL_kDHE) + || (alg_k & SSL_kECDHE) + || ((alg_k & SSL_kRSA) + && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL + || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) + && EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher) + ) + ) + ) + ) + { + ret=ssl3_send_server_key_exchange(s); + if (ret <= 0) goto end; + } + else + skip=1; + + s->state=SSL3_ST_SW_CERT_REQ_A; + s->init_num=0; + break; + + case SSL3_ST_SW_CERT_REQ_A: + case SSL3_ST_SW_CERT_REQ_B: + if (/* don't request cert unless asked for it: */ + !(s->verify_mode & SSL_VERIFY_PEER) || + /* if SSL_VERIFY_CLIENT_ONCE is set, + * don't request cert during re-negotiation: */ + ((s->session->peer != NULL) && + (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) || + /* never request cert in anonymous ciphersuites + * (see section ""Certificate request"" in SSL 3 drafts + * and in RFC 2246): */ + ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) && + /* ... except when the application insists on verification + * (against the specs, but s3_clnt.c accepts this for SSL 3) */ + !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) || + /* never request cert in Kerberos ciphersuites */ + (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) || + /* don't request certificate for SRP auth */ + (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP) + /* With normal PSK Certificates and + * Certificate Requests are omitted */ + || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) + { + /* no cert request */ + skip=1; + s->s3->tmp.cert_request=0; + s->state=SSL3_ST_SW_SRVR_DONE_A; + if (s->s3->handshake_buffer) + if (!ssl3_digest_cached_records(s)) + return -1; + } + else + { + s->s3->tmp.cert_request=1; + ret=ssl3_send_certificate_request(s); + if (ret <= 0) goto end; +#ifndef NETSCAPE_HANG_BUG + s->state=SSL3_ST_SW_SRVR_DONE_A; +#else + s->state=SSL3_ST_SW_FLUSH; + s->s3->tmp.next_state=SSL3_ST_SR_CERT_A; +#endif + s->init_num=0; + } + break; + + case SSL3_ST_SW_SRVR_DONE_A: + case SSL3_ST_SW_SRVR_DONE_B: + ret=ssl3_send_server_done(s); + if (ret <= 0) goto end; + s->s3->tmp.next_state=SSL3_ST_SR_CERT_A; + s->state=SSL3_ST_SW_FLUSH; + s->init_num=0; + break; + + case SSL3_ST_SW_FLUSH: + + /* This code originally checked to see if + * any data was pending using BIO_CTRL_INFO + * and then flushed. This caused problems + * as documented in PR#1939. The proposed + * fix doesn't completely resolve this issue + * as buggy implementations of BIO_CTRL_PENDING + * still exist. So instead we just flush + * unconditionally. + */ + + s->rwstate=SSL_WRITING; + if (BIO_flush(s->wbio) <= 0) + { + ret= -1; + goto end; + } + s->rwstate=SSL_NOTHING; + + s->state=s->s3->tmp.next_state; + break; + + case SSL3_ST_SR_CERT_A: + case SSL3_ST_SR_CERT_B: + if (s->s3->tmp.cert_request) + { + ret=ssl3_get_client_certificate(s); + if (ret <= 0) goto end; + } + s->init_num=0; + s->state=SSL3_ST_SR_KEY_EXCH_A; + break; + + case SSL3_ST_SR_KEY_EXCH_A: + case SSL3_ST_SR_KEY_EXCH_B: + ret=ssl3_get_client_key_exchange(s); + if (ret <= 0) + goto end; + if (ret == 2) + { + /* For the ECDH ciphersuites when + * the client sends its ECDH pub key in + * a certificate, the CertificateVerify + * message is not sent. + * Also for GOST ciphersuites when + * the client uses its key from the certificate + * for key exchange. + */ +#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->state=SSL3_ST_SR_FINISHED_A; +#else + if (s->s3->next_proto_neg_seen) + s->state=SSL3_ST_SR_NEXT_PROTO_A; + else + s->state=SSL3_ST_SR_FINISHED_A; +#endif + s->init_num = 0; + } + else if (SSL_USE_SIGALGS(s)) + { + s->state=SSL3_ST_SR_CERT_VRFY_A; + s->init_num=0; + if (!s->session->peer) + break; + /* For sigalgs freeze the handshake buffer + * at this point and digest cached records. + */ + if (!s->s3->handshake_buffer) + { + SSLerr(SSL_F_SSL3_ACCEPT,ERR_R_INTERNAL_ERROR); + return -1; + } + s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE; + if (!ssl3_digest_cached_records(s)) + return -1; + } + else + { + int offset=0; + int dgst_num; + + s->state=SSL3_ST_SR_CERT_VRFY_A; + s->init_num=0; + + /* We need to get hashes here so if there is + * a client cert, it can be verified + * FIXME - digest processing for CertificateVerify + * should be generalized. But it is next step + */ + if (s->s3->handshake_buffer) + if (!ssl3_digest_cached_records(s)) + return -1; + for (dgst_num=0; dgst_nums3->handshake_dgst[dgst_num]) + { + int dgst_size; + + s->method->ssl3_enc->cert_verify_mac(s,EVP_MD_CTX_type(s->s3->handshake_dgst[dgst_num]),&(s->s3->tmp.cert_verify_md[offset])); + dgst_size=EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]); + if (dgst_size < 0) + { + ret = -1; + goto end; + } + offset+=dgst_size; + } + } + break; + + case SSL3_ST_SR_CERT_VRFY_A: + case SSL3_ST_SR_CERT_VRFY_B: + /* + * This *should* be the first time we enable CCS, but be + * extra careful about surrounding code changes. We need + * to set this here because we don't know if we're + * expecting a CertificateVerify or not. + */ + if (!s->s3->change_cipher_spec) + s->s3->flags |= SSL3_FLAGS_CCS_OK; + /* we should decide if we expected this one */ + ret=ssl3_get_cert_verify(s); + if (ret <= 0) goto end; + +#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->state=SSL3_ST_SR_FINISHED_A; +#else + if (s->s3->next_proto_neg_seen) + s->state=SSL3_ST_SR_NEXT_PROTO_A; + else + s->state=SSL3_ST_SR_FINISHED_A; +#endif + s->init_num=0; + break; + +#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) + case SSL3_ST_SR_NEXT_PROTO_A: + case SSL3_ST_SR_NEXT_PROTO_B: + /* + * Enable CCS for resumed handshakes with NPN. + * In a full handshake with NPN, we end up here through + * SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was + * already set. Receiving a CCS clears the flag, so make + * sure not to re-enable it to ban duplicates. + * s->s3->change_cipher_spec is set when a CCS is + * processed in s3_pkt.c, and remains set until + * the client's Finished message is read. + */ + if (!s->s3->change_cipher_spec) + s->s3->flags |= SSL3_FLAGS_CCS_OK; + + ret=ssl3_get_next_proto(s); + if (ret <= 0) goto end; + s->init_num = 0; + s->state=SSL3_ST_SR_FINISHED_A; + break; +#endif + + case SSL3_ST_SR_FINISHED_A: + case SSL3_ST_SR_FINISHED_B: + /* + * Enable CCS for resumed handshakes without NPN. + * In a full handshake, we end up here through + * SSL3_ST_SR_CERT_VRFY_B, where SSL3_FLAGS_CCS_OK was + * already set. Receiving a CCS clears the flag, so make + * sure not to re-enable it to ban duplicates. + * s->s3->change_cipher_spec is set when a CCS is + * processed in s3_pkt.c, and remains set until + * the client's Finished message is read. + */ + if (!s->s3->change_cipher_spec) + s->s3->flags |= SSL3_FLAGS_CCS_OK; + ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A, + SSL3_ST_SR_FINISHED_B); + if (ret <= 0) goto end; + if (s->hit) + s->state=SSL_ST_OK; +#ifndef OPENSSL_NO_TLSEXT + else if (s->tlsext_ticket_expected) + s->state=SSL3_ST_SW_SESSION_TICKET_A; +#endif + else + s->state=SSL3_ST_SW_CHANGE_A; + s->init_num=0; + break; + +#ifndef OPENSSL_NO_TLSEXT + case SSL3_ST_SW_SESSION_TICKET_A: + case SSL3_ST_SW_SESSION_TICKET_B: + ret=ssl3_send_newsession_ticket(s); + if (ret <= 0) goto end; + s->state=SSL3_ST_SW_CHANGE_A; + s->init_num=0; + break; + + case SSL3_ST_SW_CERT_STATUS_A: + case SSL3_ST_SW_CERT_STATUS_B: + ret=ssl3_send_cert_status(s); + if (ret <= 0) goto end; + s->state=SSL3_ST_SW_KEY_EXCH_A; + s->init_num=0; + break; + +#endif + + case SSL3_ST_SW_CHANGE_A: + case SSL3_ST_SW_CHANGE_B: + + s->session->cipher=s->s3->tmp.new_cipher; + if (!s->method->ssl3_enc->setup_key_block(s)) + { ret= -1; goto end; } + + ret=ssl3_send_change_cipher_spec(s, + SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B); + + if (ret <= 0) goto end; + s->state=SSL3_ST_SW_FINISHED_A; + s->init_num=0; + + if (!s->method->ssl3_enc->change_cipher_state(s, + SSL3_CHANGE_CIPHER_SERVER_WRITE)) + { + ret= -1; + goto end; + } + + break; + + case SSL3_ST_SW_FINISHED_A: + case SSL3_ST_SW_FINISHED_B: + ret=ssl3_send_finished(s, + SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B, + s->method->ssl3_enc->server_finished_label, + s->method->ssl3_enc->server_finished_label_len); + if (ret <= 0) goto end; + s->state=SSL3_ST_SW_FLUSH; + if (s->hit) + { +#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A; +#else + if (s->s3->next_proto_neg_seen) + { + s->s3->tmp.next_state=SSL3_ST_SR_NEXT_PROTO_A; + } + else + s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A; +#endif + } + else + s->s3->tmp.next_state=SSL_ST_OK; + s->init_num=0; + break; + + case SSL_ST_OK: + /* clean a few things up */ + ssl3_cleanup_key_block(s); + + BUF_MEM_free(s->init_buf); + s->init_buf=NULL; + + /* remove buffering on output */ + ssl_free_wbio_buffer(s); + + s->init_num=0; + + if (s->renegotiate == 2) /* skipped if we just sent a HelloRequest */ + { + s->renegotiate=0; + s->new_session=0; + + ssl_update_cache(s,SSL_SESS_CACHE_SERVER); + + s->ctx->stats.sess_accept_good++; + /* s->server=1; */ + s->handshake_func=ssl3_accept; + + if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1); + } + + ret = 1; + goto end; + /* break; */ + + default: + SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE); + ret= -1; + goto end; + /* break; */ + } + + if (!s->s3->tmp.reuse_message && !skip) + { + if (s->debug) + { + if ((ret=BIO_flush(s->wbio)) <= 0) + goto end; + } + + + if ((cb != NULL) && (s->state != state)) + { + new_state=s->state; + s->state=state; + cb(s,SSL_CB_ACCEPT_LOOP,1); + s->state=new_state; + } + } + skip=0; + } +","@@ -453,20 +453,11 @@ int ssl3_accept(SSL *s) + case SSL3_ST_SW_KEY_EXCH_B: + alg_k = s->s3->tmp.new_cipher->algorithm_mkey; + +- /* clear this, it may get reset by +- * send_server_key_exchange */ +- if ((s->options & SSL_OP_EPHEMERAL_RSA) +-#ifndef OPENSSL_NO_KRB5 +- && !(alg_k & SSL_kKRB5) +-#endif /* OPENSSL_NO_KRB5 */ +- ) +- /* option SSL_OP_EPHEMERAL_RSA sends temporary RSA key +- * even when forbidden by protocol specs +- * (handshake may fail as clients are not required to +- * be able to handle this) */ +- s->s3->tmp.use_rsa_tmp=1; +- else +- s->s3->tmp.use_rsa_tmp=0; ++ /* ++ * clear this, it may get reset by ++ * send_server_key_exchange ++ */ ++ s->s3->tmp.use_rsa_tmp=0; + + + /* only send if a DH key exchange, fortezza or +@@ -480,7 +471,7 @@ int ssl3_accept(SSL *s) + * server certificate contains the server's + * public key for key exchange. + */ +- if (s->s3->tmp.use_rsa_tmp ++ if ( + /* PSK: send ServerKeyExchange if PSK identity + * hint if provided */ + #ifndef OPENSSL_NO_PSK",5505,5836,6144 +3887,"unsigned int __sk_run_filter(void *ctx, const struct sock_filter_int *insn) +{ + u64 stack[MAX_BPF_STACK / sizeof(u64)]; + u64 regs[MAX_BPF_REG], tmp; + void *ptr; + int off; + +#define K insn->imm +#define A regs[insn->a_reg] +#define X regs[insn->x_reg] +#define R0 regs[0] + +#define CONT ({insn++; goto select_insn; }) +#define CONT_JMP ({insn++; goto select_insn; }) + + static const void *jumptable[256] = { + [0 ... 255] = &&default_label, + /* Now overwrite non-defaults ... */ +#define DL(A, B, C) [A|B|C] = &&A##_##B##_##C + DL(BPF_ALU, BPF_ADD, BPF_X), + DL(BPF_ALU, BPF_ADD, BPF_K), + DL(BPF_ALU, BPF_SUB, BPF_X), + DL(BPF_ALU, BPF_SUB, BPF_K), + DL(BPF_ALU, BPF_AND, BPF_X), + DL(BPF_ALU, BPF_AND, BPF_K), + DL(BPF_ALU, BPF_OR, BPF_X), + DL(BPF_ALU, BPF_OR, BPF_K), + DL(BPF_ALU, BPF_LSH, BPF_X), + DL(BPF_ALU, BPF_LSH, BPF_K), + DL(BPF_ALU, BPF_RSH, BPF_X), + DL(BPF_ALU, BPF_RSH, BPF_K), + DL(BPF_ALU, BPF_XOR, BPF_X), + DL(BPF_ALU, BPF_XOR, BPF_K), + DL(BPF_ALU, BPF_MUL, BPF_X), + DL(BPF_ALU, BPF_MUL, BPF_K), + DL(BPF_ALU, BPF_MOV, BPF_X), + DL(BPF_ALU, BPF_MOV, BPF_K), + DL(BPF_ALU, BPF_DIV, BPF_X), + DL(BPF_ALU, BPF_DIV, BPF_K), + DL(BPF_ALU, BPF_MOD, BPF_X), + DL(BPF_ALU, BPF_MOD, BPF_K), + DL(BPF_ALU, BPF_NEG, 0), + DL(BPF_ALU, BPF_END, BPF_TO_BE), + DL(BPF_ALU, BPF_END, BPF_TO_LE), + DL(BPF_ALU64, BPF_ADD, BPF_X), + DL(BPF_ALU64, BPF_ADD, BPF_K), + DL(BPF_ALU64, BPF_SUB, BPF_X), + DL(BPF_ALU64, BPF_SUB, BPF_K), + DL(BPF_ALU64, BPF_AND, BPF_X), + DL(BPF_ALU64, BPF_AND, BPF_K), + DL(BPF_ALU64, BPF_OR, BPF_X), + DL(BPF_ALU64, BPF_OR, BPF_K), + DL(BPF_ALU64, BPF_LSH, BPF_X), + DL(BPF_ALU64, BPF_LSH, BPF_K), + DL(BPF_ALU64, BPF_RSH, BPF_X), + DL(BPF_ALU64, BPF_RSH, BPF_K), + DL(BPF_ALU64, BPF_XOR, BPF_X), + DL(BPF_ALU64, BPF_XOR, BPF_K), + DL(BPF_ALU64, BPF_MUL, BPF_X), + DL(BPF_ALU64, BPF_MUL, BPF_K), + DL(BPF_ALU64, BPF_MOV, BPF_X), + DL(BPF_ALU64, BPF_MOV, BPF_K), + DL(BPF_ALU64, BPF_ARSH, BPF_X), + DL(BPF_ALU64, BPF_ARSH, BPF_K), + DL(BPF_ALU64, BPF_DIV, BPF_X), + DL(BPF_ALU64, BPF_DIV, BPF_K), + DL(BPF_ALU64, BPF_MOD, BPF_X), + DL(BPF_ALU64, BPF_MOD, BPF_K), + DL(BPF_ALU64, BPF_NEG, 0), + DL(BPF_JMP, BPF_CALL, 0), + DL(BPF_JMP, BPF_JA, 0), + DL(BPF_JMP, BPF_JEQ, BPF_X), + DL(BPF_JMP, BPF_JEQ, BPF_K), + DL(BPF_JMP, BPF_JNE, BPF_X), + DL(BPF_JMP, BPF_JNE, BPF_K), + DL(BPF_JMP, BPF_JGT, BPF_X), + DL(BPF_JMP, BPF_JGT, BPF_K), + DL(BPF_JMP, BPF_JGE, BPF_X), + DL(BPF_JMP, BPF_JGE, BPF_K), + DL(BPF_JMP, BPF_JSGT, BPF_X), + DL(BPF_JMP, BPF_JSGT, BPF_K), + DL(BPF_JMP, BPF_JSGE, BPF_X), + DL(BPF_JMP, BPF_JSGE, BPF_K), + DL(BPF_JMP, BPF_JSET, BPF_X), + DL(BPF_JMP, BPF_JSET, BPF_K), + DL(BPF_JMP, BPF_EXIT, 0), + DL(BPF_STX, BPF_MEM, BPF_B), + DL(BPF_STX, BPF_MEM, BPF_H), + DL(BPF_STX, BPF_MEM, BPF_W), + DL(BPF_STX, BPF_MEM, BPF_DW), + DL(BPF_STX, BPF_XADD, BPF_W), + DL(BPF_STX, BPF_XADD, BPF_DW), + DL(BPF_ST, BPF_MEM, BPF_B), + DL(BPF_ST, BPF_MEM, BPF_H), + DL(BPF_ST, BPF_MEM, BPF_W), + DL(BPF_ST, BPF_MEM, BPF_DW), + DL(BPF_LDX, BPF_MEM, BPF_B), + DL(BPF_LDX, BPF_MEM, BPF_H), + DL(BPF_LDX, BPF_MEM, BPF_W), + DL(BPF_LDX, BPF_MEM, BPF_DW), + DL(BPF_LD, BPF_ABS, BPF_W), + DL(BPF_LD, BPF_ABS, BPF_H), + DL(BPF_LD, BPF_ABS, BPF_B), + DL(BPF_LD, BPF_IND, BPF_W), + DL(BPF_LD, BPF_IND, BPF_H), + DL(BPF_LD, BPF_IND, BPF_B), +#undef DL + }; + + regs[FP_REG] = (u64) (unsigned long) &stack[ARRAY_SIZE(stack)]; + regs[ARG1_REG] = (u64) (unsigned long) ctx; + +select_insn: + goto *jumptable[insn->code]; + + /* ALU */ +#define ALU(OPCODE, OP) \ + BPF_ALU64_##OPCODE##_BPF_X: \ + A = A OP X; \ + CONT; \ + BPF_ALU_##OPCODE##_BPF_X: \ + A = (u32) A OP (u32) X; \ + CONT; \ + BPF_ALU64_##OPCODE##_BPF_K: \ + A = A OP K; \ + CONT; \ + BPF_ALU_##OPCODE##_BPF_K: \ + A = (u32) A OP (u32) K; \ + CONT; + + ALU(BPF_ADD, +) + ALU(BPF_SUB, -) + ALU(BPF_AND, &) + ALU(BPF_OR, |) + ALU(BPF_LSH, <<) + ALU(BPF_RSH, >>) + ALU(BPF_XOR, ^) + ALU(BPF_MUL, *) +#undef ALU + BPF_ALU_BPF_NEG_0: + A = (u32) -A; + CONT; + BPF_ALU64_BPF_NEG_0: + A = -A; + CONT; + BPF_ALU_BPF_MOV_BPF_X: + A = (u32) X; + CONT; + BPF_ALU_BPF_MOV_BPF_K: + A = (u32) K; + CONT; + BPF_ALU64_BPF_MOV_BPF_X: + A = X; + CONT; + BPF_ALU64_BPF_MOV_BPF_K: + A = K; + CONT; + BPF_ALU64_BPF_ARSH_BPF_X: + (*(s64 *) &A) >>= X; + CONT; + BPF_ALU64_BPF_ARSH_BPF_K: + (*(s64 *) &A) >>= K; + CONT; + BPF_ALU64_BPF_MOD_BPF_X: + if (unlikely(X == 0)) + return 0; + tmp = A; + A = do_div(tmp, X); + CONT; + BPF_ALU_BPF_MOD_BPF_X: + if (unlikely(X == 0)) + return 0; + tmp = (u32) A; + A = do_div(tmp, (u32) X); + CONT; + BPF_ALU64_BPF_MOD_BPF_K: + tmp = A; + A = do_div(tmp, K); + CONT; + BPF_ALU_BPF_MOD_BPF_K: + tmp = (u32) A; + A = do_div(tmp, (u32) K); + CONT; + BPF_ALU64_BPF_DIV_BPF_X: + if (unlikely(X == 0)) + return 0; + do_div(A, X); + CONT; + BPF_ALU_BPF_DIV_BPF_X: + if (unlikely(X == 0)) + return 0; + tmp = (u32) A; + do_div(tmp, (u32) X); + A = (u32) tmp; + CONT; + BPF_ALU64_BPF_DIV_BPF_K: + do_div(A, K); + CONT; + BPF_ALU_BPF_DIV_BPF_K: + tmp = (u32) A; + do_div(tmp, (u32) K); + A = (u32) tmp; + CONT; + BPF_ALU_BPF_END_BPF_TO_BE: + switch (K) { + case 16: + A = (__force u16) cpu_to_be16(A); + break; + case 32: + A = (__force u32) cpu_to_be32(A); + break; + case 64: + A = (__force u64) cpu_to_be64(A); + break; + } + CONT; + BPF_ALU_BPF_END_BPF_TO_LE: + switch (K) { + case 16: + A = (__force u16) cpu_to_le16(A); + break; + case 32: + A = (__force u32) cpu_to_le32(A); + break; + case 64: + A = (__force u64) cpu_to_le64(A); + break; + } + CONT; + + /* CALL */ + BPF_JMP_BPF_CALL_0: + /* Function call scratches R1-R5 registers, preserves R6-R9, + * and stores return value into R0. + */ + R0 = (__bpf_call_base + insn->imm)(regs[1], regs[2], regs[3], + regs[4], regs[5]); + CONT; + + /* JMP */ + BPF_JMP_BPF_JA_0: + insn += insn->off; + CONT; + BPF_JMP_BPF_JEQ_BPF_X: + if (A == X) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JEQ_BPF_K: + if (A == K) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JNE_BPF_X: + if (A != X) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JNE_BPF_K: + if (A != K) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JGT_BPF_X: + if (A > X) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JGT_BPF_K: + if (A > K) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JGE_BPF_X: + if (A >= X) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JGE_BPF_K: + if (A >= K) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JSGT_BPF_X: + if (((s64)A) > ((s64)X)) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JSGT_BPF_K: + if (((s64)A) > ((s64)K)) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JSGE_BPF_X: + if (((s64)A) >= ((s64)X)) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JSGE_BPF_K: + if (((s64)A) >= ((s64)K)) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JSET_BPF_X: + if (A & X) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JSET_BPF_K: + if (A & K) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_EXIT_0: + return R0; + + /* STX and ST and LDX*/ +#define LDST(SIZEOP, SIZE) \ + BPF_STX_BPF_MEM_##SIZEOP: \ + *(SIZE *)(unsigned long) (A + insn->off) = X; \ + CONT; \ + BPF_ST_BPF_MEM_##SIZEOP: \ + *(SIZE *)(unsigned long) (A + insn->off) = K; \ + CONT; \ + BPF_LDX_BPF_MEM_##SIZEOP: \ + A = *(SIZE *)(unsigned long) (X + insn->off); \ + CONT; + + LDST(BPF_B, u8) + LDST(BPF_H, u16) + LDST(BPF_W, u32) + LDST(BPF_DW, u64) +#undef LDST + BPF_STX_BPF_XADD_BPF_W: /* lock xadd *(u32 *)(A + insn->off) += X */ + atomic_add((u32) X, (atomic_t *)(unsigned long) + (A + insn->off)); + CONT; + BPF_STX_BPF_XADD_BPF_DW: /* lock xadd *(u64 *)(A + insn->off) += X */ + atomic64_add((u64) X, (atomic64_t *)(unsigned long) + (A + insn->off)); + CONT; + BPF_LD_BPF_ABS_BPF_W: /* R0 = ntohl(*(u32 *) (skb->data + K)) */ + off = K; +load_word: + /* BPF_LD + BPD_ABS and BPF_LD + BPF_IND insns are only + * appearing in the programs where ctx == skb. All programs + * keep 'ctx' in regs[CTX_REG] == R6, sk_convert_filter() + * saves it in R6, internal BPF verifier will check that + * R6 == ctx. + * + * BPF_ABS and BPF_IND are wrappers of function calls, so + * they scratch R1-R5 registers, preserve R6-R9, and store + * return value into R0. + * + * Implicit input: + * ctx + * + * Explicit input: + * X == any register + * K == 32-bit immediate + * + * Output: + * R0 - 8/16/32-bit skb data converted to cpu endianness + */ + ptr = load_pointer((struct sk_buff *) ctx, off, 4, &tmp); + if (likely(ptr != NULL)) { + R0 = get_unaligned_be32(ptr); + CONT; + } + return 0; + BPF_LD_BPF_ABS_BPF_H: /* R0 = ntohs(*(u16 *) (skb->data + K)) */ + off = K; +load_half: + ptr = load_pointer((struct sk_buff *) ctx, off, 2, &tmp); + if (likely(ptr != NULL)) { + R0 = get_unaligned_be16(ptr); + CONT; + } + return 0; + BPF_LD_BPF_ABS_BPF_B: /* R0 = *(u8 *) (ctx + K) */ + off = K; +load_byte: + ptr = load_pointer((struct sk_buff *) ctx, off, 1, &tmp); + if (likely(ptr != NULL)) { + R0 = *(u8 *)ptr; + CONT; + } + return 0; + BPF_LD_BPF_IND_BPF_W: /* R0 = ntohl(*(u32 *) (skb->data + X + K)) */ + off = K + X; + goto load_word; + BPF_LD_BPF_IND_BPF_H: /* R0 = ntohs(*(u16 *) (skb->data + X + K)) */ + off = K + X; + goto load_half; + BPF_LD_BPF_IND_BPF_B: /* R0 = *(u8 *) (skb->data + X + K) */ + off = K + X; + goto load_byte; + + default_label: + /* If we ever reach this, we have a bug somewhere. */ + WARN_RATELIMIT(1, ""unknown opcode %02x\n"", insn->code); + return 0; +#undef CONT_JMP +#undef CONT + +#undef R0 +#undef X +#undef A +#undef K +} +",0,"unsigned int __sk_run_filter(void *ctx, const struct sock_filter_int *insn) +{ + u64 stack[MAX_BPF_STACK / sizeof(u64)]; + u64 regs[MAX_BPF_REG], tmp; + void *ptr; + int off; + +#define K insn->imm +#define A regs[insn->a_reg] +#define X regs[insn->x_reg] +#define R0 regs[0] + +#define CONT ({insn++; goto select_insn; }) +#define CONT_JMP ({insn++; goto select_insn; }) + + static const void *jumptable[256] = { + [0 ... 255] = &&default_label, + /* Now overwrite non-defaults ... */ +#define DL(A, B, C) [A|B|C] = &&A##_##B##_##C + DL(BPF_ALU, BPF_ADD, BPF_X), + DL(BPF_ALU, BPF_ADD, BPF_K), + DL(BPF_ALU, BPF_SUB, BPF_X), + DL(BPF_ALU, BPF_SUB, BPF_K), + DL(BPF_ALU, BPF_AND, BPF_X), + DL(BPF_ALU, BPF_AND, BPF_K), + DL(BPF_ALU, BPF_OR, BPF_X), + DL(BPF_ALU, BPF_OR, BPF_K), + DL(BPF_ALU, BPF_LSH, BPF_X), + DL(BPF_ALU, BPF_LSH, BPF_K), + DL(BPF_ALU, BPF_RSH, BPF_X), + DL(BPF_ALU, BPF_RSH, BPF_K), + DL(BPF_ALU, BPF_XOR, BPF_X), + DL(BPF_ALU, BPF_XOR, BPF_K), + DL(BPF_ALU, BPF_MUL, BPF_X), + DL(BPF_ALU, BPF_MUL, BPF_K), + DL(BPF_ALU, BPF_MOV, BPF_X), + DL(BPF_ALU, BPF_MOV, BPF_K), + DL(BPF_ALU, BPF_DIV, BPF_X), + DL(BPF_ALU, BPF_DIV, BPF_K), + DL(BPF_ALU, BPF_MOD, BPF_X), + DL(BPF_ALU, BPF_MOD, BPF_K), + DL(BPF_ALU, BPF_NEG, 0), + DL(BPF_ALU, BPF_END, BPF_TO_BE), + DL(BPF_ALU, BPF_END, BPF_TO_LE), + DL(BPF_ALU64, BPF_ADD, BPF_X), + DL(BPF_ALU64, BPF_ADD, BPF_K), + DL(BPF_ALU64, BPF_SUB, BPF_X), + DL(BPF_ALU64, BPF_SUB, BPF_K), + DL(BPF_ALU64, BPF_AND, BPF_X), + DL(BPF_ALU64, BPF_AND, BPF_K), + DL(BPF_ALU64, BPF_OR, BPF_X), + DL(BPF_ALU64, BPF_OR, BPF_K), + DL(BPF_ALU64, BPF_LSH, BPF_X), + DL(BPF_ALU64, BPF_LSH, BPF_K), + DL(BPF_ALU64, BPF_RSH, BPF_X), + DL(BPF_ALU64, BPF_RSH, BPF_K), + DL(BPF_ALU64, BPF_XOR, BPF_X), + DL(BPF_ALU64, BPF_XOR, BPF_K), + DL(BPF_ALU64, BPF_MUL, BPF_X), + DL(BPF_ALU64, BPF_MUL, BPF_K), + DL(BPF_ALU64, BPF_MOV, BPF_X), + DL(BPF_ALU64, BPF_MOV, BPF_K), + DL(BPF_ALU64, BPF_ARSH, BPF_X), + DL(BPF_ALU64, BPF_ARSH, BPF_K), + DL(BPF_ALU64, BPF_DIV, BPF_X), + DL(BPF_ALU64, BPF_DIV, BPF_K), + DL(BPF_ALU64, BPF_MOD, BPF_X), + DL(BPF_ALU64, BPF_MOD, BPF_K), + DL(BPF_ALU64, BPF_NEG, 0), + DL(BPF_JMP, BPF_CALL, 0), + DL(BPF_JMP, BPF_JA, 0), + DL(BPF_JMP, BPF_JEQ, BPF_X), + DL(BPF_JMP, BPF_JEQ, BPF_K), + DL(BPF_JMP, BPF_JNE, BPF_X), + DL(BPF_JMP, BPF_JNE, BPF_K), + DL(BPF_JMP, BPF_JGT, BPF_X), + DL(BPF_JMP, BPF_JGT, BPF_K), + DL(BPF_JMP, BPF_JGE, BPF_X), + DL(BPF_JMP, BPF_JGE, BPF_K), + DL(BPF_JMP, BPF_JSGT, BPF_X), + DL(BPF_JMP, BPF_JSGT, BPF_K), + DL(BPF_JMP, BPF_JSGE, BPF_X), + DL(BPF_JMP, BPF_JSGE, BPF_K), + DL(BPF_JMP, BPF_JSET, BPF_X), + DL(BPF_JMP, BPF_JSET, BPF_K), + DL(BPF_JMP, BPF_EXIT, 0), + DL(BPF_STX, BPF_MEM, BPF_B), + DL(BPF_STX, BPF_MEM, BPF_H), + DL(BPF_STX, BPF_MEM, BPF_W), + DL(BPF_STX, BPF_MEM, BPF_DW), + DL(BPF_STX, BPF_XADD, BPF_W), + DL(BPF_STX, BPF_XADD, BPF_DW), + DL(BPF_ST, BPF_MEM, BPF_B), + DL(BPF_ST, BPF_MEM, BPF_H), + DL(BPF_ST, BPF_MEM, BPF_W), + DL(BPF_ST, BPF_MEM, BPF_DW), + DL(BPF_LDX, BPF_MEM, BPF_B), + DL(BPF_LDX, BPF_MEM, BPF_H), + DL(BPF_LDX, BPF_MEM, BPF_W), + DL(BPF_LDX, BPF_MEM, BPF_DW), + DL(BPF_LD, BPF_ABS, BPF_W), + DL(BPF_LD, BPF_ABS, BPF_H), + DL(BPF_LD, BPF_ABS, BPF_B), + DL(BPF_LD, BPF_IND, BPF_W), + DL(BPF_LD, BPF_IND, BPF_H), + DL(BPF_LD, BPF_IND, BPF_B), +#undef DL + }; + + regs[FP_REG] = (u64) (unsigned long) &stack[ARRAY_SIZE(stack)]; + regs[ARG1_REG] = (u64) (unsigned long) ctx; + +select_insn: + goto *jumptable[insn->code]; + + /* ALU */ +#define ALU(OPCODE, OP) \ + BPF_ALU64_##OPCODE##_BPF_X: \ + A = A OP X; \ + CONT; \ + BPF_ALU_##OPCODE##_BPF_X: \ + A = (u32) A OP (u32) X; \ + CONT; \ + BPF_ALU64_##OPCODE##_BPF_K: \ + A = A OP K; \ + CONT; \ + BPF_ALU_##OPCODE##_BPF_K: \ + A = (u32) A OP (u32) K; \ + CONT; + + ALU(BPF_ADD, +) + ALU(BPF_SUB, -) + ALU(BPF_AND, &) + ALU(BPF_OR, |) + ALU(BPF_LSH, <<) + ALU(BPF_RSH, >>) + ALU(BPF_XOR, ^) + ALU(BPF_MUL, *) +#undef ALU + BPF_ALU_BPF_NEG_0: + A = (u32) -A; + CONT; + BPF_ALU64_BPF_NEG_0: + A = -A; + CONT; + BPF_ALU_BPF_MOV_BPF_X: + A = (u32) X; + CONT; + BPF_ALU_BPF_MOV_BPF_K: + A = (u32) K; + CONT; + BPF_ALU64_BPF_MOV_BPF_X: + A = X; + CONT; + BPF_ALU64_BPF_MOV_BPF_K: + A = K; + CONT; + BPF_ALU64_BPF_ARSH_BPF_X: + (*(s64 *) &A) >>= X; + CONT; + BPF_ALU64_BPF_ARSH_BPF_K: + (*(s64 *) &A) >>= K; + CONT; + BPF_ALU64_BPF_MOD_BPF_X: + if (unlikely(X == 0)) + return 0; + tmp = A; + A = do_div(tmp, X); + CONT; + BPF_ALU_BPF_MOD_BPF_X: + if (unlikely(X == 0)) + return 0; + tmp = (u32) A; + A = do_div(tmp, (u32) X); + CONT; + BPF_ALU64_BPF_MOD_BPF_K: + tmp = A; + A = do_div(tmp, K); + CONT; + BPF_ALU_BPF_MOD_BPF_K: + tmp = (u32) A; + A = do_div(tmp, (u32) K); + CONT; + BPF_ALU64_BPF_DIV_BPF_X: + if (unlikely(X == 0)) + return 0; + do_div(A, X); + CONT; + BPF_ALU_BPF_DIV_BPF_X: + if (unlikely(X == 0)) + return 0; + tmp = (u32) A; + do_div(tmp, (u32) X); + A = (u32) tmp; + CONT; + BPF_ALU64_BPF_DIV_BPF_K: + do_div(A, K); + CONT; + BPF_ALU_BPF_DIV_BPF_K: + tmp = (u32) A; + do_div(tmp, (u32) K); + A = (u32) tmp; + CONT; + BPF_ALU_BPF_END_BPF_TO_BE: + switch (K) { + case 16: + A = (__force u16) cpu_to_be16(A); + break; + case 32: + A = (__force u32) cpu_to_be32(A); + break; + case 64: + A = (__force u64) cpu_to_be64(A); + break; + } + CONT; + BPF_ALU_BPF_END_BPF_TO_LE: + switch (K) { + case 16: + A = (__force u16) cpu_to_le16(A); + break; + case 32: + A = (__force u32) cpu_to_le32(A); + break; + case 64: + A = (__force u64) cpu_to_le64(A); + break; + } + CONT; + + /* CALL */ + BPF_JMP_BPF_CALL_0: + /* Function call scratches R1-R5 registers, preserves R6-R9, + * and stores return value into R0. + */ + R0 = (__bpf_call_base + insn->imm)(regs[1], regs[2], regs[3], + regs[4], regs[5]); + CONT; + + /* JMP */ + BPF_JMP_BPF_JA_0: + insn += insn->off; + CONT; + BPF_JMP_BPF_JEQ_BPF_X: + if (A == X) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JEQ_BPF_K: + if (A == K) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JNE_BPF_X: + if (A != X) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JNE_BPF_K: + if (A != K) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JGT_BPF_X: + if (A > X) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JGT_BPF_K: + if (A > K) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JGE_BPF_X: + if (A >= X) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JGE_BPF_K: + if (A >= K) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JSGT_BPF_X: + if (((s64)A) > ((s64)X)) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JSGT_BPF_K: + if (((s64)A) > ((s64)K)) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JSGE_BPF_X: + if (((s64)A) >= ((s64)X)) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JSGE_BPF_K: + if (((s64)A) >= ((s64)K)) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JSET_BPF_X: + if (A & X) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_JSET_BPF_K: + if (A & K) { + insn += insn->off; + CONT_JMP; + } + CONT; + BPF_JMP_BPF_EXIT_0: + return R0; + + /* STX and ST and LDX*/ +#define LDST(SIZEOP, SIZE) \ + BPF_STX_BPF_MEM_##SIZEOP: \ + *(SIZE *)(unsigned long) (A + insn->off) = X; \ + CONT; \ + BPF_ST_BPF_MEM_##SIZEOP: \ + *(SIZE *)(unsigned long) (A + insn->off) = K; \ + CONT; \ + BPF_LDX_BPF_MEM_##SIZEOP: \ + A = *(SIZE *)(unsigned long) (X + insn->off); \ + CONT; + + LDST(BPF_B, u8) + LDST(BPF_H, u16) + LDST(BPF_W, u32) + LDST(BPF_DW, u64) +#undef LDST + BPF_STX_BPF_XADD_BPF_W: /* lock xadd *(u32 *)(A + insn->off) += X */ + atomic_add((u32) X, (atomic_t *)(unsigned long) + (A + insn->off)); + CONT; + BPF_STX_BPF_XADD_BPF_DW: /* lock xadd *(u64 *)(A + insn->off) += X */ + atomic64_add((u64) X, (atomic64_t *)(unsigned long) + (A + insn->off)); + CONT; + BPF_LD_BPF_ABS_BPF_W: /* R0 = ntohl(*(u32 *) (skb->data + K)) */ + off = K; +load_word: + /* BPF_LD + BPD_ABS and BPF_LD + BPF_IND insns are only + * appearing in the programs where ctx == skb. All programs + * keep 'ctx' in regs[CTX_REG] == R6, sk_convert_filter() + * saves it in R6, internal BPF verifier will check that + * R6 == ctx. + * + * BPF_ABS and BPF_IND are wrappers of function calls, so + * they scratch R1-R5 registers, preserve R6-R9, and store + * return value into R0. + * + * Implicit input: + * ctx + * + * Explicit input: + * X == any register + * K == 32-bit immediate + * + * Output: + * R0 - 8/16/32-bit skb data converted to cpu endianness + */ + ptr = load_pointer((struct sk_buff *) ctx, off, 4, &tmp); + if (likely(ptr != NULL)) { + R0 = get_unaligned_be32(ptr); + CONT; + } + return 0; + BPF_LD_BPF_ABS_BPF_H: /* R0 = ntohs(*(u16 *) (skb->data + K)) */ + off = K; +load_half: + ptr = load_pointer((struct sk_buff *) ctx, off, 2, &tmp); + if (likely(ptr != NULL)) { + R0 = get_unaligned_be16(ptr); + CONT; + } + return 0; + BPF_LD_BPF_ABS_BPF_B: /* R0 = *(u8 *) (ctx + K) */ + off = K; +load_byte: + ptr = load_pointer((struct sk_buff *) ctx, off, 1, &tmp); + if (likely(ptr != NULL)) { + R0 = *(u8 *)ptr; + CONT; + } + return 0; + BPF_LD_BPF_IND_BPF_W: /* R0 = ntohl(*(u32 *) (skb->data + X + K)) */ + off = K + X; + goto load_word; + BPF_LD_BPF_IND_BPF_H: /* R0 = ntohs(*(u16 *) (skb->data + X + K)) */ + off = K + X; + goto load_half; + BPF_LD_BPF_IND_BPF_B: /* R0 = *(u8 *) (skb->data + X + K) */ + off = K + X; + goto load_byte; + + default_label: + /* If we ever reach this, we have a bug somewhere. */ + WARN_RATELIMIT(1, ""unknown opcode %02x\n"", insn->code); + return 0; +#undef CONT_JMP +#undef CONT + +#undef R0 +#undef X +#undef A +#undef K +} +","@@ -600,6 +600,9 @@ static u64 __skb_get_nlattr(u64 ctx, u64 A, u64 X, u64 r4, u64 r5) + if (skb_is_nonlinear(skb)) + return 0; + ++ if (skb->len < sizeof(struct nlattr)) ++ return 0; ++ + if (A > skb->len - sizeof(struct nlattr)) + return 0; + +@@ -618,11 +621,14 @@ static u64 __skb_get_nlattr_nest(u64 ctx, u64 A, u64 X, u64 r4, u64 r5) + if (skb_is_nonlinear(skb)) + return 0; + ++ if (skb->len < sizeof(struct nlattr)) ++ return 0; ++ + if (A > skb->len - sizeof(struct nlattr)) + return 0; + + nla = (struct nlattr *) &skb->data[A]; +- if (nla->nla_len > A - skb->len) ++ if (nla->nla_len > skb->len - A) + return 0; + + nla = nla_find_nested(nla, X);",4390,4721,6144 +18169,"static Image *ReadPCXImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ +#define ThrowPCXException(severity,tag) \ + { \ + scanline=(unsigned char *) RelinquishMagickMemory(scanline); \ + pixel_info=RelinquishVirtualMemory(pixel_info); \ + ThrowReaderException(severity,tag); \ + } + + Image + *image; + + int + bits, + id, + mask; + + MagickBooleanType + status; + + MagickOffsetType + offset, + *page_table; + + MemoryInfo + *pixel_info; + + PCXInfo + pcx_info; + + register IndexPacket + *indexes; + + register ssize_t + x; + + register PixelPacket + *q; + + register ssize_t + i; + + register unsigned char + *p, + *r; + + size_t + one, + pcx_packets; + + ssize_t + count, + y; + + unsigned char + packet, + pcx_colormap[768], + *pixels, + *scanline; + + /* + 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); + } + /* + Determine if this a PCX file. + */ + page_table=(MagickOffsetType *) NULL; + if (LocaleCompare(image_info->magick,""DCX"") == 0) + { + size_t + magic; + + /* + Read the DCX page table. + */ + magic=ReadBlobLSBLong(image); + if (magic != 987654321) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + page_table=(MagickOffsetType *) AcquireQuantumMemory(1024UL, + sizeof(*page_table)); + if (page_table == (MagickOffsetType *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + for (id=0; id < 1024; id++) + { + page_table[id]=(MagickOffsetType) ReadBlobLSBLong(image); + if (page_table[id] == 0) + break; + } + } + if (page_table != (MagickOffsetType *) NULL) + { + offset=SeekBlob(image,(MagickOffsetType) page_table[0],SEEK_SET); + if (offset < 0) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + } + count=ReadBlob(image,1,&pcx_info.identifier); + for (id=1; id < 1024; id++) + { + int + bits_per_pixel; + + /* + Verify PCX identifier. + */ + pcx_info.version=(unsigned char) ReadBlobByte(image); + if ((count == 0) || (pcx_info.identifier != 0x0a)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + pcx_info.encoding=(unsigned char) ReadBlobByte(image); + bits_per_pixel=ReadBlobByte(image); + if (bits_per_pixel == -1) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + pcx_info.bits_per_pixel=(unsigned char) bits_per_pixel; + pcx_info.left=ReadBlobLSBShort(image); + pcx_info.top=ReadBlobLSBShort(image); + pcx_info.right=ReadBlobLSBShort(image); + pcx_info.bottom=ReadBlobLSBShort(image); + pcx_info.horizontal_resolution=ReadBlobLSBShort(image); + pcx_info.vertical_resolution=ReadBlobLSBShort(image); + /* + Read PCX raster colormap. + */ + image->columns=(size_t) MagickAbsoluteValue((ssize_t) pcx_info.right- + pcx_info.left)+1UL; + image->rows=(size_t) MagickAbsoluteValue((ssize_t) pcx_info.bottom- + pcx_info.top)+1UL; + if ((image->columns == 0) || (image->rows == 0) || + (pcx_info.bits_per_pixel == 0)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + image->depth=pcx_info.bits_per_pixel <= 8 ? 8U : MAGICKCORE_QUANTUM_DEPTH; + image->units=PixelsPerInchResolution; + image->x_resolution=(double) pcx_info.horizontal_resolution; + image->y_resolution=(double) pcx_info.vertical_resolution; + image->colors=16; + count=ReadBlob(image,3*image->colors,pcx_colormap); + pcx_info.reserved=(unsigned char) ReadBlobByte(image); + pcx_info.planes=(unsigned char) ReadBlobByte(image); + if ((pcx_info.bits_per_pixel*pcx_info.planes) >= 64) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + one=1; + if ((pcx_info.bits_per_pixel != 8) || (pcx_info.planes == 1)) + if ((pcx_info.version == 3) || (pcx_info.version == 5) || + ((pcx_info.bits_per_pixel*pcx_info.planes) == 1)) + image->colors=(size_t) MagickMin(one << (1UL* + (pcx_info.bits_per_pixel*pcx_info.planes)),256UL); + if (AcquireImageColormap(image,image->colors) == MagickFalse) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + if ((pcx_info.bits_per_pixel >= 8) && (pcx_info.planes != 1)) + image->storage_class=DirectClass; + p=pcx_colormap; + 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++); + } + pcx_info.bytes_per_line=ReadBlobLSBShort(image); + pcx_info.palette_info=ReadBlobLSBShort(image); + for (i=0; i < 58; i++) + (void) ReadBlobByte(image); + if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) + if (image->scene >= (image_info->scene+image_info->number_scenes-1)) + break; + /* + Read image data. + */ + pcx_packets=(size_t) image->rows*pcx_info.bytes_per_line*pcx_info.planes; + if ((size_t) (pcx_info.bits_per_pixel*pcx_info.planes*image->columns) > + (pcx_packets*8U)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + scanline=(unsigned char *) AcquireQuantumMemory(MagickMax(image->columns, + pcx_info.bytes_per_line),MagickMax(8,pcx_info.planes)*sizeof(*scanline)); + pixel_info=AcquireVirtualMemory(pcx_packets,2*sizeof(*pixels)); + if ((scanline == (unsigned char *) NULL) || + (pixel_info == (MemoryInfo *) NULL)) + { + if (scanline != (unsigned char *) NULL) + scanline=(unsigned char *) RelinquishMagickMemory(scanline); + if (pixel_info != (MemoryInfo *) NULL) + pixel_info=RelinquishVirtualMemory(pixel_info); + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + } + pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); + /* + Uncompress image data. + */ + p=pixels; + if (pcx_info.encoding == 0) + while (pcx_packets != 0) + { + packet=(unsigned char) ReadBlobByte(image); + if (EOFBlob(image) != MagickFalse) + ThrowPCXException(CorruptImageError,""UnexpectedEndOfFile""); + *p++=packet; + pcx_packets--; + } + else + while (pcx_packets != 0) + { + packet=(unsigned char) ReadBlobByte(image); + if (EOFBlob(image) != MagickFalse) + ThrowPCXException(CorruptImageError,""UnexpectedEndOfFile""); + if ((packet & 0xc0) != 0xc0) + { + *p++=packet; + pcx_packets--; + continue; + } + count=(ssize_t) (packet & 0x3f); + packet=(unsigned char) ReadBlobByte(image); + if (EOFBlob(image) != MagickFalse) + ThrowPCXException(CorruptImageError,""UnexpectedEndOfFile""); + for ( ; count != 0; count--) + { + *p++=packet; + pcx_packets--; + if (pcx_packets == 0) + break; + } + } + if (image->storage_class == DirectClass) + image->matte=pcx_info.planes > 3 ? MagickTrue : MagickFalse; + else + if ((pcx_info.version == 5) || + ((pcx_info.bits_per_pixel*pcx_info.planes) == 1)) + { + /* + Initialize image colormap. + */ + if (image->colors > 256) + ThrowPCXException(CorruptImageError,""ColormapExceeds256Colors""); + if ((pcx_info.bits_per_pixel*pcx_info.planes) == 1) + { + /* + Monochrome colormap. + */ + image->colormap[0].red=(Quantum) 0; + image->colormap[0].green=(Quantum) 0; + image->colormap[0].blue=(Quantum) 0; + image->colormap[1].red=QuantumRange; + image->colormap[1].green=QuantumRange; + image->colormap[1].blue=QuantumRange; + } + else + if (image->colors > 16) + { + /* + 256 color images have their color map at the end of the file. + */ + pcx_info.colormap_signature=(unsigned char) ReadBlobByte(image); + count=ReadBlob(image,3*image->colors,pcx_colormap); + p=pcx_colormap; + 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++); + } + } + } + /* + Convert PCX raster image to pixel packets. + */ + for (y=0; y < (ssize_t) image->rows; y++) + { + p=pixels+(y*pcx_info.bytes_per_line*pcx_info.planes); + q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); + if (q == (PixelPacket *) NULL) + break; + indexes=GetAuthenticIndexQueue(image); + r=scanline; + if (image->storage_class == DirectClass) + for (i=0; i < pcx_info.planes; i++) + { + r=scanline+i; + for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++) + { + switch (i) + { + case 0: + { + *r=(*p++); + break; + } + case 1: + { + *r=(*p++); + break; + } + case 2: + { + *r=(*p++); + break; + } + case 3: + default: + { + *r=(*p++); + break; + } + } + r+=pcx_info.planes; + } + } + else + if (pcx_info.planes > 1) + { + for (x=0; x < (ssize_t) image->columns; x++) + *r++=0; + for (i=0; i < pcx_info.planes; i++) + { + r=scanline; + for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++) + { + bits=(*p++); + for (mask=0x80; mask != 0; mask>>=1) + { + if (bits & mask) + *r|=1 << i; + r++; + } + } + } + } + else + switch (pcx_info.bits_per_pixel) + { + case 1: + { + register ssize_t + bit; + + for (x=0; x < ((ssize_t) image->columns-7); x+=8) + { + for (bit=7; bit >= 0; bit--) + *r++=(unsigned char) ((*p) & (0x01 << bit) ? 0x01 : 0x00); + p++; + } + if ((image->columns % 8) != 0) + { + for (bit=7; bit >= (ssize_t) (8-(image->columns % 8)); bit--) + *r++=(unsigned char) ((*p) & (0x01 << bit) ? 0x01 : 0x00); + p++; + } + break; + } + case 2: + { + for (x=0; x < ((ssize_t) image->columns-3); x+=4) + { + *r++=(*p >> 6) & 0x3; + *r++=(*p >> 4) & 0x3; + *r++=(*p >> 2) & 0x3; + *r++=(*p) & 0x3; + p++; + } + if ((image->columns % 4) != 0) + { + for (i=3; i >= (ssize_t) (4-(image->columns % 4)); i--) + *r++=(unsigned char) ((*p >> (i*2)) & 0x03); + p++; + } + break; + } + case 4: + { + for (x=0; x < ((ssize_t) image->columns-1); x+=2) + { + *r++=(*p >> 4) & 0xf; + *r++=(*p) & 0xf; + p++; + } + if ((image->columns % 2) != 0) + *r++=(*p++ >> 4) & 0xf; + break; + } + case 8: + { + (void) CopyMagickMemory(r,p,image->columns); + break; + } + default: + break; + } + /* + Transfer image scanline. + */ + r=scanline; + for (x=0; x < (ssize_t) image->columns; x++) + { + if (image->storage_class == PseudoClass) + SetPixelIndex(indexes+x,*r++) + else + { + SetPixelRed(q,ScaleCharToQuantum(*r++)); + SetPixelGreen(q,ScaleCharToQuantum(*r++)); + SetPixelBlue(q,ScaleCharToQuantum(*r++)); + if (image->matte != MagickFalse) + SetPixelAlpha(q,ScaleCharToQuantum(*r++)); + } + 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 (image->storage_class == PseudoClass) + (void) SyncImage(image); + scanline=(unsigned char *) RelinquishMagickMemory(scanline); + 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; + if (page_table == (MagickOffsetType *) NULL) + break; + if (page_table[id] == 0) + break; + offset=SeekBlob(image,(MagickOffsetType) page_table[id],SEEK_SET); + if (offset < 0) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + count=ReadBlob(image,1,&pcx_info.identifier); + if ((count != 0) && (pcx_info.identifier == 0x0a)) + { + /* + 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; + } + } + if (page_table != (MagickOffsetType *) NULL) + page_table=(MagickOffsetType *) RelinquishMagickMemory(page_table); + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +",1,"static Image *ReadPCXImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ +#define ThrowPCXException(severity,tag) \ + { \ + scanline=(unsigned char *) RelinquishMagickMemory(scanline); \ + pixel_info=RelinquishVirtualMemory(pixel_info); \ + ThrowReaderException(severity,tag); \ + } + + Image + *image; + + int + bits, + id, + mask; + + MagickBooleanType + status; + + MagickOffsetType + offset, + *page_table; + + MemoryInfo + *pixel_info; + + PCXInfo + pcx_info; + + register IndexPacket + *indexes; + + register ssize_t + x; + + register PixelPacket + *q; + + register ssize_t + i; + + register unsigned char + *p, + *r; + + size_t + one, + pcx_packets; + + ssize_t + count, + y; + + unsigned char + packet, + pcx_colormap[768], + *pixels, + *scanline; + + /* + 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); + } + /* + Determine if this a PCX file. + */ + page_table=(MagickOffsetType *) NULL; + if (LocaleCompare(image_info->magick,""DCX"") == 0) + { + size_t + magic; + + /* + Read the DCX page table. + */ + magic=ReadBlobLSBLong(image); + if (magic != 987654321) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + page_table=(MagickOffsetType *) AcquireQuantumMemory(1024UL, + sizeof(*page_table)); + if (page_table == (MagickOffsetType *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + for (id=0; id < 1024; id++) + { + page_table[id]=(MagickOffsetType) ReadBlobLSBLong(image); + if (page_table[id] == 0) + break; + } + } + if (page_table != (MagickOffsetType *) NULL) + { + offset=SeekBlob(image,(MagickOffsetType) page_table[0],SEEK_SET); + if (offset < 0) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + } + count=ReadBlob(image,1,&pcx_info.identifier); + for (id=1; id < 1024; id++) + { + int + bits_per_pixel; + + /* + Verify PCX identifier. + */ + pcx_info.version=(unsigned char) ReadBlobByte(image); + if ((count == 0) || (pcx_info.identifier != 0x0a)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + pcx_info.encoding=(unsigned char) ReadBlobByte(image); + bits_per_pixel=ReadBlobByte(image); + if (bits_per_pixel == -1) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + pcx_info.bits_per_pixel=(unsigned char) bits_per_pixel; + pcx_info.left=ReadBlobLSBShort(image); + pcx_info.top=ReadBlobLSBShort(image); + pcx_info.right=ReadBlobLSBShort(image); + pcx_info.bottom=ReadBlobLSBShort(image); + pcx_info.horizontal_resolution=ReadBlobLSBShort(image); + pcx_info.vertical_resolution=ReadBlobLSBShort(image); + /* + Read PCX raster colormap. + */ + image->columns=(size_t) MagickAbsoluteValue((ssize_t) pcx_info.right- + pcx_info.left)+1UL; + image->rows=(size_t) MagickAbsoluteValue((ssize_t) pcx_info.bottom- + pcx_info.top)+1UL; + if ((image->columns == 0) || (image->rows == 0) || + (pcx_info.bits_per_pixel == 0)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + image->depth=pcx_info.bits_per_pixel <= 8 ? 8U : MAGICKCORE_QUANTUM_DEPTH; + image->units=PixelsPerInchResolution; + image->x_resolution=(double) pcx_info.horizontal_resolution; + image->y_resolution=(double) pcx_info.vertical_resolution; + image->colors=16; + count=ReadBlob(image,3*image->colors,pcx_colormap); + pcx_info.reserved=(unsigned char) ReadBlobByte(image); + pcx_info.planes=(unsigned char) ReadBlobByte(image); + if ((pcx_info.bits_per_pixel*pcx_info.planes) >= 64) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + one=1; + if ((pcx_info.bits_per_pixel != 8) || (pcx_info.planes == 1)) + if ((pcx_info.version == 3) || (pcx_info.version == 5) || + ((pcx_info.bits_per_pixel*pcx_info.planes) == 1)) + image->colors=(size_t) MagickMin(one << (1UL* + (pcx_info.bits_per_pixel*pcx_info.planes)),256UL); + if (AcquireImageColormap(image,image->colors) == MagickFalse) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + if ((pcx_info.bits_per_pixel >= 8) && (pcx_info.planes != 1)) + image->storage_class=DirectClass; + p=pcx_colormap; + 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++); + } + pcx_info.bytes_per_line=ReadBlobLSBShort(image); + pcx_info.palette_info=ReadBlobLSBShort(image); + for (i=0; i < 58; i++) + (void) ReadBlobByte(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)); + } + /* + Read image data. + */ + pcx_packets=(size_t) image->rows*pcx_info.bytes_per_line*pcx_info.planes; + if ((size_t) (pcx_info.bits_per_pixel*pcx_info.planes*image->columns) > + (pcx_packets*8U)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + scanline=(unsigned char *) AcquireQuantumMemory(MagickMax(image->columns, + pcx_info.bytes_per_line),MagickMax(8,pcx_info.planes)*sizeof(*scanline)); + pixel_info=AcquireVirtualMemory(pcx_packets,2*sizeof(*pixels)); + if ((scanline == (unsigned char *) NULL) || + (pixel_info == (MemoryInfo *) NULL)) + { + if (scanline != (unsigned char *) NULL) + scanline=(unsigned char *) RelinquishMagickMemory(scanline); + if (pixel_info != (MemoryInfo *) NULL) + pixel_info=RelinquishVirtualMemory(pixel_info); + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + } + pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); + /* + Uncompress image data. + */ + p=pixels; + if (pcx_info.encoding == 0) + while (pcx_packets != 0) + { + packet=(unsigned char) ReadBlobByte(image); + if (EOFBlob(image) != MagickFalse) + ThrowPCXException(CorruptImageError,""UnexpectedEndOfFile""); + *p++=packet; + pcx_packets--; + } + else + while (pcx_packets != 0) + { + packet=(unsigned char) ReadBlobByte(image); + if (EOFBlob(image) != MagickFalse) + ThrowPCXException(CorruptImageError,""UnexpectedEndOfFile""); + if ((packet & 0xc0) != 0xc0) + { + *p++=packet; + pcx_packets--; + continue; + } + count=(ssize_t) (packet & 0x3f); + packet=(unsigned char) ReadBlobByte(image); + if (EOFBlob(image) != MagickFalse) + ThrowPCXException(CorruptImageError,""UnexpectedEndOfFile""); + for ( ; count != 0; count--) + { + *p++=packet; + pcx_packets--; + if (pcx_packets == 0) + break; + } + } + if (image->storage_class == DirectClass) + image->matte=pcx_info.planes > 3 ? MagickTrue : MagickFalse; + else + if ((pcx_info.version == 5) || + ((pcx_info.bits_per_pixel*pcx_info.planes) == 1)) + { + /* + Initialize image colormap. + */ + if (image->colors > 256) + ThrowPCXException(CorruptImageError,""ColormapExceeds256Colors""); + if ((pcx_info.bits_per_pixel*pcx_info.planes) == 1) + { + /* + Monochrome colormap. + */ + image->colormap[0].red=(Quantum) 0; + image->colormap[0].green=(Quantum) 0; + image->colormap[0].blue=(Quantum) 0; + image->colormap[1].red=QuantumRange; + image->colormap[1].green=QuantumRange; + image->colormap[1].blue=QuantumRange; + } + else + if (image->colors > 16) + { + /* + 256 color images have their color map at the end of the file. + */ + pcx_info.colormap_signature=(unsigned char) ReadBlobByte(image); + count=ReadBlob(image,3*image->colors,pcx_colormap); + p=pcx_colormap; + 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++); + } + } + } + /* + Convert PCX raster image to pixel packets. + */ + for (y=0; y < (ssize_t) image->rows; y++) + { + p=pixels+(y*pcx_info.bytes_per_line*pcx_info.planes); + q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); + if (q == (PixelPacket *) NULL) + break; + indexes=GetAuthenticIndexQueue(image); + r=scanline; + if (image->storage_class == DirectClass) + for (i=0; i < pcx_info.planes; i++) + { + r=scanline+i; + for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++) + { + switch (i) + { + case 0: + { + *r=(*p++); + break; + } + case 1: + { + *r=(*p++); + break; + } + case 2: + { + *r=(*p++); + break; + } + case 3: + default: + { + *r=(*p++); + break; + } + } + r+=pcx_info.planes; + } + } + else + if (pcx_info.planes > 1) + { + for (x=0; x < (ssize_t) image->columns; x++) + *r++=0; + for (i=0; i < pcx_info.planes; i++) + { + r=scanline; + for (x=0; x < (ssize_t) pcx_info.bytes_per_line; x++) + { + bits=(*p++); + for (mask=0x80; mask != 0; mask>>=1) + { + if (bits & mask) + *r|=1 << i; + r++; + } + } + } + } + else + switch (pcx_info.bits_per_pixel) + { + case 1: + { + register ssize_t + bit; + + for (x=0; x < ((ssize_t) image->columns-7); x+=8) + { + for (bit=7; bit >= 0; bit--) + *r++=(unsigned char) ((*p) & (0x01 << bit) ? 0x01 : 0x00); + p++; + } + if ((image->columns % 8) != 0) + { + for (bit=7; bit >= (ssize_t) (8-(image->columns % 8)); bit--) + *r++=(unsigned char) ((*p) & (0x01 << bit) ? 0x01 : 0x00); + p++; + } + break; + } + case 2: + { + for (x=0; x < ((ssize_t) image->columns-3); x+=4) + { + *r++=(*p >> 6) & 0x3; + *r++=(*p >> 4) & 0x3; + *r++=(*p >> 2) & 0x3; + *r++=(*p) & 0x3; + p++; + } + if ((image->columns % 4) != 0) + { + for (i=3; i >= (ssize_t) (4-(image->columns % 4)); i--) + *r++=(unsigned char) ((*p >> (i*2)) & 0x03); + p++; + } + break; + } + case 4: + { + for (x=0; x < ((ssize_t) image->columns-1); x+=2) + { + *r++=(*p >> 4) & 0xf; + *r++=(*p) & 0xf; + p++; + } + if ((image->columns % 2) != 0) + *r++=(*p++ >> 4) & 0xf; + break; + } + case 8: + { + (void) CopyMagickMemory(r,p,image->columns); + break; + } + default: + break; + } + /* + Transfer image scanline. + */ + r=scanline; + for (x=0; x < (ssize_t) image->columns; x++) + { + if (image->storage_class == PseudoClass) + SetPixelIndex(indexes+x,*r++) + else + { + SetPixelRed(q,ScaleCharToQuantum(*r++)); + SetPixelGreen(q,ScaleCharToQuantum(*r++)); + SetPixelBlue(q,ScaleCharToQuantum(*r++)); + if (image->matte != MagickFalse) + SetPixelAlpha(q,ScaleCharToQuantum(*r++)); + } + 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 (image->storage_class == PseudoClass) + (void) SyncImage(image); + scanline=(unsigned char *) RelinquishMagickMemory(scanline); + 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; + if (page_table == (MagickOffsetType *) NULL) + break; + if (page_table[id] == 0) + break; + offset=SeekBlob(image,(MagickOffsetType) page_table[id],SEEK_SET); + if (offset < 0) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + count=ReadBlob(image,1,&pcx_info.identifier); + if ((count != 0) && (pcx_info.identifier == 0x0a)) + { + /* + 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; + } + } + if (page_table != (MagickOffsetType *) NULL) + page_table=(MagickOffsetType *) RelinquishMagickMemory(page_table); + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +","@@ -395,6 +395,12 @@ static Image *ReadPCXImage(const ImageInfo *image_info,ExceptionInfo *exception) + 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)); ++ } + /* + Read image data. + */",3952,4283,6144 +18130,"int yr_execute_code( + YR_RULES* rules, + YR_SCAN_CONTEXT* context, + int timeout, + time_t start_time) +{ + int64_t mem[MEM_SIZE]; + int32_t sp = 0; + uint8_t* ip = rules->code_start; + + YR_VALUE args[MAX_FUNCTION_ARGS]; + YR_VALUE *stack; + YR_VALUE r1; + YR_VALUE r2; + YR_VALUE r3; + + #ifdef PROFILING_ENABLED + YR_RULE* current_rule = NULL; + #endif + + YR_RULE* rule; + YR_MATCH* match; + YR_OBJECT_FUNCTION* function; + + char* identifier; + char* args_fmt; + + int i; + int found; + int count; + int result = ERROR_SUCCESS; + int stop = FALSE; + int cycle = 0; + int tidx = context->tidx; + int stack_size; + + #ifdef PROFILING_ENABLED + clock_t start = clock(); + #endif + + yr_get_configuration(YR_CONFIG_STACK_SIZE, (void*) &stack_size); + + stack = (YR_VALUE*) yr_malloc(stack_size * sizeof(YR_VALUE)); + + if (stack == NULL) + return ERROR_INSUFFICIENT_MEMORY; + + while(!stop) + { + switch(*ip) + { + case OP_NOP: + break; + + case OP_HALT: + assert(sp == 0); // When HALT is reached the stack should be empty. + stop = TRUE; + break; + + case OP_PUSH: + r1.i = *(uint64_t*)(ip + 1); + ip += sizeof(uint64_t); + push(r1); + break; + + case OP_POP: + pop(r1); + break; + + case OP_CLEAR_M: + r1.i = *(uint64_t*)(ip + 1); + ip += sizeof(uint64_t); + mem[r1.i] = 0; + break; + + case OP_ADD_M: + r1.i = *(uint64_t*)(ip + 1); + ip += sizeof(uint64_t); + pop(r2); + if (!is_undef(r2)) + mem[r1.i] += r2.i; + break; + + case OP_INCR_M: + r1.i = *(uint64_t*)(ip + 1); + ip += sizeof(uint64_t); + mem[r1.i]++; + break; + + case OP_PUSH_M: + r1.i = *(uint64_t*)(ip + 1); + ip += sizeof(uint64_t); + r1.i = mem[r1.i]; + push(r1); + break; + + case OP_POP_M: + r1.i = *(uint64_t*)(ip + 1); + ip += sizeof(uint64_t); + pop(r2); + mem[r1.i] = r2.i; + break; + + case OP_SWAPUNDEF: + r1.i = *(uint64_t*)(ip + 1); + ip += sizeof(uint64_t); + pop(r2); + + if (is_undef(r2)) + { + r1.i = mem[r1.i]; + push(r1); + } + else + { + push(r2); + } + break; + + case OP_JNUNDEF: + pop(r1); + push(r1); + + ip = jmp_if(!is_undef(r1), ip); + break; + + case OP_JLE: + pop(r2); + pop(r1); + push(r1); + push(r2); + + ip = jmp_if(r1.i <= r2.i, ip); + break; + + case OP_JTRUE: + pop(r1); + push(r1); + + ip = jmp_if(!is_undef(r1) && r1.i, ip); + break; + + case OP_JFALSE: + pop(r1); + push(r1); + + ip = jmp_if(is_undef(r1) || !r1.i, ip); + break; + + case OP_AND: + pop(r2); + pop(r1); + + if (is_undef(r1) || is_undef(r2)) + r1.i = 0; + else + r1.i = r1.i && r2.i; + + push(r1); + break; + + case OP_OR: + pop(r2); + pop(r1); + + if (is_undef(r1)) + { + push(r2); + } + else if (is_undef(r2)) + { + push(r1); + } + else + { + r1.i = r1.i || r2.i; + push(r1); + } + break; + + case OP_NOT: + pop(r1); + + if (is_undef(r1)) + r1.i = UNDEFINED; + else + r1.i= !r1.i; + + push(r1); + break; + + case OP_MOD: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + if (r2.i != 0) + r1.i = r1.i % r2.i; + else + r1.i = UNDEFINED; + push(r1); + break; + + case OP_SHR: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i >> r2.i; + push(r1); + break; + + case OP_SHL: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i << r2.i; + push(r1); + break; + + case OP_BITWISE_NOT: + pop(r1); + ensure_defined(r1); + r1.i = ~r1.i; + push(r1); + break; + + case OP_BITWISE_AND: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i & r2.i; + push(r1); + break; + + case OP_BITWISE_OR: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i | r2.i; + push(r1); + break; + + case OP_BITWISE_XOR: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i ^ r2.i; + push(r1); + break; + + case OP_PUSH_RULE: + rule = *(YR_RULE**)(ip + 1); + ip += sizeof(uint64_t); + r1.i = rule->t_flags[tidx] & RULE_TFLAGS_MATCH ? 1 : 0; + push(r1); + break; + + case OP_INIT_RULE: + #ifdef PROFILING_ENABLED + current_rule = *(YR_RULE**)(ip + 1); + #endif + ip += sizeof(uint64_t); + break; + + case OP_MATCH_RULE: + pop(r1); + rule = *(YR_RULE**)(ip + 1); + ip += sizeof(uint64_t); + + if (!is_undef(r1) && r1.i) + rule->t_flags[tidx] |= RULE_TFLAGS_MATCH; + else if (RULE_IS_GLOBAL(rule)) + rule->ns->t_flags[tidx] |= NAMESPACE_TFLAGS_UNSATISFIED_GLOBAL; + + #ifdef PROFILING_ENABLED + rule->clock_ticks += clock() - start; + start = clock(); + #endif + break; + + case OP_OBJ_LOAD: + identifier = *(char**)(ip + 1); + ip += sizeof(uint64_t); + + r1.o = (YR_OBJECT*) yr_hash_table_lookup( + context->objects_table, + identifier, + NULL); + + assert(r1.o != NULL); + push(r1); + break; + + case OP_OBJ_FIELD: + identifier = *(char**)(ip + 1); + ip += sizeof(uint64_t); + + pop(r1); + ensure_defined(r1); + + r1.o = yr_object_lookup_field(r1.o, identifier); + + assert(r1.o != NULL); + push(r1); + break; + + case OP_OBJ_VALUE: + pop(r1); + ensure_defined(r1); + + switch(r1.o->type) + { + case OBJECT_TYPE_INTEGER: + r1.i = ((YR_OBJECT_INTEGER*) r1.o)->value; + break; + + case OBJECT_TYPE_FLOAT: + if (isnan(((YR_OBJECT_DOUBLE*) r1.o)->value)) + r1.i = UNDEFINED; + else + r1.d = ((YR_OBJECT_DOUBLE*) r1.o)->value; + break; + + case OBJECT_TYPE_STRING: + if (((YR_OBJECT_STRING*) r1.o)->value == NULL) + r1.i = UNDEFINED; + else + r1.p = ((YR_OBJECT_STRING*) r1.o)->value; + break; + + default: + assert(FALSE); + } + + push(r1); + break; + + case OP_INDEX_ARRAY: + pop(r1); // index + pop(r2); // array + + ensure_defined(r1); + ensure_defined(r2); + assert(r2.o->type == OBJECT_TYPE_ARRAY); + + r1.o = yr_object_array_get_item(r2.o, 0, (int) r1.i); + + if (r1.o == NULL) + r1.i = UNDEFINED; + + push(r1); + break; + + case OP_LOOKUP_DICT: + pop(r1); // key + pop(r2); // dictionary + + ensure_defined(r1); + ensure_defined(r2); + assert(r2.o->type == OBJECT_TYPE_DICTIONARY); + + r1.o = yr_object_dict_get_item( + r2.o, 0, r1.ss->c_string); + + if (r1.o == NULL) + r1.i = UNDEFINED; + + push(r1); + break; + + case OP_CALL: + args_fmt = *(char**)(ip + 1); + ip += sizeof(uint64_t); + + i = (int) strlen(args_fmt); + count = 0; + + + while (i > 0) + { + pop(r1); + + if (is_undef(r1)) // count the number of undefined args + count++; + + args[i - 1] = r1; + i--; + } + + pop(r2); + ensure_defined(r2); + + if (count > 0) + { + + r1.i = UNDEFINED; + push(r1); + break; + } + + function = (YR_OBJECT_FUNCTION*) r2.o; + result = ERROR_INTERNAL_FATAL_ERROR; + + for (i = 0; i < MAX_OVERLOADED_FUNCTIONS; i++) + { + if (function->prototypes[i].arguments_fmt == NULL) + break; + + if (strcmp(function->prototypes[i].arguments_fmt, args_fmt) == 0) + { + result = function->prototypes[i].code(args, context, function); + break; + } + } + + assert(i < MAX_OVERLOADED_FUNCTIONS); + + if (result == ERROR_SUCCESS) + { + r1.o = function->return_obj; + push(r1); + } + else + { + stop = TRUE; + } + + break; + + case OP_FOUND: + pop(r1); + r1.i = r1.s->matches[tidx].tail != NULL ? 1 : 0; + push(r1); + break; + + case OP_FOUND_AT: + pop(r2); + pop(r1); + + if (is_undef(r1)) + { + r1.i = 0; + push(r1); + break; + } + + match = r2.s->matches[tidx].head; + r3.i = FALSE; + + while (match != NULL) + { + if (r1.i == match->base + match->offset) + { + r3.i = TRUE; + break; + } + + if (r1.i < match->base + match->offset) + break; + + match = match->next; + } + + push(r3); + break; + + case OP_FOUND_IN: + pop(r3); + pop(r2); + pop(r1); + + ensure_defined(r1); + ensure_defined(r2); + + match = r3.s->matches[tidx].head; + r3.i = FALSE; + + while (match != NULL && !r3.i) + { + if (match->base + match->offset >= r1.i && + match->base + match->offset <= r2.i) + { + r3.i = TRUE; + } + + if (match->base + match->offset > r2.i) + break; + + match = match->next; + } + + push(r3); + break; + + case OP_COUNT: + pop(r1); + r1.i = r1.s->matches[tidx].count; + push(r1); + break; + + case OP_OFFSET: + pop(r2); + pop(r1); + + ensure_defined(r1); + + match = r2.s->matches[tidx].head; + i = 1; + r3.i = UNDEFINED; + + while (match != NULL && r3.i == UNDEFINED) + { + if (r1.i == i) + r3.i = match->base + match->offset; + + i++; + match = match->next; + } + + push(r3); + break; + + case OP_LENGTH: + pop(r2); + pop(r1); + + ensure_defined(r1); + + match = r2.s->matches[tidx].head; + i = 1; + r3.i = UNDEFINED; + + while (match != NULL && r3.i == UNDEFINED) + { + if (r1.i == i) + r3.i = match->match_length; + + i++; + match = match->next; + } + + push(r3); + break; + + case OP_OF: + found = 0; + count = 0; + pop(r1); + + while (!is_undef(r1)) + { + if (r1.s->matches[tidx].tail != NULL) + found++; + count++; + pop(r1); + } + + pop(r2); + + if (is_undef(r2)) + r1.i = found >= count ? 1 : 0; + else + r1.i = found >= r2.i ? 1 : 0; + + push(r1); + break; + + case OP_FILESIZE: + r1.i = context->file_size; + push(r1); + break; + + case OP_ENTRYPOINT: + r1.i = context->entry_point; + push(r1); + break; + + case OP_INT8: + pop(r1); + r1.i = read_int8_t_little_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_INT16: + pop(r1); + r1.i = read_int16_t_little_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_INT32: + pop(r1); + r1.i = read_int32_t_little_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_UINT8: + pop(r1); + r1.i = read_uint8_t_little_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_UINT16: + pop(r1); + r1.i = read_uint16_t_little_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_UINT32: + pop(r1); + r1.i = read_uint32_t_little_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_INT8BE: + pop(r1); + r1.i = read_int8_t_big_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_INT16BE: + pop(r1); + r1.i = read_int16_t_big_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_INT32BE: + pop(r1); + r1.i = read_int32_t_big_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_UINT8BE: + pop(r1); + r1.i = read_uint8_t_big_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_UINT16BE: + pop(r1); + r1.i = read_uint16_t_big_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_UINT32BE: + pop(r1); + r1.i = read_uint32_t_big_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_CONTAINS: + pop(r2); + pop(r1); + + ensure_defined(r1); + ensure_defined(r2); + + r1.i = memmem(r1.ss->c_string, r1.ss->length, + r2.ss->c_string, r2.ss->length) != NULL; + push(r1); + break; + + case OP_IMPORT: + r1.i = *(uint64_t*)(ip + 1); + ip += sizeof(uint64_t); + + result = yr_modules_load((char*) r1.p, context); + + if (result != ERROR_SUCCESS) + stop = TRUE; + + break; + + case OP_MATCHES: + + pop(r2); + pop(r1); + + ensure_defined(r2); + ensure_defined(r1); + + if (r1.ss->length == 0) + { + r1.i = FALSE; + push(r1); + break; + } + + result = yr_re_exec( + (uint8_t*) r2.re->code, + (uint8_t*) r1.ss->c_string, + r1.ss->length, + 0, + r2.re->flags | RE_FLAGS_SCAN, + NULL, + NULL, + &found); + + if (result != ERROR_SUCCESS) + stop = TRUE; + + r1.i = found >= 0; + push(r1); + break; + + case OP_INT_TO_DBL: + r1.i = *(uint64_t*)(ip + 1); + ip += sizeof(uint64_t); + r2 = stack[sp - r1.i]; + if (is_undef(r2)) + stack[sp - r1.i].i = UNDEFINED; + else + stack[sp - r1.i].d = (double) r2.i; + break; + + case OP_STR_TO_BOOL: + pop(r1); + ensure_defined(r1); + r1.i = r1.ss->length > 0; + push(r1); + break; + + case OP_INT_EQ: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i == r2.i; + push(r1); + break; + + case OP_INT_NEQ: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i != r2.i; + push(r1); + break; + + case OP_INT_LT: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i < r2.i; + push(r1); + break; + + case OP_INT_GT: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i > r2.i; + push(r1); + break; + + case OP_INT_LE: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i <= r2.i; + push(r1); + break; + + case OP_INT_GE: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i >= r2.i; + push(r1); + break; + + case OP_INT_ADD: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i + r2.i; + push(r1); + break; + + case OP_INT_SUB: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i - r2.i; + push(r1); + break; + + case OP_INT_MUL: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i * r2.i; + push(r1); + break; + + case OP_INT_DIV: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + if (r2.i != 0) + r1.i = r1.i / r2.i; + else + r1.i = UNDEFINED; + push(r1); + break; + + case OP_INT_MINUS: + pop(r1); + ensure_defined(r1); + r1.i = -r1.i; + push(r1); + break; + + case OP_DBL_LT: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.d < r2.d; + push(r1); + break; + + case OP_DBL_GT: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.d > r2.d; + push(r1); + break; + + case OP_DBL_LE: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.d <= r2.d; + push(r1); + break; + + case OP_DBL_GE: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.d >= r2.d; + push(r1); + break; + + case OP_DBL_EQ: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.d == r2.d; + push(r1); + break; + + case OP_DBL_NEQ: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.d != r2.d; + push(r1); + break; + + case OP_DBL_ADD: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.d = r1.d + r2.d; + push(r1); + break; + + case OP_DBL_SUB: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.d = r1.d - r2.d; + push(r1); + break; + + case OP_DBL_MUL: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.d = r1.d * r2.d; + push(r1); + break; + + case OP_DBL_DIV: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.d = r1.d / r2.d; + push(r1); + break; + + case OP_DBL_MINUS: + pop(r1); + ensure_defined(r1); + r1.d = -r1.d; + push(r1); + break; + + case OP_STR_EQ: + case OP_STR_NEQ: + case OP_STR_LT: + case OP_STR_LE: + case OP_STR_GT: + case OP_STR_GE: + + pop(r2); + pop(r1); + + ensure_defined(r1); + ensure_defined(r2); + + switch(*ip) + { + case OP_STR_EQ: + r1.i = (sized_string_cmp(r1.ss, r2.ss) == 0); + break; + case OP_STR_NEQ: + r1.i = (sized_string_cmp(r1.ss, r2.ss) != 0); + break; + case OP_STR_LT: + r1.i = (sized_string_cmp(r1.ss, r2.ss) < 0); + break; + case OP_STR_LE: + r1.i = (sized_string_cmp(r1.ss, r2.ss) <= 0); + break; + case OP_STR_GT: + r1.i = (sized_string_cmp(r1.ss, r2.ss) > 0); + break; + case OP_STR_GE: + r1.i = (sized_string_cmp(r1.ss, r2.ss) >= 0); + break; + } + + push(r1); + break; + + default: + assert(FALSE); + } + + if (timeout > 0) // timeout == 0 means no timeout + { + + if (++cycle == 10) + { + if (difftime(time(NULL), start_time) > timeout) + { + #ifdef PROFILING_ENABLED + assert(current_rule != NULL); + current_rule->clock_ticks += clock() - start; + #endif + result = ERROR_SCAN_TIMEOUT; + stop = TRUE; + } + + cycle = 0; + } + } + + ip++; + } + + yr_modules_unload_all(context); + yr_free(stack); + + return result; +} +",1,"int yr_execute_code( + YR_RULES* rules, + YR_SCAN_CONTEXT* context, + int timeout, + time_t start_time) +{ + int64_t mem[MEM_SIZE]; + int32_t sp = 0; + uint8_t* ip = rules->code_start; + + YR_VALUE args[MAX_FUNCTION_ARGS]; + YR_VALUE *stack; + YR_VALUE r1; + YR_VALUE r2; + YR_VALUE r3; + + #ifdef PROFILING_ENABLED + YR_RULE* current_rule = NULL; + #endif + + YR_RULE* rule; + YR_MATCH* match; + YR_OBJECT_FUNCTION* function; + YR_OBJECT** obj_ptr; + YR_ARENA* obj_arena; + + char* identifier; + char* args_fmt; + + int i; + int found; + int count; + int result = ERROR_SUCCESS; + int stop = FALSE; + int cycle = 0; + int tidx = context->tidx; + int stack_size; + + #ifdef PROFILING_ENABLED + clock_t start = clock(); + #endif + + yr_get_configuration(YR_CONFIG_STACK_SIZE, (void*) &stack_size); + + stack = (YR_VALUE*) yr_malloc(stack_size * sizeof(YR_VALUE)); + + if (stack == NULL) + return ERROR_INSUFFICIENT_MEMORY; + + FAIL_ON_ERROR_WITH_CLEANUP( + yr_arena_create(1024, 0, &obj_arena), + yr_free(stack)); + + while(!stop) + { + switch(*ip) + { + case OP_NOP: + break; + + case OP_HALT: + assert(sp == 0); // When HALT is reached the stack should be empty. + stop = TRUE; + break; + + case OP_PUSH: + r1.i = *(uint64_t*)(ip + 1); + ip += sizeof(uint64_t); + push(r1); + break; + + case OP_POP: + pop(r1); + break; + + case OP_CLEAR_M: + r1.i = *(uint64_t*)(ip + 1); + ip += sizeof(uint64_t); + mem[r1.i] = 0; + break; + + case OP_ADD_M: + r1.i = *(uint64_t*)(ip + 1); + ip += sizeof(uint64_t); + pop(r2); + if (!is_undef(r2)) + mem[r1.i] += r2.i; + break; + + case OP_INCR_M: + r1.i = *(uint64_t*)(ip + 1); + ip += sizeof(uint64_t); + mem[r1.i]++; + break; + + case OP_PUSH_M: + r1.i = *(uint64_t*)(ip + 1); + ip += sizeof(uint64_t); + r1.i = mem[r1.i]; + push(r1); + break; + + case OP_POP_M: + r1.i = *(uint64_t*)(ip + 1); + ip += sizeof(uint64_t); + pop(r2); + mem[r1.i] = r2.i; + break; + + case OP_SWAPUNDEF: + r1.i = *(uint64_t*)(ip + 1); + ip += sizeof(uint64_t); + pop(r2); + + if (is_undef(r2)) + { + r1.i = mem[r1.i]; + push(r1); + } + else + { + push(r2); + } + break; + + case OP_JNUNDEF: + pop(r1); + push(r1); + + ip = jmp_if(!is_undef(r1), ip); + break; + + case OP_JLE: + pop(r2); + pop(r1); + push(r1); + push(r2); + + ip = jmp_if(r1.i <= r2.i, ip); + break; + + case OP_JTRUE: + pop(r1); + push(r1); + + ip = jmp_if(!is_undef(r1) && r1.i, ip); + break; + + case OP_JFALSE: + pop(r1); + push(r1); + + ip = jmp_if(is_undef(r1) || !r1.i, ip); + break; + + case OP_AND: + pop(r2); + pop(r1); + + if (is_undef(r1) || is_undef(r2)) + r1.i = 0; + else + r1.i = r1.i && r2.i; + + push(r1); + break; + + case OP_OR: + pop(r2); + pop(r1); + + if (is_undef(r1)) + { + push(r2); + } + else if (is_undef(r2)) + { + push(r1); + } + else + { + r1.i = r1.i || r2.i; + push(r1); + } + break; + + case OP_NOT: + pop(r1); + + if (is_undef(r1)) + r1.i = UNDEFINED; + else + r1.i= !r1.i; + + push(r1); + break; + + case OP_MOD: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + if (r2.i != 0) + r1.i = r1.i % r2.i; + else + r1.i = UNDEFINED; + push(r1); + break; + + case OP_SHR: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i >> r2.i; + push(r1); + break; + + case OP_SHL: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i << r2.i; + push(r1); + break; + + case OP_BITWISE_NOT: + pop(r1); + ensure_defined(r1); + r1.i = ~r1.i; + push(r1); + break; + + case OP_BITWISE_AND: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i & r2.i; + push(r1); + break; + + case OP_BITWISE_OR: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i | r2.i; + push(r1); + break; + + case OP_BITWISE_XOR: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i ^ r2.i; + push(r1); + break; + + case OP_PUSH_RULE: + rule = *(YR_RULE**)(ip + 1); + ip += sizeof(uint64_t); + r1.i = rule->t_flags[tidx] & RULE_TFLAGS_MATCH ? 1 : 0; + push(r1); + break; + + case OP_INIT_RULE: + #ifdef PROFILING_ENABLED + current_rule = *(YR_RULE**)(ip + 1); + #endif + ip += sizeof(uint64_t); + break; + + case OP_MATCH_RULE: + pop(r1); + rule = *(YR_RULE**)(ip + 1); + ip += sizeof(uint64_t); + + if (!is_undef(r1) && r1.i) + rule->t_flags[tidx] |= RULE_TFLAGS_MATCH; + else if (RULE_IS_GLOBAL(rule)) + rule->ns->t_flags[tidx] |= NAMESPACE_TFLAGS_UNSATISFIED_GLOBAL; + + #ifdef PROFILING_ENABLED + rule->clock_ticks += clock() - start; + start = clock(); + #endif + + assert(sp == 0); + break; + + case OP_OBJ_LOAD: + identifier = *(char**)(ip + 1); + ip += sizeof(uint64_t); + + r1.o = (YR_OBJECT*) yr_hash_table_lookup( + context->objects_table, + identifier, + NULL); + + assert(r1.o != NULL); + push(r1); + break; + + case OP_OBJ_FIELD: + identifier = *(char**)(ip + 1); + ip += sizeof(uint64_t); + + pop(r1); + ensure_defined(r1); + + r1.o = yr_object_lookup_field(r1.o, identifier); + + assert(r1.o != NULL); + push(r1); + break; + + case OP_OBJ_VALUE: + pop(r1); + ensure_defined(r1); + + switch(r1.o->type) + { + case OBJECT_TYPE_INTEGER: + r1.i = ((YR_OBJECT_INTEGER*) r1.o)->value; + break; + + case OBJECT_TYPE_FLOAT: + if (isnan(((YR_OBJECT_DOUBLE*) r1.o)->value)) + r1.i = UNDEFINED; + else + r1.d = ((YR_OBJECT_DOUBLE*) r1.o)->value; + break; + + case OBJECT_TYPE_STRING: + if (((YR_OBJECT_STRING*) r1.o)->value == NULL) + r1.i = UNDEFINED; + else + r1.p = ((YR_OBJECT_STRING*) r1.o)->value; + break; + + default: + assert(FALSE); + } + + push(r1); + break; + + case OP_INDEX_ARRAY: + pop(r1); // index + pop(r2); // array + + ensure_defined(r1); + ensure_defined(r2); + assert(r2.o->type == OBJECT_TYPE_ARRAY); + + r1.o = yr_object_array_get_item(r2.o, 0, (int) r1.i); + + if (r1.o == NULL) + r1.i = UNDEFINED; + + push(r1); + break; + + case OP_LOOKUP_DICT: + pop(r1); // key + pop(r2); // dictionary + + ensure_defined(r1); + ensure_defined(r2); + assert(r2.o->type == OBJECT_TYPE_DICTIONARY); + + r1.o = yr_object_dict_get_item( + r2.o, 0, r1.ss->c_string); + + if (r1.o == NULL) + r1.i = UNDEFINED; + + push(r1); + break; + + case OP_CALL: + args_fmt = *(char**)(ip + 1); + ip += sizeof(uint64_t); + + i = (int) strlen(args_fmt); + count = 0; + + + while (i > 0) + { + pop(r1); + + if (is_undef(r1)) // count the number of undefined args + count++; + + args[i - 1] = r1; + i--; + } + + pop(r2); + ensure_defined(r2); + + if (count > 0) + { + + r1.i = UNDEFINED; + push(r1); + break; + } + + function = (YR_OBJECT_FUNCTION*) r2.o; + result = ERROR_INTERNAL_FATAL_ERROR; + + for (i = 0; i < MAX_OVERLOADED_FUNCTIONS; i++) + { + if (function->prototypes[i].arguments_fmt == NULL) + break; + + if (strcmp(function->prototypes[i].arguments_fmt, args_fmt) == 0) + { + result = function->prototypes[i].code(args, context, function); + break; + } + } + + // if i == MAX_OVERLOADED_FUNCTIONS at this point no matching + // prototype was found, but this shouldn't happen. + + assert(i < MAX_OVERLOADED_FUNCTIONS); + + // make a copy of the returned object and push the copy into the stack + // function->return_obj can't be pushed because it can change in + // subsequent calls to the same function. + + if (result == ERROR_SUCCESS) + result = yr_object_copy(function->return_obj, &r1.o); + + // a pointer to the copied object is stored in a arena in order to + // free the object before exiting yr_execute_code + + if (result == ERROR_SUCCESS) + result = yr_arena_write_data(obj_arena, &r1.o, sizeof(r1.o), NULL); + + stop = (result != ERROR_SUCCESS); + push(r1); + break; + + case OP_FOUND: + pop(r1); + r1.i = r1.s->matches[tidx].tail != NULL ? 1 : 0; + push(r1); + break; + + case OP_FOUND_AT: + pop(r2); + pop(r1); + + if (is_undef(r1)) + { + r1.i = 0; + push(r1); + break; + } + + match = r2.s->matches[tidx].head; + r3.i = FALSE; + + while (match != NULL) + { + if (r1.i == match->base + match->offset) + { + r3.i = TRUE; + break; + } + + if (r1.i < match->base + match->offset) + break; + + match = match->next; + } + + push(r3); + break; + + case OP_FOUND_IN: + pop(r3); + pop(r2); + pop(r1); + + ensure_defined(r1); + ensure_defined(r2); + + match = r3.s->matches[tidx].head; + r3.i = FALSE; + + while (match != NULL && !r3.i) + { + if (match->base + match->offset >= r1.i && + match->base + match->offset <= r2.i) + { + r3.i = TRUE; + } + + if (match->base + match->offset > r2.i) + break; + + match = match->next; + } + + push(r3); + break; + + case OP_COUNT: + pop(r1); + r1.i = r1.s->matches[tidx].count; + push(r1); + break; + + case OP_OFFSET: + pop(r2); + pop(r1); + + ensure_defined(r1); + + match = r2.s->matches[tidx].head; + i = 1; + r3.i = UNDEFINED; + + while (match != NULL && r3.i == UNDEFINED) + { + if (r1.i == i) + r3.i = match->base + match->offset; + + i++; + match = match->next; + } + + push(r3); + break; + + case OP_LENGTH: + pop(r2); + pop(r1); + + ensure_defined(r1); + + match = r2.s->matches[tidx].head; + i = 1; + r3.i = UNDEFINED; + + while (match != NULL && r3.i == UNDEFINED) + { + if (r1.i == i) + r3.i = match->match_length; + + i++; + match = match->next; + } + + push(r3); + break; + + case OP_OF: + found = 0; + count = 0; + pop(r1); + + while (!is_undef(r1)) + { + if (r1.s->matches[tidx].tail != NULL) + found++; + count++; + pop(r1); + } + + pop(r2); + + if (is_undef(r2)) + r1.i = found >= count ? 1 : 0; + else + r1.i = found >= r2.i ? 1 : 0; + + push(r1); + break; + + case OP_FILESIZE: + r1.i = context->file_size; + push(r1); + break; + + case OP_ENTRYPOINT: + r1.i = context->entry_point; + push(r1); + break; + + case OP_INT8: + pop(r1); + r1.i = read_int8_t_little_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_INT16: + pop(r1); + r1.i = read_int16_t_little_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_INT32: + pop(r1); + r1.i = read_int32_t_little_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_UINT8: + pop(r1); + r1.i = read_uint8_t_little_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_UINT16: + pop(r1); + r1.i = read_uint16_t_little_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_UINT32: + pop(r1); + r1.i = read_uint32_t_little_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_INT8BE: + pop(r1); + r1.i = read_int8_t_big_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_INT16BE: + pop(r1); + r1.i = read_int16_t_big_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_INT32BE: + pop(r1); + r1.i = read_int32_t_big_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_UINT8BE: + pop(r1); + r1.i = read_uint8_t_big_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_UINT16BE: + pop(r1); + r1.i = read_uint16_t_big_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_UINT32BE: + pop(r1); + r1.i = read_uint32_t_big_endian(context->iterator, (size_t) r1.i); + push(r1); + break; + + case OP_CONTAINS: + pop(r2); + pop(r1); + + ensure_defined(r1); + ensure_defined(r2); + + r1.i = memmem(r1.ss->c_string, r1.ss->length, + r2.ss->c_string, r2.ss->length) != NULL; + push(r1); + break; + + case OP_IMPORT: + r1.i = *(uint64_t*)(ip + 1); + ip += sizeof(uint64_t); + + result = yr_modules_load((char*) r1.p, context); + + if (result != ERROR_SUCCESS) + stop = TRUE; + + break; + + case OP_MATCHES: + + pop(r2); + pop(r1); + + ensure_defined(r2); + ensure_defined(r1); + + if (r1.ss->length == 0) + { + r1.i = FALSE; + push(r1); + break; + } + + result = yr_re_exec( + (uint8_t*) r2.re->code, + (uint8_t*) r1.ss->c_string, + r1.ss->length, + 0, + r2.re->flags | RE_FLAGS_SCAN, + NULL, + NULL, + &found); + + if (result != ERROR_SUCCESS) + stop = TRUE; + + r1.i = found >= 0; + push(r1); + break; + + case OP_INT_TO_DBL: + r1.i = *(uint64_t*)(ip + 1); + ip += sizeof(uint64_t); + r2 = stack[sp - r1.i]; + if (is_undef(r2)) + stack[sp - r1.i].i = UNDEFINED; + else + stack[sp - r1.i].d = (double) r2.i; + break; + + case OP_STR_TO_BOOL: + pop(r1); + ensure_defined(r1); + r1.i = r1.ss->length > 0; + push(r1); + break; + + case OP_INT_EQ: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i == r2.i; + push(r1); + break; + + case OP_INT_NEQ: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i != r2.i; + push(r1); + break; + + case OP_INT_LT: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i < r2.i; + push(r1); + break; + + case OP_INT_GT: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i > r2.i; + push(r1); + break; + + case OP_INT_LE: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i <= r2.i; + push(r1); + break; + + case OP_INT_GE: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i >= r2.i; + push(r1); + break; + + case OP_INT_ADD: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i + r2.i; + push(r1); + break; + + case OP_INT_SUB: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i - r2.i; + push(r1); + break; + + case OP_INT_MUL: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.i * r2.i; + push(r1); + break; + + case OP_INT_DIV: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + if (r2.i != 0) + r1.i = r1.i / r2.i; + else + r1.i = UNDEFINED; + push(r1); + break; + + case OP_INT_MINUS: + pop(r1); + ensure_defined(r1); + r1.i = -r1.i; + push(r1); + break; + + case OP_DBL_LT: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.d < r2.d; + push(r1); + break; + + case OP_DBL_GT: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.d > r2.d; + push(r1); + break; + + case OP_DBL_LE: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.d <= r2.d; + push(r1); + break; + + case OP_DBL_GE: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.d >= r2.d; + push(r1); + break; + + case OP_DBL_EQ: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.d == r2.d; + push(r1); + break; + + case OP_DBL_NEQ: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.i = r1.d != r2.d; + push(r1); + break; + + case OP_DBL_ADD: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.d = r1.d + r2.d; + push(r1); + break; + + case OP_DBL_SUB: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.d = r1.d - r2.d; + push(r1); + break; + + case OP_DBL_MUL: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.d = r1.d * r2.d; + push(r1); + break; + + case OP_DBL_DIV: + pop(r2); + pop(r1); + ensure_defined(r2); + ensure_defined(r1); + r1.d = r1.d / r2.d; + push(r1); + break; + + case OP_DBL_MINUS: + pop(r1); + ensure_defined(r1); + r1.d = -r1.d; + push(r1); + break; + + case OP_STR_EQ: + case OP_STR_NEQ: + case OP_STR_LT: + case OP_STR_LE: + case OP_STR_GT: + case OP_STR_GE: + + pop(r2); + pop(r1); + + ensure_defined(r1); + ensure_defined(r2); + + switch(*ip) + { + case OP_STR_EQ: + r1.i = (sized_string_cmp(r1.ss, r2.ss) == 0); + break; + case OP_STR_NEQ: + r1.i = (sized_string_cmp(r1.ss, r2.ss) != 0); + break; + case OP_STR_LT: + r1.i = (sized_string_cmp(r1.ss, r2.ss) < 0); + break; + case OP_STR_LE: + r1.i = (sized_string_cmp(r1.ss, r2.ss) <= 0); + break; + case OP_STR_GT: + r1.i = (sized_string_cmp(r1.ss, r2.ss) > 0); + break; + case OP_STR_GE: + r1.i = (sized_string_cmp(r1.ss, r2.ss) >= 0); + break; + } + + push(r1); + break; + + default: + assert(FALSE); + } + + if (timeout > 0) // timeout == 0 means no timeout + { + + if (++cycle == 10) + { + if (difftime(time(NULL), start_time) > timeout) + { + #ifdef PROFILING_ENABLED + assert(current_rule != NULL); + current_rule->clock_ticks += clock() - start; + #endif + result = ERROR_SCAN_TIMEOUT; + stop = TRUE; + } + + cycle = 0; + } + } + + ip++; + } + + obj_ptr = (YR_OBJECT**) yr_arena_base_address(obj_arena); + + while (obj_ptr != NULL) + { + yr_object_destroy(*obj_ptr); + + obj_ptr = (YR_OBJECT**) yr_arena_next_address( + obj_arena, obj_ptr, sizeof(YR_OBJECT*)); + } + + yr_arena_destroy(obj_arena); + yr_modules_unload_all(context); + yr_free(stack); + + return result; +} +","@@ -34,6 +34,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + #include + #include + ++#include + #include + #include + #include +@@ -177,6 +178,8 @@ int yr_execute_code( + YR_RULE* rule; + YR_MATCH* match; + YR_OBJECT_FUNCTION* function; ++ YR_OBJECT** obj_ptr; ++ YR_ARENA* obj_arena; + + char* identifier; + char* args_fmt; +@@ -201,6 +204,10 @@ int yr_execute_code( + if (stack == NULL) + return ERROR_INSUFFICIENT_MEMORY; + ++ FAIL_ON_ERROR_WITH_CLEANUP( ++ yr_arena_create(1024, 0, &obj_arena), ++ yr_free(stack)); ++ + while(!stop) + { + switch(*ip) +@@ -437,6 +444,8 @@ int yr_execute_code( + rule->clock_ticks += clock() - start; + start = clock(); + #endif ++ ++ assert(sp == 0); + break; + + case OP_OBJ_LOAD: +@@ -577,18 +586,26 @@ int yr_execute_code( + } + } + ++ // if i == MAX_OVERLOADED_FUNCTIONS at this point no matching ++ // prototype was found, but this shouldn't happen. ++ + assert(i < MAX_OVERLOADED_FUNCTIONS); + ++ // make a copy of the returned object and push the copy into the stack ++ // function->return_obj can't be pushed because it can change in ++ // subsequent calls to the same function. ++ + if (result == ERROR_SUCCESS) +- { +- r1.o = function->return_obj; +- push(r1); +- } +- else +- { +- stop = TRUE; +- } ++ result = yr_object_copy(function->return_obj, &r1.o); ++ ++ // a pointer to the copied object is stored in a arena in order to ++ // free the object before exiting yr_execute_code + ++ if (result == ERROR_SUCCESS) ++ result = yr_arena_write_data(obj_arena, &r1.o, sizeof(r1.o), NULL); ++ ++ stop = (result != ERROR_SUCCESS); ++ push(r1); + break; + + case OP_FOUND: +@@ -1146,6 +1163,17 @@ int yr_execute_code( + ip++; + } + ++ obj_ptr = (YR_OBJECT**) yr_arena_base_address(obj_arena); ++ ++ while (obj_ptr != NULL) ++ { ++ yr_object_destroy(*obj_ptr); ++ ++ obj_ptr = (YR_OBJECT**) yr_arena_next_address( ++ obj_arena, obj_ptr, sizeof(YR_OBJECT*)); ++ } ++ ++ yr_arena_destroy(obj_arena); + yr_modules_unload_all(context); + yr_free(stack); + ",5600,5931,6144 +15915,"bool GLES2DecoderImpl::GetHelper( + GLenum pname, GLint* params, GLsizei* num_written) { + DCHECK(num_written); + switch (pname) { + case GL_IMPLEMENTATION_COLOR_READ_FORMAT: + case GL_IMPLEMENTATION_COLOR_READ_TYPE: + *num_written = 1; + { + Framebuffer* framebuffer = GetBoundReadFramebuffer(); + if (framebuffer && + framebuffer->IsPossiblyComplete(feature_info_.get()) != + GL_FRAMEBUFFER_COMPLETE) { + LOCAL_SET_GL_ERROR( + GL_INVALID_OPERATION, ""glGetIntegerv"", ""incomplete framebuffer""); + if (params) { + *params = 0; + } + return true; + } + } + if (params) { + if (feature_info_->gl_version_info().is_es) { + api()->glGetIntegervFn(pname, params); + } else { + if (pname == GL_IMPLEMENTATION_COLOR_READ_FORMAT) { + *params = GLES2Util::GetGLReadPixelsImplementationFormat( + GetBoundReadFramebufferInternalFormat(), + GetBoundReadFramebufferTextureType(), + feature_info_->feature_flags().ext_read_format_bgra); + } else { + *params = GLES2Util::GetGLReadPixelsImplementationType( + GetBoundReadFramebufferInternalFormat(), + GetBoundReadFramebufferTextureType()); + } + } + if (*params == GL_HALF_FLOAT && feature_info_->IsWebGL1OrES2Context()) { + *params = GL_HALF_FLOAT_OES; + } + if (*params == GL_SRGB_ALPHA_EXT) { + *params = GL_RGBA; + } + if (*params == GL_SRGB_EXT) { + *params = GL_RGB; + } + } + return true; + default: + break; + } + + if (!gl_version_info().is_es) { + switch (pname) { + case GL_MAX_FRAGMENT_UNIFORM_VECTORS: + *num_written = 1; + if (params) { + *params = group_->max_fragment_uniform_vectors(); + } + return true; + case GL_MAX_VARYING_VECTORS: + *num_written = 1; + if (params) { + *params = group_->max_varying_vectors(); + } + return true; + case GL_MAX_VERTEX_UNIFORM_VECTORS: + *num_written = 1; + if (params) { + *params = group_->max_vertex_uniform_vectors(); + } + return true; + } + } + if (feature_info_->IsWebGL2OrES3Context()) { + switch (pname) { + case GL_MAX_VARYING_COMPONENTS: { + if (gl_version_info().is_es) { + *num_written = 1; + break; + } + + GLint max_varying_vectors = 0; + api()->glGetIntegervFn(GL_MAX_VARYING_VECTORS, &max_varying_vectors); + *num_written = 1; + if (params) { + *params = max_varying_vectors * 4; + } + return true; + } + case GL_READ_BUFFER: + *num_written = 1; + if (params) { + Framebuffer* framebuffer = GetBoundReadFramebuffer(); + GLenum read_buffer; + if (framebuffer) { + read_buffer = framebuffer->read_buffer(); + } else { + read_buffer = back_buffer_read_buffer_; + } + *params = static_cast(read_buffer); + } + return true; + case GL_TRANSFORM_FEEDBACK_ACTIVE: + *num_written = 1; + if (params) { + *params = + static_cast(state_.bound_transform_feedback->active()); + } + return true; + case GL_TRANSFORM_FEEDBACK_PAUSED: + *num_written = 1; + if (params) { + *params = + static_cast(state_.bound_transform_feedback->paused()); + } + return true; + case GL_WINDOW_RECTANGLE_EXT: + *num_written = 4; + DCHECK(!params); + return true; + } + } + switch (pname) { + case GL_MAX_VIEWPORT_DIMS: + *num_written = 2; + if (offscreen_target_frame_buffer_.get()) { + if (params) { + params[0] = renderbuffer_manager()->max_renderbuffer_size(); + params[1] = renderbuffer_manager()->max_renderbuffer_size(); + } + return true; + } + break; + case GL_MAX_SAMPLES: + *num_written = 1; + if (params) { + params[0] = renderbuffer_manager()->max_samples(); + } + return true; + case GL_MAX_RENDERBUFFER_SIZE: + *num_written = 1; + if (params) { + params[0] = renderbuffer_manager()->max_renderbuffer_size(); + } + return true; + case GL_MAX_TEXTURE_SIZE: + *num_written = 1; + if (params) { + params[0] = texture_manager()->MaxSizeForTarget(GL_TEXTURE_2D); + } + return true; + case GL_MAX_CUBE_MAP_TEXTURE_SIZE: + *num_written = 1; + if (params) { + params[0] = texture_manager()->MaxSizeForTarget(GL_TEXTURE_CUBE_MAP); + } + return true; + case GL_MAX_COLOR_ATTACHMENTS_EXT: + *num_written = 1; + if (params) { + params[0] = group_->max_color_attachments(); + } + return true; + case GL_MAX_DRAW_BUFFERS_ARB: + *num_written = 1; + if (params) { + params[0] = group_->max_draw_buffers(); + } + return true; + case GL_ALPHA_BITS: + *num_written = 1; + if (params) { + GLint v = 0; + Framebuffer* framebuffer = GetBoundDrawFramebuffer(); + if (framebuffer) { + if (framebuffer->HasAlphaMRT() && + framebuffer->HasSameInternalFormatsMRT()) { + if (gl_version_info().is_desktop_core_profile) { + for (uint32_t i = 0; i < group_->max_draw_buffers(); i++) { + if (framebuffer->HasColorAttachment(i)) { + api()->glGetFramebufferAttachmentParameterivEXTFn( + GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, + GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE, &v); + break; + } + } + } else { + api()->glGetIntegervFn(GL_ALPHA_BITS, &v); + } + } + } else { + v = (ClientExposedBackBufferHasAlpha() ? 8 : 0); + } + params[0] = v; + } + return true; + case GL_DEPTH_BITS: + *num_written = 1; + if (params) { + GLint v = 0; + if (gl_version_info().is_desktop_core_profile) { + Framebuffer* framebuffer = GetBoundDrawFramebuffer(); + if (framebuffer) { + if (framebuffer->HasDepthAttachment()) { + api()->glGetFramebufferAttachmentParameterivEXTFn( + GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, + GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE, &v); + } + } else { + v = (back_buffer_has_depth_ ? 24 : 0); + } + } else { + api()->glGetIntegervFn(GL_DEPTH_BITS, &v); + } + params[0] = BoundFramebufferHasDepthAttachment() ? v : 0; + } + return true; + case GL_RED_BITS: + case GL_GREEN_BITS: + case GL_BLUE_BITS: + *num_written = 1; + if (params) { + GLint v = 0; + if (gl_version_info().is_desktop_core_profile) { + Framebuffer* framebuffer = GetBoundDrawFramebuffer(); + if (framebuffer) { + if (framebuffer->HasSameInternalFormatsMRT()) { + GLenum framebuffer_enum = 0; + switch (pname) { + case GL_RED_BITS: + framebuffer_enum = GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE; + break; + case GL_GREEN_BITS: + framebuffer_enum = GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE; + break; + case GL_BLUE_BITS: + framebuffer_enum = GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE; + break; + } + for (uint32_t i = 0; i < group_->max_draw_buffers(); i++) { + if (framebuffer->HasColorAttachment(i)) { + api()->glGetFramebufferAttachmentParameterivEXTFn( + GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, + framebuffer_enum, &v); + break; + } + } + } + } else { + v = 8; + } + } else { + api()->glGetIntegervFn(pname, &v); + } + params[0] = v; + } + return true; + case GL_STENCIL_BITS: + *num_written = 1; + if (params) { + GLint v = 0; + if (gl_version_info().is_desktop_core_profile) { + Framebuffer* framebuffer = GetBoundDrawFramebuffer(); + if (framebuffer) { + if (framebuffer->HasStencilAttachment()) { + api()->glGetFramebufferAttachmentParameterivEXTFn( + GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, + GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE, &v); + } + } else { + v = (back_buffer_has_stencil_ ? 8 : 0); + } + } else { + api()->glGetIntegervFn(GL_STENCIL_BITS, &v); + } + params[0] = BoundFramebufferHasStencilAttachment() ? v : 0; + } + return true; + case GL_COMPRESSED_TEXTURE_FORMATS: + *num_written = validators_->compressed_texture_format.GetValues().size(); + if (params) { + for (GLint ii = 0; ii < *num_written; ++ii) { + params[ii] = validators_->compressed_texture_format.GetValues()[ii]; + } + } + return true; + case GL_NUM_COMPRESSED_TEXTURE_FORMATS: + *num_written = 1; + if (params) { + *params = validators_->compressed_texture_format.GetValues().size(); + } + return true; + case GL_NUM_SHADER_BINARY_FORMATS: + *num_written = 1; + if (params) { + *params = validators_->shader_binary_format.GetValues().size(); + } + return true; + case GL_SHADER_BINARY_FORMATS: + *num_written = validators_->shader_binary_format.GetValues().size(); + if (params) { + for (GLint ii = 0; ii < *num_written; ++ii) { + params[ii] = validators_->shader_binary_format.GetValues()[ii]; + } + } + return true; + case GL_SHADER_COMPILER: + *num_written = 1; + if (params) { + *params = GL_TRUE; + } + return true; + case GL_ARRAY_BUFFER_BINDING: + *num_written = 1; + if (params) { + *params = GetClientId( + buffer_manager(), state_.bound_array_buffer.get()); + } + return true; + case GL_ELEMENT_ARRAY_BUFFER_BINDING: + *num_written = 1; + if (params) { + *params = GetClientId( + buffer_manager(), + state_.vertex_attrib_manager->element_array_buffer()); + } + return true; + case GL_COPY_READ_BUFFER_BINDING: + *num_written = 1; + if (params) { + *params = GetClientId( + buffer_manager(), state_.bound_copy_read_buffer.get()); + } + return true; + case GL_COPY_WRITE_BUFFER_BINDING: + *num_written = 1; + if (params) { + *params = GetClientId( + buffer_manager(), state_.bound_copy_write_buffer.get()); + } + return true; + case GL_PIXEL_PACK_BUFFER_BINDING: + *num_written = 1; + if (params) { + *params = GetClientId( + buffer_manager(), state_.bound_pixel_pack_buffer.get()); + } + return true; + case GL_PIXEL_UNPACK_BUFFER_BINDING: + *num_written = 1; + if (params) { + *params = GetClientId( + buffer_manager(), state_.bound_pixel_unpack_buffer.get()); + } + return true; + case GL_TRANSFORM_FEEDBACK_BUFFER_BINDING: + *num_written = 1; + if (params) { + *params = GetClientId( + buffer_manager(), state_.bound_transform_feedback_buffer.get()); + } + return true; + case GL_UNIFORM_BUFFER_BINDING: + *num_written = 1; + if (params) { + *params = GetClientId( + buffer_manager(), state_.bound_uniform_buffer.get()); + } + return true; + case GL_FRAMEBUFFER_BINDING: + *num_written = 1; + if (params) { + *params = GetClientId( + framebuffer_manager(), + GetFramebufferInfoForTarget(GL_FRAMEBUFFER)); + } + return true; + case GL_READ_FRAMEBUFFER_BINDING_EXT: + *num_written = 1; + if (params) { + *params = GetClientId( + framebuffer_manager(), + GetFramebufferInfoForTarget(GL_READ_FRAMEBUFFER_EXT)); + } + return true; + case GL_RENDERBUFFER_BINDING: + *num_written = 1; + if (params) { + Renderbuffer* renderbuffer = + GetRenderbufferInfoForTarget(GL_RENDERBUFFER); + if (renderbuffer) { + *params = renderbuffer->client_id(); + } else { + *params = 0; + } + } + return true; + case GL_CURRENT_PROGRAM: + *num_written = 1; + if (params) { + *params = GetClientId(program_manager(), state_.current_program.get()); + } + return true; + case GL_VERTEX_ARRAY_BINDING_OES: + *num_written = 1; + if (params) { + if (state_.vertex_attrib_manager.get() != + state_.default_vertex_attrib_manager.get()) { + GLuint client_id = 0; + vertex_array_manager_->GetClientId( + state_.vertex_attrib_manager->service_id(), &client_id); + *params = client_id; + } else { + *params = 0; + } + } + return true; + case GL_TEXTURE_BINDING_2D: + *num_written = 1; + if (params) { + TextureUnit& unit = state_.texture_units[state_.active_texture_unit]; + if (unit.bound_texture_2d.get()) { + *params = unit.bound_texture_2d->client_id(); + } else { + *params = 0; + } + } + return true; + case GL_TEXTURE_BINDING_CUBE_MAP: + *num_written = 1; + if (params) { + TextureUnit& unit = state_.texture_units[state_.active_texture_unit]; + if (unit.bound_texture_cube_map.get()) { + *params = unit.bound_texture_cube_map->client_id(); + } else { + *params = 0; + } + } + return true; + case GL_TEXTURE_BINDING_EXTERNAL_OES: + *num_written = 1; + if (params) { + TextureUnit& unit = state_.texture_units[state_.active_texture_unit]; + if (unit.bound_texture_external_oes.get()) { + *params = unit.bound_texture_external_oes->client_id(); + } else { + *params = 0; + } + } + return true; + case GL_TEXTURE_BINDING_RECTANGLE_ARB: + *num_written = 1; + if (params) { + TextureUnit& unit = state_.texture_units[state_.active_texture_unit]; + if (unit.bound_texture_rectangle_arb.get()) { + *params = unit.bound_texture_rectangle_arb->client_id(); + } else { + *params = 0; + } + } + return true; + case GL_BIND_GENERATES_RESOURCE_CHROMIUM: + *num_written = 1; + if (params) { + params[0] = group_->bind_generates_resource() ? 1 : 0; + } + return true; + case GL_MAX_DUAL_SOURCE_DRAW_BUFFERS_EXT: + *num_written = 1; + if (params) { + params[0] = group_->max_dual_source_draw_buffers(); + } + return true; + + case GL_MAJOR_VERSION: + *num_written = 1; + if (params) { + params[0] = 3; + } + return true; + case GL_MINOR_VERSION: + *num_written = 1; + if (params) { + params[0] = 0; + } + return true; + + case GL_NUM_EXTENSIONS: + *num_written = 1; + if (params) { + params[0] = 0; + } + return true; + case GL_GPU_DISJOINT_EXT: + *num_written = 1; + if (params) { + params[0] = 0; + } + return true; + case GL_TIMESTAMP_EXT: + *num_written = 1; + if (params) { + params[0] = 0; + } + return true; + case GL_TEXTURE_BINDING_2D_ARRAY: + *num_written = 1; + if (params) { + TextureUnit& unit = state_.texture_units[state_.active_texture_unit]; + if (unit.bound_texture_2d_array.get()) { + *params = unit.bound_texture_2d_array->client_id(); + } else { + *params = 0; + } + } + return true; + case GL_TEXTURE_BINDING_3D: + *num_written = 1; + if (params) { + TextureUnit& unit = state_.texture_units[state_.active_texture_unit]; + if (unit.bound_texture_3d.get()) { + *params = unit.bound_texture_3d->client_id(); + } else { + *params = 0; + } + } + return true; + case GL_SAMPLER_BINDING: + *num_written = 1; + if (params) { + DCHECK_LT(state_.active_texture_unit, state_.sampler_units.size()); + Sampler* sampler = + state_.sampler_units[state_.active_texture_unit].get(); + *params = sampler ? sampler->client_id() : 0; + } + return true; + case GL_TRANSFORM_FEEDBACK_BINDING: + *num_written = 1; + if (params) { + *params = state_.bound_transform_feedback->client_id(); + } + return true; + case GL_NUM_PROGRAM_BINARY_FORMATS: + *num_written = 1; + if (params) { + *params = 0; + } + return true; + case GL_PROGRAM_BINARY_FORMATS: + *num_written = 0; + return true; + default: + if (pname >= GL_DRAW_BUFFER0_ARB && pname <= GL_DRAW_BUFFER15_ARB) { + *num_written = 1; + if (params) { + if (pname < GL_DRAW_BUFFER0_ARB + group_->max_draw_buffers()) { + Framebuffer* framebuffer = + GetFramebufferInfoForTarget(GL_FRAMEBUFFER); + if (framebuffer) { + *params = framebuffer->GetDrawBuffer(pname); + } else { // backbuffer + if (pname == GL_DRAW_BUFFER0_ARB) + *params = back_buffer_draw_buffer_; + else + *params = GL_NONE; + } + } else { + *params = GL_NONE; + } + } + return true; + } + + *num_written = util_.GLGetNumValuesReturned(pname); + if (*num_written) + break; + + return false; + } + + if (params) { + DCHECK(*num_written); + pname = AdjustGetPname(pname); + api()->glGetIntegervFn(pname, params); + } + return true; +} +",0,"bool GLES2DecoderImpl::GetHelper( + GLenum pname, GLint* params, GLsizei* num_written) { + DCHECK(num_written); + switch (pname) { + case GL_IMPLEMENTATION_COLOR_READ_FORMAT: + case GL_IMPLEMENTATION_COLOR_READ_TYPE: + *num_written = 1; + { + Framebuffer* framebuffer = GetBoundReadFramebuffer(); + if (framebuffer && + framebuffer->IsPossiblyComplete(feature_info_.get()) != + GL_FRAMEBUFFER_COMPLETE) { + LOCAL_SET_GL_ERROR( + GL_INVALID_OPERATION, ""glGetIntegerv"", ""incomplete framebuffer""); + if (params) { + *params = 0; + } + return true; + } + } + if (params) { + if (feature_info_->gl_version_info().is_es) { + api()->glGetIntegervFn(pname, params); + } else { + if (pname == GL_IMPLEMENTATION_COLOR_READ_FORMAT) { + *params = GLES2Util::GetGLReadPixelsImplementationFormat( + GetBoundReadFramebufferInternalFormat(), + GetBoundReadFramebufferTextureType(), + feature_info_->feature_flags().ext_read_format_bgra); + } else { + *params = GLES2Util::GetGLReadPixelsImplementationType( + GetBoundReadFramebufferInternalFormat(), + GetBoundReadFramebufferTextureType()); + } + } + if (*params == GL_HALF_FLOAT && feature_info_->IsWebGL1OrES2Context()) { + *params = GL_HALF_FLOAT_OES; + } + if (*params == GL_SRGB_ALPHA_EXT) { + *params = GL_RGBA; + } + if (*params == GL_SRGB_EXT) { + *params = GL_RGB; + } + } + return true; + default: + break; + } + + if (!gl_version_info().is_es) { + switch (pname) { + case GL_MAX_FRAGMENT_UNIFORM_VECTORS: + *num_written = 1; + if (params) { + *params = group_->max_fragment_uniform_vectors(); + } + return true; + case GL_MAX_VARYING_VECTORS: + *num_written = 1; + if (params) { + *params = group_->max_varying_vectors(); + } + return true; + case GL_MAX_VERTEX_UNIFORM_VECTORS: + *num_written = 1; + if (params) { + *params = group_->max_vertex_uniform_vectors(); + } + return true; + } + } + if (feature_info_->IsWebGL2OrES3Context()) { + switch (pname) { + case GL_MAX_VARYING_COMPONENTS: { + if (gl_version_info().is_es) { + *num_written = 1; + break; + } + + GLint max_varying_vectors = 0; + api()->glGetIntegervFn(GL_MAX_VARYING_VECTORS, &max_varying_vectors); + *num_written = 1; + if (params) { + *params = max_varying_vectors * 4; + } + return true; + } + case GL_READ_BUFFER: + *num_written = 1; + if (params) { + Framebuffer* framebuffer = GetBoundReadFramebuffer(); + GLenum read_buffer; + if (framebuffer) { + read_buffer = framebuffer->read_buffer(); + } else { + read_buffer = back_buffer_read_buffer_; + } + *params = static_cast(read_buffer); + } + return true; + case GL_TRANSFORM_FEEDBACK_ACTIVE: + *num_written = 1; + if (params) { + *params = + static_cast(state_.bound_transform_feedback->active()); + } + return true; + case GL_TRANSFORM_FEEDBACK_PAUSED: + *num_written = 1; + if (params) { + *params = + static_cast(state_.bound_transform_feedback->paused()); + } + return true; + case GL_WINDOW_RECTANGLE_EXT: + *num_written = 4; + DCHECK(!params); + return true; + } + } + switch (pname) { + case GL_MAX_VIEWPORT_DIMS: + *num_written = 2; + if (offscreen_target_frame_buffer_.get()) { + if (params) { + params[0] = renderbuffer_manager()->max_renderbuffer_size(); + params[1] = renderbuffer_manager()->max_renderbuffer_size(); + } + return true; + } + break; + case GL_MAX_SAMPLES: + *num_written = 1; + if (params) { + params[0] = renderbuffer_manager()->max_samples(); + } + return true; + case GL_MAX_RENDERBUFFER_SIZE: + *num_written = 1; + if (params) { + params[0] = renderbuffer_manager()->max_renderbuffer_size(); + } + return true; + case GL_MAX_TEXTURE_SIZE: + *num_written = 1; + if (params) { + params[0] = texture_manager()->MaxSizeForTarget(GL_TEXTURE_2D); + } + return true; + case GL_MAX_CUBE_MAP_TEXTURE_SIZE: + *num_written = 1; + if (params) { + params[0] = texture_manager()->MaxSizeForTarget(GL_TEXTURE_CUBE_MAP); + } + return true; + case GL_MAX_COLOR_ATTACHMENTS_EXT: + *num_written = 1; + if (params) { + params[0] = group_->max_color_attachments(); + } + return true; + case GL_MAX_DRAW_BUFFERS_ARB: + *num_written = 1; + if (params) { + params[0] = group_->max_draw_buffers(); + } + return true; + case GL_ALPHA_BITS: + *num_written = 1; + if (params) { + GLint v = 0; + Framebuffer* framebuffer = GetBoundDrawFramebuffer(); + if (framebuffer) { + if (framebuffer->HasAlphaMRT() && + framebuffer->HasSameInternalFormatsMRT()) { + if (gl_version_info().is_desktop_core_profile) { + for (uint32_t i = 0; i < group_->max_draw_buffers(); i++) { + if (framebuffer->HasColorAttachment(i)) { + api()->glGetFramebufferAttachmentParameterivEXTFn( + GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, + GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE, &v); + break; + } + } + } else { + api()->glGetIntegervFn(GL_ALPHA_BITS, &v); + } + } + } else { + v = (ClientExposedBackBufferHasAlpha() ? 8 : 0); + } + params[0] = v; + } + return true; + case GL_DEPTH_BITS: + *num_written = 1; + if (params) { + GLint v = 0; + if (gl_version_info().is_desktop_core_profile) { + Framebuffer* framebuffer = GetBoundDrawFramebuffer(); + if (framebuffer) { + if (framebuffer->HasDepthAttachment()) { + api()->glGetFramebufferAttachmentParameterivEXTFn( + GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, + GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE, &v); + } + } else { + v = (back_buffer_has_depth_ ? 24 : 0); + } + } else { + api()->glGetIntegervFn(GL_DEPTH_BITS, &v); + } + params[0] = BoundFramebufferHasDepthAttachment() ? v : 0; + } + return true; + case GL_RED_BITS: + case GL_GREEN_BITS: + case GL_BLUE_BITS: + *num_written = 1; + if (params) { + GLint v = 0; + if (gl_version_info().is_desktop_core_profile) { + Framebuffer* framebuffer = GetBoundDrawFramebuffer(); + if (framebuffer) { + if (framebuffer->HasSameInternalFormatsMRT()) { + GLenum framebuffer_enum = 0; + switch (pname) { + case GL_RED_BITS: + framebuffer_enum = GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE; + break; + case GL_GREEN_BITS: + framebuffer_enum = GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE; + break; + case GL_BLUE_BITS: + framebuffer_enum = GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE; + break; + } + for (uint32_t i = 0; i < group_->max_draw_buffers(); i++) { + if (framebuffer->HasColorAttachment(i)) { + api()->glGetFramebufferAttachmentParameterivEXTFn( + GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, + framebuffer_enum, &v); + break; + } + } + } + } else { + v = 8; + } + } else { + api()->glGetIntegervFn(pname, &v); + } + params[0] = v; + } + return true; + case GL_STENCIL_BITS: + *num_written = 1; + if (params) { + GLint v = 0; + if (gl_version_info().is_desktop_core_profile) { + Framebuffer* framebuffer = GetBoundDrawFramebuffer(); + if (framebuffer) { + if (framebuffer->HasStencilAttachment()) { + api()->glGetFramebufferAttachmentParameterivEXTFn( + GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, + GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE, &v); + } + } else { + v = (back_buffer_has_stencil_ ? 8 : 0); + } + } else { + api()->glGetIntegervFn(GL_STENCIL_BITS, &v); + } + params[0] = BoundFramebufferHasStencilAttachment() ? v : 0; + } + return true; + case GL_COMPRESSED_TEXTURE_FORMATS: + *num_written = validators_->compressed_texture_format.GetValues().size(); + if (params) { + for (GLint ii = 0; ii < *num_written; ++ii) { + params[ii] = validators_->compressed_texture_format.GetValues()[ii]; + } + } + return true; + case GL_NUM_COMPRESSED_TEXTURE_FORMATS: + *num_written = 1; + if (params) { + *params = validators_->compressed_texture_format.GetValues().size(); + } + return true; + case GL_NUM_SHADER_BINARY_FORMATS: + *num_written = 1; + if (params) { + *params = validators_->shader_binary_format.GetValues().size(); + } + return true; + case GL_SHADER_BINARY_FORMATS: + *num_written = validators_->shader_binary_format.GetValues().size(); + if (params) { + for (GLint ii = 0; ii < *num_written; ++ii) { + params[ii] = validators_->shader_binary_format.GetValues()[ii]; + } + } + return true; + case GL_SHADER_COMPILER: + *num_written = 1; + if (params) { + *params = GL_TRUE; + } + return true; + case GL_ARRAY_BUFFER_BINDING: + *num_written = 1; + if (params) { + *params = GetClientId( + buffer_manager(), state_.bound_array_buffer.get()); + } + return true; + case GL_ELEMENT_ARRAY_BUFFER_BINDING: + *num_written = 1; + if (params) { + *params = GetClientId( + buffer_manager(), + state_.vertex_attrib_manager->element_array_buffer()); + } + return true; + case GL_COPY_READ_BUFFER_BINDING: + *num_written = 1; + if (params) { + *params = GetClientId( + buffer_manager(), state_.bound_copy_read_buffer.get()); + } + return true; + case GL_COPY_WRITE_BUFFER_BINDING: + *num_written = 1; + if (params) { + *params = GetClientId( + buffer_manager(), state_.bound_copy_write_buffer.get()); + } + return true; + case GL_PIXEL_PACK_BUFFER_BINDING: + *num_written = 1; + if (params) { + *params = GetClientId( + buffer_manager(), state_.bound_pixel_pack_buffer.get()); + } + return true; + case GL_PIXEL_UNPACK_BUFFER_BINDING: + *num_written = 1; + if (params) { + *params = GetClientId( + buffer_manager(), state_.bound_pixel_unpack_buffer.get()); + } + return true; + case GL_TRANSFORM_FEEDBACK_BUFFER_BINDING: + *num_written = 1; + if (params) { + *params = GetClientId( + buffer_manager(), state_.bound_transform_feedback_buffer.get()); + } + return true; + case GL_UNIFORM_BUFFER_BINDING: + *num_written = 1; + if (params) { + *params = GetClientId( + buffer_manager(), state_.bound_uniform_buffer.get()); + } + return true; + case GL_FRAMEBUFFER_BINDING: + *num_written = 1; + if (params) { + *params = GetClientId( + framebuffer_manager(), + GetFramebufferInfoForTarget(GL_FRAMEBUFFER)); + } + return true; + case GL_READ_FRAMEBUFFER_BINDING_EXT: + *num_written = 1; + if (params) { + *params = GetClientId( + framebuffer_manager(), + GetFramebufferInfoForTarget(GL_READ_FRAMEBUFFER_EXT)); + } + return true; + case GL_RENDERBUFFER_BINDING: + *num_written = 1; + if (params) { + Renderbuffer* renderbuffer = + GetRenderbufferInfoForTarget(GL_RENDERBUFFER); + if (renderbuffer) { + *params = renderbuffer->client_id(); + } else { + *params = 0; + } + } + return true; + case GL_CURRENT_PROGRAM: + *num_written = 1; + if (params) { + *params = GetClientId(program_manager(), state_.current_program.get()); + } + return true; + case GL_VERTEX_ARRAY_BINDING_OES: + *num_written = 1; + if (params) { + if (state_.vertex_attrib_manager.get() != + state_.default_vertex_attrib_manager.get()) { + GLuint client_id = 0; + vertex_array_manager_->GetClientId( + state_.vertex_attrib_manager->service_id(), &client_id); + *params = client_id; + } else { + *params = 0; + } + } + return true; + case GL_TEXTURE_BINDING_2D: + *num_written = 1; + if (params) { + TextureUnit& unit = state_.texture_units[state_.active_texture_unit]; + if (unit.bound_texture_2d.get()) { + *params = unit.bound_texture_2d->client_id(); + } else { + *params = 0; + } + } + return true; + case GL_TEXTURE_BINDING_CUBE_MAP: + *num_written = 1; + if (params) { + TextureUnit& unit = state_.texture_units[state_.active_texture_unit]; + if (unit.bound_texture_cube_map.get()) { + *params = unit.bound_texture_cube_map->client_id(); + } else { + *params = 0; + } + } + return true; + case GL_TEXTURE_BINDING_EXTERNAL_OES: + *num_written = 1; + if (params) { + TextureUnit& unit = state_.texture_units[state_.active_texture_unit]; + if (unit.bound_texture_external_oes.get()) { + *params = unit.bound_texture_external_oes->client_id(); + } else { + *params = 0; + } + } + return true; + case GL_TEXTURE_BINDING_RECTANGLE_ARB: + *num_written = 1; + if (params) { + TextureUnit& unit = state_.texture_units[state_.active_texture_unit]; + if (unit.bound_texture_rectangle_arb.get()) { + *params = unit.bound_texture_rectangle_arb->client_id(); + } else { + *params = 0; + } + } + return true; + case GL_BIND_GENERATES_RESOURCE_CHROMIUM: + *num_written = 1; + if (params) { + params[0] = group_->bind_generates_resource() ? 1 : 0; + } + return true; + case GL_MAX_DUAL_SOURCE_DRAW_BUFFERS_EXT: + *num_written = 1; + if (params) { + params[0] = group_->max_dual_source_draw_buffers(); + } + return true; + + case GL_MAJOR_VERSION: + *num_written = 1; + if (params) { + params[0] = 3; + } + return true; + case GL_MINOR_VERSION: + *num_written = 1; + if (params) { + params[0] = 0; + } + return true; + + case GL_NUM_EXTENSIONS: + *num_written = 1; + if (params) { + params[0] = 0; + } + return true; + case GL_GPU_DISJOINT_EXT: + *num_written = 1; + if (params) { + params[0] = 0; + } + return true; + case GL_TIMESTAMP_EXT: + *num_written = 1; + if (params) { + params[0] = 0; + } + return true; + case GL_TEXTURE_BINDING_2D_ARRAY: + *num_written = 1; + if (params) { + TextureUnit& unit = state_.texture_units[state_.active_texture_unit]; + if (unit.bound_texture_2d_array.get()) { + *params = unit.bound_texture_2d_array->client_id(); + } else { + *params = 0; + } + } + return true; + case GL_TEXTURE_BINDING_3D: + *num_written = 1; + if (params) { + TextureUnit& unit = state_.texture_units[state_.active_texture_unit]; + if (unit.bound_texture_3d.get()) { + *params = unit.bound_texture_3d->client_id(); + } else { + *params = 0; + } + } + return true; + case GL_SAMPLER_BINDING: + *num_written = 1; + if (params) { + DCHECK_LT(state_.active_texture_unit, state_.sampler_units.size()); + Sampler* sampler = + state_.sampler_units[state_.active_texture_unit].get(); + *params = sampler ? sampler->client_id() : 0; + } + return true; + case GL_TRANSFORM_FEEDBACK_BINDING: + *num_written = 1; + if (params) { + *params = state_.bound_transform_feedback->client_id(); + } + return true; + case GL_NUM_PROGRAM_BINARY_FORMATS: + *num_written = 1; + if (params) { + *params = 0; + } + return true; + case GL_PROGRAM_BINARY_FORMATS: + *num_written = 0; + return true; + default: + if (pname >= GL_DRAW_BUFFER0_ARB && pname <= GL_DRAW_BUFFER15_ARB) { + *num_written = 1; + if (params) { + if (pname < GL_DRAW_BUFFER0_ARB + group_->max_draw_buffers()) { + Framebuffer* framebuffer = + GetFramebufferInfoForTarget(GL_FRAMEBUFFER); + if (framebuffer) { + *params = framebuffer->GetDrawBuffer(pname); + } else { // backbuffer + if (pname == GL_DRAW_BUFFER0_ARB) + *params = back_buffer_draw_buffer_; + else + *params = GL_NONE; + } + } else { + *params = GL_NONE; + } + } + return true; + } + + *num_written = util_.GLGetNumValuesReturned(pname); + if (*num_written) + break; + + return false; + } + + if (params) { + DCHECK(*num_written); + pname = AdjustGetPname(pname); + api()->glGetIntegervFn(pname, params); + } + return true; +} +","@@ -11384,29 +11384,24 @@ void GLES2DecoderImpl::GetTexParameterImpl( + return; + } + break; +- // Get the level information from the texture to avoid a Mac driver +- // bug where they store the levels in int16_t, making values bigger +- // than 2^15-1 overflow in the negative range. + case GL_TEXTURE_BASE_LEVEL: +- if (workarounds().use_shadowed_tex_level_params) { +- if (fparams) { +- fparams[0] = static_cast(texture->base_level()); +- } else { +- iparams[0] = texture->base_level(); +- } +- return; ++ // Use shadowed value in case it's clamped; also because older MacOSX ++ // stores the value on int16_t (see https://crbug.com/610153). ++ if (fparams) { ++ fparams[0] = static_cast(texture->unclamped_base_level()); ++ } else { ++ iparams[0] = texture->unclamped_base_level(); + } +- break; ++ return; + case GL_TEXTURE_MAX_LEVEL: +- if (workarounds().use_shadowed_tex_level_params) { +- if (fparams) { +- fparams[0] = static_cast(texture->max_level()); +- } else { +- iparams[0] = texture->max_level(); +- } +- return; ++ // Use shadowed value in case it's clamped; also because older MacOSX ++ // stores the value on int16_t (see https://crbug.com/610153). ++ if (fparams) { ++ fparams[0] = static_cast(texture->unclamped_max_level()); ++ } else { ++ iparams[0] = texture->unclamped_max_level(); + } +- break; ++ return; + case GL_TEXTURE_SWIZZLE_R: + if (fparams) { + fparams[0] = static_cast(texture->swizzle_r()); +@@ -17573,25 +17568,6 @@ void GLES2DecoderImpl::TexStorageImpl(GLenum target, + compatibility_internal_format = format_info->decompressed_internal_format; + } + +- if (workarounds().reset_base_mipmap_level_before_texstorage && +- texture->base_level() > 0) +- api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, 0); +- +- // TODO(zmo): We might need to emulate TexStorage using TexImage or +- // CompressedTexImage on Mac OSX where we expose ES3 APIs when the underlying +- // driver is lower than 4.2 and ARB_texture_storage extension doesn't exist. +- if (dimension == ContextState::k2D) { +- api()->glTexStorage2DEXTFn(target, levels, compatibility_internal_format, +- width, height); +- } else { +- api()->glTexStorage3DFn(target, levels, compatibility_internal_format, +- width, height, depth); +- } +- if (workarounds().reset_base_mipmap_level_before_texstorage && +- texture->base_level() > 0) +- api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, +- texture->base_level()); +- + { + GLsizei level_width = width; + GLsizei level_height = height; +@@ -17620,6 +17596,29 @@ void GLES2DecoderImpl::TexStorageImpl(GLenum target, + texture->ApplyFormatWorkarounds(feature_info_.get()); + texture->SetImmutable(true); + } ++ ++ if (workarounds().reset_base_mipmap_level_before_texstorage && ++ texture->base_level() > 0) ++ api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, 0); ++ ++ // TODO(zmo): We might need to emulate TexStorage using TexImage or ++ // CompressedTexImage on Mac OSX where we expose ES3 APIs when the underlying ++ // driver is lower than 4.2 and ARB_texture_storage extension doesn't exist. ++ if (dimension == ContextState::k2D) { ++ api()->glTexStorage2DEXTFn(target, levels, compatibility_internal_format, ++ width, height); ++ } else { ++ api()->glTexStorage3DFn(target, levels, compatibility_internal_format, ++ width, height, depth); ++ } ++ if (workarounds().reset_base_mipmap_level_before_texstorage && ++ texture->base_level() > 0) { ++ // Note base_level is already clamped due to texture->SetImmutable(true). ++ // This is necessary for certain NVidia Linux drivers; otherwise they ++ // may trigger segmentation fault. See https://crbug.com/877874. ++ api()->glTexParameteriFn(target, GL_TEXTURE_BASE_LEVEL, ++ texture->base_level()); ++ } + } + + void GLES2DecoderImpl::DoTexStorage2DEXT(GLenum target,",4169,4500,6144 +18159,"static Image *ReadCINImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ +#define MonoColorType 1 +#define RGBColorType 3 + + char + property[MaxTextExtent]; + + CINInfo + cin; + + Image + *image; + + MagickBooleanType + status; + + MagickOffsetType + offset; + + QuantumInfo + *quantum_info; + + QuantumType + quantum_type; + + register ssize_t + i; + + register PixelPacket + *q; + + size_t + length; + + ssize_t + count, + y; + + unsigned char + magick[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); + } + /* + File information. + */ + offset=0; + count=ReadBlob(image,4,magick); + offset+=count; + if ((count != 4) || + ((LocaleNCompare((char *) magick,""\200\052\137\327"",4) != 0))) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + image->endian=(magick[0] == 0x80) && (magick[1] == 0x2a) && + (magick[2] == 0x5f) && (magick[3] == 0xd7) ? MSBEndian : LSBEndian; + cin.file.image_offset=ReadBlobLong(image); + offset+=4; + cin.file.generic_length=ReadBlobLong(image); + offset+=4; + cin.file.industry_length=ReadBlobLong(image); + offset+=4; + cin.file.user_length=ReadBlobLong(image); + offset+=4; + cin.file.file_size=ReadBlobLong(image); + offset+=4; + offset+=ReadBlob(image,sizeof(cin.file.version),(unsigned char *) + cin.file.version); + (void) CopyMagickString(property,cin.file.version,sizeof(cin.file.version)); + (void) SetImageProperty(image,""dpx:file.version"",property); + offset+=ReadBlob(image,sizeof(cin.file.filename),(unsigned char *) + cin.file.filename); + (void) CopyMagickString(property,cin.file.filename,sizeof(cin.file.filename)); + (void) SetImageProperty(image,""dpx:file.filename"",property); + offset+=ReadBlob(image,sizeof(cin.file.create_date),(unsigned char *) + cin.file.create_date); + (void) CopyMagickString(property,cin.file.create_date, + sizeof(cin.file.create_date)); + (void) SetImageProperty(image,""dpx:file.create_date"",property); + offset+=ReadBlob(image,sizeof(cin.file.create_time),(unsigned char *) + cin.file.create_time); + (void) CopyMagickString(property,cin.file.create_time, + sizeof(cin.file.create_time)); + (void) SetImageProperty(image,""dpx:file.create_time"",property); + offset+=ReadBlob(image,sizeof(cin.file.reserve),(unsigned char *) + cin.file.reserve); + /* + Image information. + */ + cin.image.orientation=(unsigned char) ReadBlobByte(image); + offset++; + if (cin.image.orientation != (unsigned char) (~0)) + (void) FormatImageProperty(image,""dpx:image.orientation"",""%d"", + cin.image.orientation); + switch (cin.image.orientation) + { + default: + case 0: image->orientation=TopLeftOrientation; break; + case 1: image->orientation=TopRightOrientation; break; + case 2: image->orientation=BottomLeftOrientation; break; + case 3: image->orientation=BottomRightOrientation; break; + case 4: image->orientation=LeftTopOrientation; break; + case 5: image->orientation=RightTopOrientation; break; + case 6: image->orientation=LeftBottomOrientation; break; + case 7: image->orientation=RightBottomOrientation; break; + } + cin.image.number_channels=(unsigned char) ReadBlobByte(image); + offset++; + offset+=ReadBlob(image,sizeof(cin.image.reserve1),(unsigned char *) + cin.image.reserve1); + for (i=0; i < 8; i++) + { + cin.image.channel[i].designator[0]=(unsigned char) ReadBlobByte(image); + offset++; + cin.image.channel[i].designator[1]=(unsigned char) ReadBlobByte(image); + offset++; + cin.image.channel[i].bits_per_pixel=(unsigned char) ReadBlobByte(image); + offset++; + cin.image.channel[i].reserve=(unsigned char) ReadBlobByte(image); + offset++; + cin.image.channel[i].pixels_per_line=ReadBlobLong(image); + offset+=4; + cin.image.channel[i].lines_per_image=ReadBlobLong(image); + offset+=4; + cin.image.channel[i].min_data=ReadBlobFloat(image); + offset+=4; + cin.image.channel[i].min_quantity=ReadBlobFloat(image); + offset+=4; + cin.image.channel[i].max_data=ReadBlobFloat(image); + offset+=4; + cin.image.channel[i].max_quantity=ReadBlobFloat(image); + offset+=4; + } + cin.image.white_point[0]=ReadBlobFloat(image); + offset+=4; + if (IsFloatDefined(cin.image.white_point[0]) != MagickFalse) + image->chromaticity.white_point.x=cin.image.white_point[0]; + cin.image.white_point[1]=ReadBlobFloat(image); + offset+=4; + if (IsFloatDefined(cin.image.white_point[1]) != MagickFalse) + image->chromaticity.white_point.y=cin.image.white_point[1]; + cin.image.red_primary_chromaticity[0]=ReadBlobFloat(image); + offset+=4; + if (IsFloatDefined(cin.image.red_primary_chromaticity[0]) != MagickFalse) + image->chromaticity.red_primary.x=cin.image.red_primary_chromaticity[0]; + cin.image.red_primary_chromaticity[1]=ReadBlobFloat(image); + offset+=4; + if (IsFloatDefined(cin.image.red_primary_chromaticity[1]) != MagickFalse) + image->chromaticity.red_primary.y=cin.image.red_primary_chromaticity[1]; + cin.image.green_primary_chromaticity[0]=ReadBlobFloat(image); + offset+=4; + if (IsFloatDefined(cin.image.green_primary_chromaticity[0]) != MagickFalse) + image->chromaticity.red_primary.x=cin.image.green_primary_chromaticity[0]; + cin.image.green_primary_chromaticity[1]=ReadBlobFloat(image); + offset+=4; + if (IsFloatDefined(cin.image.green_primary_chromaticity[1]) != MagickFalse) + image->chromaticity.green_primary.y=cin.image.green_primary_chromaticity[1]; + cin.image.blue_primary_chromaticity[0]=ReadBlobFloat(image); + offset+=4; + if (IsFloatDefined(cin.image.blue_primary_chromaticity[0]) != MagickFalse) + image->chromaticity.blue_primary.x=cin.image.blue_primary_chromaticity[0]; + cin.image.blue_primary_chromaticity[1]=ReadBlobFloat(image); + offset+=4; + if (IsFloatDefined(cin.image.blue_primary_chromaticity[1]) != MagickFalse) + image->chromaticity.blue_primary.y=cin.image.blue_primary_chromaticity[1]; + offset+=ReadBlob(image,sizeof(cin.image.label),(unsigned char *) + cin.image.label); + (void) CopyMagickString(property,cin.image.label,sizeof(cin.image.label)); + (void) SetImageProperty(image,""dpx:image.label"",property); + offset+=ReadBlob(image,sizeof(cin.image.reserve),(unsigned char *) + cin.image.reserve); + /* + Image data format information. + */ + cin.data_format.interleave=(unsigned char) ReadBlobByte(image); + offset++; + cin.data_format.packing=(unsigned char) ReadBlobByte(image); + offset++; + cin.data_format.sign=(unsigned char) ReadBlobByte(image); + offset++; + cin.data_format.sense=(unsigned char) ReadBlobByte(image); + offset++; + cin.data_format.line_pad=ReadBlobLong(image); + offset+=4; + cin.data_format.channel_pad=ReadBlobLong(image); + offset+=4; + offset+=ReadBlob(image,sizeof(cin.data_format.reserve),(unsigned char *) + cin.data_format.reserve); + /* + Image origination information. + */ + cin.origination.x_offset=(int) ReadBlobLong(image); + offset+=4; + if ((size_t) cin.origination.x_offset != ~0UL) + (void) FormatImageProperty(image,""dpx:origination.x_offset"",""%.20g"", + (double) cin.origination.x_offset); + cin.origination.y_offset=(ssize_t) ReadBlobLong(image); + offset+=4; + if ((size_t) cin.origination.y_offset != ~0UL) + (void) FormatImageProperty(image,""dpx:origination.y_offset"",""%.20g"", + (double) cin.origination.y_offset); + offset+=ReadBlob(image,sizeof(cin.origination.filename),(unsigned char *) + cin.origination.filename); + (void) CopyMagickString(property,cin.origination.filename, + sizeof(cin.origination.filename)); + (void) SetImageProperty(image,""dpx:origination.filename"",property); + offset+=ReadBlob(image,sizeof(cin.origination.create_date),(unsigned char *) + cin.origination.create_date); + (void) CopyMagickString(property,cin.origination.create_date, + sizeof(cin.origination.create_date)); + (void) SetImageProperty(image,""dpx:origination.create_date"",property); + offset+=ReadBlob(image,sizeof(cin.origination.create_time),(unsigned char *) + cin.origination.create_time); + (void) CopyMagickString(property,cin.origination.create_time, + sizeof(cin.origination.create_time)); + (void) SetImageProperty(image,""dpx:origination.create_time"",property); + offset+=ReadBlob(image,sizeof(cin.origination.device),(unsigned char *) + cin.origination.device); + (void) CopyMagickString(property,cin.origination.device, + sizeof(cin.origination.device)); + (void) SetImageProperty(image,""dpx:origination.device"",property); + offset+=ReadBlob(image,sizeof(cin.origination.model),(unsigned char *) + cin.origination.model); + (void) CopyMagickString(property,cin.origination.model, + sizeof(cin.origination.model)); + (void) SetImageProperty(image,""dpx:origination.model"",property); + (void) ResetMagickMemory(cin.origination.serial,0, + sizeof(cin.origination.serial)); + offset+=ReadBlob(image,sizeof(cin.origination.serial),(unsigned char *) + cin.origination.serial); + (void) CopyMagickString(property,cin.origination.serial, + sizeof(cin.origination.serial)); + (void) SetImageProperty(image,""dpx:origination.serial"",property); + cin.origination.x_pitch=ReadBlobFloat(image); + offset+=4; + cin.origination.y_pitch=ReadBlobFloat(image); + offset+=4; + cin.origination.gamma=ReadBlobFloat(image); + offset+=4; + if (IsFloatDefined(cin.origination.gamma) != MagickFalse) + image->gamma=cin.origination.gamma; + offset+=ReadBlob(image,sizeof(cin.origination.reserve),(unsigned char *) + cin.origination.reserve); + if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0)) + { + int + c; + + /* + Image film information. + */ + cin.film.id=ReadBlobByte(image); + offset++; + c=cin.film.id; + if (c != ~0) + (void) FormatImageProperty(image,""dpx:film.id"",""%d"",cin.film.id); + cin.film.type=ReadBlobByte(image); + offset++; + c=cin.film.type; + if (c != ~0) + (void) FormatImageProperty(image,""dpx:film.type"",""%d"",cin.film.type); + cin.film.offset=ReadBlobByte(image); + offset++; + c=cin.film.offset; + if (c != ~0) + (void) FormatImageProperty(image,""dpx:film.offset"",""%d"", + cin.film.offset); + cin.film.reserve1=ReadBlobByte(image); + offset++; + cin.film.prefix=ReadBlobLong(image); + offset+=4; + if (cin.film.prefix != ~0UL) + (void) FormatImageProperty(image,""dpx:film.prefix"",""%.20g"",(double) + cin.film.prefix); + cin.film.count=ReadBlobLong(image); + offset+=4; + offset+=ReadBlob(image,sizeof(cin.film.format),(unsigned char *) + cin.film.format); + (void) CopyMagickString(property,cin.film.format, + sizeof(cin.film.format)); + (void) SetImageProperty(image,""dpx:film.format"",property); + cin.film.frame_position=ReadBlobLong(image); + offset+=4; + if (cin.film.frame_position != ~0UL) + (void) FormatImageProperty(image,""dpx:film.frame_position"",""%.20g"", + (double) cin.film.frame_position); + cin.film.frame_rate=ReadBlobFloat(image); + offset+=4; + if (IsFloatDefined(cin.film.frame_rate) != MagickFalse) + (void) FormatImageProperty(image,""dpx:film.frame_rate"",""%g"", + cin.film.frame_rate); + offset+=ReadBlob(image,sizeof(cin.film.frame_id),(unsigned char *) + cin.film.frame_id); + (void) CopyMagickString(property,cin.film.frame_id, + sizeof(cin.film.frame_id)); + (void) SetImageProperty(image,""dpx:film.frame_id"",property); + offset+=ReadBlob(image,sizeof(cin.film.slate_info),(unsigned char *) + cin.film.slate_info); + (void) CopyMagickString(property,cin.film.slate_info, + sizeof(cin.film.slate_info)); + (void) SetImageProperty(image,""dpx:film.slate_info"",property); + offset+=ReadBlob(image,sizeof(cin.film.reserve),(unsigned char *) + cin.film.reserve); + } + if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0)) + { + StringInfo + *profile; + + /* + User defined data. + */ + profile=BlobToStringInfo((const void *) NULL,cin.file.user_length); + if (profile == (StringInfo *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + offset+=ReadBlob(image,GetStringInfoLength(profile), + GetStringInfoDatum(profile)); + (void) SetImageProfile(image,""dpx:user.data"",profile); + profile=DestroyStringInfo(profile); + } + for ( ; offset < (MagickOffsetType) cin.file.image_offset; offset++) + (void) ReadBlobByte(image); + image->depth=cin.image.channel[0].bits_per_pixel; + image->columns=cin.image.channel[0].pixels_per_line; + image->rows=cin.image.channel[0].lines_per_image; + if (image_info->ping) + { + (void) CloseBlob(image); + return(image); + } + /* + Convert CIN raster image to pixel packets. + */ + quantum_info=AcquireQuantumInfo(image_info,image); + if (quantum_info == (QuantumInfo *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + quantum_info->quantum=32; + quantum_info->pack=MagickFalse; + quantum_type=RGBQuantum; + pixels=GetQuantumPixels(quantum_info); + length=GetQuantumExtent(image,quantum_info,quantum_type); + length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue); + if (cin.image.number_channels == 1) + { + quantum_type=GrayQuantum; + length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue); + } + for (y=0; y < (ssize_t) image->rows; y++) + { + q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); + if (q == (PixelPacket *) NULL) + break; + count=ReadBlob(image,length,pixels); + if ((size_t) count != length) + 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; + } + } + SetQuantumImageType(image,quantum_type); + quantum_info=DestroyQuantumInfo(quantum_info); + if (EOFBlob(image) != MagickFalse) + ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", + image->filename); + SetImageColorspace(image,LogColorspace); + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +",1,"static Image *ReadCINImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ +#define MonoColorType 1 +#define RGBColorType 3 + + char + property[MaxTextExtent]; + + CINInfo + cin; + + Image + *image; + + MagickBooleanType + status; + + MagickOffsetType + offset; + + QuantumInfo + *quantum_info; + + QuantumType + quantum_type; + + register ssize_t + i; + + register PixelPacket + *q; + + size_t + length; + + ssize_t + count, + y; + + unsigned char + magick[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); + } + /* + File information. + */ + offset=0; + count=ReadBlob(image,4,magick); + offset+=count; + if ((count != 4) || + ((LocaleNCompare((char *) magick,""\200\052\137\327"",4) != 0))) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + image->endian=(magick[0] == 0x80) && (magick[1] == 0x2a) && + (magick[2] == 0x5f) && (magick[3] == 0xd7) ? MSBEndian : LSBEndian; + cin.file.image_offset=ReadBlobLong(image); + offset+=4; + cin.file.generic_length=ReadBlobLong(image); + offset+=4; + cin.file.industry_length=ReadBlobLong(image); + offset+=4; + cin.file.user_length=ReadBlobLong(image); + offset+=4; + cin.file.file_size=ReadBlobLong(image); + offset+=4; + offset+=ReadBlob(image,sizeof(cin.file.version),(unsigned char *) + cin.file.version); + (void) CopyMagickString(property,cin.file.version,sizeof(cin.file.version)); + (void) SetImageProperty(image,""dpx:file.version"",property); + offset+=ReadBlob(image,sizeof(cin.file.filename),(unsigned char *) + cin.file.filename); + (void) CopyMagickString(property,cin.file.filename,sizeof(cin.file.filename)); + (void) SetImageProperty(image,""dpx:file.filename"",property); + offset+=ReadBlob(image,sizeof(cin.file.create_date),(unsigned char *) + cin.file.create_date); + (void) CopyMagickString(property,cin.file.create_date, + sizeof(cin.file.create_date)); + (void) SetImageProperty(image,""dpx:file.create_date"",property); + offset+=ReadBlob(image,sizeof(cin.file.create_time),(unsigned char *) + cin.file.create_time); + (void) CopyMagickString(property,cin.file.create_time, + sizeof(cin.file.create_time)); + (void) SetImageProperty(image,""dpx:file.create_time"",property); + offset+=ReadBlob(image,sizeof(cin.file.reserve),(unsigned char *) + cin.file.reserve); + /* + Image information. + */ + cin.image.orientation=(unsigned char) ReadBlobByte(image); + offset++; + if (cin.image.orientation != (unsigned char) (~0)) + (void) FormatImageProperty(image,""dpx:image.orientation"",""%d"", + cin.image.orientation); + switch (cin.image.orientation) + { + default: + case 0: image->orientation=TopLeftOrientation; break; + case 1: image->orientation=TopRightOrientation; break; + case 2: image->orientation=BottomLeftOrientation; break; + case 3: image->orientation=BottomRightOrientation; break; + case 4: image->orientation=LeftTopOrientation; break; + case 5: image->orientation=RightTopOrientation; break; + case 6: image->orientation=LeftBottomOrientation; break; + case 7: image->orientation=RightBottomOrientation; break; + } + cin.image.number_channels=(unsigned char) ReadBlobByte(image); + offset++; + offset+=ReadBlob(image,sizeof(cin.image.reserve1),(unsigned char *) + cin.image.reserve1); + for (i=0; i < 8; i++) + { + cin.image.channel[i].designator[0]=(unsigned char) ReadBlobByte(image); + offset++; + cin.image.channel[i].designator[1]=(unsigned char) ReadBlobByte(image); + offset++; + cin.image.channel[i].bits_per_pixel=(unsigned char) ReadBlobByte(image); + offset++; + cin.image.channel[i].reserve=(unsigned char) ReadBlobByte(image); + offset++; + cin.image.channel[i].pixels_per_line=ReadBlobLong(image); + offset+=4; + cin.image.channel[i].lines_per_image=ReadBlobLong(image); + offset+=4; + cin.image.channel[i].min_data=ReadBlobFloat(image); + offset+=4; + cin.image.channel[i].min_quantity=ReadBlobFloat(image); + offset+=4; + cin.image.channel[i].max_data=ReadBlobFloat(image); + offset+=4; + cin.image.channel[i].max_quantity=ReadBlobFloat(image); + offset+=4; + } + cin.image.white_point[0]=ReadBlobFloat(image); + offset+=4; + if (IsFloatDefined(cin.image.white_point[0]) != MagickFalse) + image->chromaticity.white_point.x=cin.image.white_point[0]; + cin.image.white_point[1]=ReadBlobFloat(image); + offset+=4; + if (IsFloatDefined(cin.image.white_point[1]) != MagickFalse) + image->chromaticity.white_point.y=cin.image.white_point[1]; + cin.image.red_primary_chromaticity[0]=ReadBlobFloat(image); + offset+=4; + if (IsFloatDefined(cin.image.red_primary_chromaticity[0]) != MagickFalse) + image->chromaticity.red_primary.x=cin.image.red_primary_chromaticity[0]; + cin.image.red_primary_chromaticity[1]=ReadBlobFloat(image); + offset+=4; + if (IsFloatDefined(cin.image.red_primary_chromaticity[1]) != MagickFalse) + image->chromaticity.red_primary.y=cin.image.red_primary_chromaticity[1]; + cin.image.green_primary_chromaticity[0]=ReadBlobFloat(image); + offset+=4; + if (IsFloatDefined(cin.image.green_primary_chromaticity[0]) != MagickFalse) + image->chromaticity.red_primary.x=cin.image.green_primary_chromaticity[0]; + cin.image.green_primary_chromaticity[1]=ReadBlobFloat(image); + offset+=4; + if (IsFloatDefined(cin.image.green_primary_chromaticity[1]) != MagickFalse) + image->chromaticity.green_primary.y=cin.image.green_primary_chromaticity[1]; + cin.image.blue_primary_chromaticity[0]=ReadBlobFloat(image); + offset+=4; + if (IsFloatDefined(cin.image.blue_primary_chromaticity[0]) != MagickFalse) + image->chromaticity.blue_primary.x=cin.image.blue_primary_chromaticity[0]; + cin.image.blue_primary_chromaticity[1]=ReadBlobFloat(image); + offset+=4; + if (IsFloatDefined(cin.image.blue_primary_chromaticity[1]) != MagickFalse) + image->chromaticity.blue_primary.y=cin.image.blue_primary_chromaticity[1]; + offset+=ReadBlob(image,sizeof(cin.image.label),(unsigned char *) + cin.image.label); + (void) CopyMagickString(property,cin.image.label,sizeof(cin.image.label)); + (void) SetImageProperty(image,""dpx:image.label"",property); + offset+=ReadBlob(image,sizeof(cin.image.reserve),(unsigned char *) + cin.image.reserve); + /* + Image data format information. + */ + cin.data_format.interleave=(unsigned char) ReadBlobByte(image); + offset++; + cin.data_format.packing=(unsigned char) ReadBlobByte(image); + offset++; + cin.data_format.sign=(unsigned char) ReadBlobByte(image); + offset++; + cin.data_format.sense=(unsigned char) ReadBlobByte(image); + offset++; + cin.data_format.line_pad=ReadBlobLong(image); + offset+=4; + cin.data_format.channel_pad=ReadBlobLong(image); + offset+=4; + offset+=ReadBlob(image,sizeof(cin.data_format.reserve),(unsigned char *) + cin.data_format.reserve); + /* + Image origination information. + */ + cin.origination.x_offset=(int) ReadBlobLong(image); + offset+=4; + if ((size_t) cin.origination.x_offset != ~0UL) + (void) FormatImageProperty(image,""dpx:origination.x_offset"",""%.20g"", + (double) cin.origination.x_offset); + cin.origination.y_offset=(ssize_t) ReadBlobLong(image); + offset+=4; + if ((size_t) cin.origination.y_offset != ~0UL) + (void) FormatImageProperty(image,""dpx:origination.y_offset"",""%.20g"", + (double) cin.origination.y_offset); + offset+=ReadBlob(image,sizeof(cin.origination.filename),(unsigned char *) + cin.origination.filename); + (void) CopyMagickString(property,cin.origination.filename, + sizeof(cin.origination.filename)); + (void) SetImageProperty(image,""dpx:origination.filename"",property); + offset+=ReadBlob(image,sizeof(cin.origination.create_date),(unsigned char *) + cin.origination.create_date); + (void) CopyMagickString(property,cin.origination.create_date, + sizeof(cin.origination.create_date)); + (void) SetImageProperty(image,""dpx:origination.create_date"",property); + offset+=ReadBlob(image,sizeof(cin.origination.create_time),(unsigned char *) + cin.origination.create_time); + (void) CopyMagickString(property,cin.origination.create_time, + sizeof(cin.origination.create_time)); + (void) SetImageProperty(image,""dpx:origination.create_time"",property); + offset+=ReadBlob(image,sizeof(cin.origination.device),(unsigned char *) + cin.origination.device); + (void) CopyMagickString(property,cin.origination.device, + sizeof(cin.origination.device)); + (void) SetImageProperty(image,""dpx:origination.device"",property); + offset+=ReadBlob(image,sizeof(cin.origination.model),(unsigned char *) + cin.origination.model); + (void) CopyMagickString(property,cin.origination.model, + sizeof(cin.origination.model)); + (void) SetImageProperty(image,""dpx:origination.model"",property); + (void) ResetMagickMemory(cin.origination.serial,0, + sizeof(cin.origination.serial)); + offset+=ReadBlob(image,sizeof(cin.origination.serial),(unsigned char *) + cin.origination.serial); + (void) CopyMagickString(property,cin.origination.serial, + sizeof(cin.origination.serial)); + (void) SetImageProperty(image,""dpx:origination.serial"",property); + cin.origination.x_pitch=ReadBlobFloat(image); + offset+=4; + cin.origination.y_pitch=ReadBlobFloat(image); + offset+=4; + cin.origination.gamma=ReadBlobFloat(image); + offset+=4; + if (IsFloatDefined(cin.origination.gamma) != MagickFalse) + image->gamma=cin.origination.gamma; + offset+=ReadBlob(image,sizeof(cin.origination.reserve),(unsigned char *) + cin.origination.reserve); + if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0)) + { + int + c; + + /* + Image film information. + */ + cin.film.id=ReadBlobByte(image); + offset++; + c=cin.film.id; + if (c != ~0) + (void) FormatImageProperty(image,""dpx:film.id"",""%d"",cin.film.id); + cin.film.type=ReadBlobByte(image); + offset++; + c=cin.film.type; + if (c != ~0) + (void) FormatImageProperty(image,""dpx:film.type"",""%d"",cin.film.type); + cin.film.offset=ReadBlobByte(image); + offset++; + c=cin.film.offset; + if (c != ~0) + (void) FormatImageProperty(image,""dpx:film.offset"",""%d"", + cin.film.offset); + cin.film.reserve1=ReadBlobByte(image); + offset++; + cin.film.prefix=ReadBlobLong(image); + offset+=4; + if (cin.film.prefix != ~0UL) + (void) FormatImageProperty(image,""dpx:film.prefix"",""%.20g"",(double) + cin.film.prefix); + cin.film.count=ReadBlobLong(image); + offset+=4; + offset+=ReadBlob(image,sizeof(cin.film.format),(unsigned char *) + cin.film.format); + (void) CopyMagickString(property,cin.film.format, + sizeof(cin.film.format)); + (void) SetImageProperty(image,""dpx:film.format"",property); + cin.film.frame_position=ReadBlobLong(image); + offset+=4; + if (cin.film.frame_position != ~0UL) + (void) FormatImageProperty(image,""dpx:film.frame_position"",""%.20g"", + (double) cin.film.frame_position); + cin.film.frame_rate=ReadBlobFloat(image); + offset+=4; + if (IsFloatDefined(cin.film.frame_rate) != MagickFalse) + (void) FormatImageProperty(image,""dpx:film.frame_rate"",""%g"", + cin.film.frame_rate); + offset+=ReadBlob(image,sizeof(cin.film.frame_id),(unsigned char *) + cin.film.frame_id); + (void) CopyMagickString(property,cin.film.frame_id, + sizeof(cin.film.frame_id)); + (void) SetImageProperty(image,""dpx:film.frame_id"",property); + offset+=ReadBlob(image,sizeof(cin.film.slate_info),(unsigned char *) + cin.film.slate_info); + (void) CopyMagickString(property,cin.film.slate_info, + sizeof(cin.film.slate_info)); + (void) SetImageProperty(image,""dpx:film.slate_info"",property); + offset+=ReadBlob(image,sizeof(cin.film.reserve),(unsigned char *) + cin.film.reserve); + } + if ((cin.file.image_offset > 2048) && (cin.file.user_length != 0)) + { + StringInfo + *profile; + + /* + User defined data. + */ + profile=BlobToStringInfo((const void *) NULL,cin.file.user_length); + if (profile == (StringInfo *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + offset+=ReadBlob(image,GetStringInfoLength(profile), + GetStringInfoDatum(profile)); + (void) SetImageProfile(image,""dpx:user.data"",profile); + profile=DestroyStringInfo(profile); + } + for ( ; offset < (MagickOffsetType) cin.file.image_offset; offset++) + (void) ReadBlobByte(image); + image->depth=cin.image.channel[0].bits_per_pixel; + image->columns=cin.image.channel[0].pixels_per_line; + image->rows=cin.image.channel[0].lines_per_image; + if (image_info->ping != MagickFalse) + { + (void) CloseBlob(image); + return(image); + } + status=SetImageExtent(image,image->columns,image->rows); + if (status == MagickFalse) + { + InheritException(exception,&image->exception); + return(DestroyImageList(image)); + } + /* + Convert CIN raster image to pixel packets. + */ + quantum_info=AcquireQuantumInfo(image_info,image); + if (quantum_info == (QuantumInfo *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + quantum_info->quantum=32; + quantum_info->pack=MagickFalse; + quantum_type=RGBQuantum; + pixels=GetQuantumPixels(quantum_info); + length=GetQuantumExtent(image,quantum_info,quantum_type); + length=GetBytesPerRow(image->columns,3,image->depth,MagickTrue); + if (cin.image.number_channels == 1) + { + quantum_type=GrayQuantum; + length=GetBytesPerRow(image->columns,1,image->depth,MagickTrue); + } + for (y=0; y < (ssize_t) image->rows; y++) + { + q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); + if (q == (PixelPacket *) NULL) + break; + count=ReadBlob(image,length,pixels); + if ((size_t) count != length) + 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; + } + } + SetQuantumImageType(image,quantum_type); + quantum_info=DestroyQuantumInfo(quantum_info); + if (EOFBlob(image) != MagickFalse) + ThrowFileException(exception,CorruptImageError,""UnexpectedEndOfFile"", + image->filename); + SetImageColorspace(image,LogColorspace); + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +","@@ -721,11 +721,17 @@ static Image *ReadCINImage(const ImageInfo *image_info,ExceptionInfo *exception) + image->depth=cin.image.channel[0].bits_per_pixel; + image->columns=cin.image.channel[0].pixels_per_line; + image->rows=cin.image.channel[0].lines_per_image; +- if (image_info->ping) ++ if (image_info->ping != MagickFalse) + { + (void) CloseBlob(image); + return(image); + } ++ status=SetImageExtent(image,image->columns,image->rows); ++ if (status == MagickFalse) ++ { ++ InheritException(exception,&image->exception); ++ return(DestroyImageList(image)); ++ } + /* + Convert CIN raster image to pixel packets. + */",3819,4150,6144 +18171,"static Image *ReadWPGImage(const ImageInfo *image_info, + ExceptionInfo *exception) +{ + typedef struct + { + size_t FileId; + MagickOffsetType DataOffset; + unsigned int ProductType; + unsigned int FileType; + unsigned char MajorVersion; + unsigned char MinorVersion; + unsigned int EncryptKey; + unsigned int Reserved; + } WPGHeader; + + typedef struct + { + unsigned char RecType; + size_t RecordLength; + } WPGRecord; + + typedef struct + { + unsigned char Class; + unsigned char RecType; + size_t Extension; + size_t RecordLength; + } WPG2Record; + + typedef struct + { + unsigned HorizontalUnits; + unsigned VerticalUnits; + unsigned char PosSizePrecision; + } WPG2Start; + + typedef struct + { + unsigned int Width; + unsigned int Height; + unsigned int Depth; + unsigned int HorzRes; + unsigned int VertRes; + } WPGBitmapType1; + + typedef struct + { + unsigned int Width; + unsigned int Height; + unsigned char Depth; + unsigned char Compression; + } WPG2BitmapType1; + + typedef struct + { + unsigned int RotAngle; + unsigned int LowLeftX; + unsigned int LowLeftY; + unsigned int UpRightX; + unsigned int UpRightY; + unsigned int Width; + unsigned int Height; + unsigned int Depth; + unsigned int HorzRes; + unsigned int VertRes; + } WPGBitmapType2; + + typedef struct + { + unsigned int StartIndex; + unsigned int NumOfEntries; + } WPGColorMapRec; + + /* + typedef struct { + size_t PS_unknown1; + unsigned int PS_unknown2; + unsigned int PS_unknown3; + } WPGPSl1Record; + */ + + Image + *image; + + unsigned int + status; + + WPGHeader + Header; + + WPGRecord + Rec; + + WPG2Record + Rec2; + + WPG2Start StartWPG; + + WPGBitmapType1 + BitmapHeader1; + + WPG2BitmapType1 + Bitmap2Header1; + + WPGBitmapType2 + BitmapHeader2; + + WPGColorMapRec + WPG_Palette; + + int + i, + bpp, + WPG2Flags; + + ssize_t + ldblk; + + size_t + one; + + unsigned char + *BImgBuff; + + tCTM CTM; /*current transform matrix*/ + + /* + Open image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickSignature); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickSignature); + one=1; + image=AcquireImage(image_info); + image->depth=8; + status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); + if (status == MagickFalse) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + /* + Read WPG image. + */ + Header.FileId=ReadBlobLSBLong(image); + Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image); + Header.ProductType=ReadBlobLSBShort(image); + Header.FileType=ReadBlobLSBShort(image); + Header.MajorVersion=ReadBlobByte(image); + Header.MinorVersion=ReadBlobByte(image); + Header.EncryptKey=ReadBlobLSBShort(image); + Header.Reserved=ReadBlobLSBShort(image); + + if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + if (Header.EncryptKey!=0) + ThrowReaderException(CoderError,""EncryptedWPGImageFileNotSupported""); + + image->columns = 1; + image->rows = 1; + image->colors = 0; + bpp=0; + BitmapHeader2.RotAngle=0; + + switch(Header.FileType) + { + case 1: /* WPG level 1 */ + while(!EOFBlob(image)) /* object parser loop */ + { + (void) SeekBlob(image,Header.DataOffset,SEEK_SET); + if(EOFBlob(image)) + break; + + Rec.RecType=(i=ReadBlobByte(image)); + if(i==EOF) + break; + Rd_WP_DWORD(image,&Rec.RecordLength); + if(EOFBlob(image)) + break; + + Header.DataOffset=TellBlob(image)+Rec.RecordLength; + + switch(Rec.RecType) + { + case 0x0B: /* bitmap type 1 */ + BitmapHeader1.Width=ReadBlobLSBShort(image); + BitmapHeader1.Height=ReadBlobLSBShort(image); + if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + BitmapHeader1.Depth=ReadBlobLSBShort(image); + BitmapHeader1.HorzRes=ReadBlobLSBShort(image); + BitmapHeader1.VertRes=ReadBlobLSBShort(image); + + if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes) + { + image->units=PixelsPerCentimeterResolution; + image->x_resolution=BitmapHeader1.HorzRes/470.0; + image->y_resolution=BitmapHeader1.VertRes/470.0; + } + image->columns=BitmapHeader1.Width; + image->rows=BitmapHeader1.Height; + bpp=BitmapHeader1.Depth; + + goto UnpackRaster; + + case 0x0E: /*Color palette */ + WPG_Palette.StartIndex=ReadBlobLSBShort(image); + WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); + + image->colors=WPG_Palette.NumOfEntries; + if (!AcquireImageColormap(image,image->colors)) + goto NoMemory; + for (i=WPG_Palette.StartIndex; + i < (int)WPG_Palette.NumOfEntries; i++) + { + image->colormap[i].red=ScaleCharToQuantum((unsigned char) + ReadBlobByte(image)); + image->colormap[i].green=ScaleCharToQuantum((unsigned char) + ReadBlobByte(image)); + image->colormap[i].blue=ScaleCharToQuantum((unsigned char) + ReadBlobByte(image)); + } + break; + + case 0x11: /* Start PS l1 */ + if(Rec.RecordLength > 8) + image=ExtractPostscript(image,image_info, + TellBlob(image)+8, /* skip PS header in the wpg */ + (ssize_t) Rec.RecordLength-8,exception); + break; + + case 0x14: /* bitmap type 2 */ + BitmapHeader2.RotAngle=ReadBlobLSBShort(image); + BitmapHeader2.LowLeftX=ReadBlobLSBShort(image); + BitmapHeader2.LowLeftY=ReadBlobLSBShort(image); + BitmapHeader2.UpRightX=ReadBlobLSBShort(image); + BitmapHeader2.UpRightY=ReadBlobLSBShort(image); + BitmapHeader2.Width=ReadBlobLSBShort(image); + BitmapHeader2.Height=ReadBlobLSBShort(image); + if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + BitmapHeader2.Depth=ReadBlobLSBShort(image); + BitmapHeader2.HorzRes=ReadBlobLSBShort(image); + BitmapHeader2.VertRes=ReadBlobLSBShort(image); + + image->units=PixelsPerCentimeterResolution; + image->page.width=(unsigned int) + ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0); + image->page.height=(unsigned int) + ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0); + image->page.x=(int) (BitmapHeader2.LowLeftX/470.0); + image->page.y=(int) (BitmapHeader2.LowLeftX/470.0); + if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes) + { + image->x_resolution=BitmapHeader2.HorzRes/470.0; + image->y_resolution=BitmapHeader2.VertRes/470.0; + } + image->columns=BitmapHeader2.Width; + image->rows=BitmapHeader2.Height; + bpp=BitmapHeader2.Depth; + + UnpackRaster: + if ((image->colors == 0) && (bpp != 24)) + { + image->colors=one << bpp; + if (!AcquireImageColormap(image,image->colors)) + { + NoMemory: + ThrowReaderException(ResourceLimitError, + ""MemoryAllocationFailed""); + } + /* printf(""Load default colormap \n""); */ + for (i=0; (i < (int) image->colors) && (i < 256); i++) + { + image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red); + image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green); + image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue); + } + } + else + { + if (bpp < 24) + if ( (image->colors < (one << bpp)) && (bpp != 24) ) + image->colormap=(PixelPacket *) ResizeQuantumMemory( + image->colormap,(size_t) (one << bpp), + sizeof(*image->colormap)); + } + + if (bpp == 1) + { + if(image->colormap[0].red==0 && + image->colormap[0].green==0 && + image->colormap[0].blue==0 && + image->colormap[1].red==0 && + image->colormap[1].green==0 && + image->colormap[1].blue==0) + { /* fix crippled monochrome palette */ + image->colormap[1].red = + image->colormap[1].green = + image->colormap[1].blue = QuantumRange; + } + } + + if(UnpackWPGRaster(image,bpp) < 0) + /* The raster cannot be unpacked */ + { + DecompressionFailed: + ThrowReaderException(CoderError,""UnableToDecompressImage""); + } + + if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping) + { + /* flop command */ + if(BitmapHeader2.RotAngle & 0x8000) + { + Image + *flop_image; + + flop_image = FlopImage(image, exception); + if (flop_image != (Image *) NULL) { + DuplicateBlob(flop_image,image); + (void) RemoveLastImageFromList(&image); + AppendImageToList(&image,flop_image); + } + } + /* flip command */ + if(BitmapHeader2.RotAngle & 0x2000) + { + Image + *flip_image; + + flip_image = FlipImage(image, exception); + if (flip_image != (Image *) NULL) { + DuplicateBlob(flip_image,image); + (void) RemoveLastImageFromList(&image); + AppendImageToList(&image,flip_image); + } + } + + /* rotate command */ + if(BitmapHeader2.RotAngle & 0x0FFF) + { + Image + *rotate_image; + + rotate_image=RotateImage(image,(BitmapHeader2.RotAngle & + 0x0FFF), exception); + if (rotate_image != (Image *) NULL) { + DuplicateBlob(rotate_image,image); + (void) RemoveLastImageFromList(&image); + AppendImageToList(&image,rotate_image); + } + } + } + + /* Allocate next image structure. */ + AcquireNextImage(image_info,image); + image->depth=8; + if (image->next == (Image *) NULL) + goto Finish; + image=SyncNextImageInList(image); + image->columns=image->rows=0; + image->colors=0; + break; + + case 0x1B: /* Postscript l2 */ + if(Rec.RecordLength>0x3C) + image=ExtractPostscript(image,image_info, + TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */ + (ssize_t) Rec.RecordLength-0x3C,exception); + break; + } + } + break; + + case 2: /* WPG level 2 */ + (void) memset(CTM,0,sizeof(CTM)); + StartWPG.PosSizePrecision = 0; + while(!EOFBlob(image)) /* object parser loop */ + { + (void) SeekBlob(image,Header.DataOffset,SEEK_SET); + if(EOFBlob(image)) + break; + + Rec2.Class=(i=ReadBlobByte(image)); + if(i==EOF) + break; + Rec2.RecType=(i=ReadBlobByte(image)); + if(i==EOF) + break; + Rd_WP_DWORD(image,&Rec2.Extension); + Rd_WP_DWORD(image,&Rec2.RecordLength); + if(EOFBlob(image)) + break; + + Header.DataOffset=TellBlob(image)+Rec2.RecordLength; + + switch(Rec2.RecType) + { + case 1: + StartWPG.HorizontalUnits=ReadBlobLSBShort(image); + StartWPG.VerticalUnits=ReadBlobLSBShort(image); + StartWPG.PosSizePrecision=ReadBlobByte(image); + break; + case 0x0C: /* Color palette */ + WPG_Palette.StartIndex=ReadBlobLSBShort(image); + WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); + + image->colors=WPG_Palette.NumOfEntries; + if (AcquireImageColormap(image,image->colors) == MagickFalse) + ThrowReaderException(ResourceLimitError, + ""MemoryAllocationFailed""); + for (i=WPG_Palette.StartIndex; + i < (int)WPG_Palette.NumOfEntries; i++) + { + image->colormap[i].red=ScaleCharToQuantum((char) + ReadBlobByte(image)); + image->colormap[i].green=ScaleCharToQuantum((char) + ReadBlobByte(image)); + image->colormap[i].blue=ScaleCharToQuantum((char) + ReadBlobByte(image)); + (void) ReadBlobByte(image); /*Opacity??*/ + } + break; + case 0x0E: + Bitmap2Header1.Width=ReadBlobLSBShort(image); + Bitmap2Header1.Height=ReadBlobLSBShort(image); + if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + Bitmap2Header1.Depth=ReadBlobByte(image); + Bitmap2Header1.Compression=ReadBlobByte(image); + + if(Bitmap2Header1.Compression > 1) + continue; /*Unknown compression method */ + switch(Bitmap2Header1.Depth) + { + case 1: + bpp=1; + break; + case 2: + bpp=2; + break; + case 3: + bpp=4; + break; + case 4: + bpp=8; + break; + case 8: + bpp=24; + break; + default: + continue; /*Ignore raster with unknown depth*/ + } + image->columns=Bitmap2Header1.Width; + image->rows=Bitmap2Header1.Height; + + if ((image->colors == 0) && (bpp != 24)) + { + size_t + one; + + one=1; + image->colors=one << bpp; + if (!AcquireImageColormap(image,image->colors)) + goto NoMemory; + } + else + { + if(bpp < 24) + if( image->colors<(one << bpp) && bpp!=24 ) + image->colormap=(PixelPacket *) ResizeQuantumMemory( + image->colormap,(size_t) (one << bpp), + sizeof(*image->colormap)); + } + + + switch(Bitmap2Header1.Compression) + { + case 0: /*Uncompressed raster*/ + { + ldblk=(ssize_t) ((bpp*image->columns+7)/8); + BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) + ldblk,sizeof(*BImgBuff)); + if (BImgBuff == (unsigned char *) NULL) + goto NoMemory; + + for(i=0; i< (ssize_t) image->rows; i++) + { + (void) ReadBlob(image,ldblk,BImgBuff); + InsertRow(BImgBuff,i,image,bpp); + } + + if(BImgBuff) + BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);; + break; + } + case 1: /*RLE for WPG2 */ + { + if( UnpackWPG2Raster(image,bpp) < 0) + goto DecompressionFailed; + break; + } + } + + if(CTM[0][0]<0 && !image_info->ping) + { /*?? RotAngle=360-RotAngle;*/ + Image + *flop_image; + + flop_image = FlopImage(image, exception); + if (flop_image != (Image *) NULL) { + DuplicateBlob(flop_image,image); + (void) RemoveLastImageFromList(&image); + AppendImageToList(&image,flop_image); + } + /* Try to change CTM according to Flip - I am not sure, must be checked. + Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0; + Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0; + Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll); + Tx(1,2)=0; Tx(2,2)=1; */ + } + if(CTM[1][1]<0 && !image_info->ping) + { /*?? RotAngle=360-RotAngle;*/ + Image + *flip_image; + + flip_image = FlipImage(image, exception); + if (flip_image != (Image *) NULL) { + DuplicateBlob(flip_image,image); + (void) RemoveLastImageFromList(&image); + AppendImageToList(&image,flip_image); + } + /* Try to change CTM according to Flip - I am not sure, must be checked. + float_matrix Tx(3,3); + Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0; + Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0; + Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll); + Tx(2,2)=1; */ + } + + + /* Allocate next image structure. */ + AcquireNextImage(image_info,image); + image->depth=8; + if (image->next == (Image *) NULL) + goto Finish; + image=SyncNextImageInList(image); + image->columns=image->rows=1; + image->colors=0; + break; + + case 0x12: /* Postscript WPG2*/ + i=ReadBlobLSBShort(image); + if(Rec2.RecordLength > (unsigned int) i) + image=ExtractPostscript(image,image_info, + TellBlob(image)+i, /*skip PS header in the wpg2*/ + (ssize_t) (Rec2.RecordLength-i-2),exception); + break; + + case 0x1B: /*bitmap rectangle*/ + WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM); + (void) WPG2Flags; + break; + } + } + + break; + + default: + { + ThrowReaderException(CoderError,""DataEncodingSchemeIsNotSupported""); + } + } + + Finish: + (void) CloseBlob(image); + + { + Image + *p; + + ssize_t + scene=0; + + /* + Rewind list, removing any empty images while rewinding. + */ + p=image; + image=NULL; + while (p != (Image *) NULL) + { + Image *tmp=p; + if ((p->rows == 0) || (p->columns == 0)) { + p=p->previous; + DeleteImageFromList(&tmp); + } else { + image=p; + p=p->previous; + } + } + /* + Fix scene numbers. + */ + for (p=image; p != (Image *) NULL; p=p->next) + p->scene=(size_t) scene++; + } + if (image == (Image *) NULL) + ThrowReaderException(CorruptImageError, + ""ImageFileDoesNotContainAnyImageData""); + return(image); +} +",1,"static Image *ReadWPGImage(const ImageInfo *image_info, + ExceptionInfo *exception) +{ + typedef struct + { + size_t FileId; + MagickOffsetType DataOffset; + unsigned int ProductType; + unsigned int FileType; + unsigned char MajorVersion; + unsigned char MinorVersion; + unsigned int EncryptKey; + unsigned int Reserved; + } WPGHeader; + + typedef struct + { + unsigned char RecType; + size_t RecordLength; + } WPGRecord; + + typedef struct + { + unsigned char Class; + unsigned char RecType; + size_t Extension; + size_t RecordLength; + } WPG2Record; + + typedef struct + { + unsigned HorizontalUnits; + unsigned VerticalUnits; + unsigned char PosSizePrecision; + } WPG2Start; + + typedef struct + { + unsigned int Width; + unsigned int Height; + unsigned int Depth; + unsigned int HorzRes; + unsigned int VertRes; + } WPGBitmapType1; + + typedef struct + { + unsigned int Width; + unsigned int Height; + unsigned char Depth; + unsigned char Compression; + } WPG2BitmapType1; + + typedef struct + { + unsigned int RotAngle; + unsigned int LowLeftX; + unsigned int LowLeftY; + unsigned int UpRightX; + unsigned int UpRightY; + unsigned int Width; + unsigned int Height; + unsigned int Depth; + unsigned int HorzRes; + unsigned int VertRes; + } WPGBitmapType2; + + typedef struct + { + unsigned int StartIndex; + unsigned int NumOfEntries; + } WPGColorMapRec; + + /* + typedef struct { + size_t PS_unknown1; + unsigned int PS_unknown2; + unsigned int PS_unknown3; + } WPGPSl1Record; + */ + + Image + *image; + + unsigned int + status; + + WPGHeader + Header; + + WPGRecord + Rec; + + WPG2Record + Rec2; + + WPG2Start StartWPG; + + WPGBitmapType1 + BitmapHeader1; + + WPG2BitmapType1 + Bitmap2Header1; + + WPGBitmapType2 + BitmapHeader2; + + WPGColorMapRec + WPG_Palette; + + int + i, + bpp, + WPG2Flags; + + ssize_t + ldblk; + + size_t + one; + + unsigned char + *BImgBuff; + + tCTM CTM; /*current transform matrix*/ + + /* + Open image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickSignature); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickSignature); + one=1; + image=AcquireImage(image_info); + image->depth=8; + status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); + if (status == MagickFalse) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + /* + Read WPG image. + */ + Header.FileId=ReadBlobLSBLong(image); + Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image); + Header.ProductType=ReadBlobLSBShort(image); + Header.FileType=ReadBlobLSBShort(image); + Header.MajorVersion=ReadBlobByte(image); + Header.MinorVersion=ReadBlobByte(image); + Header.EncryptKey=ReadBlobLSBShort(image); + Header.Reserved=ReadBlobLSBShort(image); + + if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + if (Header.EncryptKey!=0) + ThrowReaderException(CoderError,""EncryptedWPGImageFileNotSupported""); + + image->columns = 1; + image->rows = 1; + image->colors = 0; + bpp=0; + BitmapHeader2.RotAngle=0; + + switch(Header.FileType) + { + case 1: /* WPG level 1 */ + while(!EOFBlob(image)) /* object parser loop */ + { + (void) SeekBlob(image,Header.DataOffset,SEEK_SET); + if(EOFBlob(image)) + break; + + Rec.RecType=(i=ReadBlobByte(image)); + if(i==EOF) + break; + Rd_WP_DWORD(image,&Rec.RecordLength); + if(EOFBlob(image)) + break; + + Header.DataOffset=TellBlob(image)+Rec.RecordLength; + + switch(Rec.RecType) + { + case 0x0B: /* bitmap type 1 */ + BitmapHeader1.Width=ReadBlobLSBShort(image); + BitmapHeader1.Height=ReadBlobLSBShort(image); + if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + BitmapHeader1.Depth=ReadBlobLSBShort(image); + BitmapHeader1.HorzRes=ReadBlobLSBShort(image); + BitmapHeader1.VertRes=ReadBlobLSBShort(image); + + if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes) + { + image->units=PixelsPerCentimeterResolution; + image->x_resolution=BitmapHeader1.HorzRes/470.0; + image->y_resolution=BitmapHeader1.VertRes/470.0; + } + image->columns=BitmapHeader1.Width; + image->rows=BitmapHeader1.Height; + bpp=BitmapHeader1.Depth; + + goto UnpackRaster; + + case 0x0E: /*Color palette */ + WPG_Palette.StartIndex=ReadBlobLSBShort(image); + WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); + + image->colors=WPG_Palette.NumOfEntries; + if (!AcquireImageColormap(image,image->colors)) + goto NoMemory; + for (i=WPG_Palette.StartIndex; + i < (int)WPG_Palette.NumOfEntries; i++) + { + image->colormap[i].red=ScaleCharToQuantum((unsigned char) + ReadBlobByte(image)); + image->colormap[i].green=ScaleCharToQuantum((unsigned char) + ReadBlobByte(image)); + image->colormap[i].blue=ScaleCharToQuantum((unsigned char) + ReadBlobByte(image)); + } + break; + + case 0x11: /* Start PS l1 */ + if(Rec.RecordLength > 8) + image=ExtractPostscript(image,image_info, + TellBlob(image)+8, /* skip PS header in the wpg */ + (ssize_t) Rec.RecordLength-8,exception); + break; + + case 0x14: /* bitmap type 2 */ + BitmapHeader2.RotAngle=ReadBlobLSBShort(image); + BitmapHeader2.LowLeftX=ReadBlobLSBShort(image); + BitmapHeader2.LowLeftY=ReadBlobLSBShort(image); + BitmapHeader2.UpRightX=ReadBlobLSBShort(image); + BitmapHeader2.UpRightY=ReadBlobLSBShort(image); + BitmapHeader2.Width=ReadBlobLSBShort(image); + BitmapHeader2.Height=ReadBlobLSBShort(image); + if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + BitmapHeader2.Depth=ReadBlobLSBShort(image); + BitmapHeader2.HorzRes=ReadBlobLSBShort(image); + BitmapHeader2.VertRes=ReadBlobLSBShort(image); + + image->units=PixelsPerCentimeterResolution; + image->page.width=(unsigned int) + ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0); + image->page.height=(unsigned int) + ((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0); + image->page.x=(int) (BitmapHeader2.LowLeftX/470.0); + image->page.y=(int) (BitmapHeader2.LowLeftX/470.0); + if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes) + { + image->x_resolution=BitmapHeader2.HorzRes/470.0; + image->y_resolution=BitmapHeader2.VertRes/470.0; + } + image->columns=BitmapHeader2.Width; + image->rows=BitmapHeader2.Height; + bpp=BitmapHeader2.Depth; + + UnpackRaster: + if ((image->colors == 0) && (bpp != 24)) + { + image->colors=one << bpp; + if (!AcquireImageColormap(image,image->colors)) + { + NoMemory: + ThrowReaderException(ResourceLimitError, + ""MemoryAllocationFailed""); + } + /* printf(""Load default colormap \n""); */ + for (i=0; (i < (int) image->colors) && (i < 256); i++) + { + image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red); + image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green); + image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue); + } + } + else + { + if (bpp < 24) + if ( (image->colors < (one << bpp)) && (bpp != 24) ) + image->colormap=(PixelPacket *) ResizeQuantumMemory( + image->colormap,(size_t) (one << bpp), + sizeof(*image->colormap)); + } + + if (bpp == 1) + { + if(image->colormap[0].red==0 && + image->colormap[0].green==0 && + image->colormap[0].blue==0 && + image->colormap[1].red==0 && + image->colormap[1].green==0 && + image->colormap[1].blue==0) + { /* fix crippled monochrome palette */ + image->colormap[1].red = + image->colormap[1].green = + image->colormap[1].blue = QuantumRange; + } + } + + if(UnpackWPGRaster(image,bpp) < 0) + /* The raster cannot be unpacked */ + { + DecompressionFailed: + ThrowReaderException(CoderError,""UnableToDecompressImage""); + } + + if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping) + { + /* flop command */ + if(BitmapHeader2.RotAngle & 0x8000) + { + Image + *flop_image; + + flop_image = FlopImage(image, exception); + if (flop_image != (Image *) NULL) { + DuplicateBlob(flop_image,image); + (void) RemoveLastImageFromList(&image); + AppendImageToList(&image,flop_image); + } + } + /* flip command */ + if(BitmapHeader2.RotAngle & 0x2000) + { + Image + *flip_image; + + flip_image = FlipImage(image, exception); + if (flip_image != (Image *) NULL) { + DuplicateBlob(flip_image,image); + (void) RemoveLastImageFromList(&image); + AppendImageToList(&image,flip_image); + } + } + + /* rotate command */ + if(BitmapHeader2.RotAngle & 0x0FFF) + { + Image + *rotate_image; + + rotate_image=RotateImage(image,(BitmapHeader2.RotAngle & + 0x0FFF), exception); + if (rotate_image != (Image *) NULL) { + DuplicateBlob(rotate_image,image); + (void) RemoveLastImageFromList(&image); + AppendImageToList(&image,rotate_image); + } + } + } + + /* Allocate next image structure. */ + AcquireNextImage(image_info,image); + image->depth=8; + if (image->next == (Image *) NULL) + goto Finish; + image=SyncNextImageInList(image); + image->columns=image->rows=0; + image->colors=0; + break; + + case 0x1B: /* Postscript l2 */ + if(Rec.RecordLength>0x3C) + image=ExtractPostscript(image,image_info, + TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */ + (ssize_t) Rec.RecordLength-0x3C,exception); + break; + } + } + break; + + case 2: /* WPG level 2 */ + (void) memset(CTM,0,sizeof(CTM)); + StartWPG.PosSizePrecision = 0; + while(!EOFBlob(image)) /* object parser loop */ + { + (void) SeekBlob(image,Header.DataOffset,SEEK_SET); + if(EOFBlob(image)) + break; + + Rec2.Class=(i=ReadBlobByte(image)); + if(i==EOF) + break; + Rec2.RecType=(i=ReadBlobByte(image)); + if(i==EOF) + break; + Rd_WP_DWORD(image,&Rec2.Extension); + Rd_WP_DWORD(image,&Rec2.RecordLength); + if(EOFBlob(image)) + break; + + Header.DataOffset=TellBlob(image)+Rec2.RecordLength; + + switch(Rec2.RecType) + { + case 1: + StartWPG.HorizontalUnits=ReadBlobLSBShort(image); + StartWPG.VerticalUnits=ReadBlobLSBShort(image); + StartWPG.PosSizePrecision=ReadBlobByte(image); + break; + case 0x0C: /* Color palette */ + WPG_Palette.StartIndex=ReadBlobLSBShort(image); + WPG_Palette.NumOfEntries=ReadBlobLSBShort(image); + + image->colors=WPG_Palette.NumOfEntries; + if (AcquireImageColormap(image,image->colors) == MagickFalse) + ThrowReaderException(ResourceLimitError, + ""MemoryAllocationFailed""); + for (i=WPG_Palette.StartIndex; + i < (int)WPG_Palette.NumOfEntries; i++) + { + image->colormap[i].red=ScaleCharToQuantum((char) + ReadBlobByte(image)); + image->colormap[i].green=ScaleCharToQuantum((char) + ReadBlobByte(image)); + image->colormap[i].blue=ScaleCharToQuantum((char) + ReadBlobByte(image)); + (void) ReadBlobByte(image); /*Opacity??*/ + } + break; + case 0x0E: + Bitmap2Header1.Width=ReadBlobLSBShort(image); + Bitmap2Header1.Height=ReadBlobLSBShort(image); + if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + Bitmap2Header1.Depth=ReadBlobByte(image); + Bitmap2Header1.Compression=ReadBlobByte(image); + + if(Bitmap2Header1.Compression > 1) + continue; /*Unknown compression method */ + switch(Bitmap2Header1.Depth) + { + case 1: + bpp=1; + break; + case 2: + bpp=2; + break; + case 3: + bpp=4; + break; + case 4: + bpp=8; + break; + case 8: + bpp=24; + break; + default: + continue; /*Ignore raster with unknown depth*/ + } + image->columns=Bitmap2Header1.Width; + image->rows=Bitmap2Header1.Height; + + if ((image->colors == 0) && (bpp != 24)) + { + size_t + one; + + one=1; + image->colors=one << bpp; + if (!AcquireImageColormap(image,image->colors)) + goto NoMemory; + } + else + { + if(bpp < 24) + if( image->colors<(one << bpp) && bpp!=24 ) + image->colormap=(PixelPacket *) ResizeQuantumMemory( + image->colormap,(size_t) (one << bpp), + sizeof(*image->colormap)); + } + + + switch(Bitmap2Header1.Compression) + { + case 0: /*Uncompressed raster*/ + { + ldblk=(ssize_t) ((bpp*image->columns+7)/8); + BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t) + ldblk,sizeof(*BImgBuff)); + if (BImgBuff == (unsigned char *) NULL) + goto NoMemory; + + for(i=0; i< (ssize_t) image->rows; i++) + { + (void) ReadBlob(image,ldblk,BImgBuff); + InsertRow(BImgBuff,i,image,bpp); + } + + if(BImgBuff) + BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);; + break; + } + case 1: /*RLE for WPG2 */ + { + if( UnpackWPG2Raster(image,bpp) < 0) + goto DecompressionFailed; + break; + } + } + + if(CTM[0][0]<0 && !image_info->ping) + { /*?? RotAngle=360-RotAngle;*/ + Image + *flop_image; + + flop_image = FlopImage(image, exception); + if (flop_image != (Image *) NULL) { + DuplicateBlob(flop_image,image); + (void) RemoveLastImageFromList(&image); + AppendImageToList(&image,flop_image); + } + /* Try to change CTM according to Flip - I am not sure, must be checked. + Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0; + Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0; + Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll); + Tx(1,2)=0; Tx(2,2)=1; */ + } + if(CTM[1][1]<0 && !image_info->ping) + { /*?? RotAngle=360-RotAngle;*/ + Image + *flip_image; + + flip_image = FlipImage(image, exception); + if (flip_image != (Image *) NULL) { + DuplicateBlob(flip_image,image); + (void) RemoveLastImageFromList(&image); + AppendImageToList(&image,flip_image); + } + /* Try to change CTM according to Flip - I am not sure, must be checked. + float_matrix Tx(3,3); + Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0; + Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0; + Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll); + Tx(2,2)=1; */ + } + + + /* Allocate next image structure. */ + AcquireNextImage(image_info,image); + image->depth=8; + if (image->next == (Image *) NULL) + goto Finish; + image=SyncNextImageInList(image); + image->columns=image->rows=1; + image->colors=0; + break; + + case 0x12: /* Postscript WPG2*/ + i=ReadBlobLSBShort(image); + if(Rec2.RecordLength > (unsigned int) i) + image=ExtractPostscript(image,image_info, + TellBlob(image)+i, /*skip PS header in the wpg2*/ + (ssize_t) (Rec2.RecordLength-i-2),exception); + break; + + case 0x1B: /*bitmap rectangle*/ + WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM); + (void) WPG2Flags; + break; + } + } + + break; + + default: + { + ThrowReaderException(CoderError,""DataEncodingSchemeIsNotSupported""); + } + } + status=SetImageExtent(image,image->columns,image->rows); + if (status == MagickFalse) + { + InheritException(exception,&image->exception); + return(DestroyImageList(image)); + } + + Finish: + (void) CloseBlob(image); + + { + Image + *p; + + ssize_t + scene=0; + + /* + Rewind list, removing any empty images while rewinding. + */ + p=image; + image=NULL; + while (p != (Image *) NULL) + { + Image *tmp=p; + if ((p->rows == 0) || (p->columns == 0)) { + p=p->previous; + DeleteImageFromList(&tmp); + } else { + image=p; + p=p->previous; + } + } + /* + Fix scene numbers. + */ + for (p=image; p != (Image *) NULL; p=p->next) + p->scene=(size_t) scene++; + } + if (image == (Image *) NULL) + ThrowReaderException(CorruptImageError, + ""ImageFileDoesNotContainAnyImageData""); + return(image); +} +","@@ -1413,6 +1413,12 @@ static Image *ReadWPGImage(const ImageInfo *image_info, + ThrowReaderException(CoderError,""DataEncodingSchemeIsNotSupported""); + } + } ++ status=SetImageExtent(image,image->columns,image->rows); ++ if (status == MagickFalse) ++ { ++ InheritException(exception,&image->exception); ++ return(DestroyImageList(image)); ++ } + + Finish: + (void) CloseBlob(image);",4653,4984,6144 +518,"qtdemux_video_caps (GstQTDemux * qtdemux, QtDemuxStream * stream, + guint32 fourcc, const guint8 * stsd_data, gchar ** codec_name) +{ + GstCaps *caps; + const GstStructure *s; + const gchar *name; + + switch (fourcc) { + case GST_MAKE_FOURCC ('p', 'n', 'g', ' '): + _codec (""PNG still images""); + caps = gst_caps_new_simple (""image/png"", NULL); + break; + case GST_MAKE_FOURCC ('j', 'p', 'e', 'g'): + _codec (""JPEG still images""); + caps = gst_caps_new_simple (""image/jpeg"", NULL); + break; + case GST_MAKE_FOURCC ('m', 'j', 'p', 'a'): + case GST_MAKE_FOURCC ('A', 'V', 'D', 'J'): + case GST_MAKE_FOURCC ('M', 'J', 'P', 'G'): + _codec (""Motion-JPEG""); + caps = gst_caps_new_simple (""image/jpeg"", NULL); + break; + case GST_MAKE_FOURCC ('m', 'j', 'p', 'b'): + _codec (""Motion-JPEG format B""); + caps = gst_caps_new_simple (""video/x-mjpeg-b"", NULL); + break; + case GST_MAKE_FOURCC ('m', 'j', 'p', '2'): + _codec (""JPEG-2000""); + /* override to what it should be according to spec, avoid palette_data */ + stream->bits_per_sample = 24; + caps = gst_caps_new_simple (""image/x-j2c"", ""fields"", G_TYPE_INT, 1, NULL); + break; + case GST_MAKE_FOURCC ('S', 'V', 'Q', '3'): + _codec (""Sorensen video v.3""); + caps = gst_caps_new_simple (""video/x-svq"", + ""svqversion"", G_TYPE_INT, 3, NULL); + break; + case GST_MAKE_FOURCC ('s', 'v', 'q', 'i'): + case GST_MAKE_FOURCC ('S', 'V', 'Q', '1'): + _codec (""Sorensen video v.1""); + caps = gst_caps_new_simple (""video/x-svq"", + ""svqversion"", G_TYPE_INT, 1, NULL); + break; + case GST_MAKE_FOURCC ('r', 'a', 'w', ' '): + { + guint16 bps; + + _codec (""Raw RGB video""); + bps = QT_UINT16 (stsd_data + 98); + /* set common stuff */ + caps = gst_caps_new_simple (""video/x-raw-rgb"", + ""endianness"", G_TYPE_INT, G_BYTE_ORDER, ""depth"", G_TYPE_INT, bps, + NULL); + + switch (bps) { + case 15: + gst_caps_set_simple (caps, + ""bpp"", G_TYPE_INT, 16, + ""endianness"", G_TYPE_INT, G_BIG_ENDIAN, + ""red_mask"", G_TYPE_INT, 0x7c00, + ""green_mask"", G_TYPE_INT, 0x03e0, + ""blue_mask"", G_TYPE_INT, 0x001f, NULL); + break; + case 16: + gst_caps_set_simple (caps, + ""bpp"", G_TYPE_INT, 16, + ""endianness"", G_TYPE_INT, G_BIG_ENDIAN, + ""red_mask"", G_TYPE_INT, 0xf800, + ""green_mask"", G_TYPE_INT, 0x07e0, + ""blue_mask"", G_TYPE_INT, 0x001f, NULL); + break; + case 24: + gst_caps_set_simple (caps, + ""bpp"", G_TYPE_INT, 24, + ""endianness"", G_TYPE_INT, G_BIG_ENDIAN, + ""red_mask"", G_TYPE_INT, 0xff0000, + ""green_mask"", G_TYPE_INT, 0x00ff00, + ""blue_mask"", G_TYPE_INT, 0x0000ff, NULL); + break; + case 32: + gst_caps_set_simple (caps, + ""bpp"", G_TYPE_INT, 32, + ""endianness"", G_TYPE_INT, G_BIG_ENDIAN, + ""alpha_mask"", G_TYPE_INT, 0xff000000, + ""red_mask"", G_TYPE_INT, 0x00ff0000, + ""green_mask"", G_TYPE_INT, 0x0000ff00, + ""blue_mask"", G_TYPE_INT, 0x000000ff, NULL); + break; + default: + /* unknown */ + break; + } + break; + } + case GST_MAKE_FOURCC ('y', 'v', '1', '2'): + _codec (""Raw planar YUV 4:2:0""); + caps = gst_caps_new_simple (""video/x-raw-yuv"", + ""format"", GST_TYPE_FOURCC, GST_MAKE_FOURCC ('I', '4', '2', '0'), + NULL); + break; + case GST_MAKE_FOURCC ('y', 'u', 'v', '2'): + case GST_MAKE_FOURCC ('Y', 'u', 'v', '2'): + _codec (""Raw packed YUV 4:2:2""); + caps = gst_caps_new_simple (""video/x-raw-yuv"", + ""format"", GST_TYPE_FOURCC, GST_MAKE_FOURCC ('Y', 'U', 'Y', '2'), + NULL); + break; + case GST_MAKE_FOURCC ('2', 'v', 'u', 'y'): + _codec (""Raw packed YUV 4:2:0""); + caps = gst_caps_new_simple (""video/x-raw-yuv"", + ""format"", GST_TYPE_FOURCC, GST_MAKE_FOURCC ('U', 'Y', 'V', 'Y'), + NULL); + break; + case GST_MAKE_FOURCC ('m', 'p', 'e', 'g'): + case GST_MAKE_FOURCC ('m', 'p', 'g', '1'): + _codec (""MPEG-1 video""); + caps = gst_caps_new_simple (""video/mpeg"", ""mpegversion"", G_TYPE_INT, 1, + ""systemstream"", G_TYPE_BOOLEAN, FALSE, NULL); + break; + case GST_MAKE_FOURCC ('h', 'd', 'v', '1'): // HDV 720p30 + case GST_MAKE_FOURCC ('h', 'd', 'v', '2'): // HDV 1080i60 + case GST_MAKE_FOURCC ('h', 'd', 'v', '3'): // HDV 1080i50 + case GST_MAKE_FOURCC ('h', 'd', 'v', '5'): // HDV 720p25 + case GST_MAKE_FOURCC ('h', 'd', 'v', '6'): // HDV 1080i60 + case GST_MAKE_FOURCC ('m', 'x', '5', 'n'): // MPEG2 IMX NTSC 525/60 50mb/s produced by FCP + case GST_MAKE_FOURCC ('m', 'x', '5', 'p'): // MPEG2 IMX PAL 625/60 50mb/s produced by FCP + case GST_MAKE_FOURCC ('m', 'x', '4', 'n'): // MPEG2 IMX NTSC 525/60 40mb/s produced by FCP + case GST_MAKE_FOURCC ('m', 'x', '4', 'p'): // MPEG2 IMX PAL 625/60 40mb/s produced by FCP + case GST_MAKE_FOURCC ('m', 'x', '3', 'n'): // MPEG2 IMX NTSC 525/60 30mb/s produced by FCP + case GST_MAKE_FOURCC ('m', 'x', '3', 'p'): // MPEG2 IMX PAL 625/50 30mb/s produced by FCP + case GST_MAKE_FOURCC ('x', 'd', 'v', '2'): // XDCAM HD 1080i60 + case GST_MAKE_FOURCC ('A', 'V', 'm', 'p'): // AVID IMX PAL + case GST_MAKE_FOURCC ('m', 'p', 'g', '2'): // AVID IMX PAL + _codec (""MPEG-2 video""); + caps = gst_caps_new_simple (""video/mpeg"", ""mpegversion"", G_TYPE_INT, 2, + ""systemstream"", G_TYPE_BOOLEAN, FALSE, NULL); + break; + case GST_MAKE_FOURCC ('g', 'i', 'f', ' '): + _codec (""GIF still images""); + caps = gst_caps_new_simple (""image/gif"", NULL); + break; + case GST_MAKE_FOURCC ('h', '2', '6', '3'): + case GST_MAKE_FOURCC ('H', '2', '6', '3'): + case GST_MAKE_FOURCC ('s', '2', '6', '3'): + case GST_MAKE_FOURCC ('U', '2', '6', '3'): + _codec (""H.263""); + /* ffmpeg uses the height/width props, don't know why */ + caps = gst_caps_new_simple (""video/x-h263"", NULL); + break; + case GST_MAKE_FOURCC ('m', 'p', '4', 'v'): + _codec (""MPEG-4 video""); + caps = gst_caps_new_simple (""video/mpeg"", ""mpegversion"", G_TYPE_INT, 4, + ""systemstream"", G_TYPE_BOOLEAN, FALSE, NULL); + break; + case GST_MAKE_FOURCC ('3', 'i', 'v', 'd'): + case GST_MAKE_FOURCC ('3', 'I', 'V', 'D'): + _codec (""Microsoft MPEG-4 4.3""); /* FIXME? */ + caps = gst_caps_new_simple (""video/x-msmpeg"", + ""msmpegversion"", G_TYPE_INT, 43, NULL); + break; + case GST_MAKE_FOURCC ('3', 'I', 'V', '1'): + case GST_MAKE_FOURCC ('3', 'I', 'V', '2'): + _codec (""3ivX video""); + caps = gst_caps_new_simple (""video/x-3ivx"", NULL); + break; + case GST_MAKE_FOURCC ('D', 'I', 'V', '3'): + _codec (""DivX 3""); + caps = gst_caps_new_simple (""video/x-divx"", + ""divxversion"", G_TYPE_INT, 3, NULL); + break; + case GST_MAKE_FOURCC ('D', 'I', 'V', 'X'): + case GST_MAKE_FOURCC ('d', 'i', 'v', 'x'): + _codec (""DivX 4""); + caps = gst_caps_new_simple (""video/x-divx"", + ""divxversion"", G_TYPE_INT, 4, NULL); + break; + case GST_MAKE_FOURCC ('D', 'X', '5', '0'): + _codec (""DivX 5""); + caps = gst_caps_new_simple (""video/x-divx"", + ""divxversion"", G_TYPE_INT, 5, NULL); + break; + case GST_MAKE_FOURCC ('X', 'V', 'I', 'D'): + case GST_MAKE_FOURCC ('x', 'v', 'i', 'd'): + _codec (""XVID MPEG-4""); + caps = gst_caps_new_simple (""video/x-xvid"", NULL); + break; + + case GST_MAKE_FOURCC ('F', 'M', 'P', '4'): + case GST_MAKE_FOURCC ('U', 'M', 'P', '4'): + caps = gst_caps_new_simple (""video/mpeg"", + ""mpegversion"", G_TYPE_INT, 4, NULL); + if (codec_name) + *codec_name = g_strdup (""FFmpeg MPEG-4""); + break; + + case GST_MAKE_FOURCC ('c', 'v', 'i', 'd'): + _codec (""Cinepak""); + caps = gst_caps_new_simple (""video/x-cinepak"", NULL); + break; + case GST_MAKE_FOURCC ('q', 'd', 'r', 'w'): + _codec (""Apple QuickDraw""); + caps = gst_caps_new_simple (""video/x-qdrw"", NULL); + break; + case GST_MAKE_FOURCC ('r', 'p', 'z', 'a'): + _codec (""Apple video""); + caps = gst_caps_new_simple (""video/x-apple-video"", NULL); + break; + case GST_MAKE_FOURCC ('a', 'v', 'c', '1'): + _codec (""H.264 / AVC""); + caps = gst_caps_new_simple (""video/x-h264"", NULL); + break; + case GST_MAKE_FOURCC ('r', 'l', 'e', ' '): + _codec (""Run-length encoding""); + caps = gst_caps_new_simple (""video/x-rle"", + ""layout"", G_TYPE_STRING, ""quicktime"", NULL); + break; + case GST_MAKE_FOURCC ('i', 'v', '3', '2'): + _codec (""Indeo Video 3""); + caps = gst_caps_new_simple (""video/x-indeo"", + ""indeoversion"", G_TYPE_INT, 3, NULL); + break; + case GST_MAKE_FOURCC ('I', 'V', '4', '1'): + case GST_MAKE_FOURCC ('i', 'v', '4', '1'): + _codec (""Intel Video 4""); + caps = gst_caps_new_simple (""video/x-indeo"", + ""indeoversion"", G_TYPE_INT, 4, NULL); + break; + case GST_MAKE_FOURCC ('d', 'v', 'c', 'p'): + case GST_MAKE_FOURCC ('d', 'v', 'c', ' '): + case GST_MAKE_FOURCC ('d', 'v', 's', 'd'): + case GST_MAKE_FOURCC ('D', 'V', 'S', 'D'): + case GST_MAKE_FOURCC ('d', 'v', 'c', 's'): + case GST_MAKE_FOURCC ('D', 'V', 'C', 'S'): + case GST_MAKE_FOURCC ('d', 'v', '2', '5'): + case GST_MAKE_FOURCC ('d', 'v', 'p', 'p'): + _codec (""DV Video""); + caps = gst_caps_new_simple (""video/x-dv"", ""dvversion"", G_TYPE_INT, 25, + ""systemstream"", G_TYPE_BOOLEAN, FALSE, NULL); + break; + case GST_MAKE_FOURCC ('d', 'v', '5', 'n'): //DVCPRO50 NTSC + case GST_MAKE_FOURCC ('d', 'v', '5', 'p'): //DVCPRO50 PAL + _codec (""DVCPro50 Video""); + caps = gst_caps_new_simple (""video/x-dv"", ""dvversion"", G_TYPE_INT, 50, + ""systemstream"", G_TYPE_BOOLEAN, FALSE, NULL); + break; + case GST_MAKE_FOURCC ('d', 'v', 'h', '5'): //DVCPRO HD 50i produced by FCP + case GST_MAKE_FOURCC ('d', 'v', 'h', '6'): //DVCPRO HD 60i produced by FCP + _codec (""DVCProHD Video""); + caps = gst_caps_new_simple (""video/x-dv"", ""dvversion"", G_TYPE_INT, 100, + ""systemstream"", G_TYPE_BOOLEAN, FALSE, NULL); + break; + case GST_MAKE_FOURCC ('s', 'm', 'c', ' '): + _codec (""Apple Graphics (SMC)""); + caps = gst_caps_new_simple (""video/x-smc"", NULL); + break; + case GST_MAKE_FOURCC ('V', 'P', '3', '1'): + _codec (""VP3""); + caps = gst_caps_new_simple (""video/x-vp3"", NULL); + break; + case GST_MAKE_FOURCC ('X', 'i', 'T', 'h'): + _codec (""Theora""); + caps = gst_caps_new_simple (""video/x-theora"", NULL); + /* theora uses one byte of padding in the data stream because it does not + * allow 0 sized packets while theora does */ + stream->padding = 1; + break; + case GST_MAKE_FOURCC ('d', 'r', 'a', 'c'): + _codec (""Dirac""); + caps = gst_caps_new_simple (""video/x-dirac"", NULL); + break; + case GST_MAKE_FOURCC ('t', 'i', 'f', 'f'): + _codec (""TIFF still images""); + caps = gst_caps_new_simple (""image/tiff"", NULL); + break; + case GST_MAKE_FOURCC ('k', 'p', 'c', 'd'): + default: + { + char *s; + + s = g_strdup_printf (""video/x-gst-fourcc-%"" GST_FOURCC_FORMAT, + GST_FOURCC_ARGS (fourcc)); + caps = gst_caps_new_simple (s, NULL); + break; + } + } + + /* enable clipping for raw video streams */ + s = gst_caps_get_structure (caps, 0); + name = gst_structure_get_name (s); + if (g_str_has_prefix (name, ""video/x-raw-"")) { + stream->need_clip = TRUE; + } + return caps; +} +",0,"qtdemux_video_caps (GstQTDemux * qtdemux, QtDemuxStream * stream, + guint32 fourcc, const guint8 * stsd_data, gchar ** codec_name) +{ + GstCaps *caps; + const GstStructure *s; + const gchar *name; + + switch (fourcc) { + case GST_MAKE_FOURCC ('p', 'n', 'g', ' '): + _codec (""PNG still images""); + caps = gst_caps_new_simple (""image/png"", NULL); + break; + case GST_MAKE_FOURCC ('j', 'p', 'e', 'g'): + _codec (""JPEG still images""); + caps = gst_caps_new_simple (""image/jpeg"", NULL); + break; + case GST_MAKE_FOURCC ('m', 'j', 'p', 'a'): + case GST_MAKE_FOURCC ('A', 'V', 'D', 'J'): + case GST_MAKE_FOURCC ('M', 'J', 'P', 'G'): + _codec (""Motion-JPEG""); + caps = gst_caps_new_simple (""image/jpeg"", NULL); + break; + case GST_MAKE_FOURCC ('m', 'j', 'p', 'b'): + _codec (""Motion-JPEG format B""); + caps = gst_caps_new_simple (""video/x-mjpeg-b"", NULL); + break; + case GST_MAKE_FOURCC ('m', 'j', 'p', '2'): + _codec (""JPEG-2000""); + /* override to what it should be according to spec, avoid palette_data */ + stream->bits_per_sample = 24; + caps = gst_caps_new_simple (""image/x-j2c"", ""fields"", G_TYPE_INT, 1, NULL); + break; + case GST_MAKE_FOURCC ('S', 'V', 'Q', '3'): + _codec (""Sorensen video v.3""); + caps = gst_caps_new_simple (""video/x-svq"", + ""svqversion"", G_TYPE_INT, 3, NULL); + break; + case GST_MAKE_FOURCC ('s', 'v', 'q', 'i'): + case GST_MAKE_FOURCC ('S', 'V', 'Q', '1'): + _codec (""Sorensen video v.1""); + caps = gst_caps_new_simple (""video/x-svq"", + ""svqversion"", G_TYPE_INT, 1, NULL); + break; + case GST_MAKE_FOURCC ('r', 'a', 'w', ' '): + { + guint16 bps; + + _codec (""Raw RGB video""); + bps = QT_UINT16 (stsd_data + 98); + /* set common stuff */ + caps = gst_caps_new_simple (""video/x-raw-rgb"", + ""endianness"", G_TYPE_INT, G_BYTE_ORDER, ""depth"", G_TYPE_INT, bps, + NULL); + + switch (bps) { + case 15: + gst_caps_set_simple (caps, + ""bpp"", G_TYPE_INT, 16, + ""endianness"", G_TYPE_INT, G_BIG_ENDIAN, + ""red_mask"", G_TYPE_INT, 0x7c00, + ""green_mask"", G_TYPE_INT, 0x03e0, + ""blue_mask"", G_TYPE_INT, 0x001f, NULL); + break; + case 16: + gst_caps_set_simple (caps, + ""bpp"", G_TYPE_INT, 16, + ""endianness"", G_TYPE_INT, G_BIG_ENDIAN, + ""red_mask"", G_TYPE_INT, 0xf800, + ""green_mask"", G_TYPE_INT, 0x07e0, + ""blue_mask"", G_TYPE_INT, 0x001f, NULL); + break; + case 24: + gst_caps_set_simple (caps, + ""bpp"", G_TYPE_INT, 24, + ""endianness"", G_TYPE_INT, G_BIG_ENDIAN, + ""red_mask"", G_TYPE_INT, 0xff0000, + ""green_mask"", G_TYPE_INT, 0x00ff00, + ""blue_mask"", G_TYPE_INT, 0x0000ff, NULL); + break; + case 32: + gst_caps_set_simple (caps, + ""bpp"", G_TYPE_INT, 32, + ""endianness"", G_TYPE_INT, G_BIG_ENDIAN, + ""alpha_mask"", G_TYPE_INT, 0xff000000, + ""red_mask"", G_TYPE_INT, 0x00ff0000, + ""green_mask"", G_TYPE_INT, 0x0000ff00, + ""blue_mask"", G_TYPE_INT, 0x000000ff, NULL); + break; + default: + /* unknown */ + break; + } + break; + } + case GST_MAKE_FOURCC ('y', 'v', '1', '2'): + _codec (""Raw planar YUV 4:2:0""); + caps = gst_caps_new_simple (""video/x-raw-yuv"", + ""format"", GST_TYPE_FOURCC, GST_MAKE_FOURCC ('I', '4', '2', '0'), + NULL); + break; + case GST_MAKE_FOURCC ('y', 'u', 'v', '2'): + case GST_MAKE_FOURCC ('Y', 'u', 'v', '2'): + _codec (""Raw packed YUV 4:2:2""); + caps = gst_caps_new_simple (""video/x-raw-yuv"", + ""format"", GST_TYPE_FOURCC, GST_MAKE_FOURCC ('Y', 'U', 'Y', '2'), + NULL); + break; + case GST_MAKE_FOURCC ('2', 'v', 'u', 'y'): + _codec (""Raw packed YUV 4:2:0""); + caps = gst_caps_new_simple (""video/x-raw-yuv"", + ""format"", GST_TYPE_FOURCC, GST_MAKE_FOURCC ('U', 'Y', 'V', 'Y'), + NULL); + break; + case GST_MAKE_FOURCC ('m', 'p', 'e', 'g'): + case GST_MAKE_FOURCC ('m', 'p', 'g', '1'): + _codec (""MPEG-1 video""); + caps = gst_caps_new_simple (""video/mpeg"", ""mpegversion"", G_TYPE_INT, 1, + ""systemstream"", G_TYPE_BOOLEAN, FALSE, NULL); + break; + case GST_MAKE_FOURCC ('h', 'd', 'v', '1'): // HDV 720p30 + case GST_MAKE_FOURCC ('h', 'd', 'v', '2'): // HDV 1080i60 + case GST_MAKE_FOURCC ('h', 'd', 'v', '3'): // HDV 1080i50 + case GST_MAKE_FOURCC ('h', 'd', 'v', '5'): // HDV 720p25 + case GST_MAKE_FOURCC ('h', 'd', 'v', '6'): // HDV 1080i60 + case GST_MAKE_FOURCC ('m', 'x', '5', 'n'): // MPEG2 IMX NTSC 525/60 50mb/s produced by FCP + case GST_MAKE_FOURCC ('m', 'x', '5', 'p'): // MPEG2 IMX PAL 625/60 50mb/s produced by FCP + case GST_MAKE_FOURCC ('m', 'x', '4', 'n'): // MPEG2 IMX NTSC 525/60 40mb/s produced by FCP + case GST_MAKE_FOURCC ('m', 'x', '4', 'p'): // MPEG2 IMX PAL 625/60 40mb/s produced by FCP + case GST_MAKE_FOURCC ('m', 'x', '3', 'n'): // MPEG2 IMX NTSC 525/60 30mb/s produced by FCP + case GST_MAKE_FOURCC ('m', 'x', '3', 'p'): // MPEG2 IMX PAL 625/50 30mb/s produced by FCP + case GST_MAKE_FOURCC ('x', 'd', 'v', '2'): // XDCAM HD 1080i60 + case GST_MAKE_FOURCC ('A', 'V', 'm', 'p'): // AVID IMX PAL + case GST_MAKE_FOURCC ('m', 'p', 'g', '2'): // AVID IMX PAL + _codec (""MPEG-2 video""); + caps = gst_caps_new_simple (""video/mpeg"", ""mpegversion"", G_TYPE_INT, 2, + ""systemstream"", G_TYPE_BOOLEAN, FALSE, NULL); + break; + case GST_MAKE_FOURCC ('g', 'i', 'f', ' '): + _codec (""GIF still images""); + caps = gst_caps_new_simple (""image/gif"", NULL); + break; + case GST_MAKE_FOURCC ('h', '2', '6', '3'): + case GST_MAKE_FOURCC ('H', '2', '6', '3'): + case GST_MAKE_FOURCC ('s', '2', '6', '3'): + case GST_MAKE_FOURCC ('U', '2', '6', '3'): + _codec (""H.263""); + /* ffmpeg uses the height/width props, don't know why */ + caps = gst_caps_new_simple (""video/x-h263"", NULL); + break; + case GST_MAKE_FOURCC ('m', 'p', '4', 'v'): + _codec (""MPEG-4 video""); + caps = gst_caps_new_simple (""video/mpeg"", ""mpegversion"", G_TYPE_INT, 4, + ""systemstream"", G_TYPE_BOOLEAN, FALSE, NULL); + break; + case GST_MAKE_FOURCC ('3', 'i', 'v', 'd'): + case GST_MAKE_FOURCC ('3', 'I', 'V', 'D'): + _codec (""Microsoft MPEG-4 4.3""); /* FIXME? */ + caps = gst_caps_new_simple (""video/x-msmpeg"", + ""msmpegversion"", G_TYPE_INT, 43, NULL); + break; + case GST_MAKE_FOURCC ('3', 'I', 'V', '1'): + case GST_MAKE_FOURCC ('3', 'I', 'V', '2'): + _codec (""3ivX video""); + caps = gst_caps_new_simple (""video/x-3ivx"", NULL); + break; + case GST_MAKE_FOURCC ('D', 'I', 'V', '3'): + _codec (""DivX 3""); + caps = gst_caps_new_simple (""video/x-divx"", + ""divxversion"", G_TYPE_INT, 3, NULL); + break; + case GST_MAKE_FOURCC ('D', 'I', 'V', 'X'): + case GST_MAKE_FOURCC ('d', 'i', 'v', 'x'): + _codec (""DivX 4""); + caps = gst_caps_new_simple (""video/x-divx"", + ""divxversion"", G_TYPE_INT, 4, NULL); + break; + case GST_MAKE_FOURCC ('D', 'X', '5', '0'): + _codec (""DivX 5""); + caps = gst_caps_new_simple (""video/x-divx"", + ""divxversion"", G_TYPE_INT, 5, NULL); + break; + case GST_MAKE_FOURCC ('X', 'V', 'I', 'D'): + case GST_MAKE_FOURCC ('x', 'v', 'i', 'd'): + _codec (""XVID MPEG-4""); + caps = gst_caps_new_simple (""video/x-xvid"", NULL); + break; + + case GST_MAKE_FOURCC ('F', 'M', 'P', '4'): + case GST_MAKE_FOURCC ('U', 'M', 'P', '4'): + caps = gst_caps_new_simple (""video/mpeg"", + ""mpegversion"", G_TYPE_INT, 4, NULL); + if (codec_name) + *codec_name = g_strdup (""FFmpeg MPEG-4""); + break; + + case GST_MAKE_FOURCC ('c', 'v', 'i', 'd'): + _codec (""Cinepak""); + caps = gst_caps_new_simple (""video/x-cinepak"", NULL); + break; + case GST_MAKE_FOURCC ('q', 'd', 'r', 'w'): + _codec (""Apple QuickDraw""); + caps = gst_caps_new_simple (""video/x-qdrw"", NULL); + break; + case GST_MAKE_FOURCC ('r', 'p', 'z', 'a'): + _codec (""Apple video""); + caps = gst_caps_new_simple (""video/x-apple-video"", NULL); + break; + case GST_MAKE_FOURCC ('a', 'v', 'c', '1'): + _codec (""H.264 / AVC""); + caps = gst_caps_new_simple (""video/x-h264"", NULL); + break; + case GST_MAKE_FOURCC ('r', 'l', 'e', ' '): + _codec (""Run-length encoding""); + caps = gst_caps_new_simple (""video/x-rle"", + ""layout"", G_TYPE_STRING, ""quicktime"", NULL); + break; + case GST_MAKE_FOURCC ('i', 'v', '3', '2'): + _codec (""Indeo Video 3""); + caps = gst_caps_new_simple (""video/x-indeo"", + ""indeoversion"", G_TYPE_INT, 3, NULL); + break; + case GST_MAKE_FOURCC ('I', 'V', '4', '1'): + case GST_MAKE_FOURCC ('i', 'v', '4', '1'): + _codec (""Intel Video 4""); + caps = gst_caps_new_simple (""video/x-indeo"", + ""indeoversion"", G_TYPE_INT, 4, NULL); + break; + case GST_MAKE_FOURCC ('d', 'v', 'c', 'p'): + case GST_MAKE_FOURCC ('d', 'v', 'c', ' '): + case GST_MAKE_FOURCC ('d', 'v', 's', 'd'): + case GST_MAKE_FOURCC ('D', 'V', 'S', 'D'): + case GST_MAKE_FOURCC ('d', 'v', 'c', 's'): + case GST_MAKE_FOURCC ('D', 'V', 'C', 'S'): + case GST_MAKE_FOURCC ('d', 'v', '2', '5'): + case GST_MAKE_FOURCC ('d', 'v', 'p', 'p'): + _codec (""DV Video""); + caps = gst_caps_new_simple (""video/x-dv"", ""dvversion"", G_TYPE_INT, 25, + ""systemstream"", G_TYPE_BOOLEAN, FALSE, NULL); + break; + case GST_MAKE_FOURCC ('d', 'v', '5', 'n'): //DVCPRO50 NTSC + case GST_MAKE_FOURCC ('d', 'v', '5', 'p'): //DVCPRO50 PAL + _codec (""DVCPro50 Video""); + caps = gst_caps_new_simple (""video/x-dv"", ""dvversion"", G_TYPE_INT, 50, + ""systemstream"", G_TYPE_BOOLEAN, FALSE, NULL); + break; + case GST_MAKE_FOURCC ('d', 'v', 'h', '5'): //DVCPRO HD 50i produced by FCP + case GST_MAKE_FOURCC ('d', 'v', 'h', '6'): //DVCPRO HD 60i produced by FCP + _codec (""DVCProHD Video""); + caps = gst_caps_new_simple (""video/x-dv"", ""dvversion"", G_TYPE_INT, 100, + ""systemstream"", G_TYPE_BOOLEAN, FALSE, NULL); + break; + case GST_MAKE_FOURCC ('s', 'm', 'c', ' '): + _codec (""Apple Graphics (SMC)""); + caps = gst_caps_new_simple (""video/x-smc"", NULL); + break; + case GST_MAKE_FOURCC ('V', 'P', '3', '1'): + _codec (""VP3""); + caps = gst_caps_new_simple (""video/x-vp3"", NULL); + break; + case GST_MAKE_FOURCC ('X', 'i', 'T', 'h'): + _codec (""Theora""); + caps = gst_caps_new_simple (""video/x-theora"", NULL); + /* theora uses one byte of padding in the data stream because it does not + * allow 0 sized packets while theora does */ + stream->padding = 1; + break; + case GST_MAKE_FOURCC ('d', 'r', 'a', 'c'): + _codec (""Dirac""); + caps = gst_caps_new_simple (""video/x-dirac"", NULL); + break; + case GST_MAKE_FOURCC ('t', 'i', 'f', 'f'): + _codec (""TIFF still images""); + caps = gst_caps_new_simple (""image/tiff"", NULL); + break; + case GST_MAKE_FOURCC ('k', 'p', 'c', 'd'): + default: + { + char *s; + + s = g_strdup_printf (""video/x-gst-fourcc-%"" GST_FOURCC_FORMAT, + GST_FOURCC_ARGS (fourcc)); + caps = gst_caps_new_simple (s, NULL); + break; + } + } + + /* enable clipping for raw video streams */ + s = gst_caps_get_structure (caps, 0); + name = gst_structure_get_name (s); + if (g_str_has_prefix (name, ""video/x-raw-"")) { + stream->need_clip = TRUE; + } + return caps; +} +","@@ -3058,13 +3058,13 @@ qtdemux_parse_samples (GstQTDemux * qtdemux, QtDemuxStream * stream, + stream->min_duration = 0; + time = 0; + index = 0; +- for (i = 0; i < n_sample_times; i++) { ++ for (i = 0; (i < n_sample_times) && (index < stream->n_samples); i++) { + guint32 n; + guint32 duration; + + n = QT_UINT32 ((guint8 *) stts->data + 16 + 8 * i); + duration = QT_UINT32 ((guint8 *) stts->data + 16 + 8 * i + 4); +- for (j = 0; j < n; j++) { ++ for (j = 0; (j < n) && (index < stream->n_samples); j++) { + GST_DEBUG_OBJECT (qtdemux, ""sample %d: timestamp %"" GST_TIME_FORMAT, + index, GST_TIME_ARGS (timestamp)); + +@@ -3092,7 +3092,7 @@ qtdemux_parse_samples (GstQTDemux * qtdemux, QtDemuxStream * stream, + for (i = 0; i < n_sample_syncs; i++) { + /* note that the first sample is index 1, not 0 */ + index = QT_UINT32 ((guint8 *) stss->data + offset); +- if (index > 0) { ++ if (index > 0 && index <= stream->n_samples) { + samples[index - 1].keyframe = TRUE; + offset += 4; + } +@@ -3191,7 +3191,7 @@ qtdemux_parse_samples (GstQTDemux * qtdemux, QtDemuxStream * stream, + for (i = 0, j = 0; (j < stream->n_samples) && (i < n_entries); i++) { + count = QT_UINT32 (ctts_data + 16 + i * 8); + soffset = QT_UINT32 (ctts_data + 20 + i * 8); +- for (k = 0; k < count; k++, j++) { ++ for (k = 0; (k < count) && (j < stream->n_samples); k++, j++) { + /* we operate with very small soffset values here, it shouldn't overflow */ + samples[j].pts_offset = soffset * GST_SECOND / stream->timescale; + }",3901,4232,6144 +18233,"NO_INLINE JsVar *jspeFactor() { + if (lex->tk==LEX_ID) { + JsVar *a = jspGetNamedVariable(jslGetTokenValueAsString(lex)); + JSP_ASSERT_MATCH(LEX_ID); +#ifndef SAVE_ON_FLASH + if (lex->tk==LEX_TEMPLATE_LITERAL) + jsExceptionHere(JSET_SYNTAXERROR, ""Tagged template literals not supported""); + else if (lex->tk==LEX_ARROW_FUNCTION && jsvIsName(a)) { + JsVar *funcVar = jspeArrowFunction(0,a); + jsvUnLock(a); + a=funcVar; + } +#endif + return a; + } else if (lex->tk==LEX_INT) { + JsVar *v = 0; + if (JSP_SHOULD_EXECUTE) { + v = jsvNewFromLongInteger(stringToInt(jslGetTokenValueAsString(lex))); + } + JSP_ASSERT_MATCH(LEX_INT); + return v; + } else if (lex->tk==LEX_FLOAT) { + JsVar *v = 0; + if (JSP_SHOULD_EXECUTE) { + v = jsvNewFromFloat(stringToFloat(jslGetTokenValueAsString(lex))); + } + JSP_ASSERT_MATCH(LEX_FLOAT); + return v; + } else if (lex->tk=='(') { + JSP_ASSERT_MATCH('('); + if (!jspCheckStackPosition()) return 0; +#ifdef SAVE_ON_FLASH + JsVar *a = jspeExpression(); + if (!JSP_SHOULDNT_PARSE) JSP_MATCH_WITH_RETURN(')',a); + return a; +#else + return jspeExpressionOrArrowFunction(); +#endif + + } else if (lex->tk==LEX_R_TRUE) { + JSP_ASSERT_MATCH(LEX_R_TRUE); + return JSP_SHOULD_EXECUTE ? jsvNewFromBool(true) : 0; + } else if (lex->tk==LEX_R_FALSE) { + JSP_ASSERT_MATCH(LEX_R_FALSE); + return JSP_SHOULD_EXECUTE ? jsvNewFromBool(false) : 0; + } else if (lex->tk==LEX_R_NULL) { + JSP_ASSERT_MATCH(LEX_R_NULL); + return JSP_SHOULD_EXECUTE ? jsvNewWithFlags(JSV_NULL) : 0; + } else if (lex->tk==LEX_R_UNDEFINED) { + JSP_ASSERT_MATCH(LEX_R_UNDEFINED); + return 0; + } else if (lex->tk==LEX_STR) { + JsVar *a = 0; + if (JSP_SHOULD_EXECUTE) + a = jslGetTokenValueAsVar(lex); + JSP_ASSERT_MATCH(LEX_STR); + return a; +#ifndef SAVE_ON_FLASH + } else if (lex->tk==LEX_TEMPLATE_LITERAL) { + return jspeTemplateLiteral(); +#endif + } else if (lex->tk==LEX_REGEX) { + JsVar *a = 0; +#ifdef SAVE_ON_FLASH + jsExceptionHere(JSET_SYNTAXERROR, ""RegEx are not supported in this version of Espruino\n""); +#else + JsVar *regex = jslGetTokenValueAsVar(lex); + size_t regexEnd = 0, regexLen = 0; + JsvStringIterator it; + jsvStringIteratorNew(&it, regex, 0); + while (jsvStringIteratorHasChar(&it)) { + regexLen++; + if (jsvStringIteratorGetChar(&it)=='/') + regexEnd = regexLen; + jsvStringIteratorNext(&it); + } + jsvStringIteratorFree(&it); + JsVar *flags = 0; + if (regexEnd < regexLen) + flags = jsvNewFromStringVar(regex, regexEnd, JSVAPPENDSTRINGVAR_MAXLENGTH); + JsVar *regexSource = jsvNewFromStringVar(regex, 1, regexEnd-2); + a = jswrap_regexp_constructor(regexSource, flags); + jsvUnLock3(regex, flags, regexSource); +#endif + JSP_ASSERT_MATCH(LEX_REGEX); + return a; + } else if (lex->tk=='{') { + if (!jspCheckStackPosition()) return 0; + return jspeFactorObject(); + } else if (lex->tk=='[') { + if (!jspCheckStackPosition()) return 0; + return jspeFactorArray(); + } else if (lex->tk==LEX_R_FUNCTION) { + if (!jspCheckStackPosition()) return 0; + JSP_ASSERT_MATCH(LEX_R_FUNCTION); + return jspeFunctionDefinition(true); +#ifndef SAVE_ON_FLASH + } else if (lex->tk==LEX_R_CLASS) { + if (!jspCheckStackPosition()) return 0; + JSP_ASSERT_MATCH(LEX_R_CLASS); + return jspeClassDefinition(true); + } else if (lex->tk==LEX_R_SUPER) { + JSP_ASSERT_MATCH(LEX_R_SUPER); + /* This is kind of nasty, since super appears to do + three different things. + + * In the constructor it references the extended class's constructor + * in a method it references the constructor's prototype. + * in a static method it references the extended class's constructor (but this is different) + */ + + if (jsvIsObject(execInfo.thisVar)) { + JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_INHERITS_VAR, 0); // if we're in a method, get __proto__ first + JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0; // still in method, get __proto__.__proto__ + jsvUnLock(proto1); + if (!proto2) { + jsExceptionHere(JSET_SYNTAXERROR, ""Calling 'super' outside of class""); + return 0; + } + if (lex->tk=='(') return proto2; // eg. used in a constructor + JsVar *proto3 = jsvIsFunction(proto2) ? jsvObjectGetChild(proto2, JSPARSE_PROTOTYPE_VAR, 0) : 0; + jsvUnLock(proto2); + return proto3; + } else if (jsvIsFunction(execInfo.thisVar)) { + JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_PROTOTYPE_VAR, 0); + JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0; + jsvUnLock(proto1); + if (!proto2) { + jsExceptionHere(JSET_SYNTAXERROR, ""Calling 'super' outside of class""); + return 0; + } + return proto2; + } + jsExceptionHere(JSET_SYNTAXERROR, ""Calling 'super' outside of class""); + return 0; +#endif + } else if (lex->tk==LEX_R_THIS) { + JSP_ASSERT_MATCH(LEX_R_THIS); + return jsvLockAgain( execInfo.thisVar ? execInfo.thisVar : execInfo.root ); + } else if (lex->tk==LEX_R_DELETE) { + if (!jspCheckStackPosition()) return 0; + return jspeFactorDelete(); + } else if (lex->tk==LEX_R_TYPEOF) { + if (!jspCheckStackPosition()) return 0; + return jspeFactorTypeOf(); + } else if (lex->tk==LEX_R_VOID) { + JSP_ASSERT_MATCH(LEX_R_VOID); + jsvUnLock(jspeUnaryExpression()); + return 0; + } + JSP_MATCH(LEX_EOF); + jsExceptionHere(JSET_SYNTAXERROR, ""Unexpected end of Input\n""); + return 0; +} + +NO_INLINE JsVar *__jspePostfixExpression(JsVar *a) { + while (lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS) { + int op = lex->tk; + JSP_ASSERT_MATCH(op); + if (JSP_SHOULD_EXECUTE) { + JsVar *one = jsvNewFromInteger(1); + JsVar *oldValue = jsvAsNumberAndUnLock(jsvSkipName(a)); // keep the old value (but convert to number) + JsVar *res = jsvMathsOpSkipNames(oldValue, one, op==LEX_PLUSPLUS ? '+' : '-'); + jsvUnLock(one); + + jspReplaceWith(a, res); + jsvUnLock(res); + jsvUnLock(a); + a = oldValue; + } + } + return a; +} + +NO_INLINE JsVar *jspePostfixExpression() { + JsVar *a; + if (lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS) { + int op = lex->tk; + JSP_ASSERT_MATCH(op); + a = jspePostfixExpression(); + if (JSP_SHOULD_EXECUTE) { + JsVar *one = jsvNewFromInteger(1); + JsVar *res = jsvMathsOpSkipNames(a, one, op==LEX_PLUSPLUS ? '+' : '-'); + jsvUnLock(one); + jspReplaceWith(a, res); + jsvUnLock(res); + } + } else + a = jspeFactorFunctionCall(); + return __jspePostfixExpression(a); +} + +NO_INLINE JsVar *jspeUnaryExpression() { + if (lex->tk=='!' || lex->tk=='~' || lex->tk=='-' || lex->tk=='+') { + short tk = lex->tk; + JSP_ASSERT_MATCH(tk); + if (!JSP_SHOULD_EXECUTE) { + return jspeUnaryExpression(); + } + if (tk=='!') { // logical not + return jsvNewFromBool(!jsvGetBoolAndUnLock(jsvSkipNameAndUnLock(jspeUnaryExpression()))); + } else if (tk=='~') { // bitwise not + return jsvNewFromInteger(~jsvGetIntegerAndUnLock(jsvSkipNameAndUnLock(jspeUnaryExpression()))); + } else if (tk=='-') { // unary minus + return jsvNegateAndUnLock(jspeUnaryExpression()); // names already skipped + } else if (tk=='+') { // unary plus (convert to number) + JsVar *v = jsvSkipNameAndUnLock(jspeUnaryExpression()); + JsVar *r = jsvAsNumber(v); // names already skipped + jsvUnLock(v); + return r; + } + assert(0); + return 0; + } else + return jspePostfixExpression(); +} + + +unsigned int jspeGetBinaryExpressionPrecedence(int op) { + switch (op) { + case LEX_OROR: return 1; break; + case LEX_ANDAND: return 2; break; + case '|' : return 3; break; + case '^' : return 4; break; + case '&' : return 5; break; + case LEX_EQUAL: + case LEX_NEQUAL: + case LEX_TYPEEQUAL: + case LEX_NTYPEEQUAL: return 6; + case LEX_LEQUAL: + case LEX_GEQUAL: + case '<': + case '>': + case LEX_R_INSTANCEOF: return 7; + case LEX_R_IN: return (execInfo.execute&EXEC_FOR_INIT)?0:7; + case LEX_LSHIFT: + case LEX_RSHIFT: + case LEX_RSHIFTUNSIGNED: return 8; + case '+': + case '-': return 9; + case '*': + case '/': + case '%': return 10; + default: return 0; + } +} + +NO_INLINE JsVar *__jspeBinaryExpression(JsVar *a, unsigned int lastPrecedence) { + /* This one's a bit strange. Basically all the ops have their own precedence, it's not + * like & and | share the same precedence. We don't want to recurse for each one, + * so instead we do this. + * + * We deal with an expression in recursion ONLY if it's of higher precedence + * than the current one, otherwise we stick in the while loop. + */ + unsigned int precedence = jspeGetBinaryExpressionPrecedence(lex->tk); + while (precedence && precedence>lastPrecedence) { + int op = lex->tk; + JSP_ASSERT_MATCH(op); + + if (op==LEX_ANDAND || op==LEX_OROR) { + bool aValue = jsvGetBoolAndUnLock(jsvSkipName(a)); + if ((!aValue && op==LEX_ANDAND) || + (aValue && op==LEX_OROR)) { + JSP_SAVE_EXECUTE(); + jspSetNoExecute(); + jsvUnLock(__jspeBinaryExpression(jspeUnaryExpression(),precedence)); + JSP_RESTORE_EXECUTE(); + } else { + jsvUnLock(a); + a = __jspeBinaryExpression(jspeUnaryExpression(),precedence); + } + } else { // else it's a more 'normal' logical expression - just use Maths + JsVar *b = __jspeBinaryExpression(jspeUnaryExpression(),precedence); + if (JSP_SHOULD_EXECUTE) { + if (op==LEX_R_IN) { + JsVar *av = jsvSkipName(a); // needle + JsVar *bv = jsvSkipName(b); // haystack + if (jsvIsArray(bv) || jsvIsObject(bv)) { // search keys, NOT values + av = jsvAsArrayIndexAndUnLock(av); + JsVar *varFound = jspGetVarNamedField( bv, av, true); + jsvUnLock(a); + a = jsvNewFromBool(varFound!=0); + jsvUnLock(varFound); + } else {// else it will be undefined + jsExceptionHere(JSET_ERROR, ""Cannot use 'in' operator to search a %t"", bv); + jsvUnLock(a); + a = 0; + } + jsvUnLock2(av, bv); + } else if (op==LEX_R_INSTANCEOF) { + bool inst = false; + JsVar *av = jsvSkipName(a); + JsVar *bv = jsvSkipName(b); + if (!jsvIsFunction(bv)) { + jsExceptionHere(JSET_ERROR, ""Expecting a function on RHS in instanceof check, got %t"", bv); + } else { + if (jsvIsObject(av) || jsvIsFunction(av)) { + JsVar *bproto = jspGetNamedField(bv, JSPARSE_PROTOTYPE_VAR, false); + JsVar *proto = jsvObjectGetChild(av, JSPARSE_INHERITS_VAR, 0); + while (proto) { + if (proto == bproto) inst=true; + JsVar *childProto = jsvObjectGetChild(proto, JSPARSE_INHERITS_VAR, 0); + jsvUnLock(proto); + proto = childProto; + } + if (jspIsConstructor(bv, ""Object"")) inst = true; + jsvUnLock(bproto); + } + if (!inst) { + const char *name = jswGetBasicObjectName(av); + if (name) { + inst = jspIsConstructor(bv, name); + } + if (!inst && (jsvIsArray(av) || jsvIsArrayBuffer(av)) && + jspIsConstructor(bv, ""Object"")) + inst = true; + } + } + jsvUnLock3(av, bv, a); + a = jsvNewFromBool(inst); + } else { // --------------------------------------------- NORMAL + JsVar *res = jsvMathsOpSkipNames(a, b, op); + jsvUnLock(a); a = res; + } + } + jsvUnLock(b); + } + precedence = jspeGetBinaryExpressionPrecedence(lex->tk); + } + return a; +} + +JsVar *jspeBinaryExpression() { + return __jspeBinaryExpression(jspeUnaryExpression(),0); +} + +NO_INLINE JsVar *__jspeConditionalExpression(JsVar *lhs) { + if (lex->tk=='?') { + JSP_ASSERT_MATCH('?'); + if (!JSP_SHOULD_EXECUTE) { + jsvUnLock(jspeAssignmentExpression()); + JSP_MATCH(':'); + jsvUnLock(jspeAssignmentExpression()); + } else { + bool first = jsvGetBoolAndUnLock(jsvSkipName(lhs)); + jsvUnLock(lhs); + if (first) { + lhs = jspeAssignmentExpression(); + JSP_MATCH(':'); + JSP_SAVE_EXECUTE(); + jspSetNoExecute(); + jsvUnLock(jspeAssignmentExpression()); + JSP_RESTORE_EXECUTE(); + } else { + JSP_SAVE_EXECUTE(); + jspSetNoExecute(); + jsvUnLock(jspeAssignmentExpression()); + JSP_RESTORE_EXECUTE(); + JSP_MATCH(':'); + lhs = jspeAssignmentExpression(); + } + } + } + + return lhs; +} + +JsVar *jspeConditionalExpression() { + return __jspeConditionalExpression(jspeBinaryExpression()); +} + +NO_INLINE JsVar *__jspeAssignmentExpression(JsVar *lhs) { + if (lex->tk=='=' || lex->tk==LEX_PLUSEQUAL || lex->tk==LEX_MINUSEQUAL || + lex->tk==LEX_MULEQUAL || lex->tk==LEX_DIVEQUAL || lex->tk==LEX_MODEQUAL || + lex->tk==LEX_ANDEQUAL || lex->tk==LEX_OREQUAL || + lex->tk==LEX_XOREQUAL || lex->tk==LEX_RSHIFTEQUAL || + lex->tk==LEX_LSHIFTEQUAL || lex->tk==LEX_RSHIFTUNSIGNEDEQUAL) { + JsVar *rhs; + + int op = lex->tk; + JSP_ASSERT_MATCH(op); + rhs = jspeAssignmentExpression(); + rhs = jsvSkipNameAndUnLock(rhs); // ensure we get rid of any references on the RHS + + if (JSP_SHOULD_EXECUTE && lhs) { + if (op=='=') { + /* If we're assigning to this and we don't have a parent, + * add it to the symbol table root */ + if (!jsvGetRefs(lhs) && jsvIsName(lhs)) { + if (!jsvIsArrayBufferName(lhs) && !jsvIsNewChild(lhs)) + jsvAddName(execInfo.root, lhs); + } + jspReplaceWith(lhs, rhs); + } else { + if (op==LEX_PLUSEQUAL) op='+'; + else if (op==LEX_MINUSEQUAL) op='-'; + else if (op==LEX_MULEQUAL) op='*'; + else if (op==LEX_DIVEQUAL) op='/'; + else if (op==LEX_MODEQUAL) op='%'; + else if (op==LEX_ANDEQUAL) op='&'; + else if (op==LEX_OREQUAL) op='|'; + else if (op==LEX_XOREQUAL) op='^'; + else if (op==LEX_RSHIFTEQUAL) op=LEX_RSHIFT; + else if (op==LEX_LSHIFTEQUAL) op=LEX_LSHIFT; + else if (op==LEX_RSHIFTUNSIGNEDEQUAL) op=LEX_RSHIFTUNSIGNED; + if (op=='+' && jsvIsName(lhs)) { + JsVar *currentValue = jsvSkipName(lhs); + if (jsvIsString(currentValue) && !jsvIsFlatString(currentValue) && jsvGetRefs(currentValue)==1 && rhs!=currentValue) { + /* A special case for string += where this is the only use of the string + * and we're not appending to ourselves. In this case we can do a + * simple append (rather than clone + append)*/ + JsVar *str = jsvAsString(rhs, false); + jsvAppendStringVarComplete(currentValue, str); + jsvUnLock(str); + op = 0; + } + jsvUnLock(currentValue); + } + if (op) { + /* Fallback which does a proper add */ + JsVar *res = jsvMathsOpSkipNames(lhs,rhs,op); + jspReplaceWith(lhs, res); + jsvUnLock(res); + } + } + } + jsvUnLock(rhs); + } + return lhs; +} + + +JsVar *jspeAssignmentExpression() { + return __jspeAssignmentExpression(jspeConditionalExpression()); +} + +NO_INLINE JsVar *jspeExpression() { + while (!JSP_SHOULDNT_PARSE) { + JsVar *a = jspeAssignmentExpression(); + if (lex->tk!=',') return a; + jsvUnLock(a); + JSP_ASSERT_MATCH(','); + } + return 0; +} + +/** Parse a block `{ ... }` but assume brackets are already parsed */ +NO_INLINE void jspeBlockNoBrackets() { + if (JSP_SHOULD_EXECUTE) { + while (lex->tk && lex->tk!='}') { + jsvUnLock(jspeStatement()); + if (JSP_HAS_ERROR) { + if (lex && !(execInfo.execute&EXEC_ERROR_LINE_REPORTED)) { + execInfo.execute = (JsExecFlags)(execInfo.execute | EXEC_ERROR_LINE_REPORTED); + JsVar *stackTrace = jsvObjectGetChild(execInfo.hiddenRoot, JSPARSE_STACKTRACE_VAR, JSV_STRING_0); + if (stackTrace) { + jsvAppendPrintf(stackTrace, ""at ""); + jspAppendStackTrace(stackTrace); + jsvUnLock(stackTrace); + } + } + } + if (JSP_SHOULDNT_PARSE) + return; + } + } else { + int brackets = 0; + while (lex->tk && (brackets || lex->tk != '}')) { + if (lex->tk == '{') brackets++; + if (lex->tk == '}') brackets--; + JSP_ASSERT_MATCH(lex->tk); + } + } +",1,"NO_INLINE JsVar *jspeFactor() { + if (lex->tk==LEX_ID) { + JsVar *a = jspGetNamedVariable(jslGetTokenValueAsString(lex)); + JSP_ASSERT_MATCH(LEX_ID); +#ifndef SAVE_ON_FLASH + if (lex->tk==LEX_TEMPLATE_LITERAL) + jsExceptionHere(JSET_SYNTAXERROR, ""Tagged template literals not supported""); + else if (lex->tk==LEX_ARROW_FUNCTION && jsvIsName(a)) { + JsVar *funcVar = jspeArrowFunction(0,a); + jsvUnLock(a); + a=funcVar; + } +#endif + return a; + } else if (lex->tk==LEX_INT) { + JsVar *v = 0; + if (JSP_SHOULD_EXECUTE) { + v = jsvNewFromLongInteger(stringToInt(jslGetTokenValueAsString(lex))); + } + JSP_ASSERT_MATCH(LEX_INT); + return v; + } else if (lex->tk==LEX_FLOAT) { + JsVar *v = 0; + if (JSP_SHOULD_EXECUTE) { + v = jsvNewFromFloat(stringToFloat(jslGetTokenValueAsString(lex))); + } + JSP_ASSERT_MATCH(LEX_FLOAT); + return v; + } else if (lex->tk=='(') { + JSP_ASSERT_MATCH('('); + if (!jspCheckStackPosition()) return 0; +#ifdef SAVE_ON_FLASH + JsVar *a = jspeExpression(); + if (!JSP_SHOULDNT_PARSE) JSP_MATCH_WITH_RETURN(')',a); + return a; +#else + return jspeExpressionOrArrowFunction(); +#endif + + } else if (lex->tk==LEX_R_TRUE) { + JSP_ASSERT_MATCH(LEX_R_TRUE); + return JSP_SHOULD_EXECUTE ? jsvNewFromBool(true) : 0; + } else if (lex->tk==LEX_R_FALSE) { + JSP_ASSERT_MATCH(LEX_R_FALSE); + return JSP_SHOULD_EXECUTE ? jsvNewFromBool(false) : 0; + } else if (lex->tk==LEX_R_NULL) { + JSP_ASSERT_MATCH(LEX_R_NULL); + return JSP_SHOULD_EXECUTE ? jsvNewWithFlags(JSV_NULL) : 0; + } else if (lex->tk==LEX_R_UNDEFINED) { + JSP_ASSERT_MATCH(LEX_R_UNDEFINED); + return 0; + } else if (lex->tk==LEX_STR) { + JsVar *a = 0; + if (JSP_SHOULD_EXECUTE) + a = jslGetTokenValueAsVar(lex); + JSP_ASSERT_MATCH(LEX_STR); + return a; +#ifndef SAVE_ON_FLASH + } else if (lex->tk==LEX_TEMPLATE_LITERAL) { + return jspeTemplateLiteral(); +#endif + } else if (lex->tk==LEX_REGEX) { + JsVar *a = 0; +#ifdef SAVE_ON_FLASH + jsExceptionHere(JSET_SYNTAXERROR, ""RegEx are not supported in this version of Espruino\n""); +#else + JsVar *regex = jslGetTokenValueAsVar(lex); + size_t regexEnd = 0, regexLen = 0; + JsvStringIterator it; + jsvStringIteratorNew(&it, regex, 0); + while (jsvStringIteratorHasChar(&it)) { + regexLen++; + if (jsvStringIteratorGetChar(&it)=='/') + regexEnd = regexLen; + jsvStringIteratorNext(&it); + } + jsvStringIteratorFree(&it); + JsVar *flags = 0; + if (regexEnd < regexLen) + flags = jsvNewFromStringVar(regex, regexEnd, JSVAPPENDSTRINGVAR_MAXLENGTH); + JsVar *regexSource = jsvNewFromStringVar(regex, 1, regexEnd-2); + a = jswrap_regexp_constructor(regexSource, flags); + jsvUnLock3(regex, flags, regexSource); +#endif + JSP_ASSERT_MATCH(LEX_REGEX); + return a; + } else if (lex->tk=='{') { + if (!jspCheckStackPosition()) return 0; + return jspeFactorObject(); + } else if (lex->tk=='[') { + if (!jspCheckStackPosition()) return 0; + return jspeFactorArray(); + } else if (lex->tk==LEX_R_FUNCTION) { + if (!jspCheckStackPosition()) return 0; + JSP_ASSERT_MATCH(LEX_R_FUNCTION); + return jspeFunctionDefinition(true); +#ifndef SAVE_ON_FLASH + } else if (lex->tk==LEX_R_CLASS) { + if (!jspCheckStackPosition()) return 0; + JSP_ASSERT_MATCH(LEX_R_CLASS); + return jspeClassDefinition(true); + } else if (lex->tk==LEX_R_SUPER) { + JSP_ASSERT_MATCH(LEX_R_SUPER); + /* This is kind of nasty, since super appears to do + three different things. + + * In the constructor it references the extended class's constructor + * in a method it references the constructor's prototype. + * in a static method it references the extended class's constructor (but this is different) + */ + + if (jsvIsObject(execInfo.thisVar)) { + JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_INHERITS_VAR, 0); // if we're in a method, get __proto__ first + JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0; // still in method, get __proto__.__proto__ + jsvUnLock(proto1); + if (!proto2) { + jsExceptionHere(JSET_SYNTAXERROR, ""Calling 'super' outside of class""); + return 0; + } + if (lex->tk=='(') return proto2; // eg. used in a constructor + JsVar *proto3 = jsvIsFunction(proto2) ? jsvObjectGetChild(proto2, JSPARSE_PROTOTYPE_VAR, 0) : 0; + jsvUnLock(proto2); + return proto3; + } else if (jsvIsFunction(execInfo.thisVar)) { + JsVar *proto1 = jsvObjectGetChild(execInfo.thisVar, JSPARSE_PROTOTYPE_VAR, 0); + JsVar *proto2 = jsvIsObject(proto1) ? jsvObjectGetChild(proto1, JSPARSE_INHERITS_VAR, 0) : 0; + jsvUnLock(proto1); + if (!proto2) { + jsExceptionHere(JSET_SYNTAXERROR, ""Calling 'super' outside of class""); + return 0; + } + return proto2; + } + jsExceptionHere(JSET_SYNTAXERROR, ""Calling 'super' outside of class""); + return 0; +#endif + } else if (lex->tk==LEX_R_THIS) { + JSP_ASSERT_MATCH(LEX_R_THIS); + return jsvLockAgain( execInfo.thisVar ? execInfo.thisVar : execInfo.root ); + } else if (lex->tk==LEX_R_DELETE) { + if (!jspCheckStackPosition()) return 0; + return jspeFactorDelete(); + } else if (lex->tk==LEX_R_TYPEOF) { + if (!jspCheckStackPosition()) return 0; + return jspeFactorTypeOf(); + } else if (lex->tk==LEX_R_VOID) { + if (!jspCheckStackPosition()) return 0; + JSP_ASSERT_MATCH(LEX_R_VOID); + jsvUnLock(jspeUnaryExpression()); + return 0; + } + JSP_MATCH(LEX_EOF); + jsExceptionHere(JSET_SYNTAXERROR, ""Unexpected end of Input\n""); + return 0; +} + +NO_INLINE JsVar *__jspePostfixExpression(JsVar *a) { + while (lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS) { + int op = lex->tk; + JSP_ASSERT_MATCH(op); + if (JSP_SHOULD_EXECUTE) { + JsVar *one = jsvNewFromInteger(1); + JsVar *oldValue = jsvAsNumberAndUnLock(jsvSkipName(a)); // keep the old value (but convert to number) + JsVar *res = jsvMathsOpSkipNames(oldValue, one, op==LEX_PLUSPLUS ? '+' : '-'); + jsvUnLock(one); + + jspReplaceWith(a, res); + jsvUnLock(res); + jsvUnLock(a); + a = oldValue; + } + } + return a; +} + +NO_INLINE JsVar *jspePostfixExpression() { + JsVar *a; + if (lex->tk==LEX_PLUSPLUS || lex->tk==LEX_MINUSMINUS) { + int op = lex->tk; + JSP_ASSERT_MATCH(op); + a = jspePostfixExpression(); + if (JSP_SHOULD_EXECUTE) { + JsVar *one = jsvNewFromInteger(1); + JsVar *res = jsvMathsOpSkipNames(a, one, op==LEX_PLUSPLUS ? '+' : '-'); + jsvUnLock(one); + jspReplaceWith(a, res); + jsvUnLock(res); + } + } else + a = jspeFactorFunctionCall(); + return __jspePostfixExpression(a); +} + +NO_INLINE JsVar *jspeUnaryExpression() { + if (lex->tk=='!' || lex->tk=='~' || lex->tk=='-' || lex->tk=='+') { + short tk = lex->tk; + JSP_ASSERT_MATCH(tk); + if (!JSP_SHOULD_EXECUTE) { + return jspeUnaryExpression(); + } + if (tk=='!') { // logical not + return jsvNewFromBool(!jsvGetBoolAndUnLock(jsvSkipNameAndUnLock(jspeUnaryExpression()))); + } else if (tk=='~') { // bitwise not + return jsvNewFromInteger(~jsvGetIntegerAndUnLock(jsvSkipNameAndUnLock(jspeUnaryExpression()))); + } else if (tk=='-') { // unary minus + return jsvNegateAndUnLock(jspeUnaryExpression()); // names already skipped + } else if (tk=='+') { // unary plus (convert to number) + JsVar *v = jsvSkipNameAndUnLock(jspeUnaryExpression()); + JsVar *r = jsvAsNumber(v); // names already skipped + jsvUnLock(v); + return r; + } + assert(0); + return 0; + } else + return jspePostfixExpression(); +} + + +unsigned int jspeGetBinaryExpressionPrecedence(int op) { + switch (op) { + case LEX_OROR: return 1; break; + case LEX_ANDAND: return 2; break; + case '|' : return 3; break; + case '^' : return 4; break; + case '&' : return 5; break; + case LEX_EQUAL: + case LEX_NEQUAL: + case LEX_TYPEEQUAL: + case LEX_NTYPEEQUAL: return 6; + case LEX_LEQUAL: + case LEX_GEQUAL: + case '<': + case '>': + case LEX_R_INSTANCEOF: return 7; + case LEX_R_IN: return (execInfo.execute&EXEC_FOR_INIT)?0:7; + case LEX_LSHIFT: + case LEX_RSHIFT: + case LEX_RSHIFTUNSIGNED: return 8; + case '+': + case '-': return 9; + case '*': + case '/': + case '%': return 10; + default: return 0; + } +} + +NO_INLINE JsVar *__jspeBinaryExpression(JsVar *a, unsigned int lastPrecedence) { + /* This one's a bit strange. Basically all the ops have their own precedence, it's not + * like & and | share the same precedence. We don't want to recurse for each one, + * so instead we do this. + * + * We deal with an expression in recursion ONLY if it's of higher precedence + * than the current one, otherwise we stick in the while loop. + */ + unsigned int precedence = jspeGetBinaryExpressionPrecedence(lex->tk); + while (precedence && precedence>lastPrecedence) { + int op = lex->tk; + JSP_ASSERT_MATCH(op); + + if (op==LEX_ANDAND || op==LEX_OROR) { + bool aValue = jsvGetBoolAndUnLock(jsvSkipName(a)); + if ((!aValue && op==LEX_ANDAND) || + (aValue && op==LEX_OROR)) { + JSP_SAVE_EXECUTE(); + jspSetNoExecute(); + jsvUnLock(__jspeBinaryExpression(jspeUnaryExpression(),precedence)); + JSP_RESTORE_EXECUTE(); + } else { + jsvUnLock(a); + a = __jspeBinaryExpression(jspeUnaryExpression(),precedence); + } + } else { // else it's a more 'normal' logical expression - just use Maths + JsVar *b = __jspeBinaryExpression(jspeUnaryExpression(),precedence); + if (JSP_SHOULD_EXECUTE) { + if (op==LEX_R_IN) { + JsVar *av = jsvSkipName(a); // needle + JsVar *bv = jsvSkipName(b); // haystack + if (jsvIsArray(bv) || jsvIsObject(bv)) { // search keys, NOT values + av = jsvAsArrayIndexAndUnLock(av); + JsVar *varFound = jspGetVarNamedField( bv, av, true); + jsvUnLock(a); + a = jsvNewFromBool(varFound!=0); + jsvUnLock(varFound); + } else {// else it will be undefined + jsExceptionHere(JSET_ERROR, ""Cannot use 'in' operator to search a %t"", bv); + jsvUnLock(a); + a = 0; + } + jsvUnLock2(av, bv); + } else if (op==LEX_R_INSTANCEOF) { + bool inst = false; + JsVar *av = jsvSkipName(a); + JsVar *bv = jsvSkipName(b); + if (!jsvIsFunction(bv)) { + jsExceptionHere(JSET_ERROR, ""Expecting a function on RHS in instanceof check, got %t"", bv); + } else { + if (jsvIsObject(av) || jsvIsFunction(av)) { + JsVar *bproto = jspGetNamedField(bv, JSPARSE_PROTOTYPE_VAR, false); + JsVar *proto = jsvObjectGetChild(av, JSPARSE_INHERITS_VAR, 0); + while (proto) { + if (proto == bproto) inst=true; + JsVar *childProto = jsvObjectGetChild(proto, JSPARSE_INHERITS_VAR, 0); + jsvUnLock(proto); + proto = childProto; + } + if (jspIsConstructor(bv, ""Object"")) inst = true; + jsvUnLock(bproto); + } + if (!inst) { + const char *name = jswGetBasicObjectName(av); + if (name) { + inst = jspIsConstructor(bv, name); + } + if (!inst && (jsvIsArray(av) || jsvIsArrayBuffer(av)) && + jspIsConstructor(bv, ""Object"")) + inst = true; + } + } + jsvUnLock3(av, bv, a); + a = jsvNewFromBool(inst); + } else { // --------------------------------------------- NORMAL + JsVar *res = jsvMathsOpSkipNames(a, b, op); + jsvUnLock(a); a = res; + } + } + jsvUnLock(b); + } + precedence = jspeGetBinaryExpressionPrecedence(lex->tk); + } + return a; +} + +JsVar *jspeBinaryExpression() { + return __jspeBinaryExpression(jspeUnaryExpression(),0); +} + +NO_INLINE JsVar *__jspeConditionalExpression(JsVar *lhs) { + if (lex->tk=='?') { + JSP_ASSERT_MATCH('?'); + if (!JSP_SHOULD_EXECUTE) { + jsvUnLock(jspeAssignmentExpression()); + JSP_MATCH(':'); + jsvUnLock(jspeAssignmentExpression()); + } else { + bool first = jsvGetBoolAndUnLock(jsvSkipName(lhs)); + jsvUnLock(lhs); + if (first) { + lhs = jspeAssignmentExpression(); + JSP_MATCH(':'); + JSP_SAVE_EXECUTE(); + jspSetNoExecute(); + jsvUnLock(jspeAssignmentExpression()); + JSP_RESTORE_EXECUTE(); + } else { + JSP_SAVE_EXECUTE(); + jspSetNoExecute(); + jsvUnLock(jspeAssignmentExpression()); + JSP_RESTORE_EXECUTE(); + JSP_MATCH(':'); + lhs = jspeAssignmentExpression(); + } + } + } + + return lhs; +} + +JsVar *jspeConditionalExpression() { + return __jspeConditionalExpression(jspeBinaryExpression()); +} + +NO_INLINE JsVar *__jspeAssignmentExpression(JsVar *lhs) { + if (lex->tk=='=' || lex->tk==LEX_PLUSEQUAL || lex->tk==LEX_MINUSEQUAL || + lex->tk==LEX_MULEQUAL || lex->tk==LEX_DIVEQUAL || lex->tk==LEX_MODEQUAL || + lex->tk==LEX_ANDEQUAL || lex->tk==LEX_OREQUAL || + lex->tk==LEX_XOREQUAL || lex->tk==LEX_RSHIFTEQUAL || + lex->tk==LEX_LSHIFTEQUAL || lex->tk==LEX_RSHIFTUNSIGNEDEQUAL) { + JsVar *rhs; + + int op = lex->tk; + JSP_ASSERT_MATCH(op); + rhs = jspeAssignmentExpression(); + rhs = jsvSkipNameAndUnLock(rhs); // ensure we get rid of any references on the RHS + + if (JSP_SHOULD_EXECUTE && lhs) { + if (op=='=') { + /* If we're assigning to this and we don't have a parent, + * add it to the symbol table root */ + if (!jsvGetRefs(lhs) && jsvIsName(lhs)) { + if (!jsvIsArrayBufferName(lhs) && !jsvIsNewChild(lhs)) + jsvAddName(execInfo.root, lhs); + } + jspReplaceWith(lhs, rhs); + } else { + if (op==LEX_PLUSEQUAL) op='+'; + else if (op==LEX_MINUSEQUAL) op='-'; + else if (op==LEX_MULEQUAL) op='*'; + else if (op==LEX_DIVEQUAL) op='/'; + else if (op==LEX_MODEQUAL) op='%'; + else if (op==LEX_ANDEQUAL) op='&'; + else if (op==LEX_OREQUAL) op='|'; + else if (op==LEX_XOREQUAL) op='^'; + else if (op==LEX_RSHIFTEQUAL) op=LEX_RSHIFT; + else if (op==LEX_LSHIFTEQUAL) op=LEX_LSHIFT; + else if (op==LEX_RSHIFTUNSIGNEDEQUAL) op=LEX_RSHIFTUNSIGNED; + if (op=='+' && jsvIsName(lhs)) { + JsVar *currentValue = jsvSkipName(lhs); + if (jsvIsString(currentValue) && !jsvIsFlatString(currentValue) && jsvGetRefs(currentValue)==1 && rhs!=currentValue) { + /* A special case for string += where this is the only use of the string + * and we're not appending to ourselves. In this case we can do a + * simple append (rather than clone + append)*/ + JsVar *str = jsvAsString(rhs, false); + jsvAppendStringVarComplete(currentValue, str); + jsvUnLock(str); + op = 0; + } + jsvUnLock(currentValue); + } + if (op) { + /* Fallback which does a proper add */ + JsVar *res = jsvMathsOpSkipNames(lhs,rhs,op); + jspReplaceWith(lhs, res); + jsvUnLock(res); + } + } + } + jsvUnLock(rhs); + } + return lhs; +} + + +JsVar *jspeAssignmentExpression() { + return __jspeAssignmentExpression(jspeConditionalExpression()); +} + +NO_INLINE JsVar *jspeExpression() { + while (!JSP_SHOULDNT_PARSE) { + JsVar *a = jspeAssignmentExpression(); + if (lex->tk!=',') return a; + jsvUnLock(a); + JSP_ASSERT_MATCH(','); + } + return 0; +} + +/** Parse a block `{ ... }` but assume brackets are already parsed */ +NO_INLINE void jspeBlockNoBrackets() { + if (JSP_SHOULD_EXECUTE) { + while (lex->tk && lex->tk!='}') { + jsvUnLock(jspeStatement()); + if (JSP_HAS_ERROR) { + if (lex && !(execInfo.execute&EXEC_ERROR_LINE_REPORTED)) { + execInfo.execute = (JsExecFlags)(execInfo.execute | EXEC_ERROR_LINE_REPORTED); + JsVar *stackTrace = jsvObjectGetChild(execInfo.hiddenRoot, JSPARSE_STACKTRACE_VAR, JSV_STRING_0); + if (stackTrace) { + jsvAppendPrintf(stackTrace, ""at ""); + jspAppendStackTrace(stackTrace); + jsvUnLock(stackTrace); + } + } + } + if (JSP_SHOULDNT_PARSE) + return; + } + } else { + int brackets = 0; + while (lex->tk && (brackets || lex->tk != '}')) { + if (lex->tk == '{') brackets++; + if (lex->tk == '}') brackets--; + JSP_ASSERT_MATCH(lex->tk); + } + } +","@@ -1716,6 +1716,7 @@ NO_INLINE JsVar *jspeFactor() { + if (!jspCheckStackPosition()) return 0; + return jspeFactorTypeOf(); + } else if (lex->tk==LEX_R_VOID) { ++ if (!jspCheckStackPosition()) return 0; + JSP_ASSERT_MATCH(LEX_R_VOID); + jsvUnLock(jspeUnaryExpression()); + return 0;",4740,5071,6144 +18804,"IHEVCD_ERROR_T ihevcd_parse_sps(codec_t *ps_codec) +{ + IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; + WORD32 value; + + WORD32 i; + WORD32 vps_id; + WORD32 sps_max_sub_layers; + WORD32 sps_id; + WORD32 sps_temporal_id_nesting_flag; + sps_t *ps_sps; + profile_tier_lvl_info_t s_ptl; + bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm; + WORD32 ctb_log2_size_y = 0; + + + BITS_PARSE(""video_parameter_set_id"", value, ps_bitstrm, 4); + vps_id = value; + vps_id = CLIP3(vps_id, 0, MAX_VPS_CNT - 1); + + BITS_PARSE(""sps_max_sub_layers_minus1"", value, ps_bitstrm, 3); + sps_max_sub_layers = value + 1; + sps_max_sub_layers = CLIP3(sps_max_sub_layers, 1, 7); + + BITS_PARSE(""sps_temporal_id_nesting_flag"", value, ps_bitstrm, 1); + sps_temporal_id_nesting_flag = value; + + ret = ihevcd_profile_tier_level(ps_bitstrm, &(s_ptl), 1, + (sps_max_sub_layers - 1)); + + UEV_PARSE(""seq_parameter_set_id"", value, ps_bitstrm); + sps_id = value; + + if((sps_id >= MAX_SPS_CNT) || (sps_id < 0)) + { + if(ps_codec->i4_sps_done) + return IHEVCD_UNSUPPORTED_SPS_ID; + else + sps_id = 0; + } + + + ps_sps = (ps_codec->s_parse.ps_sps_base + MAX_SPS_CNT - 1); + ps_sps->i1_sps_id = sps_id; + ps_sps->i1_vps_id = vps_id; + ps_sps->i1_sps_max_sub_layers = sps_max_sub_layers; + ps_sps->i1_sps_temporal_id_nesting_flag = sps_temporal_id_nesting_flag; + /* This is used only during initialization to get reorder count etc */ + ps_codec->i4_sps_id = sps_id; + memcpy(&ps_sps->s_ptl, &s_ptl, sizeof(profile_tier_lvl_info_t)); + + UEV_PARSE(""chroma_format_idc"", value, ps_bitstrm); + ps_sps->i1_chroma_format_idc = value; + + if(ps_sps->i1_chroma_format_idc != CHROMA_FMT_IDC_YUV420) + { + ps_codec->s_parse.i4_error_code = IHEVCD_UNSUPPORTED_CHROMA_FMT_IDC; + return (IHEVCD_ERROR_T)IHEVCD_UNSUPPORTED_CHROMA_FMT_IDC; + } + + if(CHROMA_FMT_IDC_YUV444_PLANES == ps_sps->i1_chroma_format_idc) + { + BITS_PARSE(""separate_colour_plane_flag"", value, ps_bitstrm, 1); + ps_sps->i1_separate_colour_plane_flag = value; + } + else + { + ps_sps->i1_separate_colour_plane_flag = 0; + } + + UEV_PARSE(""pic_width_in_luma_samples"", value, ps_bitstrm); + ps_sps->i2_pic_width_in_luma_samples = value; + + UEV_PARSE(""pic_height_in_luma_samples"", value, ps_bitstrm); + ps_sps->i2_pic_height_in_luma_samples = value; + + if((0 >= ps_sps->i2_pic_width_in_luma_samples) || (0 >= ps_sps->i2_pic_height_in_luma_samples)) + return IHEVCD_INVALID_PARAMETER; + + /* i2_pic_width_in_luma_samples and i2_pic_height_in_luma_samples + should be multiples of min_cb_size. Here these are aligned to 8, + i.e. smallest CB size */ + ps_sps->i2_pic_width_in_luma_samples = ALIGN8(ps_sps->i2_pic_width_in_luma_samples); + ps_sps->i2_pic_height_in_luma_samples = ALIGN8(ps_sps->i2_pic_height_in_luma_samples); + + BITS_PARSE(""pic_cropping_flag"", value, ps_bitstrm, 1); + ps_sps->i1_pic_cropping_flag = value; + + if(ps_sps->i1_pic_cropping_flag) + { + + UEV_PARSE(""pic_crop_left_offset"", value, ps_bitstrm); + ps_sps->i2_pic_crop_left_offset = value; + + UEV_PARSE(""pic_crop_right_offset"", value, ps_bitstrm); + ps_sps->i2_pic_crop_right_offset = value; + + UEV_PARSE(""pic_crop_top_offset"", value, ps_bitstrm); + ps_sps->i2_pic_crop_top_offset = value; + + UEV_PARSE(""pic_crop_bottom_offset"", value, ps_bitstrm); + ps_sps->i2_pic_crop_bottom_offset = value; + } + else + { + ps_sps->i2_pic_crop_left_offset = 0; + ps_sps->i2_pic_crop_right_offset = 0; + ps_sps->i2_pic_crop_top_offset = 0; + ps_sps->i2_pic_crop_bottom_offset = 0; + } + + + UEV_PARSE(""bit_depth_luma_minus8"", value, ps_bitstrm); + if(0 != value) + return IHEVCD_UNSUPPORTED_BIT_DEPTH; + + UEV_PARSE(""bit_depth_chroma_minus8"", value, ps_bitstrm); + if(0 != value) + return IHEVCD_UNSUPPORTED_BIT_DEPTH; + + UEV_PARSE(""log2_max_pic_order_cnt_lsb_minus4"", value, ps_bitstrm); + ps_sps->i1_log2_max_pic_order_cnt_lsb = value + 4; + + BITS_PARSE(""sps_sub_layer_ordering_info_present_flag"", value, ps_bitstrm, 1); + ps_sps->i1_sps_sub_layer_ordering_info_present_flag = value; + + + i = (ps_sps->i1_sps_sub_layer_ordering_info_present_flag ? 0 : (ps_sps->i1_sps_max_sub_layers - 1)); + for(; i < ps_sps->i1_sps_max_sub_layers; i++) + { + UEV_PARSE(""max_dec_pic_buffering"", value, ps_bitstrm); + ps_sps->ai1_sps_max_dec_pic_buffering[i] = value + 1; + + if(ps_sps->ai1_sps_max_dec_pic_buffering[i] > MAX_DPB_SIZE) + { + return IHEVCD_INVALID_PARAMETER; + } + + UEV_PARSE(""num_reorder_pics"", value, ps_bitstrm); + ps_sps->ai1_sps_max_num_reorder_pics[i] = value; + + if(ps_sps->ai1_sps_max_num_reorder_pics[i] > ps_sps->ai1_sps_max_dec_pic_buffering[i]) + { + return IHEVCD_INVALID_PARAMETER; + } + + UEV_PARSE(""max_latency_increase"", value, ps_bitstrm); + ps_sps->ai1_sps_max_latency_increase[i] = value; + } + UEV_PARSE(""log2_min_coding_block_size_minus3"", value, ps_bitstrm); + ps_sps->i1_log2_min_coding_block_size = value + 3; + + UEV_PARSE(""log2_diff_max_min_coding_block_size"", value, ps_bitstrm); + ps_sps->i1_log2_diff_max_min_coding_block_size = value; + + ctb_log2_size_y = ps_sps->i1_log2_min_coding_block_size + ps_sps->i1_log2_diff_max_min_coding_block_size; + + UEV_PARSE(""log2_min_transform_block_size_minus2"", value, ps_bitstrm); + ps_sps->i1_log2_min_transform_block_size = value + 2; + + UEV_PARSE(""log2_diff_max_min_transform_block_size"", value, ps_bitstrm); + ps_sps->i1_log2_diff_max_min_transform_block_size = value; + + ps_sps->i1_log2_max_transform_block_size = ps_sps->i1_log2_min_transform_block_size + + ps_sps->i1_log2_diff_max_min_transform_block_size; + + if ((ps_sps->i1_log2_max_transform_block_size < 0) || + (ps_sps->i1_log2_max_transform_block_size > MIN(ctb_log2_size_y, 5))) + { + return IHEVCD_INVALID_PARAMETER; + } + + ps_sps->i1_log2_ctb_size = ps_sps->i1_log2_min_coding_block_size + + ps_sps->i1_log2_diff_max_min_coding_block_size; + + if((ps_sps->i1_log2_min_coding_block_size < 3) || + (ps_sps->i1_log2_min_transform_block_size < 2) || + (ps_sps->i1_log2_diff_max_min_transform_block_size < 0) || + (ps_sps->i1_log2_max_transform_block_size > ps_sps->i1_log2_ctb_size) || + (ps_sps->i1_log2_ctb_size < 4) || + (ps_sps->i1_log2_ctb_size > 6)) + { + return IHEVCD_INVALID_PARAMETER; + } + + ps_sps->i1_log2_min_pcm_coding_block_size = 0; + ps_sps->i1_log2_diff_max_min_pcm_coding_block_size = 0; + + UEV_PARSE(""max_transform_hierarchy_depth_inter"", value, ps_bitstrm); + ps_sps->i1_max_transform_hierarchy_depth_inter = value; + + UEV_PARSE(""max_transform_hierarchy_depth_intra"", value, ps_bitstrm); + ps_sps->i1_max_transform_hierarchy_depth_intra = value; + + /* String has a d (enabled) in order to match with HM */ + BITS_PARSE(""scaling_list_enabled_flag"", value, ps_bitstrm, 1); + ps_sps->i1_scaling_list_enable_flag = value; + + if(ps_sps->i1_scaling_list_enable_flag) + { + COPY_DEFAULT_SCALING_LIST(ps_sps->pi2_scaling_mat); + BITS_PARSE(""sps_scaling_list_data_present_flag"", value, ps_bitstrm, 1); + ps_sps->i1_sps_scaling_list_data_present_flag = value; + + if(ps_sps->i1_sps_scaling_list_data_present_flag) + ihevcd_scaling_list_data(ps_codec, ps_sps->pi2_scaling_mat); + } + else + { + COPY_FLAT_SCALING_LIST(ps_sps->pi2_scaling_mat); + } + /* String is asymmetric_motion_partitions_enabled_flag instead of amp_enabled_flag in order to match with HM */ + BITS_PARSE(""asymmetric_motion_partitions_enabled_flag"", value, ps_bitstrm, 1); + ps_sps->i1_amp_enabled_flag = value; + + BITS_PARSE(""sample_adaptive_offset_enabled_flag"", value, ps_bitstrm, 1); + ps_sps->i1_sample_adaptive_offset_enabled_flag = value; + + BITS_PARSE(""pcm_enabled_flag"", value, ps_bitstrm, 1); + ps_sps->i1_pcm_enabled_flag = value; + + if(ps_sps->i1_pcm_enabled_flag) + { + BITS_PARSE(""pcm_sample_bit_depth_luma"", value, ps_bitstrm, 4); + ps_sps->i1_pcm_sample_bit_depth_luma = value + 1; + + BITS_PARSE(""pcm_sample_bit_depth_chroma"", value, ps_bitstrm, 4); + ps_sps->i1_pcm_sample_bit_depth_chroma = value + 1; + + UEV_PARSE(""log2_min_pcm_coding_block_size_minus3"", value, ps_bitstrm); + ps_sps->i1_log2_min_pcm_coding_block_size = value + 3; + + UEV_PARSE(""log2_diff_max_min_pcm_coding_block_size"", value, ps_bitstrm); + ps_sps->i1_log2_diff_max_min_pcm_coding_block_size = value; + BITS_PARSE(""pcm_loop_filter_disable_flag"", value, ps_bitstrm, 1); + ps_sps->i1_pcm_loop_filter_disable_flag = value; + + } + UEV_PARSE(""num_short_term_ref_pic_sets"", value, ps_bitstrm); + ps_sps->i1_num_short_term_ref_pic_sets = value; + + ps_sps->i1_num_short_term_ref_pic_sets = CLIP3(ps_sps->i1_num_short_term_ref_pic_sets, 0, MAX_STREF_PICS_SPS); + + for(i = 0; i < ps_sps->i1_num_short_term_ref_pic_sets; i++) + ihevcd_short_term_ref_pic_set(ps_bitstrm, &ps_sps->as_stref_picset[0], ps_sps->i1_num_short_term_ref_pic_sets, i, &ps_sps->as_stref_picset[i]); + + BITS_PARSE(""long_term_ref_pics_present_flag"", value, ps_bitstrm, 1); + ps_sps->i1_long_term_ref_pics_present_flag = value; + + if(ps_sps->i1_long_term_ref_pics_present_flag) + { + UEV_PARSE(""num_long_term_ref_pics_sps"", value, ps_bitstrm); + ps_sps->i1_num_long_term_ref_pics_sps = value; + + for(i = 0; i < ps_sps->i1_num_long_term_ref_pics_sps; i++) + { + BITS_PARSE(""lt_ref_pic_poc_lsb_sps[ i ]"", value, ps_bitstrm, ps_sps->i1_log2_max_pic_order_cnt_lsb); + ps_sps->ai1_lt_ref_pic_poc_lsb_sps[i] = value; + + BITS_PARSE(""used_by_curr_pic_lt_sps_flag[ i ]"", value, ps_bitstrm, 1); + ps_sps->ai1_used_by_curr_pic_lt_sps_flag[i] = value; + } + } + + BITS_PARSE(""sps_temporal_mvp_enable_flag"", value, ps_bitstrm, 1); + ps_sps->i1_sps_temporal_mvp_enable_flag = value; + + /* Print matches HM 8-2 */ + BITS_PARSE(""sps_strong_intra_smoothing_enable_flag"", value, ps_bitstrm, 1); + ps_sps->i1_strong_intra_smoothing_enable_flag = value; + + BITS_PARSE(""vui_parameters_present_flag"", value, ps_bitstrm, 1); + ps_sps->i1_vui_parameters_present_flag = value; + + if(ps_sps->i1_vui_parameters_present_flag) + ihevcd_parse_vui_parameters(ps_bitstrm, + &ps_sps->s_vui_parameters, + ps_sps->i1_sps_max_sub_layers - 1); + + + BITS_PARSE(""sps_extension_flag"", value, ps_bitstrm, 1); + + + { + WORD32 numerator; + WORD32 ceil_offset; + + ceil_offset = (1 << ps_sps->i1_log2_ctb_size) - 1; + numerator = ps_sps->i2_pic_width_in_luma_samples; + + ps_sps->i2_pic_wd_in_ctb = ((numerator + ceil_offset) / + (1 << ps_sps->i1_log2_ctb_size)); + + numerator = ps_sps->i2_pic_height_in_luma_samples; + ps_sps->i2_pic_ht_in_ctb = ((numerator + ceil_offset) / + (1 << ps_sps->i1_log2_ctb_size)); + + ps_sps->i4_pic_size_in_ctb = ps_sps->i2_pic_ht_in_ctb * + ps_sps->i2_pic_wd_in_ctb; + + if(0 == ps_codec->i4_sps_done) + ps_codec->s_parse.i4_next_ctb_indx = ps_sps->i4_pic_size_in_ctb; + + numerator = ps_sps->i2_pic_width_in_luma_samples; + ps_sps->i2_pic_wd_in_min_cb = numerator / + (1 << ps_sps->i1_log2_min_coding_block_size); + + numerator = ps_sps->i2_pic_height_in_luma_samples; + ps_sps->i2_pic_ht_in_min_cb = numerator / + (1 << ps_sps->i1_log2_min_coding_block_size); + } + if((0 != ps_codec->i4_first_pic_done) && + ((ps_codec->i4_wd != ps_sps->i2_pic_width_in_luma_samples) || + (ps_codec->i4_ht != ps_sps->i2_pic_height_in_luma_samples))) + { + ps_codec->i4_reset_flag = 1; + return (IHEVCD_ERROR_T)IVD_RES_CHANGED; + } + + /* Update display width and display height */ + { + WORD32 disp_wd, disp_ht; + WORD32 crop_unit_x, crop_unit_y; + crop_unit_x = 1; + crop_unit_y = 1; + + if(CHROMA_FMT_IDC_YUV420 == ps_sps->i1_chroma_format_idc) + { + crop_unit_x = 2; + crop_unit_y = 2; + } + + disp_wd = ps_sps->i2_pic_width_in_luma_samples; + disp_wd -= ps_sps->i2_pic_crop_left_offset * crop_unit_x; + disp_wd -= ps_sps->i2_pic_crop_right_offset * crop_unit_x; + + + disp_ht = ps_sps->i2_pic_height_in_luma_samples; + disp_ht -= ps_sps->i2_pic_crop_top_offset * crop_unit_y; + disp_ht -= ps_sps->i2_pic_crop_bottom_offset * crop_unit_y; + + if((0 >= disp_wd) || (0 >= disp_ht)) + return IHEVCD_INVALID_PARAMETER; + + ps_codec->i4_disp_wd = disp_wd; + ps_codec->i4_disp_ht = disp_ht; + + + ps_codec->i4_wd = ps_sps->i2_pic_width_in_luma_samples; + ps_codec->i4_ht = ps_sps->i2_pic_height_in_luma_samples; + + { + WORD32 ref_strd; + ref_strd = ALIGN32(ps_sps->i2_pic_width_in_luma_samples + PAD_WD); + if(ps_codec->i4_strd < ref_strd) + { + ps_codec->i4_strd = ref_strd; + } + } + + if(0 == ps_codec->i4_share_disp_buf) + { + if(ps_codec->i4_disp_strd < ps_codec->i4_disp_wd) + { + ps_codec->i4_disp_strd = ps_codec->i4_disp_wd; + } + } + else + { + if(ps_codec->i4_disp_strd < ps_codec->i4_strd) + { + ps_codec->i4_disp_strd = ps_codec->i4_strd; + } + } + } + + ps_codec->i4_sps_done = 1; + return ret; +} +",1,"IHEVCD_ERROR_T ihevcd_parse_sps(codec_t *ps_codec) +{ + IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS; + WORD32 value; + + WORD32 i; + WORD32 vps_id; + WORD32 sps_max_sub_layers; + WORD32 sps_id; + WORD32 sps_temporal_id_nesting_flag; + sps_t *ps_sps; + profile_tier_lvl_info_t s_ptl; + bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm; + WORD32 ctb_log2_size_y = 0; + + + BITS_PARSE(""video_parameter_set_id"", value, ps_bitstrm, 4); + vps_id = value; + vps_id = CLIP3(vps_id, 0, MAX_VPS_CNT - 1); + + BITS_PARSE(""sps_max_sub_layers_minus1"", value, ps_bitstrm, 3); + sps_max_sub_layers = value + 1; + sps_max_sub_layers = CLIP3(sps_max_sub_layers, 1, 7); + + BITS_PARSE(""sps_temporal_id_nesting_flag"", value, ps_bitstrm, 1); + sps_temporal_id_nesting_flag = value; + + ret = ihevcd_profile_tier_level(ps_bitstrm, &(s_ptl), 1, + (sps_max_sub_layers - 1)); + + UEV_PARSE(""seq_parameter_set_id"", value, ps_bitstrm); + sps_id = value; + + if((sps_id >= MAX_SPS_CNT) || (sps_id < 0)) + { + if(ps_codec->i4_sps_done) + return IHEVCD_UNSUPPORTED_SPS_ID; + else + sps_id = 0; + } + + + ps_sps = (ps_codec->s_parse.ps_sps_base + MAX_SPS_CNT - 1); + ps_sps->i1_sps_id = sps_id; + ps_sps->i1_vps_id = vps_id; + ps_sps->i1_sps_max_sub_layers = sps_max_sub_layers; + ps_sps->i1_sps_temporal_id_nesting_flag = sps_temporal_id_nesting_flag; + /* This is used only during initialization to get reorder count etc */ + ps_codec->i4_sps_id = sps_id; + memcpy(&ps_sps->s_ptl, &s_ptl, sizeof(profile_tier_lvl_info_t)); + + UEV_PARSE(""chroma_format_idc"", value, ps_bitstrm); + ps_sps->i1_chroma_format_idc = value; + + if(ps_sps->i1_chroma_format_idc != CHROMA_FMT_IDC_YUV420) + { + ps_codec->s_parse.i4_error_code = IHEVCD_UNSUPPORTED_CHROMA_FMT_IDC; + return (IHEVCD_ERROR_T)IHEVCD_UNSUPPORTED_CHROMA_FMT_IDC; + } + + if(CHROMA_FMT_IDC_YUV444_PLANES == ps_sps->i1_chroma_format_idc) + { + BITS_PARSE(""separate_colour_plane_flag"", value, ps_bitstrm, 1); + ps_sps->i1_separate_colour_plane_flag = value; + } + else + { + ps_sps->i1_separate_colour_plane_flag = 0; + } + + UEV_PARSE(""pic_width_in_luma_samples"", value, ps_bitstrm); + ps_sps->i2_pic_width_in_luma_samples = value; + + UEV_PARSE(""pic_height_in_luma_samples"", value, ps_bitstrm); + ps_sps->i2_pic_height_in_luma_samples = value; + + if((0 >= ps_sps->i2_pic_width_in_luma_samples) || (0 >= ps_sps->i2_pic_height_in_luma_samples)) + return IHEVCD_INVALID_PARAMETER; + + /* i2_pic_width_in_luma_samples and i2_pic_height_in_luma_samples + should be multiples of min_cb_size. Here these are aligned to 8, + i.e. smallest CB size */ + ps_sps->i2_pic_width_in_luma_samples = ALIGN8(ps_sps->i2_pic_width_in_luma_samples); + ps_sps->i2_pic_height_in_luma_samples = ALIGN8(ps_sps->i2_pic_height_in_luma_samples); + + BITS_PARSE(""pic_cropping_flag"", value, ps_bitstrm, 1); + ps_sps->i1_pic_cropping_flag = value; + + if(ps_sps->i1_pic_cropping_flag) + { + + UEV_PARSE(""pic_crop_left_offset"", value, ps_bitstrm); + ps_sps->i2_pic_crop_left_offset = value; + + UEV_PARSE(""pic_crop_right_offset"", value, ps_bitstrm); + ps_sps->i2_pic_crop_right_offset = value; + + UEV_PARSE(""pic_crop_top_offset"", value, ps_bitstrm); + ps_sps->i2_pic_crop_top_offset = value; + + UEV_PARSE(""pic_crop_bottom_offset"", value, ps_bitstrm); + ps_sps->i2_pic_crop_bottom_offset = value; + } + else + { + ps_sps->i2_pic_crop_left_offset = 0; + ps_sps->i2_pic_crop_right_offset = 0; + ps_sps->i2_pic_crop_top_offset = 0; + ps_sps->i2_pic_crop_bottom_offset = 0; + } + + + UEV_PARSE(""bit_depth_luma_minus8"", value, ps_bitstrm); + if(0 != value) + return IHEVCD_UNSUPPORTED_BIT_DEPTH; + + UEV_PARSE(""bit_depth_chroma_minus8"", value, ps_bitstrm); + if(0 != value) + return IHEVCD_UNSUPPORTED_BIT_DEPTH; + + UEV_PARSE(""log2_max_pic_order_cnt_lsb_minus4"", value, ps_bitstrm); + ps_sps->i1_log2_max_pic_order_cnt_lsb = value + 4; + + BITS_PARSE(""sps_sub_layer_ordering_info_present_flag"", value, ps_bitstrm, 1); + ps_sps->i1_sps_sub_layer_ordering_info_present_flag = value; + + + i = (ps_sps->i1_sps_sub_layer_ordering_info_present_flag ? 0 : (ps_sps->i1_sps_max_sub_layers - 1)); + for(; i < ps_sps->i1_sps_max_sub_layers; i++) + { + UEV_PARSE(""max_dec_pic_buffering"", value, ps_bitstrm); + ps_sps->ai1_sps_max_dec_pic_buffering[i] = value + 1; + + if(ps_sps->ai1_sps_max_dec_pic_buffering[i] > MAX_DPB_SIZE) + { + return IHEVCD_INVALID_PARAMETER; + } + + UEV_PARSE(""num_reorder_pics"", value, ps_bitstrm); + ps_sps->ai1_sps_max_num_reorder_pics[i] = value; + + if(ps_sps->ai1_sps_max_num_reorder_pics[i] > ps_sps->ai1_sps_max_dec_pic_buffering[i]) + { + return IHEVCD_INVALID_PARAMETER; + } + + UEV_PARSE(""max_latency_increase"", value, ps_bitstrm); + ps_sps->ai1_sps_max_latency_increase[i] = value; + } + UEV_PARSE(""log2_min_coding_block_size_minus3"", value, ps_bitstrm); + ps_sps->i1_log2_min_coding_block_size = value + 3; + + UEV_PARSE(""log2_diff_max_min_coding_block_size"", value, ps_bitstrm); + ps_sps->i1_log2_diff_max_min_coding_block_size = value; + + ctb_log2_size_y = ps_sps->i1_log2_min_coding_block_size + ps_sps->i1_log2_diff_max_min_coding_block_size; + + UEV_PARSE(""log2_min_transform_block_size_minus2"", value, ps_bitstrm); + ps_sps->i1_log2_min_transform_block_size = value + 2; + + UEV_PARSE(""log2_diff_max_min_transform_block_size"", value, ps_bitstrm); + ps_sps->i1_log2_diff_max_min_transform_block_size = value; + + ps_sps->i1_log2_max_transform_block_size = ps_sps->i1_log2_min_transform_block_size + + ps_sps->i1_log2_diff_max_min_transform_block_size; + + if ((ps_sps->i1_log2_max_transform_block_size < 0) || + (ps_sps->i1_log2_max_transform_block_size > MIN(ctb_log2_size_y, 5))) + { + return IHEVCD_INVALID_PARAMETER; + } + + ps_sps->i1_log2_ctb_size = ps_sps->i1_log2_min_coding_block_size + + ps_sps->i1_log2_diff_max_min_coding_block_size; + + if((ps_sps->i1_log2_min_coding_block_size < 3) || + (ps_sps->i1_log2_min_transform_block_size < 2) || + (ps_sps->i1_log2_diff_max_min_transform_block_size < 0) || + (ps_sps->i1_log2_max_transform_block_size > ps_sps->i1_log2_ctb_size) || + (ps_sps->i1_log2_ctb_size < 4) || + (ps_sps->i1_log2_ctb_size > 6)) + { + return IHEVCD_INVALID_PARAMETER; + } + + ps_sps->i1_log2_min_pcm_coding_block_size = 0; + ps_sps->i1_log2_diff_max_min_pcm_coding_block_size = 0; + + UEV_PARSE(""max_transform_hierarchy_depth_inter"", value, ps_bitstrm); + ps_sps->i1_max_transform_hierarchy_depth_inter = value; + + UEV_PARSE(""max_transform_hierarchy_depth_intra"", value, ps_bitstrm); + ps_sps->i1_max_transform_hierarchy_depth_intra = value; + + /* String has a d (enabled) in order to match with HM */ + BITS_PARSE(""scaling_list_enabled_flag"", value, ps_bitstrm, 1); + ps_sps->i1_scaling_list_enable_flag = value; + + if(ps_sps->i1_scaling_list_enable_flag) + { + COPY_DEFAULT_SCALING_LIST(ps_sps->pi2_scaling_mat); + BITS_PARSE(""sps_scaling_list_data_present_flag"", value, ps_bitstrm, 1); + ps_sps->i1_sps_scaling_list_data_present_flag = value; + + if(ps_sps->i1_sps_scaling_list_data_present_flag) + ihevcd_scaling_list_data(ps_codec, ps_sps->pi2_scaling_mat); + } + else + { + COPY_FLAT_SCALING_LIST(ps_sps->pi2_scaling_mat); + } + /* String is asymmetric_motion_partitions_enabled_flag instead of amp_enabled_flag in order to match with HM */ + BITS_PARSE(""asymmetric_motion_partitions_enabled_flag"", value, ps_bitstrm, 1); + ps_sps->i1_amp_enabled_flag = value; + + BITS_PARSE(""sample_adaptive_offset_enabled_flag"", value, ps_bitstrm, 1); + ps_sps->i1_sample_adaptive_offset_enabled_flag = value; + + BITS_PARSE(""pcm_enabled_flag"", value, ps_bitstrm, 1); + ps_sps->i1_pcm_enabled_flag = value; + + if(ps_sps->i1_pcm_enabled_flag) + { + BITS_PARSE(""pcm_sample_bit_depth_luma"", value, ps_bitstrm, 4); + ps_sps->i1_pcm_sample_bit_depth_luma = value + 1; + + BITS_PARSE(""pcm_sample_bit_depth_chroma"", value, ps_bitstrm, 4); + ps_sps->i1_pcm_sample_bit_depth_chroma = value + 1; + + UEV_PARSE(""log2_min_pcm_coding_block_size_minus3"", value, ps_bitstrm); + ps_sps->i1_log2_min_pcm_coding_block_size = value + 3; + + UEV_PARSE(""log2_diff_max_min_pcm_coding_block_size"", value, ps_bitstrm); + ps_sps->i1_log2_diff_max_min_pcm_coding_block_size = value; + BITS_PARSE(""pcm_loop_filter_disable_flag"", value, ps_bitstrm, 1); + ps_sps->i1_pcm_loop_filter_disable_flag = value; + + } + UEV_PARSE(""num_short_term_ref_pic_sets"", value, ps_bitstrm); + ps_sps->i1_num_short_term_ref_pic_sets = value; + + ps_sps->i1_num_short_term_ref_pic_sets = CLIP3(ps_sps->i1_num_short_term_ref_pic_sets, 0, MAX_STREF_PICS_SPS); + + for(i = 0; i < ps_sps->i1_num_short_term_ref_pic_sets; i++) + ihevcd_short_term_ref_pic_set(ps_bitstrm, &ps_sps->as_stref_picset[0], ps_sps->i1_num_short_term_ref_pic_sets, i, &ps_sps->as_stref_picset[i]); + + BITS_PARSE(""long_term_ref_pics_present_flag"", value, ps_bitstrm, 1); + ps_sps->i1_long_term_ref_pics_present_flag = value; + + if(ps_sps->i1_long_term_ref_pics_present_flag) + { + UEV_PARSE(""num_long_term_ref_pics_sps"", value, ps_bitstrm); + ps_sps->i1_num_long_term_ref_pics_sps = value; + + for(i = 0; i < ps_sps->i1_num_long_term_ref_pics_sps; i++) + { + BITS_PARSE(""lt_ref_pic_poc_lsb_sps[ i ]"", value, ps_bitstrm, ps_sps->i1_log2_max_pic_order_cnt_lsb); + ps_sps->ai1_lt_ref_pic_poc_lsb_sps[i] = value; + + BITS_PARSE(""used_by_curr_pic_lt_sps_flag[ i ]"", value, ps_bitstrm, 1); + ps_sps->ai1_used_by_curr_pic_lt_sps_flag[i] = value; + } + } + + BITS_PARSE(""sps_temporal_mvp_enable_flag"", value, ps_bitstrm, 1); + ps_sps->i1_sps_temporal_mvp_enable_flag = value; + + /* Print matches HM 8-2 */ + BITS_PARSE(""sps_strong_intra_smoothing_enable_flag"", value, ps_bitstrm, 1); + ps_sps->i1_strong_intra_smoothing_enable_flag = value; + + BITS_PARSE(""vui_parameters_present_flag"", value, ps_bitstrm, 1); + ps_sps->i1_vui_parameters_present_flag = value; + + if(ps_sps->i1_vui_parameters_present_flag) + ihevcd_parse_vui_parameters(ps_bitstrm, + &ps_sps->s_vui_parameters, + ps_sps->i1_sps_max_sub_layers - 1); + + + BITS_PARSE(""sps_extension_flag"", value, ps_bitstrm, 1); + + if((UWORD8 *)ps_bitstrm->pu4_buf > ps_bitstrm->pu1_buf_max) + { + return IHEVCD_INVALID_PARAMETER; + } + + { + WORD32 numerator; + WORD32 ceil_offset; + + ceil_offset = (1 << ps_sps->i1_log2_ctb_size) - 1; + numerator = ps_sps->i2_pic_width_in_luma_samples; + + ps_sps->i2_pic_wd_in_ctb = ((numerator + ceil_offset) / + (1 << ps_sps->i1_log2_ctb_size)); + + numerator = ps_sps->i2_pic_height_in_luma_samples; + ps_sps->i2_pic_ht_in_ctb = ((numerator + ceil_offset) / + (1 << ps_sps->i1_log2_ctb_size)); + + ps_sps->i4_pic_size_in_ctb = ps_sps->i2_pic_ht_in_ctb * + ps_sps->i2_pic_wd_in_ctb; + + if(0 == ps_codec->i4_sps_done) + ps_codec->s_parse.i4_next_ctb_indx = ps_sps->i4_pic_size_in_ctb; + + numerator = ps_sps->i2_pic_width_in_luma_samples; + ps_sps->i2_pic_wd_in_min_cb = numerator / + (1 << ps_sps->i1_log2_min_coding_block_size); + + numerator = ps_sps->i2_pic_height_in_luma_samples; + ps_sps->i2_pic_ht_in_min_cb = numerator / + (1 << ps_sps->i1_log2_min_coding_block_size); + } + if((0 != ps_codec->i4_first_pic_done) && + ((ps_codec->i4_wd != ps_sps->i2_pic_width_in_luma_samples) || + (ps_codec->i4_ht != ps_sps->i2_pic_height_in_luma_samples))) + { + ps_codec->i4_reset_flag = 1; + return (IHEVCD_ERROR_T)IVD_RES_CHANGED; + } + + /* Update display width and display height */ + { + WORD32 disp_wd, disp_ht; + WORD32 crop_unit_x, crop_unit_y; + crop_unit_x = 1; + crop_unit_y = 1; + + if(CHROMA_FMT_IDC_YUV420 == ps_sps->i1_chroma_format_idc) + { + crop_unit_x = 2; + crop_unit_y = 2; + } + + disp_wd = ps_sps->i2_pic_width_in_luma_samples; + disp_wd -= ps_sps->i2_pic_crop_left_offset * crop_unit_x; + disp_wd -= ps_sps->i2_pic_crop_right_offset * crop_unit_x; + + + disp_ht = ps_sps->i2_pic_height_in_luma_samples; + disp_ht -= ps_sps->i2_pic_crop_top_offset * crop_unit_y; + disp_ht -= ps_sps->i2_pic_crop_bottom_offset * crop_unit_y; + + if((0 >= disp_wd) || (0 >= disp_ht)) + return IHEVCD_INVALID_PARAMETER; + + ps_codec->i4_disp_wd = disp_wd; + ps_codec->i4_disp_ht = disp_ht; + + + ps_codec->i4_wd = ps_sps->i2_pic_width_in_luma_samples; + ps_codec->i4_ht = ps_sps->i2_pic_height_in_luma_samples; + + { + WORD32 ref_strd; + ref_strd = ALIGN32(ps_sps->i2_pic_width_in_luma_samples + PAD_WD); + if(ps_codec->i4_strd < ref_strd) + { + ps_codec->i4_strd = ref_strd; + } + } + + if(0 == ps_codec->i4_share_disp_buf) + { + if(ps_codec->i4_disp_strd < ps_codec->i4_disp_wd) + { + ps_codec->i4_disp_strd = ps_codec->i4_disp_wd; + } + } + else + { + if(ps_codec->i4_disp_strd < ps_codec->i4_strd) + { + ps_codec->i4_disp_strd = ps_codec->i4_strd; + } + } + } + + ps_codec->i4_sps_done = 1; + return ret; +} +","@@ -1462,6 +1462,10 @@ + + + BITS_PARSE(""sps_extension_flag"", value, ps_bitstrm, 1); + ++ if((UWORD8 *)ps_bitstrm->pu4_buf > ps_bitstrm->pu1_buf_max) ++ { ++ return IHEVCD_INVALID_PARAMETER; ++ } + + { + WORD32 numerator; +",4127,4458,6144 +1571,"int udhcpc_main(int argc UNUSED_PARAM, char **argv) +{ + uint8_t *message; + const char *str_V, *str_h, *str_F, *str_r; + IF_FEATURE_UDHCPC_ARPING(const char *str_a = ""2000"";) + IF_FEATURE_UDHCP_PORT(char *str_P;) + void *clientid_mac_ptr; + llist_t *list_O = NULL; + llist_t *list_x = NULL; + int tryagain_timeout = 20; + int discover_timeout = 3; + int discover_retries = 3; + uint32_t server_addr = server_addr; /* for compiler */ + uint32_t requested_ip = 0; + uint32_t xid = xid; /* for compiler */ + int packet_num; + int timeout; /* must be signed */ + unsigned already_waited_sec; + unsigned opt; + IF_FEATURE_UDHCPC_ARPING(unsigned arpping_ms;) + int max_fd; + int retval; + fd_set rfds; + + /* Default options */ + IF_FEATURE_UDHCP_PORT(SERVER_PORT = 67;) + IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 68;) + client_config.interface = ""eth0""; + client_config.script = CONFIG_UDHCPC_DEFAULT_SCRIPT; + str_V = ""udhcp ""BB_VER; + + /* Parse command line */ + /* O,x: list; -T,-t,-A take numeric param */ + opt_complementary = ""O::x::T+:t+:A+"" IF_UDHCP_VERBOSE("":vv"") ; + IF_LONG_OPTS(applet_long_options = udhcpc_longopts;) + opt = getopt32(argv, ""CV:H:h:F:i:np:qRr:s:T:t:SA:O:ox:fB"" + USE_FOR_MMU(""b"") + IF_FEATURE_UDHCPC_ARPING(""a::"") + IF_FEATURE_UDHCP_PORT(""P:"") + ""v"" + , &str_V, &str_h, &str_h, &str_F + , &client_config.interface, &client_config.pidfile, &str_r /* i,p */ + , &client_config.script /* s */ + , &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */ + , &list_O + , &list_x + IF_FEATURE_UDHCPC_ARPING(, &str_a) + IF_FEATURE_UDHCP_PORT(, &str_P) + IF_UDHCP_VERBOSE(, &dhcp_verbose) + ); + if (opt & (OPT_h|OPT_H)) { + bb_error_msg(""option -h NAME is deprecated, use -x hostname:NAME""); + client_config.hostname = alloc_dhcp_option(DHCP_HOST_NAME, str_h, 0); + } + if (opt & OPT_F) { + /* FQDN option format: [0x51][len][flags][0][0] */ + client_config.fqdn = alloc_dhcp_option(DHCP_FQDN, str_F, 3); + /* Flag bits: 0000NEOS + * S: 1 = Client requests server to update A RR in DNS as well as PTR + * O: 1 = Server indicates to client that DNS has been updated regardless + * E: 1 = Name is in DNS format, i.e. <4>host<6>domain<3>com<0>, + * not ""host.domain.com"". Format 0 is obsolete. + * N: 1 = Client requests server to not update DNS (S must be 0 then) + * Two [0] bytes which follow are deprecated and must be 0. + */ + client_config.fqdn[OPT_DATA + 0] = 0x1; + /*client_config.fqdn[OPT_DATA + 1] = 0; - xzalloc did it */ + /*client_config.fqdn[OPT_DATA + 2] = 0; */ + } + if (opt & OPT_r) + requested_ip = inet_addr(str_r); +#if ENABLE_FEATURE_UDHCP_PORT + if (opt & OPT_P) { + CLIENT_PORT = xatou16(str_P); + SERVER_PORT = CLIENT_PORT - 1; + } +#endif + IF_FEATURE_UDHCPC_ARPING(arpping_ms = xatou(str_a);) + while (list_O) { + char *optstr = llist_pop(&list_O); + unsigned n = bb_strtou(optstr, NULL, 0); + if (errno || n > 254) { + n = udhcp_option_idx(optstr); + n = dhcp_optflags[n].code; + } + client_config.opt_mask[n >> 3] |= 1 << (n & 7); + } + if (!(opt & OPT_o)) { + unsigned i, n; + for (i = 0; (n = dhcp_optflags[i].code) != 0; i++) { + if (dhcp_optflags[i].flags & OPTION_REQ) { + client_config.opt_mask[n >> 3] |= 1 << (n & 7); + } + } + } + while (list_x) { + char *optstr = llist_pop(&list_x); + char *colon = strchr(optstr, ':'); + if (colon) + *colon = ' '; + /* now it looks similar to udhcpd's config file line: + * ""optname optval"", using the common routine: */ + udhcp_str2optset(optstr, &client_config.options); + } + + if (udhcp_read_interface(client_config.interface, + &client_config.ifindex, + NULL, + client_config.client_mac) + ) { + return 1; + } + + clientid_mac_ptr = NULL; + if (!(opt & OPT_C) && !udhcp_find_option(client_config.options, DHCP_CLIENT_ID)) { + /* not suppressed and not set, set the default client ID */ + client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, """", 7); + client_config.clientid[OPT_DATA] = 1; /* type: ethernet */ + clientid_mac_ptr = client_config.clientid + OPT_DATA+1; + memcpy(clientid_mac_ptr, client_config.client_mac, 6); + } + if (str_V[0] != '\0') { + client_config.vendorclass = alloc_dhcp_option(DHCP_VENDOR, str_V, 0); + } + +#if !BB_MMU + /* on NOMMU reexec (i.e., background) early */ + if (!(opt & OPT_f)) { + bb_daemonize_or_rexec(0 /* flags */, argv); + logmode = LOGMODE_NONE; + } +#endif + if (opt & OPT_S) { + openlog(applet_name, LOG_PID, LOG_DAEMON); + logmode |= LOGMODE_SYSLOG; + } + + /* Make sure fd 0,1,2 are open */ + bb_sanitize_stdio(); + /* Equivalent of doing a fflush after every \n */ + setlinebuf(stdout); + /* Create pidfile */ + write_pidfile(client_config.pidfile); + /* Goes to stdout (unless NOMMU) and possibly syslog */ + bb_info_msg(""%s (v""BB_VER"") started"", applet_name); + /* Set up the signal pipe */ + udhcp_sp_setup(); + /* We want random_xid to be random... */ + srand(monotonic_us()); + + state = INIT_SELECTING; + udhcp_run_script(NULL, ""deconfig""); + change_listen_mode(LISTEN_RAW); + packet_num = 0; + timeout = 0; + already_waited_sec = 0; + + /* Main event loop. select() waits on signal pipe and possibly + * on sockfd. + * ""continue"" statements in code below jump to the top of the loop. + */ + for (;;) { + struct timeval tv; + struct dhcp_packet packet; + /* silence ""uninitialized!"" warning */ + unsigned timestamp_before_wait = timestamp_before_wait; + + + /* Was opening raw or udp socket here + * if (listen_mode != LISTEN_NONE && sockfd < 0), + * but on fast network renew responses return faster + * than we open sockets. Thus this code is moved + * to change_listen_mode(). Thus we open listen socket + * BEFORE we send renew request (see ""case BOUND:""). */ + + max_fd = udhcp_sp_fd_set(&rfds, sockfd); + + tv.tv_sec = timeout - already_waited_sec; + tv.tv_usec = 0; + retval = 0; + /* If we already timed out, fall through with retval = 0, else... */ + if ((int)tv.tv_sec > 0) { + log1(""Waiting on select %u seconds"", (int)tv.tv_sec); + timestamp_before_wait = (unsigned)monotonic_sec(); + retval = select(max_fd + 1, &rfds, NULL, NULL, &tv); + if (retval < 0) { + /* EINTR? A signal was caught, don't panic */ + if (errno == EINTR) { + already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait; + continue; + } + /* Else: an error occured, panic! */ + bb_perror_msg_and_die(""select""); + } + } + + /* If timeout dropped to zero, time to become active: + * resend discover/renew/whatever + */ + if (retval == 0) { + /* When running on a bridge, the ifindex may have changed + * (e.g. if member interfaces were added/removed + * or if the status of the bridge changed). + * Refresh ifindex and client_mac: + */ + if (udhcp_read_interface(client_config.interface, + &client_config.ifindex, + NULL, + client_config.client_mac) + ) { + goto ret0; /* iface is gone? */ + } + if (clientid_mac_ptr) + memcpy(clientid_mac_ptr, client_config.client_mac, 6); + + /* We will restart the wait in any case */ + already_waited_sec = 0; + + switch (state) { + case INIT_SELECTING: + if (!discover_retries || packet_num < discover_retries) { + if (packet_num == 0) + xid = random_xid(); + /* broadcast */ + send_discover(xid, requested_ip); + timeout = discover_timeout; + packet_num++; + continue; + } + leasefail: + udhcp_run_script(NULL, ""leasefail""); +#if BB_MMU /* -b is not supported on NOMMU */ + if (opt & OPT_b) { /* background if no lease */ + bb_info_msg(""No lease, forking to background""); + client_background(); + /* do not background again! */ + opt = ((opt & ~OPT_b) | OPT_f); + } else +#endif + if (opt & OPT_n) { /* abort if no lease */ + bb_info_msg(""No lease, failing""); + retval = 1; + goto ret; + } + /* wait before trying again */ + timeout = tryagain_timeout; + packet_num = 0; + continue; + case REQUESTING: + if (!discover_retries || packet_num < discover_retries) { + /* send broadcast select packet */ + send_select(xid, server_addr, requested_ip); + timeout = discover_timeout; + packet_num++; + continue; + } + /* Timed out, go back to init state. + * ""discover...select...discover..."" loops + * were seen in the wild. Treat them similarly + * to ""no response to discover"" case */ + change_listen_mode(LISTEN_RAW); + state = INIT_SELECTING; + goto leasefail; + case BOUND: + /* 1/2 lease passed, enter renewing state */ + state = RENEWING; + client_config.first_secs = 0; /* make secs field count from 0 */ + change_listen_mode(LISTEN_KERNEL); + log1(""Entering renew state""); + /* fall right through */ + case RENEW_REQUESTED: /* manual (SIGUSR1) renew */ + case_RENEW_REQUESTED: + case RENEWING: + if (timeout > 60) { + /* send an unicast renew request */ + /* Sometimes observed to fail (EADDRNOTAVAIL) to bind + * a new UDP socket for sending inside send_renew. + * I hazard to guess existing listening socket + * is somehow conflicting with it, but why is it + * not deterministic then?! Strange. + * Anyway, it does recover by eventually failing through + * into INIT_SELECTING state. + */ + send_renew(xid, server_addr, requested_ip); + timeout >>= 1; + continue; + } + /* Timed out, enter rebinding state */ + log1(""Entering rebinding state""); + state = REBINDING; + /* fall right through */ + case REBINDING: + /* Switch to bcast receive */ + change_listen_mode(LISTEN_RAW); + /* Lease is *really* about to run out, + * try to find DHCP server using broadcast */ + if (timeout > 0) { + /* send a broadcast renew request */ + send_renew(xid, 0 /*INADDR_ANY*/, requested_ip); + timeout >>= 1; + continue; + } + /* Timed out, enter init state */ + bb_info_msg(""Lease lost, entering init state""); + udhcp_run_script(NULL, ""deconfig""); + state = INIT_SELECTING; + client_config.first_secs = 0; /* make secs field count from 0 */ + /*timeout = 0; - already is */ + packet_num = 0; + continue; + /* case RELEASED: */ + } + /* yah, I know, *you* say it would never happen */ + timeout = INT_MAX; + continue; /* back to main loop */ + } /* if select timed out */ + + /* select() didn't timeout, something happened */ + + /* Is it a signal? */ + /* note: udhcp_sp_read checks FD_ISSET before reading */ + switch (udhcp_sp_read(&rfds)) { + case SIGUSR1: + client_config.first_secs = 0; /* make secs field count from 0 */ + already_waited_sec = 0; + perform_renew(); + if (state == RENEW_REQUESTED) { + /* We might be either on the same network + * (in which case renew might work), + * or we might be on a completely different one + * (in which case renew won't ever succeed). + * For the second case, must make sure timeout + * is not too big, or else we can send + * futile renew requests for hours. + * (Ab)use -A TIMEOUT value (usually 20 sec) + * as a cap on the timeout. + */ + if (timeout > tryagain_timeout) + timeout = tryagain_timeout; + goto case_RENEW_REQUESTED; + } + /* Start things over */ + packet_num = 0; + /* Kill any timeouts, user wants this to hurry along */ + timeout = 0; + continue; + case SIGUSR2: + perform_release(server_addr, requested_ip); + timeout = INT_MAX; + continue; + case SIGTERM: + bb_info_msg(""Received SIGTERM""); + goto ret0; + } + + /* Is it a packet? */ + if (listen_mode == LISTEN_NONE || !FD_ISSET(sockfd, &rfds)) + continue; /* no */ + + { + int len; + + /* A packet is ready, read it */ + if (listen_mode == LISTEN_KERNEL) + len = udhcp_recv_kernel_packet(&packet, sockfd); + else + len = udhcp_recv_raw_packet(&packet, sockfd); + if (len == -1) { + /* Error is severe, reopen socket */ + bb_info_msg(""Read error: %s, reopening socket"", strerror(errno)); + sleep(discover_timeout); /* 3 seconds by default */ + change_listen_mode(listen_mode); /* just close and reopen */ + } + /* If this packet will turn out to be unrelated/bogus, + * we will go back and wait for next one. + * Be sure timeout is properly decreased. */ + already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait; + if (len < 0) + continue; + } + + if (packet.xid != xid) { + log1(""xid %x (our is %x), ignoring packet"", + (unsigned)packet.xid, (unsigned)xid); + continue; + } + + /* Ignore packets that aren't for us */ + if (packet.hlen != 6 + || memcmp(packet.chaddr, client_config.client_mac, 6) != 0 + ) { + log1(""chaddr does not match, ignoring packet""); // log2? + continue; + } + + message = udhcp_get_option(&packet, DHCP_MESSAGE_TYPE); + if (message == NULL) { + bb_error_msg(""no message type option, ignoring packet""); + continue; + } + + switch (state) { + case INIT_SELECTING: + /* Must be a DHCPOFFER */ + if (*message == DHCPOFFER) { + uint8_t *temp; + +/* What exactly is server's IP? There are several values. + * Example DHCP offer captured with tchdump: + * + * 10.34.25.254:67 > 10.34.25.202:68 // IP header's src + * BOOTP fields: + * Your-IP 10.34.25.202 + * Server-IP 10.34.32.125 // ""next server"" IP + * Gateway-IP 10.34.25.254 // relay's address (if DHCP relays are in use) + * DHCP options: + * DHCP-Message Option 53, length 1: Offer + * Server-ID Option 54, length 4: 10.34.255.7 // ""server ID"" + * Default-Gateway Option 3, length 4: 10.34.25.254 // router + * + * We think that real server IP (one to use in renew/release) + * is one in Server-ID option. But I am not 100% sure. + * IP header's src and Gateway-IP (same in this example) + * might work too. + * ""Next server"" and router are definitely wrong ones to use, though... + */ +/* We used to ignore pcakets without DHCP_SERVER_ID. + * I've got user reports from people who run ""address-less"" servers. + * They either supply DHCP_SERVER_ID of 0.0.0.0 or don't supply it at all. + * They say ISC DHCP client supports this case. + */ + server_addr = 0; + temp = udhcp_get_option(&packet, DHCP_SERVER_ID); + if (!temp) { + bb_error_msg(""no server ID, using 0.0.0.0""); + } else { + /* it IS unaligned sometimes, don't ""optimize"" */ + move_from_unaligned32(server_addr, temp); + } + /*xid = packet.xid; - already is */ + requested_ip = packet.yiaddr; + + /* enter requesting state */ + state = REQUESTING; + timeout = 0; + packet_num = 0; + already_waited_sec = 0; + } + continue; + case REQUESTING: + case RENEWING: + case RENEW_REQUESTED: + case REBINDING: + if (*message == DHCPACK) { + unsigned start; + uint32_t lease_seconds; + struct in_addr temp_addr; + uint8_t *temp; + + temp = udhcp_get_option(&packet, DHCP_LEASE_TIME); + if (!temp) { + bb_error_msg(""no lease time with ACK, using 1 hour lease""); + lease_seconds = 60 * 60; + } else { + /* it IS unaligned sometimes, don't ""optimize"" */ + move_from_unaligned32(lease_seconds, temp); + lease_seconds = ntohl(lease_seconds); + /* paranoia: must not be too small and not prone to overflows */ + if (lease_seconds < 0x10) + lease_seconds = 0x10; + if (lease_seconds >= 0x10000000) + lease_seconds = 0x0fffffff; + } +#if ENABLE_FEATURE_UDHCPC_ARPING + if (opt & OPT_a) { +/* RFC 2131 3.1 paragraph 5: + * ""The client receives the DHCPACK message with configuration + * parameters. The client SHOULD perform a final check on the + * parameters (e.g., ARP for allocated network address), and notes + * the duration of the lease specified in the DHCPACK message. At this + * point, the client is configured. If the client detects that the + * address is already in use (e.g., through the use of ARP), + * the client MUST send a DHCPDECLINE message to the server and restarts + * the configuration process..."" */ + if (!arpping(packet.yiaddr, + NULL, + (uint32_t) 0, + client_config.client_mac, + client_config.interface, + arpping_ms) + ) { + bb_info_msg(""Offered address is in use "" + ""(got ARP reply), declining""); + send_decline(/*xid,*/ server_addr, packet.yiaddr); + + if (state != REQUESTING) + udhcp_run_script(NULL, ""deconfig""); + change_listen_mode(LISTEN_RAW); + state = INIT_SELECTING; + client_config.first_secs = 0; /* make secs field count from 0 */ + requested_ip = 0; + timeout = tryagain_timeout; + packet_num = 0; + already_waited_sec = 0; + continue; /* back to main loop */ + } + } +#endif + /* enter bound state */ + temp_addr.s_addr = packet.yiaddr; + bb_info_msg(""Lease of %s obtained, lease time %u"", + inet_ntoa(temp_addr), (unsigned)lease_seconds); + requested_ip = packet.yiaddr; + + start = monotonic_sec(); + udhcp_run_script(&packet, state == REQUESTING ? ""bound"" : ""renew""); + already_waited_sec = (unsigned)monotonic_sec() - start; + timeout = lease_seconds / 2; + if ((unsigned)timeout < already_waited_sec) { + /* Something went wrong. Back to discover state */ + timeout = already_waited_sec = 0; + } + + state = BOUND; + change_listen_mode(LISTEN_NONE); + if (opt & OPT_q) { /* quit after lease */ + goto ret0; + } + /* future renew failures should not exit (JM) */ + opt &= ~OPT_n; +#if BB_MMU /* NOMMU case backgrounded earlier */ + if (!(opt & OPT_f)) { + client_background(); + /* do not background again! */ + opt = ((opt & ~OPT_b) | OPT_f); + } +#endif + /* make future renew packets use different xid */ + /* xid = random_xid(); ...but why bother? */ + + continue; /* back to main loop */ + } + if (*message == DHCPNAK) { + /* If network has more than one DHCP server, + * ""wrong"" server can reply first, with a NAK. + * Do not interpret it as a NAK from ""our"" server. + */ + if (server_addr != 0) { + uint32_t svid; + uint8_t *temp; + + temp = udhcp_get_option(&packet, DHCP_SERVER_ID); + if (!temp) { + non_matching_svid: + log1(""%s with wrong server ID, ignoring packet"", + ""Received DHCP NAK"" + ); + continue; + } + move_from_unaligned32(svid, temp); + if (svid != server_addr) + goto non_matching_svid; + } + /* return to init state */ + bb_info_msg(""Received DHCP NAK""); + udhcp_run_script(&packet, ""nak""); + if (state != REQUESTING) + udhcp_run_script(NULL, ""deconfig""); + change_listen_mode(LISTEN_RAW); + sleep(3); /* avoid excessive network traffic */ + state = INIT_SELECTING; + client_config.first_secs = 0; /* make secs field count from 0 */ + requested_ip = 0; + timeout = 0; + packet_num = 0; + already_waited_sec = 0; + } + continue; + /* case BOUND: - ignore all packets */ + /* case RELEASED: - ignore all packets */ + } + /* back to main loop */ + } /* for (;;) - main loop ends */ + + ret0: + if (opt & OPT_R) /* release on quit */ + perform_release(server_addr, requested_ip); + retval = 0; + ret: + /*if (client_config.pidfile) - remove_pidfile has its own check */ + remove_pidfile(client_config.pidfile); + return retval; +} +",0,"int udhcpc_main(int argc UNUSED_PARAM, char **argv) +{ + uint8_t *message; + const char *str_V, *str_h, *str_F, *str_r; + IF_FEATURE_UDHCPC_ARPING(const char *str_a = ""2000"";) + IF_FEATURE_UDHCP_PORT(char *str_P;) + void *clientid_mac_ptr; + llist_t *list_O = NULL; + llist_t *list_x = NULL; + int tryagain_timeout = 20; + int discover_timeout = 3; + int discover_retries = 3; + uint32_t server_addr = server_addr; /* for compiler */ + uint32_t requested_ip = 0; + uint32_t xid = xid; /* for compiler */ + int packet_num; + int timeout; /* must be signed */ + unsigned already_waited_sec; + unsigned opt; + IF_FEATURE_UDHCPC_ARPING(unsigned arpping_ms;) + int max_fd; + int retval; + fd_set rfds; + + /* Default options */ + IF_FEATURE_UDHCP_PORT(SERVER_PORT = 67;) + IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 68;) + client_config.interface = ""eth0""; + client_config.script = CONFIG_UDHCPC_DEFAULT_SCRIPT; + str_V = ""udhcp ""BB_VER; + + /* Parse command line */ + /* O,x: list; -T,-t,-A take numeric param */ + opt_complementary = ""O::x::T+:t+:A+"" IF_UDHCP_VERBOSE("":vv"") ; + IF_LONG_OPTS(applet_long_options = udhcpc_longopts;) + opt = getopt32(argv, ""CV:H:h:F:i:np:qRr:s:T:t:SA:O:ox:fB"" + USE_FOR_MMU(""b"") + IF_FEATURE_UDHCPC_ARPING(""a::"") + IF_FEATURE_UDHCP_PORT(""P:"") + ""v"" + , &str_V, &str_h, &str_h, &str_F + , &client_config.interface, &client_config.pidfile, &str_r /* i,p */ + , &client_config.script /* s */ + , &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */ + , &list_O + , &list_x + IF_FEATURE_UDHCPC_ARPING(, &str_a) + IF_FEATURE_UDHCP_PORT(, &str_P) + IF_UDHCP_VERBOSE(, &dhcp_verbose) + ); + if (opt & (OPT_h|OPT_H)) { + bb_error_msg(""option -h NAME is deprecated, use -x hostname:NAME""); + client_config.hostname = alloc_dhcp_option(DHCP_HOST_NAME, str_h, 0); + } + if (opt & OPT_F) { + /* FQDN option format: [0x51][len][flags][0][0] */ + client_config.fqdn = alloc_dhcp_option(DHCP_FQDN, str_F, 3); + /* Flag bits: 0000NEOS + * S: 1 = Client requests server to update A RR in DNS as well as PTR + * O: 1 = Server indicates to client that DNS has been updated regardless + * E: 1 = Name is in DNS format, i.e. <4>host<6>domain<3>com<0>, + * not ""host.domain.com"". Format 0 is obsolete. + * N: 1 = Client requests server to not update DNS (S must be 0 then) + * Two [0] bytes which follow are deprecated and must be 0. + */ + client_config.fqdn[OPT_DATA + 0] = 0x1; + /*client_config.fqdn[OPT_DATA + 1] = 0; - xzalloc did it */ + /*client_config.fqdn[OPT_DATA + 2] = 0; */ + } + if (opt & OPT_r) + requested_ip = inet_addr(str_r); +#if ENABLE_FEATURE_UDHCP_PORT + if (opt & OPT_P) { + CLIENT_PORT = xatou16(str_P); + SERVER_PORT = CLIENT_PORT - 1; + } +#endif + IF_FEATURE_UDHCPC_ARPING(arpping_ms = xatou(str_a);) + while (list_O) { + char *optstr = llist_pop(&list_O); + unsigned n = bb_strtou(optstr, NULL, 0); + if (errno || n > 254) { + n = udhcp_option_idx(optstr); + n = dhcp_optflags[n].code; + } + client_config.opt_mask[n >> 3] |= 1 << (n & 7); + } + if (!(opt & OPT_o)) { + unsigned i, n; + for (i = 0; (n = dhcp_optflags[i].code) != 0; i++) { + if (dhcp_optflags[i].flags & OPTION_REQ) { + client_config.opt_mask[n >> 3] |= 1 << (n & 7); + } + } + } + while (list_x) { + char *optstr = llist_pop(&list_x); + char *colon = strchr(optstr, ':'); + if (colon) + *colon = ' '; + /* now it looks similar to udhcpd's config file line: + * ""optname optval"", using the common routine: */ + udhcp_str2optset(optstr, &client_config.options); + } + + if (udhcp_read_interface(client_config.interface, + &client_config.ifindex, + NULL, + client_config.client_mac) + ) { + return 1; + } + + clientid_mac_ptr = NULL; + if (!(opt & OPT_C) && !udhcp_find_option(client_config.options, DHCP_CLIENT_ID)) { + /* not suppressed and not set, set the default client ID */ + client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, """", 7); + client_config.clientid[OPT_DATA] = 1; /* type: ethernet */ + clientid_mac_ptr = client_config.clientid + OPT_DATA+1; + memcpy(clientid_mac_ptr, client_config.client_mac, 6); + } + if (str_V[0] != '\0') { + client_config.vendorclass = alloc_dhcp_option(DHCP_VENDOR, str_V, 0); + } + +#if !BB_MMU + /* on NOMMU reexec (i.e., background) early */ + if (!(opt & OPT_f)) { + bb_daemonize_or_rexec(0 /* flags */, argv); + logmode = LOGMODE_NONE; + } +#endif + if (opt & OPT_S) { + openlog(applet_name, LOG_PID, LOG_DAEMON); + logmode |= LOGMODE_SYSLOG; + } + + /* Make sure fd 0,1,2 are open */ + bb_sanitize_stdio(); + /* Equivalent of doing a fflush after every \n */ + setlinebuf(stdout); + /* Create pidfile */ + write_pidfile(client_config.pidfile); + /* Goes to stdout (unless NOMMU) and possibly syslog */ + bb_info_msg(""%s (v""BB_VER"") started"", applet_name); + /* Set up the signal pipe */ + udhcp_sp_setup(); + /* We want random_xid to be random... */ + srand(monotonic_us()); + + state = INIT_SELECTING; + udhcp_run_script(NULL, ""deconfig""); + change_listen_mode(LISTEN_RAW); + packet_num = 0; + timeout = 0; + already_waited_sec = 0; + + /* Main event loop. select() waits on signal pipe and possibly + * on sockfd. + * ""continue"" statements in code below jump to the top of the loop. + */ + for (;;) { + struct timeval tv; + struct dhcp_packet packet; + /* silence ""uninitialized!"" warning */ + unsigned timestamp_before_wait = timestamp_before_wait; + + + /* Was opening raw or udp socket here + * if (listen_mode != LISTEN_NONE && sockfd < 0), + * but on fast network renew responses return faster + * than we open sockets. Thus this code is moved + * to change_listen_mode(). Thus we open listen socket + * BEFORE we send renew request (see ""case BOUND:""). */ + + max_fd = udhcp_sp_fd_set(&rfds, sockfd); + + tv.tv_sec = timeout - already_waited_sec; + tv.tv_usec = 0; + retval = 0; + /* If we already timed out, fall through with retval = 0, else... */ + if ((int)tv.tv_sec > 0) { + log1(""Waiting on select %u seconds"", (int)tv.tv_sec); + timestamp_before_wait = (unsigned)monotonic_sec(); + retval = select(max_fd + 1, &rfds, NULL, NULL, &tv); + if (retval < 0) { + /* EINTR? A signal was caught, don't panic */ + if (errno == EINTR) { + already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait; + continue; + } + /* Else: an error occured, panic! */ + bb_perror_msg_and_die(""select""); + } + } + + /* If timeout dropped to zero, time to become active: + * resend discover/renew/whatever + */ + if (retval == 0) { + /* When running on a bridge, the ifindex may have changed + * (e.g. if member interfaces were added/removed + * or if the status of the bridge changed). + * Refresh ifindex and client_mac: + */ + if (udhcp_read_interface(client_config.interface, + &client_config.ifindex, + NULL, + client_config.client_mac) + ) { + goto ret0; /* iface is gone? */ + } + if (clientid_mac_ptr) + memcpy(clientid_mac_ptr, client_config.client_mac, 6); + + /* We will restart the wait in any case */ + already_waited_sec = 0; + + switch (state) { + case INIT_SELECTING: + if (!discover_retries || packet_num < discover_retries) { + if (packet_num == 0) + xid = random_xid(); + /* broadcast */ + send_discover(xid, requested_ip); + timeout = discover_timeout; + packet_num++; + continue; + } + leasefail: + udhcp_run_script(NULL, ""leasefail""); +#if BB_MMU /* -b is not supported on NOMMU */ + if (opt & OPT_b) { /* background if no lease */ + bb_info_msg(""No lease, forking to background""); + client_background(); + /* do not background again! */ + opt = ((opt & ~OPT_b) | OPT_f); + } else +#endif + if (opt & OPT_n) { /* abort if no lease */ + bb_info_msg(""No lease, failing""); + retval = 1; + goto ret; + } + /* wait before trying again */ + timeout = tryagain_timeout; + packet_num = 0; + continue; + case REQUESTING: + if (!discover_retries || packet_num < discover_retries) { + /* send broadcast select packet */ + send_select(xid, server_addr, requested_ip); + timeout = discover_timeout; + packet_num++; + continue; + } + /* Timed out, go back to init state. + * ""discover...select...discover..."" loops + * were seen in the wild. Treat them similarly + * to ""no response to discover"" case */ + change_listen_mode(LISTEN_RAW); + state = INIT_SELECTING; + goto leasefail; + case BOUND: + /* 1/2 lease passed, enter renewing state */ + state = RENEWING; + client_config.first_secs = 0; /* make secs field count from 0 */ + change_listen_mode(LISTEN_KERNEL); + log1(""Entering renew state""); + /* fall right through */ + case RENEW_REQUESTED: /* manual (SIGUSR1) renew */ + case_RENEW_REQUESTED: + case RENEWING: + if (timeout > 60) { + /* send an unicast renew request */ + /* Sometimes observed to fail (EADDRNOTAVAIL) to bind + * a new UDP socket for sending inside send_renew. + * I hazard to guess existing listening socket + * is somehow conflicting with it, but why is it + * not deterministic then?! Strange. + * Anyway, it does recover by eventually failing through + * into INIT_SELECTING state. + */ + send_renew(xid, server_addr, requested_ip); + timeout >>= 1; + continue; + } + /* Timed out, enter rebinding state */ + log1(""Entering rebinding state""); + state = REBINDING; + /* fall right through */ + case REBINDING: + /* Switch to bcast receive */ + change_listen_mode(LISTEN_RAW); + /* Lease is *really* about to run out, + * try to find DHCP server using broadcast */ + if (timeout > 0) { + /* send a broadcast renew request */ + send_renew(xid, 0 /*INADDR_ANY*/, requested_ip); + timeout >>= 1; + continue; + } + /* Timed out, enter init state */ + bb_info_msg(""Lease lost, entering init state""); + udhcp_run_script(NULL, ""deconfig""); + state = INIT_SELECTING; + client_config.first_secs = 0; /* make secs field count from 0 */ + /*timeout = 0; - already is */ + packet_num = 0; + continue; + /* case RELEASED: */ + } + /* yah, I know, *you* say it would never happen */ + timeout = INT_MAX; + continue; /* back to main loop */ + } /* if select timed out */ + + /* select() didn't timeout, something happened */ + + /* Is it a signal? */ + /* note: udhcp_sp_read checks FD_ISSET before reading */ + switch (udhcp_sp_read(&rfds)) { + case SIGUSR1: + client_config.first_secs = 0; /* make secs field count from 0 */ + already_waited_sec = 0; + perform_renew(); + if (state == RENEW_REQUESTED) { + /* We might be either on the same network + * (in which case renew might work), + * or we might be on a completely different one + * (in which case renew won't ever succeed). + * For the second case, must make sure timeout + * is not too big, or else we can send + * futile renew requests for hours. + * (Ab)use -A TIMEOUT value (usually 20 sec) + * as a cap on the timeout. + */ + if (timeout > tryagain_timeout) + timeout = tryagain_timeout; + goto case_RENEW_REQUESTED; + } + /* Start things over */ + packet_num = 0; + /* Kill any timeouts, user wants this to hurry along */ + timeout = 0; + continue; + case SIGUSR2: + perform_release(server_addr, requested_ip); + timeout = INT_MAX; + continue; + case SIGTERM: + bb_info_msg(""Received SIGTERM""); + goto ret0; + } + + /* Is it a packet? */ + if (listen_mode == LISTEN_NONE || !FD_ISSET(sockfd, &rfds)) + continue; /* no */ + + { + int len; + + /* A packet is ready, read it */ + if (listen_mode == LISTEN_KERNEL) + len = udhcp_recv_kernel_packet(&packet, sockfd); + else + len = udhcp_recv_raw_packet(&packet, sockfd); + if (len == -1) { + /* Error is severe, reopen socket */ + bb_info_msg(""Read error: %s, reopening socket"", strerror(errno)); + sleep(discover_timeout); /* 3 seconds by default */ + change_listen_mode(listen_mode); /* just close and reopen */ + } + /* If this packet will turn out to be unrelated/bogus, + * we will go back and wait for next one. + * Be sure timeout is properly decreased. */ + already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait; + if (len < 0) + continue; + } + + if (packet.xid != xid) { + log1(""xid %x (our is %x), ignoring packet"", + (unsigned)packet.xid, (unsigned)xid); + continue; + } + + /* Ignore packets that aren't for us */ + if (packet.hlen != 6 + || memcmp(packet.chaddr, client_config.client_mac, 6) != 0 + ) { + log1(""chaddr does not match, ignoring packet""); // log2? + continue; + } + + message = udhcp_get_option(&packet, DHCP_MESSAGE_TYPE); + if (message == NULL) { + bb_error_msg(""no message type option, ignoring packet""); + continue; + } + + switch (state) { + case INIT_SELECTING: + /* Must be a DHCPOFFER */ + if (*message == DHCPOFFER) { + uint8_t *temp; + +/* What exactly is server's IP? There are several values. + * Example DHCP offer captured with tchdump: + * + * 10.34.25.254:67 > 10.34.25.202:68 // IP header's src + * BOOTP fields: + * Your-IP 10.34.25.202 + * Server-IP 10.34.32.125 // ""next server"" IP + * Gateway-IP 10.34.25.254 // relay's address (if DHCP relays are in use) + * DHCP options: + * DHCP-Message Option 53, length 1: Offer + * Server-ID Option 54, length 4: 10.34.255.7 // ""server ID"" + * Default-Gateway Option 3, length 4: 10.34.25.254 // router + * + * We think that real server IP (one to use in renew/release) + * is one in Server-ID option. But I am not 100% sure. + * IP header's src and Gateway-IP (same in this example) + * might work too. + * ""Next server"" and router are definitely wrong ones to use, though... + */ +/* We used to ignore pcakets without DHCP_SERVER_ID. + * I've got user reports from people who run ""address-less"" servers. + * They either supply DHCP_SERVER_ID of 0.0.0.0 or don't supply it at all. + * They say ISC DHCP client supports this case. + */ + server_addr = 0; + temp = udhcp_get_option(&packet, DHCP_SERVER_ID); + if (!temp) { + bb_error_msg(""no server ID, using 0.0.0.0""); + } else { + /* it IS unaligned sometimes, don't ""optimize"" */ + move_from_unaligned32(server_addr, temp); + } + /*xid = packet.xid; - already is */ + requested_ip = packet.yiaddr; + + /* enter requesting state */ + state = REQUESTING; + timeout = 0; + packet_num = 0; + already_waited_sec = 0; + } + continue; + case REQUESTING: + case RENEWING: + case RENEW_REQUESTED: + case REBINDING: + if (*message == DHCPACK) { + unsigned start; + uint32_t lease_seconds; + struct in_addr temp_addr; + uint8_t *temp; + + temp = udhcp_get_option(&packet, DHCP_LEASE_TIME); + if (!temp) { + bb_error_msg(""no lease time with ACK, using 1 hour lease""); + lease_seconds = 60 * 60; + } else { + /* it IS unaligned sometimes, don't ""optimize"" */ + move_from_unaligned32(lease_seconds, temp); + lease_seconds = ntohl(lease_seconds); + /* paranoia: must not be too small and not prone to overflows */ + if (lease_seconds < 0x10) + lease_seconds = 0x10; + if (lease_seconds >= 0x10000000) + lease_seconds = 0x0fffffff; + } +#if ENABLE_FEATURE_UDHCPC_ARPING + if (opt & OPT_a) { +/* RFC 2131 3.1 paragraph 5: + * ""The client receives the DHCPACK message with configuration + * parameters. The client SHOULD perform a final check on the + * parameters (e.g., ARP for allocated network address), and notes + * the duration of the lease specified in the DHCPACK message. At this + * point, the client is configured. If the client detects that the + * address is already in use (e.g., through the use of ARP), + * the client MUST send a DHCPDECLINE message to the server and restarts + * the configuration process..."" */ + if (!arpping(packet.yiaddr, + NULL, + (uint32_t) 0, + client_config.client_mac, + client_config.interface, + arpping_ms) + ) { + bb_info_msg(""Offered address is in use "" + ""(got ARP reply), declining""); + send_decline(/*xid,*/ server_addr, packet.yiaddr); + + if (state != REQUESTING) + udhcp_run_script(NULL, ""deconfig""); + change_listen_mode(LISTEN_RAW); + state = INIT_SELECTING; + client_config.first_secs = 0; /* make secs field count from 0 */ + requested_ip = 0; + timeout = tryagain_timeout; + packet_num = 0; + already_waited_sec = 0; + continue; /* back to main loop */ + } + } +#endif + /* enter bound state */ + temp_addr.s_addr = packet.yiaddr; + bb_info_msg(""Lease of %s obtained, lease time %u"", + inet_ntoa(temp_addr), (unsigned)lease_seconds); + requested_ip = packet.yiaddr; + + start = monotonic_sec(); + udhcp_run_script(&packet, state == REQUESTING ? ""bound"" : ""renew""); + already_waited_sec = (unsigned)monotonic_sec() - start; + timeout = lease_seconds / 2; + if ((unsigned)timeout < already_waited_sec) { + /* Something went wrong. Back to discover state */ + timeout = already_waited_sec = 0; + } + + state = BOUND; + change_listen_mode(LISTEN_NONE); + if (opt & OPT_q) { /* quit after lease */ + goto ret0; + } + /* future renew failures should not exit (JM) */ + opt &= ~OPT_n; +#if BB_MMU /* NOMMU case backgrounded earlier */ + if (!(opt & OPT_f)) { + client_background(); + /* do not background again! */ + opt = ((opt & ~OPT_b) | OPT_f); + } +#endif + /* make future renew packets use different xid */ + /* xid = random_xid(); ...but why bother? */ + + continue; /* back to main loop */ + } + if (*message == DHCPNAK) { + /* If network has more than one DHCP server, + * ""wrong"" server can reply first, with a NAK. + * Do not interpret it as a NAK from ""our"" server. + */ + if (server_addr != 0) { + uint32_t svid; + uint8_t *temp; + + temp = udhcp_get_option(&packet, DHCP_SERVER_ID); + if (!temp) { + non_matching_svid: + log1(""%s with wrong server ID, ignoring packet"", + ""Received DHCP NAK"" + ); + continue; + } + move_from_unaligned32(svid, temp); + if (svid != server_addr) + goto non_matching_svid; + } + /* return to init state */ + bb_info_msg(""Received DHCP NAK""); + udhcp_run_script(&packet, ""nak""); + if (state != REQUESTING) + udhcp_run_script(NULL, ""deconfig""); + change_listen_mode(LISTEN_RAW); + sleep(3); /* avoid excessive network traffic */ + state = INIT_SELECTING; + client_config.first_secs = 0; /* make secs field count from 0 */ + requested_ip = 0; + timeout = 0; + packet_num = 0; + already_waited_sec = 0; + } + continue; + /* case BOUND: - ignore all packets */ + /* case RELEASED: - ignore all packets */ + } + /* back to main loop */ + } /* for (;;) - main loop ends */ + + ret0: + if (opt & OPT_R) /* release on quit */ + perform_release(server_addr, requested_ip); + retval = 0; + ret: + /*if (client_config.pidfile) - remove_pidfile has its own check */ + remove_pidfile(client_config.pidfile); + return retval; +} +","@@ -113,7 +113,7 @@ static const uint8_t len_of_option_as_string[] = { + [OPTION_IP ] = sizeof(""255.255.255.255 ""), + [OPTION_IP_PAIR ] = sizeof(""255.255.255.255 "") * 2, + [OPTION_STATIC_ROUTES ] = sizeof(""255.255.255.255/32 255.255.255.255 ""), +- [OPTION_6RD ] = sizeof(""32 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 ""), ++ [OPTION_6RD ] = sizeof(""132 128 ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff 255.255.255.255 ""), + [OPTION_STRING ] = 1, + [OPTION_STRING_HOST ] = 1, + #if ENABLE_FEATURE_UDHCP_RFC3397 +@@ -222,7 +222,7 @@ static NOINLINE char *xmalloc_optname_optval(uint8_t *option, const struct dhcp_ + type = optflag->flags & OPTION_TYPE_MASK; + optlen = dhcp_option_lengths[type]; + upper_length = len_of_option_as_string[type] +- * ((unsigned)(len + optlen - 1) / (unsigned)optlen); ++ * ((unsigned)(len + optlen) / (unsigned)optlen); + + dest = ret = xmalloc(upper_length + strlen(opt_name) + 2); + dest += sprintf(ret, ""%s="", opt_name);",5556,5887,6144 +11896,"InlineIterator RenderBlock::LineBreaker::nextSegmentBreak(InlineBidiResolver& resolver, LineInfo& lineInfo, RenderTextInfo& renderTextInfo, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements& wordMeasurements) +{ + reset(); + + ASSERT(resolver.position().root() == m_block); + + bool appliedStartWidth = resolver.position().m_pos > 0; + bool includeEndWidth = true; + LineMidpointState& lineMidpointState = resolver.midpointState(); + + LineWidth width(m_block, lineInfo.isFirstLine(), requiresIndent(lineInfo.isFirstLine(), lineInfo.previousLineBrokeCleanly(), m_block->style())); + + skipLeadingWhitespace(resolver, lineInfo, lastFloatFromPreviousLine, width); + + if (resolver.position().atEnd()) + return resolver.position(); + + bool ignoringSpaces = false; + InlineIterator ignoreStart; + + bool currentCharacterIsSpace = false; + bool currentCharacterShouldCollapseIfPreWap = false; + TrailingObjects trailingObjects; + + InlineIterator lBreak = resolver.position(); + + InlineIterator current = resolver.position(); + RenderObject* last = current.m_obj; + bool atStart = true; + + bool startingNewParagraph = lineInfo.previousLineBrokeCleanly(); + lineInfo.setPreviousLineBrokeCleanly(false); + + bool autoWrapWasEverTrueOnLine = false; + bool floatsFitOnLine = true; + + RenderStyle* blockStyle = m_block->style(); + bool allowImagesToBreak = !m_block->document().inQuirksMode() || !m_block->isTableCell() || !blockStyle->logicalWidth().isIntrinsicOrAuto(); + + EWhiteSpace currWS = blockStyle->whiteSpace(); + EWhiteSpace lastWS = currWS; + while (current.m_obj) { + RenderStyle* currentStyle = current.m_obj->style(); + RenderObject* next = bidiNextSkippingEmptyInlines(m_block, current.m_obj); + if (next && next->parent() && !next->parent()->isDescendantOf(current.m_obj->parent())) + includeEndWidth = true; + + currWS = current.m_obj->isReplaced() ? current.m_obj->parent()->style()->whiteSpace() : currentStyle->whiteSpace(); + lastWS = last->isReplaced() ? last->parent()->style()->whiteSpace() : last->style()->whiteSpace(); + + bool autoWrap = RenderStyle::autoWrap(currWS); + autoWrapWasEverTrueOnLine = autoWrapWasEverTrueOnLine || autoWrap; + + bool preserveNewline = current.m_obj->isSVGInlineText() ? false : RenderStyle::preserveNewline(currWS); + + bool collapseWhiteSpace = RenderStyle::collapseWhiteSpace(currWS); + + if (current.m_obj->isBR()) { + if (width.fitsOnLine()) { + lBreak.moveToStartOf(current.m_obj); + lBreak.increment(); + + if (startingNewParagraph) + lineInfo.setEmpty(false, m_block, &width); + trailingObjects.clear(); + lineInfo.setPreviousLineBrokeCleanly(true); + + if (ignoringSpaces && currentStyle->clear() != CNONE) + ensureLineBoxInsideIgnoredSpaces(lineMidpointState, current.m_obj); + + if (!lineInfo.isEmpty()) + m_clear = currentStyle->clear(); + } + goto end; + } + + if (current.m_obj->isOutOfFlowPositioned()) { + RenderBox* box = toRenderBox(current.m_obj); + bool isInlineType = box->style()->isOriginalDisplayInlineType(); + if (!isInlineType) + m_block->setStaticInlinePositionForChild(box, m_block->logicalHeight(), m_block->startOffsetForContent(m_block->logicalHeight())); + else { + box->layer()->setStaticBlockPosition(m_block->logicalHeight()); + } + + if (isInlineType || current.m_obj->container()->isRenderInline()) { + if (ignoringSpaces) + ensureLineBoxInsideIgnoredSpaces(lineMidpointState, current.m_obj); + trailingObjects.appendBoxIfNeeded(box); + } else + m_positionedObjects.append(box); + width.addUncommittedWidth(inlineLogicalWidth(current.m_obj)); + renderTextInfo.m_lineBreakIterator.resetPriorContext(); + } else if (current.m_obj->isFloating()) { + RenderBox* floatBox = toRenderBox(current.m_obj); + FloatingObject* f = m_block->insertFloatingObject(floatBox); + if (floatsFitOnLine && width.fitsOnLine(f->logicalWidth(m_block->isHorizontalWritingMode()))) { + m_block->positionNewFloatOnLine(f, lastFloatFromPreviousLine, lineInfo, width); + if (lBreak.m_obj == current.m_obj) { + ASSERT(!lBreak.m_pos); + lBreak.increment(); + } + } else + floatsFitOnLine = false; + renderTextInfo.m_lineBreakIterator.updatePriorContext(replacementCharacter); + } else if (current.m_obj->isRenderInline()) { + ASSERT(isEmptyInline(current.m_obj)); + + RenderInline* flowBox = toRenderInline(current.m_obj); + + bool requiresLineBox = alwaysRequiresLineBox(current.m_obj); + if (requiresLineBox || requiresLineBoxForContent(flowBox, lineInfo)) { + if (requiresLineBox) + lineInfo.setEmpty(false, m_block, &width); + if (ignoringSpaces) { + trailingObjects.clear(); + ensureLineBoxInsideIgnoredSpaces(lineMidpointState, current.m_obj); + } else if (blockStyle->collapseWhiteSpace() && resolver.position().m_obj == current.m_obj + && shouldSkipWhitespaceAfterStartObject(m_block, current.m_obj, lineMidpointState)) { + currentCharacterShouldCollapseIfPreWap = currentCharacterIsSpace = true; + ignoringSpaces = true; + } + } + + width.addUncommittedWidth(inlineLogicalWidth(current.m_obj) + borderPaddingMarginStart(flowBox) + borderPaddingMarginEnd(flowBox)); + } else if (current.m_obj->isReplaced()) { + RenderBox* replacedBox = toRenderBox(current.m_obj); + + if (atStart) + width.updateAvailableWidth(replacedBox->logicalHeight()); + + if ((autoWrap || RenderStyle::autoWrap(lastWS)) && (!current.m_obj->isImage() || allowImagesToBreak)) { + width.commit(); + lBreak.moveToStartOf(current.m_obj); + } + + if (ignoringSpaces) + stopIgnoringSpaces(lineMidpointState, InlineIterator(0, current.m_obj, 0)); + + lineInfo.setEmpty(false, m_block, &width); + ignoringSpaces = false; + currentCharacterShouldCollapseIfPreWap = currentCharacterIsSpace = false; + trailingObjects.clear(); + + LayoutUnit replacedLogicalWidth = m_block->logicalWidthForChild(replacedBox) + m_block->marginStartForChild(replacedBox) + m_block->marginEndForChild(replacedBox) + inlineLogicalWidth(current.m_obj); + if (current.m_obj->isListMarker()) { + if (blockStyle->collapseWhiteSpace() && shouldSkipWhitespaceAfterStartObject(m_block, current.m_obj, lineMidpointState)) { + currentCharacterShouldCollapseIfPreWap = currentCharacterIsSpace = true; + ignoringSpaces = true; + } + if (toRenderListMarker(current.m_obj)->isInside()) + width.addUncommittedWidth(replacedLogicalWidth); + } else + width.addUncommittedWidth(replacedLogicalWidth); + if (current.m_obj->isRubyRun()) + width.applyOverhang(toRenderRubyRun(current.m_obj), last, next); + renderTextInfo.m_lineBreakIterator.updatePriorContext(replacementCharacter); + } else if (current.m_obj->isText()) { + if (!current.m_pos) + appliedStartWidth = false; + + RenderText* t = toRenderText(current.m_obj); + + bool isSVGText = t->isSVGInlineText(); + + if (t->style()->hasTextCombine() && current.m_obj->isCombineText() && !toRenderCombineText(current.m_obj)->isCombined()) { + RenderCombineText* combineRenderer = toRenderCombineText(current.m_obj); + combineRenderer->combineText(); + if (iteratorIsBeyondEndOfRenderCombineText(lBreak, combineRenderer)) { + ASSERT(iteratorIsBeyondEndOfRenderCombineText(resolver.position(), combineRenderer)); + lBreak.increment(); + resolver.increment(); + } + } + + RenderStyle* style = t->style(lineInfo.isFirstLine()); + const Font& f = style->font(); + bool isFixedPitch = f.isFixedPitch(); + + unsigned lastSpace = current.m_pos; + float wordSpacing = currentStyle->wordSpacing(); + float lastSpaceWordSpacing = 0; + float wordSpacingForWordMeasurement = 0; + + float wrapW = width.uncommittedWidth() + inlineLogicalWidth(current.m_obj, !appliedStartWidth, true); + float charWidth = 0; + bool breakWords = currentStyle->breakWords() && ((autoWrap && !width.committedWidth()) || currWS == PRE); + bool midWordBreak = false; + bool breakAll = currentStyle->wordBreak() == BreakAllWordBreak && autoWrap; + float hyphenWidth = 0; + + if (isSVGText) { + breakWords = false; + breakAll = false; + } + + if (t->isWordBreak()) { + width.commit(); + lBreak.moveToStartOf(current.m_obj); + ASSERT(current.m_pos == t->textLength()); + } + + if (renderTextInfo.m_text != t) { + renderTextInfo.m_text = t; + renderTextInfo.m_font = &f; + renderTextInfo.m_layout = f.createLayout(t, width.currentWidth(), collapseWhiteSpace); + renderTextInfo.m_lineBreakIterator.resetStringAndReleaseIterator(t->text(), style->locale()); + } else if (renderTextInfo.m_layout && renderTextInfo.m_font != &f) { + renderTextInfo.m_font = &f; + renderTextInfo.m_layout = f.createLayout(t, width.currentWidth(), collapseWhiteSpace); + } + + TextLayout* textLayout = renderTextInfo.m_layout.get(); + + float wordTrailingSpaceWidth = (f.typesettingFeatures() & Kerning) && !textLayout ? f.width(constructTextRun(t, f, &space, 1, style)) + wordSpacing : 0; + + UChar lastCharacter = renderTextInfo.m_lineBreakIterator.lastCharacter(); + UChar secondToLastCharacter = renderTextInfo.m_lineBreakIterator.secondToLastCharacter(); + for (; current.m_pos < t->textLength(); current.fastIncrementInTextNode()) { + bool previousCharacterIsSpace = currentCharacterIsSpace; + bool previousCharacterShouldCollapseIfPreWap = currentCharacterShouldCollapseIfPreWap; + UChar c = current.current(); + currentCharacterShouldCollapseIfPreWap = currentCharacterIsSpace = c == ' ' || c == '\t' || (!preserveNewline && (c == '\n')); + + if (!collapseWhiteSpace || !currentCharacterIsSpace) + lineInfo.setEmpty(false, m_block, &width); + + if (c == softHyphen && autoWrap && !hyphenWidth) { + hyphenWidth = measureHyphenWidth(t, f); + width.addUncommittedWidth(hyphenWidth); + } + + bool applyWordSpacing = false; + + if ((breakAll || breakWords) && !midWordBreak) { + wrapW += charWidth; + bool midWordBreakIsBeforeSurrogatePair = U16_IS_LEAD(c) && current.m_pos + 1 < t->textLength() && U16_IS_TRAIL((*t)[current.m_pos + 1]); + charWidth = textWidth(t, current.m_pos, midWordBreakIsBeforeSurrogatePair ? 2 : 1, f, width.committedWidth() + wrapW, isFixedPitch, collapseWhiteSpace, 0, textLayout); + midWordBreak = width.committedWidth() + wrapW + charWidth > width.availableWidth(); + } + + bool betweenWords = c == '\n' || (currWS != PRE && !atStart && isBreakable(renderTextInfo.m_lineBreakIterator, current.m_pos, current.m_nextBreakablePosition)); + + if (betweenWords || midWordBreak) { + bool stoppedIgnoringSpaces = false; + if (ignoringSpaces) { + lastSpaceWordSpacing = 0; + if (!currentCharacterIsSpace) { + ignoringSpaces = false; + wordSpacingForWordMeasurement = 0; + lastSpace = current.m_pos; // e.g., ""Foo goo"", don't add in any of the ignored spaces. + stopIgnoringSpaces(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos)); + stoppedIgnoringSpaces = true; + } else { + goto nextCharacter; + } + } + + wordMeasurements.grow(wordMeasurements.size() + 1); + WordMeasurement& wordMeasurement = wordMeasurements.last(); + + wordMeasurement.renderer = t; + wordMeasurement.endOffset = current.m_pos; + wordMeasurement.startOffset = lastSpace; + + float additionalTmpW; + if (wordTrailingSpaceWidth && c == ' ') + additionalTmpW = textWidth(t, lastSpace, current.m_pos + 1 - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout) - wordTrailingSpaceWidth; + else + additionalTmpW = textWidth(t, lastSpace, current.m_pos - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout); + + wordMeasurement.width = additionalTmpW + wordSpacingForWordMeasurement; + additionalTmpW += lastSpaceWordSpacing; + width.addUncommittedWidth(additionalTmpW); + if (!appliedStartWidth) { + width.addUncommittedWidth(inlineLogicalWidth(current.m_obj, true, false)); + appliedStartWidth = true; + } + + applyWordSpacing = wordSpacing && currentCharacterIsSpace; + + if (!width.committedWidth() && autoWrap && !width.fitsOnLine()) + width.fitBelowFloats(); + + if (autoWrap || breakWords) { + bool lineWasTooWide = false; + if (width.fitsOnLine() && currentCharacterIsSpace && currentStyle->breakOnlyAfterWhiteSpace() && !midWordBreak) { + float charWidth = textWidth(t, current.m_pos, 1, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout) + (applyWordSpacing ? wordSpacing : 0); + if (!width.fitsOnLine(charWidth)) { + lineWasTooWide = true; + lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition); + skipTrailingWhitespace(lBreak, lineInfo); + } + } + if (lineWasTooWide || !width.fitsOnLine()) { + if (lBreak.atTextParagraphSeparator()) { + if (!stoppedIgnoringSpaces && current.m_pos > 0) + ensureCharacterGetsLineBox(lineMidpointState, current); + lBreak.increment(); + lineInfo.setPreviousLineBrokeCleanly(true); + wordMeasurement.endOffset = lBreak.m_pos; + } + if (lBreak.m_obj && lBreak.m_pos && lBreak.m_obj->isText() && toRenderText(lBreak.m_obj)->textLength() && toRenderText(lBreak.m_obj)->characterAt(lBreak.m_pos - 1) == softHyphen) + m_hyphenated = true; + if (lBreak.m_pos && lBreak.m_pos != (unsigned)wordMeasurement.endOffset && !wordMeasurement.width) { + if (charWidth) { + wordMeasurement.endOffset = lBreak.m_pos; + wordMeasurement.width = charWidth; + } + } + if (ignoringSpaces || !collapseWhiteSpace || !currentCharacterIsSpace || !previousCharacterIsSpace) + goto end; + } else { + if (!betweenWords || (midWordBreak && !autoWrap)) + width.addUncommittedWidth(-additionalTmpW); + if (hyphenWidth) { + width.addUncommittedWidth(-hyphenWidth); + hyphenWidth = 0; + } + } + } + + if (c == '\n' && preserveNewline) { + if (!stoppedIgnoringSpaces && current.m_pos > 0) + ensureCharacterGetsLineBox(lineMidpointState, current); + lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition); + lBreak.increment(); + lineInfo.setPreviousLineBrokeCleanly(true); + return lBreak; + } + + if (autoWrap && betweenWords) { + width.commit(); + wrapW = 0; + lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition); + breakWords = false; + } + + if (midWordBreak && !U16_IS_TRAIL(c) && !(category(c) & (Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining))) { + lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition); + midWordBreak &= (breakWords || breakAll); + } + + if (betweenWords) { + lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0; + wordSpacingForWordMeasurement = (applyWordSpacing && wordMeasurement.width) ? wordSpacing : 0; + lastSpace = current.m_pos; + } + + if (!ignoringSpaces && currentStyle->collapseWhiteSpace()) { + if (currentCharacterIsSpace && previousCharacterIsSpace) { + ignoringSpaces = true; + + startIgnoringSpaces(lineMidpointState, ignoreStart); + trailingObjects.updateMidpointsForTrailingBoxes(lineMidpointState, InlineIterator(), TrailingObjects::DoNotCollapseFirstSpace); + } + } + } else if (ignoringSpaces) { + ignoringSpaces = false; + lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0; + wordSpacingForWordMeasurement = (applyWordSpacing && wordMeasurements.last().width) ? wordSpacing : 0; + lastSpace = current.m_pos; // e.g., ""Foo goo"", don't add in any of the ignored spaces. + stopIgnoringSpaces(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos)); + } + + if (isSVGText && current.m_pos > 0) { + if (toRenderSVGInlineText(t)->characterStartsNewTextChunk(current.m_pos)) + ensureCharacterGetsLineBox(lineMidpointState, current); + } + + if (currentCharacterIsSpace && !previousCharacterIsSpace) { + ignoreStart.m_obj = current.m_obj; + ignoreStart.m_pos = current.m_pos; + } + + if (!currentCharacterIsSpace && previousCharacterShouldCollapseIfPreWap) { + if (autoWrap && currentStyle->breakOnlyAfterWhiteSpace()) + lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition); + } + + if (collapseWhiteSpace && currentCharacterIsSpace && !ignoringSpaces) + trailingObjects.setTrailingWhitespace(toRenderText(current.m_obj)); + else if (!currentStyle->collapseWhiteSpace() || !currentCharacterIsSpace) + trailingObjects.clear(); + + atStart = false; + nextCharacter: + secondToLastCharacter = lastCharacter; + lastCharacter = c; + } + + renderTextInfo.m_lineBreakIterator.setPriorContext(lastCharacter, secondToLastCharacter); + + wordMeasurements.grow(wordMeasurements.size() + 1); + WordMeasurement& wordMeasurement = wordMeasurements.last(); + wordMeasurement.renderer = t; + + float additionalTmpW = ignoringSpaces ? 0 : textWidth(t, lastSpace, current.m_pos - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout); + wordMeasurement.startOffset = lastSpace; + wordMeasurement.endOffset = current.m_pos; + wordMeasurement.width = ignoringSpaces ? 0 : additionalTmpW + wordSpacingForWordMeasurement; + additionalTmpW += lastSpaceWordSpacing; + width.addUncommittedWidth(additionalTmpW + inlineLogicalWidth(current.m_obj, !appliedStartWidth, includeEndWidth)); + includeEndWidth = false; + + if (!width.fitsOnLine()) { + if (!m_hyphenated && lBreak.previousInSameNode() == softHyphen) + m_hyphenated = true; + + if (m_hyphenated) + goto end; + } + } else + ASSERT_NOT_REACHED(); + + bool checkForBreak = autoWrap; + if (width.committedWidth() && !width.fitsOnLine() && lBreak.m_obj && currWS == NOWRAP) + checkForBreak = true; + else if (next && current.m_obj->isText() && next->isText() && !next->isBR() && (autoWrap || next->style()->autoWrap())) { + if (autoWrap && currentCharacterIsSpace) + checkForBreak = true; + else { + RenderText* nextText = toRenderText(next); + if (nextText->textLength()) { + UChar c = nextText->characterAt(0); + checkForBreak = !currentCharacterIsSpace && (c == ' ' || c == '\t' || (c == '\n' && !next->preservesNewline())); + } else if (nextText->isWordBreak()) + checkForBreak = true; + + if (!width.fitsOnLine() && !width.committedWidth()) + width.fitBelowFloats(); + + bool canPlaceOnLine = width.fitsOnLine() || !autoWrapWasEverTrueOnLine; + if (canPlaceOnLine && checkForBreak) { + width.commit(); + lBreak.moveToStartOf(next); + } + } + } + + if (checkForBreak && !width.fitsOnLine()) { + if (currentCharacterIsSpace && !ignoringSpaces && currentStyle->collapseWhiteSpace()) + trailingObjects.clear(); + + if (width.committedWidth()) + goto end; + + width.fitBelowFloats(); + + if (!width.fitsOnLine()) + goto end; + } else if (blockStyle->autoWrap() && !width.fitsOnLine() && !width.committedWidth()) { + width.fitBelowFloats(); + } + + if (!current.m_obj->isFloatingOrOutOfFlowPositioned()) { + last = current.m_obj; + if (last->isReplaced() && autoWrap && (!last->isImage() || allowImagesToBreak) && (!last->isListMarker() || toRenderListMarker(last)->isInside())) { + width.commit(); + lBreak.moveToStartOf(next); + } + } + + if (!collapseWhiteSpace) + currentCharacterIsSpace = false; + + current.moveToStartOf(next); + atStart = false; + } + + if (width.fitsOnLine() || lastWS == NOWRAP) + lBreak.clear(); + + end: + ShapeInsideInfo* shapeInfo = m_block->layoutShapeInsideInfo(); + bool segmentAllowsOverflow = !shapeInfo || !shapeInfo->hasSegments(); + + if (lBreak == resolver.position() && (!lBreak.m_obj || !lBreak.m_obj->isBR()) && segmentAllowsOverflow) { + if (blockStyle->whiteSpace() == PRE && !current.m_pos) { + lBreak.moveTo(last, last->isText() ? last->length() : 0); + } else if (lBreak.m_obj) { + lBreak.moveTo(current.m_obj, current.m_pos); + } + } + + if (lBreak == resolver.position() && segmentAllowsOverflow) + lBreak.increment(); + + checkMidpoints(lineMidpointState, lBreak); + + trailingObjects.updateMidpointsForTrailingBoxes(lineMidpointState, lBreak, TrailingObjects::CollapseFirstSpace); + + if (lBreak.m_pos > 0) { + lBreak.m_pos--; + lBreak.increment(); + } + + return lBreak; +} +",0,"InlineIterator RenderBlock::LineBreaker::nextSegmentBreak(InlineBidiResolver& resolver, LineInfo& lineInfo, RenderTextInfo& renderTextInfo, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements& wordMeasurements) +{ + reset(); + + ASSERT(resolver.position().root() == m_block); + + bool appliedStartWidth = resolver.position().m_pos > 0; + bool includeEndWidth = true; + LineMidpointState& lineMidpointState = resolver.midpointState(); + + LineWidth width(m_block, lineInfo.isFirstLine(), requiresIndent(lineInfo.isFirstLine(), lineInfo.previousLineBrokeCleanly(), m_block->style())); + + skipLeadingWhitespace(resolver, lineInfo, lastFloatFromPreviousLine, width); + + if (resolver.position().atEnd()) + return resolver.position(); + + bool ignoringSpaces = false; + InlineIterator ignoreStart; + + bool currentCharacterIsSpace = false; + bool currentCharacterShouldCollapseIfPreWap = false; + TrailingObjects trailingObjects; + + InlineIterator lBreak = resolver.position(); + + InlineIterator current = resolver.position(); + RenderObject* last = current.m_obj; + bool atStart = true; + + bool startingNewParagraph = lineInfo.previousLineBrokeCleanly(); + lineInfo.setPreviousLineBrokeCleanly(false); + + bool autoWrapWasEverTrueOnLine = false; + bool floatsFitOnLine = true; + + RenderStyle* blockStyle = m_block->style(); + bool allowImagesToBreak = !m_block->document().inQuirksMode() || !m_block->isTableCell() || !blockStyle->logicalWidth().isIntrinsicOrAuto(); + + EWhiteSpace currWS = blockStyle->whiteSpace(); + EWhiteSpace lastWS = currWS; + while (current.m_obj) { + RenderStyle* currentStyle = current.m_obj->style(); + RenderObject* next = bidiNextSkippingEmptyInlines(m_block, current.m_obj); + if (next && next->parent() && !next->parent()->isDescendantOf(current.m_obj->parent())) + includeEndWidth = true; + + currWS = current.m_obj->isReplaced() ? current.m_obj->parent()->style()->whiteSpace() : currentStyle->whiteSpace(); + lastWS = last->isReplaced() ? last->parent()->style()->whiteSpace() : last->style()->whiteSpace(); + + bool autoWrap = RenderStyle::autoWrap(currWS); + autoWrapWasEverTrueOnLine = autoWrapWasEverTrueOnLine || autoWrap; + + bool preserveNewline = current.m_obj->isSVGInlineText() ? false : RenderStyle::preserveNewline(currWS); + + bool collapseWhiteSpace = RenderStyle::collapseWhiteSpace(currWS); + + if (current.m_obj->isBR()) { + if (width.fitsOnLine()) { + lBreak.moveToStartOf(current.m_obj); + lBreak.increment(); + + if (startingNewParagraph) + lineInfo.setEmpty(false, m_block, &width); + trailingObjects.clear(); + lineInfo.setPreviousLineBrokeCleanly(true); + + if (ignoringSpaces && currentStyle->clear() != CNONE) + ensureLineBoxInsideIgnoredSpaces(lineMidpointState, current.m_obj); + + if (!lineInfo.isEmpty()) + m_clear = currentStyle->clear(); + } + goto end; + } + + if (current.m_obj->isOutOfFlowPositioned()) { + RenderBox* box = toRenderBox(current.m_obj); + bool isInlineType = box->style()->isOriginalDisplayInlineType(); + if (!isInlineType) + m_block->setStaticInlinePositionForChild(box, m_block->logicalHeight(), m_block->startOffsetForContent(m_block->logicalHeight())); + else { + box->layer()->setStaticBlockPosition(m_block->logicalHeight()); + } + + if (isInlineType || current.m_obj->container()->isRenderInline()) { + if (ignoringSpaces) + ensureLineBoxInsideIgnoredSpaces(lineMidpointState, current.m_obj); + trailingObjects.appendBoxIfNeeded(box); + } else + m_positionedObjects.append(box); + width.addUncommittedWidth(inlineLogicalWidth(current.m_obj)); + renderTextInfo.m_lineBreakIterator.resetPriorContext(); + } else if (current.m_obj->isFloating()) { + RenderBox* floatBox = toRenderBox(current.m_obj); + FloatingObject* f = m_block->insertFloatingObject(floatBox); + if (floatsFitOnLine && width.fitsOnLine(f->logicalWidth(m_block->isHorizontalWritingMode()))) { + m_block->positionNewFloatOnLine(f, lastFloatFromPreviousLine, lineInfo, width); + if (lBreak.m_obj == current.m_obj) { + ASSERT(!lBreak.m_pos); + lBreak.increment(); + } + } else + floatsFitOnLine = false; + renderTextInfo.m_lineBreakIterator.updatePriorContext(replacementCharacter); + } else if (current.m_obj->isRenderInline()) { + ASSERT(isEmptyInline(current.m_obj)); + + RenderInline* flowBox = toRenderInline(current.m_obj); + + bool requiresLineBox = alwaysRequiresLineBox(current.m_obj); + if (requiresLineBox || requiresLineBoxForContent(flowBox, lineInfo)) { + if (requiresLineBox) + lineInfo.setEmpty(false, m_block, &width); + if (ignoringSpaces) { + trailingObjects.clear(); + ensureLineBoxInsideIgnoredSpaces(lineMidpointState, current.m_obj); + } else if (blockStyle->collapseWhiteSpace() && resolver.position().m_obj == current.m_obj + && shouldSkipWhitespaceAfterStartObject(m_block, current.m_obj, lineMidpointState)) { + currentCharacterShouldCollapseIfPreWap = currentCharacterIsSpace = true; + ignoringSpaces = true; + } + } + + width.addUncommittedWidth(inlineLogicalWidth(current.m_obj) + borderPaddingMarginStart(flowBox) + borderPaddingMarginEnd(flowBox)); + } else if (current.m_obj->isReplaced()) { + RenderBox* replacedBox = toRenderBox(current.m_obj); + + if (atStart) + width.updateAvailableWidth(replacedBox->logicalHeight()); + + if ((autoWrap || RenderStyle::autoWrap(lastWS)) && (!current.m_obj->isImage() || allowImagesToBreak)) { + width.commit(); + lBreak.moveToStartOf(current.m_obj); + } + + if (ignoringSpaces) + stopIgnoringSpaces(lineMidpointState, InlineIterator(0, current.m_obj, 0)); + + lineInfo.setEmpty(false, m_block, &width); + ignoringSpaces = false; + currentCharacterShouldCollapseIfPreWap = currentCharacterIsSpace = false; + trailingObjects.clear(); + + LayoutUnit replacedLogicalWidth = m_block->logicalWidthForChild(replacedBox) + m_block->marginStartForChild(replacedBox) + m_block->marginEndForChild(replacedBox) + inlineLogicalWidth(current.m_obj); + if (current.m_obj->isListMarker()) { + if (blockStyle->collapseWhiteSpace() && shouldSkipWhitespaceAfterStartObject(m_block, current.m_obj, lineMidpointState)) { + currentCharacterShouldCollapseIfPreWap = currentCharacterIsSpace = true; + ignoringSpaces = true; + } + if (toRenderListMarker(current.m_obj)->isInside()) + width.addUncommittedWidth(replacedLogicalWidth); + } else + width.addUncommittedWidth(replacedLogicalWidth); + if (current.m_obj->isRubyRun()) + width.applyOverhang(toRenderRubyRun(current.m_obj), last, next); + renderTextInfo.m_lineBreakIterator.updatePriorContext(replacementCharacter); + } else if (current.m_obj->isText()) { + if (!current.m_pos) + appliedStartWidth = false; + + RenderText* t = toRenderText(current.m_obj); + + bool isSVGText = t->isSVGInlineText(); + + if (t->style()->hasTextCombine() && current.m_obj->isCombineText() && !toRenderCombineText(current.m_obj)->isCombined()) { + RenderCombineText* combineRenderer = toRenderCombineText(current.m_obj); + combineRenderer->combineText(); + if (iteratorIsBeyondEndOfRenderCombineText(lBreak, combineRenderer)) { + ASSERT(iteratorIsBeyondEndOfRenderCombineText(resolver.position(), combineRenderer)); + lBreak.increment(); + resolver.increment(); + } + } + + RenderStyle* style = t->style(lineInfo.isFirstLine()); + const Font& f = style->font(); + bool isFixedPitch = f.isFixedPitch(); + + unsigned lastSpace = current.m_pos; + float wordSpacing = currentStyle->wordSpacing(); + float lastSpaceWordSpacing = 0; + float wordSpacingForWordMeasurement = 0; + + float wrapW = width.uncommittedWidth() + inlineLogicalWidth(current.m_obj, !appliedStartWidth, true); + float charWidth = 0; + bool breakWords = currentStyle->breakWords() && ((autoWrap && !width.committedWidth()) || currWS == PRE); + bool midWordBreak = false; + bool breakAll = currentStyle->wordBreak() == BreakAllWordBreak && autoWrap; + float hyphenWidth = 0; + + if (isSVGText) { + breakWords = false; + breakAll = false; + } + + if (t->isWordBreak()) { + width.commit(); + lBreak.moveToStartOf(current.m_obj); + ASSERT(current.m_pos == t->textLength()); + } + + if (renderTextInfo.m_text != t) { + renderTextInfo.m_text = t; + renderTextInfo.m_font = &f; + renderTextInfo.m_layout = f.createLayout(t, width.currentWidth(), collapseWhiteSpace); + renderTextInfo.m_lineBreakIterator.resetStringAndReleaseIterator(t->text(), style->locale()); + } else if (renderTextInfo.m_layout && renderTextInfo.m_font != &f) { + renderTextInfo.m_font = &f; + renderTextInfo.m_layout = f.createLayout(t, width.currentWidth(), collapseWhiteSpace); + } + + TextLayout* textLayout = renderTextInfo.m_layout.get(); + + float wordTrailingSpaceWidth = (f.typesettingFeatures() & Kerning) && !textLayout ? f.width(constructTextRun(t, f, &space, 1, style)) + wordSpacing : 0; + + UChar lastCharacter = renderTextInfo.m_lineBreakIterator.lastCharacter(); + UChar secondToLastCharacter = renderTextInfo.m_lineBreakIterator.secondToLastCharacter(); + for (; current.m_pos < t->textLength(); current.fastIncrementInTextNode()) { + bool previousCharacterIsSpace = currentCharacterIsSpace; + bool previousCharacterShouldCollapseIfPreWap = currentCharacterShouldCollapseIfPreWap; + UChar c = current.current(); + currentCharacterShouldCollapseIfPreWap = currentCharacterIsSpace = c == ' ' || c == '\t' || (!preserveNewline && (c == '\n')); + + if (!collapseWhiteSpace || !currentCharacterIsSpace) + lineInfo.setEmpty(false, m_block, &width); + + if (c == softHyphen && autoWrap && !hyphenWidth) { + hyphenWidth = measureHyphenWidth(t, f); + width.addUncommittedWidth(hyphenWidth); + } + + bool applyWordSpacing = false; + + if ((breakAll || breakWords) && !midWordBreak) { + wrapW += charWidth; + bool midWordBreakIsBeforeSurrogatePair = U16_IS_LEAD(c) && current.m_pos + 1 < t->textLength() && U16_IS_TRAIL((*t)[current.m_pos + 1]); + charWidth = textWidth(t, current.m_pos, midWordBreakIsBeforeSurrogatePair ? 2 : 1, f, width.committedWidth() + wrapW, isFixedPitch, collapseWhiteSpace, 0, textLayout); + midWordBreak = width.committedWidth() + wrapW + charWidth > width.availableWidth(); + } + + bool betweenWords = c == '\n' || (currWS != PRE && !atStart && isBreakable(renderTextInfo.m_lineBreakIterator, current.m_pos, current.m_nextBreakablePosition)); + + if (betweenWords || midWordBreak) { + bool stoppedIgnoringSpaces = false; + if (ignoringSpaces) { + lastSpaceWordSpacing = 0; + if (!currentCharacterIsSpace) { + ignoringSpaces = false; + wordSpacingForWordMeasurement = 0; + lastSpace = current.m_pos; // e.g., ""Foo goo"", don't add in any of the ignored spaces. + stopIgnoringSpaces(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos)); + stoppedIgnoringSpaces = true; + } else { + goto nextCharacter; + } + } + + wordMeasurements.grow(wordMeasurements.size() + 1); + WordMeasurement& wordMeasurement = wordMeasurements.last(); + + wordMeasurement.renderer = t; + wordMeasurement.endOffset = current.m_pos; + wordMeasurement.startOffset = lastSpace; + + float additionalTmpW; + if (wordTrailingSpaceWidth && c == ' ') + additionalTmpW = textWidth(t, lastSpace, current.m_pos + 1 - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout) - wordTrailingSpaceWidth; + else + additionalTmpW = textWidth(t, lastSpace, current.m_pos - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout); + + wordMeasurement.width = additionalTmpW + wordSpacingForWordMeasurement; + additionalTmpW += lastSpaceWordSpacing; + width.addUncommittedWidth(additionalTmpW); + if (!appliedStartWidth) { + width.addUncommittedWidth(inlineLogicalWidth(current.m_obj, true, false)); + appliedStartWidth = true; + } + + applyWordSpacing = wordSpacing && currentCharacterIsSpace; + + if (!width.committedWidth() && autoWrap && !width.fitsOnLine()) + width.fitBelowFloats(); + + if (autoWrap || breakWords) { + bool lineWasTooWide = false; + if (width.fitsOnLine() && currentCharacterIsSpace && currentStyle->breakOnlyAfterWhiteSpace() && !midWordBreak) { + float charWidth = textWidth(t, current.m_pos, 1, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout) + (applyWordSpacing ? wordSpacing : 0); + if (!width.fitsOnLine(charWidth)) { + lineWasTooWide = true; + lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition); + skipTrailingWhitespace(lBreak, lineInfo); + } + } + if (lineWasTooWide || !width.fitsOnLine()) { + if (lBreak.atTextParagraphSeparator()) { + if (!stoppedIgnoringSpaces && current.m_pos > 0) + ensureCharacterGetsLineBox(lineMidpointState, current); + lBreak.increment(); + lineInfo.setPreviousLineBrokeCleanly(true); + wordMeasurement.endOffset = lBreak.m_pos; + } + if (lBreak.m_obj && lBreak.m_pos && lBreak.m_obj->isText() && toRenderText(lBreak.m_obj)->textLength() && toRenderText(lBreak.m_obj)->characterAt(lBreak.m_pos - 1) == softHyphen) + m_hyphenated = true; + if (lBreak.m_pos && lBreak.m_pos != (unsigned)wordMeasurement.endOffset && !wordMeasurement.width) { + if (charWidth) { + wordMeasurement.endOffset = lBreak.m_pos; + wordMeasurement.width = charWidth; + } + } + if (ignoringSpaces || !collapseWhiteSpace || !currentCharacterIsSpace || !previousCharacterIsSpace) + goto end; + } else { + if (!betweenWords || (midWordBreak && !autoWrap)) + width.addUncommittedWidth(-additionalTmpW); + if (hyphenWidth) { + width.addUncommittedWidth(-hyphenWidth); + hyphenWidth = 0; + } + } + } + + if (c == '\n' && preserveNewline) { + if (!stoppedIgnoringSpaces && current.m_pos > 0) + ensureCharacterGetsLineBox(lineMidpointState, current); + lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition); + lBreak.increment(); + lineInfo.setPreviousLineBrokeCleanly(true); + return lBreak; + } + + if (autoWrap && betweenWords) { + width.commit(); + wrapW = 0; + lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition); + breakWords = false; + } + + if (midWordBreak && !U16_IS_TRAIL(c) && !(category(c) & (Mark_NonSpacing | Mark_Enclosing | Mark_SpacingCombining))) { + lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition); + midWordBreak &= (breakWords || breakAll); + } + + if (betweenWords) { + lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0; + wordSpacingForWordMeasurement = (applyWordSpacing && wordMeasurement.width) ? wordSpacing : 0; + lastSpace = current.m_pos; + } + + if (!ignoringSpaces && currentStyle->collapseWhiteSpace()) { + if (currentCharacterIsSpace && previousCharacterIsSpace) { + ignoringSpaces = true; + + startIgnoringSpaces(lineMidpointState, ignoreStart); + trailingObjects.updateMidpointsForTrailingBoxes(lineMidpointState, InlineIterator(), TrailingObjects::DoNotCollapseFirstSpace); + } + } + } else if (ignoringSpaces) { + ignoringSpaces = false; + lastSpaceWordSpacing = applyWordSpacing ? wordSpacing : 0; + wordSpacingForWordMeasurement = (applyWordSpacing && wordMeasurements.last().width) ? wordSpacing : 0; + lastSpace = current.m_pos; // e.g., ""Foo goo"", don't add in any of the ignored spaces. + stopIgnoringSpaces(lineMidpointState, InlineIterator(0, current.m_obj, current.m_pos)); + } + + if (isSVGText && current.m_pos > 0) { + if (toRenderSVGInlineText(t)->characterStartsNewTextChunk(current.m_pos)) + ensureCharacterGetsLineBox(lineMidpointState, current); + } + + if (currentCharacterIsSpace && !previousCharacterIsSpace) { + ignoreStart.m_obj = current.m_obj; + ignoreStart.m_pos = current.m_pos; + } + + if (!currentCharacterIsSpace && previousCharacterShouldCollapseIfPreWap) { + if (autoWrap && currentStyle->breakOnlyAfterWhiteSpace()) + lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition); + } + + if (collapseWhiteSpace && currentCharacterIsSpace && !ignoringSpaces) + trailingObjects.setTrailingWhitespace(toRenderText(current.m_obj)); + else if (!currentStyle->collapseWhiteSpace() || !currentCharacterIsSpace) + trailingObjects.clear(); + + atStart = false; + nextCharacter: + secondToLastCharacter = lastCharacter; + lastCharacter = c; + } + + renderTextInfo.m_lineBreakIterator.setPriorContext(lastCharacter, secondToLastCharacter); + + wordMeasurements.grow(wordMeasurements.size() + 1); + WordMeasurement& wordMeasurement = wordMeasurements.last(); + wordMeasurement.renderer = t; + + float additionalTmpW = ignoringSpaces ? 0 : textWidth(t, lastSpace, current.m_pos - lastSpace, f, width.currentWidth(), isFixedPitch, collapseWhiteSpace, &wordMeasurement.fallbackFonts, textLayout); + wordMeasurement.startOffset = lastSpace; + wordMeasurement.endOffset = current.m_pos; + wordMeasurement.width = ignoringSpaces ? 0 : additionalTmpW + wordSpacingForWordMeasurement; + additionalTmpW += lastSpaceWordSpacing; + width.addUncommittedWidth(additionalTmpW + inlineLogicalWidth(current.m_obj, !appliedStartWidth, includeEndWidth)); + includeEndWidth = false; + + if (!width.fitsOnLine()) { + if (!m_hyphenated && lBreak.previousInSameNode() == softHyphen) + m_hyphenated = true; + + if (m_hyphenated) + goto end; + } + } else + ASSERT_NOT_REACHED(); + + bool checkForBreak = autoWrap; + if (width.committedWidth() && !width.fitsOnLine() && lBreak.m_obj && currWS == NOWRAP) + checkForBreak = true; + else if (next && current.m_obj->isText() && next->isText() && !next->isBR() && (autoWrap || next->style()->autoWrap())) { + if (autoWrap && currentCharacterIsSpace) + checkForBreak = true; + else { + RenderText* nextText = toRenderText(next); + if (nextText->textLength()) { + UChar c = nextText->characterAt(0); + checkForBreak = !currentCharacterIsSpace && (c == ' ' || c == '\t' || (c == '\n' && !next->preservesNewline())); + } else if (nextText->isWordBreak()) + checkForBreak = true; + + if (!width.fitsOnLine() && !width.committedWidth()) + width.fitBelowFloats(); + + bool canPlaceOnLine = width.fitsOnLine() || !autoWrapWasEverTrueOnLine; + if (canPlaceOnLine && checkForBreak) { + width.commit(); + lBreak.moveToStartOf(next); + } + } + } + + if (checkForBreak && !width.fitsOnLine()) { + if (currentCharacterIsSpace && !ignoringSpaces && currentStyle->collapseWhiteSpace()) + trailingObjects.clear(); + + if (width.committedWidth()) + goto end; + + width.fitBelowFloats(); + + if (!width.fitsOnLine()) + goto end; + } else if (blockStyle->autoWrap() && !width.fitsOnLine() && !width.committedWidth()) { + width.fitBelowFloats(); + } + + if (!current.m_obj->isFloatingOrOutOfFlowPositioned()) { + last = current.m_obj; + if (last->isReplaced() && autoWrap && (!last->isImage() || allowImagesToBreak) && (!last->isListMarker() || toRenderListMarker(last)->isInside())) { + width.commit(); + lBreak.moveToStartOf(next); + } + } + + if (!collapseWhiteSpace) + currentCharacterIsSpace = false; + + current.moveToStartOf(next); + atStart = false; + } + + if (width.fitsOnLine() || lastWS == NOWRAP) + lBreak.clear(); + + end: + ShapeInsideInfo* shapeInfo = m_block->layoutShapeInsideInfo(); + bool segmentAllowsOverflow = !shapeInfo || !shapeInfo->hasSegments(); + + if (lBreak == resolver.position() && (!lBreak.m_obj || !lBreak.m_obj->isBR()) && segmentAllowsOverflow) { + if (blockStyle->whiteSpace() == PRE && !current.m_pos) { + lBreak.moveTo(last, last->isText() ? last->length() : 0); + } else if (lBreak.m_obj) { + lBreak.moveTo(current.m_obj, current.m_pos); + } + } + + if (lBreak == resolver.position() && segmentAllowsOverflow) + lBreak.increment(); + + checkMidpoints(lineMidpointState, lBreak); + + trailingObjects.updateMidpointsForTrailingBoxes(lineMidpointState, lBreak, TrailingObjects::CollapseFirstSpace); + + if (lBreak.m_pos > 0) { + lBreak.m_pos--; + lBreak.increment(); + } + + return lBreak; +} +","@@ -1313,7 +1313,8 @@ static inline void constructBidiRunsForSegment(InlineBidiResolver& topResolver, + // tree to see which parent inline is the isolate. We could change enterIsolate + // to take a RenderObject and do this logic there, but that would be a layering + // violation for BidiResolver (which knows nothing about RenderObject). +- RenderInline* isolatedInline = toRenderInline(containingIsolate(startObj, currentRoot)); ++ RenderInline* isolatedInline = toRenderInline(highestContainingIsolateWithinRoot(startObj, currentRoot)); ++ ASSERT(isolatedInline); + + InlineBidiResolver isolatedResolver; + EUnicodeBidi unicodeBidi = isolatedInline->style()->unicodeBidi();",5103,5434,6144 +7752,"static MagickBooleanType WritePICTImage(const ImageInfo *image_info, + Image *image,ExceptionInfo *exception) +{ +#define MaxCount 128 +#define PictCropRegionOp 0x01 +#define PictEndOfPictureOp 0xff +#define PictJPEGOp 0x8200 +#define PictInfoOp 0x0C00 +#define PictInfoSize 512 +#define PictPixmapOp 0x9A +#define PictPICTOp 0x98 +#define PictVersion 0x11 + + const StringInfo + *profile; + + double + x_resolution, + y_resolution; + + MagickBooleanType + status; + + MagickOffsetType + offset; + + PICTPixmap + pixmap; + + PICTRectangle + bounds, + crop_rectangle, + destination_rectangle, + frame_rectangle, + size_rectangle, + source_rectangle; + + register const Quantum + *p; + + register ssize_t + i, + x; + + size_t + bytes_per_line, + count, + row_bytes, + storage_class; + + ssize_t + y; + + unsigned char + *buffer, + *packed_scanline, + *scanline; + + unsigned short + base_address, + transfer_mode; + + /* + 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 > 65535L) || (image->rows > 65535L)) + ThrowWriterException(ImageError,""WidthOrHeightExceedsLimit""); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); + if (status == MagickFalse) + return(status); + (void) TransformImageColorspace(image,sRGBColorspace,exception); + /* + Initialize image info. + */ + size_rectangle.top=0; + size_rectangle.left=0; + size_rectangle.bottom=(short) image->rows; + size_rectangle.right=(short) image->columns; + frame_rectangle=size_rectangle; + crop_rectangle=size_rectangle; + source_rectangle=size_rectangle; + destination_rectangle=size_rectangle; + base_address=0xff; + row_bytes=image->columns; + bounds.top=0; + bounds.left=0; + bounds.bottom=(short) image->rows; + bounds.right=(short) image->columns; + pixmap.version=0; + pixmap.pack_type=0; + pixmap.pack_size=0; + pixmap.pixel_type=0; + pixmap.bits_per_pixel=8; + pixmap.component_count=1; + pixmap.component_size=8; + pixmap.plane_bytes=0; + pixmap.table=0; + pixmap.reserved=0; + transfer_mode=0; + x_resolution=image->resolution.x != 0.0 ? image->resolution.x : + DefaultResolution; + y_resolution=image->resolution.y != 0.0 ? image->resolution.y : + DefaultResolution; + storage_class=image->storage_class; + if (image_info->compression == JPEGCompression) + storage_class=DirectClass; + if (storage_class == DirectClass) + { + pixmap.component_count=image->alpha_trait != UndefinedPixelTrait ? 4 : 3; + pixmap.pixel_type=16; + pixmap.bits_per_pixel=32; + pixmap.pack_type=0x04; + transfer_mode=0x40; + row_bytes=4*image->columns; + } + /* + Allocate memory. + */ + bytes_per_line=image->columns; + if (storage_class == DirectClass) + bytes_per_line*=image->alpha_trait != UndefinedPixelTrait ? 4 : 3; + buffer=(unsigned char *) AcquireQuantumMemory(PictInfoSize,sizeof(*buffer)); + packed_scanline=(unsigned char *) AcquireQuantumMemory((size_t) + (row_bytes+MaxCount),sizeof(*packed_scanline)); + scanline=(unsigned char *) AcquireQuantumMemory(row_bytes,sizeof(*scanline)); + if ((buffer == (unsigned char *) NULL) || + (packed_scanline == (unsigned char *) NULL) || + (scanline == (unsigned char *) NULL)) + { + if (scanline != (unsigned char *) NULL) + scanline=(unsigned char *) RelinquishMagickMemory(scanline); + if (packed_scanline != (unsigned char *) NULL) + packed_scanline=(unsigned char *) RelinquishMagickMemory( + packed_scanline); + if (buffer != (unsigned char *) NULL) + buffer=(unsigned char *) RelinquishMagickMemory(buffer); + ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); + } + (void) memset(scanline,0,row_bytes); + (void) memset(packed_scanline,0,(size_t) (row_bytes+MaxCount)); + /* + Write header, header size, size bounding box, version, and reserved. + */ + (void) memset(buffer,0,PictInfoSize); + (void) WriteBlob(image,PictInfoSize,buffer); + (void) WriteBlobMSBShort(image,0); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.right); + (void) WriteBlobMSBShort(image,PictVersion); + (void) WriteBlobMSBShort(image,0x02ff); /* version #2 */ + (void) WriteBlobMSBShort(image,PictInfoOp); + (void) WriteBlobMSBLong(image,0xFFFE0000U); + /* + Write full size of the file, resolution, frame bounding box, and reserved. + */ + (void) WriteBlobMSBShort(image,(unsigned short) x_resolution); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) y_resolution); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.right); + (void) WriteBlobMSBLong(image,0x00000000L); + profile=GetImageProfile(image,""iptc""); + if (profile != (StringInfo *) NULL) + { + (void) WriteBlobMSBShort(image,0xa1); + (void) WriteBlobMSBShort(image,0x1f2); + (void) WriteBlobMSBShort(image,(unsigned short) + (GetStringInfoLength(profile)+4)); + (void) WriteBlobString(image,""8BIM""); + (void) WriteBlob(image,GetStringInfoLength(profile), + GetStringInfoDatum(profile)); + } + profile=GetImageProfile(image,""icc""); + if (profile != (StringInfo *) NULL) + { + (void) WriteBlobMSBShort(image,0xa1); + (void) WriteBlobMSBShort(image,0xe0); + (void) WriteBlobMSBShort(image,(unsigned short) + (GetStringInfoLength(profile)+4)); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlob(image,GetStringInfoLength(profile), + GetStringInfoDatum(profile)); + (void) WriteBlobMSBShort(image,0xa1); + (void) WriteBlobMSBShort(image,0xe0); + (void) WriteBlobMSBShort(image,4); + (void) WriteBlobMSBLong(image,0x00000002U); + } + /* + Write crop region opcode and crop bounding box. + */ + (void) WriteBlobMSBShort(image,PictCropRegionOp); + (void) WriteBlobMSBShort(image,0xa); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.right); + if (image_info->compression == JPEGCompression) + { + Image + *jpeg_image; + + ImageInfo + *jpeg_info; + + size_t + length; + + unsigned char + *blob; + + jpeg_image=CloneImage(image,0,0,MagickTrue,exception); + if (jpeg_image == (Image *) NULL) + { + (void) CloseBlob(image); + return(MagickFalse); + } + jpeg_info=CloneImageInfo(image_info); + (void) CopyMagickString(jpeg_info->magick,""JPEG"",MagickPathExtent); + length=0; + blob=(unsigned char *) ImageToBlob(jpeg_info,jpeg_image,&length, + exception); + jpeg_info=DestroyImageInfo(jpeg_info); + if (blob == (unsigned char *) NULL) + return(MagickFalse); + jpeg_image=DestroyImage(jpeg_image); + (void) WriteBlobMSBShort(image,PictJPEGOp); + (void) WriteBlobMSBLong(image,(unsigned int) length+154); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBLong(image,0x00010000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00010000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x40000000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00400000U); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) image->rows); + (void) WriteBlobMSBShort(image,(unsigned short) image->columns); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,768); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00566A70U); + (void) WriteBlobMSBLong(image,0x65670000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00000001U); + (void) WriteBlobMSBLong(image,0x00016170U); + (void) WriteBlobMSBLong(image,0x706C0000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBShort(image,768); + (void) WriteBlobMSBShort(image,(unsigned short) image->columns); + (void) WriteBlobMSBShort(image,(unsigned short) image->rows); + (void) WriteBlobMSBShort(image,(unsigned short) x_resolution); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) y_resolution); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBLong(image,length); + (void) WriteBlobMSBShort(image,0x0001); + (void) WriteBlobMSBLong(image,0x0B466F74U); + (void) WriteBlobMSBLong(image,0x6F202D20U); + (void) WriteBlobMSBLong(image,0x4A504547U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x0018FFFFU); + (void) WriteBlob(image,length,blob); + if ((length & 0x01) != 0) + (void) WriteBlobByte(image,'\0'); + blob=(unsigned char *) RelinquishMagickMemory(blob); + } + /* + Write picture opcode, row bytes, and picture bounding box, and version. + */ + if (storage_class == PseudoClass) + (void) WriteBlobMSBShort(image,PictPICTOp); + else + { + (void) WriteBlobMSBShort(image,PictPixmapOp); + (void) WriteBlobMSBLong(image,(unsigned int) base_address); + } + (void) WriteBlobMSBShort(image,(unsigned short) (row_bytes | 0x8000)); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.top); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.left); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.right); + /* + Write pack type, pack size, resolution, pixel type, and pixel size. + */ + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.version); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.pack_type); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.pack_size); + (void) WriteBlobMSBShort(image,(unsigned short) (x_resolution+0.5)); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) (y_resolution+0.5)); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.pixel_type); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.bits_per_pixel); + /* + Write component count, size, plane bytes, table size, and reserved. + */ + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_count); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_size); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.plane_bytes); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.table); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.reserved); + if (storage_class == PseudoClass) + { + /* + Write image colormap. + */ + (void) WriteBlobMSBLong(image,0x00000000L); /* color seed */ + (void) WriteBlobMSBShort(image,0L); /* color flags */ + (void) WriteBlobMSBShort(image,(unsigned short) (image->colors-1)); + for (i=0; i < (ssize_t) image->colors; i++) + { + (void) WriteBlobMSBShort(image,(unsigned short) i); + (void) WriteBlobMSBShort(image,ScaleQuantumToShort( + image->colormap[i].red)); + (void) WriteBlobMSBShort(image,ScaleQuantumToShort( + image->colormap[i].green)); + (void) WriteBlobMSBShort(image,ScaleQuantumToShort( + image->colormap[i].blue)); + } + } + /* + Write source and destination rectangle. + */ + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.right); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.right); + (void) WriteBlobMSBShort(image,(unsigned short) transfer_mode); + /* + Write picture data. + */ + count=0; + if (storage_class == PseudoClass) + for (y=0; y < (ssize_t) image->rows; y++) + { + p=GetVirtualPixels(image,0,y,image->columns,1,exception); + if (p == (const Quantum *) NULL) + break; + for (x=0; x < (ssize_t) image->columns; x++) + { + scanline[x]=(unsigned char) GetPixelIndex(image,p); + p+=GetPixelChannels(image); + } + count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF), + packed_scanline); + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + } + else + if (image_info->compression == JPEGCompression) + { + (void) memset(scanline,0,row_bytes); + for (y=0; y < (ssize_t) image->rows; y++) + count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF), + packed_scanline); + } + else + { + register unsigned char + *blue, + *green, + *opacity, + *red; + + red=scanline; + green=scanline+image->columns; + blue=scanline+2*image->columns; + opacity=scanline+3*image->columns; + for (y=0; y < (ssize_t) image->rows; y++) + { + p=GetVirtualPixels(image,0,y,image->columns,1,exception); + if (p == (const Quantum *) NULL) + break; + red=scanline; + green=scanline+image->columns; + blue=scanline+2*image->columns; + if (image->alpha_trait != UndefinedPixelTrait) + { + opacity=scanline; + red=scanline+image->columns; + green=scanline+2*image->columns; + blue=scanline+3*image->columns; + } + for (x=0; x < (ssize_t) image->columns; x++) + { + *red++=ScaleQuantumToChar(GetPixelRed(image,p)); + *green++=ScaleQuantumToChar(GetPixelGreen(image,p)); + *blue++=ScaleQuantumToChar(GetPixelBlue(image,p)); + if (image->alpha_trait != UndefinedPixelTrait) + *opacity++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(image,p))); + p+=GetPixelChannels(image); + } + count+=EncodeImage(image,scanline,bytes_per_line,packed_scanline); + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + } + } + if ((count & 0x01) != 0) + (void) WriteBlobByte(image,'\0'); + (void) WriteBlobMSBShort(image,PictEndOfPictureOp); + offset=TellBlob(image); + offset=SeekBlob(image,512,SEEK_SET); + (void) WriteBlobMSBShort(image,(unsigned short) offset); + scanline=(unsigned char *) RelinquishMagickMemory(scanline); + packed_scanline=(unsigned char *) RelinquishMagickMemory(packed_scanline); + buffer=(unsigned char *) RelinquishMagickMemory(buffer); + (void) CloseBlob(image); + return(MagickTrue); +} +",0,"static MagickBooleanType WritePICTImage(const ImageInfo *image_info, + Image *image,ExceptionInfo *exception) +{ +#define MaxCount 128 +#define PictCropRegionOp 0x01 +#define PictEndOfPictureOp 0xff +#define PictJPEGOp 0x8200 +#define PictInfoOp 0x0C00 +#define PictInfoSize 512 +#define PictPixmapOp 0x9A +#define PictPICTOp 0x98 +#define PictVersion 0x11 + + const StringInfo + *profile; + + double + x_resolution, + y_resolution; + + MagickBooleanType + status; + + MagickOffsetType + offset; + + PICTPixmap + pixmap; + + PICTRectangle + bounds, + crop_rectangle, + destination_rectangle, + frame_rectangle, + size_rectangle, + source_rectangle; + + register const Quantum + *p; + + register ssize_t + i, + x; + + size_t + bytes_per_line, + count, + row_bytes, + storage_class; + + ssize_t + y; + + unsigned char + *buffer, + *packed_scanline, + *scanline; + + unsigned short + base_address, + transfer_mode; + + /* + 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 > 65535L) || (image->rows > 65535L)) + ThrowWriterException(ImageError,""WidthOrHeightExceedsLimit""); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); + if (status == MagickFalse) + return(status); + (void) TransformImageColorspace(image,sRGBColorspace,exception); + /* + Initialize image info. + */ + size_rectangle.top=0; + size_rectangle.left=0; + size_rectangle.bottom=(short) image->rows; + size_rectangle.right=(short) image->columns; + frame_rectangle=size_rectangle; + crop_rectangle=size_rectangle; + source_rectangle=size_rectangle; + destination_rectangle=size_rectangle; + base_address=0xff; + row_bytes=image->columns; + bounds.top=0; + bounds.left=0; + bounds.bottom=(short) image->rows; + bounds.right=(short) image->columns; + pixmap.version=0; + pixmap.pack_type=0; + pixmap.pack_size=0; + pixmap.pixel_type=0; + pixmap.bits_per_pixel=8; + pixmap.component_count=1; + pixmap.component_size=8; + pixmap.plane_bytes=0; + pixmap.table=0; + pixmap.reserved=0; + transfer_mode=0; + x_resolution=image->resolution.x != 0.0 ? image->resolution.x : + DefaultResolution; + y_resolution=image->resolution.y != 0.0 ? image->resolution.y : + DefaultResolution; + storage_class=image->storage_class; + if (image_info->compression == JPEGCompression) + storage_class=DirectClass; + if (storage_class == DirectClass) + { + pixmap.component_count=image->alpha_trait != UndefinedPixelTrait ? 4 : 3; + pixmap.pixel_type=16; + pixmap.bits_per_pixel=32; + pixmap.pack_type=0x04; + transfer_mode=0x40; + row_bytes=4*image->columns; + } + /* + Allocate memory. + */ + bytes_per_line=image->columns; + if (storage_class == DirectClass) + bytes_per_line*=image->alpha_trait != UndefinedPixelTrait ? 4 : 3; + buffer=(unsigned char *) AcquireQuantumMemory(PictInfoSize,sizeof(*buffer)); + packed_scanline=(unsigned char *) AcquireQuantumMemory((size_t) + (row_bytes+MaxCount),sizeof(*packed_scanline)); + scanline=(unsigned char *) AcquireQuantumMemory(row_bytes,sizeof(*scanline)); + if ((buffer == (unsigned char *) NULL) || + (packed_scanline == (unsigned char *) NULL) || + (scanline == (unsigned char *) NULL)) + { + if (scanline != (unsigned char *) NULL) + scanline=(unsigned char *) RelinquishMagickMemory(scanline); + if (packed_scanline != (unsigned char *) NULL) + packed_scanline=(unsigned char *) RelinquishMagickMemory( + packed_scanline); + if (buffer != (unsigned char *) NULL) + buffer=(unsigned char *) RelinquishMagickMemory(buffer); + ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); + } + (void) memset(scanline,0,row_bytes); + (void) memset(packed_scanline,0,(size_t) (row_bytes+MaxCount)); + /* + Write header, header size, size bounding box, version, and reserved. + */ + (void) memset(buffer,0,PictInfoSize); + (void) WriteBlob(image,PictInfoSize,buffer); + (void) WriteBlobMSBShort(image,0); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) size_rectangle.right); + (void) WriteBlobMSBShort(image,PictVersion); + (void) WriteBlobMSBShort(image,0x02ff); /* version #2 */ + (void) WriteBlobMSBShort(image,PictInfoOp); + (void) WriteBlobMSBLong(image,0xFFFE0000U); + /* + Write full size of the file, resolution, frame bounding box, and reserved. + */ + (void) WriteBlobMSBShort(image,(unsigned short) x_resolution); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) y_resolution); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) frame_rectangle.right); + (void) WriteBlobMSBLong(image,0x00000000L); + profile=GetImageProfile(image,""iptc""); + if (profile != (StringInfo *) NULL) + { + (void) WriteBlobMSBShort(image,0xa1); + (void) WriteBlobMSBShort(image,0x1f2); + (void) WriteBlobMSBShort(image,(unsigned short) + (GetStringInfoLength(profile)+4)); + (void) WriteBlobString(image,""8BIM""); + (void) WriteBlob(image,GetStringInfoLength(profile), + GetStringInfoDatum(profile)); + } + profile=GetImageProfile(image,""icc""); + if (profile != (StringInfo *) NULL) + { + (void) WriteBlobMSBShort(image,0xa1); + (void) WriteBlobMSBShort(image,0xe0); + (void) WriteBlobMSBShort(image,(unsigned short) + (GetStringInfoLength(profile)+4)); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlob(image,GetStringInfoLength(profile), + GetStringInfoDatum(profile)); + (void) WriteBlobMSBShort(image,0xa1); + (void) WriteBlobMSBShort(image,0xe0); + (void) WriteBlobMSBShort(image,4); + (void) WriteBlobMSBLong(image,0x00000002U); + } + /* + Write crop region opcode and crop bounding box. + */ + (void) WriteBlobMSBShort(image,PictCropRegionOp); + (void) WriteBlobMSBShort(image,0xa); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) crop_rectangle.right); + if (image_info->compression == JPEGCompression) + { + Image + *jpeg_image; + + ImageInfo + *jpeg_info; + + size_t + length; + + unsigned char + *blob; + + jpeg_image=CloneImage(image,0,0,MagickTrue,exception); + if (jpeg_image == (Image *) NULL) + { + (void) CloseBlob(image); + return(MagickFalse); + } + jpeg_info=CloneImageInfo(image_info); + (void) CopyMagickString(jpeg_info->magick,""JPEG"",MagickPathExtent); + length=0; + blob=(unsigned char *) ImageToBlob(jpeg_info,jpeg_image,&length, + exception); + jpeg_info=DestroyImageInfo(jpeg_info); + if (blob == (unsigned char *) NULL) + return(MagickFalse); + jpeg_image=DestroyImage(jpeg_image); + (void) WriteBlobMSBShort(image,PictJPEGOp); + (void) WriteBlobMSBLong(image,(unsigned int) length+154); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBLong(image,0x00010000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00010000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x40000000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00400000U); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) image->rows); + (void) WriteBlobMSBShort(image,(unsigned short) image->columns); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,768); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00566A70U); + (void) WriteBlobMSBLong(image,0x65670000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00000001U); + (void) WriteBlobMSBLong(image,0x00016170U); + (void) WriteBlobMSBLong(image,0x706C0000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBShort(image,768); + (void) WriteBlobMSBShort(image,(unsigned short) image->columns); + (void) WriteBlobMSBShort(image,(unsigned short) image->rows); + (void) WriteBlobMSBShort(image,(unsigned short) x_resolution); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) y_resolution); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBLong(image,length); + (void) WriteBlobMSBShort(image,0x0001); + (void) WriteBlobMSBLong(image,0x0B466F74U); + (void) WriteBlobMSBLong(image,0x6F202D20U); + (void) WriteBlobMSBLong(image,0x4A504547U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x00000000U); + (void) WriteBlobMSBLong(image,0x0018FFFFU); + (void) WriteBlob(image,length,blob); + if ((length & 0x01) != 0) + (void) WriteBlobByte(image,'\0'); + blob=(unsigned char *) RelinquishMagickMemory(blob); + } + /* + Write picture opcode, row bytes, and picture bounding box, and version. + */ + if (storage_class == PseudoClass) + (void) WriteBlobMSBShort(image,PictPICTOp); + else + { + (void) WriteBlobMSBShort(image,PictPixmapOp); + (void) WriteBlobMSBLong(image,(unsigned int) base_address); + } + (void) WriteBlobMSBShort(image,(unsigned short) (row_bytes | 0x8000)); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.top); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.left); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) bounds.right); + /* + Write pack type, pack size, resolution, pixel type, and pixel size. + */ + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.version); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.pack_type); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.pack_size); + (void) WriteBlobMSBShort(image,(unsigned short) (x_resolution+0.5)); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) (y_resolution+0.5)); + (void) WriteBlobMSBShort(image,0x0000); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.pixel_type); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.bits_per_pixel); + /* + Write component count, size, plane bytes, table size, and reserved. + */ + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_count); + (void) WriteBlobMSBShort(image,(unsigned short) pixmap.component_size); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.plane_bytes); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.table); + (void) WriteBlobMSBLong(image,(unsigned int) pixmap.reserved); + if (storage_class == PseudoClass) + { + /* + Write image colormap. + */ + (void) WriteBlobMSBLong(image,0x00000000L); /* color seed */ + (void) WriteBlobMSBShort(image,0L); /* color flags */ + (void) WriteBlobMSBShort(image,(unsigned short) (image->colors-1)); + for (i=0; i < (ssize_t) image->colors; i++) + { + (void) WriteBlobMSBShort(image,(unsigned short) i); + (void) WriteBlobMSBShort(image,ScaleQuantumToShort( + image->colormap[i].red)); + (void) WriteBlobMSBShort(image,ScaleQuantumToShort( + image->colormap[i].green)); + (void) WriteBlobMSBShort(image,ScaleQuantumToShort( + image->colormap[i].blue)); + } + } + /* + Write source and destination rectangle. + */ + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) source_rectangle.right); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.top); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.left); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.bottom); + (void) WriteBlobMSBShort(image,(unsigned short) destination_rectangle.right); + (void) WriteBlobMSBShort(image,(unsigned short) transfer_mode); + /* + Write picture data. + */ + count=0; + if (storage_class == PseudoClass) + for (y=0; y < (ssize_t) image->rows; y++) + { + p=GetVirtualPixels(image,0,y,image->columns,1,exception); + if (p == (const Quantum *) NULL) + break; + for (x=0; x < (ssize_t) image->columns; x++) + { + scanline[x]=(unsigned char) GetPixelIndex(image,p); + p+=GetPixelChannels(image); + } + count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF), + packed_scanline); + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + } + else + if (image_info->compression == JPEGCompression) + { + (void) memset(scanline,0,row_bytes); + for (y=0; y < (ssize_t) image->rows; y++) + count+=EncodeImage(image,scanline,(size_t) (row_bytes & 0x7FFF), + packed_scanline); + } + else + { + register unsigned char + *blue, + *green, + *opacity, + *red; + + red=scanline; + green=scanline+image->columns; + blue=scanline+2*image->columns; + opacity=scanline+3*image->columns; + for (y=0; y < (ssize_t) image->rows; y++) + { + p=GetVirtualPixels(image,0,y,image->columns,1,exception); + if (p == (const Quantum *) NULL) + break; + red=scanline; + green=scanline+image->columns; + blue=scanline+2*image->columns; + if (image->alpha_trait != UndefinedPixelTrait) + { + opacity=scanline; + red=scanline+image->columns; + green=scanline+2*image->columns; + blue=scanline+3*image->columns; + } + for (x=0; x < (ssize_t) image->columns; x++) + { + *red++=ScaleQuantumToChar(GetPixelRed(image,p)); + *green++=ScaleQuantumToChar(GetPixelGreen(image,p)); + *blue++=ScaleQuantumToChar(GetPixelBlue(image,p)); + if (image->alpha_trait != UndefinedPixelTrait) + *opacity++=ScaleQuantumToChar((Quantum) (GetPixelAlpha(image,p))); + p+=GetPixelChannels(image); + } + count+=EncodeImage(image,scanline,bytes_per_line,packed_scanline); + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + } + } + if ((count & 0x01) != 0) + (void) WriteBlobByte(image,'\0'); + (void) WriteBlobMSBShort(image,PictEndOfPictureOp); + offset=TellBlob(image); + offset=SeekBlob(image,512,SEEK_SET); + (void) WriteBlobMSBShort(image,(unsigned short) offset); + scanline=(unsigned char *) RelinquishMagickMemory(scanline); + packed_scanline=(unsigned char *) RelinquishMagickMemory(packed_scanline); + buffer=(unsigned char *) RelinquishMagickMemory(buffer); + (void) CloseBlob(image); + return(MagickTrue); +} +","@@ -982,6 +982,9 @@ static Image *ReadPICTImage(const ImageInfo *image_info, + Clipping rectangle. + */ + length=ReadBlobMSBShort(image); ++ if (length > GetBlobSize(image)) ++ ThrowPICTException(CorruptImageError, ++ ""InsufficientImageDataInFile""); + if (length != 0x000a) + { + for (i=0; i < (ssize_t) (length-2); i++) +@@ -1030,6 +1033,9 @@ static Image *ReadPICTImage(const ImageInfo *image_info, + if (pattern != 1) + ThrowPICTException(CorruptImageError,""UnknownPatternType""); + length=ReadBlobMSBShort(image); ++ if (length > GetBlobSize(image)) ++ ThrowPICTException(CorruptImageError, ++ ""InsufficientImageDataInFile""); + if (ReadRectangle(image,&frame) == MagickFalse) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + if (ReadPixmap(image,&pixmap) == MagickFalse) +@@ -1041,6 +1047,9 @@ static Image *ReadPICTImage(const ImageInfo *image_info, + (void) ReadBlobMSBLong(image); + flags=(ssize_t) ReadBlobMSBShort(image); + length=ReadBlobMSBShort(image); ++ if (length > GetBlobSize(image)) ++ ThrowPICTException(CorruptImageError, ++ ""InsufficientImageDataInFile""); + for (i=0; i <= (ssize_t) length; i++) + (void) ReadBlobMSBLong(image); + width=(size_t) (frame.bottom-frame.top); +@@ -1101,6 +1110,9 @@ static Image *ReadPICTImage(const ImageInfo *image_info, + Skip polygon or region. + */ + length=ReadBlobMSBShort(image); ++ if (length > GetBlobSize(image)) ++ ThrowPICTException(CorruptImageError, ++ ""InsufficientImageDataInFile""); + for (i=0; i < (ssize_t) (length-2); i++) + if (ReadBlobByte(image) == EOF) + break; +@@ -1223,6 +1235,9 @@ static Image *ReadPICTImage(const ImageInfo *image_info, + Skip region. + */ + length=ReadBlobMSBShort(image); ++ if (length > GetBlobSize(image)) ++ ThrowPICTException(CorruptImageError, ++ ""InsufficientImageDataInFile""); + for (i=0; i < (ssize_t) (length-2); i++) + if (ReadBlobByte(image) == EOF) + break; +@@ -1345,6 +1360,9 @@ static Image *ReadPICTImage(const ImageInfo *image_info, + */ + type=ReadBlobMSBShort(image); + length=ReadBlobMSBShort(image); ++ if (length > GetBlobSize(image)) ++ ThrowPICTException(CorruptImageError, ++ ""InsufficientImageDataInFile""); + if (length == 0) + break; + (void) ReadBlobMSBLong(image); +@@ -1454,6 +1472,9 @@ static Image *ReadPICTImage(const ImageInfo *image_info, + ThrowPICTException(FileOpenError,""UnableToCreateTemporaryFile""); + } + length=ReadBlobMSBLong(image); ++ if (length > GetBlobSize(image)) ++ ThrowPICTException(CorruptImageError, ++ ""InsufficientImageDataInFile""); + if (length > 154) + { + for (i=0; i < 6; i++) +@@ -1505,6 +1526,9 @@ static Image *ReadPICTImage(const ImageInfo *image_info, + Skip reserved. + */ + length=ReadBlobMSBShort(image); ++ if (length > GetBlobSize(image)) ++ ThrowPICTException(CorruptImageError, ++ ""InsufficientImageDataInFile""); + for (i=0; i < (ssize_t) length; i++) + if (ReadBlobByte(image) == EOF) + break; +@@ -1516,6 +1540,9 @@ static Image *ReadPICTImage(const ImageInfo *image_info, + Skip reserved. + */ + length=(size_t) ((code >> 7) & 0xff); ++ if (length > GetBlobSize(image)) ++ ThrowPICTException(CorruptImageError, ++ ""InsufficientImageDataInFile""); + for (i=0; i < (ssize_t) length; i++) + if (ReadBlobByte(image) == EOF) + break;",4823,5154,6144 +675," _bdf_parse_glyphs( char* line, + unsigned long linelen, + unsigned long lineno, + void* call_data, + void* client_data ) + { + int c, mask_index; + char* s; + unsigned char* bp; + unsigned long i, slen, nibbles; + + _bdf_parse_t* p; + bdf_glyph_t* glyph; + bdf_font_t* font; + + FT_Memory memory; + FT_Error error = BDF_Err_Ok; + + FT_UNUSED( call_data ); + FT_UNUSED( lineno ); /* only used in debug mode */ + + + p = (_bdf_parse_t *)client_data; + + font = p->font; + memory = font->memory; + + /* Check for a comment. */ + if ( ft_memcmp( line, ""COMMENT"", 7 ) == 0 ) + { + linelen -= 7; + + s = line + 7; + if ( *s != 0 ) + { + s++; + linelen--; + } + error = _bdf_add_comment( p->font, s, linelen ); + goto Exit; + } + + /* The very first thing expected is the number of glyphs. */ + if ( !( p->flags & _BDF_GLYPHS ) ) + { + if ( ft_memcmp( line, ""CHARS"", 5 ) != 0 ) + { + FT_ERROR(( ""_bdf_parse_glyphs: "" ERRMSG1, lineno, ""CHARS"" )); + error = BDF_Err_Missing_Chars_Field; + goto Exit; + } + + error = _bdf_list_split( &p->list, (char *)"" +"", line, linelen ); + if ( error ) + goto Exit; + p->cnt = font->glyphs_size = _bdf_atoul( p->list.field[1], 0, 10 ); + + /* Make sure the number of glyphs is non-zero. */ + if ( p->cnt == 0 ) + font->glyphs_size = 64; + + /* Limit ourselves to 1,114,112 glyphs in the font (this is the */ + /* number of code points available in Unicode). */ + if ( p->cnt >= 0x110000UL ) + { + FT_ERROR(( ""_bdf_parse_glyphs: "" ERRMSG5, lineno, ""CHARS"" )); + error = BDF_Err_Invalid_Argument; + goto Exit; + } + + if ( FT_NEW_ARRAY( font->glyphs, font->glyphs_size ) ) + goto Exit; + + p->flags |= _BDF_GLYPHS; + + goto Exit; + } + + /* Check for the ENDFONT field. */ + if ( ft_memcmp( line, ""ENDFONT"", 7 ) == 0 ) + { + /* Sort the glyphs by encoding. */ + ft_qsort( (char *)font->glyphs, + font->glyphs_used, + sizeof ( bdf_glyph_t ), + by_encoding ); + + p->flags &= ~_BDF_START; + + goto Exit; + } + + /* Check for the ENDCHAR field. */ + if ( ft_memcmp( line, ""ENDCHAR"", 7 ) == 0 ) + { + p->glyph_enc = 0; + p->flags &= ~_BDF_GLYPH_BITS; + + goto Exit; + } + + /* Check whether a glyph is being scanned but should be */ + /* ignored because it is an unencoded glyph. */ + if ( ( p->flags & _BDF_GLYPH ) && + p->glyph_enc == -1 && + p->opts->keep_unencoded == 0 ) + goto Exit; + + /* Check for the STARTCHAR field. */ + if ( ft_memcmp( line, ""STARTCHAR"", 9 ) == 0 ) + { + /* Set the character name in the parse info first until the */ + /* encoding can be checked for an unencoded character. */ + FT_FREE( p->glyph_name ); + + error = _bdf_list_split( &p->list, (char *)"" +"", line, linelen ); + if ( error ) + goto Exit; + + _bdf_list_shift( &p->list, 1 ); + + s = _bdf_list_join( &p->list, ' ', &slen ); + + if ( !s ) + { + FT_ERROR(( ""_bdf_parse_glyphs: "" ERRMSG8, lineno, ""STARTCHAR"" )); + error = BDF_Err_Invalid_File_Format; + goto Exit; + } + + if ( FT_NEW_ARRAY( p->glyph_name, slen + 1 ) ) + goto Exit; + + FT_MEM_COPY( p->glyph_name, s, slen + 1 ); + + p->flags |= _BDF_GLYPH; + + FT_TRACE4(( DBGMSG1, lineno, s )); + + goto Exit; + } + + /* Check for the ENCODING field. */ + if ( ft_memcmp( line, ""ENCODING"", 8 ) == 0 ) + { + if ( !( p->flags & _BDF_GLYPH ) ) + { + /* Missing STARTCHAR field. */ + FT_ERROR(( ""_bdf_parse_glyphs: "" ERRMSG1, lineno, ""STARTCHAR"" )); + error = BDF_Err_Missing_Startchar_Field; + goto Exit; + } + + error = _bdf_list_split( &p->list, (char *)"" +"", line, linelen ); + if ( error ) + goto Exit; + + p->glyph_enc = _bdf_atol( p->list.field[1], 0, 10 ); + + /* Normalize negative encoding values. The specification only */ + /* allows -1, but we can be more generous here. */ + if ( p->glyph_enc < -1 ) + p->glyph_enc = -1; + + /* Check for alternative encoding format. */ + if ( p->glyph_enc == -1 && p->list.used > 2 ) + p->glyph_enc = _bdf_atol( p->list.field[2], 0, 10 ); + + FT_TRACE4(( DBGMSG2, p->glyph_enc )); + + /* Check that the encoding is in the Unicode range because */ + /* otherwise p->have (a bitmap with static size) overflows. */ + if ( p->glyph_enc > 0 && + (size_t)p->glyph_enc >= sizeof ( p->have ) * 8 ) + { + FT_ERROR(( ""_bdf_parse_glyphs: "" ERRMSG5, lineno, ""ENCODING"" )); + error = BDF_Err_Invalid_File_Format; + goto Exit; + } + + /* Check whether this encoding has already been encountered. */ + /* If it has then change it to unencoded so it gets added if */ + /* indicated. */ + if ( p->glyph_enc >= 0 ) + { + if ( _bdf_glyph_modified( p->have, p->glyph_enc ) ) + { + /* Emit a message saying a glyph has been moved to the */ + /* unencoded area. */ + FT_TRACE2(( ""_bdf_parse_glyphs: "" ACMSG12, + p->glyph_enc, p->glyph_name )); + p->glyph_enc = -1; + font->modified = 1; + } + else + _bdf_set_glyph_modified( p->have, p->glyph_enc ); + } + + if ( p->glyph_enc >= 0 ) + { + /* Make sure there are enough glyphs allocated in case the */ + /* number of characters happen to be wrong. */ + if ( font->glyphs_used == font->glyphs_size ) + { + if ( FT_RENEW_ARRAY( font->glyphs, + font->glyphs_size, + font->glyphs_size + 64 ) ) + goto Exit; + + font->glyphs_size += 64; + } + + glyph = font->glyphs + font->glyphs_used++; + glyph->name = p->glyph_name; + glyph->encoding = p->glyph_enc; + + /* Reset the initial glyph info. */ + p->glyph_name = 0; + } + else + { + /* Unencoded glyph. Check whether it should */ + /* be added or not. */ + if ( p->opts->keep_unencoded != 0 ) + { + /* Allocate the next unencoded glyph. */ + if ( font->unencoded_used == font->unencoded_size ) + { + if ( FT_RENEW_ARRAY( font->unencoded , + font->unencoded_size, + font->unencoded_size + 4 ) ) + goto Exit; + + font->unencoded_size += 4; + } + + glyph = font->unencoded + font->unencoded_used; + glyph->name = p->glyph_name; + glyph->encoding = font->unencoded_used++; + } + else + /* Free up the glyph name if the unencoded shouldn't be */ + /* kept. */ + FT_FREE( p->glyph_name ); + + p->glyph_name = 0; + } + + /* Clear the flags that might be added when width and height are */ + /* checked for consistency. */ + p->flags &= ~( _BDF_GLYPH_WIDTH_CHECK | _BDF_GLYPH_HEIGHT_CHECK ); + + p->flags |= _BDF_ENCODING; + + goto Exit; + } + + /* Point at the glyph being constructed. */ + if ( p->glyph_enc == -1 ) + glyph = font->unencoded + ( font->unencoded_used - 1 ); + else + glyph = font->glyphs + ( font->glyphs_used - 1 ); + + /* Check whether a bitmap is being constructed. */ + if ( p->flags & _BDF_BITMAP ) + { + /* If there are more rows than are specified in the glyph metrics, */ + /* ignore the remaining lines. */ + if ( p->row >= (unsigned long)glyph->bbx.height ) + { + if ( !( p->flags & _BDF_GLYPH_HEIGHT_CHECK ) ) + { + FT_TRACE2(( ""_bdf_parse_glyphs: "" ACMSG13, glyph->encoding )); + p->flags |= _BDF_GLYPH_HEIGHT_CHECK; + font->modified = 1; + } + + goto Exit; + } + + /* Only collect the number of nibbles indicated by the glyph */ + /* metrics. If there are more columns, they are simply ignored. */ + nibbles = glyph->bpr << 1; + bp = glyph->bitmap + p->row * glyph->bpr; + + for ( i = 0; i < nibbles; i++ ) + { + c = line[i]; + if ( !sbitset( hdigits, c ) ) + break; + *bp = (FT_Byte)( ( *bp << 4 ) + a2i[c] ); + if ( i + 1 < nibbles && ( i & 1 ) ) + *++bp = 0; + } + + /* If any line has not enough columns, */ + /* indicate they have been padded with zero bits. */ + if ( i < nibbles && + !( p->flags & _BDF_GLYPH_WIDTH_CHECK ) ) + { + FT_TRACE2(( ""_bdf_parse_glyphs: "" ACMSG16, glyph->encoding )); + p->flags |= _BDF_GLYPH_WIDTH_CHECK; + font->modified = 1; + } + + /* Remove possible garbage at the right. */ + mask_index = ( glyph->bbx.width * p->font->bpp ) & 7; + if ( glyph->bbx.width ) + *bp &= nibble_mask[mask_index]; + + /* If any line has extra columns, indicate they have been removed. */ + if ( i == nibbles && + sbitset( hdigits, line[nibbles] ) && + !( p->flags & _BDF_GLYPH_WIDTH_CHECK ) ) + { + FT_TRACE2(( ""_bdf_parse_glyphs: "" ACMSG14, glyph->encoding )); + p->flags |= _BDF_GLYPH_WIDTH_CHECK; + font->modified = 1; + } + + p->row++; + goto Exit; + } + + /* Expect the SWIDTH (scalable width) field next. */ + if ( ft_memcmp( line, ""SWIDTH"", 6 ) == 0 ) + { + if ( !( p->flags & _BDF_ENCODING ) ) + goto Missing_Encoding; + + error = _bdf_list_split( &p->list, (char *)"" +"", line, linelen ); + if ( error ) + goto Exit; + + glyph->swidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 ); + p->flags |= _BDF_SWIDTH; + + goto Exit; + } + + /* Expect the DWIDTH (scalable width) field next. */ + if ( ft_memcmp( line, ""DWIDTH"", 6 ) == 0 ) + { + if ( !( p->flags & _BDF_ENCODING ) ) + goto Missing_Encoding; + + error = _bdf_list_split( &p->list, (char *)"" +"", line, linelen ); + if ( error ) + goto Exit; + + glyph->dwidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 ); + + if ( !( p->flags & _BDF_SWIDTH ) ) + { + /* Missing SWIDTH field. Emit an auto correction message and set */ + /* the scalable width from the device width. */ + FT_TRACE2(( ""_bdf_parse_glyphs: "" ACMSG9, lineno )); + + glyph->swidth = (unsigned short)FT_MulDiv( + glyph->dwidth, 72000L, + (FT_Long)( font->point_size * + font->resolution_x ) ); + } + + p->flags |= _BDF_DWIDTH; + goto Exit; + } + + /* Expect the BBX field next. */ + if ( ft_memcmp( line, ""BBX"", 3 ) == 0 ) + { + if ( !( p->flags & _BDF_ENCODING ) ) + goto Missing_Encoding; + + error = _bdf_list_split( &p->list, (char *)"" +"", line, linelen ); + if ( error ) + goto Exit; + + glyph->bbx.width = _bdf_atos( p->list.field[1], 0, 10 ); + glyph->bbx.height = _bdf_atos( p->list.field[2], 0, 10 ); + glyph->bbx.x_offset = _bdf_atos( p->list.field[3], 0, 10 ); + glyph->bbx.y_offset = _bdf_atos( p->list.field[4], 0, 10 ); + + /* Generate the ascent and descent of the character. */ + glyph->bbx.ascent = (short)( glyph->bbx.height + glyph->bbx.y_offset ); + glyph->bbx.descent = (short)( -glyph->bbx.y_offset ); + + /* Determine the overall font bounding box as the characters are */ + /* loaded so corrections can be done later if indicated. */ + p->maxas = (short)FT_MAX( glyph->bbx.ascent, p->maxas ); + p->maxds = (short)FT_MAX( glyph->bbx.descent, p->maxds ); + + p->rbearing = (short)( glyph->bbx.width + glyph->bbx.x_offset ); + + p->maxrb = (short)FT_MAX( p->rbearing, p->maxrb ); + p->minlb = (short)FT_MIN( glyph->bbx.x_offset, p->minlb ); + p->maxlb = (short)FT_MAX( glyph->bbx.x_offset, p->maxlb ); + + if ( !( p->flags & _BDF_DWIDTH ) ) + { + /* Missing DWIDTH field. Emit an auto correction message and set */ + /* the device width to the glyph width. */ + FT_TRACE2(( ""_bdf_parse_glyphs: "" ACMSG10, lineno )); + glyph->dwidth = glyph->bbx.width; + } + + /* If the BDF_CORRECT_METRICS flag is set, then adjust the SWIDTH */ + /* value if necessary. */ + if ( p->opts->correct_metrics != 0 ) + { + /* Determine the point size of the glyph. */ + unsigned short sw = (unsigned short)FT_MulDiv( + glyph->dwidth, 72000L, + (FT_Long)( font->point_size * + font->resolution_x ) ); + + + if ( sw != glyph->swidth ) + { + glyph->swidth = sw; + + if ( p->glyph_enc == -1 ) + _bdf_set_glyph_modified( font->umod, + font->unencoded_used - 1 ); + else + _bdf_set_glyph_modified( font->nmod, glyph->encoding ); + + p->flags |= _BDF_SWIDTH_ADJ; + font->modified = 1; + } + } + + p->flags |= _BDF_BBX; + goto Exit; + } + + /* And finally, gather up the bitmap. */ + if ( ft_memcmp( line, ""BITMAP"", 6 ) == 0 ) + { + unsigned long bitmap_size; + + + if ( !( p->flags & _BDF_BBX ) ) + { + /* Missing BBX field. */ + FT_ERROR(( ""_bdf_parse_glyphs: "" ERRMSG1, lineno, ""BBX"" )); + error = BDF_Err_Missing_Bbx_Field; + goto Exit; + } + + /* Allocate enough space for the bitmap. */ + glyph->bpr = ( glyph->bbx.width * p->font->bpp + 7 ) >> 3; + + bitmap_size = glyph->bpr * glyph->bbx.height; + if ( glyph->bpr > 0xFFFFU || bitmap_size > 0xFFFFU ) + { + FT_ERROR(( ""_bdf_parse_glyphs: "" ERRMSG4, lineno )); + error = BDF_Err_Bbx_Too_Big; + goto Exit; + } + else + glyph->bytes = (unsigned short)bitmap_size; + + if ( FT_NEW_ARRAY( glyph->bitmap, glyph->bytes ) ) + goto Exit; + + p->row = 0; + p->flags |= _BDF_BITMAP; + + goto Exit; + } + + FT_ERROR(( ""_bdf_parse_glyphs: "" ERRMSG9, lineno )); + error = BDF_Err_Invalid_File_Format; + goto Exit; + + Missing_Encoding: + /* Missing ENCODING field. */ + FT_ERROR(( ""_bdf_parse_glyphs: "" ERRMSG1, lineno, ""ENCODING"" )); + error = BDF_Err_Missing_Encoding_Field; + + Exit: + if ( error && ( p->flags & _BDF_GLYPH ) ) + FT_FREE( p->glyph_name ); + + return error; + } +",0," _bdf_parse_glyphs( char* line, + unsigned long linelen, + unsigned long lineno, + void* call_data, + void* client_data ) + { + int c, mask_index; + char* s; + unsigned char* bp; + unsigned long i, slen, nibbles; + + _bdf_parse_t* p; + bdf_glyph_t* glyph; + bdf_font_t* font; + + FT_Memory memory; + FT_Error error = BDF_Err_Ok; + + FT_UNUSED( call_data ); + FT_UNUSED( lineno ); /* only used in debug mode */ + + + p = (_bdf_parse_t *)client_data; + + font = p->font; + memory = font->memory; + + /* Check for a comment. */ + if ( ft_memcmp( line, ""COMMENT"", 7 ) == 0 ) + { + linelen -= 7; + + s = line + 7; + if ( *s != 0 ) + { + s++; + linelen--; + } + error = _bdf_add_comment( p->font, s, linelen ); + goto Exit; + } + + /* The very first thing expected is the number of glyphs. */ + if ( !( p->flags & _BDF_GLYPHS ) ) + { + if ( ft_memcmp( line, ""CHARS"", 5 ) != 0 ) + { + FT_ERROR(( ""_bdf_parse_glyphs: "" ERRMSG1, lineno, ""CHARS"" )); + error = BDF_Err_Missing_Chars_Field; + goto Exit; + } + + error = _bdf_list_split( &p->list, (char *)"" +"", line, linelen ); + if ( error ) + goto Exit; + p->cnt = font->glyphs_size = _bdf_atoul( p->list.field[1], 0, 10 ); + + /* Make sure the number of glyphs is non-zero. */ + if ( p->cnt == 0 ) + font->glyphs_size = 64; + + /* Limit ourselves to 1,114,112 glyphs in the font (this is the */ + /* number of code points available in Unicode). */ + if ( p->cnt >= 0x110000UL ) + { + FT_ERROR(( ""_bdf_parse_glyphs: "" ERRMSG5, lineno, ""CHARS"" )); + error = BDF_Err_Invalid_Argument; + goto Exit; + } + + if ( FT_NEW_ARRAY( font->glyphs, font->glyphs_size ) ) + goto Exit; + + p->flags |= _BDF_GLYPHS; + + goto Exit; + } + + /* Check for the ENDFONT field. */ + if ( ft_memcmp( line, ""ENDFONT"", 7 ) == 0 ) + { + /* Sort the glyphs by encoding. */ + ft_qsort( (char *)font->glyphs, + font->glyphs_used, + sizeof ( bdf_glyph_t ), + by_encoding ); + + p->flags &= ~_BDF_START; + + goto Exit; + } + + /* Check for the ENDCHAR field. */ + if ( ft_memcmp( line, ""ENDCHAR"", 7 ) == 0 ) + { + p->glyph_enc = 0; + p->flags &= ~_BDF_GLYPH_BITS; + + goto Exit; + } + + /* Check whether a glyph is being scanned but should be */ + /* ignored because it is an unencoded glyph. */ + if ( ( p->flags & _BDF_GLYPH ) && + p->glyph_enc == -1 && + p->opts->keep_unencoded == 0 ) + goto Exit; + + /* Check for the STARTCHAR field. */ + if ( ft_memcmp( line, ""STARTCHAR"", 9 ) == 0 ) + { + /* Set the character name in the parse info first until the */ + /* encoding can be checked for an unencoded character. */ + FT_FREE( p->glyph_name ); + + error = _bdf_list_split( &p->list, (char *)"" +"", line, linelen ); + if ( error ) + goto Exit; + + _bdf_list_shift( &p->list, 1 ); + + s = _bdf_list_join( &p->list, ' ', &slen ); + + if ( !s ) + { + FT_ERROR(( ""_bdf_parse_glyphs: "" ERRMSG8, lineno, ""STARTCHAR"" )); + error = BDF_Err_Invalid_File_Format; + goto Exit; + } + + if ( FT_NEW_ARRAY( p->glyph_name, slen + 1 ) ) + goto Exit; + + FT_MEM_COPY( p->glyph_name, s, slen + 1 ); + + p->flags |= _BDF_GLYPH; + + FT_TRACE4(( DBGMSG1, lineno, s )); + + goto Exit; + } + + /* Check for the ENCODING field. */ + if ( ft_memcmp( line, ""ENCODING"", 8 ) == 0 ) + { + if ( !( p->flags & _BDF_GLYPH ) ) + { + /* Missing STARTCHAR field. */ + FT_ERROR(( ""_bdf_parse_glyphs: "" ERRMSG1, lineno, ""STARTCHAR"" )); + error = BDF_Err_Missing_Startchar_Field; + goto Exit; + } + + error = _bdf_list_split( &p->list, (char *)"" +"", line, linelen ); + if ( error ) + goto Exit; + + p->glyph_enc = _bdf_atol( p->list.field[1], 0, 10 ); + + /* Normalize negative encoding values. The specification only */ + /* allows -1, but we can be more generous here. */ + if ( p->glyph_enc < -1 ) + p->glyph_enc = -1; + + /* Check for alternative encoding format. */ + if ( p->glyph_enc == -1 && p->list.used > 2 ) + p->glyph_enc = _bdf_atol( p->list.field[2], 0, 10 ); + + FT_TRACE4(( DBGMSG2, p->glyph_enc )); + + /* Check that the encoding is in the Unicode range because */ + /* otherwise p->have (a bitmap with static size) overflows. */ + if ( p->glyph_enc > 0 && + (size_t)p->glyph_enc >= sizeof ( p->have ) * 8 ) + { + FT_ERROR(( ""_bdf_parse_glyphs: "" ERRMSG5, lineno, ""ENCODING"" )); + error = BDF_Err_Invalid_File_Format; + goto Exit; + } + + /* Check whether this encoding has already been encountered. */ + /* If it has then change it to unencoded so it gets added if */ + /* indicated. */ + if ( p->glyph_enc >= 0 ) + { + if ( _bdf_glyph_modified( p->have, p->glyph_enc ) ) + { + /* Emit a message saying a glyph has been moved to the */ + /* unencoded area. */ + FT_TRACE2(( ""_bdf_parse_glyphs: "" ACMSG12, + p->glyph_enc, p->glyph_name )); + p->glyph_enc = -1; + font->modified = 1; + } + else + _bdf_set_glyph_modified( p->have, p->glyph_enc ); + } + + if ( p->glyph_enc >= 0 ) + { + /* Make sure there are enough glyphs allocated in case the */ + /* number of characters happen to be wrong. */ + if ( font->glyphs_used == font->glyphs_size ) + { + if ( FT_RENEW_ARRAY( font->glyphs, + font->glyphs_size, + font->glyphs_size + 64 ) ) + goto Exit; + + font->glyphs_size += 64; + } + + glyph = font->glyphs + font->glyphs_used++; + glyph->name = p->glyph_name; + glyph->encoding = p->glyph_enc; + + /* Reset the initial glyph info. */ + p->glyph_name = 0; + } + else + { + /* Unencoded glyph. Check whether it should */ + /* be added or not. */ + if ( p->opts->keep_unencoded != 0 ) + { + /* Allocate the next unencoded glyph. */ + if ( font->unencoded_used == font->unencoded_size ) + { + if ( FT_RENEW_ARRAY( font->unencoded , + font->unencoded_size, + font->unencoded_size + 4 ) ) + goto Exit; + + font->unencoded_size += 4; + } + + glyph = font->unencoded + font->unencoded_used; + glyph->name = p->glyph_name; + glyph->encoding = font->unencoded_used++; + } + else + /* Free up the glyph name if the unencoded shouldn't be */ + /* kept. */ + FT_FREE( p->glyph_name ); + + p->glyph_name = 0; + } + + /* Clear the flags that might be added when width and height are */ + /* checked for consistency. */ + p->flags &= ~( _BDF_GLYPH_WIDTH_CHECK | _BDF_GLYPH_HEIGHT_CHECK ); + + p->flags |= _BDF_ENCODING; + + goto Exit; + } + + /* Point at the glyph being constructed. */ + if ( p->glyph_enc == -1 ) + glyph = font->unencoded + ( font->unencoded_used - 1 ); + else + glyph = font->glyphs + ( font->glyphs_used - 1 ); + + /* Check whether a bitmap is being constructed. */ + if ( p->flags & _BDF_BITMAP ) + { + /* If there are more rows than are specified in the glyph metrics, */ + /* ignore the remaining lines. */ + if ( p->row >= (unsigned long)glyph->bbx.height ) + { + if ( !( p->flags & _BDF_GLYPH_HEIGHT_CHECK ) ) + { + FT_TRACE2(( ""_bdf_parse_glyphs: "" ACMSG13, glyph->encoding )); + p->flags |= _BDF_GLYPH_HEIGHT_CHECK; + font->modified = 1; + } + + goto Exit; + } + + /* Only collect the number of nibbles indicated by the glyph */ + /* metrics. If there are more columns, they are simply ignored. */ + nibbles = glyph->bpr << 1; + bp = glyph->bitmap + p->row * glyph->bpr; + + for ( i = 0; i < nibbles; i++ ) + { + c = line[i]; + if ( !sbitset( hdigits, c ) ) + break; + *bp = (FT_Byte)( ( *bp << 4 ) + a2i[c] ); + if ( i + 1 < nibbles && ( i & 1 ) ) + *++bp = 0; + } + + /* If any line has not enough columns, */ + /* indicate they have been padded with zero bits. */ + if ( i < nibbles && + !( p->flags & _BDF_GLYPH_WIDTH_CHECK ) ) + { + FT_TRACE2(( ""_bdf_parse_glyphs: "" ACMSG16, glyph->encoding )); + p->flags |= _BDF_GLYPH_WIDTH_CHECK; + font->modified = 1; + } + + /* Remove possible garbage at the right. */ + mask_index = ( glyph->bbx.width * p->font->bpp ) & 7; + if ( glyph->bbx.width ) + *bp &= nibble_mask[mask_index]; + + /* If any line has extra columns, indicate they have been removed. */ + if ( i == nibbles && + sbitset( hdigits, line[nibbles] ) && + !( p->flags & _BDF_GLYPH_WIDTH_CHECK ) ) + { + FT_TRACE2(( ""_bdf_parse_glyphs: "" ACMSG14, glyph->encoding )); + p->flags |= _BDF_GLYPH_WIDTH_CHECK; + font->modified = 1; + } + + p->row++; + goto Exit; + } + + /* Expect the SWIDTH (scalable width) field next. */ + if ( ft_memcmp( line, ""SWIDTH"", 6 ) == 0 ) + { + if ( !( p->flags & _BDF_ENCODING ) ) + goto Missing_Encoding; + + error = _bdf_list_split( &p->list, (char *)"" +"", line, linelen ); + if ( error ) + goto Exit; + + glyph->swidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 ); + p->flags |= _BDF_SWIDTH; + + goto Exit; + } + + /* Expect the DWIDTH (scalable width) field next. */ + if ( ft_memcmp( line, ""DWIDTH"", 6 ) == 0 ) + { + if ( !( p->flags & _BDF_ENCODING ) ) + goto Missing_Encoding; + + error = _bdf_list_split( &p->list, (char *)"" +"", line, linelen ); + if ( error ) + goto Exit; + + glyph->dwidth = (unsigned short)_bdf_atoul( p->list.field[1], 0, 10 ); + + if ( !( p->flags & _BDF_SWIDTH ) ) + { + /* Missing SWIDTH field. Emit an auto correction message and set */ + /* the scalable width from the device width. */ + FT_TRACE2(( ""_bdf_parse_glyphs: "" ACMSG9, lineno )); + + glyph->swidth = (unsigned short)FT_MulDiv( + glyph->dwidth, 72000L, + (FT_Long)( font->point_size * + font->resolution_x ) ); + } + + p->flags |= _BDF_DWIDTH; + goto Exit; + } + + /* Expect the BBX field next. */ + if ( ft_memcmp( line, ""BBX"", 3 ) == 0 ) + { + if ( !( p->flags & _BDF_ENCODING ) ) + goto Missing_Encoding; + + error = _bdf_list_split( &p->list, (char *)"" +"", line, linelen ); + if ( error ) + goto Exit; + + glyph->bbx.width = _bdf_atos( p->list.field[1], 0, 10 ); + glyph->bbx.height = _bdf_atos( p->list.field[2], 0, 10 ); + glyph->bbx.x_offset = _bdf_atos( p->list.field[3], 0, 10 ); + glyph->bbx.y_offset = _bdf_atos( p->list.field[4], 0, 10 ); + + /* Generate the ascent and descent of the character. */ + glyph->bbx.ascent = (short)( glyph->bbx.height + glyph->bbx.y_offset ); + glyph->bbx.descent = (short)( -glyph->bbx.y_offset ); + + /* Determine the overall font bounding box as the characters are */ + /* loaded so corrections can be done later if indicated. */ + p->maxas = (short)FT_MAX( glyph->bbx.ascent, p->maxas ); + p->maxds = (short)FT_MAX( glyph->bbx.descent, p->maxds ); + + p->rbearing = (short)( glyph->bbx.width + glyph->bbx.x_offset ); + + p->maxrb = (short)FT_MAX( p->rbearing, p->maxrb ); + p->minlb = (short)FT_MIN( glyph->bbx.x_offset, p->minlb ); + p->maxlb = (short)FT_MAX( glyph->bbx.x_offset, p->maxlb ); + + if ( !( p->flags & _BDF_DWIDTH ) ) + { + /* Missing DWIDTH field. Emit an auto correction message and set */ + /* the device width to the glyph width. */ + FT_TRACE2(( ""_bdf_parse_glyphs: "" ACMSG10, lineno )); + glyph->dwidth = glyph->bbx.width; + } + + /* If the BDF_CORRECT_METRICS flag is set, then adjust the SWIDTH */ + /* value if necessary. */ + if ( p->opts->correct_metrics != 0 ) + { + /* Determine the point size of the glyph. */ + unsigned short sw = (unsigned short)FT_MulDiv( + glyph->dwidth, 72000L, + (FT_Long)( font->point_size * + font->resolution_x ) ); + + + if ( sw != glyph->swidth ) + { + glyph->swidth = sw; + + if ( p->glyph_enc == -1 ) + _bdf_set_glyph_modified( font->umod, + font->unencoded_used - 1 ); + else + _bdf_set_glyph_modified( font->nmod, glyph->encoding ); + + p->flags |= _BDF_SWIDTH_ADJ; + font->modified = 1; + } + } + + p->flags |= _BDF_BBX; + goto Exit; + } + + /* And finally, gather up the bitmap. */ + if ( ft_memcmp( line, ""BITMAP"", 6 ) == 0 ) + { + unsigned long bitmap_size; + + + if ( !( p->flags & _BDF_BBX ) ) + { + /* Missing BBX field. */ + FT_ERROR(( ""_bdf_parse_glyphs: "" ERRMSG1, lineno, ""BBX"" )); + error = BDF_Err_Missing_Bbx_Field; + goto Exit; + } + + /* Allocate enough space for the bitmap. */ + glyph->bpr = ( glyph->bbx.width * p->font->bpp + 7 ) >> 3; + + bitmap_size = glyph->bpr * glyph->bbx.height; + if ( glyph->bpr > 0xFFFFU || bitmap_size > 0xFFFFU ) + { + FT_ERROR(( ""_bdf_parse_glyphs: "" ERRMSG4, lineno )); + error = BDF_Err_Bbx_Too_Big; + goto Exit; + } + else + glyph->bytes = (unsigned short)bitmap_size; + + if ( FT_NEW_ARRAY( glyph->bitmap, glyph->bytes ) ) + goto Exit; + + p->row = 0; + p->flags |= _BDF_BITMAP; + + goto Exit; + } + + FT_ERROR(( ""_bdf_parse_glyphs: "" ERRMSG9, lineno )); + error = BDF_Err_Invalid_File_Format; + goto Exit; + + Missing_Encoding: + /* Missing ENCODING field. */ + FT_ERROR(( ""_bdf_parse_glyphs: "" ERRMSG1, lineno, ""ENCODING"" )); + error = BDF_Err_Missing_Encoding_Field; + + Exit: + if ( error && ( p->flags & _BDF_GLYPH ) ) + FT_FREE( p->glyph_name ); + + return error; + } +","@@ -2169,7 +2169,10 @@ + p->cnt = p->font->props_size = _bdf_atoul( p->list.field[1], 0, 10 ); + + if ( FT_NEW_ARRAY( p->font->props, p->cnt ) ) ++ { ++ p->font->props_size = 0; + goto Exit; ++ } + + p->flags |= _BDF_PROPS; + *next = _bdf_parse_properties;",4156,4487,6144 +8966,"parse_args_recurse (int *argcp, + const char ***argvp, + bool in_file, + int *total_parsed_argc_p) +{ + SetupOp *op; + int argc = *argcp; + const char **argv = *argvp; + /* I can't imagine a case where someone wants more than this. + * If you do...you should be able to pass multiple files + * via a single tmpfs and linking them there, etc. + * + * We're adding this hardening due to precedent from + * http://googleprojectzero.blogspot.com/2014/08/the-poisoned-nul-byte-2014-edition.html + * + * I picked 9000 because the Internet told me to and it was hard to + * resist. + */ + static const uint32_t MAX_ARGS = 9000; + + if (*total_parsed_argc_p > MAX_ARGS) + die (""Exceeded maximum number of arguments %u"", MAX_ARGS); + + while (argc > 0) + { + const char *arg = argv[0]; + + if (strcmp (arg, ""--help"") == 0) + { + usage (EXIT_SUCCESS, stdout); + } + else if (strcmp (arg, ""--version"") == 0) + { + print_version_and_exit (); + } + else if (strcmp (arg, ""--args"") == 0) + { + int the_fd; + char *endptr; + const char *p, *data_end; + size_t data_len; + cleanup_free const char **data_argv = NULL; + const char **data_argv_copy; + int data_argc; + int i; + + if (in_file) + die (""--args not supported in arguments file""); + + if (argc < 2) + die (""--args takes an argument""); + + the_fd = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) + die (""Invalid fd: %s"", argv[1]); + + /* opt_args_data is essentially a recursive argv array, which we must + * keep allocated until exit time, since its argv entries get used + * by the other cases in parse_args_recurse() when we recurse. */ + opt_args_data = load_file_data (the_fd, &data_len); + if (opt_args_data == NULL) + die_with_error (""Can't read --args data""); + (void) close (the_fd); + + data_end = opt_args_data + data_len; + data_argc = 0; + + p = opt_args_data; + while (p != NULL && p < data_end) + { + data_argc++; + (*total_parsed_argc_p)++; + if (*total_parsed_argc_p > MAX_ARGS) + die (""Exceeded maximum number of arguments %u"", MAX_ARGS); + p = memchr (p, 0, data_end - p); + if (p != NULL) + p++; + } + + data_argv = xcalloc (sizeof (char *) * (data_argc + 1)); + + i = 0; + p = opt_args_data; + while (p != NULL && p < data_end) + { + /* Note: load_file_data always adds a nul terminator, so this is safe + * even for the last string. */ + data_argv[i++] = p; + p = memchr (p, 0, data_end - p); + if (p != NULL) + p++; + } + + data_argv_copy = data_argv; /* Don't change data_argv, we need to free it */ + parse_args_recurse (&data_argc, &data_argv_copy, TRUE, total_parsed_argc_p); + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--unshare-all"") == 0) + { + /* Keep this in order with the older (legacy) --unshare arguments, + * we use the --try variants of user and cgroup, since we want + * to support systems/kernels without support for those. + */ + opt_unshare_user_try = opt_unshare_ipc = opt_unshare_pid = + opt_unshare_uts = opt_unshare_cgroup_try = + opt_unshare_net = TRUE; + } + /* Begin here the older individual --unshare variants */ + else if (strcmp (arg, ""--unshare-user"") == 0) + { + opt_unshare_user = TRUE; + } + else if (strcmp (arg, ""--unshare-user-try"") == 0) + { + opt_unshare_user_try = TRUE; + } + else if (strcmp (arg, ""--unshare-ipc"") == 0) + { + opt_unshare_ipc = TRUE; + } + else if (strcmp (arg, ""--unshare-pid"") == 0) + { + opt_unshare_pid = TRUE; + } + else if (strcmp (arg, ""--unshare-net"") == 0) + { + opt_unshare_net = TRUE; + } + else if (strcmp (arg, ""--unshare-uts"") == 0) + { + opt_unshare_uts = TRUE; + } + else if (strcmp (arg, ""--unshare-cgroup"") == 0) + { + opt_unshare_cgroup = TRUE; + } + else if (strcmp (arg, ""--unshare-cgroup-try"") == 0) + { + opt_unshare_cgroup_try = TRUE; + } + /* Begin here the newer --share variants */ + else if (strcmp (arg, ""--share-net"") == 0) + { + opt_unshare_net = FALSE; + } + /* End --share variants, other arguments begin */ + else if (strcmp (arg, ""--chdir"") == 0) + { + if (argc < 2) + die (""--chdir takes one argument""); + + opt_chdir_path = argv[1]; + argv++; + argc--; + } + else if (strcmp (arg, ""--remount-ro"") == 0) + { + if (argc < 2) + die (""--remount-ro takes one argument""); + + SetupOp *op = setup_op_new (SETUP_REMOUNT_RO_NO_RECURSIVE); + op->dest = argv[1]; + + argv++; + argc--; + } + else if (strcmp(arg, ""--bind"") == 0 || + strcmp(arg, ""--bind-try"") == 0) + { + if (argc < 3) + die (""%s takes two arguments"", arg); + + op = setup_op_new (SETUP_BIND_MOUNT); + op->source = argv[1]; + op->dest = argv[2]; + if (strcmp(arg, ""--bind-try"") == 0) + op->flags = ALLOW_NOTEXIST; + + argv += 2; + argc -= 2; + } + else if (strcmp(arg, ""--ro-bind"") == 0 || + strcmp(arg, ""--ro-bind-try"") == 0) + { + if (argc < 3) + die (""%s takes two arguments"", arg); + + op = setup_op_new (SETUP_RO_BIND_MOUNT); + op->source = argv[1]; + op->dest = argv[2]; + if (strcmp(arg, ""--ro-bind-try"") == 0) + op->flags = ALLOW_NOTEXIST; + + argv += 2; + argc -= 2; + } + else if (strcmp (arg, ""--dev-bind"") == 0 || + strcmp (arg, ""--dev-bind-try"") == 0) + { + if (argc < 3) + die (""%s takes two arguments"", arg); + + op = setup_op_new (SETUP_DEV_BIND_MOUNT); + op->source = argv[1]; + op->dest = argv[2]; + if (strcmp(arg, ""--dev-bind-try"") == 0) + op->flags = ALLOW_NOTEXIST; + + argv += 2; + argc -= 2; + } + else if (strcmp (arg, ""--proc"") == 0) + { + if (argc < 2) + die (""--proc takes an argument""); + + op = setup_op_new (SETUP_MOUNT_PROC); + op->dest = argv[1]; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--exec-label"") == 0) + { + if (argc < 2) + die (""--exec-label takes an argument""); + opt_exec_label = argv[1]; + die_unless_label_valid (opt_exec_label); + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--file-label"") == 0) + { + if (argc < 2) + die (""--file-label takes an argument""); + opt_file_label = argv[1]; + die_unless_label_valid (opt_file_label); + if (label_create_file (opt_file_label)) + die_with_error (""--file-label setup failed""); + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--dev"") == 0) + { + if (argc < 2) + die (""--dev takes an argument""); + + op = setup_op_new (SETUP_MOUNT_DEV); + op->dest = argv[1]; + opt_needs_devpts = TRUE; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--tmpfs"") == 0) + { + if (argc < 2) + die (""--tmpfs takes an argument""); + + op = setup_op_new (SETUP_MOUNT_TMPFS); + op->dest = argv[1]; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--mqueue"") == 0) + { + if (argc < 2) + die (""--mqueue takes an argument""); + + op = setup_op_new (SETUP_MOUNT_MQUEUE); + op->dest = argv[1]; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--dir"") == 0) + { + if (argc < 2) + die (""--dir takes an argument""); + + op = setup_op_new (SETUP_MAKE_DIR); + op->dest = argv[1]; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--file"") == 0) + { + int file_fd; + char *endptr; + + if (argc < 3) + die (""--file takes two arguments""); + + file_fd = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0) + die (""Invalid fd: %s"", argv[1]); + + op = setup_op_new (SETUP_MAKE_FILE); + op->fd = file_fd; + op->dest = argv[2]; + + argv += 2; + argc -= 2; + } + else if (strcmp (arg, ""--bind-data"") == 0) + { + int file_fd; + char *endptr; + + if (argc < 3) + die (""--bind-data takes two arguments""); + + file_fd = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0) + die (""Invalid fd: %s"", argv[1]); + + op = setup_op_new (SETUP_MAKE_BIND_FILE); + op->fd = file_fd; + op->dest = argv[2]; + + argv += 2; + argc -= 2; + } + else if (strcmp (arg, ""--ro-bind-data"") == 0) + { + int file_fd; + char *endptr; + + if (argc < 3) + die (""--ro-bind-data takes two arguments""); + + file_fd = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0) + die (""Invalid fd: %s"", argv[1]); + + op = setup_op_new (SETUP_MAKE_RO_BIND_FILE); + op->fd = file_fd; + op->dest = argv[2]; + + argv += 2; + argc -= 2; + } + else if (strcmp (arg, ""--symlink"") == 0) + { + if (argc < 3) + die (""--symlink takes two arguments""); + + op = setup_op_new (SETUP_MAKE_SYMLINK); + op->source = argv[1]; + op->dest = argv[2]; + + argv += 2; + argc -= 2; + } + else if (strcmp (arg, ""--lock-file"") == 0) + { + if (argc < 2) + die (""--lock-file takes an argument""); + + (void) lock_file_new (argv[1]); + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--sync-fd"") == 0) + { + int the_fd; + char *endptr; + + if (argc < 2) + die (""--sync-fd takes an argument""); + + the_fd = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) + die (""Invalid fd: %s"", argv[1]); + + opt_sync_fd = the_fd; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--block-fd"") == 0) + { + int the_fd; + char *endptr; + + if (argc < 2) + die (""--block-fd takes an argument""); + + the_fd = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) + die (""Invalid fd: %s"", argv[1]); + + opt_block_fd = the_fd; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--userns-block-fd"") == 0) + { + int the_fd; + char *endptr; + + if (argc < 2) + die (""--userns-block-fd takes an argument""); + + the_fd = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) + die (""Invalid fd: %s"", argv[1]); + + opt_userns_block_fd = the_fd; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--info-fd"") == 0) + { + int the_fd; + char *endptr; + + if (argc < 2) + die (""--info-fd takes an argument""); + + the_fd = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) + die (""Invalid fd: %s"", argv[1]); + + opt_info_fd = the_fd; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--json-status-fd"") == 0) + { + int the_fd; + char *endptr; + + if (argc < 2) + die (""--json-status-fd takes an argument""); + + the_fd = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) + die (""Invalid fd: %s"", argv[1]); + + opt_json_status_fd = the_fd; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--seccomp"") == 0) + { + int the_fd; + char *endptr; + + if (argc < 2) + die (""--seccomp takes an argument""); + + the_fd = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) + die (""Invalid fd: %s"", argv[1]); + + opt_seccomp_fd = the_fd; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--setenv"") == 0) + { + if (argc < 3) + die (""--setenv takes two arguments""); + + xsetenv (argv[1], argv[2], 1); + + argv += 2; + argc -= 2; + } + else if (strcmp (arg, ""--unsetenv"") == 0) + { + if (argc < 2) + die (""--unsetenv takes an argument""); + + xunsetenv (argv[1]); + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--uid"") == 0) + { + int the_uid; + char *endptr; + + if (argc < 2) + die (""--uid takes an argument""); + + the_uid = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || the_uid < 0) + die (""Invalid uid: %s"", argv[1]); + + opt_sandbox_uid = the_uid; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--gid"") == 0) + { + int the_gid; + char *endptr; + + if (argc < 2) + die (""--gid takes an argument""); + + the_gid = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || the_gid < 0) + die (""Invalid gid: %s"", argv[1]); + + opt_sandbox_gid = the_gid; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--hostname"") == 0) + { + if (argc < 2) + die (""--hostname takes an argument""); + + op = setup_op_new (SETUP_SET_HOSTNAME); + op->dest = argv[1]; + op->flags = NO_CREATE_DEST; + + opt_sandbox_hostname = argv[1]; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--new-session"") == 0) + { + opt_new_session = TRUE; + } + else if (strcmp (arg, ""--die-with-parent"") == 0) + { + opt_die_with_parent = TRUE; + } + else if (strcmp (arg, ""--as-pid-1"") == 0) + { + opt_as_pid_1 = TRUE; + } + else if (strcmp (arg, ""--cap-add"") == 0) + { + cap_value_t cap; + if (argc < 2) + die (""--cap-add takes an argument""); + + opt_cap_add_or_drop_used = TRUE; + + if (strcasecmp (argv[1], ""ALL"") == 0) + { + requested_caps[0] = requested_caps[1] = 0xFFFFFFFF; + } + else + { + if (cap_from_name (argv[1], &cap) < 0) + die (""unknown cap: %s"", argv[1]); + + if (cap < 32) + requested_caps[0] |= CAP_TO_MASK_0 (cap); + else + requested_caps[1] |= CAP_TO_MASK_1 (cap - 32); + } + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--cap-drop"") == 0) + { + cap_value_t cap; + if (argc < 2) + die (""--cap-drop takes an argument""); + + opt_cap_add_or_drop_used = TRUE; + + if (strcasecmp (argv[1], ""ALL"") == 0) + { + requested_caps[0] = requested_caps[1] = 0; + } + else + { + if (cap_from_name (argv[1], &cap) < 0) + die (""unknown cap: %s"", argv[1]); + + if (cap < 32) + requested_caps[0] &= ~CAP_TO_MASK_0 (cap); + else + requested_caps[1] &= ~CAP_TO_MASK_1 (cap - 32); + } + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--"") == 0) + { + argv += 1; + argc -= 1; + break; + } + else if (*arg == '-') + { + die (""Unknown option %s"", arg); + } + else + { + break; + } + + argv++; + argc--; + } + + *argcp = argc; + *argvp = argv; +} +",0,"parse_args_recurse (int *argcp, + const char ***argvp, + bool in_file, + int *total_parsed_argc_p) +{ + SetupOp *op; + int argc = *argcp; + const char **argv = *argvp; + /* I can't imagine a case where someone wants more than this. + * If you do...you should be able to pass multiple files + * via a single tmpfs and linking them there, etc. + * + * We're adding this hardening due to precedent from + * http://googleprojectzero.blogspot.com/2014/08/the-poisoned-nul-byte-2014-edition.html + * + * I picked 9000 because the Internet told me to and it was hard to + * resist. + */ + static const uint32_t MAX_ARGS = 9000; + + if (*total_parsed_argc_p > MAX_ARGS) + die (""Exceeded maximum number of arguments %u"", MAX_ARGS); + + while (argc > 0) + { + const char *arg = argv[0]; + + if (strcmp (arg, ""--help"") == 0) + { + usage (EXIT_SUCCESS, stdout); + } + else if (strcmp (arg, ""--version"") == 0) + { + print_version_and_exit (); + } + else if (strcmp (arg, ""--args"") == 0) + { + int the_fd; + char *endptr; + const char *p, *data_end; + size_t data_len; + cleanup_free const char **data_argv = NULL; + const char **data_argv_copy; + int data_argc; + int i; + + if (in_file) + die (""--args not supported in arguments file""); + + if (argc < 2) + die (""--args takes an argument""); + + the_fd = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) + die (""Invalid fd: %s"", argv[1]); + + /* opt_args_data is essentially a recursive argv array, which we must + * keep allocated until exit time, since its argv entries get used + * by the other cases in parse_args_recurse() when we recurse. */ + opt_args_data = load_file_data (the_fd, &data_len); + if (opt_args_data == NULL) + die_with_error (""Can't read --args data""); + (void) close (the_fd); + + data_end = opt_args_data + data_len; + data_argc = 0; + + p = opt_args_data; + while (p != NULL && p < data_end) + { + data_argc++; + (*total_parsed_argc_p)++; + if (*total_parsed_argc_p > MAX_ARGS) + die (""Exceeded maximum number of arguments %u"", MAX_ARGS); + p = memchr (p, 0, data_end - p); + if (p != NULL) + p++; + } + + data_argv = xcalloc (sizeof (char *) * (data_argc + 1)); + + i = 0; + p = opt_args_data; + while (p != NULL && p < data_end) + { + /* Note: load_file_data always adds a nul terminator, so this is safe + * even for the last string. */ + data_argv[i++] = p; + p = memchr (p, 0, data_end - p); + if (p != NULL) + p++; + } + + data_argv_copy = data_argv; /* Don't change data_argv, we need to free it */ + parse_args_recurse (&data_argc, &data_argv_copy, TRUE, total_parsed_argc_p); + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--unshare-all"") == 0) + { + /* Keep this in order with the older (legacy) --unshare arguments, + * we use the --try variants of user and cgroup, since we want + * to support systems/kernels without support for those. + */ + opt_unshare_user_try = opt_unshare_ipc = opt_unshare_pid = + opt_unshare_uts = opt_unshare_cgroup_try = + opt_unshare_net = TRUE; + } + /* Begin here the older individual --unshare variants */ + else if (strcmp (arg, ""--unshare-user"") == 0) + { + opt_unshare_user = TRUE; + } + else if (strcmp (arg, ""--unshare-user-try"") == 0) + { + opt_unshare_user_try = TRUE; + } + else if (strcmp (arg, ""--unshare-ipc"") == 0) + { + opt_unshare_ipc = TRUE; + } + else if (strcmp (arg, ""--unshare-pid"") == 0) + { + opt_unshare_pid = TRUE; + } + else if (strcmp (arg, ""--unshare-net"") == 0) + { + opt_unshare_net = TRUE; + } + else if (strcmp (arg, ""--unshare-uts"") == 0) + { + opt_unshare_uts = TRUE; + } + else if (strcmp (arg, ""--unshare-cgroup"") == 0) + { + opt_unshare_cgroup = TRUE; + } + else if (strcmp (arg, ""--unshare-cgroup-try"") == 0) + { + opt_unshare_cgroup_try = TRUE; + } + /* Begin here the newer --share variants */ + else if (strcmp (arg, ""--share-net"") == 0) + { + opt_unshare_net = FALSE; + } + /* End --share variants, other arguments begin */ + else if (strcmp (arg, ""--chdir"") == 0) + { + if (argc < 2) + die (""--chdir takes one argument""); + + opt_chdir_path = argv[1]; + argv++; + argc--; + } + else if (strcmp (arg, ""--remount-ro"") == 0) + { + if (argc < 2) + die (""--remount-ro takes one argument""); + + SetupOp *op = setup_op_new (SETUP_REMOUNT_RO_NO_RECURSIVE); + op->dest = argv[1]; + + argv++; + argc--; + } + else if (strcmp(arg, ""--bind"") == 0 || + strcmp(arg, ""--bind-try"") == 0) + { + if (argc < 3) + die (""%s takes two arguments"", arg); + + op = setup_op_new (SETUP_BIND_MOUNT); + op->source = argv[1]; + op->dest = argv[2]; + if (strcmp(arg, ""--bind-try"") == 0) + op->flags = ALLOW_NOTEXIST; + + argv += 2; + argc -= 2; + } + else if (strcmp(arg, ""--ro-bind"") == 0 || + strcmp(arg, ""--ro-bind-try"") == 0) + { + if (argc < 3) + die (""%s takes two arguments"", arg); + + op = setup_op_new (SETUP_RO_BIND_MOUNT); + op->source = argv[1]; + op->dest = argv[2]; + if (strcmp(arg, ""--ro-bind-try"") == 0) + op->flags = ALLOW_NOTEXIST; + + argv += 2; + argc -= 2; + } + else if (strcmp (arg, ""--dev-bind"") == 0 || + strcmp (arg, ""--dev-bind-try"") == 0) + { + if (argc < 3) + die (""%s takes two arguments"", arg); + + op = setup_op_new (SETUP_DEV_BIND_MOUNT); + op->source = argv[1]; + op->dest = argv[2]; + if (strcmp(arg, ""--dev-bind-try"") == 0) + op->flags = ALLOW_NOTEXIST; + + argv += 2; + argc -= 2; + } + else if (strcmp (arg, ""--proc"") == 0) + { + if (argc < 2) + die (""--proc takes an argument""); + + op = setup_op_new (SETUP_MOUNT_PROC); + op->dest = argv[1]; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--exec-label"") == 0) + { + if (argc < 2) + die (""--exec-label takes an argument""); + opt_exec_label = argv[1]; + die_unless_label_valid (opt_exec_label); + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--file-label"") == 0) + { + if (argc < 2) + die (""--file-label takes an argument""); + opt_file_label = argv[1]; + die_unless_label_valid (opt_file_label); + if (label_create_file (opt_file_label)) + die_with_error (""--file-label setup failed""); + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--dev"") == 0) + { + if (argc < 2) + die (""--dev takes an argument""); + + op = setup_op_new (SETUP_MOUNT_DEV); + op->dest = argv[1]; + opt_needs_devpts = TRUE; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--tmpfs"") == 0) + { + if (argc < 2) + die (""--tmpfs takes an argument""); + + op = setup_op_new (SETUP_MOUNT_TMPFS); + op->dest = argv[1]; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--mqueue"") == 0) + { + if (argc < 2) + die (""--mqueue takes an argument""); + + op = setup_op_new (SETUP_MOUNT_MQUEUE); + op->dest = argv[1]; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--dir"") == 0) + { + if (argc < 2) + die (""--dir takes an argument""); + + op = setup_op_new (SETUP_MAKE_DIR); + op->dest = argv[1]; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--file"") == 0) + { + int file_fd; + char *endptr; + + if (argc < 3) + die (""--file takes two arguments""); + + file_fd = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0) + die (""Invalid fd: %s"", argv[1]); + + op = setup_op_new (SETUP_MAKE_FILE); + op->fd = file_fd; + op->dest = argv[2]; + + argv += 2; + argc -= 2; + } + else if (strcmp (arg, ""--bind-data"") == 0) + { + int file_fd; + char *endptr; + + if (argc < 3) + die (""--bind-data takes two arguments""); + + file_fd = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0) + die (""Invalid fd: %s"", argv[1]); + + op = setup_op_new (SETUP_MAKE_BIND_FILE); + op->fd = file_fd; + op->dest = argv[2]; + + argv += 2; + argc -= 2; + } + else if (strcmp (arg, ""--ro-bind-data"") == 0) + { + int file_fd; + char *endptr; + + if (argc < 3) + die (""--ro-bind-data takes two arguments""); + + file_fd = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || file_fd < 0) + die (""Invalid fd: %s"", argv[1]); + + op = setup_op_new (SETUP_MAKE_RO_BIND_FILE); + op->fd = file_fd; + op->dest = argv[2]; + + argv += 2; + argc -= 2; + } + else if (strcmp (arg, ""--symlink"") == 0) + { + if (argc < 3) + die (""--symlink takes two arguments""); + + op = setup_op_new (SETUP_MAKE_SYMLINK); + op->source = argv[1]; + op->dest = argv[2]; + + argv += 2; + argc -= 2; + } + else if (strcmp (arg, ""--lock-file"") == 0) + { + if (argc < 2) + die (""--lock-file takes an argument""); + + (void) lock_file_new (argv[1]); + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--sync-fd"") == 0) + { + int the_fd; + char *endptr; + + if (argc < 2) + die (""--sync-fd takes an argument""); + + the_fd = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) + die (""Invalid fd: %s"", argv[1]); + + opt_sync_fd = the_fd; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--block-fd"") == 0) + { + int the_fd; + char *endptr; + + if (argc < 2) + die (""--block-fd takes an argument""); + + the_fd = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) + die (""Invalid fd: %s"", argv[1]); + + opt_block_fd = the_fd; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--userns-block-fd"") == 0) + { + int the_fd; + char *endptr; + + if (argc < 2) + die (""--userns-block-fd takes an argument""); + + the_fd = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) + die (""Invalid fd: %s"", argv[1]); + + opt_userns_block_fd = the_fd; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--info-fd"") == 0) + { + int the_fd; + char *endptr; + + if (argc < 2) + die (""--info-fd takes an argument""); + + the_fd = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) + die (""Invalid fd: %s"", argv[1]); + + opt_info_fd = the_fd; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--json-status-fd"") == 0) + { + int the_fd; + char *endptr; + + if (argc < 2) + die (""--json-status-fd takes an argument""); + + the_fd = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) + die (""Invalid fd: %s"", argv[1]); + + opt_json_status_fd = the_fd; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--seccomp"") == 0) + { + int the_fd; + char *endptr; + + if (argc < 2) + die (""--seccomp takes an argument""); + + the_fd = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || the_fd < 0) + die (""Invalid fd: %s"", argv[1]); + + opt_seccomp_fd = the_fd; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--setenv"") == 0) + { + if (argc < 3) + die (""--setenv takes two arguments""); + + xsetenv (argv[1], argv[2], 1); + + argv += 2; + argc -= 2; + } + else if (strcmp (arg, ""--unsetenv"") == 0) + { + if (argc < 2) + die (""--unsetenv takes an argument""); + + xunsetenv (argv[1]); + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--uid"") == 0) + { + int the_uid; + char *endptr; + + if (argc < 2) + die (""--uid takes an argument""); + + the_uid = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || the_uid < 0) + die (""Invalid uid: %s"", argv[1]); + + opt_sandbox_uid = the_uid; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--gid"") == 0) + { + int the_gid; + char *endptr; + + if (argc < 2) + die (""--gid takes an argument""); + + the_gid = strtol (argv[1], &endptr, 10); + if (argv[1][0] == 0 || endptr[0] != 0 || the_gid < 0) + die (""Invalid gid: %s"", argv[1]); + + opt_sandbox_gid = the_gid; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--hostname"") == 0) + { + if (argc < 2) + die (""--hostname takes an argument""); + + op = setup_op_new (SETUP_SET_HOSTNAME); + op->dest = argv[1]; + op->flags = NO_CREATE_DEST; + + opt_sandbox_hostname = argv[1]; + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--new-session"") == 0) + { + opt_new_session = TRUE; + } + else if (strcmp (arg, ""--die-with-parent"") == 0) + { + opt_die_with_parent = TRUE; + } + else if (strcmp (arg, ""--as-pid-1"") == 0) + { + opt_as_pid_1 = TRUE; + } + else if (strcmp (arg, ""--cap-add"") == 0) + { + cap_value_t cap; + if (argc < 2) + die (""--cap-add takes an argument""); + + opt_cap_add_or_drop_used = TRUE; + + if (strcasecmp (argv[1], ""ALL"") == 0) + { + requested_caps[0] = requested_caps[1] = 0xFFFFFFFF; + } + else + { + if (cap_from_name (argv[1], &cap) < 0) + die (""unknown cap: %s"", argv[1]); + + if (cap < 32) + requested_caps[0] |= CAP_TO_MASK_0 (cap); + else + requested_caps[1] |= CAP_TO_MASK_1 (cap - 32); + } + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--cap-drop"") == 0) + { + cap_value_t cap; + if (argc < 2) + die (""--cap-drop takes an argument""); + + opt_cap_add_or_drop_used = TRUE; + + if (strcasecmp (argv[1], ""ALL"") == 0) + { + requested_caps[0] = requested_caps[1] = 0; + } + else + { + if (cap_from_name (argv[1], &cap) < 0) + die (""unknown cap: %s"", argv[1]); + + if (cap < 32) + requested_caps[0] &= ~CAP_TO_MASK_0 (cap); + else + requested_caps[1] &= ~CAP_TO_MASK_1 (cap - 32); + } + + argv += 1; + argc -= 1; + } + else if (strcmp (arg, ""--"") == 0) + { + argv += 1; + argc -= 1; + break; + } + else if (*arg == '-') + { + die (""Unknown option %s"", arg); + } + else + { + break; + } + + argv++; + argc--; + } + + *argcp = argc; + *argvp = argv; +} +","@@ -2046,7 +2046,7 @@ main (int argc, + char **argv) + { + mode_t old_umask; +- cleanup_free char *base_path = NULL; ++ const char *base_path = NULL; + int clone_flags; + char *old_cwd = NULL; + pid_t pid; +@@ -2187,15 +2187,12 @@ main (int argc, + die_with_error (""Can't open /proc""); + + /* We need *some* mountpoint where we can mount the root tmpfs. +- We first try in /run, and if that fails, try in /tmp. */ +- base_path = xasprintf (""/run/user/%d/.bubblewrap"", real_uid); +- if (ensure_dir (base_path, 0755)) +- { +- free (base_path); +- base_path = xasprintf (""/tmp/.bubblewrap-%d"", real_uid); +- if (ensure_dir (base_path, 0755)) +- die_with_error (""Creating root mountpoint failed""); +- } ++ * Because we use pivot_root, it won't appear to be mounted from ++ * the perspective of the sandboxed process, so we can use anywhere ++ * that is sure to exist, that is sure to not be a symlink controlled ++ * by someone malicious, and that we won't immediately need to ++ * access ourselves. */ ++ base_path = ""/tmp""; + + __debug__ ((""creating new namespace\n"")); + +@@ -2400,7 +2397,8 @@ main (int argc, + /* We create a subdir ""$base_path/newroot"" for the new root, that + * way we can pivot_root to base_path, and put the old root at + * ""$base_path/oldroot"". This avoids problems accessing the oldroot +- * dir if the user requested to bind mount something over / */ ++ * dir if the user requested to bind mount something over / (or ++ * over /tmp, now that we use that for base_path). */ + + if (mkdir (""newroot"", 0755)) + die_with_error (""Creating newroot failed"");",4662,4993,6144 +9458,"int ssl3_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_read_buffer(s)) + return(-1); + + if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE)) || + (peek && (type != SSL3_RT_APPLICATION_DATA))) + { + SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR); + return -1; + } + + if ((type == SSL3_RT_HANDSHAKE) && (s->s3->handshake_fragment_len > 0)) + /* (partially) satisfy request from storage */ + { + unsigned char *src = s->s3->handshake_fragment; + unsigned char *dst = buf; + unsigned int k; + + /* peek == 0 */ + n = 0; + while ((len > 0) && (s->s3->handshake_fragment_len > 0)) + { + *dst++ = *src++; + len--; s->s3->handshake_fragment_len--; + n++; + } + /* move any remaining fragment bytes: */ + for (k = 0; k < s->s3->handshake_fragment_len; k++) + s->s3->handshake_fragment[k] = *src++; + return n; + } + + /* Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */ + + if (!s->in_handshake && SSL_in_init(s)) + { + /* type == SSL3_RT_APPLICATION_DATA */ + i=s->handshake_func(s); + if (i < 0) return(i); + if (i == 0) + { + SSLerr(SSL_F_SSL3_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); + + /* get new packet if necessary */ + if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY)) + { + ret=ssl3_get_record(s); + if (ret <= 0) return(ret); + } + + /* 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)) + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_DATA_BETWEEN_CCS_AND_FINISHED); + goto f_err; + } + + /* 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_SSL3_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; + if (s->mode & SSL_MODE_RELEASE_BUFFERS && s->s3->rbuf.left == 0) + ssl3_release_read_buffer(s); + } + } + 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 dest_maxlen = 0; + unsigned char *dest = NULL; + unsigned int *dest_len = NULL; + + if (rr->type == SSL3_RT_HANDSHAKE) + { + dest_maxlen = sizeof s->s3->handshake_fragment; + dest = s->s3->handshake_fragment; + dest_len = &s->s3->handshake_fragment_len; + } + else if (rr->type == SSL3_RT_ALERT) + { + dest_maxlen = sizeof s->s3->alert_fragment; + dest = s->s3->alert_fragment; + dest_len = &s->s3->alert_fragment_len; + } +#ifndef OPENSSL_NO_HEARTBEATS + else if (rr->type == TLS1_RT_HEARTBEAT) + { + tls1_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 + + if (dest_maxlen > 0) + { + n = dest_maxlen - *dest_len; /* available space in 'dest' */ + if (rr->length < n) + n = rr->length; /* available bytes */ + + /* now move 'n' bytes: */ + while (n-- > 0) + { + dest[(*dest_len)++] = rr->data[rr->off++]; + rr->length--; + } + + if (*dest_len < dest_maxlen) + goto start; /* fragment was too small */ + } + } + + /*- + * s->s3->handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE; + * s->s3->alert_fragment_len == 2 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->s3->handshake_fragment_len >= 4) && + (s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) && + (s->session != NULL) && (s->session->cipher != NULL)) + { + s->s3->handshake_fragment_len = 0; + + if ((s->s3->handshake_fragment[1] != 0) || + (s->s3->handshake_fragment[2] != 0) || + (s->s3->handshake_fragment[3] != 0)) + { + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_BAD_HELLO_REQUEST); + goto f_err; + } + + if (s->msg_callback) + s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->s3->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) + { + ssl3_renegotiate(s); + if (ssl3_renegotiate_check(s)) + { + i=s->handshake_func(s); + if (i < 0) return(i); + if (i == 0) + { + SSLerr(SSL_F_SSL3_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 we are a server and get a client hello when renegotiation isn't + * allowed send back a no renegotiation alert and carry on. + * WARNING: experimental code, needs reviewing (steve) + */ + if (s->server && + SSL_is_init_finished(s) && + !s->s3->send_connection_binding && + (s->version > SSL3_VERSION) && + (s->s3->handshake_fragment_len >= 4) && + (s->s3->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) && + (s->session != NULL) && (s->session->cipher != NULL) && + !(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) + + { + /*s->s3->handshake_fragment_len = 0;*/ + rr->length = 0; + ssl3_send_alert(s,SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION); + goto start; + } + if (s->s3->alert_fragment_len >= 2) + { + int alert_level = s->s3->alert_fragment[0]; + int alert_descr = s->s3->alert_fragment[1]; + + s->s3->alert_fragment_len = 0; + + if (s->msg_callback) + s->msg_callback(0, s->version, SSL3_RT_ALERT, s->s3->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) + { + s->shutdown |= SSL_RECEIVED_SHUTDOWN; + return(0); + } + /* This is a warning but we receive it if we requested + * renegotiation and the peer denied it. Terminate with + * a fatal alert because if application tried to + * renegotiatie it presumably had a good reason and + * expects it to succeed. + * + * In future we might have a renegotiation where we + * don't care if the peer refused it where we carry on. + */ + else if (alert_descr == SSL_AD_NO_RENEGOTIATION) + { + al = SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_NO_RENEGOTIATION); + goto f_err; + } +#ifdef SSL_AD_MISSING_SRP_USERNAME + else if (alert_descr == SSL_AD_MISSING_SRP_USERNAME) + return(0); +#endif + } + else if (alert_level == 2) /* fatal */ + { + char tmp[16]; + + s->rwstate=SSL_NOTHING; + s->s3->fatal_alert = alert_descr; + SSLerr(SSL_F_SSL3_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_SSL3_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) + { + /* 'Change Cipher Spec' is just a single byte, so we know + * exactly what the record payload has to look like */ + if ( (rr->length != 1) || (rr->off != 0) || + (rr->data[0] != SSL3_MT_CCS)) + { + al=SSL_AD_ILLEGAL_PARAMETER; + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_BAD_CHANGE_CIPHER_SPEC); + goto f_err; + } + + /* Check we have a cipher to change to */ + if (s->s3->tmp.new_cipher == NULL) + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_CCS_RECEIVED_EARLY); + goto f_err; + } + + if (!(s->s3->flags & SSL3_FLAGS_CCS_OK)) + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_CCS_RECEIVED_EARLY); + goto f_err; + } + + s->s3->flags &= ~SSL3_FLAGS_CCS_OK; + + 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); + + s->s3->change_cipher_spec=1; + if (!ssl3_do_change_cipher_spec(s)) + goto err; + else + goto start; + } + + /* Unexpected handshake message (Client Hello, or protocol violation) */ + if ((s->s3->handshake_fragment_len >= 4) && !s->in_handshake) + { + 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_SSL3_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 up to v1.1 just ignores unknown message types: + * TLS v1.2 give an unexpected message alert. + */ + if (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION) + { + rr->length = 0; + goto start; + } +#endif + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_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_SSL3_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_SSL3_READ_BYTES,SSL_R_UNEXPECTED_RECORD); + goto f_err; + } + } + /* not reached */ + +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,al); +err: + return(-1); + } +",0,"int ssl3_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_read_buffer(s)) + return(-1); + + if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE)) || + (peek && (type != SSL3_RT_APPLICATION_DATA))) + { + SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR); + return -1; + } + + if ((type == SSL3_RT_HANDSHAKE) && (s->s3->handshake_fragment_len > 0)) + /* (partially) satisfy request from storage */ + { + unsigned char *src = s->s3->handshake_fragment; + unsigned char *dst = buf; + unsigned int k; + + /* peek == 0 */ + n = 0; + while ((len > 0) && (s->s3->handshake_fragment_len > 0)) + { + *dst++ = *src++; + len--; s->s3->handshake_fragment_len--; + n++; + } + /* move any remaining fragment bytes: */ + for (k = 0; k < s->s3->handshake_fragment_len; k++) + s->s3->handshake_fragment[k] = *src++; + return n; + } + + /* Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */ + + if (!s->in_handshake && SSL_in_init(s)) + { + /* type == SSL3_RT_APPLICATION_DATA */ + i=s->handshake_func(s); + if (i < 0) return(i); + if (i == 0) + { + SSLerr(SSL_F_SSL3_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); + + /* get new packet if necessary */ + if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY)) + { + ret=ssl3_get_record(s); + if (ret <= 0) return(ret); + } + + /* 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)) + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_DATA_BETWEEN_CCS_AND_FINISHED); + goto f_err; + } + + /* 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_SSL3_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; + if (s->mode & SSL_MODE_RELEASE_BUFFERS && s->s3->rbuf.left == 0) + ssl3_release_read_buffer(s); + } + } + 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 dest_maxlen = 0; + unsigned char *dest = NULL; + unsigned int *dest_len = NULL; + + if (rr->type == SSL3_RT_HANDSHAKE) + { + dest_maxlen = sizeof s->s3->handshake_fragment; + dest = s->s3->handshake_fragment; + dest_len = &s->s3->handshake_fragment_len; + } + else if (rr->type == SSL3_RT_ALERT) + { + dest_maxlen = sizeof s->s3->alert_fragment; + dest = s->s3->alert_fragment; + dest_len = &s->s3->alert_fragment_len; + } +#ifndef OPENSSL_NO_HEARTBEATS + else if (rr->type == TLS1_RT_HEARTBEAT) + { + tls1_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 + + if (dest_maxlen > 0) + { + n = dest_maxlen - *dest_len; /* available space in 'dest' */ + if (rr->length < n) + n = rr->length; /* available bytes */ + + /* now move 'n' bytes: */ + while (n-- > 0) + { + dest[(*dest_len)++] = rr->data[rr->off++]; + rr->length--; + } + + if (*dest_len < dest_maxlen) + goto start; /* fragment was too small */ + } + } + + /*- + * s->s3->handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE; + * s->s3->alert_fragment_len == 2 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->s3->handshake_fragment_len >= 4) && + (s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) && + (s->session != NULL) && (s->session->cipher != NULL)) + { + s->s3->handshake_fragment_len = 0; + + if ((s->s3->handshake_fragment[1] != 0) || + (s->s3->handshake_fragment[2] != 0) || + (s->s3->handshake_fragment[3] != 0)) + { + al=SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_BAD_HELLO_REQUEST); + goto f_err; + } + + if (s->msg_callback) + s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->s3->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) + { + ssl3_renegotiate(s); + if (ssl3_renegotiate_check(s)) + { + i=s->handshake_func(s); + if (i < 0) return(i); + if (i == 0) + { + SSLerr(SSL_F_SSL3_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 we are a server and get a client hello when renegotiation isn't + * allowed send back a no renegotiation alert and carry on. + * WARNING: experimental code, needs reviewing (steve) + */ + if (s->server && + SSL_is_init_finished(s) && + !s->s3->send_connection_binding && + (s->version > SSL3_VERSION) && + (s->s3->handshake_fragment_len >= 4) && + (s->s3->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) && + (s->session != NULL) && (s->session->cipher != NULL) && + !(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) + + { + /*s->s3->handshake_fragment_len = 0;*/ + rr->length = 0; + ssl3_send_alert(s,SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION); + goto start; + } + if (s->s3->alert_fragment_len >= 2) + { + int alert_level = s->s3->alert_fragment[0]; + int alert_descr = s->s3->alert_fragment[1]; + + s->s3->alert_fragment_len = 0; + + if (s->msg_callback) + s->msg_callback(0, s->version, SSL3_RT_ALERT, s->s3->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) + { + s->shutdown |= SSL_RECEIVED_SHUTDOWN; + return(0); + } + /* This is a warning but we receive it if we requested + * renegotiation and the peer denied it. Terminate with + * a fatal alert because if application tried to + * renegotiatie it presumably had a good reason and + * expects it to succeed. + * + * In future we might have a renegotiation where we + * don't care if the peer refused it where we carry on. + */ + else if (alert_descr == SSL_AD_NO_RENEGOTIATION) + { + al = SSL_AD_HANDSHAKE_FAILURE; + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_NO_RENEGOTIATION); + goto f_err; + } +#ifdef SSL_AD_MISSING_SRP_USERNAME + else if (alert_descr == SSL_AD_MISSING_SRP_USERNAME) + return(0); +#endif + } + else if (alert_level == 2) /* fatal */ + { + char tmp[16]; + + s->rwstate=SSL_NOTHING; + s->s3->fatal_alert = alert_descr; + SSLerr(SSL_F_SSL3_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_SSL3_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) + { + /* 'Change Cipher Spec' is just a single byte, so we know + * exactly what the record payload has to look like */ + if ( (rr->length != 1) || (rr->off != 0) || + (rr->data[0] != SSL3_MT_CCS)) + { + al=SSL_AD_ILLEGAL_PARAMETER; + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_BAD_CHANGE_CIPHER_SPEC); + goto f_err; + } + + /* Check we have a cipher to change to */ + if (s->s3->tmp.new_cipher == NULL) + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_CCS_RECEIVED_EARLY); + goto f_err; + } + + if (!(s->s3->flags & SSL3_FLAGS_CCS_OK)) + { + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_CCS_RECEIVED_EARLY); + goto f_err; + } + + s->s3->flags &= ~SSL3_FLAGS_CCS_OK; + + 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); + + s->s3->change_cipher_spec=1; + if (!ssl3_do_change_cipher_spec(s)) + goto err; + else + goto start; + } + + /* Unexpected handshake message (Client Hello, or protocol violation) */ + if ((s->s3->handshake_fragment_len >= 4) && !s->in_handshake) + { + 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_SSL3_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 up to v1.1 just ignores unknown message types: + * TLS v1.2 give an unexpected message alert. + */ + if (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION) + { + rr->length = 0; + goto start; + } +#endif + al=SSL_AD_UNEXPECTED_MESSAGE; + SSLerr(SSL_F_SSL3_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_SSL3_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_SSL3_READ_BYTES,SSL_R_UNEXPECTED_RECORD); + goto f_err; + } + } + /* not reached */ + +f_err: + ssl3_send_alert(s,SSL3_AL_FATAL,al); +err: + return(-1); + } +","@@ -197,6 +197,8 @@ int ssl3_read_n(SSL *s, int n, int max, int extend) + * at once (as long as it fits into the buffer). */ + if (SSL_IS_DTLS(s)) + { ++ if (left == 0 && extend) ++ return 0; + if (left > 0 && n > left) + n = left; + }",4316,4647,6144 +1314,"int ssl3_accept(SSL *s) +{ + BUF_MEM *buf; + unsigned long alg_k, Time = (unsigned long)time(NULL); + void (*cb) (const SSL *ssl, int type, int val) = NULL; + int ret = -1; + int new_state, state, skip = 0; + + RAND_add(&Time, sizeof(Time), 0); + ERR_clear_error(); + clear_sys_error(); + + if (s->info_callback != NULL) + cb = s->info_callback; + else if (s->ctx->info_callback != NULL) + cb = s->ctx->info_callback; + + /* init things to blank */ + s->in_handshake++; + if (!SSL_in_init(s) || SSL_in_before(s)) + SSL_clear(s); + + if (s->cert == NULL) { + SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_NO_CERTIFICATE_SET); + return (-1); + } +#ifndef OPENSSL_NO_HEARTBEATS + /* + * If we're awaiting a HeartbeatResponse, pretend we already got and + * don't await it anymore, because Heartbeats don't make sense during + * handshakes anyway. + */ + if (s->tlsext_hb_pending) { + s->tlsext_hb_pending = 0; + s->tlsext_hb_seq++; + } +#endif + + for (;;) { + state = s->state; + + switch (s->state) { + case SSL_ST_RENEGOTIATE: + s->renegotiate = 1; + /* s->state=SSL_ST_ACCEPT; */ + + case SSL_ST_BEFORE: + case SSL_ST_ACCEPT: + case SSL_ST_BEFORE | SSL_ST_ACCEPT: + case SSL_ST_OK | SSL_ST_ACCEPT: + + s->server = 1; + if (cb != NULL) + cb(s, SSL_CB_HANDSHAKE_START, 1); + + if ((s->version >> 8) != 3) { + SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR); + s->state = SSL_ST_ERR; + return -1; + } + s->type = SSL_ST_ACCEPT; + + if (s->init_buf == NULL) { + if ((buf = BUF_MEM_new()) == NULL) { + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) { + BUF_MEM_free(buf); + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + s->init_buf = buf; + } + + if (!ssl3_setup_buffers(s)) { + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + + s->init_num = 0; + s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY; + s->s3->flags &= ~SSL3_FLAGS_CCS_OK; + /* + * Should have been reset by ssl3_get_finished, too. + */ + s->s3->change_cipher_spec = 0; + + if (s->state != SSL_ST_RENEGOTIATE) { + /* + * Ok, we now need to push on a buffering BIO so that the + * output is sent in a way that TCP likes :-) + */ + if (!ssl_init_wbio_buffer(s, 1)) { + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + + ssl3_init_finished_mac(s); + s->state = SSL3_ST_SR_CLNT_HELLO_A; + s->ctx->stats.sess_accept++; + } else if (!s->s3->send_connection_binding && + !(s->options & + SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { + /* + * Server attempting to renegotiate with client that doesn't + * support secure renegotiation. + */ + SSLerr(SSL_F_SSL3_ACCEPT, + SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); + ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } else { + /* + * s->state == SSL_ST_RENEGOTIATE, we will just send a + * HelloRequest + */ + s->ctx->stats.sess_accept_renegotiate++; + s->state = SSL3_ST_SW_HELLO_REQ_A; + } + break; + + case SSL3_ST_SW_HELLO_REQ_A: + case SSL3_ST_SW_HELLO_REQ_B: + + s->shutdown = 0; + ret = ssl3_send_hello_request(s); + if (ret <= 0) + goto end; + s->s3->tmp.next_state = SSL3_ST_SW_HELLO_REQ_C; + s->state = SSL3_ST_SW_FLUSH; + s->init_num = 0; + + ssl3_init_finished_mac(s); + break; + + case SSL3_ST_SW_HELLO_REQ_C: + s->state = SSL_ST_OK; + break; + + case SSL3_ST_SR_CLNT_HELLO_A: + case SSL3_ST_SR_CLNT_HELLO_B: + case SSL3_ST_SR_CLNT_HELLO_C: + + s->shutdown = 0; + ret = ssl3_get_client_hello(s); + if (ret <= 0) + goto end; +#ifndef OPENSSL_NO_SRP + s->state = SSL3_ST_SR_CLNT_HELLO_D; + case SSL3_ST_SR_CLNT_HELLO_D: + { + int al; + if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) { + /* + * callback indicates firther work to be done + */ + s->rwstate = SSL_X509_LOOKUP; + goto end; + } + if (ret != SSL_ERROR_NONE) { + ssl3_send_alert(s, SSL3_AL_FATAL, al); + /* + * This is not really an error but the only means to for + * a client to detect whether srp is supported. + */ + if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY) + SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_CLIENTHELLO_TLSEXT); + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + } +#endif + + s->renegotiate = 2; + s->state = SSL3_ST_SW_SRVR_HELLO_A; + s->init_num = 0; + break; + + case SSL3_ST_SW_SRVR_HELLO_A: + case SSL3_ST_SW_SRVR_HELLO_B: + ret = ssl3_send_server_hello(s); + if (ret <= 0) + goto end; +#ifndef OPENSSL_NO_TLSEXT + if (s->hit) { + if (s->tlsext_ticket_expected) + s->state = SSL3_ST_SW_SESSION_TICKET_A; + else + s->state = SSL3_ST_SW_CHANGE_A; + } +#else + if (s->hit) + s->state = SSL3_ST_SW_CHANGE_A; +#endif + else + s->state = SSL3_ST_SW_CERT_A; + s->init_num = 0; + break; + + case SSL3_ST_SW_CERT_A: + case SSL3_ST_SW_CERT_B: + /* Check if it is anon DH or anon ECDH, */ + /* normal PSK or KRB5 or SRP */ + if (! + (s->s3->tmp. + new_cipher->algorithm_auth & (SSL_aNULL | SSL_aKRB5 | + SSL_aSRP)) +&& !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { + ret = ssl3_send_server_certificate(s); + if (ret <= 0) + goto end; +#ifndef OPENSSL_NO_TLSEXT + if (s->tlsext_status_expected) + s->state = SSL3_ST_SW_CERT_STATUS_A; + else + s->state = SSL3_ST_SW_KEY_EXCH_A; + } else { + skip = 1; + s->state = SSL3_ST_SW_KEY_EXCH_A; + } +#else + } else + skip = 1; + + s->state = SSL3_ST_SW_KEY_EXCH_A; +#endif + s->init_num = 0; + break; + + case SSL3_ST_SW_KEY_EXCH_A: + case SSL3_ST_SW_KEY_EXCH_B: + alg_k = s->s3->tmp.new_cipher->algorithm_mkey; + + /* + * clear this, it may get reset by + * send_server_key_exchange + */ + s->s3->tmp.use_rsa_tmp = 0; + + /* + * only send if a DH key exchange, fortezza or RSA but we have a + * sign only certificate PSK: may send PSK identity hints For + * ECC ciphersuites, we send a serverKeyExchange message only if + * the cipher suite is either ECDH-anon or ECDHE. In other cases, + * the server certificate contains the server's public key for + * key exchange. + */ + if (0 + /* + * PSK: send ServerKeyExchange if PSK identity hint if + * provided + */ +#ifndef OPENSSL_NO_PSK + || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint) +#endif +#ifndef OPENSSL_NO_SRP + /* SRP: send ServerKeyExchange */ + || (alg_k & SSL_kSRP) +#endif + || (alg_k & SSL_kEDH) + || (alg_k & SSL_kEECDH) + || ((alg_k & SSL_kRSA) + && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL + || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) + && EVP_PKEY_size(s->cert->pkeys + [SSL_PKEY_RSA_ENC].privatekey) * + 8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher) + ) + ) + ) + ) { + ret = ssl3_send_server_key_exchange(s); + if (ret <= 0) + goto end; + } else + skip = 1; + + s->state = SSL3_ST_SW_CERT_REQ_A; + s->init_num = 0; + break; + + case SSL3_ST_SW_CERT_REQ_A: + case SSL3_ST_SW_CERT_REQ_B: + if ( /* don't request cert unless asked for it: */ + !(s->verify_mode & SSL_VERIFY_PEER) || + /* + * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert + * during re-negotiation: + */ + ((s->session->peer != NULL) && + (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) || + /* + * never request cert in anonymous ciphersuites (see + * section ""Certificate request"" in SSL 3 drafts and in + * RFC 2246): + */ + ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) && + /* + * ... except when the application insists on + * verification (against the specs, but s3_clnt.c accepts + * this for SSL 3) + */ + !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) || + /* + * never request cert in Kerberos ciphersuites + */ + (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) || + /* don't request certificate for SRP auth */ + (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP) + /* + * With normal PSK Certificates and Certificate Requests + * are omitted + */ + || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { + /* no cert request */ + skip = 1; + s->s3->tmp.cert_request = 0; + s->state = SSL3_ST_SW_SRVR_DONE_A; + if (s->s3->handshake_buffer) { + if (!ssl3_digest_cached_records(s)) { + s->state = SSL_ST_ERR; + return -1; + } + } + } else { + s->s3->tmp.cert_request = 1; + ret = ssl3_send_certificate_request(s); + if (ret <= 0) + goto end; +#ifndef NETSCAPE_HANG_BUG + s->state = SSL3_ST_SW_SRVR_DONE_A; +#else + s->state = SSL3_ST_SW_FLUSH; + s->s3->tmp.next_state = SSL3_ST_SR_CERT_A; +#endif + s->init_num = 0; + } + break; + + case SSL3_ST_SW_SRVR_DONE_A: + case SSL3_ST_SW_SRVR_DONE_B: + ret = ssl3_send_server_done(s); + if (ret <= 0) + goto end; + s->s3->tmp.next_state = SSL3_ST_SR_CERT_A; + s->state = SSL3_ST_SW_FLUSH; + s->init_num = 0; + break; + + case SSL3_ST_SW_FLUSH: + + /* + * This code originally checked to see if any data was pending + * using BIO_CTRL_INFO and then flushed. This caused problems as + * documented in PR#1939. The proposed fix doesn't completely + * resolve this issue as buggy implementations of + * BIO_CTRL_PENDING still exist. So instead we just flush + * unconditionally. + */ + + s->rwstate = SSL_WRITING; + if (BIO_flush(s->wbio) <= 0) { + ret = -1; + goto end; + } + s->rwstate = SSL_NOTHING; + + s->state = s->s3->tmp.next_state; + break; + + case SSL3_ST_SR_CERT_A: + case SSL3_ST_SR_CERT_B: + if (s->s3->tmp.cert_request) { + ret = ssl3_get_client_certificate(s); + if (ret <= 0) + goto end; + } + s->init_num = 0; + s->state = SSL3_ST_SR_KEY_EXCH_A; + break; + + case SSL3_ST_SR_KEY_EXCH_A: + case SSL3_ST_SR_KEY_EXCH_B: + ret = ssl3_get_client_key_exchange(s); + if (ret <= 0) + goto end; + if (ret == 2) { + /* + * For the ECDH ciphersuites when the client sends its ECDH + * pub key in a certificate, the CertificateVerify message is + * not sent. Also for GOST ciphersuites when the client uses + * its key from the certificate for key exchange. + */ +#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->state = SSL3_ST_SR_FINISHED_A; +#else + if (s->s3->next_proto_neg_seen) + s->state = SSL3_ST_SR_NEXT_PROTO_A; + else + s->state = SSL3_ST_SR_FINISHED_A; +#endif + s->init_num = 0; + } else if (SSL_USE_SIGALGS(s)) { + s->state = SSL3_ST_SR_CERT_VRFY_A; + s->init_num = 0; + if (!s->session->peer) + break; + /* + * For sigalgs freeze the handshake buffer at this point and + * digest cached records. + */ + if (!s->s3->handshake_buffer) { + SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR); + s->state = SSL_ST_ERR; + return -1; + } + s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE; + if (!ssl3_digest_cached_records(s)) { + s->state = SSL_ST_ERR; + return -1; + } + } else { + int offset = 0; + int dgst_num; + + s->state = SSL3_ST_SR_CERT_VRFY_A; + s->init_num = 0; + + /* + * We need to get hashes here so if there is a client cert, + * it can be verified FIXME - digest processing for + * CertificateVerify should be generalized. But it is next + * step + */ + if (s->s3->handshake_buffer) { + if (!ssl3_digest_cached_records(s)) { + s->state = SSL_ST_ERR; + return -1; + } + } + for (dgst_num = 0; dgst_num < SSL_MAX_DIGEST; dgst_num++) + if (s->s3->handshake_dgst[dgst_num]) { + int dgst_size; + + s->method->ssl3_enc->cert_verify_mac(s, + EVP_MD_CTX_type + (s-> + s3->handshake_dgst + [dgst_num]), + &(s->s3-> + tmp.cert_verify_md + [offset])); + dgst_size = + EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]); + if (dgst_size < 0) { + s->state = SSL_ST_ERR; + ret = -1; + goto end; + } + offset += dgst_size; + } + } + break; + + case SSL3_ST_SR_CERT_VRFY_A: + case SSL3_ST_SR_CERT_VRFY_B: + ret = ssl3_get_cert_verify(s); + if (ret <= 0) + goto end; + +#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->state = SSL3_ST_SR_FINISHED_A; +#else + if (s->s3->next_proto_neg_seen) + s->state = SSL3_ST_SR_NEXT_PROTO_A; + else + s->state = SSL3_ST_SR_FINISHED_A; +#endif + s->init_num = 0; + break; + +#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) + case SSL3_ST_SR_NEXT_PROTO_A: + case SSL3_ST_SR_NEXT_PROTO_B: + /* + * Enable CCS for NPN. Receiving a CCS clears the flag, so make + * sure not to re-enable it to ban duplicates. This *should* be the + * first time we have received one - but we check anyway to be + * cautious. + * s->s3->change_cipher_spec is set when a CCS is + * processed in s3_pkt.c, and remains set until + * the client's Finished message is read. + */ + if (!s->s3->change_cipher_spec) + s->s3->flags |= SSL3_FLAGS_CCS_OK; + + ret = ssl3_get_next_proto(s); + if (ret <= 0) + goto end; + s->init_num = 0; + s->state = SSL3_ST_SR_FINISHED_A; + break; +#endif + + case SSL3_ST_SR_FINISHED_A: + case SSL3_ST_SR_FINISHED_B: + /* + * Enable CCS for handshakes without NPN. In NPN the CCS flag has + * already been set. Receiving a CCS clears the flag, so make + * sure not to re-enable it to ban duplicates. + * s->s3->change_cipher_spec is set when a CCS is + * processed in s3_pkt.c, and remains set until + * the client's Finished message is read. + */ + if (!s->s3->change_cipher_spec) + s->s3->flags |= SSL3_FLAGS_CCS_OK; + ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A, + SSL3_ST_SR_FINISHED_B); + if (ret <= 0) + goto end; + if (s->hit) + s->state = SSL_ST_OK; +#ifndef OPENSSL_NO_TLSEXT + else if (s->tlsext_ticket_expected) + s->state = SSL3_ST_SW_SESSION_TICKET_A; +#endif + else + s->state = SSL3_ST_SW_CHANGE_A; + s->init_num = 0; + break; + +#ifndef OPENSSL_NO_TLSEXT + case SSL3_ST_SW_SESSION_TICKET_A: + case SSL3_ST_SW_SESSION_TICKET_B: + ret = ssl3_send_newsession_ticket(s); + if (ret <= 0) + goto end; + s->state = SSL3_ST_SW_CHANGE_A; + s->init_num = 0; + break; + + case SSL3_ST_SW_CERT_STATUS_A: + case SSL3_ST_SW_CERT_STATUS_B: + ret = ssl3_send_cert_status(s); + if (ret <= 0) + goto end; + s->state = SSL3_ST_SW_KEY_EXCH_A; + s->init_num = 0; + break; + +#endif + + case SSL3_ST_SW_CHANGE_A: + case SSL3_ST_SW_CHANGE_B: + + s->session->cipher = s->s3->tmp.new_cipher; + if (!s->method->ssl3_enc->setup_key_block(s)) { + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + + ret = ssl3_send_change_cipher_spec(s, + SSL3_ST_SW_CHANGE_A, + SSL3_ST_SW_CHANGE_B); + + if (ret <= 0) + goto end; + s->state = SSL3_ST_SW_FINISHED_A; + s->init_num = 0; + + if (!s->method->ssl3_enc->change_cipher_state(s, + SSL3_CHANGE_CIPHER_SERVER_WRITE)) + { + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + + break; + + case SSL3_ST_SW_FINISHED_A: + case SSL3_ST_SW_FINISHED_B: + ret = ssl3_send_finished(s, + SSL3_ST_SW_FINISHED_A, + SSL3_ST_SW_FINISHED_B, + s->method-> + ssl3_enc->server_finished_label, + s->method-> + ssl3_enc->server_finished_label_len); + if (ret <= 0) + goto end; + s->state = SSL3_ST_SW_FLUSH; + if (s->hit) { +#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A; +#else + if (s->s3->next_proto_neg_seen) { + s->s3->tmp.next_state = SSL3_ST_SR_NEXT_PROTO_A; + } else + s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A; +#endif + } else + s->s3->tmp.next_state = SSL_ST_OK; + s->init_num = 0; + break; + + case SSL_ST_OK: + /* clean a few things up */ + ssl3_cleanup_key_block(s); + + BUF_MEM_free(s->init_buf); + s->init_buf = NULL; + + /* remove buffering on output */ + ssl_free_wbio_buffer(s); + + s->init_num = 0; + + if (s->renegotiate == 2) { /* skipped if we just sent a + * HelloRequest */ + s->renegotiate = 0; + s->new_session = 0; + + ssl_update_cache(s, SSL_SESS_CACHE_SERVER); + + s->ctx->stats.sess_accept_good++; + /* s->server=1; */ + s->handshake_func = ssl3_accept; + + if (cb != NULL) + cb(s, SSL_CB_HANDSHAKE_DONE, 1); + } + + ret = 1; + goto end; + /* break; */ + + case SSL_ST_ERR: + default: + SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNKNOWN_STATE); + ret = -1; + goto end; + /* break; */ + } + + if (!s->s3->tmp.reuse_message && !skip) { + if (s->debug) { + if ((ret = BIO_flush(s->wbio)) <= 0) + goto end; + } + + if ((cb != NULL) && (s->state != state)) { + new_state = s->state; + s->state = state; + cb(s, SSL_CB_ACCEPT_LOOP, 1); + s->state = new_state; + } + } + skip = 0; + } +",0,"int ssl3_accept(SSL *s) +{ + BUF_MEM *buf; + unsigned long alg_k, Time = (unsigned long)time(NULL); + void (*cb) (const SSL *ssl, int type, int val) = NULL; + int ret = -1; + int new_state, state, skip = 0; + + RAND_add(&Time, sizeof(Time), 0); + ERR_clear_error(); + clear_sys_error(); + + if (s->info_callback != NULL) + cb = s->info_callback; + else if (s->ctx->info_callback != NULL) + cb = s->ctx->info_callback; + + /* init things to blank */ + s->in_handshake++; + if (!SSL_in_init(s) || SSL_in_before(s)) + SSL_clear(s); + + if (s->cert == NULL) { + SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_NO_CERTIFICATE_SET); + return (-1); + } +#ifndef OPENSSL_NO_HEARTBEATS + /* + * If we're awaiting a HeartbeatResponse, pretend we already got and + * don't await it anymore, because Heartbeats don't make sense during + * handshakes anyway. + */ + if (s->tlsext_hb_pending) { + s->tlsext_hb_pending = 0; + s->tlsext_hb_seq++; + } +#endif + + for (;;) { + state = s->state; + + switch (s->state) { + case SSL_ST_RENEGOTIATE: + s->renegotiate = 1; + /* s->state=SSL_ST_ACCEPT; */ + + case SSL_ST_BEFORE: + case SSL_ST_ACCEPT: + case SSL_ST_BEFORE | SSL_ST_ACCEPT: + case SSL_ST_OK | SSL_ST_ACCEPT: + + s->server = 1; + if (cb != NULL) + cb(s, SSL_CB_HANDSHAKE_START, 1); + + if ((s->version >> 8) != 3) { + SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR); + s->state = SSL_ST_ERR; + return -1; + } + s->type = SSL_ST_ACCEPT; + + if (s->init_buf == NULL) { + if ((buf = BUF_MEM_new()) == NULL) { + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) { + BUF_MEM_free(buf); + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + s->init_buf = buf; + } + + if (!ssl3_setup_buffers(s)) { + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + + s->init_num = 0; + s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY; + s->s3->flags &= ~SSL3_FLAGS_CCS_OK; + /* + * Should have been reset by ssl3_get_finished, too. + */ + s->s3->change_cipher_spec = 0; + + if (s->state != SSL_ST_RENEGOTIATE) { + /* + * Ok, we now need to push on a buffering BIO so that the + * output is sent in a way that TCP likes :-) + */ + if (!ssl_init_wbio_buffer(s, 1)) { + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + + ssl3_init_finished_mac(s); + s->state = SSL3_ST_SR_CLNT_HELLO_A; + s->ctx->stats.sess_accept++; + } else if (!s->s3->send_connection_binding && + !(s->options & + SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) { + /* + * Server attempting to renegotiate with client that doesn't + * support secure renegotiation. + */ + SSLerr(SSL_F_SSL3_ACCEPT, + SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED); + ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE); + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } else { + /* + * s->state == SSL_ST_RENEGOTIATE, we will just send a + * HelloRequest + */ + s->ctx->stats.sess_accept_renegotiate++; + s->state = SSL3_ST_SW_HELLO_REQ_A; + } + break; + + case SSL3_ST_SW_HELLO_REQ_A: + case SSL3_ST_SW_HELLO_REQ_B: + + s->shutdown = 0; + ret = ssl3_send_hello_request(s); + if (ret <= 0) + goto end; + s->s3->tmp.next_state = SSL3_ST_SW_HELLO_REQ_C; + s->state = SSL3_ST_SW_FLUSH; + s->init_num = 0; + + ssl3_init_finished_mac(s); + break; + + case SSL3_ST_SW_HELLO_REQ_C: + s->state = SSL_ST_OK; + break; + + case SSL3_ST_SR_CLNT_HELLO_A: + case SSL3_ST_SR_CLNT_HELLO_B: + case SSL3_ST_SR_CLNT_HELLO_C: + + s->shutdown = 0; + ret = ssl3_get_client_hello(s); + if (ret <= 0) + goto end; +#ifndef OPENSSL_NO_SRP + s->state = SSL3_ST_SR_CLNT_HELLO_D; + case SSL3_ST_SR_CLNT_HELLO_D: + { + int al; + if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) { + /* + * callback indicates firther work to be done + */ + s->rwstate = SSL_X509_LOOKUP; + goto end; + } + if (ret != SSL_ERROR_NONE) { + ssl3_send_alert(s, SSL3_AL_FATAL, al); + /* + * This is not really an error but the only means to for + * a client to detect whether srp is supported. + */ + if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY) + SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_CLIENTHELLO_TLSEXT); + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + } +#endif + + s->renegotiate = 2; + s->state = SSL3_ST_SW_SRVR_HELLO_A; + s->init_num = 0; + break; + + case SSL3_ST_SW_SRVR_HELLO_A: + case SSL3_ST_SW_SRVR_HELLO_B: + ret = ssl3_send_server_hello(s); + if (ret <= 0) + goto end; +#ifndef OPENSSL_NO_TLSEXT + if (s->hit) { + if (s->tlsext_ticket_expected) + s->state = SSL3_ST_SW_SESSION_TICKET_A; + else + s->state = SSL3_ST_SW_CHANGE_A; + } +#else + if (s->hit) + s->state = SSL3_ST_SW_CHANGE_A; +#endif + else + s->state = SSL3_ST_SW_CERT_A; + s->init_num = 0; + break; + + case SSL3_ST_SW_CERT_A: + case SSL3_ST_SW_CERT_B: + /* Check if it is anon DH or anon ECDH, */ + /* normal PSK or KRB5 or SRP */ + if (! + (s->s3->tmp. + new_cipher->algorithm_auth & (SSL_aNULL | SSL_aKRB5 | + SSL_aSRP)) +&& !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { + ret = ssl3_send_server_certificate(s); + if (ret <= 0) + goto end; +#ifndef OPENSSL_NO_TLSEXT + if (s->tlsext_status_expected) + s->state = SSL3_ST_SW_CERT_STATUS_A; + else + s->state = SSL3_ST_SW_KEY_EXCH_A; + } else { + skip = 1; + s->state = SSL3_ST_SW_KEY_EXCH_A; + } +#else + } else + skip = 1; + + s->state = SSL3_ST_SW_KEY_EXCH_A; +#endif + s->init_num = 0; + break; + + case SSL3_ST_SW_KEY_EXCH_A: + case SSL3_ST_SW_KEY_EXCH_B: + alg_k = s->s3->tmp.new_cipher->algorithm_mkey; + + /* + * clear this, it may get reset by + * send_server_key_exchange + */ + s->s3->tmp.use_rsa_tmp = 0; + + /* + * only send if a DH key exchange, fortezza or RSA but we have a + * sign only certificate PSK: may send PSK identity hints For + * ECC ciphersuites, we send a serverKeyExchange message only if + * the cipher suite is either ECDH-anon or ECDHE. In other cases, + * the server certificate contains the server's public key for + * key exchange. + */ + if (0 + /* + * PSK: send ServerKeyExchange if PSK identity hint if + * provided + */ +#ifndef OPENSSL_NO_PSK + || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint) +#endif +#ifndef OPENSSL_NO_SRP + /* SRP: send ServerKeyExchange */ + || (alg_k & SSL_kSRP) +#endif + || (alg_k & SSL_kEDH) + || (alg_k & SSL_kEECDH) + || ((alg_k & SSL_kRSA) + && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL + || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) + && EVP_PKEY_size(s->cert->pkeys + [SSL_PKEY_RSA_ENC].privatekey) * + 8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher) + ) + ) + ) + ) { + ret = ssl3_send_server_key_exchange(s); + if (ret <= 0) + goto end; + } else + skip = 1; + + s->state = SSL3_ST_SW_CERT_REQ_A; + s->init_num = 0; + break; + + case SSL3_ST_SW_CERT_REQ_A: + case SSL3_ST_SW_CERT_REQ_B: + if ( /* don't request cert unless asked for it: */ + !(s->verify_mode & SSL_VERIFY_PEER) || + /* + * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert + * during re-negotiation: + */ + ((s->session->peer != NULL) && + (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) || + /* + * never request cert in anonymous ciphersuites (see + * section ""Certificate request"" in SSL 3 drafts and in + * RFC 2246): + */ + ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) && + /* + * ... except when the application insists on + * verification (against the specs, but s3_clnt.c accepts + * this for SSL 3) + */ + !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) || + /* + * never request cert in Kerberos ciphersuites + */ + (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) || + /* don't request certificate for SRP auth */ + (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP) + /* + * With normal PSK Certificates and Certificate Requests + * are omitted + */ + || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) { + /* no cert request */ + skip = 1; + s->s3->tmp.cert_request = 0; + s->state = SSL3_ST_SW_SRVR_DONE_A; + if (s->s3->handshake_buffer) { + if (!ssl3_digest_cached_records(s)) { + s->state = SSL_ST_ERR; + return -1; + } + } + } else { + s->s3->tmp.cert_request = 1; + ret = ssl3_send_certificate_request(s); + if (ret <= 0) + goto end; +#ifndef NETSCAPE_HANG_BUG + s->state = SSL3_ST_SW_SRVR_DONE_A; +#else + s->state = SSL3_ST_SW_FLUSH; + s->s3->tmp.next_state = SSL3_ST_SR_CERT_A; +#endif + s->init_num = 0; + } + break; + + case SSL3_ST_SW_SRVR_DONE_A: + case SSL3_ST_SW_SRVR_DONE_B: + ret = ssl3_send_server_done(s); + if (ret <= 0) + goto end; + s->s3->tmp.next_state = SSL3_ST_SR_CERT_A; + s->state = SSL3_ST_SW_FLUSH; + s->init_num = 0; + break; + + case SSL3_ST_SW_FLUSH: + + /* + * This code originally checked to see if any data was pending + * using BIO_CTRL_INFO and then flushed. This caused problems as + * documented in PR#1939. The proposed fix doesn't completely + * resolve this issue as buggy implementations of + * BIO_CTRL_PENDING still exist. So instead we just flush + * unconditionally. + */ + + s->rwstate = SSL_WRITING; + if (BIO_flush(s->wbio) <= 0) { + ret = -1; + goto end; + } + s->rwstate = SSL_NOTHING; + + s->state = s->s3->tmp.next_state; + break; + + case SSL3_ST_SR_CERT_A: + case SSL3_ST_SR_CERT_B: + if (s->s3->tmp.cert_request) { + ret = ssl3_get_client_certificate(s); + if (ret <= 0) + goto end; + } + s->init_num = 0; + s->state = SSL3_ST_SR_KEY_EXCH_A; + break; + + case SSL3_ST_SR_KEY_EXCH_A: + case SSL3_ST_SR_KEY_EXCH_B: + ret = ssl3_get_client_key_exchange(s); + if (ret <= 0) + goto end; + if (ret == 2) { + /* + * For the ECDH ciphersuites when the client sends its ECDH + * pub key in a certificate, the CertificateVerify message is + * not sent. Also for GOST ciphersuites when the client uses + * its key from the certificate for key exchange. + */ +#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->state = SSL3_ST_SR_FINISHED_A; +#else + if (s->s3->next_proto_neg_seen) + s->state = SSL3_ST_SR_NEXT_PROTO_A; + else + s->state = SSL3_ST_SR_FINISHED_A; +#endif + s->init_num = 0; + } else if (SSL_USE_SIGALGS(s)) { + s->state = SSL3_ST_SR_CERT_VRFY_A; + s->init_num = 0; + if (!s->session->peer) + break; + /* + * For sigalgs freeze the handshake buffer at this point and + * digest cached records. + */ + if (!s->s3->handshake_buffer) { + SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR); + s->state = SSL_ST_ERR; + return -1; + } + s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE; + if (!ssl3_digest_cached_records(s)) { + s->state = SSL_ST_ERR; + return -1; + } + } else { + int offset = 0; + int dgst_num; + + s->state = SSL3_ST_SR_CERT_VRFY_A; + s->init_num = 0; + + /* + * We need to get hashes here so if there is a client cert, + * it can be verified FIXME - digest processing for + * CertificateVerify should be generalized. But it is next + * step + */ + if (s->s3->handshake_buffer) { + if (!ssl3_digest_cached_records(s)) { + s->state = SSL_ST_ERR; + return -1; + } + } + for (dgst_num = 0; dgst_num < SSL_MAX_DIGEST; dgst_num++) + if (s->s3->handshake_dgst[dgst_num]) { + int dgst_size; + + s->method->ssl3_enc->cert_verify_mac(s, + EVP_MD_CTX_type + (s-> + s3->handshake_dgst + [dgst_num]), + &(s->s3-> + tmp.cert_verify_md + [offset])); + dgst_size = + EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]); + if (dgst_size < 0) { + s->state = SSL_ST_ERR; + ret = -1; + goto end; + } + offset += dgst_size; + } + } + break; + + case SSL3_ST_SR_CERT_VRFY_A: + case SSL3_ST_SR_CERT_VRFY_B: + ret = ssl3_get_cert_verify(s); + if (ret <= 0) + goto end; + +#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->state = SSL3_ST_SR_FINISHED_A; +#else + if (s->s3->next_proto_neg_seen) + s->state = SSL3_ST_SR_NEXT_PROTO_A; + else + s->state = SSL3_ST_SR_FINISHED_A; +#endif + s->init_num = 0; + break; + +#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG) + case SSL3_ST_SR_NEXT_PROTO_A: + case SSL3_ST_SR_NEXT_PROTO_B: + /* + * Enable CCS for NPN. Receiving a CCS clears the flag, so make + * sure not to re-enable it to ban duplicates. This *should* be the + * first time we have received one - but we check anyway to be + * cautious. + * s->s3->change_cipher_spec is set when a CCS is + * processed in s3_pkt.c, and remains set until + * the client's Finished message is read. + */ + if (!s->s3->change_cipher_spec) + s->s3->flags |= SSL3_FLAGS_CCS_OK; + + ret = ssl3_get_next_proto(s); + if (ret <= 0) + goto end; + s->init_num = 0; + s->state = SSL3_ST_SR_FINISHED_A; + break; +#endif + + case SSL3_ST_SR_FINISHED_A: + case SSL3_ST_SR_FINISHED_B: + /* + * Enable CCS for handshakes without NPN. In NPN the CCS flag has + * already been set. Receiving a CCS clears the flag, so make + * sure not to re-enable it to ban duplicates. + * s->s3->change_cipher_spec is set when a CCS is + * processed in s3_pkt.c, and remains set until + * the client's Finished message is read. + */ + if (!s->s3->change_cipher_spec) + s->s3->flags |= SSL3_FLAGS_CCS_OK; + ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A, + SSL3_ST_SR_FINISHED_B); + if (ret <= 0) + goto end; + if (s->hit) + s->state = SSL_ST_OK; +#ifndef OPENSSL_NO_TLSEXT + else if (s->tlsext_ticket_expected) + s->state = SSL3_ST_SW_SESSION_TICKET_A; +#endif + else + s->state = SSL3_ST_SW_CHANGE_A; + s->init_num = 0; + break; + +#ifndef OPENSSL_NO_TLSEXT + case SSL3_ST_SW_SESSION_TICKET_A: + case SSL3_ST_SW_SESSION_TICKET_B: + ret = ssl3_send_newsession_ticket(s); + if (ret <= 0) + goto end; + s->state = SSL3_ST_SW_CHANGE_A; + s->init_num = 0; + break; + + case SSL3_ST_SW_CERT_STATUS_A: + case SSL3_ST_SW_CERT_STATUS_B: + ret = ssl3_send_cert_status(s); + if (ret <= 0) + goto end; + s->state = SSL3_ST_SW_KEY_EXCH_A; + s->init_num = 0; + break; + +#endif + + case SSL3_ST_SW_CHANGE_A: + case SSL3_ST_SW_CHANGE_B: + + s->session->cipher = s->s3->tmp.new_cipher; + if (!s->method->ssl3_enc->setup_key_block(s)) { + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + + ret = ssl3_send_change_cipher_spec(s, + SSL3_ST_SW_CHANGE_A, + SSL3_ST_SW_CHANGE_B); + + if (ret <= 0) + goto end; + s->state = SSL3_ST_SW_FINISHED_A; + s->init_num = 0; + + if (!s->method->ssl3_enc->change_cipher_state(s, + SSL3_CHANGE_CIPHER_SERVER_WRITE)) + { + ret = -1; + s->state = SSL_ST_ERR; + goto end; + } + + break; + + case SSL3_ST_SW_FINISHED_A: + case SSL3_ST_SW_FINISHED_B: + ret = ssl3_send_finished(s, + SSL3_ST_SW_FINISHED_A, + SSL3_ST_SW_FINISHED_B, + s->method-> + ssl3_enc->server_finished_label, + s->method-> + ssl3_enc->server_finished_label_len); + if (ret <= 0) + goto end; + s->state = SSL3_ST_SW_FLUSH; + if (s->hit) { +#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG) + s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A; +#else + if (s->s3->next_proto_neg_seen) { + s->s3->tmp.next_state = SSL3_ST_SR_NEXT_PROTO_A; + } else + s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A; +#endif + } else + s->s3->tmp.next_state = SSL_ST_OK; + s->init_num = 0; + break; + + case SSL_ST_OK: + /* clean a few things up */ + ssl3_cleanup_key_block(s); + + BUF_MEM_free(s->init_buf); + s->init_buf = NULL; + + /* remove buffering on output */ + ssl_free_wbio_buffer(s); + + s->init_num = 0; + + if (s->renegotiate == 2) { /* skipped if we just sent a + * HelloRequest */ + s->renegotiate = 0; + s->new_session = 0; + + ssl_update_cache(s, SSL_SESS_CACHE_SERVER); + + s->ctx->stats.sess_accept_good++; + /* s->server=1; */ + s->handshake_func = ssl3_accept; + + if (cb != NULL) + cb(s, SSL_CB_HANDSHAKE_DONE, 1); + } + + ret = 1; + goto end; + /* break; */ + + case SSL_ST_ERR: + default: + SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNKNOWN_STATE); + ret = -1; + goto end; + /* break; */ + } + + if (!s->s3->tmp.reuse_message && !skip) { + if (s->debug) { + if ((ret = BIO_flush(s->wbio)) <= 0) + goto end; + } + + if ((cb != NULL) && (s->state != state)) { + new_state = s->state; + s->state = state; + cb(s, SSL_CB_ACCEPT_LOOP, 1); + s->state = new_state; + } + } + skip = 0; + } +","@@ -980,7 +980,7 @@ int ssl3_get_client_hello(SSL *s) + + session_length = *(p + SSL3_RANDOM_SIZE); + +- if (p + SSL3_RANDOM_SIZE + session_length + 1 >= d + n) { ++ if (SSL3_RANDOM_SIZE + session_length + 1 >= (d + n) - p) { + al = SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); + goto f_err; +@@ -998,7 +998,7 @@ int ssl3_get_client_hello(SSL *s) + /* get the session-id */ + j = *(p++); + +- if (p + j > d + n) { ++ if ((d + n) - p < j) { + al = SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); + goto f_err; +@@ -1054,14 +1054,14 @@ int ssl3_get_client_hello(SSL *s) + + if (SSL_IS_DTLS(s)) { + /* cookie stuff */ +- if (p + 1 > d + n) { ++ if ((d + n) - p < 1) { + al = SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); + goto f_err; + } + cookie_len = *(p++); + +- if (p + cookie_len > d + n) { ++ if ((d + n ) - p < cookie_len) { + al = SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); + goto f_err; +@@ -1131,7 +1131,7 @@ int ssl3_get_client_hello(SSL *s) + } + } + +- if (p + 2 > d + n) { ++ if ((d + n ) - p < 2) { + al = SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT); + goto f_err; +@@ -1145,7 +1145,7 @@ int ssl3_get_client_hello(SSL *s) + } + + /* i bytes of cipher data + 1 byte for compression length later */ +- if ((p + i + 1) > (d + n)) { ++ if ((d + n) - p < i + 1) { + /* not enough data */ + al = SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH); +@@ -1211,7 +1211,7 @@ int ssl3_get_client_hello(SSL *s) + + /* compression */ + i = *(p++); +- if ((p + i) > (d + n)) { ++ if ((d + n) - p < i) { + /* not enough data */ + al = SSL_AD_DECODE_ERROR; + SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);",5284,5615,6144 +18627,"EnumTraits::ToMojom( + media::VideoCaptureError input) { + switch (input) { + case media::VideoCaptureError::kNone: + return media::mojom::VideoCaptureError::kNone; + case media::VideoCaptureError:: + kVideoCaptureControllerInvalidOrUnsupportedVideoCaptureParametersRequested: + return media::mojom::VideoCaptureError:: + kVideoCaptureControllerInvalidOrUnsupportedVideoCaptureParametersRequested; + case media::VideoCaptureError::kVideoCaptureControllerIsAlreadyInErrorState: + return media::mojom::VideoCaptureError:: + kVideoCaptureControllerIsAlreadyInErrorState; + case media::VideoCaptureError::kVideoCaptureManagerDeviceConnectionLost: + return media::mojom::VideoCaptureError:: + kVideoCaptureManagerDeviceConnectionLost; + case media::VideoCaptureError:: + kFrameSinkVideoCaptureDeviceAleradyEndedOnFatalError: + return media::mojom::VideoCaptureError:: + kFrameSinkVideoCaptureDeviceAleradyEndedOnFatalError; + case media::VideoCaptureError:: + kFrameSinkVideoCaptureDeviceEncounteredFatalError: + return media::mojom::VideoCaptureError:: + kFrameSinkVideoCaptureDeviceEncounteredFatalError; + case media::VideoCaptureError::kV4L2FailedToOpenV4L2DeviceDriverFile: + return media::mojom::VideoCaptureError:: + kV4L2FailedToOpenV4L2DeviceDriverFile; + case media::VideoCaptureError::kV4L2ThisIsNotAV4L2VideoCaptureDevice: + return media::mojom::VideoCaptureError:: + kV4L2ThisIsNotAV4L2VideoCaptureDevice; + case media::VideoCaptureError::kV4L2FailedToFindASupportedCameraFormat: + return media::mojom::VideoCaptureError:: + kV4L2FailedToFindASupportedCameraFormat; + case media::VideoCaptureError::kV4L2FailedToSetVideoCaptureFormat: + return media::mojom::VideoCaptureError:: + kV4L2FailedToSetVideoCaptureFormat; + case media::VideoCaptureError::kV4L2UnsupportedPixelFormat: + return media::mojom::VideoCaptureError::kV4L2UnsupportedPixelFormat; + case media::VideoCaptureError::kV4L2FailedToSetCameraFramerate: + return media::mojom::VideoCaptureError::kV4L2FailedToSetCameraFramerate; + case media::VideoCaptureError::kV4L2ErrorRequestingMmapBuffers: + return media::mojom::VideoCaptureError::kV4L2ErrorRequestingMmapBuffers; + case media::VideoCaptureError::kV4L2AllocateBufferFailed: + return media::mojom::VideoCaptureError::kV4L2AllocateBufferFailed; + case media::VideoCaptureError::kV4L2VidiocStreamonFailed: + return media::mojom::VideoCaptureError::kV4L2VidiocStreamonFailed; + case media::VideoCaptureError::kV4L2VidiocStreamoffFailed: + return media::mojom::VideoCaptureError::kV4L2VidiocStreamoffFailed; + case media::VideoCaptureError::kV4L2FailedToVidiocReqbufsWithCount0: + return media::mojom::VideoCaptureError:: + kV4L2FailedToVidiocReqbufsWithCount0; + case media::VideoCaptureError::kV4L2PollFailed: + return media::mojom::VideoCaptureError::kV4L2PollFailed; + case media::VideoCaptureError:: + kV4L2MultipleContinuousTimeoutsWhileReadPolling: + return media::mojom::VideoCaptureError:: + kV4L2MultipleContinuousTimeoutsWhileReadPolling; + case media::VideoCaptureError::kV4L2FailedToDequeueCaptureBuffer: + return media::mojom::VideoCaptureError::kV4L2FailedToDequeueCaptureBuffer; + case media::VideoCaptureError::kV4L2FailedToEnqueueCaptureBuffer: + return media::mojom::VideoCaptureError::kV4L2FailedToEnqueueCaptureBuffer; + case media::VideoCaptureError:: + kSingleClientVideoCaptureHostLostConnectionToDevice: + return media::mojom::VideoCaptureError:: + kSingleClientVideoCaptureHostLostConnectionToDevice; + case media::VideoCaptureError::kSingleClientVideoCaptureDeviceLaunchAborted: + return media::mojom::VideoCaptureError:: + kSingleClientVideoCaptureDeviceLaunchAborted; + case media::VideoCaptureError:: + kDesktopCaptureDeviceWebrtcDesktopCapturerHasFailed: + return media::mojom::VideoCaptureError:: + kDesktopCaptureDeviceWebrtcDesktopCapturerHasFailed; + case media::VideoCaptureError::kFileVideoCaptureDeviceCouldNotOpenVideoFile: + return media::mojom::VideoCaptureError:: + kFileVideoCaptureDeviceCouldNotOpenVideoFile; + case media::VideoCaptureError:: + kDeviceCaptureLinuxFailedToCreateVideoCaptureDelegate: + return media::mojom::VideoCaptureError:: + kDeviceCaptureLinuxFailedToCreateVideoCaptureDelegate; + case media::VideoCaptureError:: + kErrorFakeDeviceIntentionallyEmittingErrorEvent: + return media::mojom::VideoCaptureError:: + kErrorFakeDeviceIntentionallyEmittingErrorEvent; + case media::VideoCaptureError::kDeviceClientTooManyFramesDroppedY16: + return media::mojom::VideoCaptureError:: + kDeviceClientTooManyFramesDroppedY16; + case media::VideoCaptureError:: + kDeviceMediaToMojoAdapterEncounteredUnsupportedBufferType: + return media::mojom::VideoCaptureError:: + kDeviceMediaToMojoAdapterEncounteredUnsupportedBufferType; + case media::VideoCaptureError:: + kVideoCaptureManagerProcessDeviceStartQueueDeviceInfoNotFound: + return media::mojom::VideoCaptureError:: + kVideoCaptureManagerProcessDeviceStartQueueDeviceInfoNotFound; + case media::VideoCaptureError:: + kInProcessDeviceLauncherFailedToCreateDeviceInstance: + return media::mojom::VideoCaptureError:: + kInProcessDeviceLauncherFailedToCreateDeviceInstance; + case media::VideoCaptureError:: + kServiceDeviceLauncherLostConnectionToDeviceFactoryDuringDeviceStart: + return media::mojom::VideoCaptureError:: + kServiceDeviceLauncherLostConnectionToDeviceFactoryDuringDeviceStart; + case media::VideoCaptureError:: + kServiceDeviceLauncherServiceRespondedWithDeviceNotFound: + return media::mojom::VideoCaptureError:: + kServiceDeviceLauncherServiceRespondedWithDeviceNotFound; + case media::VideoCaptureError:: + kServiceDeviceLauncherConnectionLostWhileWaitingForCallback: + return media::mojom::VideoCaptureError:: + kServiceDeviceLauncherConnectionLostWhileWaitingForCallback; + case media::VideoCaptureError::kIntentionalErrorRaisedByUnitTest: + return media::mojom::VideoCaptureError::kIntentionalErrorRaisedByUnitTest; + case media::VideoCaptureError::kCrosHalV3FailedToStartDeviceThread: + return media::mojom::VideoCaptureError:: + kCrosHalV3FailedToStartDeviceThread; + case media::VideoCaptureError::kCrosHalV3DeviceDelegateMojoConnectionError: + return media::mojom::VideoCaptureError:: + kCrosHalV3DeviceDelegateMojoConnectionError; + case media::VideoCaptureError:: + kCrosHalV3DeviceDelegateFailedToGetCameraInfo: + return media::mojom::VideoCaptureError:: + kCrosHalV3DeviceDelegateFailedToGetCameraInfo; + case media::VideoCaptureError:: + kCrosHalV3DeviceDelegateMissingSensorOrientationInfo: + return media::mojom::VideoCaptureError:: + kCrosHalV3DeviceDelegateMissingSensorOrientationInfo; + case media::VideoCaptureError:: + kCrosHalV3DeviceDelegateFailedToOpenCameraDevice: + return media::mojom::VideoCaptureError:: + kCrosHalV3DeviceDelegateFailedToOpenCameraDevice; + case media::VideoCaptureError:: + kCrosHalV3DeviceDelegateFailedToInitializeCameraDevice: + return media::mojom::VideoCaptureError:: + kCrosHalV3DeviceDelegateFailedToInitializeCameraDevice; + case media::VideoCaptureError:: + kCrosHalV3DeviceDelegateFailedToConfigureStreams: + return media::mojom::VideoCaptureError:: + kCrosHalV3DeviceDelegateFailedToConfigureStreams; + case media::VideoCaptureError:: + kCrosHalV3DeviceDelegateWrongNumberOfStreamsConfigured: + return media::mojom::VideoCaptureError:: + kCrosHalV3DeviceDelegateWrongNumberOfStreamsConfigured; + case media::VideoCaptureError:: + kCrosHalV3DeviceDelegateFailedToGetDefaultRequestSettings: + return media::mojom::VideoCaptureError:: + kCrosHalV3DeviceDelegateFailedToGetDefaultRequestSettings; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerHalRequestedTooManyBuffers: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerHalRequestedTooManyBuffers; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerFailedToCreateGpuMemoryBuffer: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerFailedToCreateGpuMemoryBuffer; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerFailedToMapGpuMemoryBuffer: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerFailedToMapGpuMemoryBuffer; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerUnsupportedVideoPixelFormat: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerUnsupportedVideoPixelFormat; + case media::VideoCaptureError::kCrosHalV3BufferManagerFailedToDupFd: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerFailedToDupFd; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerFailedToWrapGpuMemoryHandle: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerFailedToWrapGpuMemoryHandle; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerFailedToRegisterBuffer: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerFailedToRegisterBuffer; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerProcessCaptureRequestFailed: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerProcessCaptureRequestFailed; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerInvalidPendingResultId: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerInvalidPendingResultId; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerReceivedDuplicatedPartialMetadata: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerReceivedDuplicatedPartialMetadata; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerIncorrectNumberOfOutputBuffersReceived: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerIncorrectNumberOfOutputBuffersReceived; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerInvalidTypeOfOutputBuffersReceived: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerInvalidTypeOfOutputBuffersReceived; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerReceivedMultipleResultBuffersForFrame: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerReceivedMultipleResultBuffersForFrame; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerUnknownStreamInCamera3NotifyMsg: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerUnknownStreamInCamera3NotifyMsg; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerReceivedInvalidShutterTime: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerReceivedInvalidShutterTime; + case media::VideoCaptureError::kCrosHalV3BufferManagerFatalDeviceError: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerFatalDeviceError; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerReceivedFrameIsOutOfOrder: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerReceivedFrameIsOutOfOrder; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerFailedToUnwrapReleaseFenceFd: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerFailedToUnwrapReleaseFenceFd; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerSyncWaitOnReleaseFenceTimedOut: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerSyncWaitOnReleaseFenceTimedOut; + case media::VideoCaptureError::kCrosHalV3BufferManagerInvalidJpegBlob: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerInvalidJpegBlob; + case media::VideoCaptureError::kAndroidFailedToAllocate: + return media::mojom::VideoCaptureError::kAndroidFailedToAllocate; + case media::VideoCaptureError::kAndroidFailedToStartCapture: + return media::mojom::VideoCaptureError::kAndroidFailedToStartCapture; + case media::VideoCaptureError::kAndroidFailedToStopCapture: + return media::mojom::VideoCaptureError::kAndroidFailedToStopCapture; + case media::VideoCaptureError::kAndroidApi1CameraErrorCallbackReceived: + return media::mojom::VideoCaptureError:: + kAndroidApi1CameraErrorCallbackReceived; + case media::VideoCaptureError::kAndroidApi2CameraDeviceErrorReceived: + return media::mojom::VideoCaptureError:: + kAndroidApi2CameraDeviceErrorReceived; + case media::VideoCaptureError::kAndroidApi2CaptureSessionConfigureFailed: + return media::mojom::VideoCaptureError:: + kAndroidApi2CaptureSessionConfigureFailed; + case media::VideoCaptureError::kAndroidApi2ImageReaderUnexpectedImageFormat: + return media::mojom::VideoCaptureError:: + kAndroidApi2ImageReaderUnexpectedImageFormat; + case media::VideoCaptureError:: + kAndroidApi2ImageReaderSizeDidNotMatchImageSize: + return media::mojom::VideoCaptureError:: + kAndroidApi2ImageReaderSizeDidNotMatchImageSize; + case media::VideoCaptureError::kAndroidApi2ErrorRestartingPreview: + return media::mojom::VideoCaptureError:: + kAndroidApi2ErrorRestartingPreview; + case media::VideoCaptureError::kAndroidScreenCaptureUnsupportedFormat: + return media::mojom::VideoCaptureError:: + kAndroidScreenCaptureUnsupportedFormat; + case media::VideoCaptureError:: + kAndroidScreenCaptureFailedToStartCaptureMachine: + return media::mojom::VideoCaptureError:: + kAndroidScreenCaptureFailedToStartCaptureMachine; + case media::VideoCaptureError:: + kAndroidScreenCaptureTheUserDeniedScreenCapture: + return media::mojom::VideoCaptureError:: + kAndroidScreenCaptureTheUserDeniedScreenCapture; + case media::VideoCaptureError:: + kAndroidScreenCaptureFailedToStartScreenCapture: + return media::mojom::VideoCaptureError:: + kAndroidScreenCaptureFailedToStartScreenCapture; + case media::VideoCaptureError::kWinDirectShowCantGetCaptureFormatSettings: + return media::mojom::VideoCaptureError:: + kWinDirectShowCantGetCaptureFormatSettings; + case media::VideoCaptureError:: + kWinDirectShowFailedToGetNumberOfCapabilities: + return media::mojom::VideoCaptureError:: + kWinDirectShowFailedToGetNumberOfCapabilities; + case media::VideoCaptureError:: + kWinDirectShowFailedToGetCaptureDeviceCapabilities: + return media::mojom::VideoCaptureError:: + kWinDirectShowFailedToGetCaptureDeviceCapabilities; + case media::VideoCaptureError:: + kWinDirectShowFailedToSetCaptureDeviceOutputFormat: + return media::mojom::VideoCaptureError:: + kWinDirectShowFailedToSetCaptureDeviceOutputFormat; + case media::VideoCaptureError::kWinDirectShowFailedToConnectTheCaptureGraph: + return media::mojom::VideoCaptureError:: + kWinDirectShowFailedToConnectTheCaptureGraph; + case media::VideoCaptureError::kWinDirectShowFailedToPauseTheCaptureDevice: + return media::mojom::VideoCaptureError:: + kWinDirectShowFailedToPauseTheCaptureDevice; + case media::VideoCaptureError::kWinDirectShowFailedToStartTheCaptureDevice: + return media::mojom::VideoCaptureError:: + kWinDirectShowFailedToStartTheCaptureDevice; + case media::VideoCaptureError::kWinDirectShowFailedToStopTheCaptureGraph: + return media::mojom::VideoCaptureError:: + kWinDirectShowFailedToStopTheCaptureGraph; + case media::VideoCaptureError::kWinMediaFoundationEngineIsNull: + return media::mojom::VideoCaptureError::kWinMediaFoundationEngineIsNull; + case media::VideoCaptureError::kWinMediaFoundationEngineGetSourceFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationEngineGetSourceFailed; + case media::VideoCaptureError:: + kWinMediaFoundationFillPhotoCapabilitiesFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationFillPhotoCapabilitiesFailed; + case media::VideoCaptureError:: + kWinMediaFoundationFillVideoCapabilitiesFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationFillVideoCapabilitiesFailed; + case media::VideoCaptureError::kWinMediaFoundationNoVideoCapabilityFound: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationNoVideoCapabilityFound; + case media::VideoCaptureError:: + kWinMediaFoundationGetAvailableDeviceMediaTypeFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationGetAvailableDeviceMediaTypeFailed; + case media::VideoCaptureError:: + kWinMediaFoundationSetCurrentDeviceMediaTypeFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationSetCurrentDeviceMediaTypeFailed; + case media::VideoCaptureError::kWinMediaFoundationEngineGetSinkFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationEngineGetSinkFailed; + case media::VideoCaptureError:: + kWinMediaFoundationSinkQueryCapturePreviewInterfaceFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationSinkQueryCapturePreviewInterfaceFailed; + case media::VideoCaptureError:: + kWinMediaFoundationSinkRemoveAllStreamsFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationSinkRemoveAllStreamsFailed; + case media::VideoCaptureError:: + kWinMediaFoundationCreateSinkVideoMediaTypeFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationCreateSinkVideoMediaTypeFailed; + case media::VideoCaptureError:: + kWinMediaFoundationConvertToVideoSinkMediaTypeFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationConvertToVideoSinkMediaTypeFailed; + case media::VideoCaptureError::kWinMediaFoundationSinkAddStreamFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationSinkAddStreamFailed; + case media::VideoCaptureError:: + kWinMediaFoundationSinkSetSampleCallbackFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationSinkSetSampleCallbackFailed; + case media::VideoCaptureError::kWinMediaFoundationEngineStartPreviewFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationEngineStartPreviewFailed; + case media::VideoCaptureError::kWinMediaFoundationGetMediaEventStatusFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationGetMediaEventStatusFailed; + case media::VideoCaptureError::kMacSetCaptureDeviceFailed: + return media::mojom::VideoCaptureError::kMacSetCaptureDeviceFailed; + case media::VideoCaptureError::kMacCouldNotStartCaptureDevice: + return media::mojom::VideoCaptureError::kMacCouldNotStartCaptureDevice; + case media::VideoCaptureError::kMacReceivedFrameWithUnexpectedResolution: + return media::mojom::VideoCaptureError:: + kMacReceivedFrameWithUnexpectedResolution; + case media::VideoCaptureError::kMacUpdateCaptureResolutionFailed: + return media::mojom::VideoCaptureError::kMacUpdateCaptureResolutionFailed; + case media::VideoCaptureError::kMacDeckLinkDeviceIdNotFoundInTheSystem: + return media::mojom::VideoCaptureError:: + kMacDeckLinkDeviceIdNotFoundInTheSystem; + case media::VideoCaptureError::kMacDeckLinkErrorQueryingInputInterface: + return media::mojom::VideoCaptureError:: + kMacDeckLinkErrorQueryingInputInterface; + case media::VideoCaptureError::kMacDeckLinkErrorCreatingDisplayModeIterator: + return media::mojom::VideoCaptureError:: + kMacDeckLinkErrorCreatingDisplayModeIterator; + case media::VideoCaptureError::kMacDeckLinkCouldNotFindADisplayMode: + return media::mojom::VideoCaptureError:: + kMacDeckLinkCouldNotFindADisplayMode; + case media::VideoCaptureError:: + kMacDeckLinkCouldNotSelectTheVideoFormatWeLike: + return media::mojom::VideoCaptureError:: + kMacDeckLinkCouldNotSelectTheVideoFormatWeLike; + case media::VideoCaptureError::kMacDeckLinkCouldNotStartCapturing: + return media::mojom::VideoCaptureError:: + kMacDeckLinkCouldNotStartCapturing; + case media::VideoCaptureError::kMacDeckLinkUnsupportedPixelFormat: + return media::mojom::VideoCaptureError:: + kMacDeckLinkUnsupportedPixelFormat; + case media::VideoCaptureError:: + kMacAvFoundationReceivedAVCaptureSessionRuntimeErrorNotification: + return media::mojom::VideoCaptureError:: + kMacAvFoundationReceivedAVCaptureSessionRuntimeErrorNotification; + case media::VideoCaptureError::kAndroidApi2ErrorConfiguringCamera: + return media::mojom::VideoCaptureError:: + kAndroidApi2ErrorConfiguringCamera; + case media::VideoCaptureError::kCrosHalV3DeviceDelegateFailedToFlush: + return media::mojom::VideoCaptureError:: + kCrosHalV3DeviceDelegateFailedToFlush; + } + NOTREACHED(); + return media::mojom::VideoCaptureError::kNone; +} +",1,"EnumTraits::ToMojom( + media::VideoCaptureError input) { + switch (input) { + case media::VideoCaptureError::kNone: + return media::mojom::VideoCaptureError::kNone; + case media::VideoCaptureError:: + kVideoCaptureControllerInvalidOrUnsupportedVideoCaptureParametersRequested: + return media::mojom::VideoCaptureError:: + kVideoCaptureControllerInvalidOrUnsupportedVideoCaptureParametersRequested; + case media::VideoCaptureError::kVideoCaptureControllerIsAlreadyInErrorState: + return media::mojom::VideoCaptureError:: + kVideoCaptureControllerIsAlreadyInErrorState; + case media::VideoCaptureError::kVideoCaptureManagerDeviceConnectionLost: + return media::mojom::VideoCaptureError:: + kVideoCaptureManagerDeviceConnectionLost; + case media::VideoCaptureError:: + kFrameSinkVideoCaptureDeviceAleradyEndedOnFatalError: + return media::mojom::VideoCaptureError:: + kFrameSinkVideoCaptureDeviceAleradyEndedOnFatalError; + case media::VideoCaptureError:: + kFrameSinkVideoCaptureDeviceEncounteredFatalError: + return media::mojom::VideoCaptureError:: + kFrameSinkVideoCaptureDeviceEncounteredFatalError; + case media::VideoCaptureError::kV4L2FailedToOpenV4L2DeviceDriverFile: + return media::mojom::VideoCaptureError:: + kV4L2FailedToOpenV4L2DeviceDriverFile; + case media::VideoCaptureError::kV4L2ThisIsNotAV4L2VideoCaptureDevice: + return media::mojom::VideoCaptureError:: + kV4L2ThisIsNotAV4L2VideoCaptureDevice; + case media::VideoCaptureError::kV4L2FailedToFindASupportedCameraFormat: + return media::mojom::VideoCaptureError:: + kV4L2FailedToFindASupportedCameraFormat; + case media::VideoCaptureError::kV4L2FailedToSetVideoCaptureFormat: + return media::mojom::VideoCaptureError:: + kV4L2FailedToSetVideoCaptureFormat; + case media::VideoCaptureError::kV4L2UnsupportedPixelFormat: + return media::mojom::VideoCaptureError::kV4L2UnsupportedPixelFormat; + case media::VideoCaptureError::kV4L2FailedToSetCameraFramerate: + return media::mojom::VideoCaptureError::kV4L2FailedToSetCameraFramerate; + case media::VideoCaptureError::kV4L2ErrorRequestingMmapBuffers: + return media::mojom::VideoCaptureError::kV4L2ErrorRequestingMmapBuffers; + case media::VideoCaptureError::kV4L2AllocateBufferFailed: + return media::mojom::VideoCaptureError::kV4L2AllocateBufferFailed; + case media::VideoCaptureError::kV4L2VidiocStreamonFailed: + return media::mojom::VideoCaptureError::kV4L2VidiocStreamonFailed; + case media::VideoCaptureError::kV4L2VidiocStreamoffFailed: + return media::mojom::VideoCaptureError::kV4L2VidiocStreamoffFailed; + case media::VideoCaptureError::kV4L2FailedToVidiocReqbufsWithCount0: + return media::mojom::VideoCaptureError:: + kV4L2FailedToVidiocReqbufsWithCount0; + case media::VideoCaptureError::kV4L2PollFailed: + return media::mojom::VideoCaptureError::kV4L2PollFailed; + case media::VideoCaptureError:: + kV4L2MultipleContinuousTimeoutsWhileReadPolling: + return media::mojom::VideoCaptureError:: + kV4L2MultipleContinuousTimeoutsWhileReadPolling; + case media::VideoCaptureError::kV4L2FailedToDequeueCaptureBuffer: + return media::mojom::VideoCaptureError::kV4L2FailedToDequeueCaptureBuffer; + case media::VideoCaptureError::kV4L2FailedToEnqueueCaptureBuffer: + return media::mojom::VideoCaptureError::kV4L2FailedToEnqueueCaptureBuffer; + case media::VideoCaptureError:: + kSingleClientVideoCaptureHostLostConnectionToDevice: + return media::mojom::VideoCaptureError:: + kSingleClientVideoCaptureHostLostConnectionToDevice; + case media::VideoCaptureError::kSingleClientVideoCaptureDeviceLaunchAborted: + return media::mojom::VideoCaptureError:: + kSingleClientVideoCaptureDeviceLaunchAborted; + case media::VideoCaptureError:: + kDesktopCaptureDeviceWebrtcDesktopCapturerHasFailed: + return media::mojom::VideoCaptureError:: + kDesktopCaptureDeviceWebrtcDesktopCapturerHasFailed; + case media::VideoCaptureError::kFileVideoCaptureDeviceCouldNotOpenVideoFile: + return media::mojom::VideoCaptureError:: + kFileVideoCaptureDeviceCouldNotOpenVideoFile; + case media::VideoCaptureError:: + kDeviceCaptureLinuxFailedToCreateVideoCaptureDelegate: + return media::mojom::VideoCaptureError:: + kDeviceCaptureLinuxFailedToCreateVideoCaptureDelegate; + case media::VideoCaptureError:: + kErrorFakeDeviceIntentionallyEmittingErrorEvent: + return media::mojom::VideoCaptureError:: + kErrorFakeDeviceIntentionallyEmittingErrorEvent; + case media::VideoCaptureError::kDeviceClientTooManyFramesDroppedY16: + return media::mojom::VideoCaptureError:: + kDeviceClientTooManyFramesDroppedY16; + case media::VideoCaptureError:: + kDeviceMediaToMojoAdapterEncounteredUnsupportedBufferType: + return media::mojom::VideoCaptureError:: + kDeviceMediaToMojoAdapterEncounteredUnsupportedBufferType; + case media::VideoCaptureError:: + kVideoCaptureManagerProcessDeviceStartQueueDeviceInfoNotFound: + return media::mojom::VideoCaptureError:: + kVideoCaptureManagerProcessDeviceStartQueueDeviceInfoNotFound; + case media::VideoCaptureError:: + kInProcessDeviceLauncherFailedToCreateDeviceInstance: + return media::mojom::VideoCaptureError:: + kInProcessDeviceLauncherFailedToCreateDeviceInstance; + case media::VideoCaptureError:: + kServiceDeviceLauncherLostConnectionToDeviceFactoryDuringDeviceStart: + return media::mojom::VideoCaptureError:: + kServiceDeviceLauncherLostConnectionToDeviceFactoryDuringDeviceStart; + case media::VideoCaptureError:: + kServiceDeviceLauncherServiceRespondedWithDeviceNotFound: + return media::mojom::VideoCaptureError:: + kServiceDeviceLauncherServiceRespondedWithDeviceNotFound; + case media::VideoCaptureError:: + kServiceDeviceLauncherConnectionLostWhileWaitingForCallback: + return media::mojom::VideoCaptureError:: + kServiceDeviceLauncherConnectionLostWhileWaitingForCallback; + case media::VideoCaptureError::kIntentionalErrorRaisedByUnitTest: + return media::mojom::VideoCaptureError::kIntentionalErrorRaisedByUnitTest; + case media::VideoCaptureError::kCrosHalV3FailedToStartDeviceThread: + return media::mojom::VideoCaptureError:: + kCrosHalV3FailedToStartDeviceThread; + case media::VideoCaptureError::kCrosHalV3DeviceDelegateMojoConnectionError: + return media::mojom::VideoCaptureError:: + kCrosHalV3DeviceDelegateMojoConnectionError; + case media::VideoCaptureError:: + kCrosHalV3DeviceDelegateFailedToGetCameraInfo: + return media::mojom::VideoCaptureError:: + kCrosHalV3DeviceDelegateFailedToGetCameraInfo; + case media::VideoCaptureError:: + kCrosHalV3DeviceDelegateMissingSensorOrientationInfo: + return media::mojom::VideoCaptureError:: + kCrosHalV3DeviceDelegateMissingSensorOrientationInfo; + case media::VideoCaptureError:: + kCrosHalV3DeviceDelegateFailedToOpenCameraDevice: + return media::mojom::VideoCaptureError:: + kCrosHalV3DeviceDelegateFailedToOpenCameraDevice; + case media::VideoCaptureError:: + kCrosHalV3DeviceDelegateFailedToInitializeCameraDevice: + return media::mojom::VideoCaptureError:: + kCrosHalV3DeviceDelegateFailedToInitializeCameraDevice; + case media::VideoCaptureError:: + kCrosHalV3DeviceDelegateFailedToConfigureStreams: + return media::mojom::VideoCaptureError:: + kCrosHalV3DeviceDelegateFailedToConfigureStreams; + case media::VideoCaptureError:: + kCrosHalV3DeviceDelegateWrongNumberOfStreamsConfigured: + return media::mojom::VideoCaptureError:: + kCrosHalV3DeviceDelegateWrongNumberOfStreamsConfigured; + case media::VideoCaptureError:: + kCrosHalV3DeviceDelegateFailedToGetDefaultRequestSettings: + return media::mojom::VideoCaptureError:: + kCrosHalV3DeviceDelegateFailedToGetDefaultRequestSettings; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerHalRequestedTooManyBuffers: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerHalRequestedTooManyBuffers; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerFailedToCreateGpuMemoryBuffer: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerFailedToCreateGpuMemoryBuffer; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerFailedToMapGpuMemoryBuffer: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerFailedToMapGpuMemoryBuffer; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerUnsupportedVideoPixelFormat: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerUnsupportedVideoPixelFormat; + case media::VideoCaptureError::kCrosHalV3BufferManagerFailedToDupFd: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerFailedToDupFd; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerFailedToWrapGpuMemoryHandle: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerFailedToWrapGpuMemoryHandle; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerFailedToRegisterBuffer: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerFailedToRegisterBuffer; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerProcessCaptureRequestFailed: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerProcessCaptureRequestFailed; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerInvalidPendingResultId: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerInvalidPendingResultId; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerReceivedDuplicatedPartialMetadata: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerReceivedDuplicatedPartialMetadata; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerIncorrectNumberOfOutputBuffersReceived: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerIncorrectNumberOfOutputBuffersReceived; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerInvalidTypeOfOutputBuffersReceived: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerInvalidTypeOfOutputBuffersReceived; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerReceivedMultipleResultBuffersForFrame: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerReceivedMultipleResultBuffersForFrame; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerUnknownStreamInCamera3NotifyMsg: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerUnknownStreamInCamera3NotifyMsg; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerReceivedInvalidShutterTime: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerReceivedInvalidShutterTime; + case media::VideoCaptureError::kCrosHalV3BufferManagerFatalDeviceError: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerFatalDeviceError; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerReceivedFrameIsOutOfOrder: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerReceivedFrameIsOutOfOrder; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerFailedToUnwrapReleaseFenceFd: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerFailedToUnwrapReleaseFenceFd; + case media::VideoCaptureError:: + kCrosHalV3BufferManagerSyncWaitOnReleaseFenceTimedOut: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerSyncWaitOnReleaseFenceTimedOut; + case media::VideoCaptureError::kCrosHalV3BufferManagerInvalidJpegBlob: + return media::mojom::VideoCaptureError:: + kCrosHalV3BufferManagerInvalidJpegBlob; + case media::VideoCaptureError::kAndroidFailedToAllocate: + return media::mojom::VideoCaptureError::kAndroidFailedToAllocate; + case media::VideoCaptureError::kAndroidFailedToStartCapture: + return media::mojom::VideoCaptureError::kAndroidFailedToStartCapture; + case media::VideoCaptureError::kAndroidFailedToStopCapture: + return media::mojom::VideoCaptureError::kAndroidFailedToStopCapture; + case media::VideoCaptureError::kAndroidApi1CameraErrorCallbackReceived: + return media::mojom::VideoCaptureError:: + kAndroidApi1CameraErrorCallbackReceived; + case media::VideoCaptureError::kAndroidApi2CameraDeviceErrorReceived: + return media::mojom::VideoCaptureError:: + kAndroidApi2CameraDeviceErrorReceived; + case media::VideoCaptureError::kAndroidApi2CaptureSessionConfigureFailed: + return media::mojom::VideoCaptureError:: + kAndroidApi2CaptureSessionConfigureFailed; + case media::VideoCaptureError::kAndroidApi2ImageReaderUnexpectedImageFormat: + return media::mojom::VideoCaptureError:: + kAndroidApi2ImageReaderUnexpectedImageFormat; + case media::VideoCaptureError:: + kAndroidApi2ImageReaderSizeDidNotMatchImageSize: + return media::mojom::VideoCaptureError:: + kAndroidApi2ImageReaderSizeDidNotMatchImageSize; + case media::VideoCaptureError::kAndroidApi2ErrorRestartingPreview: + return media::mojom::VideoCaptureError:: + kAndroidApi2ErrorRestartingPreview; + case media::VideoCaptureError::kAndroidScreenCaptureUnsupportedFormat: + return media::mojom::VideoCaptureError:: + kAndroidScreenCaptureUnsupportedFormat; + case media::VideoCaptureError:: + kAndroidScreenCaptureFailedToStartCaptureMachine: + return media::mojom::VideoCaptureError:: + kAndroidScreenCaptureFailedToStartCaptureMachine; + case media::VideoCaptureError:: + kAndroidScreenCaptureTheUserDeniedScreenCapture: + return media::mojom::VideoCaptureError:: + kAndroidScreenCaptureTheUserDeniedScreenCapture; + case media::VideoCaptureError:: + kAndroidScreenCaptureFailedToStartScreenCapture: + return media::mojom::VideoCaptureError:: + kAndroidScreenCaptureFailedToStartScreenCapture; + case media::VideoCaptureError::kWinDirectShowCantGetCaptureFormatSettings: + return media::mojom::VideoCaptureError:: + kWinDirectShowCantGetCaptureFormatSettings; + case media::VideoCaptureError:: + kWinDirectShowFailedToGetNumberOfCapabilities: + return media::mojom::VideoCaptureError:: + kWinDirectShowFailedToGetNumberOfCapabilities; + case media::VideoCaptureError:: + kWinDirectShowFailedToGetCaptureDeviceCapabilities: + return media::mojom::VideoCaptureError:: + kWinDirectShowFailedToGetCaptureDeviceCapabilities; + case media::VideoCaptureError:: + kWinDirectShowFailedToSetCaptureDeviceOutputFormat: + return media::mojom::VideoCaptureError:: + kWinDirectShowFailedToSetCaptureDeviceOutputFormat; + case media::VideoCaptureError::kWinDirectShowFailedToConnectTheCaptureGraph: + return media::mojom::VideoCaptureError:: + kWinDirectShowFailedToConnectTheCaptureGraph; + case media::VideoCaptureError::kWinDirectShowFailedToPauseTheCaptureDevice: + return media::mojom::VideoCaptureError:: + kWinDirectShowFailedToPauseTheCaptureDevice; + case media::VideoCaptureError::kWinDirectShowFailedToStartTheCaptureDevice: + return media::mojom::VideoCaptureError:: + kWinDirectShowFailedToStartTheCaptureDevice; + case media::VideoCaptureError::kWinDirectShowFailedToStopTheCaptureGraph: + return media::mojom::VideoCaptureError:: + kWinDirectShowFailedToStopTheCaptureGraph; + case media::VideoCaptureError::kWinMediaFoundationEngineIsNull: + return media::mojom::VideoCaptureError::kWinMediaFoundationEngineIsNull; + case media::VideoCaptureError::kWinMediaFoundationEngineGetSourceFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationEngineGetSourceFailed; + case media::VideoCaptureError:: + kWinMediaFoundationFillPhotoCapabilitiesFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationFillPhotoCapabilitiesFailed; + case media::VideoCaptureError:: + kWinMediaFoundationFillVideoCapabilitiesFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationFillVideoCapabilitiesFailed; + case media::VideoCaptureError::kWinMediaFoundationNoVideoCapabilityFound: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationNoVideoCapabilityFound; + case media::VideoCaptureError:: + kWinMediaFoundationGetAvailableDeviceMediaTypeFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationGetAvailableDeviceMediaTypeFailed; + case media::VideoCaptureError:: + kWinMediaFoundationSetCurrentDeviceMediaTypeFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationSetCurrentDeviceMediaTypeFailed; + case media::VideoCaptureError::kWinMediaFoundationEngineGetSinkFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationEngineGetSinkFailed; + case media::VideoCaptureError:: + kWinMediaFoundationSinkQueryCapturePreviewInterfaceFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationSinkQueryCapturePreviewInterfaceFailed; + case media::VideoCaptureError:: + kWinMediaFoundationSinkRemoveAllStreamsFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationSinkRemoveAllStreamsFailed; + case media::VideoCaptureError:: + kWinMediaFoundationCreateSinkVideoMediaTypeFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationCreateSinkVideoMediaTypeFailed; + case media::VideoCaptureError:: + kWinMediaFoundationConvertToVideoSinkMediaTypeFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationConvertToVideoSinkMediaTypeFailed; + case media::VideoCaptureError::kWinMediaFoundationSinkAddStreamFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationSinkAddStreamFailed; + case media::VideoCaptureError:: + kWinMediaFoundationSinkSetSampleCallbackFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationSinkSetSampleCallbackFailed; + case media::VideoCaptureError::kWinMediaFoundationEngineStartPreviewFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationEngineStartPreviewFailed; + case media::VideoCaptureError::kWinMediaFoundationGetMediaEventStatusFailed: + return media::mojom::VideoCaptureError:: + kWinMediaFoundationGetMediaEventStatusFailed; + case media::VideoCaptureError::kMacSetCaptureDeviceFailed: + return media::mojom::VideoCaptureError::kMacSetCaptureDeviceFailed; + case media::VideoCaptureError::kMacCouldNotStartCaptureDevice: + return media::mojom::VideoCaptureError::kMacCouldNotStartCaptureDevice; + case media::VideoCaptureError::kMacReceivedFrameWithUnexpectedResolution: + return media::mojom::VideoCaptureError:: + kMacReceivedFrameWithUnexpectedResolution; + case media::VideoCaptureError::kMacUpdateCaptureResolutionFailed: + return media::mojom::VideoCaptureError::kMacUpdateCaptureResolutionFailed; + case media::VideoCaptureError::kMacDeckLinkDeviceIdNotFoundInTheSystem: + return media::mojom::VideoCaptureError:: + kMacDeckLinkDeviceIdNotFoundInTheSystem; + case media::VideoCaptureError::kMacDeckLinkErrorQueryingInputInterface: + return media::mojom::VideoCaptureError:: + kMacDeckLinkErrorQueryingInputInterface; + case media::VideoCaptureError::kMacDeckLinkErrorCreatingDisplayModeIterator: + return media::mojom::VideoCaptureError:: + kMacDeckLinkErrorCreatingDisplayModeIterator; + case media::VideoCaptureError::kMacDeckLinkCouldNotFindADisplayMode: + return media::mojom::VideoCaptureError:: + kMacDeckLinkCouldNotFindADisplayMode; + case media::VideoCaptureError:: + kMacDeckLinkCouldNotSelectTheVideoFormatWeLike: + return media::mojom::VideoCaptureError:: + kMacDeckLinkCouldNotSelectTheVideoFormatWeLike; + case media::VideoCaptureError::kMacDeckLinkCouldNotStartCapturing: + return media::mojom::VideoCaptureError:: + kMacDeckLinkCouldNotStartCapturing; + case media::VideoCaptureError::kMacDeckLinkUnsupportedPixelFormat: + return media::mojom::VideoCaptureError:: + kMacDeckLinkUnsupportedPixelFormat; + case media::VideoCaptureError:: + kMacAvFoundationReceivedAVCaptureSessionRuntimeErrorNotification: + return media::mojom::VideoCaptureError:: + kMacAvFoundationReceivedAVCaptureSessionRuntimeErrorNotification; + case media::VideoCaptureError::kAndroidApi2ErrorConfiguringCamera: + return media::mojom::VideoCaptureError:: + kAndroidApi2ErrorConfiguringCamera; + } + NOTREACHED(); + return media::mojom::VideoCaptureError::kNone; +} +","@@ -658,9 +658,6 @@ EnumTraits::ToMojom( + case media::VideoCaptureError::kAndroidApi2ErrorConfiguringCamera: + return media::mojom::VideoCaptureError:: + kAndroidApi2ErrorConfiguringCamera; +- case media::VideoCaptureError::kCrosHalV3DeviceDelegateFailedToFlush: +- return media::mojom::VideoCaptureError:: +- kCrosHalV3DeviceDelegateFailedToFlush; + } + NOTREACHED(); + return media::mojom::VideoCaptureError::kNone; +@@ -1179,9 +1176,6 @@ bool EnumTraits:: + case media::mojom::VideoCaptureError::kAndroidApi2ErrorConfiguringCamera: + *output = media::VideoCaptureError::kAndroidApi2ErrorConfiguringCamera; + return true; +- case media::mojom::VideoCaptureError::kCrosHalV3DeviceDelegateFailedToFlush: +- *output = media::VideoCaptureError::kCrosHalV3DeviceDelegateFailedToFlush; +- return true; + } + NOTREACHED(); + return false;",4886,5217,6144 +18164,"static Image *ReadICONImage(const ImageInfo *image_info, + ExceptionInfo *exception) +{ + IconFile + icon_file; + + IconInfo + icon_info; + + Image + *image; + + MagickBooleanType + status; + + register IndexPacket + *indexes; + + register ssize_t + i, + x; + + register PixelPacket + *q; + + register unsigned char + *p; + + size_t + bit, + byte, + bytes_per_line, + one, + scanline_pad; + + ssize_t + count, + offset, + y; + + /* + Open image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickSignature); + (void) LogMagickEvent(CoderEvent,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); + } + icon_file.reserved=(short) ReadBlobLSBShort(image); + icon_file.resource_type=(short) ReadBlobLSBShort(image); + icon_file.count=(short) ReadBlobLSBShort(image); + if ((icon_file.reserved != 0) || + ((icon_file.resource_type != 1) && (icon_file.resource_type != 2)) || + (icon_file.count > MaxIcons)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + for (i=0; i < icon_file.count; i++) + { + icon_file.directory[i].width=(unsigned char) ReadBlobByte(image); + icon_file.directory[i].height=(unsigned char) ReadBlobByte(image); + icon_file.directory[i].colors=(unsigned char) ReadBlobByte(image); + icon_file.directory[i].reserved=(unsigned char) ReadBlobByte(image); + icon_file.directory[i].planes=(unsigned short) ReadBlobLSBShort(image); + icon_file.directory[i].bits_per_pixel=(unsigned short) + ReadBlobLSBShort(image); + icon_file.directory[i].size=ReadBlobLSBLong(image); + icon_file.directory[i].offset=ReadBlobLSBLong(image); + } + one=1; + for (i=0; i < icon_file.count; i++) + { + /* + Verify Icon identifier. + */ + offset=(ssize_t) SeekBlob(image,(MagickOffsetType) + icon_file.directory[i].offset,SEEK_SET); + if (offset < 0) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + icon_info.size=ReadBlobLSBLong(image); + icon_info.width=(unsigned char) ((int) ReadBlobLSBLong(image)); + icon_info.height=(unsigned char) ((int) ReadBlobLSBLong(image)/2); + icon_info.planes=ReadBlobLSBShort(image); + icon_info.bits_per_pixel=ReadBlobLSBShort(image); + if (((icon_info.planes == 18505) && (icon_info.bits_per_pixel == 21060)) || + (icon_info.size == 0x474e5089)) + { + Image + *icon_image; + + ImageInfo + *read_info; + + size_t + length; + + unsigned char + *png; + + /* + Icon image encoded as a compressed PNG image. + */ + length=icon_file.directory[i].size; + png=(unsigned char *) AcquireQuantumMemory(length+16,sizeof(*png)); + if (png == (unsigned char *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + (void) CopyMagickMemory(png,""\211PNG\r\n\032\n\000\000\000\015"",12); + png[12]=(unsigned char) icon_info.planes; + png[13]=(unsigned char) (icon_info.planes >> 8); + png[14]=(unsigned char) icon_info.bits_per_pixel; + png[15]=(unsigned char) (icon_info.bits_per_pixel >> 8); + count=ReadBlob(image,length-16,png+16); + icon_image=(Image *) NULL; + if (count > 0) + { + read_info=CloneImageInfo(image_info); + (void) CopyMagickString(read_info->magick,""PNG"",MaxTextExtent); + icon_image=BlobToImage(read_info,png,length+16,exception); + read_info=DestroyImageInfo(read_info); + } + png=(unsigned char *) RelinquishMagickMemory(png); + if (icon_image == (Image *) NULL) + { + if (count != (ssize_t) (length-16)) + ThrowReaderException(CorruptImageError, + ""InsufficientImageDataInFile""); + image=DestroyImageList(image); + return((Image *) NULL); + } + DestroyBlob(icon_image); + icon_image->blob=ReferenceBlob(image->blob); + ReplaceImageInList(&image,icon_image); + icon_image->scene=i; + } + else + { + if (icon_info.bits_per_pixel > 32) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + icon_info.compression=ReadBlobLSBLong(image); + icon_info.image_size=ReadBlobLSBLong(image); + icon_info.x_pixels=ReadBlobLSBLong(image); + icon_info.y_pixels=ReadBlobLSBLong(image); + icon_info.number_colors=ReadBlobLSBLong(image); + icon_info.colors_important=ReadBlobLSBLong(image); + image->matte=MagickTrue; + image->columns=(size_t) icon_file.directory[i].width; + if ((ssize_t) image->columns > icon_info.width) + image->columns=(size_t) icon_info.width; + if (image->columns == 0) + image->columns=256; + image->rows=(size_t) icon_file.directory[i].height; + if ((ssize_t) image->rows > icon_info.height) + image->rows=(size_t) icon_info.height; + if (image->rows == 0) + image->rows=256; + image->depth=icon_info.bits_per_pixel; + if (image->debug != MagickFalse) + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" scene = %.20g"",(double) i); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" size = %.20g"",(double) icon_info.size); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" width = %.20g"",(double) icon_file.directory[i].width); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" height = %.20g"",(double) icon_file.directory[i].height); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" colors = %.20g"",(double ) icon_info.number_colors); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" planes = %.20g"",(double) icon_info.planes); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" bpp = %.20g"",(double) icon_info.bits_per_pixel); + } + if ((icon_info.number_colors != 0) || (icon_info.bits_per_pixel <= 16U)) + { + image->storage_class=PseudoClass; + image->colors=icon_info.number_colors; + if (image->colors == 0) + image->colors=one << icon_info.bits_per_pixel; + } + if (image->storage_class == PseudoClass) + { + register ssize_t + i; + + unsigned char + *icon_colormap; + + /* + Read Icon raster colormap. + */ + if (AcquireImageColormap(image,image->colors) == MagickFalse) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + icon_colormap=(unsigned char *) AcquireQuantumMemory((size_t) + image->colors,4UL*sizeof(*icon_colormap)); + if (icon_colormap == (unsigned char *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + count=ReadBlob(image,(size_t) (4*image->colors),icon_colormap); + if (count != (ssize_t) (4*image->colors)) + ThrowReaderException(CorruptImageError, + ""InsufficientImageDataInFile""); + p=icon_colormap; + for (i=0; i < (ssize_t) image->colors; i++) + { + image->colormap[i].blue=(Quantum) ScaleCharToQuantum(*p++); + image->colormap[i].green=(Quantum) ScaleCharToQuantum(*p++); + image->colormap[i].red=(Quantum) ScaleCharToQuantum(*p++); + p++; + } + icon_colormap=(unsigned char *) RelinquishMagickMemory(icon_colormap); + } + /* + Convert Icon raster image to pixel packets. + */ + if ((image_info->ping != MagickFalse) && + (image_info->number_scenes != 0)) + if (image->scene >= (image_info->scene+image_info->number_scenes-1)) + break; + bytes_per_line=(((image->columns*icon_info.bits_per_pixel)+31) & + ~31) >> 3; + (void) bytes_per_line; + scanline_pad=((((image->columns*icon_info.bits_per_pixel)+31) & ~31)- + (image->columns*icon_info.bits_per_pixel)) >> 3; + switch (icon_info.bits_per_pixel) + { + case 1: + { + /* + Convert bitmap scanline. + */ + for (y=(ssize_t) image->rows-1; y >= 0; 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-7); x+=8) + { + byte=(size_t) ReadBlobByte(image); + for (bit=0; bit < 8; bit++) + SetPixelIndex(indexes+x+bit,((byte & (0x80 >> bit)) != 0 ? + 0x01 : 0x00)); + } + if ((image->columns % 8) != 0) + { + byte=(size_t) ReadBlobByte(image); + for (bit=0; bit < (image->columns % 8); bit++) + SetPixelIndex(indexes+x+bit,((byte & (0x80 >> bit)) != 0 ? + 0x01 : 0x00)); + } + for (x=0; x < (ssize_t) scanline_pad; x++) + (void) ReadBlobByte(image); + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,LoadImageTag,image->rows-y-1, + image->rows); + if (status == MagickFalse) + break; + } + } + break; + } + case 4: + { + /* + Read 4-bit Icon scanline. + */ + for (y=(ssize_t) image->rows-1; y >= 0; 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-1); x+=2) + { + byte=(size_t) ReadBlobByte(image); + SetPixelIndex(indexes+x,((byte >> 4) & 0xf)); + SetPixelIndex(indexes+x+1,((byte) & 0xf)); + } + if ((image->columns % 2) != 0) + { + byte=(size_t) ReadBlobByte(image); + SetPixelIndex(indexes+x,((byte >> 4) & 0xf)); + } + for (x=0; x < (ssize_t) scanline_pad; x++) + (void) ReadBlobByte(image); + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,LoadImageTag,image->rows-y-1, + image->rows); + if (status == MagickFalse) + break; + } + } + break; + } + case 8: + { + /* + Convert PseudoColor scanline. + */ + for (y=(ssize_t) image->rows-1; y >= 0; 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++) + { + byte=(size_t) ReadBlobByte(image); + SetPixelIndex(indexes+x,byte); + } + for (x=0; x < (ssize_t) scanline_pad; x++) + (void) ReadBlobByte(image); + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,LoadImageTag,image->rows-y-1, + image->rows); + if (status == MagickFalse) + break; + } + } + break; + } + case 16: + { + /* + Convert PseudoColor scanline. + */ + for (y=(ssize_t) image->rows-1; y >= 0; 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++) + { + byte=(size_t) ReadBlobByte(image); + byte|=(size_t) (ReadBlobByte(image) << 8); + SetPixelIndex(indexes+x,byte); + } + for (x=0; x < (ssize_t) scanline_pad; x++) + (void) ReadBlobByte(image); + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,LoadImageTag,image->rows-y-1, + image->rows); + if (status == MagickFalse) + break; + } + } + break; + } + case 24: + case 32: + { + /* + Convert DirectColor scanline. + */ + for (y=(ssize_t) image->rows-1; y >= 0; y--) + { + q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); + if (q == (PixelPacket *) NULL) + break; + for (x=0; x < (ssize_t) image->columns; x++) + { + SetPixelBlue(q,ScaleCharToQuantum((unsigned char) + ReadBlobByte(image))); + SetPixelGreen(q,ScaleCharToQuantum((unsigned char) + ReadBlobByte(image))); + SetPixelRed(q,ScaleCharToQuantum((unsigned char) + ReadBlobByte(image))); + if (icon_info.bits_per_pixel == 32) + SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) + ReadBlobByte(image))); + q++; + } + if (icon_info.bits_per_pixel == 24) + for (x=0; x < (ssize_t) scanline_pad; x++) + (void) ReadBlobByte(image); + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,LoadImageTag,image->rows-y-1, + image->rows); + if (status == MagickFalse) + break; + } + } + break; + } + default: + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + } + if (image_info->ping == MagickFalse) + (void) SyncImage(image); + if (icon_info.bits_per_pixel != 32) + { + /* + Read the ICON alpha mask. + */ + image->storage_class=DirectClass; + for (y=(ssize_t) image->rows-1; y >= 0; y--) + { + q=GetAuthenticPixels(image,0,y,image->columns,1,exception); + if (q == (PixelPacket *) NULL) + break; + for (x=0; x < ((ssize_t) image->columns-7); x+=8) + { + byte=(size_t) ReadBlobByte(image); + for (bit=0; bit < 8; bit++) + SetPixelOpacity(q+x+bit,(((byte & (0x80 >> bit)) != 0) ? + TransparentOpacity : OpaqueOpacity)); + } + if ((image->columns % 8) != 0) + { + byte=(size_t) ReadBlobByte(image); + for (bit=0; bit < (image->columns % 8); bit++) + SetPixelOpacity(q+x+bit,(((byte & (0x80 >> bit)) != 0) ? + TransparentOpacity : OpaqueOpacity)); + } + if ((image->columns % 32) != 0) + for (x=0; x < (ssize_t) ((32-(image->columns % 32))/8); x++) + (void) ReadBlobByte(image); + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + } + } + 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 (i < (ssize_t) (icon_file.count-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; + } + } + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +",1,"static Image *ReadICONImage(const ImageInfo *image_info, + ExceptionInfo *exception) +{ + IconFile + icon_file; + + IconInfo + icon_info; + + Image + *image; + + MagickBooleanType + status; + + register IndexPacket + *indexes; + + register ssize_t + i, + x; + + register PixelPacket + *q; + + register unsigned char + *p; + + size_t + bit, + byte, + bytes_per_line, + one, + scanline_pad; + + ssize_t + count, + offset, + y; + + /* + Open image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickSignature); + (void) LogMagickEvent(CoderEvent,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); + } + icon_file.reserved=(short) ReadBlobLSBShort(image); + icon_file.resource_type=(short) ReadBlobLSBShort(image); + icon_file.count=(short) ReadBlobLSBShort(image); + if ((icon_file.reserved != 0) || + ((icon_file.resource_type != 1) && (icon_file.resource_type != 2)) || + (icon_file.count > MaxIcons)) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + for (i=0; i < icon_file.count; i++) + { + icon_file.directory[i].width=(unsigned char) ReadBlobByte(image); + icon_file.directory[i].height=(unsigned char) ReadBlobByte(image); + icon_file.directory[i].colors=(unsigned char) ReadBlobByte(image); + icon_file.directory[i].reserved=(unsigned char) ReadBlobByte(image); + icon_file.directory[i].planes=(unsigned short) ReadBlobLSBShort(image); + icon_file.directory[i].bits_per_pixel=(unsigned short) + ReadBlobLSBShort(image); + icon_file.directory[i].size=ReadBlobLSBLong(image); + icon_file.directory[i].offset=ReadBlobLSBLong(image); + } + one=1; + for (i=0; i < icon_file.count; i++) + { + /* + Verify Icon identifier. + */ + offset=(ssize_t) SeekBlob(image,(MagickOffsetType) + icon_file.directory[i].offset,SEEK_SET); + if (offset < 0) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + icon_info.size=ReadBlobLSBLong(image); + icon_info.width=(unsigned char) ((int) ReadBlobLSBLong(image)); + icon_info.height=(unsigned char) ((int) ReadBlobLSBLong(image)/2); + icon_info.planes=ReadBlobLSBShort(image); + icon_info.bits_per_pixel=ReadBlobLSBShort(image); + if (((icon_info.planes == 18505) && (icon_info.bits_per_pixel == 21060)) || + (icon_info.size == 0x474e5089)) + { + Image + *icon_image; + + ImageInfo + *read_info; + + size_t + length; + + unsigned char + *png; + + /* + Icon image encoded as a compressed PNG image. + */ + length=icon_file.directory[i].size; + png=(unsigned char *) AcquireQuantumMemory(length+16,sizeof(*png)); + if (png == (unsigned char *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + (void) CopyMagickMemory(png,""\211PNG\r\n\032\n\000\000\000\015"",12); + png[12]=(unsigned char) icon_info.planes; + png[13]=(unsigned char) (icon_info.planes >> 8); + png[14]=(unsigned char) icon_info.bits_per_pixel; + png[15]=(unsigned char) (icon_info.bits_per_pixel >> 8); + count=ReadBlob(image,length-16,png+16); + icon_image=(Image *) NULL; + if (count > 0) + { + read_info=CloneImageInfo(image_info); + (void) CopyMagickString(read_info->magick,""PNG"",MaxTextExtent); + icon_image=BlobToImage(read_info,png,length+16,exception); + read_info=DestroyImageInfo(read_info); + } + png=(unsigned char *) RelinquishMagickMemory(png); + if (icon_image == (Image *) NULL) + { + if (count != (ssize_t) (length-16)) + ThrowReaderException(CorruptImageError, + ""InsufficientImageDataInFile""); + image=DestroyImageList(image); + return((Image *) NULL); + } + DestroyBlob(icon_image); + icon_image->blob=ReferenceBlob(image->blob); + ReplaceImageInList(&image,icon_image); + icon_image->scene=i; + } + else + { + if (icon_info.bits_per_pixel > 32) + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + icon_info.compression=ReadBlobLSBLong(image); + icon_info.image_size=ReadBlobLSBLong(image); + icon_info.x_pixels=ReadBlobLSBLong(image); + icon_info.y_pixels=ReadBlobLSBLong(image); + icon_info.number_colors=ReadBlobLSBLong(image); + icon_info.colors_important=ReadBlobLSBLong(image); + image->matte=MagickTrue; + image->columns=(size_t) icon_file.directory[i].width; + if ((ssize_t) image->columns > icon_info.width) + image->columns=(size_t) icon_info.width; + if (image->columns == 0) + image->columns=256; + image->rows=(size_t) icon_file.directory[i].height; + if ((ssize_t) image->rows > icon_info.height) + image->rows=(size_t) icon_info.height; + if (image->rows == 0) + image->rows=256; + image->depth=icon_info.bits_per_pixel; + if (image->debug != MagickFalse) + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" scene = %.20g"",(double) i); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" size = %.20g"",(double) icon_info.size); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" width = %.20g"",(double) icon_file.directory[i].width); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" height = %.20g"",(double) icon_file.directory[i].height); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" colors = %.20g"",(double ) icon_info.number_colors); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" planes = %.20g"",(double) icon_info.planes); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" bpp = %.20g"",(double) icon_info.bits_per_pixel); + } + if ((icon_info.number_colors != 0) || (icon_info.bits_per_pixel <= 16U)) + { + image->storage_class=PseudoClass; + image->colors=icon_info.number_colors; + if (image->colors == 0) + image->colors=one << icon_info.bits_per_pixel; + } + if (image->storage_class == PseudoClass) + { + register ssize_t + i; + + unsigned char + *icon_colormap; + + /* + Read Icon raster colormap. + */ + if (AcquireImageColormap(image,image->colors) == MagickFalse) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + icon_colormap=(unsigned char *) AcquireQuantumMemory((size_t) + image->colors,4UL*sizeof(*icon_colormap)); + if (icon_colormap == (unsigned char *) NULL) + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + count=ReadBlob(image,(size_t) (4*image->colors),icon_colormap); + if (count != (ssize_t) (4*image->colors)) + ThrowReaderException(CorruptImageError, + ""InsufficientImageDataInFile""); + p=icon_colormap; + for (i=0; i < (ssize_t) image->colors; i++) + { + image->colormap[i].blue=(Quantum) ScaleCharToQuantum(*p++); + image->colormap[i].green=(Quantum) ScaleCharToQuantum(*p++); + image->colormap[i].red=(Quantum) ScaleCharToQuantum(*p++); + p++; + } + icon_colormap=(unsigned char *) RelinquishMagickMemory(icon_colormap); + } + /* + Convert Icon raster image to pixel packets. + */ + 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)); + } + bytes_per_line=(((image->columns*icon_info.bits_per_pixel)+31) & + ~31) >> 3; + (void) bytes_per_line; + scanline_pad=((((image->columns*icon_info.bits_per_pixel)+31) & ~31)- + (image->columns*icon_info.bits_per_pixel)) >> 3; + switch (icon_info.bits_per_pixel) + { + case 1: + { + /* + Convert bitmap scanline. + */ + for (y=(ssize_t) image->rows-1; y >= 0; 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-7); x+=8) + { + byte=(size_t) ReadBlobByte(image); + for (bit=0; bit < 8; bit++) + SetPixelIndex(indexes+x+bit,((byte & (0x80 >> bit)) != 0 ? + 0x01 : 0x00)); + } + if ((image->columns % 8) != 0) + { + byte=(size_t) ReadBlobByte(image); + for (bit=0; bit < (image->columns % 8); bit++) + SetPixelIndex(indexes+x+bit,((byte & (0x80 >> bit)) != 0 ? + 0x01 : 0x00)); + } + for (x=0; x < (ssize_t) scanline_pad; x++) + (void) ReadBlobByte(image); + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,LoadImageTag,image->rows-y-1, + image->rows); + if (status == MagickFalse) + break; + } + } + break; + } + case 4: + { + /* + Read 4-bit Icon scanline. + */ + for (y=(ssize_t) image->rows-1; y >= 0; 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-1); x+=2) + { + byte=(size_t) ReadBlobByte(image); + SetPixelIndex(indexes+x,((byte >> 4) & 0xf)); + SetPixelIndex(indexes+x+1,((byte) & 0xf)); + } + if ((image->columns % 2) != 0) + { + byte=(size_t) ReadBlobByte(image); + SetPixelIndex(indexes+x,((byte >> 4) & 0xf)); + } + for (x=0; x < (ssize_t) scanline_pad; x++) + (void) ReadBlobByte(image); + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,LoadImageTag,image->rows-y-1, + image->rows); + if (status == MagickFalse) + break; + } + } + break; + } + case 8: + { + /* + Convert PseudoColor scanline. + */ + for (y=(ssize_t) image->rows-1; y >= 0; 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++) + { + byte=(size_t) ReadBlobByte(image); + SetPixelIndex(indexes+x,byte); + } + for (x=0; x < (ssize_t) scanline_pad; x++) + (void) ReadBlobByte(image); + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,LoadImageTag,image->rows-y-1, + image->rows); + if (status == MagickFalse) + break; + } + } + break; + } + case 16: + { + /* + Convert PseudoColor scanline. + */ + for (y=(ssize_t) image->rows-1; y >= 0; 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++) + { + byte=(size_t) ReadBlobByte(image); + byte|=(size_t) (ReadBlobByte(image) << 8); + SetPixelIndex(indexes+x,byte); + } + for (x=0; x < (ssize_t) scanline_pad; x++) + (void) ReadBlobByte(image); + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,LoadImageTag,image->rows-y-1, + image->rows); + if (status == MagickFalse) + break; + } + } + break; + } + case 24: + case 32: + { + /* + Convert DirectColor scanline. + */ + for (y=(ssize_t) image->rows-1; y >= 0; y--) + { + q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); + if (q == (PixelPacket *) NULL) + break; + for (x=0; x < (ssize_t) image->columns; x++) + { + SetPixelBlue(q,ScaleCharToQuantum((unsigned char) + ReadBlobByte(image))); + SetPixelGreen(q,ScaleCharToQuantum((unsigned char) + ReadBlobByte(image))); + SetPixelRed(q,ScaleCharToQuantum((unsigned char) + ReadBlobByte(image))); + if (icon_info.bits_per_pixel == 32) + SetPixelAlpha(q,ScaleCharToQuantum((unsigned char) + ReadBlobByte(image))); + q++; + } + if (icon_info.bits_per_pixel == 24) + for (x=0; x < (ssize_t) scanline_pad; x++) + (void) ReadBlobByte(image); + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + if (image->previous == (Image *) NULL) + { + status=SetImageProgress(image,LoadImageTag,image->rows-y-1, + image->rows); + if (status == MagickFalse) + break; + } + } + break; + } + default: + ThrowReaderException(CorruptImageError,""ImproperImageHeader""); + } + if (image_info->ping == MagickFalse) + (void) SyncImage(image); + if (icon_info.bits_per_pixel != 32) + { + /* + Read the ICON alpha mask. + */ + image->storage_class=DirectClass; + for (y=(ssize_t) image->rows-1; y >= 0; y--) + { + q=GetAuthenticPixels(image,0,y,image->columns,1,exception); + if (q == (PixelPacket *) NULL) + break; + for (x=0; x < ((ssize_t) image->columns-7); x+=8) + { + byte=(size_t) ReadBlobByte(image); + for (bit=0; bit < 8; bit++) + SetPixelOpacity(q+x+bit,(((byte & (0x80 >> bit)) != 0) ? + TransparentOpacity : OpaqueOpacity)); + } + if ((image->columns % 8) != 0) + { + byte=(size_t) ReadBlobByte(image); + for (bit=0; bit < (image->columns % 8); bit++) + SetPixelOpacity(q+x+bit,(((byte & (0x80 >> bit)) != 0) ? + TransparentOpacity : OpaqueOpacity)); + } + if ((image->columns % 32) != 0) + for (x=0; x < (ssize_t) ((32-(image->columns % 32))/8); x++) + (void) ReadBlobByte(image); + if (SyncAuthenticPixels(image,exception) == MagickFalse) + break; + } + } + 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 (i < (ssize_t) (icon_file.count-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; + } + } + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +","@@ -462,6 +462,12 @@ static Image *ReadICONImage(const ImageInfo *image_info, + (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)); ++ } + bytes_per_line=(((image->columns*icon_info.bits_per_pixel)+31) & + ~31) >> 3; + (void) bytes_per_line;",4229,4560,6144 diff --git a/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_4096_to_6144.pkl b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_4096_to_6144.pkl new file mode 100644 index 0000000000000000000000000000000000000000..1d57a59190eadfdd20755432e8147014fe38f886 --- /dev/null +++ b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_4096_to_6144.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:348af8c01875a1931b0cf1bc266e245456162a59195e3d698b7e39b94a25860b +size 1526394 diff --git a/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_512_to_1024.csv b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_512_to_1024.csv new file mode 100644 index 0000000000000000000000000000000000000000..b55e8546a40272846006c1c1d679c54d10692af8 --- /dev/null +++ b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_512_to_1024.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fd89ce17f62175ed404063045ecd4e45387339c69ebe8ac01a0b873fa148ff54 +size 15658900 diff --git a/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_512_to_1024.pkl b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_512_to_1024.pkl new file mode 100644 index 0000000000000000000000000000000000000000..9782207a0df69c66fbf61228fa720526e03630cf --- /dev/null +++ b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_512_to_1024.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:07f65a3d5015fad0b9483cf6ee507cd9300f88a6816482a60366399d1b697250 +size 10480878 diff --git a/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_6144_to_8192.csv b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_6144_to_8192.csv new file mode 100644 index 0000000000000000000000000000000000000000..ec5dd22d9948b24a56d975e78e8eda7939eb441f --- /dev/null +++ b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_6144_to_8192.csv @@ -0,0 +1,15503 @@ +idx,func_before,vul,func_after,patch,code_token_length,total_token_length,max_tokens_setting +18733,"WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op) +{ + /* ! */ + + dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle); + + WORD32 i4_err_status = 0; + UWORD8 *pu1_buf = NULL; + WORD32 buflen; + UWORD32 u4_max_ofst, u4_length_of_start_code = 0; + + UWORD32 bytes_consumed = 0; + UWORD32 cur_slice_is_nonref = 0; + UWORD32 u4_next_is_aud; + UWORD32 u4_first_start_code_found = 0; + WORD32 ret = 0,api_ret_value = IV_SUCCESS; + WORD32 header_data_left = 0,frame_data_left = 0; + UWORD8 *pu1_bitstrm_buf; + ivd_video_decode_ip_t *ps_dec_ip; + ivd_video_decode_op_t *ps_dec_op; + + ithread_set_name((void*)""Parse_thread""); + + ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip; + ps_dec_op = (ivd_video_decode_op_t *)pv_api_op; + + { + UWORD32 u4_size; + u4_size = ps_dec_op->u4_size; + memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t)); + ps_dec_op->u4_size = u4_size; + } + + ps_dec->pv_dec_out = ps_dec_op; + if(ps_dec->init_done != 1) + { + return IV_FAIL; + } + + /*Data memory barries instruction,so that bitstream write by the application is complete*/ + DATA_SYNC(); + + if(0 == ps_dec->u1_flushfrm) + { + if(ps_dec_ip->pv_stream_buffer == NULL) + { + ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; + ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL; + return IV_FAIL; + } + if(ps_dec_ip->u4_num_Bytes <= 0) + { + ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; + ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV; + return IV_FAIL; + + } + } + ps_dec->u1_pic_decode_done = 0; + + ps_dec_op->u4_num_bytes_consumed = 0; + + ps_dec->ps_out_buffer = NULL; + + if(ps_dec_ip->u4_size + >= offsetof(ivd_video_decode_ip_t, s_out_buffer)) + ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer; + + ps_dec->u4_fmt_conv_cur_row = 0; + + ps_dec->u4_output_present = 0; + ps_dec->s_disp_op.u4_error_code = 1; + ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS; + if(0 == ps_dec->u4_share_disp_buf + && ps_dec->i4_decode_header == 0) + { + UWORD32 i; + if(ps_dec->ps_out_buffer->u4_num_bufs == 0) + { + ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; + ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS; + return IV_FAIL; + } + + for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++) + { + if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL) + { + ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; + ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL; + return IV_FAIL; + } + + if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0) + { + ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; + ps_dec_op->u4_error_code |= + IVD_DISP_FRM_ZERO_OP_BUF_SIZE; + return IV_FAIL; + } + } + } + + if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT) + { + ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER; + return IV_FAIL; + } + + /* ! */ + ps_dec->u4_ts = ps_dec_ip->u4_ts; + + ps_dec_op->u4_error_code = 0; + ps_dec_op->e_pic_type = -1; + ps_dec_op->u4_output_present = 0; + ps_dec_op->u4_frame_decoded_flag = 0; + + ps_dec->i4_frametype = -1; + ps_dec->i4_content_type = -1; + /* + * For field pictures, set the bottom and top picture decoded u4_flag correctly. + */ + { + if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded) + { + ps_dec->u1_top_bottom_decoded = 0; + } + } + ps_dec->u4_slice_start_code_found = 0; + + /* In case the deocder is not in flush mode(in shared mode), + then decoder has to pick up a buffer to write current frame. + Check if a frame is available in such cases */ + + if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1 + && ps_dec->u1_flushfrm == 0) + { + UWORD32 i; + + WORD32 disp_avail = 0, free_id; + + /* Check if at least one buffer is available with the codec */ + /* If not then return to application with error */ + for(i = 0; i < ps_dec->u1_pic_bufs; i++) + { + if(0 == ps_dec->u4_disp_buf_mapping[i] + || 1 == ps_dec->u4_disp_buf_to_be_freed[i]) + { + disp_avail = 1; + break; + } + + } + + if(0 == disp_avail) + { + /* If something is queued for display wait for that buffer to be returned */ + + ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; + ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); + return (IV_FAIL); + } + + while(1) + { + pic_buffer_t *ps_pic_buf; + ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free( + (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id); + + if(ps_pic_buf == NULL) + { + UWORD32 i, display_queued = 0; + + /* check if any buffer was given for display which is not returned yet */ + for(i = 0; i < (MAX_DISP_BUFS_NEW); i++) + { + if(0 != ps_dec->u4_disp_buf_mapping[i]) + { + display_queued = 1; + break; + } + } + /* If some buffer is queued for display, then codec has to singal an error and wait + for that buffer to be returned. + If nothing is queued for display then codec has ownership of all display buffers + and it can reuse any of the existing buffers and continue decoding */ + + if(1 == display_queued) + { + /* If something is queued for display wait for that buffer to be returned */ + ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; + ps_dec_op->u4_error_code |= (1 + << IVD_UNSUPPORTEDPARAM); + return (IV_FAIL); + } + } + else + { + /* If the buffer is with display, then mark it as in use and then look for a buffer again */ + if(1 == ps_dec->u4_disp_buf_mapping[free_id]) + { + ih264_buf_mgr_set_status( + (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, + free_id, + BUF_MGR_IO); + } + else + { + /** + * Found a free buffer for present call. Release it now. + * Will be again obtained later. + */ + ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, + free_id, + BUF_MGR_IO); + break; + } + } + } + + } + + if(ps_dec->u1_flushfrm && ps_dec->u1_init_dec_flag) + { + + ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, + &(ps_dec->s_disp_op)); + if(0 == ps_dec->s_disp_op.u4_error_code) + { + ps_dec->u4_fmt_conv_cur_row = 0; + ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht; + ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), + ps_dec->u4_fmt_conv_cur_row, + ps_dec->u4_fmt_conv_num_rows); + ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; + ps_dec->u4_output_present = 1; + + } + ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); + + ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; + ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; + + ps_dec_op->u4_new_seq = 0; + + ps_dec_op->u4_output_present = ps_dec->u4_output_present; + ps_dec_op->u4_progressive_frame_flag = + ps_dec->s_disp_op.u4_progressive_frame_flag; + ps_dec_op->e_output_format = + ps_dec->s_disp_op.e_output_format; + ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf; + ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type; + ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts; + ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id; + + /*In the case of flush ,since no frame is decoded set pic type as invalid*/ + ps_dec_op->u4_is_ref_flag = -1; + ps_dec_op->e_pic_type = IV_NA_FRAME; + ps_dec_op->u4_frame_decoded_flag = 0; + + if(0 == ps_dec->s_disp_op.u4_error_code) + { + return (IV_SUCCESS); + } + else + return (IV_FAIL); + + } + if(ps_dec->u1_res_changed == 1) + { + /*if resolution has changed and all buffers have been flushed, reset decoder*/ + ih264d_init_decoder(ps_dec); + } + + ps_dec->u4_prev_nal_skipped = 0; + + ps_dec->u2_cur_mb_addr = 0; + ps_dec->u2_total_mbs_coded = 0; + ps_dec->u2_cur_slice_num = 0; + ps_dec->cur_dec_mb_num = 0; + ps_dec->cur_recon_mb_num = 0; + ps_dec->u4_first_slice_in_pic = 2; + ps_dec->u1_first_pb_nal_in_pic = 1; + ps_dec->u1_slice_header_done = 0; + ps_dec->u1_dangling_field = 0; + + ps_dec->u4_dec_thread_created = 0; + ps_dec->u4_bs_deblk_thread_created = 0; + ps_dec->u4_cur_bs_mb_num = 0; + ps_dec->u4_start_recon_deblk = 0; + + DEBUG_THREADS_PRINTF("" Starting process call\n""); + + + ps_dec->u4_pic_buf_got = 0; + + do + { + WORD32 buf_size; + + pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer + + ps_dec_op->u4_num_bytes_consumed; + + u4_max_ofst = ps_dec_ip->u4_num_Bytes + - ps_dec_op->u4_num_bytes_consumed; + + /* If dynamic bitstream buffer is not allocated and + * header decode is done, then allocate dynamic bitstream buffer + */ + if((NULL == ps_dec->pu1_bits_buf_dynamic) && + (ps_dec->i4_header_decoded & 1)) + { + WORD32 size; + + void *pv_buf; + void *pv_mem_ctxt = ps_dec->pv_mem_ctxt; + size = MAX(256000, ps_dec->u2_pic_wd * ps_dec->u2_pic_ht * 3 / 2); + pv_buf = ps_dec->pf_aligned_alloc(pv_mem_ctxt, 128, size); + RETURN_IF((NULL == pv_buf), IV_FAIL); + ps_dec->pu1_bits_buf_dynamic = pv_buf; + ps_dec->u4_dynamic_bits_buf_size = size; + } + + if(ps_dec->pu1_bits_buf_dynamic) + { + pu1_bitstrm_buf = ps_dec->pu1_bits_buf_dynamic; + buf_size = ps_dec->u4_dynamic_bits_buf_size; + } + else + { + pu1_bitstrm_buf = ps_dec->pu1_bits_buf_static; + buf_size = ps_dec->u4_static_bits_buf_size; + } + + u4_next_is_aud = 0; + + buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst, + &u4_length_of_start_code, + &u4_next_is_aud); + + if(buflen == -1) + buflen = 0; + /* Ignore bytes beyond the allocated size of intermediate buffer */ + buflen = MIN(buflen, buf_size); + + bytes_consumed = buflen + u4_length_of_start_code; + ps_dec_op->u4_num_bytes_consumed += bytes_consumed; + + { + UWORD8 u1_firstbyte, u1_nal_ref_idc; + + if(ps_dec->i4_app_skip_mode == IVD_SKIP_B) + { + u1_firstbyte = *(pu1_buf + u4_length_of_start_code); + u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte)); + if(u1_nal_ref_idc == 0) + { + /*skip non reference frames*/ + cur_slice_is_nonref = 1; + continue; + } + else + { + if(1 == cur_slice_is_nonref) + { + /*We have encountered a referenced frame,return to app*/ + ps_dec_op->u4_num_bytes_consumed -= + bytes_consumed; + ps_dec_op->e_pic_type = IV_B_FRAME; + ps_dec_op->u4_error_code = + IVD_DEC_FRM_SKIPPED; + ps_dec_op->u4_error_code |= (1 + << IVD_UNSUPPORTEDPARAM); + ps_dec_op->u4_frame_decoded_flag = 0; + ps_dec_op->u4_size = + sizeof(ivd_video_decode_op_t); + /*signal the decode thread*/ + ih264d_signal_decode_thread(ps_dec); + /* close deblock thread if it is not closed yet*/ + if(ps_dec->u4_num_cores == 3) + { + ih264d_signal_bs_deblk_thread(ps_dec); + } + + return (IV_FAIL); + } + } + + } + + } + + + if(buflen) + { + memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code, + buflen); + /* Decoder may read extra 8 bytes near end of the frame */ + if((buflen + 8) < buf_size) + { + memset(pu1_bitstrm_buf + buflen, 0, 8); + } + u4_first_start_code_found = 1; + + } + else + { + /*start code not found*/ + + if(u4_first_start_code_found == 0) + { + /*no start codes found in current process call*/ + + ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND; + ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA; + + if(ps_dec->u4_pic_buf_got == 0) + { + + ih264d_fill_output_struct_from_context(ps_dec, + ps_dec_op); + + ps_dec_op->u4_error_code = ps_dec->i4_error_code; + ps_dec_op->u4_frame_decoded_flag = 0; + + return (IV_FAIL); + } + else + { + ps_dec->u1_pic_decode_done = 1; + continue; + } + } + else + { + /* a start code has already been found earlier in the same process call*/ + frame_data_left = 0; + continue; + } + + } + + ps_dec->u4_return_to_app = 0; + ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op, + pu1_bitstrm_buf, buflen); + if(ret != OK) + { + UWORD32 error = ih264d_map_error(ret); + ps_dec_op->u4_error_code = error | ret; + api_ret_value = IV_FAIL; + + if((ret == IVD_RES_CHANGED) + || (ret == IVD_MEM_ALLOC_FAILED) + || (ret == ERROR_UNAVAIL_PICBUF_T) + || (ret == ERROR_UNAVAIL_MVBUF_T) + || (ret == ERROR_INV_SPS_PPS_T)) + { + ps_dec->u4_slice_start_code_found = 0; + break; + } + + if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC)) + { + ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; + api_ret_value = IV_FAIL; + break; + } + + if(ret == ERROR_IN_LAST_SLICE_OF_PIC) + { + api_ret_value = IV_FAIL; + break; + } + + } + + if(ps_dec->u4_return_to_app) + { + /*We have encountered a referenced frame,return to app*/ + ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; + ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; + ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); + ps_dec_op->u4_frame_decoded_flag = 0; + ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); + /*signal the decode thread*/ + ih264d_signal_decode_thread(ps_dec); + /* close deblock thread if it is not closed yet*/ + if(ps_dec->u4_num_cores == 3) + { + ih264d_signal_bs_deblk_thread(ps_dec); + } + return (IV_FAIL); + + } + + + + header_data_left = ((ps_dec->i4_decode_header == 1) + && (ps_dec->i4_header_decoded != 3) + && (ps_dec_op->u4_num_bytes_consumed + < ps_dec_ip->u4_num_Bytes)); + frame_data_left = (((ps_dec->i4_decode_header == 0) + && ((ps_dec->u1_pic_decode_done == 0) + || (u4_next_is_aud == 1))) + && (ps_dec_op->u4_num_bytes_consumed + < ps_dec_ip->u4_num_Bytes)); + } + while(( header_data_left == 1)||(frame_data_left == 1)); + + if((ps_dec->u4_slice_start_code_found == 1) + && (ret != IVD_MEM_ALLOC_FAILED) + && ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) + { + WORD32 num_mb_skipped; + WORD32 prev_slice_err; + pocstruct_t temp_poc; + WORD32 ret1; + + num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) + - ps_dec->u2_total_mbs_coded; + + if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0)) + prev_slice_err = 1; + + else + prev_slice_err = 2; + + ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num, + &temp_poc, prev_slice_err); + + if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T)) + { + return IV_FAIL; + } + } + + if((ret == IVD_RES_CHANGED) + || (ret == IVD_MEM_ALLOC_FAILED) + || (ret == ERROR_UNAVAIL_PICBUF_T) + || (ret == ERROR_UNAVAIL_MVBUF_T) + || (ret == ERROR_INV_SPS_PPS_T)) + { + + /* signal the decode thread */ + ih264d_signal_decode_thread(ps_dec); + /* close deblock thread if it is not closed yet */ + if(ps_dec->u4_num_cores == 3) + { + ih264d_signal_bs_deblk_thread(ps_dec); + } + /* dont consume bitstream for change in resolution case */ + if(ret == IVD_RES_CHANGED) + { + ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; + } + return IV_FAIL; + } + + + if(ps_dec->u1_separate_parse) + { + /* If Format conversion is not complete, + complete it here */ + if(ps_dec->u4_num_cores == 2) + { + + /*do deblocking of all mbs*/ + if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0)) + { + UWORD32 u4_num_mbs,u4_max_addr; + tfr_ctxt_t s_tfr_ctxt; + tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt; + pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr; + + /*BS is done for all mbs while parsing*/ + u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1; + ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1; + + + ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt, + ps_dec->u2_frm_wd_in_mbs, 0); + + + u4_num_mbs = u4_max_addr + - ps_dec->u4_cur_deblk_mb_num + 1; + + DEBUG_PERF_PRINTF(""mbs left for deblocking= %d \n"",u4_num_mbs); + + if(u4_num_mbs != 0) + ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs, + ps_tfr_cxt,1); + + ps_dec->u4_start_recon_deblk = 0; + + } + + } + + /*signal the decode thread*/ + ih264d_signal_decode_thread(ps_dec); + /* close deblock thread if it is not closed yet*/ + if(ps_dec->u4_num_cores == 3) + { + ih264d_signal_bs_deblk_thread(ps_dec); + } + } + + + DATA_SYNC(); + + + if((ps_dec_op->u4_error_code & 0xff) + != ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED) + { + ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; + ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; + } + + if(ps_dec->i4_header_decoded != 3) + { + ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); + + } + + if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3) + { + ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); + + } + if(ps_dec->u4_prev_nal_skipped) + { + /*We have encountered a referenced frame,return to app*/ + ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; + ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); + ps_dec_op->u4_frame_decoded_flag = 0; + ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); + /* close deblock thread if it is not closed yet*/ + if(ps_dec->u4_num_cores == 3) + { + ih264d_signal_bs_deblk_thread(ps_dec); + } + return (IV_FAIL); + + } + + if((ps_dec->u4_slice_start_code_found == 1) + && (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status)) + { + /* + * For field pictures, set the bottom and top picture decoded u4_flag correctly. + */ + + if(ps_dec->ps_cur_slice->u1_field_pic_flag) + { + if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag) + { + ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY; + } + else + { + ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY; + } + } + + /* if new frame in not found (if we are still getting slices from previous frame) + * ih264d_deblock_display is not called. Such frames will not be added to reference /display + */ + if((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0) + { + /* Calling Function to deblock Picture and Display */ + ret = ih264d_deblock_display(ps_dec); + if(ret != 0) + { + return IV_FAIL; + } + } + + + /*set to complete ,as we dont support partial frame decode*/ + if(ps_dec->i4_header_decoded == 3) + { + ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; + } + + /*Update the i4_frametype at the end of picture*/ + if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL) + { + ps_dec->i4_frametype = IV_IDR_FRAME; + } + else if(ps_dec->i4_pic_type == B_SLICE) + { + ps_dec->i4_frametype = IV_B_FRAME; + } + else if(ps_dec->i4_pic_type == P_SLICE) + { + ps_dec->i4_frametype = IV_P_FRAME; + } + else if(ps_dec->i4_pic_type == I_SLICE) + { + ps_dec->i4_frametype = IV_I_FRAME; + } + else + { + H264_DEC_DEBUG_PRINT(""Shouldn't come here\n""); + } + + ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag; + + ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2; + ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + - ps_dec->ps_cur_slice->u1_field_pic_flag; + + } + + /* close deblock thread if it is not closed yet*/ + if(ps_dec->u4_num_cores == 3) + { + ih264d_signal_bs_deblk_thread(ps_dec); + } + + + { + /* In case the decoder is configured to run in low delay mode, + * then get display buffer and then format convert. + * Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles + */ + + if((IVD_DECODE_FRAME_OUT == ps_dec->e_frm_out_mode) + && ps_dec->u1_init_dec_flag) + { + + ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, + &(ps_dec->s_disp_op)); + if(0 == ps_dec->s_disp_op.u4_error_code) + { + ps_dec->u4_fmt_conv_cur_row = 0; + ps_dec->u4_output_present = 1; + } + } + + ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); + + /* If Format conversion is not complete, + complete it here */ + if(ps_dec->u4_output_present && + (ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht)) + { + ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht + - ps_dec->u4_fmt_conv_cur_row; + ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), + ps_dec->u4_fmt_conv_cur_row, + ps_dec->u4_fmt_conv_num_rows); + ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; + } + + ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); + } + + if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1) + { + ps_dec_op->u4_progressive_frame_flag = 1; + if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) + { + if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag) + && (0 == ps_dec->ps_sps->u1_mb_aff_flag)) + ps_dec_op->u4_progressive_frame_flag = 0; + + } + } + + /*Data memory barrier instruction,so that yuv write by the library is complete*/ + DATA_SYNC(); + + H264_DEC_DEBUG_PRINT(""The num bytes consumed: %d\n"", + ps_dec_op->u4_num_bytes_consumed); + return api_ret_value; +} +",1,"WORD32 ih264d_video_decode(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op) +{ + /* ! */ + + dec_struct_t * ps_dec = (dec_struct_t *)(dec_hdl->pv_codec_handle); + + WORD32 i4_err_status = 0; + UWORD8 *pu1_buf = NULL; + WORD32 buflen; + UWORD32 u4_max_ofst, u4_length_of_start_code = 0; + + UWORD32 bytes_consumed = 0; + UWORD32 cur_slice_is_nonref = 0; + UWORD32 u4_next_is_aud; + UWORD32 u4_first_start_code_found = 0; + WORD32 ret = 0,api_ret_value = IV_SUCCESS; + WORD32 header_data_left = 0,frame_data_left = 0; + UWORD8 *pu1_bitstrm_buf; + ivd_video_decode_ip_t *ps_dec_ip; + ivd_video_decode_op_t *ps_dec_op; + + ithread_set_name((void*)""Parse_thread""); + + ps_dec_ip = (ivd_video_decode_ip_t *)pv_api_ip; + ps_dec_op = (ivd_video_decode_op_t *)pv_api_op; + + { + UWORD32 u4_size; + u4_size = ps_dec_op->u4_size; + memset(ps_dec_op, 0, sizeof(ivd_video_decode_op_t)); + ps_dec_op->u4_size = u4_size; + } + + ps_dec->pv_dec_out = ps_dec_op; + if(ps_dec->init_done != 1) + { + return IV_FAIL; + } + + /*Data memory barries instruction,so that bitstream write by the application is complete*/ + DATA_SYNC(); + + if(0 == ps_dec->u1_flushfrm) + { + if(ps_dec_ip->pv_stream_buffer == NULL) + { + ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; + ps_dec_op->u4_error_code |= IVD_DEC_FRM_BS_BUF_NULL; + return IV_FAIL; + } + if(ps_dec_ip->u4_num_Bytes <= 0) + { + ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; + ps_dec_op->u4_error_code |= IVD_DEC_NUMBYTES_INV; + return IV_FAIL; + + } + } + ps_dec->u1_pic_decode_done = 0; + + ps_dec_op->u4_num_bytes_consumed = 0; + + ps_dec->ps_out_buffer = NULL; + + if(ps_dec_ip->u4_size + >= offsetof(ivd_video_decode_ip_t, s_out_buffer)) + ps_dec->ps_out_buffer = &ps_dec_ip->s_out_buffer; + + ps_dec->u4_fmt_conv_cur_row = 0; + + ps_dec->u4_output_present = 0; + ps_dec->s_disp_op.u4_error_code = 1; + ps_dec->u4_fmt_conv_num_rows = FMT_CONV_NUM_ROWS; + if(0 == ps_dec->u4_share_disp_buf + && ps_dec->i4_decode_header == 0) + { + UWORD32 i; + if(ps_dec->ps_out_buffer->u4_num_bufs == 0) + { + ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; + ps_dec_op->u4_error_code |= IVD_DISP_FRM_ZERO_OP_BUFS; + return IV_FAIL; + } + + for(i = 0; i < ps_dec->ps_out_buffer->u4_num_bufs; i++) + { + if(ps_dec->ps_out_buffer->pu1_bufs[i] == NULL) + { + ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; + ps_dec_op->u4_error_code |= IVD_DISP_FRM_OP_BUF_NULL; + return IV_FAIL; + } + + if(ps_dec->ps_out_buffer->u4_min_out_buf_size[i] == 0) + { + ps_dec_op->u4_error_code |= 1 << IVD_UNSUPPORTEDPARAM; + ps_dec_op->u4_error_code |= + IVD_DISP_FRM_ZERO_OP_BUF_SIZE; + return IV_FAIL; + } + } + } + + if(ps_dec->u4_total_frames_decoded >= NUM_FRAMES_LIMIT) + { + ps_dec_op->u4_error_code = ERROR_FRAME_LIMIT_OVER; + return IV_FAIL; + } + + /* ! */ + ps_dec->u4_ts = ps_dec_ip->u4_ts; + + ps_dec_op->u4_error_code = 0; + ps_dec_op->e_pic_type = -1; + ps_dec_op->u4_output_present = 0; + ps_dec_op->u4_frame_decoded_flag = 0; + + ps_dec->i4_frametype = -1; + ps_dec->i4_content_type = -1; + /* + * For field pictures, set the bottom and top picture decoded u4_flag correctly. + */ + { + if((TOP_FIELD_ONLY | BOT_FIELD_ONLY) == ps_dec->u1_top_bottom_decoded) + { + ps_dec->u1_top_bottom_decoded = 0; + } + } + ps_dec->u4_slice_start_code_found = 0; + + /* In case the deocder is not in flush mode(in shared mode), + then decoder has to pick up a buffer to write current frame. + Check if a frame is available in such cases */ + + if(ps_dec->u1_init_dec_flag == 1 && ps_dec->u4_share_disp_buf == 1 + && ps_dec->u1_flushfrm == 0) + { + UWORD32 i; + + WORD32 disp_avail = 0, free_id; + + /* Check if at least one buffer is available with the codec */ + /* If not then return to application with error */ + for(i = 0; i < ps_dec->u1_pic_bufs; i++) + { + if(0 == ps_dec->u4_disp_buf_mapping[i] + || 1 == ps_dec->u4_disp_buf_to_be_freed[i]) + { + disp_avail = 1; + break; + } + + } + + if(0 == disp_avail) + { + /* If something is queued for display wait for that buffer to be returned */ + + ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; + ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); + return (IV_FAIL); + } + + while(1) + { + pic_buffer_t *ps_pic_buf; + ps_pic_buf = (pic_buffer_t *)ih264_buf_mgr_get_next_free( + (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, &free_id); + + if(ps_pic_buf == NULL) + { + UWORD32 i, display_queued = 0; + + /* check if any buffer was given for display which is not returned yet */ + for(i = 0; i < (MAX_DISP_BUFS_NEW); i++) + { + if(0 != ps_dec->u4_disp_buf_mapping[i]) + { + display_queued = 1; + break; + } + } + /* If some buffer is queued for display, then codec has to singal an error and wait + for that buffer to be returned. + If nothing is queued for display then codec has ownership of all display buffers + and it can reuse any of the existing buffers and continue decoding */ + + if(1 == display_queued) + { + /* If something is queued for display wait for that buffer to be returned */ + ps_dec_op->u4_error_code = IVD_DEC_REF_BUF_NULL; + ps_dec_op->u4_error_code |= (1 + << IVD_UNSUPPORTEDPARAM); + return (IV_FAIL); + } + } + else + { + /* If the buffer is with display, then mark it as in use and then look for a buffer again */ + if(1 == ps_dec->u4_disp_buf_mapping[free_id]) + { + ih264_buf_mgr_set_status( + (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, + free_id, + BUF_MGR_IO); + } + else + { + /** + * Found a free buffer for present call. Release it now. + * Will be again obtained later. + */ + ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, + free_id, + BUF_MGR_IO); + break; + } + } + } + + } + + if(ps_dec->u1_flushfrm && ps_dec->u1_init_dec_flag) + { + + ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, + &(ps_dec->s_disp_op)); + if(0 == ps_dec->s_disp_op.u4_error_code) + { + ps_dec->u4_fmt_conv_cur_row = 0; + ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht; + ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), + ps_dec->u4_fmt_conv_cur_row, + ps_dec->u4_fmt_conv_num_rows); + ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; + ps_dec->u4_output_present = 1; + + } + ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); + + ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; + ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; + + ps_dec_op->u4_new_seq = 0; + + ps_dec_op->u4_output_present = ps_dec->u4_output_present; + ps_dec_op->u4_progressive_frame_flag = + ps_dec->s_disp_op.u4_progressive_frame_flag; + ps_dec_op->e_output_format = + ps_dec->s_disp_op.e_output_format; + ps_dec_op->s_disp_frm_buf = ps_dec->s_disp_op.s_disp_frm_buf; + ps_dec_op->e4_fld_type = ps_dec->s_disp_op.e4_fld_type; + ps_dec_op->u4_ts = ps_dec->s_disp_op.u4_ts; + ps_dec_op->u4_disp_buf_id = ps_dec->s_disp_op.u4_disp_buf_id; + + /*In the case of flush ,since no frame is decoded set pic type as invalid*/ + ps_dec_op->u4_is_ref_flag = -1; + ps_dec_op->e_pic_type = IV_NA_FRAME; + ps_dec_op->u4_frame_decoded_flag = 0; + + if(0 == ps_dec->s_disp_op.u4_error_code) + { + return (IV_SUCCESS); + } + else + return (IV_FAIL); + + } + if(ps_dec->u1_res_changed == 1) + { + /*if resolution has changed and all buffers have been flushed, reset decoder*/ + ih264d_init_decoder(ps_dec); + } + + ps_dec->u4_prev_nal_skipped = 0; + + ps_dec->u2_cur_mb_addr = 0; + ps_dec->u2_total_mbs_coded = 0; + ps_dec->u2_cur_slice_num = 0; + ps_dec->cur_dec_mb_num = 0; + ps_dec->cur_recon_mb_num = 0; + ps_dec->u4_first_slice_in_pic = 2; + ps_dec->u1_first_pb_nal_in_pic = 1; + ps_dec->u1_slice_header_done = 0; + ps_dec->u1_dangling_field = 0; + + ps_dec->u4_dec_thread_created = 0; + ps_dec->u4_bs_deblk_thread_created = 0; + ps_dec->u4_cur_bs_mb_num = 0; + ps_dec->u4_start_recon_deblk = 0; + + DEBUG_THREADS_PRINTF("" Starting process call\n""); + + + ps_dec->u4_pic_buf_got = 0; + + do + { + WORD32 buf_size; + + pu1_buf = (UWORD8*)ps_dec_ip->pv_stream_buffer + + ps_dec_op->u4_num_bytes_consumed; + + u4_max_ofst = ps_dec_ip->u4_num_Bytes + - ps_dec_op->u4_num_bytes_consumed; + + /* If dynamic bitstream buffer is not allocated and + * header decode is done, then allocate dynamic bitstream buffer + */ + if((NULL == ps_dec->pu1_bits_buf_dynamic) && + (ps_dec->i4_header_decoded & 1)) + { + WORD32 size; + + void *pv_buf; + void *pv_mem_ctxt = ps_dec->pv_mem_ctxt; + size = MAX(256000, ps_dec->u2_pic_wd * ps_dec->u2_pic_ht * 3 / 2); + pv_buf = ps_dec->pf_aligned_alloc(pv_mem_ctxt, 128, size); + RETURN_IF((NULL == pv_buf), IV_FAIL); + ps_dec->pu1_bits_buf_dynamic = pv_buf; + ps_dec->u4_dynamic_bits_buf_size = size; + } + + if(ps_dec->pu1_bits_buf_dynamic) + { + pu1_bitstrm_buf = ps_dec->pu1_bits_buf_dynamic; + buf_size = ps_dec->u4_dynamic_bits_buf_size; + } + else + { + pu1_bitstrm_buf = ps_dec->pu1_bits_buf_static; + buf_size = ps_dec->u4_static_bits_buf_size; + } + + u4_next_is_aud = 0; + + buflen = ih264d_find_start_code(pu1_buf, 0, u4_max_ofst, + &u4_length_of_start_code, + &u4_next_is_aud); + + if(buflen == -1) + buflen = 0; + /* Ignore bytes beyond the allocated size of intermediate buffer */ + buflen = MIN(buflen, buf_size); + + bytes_consumed = buflen + u4_length_of_start_code; + ps_dec_op->u4_num_bytes_consumed += bytes_consumed; + + { + UWORD8 u1_firstbyte, u1_nal_ref_idc; + + if(ps_dec->i4_app_skip_mode == IVD_SKIP_B) + { + u1_firstbyte = *(pu1_buf + u4_length_of_start_code); + u1_nal_ref_idc = (UWORD8)(NAL_REF_IDC(u1_firstbyte)); + if(u1_nal_ref_idc == 0) + { + /*skip non reference frames*/ + cur_slice_is_nonref = 1; + continue; + } + else + { + if(1 == cur_slice_is_nonref) + { + /*We have encountered a referenced frame,return to app*/ + ps_dec_op->u4_num_bytes_consumed -= + bytes_consumed; + ps_dec_op->e_pic_type = IV_B_FRAME; + ps_dec_op->u4_error_code = + IVD_DEC_FRM_SKIPPED; + ps_dec_op->u4_error_code |= (1 + << IVD_UNSUPPORTEDPARAM); + ps_dec_op->u4_frame_decoded_flag = 0; + ps_dec_op->u4_size = + sizeof(ivd_video_decode_op_t); + /*signal the decode thread*/ + ih264d_signal_decode_thread(ps_dec); + /* close deblock thread if it is not closed yet*/ + if(ps_dec->u4_num_cores == 3) + { + ih264d_signal_bs_deblk_thread(ps_dec); + } + + return (IV_FAIL); + } + } + + } + + } + + + if(buflen) + { + memcpy(pu1_bitstrm_buf, pu1_buf + u4_length_of_start_code, + buflen); + /* Decoder may read extra 8 bytes near end of the frame */ + if((buflen + 8) < buf_size) + { + memset(pu1_bitstrm_buf + buflen, 0, 8); + } + u4_first_start_code_found = 1; + + } + else + { + /*start code not found*/ + + if(u4_first_start_code_found == 0) + { + /*no start codes found in current process call*/ + + ps_dec->i4_error_code = ERROR_START_CODE_NOT_FOUND; + ps_dec_op->u4_error_code |= 1 << IVD_INSUFFICIENTDATA; + + if(ps_dec->u4_pic_buf_got == 0) + { + + ih264d_fill_output_struct_from_context(ps_dec, + ps_dec_op); + + ps_dec_op->u4_error_code = ps_dec->i4_error_code; + ps_dec_op->u4_frame_decoded_flag = 0; + + return (IV_FAIL); + } + else + { + ps_dec->u1_pic_decode_done = 1; + continue; + } + } + else + { + /* a start code has already been found earlier in the same process call*/ + frame_data_left = 0; + continue; + } + + } + + ps_dec->u4_return_to_app = 0; + ret = ih264d_parse_nal_unit(dec_hdl, ps_dec_op, + pu1_bitstrm_buf, buflen); + if(ret != OK) + { + UWORD32 error = ih264d_map_error(ret); + ps_dec_op->u4_error_code = error | ret; + api_ret_value = IV_FAIL; + + if((ret == IVD_RES_CHANGED) + || (ret == IVD_MEM_ALLOC_FAILED) + || (ret == ERROR_UNAVAIL_PICBUF_T) + || (ret == ERROR_UNAVAIL_MVBUF_T) + || (ret == ERROR_INV_SPS_PPS_T)) + { + ps_dec->u4_slice_start_code_found = 0; + break; + } + + if((ret == ERROR_INCOMPLETE_FRAME) || (ret == ERROR_DANGLING_FIELD_IN_PIC)) + { + ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; + api_ret_value = IV_FAIL; + break; + } + + if(ret == ERROR_IN_LAST_SLICE_OF_PIC) + { + api_ret_value = IV_FAIL; + break; + } + + } + + if(ps_dec->u4_return_to_app) + { + /*We have encountered a referenced frame,return to app*/ + ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; + ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; + ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); + ps_dec_op->u4_frame_decoded_flag = 0; + ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); + /*signal the decode thread*/ + ih264d_signal_decode_thread(ps_dec); + /* close deblock thread if it is not closed yet*/ + if(ps_dec->u4_num_cores == 3) + { + ih264d_signal_bs_deblk_thread(ps_dec); + } + return (IV_FAIL); + + } + + + + header_data_left = ((ps_dec->i4_decode_header == 1) + && (ps_dec->i4_header_decoded != 3) + && (ps_dec_op->u4_num_bytes_consumed + < ps_dec_ip->u4_num_Bytes)); + frame_data_left = (((ps_dec->i4_decode_header == 0) + && ((ps_dec->u1_pic_decode_done == 0) + || (u4_next_is_aud == 1))) + && (ps_dec_op->u4_num_bytes_consumed + < ps_dec_ip->u4_num_Bytes)); + } + while(( header_data_left == 1)||(frame_data_left == 1)); + + if((ps_dec->u4_slice_start_code_found == 1) + && (ret != IVD_MEM_ALLOC_FAILED) + && ps_dec->u2_total_mbs_coded < ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) + { + WORD32 num_mb_skipped; + WORD32 prev_slice_err; + pocstruct_t temp_poc; + WORD32 ret1; + + num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) + - ps_dec->u2_total_mbs_coded; + + if(ps_dec->u4_first_slice_in_pic && (ps_dec->u4_pic_buf_got == 0)) + prev_slice_err = 1; + + else + prev_slice_err = 2; + + if(ps_dec->u4_first_slice_in_pic && (ps_dec->u2_total_mbs_coded == 0)) + prev_slice_err = 1; + + ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num, + &temp_poc, prev_slice_err); + + if((ret1 == ERROR_UNAVAIL_PICBUF_T) || (ret1 == ERROR_UNAVAIL_MVBUF_T)) + { + return IV_FAIL; + } + } + + if((ret == IVD_RES_CHANGED) + || (ret == IVD_MEM_ALLOC_FAILED) + || (ret == ERROR_UNAVAIL_PICBUF_T) + || (ret == ERROR_UNAVAIL_MVBUF_T) + || (ret == ERROR_INV_SPS_PPS_T)) + { + + /* signal the decode thread */ + ih264d_signal_decode_thread(ps_dec); + /* close deblock thread if it is not closed yet */ + if(ps_dec->u4_num_cores == 3) + { + ih264d_signal_bs_deblk_thread(ps_dec); + } + /* dont consume bitstream for change in resolution case */ + if(ret == IVD_RES_CHANGED) + { + ps_dec_op->u4_num_bytes_consumed -= bytes_consumed; + } + return IV_FAIL; + } + + + if(ps_dec->u1_separate_parse) + { + /* If Format conversion is not complete, + complete it here */ + if(ps_dec->u4_num_cores == 2) + { + + /*do deblocking of all mbs*/ + if((ps_dec->u4_nmb_deblk == 0) &&(ps_dec->u4_start_recon_deblk == 1) && (ps_dec->ps_cur_sps->u1_mb_aff_flag == 0)) + { + UWORD32 u4_num_mbs,u4_max_addr; + tfr_ctxt_t s_tfr_ctxt; + tfr_ctxt_t *ps_tfr_cxt = &s_tfr_ctxt; + pad_mgr_t *ps_pad_mgr = &ps_dec->s_pad_mgr; + + /*BS is done for all mbs while parsing*/ + u4_max_addr = (ps_dec->u2_frm_wd_in_mbs * ps_dec->u2_frm_ht_in_mbs) - 1; + ps_dec->u4_cur_bs_mb_num = u4_max_addr + 1; + + + ih264d_init_deblk_tfr_ctxt(ps_dec, ps_pad_mgr, ps_tfr_cxt, + ps_dec->u2_frm_wd_in_mbs, 0); + + + u4_num_mbs = u4_max_addr + - ps_dec->u4_cur_deblk_mb_num + 1; + + DEBUG_PERF_PRINTF(""mbs left for deblocking= %d \n"",u4_num_mbs); + + if(u4_num_mbs != 0) + ih264d_check_mb_map_deblk(ps_dec, u4_num_mbs, + ps_tfr_cxt,1); + + ps_dec->u4_start_recon_deblk = 0; + + } + + } + + /*signal the decode thread*/ + ih264d_signal_decode_thread(ps_dec); + /* close deblock thread if it is not closed yet*/ + if(ps_dec->u4_num_cores == 3) + { + ih264d_signal_bs_deblk_thread(ps_dec); + } + } + + + DATA_SYNC(); + + + if((ps_dec_op->u4_error_code & 0xff) + != ERROR_DYNAMIC_RESOLUTION_NOT_SUPPORTED) + { + ps_dec_op->u4_pic_wd = (UWORD32)ps_dec->u2_disp_width; + ps_dec_op->u4_pic_ht = (UWORD32)ps_dec->u2_disp_height; + } + + if(ps_dec->i4_header_decoded != 3) + { + ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); + + } + + if(ps_dec->i4_decode_header == 1 && ps_dec->i4_header_decoded != 3) + { + ps_dec_op->u4_error_code |= (1 << IVD_INSUFFICIENTDATA); + + } + if(ps_dec->u4_prev_nal_skipped) + { + /*We have encountered a referenced frame,return to app*/ + ps_dec_op->u4_error_code = IVD_DEC_FRM_SKIPPED; + ps_dec_op->u4_error_code |= (1 << IVD_UNSUPPORTEDPARAM); + ps_dec_op->u4_frame_decoded_flag = 0; + ps_dec_op->u4_size = sizeof(ivd_video_decode_op_t); + /* close deblock thread if it is not closed yet*/ + if(ps_dec->u4_num_cores == 3) + { + ih264d_signal_bs_deblk_thread(ps_dec); + } + return (IV_FAIL); + + } + + if((ps_dec->u4_slice_start_code_found == 1) + && (ERROR_DANGLING_FIELD_IN_PIC != i4_err_status)) + { + /* + * For field pictures, set the bottom and top picture decoded u4_flag correctly. + */ + + if(ps_dec->ps_cur_slice->u1_field_pic_flag) + { + if(1 == ps_dec->ps_cur_slice->u1_bottom_field_flag) + { + ps_dec->u1_top_bottom_decoded |= BOT_FIELD_ONLY; + } + else + { + ps_dec->u1_top_bottom_decoded |= TOP_FIELD_ONLY; + } + } + + /* if new frame in not found (if we are still getting slices from previous frame) + * ih264d_deblock_display is not called. Such frames will not be added to reference /display + */ + if((ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) == 0) + { + /* Calling Function to deblock Picture and Display */ + ret = ih264d_deblock_display(ps_dec); + if(ret != 0) + { + return IV_FAIL; + } + } + + + /*set to complete ,as we dont support partial frame decode*/ + if(ps_dec->i4_header_decoded == 3) + { + ps_dec->u2_total_mbs_coded = ps_dec->ps_cur_sps->u2_max_mb_addr + 1; + } + + /*Update the i4_frametype at the end of picture*/ + if(ps_dec->ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL) + { + ps_dec->i4_frametype = IV_IDR_FRAME; + } + else if(ps_dec->i4_pic_type == B_SLICE) + { + ps_dec->i4_frametype = IV_B_FRAME; + } + else if(ps_dec->i4_pic_type == P_SLICE) + { + ps_dec->i4_frametype = IV_P_FRAME; + } + else if(ps_dec->i4_pic_type == I_SLICE) + { + ps_dec->i4_frametype = IV_I_FRAME; + } + else + { + H264_DEC_DEBUG_PRINT(""Shouldn't come here\n""); + } + + ps_dec->i4_content_type = ps_dec->ps_cur_slice->u1_field_pic_flag; + + ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + 2; + ps_dec->u4_total_frames_decoded = ps_dec->u4_total_frames_decoded + - ps_dec->ps_cur_slice->u1_field_pic_flag; + + } + + /* close deblock thread if it is not closed yet*/ + if(ps_dec->u4_num_cores == 3) + { + ih264d_signal_bs_deblk_thread(ps_dec); + } + + + { + /* In case the decoder is configured to run in low delay mode, + * then get display buffer and then format convert. + * Note in this mode, format conversion does not run paralelly in a thread and adds to the codec cycles + */ + + if((IVD_DECODE_FRAME_OUT == ps_dec->e_frm_out_mode) + && ps_dec->u1_init_dec_flag) + { + + ih264d_get_next_display_field(ps_dec, ps_dec->ps_out_buffer, + &(ps_dec->s_disp_op)); + if(0 == ps_dec->s_disp_op.u4_error_code) + { + ps_dec->u4_fmt_conv_cur_row = 0; + ps_dec->u4_output_present = 1; + } + } + + ih264d_fill_output_struct_from_context(ps_dec, ps_dec_op); + + /* If Format conversion is not complete, + complete it here */ + if(ps_dec->u4_output_present && + (ps_dec->u4_fmt_conv_cur_row < ps_dec->s_disp_frame_info.u4_y_ht)) + { + ps_dec->u4_fmt_conv_num_rows = ps_dec->s_disp_frame_info.u4_y_ht + - ps_dec->u4_fmt_conv_cur_row; + ih264d_format_convert(ps_dec, &(ps_dec->s_disp_op), + ps_dec->u4_fmt_conv_cur_row, + ps_dec->u4_fmt_conv_num_rows); + ps_dec->u4_fmt_conv_cur_row += ps_dec->u4_fmt_conv_num_rows; + } + + ih264d_release_display_field(ps_dec, &(ps_dec->s_disp_op)); + } + + if(ps_dec->i4_decode_header == 1 && (ps_dec->i4_header_decoded & 1) == 1) + { + ps_dec_op->u4_progressive_frame_flag = 1; + if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) + { + if((0 == ps_dec->ps_sps->u1_frame_mbs_only_flag) + && (0 == ps_dec->ps_sps->u1_mb_aff_flag)) + ps_dec_op->u4_progressive_frame_flag = 0; + + } + } + + /*Data memory barrier instruction,so that yuv write by the library is complete*/ + DATA_SYNC(); + + H264_DEC_DEBUG_PRINT(""The num bytes consumed: %d\n"", + ps_dec_op->u4_num_bytes_consumed); + return api_ret_value; +} +","@@ -2140,6 +2140,9 @@ + + else + prev_slice_err = 2; + ++ if(ps_dec->u4_first_slice_in_pic && (ps_dec->u2_total_mbs_coded == 0)) ++ prev_slice_err = 1; ++ + ret1 = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, ps_dec->u1_nal_unit_type == IDR_SLICE_NAL, ps_dec->ps_cur_slice->u2_frame_num, + &temp_poc, prev_slice_err); + +",6309,6640,8192 +18210,"static Image *ReadPICTImage(const ImageInfo *image_info, + ExceptionInfo *exception) +{ +#define ThrowPICTException(exception,message) \ +{ \ + if (tile_image != (Image *) NULL) \ + tile_image=DestroyImage(tile_image); \ + if (read_info != (ImageInfo *) NULL) \ + read_info=DestroyImageInfo(read_info); \ + ThrowReaderException((exception),(message)); \ +} + + char + geometry[MagickPathExtent], + header_ole[4]; + + Image + *image, + *tile_image; + + ImageInfo + *read_info; + + int + c, + code; + + MagickBooleanType + jpeg, + status; + + PICTRectangle + frame; + + PICTPixmap + pixmap; + + Quantum + index; + + register Quantum + *q; + + register ssize_t + i, + x; + + size_t + extent, + length; + + ssize_t + count, + flags, + j, + version, + y; + + StringInfo + *profile; + + /* + 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 PICT header. + */ + read_info=(ImageInfo *) NULL; + tile_image=(Image *) NULL; + pixmap.bits_per_pixel=0; + pixmap.component_count=0; + /* + Skip header : 512 for standard PICT and 4, ie ""PICT"" for OLE2. + */ + header_ole[0]=ReadBlobByte(image); + header_ole[1]=ReadBlobByte(image); + header_ole[2]=ReadBlobByte(image); + header_ole[3]=ReadBlobByte(image); + if (!((header_ole[0] == 0x50) && (header_ole[1] == 0x49) && + (header_ole[2] == 0x43) && (header_ole[3] == 0x54 ))) + for (i=0; i < 508; i++) + if (ReadBlobByte(image) == EOF) + break; + (void) ReadBlobMSBShort(image); /* skip picture size */ + if (ReadRectangle(image,&frame) == MagickFalse) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + while ((c=ReadBlobByte(image)) == 0) ; + if (c != 0x11) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + version=(ssize_t) ReadBlobByte(image); + if (version == 2) + { + c=ReadBlobByte(image); + if (c != 0xff) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + } + else + if (version != 1) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + if ((frame.left < 0) || (frame.right < 0) || (frame.top < 0) || + (frame.bottom < 0) || (frame.left >= frame.right) || + (frame.top >= frame.bottom)) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + /* + Create black canvas. + */ + flags=0; + image->depth=8; + image->columns=(size_t) (frame.right-frame.left); + image->rows=(size_t) (frame.bottom-frame.top); + image->resolution.x=DefaultResolution; + image->resolution.y=DefaultResolution; + image->units=UndefinedResolution; + if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) + if (image->scene >= (image_info->scene+image_info->number_scenes-1)) + { + (void) CloseBlob(image); + return(GetFirstImageInList(image)); + } + status=SetImageExtent(image,image->columns,image->rows,exception); + if (status != MagickFalse) + status=ResetImagePixels(image,exception); + if (status == MagickFalse) + return(DestroyImageList(image)); + /* + Interpret PICT opcodes. + */ + jpeg=MagickFalse; + for (code=0; EOFBlob(image) == MagickFalse; ) + { + if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) + if (image->scene >= (image_info->scene+image_info->number_scenes-1)) + break; + if ((version == 1) || ((TellBlob(image) % 2) != 0)) + code=ReadBlobByte(image); + if (version == 2) + code=ReadBlobMSBSignedShort(image); + if (code < 0) + break; + if (code == 0) + continue; + if (code > 0xa1) + { + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(),""%04X:"",code); + } + else + { + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" %04X %s: %s"",code,codes[code].name,codes[code].description); + switch (code) + { + case 0x01: + { + /* + Clipping rectangle. + */ + length=ReadBlobMSBShort(image); + if (length != 0x000a) + { + for (i=0; i < (ssize_t) (length-2); i++) + if (ReadBlobByte(image) == EOF) + break; + break; + } + if (ReadRectangle(image,&frame) == MagickFalse) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + if (((frame.left & 0x8000) != 0) || ((frame.top & 0x8000) != 0)) + break; + image->columns=(size_t) (frame.right-frame.left); + image->rows=(size_t) (frame.bottom-frame.top); + status=SetImageExtent(image,image->columns,image->rows,exception); + if (status != MagickFalse) + status=ResetImagePixels(image,exception); + if (status == MagickFalse) + return(DestroyImageList(image)); + break; + } + case 0x12: + case 0x13: + case 0x14: + { + ssize_t + pattern; + + size_t + height, + width; + + /* + Skip pattern definition. + */ + pattern=(ssize_t) ReadBlobMSBShort(image); + for (i=0; i < 8; i++) + if (ReadBlobByte(image) == EOF) + break; + if (pattern == 2) + { + for (i=0; i < 5; i++) + if (ReadBlobByte(image) == EOF) + break; + break; + } + if (pattern != 1) + ThrowPICTException(CorruptImageError,""UnknownPatternType""); + length=ReadBlobMSBShort(image); + if (ReadRectangle(image,&frame) == MagickFalse) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + if (ReadPixmap(image,&pixmap) == MagickFalse) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + image->depth=(size_t) pixmap.component_size; + image->resolution.x=1.0*pixmap.horizontal_resolution; + image->resolution.y=1.0*pixmap.vertical_resolution; + image->units=PixelsPerInchResolution; + (void) ReadBlobMSBLong(image); + flags=(ssize_t) ReadBlobMSBShort(image); + length=ReadBlobMSBShort(image); + for (i=0; i <= (ssize_t) length; i++) + (void) ReadBlobMSBLong(image); + width=(size_t) (frame.bottom-frame.top); + height=(size_t) (frame.right-frame.left); + if (pixmap.bits_per_pixel <= 8) + length&=0x7fff; + if (pixmap.bits_per_pixel == 16) + width<<=1; + if (length == 0) + length=width; + if (length < 8) + { + for (i=0; i < (ssize_t) (length*height); i++) + if (ReadBlobByte(image) == EOF) + break; + } + else + for (i=0; i < (ssize_t) height; i++) + { + if (EOFBlob(image) != MagickFalse) + break; + if (length > 200) + { + for (j=0; j < (ssize_t) ReadBlobMSBShort(image); j++) + if (ReadBlobByte(image) == EOF) + break; + } + else + for (j=0; j < (ssize_t) ReadBlobByte(image); j++) + if (ReadBlobByte(image) == EOF) + break; + } + break; + } + case 0x1b: + { + /* + Initialize image background color. + */ + image->background_color.red=(Quantum) + ScaleShortToQuantum(ReadBlobMSBShort(image)); + image->background_color.green=(Quantum) + ScaleShortToQuantum(ReadBlobMSBShort(image)); + image->background_color.blue=(Quantum) + ScaleShortToQuantum(ReadBlobMSBShort(image)); + break; + } + case 0x70: + case 0x71: + case 0x72: + case 0x73: + case 0x74: + case 0x75: + case 0x76: + case 0x77: + { + /* + Skip polygon or region. + */ + length=ReadBlobMSBShort(image); + for (i=0; i < (ssize_t) (length-2); i++) + if (ReadBlobByte(image) == EOF) + break; + break; + } + case 0x90: + case 0x91: + case 0x98: + case 0x99: + case 0x9a: + case 0x9b: + { + PICTRectangle + source, + destination; + + register unsigned char + *p; + + size_t + j; + + ssize_t + bytes_per_line; + + unsigned char + *pixels; + + /* + Pixmap clipped by a rectangle. + */ + bytes_per_line=0; + if ((code != 0x9a) && (code != 0x9b)) + bytes_per_line=(ssize_t) ReadBlobMSBShort(image); + else + { + (void) ReadBlobMSBShort(image); + (void) ReadBlobMSBShort(image); + (void) ReadBlobMSBShort(image); + } + if (ReadRectangle(image,&frame) == MagickFalse) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + /* + Initialize tile image. + */ + tile_image=CloneImage(image,(size_t) (frame.right-frame.left), + (size_t) (frame.bottom-frame.top),MagickTrue,exception); + if (tile_image == (Image *) NULL) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + if ((code == 0x9a) || (code == 0x9b) || + ((bytes_per_line & 0x8000) != 0)) + { + if (ReadPixmap(image,&pixmap) == MagickFalse) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + tile_image->depth=(size_t) pixmap.component_size; + tile_image->alpha_trait=pixmap.component_count == 4 ? + BlendPixelTrait : UndefinedPixelTrait; + tile_image->resolution.x=(double) pixmap.horizontal_resolution; + tile_image->resolution.y=(double) pixmap.vertical_resolution; + tile_image->units=PixelsPerInchResolution; + if (tile_image->alpha_trait != UndefinedPixelTrait) + (void) SetImageAlpha(tile_image,OpaqueAlpha,exception); + } + if ((code != 0x9a) && (code != 0x9b)) + { + /* + Initialize colormap. + */ + tile_image->colors=2; + if ((bytes_per_line & 0x8000) != 0) + { + (void) ReadBlobMSBLong(image); + flags=(ssize_t) ReadBlobMSBShort(image); + tile_image->colors=1UL*ReadBlobMSBShort(image)+1; + } + status=AcquireImageColormap(tile_image,tile_image->colors, + exception); + if (status == MagickFalse) + ThrowPICTException(ResourceLimitError, + ""MemoryAllocationFailed""); + if ((bytes_per_line & 0x8000) != 0) + { + for (i=0; i < (ssize_t) tile_image->colors; i++) + { + j=ReadBlobMSBShort(image) % tile_image->colors; + if ((flags & 0x8000) != 0) + j=(size_t) i; + tile_image->colormap[j].red=(Quantum) + ScaleShortToQuantum(ReadBlobMSBShort(image)); + tile_image->colormap[j].green=(Quantum) + ScaleShortToQuantum(ReadBlobMSBShort(image)); + tile_image->colormap[j].blue=(Quantum) + ScaleShortToQuantum(ReadBlobMSBShort(image)); + } + } + else + { + for (i=0; i < (ssize_t) tile_image->colors; i++) + { + tile_image->colormap[i].red=(Quantum) (QuantumRange- + tile_image->colormap[i].red); + tile_image->colormap[i].green=(Quantum) (QuantumRange- + tile_image->colormap[i].green); + tile_image->colormap[i].blue=(Quantum) (QuantumRange- + tile_image->colormap[i].blue); + } + } + } + if (EOFBlob(image) != MagickFalse) + ThrowPICTException(CorruptImageError, + ""InsufficientImageDataInFile""); + if (ReadRectangle(image,&source) == MagickFalse) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + if (ReadRectangle(image,&destination) == MagickFalse) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + (void) ReadBlobMSBShort(image); + if ((code == 0x91) || (code == 0x99) || (code == 0x9b)) + { + /* + Skip region. + */ + length=ReadBlobMSBShort(image); + for (i=0; i < (ssize_t) (length-2); i++) + if (ReadBlobByte(image) == EOF) + break; + } + if ((code != 0x9a) && (code != 0x9b) && + (bytes_per_line & 0x8000) == 0) + pixels=DecodeImage(image,tile_image,(size_t) bytes_per_line,1, + &extent); + else + pixels=DecodeImage(image,tile_image,(size_t) bytes_per_line, + (unsigned int) pixmap.bits_per_pixel,&extent); + if (pixels == (unsigned char *) NULL) + ThrowPICTException(CorruptImageError,""UnableToUncompressImage""); + /* + Convert PICT tile image to pixel packets. + */ + p=pixels; + for (y=0; y < (ssize_t) tile_image->rows; y++) + { + if (p > (pixels+extent+image->columns)) + { + pixels=(unsigned char *) RelinquishMagickMemory(pixels); + ThrowPICTException(CorruptImageError,""NotEnoughPixelData""); + } + q=QueueAuthenticPixels(tile_image,0,y,tile_image->columns,1, + exception); + if (q == (Quantum *) NULL) + break; + for (x=0; x < (ssize_t) tile_image->columns; x++) + { + if (tile_image->storage_class == PseudoClass) + { + index=(Quantum) ConstrainColormapIndex(tile_image,(ssize_t) + *p,exception); + SetPixelIndex(tile_image,index,q); + SetPixelRed(tile_image, + tile_image->colormap[(ssize_t) index].red,q); + SetPixelGreen(tile_image, + tile_image->colormap[(ssize_t) index].green,q); + SetPixelBlue(tile_image, + tile_image->colormap[(ssize_t) index].blue,q); + } + else + { + if (pixmap.bits_per_pixel == 16) + { + i=(ssize_t) (*p++); + j=(size_t) (*p); + SetPixelRed(tile_image,ScaleCharToQuantum( + (unsigned char) ((i & 0x7c) << 1)),q); + SetPixelGreen(tile_image,ScaleCharToQuantum( + (unsigned char) (((i & 0x03) << 6) | + ((j & 0xe0) >> 2))),q); + SetPixelBlue(tile_image,ScaleCharToQuantum( + (unsigned char) ((j & 0x1f) << 3)),q); + } + else + if (tile_image->alpha_trait == UndefinedPixelTrait) + { + if (p > (pixels+extent+2*image->columns)) + ThrowPICTException(CorruptImageError, + ""NotEnoughPixelData""); + SetPixelRed(tile_image,ScaleCharToQuantum(*p),q); + SetPixelGreen(tile_image,ScaleCharToQuantum( + *(p+tile_image->columns)),q); + SetPixelBlue(tile_image,ScaleCharToQuantum( + *(p+2*tile_image->columns)),q); + } + else + { + if (p > (pixels+extent+3*image->columns)) + ThrowPICTException(CorruptImageError, + ""NotEnoughPixelData""); + SetPixelAlpha(tile_image,ScaleCharToQuantum(*p),q); + SetPixelRed(tile_image,ScaleCharToQuantum( + *(p+tile_image->columns)),q); + SetPixelGreen(tile_image,ScaleCharToQuantum( + *(p+2*tile_image->columns)),q); + SetPixelBlue(tile_image,ScaleCharToQuantum( + *(p+3*tile_image->columns)),q); + } + } + p++; + q+=GetPixelChannels(tile_image); + } + if (SyncAuthenticPixels(tile_image,exception) == MagickFalse) + break; + if ((tile_image->storage_class == DirectClass) && + (pixmap.bits_per_pixel != 16)) + { + p+=(pixmap.component_count-1)*tile_image->columns; + if (p < pixels) + break; + } + status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, + tile_image->rows); + if (status == MagickFalse) + break; + } + pixels=(unsigned char *) RelinquishMagickMemory(pixels); + if ((jpeg == MagickFalse) && (EOFBlob(image) == MagickFalse)) + if ((code == 0x9a) || (code == 0x9b) || + ((bytes_per_line & 0x8000) != 0)) + (void) CompositeImage(image,tile_image,CopyCompositeOp, + MagickTrue,(ssize_t) destination.left,(ssize_t) + destination.top,exception); + tile_image=DestroyImage(tile_image); + break; + } + case 0xa1: + { + unsigned char + *info; + + size_t + type; + + /* + Comment. + */ + type=ReadBlobMSBShort(image); + length=ReadBlobMSBShort(image); + if (length == 0) + break; + (void) ReadBlobMSBLong(image); + length-=MagickMin(length,4); + if (length == 0) + break; + info=(unsigned char *) AcquireQuantumMemory(length,sizeof(*info)); + if (info == (unsigned char *) NULL) + break; + count=ReadBlob(image,length,info); + if (count != (ssize_t) length) + { + info=(unsigned char *) RelinquishMagickMemory(info); + ThrowPICTException(ResourceLimitError,""UnableToReadImageData""); + } + switch (type) + { + case 0xe0: + { + profile=BlobToStringInfo((const void *) NULL,length); + SetStringInfoDatum(profile,info); + status=SetImageProfile(image,""icc"",profile,exception); + profile=DestroyStringInfo(profile); + if (status == MagickFalse) + { + info=(unsigned char *) RelinquishMagickMemory(info); + ThrowPICTException(ResourceLimitError, + ""MemoryAllocationFailed""); + } + break; + } + case 0x1f2: + { + profile=BlobToStringInfo((const void *) NULL,length); + SetStringInfoDatum(profile,info); + status=SetImageProfile(image,""iptc"",profile,exception); + if (status == MagickFalse) + { + info=(unsigned char *) RelinquishMagickMemory(info); + ThrowPICTException(ResourceLimitError, + ""MemoryAllocationFailed""); + } + profile=DestroyStringInfo(profile); + break; + } + default: + break; + } + info=(unsigned char *) RelinquishMagickMemory(info); + break; + } + default: + { + /* + Skip to next op code. + */ + if (codes[code].length == -1) + (void) ReadBlobMSBShort(image); + else + for (i=0; i < (ssize_t) codes[code].length; i++) + if (ReadBlobByte(image) == EOF) + break; + } + } + } + if (code == 0xc00) + { + /* + Skip header. + */ + for (i=0; i < 24; i++) + if (ReadBlobByte(image) == EOF) + break; + continue; + } + if (((code >= 0xb0) && (code <= 0xcf)) || + ((code >= 0x8000) && (code <= 0x80ff))) + continue; + if (code == 0x8200) + { + char + filename[MaxTextExtent]; + + FILE + *file; + + int + unique_file; + + /* + Embedded JPEG. + */ + jpeg=MagickTrue; + read_info=CloneImageInfo(image_info); + SetImageInfoBlob(read_info,(void *) NULL,0); + file=(FILE *) NULL; + unique_file=AcquireUniqueFileResource(filename); + (void) FormatLocaleString(read_info->filename,MaxTextExtent,""jpeg:%s"", + filename); + if (unique_file != -1) + file=fdopen(unique_file,""wb""); + if ((unique_file == -1) || (file == (FILE *) NULL)) + { + (void) RelinquishUniqueFileResource(read_info->filename); + (void) CopyMagickString(image->filename,read_info->filename, + MagickPathExtent); + ThrowPICTException(FileOpenError,""UnableToCreateTemporaryFile""); + } + length=ReadBlobMSBLong(image); + if (length > 154) + { + for (i=0; i < 6; i++) + (void) ReadBlobMSBLong(image); + if (ReadRectangle(image,&frame) == MagickFalse) + { + (void) fclose(file); + (void) RelinquishUniqueFileResource(read_info->filename); + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + } + for (i=0; i < 122; i++) + if (ReadBlobByte(image) == EOF) + break; + for (i=0; i < (ssize_t) (length-154); i++) + { + c=ReadBlobByte(image); + if (c == EOF) + break; + (void) fputc(c,file); + } + } + (void) fclose(file); + (void) close(unique_file); + tile_image=ReadImage(read_info,exception); + (void) RelinquishUniqueFileResource(filename); + read_info=DestroyImageInfo(read_info); + if (tile_image == (Image *) NULL) + continue; + (void) FormatLocaleString(geometry,MagickPathExtent,""%.20gx%.20g"", + (double) MagickMax(image->columns,tile_image->columns), + (double) MagickMax(image->rows,tile_image->rows)); + (void) SetImageExtent(image, + MagickMax(image->columns,tile_image->columns), + MagickMax(image->rows,tile_image->rows),exception); + (void) TransformImageColorspace(image,tile_image->colorspace,exception); + (void) CompositeImage(image,tile_image,CopyCompositeOp,MagickTrue, + (ssize_t) frame.left,(ssize_t) frame.right,exception); + image->compression=tile_image->compression; + tile_image=DestroyImage(tile_image); + continue; + } + if ((code == 0xff) || (code == 0xffff)) + break; + if (((code >= 0xd0) && (code <= 0xfe)) || + ((code >= 0x8100) && (code <= 0xffff))) + { + /* + Skip reserved. + */ + length=ReadBlobMSBShort(image); + for (i=0; i < (ssize_t) length; i++) + if (ReadBlobByte(image) == EOF) + break; + continue; + } + if ((code >= 0x100) && (code <= 0x7fff)) + { + /* + Skip reserved. + */ + length=(size_t) ((code >> 7) & 0xff); + for (i=0; i < (ssize_t) length; i++) + if (ReadBlobByte(image) == EOF) + break; + continue; + } + } + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +",1,"static Image *ReadPICTImage(const ImageInfo *image_info, + ExceptionInfo *exception) +{ +#define ThrowPICTException(exception,message) \ +{ \ + if (tile_image != (Image *) NULL) \ + tile_image=DestroyImage(tile_image); \ + if (read_info != (ImageInfo *) NULL) \ + read_info=DestroyImageInfo(read_info); \ + ThrowReaderException((exception),(message)); \ +} + + char + geometry[MagickPathExtent], + header_ole[4]; + + Image + *image, + *tile_image; + + ImageInfo + *read_info; + + int + c, + code; + + MagickBooleanType + jpeg, + status; + + PICTRectangle + frame; + + PICTPixmap + pixmap; + + Quantum + index; + + register Quantum + *q; + + register ssize_t + i, + x; + + size_t + extent, + length; + + ssize_t + count, + flags, + j, + version, + y; + + StringInfo + *profile; + + /* + 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 PICT header. + */ + read_info=(ImageInfo *) NULL; + tile_image=(Image *) NULL; + pixmap.bits_per_pixel=0; + pixmap.component_count=0; + /* + Skip header : 512 for standard PICT and 4, ie ""PICT"" for OLE2. + */ + header_ole[0]=ReadBlobByte(image); + header_ole[1]=ReadBlobByte(image); + header_ole[2]=ReadBlobByte(image); + header_ole[3]=ReadBlobByte(image); + if (!((header_ole[0] == 0x50) && (header_ole[1] == 0x49) && + (header_ole[2] == 0x43) && (header_ole[3] == 0x54 ))) + for (i=0; i < 508; i++) + if (ReadBlobByte(image) == EOF) + break; + (void) ReadBlobMSBShort(image); /* skip picture size */ + if (ReadRectangle(image,&frame) == MagickFalse) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + while ((c=ReadBlobByte(image)) == 0) ; + if (c != 0x11) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + version=(ssize_t) ReadBlobByte(image); + if (version == 2) + { + c=ReadBlobByte(image); + if (c != 0xff) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + } + else + if (version != 1) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + if ((frame.left < 0) || (frame.right < 0) || (frame.top < 0) || + (frame.bottom < 0) || (frame.left >= frame.right) || + (frame.top >= frame.bottom)) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + /* + Create black canvas. + */ + flags=0; + image->depth=8; + image->columns=(size_t) (frame.right-frame.left); + image->rows=(size_t) (frame.bottom-frame.top); + image->resolution.x=DefaultResolution; + image->resolution.y=DefaultResolution; + image->units=UndefinedResolution; + if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) + if (image->scene >= (image_info->scene+image_info->number_scenes-1)) + { + (void) CloseBlob(image); + return(GetFirstImageInList(image)); + } + status=SetImageExtent(image,image->columns,image->rows,exception); + if (status != MagickFalse) + status=ResetImagePixels(image,exception); + if (status == MagickFalse) + return(DestroyImageList(image)); + /* + Interpret PICT opcodes. + */ + jpeg=MagickFalse; + for (code=0; EOFBlob(image) == MagickFalse; ) + { + if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) + if (image->scene >= (image_info->scene+image_info->number_scenes-1)) + break; + if ((version == 1) || ((TellBlob(image) % 2) != 0)) + code=ReadBlobByte(image); + if (version == 2) + code=ReadBlobMSBSignedShort(image); + if (code < 0) + break; + if (code == 0) + continue; + if (code > 0xa1) + { + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(),""%04X:"",code); + } + else + { + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" %04X %s: %s"",code,codes[code].name,codes[code].description); + switch (code) + { + case 0x01: + { + /* + Clipping rectangle. + */ + length=ReadBlobMSBShort(image); + if (length != 0x000a) + { + for (i=0; i < (ssize_t) (length-2); i++) + if (ReadBlobByte(image) == EOF) + break; + break; + } + if (ReadRectangle(image,&frame) == MagickFalse) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + if (((frame.left & 0x8000) != 0) || ((frame.top & 0x8000) != 0)) + break; + image->columns=(size_t) (frame.right-frame.left); + image->rows=(size_t) (frame.bottom-frame.top); + status=SetImageExtent(image,image->columns,image->rows,exception); + if (status != MagickFalse) + status=ResetImagePixels(image,exception); + if (status == MagickFalse) + return(DestroyImageList(image)); + break; + } + case 0x12: + case 0x13: + case 0x14: + { + ssize_t + pattern; + + size_t + height, + width; + + /* + Skip pattern definition. + */ + pattern=(ssize_t) ReadBlobMSBShort(image); + for (i=0; i < 8; i++) + if (ReadBlobByte(image) == EOF) + break; + if (pattern == 2) + { + for (i=0; i < 5; i++) + if (ReadBlobByte(image) == EOF) + break; + break; + } + if (pattern != 1) + ThrowPICTException(CorruptImageError,""UnknownPatternType""); + length=ReadBlobMSBShort(image); + if (ReadRectangle(image,&frame) == MagickFalse) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + if (ReadPixmap(image,&pixmap) == MagickFalse) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + image->depth=(size_t) pixmap.component_size; + image->resolution.x=1.0*pixmap.horizontal_resolution; + image->resolution.y=1.0*pixmap.vertical_resolution; + image->units=PixelsPerInchResolution; + (void) ReadBlobMSBLong(image); + flags=(ssize_t) ReadBlobMSBShort(image); + length=ReadBlobMSBShort(image); + for (i=0; i <= (ssize_t) length; i++) + (void) ReadBlobMSBLong(image); + width=(size_t) (frame.bottom-frame.top); + height=(size_t) (frame.right-frame.left); + if (pixmap.bits_per_pixel <= 8) + length&=0x7fff; + if (pixmap.bits_per_pixel == 16) + width<<=1; + if (length == 0) + length=width; + if (length < 8) + { + for (i=0; i < (ssize_t) (length*height); i++) + if (ReadBlobByte(image) == EOF) + break; + } + else + for (i=0; i < (ssize_t) height; i++) + { + if (EOFBlob(image) != MagickFalse) + break; + if (length > 200) + { + for (j=0; j < (ssize_t) ReadBlobMSBShort(image); j++) + if (ReadBlobByte(image) == EOF) + break; + } + else + for (j=0; j < (ssize_t) ReadBlobByte(image); j++) + if (ReadBlobByte(image) == EOF) + break; + } + break; + } + case 0x1b: + { + /* + Initialize image background color. + */ + image->background_color.red=(Quantum) + ScaleShortToQuantum(ReadBlobMSBShort(image)); + image->background_color.green=(Quantum) + ScaleShortToQuantum(ReadBlobMSBShort(image)); + image->background_color.blue=(Quantum) + ScaleShortToQuantum(ReadBlobMSBShort(image)); + break; + } + case 0x70: + case 0x71: + case 0x72: + case 0x73: + case 0x74: + case 0x75: + case 0x76: + case 0x77: + { + /* + Skip polygon or region. + */ + length=ReadBlobMSBShort(image); + for (i=0; i < (ssize_t) (length-2); i++) + if (ReadBlobByte(image) == EOF) + break; + break; + } + case 0x90: + case 0x91: + case 0x98: + case 0x99: + case 0x9a: + case 0x9b: + { + PICTRectangle + source, + destination; + + register unsigned char + *p; + + size_t + j; + + ssize_t + bytes_per_line; + + unsigned char + *pixels; + + /* + Pixmap clipped by a rectangle. + */ + bytes_per_line=0; + if ((code != 0x9a) && (code != 0x9b)) + bytes_per_line=(ssize_t) ReadBlobMSBShort(image); + else + { + (void) ReadBlobMSBShort(image); + (void) ReadBlobMSBShort(image); + (void) ReadBlobMSBShort(image); + } + if (ReadRectangle(image,&frame) == MagickFalse) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + /* + Initialize tile image. + */ + tile_image=CloneImage(image,(size_t) (frame.right-frame.left), + (size_t) (frame.bottom-frame.top),MagickTrue,exception); + if (tile_image == (Image *) NULL) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + if ((code == 0x9a) || (code == 0x9b) || + ((bytes_per_line & 0x8000) != 0)) + { + if (ReadPixmap(image,&pixmap) == MagickFalse) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + tile_image->depth=(size_t) pixmap.component_size; + tile_image->alpha_trait=pixmap.component_count == 4 ? + BlendPixelTrait : UndefinedPixelTrait; + tile_image->resolution.x=(double) pixmap.horizontal_resolution; + tile_image->resolution.y=(double) pixmap.vertical_resolution; + tile_image->units=PixelsPerInchResolution; + if (tile_image->alpha_trait != UndefinedPixelTrait) + (void) SetImageAlpha(tile_image,OpaqueAlpha,exception); + } + if ((code != 0x9a) && (code != 0x9b)) + { + /* + Initialize colormap. + */ + tile_image->colors=2; + if ((bytes_per_line & 0x8000) != 0) + { + (void) ReadBlobMSBLong(image); + flags=(ssize_t) ReadBlobMSBShort(image); + tile_image->colors=1UL*ReadBlobMSBShort(image)+1; + } + status=AcquireImageColormap(tile_image,tile_image->colors, + exception); + if (status == MagickFalse) + ThrowPICTException(ResourceLimitError, + ""MemoryAllocationFailed""); + if ((bytes_per_line & 0x8000) != 0) + { + for (i=0; i < (ssize_t) tile_image->colors; i++) + { + j=ReadBlobMSBShort(image) % tile_image->colors; + if ((flags & 0x8000) != 0) + j=(size_t) i; + tile_image->colormap[j].red=(Quantum) + ScaleShortToQuantum(ReadBlobMSBShort(image)); + tile_image->colormap[j].green=(Quantum) + ScaleShortToQuantum(ReadBlobMSBShort(image)); + tile_image->colormap[j].blue=(Quantum) + ScaleShortToQuantum(ReadBlobMSBShort(image)); + } + } + else + { + for (i=0; i < (ssize_t) tile_image->colors; i++) + { + tile_image->colormap[i].red=(Quantum) (QuantumRange- + tile_image->colormap[i].red); + tile_image->colormap[i].green=(Quantum) (QuantumRange- + tile_image->colormap[i].green); + tile_image->colormap[i].blue=(Quantum) (QuantumRange- + tile_image->colormap[i].blue); + } + } + } + if (EOFBlob(image) != MagickFalse) + ThrowPICTException(CorruptImageError, + ""InsufficientImageDataInFile""); + if (ReadRectangle(image,&source) == MagickFalse) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + if (ReadRectangle(image,&destination) == MagickFalse) + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + (void) ReadBlobMSBShort(image); + if ((code == 0x91) || (code == 0x99) || (code == 0x9b)) + { + /* + Skip region. + */ + length=ReadBlobMSBShort(image); + for (i=0; i < (ssize_t) (length-2); i++) + if (ReadBlobByte(image) == EOF) + break; + } + if ((code != 0x9a) && (code != 0x9b) && + (bytes_per_line & 0x8000) == 0) + pixels=DecodeImage(image,tile_image,(size_t) bytes_per_line,1, + &extent); + else + pixels=DecodeImage(image,tile_image,(size_t) bytes_per_line, + (unsigned int) pixmap.bits_per_pixel,&extent); + if (pixels == (unsigned char *) NULL) + ThrowPICTException(CorruptImageError,""UnableToUncompressImage""); + /* + Convert PICT tile image to pixel packets. + */ + p=pixels; + for (y=0; y < (ssize_t) tile_image->rows; y++) + { + if (p > (pixels+extent+image->columns)) + { + pixels=(unsigned char *) RelinquishMagickMemory(pixels); + ThrowPICTException(CorruptImageError,""NotEnoughPixelData""); + } + q=QueueAuthenticPixels(tile_image,0,y,tile_image->columns,1, + exception); + if (q == (Quantum *) NULL) + break; + for (x=0; x < (ssize_t) tile_image->columns; x++) + { + if (tile_image->storage_class == PseudoClass) + { + index=(Quantum) ConstrainColormapIndex(tile_image,(ssize_t) + *p,exception); + SetPixelIndex(tile_image,index,q); + SetPixelRed(tile_image, + tile_image->colormap[(ssize_t) index].red,q); + SetPixelGreen(tile_image, + tile_image->colormap[(ssize_t) index].green,q); + SetPixelBlue(tile_image, + tile_image->colormap[(ssize_t) index].blue,q); + } + else + { + if (pixmap.bits_per_pixel == 16) + { + i=(ssize_t) (*p++); + j=(size_t) (*p); + SetPixelRed(tile_image,ScaleCharToQuantum( + (unsigned char) ((i & 0x7c) << 1)),q); + SetPixelGreen(tile_image,ScaleCharToQuantum( + (unsigned char) (((i & 0x03) << 6) | + ((j & 0xe0) >> 2))),q); + SetPixelBlue(tile_image,ScaleCharToQuantum( + (unsigned char) ((j & 0x1f) << 3)),q); + } + else + if (tile_image->alpha_trait == UndefinedPixelTrait) + { + if (p > (pixels+extent+2*image->columns)) + ThrowPICTException(CorruptImageError, + ""NotEnoughPixelData""); + SetPixelRed(tile_image,ScaleCharToQuantum(*p),q); + SetPixelGreen(tile_image,ScaleCharToQuantum( + *(p+tile_image->columns)),q); + SetPixelBlue(tile_image,ScaleCharToQuantum( + *(p+2*tile_image->columns)),q); + } + else + { + if (p > (pixels+extent+3*image->columns)) + ThrowPICTException(CorruptImageError, + ""NotEnoughPixelData""); + SetPixelAlpha(tile_image,ScaleCharToQuantum(*p),q); + SetPixelRed(tile_image,ScaleCharToQuantum( + *(p+tile_image->columns)),q); + SetPixelGreen(tile_image,ScaleCharToQuantum( + *(p+2*tile_image->columns)),q); + SetPixelBlue(tile_image,ScaleCharToQuantum( + *(p+3*tile_image->columns)),q); + } + } + p++; + q+=GetPixelChannels(tile_image); + } + if (SyncAuthenticPixels(tile_image,exception) == MagickFalse) + break; + if ((tile_image->storage_class == DirectClass) && + (pixmap.bits_per_pixel != 16)) + { + p+=(pixmap.component_count-1)*tile_image->columns; + if (p < pixels) + break; + } + status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, + tile_image->rows); + if (status == MagickFalse) + break; + } + pixels=(unsigned char *) RelinquishMagickMemory(pixels); + if ((jpeg == MagickFalse) && (EOFBlob(image) == MagickFalse)) + if ((code == 0x9a) || (code == 0x9b) || + ((bytes_per_line & 0x8000) != 0)) + (void) CompositeImage(image,tile_image,CopyCompositeOp, + MagickTrue,(ssize_t) destination.left,(ssize_t) + destination.top,exception); + tile_image=DestroyImage(tile_image); + break; + } + case 0xa1: + { + unsigned char + *info; + + size_t + type; + + /* + Comment. + */ + type=ReadBlobMSBShort(image); + length=ReadBlobMSBShort(image); + if (length == 0) + break; + (void) ReadBlobMSBLong(image); + length-=MagickMin(length,4); + if (length == 0) + break; + info=(unsigned char *) AcquireQuantumMemory(length,sizeof(*info)); + if (info == (unsigned char *) NULL) + break; + count=ReadBlob(image,length,info); + if (count != (ssize_t) length) + { + info=(unsigned char *) RelinquishMagickMemory(info); + ThrowPICTException(ResourceLimitError,""UnableToReadImageData""); + } + switch (type) + { + case 0xe0: + { + profile=BlobToStringInfo((const void *) NULL,length); + SetStringInfoDatum(profile,info); + status=SetImageProfile(image,""icc"",profile,exception); + profile=DestroyStringInfo(profile); + if (status == MagickFalse) + { + info=(unsigned char *) RelinquishMagickMemory(info); + ThrowPICTException(ResourceLimitError, + ""MemoryAllocationFailed""); + } + break; + } + case 0x1f2: + { + profile=BlobToStringInfo((const void *) NULL,length); + SetStringInfoDatum(profile,info); + status=SetImageProfile(image,""iptc"",profile,exception); + if (status == MagickFalse) + { + info=(unsigned char *) RelinquishMagickMemory(info); + ThrowPICTException(ResourceLimitError, + ""MemoryAllocationFailed""); + } + profile=DestroyStringInfo(profile); + break; + } + default: + break; + } + info=(unsigned char *) RelinquishMagickMemory(info); + break; + } + default: + { + /* + Skip to next op code. + */ + if (codes[code].length == -1) + (void) ReadBlobMSBShort(image); + else + for (i=0; i < (ssize_t) codes[code].length; i++) + if (ReadBlobByte(image) == EOF) + break; + } + } + } + if (code == 0xc00) + { + /* + Skip header. + */ + for (i=0; i < 24; i++) + if (ReadBlobByte(image) == EOF) + break; + continue; + } + if (((code >= 0xb0) && (code <= 0xcf)) || + ((code >= 0x8000) && (code <= 0x80ff))) + continue; + if (code == 0x8200) + { + char + filename[MaxTextExtent]; + + FILE + *file; + + int + unique_file; + + /* + Embedded JPEG. + */ + jpeg=MagickTrue; + read_info=CloneImageInfo(image_info); + SetImageInfoBlob(read_info,(void *) NULL,0); + file=(FILE *) NULL; + unique_file=AcquireUniqueFileResource(filename); + (void) FormatLocaleString(read_info->filename,MaxTextExtent,""jpeg:%s"", + filename); + if (unique_file != -1) + file=fdopen(unique_file,""wb""); + if ((unique_file == -1) || (file == (FILE *) NULL)) + { + (void) RelinquishUniqueFileResource(read_info->filename); + (void) CopyMagickString(image->filename,read_info->filename, + MagickPathExtent); + ThrowPICTException(FileOpenError,""UnableToCreateTemporaryFile""); + } + length=ReadBlobMSBLong(image); + if (length > 154) + { + for (i=0; i < 6; i++) + (void) ReadBlobMSBLong(image); + if (ReadRectangle(image,&frame) == MagickFalse) + { + (void) fclose(file); + (void) RelinquishUniqueFileResource(read_info->filename); + ThrowPICTException(CorruptImageError,""ImproperImageHeader""); + } + for (i=0; i < 122; i++) + if (ReadBlobByte(image) == EOF) + break; + for (i=0; i < (ssize_t) (length-154); i++) + { + c=ReadBlobByte(image); + if (c == EOF) + break; + if (fputc(c,file) != c) + break; + } + } + (void) fclose(file); + (void) close(unique_file); + tile_image=ReadImage(read_info,exception); + (void) RelinquishUniqueFileResource(filename); + read_info=DestroyImageInfo(read_info); + if (tile_image == (Image *) NULL) + continue; + (void) FormatLocaleString(geometry,MagickPathExtent,""%.20gx%.20g"", + (double) MagickMax(image->columns,tile_image->columns), + (double) MagickMax(image->rows,tile_image->rows)); + (void) SetImageExtent(image, + MagickMax(image->columns,tile_image->columns), + MagickMax(image->rows,tile_image->rows),exception); + (void) TransformImageColorspace(image,tile_image->colorspace,exception); + (void) CompositeImage(image,tile_image,CopyCompositeOp,MagickTrue, + (ssize_t) frame.left,(ssize_t) frame.right,exception); + image->compression=tile_image->compression; + tile_image=DestroyImage(tile_image); + continue; + } + if ((code == 0xff) || (code == 0xffff)) + break; + if (((code >= 0xd0) && (code <= 0xfe)) || + ((code >= 0x8100) && (code <= 0xffff))) + { + /* + Skip reserved. + */ + length=ReadBlobMSBShort(image); + for (i=0; i < (ssize_t) length; i++) + if (ReadBlobByte(image) == EOF) + break; + continue; + } + if ((code >= 0x100) && (code <= 0x7fff)) + { + /* + Skip reserved. + */ + length=(size_t) ((code >> 7) & 0xff); + for (i=0; i < (ssize_t) length; i++) + if (ReadBlobByte(image) == EOF) + break; + continue; + } + } + (void) CloseBlob(image); + return(GetFirstImageInList(image)); +} +","@@ -1472,7 +1472,8 @@ static Image *ReadPICTImage(const ImageInfo *image_info, + c=ReadBlobByte(image); + if (c == EOF) + break; +- (void) fputc(c,file); ++ if (fputc(c,file) != c) ++ break; + } + } + (void) fclose(file);",5895,6226,8192 +18346,"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+1) >= 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+1) >= 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); +} +",1,"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); +} +","@@ -1826,7 +1826,7 @@ static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image, + extent=(size_t) count; + (void) strncpy((char *) q,buffer,extent); + q+=extent; +- if ((q-pixels+extent+1) >= sizeof(pixels)) ++ if ((q-pixels+extent+2) >= sizeof(pixels)) + { + *q++='\n'; + (void) WriteBlob(image,q-pixels,pixels); +@@ -1901,7 +1901,7 @@ static MagickBooleanType WritePNMImage(const ImageInfo *image_info,Image *image, + extent=(size_t) count; + (void) strncpy((char *) q,buffer,extent); + q+=extent; +- if ((q-pixels+extent+1) >= sizeof(pixels)) ++ if ((q-pixels+extent+2) >= sizeof(pixels)) + { + *q++='\n'; + (void) WriteBlob(image,q-pixels,pixels);",7487,7818,8192 +17552,"WORD32 ih264d_start_of_pic(dec_struct_t *ps_dec, + WORD32 i4_poc, + pocstruct_t *ps_temp_poc, + UWORD16 u2_frame_num, + dec_pic_params_t *ps_pps) +{ + pocstruct_t *ps_prev_poc = &ps_dec->s_cur_pic_poc; + pocstruct_t *ps_cur_poc = ps_temp_poc; + + pic_buffer_t *pic_buf; + + ivd_video_decode_op_t * ps_dec_output = + (ivd_video_decode_op_t *)ps_dec->pv_dec_out; + dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice; + dec_seq_params_t *ps_seq = ps_pps->ps_sps; + UWORD8 u1_bottom_field_flag = ps_cur_slice->u1_bottom_field_flag; + UWORD8 u1_field_pic_flag = ps_cur_slice->u1_field_pic_flag; + /* high profile related declarations */ + high_profile_tools_t s_high_profile; + WORD32 ret; + + H264_MUTEX_LOCK(&ps_dec->process_disp_mutex); + + ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb; + ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb; + ps_prev_poc->i4_delta_pic_order_cnt_bottom = + ps_cur_poc->i4_delta_pic_order_cnt_bottom; + ps_prev_poc->i4_delta_pic_order_cnt[0] = + ps_cur_poc->i4_delta_pic_order_cnt[0]; + ps_prev_poc->i4_delta_pic_order_cnt[1] = + ps_cur_poc->i4_delta_pic_order_cnt[1]; + ps_prev_poc->u1_bot_field = ps_dec->ps_cur_slice->u1_bottom_field_flag; + ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst; + ps_prev_poc->u2_frame_num = u2_frame_num; + ps_dec->i1_prev_mb_qp_delta = 0; + ps_dec->i1_next_ctxt_idx = 0; + + + ps_dec->u4_nmb_deblk = 0; + if(ps_dec->u4_num_cores == 1) + ps_dec->u4_nmb_deblk = 1; + + + + if(ps_seq->u1_mb_aff_flag == 1) + { + ps_dec->u4_nmb_deblk = 0; + if(ps_dec->u4_num_cores > 2) + ps_dec->u4_num_cores = 2; + } + + ps_dec->u4_use_intrapred_line_copy = 0; + + + + if (ps_seq->u1_mb_aff_flag == 0) + { + ps_dec->u4_use_intrapred_line_copy = 1; + } + + ps_dec->u4_app_disable_deblk_frm = 0; + /* If degrade is enabled, set the degrade flags appropriately */ + if(ps_dec->i4_degrade_type && ps_dec->i4_degrade_pics) + { + WORD32 degrade_pic; + ps_dec->i4_degrade_pic_cnt++; + degrade_pic = 0; + + /* If degrade is to be done in all frames, then do not check further */ + switch(ps_dec->i4_degrade_pics) + { + case 4: + { + degrade_pic = 1; + break; + } + case 3: + { + if(ps_cur_slice->u1_slice_type != I_SLICE) + degrade_pic = 1; + + break; + } + case 2: + { + + /* If pic count hits non-degrade interval or it is an islice, then do not degrade */ + if((ps_cur_slice->u1_slice_type != I_SLICE) + && (ps_dec->i4_degrade_pic_cnt + != ps_dec->i4_nondegrade_interval)) + degrade_pic = 1; + + break; + } + case 1: + { + /* Check if the current picture is non-ref */ + if(0 == ps_cur_slice->u1_nal_ref_idc) + { + degrade_pic = 1; + } + break; + } + + } + if(degrade_pic) + { + if(ps_dec->i4_degrade_type & 0x2) + ps_dec->u4_app_disable_deblk_frm = 1; + + /* MC degrading is done only for non-ref pictures */ + if(0 == ps_cur_slice->u1_nal_ref_idc) + { + if(ps_dec->i4_degrade_type & 0x4) + ps_dec->i4_mv_frac_mask = 0; + + if(ps_dec->i4_degrade_type & 0x8) + ps_dec->i4_mv_frac_mask = 0; + } + } + else + ps_dec->i4_degrade_pic_cnt = 0; + } + + { + dec_err_status_t * ps_err = ps_dec->ps_dec_err_status; + if(ps_dec->u1_sl_typ_5_9 + && ((ps_cur_slice->u1_slice_type == I_SLICE) + || (ps_cur_slice->u1_slice_type + == SI_SLICE))) + ps_err->u1_cur_pic_type = PIC_TYPE_I; + else + ps_err->u1_cur_pic_type = PIC_TYPE_UNKNOWN; + + if(ps_err->u1_pic_aud_i == PIC_TYPE_I) + { + ps_err->u1_cur_pic_type = PIC_TYPE_I; + ps_err->u1_pic_aud_i = PIC_TYPE_UNKNOWN; + } + + if(ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL) + { + if(ps_err->u1_err_flag) + ih264d_reset_ref_bufs(ps_dec->ps_dpb_mgr); + ps_err->u1_err_flag = ACCEPT_ALL_PICS; + } + } + + if(ps_dec->u1_init_dec_flag && ps_dec->s_prev_seq_params.u1_eoseq_pending) + { + /* Reset the decoder picture buffers */ + WORD32 j; + for(j = 0; j < MAX_DISP_BUFS_NEW; j++) + { + + ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, + j, + BUF_MGR_REF); + ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_mv_buf_mgr, + ps_dec->au1_pic_buf_id_mv_buf_id_map[j], + BUF_MGR_REF); + ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, + j, + BUF_MGR_IO); + } + + /* reset the decoder structure parameters related to buffer handling */ + ps_dec->u1_second_field = 0; + ps_dec->i4_cur_display_seq = 0; + + /********************************************************************/ + /* indicate in the decoder output i4_status that some frames are being */ + /* dropped, so that it resets timestamp and wait for a new sequence */ + /********************************************************************/ + + ps_dec->s_prev_seq_params.u1_eoseq_pending = 0; + } + ret = ih264d_init_pic(ps_dec, u2_frame_num, i4_poc, ps_pps); + if(ret != OK) + return ret; + + ps_dec->pv_parse_tu_coeff_data = ps_dec->pv_pic_tu_coeff_data; + ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_pic_tu_coeff_data; + ps_dec->ps_nmb_info = ps_dec->ps_frm_mb_info; + if(ps_dec->u1_separate_parse) + { + UWORD16 pic_wd = ps_dec->u4_width_at_init; + UWORD16 pic_ht = ps_dec->u4_height_at_init; + UWORD32 num_mbs; + + if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) + { + pic_wd = ps_dec->u2_pic_wd; + pic_ht = ps_dec->u2_pic_ht; + } + num_mbs = (pic_wd * pic_ht) >> 8; + + if(ps_dec->pu1_dec_mb_map) + { + memset((void *)ps_dec->pu1_dec_mb_map, 0, num_mbs); + } + + if(ps_dec->pu1_recon_mb_map) + { + + memset((void *)ps_dec->pu1_recon_mb_map, 0, num_mbs); + } + + if(ps_dec->pu2_slice_num_map) + { + memset((void *)ps_dec->pu2_slice_num_map, 0, + (num_mbs * sizeof(UWORD16))); + } + + } + + ps_dec->ps_parse_cur_slice = &(ps_dec->ps_dec_slice_buf[0]); + ps_dec->ps_decode_cur_slice = &(ps_dec->ps_dec_slice_buf[0]); + ps_dec->ps_computebs_cur_slice = &(ps_dec->ps_dec_slice_buf[0]); + ps_dec->u2_cur_slice_num = 0; + + /* Initialize all the HP toolsets to zero */ + ps_dec->s_high_profile.u1_scaling_present = 0; + ps_dec->s_high_profile.u1_transform8x8_present = 0; + + /* Get Next Free Picture */ + if(1 == ps_dec->u4_share_disp_buf) + { + UWORD32 i; + /* Free any buffer that is in the queue to be freed */ + for(i = 0; i < MAX_DISP_BUFS_NEW; i++) + { + if(0 == ps_dec->u4_disp_buf_to_be_freed[i]) + continue; + ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, i, + BUF_MGR_IO); + ps_dec->u4_disp_buf_to_be_freed[i] = 0; + ps_dec->u4_disp_buf_mapping[i] = 0; + + } + } + if(!(u1_field_pic_flag && 0 != ps_dec->u1_top_bottom_decoded)) //ps_dec->u1_second_field)) + { + pic_buffer_t *ps_cur_pic; + WORD32 cur_pic_buf_id, cur_mv_buf_id; + col_mv_buf_t *ps_col_mv; + while(1) + { + ps_cur_pic = (pic_buffer_t *)ih264_buf_mgr_get_next_free( + (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, + &cur_pic_buf_id); + if(ps_cur_pic == NULL) + { + ps_dec->i4_error_code = ERROR_UNAVAIL_PICBUF_T; + return ERROR_UNAVAIL_PICBUF_T; + } + if(0 == ps_dec->u4_disp_buf_mapping[cur_pic_buf_id]) + { + break; + } + + } + ps_col_mv = (col_mv_buf_t *)ih264_buf_mgr_get_next_free((buf_mgr_t *)ps_dec->pv_mv_buf_mgr, + &cur_mv_buf_id); + if(ps_col_mv == NULL) + { + ps_dec->i4_error_code = ERROR_UNAVAIL_MVBUF_T; + return ERROR_UNAVAIL_MVBUF_T; + } + + ps_dec->ps_cur_pic = ps_cur_pic; + ps_dec->u1_pic_buf_id = cur_pic_buf_id; + ps_cur_pic->u4_ts = ps_dec->u4_ts; + + + ps_cur_pic->u1_mv_buf_id = cur_mv_buf_id; + ps_dec->au1_pic_buf_id_mv_buf_id_map[cur_pic_buf_id] = cur_mv_buf_id; + + ps_cur_pic->pu1_col_zero_flag = (UWORD8 *)ps_col_mv->pv_col_zero_flag; + ps_cur_pic->ps_mv = (mv_pred_t *)ps_col_mv->pv_mv; + ps_dec->au1_pic_buf_ref_flag[cur_pic_buf_id] = 0; + if(ps_dec->u1_first_slice_in_stream) + { + /*make first entry of list0 point to cur pic,so that if first Islice is in error, ref pic struct will have valid entries*/ + ps_dec->ps_ref_pic_buf_lx[0] = ps_dec->ps_dpb_mgr->ps_init_dpb[0]; + *(ps_dec->ps_dpb_mgr->ps_init_dpb[0][0]) = *ps_cur_pic; + /* Initialize for field reference as well */ + *(ps_dec->ps_dpb_mgr->ps_init_dpb[0][MAX_REF_BUFS]) = *ps_cur_pic; + } + + if(!ps_dec->ps_cur_pic) + { + WORD32 j; + H264_DEC_DEBUG_PRINT(""------- Display Buffers Reset --------\n""); + for(j = 0; j < MAX_DISP_BUFS_NEW; j++) + { + + ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, + j, + BUF_MGR_REF); + ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_mv_buf_mgr, + ps_dec->au1_pic_buf_id_mv_buf_id_map[j], + BUF_MGR_REF); + ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, + j, + BUF_MGR_IO); + } + + ps_dec->i4_cur_display_seq = 0; + ps_dec->i4_prev_max_display_seq = 0; + ps_dec->i4_max_poc = 0; + + ps_cur_pic = (pic_buffer_t *)ih264_buf_mgr_get_next_free( + (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, + &cur_pic_buf_id); + if(ps_cur_pic == NULL) + { + ps_dec->i4_error_code = ERROR_UNAVAIL_PICBUF_T; + return ERROR_UNAVAIL_PICBUF_T; + } + + ps_col_mv = (col_mv_buf_t *)ih264_buf_mgr_get_next_free((buf_mgr_t *)ps_dec->pv_mv_buf_mgr, + &cur_mv_buf_id); + if(ps_col_mv == NULL) + { + ps_dec->i4_error_code = ERROR_UNAVAIL_MVBUF_T; + return ERROR_UNAVAIL_MVBUF_T; + } + + ps_dec->ps_cur_pic = ps_cur_pic; + ps_dec->u1_pic_buf_id = cur_pic_buf_id; + ps_cur_pic->u4_ts = ps_dec->u4_ts; + ps_dec->apv_buf_id_pic_buf_map[cur_pic_buf_id] = (void *)ps_cur_pic; + + ps_cur_pic->u1_mv_buf_id = cur_mv_buf_id; + ps_dec->au1_pic_buf_id_mv_buf_id_map[cur_pic_buf_id] = cur_mv_buf_id; + + ps_cur_pic->pu1_col_zero_flag = (UWORD8 *)ps_col_mv->pv_col_zero_flag; + ps_cur_pic->ps_mv = (mv_pred_t *)ps_col_mv->pv_mv; + ps_dec->au1_pic_buf_ref_flag[cur_pic_buf_id] = 0; + + } + + ps_dec->ps_cur_pic->u1_picturetype = u1_field_pic_flag; + ps_dec->ps_cur_pic->u4_pack_slc_typ = SKIP_NONE; + H264_DEC_DEBUG_PRINT(""got a buffer\n""); + } + else + { + H264_DEC_DEBUG_PRINT(""did not get a buffer\n""); + } + + ps_dec->u4_pic_buf_got = 1; + + ps_dec->ps_cur_pic->i4_poc = i4_poc; + ps_dec->ps_cur_pic->i4_frame_num = u2_frame_num; + ps_dec->ps_cur_pic->i4_pic_num = u2_frame_num; + ps_dec->ps_cur_pic->i4_top_field_order_cnt = ps_pps->i4_top_field_order_cnt; + ps_dec->ps_cur_pic->i4_bottom_field_order_cnt = + ps_pps->i4_bottom_field_order_cnt; + ps_dec->ps_cur_pic->i4_avg_poc = ps_pps->i4_avg_poc; + ps_dec->ps_cur_pic->u4_time_stamp = ps_dec->u4_pts; + + ps_dec->s_cur_pic = *(ps_dec->ps_cur_pic); + if(u1_field_pic_flag && u1_bottom_field_flag) + { + WORD32 i4_temp_poc; + WORD32 i4_top_field_order_poc, i4_bot_field_order_poc; + /* Point to odd lines, since it's bottom field */ + ps_dec->s_cur_pic.pu1_buf1 += ps_dec->s_cur_pic.u2_frm_wd_y; + ps_dec->s_cur_pic.pu1_buf2 += ps_dec->s_cur_pic.u2_frm_wd_uv; + ps_dec->s_cur_pic.pu1_buf3 += ps_dec->s_cur_pic.u2_frm_wd_uv; + ps_dec->s_cur_pic.ps_mv += + ((ps_dec->u2_pic_ht * ps_dec->u2_pic_wd) >> 5); + ps_dec->s_cur_pic.pu1_col_zero_flag += ((ps_dec->u2_pic_ht + * ps_dec->u2_pic_wd) >> 5); + ps_dec->ps_cur_pic->u1_picturetype |= BOT_FLD; + i4_top_field_order_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt; + i4_bot_field_order_poc = ps_dec->ps_cur_pic->i4_bottom_field_order_cnt; + i4_temp_poc = MIN(i4_top_field_order_poc, + i4_bot_field_order_poc); + ps_dec->ps_cur_pic->i4_avg_poc = i4_temp_poc; + } + + ps_cur_slice->u1_mbaff_frame_flag = ps_seq->u1_mb_aff_flag + && (!u1_field_pic_flag); + + ps_dec->ps_cur_pic->u1_picturetype |= (ps_cur_slice->u1_mbaff_frame_flag + << 2); + + ps_dec->ps_cur_mb_row = ps_dec->ps_nbr_mb_row; //[0]; + ps_dec->ps_cur_mb_row++; //Increment by 1 ,so that left mb will always be valid + ps_dec->ps_top_mb_row = + ps_dec->ps_nbr_mb_row + + ((ps_dec->u2_frm_wd_in_mbs + 1) + << (1 + - ps_dec->ps_cur_sps->u1_frame_mbs_only_flag)); + ps_dec->ps_top_mb_row++; //Increment by 1 ,so that left mb will always be valid + + ps_dec->pu1_y = ps_dec->pu1_y_scratch[0]; + ps_dec->pu1_u = ps_dec->pu1_u_scratch[0]; + ps_dec->pu1_v = ps_dec->pu1_v_scratch[0]; + ps_dec->u1_yuv_scratch_idx = 0; + /* CHANGED CODE */ + ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv; + ps_dec->ps_mv_top = ps_dec->ps_mv_top_p[0]; + /* CHANGED CODE */ + ps_dec->u1_mv_top_p = 0; + ps_dec->u1_mb_idx = 0; + /* CHANGED CODE */ + ps_dec->ps_mv_left = ps_dec->s_cur_pic.ps_mv; + ps_dec->pu1_yleft = 0; + ps_dec->pu1_uleft = 0; + ps_dec->pu1_vleft = 0; + ps_dec->u1_not_wait_rec = 2; + ps_dec->u2_total_mbs_coded = 0; + ps_dec->i4_submb_ofst = -(SUB_BLK_SIZE); + ps_dec->u4_pred_info_idx = 0; + ps_dec->u4_pred_info_pkd_idx = 0; + ps_dec->u4_dma_buf_idx = 0; + ps_dec->ps_mv = ps_dec->s_cur_pic.ps_mv; + ps_dec->ps_mv_bank_cur = ps_dec->s_cur_pic.ps_mv; + ps_dec->pu1_col_zero_flag = ps_dec->s_cur_pic.pu1_col_zero_flag; + ps_dec->ps_part = ps_dec->ps_parse_part_params; + ps_dec->i2_prev_slice_mbx = -1; + ps_dec->i2_prev_slice_mby = 0; + ps_dec->u2_mv_2mb[0] = 0; + ps_dec->u2_mv_2mb[1] = 0; + ps_dec->u1_last_pic_not_decoded = 0; + + ps_dec->u2_cur_slice_num_dec_thread = 0; + ps_dec->u2_cur_slice_num_bs = 0; + ps_dec->u4_intra_pred_line_ofst = 0; + ps_dec->pu1_cur_y_intra_pred_line = ps_dec->pu1_y_intra_pred_line; + ps_dec->pu1_cur_u_intra_pred_line = ps_dec->pu1_u_intra_pred_line; + ps_dec->pu1_cur_v_intra_pred_line = ps_dec->pu1_v_intra_pred_line; + + ps_dec->pu1_cur_y_intra_pred_line_base = ps_dec->pu1_y_intra_pred_line; + ps_dec->pu1_cur_u_intra_pred_line_base = ps_dec->pu1_u_intra_pred_line; + ps_dec->pu1_cur_v_intra_pred_line_base = ps_dec->pu1_v_intra_pred_line; + + + + + + ps_dec->pu1_prev_y_intra_pred_line = ps_dec->pu1_y_intra_pred_line + + (ps_dec->u2_frm_wd_in_mbs * MB_SIZE); + + ps_dec->pu1_prev_u_intra_pred_line = ps_dec->pu1_u_intra_pred_line + + ps_dec->u2_frm_wd_in_mbs * BLK8x8SIZE * YUV420SP_FACTOR; + ps_dec->pu1_prev_v_intra_pred_line = ps_dec->pu1_v_intra_pred_line + + ps_dec->u2_frm_wd_in_mbs * BLK8x8SIZE; + + ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic; + ps_dec->ps_deblk_mbn_curr = ps_dec->ps_deblk_mbn; + ps_dec->ps_deblk_mbn_prev = ps_dec->ps_deblk_mbn + ps_dec->u1_recon_mb_grp; + /* Initialize The Function Pointer Depending Upon the Entropy and MbAff Flag */ + { + if(ps_cur_slice->u1_mbaff_frame_flag) + { + ps_dec->pf_compute_bs = ih264d_compute_bs_mbaff; + ps_dec->pf_mvpred = ih264d_mvpred_mbaff; + } + else + { + ps_dec->pf_compute_bs = ih264d_compute_bs_non_mbaff; + ps_dec->u1_cur_mb_fld_dec_flag = ps_cur_slice->u1_field_pic_flag; + } + } + /* Set up the Parameter for DMA transfer */ + { + UWORD8 u1_field_pic_flag = ps_dec->ps_cur_slice->u1_field_pic_flag; + + UWORD8 u1_mbaff = ps_cur_slice->u1_mbaff_frame_flag; + + UWORD8 uc_lastmbs = (((ps_dec->u2_pic_wd) >> 4) + % (ps_dec->u1_recon_mb_grp >> u1_mbaff)); + UWORD16 ui16_lastmbs_widthY = + (uc_lastmbs ? (uc_lastmbs << 4) : ((ps_dec->u1_recon_mb_grp + >> u1_mbaff) << 4)); + UWORD16 ui16_lastmbs_widthUV = + uc_lastmbs ? (uc_lastmbs << 3) : ((ps_dec->u1_recon_mb_grp + >> u1_mbaff) << 3); + + ps_dec->s_tran_addrecon.pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1; + ps_dec->s_tran_addrecon.pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2; + ps_dec->s_tran_addrecon.pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3; + + ps_dec->s_tran_addrecon.u2_frm_wd_y = ps_dec->u2_frm_wd_y + << u1_field_pic_flag; + ps_dec->s_tran_addrecon.u2_frm_wd_uv = ps_dec->u2_frm_wd_uv + << u1_field_pic_flag; + + if(u1_field_pic_flag) + { + ui16_lastmbs_widthY += ps_dec->u2_frm_wd_y; + ui16_lastmbs_widthUV += ps_dec->u2_frm_wd_uv; + } + + /* Normal Increment of Pointer */ + ps_dec->s_tran_addrecon.u4_inc_y[0] = ((ps_dec->u1_recon_mb_grp << 4) + >> u1_mbaff); + ps_dec->s_tran_addrecon.u4_inc_uv[0] = ((ps_dec->u1_recon_mb_grp << 4) + >> u1_mbaff); + + /* End of Row Increment */ + ps_dec->s_tran_addrecon.u4_inc_y[1] = (ui16_lastmbs_widthY + + (PAD_LEN_Y_H << 1) + + ps_dec->s_tran_addrecon.u2_frm_wd_y + * ((15 << u1_mbaff) + u1_mbaff)); + ps_dec->s_tran_addrecon.u4_inc_uv[1] = (ui16_lastmbs_widthUV + + (PAD_LEN_UV_H << 2) + + ps_dec->s_tran_addrecon.u2_frm_wd_uv + * ((15 << u1_mbaff) + u1_mbaff)); + + /* Assign picture numbers to each frame/field */ + /* only once per picture. */ + ih264d_assign_pic_num(ps_dec); + ps_dec->s_tran_addrecon.u2_mv_top_left_inc = (ps_dec->u1_recon_mb_grp + << 2) - 1 - (u1_mbaff << 2); + ps_dec->s_tran_addrecon.u2_mv_left_inc = ((ps_dec->u1_recon_mb_grp + >> u1_mbaff) - 1) << (4 + u1_mbaff); + } + /**********************************************************************/ + /* High profile related initialization at pictrue level */ + /**********************************************************************/ + if(ps_seq->u1_profile_idc == HIGH_PROFILE_IDC) + { + if((ps_seq->i4_seq_scaling_matrix_present_flag) + || (ps_pps->i4_pic_scaling_matrix_present_flag)) + { + ih264d_form_scaling_matrix_picture(ps_seq, ps_pps, ps_dec); + ps_dec->s_high_profile.u1_scaling_present = 1; + } + else + { + ih264d_form_default_scaling_matrix(ps_dec); + } + + if(ps_pps->i4_transform_8x8_mode_flag) + { + ps_dec->s_high_profile.u1_transform8x8_present = 1; + } + } + else + { + ih264d_form_default_scaling_matrix(ps_dec); + } + + /* required while reading the transform_size_8x8 u4_flag */ + ps_dec->s_high_profile.u1_direct_8x8_inference_flag = + ps_seq->u1_direct_8x8_inference_flag; + ps_dec->s_high_profile.s_cavlc_ctxt = ps_dec->s_cavlc_ctxt; + + ps_dec->i1_recon_in_thread3_flag = 1; + ps_dec->ps_frame_buf_ip_recon = &ps_dec->s_tran_addrecon; + if(ps_dec->u1_separate_parse) + { + memcpy(&ps_dec->s_tran_addrecon_parse, &ps_dec->s_tran_addrecon, + sizeof(tfr_ctxt_t)); + if(ps_dec->u4_num_cores >= 3 && ps_dec->i1_recon_in_thread3_flag) + { + memcpy(&ps_dec->s_tran_iprecon, &ps_dec->s_tran_addrecon, + sizeof(tfr_ctxt_t)); + ps_dec->ps_frame_buf_ip_recon = &ps_dec->s_tran_iprecon; + } + } + + + ih264d_init_deblk_tfr_ctxt(ps_dec,&(ps_dec->s_pad_mgr), &(ps_dec->s_tran_addrecon), + ps_dec->u2_frm_wd_in_mbs, 0); + + ps_dec->ps_cur_deblk_mb = ps_dec->ps_deblk_pic; + ps_dec->u4_cur_deblk_mb_num = 0; + + ps_dec->u4_deblk_mb_x = 0; + ps_dec->u4_deblk_mb_y = 0; + ps_dec->pu4_wt_ofsts = ps_dec->pu4_wts_ofsts_mat; + + H264_MUTEX_UNLOCK(&ps_dec->process_disp_mutex); + return OK; +} +",0,"WORD32 ih264d_start_of_pic(dec_struct_t *ps_dec, + WORD32 i4_poc, + pocstruct_t *ps_temp_poc, + UWORD16 u2_frame_num, + dec_pic_params_t *ps_pps) +{ + pocstruct_t *ps_prev_poc = &ps_dec->s_cur_pic_poc; + pocstruct_t *ps_cur_poc = ps_temp_poc; + + pic_buffer_t *pic_buf; + + ivd_video_decode_op_t * ps_dec_output = + (ivd_video_decode_op_t *)ps_dec->pv_dec_out; + dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice; + dec_seq_params_t *ps_seq = ps_pps->ps_sps; + UWORD8 u1_bottom_field_flag = ps_cur_slice->u1_bottom_field_flag; + UWORD8 u1_field_pic_flag = ps_cur_slice->u1_field_pic_flag; + /* high profile related declarations */ + high_profile_tools_t s_high_profile; + WORD32 ret; + + H264_MUTEX_LOCK(&ps_dec->process_disp_mutex); + + ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb; + ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb; + ps_prev_poc->i4_delta_pic_order_cnt_bottom = + ps_cur_poc->i4_delta_pic_order_cnt_bottom; + ps_prev_poc->i4_delta_pic_order_cnt[0] = + ps_cur_poc->i4_delta_pic_order_cnt[0]; + ps_prev_poc->i4_delta_pic_order_cnt[1] = + ps_cur_poc->i4_delta_pic_order_cnt[1]; + ps_prev_poc->u1_bot_field = ps_dec->ps_cur_slice->u1_bottom_field_flag; + ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst; + ps_prev_poc->u2_frame_num = u2_frame_num; + ps_dec->i1_prev_mb_qp_delta = 0; + ps_dec->i1_next_ctxt_idx = 0; + + + ps_dec->u4_nmb_deblk = 0; + if(ps_dec->u4_num_cores == 1) + ps_dec->u4_nmb_deblk = 1; + + + + if(ps_seq->u1_mb_aff_flag == 1) + { + ps_dec->u4_nmb_deblk = 0; + if(ps_dec->u4_num_cores > 2) + ps_dec->u4_num_cores = 2; + } + + ps_dec->u4_use_intrapred_line_copy = 0; + + + + if (ps_seq->u1_mb_aff_flag == 0) + { + ps_dec->u4_use_intrapred_line_copy = 1; + } + + ps_dec->u4_app_disable_deblk_frm = 0; + /* If degrade is enabled, set the degrade flags appropriately */ + if(ps_dec->i4_degrade_type && ps_dec->i4_degrade_pics) + { + WORD32 degrade_pic; + ps_dec->i4_degrade_pic_cnt++; + degrade_pic = 0; + + /* If degrade is to be done in all frames, then do not check further */ + switch(ps_dec->i4_degrade_pics) + { + case 4: + { + degrade_pic = 1; + break; + } + case 3: + { + if(ps_cur_slice->u1_slice_type != I_SLICE) + degrade_pic = 1; + + break; + } + case 2: + { + + /* If pic count hits non-degrade interval or it is an islice, then do not degrade */ + if((ps_cur_slice->u1_slice_type != I_SLICE) + && (ps_dec->i4_degrade_pic_cnt + != ps_dec->i4_nondegrade_interval)) + degrade_pic = 1; + + break; + } + case 1: + { + /* Check if the current picture is non-ref */ + if(0 == ps_cur_slice->u1_nal_ref_idc) + { + degrade_pic = 1; + } + break; + } + + } + if(degrade_pic) + { + if(ps_dec->i4_degrade_type & 0x2) + ps_dec->u4_app_disable_deblk_frm = 1; + + /* MC degrading is done only for non-ref pictures */ + if(0 == ps_cur_slice->u1_nal_ref_idc) + { + if(ps_dec->i4_degrade_type & 0x4) + ps_dec->i4_mv_frac_mask = 0; + + if(ps_dec->i4_degrade_type & 0x8) + ps_dec->i4_mv_frac_mask = 0; + } + } + else + ps_dec->i4_degrade_pic_cnt = 0; + } + + { + dec_err_status_t * ps_err = ps_dec->ps_dec_err_status; + if(ps_dec->u1_sl_typ_5_9 + && ((ps_cur_slice->u1_slice_type == I_SLICE) + || (ps_cur_slice->u1_slice_type + == SI_SLICE))) + ps_err->u1_cur_pic_type = PIC_TYPE_I; + else + ps_err->u1_cur_pic_type = PIC_TYPE_UNKNOWN; + + if(ps_err->u1_pic_aud_i == PIC_TYPE_I) + { + ps_err->u1_cur_pic_type = PIC_TYPE_I; + ps_err->u1_pic_aud_i = PIC_TYPE_UNKNOWN; + } + + if(ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL) + { + if(ps_err->u1_err_flag) + ih264d_reset_ref_bufs(ps_dec->ps_dpb_mgr); + ps_err->u1_err_flag = ACCEPT_ALL_PICS; + } + } + + if(ps_dec->u1_init_dec_flag && ps_dec->s_prev_seq_params.u1_eoseq_pending) + { + /* Reset the decoder picture buffers */ + WORD32 j; + for(j = 0; j < MAX_DISP_BUFS_NEW; j++) + { + + ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, + j, + BUF_MGR_REF); + ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_mv_buf_mgr, + ps_dec->au1_pic_buf_id_mv_buf_id_map[j], + BUF_MGR_REF); + ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, + j, + BUF_MGR_IO); + } + + /* reset the decoder structure parameters related to buffer handling */ + ps_dec->u1_second_field = 0; + ps_dec->i4_cur_display_seq = 0; + + /********************************************************************/ + /* indicate in the decoder output i4_status that some frames are being */ + /* dropped, so that it resets timestamp and wait for a new sequence */ + /********************************************************************/ + + ps_dec->s_prev_seq_params.u1_eoseq_pending = 0; + } + ret = ih264d_init_pic(ps_dec, u2_frame_num, i4_poc, ps_pps); + if(ret != OK) + return ret; + + ps_dec->pv_parse_tu_coeff_data = ps_dec->pv_pic_tu_coeff_data; + ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_pic_tu_coeff_data; + ps_dec->ps_nmb_info = ps_dec->ps_frm_mb_info; + if(ps_dec->u1_separate_parse) + { + UWORD16 pic_wd = ps_dec->u4_width_at_init; + UWORD16 pic_ht = ps_dec->u4_height_at_init; + UWORD32 num_mbs; + + if((NULL != ps_dec->ps_cur_sps) && (1 == (ps_dec->ps_cur_sps->u1_is_valid))) + { + pic_wd = ps_dec->u2_pic_wd; + pic_ht = ps_dec->u2_pic_ht; + } + num_mbs = (pic_wd * pic_ht) >> 8; + + if(ps_dec->pu1_dec_mb_map) + { + memset((void *)ps_dec->pu1_dec_mb_map, 0, num_mbs); + } + + if(ps_dec->pu1_recon_mb_map) + { + + memset((void *)ps_dec->pu1_recon_mb_map, 0, num_mbs); + } + + if(ps_dec->pu2_slice_num_map) + { + memset((void *)ps_dec->pu2_slice_num_map, 0, + (num_mbs * sizeof(UWORD16))); + } + + } + + ps_dec->ps_parse_cur_slice = &(ps_dec->ps_dec_slice_buf[0]); + ps_dec->ps_decode_cur_slice = &(ps_dec->ps_dec_slice_buf[0]); + ps_dec->ps_computebs_cur_slice = &(ps_dec->ps_dec_slice_buf[0]); + ps_dec->u2_cur_slice_num = 0; + + /* Initialize all the HP toolsets to zero */ + ps_dec->s_high_profile.u1_scaling_present = 0; + ps_dec->s_high_profile.u1_transform8x8_present = 0; + + /* Get Next Free Picture */ + if(1 == ps_dec->u4_share_disp_buf) + { + UWORD32 i; + /* Free any buffer that is in the queue to be freed */ + for(i = 0; i < MAX_DISP_BUFS_NEW; i++) + { + if(0 == ps_dec->u4_disp_buf_to_be_freed[i]) + continue; + ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, i, + BUF_MGR_IO); + ps_dec->u4_disp_buf_to_be_freed[i] = 0; + ps_dec->u4_disp_buf_mapping[i] = 0; + + } + } + if(!(u1_field_pic_flag && 0 != ps_dec->u1_top_bottom_decoded)) //ps_dec->u1_second_field)) + { + pic_buffer_t *ps_cur_pic; + WORD32 cur_pic_buf_id, cur_mv_buf_id; + col_mv_buf_t *ps_col_mv; + while(1) + { + ps_cur_pic = (pic_buffer_t *)ih264_buf_mgr_get_next_free( + (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, + &cur_pic_buf_id); + if(ps_cur_pic == NULL) + { + ps_dec->i4_error_code = ERROR_UNAVAIL_PICBUF_T; + return ERROR_UNAVAIL_PICBUF_T; + } + if(0 == ps_dec->u4_disp_buf_mapping[cur_pic_buf_id]) + { + break; + } + + } + ps_col_mv = (col_mv_buf_t *)ih264_buf_mgr_get_next_free((buf_mgr_t *)ps_dec->pv_mv_buf_mgr, + &cur_mv_buf_id); + if(ps_col_mv == NULL) + { + ps_dec->i4_error_code = ERROR_UNAVAIL_MVBUF_T; + return ERROR_UNAVAIL_MVBUF_T; + } + + ps_dec->ps_cur_pic = ps_cur_pic; + ps_dec->u1_pic_buf_id = cur_pic_buf_id; + ps_cur_pic->u4_ts = ps_dec->u4_ts; + + + ps_cur_pic->u1_mv_buf_id = cur_mv_buf_id; + ps_dec->au1_pic_buf_id_mv_buf_id_map[cur_pic_buf_id] = cur_mv_buf_id; + + ps_cur_pic->pu1_col_zero_flag = (UWORD8 *)ps_col_mv->pv_col_zero_flag; + ps_cur_pic->ps_mv = (mv_pred_t *)ps_col_mv->pv_mv; + ps_dec->au1_pic_buf_ref_flag[cur_pic_buf_id] = 0; + if(ps_dec->u1_first_slice_in_stream) + { + /*make first entry of list0 point to cur pic,so that if first Islice is in error, ref pic struct will have valid entries*/ + ps_dec->ps_ref_pic_buf_lx[0] = ps_dec->ps_dpb_mgr->ps_init_dpb[0]; + *(ps_dec->ps_dpb_mgr->ps_init_dpb[0][0]) = *ps_cur_pic; + /* Initialize for field reference as well */ + *(ps_dec->ps_dpb_mgr->ps_init_dpb[0][MAX_REF_BUFS]) = *ps_cur_pic; + } + + if(!ps_dec->ps_cur_pic) + { + WORD32 j; + H264_DEC_DEBUG_PRINT(""------- Display Buffers Reset --------\n""); + for(j = 0; j < MAX_DISP_BUFS_NEW; j++) + { + + ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, + j, + BUF_MGR_REF); + ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_mv_buf_mgr, + ps_dec->au1_pic_buf_id_mv_buf_id_map[j], + BUF_MGR_REF); + ih264_buf_mgr_release((buf_mgr_t *)ps_dec->pv_pic_buf_mgr, + j, + BUF_MGR_IO); + } + + ps_dec->i4_cur_display_seq = 0; + ps_dec->i4_prev_max_display_seq = 0; + ps_dec->i4_max_poc = 0; + + ps_cur_pic = (pic_buffer_t *)ih264_buf_mgr_get_next_free( + (buf_mgr_t *)ps_dec->pv_pic_buf_mgr, + &cur_pic_buf_id); + if(ps_cur_pic == NULL) + { + ps_dec->i4_error_code = ERROR_UNAVAIL_PICBUF_T; + return ERROR_UNAVAIL_PICBUF_T; + } + + ps_col_mv = (col_mv_buf_t *)ih264_buf_mgr_get_next_free((buf_mgr_t *)ps_dec->pv_mv_buf_mgr, + &cur_mv_buf_id); + if(ps_col_mv == NULL) + { + ps_dec->i4_error_code = ERROR_UNAVAIL_MVBUF_T; + return ERROR_UNAVAIL_MVBUF_T; + } + + ps_dec->ps_cur_pic = ps_cur_pic; + ps_dec->u1_pic_buf_id = cur_pic_buf_id; + ps_cur_pic->u4_ts = ps_dec->u4_ts; + ps_dec->apv_buf_id_pic_buf_map[cur_pic_buf_id] = (void *)ps_cur_pic; + + ps_cur_pic->u1_mv_buf_id = cur_mv_buf_id; + ps_dec->au1_pic_buf_id_mv_buf_id_map[cur_pic_buf_id] = cur_mv_buf_id; + + ps_cur_pic->pu1_col_zero_flag = (UWORD8 *)ps_col_mv->pv_col_zero_flag; + ps_cur_pic->ps_mv = (mv_pred_t *)ps_col_mv->pv_mv; + ps_dec->au1_pic_buf_ref_flag[cur_pic_buf_id] = 0; + + } + + ps_dec->ps_cur_pic->u1_picturetype = u1_field_pic_flag; + ps_dec->ps_cur_pic->u4_pack_slc_typ = SKIP_NONE; + H264_DEC_DEBUG_PRINT(""got a buffer\n""); + } + else + { + H264_DEC_DEBUG_PRINT(""did not get a buffer\n""); + } + + ps_dec->u4_pic_buf_got = 1; + + ps_dec->ps_cur_pic->i4_poc = i4_poc; + ps_dec->ps_cur_pic->i4_frame_num = u2_frame_num; + ps_dec->ps_cur_pic->i4_pic_num = u2_frame_num; + ps_dec->ps_cur_pic->i4_top_field_order_cnt = ps_pps->i4_top_field_order_cnt; + ps_dec->ps_cur_pic->i4_bottom_field_order_cnt = + ps_pps->i4_bottom_field_order_cnt; + ps_dec->ps_cur_pic->i4_avg_poc = ps_pps->i4_avg_poc; + ps_dec->ps_cur_pic->u4_time_stamp = ps_dec->u4_pts; + + ps_dec->s_cur_pic = *(ps_dec->ps_cur_pic); + if(u1_field_pic_flag && u1_bottom_field_flag) + { + WORD32 i4_temp_poc; + WORD32 i4_top_field_order_poc, i4_bot_field_order_poc; + /* Point to odd lines, since it's bottom field */ + ps_dec->s_cur_pic.pu1_buf1 += ps_dec->s_cur_pic.u2_frm_wd_y; + ps_dec->s_cur_pic.pu1_buf2 += ps_dec->s_cur_pic.u2_frm_wd_uv; + ps_dec->s_cur_pic.pu1_buf3 += ps_dec->s_cur_pic.u2_frm_wd_uv; + ps_dec->s_cur_pic.ps_mv += + ((ps_dec->u2_pic_ht * ps_dec->u2_pic_wd) >> 5); + ps_dec->s_cur_pic.pu1_col_zero_flag += ((ps_dec->u2_pic_ht + * ps_dec->u2_pic_wd) >> 5); + ps_dec->ps_cur_pic->u1_picturetype |= BOT_FLD; + i4_top_field_order_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt; + i4_bot_field_order_poc = ps_dec->ps_cur_pic->i4_bottom_field_order_cnt; + i4_temp_poc = MIN(i4_top_field_order_poc, + i4_bot_field_order_poc); + ps_dec->ps_cur_pic->i4_avg_poc = i4_temp_poc; + } + + ps_cur_slice->u1_mbaff_frame_flag = ps_seq->u1_mb_aff_flag + && (!u1_field_pic_flag); + + ps_dec->ps_cur_pic->u1_picturetype |= (ps_cur_slice->u1_mbaff_frame_flag + << 2); + + ps_dec->ps_cur_mb_row = ps_dec->ps_nbr_mb_row; //[0]; + ps_dec->ps_cur_mb_row++; //Increment by 1 ,so that left mb will always be valid + ps_dec->ps_top_mb_row = + ps_dec->ps_nbr_mb_row + + ((ps_dec->u2_frm_wd_in_mbs + 1) + << (1 + - ps_dec->ps_cur_sps->u1_frame_mbs_only_flag)); + ps_dec->ps_top_mb_row++; //Increment by 1 ,so that left mb will always be valid + + ps_dec->pu1_y = ps_dec->pu1_y_scratch[0]; + ps_dec->pu1_u = ps_dec->pu1_u_scratch[0]; + ps_dec->pu1_v = ps_dec->pu1_v_scratch[0]; + ps_dec->u1_yuv_scratch_idx = 0; + /* CHANGED CODE */ + ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv; + ps_dec->ps_mv_top = ps_dec->ps_mv_top_p[0]; + /* CHANGED CODE */ + ps_dec->u1_mv_top_p = 0; + ps_dec->u1_mb_idx = 0; + /* CHANGED CODE */ + ps_dec->ps_mv_left = ps_dec->s_cur_pic.ps_mv; + ps_dec->pu1_yleft = 0; + ps_dec->pu1_uleft = 0; + ps_dec->pu1_vleft = 0; + ps_dec->u1_not_wait_rec = 2; + ps_dec->u2_total_mbs_coded = 0; + ps_dec->i4_submb_ofst = -(SUB_BLK_SIZE); + ps_dec->u4_pred_info_idx = 0; + ps_dec->u4_pred_info_pkd_idx = 0; + ps_dec->u4_dma_buf_idx = 0; + ps_dec->ps_mv = ps_dec->s_cur_pic.ps_mv; + ps_dec->ps_mv_bank_cur = ps_dec->s_cur_pic.ps_mv; + ps_dec->pu1_col_zero_flag = ps_dec->s_cur_pic.pu1_col_zero_flag; + ps_dec->ps_part = ps_dec->ps_parse_part_params; + ps_dec->i2_prev_slice_mbx = -1; + ps_dec->i2_prev_slice_mby = 0; + ps_dec->u2_mv_2mb[0] = 0; + ps_dec->u2_mv_2mb[1] = 0; + ps_dec->u1_last_pic_not_decoded = 0; + + ps_dec->u2_cur_slice_num_dec_thread = 0; + ps_dec->u2_cur_slice_num_bs = 0; + ps_dec->u4_intra_pred_line_ofst = 0; + ps_dec->pu1_cur_y_intra_pred_line = ps_dec->pu1_y_intra_pred_line; + ps_dec->pu1_cur_u_intra_pred_line = ps_dec->pu1_u_intra_pred_line; + ps_dec->pu1_cur_v_intra_pred_line = ps_dec->pu1_v_intra_pred_line; + + ps_dec->pu1_cur_y_intra_pred_line_base = ps_dec->pu1_y_intra_pred_line; + ps_dec->pu1_cur_u_intra_pred_line_base = ps_dec->pu1_u_intra_pred_line; + ps_dec->pu1_cur_v_intra_pred_line_base = ps_dec->pu1_v_intra_pred_line; + + + + + + ps_dec->pu1_prev_y_intra_pred_line = ps_dec->pu1_y_intra_pred_line + + (ps_dec->u2_frm_wd_in_mbs * MB_SIZE); + + ps_dec->pu1_prev_u_intra_pred_line = ps_dec->pu1_u_intra_pred_line + + ps_dec->u2_frm_wd_in_mbs * BLK8x8SIZE * YUV420SP_FACTOR; + ps_dec->pu1_prev_v_intra_pred_line = ps_dec->pu1_v_intra_pred_line + + ps_dec->u2_frm_wd_in_mbs * BLK8x8SIZE; + + ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic; + ps_dec->ps_deblk_mbn_curr = ps_dec->ps_deblk_mbn; + ps_dec->ps_deblk_mbn_prev = ps_dec->ps_deblk_mbn + ps_dec->u1_recon_mb_grp; + /* Initialize The Function Pointer Depending Upon the Entropy and MbAff Flag */ + { + if(ps_cur_slice->u1_mbaff_frame_flag) + { + ps_dec->pf_compute_bs = ih264d_compute_bs_mbaff; + ps_dec->pf_mvpred = ih264d_mvpred_mbaff; + } + else + { + ps_dec->pf_compute_bs = ih264d_compute_bs_non_mbaff; + ps_dec->u1_cur_mb_fld_dec_flag = ps_cur_slice->u1_field_pic_flag; + } + } + /* Set up the Parameter for DMA transfer */ + { + UWORD8 u1_field_pic_flag = ps_dec->ps_cur_slice->u1_field_pic_flag; + + UWORD8 u1_mbaff = ps_cur_slice->u1_mbaff_frame_flag; + + UWORD8 uc_lastmbs = (((ps_dec->u2_pic_wd) >> 4) + % (ps_dec->u1_recon_mb_grp >> u1_mbaff)); + UWORD16 ui16_lastmbs_widthY = + (uc_lastmbs ? (uc_lastmbs << 4) : ((ps_dec->u1_recon_mb_grp + >> u1_mbaff) << 4)); + UWORD16 ui16_lastmbs_widthUV = + uc_lastmbs ? (uc_lastmbs << 3) : ((ps_dec->u1_recon_mb_grp + >> u1_mbaff) << 3); + + ps_dec->s_tran_addrecon.pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1; + ps_dec->s_tran_addrecon.pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2; + ps_dec->s_tran_addrecon.pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3; + + ps_dec->s_tran_addrecon.u2_frm_wd_y = ps_dec->u2_frm_wd_y + << u1_field_pic_flag; + ps_dec->s_tran_addrecon.u2_frm_wd_uv = ps_dec->u2_frm_wd_uv + << u1_field_pic_flag; + + if(u1_field_pic_flag) + { + ui16_lastmbs_widthY += ps_dec->u2_frm_wd_y; + ui16_lastmbs_widthUV += ps_dec->u2_frm_wd_uv; + } + + /* Normal Increment of Pointer */ + ps_dec->s_tran_addrecon.u4_inc_y[0] = ((ps_dec->u1_recon_mb_grp << 4) + >> u1_mbaff); + ps_dec->s_tran_addrecon.u4_inc_uv[0] = ((ps_dec->u1_recon_mb_grp << 4) + >> u1_mbaff); + + /* End of Row Increment */ + ps_dec->s_tran_addrecon.u4_inc_y[1] = (ui16_lastmbs_widthY + + (PAD_LEN_Y_H << 1) + + ps_dec->s_tran_addrecon.u2_frm_wd_y + * ((15 << u1_mbaff) + u1_mbaff)); + ps_dec->s_tran_addrecon.u4_inc_uv[1] = (ui16_lastmbs_widthUV + + (PAD_LEN_UV_H << 2) + + ps_dec->s_tran_addrecon.u2_frm_wd_uv + * ((15 << u1_mbaff) + u1_mbaff)); + + /* Assign picture numbers to each frame/field */ + /* only once per picture. */ + ih264d_assign_pic_num(ps_dec); + ps_dec->s_tran_addrecon.u2_mv_top_left_inc = (ps_dec->u1_recon_mb_grp + << 2) - 1 - (u1_mbaff << 2); + ps_dec->s_tran_addrecon.u2_mv_left_inc = ((ps_dec->u1_recon_mb_grp + >> u1_mbaff) - 1) << (4 + u1_mbaff); + } + /**********************************************************************/ + /* High profile related initialization at pictrue level */ + /**********************************************************************/ + if(ps_seq->u1_profile_idc == HIGH_PROFILE_IDC) + { + if((ps_seq->i4_seq_scaling_matrix_present_flag) + || (ps_pps->i4_pic_scaling_matrix_present_flag)) + { + ih264d_form_scaling_matrix_picture(ps_seq, ps_pps, ps_dec); + ps_dec->s_high_profile.u1_scaling_present = 1; + } + else + { + ih264d_form_default_scaling_matrix(ps_dec); + } + + if(ps_pps->i4_transform_8x8_mode_flag) + { + ps_dec->s_high_profile.u1_transform8x8_present = 1; + } + } + else + { + ih264d_form_default_scaling_matrix(ps_dec); + } + + /* required while reading the transform_size_8x8 u4_flag */ + ps_dec->s_high_profile.u1_direct_8x8_inference_flag = + ps_seq->u1_direct_8x8_inference_flag; + ps_dec->s_high_profile.s_cavlc_ctxt = ps_dec->s_cavlc_ctxt; + + ps_dec->i1_recon_in_thread3_flag = 1; + ps_dec->ps_frame_buf_ip_recon = &ps_dec->s_tran_addrecon; + if(ps_dec->u1_separate_parse) + { + memcpy(&ps_dec->s_tran_addrecon_parse, &ps_dec->s_tran_addrecon, + sizeof(tfr_ctxt_t)); + if(ps_dec->u4_num_cores >= 3 && ps_dec->i1_recon_in_thread3_flag) + { + memcpy(&ps_dec->s_tran_iprecon, &ps_dec->s_tran_addrecon, + sizeof(tfr_ctxt_t)); + ps_dec->ps_frame_buf_ip_recon = &ps_dec->s_tran_iprecon; + } + } + + + ih264d_init_deblk_tfr_ctxt(ps_dec,&(ps_dec->s_pad_mgr), &(ps_dec->s_tran_addrecon), + ps_dec->u2_frm_wd_in_mbs, 0); + + ps_dec->ps_cur_deblk_mb = ps_dec->ps_deblk_pic; + ps_dec->u4_cur_deblk_mb_num = 0; + + ps_dec->u4_deblk_mb_x = 0; + ps_dec->u4_deblk_mb_y = 0; + ps_dec->pu4_wt_ofsts = ps_dec->pu4_wts_ofsts_mat; + + H264_MUTEX_UNLOCK(&ps_dec->process_disp_mutex); + return OK; +} +","@@ -1152,19 +1152,19 @@ + + + u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); + if(u4_temp & MASK_ERR_PIC_SET_ID) +- return ERROR_INV_SPS_PPS_T; ++ return ERROR_INV_SLICE_HDR_T; + /* discard slice if pic param is invalid */ + COPYTHECONTEXT(""SH: pic_parameter_set_id"", u4_temp); + ps_pps = &ps_dec->ps_pps[u4_temp]; + if(FALSE == ps_pps->u1_is_valid) + { +- return ERROR_INV_SPS_PPS_T; ++ return ERROR_INV_SLICE_HDR_T; + } + ps_seq = ps_pps->ps_sps; + if(!ps_seq) +- return ERROR_INV_SPS_PPS_T; ++ return ERROR_INV_SLICE_HDR_T; + if(FALSE == ps_seq->u1_is_valid) +- return ERROR_INV_SPS_PPS_T; ++ return ERROR_INV_SLICE_HDR_T; + + /* Get the frame num */ + u2_frame_num = ih264d_get_bits_h264(ps_bitstrm, +@@ -1213,7 +1213,7 @@ + + u4_idr_pic_id = ih264d_uev(pu4_bitstrm_ofst, + pu4_bitstrm_buf); + if(u4_idr_pic_id > 65535) +- return ERROR_INV_SPS_PPS_T; ++ return ERROR_INV_SLICE_HDR_T; + COPYTHECONTEXT(""SH: "", u4_idr_pic_id); + } + +@@ -1228,7 +1228,7 @@ + + ps_bitstrm, + ps_seq->u1_log2_max_pic_order_cnt_lsb_minus); + if(i_temp < 0 || i_temp >= ps_seq->i4_max_pic_order_cntLsb) +- return ERROR_INV_SPS_PPS_T; ++ return ERROR_INV_SLICE_HDR_T; + s_tmp_poc.i4_pic_order_cnt_lsb = i_temp; + COPYTHECONTEXT(""SH: pic_order_cnt_lsb"", s_tmp_poc.i4_pic_order_cnt_lsb); + +@@ -1265,7 +1265,7 @@ + + { + u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); + if(u4_temp > MAX_REDUNDANT_PIC_CNT) +- return ERROR_INV_SPS_PPS_T; ++ return ERROR_INV_SLICE_HDR_T; + u1_redundant_pic_cnt = u4_temp; + COPYTHECONTEXT(""SH: redundant_pic_cnt"", u1_redundant_pic_cnt); + } +",6059,6390,8192 +7750,"static MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image) +{ + MagickBooleanType + excluding, + logging, + status; + + MngInfo + *mng_info; + + const char + *value; + + int + source; + + /* + Open image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickCoreSignature); + assert(image != (Image *) NULL); + assert(image->signature == MagickCoreSignature); + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); + logging=LogMagickEvent(CoderEvent,GetMagickModule(),""Enter WritePNGImage()""); + /* + Allocate a MngInfo structure. + */ + mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); + + if (mng_info == (MngInfo *) NULL) + ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); + + /* + Initialize members of the MngInfo structure. + */ + (void) memset(mng_info,0,sizeof(MngInfo)); + mng_info->image=image; + mng_info->equal_backgrounds=MagickTrue; + + /* See if user has requested a specific PNG subformat */ + + mng_info->write_png8=LocaleCompare(image_info->magick,""PNG8"") == 0; + mng_info->write_png24=LocaleCompare(image_info->magick,""PNG24"") == 0; + mng_info->write_png32=LocaleCompare(image_info->magick,""PNG32"") == 0; + mng_info->write_png48=LocaleCompare(image_info->magick,""PNG48"") == 0; + mng_info->write_png64=LocaleCompare(image_info->magick,""PNG64"") == 0; + + value=GetImageOption(image_info,""png:format""); + + if (value != (char *) NULL || LocaleCompare(image_info->magick,""PNG00"") == 0) + { + mng_info->write_png8 = MagickFalse; + mng_info->write_png24 = MagickFalse; + mng_info->write_png32 = MagickFalse; + mng_info->write_png48 = MagickFalse; + mng_info->write_png64 = MagickFalse; + + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Format=%s"",value); + + if (LocaleCompare(value,""png8"") == 0) + mng_info->write_png8 = MagickTrue; + + else if (LocaleCompare(value,""png24"") == 0) + mng_info->write_png24 = MagickTrue; + + else if (LocaleCompare(value,""png32"") == 0) + mng_info->write_png32 = MagickTrue; + + else if (LocaleCompare(value,""png48"") == 0) + mng_info->write_png48 = MagickTrue; + + else if (LocaleCompare(value,""png64"") == 0) + mng_info->write_png64 = MagickTrue; + + else if ((LocaleCompare(value,""png00"") == 0) || + LocaleCompare(image_info->magick,""PNG00"") == 0) + { + /* Retrieve png:IHDR.bit-depth-orig and png:IHDR.color-type-orig */ + value=GetImageProperty(image,""png:IHDR.bit-depth-orig""); + + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" png00 inherited bit depth=%s"",value); + + if (value != (char *) NULL) + { + + if (LocaleCompare(value,""1"") == 0) + mng_info->write_png_depth = 1; + + else if (LocaleCompare(value,""2"") == 0) + mng_info->write_png_depth = 2; + + else if (LocaleCompare(value,""4"") == 0) + mng_info->write_png_depth = 4; + + else if (LocaleCompare(value,""8"") == 0) + mng_info->write_png_depth = 8; + + else if (LocaleCompare(value,""16"") == 0) + mng_info->write_png_depth = 16; + } + + value=GetImageProperty(image,""png:IHDR.color-type-orig""); + + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" png00 inherited color type=%s"",value); + + if (value != (char *) NULL) + { + if (LocaleCompare(value,""0"") == 0) + mng_info->write_png_colortype = 1; + + else if (LocaleCompare(value,""2"") == 0) + mng_info->write_png_colortype = 3; + + else if (LocaleCompare(value,""3"") == 0) + mng_info->write_png_colortype = 4; + + else if (LocaleCompare(value,""4"") == 0) + mng_info->write_png_colortype = 5; + + else if (LocaleCompare(value,""6"") == 0) + mng_info->write_png_colortype = 7; + } + } + } + + if (mng_info->write_png8) + { + mng_info->write_png_colortype = /* 3 */ 4; + mng_info->write_png_depth = 8; + image->depth = 8; + } + + if (mng_info->write_png24) + { + mng_info->write_png_colortype = /* 2 */ 3; + mng_info->write_png_depth = 8; + image->depth = 8; + + if (image->matte != MagickFalse) + (void) SetImageType(image,TrueColorMatteType); + + else + (void) SetImageType(image,TrueColorType); + + (void) SyncImage(image); + } + + if (mng_info->write_png32) + { + mng_info->write_png_colortype = /* 6 */ 7; + mng_info->write_png_depth = 8; + image->depth = 8; + image->matte = MagickTrue; + (void) SetImageType(image,TrueColorMatteType); + (void) SyncImage(image); + } + + if (mng_info->write_png48) + { + mng_info->write_png_colortype = /* 2 */ 3; + mng_info->write_png_depth = 16; + image->depth = 16; + + if (image->matte != MagickFalse) + (void) SetImageType(image,TrueColorMatteType); + + else + (void) SetImageType(image,TrueColorType); + + (void) SyncImage(image); + } + + if (mng_info->write_png64) + { + mng_info->write_png_colortype = /* 6 */ 7; + mng_info->write_png_depth = 16; + image->depth = 16; + image->matte = MagickTrue; + (void) SetImageType(image,TrueColorMatteType); + (void) SyncImage(image); + } + + value=GetImageOption(image_info,""png:bit-depth""); + + if (value != (char *) NULL) + { + if (LocaleCompare(value,""1"") == 0) + mng_info->write_png_depth = 1; + + else if (LocaleCompare(value,""2"") == 0) + mng_info->write_png_depth = 2; + + else if (LocaleCompare(value,""4"") == 0) + mng_info->write_png_depth = 4; + + else if (LocaleCompare(value,""8"") == 0) + mng_info->write_png_depth = 8; + + else if (LocaleCompare(value,""16"") == 0) + mng_info->write_png_depth = 16; + + else + (void) ThrowMagickException(&image->exception, + GetMagickModule(),CoderWarning, + ""ignoring invalid defined png:bit-depth"", + ""=%s"",value); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" png:bit-depth=%d was defined.\n"",mng_info->write_png_depth); + } + + value=GetImageOption(image_info,""png:color-type""); + + if (value != (char *) NULL) + { + /* We must store colortype+1 because 0 is a valid colortype */ + if (LocaleCompare(value,""0"") == 0) + mng_info->write_png_colortype = 1; + + else if (LocaleCompare(value,""2"") == 0) + mng_info->write_png_colortype = 3; + + else if (LocaleCompare(value,""3"") == 0) + mng_info->write_png_colortype = 4; + + else if (LocaleCompare(value,""4"") == 0) + mng_info->write_png_colortype = 5; + + else if (LocaleCompare(value,""6"") == 0) + mng_info->write_png_colortype = 7; + + else + (void) ThrowMagickException(&image->exception, + GetMagickModule(),CoderWarning, + ""ignoring invalid defined png:color-type"", + ""=%s"",value); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" png:color-type=%d was defined.\n"",mng_info->write_png_colortype-1); + } + + /* Check for chunks to be excluded: + * + * The default is to not exclude any known chunks except for any + * listed in the ""unused_chunks"" array, above. + * + * Chunks can be listed for exclusion via a ""png:exclude-chunk"" + * define (in the image properties or in the image artifacts) + * or via a mng_info member. For convenience, in addition + * to or instead of a comma-separated list of chunks, the + * ""exclude-chunk"" string can be simply ""all"" or ""none"". + * + * The exclude-chunk define takes priority over the mng_info. + * + * A ""png:include-chunk"" define takes priority over both the + * mng_info and the ""png:exclude-chunk"" define. Like the + * ""exclude-chunk"" string, it can define ""all"" or ""none"" as + * well as a comma-separated list. Chunks that are unknown to + * ImageMagick are always excluded, regardless of their ""copy-safe"" + * status according to the PNG specification, and even if they + * appear in the ""include-chunk"" list. Such defines appearing among + * the image options take priority over those found among the image + * artifacts. + * + * Finally, all chunks listed in the ""unused_chunks"" array are + * automatically excluded, regardless of the other instructions + * or lack thereof. + * + * if you exclude sRGB but not gAMA (recommended), then sRGB chunk + * will not be written and the gAMA chunk will only be written if it + * is not between .45 and .46, or approximately (1.0/2.2). + * + * If you exclude tRNS and the image has transparency, the colortype + * is forced to be 4 or 6 (GRAY_ALPHA or RGB_ALPHA). + * + * The -strip option causes StripImage() to set the png:include-chunk + * artifact to ""none,trns,gama"". + */ + + mng_info->ping_exclude_bKGD=MagickFalse; + mng_info->ping_exclude_caNv=MagickFalse; + mng_info->ping_exclude_cHRM=MagickFalse; + mng_info->ping_exclude_date=MagickFalse; + mng_info->ping_exclude_eXIf=MagickFalse; + mng_info->ping_exclude_EXIF=MagickFalse; /* hex-encoded EXIF in zTXt */ + mng_info->ping_exclude_gAMA=MagickFalse; + mng_info->ping_exclude_iCCP=MagickFalse; + /* mng_info->ping_exclude_iTXt=MagickFalse; */ + mng_info->ping_exclude_oFFs=MagickFalse; + mng_info->ping_exclude_pHYs=MagickFalse; + mng_info->ping_exclude_sRGB=MagickFalse; + mng_info->ping_exclude_tEXt=MagickFalse; + mng_info->ping_exclude_tIME=MagickFalse; + mng_info->ping_exclude_tRNS=MagickFalse; + mng_info->ping_exclude_zCCP=MagickFalse; /* hex-encoded iCCP in zTXt */ + mng_info->ping_exclude_zTXt=MagickFalse; + + mng_info->ping_preserve_colormap=MagickFalse; + + value=GetImageOption(image_info,""png:preserve-colormap""); + if (value == NULL) + value=GetImageArtifact(image,""png:preserve-colormap""); + if (value != NULL) + mng_info->ping_preserve_colormap=MagickTrue; + + + mng_info->ping_preserve_iCCP=MagickFalse; + + value=GetImageOption(image_info,""png:preserve-iCCP""); + if (value == NULL) + value=GetImageArtifact(image,""png:preserve-iCCP""); + if (value != NULL) + mng_info->ping_preserve_iCCP=MagickTrue; + + /* These compression-level, compression-strategy, and compression-filter + * defines take precedence over values from the -quality option. + */ + value=GetImageOption(image_info,""png:compression-level""); + if (value == NULL) + value=GetImageArtifact(image,""png:compression-level""); + if (value != NULL) + { + /* To do: use a ""LocaleInteger:()"" function here. */ + + /* We have to add 1 to everything because 0 is a valid input, + * and we want to use 0 (the default) to mean undefined. + */ + if (LocaleCompare(value,""0"") == 0) + mng_info->write_png_compression_level = 1; + + else if (LocaleCompare(value,""1"") == 0) + mng_info->write_png_compression_level = 2; + + else if (LocaleCompare(value,""2"") == 0) + mng_info->write_png_compression_level = 3; + + else if (LocaleCompare(value,""3"") == 0) + mng_info->write_png_compression_level = 4; + + else if (LocaleCompare(value,""4"") == 0) + mng_info->write_png_compression_level = 5; + + else if (LocaleCompare(value,""5"") == 0) + mng_info->write_png_compression_level = 6; + + else if (LocaleCompare(value,""6"") == 0) + mng_info->write_png_compression_level = 7; + + else if (LocaleCompare(value,""7"") == 0) + mng_info->write_png_compression_level = 8; + + else if (LocaleCompare(value,""8"") == 0) + mng_info->write_png_compression_level = 9; + + else if (LocaleCompare(value,""9"") == 0) + mng_info->write_png_compression_level = 10; + + else + (void) ThrowMagickException(&image->exception, + GetMagickModule(),CoderWarning, + ""ignoring invalid defined png:compression-level"", + ""=%s"",value); + } + + value=GetImageOption(image_info,""png:compression-strategy""); + if (value == NULL) + value=GetImageArtifact(image,""png:compression-strategy""); + if (value != NULL) + { + if (LocaleCompare(value,""0"") == 0) + mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; + + else if (LocaleCompare(value,""1"") == 0) + mng_info->write_png_compression_strategy = Z_FILTERED+1; + + else if (LocaleCompare(value,""2"") == 0) + mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; + + else if (LocaleCompare(value,""3"") == 0) +#ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ + mng_info->write_png_compression_strategy = Z_RLE+1; +#else + mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; +#endif + + else if (LocaleCompare(value,""4"") == 0) +#ifdef Z_FIXED /* Z_FIXED was added to zlib-1.2.2.2 */ + mng_info->write_png_compression_strategy = Z_FIXED+1; +#else + mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; +#endif + + else + (void) ThrowMagickException(&image->exception, + GetMagickModule(),CoderWarning, + ""ignoring invalid defined png:compression-strategy"", + ""=%s"",value); + } + + value=GetImageOption(image_info,""png:compression-filter""); + if (value == NULL) + value=GetImageArtifact(image,""png:compression-filter""); + if (value != NULL) + { + /* To do: combinations of filters allowed by libpng + * masks 0x08 through 0xf8 + * + * Implement this as a comma-separated list of 0,1,2,3,4,5 + * where 5 is a special case meaning PNG_ALL_FILTERS. + */ + + if (LocaleCompare(value,""0"") == 0) + mng_info->write_png_compression_filter = 1; + + else if (LocaleCompare(value,""1"") == 0) + mng_info->write_png_compression_filter = 2; + + else if (LocaleCompare(value,""2"") == 0) + mng_info->write_png_compression_filter = 3; + + else if (LocaleCompare(value,""3"") == 0) + mng_info->write_png_compression_filter = 4; + + else if (LocaleCompare(value,""4"") == 0) + mng_info->write_png_compression_filter = 5; + + else if (LocaleCompare(value,""5"") == 0) + mng_info->write_png_compression_filter = 6; + + else + (void) ThrowMagickException(&image->exception, + GetMagickModule(),CoderWarning, + ""ignoring invalid defined png:compression-filter"", + ""=%s"",value); + } + + for (source=0; source<8; source++) + { + value = NULL; + + if (source == 0) + value=GetImageOption(image_info,""png:exclude-chunks""); + + if (source == 1) + value=GetImageArtifact(image,""png:exclude-chunks""); + + if (source == 2) + value=GetImageOption(image_info,""png:exclude-chunk""); + + if (source == 3) + value=GetImageArtifact(image,""png:exclude-chunk""); + + if (source == 4) + value=GetImageOption(image_info,""png:include-chunks""); + + if (source == 5) + value=GetImageArtifact(image,""png:include-chunks""); + + if (source == 6) + value=GetImageOption(image_info,""png:include-chunk""); + + if (source == 7) + value=GetImageArtifact(image,""png:include-chunk""); + + if (value == NULL) + continue; + + if (source < 4) + excluding = MagickTrue; + else + excluding = MagickFalse; + + if (logging != MagickFalse) + { + if (source == 0 || source == 2) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" png:exclude-chunk=%s found in image options.\n"", value); + else if (source == 1 || source == 3) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" png:exclude-chunk=%s found in image artifacts.\n"", value); + else if (source == 4 || source == 6) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" png:include-chunk=%s found in image options.\n"", value); + else /* if (source == 5 || source == 7) */ + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" png:include-chunk=%s found in image artifacts.\n"", value); + } + + if (IsOptionMember(""all"",value) != MagickFalse) + { + mng_info->ping_exclude_bKGD=excluding; + mng_info->ping_exclude_caNv=excluding; + mng_info->ping_exclude_cHRM=excluding; + mng_info->ping_exclude_date=excluding; + mng_info->ping_exclude_EXIF=excluding; + mng_info->ping_exclude_eXIf=excluding; + mng_info->ping_exclude_gAMA=excluding; + mng_info->ping_exclude_iCCP=excluding; + /* mng_info->ping_exclude_iTXt=excluding; */ + mng_info->ping_exclude_oFFs=excluding; + mng_info->ping_exclude_pHYs=excluding; + mng_info->ping_exclude_sRGB=excluding; + mng_info->ping_exclude_tIME=excluding; + mng_info->ping_exclude_tEXt=excluding; + mng_info->ping_exclude_tRNS=excluding; + mng_info->ping_exclude_zCCP=excluding; + mng_info->ping_exclude_zTXt=excluding; + } + + if (IsOptionMember(""none"",value) != MagickFalse) + { + mng_info->ping_exclude_bKGD=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_caNv=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_cHRM=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_date=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_eXIf=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_EXIF=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_gAMA=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_iCCP=excluding != MagickFalse ? MagickFalse : + MagickTrue; + /* mng_info->ping_exclude_iTXt=!excluding; */ + mng_info->ping_exclude_oFFs=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_pHYs=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_sRGB=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_tEXt=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_tIME=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_tRNS=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_zCCP=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_zTXt=excluding != MagickFalse ? MagickFalse : + MagickTrue; + } + + if (IsOptionMember(""bkgd"",value) != MagickFalse) + mng_info->ping_exclude_bKGD=excluding; + + if (IsOptionMember(""caNv"",value) != MagickFalse) + mng_info->ping_exclude_caNv=excluding; + + if (IsOptionMember(""chrm"",value) != MagickFalse) + mng_info->ping_exclude_cHRM=excluding; + + if (IsOptionMember(""date"",value) != MagickFalse) + mng_info->ping_exclude_date=excluding; + + if (IsOptionMember(""exif"",value) != MagickFalse) + { + mng_info->ping_exclude_EXIF=excluding; + mng_info->ping_exclude_eXIf=excluding; + } + + if (IsOptionMember(""gama"",value) != MagickFalse) + mng_info->ping_exclude_gAMA=excluding; + + if (IsOptionMember(""iccp"",value) != MagickFalse) + mng_info->ping_exclude_iCCP=excluding; + +#if 0 + if (IsOptionMember(""itxt"",value) != MagickFalse) + mng_info->ping_exclude_iTXt=excluding; +#endif + + if (IsOptionMember(""offs"",value) != MagickFalse) + mng_info->ping_exclude_oFFs=excluding; + + if (IsOptionMember(""phys"",value) != MagickFalse) + mng_info->ping_exclude_pHYs=excluding; + + if (IsOptionMember(""srgb"",value) != MagickFalse) + mng_info->ping_exclude_sRGB=excluding; + + if (IsOptionMember(""text"",value) != MagickFalse) + mng_info->ping_exclude_tEXt=excluding; + + if (IsOptionMember(""time"",value) != MagickFalse) + mng_info->ping_exclude_tIME=excluding; + + if (IsOptionMember(""trns"",value) != MagickFalse) + mng_info->ping_exclude_tRNS=excluding; + + if (IsOptionMember(""zccp"",value) != MagickFalse) + mng_info->ping_exclude_zCCP=excluding; + + if (IsOptionMember(""ztxt"",value) != MagickFalse) + mng_info->ping_exclude_zTXt=excluding; + } + + if (logging != MagickFalse) + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Chunks to be excluded from the output png:""); + if (mng_info->ping_exclude_bKGD != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" bKGD""); + if (mng_info->ping_exclude_caNv != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" caNv""); + if (mng_info->ping_exclude_cHRM != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" cHRM""); + if (mng_info->ping_exclude_date != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" date""); + if (mng_info->ping_exclude_EXIF != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" EXIF""); + if (mng_info->ping_exclude_eXIf != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" eXIf""); + if (mng_info->ping_exclude_gAMA != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" gAMA""); + if (mng_info->ping_exclude_iCCP != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" iCCP""); +#if 0 + if (mng_info->ping_exclude_iTXt != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" iTXt""); +#endif + + if (mng_info->ping_exclude_oFFs != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" oFFs""); + if (mng_info->ping_exclude_pHYs != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" pHYs""); + if (mng_info->ping_exclude_sRGB != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" sRGB""); + if (mng_info->ping_exclude_tEXt != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" tEXt""); + if (mng_info->ping_exclude_tIME != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" tIME""); + if (mng_info->ping_exclude_tRNS != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" tRNS""); + if (mng_info->ping_exclude_zCCP != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" zCCP""); + if (mng_info->ping_exclude_zTXt != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" zTXt""); + } + + mng_info->need_blob = MagickTrue; + + status=WriteOnePNGImage(mng_info,image_info,image); + + (void) CloseBlob(image); + + mng_info=MngInfoFreeStruct(mng_info); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(),""exit WritePNGImage()""); + + return(status); +} +",0,"static MagickBooleanType WritePNGImage(const ImageInfo *image_info,Image *image) +{ + MagickBooleanType + excluding, + logging, + status; + + MngInfo + *mng_info; + + const char + *value; + + int + source; + + /* + Open image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickCoreSignature); + assert(image != (Image *) NULL); + assert(image->signature == MagickCoreSignature); + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); + logging=LogMagickEvent(CoderEvent,GetMagickModule(),""Enter WritePNGImage()""); + /* + Allocate a MngInfo structure. + */ + mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); + + if (mng_info == (MngInfo *) NULL) + ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); + + /* + Initialize members of the MngInfo structure. + */ + (void) memset(mng_info,0,sizeof(MngInfo)); + mng_info->image=image; + mng_info->equal_backgrounds=MagickTrue; + + /* See if user has requested a specific PNG subformat */ + + mng_info->write_png8=LocaleCompare(image_info->magick,""PNG8"") == 0; + mng_info->write_png24=LocaleCompare(image_info->magick,""PNG24"") == 0; + mng_info->write_png32=LocaleCompare(image_info->magick,""PNG32"") == 0; + mng_info->write_png48=LocaleCompare(image_info->magick,""PNG48"") == 0; + mng_info->write_png64=LocaleCompare(image_info->magick,""PNG64"") == 0; + + value=GetImageOption(image_info,""png:format""); + + if (value != (char *) NULL || LocaleCompare(image_info->magick,""PNG00"") == 0) + { + mng_info->write_png8 = MagickFalse; + mng_info->write_png24 = MagickFalse; + mng_info->write_png32 = MagickFalse; + mng_info->write_png48 = MagickFalse; + mng_info->write_png64 = MagickFalse; + + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Format=%s"",value); + + if (LocaleCompare(value,""png8"") == 0) + mng_info->write_png8 = MagickTrue; + + else if (LocaleCompare(value,""png24"") == 0) + mng_info->write_png24 = MagickTrue; + + else if (LocaleCompare(value,""png32"") == 0) + mng_info->write_png32 = MagickTrue; + + else if (LocaleCompare(value,""png48"") == 0) + mng_info->write_png48 = MagickTrue; + + else if (LocaleCompare(value,""png64"") == 0) + mng_info->write_png64 = MagickTrue; + + else if ((LocaleCompare(value,""png00"") == 0) || + LocaleCompare(image_info->magick,""PNG00"") == 0) + { + /* Retrieve png:IHDR.bit-depth-orig and png:IHDR.color-type-orig */ + value=GetImageProperty(image,""png:IHDR.bit-depth-orig""); + + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" png00 inherited bit depth=%s"",value); + + if (value != (char *) NULL) + { + + if (LocaleCompare(value,""1"") == 0) + mng_info->write_png_depth = 1; + + else if (LocaleCompare(value,""2"") == 0) + mng_info->write_png_depth = 2; + + else if (LocaleCompare(value,""4"") == 0) + mng_info->write_png_depth = 4; + + else if (LocaleCompare(value,""8"") == 0) + mng_info->write_png_depth = 8; + + else if (LocaleCompare(value,""16"") == 0) + mng_info->write_png_depth = 16; + } + + value=GetImageProperty(image,""png:IHDR.color-type-orig""); + + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" png00 inherited color type=%s"",value); + + if (value != (char *) NULL) + { + if (LocaleCompare(value,""0"") == 0) + mng_info->write_png_colortype = 1; + + else if (LocaleCompare(value,""2"") == 0) + mng_info->write_png_colortype = 3; + + else if (LocaleCompare(value,""3"") == 0) + mng_info->write_png_colortype = 4; + + else if (LocaleCompare(value,""4"") == 0) + mng_info->write_png_colortype = 5; + + else if (LocaleCompare(value,""6"") == 0) + mng_info->write_png_colortype = 7; + } + } + } + + if (mng_info->write_png8) + { + mng_info->write_png_colortype = /* 3 */ 4; + mng_info->write_png_depth = 8; + image->depth = 8; + } + + if (mng_info->write_png24) + { + mng_info->write_png_colortype = /* 2 */ 3; + mng_info->write_png_depth = 8; + image->depth = 8; + + if (image->matte != MagickFalse) + (void) SetImageType(image,TrueColorMatteType); + + else + (void) SetImageType(image,TrueColorType); + + (void) SyncImage(image); + } + + if (mng_info->write_png32) + { + mng_info->write_png_colortype = /* 6 */ 7; + mng_info->write_png_depth = 8; + image->depth = 8; + image->matte = MagickTrue; + (void) SetImageType(image,TrueColorMatteType); + (void) SyncImage(image); + } + + if (mng_info->write_png48) + { + mng_info->write_png_colortype = /* 2 */ 3; + mng_info->write_png_depth = 16; + image->depth = 16; + + if (image->matte != MagickFalse) + (void) SetImageType(image,TrueColorMatteType); + + else + (void) SetImageType(image,TrueColorType); + + (void) SyncImage(image); + } + + if (mng_info->write_png64) + { + mng_info->write_png_colortype = /* 6 */ 7; + mng_info->write_png_depth = 16; + image->depth = 16; + image->matte = MagickTrue; + (void) SetImageType(image,TrueColorMatteType); + (void) SyncImage(image); + } + + value=GetImageOption(image_info,""png:bit-depth""); + + if (value != (char *) NULL) + { + if (LocaleCompare(value,""1"") == 0) + mng_info->write_png_depth = 1; + + else if (LocaleCompare(value,""2"") == 0) + mng_info->write_png_depth = 2; + + else if (LocaleCompare(value,""4"") == 0) + mng_info->write_png_depth = 4; + + else if (LocaleCompare(value,""8"") == 0) + mng_info->write_png_depth = 8; + + else if (LocaleCompare(value,""16"") == 0) + mng_info->write_png_depth = 16; + + else + (void) ThrowMagickException(&image->exception, + GetMagickModule(),CoderWarning, + ""ignoring invalid defined png:bit-depth"", + ""=%s"",value); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" png:bit-depth=%d was defined.\n"",mng_info->write_png_depth); + } + + value=GetImageOption(image_info,""png:color-type""); + + if (value != (char *) NULL) + { + /* We must store colortype+1 because 0 is a valid colortype */ + if (LocaleCompare(value,""0"") == 0) + mng_info->write_png_colortype = 1; + + else if (LocaleCompare(value,""2"") == 0) + mng_info->write_png_colortype = 3; + + else if (LocaleCompare(value,""3"") == 0) + mng_info->write_png_colortype = 4; + + else if (LocaleCompare(value,""4"") == 0) + mng_info->write_png_colortype = 5; + + else if (LocaleCompare(value,""6"") == 0) + mng_info->write_png_colortype = 7; + + else + (void) ThrowMagickException(&image->exception, + GetMagickModule(),CoderWarning, + ""ignoring invalid defined png:color-type"", + ""=%s"",value); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" png:color-type=%d was defined.\n"",mng_info->write_png_colortype-1); + } + + /* Check for chunks to be excluded: + * + * The default is to not exclude any known chunks except for any + * listed in the ""unused_chunks"" array, above. + * + * Chunks can be listed for exclusion via a ""png:exclude-chunk"" + * define (in the image properties or in the image artifacts) + * or via a mng_info member. For convenience, in addition + * to or instead of a comma-separated list of chunks, the + * ""exclude-chunk"" string can be simply ""all"" or ""none"". + * + * The exclude-chunk define takes priority over the mng_info. + * + * A ""png:include-chunk"" define takes priority over both the + * mng_info and the ""png:exclude-chunk"" define. Like the + * ""exclude-chunk"" string, it can define ""all"" or ""none"" as + * well as a comma-separated list. Chunks that are unknown to + * ImageMagick are always excluded, regardless of their ""copy-safe"" + * status according to the PNG specification, and even if they + * appear in the ""include-chunk"" list. Such defines appearing among + * the image options take priority over those found among the image + * artifacts. + * + * Finally, all chunks listed in the ""unused_chunks"" array are + * automatically excluded, regardless of the other instructions + * or lack thereof. + * + * if you exclude sRGB but not gAMA (recommended), then sRGB chunk + * will not be written and the gAMA chunk will only be written if it + * is not between .45 and .46, or approximately (1.0/2.2). + * + * If you exclude tRNS and the image has transparency, the colortype + * is forced to be 4 or 6 (GRAY_ALPHA or RGB_ALPHA). + * + * The -strip option causes StripImage() to set the png:include-chunk + * artifact to ""none,trns,gama"". + */ + + mng_info->ping_exclude_bKGD=MagickFalse; + mng_info->ping_exclude_caNv=MagickFalse; + mng_info->ping_exclude_cHRM=MagickFalse; + mng_info->ping_exclude_date=MagickFalse; + mng_info->ping_exclude_eXIf=MagickFalse; + mng_info->ping_exclude_EXIF=MagickFalse; /* hex-encoded EXIF in zTXt */ + mng_info->ping_exclude_gAMA=MagickFalse; + mng_info->ping_exclude_iCCP=MagickFalse; + /* mng_info->ping_exclude_iTXt=MagickFalse; */ + mng_info->ping_exclude_oFFs=MagickFalse; + mng_info->ping_exclude_pHYs=MagickFalse; + mng_info->ping_exclude_sRGB=MagickFalse; + mng_info->ping_exclude_tEXt=MagickFalse; + mng_info->ping_exclude_tIME=MagickFalse; + mng_info->ping_exclude_tRNS=MagickFalse; + mng_info->ping_exclude_zCCP=MagickFalse; /* hex-encoded iCCP in zTXt */ + mng_info->ping_exclude_zTXt=MagickFalse; + + mng_info->ping_preserve_colormap=MagickFalse; + + value=GetImageOption(image_info,""png:preserve-colormap""); + if (value == NULL) + value=GetImageArtifact(image,""png:preserve-colormap""); + if (value != NULL) + mng_info->ping_preserve_colormap=MagickTrue; + + + mng_info->ping_preserve_iCCP=MagickFalse; + + value=GetImageOption(image_info,""png:preserve-iCCP""); + if (value == NULL) + value=GetImageArtifact(image,""png:preserve-iCCP""); + if (value != NULL) + mng_info->ping_preserve_iCCP=MagickTrue; + + /* These compression-level, compression-strategy, and compression-filter + * defines take precedence over values from the -quality option. + */ + value=GetImageOption(image_info,""png:compression-level""); + if (value == NULL) + value=GetImageArtifact(image,""png:compression-level""); + if (value != NULL) + { + /* To do: use a ""LocaleInteger:()"" function here. */ + + /* We have to add 1 to everything because 0 is a valid input, + * and we want to use 0 (the default) to mean undefined. + */ + if (LocaleCompare(value,""0"") == 0) + mng_info->write_png_compression_level = 1; + + else if (LocaleCompare(value,""1"") == 0) + mng_info->write_png_compression_level = 2; + + else if (LocaleCompare(value,""2"") == 0) + mng_info->write_png_compression_level = 3; + + else if (LocaleCompare(value,""3"") == 0) + mng_info->write_png_compression_level = 4; + + else if (LocaleCompare(value,""4"") == 0) + mng_info->write_png_compression_level = 5; + + else if (LocaleCompare(value,""5"") == 0) + mng_info->write_png_compression_level = 6; + + else if (LocaleCompare(value,""6"") == 0) + mng_info->write_png_compression_level = 7; + + else if (LocaleCompare(value,""7"") == 0) + mng_info->write_png_compression_level = 8; + + else if (LocaleCompare(value,""8"") == 0) + mng_info->write_png_compression_level = 9; + + else if (LocaleCompare(value,""9"") == 0) + mng_info->write_png_compression_level = 10; + + else + (void) ThrowMagickException(&image->exception, + GetMagickModule(),CoderWarning, + ""ignoring invalid defined png:compression-level"", + ""=%s"",value); + } + + value=GetImageOption(image_info,""png:compression-strategy""); + if (value == NULL) + value=GetImageArtifact(image,""png:compression-strategy""); + if (value != NULL) + { + if (LocaleCompare(value,""0"") == 0) + mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; + + else if (LocaleCompare(value,""1"") == 0) + mng_info->write_png_compression_strategy = Z_FILTERED+1; + + else if (LocaleCompare(value,""2"") == 0) + mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1; + + else if (LocaleCompare(value,""3"") == 0) +#ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */ + mng_info->write_png_compression_strategy = Z_RLE+1; +#else + mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; +#endif + + else if (LocaleCompare(value,""4"") == 0) +#ifdef Z_FIXED /* Z_FIXED was added to zlib-1.2.2.2 */ + mng_info->write_png_compression_strategy = Z_FIXED+1; +#else + mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1; +#endif + + else + (void) ThrowMagickException(&image->exception, + GetMagickModule(),CoderWarning, + ""ignoring invalid defined png:compression-strategy"", + ""=%s"",value); + } + + value=GetImageOption(image_info,""png:compression-filter""); + if (value == NULL) + value=GetImageArtifact(image,""png:compression-filter""); + if (value != NULL) + { + /* To do: combinations of filters allowed by libpng + * masks 0x08 through 0xf8 + * + * Implement this as a comma-separated list of 0,1,2,3,4,5 + * where 5 is a special case meaning PNG_ALL_FILTERS. + */ + + if (LocaleCompare(value,""0"") == 0) + mng_info->write_png_compression_filter = 1; + + else if (LocaleCompare(value,""1"") == 0) + mng_info->write_png_compression_filter = 2; + + else if (LocaleCompare(value,""2"") == 0) + mng_info->write_png_compression_filter = 3; + + else if (LocaleCompare(value,""3"") == 0) + mng_info->write_png_compression_filter = 4; + + else if (LocaleCompare(value,""4"") == 0) + mng_info->write_png_compression_filter = 5; + + else if (LocaleCompare(value,""5"") == 0) + mng_info->write_png_compression_filter = 6; + + else + (void) ThrowMagickException(&image->exception, + GetMagickModule(),CoderWarning, + ""ignoring invalid defined png:compression-filter"", + ""=%s"",value); + } + + for (source=0; source<8; source++) + { + value = NULL; + + if (source == 0) + value=GetImageOption(image_info,""png:exclude-chunks""); + + if (source == 1) + value=GetImageArtifact(image,""png:exclude-chunks""); + + if (source == 2) + value=GetImageOption(image_info,""png:exclude-chunk""); + + if (source == 3) + value=GetImageArtifact(image,""png:exclude-chunk""); + + if (source == 4) + value=GetImageOption(image_info,""png:include-chunks""); + + if (source == 5) + value=GetImageArtifact(image,""png:include-chunks""); + + if (source == 6) + value=GetImageOption(image_info,""png:include-chunk""); + + if (source == 7) + value=GetImageArtifact(image,""png:include-chunk""); + + if (value == NULL) + continue; + + if (source < 4) + excluding = MagickTrue; + else + excluding = MagickFalse; + + if (logging != MagickFalse) + { + if (source == 0 || source == 2) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" png:exclude-chunk=%s found in image options.\n"", value); + else if (source == 1 || source == 3) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" png:exclude-chunk=%s found in image artifacts.\n"", value); + else if (source == 4 || source == 6) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" png:include-chunk=%s found in image options.\n"", value); + else /* if (source == 5 || source == 7) */ + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" png:include-chunk=%s found in image artifacts.\n"", value); + } + + if (IsOptionMember(""all"",value) != MagickFalse) + { + mng_info->ping_exclude_bKGD=excluding; + mng_info->ping_exclude_caNv=excluding; + mng_info->ping_exclude_cHRM=excluding; + mng_info->ping_exclude_date=excluding; + mng_info->ping_exclude_EXIF=excluding; + mng_info->ping_exclude_eXIf=excluding; + mng_info->ping_exclude_gAMA=excluding; + mng_info->ping_exclude_iCCP=excluding; + /* mng_info->ping_exclude_iTXt=excluding; */ + mng_info->ping_exclude_oFFs=excluding; + mng_info->ping_exclude_pHYs=excluding; + mng_info->ping_exclude_sRGB=excluding; + mng_info->ping_exclude_tIME=excluding; + mng_info->ping_exclude_tEXt=excluding; + mng_info->ping_exclude_tRNS=excluding; + mng_info->ping_exclude_zCCP=excluding; + mng_info->ping_exclude_zTXt=excluding; + } + + if (IsOptionMember(""none"",value) != MagickFalse) + { + mng_info->ping_exclude_bKGD=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_caNv=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_cHRM=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_date=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_eXIf=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_EXIF=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_gAMA=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_iCCP=excluding != MagickFalse ? MagickFalse : + MagickTrue; + /* mng_info->ping_exclude_iTXt=!excluding; */ + mng_info->ping_exclude_oFFs=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_pHYs=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_sRGB=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_tEXt=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_tIME=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_tRNS=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_zCCP=excluding != MagickFalse ? MagickFalse : + MagickTrue; + mng_info->ping_exclude_zTXt=excluding != MagickFalse ? MagickFalse : + MagickTrue; + } + + if (IsOptionMember(""bkgd"",value) != MagickFalse) + mng_info->ping_exclude_bKGD=excluding; + + if (IsOptionMember(""caNv"",value) != MagickFalse) + mng_info->ping_exclude_caNv=excluding; + + if (IsOptionMember(""chrm"",value) != MagickFalse) + mng_info->ping_exclude_cHRM=excluding; + + if (IsOptionMember(""date"",value) != MagickFalse) + mng_info->ping_exclude_date=excluding; + + if (IsOptionMember(""exif"",value) != MagickFalse) + { + mng_info->ping_exclude_EXIF=excluding; + mng_info->ping_exclude_eXIf=excluding; + } + + if (IsOptionMember(""gama"",value) != MagickFalse) + mng_info->ping_exclude_gAMA=excluding; + + if (IsOptionMember(""iccp"",value) != MagickFalse) + mng_info->ping_exclude_iCCP=excluding; + +#if 0 + if (IsOptionMember(""itxt"",value) != MagickFalse) + mng_info->ping_exclude_iTXt=excluding; +#endif + + if (IsOptionMember(""offs"",value) != MagickFalse) + mng_info->ping_exclude_oFFs=excluding; + + if (IsOptionMember(""phys"",value) != MagickFalse) + mng_info->ping_exclude_pHYs=excluding; + + if (IsOptionMember(""srgb"",value) != MagickFalse) + mng_info->ping_exclude_sRGB=excluding; + + if (IsOptionMember(""text"",value) != MagickFalse) + mng_info->ping_exclude_tEXt=excluding; + + if (IsOptionMember(""time"",value) != MagickFalse) + mng_info->ping_exclude_tIME=excluding; + + if (IsOptionMember(""trns"",value) != MagickFalse) + mng_info->ping_exclude_tRNS=excluding; + + if (IsOptionMember(""zccp"",value) != MagickFalse) + mng_info->ping_exclude_zCCP=excluding; + + if (IsOptionMember(""ztxt"",value) != MagickFalse) + mng_info->ping_exclude_zTXt=excluding; + } + + if (logging != MagickFalse) + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Chunks to be excluded from the output png:""); + if (mng_info->ping_exclude_bKGD != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" bKGD""); + if (mng_info->ping_exclude_caNv != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" caNv""); + if (mng_info->ping_exclude_cHRM != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" cHRM""); + if (mng_info->ping_exclude_date != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" date""); + if (mng_info->ping_exclude_EXIF != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" EXIF""); + if (mng_info->ping_exclude_eXIf != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" eXIf""); + if (mng_info->ping_exclude_gAMA != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" gAMA""); + if (mng_info->ping_exclude_iCCP != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" iCCP""); +#if 0 + if (mng_info->ping_exclude_iTXt != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" iTXt""); +#endif + + if (mng_info->ping_exclude_oFFs != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" oFFs""); + if (mng_info->ping_exclude_pHYs != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" pHYs""); + if (mng_info->ping_exclude_sRGB != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" sRGB""); + if (mng_info->ping_exclude_tEXt != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" tEXt""); + if (mng_info->ping_exclude_tIME != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" tIME""); + if (mng_info->ping_exclude_tRNS != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" tRNS""); + if (mng_info->ping_exclude_zCCP != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" zCCP""); + if (mng_info->ping_exclude_zTXt != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" zTXt""); + } + + mng_info->need_blob = MagickTrue; + + status=WriteOnePNGImage(mng_info,image_info,image); + + (void) CloseBlob(image); + + mng_info=MngInfoFreeStruct(mng_info); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(),""exit WritePNGImage()""); + + return(status); +} +","@@ -4584,7 +4584,7 @@ static Image *ReadOneJNGImage(MngInfo *mng_info, + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Copying JDAT chunk data to color_blob.""); + +- if (length != 0) ++ if ((length != 0) && (color_image != (Image *) NULL)) + { + (void) WriteBlob(color_image,length,chunk); + chunk=(unsigned char *) RelinquishMagickMemory(chunk);",6428,6759,8192 +9292,"main(int argc, char **argv) +{ + register int cnt, op, i; + bpf_u_int32 localnet =0 , netmask = 0; + int timezone_offset = 0; + register char *cp, *infile, *cmdbuf, *device, *RFileName, *VFileName, *WFileName; + pcap_handler callback; + int dlt; + const char *dlt_name; + struct bpf_program fcode; +#ifndef _WIN32 + RETSIGTYPE (*oldhandler)(int); +#endif + struct dump_info dumpinfo; + u_char *pcap_userdata; + char ebuf[PCAP_ERRBUF_SIZE]; + char VFileLine[PATH_MAX + 1]; + char *username = NULL; + char *chroot_dir = NULL; + char *ret = NULL; + char *end; +#ifdef HAVE_PCAP_FINDALLDEVS + pcap_if_t *devlist; + long devnum; +#endif + int status; + FILE *VFile; +#ifdef HAVE_CAPSICUM + cap_rights_t rights; + int cansandbox; +#endif /* HAVE_CAPSICUM */ + int Oflag = 1; /* run filter code optimizer */ + int yflag_dlt = -1; + const char *yflag_dlt_name = NULL; + + netdissect_options Ndo; + netdissect_options *ndo = &Ndo; + + /* + * Initialize the netdissect code. + */ + if (nd_init(ebuf, sizeof ebuf) == -1) + error(""%s"", ebuf); + + memset(ndo, 0, sizeof(*ndo)); + ndo_set_function_pointers(ndo); + ndo->ndo_snaplen = DEFAULT_SNAPLEN; + + cnt = -1; + device = NULL; + infile = NULL; + RFileName = NULL; + VFileName = NULL; + VFile = NULL; + WFileName = NULL; + dlt = -1; + if ((cp = strrchr(argv[0], '/')) != NULL) + ndo->program_name = program_name = cp + 1; + else + ndo->program_name = program_name = argv[0]; + +#ifdef _WIN32 + if (pcap_wsockinit() != 0) + error(""Attempting to initialize Winsock failed""); +#endif /* _WIN32 */ + + /* + * On platforms where the CPU doesn't support unaligned loads, + * force unaligned accesses to abort with SIGBUS, rather than + * being fixed up (slowly) by the OS kernel; on those platforms, + * misaligned accesses are bugs, and we want tcpdump to crash so + * that the bugs are reported. + */ + if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0) + error(""%s"", ebuf); + + while ( + (op = getopt_long(argc, argv, SHORTOPTS, longopts, NULL)) != -1) + switch (op) { + + case 'a': + /* compatibility for old -a */ + break; + + case 'A': + ++ndo->ndo_Aflag; + break; + + case 'b': + ++ndo->ndo_bflag; + break; + +#if defined(HAVE_PCAP_CREATE) || defined(_WIN32) + case 'B': + Bflag = atoi(optarg)*1024; + if (Bflag <= 0) + error(""invalid packet buffer size %s"", optarg); + break; +#endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */ + + case 'c': + cnt = atoi(optarg); + if (cnt <= 0) + error(""invalid packet count %s"", optarg); + break; + + case 'C': + Cflag = atoi(optarg) * 1000000; + if (Cflag <= 0) + error(""invalid file size %s"", optarg); + break; + + case 'd': + ++dflag; + break; + + case 'D': + Dflag++; + break; + + case 'L': + Lflag++; + break; + + case 'e': + ++ndo->ndo_eflag; + break; + + case 'E': +#ifndef HAVE_LIBCRYPTO + warning(""crypto code not compiled in""); +#endif + ndo->ndo_espsecret = optarg; + break; + + case 'f': + ++ndo->ndo_fflag; + break; + + case 'F': + infile = optarg; + break; + + case 'G': + Gflag = atoi(optarg); + if (Gflag < 0) + error(""invalid number of seconds %s"", optarg); + + /* We will create one file initially. */ + Gflag_count = 0; + + /* Grab the current time for rotation use. */ + if ((Gflag_time = time(NULL)) == (time_t)-1) { + error(""main: can't get current time: %s"", + pcap_strerror(errno)); + } + break; + + case 'h': + print_usage(); + exit_tcpdump(0); + break; + + case 'H': + ++ndo->ndo_Hflag; + break; + + case 'i': + device = optarg; + break; + +#ifdef HAVE_PCAP_CREATE + case 'I': + ++Iflag; + break; +#endif /* HAVE_PCAP_CREATE */ + +#ifdef HAVE_PCAP_SET_TSTAMP_TYPE + case 'j': + jflag = pcap_tstamp_type_name_to_val(optarg); + if (jflag < 0) + error(""invalid time stamp type %s"", optarg); + break; + + case 'J': + Jflag++; + break; +#endif + + case 'l': +#ifdef _WIN32 + /* + * _IOLBF is the same as _IOFBF in Microsoft's C + * libraries; the only alternative they offer + * is _IONBF. + * + * XXX - this should really be checking for MSVC++, + * not _WIN32, if, for example, MinGW has its own + * C library that is more UNIX-compatible. + */ + setvbuf(stdout, NULL, _IONBF, 0); +#else /* _WIN32 */ +#ifdef HAVE_SETLINEBUF + setlinebuf(stdout); +#else + setvbuf(stdout, NULL, _IOLBF, 0); +#endif +#endif /* _WIN32 */ + break; + + case 'K': + ++ndo->ndo_Kflag; + break; + + case 'm': + if (nd_have_smi_support()) { + if (nd_load_smi_module(optarg, ebuf, sizeof ebuf) == -1) + error(""%s"", ebuf); + } else { + (void)fprintf(stderr, ""%s: ignoring option `-m %s' "", + program_name, optarg); + (void)fprintf(stderr, ""(no libsmi support)\n""); + } + break; + + case 'M': + /* TCP-MD5 shared secret */ +#ifndef HAVE_LIBCRYPTO + warning(""crypto code not compiled in""); +#endif + ndo->ndo_sigsecret = optarg; + break; + + case 'n': + ++ndo->ndo_nflag; + break; + + case 'N': + ++ndo->ndo_Nflag; + break; + + case 'O': + Oflag = 0; + break; + + case 'p': + ++pflag; + break; + + case 'q': + ++ndo->ndo_qflag; + ++ndo->ndo_suppress_default_print; + break; + +#ifdef HAVE_PCAP_SETDIRECTION + case 'Q': + if (ascii_strcasecmp(optarg, ""in"") == 0) + Qflag = PCAP_D_IN; + else if (ascii_strcasecmp(optarg, ""out"") == 0) + Qflag = PCAP_D_OUT; + else if (ascii_strcasecmp(optarg, ""inout"") == 0) + Qflag = PCAP_D_INOUT; + else + error(""unknown capture direction `%s'"", optarg); + break; +#endif /* HAVE_PCAP_SETDIRECTION */ + + case 'r': + RFileName = optarg; + break; + + case 's': + ndo->ndo_snaplen = strtol(optarg, &end, 0); + if (optarg == end || *end != '\0' + || ndo->ndo_snaplen < 0 || ndo->ndo_snaplen > MAXIMUM_SNAPLEN) + error(""invalid snaplen %s"", optarg); + else if (ndo->ndo_snaplen == 0) + ndo->ndo_snaplen = MAXIMUM_SNAPLEN; + break; + + case 'S': + ++ndo->ndo_Sflag; + break; + + case 't': + ++ndo->ndo_tflag; + break; + + case 'T': + if (ascii_strcasecmp(optarg, ""vat"") == 0) + ndo->ndo_packettype = PT_VAT; + else if (ascii_strcasecmp(optarg, ""wb"") == 0) + ndo->ndo_packettype = PT_WB; + else if (ascii_strcasecmp(optarg, ""rpc"") == 0) + ndo->ndo_packettype = PT_RPC; + else if (ascii_strcasecmp(optarg, ""rtp"") == 0) + ndo->ndo_packettype = PT_RTP; + else if (ascii_strcasecmp(optarg, ""rtcp"") == 0) + ndo->ndo_packettype = PT_RTCP; + else if (ascii_strcasecmp(optarg, ""snmp"") == 0) + ndo->ndo_packettype = PT_SNMP; + else if (ascii_strcasecmp(optarg, ""cnfp"") == 0) + ndo->ndo_packettype = PT_CNFP; + else if (ascii_strcasecmp(optarg, ""tftp"") == 0) + ndo->ndo_packettype = PT_TFTP; + else if (ascii_strcasecmp(optarg, ""aodv"") == 0) + ndo->ndo_packettype = PT_AODV; + else if (ascii_strcasecmp(optarg, ""carp"") == 0) + ndo->ndo_packettype = PT_CARP; + else if (ascii_strcasecmp(optarg, ""radius"") == 0) + ndo->ndo_packettype = PT_RADIUS; + else if (ascii_strcasecmp(optarg, ""zmtp1"") == 0) + ndo->ndo_packettype = PT_ZMTP1; + else if (ascii_strcasecmp(optarg, ""vxlan"") == 0) + ndo->ndo_packettype = PT_VXLAN; + else if (ascii_strcasecmp(optarg, ""pgm"") == 0) + ndo->ndo_packettype = PT_PGM; + else if (ascii_strcasecmp(optarg, ""pgm_zmtp1"") == 0) + ndo->ndo_packettype = PT_PGM_ZMTP1; + else if (ascii_strcasecmp(optarg, ""lmp"") == 0) + ndo->ndo_packettype = PT_LMP; + else if (ascii_strcasecmp(optarg, ""resp"") == 0) + ndo->ndo_packettype = PT_RESP; + else + error(""unknown packet type `%s'"", optarg); + break; + + case 'u': + ++ndo->ndo_uflag; + break; + +#ifdef HAVE_PCAP_DUMP_FLUSH + case 'U': + ++Uflag; + break; +#endif + + case 'v': + ++ndo->ndo_vflag; + break; + + case 'V': + VFileName = optarg; + break; + + case 'w': + WFileName = optarg; + break; + + case 'W': + Wflag = atoi(optarg); + if (Wflag <= 0) + error(""invalid number of output files %s"", optarg); + WflagChars = getWflagChars(Wflag); + break; + + case 'x': + ++ndo->ndo_xflag; + ++ndo->ndo_suppress_default_print; + break; + + case 'X': + ++ndo->ndo_Xflag; + ++ndo->ndo_suppress_default_print; + break; + + case 'y': + yflag_dlt_name = optarg; + yflag_dlt = + pcap_datalink_name_to_val(yflag_dlt_name); + if (yflag_dlt < 0) + error(""invalid data link type %s"", yflag_dlt_name); + break; + +#ifdef HAVE_PCAP_SET_PARSER_DEBUG + case 'Y': + { + /* Undocumented flag */ + pcap_set_parser_debug(1); + } + break; +#endif + case 'z': + zflag = optarg; + break; + + case 'Z': + username = optarg; + break; + + case '#': + ndo->ndo_packet_number = 1; + break; + + case OPTION_VERSION: + print_version(); + exit_tcpdump(0); + break; + +#ifdef HAVE_PCAP_SET_TSTAMP_PRECISION + case OPTION_TSTAMP_PRECISION: + ndo->ndo_tstamp_precision = tstamp_precision_from_string(optarg); + if (ndo->ndo_tstamp_precision < 0) + error(""unsupported time stamp precision""); + break; +#endif + +#ifdef HAVE_PCAP_SET_IMMEDIATE_MODE + case OPTION_IMMEDIATE_MODE: + immediate_mode = 1; + break; +#endif + + default: + print_usage(); + exit_tcpdump(1); + /* NOTREACHED */ + } + +#ifdef HAVE_PCAP_FINDALLDEVS + if (Dflag) + show_devices_and_exit(); +#endif + + switch (ndo->ndo_tflag) { + + case 0: /* Default */ + case 4: /* Default + Date*/ + timezone_offset = gmt2local(0); + break; + + case 1: /* No time stamp */ + case 2: /* Unix timeval style */ + case 3: /* Microseconds since previous packet */ + case 5: /* Microseconds since first packet */ + break; + + default: /* Not supported */ + error(""only -t, -tt, -ttt, -tttt and -ttttt are supported""); + break; + } + + if (ndo->ndo_fflag != 0 && (VFileName != NULL || RFileName != NULL)) + error(""-f can not be used with -V or -r""); + + if (VFileName != NULL && RFileName != NULL) + error(""-V and -r are mutually exclusive.""); + +#ifdef HAVE_PCAP_SET_IMMEDIATE_MODE + /* + * If we're printing dissected packets to the standard output + * rather than saving raw packets to a file, and the standard + * output is a terminal, use immediate mode, as the user's + * probably expecting to see packets pop up immediately. + */ + if (WFileName == NULL && isatty(1)) + immediate_mode = 1; +#endif + +#ifdef WITH_CHROOT + /* if run as root, prepare for chrooting */ + if (getuid() == 0 || geteuid() == 0) { + /* future extensibility for cmd-line arguments */ + if (!chroot_dir) + chroot_dir = WITH_CHROOT; + } +#endif + +#ifdef WITH_USER + /* if run as root, prepare for dropping root privileges */ + if (getuid() == 0 || geteuid() == 0) { + /* Run with '-Z root' to restore old behaviour */ + if (!username) + username = WITH_USER; + } +#endif + + if (RFileName != NULL || VFileName != NULL) { + /* + * If RFileName is non-null, it's the pathname of a + * savefile to read. If VFileName is non-null, it's + * the pathname of a file containing a list of pathnames + * (one per line) of savefiles to read. + * + * In either case, we're reading a savefile, not doing + * a live capture. + */ +#ifndef _WIN32 + /* + * We don't need network access, so relinquish any set-UID + * or set-GID privileges we have (if any). + * + * We do *not* want set-UID privileges when opening a + * trace file, as that might let the user read other + * people's trace files (especially if we're set-UID + * root). + */ + if (setgid(getgid()) != 0 || setuid(getuid()) != 0 ) + fprintf(stderr, ""Warning: setgid/setuid failed !\n""); +#endif /* _WIN32 */ + if (VFileName != NULL) { + if (VFileName[0] == '-' && VFileName[1] == '\0') + VFile = stdin; + else + VFile = fopen(VFileName, ""r""); + + if (VFile == NULL) + error(""Unable to open file: %s\n"", pcap_strerror(errno)); + + ret = get_next_file(VFile, VFileLine); + if (!ret) + error(""Nothing in %s\n"", VFileName); + RFileName = VFileLine; + } + +#ifdef HAVE_PCAP_SET_TSTAMP_PRECISION + pd = pcap_open_offline_with_tstamp_precision(RFileName, + ndo->ndo_tstamp_precision, ebuf); +#else + pd = pcap_open_offline(RFileName, ebuf); +#endif + + if (pd == NULL) + error(""%s"", ebuf); +#ifdef HAVE_CAPSICUM + cap_rights_init(&rights, CAP_READ); + if (cap_rights_limit(fileno(pcap_file(pd)), &rights) < 0 && + errno != ENOSYS) { + error(""unable to limit pcap descriptor""); + } +#endif + dlt = pcap_datalink(pd); + dlt_name = pcap_datalink_val_to_name(dlt); + if (dlt_name == NULL) { + fprintf(stderr, ""reading from file %s, link-type %u\n"", + RFileName, dlt); + } else { + fprintf(stderr, + ""reading from file %s, link-type %s (%s)\n"", + RFileName, dlt_name, + pcap_datalink_val_to_description(dlt)); + } + } else { + /* + * We're doing a live capture. + */ + if (device == NULL) { + /* + * No interface was specified. Pick one. + */ +#ifdef HAVE_PCAP_FINDALLDEVS + /* + * Find the list of interfaces, and pick + * the first interface. + */ + if (pcap_findalldevs(&devlist, ebuf) >= 0 && + devlist != NULL) { + device = strdup(devlist->name); + pcap_freealldevs(devlist); + } +#else /* HAVE_PCAP_FINDALLDEVS */ + /* + * Use whatever interface pcap_lookupdev() + * chooses. + */ + device = pcap_lookupdev(ebuf); +#endif + if (device == NULL) + error(""%s"", ebuf); + } + + /* + * Try to open the interface with the specified name. + */ + pd = open_interface(device, ndo, ebuf); + if (pd == NULL) { + /* + * That failed. If we can get a list of + * interfaces, and the interface name + * is purely numeric, try to use it as + * a 1-based index in the list of + * interfaces. + */ +#ifdef HAVE_PCAP_FINDALLDEVS + devnum = parse_interface_number(device); + if (devnum == -1) { + /* + * It's not a number; just report + * the open error and fail. + */ + error(""%s"", ebuf); + } + + /* + * OK, it's a number; try to find the + * interface with that index, and try + * to open it. + * + * find_interface_by_number() exits if it + * couldn't be found. + */ + device = find_interface_by_number(devnum); + pd = open_interface(device, ndo, ebuf); + if (pd == NULL) + error(""%s"", ebuf); +#else /* HAVE_PCAP_FINDALLDEVS */ + /* + * We can't get a list of interfaces; just + * fail. + */ + error(""%s"", ebuf); +#endif /* HAVE_PCAP_FINDALLDEVS */ + } + + /* + * Let user own process after socket has been opened. + */ +#ifndef _WIN32 + if (setgid(getgid()) != 0 || setuid(getuid()) != 0) + fprintf(stderr, ""Warning: setgid/setuid failed !\n""); +#endif /* _WIN32 */ +#if !defined(HAVE_PCAP_CREATE) && defined(_WIN32) + if(Bflag != 0) + if(pcap_setbuff(pd, Bflag)==-1){ + error(""%s"", pcap_geterr(pd)); + } +#endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */ + if (Lflag) + show_dlts_and_exit(pd, device); + if (yflag_dlt >= 0) { +#ifdef HAVE_PCAP_SET_DATALINK + if (pcap_set_datalink(pd, yflag_dlt) < 0) + error(""%s"", pcap_geterr(pd)); +#else + /* + * We don't actually support changing the + * data link type, so we only let them + * set it to what it already is. + */ + if (yflag_dlt != pcap_datalink(pd)) { + error(""%s is not one of the DLTs supported by this device\n"", + yflag_dlt_name); + } +#endif + (void)fprintf(stderr, ""%s: data link type %s\n"", + program_name, yflag_dlt_name); + (void)fflush(stderr); + } + i = pcap_snapshot(pd); + if (ndo->ndo_snaplen < i) { + warning(""snaplen raised from %d to %d"", ndo->ndo_snaplen, i); + ndo->ndo_snaplen = i; + } + if(ndo->ndo_fflag != 0) { + if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) { + warning(""foreign (-f) flag used but: %s"", ebuf); + } + } + + } + if (infile) + cmdbuf = read_infile(infile); + else + cmdbuf = copy_argv(&argv[optind]); + +#ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG + pcap_set_optimizer_debug(dflag); +#endif + if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0) + error(""%s"", pcap_geterr(pd)); + if (dflag) { + bpf_dump(&fcode, dflag); + pcap_close(pd); + free(cmdbuf); + pcap_freecode(&fcode); + exit_tcpdump(0); + } + init_print(ndo, localnet, netmask, timezone_offset); + +#ifndef _WIN32 + (void)setsignal(SIGPIPE, cleanup); + (void)setsignal(SIGTERM, cleanup); + (void)setsignal(SIGINT, cleanup); +#endif /* _WIN32 */ +#if defined(HAVE_FORK) || defined(HAVE_VFORK) + (void)setsignal(SIGCHLD, child_cleanup); +#endif + /* Cooperate with nohup(1) */ +#ifndef _WIN32 + if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL) + (void)setsignal(SIGHUP, oldhandler); +#endif /* _WIN32 */ + +#ifndef _WIN32 + /* + * If a user name was specified with ""-Z"", attempt to switch to + * that user's UID. This would probably be used with sudo, + * to allow tcpdump to be run in a special restricted + * account (if you just want to allow users to open capture + * devices, and can't just give users that permission, + * you'd make tcpdump set-UID or set-GID). + * + * Tcpdump doesn't necessarily write only to one savefile; + * the general only way to allow a -Z instance to write to + * savefiles as the user under whose UID it's run, rather + * than as the user specified with -Z, would thus be to switch + * to the original user ID before opening a capture file and + * then switch back to the -Z user ID after opening the savefile. + * Switching to the -Z user ID only after opening the first + * savefile doesn't handle the general case. + */ + + if (getuid() == 0 || geteuid() == 0) { +#ifdef HAVE_LIBCAP_NG + /* Initialize capng */ + capng_clear(CAPNG_SELECT_BOTH); + if (username) { + capng_updatev( + CAPNG_ADD, + CAPNG_PERMITTED | CAPNG_EFFECTIVE, + CAP_SETUID, + CAP_SETGID, + -1); + } + if (chroot_dir) { + capng_update( + CAPNG_ADD, + CAPNG_PERMITTED | CAPNG_EFFECTIVE, + CAP_SYS_CHROOT + ); + } + + if (WFileName) { + capng_update( + CAPNG_ADD, + CAPNG_PERMITTED | CAPNG_EFFECTIVE, + CAP_DAC_OVERRIDE + ); + } + capng_apply(CAPNG_SELECT_BOTH); +#endif /* HAVE_LIBCAP_NG */ + if (username || chroot_dir) + droproot(username, chroot_dir); + + } +#endif /* _WIN32 */ + + if (pcap_setfilter(pd, &fcode) < 0) + error(""%s"", pcap_geterr(pd)); +#ifdef HAVE_CAPSICUM + if (RFileName == NULL && VFileName == NULL) { + static const unsigned long cmds[] = { BIOCGSTATS, BIOCROTZBUF }; + + /* + * The various libpcap devices use a combination of + * read (bpf), ioctl (bpf, netmap), poll (netmap) + * so we add the relevant access rights. + */ + cap_rights_init(&rights, CAP_IOCTL, CAP_READ, CAP_EVENT); + if (cap_rights_limit(pcap_fileno(pd), &rights) < 0 && + errno != ENOSYS) { + error(""unable to limit pcap descriptor""); + } + if (cap_ioctls_limit(pcap_fileno(pd), cmds, + sizeof(cmds) / sizeof(cmds[0])) < 0 && errno != ENOSYS) { + error(""unable to limit ioctls on pcap descriptor""); + } + } +#endif + if (WFileName) { + pcap_dumper_t *p; + /* Do not exceed the default PATH_MAX for files. */ + dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1); + + if (dumpinfo.CurrentFileName == NULL) + error(""malloc of dumpinfo.CurrentFileName""); + + /* We do not need numbering for dumpfiles if Cflag isn't set. */ + if (Cflag != 0) + MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars); + else + MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0); + + p = pcap_dump_open(pd, dumpinfo.CurrentFileName); +#ifdef HAVE_LIBCAP_NG + /* Give up CAP_DAC_OVERRIDE capability. + * Only allow it to be restored if the -C or -G flag have been + * set since we may need to create more files later on. + */ + capng_update( + CAPNG_DROP, + (Cflag || Gflag ? 0 : CAPNG_PERMITTED) + | CAPNG_EFFECTIVE, + CAP_DAC_OVERRIDE + ); + capng_apply(CAPNG_SELECT_BOTH); +#endif /* HAVE_LIBCAP_NG */ + if (p == NULL) + error(""%s"", pcap_geterr(pd)); +#ifdef HAVE_CAPSICUM + set_dumper_capsicum_rights(p); +#endif + if (Cflag != 0 || Gflag != 0) { +#ifdef HAVE_CAPSICUM + dumpinfo.WFileName = strdup(basename(WFileName)); + if (dumpinfo.WFileName == NULL) { + error(""Unable to allocate memory for file %s"", + WFileName); + } + dumpinfo.dirfd = open(dirname(WFileName), + O_DIRECTORY | O_RDONLY); + if (dumpinfo.dirfd < 0) { + error(""unable to open directory %s"", + dirname(WFileName)); + } + cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL, + CAP_FTRUNCATE, CAP_LOOKUP, CAP_SEEK, CAP_WRITE); + if (cap_rights_limit(dumpinfo.dirfd, &rights) < 0 && + errno != ENOSYS) { + error(""unable to limit directory rights""); + } + if (cap_fcntls_limit(dumpinfo.dirfd, CAP_FCNTL_GETFL) < 0 && + errno != ENOSYS) { + error(""unable to limit dump descriptor fcntls""); + } +#else /* !HAVE_CAPSICUM */ + dumpinfo.WFileName = WFileName; +#endif + callback = dump_packet_and_trunc; + dumpinfo.pd = pd; + dumpinfo.p = p; + pcap_userdata = (u_char *)&dumpinfo; + } else { + callback = dump_packet; + pcap_userdata = (u_char *)p; + } +#ifdef HAVE_PCAP_DUMP_FLUSH + if (Uflag) + pcap_dump_flush(p); +#endif + } else { + dlt = pcap_datalink(pd); + ndo->ndo_if_printer = get_if_printer(ndo, dlt); + callback = print_packet; + pcap_userdata = (u_char *)ndo; + } + +#ifdef SIGNAL_REQ_INFO + /* + * We can't get statistics when reading from a file rather + * than capturing from a device. + */ + if (RFileName == NULL) + (void)setsignal(SIGNAL_REQ_INFO, requestinfo); +#endif + + if (ndo->ndo_vflag > 0 && WFileName) { + /* + * When capturing to a file, ""-v"" means tcpdump should, + * every 10 seconds, ""v""erbosely report the number of + * packets captured. + */ +#ifdef USE_WIN32_MM_TIMER + /* call verbose_stats_dump() each 1000 +/-100msec */ + timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC); + setvbuf(stderr, NULL, _IONBF, 0); +#elif defined(HAVE_ALARM) + (void)setsignal(SIGALRM, verbose_stats_dump); + alarm(1); +#endif + } + + if (RFileName == NULL) { + /* + * Live capture (if -V was specified, we set RFileName + * to a file from the -V file). Print a message to + * the standard error on UN*X. + */ + if (!ndo->ndo_vflag && !WFileName) { + (void)fprintf(stderr, + ""%s: verbose output suppressed, use -v or -vv for full protocol decode\n"", + program_name); + } else + (void)fprintf(stderr, ""%s: "", program_name); + dlt = pcap_datalink(pd); + dlt_name = pcap_datalink_val_to_name(dlt); + if (dlt_name == NULL) { + (void)fprintf(stderr, ""listening on %s, link-type %u, capture size %u bytes\n"", + device, dlt, ndo->ndo_snaplen); + } else { + (void)fprintf(stderr, ""listening on %s, link-type %s (%s), capture size %u bytes\n"", + device, dlt_name, + pcap_datalink_val_to_description(dlt), ndo->ndo_snaplen); + } + (void)fflush(stderr); + } + +#ifdef HAVE_CAPSICUM + cansandbox = (ndo->ndo_nflag && VFileName == NULL && zflag == NULL); + if (cansandbox && cap_enter() < 0 && errno != ENOSYS) + error(""unable to enter the capability mode""); +#endif /* HAVE_CAPSICUM */ + + do { + status = pcap_loop(pd, cnt, callback, pcap_userdata); + if (WFileName == NULL) { + /* + * We're printing packets. Flush the printed output, + * so it doesn't get intermingled with error output. + */ + if (status == -2) { + /* + * We got interrupted, so perhaps we didn't + * manage to finish a line we were printing. + * Print an extra newline, just in case. + */ + putchar('\n'); + } + (void)fflush(stdout); + } + if (status == -2) { + /* + * We got interrupted. If we are reading multiple + * files (via -V) set these so that we stop. + */ + VFileName = NULL; + ret = NULL; + } + if (status == -1) { + /* + * Error. Report it. + */ + (void)fprintf(stderr, ""%s: pcap_loop: %s\n"", + program_name, pcap_geterr(pd)); + } + if (RFileName == NULL) { + /* + * We're doing a live capture. Report the capture + * statistics. + */ + info(1); + } + pcap_close(pd); + if (VFileName != NULL) { + ret = get_next_file(VFile, VFileLine); + if (ret) { + int new_dlt; + + RFileName = VFileLine; + pd = pcap_open_offline(RFileName, ebuf); + if (pd == NULL) + error(""%s"", ebuf); +#ifdef HAVE_CAPSICUM + cap_rights_init(&rights, CAP_READ); + if (cap_rights_limit(fileno(pcap_file(pd)), + &rights) < 0 && errno != ENOSYS) { + error(""unable to limit pcap descriptor""); + } +#endif + new_dlt = pcap_datalink(pd); + if (new_dlt != dlt) { + /* + * The new file has a different + * link-layer header type from the + * previous one. + */ + if (WFileName != NULL) { + /* + * We're writing raw packets + * that match the filter to + * a pcap file. pcap files + * don't support multiple + * different link-layer + * header types, so we fail + * here. + */ + error(""%s: new dlt does not match original"", RFileName); + } + + /* + * We're printing the decoded packets; + * switch to the new DLT. + * + * To do that, we need to change + * the printer, change the DLT name, + * and recompile the filter with + * the new DLT. + */ + dlt = new_dlt; + ndo->ndo_if_printer = get_if_printer(ndo, dlt); + if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0) + error(""%s"", pcap_geterr(pd)); + } + + /* + * Set the filter on the new file. + */ + if (pcap_setfilter(pd, &fcode) < 0) + error(""%s"", pcap_geterr(pd)); + + /* + * Report the new file. + */ + dlt_name = pcap_datalink_val_to_name(dlt); + if (dlt_name == NULL) { + fprintf(stderr, ""reading from file %s, link-type %u\n"", + RFileName, dlt); + } else { + fprintf(stderr, + ""reading from file %s, link-type %s (%s)\n"", + RFileName, dlt_name, + pcap_datalink_val_to_description(dlt)); + } + } + } + } + while (ret != NULL); + + free(cmdbuf); + pcap_freecode(&fcode); + exit_tcpdump(status == -1 ? 1 : 0); +} +",0,"main(int argc, char **argv) +{ + register int cnt, op, i; + bpf_u_int32 localnet =0 , netmask = 0; + int timezone_offset = 0; + register char *cp, *infile, *cmdbuf, *device, *RFileName, *VFileName, *WFileName; + pcap_handler callback; + int dlt; + const char *dlt_name; + struct bpf_program fcode; +#ifndef _WIN32 + RETSIGTYPE (*oldhandler)(int); +#endif + struct dump_info dumpinfo; + u_char *pcap_userdata; + char ebuf[PCAP_ERRBUF_SIZE]; + char VFileLine[PATH_MAX + 1]; + char *username = NULL; + char *chroot_dir = NULL; + char *ret = NULL; + char *end; +#ifdef HAVE_PCAP_FINDALLDEVS + pcap_if_t *devlist; + long devnum; +#endif + int status; + FILE *VFile; +#ifdef HAVE_CAPSICUM + cap_rights_t rights; + int cansandbox; +#endif /* HAVE_CAPSICUM */ + int Oflag = 1; /* run filter code optimizer */ + int yflag_dlt = -1; + const char *yflag_dlt_name = NULL; + + netdissect_options Ndo; + netdissect_options *ndo = &Ndo; + + /* + * Initialize the netdissect code. + */ + if (nd_init(ebuf, sizeof ebuf) == -1) + error(""%s"", ebuf); + + memset(ndo, 0, sizeof(*ndo)); + ndo_set_function_pointers(ndo); + ndo->ndo_snaplen = DEFAULT_SNAPLEN; + + cnt = -1; + device = NULL; + infile = NULL; + RFileName = NULL; + VFileName = NULL; + VFile = NULL; + WFileName = NULL; + dlt = -1; + if ((cp = strrchr(argv[0], '/')) != NULL) + ndo->program_name = program_name = cp + 1; + else + ndo->program_name = program_name = argv[0]; + +#ifdef _WIN32 + if (pcap_wsockinit() != 0) + error(""Attempting to initialize Winsock failed""); +#endif /* _WIN32 */ + + /* + * On platforms where the CPU doesn't support unaligned loads, + * force unaligned accesses to abort with SIGBUS, rather than + * being fixed up (slowly) by the OS kernel; on those platforms, + * misaligned accesses are bugs, and we want tcpdump to crash so + * that the bugs are reported. + */ + if (abort_on_misalignment(ebuf, sizeof(ebuf)) < 0) + error(""%s"", ebuf); + + while ( + (op = getopt_long(argc, argv, SHORTOPTS, longopts, NULL)) != -1) + switch (op) { + + case 'a': + /* compatibility for old -a */ + break; + + case 'A': + ++ndo->ndo_Aflag; + break; + + case 'b': + ++ndo->ndo_bflag; + break; + +#if defined(HAVE_PCAP_CREATE) || defined(_WIN32) + case 'B': + Bflag = atoi(optarg)*1024; + if (Bflag <= 0) + error(""invalid packet buffer size %s"", optarg); + break; +#endif /* defined(HAVE_PCAP_CREATE) || defined(_WIN32) */ + + case 'c': + cnt = atoi(optarg); + if (cnt <= 0) + error(""invalid packet count %s"", optarg); + break; + + case 'C': + Cflag = atoi(optarg) * 1000000; + if (Cflag <= 0) + error(""invalid file size %s"", optarg); + break; + + case 'd': + ++dflag; + break; + + case 'D': + Dflag++; + break; + + case 'L': + Lflag++; + break; + + case 'e': + ++ndo->ndo_eflag; + break; + + case 'E': +#ifndef HAVE_LIBCRYPTO + warning(""crypto code not compiled in""); +#endif + ndo->ndo_espsecret = optarg; + break; + + case 'f': + ++ndo->ndo_fflag; + break; + + case 'F': + infile = optarg; + break; + + case 'G': + Gflag = atoi(optarg); + if (Gflag < 0) + error(""invalid number of seconds %s"", optarg); + + /* We will create one file initially. */ + Gflag_count = 0; + + /* Grab the current time for rotation use. */ + if ((Gflag_time = time(NULL)) == (time_t)-1) { + error(""main: can't get current time: %s"", + pcap_strerror(errno)); + } + break; + + case 'h': + print_usage(); + exit_tcpdump(0); + break; + + case 'H': + ++ndo->ndo_Hflag; + break; + + case 'i': + device = optarg; + break; + +#ifdef HAVE_PCAP_CREATE + case 'I': + ++Iflag; + break; +#endif /* HAVE_PCAP_CREATE */ + +#ifdef HAVE_PCAP_SET_TSTAMP_TYPE + case 'j': + jflag = pcap_tstamp_type_name_to_val(optarg); + if (jflag < 0) + error(""invalid time stamp type %s"", optarg); + break; + + case 'J': + Jflag++; + break; +#endif + + case 'l': +#ifdef _WIN32 + /* + * _IOLBF is the same as _IOFBF in Microsoft's C + * libraries; the only alternative they offer + * is _IONBF. + * + * XXX - this should really be checking for MSVC++, + * not _WIN32, if, for example, MinGW has its own + * C library that is more UNIX-compatible. + */ + setvbuf(stdout, NULL, _IONBF, 0); +#else /* _WIN32 */ +#ifdef HAVE_SETLINEBUF + setlinebuf(stdout); +#else + setvbuf(stdout, NULL, _IOLBF, 0); +#endif +#endif /* _WIN32 */ + break; + + case 'K': + ++ndo->ndo_Kflag; + break; + + case 'm': + if (nd_have_smi_support()) { + if (nd_load_smi_module(optarg, ebuf, sizeof ebuf) == -1) + error(""%s"", ebuf); + } else { + (void)fprintf(stderr, ""%s: ignoring option `-m %s' "", + program_name, optarg); + (void)fprintf(stderr, ""(no libsmi support)\n""); + } + break; + + case 'M': + /* TCP-MD5 shared secret */ +#ifndef HAVE_LIBCRYPTO + warning(""crypto code not compiled in""); +#endif + ndo->ndo_sigsecret = optarg; + break; + + case 'n': + ++ndo->ndo_nflag; + break; + + case 'N': + ++ndo->ndo_Nflag; + break; + + case 'O': + Oflag = 0; + break; + + case 'p': + ++pflag; + break; + + case 'q': + ++ndo->ndo_qflag; + ++ndo->ndo_suppress_default_print; + break; + +#ifdef HAVE_PCAP_SETDIRECTION + case 'Q': + if (ascii_strcasecmp(optarg, ""in"") == 0) + Qflag = PCAP_D_IN; + else if (ascii_strcasecmp(optarg, ""out"") == 0) + Qflag = PCAP_D_OUT; + else if (ascii_strcasecmp(optarg, ""inout"") == 0) + Qflag = PCAP_D_INOUT; + else + error(""unknown capture direction `%s'"", optarg); + break; +#endif /* HAVE_PCAP_SETDIRECTION */ + + case 'r': + RFileName = optarg; + break; + + case 's': + ndo->ndo_snaplen = strtol(optarg, &end, 0); + if (optarg == end || *end != '\0' + || ndo->ndo_snaplen < 0 || ndo->ndo_snaplen > MAXIMUM_SNAPLEN) + error(""invalid snaplen %s"", optarg); + else if (ndo->ndo_snaplen == 0) + ndo->ndo_snaplen = MAXIMUM_SNAPLEN; + break; + + case 'S': + ++ndo->ndo_Sflag; + break; + + case 't': + ++ndo->ndo_tflag; + break; + + case 'T': + if (ascii_strcasecmp(optarg, ""vat"") == 0) + ndo->ndo_packettype = PT_VAT; + else if (ascii_strcasecmp(optarg, ""wb"") == 0) + ndo->ndo_packettype = PT_WB; + else if (ascii_strcasecmp(optarg, ""rpc"") == 0) + ndo->ndo_packettype = PT_RPC; + else if (ascii_strcasecmp(optarg, ""rtp"") == 0) + ndo->ndo_packettype = PT_RTP; + else if (ascii_strcasecmp(optarg, ""rtcp"") == 0) + ndo->ndo_packettype = PT_RTCP; + else if (ascii_strcasecmp(optarg, ""snmp"") == 0) + ndo->ndo_packettype = PT_SNMP; + else if (ascii_strcasecmp(optarg, ""cnfp"") == 0) + ndo->ndo_packettype = PT_CNFP; + else if (ascii_strcasecmp(optarg, ""tftp"") == 0) + ndo->ndo_packettype = PT_TFTP; + else if (ascii_strcasecmp(optarg, ""aodv"") == 0) + ndo->ndo_packettype = PT_AODV; + else if (ascii_strcasecmp(optarg, ""carp"") == 0) + ndo->ndo_packettype = PT_CARP; + else if (ascii_strcasecmp(optarg, ""radius"") == 0) + ndo->ndo_packettype = PT_RADIUS; + else if (ascii_strcasecmp(optarg, ""zmtp1"") == 0) + ndo->ndo_packettype = PT_ZMTP1; + else if (ascii_strcasecmp(optarg, ""vxlan"") == 0) + ndo->ndo_packettype = PT_VXLAN; + else if (ascii_strcasecmp(optarg, ""pgm"") == 0) + ndo->ndo_packettype = PT_PGM; + else if (ascii_strcasecmp(optarg, ""pgm_zmtp1"") == 0) + ndo->ndo_packettype = PT_PGM_ZMTP1; + else if (ascii_strcasecmp(optarg, ""lmp"") == 0) + ndo->ndo_packettype = PT_LMP; + else if (ascii_strcasecmp(optarg, ""resp"") == 0) + ndo->ndo_packettype = PT_RESP; + else + error(""unknown packet type `%s'"", optarg); + break; + + case 'u': + ++ndo->ndo_uflag; + break; + +#ifdef HAVE_PCAP_DUMP_FLUSH + case 'U': + ++Uflag; + break; +#endif + + case 'v': + ++ndo->ndo_vflag; + break; + + case 'V': + VFileName = optarg; + break; + + case 'w': + WFileName = optarg; + break; + + case 'W': + Wflag = atoi(optarg); + if (Wflag <= 0) + error(""invalid number of output files %s"", optarg); + WflagChars = getWflagChars(Wflag); + break; + + case 'x': + ++ndo->ndo_xflag; + ++ndo->ndo_suppress_default_print; + break; + + case 'X': + ++ndo->ndo_Xflag; + ++ndo->ndo_suppress_default_print; + break; + + case 'y': + yflag_dlt_name = optarg; + yflag_dlt = + pcap_datalink_name_to_val(yflag_dlt_name); + if (yflag_dlt < 0) + error(""invalid data link type %s"", yflag_dlt_name); + break; + +#ifdef HAVE_PCAP_SET_PARSER_DEBUG + case 'Y': + { + /* Undocumented flag */ + pcap_set_parser_debug(1); + } + break; +#endif + case 'z': + zflag = optarg; + break; + + case 'Z': + username = optarg; + break; + + case '#': + ndo->ndo_packet_number = 1; + break; + + case OPTION_VERSION: + print_version(); + exit_tcpdump(0); + break; + +#ifdef HAVE_PCAP_SET_TSTAMP_PRECISION + case OPTION_TSTAMP_PRECISION: + ndo->ndo_tstamp_precision = tstamp_precision_from_string(optarg); + if (ndo->ndo_tstamp_precision < 0) + error(""unsupported time stamp precision""); + break; +#endif + +#ifdef HAVE_PCAP_SET_IMMEDIATE_MODE + case OPTION_IMMEDIATE_MODE: + immediate_mode = 1; + break; +#endif + + default: + print_usage(); + exit_tcpdump(1); + /* NOTREACHED */ + } + +#ifdef HAVE_PCAP_FINDALLDEVS + if (Dflag) + show_devices_and_exit(); +#endif + + switch (ndo->ndo_tflag) { + + case 0: /* Default */ + case 4: /* Default + Date*/ + timezone_offset = gmt2local(0); + break; + + case 1: /* No time stamp */ + case 2: /* Unix timeval style */ + case 3: /* Microseconds since previous packet */ + case 5: /* Microseconds since first packet */ + break; + + default: /* Not supported */ + error(""only -t, -tt, -ttt, -tttt and -ttttt are supported""); + break; + } + + if (ndo->ndo_fflag != 0 && (VFileName != NULL || RFileName != NULL)) + error(""-f can not be used with -V or -r""); + + if (VFileName != NULL && RFileName != NULL) + error(""-V and -r are mutually exclusive.""); + +#ifdef HAVE_PCAP_SET_IMMEDIATE_MODE + /* + * If we're printing dissected packets to the standard output + * rather than saving raw packets to a file, and the standard + * output is a terminal, use immediate mode, as the user's + * probably expecting to see packets pop up immediately. + */ + if (WFileName == NULL && isatty(1)) + immediate_mode = 1; +#endif + +#ifdef WITH_CHROOT + /* if run as root, prepare for chrooting */ + if (getuid() == 0 || geteuid() == 0) { + /* future extensibility for cmd-line arguments */ + if (!chroot_dir) + chroot_dir = WITH_CHROOT; + } +#endif + +#ifdef WITH_USER + /* if run as root, prepare for dropping root privileges */ + if (getuid() == 0 || geteuid() == 0) { + /* Run with '-Z root' to restore old behaviour */ + if (!username) + username = WITH_USER; + } +#endif + + if (RFileName != NULL || VFileName != NULL) { + /* + * If RFileName is non-null, it's the pathname of a + * savefile to read. If VFileName is non-null, it's + * the pathname of a file containing a list of pathnames + * (one per line) of savefiles to read. + * + * In either case, we're reading a savefile, not doing + * a live capture. + */ +#ifndef _WIN32 + /* + * We don't need network access, so relinquish any set-UID + * or set-GID privileges we have (if any). + * + * We do *not* want set-UID privileges when opening a + * trace file, as that might let the user read other + * people's trace files (especially if we're set-UID + * root). + */ + if (setgid(getgid()) != 0 || setuid(getuid()) != 0 ) + fprintf(stderr, ""Warning: setgid/setuid failed !\n""); +#endif /* _WIN32 */ + if (VFileName != NULL) { + if (VFileName[0] == '-' && VFileName[1] == '\0') + VFile = stdin; + else + VFile = fopen(VFileName, ""r""); + + if (VFile == NULL) + error(""Unable to open file: %s\n"", pcap_strerror(errno)); + + ret = get_next_file(VFile, VFileLine); + if (!ret) + error(""Nothing in %s\n"", VFileName); + RFileName = VFileLine; + } + +#ifdef HAVE_PCAP_SET_TSTAMP_PRECISION + pd = pcap_open_offline_with_tstamp_precision(RFileName, + ndo->ndo_tstamp_precision, ebuf); +#else + pd = pcap_open_offline(RFileName, ebuf); +#endif + + if (pd == NULL) + error(""%s"", ebuf); +#ifdef HAVE_CAPSICUM + cap_rights_init(&rights, CAP_READ); + if (cap_rights_limit(fileno(pcap_file(pd)), &rights) < 0 && + errno != ENOSYS) { + error(""unable to limit pcap descriptor""); + } +#endif + dlt = pcap_datalink(pd); + dlt_name = pcap_datalink_val_to_name(dlt); + if (dlt_name == NULL) { + fprintf(stderr, ""reading from file %s, link-type %u\n"", + RFileName, dlt); + } else { + fprintf(stderr, + ""reading from file %s, link-type %s (%s)\n"", + RFileName, dlt_name, + pcap_datalink_val_to_description(dlt)); + } + } else { + /* + * We're doing a live capture. + */ + if (device == NULL) { + /* + * No interface was specified. Pick one. + */ +#ifdef HAVE_PCAP_FINDALLDEVS + /* + * Find the list of interfaces, and pick + * the first interface. + */ + if (pcap_findalldevs(&devlist, ebuf) >= 0 && + devlist != NULL) { + device = strdup(devlist->name); + pcap_freealldevs(devlist); + } +#else /* HAVE_PCAP_FINDALLDEVS */ + /* + * Use whatever interface pcap_lookupdev() + * chooses. + */ + device = pcap_lookupdev(ebuf); +#endif + if (device == NULL) + error(""%s"", ebuf); + } + + /* + * Try to open the interface with the specified name. + */ + pd = open_interface(device, ndo, ebuf); + if (pd == NULL) { + /* + * That failed. If we can get a list of + * interfaces, and the interface name + * is purely numeric, try to use it as + * a 1-based index in the list of + * interfaces. + */ +#ifdef HAVE_PCAP_FINDALLDEVS + devnum = parse_interface_number(device); + if (devnum == -1) { + /* + * It's not a number; just report + * the open error and fail. + */ + error(""%s"", ebuf); + } + + /* + * OK, it's a number; try to find the + * interface with that index, and try + * to open it. + * + * find_interface_by_number() exits if it + * couldn't be found. + */ + device = find_interface_by_number(devnum); + pd = open_interface(device, ndo, ebuf); + if (pd == NULL) + error(""%s"", ebuf); +#else /* HAVE_PCAP_FINDALLDEVS */ + /* + * We can't get a list of interfaces; just + * fail. + */ + error(""%s"", ebuf); +#endif /* HAVE_PCAP_FINDALLDEVS */ + } + + /* + * Let user own process after socket has been opened. + */ +#ifndef _WIN32 + if (setgid(getgid()) != 0 || setuid(getuid()) != 0) + fprintf(stderr, ""Warning: setgid/setuid failed !\n""); +#endif /* _WIN32 */ +#if !defined(HAVE_PCAP_CREATE) && defined(_WIN32) + if(Bflag != 0) + if(pcap_setbuff(pd, Bflag)==-1){ + error(""%s"", pcap_geterr(pd)); + } +#endif /* !defined(HAVE_PCAP_CREATE) && defined(_WIN32) */ + if (Lflag) + show_dlts_and_exit(pd, device); + if (yflag_dlt >= 0) { +#ifdef HAVE_PCAP_SET_DATALINK + if (pcap_set_datalink(pd, yflag_dlt) < 0) + error(""%s"", pcap_geterr(pd)); +#else + /* + * We don't actually support changing the + * data link type, so we only let them + * set it to what it already is. + */ + if (yflag_dlt != pcap_datalink(pd)) { + error(""%s is not one of the DLTs supported by this device\n"", + yflag_dlt_name); + } +#endif + (void)fprintf(stderr, ""%s: data link type %s\n"", + program_name, yflag_dlt_name); + (void)fflush(stderr); + } + i = pcap_snapshot(pd); + if (ndo->ndo_snaplen < i) { + warning(""snaplen raised from %d to %d"", ndo->ndo_snaplen, i); + ndo->ndo_snaplen = i; + } + if(ndo->ndo_fflag != 0) { + if (pcap_lookupnet(device, &localnet, &netmask, ebuf) < 0) { + warning(""foreign (-f) flag used but: %s"", ebuf); + } + } + + } + if (infile) + cmdbuf = read_infile(infile); + else + cmdbuf = copy_argv(&argv[optind]); + +#ifdef HAVE_PCAP_SET_OPTIMIZER_DEBUG + pcap_set_optimizer_debug(dflag); +#endif + if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0) + error(""%s"", pcap_geterr(pd)); + if (dflag) { + bpf_dump(&fcode, dflag); + pcap_close(pd); + free(cmdbuf); + pcap_freecode(&fcode); + exit_tcpdump(0); + } + init_print(ndo, localnet, netmask, timezone_offset); + +#ifndef _WIN32 + (void)setsignal(SIGPIPE, cleanup); + (void)setsignal(SIGTERM, cleanup); + (void)setsignal(SIGINT, cleanup); +#endif /* _WIN32 */ +#if defined(HAVE_FORK) || defined(HAVE_VFORK) + (void)setsignal(SIGCHLD, child_cleanup); +#endif + /* Cooperate with nohup(1) */ +#ifndef _WIN32 + if ((oldhandler = setsignal(SIGHUP, cleanup)) != SIG_DFL) + (void)setsignal(SIGHUP, oldhandler); +#endif /* _WIN32 */ + +#ifndef _WIN32 + /* + * If a user name was specified with ""-Z"", attempt to switch to + * that user's UID. This would probably be used with sudo, + * to allow tcpdump to be run in a special restricted + * account (if you just want to allow users to open capture + * devices, and can't just give users that permission, + * you'd make tcpdump set-UID or set-GID). + * + * Tcpdump doesn't necessarily write only to one savefile; + * the general only way to allow a -Z instance to write to + * savefiles as the user under whose UID it's run, rather + * than as the user specified with -Z, would thus be to switch + * to the original user ID before opening a capture file and + * then switch back to the -Z user ID after opening the savefile. + * Switching to the -Z user ID only after opening the first + * savefile doesn't handle the general case. + */ + + if (getuid() == 0 || geteuid() == 0) { +#ifdef HAVE_LIBCAP_NG + /* Initialize capng */ + capng_clear(CAPNG_SELECT_BOTH); + if (username) { + capng_updatev( + CAPNG_ADD, + CAPNG_PERMITTED | CAPNG_EFFECTIVE, + CAP_SETUID, + CAP_SETGID, + -1); + } + if (chroot_dir) { + capng_update( + CAPNG_ADD, + CAPNG_PERMITTED | CAPNG_EFFECTIVE, + CAP_SYS_CHROOT + ); + } + + if (WFileName) { + capng_update( + CAPNG_ADD, + CAPNG_PERMITTED | CAPNG_EFFECTIVE, + CAP_DAC_OVERRIDE + ); + } + capng_apply(CAPNG_SELECT_BOTH); +#endif /* HAVE_LIBCAP_NG */ + if (username || chroot_dir) + droproot(username, chroot_dir); + + } +#endif /* _WIN32 */ + + if (pcap_setfilter(pd, &fcode) < 0) + error(""%s"", pcap_geterr(pd)); +#ifdef HAVE_CAPSICUM + if (RFileName == NULL && VFileName == NULL) { + static const unsigned long cmds[] = { BIOCGSTATS, BIOCROTZBUF }; + + /* + * The various libpcap devices use a combination of + * read (bpf), ioctl (bpf, netmap), poll (netmap) + * so we add the relevant access rights. + */ + cap_rights_init(&rights, CAP_IOCTL, CAP_READ, CAP_EVENT); + if (cap_rights_limit(pcap_fileno(pd), &rights) < 0 && + errno != ENOSYS) { + error(""unable to limit pcap descriptor""); + } + if (cap_ioctls_limit(pcap_fileno(pd), cmds, + sizeof(cmds) / sizeof(cmds[0])) < 0 && errno != ENOSYS) { + error(""unable to limit ioctls on pcap descriptor""); + } + } +#endif + if (WFileName) { + pcap_dumper_t *p; + /* Do not exceed the default PATH_MAX for files. */ + dumpinfo.CurrentFileName = (char *)malloc(PATH_MAX + 1); + + if (dumpinfo.CurrentFileName == NULL) + error(""malloc of dumpinfo.CurrentFileName""); + + /* We do not need numbering for dumpfiles if Cflag isn't set. */ + if (Cflag != 0) + MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, WflagChars); + else + MakeFilename(dumpinfo.CurrentFileName, WFileName, 0, 0); + + p = pcap_dump_open(pd, dumpinfo.CurrentFileName); +#ifdef HAVE_LIBCAP_NG + /* Give up CAP_DAC_OVERRIDE capability. + * Only allow it to be restored if the -C or -G flag have been + * set since we may need to create more files later on. + */ + capng_update( + CAPNG_DROP, + (Cflag || Gflag ? 0 : CAPNG_PERMITTED) + | CAPNG_EFFECTIVE, + CAP_DAC_OVERRIDE + ); + capng_apply(CAPNG_SELECT_BOTH); +#endif /* HAVE_LIBCAP_NG */ + if (p == NULL) + error(""%s"", pcap_geterr(pd)); +#ifdef HAVE_CAPSICUM + set_dumper_capsicum_rights(p); +#endif + if (Cflag != 0 || Gflag != 0) { +#ifdef HAVE_CAPSICUM + dumpinfo.WFileName = strdup(basename(WFileName)); + if (dumpinfo.WFileName == NULL) { + error(""Unable to allocate memory for file %s"", + WFileName); + } + dumpinfo.dirfd = open(dirname(WFileName), + O_DIRECTORY | O_RDONLY); + if (dumpinfo.dirfd < 0) { + error(""unable to open directory %s"", + dirname(WFileName)); + } + cap_rights_init(&rights, CAP_CREATE, CAP_FCNTL, + CAP_FTRUNCATE, CAP_LOOKUP, CAP_SEEK, CAP_WRITE); + if (cap_rights_limit(dumpinfo.dirfd, &rights) < 0 && + errno != ENOSYS) { + error(""unable to limit directory rights""); + } + if (cap_fcntls_limit(dumpinfo.dirfd, CAP_FCNTL_GETFL) < 0 && + errno != ENOSYS) { + error(""unable to limit dump descriptor fcntls""); + } +#else /* !HAVE_CAPSICUM */ + dumpinfo.WFileName = WFileName; +#endif + callback = dump_packet_and_trunc; + dumpinfo.pd = pd; + dumpinfo.p = p; + pcap_userdata = (u_char *)&dumpinfo; + } else { + callback = dump_packet; + pcap_userdata = (u_char *)p; + } +#ifdef HAVE_PCAP_DUMP_FLUSH + if (Uflag) + pcap_dump_flush(p); +#endif + } else { + dlt = pcap_datalink(pd); + ndo->ndo_if_printer = get_if_printer(ndo, dlt); + callback = print_packet; + pcap_userdata = (u_char *)ndo; + } + +#ifdef SIGNAL_REQ_INFO + /* + * We can't get statistics when reading from a file rather + * than capturing from a device. + */ + if (RFileName == NULL) + (void)setsignal(SIGNAL_REQ_INFO, requestinfo); +#endif + + if (ndo->ndo_vflag > 0 && WFileName) { + /* + * When capturing to a file, ""-v"" means tcpdump should, + * every 10 seconds, ""v""erbosely report the number of + * packets captured. + */ +#ifdef USE_WIN32_MM_TIMER + /* call verbose_stats_dump() each 1000 +/-100msec */ + timer_id = timeSetEvent(1000, 100, verbose_stats_dump, 0, TIME_PERIODIC); + setvbuf(stderr, NULL, _IONBF, 0); +#elif defined(HAVE_ALARM) + (void)setsignal(SIGALRM, verbose_stats_dump); + alarm(1); +#endif + } + + if (RFileName == NULL) { + /* + * Live capture (if -V was specified, we set RFileName + * to a file from the -V file). Print a message to + * the standard error on UN*X. + */ + if (!ndo->ndo_vflag && !WFileName) { + (void)fprintf(stderr, + ""%s: verbose output suppressed, use -v or -vv for full protocol decode\n"", + program_name); + } else + (void)fprintf(stderr, ""%s: "", program_name); + dlt = pcap_datalink(pd); + dlt_name = pcap_datalink_val_to_name(dlt); + if (dlt_name == NULL) { + (void)fprintf(stderr, ""listening on %s, link-type %u, capture size %u bytes\n"", + device, dlt, ndo->ndo_snaplen); + } else { + (void)fprintf(stderr, ""listening on %s, link-type %s (%s), capture size %u bytes\n"", + device, dlt_name, + pcap_datalink_val_to_description(dlt), ndo->ndo_snaplen); + } + (void)fflush(stderr); + } + +#ifdef HAVE_CAPSICUM + cansandbox = (ndo->ndo_nflag && VFileName == NULL && zflag == NULL); + if (cansandbox && cap_enter() < 0 && errno != ENOSYS) + error(""unable to enter the capability mode""); +#endif /* HAVE_CAPSICUM */ + + do { + status = pcap_loop(pd, cnt, callback, pcap_userdata); + if (WFileName == NULL) { + /* + * We're printing packets. Flush the printed output, + * so it doesn't get intermingled with error output. + */ + if (status == -2) { + /* + * We got interrupted, so perhaps we didn't + * manage to finish a line we were printing. + * Print an extra newline, just in case. + */ + putchar('\n'); + } + (void)fflush(stdout); + } + if (status == -2) { + /* + * We got interrupted. If we are reading multiple + * files (via -V) set these so that we stop. + */ + VFileName = NULL; + ret = NULL; + } + if (status == -1) { + /* + * Error. Report it. + */ + (void)fprintf(stderr, ""%s: pcap_loop: %s\n"", + program_name, pcap_geterr(pd)); + } + if (RFileName == NULL) { + /* + * We're doing a live capture. Report the capture + * statistics. + */ + info(1); + } + pcap_close(pd); + if (VFileName != NULL) { + ret = get_next_file(VFile, VFileLine); + if (ret) { + int new_dlt; + + RFileName = VFileLine; + pd = pcap_open_offline(RFileName, ebuf); + if (pd == NULL) + error(""%s"", ebuf); +#ifdef HAVE_CAPSICUM + cap_rights_init(&rights, CAP_READ); + if (cap_rights_limit(fileno(pcap_file(pd)), + &rights) < 0 && errno != ENOSYS) { + error(""unable to limit pcap descriptor""); + } +#endif + new_dlt = pcap_datalink(pd); + if (new_dlt != dlt) { + /* + * The new file has a different + * link-layer header type from the + * previous one. + */ + if (WFileName != NULL) { + /* + * We're writing raw packets + * that match the filter to + * a pcap file. pcap files + * don't support multiple + * different link-layer + * header types, so we fail + * here. + */ + error(""%s: new dlt does not match original"", RFileName); + } + + /* + * We're printing the decoded packets; + * switch to the new DLT. + * + * To do that, we need to change + * the printer, change the DLT name, + * and recompile the filter with + * the new DLT. + */ + dlt = new_dlt; + ndo->ndo_if_printer = get_if_printer(ndo, dlt); + if (pcap_compile(pd, &fcode, cmdbuf, Oflag, netmask) < 0) + error(""%s"", pcap_geterr(pd)); + } + + /* + * Set the filter on the new file. + */ + if (pcap_setfilter(pd, &fcode) < 0) + error(""%s"", pcap_geterr(pd)); + + /* + * Report the new file. + */ + dlt_name = pcap_datalink_val_to_name(dlt); + if (dlt_name == NULL) { + fprintf(stderr, ""reading from file %s, link-type %u\n"", + RFileName, dlt); + } else { + fprintf(stderr, + ""reading from file %s, link-type %s (%s)\n"", + RFileName, dlt_name, + pcap_datalink_val_to_description(dlt)); + } + } + } + } + while (ret != NULL); + + free(cmdbuf); + pcap_freecode(&fcode); + exit_tcpdump(status == -1 ? 1 : 0); +} +","@@ -699,13 +699,15 @@ static char * + get_next_file(FILE *VFile, char *ptr) + { + char *ret; ++ size_t len; + + ret = fgets(ptr, PATH_MAX, VFile); + if (!ret) + return NULL; + +- if (ptr[strlen(ptr) - 1] == '\n') +- ptr[strlen(ptr) - 1] = '\0'; ++ len = strlen (ptr); ++ if (len > 0 && ptr[len - 1] == '\n') ++ ptr[len - 1] = '\0'; + + return ret; + }",7834,8165,8192 +18252,"add_job(cupsd_client_t *con, /* I - Client connection */ + cupsd_printer_t *printer, /* I - Destination printer */ + mime_type_t *filetype) /* I - First print file type, if any */ +{ + http_status_t status; /* Policy status */ + ipp_attribute_t *attr, /* Current attribute */ + *auth_info; /* auth-info attribute */ + const char *mandatory; /* Current mandatory job attribute */ + const char *val; /* Default option value */ + int priority; /* Job priority */ + cupsd_job_t *job; /* Current job */ + char job_uri[HTTP_MAX_URI]; /* Job URI */ + int kbytes; /* Size of print file */ + int i; /* Looping var */ + int lowerpagerange; /* Page range bound */ + int exact; /* Did we have an exact match? */ + ipp_attribute_t *media_col, /* media-col attribute */ + *media_margin; /* media-*-margin attribute */ + ipp_t *unsup_col; /* media-col in unsupported response */ + static const char * const readonly[] =/* List of read-only attributes */ + { + ""date-time-at-completed"", + ""date-time-at-creation"", + ""date-time-at-processing"", + ""job-detailed-status-messages"", + ""job-document-access-errors"", + ""job-id"", + ""job-impressions-completed"", + ""job-k-octets-completed"", + ""job-media-sheets-completed"", + ""job-pages-completed"", + ""job-printer-up-time"", + ""job-printer-uri"", + ""job-state"", + ""job-state-message"", + ""job-state-reasons"", + ""job-uri"", + ""number-of-documents"", + ""number-of-intervening-jobs"", + ""output-device-assigned"", + ""time-at-completed"", + ""time-at-creation"", + ""time-at-processing"" + }; + + + cupsdLogMessage(CUPSD_LOG_DEBUG2, ""add_job(%p[%d], %p(%s), %p(%s/%s))"", + con, con->number, printer, printer->name, + filetype, filetype ? filetype->super : ""none"", + filetype ? filetype->type : ""none""); + + /* + * Check remote printing to non-shared printer... + */ + + if (!printer->shared && + _cups_strcasecmp(con->http->hostname, ""localhost"") && + _cups_strcasecmp(con->http->hostname, ServerName)) + { + send_ipp_status(con, IPP_NOT_AUTHORIZED, + _(""The printer or class is not shared."")); + return (NULL); + } + + /* + * Check policy... + */ + + auth_info = ippFindAttribute(con->request, ""auth-info"", IPP_TAG_TEXT); + + if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK) + { + send_http_error(con, status, printer); + return (NULL); + } + else if (printer->num_auth_info_required == 1 && + !strcmp(printer->auth_info_required[0], ""negotiate"") && + !con->username[0]) + { + send_http_error(con, HTTP_UNAUTHORIZED, printer); + return (NULL); + } +#ifdef HAVE_SSL + else if (auth_info && !con->http->tls && + !httpAddrLocalhost(con->http->hostaddr)) + { + /* + * Require encryption of auth-info over non-local connections... + */ + + send_http_error(con, HTTP_UPGRADE_REQUIRED, printer); + return (NULL); + } +#endif /* HAVE_SSL */ + + /* + * See if the printer is accepting jobs... + */ + + if (!printer->accepting) + { + send_ipp_status(con, IPP_NOT_ACCEPTING, + _(""Destination \""%s\"" is not accepting jobs.""), + printer->name); + return (NULL); + } + + /* + * Validate job template attributes; for now just document-format, + * copies, job-sheets, number-up, page-ranges, mandatory attributes, and + * media... + */ + + for (i = 0; i < (int)(sizeof(readonly) / sizeof(readonly[0])); i ++) + { + if ((attr = ippFindAttribute(con->request, readonly[i], IPP_TAG_ZERO)) != NULL) + { + ippDeleteAttribute(con->request, attr); + + if (StrictConformance) + { + send_ipp_status(con, IPP_BAD_REQUEST, _(""The '%s' Job Status attribute cannot be supplied in a job creation request.""), readonly[i]); + return (NULL); + } + + cupsdLogMessage(CUPSD_LOG_INFO, ""Unexpected '%s' Job Status attribute in a job creation request."", readonly[i]); + } + } + + if (printer->pc) + { + for (mandatory = (char *)cupsArrayFirst(printer->pc->mandatory); + mandatory; + mandatory = (char *)cupsArrayNext(printer->pc->mandatory)) + { + if (!ippFindAttribute(con->request, mandatory, IPP_TAG_ZERO)) + { + /* + * Missing a required attribute... + */ + + send_ipp_status(con, IPP_CONFLICT, + _(""The \""%s\"" attribute is required for print jobs.""), + mandatory); + return (NULL); + } + } + } + + if (filetype && printer->filetypes && + !cupsArrayFind(printer->filetypes, filetype)) + { + char mimetype[MIME_MAX_SUPER + MIME_MAX_TYPE + 2]; + /* MIME media type string */ + + + snprintf(mimetype, sizeof(mimetype), ""%s/%s"", filetype->super, + filetype->type); + + send_ipp_status(con, IPP_DOCUMENT_FORMAT, + _(""Unsupported format \""%s\"".""), mimetype); + + ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_MIMETYPE, + ""document-format"", NULL, mimetype); + + return (NULL); + } + + if ((attr = ippFindAttribute(con->request, ""copies"", + IPP_TAG_INTEGER)) != NULL) + { + if (attr->values[0].integer < 1 || attr->values[0].integer > MaxCopies) + { + send_ipp_status(con, IPP_ATTRIBUTES, _(""Bad copies value %d.""), + attr->values[0].integer); + ippAddInteger(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_INTEGER, + ""copies"", attr->values[0].integer); + return (NULL); + } + } + + if ((attr = ippFindAttribute(con->request, ""job-sheets"", + IPP_TAG_ZERO)) != NULL) + { + if (attr->value_tag != IPP_TAG_KEYWORD && + attr->value_tag != IPP_TAG_NAME) + { + send_ipp_status(con, IPP_BAD_REQUEST, _(""Bad job-sheets value type."")); + return (NULL); + } + + if (attr->num_values > 2) + { + send_ipp_status(con, IPP_BAD_REQUEST, + _(""Too many job-sheets values (%d > 2).""), + attr->num_values); + return (NULL); + } + + for (i = 0; i < attr->num_values; i ++) + if (strcmp(attr->values[i].string.text, ""none"") && + !cupsdFindBanner(attr->values[i].string.text)) + { + send_ipp_status(con, IPP_BAD_REQUEST, _(""Bad job-sheets value \""%s\"".""), + attr->values[i].string.text); + return (NULL); + } + } + + if ((attr = ippFindAttribute(con->request, ""number-up"", + IPP_TAG_INTEGER)) != NULL) + { + if (attr->values[0].integer != 1 && + attr->values[0].integer != 2 && + attr->values[0].integer != 4 && + attr->values[0].integer != 6 && + attr->values[0].integer != 9 && + attr->values[0].integer != 16) + { + send_ipp_status(con, IPP_ATTRIBUTES, _(""Bad number-up value %d.""), + attr->values[0].integer); + ippAddInteger(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_INTEGER, + ""number-up"", attr->values[0].integer); + return (NULL); + } + } + + if ((attr = ippFindAttribute(con->request, ""page-ranges"", + IPP_TAG_RANGE)) != NULL) + { + for (i = 0, lowerpagerange = 1; i < attr->num_values; i ++) + { + if (attr->values[i].range.lower < lowerpagerange || + attr->values[i].range.lower > attr->values[i].range.upper) + { + send_ipp_status(con, IPP_BAD_REQUEST, + _(""Bad page-ranges values %d-%d.""), + attr->values[i].range.lower, + attr->values[i].range.upper); + return (NULL); + } + + lowerpagerange = attr->values[i].range.upper + 1; + } + } + + /* + * Do media selection as needed... + */ + + if (!ippFindAttribute(con->request, ""PageRegion"", IPP_TAG_ZERO) && + !ippFindAttribute(con->request, ""PageSize"", IPP_TAG_ZERO) && + _ppdCacheGetPageSize(printer->pc, con->request, NULL, &exact)) + { + if (!exact && + (media_col = ippFindAttribute(con->request, ""media-col"", + IPP_TAG_BEGIN_COLLECTION)) != NULL) + { + send_ipp_status(con, IPP_OK_SUBST, _(""Unsupported margins."")); + + unsup_col = ippNew(); + if ((media_margin = ippFindAttribute(media_col->values[0].collection, + ""media-bottom-margin"", + IPP_TAG_INTEGER)) != NULL) + ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER, + ""media-bottom-margin"", media_margin->values[0].integer); + + if ((media_margin = ippFindAttribute(media_col->values[0].collection, + ""media-left-margin"", + IPP_TAG_INTEGER)) != NULL) + ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER, + ""media-left-margin"", media_margin->values[0].integer); + + if ((media_margin = ippFindAttribute(media_col->values[0].collection, + ""media-right-margin"", + IPP_TAG_INTEGER)) != NULL) + ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER, + ""media-right-margin"", media_margin->values[0].integer); + + if ((media_margin = ippFindAttribute(media_col->values[0].collection, + ""media-top-margin"", + IPP_TAG_INTEGER)) != NULL) + ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER, + ""media-top-margin"", media_margin->values[0].integer); + + ippAddCollection(con->response, IPP_TAG_UNSUPPORTED_GROUP, ""media-col"", + unsup_col); + ippDelete(unsup_col); + } + } + + /* + * Make sure we aren't over our limit... + */ + + if (MaxJobs && cupsArrayCount(Jobs) >= MaxJobs) + cupsdCleanJobs(); + + if (MaxJobs && cupsArrayCount(Jobs) >= MaxJobs) + { + send_ipp_status(con, IPP_NOT_POSSIBLE, _(""Too many active jobs."")); + return (NULL); + } + + if ((i = check_quotas(con, printer)) < 0) + { + send_ipp_status(con, IPP_NOT_POSSIBLE, _(""Quota limit reached."")); + return (NULL); + } + else if (i == 0) + { + send_ipp_status(con, IPP_NOT_AUTHORIZED, _(""Not allowed to print."")); + return (NULL); + } + + /* + * Create the job and set things up... + */ + + if ((attr = ippFindAttribute(con->request, ""job-priority"", + IPP_TAG_INTEGER)) != NULL) + priority = attr->values[0].integer; + else + { + if ((val = cupsGetOption(""job-priority"", printer->num_options, + printer->options)) != NULL) + priority = atoi(val); + else + priority = 50; + + ippAddInteger(con->request, IPP_TAG_JOB, IPP_TAG_INTEGER, ""job-priority"", + priority); + } + + if ((attr = ippFindAttribute(con->request, ""job-name"", IPP_TAG_ZERO)) == NULL) + ippAddString(con->request, IPP_TAG_JOB, IPP_TAG_NAME, ""job-name"", NULL, ""Untitled""); + else if ((attr->value_tag != IPP_TAG_NAME && + attr->value_tag != IPP_TAG_NAMELANG) || + attr->num_values != 1) + { + send_ipp_status(con, IPP_ATTRIBUTES, + _(""Bad job-name value: Wrong type or count."")); + if ((attr = ippCopyAttribute(con->response, attr, 0)) != NULL) + attr->group_tag = IPP_TAG_UNSUPPORTED_GROUP; + return (NULL); + } + else if (!ippValidateAttribute(attr)) + { + send_ipp_status(con, IPP_ATTRIBUTES, _(""Bad job-name value: %s""), + cupsLastErrorString()); + if ((attr = ippCopyAttribute(con->response, attr, 0)) != NULL) + attr->group_tag = IPP_TAG_UNSUPPORTED_GROUP; + return (NULL); + } + + if ((job = cupsdAddJob(priority, printer->name)) == NULL) + { + send_ipp_status(con, IPP_INTERNAL_ERROR, + _(""Unable to add job for destination \""%s\"".""), + printer->name); + return (NULL); + } + + job->dtype = printer->type & (CUPS_PRINTER_CLASS | CUPS_PRINTER_REMOTE); + job->attrs = con->request; + job->dirty = 1; + con->request = ippNewRequest(job->attrs->request.op.operation_id); + + cupsdMarkDirty(CUPSD_DIRTY_JOBS); + + add_job_uuid(job); + apply_printer_defaults(printer, job); + + attr = ippFindAttribute(job->attrs, ""requesting-user-name"", IPP_TAG_NAME); + if (con->username[0]) + { + cupsdSetString(&job->username, con->username); + + if (attr) + ippSetString(job->attrs, &attr, 0, con->username); + } + else if (attr) + { + cupsdLogMessage(CUPSD_LOG_DEBUG, + ""add_job: requesting-user-name=\""%s\"""", + attr->values[0].string.text); + + cupsdSetString(&job->username, attr->values[0].string.text); + } + else + cupsdSetString(&job->username, ""anonymous""); + + if (!attr) + ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, + ""job-originating-user-name"", NULL, job->username); + else + { + ippSetGroupTag(job->attrs, &attr, IPP_TAG_JOB); + ippSetName(job->attrs, &attr, ""job-originating-user-name""); + } + + if (con->username[0] || auth_info) + { + save_auth_info(con, job, auth_info); + + /* + * Remove the auth-info attribute from the attribute data... + */ + + if (auth_info) + ippDeleteAttribute(job->attrs, auth_info); + } + + if ((attr = ippFindAttribute(con->request, ""job-name"", IPP_TAG_NAME)) != NULL) + cupsdSetString(&(job->name), attr->values[0].string.text); + + if ((attr = ippFindAttribute(job->attrs, ""job-originating-host-name"", + IPP_TAG_ZERO)) != NULL) + { + /* + * Request contains a job-originating-host-name attribute; validate it... + */ + + if (attr->value_tag != IPP_TAG_NAME || + attr->num_values != 1 || + strcmp(con->http->hostname, ""localhost"")) + { + /* + * Can't override the value if we aren't connected via localhost. + * Also, we can only have 1 value and it must be a name value. + */ + + ippDeleteAttribute(job->attrs, attr); + ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, ""job-originating-host-name"", NULL, con->http->hostname); + } + else + ippSetGroupTag(job->attrs, &attr, IPP_TAG_JOB); + } + else + { + /* + * No job-originating-host-name attribute, so use the hostname from + * the connection... + */ + + ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, + ""job-originating-host-name"", NULL, con->http->hostname); + } + + ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, ""date-time-at-completed""); + ippAddDate(job->attrs, IPP_TAG_JOB, ""date-time-at-creation"", ippTimeToDate(time(NULL))); + ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, ""date-time-at-processing""); + ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, ""time-at-completed""); + ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, ""time-at-creation"", time(NULL)); + ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, ""time-at-processing""); + + /* + * Add remaining job attributes... + */ + + ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, ""job-id"", job->id); + job->state = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_ENUM, + ""job-state"", IPP_JOB_STOPPED); + job->state_value = (ipp_jstate_t)job->state->values[0].integer; + job->reasons = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD, + ""job-state-reasons"", NULL, ""job-incoming""); + job->impressions = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, ""job-impressions-completed"", 0); + job->sheets = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, + ""job-media-sheets-completed"", 0); + ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_URI, ""job-printer-uri"", NULL, + printer->uri); + + if ((attr = ippFindAttribute(job->attrs, ""job-k-octets"", IPP_TAG_INTEGER)) != NULL) + attr->values[0].integer = 0; + else + ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, ""job-k-octets"", 0); + + if ((attr = ippFindAttribute(job->attrs, ""job-hold-until"", + IPP_TAG_KEYWORD)) == NULL) + attr = ippFindAttribute(job->attrs, ""job-hold-until"", IPP_TAG_NAME); + if (!attr) + { + if ((val = cupsGetOption(""job-hold-until"", printer->num_options, + printer->options)) == NULL) + val = ""no-hold""; + + attr = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD, + ""job-hold-until"", NULL, val); + } + + if (printer->holding_new_jobs) + { + /* + * Hold all new jobs on this printer... + */ + + if (attr && strcmp(attr->values[0].string.text, ""no-hold"")) + cupsdSetJobHoldUntil(job, ippGetString(attr, 0, NULL), 0); + else + cupsdSetJobHoldUntil(job, ""indefinite"", 0); + + job->state->values[0].integer = IPP_JOB_HELD; + job->state_value = IPP_JOB_HELD; + + ippSetString(job->attrs, &job->reasons, 0, ""job-held-on-create""); + } + else if (attr && strcmp(attr->values[0].string.text, ""no-hold"")) + { + /* + * Hold job until specified time... + */ + + cupsdSetJobHoldUntil(job, attr->values[0].string.text, 0); + + job->state->values[0].integer = IPP_JOB_HELD; + job->state_value = IPP_JOB_HELD; + + ippSetString(job->attrs, &job->reasons, 0, ""job-hold-until-specified""); + } + else if (job->attrs->request.op.operation_id == IPP_CREATE_JOB) + { + job->hold_until = time(NULL) + MultipleOperationTimeout; + job->state->values[0].integer = IPP_JOB_HELD; + job->state_value = IPP_JOB_HELD; + } + else + { + job->state->values[0].integer = IPP_JOB_PENDING; + job->state_value = IPP_JOB_PENDING; + + ippSetString(job->attrs, &job->reasons, 0, ""none""); + } + + if (!(printer->type & CUPS_PRINTER_REMOTE) || Classification) + { + /* + * Add job sheets options... + */ + + if ((attr = ippFindAttribute(job->attrs, ""job-sheets"", + IPP_TAG_ZERO)) == NULL) + { + cupsdLogMessage(CUPSD_LOG_DEBUG, + ""Adding default job-sheets values \""%s,%s\""..."", + printer->job_sheets[0], printer->job_sheets[1]); + + attr = ippAddStrings(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, ""job-sheets"", + 2, NULL, NULL); + ippSetString(job->attrs, &attr, 0, printer->job_sheets[0]); + ippSetString(job->attrs, &attr, 1, printer->job_sheets[1]); + } + + job->job_sheets = attr; + + /* + * Enforce classification level if set... + */ + + if (Classification) + { + cupsdLogMessage(CUPSD_LOG_INFO, + ""Classification=\""%s\"", ClassifyOverride=%d"", + Classification ? Classification : ""(null)"", + ClassifyOverride); + + if (ClassifyOverride) + { + if (!strcmp(attr->values[0].string.text, ""none"") && + (attr->num_values == 1 || + !strcmp(attr->values[1].string.text, ""none""))) + { + /* + * Force the leading banner to have the classification on it... + */ + + ippSetString(job->attrs, &attr, 0, Classification); + + cupsdLogJob(job, CUPSD_LOG_NOTICE, ""CLASSIFICATION FORCED "" + ""job-sheets=\""%s,none\"", "" + ""job-originating-user-name=\""%s\"""", + Classification, job->username); + } + else if (attr->num_values == 2 && + strcmp(attr->values[0].string.text, + attr->values[1].string.text) && + strcmp(attr->values[0].string.text, ""none"") && + strcmp(attr->values[1].string.text, ""none"")) + { + /* + * Can't put two different security markings on the same document! + */ + + ippSetString(job->attrs, &attr, 1, attr->values[0].string.text); + + cupsdLogJob(job, CUPSD_LOG_NOTICE, ""CLASSIFICATION FORCED "" + ""job-sheets=\""%s,%s\"", "" + ""job-originating-user-name=\""%s\"""", + attr->values[0].string.text, + attr->values[1].string.text, job->username); + } + else if (strcmp(attr->values[0].string.text, Classification) && + strcmp(attr->values[0].string.text, ""none"") && + (attr->num_values == 1 || + (strcmp(attr->values[1].string.text, Classification) && + strcmp(attr->values[1].string.text, ""none"")))) + { + if (attr->num_values == 1) + cupsdLogJob(job, CUPSD_LOG_NOTICE, + ""CLASSIFICATION OVERRIDDEN "" + ""job-sheets=\""%s\"", "" + ""job-originating-user-name=\""%s\"""", + attr->values[0].string.text, job->username); + else + cupsdLogJob(job, CUPSD_LOG_NOTICE, + ""CLASSIFICATION OVERRIDDEN "" + ""job-sheets=\""%s,%s\"",fffff "" + ""job-originating-user-name=\""%s\"""", + attr->values[0].string.text, + attr->values[1].string.text, job->username); + } + } + else if (strcmp(attr->values[0].string.text, Classification) && + (attr->num_values == 1 || + strcmp(attr->values[1].string.text, Classification))) + { + /* + * Force the banner to have the classification on it... + */ + + if (attr->num_values > 1 && + !strcmp(attr->values[0].string.text, attr->values[1].string.text)) + { + ippSetString(job->attrs, &attr, 0, Classification); + ippSetString(job->attrs, &attr, 1, Classification); + } + else + { + if (attr->num_values == 1 || + strcmp(attr->values[0].string.text, ""none"")) + ippSetString(job->attrs, &attr, 0, Classification); + + if (attr->num_values > 1 && + strcmp(attr->values[1].string.text, ""none"")) + ippSetString(job->attrs, &attr, 1, Classification); + } + + if (attr->num_values > 1) + cupsdLogJob(job, CUPSD_LOG_NOTICE, + ""CLASSIFICATION FORCED "" + ""job-sheets=\""%s,%s\"", "" + ""job-originating-user-name=\""%s\"""", + attr->values[0].string.text, + attr->values[1].string.text, job->username); + else + cupsdLogJob(job, CUPSD_LOG_NOTICE, + ""CLASSIFICATION FORCED "" + ""job-sheets=\""%s\"", "" + ""job-originating-user-name=\""%s\"""", + Classification, job->username); + } + } + + /* + * See if we need to add the starting sheet... + */ + + if (!(printer->type & CUPS_PRINTER_REMOTE)) + { + cupsdLogJob(job, CUPSD_LOG_INFO, ""Adding start banner page \""%s\""."", + attr->values[0].string.text); + + if ((kbytes = copy_banner(con, job, attr->values[0].string.text)) < 0) + { + cupsdSetJobState(job, IPP_JOB_ABORTED, CUPSD_JOB_PURGE, + ""Aborting job because the start banner could not be "" + ""copied.""); + return (NULL); + } + + cupsdUpdateQuota(printer, job->username, 0, kbytes); + } + } + else if ((attr = ippFindAttribute(job->attrs, ""job-sheets"", + IPP_TAG_ZERO)) != NULL) + job->job_sheets = attr; + + /* + * Fill in the response info... + */ + + httpAssembleURIf(HTTP_URI_CODING_ALL, job_uri, sizeof(job_uri), ""ipp"", NULL, + con->clientname, con->clientport, ""/jobs/%d"", job->id); + ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_URI, ""job-uri"", NULL, + job_uri); + + ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER, ""job-id"", job->id); + + ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_ENUM, ""job-state"", + job->state_value); + ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_TEXT, ""job-state-message"", NULL, """"); + ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_KEYWORD, ""job-state-reasons"", + NULL, job->reasons->values[0].string.text); + + con->response->request.status.status_code = IPP_OK; + + /* + * Add any job subscriptions... + */ + + add_job_subscriptions(con, job); + + /* + * Set all but the first two attributes to the job attributes group... + */ + + for (attr = job->attrs->attrs->next->next; attr; attr = attr->next) + attr->group_tag = IPP_TAG_JOB; + + /* + * Fire the ""job created"" event... + */ + + cupsdAddEvent(CUPSD_EVENT_JOB_CREATED, printer, job, ""Job created.""); + + /* + * Return the new job... + */ + + return (job); +} +",1,"add_job(cupsd_client_t *con, /* I - Client connection */ + cupsd_printer_t *printer, /* I - Destination printer */ + mime_type_t *filetype) /* I - First print file type, if any */ +{ + http_status_t status; /* Policy status */ + ipp_attribute_t *attr, /* Current attribute */ + *auth_info; /* auth-info attribute */ + const char *mandatory; /* Current mandatory job attribute */ + const char *val; /* Default option value */ + int priority; /* Job priority */ + cupsd_job_t *job; /* Current job */ + char job_uri[HTTP_MAX_URI]; /* Job URI */ + int kbytes; /* Size of print file */ + int i; /* Looping var */ + int lowerpagerange; /* Page range bound */ + int exact; /* Did we have an exact match? */ + ipp_attribute_t *media_col, /* media-col attribute */ + *media_margin; /* media-*-margin attribute */ + ipp_t *unsup_col; /* media-col in unsupported response */ + static const char * const readonly[] =/* List of read-only attributes */ + { + ""date-time-at-completed"", + ""date-time-at-creation"", + ""date-time-at-processing"", + ""job-detailed-status-messages"", + ""job-document-access-errors"", + ""job-id"", + ""job-impressions-completed"", + ""job-k-octets-completed"", + ""job-media-sheets-completed"", + ""job-pages-completed"", + ""job-printer-up-time"", + ""job-printer-uri"", + ""job-state"", + ""job-state-message"", + ""job-state-reasons"", + ""job-uri"", + ""number-of-documents"", + ""number-of-intervening-jobs"", + ""output-device-assigned"", + ""time-at-completed"", + ""time-at-creation"", + ""time-at-processing"" + }; + + + cupsdLogMessage(CUPSD_LOG_DEBUG2, ""add_job(%p[%d], %p(%s), %p(%s/%s))"", + con, con->number, printer, printer->name, + filetype, filetype ? filetype->super : ""none"", + filetype ? filetype->type : ""none""); + + /* + * Check remote printing to non-shared printer... + */ + + if (!printer->shared && + _cups_strcasecmp(con->http->hostname, ""localhost"") && + _cups_strcasecmp(con->http->hostname, ServerName)) + { + send_ipp_status(con, IPP_NOT_AUTHORIZED, + _(""The printer or class is not shared."")); + return (NULL); + } + + /* + * Check policy... + */ + + auth_info = ippFindAttribute(con->request, ""auth-info"", IPP_TAG_TEXT); + + if ((status = cupsdCheckPolicy(printer->op_policy_ptr, con, NULL)) != HTTP_OK) + { + send_http_error(con, status, printer); + return (NULL); + } + else if (printer->num_auth_info_required == 1 && + !strcmp(printer->auth_info_required[0], ""negotiate"") && + !con->username[0]) + { + send_http_error(con, HTTP_UNAUTHORIZED, printer); + return (NULL); + } +#ifdef HAVE_SSL + else if (auth_info && !con->http->tls && + !httpAddrLocalhost(con->http->hostaddr)) + { + /* + * Require encryption of auth-info over non-local connections... + */ + + send_http_error(con, HTTP_UPGRADE_REQUIRED, printer); + return (NULL); + } +#endif /* HAVE_SSL */ + + /* + * See if the printer is accepting jobs... + */ + + if (!printer->accepting) + { + send_ipp_status(con, IPP_NOT_ACCEPTING, + _(""Destination \""%s\"" is not accepting jobs.""), + printer->name); + return (NULL); + } + + /* + * Validate job template attributes; for now just document-format, + * copies, job-sheets, number-up, page-ranges, mandatory attributes, and + * media... + */ + + for (i = 0; i < (int)(sizeof(readonly) / sizeof(readonly[0])); i ++) + { + if ((attr = ippFindAttribute(con->request, readonly[i], IPP_TAG_ZERO)) != NULL) + { + ippDeleteAttribute(con->request, attr); + + if (StrictConformance) + { + send_ipp_status(con, IPP_BAD_REQUEST, _(""The '%s' Job Status attribute cannot be supplied in a job creation request.""), readonly[i]); + return (NULL); + } + + cupsdLogMessage(CUPSD_LOG_INFO, ""Unexpected '%s' Job Status attribute in a job creation request."", readonly[i]); + } + } + + if (printer->pc) + { + for (mandatory = (char *)cupsArrayFirst(printer->pc->mandatory); + mandatory; + mandatory = (char *)cupsArrayNext(printer->pc->mandatory)) + { + if (!ippFindAttribute(con->request, mandatory, IPP_TAG_ZERO)) + { + /* + * Missing a required attribute... + */ + + send_ipp_status(con, IPP_CONFLICT, + _(""The \""%s\"" attribute is required for print jobs.""), + mandatory); + return (NULL); + } + } + } + + if (filetype && printer->filetypes && + !cupsArrayFind(printer->filetypes, filetype)) + { + char mimetype[MIME_MAX_SUPER + MIME_MAX_TYPE + 2]; + /* MIME media type string */ + + + snprintf(mimetype, sizeof(mimetype), ""%s/%s"", filetype->super, + filetype->type); + + send_ipp_status(con, IPP_DOCUMENT_FORMAT, + _(""Unsupported format \""%s\"".""), mimetype); + + ippAddString(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_MIMETYPE, + ""document-format"", NULL, mimetype); + + return (NULL); + } + + if ((attr = ippFindAttribute(con->request, ""copies"", + IPP_TAG_INTEGER)) != NULL) + { + if (attr->values[0].integer < 1 || attr->values[0].integer > MaxCopies) + { + send_ipp_status(con, IPP_ATTRIBUTES, _(""Bad copies value %d.""), + attr->values[0].integer); + ippAddInteger(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_INTEGER, + ""copies"", attr->values[0].integer); + return (NULL); + } + } + + if ((attr = ippFindAttribute(con->request, ""job-sheets"", + IPP_TAG_ZERO)) != NULL) + { + if (attr->value_tag != IPP_TAG_KEYWORD && + attr->value_tag != IPP_TAG_NAME) + { + send_ipp_status(con, IPP_BAD_REQUEST, _(""Bad job-sheets value type."")); + return (NULL); + } + + if (attr->num_values > 2) + { + send_ipp_status(con, IPP_BAD_REQUEST, + _(""Too many job-sheets values (%d > 2).""), + attr->num_values); + return (NULL); + } + + for (i = 0; i < attr->num_values; i ++) + if (strcmp(attr->values[i].string.text, ""none"") && + !cupsdFindBanner(attr->values[i].string.text)) + { + send_ipp_status(con, IPP_BAD_REQUEST, _(""Bad job-sheets value \""%s\"".""), + attr->values[i].string.text); + return (NULL); + } + } + + if ((attr = ippFindAttribute(con->request, ""number-up"", + IPP_TAG_INTEGER)) != NULL) + { + if (attr->values[0].integer != 1 && + attr->values[0].integer != 2 && + attr->values[0].integer != 4 && + attr->values[0].integer != 6 && + attr->values[0].integer != 9 && + attr->values[0].integer != 16) + { + send_ipp_status(con, IPP_ATTRIBUTES, _(""Bad number-up value %d.""), + attr->values[0].integer); + ippAddInteger(con->response, IPP_TAG_UNSUPPORTED_GROUP, IPP_TAG_INTEGER, + ""number-up"", attr->values[0].integer); + return (NULL); + } + } + + if ((attr = ippFindAttribute(con->request, ""page-ranges"", + IPP_TAG_RANGE)) != NULL) + { + for (i = 0, lowerpagerange = 1; i < attr->num_values; i ++) + { + if (attr->values[i].range.lower < lowerpagerange || + attr->values[i].range.lower > attr->values[i].range.upper) + { + send_ipp_status(con, IPP_BAD_REQUEST, + _(""Bad page-ranges values %d-%d.""), + attr->values[i].range.lower, + attr->values[i].range.upper); + return (NULL); + } + + lowerpagerange = attr->values[i].range.upper + 1; + } + } + + /* + * Do media selection as needed... + */ + + if (!ippFindAttribute(con->request, ""PageRegion"", IPP_TAG_ZERO) && + !ippFindAttribute(con->request, ""PageSize"", IPP_TAG_ZERO) && + _ppdCacheGetPageSize(printer->pc, con->request, NULL, &exact)) + { + if (!exact && + (media_col = ippFindAttribute(con->request, ""media-col"", + IPP_TAG_BEGIN_COLLECTION)) != NULL) + { + send_ipp_status(con, IPP_OK_SUBST, _(""Unsupported margins."")); + + unsup_col = ippNew(); + if ((media_margin = ippFindAttribute(media_col->values[0].collection, + ""media-bottom-margin"", + IPP_TAG_INTEGER)) != NULL) + ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER, + ""media-bottom-margin"", media_margin->values[0].integer); + + if ((media_margin = ippFindAttribute(media_col->values[0].collection, + ""media-left-margin"", + IPP_TAG_INTEGER)) != NULL) + ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER, + ""media-left-margin"", media_margin->values[0].integer); + + if ((media_margin = ippFindAttribute(media_col->values[0].collection, + ""media-right-margin"", + IPP_TAG_INTEGER)) != NULL) + ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER, + ""media-right-margin"", media_margin->values[0].integer); + + if ((media_margin = ippFindAttribute(media_col->values[0].collection, + ""media-top-margin"", + IPP_TAG_INTEGER)) != NULL) + ippAddInteger(unsup_col, IPP_TAG_ZERO, IPP_TAG_INTEGER, + ""media-top-margin"", media_margin->values[0].integer); + + ippAddCollection(con->response, IPP_TAG_UNSUPPORTED_GROUP, ""media-col"", + unsup_col); + ippDelete(unsup_col); + } + } + + /* + * Make sure we aren't over our limit... + */ + + if (MaxJobs && cupsArrayCount(Jobs) >= MaxJobs) + cupsdCleanJobs(); + + if (MaxJobs && cupsArrayCount(Jobs) >= MaxJobs) + { + send_ipp_status(con, IPP_NOT_POSSIBLE, _(""Too many active jobs."")); + return (NULL); + } + + if ((i = check_quotas(con, printer)) < 0) + { + send_ipp_status(con, IPP_NOT_POSSIBLE, _(""Quota limit reached."")); + return (NULL); + } + else if (i == 0) + { + send_ipp_status(con, IPP_NOT_AUTHORIZED, _(""Not allowed to print."")); + return (NULL); + } + + /* + * Create the job and set things up... + */ + + if ((attr = ippFindAttribute(con->request, ""job-priority"", + IPP_TAG_INTEGER)) != NULL) + priority = attr->values[0].integer; + else + { + if ((val = cupsGetOption(""job-priority"", printer->num_options, + printer->options)) != NULL) + priority = atoi(val); + else + priority = 50; + + ippAddInteger(con->request, IPP_TAG_JOB, IPP_TAG_INTEGER, ""job-priority"", + priority); + } + + if ((attr = ippFindAttribute(con->request, ""job-name"", IPP_TAG_ZERO)) == NULL) + ippAddString(con->request, IPP_TAG_JOB, IPP_TAG_NAME, ""job-name"", NULL, ""Untitled""); + else if ((attr->value_tag != IPP_TAG_NAME && + attr->value_tag != IPP_TAG_NAMELANG) || + attr->num_values != 1) + { + send_ipp_status(con, IPP_ATTRIBUTES, + _(""Bad job-name value: Wrong type or count."")); + if ((attr = ippCopyAttribute(con->response, attr, 0)) != NULL) + attr->group_tag = IPP_TAG_UNSUPPORTED_GROUP; + return (NULL); + } + else if (!ippValidateAttribute(attr)) + { + send_ipp_status(con, IPP_ATTRIBUTES, _(""Bad job-name value: %s""), + cupsLastErrorString()); + if ((attr = ippCopyAttribute(con->response, attr, 0)) != NULL) + attr->group_tag = IPP_TAG_UNSUPPORTED_GROUP; + return (NULL); + } + + attr = ippFindAttribute(con->request, ""requesting-user-name"", IPP_TAG_NAME); + + if (attr && !ippValidateAttribute(attr)) + { + send_ipp_status(con, IPP_ATTRIBUTES, _(""Bad requesting-user-name value: %s""), cupsLastErrorString()); + if ((attr = ippCopyAttribute(con->response, attr, 0)) != NULL) + attr->group_tag = IPP_TAG_UNSUPPORTED_GROUP; + return (NULL); + } + + if ((job = cupsdAddJob(priority, printer->name)) == NULL) + { + send_ipp_status(con, IPP_INTERNAL_ERROR, + _(""Unable to add job for destination \""%s\"".""), + printer->name); + return (NULL); + } + + job->dtype = printer->type & (CUPS_PRINTER_CLASS | CUPS_PRINTER_REMOTE); + job->attrs = con->request; + job->dirty = 1; + con->request = ippNewRequest(job->attrs->request.op.operation_id); + + cupsdMarkDirty(CUPSD_DIRTY_JOBS); + + add_job_uuid(job); + apply_printer_defaults(printer, job); + + if (con->username[0]) + { + cupsdSetString(&job->username, con->username); + + if (attr) + ippSetString(job->attrs, &attr, 0, con->username); + } + else if (attr) + { + cupsdLogMessage(CUPSD_LOG_DEBUG, + ""add_job: requesting-user-name=\""%s\"""", + attr->values[0].string.text); + + cupsdSetString(&job->username, attr->values[0].string.text); + } + else + cupsdSetString(&job->username, ""anonymous""); + + if (!attr) + ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, + ""job-originating-user-name"", NULL, job->username); + else + { + ippSetGroupTag(job->attrs, &attr, IPP_TAG_JOB); + ippSetName(job->attrs, &attr, ""job-originating-user-name""); + } + + if (con->username[0] || auth_info) + { + save_auth_info(con, job, auth_info); + + /* + * Remove the auth-info attribute from the attribute data... + */ + + if (auth_info) + ippDeleteAttribute(job->attrs, auth_info); + } + + if ((attr = ippFindAttribute(con->request, ""job-name"", IPP_TAG_NAME)) != NULL) + cupsdSetString(&(job->name), attr->values[0].string.text); + + if ((attr = ippFindAttribute(job->attrs, ""job-originating-host-name"", + IPP_TAG_ZERO)) != NULL) + { + /* + * Request contains a job-originating-host-name attribute; validate it... + */ + + if (attr->value_tag != IPP_TAG_NAME || + attr->num_values != 1 || + strcmp(con->http->hostname, ""localhost"")) + { + /* + * Can't override the value if we aren't connected via localhost. + * Also, we can only have 1 value and it must be a name value. + */ + + ippDeleteAttribute(job->attrs, attr); + ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, ""job-originating-host-name"", NULL, con->http->hostname); + } + else + ippSetGroupTag(job->attrs, &attr, IPP_TAG_JOB); + } + else + { + /* + * No job-originating-host-name attribute, so use the hostname from + * the connection... + */ + + ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, + ""job-originating-host-name"", NULL, con->http->hostname); + } + + ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, ""date-time-at-completed""); + ippAddDate(job->attrs, IPP_TAG_JOB, ""date-time-at-creation"", ippTimeToDate(time(NULL))); + ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, ""date-time-at-processing""); + ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, ""time-at-completed""); + ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, ""time-at-creation"", time(NULL)); + ippAddOutOfBand(job->attrs, IPP_TAG_JOB, IPP_TAG_NOVALUE, ""time-at-processing""); + + /* + * Add remaining job attributes... + */ + + ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, ""job-id"", job->id); + job->state = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_ENUM, + ""job-state"", IPP_JOB_STOPPED); + job->state_value = (ipp_jstate_t)job->state->values[0].integer; + job->reasons = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD, + ""job-state-reasons"", NULL, ""job-incoming""); + job->impressions = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, ""job-impressions-completed"", 0); + job->sheets = ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, + ""job-media-sheets-completed"", 0); + ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_URI, ""job-printer-uri"", NULL, + printer->uri); + + if ((attr = ippFindAttribute(job->attrs, ""job-k-octets"", IPP_TAG_INTEGER)) != NULL) + attr->values[0].integer = 0; + else + ippAddInteger(job->attrs, IPP_TAG_JOB, IPP_TAG_INTEGER, ""job-k-octets"", 0); + + if ((attr = ippFindAttribute(job->attrs, ""job-hold-until"", + IPP_TAG_KEYWORD)) == NULL) + attr = ippFindAttribute(job->attrs, ""job-hold-until"", IPP_TAG_NAME); + if (!attr) + { + if ((val = cupsGetOption(""job-hold-until"", printer->num_options, + printer->options)) == NULL) + val = ""no-hold""; + + attr = ippAddString(job->attrs, IPP_TAG_JOB, IPP_TAG_KEYWORD, + ""job-hold-until"", NULL, val); + } + + if (printer->holding_new_jobs) + { + /* + * Hold all new jobs on this printer... + */ + + if (attr && strcmp(attr->values[0].string.text, ""no-hold"")) + cupsdSetJobHoldUntil(job, ippGetString(attr, 0, NULL), 0); + else + cupsdSetJobHoldUntil(job, ""indefinite"", 0); + + job->state->values[0].integer = IPP_JOB_HELD; + job->state_value = IPP_JOB_HELD; + + ippSetString(job->attrs, &job->reasons, 0, ""job-held-on-create""); + } + else if (attr && strcmp(attr->values[0].string.text, ""no-hold"")) + { + /* + * Hold job until specified time... + */ + + cupsdSetJobHoldUntil(job, attr->values[0].string.text, 0); + + job->state->values[0].integer = IPP_JOB_HELD; + job->state_value = IPP_JOB_HELD; + + ippSetString(job->attrs, &job->reasons, 0, ""job-hold-until-specified""); + } + else if (job->attrs->request.op.operation_id == IPP_CREATE_JOB) + { + job->hold_until = time(NULL) + MultipleOperationTimeout; + job->state->values[0].integer = IPP_JOB_HELD; + job->state_value = IPP_JOB_HELD; + } + else + { + job->state->values[0].integer = IPP_JOB_PENDING; + job->state_value = IPP_JOB_PENDING; + + ippSetString(job->attrs, &job->reasons, 0, ""none""); + } + + if (!(printer->type & CUPS_PRINTER_REMOTE) || Classification) + { + /* + * Add job sheets options... + */ + + if ((attr = ippFindAttribute(job->attrs, ""job-sheets"", + IPP_TAG_ZERO)) == NULL) + { + cupsdLogMessage(CUPSD_LOG_DEBUG, + ""Adding default job-sheets values \""%s,%s\""..."", + printer->job_sheets[0], printer->job_sheets[1]); + + attr = ippAddStrings(job->attrs, IPP_TAG_JOB, IPP_TAG_NAME, ""job-sheets"", + 2, NULL, NULL); + ippSetString(job->attrs, &attr, 0, printer->job_sheets[0]); + ippSetString(job->attrs, &attr, 1, printer->job_sheets[1]); + } + + job->job_sheets = attr; + + /* + * Enforce classification level if set... + */ + + if (Classification) + { + cupsdLogMessage(CUPSD_LOG_INFO, + ""Classification=\""%s\"", ClassifyOverride=%d"", + Classification ? Classification : ""(null)"", + ClassifyOverride); + + if (ClassifyOverride) + { + if (!strcmp(attr->values[0].string.text, ""none"") && + (attr->num_values == 1 || + !strcmp(attr->values[1].string.text, ""none""))) + { + /* + * Force the leading banner to have the classification on it... + */ + + ippSetString(job->attrs, &attr, 0, Classification); + + cupsdLogJob(job, CUPSD_LOG_NOTICE, ""CLASSIFICATION FORCED "" + ""job-sheets=\""%s,none\"", "" + ""job-originating-user-name=\""%s\"""", + Classification, job->username); + } + else if (attr->num_values == 2 && + strcmp(attr->values[0].string.text, + attr->values[1].string.text) && + strcmp(attr->values[0].string.text, ""none"") && + strcmp(attr->values[1].string.text, ""none"")) + { + /* + * Can't put two different security markings on the same document! + */ + + ippSetString(job->attrs, &attr, 1, attr->values[0].string.text); + + cupsdLogJob(job, CUPSD_LOG_NOTICE, ""CLASSIFICATION FORCED "" + ""job-sheets=\""%s,%s\"", "" + ""job-originating-user-name=\""%s\"""", + attr->values[0].string.text, + attr->values[1].string.text, job->username); + } + else if (strcmp(attr->values[0].string.text, Classification) && + strcmp(attr->values[0].string.text, ""none"") && + (attr->num_values == 1 || + (strcmp(attr->values[1].string.text, Classification) && + strcmp(attr->values[1].string.text, ""none"")))) + { + if (attr->num_values == 1) + cupsdLogJob(job, CUPSD_LOG_NOTICE, + ""CLASSIFICATION OVERRIDDEN "" + ""job-sheets=\""%s\"", "" + ""job-originating-user-name=\""%s\"""", + attr->values[0].string.text, job->username); + else + cupsdLogJob(job, CUPSD_LOG_NOTICE, + ""CLASSIFICATION OVERRIDDEN "" + ""job-sheets=\""%s,%s\"",fffff "" + ""job-originating-user-name=\""%s\"""", + attr->values[0].string.text, + attr->values[1].string.text, job->username); + } + } + else if (strcmp(attr->values[0].string.text, Classification) && + (attr->num_values == 1 || + strcmp(attr->values[1].string.text, Classification))) + { + /* + * Force the banner to have the classification on it... + */ + + if (attr->num_values > 1 && + !strcmp(attr->values[0].string.text, attr->values[1].string.text)) + { + ippSetString(job->attrs, &attr, 0, Classification); + ippSetString(job->attrs, &attr, 1, Classification); + } + else + { + if (attr->num_values == 1 || + strcmp(attr->values[0].string.text, ""none"")) + ippSetString(job->attrs, &attr, 0, Classification); + + if (attr->num_values > 1 && + strcmp(attr->values[1].string.text, ""none"")) + ippSetString(job->attrs, &attr, 1, Classification); + } + + if (attr->num_values > 1) + cupsdLogJob(job, CUPSD_LOG_NOTICE, + ""CLASSIFICATION FORCED "" + ""job-sheets=\""%s,%s\"", "" + ""job-originating-user-name=\""%s\"""", + attr->values[0].string.text, + attr->values[1].string.text, job->username); + else + cupsdLogJob(job, CUPSD_LOG_NOTICE, + ""CLASSIFICATION FORCED "" + ""job-sheets=\""%s\"", "" + ""job-originating-user-name=\""%s\"""", + Classification, job->username); + } + } + + /* + * See if we need to add the starting sheet... + */ + + if (!(printer->type & CUPS_PRINTER_REMOTE)) + { + cupsdLogJob(job, CUPSD_LOG_INFO, ""Adding start banner page \""%s\""."", + attr->values[0].string.text); + + if ((kbytes = copy_banner(con, job, attr->values[0].string.text)) < 0) + { + cupsdSetJobState(job, IPP_JOB_ABORTED, CUPSD_JOB_PURGE, + ""Aborting job because the start banner could not be "" + ""copied.""); + return (NULL); + } + + cupsdUpdateQuota(printer, job->username, 0, kbytes); + } + } + else if ((attr = ippFindAttribute(job->attrs, ""job-sheets"", + IPP_TAG_ZERO)) != NULL) + job->job_sheets = attr; + + /* + * Fill in the response info... + */ + + httpAssembleURIf(HTTP_URI_CODING_ALL, job_uri, sizeof(job_uri), ""ipp"", NULL, + con->clientname, con->clientport, ""/jobs/%d"", job->id); + ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_URI, ""job-uri"", NULL, + job_uri); + + ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_INTEGER, ""job-id"", job->id); + + ippAddInteger(con->response, IPP_TAG_JOB, IPP_TAG_ENUM, ""job-state"", + job->state_value); + ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_TEXT, ""job-state-message"", NULL, """"); + ippAddString(con->response, IPP_TAG_JOB, IPP_TAG_KEYWORD, ""job-state-reasons"", + NULL, job->reasons->values[0].string.text); + + con->response->request.status.status_code = IPP_OK; + + /* + * Add any job subscriptions... + */ + + add_job_subscriptions(con, job); + + /* + * Set all but the first two attributes to the job attributes group... + */ + + for (attr = job->attrs->attrs->next->next; attr; attr = attr->next) + attr->group_tag = IPP_TAG_JOB; + + /* + * Fire the ""job created"" event... + */ + + cupsdAddEvent(CUPSD_EVENT_JOB_CREATED, printer, job, ""Job created.""); + + /* + * Return the new job... + */ + + return (job); +} +","@@ -1597,6 +1597,16 @@ add_job(cupsd_client_t *con, /* I - Client connection */ + return (NULL); + } + ++ attr = ippFindAttribute(con->request, ""requesting-user-name"", IPP_TAG_NAME); ++ ++ if (attr && !ippValidateAttribute(attr)) ++ { ++ send_ipp_status(con, IPP_ATTRIBUTES, _(""Bad requesting-user-name value: %s""), cupsLastErrorString()); ++ if ((attr = ippCopyAttribute(con->response, attr, 0)) != NULL) ++ attr->group_tag = IPP_TAG_UNSUPPORTED_GROUP; ++ return (NULL); ++ } ++ + if ((job = cupsdAddJob(priority, printer->name)) == NULL) + { + send_ipp_status(con, IPP_INTERNAL_ERROR, +@@ -1615,8 +1625,6 @@ add_job(cupsd_client_t *con, /* I - Client connection */ + add_job_uuid(job); + apply_printer_defaults(printer, job); + +- attr = ippFindAttribute(job->attrs, ""requesting-user-name"", IPP_TAG_NAME); +- + if (con->username[0]) + { + cupsdSetString(&job->username, con->username);",6205,6536,8192 +7012,"TIFFReadDirectory(TIFF* tif) +{ + static const char module[] = ""TIFFReadDirectory""; + TIFFDirEntry* dir; + uint16 dircount; + TIFFDirEntry* dp; + uint16 di; + const TIFFField* fip; + uint32 fii=FAILED_FII; + toff_t nextdiroff; + int bitspersample_read = FALSE; + + tif->tif_diroff=tif->tif_nextdiroff; + if (!TIFFCheckDirOffset(tif,tif->tif_nextdiroff)) + return 0; /* last offset or bad offset (IFD looping) */ + (*tif->tif_cleanup)(tif); /* cleanup any previous compression state */ + tif->tif_curdir++; + nextdiroff = tif->tif_nextdiroff; + dircount=TIFFFetchDirectory(tif,nextdiroff,&dir,&tif->tif_nextdiroff); + if (!dircount) + { + TIFFErrorExt(tif->tif_clientdata,module, + ""Failed to read directory at offset "" TIFF_UINT64_FORMAT,nextdiroff); + return 0; + } + TIFFReadDirectoryCheckOrder(tif,dir,dircount); + + /* + * Mark duplicates of any tag to be ignored (bugzilla 1994) + * to avoid certain pathological problems. + */ + { + TIFFDirEntry* ma; + uint16 mb; + for (ma=dir, mb=0; mbtdir_tag==na->tdir_tag) + na->tdir_tag=IGNORE; + } + } + } + + tif->tif_flags &= ~TIFF_BEENWRITING; /* reset before new dir */ + tif->tif_flags &= ~TIFF_BUF4WRITE; /* reset before new dir */ + /* free any old stuff and reinit */ + TIFFFreeDirectory(tif); + TIFFDefaultDirectory(tif); + /* + * Electronic Arts writes gray-scale TIFF files + * without a PlanarConfiguration directory entry. + * Thus we setup a default value here, even though + * the TIFF spec says there is no default value. + */ + TIFFSetField(tif,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); + /* + * Setup default value and then make a pass over + * the fields to check type and tag information, + * and to extract info required to size data + * structures. A second pass is made afterwards + * to read in everything not taken in the first pass. + * But we must process the Compression tag first + * in order to merge in codec-private tag definitions (otherwise + * we may get complaints about unknown tags). However, the + * Compression tag may be dependent on the SamplesPerPixel + * tag value because older TIFF specs permitted Compression + * to be written as a SamplesPerPixel-count tag entry. + * Thus if we don't first figure out the correct SamplesPerPixel + * tag value then we may end up ignoring the Compression tag + * value because it has an incorrect count value (if the + * true value of SamplesPerPixel is not 1). + */ + dp=TIFFReadDirectoryFindEntry(tif,dir,dircount,TIFFTAG_SAMPLESPERPIXEL); + if (dp) + { + if (!TIFFFetchNormalTag(tif,dp,0)) + goto bad; + dp->tdir_tag=IGNORE; + } + dp=TIFFReadDirectoryFindEntry(tif,dir,dircount,TIFFTAG_COMPRESSION); + if (dp) + { + /* + * The 5.0 spec says the Compression tag has one value, while + * earlier specs say it has one value per sample. Because of + * this, we accept the tag if one value is supplied with either + * count. + */ + uint16 value; + enum TIFFReadDirEntryErr err; + err=TIFFReadDirEntryShort(tif,dp,&value); + if (err==TIFFReadDirEntryErrCount) + err=TIFFReadDirEntryPersampleShort(tif,dp,&value); + if (err!=TIFFReadDirEntryErrOk) + { + TIFFReadDirEntryOutputErr(tif,err,module,""Compression"",0); + goto bad; + } + if (!TIFFSetField(tif,TIFFTAG_COMPRESSION,value)) + goto bad; + dp->tdir_tag=IGNORE; + } + else + { + if (!TIFFSetField(tif,TIFFTAG_COMPRESSION,COMPRESSION_NONE)) + goto bad; + } + /* + * First real pass over the directory. + */ + for (di=0, dp=dir; ditdir_tag!=IGNORE) + { + TIFFReadDirectoryFindFieldInfo(tif,dp->tdir_tag,&fii); + if (fii == FAILED_FII) + { + TIFFWarningExt(tif->tif_clientdata, module, + ""Unknown field with tag %d (0x%x) encountered"", + dp->tdir_tag,dp->tdir_tag); + /* the following knowingly leaks the + anonymous field structure */ + if (!_TIFFMergeFields(tif, + _TIFFCreateAnonField(tif, + dp->tdir_tag, + (TIFFDataType) dp->tdir_type), + 1)) { + TIFFWarningExt(tif->tif_clientdata, + module, + ""Registering anonymous field with tag %d (0x%x) failed"", + dp->tdir_tag, + dp->tdir_tag); + dp->tdir_tag=IGNORE; + } else { + TIFFReadDirectoryFindFieldInfo(tif,dp->tdir_tag,&fii); + assert(fii != FAILED_FII); + } + } + } + if (dp->tdir_tag!=IGNORE) + { + fip=tif->tif_fields[fii]; + if (fip->field_bit==FIELD_IGNORE) + dp->tdir_tag=IGNORE; + else + { + switch (dp->tdir_tag) + { + case TIFFTAG_STRIPOFFSETS: + case TIFFTAG_STRIPBYTECOUNTS: + case TIFFTAG_TILEOFFSETS: + case TIFFTAG_TILEBYTECOUNTS: + TIFFSetFieldBit(tif,fip->field_bit); + break; + case TIFFTAG_IMAGEWIDTH: + case TIFFTAG_IMAGELENGTH: + case TIFFTAG_IMAGEDEPTH: + case TIFFTAG_TILELENGTH: + case TIFFTAG_TILEWIDTH: + case TIFFTAG_TILEDEPTH: + case TIFFTAG_PLANARCONFIG: + case TIFFTAG_ROWSPERSTRIP: + case TIFFTAG_EXTRASAMPLES: + if (!TIFFFetchNormalTag(tif,dp,0)) + goto bad; + dp->tdir_tag=IGNORE; + break; + } + } + } + } + /* + * XXX: OJPEG hack. + * If a) compression is OJPEG, b) planarconfig tag says it's separate, + * c) strip offsets/bytecounts tag are both present and + * d) both contain exactly one value, then we consistently find + * that the buggy implementation of the buggy compression scheme + * matches contig planarconfig best. So we 'fix-up' the tag here + */ + if ((tif->tif_dir.td_compression==COMPRESSION_OJPEG)&& + (tif->tif_dir.td_planarconfig==PLANARCONFIG_SEPARATE)) + { + if (!_TIFFFillStriles(tif)) + goto bad; + dp=TIFFReadDirectoryFindEntry(tif,dir,dircount,TIFFTAG_STRIPOFFSETS); + if ((dp!=0)&&(dp->tdir_count==1)) + { + dp=TIFFReadDirectoryFindEntry(tif,dir,dircount, + TIFFTAG_STRIPBYTECOUNTS); + if ((dp!=0)&&(dp->tdir_count==1)) + { + tif->tif_dir.td_planarconfig=PLANARCONFIG_CONTIG; + TIFFWarningExt(tif->tif_clientdata,module, + ""Planarconfig tag value assumed incorrect, "" + ""assuming data is contig instead of chunky""); + } + } + } + /* + * Allocate directory structure and setup defaults. + */ + if (!TIFFFieldSet(tif,FIELD_IMAGEDIMENSIONS)) + { + MissingRequired(tif,""ImageLength""); + goto bad; + } + /* + * Setup appropriate structures (by strip or by tile) + */ + if (!TIFFFieldSet(tif, FIELD_TILEDIMENSIONS)) { + tif->tif_dir.td_nstrips = TIFFNumberOfStrips(tif); + tif->tif_dir.td_tilewidth = tif->tif_dir.td_imagewidth; + tif->tif_dir.td_tilelength = tif->tif_dir.td_rowsperstrip; + tif->tif_dir.td_tiledepth = tif->tif_dir.td_imagedepth; + tif->tif_flags &= ~TIFF_ISTILED; + } else { + tif->tif_dir.td_nstrips = TIFFNumberOfTiles(tif); + tif->tif_flags |= TIFF_ISTILED; + } + if (!tif->tif_dir.td_nstrips) { + TIFFErrorExt(tif->tif_clientdata, module, + ""Cannot handle zero number of %s"", + isTiled(tif) ? ""tiles"" : ""strips""); + goto bad; + } + tif->tif_dir.td_stripsperimage = tif->tif_dir.td_nstrips; + if (tif->tif_dir.td_planarconfig == PLANARCONFIG_SEPARATE) + tif->tif_dir.td_stripsperimage /= tif->tif_dir.td_samplesperpixel; + if (!TIFFFieldSet(tif, FIELD_STRIPOFFSETS)) { +#ifdef OJPEG_SUPPORT + if ((tif->tif_dir.td_compression==COMPRESSION_OJPEG) && + (isTiled(tif)==0) && + (tif->tif_dir.td_nstrips==1)) { + /* + * XXX: OJPEG hack. + * If a) compression is OJPEG, b) it's not a tiled TIFF, + * and c) the number of strips is 1, + * then we tolerate the absence of stripoffsets tag, + * because, presumably, all required data is in the + * JpegInterchangeFormat stream. + */ + TIFFSetFieldBit(tif, FIELD_STRIPOFFSETS); + } else +#endif + { + MissingRequired(tif, + isTiled(tif) ? ""TileOffsets"" : ""StripOffsets""); + goto bad; + } + } + /* + * Second pass: extract other information. + */ + for (di=0, dp=dir; ditdir_tag) + { + case IGNORE: + break; + case TIFFTAG_MINSAMPLEVALUE: + case TIFFTAG_MAXSAMPLEVALUE: + case TIFFTAG_BITSPERSAMPLE: + case TIFFTAG_DATATYPE: + case TIFFTAG_SAMPLEFORMAT: + /* + * The MinSampleValue, MaxSampleValue, BitsPerSample + * DataType and SampleFormat tags are supposed to be + * written as one value/sample, but some vendors + * incorrectly write one value only -- so we accept + * that as well (yuck). Other vendors write correct + * value for NumberOfSamples, but incorrect one for + * BitsPerSample and friends, and we will read this + * too. + */ + { + uint16 value; + enum TIFFReadDirEntryErr err; + err=TIFFReadDirEntryShort(tif,dp,&value); + if (err==TIFFReadDirEntryErrCount) + err=TIFFReadDirEntryPersampleShort(tif,dp,&value); + if (err!=TIFFReadDirEntryErrOk) + { + fip = TIFFFieldWithTag(tif,dp->tdir_tag); + TIFFReadDirEntryOutputErr(tif,err,module,fip ? fip->field_name : ""unknown tagname"",0); + goto bad; + } + if (!TIFFSetField(tif,dp->tdir_tag,value)) + goto bad; + if( dp->tdir_tag == TIFFTAG_BITSPERSAMPLE ) + bitspersample_read = TRUE; + } + break; + case TIFFTAG_SMINSAMPLEVALUE: + case TIFFTAG_SMAXSAMPLEVALUE: + { + + double *data = NULL; + enum TIFFReadDirEntryErr err; + uint32 saved_flags; + int m; + if (dp->tdir_count != (uint64)tif->tif_dir.td_samplesperpixel) + err = TIFFReadDirEntryErrCount; + else + err = TIFFReadDirEntryDoubleArray(tif, dp, &data); + if (err!=TIFFReadDirEntryErrOk) + { + fip = TIFFFieldWithTag(tif,dp->tdir_tag); + TIFFReadDirEntryOutputErr(tif,err,module,fip ? fip->field_name : ""unknown tagname"",0); + goto bad; + } + saved_flags = tif->tif_flags; + tif->tif_flags |= TIFF_PERSAMPLE; + m = TIFFSetField(tif,dp->tdir_tag,data); + tif->tif_flags = saved_flags; + _TIFFfree(data); + if (!m) + goto bad; + } + break; + case TIFFTAG_STRIPOFFSETS: + case TIFFTAG_TILEOFFSETS: +#if defined(DEFER_STRILE_LOAD) + _TIFFmemcpy( &(tif->tif_dir.td_stripoffset_entry), + dp, sizeof(TIFFDirEntry) ); +#else + if (!TIFFFetchStripThing(tif,dp,tif->tif_dir.td_nstrips,&tif->tif_dir.td_stripoffset)) + goto bad; +#endif + break; + case TIFFTAG_STRIPBYTECOUNTS: + case TIFFTAG_TILEBYTECOUNTS: +#if defined(DEFER_STRILE_LOAD) + _TIFFmemcpy( &(tif->tif_dir.td_stripbytecount_entry), + dp, sizeof(TIFFDirEntry) ); +#else + if (!TIFFFetchStripThing(tif,dp,tif->tif_dir.td_nstrips,&tif->tif_dir.td_stripbytecount)) + goto bad; +#endif + break; + case TIFFTAG_COLORMAP: + case TIFFTAG_TRANSFERFUNCTION: + { + enum TIFFReadDirEntryErr err; + uint32 countpersample; + uint32 countrequired; + uint32 incrementpersample; + uint16* value=NULL; + /* It would be dangerous to instantiate those tag values */ + /* since if td_bitspersample has not yet been read (due to */ + /* unordered tags), it could be read afterwards with a */ + /* values greater than the default one (1), which may cause */ + /* crashes in user code */ + if( !bitspersample_read ) + { + fip = TIFFFieldWithTag(tif,dp->tdir_tag); + TIFFWarningExt(tif->tif_clientdata,module, + ""Ignoring %s since BitsPerSample tag not found"", + fip ? fip->field_name : ""unknown tagname""); + continue; + } + /* ColorMap or TransferFunction for high bit */ + /* depths do not make much sense and could be */ + /* used as a denial of service vector */ + if (tif->tif_dir.td_bitspersample > 24) + { + fip = TIFFFieldWithTag(tif,dp->tdir_tag); + TIFFWarningExt(tif->tif_clientdata,module, + ""Ignoring %s because BitsPerSample=%d>24"", + fip ? fip->field_name : ""unknown tagname"", + tif->tif_dir.td_bitspersample); + continue; + } + countpersample=(1U<tif_dir.td_bitspersample); + if ((dp->tdir_tag==TIFFTAG_TRANSFERFUNCTION)&&(dp->tdir_count==(uint64)countpersample)) + { + countrequired=countpersample; + incrementpersample=0; + } + else + { + countrequired=3*countpersample; + incrementpersample=countpersample; + } + if (dp->tdir_count!=(uint64)countrequired) + err=TIFFReadDirEntryErrCount; + else + err=TIFFReadDirEntryShortArray(tif,dp,&value); + if (err!=TIFFReadDirEntryErrOk) + { + fip = TIFFFieldWithTag(tif,dp->tdir_tag); + TIFFReadDirEntryOutputErr(tif,err,module,fip ? fip->field_name : ""unknown tagname"",1); + } + else + { + TIFFSetField(tif,dp->tdir_tag,value,value+incrementpersample,value+2*incrementpersample); + _TIFFfree(value); + } + } + break; +/* BEGIN REV 4.0 COMPATIBILITY */ + case TIFFTAG_OSUBFILETYPE: + { + uint16 valueo; + uint32 value; + if (TIFFReadDirEntryShort(tif,dp,&valueo)==TIFFReadDirEntryErrOk) + { + switch (valueo) + { + case OFILETYPE_REDUCEDIMAGE: value=FILETYPE_REDUCEDIMAGE; break; + case OFILETYPE_PAGE: value=FILETYPE_PAGE; break; + default: value=0; break; + } + if (value!=0) + TIFFSetField(tif,TIFFTAG_SUBFILETYPE,value); + } + } + break; +/* END REV 4.0 COMPATIBILITY */ + default: + (void) TIFFFetchNormalTag(tif, dp, TRUE); + break; + } + } + /* + * OJPEG hack: + * - If a) compression is OJPEG, and b) photometric tag is missing, + * then we consistently find that photometric should be YCbCr + * - If a) compression is OJPEG, and b) photometric tag says it's RGB, + * then we consistently find that the buggy implementation of the + * buggy compression scheme matches photometric YCbCr instead. + * - If a) compression is OJPEG, and b) bitspersample tag is missing, + * then we consistently find bitspersample should be 8. + * - If a) compression is OJPEG, b) samplesperpixel tag is missing, + * and c) photometric is RGB or YCbCr, then we consistently find + * samplesperpixel should be 3 + * - If a) compression is OJPEG, b) samplesperpixel tag is missing, + * and c) photometric is MINISWHITE or MINISBLACK, then we consistently + * find samplesperpixel should be 3 + */ + if (tif->tif_dir.td_compression==COMPRESSION_OJPEG) + { + if (!TIFFFieldSet(tif,FIELD_PHOTOMETRIC)) + { + TIFFWarningExt(tif->tif_clientdata, module, + ""Photometric tag is missing, assuming data is YCbCr""); + if (!TIFFSetField(tif,TIFFTAG_PHOTOMETRIC,PHOTOMETRIC_YCBCR)) + goto bad; + } + else if (tif->tif_dir.td_photometric==PHOTOMETRIC_RGB) + { + tif->tif_dir.td_photometric=PHOTOMETRIC_YCBCR; + TIFFWarningExt(tif->tif_clientdata, module, + ""Photometric tag value assumed incorrect, "" + ""assuming data is YCbCr instead of RGB""); + } + if (!TIFFFieldSet(tif,FIELD_BITSPERSAMPLE)) + { + TIFFWarningExt(tif->tif_clientdata,module, + ""BitsPerSample tag is missing, assuming 8 bits per sample""); + if (!TIFFSetField(tif,TIFFTAG_BITSPERSAMPLE,8)) + goto bad; + } + if (!TIFFFieldSet(tif,FIELD_SAMPLESPERPIXEL)) + { + if (tif->tif_dir.td_photometric==PHOTOMETRIC_RGB) + { + TIFFWarningExt(tif->tif_clientdata,module, + ""SamplesPerPixel tag is missing, "" + ""assuming correct SamplesPerPixel value is 3""); + if (!TIFFSetField(tif,TIFFTAG_SAMPLESPERPIXEL,3)) + goto bad; + } + if (tif->tif_dir.td_photometric==PHOTOMETRIC_YCBCR) + { + TIFFWarningExt(tif->tif_clientdata,module, + ""SamplesPerPixel tag is missing, "" + ""applying correct SamplesPerPixel value of 3""); + if (!TIFFSetField(tif,TIFFTAG_SAMPLESPERPIXEL,3)) + goto bad; + } + else if ((tif->tif_dir.td_photometric==PHOTOMETRIC_MINISWHITE) + || (tif->tif_dir.td_photometric==PHOTOMETRIC_MINISBLACK)) + { + /* + * SamplesPerPixel tag is missing, but is not required + * by spec. Assume correct SamplesPerPixel value of 1. + */ + if (!TIFFSetField(tif,TIFFTAG_SAMPLESPERPIXEL,1)) + goto bad; + } + } + } + /* + * Verify Palette image has a Colormap. + */ + if (tif->tif_dir.td_photometric == PHOTOMETRIC_PALETTE && + !TIFFFieldSet(tif, FIELD_COLORMAP)) { + if ( tif->tif_dir.td_bitspersample>=8 && tif->tif_dir.td_samplesperpixel==3) + tif->tif_dir.td_photometric = PHOTOMETRIC_RGB; + else if (tif->tif_dir.td_bitspersample>=8) + tif->tif_dir.td_photometric = PHOTOMETRIC_MINISBLACK; + else { + MissingRequired(tif, ""Colormap""); + goto bad; + } + } + /* + * OJPEG hack: + * We do no further messing with strip/tile offsets/bytecounts in OJPEG + * TIFFs + */ + if (tif->tif_dir.td_compression!=COMPRESSION_OJPEG) + { + /* + * Attempt to deal with a missing StripByteCounts tag. + */ + if (!TIFFFieldSet(tif, FIELD_STRIPBYTECOUNTS)) { + /* + * Some manufacturers violate the spec by not giving + * the size of the strips. In this case, assume there + * is one uncompressed strip of data. + */ + if ((tif->tif_dir.td_planarconfig == PLANARCONFIG_CONTIG && + tif->tif_dir.td_nstrips > 1) || + (tif->tif_dir.td_planarconfig == PLANARCONFIG_SEPARATE && + tif->tif_dir.td_nstrips != (uint32)tif->tif_dir.td_samplesperpixel)) { + MissingRequired(tif, ""StripByteCounts""); + goto bad; + } + TIFFWarningExt(tif->tif_clientdata, module, + ""TIFF directory is missing required "" + ""\""StripByteCounts\"" field, calculating from imagelength""); + if (EstimateStripByteCounts(tif, dir, dircount) < 0) + goto bad; + /* + * Assume we have wrong StripByteCount value (in case + * of single strip) in following cases: + * - it is equal to zero along with StripOffset; + * - it is larger than file itself (in case of uncompressed + * image); + * - it is smaller than the size of the bytes per row + * multiplied on the number of rows. The last case should + * not be checked in the case of writing new image, + * because we may do not know the exact strip size + * until the whole image will be written and directory + * dumped out. + */ + #define BYTECOUNTLOOKSBAD \ + ( (tif->tif_dir.td_stripbytecount[0] == 0 && tif->tif_dir.td_stripoffset[0] != 0) || \ + (tif->tif_dir.td_compression == COMPRESSION_NONE && \ + tif->tif_dir.td_stripbytecount[0] > TIFFGetFileSize(tif) - tif->tif_dir.td_stripoffset[0]) || \ + (tif->tif_mode == O_RDONLY && \ + tif->tif_dir.td_compression == COMPRESSION_NONE && \ + tif->tif_dir.td_stripbytecount[0] < TIFFScanlineSize64(tif) * tif->tif_dir.td_imagelength) ) + + } else if (tif->tif_dir.td_nstrips == 1 + && _TIFFFillStriles(tif) + && tif->tif_dir.td_stripoffset[0] != 0 + && BYTECOUNTLOOKSBAD) { + /* + * XXX: Plexus (and others) sometimes give a value of + * zero for a tag when they don't know what the + * correct value is! Try and handle the simple case + * of estimating the size of a one strip image. + */ + TIFFWarningExt(tif->tif_clientdata, module, + ""Bogus \""StripByteCounts\"" field, ignoring and calculating from imagelength""); + if(EstimateStripByteCounts(tif, dir, dircount) < 0) + goto bad; + +#if !defined(DEFER_STRILE_LOAD) + } else if (tif->tif_dir.td_planarconfig == PLANARCONFIG_CONTIG + && tif->tif_dir.td_nstrips > 2 + && tif->tif_dir.td_compression == COMPRESSION_NONE + && tif->tif_dir.td_stripbytecount[0] != tif->tif_dir.td_stripbytecount[1] + && tif->tif_dir.td_stripbytecount[0] != 0 + && tif->tif_dir.td_stripbytecount[1] != 0 ) { + /* + * XXX: Some vendors fill StripByteCount array with + * absolutely wrong values (it can be equal to + * StripOffset array, for example). Catch this case + * here. + * + * We avoid this check if deferring strile loading + * as it would always force us to load the strip/tile + * information. + */ + TIFFWarningExt(tif->tif_clientdata, module, + ""Wrong \""StripByteCounts\"" field, ignoring and calculating from imagelength""); + if (EstimateStripByteCounts(tif, dir, dircount) < 0) + goto bad; +#endif /* !defined(DEFER_STRILE_LOAD) */ + } + } + if (dir) + { + _TIFFfree(dir); + dir=NULL; + } + if (!TIFFFieldSet(tif, FIELD_MAXSAMPLEVALUE)) + { + if (tif->tif_dir.td_bitspersample>=16) + tif->tif_dir.td_maxsamplevalue=0xFFFF; + else + tif->tif_dir.td_maxsamplevalue = (uint16)((1L<tif_dir.td_bitspersample)-1); + } + /* + * XXX: We can optimize checking for the strip bounds using the sorted + * bytecounts array. See also comments for TIFFAppendToStrip() + * function in tif_write.c. + */ +#if !defined(DEFER_STRILE_LOAD) + if (tif->tif_dir.td_nstrips > 1) { + uint32 strip; + + tif->tif_dir.td_stripbytecountsorted = 1; + for (strip = 1; strip < tif->tif_dir.td_nstrips; strip++) { + if (tif->tif_dir.td_stripoffset[strip - 1] > + tif->tif_dir.td_stripoffset[strip]) { + tif->tif_dir.td_stripbytecountsorted = 0; + break; + } + } + } +#endif /* !defined(DEFER_STRILE_LOAD) */ + + /* + * An opportunity for compression mode dependent tag fixup + */ + (*tif->tif_fixuptags)(tif); + + /* + * Some manufacturers make life difficult by writing + * large amounts of uncompressed data as a single strip. + * This is contrary to the recommendations of the spec. + * The following makes an attempt at breaking such images + * into strips closer to the recommended 8k bytes. A + * side effect, however, is that the RowsPerStrip tag + * value may be changed. + */ + if ((tif->tif_dir.td_planarconfig==PLANARCONFIG_CONTIG)&& + (tif->tif_dir.td_nstrips==1)&& + (tif->tif_dir.td_compression==COMPRESSION_NONE)&& + ((tif->tif_flags&(TIFF_STRIPCHOP|TIFF_ISTILED))==TIFF_STRIPCHOP)) + { + if ( !_TIFFFillStriles(tif) || !tif->tif_dir.td_stripbytecount ) + return 0; + ChopUpSingleUncompressedStrip(tif); + } + + /* + * Clear the dirty directory flag. + */ + tif->tif_flags &= ~TIFF_DIRTYDIRECT; + tif->tif_flags &= ~TIFF_DIRTYSTRIP; + + /* + * Reinitialize i/o since we are starting on a new directory. + */ + tif->tif_row = (uint32) -1; + tif->tif_curstrip = (uint32) -1; + tif->tif_col = (uint32) -1; + tif->tif_curtile = (uint32) -1; + tif->tif_tilesize = (tmsize_t) -1; + + tif->tif_scanlinesize = TIFFScanlineSize(tif); + if (!tif->tif_scanlinesize) { + TIFFErrorExt(tif->tif_clientdata, module, + ""Cannot handle zero scanline size""); + return (0); + } + + if (isTiled(tif)) { + tif->tif_tilesize = TIFFTileSize(tif); + if (!tif->tif_tilesize) { + TIFFErrorExt(tif->tif_clientdata, module, + ""Cannot handle zero tile size""); + return (0); + } + } else { + if (!TIFFStripSize(tif)) { + TIFFErrorExt(tif->tif_clientdata, module, + ""Cannot handle zero strip size""); + return (0); + } + } + return (1); +bad: + if (dir) + _TIFFfree(dir); + return (0); +} +",0,"TIFFReadDirectory(TIFF* tif) +{ + static const char module[] = ""TIFFReadDirectory""; + TIFFDirEntry* dir; + uint16 dircount; + TIFFDirEntry* dp; + uint16 di; + const TIFFField* fip; + uint32 fii=FAILED_FII; + toff_t nextdiroff; + int bitspersample_read = FALSE; + + tif->tif_diroff=tif->tif_nextdiroff; + if (!TIFFCheckDirOffset(tif,tif->tif_nextdiroff)) + return 0; /* last offset or bad offset (IFD looping) */ + (*tif->tif_cleanup)(tif); /* cleanup any previous compression state */ + tif->tif_curdir++; + nextdiroff = tif->tif_nextdiroff; + dircount=TIFFFetchDirectory(tif,nextdiroff,&dir,&tif->tif_nextdiroff); + if (!dircount) + { + TIFFErrorExt(tif->tif_clientdata,module, + ""Failed to read directory at offset "" TIFF_UINT64_FORMAT,nextdiroff); + return 0; + } + TIFFReadDirectoryCheckOrder(tif,dir,dircount); + + /* + * Mark duplicates of any tag to be ignored (bugzilla 1994) + * to avoid certain pathological problems. + */ + { + TIFFDirEntry* ma; + uint16 mb; + for (ma=dir, mb=0; mbtdir_tag==na->tdir_tag) + na->tdir_tag=IGNORE; + } + } + } + + tif->tif_flags &= ~TIFF_BEENWRITING; /* reset before new dir */ + tif->tif_flags &= ~TIFF_BUF4WRITE; /* reset before new dir */ + /* free any old stuff and reinit */ + TIFFFreeDirectory(tif); + TIFFDefaultDirectory(tif); + /* + * Electronic Arts writes gray-scale TIFF files + * without a PlanarConfiguration directory entry. + * Thus we setup a default value here, even though + * the TIFF spec says there is no default value. + */ + TIFFSetField(tif,TIFFTAG_PLANARCONFIG,PLANARCONFIG_CONTIG); + /* + * Setup default value and then make a pass over + * the fields to check type and tag information, + * and to extract info required to size data + * structures. A second pass is made afterwards + * to read in everything not taken in the first pass. + * But we must process the Compression tag first + * in order to merge in codec-private tag definitions (otherwise + * we may get complaints about unknown tags). However, the + * Compression tag may be dependent on the SamplesPerPixel + * tag value because older TIFF specs permitted Compression + * to be written as a SamplesPerPixel-count tag entry. + * Thus if we don't first figure out the correct SamplesPerPixel + * tag value then we may end up ignoring the Compression tag + * value because it has an incorrect count value (if the + * true value of SamplesPerPixel is not 1). + */ + dp=TIFFReadDirectoryFindEntry(tif,dir,dircount,TIFFTAG_SAMPLESPERPIXEL); + if (dp) + { + if (!TIFFFetchNormalTag(tif,dp,0)) + goto bad; + dp->tdir_tag=IGNORE; + } + dp=TIFFReadDirectoryFindEntry(tif,dir,dircount,TIFFTAG_COMPRESSION); + if (dp) + { + /* + * The 5.0 spec says the Compression tag has one value, while + * earlier specs say it has one value per sample. Because of + * this, we accept the tag if one value is supplied with either + * count. + */ + uint16 value; + enum TIFFReadDirEntryErr err; + err=TIFFReadDirEntryShort(tif,dp,&value); + if (err==TIFFReadDirEntryErrCount) + err=TIFFReadDirEntryPersampleShort(tif,dp,&value); + if (err!=TIFFReadDirEntryErrOk) + { + TIFFReadDirEntryOutputErr(tif,err,module,""Compression"",0); + goto bad; + } + if (!TIFFSetField(tif,TIFFTAG_COMPRESSION,value)) + goto bad; + dp->tdir_tag=IGNORE; + } + else + { + if (!TIFFSetField(tif,TIFFTAG_COMPRESSION,COMPRESSION_NONE)) + goto bad; + } + /* + * First real pass over the directory. + */ + for (di=0, dp=dir; ditdir_tag!=IGNORE) + { + TIFFReadDirectoryFindFieldInfo(tif,dp->tdir_tag,&fii); + if (fii == FAILED_FII) + { + TIFFWarningExt(tif->tif_clientdata, module, + ""Unknown field with tag %d (0x%x) encountered"", + dp->tdir_tag,dp->tdir_tag); + /* the following knowingly leaks the + anonymous field structure */ + if (!_TIFFMergeFields(tif, + _TIFFCreateAnonField(tif, + dp->tdir_tag, + (TIFFDataType) dp->tdir_type), + 1)) { + TIFFWarningExt(tif->tif_clientdata, + module, + ""Registering anonymous field with tag %d (0x%x) failed"", + dp->tdir_tag, + dp->tdir_tag); + dp->tdir_tag=IGNORE; + } else { + TIFFReadDirectoryFindFieldInfo(tif,dp->tdir_tag,&fii); + assert(fii != FAILED_FII); + } + } + } + if (dp->tdir_tag!=IGNORE) + { + fip=tif->tif_fields[fii]; + if (fip->field_bit==FIELD_IGNORE) + dp->tdir_tag=IGNORE; + else + { + switch (dp->tdir_tag) + { + case TIFFTAG_STRIPOFFSETS: + case TIFFTAG_STRIPBYTECOUNTS: + case TIFFTAG_TILEOFFSETS: + case TIFFTAG_TILEBYTECOUNTS: + TIFFSetFieldBit(tif,fip->field_bit); + break; + case TIFFTAG_IMAGEWIDTH: + case TIFFTAG_IMAGELENGTH: + case TIFFTAG_IMAGEDEPTH: + case TIFFTAG_TILELENGTH: + case TIFFTAG_TILEWIDTH: + case TIFFTAG_TILEDEPTH: + case TIFFTAG_PLANARCONFIG: + case TIFFTAG_ROWSPERSTRIP: + case TIFFTAG_EXTRASAMPLES: + if (!TIFFFetchNormalTag(tif,dp,0)) + goto bad; + dp->tdir_tag=IGNORE; + break; + } + } + } + } + /* + * XXX: OJPEG hack. + * If a) compression is OJPEG, b) planarconfig tag says it's separate, + * c) strip offsets/bytecounts tag are both present and + * d) both contain exactly one value, then we consistently find + * that the buggy implementation of the buggy compression scheme + * matches contig planarconfig best. So we 'fix-up' the tag here + */ + if ((tif->tif_dir.td_compression==COMPRESSION_OJPEG)&& + (tif->tif_dir.td_planarconfig==PLANARCONFIG_SEPARATE)) + { + if (!_TIFFFillStriles(tif)) + goto bad; + dp=TIFFReadDirectoryFindEntry(tif,dir,dircount,TIFFTAG_STRIPOFFSETS); + if ((dp!=0)&&(dp->tdir_count==1)) + { + dp=TIFFReadDirectoryFindEntry(tif,dir,dircount, + TIFFTAG_STRIPBYTECOUNTS); + if ((dp!=0)&&(dp->tdir_count==1)) + { + tif->tif_dir.td_planarconfig=PLANARCONFIG_CONTIG; + TIFFWarningExt(tif->tif_clientdata,module, + ""Planarconfig tag value assumed incorrect, "" + ""assuming data is contig instead of chunky""); + } + } + } + /* + * Allocate directory structure and setup defaults. + */ + if (!TIFFFieldSet(tif,FIELD_IMAGEDIMENSIONS)) + { + MissingRequired(tif,""ImageLength""); + goto bad; + } + /* + * Setup appropriate structures (by strip or by tile) + */ + if (!TIFFFieldSet(tif, FIELD_TILEDIMENSIONS)) { + tif->tif_dir.td_nstrips = TIFFNumberOfStrips(tif); + tif->tif_dir.td_tilewidth = tif->tif_dir.td_imagewidth; + tif->tif_dir.td_tilelength = tif->tif_dir.td_rowsperstrip; + tif->tif_dir.td_tiledepth = tif->tif_dir.td_imagedepth; + tif->tif_flags &= ~TIFF_ISTILED; + } else { + tif->tif_dir.td_nstrips = TIFFNumberOfTiles(tif); + tif->tif_flags |= TIFF_ISTILED; + } + if (!tif->tif_dir.td_nstrips) { + TIFFErrorExt(tif->tif_clientdata, module, + ""Cannot handle zero number of %s"", + isTiled(tif) ? ""tiles"" : ""strips""); + goto bad; + } + tif->tif_dir.td_stripsperimage = tif->tif_dir.td_nstrips; + if (tif->tif_dir.td_planarconfig == PLANARCONFIG_SEPARATE) + tif->tif_dir.td_stripsperimage /= tif->tif_dir.td_samplesperpixel; + if (!TIFFFieldSet(tif, FIELD_STRIPOFFSETS)) { +#ifdef OJPEG_SUPPORT + if ((tif->tif_dir.td_compression==COMPRESSION_OJPEG) && + (isTiled(tif)==0) && + (tif->tif_dir.td_nstrips==1)) { + /* + * XXX: OJPEG hack. + * If a) compression is OJPEG, b) it's not a tiled TIFF, + * and c) the number of strips is 1, + * then we tolerate the absence of stripoffsets tag, + * because, presumably, all required data is in the + * JpegInterchangeFormat stream. + */ + TIFFSetFieldBit(tif, FIELD_STRIPOFFSETS); + } else +#endif + { + MissingRequired(tif, + isTiled(tif) ? ""TileOffsets"" : ""StripOffsets""); + goto bad; + } + } + /* + * Second pass: extract other information. + */ + for (di=0, dp=dir; ditdir_tag) + { + case IGNORE: + break; + case TIFFTAG_MINSAMPLEVALUE: + case TIFFTAG_MAXSAMPLEVALUE: + case TIFFTAG_BITSPERSAMPLE: + case TIFFTAG_DATATYPE: + case TIFFTAG_SAMPLEFORMAT: + /* + * The MinSampleValue, MaxSampleValue, BitsPerSample + * DataType and SampleFormat tags are supposed to be + * written as one value/sample, but some vendors + * incorrectly write one value only -- so we accept + * that as well (yuck). Other vendors write correct + * value for NumberOfSamples, but incorrect one for + * BitsPerSample and friends, and we will read this + * too. + */ + { + uint16 value; + enum TIFFReadDirEntryErr err; + err=TIFFReadDirEntryShort(tif,dp,&value); + if (err==TIFFReadDirEntryErrCount) + err=TIFFReadDirEntryPersampleShort(tif,dp,&value); + if (err!=TIFFReadDirEntryErrOk) + { + fip = TIFFFieldWithTag(tif,dp->tdir_tag); + TIFFReadDirEntryOutputErr(tif,err,module,fip ? fip->field_name : ""unknown tagname"",0); + goto bad; + } + if (!TIFFSetField(tif,dp->tdir_tag,value)) + goto bad; + if( dp->tdir_tag == TIFFTAG_BITSPERSAMPLE ) + bitspersample_read = TRUE; + } + break; + case TIFFTAG_SMINSAMPLEVALUE: + case TIFFTAG_SMAXSAMPLEVALUE: + { + + double *data = NULL; + enum TIFFReadDirEntryErr err; + uint32 saved_flags; + int m; + if (dp->tdir_count != (uint64)tif->tif_dir.td_samplesperpixel) + err = TIFFReadDirEntryErrCount; + else + err = TIFFReadDirEntryDoubleArray(tif, dp, &data); + if (err!=TIFFReadDirEntryErrOk) + { + fip = TIFFFieldWithTag(tif,dp->tdir_tag); + TIFFReadDirEntryOutputErr(tif,err,module,fip ? fip->field_name : ""unknown tagname"",0); + goto bad; + } + saved_flags = tif->tif_flags; + tif->tif_flags |= TIFF_PERSAMPLE; + m = TIFFSetField(tif,dp->tdir_tag,data); + tif->tif_flags = saved_flags; + _TIFFfree(data); + if (!m) + goto bad; + } + break; + case TIFFTAG_STRIPOFFSETS: + case TIFFTAG_TILEOFFSETS: +#if defined(DEFER_STRILE_LOAD) + _TIFFmemcpy( &(tif->tif_dir.td_stripoffset_entry), + dp, sizeof(TIFFDirEntry) ); +#else + if (!TIFFFetchStripThing(tif,dp,tif->tif_dir.td_nstrips,&tif->tif_dir.td_stripoffset)) + goto bad; +#endif + break; + case TIFFTAG_STRIPBYTECOUNTS: + case TIFFTAG_TILEBYTECOUNTS: +#if defined(DEFER_STRILE_LOAD) + _TIFFmemcpy( &(tif->tif_dir.td_stripbytecount_entry), + dp, sizeof(TIFFDirEntry) ); +#else + if (!TIFFFetchStripThing(tif,dp,tif->tif_dir.td_nstrips,&tif->tif_dir.td_stripbytecount)) + goto bad; +#endif + break; + case TIFFTAG_COLORMAP: + case TIFFTAG_TRANSFERFUNCTION: + { + enum TIFFReadDirEntryErr err; + uint32 countpersample; + uint32 countrequired; + uint32 incrementpersample; + uint16* value=NULL; + /* It would be dangerous to instantiate those tag values */ + /* since if td_bitspersample has not yet been read (due to */ + /* unordered tags), it could be read afterwards with a */ + /* values greater than the default one (1), which may cause */ + /* crashes in user code */ + if( !bitspersample_read ) + { + fip = TIFFFieldWithTag(tif,dp->tdir_tag); + TIFFWarningExt(tif->tif_clientdata,module, + ""Ignoring %s since BitsPerSample tag not found"", + fip ? fip->field_name : ""unknown tagname""); + continue; + } + /* ColorMap or TransferFunction for high bit */ + /* depths do not make much sense and could be */ + /* used as a denial of service vector */ + if (tif->tif_dir.td_bitspersample > 24) + { + fip = TIFFFieldWithTag(tif,dp->tdir_tag); + TIFFWarningExt(tif->tif_clientdata,module, + ""Ignoring %s because BitsPerSample=%d>24"", + fip ? fip->field_name : ""unknown tagname"", + tif->tif_dir.td_bitspersample); + continue; + } + countpersample=(1U<tif_dir.td_bitspersample); + if ((dp->tdir_tag==TIFFTAG_TRANSFERFUNCTION)&&(dp->tdir_count==(uint64)countpersample)) + { + countrequired=countpersample; + incrementpersample=0; + } + else + { + countrequired=3*countpersample; + incrementpersample=countpersample; + } + if (dp->tdir_count!=(uint64)countrequired) + err=TIFFReadDirEntryErrCount; + else + err=TIFFReadDirEntryShortArray(tif,dp,&value); + if (err!=TIFFReadDirEntryErrOk) + { + fip = TIFFFieldWithTag(tif,dp->tdir_tag); + TIFFReadDirEntryOutputErr(tif,err,module,fip ? fip->field_name : ""unknown tagname"",1); + } + else + { + TIFFSetField(tif,dp->tdir_tag,value,value+incrementpersample,value+2*incrementpersample); + _TIFFfree(value); + } + } + break; +/* BEGIN REV 4.0 COMPATIBILITY */ + case TIFFTAG_OSUBFILETYPE: + { + uint16 valueo; + uint32 value; + if (TIFFReadDirEntryShort(tif,dp,&valueo)==TIFFReadDirEntryErrOk) + { + switch (valueo) + { + case OFILETYPE_REDUCEDIMAGE: value=FILETYPE_REDUCEDIMAGE; break; + case OFILETYPE_PAGE: value=FILETYPE_PAGE; break; + default: value=0; break; + } + if (value!=0) + TIFFSetField(tif,TIFFTAG_SUBFILETYPE,value); + } + } + break; +/* END REV 4.0 COMPATIBILITY */ + default: + (void) TIFFFetchNormalTag(tif, dp, TRUE); + break; + } + } + /* + * OJPEG hack: + * - If a) compression is OJPEG, and b) photometric tag is missing, + * then we consistently find that photometric should be YCbCr + * - If a) compression is OJPEG, and b) photometric tag says it's RGB, + * then we consistently find that the buggy implementation of the + * buggy compression scheme matches photometric YCbCr instead. + * - If a) compression is OJPEG, and b) bitspersample tag is missing, + * then we consistently find bitspersample should be 8. + * - If a) compression is OJPEG, b) samplesperpixel tag is missing, + * and c) photometric is RGB or YCbCr, then we consistently find + * samplesperpixel should be 3 + * - If a) compression is OJPEG, b) samplesperpixel tag is missing, + * and c) photometric is MINISWHITE or MINISBLACK, then we consistently + * find samplesperpixel should be 3 + */ + if (tif->tif_dir.td_compression==COMPRESSION_OJPEG) + { + if (!TIFFFieldSet(tif,FIELD_PHOTOMETRIC)) + { + TIFFWarningExt(tif->tif_clientdata, module, + ""Photometric tag is missing, assuming data is YCbCr""); + if (!TIFFSetField(tif,TIFFTAG_PHOTOMETRIC,PHOTOMETRIC_YCBCR)) + goto bad; + } + else if (tif->tif_dir.td_photometric==PHOTOMETRIC_RGB) + { + tif->tif_dir.td_photometric=PHOTOMETRIC_YCBCR; + TIFFWarningExt(tif->tif_clientdata, module, + ""Photometric tag value assumed incorrect, "" + ""assuming data is YCbCr instead of RGB""); + } + if (!TIFFFieldSet(tif,FIELD_BITSPERSAMPLE)) + { + TIFFWarningExt(tif->tif_clientdata,module, + ""BitsPerSample tag is missing, assuming 8 bits per sample""); + if (!TIFFSetField(tif,TIFFTAG_BITSPERSAMPLE,8)) + goto bad; + } + if (!TIFFFieldSet(tif,FIELD_SAMPLESPERPIXEL)) + { + if (tif->tif_dir.td_photometric==PHOTOMETRIC_RGB) + { + TIFFWarningExt(tif->tif_clientdata,module, + ""SamplesPerPixel tag is missing, "" + ""assuming correct SamplesPerPixel value is 3""); + if (!TIFFSetField(tif,TIFFTAG_SAMPLESPERPIXEL,3)) + goto bad; + } + if (tif->tif_dir.td_photometric==PHOTOMETRIC_YCBCR) + { + TIFFWarningExt(tif->tif_clientdata,module, + ""SamplesPerPixel tag is missing, "" + ""applying correct SamplesPerPixel value of 3""); + if (!TIFFSetField(tif,TIFFTAG_SAMPLESPERPIXEL,3)) + goto bad; + } + else if ((tif->tif_dir.td_photometric==PHOTOMETRIC_MINISWHITE) + || (tif->tif_dir.td_photometric==PHOTOMETRIC_MINISBLACK)) + { + /* + * SamplesPerPixel tag is missing, but is not required + * by spec. Assume correct SamplesPerPixel value of 1. + */ + if (!TIFFSetField(tif,TIFFTAG_SAMPLESPERPIXEL,1)) + goto bad; + } + } + } + /* + * Verify Palette image has a Colormap. + */ + if (tif->tif_dir.td_photometric == PHOTOMETRIC_PALETTE && + !TIFFFieldSet(tif, FIELD_COLORMAP)) { + if ( tif->tif_dir.td_bitspersample>=8 && tif->tif_dir.td_samplesperpixel==3) + tif->tif_dir.td_photometric = PHOTOMETRIC_RGB; + else if (tif->tif_dir.td_bitspersample>=8) + tif->tif_dir.td_photometric = PHOTOMETRIC_MINISBLACK; + else { + MissingRequired(tif, ""Colormap""); + goto bad; + } + } + /* + * OJPEG hack: + * We do no further messing with strip/tile offsets/bytecounts in OJPEG + * TIFFs + */ + if (tif->tif_dir.td_compression!=COMPRESSION_OJPEG) + { + /* + * Attempt to deal with a missing StripByteCounts tag. + */ + if (!TIFFFieldSet(tif, FIELD_STRIPBYTECOUNTS)) { + /* + * Some manufacturers violate the spec by not giving + * the size of the strips. In this case, assume there + * is one uncompressed strip of data. + */ + if ((tif->tif_dir.td_planarconfig == PLANARCONFIG_CONTIG && + tif->tif_dir.td_nstrips > 1) || + (tif->tif_dir.td_planarconfig == PLANARCONFIG_SEPARATE && + tif->tif_dir.td_nstrips != (uint32)tif->tif_dir.td_samplesperpixel)) { + MissingRequired(tif, ""StripByteCounts""); + goto bad; + } + TIFFWarningExt(tif->tif_clientdata, module, + ""TIFF directory is missing required "" + ""\""StripByteCounts\"" field, calculating from imagelength""); + if (EstimateStripByteCounts(tif, dir, dircount) < 0) + goto bad; + /* + * Assume we have wrong StripByteCount value (in case + * of single strip) in following cases: + * - it is equal to zero along with StripOffset; + * - it is larger than file itself (in case of uncompressed + * image); + * - it is smaller than the size of the bytes per row + * multiplied on the number of rows. The last case should + * not be checked in the case of writing new image, + * because we may do not know the exact strip size + * until the whole image will be written and directory + * dumped out. + */ + #define BYTECOUNTLOOKSBAD \ + ( (tif->tif_dir.td_stripbytecount[0] == 0 && tif->tif_dir.td_stripoffset[0] != 0) || \ + (tif->tif_dir.td_compression == COMPRESSION_NONE && \ + tif->tif_dir.td_stripbytecount[0] > TIFFGetFileSize(tif) - tif->tif_dir.td_stripoffset[0]) || \ + (tif->tif_mode == O_RDONLY && \ + tif->tif_dir.td_compression == COMPRESSION_NONE && \ + tif->tif_dir.td_stripbytecount[0] < TIFFScanlineSize64(tif) * tif->tif_dir.td_imagelength) ) + + } else if (tif->tif_dir.td_nstrips == 1 + && _TIFFFillStriles(tif) + && tif->tif_dir.td_stripoffset[0] != 0 + && BYTECOUNTLOOKSBAD) { + /* + * XXX: Plexus (and others) sometimes give a value of + * zero for a tag when they don't know what the + * correct value is! Try and handle the simple case + * of estimating the size of a one strip image. + */ + TIFFWarningExt(tif->tif_clientdata, module, + ""Bogus \""StripByteCounts\"" field, ignoring and calculating from imagelength""); + if(EstimateStripByteCounts(tif, dir, dircount) < 0) + goto bad; + +#if !defined(DEFER_STRILE_LOAD) + } else if (tif->tif_dir.td_planarconfig == PLANARCONFIG_CONTIG + && tif->tif_dir.td_nstrips > 2 + && tif->tif_dir.td_compression == COMPRESSION_NONE + && tif->tif_dir.td_stripbytecount[0] != tif->tif_dir.td_stripbytecount[1] + && tif->tif_dir.td_stripbytecount[0] != 0 + && tif->tif_dir.td_stripbytecount[1] != 0 ) { + /* + * XXX: Some vendors fill StripByteCount array with + * absolutely wrong values (it can be equal to + * StripOffset array, for example). Catch this case + * here. + * + * We avoid this check if deferring strile loading + * as it would always force us to load the strip/tile + * information. + */ + TIFFWarningExt(tif->tif_clientdata, module, + ""Wrong \""StripByteCounts\"" field, ignoring and calculating from imagelength""); + if (EstimateStripByteCounts(tif, dir, dircount) < 0) + goto bad; +#endif /* !defined(DEFER_STRILE_LOAD) */ + } + } + if (dir) + { + _TIFFfree(dir); + dir=NULL; + } + if (!TIFFFieldSet(tif, FIELD_MAXSAMPLEVALUE)) + { + if (tif->tif_dir.td_bitspersample>=16) + tif->tif_dir.td_maxsamplevalue=0xFFFF; + else + tif->tif_dir.td_maxsamplevalue = (uint16)((1L<tif_dir.td_bitspersample)-1); + } + /* + * XXX: We can optimize checking for the strip bounds using the sorted + * bytecounts array. See also comments for TIFFAppendToStrip() + * function in tif_write.c. + */ +#if !defined(DEFER_STRILE_LOAD) + if (tif->tif_dir.td_nstrips > 1) { + uint32 strip; + + tif->tif_dir.td_stripbytecountsorted = 1; + for (strip = 1; strip < tif->tif_dir.td_nstrips; strip++) { + if (tif->tif_dir.td_stripoffset[strip - 1] > + tif->tif_dir.td_stripoffset[strip]) { + tif->tif_dir.td_stripbytecountsorted = 0; + break; + } + } + } +#endif /* !defined(DEFER_STRILE_LOAD) */ + + /* + * An opportunity for compression mode dependent tag fixup + */ + (*tif->tif_fixuptags)(tif); + + /* + * Some manufacturers make life difficult by writing + * large amounts of uncompressed data as a single strip. + * This is contrary to the recommendations of the spec. + * The following makes an attempt at breaking such images + * into strips closer to the recommended 8k bytes. A + * side effect, however, is that the RowsPerStrip tag + * value may be changed. + */ + if ((tif->tif_dir.td_planarconfig==PLANARCONFIG_CONTIG)&& + (tif->tif_dir.td_nstrips==1)&& + (tif->tif_dir.td_compression==COMPRESSION_NONE)&& + ((tif->tif_flags&(TIFF_STRIPCHOP|TIFF_ISTILED))==TIFF_STRIPCHOP)) + { + if ( !_TIFFFillStriles(tif) || !tif->tif_dir.td_stripbytecount ) + return 0; + ChopUpSingleUncompressedStrip(tif); + } + + /* + * Clear the dirty directory flag. + */ + tif->tif_flags &= ~TIFF_DIRTYDIRECT; + tif->tif_flags &= ~TIFF_DIRTYSTRIP; + + /* + * Reinitialize i/o since we are starting on a new directory. + */ + tif->tif_row = (uint32) -1; + tif->tif_curstrip = (uint32) -1; + tif->tif_col = (uint32) -1; + tif->tif_curtile = (uint32) -1; + tif->tif_tilesize = (tmsize_t) -1; + + tif->tif_scanlinesize = TIFFScanlineSize(tif); + if (!tif->tif_scanlinesize) { + TIFFErrorExt(tif->tif_clientdata, module, + ""Cannot handle zero scanline size""); + return (0); + } + + if (isTiled(tif)) { + tif->tif_tilesize = TIFFTileSize(tif); + if (!tif->tif_tilesize) { + TIFFErrorExt(tif->tif_clientdata, module, + ""Cannot handle zero tile size""); + return (0); + } + } else { + if (!TIFFStripSize(tif)) { + TIFFErrorExt(tif->tif_clientdata, module, + ""Cannot handle zero strip size""); + return (0); + } + } + return (1); +bad: + if (dir) + _TIFFfree(dir); + return (0); +} +","@@ -5502,8 +5502,7 @@ ChopUpSingleUncompressedStrip(TIFF* tif) + uint64 rowblockbytes; + uint64 stripbytes; + uint32 strip; +- uint64 nstrips64; +- uint32 nstrips32; ++ uint32 nstrips; + uint32 rowsperstrip; + uint64* newcounts; + uint64* newoffsets; +@@ -5534,18 +5533,17 @@ ChopUpSingleUncompressedStrip(TIFF* tif) + return; + + /* +- * never increase the number of strips in an image ++ * never increase the number of rows per strip + */ + if (rowsperstrip >= td->td_rowsperstrip) + return; +- nstrips64 = TIFFhowmany_64(bytecount, stripbytes); +- if ((nstrips64==0)||(nstrips64>0xFFFFFFFF)) /* something is wonky, do nothing. */ +- return; +- nstrips32 = (uint32)nstrips64; ++ nstrips = TIFFhowmany_32(td->td_imagelength, rowsperstrip); ++ if( nstrips == 0 ) ++ return; + +- newcounts = (uint64*) _TIFFCheckMalloc(tif, nstrips32, sizeof (uint64), ++ newcounts = (uint64*) _TIFFCheckMalloc(tif, nstrips, sizeof (uint64), + ""for chopped \""StripByteCounts\"" array""); +- newoffsets = (uint64*) _TIFFCheckMalloc(tif, nstrips32, sizeof (uint64), ++ newoffsets = (uint64*) _TIFFCheckMalloc(tif, nstrips, sizeof (uint64), + ""for chopped \""StripOffsets\"" array""); + if (newcounts == NULL || newoffsets == NULL) { + /* +@@ -5562,18 +5560,18 @@ ChopUpSingleUncompressedStrip(TIFF* tif) + * Fill the strip information arrays with new bytecounts and offsets + * that reflect the broken-up format. + */ +- for (strip = 0; strip < nstrips32; strip++) { ++ for (strip = 0; strip < nstrips; strip++) { + if (stripbytes > bytecount) + stripbytes = bytecount; + newcounts[strip] = stripbytes; +- newoffsets[strip] = offset; ++ newoffsets[strip] = stripbytes ? offset : 0; + offset += stripbytes; + bytecount -= stripbytes; + } + /* + * Replace old single strip info with multi-strip info. + */ +- td->td_stripsperimage = td->td_nstrips = nstrips32; ++ td->td_stripsperimage = td->td_nstrips = nstrips; + TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip); + + _TIFFfree(td->td_stripbytecount);",6813,7144,8192 +18232,"static int _6502_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) { + char addrbuf[64]; + const int buffsize = sizeof (addrbuf) - 1; + + memset (op, '\0', sizeof (RAnalOp)); + op->size = snes_op_get_size (1, 1, &snes_op[data[0]]); //snes-arch is similiar to nes/6502 + op->addr = addr; + op->type = R_ANAL_OP_TYPE_UNK; + op->id = data[0]; + r_strbuf_init (&op->esil); + switch (data[0]) { + case 0x02: + case 0x03: + case 0x04: + case 0x07: + case 0x0b: + case 0x0c: + case 0x0f: + case 0x12: + case 0x13: + case 0x14: + case 0x17: + case 0x1a: + case 0x1b: + case 0x1c: + case 0x1f: + case 0x22: + case 0x23: + case 0x27: + case 0x2b: + case 0x2f: + case 0x32: + case 0x33: + case 0x34: + case 0x37: + case 0x3a: + case 0x3b: + case 0x3c: + case 0x3f: + case 0x42: + case 0x43: + case 0x44: + case 0x47: + case 0x4b: + case 0x4f: + case 0x52: + case 0x53: + case 0x54: + case 0x57: + case 0x5a: + case 0x5b: + case 0x5c: + case 0x5f: + case 0x62: + case 0x63: + case 0x64: + case 0x67: + case 0x6b: + case 0x6f: + case 0x72: + case 0x73: + case 0x74: + case 0x77: + case 0x7a: + case 0x7b: + case 0x7c: + case 0x7f: + case 0x80: + case 0x82: + case 0x83: + case 0x87: + case 0x89: + case 0x8b: + case 0x8f: + case 0x92: + case 0x93: + case 0x97: + case 0x9b: + case 0x9c: + case 0x9e: + case 0x9f: + case 0xa3: + case 0xa7: + case 0xab: + case 0xaf: + case 0xb2: + case 0xb3: + case 0xb7: + case 0xbb: + case 0xbf: + case 0xc2: + case 0xc3: + case 0xc7: + case 0xcb: + case 0xcf: + case 0xd2: + case 0xd3: + case 0xd4: + case 0xd7: + case 0xda: + case 0xdb: + case 0xdc: + case 0xdf: + case 0xe2: + case 0xe3: + case 0xe7: + case 0xeb: + case 0xef: + case 0xf2: + case 0xf3: + case 0xf4: + case 0xf7: + case 0xfa: + case 0xfb: + case 0xfc: + case 0xff: + op->size = 1; + op->type = R_ANAL_OP_TYPE_ILL; + break; + + case 0x00: // brk + op->cycles = 7; + op->type = R_ANAL_OP_TYPE_SWI; + op->size = 1; + r_strbuf_set (&op->esil, "",1,I,=,0,D,=,flags,0x10,|,0x100,sp,+,=[1],pc,1,+,0xfe,sp,+,=[2],3,sp,-=,0xfffe,[2],pc,=""); + break; + + case 0x78: // sei + case 0x58: // cli + case 0x38: // sec + case 0x18: // clc + case 0xf8: // sed + case 0xd8: // cld + case 0xb8: // clv + op->cycles = 2; + op->type = R_ANAL_OP_TYPE_NOP; + _6502_anal_esil_flags (op, data[0]); + break; + case 0x24: // bit $ff + case 0x2c: // bit $ffff + op->type = R_ANAL_OP_TYPE_MOV; + _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0); + r_strbuf_setf (&op->esil, ""a,%s,[1],&,0x80,&,!,!,N,=,a,%s,[1],&,0x40,&,!,!,V,=,a,%s,[1],&,0xff,&,!,Z,="",addrbuf, addrbuf, addrbuf); + break; + case 0x69: // adc #$ff + case 0x65: // adc $ff + case 0x75: // adc $ff,x + case 0x6d: // adc $ffff + case 0x7d: // adc $ffff,x + case 0x79: // adc $ffff,y + case 0x61: // adc ($ff,x) + case 0x71: // adc ($ff,y) + op->type = R_ANAL_OP_TYPE_ADD; + _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); + if (data[0] == 0x69) // immediate mode + r_strbuf_setf (&op->esil, ""%s,a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|="", addrbuf); + else r_strbuf_setf (&op->esil, ""%s,[1],a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|="", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + r_strbuf_append (&op->esil, "",a,a,=,$z,Z,=""); + break; + case 0xe9: // sbc #$ff + case 0xe5: // sbc $ff + case 0xf5: // sbc $ff,x + case 0xed: // sbc $ffff + case 0xfd: // sbc $ffff,x + case 0xf9: // sbc $ffff,y + case 0xe1: // sbc ($ff,x) + case 0xf1: // sbc ($ff,y) + op->type = R_ANAL_OP_TYPE_SUB; + _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); + if (data[0] == 0xe9) // immediate mode + r_strbuf_setf (&op->esil, ""C,!,%s,+,a,-="", addrbuf); + else r_strbuf_setf (&op->esil, ""C,!,%s,[1],+,a,-="", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_BNZ); + r_strbuf_append (&op->esil, "",a,a,=,$z,Z,=,C,!=""); + break; + case 0x09: // ora #$ff + case 0x05: // ora $ff + case 0x15: // ora $ff,x + case 0x0d: // ora $ffff + case 0x1d: // ora $ffff,x + case 0x19: // ora $ffff,y + case 0x01: // ora ($ff,x) + case 0x11: // ora ($ff),y + op->type = R_ANAL_OP_TYPE_OR; + _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); + if (data[0] == 0x09) // immediate mode + r_strbuf_setf (&op->esil, ""%s,a,|="", addrbuf); + else r_strbuf_setf (&op->esil, ""%s,[1],a,|="", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0x29: // and #$ff + case 0x25: // and $ff + case 0x35: // and $ff,x + case 0x2d: // and $ffff + case 0x3d: // and $ffff,x + case 0x39: // and $ffff,y + case 0x21: // and ($ff,x) + case 0x31: // and ($ff),y + op->type = R_ANAL_OP_TYPE_AND; + _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); + if (data[0] == 0x29) // immediate mode + r_strbuf_setf (&op->esil, ""%s,a,&="", addrbuf); + else r_strbuf_setf (&op->esil, ""%s,[1],a,&="", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0x49: // eor #$ff + case 0x45: // eor $ff + case 0x55: // eor $ff,x + case 0x4d: // eor $ffff + case 0x5d: // eor $ffff,x + case 0x59: // eor $ffff,y + case 0x41: // eor ($ff,x) + case 0x51: // eor ($ff),y + op->type = R_ANAL_OP_TYPE_XOR; + _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); + if (data[0] == 0x49) // immediate mode + r_strbuf_setf (&op->esil, ""%s,a,^="", addrbuf); + else r_strbuf_setf (&op->esil, ""%s,[1],a,^="", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0x0a: // asl a + case 0x06: // asl $ff + case 0x16: // asl $ff,x + case 0x0e: // asl $ffff + case 0x1e: // asl $ffff,x + op->type = R_ANAL_OP_TYPE_SHL; + if (data[0] == 0x0a) { + r_strbuf_set (&op->esil, ""1,a,<<=,$c7,C,=,a,a,=""); + } else { + _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); + r_strbuf_setf (&op->esil, ""1,%s,[1],<<,%s,=[1],$c7,C,="", addrbuf, addrbuf); + } + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0x4a: // lsr a + case 0x46: // lsr $ff + case 0x56: // lsr $ff,x + case 0x4e: // lsr $ffff + case 0x5e: // lsr $ffff,x + op->type = R_ANAL_OP_TYPE_SHR; + if (data[0] == 0x4a) { + r_strbuf_set (&op->esil, ""1,a,&,C,=,1,a,>>=""); + } else { + _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); + r_strbuf_setf (&op->esil, ""1,%s,[1],&,C,=,1,%s,[1],>>,%s,=[1]"", addrbuf, addrbuf, addrbuf); + } + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0x2a: // rol a + case 0x26: // rol $ff + case 0x36: // rol $ff,x + case 0x2e: // rol $ffff + case 0x3e: // rol $ffff,x + op->type = R_ANAL_OP_TYPE_ROL; + if (data[0] == 0x2a) { + r_strbuf_set (&op->esil, ""1,a,<<,C,|,a,=,$c7,C,=,a,a,=""); + } else { + _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); + r_strbuf_setf (&op->esil, ""1,%s,[1],<<,C,|,%s,=[1],$c7,C,="", addrbuf, addrbuf); + } + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0x6a: // ror a + case 0x66: // ror $ff + case 0x76: // ror $ff,x + case 0x6e: // ror $ffff + case 0x7e: // ror $ffff,x + op->type = R_ANAL_OP_TYPE_ROR; + if (data[0] == 0x6a) { + r_strbuf_set (&op->esil, ""C,N,=,1,a,&,C,=,1,a,>>,7,N,<<,|,a,=""); + } else { + _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); + r_strbuf_setf (&op->esil, ""C,N,=,1,%s,[1],&,C,=,1,%s,[1],>>,7,N,<<,|,%s,=[1]"", addrbuf, addrbuf, addrbuf); + } + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0xe6: // inc $ff + case 0xf6: // inc $ff,x + case 0xee: // inc $ffff + case 0xfe: // inc $ffff,x + op->type = R_ANAL_OP_TYPE_STORE; + _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); + r_strbuf_setf (&op->esil, ""%s,++=[1]"", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0xc6: // dec $ff + case 0xd6: // dec $ff,x + case 0xce: // dec $ffff + case 0xde: // dec $ffff,x + op->type = R_ANAL_OP_TYPE_STORE; + _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); + r_strbuf_setf (&op->esil, ""%s,--=[1]"", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0xe8: // inx + case 0xc8: // iny + op->cycles = 2; + op->type = R_ANAL_OP_TYPE_STORE; + _6502_anal_esil_inc_reg (op, data[0], ""+""); + break; + case 0xca: // dex + case 0x88: // dey + op->cycles = 2; + op->type = R_ANAL_OP_TYPE_STORE; + _6502_anal_esil_inc_reg (op, data[0], ""-""); + break; + case 0xc9: // cmp #$ff + case 0xc5: // cmp $ff + case 0xd5: // cmp $ff,x + case 0xcd: // cmp $ffff + case 0xdd: // cmp $ffff,x + case 0xd9: // cmp $ffff,y + case 0xc1: // cmp ($ff,x) + case 0xd1: // cmp ($ff),y + op->type = R_ANAL_OP_TYPE_CMP; + _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); + if (data[0] == 0xc9) // immediate mode + r_strbuf_setf (&op->esil, ""%s,a,=="", addrbuf); + else r_strbuf_setf (&op->esil, ""%s,[1],a,=="", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_BNZ); + r_strbuf_append (&op->esil, "",C,!,C,=""); + break; + case 0xe0: // cpx #$ff + case 0xe4: // cpx $ff + case 0xec: // cpx $ffff + op->type = R_ANAL_OP_TYPE_CMP; + _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0); + if (data[0] == 0xe0) // immediate mode + r_strbuf_setf (&op->esil, ""%s,x,=="", addrbuf); + else r_strbuf_setf (&op->esil, ""%s,[1],x,=="", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_BNZ); + r_strbuf_append (&op->esil, "",C,!,C,=""); + break; + case 0xc0: // cpy #$ff + case 0xc4: // cpy $ff + case 0xcc: // cpy $ffff + op->type = R_ANAL_OP_TYPE_CMP; + _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0); + if (data[0] == 0xc0) // immediate mode + r_strbuf_setf (&op->esil, ""%s,y,=="", addrbuf); + else r_strbuf_setf (&op->esil, ""%s,[1],y,=="", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_BNZ); + r_strbuf_append (&op->esil, "",C,!,C,=""); + break; + case 0x10: // bpl $ffff + case 0x30: // bmi $ffff + case 0x50: // bvc $ffff + case 0x70: // bvs $ffff + case 0x90: // bcc $ffff + case 0xb0: // bcs $ffff + case 0xd0: // bne $ffff + case 0xf0: // beq $ffff + op->cycles = 2; + op->failcycles = 3; + op->type = R_ANAL_OP_TYPE_CJMP; + if (data[1] <= 127) + op->jump = addr + data[1] + op->size; + else op->jump = addr - (256 - data[1]) + op->size; + op->fail = addr + op->size; + _6502_anal_esil_ccall (op, data[0]); + break; + case 0x20: // jsr $ffff + op->cycles = 6; + op->type = R_ANAL_OP_TYPE_CALL; + op->jump = data[1] | data[2] << 8; + op->stackop = R_ANAL_STACK_INC; + op->stackptr = 2; + r_strbuf_setf (&op->esil, ""1,pc,-,0xff,sp,+,=[2],0x%04x,pc,=,2,sp,-="", op->jump); + break; + case 0x4c: // jmp $ffff + op->cycles = 3; + op->type = R_ANAL_OP_TYPE_JMP; + op->jump = data[1] | data[2] << 8; + r_strbuf_setf (&op->esil, ""0x%04x,pc,="", op->jump); + break; + case 0x6c: // jmp ($ffff) + op->cycles = 5; + op->type = R_ANAL_OP_TYPE_UJMP; + r_strbuf_setf (&op->esil, ""0x%04x,[2],pc,="", data[1] | data[2] << 8); + break; + case 0x60: // rts + op->eob = true; + op->type = R_ANAL_OP_TYPE_RET; + op->cycles = 6; + op->stackop = R_ANAL_STACK_INC; + op->stackptr = -2; + r_strbuf_set (&op->esil, ""0x101,sp,+,[2],pc,=,pc,++=,2,sp,+=""); + break; + case 0x40: // rti + op->eob = true; + op->type = R_ANAL_OP_TYPE_RET; + op->cycles = 6; + op->stackop = R_ANAL_STACK_INC; + op->stackptr = -3; + r_strbuf_set (&op->esil, ""0x101,sp,+,[1],flags,=,0x102,sp,+,[2],pc,=,3,sp,+=""); + break; + case 0xea: // nop + op->type = R_ANAL_OP_TYPE_NOP; + op->cycles = 2; + break; + case 0xa9: // lda #$ff + case 0xa5: // lda $ff + case 0xb5: // lda $ff,x + case 0xad: // lda $ffff + case 0xbd: // lda $ffff,x + case 0xb9: // lda $ffff,y + case 0xa1: // lda ($ff,x) + case 0xb1: // lda ($ff),y + op->type = R_ANAL_OP_TYPE_LOAD; + _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); + if (data[0] == 0xa9) // immediate mode + r_strbuf_setf (&op->esil, ""%s,a,="", addrbuf); + else r_strbuf_setf (&op->esil, ""%s,[1],a,="", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0xa2: // ldx #$ff + case 0xa6: // ldx $ff + case 0xb6: // ldx $ff,y + case 0xae: // ldx $ffff + case 0xbe: // ldx $ffff,y + op->type = R_ANAL_OP_TYPE_LOAD; + _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y'); + if (data[0] == 0xa2) // immediate mode + r_strbuf_setf (&op->esil, ""%s,x,="", addrbuf); + else r_strbuf_setf (&op->esil, ""%s,[1],x,="", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0xa0: // ldy #$ff + case 0xa4: // ldy $ff + case 0xb4: // ldy $ff,x + case 0xac: // ldy $ffff + case 0xbc: // ldy $ffff,x + op->type = R_ANAL_OP_TYPE_LOAD; + _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x'); + if (data[0] == 0xa0) // immediate mode + r_strbuf_setf (&op->esil, ""%s,y,="", addrbuf); + else r_strbuf_setf (&op->esil, ""%s,[1],y,="", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0x85: // sta $ff + case 0x95: // sta $ff,x + case 0x8d: // sta $ffff + case 0x9d: // sta $ffff,x + case 0x99: // sta $ffff,y + case 0x81: // sta ($ff,x) + case 0x91: // sta ($ff),y + op->type = R_ANAL_OP_TYPE_STORE; + _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); + r_strbuf_setf (&op->esil, ""a,%s,=[1]"", addrbuf); + break; + case 0x86: // stx $ff + case 0x96: // stx $ff,y + case 0x8e: // stx $ffff + op->type = R_ANAL_OP_TYPE_STORE; + _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y'); + r_strbuf_setf (&op->esil, ""x,%s,=[1]"", addrbuf); + break; + case 0x84: // sty $ff + case 0x94: // sty $ff,x + case 0x8c: // sty $ffff + op->type = R_ANAL_OP_TYPE_STORE; + _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x'); + r_strbuf_setf (&op->esil, ""y,%s,=[1]"", addrbuf); + break; + case 0x08: // php + case 0x48: // pha + op->type = R_ANAL_OP_TYPE_PUSH; + op->cycles = 3; + op->stackop = R_ANAL_STACK_INC; + op->stackptr = 1; + _6502_anal_esil_push (op, data[0]); + break; + case 0x28: // plp + case 0x68: // plp + op->type = R_ANAL_OP_TYPE_POP; + op->cycles = 4; + op->stackop = R_ANAL_STACK_INC; + op->stackptr = -1; + _6502_anal_esil_pop (op, data[0]); + break; + case 0xaa: // tax + case 0x8a: // txa + case 0xa8: // tay + case 0x98: // tya + op->type = R_ANAL_OP_TYPE_MOV; + op->cycles = 2; + _6502_anal_esil_mov (op, data[0]); + break; + case 0x9a: // txs + op->type = R_ANAL_OP_TYPE_MOV; + op->cycles = 2; + op->stackop = R_ANAL_STACK_SET; + _6502_anal_esil_mov (op, data[0]); + break; + case 0xba: // tsx + op->type = R_ANAL_OP_TYPE_MOV; + op->cycles = 2; + op->stackop = R_ANAL_STACK_GET; + _6502_anal_esil_mov (op, data[0]); + break; + } + return op->size; +} +",1,"static int _6502_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int len) { + char addrbuf[64]; + const int buffsize = sizeof (addrbuf) - 1; + + memset (op, '\0', sizeof (RAnalOp)); + op->size = snes_op_get_size (1, 1, &snes_op[data[0]]); //snes-arch is similiar to nes/6502 + op->addr = addr; + op->type = R_ANAL_OP_TYPE_UNK; + op->id = data[0]; + r_strbuf_init (&op->esil); + switch (data[0]) { + case 0x02: + case 0x03: + case 0x04: + case 0x07: + case 0x0b: + case 0x0c: + case 0x0f: + case 0x12: + case 0x13: + case 0x14: + case 0x17: + case 0x1a: + case 0x1b: + case 0x1c: + case 0x1f: + case 0x22: + case 0x23: + case 0x27: + case 0x2b: + case 0x2f: + case 0x32: + case 0x33: + case 0x34: + case 0x37: + case 0x3a: + case 0x3b: + case 0x3c: + case 0x3f: + case 0x42: + case 0x43: + case 0x44: + case 0x47: + case 0x4b: + case 0x4f: + case 0x52: + case 0x53: + case 0x54: + case 0x57: + case 0x5a: + case 0x5b: + case 0x5c: + case 0x5f: + case 0x62: + case 0x63: + case 0x64: + case 0x67: + case 0x6b: + case 0x6f: + case 0x72: + case 0x73: + case 0x74: + case 0x77: + case 0x7a: + case 0x7b: + case 0x7c: + case 0x7f: + case 0x80: + case 0x82: + case 0x83: + case 0x87: + case 0x89: + case 0x8b: + case 0x8f: + case 0x92: + case 0x93: + case 0x97: + case 0x9b: + case 0x9c: + case 0x9e: + case 0x9f: + case 0xa3: + case 0xa7: + case 0xab: + case 0xaf: + case 0xb2: + case 0xb3: + case 0xb7: + case 0xbb: + case 0xbf: + case 0xc2: + case 0xc3: + case 0xc7: + case 0xcb: + case 0xcf: + case 0xd2: + case 0xd3: + case 0xd4: + case 0xd7: + case 0xda: + case 0xdb: + case 0xdc: + case 0xdf: + case 0xe2: + case 0xe3: + case 0xe7: + case 0xeb: + case 0xef: + case 0xf2: + case 0xf3: + case 0xf4: + case 0xf7: + case 0xfa: + case 0xfb: + case 0xfc: + case 0xff: + op->size = 1; + op->type = R_ANAL_OP_TYPE_ILL; + break; + + case 0x00: // brk + op->cycles = 7; + op->type = R_ANAL_OP_TYPE_SWI; + op->size = 1; + r_strbuf_set (&op->esil, "",1,I,=,0,D,=,flags,0x10,|,0x100,sp,+,=[1],pc,1,+,0xfe,sp,+,=[2],3,sp,-=,0xfffe,[2],pc,=""); + break; + + case 0x78: // sei + case 0x58: // cli + case 0x38: // sec + case 0x18: // clc + case 0xf8: // sed + case 0xd8: // cld + case 0xb8: // clv + op->cycles = 2; + op->type = R_ANAL_OP_TYPE_NOP; + _6502_anal_esil_flags (op, data[0]); + break; + case 0x24: // bit $ff + case 0x2c: // bit $ffff + op->type = R_ANAL_OP_TYPE_MOV; + _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0); + r_strbuf_setf (&op->esil, ""a,%s,[1],&,0x80,&,!,!,N,=,a,%s,[1],&,0x40,&,!,!,V,=,a,%s,[1],&,0xff,&,!,Z,="",addrbuf, addrbuf, addrbuf); + break; + case 0x69: // adc #$ff + case 0x65: // adc $ff + case 0x75: // adc $ff,x + case 0x6d: // adc $ffff + case 0x7d: // adc $ffff,x + case 0x79: // adc $ffff,y + case 0x61: // adc ($ff,x) + case 0x71: // adc ($ff,y) + op->type = R_ANAL_OP_TYPE_ADD; + _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); + if (data[0] == 0x69) // immediate mode + r_strbuf_setf (&op->esil, ""%s,a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|="", addrbuf); + else r_strbuf_setf (&op->esil, ""%s,[1],a,+=,C,NUM,$c7,C,=,a,+=,$c7,C,|="", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + r_strbuf_append (&op->esil, "",a,a,=,$z,Z,=""); + break; + case 0xe9: // sbc #$ff + case 0xe5: // sbc $ff + case 0xf5: // sbc $ff,x + case 0xed: // sbc $ffff + case 0xfd: // sbc $ffff,x + case 0xf9: // sbc $ffff,y + case 0xe1: // sbc ($ff,x) + case 0xf1: // sbc ($ff,y) + op->type = R_ANAL_OP_TYPE_SUB; + _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); + if (data[0] == 0xe9) // immediate mode + r_strbuf_setf (&op->esil, ""C,!,%s,+,a,-="", addrbuf); + else r_strbuf_setf (&op->esil, ""C,!,%s,[1],+,a,-="", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_BNZ); + r_strbuf_append (&op->esil, "",a,a,=,$z,Z,=,C,!=""); + break; + case 0x09: // ora #$ff + case 0x05: // ora $ff + case 0x15: // ora $ff,x + case 0x0d: // ora $ffff + case 0x1d: // ora $ffff,x + case 0x19: // ora $ffff,y + case 0x01: // ora ($ff,x) + case 0x11: // ora ($ff),y + op->type = R_ANAL_OP_TYPE_OR; + _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); + if (data[0] == 0x09) // immediate mode + r_strbuf_setf (&op->esil, ""%s,a,|="", addrbuf); + else r_strbuf_setf (&op->esil, ""%s,[1],a,|="", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0x29: // and #$ff + case 0x25: // and $ff + case 0x35: // and $ff,x + case 0x2d: // and $ffff + case 0x3d: // and $ffff,x + case 0x39: // and $ffff,y + case 0x21: // and ($ff,x) + case 0x31: // and ($ff),y + op->type = R_ANAL_OP_TYPE_AND; + _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); + if (data[0] == 0x29) // immediate mode + r_strbuf_setf (&op->esil, ""%s,a,&="", addrbuf); + else r_strbuf_setf (&op->esil, ""%s,[1],a,&="", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0x49: // eor #$ff + case 0x45: // eor $ff + case 0x55: // eor $ff,x + case 0x4d: // eor $ffff + case 0x5d: // eor $ffff,x + case 0x59: // eor $ffff,y + case 0x41: // eor ($ff,x) + case 0x51: // eor ($ff),y + op->type = R_ANAL_OP_TYPE_XOR; + _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); + if (data[0] == 0x49) // immediate mode + r_strbuf_setf (&op->esil, ""%s,a,^="", addrbuf); + else r_strbuf_setf (&op->esil, ""%s,[1],a,^="", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0x0a: // asl a + case 0x06: // asl $ff + case 0x16: // asl $ff,x + case 0x0e: // asl $ffff + case 0x1e: // asl $ffff,x + op->type = R_ANAL_OP_TYPE_SHL; + if (data[0] == 0x0a) { + r_strbuf_set (&op->esil, ""1,a,<<=,$c7,C,=,a,a,=""); + } else { + _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); + r_strbuf_setf (&op->esil, ""1,%s,[1],<<,%s,=[1],$c7,C,="", addrbuf, addrbuf); + } + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0x4a: // lsr a + case 0x46: // lsr $ff + case 0x56: // lsr $ff,x + case 0x4e: // lsr $ffff + case 0x5e: // lsr $ffff,x + op->type = R_ANAL_OP_TYPE_SHR; + if (data[0] == 0x4a) { + r_strbuf_set (&op->esil, ""1,a,&,C,=,1,a,>>=""); + } else { + _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); + r_strbuf_setf (&op->esil, ""1,%s,[1],&,C,=,1,%s,[1],>>,%s,=[1]"", addrbuf, addrbuf, addrbuf); + } + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0x2a: // rol a + case 0x26: // rol $ff + case 0x36: // rol $ff,x + case 0x2e: // rol $ffff + case 0x3e: // rol $ffff,x + op->type = R_ANAL_OP_TYPE_ROL; + if (data[0] == 0x2a) { + r_strbuf_set (&op->esil, ""1,a,<<,C,|,a,=,$c7,C,=,a,a,=""); + } else { + _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); + r_strbuf_setf (&op->esil, ""1,%s,[1],<<,C,|,%s,=[1],$c7,C,="", addrbuf, addrbuf); + } + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0x6a: // ror a + case 0x66: // ror $ff + case 0x76: // ror $ff,x + case 0x6e: // ror $ffff + case 0x7e: // ror $ffff,x + op->type = R_ANAL_OP_TYPE_ROR; + if (data[0] == 0x6a) { + r_strbuf_set (&op->esil, ""C,N,=,1,a,&,C,=,1,a,>>,7,N,<<,|,a,=""); + } else { + _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); + r_strbuf_setf (&op->esil, ""C,N,=,1,%s,[1],&,C,=,1,%s,[1],>>,7,N,<<,|,%s,=[1]"", addrbuf, addrbuf, addrbuf); + } + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0xe6: // inc $ff + case 0xf6: // inc $ff,x + case 0xee: // inc $ffff + case 0xfe: // inc $ffff,x + op->type = R_ANAL_OP_TYPE_STORE; + _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); + r_strbuf_setf (&op->esil, ""%s,++=[1]"", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0xc6: // dec $ff + case 0xd6: // dec $ff,x + case 0xce: // dec $ffff + case 0xde: // dec $ffff,x + op->type = R_ANAL_OP_TYPE_STORE; + _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'x'); + r_strbuf_setf (&op->esil, ""%s,--=[1]"", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0xe8: // inx + case 0xc8: // iny + op->cycles = 2; + op->type = R_ANAL_OP_TYPE_STORE; + _6502_anal_esil_inc_reg (op, data[0], ""+""); + break; + case 0xca: // dex + case 0x88: // dey + op->cycles = 2; + op->type = R_ANAL_OP_TYPE_STORE; + _6502_anal_esil_inc_reg (op, data[0], ""-""); + break; + case 0xc9: // cmp #$ff + case 0xc5: // cmp $ff + case 0xd5: // cmp $ff,x + case 0xcd: // cmp $ffff + case 0xdd: // cmp $ffff,x + case 0xd9: // cmp $ffff,y + case 0xc1: // cmp ($ff,x) + case 0xd1: // cmp ($ff),y + op->type = R_ANAL_OP_TYPE_CMP; + _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); + if (data[0] == 0xc9) // immediate mode + r_strbuf_setf (&op->esil, ""%s,a,=="", addrbuf); + else r_strbuf_setf (&op->esil, ""%s,[1],a,=="", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_BNZ); + r_strbuf_append (&op->esil, "",C,!,C,=""); + break; + case 0xe0: // cpx #$ff + case 0xe4: // cpx $ff + case 0xec: // cpx $ffff + op->type = R_ANAL_OP_TYPE_CMP; + _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0); + if (data[0] == 0xe0) // immediate mode + r_strbuf_setf (&op->esil, ""%s,x,=="", addrbuf); + else r_strbuf_setf (&op->esil, ""%s,[1],x,=="", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_BNZ); + r_strbuf_append (&op->esil, "",C,!,C,=""); + break; + case 0xc0: // cpy #$ff + case 0xc4: // cpy $ff + case 0xcc: // cpy $ffff + op->type = R_ANAL_OP_TYPE_CMP; + _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 0); + if (data[0] == 0xc0) // immediate mode + r_strbuf_setf (&op->esil, ""%s,y,=="", addrbuf); + else r_strbuf_setf (&op->esil, ""%s,[1],y,=="", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_BNZ); + r_strbuf_append (&op->esil, "",C,!,C,=""); + break; + case 0x10: // bpl $ffff + case 0x30: // bmi $ffff + case 0x50: // bvc $ffff + case 0x70: // bvs $ffff + case 0x90: // bcc $ffff + case 0xb0: // bcs $ffff + case 0xd0: // bne $ffff + case 0xf0: // beq $ffff + op->cycles = 2; + op->failcycles = 3; + op->type = R_ANAL_OP_TYPE_CJMP; + if (len > 1) { + if (data[1] <= 127) { + op->jump = addr + data[1] + op->size; + } else { + op->jump = addr - (256 - data[1]) + op->size; + } + } else { + op->jump = addr; + } + op->fail = addr + op->size; + _6502_anal_esil_ccall (op, data[0]); + break; + case 0x20: // jsr $ffff + op->cycles = 6; + op->type = R_ANAL_OP_TYPE_CALL; + op->jump = data[1] | data[2] << 8; + op->stackop = R_ANAL_STACK_INC; + op->stackptr = 2; + r_strbuf_setf (&op->esil, ""1,pc,-,0xff,sp,+,=[2],0x%04x,pc,=,2,sp,-="", op->jump); + break; + case 0x4c: // jmp $ffff + op->cycles = 3; + op->type = R_ANAL_OP_TYPE_JMP; + op->jump = data[1] | data[2] << 8; + r_strbuf_setf (&op->esil, ""0x%04x,pc,="", op->jump); + break; + case 0x6c: // jmp ($ffff) + op->cycles = 5; + op->type = R_ANAL_OP_TYPE_UJMP; + r_strbuf_setf (&op->esil, ""0x%04x,[2],pc,="", data[1] | data[2] << 8); + break; + case 0x60: // rts + op->eob = true; + op->type = R_ANAL_OP_TYPE_RET; + op->cycles = 6; + op->stackop = R_ANAL_STACK_INC; + op->stackptr = -2; + r_strbuf_set (&op->esil, ""0x101,sp,+,[2],pc,=,pc,++=,2,sp,+=""); + break; + case 0x40: // rti + op->eob = true; + op->type = R_ANAL_OP_TYPE_RET; + op->cycles = 6; + op->stackop = R_ANAL_STACK_INC; + op->stackptr = -3; + r_strbuf_set (&op->esil, ""0x101,sp,+,[1],flags,=,0x102,sp,+,[2],pc,=,3,sp,+=""); + break; + case 0xea: // nop + op->type = R_ANAL_OP_TYPE_NOP; + op->cycles = 2; + break; + case 0xa9: // lda #$ff + case 0xa5: // lda $ff + case 0xb5: // lda $ff,x + case 0xad: // lda $ffff + case 0xbd: // lda $ffff,x + case 0xb9: // lda $ffff,y + case 0xa1: // lda ($ff,x) + case 0xb1: // lda ($ff),y + op->type = R_ANAL_OP_TYPE_LOAD; + _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); + if (data[0] == 0xa9) // immediate mode + r_strbuf_setf (&op->esil, ""%s,a,="", addrbuf); + else r_strbuf_setf (&op->esil, ""%s,[1],a,="", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0xa2: // ldx #$ff + case 0xa6: // ldx $ff + case 0xb6: // ldx $ff,y + case 0xae: // ldx $ffff + case 0xbe: // ldx $ffff,y + op->type = R_ANAL_OP_TYPE_LOAD; + _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y'); + if (data[0] == 0xa2) // immediate mode + r_strbuf_setf (&op->esil, ""%s,x,="", addrbuf); + else r_strbuf_setf (&op->esil, ""%s,[1],x,="", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0xa0: // ldy #$ff + case 0xa4: // ldy $ff + case 0xb4: // ldy $ff,x + case 0xac: // ldy $ffff + case 0xbc: // ldy $ffff,x + op->type = R_ANAL_OP_TYPE_LOAD; + _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x'); + if (data[0] == 0xa0) // immediate mode + r_strbuf_setf (&op->esil, ""%s,y,="", addrbuf); + else r_strbuf_setf (&op->esil, ""%s,[1],y,="", addrbuf); + _6502_anal_update_flags (op, _6502_FLAGS_NZ); + break; + case 0x85: // sta $ff + case 0x95: // sta $ff,x + case 0x8d: // sta $ffff + case 0x9d: // sta $ffff,x + case 0x99: // sta $ffff,y + case 0x81: // sta ($ff,x) + case 0x91: // sta ($ff),y + op->type = R_ANAL_OP_TYPE_STORE; + _6502_anal_esil_get_addr_pattern1 (op, data, addrbuf, buffsize); + r_strbuf_setf (&op->esil, ""a,%s,=[1]"", addrbuf); + break; + case 0x86: // stx $ff + case 0x96: // stx $ff,y + case 0x8e: // stx $ffff + op->type = R_ANAL_OP_TYPE_STORE; + _6502_anal_esil_get_addr_pattern2 (op, data, addrbuf, buffsize, 'y'); + r_strbuf_setf (&op->esil, ""x,%s,=[1]"", addrbuf); + break; + case 0x84: // sty $ff + case 0x94: // sty $ff,x + case 0x8c: // sty $ffff + op->type = R_ANAL_OP_TYPE_STORE; + _6502_anal_esil_get_addr_pattern3 (op, data, addrbuf, buffsize, 'x'); + r_strbuf_setf (&op->esil, ""y,%s,=[1]"", addrbuf); + break; + case 0x08: // php + case 0x48: // pha + op->type = R_ANAL_OP_TYPE_PUSH; + op->cycles = 3; + op->stackop = R_ANAL_STACK_INC; + op->stackptr = 1; + _6502_anal_esil_push (op, data[0]); + break; + case 0x28: // plp + case 0x68: // plp + op->type = R_ANAL_OP_TYPE_POP; + op->cycles = 4; + op->stackop = R_ANAL_STACK_INC; + op->stackptr = -1; + _6502_anal_esil_pop (op, data[0]); + break; + case 0xaa: // tax + case 0x8a: // txa + case 0xa8: // tay + case 0x98: // tya + op->type = R_ANAL_OP_TYPE_MOV; + op->cycles = 2; + _6502_anal_esil_mov (op, data[0]); + break; + case 0x9a: // txs + op->type = R_ANAL_OP_TYPE_MOV; + op->cycles = 2; + op->stackop = R_ANAL_STACK_SET; + _6502_anal_esil_mov (op, data[0]); + break; + case 0xba: // tsx + op->type = R_ANAL_OP_TYPE_MOV; + op->cycles = 2; + op->stackop = R_ANAL_STACK_GET; + _6502_anal_esil_mov (op, data[0]); + break; + } + return op->size; +} +","@@ -682,9 +682,15 @@ static int _6502_op(RAnal *anal, RAnalOp *op, ut64 addr, const ut8 *data, int le + op->cycles = 2; + op->failcycles = 3; + op->type = R_ANAL_OP_TYPE_CJMP; +- if (data[1] <= 127) +- op->jump = addr + data[1] + op->size; +- else op->jump = addr - (256 - data[1]) + op->size; ++ if (len > 1) { ++ if (data[1] <= 127) { ++ op->jump = addr + data[1] + op->size; ++ } else { ++ op->jump = addr - (256 - data[1]) + op->size; ++ } ++ } else { ++ op->jump = addr; ++ } + op->fail = addr + op->size; + // FIXME: add a type of conditional + // op->cond = R_ANAL_COND_LE;",6444,6775,8192 +18344,"WandPrivate MagickBooleanType CLIListOperatorImages(MagickCLI *cli_wand, + const char *option,const char *arg1n,const char *arg2n) +{ + const char /* percent escaped versions of the args */ + *arg1, + *arg2; + + Image + *new_images; + + MagickStatusType + status; + + ssize_t + parse; + +#define _image_info (cli_wand->wand.image_info) +#define _images (cli_wand->wand.images) +#define _exception (cli_wand->wand.exception) +#define _draw_info (cli_wand->draw_info) +#define _quantize_info (cli_wand->quantize_info) +#define _process_flags (cli_wand->process_flags) +#define _option_type ((CommandOptionFlags) cli_wand->command->flags) +#define IfNormalOp (*option=='-') +#define IfPlusOp (*option!='-') +#define IsNormalOp IfNormalOp ? MagickTrue : MagickFalse + + assert(cli_wand != (MagickCLI *) NULL); + assert(cli_wand->signature == MagickWandSignature); + assert(cli_wand->wand.signature == MagickWandSignature); + assert(_images != (Image *) NULL); /* _images must be present */ + + if (cli_wand->wand.debug != MagickFalse) + (void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(), + ""- List Operator: %s \""%s\"" \""%s\"""", option, + arg1n == (const char *) NULL ? ""null"" : arg1n, + arg2n == (const char *) NULL ? ""null"" : arg2n); + + arg1 = arg1n; + arg2 = arg2n; + + /* Interpret Percent Escapes in Arguments - using first image */ + if ( (((_process_flags & ProcessInterpretProperities) != 0 ) + || ((_option_type & AlwaysInterpretArgsFlag) != 0) + ) && ((_option_type & NeverInterpretArgsFlag) == 0) ) { + /* Interpret Percent escapes in argument 1 */ + if (arg1n != (char *) NULL) { + arg1=InterpretImageProperties(_image_info,_images,arg1n,_exception); + if (arg1 == (char *) NULL) { + CLIWandException(OptionWarning,""InterpretPropertyFailure"",option); + arg1=arg1n; /* use the given argument as is */ + } + } + if (arg2n != (char *) NULL) { + arg2=InterpretImageProperties(_image_info,_images,arg2n,_exception); + if (arg2 == (char *) NULL) { + CLIWandException(OptionWarning,""InterpretPropertyFailure"",option); + arg2=arg2n; /* use the given argument as is */ + } + } + } +#undef _process_flags +#undef _option_type + + status=MagickTrue; + new_images=NewImageList(); + + switch (*(option+1)) + { + case 'a': + { + if (LocaleCompare(""append"",option+1) == 0) + { + new_images=AppendImages(_images,IsNormalOp,_exception); + break; + } + if (LocaleCompare(""average"",option+1) == 0) + { + CLIWandWarnReplaced(""-evaluate-sequence Mean""); + (void) CLIListOperatorImages(cli_wand,""-evaluate-sequence"",""Mean"", + NULL); + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + case 'c': + { + if (LocaleCompare(""channel-fx"",option+1) == 0) + { + new_images=ChannelFxImage(_images,arg1,_exception); + break; + } + if (LocaleCompare(""clut"",option+1) == 0) + { + Image + *clut_image; + + /* FUTURE - make this a compose option, and thus can be used + with layers compose or even compose last image over all other + _images. + */ + new_images=RemoveFirstImageFromList(&_images); + clut_image=RemoveLastImageFromList(&_images); + /* FUTURE - produce Exception, rather than silent fail */ + if (clut_image == (Image *) NULL) + break; + (void) ClutImage(new_images,clut_image,new_images->interpolate, + _exception); + clut_image=DestroyImage(clut_image); + break; + } + if (LocaleCompare(""coalesce"",option+1) == 0) + { + new_images=CoalesceImages(_images,_exception); + break; + } + if (LocaleCompare(""combine"",option+1) == 0) + { + parse=(ssize_t) _images->colorspace; + if (_images->number_channels < GetImageListLength(_images)) + parse=sRGBColorspace; + if ( IfPlusOp ) + parse=ParseCommandOption(MagickColorspaceOptions,MagickFalse,arg1); + if (parse < 0) + CLIWandExceptArgBreak(OptionError,""UnrecognizedColorspace"",option, + arg1); + new_images=CombineImages(_images,(ColorspaceType) parse,_exception); + break; + } + if (LocaleCompare(""compare"",option+1) == 0) + { + double + distortion; + + Image + *image, + *reconstruct_image; + + MetricType + metric; + + /* + Mathematically and visually annotate the difference between an + image and its reconstruction. + */ + image=RemoveFirstImageFromList(&_images); + reconstruct_image=RemoveFirstImageFromList(&_images); + /* FUTURE - produce Exception, rather than silent fail */ + if (reconstruct_image == (Image *) NULL) + { + image=DestroyImage(image); + break; + } + metric=UndefinedErrorMetric; + option=GetImageOption(_image_info,""metric""); + if (option != (const char *) NULL) + metric=(MetricType) ParseCommandOption(MagickMetricOptions, + MagickFalse,option); + new_images=CompareImages(image,reconstruct_image,metric,&distortion, + _exception); + (void) distortion; + reconstruct_image=DestroyImage(reconstruct_image); + image=DestroyImage(image); + break; + } + if (LocaleCompare(""complex"",option+1) == 0) + { + parse=ParseCommandOption(MagickComplexOptions,MagickFalse,arg1); + if (parse < 0) + CLIWandExceptArgBreak(OptionError,""UnrecognizedEvaluateOperator"", + option,arg1); + new_images=ComplexImages(_images,(ComplexOperator) parse,_exception); + break; + } + if (LocaleCompare(""composite"",option+1) == 0) + { + CompositeOperator + compose; + + const char* + value; + + MagickBooleanType + clip_to_self; + + Image + *mask_image, + *source_image; + + RectangleInfo + geometry; + + /* Compose value from ""-compose"" option only */ + value=GetImageOption(_image_info,""compose""); + if (value == (const char *) NULL) + compose=OverCompositeOp; /* use Over not source_image->compose */ + else + compose=(CompositeOperator) ParseCommandOption(MagickComposeOptions, + MagickFalse,value); + + /* Get ""clip-to-self"" expert setting (false is normal) */ + clip_to_self=GetCompositeClipToSelf(compose); + value=GetImageOption(_image_info,""compose:clip-to-self""); + if (value != (const char *) NULL) + clip_to_self=IsStringTrue(value); + value=GetImageOption(_image_info,""compose:outside-overlay""); + if (value != (const char *) NULL) + clip_to_self=IsStringFalse(value); /* deprecated */ + + new_images=RemoveFirstImageFromList(&_images); + source_image=RemoveFirstImageFromList(&_images); + if (source_image == (Image *) NULL) + break; /* FUTURE - produce Exception, rather than silent fail */ + + /* FUTURE - this should not be here! - should be part of -geometry */ + if (source_image->geometry != (char *) NULL) + { + RectangleInfo + resize_geometry; + + (void) ParseRegionGeometry(source_image,source_image->geometry, + &resize_geometry,_exception); + if ((source_image->columns != resize_geometry.width) || + (source_image->rows != resize_geometry.height)) + { + Image + *resize_image; + + resize_image=ResizeImage(source_image,resize_geometry.width, + resize_geometry.height,source_image->filter,_exception); + if (resize_image != (Image *) NULL) + { + source_image=DestroyImage(source_image); + source_image=resize_image; + } + } + } + SetGeometry(source_image,&geometry); + (void) ParseAbsoluteGeometry(source_image->geometry,&geometry); + GravityAdjustGeometry(new_images->columns,new_images->rows, + new_images->gravity, &geometry); + mask_image=RemoveFirstImageFromList(&_images); + if (mask_image == (Image *) NULL) + status&=CompositeImage(new_images,source_image,compose,clip_to_self, + geometry.x,geometry.y,_exception); + else + { + if ((compose == DisplaceCompositeOp) || + (compose == DistortCompositeOp)) + { + status&=CompositeImage(source_image,mask_image, + CopyGreenCompositeOp,MagickTrue,0,0,_exception); + status&=CompositeImage(new_images,source_image,compose, + clip_to_self,geometry.x,geometry.y,_exception); + } + else + { + Image + *clone_image; + + clone_image=CloneImage(new_images,0,0,MagickTrue,_exception); + if (clone_image == (Image *) NULL) + break; + status&=CompositeImage(new_images,source_image,compose, + clip_to_self,geometry.x,geometry.y,_exception); + status&=CompositeImage(new_images,mask_image, + CopyAlphaCompositeOp,MagickTrue,0,0,_exception); + status&=CompositeImage(clone_image,new_images,OverCompositeOp, + clip_to_self,0,0,_exception); + new_images=DestroyImageList(new_images); + new_images=clone_image; + } + mask_image=DestroyImage(mask_image); + } + source_image=DestroyImage(source_image); + break; + } + if (LocaleCompare(""copy"",option+1) == 0) + { + Image + *source_image; + + OffsetInfo + offset; + + RectangleInfo + geometry; + + /* + Copy image pixels. + */ + if (IsGeometry(arg1) == MagickFalse) + CLIWandExceptArgBreak(OptionError,""InvalidArgument"",option,arg1); + if (IsGeometry(arg2) == MagickFalse) + CLIWandExceptArgBreak(OptionError,""InvalidArgument"",option,arg1); + (void) ParsePageGeometry(_images,arg2,&geometry,_exception); + offset.x=geometry.x; + offset.y=geometry.y; + source_image=_images; + if (source_image->next != (Image *) NULL) + source_image=source_image->next; + (void) ParsePageGeometry(source_image,arg1,&geometry,_exception); + (void) CopyImagePixels(_images,source_image,&geometry,&offset, + _exception); + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + case 'd': + { + if (LocaleCompare(""deconstruct"",option+1) == 0) + { + CLIWandWarnReplaced(""-layer CompareAny""); + (void) CLIListOperatorImages(cli_wand,""-layer"",""CompareAny"",NULL); + break; + } + if (LocaleCompare(""delete"",option+1) == 0) + { + if (IfNormalOp) + DeleteImages(&_images,arg1,_exception); + else + DeleteImages(&_images,""-1"",_exception); + break; + } + if (LocaleCompare(""duplicate"",option+1) == 0) + { + if (IfNormalOp) + { + const char + *p; + + size_t + number_duplicates; + + if (IsGeometry(arg1) == MagickFalse) + CLIWandExceptArgBreak(OptionError,""InvalidArgument"",option, + arg1); + number_duplicates=(size_t) StringToLong(arg1); + p=strchr(arg1,','); + if (p == (const char *) NULL) + new_images=DuplicateImages(_images,number_duplicates,""-1"", + _exception); + else + new_images=DuplicateImages(_images,number_duplicates,p, + _exception); + } + else + new_images=DuplicateImages(_images,1,""-1"",_exception); + AppendImageToList(&_images, new_images); + new_images=(Image *) NULL; + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + case 'e': + { + if (LocaleCompare(""evaluate-sequence"",option+1) == 0) + { + parse=ParseCommandOption(MagickEvaluateOptions,MagickFalse,arg1); + if (parse < 0) + CLIWandExceptArgBreak(OptionError,""UnrecognizedEvaluateOperator"", + option,arg1); + new_images=EvaluateImages(_images,(MagickEvaluateOperator) parse, + _exception); + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + case 'f': + { + if (LocaleCompare(""fft"",option+1) == 0) + { + new_images=ForwardFourierTransformImage(_images,IsNormalOp, + _exception); + break; + } + if (LocaleCompare(""flatten"",option+1) == 0) + { + /* REDIRECTED to use -layers flatten instead */ + (void) CLIListOperatorImages(cli_wand,""-layers"",option+1,NULL); + break; + } + if (LocaleCompare(""fx"",option+1) == 0) + { + new_images=FxImage(_images,arg1,_exception); + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + case 'h': + { + if (LocaleCompare(""hald-clut"",option+1) == 0) + { + /* FUTURE - make this a compose option (and thus layers compose ) + or perhaps compose last image over all other _images. + */ + Image + *hald_image; + + new_images=RemoveFirstImageFromList(&_images); + hald_image=RemoveLastImageFromList(&_images); + if (hald_image == (Image *) NULL) + break; + (void) HaldClutImage(new_images,hald_image,_exception); + hald_image=DestroyImage(hald_image); + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + case 'i': + { + if (LocaleCompare(""ift"",option+1) == 0) + { + Image + *magnitude_image, + *phase_image; + + magnitude_image=RemoveFirstImageFromList(&_images); + phase_image=RemoveFirstImageFromList(&_images); + /* FUTURE - produce Exception, rather than silent fail */ + if (phase_image == (Image *) NULL) + break; + new_images=InverseFourierTransformImage(magnitude_image,phase_image, + IsNormalOp,_exception); + magnitude_image=DestroyImage(magnitude_image); + phase_image=DestroyImage(phase_image); + break; + } + if (LocaleCompare(""insert"",option+1) == 0) + { + Image + *insert_image, + *index_image; + + ssize_t + index; + + if (IfNormalOp && (IsGeometry(arg1) == MagickFalse)) + CLIWandExceptArgBreak(OptionError,""InvalidArgument"",option,arg1); + index=0; + insert_image=RemoveLastImageFromList(&_images); + if (IfNormalOp) + index=(ssize_t) StringToLong(arg1); + index_image=insert_image; + if (index == 0) + PrependImageToList(&_images,insert_image); + else if (index == (ssize_t) GetImageListLength(_images)) + AppendImageToList(&_images,insert_image); + else + { + index_image=GetImageFromList(_images,index-1); + if (index_image == (Image *) NULL) + { + insert_image=DestroyImage(insert_image); + CLIWandExceptArgBreak(OptionError,""NoSuchImage"",option,arg1); + } + InsertImageInList(&index_image,insert_image); + } + _images=GetFirstImageInList(index_image); + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + case 'l': + { + if (LocaleCompare(""layers"",option+1) == 0) + { + parse=ParseCommandOption(MagickLayerOptions,MagickFalse,arg1); + if ( parse < 0 ) + CLIWandExceptArgBreak(OptionError,""UnrecognizedLayerMethod"", + option,arg1); + switch ((LayerMethod) parse) + { + case CoalesceLayer: + { + new_images=CoalesceImages(_images,_exception); + break; + } + case CompareAnyLayer: + case CompareClearLayer: + case CompareOverlayLayer: + default: + { + new_images=CompareImagesLayers(_images,(LayerMethod) parse, + _exception); + break; + } + case MergeLayer: + case FlattenLayer: + case MosaicLayer: + case TrimBoundsLayer: + { + new_images=MergeImageLayers(_images,(LayerMethod) parse, + _exception); + break; + } + case DisposeLayer: + { + new_images=DisposeImages(_images,_exception); + break; + } + case OptimizeImageLayer: + { + new_images=OptimizeImageLayers(_images,_exception); + break; + } + case OptimizePlusLayer: + { + new_images=OptimizePlusImageLayers(_images,_exception); + break; + } + case OptimizeTransLayer: + { + OptimizeImageTransparency(_images,_exception); + break; + } + case RemoveDupsLayer: + { + RemoveDuplicateLayers(&_images,_exception); + break; + } + case RemoveZeroLayer: + { + RemoveZeroDelayLayers(&_images,_exception); + break; + } + case OptimizeLayer: + { /* General Purpose, GIF Animation Optimizer. */ + new_images=CoalesceImages(_images,_exception); + if (new_images == (Image *) NULL) + break; + _images=DestroyImageList(_images); + _images=OptimizeImageLayers(new_images,_exception); + if (_images == (Image *) NULL) + break; + new_images=DestroyImageList(new_images); + OptimizeImageTransparency(_images,_exception); + (void) RemapImages(_quantize_info,_images,(Image *) NULL, + _exception); + break; + } + case CompositeLayer: + { + Image + *source; + + RectangleInfo + geometry; + + CompositeOperator + compose; + + const char* + value; + + value=GetImageOption(_image_info,""compose""); + compose=OverCompositeOp; /* Default to Over */ + if (value != (const char *) NULL) + compose=(CompositeOperator) ParseCommandOption( + MagickComposeOptions,MagickFalse,value); + + /* Split image sequence at the first 'NULL:' image. */ + source=_images; + while (source != (Image *) NULL) + { + source=GetNextImageInList(source); + if ((source != (Image *) NULL) && + (LocaleCompare(source->magick,""NULL"") == 0)) + break; + } + if (source != (Image *) NULL) + { + if ((GetPreviousImageInList(source) == (Image *) NULL) || + (GetNextImageInList(source) == (Image *) NULL)) + source=(Image *) NULL; + else + { /* Separate the two lists, junk the null: image. */ + source=SplitImageList(source->previous); + DeleteImageFromList(&source); + } + } + if (source == (Image *) NULL) + { + (void) ThrowMagickException(_exception,GetMagickModule(), + OptionError,""MissingNullSeparator"",""layers Composite""); + break; + } + /* Adjust offset with gravity and virtual canvas. */ + SetGeometry(_images,&geometry); + (void) ParseAbsoluteGeometry(_images->geometry,&geometry); + geometry.width=source->page.width != 0 ? + source->page.width : source->columns; + geometry.height=source->page.height != 0 ? + source->page.height : source->rows; + GravityAdjustGeometry(_images->page.width != 0 ? + _images->page.width : _images->columns, + _images->page.height != 0 ? _images->page.height : + _images->rows,_images->gravity,&geometry); + + /* Compose the two image sequences together */ + CompositeLayers(_images,compose,source,geometry.x,geometry.y, + _exception); + source=DestroyImageList(source); + break; + } + } + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + case 'm': + { + if (LocaleCompare(""map"",option+1) == 0) + { + CLIWandWarnReplaced(""+remap""); + (void) RemapImages(_quantize_info,_images,(Image *) NULL,_exception); + break; + } + if (LocaleCompare(""metric"",option+1) == 0) + { + (void) SetImageOption(_image_info,option+1,arg1); + break; + } + if (LocaleCompare(""morph"",option+1) == 0) + { + Image + *morph_image; + + if (IsGeometry(arg1) == MagickFalse) + CLIWandExceptArgBreak(OptionError,""InvalidArgument"",option,arg1); + morph_image=MorphImages(_images,StringToUnsignedLong(arg1), + _exception); + if (morph_image == (Image *) NULL) + break; + _images=DestroyImageList(_images); + _images=morph_image; + break; + } + if (LocaleCompare(""mosaic"",option+1) == 0) + { + /* REDIRECTED to use -layers mosaic instead */ + (void) CLIListOperatorImages(cli_wand,""-layers"",option+1,NULL); + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + case 'p': + { + if (LocaleCompare(""poly"",option+1) == 0) + { + double + *args; + + ssize_t + count; + + /* convert argument string into an array of doubles */ + args = StringToArrayOfDoubles(arg1,&count,_exception); + if (args == (double *) NULL ) + CLIWandExceptArgBreak(OptionError,""InvalidNumberList"",option,arg1); + new_images=PolynomialImage(_images,(size_t) (count >> 1),args, + _exception); + args=(double *) RelinquishMagickMemory(args); + break; + } + if (LocaleCompare(""process"",option+1) == 0) + { + /* FUTURE: better parsing using ScriptToken() from string ??? */ + char + **arguments; + + int + j, + number_arguments; + + arguments=StringToArgv(arg1,&number_arguments); + if (arguments == (char **) NULL) + break; + if (strchr(arguments[1],'=') != (char *) NULL) + { + char + breaker, + quote, + *token; + + const char + *arguments; + + int + next, + status; + + size_t + length; + + TokenInfo + *token_info; + + /* + Support old style syntax, filter=""-option arg1"". + */ + assert(arg1 != (const char *) NULL); + length=strlen(arg1); + token=(char *) NULL; + if (~length >= (MagickPathExtent-1)) + token=(char *) AcquireQuantumMemory(length+MagickPathExtent, + sizeof(*token)); + if (token == (char *) NULL) + break; + next=0; + arguments=arg1; + token_info=AcquireTokenInfo(); + status=Tokenizer(token_info,0,token,length,arguments,"""",""="", + ""\"""",'\0',&breaker,&next,"e); + token_info=DestroyTokenInfo(token_info); + if (status == 0) + { + const char + *argv; + + argv=(&(arguments[next])); + (void) InvokeDynamicImageFilter(token,&_images,1,&argv, + _exception); + } + token=DestroyString(token); + break; + } + (void) SubstituteString(&arguments[1],""-"",""""); + (void) InvokeDynamicImageFilter(arguments[1],&_images, + number_arguments-2,(const char **) arguments+2,_exception); + for (j=0; j < number_arguments; j++) + arguments[j]=DestroyString(arguments[j]); + arguments=(char **) RelinquishMagickMemory(arguments); + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + case 'r': + { + if (LocaleCompare(""remap"",option+1) == 0) + { + (void) RemapImages(_quantize_info,_images,(Image *) NULL,_exception); + break; + } + if (LocaleCompare(""reverse"",option+1) == 0) + { + ReverseImageList(&_images); + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + case 's': + { + if (LocaleCompare(""smush"",option+1) == 0) + { + /* FUTURE: this option needs more work to make better */ + ssize_t + offset; + + if (IsGeometry(arg1) == MagickFalse) + CLIWandExceptArgBreak(OptionError,""InvalidArgument"",option,arg1); + offset=(ssize_t) StringToLong(arg1); + new_images=SmushImages(_images,IsNormalOp,offset,_exception); + break; + } + if (LocaleCompare(""subimage"",option+1) == 0) + { + Image + *base_image, + *compare_image; + + const char + *value; + + MetricType + metric; + + double + similarity; + + RectangleInfo + offset; + + base_image=GetImageFromList(_images,0); + compare_image=GetImageFromList(_images,1); + + /* Comparision Metric */ + metric=UndefinedErrorMetric; + value=GetImageOption(_image_info,""metric""); + if (value != (const char *) NULL) + metric=(MetricType) ParseCommandOption(MagickMetricOptions, + MagickFalse,value); + + new_images=SimilarityImage(base_image,compare_image,metric,0.0, + &offset,&similarity,_exception); + + if (new_images != (Image *) NULL) + { + char + result[MagickPathExtent]; + + (void) FormatLocaleString(result,MagickPathExtent,""%lf"", + similarity); + (void) SetImageProperty(new_images,""subimage:similarity"",result, + _exception); + (void) FormatLocaleString(result,MagickPathExtent,""%+ld"",(long) + offset.x); + (void) SetImageProperty(new_images,""subimage:x"",result, + _exception); + (void) FormatLocaleString(result,MagickPathExtent,""%+ld"",(long) + offset.y); + (void) SetImageProperty(new_images,""subimage:y"",result, + _exception); + (void) FormatLocaleString(result,MagickPathExtent, + ""%lux%lu%+ld%+ld"",(unsigned long) offset.width,(unsigned long) + offset.height,(long) offset.x,(long) offset.y); + (void) SetImageProperty(new_images,""subimage:offset"",result, + _exception); + } + break; + } + if (LocaleCompare(""swap"",option+1) == 0) + { + Image + *p, + *q, + *swap; + + ssize_t + index, + swap_index; + + index=(-1); + swap_index=(-2); + if (IfNormalOp) { + GeometryInfo + geometry_info; + + MagickStatusType + flags; + + swap_index=(-1); + flags=ParseGeometry(arg1,&geometry_info); + if ((flags & RhoValue) == 0) + CLIWandExceptArgBreak(OptionError,""InvalidArgument"",option,arg1); + index=(ssize_t) geometry_info.rho; + if ((flags & SigmaValue) != 0) + swap_index=(ssize_t) geometry_info.sigma; + } + p=GetImageFromList(_images,index); + q=GetImageFromList(_images,swap_index); + if ((p == (Image *) NULL) || (q == (Image *) NULL)) { + if (IfNormalOp) + CLIWandExceptArgBreak(OptionError,""InvalidImageIndex"",option,arg1) + else + CLIWandExceptionBreak(OptionError,""TwoOrMoreImagesRequired"",option); + } + if (p == q) + CLIWandExceptArgBreak(OptionError,""InvalidImageIndex"",option,arg1); + swap=CloneImage(p,0,0,MagickTrue,_exception); + if (swap == (Image *) NULL) + CLIWandExceptArgBreak(ResourceLimitError,""MemoryAllocationFailed"", + option,GetExceptionMessage(errno)); + ReplaceImageInList(&p,CloneImage(q,0,0,MagickTrue,_exception)); + ReplaceImageInList(&q,swap); + _images=GetFirstImageInList(q); + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + default: + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + + /* clean up percent escape interpreted strings */ + if (arg1 != arg1n ) + arg1=DestroyString((char *)arg1); + if (arg2 != arg2n ) + arg2=DestroyString((char *)arg2); + + /* if new image list generated, replace existing image list */ + if (new_images == (Image *) NULL) + return(status == 0 ? MagickFalse : MagickTrue); + _images=DestroyImageList(_images); + _images=GetFirstImageInList(new_images); + return(status == 0 ? MagickFalse : MagickTrue); + +#undef _image_info +#undef _images +#undef _exception +#undef _draw_info +#undef _quantize_info +#undef IfNormalOp +#undef IfPlusOp +#undef IsNormalOp +} +",1,"WandPrivate MagickBooleanType CLIListOperatorImages(MagickCLI *cli_wand, + const char *option,const char *arg1n,const char *arg2n) +{ + const char /* percent escaped versions of the args */ + *arg1, + *arg2; + + Image + *new_images; + + MagickStatusType + status; + + ssize_t + parse; + +#define _image_info (cli_wand->wand.image_info) +#define _images (cli_wand->wand.images) +#define _exception (cli_wand->wand.exception) +#define _draw_info (cli_wand->draw_info) +#define _quantize_info (cli_wand->quantize_info) +#define _process_flags (cli_wand->process_flags) +#define _option_type ((CommandOptionFlags) cli_wand->command->flags) +#define IfNormalOp (*option=='-') +#define IfPlusOp (*option!='-') +#define IsNormalOp IfNormalOp ? MagickTrue : MagickFalse + + assert(cli_wand != (MagickCLI *) NULL); + assert(cli_wand->signature == MagickWandSignature); + assert(cli_wand->wand.signature == MagickWandSignature); + assert(_images != (Image *) NULL); /* _images must be present */ + + if (cli_wand->wand.debug != MagickFalse) + (void) CLILogEvent(cli_wand,CommandEvent,GetMagickModule(), + ""- List Operator: %s \""%s\"" \""%s\"""", option, + arg1n == (const char *) NULL ? ""null"" : arg1n, + arg2n == (const char *) NULL ? ""null"" : arg2n); + + arg1 = arg1n; + arg2 = arg2n; + + /* Interpret Percent Escapes in Arguments - using first image */ + if ( (((_process_flags & ProcessInterpretProperities) != 0 ) + || ((_option_type & AlwaysInterpretArgsFlag) != 0) + ) && ((_option_type & NeverInterpretArgsFlag) == 0) ) { + /* Interpret Percent escapes in argument 1 */ + if (arg1n != (char *) NULL) { + arg1=InterpretImageProperties(_image_info,_images,arg1n,_exception); + if (arg1 == (char *) NULL) { + CLIWandException(OptionWarning,""InterpretPropertyFailure"",option); + arg1=arg1n; /* use the given argument as is */ + } + } + if (arg2n != (char *) NULL) { + arg2=InterpretImageProperties(_image_info,_images,arg2n,_exception); + if (arg2 == (char *) NULL) { + CLIWandException(OptionWarning,""InterpretPropertyFailure"",option); + arg2=arg2n; /* use the given argument as is */ + } + } + } +#undef _process_flags +#undef _option_type + + status=MagickTrue; + new_images=NewImageList(); + + switch (*(option+1)) + { + case 'a': + { + if (LocaleCompare(""append"",option+1) == 0) + { + new_images=AppendImages(_images,IsNormalOp,_exception); + break; + } + if (LocaleCompare(""average"",option+1) == 0) + { + CLIWandWarnReplaced(""-evaluate-sequence Mean""); + (void) CLIListOperatorImages(cli_wand,""-evaluate-sequence"",""Mean"", + NULL); + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + case 'c': + { + if (LocaleCompare(""channel-fx"",option+1) == 0) + { + new_images=ChannelFxImage(_images,arg1,_exception); + break; + } + if (LocaleCompare(""clut"",option+1) == 0) + { + Image + *clut_image; + + /* FUTURE - make this a compose option, and thus can be used + with layers compose or even compose last image over all other + _images. + */ + new_images=RemoveFirstImageFromList(&_images); + clut_image=RemoveFirstImageFromList(&_images); + /* FUTURE - produce Exception, rather than silent fail */ + if (clut_image == (Image *) NULL) + { + (void) ThrowMagickException(_exception,GetMagickModule(), + OptionError,""ImageSequenceRequired"",""`%s'"",option); + new_images=DestroyImage(new_images); + status=MagickFalse; + break; + } + (void) ClutImage(new_images,clut_image,new_images->interpolate, + _exception); + clut_image=DestroyImage(clut_image); + break; + } + if (LocaleCompare(""coalesce"",option+1) == 0) + { + new_images=CoalesceImages(_images,_exception); + break; + } + if (LocaleCompare(""combine"",option+1) == 0) + { + parse=(ssize_t) _images->colorspace; + if (_images->number_channels < GetImageListLength(_images)) + parse=sRGBColorspace; + if ( IfPlusOp ) + parse=ParseCommandOption(MagickColorspaceOptions,MagickFalse,arg1); + if (parse < 0) + CLIWandExceptArgBreak(OptionError,""UnrecognizedColorspace"",option, + arg1); + new_images=CombineImages(_images,(ColorspaceType) parse,_exception); + break; + } + if (LocaleCompare(""compare"",option+1) == 0) + { + double + distortion; + + Image + *image, + *reconstruct_image; + + MetricType + metric; + + /* + Mathematically and visually annotate the difference between an + image and its reconstruction. + */ + image=RemoveFirstImageFromList(&_images); + reconstruct_image=RemoveFirstImageFromList(&_images); + /* FUTURE - produce Exception, rather than silent fail */ + if (reconstruct_image == (Image *) NULL) + { + (void) ThrowMagickException(_exception,GetMagickModule(), + OptionError,""ImageSequenceRequired"",""`%s'"",option); + image=DestroyImage(image); + status=MagickFalse; + break; + } + metric=UndefinedErrorMetric; + option=GetImageOption(_image_info,""metric""); + if (option != (const char *) NULL) + metric=(MetricType) ParseCommandOption(MagickMetricOptions, + MagickFalse,option); + new_images=CompareImages(image,reconstruct_image,metric,&distortion, + _exception); + (void) distortion; + reconstruct_image=DestroyImage(reconstruct_image); + image=DestroyImage(image); + break; + } + if (LocaleCompare(""complex"",option+1) == 0) + { + parse=ParseCommandOption(MagickComplexOptions,MagickFalse,arg1); + if (parse < 0) + CLIWandExceptArgBreak(OptionError,""UnrecognizedEvaluateOperator"", + option,arg1); + new_images=ComplexImages(_images,(ComplexOperator) parse,_exception); + break; + } + if (LocaleCompare(""composite"",option+1) == 0) + { + CompositeOperator + compose; + + const char* + value; + + MagickBooleanType + clip_to_self; + + Image + *mask_image, + *source_image; + + RectangleInfo + geometry; + + /* Compose value from ""-compose"" option only */ + value=GetImageOption(_image_info,""compose""); + if (value == (const char *) NULL) + compose=OverCompositeOp; /* use Over not source_image->compose */ + else + compose=(CompositeOperator) ParseCommandOption(MagickComposeOptions, + MagickFalse,value); + + /* Get ""clip-to-self"" expert setting (false is normal) */ + clip_to_self=GetCompositeClipToSelf(compose); + value=GetImageOption(_image_info,""compose:clip-to-self""); + if (value != (const char *) NULL) + clip_to_self=IsStringTrue(value); + value=GetImageOption(_image_info,""compose:outside-overlay""); + if (value != (const char *) NULL) + clip_to_self=IsStringFalse(value); /* deprecated */ + + new_images=RemoveFirstImageFromList(&_images); + source_image=RemoveFirstImageFromList(&_images); + if (source_image == (Image *) NULL) + { + (void) ThrowMagickException(_exception,GetMagickModule(), + OptionError,""ImageSequenceRequired"",""`%s'"",option); + new_images=DestroyImage(new_images); + status=MagickFalse; + break; + } + + /* FUTURE - this should not be here! - should be part of -geometry */ + if (source_image->geometry != (char *) NULL) + { + RectangleInfo + resize_geometry; + + (void) ParseRegionGeometry(source_image,source_image->geometry, + &resize_geometry,_exception); + if ((source_image->columns != resize_geometry.width) || + (source_image->rows != resize_geometry.height)) + { + Image + *resize_image; + + resize_image=ResizeImage(source_image,resize_geometry.width, + resize_geometry.height,source_image->filter,_exception); + if (resize_image != (Image *) NULL) + { + source_image=DestroyImage(source_image); + source_image=resize_image; + } + } + } + SetGeometry(source_image,&geometry); + (void) ParseAbsoluteGeometry(source_image->geometry,&geometry); + GravityAdjustGeometry(new_images->columns,new_images->rows, + new_images->gravity, &geometry); + mask_image=RemoveFirstImageFromList(&_images); + if (mask_image == (Image *) NULL) + status&=CompositeImage(new_images,source_image,compose,clip_to_self, + geometry.x,geometry.y,_exception); + else + { + if ((compose == DisplaceCompositeOp) || + (compose == DistortCompositeOp)) + { + status&=CompositeImage(source_image,mask_image, + CopyGreenCompositeOp,MagickTrue,0,0,_exception); + status&=CompositeImage(new_images,source_image,compose, + clip_to_self,geometry.x,geometry.y,_exception); + } + else + { + Image + *clone_image; + + clone_image=CloneImage(new_images,0,0,MagickTrue,_exception); + if (clone_image == (Image *) NULL) + break; + status&=CompositeImage(new_images,source_image,compose, + clip_to_self,geometry.x,geometry.y,_exception); + status&=CompositeImage(new_images,mask_image, + CopyAlphaCompositeOp,MagickTrue,0,0,_exception); + status&=CompositeImage(clone_image,new_images,OverCompositeOp, + clip_to_self,0,0,_exception); + new_images=DestroyImageList(new_images); + new_images=clone_image; + } + mask_image=DestroyImage(mask_image); + } + source_image=DestroyImage(source_image); + break; + } + if (LocaleCompare(""copy"",option+1) == 0) + { + Image + *source_image; + + OffsetInfo + offset; + + RectangleInfo + geometry; + + /* + Copy image pixels. + */ + if (IsGeometry(arg1) == MagickFalse) + CLIWandExceptArgBreak(OptionError,""InvalidArgument"",option,arg1); + if (IsGeometry(arg2) == MagickFalse) + CLIWandExceptArgBreak(OptionError,""InvalidArgument"",option,arg1); + (void) ParsePageGeometry(_images,arg2,&geometry,_exception); + offset.x=geometry.x; + offset.y=geometry.y; + source_image=_images; + if (source_image->next != (Image *) NULL) + source_image=source_image->next; + (void) ParsePageGeometry(source_image,arg1,&geometry,_exception); + (void) CopyImagePixels(_images,source_image,&geometry,&offset, + _exception); + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + case 'd': + { + if (LocaleCompare(""deconstruct"",option+1) == 0) + { + CLIWandWarnReplaced(""-layer CompareAny""); + (void) CLIListOperatorImages(cli_wand,""-layer"",""CompareAny"",NULL); + break; + } + if (LocaleCompare(""delete"",option+1) == 0) + { + if (IfNormalOp) + DeleteImages(&_images,arg1,_exception); + else + DeleteImages(&_images,""-1"",_exception); + break; + } + if (LocaleCompare(""duplicate"",option+1) == 0) + { + if (IfNormalOp) + { + const char + *p; + + size_t + number_duplicates; + + if (IsGeometry(arg1) == MagickFalse) + CLIWandExceptArgBreak(OptionError,""InvalidArgument"",option, + arg1); + number_duplicates=(size_t) StringToLong(arg1); + p=strchr(arg1,','); + if (p == (const char *) NULL) + new_images=DuplicateImages(_images,number_duplicates,""-1"", + _exception); + else + new_images=DuplicateImages(_images,number_duplicates,p, + _exception); + } + else + new_images=DuplicateImages(_images,1,""-1"",_exception); + AppendImageToList(&_images, new_images); + new_images=(Image *) NULL; + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + case 'e': + { + if (LocaleCompare(""evaluate-sequence"",option+1) == 0) + { + parse=ParseCommandOption(MagickEvaluateOptions,MagickFalse,arg1); + if (parse < 0) + CLIWandExceptArgBreak(OptionError,""UnrecognizedEvaluateOperator"", + option,arg1); + new_images=EvaluateImages(_images,(MagickEvaluateOperator) parse, + _exception); + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + case 'f': + { + if (LocaleCompare(""fft"",option+1) == 0) + { + new_images=ForwardFourierTransformImage(_images,IsNormalOp, + _exception); + break; + } + if (LocaleCompare(""flatten"",option+1) == 0) + { + /* REDIRECTED to use -layers flatten instead */ + (void) CLIListOperatorImages(cli_wand,""-layers"",option+1,NULL); + break; + } + if (LocaleCompare(""fx"",option+1) == 0) + { + new_images=FxImage(_images,arg1,_exception); + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + case 'h': + { + if (LocaleCompare(""hald-clut"",option+1) == 0) + { + /* FUTURE - make this a compose option (and thus layers compose ) + or perhaps compose last image over all other _images. + */ + Image + *hald_image; + + new_images=RemoveFirstImageFromList(&_images); + hald_image=RemoveLastImageFromList(&_images); + if (hald_image == (Image *) NULL) + { + (void) ThrowMagickException(_exception,GetMagickModule(), + OptionError,""ImageSequenceRequired"",""`%s'"",option); + new_images=DestroyImage(new_images); + status=MagickFalse; + break; + } + (void) HaldClutImage(new_images,hald_image,_exception); + hald_image=DestroyImage(hald_image); + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + case 'i': + { + if (LocaleCompare(""ift"",option+1) == 0) + { + Image + *magnitude_image, + *phase_image; + + magnitude_image=RemoveFirstImageFromList(&_images); + phase_image=RemoveFirstImageFromList(&_images); + if (phase_image == (Image *) NULL) + { + (void) ThrowMagickException(_exception,GetMagickModule(), + OptionError,""ImageSequenceRequired"",""`%s'"",option); + magnitude_image=DestroyImage(magnitude_image); + status=MagickFalse; + break; + } + new_images=InverseFourierTransformImage(magnitude_image,phase_image, + IsNormalOp,_exception); + magnitude_image=DestroyImage(magnitude_image); + phase_image=DestroyImage(phase_image); + break; + } + if (LocaleCompare(""insert"",option+1) == 0) + { + Image + *insert_image, + *index_image; + + ssize_t + index; + + if (IfNormalOp && (IsGeometry(arg1) == MagickFalse)) + CLIWandExceptArgBreak(OptionError,""InvalidArgument"",option,arg1); + index=0; + insert_image=RemoveLastImageFromList(&_images); + if (IfNormalOp) + index=(ssize_t) StringToLong(arg1); + index_image=insert_image; + if (index == 0) + PrependImageToList(&_images,insert_image); + else if (index == (ssize_t) GetImageListLength(_images)) + AppendImageToList(&_images,insert_image); + else + { + index_image=GetImageFromList(_images,index-1); + if (index_image == (Image *) NULL) + { + insert_image=DestroyImage(insert_image); + CLIWandExceptArgBreak(OptionError,""NoSuchImage"",option,arg1); + } + InsertImageInList(&index_image,insert_image); + } + _images=GetFirstImageInList(index_image); + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + case 'l': + { + if (LocaleCompare(""layers"",option+1) == 0) + { + parse=ParseCommandOption(MagickLayerOptions,MagickFalse,arg1); + if ( parse < 0 ) + CLIWandExceptArgBreak(OptionError,""UnrecognizedLayerMethod"", + option,arg1); + switch ((LayerMethod) parse) + { + case CoalesceLayer: + { + new_images=CoalesceImages(_images,_exception); + break; + } + case CompareAnyLayer: + case CompareClearLayer: + case CompareOverlayLayer: + default: + { + new_images=CompareImagesLayers(_images,(LayerMethod) parse, + _exception); + break; + } + case MergeLayer: + case FlattenLayer: + case MosaicLayer: + case TrimBoundsLayer: + { + new_images=MergeImageLayers(_images,(LayerMethod) parse, + _exception); + break; + } + case DisposeLayer: + { + new_images=DisposeImages(_images,_exception); + break; + } + case OptimizeImageLayer: + { + new_images=OptimizeImageLayers(_images,_exception); + break; + } + case OptimizePlusLayer: + { + new_images=OptimizePlusImageLayers(_images,_exception); + break; + } + case OptimizeTransLayer: + { + OptimizeImageTransparency(_images,_exception); + break; + } + case RemoveDupsLayer: + { + RemoveDuplicateLayers(&_images,_exception); + break; + } + case RemoveZeroLayer: + { + RemoveZeroDelayLayers(&_images,_exception); + break; + } + case OptimizeLayer: + { /* General Purpose, GIF Animation Optimizer. */ + new_images=CoalesceImages(_images,_exception); + if (new_images == (Image *) NULL) + break; + _images=DestroyImageList(_images); + _images=OptimizeImageLayers(new_images,_exception); + if (_images == (Image *) NULL) + break; + new_images=DestroyImageList(new_images); + OptimizeImageTransparency(_images,_exception); + (void) RemapImages(_quantize_info,_images,(Image *) NULL, + _exception); + break; + } + case CompositeLayer: + { + Image + *source; + + RectangleInfo + geometry; + + CompositeOperator + compose; + + const char* + value; + + value=GetImageOption(_image_info,""compose""); + compose=OverCompositeOp; /* Default to Over */ + if (value != (const char *) NULL) + compose=(CompositeOperator) ParseCommandOption( + MagickComposeOptions,MagickFalse,value); + + /* Split image sequence at the first 'NULL:' image. */ + source=_images; + while (source != (Image *) NULL) + { + source=GetNextImageInList(source); + if ((source != (Image *) NULL) && + (LocaleCompare(source->magick,""NULL"") == 0)) + break; + } + if (source != (Image *) NULL) + { + if ((GetPreviousImageInList(source) == (Image *) NULL) || + (GetNextImageInList(source) == (Image *) NULL)) + source=(Image *) NULL; + else + { /* Separate the two lists, junk the null: image. */ + source=SplitImageList(source->previous); + DeleteImageFromList(&source); + } + } + if (source == (Image *) NULL) + { + (void) ThrowMagickException(_exception,GetMagickModule(), + OptionError,""MissingNullSeparator"",""layers Composite""); + break; + } + /* Adjust offset with gravity and virtual canvas. */ + SetGeometry(_images,&geometry); + (void) ParseAbsoluteGeometry(_images->geometry,&geometry); + geometry.width=source->page.width != 0 ? + source->page.width : source->columns; + geometry.height=source->page.height != 0 ? + source->page.height : source->rows; + GravityAdjustGeometry(_images->page.width != 0 ? + _images->page.width : _images->columns, + _images->page.height != 0 ? _images->page.height : + _images->rows,_images->gravity,&geometry); + + /* Compose the two image sequences together */ + CompositeLayers(_images,compose,source,geometry.x,geometry.y, + _exception); + source=DestroyImageList(source); + break; + } + } + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + case 'm': + { + if (LocaleCompare(""map"",option+1) == 0) + { + CLIWandWarnReplaced(""+remap""); + (void) RemapImages(_quantize_info,_images,(Image *) NULL,_exception); + break; + } + if (LocaleCompare(""metric"",option+1) == 0) + { + (void) SetImageOption(_image_info,option+1,arg1); + break; + } + if (LocaleCompare(""morph"",option+1) == 0) + { + Image + *morph_image; + + if (IsGeometry(arg1) == MagickFalse) + CLIWandExceptArgBreak(OptionError,""InvalidArgument"",option,arg1); + morph_image=MorphImages(_images,StringToUnsignedLong(arg1), + _exception); + if (morph_image == (Image *) NULL) + break; + _images=DestroyImageList(_images); + _images=morph_image; + break; + } + if (LocaleCompare(""mosaic"",option+1) == 0) + { + /* REDIRECTED to use -layers mosaic instead */ + (void) CLIListOperatorImages(cli_wand,""-layers"",option+1,NULL); + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + case 'p': + { + if (LocaleCompare(""poly"",option+1) == 0) + { + double + *args; + + ssize_t + count; + + /* convert argument string into an array of doubles */ + args = StringToArrayOfDoubles(arg1,&count,_exception); + if (args == (double *) NULL ) + CLIWandExceptArgBreak(OptionError,""InvalidNumberList"",option,arg1); + new_images=PolynomialImage(_images,(size_t) (count >> 1),args, + _exception); + args=(double *) RelinquishMagickMemory(args); + break; + } + if (LocaleCompare(""process"",option+1) == 0) + { + /* FUTURE: better parsing using ScriptToken() from string ??? */ + char + **arguments; + + int + j, + number_arguments; + + arguments=StringToArgv(arg1,&number_arguments); + if (arguments == (char **) NULL) + break; + if (strchr(arguments[1],'=') != (char *) NULL) + { + char + breaker, + quote, + *token; + + const char + *arguments; + + int + next, + status; + + size_t + length; + + TokenInfo + *token_info; + + /* + Support old style syntax, filter=""-option arg1"". + */ + assert(arg1 != (const char *) NULL); + length=strlen(arg1); + token=(char *) NULL; + if (~length >= (MagickPathExtent-1)) + token=(char *) AcquireQuantumMemory(length+MagickPathExtent, + sizeof(*token)); + if (token == (char *) NULL) + break; + next=0; + arguments=arg1; + token_info=AcquireTokenInfo(); + status=Tokenizer(token_info,0,token,length,arguments,"""",""="", + ""\"""",'\0',&breaker,&next,"e); + token_info=DestroyTokenInfo(token_info); + if (status == 0) + { + const char + *argv; + + argv=(&(arguments[next])); + (void) InvokeDynamicImageFilter(token,&_images,1,&argv, + _exception); + } + token=DestroyString(token); + break; + } + (void) SubstituteString(&arguments[1],""-"",""""); + (void) InvokeDynamicImageFilter(arguments[1],&_images, + number_arguments-2,(const char **) arguments+2,_exception); + for (j=0; j < number_arguments; j++) + arguments[j]=DestroyString(arguments[j]); + arguments=(char **) RelinquishMagickMemory(arguments); + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + case 'r': + { + if (LocaleCompare(""remap"",option+1) == 0) + { + (void) RemapImages(_quantize_info,_images,(Image *) NULL,_exception); + break; + } + if (LocaleCompare(""reverse"",option+1) == 0) + { + ReverseImageList(&_images); + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + case 's': + { + if (LocaleCompare(""smush"",option+1) == 0) + { + /* FUTURE: this option needs more work to make better */ + ssize_t + offset; + + if (IsGeometry(arg1) == MagickFalse) + CLIWandExceptArgBreak(OptionError,""InvalidArgument"",option,arg1); + offset=(ssize_t) StringToLong(arg1); + new_images=SmushImages(_images,IsNormalOp,offset,_exception); + break; + } + if (LocaleCompare(""subimage"",option+1) == 0) + { + Image + *base_image, + *compare_image; + + const char + *value; + + MetricType + metric; + + double + similarity; + + RectangleInfo + offset; + + base_image=GetImageFromList(_images,0); + compare_image=GetImageFromList(_images,1); + + /* Comparision Metric */ + metric=UndefinedErrorMetric; + value=GetImageOption(_image_info,""metric""); + if (value != (const char *) NULL) + metric=(MetricType) ParseCommandOption(MagickMetricOptions, + MagickFalse,value); + + new_images=SimilarityImage(base_image,compare_image,metric,0.0, + &offset,&similarity,_exception); + + if (new_images != (Image *) NULL) + { + char + result[MagickPathExtent]; + + (void) FormatLocaleString(result,MagickPathExtent,""%lf"", + similarity); + (void) SetImageProperty(new_images,""subimage:similarity"",result, + _exception); + (void) FormatLocaleString(result,MagickPathExtent,""%+ld"",(long) + offset.x); + (void) SetImageProperty(new_images,""subimage:x"",result, + _exception); + (void) FormatLocaleString(result,MagickPathExtent,""%+ld"",(long) + offset.y); + (void) SetImageProperty(new_images,""subimage:y"",result, + _exception); + (void) FormatLocaleString(result,MagickPathExtent, + ""%lux%lu%+ld%+ld"",(unsigned long) offset.width,(unsigned long) + offset.height,(long) offset.x,(long) offset.y); + (void) SetImageProperty(new_images,""subimage:offset"",result, + _exception); + } + break; + } + if (LocaleCompare(""swap"",option+1) == 0) + { + Image + *p, + *q, + *swap; + + ssize_t + index, + swap_index; + + index=(-1); + swap_index=(-2); + if (IfNormalOp) { + GeometryInfo + geometry_info; + + MagickStatusType + flags; + + swap_index=(-1); + flags=ParseGeometry(arg1,&geometry_info); + if ((flags & RhoValue) == 0) + CLIWandExceptArgBreak(OptionError,""InvalidArgument"",option,arg1); + index=(ssize_t) geometry_info.rho; + if ((flags & SigmaValue) != 0) + swap_index=(ssize_t) geometry_info.sigma; + } + p=GetImageFromList(_images,index); + q=GetImageFromList(_images,swap_index); + if ((p == (Image *) NULL) || (q == (Image *) NULL)) { + if (IfNormalOp) + CLIWandExceptArgBreak(OptionError,""InvalidImageIndex"",option,arg1) + else + CLIWandExceptionBreak(OptionError,""TwoOrMoreImagesRequired"",option); + } + if (p == q) + CLIWandExceptArgBreak(OptionError,""InvalidImageIndex"",option,arg1); + swap=CloneImage(p,0,0,MagickTrue,_exception); + if (swap == (Image *) NULL) + CLIWandExceptArgBreak(ResourceLimitError,""MemoryAllocationFailed"", + option,GetExceptionMessage(errno)); + ReplaceImageInList(&p,CloneImage(q,0,0,MagickTrue,_exception)); + ReplaceImageInList(&q,swap); + _images=GetFirstImageInList(q); + break; + } + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + default: + CLIWandExceptionBreak(OptionError,""UnrecognizedOption"",option); + } + + /* clean up percent escape interpreted strings */ + if (arg1 != arg1n ) + arg1=DestroyString((char *)arg1); + if (arg2 != arg2n ) + arg2=DestroyString((char *)arg2); + + /* if new image list generated, replace existing image list */ + if (new_images == (Image *) NULL) + return(status == 0 ? MagickFalse : MagickTrue); + _images=DestroyImageList(_images); + _images=GetFirstImageInList(new_images); + return(status == 0 ? MagickFalse : MagickTrue); + +#undef _image_info +#undef _images +#undef _exception +#undef _draw_info +#undef _quantize_info +#undef IfNormalOp +#undef IfPlusOp +#undef IsNormalOp +} +","@@ -3821,10 +3821,16 @@ WandPrivate MagickBooleanType CLIListOperatorImages(MagickCLI *cli_wand, + _images. + */ + new_images=RemoveFirstImageFromList(&_images); +- clut_image=RemoveLastImageFromList(&_images); ++ clut_image=RemoveFirstImageFromList(&_images); + /* FUTURE - produce Exception, rather than silent fail */ + if (clut_image == (Image *) NULL) +- break; ++ { ++ (void) ThrowMagickException(_exception,GetMagickModule(), ++ OptionError,""ImageSequenceRequired"",""`%s'"",option); ++ new_images=DestroyImage(new_images); ++ status=MagickFalse; ++ break; ++ } + (void) ClutImage(new_images,clut_image,new_images->interpolate, + _exception); + clut_image=DestroyImage(clut_image); +@@ -3868,8 +3874,11 @@ WandPrivate MagickBooleanType CLIListOperatorImages(MagickCLI *cli_wand, + reconstruct_image=RemoveFirstImageFromList(&_images); + /* FUTURE - produce Exception, rather than silent fail */ + if (reconstruct_image == (Image *) NULL) +- { ++ { ++ (void) ThrowMagickException(_exception,GetMagickModule(), ++ OptionError,""ImageSequenceRequired"",""`%s'"",option); + image=DestroyImage(image); ++ status=MagickFalse; + break; + } + metric=UndefinedErrorMetric; +@@ -3931,7 +3940,13 @@ WandPrivate MagickBooleanType CLIListOperatorImages(MagickCLI *cli_wand, + new_images=RemoveFirstImageFromList(&_images); + source_image=RemoveFirstImageFromList(&_images); + if (source_image == (Image *) NULL) +- break; /* FUTURE - produce Exception, rather than silent fail */ ++ { ++ (void) ThrowMagickException(_exception,GetMagickModule(), ++ OptionError,""ImageSequenceRequired"",""`%s'"",option); ++ new_images=DestroyImage(new_images); ++ status=MagickFalse; ++ break; ++ } + + /* FUTURE - this should not be here! - should be part of -geometry */ + if (source_image->geometry != (char *) NULL) +@@ -4121,7 +4136,13 @@ WandPrivate MagickBooleanType CLIListOperatorImages(MagickCLI *cli_wand, + new_images=RemoveFirstImageFromList(&_images); + hald_image=RemoveLastImageFromList(&_images); + if (hald_image == (Image *) NULL) +- break; ++ { ++ (void) ThrowMagickException(_exception,GetMagickModule(), ++ OptionError,""ImageSequenceRequired"",""`%s'"",option); ++ new_images=DestroyImage(new_images); ++ status=MagickFalse; ++ break; ++ } + (void) HaldClutImage(new_images,hald_image,_exception); + hald_image=DestroyImage(hald_image); + break; +@@ -4136,15 +4157,20 @@ WandPrivate MagickBooleanType CLIListOperatorImages(MagickCLI *cli_wand, + *magnitude_image, + *phase_image; + +- magnitude_image=RemoveFirstImageFromList(&_images); +- phase_image=RemoveFirstImageFromList(&_images); +- /* FUTURE - produce Exception, rather than silent fail */ +- if (phase_image == (Image *) NULL) +- break; +- new_images=InverseFourierTransformImage(magnitude_image,phase_image, +- IsNormalOp,_exception); +- magnitude_image=DestroyImage(magnitude_image); +- phase_image=DestroyImage(phase_image); ++ magnitude_image=RemoveFirstImageFromList(&_images); ++ phase_image=RemoveFirstImageFromList(&_images); ++ if (phase_image == (Image *) NULL) ++ { ++ (void) ThrowMagickException(_exception,GetMagickModule(), ++ OptionError,""ImageSequenceRequired"",""`%s'"",option); ++ magnitude_image=DestroyImage(magnitude_image); ++ status=MagickFalse; ++ break; ++ } ++ new_images=InverseFourierTransformImage(magnitude_image,phase_image, ++ IsNormalOp,_exception); ++ magnitude_image=DestroyImage(magnitude_image); ++ phase_image=DestroyImage(phase_image); + break; + } + if (LocaleCompare(""insert"",option+1) == 0)",6695,7026,8192 diff --git a/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_6144_to_8192.pkl b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_6144_to_8192.pkl new file mode 100644 index 0000000000000000000000000000000000000000..8b4187e3778f4743bc554052c0d59c1099026269 --- /dev/null +++ b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_6144_to_8192.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4ceafe9ea38e1a5f4dfcd26459dd3ce1a99920bb44e3b04922d48eb18720d5f4 +size 497017 diff --git a/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_8192_to_11000.csv b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_8192_to_11000.csv new file mode 100644 index 0000000000000000000000000000000000000000..d7781d6a767c26263516c4c38423d706da65ba5f --- /dev/null +++ b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_8192_to_11000.csv @@ -0,0 +1,15759 @@ +idx,func_before,vul,func_after,patch,code_token_length,total_token_length,max_tokens_setting +18105,"isis_print(netdissect_options *ndo, + const uint8_t *p, u_int length) +{ + const struct isis_common_header *isis_header; + + const struct isis_iih_lan_header *header_iih_lan; + const struct isis_iih_ptp_header *header_iih_ptp; + const struct isis_lsp_header *header_lsp; + const struct isis_csnp_header *header_csnp; + const struct isis_psnp_header *header_psnp; + + const struct isis_tlv_lsp *tlv_lsp; + const struct isis_tlv_ptp_adj *tlv_ptp_adj; + const struct isis_tlv_is_reach *tlv_is_reach; + const struct isis_tlv_es_reach *tlv_es_reach; + + uint8_t pdu_type, max_area, id_length, tlv_type, tlv_len, tmp, alen, lan_alen, prefix_len; + uint8_t ext_is_len, ext_ip_len, mt_len; + const uint8_t *optr, *pptr, *tptr; + u_short packet_len,pdu_len, key_id; + u_int i,vendor_id; + int sigcheck; + + packet_len=length; + optr = p; /* initialize the _o_riginal pointer to the packet start - + need it for parsing the checksum TLV and authentication + TLV verification */ + isis_header = (const struct isis_common_header *)p; + ND_TCHECK(*isis_header); + if (length < ISIS_COMMON_HEADER_SIZE) + goto trunc; + pptr = p+(ISIS_COMMON_HEADER_SIZE); + header_iih_lan = (const struct isis_iih_lan_header *)pptr; + header_iih_ptp = (const struct isis_iih_ptp_header *)pptr; + header_lsp = (const struct isis_lsp_header *)pptr; + header_csnp = (const struct isis_csnp_header *)pptr; + header_psnp = (const struct isis_psnp_header *)pptr; + + if (!ndo->ndo_eflag) + ND_PRINT((ndo, ""IS-IS"")); + + /* + * Sanity checking of the header. + */ + + if (isis_header->version != ISIS_VERSION) { + ND_PRINT((ndo, ""version %d packet not supported"", isis_header->version)); + return (0); + } + + if ((isis_header->id_length != SYSTEM_ID_LEN) && (isis_header->id_length != 0)) { + ND_PRINT((ndo, ""system ID length of %d is not supported"", + isis_header->id_length)); + return (0); + } + + if (isis_header->pdu_version != ISIS_VERSION) { + ND_PRINT((ndo, ""version %d packet not supported"", isis_header->pdu_version)); + return (0); + } + + if (length < isis_header->fixed_len) { + ND_PRINT((ndo, ""fixed header length %u > packet length %u"", isis_header->fixed_len, length)); + return (0); + } + + if (isis_header->fixed_len < ISIS_COMMON_HEADER_SIZE) { + ND_PRINT((ndo, ""fixed header length %u < minimum header size %u"", isis_header->fixed_len, (u_int)ISIS_COMMON_HEADER_SIZE)); + return (0); + } + + max_area = isis_header->max_area; + switch(max_area) { + case 0: + max_area = 3; /* silly shit */ + break; + case 255: + ND_PRINT((ndo, ""bad packet -- 255 areas"")); + return (0); + default: + break; + } + + id_length = isis_header->id_length; + switch(id_length) { + case 0: + id_length = 6; /* silly shit again */ + break; + case 1: /* 1-8 are valid sys-ID lenghts */ + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + break; + case 255: + id_length = 0; /* entirely useless */ + break; + default: + break; + } + + /* toss any non 6-byte sys-ID len PDUs */ + if (id_length != 6 ) { + ND_PRINT((ndo, ""bad packet -- illegal sys-ID length (%u)"", id_length)); + return (0); + } + + pdu_type=isis_header->pdu_type; + + /* in non-verbose mode print the basic PDU Type plus PDU specific brief information*/ + if (ndo->ndo_vflag == 0) { + ND_PRINT((ndo, ""%s%s"", + ndo->ndo_eflag ? """" : "", "", + tok2str(isis_pdu_values, ""unknown PDU-Type %u"", pdu_type))); + } else { + /* ok they seem to want to know everything - lets fully decode it */ + ND_PRINT((ndo, ""%slength %u"", ndo->ndo_eflag ? """" : "", "", length)); + + ND_PRINT((ndo, ""\n\t%s, hlen: %u, v: %u, pdu-v: %u, sys-id-len: %u (%u), max-area: %u (%u)"", + tok2str(isis_pdu_values, + ""unknown, type %u"", + pdu_type), + isis_header->fixed_len, + isis_header->version, + isis_header->pdu_version, + id_length, + isis_header->id_length, + max_area, + isis_header->max_area)); + + if (ndo->ndo_vflag > 1) { + if (!print_unknown_data(ndo, optr, ""\n\t"", 8)) /* provide the _o_riginal pointer */ + return (0); /* for optionally debugging the common header */ + } + } + + switch (pdu_type) { + + case ISIS_PDU_L1_LAN_IIH: + case ISIS_PDU_L2_LAN_IIH: + if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)) { + ND_PRINT((ndo, "", bogus fixed header length %u should be %lu"", + isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE))); + return (0); + } + ND_TCHECK(*header_iih_lan); + if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE) + goto trunc; + if (ndo->ndo_vflag == 0) { + ND_PRINT((ndo, "", src-id %s"", + isis_print_id(header_iih_lan->source_id, SYSTEM_ID_LEN))); + ND_PRINT((ndo, "", lan-id %s, prio %u"", + isis_print_id(header_iih_lan->lan_id,NODE_ID_LEN), + header_iih_lan->priority)); + ND_PRINT((ndo, "", length %u"", length)); + return (1); + } + pdu_len=EXTRACT_16BITS(header_iih_lan->pdu_len); + if (packet_len>pdu_len) { + packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ + length=pdu_len; + } + + ND_PRINT((ndo, ""\n\t source-id: %s, holding time: %us, Flags: [%s]"", + isis_print_id(header_iih_lan->source_id,SYSTEM_ID_LEN), + EXTRACT_16BITS(header_iih_lan->holding_time), + tok2str(isis_iih_circuit_type_values, + ""unknown circuit type 0x%02x"", + header_iih_lan->circuit_type))); + + ND_PRINT((ndo, ""\n\t lan-id: %s, Priority: %u, PDU length: %u"", + isis_print_id(header_iih_lan->lan_id, NODE_ID_LEN), + (header_iih_lan->priority) & ISIS_LAN_PRIORITY_MASK, + pdu_len)); + + if (ndo->ndo_vflag > 1) { + if (!print_unknown_data(ndo, pptr, ""\n\t "", ISIS_IIH_LAN_HEADER_SIZE)) + return (0); + } + + packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE); + pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE); + break; + + case ISIS_PDU_PTP_IIH: + if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)) { + ND_PRINT((ndo, "", bogus fixed header length %u should be %lu"", + isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE))); + return (0); + } + ND_TCHECK(*header_iih_ptp); + if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE) + goto trunc; + if (ndo->ndo_vflag == 0) { + ND_PRINT((ndo, "", src-id %s"", isis_print_id(header_iih_ptp->source_id, SYSTEM_ID_LEN))); + ND_PRINT((ndo, "", length %u"", length)); + return (1); + } + pdu_len=EXTRACT_16BITS(header_iih_ptp->pdu_len); + if (packet_len>pdu_len) { + packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ + length=pdu_len; + } + + ND_PRINT((ndo, ""\n\t source-id: %s, holding time: %us, Flags: [%s]"", + isis_print_id(header_iih_ptp->source_id,SYSTEM_ID_LEN), + EXTRACT_16BITS(header_iih_ptp->holding_time), + tok2str(isis_iih_circuit_type_values, + ""unknown circuit type 0x%02x"", + header_iih_ptp->circuit_type))); + + ND_PRINT((ndo, ""\n\t circuit-id: 0x%02x, PDU length: %u"", + header_iih_ptp->circuit_id, + pdu_len)); + + if (ndo->ndo_vflag > 1) { + if (!print_unknown_data(ndo, pptr, ""\n\t "", ISIS_IIH_PTP_HEADER_SIZE)) + return (0); + } + + packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE); + pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE); + break; + + case ISIS_PDU_L1_LSP: + case ISIS_PDU_L2_LSP: + if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)) { + ND_PRINT((ndo, "", bogus fixed header length %u should be %lu"", + isis_header->fixed_len, (unsigned long)ISIS_LSP_HEADER_SIZE)); + return (0); + } + ND_TCHECK(*header_lsp); + if (length < ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE) + goto trunc; + if (ndo->ndo_vflag == 0) { + ND_PRINT((ndo, "", lsp-id %s, seq 0x%08x, lifetime %5us"", + isis_print_id(header_lsp->lsp_id, LSP_ID_LEN), + EXTRACT_32BITS(header_lsp->sequence_number), + EXTRACT_16BITS(header_lsp->remaining_lifetime))); + ND_PRINT((ndo, "", length %u"", length)); + return (1); + } + pdu_len=EXTRACT_16BITS(header_lsp->pdu_len); + if (packet_len>pdu_len) { + packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ + length=pdu_len; + } + + ND_PRINT((ndo, ""\n\t lsp-id: %s, seq: 0x%08x, lifetime: %5us\n\t chksum: 0x%04x"", + isis_print_id(header_lsp->lsp_id, LSP_ID_LEN), + EXTRACT_32BITS(header_lsp->sequence_number), + EXTRACT_16BITS(header_lsp->remaining_lifetime), + EXTRACT_16BITS(header_lsp->checksum))); + + osi_print_cksum(ndo, (const uint8_t *)header_lsp->lsp_id, + EXTRACT_16BITS(header_lsp->checksum), + 12, length-12); + + ND_PRINT((ndo, "", PDU length: %u, Flags: [ %s"", + pdu_len, + ISIS_MASK_LSP_OL_BIT(header_lsp->typeblock) ? ""Overload bit set, "" : """")); + + if (ISIS_MASK_LSP_ATT_BITS(header_lsp->typeblock)) { + ND_PRINT((ndo, ""%s"", ISIS_MASK_LSP_ATT_DEFAULT_BIT(header_lsp->typeblock) ? ""default "" : """")); + ND_PRINT((ndo, ""%s"", ISIS_MASK_LSP_ATT_DELAY_BIT(header_lsp->typeblock) ? ""delay "" : """")); + ND_PRINT((ndo, ""%s"", ISIS_MASK_LSP_ATT_EXPENSE_BIT(header_lsp->typeblock) ? ""expense "" : """")); + ND_PRINT((ndo, ""%s"", ISIS_MASK_LSP_ATT_ERROR_BIT(header_lsp->typeblock) ? ""error "" : """")); + ND_PRINT((ndo, ""ATT bit set, "")); + } + ND_PRINT((ndo, ""%s"", ISIS_MASK_LSP_PARTITION_BIT(header_lsp->typeblock) ? ""P bit set, "" : """")); + ND_PRINT((ndo, ""%s ]"", tok2str(isis_lsp_istype_values, ""Unknown(0x%x)"", + ISIS_MASK_LSP_ISTYPE_BITS(header_lsp->typeblock)))); + + if (ndo->ndo_vflag > 1) { + if (!print_unknown_data(ndo, pptr, ""\n\t "", ISIS_LSP_HEADER_SIZE)) + return (0); + } + + packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE); + pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE); + break; + + case ISIS_PDU_L1_CSNP: + case ISIS_PDU_L2_CSNP: + if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)) { + ND_PRINT((ndo, "", bogus fixed header length %u should be %lu"", + isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE))); + return (0); + } + ND_TCHECK(*header_csnp); + if (length < ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE) + goto trunc; + if (ndo->ndo_vflag == 0) { + ND_PRINT((ndo, "", src-id %s"", isis_print_id(header_csnp->source_id, NODE_ID_LEN))); + ND_PRINT((ndo, "", length %u"", length)); + return (1); + } + pdu_len=EXTRACT_16BITS(header_csnp->pdu_len); + if (packet_len>pdu_len) { + packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ + length=pdu_len; + } + + ND_PRINT((ndo, ""\n\t source-id: %s, PDU length: %u"", + isis_print_id(header_csnp->source_id, NODE_ID_LEN), + pdu_len)); + ND_PRINT((ndo, ""\n\t start lsp-id: %s"", + isis_print_id(header_csnp->start_lsp_id, LSP_ID_LEN))); + ND_PRINT((ndo, ""\n\t end lsp-id: %s"", + isis_print_id(header_csnp->end_lsp_id, LSP_ID_LEN))); + + if (ndo->ndo_vflag > 1) { + if (!print_unknown_data(ndo, pptr, ""\n\t "", ISIS_CSNP_HEADER_SIZE)) + return (0); + } + + packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE); + pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE); + break; + + case ISIS_PDU_L1_PSNP: + case ISIS_PDU_L2_PSNP: + if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)) { + ND_PRINT((ndo, ""- bogus fixed header length %u should be %lu"", + isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE))); + return (0); + } + ND_TCHECK(*header_psnp); + if (length < ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE) + goto trunc; + if (ndo->ndo_vflag == 0) { + ND_PRINT((ndo, "", src-id %s"", isis_print_id(header_psnp->source_id, NODE_ID_LEN))); + ND_PRINT((ndo, "", length %u"", length)); + return (1); + } + pdu_len=EXTRACT_16BITS(header_psnp->pdu_len); + if (packet_len>pdu_len) { + packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ + length=pdu_len; + } + + ND_PRINT((ndo, ""\n\t source-id: %s, PDU length: %u"", + isis_print_id(header_psnp->source_id, NODE_ID_LEN), + pdu_len)); + + if (ndo->ndo_vflag > 1) { + if (!print_unknown_data(ndo, pptr, ""\n\t "", ISIS_PSNP_HEADER_SIZE)) + return (0); + } + + packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE); + pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE); + break; + + default: + if (ndo->ndo_vflag == 0) { + ND_PRINT((ndo, "", length %u"", length)); + return (1); + } + (void)print_unknown_data(ndo, pptr, ""\n\t "", length); + return (0); + } + + /* + * Now print the TLV's. + */ + + while (packet_len > 0) { + ND_TCHECK2(*pptr, 2); + if (packet_len < 2) + goto trunc; + tlv_type = *pptr++; + tlv_len = *pptr++; + tmp =tlv_len; /* copy temporary len & pointer to packet data */ + tptr = pptr; + packet_len -= 2; + + /* first lets see if we know the TLVs name*/ + ND_PRINT((ndo, ""\n\t %s TLV #%u, length: %u"", + tok2str(isis_tlv_values, + ""unknown"", + tlv_type), + tlv_type, + tlv_len)); + + if (tlv_len == 0) /* something is invalid */ + continue; + + if (packet_len < tlv_len) + goto trunc; + + /* now check if we have a decoder otherwise do a hexdump at the end*/ + switch (tlv_type) { + case ISIS_TLV_AREA_ADDR: + ND_TCHECK2(*tptr, 1); + alen = *tptr++; + while (tmp && alen < tmp) { + ND_PRINT((ndo, ""\n\t Area address (length: %u): %s"", + alen, + isonsap_string(ndo, tptr, alen))); + tptr += alen; + tmp -= alen + 1; + if (tmp==0) /* if this is the last area address do not attemt a boundary check */ + break; + ND_TCHECK2(*tptr, 1); + alen = *tptr++; + } + break; + case ISIS_TLV_ISNEIGH: + while (tmp >= ETHER_ADDR_LEN) { + ND_TCHECK2(*tptr, ETHER_ADDR_LEN); + ND_PRINT((ndo, ""\n\t SNPA: %s"", isis_print_id(tptr, ETHER_ADDR_LEN))); + tmp -= ETHER_ADDR_LEN; + tptr += ETHER_ADDR_LEN; + } + break; + + case ISIS_TLV_ISNEIGH_VARLEN: + if (!ND_TTEST2(*tptr, 1) || tmp < 3) /* min. TLV length */ + goto trunctlv; + lan_alen = *tptr++; /* LAN address length */ + if (lan_alen == 0) { + ND_PRINT((ndo, ""\n\t LAN address length 0 bytes (invalid)"")); + break; + } + tmp --; + ND_PRINT((ndo, ""\n\t LAN address length %u bytes "", lan_alen)); + while (tmp >= lan_alen) { + ND_TCHECK2(*tptr, lan_alen); + ND_PRINT((ndo, ""\n\t\tIS Neighbor: %s"", isis_print_id(tptr, lan_alen))); + tmp -= lan_alen; + tptr +=lan_alen; + } + break; + + case ISIS_TLV_PADDING: + break; + + case ISIS_TLV_MT_IS_REACH: + mt_len = isis_print_mtid(ndo, tptr, ""\n\t ""); + if (mt_len == 0) /* did something go wrong ? */ + goto trunctlv; + tptr+=mt_len; + tmp-=mt_len; + while (tmp >= 2+NODE_ID_LEN+3+1) { + ext_is_len = isis_print_ext_is_reach(ndo, tptr, ""\n\t "", tlv_type); + if (ext_is_len == 0) /* did something go wrong ? */ + goto trunctlv; + + tmp-=ext_is_len; + tptr+=ext_is_len; + } + break; + + case ISIS_TLV_IS_ALIAS_ID: + while (tmp >= NODE_ID_LEN+1) { /* is it worth attempting a decode ? */ + ext_is_len = isis_print_ext_is_reach(ndo, tptr, ""\n\t "", tlv_type); + if (ext_is_len == 0) /* did something go wrong ? */ + goto trunctlv; + tmp-=ext_is_len; + tptr+=ext_is_len; + } + break; + + case ISIS_TLV_EXT_IS_REACH: + while (tmp >= NODE_ID_LEN+3+1) { /* is it worth attempting a decode ? */ + ext_is_len = isis_print_ext_is_reach(ndo, tptr, ""\n\t "", tlv_type); + if (ext_is_len == 0) /* did something go wrong ? */ + goto trunctlv; + tmp-=ext_is_len; + tptr+=ext_is_len; + } + break; + case ISIS_TLV_IS_REACH: + ND_TCHECK2(*tptr,1); /* check if there is one byte left to read out the virtual flag */ + ND_PRINT((ndo, ""\n\t %s"", + tok2str(isis_is_reach_virtual_values, + ""bogus virtual flag 0x%02x"", + *tptr++))); + tlv_is_reach = (const struct isis_tlv_is_reach *)tptr; + while (tmp >= sizeof(struct isis_tlv_is_reach)) { + ND_TCHECK(*tlv_is_reach); + ND_PRINT((ndo, ""\n\t IS Neighbor: %s"", + isis_print_id(tlv_is_reach->neighbor_nodeid, NODE_ID_LEN))); + isis_print_metric_block(ndo, &tlv_is_reach->isis_metric_block); + tmp -= sizeof(struct isis_tlv_is_reach); + tlv_is_reach++; + } + break; + + case ISIS_TLV_ESNEIGH: + tlv_es_reach = (const struct isis_tlv_es_reach *)tptr; + while (tmp >= sizeof(struct isis_tlv_es_reach)) { + ND_TCHECK(*tlv_es_reach); + ND_PRINT((ndo, ""\n\t ES Neighbor: %s"", + isis_print_id(tlv_es_reach->neighbor_sysid, SYSTEM_ID_LEN))); + isis_print_metric_block(ndo, &tlv_es_reach->isis_metric_block); + tmp -= sizeof(struct isis_tlv_es_reach); + tlv_es_reach++; + } + break; + + /* those two TLVs share the same format */ + case ISIS_TLV_INT_IP_REACH: + case ISIS_TLV_EXT_IP_REACH: + if (!isis_print_tlv_ip_reach(ndo, pptr, ""\n\t "", tlv_len)) + return (1); + break; + + case ISIS_TLV_EXTD_IP_REACH: + while (tmp>0) { + ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, ""\n\t "", AF_INET); + if (ext_ip_len == 0) /* did something go wrong ? */ + goto trunctlv; + tptr+=ext_ip_len; + tmp-=ext_ip_len; + } + break; + + case ISIS_TLV_MT_IP_REACH: + mt_len = isis_print_mtid(ndo, tptr, ""\n\t ""); + if (mt_len == 0) { /* did something go wrong ? */ + goto trunctlv; + } + tptr+=mt_len; + tmp-=mt_len; + + while (tmp>0) { + ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, ""\n\t "", AF_INET); + if (ext_ip_len == 0) /* did something go wrong ? */ + goto trunctlv; + tptr+=ext_ip_len; + tmp-=ext_ip_len; + } + break; + + case ISIS_TLV_IP6_REACH: + while (tmp>0) { + ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, ""\n\t "", AF_INET6); + if (ext_ip_len == 0) /* did something go wrong ? */ + goto trunctlv; + tptr+=ext_ip_len; + tmp-=ext_ip_len; + } + break; + + case ISIS_TLV_MT_IP6_REACH: + mt_len = isis_print_mtid(ndo, tptr, ""\n\t ""); + if (mt_len == 0) { /* did something go wrong ? */ + goto trunctlv; + } + tptr+=mt_len; + tmp-=mt_len; + + while (tmp>0) { + ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, ""\n\t "", AF_INET6); + if (ext_ip_len == 0) /* did something go wrong ? */ + goto trunctlv; + tptr+=ext_ip_len; + tmp-=ext_ip_len; + } + break; + + case ISIS_TLV_IP6ADDR: + while (tmp>=sizeof(struct in6_addr)) { + ND_TCHECK2(*tptr, sizeof(struct in6_addr)); + + ND_PRINT((ndo, ""\n\t IPv6 interface address: %s"", + ip6addr_string(ndo, tptr))); + + tptr += sizeof(struct in6_addr); + tmp -= sizeof(struct in6_addr); + } + break; + case ISIS_TLV_AUTH: + ND_TCHECK2(*tptr, 1); + + ND_PRINT((ndo, ""\n\t %s: "", + tok2str(isis_subtlv_auth_values, + ""unknown Authentication type 0x%02x"", + *tptr))); + + switch (*tptr) { + case ISIS_SUBTLV_AUTH_SIMPLE: + if (fn_printzp(ndo, tptr + 1, tlv_len - 1, ndo->ndo_snapend)) + goto trunctlv; + break; + case ISIS_SUBTLV_AUTH_MD5: + for(i=1;i=1) { + ND_TCHECK2(*tptr, 1); + ND_PRINT((ndo, ""\n\t Adjacency State: %s (%u)"", + tok2str(isis_ptp_adjancey_values, ""unknown"", *tptr), + *tptr)); + tmp--; + } + if(tmp>sizeof(tlv_ptp_adj->extd_local_circuit_id)) { + ND_TCHECK(tlv_ptp_adj->extd_local_circuit_id); + ND_PRINT((ndo, ""\n\t Extended Local circuit-ID: 0x%08x"", + EXTRACT_32BITS(tlv_ptp_adj->extd_local_circuit_id))); + tmp-=sizeof(tlv_ptp_adj->extd_local_circuit_id); + } + if(tmp>=SYSTEM_ID_LEN) { + ND_TCHECK2(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN); + ND_PRINT((ndo, ""\n\t Neighbor System-ID: %s"", + isis_print_id(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN))); + tmp-=SYSTEM_ID_LEN; + } + if(tmp>=sizeof(tlv_ptp_adj->neighbor_extd_local_circuit_id)) { + ND_TCHECK(tlv_ptp_adj->neighbor_extd_local_circuit_id); + ND_PRINT((ndo, ""\n\t Neighbor Extended Local circuit-ID: 0x%08x"", + EXTRACT_32BITS(tlv_ptp_adj->neighbor_extd_local_circuit_id))); + } + break; + + case ISIS_TLV_PROTOCOLS: + ND_PRINT((ndo, ""\n\t NLPID(s): "")); + while (tmp>0) { + ND_TCHECK2(*(tptr), 1); + ND_PRINT((ndo, ""%s (0x%02x)"", + tok2str(nlpid_values, + ""unknown"", + *tptr), + *tptr)); + if (tmp>1) /* further NPLIDs ? - put comma */ + ND_PRINT((ndo, "", "")); + tptr++; + tmp--; + } + break; + + case ISIS_TLV_MT_PORT_CAP: + { + ND_TCHECK2(*(tptr), 2); + + ND_PRINT((ndo, ""\n\t RES: %d, MTID(s): %d"", + (EXTRACT_16BITS (tptr) >> 12), + (EXTRACT_16BITS (tptr) & 0x0fff))); + + tmp = tmp-2; + tptr = tptr+2; + + if (tmp) + isis_print_mt_port_cap_subtlv(ndo, tptr, tmp); + + break; + } + + case ISIS_TLV_MT_CAPABILITY: + + ND_TCHECK2(*(tptr), 2); + + ND_PRINT((ndo, ""\n\t O: %d, RES: %d, MTID(s): %d"", + (EXTRACT_16BITS(tptr) >> 15) & 0x01, + (EXTRACT_16BITS(tptr) >> 12) & 0x07, + EXTRACT_16BITS(tptr) & 0x0fff)); + + tmp = tmp-2; + tptr = tptr+2; + + if (tmp) + isis_print_mt_capability_subtlv(ndo, tptr, tmp); + + break; + + case ISIS_TLV_TE_ROUTER_ID: + ND_TCHECK2(*pptr, sizeof(struct in_addr)); + ND_PRINT((ndo, ""\n\t Traffic Engineering Router ID: %s"", ipaddr_string(ndo, pptr))); + break; + + case ISIS_TLV_IPADDR: + while (tmp>=sizeof(struct in_addr)) { + ND_TCHECK2(*tptr, sizeof(struct in_addr)); + ND_PRINT((ndo, ""\n\t IPv4 interface address: %s"", ipaddr_string(ndo, tptr))); + tptr += sizeof(struct in_addr); + tmp -= sizeof(struct in_addr); + } + break; + + case ISIS_TLV_HOSTNAME: + ND_PRINT((ndo, ""\n\t Hostname: "")); + if (fn_printzp(ndo, tptr, tmp, ndo->ndo_snapend)) + goto trunctlv; + break; + + case ISIS_TLV_SHARED_RISK_GROUP: + if (tmp < NODE_ID_LEN) + break; + ND_TCHECK2(*tptr, NODE_ID_LEN); + ND_PRINT((ndo, ""\n\t IS Neighbor: %s"", isis_print_id(tptr, NODE_ID_LEN))); + tptr+=(NODE_ID_LEN); + tmp-=(NODE_ID_LEN); + + if (tmp < 1) + break; + ND_TCHECK2(*tptr, 1); + ND_PRINT((ndo, "", Flags: [%s]"", ISIS_MASK_TLV_SHARED_RISK_GROUP(*tptr++) ? ""numbered"" : ""unnumbered"")); + tmp--; + + if (tmp < sizeof(struct in_addr)) + break; + ND_TCHECK2(*tptr, sizeof(struct in_addr)); + ND_PRINT((ndo, ""\n\t IPv4 interface address: %s"", ipaddr_string(ndo, tptr))); + tptr+=sizeof(struct in_addr); + tmp-=sizeof(struct in_addr); + + if (tmp < sizeof(struct in_addr)) + break; + ND_TCHECK2(*tptr, sizeof(struct in_addr)); + ND_PRINT((ndo, ""\n\t IPv4 neighbor address: %s"", ipaddr_string(ndo, tptr))); + tptr+=sizeof(struct in_addr); + tmp-=sizeof(struct in_addr); + + while (tmp>=4) { + ND_TCHECK2(*tptr, 4); + ND_PRINT((ndo, ""\n\t Link-ID: 0x%08x"", EXTRACT_32BITS(tptr))); + tptr+=4; + tmp-=4; + } + break; + + case ISIS_TLV_LSP: + tlv_lsp = (const struct isis_tlv_lsp *)tptr; + while(tmp>=sizeof(struct isis_tlv_lsp)) { + ND_TCHECK((tlv_lsp->lsp_id)[LSP_ID_LEN-1]); + ND_PRINT((ndo, ""\n\t lsp-id: %s"", + isis_print_id(tlv_lsp->lsp_id, LSP_ID_LEN))); + ND_TCHECK2(tlv_lsp->sequence_number, 4); + ND_PRINT((ndo, "", seq: 0x%08x"", EXTRACT_32BITS(tlv_lsp->sequence_number))); + ND_TCHECK2(tlv_lsp->remaining_lifetime, 2); + ND_PRINT((ndo, "", lifetime: %5ds"", EXTRACT_16BITS(tlv_lsp->remaining_lifetime))); + ND_TCHECK2(tlv_lsp->checksum, 2); + ND_PRINT((ndo, "", chksum: 0x%04x"", EXTRACT_16BITS(tlv_lsp->checksum))); + tmp-=sizeof(struct isis_tlv_lsp); + tlv_lsp++; + } + break; + + case ISIS_TLV_CHECKSUM: + if (tmp < ISIS_TLV_CHECKSUM_MINLEN) + break; + ND_TCHECK2(*tptr, ISIS_TLV_CHECKSUM_MINLEN); + ND_PRINT((ndo, ""\n\t checksum: 0x%04x "", EXTRACT_16BITS(tptr))); + /* do not attempt to verify the checksum if it is zero + * most likely a HMAC-MD5 TLV is also present and + * to avoid conflicts the checksum TLV is zeroed. + * see rfc3358 for details + */ + osi_print_cksum(ndo, optr, EXTRACT_16BITS(tptr), tptr-optr, + length); + break; + + case ISIS_TLV_POI: + if (tlv_len >= SYSTEM_ID_LEN + 1) { + ND_TCHECK2(*tptr, SYSTEM_ID_LEN + 1); + ND_PRINT((ndo, ""\n\t Purge Originator System-ID: %s"", + isis_print_id(tptr + 1, SYSTEM_ID_LEN))); + } + + if (tlv_len == 2 * SYSTEM_ID_LEN + 1) { + ND_TCHECK2(*tptr, 2 * SYSTEM_ID_LEN + 1); + ND_PRINT((ndo, ""\n\t Received from System-ID: %s"", + isis_print_id(tptr + SYSTEM_ID_LEN + 1, SYSTEM_ID_LEN))); + } + break; + + case ISIS_TLV_MT_SUPPORTED: + if (tmp < ISIS_TLV_MT_SUPPORTED_MINLEN) + break; + while (tmp>1) { + /* length can only be a multiple of 2, otherwise there is + something broken -> so decode down until length is 1 */ + if (tmp!=1) { + mt_len = isis_print_mtid(ndo, tptr, ""\n\t ""); + if (mt_len == 0) /* did something go wrong ? */ + goto trunctlv; + tptr+=mt_len; + tmp-=mt_len; + } else { + ND_PRINT((ndo, ""\n\t invalid MT-ID"")); + break; + } + } + break; + + case ISIS_TLV_RESTART_SIGNALING: + /* first attempt to decode the flags */ + if (tmp < ISIS_TLV_RESTART_SIGNALING_FLAGLEN) + break; + ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_FLAGLEN); + ND_PRINT((ndo, ""\n\t Flags [%s]"", + bittok2str(isis_restart_flag_values, ""none"", *tptr))); + tptr+=ISIS_TLV_RESTART_SIGNALING_FLAGLEN; + tmp-=ISIS_TLV_RESTART_SIGNALING_FLAGLEN; + + /* is there anything other than the flags field? */ + if (tmp == 0) + break; + + if (tmp < ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN) + break; + ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN); + + ND_PRINT((ndo, "", Remaining holding time %us"", EXTRACT_16BITS(tptr))); + tptr+=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN; + tmp-=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN; + + /* is there an additional sysid field present ?*/ + if (tmp == SYSTEM_ID_LEN) { + ND_TCHECK2(*tptr, SYSTEM_ID_LEN); + ND_PRINT((ndo, "", for %s"", isis_print_id(tptr,SYSTEM_ID_LEN))); + } + break; + + case ISIS_TLV_IDRP_INFO: + if (tmp < ISIS_TLV_IDRP_INFO_MINLEN) + break; + ND_TCHECK2(*tptr, ISIS_TLV_IDRP_INFO_MINLEN); + ND_PRINT((ndo, ""\n\t Inter-Domain Information Type: %s"", + tok2str(isis_subtlv_idrp_values, + ""Unknown (0x%02x)"", + *tptr))); + switch (*tptr++) { + case ISIS_SUBTLV_IDRP_ASN: + ND_TCHECK2(*tptr, 2); /* fetch AS number */ + ND_PRINT((ndo, ""AS Number: %u"", EXTRACT_16BITS(tptr))); + break; + case ISIS_SUBTLV_IDRP_LOCAL: + case ISIS_SUBTLV_IDRP_RES: + default: + if (!print_unknown_data(ndo, tptr, ""\n\t "", tlv_len - 1)) + return(0); + break; + } + break; + + case ISIS_TLV_LSP_BUFFERSIZE: + if (tmp < ISIS_TLV_LSP_BUFFERSIZE_MINLEN) + break; + ND_TCHECK2(*tptr, ISIS_TLV_LSP_BUFFERSIZE_MINLEN); + ND_PRINT((ndo, ""\n\t LSP Buffersize: %u"", EXTRACT_16BITS(tptr))); + break; + + case ISIS_TLV_PART_DIS: + while (tmp >= SYSTEM_ID_LEN) { + ND_TCHECK2(*tptr, SYSTEM_ID_LEN); + ND_PRINT((ndo, ""\n\t %s"", isis_print_id(tptr, SYSTEM_ID_LEN))); + tptr+=SYSTEM_ID_LEN; + tmp-=SYSTEM_ID_LEN; + } + break; + + case ISIS_TLV_PREFIX_NEIGH: + if (tmp < sizeof(struct isis_metric_block)) + break; + ND_TCHECK2(*tptr, sizeof(struct isis_metric_block)); + ND_PRINT((ndo, ""\n\t Metric Block"")); + isis_print_metric_block(ndo, (const struct isis_metric_block *)tptr); + tptr+=sizeof(struct isis_metric_block); + tmp-=sizeof(struct isis_metric_block); + + while(tmp>0) { + ND_TCHECK2(*tptr, 1); + prefix_len=*tptr++; /* read out prefix length in semioctets*/ + if (prefix_len < 2) { + ND_PRINT((ndo, ""\n\t\tAddress: prefix length %u < 2"", prefix_len)); + break; + } + tmp--; + if (tmp < prefix_len/2) + break; + ND_TCHECK2(*tptr, prefix_len / 2); + ND_PRINT((ndo, ""\n\t\tAddress: %s/%u"", + isonsap_string(ndo, tptr, prefix_len / 2), prefix_len * 4)); + tptr+=prefix_len/2; + tmp-=prefix_len/2; + } + break; + + case ISIS_TLV_IIH_SEQNR: + if (tmp < ISIS_TLV_IIH_SEQNR_MINLEN) + break; + ND_TCHECK2(*tptr, ISIS_TLV_IIH_SEQNR_MINLEN); /* check if four bytes are on the wire */ + ND_PRINT((ndo, ""\n\t Sequence number: %u"", EXTRACT_32BITS(tptr))); + break; + + case ISIS_TLV_VENDOR_PRIVATE: + if (tmp < ISIS_TLV_VENDOR_PRIVATE_MINLEN) + break; + ND_TCHECK2(*tptr, ISIS_TLV_VENDOR_PRIVATE_MINLEN); /* check if enough byte for a full oui */ + vendor_id = EXTRACT_24BITS(tptr); + ND_PRINT((ndo, ""\n\t Vendor: %s (%u)"", + tok2str(oui_values, ""Unknown"", vendor_id), + vendor_id)); + tptr+=3; + tmp-=3; + if (tmp > 0) /* hexdump the rest */ + if (!print_unknown_data(ndo, tptr, ""\n\t\t"", tmp)) + return(0); + break; + /* + * FIXME those are the defined TLVs that lack a decoder + * you are welcome to contribute code ;-) + */ + + case ISIS_TLV_DECNET_PHASE4: + case ISIS_TLV_LUCENT_PRIVATE: + case ISIS_TLV_IPAUTH: + case ISIS_TLV_NORTEL_PRIVATE1: + case ISIS_TLV_NORTEL_PRIVATE2: + + default: + if (ndo->ndo_vflag <= 1) { + if (!print_unknown_data(ndo, pptr, ""\n\t\t"", tlv_len)) + return(0); + } + break; + } + /* do we want to see an additionally hexdump ? */ + if (ndo->ndo_vflag> 1) { + if (!print_unknown_data(ndo, pptr, ""\n\t "", tlv_len)) + return(0); + } + + pptr += tlv_len; + packet_len -= tlv_len; + } + + if (packet_len != 0) { + ND_PRINT((ndo, ""\n\t %u straggler bytes"", packet_len)); + } + return (1); + + trunc: + ND_PRINT((ndo, ""%s"", tstr)); + return (1); + + trunctlv: + ND_PRINT((ndo, ""\n\t\t"")); + ND_PRINT((ndo, ""%s"", tstr)); + return(1); +} +",1,"isis_print(netdissect_options *ndo, + const uint8_t *p, u_int length) +{ + const struct isis_common_header *isis_header; + + const struct isis_iih_lan_header *header_iih_lan; + const struct isis_iih_ptp_header *header_iih_ptp; + const struct isis_lsp_header *header_lsp; + const struct isis_csnp_header *header_csnp; + const struct isis_psnp_header *header_psnp; + + const struct isis_tlv_lsp *tlv_lsp; + const struct isis_tlv_ptp_adj *tlv_ptp_adj; + const struct isis_tlv_is_reach *tlv_is_reach; + const struct isis_tlv_es_reach *tlv_es_reach; + + uint8_t pdu_type, max_area, id_length, tlv_type, tlv_len, tmp, alen, lan_alen, prefix_len; + uint8_t ext_is_len, ext_ip_len, mt_len; + const uint8_t *optr, *pptr, *tptr; + u_short packet_len,pdu_len, key_id; + u_int i,vendor_id; + int sigcheck; + + packet_len=length; + optr = p; /* initialize the _o_riginal pointer to the packet start - + need it for parsing the checksum TLV and authentication + TLV verification */ + isis_header = (const struct isis_common_header *)p; + ND_TCHECK(*isis_header); + if (length < ISIS_COMMON_HEADER_SIZE) + goto trunc; + pptr = p+(ISIS_COMMON_HEADER_SIZE); + header_iih_lan = (const struct isis_iih_lan_header *)pptr; + header_iih_ptp = (const struct isis_iih_ptp_header *)pptr; + header_lsp = (const struct isis_lsp_header *)pptr; + header_csnp = (const struct isis_csnp_header *)pptr; + header_psnp = (const struct isis_psnp_header *)pptr; + + if (!ndo->ndo_eflag) + ND_PRINT((ndo, ""IS-IS"")); + + /* + * Sanity checking of the header. + */ + + if (isis_header->version != ISIS_VERSION) { + ND_PRINT((ndo, ""version %d packet not supported"", isis_header->version)); + return (0); + } + + if ((isis_header->id_length != SYSTEM_ID_LEN) && (isis_header->id_length != 0)) { + ND_PRINT((ndo, ""system ID length of %d is not supported"", + isis_header->id_length)); + return (0); + } + + if (isis_header->pdu_version != ISIS_VERSION) { + ND_PRINT((ndo, ""version %d packet not supported"", isis_header->pdu_version)); + return (0); + } + + if (length < isis_header->fixed_len) { + ND_PRINT((ndo, ""fixed header length %u > packet length %u"", isis_header->fixed_len, length)); + return (0); + } + + if (isis_header->fixed_len < ISIS_COMMON_HEADER_SIZE) { + ND_PRINT((ndo, ""fixed header length %u < minimum header size %u"", isis_header->fixed_len, (u_int)ISIS_COMMON_HEADER_SIZE)); + return (0); + } + + max_area = isis_header->max_area; + switch(max_area) { + case 0: + max_area = 3; /* silly shit */ + break; + case 255: + ND_PRINT((ndo, ""bad packet -- 255 areas"")); + return (0); + default: + break; + } + + id_length = isis_header->id_length; + switch(id_length) { + case 0: + id_length = 6; /* silly shit again */ + break; + case 1: /* 1-8 are valid sys-ID lenghts */ + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + break; + case 255: + id_length = 0; /* entirely useless */ + break; + default: + break; + } + + /* toss any non 6-byte sys-ID len PDUs */ + if (id_length != 6 ) { + ND_PRINT((ndo, ""bad packet -- illegal sys-ID length (%u)"", id_length)); + return (0); + } + + pdu_type=isis_header->pdu_type; + + /* in non-verbose mode print the basic PDU Type plus PDU specific brief information*/ + if (ndo->ndo_vflag == 0) { + ND_PRINT((ndo, ""%s%s"", + ndo->ndo_eflag ? """" : "", "", + tok2str(isis_pdu_values, ""unknown PDU-Type %u"", pdu_type))); + } else { + /* ok they seem to want to know everything - lets fully decode it */ + ND_PRINT((ndo, ""%slength %u"", ndo->ndo_eflag ? """" : "", "", length)); + + ND_PRINT((ndo, ""\n\t%s, hlen: %u, v: %u, pdu-v: %u, sys-id-len: %u (%u), max-area: %u (%u)"", + tok2str(isis_pdu_values, + ""unknown, type %u"", + pdu_type), + isis_header->fixed_len, + isis_header->version, + isis_header->pdu_version, + id_length, + isis_header->id_length, + max_area, + isis_header->max_area)); + + if (ndo->ndo_vflag > 1) { + if (!print_unknown_data(ndo, optr, ""\n\t"", 8)) /* provide the _o_riginal pointer */ + return (0); /* for optionally debugging the common header */ + } + } + + switch (pdu_type) { + + case ISIS_PDU_L1_LAN_IIH: + case ISIS_PDU_L2_LAN_IIH: + if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE)) { + ND_PRINT((ndo, "", bogus fixed header length %u should be %lu"", + isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE))); + return (0); + } + ND_TCHECK(*header_iih_lan); + if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE) + goto trunc; + if (ndo->ndo_vflag == 0) { + ND_PRINT((ndo, "", src-id %s"", + isis_print_id(header_iih_lan->source_id, SYSTEM_ID_LEN))); + ND_PRINT((ndo, "", lan-id %s, prio %u"", + isis_print_id(header_iih_lan->lan_id,NODE_ID_LEN), + header_iih_lan->priority)); + ND_PRINT((ndo, "", length %u"", length)); + return (1); + } + pdu_len=EXTRACT_16BITS(header_iih_lan->pdu_len); + if (packet_len>pdu_len) { + packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ + length=pdu_len; + } + + ND_PRINT((ndo, ""\n\t source-id: %s, holding time: %us, Flags: [%s]"", + isis_print_id(header_iih_lan->source_id,SYSTEM_ID_LEN), + EXTRACT_16BITS(header_iih_lan->holding_time), + tok2str(isis_iih_circuit_type_values, + ""unknown circuit type 0x%02x"", + header_iih_lan->circuit_type))); + + ND_PRINT((ndo, ""\n\t lan-id: %s, Priority: %u, PDU length: %u"", + isis_print_id(header_iih_lan->lan_id, NODE_ID_LEN), + (header_iih_lan->priority) & ISIS_LAN_PRIORITY_MASK, + pdu_len)); + + if (ndo->ndo_vflag > 1) { + if (!print_unknown_data(ndo, pptr, ""\n\t "", ISIS_IIH_LAN_HEADER_SIZE)) + return (0); + } + + packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE); + pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_LAN_HEADER_SIZE); + break; + + case ISIS_PDU_PTP_IIH: + if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE)) { + ND_PRINT((ndo, "", bogus fixed header length %u should be %lu"", + isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE))); + return (0); + } + ND_TCHECK(*header_iih_ptp); + if (length < ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE) + goto trunc; + if (ndo->ndo_vflag == 0) { + ND_PRINT((ndo, "", src-id %s"", isis_print_id(header_iih_ptp->source_id, SYSTEM_ID_LEN))); + ND_PRINT((ndo, "", length %u"", length)); + return (1); + } + pdu_len=EXTRACT_16BITS(header_iih_ptp->pdu_len); + if (packet_len>pdu_len) { + packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ + length=pdu_len; + } + + ND_PRINT((ndo, ""\n\t source-id: %s, holding time: %us, Flags: [%s]"", + isis_print_id(header_iih_ptp->source_id,SYSTEM_ID_LEN), + EXTRACT_16BITS(header_iih_ptp->holding_time), + tok2str(isis_iih_circuit_type_values, + ""unknown circuit type 0x%02x"", + header_iih_ptp->circuit_type))); + + ND_PRINT((ndo, ""\n\t circuit-id: 0x%02x, PDU length: %u"", + header_iih_ptp->circuit_id, + pdu_len)); + + if (ndo->ndo_vflag > 1) { + if (!print_unknown_data(ndo, pptr, ""\n\t "", ISIS_IIH_PTP_HEADER_SIZE)) + return (0); + } + + packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE); + pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_IIH_PTP_HEADER_SIZE); + break; + + case ISIS_PDU_L1_LSP: + case ISIS_PDU_L2_LSP: + if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE)) { + ND_PRINT((ndo, "", bogus fixed header length %u should be %lu"", + isis_header->fixed_len, (unsigned long)ISIS_LSP_HEADER_SIZE)); + return (0); + } + ND_TCHECK(*header_lsp); + if (length < ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE) + goto trunc; + if (ndo->ndo_vflag == 0) { + ND_PRINT((ndo, "", lsp-id %s, seq 0x%08x, lifetime %5us"", + isis_print_id(header_lsp->lsp_id, LSP_ID_LEN), + EXTRACT_32BITS(header_lsp->sequence_number), + EXTRACT_16BITS(header_lsp->remaining_lifetime))); + ND_PRINT((ndo, "", length %u"", length)); + return (1); + } + pdu_len=EXTRACT_16BITS(header_lsp->pdu_len); + if (packet_len>pdu_len) { + packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ + length=pdu_len; + } + + ND_PRINT((ndo, ""\n\t lsp-id: %s, seq: 0x%08x, lifetime: %5us\n\t chksum: 0x%04x"", + isis_print_id(header_lsp->lsp_id, LSP_ID_LEN), + EXTRACT_32BITS(header_lsp->sequence_number), + EXTRACT_16BITS(header_lsp->remaining_lifetime), + EXTRACT_16BITS(header_lsp->checksum))); + + osi_print_cksum(ndo, (const uint8_t *)header_lsp->lsp_id, + EXTRACT_16BITS(header_lsp->checksum), + 12, length-12); + + ND_PRINT((ndo, "", PDU length: %u, Flags: [ %s"", + pdu_len, + ISIS_MASK_LSP_OL_BIT(header_lsp->typeblock) ? ""Overload bit set, "" : """")); + + if (ISIS_MASK_LSP_ATT_BITS(header_lsp->typeblock)) { + ND_PRINT((ndo, ""%s"", ISIS_MASK_LSP_ATT_DEFAULT_BIT(header_lsp->typeblock) ? ""default "" : """")); + ND_PRINT((ndo, ""%s"", ISIS_MASK_LSP_ATT_DELAY_BIT(header_lsp->typeblock) ? ""delay "" : """")); + ND_PRINT((ndo, ""%s"", ISIS_MASK_LSP_ATT_EXPENSE_BIT(header_lsp->typeblock) ? ""expense "" : """")); + ND_PRINT((ndo, ""%s"", ISIS_MASK_LSP_ATT_ERROR_BIT(header_lsp->typeblock) ? ""error "" : """")); + ND_PRINT((ndo, ""ATT bit set, "")); + } + ND_PRINT((ndo, ""%s"", ISIS_MASK_LSP_PARTITION_BIT(header_lsp->typeblock) ? ""P bit set, "" : """")); + ND_PRINT((ndo, ""%s ]"", tok2str(isis_lsp_istype_values, ""Unknown(0x%x)"", + ISIS_MASK_LSP_ISTYPE_BITS(header_lsp->typeblock)))); + + if (ndo->ndo_vflag > 1) { + if (!print_unknown_data(ndo, pptr, ""\n\t "", ISIS_LSP_HEADER_SIZE)) + return (0); + } + + packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE); + pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_LSP_HEADER_SIZE); + break; + + case ISIS_PDU_L1_CSNP: + case ISIS_PDU_L2_CSNP: + if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE)) { + ND_PRINT((ndo, "", bogus fixed header length %u should be %lu"", + isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE))); + return (0); + } + ND_TCHECK(*header_csnp); + if (length < ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE) + goto trunc; + if (ndo->ndo_vflag == 0) { + ND_PRINT((ndo, "", src-id %s"", isis_print_id(header_csnp->source_id, NODE_ID_LEN))); + ND_PRINT((ndo, "", length %u"", length)); + return (1); + } + pdu_len=EXTRACT_16BITS(header_csnp->pdu_len); + if (packet_len>pdu_len) { + packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ + length=pdu_len; + } + + ND_PRINT((ndo, ""\n\t source-id: %s, PDU length: %u"", + isis_print_id(header_csnp->source_id, NODE_ID_LEN), + pdu_len)); + ND_PRINT((ndo, ""\n\t start lsp-id: %s"", + isis_print_id(header_csnp->start_lsp_id, LSP_ID_LEN))); + ND_PRINT((ndo, ""\n\t end lsp-id: %s"", + isis_print_id(header_csnp->end_lsp_id, LSP_ID_LEN))); + + if (ndo->ndo_vflag > 1) { + if (!print_unknown_data(ndo, pptr, ""\n\t "", ISIS_CSNP_HEADER_SIZE)) + return (0); + } + + packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE); + pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_CSNP_HEADER_SIZE); + break; + + case ISIS_PDU_L1_PSNP: + case ISIS_PDU_L2_PSNP: + if (isis_header->fixed_len != (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE)) { + ND_PRINT((ndo, ""- bogus fixed header length %u should be %lu"", + isis_header->fixed_len, (unsigned long)(ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE))); + return (0); + } + ND_TCHECK(*header_psnp); + if (length < ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE) + goto trunc; + if (ndo->ndo_vflag == 0) { + ND_PRINT((ndo, "", src-id %s"", isis_print_id(header_psnp->source_id, NODE_ID_LEN))); + ND_PRINT((ndo, "", length %u"", length)); + return (1); + } + pdu_len=EXTRACT_16BITS(header_psnp->pdu_len); + if (packet_len>pdu_len) { + packet_len=pdu_len; /* do TLV decoding as long as it makes sense */ + length=pdu_len; + } + + ND_PRINT((ndo, ""\n\t source-id: %s, PDU length: %u"", + isis_print_id(header_psnp->source_id, NODE_ID_LEN), + pdu_len)); + + if (ndo->ndo_vflag > 1) { + if (!print_unknown_data(ndo, pptr, ""\n\t "", ISIS_PSNP_HEADER_SIZE)) + return (0); + } + + packet_len -= (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE); + pptr = p + (ISIS_COMMON_HEADER_SIZE+ISIS_PSNP_HEADER_SIZE); + break; + + default: + if (ndo->ndo_vflag == 0) { + ND_PRINT((ndo, "", length %u"", length)); + return (1); + } + (void)print_unknown_data(ndo, pptr, ""\n\t "", length); + return (0); + } + + /* + * Now print the TLV's. + */ + + while (packet_len > 0) { + ND_TCHECK2(*pptr, 2); + if (packet_len < 2) + goto trunc; + tlv_type = *pptr++; + tlv_len = *pptr++; + tmp =tlv_len; /* copy temporary len & pointer to packet data */ + tptr = pptr; + packet_len -= 2; + + /* first lets see if we know the TLVs name*/ + ND_PRINT((ndo, ""\n\t %s TLV #%u, length: %u"", + tok2str(isis_tlv_values, + ""unknown"", + tlv_type), + tlv_type, + tlv_len)); + + if (tlv_len == 0) /* something is invalid */ + continue; + + if (packet_len < tlv_len) + goto trunc; + + /* now check if we have a decoder otherwise do a hexdump at the end*/ + switch (tlv_type) { + case ISIS_TLV_AREA_ADDR: + ND_TCHECK2(*tptr, 1); + alen = *tptr++; + while (tmp && alen < tmp) { + ND_TCHECK2(*tptr, alen); + ND_PRINT((ndo, ""\n\t Area address (length: %u): %s"", + alen, + isonsap_string(ndo, tptr, alen))); + tptr += alen; + tmp -= alen + 1; + if (tmp==0) /* if this is the last area address do not attemt a boundary check */ + break; + ND_TCHECK2(*tptr, 1); + alen = *tptr++; + } + break; + case ISIS_TLV_ISNEIGH: + while (tmp >= ETHER_ADDR_LEN) { + ND_TCHECK2(*tptr, ETHER_ADDR_LEN); + ND_PRINT((ndo, ""\n\t SNPA: %s"", isis_print_id(tptr, ETHER_ADDR_LEN))); + tmp -= ETHER_ADDR_LEN; + tptr += ETHER_ADDR_LEN; + } + break; + + case ISIS_TLV_ISNEIGH_VARLEN: + if (!ND_TTEST2(*tptr, 1) || tmp < 3) /* min. TLV length */ + goto trunctlv; + lan_alen = *tptr++; /* LAN address length */ + if (lan_alen == 0) { + ND_PRINT((ndo, ""\n\t LAN address length 0 bytes (invalid)"")); + break; + } + tmp --; + ND_PRINT((ndo, ""\n\t LAN address length %u bytes "", lan_alen)); + while (tmp >= lan_alen) { + ND_TCHECK2(*tptr, lan_alen); + ND_PRINT((ndo, ""\n\t\tIS Neighbor: %s"", isis_print_id(tptr, lan_alen))); + tmp -= lan_alen; + tptr +=lan_alen; + } + break; + + case ISIS_TLV_PADDING: + break; + + case ISIS_TLV_MT_IS_REACH: + mt_len = isis_print_mtid(ndo, tptr, ""\n\t ""); + if (mt_len == 0) /* did something go wrong ? */ + goto trunctlv; + tptr+=mt_len; + tmp-=mt_len; + while (tmp >= 2+NODE_ID_LEN+3+1) { + ext_is_len = isis_print_ext_is_reach(ndo, tptr, ""\n\t "", tlv_type); + if (ext_is_len == 0) /* did something go wrong ? */ + goto trunctlv; + + tmp-=ext_is_len; + tptr+=ext_is_len; + } + break; + + case ISIS_TLV_IS_ALIAS_ID: + while (tmp >= NODE_ID_LEN+1) { /* is it worth attempting a decode ? */ + ext_is_len = isis_print_ext_is_reach(ndo, tptr, ""\n\t "", tlv_type); + if (ext_is_len == 0) /* did something go wrong ? */ + goto trunctlv; + tmp-=ext_is_len; + tptr+=ext_is_len; + } + break; + + case ISIS_TLV_EXT_IS_REACH: + while (tmp >= NODE_ID_LEN+3+1) { /* is it worth attempting a decode ? */ + ext_is_len = isis_print_ext_is_reach(ndo, tptr, ""\n\t "", tlv_type); + if (ext_is_len == 0) /* did something go wrong ? */ + goto trunctlv; + tmp-=ext_is_len; + tptr+=ext_is_len; + } + break; + case ISIS_TLV_IS_REACH: + ND_TCHECK2(*tptr,1); /* check if there is one byte left to read out the virtual flag */ + ND_PRINT((ndo, ""\n\t %s"", + tok2str(isis_is_reach_virtual_values, + ""bogus virtual flag 0x%02x"", + *tptr++))); + tlv_is_reach = (const struct isis_tlv_is_reach *)tptr; + while (tmp >= sizeof(struct isis_tlv_is_reach)) { + ND_TCHECK(*tlv_is_reach); + ND_PRINT((ndo, ""\n\t IS Neighbor: %s"", + isis_print_id(tlv_is_reach->neighbor_nodeid, NODE_ID_LEN))); + isis_print_metric_block(ndo, &tlv_is_reach->isis_metric_block); + tmp -= sizeof(struct isis_tlv_is_reach); + tlv_is_reach++; + } + break; + + case ISIS_TLV_ESNEIGH: + tlv_es_reach = (const struct isis_tlv_es_reach *)tptr; + while (tmp >= sizeof(struct isis_tlv_es_reach)) { + ND_TCHECK(*tlv_es_reach); + ND_PRINT((ndo, ""\n\t ES Neighbor: %s"", + isis_print_id(tlv_es_reach->neighbor_sysid, SYSTEM_ID_LEN))); + isis_print_metric_block(ndo, &tlv_es_reach->isis_metric_block); + tmp -= sizeof(struct isis_tlv_es_reach); + tlv_es_reach++; + } + break; + + /* those two TLVs share the same format */ + case ISIS_TLV_INT_IP_REACH: + case ISIS_TLV_EXT_IP_REACH: + if (!isis_print_tlv_ip_reach(ndo, pptr, ""\n\t "", tlv_len)) + return (1); + break; + + case ISIS_TLV_EXTD_IP_REACH: + while (tmp>0) { + ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, ""\n\t "", AF_INET); + if (ext_ip_len == 0) /* did something go wrong ? */ + goto trunctlv; + tptr+=ext_ip_len; + tmp-=ext_ip_len; + } + break; + + case ISIS_TLV_MT_IP_REACH: + mt_len = isis_print_mtid(ndo, tptr, ""\n\t ""); + if (mt_len == 0) { /* did something go wrong ? */ + goto trunctlv; + } + tptr+=mt_len; + tmp-=mt_len; + + while (tmp>0) { + ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, ""\n\t "", AF_INET); + if (ext_ip_len == 0) /* did something go wrong ? */ + goto trunctlv; + tptr+=ext_ip_len; + tmp-=ext_ip_len; + } + break; + + case ISIS_TLV_IP6_REACH: + while (tmp>0) { + ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, ""\n\t "", AF_INET6); + if (ext_ip_len == 0) /* did something go wrong ? */ + goto trunctlv; + tptr+=ext_ip_len; + tmp-=ext_ip_len; + } + break; + + case ISIS_TLV_MT_IP6_REACH: + mt_len = isis_print_mtid(ndo, tptr, ""\n\t ""); + if (mt_len == 0) { /* did something go wrong ? */ + goto trunctlv; + } + tptr+=mt_len; + tmp-=mt_len; + + while (tmp>0) { + ext_ip_len = isis_print_extd_ip_reach(ndo, tptr, ""\n\t "", AF_INET6); + if (ext_ip_len == 0) /* did something go wrong ? */ + goto trunctlv; + tptr+=ext_ip_len; + tmp-=ext_ip_len; + } + break; + + case ISIS_TLV_IP6ADDR: + while (tmp>=sizeof(struct in6_addr)) { + ND_TCHECK2(*tptr, sizeof(struct in6_addr)); + + ND_PRINT((ndo, ""\n\t IPv6 interface address: %s"", + ip6addr_string(ndo, tptr))); + + tptr += sizeof(struct in6_addr); + tmp -= sizeof(struct in6_addr); + } + break; + case ISIS_TLV_AUTH: + ND_TCHECK2(*tptr, 1); + + ND_PRINT((ndo, ""\n\t %s: "", + tok2str(isis_subtlv_auth_values, + ""unknown Authentication type 0x%02x"", + *tptr))); + + switch (*tptr) { + case ISIS_SUBTLV_AUTH_SIMPLE: + if (fn_printzp(ndo, tptr + 1, tlv_len - 1, ndo->ndo_snapend)) + goto trunctlv; + break; + case ISIS_SUBTLV_AUTH_MD5: + for(i=1;i=1) { + ND_TCHECK2(*tptr, 1); + ND_PRINT((ndo, ""\n\t Adjacency State: %s (%u)"", + tok2str(isis_ptp_adjancey_values, ""unknown"", *tptr), + *tptr)); + tmp--; + } + if(tmp>sizeof(tlv_ptp_adj->extd_local_circuit_id)) { + ND_TCHECK(tlv_ptp_adj->extd_local_circuit_id); + ND_PRINT((ndo, ""\n\t Extended Local circuit-ID: 0x%08x"", + EXTRACT_32BITS(tlv_ptp_adj->extd_local_circuit_id))); + tmp-=sizeof(tlv_ptp_adj->extd_local_circuit_id); + } + if(tmp>=SYSTEM_ID_LEN) { + ND_TCHECK2(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN); + ND_PRINT((ndo, ""\n\t Neighbor System-ID: %s"", + isis_print_id(tlv_ptp_adj->neighbor_sysid, SYSTEM_ID_LEN))); + tmp-=SYSTEM_ID_LEN; + } + if(tmp>=sizeof(tlv_ptp_adj->neighbor_extd_local_circuit_id)) { + ND_TCHECK(tlv_ptp_adj->neighbor_extd_local_circuit_id); + ND_PRINT((ndo, ""\n\t Neighbor Extended Local circuit-ID: 0x%08x"", + EXTRACT_32BITS(tlv_ptp_adj->neighbor_extd_local_circuit_id))); + } + break; + + case ISIS_TLV_PROTOCOLS: + ND_PRINT((ndo, ""\n\t NLPID(s): "")); + while (tmp>0) { + ND_TCHECK2(*(tptr), 1); + ND_PRINT((ndo, ""%s (0x%02x)"", + tok2str(nlpid_values, + ""unknown"", + *tptr), + *tptr)); + if (tmp>1) /* further NPLIDs ? - put comma */ + ND_PRINT((ndo, "", "")); + tptr++; + tmp--; + } + break; + + case ISIS_TLV_MT_PORT_CAP: + { + ND_TCHECK2(*(tptr), 2); + + ND_PRINT((ndo, ""\n\t RES: %d, MTID(s): %d"", + (EXTRACT_16BITS (tptr) >> 12), + (EXTRACT_16BITS (tptr) & 0x0fff))); + + tmp = tmp-2; + tptr = tptr+2; + + if (tmp) + isis_print_mt_port_cap_subtlv(ndo, tptr, tmp); + + break; + } + + case ISIS_TLV_MT_CAPABILITY: + + ND_TCHECK2(*(tptr), 2); + + ND_PRINT((ndo, ""\n\t O: %d, RES: %d, MTID(s): %d"", + (EXTRACT_16BITS(tptr) >> 15) & 0x01, + (EXTRACT_16BITS(tptr) >> 12) & 0x07, + EXTRACT_16BITS(tptr) & 0x0fff)); + + tmp = tmp-2; + tptr = tptr+2; + + if (tmp) + isis_print_mt_capability_subtlv(ndo, tptr, tmp); + + break; + + case ISIS_TLV_TE_ROUTER_ID: + ND_TCHECK2(*pptr, sizeof(struct in_addr)); + ND_PRINT((ndo, ""\n\t Traffic Engineering Router ID: %s"", ipaddr_string(ndo, pptr))); + break; + + case ISIS_TLV_IPADDR: + while (tmp>=sizeof(struct in_addr)) { + ND_TCHECK2(*tptr, sizeof(struct in_addr)); + ND_PRINT((ndo, ""\n\t IPv4 interface address: %s"", ipaddr_string(ndo, tptr))); + tptr += sizeof(struct in_addr); + tmp -= sizeof(struct in_addr); + } + break; + + case ISIS_TLV_HOSTNAME: + ND_PRINT((ndo, ""\n\t Hostname: "")); + if (fn_printzp(ndo, tptr, tmp, ndo->ndo_snapend)) + goto trunctlv; + break; + + case ISIS_TLV_SHARED_RISK_GROUP: + if (tmp < NODE_ID_LEN) + break; + ND_TCHECK2(*tptr, NODE_ID_LEN); + ND_PRINT((ndo, ""\n\t IS Neighbor: %s"", isis_print_id(tptr, NODE_ID_LEN))); + tptr+=(NODE_ID_LEN); + tmp-=(NODE_ID_LEN); + + if (tmp < 1) + break; + ND_TCHECK2(*tptr, 1); + ND_PRINT((ndo, "", Flags: [%s]"", ISIS_MASK_TLV_SHARED_RISK_GROUP(*tptr++) ? ""numbered"" : ""unnumbered"")); + tmp--; + + if (tmp < sizeof(struct in_addr)) + break; + ND_TCHECK2(*tptr, sizeof(struct in_addr)); + ND_PRINT((ndo, ""\n\t IPv4 interface address: %s"", ipaddr_string(ndo, tptr))); + tptr+=sizeof(struct in_addr); + tmp-=sizeof(struct in_addr); + + if (tmp < sizeof(struct in_addr)) + break; + ND_TCHECK2(*tptr, sizeof(struct in_addr)); + ND_PRINT((ndo, ""\n\t IPv4 neighbor address: %s"", ipaddr_string(ndo, tptr))); + tptr+=sizeof(struct in_addr); + tmp-=sizeof(struct in_addr); + + while (tmp>=4) { + ND_TCHECK2(*tptr, 4); + ND_PRINT((ndo, ""\n\t Link-ID: 0x%08x"", EXTRACT_32BITS(tptr))); + tptr+=4; + tmp-=4; + } + break; + + case ISIS_TLV_LSP: + tlv_lsp = (const struct isis_tlv_lsp *)tptr; + while(tmp>=sizeof(struct isis_tlv_lsp)) { + ND_TCHECK((tlv_lsp->lsp_id)[LSP_ID_LEN-1]); + ND_PRINT((ndo, ""\n\t lsp-id: %s"", + isis_print_id(tlv_lsp->lsp_id, LSP_ID_LEN))); + ND_TCHECK2(tlv_lsp->sequence_number, 4); + ND_PRINT((ndo, "", seq: 0x%08x"", EXTRACT_32BITS(tlv_lsp->sequence_number))); + ND_TCHECK2(tlv_lsp->remaining_lifetime, 2); + ND_PRINT((ndo, "", lifetime: %5ds"", EXTRACT_16BITS(tlv_lsp->remaining_lifetime))); + ND_TCHECK2(tlv_lsp->checksum, 2); + ND_PRINT((ndo, "", chksum: 0x%04x"", EXTRACT_16BITS(tlv_lsp->checksum))); + tmp-=sizeof(struct isis_tlv_lsp); + tlv_lsp++; + } + break; + + case ISIS_TLV_CHECKSUM: + if (tmp < ISIS_TLV_CHECKSUM_MINLEN) + break; + ND_TCHECK2(*tptr, ISIS_TLV_CHECKSUM_MINLEN); + ND_PRINT((ndo, ""\n\t checksum: 0x%04x "", EXTRACT_16BITS(tptr))); + /* do not attempt to verify the checksum if it is zero + * most likely a HMAC-MD5 TLV is also present and + * to avoid conflicts the checksum TLV is zeroed. + * see rfc3358 for details + */ + osi_print_cksum(ndo, optr, EXTRACT_16BITS(tptr), tptr-optr, + length); + break; + + case ISIS_TLV_POI: + if (tlv_len >= SYSTEM_ID_LEN + 1) { + ND_TCHECK2(*tptr, SYSTEM_ID_LEN + 1); + ND_PRINT((ndo, ""\n\t Purge Originator System-ID: %s"", + isis_print_id(tptr + 1, SYSTEM_ID_LEN))); + } + + if (tlv_len == 2 * SYSTEM_ID_LEN + 1) { + ND_TCHECK2(*tptr, 2 * SYSTEM_ID_LEN + 1); + ND_PRINT((ndo, ""\n\t Received from System-ID: %s"", + isis_print_id(tptr + SYSTEM_ID_LEN + 1, SYSTEM_ID_LEN))); + } + break; + + case ISIS_TLV_MT_SUPPORTED: + if (tmp < ISIS_TLV_MT_SUPPORTED_MINLEN) + break; + while (tmp>1) { + /* length can only be a multiple of 2, otherwise there is + something broken -> so decode down until length is 1 */ + if (tmp!=1) { + mt_len = isis_print_mtid(ndo, tptr, ""\n\t ""); + if (mt_len == 0) /* did something go wrong ? */ + goto trunctlv; + tptr+=mt_len; + tmp-=mt_len; + } else { + ND_PRINT((ndo, ""\n\t invalid MT-ID"")); + break; + } + } + break; + + case ISIS_TLV_RESTART_SIGNALING: + /* first attempt to decode the flags */ + if (tmp < ISIS_TLV_RESTART_SIGNALING_FLAGLEN) + break; + ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_FLAGLEN); + ND_PRINT((ndo, ""\n\t Flags [%s]"", + bittok2str(isis_restart_flag_values, ""none"", *tptr))); + tptr+=ISIS_TLV_RESTART_SIGNALING_FLAGLEN; + tmp-=ISIS_TLV_RESTART_SIGNALING_FLAGLEN; + + /* is there anything other than the flags field? */ + if (tmp == 0) + break; + + if (tmp < ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN) + break; + ND_TCHECK2(*tptr, ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN); + + ND_PRINT((ndo, "", Remaining holding time %us"", EXTRACT_16BITS(tptr))); + tptr+=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN; + tmp-=ISIS_TLV_RESTART_SIGNALING_HOLDTIMELEN; + + /* is there an additional sysid field present ?*/ + if (tmp == SYSTEM_ID_LEN) { + ND_TCHECK2(*tptr, SYSTEM_ID_LEN); + ND_PRINT((ndo, "", for %s"", isis_print_id(tptr,SYSTEM_ID_LEN))); + } + break; + + case ISIS_TLV_IDRP_INFO: + if (tmp < ISIS_TLV_IDRP_INFO_MINLEN) + break; + ND_TCHECK2(*tptr, ISIS_TLV_IDRP_INFO_MINLEN); + ND_PRINT((ndo, ""\n\t Inter-Domain Information Type: %s"", + tok2str(isis_subtlv_idrp_values, + ""Unknown (0x%02x)"", + *tptr))); + switch (*tptr++) { + case ISIS_SUBTLV_IDRP_ASN: + ND_TCHECK2(*tptr, 2); /* fetch AS number */ + ND_PRINT((ndo, ""AS Number: %u"", EXTRACT_16BITS(tptr))); + break; + case ISIS_SUBTLV_IDRP_LOCAL: + case ISIS_SUBTLV_IDRP_RES: + default: + if (!print_unknown_data(ndo, tptr, ""\n\t "", tlv_len - 1)) + return(0); + break; + } + break; + + case ISIS_TLV_LSP_BUFFERSIZE: + if (tmp < ISIS_TLV_LSP_BUFFERSIZE_MINLEN) + break; + ND_TCHECK2(*tptr, ISIS_TLV_LSP_BUFFERSIZE_MINLEN); + ND_PRINT((ndo, ""\n\t LSP Buffersize: %u"", EXTRACT_16BITS(tptr))); + break; + + case ISIS_TLV_PART_DIS: + while (tmp >= SYSTEM_ID_LEN) { + ND_TCHECK2(*tptr, SYSTEM_ID_LEN); + ND_PRINT((ndo, ""\n\t %s"", isis_print_id(tptr, SYSTEM_ID_LEN))); + tptr+=SYSTEM_ID_LEN; + tmp-=SYSTEM_ID_LEN; + } + break; + + case ISIS_TLV_PREFIX_NEIGH: + if (tmp < sizeof(struct isis_metric_block)) + break; + ND_TCHECK2(*tptr, sizeof(struct isis_metric_block)); + ND_PRINT((ndo, ""\n\t Metric Block"")); + isis_print_metric_block(ndo, (const struct isis_metric_block *)tptr); + tptr+=sizeof(struct isis_metric_block); + tmp-=sizeof(struct isis_metric_block); + + while(tmp>0) { + ND_TCHECK2(*tptr, 1); + prefix_len=*tptr++; /* read out prefix length in semioctets*/ + if (prefix_len < 2) { + ND_PRINT((ndo, ""\n\t\tAddress: prefix length %u < 2"", prefix_len)); + break; + } + tmp--; + if (tmp < prefix_len/2) + break; + ND_TCHECK2(*tptr, prefix_len / 2); + ND_PRINT((ndo, ""\n\t\tAddress: %s/%u"", + isonsap_string(ndo, tptr, prefix_len / 2), prefix_len * 4)); + tptr+=prefix_len/2; + tmp-=prefix_len/2; + } + break; + + case ISIS_TLV_IIH_SEQNR: + if (tmp < ISIS_TLV_IIH_SEQNR_MINLEN) + break; + ND_TCHECK2(*tptr, ISIS_TLV_IIH_SEQNR_MINLEN); /* check if four bytes are on the wire */ + ND_PRINT((ndo, ""\n\t Sequence number: %u"", EXTRACT_32BITS(tptr))); + break; + + case ISIS_TLV_VENDOR_PRIVATE: + if (tmp < ISIS_TLV_VENDOR_PRIVATE_MINLEN) + break; + ND_TCHECK2(*tptr, ISIS_TLV_VENDOR_PRIVATE_MINLEN); /* check if enough byte for a full oui */ + vendor_id = EXTRACT_24BITS(tptr); + ND_PRINT((ndo, ""\n\t Vendor: %s (%u)"", + tok2str(oui_values, ""Unknown"", vendor_id), + vendor_id)); + tptr+=3; + tmp-=3; + if (tmp > 0) /* hexdump the rest */ + if (!print_unknown_data(ndo, tptr, ""\n\t\t"", tmp)) + return(0); + break; + /* + * FIXME those are the defined TLVs that lack a decoder + * you are welcome to contribute code ;-) + */ + + case ISIS_TLV_DECNET_PHASE4: + case ISIS_TLV_LUCENT_PRIVATE: + case ISIS_TLV_IPAUTH: + case ISIS_TLV_NORTEL_PRIVATE1: + case ISIS_TLV_NORTEL_PRIVATE2: + + default: + if (ndo->ndo_vflag <= 1) { + if (!print_unknown_data(ndo, pptr, ""\n\t\t"", tlv_len)) + return(0); + } + break; + } + /* do we want to see an additionally hexdump ? */ + if (ndo->ndo_vflag> 1) { + if (!print_unknown_data(ndo, pptr, ""\n\t "", tlv_len)) + return(0); + } + + pptr += tlv_len; + packet_len -= tlv_len; + } + + if (packet_len != 0) { + ND_PRINT((ndo, ""\n\t %u straggler bytes"", packet_len)); + } + return (1); + + trunc: + ND_PRINT((ndo, ""%s"", tstr)); + return (1); + + trunctlv: + ND_PRINT((ndo, ""\n\t\t"")); + ND_PRINT((ndo, ""%s"", tstr)); + return(1); +} +","@@ -2532,6 +2532,7 @@ isis_print(netdissect_options *ndo, + ND_TCHECK2(*tptr, 1); + alen = *tptr++; + while (tmp && alen < tmp) { ++ ND_TCHECK2(*tptr, alen); + ND_PRINT((ndo, ""\n\t Area address (length: %u): %s"", + alen, + isonsap_string(ndo, tptr, alen)));",9848,10179,11000 +18805,"WORD32 ih264d_parse_decode_slice(UWORD8 u1_is_idr_slice, + UWORD8 u1_nal_ref_idc, + dec_struct_t *ps_dec /* Decoder parameters */ + ) +{ + dec_bit_stream_t * ps_bitstrm = ps_dec->ps_bitstrm; + dec_pic_params_t *ps_pps; + dec_seq_params_t *ps_seq; + dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice; + pocstruct_t s_tmp_poc; + WORD32 i_delta_poc[2]; + WORD32 i4_poc = 0; + UWORD16 u2_first_mb_in_slice, u2_frame_num; + UWORD8 u1_field_pic_flag, u1_redundant_pic_cnt = 0, u1_slice_type; + UWORD32 u4_idr_pic_id = 0; + UWORD8 u1_bottom_field_flag, u1_pic_order_cnt_type; + + UWORD8 u1_nal_unit_type; + UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; + UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; + WORD8 i1_is_end_of_poc; + + WORD32 ret, end_of_frame; + WORD32 prev_slice_err, num_mb_skipped; + UWORD8 u1_mbaff; + pocstruct_t *ps_cur_poc; + + UWORD32 u4_temp; + WORD32 i_temp; + UWORD32 u4_call_end_of_pic = 0; + + /* read FirstMbInSlice and slice type*/ + ps_dec->ps_dpb_cmds->u1_dpb_commands_read_slc = 0; + u2_first_mb_in_slice = ih264d_uev(pu4_bitstrm_ofst, + pu4_bitstrm_buf); + if(u2_first_mb_in_slice + > (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)) + { + + return ERROR_CORRUPTED_SLICE; + } + + /*we currently don not support ASO*/ + if(((u2_first_mb_in_slice << ps_cur_slice->u1_mbaff_frame_flag) + <= ps_dec->u2_cur_mb_addr) && (ps_dec->u4_first_slice_in_pic == 0)) + { + return ERROR_CORRUPTED_SLICE; + } + + COPYTHECONTEXT(""SH: first_mb_in_slice"",u2_first_mb_in_slice); + + u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); + + if(u4_temp > 9) + return ERROR_INV_SLC_TYPE_T; + + u1_slice_type = u4_temp; + COPYTHECONTEXT(""SH: slice_type"",(u1_slice_type)); + ps_dec->u1_sl_typ_5_9 = 0; + /* Find Out the Slice Type is 5 to 9 or not then Set the Flag */ + /* u1_sl_typ_5_9 = 1 .Which tells that all the slices in the Pic*/ + /* will be of same type of current */ + if(u1_slice_type > 4) + { + u1_slice_type -= 5; + ps_dec->u1_sl_typ_5_9 = 1; + } + + { + UWORD32 skip; + + if((ps_dec->i4_app_skip_mode == IVD_SKIP_PB) + || (ps_dec->i4_dec_skip_mode == IVD_SKIP_PB)) + { + UWORD32 u4_bit_stream_offset = 0; + + if(ps_dec->u1_nal_unit_type == IDR_SLICE_NAL) + { + skip = 0; + + ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE; + } + else if((I_SLICE == u1_slice_type) + && (1 >= ps_dec->ps_cur_sps->u1_num_ref_frames)) + { + skip = 0; + + ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE; + } + else + { + skip = 1; + } + + /* If one frame worth of data is already skipped, do not skip the next one */ + if((0 == u2_first_mb_in_slice) && (1 == ps_dec->u4_prev_nal_skipped)) + { + skip = 0; + } + + if(skip) + { + ps_dec->u4_prev_nal_skipped = 1; + ps_dec->i4_dec_skip_mode = IVD_SKIP_PB; + return 0; + } + else + { + /* If the previous NAL was skipped, then + do not process that buffer in this call. + Return to app and process it in the next call. + This is necessary to handle cases where I/IDR is not complete in + the current buffer and application intends to fill the remaining part of the bitstream + later. This ensures we process only frame worth of data in every call */ + if(1 == ps_dec->u4_prev_nal_skipped) + { + ps_dec->u4_return_to_app = 1; + return 0; + } + } + } + + } + + u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); + if(u4_temp & MASK_ERR_PIC_SET_ID) + return ERROR_INV_SLICE_HDR_T; + /* discard slice if pic param is invalid */ + COPYTHECONTEXT(""SH: pic_parameter_set_id"", u4_temp); + ps_pps = &ps_dec->ps_pps[u4_temp]; + if(FALSE == ps_pps->u1_is_valid) + { + return ERROR_INV_SLICE_HDR_T; + } + ps_seq = ps_pps->ps_sps; + if(!ps_seq) + return ERROR_INV_SLICE_HDR_T; + if(FALSE == ps_seq->u1_is_valid) + return ERROR_INV_SLICE_HDR_T; + + /* Get the frame num */ + u2_frame_num = ih264d_get_bits_h264(ps_bitstrm, + ps_seq->u1_bits_in_frm_num); + + + COPYTHECONTEXT(""SH: frame_num"", u2_frame_num); + if(!ps_dec->u1_first_slice_in_stream && (ps_dec->u4_first_slice_in_pic == 2)) + { + pocstruct_t *ps_prev_poc = &ps_dec->s_prev_pic_poc; + pocstruct_t *ps_cur_poc = &ps_dec->s_cur_pic_poc; + + ps_dec->u2_mbx = 0xffff; + ps_dec->u2_mby = 0; + + if((0 == u1_is_idr_slice) && ps_cur_slice->u1_nal_ref_idc) + ps_dec->u2_prev_ref_frame_num = ps_cur_slice->u2_frame_num; + + if(u1_is_idr_slice || ps_cur_slice->u1_mmco_equalto5) + ps_dec->u2_prev_ref_frame_num = 0; + + if(ps_dec->ps_cur_sps->u1_gaps_in_frame_num_value_allowed_flag) + { + ih264d_decode_gaps_in_frame_num(ps_dec, u2_frame_num); + } + + ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst; + ps_prev_poc->u2_frame_num = ps_cur_poc->u2_frame_num; + ps_prev_poc->u1_mmco_equalto5 = ps_cur_slice->u1_mmco_equalto5; + if(ps_cur_slice->u1_nal_ref_idc) + { + ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb; + ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb; + ps_prev_poc->i4_delta_pic_order_cnt_bottom = + ps_cur_poc->i4_delta_pic_order_cnt_bottom; + ps_prev_poc->i4_delta_pic_order_cnt[0] = + ps_cur_poc->i4_delta_pic_order_cnt[0]; + ps_prev_poc->i4_delta_pic_order_cnt[1] = + ps_cur_poc->i4_delta_pic_order_cnt[1]; + ps_prev_poc->u1_bot_field = ps_cur_poc->u1_bot_field; + } + + ps_dec->u2_total_mbs_coded = 0; + } + /* Get the field related flags */ + if(!ps_seq->u1_frame_mbs_only_flag) + { + + u1_field_pic_flag = ih264d_get_bit_h264(ps_bitstrm); + COPYTHECONTEXT(""SH: field_pic_flag"", u1_field_pic_flag); + u1_bottom_field_flag = 0; + + if(u1_field_pic_flag) + { + ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan_fld; + u1_bottom_field_flag = ih264d_get_bit_h264(ps_bitstrm); + COPYTHECONTEXT(""SH: bottom_field_flag"", u1_bottom_field_flag); + + } + else + { + ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan; + } + } + else + { + u1_field_pic_flag = 0; + u1_bottom_field_flag = 0; + + ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan; + } + + u1_nal_unit_type = SLICE_NAL; + if(u1_is_idr_slice) + { + if(0 == u1_field_pic_flag) + { + ps_dec->u1_top_bottom_decoded = TOP_FIELD_ONLY | BOT_FIELD_ONLY; + } + u1_nal_unit_type = IDR_SLICE_NAL; + u4_idr_pic_id = ih264d_uev(pu4_bitstrm_ofst, + pu4_bitstrm_buf); + if(u4_idr_pic_id > 65535) + return ERROR_INV_SLICE_HDR_T; + COPYTHECONTEXT(""SH: "", u4_idr_pic_id); + } + + /* read delta pic order count information*/ + i_delta_poc[0] = i_delta_poc[1] = 0; + s_tmp_poc.i4_pic_order_cnt_lsb = 0; + s_tmp_poc.i4_delta_pic_order_cnt_bottom = 0; + u1_pic_order_cnt_type = ps_seq->u1_pic_order_cnt_type; + if(u1_pic_order_cnt_type == 0) + { + i_temp = ih264d_get_bits_h264( + ps_bitstrm, + ps_seq->u1_log2_max_pic_order_cnt_lsb_minus); + if(i_temp < 0 || i_temp >= ps_seq->i4_max_pic_order_cntLsb) + return ERROR_INV_SLICE_HDR_T; + s_tmp_poc.i4_pic_order_cnt_lsb = i_temp; + COPYTHECONTEXT(""SH: pic_order_cnt_lsb"", s_tmp_poc.i4_pic_order_cnt_lsb); + + if((ps_pps->u1_pic_order_present_flag == 1) && (!u1_field_pic_flag)) + { + s_tmp_poc.i4_delta_pic_order_cnt_bottom = ih264d_sev( + pu4_bitstrm_ofst, pu4_bitstrm_buf); + COPYTHECONTEXT(""SH: delta_pic_order_cnt_bottom"", + s_tmp_poc.i4_delta_pic_order_cnt_bottom); + } + } + + s_tmp_poc.i4_delta_pic_order_cnt[0] = 0; + s_tmp_poc.i4_delta_pic_order_cnt[1] = 0; + if(u1_pic_order_cnt_type == 1 + && (!ps_seq->u1_delta_pic_order_always_zero_flag)) + { + s_tmp_poc.i4_delta_pic_order_cnt[0] = ih264d_sev(pu4_bitstrm_ofst, + pu4_bitstrm_buf); + COPYTHECONTEXT(""SH: delta_pic_order_cnt[0]"", + s_tmp_poc.i4_delta_pic_order_cnt[0]); + + if(ps_pps->u1_pic_order_present_flag && !u1_field_pic_flag) + { + s_tmp_poc.i4_delta_pic_order_cnt[1] = ih264d_sev( + pu4_bitstrm_ofst, pu4_bitstrm_buf); + COPYTHECONTEXT(""SH: delta_pic_order_cnt[1]"", + s_tmp_poc.i4_delta_pic_order_cnt[1]); + } + } + + if(ps_pps->u1_redundant_pic_cnt_present_flag) + { + u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); + if(u4_temp > MAX_REDUNDANT_PIC_CNT) + return ERROR_INV_SLICE_HDR_T; + u1_redundant_pic_cnt = u4_temp; + COPYTHECONTEXT(""SH: redundant_pic_cnt"", u1_redundant_pic_cnt); + } + + /*--------------------------------------------------------------------*/ + /* Check if the slice is part of new picture */ + /*--------------------------------------------------------------------*/ + /* First slice of a picture is always considered as part of new picture */ + + i1_is_end_of_poc = 1; + ps_dec->ps_dec_err_status->u1_err_flag &= MASK_REJECT_CUR_PIC; + + if(ps_dec->u4_first_slice_in_pic != 2) + { + i1_is_end_of_poc = ih264d_is_end_of_pic(u2_frame_num, u1_nal_ref_idc, + &s_tmp_poc, &ps_dec->s_cur_pic_poc, + ps_cur_slice, u1_pic_order_cnt_type, + u1_nal_unit_type, u4_idr_pic_id, + u1_field_pic_flag, + u1_bottom_field_flag); + if(i1_is_end_of_poc) + { + ps_dec->u1_first_slice_in_stream = 0; + return ERROR_INCOMPLETE_FRAME; + } + + } + + /*--------------------------------------------------------------------*/ + /* Check for error in slice and parse the missing/corrupted MB's */ + /* as skip-MB's in an inserted P-slice */ + /*--------------------------------------------------------------------*/ + u1_mbaff = ps_seq->u1_mb_aff_flag && (!u1_field_pic_flag); + prev_slice_err = 0; + + if(i1_is_end_of_poc || ps_dec->u1_first_slice_in_stream) + { + if(u2_frame_num != ps_dec->u2_prv_frame_num + && ps_dec->u1_top_bottom_decoded != 0 + && ps_dec->u1_top_bottom_decoded + != (TOP_FIELD_ONLY | BOT_FIELD_ONLY)) + { + ps_dec->u1_dangling_field = 1; + if(ps_dec->u4_first_slice_in_pic) + { + prev_slice_err = 1; + } + else + { + prev_slice_err = 2; + } + + if(ps_dec->u1_top_bottom_decoded ==TOP_FIELD_ONLY) + ps_cur_slice->u1_bottom_field_flag = 1; + else + ps_cur_slice->u1_bottom_field_flag = 0; + + num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) + - ps_dec->u2_total_mbs_coded; + ps_cur_poc = &ps_dec->s_cur_pic_poc; + + + u1_is_idr_slice = ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL; + } + else if(ps_dec->u4_first_slice_in_pic == 2) + { + if(u2_first_mb_in_slice > 0) + { + prev_slice_err = 1; + num_mb_skipped = u2_first_mb_in_slice << u1_mbaff; + ps_cur_poc = &s_tmp_poc; + + ps_cur_slice->u4_idr_pic_id = u4_idr_pic_id; + ps_cur_slice->u1_field_pic_flag = u1_field_pic_flag; + ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag; + ps_cur_slice->i4_pic_order_cnt_lsb = + s_tmp_poc.i4_pic_order_cnt_lsb; + ps_cur_slice->u1_nal_unit_type = u1_nal_unit_type; + ps_cur_slice->u1_redundant_pic_cnt = u1_redundant_pic_cnt; + ps_cur_slice->u1_nal_ref_idc = u1_nal_ref_idc; + ps_cur_slice->u1_pic_order_cnt_type = u1_pic_order_cnt_type; + ps_cur_slice->u1_mbaff_frame_flag = ps_seq->u1_mb_aff_flag + && (!u1_field_pic_flag); + } + + } + else + { + if(ps_dec->u4_first_slice_in_pic) + { + /* if valid slice header is not decoded do start of pic processing + * since in the current process call, frame num is not updated in the slice structure yet + * ih264d_is_end_of_pic is checked with valid frame num of previous process call, + * although i1_is_end_of_poc is set there could be more slices in the frame, + * so conceal only till cur slice */ + prev_slice_err = 1; + num_mb_skipped = u2_first_mb_in_slice << u1_mbaff; + } + else + { + /* since i1_is_end_of_poc is set ,means new frame num is encountered. so conceal the current frame + * completely */ + prev_slice_err = 2; + num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) + - ps_dec->u2_total_mbs_coded; + } + ps_cur_poc = &s_tmp_poc; + } + } + else + { + if((u2_first_mb_in_slice << u1_mbaff) > ps_dec->u2_total_mbs_coded) + { + prev_slice_err = 2; + num_mb_skipped = (u2_first_mb_in_slice << u1_mbaff) + - ps_dec->u2_total_mbs_coded; + ps_cur_poc = &s_tmp_poc; + } + else if((u2_first_mb_in_slice << u1_mbaff) < ps_dec->u2_total_mbs_coded) + { + return ERROR_CORRUPTED_SLICE; + } + } + + if(prev_slice_err) + { + ret = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, u1_is_idr_slice, u2_frame_num, ps_cur_poc, prev_slice_err); + + if(ps_dec->u1_dangling_field == 1) + { + ps_dec->u1_second_field = 1 - ps_dec->u1_second_field; + ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag; + ps_dec->u2_prv_frame_num = u2_frame_num; + ps_dec->u1_first_slice_in_stream = 0; + return ERROR_DANGLING_FIELD_IN_PIC; + } + + if(prev_slice_err == 2) + { + ps_dec->u1_first_slice_in_stream = 0; + return ERROR_INCOMPLETE_FRAME; + } + + if(ps_dec->u2_total_mbs_coded + >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) + { + /* return if all MBs in frame are parsed*/ + ps_dec->u1_first_slice_in_stream = 0; + return ERROR_IN_LAST_SLICE_OF_PIC; + } + + if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) + { + ih264d_err_pic_dispbuf_mgr(ps_dec); + return ERROR_NEW_FRAME_EXPECTED; + } + + if(ret != OK) + return ret; + + i1_is_end_of_poc = 0; + } + + if (ps_dec->u4_first_slice_in_pic == 0) + { + ps_dec->ps_parse_cur_slice++; + ps_dec->u2_cur_slice_num++; + } + + if((ps_dec->u1_separate_parse == 0) && (ps_dec->u4_first_slice_in_pic == 0)) + { + ps_dec->ps_decode_cur_slice++; + } + ps_dec->u1_slice_header_done = 0; + + + if(u1_field_pic_flag) + { + ps_dec->u2_prv_frame_num = u2_frame_num; + } + + if(ps_cur_slice->u1_mmco_equalto5) + { + WORD32 i4_temp_poc; + WORD32 i4_top_field_order_poc, i4_bot_field_order_poc; + + if(!ps_cur_slice->u1_field_pic_flag) // or a complementary field pair + { + i4_top_field_order_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt; + i4_bot_field_order_poc = + ps_dec->ps_cur_pic->i4_bottom_field_order_cnt; + i4_temp_poc = MIN(i4_top_field_order_poc, + i4_bot_field_order_poc); + } + else if(!ps_cur_slice->u1_bottom_field_flag) + i4_temp_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt; + else + i4_temp_poc = ps_dec->ps_cur_pic->i4_bottom_field_order_cnt; + + ps_dec->ps_cur_pic->i4_top_field_order_cnt = i4_temp_poc + - ps_dec->ps_cur_pic->i4_top_field_order_cnt; + ps_dec->ps_cur_pic->i4_bottom_field_order_cnt = i4_temp_poc + - ps_dec->ps_cur_pic->i4_bottom_field_order_cnt; + + ps_dec->ps_cur_pic->i4_poc = i4_temp_poc; + ps_dec->ps_cur_pic->i4_avg_poc = i4_temp_poc; + } + if(ps_dec->u4_first_slice_in_pic == 2) + { + ret = ih264d_decode_pic_order_cnt(u1_is_idr_slice, u2_frame_num, + &ps_dec->s_prev_pic_poc, + &s_tmp_poc, ps_cur_slice, ps_pps, + u1_nal_ref_idc, + u1_bottom_field_flag, + u1_field_pic_flag, &i4_poc); + if(ret != OK) + return ret; + /* Display seq no calculations */ + if(i4_poc >= ps_dec->i4_max_poc) + ps_dec->i4_max_poc = i4_poc; + /* IDR Picture or POC wrap around */ + if(i4_poc == 0) + { + ps_dec->i4_prev_max_display_seq = ps_dec->i4_prev_max_display_seq + + ps_dec->i4_max_poc + + ps_dec->u1_max_dec_frame_buffering + 1; + ps_dec->i4_max_poc = 0; + } + } + + /*--------------------------------------------------------------------*/ + /* Copy the values read from the bitstream to the slice header and then*/ + /* If the slice is first slice in picture, then do Start of Picture */ + /* processing. */ + /*--------------------------------------------------------------------*/ + ps_cur_slice->i4_delta_pic_order_cnt[0] = i_delta_poc[0]; + ps_cur_slice->i4_delta_pic_order_cnt[1] = i_delta_poc[1]; + ps_cur_slice->u4_idr_pic_id = u4_idr_pic_id; + ps_cur_slice->u2_first_mb_in_slice = u2_first_mb_in_slice; + ps_cur_slice->u1_field_pic_flag = u1_field_pic_flag; + ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag; + ps_cur_slice->u1_slice_type = u1_slice_type; + ps_cur_slice->i4_pic_order_cnt_lsb = s_tmp_poc.i4_pic_order_cnt_lsb; + + ps_cur_slice->u1_nal_unit_type = u1_nal_unit_type; + ps_cur_slice->u1_redundant_pic_cnt = u1_redundant_pic_cnt; + ps_cur_slice->u1_nal_ref_idc = u1_nal_ref_idc; + ps_cur_slice->u1_pic_order_cnt_type = u1_pic_order_cnt_type; + + if(ps_seq->u1_frame_mbs_only_flag) + ps_cur_slice->u1_direct_8x8_inference_flag = + ps_seq->u1_direct_8x8_inference_flag; + else + ps_cur_slice->u1_direct_8x8_inference_flag = 1; + + if(u1_slice_type == B_SLICE) + { + ps_cur_slice->u1_direct_spatial_mv_pred_flag = ih264d_get_bit_h264( + ps_bitstrm); + COPYTHECONTEXT(""SH: direct_spatial_mv_pred_flag"", + ps_cur_slice->u1_direct_spatial_mv_pred_flag); + + if(ps_cur_slice->u1_direct_spatial_mv_pred_flag) + ps_cur_slice->pf_decodeDirect = ih264d_decode_spatial_direct; + else + ps_cur_slice->pf_decodeDirect = ih264d_decode_temporal_direct; + if(!((ps_pps->ps_sps->u1_mb_aff_flag) && (!u1_field_pic_flag))) + ps_dec->pf_mvpred = ih264d_mvpred_nonmbaffB; + } + else + { + if(!((ps_pps->ps_sps->u1_mb_aff_flag) && (!u1_field_pic_flag))) + + ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff; + } + + if(ps_dec->u4_first_slice_in_pic == 2) + { + if(u2_first_mb_in_slice == 0) + { + ret = ih264d_start_of_pic(ps_dec, i4_poc, &s_tmp_poc, u2_frame_num, ps_pps); + if(ret != OK) + return ret; + } + + ps_dec->u4_output_present = 0; + + { + ih264d_get_next_display_field(ps_dec, + ps_dec->ps_out_buffer, + &(ps_dec->s_disp_op)); + /* If error code is non-zero then there is no buffer available for display, + hence avoid format conversion */ + + if(0 != ps_dec->s_disp_op.u4_error_code) + { + ps_dec->u4_fmt_conv_cur_row = ps_dec->s_disp_frame_info.u4_y_ht; + } + else + ps_dec->u4_output_present = 1; + } + if(ps_dec->u1_separate_parse == 1) + { + if(ps_dec->u4_dec_thread_created == 0) + { + ithread_create(ps_dec->pv_dec_thread_handle, NULL, + (void *)ih264d_decode_picture_thread, + (void *)ps_dec); + + ps_dec->u4_dec_thread_created = 1; + } + + if((ps_dec->u4_num_cores == 3) && + ((ps_dec->u4_app_disable_deblk_frm == 0) || ps_dec->i1_recon_in_thread3_flag) + && (ps_dec->u4_bs_deblk_thread_created == 0)) + { + ps_dec->u4_start_recon_deblk = 0; + ithread_create(ps_dec->pv_bs_deblk_thread_handle, NULL, + (void *)ih264d_recon_deblk_thread, + (void *)ps_dec); + ps_dec->u4_bs_deblk_thread_created = 1; + } + } + + } + + /* INITIALIZATION of fn ptrs for MC and formMbPartInfo functions */ + { + UWORD8 uc_nofield_nombaff; + + + + uc_nofield_nombaff = ((ps_dec->ps_cur_slice->u1_field_pic_flag == 0) + && (ps_dec->ps_cur_slice->u1_mbaff_frame_flag == 0) + && (u1_slice_type != B_SLICE) + && (ps_dec->ps_cur_pps->u1_wted_pred_flag == 0)); + + /* Initialise MC and formMbPartInfo fn ptrs one time based on profile_idc */ + + if(uc_nofield_nombaff) + { + ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp; + ps_dec->p_motion_compensate = ih264d_motion_compensate_bp; + } + else + { + ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_mp; + ps_dec->p_motion_compensate = ih264d_motion_compensate_mp; + } + + + } + + /* + * Decide whether to decode the current picture or not + */ + { + dec_err_status_t * ps_err = ps_dec->ps_dec_err_status; + if(ps_err->u4_frm_sei_sync == u2_frame_num) + { + ps_err->u1_err_flag = ACCEPT_ALL_PICS; + ps_err->u4_frm_sei_sync = SYNC_FRM_DEFAULT; + } + ps_err->u4_cur_frm = u2_frame_num; + } + + /* Decision for decoding if the picture is to be skipped */ + { + WORD32 i4_skip_b_pic, i4_skip_p_pic; + + i4_skip_b_pic = (ps_dec->u4_skip_frm_mask & B_SLC_BIT) + && (B_SLICE == u1_slice_type) && (0 == u1_nal_ref_idc); + + i4_skip_p_pic = (ps_dec->u4_skip_frm_mask & P_SLC_BIT) + && (P_SLICE == u1_slice_type) && (0 == u1_nal_ref_idc); + + /**************************************************************/ + /* Skip the B picture if skip mask is set for B picture and */ + /* Current B picture is a non reference B picture or there is */ + /* no user for reference B picture */ + /**************************************************************/ + if(i4_skip_b_pic) + { + ps_dec->ps_cur_pic->u4_pack_slc_typ |= B_SLC_BIT; + /* Don't decode the picture in SKIP-B mode if that picture is B */ + /* and also it is not to be used as a reference picture */ + ps_dec->u1_last_pic_not_decoded = 1; + + return OK; + } + /**************************************************************/ + /* Skip the P picture if skip mask is set for P picture and */ + /* Current P picture is a non reference P picture or there is */ + /* no user for reference P picture */ + /**************************************************************/ + if(i4_skip_p_pic) + { + ps_dec->ps_cur_pic->u4_pack_slc_typ |= P_SLC_BIT; + /* Don't decode the picture in SKIP-P mode if that picture is P */ + /* and also it is not to be used as a reference picture */ + ps_dec->u1_last_pic_not_decoded = 1; + + return OK; + } + } + + { + UWORD16 u2_mb_x, u2_mb_y; + + ps_dec->i4_submb_ofst = ((u2_first_mb_in_slice + << ps_cur_slice->u1_mbaff_frame_flag) * SUB_BLK_SIZE) + - SUB_BLK_SIZE; + if(u2_first_mb_in_slice) + { + UWORD8 u1_mb_aff; + UWORD8 u1_field_pic; + UWORD16 u2_frm_wd_in_mbs; + u2_frm_wd_in_mbs = ps_seq->u2_frm_wd_in_mbs; + u1_mb_aff = ps_cur_slice->u1_mbaff_frame_flag; + u1_field_pic = ps_cur_slice->u1_field_pic_flag; + + { + UWORD32 x_offset; + UWORD32 y_offset; + UWORD32 u4_frame_stride; + tfr_ctxt_t *ps_trns_addr; // = &ps_dec->s_tran_addrecon_parse; + + if(ps_dec->u1_separate_parse) + { + ps_trns_addr = &ps_dec->s_tran_addrecon_parse; + } + else + { + ps_trns_addr = &ps_dec->s_tran_addrecon; + } + u2_mb_x = MOD(u2_first_mb_in_slice, u2_frm_wd_in_mbs); + u2_mb_y = DIV(u2_first_mb_in_slice, u2_frm_wd_in_mbs); + + u2_mb_y <<= u1_mb_aff; + + if((u2_mb_x > u2_frm_wd_in_mbs - 1) + || (u2_mb_y > ps_dec->u2_frm_ht_in_mbs - 1)) + { + return ERROR_CORRUPTED_SLICE; + } + + u4_frame_stride = ps_dec->u2_frm_wd_y << u1_field_pic; + x_offset = u2_mb_x << 4; + y_offset = (u2_mb_y * u4_frame_stride) << 4; + + ps_trns_addr->pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1 + x_offset + + y_offset; + + u4_frame_stride = ps_dec->u2_frm_wd_uv << u1_field_pic; + x_offset >>= 1; + y_offset = (u2_mb_y * u4_frame_stride) << 3; + + x_offset *= YUV420SP_FACTOR; + + ps_trns_addr->pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2 + x_offset + + y_offset; + ps_trns_addr->pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3 + x_offset + + y_offset; + + ps_trns_addr->pu1_mb_y = ps_trns_addr->pu1_dest_y; + ps_trns_addr->pu1_mb_u = ps_trns_addr->pu1_dest_u; + ps_trns_addr->pu1_mb_v = ps_trns_addr->pu1_dest_v; + + + if(ps_dec->u1_separate_parse == 1) + { + ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic + + (u2_first_mb_in_slice << u1_mb_aff); + } + else + { + ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic + + (u2_first_mb_in_slice << u1_mb_aff); + } + + ps_dec->u2_cur_mb_addr = (u2_first_mb_in_slice << u1_mb_aff); + + ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv + + ((u2_first_mb_in_slice << u1_mb_aff) << 4); + } + } + else + { + tfr_ctxt_t *ps_trns_addr; + + if(ps_dec->u1_separate_parse) + { + ps_trns_addr = &ps_dec->s_tran_addrecon_parse; + } + else + { + ps_trns_addr = &ps_dec->s_tran_addrecon; + } + + u2_mb_x = 0xffff; + u2_mb_y = 0; + ps_dec->u2_cur_mb_addr = 0; + ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic; + ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv; + ps_trns_addr->pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1; + ps_trns_addr->pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2; + ps_trns_addr->pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3; + + ps_trns_addr->pu1_mb_y = ps_trns_addr->pu1_dest_y; + ps_trns_addr->pu1_mb_u = ps_trns_addr->pu1_dest_u; + ps_trns_addr->pu1_mb_v = ps_trns_addr->pu1_dest_v; + + } + + ps_dec->ps_part = ps_dec->ps_parse_part_params; + + ps_dec->u2_mbx = + (MOD(u2_first_mb_in_slice - 1, ps_seq->u2_frm_wd_in_mbs)); + ps_dec->u2_mby = + (DIV(u2_first_mb_in_slice - 1, ps_seq->u2_frm_wd_in_mbs)); + ps_dec->u2_mby <<= ps_cur_slice->u1_mbaff_frame_flag; + ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; + ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; + } + + /* RBSP stop bit is used for CABAC decoding*/ + ps_bitstrm->u4_max_ofst += ps_dec->ps_cur_pps->u1_entropy_coding_mode; + + ps_dec->u1_B = (u1_slice_type == B_SLICE); + ps_dec->u4_next_mb_skip = 0; + + ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice = + ps_dec->ps_cur_slice->u2_first_mb_in_slice; + ps_dec->ps_parse_cur_slice->slice_type = + ps_dec->ps_cur_slice->u1_slice_type; + + + ps_dec->u4_start_recon_deblk = 1; + { + WORD32 num_entries; + WORD32 size; + UWORD8 *pu1_buf; + + num_entries = MIN(MAX_FRAMES, ps_dec->u4_num_ref_frames_at_init); + num_entries = 2 * ((2 * num_entries) + 1); + + size = num_entries * sizeof(void *); + size += PAD_MAP_IDX_POC * sizeof(void *); + + pu1_buf = (UWORD8 *)ps_dec->pv_map_ref_idx_to_poc_buf; + pu1_buf += size * ps_dec->u2_cur_slice_num; + ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc = ( void *)pu1_buf; + } + + if(ps_dec->u1_separate_parse) + { + ps_dec->ps_parse_cur_slice->pv_tu_coeff_data_start = ps_dec->pv_parse_tu_coeff_data; + } + else + { + ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data; + } + + if(u1_slice_type == I_SLICE) + { + ps_dec->ps_cur_pic->u4_pack_slc_typ |= I_SLC_BIT; + + ret = ih264d_parse_islice(ps_dec, u2_first_mb_in_slice); + + if(ps_dec->i4_pic_type != B_SLICE && ps_dec->i4_pic_type != P_SLICE) + ps_dec->i4_pic_type = I_SLICE; + + } + else if(u1_slice_type == P_SLICE) + { + ps_dec->ps_cur_pic->u4_pack_slc_typ |= P_SLC_BIT; + ret = ih264d_parse_pslice(ps_dec, u2_first_mb_in_slice); + ps_dec->u1_pr_sl_type = u1_slice_type; + if(ps_dec->i4_pic_type != B_SLICE) + ps_dec->i4_pic_type = P_SLICE; + } + else if(u1_slice_type == B_SLICE) + { + ps_dec->ps_cur_pic->u4_pack_slc_typ |= B_SLC_BIT; + ret = ih264d_parse_bslice(ps_dec, u2_first_mb_in_slice); + ps_dec->u1_pr_sl_type = u1_slice_type; + ps_dec->i4_pic_type = B_SLICE; + } + else + return ERROR_INV_SLC_TYPE_T; + + + if(ps_dec->u1_slice_header_done) + { + /* set to zero to indicate a valid slice has been decoded */ + /* first slice header successfully decoded */ + ps_dec->u4_first_slice_in_pic = 0; + ps_dec->u1_first_slice_in_stream = 0; + } + + if(ret != OK) + return ret; + + /* storing last Mb X and MbY of the slice */ + ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; + ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; + + /* End of Picture detection */ + + if(ps_dec->u2_total_mbs_coded >= (ps_seq->u2_max_mb_addr + 1)) + { + ps_dec->u1_pic_decode_done = 1; + + } + + { + dec_err_status_t * ps_err = ps_dec->ps_dec_err_status; + if((ps_err->u1_err_flag & REJECT_PB_PICS) + && (ps_err->u1_cur_pic_type == PIC_TYPE_I)) + { + ps_err->u1_err_flag = ACCEPT_ALL_PICS; + } + } + + PRINT_BIN_BIT_RATIO(ps_dec) + + return ret; +} +",1,"WORD32 ih264d_parse_decode_slice(UWORD8 u1_is_idr_slice, + UWORD8 u1_nal_ref_idc, + dec_struct_t *ps_dec /* Decoder parameters */ + ) +{ + dec_bit_stream_t * ps_bitstrm = ps_dec->ps_bitstrm; + dec_pic_params_t *ps_pps; + dec_seq_params_t *ps_seq; + dec_slice_params_t *ps_cur_slice = ps_dec->ps_cur_slice; + pocstruct_t s_tmp_poc; + WORD32 i_delta_poc[2]; + WORD32 i4_poc = 0; + UWORD16 u2_first_mb_in_slice, u2_frame_num; + UWORD8 u1_field_pic_flag, u1_redundant_pic_cnt = 0, u1_slice_type; + UWORD32 u4_idr_pic_id = 0; + UWORD8 u1_bottom_field_flag, u1_pic_order_cnt_type; + + UWORD8 u1_nal_unit_type; + UWORD32 *pu4_bitstrm_buf = ps_bitstrm->pu4_buffer; + UWORD32 *pu4_bitstrm_ofst = &ps_bitstrm->u4_ofst; + WORD8 i1_is_end_of_poc; + + WORD32 ret, end_of_frame; + WORD32 prev_slice_err, num_mb_skipped; + UWORD8 u1_mbaff; + pocstruct_t *ps_cur_poc; + + UWORD32 u4_temp; + WORD32 i_temp; + UWORD32 u4_call_end_of_pic = 0; + + /* read FirstMbInSlice and slice type*/ + ps_dec->ps_dpb_cmds->u1_dpb_commands_read_slc = 0; + u2_first_mb_in_slice = ih264d_uev(pu4_bitstrm_ofst, + pu4_bitstrm_buf); + if(u2_first_mb_in_slice + > (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs)) + { + + return ERROR_CORRUPTED_SLICE; + } + + /*we currently don not support ASO*/ + if(((u2_first_mb_in_slice << ps_cur_slice->u1_mbaff_frame_flag) + <= ps_dec->u2_cur_mb_addr) && (ps_dec->u4_first_slice_in_pic == 0)) + { + return ERROR_CORRUPTED_SLICE; + } + + COPYTHECONTEXT(""SH: first_mb_in_slice"",u2_first_mb_in_slice); + + u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); + + if(u4_temp > 9) + return ERROR_INV_SLC_TYPE_T; + + u1_slice_type = u4_temp; + COPYTHECONTEXT(""SH: slice_type"",(u1_slice_type)); + ps_dec->u1_sl_typ_5_9 = 0; + /* Find Out the Slice Type is 5 to 9 or not then Set the Flag */ + /* u1_sl_typ_5_9 = 1 .Which tells that all the slices in the Pic*/ + /* will be of same type of current */ + if(u1_slice_type > 4) + { + u1_slice_type -= 5; + ps_dec->u1_sl_typ_5_9 = 1; + } + + { + UWORD32 skip; + + if((ps_dec->i4_app_skip_mode == IVD_SKIP_PB) + || (ps_dec->i4_dec_skip_mode == IVD_SKIP_PB)) + { + UWORD32 u4_bit_stream_offset = 0; + + if(ps_dec->u1_nal_unit_type == IDR_SLICE_NAL) + { + skip = 0; + + ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE; + } + else if((I_SLICE == u1_slice_type) + && (1 >= ps_dec->ps_cur_sps->u1_num_ref_frames)) + { + skip = 0; + + ps_dec->i4_dec_skip_mode = IVD_SKIP_NONE; + } + else + { + skip = 1; + } + + /* If one frame worth of data is already skipped, do not skip the next one */ + if((0 == u2_first_mb_in_slice) && (1 == ps_dec->u4_prev_nal_skipped)) + { + skip = 0; + } + + if(skip) + { + ps_dec->u4_prev_nal_skipped = 1; + ps_dec->i4_dec_skip_mode = IVD_SKIP_PB; + return 0; + } + else + { + /* If the previous NAL was skipped, then + do not process that buffer in this call. + Return to app and process it in the next call. + This is necessary to handle cases where I/IDR is not complete in + the current buffer and application intends to fill the remaining part of the bitstream + later. This ensures we process only frame worth of data in every call */ + if(1 == ps_dec->u4_prev_nal_skipped) + { + ps_dec->u4_return_to_app = 1; + return 0; + } + } + } + + } + + u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); + if(u4_temp & MASK_ERR_PIC_SET_ID) + return ERROR_INV_SLICE_HDR_T; + /* discard slice if pic param is invalid */ + COPYTHECONTEXT(""SH: pic_parameter_set_id"", u4_temp); + ps_pps = &ps_dec->ps_pps[u4_temp]; + if(FALSE == ps_pps->u1_is_valid) + { + return ERROR_INV_SLICE_HDR_T; + } + ps_seq = ps_pps->ps_sps; + if(!ps_seq) + return ERROR_INV_SLICE_HDR_T; + if(FALSE == ps_seq->u1_is_valid) + return ERROR_INV_SLICE_HDR_T; + + /* Get the frame num */ + u2_frame_num = ih264d_get_bits_h264(ps_bitstrm, + ps_seq->u1_bits_in_frm_num); + + + COPYTHECONTEXT(""SH: frame_num"", u2_frame_num); + if(!ps_dec->u1_first_slice_in_stream && ps_dec->u4_first_slice_in_pic) + { + pocstruct_t *ps_prev_poc = &ps_dec->s_prev_pic_poc; + pocstruct_t *ps_cur_poc = &ps_dec->s_cur_pic_poc; + + ps_dec->u2_mbx = 0xffff; + ps_dec->u2_mby = 0; + + if((0 == u1_is_idr_slice) && ps_cur_slice->u1_nal_ref_idc) + ps_dec->u2_prev_ref_frame_num = ps_cur_slice->u2_frame_num; + + if(u1_is_idr_slice || ps_cur_slice->u1_mmco_equalto5) + ps_dec->u2_prev_ref_frame_num = 0; + + if(ps_dec->ps_cur_sps->u1_gaps_in_frame_num_value_allowed_flag) + { + ih264d_decode_gaps_in_frame_num(ps_dec, u2_frame_num); + } + + ps_prev_poc->i4_prev_frame_num_ofst = ps_cur_poc->i4_prev_frame_num_ofst; + ps_prev_poc->u2_frame_num = ps_cur_poc->u2_frame_num; + ps_prev_poc->u1_mmco_equalto5 = ps_cur_slice->u1_mmco_equalto5; + if(ps_cur_slice->u1_nal_ref_idc) + { + ps_prev_poc->i4_pic_order_cnt_lsb = ps_cur_poc->i4_pic_order_cnt_lsb; + ps_prev_poc->i4_pic_order_cnt_msb = ps_cur_poc->i4_pic_order_cnt_msb; + ps_prev_poc->i4_delta_pic_order_cnt_bottom = + ps_cur_poc->i4_delta_pic_order_cnt_bottom; + ps_prev_poc->i4_delta_pic_order_cnt[0] = + ps_cur_poc->i4_delta_pic_order_cnt[0]; + ps_prev_poc->i4_delta_pic_order_cnt[1] = + ps_cur_poc->i4_delta_pic_order_cnt[1]; + ps_prev_poc->u1_bot_field = ps_cur_poc->u1_bot_field; + } + + ps_dec->u2_total_mbs_coded = 0; + } + /* Get the field related flags */ + if(!ps_seq->u1_frame_mbs_only_flag) + { + + u1_field_pic_flag = ih264d_get_bit_h264(ps_bitstrm); + COPYTHECONTEXT(""SH: field_pic_flag"", u1_field_pic_flag); + u1_bottom_field_flag = 0; + + if(u1_field_pic_flag) + { + ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan_fld; + u1_bottom_field_flag = ih264d_get_bit_h264(ps_bitstrm); + COPYTHECONTEXT(""SH: bottom_field_flag"", u1_bottom_field_flag); + + } + else + { + ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan; + } + } + else + { + u1_field_pic_flag = 0; + u1_bottom_field_flag = 0; + + ps_dec->pu1_inv_scan = (UWORD8 *)gau1_ih264d_inv_scan; + } + + u1_nal_unit_type = SLICE_NAL; + if(u1_is_idr_slice) + { + if(0 == u1_field_pic_flag) + { + ps_dec->u1_top_bottom_decoded = TOP_FIELD_ONLY | BOT_FIELD_ONLY; + } + u1_nal_unit_type = IDR_SLICE_NAL; + u4_idr_pic_id = ih264d_uev(pu4_bitstrm_ofst, + pu4_bitstrm_buf); + if(u4_idr_pic_id > 65535) + return ERROR_INV_SLICE_HDR_T; + COPYTHECONTEXT(""SH: "", u4_idr_pic_id); + } + + /* read delta pic order count information*/ + i_delta_poc[0] = i_delta_poc[1] = 0; + s_tmp_poc.i4_pic_order_cnt_lsb = 0; + s_tmp_poc.i4_delta_pic_order_cnt_bottom = 0; + u1_pic_order_cnt_type = ps_seq->u1_pic_order_cnt_type; + if(u1_pic_order_cnt_type == 0) + { + i_temp = ih264d_get_bits_h264( + ps_bitstrm, + ps_seq->u1_log2_max_pic_order_cnt_lsb_minus); + if(i_temp < 0 || i_temp >= ps_seq->i4_max_pic_order_cntLsb) + return ERROR_INV_SLICE_HDR_T; + s_tmp_poc.i4_pic_order_cnt_lsb = i_temp; + COPYTHECONTEXT(""SH: pic_order_cnt_lsb"", s_tmp_poc.i4_pic_order_cnt_lsb); + + if((ps_pps->u1_pic_order_present_flag == 1) && (!u1_field_pic_flag)) + { + s_tmp_poc.i4_delta_pic_order_cnt_bottom = ih264d_sev( + pu4_bitstrm_ofst, pu4_bitstrm_buf); + COPYTHECONTEXT(""SH: delta_pic_order_cnt_bottom"", + s_tmp_poc.i4_delta_pic_order_cnt_bottom); + } + } + + s_tmp_poc.i4_delta_pic_order_cnt[0] = 0; + s_tmp_poc.i4_delta_pic_order_cnt[1] = 0; + if(u1_pic_order_cnt_type == 1 + && (!ps_seq->u1_delta_pic_order_always_zero_flag)) + { + s_tmp_poc.i4_delta_pic_order_cnt[0] = ih264d_sev(pu4_bitstrm_ofst, + pu4_bitstrm_buf); + COPYTHECONTEXT(""SH: delta_pic_order_cnt[0]"", + s_tmp_poc.i4_delta_pic_order_cnt[0]); + + if(ps_pps->u1_pic_order_present_flag && !u1_field_pic_flag) + { + s_tmp_poc.i4_delta_pic_order_cnt[1] = ih264d_sev( + pu4_bitstrm_ofst, pu4_bitstrm_buf); + COPYTHECONTEXT(""SH: delta_pic_order_cnt[1]"", + s_tmp_poc.i4_delta_pic_order_cnt[1]); + } + } + + if(ps_pps->u1_redundant_pic_cnt_present_flag) + { + u4_temp = ih264d_uev(pu4_bitstrm_ofst, pu4_bitstrm_buf); + if(u4_temp > MAX_REDUNDANT_PIC_CNT) + return ERROR_INV_SLICE_HDR_T; + u1_redundant_pic_cnt = u4_temp; + COPYTHECONTEXT(""SH: redundant_pic_cnt"", u1_redundant_pic_cnt); + } + + /*--------------------------------------------------------------------*/ + /* Check if the slice is part of new picture */ + /*--------------------------------------------------------------------*/ + /* First slice of a picture is always considered as part of new picture */ + + i1_is_end_of_poc = 1; + ps_dec->ps_dec_err_status->u1_err_flag &= MASK_REJECT_CUR_PIC; + + if(ps_dec->u4_first_slice_in_pic == 0) + { + i1_is_end_of_poc = ih264d_is_end_of_pic(u2_frame_num, u1_nal_ref_idc, + &s_tmp_poc, &ps_dec->s_cur_pic_poc, + ps_cur_slice, u1_pic_order_cnt_type, + u1_nal_unit_type, u4_idr_pic_id, + u1_field_pic_flag, + u1_bottom_field_flag); + if(i1_is_end_of_poc) + { + ps_dec->u1_first_slice_in_stream = 0; + return ERROR_INCOMPLETE_FRAME; + } + + } + + /*--------------------------------------------------------------------*/ + /* Check for error in slice and parse the missing/corrupted MB's */ + /* as skip-MB's in an inserted P-slice */ + /*--------------------------------------------------------------------*/ + u1_mbaff = ps_seq->u1_mb_aff_flag && (!u1_field_pic_flag); + prev_slice_err = 0; + + if(i1_is_end_of_poc || ps_dec->u1_first_slice_in_stream) + { + if(u2_frame_num != ps_dec->u2_prv_frame_num + && ps_dec->u1_top_bottom_decoded != 0 + && ps_dec->u1_top_bottom_decoded + != (TOP_FIELD_ONLY | BOT_FIELD_ONLY)) + { + ps_dec->u1_dangling_field = 1; + if(ps_dec->u4_first_slice_in_pic) + { + prev_slice_err = 1; + } + else + { + prev_slice_err = 2; + } + + if(ps_dec->u1_top_bottom_decoded ==TOP_FIELD_ONLY) + ps_cur_slice->u1_bottom_field_flag = 1; + else + ps_cur_slice->u1_bottom_field_flag = 0; + + num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) + - ps_dec->u2_total_mbs_coded; + ps_cur_poc = &ps_dec->s_cur_pic_poc; + + + u1_is_idr_slice = ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL; + } + else if(ps_dec->u4_first_slice_in_pic) + { + if(u2_first_mb_in_slice > 0) + { + prev_slice_err = 1; + num_mb_skipped = u2_first_mb_in_slice << u1_mbaff; + ps_cur_poc = &s_tmp_poc; + + ps_cur_slice->u4_idr_pic_id = u4_idr_pic_id; + ps_cur_slice->u1_field_pic_flag = u1_field_pic_flag; + ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag; + ps_cur_slice->i4_pic_order_cnt_lsb = + s_tmp_poc.i4_pic_order_cnt_lsb; + ps_cur_slice->u1_nal_unit_type = u1_nal_unit_type; + ps_cur_slice->u1_redundant_pic_cnt = u1_redundant_pic_cnt; + ps_cur_slice->u1_nal_ref_idc = u1_nal_ref_idc; + ps_cur_slice->u1_pic_order_cnt_type = u1_pic_order_cnt_type; + ps_cur_slice->u1_mbaff_frame_flag = ps_seq->u1_mb_aff_flag + && (!u1_field_pic_flag); + } + + } + else + { + /* since i1_is_end_of_poc is set ,means new frame num is encountered. so conceal the current frame + * completely */ + prev_slice_err = 2; + num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs + * ps_dec->u2_frm_wd_in_mbs) + - ps_dec->u2_total_mbs_coded; + ps_cur_poc = &s_tmp_poc; + } + } + else + { + if((u2_first_mb_in_slice << u1_mbaff) > ps_dec->u2_total_mbs_coded) + { + prev_slice_err = 2; + num_mb_skipped = (u2_first_mb_in_slice << u1_mbaff) + - ps_dec->u2_total_mbs_coded; + ps_cur_poc = &s_tmp_poc; + } + else if((u2_first_mb_in_slice << u1_mbaff) < ps_dec->u2_total_mbs_coded) + { + return ERROR_CORRUPTED_SLICE; + } + } + + if(prev_slice_err) + { + ret = ih264d_mark_err_slice_skip(ps_dec, num_mb_skipped, u1_is_idr_slice, u2_frame_num, ps_cur_poc, prev_slice_err); + + if(ps_dec->u1_dangling_field == 1) + { + ps_dec->u1_second_field = 1 - ps_dec->u1_second_field; + ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag; + ps_dec->u2_prv_frame_num = u2_frame_num; + ps_dec->u1_first_slice_in_stream = 0; + return ERROR_DANGLING_FIELD_IN_PIC; + } + + if(prev_slice_err == 2) + { + ps_dec->u1_first_slice_in_stream = 0; + return ERROR_INCOMPLETE_FRAME; + } + + if(ps_dec->u2_total_mbs_coded + >= ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) + { + /* return if all MBs in frame are parsed*/ + ps_dec->u1_first_slice_in_stream = 0; + return ERROR_IN_LAST_SLICE_OF_PIC; + } + + if(ps_dec->ps_dec_err_status->u1_err_flag & REJECT_CUR_PIC) + { + ih264d_err_pic_dispbuf_mgr(ps_dec); + return ERROR_NEW_FRAME_EXPECTED; + } + + if(ret != OK) + return ret; + + i1_is_end_of_poc = 0; + } + + if (ps_dec->u4_first_slice_in_pic == 0) + { + ps_dec->ps_parse_cur_slice++; + ps_dec->u2_cur_slice_num++; + } + + if((ps_dec->u1_separate_parse == 0) && (ps_dec->u4_first_slice_in_pic == 0)) + { + ps_dec->ps_decode_cur_slice++; + } + ps_dec->u1_slice_header_done = 0; + + + if(u1_field_pic_flag) + { + ps_dec->u2_prv_frame_num = u2_frame_num; + } + + if(ps_cur_slice->u1_mmco_equalto5) + { + WORD32 i4_temp_poc; + WORD32 i4_top_field_order_poc, i4_bot_field_order_poc; + + if(!ps_cur_slice->u1_field_pic_flag) // or a complementary field pair + { + i4_top_field_order_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt; + i4_bot_field_order_poc = + ps_dec->ps_cur_pic->i4_bottom_field_order_cnt; + i4_temp_poc = MIN(i4_top_field_order_poc, + i4_bot_field_order_poc); + } + else if(!ps_cur_slice->u1_bottom_field_flag) + i4_temp_poc = ps_dec->ps_cur_pic->i4_top_field_order_cnt; + else + i4_temp_poc = ps_dec->ps_cur_pic->i4_bottom_field_order_cnt; + + ps_dec->ps_cur_pic->i4_top_field_order_cnt = i4_temp_poc + - ps_dec->ps_cur_pic->i4_top_field_order_cnt; + ps_dec->ps_cur_pic->i4_bottom_field_order_cnt = i4_temp_poc + - ps_dec->ps_cur_pic->i4_bottom_field_order_cnt; + + ps_dec->ps_cur_pic->i4_poc = i4_temp_poc; + ps_dec->ps_cur_pic->i4_avg_poc = i4_temp_poc; + } + if(ps_dec->u4_first_slice_in_pic) + { + ret = ih264d_decode_pic_order_cnt(u1_is_idr_slice, u2_frame_num, + &ps_dec->s_prev_pic_poc, + &s_tmp_poc, ps_cur_slice, ps_pps, + u1_nal_ref_idc, + u1_bottom_field_flag, + u1_field_pic_flag, &i4_poc); + if(ret != OK) + return ret; + /* Display seq no calculations */ + if(i4_poc >= ps_dec->i4_max_poc) + ps_dec->i4_max_poc = i4_poc; + /* IDR Picture or POC wrap around */ + if(i4_poc == 0) + { + ps_dec->i4_prev_max_display_seq = ps_dec->i4_prev_max_display_seq + + ps_dec->i4_max_poc + + ps_dec->u1_max_dec_frame_buffering + 1; + ps_dec->i4_max_poc = 0; + } + } + + /*--------------------------------------------------------------------*/ + /* Copy the values read from the bitstream to the slice header and then*/ + /* If the slice is first slice in picture, then do Start of Picture */ + /* processing. */ + /*--------------------------------------------------------------------*/ + ps_cur_slice->i4_delta_pic_order_cnt[0] = i_delta_poc[0]; + ps_cur_slice->i4_delta_pic_order_cnt[1] = i_delta_poc[1]; + ps_cur_slice->u4_idr_pic_id = u4_idr_pic_id; + ps_cur_slice->u2_first_mb_in_slice = u2_first_mb_in_slice; + ps_cur_slice->u1_field_pic_flag = u1_field_pic_flag; + ps_cur_slice->u1_bottom_field_flag = u1_bottom_field_flag; + ps_cur_slice->u1_slice_type = u1_slice_type; + ps_cur_slice->i4_pic_order_cnt_lsb = s_tmp_poc.i4_pic_order_cnt_lsb; + + ps_cur_slice->u1_nal_unit_type = u1_nal_unit_type; + ps_cur_slice->u1_redundant_pic_cnt = u1_redundant_pic_cnt; + ps_cur_slice->u1_nal_ref_idc = u1_nal_ref_idc; + ps_cur_slice->u1_pic_order_cnt_type = u1_pic_order_cnt_type; + + if(ps_seq->u1_frame_mbs_only_flag) + ps_cur_slice->u1_direct_8x8_inference_flag = + ps_seq->u1_direct_8x8_inference_flag; + else + ps_cur_slice->u1_direct_8x8_inference_flag = 1; + + if(u1_slice_type == B_SLICE) + { + ps_cur_slice->u1_direct_spatial_mv_pred_flag = ih264d_get_bit_h264( + ps_bitstrm); + COPYTHECONTEXT(""SH: direct_spatial_mv_pred_flag"", + ps_cur_slice->u1_direct_spatial_mv_pred_flag); + + if(ps_cur_slice->u1_direct_spatial_mv_pred_flag) + ps_cur_slice->pf_decodeDirect = ih264d_decode_spatial_direct; + else + ps_cur_slice->pf_decodeDirect = ih264d_decode_temporal_direct; + if(!((ps_pps->ps_sps->u1_mb_aff_flag) && (!u1_field_pic_flag))) + ps_dec->pf_mvpred = ih264d_mvpred_nonmbaffB; + } + else + { + if(!((ps_pps->ps_sps->u1_mb_aff_flag) && (!u1_field_pic_flag))) + + ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff; + } + + if(ps_dec->u4_first_slice_in_pic) + { + if(u2_first_mb_in_slice == 0) + { + ret = ih264d_start_of_pic(ps_dec, i4_poc, &s_tmp_poc, u2_frame_num, ps_pps); + if(ret != OK) + return ret; + } + + ps_dec->u4_output_present = 0; + + { + ih264d_get_next_display_field(ps_dec, + ps_dec->ps_out_buffer, + &(ps_dec->s_disp_op)); + /* If error code is non-zero then there is no buffer available for display, + hence avoid format conversion */ + + if(0 != ps_dec->s_disp_op.u4_error_code) + { + ps_dec->u4_fmt_conv_cur_row = ps_dec->s_disp_frame_info.u4_y_ht; + } + else + ps_dec->u4_output_present = 1; + } + if(ps_dec->u1_separate_parse == 1) + { + if(ps_dec->u4_dec_thread_created == 0) + { + ithread_create(ps_dec->pv_dec_thread_handle, NULL, + (void *)ih264d_decode_picture_thread, + (void *)ps_dec); + + ps_dec->u4_dec_thread_created = 1; + } + + if((ps_dec->u4_num_cores == 3) && + ((ps_dec->u4_app_disable_deblk_frm == 0) || ps_dec->i1_recon_in_thread3_flag) + && (ps_dec->u4_bs_deblk_thread_created == 0)) + { + ps_dec->u4_start_recon_deblk = 0; + ithread_create(ps_dec->pv_bs_deblk_thread_handle, NULL, + (void *)ih264d_recon_deblk_thread, + (void *)ps_dec); + ps_dec->u4_bs_deblk_thread_created = 1; + } + } + + } + + /* INITIALIZATION of fn ptrs for MC and formMbPartInfo functions */ + { + UWORD8 uc_nofield_nombaff; + + + + uc_nofield_nombaff = ((ps_dec->ps_cur_slice->u1_field_pic_flag == 0) + && (ps_dec->ps_cur_slice->u1_mbaff_frame_flag == 0) + && (u1_slice_type != B_SLICE) + && (ps_dec->ps_cur_pps->u1_wted_pred_flag == 0)); + + /* Initialise MC and formMbPartInfo fn ptrs one time based on profile_idc */ + + if(uc_nofield_nombaff) + { + ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_bp; + ps_dec->p_motion_compensate = ih264d_motion_compensate_bp; + } + else + { + ps_dec->p_form_mb_part_info = ih264d_form_mb_part_info_mp; + ps_dec->p_motion_compensate = ih264d_motion_compensate_mp; + } + + + } + + /* + * Decide whether to decode the current picture or not + */ + { + dec_err_status_t * ps_err = ps_dec->ps_dec_err_status; + if(ps_err->u4_frm_sei_sync == u2_frame_num) + { + ps_err->u1_err_flag = ACCEPT_ALL_PICS; + ps_err->u4_frm_sei_sync = SYNC_FRM_DEFAULT; + } + ps_err->u4_cur_frm = u2_frame_num; + } + + /* Decision for decoding if the picture is to be skipped */ + { + WORD32 i4_skip_b_pic, i4_skip_p_pic; + + i4_skip_b_pic = (ps_dec->u4_skip_frm_mask & B_SLC_BIT) + && (B_SLICE == u1_slice_type) && (0 == u1_nal_ref_idc); + + i4_skip_p_pic = (ps_dec->u4_skip_frm_mask & P_SLC_BIT) + && (P_SLICE == u1_slice_type) && (0 == u1_nal_ref_idc); + + /**************************************************************/ + /* Skip the B picture if skip mask is set for B picture and */ + /* Current B picture is a non reference B picture or there is */ + /* no user for reference B picture */ + /**************************************************************/ + if(i4_skip_b_pic) + { + ps_dec->ps_cur_pic->u4_pack_slc_typ |= B_SLC_BIT; + /* Don't decode the picture in SKIP-B mode if that picture is B */ + /* and also it is not to be used as a reference picture */ + ps_dec->u1_last_pic_not_decoded = 1; + + return OK; + } + /**************************************************************/ + /* Skip the P picture if skip mask is set for P picture and */ + /* Current P picture is a non reference P picture or there is */ + /* no user for reference P picture */ + /**************************************************************/ + if(i4_skip_p_pic) + { + ps_dec->ps_cur_pic->u4_pack_slc_typ |= P_SLC_BIT; + /* Don't decode the picture in SKIP-P mode if that picture is P */ + /* and also it is not to be used as a reference picture */ + ps_dec->u1_last_pic_not_decoded = 1; + + return OK; + } + } + + { + UWORD16 u2_mb_x, u2_mb_y; + + ps_dec->i4_submb_ofst = ((u2_first_mb_in_slice + << ps_cur_slice->u1_mbaff_frame_flag) * SUB_BLK_SIZE) + - SUB_BLK_SIZE; + if(u2_first_mb_in_slice) + { + UWORD8 u1_mb_aff; + UWORD8 u1_field_pic; + UWORD16 u2_frm_wd_in_mbs; + u2_frm_wd_in_mbs = ps_seq->u2_frm_wd_in_mbs; + u1_mb_aff = ps_cur_slice->u1_mbaff_frame_flag; + u1_field_pic = ps_cur_slice->u1_field_pic_flag; + + { + UWORD32 x_offset; + UWORD32 y_offset; + UWORD32 u4_frame_stride; + tfr_ctxt_t *ps_trns_addr; // = &ps_dec->s_tran_addrecon_parse; + + if(ps_dec->u1_separate_parse) + { + ps_trns_addr = &ps_dec->s_tran_addrecon_parse; + } + else + { + ps_trns_addr = &ps_dec->s_tran_addrecon; + } + u2_mb_x = MOD(u2_first_mb_in_slice, u2_frm_wd_in_mbs); + u2_mb_y = DIV(u2_first_mb_in_slice, u2_frm_wd_in_mbs); + + u2_mb_y <<= u1_mb_aff; + + if((u2_mb_x > u2_frm_wd_in_mbs - 1) + || (u2_mb_y > ps_dec->u2_frm_ht_in_mbs - 1)) + { + return ERROR_CORRUPTED_SLICE; + } + + u4_frame_stride = ps_dec->u2_frm_wd_y << u1_field_pic; + x_offset = u2_mb_x << 4; + y_offset = (u2_mb_y * u4_frame_stride) << 4; + + ps_trns_addr->pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1 + x_offset + + y_offset; + + u4_frame_stride = ps_dec->u2_frm_wd_uv << u1_field_pic; + x_offset >>= 1; + y_offset = (u2_mb_y * u4_frame_stride) << 3; + + x_offset *= YUV420SP_FACTOR; + + ps_trns_addr->pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2 + x_offset + + y_offset; + ps_trns_addr->pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3 + x_offset + + y_offset; + + ps_trns_addr->pu1_mb_y = ps_trns_addr->pu1_dest_y; + ps_trns_addr->pu1_mb_u = ps_trns_addr->pu1_dest_u; + ps_trns_addr->pu1_mb_v = ps_trns_addr->pu1_dest_v; + + + if(ps_dec->u1_separate_parse == 1) + { + ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic + + (u2_first_mb_in_slice << u1_mb_aff); + } + else + { + ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic + + (u2_first_mb_in_slice << u1_mb_aff); + } + + ps_dec->u2_cur_mb_addr = (u2_first_mb_in_slice << u1_mb_aff); + + ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv + + ((u2_first_mb_in_slice << u1_mb_aff) << 4); + } + } + else + { + tfr_ctxt_t *ps_trns_addr; + + if(ps_dec->u1_separate_parse) + { + ps_trns_addr = &ps_dec->s_tran_addrecon_parse; + } + else + { + ps_trns_addr = &ps_dec->s_tran_addrecon; + } + + u2_mb_x = 0xffff; + u2_mb_y = 0; + ps_dec->u2_cur_mb_addr = 0; + ps_dec->ps_deblk_mbn = ps_dec->ps_deblk_pic; + ps_dec->ps_mv_cur = ps_dec->s_cur_pic.ps_mv; + ps_trns_addr->pu1_dest_y = ps_dec->s_cur_pic.pu1_buf1; + ps_trns_addr->pu1_dest_u = ps_dec->s_cur_pic.pu1_buf2; + ps_trns_addr->pu1_dest_v = ps_dec->s_cur_pic.pu1_buf3; + + ps_trns_addr->pu1_mb_y = ps_trns_addr->pu1_dest_y; + ps_trns_addr->pu1_mb_u = ps_trns_addr->pu1_dest_u; + ps_trns_addr->pu1_mb_v = ps_trns_addr->pu1_dest_v; + + } + + ps_dec->ps_part = ps_dec->ps_parse_part_params; + + ps_dec->u2_mbx = + (MOD(u2_first_mb_in_slice - 1, ps_seq->u2_frm_wd_in_mbs)); + ps_dec->u2_mby = + (DIV(u2_first_mb_in_slice - 1, ps_seq->u2_frm_wd_in_mbs)); + ps_dec->u2_mby <<= ps_cur_slice->u1_mbaff_frame_flag; + ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; + ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; + } + + /* RBSP stop bit is used for CABAC decoding*/ + ps_bitstrm->u4_max_ofst += ps_dec->ps_cur_pps->u1_entropy_coding_mode; + + ps_dec->u1_B = (u1_slice_type == B_SLICE); + ps_dec->u4_next_mb_skip = 0; + + ps_dec->ps_parse_cur_slice->u4_first_mb_in_slice = + ps_dec->ps_cur_slice->u2_first_mb_in_slice; + ps_dec->ps_parse_cur_slice->slice_type = + ps_dec->ps_cur_slice->u1_slice_type; + + + ps_dec->u4_start_recon_deblk = 1; + { + WORD32 num_entries; + WORD32 size; + UWORD8 *pu1_buf; + + num_entries = MIN(MAX_FRAMES, ps_dec->u4_num_ref_frames_at_init); + num_entries = 2 * ((2 * num_entries) + 1); + + size = num_entries * sizeof(void *); + size += PAD_MAP_IDX_POC * sizeof(void *); + + pu1_buf = (UWORD8 *)ps_dec->pv_map_ref_idx_to_poc_buf; + pu1_buf += size * ps_dec->u2_cur_slice_num; + ps_dec->ps_parse_cur_slice->ppv_map_ref_idx_to_poc = ( void *)pu1_buf; + } + + if(ps_dec->u1_separate_parse) + { + ps_dec->ps_parse_cur_slice->pv_tu_coeff_data_start = ps_dec->pv_parse_tu_coeff_data; + } + else + { + ps_dec->pv_proc_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data; + } + + if(u1_slice_type == I_SLICE) + { + ps_dec->ps_cur_pic->u4_pack_slc_typ |= I_SLC_BIT; + + ret = ih264d_parse_islice(ps_dec, u2_first_mb_in_slice); + + if(ps_dec->i4_pic_type != B_SLICE && ps_dec->i4_pic_type != P_SLICE) + ps_dec->i4_pic_type = I_SLICE; + + } + else if(u1_slice_type == P_SLICE) + { + ps_dec->ps_cur_pic->u4_pack_slc_typ |= P_SLC_BIT; + ret = ih264d_parse_pslice(ps_dec, u2_first_mb_in_slice); + ps_dec->u1_pr_sl_type = u1_slice_type; + if(ps_dec->i4_pic_type != B_SLICE) + ps_dec->i4_pic_type = P_SLICE; + } + else if(u1_slice_type == B_SLICE) + { + ps_dec->ps_cur_pic->u4_pack_slc_typ |= B_SLC_BIT; + ret = ih264d_parse_bslice(ps_dec, u2_first_mb_in_slice); + ps_dec->u1_pr_sl_type = u1_slice_type; + ps_dec->i4_pic_type = B_SLICE; + } + else + return ERROR_INV_SLC_TYPE_T; + + + if(ps_dec->u1_slice_header_done) + { + /* set to zero to indicate a valid slice has been decoded */ + ps_dec->u1_first_slice_in_stream = 0; + } + + if(ret != OK) + return ret; + + /* storing last Mb X and MbY of the slice */ + ps_dec->i2_prev_slice_mbx = ps_dec->u2_mbx; + ps_dec->i2_prev_slice_mby = ps_dec->u2_mby; + + /* End of Picture detection */ + + if(ps_dec->u2_total_mbs_coded >= (ps_seq->u2_max_mb_addr + 1)) + { + ps_dec->u1_pic_decode_done = 1; + + } + + { + dec_err_status_t * ps_err = ps_dec->ps_dec_err_status; + if((ps_err->u1_err_flag & REJECT_PB_PICS) + && (ps_err->u1_cur_pic_type == PIC_TYPE_I)) + { + ps_err->u1_err_flag = ACCEPT_ALL_PICS; + } + } + + PRINT_BIN_BIT_RATIO(ps_dec) + + return ret; +} +","@@ -737,6 +737,7 @@ + + ps_dec->u4_deblk_mb_y = 0; + ps_dec->pu4_wt_ofsts = ps_dec->pu4_wts_ofsts_mat; + ++ ps_dec->u4_first_slice_in_pic = 0; + H264_MUTEX_UNLOCK(&ps_dec->process_disp_mutex); + return OK; + } +@@ -1136,7 +1137,7 @@ + + + COPYTHECONTEXT(""SH: frame_num"", u2_frame_num); + // H264_DEC_DEBUG_PRINT(""Second field: %d frame num: %d prv_frame_num: %d \n"", ps_dec->u1_second_field, u2_frame_num, ps_dec->u2_prv_frame_num); +- if(!ps_dec->u1_first_slice_in_stream && (ps_dec->u4_first_slice_in_pic == 2)) ++ if(!ps_dec->u1_first_slice_in_stream && ps_dec->u4_first_slice_in_pic) + { + pocstruct_t *ps_prev_poc = &ps_dec->s_prev_pic_poc; + pocstruct_t *ps_cur_poc = &ps_dec->s_cur_pic_poc; +@@ -1276,7 +1277,7 @@ + + i1_is_end_of_poc = 1; + ps_dec->ps_dec_err_status->u1_err_flag &= MASK_REJECT_CUR_PIC; + +- if(ps_dec->u4_first_slice_in_pic != 2) ++ if(ps_dec->u4_first_slice_in_pic == 0) + { + i1_is_end_of_poc = ih264d_is_end_of_pic(u2_frame_num, u1_nal_ref_idc, + &s_tmp_poc, &ps_dec->s_cur_pic_poc, +@@ -1329,7 +1330,7 @@ + + + u1_is_idr_slice = ps_cur_slice->u1_nal_unit_type == IDR_SLICE_NAL; + } +- else if(ps_dec->u4_first_slice_in_pic == 2) ++ else if(ps_dec->u4_first_slice_in_pic) + { + if(u2_first_mb_in_slice > 0) + { +@@ -1354,25 +1355,12 @@ + + } + else + { +- +- if(ps_dec->u4_first_slice_in_pic) +- { +- /* if valid slice header is not decoded do start of pic processing +- * since in the current process call, frame num is not updated in the slice structure yet +- * ih264d_is_end_of_pic is checked with valid frame num of previous process call, +- * although i1_is_end_of_poc is set there could be more slices in the frame, +- * so conceal only till cur slice */ +- prev_slice_err = 1; +- num_mb_skipped = u2_first_mb_in_slice << u1_mbaff; +- } +- else +- { +- /* since i1_is_end_of_poc is set ,means new frame num is encountered. so conceal the current frame +- * completely */ +- prev_slice_err = 2; +- num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs * ps_dec->u2_frm_wd_in_mbs) +- - ps_dec->u2_total_mbs_coded; +- } ++ /* since i1_is_end_of_poc is set ,means new frame num is encountered. so conceal the current frame ++ * completely */ ++ prev_slice_err = 2; ++ num_mb_skipped = (ps_dec->u2_frm_ht_in_mbs ++ * ps_dec->u2_frm_wd_in_mbs) ++ - ps_dec->u2_total_mbs_coded; + ps_cur_poc = &s_tmp_poc; + } + } +@@ -1475,7 +1463,7 @@ + + ps_dec->ps_cur_pic->i4_poc = i4_temp_poc; + ps_dec->ps_cur_pic->i4_avg_poc = i4_temp_poc; + } +- if(ps_dec->u4_first_slice_in_pic == 2) ++ if(ps_dec->u4_first_slice_in_pic) + { + ret = ih264d_decode_pic_order_cnt(u1_is_idr_slice, u2_frame_num, + &ps_dec->s_prev_pic_poc, +@@ -1543,7 +1531,7 @@ + + ps_dec->pf_mvpred = ih264d_mvpred_nonmbaff; + } + +- if(ps_dec->u4_first_slice_in_pic == 2) ++ if(ps_dec->u4_first_slice_in_pic) + { + if(u2_first_mb_in_slice == 0) + { +@@ -1863,8 +1851,6 @@ + + if(ps_dec->u1_slice_header_done) + { + /* set to zero to indicate a valid slice has been decoded */ +- /* first slice header successfully decoded */ +- ps_dec->u4_first_slice_in_pic = 0; + ps_dec->u1_first_slice_in_stream = 0; + } + +",8541,8872,11000 +8570,"static int ssl_parse_client_hello( mbedtls_ssl_context *ssl ) +{ + int ret, got_common_suite; + size_t i, j; + size_t ciph_offset, comp_offset, ext_offset; + size_t msg_len, ciph_len, sess_len, comp_len, ext_len; +#if defined(MBEDTLS_SSL_PROTO_DTLS) + size_t cookie_offset, cookie_len; +#endif + unsigned char *buf, *p, *ext; +#if defined(MBEDTLS_SSL_RENEGOTIATION) + int renegotiation_info_seen = 0; +#endif + int handshake_failure = 0; + const int *ciphersuites; + const mbedtls_ssl_ciphersuite_t *ciphersuite_info; + int major, minor; + + /* If there is no signature-algorithm extension present, + * we need to fall back to the default values for allowed + * signature-hash pairs. */ +#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ + defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) + int sig_hash_alg_ext_present = 0; +#endif /* MBEDTLS_SSL_PROTO_TLS1_2 && + MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */ + + MBEDTLS_SSL_DEBUG_MSG( 2, ( ""=> parse client hello"" ) ); + +#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) +read_record_header: +#endif + /* + * If renegotiating, then the input was read with mbedtls_ssl_read_record(), + * otherwise read it ourselves manually in order to support SSLv2 + * ClientHello, which doesn't use the same record layer format. + */ +#if defined(MBEDTLS_SSL_RENEGOTIATION) + if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE ) +#endif + { + if( ( ret = mbedtls_ssl_fetch_input( ssl, 5 ) ) != 0 ) + { + /* No alert on a read error. */ + MBEDTLS_SSL_DEBUG_RET( 1, ""mbedtls_ssl_fetch_input"", ret ); + return( ret ); + } + } + + buf = ssl->in_hdr; + +#if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO) +#if defined(MBEDTLS_SSL_PROTO_DTLS) + if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_STREAM ) +#endif + if( ( buf[0] & 0x80 ) != 0 ) + return( ssl_parse_client_hello_v2( ssl ) ); +#endif + + MBEDTLS_SSL_DEBUG_BUF( 4, ""record header"", buf, mbedtls_ssl_hdr_len( ssl ) ); + + /* + * SSLv3/TLS Client Hello + * + * Record layer: + * 0 . 0 message type + * 1 . 2 protocol version + * 3 . 11 DTLS: epoch + record sequence number + * 3 . 4 message length + */ + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""client hello v3, message type: %d"", + buf[0] ) ); + + if( buf[0] != MBEDTLS_SSL_MSG_HANDSHAKE ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""client hello v3, message len.: %d"", + ( ssl->in_len[0] << 8 ) | ssl->in_len[1] ) ); + + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""client hello v3, protocol version: [%d:%d]"", + buf[1], buf[2] ) ); + + mbedtls_ssl_read_version( &major, &minor, ssl->conf->transport, buf + 1 ); + + /* According to RFC 5246 Appendix E.1, the version here is typically + * ""{03,00}, the lowest version number supported by the client, [or] the + * value of ClientHello.client_version"", so the only meaningful check here + * is the major version shouldn't be less than 3 */ + if( major < MBEDTLS_SSL_MAJOR_VERSION_3 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + /* For DTLS if this is the initial handshake, remember the client sequence + * number to use it in our next message (RFC 6347 4.2.1) */ +#if defined(MBEDTLS_SSL_PROTO_DTLS) + if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM +#if defined(MBEDTLS_SSL_RENEGOTIATION) + && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE +#endif + ) + { + /* Epoch should be 0 for initial handshakes */ + if( ssl->in_ctr[0] != 0 || ssl->in_ctr[1] != 0 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + memcpy( ssl->out_ctr + 2, ssl->in_ctr + 2, 6 ); + +#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) + if( mbedtls_ssl_dtls_replay_check( ssl ) != 0 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""replayed record, discarding"" ) ); + ssl->next_record_offset = 0; + ssl->in_left = 0; + goto read_record_header; + } + + /* No MAC to check yet, so we can update right now */ + mbedtls_ssl_dtls_replay_update( ssl ); +#endif + } +#endif /* MBEDTLS_SSL_PROTO_DTLS */ + + msg_len = ( ssl->in_len[0] << 8 ) | ssl->in_len[1]; + +#if defined(MBEDTLS_SSL_RENEGOTIATION) + if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ) + { + /* Set by mbedtls_ssl_read_record() */ + msg_len = ssl->in_hslen; + } + else +#endif + { + if( msg_len > MBEDTLS_SSL_MAX_CONTENT_LEN ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + if( ( ret = mbedtls_ssl_fetch_input( ssl, + mbedtls_ssl_hdr_len( ssl ) + msg_len ) ) != 0 ) + { + MBEDTLS_SSL_DEBUG_RET( 1, ""mbedtls_ssl_fetch_input"", ret ); + return( ret ); + } + + /* Done reading this record, get ready for the next one */ +#if defined(MBEDTLS_SSL_PROTO_DTLS) + if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) + ssl->next_record_offset = msg_len + mbedtls_ssl_hdr_len( ssl ); + else +#endif + ssl->in_left = 0; + } + + buf = ssl->in_msg; + + MBEDTLS_SSL_DEBUG_BUF( 4, ""record contents"", buf, msg_len ); + + ssl->handshake->update_checksum( ssl, buf, msg_len ); + + /* + * Handshake layer: + * 0 . 0 handshake type + * 1 . 3 handshake length + * 4 . 5 DTLS only: message seqence number + * 6 . 8 DTLS only: fragment offset + * 9 . 11 DTLS only: fragment length + */ + if( msg_len < mbedtls_ssl_hs_hdr_len( ssl ) ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""client hello v3, handshake type: %d"", buf[0] ) ); + + if( buf[0] != MBEDTLS_SSL_HS_CLIENT_HELLO ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""client hello v3, handshake len.: %d"", + ( buf[1] << 16 ) | ( buf[2] << 8 ) | buf[3] ) ); + + /* We don't support fragmentation of ClientHello (yet?) */ + if( buf[1] != 0 || + msg_len != mbedtls_ssl_hs_hdr_len( ssl ) + ( ( buf[2] << 8 ) | buf[3] ) ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + +#if defined(MBEDTLS_SSL_PROTO_DTLS) + if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) + { + /* + * Copy the client's handshake message_seq on initial handshakes, + * check sequence number on renego. + */ +#if defined(MBEDTLS_SSL_RENEGOTIATION) + if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) + { + /* This couldn't be done in ssl_prepare_handshake_record() */ + unsigned int cli_msg_seq = ( ssl->in_msg[4] << 8 ) | + ssl->in_msg[5]; + + if( cli_msg_seq != ssl->handshake->in_msg_seq ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message_seq: "" + ""%d (expected %d)"", cli_msg_seq, + ssl->handshake->in_msg_seq ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + ssl->handshake->in_msg_seq++; + } + else +#endif + { + unsigned int cli_msg_seq = ( ssl->in_msg[4] << 8 ) | + ssl->in_msg[5]; + ssl->handshake->out_msg_seq = cli_msg_seq; + ssl->handshake->in_msg_seq = cli_msg_seq + 1; + } + + /* + * For now we don't support fragmentation, so make sure + * fragment_offset == 0 and fragment_length == length + */ + if( ssl->in_msg[6] != 0 || ssl->in_msg[7] != 0 || ssl->in_msg[8] != 0 || + memcmp( ssl->in_msg + 1, ssl->in_msg + 9, 3 ) != 0 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""ClientHello fragmentation not supported"" ) ); + return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); + } + } +#endif /* MBEDTLS_SSL_PROTO_DTLS */ + + buf += mbedtls_ssl_hs_hdr_len( ssl ); + msg_len -= mbedtls_ssl_hs_hdr_len( ssl ); + + /* + * ClientHello layer: + * 0 . 1 protocol version + * 2 . 33 random bytes (starting with 4 bytes of Unix time) + * 34 . 35 session id length (1 byte) + * 35 . 34+x session id + * 35+x . 35+x DTLS only: cookie length (1 byte) + * 36+x . .. DTLS only: cookie + * .. . .. ciphersuite list length (2 bytes) + * .. . .. ciphersuite list + * .. . .. compression alg. list length (1 byte) + * .. . .. compression alg. list + * .. . .. extensions length (2 bytes, optional) + * .. . .. extensions (optional) + */ + + /* + * Minimal length (with everything empty and extensions ommitted) is + * 2 + 32 + 1 + 2 + 1 = 38 bytes. Check that first, so that we can + * read at least up to session id length without worrying. + */ + if( msg_len < 38 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + /* + * Check and save the protocol version + */ + MBEDTLS_SSL_DEBUG_BUF( 3, ""client hello, version"", buf, 2 ); + + mbedtls_ssl_read_version( &ssl->major_ver, &ssl->minor_ver, + ssl->conf->transport, buf ); + + ssl->handshake->max_major_ver = ssl->major_ver; + ssl->handshake->max_minor_ver = ssl->minor_ver; + + if( ssl->major_ver < ssl->conf->min_major_ver || + ssl->minor_ver < ssl->conf->min_minor_ver ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""client only supports ssl smaller than minimum"" + "" [%d:%d] < [%d:%d]"", + ssl->major_ver, ssl->minor_ver, + ssl->conf->min_major_ver, ssl->conf->min_minor_ver ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION ); + return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION ); + } + + if( ssl->major_ver > ssl->conf->max_major_ver ) + { + ssl->major_ver = ssl->conf->max_major_ver; + ssl->minor_ver = ssl->conf->max_minor_ver; + } + else if( ssl->minor_ver > ssl->conf->max_minor_ver ) + ssl->minor_ver = ssl->conf->max_minor_ver; + + /* + * Save client random (inc. Unix time) + */ + MBEDTLS_SSL_DEBUG_BUF( 3, ""client hello, random bytes"", buf + 2, 32 ); + + memcpy( ssl->handshake->randbytes, buf + 2, 32 ); + + /* + * Check the session ID length and save session ID + */ + sess_len = buf[34]; + + if( sess_len > sizeof( ssl->session_negotiate->id ) || + sess_len + 34 + 2 > msg_len ) /* 2 for cipherlist length field */ + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + MBEDTLS_SSL_DEBUG_BUF( 3, ""client hello, session id"", buf + 35, sess_len ); + + ssl->session_negotiate->id_len = sess_len; + memset( ssl->session_negotiate->id, 0, + sizeof( ssl->session_negotiate->id ) ); + memcpy( ssl->session_negotiate->id, buf + 35, + ssl->session_negotiate->id_len ); + + /* + * Check the cookie length and content + */ +#if defined(MBEDTLS_SSL_PROTO_DTLS) + if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) + { + cookie_offset = 35 + sess_len; + cookie_len = buf[cookie_offset]; + + if( cookie_offset + 1 + cookie_len + 2 > msg_len ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + MBEDTLS_SSL_DEBUG_BUF( 3, ""client hello, cookie"", + buf + cookie_offset + 1, cookie_len ); + +#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) + if( ssl->conf->f_cookie_check != NULL +#if defined(MBEDTLS_SSL_RENEGOTIATION) + && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE +#endif + ) + { + if( ssl->conf->f_cookie_check( ssl->conf->p_cookie, + buf + cookie_offset + 1, cookie_len, + ssl->cli_id, ssl->cli_id_len ) != 0 ) + { + MBEDTLS_SSL_DEBUG_MSG( 2, ( ""cookie verification failed"" ) ); + ssl->handshake->verify_cookie_len = 1; + } + else + { + MBEDTLS_SSL_DEBUG_MSG( 2, ( ""cookie verification passed"" ) ); + ssl->handshake->verify_cookie_len = 0; + } + } + else +#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */ + { + /* We know we didn't send a cookie, so it should be empty */ + if( cookie_len != 0 ) + { + /* This may be an attacker's probe, so don't send an alert */ + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + MBEDTLS_SSL_DEBUG_MSG( 2, ( ""cookie verification skipped"" ) ); + } + + /* + * Check the ciphersuitelist length (will be parsed later) + */ + ciph_offset = cookie_offset + 1 + cookie_len; + } + else +#endif /* MBEDTLS_SSL_PROTO_DTLS */ + ciph_offset = 35 + sess_len; + + ciph_len = ( buf[ciph_offset + 0] << 8 ) + | ( buf[ciph_offset + 1] ); + + if( ciph_len < 2 || + ciph_len + 2 + ciph_offset + 1 > msg_len || /* 1 for comp. alg. len */ + ( ciph_len % 2 ) != 0 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + MBEDTLS_SSL_DEBUG_BUF( 3, ""client hello, ciphersuitelist"", + buf + ciph_offset + 2, ciph_len ); + + /* + * Check the compression algorithms length and pick one + */ + comp_offset = ciph_offset + 2 + ciph_len; + + comp_len = buf[comp_offset]; + + if( comp_len < 1 || + comp_len > 16 || + comp_len + comp_offset + 1 > msg_len ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + MBEDTLS_SSL_DEBUG_BUF( 3, ""client hello, compression"", + buf + comp_offset + 1, comp_len ); + + ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_NULL; +#if defined(MBEDTLS_ZLIB_SUPPORT) + for( i = 0; i < comp_len; ++i ) + { + if( buf[comp_offset + 1 + i] == MBEDTLS_SSL_COMPRESS_DEFLATE ) + { + ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_DEFLATE; + break; + } + } +#endif + + /* See comments in ssl_write_client_hello() */ +#if defined(MBEDTLS_SSL_PROTO_DTLS) + if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) + ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_NULL; +#endif + + /* Do not parse the extensions if the protocol is SSLv3 */ +#if defined(MBEDTLS_SSL_PROTO_SSL3) + if( ( ssl->major_ver != 3 ) || ( ssl->minor_ver != 0 ) ) + { +#endif + /* + * Check the extension length + */ + ext_offset = comp_offset + 1 + comp_len; + if( msg_len > ext_offset ) + { + if( msg_len < ext_offset + 2 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + ext_len = ( buf[ext_offset + 0] << 8 ) + | ( buf[ext_offset + 1] ); + + if( ( ext_len > 0 && ext_len < 4 ) || + msg_len != ext_offset + 2 + ext_len ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + } + else + ext_len = 0; + + ext = buf + ext_offset + 2; + MBEDTLS_SSL_DEBUG_BUF( 3, ""client hello extensions"", ext, ext_len ); + + while( ext_len != 0 ) + { + unsigned int ext_id = ( ( ext[0] << 8 ) + | ( ext[1] ) ); + unsigned int ext_size = ( ( ext[2] << 8 ) + | ( ext[3] ) ); + + if( ext_size + 4 > ext_len ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + switch( ext_id ) + { +#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) + case MBEDTLS_TLS_EXT_SERVERNAME: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found ServerName extension"" ) ); + if( ssl->conf->f_sni == NULL ) + break; + + ret = ssl_parse_servername_ext( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + break; +#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ + + case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found renegotiation extension"" ) ); +#if defined(MBEDTLS_SSL_RENEGOTIATION) + renegotiation_info_seen = 1; +#endif + + ret = ssl_parse_renegotiation_info( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + break; + +#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ + defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) + case MBEDTLS_TLS_EXT_SIG_ALG: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found signature_algorithms extension"" ) ); +#if defined(MBEDTLS_SSL_RENEGOTIATION) + if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) + break; +#endif + ret = ssl_parse_signature_algorithms_ext( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + + sig_hash_alg_ext_present = 1; + break; +#endif /* MBEDTLS_SSL_PROTO_TLS1_2 && + MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */ + +#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) + case MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found supported elliptic curves extension"" ) ); + + ret = ssl_parse_supported_elliptic_curves( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + break; + + case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found supported point formats extension"" ) ); + ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT; + + ret = ssl_parse_supported_point_formats( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + break; +#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || + MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ + +#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) + case MBEDTLS_TLS_EXT_ECJPAKE_KKPP: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found ecjpake kkpp extension"" ) ); + + ret = ssl_parse_ecjpake_kkpp( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + break; +#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ + +#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) + case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found max fragment length extension"" ) ); + + ret = ssl_parse_max_fragment_length_ext( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + break; +#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ + +#if defined(MBEDTLS_SSL_TRUNCATED_HMAC) + case MBEDTLS_TLS_EXT_TRUNCATED_HMAC: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found truncated hmac extension"" ) ); + + ret = ssl_parse_truncated_hmac_ext( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + break; +#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ + +#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) + case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found encrypt then mac extension"" ) ); + + ret = ssl_parse_encrypt_then_mac_ext( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + break; +#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ + +#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) + case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found extended master secret extension"" ) ); + + ret = ssl_parse_extended_ms_ext( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + break; +#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ + +#if defined(MBEDTLS_SSL_SESSION_TICKETS) + case MBEDTLS_TLS_EXT_SESSION_TICKET: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found session ticket extension"" ) ); + + ret = ssl_parse_session_ticket_ext( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + break; +#endif /* MBEDTLS_SSL_SESSION_TICKETS */ + +#if defined(MBEDTLS_SSL_ALPN) + case MBEDTLS_TLS_EXT_ALPN: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found alpn extension"" ) ); + + ret = ssl_parse_alpn_ext( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + break; +#endif /* MBEDTLS_SSL_SESSION_TICKETS */ + + default: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""unknown extension found: %d (ignoring)"", + ext_id ) ); + } + + ext_len -= 4 + ext_size; + ext += 4 + ext_size; + + if( ext_len > 0 && ext_len < 4 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + } +#if defined(MBEDTLS_SSL_PROTO_SSL3) + } +#endif + +#if defined(MBEDTLS_SSL_FALLBACK_SCSV) + for( i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2 ) + { + if( p[0] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 ) & 0xff ) && + p[1] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE ) & 0xff ) ) + { + MBEDTLS_SSL_DEBUG_MSG( 2, ( ""received FALLBACK_SCSV"" ) ); + + if( ssl->minor_ver < ssl->conf->max_minor_ver ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""inapropriate fallback"" ) ); + + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK ); + + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + break; + } + } +#endif /* MBEDTLS_SSL_FALLBACK_SCSV */ + +#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ + defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) + + /* + * Try to fall back to default hash SHA1 if the client + * hasn't provided any preferred signature-hash combinations. + */ + if( sig_hash_alg_ext_present == 0 ) + { + mbedtls_md_type_t md_default = MBEDTLS_MD_SHA1; + + if( mbedtls_ssl_check_sig_hash( ssl, md_default ) != 0 ) + md_default = MBEDTLS_MD_NONE; + + mbedtls_ssl_sig_hash_set_const_hash( &ssl->handshake->hash_algs, md_default ); + } + +#endif /* MBEDTLS_SSL_PROTO_TLS1_2 && + MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */ + + /* + * Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV + */ + for( i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2 ) + { + if( p[0] == 0 && p[1] == MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO ) + { + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""received TLS_EMPTY_RENEGOTIATION_INFO "" ) ); +#if defined(MBEDTLS_SSL_RENEGOTIATION) + if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""received RENEGOTIATION SCSV "" + ""during renegotiation"" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } +#endif + ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION; + break; + } + } + + /* + * Renegotiation security checks + */ + if( ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION && + ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""legacy renegotiation, breaking off handshake"" ) ); + handshake_failure = 1; + } +#if defined(MBEDTLS_SSL_RENEGOTIATION) + else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && + ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION && + renegotiation_info_seen == 0 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""renegotiation_info extension missing (secure)"" ) ); + handshake_failure = 1; + } + else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && + ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && + ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""legacy renegotiation not allowed"" ) ); + handshake_failure = 1; + } + else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && + ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && + renegotiation_info_seen == 1 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""renegotiation_info extension present (legacy)"" ) ); + handshake_failure = 1; + } +#endif /* MBEDTLS_SSL_RENEGOTIATION */ + + if( handshake_failure == 1 ) + { + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + /* + * Search for a matching ciphersuite + * (At the end because we need information from the EC-based extensions + * and certificate from the SNI callback triggered by the SNI extension.) + */ + got_common_suite = 0; + ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver]; + ciphersuite_info = NULL; +#if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE) + for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 ) + for( i = 0; ciphersuites[i] != 0; i++ ) +#else + for( i = 0; ciphersuites[i] != 0; i++ ) + for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 ) +#endif + { + if( p[0] != ( ( ciphersuites[i] >> 8 ) & 0xFF ) || + p[1] != ( ( ciphersuites[i] ) & 0xFF ) ) + continue; + + got_common_suite = 1; + + if( ( ret = ssl_ciphersuite_match( ssl, ciphersuites[i], + &ciphersuite_info ) ) != 0 ) + return( ret ); + + if( ciphersuite_info != NULL ) + goto have_ciphersuite; + } + + if( got_common_suite ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""got ciphersuites in common, "" + ""but none of them usable"" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); + return( MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE ); + } + else + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""got no ciphersuites in common"" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); + return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN ); + } + +have_ciphersuite: + MBEDTLS_SSL_DEBUG_MSG( 2, ( ""selected ciphersuite: %s"", ciphersuite_info->name ) ); + + ssl->session_negotiate->ciphersuite = ciphersuites[i]; + ssl->transform_negotiate->ciphersuite_info = ciphersuite_info; + + ssl->state++; + +#if defined(MBEDTLS_SSL_PROTO_DTLS) + if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) + mbedtls_ssl_recv_flight_completed( ssl ); +#endif + + /* Debugging-only output for testsuite */ +#if defined(MBEDTLS_DEBUG_C) && \ + defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ + defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) + if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) + { + mbedtls_pk_type_t sig_alg = mbedtls_ssl_get_ciphersuite_sig_alg( ciphersuite_info ); + if( sig_alg != MBEDTLS_PK_NONE ) + { + mbedtls_md_type_t md_alg = mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs, + sig_alg ); + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""client hello v3, signature_algorithm ext: %d"", + mbedtls_ssl_hash_from_md_alg( md_alg ) ) ); + } + else + { + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""no hash algorithm for signature algorithm "" + ""%d - should not happen"", sig_alg ) ); + } + } +#endif + + MBEDTLS_SSL_DEBUG_MSG( 2, ( ""<= parse client hello"" ) ); + + return( 0 ); +} +",0,"static int ssl_parse_client_hello( mbedtls_ssl_context *ssl ) +{ + int ret, got_common_suite; + size_t i, j; + size_t ciph_offset, comp_offset, ext_offset; + size_t msg_len, ciph_len, sess_len, comp_len, ext_len; +#if defined(MBEDTLS_SSL_PROTO_DTLS) + size_t cookie_offset, cookie_len; +#endif + unsigned char *buf, *p, *ext; +#if defined(MBEDTLS_SSL_RENEGOTIATION) + int renegotiation_info_seen = 0; +#endif + int handshake_failure = 0; + const int *ciphersuites; + const mbedtls_ssl_ciphersuite_t *ciphersuite_info; + int major, minor; + + /* If there is no signature-algorithm extension present, + * we need to fall back to the default values for allowed + * signature-hash pairs. */ +#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ + defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) + int sig_hash_alg_ext_present = 0; +#endif /* MBEDTLS_SSL_PROTO_TLS1_2 && + MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */ + + MBEDTLS_SSL_DEBUG_MSG( 2, ( ""=> parse client hello"" ) ); + +#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) +read_record_header: +#endif + /* + * If renegotiating, then the input was read with mbedtls_ssl_read_record(), + * otherwise read it ourselves manually in order to support SSLv2 + * ClientHello, which doesn't use the same record layer format. + */ +#if defined(MBEDTLS_SSL_RENEGOTIATION) + if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE ) +#endif + { + if( ( ret = mbedtls_ssl_fetch_input( ssl, 5 ) ) != 0 ) + { + /* No alert on a read error. */ + MBEDTLS_SSL_DEBUG_RET( 1, ""mbedtls_ssl_fetch_input"", ret ); + return( ret ); + } + } + + buf = ssl->in_hdr; + +#if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO) +#if defined(MBEDTLS_SSL_PROTO_DTLS) + if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_STREAM ) +#endif + if( ( buf[0] & 0x80 ) != 0 ) + return( ssl_parse_client_hello_v2( ssl ) ); +#endif + + MBEDTLS_SSL_DEBUG_BUF( 4, ""record header"", buf, mbedtls_ssl_hdr_len( ssl ) ); + + /* + * SSLv3/TLS Client Hello + * + * Record layer: + * 0 . 0 message type + * 1 . 2 protocol version + * 3 . 11 DTLS: epoch + record sequence number + * 3 . 4 message length + */ + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""client hello v3, message type: %d"", + buf[0] ) ); + + if( buf[0] != MBEDTLS_SSL_MSG_HANDSHAKE ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""client hello v3, message len.: %d"", + ( ssl->in_len[0] << 8 ) | ssl->in_len[1] ) ); + + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""client hello v3, protocol version: [%d:%d]"", + buf[1], buf[2] ) ); + + mbedtls_ssl_read_version( &major, &minor, ssl->conf->transport, buf + 1 ); + + /* According to RFC 5246 Appendix E.1, the version here is typically + * ""{03,00}, the lowest version number supported by the client, [or] the + * value of ClientHello.client_version"", so the only meaningful check here + * is the major version shouldn't be less than 3 */ + if( major < MBEDTLS_SSL_MAJOR_VERSION_3 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + /* For DTLS if this is the initial handshake, remember the client sequence + * number to use it in our next message (RFC 6347 4.2.1) */ +#if defined(MBEDTLS_SSL_PROTO_DTLS) + if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM +#if defined(MBEDTLS_SSL_RENEGOTIATION) + && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE +#endif + ) + { + /* Epoch should be 0 for initial handshakes */ + if( ssl->in_ctr[0] != 0 || ssl->in_ctr[1] != 0 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + memcpy( ssl->out_ctr + 2, ssl->in_ctr + 2, 6 ); + +#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) + if( mbedtls_ssl_dtls_replay_check( ssl ) != 0 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""replayed record, discarding"" ) ); + ssl->next_record_offset = 0; + ssl->in_left = 0; + goto read_record_header; + } + + /* No MAC to check yet, so we can update right now */ + mbedtls_ssl_dtls_replay_update( ssl ); +#endif + } +#endif /* MBEDTLS_SSL_PROTO_DTLS */ + + msg_len = ( ssl->in_len[0] << 8 ) | ssl->in_len[1]; + +#if defined(MBEDTLS_SSL_RENEGOTIATION) + if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ) + { + /* Set by mbedtls_ssl_read_record() */ + msg_len = ssl->in_hslen; + } + else +#endif + { + if( msg_len > MBEDTLS_SSL_MAX_CONTENT_LEN ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + if( ( ret = mbedtls_ssl_fetch_input( ssl, + mbedtls_ssl_hdr_len( ssl ) + msg_len ) ) != 0 ) + { + MBEDTLS_SSL_DEBUG_RET( 1, ""mbedtls_ssl_fetch_input"", ret ); + return( ret ); + } + + /* Done reading this record, get ready for the next one */ +#if defined(MBEDTLS_SSL_PROTO_DTLS) + if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) + ssl->next_record_offset = msg_len + mbedtls_ssl_hdr_len( ssl ); + else +#endif + ssl->in_left = 0; + } + + buf = ssl->in_msg; + + MBEDTLS_SSL_DEBUG_BUF( 4, ""record contents"", buf, msg_len ); + + ssl->handshake->update_checksum( ssl, buf, msg_len ); + + /* + * Handshake layer: + * 0 . 0 handshake type + * 1 . 3 handshake length + * 4 . 5 DTLS only: message seqence number + * 6 . 8 DTLS only: fragment offset + * 9 . 11 DTLS only: fragment length + */ + if( msg_len < mbedtls_ssl_hs_hdr_len( ssl ) ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""client hello v3, handshake type: %d"", buf[0] ) ); + + if( buf[0] != MBEDTLS_SSL_HS_CLIENT_HELLO ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""client hello v3, handshake len.: %d"", + ( buf[1] << 16 ) | ( buf[2] << 8 ) | buf[3] ) ); + + /* We don't support fragmentation of ClientHello (yet?) */ + if( buf[1] != 0 || + msg_len != mbedtls_ssl_hs_hdr_len( ssl ) + ( ( buf[2] << 8 ) | buf[3] ) ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + +#if defined(MBEDTLS_SSL_PROTO_DTLS) + if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) + { + /* + * Copy the client's handshake message_seq on initial handshakes, + * check sequence number on renego. + */ +#if defined(MBEDTLS_SSL_RENEGOTIATION) + if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) + { + /* This couldn't be done in ssl_prepare_handshake_record() */ + unsigned int cli_msg_seq = ( ssl->in_msg[4] << 8 ) | + ssl->in_msg[5]; + + if( cli_msg_seq != ssl->handshake->in_msg_seq ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message_seq: "" + ""%d (expected %d)"", cli_msg_seq, + ssl->handshake->in_msg_seq ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + ssl->handshake->in_msg_seq++; + } + else +#endif + { + unsigned int cli_msg_seq = ( ssl->in_msg[4] << 8 ) | + ssl->in_msg[5]; + ssl->handshake->out_msg_seq = cli_msg_seq; + ssl->handshake->in_msg_seq = cli_msg_seq + 1; + } + + /* + * For now we don't support fragmentation, so make sure + * fragment_offset == 0 and fragment_length == length + */ + if( ssl->in_msg[6] != 0 || ssl->in_msg[7] != 0 || ssl->in_msg[8] != 0 || + memcmp( ssl->in_msg + 1, ssl->in_msg + 9, 3 ) != 0 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""ClientHello fragmentation not supported"" ) ); + return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); + } + } +#endif /* MBEDTLS_SSL_PROTO_DTLS */ + + buf += mbedtls_ssl_hs_hdr_len( ssl ); + msg_len -= mbedtls_ssl_hs_hdr_len( ssl ); + + /* + * ClientHello layer: + * 0 . 1 protocol version + * 2 . 33 random bytes (starting with 4 bytes of Unix time) + * 34 . 35 session id length (1 byte) + * 35 . 34+x session id + * 35+x . 35+x DTLS only: cookie length (1 byte) + * 36+x . .. DTLS only: cookie + * .. . .. ciphersuite list length (2 bytes) + * .. . .. ciphersuite list + * .. . .. compression alg. list length (1 byte) + * .. . .. compression alg. list + * .. . .. extensions length (2 bytes, optional) + * .. . .. extensions (optional) + */ + + /* + * Minimal length (with everything empty and extensions ommitted) is + * 2 + 32 + 1 + 2 + 1 = 38 bytes. Check that first, so that we can + * read at least up to session id length without worrying. + */ + if( msg_len < 38 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + /* + * Check and save the protocol version + */ + MBEDTLS_SSL_DEBUG_BUF( 3, ""client hello, version"", buf, 2 ); + + mbedtls_ssl_read_version( &ssl->major_ver, &ssl->minor_ver, + ssl->conf->transport, buf ); + + ssl->handshake->max_major_ver = ssl->major_ver; + ssl->handshake->max_minor_ver = ssl->minor_ver; + + if( ssl->major_ver < ssl->conf->min_major_ver || + ssl->minor_ver < ssl->conf->min_minor_ver ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""client only supports ssl smaller than minimum"" + "" [%d:%d] < [%d:%d]"", + ssl->major_ver, ssl->minor_ver, + ssl->conf->min_major_ver, ssl->conf->min_minor_ver ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION ); + return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION ); + } + + if( ssl->major_ver > ssl->conf->max_major_ver ) + { + ssl->major_ver = ssl->conf->max_major_ver; + ssl->minor_ver = ssl->conf->max_minor_ver; + } + else if( ssl->minor_ver > ssl->conf->max_minor_ver ) + ssl->minor_ver = ssl->conf->max_minor_ver; + + /* + * Save client random (inc. Unix time) + */ + MBEDTLS_SSL_DEBUG_BUF( 3, ""client hello, random bytes"", buf + 2, 32 ); + + memcpy( ssl->handshake->randbytes, buf + 2, 32 ); + + /* + * Check the session ID length and save session ID + */ + sess_len = buf[34]; + + if( sess_len > sizeof( ssl->session_negotiate->id ) || + sess_len + 34 + 2 > msg_len ) /* 2 for cipherlist length field */ + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + MBEDTLS_SSL_DEBUG_BUF( 3, ""client hello, session id"", buf + 35, sess_len ); + + ssl->session_negotiate->id_len = sess_len; + memset( ssl->session_negotiate->id, 0, + sizeof( ssl->session_negotiate->id ) ); + memcpy( ssl->session_negotiate->id, buf + 35, + ssl->session_negotiate->id_len ); + + /* + * Check the cookie length and content + */ +#if defined(MBEDTLS_SSL_PROTO_DTLS) + if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) + { + cookie_offset = 35 + sess_len; + cookie_len = buf[cookie_offset]; + + if( cookie_offset + 1 + cookie_len + 2 > msg_len ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + MBEDTLS_SSL_DEBUG_BUF( 3, ""client hello, cookie"", + buf + cookie_offset + 1, cookie_len ); + +#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) + if( ssl->conf->f_cookie_check != NULL +#if defined(MBEDTLS_SSL_RENEGOTIATION) + && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE +#endif + ) + { + if( ssl->conf->f_cookie_check( ssl->conf->p_cookie, + buf + cookie_offset + 1, cookie_len, + ssl->cli_id, ssl->cli_id_len ) != 0 ) + { + MBEDTLS_SSL_DEBUG_MSG( 2, ( ""cookie verification failed"" ) ); + ssl->handshake->verify_cookie_len = 1; + } + else + { + MBEDTLS_SSL_DEBUG_MSG( 2, ( ""cookie verification passed"" ) ); + ssl->handshake->verify_cookie_len = 0; + } + } + else +#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */ + { + /* We know we didn't send a cookie, so it should be empty */ + if( cookie_len != 0 ) + { + /* This may be an attacker's probe, so don't send an alert */ + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + MBEDTLS_SSL_DEBUG_MSG( 2, ( ""cookie verification skipped"" ) ); + } + + /* + * Check the ciphersuitelist length (will be parsed later) + */ + ciph_offset = cookie_offset + 1 + cookie_len; + } + else +#endif /* MBEDTLS_SSL_PROTO_DTLS */ + ciph_offset = 35 + sess_len; + + ciph_len = ( buf[ciph_offset + 0] << 8 ) + | ( buf[ciph_offset + 1] ); + + if( ciph_len < 2 || + ciph_len + 2 + ciph_offset + 1 > msg_len || /* 1 for comp. alg. len */ + ( ciph_len % 2 ) != 0 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + MBEDTLS_SSL_DEBUG_BUF( 3, ""client hello, ciphersuitelist"", + buf + ciph_offset + 2, ciph_len ); + + /* + * Check the compression algorithms length and pick one + */ + comp_offset = ciph_offset + 2 + ciph_len; + + comp_len = buf[comp_offset]; + + if( comp_len < 1 || + comp_len > 16 || + comp_len + comp_offset + 1 > msg_len ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + MBEDTLS_SSL_DEBUG_BUF( 3, ""client hello, compression"", + buf + comp_offset + 1, comp_len ); + + ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_NULL; +#if defined(MBEDTLS_ZLIB_SUPPORT) + for( i = 0; i < comp_len; ++i ) + { + if( buf[comp_offset + 1 + i] == MBEDTLS_SSL_COMPRESS_DEFLATE ) + { + ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_DEFLATE; + break; + } + } +#endif + + /* See comments in ssl_write_client_hello() */ +#if defined(MBEDTLS_SSL_PROTO_DTLS) + if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) + ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_NULL; +#endif + + /* Do not parse the extensions if the protocol is SSLv3 */ +#if defined(MBEDTLS_SSL_PROTO_SSL3) + if( ( ssl->major_ver != 3 ) || ( ssl->minor_ver != 0 ) ) + { +#endif + /* + * Check the extension length + */ + ext_offset = comp_offset + 1 + comp_len; + if( msg_len > ext_offset ) + { + if( msg_len < ext_offset + 2 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + ext_len = ( buf[ext_offset + 0] << 8 ) + | ( buf[ext_offset + 1] ); + + if( ( ext_len > 0 && ext_len < 4 ) || + msg_len != ext_offset + 2 + ext_len ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + } + else + ext_len = 0; + + ext = buf + ext_offset + 2; + MBEDTLS_SSL_DEBUG_BUF( 3, ""client hello extensions"", ext, ext_len ); + + while( ext_len != 0 ) + { + unsigned int ext_id = ( ( ext[0] << 8 ) + | ( ext[1] ) ); + unsigned int ext_size = ( ( ext[2] << 8 ) + | ( ext[3] ) ); + + if( ext_size + 4 > ext_len ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + switch( ext_id ) + { +#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) + case MBEDTLS_TLS_EXT_SERVERNAME: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found ServerName extension"" ) ); + if( ssl->conf->f_sni == NULL ) + break; + + ret = ssl_parse_servername_ext( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + break; +#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ + + case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found renegotiation extension"" ) ); +#if defined(MBEDTLS_SSL_RENEGOTIATION) + renegotiation_info_seen = 1; +#endif + + ret = ssl_parse_renegotiation_info( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + break; + +#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ + defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) + case MBEDTLS_TLS_EXT_SIG_ALG: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found signature_algorithms extension"" ) ); +#if defined(MBEDTLS_SSL_RENEGOTIATION) + if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) + break; +#endif + ret = ssl_parse_signature_algorithms_ext( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + + sig_hash_alg_ext_present = 1; + break; +#endif /* MBEDTLS_SSL_PROTO_TLS1_2 && + MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */ + +#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ + defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) + case MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found supported elliptic curves extension"" ) ); + + ret = ssl_parse_supported_elliptic_curves( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + break; + + case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found supported point formats extension"" ) ); + ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT; + + ret = ssl_parse_supported_point_formats( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + break; +#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || + MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ + +#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) + case MBEDTLS_TLS_EXT_ECJPAKE_KKPP: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found ecjpake kkpp extension"" ) ); + + ret = ssl_parse_ecjpake_kkpp( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + break; +#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ + +#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) + case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found max fragment length extension"" ) ); + + ret = ssl_parse_max_fragment_length_ext( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + break; +#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ + +#if defined(MBEDTLS_SSL_TRUNCATED_HMAC) + case MBEDTLS_TLS_EXT_TRUNCATED_HMAC: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found truncated hmac extension"" ) ); + + ret = ssl_parse_truncated_hmac_ext( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + break; +#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ + +#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) + case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found encrypt then mac extension"" ) ); + + ret = ssl_parse_encrypt_then_mac_ext( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + break; +#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ + +#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) + case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found extended master secret extension"" ) ); + + ret = ssl_parse_extended_ms_ext( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + break; +#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ + +#if defined(MBEDTLS_SSL_SESSION_TICKETS) + case MBEDTLS_TLS_EXT_SESSION_TICKET: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found session ticket extension"" ) ); + + ret = ssl_parse_session_ticket_ext( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + break; +#endif /* MBEDTLS_SSL_SESSION_TICKETS */ + +#if defined(MBEDTLS_SSL_ALPN) + case MBEDTLS_TLS_EXT_ALPN: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""found alpn extension"" ) ); + + ret = ssl_parse_alpn_ext( ssl, ext + 4, ext_size ); + if( ret != 0 ) + return( ret ); + break; +#endif /* MBEDTLS_SSL_SESSION_TICKETS */ + + default: + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""unknown extension found: %d (ignoring)"", + ext_id ) ); + } + + ext_len -= 4 + ext_size; + ext += 4 + ext_size; + + if( ext_len > 0 && ext_len < 4 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client hello message"" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + } +#if defined(MBEDTLS_SSL_PROTO_SSL3) + } +#endif + +#if defined(MBEDTLS_SSL_FALLBACK_SCSV) + for( i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2 ) + { + if( p[0] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 ) & 0xff ) && + p[1] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE ) & 0xff ) ) + { + MBEDTLS_SSL_DEBUG_MSG( 2, ( ""received FALLBACK_SCSV"" ) ); + + if( ssl->minor_ver < ssl->conf->max_minor_ver ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""inapropriate fallback"" ) ); + + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK ); + + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + break; + } + } +#endif /* MBEDTLS_SSL_FALLBACK_SCSV */ + +#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ + defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) + + /* + * Try to fall back to default hash SHA1 if the client + * hasn't provided any preferred signature-hash combinations. + */ + if( sig_hash_alg_ext_present == 0 ) + { + mbedtls_md_type_t md_default = MBEDTLS_MD_SHA1; + + if( mbedtls_ssl_check_sig_hash( ssl, md_default ) != 0 ) + md_default = MBEDTLS_MD_NONE; + + mbedtls_ssl_sig_hash_set_const_hash( &ssl->handshake->hash_algs, md_default ); + } + +#endif /* MBEDTLS_SSL_PROTO_TLS1_2 && + MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */ + + /* + * Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV + */ + for( i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2 ) + { + if( p[0] == 0 && p[1] == MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO ) + { + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""received TLS_EMPTY_RENEGOTIATION_INFO "" ) ); +#if defined(MBEDTLS_SSL_RENEGOTIATION) + if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""received RENEGOTIATION SCSV "" + ""during renegotiation"" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } +#endif + ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION; + break; + } + } + + /* + * Renegotiation security checks + */ + if( ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION && + ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""legacy renegotiation, breaking off handshake"" ) ); + handshake_failure = 1; + } +#if defined(MBEDTLS_SSL_RENEGOTIATION) + else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && + ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION && + renegotiation_info_seen == 0 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""renegotiation_info extension missing (secure)"" ) ); + handshake_failure = 1; + } + else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && + ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && + ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""legacy renegotiation not allowed"" ) ); + handshake_failure = 1; + } + else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && + ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && + renegotiation_info_seen == 1 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""renegotiation_info extension present (legacy)"" ) ); + handshake_failure = 1; + } +#endif /* MBEDTLS_SSL_RENEGOTIATION */ + + if( handshake_failure == 1 ) + { + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); + } + + /* + * Search for a matching ciphersuite + * (At the end because we need information from the EC-based extensions + * and certificate from the SNI callback triggered by the SNI extension.) + */ + got_common_suite = 0; + ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver]; + ciphersuite_info = NULL; +#if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE) + for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 ) + for( i = 0; ciphersuites[i] != 0; i++ ) +#else + for( i = 0; ciphersuites[i] != 0; i++ ) + for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 ) +#endif + { + if( p[0] != ( ( ciphersuites[i] >> 8 ) & 0xFF ) || + p[1] != ( ( ciphersuites[i] ) & 0xFF ) ) + continue; + + got_common_suite = 1; + + if( ( ret = ssl_ciphersuite_match( ssl, ciphersuites[i], + &ciphersuite_info ) ) != 0 ) + return( ret ); + + if( ciphersuite_info != NULL ) + goto have_ciphersuite; + } + + if( got_common_suite ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""got ciphersuites in common, "" + ""but none of them usable"" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); + return( MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE ); + } + else + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""got no ciphersuites in common"" ) ); + mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, + MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); + return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN ); + } + +have_ciphersuite: + MBEDTLS_SSL_DEBUG_MSG( 2, ( ""selected ciphersuite: %s"", ciphersuite_info->name ) ); + + ssl->session_negotiate->ciphersuite = ciphersuites[i]; + ssl->transform_negotiate->ciphersuite_info = ciphersuite_info; + + ssl->state++; + +#if defined(MBEDTLS_SSL_PROTO_DTLS) + if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) + mbedtls_ssl_recv_flight_completed( ssl ); +#endif + + /* Debugging-only output for testsuite */ +#if defined(MBEDTLS_DEBUG_C) && \ + defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ + defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED) + if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) + { + mbedtls_pk_type_t sig_alg = mbedtls_ssl_get_ciphersuite_sig_alg( ciphersuite_info ); + if( sig_alg != MBEDTLS_PK_NONE ) + { + mbedtls_md_type_t md_alg = mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs, + sig_alg ); + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""client hello v3, signature_algorithm ext: %d"", + mbedtls_ssl_hash_from_md_alg( md_alg ) ) ); + } + else + { + MBEDTLS_SSL_DEBUG_MSG( 3, ( ""no hash algorithm for signature algorithm "" + ""%d - should not happen"", sig_alg ) ); + } + } +#endif + + MBEDTLS_SSL_DEBUG_MSG( 2, ( ""<= parse client hello"" ) ); + + return( 0 ); +} +","@@ -3436,7 +3436,7 @@ static int ssl_parse_client_psk_identity( mbedtls_ssl_context *ssl, unsigned cha + /* + * Receive client pre-shared key identity name + */ +- if( *p + 2 > end ) ++ if( end - *p < 2 ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client key exchange message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); +@@ -3445,7 +3445,7 @@ static int ssl_parse_client_psk_identity( mbedtls_ssl_context *ssl, unsigned cha + n = ( (*p)[0] << 8 ) | (*p)[1]; + *p += 2; + +- if( n < 1 || n > 65535 || *p + n > end ) ++ if( n < 1 || n > 65535 || n > (size_t) ( end - *p ) ) + { + MBEDTLS_SSL_DEBUG_MSG( 1, ( ""bad client key exchange message"" ) ); + return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );",8223,8554,11000 +6225,"bgp_attr_print(netdissect_options *ndo, + u_int atype, const u_char *pptr, u_int len) +{ + int i; + uint16_t af; + uint8_t safi, snpa, nhlen; + union { /* copy buffer for bandwidth values */ + float f; + uint32_t i; + } bw; + int advance; + u_int tlen; + const u_char *tptr; + char buf[MAXHOSTNAMELEN + 100]; + int as_size; + + tptr = pptr; + tlen=len; + + switch (atype) { + case BGPTYPE_ORIGIN: + if (len != 1) + ND_PRINT((ndo, ""invalid len"")); + else { + ND_TCHECK(*tptr); + ND_PRINT((ndo, ""%s"", tok2str(bgp_origin_values, + ""Unknown Origin Typecode"", + tptr[0]))); + } + break; + + /* + * Process AS4 byte path and AS2 byte path attributes here. + */ + case BGPTYPE_AS4_PATH: + case BGPTYPE_AS_PATH: + if (len % 2) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + if (!len) { + ND_PRINT((ndo, ""empty"")); + break; + } + + /* + * BGP updates exchanged between New speakers that support 4 + * byte AS, ASs are always encoded in 4 bytes. There is no + * definitive way to find this, just by the packet's + * contents. So, check for packet's TLV's sanity assuming + * 2 bytes first, and it does not pass, assume that ASs are + * encoded in 4 bytes format and move on. + */ + as_size = bgp_attr_get_as_size(ndo, atype, pptr, len); + + while (tptr < pptr + len) { + ND_TCHECK(tptr[0]); + ND_PRINT((ndo, ""%s"", tok2str(bgp_as_path_segment_open_values, + ""?"", tptr[0]))); + ND_TCHECK(tptr[1]); + for (i = 0; i < tptr[1] * as_size; i += as_size) { + ND_TCHECK2(tptr[2 + i], as_size); + ND_PRINT((ndo, ""%s "", + as_printf(ndo, astostr, sizeof(astostr), + as_size == 2 ? + EXTRACT_16BITS(&tptr[2 + i]) : + EXTRACT_32BITS(&tptr[2 + i])))); + } + ND_TCHECK(tptr[0]); + ND_PRINT((ndo, ""%s"", tok2str(bgp_as_path_segment_close_values, + ""?"", tptr[0]))); + ND_TCHECK(tptr[1]); + tptr += 2 + tptr[1] * as_size; + } + break; + case BGPTYPE_NEXT_HOP: + if (len != 4) + ND_PRINT((ndo, ""invalid len"")); + else { + ND_TCHECK2(tptr[0], 4); + ND_PRINT((ndo, ""%s"", ipaddr_string(ndo, tptr))); + } + break; + case BGPTYPE_MULTI_EXIT_DISC: + case BGPTYPE_LOCAL_PREF: + if (len != 4) + ND_PRINT((ndo, ""invalid len"")); + else { + ND_TCHECK2(tptr[0], 4); + ND_PRINT((ndo, ""%u"", EXTRACT_32BITS(tptr))); + } + break; + case BGPTYPE_ATOMIC_AGGREGATE: + if (len != 0) + ND_PRINT((ndo, ""invalid len"")); + break; + case BGPTYPE_AGGREGATOR: + + /* + * Depending on the AS encoded is of 2 bytes or of 4 bytes, + * the length of this PA can be either 6 bytes or 8 bytes. + */ + if (len != 6 && len != 8) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + ND_TCHECK2(tptr[0], len); + if (len == 6) { + ND_PRINT((ndo, "" AS #%s, origin %s"", + as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)), + ipaddr_string(ndo, tptr + 2))); + } else { + ND_PRINT((ndo, "" AS #%s, origin %s"", + as_printf(ndo, astostr, sizeof(astostr), + EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); + } + break; + case BGPTYPE_AGGREGATOR4: + if (len != 8) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + ND_TCHECK2(tptr[0], 8); + ND_PRINT((ndo, "" AS #%s, origin %s"", + as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), + ipaddr_string(ndo, tptr + 4))); + break; + case BGPTYPE_COMMUNITIES: + if (len % 4) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + while (tlen>0) { + uint32_t comm; + ND_TCHECK2(tptr[0], 4); + comm = EXTRACT_32BITS(tptr); + switch (comm) { + case BGP_COMMUNITY_NO_EXPORT: + ND_PRINT((ndo, "" NO_EXPORT"")); + break; + case BGP_COMMUNITY_NO_ADVERT: + ND_PRINT((ndo, "" NO_ADVERTISE"")); + break; + case BGP_COMMUNITY_NO_EXPORT_SUBCONFED: + ND_PRINT((ndo, "" NO_EXPORT_SUBCONFED"")); + break; + default: + ND_PRINT((ndo, ""%u:%u%s"", + (comm >> 16) & 0xffff, + comm & 0xffff, + (tlen>4) ? "", "" : """")); + break; + } + tlen -=4; + tptr +=4; + } + break; + case BGPTYPE_ORIGINATOR_ID: + if (len != 4) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + ND_TCHECK2(tptr[0], 4); + ND_PRINT((ndo, ""%s"",ipaddr_string(ndo, tptr))); + break; + case BGPTYPE_CLUSTER_LIST: + if (len % 4) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + while (tlen>0) { + ND_TCHECK2(tptr[0], 4); + ND_PRINT((ndo, ""%s%s"", + ipaddr_string(ndo, tptr), + (tlen>4) ? "", "" : """")); + tlen -=4; + tptr +=4; + } + break; + case BGPTYPE_MP_REACH_NLRI: + ND_TCHECK2(tptr[0], 3); + af = EXTRACT_16BITS(tptr); + safi = tptr[2]; + + ND_PRINT((ndo, ""\n\t AFI: %s (%u), %sSAFI: %s (%u)"", + tok2str(af_values, ""Unknown AFI"", af), + af, + (safi>128) ? ""vendor specific "" : """", /* 128 is meanwhile wellknown */ + tok2str(bgp_safi_values, ""Unknown SAFI"", safi), + safi)); + + switch(af<<8 | safi) { + case (AFNUM_INET<<8 | SAFNUM_UNICAST): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): + case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): + case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): + case (AFNUM_INET<<8 | SAFNUM_MDT): + case (AFNUM_INET6<<8 | SAFNUM_UNICAST): + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): + case (AFNUM_VPLS<<8 | SAFNUM_VPLS): + break; + default: + ND_TCHECK2(tptr[0], tlen); + ND_PRINT((ndo, ""\n\t no AFI %u / SAFI %u decoder"", af, safi)); + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, tptr, ""\n\t "", tlen); + goto done; + break; + } + + tptr +=3; + + ND_TCHECK(tptr[0]); + nhlen = tptr[0]; + tlen = nhlen; + tptr++; + + if (tlen) { + int nnh = 0; + ND_PRINT((ndo, ""\n\t nexthop: "")); + while (tlen > 0) { + if ( nnh++ > 0 ) { + ND_PRINT((ndo, "", "" )); + } + switch(af<<8 | safi) { + case (AFNUM_INET<<8 | SAFNUM_UNICAST): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): + case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): + case (AFNUM_INET<<8 | SAFNUM_MDT): + if (tlen < (int)sizeof(struct in_addr)) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], sizeof(struct in_addr)); + ND_PRINT((ndo, ""%s"",ipaddr_string(ndo, tptr))); + tlen -= sizeof(struct in_addr); + tptr += sizeof(struct in_addr); + } + break; + case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): + if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN); + ND_PRINT((ndo, ""RD: %s, %s"", + bgp_vpn_rd_print(ndo, tptr), + ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN))); + tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN); + tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN); + } + break; + case (AFNUM_INET6<<8 | SAFNUM_UNICAST): + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): + if (tlen < (int)sizeof(struct in6_addr)) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], sizeof(struct in6_addr)); + ND_PRINT((ndo, ""%s"", ip6addr_string(ndo, tptr))); + tlen -= sizeof(struct in6_addr); + tptr += sizeof(struct in6_addr); + } + break; + case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): + if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN); + ND_PRINT((ndo, ""RD: %s, %s"", + bgp_vpn_rd_print(ndo, tptr), + ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN))); + tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); + tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); + } + break; + case (AFNUM_VPLS<<8 | SAFNUM_VPLS): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): + if (tlen < (int)sizeof(struct in_addr)) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], sizeof(struct in_addr)); + ND_PRINT((ndo, ""%s"", ipaddr_string(ndo, tptr))); + tlen -= (sizeof(struct in_addr)); + tptr += (sizeof(struct in_addr)); + } + break; + case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): + ND_TCHECK2(tptr[0], tlen); + ND_PRINT((ndo, ""%s"", isonsap_string(ndo, tptr, tlen))); + tptr += tlen; + tlen = 0; + break; + + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): + if (tlen < BGP_VPN_RD_LEN+1) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], tlen); + ND_PRINT((ndo, ""RD: %s, %s"", + bgp_vpn_rd_print(ndo, tptr), + isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN))); + /* rfc986 mapped IPv4 address ? */ + if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601) + ND_PRINT((ndo, "" = %s"", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4))); + /* rfc1888 mapped IPv6 address ? */ + else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000) + ND_PRINT((ndo, "" = %s"", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3))); + tptr += tlen; + tlen = 0; + } + break; + default: + ND_TCHECK2(tptr[0], tlen); + ND_PRINT((ndo, ""no AFI %u/SAFI %u decoder"", af, safi)); + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, tptr, ""\n\t "", tlen); + tptr += tlen; + tlen = 0; + goto done; + break; + } + } + } + ND_PRINT((ndo, "", nh-length: %u"", nhlen)); + tptr += tlen; + + ND_TCHECK(tptr[0]); + snpa = tptr[0]; + tptr++; + + if (snpa) { + ND_PRINT((ndo, ""\n\t %u SNPA"", snpa)); + for (/*nothing*/; snpa > 0; snpa--) { + ND_TCHECK(tptr[0]); + ND_PRINT((ndo, ""\n\t %d bytes"", tptr[0])); + tptr += tptr[0] + 1; + } + } else { + ND_PRINT((ndo, "", no SNPA"")); + } + + while (tptr < pptr + len) { + switch (af<<8 | safi) { + case (AFNUM_INET<<8 | SAFNUM_UNICAST): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): + advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): + advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): + advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): + advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + + case (AFNUM_INET<<8 | SAFNUM_MDT): + advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_UNICAST): + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): + advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): + advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_VPLS<<8 | SAFNUM_VPLS): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): + advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + default: + ND_TCHECK2(*tptr,tlen); + ND_PRINT((ndo, ""\n\t no AFI %u / SAFI %u decoder"", af, safi)); + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, tptr, ""\n\t "", tlen); + advance = 0; + tptr = pptr + len; + break; + } + if (advance < 0) + break; + tptr += advance; + } + done: + break; + + case BGPTYPE_MP_UNREACH_NLRI: + ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE); + af = EXTRACT_16BITS(tptr); + safi = tptr[2]; + + ND_PRINT((ndo, ""\n\t AFI: %s (%u), %sSAFI: %s (%u)"", + tok2str(af_values, ""Unknown AFI"", af), + af, + (safi>128) ? ""vendor specific "" : """", /* 128 is meanwhile wellknown */ + tok2str(bgp_safi_values, ""Unknown SAFI"", safi), + safi)); + + if (len == BGP_MP_NLRI_MINSIZE) + ND_PRINT((ndo, ""\n\t End-of-Rib Marker (empty NLRI)"")); + + tptr += 3; + + while (tptr < pptr + len) { + switch (af<<8 | safi) { + case (AFNUM_INET<<8 | SAFNUM_UNICAST): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): + advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): + advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_UNICAST): + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): + advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): + advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_VPLS<<8 | SAFNUM_VPLS): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): + advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_MDT): + advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): + advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + default: + ND_TCHECK2(*(tptr-3),tlen); + ND_PRINT((ndo, ""no AFI %u / SAFI %u decoder"", af, safi)); + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, tptr-3, ""\n\t "", tlen); + advance = 0; + tptr = pptr + len; + break; + } + if (advance < 0) + break; + tptr += advance; + } + break; + case BGPTYPE_EXTD_COMMUNITIES: + if (len % 8) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + while (tlen>0) { + uint16_t extd_comm; + + ND_TCHECK2(tptr[0], 2); + extd_comm=EXTRACT_16BITS(tptr); + + ND_PRINT((ndo, ""\n\t %s (0x%04x), Flags [%s]"", + tok2str(bgp_extd_comm_subtype_values, + ""unknown extd community typecode"", + extd_comm), + extd_comm, + bittok2str(bgp_extd_comm_flag_values, ""none"", extd_comm))); + + ND_TCHECK2(*(tptr+2), 6); + switch(extd_comm) { + case BGP_EXT_COM_RT_0: + case BGP_EXT_COM_RO_0: + case BGP_EXT_COM_L2VPN_RT_0: + ND_PRINT((ndo, "": %u:%u (= %s)"", + EXTRACT_16BITS(tptr+2), + EXTRACT_32BITS(tptr+4), + ipaddr_string(ndo, tptr+4))); + break; + case BGP_EXT_COM_RT_1: + case BGP_EXT_COM_RO_1: + case BGP_EXT_COM_L2VPN_RT_1: + case BGP_EXT_COM_VRF_RT_IMP: + ND_PRINT((ndo, "": %s:%u"", + ipaddr_string(ndo, tptr+2), + EXTRACT_16BITS(tptr+6))); + break; + case BGP_EXT_COM_RT_2: + case BGP_EXT_COM_RO_2: + ND_PRINT((ndo, "": %s:%u"", + as_printf(ndo, astostr, sizeof(astostr), + EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6))); + break; + case BGP_EXT_COM_LINKBAND: + bw.i = EXTRACT_32BITS(tptr+2); + ND_PRINT((ndo, "": bandwidth: %.3f Mbps"", + bw.f*8/1000000)); + break; + case BGP_EXT_COM_VPN_ORIGIN: + case BGP_EXT_COM_VPN_ORIGIN2: + case BGP_EXT_COM_VPN_ORIGIN3: + case BGP_EXT_COM_VPN_ORIGIN4: + case BGP_EXT_COM_OSPF_RID: + case BGP_EXT_COM_OSPF_RID2: + ND_PRINT((ndo, ""%s"", ipaddr_string(ndo, tptr+2))); + break; + case BGP_EXT_COM_OSPF_RTYPE: + case BGP_EXT_COM_OSPF_RTYPE2: + ND_PRINT((ndo, "": area:%s, router-type:%s, metric-type:%s%s"", + ipaddr_string(ndo, tptr+2), + tok2str(bgp_extd_comm_ospf_rtype_values, + ""unknown (0x%02x)"", + *(tptr+6)), + (*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? ""E2"" : """", + ((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? ""E1"" : """")); + break; + case BGP_EXT_COM_L2INFO: + ND_PRINT((ndo, "": %s Control Flags [0x%02x]:MTU %u"", + tok2str(l2vpn_encaps_values, + ""unknown encaps"", + *(tptr+2)), + *(tptr+3), + EXTRACT_16BITS(tptr+4))); + break; + case BGP_EXT_COM_SOURCE_AS: + ND_PRINT((ndo, "": AS %u"", EXTRACT_16BITS(tptr+2))); + break; + default: + ND_TCHECK2(*tptr,8); + print_unknown_data(ndo, tptr, ""\n\t "", 8); + break; + } + tlen -=8; + tptr +=8; + } + break; + + case BGPTYPE_PMSI_TUNNEL: + { + uint8_t tunnel_type, flags; + + ND_TCHECK2(tptr[0], 5); + tunnel_type = *(tptr+1); + flags = *tptr; + tlen = len; + + ND_PRINT((ndo, ""\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u"", + tok2str(bgp_pmsi_tunnel_values, ""Unknown"", tunnel_type), + tunnel_type, + bittok2str(bgp_pmsi_flag_values, ""none"", flags), + EXTRACT_24BITS(tptr+2)>>4)); + + tptr +=5; + tlen -= 5; + + switch (tunnel_type) { + case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */ + case BGP_PMSI_TUNNEL_PIM_BIDIR: + ND_TCHECK2(tptr[0], 8); + ND_PRINT((ndo, ""\n\t Sender %s, P-Group %s"", + ipaddr_string(ndo, tptr), + ipaddr_string(ndo, tptr+4))); + break; + + case BGP_PMSI_TUNNEL_PIM_SSM: + ND_TCHECK2(tptr[0], 8); + ND_PRINT((ndo, ""\n\t Root-Node %s, P-Group %s"", + ipaddr_string(ndo, tptr), + ipaddr_string(ndo, tptr+4))); + break; + case BGP_PMSI_TUNNEL_INGRESS: + ND_TCHECK2(tptr[0], 4); + ND_PRINT((ndo, ""\n\t Tunnel-Endpoint %s"", + ipaddr_string(ndo, tptr))); + break; + case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */ + case BGP_PMSI_TUNNEL_LDP_MP2MP: + ND_TCHECK2(tptr[0], 8); + ND_PRINT((ndo, ""\n\t Root-Node %s, LSP-ID 0x%08x"", + ipaddr_string(ndo, tptr), + EXTRACT_32BITS(tptr+4))); + break; + case BGP_PMSI_TUNNEL_RSVP_P2MP: + ND_TCHECK2(tptr[0], 8); + ND_PRINT((ndo, ""\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x"", + ipaddr_string(ndo, tptr), + EXTRACT_32BITS(tptr+4))); + break; + default: + if (ndo->ndo_vflag <= 1) { + print_unknown_data(ndo, tptr, ""\n\t "", tlen); + } + } + break; + } + case BGPTYPE_AIGP: + { + uint8_t type; + uint16_t length; + + tlen = len; + + while (tlen >= 3) { + + ND_TCHECK2(tptr[0], 3); + + type = *tptr; + length = EXTRACT_16BITS(tptr+1); + tptr += 3; + tlen -= 3; + + ND_PRINT((ndo, ""\n\t %s TLV (%u), length %u"", + tok2str(bgp_aigp_values, ""Unknown"", type), + type, length)); + + if (length < 3) + goto trunc; + length -= 3; + + /* + * Check if we can read the TLV data. + */ + ND_TCHECK2(tptr[3], length); + + switch (type) { + + case BGP_AIGP_TLV: + if (length < 8) + goto trunc; + ND_PRINT((ndo, "", metric %"" PRIu64, + EXTRACT_64BITS(tptr))); + break; + + default: + if (ndo->ndo_vflag <= 1) { + print_unknown_data(ndo, tptr,""\n\t "", length); + } + } + + tptr += length; + tlen -= length; + } + break; + } + case BGPTYPE_ATTR_SET: + ND_TCHECK2(tptr[0], 4); + if (len < 4) + goto trunc; + ND_PRINT((ndo, ""\n\t Origin AS: %s"", + as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)))); + tptr+=4; + len -=4; + + while (len) { + u_int aflags, alenlen, alen; + + ND_TCHECK2(tptr[0], 2); + if (len < 2) + goto trunc; + aflags = *tptr; + atype = *(tptr + 1); + tptr += 2; + len -= 2; + alenlen = bgp_attr_lenlen(aflags, tptr); + ND_TCHECK2(tptr[0], alenlen); + if (len < alenlen) + goto trunc; + alen = bgp_attr_len(aflags, tptr); + tptr += alenlen; + len -= alenlen; + + ND_PRINT((ndo, ""\n\t %s (%u), length: %u"", + tok2str(bgp_attr_values, + ""Unknown Attribute"", atype), + atype, + alen)); + + if (aflags) { + ND_PRINT((ndo, "", Flags [%s%s%s%s"", + aflags & 0x80 ? ""O"" : """", + aflags & 0x40 ? ""T"" : """", + aflags & 0x20 ? ""P"" : """", + aflags & 0x10 ? ""E"" : """")); + if (aflags & 0xf) + ND_PRINT((ndo, ""+%x"", aflags & 0xf)); + ND_PRINT((ndo, ""]: "")); + } + /* FIXME check for recursion */ + if (!bgp_attr_print(ndo, atype, tptr, alen)) + return 0; + tptr += alen; + len -= alen; + } + break; + + case BGPTYPE_LARGE_COMMUNITY: + if (len == 0 || len % 12) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + ND_PRINT((ndo, ""\n\t "")); + while (len > 0) { + ND_TCHECK2(*tptr, 12); + ND_PRINT((ndo, ""%u:%u:%u%s"", + EXTRACT_32BITS(tptr), + EXTRACT_32BITS(tptr + 4), + EXTRACT_32BITS(tptr + 8), + (len > 12) ? "", "" : """")); + tptr += 12; + len -= 12; + } + break; + default: + ND_TCHECK2(*pptr,len); + ND_PRINT((ndo, ""\n\t no Attribute %u decoder"", atype)); /* we have no decoder for the attribute */ + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, pptr, ""\n\t "", len); + break; + } + if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/ + ND_TCHECK2(*pptr,len); + print_unknown_data(ndo, pptr, ""\n\t "", len); + } + return 1; + +trunc: + return 0; +} +",0,"bgp_attr_print(netdissect_options *ndo, + u_int atype, const u_char *pptr, u_int len) +{ + int i; + uint16_t af; + uint8_t safi, snpa, nhlen; + union { /* copy buffer for bandwidth values */ + float f; + uint32_t i; + } bw; + int advance; + u_int tlen; + const u_char *tptr; + char buf[MAXHOSTNAMELEN + 100]; + int as_size; + + tptr = pptr; + tlen=len; + + switch (atype) { + case BGPTYPE_ORIGIN: + if (len != 1) + ND_PRINT((ndo, ""invalid len"")); + else { + ND_TCHECK(*tptr); + ND_PRINT((ndo, ""%s"", tok2str(bgp_origin_values, + ""Unknown Origin Typecode"", + tptr[0]))); + } + break; + + /* + * Process AS4 byte path and AS2 byte path attributes here. + */ + case BGPTYPE_AS4_PATH: + case BGPTYPE_AS_PATH: + if (len % 2) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + if (!len) { + ND_PRINT((ndo, ""empty"")); + break; + } + + /* + * BGP updates exchanged between New speakers that support 4 + * byte AS, ASs are always encoded in 4 bytes. There is no + * definitive way to find this, just by the packet's + * contents. So, check for packet's TLV's sanity assuming + * 2 bytes first, and it does not pass, assume that ASs are + * encoded in 4 bytes format and move on. + */ + as_size = bgp_attr_get_as_size(ndo, atype, pptr, len); + + while (tptr < pptr + len) { + ND_TCHECK(tptr[0]); + ND_PRINT((ndo, ""%s"", tok2str(bgp_as_path_segment_open_values, + ""?"", tptr[0]))); + ND_TCHECK(tptr[1]); + for (i = 0; i < tptr[1] * as_size; i += as_size) { + ND_TCHECK2(tptr[2 + i], as_size); + ND_PRINT((ndo, ""%s "", + as_printf(ndo, astostr, sizeof(astostr), + as_size == 2 ? + EXTRACT_16BITS(&tptr[2 + i]) : + EXTRACT_32BITS(&tptr[2 + i])))); + } + ND_TCHECK(tptr[0]); + ND_PRINT((ndo, ""%s"", tok2str(bgp_as_path_segment_close_values, + ""?"", tptr[0]))); + ND_TCHECK(tptr[1]); + tptr += 2 + tptr[1] * as_size; + } + break; + case BGPTYPE_NEXT_HOP: + if (len != 4) + ND_PRINT((ndo, ""invalid len"")); + else { + ND_TCHECK2(tptr[0], 4); + ND_PRINT((ndo, ""%s"", ipaddr_string(ndo, tptr))); + } + break; + case BGPTYPE_MULTI_EXIT_DISC: + case BGPTYPE_LOCAL_PREF: + if (len != 4) + ND_PRINT((ndo, ""invalid len"")); + else { + ND_TCHECK2(tptr[0], 4); + ND_PRINT((ndo, ""%u"", EXTRACT_32BITS(tptr))); + } + break; + case BGPTYPE_ATOMIC_AGGREGATE: + if (len != 0) + ND_PRINT((ndo, ""invalid len"")); + break; + case BGPTYPE_AGGREGATOR: + + /* + * Depending on the AS encoded is of 2 bytes or of 4 bytes, + * the length of this PA can be either 6 bytes or 8 bytes. + */ + if (len != 6 && len != 8) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + ND_TCHECK2(tptr[0], len); + if (len == 6) { + ND_PRINT((ndo, "" AS #%s, origin %s"", + as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)), + ipaddr_string(ndo, tptr + 2))); + } else { + ND_PRINT((ndo, "" AS #%s, origin %s"", + as_printf(ndo, astostr, sizeof(astostr), + EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); + } + break; + case BGPTYPE_AGGREGATOR4: + if (len != 8) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + ND_TCHECK2(tptr[0], 8); + ND_PRINT((ndo, "" AS #%s, origin %s"", + as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), + ipaddr_string(ndo, tptr + 4))); + break; + case BGPTYPE_COMMUNITIES: + if (len % 4) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + while (tlen>0) { + uint32_t comm; + ND_TCHECK2(tptr[0], 4); + comm = EXTRACT_32BITS(tptr); + switch (comm) { + case BGP_COMMUNITY_NO_EXPORT: + ND_PRINT((ndo, "" NO_EXPORT"")); + break; + case BGP_COMMUNITY_NO_ADVERT: + ND_PRINT((ndo, "" NO_ADVERTISE"")); + break; + case BGP_COMMUNITY_NO_EXPORT_SUBCONFED: + ND_PRINT((ndo, "" NO_EXPORT_SUBCONFED"")); + break; + default: + ND_PRINT((ndo, ""%u:%u%s"", + (comm >> 16) & 0xffff, + comm & 0xffff, + (tlen>4) ? "", "" : """")); + break; + } + tlen -=4; + tptr +=4; + } + break; + case BGPTYPE_ORIGINATOR_ID: + if (len != 4) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + ND_TCHECK2(tptr[0], 4); + ND_PRINT((ndo, ""%s"",ipaddr_string(ndo, tptr))); + break; + case BGPTYPE_CLUSTER_LIST: + if (len % 4) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + while (tlen>0) { + ND_TCHECK2(tptr[0], 4); + ND_PRINT((ndo, ""%s%s"", + ipaddr_string(ndo, tptr), + (tlen>4) ? "", "" : """")); + tlen -=4; + tptr +=4; + } + break; + case BGPTYPE_MP_REACH_NLRI: + ND_TCHECK2(tptr[0], 3); + af = EXTRACT_16BITS(tptr); + safi = tptr[2]; + + ND_PRINT((ndo, ""\n\t AFI: %s (%u), %sSAFI: %s (%u)"", + tok2str(af_values, ""Unknown AFI"", af), + af, + (safi>128) ? ""vendor specific "" : """", /* 128 is meanwhile wellknown */ + tok2str(bgp_safi_values, ""Unknown SAFI"", safi), + safi)); + + switch(af<<8 | safi) { + case (AFNUM_INET<<8 | SAFNUM_UNICAST): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): + case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): + case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): + case (AFNUM_INET<<8 | SAFNUM_MDT): + case (AFNUM_INET6<<8 | SAFNUM_UNICAST): + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): + case (AFNUM_VPLS<<8 | SAFNUM_VPLS): + break; + default: + ND_TCHECK2(tptr[0], tlen); + ND_PRINT((ndo, ""\n\t no AFI %u / SAFI %u decoder"", af, safi)); + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, tptr, ""\n\t "", tlen); + goto done; + break; + } + + tptr +=3; + + ND_TCHECK(tptr[0]); + nhlen = tptr[0]; + tlen = nhlen; + tptr++; + + if (tlen) { + int nnh = 0; + ND_PRINT((ndo, ""\n\t nexthop: "")); + while (tlen > 0) { + if ( nnh++ > 0 ) { + ND_PRINT((ndo, "", "" )); + } + switch(af<<8 | safi) { + case (AFNUM_INET<<8 | SAFNUM_UNICAST): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): + case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): + case (AFNUM_INET<<8 | SAFNUM_MDT): + if (tlen < (int)sizeof(struct in_addr)) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], sizeof(struct in_addr)); + ND_PRINT((ndo, ""%s"",ipaddr_string(ndo, tptr))); + tlen -= sizeof(struct in_addr); + tptr += sizeof(struct in_addr); + } + break; + case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): + if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN); + ND_PRINT((ndo, ""RD: %s, %s"", + bgp_vpn_rd_print(ndo, tptr), + ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN))); + tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN); + tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN); + } + break; + case (AFNUM_INET6<<8 | SAFNUM_UNICAST): + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): + if (tlen < (int)sizeof(struct in6_addr)) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], sizeof(struct in6_addr)); + ND_PRINT((ndo, ""%s"", ip6addr_string(ndo, tptr))); + tlen -= sizeof(struct in6_addr); + tptr += sizeof(struct in6_addr); + } + break; + case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): + if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN); + ND_PRINT((ndo, ""RD: %s, %s"", + bgp_vpn_rd_print(ndo, tptr), + ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN))); + tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); + tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); + } + break; + case (AFNUM_VPLS<<8 | SAFNUM_VPLS): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): + if (tlen < (int)sizeof(struct in_addr)) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], sizeof(struct in_addr)); + ND_PRINT((ndo, ""%s"", ipaddr_string(ndo, tptr))); + tlen -= (sizeof(struct in_addr)); + tptr += (sizeof(struct in_addr)); + } + break; + case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): + ND_TCHECK2(tptr[0], tlen); + ND_PRINT((ndo, ""%s"", isonsap_string(ndo, tptr, tlen))); + tptr += tlen; + tlen = 0; + break; + + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): + if (tlen < BGP_VPN_RD_LEN+1) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], tlen); + ND_PRINT((ndo, ""RD: %s, %s"", + bgp_vpn_rd_print(ndo, tptr), + isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN))); + /* rfc986 mapped IPv4 address ? */ + if (EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601) + ND_PRINT((ndo, "" = %s"", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4))); + /* rfc1888 mapped IPv6 address ? */ + else if (EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000) + ND_PRINT((ndo, "" = %s"", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3))); + tptr += tlen; + tlen = 0; + } + break; + default: + ND_TCHECK2(tptr[0], tlen); + ND_PRINT((ndo, ""no AFI %u/SAFI %u decoder"", af, safi)); + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, tptr, ""\n\t "", tlen); + tptr += tlen; + tlen = 0; + goto done; + break; + } + } + } + ND_PRINT((ndo, "", nh-length: %u"", nhlen)); + tptr += tlen; + + ND_TCHECK(tptr[0]); + snpa = tptr[0]; + tptr++; + + if (snpa) { + ND_PRINT((ndo, ""\n\t %u SNPA"", snpa)); + for (/*nothing*/; snpa > 0; snpa--) { + ND_TCHECK(tptr[0]); + ND_PRINT((ndo, ""\n\t %d bytes"", tptr[0])); + tptr += tptr[0] + 1; + } + } else { + ND_PRINT((ndo, "", no SNPA"")); + } + + while (tptr < pptr + len) { + switch (af<<8 | safi) { + case (AFNUM_INET<<8 | SAFNUM_UNICAST): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): + advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): + advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): + advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): + advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + + case (AFNUM_INET<<8 | SAFNUM_MDT): + advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_UNICAST): + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): + advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): + advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_VPLS<<8 | SAFNUM_VPLS): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): + advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + default: + ND_TCHECK2(*tptr,tlen); + ND_PRINT((ndo, ""\n\t no AFI %u / SAFI %u decoder"", af, safi)); + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, tptr, ""\n\t "", tlen); + advance = 0; + tptr = pptr + len; + break; + } + if (advance < 0) + break; + tptr += advance; + } + done: + break; + + case BGPTYPE_MP_UNREACH_NLRI: + ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE); + af = EXTRACT_16BITS(tptr); + safi = tptr[2]; + + ND_PRINT((ndo, ""\n\t AFI: %s (%u), %sSAFI: %s (%u)"", + tok2str(af_values, ""Unknown AFI"", af), + af, + (safi>128) ? ""vendor specific "" : """", /* 128 is meanwhile wellknown */ + tok2str(bgp_safi_values, ""Unknown SAFI"", safi), + safi)); + + if (len == BGP_MP_NLRI_MINSIZE) + ND_PRINT((ndo, ""\n\t End-of-Rib Marker (empty NLRI)"")); + + tptr += 3; + + while (tptr < pptr + len) { + switch (af<<8 | safi) { + case (AFNUM_INET<<8 | SAFNUM_UNICAST): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): + advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): + advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_UNICAST): + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): + advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): + advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_VPLS<<8 | SAFNUM_VPLS): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): + advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_MDT): + advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): + advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + default: + ND_TCHECK2(*(tptr-3),tlen); + ND_PRINT((ndo, ""no AFI %u / SAFI %u decoder"", af, safi)); + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, tptr-3, ""\n\t "", tlen); + advance = 0; + tptr = pptr + len; + break; + } + if (advance < 0) + break; + tptr += advance; + } + break; + case BGPTYPE_EXTD_COMMUNITIES: + if (len % 8) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + while (tlen>0) { + uint16_t extd_comm; + + ND_TCHECK2(tptr[0], 2); + extd_comm=EXTRACT_16BITS(tptr); + + ND_PRINT((ndo, ""\n\t %s (0x%04x), Flags [%s]"", + tok2str(bgp_extd_comm_subtype_values, + ""unknown extd community typecode"", + extd_comm), + extd_comm, + bittok2str(bgp_extd_comm_flag_values, ""none"", extd_comm))); + + ND_TCHECK2(*(tptr+2), 6); + switch(extd_comm) { + case BGP_EXT_COM_RT_0: + case BGP_EXT_COM_RO_0: + case BGP_EXT_COM_L2VPN_RT_0: + ND_PRINT((ndo, "": %u:%u (= %s)"", + EXTRACT_16BITS(tptr+2), + EXTRACT_32BITS(tptr+4), + ipaddr_string(ndo, tptr+4))); + break; + case BGP_EXT_COM_RT_1: + case BGP_EXT_COM_RO_1: + case BGP_EXT_COM_L2VPN_RT_1: + case BGP_EXT_COM_VRF_RT_IMP: + ND_PRINT((ndo, "": %s:%u"", + ipaddr_string(ndo, tptr+2), + EXTRACT_16BITS(tptr+6))); + break; + case BGP_EXT_COM_RT_2: + case BGP_EXT_COM_RO_2: + ND_PRINT((ndo, "": %s:%u"", + as_printf(ndo, astostr, sizeof(astostr), + EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6))); + break; + case BGP_EXT_COM_LINKBAND: + bw.i = EXTRACT_32BITS(tptr+2); + ND_PRINT((ndo, "": bandwidth: %.3f Mbps"", + bw.f*8/1000000)); + break; + case BGP_EXT_COM_VPN_ORIGIN: + case BGP_EXT_COM_VPN_ORIGIN2: + case BGP_EXT_COM_VPN_ORIGIN3: + case BGP_EXT_COM_VPN_ORIGIN4: + case BGP_EXT_COM_OSPF_RID: + case BGP_EXT_COM_OSPF_RID2: + ND_PRINT((ndo, ""%s"", ipaddr_string(ndo, tptr+2))); + break; + case BGP_EXT_COM_OSPF_RTYPE: + case BGP_EXT_COM_OSPF_RTYPE2: + ND_PRINT((ndo, "": area:%s, router-type:%s, metric-type:%s%s"", + ipaddr_string(ndo, tptr+2), + tok2str(bgp_extd_comm_ospf_rtype_values, + ""unknown (0x%02x)"", + *(tptr+6)), + (*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? ""E2"" : """", + ((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? ""E1"" : """")); + break; + case BGP_EXT_COM_L2INFO: + ND_PRINT((ndo, "": %s Control Flags [0x%02x]:MTU %u"", + tok2str(l2vpn_encaps_values, + ""unknown encaps"", + *(tptr+2)), + *(tptr+3), + EXTRACT_16BITS(tptr+4))); + break; + case BGP_EXT_COM_SOURCE_AS: + ND_PRINT((ndo, "": AS %u"", EXTRACT_16BITS(tptr+2))); + break; + default: + ND_TCHECK2(*tptr,8); + print_unknown_data(ndo, tptr, ""\n\t "", 8); + break; + } + tlen -=8; + tptr +=8; + } + break; + + case BGPTYPE_PMSI_TUNNEL: + { + uint8_t tunnel_type, flags; + + ND_TCHECK2(tptr[0], 5); + tunnel_type = *(tptr+1); + flags = *tptr; + tlen = len; + + ND_PRINT((ndo, ""\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u"", + tok2str(bgp_pmsi_tunnel_values, ""Unknown"", tunnel_type), + tunnel_type, + bittok2str(bgp_pmsi_flag_values, ""none"", flags), + EXTRACT_24BITS(tptr+2)>>4)); + + tptr +=5; + tlen -= 5; + + switch (tunnel_type) { + case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */ + case BGP_PMSI_TUNNEL_PIM_BIDIR: + ND_TCHECK2(tptr[0], 8); + ND_PRINT((ndo, ""\n\t Sender %s, P-Group %s"", + ipaddr_string(ndo, tptr), + ipaddr_string(ndo, tptr+4))); + break; + + case BGP_PMSI_TUNNEL_PIM_SSM: + ND_TCHECK2(tptr[0], 8); + ND_PRINT((ndo, ""\n\t Root-Node %s, P-Group %s"", + ipaddr_string(ndo, tptr), + ipaddr_string(ndo, tptr+4))); + break; + case BGP_PMSI_TUNNEL_INGRESS: + ND_TCHECK2(tptr[0], 4); + ND_PRINT((ndo, ""\n\t Tunnel-Endpoint %s"", + ipaddr_string(ndo, tptr))); + break; + case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */ + case BGP_PMSI_TUNNEL_LDP_MP2MP: + ND_TCHECK2(tptr[0], 8); + ND_PRINT((ndo, ""\n\t Root-Node %s, LSP-ID 0x%08x"", + ipaddr_string(ndo, tptr), + EXTRACT_32BITS(tptr+4))); + break; + case BGP_PMSI_TUNNEL_RSVP_P2MP: + ND_TCHECK2(tptr[0], 8); + ND_PRINT((ndo, ""\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x"", + ipaddr_string(ndo, tptr), + EXTRACT_32BITS(tptr+4))); + break; + default: + if (ndo->ndo_vflag <= 1) { + print_unknown_data(ndo, tptr, ""\n\t "", tlen); + } + } + break; + } + case BGPTYPE_AIGP: + { + uint8_t type; + uint16_t length; + + tlen = len; + + while (tlen >= 3) { + + ND_TCHECK2(tptr[0], 3); + + type = *tptr; + length = EXTRACT_16BITS(tptr+1); + tptr += 3; + tlen -= 3; + + ND_PRINT((ndo, ""\n\t %s TLV (%u), length %u"", + tok2str(bgp_aigp_values, ""Unknown"", type), + type, length)); + + if (length < 3) + goto trunc; + length -= 3; + + /* + * Check if we can read the TLV data. + */ + ND_TCHECK2(tptr[3], length); + + switch (type) { + + case BGP_AIGP_TLV: + if (length < 8) + goto trunc; + ND_PRINT((ndo, "", metric %"" PRIu64, + EXTRACT_64BITS(tptr))); + break; + + default: + if (ndo->ndo_vflag <= 1) { + print_unknown_data(ndo, tptr,""\n\t "", length); + } + } + + tptr += length; + tlen -= length; + } + break; + } + case BGPTYPE_ATTR_SET: + ND_TCHECK2(tptr[0], 4); + if (len < 4) + goto trunc; + ND_PRINT((ndo, ""\n\t Origin AS: %s"", + as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)))); + tptr+=4; + len -=4; + + while (len) { + u_int aflags, alenlen, alen; + + ND_TCHECK2(tptr[0], 2); + if (len < 2) + goto trunc; + aflags = *tptr; + atype = *(tptr + 1); + tptr += 2; + len -= 2; + alenlen = bgp_attr_lenlen(aflags, tptr); + ND_TCHECK2(tptr[0], alenlen); + if (len < alenlen) + goto trunc; + alen = bgp_attr_len(aflags, tptr); + tptr += alenlen; + len -= alenlen; + + ND_PRINT((ndo, ""\n\t %s (%u), length: %u"", + tok2str(bgp_attr_values, + ""Unknown Attribute"", atype), + atype, + alen)); + + if (aflags) { + ND_PRINT((ndo, "", Flags [%s%s%s%s"", + aflags & 0x80 ? ""O"" : """", + aflags & 0x40 ? ""T"" : """", + aflags & 0x20 ? ""P"" : """", + aflags & 0x10 ? ""E"" : """")); + if (aflags & 0xf) + ND_PRINT((ndo, ""+%x"", aflags & 0xf)); + ND_PRINT((ndo, ""]: "")); + } + /* FIXME check for recursion */ + if (!bgp_attr_print(ndo, atype, tptr, alen)) + return 0; + tptr += alen; + len -= alen; + } + break; + + case BGPTYPE_LARGE_COMMUNITY: + if (len == 0 || len % 12) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + ND_PRINT((ndo, ""\n\t "")); + while (len > 0) { + ND_TCHECK2(*tptr, 12); + ND_PRINT((ndo, ""%u:%u:%u%s"", + EXTRACT_32BITS(tptr), + EXTRACT_32BITS(tptr + 4), + EXTRACT_32BITS(tptr + 8), + (len > 12) ? "", "" : """")); + tptr += 12; + len -= 12; + } + break; + default: + ND_TCHECK2(*pptr,len); + ND_PRINT((ndo, ""\n\t no Attribute %u decoder"", atype)); /* we have no decoder for the attribute */ + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, pptr, ""\n\t "", len); + break; + } + if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/ + ND_TCHECK2(*pptr,len); + print_unknown_data(ndo, pptr, ""\n\t "", len); + } + return 1; + +trunc: + return 0; +} +","@@ -761,32 +761,48 @@ decode_rt_routing_info(netdissect_options *ndo, + { + uint8_t route_target[8]; + u_int plen; ++ char asbuf[sizeof(astostr)]; /* bgp_vpn_rd_print() overwrites astostr */ + ++ /* NLRI ""prefix length"" from RFC 2858 Section 4. */ + ND_TCHECK(pptr[0]); + plen = pptr[0]; /* get prefix length */ + ++ /* NLRI ""prefix"" (ibid), valid lengths are { 0, 32, 33, ..., 96 } bits. ++ * RFC 4684 Section 4 defines the layout of ""origin AS"" and ""route ++ * target"" fields inside the ""prefix"" depending on its length. ++ */ + if (0 == plen) { ++ /* Without ""origin AS"", without ""route target"". */ + snprintf(buf, buflen, ""default route target""); + return 1; + } + + if (32 > plen) + return -1; + ++ /* With at least ""origin AS"", possibly with ""route target"". */ ++ ND_TCHECK_32BITS(pptr + 1); ++ as_printf(ndo, asbuf, sizeof(asbuf), EXTRACT_32BITS(pptr + 1)); ++ + plen-=32; /* adjust prefix length */ + + if (64 < plen) + return -1; + ++ /* From now on (plen + 7) / 8 evaluates to { 0, 1, 2, ..., 8 } ++ * and gives the number of octets in the variable-length ""route ++ * target"" field inside this NLRI ""prefix"". Look for it. ++ */ + memset(&route_target, 0, sizeof(route_target)); +- ND_TCHECK2(pptr[1], (plen + 7) / 8); +- memcpy(&route_target, &pptr[1], (plen + 7) / 8); ++ ND_TCHECK2(pptr[5], (plen + 7) / 8); ++ memcpy(&route_target, &pptr[5], (plen + 7) / 8); ++ /* Which specification says to do this? */ + if (plen % 8) { + ((u_char *)&route_target)[(plen + 7) / 8 - 1] &= + ((0xff00 >> (plen % 8)) & 0xff); + } + snprintf(buf, buflen, ""origin AS: %s, route target %s"", +- as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+1)), ++ asbuf, + bgp_vpn_rd_print(ndo, (u_char *)&route_target)); + + return 5 + (plen + 7) / 8;",9830,10161,11000 +18294," bgp_attr_print(netdissect_options *ndo, + u_int atype, const u_char *pptr, u_int len) + { + int i; + uint16_t af; + uint8_t safi, snpa, nhlen; + union { /* copy buffer for bandwidth values */ + float f; + uint32_t i; + } bw; + int advance; + u_int tlen; + const u_char *tptr; + char buf[MAXHOSTNAMELEN + 100]; + int as_size; + + tptr = pptr; + tlen=len; + + switch (atype) { + case BGPTYPE_ORIGIN: + if (len != 1) + ND_PRINT((ndo, ""invalid len"")); + else { + ND_TCHECK(*tptr); + ND_PRINT((ndo, ""%s"", tok2str(bgp_origin_values, + ""Unknown Origin Typecode"", + tptr[0]))); + } + break; + + /* + * Process AS4 byte path and AS2 byte path attributes here. + */ + case BGPTYPE_AS4_PATH: + case BGPTYPE_AS_PATH: + if (len % 2) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + if (!len) { + ND_PRINT((ndo, ""empty"")); + break; + } + + /* + * BGP updates exchanged between New speakers that support 4 + * byte AS, ASs are always encoded in 4 bytes. There is no + * definitive way to find this, just by the packet's + * contents. So, check for packet's TLV's sanity assuming + * 2 bytes first, and it does not pass, assume that ASs are + * encoded in 4 bytes format and move on. + */ + as_size = bgp_attr_get_as_size(ndo, atype, pptr, len); + + while (tptr < pptr + len) { + ND_TCHECK(tptr[0]); + ND_PRINT((ndo, ""%s"", tok2str(bgp_as_path_segment_open_values, + ""?"", tptr[0]))); + ND_TCHECK(tptr[1]); + for (i = 0; i < tptr[1] * as_size; i += as_size) { + ND_TCHECK2(tptr[2 + i], as_size); + ND_PRINT((ndo, ""%s "", + as_printf(ndo, astostr, sizeof(astostr), + as_size == 2 ? + EXTRACT_16BITS(&tptr[2 + i]) : + EXTRACT_32BITS(&tptr[2 + i])))); + } + ND_TCHECK(tptr[0]); + ND_PRINT((ndo, ""%s"", tok2str(bgp_as_path_segment_close_values, + ""?"", tptr[0]))); + ND_TCHECK(tptr[1]); + tptr += 2 + tptr[1] * as_size; + } + break; + case BGPTYPE_NEXT_HOP: + if (len != 4) + ND_PRINT((ndo, ""invalid len"")); + else { + ND_TCHECK2(tptr[0], 4); + ND_PRINT((ndo, ""%s"", ipaddr_string(ndo, tptr))); + } + break; + case BGPTYPE_MULTI_EXIT_DISC: + case BGPTYPE_LOCAL_PREF: + if (len != 4) + ND_PRINT((ndo, ""invalid len"")); + else { + ND_TCHECK2(tptr[0], 4); + ND_PRINT((ndo, ""%u"", EXTRACT_32BITS(tptr))); + } + break; + case BGPTYPE_ATOMIC_AGGREGATE: + if (len != 0) + ND_PRINT((ndo, ""invalid len"")); + break; + case BGPTYPE_AGGREGATOR: + + /* + * Depending on the AS encoded is of 2 bytes or of 4 bytes, + * the length of this PA can be either 6 bytes or 8 bytes. + */ + if (len != 6 && len != 8) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + ND_TCHECK2(tptr[0], len); + if (len == 6) { + ND_PRINT((ndo, "" AS #%s, origin %s"", + as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)), + ipaddr_string(ndo, tptr + 2))); + } else { + ND_PRINT((ndo, "" AS #%s, origin %s"", + as_printf(ndo, astostr, sizeof(astostr), + EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); + } + break; + case BGPTYPE_AGGREGATOR4: + if (len != 8) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + ND_TCHECK2(tptr[0], 8); + ND_PRINT((ndo, "" AS #%s, origin %s"", + as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), + ipaddr_string(ndo, tptr + 4))); + break; + case BGPTYPE_COMMUNITIES: + if (len % 4) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + while (tlen>0) { + uint32_t comm; + ND_TCHECK2(tptr[0], 4); + comm = EXTRACT_32BITS(tptr); + switch (comm) { + case BGP_COMMUNITY_NO_EXPORT: + ND_PRINT((ndo, "" NO_EXPORT"")); + break; + case BGP_COMMUNITY_NO_ADVERT: + ND_PRINT((ndo, "" NO_ADVERTISE"")); + break; + case BGP_COMMUNITY_NO_EXPORT_SUBCONFED: + ND_PRINT((ndo, "" NO_EXPORT_SUBCONFED"")); + break; + default: + ND_PRINT((ndo, ""%u:%u%s"", + (comm >> 16) & 0xffff, + comm & 0xffff, + (tlen>4) ? "", "" : """")); + break; + } + tlen -=4; + tptr +=4; + } + break; + case BGPTYPE_ORIGINATOR_ID: + if (len != 4) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + ND_TCHECK2(tptr[0], 4); + ND_PRINT((ndo, ""%s"",ipaddr_string(ndo, tptr))); + break; + case BGPTYPE_CLUSTER_LIST: + if (len % 4) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + while (tlen>0) { + ND_TCHECK2(tptr[0], 4); + ND_PRINT((ndo, ""%s%s"", + ipaddr_string(ndo, tptr), + (tlen>4) ? "", "" : """")); + tlen -=4; + tptr +=4; + } + break; + case BGPTYPE_MP_REACH_NLRI: + ND_TCHECK2(tptr[0], 3); + af = EXTRACT_16BITS(tptr); + safi = tptr[2]; + + ND_PRINT((ndo, ""\n\t AFI: %s (%u), %sSAFI: %s (%u)"", + tok2str(af_values, ""Unknown AFI"", af), + af, + (safi>128) ? ""vendor specific "" : """", /* 128 is meanwhile wellknown */ + tok2str(bgp_safi_values, ""Unknown SAFI"", safi), + safi)); + + switch(af<<8 | safi) { + case (AFNUM_INET<<8 | SAFNUM_UNICAST): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): + case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): + case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): + case (AFNUM_INET<<8 | SAFNUM_MDT): + case (AFNUM_INET6<<8 | SAFNUM_UNICAST): + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): + case (AFNUM_VPLS<<8 | SAFNUM_VPLS): + break; + default: + ND_TCHECK2(tptr[0], tlen); + ND_PRINT((ndo, ""\n\t no AFI %u / SAFI %u decoder"", af, safi)); + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, tptr, ""\n\t "", tlen); + goto done; + break; + } + + tptr +=3; + + ND_TCHECK(tptr[0]); + nhlen = tptr[0]; + tlen = nhlen; + tptr++; + + if (tlen) { + int nnh = 0; + ND_PRINT((ndo, ""\n\t nexthop: "")); + while (tlen > 0) { + if ( nnh++ > 0 ) { + ND_PRINT((ndo, "", "" )); + } + switch(af<<8 | safi) { + case (AFNUM_INET<<8 | SAFNUM_UNICAST): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): + case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): + case (AFNUM_INET<<8 | SAFNUM_MDT): + if (tlen < (int)sizeof(struct in_addr)) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], sizeof(struct in_addr)); + ND_PRINT((ndo, ""%s"",ipaddr_string(ndo, tptr))); + tlen -= sizeof(struct in_addr); + tptr += sizeof(struct in_addr); + } + break; + case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): + if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN); + ND_PRINT((ndo, ""RD: %s, %s"", + bgp_vpn_rd_print(ndo, tptr), + ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN))); + tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN); + tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN); + } + break; + case (AFNUM_INET6<<8 | SAFNUM_UNICAST): + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): + if (tlen < (int)sizeof(struct in6_addr)) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], sizeof(struct in6_addr)); + ND_PRINT((ndo, ""%s"", ip6addr_string(ndo, tptr))); + tlen -= sizeof(struct in6_addr); + tptr += sizeof(struct in6_addr); + } + break; + case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): + if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN); + ND_PRINT((ndo, ""RD: %s, %s"", + bgp_vpn_rd_print(ndo, tptr), + ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN))); + tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); + tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); + } + break; + case (AFNUM_VPLS<<8 | SAFNUM_VPLS): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): + if (tlen < (int)sizeof(struct in_addr)) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], sizeof(struct in_addr)); + ND_PRINT((ndo, ""%s"", ipaddr_string(ndo, tptr))); + tlen -= (sizeof(struct in_addr)); + tptr += (sizeof(struct in_addr)); + } + break; + case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): + ND_TCHECK2(tptr[0], tlen); + ND_PRINT((ndo, ""%s"", isonsap_string(ndo, tptr, tlen))); + tptr += tlen; + tlen = 0; + break; + + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): + if (tlen < BGP_VPN_RD_LEN+1) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], tlen); + ND_PRINT((ndo, ""RD: %s, %s"", + bgp_vpn_rd_print(ndo, tptr), + isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN))); + /* rfc986 mapped IPv4 address ? */ + if (tlen == BGP_VPN_RD_LEN + 4 + sizeof(struct in_addr) + && EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601) + ND_PRINT((ndo, "" = %s"", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4))); + /* rfc1888 mapped IPv6 address ? */ + else if (tlen == BGP_VPN_RD_LEN + 3 + sizeof(struct in6_addr) + && EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000) + ND_PRINT((ndo, "" = %s"", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3))); + tptr += tlen; + tlen = 0; + } + break; + default: + ND_TCHECK2(tptr[0], tlen); + ND_PRINT((ndo, ""no AFI %u/SAFI %u decoder"", af, safi)); + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, tptr, ""\n\t "", tlen); + tptr += tlen; + tlen = 0; + goto done; + break; + } + } + } + ND_PRINT((ndo, "", nh-length: %u"", nhlen)); + tptr += tlen; + + ND_TCHECK(tptr[0]); + snpa = tptr[0]; + tptr++; + + if (snpa) { + ND_PRINT((ndo, ""\n\t %u SNPA"", snpa)); + for (/*nothing*/; snpa > 0; snpa--) { + ND_TCHECK(tptr[0]); + ND_PRINT((ndo, ""\n\t %d bytes"", tptr[0])); + tptr += tptr[0] + 1; + } + } else { + ND_PRINT((ndo, "", no SNPA"")); + } + + while (tptr < pptr + len) { + switch (af<<8 | safi) { + case (AFNUM_INET<<8 | SAFNUM_UNICAST): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): + advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): + advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): + advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): + advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + + case (AFNUM_INET<<8 | SAFNUM_MDT): + advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_UNICAST): + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): + advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): + advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_VPLS<<8 | SAFNUM_VPLS): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): + advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + default: + ND_TCHECK2(*tptr,tlen); + ND_PRINT((ndo, ""\n\t no AFI %u / SAFI %u decoder"", af, safi)); + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, tptr, ""\n\t "", tlen); + advance = 0; + tptr = pptr + len; + break; + } + if (advance < 0) + break; + tptr += advance; + } + done: + break; + + case BGPTYPE_MP_UNREACH_NLRI: + ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE); + af = EXTRACT_16BITS(tptr); + safi = tptr[2]; + + ND_PRINT((ndo, ""\n\t AFI: %s (%u), %sSAFI: %s (%u)"", + tok2str(af_values, ""Unknown AFI"", af), + af, + (safi>128) ? ""vendor specific "" : """", /* 128 is meanwhile wellknown */ + tok2str(bgp_safi_values, ""Unknown SAFI"", safi), + safi)); + + if (len == BGP_MP_NLRI_MINSIZE) + ND_PRINT((ndo, ""\n\t End-of-Rib Marker (empty NLRI)"")); + + tptr += 3; + + while (tptr < pptr + len) { + switch (af<<8 | safi) { + case (AFNUM_INET<<8 | SAFNUM_UNICAST): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): + advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): + advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_UNICAST): + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): + advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): + advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_VPLS<<8 | SAFNUM_VPLS): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): + advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_MDT): + advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): + advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + default: + ND_TCHECK2(*(tptr-3),tlen); + ND_PRINT((ndo, ""no AFI %u / SAFI %u decoder"", af, safi)); + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, tptr-3, ""\n\t "", tlen); + advance = 0; + tptr = pptr + len; + break; + } + if (advance < 0) + break; + tptr += advance; + } + break; + case BGPTYPE_EXTD_COMMUNITIES: + if (len % 8) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + while (tlen>0) { + uint16_t extd_comm; + + ND_TCHECK2(tptr[0], 2); + extd_comm=EXTRACT_16BITS(tptr); + + ND_PRINT((ndo, ""\n\t %s (0x%04x), Flags [%s]"", + tok2str(bgp_extd_comm_subtype_values, + ""unknown extd community typecode"", + extd_comm), + extd_comm, + bittok2str(bgp_extd_comm_flag_values, ""none"", extd_comm))); + + ND_TCHECK2(*(tptr+2), 6); + switch(extd_comm) { + case BGP_EXT_COM_RT_0: + case BGP_EXT_COM_RO_0: + case BGP_EXT_COM_L2VPN_RT_0: + ND_PRINT((ndo, "": %u:%u (= %s)"", + EXTRACT_16BITS(tptr+2), + EXTRACT_32BITS(tptr+4), + ipaddr_string(ndo, tptr+4))); + break; + case BGP_EXT_COM_RT_1: + case BGP_EXT_COM_RO_1: + case BGP_EXT_COM_L2VPN_RT_1: + case BGP_EXT_COM_VRF_RT_IMP: + ND_PRINT((ndo, "": %s:%u"", + ipaddr_string(ndo, tptr+2), + EXTRACT_16BITS(tptr+6))); + break; + case BGP_EXT_COM_RT_2: + case BGP_EXT_COM_RO_2: + ND_PRINT((ndo, "": %s:%u"", + as_printf(ndo, astostr, sizeof(astostr), + EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6))); + break; + case BGP_EXT_COM_LINKBAND: + bw.i = EXTRACT_32BITS(tptr+2); + ND_PRINT((ndo, "": bandwidth: %.3f Mbps"", + bw.f*8/1000000)); + break; + case BGP_EXT_COM_VPN_ORIGIN: + case BGP_EXT_COM_VPN_ORIGIN2: + case BGP_EXT_COM_VPN_ORIGIN3: + case BGP_EXT_COM_VPN_ORIGIN4: + case BGP_EXT_COM_OSPF_RID: + case BGP_EXT_COM_OSPF_RID2: + ND_PRINT((ndo, ""%s"", ipaddr_string(ndo, tptr+2))); + break; + case BGP_EXT_COM_OSPF_RTYPE: + case BGP_EXT_COM_OSPF_RTYPE2: + ND_PRINT((ndo, "": area:%s, router-type:%s, metric-type:%s%s"", + ipaddr_string(ndo, tptr+2), + tok2str(bgp_extd_comm_ospf_rtype_values, + ""unknown (0x%02x)"", + *(tptr+6)), + (*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? ""E2"" : """", + ((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? ""E1"" : """")); + break; + case BGP_EXT_COM_L2INFO: + ND_PRINT((ndo, "": %s Control Flags [0x%02x]:MTU %u"", + tok2str(l2vpn_encaps_values, + ""unknown encaps"", + *(tptr+2)), + *(tptr+3), + EXTRACT_16BITS(tptr+4))); + break; + case BGP_EXT_COM_SOURCE_AS: + ND_PRINT((ndo, "": AS %u"", EXTRACT_16BITS(tptr+2))); + break; + default: + ND_TCHECK2(*tptr,8); + print_unknown_data(ndo, tptr, ""\n\t "", 8); + break; + } + tlen -=8; + tptr +=8; + } + break; + + case BGPTYPE_PMSI_TUNNEL: + { + uint8_t tunnel_type, flags; + + ND_TCHECK2(tptr[0], 5); + tunnel_type = *(tptr+1); + flags = *tptr; + tlen = len; + + ND_PRINT((ndo, ""\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u"", + tok2str(bgp_pmsi_tunnel_values, ""Unknown"", tunnel_type), + tunnel_type, + bittok2str(bgp_pmsi_flag_values, ""none"", flags), + EXTRACT_24BITS(tptr+2)>>4)); + + tptr +=5; + tlen -= 5; + + switch (tunnel_type) { + case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */ + case BGP_PMSI_TUNNEL_PIM_BIDIR: + ND_TCHECK2(tptr[0], 8); + ND_PRINT((ndo, ""\n\t Sender %s, P-Group %s"", + ipaddr_string(ndo, tptr), + ipaddr_string(ndo, tptr+4))); + break; + + case BGP_PMSI_TUNNEL_PIM_SSM: + ND_TCHECK2(tptr[0], 8); + ND_PRINT((ndo, ""\n\t Root-Node %s, P-Group %s"", + ipaddr_string(ndo, tptr), + ipaddr_string(ndo, tptr+4))); + break; + case BGP_PMSI_TUNNEL_INGRESS: + ND_TCHECK2(tptr[0], 4); + ND_PRINT((ndo, ""\n\t Tunnel-Endpoint %s"", + ipaddr_string(ndo, tptr))); + break; + case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */ + case BGP_PMSI_TUNNEL_LDP_MP2MP: + ND_TCHECK2(tptr[0], 8); + ND_PRINT((ndo, ""\n\t Root-Node %s, LSP-ID 0x%08x"", + ipaddr_string(ndo, tptr), + EXTRACT_32BITS(tptr+4))); + break; + case BGP_PMSI_TUNNEL_RSVP_P2MP: + ND_TCHECK2(tptr[0], 8); + ND_PRINT((ndo, ""\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x"", + ipaddr_string(ndo, tptr), + EXTRACT_32BITS(tptr+4))); + break; + default: + if (ndo->ndo_vflag <= 1) { + print_unknown_data(ndo, tptr, ""\n\t "", tlen); + } + } + break; + } + case BGPTYPE_AIGP: + { + uint8_t type; + uint16_t length; + + tlen = len; + + while (tlen >= 3) { + + ND_TCHECK2(tptr[0], 3); + + type = *tptr; + length = EXTRACT_16BITS(tptr+1); + tptr += 3; + tlen -= 3; + + ND_PRINT((ndo, ""\n\t %s TLV (%u), length %u"", + tok2str(bgp_aigp_values, ""Unknown"", type), + type, length)); + + if (length < 3) + goto trunc; + length -= 3; + + /* + * Check if we can read the TLV data. + */ + ND_TCHECK2(tptr[3], length); + + switch (type) { + + case BGP_AIGP_TLV: + if (length < 8) + goto trunc; + ND_PRINT((ndo, "", metric %"" PRIu64, + EXTRACT_64BITS(tptr))); + break; + + default: + if (ndo->ndo_vflag <= 1) { + print_unknown_data(ndo, tptr,""\n\t "", length); + } + } + + tptr += length; + tlen -= length; + } + break; + } + case BGPTYPE_ATTR_SET: + ND_TCHECK2(tptr[0], 4); + if (len < 4) + goto trunc; + ND_PRINT((ndo, ""\n\t Origin AS: %s"", + as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)))); + tptr+=4; + len -=4; + + while (len) { + u_int aflags, alenlen, alen; + + ND_TCHECK2(tptr[0], 2); + if (len < 2) + goto trunc; + aflags = *tptr; + atype = *(tptr + 1); + tptr += 2; + len -= 2; + alenlen = bgp_attr_lenlen(aflags, tptr); + ND_TCHECK2(tptr[0], alenlen); + if (len < alenlen) + goto trunc; + alen = bgp_attr_len(aflags, tptr); + tptr += alenlen; + len -= alenlen; + + ND_PRINT((ndo, ""\n\t %s (%u), length: %u"", + tok2str(bgp_attr_values, + ""Unknown Attribute"", atype), + atype, + alen)); + + if (aflags) { + ND_PRINT((ndo, "", Flags [%s%s%s%s"", + aflags & 0x80 ? ""O"" : """", + aflags & 0x40 ? ""T"" : """", + aflags & 0x20 ? ""P"" : """", + aflags & 0x10 ? ""E"" : """")); + if (aflags & 0xf) + ND_PRINT((ndo, ""+%x"", aflags & 0xf)); + ND_PRINT((ndo, ""]: "")); + } + /* FIXME check for recursion */ + if (!bgp_attr_print(ndo, atype, tptr, alen)) + return 0; + tptr += alen; + len -= alen; + } + break; + + case BGPTYPE_LARGE_COMMUNITY: + if (len == 0 || len % 12) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + ND_PRINT((ndo, ""\n\t "")); + while (len > 0) { + ND_TCHECK2(*tptr, 12); + ND_PRINT((ndo, ""%u:%u:%u%s"", + EXTRACT_32BITS(tptr), + EXTRACT_32BITS(tptr + 4), + EXTRACT_32BITS(tptr + 8), + (len > 12) ? "", "" : """")); + tptr += 12; + len -= 12; + } + break; + default: + ND_TCHECK2(*pptr,len); + ND_PRINT((ndo, ""\n\t no Attribute %u decoder"", atype)); /* we have no decoder for the attribute */ + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, pptr, ""\n\t "", len); + break; + } + if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/ + ND_TCHECK2(*pptr,len); + print_unknown_data(ndo, pptr, ""\n\t "", len); + } + return 1; + +trunc: + return 0; +} +",1," bgp_attr_print(netdissect_options *ndo, + u_int atype, const u_char *pptr, u_int len, const unsigned attr_set_level) + { + int i; + uint16_t af; + uint8_t safi, snpa, nhlen; + union { /* copy buffer for bandwidth values */ + float f; + uint32_t i; + } bw; + int advance; + u_int tlen; + const u_char *tptr; + char buf[MAXHOSTNAMELEN + 100]; + int as_size; + + tptr = pptr; + tlen=len; + + switch (atype) { + case BGPTYPE_ORIGIN: + if (len != 1) + ND_PRINT((ndo, ""invalid len"")); + else { + ND_TCHECK(*tptr); + ND_PRINT((ndo, ""%s"", tok2str(bgp_origin_values, + ""Unknown Origin Typecode"", + tptr[0]))); + } + break; + + /* + * Process AS4 byte path and AS2 byte path attributes here. + */ + case BGPTYPE_AS4_PATH: + case BGPTYPE_AS_PATH: + if (len % 2) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + if (!len) { + ND_PRINT((ndo, ""empty"")); + break; + } + + /* + * BGP updates exchanged between New speakers that support 4 + * byte AS, ASs are always encoded in 4 bytes. There is no + * definitive way to find this, just by the packet's + * contents. So, check for packet's TLV's sanity assuming + * 2 bytes first, and it does not pass, assume that ASs are + * encoded in 4 bytes format and move on. + */ + as_size = bgp_attr_get_as_size(ndo, atype, pptr, len); + + while (tptr < pptr + len) { + ND_TCHECK(tptr[0]); + ND_PRINT((ndo, ""%s"", tok2str(bgp_as_path_segment_open_values, + ""?"", tptr[0]))); + ND_TCHECK(tptr[1]); + for (i = 0; i < tptr[1] * as_size; i += as_size) { + ND_TCHECK2(tptr[2 + i], as_size); + ND_PRINT((ndo, ""%s "", + as_printf(ndo, astostr, sizeof(astostr), + as_size == 2 ? + EXTRACT_16BITS(&tptr[2 + i]) : + EXTRACT_32BITS(&tptr[2 + i])))); + } + ND_TCHECK(tptr[0]); + ND_PRINT((ndo, ""%s"", tok2str(bgp_as_path_segment_close_values, + ""?"", tptr[0]))); + ND_TCHECK(tptr[1]); + tptr += 2 + tptr[1] * as_size; + } + break; + case BGPTYPE_NEXT_HOP: + if (len != 4) + ND_PRINT((ndo, ""invalid len"")); + else { + ND_TCHECK2(tptr[0], 4); + ND_PRINT((ndo, ""%s"", ipaddr_string(ndo, tptr))); + } + break; + case BGPTYPE_MULTI_EXIT_DISC: + case BGPTYPE_LOCAL_PREF: + if (len != 4) + ND_PRINT((ndo, ""invalid len"")); + else { + ND_TCHECK2(tptr[0], 4); + ND_PRINT((ndo, ""%u"", EXTRACT_32BITS(tptr))); + } + break; + case BGPTYPE_ATOMIC_AGGREGATE: + if (len != 0) + ND_PRINT((ndo, ""invalid len"")); + break; + case BGPTYPE_AGGREGATOR: + + /* + * Depending on the AS encoded is of 2 bytes or of 4 bytes, + * the length of this PA can be either 6 bytes or 8 bytes. + */ + if (len != 6 && len != 8) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + ND_TCHECK2(tptr[0], len); + if (len == 6) { + ND_PRINT((ndo, "" AS #%s, origin %s"", + as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)), + ipaddr_string(ndo, tptr + 2))); + } else { + ND_PRINT((ndo, "" AS #%s, origin %s"", + as_printf(ndo, astostr, sizeof(astostr), + EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4))); + } + break; + case BGPTYPE_AGGREGATOR4: + if (len != 8) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + ND_TCHECK2(tptr[0], 8); + ND_PRINT((ndo, "" AS #%s, origin %s"", + as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)), + ipaddr_string(ndo, tptr + 4))); + break; + case BGPTYPE_COMMUNITIES: + if (len % 4) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + while (tlen>0) { + uint32_t comm; + ND_TCHECK2(tptr[0], 4); + comm = EXTRACT_32BITS(tptr); + switch (comm) { + case BGP_COMMUNITY_NO_EXPORT: + ND_PRINT((ndo, "" NO_EXPORT"")); + break; + case BGP_COMMUNITY_NO_ADVERT: + ND_PRINT((ndo, "" NO_ADVERTISE"")); + break; + case BGP_COMMUNITY_NO_EXPORT_SUBCONFED: + ND_PRINT((ndo, "" NO_EXPORT_SUBCONFED"")); + break; + default: + ND_PRINT((ndo, ""%u:%u%s"", + (comm >> 16) & 0xffff, + comm & 0xffff, + (tlen>4) ? "", "" : """")); + break; + } + tlen -=4; + tptr +=4; + } + break; + case BGPTYPE_ORIGINATOR_ID: + if (len != 4) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + ND_TCHECK2(tptr[0], 4); + ND_PRINT((ndo, ""%s"",ipaddr_string(ndo, tptr))); + break; + case BGPTYPE_CLUSTER_LIST: + if (len % 4) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + while (tlen>0) { + ND_TCHECK2(tptr[0], 4); + ND_PRINT((ndo, ""%s%s"", + ipaddr_string(ndo, tptr), + (tlen>4) ? "", "" : """")); + tlen -=4; + tptr +=4; + } + break; + case BGPTYPE_MP_REACH_NLRI: + ND_TCHECK2(tptr[0], 3); + af = EXTRACT_16BITS(tptr); + safi = tptr[2]; + + ND_PRINT((ndo, ""\n\t AFI: %s (%u), %sSAFI: %s (%u)"", + tok2str(af_values, ""Unknown AFI"", af), + af, + (safi>128) ? ""vendor specific "" : """", /* 128 is meanwhile wellknown */ + tok2str(bgp_safi_values, ""Unknown SAFI"", safi), + safi)); + + switch(af<<8 | safi) { + case (AFNUM_INET<<8 | SAFNUM_UNICAST): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): + case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): + case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): + case (AFNUM_INET<<8 | SAFNUM_MDT): + case (AFNUM_INET6<<8 | SAFNUM_UNICAST): + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): + case (AFNUM_VPLS<<8 | SAFNUM_VPLS): + break; + default: + ND_TCHECK2(tptr[0], tlen); + ND_PRINT((ndo, ""\n\t no AFI %u / SAFI %u decoder"", af, safi)); + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, tptr, ""\n\t "", tlen); + goto done; + break; + } + + tptr +=3; + + ND_TCHECK(tptr[0]); + nhlen = tptr[0]; + tlen = nhlen; + tptr++; + + if (tlen) { + int nnh = 0; + ND_PRINT((ndo, ""\n\t nexthop: "")); + while (tlen > 0) { + if ( nnh++ > 0 ) { + ND_PRINT((ndo, "", "" )); + } + switch(af<<8 | safi) { + case (AFNUM_INET<<8 | SAFNUM_UNICAST): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): + case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): + case (AFNUM_INET<<8 | SAFNUM_MDT): + if (tlen < (int)sizeof(struct in_addr)) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], sizeof(struct in_addr)); + ND_PRINT((ndo, ""%s"",ipaddr_string(ndo, tptr))); + tlen -= sizeof(struct in_addr); + tptr += sizeof(struct in_addr); + } + break; + case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): + if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN); + ND_PRINT((ndo, ""RD: %s, %s"", + bgp_vpn_rd_print(ndo, tptr), + ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN))); + tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN); + tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN); + } + break; + case (AFNUM_INET6<<8 | SAFNUM_UNICAST): + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): + if (tlen < (int)sizeof(struct in6_addr)) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], sizeof(struct in6_addr)); + ND_PRINT((ndo, ""%s"", ip6addr_string(ndo, tptr))); + tlen -= sizeof(struct in6_addr); + tptr += sizeof(struct in6_addr); + } + break; + case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): + if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN); + ND_PRINT((ndo, ""RD: %s, %s"", + bgp_vpn_rd_print(ndo, tptr), + ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN))); + tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); + tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN); + } + break; + case (AFNUM_VPLS<<8 | SAFNUM_VPLS): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): + if (tlen < (int)sizeof(struct in_addr)) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], sizeof(struct in_addr)); + ND_PRINT((ndo, ""%s"", ipaddr_string(ndo, tptr))); + tlen -= (sizeof(struct in_addr)); + tptr += (sizeof(struct in_addr)); + } + break; + case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): + ND_TCHECK2(tptr[0], tlen); + ND_PRINT((ndo, ""%s"", isonsap_string(ndo, tptr, tlen))); + tptr += tlen; + tlen = 0; + break; + + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): + if (tlen < BGP_VPN_RD_LEN+1) { + ND_PRINT((ndo, ""invalid len"")); + tlen = 0; + } else { + ND_TCHECK2(tptr[0], tlen); + ND_PRINT((ndo, ""RD: %s, %s"", + bgp_vpn_rd_print(ndo, tptr), + isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN))); + /* rfc986 mapped IPv4 address ? */ + if (tlen == BGP_VPN_RD_LEN + 4 + sizeof(struct in_addr) + && EXTRACT_32BITS(tptr+BGP_VPN_RD_LEN) == 0x47000601) + ND_PRINT((ndo, "" = %s"", ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN+4))); + /* rfc1888 mapped IPv6 address ? */ + else if (tlen == BGP_VPN_RD_LEN + 3 + sizeof(struct in6_addr) + && EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000) + ND_PRINT((ndo, "" = %s"", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3))); + tptr += tlen; + tlen = 0; + } + break; + default: + ND_TCHECK2(tptr[0], tlen); + ND_PRINT((ndo, ""no AFI %u/SAFI %u decoder"", af, safi)); + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, tptr, ""\n\t "", tlen); + tptr += tlen; + tlen = 0; + goto done; + break; + } + } + } + ND_PRINT((ndo, "", nh-length: %u"", nhlen)); + tptr += tlen; + + ND_TCHECK(tptr[0]); + snpa = tptr[0]; + tptr++; + + if (snpa) { + ND_PRINT((ndo, ""\n\t %u SNPA"", snpa)); + for (/*nothing*/; snpa > 0; snpa--) { + ND_TCHECK(tptr[0]); + ND_PRINT((ndo, ""\n\t %d bytes"", tptr[0])); + tptr += tptr[0] + 1; + } + } else { + ND_PRINT((ndo, "", no SNPA"")); + } + + while (tptr < pptr + len) { + switch (af<<8 | safi) { + case (AFNUM_INET<<8 | SAFNUM_UNICAST): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): + advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): + advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO): + advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): + advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + + case (AFNUM_INET<<8 | SAFNUM_MDT): + advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_UNICAST): + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): + advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): + advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_VPLS<<8 | SAFNUM_VPLS): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): + advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + default: + ND_TCHECK2(*tptr,tlen); + ND_PRINT((ndo, ""\n\t no AFI %u / SAFI %u decoder"", af, safi)); + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, tptr, ""\n\t "", tlen); + advance = 0; + tptr = pptr + len; + break; + } + if (advance < 0) + break; + tptr += advance; + } + done: + break; + + case BGPTYPE_MP_UNREACH_NLRI: + ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE); + af = EXTRACT_16BITS(tptr); + safi = tptr[2]; + + ND_PRINT((ndo, ""\n\t AFI: %s (%u), %sSAFI: %s (%u)"", + tok2str(af_values, ""Unknown AFI"", af), + af, + (safi>128) ? ""vendor specific "" : """", /* 128 is meanwhile wellknown */ + tok2str(bgp_safi_values, ""Unknown SAFI"", safi), + safi)); + + if (len == BGP_MP_NLRI_MINSIZE) + ND_PRINT((ndo, ""\n\t End-of-Rib Marker (empty NLRI)"")); + + tptr += 3; + + while (tptr < pptr + len) { + switch (af<<8 | safi) { + case (AFNUM_INET<<8 | SAFNUM_UNICAST): + case (AFNUM_INET<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST): + advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_LABUNICAST): + advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_UNICAST): + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST): + advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST): + advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else if (advance == -3) + break; /* bytes left, but not enough */ + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_VPLS<<8 | SAFNUM_VPLS): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_NSAP<<8 | SAFNUM_UNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST): + advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST): + case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST): + advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_MDT): + advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */ + case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN): + advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf)); + if (advance == -1) + ND_PRINT((ndo, ""\n\t (illegal prefix length)"")); + else if (advance == -2) + goto trunc; + else + ND_PRINT((ndo, ""\n\t %s"", buf)); + break; + default: + ND_TCHECK2(*(tptr-3),tlen); + ND_PRINT((ndo, ""no AFI %u / SAFI %u decoder"", af, safi)); + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, tptr-3, ""\n\t "", tlen); + advance = 0; + tptr = pptr + len; + break; + } + if (advance < 0) + break; + tptr += advance; + } + break; + case BGPTYPE_EXTD_COMMUNITIES: + if (len % 8) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + while (tlen>0) { + uint16_t extd_comm; + + ND_TCHECK2(tptr[0], 2); + extd_comm=EXTRACT_16BITS(tptr); + + ND_PRINT((ndo, ""\n\t %s (0x%04x), Flags [%s]"", + tok2str(bgp_extd_comm_subtype_values, + ""unknown extd community typecode"", + extd_comm), + extd_comm, + bittok2str(bgp_extd_comm_flag_values, ""none"", extd_comm))); + + ND_TCHECK2(*(tptr+2), 6); + switch(extd_comm) { + case BGP_EXT_COM_RT_0: + case BGP_EXT_COM_RO_0: + case BGP_EXT_COM_L2VPN_RT_0: + ND_PRINT((ndo, "": %u:%u (= %s)"", + EXTRACT_16BITS(tptr+2), + EXTRACT_32BITS(tptr+4), + ipaddr_string(ndo, tptr+4))); + break; + case BGP_EXT_COM_RT_1: + case BGP_EXT_COM_RO_1: + case BGP_EXT_COM_L2VPN_RT_1: + case BGP_EXT_COM_VRF_RT_IMP: + ND_PRINT((ndo, "": %s:%u"", + ipaddr_string(ndo, tptr+2), + EXTRACT_16BITS(tptr+6))); + break; + case BGP_EXT_COM_RT_2: + case BGP_EXT_COM_RO_2: + ND_PRINT((ndo, "": %s:%u"", + as_printf(ndo, astostr, sizeof(astostr), + EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6))); + break; + case BGP_EXT_COM_LINKBAND: + bw.i = EXTRACT_32BITS(tptr+2); + ND_PRINT((ndo, "": bandwidth: %.3f Mbps"", + bw.f*8/1000000)); + break; + case BGP_EXT_COM_VPN_ORIGIN: + case BGP_EXT_COM_VPN_ORIGIN2: + case BGP_EXT_COM_VPN_ORIGIN3: + case BGP_EXT_COM_VPN_ORIGIN4: + case BGP_EXT_COM_OSPF_RID: + case BGP_EXT_COM_OSPF_RID2: + ND_PRINT((ndo, ""%s"", ipaddr_string(ndo, tptr+2))); + break; + case BGP_EXT_COM_OSPF_RTYPE: + case BGP_EXT_COM_OSPF_RTYPE2: + ND_PRINT((ndo, "": area:%s, router-type:%s, metric-type:%s%s"", + ipaddr_string(ndo, tptr+2), + tok2str(bgp_extd_comm_ospf_rtype_values, + ""unknown (0x%02x)"", + *(tptr+6)), + (*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? ""E2"" : """", + ((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? ""E1"" : """")); + break; + case BGP_EXT_COM_L2INFO: + ND_PRINT((ndo, "": %s Control Flags [0x%02x]:MTU %u"", + tok2str(l2vpn_encaps_values, + ""unknown encaps"", + *(tptr+2)), + *(tptr+3), + EXTRACT_16BITS(tptr+4))); + break; + case BGP_EXT_COM_SOURCE_AS: + ND_PRINT((ndo, "": AS %u"", EXTRACT_16BITS(tptr+2))); + break; + default: + ND_TCHECK2(*tptr,8); + print_unknown_data(ndo, tptr, ""\n\t "", 8); + break; + } + tlen -=8; + tptr +=8; + } + break; + + case BGPTYPE_PMSI_TUNNEL: + { + uint8_t tunnel_type, flags; + + ND_TCHECK2(tptr[0], 5); + tunnel_type = *(tptr+1); + flags = *tptr; + tlen = len; + + ND_PRINT((ndo, ""\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u"", + tok2str(bgp_pmsi_tunnel_values, ""Unknown"", tunnel_type), + tunnel_type, + bittok2str(bgp_pmsi_flag_values, ""none"", flags), + EXTRACT_24BITS(tptr+2)>>4)); + + tptr +=5; + tlen -= 5; + + switch (tunnel_type) { + case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */ + case BGP_PMSI_TUNNEL_PIM_BIDIR: + ND_TCHECK2(tptr[0], 8); + ND_PRINT((ndo, ""\n\t Sender %s, P-Group %s"", + ipaddr_string(ndo, tptr), + ipaddr_string(ndo, tptr+4))); + break; + + case BGP_PMSI_TUNNEL_PIM_SSM: + ND_TCHECK2(tptr[0], 8); + ND_PRINT((ndo, ""\n\t Root-Node %s, P-Group %s"", + ipaddr_string(ndo, tptr), + ipaddr_string(ndo, tptr+4))); + break; + case BGP_PMSI_TUNNEL_INGRESS: + ND_TCHECK2(tptr[0], 4); + ND_PRINT((ndo, ""\n\t Tunnel-Endpoint %s"", + ipaddr_string(ndo, tptr))); + break; + case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */ + case BGP_PMSI_TUNNEL_LDP_MP2MP: + ND_TCHECK2(tptr[0], 8); + ND_PRINT((ndo, ""\n\t Root-Node %s, LSP-ID 0x%08x"", + ipaddr_string(ndo, tptr), + EXTRACT_32BITS(tptr+4))); + break; + case BGP_PMSI_TUNNEL_RSVP_P2MP: + ND_TCHECK2(tptr[0], 8); + ND_PRINT((ndo, ""\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x"", + ipaddr_string(ndo, tptr), + EXTRACT_32BITS(tptr+4))); + break; + default: + if (ndo->ndo_vflag <= 1) { + print_unknown_data(ndo, tptr, ""\n\t "", tlen); + } + } + break; + } + case BGPTYPE_AIGP: + { + uint8_t type; + uint16_t length; + + tlen = len; + + while (tlen >= 3) { + + ND_TCHECK2(tptr[0], 3); + + type = *tptr; + length = EXTRACT_16BITS(tptr+1); + tptr += 3; + tlen -= 3; + + ND_PRINT((ndo, ""\n\t %s TLV (%u), length %u"", + tok2str(bgp_aigp_values, ""Unknown"", type), + type, length)); + + if (length < 3) + goto trunc; + length -= 3; + + /* + * Check if we can read the TLV data. + */ + ND_TCHECK2(tptr[3], length); + + switch (type) { + + case BGP_AIGP_TLV: + if (length < 8) + goto trunc; + ND_PRINT((ndo, "", metric %"" PRIu64, + EXTRACT_64BITS(tptr))); + break; + + default: + if (ndo->ndo_vflag <= 1) { + print_unknown_data(ndo, tptr,""\n\t "", length); + } + } + + tptr += length; + tlen -= length; + } + break; + } + case BGPTYPE_ATTR_SET: + ND_TCHECK2(tptr[0], 4); + if (len < 4) + goto trunc; + ND_PRINT((ndo, ""\n\t Origin AS: %s"", + as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)))); + tptr+=4; + len -=4; + + while (len) { + u_int aflags, alenlen, alen; + + ND_TCHECK2(tptr[0], 2); + if (len < 2) + goto trunc; + aflags = *tptr; + atype = *(tptr + 1); + tptr += 2; + len -= 2; + alenlen = bgp_attr_lenlen(aflags, tptr); + ND_TCHECK2(tptr[0], alenlen); + if (len < alenlen) + goto trunc; + alen = bgp_attr_len(aflags, tptr); + tptr += alenlen; + len -= alenlen; + + ND_PRINT((ndo, ""\n\t %s (%u), length: %u"", + tok2str(bgp_attr_values, + ""Unknown Attribute"", atype), + atype, + alen)); + + if (aflags) { + ND_PRINT((ndo, "", Flags [%s%s%s%s"", + aflags & 0x80 ? ""O"" : """", + aflags & 0x40 ? ""T"" : """", + aflags & 0x20 ? ""P"" : """", + aflags & 0x10 ? ""E"" : """")); + if (aflags & 0xf) + ND_PRINT((ndo, ""+%x"", aflags & 0xf)); + ND_PRINT((ndo, ""]: "")); + } + /* The protocol encoding per se allows ATTR_SET to be nested as many times + * as the message can accommodate. This printer used to be able to recurse + * into ATTR_SET contents until the stack exhaustion, but now there is a + * limit on that (if live protocol exchange goes that many levels deep, + * something is probably wrong anyway). Feel free to refine this value if + * you can find the spec with respective normative text. + */ + if (attr_set_level == 10) + ND_PRINT((ndo, ""(too many nested levels, not recursing)"")); + else if (!bgp_attr_print(ndo, atype, tptr, alen, attr_set_level + 1)) + return 0; + tptr += alen; + len -= alen; + } + break; + + case BGPTYPE_LARGE_COMMUNITY: + if (len == 0 || len % 12) { + ND_PRINT((ndo, ""invalid len"")); + break; + } + ND_PRINT((ndo, ""\n\t "")); + while (len > 0) { + ND_TCHECK2(*tptr, 12); + ND_PRINT((ndo, ""%u:%u:%u%s"", + EXTRACT_32BITS(tptr), + EXTRACT_32BITS(tptr + 4), + EXTRACT_32BITS(tptr + 8), + (len > 12) ? "", "" : """")); + tptr += 12; + len -= 12; + } + break; + default: + ND_TCHECK2(*pptr,len); + ND_PRINT((ndo, ""\n\t no Attribute %u decoder"", atype)); /* we have no decoder for the attribute */ + if (ndo->ndo_vflag <= 1) + print_unknown_data(ndo, pptr, ""\n\t "", len); + break; + } + if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/ + ND_TCHECK2(*pptr,len); + print_unknown_data(ndo, pptr, ""\n\t "", len); + } + return 1; + +trunc: + return 0; +} +","@@ -1361,7 +1361,7 @@ bgp_attr_get_as_size(netdissect_options *ndo, + + static int + bgp_attr_print(netdissect_options *ndo, +- u_int atype, const u_char *pptr, u_int len) ++ u_int atype, const u_char *pptr, u_int len, const unsigned attr_set_level) + { + int i; + uint16_t af; +@@ -2284,8 +2284,16 @@ bgp_attr_print(netdissect_options *ndo, + ND_PRINT((ndo, ""+%x"", aflags & 0xf)); + ND_PRINT((ndo, ""]: "")); + } +- /* FIXME check for recursion */ +- if (!bgp_attr_print(ndo, atype, tptr, alen)) ++ /* The protocol encoding per se allows ATTR_SET to be nested as many times ++ * as the message can accommodate. This printer used to be able to recurse ++ * into ATTR_SET contents until the stack exhaustion, but now there is a ++ * limit on that (if live protocol exchange goes that many levels deep, ++ * something is probably wrong anyway). Feel free to refine this value if ++ * you can find the spec with respective normative text. ++ */ ++ if (attr_set_level == 10) ++ ND_PRINT((ndo, ""(too many nested levels, not recursing)"")); ++ else if (!bgp_attr_print(ndo, atype, tptr, alen, attr_set_level + 1)) + return 0; + tptr += alen; + len -= alen; +@@ -2592,7 +2600,7 @@ bgp_update_print(netdissect_options *ndo, + goto trunc; + if (length < alen) + goto trunc; +- if (!bgp_attr_print(ndo, atype, p, alen)) ++ if (!bgp_attr_print(ndo, atype, p, alen, 0)) + goto trunc; + p += alen; + len -= alen;",9872,10203,11000 +18172,"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; + 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; + } + status=SetImageExtent(image,image->columns,image->rows); + if (status == MagickFalse) + { + InheritException(exception,&image->exception); + return(DestroyImageList(image)); + } + 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; + + /* + 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=(MagickSizeType) columns*rows; + if ((number_pixels*sizeof(uint32)) != (MagickSizeType) ((size_t) + (number_pixels*sizeof(uint32)))) + { + TIFFClose(tiff); + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + } + 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)); +} +",1,"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; + 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; + } + status=SetImageExtent(image,image->columns,image->rows); + if (status == MagickFalse) + { + InheritException(exception,&image->exception); + return(DestroyImageList(image)); + } + 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; + + /* + 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=(MagickSizeType) columns*rows; + if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse) + { + TIFFClose(tiff); + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + } + tile_pixels=(uint32 *) AcquireQuantumMemory(columns, + rows*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 (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse) + { + TIFFClose(tiff); + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + } + pixel_info=AcquireVirtualMemory(image->columns,image->rows* + sizeof(*pixels)); + 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)); +} +","@@ -62,6 +62,7 @@ + #include ""magick/log.h"" + #include ""magick/magick.h"" + #include ""magick/memory_.h"" ++#include ""magick/memory-private.h"" + #include ""magick/module.h"" + #include ""magick/monitor.h"" + #include ""magick/monitor-private.h"" +@@ -1903,14 +1904,13 @@ RestoreMSCWarning + } + (void) SetImageStorageClass(image,DirectClass); + number_pixels=(MagickSizeType) columns*rows; +- if ((number_pixels*sizeof(uint32)) != (MagickSizeType) ((size_t) +- (number_pixels*sizeof(uint32)))) ++ if (HeapOverflowSanityCheck(rows,sizeof(*tile_pixels)) != MagickFalse) + { + TIFFClose(tiff); + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + } +- tile_pixels=(uint32 *) AcquireQuantumMemory(number_pixels, +- sizeof(*tile_pixels)); ++ tile_pixels=(uint32 *) AcquireQuantumMemory(columns, ++ rows*sizeof(*tile_pixels)); + if (tile_pixels == (uint32 *) NULL) + { + TIFFClose(tiff); +@@ -2012,14 +2012,13 @@ RestoreMSCWarning + 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)))) ++ if (HeapOverflowSanityCheck(image->rows,sizeof(*pixels)) != MagickFalse) + { + TIFFClose(tiff); + ThrowReaderException(ResourceLimitError,""MemoryAllocationFailed""); + } + pixel_info=AcquireVirtualMemory(image->columns,image->rows* +- sizeof(uint32)); ++ sizeof(*pixels)); + if (pixel_info == (MemoryInfo *) NULL) + { + TIFFClose(tiff);",8576,8907,11000 +18727,"status_t MPEG4Extractor::parseChunk(off64_t *offset, int depth) { + ALOGV(""entering parseChunk %lld/%d"", *offset, depth); + uint32_t hdr[2]; + if (mDataSource->readAt(*offset, hdr, 8) < 8) { + return ERROR_IO; + } + uint64_t chunk_size = ntohl(hdr[0]); + uint32_t chunk_type = ntohl(hdr[1]); + off64_t data_offset = *offset + 8; + + if (chunk_size == 1) { + if (mDataSource->readAt(*offset + 8, &chunk_size, 8) < 8) { + return ERROR_IO; + } + chunk_size = ntoh64(chunk_size); + data_offset += 8; + + if (chunk_size < 16) { + return ERROR_MALFORMED; + } + } else if (chunk_size == 0) { + if (depth == 0) { + off64_t sourceSize; + if (mDataSource->getSize(&sourceSize) == OK) { + chunk_size = (sourceSize - *offset); + } else { + ALOGE(""atom size is 0, and data source has no size""); + return ERROR_MALFORMED; + } + } else { + *offset += 4; + return OK; + } + } else if (chunk_size < 8) { + ALOGE(""invalid chunk size: %"" PRIu64, chunk_size); + return ERROR_MALFORMED; + } + + char chunk[5]; + MakeFourCCString(chunk_type, chunk); + ALOGV(""chunk: %s @ %lld, %d"", chunk, *offset, depth); + +#if 0 + static const char kWhitespace[] = "" ""; + const char *indent = &kWhitespace[sizeof(kWhitespace) - 1 - 2 * depth]; + printf(""%sfound chunk '%s' of size %"" PRIu64 ""\n"", indent, chunk, chunk_size); + + char buffer[256]; + size_t n = chunk_size; + if (n > sizeof(buffer)) { + n = sizeof(buffer); + } + if (mDataSource->readAt(*offset, buffer, n) + < (ssize_t)n) { + return ERROR_IO; + } + + hexdump(buffer, n); +#endif + + PathAdder autoAdder(&mPath, chunk_type); + + off64_t chunk_data_size = *offset + chunk_size - data_offset; + + if (chunk_type != FOURCC('c', 'p', 'r', 't') + && chunk_type != FOURCC('c', 'o', 'v', 'r') + && mPath.size() == 5 && underMetaDataPath(mPath)) { + off64_t stop_offset = *offset + chunk_size; + *offset = data_offset; + while (*offset < stop_offset) { + status_t err = parseChunk(offset, depth + 1); + if (err != OK) { + return err; + } + } + + if (*offset != stop_offset) { + return ERROR_MALFORMED; + } + + return OK; + } + + switch(chunk_type) { + case FOURCC('m', 'o', 'o', 'v'): + case FOURCC('t', 'r', 'a', 'k'): + case FOURCC('m', 'd', 'i', 'a'): + case FOURCC('m', 'i', 'n', 'f'): + case FOURCC('d', 'i', 'n', 'f'): + case FOURCC('s', 't', 'b', 'l'): + case FOURCC('m', 'v', 'e', 'x'): + case FOURCC('m', 'o', 'o', 'f'): + case FOURCC('t', 'r', 'a', 'f'): + case FOURCC('m', 'f', 'r', 'a'): + case FOURCC('u', 'd', 't', 'a'): + case FOURCC('i', 'l', 's', 't'): + case FOURCC('s', 'i', 'n', 'f'): + case FOURCC('s', 'c', 'h', 'i'): + case FOURCC('e', 'd', 't', 's'): + { + if (chunk_type == FOURCC('s', 't', 'b', 'l')) { + ALOGV(""sampleTable chunk is %"" PRIu64 "" bytes long."", chunk_size); + + if (mDataSource->flags() + & (DataSource::kWantsPrefetching + | DataSource::kIsCachingDataSource)) { + sp cachedSource = + new MPEG4DataSource(mDataSource); + + if (cachedSource->setCachedRange(*offset, chunk_size) == OK) { + mDataSource = cachedSource; + } + } + + mLastTrack->sampleTable = new SampleTable(mDataSource); + } + + bool isTrack = false; + if (chunk_type == FOURCC('t', 'r', 'a', 'k')) { + isTrack = true; + + Track *track = new Track; + track->next = NULL; + if (mLastTrack) { + mLastTrack->next = track; + } else { + mFirstTrack = track; + } + mLastTrack = track; + + track->meta = new MetaData; + track->includes_expensive_metadata = false; + track->skipTrack = false; + track->timescale = 0; + track->meta->setCString(kKeyMIMEType, ""application/octet-stream""); + } + + off64_t stop_offset = *offset + chunk_size; + *offset = data_offset; + while (*offset < stop_offset) { + status_t err = parseChunk(offset, depth + 1); + if (err != OK) { + return err; + } + } + + if (*offset != stop_offset) { + return ERROR_MALFORMED; + } + + if (isTrack) { + if (mLastTrack->skipTrack) { + Track *cur = mFirstTrack; + + if (cur == mLastTrack) { + delete cur; + mFirstTrack = mLastTrack = NULL; + } else { + while (cur && cur->next != mLastTrack) { + cur = cur->next; + } + cur->next = NULL; + delete mLastTrack; + mLastTrack = cur; + } + + return OK; + } + + status_t err = verifyTrack(mLastTrack); + + if (err != OK) { + return err; + } + } else if (chunk_type == FOURCC('m', 'o', 'o', 'v')) { + mInitCheck = OK; + + if (!mIsDrm) { + return UNKNOWN_ERROR; // Return a dummy error. + } else { + return OK; + } + } + break; + } + + case FOURCC('e', 'l', 's', 't'): + { + *offset += chunk_size; + + uint8_t version; + if (mDataSource->readAt(data_offset, &version, 1) < 1) { + return ERROR_IO; + } + + uint32_t entry_count; + if (!mDataSource->getUInt32(data_offset + 4, &entry_count)) { + return ERROR_IO; + } + + if (entry_count != 1) { + ALOGW(""ignoring edit list with %d entries"", entry_count); + } else if (mHeaderTimescale == 0) { + ALOGW(""ignoring edit list because timescale is 0""); + } else { + off64_t entriesoffset = data_offset + 8; + uint64_t segment_duration; + int64_t media_time; + + if (version == 1) { + if (!mDataSource->getUInt64(entriesoffset, &segment_duration) || + !mDataSource->getUInt64(entriesoffset + 8, (uint64_t*)&media_time)) { + return ERROR_IO; + } + } else if (version == 0) { + uint32_t sd; + int32_t mt; + if (!mDataSource->getUInt32(entriesoffset, &sd) || + !mDataSource->getUInt32(entriesoffset + 4, (uint32_t*)&mt)) { + return ERROR_IO; + } + segment_duration = sd; + media_time = mt; + } else { + return ERROR_IO; + } + + uint64_t halfscale = mHeaderTimescale / 2; + segment_duration = (segment_duration * 1000000 + halfscale)/ mHeaderTimescale; + media_time = (media_time * 1000000 + halfscale) / mHeaderTimescale; + + int64_t duration; + int32_t samplerate; + if (!mLastTrack) { + return ERROR_MALFORMED; + } + if (mLastTrack->meta->findInt64(kKeyDuration, &duration) && + mLastTrack->meta->findInt32(kKeySampleRate, &samplerate)) { + + int64_t delay = (media_time * samplerate + 500000) / 1000000; + mLastTrack->meta->setInt32(kKeyEncoderDelay, delay); + + int64_t paddingus = duration - (segment_duration + media_time); + if (paddingus < 0) { + paddingus = 0; + } + int64_t paddingsamples = (paddingus * samplerate + 500000) / 1000000; + mLastTrack->meta->setInt32(kKeyEncoderPadding, paddingsamples); + } + } + break; + } + + case FOURCC('f', 'r', 'm', 'a'): + { + *offset += chunk_size; + + uint32_t original_fourcc; + if (mDataSource->readAt(data_offset, &original_fourcc, 4) < 4) { + return ERROR_IO; + } + original_fourcc = ntohl(original_fourcc); + ALOGV(""read original format: %d"", original_fourcc); + mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(original_fourcc)); + uint32_t num_channels = 0; + uint32_t sample_rate = 0; + if (AdjustChannelsAndRate(original_fourcc, &num_channels, &sample_rate)) { + mLastTrack->meta->setInt32(kKeyChannelCount, num_channels); + mLastTrack->meta->setInt32(kKeySampleRate, sample_rate); + } + break; + } + + case FOURCC('t', 'e', 'n', 'c'): + { + *offset += chunk_size; + + if (chunk_size < 32) { + return ERROR_MALFORMED; + } + + char buf[4]; + memset(buf, 0, 4); + if (mDataSource->readAt(data_offset + 4, buf + 1, 3) < 3) { + return ERROR_IO; + } + uint32_t defaultAlgorithmId = ntohl(*((int32_t*)buf)); + if (defaultAlgorithmId > 1) { + return ERROR_MALFORMED; + } + + memset(buf, 0, 4); + if (mDataSource->readAt(data_offset + 7, buf + 3, 1) < 1) { + return ERROR_IO; + } + uint32_t defaultIVSize = ntohl(*((int32_t*)buf)); + + if ((defaultAlgorithmId == 0 && defaultIVSize != 0) || + (defaultAlgorithmId != 0 && defaultIVSize == 0)) { + return ERROR_MALFORMED; + } else if (defaultIVSize != 0 && + defaultIVSize != 8 && + defaultIVSize != 16) { + return ERROR_MALFORMED; + } + + uint8_t defaultKeyId[16]; + + if (mDataSource->readAt(data_offset + 8, &defaultKeyId, 16) < 16) { + return ERROR_IO; + } + + mLastTrack->meta->setInt32(kKeyCryptoMode, defaultAlgorithmId); + mLastTrack->meta->setInt32(kKeyCryptoDefaultIVSize, defaultIVSize); + mLastTrack->meta->setData(kKeyCryptoKey, 'tenc', defaultKeyId, 16); + break; + } + + case FOURCC('t', 'k', 'h', 'd'): + { + *offset += chunk_size; + + status_t err; + if ((err = parseTrackHeader(data_offset, chunk_data_size)) != OK) { + return err; + } + + break; + } + + case FOURCC('p', 's', 's', 'h'): + { + *offset += chunk_size; + + PsshInfo pssh; + + if (mDataSource->readAt(data_offset + 4, &pssh.uuid, 16) < 16) { + return ERROR_IO; + } + + uint32_t psshdatalen = 0; + if (mDataSource->readAt(data_offset + 20, &psshdatalen, 4) < 4) { + return ERROR_IO; + } + pssh.datalen = ntohl(psshdatalen); + ALOGV(""pssh data size: %d"", pssh.datalen); + if (pssh.datalen + 20 > chunk_size) { + return ERROR_MALFORMED; + } + + pssh.data = new (std::nothrow) uint8_t[pssh.datalen]; + if (pssh.data == NULL) { + return ERROR_MALFORMED; + } + ALOGV(""allocated pssh @ %p"", pssh.data); + ssize_t requested = (ssize_t) pssh.datalen; + if (mDataSource->readAt(data_offset + 24, pssh.data, requested) < requested) { + return ERROR_IO; + } + mPssh.push_back(pssh); + + break; + } + + case FOURCC('m', 'd', 'h', 'd'): + { + *offset += chunk_size; + + if (chunk_data_size < 4 || mLastTrack == NULL) { + return ERROR_MALFORMED; + } + + uint8_t version; + if (mDataSource->readAt( + data_offset, &version, sizeof(version)) + < (ssize_t)sizeof(version)) { + return ERROR_IO; + } + + off64_t timescale_offset; + + if (version == 1) { + timescale_offset = data_offset + 4 + 16; + } else if (version == 0) { + timescale_offset = data_offset + 4 + 8; + } else { + return ERROR_IO; + } + + uint32_t timescale; + if (mDataSource->readAt( + timescale_offset, ×cale, sizeof(timescale)) + < (ssize_t)sizeof(timescale)) { + return ERROR_IO; + } + + mLastTrack->timescale = ntohl(timescale); + + int64_t duration = 0; + if (version == 1) { + if (mDataSource->readAt( + timescale_offset + 4, &duration, sizeof(duration)) + < (ssize_t)sizeof(duration)) { + return ERROR_IO; + } + if (duration != -1) { + duration = ntoh64(duration); + } + } else { + uint32_t duration32; + if (mDataSource->readAt( + timescale_offset + 4, &duration32, sizeof(duration32)) + < (ssize_t)sizeof(duration32)) { + return ERROR_IO; + } + if (duration32 != 0xffffffff) { + duration = ntohl(duration32); + } + } + if (duration != 0) { + mLastTrack->meta->setInt64( + kKeyDuration, (duration * 1000000) / mLastTrack->timescale); + } + + uint8_t lang[2]; + off64_t lang_offset; + if (version == 1) { + lang_offset = timescale_offset + 4 + 8; + } else if (version == 0) { + lang_offset = timescale_offset + 4 + 4; + } else { + return ERROR_IO; + } + + if (mDataSource->readAt(lang_offset, &lang, sizeof(lang)) + < (ssize_t)sizeof(lang)) { + return ERROR_IO; + } + + char lang_code[4]; + lang_code[0] = ((lang[0] >> 2) & 0x1f) + 0x60; + lang_code[1] = ((lang[0] & 0x3) << 3 | (lang[1] >> 5)) + 0x60; + lang_code[2] = (lang[1] & 0x1f) + 0x60; + lang_code[3] = '\0'; + + mLastTrack->meta->setCString( + kKeyMediaLanguage, lang_code); + + break; + } + + case FOURCC('s', 't', 's', 'd'): + { + if (chunk_data_size < 8) { + return ERROR_MALFORMED; + } + + uint8_t buffer[8]; + if (chunk_data_size < (off64_t)sizeof(buffer)) { + return ERROR_MALFORMED; + } + + if (mDataSource->readAt( + data_offset, buffer, 8) < 8) { + return ERROR_IO; + } + + if (U32_AT(buffer) != 0) { + return ERROR_MALFORMED; + } + + uint32_t entry_count = U32_AT(&buffer[4]); + + if (entry_count > 1) { + const char *mime; + CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); + if (strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP) && + strcasecmp(mime, ""application/octet-stream"")) { + mLastTrack->skipTrack = true; + *offset += chunk_size; + break; + } + } + off64_t stop_offset = *offset + chunk_size; + *offset = data_offset + 8; + for (uint32_t i = 0; i < entry_count; ++i) { + status_t err = parseChunk(offset, depth + 1); + if (err != OK) { + return err; + } + } + + if (*offset != stop_offset) { + return ERROR_MALFORMED; + } + break; + } + + case FOURCC('m', 'p', '4', 'a'): + case FOURCC('e', 'n', 'c', 'a'): + case FOURCC('s', 'a', 'm', 'r'): + case FOURCC('s', 'a', 'w', 'b'): + { + uint8_t buffer[8 + 20]; + if (chunk_data_size < (ssize_t)sizeof(buffer)) { + return ERROR_MALFORMED; + } + + if (mDataSource->readAt( + data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) { + return ERROR_IO; + } + + uint16_t data_ref_index = U16_AT(&buffer[6]); + uint32_t num_channels = U16_AT(&buffer[16]); + + uint16_t sample_size = U16_AT(&buffer[18]); + uint32_t sample_rate = U32_AT(&buffer[24]) >> 16; + + if (chunk_type != FOURCC('e', 'n', 'c', 'a')) { + mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type)); + AdjustChannelsAndRate(chunk_type, &num_channels, &sample_rate); + } + ALOGV(""*** coding='%s' %d channels, size %d, rate %d\n"", + chunk, num_channels, sample_size, sample_rate); + mLastTrack->meta->setInt32(kKeyChannelCount, num_channels); + mLastTrack->meta->setInt32(kKeySampleRate, sample_rate); + + off64_t stop_offset = *offset + chunk_size; + *offset = data_offset + sizeof(buffer); + while (*offset < stop_offset) { + status_t err = parseChunk(offset, depth + 1); + if (err != OK) { + return err; + } + } + + if (*offset != stop_offset) { + return ERROR_MALFORMED; + } + break; + } + + case FOURCC('m', 'p', '4', 'v'): + case FOURCC('e', 'n', 'c', 'v'): + case FOURCC('s', '2', '6', '3'): + case FOURCC('H', '2', '6', '3'): + case FOURCC('h', '2', '6', '3'): + case FOURCC('a', 'v', 'c', '1'): + case FOURCC('h', 'v', 'c', '1'): + case FOURCC('h', 'e', 'v', '1'): + { + mHasVideo = true; + + uint8_t buffer[78]; + if (chunk_data_size < (ssize_t)sizeof(buffer)) { + return ERROR_MALFORMED; + } + + if (mDataSource->readAt( + data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) { + return ERROR_IO; + } + + uint16_t data_ref_index = U16_AT(&buffer[6]); + uint16_t width = U16_AT(&buffer[6 + 18]); + uint16_t height = U16_AT(&buffer[6 + 20]); + + if (width == 0) width = 352; + if (height == 0) height = 288; + + + if (chunk_type != FOURCC('e', 'n', 'c', 'v')) { + mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type)); + } + mLastTrack->meta->setInt32(kKeyWidth, width); + mLastTrack->meta->setInt32(kKeyHeight, height); + + off64_t stop_offset = *offset + chunk_size; + *offset = data_offset + sizeof(buffer); + while (*offset < stop_offset) { + status_t err = parseChunk(offset, depth + 1); + if (err != OK) { + return err; + } + } + + if (*offset != stop_offset) { + return ERROR_MALFORMED; + } + break; + } + + case FOURCC('s', 't', 'c', 'o'): + case FOURCC('c', 'o', '6', '4'): + { + status_t err = + mLastTrack->sampleTable->setChunkOffsetParams( + chunk_type, data_offset, chunk_data_size); + + *offset += chunk_size; + + if (err != OK) { + return err; + } + + break; + } + + case FOURCC('s', 't', 's', 'c'): + { + status_t err = + mLastTrack->sampleTable->setSampleToChunkParams( + data_offset, chunk_data_size); + + *offset += chunk_size; + + if (err != OK) { + return err; + } + + break; + } + + case FOURCC('s', 't', 's', 'z'): + case FOURCC('s', 't', 'z', '2'): + { + status_t err = + mLastTrack->sampleTable->setSampleSizeParams( + chunk_type, data_offset, chunk_data_size); + + *offset += chunk_size; + + if (err != OK) { + return err; + } + + size_t max_size; + err = mLastTrack->sampleTable->getMaxSampleSize(&max_size); + + if (err != OK) { + return err; + } + + if (max_size != 0) { + mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size + 10 * 2); + } else { + int32_t width, height; + if (!mLastTrack->meta->findInt32(kKeyWidth, &width) || + !mLastTrack->meta->findInt32(kKeyHeight, &height)) { + ALOGE(""No width or height, assuming worst case 1080p""); + width = 1920; + height = 1080; + } + + const char *mime; + CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); + if (!strcmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)) { + max_size = ((width + 15) / 16) * ((height + 15) / 16) * 192; + } else { + max_size = width * height * 3 / 2; + } + mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size); + } + + const char *mime; + CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); + if (!strncasecmp(""video/"", mime, 6)) { + size_t nSamples = mLastTrack->sampleTable->countSamples(); + int64_t durationUs; + if (mLastTrack->meta->findInt64(kKeyDuration, &durationUs)) { + if (durationUs > 0) { + int32_t frameRate = (nSamples * 1000000LL + + (durationUs >> 1)) / durationUs; + mLastTrack->meta->setInt32(kKeyFrameRate, frameRate); + } + } + } + + break; + } + + case FOURCC('s', 't', 't', 's'): + { + *offset += chunk_size; + + status_t err = + mLastTrack->sampleTable->setTimeToSampleParams( + data_offset, chunk_data_size); + + if (err != OK) { + return err; + } + + break; + } + + case FOURCC('c', 't', 't', 's'): + { + *offset += chunk_size; + + status_t err = + mLastTrack->sampleTable->setCompositionTimeToSampleParams( + data_offset, chunk_data_size); + + if (err != OK) { + return err; + } + + break; + } + + case FOURCC('s', 't', 's', 's'): + { + *offset += chunk_size; + + status_t err = + mLastTrack->sampleTable->setSyncSampleParams( + data_offset, chunk_data_size); + + if (err != OK) { + return err; + } + + break; + } + + case FOURCC('\xA9', 'x', 'y', 'z'): + { + *offset += chunk_size; + + if (chunk_data_size < 8) { + return ERROR_MALFORMED; + } + + char buffer[18]; + + off64_t location_length = chunk_data_size - 5; + if (location_length >= (off64_t) sizeof(buffer)) { + return ERROR_MALFORMED; + } + + if (mDataSource->readAt( + data_offset + 4, buffer, location_length) < location_length) { + return ERROR_IO; + } + + buffer[location_length] = '\0'; + mFileMetaData->setCString(kKeyLocation, buffer); + break; + } + + case FOURCC('e', 's', 'd', 's'): + { + *offset += chunk_size; + + if (chunk_data_size < 4) { + return ERROR_MALFORMED; + } + + uint8_t buffer[256]; + if (chunk_data_size > (off64_t)sizeof(buffer)) { + return ERROR_BUFFER_TOO_SMALL; + } + + if (mDataSource->readAt( + data_offset, buffer, chunk_data_size) < chunk_data_size) { + return ERROR_IO; + } + + if (U32_AT(buffer) != 0) { + return ERROR_MALFORMED; + } + + mLastTrack->meta->setData( + kKeyESDS, kTypeESDS, &buffer[4], chunk_data_size - 4); + + if (mPath.size() >= 2 + && mPath[mPath.size() - 2] == FOURCC('m', 'p', '4', 'a')) { + + status_t err = updateAudioTrackInfoFromESDS_MPEG4Audio( + &buffer[4], chunk_data_size - 4); + + if (err != OK) { + return err; + } + } + + break; + } + + case FOURCC('a', 'v', 'c', 'C'): + { + *offset += chunk_size; + + sp buffer = new ABuffer(chunk_data_size); + + if (mDataSource->readAt( + data_offset, buffer->data(), chunk_data_size) < chunk_data_size) { + return ERROR_IO; + } + + mLastTrack->meta->setData( + kKeyAVCC, kTypeAVCC, buffer->data(), chunk_data_size); + + break; + } + case FOURCC('h', 'v', 'c', 'C'): + { + sp buffer = new ABuffer(chunk_data_size); + + if (mDataSource->readAt( + data_offset, buffer->data(), chunk_data_size) < chunk_data_size) { + return ERROR_IO; + } + + mLastTrack->meta->setData( + kKeyHVCC, kTypeHVCC, buffer->data(), chunk_data_size); + + *offset += chunk_size; + break; + } + + case FOURCC('d', '2', '6', '3'): + { + *offset += chunk_size; + /* + * d263 contains a fixed 7 bytes part: + * vendor - 4 bytes + * version - 1 byte + * level - 1 byte + * profile - 1 byte + * optionally, ""d263"" box itself may contain a 16-byte + * bit rate box (bitr) + * average bit rate - 4 bytes + * max bit rate - 4 bytes + */ + char buffer[23]; + if (chunk_data_size != 7 && + chunk_data_size != 23) { + ALOGE(""Incorrect D263 box size %lld"", chunk_data_size); + return ERROR_MALFORMED; + } + + if (mDataSource->readAt( + data_offset, buffer, chunk_data_size) < chunk_data_size) { + return ERROR_IO; + } + + mLastTrack->meta->setData(kKeyD263, kTypeD263, buffer, chunk_data_size); + + break; + } + + case FOURCC('m', 'e', 't', 'a'): + { + uint8_t buffer[4]; + if (chunk_data_size < (off64_t)sizeof(buffer)) { + *offset += chunk_size; + return ERROR_MALFORMED; + } + + if (mDataSource->readAt( + data_offset, buffer, 4) < 4) { + *offset += chunk_size; + return ERROR_IO; + } + + if (U32_AT(buffer) != 0) { + + *offset += chunk_size; + return OK; + } + + off64_t stop_offset = *offset + chunk_size; + *offset = data_offset + sizeof(buffer); + while (*offset < stop_offset) { + status_t err = parseChunk(offset, depth + 1); + if (err != OK) { + return err; + } + } + + if (*offset != stop_offset) { + return ERROR_MALFORMED; + } + break; + } + + case FOURCC('m', 'e', 'a', 'n'): + case FOURCC('n', 'a', 'm', 'e'): + case FOURCC('d', 'a', 't', 'a'): + { + *offset += chunk_size; + + if (mPath.size() == 6 && underMetaDataPath(mPath)) { + status_t err = parseITunesMetaData(data_offset, chunk_data_size); + + if (err != OK) { + return err; + } + } + + break; + } + + case FOURCC('m', 'v', 'h', 'd'): + { + *offset += chunk_size; + + if (chunk_data_size < 32) { + return ERROR_MALFORMED; + } + + uint8_t header[32]; + if (mDataSource->readAt( + data_offset, header, sizeof(header)) + < (ssize_t)sizeof(header)) { + return ERROR_IO; + } + + uint64_t creationTime; + uint64_t duration = 0; + if (header[0] == 1) { + creationTime = U64_AT(&header[4]); + mHeaderTimescale = U32_AT(&header[20]); + duration = U64_AT(&header[24]); + if (duration == 0xffffffffffffffff) { + duration = 0; + } + } else if (header[0] != 0) { + return ERROR_MALFORMED; + } else { + creationTime = U32_AT(&header[4]); + mHeaderTimescale = U32_AT(&header[12]); + uint32_t d32 = U32_AT(&header[16]); + if (d32 == 0xffffffff) { + d32 = 0; + } + duration = d32; + } + if (duration != 0) { + mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale); + } + + String8 s; + convertTimeToDate(creationTime, &s); + + mFileMetaData->setCString(kKeyDate, s.string()); + + break; + } + + case FOURCC('m', 'e', 'h', 'd'): + { + *offset += chunk_size; + + if (chunk_data_size < 8) { + return ERROR_MALFORMED; + } + + uint8_t flags[4]; + if (mDataSource->readAt( + data_offset, flags, sizeof(flags)) + < (ssize_t)sizeof(flags)) { + return ERROR_IO; + } + + uint64_t duration = 0; + if (flags[0] == 1) { + if (chunk_data_size < 12) { + return ERROR_MALFORMED; + } + mDataSource->getUInt64(data_offset + 4, &duration); + if (duration == 0xffffffffffffffff) { + duration = 0; + } + } else if (flags[0] == 0) { + uint32_t d32; + mDataSource->getUInt32(data_offset + 4, &d32); + if (d32 == 0xffffffff) { + d32 = 0; + } + duration = d32; + } else { + return ERROR_MALFORMED; + } + + if (duration != 0) { + mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale); + } + + break; + } + + case FOURCC('m', 'd', 'a', 't'): + { + ALOGV(""mdat chunk, drm: %d"", mIsDrm); + if (!mIsDrm) { + *offset += chunk_size; + break; + } + + if (chunk_size < 8) { + return ERROR_MALFORMED; + } + + return parseDrmSINF(offset, data_offset); + } + + case FOURCC('h', 'd', 'l', 'r'): + { + *offset += chunk_size; + + uint32_t buffer; + if (mDataSource->readAt( + data_offset + 8, &buffer, 4) < 4) { + return ERROR_IO; + } + + uint32_t type = ntohl(buffer); + if (type == FOURCC('t', 'e', 'x', 't') || type == FOURCC('s', 'b', 't', 'l')) { + mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_TEXT_3GPP); + } + + break; + } + + case FOURCC('t', 'r', 'e', 'x'): + { + *offset += chunk_size; + + if (chunk_data_size < 24) { + return ERROR_IO; + } + uint32_t duration; + Trex trex; + if (!mDataSource->getUInt32(data_offset + 4, &trex.track_ID) || + !mDataSource->getUInt32(data_offset + 8, &trex.default_sample_description_index) || + !mDataSource->getUInt32(data_offset + 12, &trex.default_sample_duration) || + !mDataSource->getUInt32(data_offset + 16, &trex.default_sample_size) || + !mDataSource->getUInt32(data_offset + 20, &trex.default_sample_flags)) { + return ERROR_IO; + } + mTrex.add(trex); + break; + } + + case FOURCC('t', 'x', '3', 'g'): + { + uint32_t type; + const void *data; + size_t size = 0; + if (!mLastTrack->meta->findData( + kKeyTextFormatData, &type, &data, &size)) { + size = 0; + } + + uint8_t *buffer = new (std::nothrow) uint8_t[size + chunk_size]; + if (buffer == NULL) { + return ERROR_MALFORMED; + } + + if (size > 0) { + memcpy(buffer, data, size); + } + + if ((size_t)(mDataSource->readAt(*offset, buffer + size, chunk_size)) + < chunk_size) { + delete[] buffer; + buffer = NULL; + + *offset += chunk_size; + return ERROR_IO; + } + + mLastTrack->meta->setData( + kKeyTextFormatData, 0, buffer, size + chunk_size); + + delete[] buffer; + + *offset += chunk_size; + break; + } + + case FOURCC('c', 'o', 'v', 'r'): + { + *offset += chunk_size; + + if (mFileMetaData != NULL) { + ALOGV(""chunk_data_size = %lld and data_offset = %lld"", + chunk_data_size, data_offset); + sp buffer = new ABuffer(chunk_data_size + 1); + if (mDataSource->readAt( + data_offset, buffer->data(), chunk_data_size) != (ssize_t)chunk_data_size) { + + return ERROR_IO; + } + const int kSkipBytesOfDataBox = 16; + mFileMetaData->setData( + kKeyAlbumArt, MetaData::TYPE_NONE, + buffer->data() + kSkipBytesOfDataBox, chunk_data_size - kSkipBytesOfDataBox); + } + + break; + } + + case FOURCC('t', 'i', 't', 'l'): + case FOURCC('p', 'e', 'r', 'f'): + case FOURCC('a', 'u', 't', 'h'): + case FOURCC('g', 'n', 'r', 'e'): + case FOURCC('a', 'l', 'b', 'm'): + case FOURCC('y', 'r', 'r', 'c'): + { + *offset += chunk_size; + + status_t err = parse3GPPMetaData(data_offset, chunk_data_size, depth); + + if (err != OK) { + return err; + } + + break; + } + + case FOURCC('I', 'D', '3', '2'): + { + *offset += chunk_size; + + if (chunk_data_size < 6) { + return ERROR_MALFORMED; + } + + parseID3v2MetaData(data_offset + 6); + + break; + } + + case FOURCC('-', '-', '-', '-'): + { + mLastCommentMean.clear(); + mLastCommentName.clear(); + mLastCommentData.clear(); + *offset += chunk_size; + break; + } + + case FOURCC('s', 'i', 'd', 'x'): + { + parseSegmentIndex(data_offset, chunk_data_size); + *offset += chunk_size; + return UNKNOWN_ERROR; // stop parsing after sidx + } + + default: + { + *offset += chunk_size; + break; + } + } + + return OK; +} +",1,"status_t MPEG4Extractor::parseChunk(off64_t *offset, int depth) { + ALOGV(""entering parseChunk %lld/%d"", *offset, depth); + uint32_t hdr[2]; + if (mDataSource->readAt(*offset, hdr, 8) < 8) { + return ERROR_IO; + } + uint64_t chunk_size = ntohl(hdr[0]); + uint32_t chunk_type = ntohl(hdr[1]); + off64_t data_offset = *offset + 8; + + if (chunk_size == 1) { + if (mDataSource->readAt(*offset + 8, &chunk_size, 8) < 8) { + return ERROR_IO; + } + chunk_size = ntoh64(chunk_size); + data_offset += 8; + + if (chunk_size < 16) { + return ERROR_MALFORMED; + } + } else if (chunk_size == 0) { + if (depth == 0) { + off64_t sourceSize; + if (mDataSource->getSize(&sourceSize) == OK) { + chunk_size = (sourceSize - *offset); + } else { + ALOGE(""atom size is 0, and data source has no size""); + return ERROR_MALFORMED; + } + } else { + *offset += 4; + return OK; + } + } else if (chunk_size < 8) { + ALOGE(""invalid chunk size: %"" PRIu64, chunk_size); + return ERROR_MALFORMED; + } + + char chunk[5]; + MakeFourCCString(chunk_type, chunk); + ALOGV(""chunk: %s @ %lld, %d"", chunk, *offset, depth); + +#if 0 + static const char kWhitespace[] = "" ""; + const char *indent = &kWhitespace[sizeof(kWhitespace) - 1 - 2 * depth]; + printf(""%sfound chunk '%s' of size %"" PRIu64 ""\n"", indent, chunk, chunk_size); + + char buffer[256]; + size_t n = chunk_size; + if (n > sizeof(buffer)) { + n = sizeof(buffer); + } + if (mDataSource->readAt(*offset, buffer, n) + < (ssize_t)n) { + return ERROR_IO; + } + + hexdump(buffer, n); +#endif + + PathAdder autoAdder(&mPath, chunk_type); + + off64_t chunk_data_size = *offset + chunk_size - data_offset; + + if (chunk_type != FOURCC('c', 'p', 'r', 't') + && chunk_type != FOURCC('c', 'o', 'v', 'r') + && mPath.size() == 5 && underMetaDataPath(mPath)) { + off64_t stop_offset = *offset + chunk_size; + *offset = data_offset; + while (*offset < stop_offset) { + status_t err = parseChunk(offset, depth + 1); + if (err != OK) { + return err; + } + } + + if (*offset != stop_offset) { + return ERROR_MALFORMED; + } + + return OK; + } + + switch(chunk_type) { + case FOURCC('m', 'o', 'o', 'v'): + case FOURCC('t', 'r', 'a', 'k'): + case FOURCC('m', 'd', 'i', 'a'): + case FOURCC('m', 'i', 'n', 'f'): + case FOURCC('d', 'i', 'n', 'f'): + case FOURCC('s', 't', 'b', 'l'): + case FOURCC('m', 'v', 'e', 'x'): + case FOURCC('m', 'o', 'o', 'f'): + case FOURCC('t', 'r', 'a', 'f'): + case FOURCC('m', 'f', 'r', 'a'): + case FOURCC('u', 'd', 't', 'a'): + case FOURCC('i', 'l', 's', 't'): + case FOURCC('s', 'i', 'n', 'f'): + case FOURCC('s', 'c', 'h', 'i'): + case FOURCC('e', 'd', 't', 's'): + { + if (chunk_type == FOURCC('s', 't', 'b', 'l')) { + ALOGV(""sampleTable chunk is %"" PRIu64 "" bytes long."", chunk_size); + + if (mDataSource->flags() + & (DataSource::kWantsPrefetching + | DataSource::kIsCachingDataSource)) { + sp cachedSource = + new MPEG4DataSource(mDataSource); + + if (cachedSource->setCachedRange(*offset, chunk_size) == OK) { + mDataSource = cachedSource; + } + } + + mLastTrack->sampleTable = new SampleTable(mDataSource); + } + + bool isTrack = false; + if (chunk_type == FOURCC('t', 'r', 'a', 'k')) { + isTrack = true; + + Track *track = new Track; + track->next = NULL; + if (mLastTrack) { + mLastTrack->next = track; + } else { + mFirstTrack = track; + } + mLastTrack = track; + + track->meta = new MetaData; + track->includes_expensive_metadata = false; + track->skipTrack = false; + track->timescale = 0; + track->meta->setCString(kKeyMIMEType, ""application/octet-stream""); + } + + off64_t stop_offset = *offset + chunk_size; + *offset = data_offset; + while (*offset < stop_offset) { + status_t err = parseChunk(offset, depth + 1); + if (err != OK) { + return err; + } + } + + if (*offset != stop_offset) { + return ERROR_MALFORMED; + } + + if (isTrack) { + if (mLastTrack->skipTrack) { + Track *cur = mFirstTrack; + + if (cur == mLastTrack) { + delete cur; + mFirstTrack = mLastTrack = NULL; + } else { + while (cur && cur->next != mLastTrack) { + cur = cur->next; + } + cur->next = NULL; + delete mLastTrack; + mLastTrack = cur; + } + + return OK; + } + + status_t err = verifyTrack(mLastTrack); + + if (err != OK) { + return err; + } + } else if (chunk_type == FOURCC('m', 'o', 'o', 'v')) { + mInitCheck = OK; + + if (!mIsDrm) { + return UNKNOWN_ERROR; // Return a dummy error. + } else { + return OK; + } + } + break; + } + + case FOURCC('e', 'l', 's', 't'): + { + *offset += chunk_size; + + uint8_t version; + if (mDataSource->readAt(data_offset, &version, 1) < 1) { + return ERROR_IO; + } + + uint32_t entry_count; + if (!mDataSource->getUInt32(data_offset + 4, &entry_count)) { + return ERROR_IO; + } + + if (entry_count != 1) { + ALOGW(""ignoring edit list with %d entries"", entry_count); + } else if (mHeaderTimescale == 0) { + ALOGW(""ignoring edit list because timescale is 0""); + } else { + off64_t entriesoffset = data_offset + 8; + uint64_t segment_duration; + int64_t media_time; + + if (version == 1) { + if (!mDataSource->getUInt64(entriesoffset, &segment_duration) || + !mDataSource->getUInt64(entriesoffset + 8, (uint64_t*)&media_time)) { + return ERROR_IO; + } + } else if (version == 0) { + uint32_t sd; + int32_t mt; + if (!mDataSource->getUInt32(entriesoffset, &sd) || + !mDataSource->getUInt32(entriesoffset + 4, (uint32_t*)&mt)) { + return ERROR_IO; + } + segment_duration = sd; + media_time = mt; + } else { + return ERROR_IO; + } + + uint64_t halfscale = mHeaderTimescale / 2; + segment_duration = (segment_duration * 1000000 + halfscale)/ mHeaderTimescale; + media_time = (media_time * 1000000 + halfscale) / mHeaderTimescale; + + int64_t duration; + int32_t samplerate; + if (!mLastTrack) { + return ERROR_MALFORMED; + } + if (mLastTrack->meta->findInt64(kKeyDuration, &duration) && + mLastTrack->meta->findInt32(kKeySampleRate, &samplerate)) { + + int64_t delay = (media_time * samplerate + 500000) / 1000000; + mLastTrack->meta->setInt32(kKeyEncoderDelay, delay); + + int64_t paddingus = duration - (segment_duration + media_time); + if (paddingus < 0) { + paddingus = 0; + } + int64_t paddingsamples = (paddingus * samplerate + 500000) / 1000000; + mLastTrack->meta->setInt32(kKeyEncoderPadding, paddingsamples); + } + } + break; + } + + case FOURCC('f', 'r', 'm', 'a'): + { + *offset += chunk_size; + + uint32_t original_fourcc; + if (mDataSource->readAt(data_offset, &original_fourcc, 4) < 4) { + return ERROR_IO; + } + original_fourcc = ntohl(original_fourcc); + ALOGV(""read original format: %d"", original_fourcc); + mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(original_fourcc)); + uint32_t num_channels = 0; + uint32_t sample_rate = 0; + if (AdjustChannelsAndRate(original_fourcc, &num_channels, &sample_rate)) { + mLastTrack->meta->setInt32(kKeyChannelCount, num_channels); + mLastTrack->meta->setInt32(kKeySampleRate, sample_rate); + } + break; + } + + case FOURCC('t', 'e', 'n', 'c'): + { + *offset += chunk_size; + + if (chunk_size < 32) { + return ERROR_MALFORMED; + } + + char buf[4]; + memset(buf, 0, 4); + if (mDataSource->readAt(data_offset + 4, buf + 1, 3) < 3) { + return ERROR_IO; + } + uint32_t defaultAlgorithmId = ntohl(*((int32_t*)buf)); + if (defaultAlgorithmId > 1) { + return ERROR_MALFORMED; + } + + memset(buf, 0, 4); + if (mDataSource->readAt(data_offset + 7, buf + 3, 1) < 1) { + return ERROR_IO; + } + uint32_t defaultIVSize = ntohl(*((int32_t*)buf)); + + if ((defaultAlgorithmId == 0 && defaultIVSize != 0) || + (defaultAlgorithmId != 0 && defaultIVSize == 0)) { + return ERROR_MALFORMED; + } else if (defaultIVSize != 0 && + defaultIVSize != 8 && + defaultIVSize != 16) { + return ERROR_MALFORMED; + } + + uint8_t defaultKeyId[16]; + + if (mDataSource->readAt(data_offset + 8, &defaultKeyId, 16) < 16) { + return ERROR_IO; + } + + mLastTrack->meta->setInt32(kKeyCryptoMode, defaultAlgorithmId); + mLastTrack->meta->setInt32(kKeyCryptoDefaultIVSize, defaultIVSize); + mLastTrack->meta->setData(kKeyCryptoKey, 'tenc', defaultKeyId, 16); + break; + } + + case FOURCC('t', 'k', 'h', 'd'): + { + *offset += chunk_size; + + status_t err; + if ((err = parseTrackHeader(data_offset, chunk_data_size)) != OK) { + return err; + } + + break; + } + + case FOURCC('p', 's', 's', 'h'): + { + *offset += chunk_size; + + PsshInfo pssh; + + if (mDataSource->readAt(data_offset + 4, &pssh.uuid, 16) < 16) { + return ERROR_IO; + } + + uint32_t psshdatalen = 0; + if (mDataSource->readAt(data_offset + 20, &psshdatalen, 4) < 4) { + return ERROR_IO; + } + pssh.datalen = ntohl(psshdatalen); + ALOGV(""pssh data size: %d"", pssh.datalen); + if (pssh.datalen + 20 > chunk_size) { + return ERROR_MALFORMED; + } + + pssh.data = new (std::nothrow) uint8_t[pssh.datalen]; + if (pssh.data == NULL) { + return ERROR_MALFORMED; + } + ALOGV(""allocated pssh @ %p"", pssh.data); + ssize_t requested = (ssize_t) pssh.datalen; + if (mDataSource->readAt(data_offset + 24, pssh.data, requested) < requested) { + return ERROR_IO; + } + mPssh.push_back(pssh); + + break; + } + + case FOURCC('m', 'd', 'h', 'd'): + { + *offset += chunk_size; + + if (chunk_data_size < 4 || mLastTrack == NULL) { + return ERROR_MALFORMED; + } + + uint8_t version; + if (mDataSource->readAt( + data_offset, &version, sizeof(version)) + < (ssize_t)sizeof(version)) { + return ERROR_IO; + } + + off64_t timescale_offset; + + if (version == 1) { + timescale_offset = data_offset + 4 + 16; + } else if (version == 0) { + timescale_offset = data_offset + 4 + 8; + } else { + return ERROR_IO; + } + + uint32_t timescale; + if (mDataSource->readAt( + timescale_offset, ×cale, sizeof(timescale)) + < (ssize_t)sizeof(timescale)) { + return ERROR_IO; + } + + mLastTrack->timescale = ntohl(timescale); + + int64_t duration = 0; + if (version == 1) { + if (mDataSource->readAt( + timescale_offset + 4, &duration, sizeof(duration)) + < (ssize_t)sizeof(duration)) { + return ERROR_IO; + } + if (duration != -1) { + duration = ntoh64(duration); + } + } else { + uint32_t duration32; + if (mDataSource->readAt( + timescale_offset + 4, &duration32, sizeof(duration32)) + < (ssize_t)sizeof(duration32)) { + return ERROR_IO; + } + if (duration32 != 0xffffffff) { + duration = ntohl(duration32); + } + } + if (duration != 0) { + mLastTrack->meta->setInt64( + kKeyDuration, (duration * 1000000) / mLastTrack->timescale); + } + + uint8_t lang[2]; + off64_t lang_offset; + if (version == 1) { + lang_offset = timescale_offset + 4 + 8; + } else if (version == 0) { + lang_offset = timescale_offset + 4 + 4; + } else { + return ERROR_IO; + } + + if (mDataSource->readAt(lang_offset, &lang, sizeof(lang)) + < (ssize_t)sizeof(lang)) { + return ERROR_IO; + } + + char lang_code[4]; + lang_code[0] = ((lang[0] >> 2) & 0x1f) + 0x60; + lang_code[1] = ((lang[0] & 0x3) << 3 | (lang[1] >> 5)) + 0x60; + lang_code[2] = (lang[1] & 0x1f) + 0x60; + lang_code[3] = '\0'; + + mLastTrack->meta->setCString( + kKeyMediaLanguage, lang_code); + + break; + } + + case FOURCC('s', 't', 's', 'd'): + { + if (chunk_data_size < 8) { + return ERROR_MALFORMED; + } + + uint8_t buffer[8]; + if (chunk_data_size < (off64_t)sizeof(buffer)) { + return ERROR_MALFORMED; + } + + if (mDataSource->readAt( + data_offset, buffer, 8) < 8) { + return ERROR_IO; + } + + if (U32_AT(buffer) != 0) { + return ERROR_MALFORMED; + } + + uint32_t entry_count = U32_AT(&buffer[4]); + + if (entry_count > 1) { + const char *mime; + CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); + if (strcasecmp(mime, MEDIA_MIMETYPE_TEXT_3GPP) && + strcasecmp(mime, ""application/octet-stream"")) { + mLastTrack->skipTrack = true; + *offset += chunk_size; + break; + } + } + off64_t stop_offset = *offset + chunk_size; + *offset = data_offset + 8; + for (uint32_t i = 0; i < entry_count; ++i) { + status_t err = parseChunk(offset, depth + 1); + if (err != OK) { + return err; + } + } + + if (*offset != stop_offset) { + return ERROR_MALFORMED; + } + break; + } + + case FOURCC('m', 'p', '4', 'a'): + case FOURCC('e', 'n', 'c', 'a'): + case FOURCC('s', 'a', 'm', 'r'): + case FOURCC('s', 'a', 'w', 'b'): + { + uint8_t buffer[8 + 20]; + if (chunk_data_size < (ssize_t)sizeof(buffer)) { + return ERROR_MALFORMED; + } + + if (mDataSource->readAt( + data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) { + return ERROR_IO; + } + + uint16_t data_ref_index = U16_AT(&buffer[6]); + uint32_t num_channels = U16_AT(&buffer[16]); + + uint16_t sample_size = U16_AT(&buffer[18]); + uint32_t sample_rate = U32_AT(&buffer[24]) >> 16; + + if (chunk_type != FOURCC('e', 'n', 'c', 'a')) { + mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type)); + AdjustChannelsAndRate(chunk_type, &num_channels, &sample_rate); + } + ALOGV(""*** coding='%s' %d channels, size %d, rate %d\n"", + chunk, num_channels, sample_size, sample_rate); + mLastTrack->meta->setInt32(kKeyChannelCount, num_channels); + mLastTrack->meta->setInt32(kKeySampleRate, sample_rate); + + off64_t stop_offset = *offset + chunk_size; + *offset = data_offset + sizeof(buffer); + while (*offset < stop_offset) { + status_t err = parseChunk(offset, depth + 1); + if (err != OK) { + return err; + } + } + + if (*offset != stop_offset) { + return ERROR_MALFORMED; + } + break; + } + + case FOURCC('m', 'p', '4', 'v'): + case FOURCC('e', 'n', 'c', 'v'): + case FOURCC('s', '2', '6', '3'): + case FOURCC('H', '2', '6', '3'): + case FOURCC('h', '2', '6', '3'): + case FOURCC('a', 'v', 'c', '1'): + case FOURCC('h', 'v', 'c', '1'): + case FOURCC('h', 'e', 'v', '1'): + { + mHasVideo = true; + + uint8_t buffer[78]; + if (chunk_data_size < (ssize_t)sizeof(buffer)) { + return ERROR_MALFORMED; + } + + if (mDataSource->readAt( + data_offset, buffer, sizeof(buffer)) < (ssize_t)sizeof(buffer)) { + return ERROR_IO; + } + + uint16_t data_ref_index = U16_AT(&buffer[6]); + uint16_t width = U16_AT(&buffer[6 + 18]); + uint16_t height = U16_AT(&buffer[6 + 20]); + + if (width == 0) width = 352; + if (height == 0) height = 288; + + + if (chunk_type != FOURCC('e', 'n', 'c', 'v')) { + mLastTrack->meta->setCString(kKeyMIMEType, FourCC2MIME(chunk_type)); + } + mLastTrack->meta->setInt32(kKeyWidth, width); + mLastTrack->meta->setInt32(kKeyHeight, height); + + off64_t stop_offset = *offset + chunk_size; + *offset = data_offset + sizeof(buffer); + while (*offset < stop_offset) { + status_t err = parseChunk(offset, depth + 1); + if (err != OK) { + return err; + } + } + + if (*offset != stop_offset) { + return ERROR_MALFORMED; + } + break; + } + + case FOURCC('s', 't', 'c', 'o'): + case FOURCC('c', 'o', '6', '4'): + { + status_t err = + mLastTrack->sampleTable->setChunkOffsetParams( + chunk_type, data_offset, chunk_data_size); + + *offset += chunk_size; + + if (err != OK) { + return err; + } + + break; + } + + case FOURCC('s', 't', 's', 'c'): + { + status_t err = + mLastTrack->sampleTable->setSampleToChunkParams( + data_offset, chunk_data_size); + + *offset += chunk_size; + + if (err != OK) { + return err; + } + + break; + } + + case FOURCC('s', 't', 's', 'z'): + case FOURCC('s', 't', 'z', '2'): + { + status_t err = + mLastTrack->sampleTable->setSampleSizeParams( + chunk_type, data_offset, chunk_data_size); + + *offset += chunk_size; + + if (err != OK) { + return err; + } + + size_t max_size; + err = mLastTrack->sampleTable->getMaxSampleSize(&max_size); + + if (err != OK) { + return err; + } + + if (max_size != 0) { + mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size + 10 * 2); + } else { + int32_t width, height; + if (!mLastTrack->meta->findInt32(kKeyWidth, &width) || + !mLastTrack->meta->findInt32(kKeyHeight, &height)) { + ALOGE(""No width or height, assuming worst case 1080p""); + width = 1920; + height = 1080; + } + + const char *mime; + CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); + if (!strcmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)) { + max_size = ((width + 15) / 16) * ((height + 15) / 16) * 192; + } else { + max_size = width * height * 3 / 2; + } + mLastTrack->meta->setInt32(kKeyMaxInputSize, max_size); + } + + const char *mime; + CHECK(mLastTrack->meta->findCString(kKeyMIMEType, &mime)); + if (!strncasecmp(""video/"", mime, 6)) { + size_t nSamples = mLastTrack->sampleTable->countSamples(); + int64_t durationUs; + if (mLastTrack->meta->findInt64(kKeyDuration, &durationUs)) { + if (durationUs > 0) { + int32_t frameRate = (nSamples * 1000000LL + + (durationUs >> 1)) / durationUs; + mLastTrack->meta->setInt32(kKeyFrameRate, frameRate); + } + } + } + + break; + } + + case FOURCC('s', 't', 't', 's'): + { + *offset += chunk_size; + + status_t err = + mLastTrack->sampleTable->setTimeToSampleParams( + data_offset, chunk_data_size); + + if (err != OK) { + return err; + } + + break; + } + + case FOURCC('c', 't', 't', 's'): + { + *offset += chunk_size; + + status_t err = + mLastTrack->sampleTable->setCompositionTimeToSampleParams( + data_offset, chunk_data_size); + + if (err != OK) { + return err; + } + + break; + } + + case FOURCC('s', 't', 's', 's'): + { + *offset += chunk_size; + + status_t err = + mLastTrack->sampleTable->setSyncSampleParams( + data_offset, chunk_data_size); + + if (err != OK) { + return err; + } + + break; + } + + case FOURCC('\xA9', 'x', 'y', 'z'): + { + *offset += chunk_size; + + if (chunk_data_size < 8) { + return ERROR_MALFORMED; + } + + char buffer[18]; + + off64_t location_length = chunk_data_size - 5; + if (location_length >= (off64_t) sizeof(buffer)) { + return ERROR_MALFORMED; + } + + if (mDataSource->readAt( + data_offset + 4, buffer, location_length) < location_length) { + return ERROR_IO; + } + + buffer[location_length] = '\0'; + mFileMetaData->setCString(kKeyLocation, buffer); + break; + } + + case FOURCC('e', 's', 'd', 's'): + { + *offset += chunk_size; + + if (chunk_data_size < 4) { + return ERROR_MALFORMED; + } + + uint8_t buffer[256]; + if (chunk_data_size > (off64_t)sizeof(buffer)) { + return ERROR_BUFFER_TOO_SMALL; + } + + if (mDataSource->readAt( + data_offset, buffer, chunk_data_size) < chunk_data_size) { + return ERROR_IO; + } + + if (U32_AT(buffer) != 0) { + return ERROR_MALFORMED; + } + + mLastTrack->meta->setData( + kKeyESDS, kTypeESDS, &buffer[4], chunk_data_size - 4); + + if (mPath.size() >= 2 + && mPath[mPath.size() - 2] == FOURCC('m', 'p', '4', 'a')) { + + status_t err = updateAudioTrackInfoFromESDS_MPEG4Audio( + &buffer[4], chunk_data_size - 4); + + if (err != OK) { + return err; + } + } + + break; + } + + case FOURCC('a', 'v', 'c', 'C'): + { + *offset += chunk_size; + + sp buffer = new ABuffer(chunk_data_size); + + if (mDataSource->readAt( + data_offset, buffer->data(), chunk_data_size) < chunk_data_size) { + return ERROR_IO; + } + + mLastTrack->meta->setData( + kKeyAVCC, kTypeAVCC, buffer->data(), chunk_data_size); + + break; + } + case FOURCC('h', 'v', 'c', 'C'): + { + sp buffer = new ABuffer(chunk_data_size); + + if (mDataSource->readAt( + data_offset, buffer->data(), chunk_data_size) < chunk_data_size) { + return ERROR_IO; + } + + mLastTrack->meta->setData( + kKeyHVCC, kTypeHVCC, buffer->data(), chunk_data_size); + + *offset += chunk_size; + break; + } + + case FOURCC('d', '2', '6', '3'): + { + *offset += chunk_size; + /* + * d263 contains a fixed 7 bytes part: + * vendor - 4 bytes + * version - 1 byte + * level - 1 byte + * profile - 1 byte + * optionally, ""d263"" box itself may contain a 16-byte + * bit rate box (bitr) + * average bit rate - 4 bytes + * max bit rate - 4 bytes + */ + char buffer[23]; + if (chunk_data_size != 7 && + chunk_data_size != 23) { + ALOGE(""Incorrect D263 box size %lld"", chunk_data_size); + return ERROR_MALFORMED; + } + + if (mDataSource->readAt( + data_offset, buffer, chunk_data_size) < chunk_data_size) { + return ERROR_IO; + } + + mLastTrack->meta->setData(kKeyD263, kTypeD263, buffer, chunk_data_size); + + break; + } + + case FOURCC('m', 'e', 't', 'a'): + { + uint8_t buffer[4]; + if (chunk_data_size < (off64_t)sizeof(buffer)) { + *offset += chunk_size; + return ERROR_MALFORMED; + } + + if (mDataSource->readAt( + data_offset, buffer, 4) < 4) { + *offset += chunk_size; + return ERROR_IO; + } + + if (U32_AT(buffer) != 0) { + + *offset += chunk_size; + return OK; + } + + off64_t stop_offset = *offset + chunk_size; + *offset = data_offset + sizeof(buffer); + while (*offset < stop_offset) { + status_t err = parseChunk(offset, depth + 1); + if (err != OK) { + return err; + } + } + + if (*offset != stop_offset) { + return ERROR_MALFORMED; + } + break; + } + + case FOURCC('m', 'e', 'a', 'n'): + case FOURCC('n', 'a', 'm', 'e'): + case FOURCC('d', 'a', 't', 'a'): + { + *offset += chunk_size; + + if (mPath.size() == 6 && underMetaDataPath(mPath)) { + status_t err = parseITunesMetaData(data_offset, chunk_data_size); + + if (err != OK) { + return err; + } + } + + break; + } + + case FOURCC('m', 'v', 'h', 'd'): + { + *offset += chunk_size; + + if (chunk_data_size < 32) { + return ERROR_MALFORMED; + } + + uint8_t header[32]; + if (mDataSource->readAt( + data_offset, header, sizeof(header)) + < (ssize_t)sizeof(header)) { + return ERROR_IO; + } + + uint64_t creationTime; + uint64_t duration = 0; + if (header[0] == 1) { + creationTime = U64_AT(&header[4]); + mHeaderTimescale = U32_AT(&header[20]); + duration = U64_AT(&header[24]); + if (duration == 0xffffffffffffffff) { + duration = 0; + } + } else if (header[0] != 0) { + return ERROR_MALFORMED; + } else { + creationTime = U32_AT(&header[4]); + mHeaderTimescale = U32_AT(&header[12]); + uint32_t d32 = U32_AT(&header[16]); + if (d32 == 0xffffffff) { + d32 = 0; + } + duration = d32; + } + if (duration != 0) { + mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale); + } + + String8 s; + convertTimeToDate(creationTime, &s); + + mFileMetaData->setCString(kKeyDate, s.string()); + + break; + } + + case FOURCC('m', 'e', 'h', 'd'): + { + *offset += chunk_size; + + if (chunk_data_size < 8) { + return ERROR_MALFORMED; + } + + uint8_t flags[4]; + if (mDataSource->readAt( + data_offset, flags, sizeof(flags)) + < (ssize_t)sizeof(flags)) { + return ERROR_IO; + } + + uint64_t duration = 0; + if (flags[0] == 1) { + if (chunk_data_size < 12) { + return ERROR_MALFORMED; + } + mDataSource->getUInt64(data_offset + 4, &duration); + if (duration == 0xffffffffffffffff) { + duration = 0; + } + } else if (flags[0] == 0) { + uint32_t d32; + mDataSource->getUInt32(data_offset + 4, &d32); + if (d32 == 0xffffffff) { + d32 = 0; + } + duration = d32; + } else { + return ERROR_MALFORMED; + } + + if (duration != 0) { + mFileMetaData->setInt64(kKeyDuration, duration * 1000000 / mHeaderTimescale); + } + + break; + } + + case FOURCC('m', 'd', 'a', 't'): + { + ALOGV(""mdat chunk, drm: %d"", mIsDrm); + if (!mIsDrm) { + *offset += chunk_size; + break; + } + + if (chunk_size < 8) { + return ERROR_MALFORMED; + } + + return parseDrmSINF(offset, data_offset); + } + + case FOURCC('h', 'd', 'l', 'r'): + { + *offset += chunk_size; + + uint32_t buffer; + if (mDataSource->readAt( + data_offset + 8, &buffer, 4) < 4) { + return ERROR_IO; + } + + uint32_t type = ntohl(buffer); + if (type == FOURCC('t', 'e', 'x', 't') || type == FOURCC('s', 'b', 't', 'l')) { + mLastTrack->meta->setCString(kKeyMIMEType, MEDIA_MIMETYPE_TEXT_3GPP); + } + + break; + } + + case FOURCC('t', 'r', 'e', 'x'): + { + *offset += chunk_size; + + if (chunk_data_size < 24) { + return ERROR_IO; + } + uint32_t duration; + Trex trex; + if (!mDataSource->getUInt32(data_offset + 4, &trex.track_ID) || + !mDataSource->getUInt32(data_offset + 8, &trex.default_sample_description_index) || + !mDataSource->getUInt32(data_offset + 12, &trex.default_sample_duration) || + !mDataSource->getUInt32(data_offset + 16, &trex.default_sample_size) || + !mDataSource->getUInt32(data_offset + 20, &trex.default_sample_flags)) { + return ERROR_IO; + } + mTrex.add(trex); + break; + } + + case FOURCC('t', 'x', '3', 'g'): + { + uint32_t type; + const void *data; + size_t size = 0; + if (!mLastTrack->meta->findData( + kKeyTextFormatData, &type, &data, &size)) { + size = 0; + } + + uint8_t *buffer = new (std::nothrow) uint8_t[size + chunk_size]; + if (buffer == NULL) { + return ERROR_MALFORMED; + } + + if (size > 0) { + memcpy(buffer, data, size); + } + + if ((size_t)(mDataSource->readAt(*offset, buffer + size, chunk_size)) + < chunk_size) { + delete[] buffer; + buffer = NULL; + + *offset += chunk_size; + return ERROR_IO; + } + + mLastTrack->meta->setData( + kKeyTextFormatData, 0, buffer, size + chunk_size); + + delete[] buffer; + + *offset += chunk_size; + break; + } + + case FOURCC('c', 'o', 'v', 'r'): + { + *offset += chunk_size; + + if (mFileMetaData != NULL) { + ALOGV(""chunk_data_size = %lld and data_offset = %lld"", + chunk_data_size, data_offset); + sp buffer = new ABuffer(chunk_data_size + 1); + if (mDataSource->readAt( + data_offset, buffer->data(), chunk_data_size) != (ssize_t)chunk_data_size) { + + return ERROR_IO; + } + const int kSkipBytesOfDataBox = 16; + if (chunk_data_size <= kSkipBytesOfDataBox) { + return ERROR_MALFORMED; + } + + mFileMetaData->setData( + kKeyAlbumArt, MetaData::TYPE_NONE, + buffer->data() + kSkipBytesOfDataBox, chunk_data_size - kSkipBytesOfDataBox); + } + + break; + } + + case FOURCC('t', 'i', 't', 'l'): + case FOURCC('p', 'e', 'r', 'f'): + case FOURCC('a', 'u', 't', 'h'): + case FOURCC('g', 'n', 'r', 'e'): + case FOURCC('a', 'l', 'b', 'm'): + case FOURCC('y', 'r', 'r', 'c'): + { + *offset += chunk_size; + + status_t err = parse3GPPMetaData(data_offset, chunk_data_size, depth); + + if (err != OK) { + return err; + } + + break; + } + + case FOURCC('I', 'D', '3', '2'): + { + *offset += chunk_size; + + if (chunk_data_size < 6) { + return ERROR_MALFORMED; + } + + parseID3v2MetaData(data_offset + 6); + + break; + } + + case FOURCC('-', '-', '-', '-'): + { + mLastCommentMean.clear(); + mLastCommentName.clear(); + mLastCommentData.clear(); + *offset += chunk_size; + break; + } + + case FOURCC('s', 'i', 'd', 'x'): + { + parseSegmentIndex(data_offset, chunk_data_size); + *offset += chunk_size; + return UNKNOWN_ERROR; // stop parsing after sidx + } + + default: + { + *offset += chunk_size; + break; + } + } + + return OK; +} +","@@ -1934,6 +1934,10 @@ + + return ERROR_IO; + } + const int kSkipBytesOfDataBox = 16; ++ if (chunk_data_size <= kSkipBytesOfDataBox) { ++ return ERROR_MALFORMED; ++ } ++ + mFileMetaData->setData( + kKeyAlbumArt, MetaData::TYPE_NONE, + buffer->data() + kSkipBytesOfDataBox, chunk_data_size - kSkipBytesOfDataBox); +",8152,8483,11000 +7749,"static MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image) +{ + const char + *option; + + Image + *next_image; + + MagickBooleanType + status; + + volatile MagickBooleanType + logging; + + MngInfo + *mng_info; + + int + image_count, + need_iterations, + need_matte; + + volatile int +#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ + defined(PNG_MNG_FEATURES_SUPPORTED) + need_local_plte, +#endif + all_images_are_gray, + need_defi, + use_global_plte; + + register ssize_t + i; + + unsigned char + chunk[800]; + + volatile unsigned int + write_jng, + write_mng; + + volatile size_t + scene; + + size_t + final_delay=0, + initial_delay, + imageListLength; + +#if (PNG_LIBPNG_VER < 10200) + if (image_info->verbose) + printf(""Your PNG library (libpng-%s) is rather old.\n"", + PNG_LIBPNG_VER_STRING); +#endif + + /* + Open image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickCoreSignature); + assert(image != (Image *) NULL); + assert(image->signature == MagickCoreSignature); + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); + logging=LogMagickEvent(CoderEvent,GetMagickModule(),""Enter WriteMNGImage()""); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); + if (status == MagickFalse) + return(status); + + /* + Allocate a MngInfo structure. + */ + mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); + if (mng_info == (MngInfo *) NULL) + ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); + /* + Initialize members of the MngInfo structure. + */ + (void) memset(mng_info,0,sizeof(MngInfo)); + mng_info->image=image; + write_mng=LocaleCompare(image_info->magick,""MNG"") == 0; + + /* + * See if user has requested a specific PNG subformat to be used + * for all of the PNGs in the MNG being written, e.g., + * + * convert *.png png8:animation.mng + * + * To do: check -define png:bit_depth and png:color_type as well, + * or perhaps use mng:bit_depth and mng:color_type instead for + * global settings. + */ + + mng_info->write_png8=LocaleCompare(image_info->magick,""PNG8"") == 0; + mng_info->write_png24=LocaleCompare(image_info->magick,""PNG24"") == 0; + mng_info->write_png32=LocaleCompare(image_info->magick,""PNG32"") == 0; + + write_jng=MagickFalse; + if (image_info->compression == JPEGCompression) + write_jng=MagickTrue; + + mng_info->adjoin=image_info->adjoin && + (GetNextImageInList(image) != (Image *) NULL) && write_mng; + + if (logging != MagickFalse) + { + /* Log some info about the input */ + Image + *p; + + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Checking input image(s)\n"" + "" Image_info depth: %.20g, Type: %d"", + (double) image_info->depth, image_info->type); + + scene=0; + for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Scene: %.20g\n, Image depth: %.20g"", + (double) scene++, (double) p->depth); + + if (p->matte) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Matte: True""); + + else + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Matte: False""); + + if (p->storage_class == PseudoClass) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Storage class: PseudoClass""); + + else + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Storage class: DirectClass""); + + if (p->colors) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Number of colors: %.20g"",(double) p->colors); + + else + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Number of colors: unspecified""); + + if (mng_info->adjoin == MagickFalse) + break; + } + } + + use_global_plte=MagickFalse; + all_images_are_gray=MagickFalse; +#ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED + need_local_plte=MagickTrue; +#endif + need_defi=MagickFalse; + need_matte=MagickFalse; + mng_info->framing_mode=1; + mng_info->old_framing_mode=1; + + if (write_mng) + if (image_info->page != (char *) NULL) + { + /* + Determine image bounding box. + */ + SetGeometry(image,&mng_info->page); + (void) ParseMetaGeometry(image_info->page,&mng_info->page.x, + &mng_info->page.y,&mng_info->page.width,&mng_info->page.height); + } + if (write_mng) + { + unsigned int + need_geom; + + unsigned short + red, + green, + blue; + + mng_info->page=image->page; + need_geom=MagickTrue; + if (mng_info->page.width || mng_info->page.height) + need_geom=MagickFalse; + /* + Check all the scenes. + */ + initial_delay=image->delay; + need_iterations=MagickFalse; + mng_info->equal_chrms=image->chromaticity.red_primary.x != 0.0; + mng_info->equal_physs=MagickTrue, + mng_info->equal_gammas=MagickTrue; + mng_info->equal_srgbs=MagickTrue; + mng_info->equal_backgrounds=MagickTrue; + image_count=0; +#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ + defined(PNG_MNG_FEATURES_SUPPORTED) + all_images_are_gray=MagickTrue; + mng_info->equal_palettes=MagickFalse; + need_local_plte=MagickFalse; +#endif + for (next_image=image; next_image != (Image *) NULL; ) + { + if (need_geom) + { + if ((next_image->columns+next_image->page.x) > mng_info->page.width) + mng_info->page.width=next_image->columns+next_image->page.x; + + if ((next_image->rows+next_image->page.y) > mng_info->page.height) + mng_info->page.height=next_image->rows+next_image->page.y; + } + + if (next_image->page.x || next_image->page.y) + need_defi=MagickTrue; + + if (next_image->matte) + need_matte=MagickTrue; + + if ((int) next_image->dispose >= BackgroundDispose) + if (next_image->matte || next_image->page.x || next_image->page.y || + ((next_image->columns < mng_info->page.width) && + (next_image->rows < mng_info->page.height))) + mng_info->need_fram=MagickTrue; + + if (next_image->iterations) + need_iterations=MagickTrue; + + final_delay=next_image->delay; + + if (final_delay != initial_delay || final_delay > 1UL* + next_image->ticks_per_second) + mng_info->need_fram=1; + +#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ + defined(PNG_MNG_FEATURES_SUPPORTED) + /* + check for global palette possibility. + */ + if (image->matte != MagickFalse) + need_local_plte=MagickTrue; + + if (need_local_plte == 0) + { + if (SetImageGray(image,&image->exception) == MagickFalse) + all_images_are_gray=MagickFalse; + mng_info->equal_palettes=PalettesAreEqual(image,next_image); + if (use_global_plte == 0) + use_global_plte=mng_info->equal_palettes; + need_local_plte=!mng_info->equal_palettes; + } +#endif + if (GetNextImageInList(next_image) != (Image *) NULL) + { + if (next_image->background_color.red != + next_image->next->background_color.red || + next_image->background_color.green != + next_image->next->background_color.green || + next_image->background_color.blue != + next_image->next->background_color.blue) + mng_info->equal_backgrounds=MagickFalse; + + if (next_image->gamma != next_image->next->gamma) + mng_info->equal_gammas=MagickFalse; + + if (next_image->rendering_intent != + next_image->next->rendering_intent) + mng_info->equal_srgbs=MagickFalse; + + if ((next_image->units != next_image->next->units) || + (next_image->x_resolution != next_image->next->x_resolution) || + (next_image->y_resolution != next_image->next->y_resolution)) + mng_info->equal_physs=MagickFalse; + + if (mng_info->equal_chrms) + { + if (next_image->chromaticity.red_primary.x != + next_image->next->chromaticity.red_primary.x || + next_image->chromaticity.red_primary.y != + next_image->next->chromaticity.red_primary.y || + next_image->chromaticity.green_primary.x != + next_image->next->chromaticity.green_primary.x || + next_image->chromaticity.green_primary.y != + next_image->next->chromaticity.green_primary.y || + next_image->chromaticity.blue_primary.x != + next_image->next->chromaticity.blue_primary.x || + next_image->chromaticity.blue_primary.y != + next_image->next->chromaticity.blue_primary.y || + next_image->chromaticity.white_point.x != + next_image->next->chromaticity.white_point.x || + next_image->chromaticity.white_point.y != + next_image->next->chromaticity.white_point.y) + mng_info->equal_chrms=MagickFalse; + } + } + image_count++; + next_image=GetNextImageInList(next_image); + } + if (image_count < 2) + { + mng_info->equal_backgrounds=MagickFalse; + mng_info->equal_chrms=MagickFalse; + mng_info->equal_gammas=MagickFalse; + mng_info->equal_srgbs=MagickFalse; + mng_info->equal_physs=MagickFalse; + use_global_plte=MagickFalse; +#ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED + need_local_plte=MagickTrue; +#endif + need_iterations=MagickFalse; + } + + if (mng_info->need_fram == MagickFalse) + { + /* + Only certain framing rates 100/n are exactly representable without + the FRAM chunk but we'll allow some slop in VLC files + */ + if (final_delay == 0) + { + if (need_iterations != MagickFalse) + { + /* + It's probably a GIF with loop; don't run it *too* fast. + */ + if (mng_info->adjoin) + { + final_delay=10; + (void) ThrowMagickException(&image->exception, + GetMagickModule(),CoderWarning, + ""input has zero delay between all frames; assuming"", + "" 10 cs `%s'"",""""); + } + } + else + mng_info->ticks_per_second=0; + } + if (final_delay != 0) + mng_info->ticks_per_second=(png_uint_32) + (image->ticks_per_second/final_delay); + if (final_delay > 50) + mng_info->ticks_per_second=2; + + if (final_delay > 75) + mng_info->ticks_per_second=1; + + if (final_delay > 125) + mng_info->need_fram=MagickTrue; + + if (need_defi && final_delay > 2 && (final_delay != 4) && + (final_delay != 5) && (final_delay != 10) && (final_delay != 20) && + (final_delay != 25) && (final_delay != 50) && + (final_delay != (size_t) image->ticks_per_second)) + mng_info->need_fram=MagickTrue; /* make it exact; cannot be VLC */ + } + + if (mng_info->need_fram != MagickFalse) + mng_info->ticks_per_second=1UL*image->ticks_per_second; + /* + If pseudocolor, we should also check to see if all the + palettes are identical and write a global PLTE if they are. + ../glennrp Feb 99. + */ + /* + Write the MNG version 1.0 signature and MHDR chunk. + */ + (void) WriteBlob(image,8,(const unsigned char *) ""\212MNG\r\n\032\n""); + (void) WriteBlobMSBULong(image,28L); /* chunk data length=28 */ + PNGType(chunk,mng_MHDR); + LogPNGChunk(logging,mng_MHDR,28L); + PNGLong(chunk+4,(png_uint_32) mng_info->page.width); + PNGLong(chunk+8,(png_uint_32) mng_info->page.height); + PNGLong(chunk+12,mng_info->ticks_per_second); + PNGLong(chunk+16,0L); /* layer count=unknown */ + PNGLong(chunk+20,0L); /* frame count=unknown */ + PNGLong(chunk+24,0L); /* play time=unknown */ + if (write_jng) + { + if (need_matte) + { + if (need_defi || mng_info->need_fram || use_global_plte) + PNGLong(chunk+28,27L); /* simplicity=LC+JNG */ + + else + PNGLong(chunk+28,25L); /* simplicity=VLC+JNG */ + } + + else + { + if (need_defi || mng_info->need_fram || use_global_plte) + PNGLong(chunk+28,19L); /* simplicity=LC+JNG, no transparency */ + + else + PNGLong(chunk+28,17L); /* simplicity=VLC+JNG, no transparency */ + } + } + + else + { + if (need_matte) + { + if (need_defi || mng_info->need_fram || use_global_plte) + PNGLong(chunk+28,11L); /* simplicity=LC */ + + else + PNGLong(chunk+28,9L); /* simplicity=VLC */ + } + + else + { + if (need_defi || mng_info->need_fram || use_global_plte) + PNGLong(chunk+28,3L); /* simplicity=LC, no transparency */ + + else + PNGLong(chunk+28,1L); /* simplicity=VLC, no transparency */ + } + } + (void) WriteBlob(image,32,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,32)); + option=GetImageOption(image_info,""mng:need-cacheoff""); + if (option != (const char *) NULL) + { + size_t + length; + + /* + Write ""nEED CACHEOFF"" to turn playback caching off for streaming MNG. + */ + PNGType(chunk,mng_nEED); + length=CopyMagickString((char *) chunk+4,""CACHEOFF"",20); + (void) WriteBlobMSBULong(image,(size_t) length); + LogPNGChunk(logging,mng_nEED,(size_t) length); + length+=4; + (void) WriteBlob(image,length,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) length)); + } + if ((GetPreviousImageInList(image) == (Image *) NULL) && + (GetNextImageInList(image) != (Image *) NULL) && + (image->iterations != 1)) + { + /* + Write MNG TERM chunk + */ + (void) WriteBlobMSBULong(image,10L); /* data length=10 */ + PNGType(chunk,mng_TERM); + LogPNGChunk(logging,mng_TERM,10L); + chunk[4]=3; /* repeat animation */ + chunk[5]=0; /* show last frame when done */ + PNGLong(chunk+6,(png_uint_32) (mng_info->ticks_per_second* + final_delay/MagickMax(image->ticks_per_second,1))); + + if (image->iterations == 0) + PNGLong(chunk+10,PNG_UINT_31_MAX); + + else + PNGLong(chunk+10,(png_uint_32) image->iterations); + + if (logging != MagickFalse) + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" TERM delay: %.20g"",(double) (mng_info->ticks_per_second* + final_delay/MagickMax(image->ticks_per_second,1))); + + if (image->iterations == 0) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" TERM iterations: %.20g"",(double) PNG_UINT_31_MAX); + + else + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Image iterations: %.20g"",(double) image->iterations); + } + (void) WriteBlob(image,14,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,14)); + } + /* + To do: check for cHRM+gAMA == sRGB, and write sRGB instead. + */ + if ((image->colorspace == sRGBColorspace || image->rendering_intent) && + mng_info->equal_srgbs) + { + /* + Write MNG sRGB chunk + */ + (void) WriteBlobMSBULong(image,1L); + PNGType(chunk,mng_sRGB); + LogPNGChunk(logging,mng_sRGB,1L); + + if (image->rendering_intent != UndefinedIntent) + chunk[4]=(unsigned char) + Magick_RenderingIntent_to_PNG_RenderingIntent( + (image->rendering_intent)); + + else + chunk[4]=(unsigned char) + Magick_RenderingIntent_to_PNG_RenderingIntent( + (PerceptualIntent)); + + (void) WriteBlob(image,5,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); + mng_info->have_write_global_srgb=MagickTrue; + } + + else + { + if (image->gamma && mng_info->equal_gammas) + { + /* + Write MNG gAMA chunk + */ + (void) WriteBlobMSBULong(image,4L); + PNGType(chunk,mng_gAMA); + LogPNGChunk(logging,mng_gAMA,4L); + PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5)); + (void) WriteBlob(image,8,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,8)); + mng_info->have_write_global_gama=MagickTrue; + } + if (mng_info->equal_chrms) + { + PrimaryInfo + primary; + + /* + Write MNG cHRM chunk + */ + (void) WriteBlobMSBULong(image,32L); + PNGType(chunk,mng_cHRM); + LogPNGChunk(logging,mng_cHRM,32L); + primary=image->chromaticity.white_point; + PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5)); + PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5)); + primary=image->chromaticity.red_primary; + PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5)); + PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5)); + primary=image->chromaticity.green_primary; + PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5)); + PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5)); + primary=image->chromaticity.blue_primary; + PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5)); + PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5)); + (void) WriteBlob(image,36,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,36)); + mng_info->have_write_global_chrm=MagickTrue; + } + } + if (image->x_resolution && image->y_resolution && mng_info->equal_physs) + { + /* + Write MNG pHYs chunk + */ + (void) WriteBlobMSBULong(image,9L); + PNGType(chunk,mng_pHYs); + LogPNGChunk(logging,mng_pHYs,9L); + + if (image->units == PixelsPerInchResolution) + { + PNGLong(chunk+4,(png_uint_32) + (image->x_resolution*100.0/2.54+0.5)); + + PNGLong(chunk+8,(png_uint_32) + (image->y_resolution*100.0/2.54+0.5)); + + chunk[12]=1; + } + + else + { + if (image->units == PixelsPerCentimeterResolution) + { + PNGLong(chunk+4,(png_uint_32) + (image->x_resolution*100.0+0.5)); + + PNGLong(chunk+8,(png_uint_32) + (image->y_resolution*100.0+0.5)); + + chunk[12]=1; + } + + else + { + PNGLong(chunk+4,(png_uint_32) (image->x_resolution+0.5)); + PNGLong(chunk+8,(png_uint_32) (image->y_resolution+0.5)); + chunk[12]=0; + } + } + (void) WriteBlob(image,13,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); + } + /* + Write MNG BACK chunk and global bKGD chunk, if the image is transparent + or does not cover the entire frame. + */ + if (write_mng && (image->matte || image->page.x > 0 || + image->page.y > 0 || (image->page.width && + (image->page.width+image->page.x < mng_info->page.width)) + || (image->page.height && (image->page.height+image->page.y + < mng_info->page.height)))) + { + (void) WriteBlobMSBULong(image,6L); + PNGType(chunk,mng_BACK); + LogPNGChunk(logging,mng_BACK,6L); + red=ScaleQuantumToShort(image->background_color.red); + green=ScaleQuantumToShort(image->background_color.green); + blue=ScaleQuantumToShort(image->background_color.blue); + PNGShort(chunk+4,red); + PNGShort(chunk+6,green); + PNGShort(chunk+8,blue); + (void) WriteBlob(image,10,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,10)); + if (mng_info->equal_backgrounds) + { + (void) WriteBlobMSBULong(image,6L); + PNGType(chunk,mng_bKGD); + LogPNGChunk(logging,mng_bKGD,6L); + (void) WriteBlob(image,10,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,10)); + } + } + +#ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED + if ((need_local_plte == MagickFalse) && + (image->storage_class == PseudoClass) && + (all_images_are_gray == MagickFalse)) + { + size_t + data_length; + + /* + Write MNG PLTE chunk + */ + data_length=3*image->colors; + (void) WriteBlobMSBULong(image,data_length); + PNGType(chunk,mng_PLTE); + LogPNGChunk(logging,mng_PLTE,data_length); + + for (i=0; i < (ssize_t) image->colors; i++) + { + chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red) & 0xff; + chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green) & 0xff; + chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue) & 0xff; + } + + (void) WriteBlob(image,data_length+4,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) (data_length+4))); + mng_info->have_write_global_plte=MagickTrue; + } +#endif + } + scene=0; + mng_info->delay=0; +#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ + defined(PNG_MNG_FEATURES_SUPPORTED) + mng_info->equal_palettes=MagickFalse; +#endif + imageListLength=GetImageListLength(image); + do + { + if (mng_info->adjoin) + { +#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ + defined(PNG_MNG_FEATURES_SUPPORTED) + /* + If we aren't using a global palette for the entire MNG, check to + see if we can use one for two or more consecutive images. + */ + if (need_local_plte && use_global_plte && !all_images_are_gray) + { + if (mng_info->IsPalette) + { + /* + When equal_palettes is true, this image has the same palette + as the previous PseudoClass image + */ + mng_info->have_write_global_plte=mng_info->equal_palettes; + mng_info->equal_palettes=PalettesAreEqual(image,image->next); + if (mng_info->equal_palettes && !mng_info->have_write_global_plte) + { + /* + Write MNG PLTE chunk + */ + size_t + data_length; + + data_length=3*image->colors; + (void) WriteBlobMSBULong(image,data_length); + PNGType(chunk,mng_PLTE); + LogPNGChunk(logging,mng_PLTE,data_length); + + for (i=0; i < (ssize_t) image->colors; i++) + { + chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red); + chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green); + chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue); + } + + (void) WriteBlob(image,data_length+4,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk, + (uInt) (data_length+4))); + mng_info->have_write_global_plte=MagickTrue; + } + } + else + mng_info->have_write_global_plte=MagickFalse; + } +#endif + if (need_defi) + { + ssize_t + previous_x, + previous_y; + + if (scene != 0) + { + previous_x=mng_info->page.x; + previous_y=mng_info->page.y; + } + else + { + previous_x=0; + previous_y=0; + } + mng_info->page=image->page; + if ((mng_info->page.x != previous_x) || + (mng_info->page.y != previous_y)) + { + (void) WriteBlobMSBULong(image,12L); /* data length=12 */ + PNGType(chunk,mng_DEFI); + LogPNGChunk(logging,mng_DEFI,12L); + chunk[4]=0; /* object 0 MSB */ + chunk[5]=0; /* object 0 LSB */ + chunk[6]=0; /* visible */ + chunk[7]=0; /* abstract */ + PNGLong(chunk+8,(png_uint_32) mng_info->page.x); + PNGLong(chunk+12,(png_uint_32) mng_info->page.y); + (void) WriteBlob(image,16,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,16)); + } + } + } + + mng_info->write_mng=write_mng; + + if ((int) image->dispose >= 3) + mng_info->framing_mode=3; + + if (mng_info->need_fram && mng_info->adjoin && + ((image->delay != mng_info->delay) || + (mng_info->framing_mode != mng_info->old_framing_mode))) + { + if (image->delay == mng_info->delay) + { + /* + Write a MNG FRAM chunk with the new framing mode. + */ + (void) WriteBlobMSBULong(image,1L); /* data length=1 */ + PNGType(chunk,mng_FRAM); + LogPNGChunk(logging,mng_FRAM,1L); + chunk[4]=(unsigned char) mng_info->framing_mode; + (void) WriteBlob(image,5,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); + } + else + { + /* + Write a MNG FRAM chunk with the delay. + */ + (void) WriteBlobMSBULong(image,10L); /* data length=10 */ + PNGType(chunk,mng_FRAM); + LogPNGChunk(logging,mng_FRAM,10L); + chunk[4]=(unsigned char) mng_info->framing_mode; + chunk[5]=0; /* frame name separator (no name) */ + chunk[6]=2; /* flag for changing default delay */ + chunk[7]=0; /* flag for changing frame timeout */ + chunk[8]=0; /* flag for changing frame clipping */ + chunk[9]=0; /* flag for changing frame sync_id */ + PNGLong(chunk+10,(png_uint_32) + ((mng_info->ticks_per_second* + image->delay)/MagickMax(image->ticks_per_second,1))); + (void) WriteBlob(image,14,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,14)); + mng_info->delay=(png_uint_32) image->delay; + } + mng_info->old_framing_mode=mng_info->framing_mode; + } + +#if defined(JNG_SUPPORTED) + if (image_info->compression == JPEGCompression) + { + ImageInfo + *write_info; + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Writing JNG object.""); + /* To do: specify the desired alpha compression method. */ + write_info=CloneImageInfo(image_info); + write_info->compression=UndefinedCompression; + status=WriteOneJNGImage(mng_info,write_info,image); + write_info=DestroyImageInfo(write_info); + } + else +#endif + { + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Writing PNG object.""); + + mng_info->need_blob = MagickFalse; + mng_info->ping_preserve_colormap = MagickFalse; + + /* We don't want any ancillary chunks written */ + mng_info->ping_exclude_bKGD=MagickTrue; + mng_info->ping_exclude_caNv=MagickTrue; + mng_info->ping_exclude_cHRM=MagickTrue; + mng_info->ping_exclude_date=MagickTrue; + mng_info->ping_exclude_EXIF=MagickTrue; + mng_info->ping_exclude_eXIf=MagickTrue; + mng_info->ping_exclude_gAMA=MagickTrue; + mng_info->ping_exclude_iCCP=MagickTrue; + /* mng_info->ping_exclude_iTXt=MagickTrue; */ + mng_info->ping_exclude_oFFs=MagickTrue; + mng_info->ping_exclude_pHYs=MagickTrue; + mng_info->ping_exclude_sRGB=MagickTrue; + mng_info->ping_exclude_tEXt=MagickTrue; + mng_info->ping_exclude_tRNS=MagickTrue; + mng_info->ping_exclude_zCCP=MagickTrue; + mng_info->ping_exclude_zTXt=MagickTrue; + + status=WriteOnePNGImage(mng_info,image_info,image); + } + + if (status == MagickFalse) + { + mng_info=MngInfoFreeStruct(mng_info); + (void) CloseBlob(image); + return(MagickFalse); + } + (void) CatchImageException(image); + if (GetNextImageInList(image) == (Image *) NULL) + break; + image=SyncNextImageInList(image); + status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); + + if (status == MagickFalse) + break; + + } while (mng_info->adjoin); + + if (write_mng) + { + while (GetPreviousImageInList(image) != (Image *) NULL) + image=GetPreviousImageInList(image); + /* + Write the MEND chunk. + */ + (void) WriteBlobMSBULong(image,0x00000000L); + PNGType(chunk,mng_MEND); + LogPNGChunk(logging,mng_MEND,0L); + (void) WriteBlob(image,4,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,4)); + } + /* + Relinquish resources. + */ + (void) CloseBlob(image); + mng_info=MngInfoFreeStruct(mng_info); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(),""exit WriteMNGImage()""); + + return(MagickTrue); +} +",0,"static MagickBooleanType WriteMNGImage(const ImageInfo *image_info,Image *image) +{ + const char + *option; + + Image + *next_image; + + MagickBooleanType + status; + + volatile MagickBooleanType + logging; + + MngInfo + *mng_info; + + int + image_count, + need_iterations, + need_matte; + + volatile int +#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ + defined(PNG_MNG_FEATURES_SUPPORTED) + need_local_plte, +#endif + all_images_are_gray, + need_defi, + use_global_plte; + + register ssize_t + i; + + unsigned char + chunk[800]; + + volatile unsigned int + write_jng, + write_mng; + + volatile size_t + scene; + + size_t + final_delay=0, + initial_delay, + imageListLength; + +#if (PNG_LIBPNG_VER < 10200) + if (image_info->verbose) + printf(""Your PNG library (libpng-%s) is rather old.\n"", + PNG_LIBPNG_VER_STRING); +#endif + + /* + Open image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickCoreSignature); + assert(image != (Image *) NULL); + assert(image->signature == MagickCoreSignature); + (void) LogMagickEvent(TraceEvent,GetMagickModule(),""%s"",image->filename); + logging=LogMagickEvent(CoderEvent,GetMagickModule(),""Enter WriteMNGImage()""); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); + if (status == MagickFalse) + return(status); + + /* + Allocate a MngInfo structure. + */ + mng_info=(MngInfo *) AcquireMagickMemory(sizeof(MngInfo)); + if (mng_info == (MngInfo *) NULL) + ThrowWriterException(ResourceLimitError,""MemoryAllocationFailed""); + /* + Initialize members of the MngInfo structure. + */ + (void) memset(mng_info,0,sizeof(MngInfo)); + mng_info->image=image; + write_mng=LocaleCompare(image_info->magick,""MNG"") == 0; + + /* + * See if user has requested a specific PNG subformat to be used + * for all of the PNGs in the MNG being written, e.g., + * + * convert *.png png8:animation.mng + * + * To do: check -define png:bit_depth and png:color_type as well, + * or perhaps use mng:bit_depth and mng:color_type instead for + * global settings. + */ + + mng_info->write_png8=LocaleCompare(image_info->magick,""PNG8"") == 0; + mng_info->write_png24=LocaleCompare(image_info->magick,""PNG24"") == 0; + mng_info->write_png32=LocaleCompare(image_info->magick,""PNG32"") == 0; + + write_jng=MagickFalse; + if (image_info->compression == JPEGCompression) + write_jng=MagickTrue; + + mng_info->adjoin=image_info->adjoin && + (GetNextImageInList(image) != (Image *) NULL) && write_mng; + + if (logging != MagickFalse) + { + /* Log some info about the input */ + Image + *p; + + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Checking input image(s)\n"" + "" Image_info depth: %.20g, Type: %d"", + (double) image_info->depth, image_info->type); + + scene=0; + for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Scene: %.20g\n, Image depth: %.20g"", + (double) scene++, (double) p->depth); + + if (p->matte) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Matte: True""); + + else + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Matte: False""); + + if (p->storage_class == PseudoClass) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Storage class: PseudoClass""); + + else + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Storage class: DirectClass""); + + if (p->colors) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Number of colors: %.20g"",(double) p->colors); + + else + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Number of colors: unspecified""); + + if (mng_info->adjoin == MagickFalse) + break; + } + } + + use_global_plte=MagickFalse; + all_images_are_gray=MagickFalse; +#ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED + need_local_plte=MagickTrue; +#endif + need_defi=MagickFalse; + need_matte=MagickFalse; + mng_info->framing_mode=1; + mng_info->old_framing_mode=1; + + if (write_mng) + if (image_info->page != (char *) NULL) + { + /* + Determine image bounding box. + */ + SetGeometry(image,&mng_info->page); + (void) ParseMetaGeometry(image_info->page,&mng_info->page.x, + &mng_info->page.y,&mng_info->page.width,&mng_info->page.height); + } + if (write_mng) + { + unsigned int + need_geom; + + unsigned short + red, + green, + blue; + + mng_info->page=image->page; + need_geom=MagickTrue; + if (mng_info->page.width || mng_info->page.height) + need_geom=MagickFalse; + /* + Check all the scenes. + */ + initial_delay=image->delay; + need_iterations=MagickFalse; + mng_info->equal_chrms=image->chromaticity.red_primary.x != 0.0; + mng_info->equal_physs=MagickTrue, + mng_info->equal_gammas=MagickTrue; + mng_info->equal_srgbs=MagickTrue; + mng_info->equal_backgrounds=MagickTrue; + image_count=0; +#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ + defined(PNG_MNG_FEATURES_SUPPORTED) + all_images_are_gray=MagickTrue; + mng_info->equal_palettes=MagickFalse; + need_local_plte=MagickFalse; +#endif + for (next_image=image; next_image != (Image *) NULL; ) + { + if (need_geom) + { + if ((next_image->columns+next_image->page.x) > mng_info->page.width) + mng_info->page.width=next_image->columns+next_image->page.x; + + if ((next_image->rows+next_image->page.y) > mng_info->page.height) + mng_info->page.height=next_image->rows+next_image->page.y; + } + + if (next_image->page.x || next_image->page.y) + need_defi=MagickTrue; + + if (next_image->matte) + need_matte=MagickTrue; + + if ((int) next_image->dispose >= BackgroundDispose) + if (next_image->matte || next_image->page.x || next_image->page.y || + ((next_image->columns < mng_info->page.width) && + (next_image->rows < mng_info->page.height))) + mng_info->need_fram=MagickTrue; + + if (next_image->iterations) + need_iterations=MagickTrue; + + final_delay=next_image->delay; + + if (final_delay != initial_delay || final_delay > 1UL* + next_image->ticks_per_second) + mng_info->need_fram=1; + +#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ + defined(PNG_MNG_FEATURES_SUPPORTED) + /* + check for global palette possibility. + */ + if (image->matte != MagickFalse) + need_local_plte=MagickTrue; + + if (need_local_plte == 0) + { + if (SetImageGray(image,&image->exception) == MagickFalse) + all_images_are_gray=MagickFalse; + mng_info->equal_palettes=PalettesAreEqual(image,next_image); + if (use_global_plte == 0) + use_global_plte=mng_info->equal_palettes; + need_local_plte=!mng_info->equal_palettes; + } +#endif + if (GetNextImageInList(next_image) != (Image *) NULL) + { + if (next_image->background_color.red != + next_image->next->background_color.red || + next_image->background_color.green != + next_image->next->background_color.green || + next_image->background_color.blue != + next_image->next->background_color.blue) + mng_info->equal_backgrounds=MagickFalse; + + if (next_image->gamma != next_image->next->gamma) + mng_info->equal_gammas=MagickFalse; + + if (next_image->rendering_intent != + next_image->next->rendering_intent) + mng_info->equal_srgbs=MagickFalse; + + if ((next_image->units != next_image->next->units) || + (next_image->x_resolution != next_image->next->x_resolution) || + (next_image->y_resolution != next_image->next->y_resolution)) + mng_info->equal_physs=MagickFalse; + + if (mng_info->equal_chrms) + { + if (next_image->chromaticity.red_primary.x != + next_image->next->chromaticity.red_primary.x || + next_image->chromaticity.red_primary.y != + next_image->next->chromaticity.red_primary.y || + next_image->chromaticity.green_primary.x != + next_image->next->chromaticity.green_primary.x || + next_image->chromaticity.green_primary.y != + next_image->next->chromaticity.green_primary.y || + next_image->chromaticity.blue_primary.x != + next_image->next->chromaticity.blue_primary.x || + next_image->chromaticity.blue_primary.y != + next_image->next->chromaticity.blue_primary.y || + next_image->chromaticity.white_point.x != + next_image->next->chromaticity.white_point.x || + next_image->chromaticity.white_point.y != + next_image->next->chromaticity.white_point.y) + mng_info->equal_chrms=MagickFalse; + } + } + image_count++; + next_image=GetNextImageInList(next_image); + } + if (image_count < 2) + { + mng_info->equal_backgrounds=MagickFalse; + mng_info->equal_chrms=MagickFalse; + mng_info->equal_gammas=MagickFalse; + mng_info->equal_srgbs=MagickFalse; + mng_info->equal_physs=MagickFalse; + use_global_plte=MagickFalse; +#ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED + need_local_plte=MagickTrue; +#endif + need_iterations=MagickFalse; + } + + if (mng_info->need_fram == MagickFalse) + { + /* + Only certain framing rates 100/n are exactly representable without + the FRAM chunk but we'll allow some slop in VLC files + */ + if (final_delay == 0) + { + if (need_iterations != MagickFalse) + { + /* + It's probably a GIF with loop; don't run it *too* fast. + */ + if (mng_info->adjoin) + { + final_delay=10; + (void) ThrowMagickException(&image->exception, + GetMagickModule(),CoderWarning, + ""input has zero delay between all frames; assuming"", + "" 10 cs `%s'"",""""); + } + } + else + mng_info->ticks_per_second=0; + } + if (final_delay != 0) + mng_info->ticks_per_second=(png_uint_32) + (image->ticks_per_second/final_delay); + if (final_delay > 50) + mng_info->ticks_per_second=2; + + if (final_delay > 75) + mng_info->ticks_per_second=1; + + if (final_delay > 125) + mng_info->need_fram=MagickTrue; + + if (need_defi && final_delay > 2 && (final_delay != 4) && + (final_delay != 5) && (final_delay != 10) && (final_delay != 20) && + (final_delay != 25) && (final_delay != 50) && + (final_delay != (size_t) image->ticks_per_second)) + mng_info->need_fram=MagickTrue; /* make it exact; cannot be VLC */ + } + + if (mng_info->need_fram != MagickFalse) + mng_info->ticks_per_second=1UL*image->ticks_per_second; + /* + If pseudocolor, we should also check to see if all the + palettes are identical and write a global PLTE if they are. + ../glennrp Feb 99. + */ + /* + Write the MNG version 1.0 signature and MHDR chunk. + */ + (void) WriteBlob(image,8,(const unsigned char *) ""\212MNG\r\n\032\n""); + (void) WriteBlobMSBULong(image,28L); /* chunk data length=28 */ + PNGType(chunk,mng_MHDR); + LogPNGChunk(logging,mng_MHDR,28L); + PNGLong(chunk+4,(png_uint_32) mng_info->page.width); + PNGLong(chunk+8,(png_uint_32) mng_info->page.height); + PNGLong(chunk+12,mng_info->ticks_per_second); + PNGLong(chunk+16,0L); /* layer count=unknown */ + PNGLong(chunk+20,0L); /* frame count=unknown */ + PNGLong(chunk+24,0L); /* play time=unknown */ + if (write_jng) + { + if (need_matte) + { + if (need_defi || mng_info->need_fram || use_global_plte) + PNGLong(chunk+28,27L); /* simplicity=LC+JNG */ + + else + PNGLong(chunk+28,25L); /* simplicity=VLC+JNG */ + } + + else + { + if (need_defi || mng_info->need_fram || use_global_plte) + PNGLong(chunk+28,19L); /* simplicity=LC+JNG, no transparency */ + + else + PNGLong(chunk+28,17L); /* simplicity=VLC+JNG, no transparency */ + } + } + + else + { + if (need_matte) + { + if (need_defi || mng_info->need_fram || use_global_plte) + PNGLong(chunk+28,11L); /* simplicity=LC */ + + else + PNGLong(chunk+28,9L); /* simplicity=VLC */ + } + + else + { + if (need_defi || mng_info->need_fram || use_global_plte) + PNGLong(chunk+28,3L); /* simplicity=LC, no transparency */ + + else + PNGLong(chunk+28,1L); /* simplicity=VLC, no transparency */ + } + } + (void) WriteBlob(image,32,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,32)); + option=GetImageOption(image_info,""mng:need-cacheoff""); + if (option != (const char *) NULL) + { + size_t + length; + + /* + Write ""nEED CACHEOFF"" to turn playback caching off for streaming MNG. + */ + PNGType(chunk,mng_nEED); + length=CopyMagickString((char *) chunk+4,""CACHEOFF"",20); + (void) WriteBlobMSBULong(image,(size_t) length); + LogPNGChunk(logging,mng_nEED,(size_t) length); + length+=4; + (void) WriteBlob(image,length,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) length)); + } + if ((GetPreviousImageInList(image) == (Image *) NULL) && + (GetNextImageInList(image) != (Image *) NULL) && + (image->iterations != 1)) + { + /* + Write MNG TERM chunk + */ + (void) WriteBlobMSBULong(image,10L); /* data length=10 */ + PNGType(chunk,mng_TERM); + LogPNGChunk(logging,mng_TERM,10L); + chunk[4]=3; /* repeat animation */ + chunk[5]=0; /* show last frame when done */ + PNGLong(chunk+6,(png_uint_32) (mng_info->ticks_per_second* + final_delay/MagickMax(image->ticks_per_second,1))); + + if (image->iterations == 0) + PNGLong(chunk+10,PNG_UINT_31_MAX); + + else + PNGLong(chunk+10,(png_uint_32) image->iterations); + + if (logging != MagickFalse) + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" TERM delay: %.20g"",(double) (mng_info->ticks_per_second* + final_delay/MagickMax(image->ticks_per_second,1))); + + if (image->iterations == 0) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" TERM iterations: %.20g"",(double) PNG_UINT_31_MAX); + + else + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Image iterations: %.20g"",(double) image->iterations); + } + (void) WriteBlob(image,14,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,14)); + } + /* + To do: check for cHRM+gAMA == sRGB, and write sRGB instead. + */ + if ((image->colorspace == sRGBColorspace || image->rendering_intent) && + mng_info->equal_srgbs) + { + /* + Write MNG sRGB chunk + */ + (void) WriteBlobMSBULong(image,1L); + PNGType(chunk,mng_sRGB); + LogPNGChunk(logging,mng_sRGB,1L); + + if (image->rendering_intent != UndefinedIntent) + chunk[4]=(unsigned char) + Magick_RenderingIntent_to_PNG_RenderingIntent( + (image->rendering_intent)); + + else + chunk[4]=(unsigned char) + Magick_RenderingIntent_to_PNG_RenderingIntent( + (PerceptualIntent)); + + (void) WriteBlob(image,5,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); + mng_info->have_write_global_srgb=MagickTrue; + } + + else + { + if (image->gamma && mng_info->equal_gammas) + { + /* + Write MNG gAMA chunk + */ + (void) WriteBlobMSBULong(image,4L); + PNGType(chunk,mng_gAMA); + LogPNGChunk(logging,mng_gAMA,4L); + PNGLong(chunk+4,(png_uint_32) (100000*image->gamma+0.5)); + (void) WriteBlob(image,8,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,8)); + mng_info->have_write_global_gama=MagickTrue; + } + if (mng_info->equal_chrms) + { + PrimaryInfo + primary; + + /* + Write MNG cHRM chunk + */ + (void) WriteBlobMSBULong(image,32L); + PNGType(chunk,mng_cHRM); + LogPNGChunk(logging,mng_cHRM,32L); + primary=image->chromaticity.white_point; + PNGLong(chunk+4,(png_uint_32) (100000*primary.x+0.5)); + PNGLong(chunk+8,(png_uint_32) (100000*primary.y+0.5)); + primary=image->chromaticity.red_primary; + PNGLong(chunk+12,(png_uint_32) (100000*primary.x+0.5)); + PNGLong(chunk+16,(png_uint_32) (100000*primary.y+0.5)); + primary=image->chromaticity.green_primary; + PNGLong(chunk+20,(png_uint_32) (100000*primary.x+0.5)); + PNGLong(chunk+24,(png_uint_32) (100000*primary.y+0.5)); + primary=image->chromaticity.blue_primary; + PNGLong(chunk+28,(png_uint_32) (100000*primary.x+0.5)); + PNGLong(chunk+32,(png_uint_32) (100000*primary.y+0.5)); + (void) WriteBlob(image,36,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,36)); + mng_info->have_write_global_chrm=MagickTrue; + } + } + if (image->x_resolution && image->y_resolution && mng_info->equal_physs) + { + /* + Write MNG pHYs chunk + */ + (void) WriteBlobMSBULong(image,9L); + PNGType(chunk,mng_pHYs); + LogPNGChunk(logging,mng_pHYs,9L); + + if (image->units == PixelsPerInchResolution) + { + PNGLong(chunk+4,(png_uint_32) + (image->x_resolution*100.0/2.54+0.5)); + + PNGLong(chunk+8,(png_uint_32) + (image->y_resolution*100.0/2.54+0.5)); + + chunk[12]=1; + } + + else + { + if (image->units == PixelsPerCentimeterResolution) + { + PNGLong(chunk+4,(png_uint_32) + (image->x_resolution*100.0+0.5)); + + PNGLong(chunk+8,(png_uint_32) + (image->y_resolution*100.0+0.5)); + + chunk[12]=1; + } + + else + { + PNGLong(chunk+4,(png_uint_32) (image->x_resolution+0.5)); + PNGLong(chunk+8,(png_uint_32) (image->y_resolution+0.5)); + chunk[12]=0; + } + } + (void) WriteBlob(image,13,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,13)); + } + /* + Write MNG BACK chunk and global bKGD chunk, if the image is transparent + or does not cover the entire frame. + */ + if (write_mng && (image->matte || image->page.x > 0 || + image->page.y > 0 || (image->page.width && + (image->page.width+image->page.x < mng_info->page.width)) + || (image->page.height && (image->page.height+image->page.y + < mng_info->page.height)))) + { + (void) WriteBlobMSBULong(image,6L); + PNGType(chunk,mng_BACK); + LogPNGChunk(logging,mng_BACK,6L); + red=ScaleQuantumToShort(image->background_color.red); + green=ScaleQuantumToShort(image->background_color.green); + blue=ScaleQuantumToShort(image->background_color.blue); + PNGShort(chunk+4,red); + PNGShort(chunk+6,green); + PNGShort(chunk+8,blue); + (void) WriteBlob(image,10,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,10)); + if (mng_info->equal_backgrounds) + { + (void) WriteBlobMSBULong(image,6L); + PNGType(chunk,mng_bKGD); + LogPNGChunk(logging,mng_bKGD,6L); + (void) WriteBlob(image,10,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,10)); + } + } + +#ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED + if ((need_local_plte == MagickFalse) && + (image->storage_class == PseudoClass) && + (all_images_are_gray == MagickFalse)) + { + size_t + data_length; + + /* + Write MNG PLTE chunk + */ + data_length=3*image->colors; + (void) WriteBlobMSBULong(image,data_length); + PNGType(chunk,mng_PLTE); + LogPNGChunk(logging,mng_PLTE,data_length); + + for (i=0; i < (ssize_t) image->colors; i++) + { + chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red) & 0xff; + chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green) & 0xff; + chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue) & 0xff; + } + + (void) WriteBlob(image,data_length+4,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,(uInt) (data_length+4))); + mng_info->have_write_global_plte=MagickTrue; + } +#endif + } + scene=0; + mng_info->delay=0; +#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ + defined(PNG_MNG_FEATURES_SUPPORTED) + mng_info->equal_palettes=MagickFalse; +#endif + imageListLength=GetImageListLength(image); + do + { + if (mng_info->adjoin) + { +#if defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED) || \ + defined(PNG_MNG_FEATURES_SUPPORTED) + /* + If we aren't using a global palette for the entire MNG, check to + see if we can use one for two or more consecutive images. + */ + if (need_local_plte && use_global_plte && !all_images_are_gray) + { + if (mng_info->IsPalette) + { + /* + When equal_palettes is true, this image has the same palette + as the previous PseudoClass image + */ + mng_info->have_write_global_plte=mng_info->equal_palettes; + mng_info->equal_palettes=PalettesAreEqual(image,image->next); + if (mng_info->equal_palettes && !mng_info->have_write_global_plte) + { + /* + Write MNG PLTE chunk + */ + size_t + data_length; + + data_length=3*image->colors; + (void) WriteBlobMSBULong(image,data_length); + PNGType(chunk,mng_PLTE); + LogPNGChunk(logging,mng_PLTE,data_length); + + for (i=0; i < (ssize_t) image->colors; i++) + { + chunk[4+i*3]=ScaleQuantumToChar(image->colormap[i].red); + chunk[5+i*3]=ScaleQuantumToChar(image->colormap[i].green); + chunk[6+i*3]=ScaleQuantumToChar(image->colormap[i].blue); + } + + (void) WriteBlob(image,data_length+4,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk, + (uInt) (data_length+4))); + mng_info->have_write_global_plte=MagickTrue; + } + } + else + mng_info->have_write_global_plte=MagickFalse; + } +#endif + if (need_defi) + { + ssize_t + previous_x, + previous_y; + + if (scene != 0) + { + previous_x=mng_info->page.x; + previous_y=mng_info->page.y; + } + else + { + previous_x=0; + previous_y=0; + } + mng_info->page=image->page; + if ((mng_info->page.x != previous_x) || + (mng_info->page.y != previous_y)) + { + (void) WriteBlobMSBULong(image,12L); /* data length=12 */ + PNGType(chunk,mng_DEFI); + LogPNGChunk(logging,mng_DEFI,12L); + chunk[4]=0; /* object 0 MSB */ + chunk[5]=0; /* object 0 LSB */ + chunk[6]=0; /* visible */ + chunk[7]=0; /* abstract */ + PNGLong(chunk+8,(png_uint_32) mng_info->page.x); + PNGLong(chunk+12,(png_uint_32) mng_info->page.y); + (void) WriteBlob(image,16,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,16)); + } + } + } + + mng_info->write_mng=write_mng; + + if ((int) image->dispose >= 3) + mng_info->framing_mode=3; + + if (mng_info->need_fram && mng_info->adjoin && + ((image->delay != mng_info->delay) || + (mng_info->framing_mode != mng_info->old_framing_mode))) + { + if (image->delay == mng_info->delay) + { + /* + Write a MNG FRAM chunk with the new framing mode. + */ + (void) WriteBlobMSBULong(image,1L); /* data length=1 */ + PNGType(chunk,mng_FRAM); + LogPNGChunk(logging,mng_FRAM,1L); + chunk[4]=(unsigned char) mng_info->framing_mode; + (void) WriteBlob(image,5,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,5)); + } + else + { + /* + Write a MNG FRAM chunk with the delay. + */ + (void) WriteBlobMSBULong(image,10L); /* data length=10 */ + PNGType(chunk,mng_FRAM); + LogPNGChunk(logging,mng_FRAM,10L); + chunk[4]=(unsigned char) mng_info->framing_mode; + chunk[5]=0; /* frame name separator (no name) */ + chunk[6]=2; /* flag for changing default delay */ + chunk[7]=0; /* flag for changing frame timeout */ + chunk[8]=0; /* flag for changing frame clipping */ + chunk[9]=0; /* flag for changing frame sync_id */ + PNGLong(chunk+10,(png_uint_32) + ((mng_info->ticks_per_second* + image->delay)/MagickMax(image->ticks_per_second,1))); + (void) WriteBlob(image,14,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,14)); + mng_info->delay=(png_uint_32) image->delay; + } + mng_info->old_framing_mode=mng_info->framing_mode; + } + +#if defined(JNG_SUPPORTED) + if (image_info->compression == JPEGCompression) + { + ImageInfo + *write_info; + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Writing JNG object.""); + /* To do: specify the desired alpha compression method. */ + write_info=CloneImageInfo(image_info); + write_info->compression=UndefinedCompression; + status=WriteOneJNGImage(mng_info,write_info,image); + write_info=DestroyImageInfo(write_info); + } + else +#endif + { + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Writing PNG object.""); + + mng_info->need_blob = MagickFalse; + mng_info->ping_preserve_colormap = MagickFalse; + + /* We don't want any ancillary chunks written */ + mng_info->ping_exclude_bKGD=MagickTrue; + mng_info->ping_exclude_caNv=MagickTrue; + mng_info->ping_exclude_cHRM=MagickTrue; + mng_info->ping_exclude_date=MagickTrue; + mng_info->ping_exclude_EXIF=MagickTrue; + mng_info->ping_exclude_eXIf=MagickTrue; + mng_info->ping_exclude_gAMA=MagickTrue; + mng_info->ping_exclude_iCCP=MagickTrue; + /* mng_info->ping_exclude_iTXt=MagickTrue; */ + mng_info->ping_exclude_oFFs=MagickTrue; + mng_info->ping_exclude_pHYs=MagickTrue; + mng_info->ping_exclude_sRGB=MagickTrue; + mng_info->ping_exclude_tEXt=MagickTrue; + mng_info->ping_exclude_tRNS=MagickTrue; + mng_info->ping_exclude_zCCP=MagickTrue; + mng_info->ping_exclude_zTXt=MagickTrue; + + status=WriteOnePNGImage(mng_info,image_info,image); + } + + if (status == MagickFalse) + { + mng_info=MngInfoFreeStruct(mng_info); + (void) CloseBlob(image); + return(MagickFalse); + } + (void) CatchImageException(image); + if (GetNextImageInList(image) == (Image *) NULL) + break; + image=SyncNextImageInList(image); + status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); + + if (status == MagickFalse) + break; + + } while (mng_info->adjoin); + + if (write_mng) + { + while (GetPreviousImageInList(image) != (Image *) NULL) + image=GetPreviousImageInList(image); + /* + Write the MEND chunk. + */ + (void) WriteBlobMSBULong(image,0x00000000L); + PNGType(chunk,mng_MEND); + LogPNGChunk(logging,mng_MEND,0L); + (void) WriteBlob(image,4,chunk); + (void) WriteBlobMSBULong(image,crc32(0,chunk,4)); + } + /* + Relinquish resources. + */ + (void) CloseBlob(image); + mng_info=MngInfoFreeStruct(mng_info); + + if (logging != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(),""exit WriteMNGImage()""); + + return(MagickTrue); +} +","@@ -4584,7 +4584,7 @@ static Image *ReadOneJNGImage(MngInfo *mng_info, + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "" Copying JDAT chunk data to color_blob.""); + +- if (length != 0) ++ if ((length != 0) && (color_image != (Image *) NULL)) + { + (void) WriteBlob(color_image,length,chunk); + chunk=(unsigned char *) RelinquishMagickMemory(chunk);",7949,8280,11000 diff --git a/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_8192_to_11000.pkl b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_8192_to_11000.pkl new file mode 100644 index 0000000000000000000000000000000000000000..72f732044f96371d702a4eaad1e517c0966e8196 --- /dev/null +++ b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_8192_to_11000.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7f686fcde13395ae7007ea7d907077079e759c0ff8770571e75d493274057d82 +size 553687 diff --git a/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_stats.json b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_stats.json new file mode 100644 index 0000000000000000000000000000000000000000..0a9071a275b8412c32fbc7d9bd0b7fd34459073d --- /dev/null +++ b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_stats.json @@ -0,0 +1,47 @@ +{ + "total": 10000, + "processed": 9998, + "skipped": 2, + "categories": { + "under_512": { + "count": 6438, + "percentage": 64.38, + "max_tokens_setting": 512 + }, + "512_to_1024": { + "count": 2759, + "percentage": 27.59, + "max_tokens_setting": 1024 + }, + "1024_to_2048": { + "count": 588, + "percentage": 5.88, + "max_tokens_setting": 2048 + }, + "2048_to_4096": { + "count": 152, + "percentage": 1.52, + "max_tokens_setting": 4096 + }, + "4096_to_6144": { + "count": 41, + "percentage": 0.41, + "max_tokens_setting": 6144 + }, + "6144_to_8192": { + "count": 10, + "percentage": 0.1, + "max_tokens_setting": 8192 + }, + "8192_to_11000": { + "count": 8, + "percentage": 0.08, + "max_tokens_setting": 11000 + }, + "11000_to_15000": { + "count": 2, + "percentage": 0.02, + "max_tokens_setting": 15000 + } + } +} \ No newline at end of file diff --git a/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_under_512.csv b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_under_512.csv new file mode 100644 index 0000000000000000000000000000000000000000..a7d468d64300efa04c6693b1bff89cca38e8ca43 --- /dev/null +++ b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_under_512.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a1110280e244e2d13ab223d9e9ee0a8b78d54ed821b1b04f9fc39d8de0048d5f +size 25290965 diff --git a/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_under_512.pkl b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_under_512.pkl new file mode 100644 index 0000000000000000000000000000000000000000..c833113fdf533d3dbea79660126baae047728e22 --- /dev/null +++ b/categorized_datasets_for_R1-Distill-Qwen-7B/BigVul_Sample/BigVul_Sample_under_512.pkl @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:55935fc6db63b38d4816979ef460d23436392bf380d505c5f4506f1957650588 +size 10126584 diff --git a/categorized_datasets_for_R1-Distill-Qwen-7B/DiverseVul_Sample/DiverseVul_Sample_1024_to_2048.jsonl b/categorized_datasets_for_R1-Distill-Qwen-7B/DiverseVul_Sample/DiverseVul_Sample_1024_to_2048.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c91b45a404514efcd16b8051ddf4133591a022b9 --- /dev/null +++ b/categorized_datasets_for_R1-Distill-Qwen-7B/DiverseVul_Sample/DiverseVul_Sample_1024_to_2048.jsonl @@ -0,0 +1,793 @@ +{"idx":315835,"func":"static void phar_mung_server_vars(char *fname, char *entry, int entry_len, char *basename, int request_uri_len TSRMLS_DC) \/* {{{ *\/\n{\n\tHashTable *_SERVER;\n\tzval **stuff;\n\tchar *path_info;\n\tint basename_len = strlen(basename);\n\tint code;\n\tzval *temp;\n\n\t\/* \"tweak\" $_SERVER variables requested in earlier call to Phar::mungServer() *\/\n\tif (!PG(http_globals)[TRACK_VARS_SERVER]) {\n\t\treturn;\n\t}\n\n\t_SERVER = Z_ARRVAL_P(PG(http_globals)[TRACK_VARS_SERVER]);\n\n\t\/* PATH_INFO and PATH_TRANSLATED should always be munged *\/\n\tif (SUCCESS == zend_hash_find(_SERVER, \"PATH_INFO\", sizeof(\"PATH_INFO\"), (void **) &stuff)) {\n\t\tpath_info = Z_STRVAL_PP(stuff);\n\t\tcode = Z_STRLEN_PP(stuff);\n\n\t\tif (Z_STRLEN_PP(stuff) > entry_len && !memcmp(Z_STRVAL_PP(stuff), entry, entry_len)) {\n\t\t\tZVAL_STRINGL(*stuff, Z_STRVAL_PP(stuff) + entry_len, request_uri_len, 1);\n\n\t\t\tMAKE_STD_ZVAL(temp);\n\t\t\tZVAL_STRINGL(temp, path_info, code, 0);\n\n\t\t\tzend_hash_update(_SERVER, \"PHAR_PATH_INFO\", sizeof(\"PHAR_PATH_INFO\"), &temp, sizeof(zval **), NULL);\n\t\t}\n\t}\n\n\tif (SUCCESS == zend_hash_find(_SERVER, \"PATH_TRANSLATED\", sizeof(\"PATH_TRANSLATED\"), (void **) &stuff)) {\n\t\tpath_info = Z_STRVAL_PP(stuff);\n\t\tcode = Z_STRLEN_PP(stuff);\n\t\tZ_STRLEN_PP(stuff) = spprintf(&(Z_STRVAL_PP(stuff)), 4096, \"phar:\/\/%s%s\", fname, entry);\n\n\t\tMAKE_STD_ZVAL(temp);\n\t\tZVAL_STRINGL(temp, path_info, code, 0);\n\n\t\tzend_hash_update(_SERVER, \"PHAR_PATH_TRANSLATED\", sizeof(\"PHAR_PATH_TRANSLATED\"), (void *) &temp, sizeof(zval **), NULL);\n\t}\n\n\tif (!PHAR_GLOBALS->phar_SERVER_mung_list) {\n\t\treturn;\n\t}\n\n\tif (PHAR_GLOBALS->phar_SERVER_mung_list & PHAR_MUNG_REQUEST_URI) {\n\t\tif (SUCCESS == zend_hash_find(_SERVER, \"REQUEST_URI\", sizeof(\"REQUEST_URI\"), (void **) &stuff)) {\n\t\t\tpath_info = Z_STRVAL_PP(stuff);\n\t\t\tcode = Z_STRLEN_PP(stuff);\n\n\t\t\tif (Z_STRLEN_PP(stuff) > basename_len && !memcmp(Z_STRVAL_PP(stuff), basename, basename_len)) {\n\t\t\t\tZVAL_STRINGL(*stuff, Z_STRVAL_PP(stuff) + basename_len, Z_STRLEN_PP(stuff) - basename_len, 1);\n\n\t\t\t\tMAKE_STD_ZVAL(temp);\n\t\t\t\tZVAL_STRINGL(temp, path_info, code, 0);\n\n\t\t\t\tzend_hash_update(_SERVER, \"PHAR_REQUEST_URI\", sizeof(\"PHAR_REQUEST_URI\"), (void *) &temp, sizeof(zval **), NULL);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (PHAR_GLOBALS->phar_SERVER_mung_list & PHAR_MUNG_PHP_SELF) {\n\t\tif (SUCCESS == zend_hash_find(_SERVER, \"PHP_SELF\", sizeof(\"PHP_SELF\"), (void **) &stuff)) {\n\t\t\tpath_info = Z_STRVAL_PP(stuff);\n\t\t\tcode = Z_STRLEN_PP(stuff);\n\n\t\t\tif (Z_STRLEN_PP(stuff) > basename_len && !memcmp(Z_STRVAL_PP(stuff), basename, basename_len)) {\n\t\t\t\tZVAL_STRINGL(*stuff, Z_STRVAL_PP(stuff) + basename_len, Z_STRLEN_PP(stuff) - basename_len, 1);\n\n\t\t\t\tMAKE_STD_ZVAL(temp);\n\t\t\t\tZVAL_STRINGL(temp, path_info, code, 0);\n\n\t\t\t\tzend_hash_update(_SERVER, \"PHAR_PHP_SELF\", sizeof(\"PHAR_PHP_SELF\"), (void *) &temp, sizeof(zval **), NULL);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (PHAR_GLOBALS->phar_SERVER_mung_list & PHAR_MUNG_SCRIPT_NAME) {\n\t\tif (SUCCESS == zend_hash_find(_SERVER, \"SCRIPT_NAME\", sizeof(\"SCRIPT_NAME\"), (void **) &stuff)) {\n\t\t\tpath_info = Z_STRVAL_PP(stuff);\n\t\t\tcode = Z_STRLEN_PP(stuff);\n\t\t\tZVAL_STRINGL(*stuff, entry, entry_len, 1);\n\n\t\t\tMAKE_STD_ZVAL(temp);\n\t\t\tZVAL_STRINGL(temp, path_info, code, 0);\n\n\t\t\tzend_hash_update(_SERVER, \"PHAR_SCRIPT_NAME\", sizeof(\"PHAR_SCRIPT_NAME\"), (void *) &temp, sizeof(zval **), NULL);\n\t\t}\n\t}\n\n\tif (PHAR_GLOBALS->phar_SERVER_mung_list & PHAR_MUNG_SCRIPT_FILENAME) {\n\t\tif (SUCCESS == zend_hash_find(_SERVER, \"SCRIPT_FILENAME\", sizeof(\"SCRIPT_FILENAME\"), (void **) &stuff)) {\n\t\t\tpath_info = Z_STRVAL_PP(stuff);\n\t\t\tcode = Z_STRLEN_PP(stuff);\n\t\t\tZ_STRLEN_PP(stuff) = spprintf(&(Z_STRVAL_PP(stuff)), 4096, \"phar:\/\/%s%s\", fname, entry);\n\n\t\t\tMAKE_STD_ZVAL(temp);\n\t\t\tZVAL_STRINGL(temp, path_info, code, 0);\n\n\t\t\tzend_hash_update(_SERVER, \"PHAR_SCRIPT_FILENAME\", sizeof(\"PHAR_SCRIPT_FILENAME\"), (void *) &temp, sizeof(zval **), NULL);\n\t\t}\n\t}\n}\n\/* }}} *\/\n","target":0,"code_token_length":1178,"total_token_length":1509,"max_tokens_setting":2048} +{"idx":338003,"func":"static int dts_probe(AVProbeData *p)\n\n{\n\n const uint8_t *buf, *bufp;\n\n uint32_t state = -1;\n\n int markers[4*16] = {0};\n\n int exss_markers = 0, exss_nextpos = 0;\n\n int sum, max, pos, i;\n\n int64_t diff = 0;\n\n uint8_t hdr[12 + AV_INPUT_BUFFER_PADDING_SIZE] = { 0 };\n\n\n\n for (pos = FFMIN(4096, p->buf_size); pos < p->buf_size - 2; pos += 2) {\n\n int marker, sample_blocks, sample_rate, sr_code, framesize;\n\n int lfe, wide_hdr, hdr_size;\n\n GetBitContext gb;\n\n\n\n bufp = buf = p->buf + pos;\n\n state = (state << 16) | bytestream_get_be16(&bufp);\n\n\n\n if (pos >= 4)\n\n diff += FFABS(((int16_t)AV_RL16(buf)) - (int16_t)AV_RL16(buf-4));\n\n\n\n \/* extension substream (EXSS) *\/\n\n if (state == DCA_SYNCWORD_SUBSTREAM) {\n\n if (pos < exss_nextpos)\n\n continue;\n\n\n\n init_get_bits(&gb, buf - 2, 96);\n\n skip_bits_long(&gb, 42);\n\n\n\n wide_hdr = get_bits1(&gb);\n\n hdr_size = get_bits(&gb, 8 + 4 * wide_hdr) + 1;\n\n framesize = get_bits(&gb, 16 + 4 * wide_hdr) + 1;\n\n if (hdr_size & 3 || framesize & 3)\n\n continue;\n\n if (hdr_size < 16 || framesize < hdr_size)\n\n continue;\n\n if (pos - 2 + hdr_size > p->buf_size)\n\n continue;\n\n if (av_crc(av_crc_get_table(AV_CRC_16_CCITT), 0xffff, buf + 3, hdr_size - 5))\n\n continue;\n\n\n\n if (pos == exss_nextpos)\n\n exss_markers++;\n\n else\n\n exss_markers = FFMAX(1, exss_markers - 1);\n\n exss_nextpos = pos + framesize;\n\n continue;\n\n }\n\n\n\n \/* regular bitstream *\/\n\n if (state == DCA_SYNCWORD_CORE_BE &&\n\n (bytestream_get_be16(&bufp) & 0xFC00) == 0xFC00)\n\n marker = 0;\n\n else if (state == DCA_SYNCWORD_CORE_LE &&\n\n (bytestream_get_be16(&bufp) & 0x00FC) == 0x00FC)\n\n marker = 1;\n\n\n\n \/* 14 bits big-endian bitstream *\/\n\n else if (state == DCA_SYNCWORD_CORE_14B_BE &&\n\n (bytestream_get_be16(&bufp) & 0xFFF0) == 0x07F0)\n\n marker = 2;\n\n\n\n \/* 14 bits little-endian bitstream *\/\n\n else if (state == DCA_SYNCWORD_CORE_14B_LE &&\n\n (bytestream_get_be16(&bufp) & 0xF0FF) == 0xF007)\n\n marker = 3;\n\n else\n\n continue;\n\n\n\n if (avpriv_dca_convert_bitstream(buf-2, 12, hdr, 12) < 0)\n\n continue;\n\n\n\n init_get_bits(&gb, hdr, 96);\n\n skip_bits_long(&gb, 39);\n\n\n\n sample_blocks = get_bits(&gb, 7) + 1;\n\n if (sample_blocks < 8)\n\n continue;\n\n\n\n framesize = get_bits(&gb, 14) + 1;\n\n if (framesize < 95)\n\n continue;\n\n\n\n skip_bits(&gb, 6);\n\n sr_code = get_bits(&gb, 4);\n\n sample_rate = avpriv_dca_sample_rates[sr_code];\n\n if (sample_rate == 0)\n\n continue;\n\n\n\n get_bits(&gb, 5);\n\n if (get_bits(&gb, 1))\n\n continue;\n\n\n\n skip_bits_long(&gb, 9);\n\n lfe = get_bits(&gb, 2);\n\n if (lfe > 2)\n\n continue;\n\n\n\n marker += 4* sr_code;\n\n\n\n markers[marker] ++;\n\n }\n\n\n\n if (exss_markers > 3)\n\n return AVPROBE_SCORE_EXTENSION + 1;\n\n\n\n sum = max = 0;\n\n for (i=0; i 3 && p->buf_size \/ markers[max] < 32*1024 &&\n\n markers[max] * 4 > sum * 3 &&\n\n diff \/ p->buf_size > 200)\n\n return AVPROBE_SCORE_EXTENSION + 1;\n\n\n\n return 0;\n\n}\n","target":0,"code_token_length":1130,"total_token_length":1461,"max_tokens_setting":2048} +{"idx":288589,"func":"IN_PROC_BROWSER_TEST_F ( SitePerProcessInteractiveBrowserTest , SequentialFocusNavigation ) {\n GURL main_url ( embedded_test_server ( ) -> GetURL ( \"a.com\" , \"\/cross_site_iframe_factory.html?a(b,c)\" ) ) ;\n ui_test_utils : : NavigateToURL ( browser ( ) , main_url ) ;\n content : : WebContents * web_contents = browser ( ) -> tab_strip_model ( ) -> GetActiveWebContents ( ) ;\n content : : RenderFrameHost * main_frame = web_contents -> GetMainFrame ( ) ;\n content : : RenderFrameHost * child1 = ChildFrameAt ( main_frame , 0 ) ;\n ASSERT_NE ( nullptr , child1 ) ;\n content : : RenderFrameHost * child2 = ChildFrameAt ( main_frame , 1 ) ;\n ASSERT_NE ( nullptr , child2 ) ;\n EXPECT_TRUE ( ExecuteScript ( main_frame , \"window.name = 'root';\n\" ) ) ;\n EXPECT_TRUE ( ExecuteScript ( child1 , \"window.name = 'child1';\n\" ) ) ;\n EXPECT_TRUE ( ExecuteScript ( child2 , \"window.name = 'child2';\n\" ) ) ;\n std : : string script = \"function onFocus(e) {\n\" \" domAutomationController.setAutomationId(0);\n\" \" domAutomationController.send(window.name + '-focused-' + e.target.id);\n\" \"}\n\" \"var input1 = document.createElement('input');\n\" \"input1.id = 'input1';\n\" \"var input2 = document.createElement('input');\n\" \"input2.id = 'input2';\n\" \"document.body.insertBefore(input1, document.body.firstChild);\n\" \"document.body.appendChild(input2);\n\" \"input1.addEventListener('focus', onFocus, false);\n\" \"input2.addEventListener('focus', onFocus, false);\n\" ;\n EXPECT_TRUE ( ExecuteScript ( main_frame , script ) ) ;\n EXPECT_TRUE ( ExecuteScript ( child1 , script ) ) ;\n EXPECT_TRUE ( ExecuteScript ( child2 , script ) ) ;\n auto press_tab_and_wait_for_message = [ web_contents ] ( bool reverse ) {\n content : : DOMMessageQueue msg_queue ;\n std : : string reply ;\n SimulateKeyPress ( web_contents , ui : : DomKey : : TAB , ui : : DomCode : : TAB , ui : : VKEY_TAB , false , reverse , false , false ) ;\n EXPECT_TRUE ( msg_queue . WaitForMessage ( & reply ) ) ;\n return reply ;\n }\n ;\n EXPECT_EQ ( \"\\\"root-focused-input1\\\"\" , press_tab_and_wait_for_message ( false ) ) ;\n EXPECT_EQ ( main_frame , web_contents -> GetFocusedFrame ( ) ) ;\n EXPECT_EQ ( \"\\\"child1-focused-input1\\\"\" , press_tab_and_wait_for_message ( false ) ) ;\n EXPECT_EQ ( child1 , web_contents -> GetFocusedFrame ( ) ) ;\n EXPECT_EQ ( \"\\\"child1-focused-input2\\\"\" , press_tab_and_wait_for_message ( false ) ) ;\n EXPECT_EQ ( \"\\\"child2-focused-input1\\\"\" , press_tab_and_wait_for_message ( false ) ) ;\n EXPECT_EQ ( child2 , web_contents -> GetFocusedFrame ( ) ) ;\n EXPECT_EQ ( \"\\\"child2-focused-input2\\\"\" , press_tab_and_wait_for_message ( false ) ) ;\n EXPECT_EQ ( \"\\\"root-focused-input2\\\"\" , press_tab_and_wait_for_message ( false ) ) ;\n EXPECT_EQ ( main_frame , web_contents -> GetFocusedFrame ( ) ) ;\n EXPECT_EQ ( \"\\\"child2-focused-input2\\\"\" , press_tab_and_wait_for_message ( true ) ) ;\n EXPECT_EQ ( child2 , web_contents -> GetFocusedFrame ( ) ) ;\n EXPECT_EQ ( \"\\\"child2-focused-input1\\\"\" , press_tab_and_wait_for_message ( true ) ) ;\n EXPECT_EQ ( \"\\\"child1-focused-input2\\\"\" , press_tab_and_wait_for_message ( true ) ) ;\n EXPECT_EQ ( child1 , web_contents -> GetFocusedFrame ( ) ) ;\n EXPECT_EQ ( \"\\\"child1-focused-input1\\\"\" , press_tab_and_wait_for_message ( true ) ) ;\n EXPECT_EQ ( \"\\\"root-focused-input1\\\"\" , press_tab_and_wait_for_message ( true ) ) ;\n EXPECT_EQ ( main_frame , web_contents -> GetFocusedFrame ( ) ) ;\n }","target":0,"code_token_length":847,"total_token_length":1178,"max_tokens_setting":2048} +{"idx":367937,"func":"int pgmraw_to_fits (char *pgmfile, char *fitsfile)\n\n{FITS_FILE *fitsout = NULL;\n FILE *pgmin = NULL;\n FITS_HDU_LIST *hdu;\n char buffer[1024];\n int width, height, numbytes, maxbytes;\n int retval = -1;\n\n fitsout = fits_open (fitsfile, \"w\");\n if (fitsout == NULL) goto err_return;\n\n pgmin = g_fopen (pgmfile, \"r\");\n if (pgmin == NULL) goto err_return;\n\n \/* Read signature of PGM file *\/\n if (fgets (buffer, sizeof (buffer), pgmin) == NULL) goto err_return;\n if ((buffer[0] != 'P') || (buffer[1] != '5')) goto err_return;\n\n \/* Skip comments upto width\/height *\/\n do\n {\n if (fgets (buffer, sizeof (buffer), pgmin) == NULL) goto err_return;\n } while (buffer[0] == '#');\n\n if (sscanf (buffer, \"%d%d\", &width, &height) != 2) goto err_return;\n if ((width < 1) || (height < 1)) goto err_return;\n\n \/* Skip comments upto maxval *\/\n do\n {\n if (fgets (buffer, sizeof (buffer), pgmin) == NULL) goto err_return;\n } while (buffer[0] == '#');\n \/* Ignore maxval *\/\n\n hdu = fits_add_hdu (fitsout); \/* Create a HDU for the FITS file *\/\n if (hdu == NULL) goto err_return;\n\n hdu->used.simple = 1; \/* Set proper values *\/\n hdu->bitpix = 8;\n hdu->naxis = 2;\n hdu->naxisn[0] = width;\n hdu->naxisn[1] = height;\n hdu->used.datamin = 1;\n hdu->datamin = 0.0;\n hdu->used.datamax = 1;\n hdu->datamax = 255.0;\n hdu->used.bzero = 1;\n hdu->bzero = 0.0;\n hdu->used.bscale = 1;\n hdu->bscale = 1.0;\n\n fits_add_card (hdu, \"\");\n fits_add_card (hdu, \"HISTORY THIS FITS FILE WAS GENERATED BY FITSRW\\\n USING PGMRAW_TO_FITS\");\n\n \/* Write the header. Blocking is done automatically *\/\n if (fits_write_header (fitsout, hdu) < 0) goto err_return;\n\n \/* The primary array plus blocking must be written manually *\/\n numbytes = width * height;\n\n while (numbytes > 0)\n {\n maxbytes = sizeof (buffer);\n if (maxbytes > numbytes) maxbytes = numbytes;\n\n if (fread (buffer, 1, maxbytes, pgmin) != maxbytes) goto err_return;\n if (fwrite (buffer, 1, maxbytes, fitsout->fp) != maxbytes) goto err_return;\n\n numbytes -= maxbytes;\n }\n\n \/* Do blocking *\/\n numbytes = (width * height) % FITS_RECORD_SIZE;\n if (numbytes)\n {\n while (numbytes++ < FITS_RECORD_SIZE)\n if (putc (0, fitsout->fp) == EOF) goto err_return;\n }\n retval = 0;\n\nerr_return:\n\n if (fitsout) fits_close (fitsout);\n if (pgmin) fclose (pgmin);\n\n return (retval);\n}","target":0,"code_token_length":745,"total_token_length":1076,"max_tokens_setting":2048} +{"idx":476798,"func":"static void ax_encaps(struct net_device *dev, unsigned char *icp, int len)\n{\n\tstruct mkiss *ax = netdev_priv(dev);\n\tunsigned char *p;\n\tint actual, count;\n\n\tif (ax->mtu != ax->dev->mtu + 73)\t\/* Someone has been ifconfigging *\/\n\t\tax_changedmtu(ax);\n\n\tif (len > ax->mtu) {\t\t\/* Sigh, shouldn't occur BUT ... *\/\n\t\tprintk(KERN_ERR \"mkiss: %s: truncating oversized transmit packet!\\n\", ax->dev->name);\n\t\tdev->stats.tx_dropped++;\n\t\tnetif_start_queue(dev);\n\t\treturn;\n\t}\n\n\tp = icp;\n\n\tspin_lock_bh(&ax->buflock);\n\tif ((*p & 0x0f) != 0) {\n\t\t\/* Configuration Command (kissparms(1).\n\t\t * Protocol spec says: never append CRC.\n\t\t * This fixes a very old bug in the linux\n\t\t * kiss driver. -- dl9sau *\/\n\t\tswitch (*p & 0xff) {\n\t\tcase 0x85:\n\t\t\t\/* command from userspace especially for us,\n\t\t\t * not for delivery to the tnc *\/\n\t\t\tif (len > 1) {\n\t\t\t\tint cmd = (p[1] & 0xff);\n\t\t\t\tswitch(cmd) {\n\t\t\t\tcase 3:\n\t\t\t\t ax->crcmode = CRC_MODE_SMACK;\n\t\t\t\t break;\n\t\t\t\tcase 2:\n\t\t\t\t ax->crcmode = CRC_MODE_FLEX;\n\t\t\t\t break;\n\t\t\t\tcase 1:\n\t\t\t\t ax->crcmode = CRC_MODE_NONE;\n\t\t\t\t break;\n\t\t\t\tcase 0:\n\t\t\t\tdefault:\n\t\t\t\t ax->crcmode = CRC_MODE_SMACK_TEST;\n\t\t\t\t cmd = 0;\n\t\t\t\t}\n\t\t\t\tax->crcauto = (cmd ? 0 : 1);\n\t\t\t\tprintk(KERN_INFO \"mkiss: %s: crc mode set to %d\\n\",\n\t\t\t\t ax->dev->name, cmd);\n\t\t\t}\n\t\t\tspin_unlock_bh(&ax->buflock);\n\t\t\tnetif_start_queue(dev);\n\n\t\t\treturn;\n\t\tdefault:\n\t\t\tcount = kiss_esc(p, ax->xbuff, len);\n\t\t}\n\t} else {\n\t\tunsigned short crc;\n\t\tswitch (ax->crcmode) {\n\t\tcase CRC_MODE_SMACK_TEST:\n\t\t\tax->crcmode = CRC_MODE_FLEX_TEST;\n\t\t\tprintk(KERN_INFO \"mkiss: %s: Trying crc-smack\\n\", ax->dev->name);\n\t\t\tfallthrough;\n\t\tcase CRC_MODE_SMACK:\n\t\t\t*p |= 0x80;\n\t\t\tcrc = swab16(crc16(0, p, len));\n\t\t\tcount = kiss_esc_crc(p, ax->xbuff, crc, len+2);\n\t\t\tbreak;\n\t\tcase CRC_MODE_FLEX_TEST:\n\t\t\tax->crcmode = CRC_MODE_NONE;\n\t\t\tprintk(KERN_INFO \"mkiss: %s: Trying crc-flexnet\\n\", ax->dev->name);\n\t\t\tfallthrough;\n\t\tcase CRC_MODE_FLEX:\n\t\t\t*p |= 0x20;\n\t\t\tcrc = calc_crc_flex(p, len);\n\t\t\tcount = kiss_esc_crc(p, ax->xbuff, crc, len+2);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tcount = kiss_esc(p, ax->xbuff, len);\n\t\t}\n\t}\n\tspin_unlock_bh(&ax->buflock);\n\n\tset_bit(TTY_DO_WRITE_WAKEUP, &ax->tty->flags);\n\tactual = ax->tty->ops->write(ax->tty, ax->xbuff, count);\n\tdev->stats.tx_packets++;\n\tdev->stats.tx_bytes += actual;\n\n\tnetif_trans_update(ax->dev);\n\tax->xleft = count - actual;\n\tax->xhead = ax->xbuff + actual;\n}","target":0,"code_token_length":790,"total_token_length":1121,"max_tokens_setting":2048} +{"idx":122896,"func":"inline void LstmCell(\n const LstmCellParams& params, const RuntimeShape& unextended_input_shape,\n const float* input_data, const RuntimeShape& unextended_prev_activ_shape,\n const float* prev_activ_data, const RuntimeShape& weights_shape,\n const float* weights_data, const RuntimeShape& unextended_bias_shape,\n const float* bias_data, const RuntimeShape& unextended_prev_state_shape,\n const float* prev_state_data,\n const RuntimeShape& unextended_output_state_shape, float* output_state_data,\n const RuntimeShape& unextended_output_activ_shape, float* output_activ_data,\n const RuntimeShape& unextended_concat_temp_shape, float* concat_temp_data,\n const RuntimeShape& unextended_activ_temp_shape, float* activ_temp_data,\n CpuBackendContext* cpu_backend_context) {\n ruy::profiler::ScopeLabel label(\"LstmCell\");\n TFLITE_DCHECK_LE(unextended_input_shape.DimensionsCount(), 4);\n TFLITE_DCHECK_LE(unextended_prev_activ_shape.DimensionsCount(), 4);\n TFLITE_DCHECK_LE(unextended_bias_shape.DimensionsCount(), 4);\n TFLITE_DCHECK_LE(unextended_prev_state_shape.DimensionsCount(), 4);\n TFLITE_DCHECK_LE(unextended_output_state_shape.DimensionsCount(), 4);\n TFLITE_DCHECK_LE(unextended_output_activ_shape.DimensionsCount(), 4);\n TFLITE_DCHECK_LE(unextended_concat_temp_shape.DimensionsCount(), 4);\n TFLITE_DCHECK_LE(unextended_activ_temp_shape.DimensionsCount(), 4);\n const RuntimeShape input_shape =\n RuntimeShape::ExtendedShape(4, unextended_input_shape);\n const RuntimeShape prev_activ_shape =\n RuntimeShape::ExtendedShape(4, unextended_prev_activ_shape);\n const RuntimeShape bias_shape =\n RuntimeShape::ExtendedShape(4, unextended_bias_shape);\n const RuntimeShape prev_state_shape =\n RuntimeShape::ExtendedShape(4, unextended_prev_state_shape);\n const RuntimeShape output_state_shape =\n RuntimeShape::ExtendedShape(4, unextended_output_state_shape);\n const RuntimeShape output_activ_shape =\n RuntimeShape::ExtendedShape(4, unextended_output_activ_shape);\n const RuntimeShape concat_temp_shape =\n RuntimeShape::ExtendedShape(4, unextended_concat_temp_shape);\n const RuntimeShape activ_temp_shape =\n RuntimeShape::ExtendedShape(4, unextended_activ_temp_shape);\n TFLITE_DCHECK_GE(weights_shape.DimensionsCount(), 2);\n\n const int weights_dim_count = weights_shape.DimensionsCount();\n MatchingDim( \/\/ batches\n input_shape, 0, prev_activ_shape, 0, prev_state_shape, 0,\n output_state_shape, 0, output_activ_shape, 0);\n MatchingDim( \/\/ height\n input_shape, 1, prev_activ_shape, 1, prev_state_shape, 1,\n output_state_shape, 1, output_activ_shape, 1);\n MatchingDim( \/\/ width\n input_shape, 2, prev_activ_shape, 2, prev_state_shape, 2,\n output_state_shape, 2, output_activ_shape, 2);\n const int input_depth = input_shape.Dims(3);\n const int prev_activ_depth = prev_activ_shape.Dims(3);\n const int total_input_depth = prev_activ_depth + input_depth;\n TFLITE_DCHECK_EQ(weights_shape.Dims(weights_dim_count - 1),\n total_input_depth);\n TFLITE_DCHECK_EQ(FlatSizeSkipDim(bias_shape, 3), 1);\n const int intern_activ_depth =\n MatchingDim(weights_shape, weights_dim_count - 2, bias_shape, 3);\n TFLITE_DCHECK_EQ(weights_shape.FlatSize(),\n intern_activ_depth * total_input_depth);\n TFLITE_DCHECK_EQ(intern_activ_depth % 4, 0);\n const int output_depth =\n MatchingDim(prev_state_shape, 3, prev_activ_shape, 3, output_state_shape,\n 3, output_activ_shape, 3);\n TFLITE_DCHECK_EQ(output_depth, intern_activ_depth \/ 4);\n\n \/\/ Concatenate prev_activ and input data together\n std::vector concat_input_arrays_data;\n std::vector concat_input_arrays_shapes;\n concat_input_arrays_data.push_back(input_data);\n concat_input_arrays_data.push_back(prev_activ_data);\n concat_input_arrays_shapes.push_back(&input_shape);\n concat_input_arrays_shapes.push_back(&prev_activ_shape);\n tflite::ConcatenationParams concat_params;\n concat_params.axis = 3;\n concat_params.inputs_count = concat_input_arrays_data.size();\n Concatenation(concat_params, &(concat_input_arrays_shapes[0]),\n &(concat_input_arrays_data[0]), concat_temp_shape,\n concat_temp_data);\n\n \/\/ Fully connected\n tflite::FullyConnectedParams fc_params;\n fc_params.float_activation_min = std::numeric_limits::lowest();\n fc_params.float_activation_max = std::numeric_limits::max();\n fc_params.lhs_cacheable = false;\n fc_params.rhs_cacheable = false;\n FullyConnected(fc_params, concat_temp_shape, concat_temp_data, weights_shape,\n weights_data, bias_shape, bias_data, activ_temp_shape,\n activ_temp_data, cpu_backend_context);\n\n \/\/ Map raw arrays to Eigen arrays so we can use Eigen's optimized array\n \/\/ operations.\n ArrayMap activ_temp_map =\n MapAsArrayWithLastDimAsRows(activ_temp_data, activ_temp_shape);\n auto input_gate_sm = activ_temp_map.block(0 * output_depth, 0, output_depth,\n activ_temp_map.cols());\n auto new_input_sm = activ_temp_map.block(1 * output_depth, 0, output_depth,\n activ_temp_map.cols());\n auto forget_gate_sm = activ_temp_map.block(2 * output_depth, 0, output_depth,\n activ_temp_map.cols());\n auto output_gate_sm = activ_temp_map.block(3 * output_depth, 0, output_depth,\n activ_temp_map.cols());\n ArrayMap prev_state_map =\n MapAsArrayWithLastDimAsRows(prev_state_data, prev_state_shape);\n ArrayMap output_state_map =\n MapAsArrayWithLastDimAsRows(output_state_data, output_state_shape);\n ArrayMap output_activ_map =\n MapAsArrayWithLastDimAsRows(output_activ_data, output_activ_shape);\n\n \/\/ Combined memory state and final output calculation\n ruy::profiler::ScopeLabel label2(\"MemoryStateAndFinalOutput\");\n output_state_map =\n input_gate_sm.unaryExpr(Eigen::internal::scalar_logistic_op()) *\n new_input_sm.tanh() +\n forget_gate_sm.unaryExpr(Eigen::internal::scalar_logistic_op()) *\n prev_state_map;\n output_activ_map =\n output_gate_sm.unaryExpr(Eigen::internal::scalar_logistic_op()) *\n output_state_map.tanh();\n}","target":0,"code_token_length":1507,"total_token_length":1838,"max_tokens_setting":2048} +{"idx":494496,"func":"static CURLcode gzip_unencode_write(struct Curl_easy *data,\n struct contenc_writer *writer,\n const char *buf, size_t nbytes)\n{\n struct zlib_params *zp = (struct zlib_params *) &writer->params;\n z_stream *z = &zp->z; \/* zlib state structure *\/\n\n if(zp->zlib_init == ZLIB_INIT_GZIP) {\n \/* Let zlib handle the gzip decompression entirely *\/\n z->next_in = (Bytef *) buf;\n z->avail_in = (uInt) nbytes;\n \/* Now uncompress the data *\/\n return inflate_stream(data, writer, ZLIB_INIT_GZIP);\n }\n\n#ifndef OLD_ZLIB_SUPPORT\n \/* Support for old zlib versions is compiled away and we are running with\n an old version, so return an error. *\/\n return exit_zlib(data, z, &zp->zlib_init, CURLE_WRITE_ERROR);\n\n#else\n \/* This next mess is to get around the potential case where there isn't\n * enough data passed in to skip over the gzip header. If that happens, we\n * malloc a block and copy what we have then wait for the next call. If\n * there still isn't enough (this is definitely a worst-case scenario), we\n * make the block bigger, copy the next part in and keep waiting.\n *\n * This is only required with zlib versions < 1.2.0.4 as newer versions\n * can handle the gzip header themselves.\n *\/\n\n switch(zp->zlib_init) {\n \/* Skip over gzip header? *\/\n case ZLIB_INIT:\n {\n \/* Initial call state *\/\n ssize_t hlen;\n\n switch(check_gzip_header((unsigned char *) buf, nbytes, &hlen)) {\n case GZIP_OK:\n z->next_in = (Bytef *) buf + hlen;\n z->avail_in = (uInt) (nbytes - hlen);\n zp->zlib_init = ZLIB_GZIP_INFLATING; \/* Inflating stream state *\/\n break;\n\n case GZIP_UNDERFLOW:\n \/* We need more data so we can find the end of the gzip header. It's\n * possible that the memory block we malloc here will never be freed if\n * the transfer abruptly aborts after this point. Since it's unlikely\n * that circumstances will be right for this code path to be followed in\n * the first place, and it's even more unlikely for a transfer to fail\n * immediately afterwards, it should seldom be a problem.\n *\/\n z->avail_in = (uInt) nbytes;\n z->next_in = malloc(z->avail_in);\n if(!z->next_in) {\n return exit_zlib(data, z, &zp->zlib_init, CURLE_OUT_OF_MEMORY);\n }\n memcpy(z->next_in, buf, z->avail_in);\n zp->zlib_init = ZLIB_GZIP_HEADER; \/* Need more gzip header data state *\/\n \/* We don't have any data to inflate yet *\/\n return CURLE_OK;\n\n case GZIP_BAD:\n default:\n return exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z));\n }\n\n }\n break;\n\n case ZLIB_GZIP_HEADER:\n {\n \/* Need more gzip header data state *\/\n ssize_t hlen;\n z->avail_in += (uInt) nbytes;\n z->next_in = Curl_saferealloc(z->next_in, z->avail_in);\n if(!z->next_in) {\n return exit_zlib(data, z, &zp->zlib_init, CURLE_OUT_OF_MEMORY);\n }\n \/* Append the new block of data to the previous one *\/\n memcpy(z->next_in + z->avail_in - nbytes, buf, nbytes);\n\n switch(check_gzip_header(z->next_in, z->avail_in, &hlen)) {\n case GZIP_OK:\n \/* This is the zlib stream data *\/\n free(z->next_in);\n \/* Don't point into the malloced block since we just freed it *\/\n z->next_in = (Bytef *) buf + hlen + nbytes - z->avail_in;\n z->avail_in = (uInt) (z->avail_in - hlen);\n zp->zlib_init = ZLIB_GZIP_INFLATING; \/* Inflating stream state *\/\n break;\n\n case GZIP_UNDERFLOW:\n \/* We still don't have any data to inflate! *\/\n return CURLE_OK;\n\n case GZIP_BAD:\n default:\n return exit_zlib(data, z, &zp->zlib_init, process_zlib_error(data, z));\n }\n\n }\n break;\n\n case ZLIB_EXTERNAL_TRAILER:\n z->next_in = (Bytef *) buf;\n z->avail_in = (uInt) nbytes;\n return process_trailer(data, zp);\n\n case ZLIB_GZIP_INFLATING:\n default:\n \/* Inflating stream state *\/\n z->next_in = (Bytef *) buf;\n z->avail_in = (uInt) nbytes;\n break;\n }\n\n if(z->avail_in == 0) {\n \/* We don't have any data to inflate; wait until next time *\/\n return CURLE_OK;\n }\n\n \/* We've parsed the header, now uncompress the data *\/\n return inflate_stream(data, writer, ZLIB_GZIP_INFLATING);\n#endif\n}","target":0,"code_token_length":1179,"total_token_length":1510,"max_tokens_setting":2048} +{"idx":271893,"func":"Status DepthwiseConv2DNativeShapeImpl(shape_inference::InferenceContext* c,\n bool supports_explicit_padding) {\n ShapeHandle input_shape;\n TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 4, &input_shape));\n ShapeHandle filter_shape;\n TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 4, &filter_shape));\n\n std::vector strides;\n TF_RETURN_IF_ERROR(c->GetAttr(\"strides\", &strides));\n\n if (strides.size() != 4) {\n return errors::InvalidArgument(\n \"DepthwiseConv2D requires the stride attribute to contain 4 values, \"\n \"but got: \",\n strides.size());\n }\n\n std::vector dilations;\n if (!c->GetAttr(\"dilations\", &dilations).ok()) {\n dilations.resize(4, 1);\n }\n\n if (dilations.size() != 4) {\n return errors::InvalidArgument(\n \"DepthwiseConv2D requires the dilations attribute to contain 4 values, \"\n \"but got: \",\n dilations.size());\n }\n\n string data_format_str;\n Status s = c->GetAttr(\"data_format\", &data_format_str);\n TensorFormat data_format;\n if (!s.ok() || !FormatFromString(data_format_str, &data_format)) {\n data_format = FORMAT_NHWC;\n }\n int32_t stride_rows;\n int32_t stride_cols;\n int32_t dilation_rows;\n int32_t dilation_cols;\n if (data_format == FORMAT_NCHW) {\n \/\/ Canonicalize input shape to NHWC so the shape inference code below can\n \/\/ process it.\n input_shape =\n c->MakeShape({{c->Dim(input_shape, 0), c->Dim(input_shape, 2),\n c->Dim(input_shape, 3), c->Dim(input_shape, 1)}});\n stride_rows = strides[2];\n stride_cols = strides[3];\n dilation_rows = dilations[2];\n dilation_cols = dilations[3];\n } else {\n stride_rows = strides[1];\n stride_cols = strides[2];\n dilation_rows = dilations[1];\n dilation_cols = dilations[2];\n }\n\n DimensionHandle batch_size_dim = c->Dim(input_shape, 0);\n DimensionHandle in_rows_dim = c->Dim(input_shape, 1);\n DimensionHandle in_cols_dim = c->Dim(input_shape, 2);\n\n DimensionHandle filter_rows_dim = c->Dim(filter_shape, 0);\n DimensionHandle filter_cols_dim = c->Dim(filter_shape, 1);\n DimensionHandle input_depth = c->Dim(filter_shape, 2);\n DimensionHandle depth_multiplier = c->Dim(filter_shape, 3);\n\n \/\/ Check that the input depths are compatible.\n TF_RETURN_IF_ERROR(\n c->Merge(c->Dim(input_shape, 3), input_depth, &input_depth));\n\n DimensionHandle output_depth;\n TF_RETURN_IF_ERROR(c->Multiply(input_depth, depth_multiplier, &output_depth));\n\n Padding padding;\n TF_RETURN_IF_ERROR(c->GetAttr(\"padding\", &padding));\n\n std::vector explicit_paddings;\n if (supports_explicit_padding) {\n Status status = c->GetAttr(\"explicit_paddings\", &explicit_paddings);\n \/\/ Use the default value, which is an empty list, if the attribute is not\n \/\/ found. Otherwise return the error to the caller.\n if (!status.ok() && !errors::IsNotFound(status)) {\n return status;\n }\n TF_RETURN_IF_ERROR(CheckValidPadding(padding, explicit_paddings,\n \/*num_dims=*\/4, data_format));\n } else {\n DCHECK(padding != Padding::EXPLICIT);\n }\n\n \/\/ TODO(mrry,shlens): Raise an error if the stride would cause\n \/\/ information in the input to be ignored. This will require a change\n \/\/ in the kernel implementation.\n DimensionHandle output_rows, output_cols;\n int64_t pad_rows_before = -1, pad_rows_after = -1;\n int64_t pad_cols_before = -1, pad_cols_after = -1;\n if (padding == Padding::EXPLICIT) {\n GetExplicitPaddingForDim(explicit_paddings, data_format, 'H',\n &pad_rows_before, &pad_rows_after);\n GetExplicitPaddingForDim(explicit_paddings, data_format, 'W',\n &pad_cols_before, &pad_cols_after);\n }\n TF_RETURN_IF_ERROR(GetWindowedOutputSizeFromDimsV2(\n c, in_rows_dim, filter_rows_dim, dilation_rows, stride_rows, padding,\n pad_rows_before, pad_rows_after, &output_rows));\n TF_RETURN_IF_ERROR(GetWindowedOutputSizeFromDimsV2(\n c, in_cols_dim, filter_cols_dim, dilation_cols, stride_cols, padding,\n pad_cols_before, pad_cols_after, &output_cols));\n\n ShapeHandle output_shape;\n if (data_format == FORMAT_NCHW) {\n output_shape =\n c->MakeShape({batch_size_dim, output_depth, output_rows, output_cols});\n } else {\n output_shape =\n c->MakeShape({batch_size_dim, output_rows, output_cols, output_depth});\n }\n c->set_output(0, output_shape);\n return Status::OK();\n}","target":0,"code_token_length":1171,"total_token_length":1502,"max_tokens_setting":2048} +{"idx":382351,"func":"StreamConnection(pgsocket server_fd, Port *port)\n{\n\t\/* accept connection and fill in the client (remote) address *\/\n\tport->raddr.salen = sizeof(port->raddr.addr);\n\tif ((port->sock = accept(server_fd,\n\t\t\t\t\t\t\t (struct sockaddr *) & port->raddr.addr,\n\t\t\t\t\t\t\t &port->raddr.salen)) == PGINVALID_SOCKET)\n\t{\n\t\tereport(LOG,\n\t\t\t\t(errcode_for_socket_access(),\n\t\t\t\t errmsg(\"could not accept new connection: %m\")));\n\n\t\t\/*\n\t\t * If accept() fails then postmaster.c will still see the server\n\t\t * socket as read-ready, and will immediately try again. To avoid\n\t\t * uselessly sucking lots of CPU, delay a bit before trying again.\n\t\t * (The most likely reason for failure is being out of kernel file\n\t\t * table slots; we can do little except hope some will get freed up.)\n\t\t *\/\n\t\tpg_usleep(100000L);\t\t\/* wait 0.1 sec *\/\n\t\treturn STATUS_ERROR;\n\t}\n\n#ifdef SCO_ACCEPT_BUG\n\n\t\/*\n\t * UnixWare 7+ and OpenServer 5.0.4 are known to have this bug, but it\n\t * shouldn't hurt to catch it for all versions of those platforms.\n\t *\/\n\tif (port->raddr.addr.ss_family == 0)\n\t\tport->raddr.addr.ss_family = AF_UNIX;\n#endif\n\n\t\/* fill in the server (local) address *\/\n\tport->laddr.salen = sizeof(port->laddr.addr);\n\tif (getsockname(port->sock,\n\t\t\t\t\t(struct sockaddr *) & port->laddr.addr,\n\t\t\t\t\t&port->laddr.salen) < 0)\n\t{\n\t\telog(LOG, \"getsockname() failed: %m\");\n\t\treturn STATUS_ERROR;\n\t}\n\n\t\/* select NODELAY and KEEPALIVE options if it's a TCP connection *\/\n\tif (!IS_AF_UNIX(port->laddr.addr.ss_family))\n\t{\n\t\tint\t\t\ton;\n\n#ifdef\tTCP_NODELAY\n\t\ton = 1;\n\t\tif (setsockopt(port->sock, IPPROTO_TCP, TCP_NODELAY,\n\t\t\t\t\t (char *) &on, sizeof(on)) < 0)\n\t\t{\n\t\t\telog(LOG, \"setsockopt(TCP_NODELAY) failed: %m\");\n\t\t\treturn STATUS_ERROR;\n\t\t}\n#endif\n\t\ton = 1;\n\t\tif (setsockopt(port->sock, SOL_SOCKET, SO_KEEPALIVE,\n\t\t\t\t\t (char *) &on, sizeof(on)) < 0)\n\t\t{\n\t\t\telog(LOG, \"setsockopt(SO_KEEPALIVE) failed: %m\");\n\t\t\treturn STATUS_ERROR;\n\t\t}\n\n#ifdef WIN32\n\n\t\t\/*\n\t\t * This is a Win32 socket optimization. The ideal size is 32k.\n\t\t * http:\/\/support.microsoft.com\/kb\/823764\/EN-US\/\n\t\t *\/\n\t\ton = PQ_SEND_BUFFER_SIZE * 4;\n\t\tif (setsockopt(port->sock, SOL_SOCKET, SO_SNDBUF, (char *) &on,\n\t\t\t\t\t sizeof(on)) < 0)\n\t\t{\n\t\t\telog(LOG, \"setsockopt(SO_SNDBUF) failed: %m\");\n\t\t\treturn STATUS_ERROR;\n\t\t}\n#endif\n\n\t\t\/*\n\t\t * Also apply the current keepalive parameters. If we fail to set a\n\t\t * parameter, don't error out, because these aren't universally\n\t\t * supported. (Note: you might think we need to reset the GUC\n\t\t * variables to 0 in such a case, but it's not necessary because the\n\t\t * show hooks for these variables report the truth anyway.)\n\t\t *\/\n\t\t(void) pq_setkeepalivesidle(tcp_keepalives_idle, port);\n\t\t(void) pq_setkeepalivesinterval(tcp_keepalives_interval, port);\n\t\t(void) pq_setkeepalivescount(tcp_keepalives_count, port);\n\t}\n\n\treturn STATUS_OK;\n}","target":0,"code_token_length":837,"total_token_length":1168,"max_tokens_setting":2048} +{"idx":393100,"func":"xmlSchemaBucketCreate(xmlSchemaParserCtxtPtr pctxt,\n\t\t\t int type, const xmlChar *targetNamespace)\n{\n xmlSchemaBucketPtr ret;\n int size;\n xmlSchemaPtr mainSchema;\n\n if (WXS_CONSTRUCTOR(pctxt)->mainSchema == NULL) {\n\tPERROR_INT(\"xmlSchemaBucketCreate\",\n\t \"no main schema on constructor\");\n\treturn(NULL);\n }\n mainSchema = WXS_CONSTRUCTOR(pctxt)->mainSchema;\n \/* Create the schema bucket. *\/\n if (WXS_IS_BUCKET_INCREDEF(type))\n\tsize = sizeof(xmlSchemaInclude);\n else\n\tsize = sizeof(xmlSchemaImport);\n ret = (xmlSchemaBucketPtr) xmlMalloc(size);\n if (ret == NULL) {\n\txmlSchemaPErrMemory(NULL, \"allocating schema bucket\", NULL);\n\treturn(NULL);\n }\n memset(ret, 0, size);\n ret->targetNamespace = targetNamespace;\n ret->type = type;\n ret->globals = xmlSchemaItemListCreate();\n if (ret->globals == NULL) {\n\txmlFree(ret);\n\treturn(NULL);\n }\n ret->locals = xmlSchemaItemListCreate();\n if (ret->locals == NULL) {\n\txmlFree(ret);\n\treturn(NULL);\n }\n \/*\n * The following will assure that only the first bucket is marked as\n * XML_SCHEMA_SCHEMA_MAIN and it points to the *main* schema.\n * For each following import buckets an xmlSchema will be created.\n * An xmlSchema will be created for every distinct targetNamespace.\n * We assign the targetNamespace to the schemata here.\n *\/\n if (! WXS_HAS_BUCKETS(pctxt)) {\n\tif (WXS_IS_BUCKET_INCREDEF(type)) {\n\t PERROR_INT(\"xmlSchemaBucketCreate\",\n\t\t\"first bucket but it's an include or redefine\");\n\t xmlSchemaBucketFree(ret);\n\t return(NULL);\n\t}\n\t\/* Force the type to be XML_SCHEMA_SCHEMA_MAIN. *\/\n\tret->type = XML_SCHEMA_SCHEMA_MAIN;\n\t\/* Point to the *main* schema. *\/\n\tWXS_CONSTRUCTOR(pctxt)->mainBucket = ret;\n\tWXS_IMPBUCKET(ret)->schema = mainSchema;\n\t\/*\n\t* Ensure that the main schema gets a targetNamespace.\n\t*\/\n\tmainSchema->targetNamespace = targetNamespace;\n } else {\n\tif (type == XML_SCHEMA_SCHEMA_MAIN) {\n\t PERROR_INT(\"xmlSchemaBucketCreate\",\n\t\t\"main bucket but it's not the first one\");\n\t xmlSchemaBucketFree(ret);\n\t return(NULL);\n\t} else if (type == XML_SCHEMA_SCHEMA_IMPORT) {\n\t \/*\n\t * Create a schema for imports and assign the\n\t * targetNamespace.\n\t *\/\n\t WXS_IMPBUCKET(ret)->schema = xmlSchemaNewSchema(pctxt);\n\t if (WXS_IMPBUCKET(ret)->schema == NULL) {\n\t\txmlSchemaBucketFree(ret);\n\t\treturn(NULL);\n\t }\n\t WXS_IMPBUCKET(ret)->schema->targetNamespace = targetNamespace;\n\t}\n }\n if (WXS_IS_BUCKET_IMPMAIN(type)) {\n\tint res;\n\t\/*\n\t* Imports go into the \"schemasImports\" slot of the main *schema*.\n\t* Note that we create an import entry for the main schema as well; i.e.,\n\t* even if there's only one schema, we'll get an import.\n\t*\/\n\tif (mainSchema->schemasImports == NULL) {\n\t mainSchema->schemasImports = xmlHashCreateDict(5,\n\t\tWXS_CONSTRUCTOR(pctxt)->dict);\n\t if (mainSchema->schemasImports == NULL) {\n\t\txmlSchemaBucketFree(ret);\n\t\treturn(NULL);\n\t }\n\t}\n\tif (targetNamespace == NULL)\n\t res = xmlHashAddEntry(mainSchema->schemasImports,\n\t\tXML_SCHEMAS_NO_NAMESPACE, ret);\n\telse\n\t res = xmlHashAddEntry(mainSchema->schemasImports,\n\t\ttargetNamespace, ret);\n\tif (res != 0) {\n\t PERROR_INT(\"xmlSchemaBucketCreate\",\n\t\t\"failed to add the schema bucket to the hash\");\n\t xmlSchemaBucketFree(ret);\n\t return(NULL);\n\t}\n } else {\n\t\/* Set the @ownerImport of an include bucket. *\/\n\tif (WXS_IS_BUCKET_IMPMAIN(WXS_CONSTRUCTOR(pctxt)->bucket->type))\n\t WXS_INCBUCKET(ret)->ownerImport =\n\t\tWXS_IMPBUCKET(WXS_CONSTRUCTOR(pctxt)->bucket);\n\telse\n\t WXS_INCBUCKET(ret)->ownerImport =\n\t\tWXS_INCBUCKET(WXS_CONSTRUCTOR(pctxt)->bucket)->ownerImport;\n\n\t\/* Includes got into the \"includes\" slot of the *main* schema. *\/\n\tif (mainSchema->includes == NULL) {\n\t mainSchema->includes = xmlSchemaItemListCreate();\n\t if (mainSchema->includes == NULL) {\n\t\txmlSchemaBucketFree(ret);\n\t\treturn(NULL);\n\t }\n\t}\n\txmlSchemaItemListAdd(mainSchema->includes, ret);\n }\n \/*\n * Add to list of all buckets; this is used for lookup\n * during schema construction time only.\n *\/\n if (xmlSchemaItemListAdd(WXS_CONSTRUCTOR(pctxt)->buckets, ret) == -1)\n\treturn(NULL);\n return(ret);\n}","target":0,"code_token_length":1080,"total_token_length":1411,"max_tokens_setting":2048} +{"idx":156649,"func":"static int process_block(struct archive_read* a) {\n\tconst uint8_t* p;\n\tstruct rar5* rar = get_context(a);\n\tint ret;\n\n\t\/* If we don't have any data to be processed, this most probably means\n\t * we need to switch to the next volume. *\/\n\tif(rar->main.volume && rar->file.bytes_remaining == 0) {\n\t\tret = advance_multivolume(a);\n\t\tif(ret != ARCHIVE_OK)\n\t\t\treturn ret;\n\t}\n\n\tif(rar->cstate.block_parsing_finished) {\n\t\tssize_t block_size;\n\t\tssize_t to_skip;\n\t\tssize_t cur_block_size;\n\n\t\t\/* The header size won't be bigger than 6 bytes. *\/\n\t\tif(!read_ahead(a, 6, &p)) {\n\t\t\t\/* Failed to prefetch data block header. *\/\n\t\t\treturn ARCHIVE_EOF;\n\t\t}\n\n\t\t\/*\n\t\t * Read block_size by parsing block header. Validate the header\n\t\t * by calculating CRC byte stored inside the header. Size of\n\t\t * the header is not constant (block size can be stored either\n\t\t * in 1 or 2 bytes), that's why block size is left out from the\n\t\t * `compressed_block_header` structure and returned by\n\t\t * `parse_block_header` as the second argument. *\/\n\n\t\tret = parse_block_header(a, p, &block_size,\n\t\t &rar->last_block_hdr);\n\t\tif(ret != ARCHIVE_OK) {\n\t\t\treturn ret;\n\t\t}\n\n\t\t\/* Skip block header. Next data is huffman tables,\n\t\t * if present. *\/\n\t\tto_skip = sizeof(struct compressed_block_header) +\n\t\t\tbf_byte_count(&rar->last_block_hdr) + 1;\n\n\t\tif(ARCHIVE_OK != consume(a, to_skip))\n\t\t\treturn ARCHIVE_EOF;\n\n\t\trar->file.bytes_remaining -= to_skip;\n\n\t\t\/* The block size gives information about the whole block size,\n\t\t * but the block could be stored in split form when using\n\t\t * multi-volume archives. In this case, the block size will be\n\t\t * bigger than the actual data stored in this file. Remaining\n\t\t * part of the data will be in another file. *\/\n\n\t\tcur_block_size =\n\t\t\trar5_min(rar->file.bytes_remaining, block_size);\n\n\t\tif(block_size > rar->file.bytes_remaining) {\n\t\t\t\/* If current blocks' size is bigger than our data\n\t\t\t * size, this means we have a multivolume archive.\n\t\t\t * In this case, skip all base headers until the end\n\t\t\t * of the file, proceed to next \"partXXX.rar\" volume,\n\t\t\t * find its signature, skip all headers up to the first\n\t\t\t * FILE base header, and continue from there.\n\t\t\t *\n\t\t\t * Note that `merge_block` will update the `rar`\n\t\t\t * context structure quite extensively. *\/\n\n\t\t\tret = merge_block(a, block_size, &p);\n\t\t\tif(ret != ARCHIVE_OK) {\n\t\t\t\treturn ret;\n\t\t\t}\n\n\t\t\tcur_block_size = block_size;\n\n\t\t\t\/* Current stream pointer should be now directly\n\t\t\t * *after* the block that spanned through multiple\n\t\t\t * archive files. `p` pointer should have the data of\n\t\t\t * the *whole* block (merged from partial blocks\n\t\t\t * stored in multiple archives files). *\/\n\t\t} else {\n\t\t\trar->cstate.switch_multivolume = 0;\n\n\t\t\t\/* Read the whole block size into memory. This can take\n\t\t\t * up to 8 megabytes of memory in theoretical cases.\n\t\t\t * Might be worth to optimize this and use a standard\n\t\t\t * chunk of 4kb's. *\/\n\t\t\tif(!read_ahead(a, 4 + cur_block_size, &p)) {\n\t\t\t\t\/* Failed to prefetch block data. *\/\n\t\t\t\treturn ARCHIVE_EOF;\n\t\t\t}\n\t\t}\n\n\t\trar->cstate.block_buf = p;\n\t\trar->cstate.cur_block_size = cur_block_size;\n\t\trar->cstate.block_parsing_finished = 0;\n\n\t\trar->bits.in_addr = 0;\n\t\trar->bits.bit_addr = 0;\n\n\t\tif(bf_is_table_present(&rar->last_block_hdr)) {\n\t\t\t\/* Load Huffman tables. *\/\n\t\t\tret = parse_tables(a, rar, p);\n\t\t\tif(ret != ARCHIVE_OK) {\n\t\t\t\t\/* Error during decompression of Huffman\n\t\t\t\t * tables. *\/\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t}\n\t} else {\n\t\t\/* Block parsing not finished, reuse previous memory buffer. *\/\n\t\tp = rar->cstate.block_buf;\n\t}\n\n\t\/* Uncompress the block, or a part of it, depending on how many bytes\n\t * will be generated by uncompressing the block.\n\t *\n\t * In case too many bytes will be generated, calling this function\n\t * again will resume the uncompression operation. *\/\n\tret = do_uncompress_block(a, p);\n\tif(ret != ARCHIVE_OK) {\n\t\treturn ret;\n\t}\n\n\tif(rar->cstate.block_parsing_finished &&\n\t rar->cstate.switch_multivolume == 0 &&\n\t rar->cstate.cur_block_size > 0)\n\t{\n\t\t\/* If we're processing a normal block, consume the whole\n\t\t * block. We can do this because we've already read the whole\n\t\t * block to memory. *\/\n\t\tif(ARCHIVE_OK != consume(a, rar->cstate.cur_block_size))\n\t\t\treturn ARCHIVE_FATAL;\n\n\t\trar->file.bytes_remaining -= rar->cstate.cur_block_size;\n\t} else if(rar->cstate.switch_multivolume) {\n\t\t\/* Don't consume the block if we're doing multivolume\n\t\t * processing. The volume switching function will consume\n\t\t * the proper count of bytes instead. *\/\n\t\trar->cstate.switch_multivolume = 0;\n\t}\n\n\treturn ARCHIVE_OK;\n}","target":0,"code_token_length":1247,"total_token_length":1578,"max_tokens_setting":2048} +{"idx":298950,"func":"rs_filter_set_recursive(RSFilter *filter, ...)\n{\n\tva_list ap;\n\tgchar *property_name;\n\tRSFilter *current_filter;\n\tGParamSpec *spec;\n\tRSFilter *first_seen_here = NULL;\n\tGTypeValueTable *table = NULL;\n\tGType type = 0;\n\tunion CValue {\n\t\tgint v_int;\n\t\tglong v_long;\n\t\tgint64 v_int64;\n\t\tgdouble v_double;\n\t\tgpointer v_pointer;\n\t} value;\n\n\tg_return_if_fail(RS_IS_FILTER(filter));\n\n\tva_start(ap, filter);\n\n\t\/* Loop through all properties *\/\n\twhile ((property_name = va_arg(ap, gchar *)))\n\t{\n\t\t\/* We set table to NULL for every property to indicate that we (again)\n\t\t * have an \"unknown\" type *\/\n\t\ttable = NULL;\n\n\t\tcurrent_filter = filter;\n\t\t\/* Iterate through all filters previous to filter *\/\n\t\tdo {\n\t\t\tif ((spec = g_object_class_find_property(G_OBJECT_GET_CLASS(current_filter), property_name)))\n\t\t\t\tif (spec->flags & G_PARAM_WRITABLE)\n\t\t\t\t{\n\t\t\t\t\t\/* If we got no GTypeValueTable at this point, we aquire\n\t\t\t\t\t * one. We rely on all filters using the same type for all\n\t\t\t\t\t * properties equally named *\/\n\t\t\t\t\tif (!table)\n\t\t\t\t\t{\n\t\t\t\t\t\tfirst_seen_here = current_filter;\n\t\t\t\t\t\ttype = spec->value_type;\n\t\t\t\t\t\ttable = g_type_value_table_peek(type);\n\n\t\t\t\t\t\t\/* If we have no valuetable, we're screwed, bail out *\/\n\t\t\t\t\t\tif (!table)\n\t\t\t\t\t\t\tg_error(\"No GTypeValueTable found for '%s'\", g_type_name(type));\n\n\t\t\t\t\t\tswitch (table->collect_format[0])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcase 'i': value.v_int = va_arg(ap, gint); break;\n\t\t\t\t\t\t\tcase 'l': value.v_long = va_arg(ap, glong); break;\n\t\t\t\t\t\t\tcase 'd': value.v_double = va_arg(ap, gdouble); break;\n\t\t\t\t\t\t\tcase 'p': value.v_pointer = va_arg(ap, gpointer); break;\n\t\t\t\t\t\t\tdefault: g_error(\"Don't know how to collect for '%s'\", g_type_name(type)); break;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (table)\n\t\t\t\t\t{\n\t\t\t\t\t\t\/* We try to catch cases where different filters use\n\t\t\t\t\t\t * the same property name for different types *\/\n\t\t\t\t\t\tif (type != spec->value_type)\n\t\t\t\t\t\t\tg_warning(\"Diverging types found for property '%s' (on filter '%s' and '%s')\",\n\t\t\t\t\t\t\t\tproperty_name,\n\t\t\t\t\t\t\t\tRS_FILTER_NAME(first_seen_here),\n\t\t\t\t\t\t\t\tRS_FILTER_NAME(current_filter));\n\n\t\t\t\t\t\tswitch (table->collect_format[0])\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcase 'i': g_object_set(current_filter, property_name, value.v_int, NULL); break;\n\t\t\t\t\t\t\tcase 'l': g_object_set(current_filter, property_name, value.v_long, NULL); break;\n\t\t\t\t\t\t\tcase 'd': g_object_set(current_filter, property_name, value.v_double, NULL); break;\n\t\t\t\t\t\t\tcase 'p': g_object_set(current_filter, property_name, value.v_pointer, NULL); break;\n\t\t\t\t\t\t\tdefault: break;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t} while (RS_IS_FILTER(current_filter = current_filter->previous));\n\t\tif (!table)\n\t\t{\n\/\/\t\t\tg_warning(\"Property: %s could not be found in filter chain. Skipping further properties\", property_name);\n\t\t\tva_end(ap);\n\t\t\treturn;\n\t\t}\n\t}\n\n\tva_end(ap);\n}","target":0,"code_token_length":731,"total_token_length":1062,"max_tokens_setting":2048} +{"idx":64203,"func":"RawTile TileManager::getTile( int resolution, int tile, int xangle, int yangle, int layers, CompressionType ctype ){\n\n RawTile* rawtile = NULL;\n string tileCompression;\n string compName;\n\n\n \/\/ Time the tile retrieval\n if( loglevel >= 3 ) tile_timer.start();\n\n\n \/* Try to get the encoded tile directly from our cache first.\n Otherwise decode one from the source image and add it to the cache\n *\/\n switch( ctype )\n {\n\n case JPEG:\n if( (rawtile = tileCache->getTile( image->getImagePath(), resolution, tile,\n\t\t\t\t\t xangle, yangle, JPEG, compressor->getQuality() )) ) break;\n if( (rawtile = tileCache->getTile( image->getImagePath(), resolution, tile,\n\t\t\t\t\t xangle, yangle, UNCOMPRESSED, 0 )) ) break;\n break;\n\n\n case PNG:\n if( (rawtile = tileCache->getTile( image->getImagePath(), resolution, tile,\n\t\t\t\t\t xangle, yangle, PNG, compressor->getQuality() )) ) break;\n if( (rawtile = tileCache->getTile( image->getImagePath(), resolution, tile,\n\t\t\t\t\t xangle, yangle, UNCOMPRESSED, 0 )) ) break;\n break;\n\n\n case UNCOMPRESSED:\n if( (rawtile = tileCache->getTile( image->getImagePath(), resolution, tile,\n\t\t\t\t\t xangle, yangle, UNCOMPRESSED, 0 )) ) break;\n break;\n\n\n default: \n break;\n\n }\n\n\n\n if( loglevel >= 3 ){\n \/\/ Define our compression names for logging purposes\n switch( ctype ){\n case JPEG: compName = \"JPEG\"; break;\n case PNG: compName = \"PNG\"; break;\n case DEFLATE: compName = \"DEFLATE\"; break;\n case UNCOMPRESSED: compName = \"UNCOMPRESSED\"; break;\n default: break;\n }\n }\n\n\n \/\/ If we haven't been able to get a tile, get a raw one\n if( !rawtile || (rawtile && (rawtile->timestamp < image->timestamp)) ){\n\n if( rawtile && (rawtile->timestamp < image->timestamp) ){\n if( loglevel >= 3 ) *logfile << \"TileManager :: Tile has old timestamp \"\n\t\t\t << rawtile->timestamp << \" - \" << image->timestamp\n << \" ... updating\" << endl;\n }\n\n if( loglevel >= 4 ) *logfile << \"TileManager :: Cache Miss for resolution: \" << resolution\n\t\t\t\t << \", tile: \" << tile\n\t\t\t\t << \", compression: \" << compName\n\t\t\t\t << \", quality: \" << compressor->getQuality() << endl\n\t\t\t\t << \"TileManager :: Cache Size: \" << tileCache->getNumElements()\n\t\t\t\t << \" tiles, \" << tileCache->getMemorySize() << \" MB\" << endl;\n\n \n RawTile newtile = this->getNewTile( resolution, tile, xangle, yangle, layers, ctype );\n\n if( loglevel >= 3 ) *logfile << \"TileManager :: Total Tile Access Time: \"\n\t\t\t\t << tile_timer.getTime() << \" microseconds\" << endl;\n return newtile;\n }\n\n\n\n\n if( loglevel >= 3 ) *logfile << \"TileManager :: Cache Hit for resolution: \" << resolution\n\t\t\t << \", tile: \" << tile\n\t\t\t << \", compression: \" << compName\n\t\t\t << \", quality: \" << compressor->getQuality() << endl\n\t\t\t << \"TileManager :: Cache Size: \"\n\t\t\t << tileCache->getNumElements() << \" tiles, \"\n\t\t\t << tileCache->getMemorySize() << \" MB\" << endl;\n\n\n \/\/ Check whether the compression used for out tile matches our requested compression type. If not, we must convert\n \/\/ Perform JPEG compression iff we have an 8 bit per channel image and either 1 or 3 bands\n \/\/ PNG compression can have 8 or 16 bits and alpha channels\n if( (rawtile->compressionType == UNCOMPRESSED) &&\n ( ( ctype==JPEG && rawtile->bpc==8 && (rawtile->channels==1 || rawtile->channels==3) ) || ctype==PNG ) ){\n\n \/\/ Rawtile is a pointer to the cache data, so we need to create a copy of it in case we compress it\n RawTile ttt( *rawtile );\n\n \/\/ Crop if this is an edge tile\n if( ( (ttt.width != image->getTileWidth()) || (ttt.height != image->getTileHeight()) ) && ttt.padded ){\n if( loglevel >= 5 ) * logfile << \"TileManager :: Cropping tile\" << endl;\n this->crop( &ttt );\n }\n\n if( loglevel >=2 ) compression_timer.start();\n unsigned int oldlen = rawtile->dataLength;\n unsigned int newlen = compressor->Compress( ttt );\n if( loglevel >= 3 ) *logfile << \"TileManager :: \" << compName << \" requested, but UNCOMPRESSED compression found in cache.\" << endl\n\t\t\t\t << \"TileManager :: \" << compName << \" Compression Time: \"\n\t\t\t\t << compression_timer.getTime() << \" microseconds\" << endl\n\t\t\t\t << \"TileManager :: Compression Ratio: \" << newlen << \"\/\" << oldlen << \" = \"\n\t\t\t\t << ( (float)newlen\/(float)oldlen ) << endl;\n\n \/\/ Add our compressed tile to the cache\n if( loglevel >= 3 ) insert_timer.start();\n tileCache->insert( ttt );\n if( loglevel >= 3 ) *logfile << \"TileManager :: Tile cache insertion time: \" << insert_timer.getTime()\n\t\t\t\t << \" microseconds\" << endl;\n\n if( loglevel >= 3 ) *logfile << \"TileManager :: Total Tile Access Time: \"\n\t\t\t\t << tile_timer.getTime() << \" microseconds\" << endl;\n return RawTile( ttt );\n }\n\n if( loglevel >= 3 ) *logfile << \"TileManager :: Total Tile Access Time: \"\n\t\t\t << tile_timer.getTime() << \" microseconds\" << endl;\n\n return RawTile( *rawtile );\n\n\n}","target":0,"code_token_length":1323,"total_token_length":1654,"max_tokens_setting":2048} +{"idx":221680,"func":"WORD32 ih264d_delete_gap_frm_sliding(dpb_manager_t *ps_dpb_mgr,\n WORD32 i4_frame_num,\n UWORD8 *pu1_del_node)\n{\n WORD8 i1_gap_idx, i, j, j_min;\n WORD32 *pi4_gaps_start_frm_num, *pi4_gaps_end_frm_num, i4_gap_frame_num;\n WORD32 i4_start_frm_num, i4_end_frm_num;\n WORD32 i4_max_frm_num;\n WORD32 i4_frm_num, i4_gap_frm_num_min;\n\n \/* find the least frame num from gaps and current DPB node *\/\n \/* Delete the least one *\/\n *pu1_del_node = 1;\n if(0 == ps_dpb_mgr->u1_num_gaps)\n return OK;\n pi4_gaps_start_frm_num = ps_dpb_mgr->ai4_gaps_start_frm_num;\n pi4_gaps_end_frm_num = ps_dpb_mgr->ai4_gaps_end_frm_num;\n i4_gap_frame_num = INVALID_FRAME_NUM;\n i4_max_frm_num = ps_dpb_mgr->i4_max_frm_num;\n\n i1_gap_idx = -1;\n if(INVALID_FRAME_NUM != i4_frame_num)\n {\n i4_gap_frame_num = i4_frame_num;\n for(i = 0; i < MAX_FRAMES; i++)\n {\n i4_start_frm_num = pi4_gaps_start_frm_num[i];\n if(INVALID_FRAME_NUM != i4_start_frm_num)\n {\n i4_end_frm_num = pi4_gaps_end_frm_num[i];\n if(i4_end_frm_num < i4_max_frm_num)\n {\n if(i4_start_frm_num <= i4_gap_frame_num)\n {\n i4_gap_frame_num = i4_start_frm_num;\n i1_gap_idx = i;\n }\n }\n else\n {\n if(((i4_start_frm_num <= i4_gap_frame_num)\n && (i4_gap_frame_num <= i4_max_frm_num))\n || ((i4_start_frm_num >= i4_gap_frame_num)\n && ((i4_gap_frame_num\n + i4_max_frm_num)\n >= i4_end_frm_num)))\n {\n i4_gap_frame_num = i4_start_frm_num;\n i1_gap_idx = i;\n }\n }\n }\n }\n }\n else\n {\n \/* no valid short term buffers, delete one gap from the least start *\/\n \/* of gap sequence *\/\n i4_gap_frame_num = pi4_gaps_start_frm_num[0];\n i1_gap_idx = 0;\n for(i = 1; i < MAX_FRAMES; i++)\n {\n if(INVALID_FRAME_NUM != pi4_gaps_start_frm_num[i])\n {\n if(pi4_gaps_start_frm_num[i] < i4_gap_frame_num)\n {\n i4_gap_frame_num = pi4_gaps_start_frm_num[i];\n i1_gap_idx = i;\n }\n }\n }\n if(INVALID_FRAME_NUM == i4_gap_frame_num)\n {\n UWORD32 i4_error_code;\n i4_error_code = ERROR_DBP_MANAGER_T;\n return i4_error_code;\n }\n }\n\n if(-1 != i1_gap_idx)\n {\n \/* find least frame_num in the poc_map, which is in this range *\/\n i4_start_frm_num = pi4_gaps_start_frm_num[i1_gap_idx];\n if(i4_start_frm_num < 0)\n i4_start_frm_num += i4_max_frm_num;\n i4_end_frm_num = pi4_gaps_end_frm_num[i1_gap_idx];\n if(i4_end_frm_num < 0)\n i4_end_frm_num += i4_max_frm_num;\n\n i4_gap_frm_num_min = 0xfffffff;\n j_min = MAX_FRAMES;\n for(j = 0; j < MAX_FRAMES; j++)\n {\n i4_frm_num = ps_dpb_mgr->ai4_poc_buf_id_map[j][2];\n if((i4_start_frm_num <= i4_frm_num)\n && (i4_end_frm_num >= i4_frm_num))\n {\n if(i4_frm_num < i4_gap_frm_num_min)\n {\n j_min = j;\n i4_gap_frm_num_min = i4_frm_num;\n }\n }\n }\n\n if(j_min != MAX_FRAMES)\n {\n\n ps_dpb_mgr->ai4_poc_buf_id_map[j_min][0] = -1;\n ps_dpb_mgr->ai4_poc_buf_id_map[j_min][1] = 0x7fffffff;\n ps_dpb_mgr->ai4_poc_buf_id_map[j_min][2] = GAP_FRAME_NUM;\n ps_dpb_mgr->i1_gaps_deleted++;\n\n ps_dpb_mgr->ai1_gaps_per_seq[i1_gap_idx]--;\n ps_dpb_mgr->u1_num_gaps--;\n *pu1_del_node = 0;\n if(0 == ps_dpb_mgr->ai1_gaps_per_seq[i1_gap_idx])\n {\n ps_dpb_mgr->ai4_gaps_start_frm_num[i1_gap_idx] =\n INVALID_FRAME_NUM;\n ps_dpb_mgr->ai4_gaps_end_frm_num[i1_gap_idx] = 0;\n }\n }\n }\n\n return OK;\n}\n","target":0,"code_token_length":1092,"total_token_length":1423,"max_tokens_setting":2048} +{"idx":6061,"func":"static void merge_param(HashTable *params, zval *zdata, zval ***current_param, zval ***current_args TSRMLS_DC)\n{\n\tzval **ptr, **zdata_ptr;\n\tphp_http_array_hashkey_t hkey = php_http_array_hashkey_init(0);\n\n#if 0\n\t{\n\t\tzval tmp;\n\t\tINIT_PZVAL_ARRAY(&tmp, params);\n\t\tfprintf(stderr, \"params = \");\n\t\tzend_print_zval_r(&tmp, 1 TSRMLS_CC);\n\t\tfprintf(stderr, \"\\n\");\n\t}\n#endif\n\n\thkey.type = zend_hash_get_current_key_ex(Z_ARRVAL_P(zdata), &hkey.str, &hkey.len, &hkey.num, hkey.dup, NULL);\n\n\tif ((hkey.type == HASH_KEY_IS_STRING && !zend_hash_exists(params, hkey.str, hkey.len))\n\t||\t(hkey.type == HASH_KEY_IS_LONG && !zend_hash_index_exists(params, hkey.num))\n\t) {\n\t\tzval *tmp, *arg, **args;\n\n\t\t\/* create the entry if it doesn't exist *\/\n\t\tzend_hash_get_current_data(Z_ARRVAL_P(zdata), (void *) &ptr);\n\t\tZ_ADDREF_PP(ptr);\n\t\tMAKE_STD_ZVAL(tmp);\n\t\tarray_init(tmp);\n\t\tadd_assoc_zval_ex(tmp, ZEND_STRS(\"value\"), *ptr);\n\n\t\tMAKE_STD_ZVAL(arg);\n\t\tarray_init(arg);\n\t\tzend_hash_update(Z_ARRVAL_P(tmp), \"arguments\", sizeof(\"arguments\"), (void *) &arg, sizeof(zval *), (void *) &args);\n\t\t*current_args = args;\n\n\t\tif (hkey.type == HASH_KEY_IS_STRING) {\n\t\t\tzend_hash_update(params, hkey.str, hkey.len, (void *) &tmp, sizeof(zval *), (void *) &ptr);\n\t\t} else {\n\t\t\tzend_hash_index_update(params, hkey.num, (void *) &tmp, sizeof(zval *), (void *) &ptr);\n\t\t}\n\t} else {\n\t\t\/* merge *\/\n\t\tif (hkey.type == HASH_KEY_IS_STRING) {\n\t\t\tzend_hash_find(params, hkey.str, hkey.len, (void *) &ptr);\n\t\t} else {\n\t\t\tzend_hash_index_find(params, hkey.num, (void *) &ptr);\n\t\t}\n\n\t\tzdata_ptr = &zdata;\n\n\t\tif (Z_TYPE_PP(ptr) == IS_ARRAY\n\t\t&&\tSUCCESS == zend_hash_find(Z_ARRVAL_PP(ptr), \"value\", sizeof(\"value\"), (void *) &ptr)\n\t\t&&\tSUCCESS == zend_hash_get_current_data(Z_ARRVAL_PP(zdata_ptr), (void *) &zdata_ptr)\n\t\t) {\n\t\t\t\/*\n\t\t\t * params = [arr => [value => [0 => 1]]]\n\t\t\t * ^- ptr\n\t\t\t * zdata = [arr => [0 => NULL]]\n\t\t\t * ^- zdata_ptr\n\t\t\t *\/\n\t\t\tzval **test_ptr;\n\n\t\t\twhile (Z_TYPE_PP(zdata_ptr) == IS_ARRAY\n\t\t\t&&\tSUCCESS == zend_hash_get_current_data(Z_ARRVAL_PP(zdata_ptr), (void *) &test_ptr)\n\t\t\t) {\n\t\t\t\tif (Z_TYPE_PP(test_ptr) == IS_ARRAY) {\n\n\t\t\t\t\t\/* now find key in ptr *\/\n\t\t\t\t\tif (HASH_KEY_IS_STRING == zend_hash_get_current_key_ex(Z_ARRVAL_PP(zdata_ptr), &hkey.str, &hkey.len, &hkey.num, hkey.dup, NULL)) {\n\t\t\t\t\t\tif (SUCCESS == zend_hash_find(Z_ARRVAL_PP(ptr), hkey.str, hkey.len, (void *) &ptr)) {\n\t\t\t\t\t\t\tzdata_ptr = test_ptr;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tZ_ADDREF_PP(test_ptr);\n\t\t\t\t\t\t\tzend_hash_update(Z_ARRVAL_PP(ptr), hkey.str, hkey.len, (void *) test_ptr, sizeof(zval *), (void *) &ptr);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (SUCCESS == zend_hash_index_find(Z_ARRVAL_PP(ptr), hkey.num, (void *) &ptr)) {\n\t\t\t\t\t\t\tzdata_ptr = test_ptr;\n\t\t\t\t\t\t} else if (hkey.num) {\n\t\t\t\t\t\t\tZ_ADDREF_PP(test_ptr);\n\t\t\t\t\t\t\tzend_hash_index_update(Z_ARRVAL_PP(ptr), hkey.num, (void *) test_ptr, sizeof(zval *), (void *) &ptr);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tZ_ADDREF_PP(test_ptr);\n\t\t\t\t\t\t\tzend_hash_next_index_insert(Z_ARRVAL_PP(ptr), (void *) test_ptr, sizeof(zval *), (void *) &ptr);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t\/* this is the leaf *\/\n\t\t\t\t\tZ_ADDREF_PP(test_ptr);\n\t\t\t\t\tif (Z_TYPE_PP(ptr) != IS_ARRAY) {\n\t\t\t\t\t\tzval_dtor(*ptr);\n\t\t\t\t\t\tarray_init(*ptr);\n\t\t\t\t\t}\n\t\t\t\t\tif (HASH_KEY_IS_STRING == zend_hash_get_current_key_ex(Z_ARRVAL_PP(zdata_ptr), &hkey.str, &hkey.len, &hkey.num, hkey.dup, NULL)) {\n\t\t\t\t\t\tzend_hash_update(Z_ARRVAL_PP(ptr), hkey.str, hkey.len, (void *) test_ptr, sizeof(zval *), (void *) &ptr);\n\t\t\t\t\t} else if (hkey.num) {\n\t\t\t\t\t\tzend_hash_index_update(Z_ARRVAL_PP(ptr), hkey.num, (void *) test_ptr, sizeof(zval *), (void *) &ptr);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tzend_hash_next_index_insert(Z_ARRVAL_PP(ptr), (void *) test_ptr, sizeof(zval *), (void *) &ptr);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t}\n\n\t\/* bubble up *\/\n\twhile (Z_TYPE_PP(ptr) == IS_ARRAY && SUCCESS == zend_hash_get_current_data(Z_ARRVAL_PP(ptr), (void *) &ptr));\n\t*current_param = ptr;\n}","target":1,"code_token_length":1252,"total_token_length":1583,"max_tokens_setting":2048} +{"idx":9907,"func":"static void JNI_WebApkUpdateManager_StoreWebApkUpdateRequestToFile(\n JNIEnv* env,\n const JavaParamRef& java_update_request_path,\n const JavaParamRef& java_start_url,\n const JavaParamRef& java_scope,\n const JavaParamRef& java_name,\n const JavaParamRef& java_short_name,\n const JavaParamRef& java_primary_icon_url,\n const JavaParamRef& java_primary_icon_bitmap,\n const JavaParamRef& java_badge_icon_url,\n const JavaParamRef& java_badge_icon_bitmap,\n const JavaParamRef& java_icon_urls,\n const JavaParamRef& java_icon_hashes,\n jint java_display_mode,\n jint java_orientation,\n jlong java_theme_color,\n jlong java_background_color,\n const JavaParamRef& java_web_manifest_url,\n const JavaParamRef& java_webapk_package,\n jint java_webapk_version,\n jboolean java_is_manifest_stale,\n jint java_update_reason,\n const JavaParamRef& java_callback) {\n DCHECK_CURRENTLY_ON(content::BrowserThread::UI);\n\n std::string update_request_path =\n ConvertJavaStringToUTF8(env, java_update_request_path);\n\n ShortcutInfo info(GURL(ConvertJavaStringToUTF8(env, java_start_url)));\n info.scope = GURL(ConvertJavaStringToUTF8(env, java_scope));\n info.name = ConvertJavaStringToUTF16(env, java_name);\n info.short_name = ConvertJavaStringToUTF16(env, java_short_name);\n info.user_title = info.short_name;\n info.display = static_cast(java_display_mode);\n info.orientation =\n static_cast(java_orientation);\n info.theme_color = (int64_t)java_theme_color;\n info.background_color = (int64_t)java_background_color;\n info.best_primary_icon_url =\n GURL(ConvertJavaStringToUTF8(env, java_primary_icon_url));\n info.best_badge_icon_url =\n GURL(ConvertJavaStringToUTF8(env, java_badge_icon_url));\n info.manifest_url = GURL(ConvertJavaStringToUTF8(env, java_web_manifest_url));\n \n base::android::AppendJavaStringArrayToStringVector(env, java_icon_urls,\n &info.icon_urls);\n \n std::vector icon_hashes;\n base::android::AppendJavaStringArrayToStringVector(env, java_icon_hashes,\n &icon_hashes);\n\n std::map icon_url_to_murmur2_hash;\n for (size_t i = 0; i < info.icon_urls.size(); ++i)\n icon_url_to_murmur2_hash[info.icon_urls[i]] = icon_hashes[i];\n\n gfx::JavaBitmap java_primary_icon_bitmap_lock(java_primary_icon_bitmap);\n SkBitmap primary_icon =\n gfx::CreateSkBitmapFromJavaBitmap(java_primary_icon_bitmap_lock);\n primary_icon.setImmutable();\n\n SkBitmap badge_icon;\n if (!java_badge_icon_bitmap.is_null()) {\n gfx::JavaBitmap java_badge_icon_bitmap_lock(java_badge_icon_bitmap);\n gfx::CreateSkBitmapFromJavaBitmap(java_badge_icon_bitmap_lock);\n badge_icon.setImmutable();\n }\n\n std::string webapk_package;\n ConvertJavaStringToUTF8(env, java_webapk_package, &webapk_package);\n\n WebApkUpdateReason update_reason =\n static_cast(java_update_reason);\n\n WebApkInstaller::StoreUpdateRequestToFile(\n base::FilePath(update_request_path), info, primary_icon, badge_icon,\n webapk_package, std::to_string(java_webapk_version),\n icon_url_to_murmur2_hash, java_is_manifest_stale, update_reason,\n base::BindOnce(&base::android::RunBooleanCallbackAndroid,\n ScopedJavaGlobalRef(java_callback)));\n}\n","target":1,"code_token_length":845,"total_token_length":1176,"max_tokens_setting":2048} +{"idx":356146,"func":"generic_file_direct_write(struct kiocb *iocb, const struct iovec *iov,\n\t\tunsigned long *nr_segs, loff_t pos, loff_t *ppos,\n\t\tsize_t count, size_t ocount)\n{\n\tstruct file\t*file = iocb->ki_filp;\n\tstruct address_space *mapping = file->f_mapping;\n\tstruct inode\t*inode = mapping->host;\n\tssize_t\t\twritten;\n\tsize_t\t\twrite_len;\n\tpgoff_t\t\tend;\n\n\tif (count != ocount)\n\t\t*nr_segs = iov_shorten((struct iovec *)iov, *nr_segs, count);\n\n\t\/*\n\t * Unmap all mmappings of the file up-front.\n\t *\n\t * This will cause any pte dirty bits to be propagated into the\n\t * pageframes for the subsequent filemap_write_and_wait().\n\t *\/\n\twrite_len = iov_length(iov, *nr_segs);\n\tend = (pos + write_len - 1) >> PAGE_CACHE_SHIFT;\n\tif (mapping_mapped(mapping))\n\t\tunmap_mapping_range(mapping, pos, write_len, 0);\n\n\twritten = filemap_write_and_wait(mapping);\n\tif (written)\n\t\tgoto out;\n\n\t\/*\n\t * After a write we want buffered reads to be sure to go to disk to get\n\t * the new data. We invalidate clean cached page from the region we're\n\t * about to write. We do this *before* the write so that we can return\n\t * -EIO without clobbering -EIOCBQUEUED from ->direct_IO().\n\t *\/\n\tif (mapping->nrpages) {\n\t\twritten = invalidate_inode_pages2_range(mapping,\n\t\t\t\t\tpos >> PAGE_CACHE_SHIFT, end);\n\t\tif (written)\n\t\t\tgoto out;\n\t}\n\n\twritten = mapping->a_ops->direct_IO(WRITE, iocb, iov, pos, *nr_segs);\n\n\t\/*\n\t * Finally, try again to invalidate clean pages which might have been\n\t * cached by non-direct readahead, or faulted in by get_user_pages()\n\t * if the source of the write was an mmap'ed region of the file\n\t * we're writing. Either one is a pretty crazy thing to do,\n\t * so we don't support it 100%. If this invalidation\n\t * fails, tough, the write still worked...\n\t *\/\n\tif (mapping->nrpages) {\n\t\tinvalidate_inode_pages2_range(mapping,\n\t\t\t\t\t pos >> PAGE_CACHE_SHIFT, end);\n\t}\n\n\tif (written > 0) {\n\t\tloff_t end = pos + written;\n\t\tif (end > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {\n\t\t\ti_size_write(inode, end);\n\t\t\tmark_inode_dirty(inode);\n\t\t}\n\t\t*ppos = end;\n\t}\n\n\t\/*\n\t * Sync the fs metadata but not the minor inode changes and\n\t * of course not the data as we did direct DMA for the IO.\n\t * i_mutex is held, which protects generic_osync_inode() from\n\t * livelocking. AIO O_DIRECT ops attempt to sync metadata here.\n\t *\/\nout:\n\tif ((written >= 0 || written == -EIOCBQUEUED) &&\n\t ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {\n\t\tint err = generic_osync_inode(inode, mapping, OSYNC_METADATA);\n\t\tif (err < 0)\n\t\t\twritten = err;\n\t}\n\treturn written;\n}","target":0,"code_token_length":740,"total_token_length":1071,"max_tokens_setting":2048} +{"idx":496378,"func":"CURLcode Curl_ossl_verifyhost(struct Curl_easy *data, struct connectdata *conn,\n X509 *server_cert)\n{\n bool matched = FALSE;\n int target = GEN_DNS; \/* target type, GEN_DNS or GEN_IPADD *\/\n size_t addrlen = 0;\n STACK_OF(GENERAL_NAME) *altnames;\n#ifdef ENABLE_IPV6\n struct in6_addr addr;\n#else\n struct in_addr addr;\n#endif\n CURLcode result = CURLE_OK;\n bool dNSName = FALSE; \/* if a dNSName field exists in the cert *\/\n bool iPAddress = FALSE; \/* if a iPAddress field exists in the cert *\/\n const char * const hostname = SSL_HOST_NAME();\n const char * const dispname = SSL_HOST_DISPNAME();\n size_t hostlen = strlen(hostname);\n\n#ifdef ENABLE_IPV6\n if(conn->bits.ipv6_ip &&\n Curl_inet_pton(AF_INET6, hostname, &addr)) {\n target = GEN_IPADD;\n addrlen = sizeof(struct in6_addr);\n }\n else\n#endif\n if(Curl_inet_pton(AF_INET, hostname, &addr)) {\n target = GEN_IPADD;\n addrlen = sizeof(struct in_addr);\n }\n\n \/* get a \"list\" of alternative names *\/\n altnames = X509_get_ext_d2i(server_cert, NID_subject_alt_name, NULL, NULL);\n\n if(altnames) {\n#ifdef OPENSSL_IS_BORINGSSL\n size_t numalts;\n size_t i;\n#else\n int numalts;\n int i;\n#endif\n bool dnsmatched = FALSE;\n bool ipmatched = FALSE;\n\n \/* get amount of alternatives, RFC2459 claims there MUST be at least\n one, but we don't depend on it... *\/\n numalts = sk_GENERAL_NAME_num(altnames);\n\n \/* loop through all alternatives - until a dnsmatch *\/\n for(i = 0; (i < numalts) && !dnsmatched; i++) {\n \/* get a handle to alternative name number i *\/\n const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);\n\n if(check->type == GEN_DNS)\n dNSName = TRUE;\n else if(check->type == GEN_IPADD)\n iPAddress = TRUE;\n\n \/* only check alternatives of the same type the target is *\/\n if(check->type == target) {\n \/* get data and length *\/\n const char *altptr = (char *)ASN1_STRING_get0_data(check->d.ia5);\n size_t altlen = (size_t) ASN1_STRING_length(check->d.ia5);\n\n switch(target) {\n case GEN_DNS: \/* name\/pattern comparison *\/\n \/* The OpenSSL man page explicitly says: \"In general it cannot be\n assumed that the data returned by ASN1_STRING_data() is null\n terminated or does not contain embedded nulls.\" But also that\n \"The actual format of the data will depend on the actual string\n type itself: for example for an IA5String the data will be ASCII\"\n\n It has been however verified that in 0.9.6 and 0.9.7, IA5String\n is always null-terminated.\n *\/\n if((altlen == strlen(altptr)) &&\n \/* if this isn't true, there was an embedded zero in the name\n string and we cannot match it. *\/\n subj_alt_hostcheck(data,\n altptr,\n altlen, hostname, hostlen, dispname)) {\n dnsmatched = TRUE;\n }\n break;\n\n case GEN_IPADD: \/* IP address comparison *\/\n \/* compare alternative IP address if the data chunk is the same size\n our server IP address is *\/\n if((altlen == addrlen) && !memcmp(altptr, &addr, altlen)) {\n ipmatched = TRUE;\n infof(data,\n \" subjectAltName: host \\\"%s\\\" matched cert's IP address!\",\n dispname);\n }\n break;\n }\n }\n }\n GENERAL_NAMES_free(altnames);\n\n if(dnsmatched || ipmatched)\n matched = TRUE;\n }\n\n if(matched)\n \/* an alternative name matched *\/\n ;\n else if(dNSName || iPAddress) {\n infof(data, \" subjectAltName does not match %s\", dispname);\n failf(data, \"SSL: no alternative certificate subject name matches \"\n \"target host name '%s'\", dispname);\n result = CURLE_PEER_FAILED_VERIFICATION;\n }\n else {\n \/* we have to look to the last occurrence of a commonName in the\n distinguished one to get the most significant one. *\/\n int i = -1;\n unsigned char *peer_CN = NULL;\n int peerlen = 0;\n\n \/* The following is done because of a bug in 0.9.6b *\/\n X509_NAME *name = X509_get_subject_name(server_cert);\n if(name) {\n int j;\n while((j = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0)\n i = j;\n }\n\n \/* we have the name entry and we will now convert this to a string\n that we can use for comparison. Doing this we support BMPstring,\n UTF8, etc. *\/\n\n if(i >= 0) {\n ASN1_STRING *tmp =\n X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i));\n\n \/* In OpenSSL 0.9.7d and earlier, ASN1_STRING_to_UTF8 fails if the input\n is already UTF-8 encoded. We check for this case and copy the raw\n string manually to avoid the problem. This code can be made\n conditional in the future when OpenSSL has been fixed. *\/\n if(tmp) {\n if(ASN1_STRING_type(tmp) == V_ASN1_UTF8STRING) {\n peerlen = ASN1_STRING_length(tmp);\n if(peerlen >= 0) {\n peer_CN = OPENSSL_malloc(peerlen + 1);\n if(peer_CN) {\n memcpy(peer_CN, ASN1_STRING_get0_data(tmp), peerlen);\n peer_CN[peerlen] = '\\0';\n }\n else\n result = CURLE_OUT_OF_MEMORY;\n }\n }\n else \/* not a UTF8 name *\/\n peerlen = ASN1_STRING_to_UTF8(&peer_CN, tmp);\n\n if(peer_CN && (curlx_uztosi(strlen((char *)peer_CN)) != peerlen)) {\n \/* there was a terminating zero before the end of string, this\n cannot match and we return failure! *\/\n failf(data, \"SSL: illegal cert name field\");\n result = CURLE_PEER_FAILED_VERIFICATION;\n }\n }\n }\n\n if(result)\n \/* error already detected, pass through *\/\n ;\n else if(!peer_CN) {\n failf(data,\n \"SSL: unable to obtain common name from peer certificate\");\n result = CURLE_PEER_FAILED_VERIFICATION;\n }\n else if(!Curl_cert_hostcheck((const char *)peer_CN,\n peerlen, hostname, hostlen)) {\n failf(data, \"SSL: certificate subject name '%s' does not match \"\n \"target host name '%s'\", peer_CN, dispname);\n result = CURLE_PEER_FAILED_VERIFICATION;\n }\n else {\n infof(data, \" common name: %s (matched)\", peer_CN);\n }\n if(peer_CN)\n OPENSSL_free(peer_CN);\n }\n\n return result;\n}","target":0,"code_token_length":1642,"total_token_length":1973,"max_tokens_setting":2048} +{"idx":490852,"func":"static pid_t do_cmd(char *cmd, char *machine, char *user, char **remote_argv, int remote_argc,\n\t\t int *f_in_p, int *f_out_p)\n{\n\tint i, argc = 0;\n\tchar *args[MAX_ARGS], *need_to_free = NULL;\n\tpid_t pid;\n\tint dash_l_set = 0;\n\n\tif (!read_batch && !local_server) {\n\t\tchar *t, *f, in_quote = '\\0';\n\t\tchar *rsh_env = getenv(RSYNC_RSH_ENV);\n\t\tif (!cmd)\n\t\t\tcmd = rsh_env;\n\t\tif (!cmd)\n\t\t\tcmd = RSYNC_RSH;\n\t\tcmd = need_to_free = strdup(cmd);\n\n\t\tfor (t = f = cmd; *f; f++) {\n\t\t\tif (*f == ' ')\n\t\t\t\tcontinue;\n\t\t\t\/* Comparison leaves rooms for server_options(). *\/\n\t\t\tif (argc >= MAX_ARGS - MAX_SERVER_ARGS)\n\t\t\t\tgoto arg_overflow;\n\t\t\targs[argc++] = t;\n\t\t\twhile (*f != ' ' || in_quote) {\n\t\t\t\tif (!*f) {\n\t\t\t\t\tif (in_quote) {\n\t\t\t\t\t\trprintf(FERROR,\n\t\t\t\t\t\t\t\"Missing trailing-%c in remote-shell command.\\n\",\n\t\t\t\t\t\t\tin_quote);\n\t\t\t\t\t\texit_cleanup(RERR_SYNTAX);\n\t\t\t\t\t}\n\t\t\t\t\tf--;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (*f == '\\'' || *f == '\"') {\n\t\t\t\t\tif (!in_quote) {\n\t\t\t\t\t\tin_quote = *f++;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (*f == in_quote && *++f != in_quote) {\n\t\t\t\t\t\tin_quote = '\\0';\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t*t++ = *f++;\n\t\t\t}\n\t\t\t*t++ = '\\0';\n\t\t}\n\n\t\t\/* NOTE: must preserve t == start of command name until the end of the args handling! *\/\n\t\tif ((t = strrchr(cmd, '\/')) != NULL)\n\t\t\tt++;\n\t\telse\n\t\t\tt = cmd;\n\n\t\t\/* Check to see if we've already been given '-l user' in the remote-shell command. *\/\n\t\tfor (i = 0; i < argc-1; i++) {\n\t\t\tif (!strcmp(args[i], \"-l\") && args[i+1][0] != '-')\n\t\t\t\tdash_l_set = 1;\n\t\t}\n\n#ifdef HAVE_REMSH\n\t\t\/* remsh (on HPUX) takes the arguments the other way around *\/\n\t\targs[argc++] = machine;\n\t\tif (user && !(daemon_connection && dash_l_set)) {\n\t\t\targs[argc++] = \"-l\";\n\t\t\targs[argc++] = user;\n\t\t}\n#else\n\t\tif (user && !(daemon_connection && dash_l_set)) {\n\t\t\targs[argc++] = \"-l\";\n\t\t\targs[argc++] = user;\n\t\t}\n#ifdef AF_INET\n\t\tif (default_af_hint == AF_INET && strcmp(t, \"ssh\") == 0)\n\t\t\targs[argc++] = \"-4\"; \/* we're using ssh so we can add a -4 option *\/\n#endif\n#ifdef AF_INET6\n\t\tif (default_af_hint == AF_INET6 && strcmp(t, \"ssh\") == 0)\n\t\t\targs[argc++] = \"-6\"; \/* we're using ssh so we can add a -6 option *\/\n#endif\n\t\targs[argc++] = machine;\n#endif\n\n\t\targs[argc++] = rsync_path;\n\n\t\tif (blocking_io < 0 && (strcmp(t, \"rsh\") == 0 || strcmp(t, \"remsh\") == 0))\n\t\t\tblocking_io = 1;\n\n\t\tif (daemon_connection > 0) {\n\t\t\targs[argc++] = \"--server\";\n\t\t\targs[argc++] = \"--daemon\";\n\t\t} else\n\t\t\tserver_options(args, &argc);\n\n\t\tif (argc >= MAX_ARGS - 2)\n\t\t\tgoto arg_overflow;\n\t}\n\n\targs[argc++] = \".\";\n\n\tif (!daemon_connection) {\n\t\twhile (remote_argc > 0) {\n\t\t\tif (argc >= MAX_ARGS - 1) {\n\t\t\t arg_overflow:\n\t\t\t\trprintf(FERROR, \"internal: args[] overflowed in do_cmd()\\n\");\n\t\t\t\texit_cleanup(RERR_SYNTAX);\n\t\t\t}\n\t\t\targs[argc++] = safe_arg(NULL, *remote_argv++);\n\t\t\tremote_argc--;\n\t\t}\n\t}\n\n\targs[argc] = NULL;\n\n\tif (DEBUG_GTE(CMD, 2)) {\n\t\tfor (i = 0; i < argc; i++)\n\t\t\trprintf(FCLIENT, \"cmd[%d]=%s \", i, args[i]);\n\t\trprintf(FCLIENT, \"\\n\");\n\t}\n\n\tif (read_batch) {\n\t\tint from_gen_pipe[2];\n\t\tset_allow_inc_recurse();\n\t\tif (fd_pair(from_gen_pipe) < 0) {\n\t\t\trsyserr(FERROR, errno, \"pipe\");\n\t\t\texit_cleanup(RERR_IPC);\n\t\t}\n\t\tbatch_gen_fd = from_gen_pipe[0];\n\t\t*f_out_p = from_gen_pipe[1];\n\t\t*f_in_p = batch_fd;\n\t\tpid = (pid_t)-1; \/* no child pid *\/\n#ifdef ICONV_CONST\n\t\tsetup_iconv();\n#endif\n\t\ttrust_sender_filter = 1;\n\t} else if (local_server) {\n\t\t\/* If the user didn't request --[no-]whole-file, force\n\t\t * it on, but only if we're not batch processing. *\/\n\t\tif (whole_file < 0 && !write_batch)\n\t\t\twhole_file = 1;\n\t\tset_allow_inc_recurse();\n\t\tpid = local_child(argc, args, f_in_p, f_out_p, child_main);\n#ifdef ICONV_CONST\n\t\tsetup_iconv();\n#endif\n\t} else {\n\t\tpid = piped_child(args, f_in_p, f_out_p);\n#ifdef ICONV_CONST\n\t\tsetup_iconv();\n#endif\n\t\tif (protect_args && !daemon_connection)\n\t\t\tsend_protected_args(*f_out_p, args);\n\t}\n\n\tif (need_to_free)\n\t\tfree(need_to_free);\n\n\treturn pid;\n}","target":0,"code_token_length":1269,"total_token_length":1600,"max_tokens_setting":2048} +{"idx":376759,"func":"void HGraphBuilder::VisitCompareOperation(CompareOperation* expr) {\n ASSERT(!HasStackOverflow());\n ASSERT(current_block() != NULL);\n ASSERT(current_block()->HasPredecessor());\n if (IsClassOfTest(expr)) {\n CallRuntime* call = expr->left()->AsCallRuntime();\n ASSERT(call->arguments()->length() == 1);\n CHECK_ALIVE(VisitForValue(call->arguments()->at(0)));\n HValue* value = Pop();\n Literal* literal = expr->right()->AsLiteral();\n Handle rhs = Handle::cast(literal->handle());\n HClassOfTestAndBranch* instr =\n new(zone()) HClassOfTestAndBranch(value, rhs);\n instr->set_position(expr->position());\n return ast_context()->ReturnControl(instr, expr->id());\n }\n\n TypeInfo type_info = oracle()->CompareType(expr);\n \/\/ Check if this expression was ever executed according to type feedback.\n \/\/ Note that for the special typeof\/null\/undefined cases we get unknown here.\n if (type_info.IsUninitialized()) {\n AddInstruction(new(zone()) HSoftDeoptimize);\n current_block()->MarkAsDeoptimizing();\n type_info = TypeInfo::Unknown();\n }\n\n CHECK_ALIVE(VisitForValue(expr->left()));\n CHECK_ALIVE(VisitForValue(expr->right()));\n\n HValue* context = environment()->LookupContext();\n HValue* right = Pop();\n HValue* left = Pop();\n Token::Value op = expr->op();\n\n HTypeof* typeof_expr = NULL;\n Handle check;\n if (IsLiteralCompareTypeof(left, op, right, &typeof_expr, &check)) {\n return HandleLiteralCompareTypeof(expr, typeof_expr, check);\n }\n HValue* sub_expr = NULL;\n Factory* f = graph()->isolate()->factory();\n if (IsLiteralCompareNil(left, op, right, f->undefined_value(), &sub_expr)) {\n return HandleLiteralCompareNil(expr, sub_expr, kUndefinedValue);\n }\n if (IsLiteralCompareNil(left, op, right, f->null_value(), &sub_expr)) {\n return HandleLiteralCompareNil(expr, sub_expr, kNullValue);\n }\n if (IsLiteralCompareBool(left, op, right)) {\n HCompareObjectEqAndBranch* result =\n new(zone()) HCompareObjectEqAndBranch(left, right);\n result->set_position(expr->position());\n return ast_context()->ReturnControl(result, expr->id());\n }\n\n if (op == Token::INSTANCEOF) {\n \/\/ Check to see if the rhs of the instanceof is a global function not\n \/\/ residing in new space. If it is we assume that the function will stay the\n \/\/ same.\n Handle target = Handle::null();\n VariableProxy* proxy = expr->right()->AsVariableProxy();\n bool global_function = (proxy != NULL) && proxy->var()->IsUnallocated();\n if (global_function &&\n info()->has_global_object() &&\n !info()->global_object()->IsAccessCheckNeeded()) {\n Handle name = proxy->name();\n Handle global(info()->global_object());\n LookupResult lookup(isolate());\n global->Lookup(*name, &lookup);\n if (lookup.IsNormal() && lookup.GetValue()->IsJSFunction()) {\n Handle candidate(JSFunction::cast(lookup.GetValue()));\n \/\/ If the function is in new space we assume it's more likely to\n \/\/ change and thus prefer the general IC code.\n if (!isolate()->heap()->InNewSpace(*candidate)) {\n target = candidate;\n }\n }\n }\n\n \/\/ If the target is not null we have found a known global function that is\n \/\/ assumed to stay the same for this instanceof.\n if (target.is_null()) {\n HInstanceOf* result = new(zone()) HInstanceOf(context, left, right);\n result->set_position(expr->position());\n return ast_context()->ReturnInstruction(result, expr->id());\n } else {\n AddInstruction(new(zone()) HCheckFunction(right, target));\n HInstanceOfKnownGlobal* result =\n new(zone()) HInstanceOfKnownGlobal(context, left, target);\n result->set_position(expr->position());\n return ast_context()->ReturnInstruction(result, expr->id());\n }\n } else if (op == Token::IN) {\n HIn* result = new(zone()) HIn(context, left, right);\n result->set_position(expr->position());\n return ast_context()->ReturnInstruction(result, expr->id());\n } else if (type_info.IsNonPrimitive()) {\n switch (op) {\n case Token::EQ:\n case Token::EQ_STRICT: {\n \/\/ Can we get away with map check and not instance type check?\n Handle map = oracle()->GetCompareMap(expr);\n if (!map.is_null()) {\n AddInstruction(new(zone()) HCheckNonSmi(left));\n AddInstruction(HCheckMaps::NewWithTransitions(left, map, zone()));\n AddInstruction(new(zone()) HCheckNonSmi(right));\n AddInstruction(HCheckMaps::NewWithTransitions(right, map, zone()));\n HCompareObjectEqAndBranch* result =\n new(zone()) HCompareObjectEqAndBranch(left, right);\n result->set_position(expr->position());\n return ast_context()->ReturnControl(result, expr->id());\n } else {\n AddInstruction(new(zone()) HCheckNonSmi(left));\n AddInstruction(HCheckInstanceType::NewIsSpecObject(left, zone()));\n AddInstruction(new(zone()) HCheckNonSmi(right));\n AddInstruction(HCheckInstanceType::NewIsSpecObject(right, zone()));\n HCompareObjectEqAndBranch* result =\n new(zone()) HCompareObjectEqAndBranch(left, right);\n result->set_position(expr->position());\n return ast_context()->ReturnControl(result, expr->id());\n }\n }\n default:\n return Bailout(\"Unsupported non-primitive compare\");\n }\n } else if (type_info.IsString() && oracle()->IsSymbolCompare(expr) &&\n (op == Token::EQ || op == Token::EQ_STRICT)) {\n AddInstruction(new(zone()) HCheckNonSmi(left));\n AddInstruction(HCheckInstanceType::NewIsSymbol(left, zone()));\n AddInstruction(new(zone()) HCheckNonSmi(right));\n AddInstruction(HCheckInstanceType::NewIsSymbol(right, zone()));\n HCompareObjectEqAndBranch* result =\n new(zone()) HCompareObjectEqAndBranch(left, right);\n result->set_position(expr->position());\n return ast_context()->ReturnControl(result, expr->id());\n } else {\n Representation r = ToRepresentation(type_info);\n if (r.IsTagged()) {\n HCompareGeneric* result =\n new(zone()) HCompareGeneric(context, left, right, op);\n result->set_position(expr->position());\n return ast_context()->ReturnInstruction(result, expr->id());\n } else {\n HCompareIDAndBranch* result =\n new(zone()) HCompareIDAndBranch(left, right, op);\n result->set_position(expr->position());\n result->SetInputRepresentation(r);\n return ast_context()->ReturnControl(result, expr->id());\n }\n }\n}","target":0,"code_token_length":1546,"total_token_length":1877,"max_tokens_setting":2048} +{"idx":416616,"func":"int gx_device_unsubclass(gx_device *dev)\n{\n generic_subclass_data *psubclass_data;\n gx_device *parent, *child;\n gs_memory_struct_type_t *a_std = 0, *b_std = 0;\n int dynamic, ref_count;\n\n \/* This should not happen... *\/\n if (!dev)\n return 0;\n\n ref_count = dev->rc.ref_count;\n child = dev->child;\n psubclass_data = (generic_subclass_data *)dev->subclass_data;\n parent = dev->parent;\n dynamic = dev->stype_is_dynamic;\n\n \/* We need to account for the fact that we are removing ourselves from\n * the device chain after a clist device has been pushed, due to a\n * compositor action. Since we patched the clist 'create_compositor'\n * method (and target device) when it was pushed.\n * A point to note; we *don't* want to change the forwarding device's\n * 'target', because when we copy the child up to replace 'this' device\n * we do still want the forwarding device to point here. NB its the *child*\n * device that goes away.\n *\/\n if (psubclass_data != NULL && psubclass_data->forwarding_dev != NULL && psubclass_data->saved_compositor_method)\n psubclass_data->forwarding_dev->procs.create_compositor = psubclass_data->saved_compositor_method;\n\n \/* If ths device's stype is dynamically allocated, keep a copy of it\n * in case we might need it.\n *\/\n if (dynamic) {\n a_std = (gs_memory_struct_type_t *)dev->stype;\n if (child)\n *a_std = *child->stype;\n }\n\n \/* If ths device has any private storage, free it now *\/\n if (psubclass_data)\n gs_free_object(dev->memory->non_gc_memory, psubclass_data, \"subclass memory for first-last page\");\n\n \/* Copy the child device into ths device's memory *\/\n if (child) {\n b_std = (gs_memory_struct_type_t *)dev->stype;\n rc_decrement(dev->icc_struct, \"unsubclass device\");\n rc_increment(child->icc_struct);\n memcpy(dev, child, child->stype->ssize);\n \/* Patch back the 'stype' in the memory manager *\/\n gs_set_object_type(child->memory, dev, b_std);\n\n dev->stype = b_std;\n \/* The reference count of the subclassing device may have been changed\n * (eg graphics states pointing to it) after we subclassed the device. We\n * need to ensure that we do not overwrite this when we copy back the subclassed\n * device.\n *\/\n dev->rc.ref_count = ref_count;\n\n \/* If we have a chain of devices, make sure the chain beond the device we're unsubclassing\n * doesn't get broken, we needd to detach the lower chain and reattach it at the new\n * highest level\n *\/\n if (child->child)\n child->child->parent = dev;\n child->parent->child = child->child;\n }\n\n \/* How can we have a subclass device with no child ? Simples; when we hit the end of job\n * restore, the devices are not freed in device chain order. To make sure we don't end up\n * following stale pointers, when a device is freed we remove it from the chain and update\n * any danlging poitners to NULL. When we later free the remaining devices its possible that\n * their child pointer can then be NULL.\n *\/\n if (child) {\n if (child->icc_struct)\n rc_decrement(child->icc_struct, \"gx_unsubclass_device, icc_struct\");\n if (child->PageList)\n rc_decrement(child->PageList, \"gx_unsubclass_device, PageList\");\n \/* we cannot afford to free the child device if its stype is not dynamic because\n * we can't 'null' the finalise routine, and we cannot permit the device to be finalised\n * because we have copied it up one level, not discarded it.\n * (this shouldn't happen! Child devices are always created with a dynamic stype)\n * If this ever happens garbage collecton will eventually clean up the memory.\n *\/\n if (child->stype_is_dynamic) {\n \/* Make sure that nothing will tyr to follow the device chain, just security here *\/\n child->parent = NULL;\n child->child = NULL;\n \/* Make certainthe memory will be freed, zap the reference count *\/\n child->rc.ref_count = 0;\n \/* We *don't* want to run the finalize routine. This would free the stype and\n * properly handle the icc_struct and PageList, but for devices with a custom\n * finalize (eg psdcmyk) it might also free memory it had allocated, and we're\n * still pointing at that memory in the parent.\n * The indirection through a variable is just to get rid of const warnings.\n *\/\n b_std = (gs_memory_struct_type_t *)child->stype;\n b_std->finalize = NULL;\n \/* Having patched the stype, we need to make sure the memory manager uses it.\n * It keeps a copy in its own data structure, and would use that copy, which would\n * mean it would call the finalize routine that we just patched out.\n *\/\n gs_set_object_type(dev->memory->stable_memory, child, b_std);\n \/* Now (finally) free the child memory *\/\n gs_free_object(dev->memory->stable_memory, child, \"gx_unsubclass_device(device)\");\n \/* And the stype for it *\/\n gs_free_const_object(dev->memory->non_gc_memory, b_std, \"gs_device_unsubclass(stype)\");\n child = 0;\n }\n }\n if(child)\n child->parent = dev;\n dev->parent = parent;\n\n \/* If this device has a dynamic stype, we wnt to keep using it, but we copied\n * the stype pointer from the child when we copied the rest of the device. So\n * we update the stype pointer with the saved pointer to this device's stype.\n *\/\n if (dynamic) {\n dev->stype = a_std;\n dev->stype_is_dynamic = 1;\n } else {\n dev->stype_is_dynamic = 0;\n }\n\n return 0;\n}","target":0,"code_token_length":1397,"total_token_length":1728,"max_tokens_setting":2048} +{"idx":5664,"func":"static int read_data(void *opaque, uint8_t *buf, int buf_size)\n{\n struct playlist *v = opaque;\n HLSContext *c = v->parent->priv_data;\n int ret, i;\n int just_opened = 0;\n\nrestart:\n if (!v->needed)\n return AVERROR_EOF;\n\n if (!v->input) {\n int64_t reload_interval;\n struct segment *seg;\n\n \/* Check that the playlist is still needed before opening a new\n * segment. *\/\n if (v->ctx && v->ctx->nb_streams) {\n v->needed = 0;\n for (i = 0; i < v->n_main_streams; i++) {\n if (v->main_streams[i]->discard < AVDISCARD_ALL) {\n v->needed = 1;\n break;\n }\n }\n }\n if (!v->needed) {\n av_log(v->parent, AV_LOG_INFO, \"No longer receiving playlist %d\\n\",\n v->index);\n return AVERROR_EOF;\n }\n\n \/* If this is a live stream and the reload interval has elapsed since\n * the last playlist reload, reload the playlists now. *\/\n reload_interval = default_reload_interval(v);\n\nreload:\n if (!v->finished &&\n av_gettime_relative() - v->last_load_time >= reload_interval) {\n if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) {\n av_log(v->parent, AV_LOG_WARNING, \"Failed to reload playlist %d\\n\",\n v->index);\n return ret;\n }\n \/* If we need to reload the playlist again below (if\n * there's still no more segments), switch to a reload\n * interval of half the target duration. *\/\n reload_interval = v->target_duration \/ 2;\n }\n if (v->cur_seq_no < v->start_seq_no) {\n av_log(NULL, AV_LOG_WARNING,\n \"skipping %d segments ahead, expired from playlists\\n\",\n v->start_seq_no - v->cur_seq_no);\n v->cur_seq_no = v->start_seq_no;\n }\n if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {\n if (v->finished)\n return AVERROR_EOF;\n while (av_gettime_relative() - v->last_load_time < reload_interval) {\n if (ff_check_interrupt(c->interrupt_callback))\n return AVERROR_EXIT;\n av_usleep(100*1000);\n }\n \/* Enough time has elapsed since the last reload *\/\n goto reload;\n }\n\n seg = current_segment(v);\n\n \/* load\/update Media Initialization Section, if any *\/\n ret = update_init_section(v, seg);\n if (ret)\n return ret;\n\n ret = open_input(c, v, seg);\n if (ret < 0) {\n if (ff_check_interrupt(c->interrupt_callback))\n return AVERROR_EXIT;\n av_log(v->parent, AV_LOG_WARNING, \"Failed to open segment of playlist %d\\n\",\n v->index);\n v->cur_seq_no += 1;\n goto reload;\n }\n just_opened = 1;\n }\n\n if (v->init_sec_buf_read_offset < v->init_sec_data_len) {\n \/* Push init section out first before first actual segment *\/\n int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);\n memcpy(buf, v->init_sec_buf, copy_size);\n v->init_sec_buf_read_offset += copy_size;\n return copy_size;\n }\n\n ret = read_from_url(v, current_segment(v), buf, buf_size, READ_NORMAL);\n if (ret > 0) {\n if (just_opened && v->is_id3_timestamped != 0) {\n \/* Intercept ID3 tags here, elementary audio streams are required\n * to convey timestamps using them in the beginning of each segment. *\/\n intercept_id3(v, buf, buf_size, &ret);\n }\n\n return ret;\n }\n ff_format_io_close(v->parent, &v->input);\n v->cur_seq_no++;\n\n c->cur_seq_no = v->cur_seq_no;\n\n goto restart;\n}","target":1,"code_token_length":919,"total_token_length":1250,"max_tokens_setting":2048} +{"idx":68088,"func":"sampled_guards_update_from_consensus(guard_selection_t *gs)\n{\n tor_assert(gs);\n const int REMOVE_UNLISTED_GUARDS_AFTER =\n (get_remove_unlisted_guards_after_days() * 86400);\n const int unlisted_since_slop = REMOVE_UNLISTED_GUARDS_AFTER \/ 5;\n\n \/\/ It's important to use only a live consensus here; we don't want to\n \/\/ make changes based on anything expired or old.\n if (live_consensus_is_missing(gs)) {\n log_info(LD_GUARD, \"Not updating the sample guard set; we have \"\n \"no live consensus.\");\n return;\n }\n log_info(LD_GUARD, \"Updating sampled guard status based on received \"\n \"consensus.\");\n\n int n_changes = 0;\n\n \/* First: Update listed\/unlisted. *\/\n SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {\n \/* XXXX #20827 check ed ID too *\/\n const int is_listed = entry_guard_is_listed(gs, guard);\n\n if (is_listed && ! guard->currently_listed) {\n ++n_changes;\n guard->currently_listed = 1;\n guard->unlisted_since_date = 0;\n log_info(LD_GUARD, \"Sampled guard %s is now listed again.\",\n entry_guard_describe(guard));\n } else if (!is_listed && guard->currently_listed) {\n ++n_changes;\n guard->currently_listed = 0;\n guard->unlisted_since_date = randomize_time(approx_time(),\n unlisted_since_slop);\n log_info(LD_GUARD, \"Sampled guard %s is now unlisted.\",\n entry_guard_describe(guard));\n } else if (is_listed && guard->currently_listed) {\n log_debug(LD_GUARD, \"Sampled guard %s is still listed.\",\n entry_guard_describe(guard));\n } else {\n tor_assert(! is_listed && ! guard->currently_listed);\n log_debug(LD_GUARD, \"Sampled guard %s is still unlisted.\",\n entry_guard_describe(guard));\n }\n\n \/* Clean up unlisted_since_date, just in case. *\/\n if (guard->currently_listed && guard->unlisted_since_date) {\n ++n_changes;\n guard->unlisted_since_date = 0;\n log_warn(LD_BUG, \"Sampled guard %s was listed, but with \"\n \"unlisted_since_date set. Fixing.\",\n entry_guard_describe(guard));\n } else if (!guard->currently_listed && ! guard->unlisted_since_date) {\n ++n_changes;\n guard->unlisted_since_date = randomize_time(approx_time(),\n unlisted_since_slop);\n log_warn(LD_BUG, \"Sampled guard %s was unlisted, but with \"\n \"unlisted_since_date unset. Fixing.\",\n entry_guard_describe(guard));\n }\n } SMARTLIST_FOREACH_END(guard);\n\n const time_t remove_if_unlisted_since =\n approx_time() - REMOVE_UNLISTED_GUARDS_AFTER;\n const time_t maybe_remove_if_sampled_before =\n approx_time() - get_guard_lifetime();\n const time_t remove_if_confirmed_before =\n approx_time() - get_guard_confirmed_min_lifetime();\n\n \/* Then: remove the ones that have been junk for too long *\/\n SMARTLIST_FOREACH_BEGIN(gs->sampled_entry_guards, entry_guard_t *, guard) {\n int rmv = 0;\n\n if (guard->currently_listed == 0 &&\n guard->unlisted_since_date < remove_if_unlisted_since) {\n \/*\n \"We have a live consensus, and {IS_LISTED} is false, and\n {FIRST_UNLISTED_AT} is over {REMOVE_UNLISTED_GUARDS_AFTER}\n days in the past.\"\n *\/\n log_info(LD_GUARD, \"Removing sampled guard %s: it has been unlisted \"\n \"for over %d days\", entry_guard_describe(guard),\n get_remove_unlisted_guards_after_days());\n rmv = 1;\n } else if (guard->sampled_on_date < maybe_remove_if_sampled_before) {\n \/* We have a live consensus, and {ADDED_ON_DATE} is over\n {GUARD_LIFETIME} ago, *and* {CONFIRMED_ON_DATE} is either\n \"never\", or over {GUARD_CONFIRMED_MIN_LIFETIME} ago.\n *\/\n if (guard->confirmed_on_date == 0) {\n rmv = 1;\n log_info(LD_GUARD, \"Removing sampled guard %s: it was sampled \"\n \"over %d days ago, but never confirmed.\",\n entry_guard_describe(guard),\n get_guard_lifetime() \/ 86400);\n } else if (guard->confirmed_on_date < remove_if_confirmed_before) {\n rmv = 1;\n log_info(LD_GUARD, \"Removing sampled guard %s: it was sampled \"\n \"over %d days ago, and confirmed over %d days ago.\",\n entry_guard_describe(guard),\n get_guard_lifetime() \/ 86400,\n get_guard_confirmed_min_lifetime() \/ 86400);\n }\n }\n\n if (rmv) {\n ++n_changes;\n SMARTLIST_DEL_CURRENT(gs->sampled_entry_guards, guard);\n remove_guard_from_confirmed_and_primary_lists(gs, guard);\n entry_guard_free(guard);\n }\n } SMARTLIST_FOREACH_END(guard);\n\n if (n_changes) {\n gs->primary_guards_up_to_date = 0;\n entry_guards_update_filtered_sets(gs);\n \/* We don't need to rebuild the confirmed list right here -- we may have\n * removed confirmed guards above, but we can't have added any new\n * confirmed guards.\n *\/\n entry_guards_changed_for_guard_selection(gs);\n }\n}","target":0,"code_token_length":1287,"total_token_length":1618,"max_tokens_setting":2048} +{"idx":69009,"func":"static int i40e_config_netdev(struct i40e_vsi *vsi)\n{\n\tstruct i40e_pf *pf = vsi->back;\n\tstruct i40e_hw *hw = &pf->hw;\n\tstruct i40e_netdev_priv *np;\n\tstruct net_device *netdev;\n\tu8 broadcast[ETH_ALEN];\n\tu8 mac_addr[ETH_ALEN];\n\tint etherdev_size;\n\tnetdev_features_t hw_enc_features;\n\tnetdev_features_t hw_features;\n\n\tetherdev_size = sizeof(struct i40e_netdev_priv);\n\tnetdev = alloc_etherdev_mq(etherdev_size, vsi->alloc_queue_pairs);\n\tif (!netdev)\n\t\treturn -ENOMEM;\n\n\tvsi->netdev = netdev;\n\tnp = netdev_priv(netdev);\n\tnp->vsi = vsi;\n\n\thw_enc_features = NETIF_F_SG\t\t\t|\n\t\t\t NETIF_F_IP_CSUM\t\t|\n\t\t\t NETIF_F_IPV6_CSUM\t\t|\n\t\t\t NETIF_F_HIGHDMA\t\t|\n\t\t\t NETIF_F_SOFT_FEATURES\t\t|\n\t\t\t NETIF_F_TSO\t\t\t|\n\t\t\t NETIF_F_TSO_ECN\t\t|\n\t\t\t NETIF_F_TSO6\t\t\t|\n\t\t\t NETIF_F_GSO_GRE\t\t|\n\t\t\t NETIF_F_GSO_GRE_CSUM\t\t|\n\t\t\t NETIF_F_GSO_PARTIAL\t\t|\n\t\t\t NETIF_F_GSO_IPXIP4\t\t|\n\t\t\t NETIF_F_GSO_IPXIP6\t\t|\n\t\t\t NETIF_F_GSO_UDP_TUNNEL\t|\n\t\t\t NETIF_F_GSO_UDP_TUNNEL_CSUM\t|\n\t\t\t NETIF_F_SCTP_CRC\t\t|\n\t\t\t NETIF_F_RXHASH\t\t|\n\t\t\t NETIF_F_RXCSUM\t\t|\n\t\t\t 0;\n\n\tif (!(pf->hw_features & I40E_HW_OUTER_UDP_CSUM_CAPABLE))\n\t\tnetdev->gso_partial_features |= NETIF_F_GSO_UDP_TUNNEL_CSUM;\n\n\tnetdev->gso_partial_features |= NETIF_F_GSO_GRE_CSUM;\n\n\tnetdev->hw_enc_features |= hw_enc_features;\n\n\t\/* record features VLANs can make use of *\/\n\tnetdev->vlan_features |= hw_enc_features | NETIF_F_TSO_MANGLEID;\n\n\t\/* enable macvlan offloads *\/\n\tnetdev->hw_features |= NETIF_F_HW_L2FW_DOFFLOAD;\n\n\thw_features = hw_enc_features\t\t|\n\t\t NETIF_F_HW_VLAN_CTAG_TX\t|\n\t\t NETIF_F_HW_VLAN_CTAG_RX;\n\n\tif (!(pf->flags & I40E_FLAG_MFP_ENABLED))\n\t\thw_features |= NETIF_F_NTUPLE | NETIF_F_HW_TC;\n\n\tnetdev->hw_features |= hw_features;\n\n\tnetdev->features |= hw_features | NETIF_F_HW_VLAN_CTAG_FILTER;\n\tnetdev->hw_enc_features |= NETIF_F_TSO_MANGLEID;\n\n\tif (vsi->type == I40E_VSI_MAIN) {\n\t\tSET_NETDEV_DEV(netdev, &pf->pdev->dev);\n\t\tether_addr_copy(mac_addr, hw->mac.perm_addr);\n\t\t\/* The following steps are necessary for two reasons. First,\n\t\t * some older NVM configurations load a default MAC-VLAN\n\t\t * filter that will accept any tagged packet, and we want to\n\t\t * replace this with a normal filter. Additionally, it is\n\t\t * possible our MAC address was provided by the platform using\n\t\t * Open Firmware or similar.\n\t\t *\n\t\t * Thus, we need to remove the default filter and install one\n\t\t * specific to the MAC address.\n\t\t *\/\n\t\ti40e_rm_default_mac_filter(vsi, mac_addr);\n\t\tspin_lock_bh(&vsi->mac_filter_hash_lock);\n\t\ti40e_add_mac_filter(vsi, mac_addr);\n\t\tspin_unlock_bh(&vsi->mac_filter_hash_lock);\n\t} else {\n\t\t\/* Relate the VSI_VMDQ name to the VSI_MAIN name. Note that we\n\t\t * are still limited by IFNAMSIZ, but we're adding 'v%d\\0' to\n\t\t * the end, which is 4 bytes long, so force truncation of the\n\t\t * original name by IFNAMSIZ - 4\n\t\t *\/\n\t\tsnprintf(netdev->name, IFNAMSIZ, \"%.*sv%%d\",\n\t\t\t IFNAMSIZ - 4,\n\t\t\t pf->vsi[pf->lan_vsi]->netdev->name);\n\t\teth_random_addr(mac_addr);\n\n\t\tspin_lock_bh(&vsi->mac_filter_hash_lock);\n\t\ti40e_add_mac_filter(vsi, mac_addr);\n\t\tspin_unlock_bh(&vsi->mac_filter_hash_lock);\n\t}\n\n\t\/* Add the broadcast filter so that we initially will receive\n\t * broadcast packets. Note that when a new VLAN is first added the\n\t * driver will convert all filters marked I40E_VLAN_ANY into VLAN\n\t * specific filters as part of transitioning into \"vlan\" operation.\n\t * When more VLANs are added, the driver will copy each existing MAC\n\t * filter and add it for the new VLAN.\n\t *\n\t * Broadcast filters are handled specially by\n\t * i40e_sync_filters_subtask, as the driver must to set the broadcast\n\t * promiscuous bit instead of adding this directly as a MAC\/VLAN\n\t * filter. The subtask will update the correct broadcast promiscuous\n\t * bits as VLANs become active or inactive.\n\t *\/\n\teth_broadcast_addr(broadcast);\n\tspin_lock_bh(&vsi->mac_filter_hash_lock);\n\ti40e_add_mac_filter(vsi, broadcast);\n\tspin_unlock_bh(&vsi->mac_filter_hash_lock);\n\n\tether_addr_copy(netdev->dev_addr, mac_addr);\n\tether_addr_copy(netdev->perm_addr, mac_addr);\n\n\t\/* i40iw_net_event() reads 16 bytes from neigh->primary_key *\/\n\tnetdev->neigh_priv_len = sizeof(u32) * 4;\n\n\tnetdev->priv_flags |= IFF_UNICAST_FLT;\n\tnetdev->priv_flags |= IFF_SUPP_NOFCS;\n\t\/* Setup netdev TC information *\/\n\ti40e_vsi_config_netdev_tc(vsi, vsi->tc_config.enabled_tc);\n\n\tnetdev->netdev_ops = &i40e_netdev_ops;\n\tnetdev->watchdog_timeo = 5 * HZ;\n\ti40e_set_ethtool_ops(netdev);\n\n\t\/* MTU range: 68 - 9706 *\/\n\tnetdev->min_mtu = ETH_MIN_MTU;\n\tnetdev->max_mtu = I40E_MAX_RXBUFFER - I40E_PACKET_HDR_PAD;\n\n\treturn 0;\n}","target":0,"code_token_length":1413,"total_token_length":1744,"max_tokens_setting":2048} +{"idx":300116,"func":"inline void Mean(const tflite::MeanParams& op_params,\n const RuntimeShape& unextended_input_shape,\n const uint8_t* input_data, int32 input_zero_point,\n float input_scale, const RuntimeShape& unextended_output_shape,\n uint8_t* output_data, int32 output_zero_point,\n float output_scale, CpuBackendContext* cpu_backend_context) {\n ruy::profiler::ScopeLabel label(\"Mean4D\/Uint8\");\n \/\/ Current implementation only supports dimension equals 4 and simultaneous\n \/\/ reduction over width and height.\n TFLITE_CHECK_EQ(unextended_input_shape.DimensionsCount(), 4);\n TFLITE_CHECK_LE(unextended_output_shape.DimensionsCount(), 4);\n const RuntimeShape input_shape =\n RuntimeShape::ExtendedShape(4, unextended_input_shape);\n const RuntimeShape output_shape =\n RuntimeShape::ExtendedShape(4, unextended_output_shape);\n const int output_height = output_shape.Dims(1);\n const int output_width = output_shape.Dims(2);\n const int output_depth = output_shape.Dims(3);\n\n TFLITE_CHECK_EQ(op_params.axis_count, 2);\n TFLITE_CHECK((op_params.axis[0] == 1 && op_params.axis[1] == 2) ||\n (op_params.axis[0] == 2 && op_params.axis[1] == 1));\n TFLITE_CHECK_EQ(output_height, 1);\n TFLITE_CHECK_EQ(output_width, 1);\n\n const int input_height = input_shape.Dims(1);\n const int input_width = input_shape.Dims(2);\n const float num_elements_in_axis = input_width * input_height;\n\n float temp = input_zero_point * input_scale \/ output_scale;\n temp = temp > 0 ? temp + 0.5f : temp - 0.5f;\n int32_t bias = output_zero_point - static_cast(temp);\n float real_scale = input_scale \/ (num_elements_in_axis * output_scale);\n\n int32 multiplier, shift;\n QuantizeMultiplier(real_scale, &multiplier, &shift);\n\n constexpr int kMinDepthPerThread = 8;\n int thread_count = output_depth \/ kMinDepthPerThread;\n thread_count = thread_count > 0 ? thread_count : 1;\n const int capped_thread_count =\n std::min(thread_count, cpu_backend_context->max_num_threads());\n\n if (capped_thread_count == 1) {\n MeanImpl(op_params, input_shape, input_data, multiplier, shift, bias,\n output_shape, output_data, 0, output_depth);\n } else {\n \/\/ Instead parallel for batch, we loop for the output_depth since batch\n \/\/ is typical 1.\n std::vector tasks;\n \/\/ TODO(b\/131746020) don't create new heap allocations every time.\n \/\/ At least we make it a single heap allocation by using reserve().\n tasks.reserve(capped_thread_count);\n int depth_start = 0;\n for (int i = 0; i < capped_thread_count; ++i) {\n \/\/ Try to distribute the tasks as even as possible.\n int depth_end = depth_start +\n (output_depth - depth_start) \/ (capped_thread_count - i);\n tasks.emplace_back(op_params, input_shape, input_data, multiplier, shift,\n bias, output_shape, output_data, depth_start,\n depth_end);\n depth_start = depth_end;\n }\n cpu_backend_threadpool::Execute(tasks.size(), tasks.data(),\n cpu_backend_context);\n }\n}","target":0,"code_token_length":784,"total_token_length":1115,"max_tokens_setting":2048} +{"idx":316509,"func":"long Segment::ParseCues(long long off, long long& pos, long& len) {\n if (m_pCues)\n return 0; \/\/ success\n\n if (off < 0)\n return -1;\n\n long long total, avail;\n\n const int status = m_pReader->Length(&total, &avail);\n\n if (status < 0) \/\/ error\n return status;\n\n assert((total < 0) || (avail <= total));\n\n pos = m_start + off;\n\n if ((total < 0) || (pos >= total))\n return 1; \/\/ don't bother parsing cues\n\n const long long element_start = pos;\n const long long segment_stop = (m_size < 0) ? -1 : m_start + m_size;\n\n if ((pos + 1) > avail) {\n len = 1;\n return E_BUFFER_NOT_FULL;\n }\n\n long long result = GetUIntLength(m_pReader, pos, len);\n\n if (result < 0) \/\/ error\n return static_cast(result);\n\n if (result > 0) \/\/ underflow (weird)\n {\n len = 1;\n return E_BUFFER_NOT_FULL;\n }\n\n if ((segment_stop >= 0) && ((pos + len) > segment_stop))\n return E_FILE_FORMAT_INVALID;\n\n if ((pos + len) > avail)\n return E_BUFFER_NOT_FULL;\n\n const long long idpos = pos;\n\n const long long id = ReadID(m_pReader, idpos, len);\n\n if (id != 0x0C53BB6B) \/\/ Cues ID\n return E_FILE_FORMAT_INVALID;\n\n pos += len; \/\/ consume ID\n assert((segment_stop < 0) || (pos <= segment_stop));\n\n\n if ((pos + 1) > avail) {\n len = 1;\n return E_BUFFER_NOT_FULL;\n }\n\n result = GetUIntLength(m_pReader, pos, len);\n\n if (result < 0) \/\/ error\n return static_cast(result);\n\n if (result > 0) \/\/ underflow (weird)\n {\n len = 1;\n return E_BUFFER_NOT_FULL;\n }\n\n if ((segment_stop >= 0) && ((pos + len) > segment_stop))\n return E_FILE_FORMAT_INVALID;\n\n if ((pos + len) > avail)\n return E_BUFFER_NOT_FULL;\n\n const long long size = ReadUInt(m_pReader, pos, len);\n\n if (size < 0) \/\/ error\n return static_cast(size);\n\n if (size == 0) \/\/ weird, although technically not illegal\n return 1; \/\/ done\n\n pos += len; \/\/ consume length of size of element\n assert((segment_stop < 0) || (pos <= segment_stop));\n\n\n const long long element_stop = pos + size;\n\n if ((segment_stop >= 0) && (element_stop > segment_stop))\n return E_FILE_FORMAT_INVALID;\n\n if ((total >= 0) && (element_stop > total))\n return 1; \/\/ don't bother parsing anymore\n\n len = static_cast(size);\n\n if (element_stop > avail)\n return E_BUFFER_NOT_FULL;\n\n const long long element_size = element_stop - element_start;\n\n m_pCues =\n new (std::nothrow) Cues(this, pos, size, element_start, element_size);\n if (m_pCues == NULL)\n return -1;\n\n return 0; \/\/ success\n}\n","target":0,"code_token_length":698,"total_token_length":1029,"max_tokens_setting":2048} +{"idx":429792,"func":"static BOOL check_opcode_types(compiler_common *common, PCRE2_SPTR cc, PCRE2_SPTR ccend)\n{\nint count;\nPCRE2_SPTR slot;\nPCRE2_SPTR assert_back_end = cc - 1;\n\n\/* Calculate important variables (like stack size) and checks whether all opcodes are supported. *\/\nwhile (cc < ccend)\n {\n switch(*cc)\n {\n case OP_SET_SOM:\n common->has_set_som = TRUE;\n common->might_be_empty = TRUE;\n cc += 1;\n break;\n\n case OP_REF:\n case OP_REFI:\n common->optimized_cbracket[GET2(cc, 1)] = 0;\n cc += 1 + IMM2_SIZE;\n break;\n\n case OP_CBRAPOS:\n case OP_SCBRAPOS:\n common->optimized_cbracket[GET2(cc, 1 + LINK_SIZE)] = 0;\n cc += 1 + LINK_SIZE + IMM2_SIZE;\n break;\n\n case OP_COND:\n case OP_SCOND:\n \/* Only AUTO_CALLOUT can insert this opcode. We do\n not intend to support this case. *\/\n if (cc[1 + LINK_SIZE] == OP_CALLOUT || cc[1 + LINK_SIZE] == OP_CALLOUT_STR)\n return FALSE;\n cc += 1 + LINK_SIZE;\n break;\n\n case OP_CREF:\n common->optimized_cbracket[GET2(cc, 1)] = 0;\n cc += 1 + IMM2_SIZE;\n break;\n\n case OP_DNREF:\n case OP_DNREFI:\n case OP_DNCREF:\n count = GET2(cc, 1 + IMM2_SIZE);\n slot = common->name_table + GET2(cc, 1) * common->name_entry_size;\n while (count-- > 0)\n {\n common->optimized_cbracket[GET2(slot, 0)] = 0;\n slot += common->name_entry_size;\n }\n cc += 1 + 2 * IMM2_SIZE;\n break;\n\n case OP_RECURSE:\n \/* Set its value only once. *\/\n if (common->recursive_head_ptr == 0)\n {\n common->recursive_head_ptr = common->ovector_start;\n common->ovector_start += sizeof(sljit_sw);\n }\n cc += 1 + LINK_SIZE;\n break;\n\n case OP_CALLOUT:\n case OP_CALLOUT_STR:\n if (common->capture_last_ptr == 0)\n {\n common->capture_last_ptr = common->ovector_start;\n common->ovector_start += sizeof(sljit_sw);\n }\n cc += (*cc == OP_CALLOUT) ? PRIV(OP_lengths)[OP_CALLOUT] : GET(cc, 1 + 2*LINK_SIZE);\n break;\n\n case OP_ASSERTBACK:\n slot = bracketend(cc);\n if (slot > assert_back_end)\n assert_back_end = slot;\n cc += 1 + LINK_SIZE;\n break;\n\n case OP_THEN_ARG:\n common->has_then = TRUE;\n common->control_head_ptr = 1;\n \/* Fall through. *\/\n\n case OP_COMMIT_ARG:\n case OP_PRUNE_ARG:\n case OP_MARK:\n if (common->mark_ptr == 0)\n {\n common->mark_ptr = common->ovector_start;\n common->ovector_start += sizeof(sljit_sw);\n }\n cc += 1 + 2 + cc[1];\n break;\n\n case OP_THEN:\n common->has_then = TRUE;\n common->control_head_ptr = 1;\n cc += 1;\n break;\n\n case OP_SKIP:\n if (cc < assert_back_end)\n common->has_skip_in_assert_back = TRUE;\n cc += 1;\n break;\n\n case OP_SKIP_ARG:\n common->control_head_ptr = 1;\n common->has_skip_arg = TRUE;\n if (cc < assert_back_end)\n common->has_skip_in_assert_back = TRUE;\n cc += 1 + 2 + cc[1];\n break;\n\n default:\n cc = next_opcode(common, cc);\n if (cc == NULL)\n return FALSE;\n break;\n }\n }\nreturn TRUE;\n}","target":0,"code_token_length":924,"total_token_length":1255,"max_tokens_setting":2048} +{"idx":44181,"func":"static RectangleInfo CompareImagesBounds(const Image *image1,\n const Image *image2,const LayerMethod method,ExceptionInfo *exception)\n{\n RectangleInfo\n bounds;\n\n PixelInfo\n pixel1,\n pixel2;\n\n register const Quantum\n *p,\n *q;\n\n register ssize_t\n x;\n\n ssize_t\n y;\n\n \/*\n Set bounding box of the differences between images.\n *\/\n GetPixelInfo(image1,&pixel1);\n GetPixelInfo(image2,&pixel2);\n for (x=0; x < (ssize_t) image1->columns; x++)\n {\n p=GetVirtualPixels(image1,x,0,1,image1->rows,exception);\n q=GetVirtualPixels(image2,x,0,1,image2->rows,exception);\n if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))\n break;\n for (y=0; y < (ssize_t) image1->rows; y++)\n {\n GetPixelInfoPixel(image1,p,&pixel1);\n GetPixelInfoPixel(image2,q,&pixel2);\n if (ComparePixels(method,&pixel1,&pixel2) != MagickFalse)\n break;\n p+=GetPixelChannels(image1);\n q+=GetPixelChannels(image2);\n }\n if (y < (ssize_t) image1->rows)\n break;\n }\n if (x >= (ssize_t) image1->columns)\n {\n \/*\n Images are identical, return a null image.\n *\/\n bounds.x=-1;\n bounds.y=-1;\n bounds.width=1;\n bounds.height=1;\n return(bounds);\n }\n bounds.x=x;\n for (x=(ssize_t) image1->columns-1; x >= 0; x--)\n {\n p=GetVirtualPixels(image1,x,0,1,image1->rows,exception);\n q=GetVirtualPixels(image2,x,0,1,image2->rows,exception);\n if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))\n break;\n for (y=0; y < (ssize_t) image1->rows; y++)\n {\n GetPixelInfoPixel(image1,p,&pixel1);\n GetPixelInfoPixel(image2,q,&pixel2);\n if (ComparePixels(method,&pixel1,&pixel2) != MagickFalse)\n break;\n p+=GetPixelChannels(image1);\n q+=GetPixelChannels(image2);\n }\n if (y < (ssize_t) image1->rows)\n break;\n }\n bounds.width=(size_t) (x-bounds.x+1);\n for (y=0; y < (ssize_t) image1->rows; y++)\n {\n p=GetVirtualPixels(image1,0,y,image1->columns,1,exception);\n q=GetVirtualPixels(image2,0,y,image2->columns,1,exception);\n if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))\n break;\n for (x=0; x < (ssize_t) image1->columns; x++)\n {\n GetPixelInfoPixel(image1,p,&pixel1);\n GetPixelInfoPixel(image2,q,&pixel2);\n if (ComparePixels(method,&pixel1,&pixel2) != MagickFalse)\n break;\n p+=GetPixelChannels(image1);\n q+=GetPixelChannels(image2);\n }\n if (x < (ssize_t) image1->columns)\n break;\n }\n bounds.y=y;\n for (y=(ssize_t) image1->rows-1; y >= 0; y--)\n {\n p=GetVirtualPixels(image1,0,y,image1->columns,1,exception);\n q=GetVirtualPixels(image2,0,y,image2->columns,1,exception);\n if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL))\n break;\n for (x=0; x < (ssize_t) image1->columns; x++)\n {\n GetPixelInfoPixel(image1,p,&pixel1);\n GetPixelInfoPixel(image2,q,&pixel2);\n if (ComparePixels(method,&pixel1,&pixel2) != MagickFalse)\n break;\n p+=GetPixelChannels(image1);\n q+=GetPixelChannels(image2);\n }\n if (x < (ssize_t) image1->columns)\n break;\n }\n bounds.height=(size_t) (y-bounds.y+1);\n return(bounds);\n}","target":0,"code_token_length":984,"total_token_length":1315,"max_tokens_setting":2048} +{"idx":400942,"func":"innodb_switch_mapping(\n\/*==================*\/\n\tENGINE_HANDLE*\t\thandle,\t\t\/*!< in: Engine handle *\/\n\tconst void*\t\tcookie,\t\t\/*!< in: connection cookie *\/\n\tconst char*\t\tname,\t\t\/*!< in: full name contains\n\t\t\t\t\t\ttable map name, and possible\n\t\t\t\t\t\tkey value *\/\n\tsize_t*\t\t\tname_len,\t\/*!< in\/out: name length,\n\t\t\t\t\t\tout with length excludes\n\t\t\t\t\t\tthe table map name *\/\n\tbool\t\t\thas_prefix)\t\/*!< in: whether the name has\n\t\t\t\t\t\t\"@@\" prefix *\/\n{\n\tstruct innodb_engine*\tinnodb_eng = innodb_handle(handle);\n\tinnodb_conn_data_t*\tconn_data;\n\tchar\t\t\tnew_name[KEY_MAX_LENGTH];\n\tmeta_cfg_info_t*\tmeta_info = innodb_eng->meta_info;\n\tchar*\t\t\tnew_map_name;\n\tunsigned int\t\tnew_map_name_len = 0;\n\tchar*\t\t\tlast;\n\tmeta_cfg_info_t*\tnew_meta_info;\n\tint\t\t\tsep_len = 0;\n\n\tif (has_prefix) {\n\t\tchar*\t\tsep = NULL;\n\n\t\tassert(*name_len > 2 && name[0] == '@' && name[1] == '@');\n\t\tassert(*name_len < KEY_MAX_LENGTH);\n\n\t\tmemcpy(new_name, &name[2], (*name_len) - 2);\n\n\t\tnew_name[*name_len - 2] = 0;\n\n\t\tGET_OPTION(meta_info, OPTION_ID_TBL_MAP_SEP, sep, sep_len);\n\n\t\tassert(sep_len > 0);\n\n\t\tnew_map_name = strtok_r(new_name, sep, &last);\n\n\t\tif (new_map_name == NULL) {\n\t\t\treturn(ENGINE_KEY_ENOENT);\n\t\t}\n\n\t\tnew_map_name_len = strlen(new_map_name);\n\t} else {\n\t\t\/* This is used in the \"bind\" command, and without the\n\t\t\"@@\" prefix. *\/\n\t\tif (name == NULL) {\n\t\t\treturn(ENGINE_KEY_ENOENT);\n\t\t}\n\n\t\tnew_map_name = (char*) name;\n\t\tnew_map_name_len = *name_len;\n\t}\n\n\tconn_data = innodb_eng->server.cookie->get_engine_specific(cookie);\n\n\t\/* Check if we are getting the same configure setting as existing one *\/\n\tif (conn_data && conn_data->conn_meta\n\t && (new_map_name_len\n\t\t== conn_data->conn_meta->col_info[CONTAINER_NAME].col_name_len)\n\t && (strcmp(\n\t\tnew_map_name,\n\t\tconn_data->conn_meta->col_info[CONTAINER_NAME].col_name) == 0)) {\n\t\tgoto get_key_name;\n\t}\n\n\tnew_meta_info = innodb_config(\n\t\tnew_map_name, new_map_name_len, &innodb_eng->meta_hash);\n\n\tif (!new_meta_info) {\n\t\treturn(ENGINE_KEY_ENOENT);\n\t}\n\n\t\/* Clean up the existing connection metadata if exists *\/\n\tif (conn_data) {\n\t\tinnodb_conn_clean_data(conn_data, false, false);\n\n\t\t\/* Point to the new metadata *\/\n\t\tconn_data->conn_meta = new_meta_info;\n\t}\n\n\tconn_data = innodb_conn_init(innodb_eng, cookie,\n\t\t\t\t CONN_MODE_NONE, 0, false,\n\t\t\t\t new_meta_info);\n\n\tassert(conn_data->conn_meta == new_meta_info);\n\nget_key_name:\n\t\/* Now calculate name length exclude the table mapping name,\n\tthis is the length for the remaining key portion *\/\n\tif (has_prefix) {\n\t\tassert(*name_len >= strlen(new_map_name) + 2);\n\n\t\tif (*name_len >= strlen(new_map_name) + 2 + sep_len) {\n\t\t\t*name_len -= strlen(new_map_name) + 2 + sep_len;\n\t\t} else {\n\t\t\t\/* the name does not even contain a delimiter,\n\t\t\tso there will be no keys either *\/\n\t\t\t*name_len = 0;\n\t\t}\n\t}\n\n\treturn(ENGINE_SUCCESS);\n}","target":0,"code_token_length":815,"total_token_length":1146,"max_tokens_setting":2048} +{"idx":446269,"func":"virDomainFSDefFormat(virBufferPtr buf,\n virDomainFSDefPtr def,\n unsigned int flags)\n{\n const char *type = virDomainFSTypeToString(def->type);\n const char *accessmode = virDomainFSAccessModeTypeToString(def->accessmode);\n const char *fsdriver = virDomainFSDriverTypeToString(def->fsdriver);\n const char *wrpolicy = virDomainFSWrpolicyTypeToString(def->wrpolicy);\n const char *multidevs = virDomainFSMultidevsTypeToString(def->multidevs);\n const char *src = def->src->path;\n g_auto(virBuffer) driverAttrBuf = VIR_BUFFER_INITIALIZER;\n g_auto(virBuffer) driverBuf = VIR_BUFFER_INIT_CHILD(buf);\n g_auto(virBuffer) binaryAttrBuf = VIR_BUFFER_INITIALIZER;\n g_auto(virBuffer) binaryBuf = VIR_BUFFER_INIT_CHILD(buf);\n\n if (!type) {\n virReportError(VIR_ERR_INTERNAL_ERROR,\n _(\"unexpected filesystem type %d\"), def->type);\n return -1;\n }\n\n if (!accessmode) {\n virReportError(VIR_ERR_INTERNAL_ERROR,\n _(\"unexpected accessmode %d\"), def->accessmode);\n return -1;\n }\n\n if (!multidevs) {\n virReportError(VIR_ERR_INTERNAL_ERROR,\n _(\"unexpected multidevs %d\"), def->multidevs);\n return -1;\n }\n\n virBufferAsprintf(buf,\n \"model) {\n virBufferAsprintf(buf, \" model='%s'\",\n virDomainFSModelTypeToString(def->model));\n }\n if (def->multidevs)\n virBufferAsprintf(buf, \" multidevs='%s'\", multidevs);\n virBufferAddLit(buf, \">\\n\");\n\n virBufferAdjustIndent(buf, 2);\n virBufferAdjustIndent(&driverBuf, 2);\n virBufferAdjustIndent(&binaryBuf, 2);\n if (def->fsdriver) {\n virBufferAsprintf(&driverAttrBuf, \" type='%s'\", fsdriver);\n\n if (def->format)\n virBufferAsprintf(&driverAttrBuf, \" format='%s'\",\n virStorageFileFormatTypeToString(def->format));\n\n \/* Don't generate anything if wrpolicy is set to default *\/\n if (def->wrpolicy)\n virBufferAsprintf(&driverAttrBuf, \" wrpolicy='%s'\", wrpolicy);\n\n if (def->queue_size)\n virBufferAsprintf(&driverAttrBuf, \" queue='%llu'\", def->queue_size);\n\n }\n\n if (def->fsdriver == VIR_DOMAIN_FS_DRIVER_TYPE_VIRTIOFS) {\n g_auto(virBuffer) lockAttrBuf = VIR_BUFFER_INITIALIZER;\n virBufferEscapeString(&binaryAttrBuf, \" path='%s'\", def->binary);\n\n if (def->xattr != VIR_TRISTATE_SWITCH_ABSENT) {\n virBufferAsprintf(&binaryAttrBuf, \" xattr='%s'\",\n virTristateSwitchTypeToString(def->xattr));\n }\n\n if (def->cache != VIR_DOMAIN_FS_CACHE_MODE_DEFAULT) {\n virBufferAsprintf(&binaryBuf, \"\\n\",\n virDomainFSCacheModeTypeToString(def->cache));\n }\n\n if (def->posix_lock != VIR_TRISTATE_SWITCH_ABSENT) {\n virBufferAsprintf(&lockAttrBuf, \" posix='%s'\",\n virTristateSwitchTypeToString(def->posix_lock));\n }\n\n if (def->flock != VIR_TRISTATE_SWITCH_ABSENT) {\n virBufferAsprintf(&lockAttrBuf, \" flock='%s'\",\n virTristateSwitchTypeToString(def->flock));\n }\n\n virXMLFormatElement(&binaryBuf, \"lock\", &lockAttrBuf, NULL);\n }\n\n virDomainVirtioOptionsFormat(&driverAttrBuf, def->virtio);\n\n virXMLFormatElement(buf, \"driver\", &driverAttrBuf, &driverBuf);\n virXMLFormatElement(buf, \"binary\", &binaryAttrBuf, &binaryBuf);\n\n switch (def->type) {\n case VIR_DOMAIN_FS_TYPE_MOUNT:\n case VIR_DOMAIN_FS_TYPE_BIND:\n virBufferEscapeString(buf, \"\\n\",\n src);\n break;\n\n case VIR_DOMAIN_FS_TYPE_BLOCK:\n virBufferEscapeString(buf, \"\\n\",\n src);\n break;\n\n case VIR_DOMAIN_FS_TYPE_FILE:\n virBufferEscapeString(buf, \"\\n\",\n src);\n break;\n\n case VIR_DOMAIN_FS_TYPE_TEMPLATE:\n virBufferEscapeString(buf, \"\\n\",\n src);\n break;\n\n case VIR_DOMAIN_FS_TYPE_RAM:\n virBufferAsprintf(buf, \"\\n\",\n def->usage \/ 1024);\n break;\n\n case VIR_DOMAIN_FS_TYPE_VOLUME:\n virBufferAddLit(buf, \"src->srcpool->pool);\n virBufferEscapeString(buf, \" volume='%s'\", def->src->srcpool->volume);\n virBufferAddLit(buf, \"\/>\\n\");\n break;\n }\n\n virBufferEscapeString(buf, \"\\n\",\n def->dst);\n\n if (def->readonly)\n virBufferAddLit(buf, \"\\n\");\n\n if (virDomainDeviceInfoFormat(buf, &def->info, flags) < 0)\n return -1;\n\n if (def->space_hard_limit)\n virBufferAsprintf(buf, \"\"\n \"%llu<\/space_hard_limit>\\n\", def->space_hard_limit);\n if (def->space_soft_limit) {\n virBufferAsprintf(buf, \"\"\n \"%llu<\/space_soft_limit>\\n\", def->space_soft_limit);\n }\n virBufferAdjustIndent(buf, -2);\n virBufferAddLit(buf, \"<\/filesystem>\\n\");\n\n return 0;\n}","target":0,"code_token_length":1322,"total_token_length":1653,"max_tokens_setting":2048} +{"idx":506294,"func":"int ssl3_get_certificate_request(SSL *s)\n\t{\n\tint ok,ret=0;\n\tunsigned long n,nc,l;\n\tunsigned int llen,ctype_num,i;\n\tX509_NAME *xn=NULL;\n\tconst unsigned char *p,*q;\n\tunsigned char *d;\n\tSTACK_OF(X509_NAME) *ca_sk=NULL;\n\n\tn=s->method->ssl_get_message(s,\n\t\tSSL3_ST_CR_CERT_REQ_A,\n\t\tSSL3_ST_CR_CERT_REQ_B,\n\t\t-1,\n\t\ts->max_cert_list,\n\t\t&ok);\n\n\tif (!ok) return((int)n);\n\n\ts->s3->tmp.cert_req=0;\n\n\tif (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE)\n\t\t{\n\t\ts->s3->tmp.reuse_message=1;\n\t\treturn(1);\n\t\t}\n\n\tif (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST)\n\t\t{\n\t\tssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);\n\t\tSSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_WRONG_MESSAGE_TYPE);\n\t\tgoto err;\n\t\t}\n\n\t\/* TLS does not like anon-DH with client cert *\/\n\tif (s->version > SSL3_VERSION)\n\t\t{\n\t\tl=s->s3->tmp.new_cipher->algorithms;\n\t\tif (l & SSL_aNULL)\n\t\t\t{\n\t\t\tssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);\n\t\t\tSSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);\n\t\t\tgoto err;\n\t\t\t}\n\t\t}\n\n\tp=d=(unsigned char *)s->init_msg;\n\n\tif ((ca_sk=sk_X509_NAME_new(ca_dn_cmp)) == NULL)\n\t\t{\n\t\tSSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);\n\t\tgoto err;\n\t\t}\n\n\t\/* get the certificate types *\/\n\tctype_num= *(p++);\n\tif (ctype_num > SSL3_CT_NUMBER)\n\t\tctype_num=SSL3_CT_NUMBER;\n\tfor (i=0; is3->tmp.ctype[i]= p[i];\n\tp+=ctype_num;\n\n\t\/* get the CA RDNs *\/\n\tn2s(p,llen);\n#if 0\n{\nFILE *out;\nout=fopen(\"\/tmp\/vsign.der\",\"w\");\nfwrite(p,1,llen,out);\nfclose(out);\n}\n#endif\n\n\tif ((llen+ctype_num+2+1) != n)\n\t\t{\n\t\tssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);\n\t\tSSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_LENGTH_MISMATCH);\n\t\tgoto err;\n\t\t}\n\n\tfor (nc=0; nc llen)\n\t\t\t{\n\t\t\tif ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG))\n\t\t\t\tgoto cont; \/* netscape bugs *\/\n\t\t\tssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);\n\t\t\tSSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_TOO_LONG);\n\t\t\tgoto err;\n\t\t\t}\n\n\t\tq=p;\n\n\t\tif ((xn=d2i_X509_NAME(NULL,&q,l)) == NULL)\n\t\t\t{\n\t\t\t\/* If netscape tolerance is on, ignore errors *\/\n\t\t\tif (s->options & SSL_OP_NETSCAPE_CA_DN_BUG)\n\t\t\t\tgoto cont;\n\t\t\telse\n\t\t\t\t{\n\t\t\t\tssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);\n\t\t\t\tSSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_ASN1_LIB);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\t}\n\n\t\tif (q != (p+l))\n\t\t\t{\n\t\t\tssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);\n\t\t\tSSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_LENGTH_MISMATCH);\n\t\t\tgoto err;\n\t\t\t}\n\t\tif (!sk_X509_NAME_push(ca_sk,xn))\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);\n\t\t\tgoto err;\n\t\t\t}\n\n\t\tp+=l;\n\t\tnc+=l+2;\n\t\t}\n\n\tif (0)\n\t\t{\ncont:\n\t\tERR_clear_error();\n\t\t}\n\n\t\/* we should setup a certificate to return.... *\/\n\ts->s3->tmp.cert_req=1;\n\ts->s3->tmp.ctype_num=ctype_num;\n\tif (s->s3->tmp.ca_names != NULL)\n\t\tsk_X509_NAME_pop_free(s->s3->tmp.ca_names,X509_NAME_free);\n\ts->s3->tmp.ca_names=ca_sk;\n\tca_sk=NULL;\n\n\tret=1;\nerr:\n\tif (ca_sk != NULL) sk_X509_NAME_pop_free(ca_sk,X509_NAME_free);\n\treturn(ret);\n\t}","target":0,"code_token_length":1082,"total_token_length":1413,"max_tokens_setting":2048} +{"idx":83514,"func":"static Jsi_RC jsi_csSetupStruct(Jsi_Interp *interp, Jsi_StructSpec *sl, Jsi_FieldSpec *sf, \n Jsi_StructSpec* recs, int flen, Jsi_OptionTypedef** stPtr, int arrCnt) {\n bool isNew;\n int i, cnt = 0, boffset = 0;\n Jsi_HashEntry *entry, *hPtr;\n if (!(hPtr=Jsi_HashEntryNew(interp->CTypeHash, sl->name, &isNew)) || !isNew)\n return Jsi_LogError(\"struct is c-type: %s\", sl->name);\n entry = Jsi_HashEntryNew(interp->StructHash, sl->name, &isNew);\n if (!isNew)\n return Jsi_LogError(\"duplicate struct: %s\", sl->name);\n Jsi_FieldSpec *asf = NULL, *osf = sf;\n while (sf && sf->id != JSI_OPTION_END) {\n if (!sf->type)\n sf->type = Jsi_OptionTypeInfo(sf->id);\n if (!sf->type && sf->tname)\n sf->type = Jsi_TypeLookup(interp, sf->tname);\n int isbitset = ((sf->flags&JSI_OPT_BITSET_ENUM)!=0);\n if (sf->type && sf->type->extData && (sf->type->flags&(jsi_CTYP_ENUM|jsi_CTYP_STRUCT))) {\n \/\/ A struct sub-field or a bit field mapped to an ENUM.\n Jsi_OptionSpec *es = (typeof(es))sf->type->extData;\n es->value++;\n if ((sf->type->flags&jsi_CTYP_ENUM)) {\n if (sf->bits)\n return Jsi_LogError(\"enum of bits unsupported: %s\", sl->name); \/\/TODO: get working again...\n sf->custom = (isbitset ? Jsi_Opt_SwitchBitset : Jsi_Opt_SwitchEnum);\n sf->data = (void*)es->data;\n sf->id = JSI_OPTION_CUSTOM;\n }\n else if (sf->type->flags & jsi_CTYP_STRUCT) {\n sf->custom = Jsi_Opt_SwitchSuboption;\n sf->data = es->extData;\n sf->id = JSI_OPTION_CUSTOM;\n }\n }\n if (recs) {\n if (!sf->type)\n return Jsi_LogError(\"unknown id\");\n sf->tname = sf->type->cName;\n sf->size = (isbitset?(int)sizeof(int):sf->type->size);\n if (sf->arrSize)\n sf->size *= sf->arrSize;\n sf->idx = cnt;\n sf->boffset = boffset;\n if (sf->bits) {\n if (sf->bits>=64)\n return Jsi_LogError(\"bits too large\");\n boffset += sf->bits;\n sf->id = JSI_OPTION_CUSTOM;\n sf->custom=Jsi_Opt_SwitchBitfield;\n sf->init.OPT_BITS=&jsi_csBitGetSet;\n } else {\n sf->offset = (boffset+7)\/8;\n boffset += sf->size*8;\n }\n } else {\n boffset += sf->size*8;\n }\n sf->extData = (uchar*)sl;\n sf++, cnt++;\n }\n sl->idx = cnt;\n if (!sl->size) \n sl->size = (boffset+7)\/8;\n if (sl->ssig)\n Jsi_HashSet(interp->SigHash, (void*)(uintptr_t)sl->ssig, sl);\n int extra = 0;\n if (flen)\n extra = sl->size + ((flen+2+arrCnt*2)*sizeof(Jsi_StructSpec));\n Jsi_OptionTypedef *st = (typeof(st))Jsi_Calloc(1, sizeof(*st) + extra);\n SIGINIT(st, TYPEDEF);\n if (!recs) \n sf = osf;\n else {\n st->extra = (uchar*)(st+1); \/\/ Space for struct initializer.\n sf = (typeof(sf))(st->extra + sl->size);\n memcpy(sf, recs, sizeof(*sf)*(flen+1));\n sl = sf+flen+1;\n if (arrCnt)\n asf = sl+1;\n memcpy(sl, recs+flen+1, sizeof(*sl));\n for (i=0; iid;\n if (sf[i].arrSize) {\n asf[0] = sf[i];\n asf[1] = sf[flen];\n asf->arrSize = asf->offset = 0;\n \/\/asf->size = asf->type->size;\n sf[i].id = JSI_OPTION_CUSTOM;\n sf[i].custom=Jsi_Opt_SwitchCArray;\n sf[i].init.OPT_CARRAY = asf;\n asf += 2;\n \/\/sf[i].extData = \n \/\/ {.sig=JSI_SIG_OPTS_FIELD, .name=sf[i].name, \n \/\/ JSI_OPT_CARRAY_ITEM_(JSI_SIG_OPTS_FIELD,'+otype+', '+name+', sf[i].name, .help=sf[i].help, .flags='+fflags+rest+'),\\n'\n \/\/ JSI_OPT_END_(JSI_SIG_OPTS_FIELD,'+name+', .help=\"Options for array field '+name+'.'+fname+'\")\\n };\\n\\n';\n \/\/ JSI_OPT_CARRAY_(JSI_SIG_OPTS_FIELD,'+name+', '+fname+', \"'+fdescr+'\", '+fflags+', '+arnam+', '+f.asize+', \"'+type+'\", '+csinit+'),\\n';\n }\n }\n }\n st->extData = (uchar*)sl;\n sl->extData = (uchar*)sf;\n sl->type = st;\n st->cName = sl->name;\n st->idName = \"CUSTOM\";\n st->id = JSI_OPTION_CUSTOM;\n st->size = sl->size;\n st->flags = jsi_CTYP_DYN_MEMORY|jsi_CTYP_STRUCT;\n Jsi_HashValueSet(entry, sl);\n Jsi_HashValueSet(hPtr, st);\n st->hPtr = hPtr;\n if (stPtr)\n *stPtr = st;\n return JSI_OK;\n}","target":0,"code_token_length":1449,"total_token_length":1780,"max_tokens_setting":2048} +{"idx":506941,"func":"int n_ssl3_mac(SSL *ssl, unsigned char *md, int send)\n\t{\n\tSSL3_RECORD *rec;\n\tunsigned char *mac_sec,*seq;\n\tEVP_MD_CTX md_ctx;\n\tconst EVP_MD_CTX *hash;\n\tunsigned char *p,rec_char;\n\tsize_t md_size, orig_len;\n\tint npad;\n\tint t;\n\n\tif (send)\n\t\t{\n\t\trec= &(ssl->s3->wrec);\n\t\tmac_sec= &(ssl->s3->write_mac_secret[0]);\n\t\tseq= &(ssl->s3->write_sequence[0]);\n\t\thash=ssl->write_hash;\n\t\t}\n\telse\n\t\t{\n\t\trec= &(ssl->s3->rrec);\n\t\tmac_sec= &(ssl->s3->read_mac_secret[0]);\n\t\tseq= &(ssl->s3->read_sequence[0]);\n\t\thash=ssl->read_hash;\n\t\t}\n\n\tt=EVP_MD_CTX_size(hash);\n\tif (t < 0)\n\t\treturn -1;\n\tmd_size=t;\n\tnpad=(48\/md_size)*md_size;\n\n\t\/* kludge: ssl3_cbc_remove_padding passes padding length in rec->type *\/\n\torig_len = rec->length+md_size+((unsigned int)rec->type>>8);\n\trec->type &= 0xff;\n\n\tif (!send &&\n\t EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&\n\t ssl3_cbc_record_digest_supported(hash))\n\t\t{\n\t\t\/* This is a CBC-encrypted record. We must avoid leaking any\n\t\t * timing-side channel information about how many blocks of\n\t\t * data we are hashing because that gives an attacker a\n\t\t * timing-oracle. *\/\n\n\t\t\/* npad is, at most, 48 bytes and that's with MD5:\n\t\t * 16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.\n\t\t *\n\t\t * With SHA-1 (the largest hash speced for SSLv3) the hash size\n\t\t * goes up 4, but npad goes down by 8, resulting in a smaller\n\t\t * total size. *\/\n\t\tunsigned char header[75];\n\t\tunsigned j = 0;\n\t\tmemcpy(header+j, mac_sec, md_size);\n\t\tj += md_size;\n\t\tmemcpy(header+j, ssl3_pad_1, npad);\n\t\tj += npad;\n\t\tmemcpy(header+j, seq, 8);\n\t\tj += 8;\n\t\theader[j++] = rec->type;\n\t\theader[j++] = rec->length >> 8;\n\t\theader[j++] = rec->length & 0xff;\n\n\t\tssl3_cbc_digest_record(\n\t\t\thash,\n\t\t\tmd, &md_size,\n\t\t\theader, rec->input,\n\t\t\trec->length + md_size, orig_len,\n\t\t\tmac_sec, md_size,\n\t\t\t1 \/* is SSLv3 *\/);\n\t\t}\n\telse\n\t\t{\n\t\tunsigned int md_size_u;\n\t\t\/* Chop the digest off the end :-) *\/\n\t\tEVP_MD_CTX_init(&md_ctx);\n\n\t\tEVP_MD_CTX_copy_ex( &md_ctx,hash);\n\t\tEVP_DigestUpdate(&md_ctx,mac_sec,md_size);\n\t\tEVP_DigestUpdate(&md_ctx,ssl3_pad_1,npad);\n\t\tEVP_DigestUpdate(&md_ctx,seq,8);\n\t\trec_char=rec->type;\n\t\tEVP_DigestUpdate(&md_ctx,&rec_char,1);\n\t\tp=md;\n\t\ts2n(rec->length,p);\n\t\tEVP_DigestUpdate(&md_ctx,md,2);\n\t\tEVP_DigestUpdate(&md_ctx,rec->input,rec->length);\n\t\tEVP_DigestFinal_ex( &md_ctx,md,NULL);\n\n\t\tEVP_MD_CTX_copy_ex( &md_ctx,hash);\n\t\tEVP_DigestUpdate(&md_ctx,mac_sec,md_size);\n\t\tEVP_DigestUpdate(&md_ctx,ssl3_pad_2,npad);\n\t\tEVP_DigestUpdate(&md_ctx,md,md_size);\n\t\tEVP_DigestFinal_ex( &md_ctx,md,&md_size_u);\n\t\tmd_size = md_size_u;\n\n\t\tEVP_MD_CTX_cleanup(&md_ctx);\n\t}\n\n\tssl3_record_sequence_update(seq);\n\treturn(md_size);\n\t}","target":0,"code_token_length":915,"total_token_length":1246,"max_tokens_setting":2048} +{"idx":408660,"func":"static int netlink_dump(struct sock *sk)\n{\n\tstruct netlink_sock *nlk = nlk_sk(sk);\n\tstruct netlink_callback *cb;\n\tstruct sk_buff *skb = NULL;\n\tstruct nlmsghdr *nlh;\n\tstruct module *module;\n\tint err = -ENOBUFS;\n\tint alloc_min_size;\n\tint alloc_size;\n\n\tmutex_lock(nlk->cb_mutex);\n\tif (!nlk->cb_running) {\n\t\terr = -EINVAL;\n\t\tgoto errout_skb;\n\t}\n\n\tif (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)\n\t\tgoto errout_skb;\n\n\t\/* NLMSG_GOODSIZE is small to avoid high order allocations being\n\t * required, but it makes sense to _attempt_ a 16K bytes allocation\n\t * to reduce number of system calls on dump operations, if user\n\t * ever provided a big enough buffer.\n\t *\/\n\tcb = &nlk->cb;\n\talloc_min_size = max_t(int, cb->min_dump_alloc, NLMSG_GOODSIZE);\n\n\tif (alloc_min_size < nlk->max_recvmsg_len) {\n\t\talloc_size = nlk->max_recvmsg_len;\n\t\tskb = alloc_skb(alloc_size,\n\t\t\t\t(GFP_KERNEL & ~__GFP_DIRECT_RECLAIM) |\n\t\t\t\t__GFP_NOWARN | __GFP_NORETRY);\n\t}\n\tif (!skb) {\n\t\talloc_size = alloc_min_size;\n\t\tskb = alloc_skb(alloc_size, GFP_KERNEL);\n\t}\n\tif (!skb)\n\t\tgoto errout_skb;\n\n\t\/* Trim skb to allocated size. User is expected to provide buffer as\n\t * large as max(min_dump_alloc, 16KiB (mac_recvmsg_len capped at\n\t * netlink_recvmsg())). dump will pack as many smaller messages as\n\t * could fit within the allocated skb. skb is typically allocated\n\t * with larger space than required (could be as much as near 2x the\n\t * requested size with align to next power of 2 approach). Allowing\n\t * dump to use the excess space makes it difficult for a user to have a\n\t * reasonable static buffer based on the expected largest dump of a\n\t * single netdev. The outcome is MSG_TRUNC error.\n\t *\/\n\tskb_reserve(skb, skb_tailroom(skb) - alloc_size);\n\tnetlink_skb_set_owner_r(skb, sk);\n\n\tif (nlk->dump_done_errno > 0)\n\t\tnlk->dump_done_errno = cb->dump(skb, cb);\n\n\tif (nlk->dump_done_errno > 0 ||\n\t skb_tailroom(skb) < nlmsg_total_size(sizeof(nlk->dump_done_errno))) {\n\t\tmutex_unlock(nlk->cb_mutex);\n\n\t\tif (sk_filter(sk, skb))\n\t\t\tkfree_skb(skb);\n\t\telse\n\t\t\t__netlink_sendskb(sk, skb);\n\t\treturn 0;\n\t}\n\n\tnlh = nlmsg_put_answer(skb, cb, NLMSG_DONE,\n\t\t\t sizeof(nlk->dump_done_errno), NLM_F_MULTI);\n\tif (WARN_ON(!nlh))\n\t\tgoto errout_skb;\n\n\tnl_dump_check_consistent(cb, nlh);\n\n\tmemcpy(nlmsg_data(nlh), &nlk->dump_done_errno,\n\t sizeof(nlk->dump_done_errno));\n\n\tif (sk_filter(sk, skb))\n\t\tkfree_skb(skb);\n\telse\n\t\t__netlink_sendskb(sk, skb);\n\n\tif (cb->done)\n\t\tcb->done(cb);\n\n\tnlk->cb_running = false;\n\tmodule = cb->module;\n\tskb = cb->skb;\n\tmutex_unlock(nlk->cb_mutex);\n\tmodule_put(module);\n\tconsume_skb(skb);\n\treturn 0;\n\nerrout_skb:\n\tmutex_unlock(nlk->cb_mutex);\n\tkfree_skb(skb);\n\treturn err;\n}","target":0,"code_token_length":785,"total_token_length":1116,"max_tokens_setting":2048} +{"idx":111463,"func":"static enum TIFFReadDirEntryErr TIFFReadDirEntryArrayWithLimit(\n TIFF* tif, TIFFDirEntry* direntry, uint32* count, uint32 desttypesize,\n void** value, uint64 maxcount)\n{\n\tint typesize;\n\tuint32 datasize;\n\tvoid* data;\n uint64 target_count64;\n\ttypesize=TIFFDataWidth(direntry->tdir_type);\n\n target_count64 = (direntry->tdir_count > maxcount) ?\n maxcount : direntry->tdir_count;\n\n\tif ((target_count64==0)||(typesize==0))\n\t{\n\t\t*value=0;\n\t\treturn(TIFFReadDirEntryErrOk);\n\t}\n (void) desttypesize;\n\n \/* \n * As a sanity check, make sure we have no more than a 2GB tag array \n * in either the current data type or the dest data type. This also\n * avoids problems with overflow of tmsize_t on 32bit systems.\n *\/\n\tif ((uint64)(2147483647\/typesize)0);\n\n\tif( isMapped(tif) && datasize > (uint32)tif->tif_size )\n\t\treturn TIFFReadDirEntryErrIo;\n\n\tif( !isMapped(tif) &&\n\t\t(((tif->tif_flags&TIFF_BIGTIFF) && datasize > 8) ||\n\t\t(!(tif->tif_flags&TIFF_BIGTIFF) && datasize > 4)) )\n\t{\n\t\tdata = NULL;\n\t}\n\telse\n\t{\n\t\tdata=_TIFFCheckMalloc(tif, *count, typesize, \"ReadDirEntryArray\");\n\t\tif (data==0)\n\t\t\treturn(TIFFReadDirEntryErrAlloc);\n\t}\n\tif (!(tif->tif_flags&TIFF_BIGTIFF))\n\t{\n\t\tif (datasize<=4)\n\t\t\t_TIFFmemcpy(data,&direntry->tdir_offset,datasize);\n\t\telse\n\t\t{\n\t\t\tenum TIFFReadDirEntryErr err;\n\t\t\tuint32 offset = direntry->tdir_offset.toff_long;\n\t\t\tif (tif->tif_flags&TIFF_SWAB)\n\t\t\t\tTIFFSwabLong(&offset);\n\t\t\tif( isMapped(tif) )\n\t\t\t\terr=TIFFReadDirEntryData(tif,(uint64)offset,(tmsize_t)datasize,data);\n\t\t\telse\n\t\t\t\terr=TIFFReadDirEntryDataAndRealloc(tif,(uint64)offset,(tmsize_t)datasize,&data);\n\t\t\tif (err!=TIFFReadDirEntryErrOk)\n\t\t\t{\n\t\t\t\t_TIFFfree(data);\n\t\t\t\treturn(err);\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\tif (datasize<=8)\n\t\t\t_TIFFmemcpy(data,&direntry->tdir_offset,datasize);\n\t\telse\n\t\t{\n\t\t\tenum TIFFReadDirEntryErr err;\n\t\t\tuint64 offset = direntry->tdir_offset.toff_long8;\n\t\t\tif (tif->tif_flags&TIFF_SWAB)\n\t\t\t\tTIFFSwabLong8(&offset);\n\t\t\tif( isMapped(tif) )\n\t\t\t\terr=TIFFReadDirEntryData(tif,(uint64)offset,(tmsize_t)datasize,data);\n\t\t\telse\n\t\t\t\terr=TIFFReadDirEntryDataAndRealloc(tif,(uint64)offset,(tmsize_t)datasize,&data);\n\t\t\tif (err!=TIFFReadDirEntryErrOk)\n\t\t\t{\n\t\t\t\t_TIFFfree(data);\n\t\t\t\treturn(err);\n\t\t\t}\n\t\t}\n\t}\n\t*value=data;\n\treturn(TIFFReadDirEntryErrOk);\n}","target":0,"code_token_length":879,"total_token_length":1210,"max_tokens_setting":2048} +{"idx":463317,"func":"autoar_extractor_step_scan_toplevel (AutoarExtractor *self)\n{\n \/* Step 0: Scan all file names in the archive\n * We have to check whether the archive contains a top-level directory\n * before performing the extraction. We emit the \"scanned\" signal when\n * the checking is completed. *\/\n\n struct archive *a;\n struct archive_entry *entry;\n\n int r;\n\n g_debug (\"autoar_extractor_step_scan_toplevel: called\");\n\n r = libarchive_create_read_object (FALSE, self, &a);\n if (r != ARCHIVE_OK) {\n archive_read_free (a);\n r = libarchive_create_read_object (TRUE, self, &a);\n if (r != ARCHIVE_OK) {\n if (self->error == NULL)\n self->error = autoar_common_g_error_new_a (a, self->source_basename);\n return;\n } else if (archive_filter_count (a) <= 1){\n \/* If we only use raw format and filter count is one, libarchive will\n * not do anything except for just copying the source file. We do not\n * want this thing to happen because it does unnecesssary copying. *\/\n if (self->error == NULL)\n self->error = g_error_new (AUTOAR_EXTRACTOR_ERROR,\n NOT_AN_ARCHIVE_ERRNO,\n \"\\'%s\\': %s\",\n self->source_basename,\n \"not an archive\");\n return;\n }\n self->use_raw_format = TRUE;\n }\n\n while ((r = archive_read_next_header (a, &entry)) == ARCHIVE_OK) {\n const char *pathname;\n g_autofree char *utf8_pathname = NULL;\n\n if (g_cancellable_is_cancelled (self->cancellable)) {\n archive_read_free (a);\n return;\n }\n\n if (archive_entry_is_encrypted (entry)) {\n autoar_extractor_request_passphrase (self);\n }\n\n if (self->use_raw_format) {\n pathname = autoar_common_get_basename_remove_extension (g_file_peek_path (self->source_file));\n g_debug (\"autoar_extractor_step_scan_toplevel: %d: raw pathname = %s\",\n self->total_files, pathname);\n } else {\n const char *symlink_pathname;\n const char *hardlink_pathname;\n\n pathname = archive_entry_pathname (entry);\n utf8_pathname = autoar_common_get_utf8_pathname (pathname);\n symlink_pathname = archive_entry_symlink (entry);\n hardlink_pathname = archive_entry_hardlink (entry);\n\n g_debug (\"autoar_extractor_step_scan_toplevel: %d: pathname = %s%s%s%s%s%s%s\",\n self->total_files, pathname,\n utf8_pathname ? \" utf8 pathname = \" : \"\",\n utf8_pathname ? utf8_pathname : \"\",\n symlink_pathname ? \" symlink = \" : \"\",\n symlink_pathname ? symlink_pathname : \"\",\n hardlink_pathname ? \" hardlink = \" : \"\",\n hardlink_pathname ? hardlink_pathname : \"\");\n }\n self->files_list =\n g_list_prepend (self->files_list,\n g_file_get_child (self->output_file,\n utf8_pathname ? utf8_pathname : pathname));\n self->total_files++;\n self->total_size += archive_entry_size (entry);\n archive_read_data_skip (a);\n }\n\n if (self->files_list == NULL) {\n if (self->error == NULL) {\n self->error = g_error_new (AUTOAR_EXTRACTOR_ERROR,\n EMPTY_ARCHIVE_ERRNO,\n \"\\'%s\\': %s\",\n self->source_basename,\n \"empty archive\");\n }\n archive_read_free (a);\n return;\n }\n\n if (r != ARCHIVE_EOF) {\n if (self->error == NULL) {\n self->error =\n autoar_common_g_error_new_a (a, self->source_basename);\n }\n archive_read_free (a);\n return;\n }\n\n \/* If we are unable to determine the total size, set it to a positive\n * number to prevent strange percentage. *\/\n if (self->total_size <= 0)\n self->total_size = G_MAXUINT64;\n\n archive_read_free (a);\n\n g_debug (\"autoar_extractor_step_scan_toplevel: files = %d\",\n self->total_files);\n\n self->files_list = g_list_reverse (self->files_list);\n\n autoar_extractor_signal_scanned (self);\n}","target":0,"code_token_length":971,"total_token_length":1302,"max_tokens_setting":2048} +{"idx":423620,"func":"got_transfer_quota(isc_task_t *task, isc_event_t *event) {\n\tisc_result_t result = ISC_R_SUCCESS;\n\tdns_peer_t *peer = NULL;\n\tchar master[ISC_SOCKADDR_FORMATSIZE];\n\tchar source[ISC_SOCKADDR_FORMATSIZE];\n\tdns_rdatatype_t xfrtype;\n\tdns_zone_t *zone = event->ev_arg;\n\tisc_netaddr_t masterip;\n\tisc_sockaddr_t sourceaddr;\n\tisc_sockaddr_t masteraddr;\n\tisc_time_t now;\n\tconst char *soa_before = \"\";\n\tisc_dscp_t dscp = -1;\n\tbool loaded;\n\n\tUNUSED(task);\n\n\tINSIST(task == zone->task);\n\n\tif (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_EXITING)) {\n\t\tresult = ISC_R_CANCELED;\n\t\tgoto cleanup;\n\t}\n\n\tTIME_NOW(&now);\n\n\tisc_sockaddr_format(&zone->masteraddr, master, sizeof(master));\n\tif (dns_zonemgr_unreachable(zone->zmgr, &zone->masteraddr,\n\t\t\t\t &zone->sourceaddr, &now))\n\t{\n\t\tisc_sockaddr_format(&zone->sourceaddr, source, sizeof(source));\n\t\tdns_zone_log(zone, ISC_LOG_INFO,\n\t\t\t \"got_transfer_quota: skipping zone transfer as \"\n\t\t\t \"master %s (source %s) is unreachable (cached)\",\n\t\t\t master, source);\n\t\tresult = ISC_R_CANCELED;\n\t\tgoto cleanup;\n\t}\n\n\tisc_netaddr_fromsockaddr(&masterip, &zone->masteraddr);\n\t(void)dns_peerlist_peerbyaddr(zone->view->peers, &masterip, &peer);\n\n\tif (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_SOABEFOREAXFR))\n\t\tsoa_before = \"SOA before \";\n\t\/*\n\t * Decide whether we should request IXFR or AXFR.\n\t *\/\n\tZONEDB_LOCK(&zone->dblock, isc_rwlocktype_read);\n\tloaded = (zone->db != NULL);\n\tZONEDB_UNLOCK(&zone->dblock, isc_rwlocktype_read);\n\n\tif (!loaded) {\n\t\tdns_zone_log(zone, ISC_LOG_DEBUG(1),\n\t\t\t \"no database exists yet, requesting AXFR of \"\n\t\t\t \"initial version from %s\", master);\n\t\txfrtype = dns_rdatatype_axfr;\n\t} else if (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_FORCEXFER)) {\n\t\tdns_zone_log(zone, ISC_LOG_DEBUG(1),\n\t\t\t \"forced reload, requesting AXFR of \"\n\t\t\t \"initial version from %s\", master);\n\t\txfrtype = dns_rdatatype_axfr;\n\t} else if (DNS_ZONE_FLAG(zone, DNS_ZONEFLAG_NOIXFR)) {\n\t\tdns_zone_log(zone, ISC_LOG_DEBUG(1),\n\t\t\t \"retrying with AXFR from %s due to \"\n\t\t\t \"previous IXFR failure\", master);\n\t\txfrtype = dns_rdatatype_axfr;\n\t\tLOCK_ZONE(zone);\n\t\tDNS_ZONE_CLRFLAG(zone, DNS_ZONEFLAG_NOIXFR);\n\t\tUNLOCK_ZONE(zone);\n\t} else {\n\t\tbool use_ixfr = true;\n\t\tif (peer != NULL)\n\t\t\tresult = dns_peer_getrequestixfr(peer, &use_ixfr);\n\t\tif (peer == NULL || result != ISC_R_SUCCESS)\n\t\t\tuse_ixfr = zone->requestixfr;\n\t\tif (use_ixfr == false) {\n\t\t\tdns_zone_log(zone, ISC_LOG_DEBUG(1),\n\t\t\t\t \"IXFR disabled, requesting %sAXFR from %s\",\n\t\t\t\t soa_before, master);\n\t\t\tif (DNS_ZONE_FLAG(zone, DNS_ZONEFLG_SOABEFOREAXFR))\n\t\t\t\txfrtype = dns_rdatatype_soa;\n\t\t\telse\n\t\t\t\txfrtype = dns_rdatatype_axfr;\n\t\t} else {\n\t\t\tdns_zone_log(zone, ISC_LOG_DEBUG(1),\n\t\t\t\t \"requesting IXFR from %s\", master);\n\t\t\txfrtype = dns_rdatatype_ixfr;\n\t\t}\n\t}\n\n\t\/*\n\t * Determine if we should attempt to sign the request with TSIG.\n\t *\/\n\tresult = ISC_R_NOTFOUND;\n\n\t\/*\n\t * First, look for a tsig key in the master statement, then\n\t * try for a server key.\n\t *\/\n\tif ((zone->masterkeynames != NULL) &&\n\t (zone->masterkeynames[zone->curmaster] != NULL)) {\n\t\tdns_view_t *view = dns_zone_getview(zone);\n\t\tdns_name_t *keyname = zone->masterkeynames[zone->curmaster];\n\t\tresult = dns_view_gettsig(view, keyname, &zone->tsigkey);\n\t}\n\tif (zone->tsigkey == NULL)\n\t\tresult = dns_view_getpeertsig(zone->view, &masterip,\n\t\t\t\t\t &zone->tsigkey);\n\n\tif (result != ISC_R_SUCCESS && result != ISC_R_NOTFOUND) {\n\t\tdns_zone_log(zone, ISC_LOG_ERROR,\n\t\t\t \"could not get TSIG key for zone transfer: %s\",\n\t\t\t isc_result_totext(result));\n\t}\n\n\tif (zone->masterdscps != NULL)\n\t dscp = zone->masterdscps[zone->curmaster];\n\n\tLOCK_ZONE(zone);\n\tmasteraddr = zone->masteraddr;\n\tsourceaddr = zone->sourceaddr;\n\tswitch (isc_sockaddr_pf(&masteraddr)) {\n\tcase PF_INET:\n\t\tif (dscp == -1)\n\t\t\tdscp = zone->xfrsource4dscp;\n\t\tbreak;\n\tcase PF_INET6:\n\t\tif (dscp == -1)\n\t\t\tdscp = zone->xfrsource6dscp;\n\t\tbreak;\n\tdefault:\n\t\tINSIST(0);\n\t\tISC_UNREACHABLE();\n\t}\n\tUNLOCK_ZONE(zone);\n\tINSIST(isc_sockaddr_pf(&masteraddr) == isc_sockaddr_pf(&sourceaddr));\n\tresult = dns_xfrin_create(zone, xfrtype, &masteraddr, &sourceaddr,\n\t\t\t\t dscp, zone->tsigkey, zone->mctx,\n\t\t\t\t zone->zmgr->timermgr, zone->zmgr->socketmgr,\n\t\t\t\t zone->task, zone_xfrdone, &zone->xfr);\n\tif (result == ISC_R_SUCCESS) {\n\t\tLOCK_ZONE(zone);\n\t\tif (xfrtype == dns_rdatatype_axfr) {\n\t\t\tif (isc_sockaddr_pf(&masteraddr) == PF_INET)\n\t\t\t\tinc_stats(zone, dns_zonestatscounter_axfrreqv4);\n\t\t\telse\n\t\t\t\tinc_stats(zone, dns_zonestatscounter_axfrreqv6);\n\t\t} else if (xfrtype == dns_rdatatype_ixfr) {\n\t\t\tif (isc_sockaddr_pf(&masteraddr) == PF_INET)\n\t\t\t\tinc_stats(zone, dns_zonestatscounter_ixfrreqv4);\n\t\t\telse\n\t\t\t\tinc_stats(zone, dns_zonestatscounter_ixfrreqv6);\n\t\t}\n\t\tUNLOCK_ZONE(zone);\n\t}\n cleanup:\n\t\/*\n\t * Any failure in this function is handled like a failed\n\t * zone transfer. This ensures that we get removed from\n\t * zmgr->xfrin_in_progress.\n\t *\/\n\tif (result != ISC_R_SUCCESS)\n\t\tzone_xfrdone(zone, result);\n\n\tisc_event_free(&event);\n}","target":0,"code_token_length":1515,"total_token_length":1846,"max_tokens_setting":2048} +{"idx":190615,"func":"static zend_object_value spl_heap_object_new_ex(zend_class_entry *class_type, spl_heap_object **obj, zval *orig, int clone_orig TSRMLS_DC) \/* {{{ *\/\n{\n\tzend_object_value retval;\n\tspl_heap_object *intern;\n\tzend_class_entry *parent = class_type;\n\tint inherited = 0;\n\n\tintern = ecalloc(1, sizeof(spl_heap_object));\n\t*obj = intern;\n\tALLOC_INIT_ZVAL(intern->retval);\n\n\tzend_object_std_init(&intern->std, class_type TSRMLS_CC);\n\tobject_properties_init(&intern->std, class_type);\n\n\tintern->flags = 0;\n\tintern->fptr_cmp = NULL;\n\tintern->debug_info = NULL;\n\n\tif (orig) {\n\t\tspl_heap_object *other = (spl_heap_object*)zend_object_store_get_object(orig TSRMLS_CC);\n\t\tintern->ce_get_iterator = other->ce_get_iterator;\n\n\t\tif (clone_orig) {\n\t\t\tint i;\n\t\t\tintern->heap = spl_ptr_heap_clone(other->heap TSRMLS_CC);\n\t\t\tfor (i = 0; i < intern->heap->count; ++i) {\n\t\t\t\tif (intern->heap->elements[i]) {\n\t\t\t\t\tZ_ADDREF_P((zval *)intern->heap->elements[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tintern->heap = other->heap;\n\t\t}\n\n\t\tintern->flags = other->flags;\n\t} else {\n\t\tintern->heap = spl_ptr_heap_init(spl_ptr_heap_zval_max_cmp, spl_ptr_heap_zval_ctor, spl_ptr_heap_zval_dtor);\n\t}\n\n\tretval.handlers = &spl_handler_SplHeap;\n\n\twhile (parent) {\n\t\tif (parent == spl_ce_SplPriorityQueue) {\n\t\t\tintern->heap->cmp = spl_ptr_pqueue_zval_cmp;\n\t\t\tintern->flags = SPL_PQUEUE_EXTR_DATA;\n\t\t\tretval.handlers = &spl_handler_SplPriorityQueue;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (parent == spl_ce_SplMinHeap) {\n\t\t\tintern->heap->cmp = spl_ptr_heap_zval_min_cmp;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (parent == spl_ce_SplMaxHeap) {\n\t\t\tintern->heap->cmp = spl_ptr_heap_zval_max_cmp;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (parent == spl_ce_SplHeap) {\n\t\t\tbreak;\n\t\t}\n\n\t\tparent = parent->parent;\n\t\tinherited = 1;\n\t}\n\n\tretval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, spl_heap_object_free_storage, NULL TSRMLS_CC);\n\n\tif (!parent) { \/* this must never happen *\/\n\t\tphp_error_docref(NULL TSRMLS_CC, E_COMPILE_ERROR, \"Internal compiler error, Class is not child of SplHeap\");\n\t}\n\n\tif (inherited) {\n\t\tzend_hash_find(&class_type->function_table, \"compare\", sizeof(\"compare\"), (void **) &intern->fptr_cmp);\n\t\tif (intern->fptr_cmp->common.scope == parent) {\n\t\t\tintern->fptr_cmp = NULL;\n\t\t}\n\t\tzend_hash_find(&class_type->function_table, \"count\", sizeof(\"count\"), (void **) &intern->fptr_count);\n\t\tif (intern->fptr_count->common.scope == parent) {\n\t\t\tintern->fptr_count = NULL;\n\t\t}\n\t}\n\n\treturn retval;\n}\n\/* }}} *\/\n","target":0,"code_token_length":732,"total_token_length":1063,"max_tokens_setting":2048} +{"idx":159404,"func":"static int addrconf_notify(struct notifier_block *this, unsigned long event,\n\t\t\t void *ptr)\n{\n\tstruct net_device *dev = netdev_notifier_info_to_dev(ptr);\n\tstruct inet6_dev *idev = __in6_dev_get(dev);\n\tint run_pending = 0;\n\tint err;\n\n\tswitch (event) {\n\tcase NETDEV_REGISTER:\n\t\tif (!idev && dev->mtu >= IPV6_MIN_MTU) {\n\t\t\tidev = ipv6_add_dev(dev);\n\t\t\tif (IS_ERR(idev))\n\t\t\t\treturn notifier_from_errno(PTR_ERR(idev));\n\t\t}\n\t\tbreak;\n\n\tcase NETDEV_UP:\n\tcase NETDEV_CHANGE:\n\t\tif (dev->flags & IFF_SLAVE)\n\t\t\tbreak;\n\n\t\tif (idev && idev->cnf.disable_ipv6)\n\t\t\tbreak;\n\n\t\tif (event == NETDEV_UP) {\n\t\t\tif (!addrconf_qdisc_ok(dev)) {\n\t\t\t\t\/* device is not ready yet. *\/\n\t\t\t\tpr_info(\"ADDRCONF(NETDEV_UP): %s: link is not ready\\n\",\n\t\t\t\t\tdev->name);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (!idev && dev->mtu >= IPV6_MIN_MTU)\n\t\t\t\tidev = ipv6_add_dev(dev);\n\n\t\t\tif (!IS_ERR_OR_NULL(idev)) {\n\t\t\t\tidev->if_flags |= IF_READY;\n\t\t\t\trun_pending = 1;\n\t\t\t}\n\t\t} else {\n\t\t\tif (!addrconf_qdisc_ok(dev)) {\n\t\t\t\t\/* device is still not ready. *\/\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tif (idev) {\n\t\t\t\tif (idev->if_flags & IF_READY)\n\t\t\t\t\t\/* device is already configured. *\/\n\t\t\t\t\tbreak;\n\t\t\t\tidev->if_flags |= IF_READY;\n\t\t\t}\n\n\t\t\tpr_info(\"ADDRCONF(NETDEV_CHANGE): %s: link becomes ready\\n\",\n\t\t\t\tdev->name);\n\n\t\t\trun_pending = 1;\n\t\t}\n\n\t\tswitch (dev->type) {\n#if IS_ENABLED(CONFIG_IPV6_SIT)\n\t\tcase ARPHRD_SIT:\n\t\t\taddrconf_sit_config(dev);\n\t\t\tbreak;\n#endif\n#if IS_ENABLED(CONFIG_NET_IPGRE)\n\t\tcase ARPHRD_IPGRE:\n\t\t\taddrconf_gre_config(dev);\n\t\t\tbreak;\n#endif\n\t\tcase ARPHRD_LOOPBACK:\n\t\t\tinit_loopback(dev);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\taddrconf_dev_config(dev);\n\t\t\tbreak;\n\t\t}\n\n\t\tif (!IS_ERR_OR_NULL(idev)) {\n\t\t\tif (run_pending)\n\t\t\t\taddrconf_dad_run(idev);\n\n\t\t\t\/*\n\t\t\t * If the MTU changed during the interface down,\n\t\t\t * when the interface up, the changed MTU must be\n\t\t\t * reflected in the idev as well as routers.\n\t\t\t *\/\n\t\t\tif (idev->cnf.mtu6 != dev->mtu &&\n\t\t\t dev->mtu >= IPV6_MIN_MTU) {\n\t\t\t\trt6_mtu_change(dev, dev->mtu);\n\t\t\t\tidev->cnf.mtu6 = dev->mtu;\n\t\t\t}\n\t\t\tidev->tstamp = jiffies;\n\t\t\tinet6_ifinfo_notify(RTM_NEWLINK, idev);\n\n\t\t\t\/*\n\t\t\t * If the changed mtu during down is lower than\n\t\t\t * IPV6_MIN_MTU stop IPv6 on this interface.\n\t\t\t *\/\n\t\t\tif (dev->mtu < IPV6_MIN_MTU)\n\t\t\t\taddrconf_ifdown(dev, 1);\n\t\t}\n\t\tbreak;\n\n\tcase NETDEV_CHANGEMTU:\n\t\tif (idev && dev->mtu >= IPV6_MIN_MTU) {\n\t\t\trt6_mtu_change(dev, dev->mtu);\n\t\t\tidev->cnf.mtu6 = dev->mtu;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (!idev && dev->mtu >= IPV6_MIN_MTU) {\n\t\t\tidev = ipv6_add_dev(dev);\n\t\t\tif (!IS_ERR(idev))\n\t\t\t\tbreak;\n\t\t}\n\n\t\t\/*\n\t\t * if MTU under IPV6_MIN_MTU.\n\t\t * Stop IPv6 on this interface.\n\t\t *\/\n\n\tcase NETDEV_DOWN:\n\tcase NETDEV_UNREGISTER:\n\t\t\/*\n\t\t *\tRemove all addresses from this interface.\n\t\t *\/\n\t\taddrconf_ifdown(dev, event != NETDEV_DOWN);\n\t\tbreak;\n\n\tcase NETDEV_CHANGENAME:\n\t\tif (idev) {\n\t\t\tsnmp6_unregister_dev(idev);\n\t\t\taddrconf_sysctl_unregister(idev);\n\t\t\terr = addrconf_sysctl_register(idev);\n\t\t\tif (err)\n\t\t\t\treturn notifier_from_errno(err);\n\t\t\terr = snmp6_register_dev(idev);\n\t\t\tif (err) {\n\t\t\t\taddrconf_sysctl_unregister(idev);\n\t\t\t\treturn notifier_from_errno(err);\n\t\t\t}\n\t\t}\n\t\tbreak;\n\n\tcase NETDEV_PRE_TYPE_CHANGE:\n\tcase NETDEV_POST_TYPE_CHANGE:\n\t\taddrconf_type_change(dev, event);\n\t\tbreak;\n\t}\n\n\treturn NOTIFY_OK;\n}","target":0,"code_token_length":1032,"total_token_length":1363,"max_tokens_setting":2048} +{"idx":341363,"func":"static coroutine_fn int qcow_co_readv(BlockDriverState *bs, int64_t sector_num,\n\n int nb_sectors, QEMUIOVector *qiov)\n\n{\n\n BDRVQcowState *s = bs->opaque;\n\n int index_in_cluster;\n\n int ret = 0, n;\n\n uint64_t cluster_offset;\n\n struct iovec hd_iov;\n\n QEMUIOVector hd_qiov;\n\n uint8_t *buf;\n\n void *orig_buf;\n\n Error *err = NULL;\n\n\n\n if (qiov->niov > 1) {\n\n buf = orig_buf = qemu_try_blockalign(bs, qiov->size);\n\n if (buf == NULL) {\n\n return -ENOMEM;\n\n }\n\n } else {\n\n orig_buf = NULL;\n\n buf = (uint8_t *)qiov->iov->iov_base;\n\n }\n\n\n\n qemu_co_mutex_lock(&s->lock);\n\n\n\n while (nb_sectors != 0) {\n\n \/* prepare next request *\/\n\n cluster_offset = get_cluster_offset(bs, sector_num << 9,\n\n 0, 0, 0, 0);\n\n index_in_cluster = sector_num & (s->cluster_sectors - 1);\n\n n = s->cluster_sectors - index_in_cluster;\n\n if (n > nb_sectors) {\n\n n = nb_sectors;\n\n }\n\n\n\n if (!cluster_offset) {\n\n if (bs->backing) {\n\n \/* read from the base image *\/\n\n hd_iov.iov_base = (void *)buf;\n\n hd_iov.iov_len = n * 512;\n\n qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);\n\n qemu_co_mutex_unlock(&s->lock);\n\n ret = bdrv_co_readv(bs->backing, sector_num, n, &hd_qiov);\n\n qemu_co_mutex_lock(&s->lock);\n\n if (ret < 0) {\n\n goto fail;\n\n }\n\n } else {\n\n \/* Note: in this case, no need to wait *\/\n\n memset(buf, 0, 512 * n);\n\n }\n\n } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {\n\n \/* add AIO support for compressed blocks ? *\/\n\n if (decompress_cluster(bs, cluster_offset) < 0) {\n\n goto fail;\n\n }\n\n memcpy(buf,\n\n s->cluster_cache + index_in_cluster * 512, 512 * n);\n\n } else {\n\n if ((cluster_offset & 511) != 0) {\n\n goto fail;\n\n }\n\n hd_iov.iov_base = (void *)buf;\n\n hd_iov.iov_len = n * 512;\n\n qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);\n\n qemu_co_mutex_unlock(&s->lock);\n\n ret = bdrv_co_readv(bs->file,\n\n (cluster_offset >> 9) + index_in_cluster,\n\n n, &hd_qiov);\n\n qemu_co_mutex_lock(&s->lock);\n\n if (ret < 0) {\n\n break;\n\n }\n\n if (bs->encrypted) {\n\n assert(s->cipher);\n\n if (encrypt_sectors(s, sector_num, buf,\n\n n, false, &err) < 0) {\n\n goto fail;\n\n }\n\n }\n\n }\n\n ret = 0;\n\n\n\n nb_sectors -= n;\n\n sector_num += n;\n\n buf += n * 512;\n\n }\n\n\n\ndone:\n\n qemu_co_mutex_unlock(&s->lock);\n\n\n\n if (qiov->niov > 1) {\n\n qemu_iovec_from_buf(qiov, 0, orig_buf, qiov->size);\n\n qemu_vfree(orig_buf);\n\n }\n\n\n\n return ret;\n\n\n\nfail:\n\n error_free(err);\n\n ret = -EIO;\n\n goto done;\n\n}\n","target":0,"code_token_length":827,"total_token_length":1158,"max_tokens_setting":2048} +{"idx":49438,"func":"static int snd_timer_user_params(struct file *file,\n\t\t\t\t struct snd_timer_params __user *_params)\n{\n\tstruct snd_timer_user *tu;\n\tstruct snd_timer_params params;\n\tstruct snd_timer *t;\n\tint err;\n\n\ttu = file->private_data;\n\tif (!tu->timeri)\n\t\treturn -EBADFD;\n\tt = tu->timeri->timer;\n\tif (!t)\n\t\treturn -EBADFD;\n\tif (copy_from_user(¶ms, _params, sizeof(params)))\n\t\treturn -EFAULT;\n\tif (!(t->hw.flags & SNDRV_TIMER_HW_SLAVE)) {\n\t\tu64 resolution;\n\n\t\tif (params.ticks < 1) {\n\t\t\terr = -EINVAL;\n\t\t\tgoto _end;\n\t\t}\n\n\t\t\/* Don't allow resolution less than 1ms *\/\n\t\tresolution = snd_timer_resolution(tu->timeri);\n\t\tresolution *= params.ticks;\n\t\tif (resolution < 1000000) {\n\t\t\terr = -EINVAL;\n\t\t\tgoto _end;\n\t\t}\n\t}\n\tif (params.queue_size > 0 &&\n\t (params.queue_size < 32 || params.queue_size > 1024)) {\n\t\terr = -EINVAL;\n\t\tgoto _end;\n\t}\n\tif (params.filter & ~((1<timeri);\n\tspin_lock_irq(&t->lock);\n\ttu->timeri->flags &= ~(SNDRV_TIMER_IFLG_AUTO|\n\t\t\t SNDRV_TIMER_IFLG_EXCLUSIVE|\n\t\t\t SNDRV_TIMER_IFLG_EARLY_EVENT);\n\tif (params.flags & SNDRV_TIMER_PSFLG_AUTO)\n\t\ttu->timeri->flags |= SNDRV_TIMER_IFLG_AUTO;\n\tif (params.flags & SNDRV_TIMER_PSFLG_EXCLUSIVE)\n\t\ttu->timeri->flags |= SNDRV_TIMER_IFLG_EXCLUSIVE;\n\tif (params.flags & SNDRV_TIMER_PSFLG_EARLY_EVENT)\n\t\ttu->timeri->flags |= SNDRV_TIMER_IFLG_EARLY_EVENT;\n\tspin_unlock_irq(&t->lock);\n\tif (params.queue_size > 0 &&\n\t (unsigned int)tu->queue_size != params.queue_size) {\n\t\terr = realloc_user_queue(tu, params.queue_size);\n\t\tif (err < 0)\n\t\t\tgoto _end;\n\t}\n\tspin_lock_irq(&tu->qlock);\n\ttu->qhead = tu->qtail = tu->qused = 0;\n\tif (tu->timeri->flags & SNDRV_TIMER_IFLG_EARLY_EVENT) {\n\t\tif (tu->tread) {\n\t\t\tstruct snd_timer_tread tread;\n\t\t\tmemset(&tread, 0, sizeof(tread));\n\t\t\ttread.event = SNDRV_TIMER_EVENT_EARLY;\n\t\t\ttread.tstamp.tv_sec = 0;\n\t\t\ttread.tstamp.tv_nsec = 0;\n\t\t\ttread.val = 0;\n\t\t\tsnd_timer_user_append_to_tqueue(tu, &tread);\n\t\t} else {\n\t\t\tstruct snd_timer_read *r = &tu->queue[0];\n\t\t\tr->resolution = 0;\n\t\t\tr->ticks = 0;\n\t\t\ttu->qused++;\n\t\t\ttu->qtail++;\n\t\t}\n\t}\n\ttu->filter = params.filter;\n\ttu->ticks = params.ticks;\n\tspin_unlock_irq(&tu->qlock);\n\terr = 0;\n _end:\n\tif (copy_to_user(_params, ¶ms, sizeof(params)))\n\t\treturn -EFAULT;\n\treturn err;\n}","target":0,"code_token_length":901,"total_token_length":1232,"max_tokens_setting":2048} +{"idx":304421,"func":" Status TrySimplify(NodeDef* node, string* simplified_node_name) override {\n Tensor pow;\n if (!GetTensorFromConstNode(node->input(1), &pow)) return Status::OK();\n complex128 prev, curr;\n for (int i = 0; i < pow.NumElements(); ++i) {\n if (!GetElementUnexhaustive(pow, i, {pow.dtype()}, &curr)) {\n \/\/ input data type is not supported by Pow. Skip.\n return Status::OK();\n }\n if (i != 0 && curr != prev) {\n \/\/ pow has different values on different elements. Skip.\n return Status::OK();\n }\n prev = curr;\n }\n NodeDef *x, *y;\n TF_RETURN_IF_ERROR(GetInputNode(node->input(0), &x));\n TF_RETURN_IF_ERROR(GetInputNode(node->input(1), &y));\n const auto& value_props =\n ctx().graph_properties->GetInputProperties(node->name())[0];\n const TensorShapeProto& output_shape =\n ctx().graph_properties->GetOutputProperties(node->name())[0].shape();\n if (curr == complex128(2, 0)) {\n node->set_op(\"Square\");\n node->set_input(1, AsControlDependency(y->name()));\n AddToOptimizationQueue(node);\n AddToOptimizationQueue(y);\n } else if (curr == complex128(3, 0)) {\n \/\/ TODO(courbet): Use 'Cube' when it's added to TF ops.\n if (NodeIsOnCpu(*node)) {\n \/\/ We create an inner square node: inner_square = square(x)\n const NodeScopeAndName scope_and_name =\n ParseNodeScopeAndName(node->name());\n const string inner_square_name =\n OptimizedNodeName(scope_and_name, \"_inner\");\n NodeDef* inner_square_node = ctx().node_map->GetNode(inner_square_name);\n if (inner_square_node == nullptr) {\n inner_square_node = AddCopyNode(inner_square_name, node);\n inner_square_node->set_op(\"Square\");\n inner_square_node->mutable_input()->RemoveLast();\n }\n ctx().node_map->AddOutput(x->name(), inner_square_node->name());\n \/\/ We modify `node`: node = mul(x, inner_square);\n node->set_op(\"Mul\");\n node->set_input(1, inner_square_node->name());\n node->add_input(AsControlDependency(y->name()));\n\n AddToOptimizationQueue(node);\n AddToOptimizationQueue(inner_square_node);\n AddToOptimizationQueue(y);\n }\n } else if (curr == complex128(1, 0) &&\n ShapesSymbolicallyEqual(value_props.shape(), output_shape)) {\n \/\/ Pow could be used to broadcast, so make sure the shapes of the two\n \/\/ arguments are identical before replacing Pow with Identity.\n node->set_op(\"Identity\");\n node->set_input(1, AsControlDependency(y->name()));\n AddToOptimizationQueue(node);\n AddToOptimizationQueue(y);\n } else if (curr == complex128(0.5, 0)) {\n node->set_op(\"Sqrt\");\n node->set_input(1, AsControlDependency(y->name()));\n AddToOptimizationQueue(node);\n AddToOptimizationQueue(y);\n } else if (curr == complex128(0, 0) &&\n ShapesSymbolicallyEqual(value_props.shape(), output_shape) &&\n PartialTensorShape(output_shape).IsFullyDefined()) {\n const auto dtype = node->attr().at(\"T\").type();\n Tensor ones(dtype, output_shape);\n for (int i = 0; i < ones.NumElements(); ++i) {\n TF_RETURN_IF_ERROR(SetElementToOne(i, &ones));\n }\n node->set_op(\"Const\");\n (*node->mutable_attr())[\"dtype\"].set_type(dtype);\n node->mutable_attr()->erase(\"T\");\n ones.AsProtoTensorContent(\n (*node->mutable_attr())[\"value\"].mutable_tensor());\n node->set_input(0, AsControlDependency(x->name()));\n node->set_input(1, AsControlDependency(y->name()));\n AddToOptimizationQueue(node);\n AddToOptimizationQueue(x);\n AddToOptimizationQueue(y);\n } else if (curr == complex128(-0.5, 0)) {\n node->set_op(\"Rsqrt\");\n node->set_input(1, AsControlDependency(y->name()));\n AddToOptimizationQueue(node);\n AddToOptimizationQueue(y);\n } else if (curr == complex128(-1, 0)) {\n node->set_op(\"Reciprocal\");\n node->set_input(1, AsControlDependency(y->name()));\n AddToOptimizationQueue(node);\n AddToOptimizationQueue(y);\n }\n return Status::OK();\n }","target":0,"code_token_length":1060,"total_token_length":1391,"max_tokens_setting":2048} +{"idx":211671,"func":"static int parseOptions(int argc, char **argv) {\n int i;\n\n for (i = 1; i < argc; i++) {\n int lastarg = i==argc-1;\n\n if (!strcmp(argv[i],\"-h\") && !lastarg) {\n sdsfree(config.hostip);\n config.hostip = sdsnew(argv[++i]);\n } else if (!strcmp(argv[i],\"-h\") && lastarg) {\n usage();\n } else if (!strcmp(argv[i],\"--help\")) {\n usage();\n } else if (!strcmp(argv[i],\"-x\")) {\n config.stdinarg = 1;\n } else if (!strcmp(argv[i],\"-p\") && !lastarg) {\n config.hostport = atoi(argv[++i]);\n } else if (!strcmp(argv[i],\"-s\") && !lastarg) {\n config.hostsocket = argv[++i];\n } else if (!strcmp(argv[i],\"-r\") && !lastarg) {\n config.repeat = strtoll(argv[++i],NULL,10);\n } else if (!strcmp(argv[i],\"-i\") && !lastarg) {\n double seconds = atof(argv[++i]);\n config.interval = seconds*1000000;\n } else if (!strcmp(argv[i],\"-n\") && !lastarg) {\n config.dbnum = atoi(argv[++i]);\n } else if (!strcmp(argv[i],\"-a\") && !lastarg) {\n fputs(\"Warning: Using a password with '-a' option on the command line interface may not be safe.\\n\", stderr);\n config.auth = argv[++i];\n } else if (!strcmp(argv[i],\"-u\") && !lastarg) {\n parseRedisUri(argv[++i]);\n } else if (!strcmp(argv[i],\"--raw\")) {\n config.output = OUTPUT_RAW;\n } else if (!strcmp(argv[i],\"--no-raw\")) {\n config.output = OUTPUT_STANDARD;\n } else if (!strcmp(argv[i],\"--csv\")) {\n config.output = OUTPUT_CSV;\n } else if (!strcmp(argv[i],\"--latency\")) {\n config.latency_mode = 1;\n } else if (!strcmp(argv[i],\"--latency-dist\")) {\n config.latency_dist_mode = 1;\n } else if (!strcmp(argv[i],\"--mono\")) {\n spectrum_palette = spectrum_palette_mono;\n spectrum_palette_size = spectrum_palette_mono_size;\n } else if (!strcmp(argv[i],\"--latency-history\")) {\n config.latency_mode = 1;\n config.latency_history = 1;\n } else if (!strcmp(argv[i],\"--lru-test\") && !lastarg) {\n config.lru_test_mode = 1;\n config.lru_test_sample_size = strtoll(argv[++i],NULL,10);\n } else if (!strcmp(argv[i],\"--slave\")) {\n config.slave_mode = 1;\n } else if (!strcmp(argv[i],\"--stat\")) {\n config.stat_mode = 1;\n } else if (!strcmp(argv[i],\"--scan\")) {\n config.scan_mode = 1;\n } else if (!strcmp(argv[i],\"--pattern\") && !lastarg) {\n config.pattern = argv[++i];\n } else if (!strcmp(argv[i],\"--intrinsic-latency\") && !lastarg) {\n config.intrinsic_latency_mode = 1;\n config.intrinsic_latency_duration = atoi(argv[++i]);\n } else if (!strcmp(argv[i],\"--rdb\") && !lastarg) {\n config.getrdb_mode = 1;\n config.rdb_filename = argv[++i];\n } else if (!strcmp(argv[i],\"--pipe\")) {\n config.pipe_mode = 1;\n } else if (!strcmp(argv[i],\"--pipe-timeout\") && !lastarg) {\n config.pipe_timeout = atoi(argv[++i]);\n } else if (!strcmp(argv[i],\"--bigkeys\")) {\n config.bigkeys = 1;\n } else if (!strcmp(argv[i],\"--hotkeys\")) {\n config.hotkeys = 1;\n } else if (!strcmp(argv[i],\"--eval\") && !lastarg) {\n config.eval = argv[++i];\n } else if (!strcmp(argv[i],\"--ldb\")) {\n config.eval_ldb = 1;\n config.output = OUTPUT_RAW;\n } else if (!strcmp(argv[i],\"--ldb-sync-mode\")) {\n config.eval_ldb = 1;\n config.eval_ldb_sync = 1;\n config.output = OUTPUT_RAW;\n } else if (!strcmp(argv[i],\"-c\")) {\n config.cluster_mode = 1;\n } else if (!strcmp(argv[i],\"-d\") && !lastarg) {\n sdsfree(config.mb_delim);\n config.mb_delim = sdsnew(argv[++i]);\n } else if (!strcmp(argv[i],\"-v\") || !strcmp(argv[i], \"--version\")) {\n sds version = cliVersion();\n printf(\"redis-cli %s\\n\", version);\n sdsfree(version);\n exit(0);\n } else {\n if (argv[i][0] == '-') {\n fprintf(stderr,\n \"Unrecognized option or bad number of args for: '%s'\\n\",\n argv[i]);\n exit(1);\n } else {\n \/* Likely the command name, stop here. *\/\n break;\n }\n }\n }\n\n \/* --ldb requires --eval. *\/\n if (config.eval_ldb && config.eval == NULL) {\n fprintf(stderr,\"Options --ldb and --ldb-sync-mode require --eval.\\n\");\n fprintf(stderr,\"Try %s --help for more information.\\n\", argv[0]);\n exit(1);\n }\n return i;\n}\n","target":0,"code_token_length":1212,"total_token_length":1543,"max_tokens_setting":2048} +{"idx":433023,"func":"v9fs_stat2inode_dotl(struct p9_stat_dotl *stat, struct inode *inode,\n\t\t unsigned int flags)\n{\n\tumode_t mode;\n\tstruct v9fs_inode *v9inode = V9FS_I(inode);\n\n\tif ((stat->st_result_mask & P9_STATS_BASIC) == P9_STATS_BASIC) {\n\t\tinode->i_atime.tv_sec = stat->st_atime_sec;\n\t\tinode->i_atime.tv_nsec = stat->st_atime_nsec;\n\t\tinode->i_mtime.tv_sec = stat->st_mtime_sec;\n\t\tinode->i_mtime.tv_nsec = stat->st_mtime_nsec;\n\t\tinode->i_ctime.tv_sec = stat->st_ctime_sec;\n\t\tinode->i_ctime.tv_nsec = stat->st_ctime_nsec;\n\t\tinode->i_uid = stat->st_uid;\n\t\tinode->i_gid = stat->st_gid;\n\t\tset_nlink(inode, stat->st_nlink);\n\n\t\tmode = stat->st_mode & S_IALLUGO;\n\t\tmode |= inode->i_mode & ~S_IALLUGO;\n\t\tinode->i_mode = mode;\n\n\t\tif (!(flags & V9FS_STAT2INODE_KEEP_ISIZE))\n\t\t\tv9fs_i_size_write(inode, stat->st_size);\n\t\tinode->i_blocks = stat->st_blocks;\n\t} else {\n\t\tif (stat->st_result_mask & P9_STATS_ATIME) {\n\t\t\tinode->i_atime.tv_sec = stat->st_atime_sec;\n\t\t\tinode->i_atime.tv_nsec = stat->st_atime_nsec;\n\t\t}\n\t\tif (stat->st_result_mask & P9_STATS_MTIME) {\n\t\t\tinode->i_mtime.tv_sec = stat->st_mtime_sec;\n\t\t\tinode->i_mtime.tv_nsec = stat->st_mtime_nsec;\n\t\t}\n\t\tif (stat->st_result_mask & P9_STATS_CTIME) {\n\t\t\tinode->i_ctime.tv_sec = stat->st_ctime_sec;\n\t\t\tinode->i_ctime.tv_nsec = stat->st_ctime_nsec;\n\t\t}\n\t\tif (stat->st_result_mask & P9_STATS_UID)\n\t\t\tinode->i_uid = stat->st_uid;\n\t\tif (stat->st_result_mask & P9_STATS_GID)\n\t\t\tinode->i_gid = stat->st_gid;\n\t\tif (stat->st_result_mask & P9_STATS_NLINK)\n\t\t\tset_nlink(inode, stat->st_nlink);\n\t\tif (stat->st_result_mask & P9_STATS_MODE) {\n\t\t\tinode->i_mode = stat->st_mode;\n\t\t\tif ((S_ISBLK(inode->i_mode)) ||\n\t\t\t\t\t\t(S_ISCHR(inode->i_mode)))\n\t\t\t\tinit_special_inode(inode, inode->i_mode,\n\t\t\t\t\t\t\t\tinode->i_rdev);\n\t\t}\n\t\tif (stat->st_result_mask & P9_STATS_RDEV)\n\t\t\tinode->i_rdev = new_decode_dev(stat->st_rdev);\n\t\tif (!(flags & V9FS_STAT2INODE_KEEP_ISIZE) &&\n\t\t stat->st_result_mask & P9_STATS_SIZE)\n\t\t\tv9fs_i_size_write(inode, stat->st_size);\n\t\tif (stat->st_result_mask & P9_STATS_BLOCKS)\n\t\t\tinode->i_blocks = stat->st_blocks;\n\t}\n\tif (stat->st_result_mask & P9_STATS_GEN)\n\t\tinode->i_generation = stat->st_gen;\n\n\t\/* Currently we don't support P9_STATS_BTIME and P9_STATS_DATA_VERSION\n\t * because the inode structure does not have fields for them.\n\t *\/\n\tv9inode->cache_validity &= ~V9FS_INO_INVALID_ATTR;\n}","target":0,"code_token_length":776,"total_token_length":1107,"max_tokens_setting":2048} +{"idx":331603,"func":"static int vb_decode_framedata(VBDecContext *c, const uint8_t *buf, int offset)\n\n{\n\n uint8_t *prev, *cur;\n\n int blk, blocks, t, blk2;\n\n int blocktypes = 0;\n\n int x, y, a, b;\n\n int pattype, pattern;\n\n const int width = c->avctx->width;\n\n uint8_t *pstart = c->prev_frame;\n\n uint8_t *pend = c->prev_frame + width*c->avctx->height;\n\n\n\n prev = c->prev_frame + offset;\n\n cur = c->frame;\n\n\n\n blocks = (c->avctx->width >> 2) * (c->avctx->height >> 2);\n\n blk2 = 0;\n\n for(blk = 0; blk < blocks; blk++){\n\n if(!(blk & 3))\n\n blocktypes = bytestream_get_byte(&buf);\n\n switch(blocktypes & 0xC0){\n\n case 0x00: \/\/skip\n\n for(y = 0; y < 4; y++)\n\n if(check_line(prev + y*width, pstart, pend))\n\n memcpy(cur + y*width, prev + y*width, 4);\n\n else\n\n memset(cur + y*width, 0, 4);\n\n break;\n\n case 0x40:\n\n t = bytestream_get_byte(&buf);\n\n if(!t){ \/\/raw block\n\n for(y = 0; y < 4; y++)\n\n memcpy(cur + y*width, buf + y*4, 4);\n\n buf += 16;\n\n }else{ \/\/ motion compensation\n\n x = ((t & 0xF)^8) - 8;\n\n y = ((t >> 4) ^8) - 8;\n\n t = x + y*width;\n\n for(y = 0; y < 4; y++)\n\n if(check_line(prev + t + y*width, pstart, pend))\n\n memcpy(cur + y*width, prev + t + y*width, 4);\n\n else\n\n memset(cur + y*width, 0, 4);\n\n }\n\n break;\n\n case 0x80: \/\/ fill\n\n t = bytestream_get_byte(&buf);\n\n for(y = 0; y < 4; y++)\n\n memset(cur + y*width, t, 4);\n\n break;\n\n case 0xC0: \/\/ pattern fill\n\n t = bytestream_get_byte(&buf);\n\n pattype = t >> 6;\n\n pattern = vb_patterns[t & 0x3F];\n\n switch(pattype){\n\n case 0:\n\n a = bytestream_get_byte(&buf);\n\n b = bytestream_get_byte(&buf);\n\n for(y = 0; y < 4; y++)\n\n for(x = 0; x < 4; x++, pattern >>= 1)\n\n cur[x + y*width] = (pattern & 1) ? b : a;\n\n break;\n\n case 1:\n\n pattern = ~pattern;\n\n case 2:\n\n a = bytestream_get_byte(&buf);\n\n for(y = 0; y < 4; y++)\n\n for(x = 0; x < 4; x++, pattern >>= 1)\n\n if(pattern & 1 && check_pixel(prev + x + y*width, pstart, pend))\n\n cur[x + y*width] = prev[x + y*width];\n\n else\n\n cur[x + y*width] = a;\n\n break;\n\n case 3:\n\n av_log(c->avctx, AV_LOG_ERROR, \"Invalid opcode seen @%d\\n\",blk);\n\n return -1;\n\n }\n\n break;\n\n }\n\n blocktypes <<= 2;\n\n cur += 4;\n\n prev += 4;\n\n blk2++;\n\n if(blk2 == (width >> 2)){\n\n blk2 = 0;\n\n cur += width * 3;\n\n prev += width * 3;\n\n }\n\n }\n\n return 0;\n\n}\n","target":0,"code_token_length":874,"total_token_length":1205,"max_tokens_setting":2048} +{"idx":87089,"func":"static int init_shdr(ELFOBJ *bin) {\n\tut32 shdr_size;\n\tut8 shdr[sizeof (Elf_(Shdr))] = {0};\n\tint i, j, len;\n\n\tif (!bin || bin->shdr) {\n\t\treturn true;\n\t}\n\tif (!UT32_MUL (&shdr_size, bin->ehdr.e_shnum, sizeof (Elf_(Shdr)))) {\n\t\treturn false;\n\t}\n\tif (shdr_size < 1) {\n\t\treturn false;\n\t}\n\tif (shdr_size > bin->size) {\n\t\treturn false;\n\t}\n\tif (bin->ehdr.e_shoff > bin->size) {\n\t\treturn false;\n\t}\n\tif (bin->ehdr.e_shoff + shdr_size > bin->size) {\n\t\treturn false;\n\t}\n\tif (!(bin->shdr = calloc (1, shdr_size + 1))) {\n\t\tperror (\"malloc (shdr)\");\n\t\treturn false;\n\t}\n\tsdb_num_set (bin->kv, \"elf_shdr.offset\", bin->ehdr.e_shoff, 0);\n\tsdb_num_set (bin->kv, \"elf_shdr.size\", sizeof (Elf_(Shdr)), 0);\n\tsdb_set (bin->kv, \"elf_s_type.cparse\", \"enum elf_s_type {SHT_NULL=0,SHT_PROGBITS=1,\"\n\t\t\t\"SHT_SYMTAB=2,SHT_STRTAB=3,SHT_RELA=4,SHT_HASH=5,SHT_DYNAMIC=6,SHT_NOTE=7,\"\n\t\t\t\"SHT_NOBITS=8,SHT_REL=9,SHT_SHLIB=10,SHT_DYNSYM=11,SHT_LOOS=0x60000000,\"\n\t\t\t\"SHT_HIOS=0x6fffffff,SHT_LOPROC=0x70000000,SHT_HIPROC=0x7fffffff};\", 0);\n\n\tfor (i = 0; i < bin->ehdr.e_shnum; i++) {\n\t\tj = 0;\n\t\tlen = r_buf_read_at (bin->b, bin->ehdr.e_shoff + i * sizeof (Elf_(Shdr)), shdr, sizeof (Elf_(Shdr)));\n\t\tif (len < 1) {\n\t\t\tbprintf (\"Warning: read (shdr) at 0x%\"PFMT64x\"\\n\", (ut64) bin->ehdr.e_shoff);\n\t\t\tR_FREE (bin->shdr);\n\t\t\treturn false;\n\t\t}\n\t\tbin->shdr[i].sh_name = READ32 (shdr, j)\n\t\tbin->shdr[i].sh_type = READ32 (shdr, j)\n#if R_BIN_ELF64\n\t\tbin->shdr[i].sh_flags = READ64 (shdr, j)\n\t\tbin->shdr[i].sh_addr = READ64 (shdr, j)\n\t\tbin->shdr[i].sh_offset = READ64 (shdr, j)\n\t\tbin->shdr[i].sh_size = READ64 (shdr, j)\n\t\tbin->shdr[i].sh_link = READ32 (shdr, j)\n\t\tbin->shdr[i].sh_info = READ32 (shdr, j)\n\t\tbin->shdr[i].sh_addralign = READ64 (shdr, j)\n\t\tbin->shdr[i].sh_entsize = READ64 (shdr, j)\n#else\n\t\tbin->shdr[i].sh_flags = READ32 (shdr, j)\n\t\tbin->shdr[i].sh_addr = READ32 (shdr, j)\n\t\tbin->shdr[i].sh_offset = READ32 (shdr, j)\n\t\tbin->shdr[i].sh_size = READ32 (shdr, j)\n\t\tbin->shdr[i].sh_link = READ32 (shdr, j)\n\t\tbin->shdr[i].sh_info = READ32 (shdr, j)\n\t\tbin->shdr[i].sh_addralign = READ32 (shdr, j)\n\t\tbin->shdr[i].sh_entsize = READ32 (shdr, j)\n#endif\n\t}\n\n#if R_BIN_ELF64\n\tsdb_set (bin->kv, \"elf_s_flags_64.cparse\", \"enum elf_s_flags_64 {SF64_None=0,SF64_Exec=1,\"\n\t\t\t\"SF64_Alloc=2,SF64_Alloc_Exec=3,SF64_Write=4,SF64_Write_Exec=5,\"\n\t\t\t\"SF64_Write_Alloc=6,SF64_Write_Alloc_Exec=7};\", 0);\n\tsdb_set (bin->kv, \"elf_shdr.format\", \"x[4]E[8]Eqqqxxqq name (elf_s_type)type\"\n\t\t\t\" (elf_s_flags_64)flags addr offset size link info addralign entsize\", 0);\n#else\n\tsdb_set (bin->kv, \"elf_s_flags_32.cparse\", \"enum elf_s_flags_32 {SF32_None=0,SF32_Exec=1,\"\n\t\t\t\"SF32_Alloc=2,SF32_Alloc_Exec=3,SF32_Write=4,SF32_Write_Exec=5,\"\n\t\t\t\"SF32_Write_Alloc=6,SF32_Write_Alloc_Exec=7};\", 0);\n\tsdb_set (bin->kv, \"elf_shdr.format\", \"x[4]E[4]Exxxxxxx name (elf_s_type)type\"\n\t\t\t\" (elf_s_flags_32)flags addr offset size link info addralign entsize\", 0);\n#endif\n\treturn true;\n\t\/\/ Usage example:\n\t\/\/ > td `k bin\/cur\/info\/elf_s_type.cparse`; td `k bin\/cur\/info\/elf_s_flags_64.cparse`\n\t\/\/ > pf `k bin\/cur\/info\/elf_shdr.format` @ `k bin\/cur\/info\/elf_shdr.offset`\n}","target":0,"code_token_length":1341,"total_token_length":1672,"max_tokens_setting":2048} +{"idx":499784,"func":"QPDFWriter::writeTrailer(trailer_e which, int size, bool xref_stream,\n qpdf_offset_t prev, int linearization_pass)\n{\n QPDFObjectHandle trailer = getTrimmedTrailer();\n if (! xref_stream)\n {\n\twriteString(\"trailer <<\");\n }\n writeStringQDF(\"\\n\");\n if (which == t_lin_second)\n {\n\twriteString(\" \/Size \");\n\twriteString(QUtil::int_to_string(size));\n }\n else\n {\n\tstd::set keys = trailer.getKeys();\n\tfor (std::set::iterator iter = keys.begin();\n\t iter != keys.end(); ++iter)\n\t{\n\t std::string const& key = *iter;\n\t writeStringQDF(\" \");\n\t writeStringNoQDF(\" \");\n\t writeString(QPDF_Name::normalizeName(key));\n\t writeString(\" \");\n\t if (key == \"\/Size\")\n\t {\n\t\twriteString(QUtil::int_to_string(size));\n\t\tif (which == t_lin_first)\n\t\t{\n\t\t writeString(\" \/Prev \");\n\t\t qpdf_offset_t pos = this->m->pipeline->getCount();\n\t\t writeString(QUtil::int_to_string(prev));\n\t\t int nspaces =\n QIntC::to_int(pos - this->m->pipeline->getCount() + 21);\n\t\t if (nspaces < 0)\n {\n throw std::logic_error(\n \"QPDFWriter: no padding required in trailer\");\n }\n\t\t writePad(nspaces);\n\t\t}\n\t }\n\t else\n\t {\n\t\tunparseChild(trailer.getKey(key), 1, 0);\n\t }\n\t writeStringQDF(\"\\n\");\n\t}\n }\n\n \/\/ Write ID\n writeStringQDF(\" \");\n writeString(\" \/ID [\");\n if (linearization_pass == 1)\n {\n\tstd::string original_id1 = getOriginalID1();\n if (original_id1.empty())\n {\n writeString(\"<00000000000000000000000000000000>\");\n }\n else\n {\n \/\/ Write a string of zeroes equal in length to the\n \/\/ representation of the original ID. While writing the\n \/\/ original ID would have the same number of bytes, it\n \/\/ would cause a change to the deterministic ID generated\n \/\/ by older versions of the software that hard-coded the\n \/\/ length of the ID to 16 bytes.\n writeString(\"<\");\n size_t len = QPDF_String(original_id1).unparse(true).length() - 2;\n for (size_t i = 0; i < len; ++i)\n {\n writeString(\"0\");\n }\n writeString(\">\");\n }\n writeString(\"<00000000000000000000000000000000>\");\n }\n else\n {\n if ((linearization_pass == 0) && (this->m->deterministic_id))\n {\n computeDeterministicIDData();\n }\n generateID();\n writeString(QPDF_String(this->m->id1).unparse(true));\n writeString(QPDF_String(this->m->id2).unparse(true));\n }\n writeString(\"]\");\n\n if (which != t_lin_second)\n {\n\t\/\/ Write reference to encryption dictionary\n\tif (this->m->encrypted)\n\t{\n\t writeString(\" \/Encrypt \");\n\t writeString(QUtil::int_to_string(this->m->encryption_dict_objid));\n\t writeString(\" 0 R\");\n\t}\n }\n\n writeStringQDF(\"\\n\");\n writeStringNoQDF(\" \");\n writeString(\">>\");\n}","target":0,"code_token_length":807,"total_token_length":1138,"max_tokens_setting":2048} +{"idx":351773,"func":"CalendarRegressionTest::runIndexedTest( int32_t index, UBool exec, const char* &name, char* \/*par*\/ )\n{\n \/\/ if (exec) logln((UnicodeString)\"TestSuite NumberFormatRegressionTest\");\n switch (index) {\n CASE(0,test4100311);\n CASE(1,test4074758);\n CASE(2,test4028518);\n CASE(3,test4031502);\n CASE(4,test4035301);\n CASE(5,test4040996);\n CASE(6,test4051765);\n CASE(7,test4061476);\n CASE(8,test4070502);\n CASE(9,test4071197);\n CASE(10,test4071385);\n CASE(11,test4073929);\n CASE(12,test4083167);\n CASE(13,test4086724);\n CASE(14,test4095407);\n CASE(15,test4096231);\n CASE(16,test4096539);\n CASE(17,test41003112);\n CASE(18,test4103271);\n CASE(19,test4106136);\n CASE(20,test4108764);\n CASE(21,test4114578);\n CASE(22,test4118384);\n CASE(23,test4125881);\n CASE(24,test4125892);\n CASE(25,test4141665);\n CASE(26,test4142933);\n CASE(27,test4145158);\n CASE(28,test4145983);\n CASE(29,test4147269);\n\n CASE(30,Test4149677);\n CASE(31,Test4162587);\n CASE(32,Test4165343);\n CASE(33,Test4166109);\n CASE(34,Test4167060);\n CASE(35,Test4197699);\n CASE(36,TestJ81);\n CASE(37,TestJ438);\n CASE(38,TestLeapFieldDifference);\n CASE(39,TestMalaysianInstance);\n CASE(40,test4059654);\n CASE(41,test4092362);\n CASE(42,TestWeekShift);\n CASE(43,TestTimeZoneTransitionAdd);\n CASE(44,TestDeprecates);\n CASE(45,TestT5555);\n CASE(46,TestT6745);\n CASE(47,TestT8057);\n CASE(48,TestT8596);\n CASE(49,Test9019);\n CASE(50,TestT9452);\n CASE(51,TestT11632);\n default: name = \"\"; break;\n }\n}","target":1,"code_token_length":766,"total_token_length":1097,"max_tokens_setting":2048} +{"idx":343504,"func":"int __udp_lib_get_port(struct sock *sk, unsigned short snum,\n\t\t struct hlist_head udptable[], int *port_rover,\n\t\t int (*saddr_comp)(const struct sock *sk1,\n\t\t\t\t\t const struct sock *sk2 ) )\n{\n\tstruct hlist_node *node;\n\tstruct hlist_head *head;\n\tstruct sock *sk2;\n\tint error = 1;\n\n\twrite_lock_bh(&udp_hash_lock);\n\tif (snum == 0) {\n\t\tint best_size_so_far, best, result, i;\n\n\t\tif (*port_rover > sysctl_local_port_range[1] ||\n\t\t *port_rover < sysctl_local_port_range[0])\n\t\t\t*port_rover = sysctl_local_port_range[0];\n\t\tbest_size_so_far = 32767;\n\t\tbest = result = *port_rover;\n\t\tfor (i = 0; i < UDP_HTABLE_SIZE; i++, result++) {\n\t\t\tint size;\n\n\t\t\thead = &udptable[result & (UDP_HTABLE_SIZE - 1)];\n\t\t\tif (hlist_empty(head)) {\n\t\t\t\tif (result > sysctl_local_port_range[1])\n\t\t\t\t\tresult = sysctl_local_port_range[0] +\n\t\t\t\t\t\t((result - sysctl_local_port_range[0]) &\n\t\t\t\t\t\t (UDP_HTABLE_SIZE - 1));\n\t\t\t\tgoto gotit;\n\t\t\t}\n\t\t\tsize = 0;\n\t\t\tsk_for_each(sk2, node, head) {\n\t\t\t\tif (++size >= best_size_so_far)\n\t\t\t\t\tgoto next;\n\t\t\t}\n\t\t\tbest_size_so_far = size;\n\t\t\tbest = result;\n\t\tnext:\n\t\t\t;\n\t\t}\n\t\tresult = best;\n\t\tfor (i = 0; i < (1 << 16) \/ UDP_HTABLE_SIZE;\n\t\t i++, result += UDP_HTABLE_SIZE) {\n\t\t\tif (result > sysctl_local_port_range[1])\n\t\t\t\tresult = sysctl_local_port_range[0]\n\t\t\t\t\t+ ((result - sysctl_local_port_range[0]) &\n\t\t\t\t\t (UDP_HTABLE_SIZE - 1));\n\t\t\tif (! __udp_lib_lport_inuse(result, udptable))\n\t\t\t\tbreak;\n\t\t}\n\t\tif (i >= (1 << 16) \/ UDP_HTABLE_SIZE)\n\t\t\tgoto fail;\ngotit:\n\t\t*port_rover = snum = result;\n\t} else {\n\t\thead = &udptable[snum & (UDP_HTABLE_SIZE - 1)];\n\n\t\tsk_for_each(sk2, node, head)\n\t\t\tif (sk2->sk_hash == snum &&\n\t\t\t sk2 != sk &&\n\t\t\t (!sk2->sk_reuse || !sk->sk_reuse) &&\n\t\t\t (!sk2->sk_bound_dev_if || !sk->sk_bound_dev_if\n\t\t\t || sk2->sk_bound_dev_if == sk->sk_bound_dev_if) &&\n\t\t\t (*saddr_comp)(sk, sk2) )\n\t\t\t\tgoto fail;\n\t}\n\tinet_sk(sk)->num = snum;\n\tsk->sk_hash = snum;\n\tif (sk_unhashed(sk)) {\n\t\thead = &udptable[snum & (UDP_HTABLE_SIZE - 1)];\n\t\tsk_add_node(sk, head);\n\t\tsock_prot_inc_use(sk->sk_prot);\n\t}\n\terror = 0;\nfail:\n\twrite_unlock_bh(&udp_hash_lock);\n\treturn error;\n}","target":1,"code_token_length":710,"total_token_length":1041,"max_tokens_setting":2048} +{"idx":293526,"func":"i915_gem_execbuffer_relocate_entry(struct drm_i915_gem_object *obj,\n\t\t\t\t struct eb_objects *eb,\n\t\t\t\t struct drm_i915_gem_relocation_entry *reloc)\n{\n\tstruct drm_device *dev = obj->base.dev;\n\tstruct drm_gem_object *target_obj;\n\tuint32_t target_offset;\n\tint ret = -EINVAL;\n\n\t\/* we've already hold a reference to all valid objects *\/\n\ttarget_obj = &eb_get_object(eb, reloc->target_handle)->base;\n\tif (unlikely(target_obj == NULL))\n\t\treturn -ENOENT;\n\n\ttarget_offset = to_intel_bo(target_obj)->gtt_offset;\n\n\t\/* The target buffer should have appeared before us in the\n\t * exec_object list, so it should have a GTT space bound by now.\n\t *\/\n\tif (unlikely(target_offset == 0)) {\n\t\tDRM_DEBUG(\"No GTT space found for object %d\\n\",\n\t\t\t reloc->target_handle);\n\t\treturn ret;\n\t}\n\n\t\/* Validate that the target is in a valid r\/w GPU domain *\/\n\tif (unlikely(reloc->write_domain & (reloc->write_domain - 1))) {\n\t\tDRM_DEBUG(\"reloc with multiple write domains: \"\n\t\t\t \"obj %p target %d offset %d \"\n\t\t\t \"read %08x write %08x\",\n\t\t\t obj, reloc->target_handle,\n\t\t\t (int) reloc->offset,\n\t\t\t reloc->read_domains,\n\t\t\t reloc->write_domain);\n\t\treturn ret;\n\t}\n\tif (unlikely((reloc->write_domain | reloc->read_domains)\n\t\t & ~I915_GEM_GPU_DOMAINS)) {\n\t\tDRM_DEBUG(\"reloc with read\/write non-GPU domains: \"\n\t\t\t \"obj %p target %d offset %d \"\n\t\t\t \"read %08x write %08x\",\n\t\t\t obj, reloc->target_handle,\n\t\t\t (int) reloc->offset,\n\t\t\t reloc->read_domains,\n\t\t\t reloc->write_domain);\n\t\treturn ret;\n\t}\n\tif (unlikely(reloc->write_domain && target_obj->pending_write_domain &&\n\t\t reloc->write_domain != target_obj->pending_write_domain)) {\n\t\tDRM_DEBUG(\"Write domain conflict: \"\n\t\t\t \"obj %p target %d offset %d \"\n\t\t\t \"new %08x old %08x\\n\",\n\t\t\t obj, reloc->target_handle,\n\t\t\t (int) reloc->offset,\n\t\t\t reloc->write_domain,\n\t\t\t target_obj->pending_write_domain);\n\t\treturn ret;\n\t}\n\n\ttarget_obj->pending_read_domains |= reloc->read_domains;\n\ttarget_obj->pending_write_domain |= reloc->write_domain;\n\n\t\/* If the relocation already has the right value in it, no\n\t * more work needs to be done.\n\t *\/\n\tif (target_offset == reloc->presumed_offset)\n\t\treturn 0;\n\n\t\/* Check that the relocation address is valid... *\/\n\tif (unlikely(reloc->offset > obj->base.size - 4)) {\n\t\tDRM_DEBUG(\"Relocation beyond object bounds: \"\n\t\t\t \"obj %p target %d offset %d size %d.\\n\",\n\t\t\t obj, reloc->target_handle,\n\t\t\t (int) reloc->offset,\n\t\t\t (int) obj->base.size);\n\t\treturn ret;\n\t}\n\tif (unlikely(reloc->offset & 3)) {\n\t\tDRM_DEBUG(\"Relocation not 4-byte aligned: \"\n\t\t\t \"obj %p target %d offset %d.\\n\",\n\t\t\t obj, reloc->target_handle,\n\t\t\t (int) reloc->offset);\n\t\treturn ret;\n\t}\n\n\treloc->delta += target_offset;\n\tif (obj->base.write_domain == I915_GEM_DOMAIN_CPU) {\n\t\tuint32_t page_offset = reloc->offset & ~PAGE_MASK;\n\t\tchar *vaddr;\n\n\t\tvaddr = kmap_atomic(obj->pages[reloc->offset >> PAGE_SHIFT]);\n\t\t*(uint32_t *)(vaddr + page_offset) = reloc->delta;\n\t\tkunmap_atomic(vaddr);\n\t} else {\n\t\tstruct drm_i915_private *dev_priv = dev->dev_private;\n\t\tuint32_t __iomem *reloc_entry;\n\t\tvoid __iomem *reloc_page;\n\n\t\t\/* We can't wait for rendering with pagefaults disabled *\/\n\t\tif (obj->active && in_atomic())\n\t\t\treturn -EFAULT;\n\n\t\tret = i915_gem_object_set_to_gtt_domain(obj, 1);\n\t\tif (ret)\n\t\t\treturn ret;\n\n\t\t\/* Map the page containing the relocation we're going to perform. *\/\n\t\treloc->offset += obj->gtt_offset;\n\t\treloc_page = io_mapping_map_atomic_wc(dev_priv->mm.gtt_mapping,\n\t\t\t\t\t\t reloc->offset & PAGE_MASK);\n\t\treloc_entry = (uint32_t __iomem *)\n\t\t\t(reloc_page + (reloc->offset & ~PAGE_MASK));\n\t\tiowrite32(reloc->delta, reloc_entry);\n\t\tio_mapping_unmap_atomic(reloc_page);\n\t}\n\n\t\/* and update the user's relocation entry *\/\n\treloc->presumed_offset = target_offset;\n\n\treturn 0;\n}","target":0,"code_token_length":1074,"total_token_length":1405,"max_tokens_setting":2048} +{"idx":348946,"func":"static struct ad5755_platform_data *ad5755_parse_dt(struct device *dev)\n{\n\tstruct device_node *np = dev->of_node;\n\tstruct device_node *pp;\n\tstruct ad5755_platform_data *pdata;\n\tunsigned int tmp;\n\tunsigned int tmparray[3];\n\tint devnr, i;\n\n\tpdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL);\n\tif (!pdata)\n\t\treturn NULL;\n\n\tpdata->ext_dc_dc_compenstation_resistor =\n\t of_property_read_bool(np, \"adi,ext-dc-dc-compenstation-resistor\");\n\n\tif (!of_property_read_u32(np, \"adi,dc-dc-phase\", &tmp))\n\t\tpdata->dc_dc_phase = tmp;\n\telse\n\t\tpdata->dc_dc_phase = AD5755_DC_DC_PHASE_ALL_SAME_EDGE;\n\n\tpdata->dc_dc_freq = AD5755_DC_DC_FREQ_410kHZ;\n\tif (!of_property_read_u32(np, \"adi,dc-dc-freq-hz\", &tmp)) {\n\t\tfor (i = 0; i < ARRAY_SIZE(ad5755_dcdc_freq_table); i++) {\n\t\t\tif (tmp == ad5755_dcdc_freq_table[i][0]) {\n\t\t\t\tpdata->dc_dc_freq = ad5755_dcdc_freq_table[i][1];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (i == ARRAY_SIZE(ad5755_dcdc_freq_table)) {\n\t\t\tdev_err(dev,\n\t\t\t\t\"adi,dc-dc-freq out of range selecting 410kHz\");\n\t\t}\n\t}\n\n\tpdata->dc_dc_maxv = AD5755_DC_DC_MAXV_23V;\n\tif (!of_property_read_u32(np, \"adi,dc-dc-max-microvolt\", &tmp)) {\n\t\tfor (i = 0; i < ARRAY_SIZE(ad5755_dcdc_maxv_table); i++) {\n\t\t\tif (tmp == ad5755_dcdc_maxv_table[i][0]) {\n\t\t\t\tpdata->dc_dc_maxv = ad5755_dcdc_maxv_table[i][1];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (i == ARRAY_SIZE(ad5755_dcdc_maxv_table)) {\n\t\t\t\tdev_err(dev,\n\t\t\t\t\t\"adi,dc-dc-maxv out of range selecting 23V\");\n\t\t}\n\t}\n\n\tdevnr = 0;\n\tfor_each_child_of_node(np, pp) {\n\t\tif (devnr > AD5755_NUM_CHANNELS) {\n\t\t\tdev_err(dev,\n\t\t\t\t\"There is to many channels defined in DT\\n\");\n\t\t\tgoto error_out;\n\t\t}\n\n\t\tif (!of_property_read_u32(pp, \"adi,mode\", &tmp))\n\t\t\tpdata->dac[devnr].mode = tmp;\n\t\telse\n\t\t\tpdata->dac[devnr].mode = AD5755_MODE_CURRENT_4mA_20mA;\n\n\t\tpdata->dac[devnr].ext_current_sense_resistor =\n\t\t of_property_read_bool(pp, \"adi,ext-current-sense-resistor\");\n\n\t\tpdata->dac[devnr].enable_voltage_overrange =\n\t\t of_property_read_bool(pp, \"adi,enable-voltage-overrange\");\n\n\t\tif (!of_property_read_u32_array(pp, \"adi,slew\", tmparray, 3)) {\n\t\t\tpdata->dac[devnr].slew.enable = tmparray[0];\n\n\t\t\tpdata->dac[devnr].slew.rate = AD5755_SLEW_RATE_64k;\n\t\t\tfor (i = 0; i < ARRAY_SIZE(ad5755_slew_rate_table); i++) {\n\t\t\t\tif (tmparray[1] == ad5755_slew_rate_table[i][0]) {\n\t\t\t\t\tpdata->dac[devnr].slew.rate =\n\t\t\t\t\t\tad5755_slew_rate_table[i][1];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (i == ARRAY_SIZE(ad5755_slew_rate_table)) {\n\t\t\t\tdev_err(dev,\n\t\t\t\t\t\"channel %d slew rate out of range selecting 64kHz\",\n\t\t\t\t\tdevnr);\n\t\t\t}\n\n\t\t\tpdata->dac[devnr].slew.step_size = AD5755_SLEW_STEP_SIZE_1;\n\t\t\tfor (i = 0; i < ARRAY_SIZE(ad5755_slew_step_table); i++) {\n\t\t\t\tif (tmparray[2] == ad5755_slew_step_table[i][0]) {\n\t\t\t\t\tpdata->dac[devnr].slew.step_size =\n\t\t\t\t\t\tad5755_slew_step_table[i][1];\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (i == ARRAY_SIZE(ad5755_slew_step_table)) {\n\t\t\t\tdev_err(dev,\n\t\t\t\t\t\"channel %d slew step size out of range selecting 1 LSB\",\n\t\t\t\t\tdevnr);\n\t\t\t}\n\t\t} else {\n\t\t\tpdata->dac[devnr].slew.enable = false;\n\t\t\tpdata->dac[devnr].slew.rate = AD5755_SLEW_RATE_64k;\n\t\t\tpdata->dac[devnr].slew.step_size =\n\t\t\t AD5755_SLEW_STEP_SIZE_1;\n\t\t}\n\t\tdevnr++;\n\t}\n\n\treturn pdata;\n\n error_out:\n\tdevm_kfree(dev, pdata);\n\treturn NULL;\n}","target":1,"code_token_length":1164,"total_token_length":1495,"max_tokens_setting":2048} +{"idx":266793,"func":"FUNC_DECODER(dissector_postgresql)\n{\n DECLARE_DISP_PTR(ptr);\n struct ec_session *s = NULL;\n void *ident = NULL;\n char tmp[MAX_ASCII_ADDR_LEN];\n struct postgresql_status *conn_status;\n\n \/* don't complain about unused var *\/\n (void) DECODE_DATA; \n (void) DECODE_DATALEN;\n (void) DECODED_LEN;\n \n if (FROM_CLIENT(\"postgresql\", PACKET)) {\n if (PACKET->DATA.len < 4)\n return NULL;\n\n dissect_create_ident(&ident, PACKET, DISSECT_CODE(dissector_postgresql));\n\n \/* if the session does not exist... *\/\n if (session_get(&s, ident, DISSECT_IDENT_LEN) == -ENOTFOUND) {\n \/* search for user and database strings, look for StartupMessage *\/\n unsigned char *u = memmem(ptr, PACKET->DATA.len, \"user\", 4);\n unsigned char *d = memmem(ptr, PACKET->DATA.len, \"database\", 8);\n if (!memcmp(ptr + 4, \"\\x00\\x03\\x00\\x00\", 4) && u && d) {\n \/* create the new session *\/\n dissect_create_session(&s, PACKET, DISSECT_CODE(dissector_postgresql));\n\n \/* remember the state (used later) *\/\n SAFE_CALLOC(s->data, 1, sizeof(struct postgresql_status));\n\n conn_status = (struct postgresql_status *) s->data;\n conn_status->status = WAIT_AUTH;\n\n \/* user is always null-terminated *\/\n strncpy((char*)conn_status->user, (char*)(u + 5), 65);\n conn_status->user[64] = 0;\n\n \/* database is always null-terminated *\/\n strncpy((char*)conn_status->database, (char*)(d + 9), 65);\n conn_status->database[64] = 0;\n\n \/* save the session *\/\n session_put(s);\n }\n } else {\n conn_status = (struct postgresql_status *) s->data;\n if (conn_status->status == WAIT_RESPONSE) {\n\n \/* check for PasswordMessage packet *\/\n if (ptr[0] == 'p' && conn_status->type == MD5) {\n DEBUG_MSG(\"\\tDissector_postgresql RESPONSE type is MD5\");\n if(memcmp(ptr + 1, \"\\x00\\x00\\x00\\x28\", 4)) {\n DEBUG_MSG(\"\\tDissector_postgresql BUG, expected length is 40\");\n return NULL;\n }\n if (PACKET->DATA.len < 40) {\n DEBUG_MSG(\"\\tDissector_postgresql BUG, expected length is 40\");\n return NULL;\n }\n memcpy(conn_status->hash, ptr + 5 + 3, 32);\n conn_status->hash[32] = 0;\n DISSECT_MSG(\"%s:$postgres$%s*%s*%s:%s:%d\\n\", conn_status->user, conn_status->user, conn_status->salt, conn_status->hash, ip_addr_ntoa(&PACKET->L3.dst, tmp), ntohs(PACKET->L4.dst));\n dissect_wipe_session(PACKET, DISSECT_CODE(dissector_postgresql));\n }\n else if (ptr[0] == 'p' && conn_status->type == CT) {\n int length;\n DEBUG_MSG(\"\\tDissector_postgresql RESPONSE type is clear-text!\");\n GET_ULONG_BE(length, ptr, 1);\n length -= 4;\n if (length < 0 || length > 65 || PACKET->DATA.len < length+5) {\n dissect_wipe_session(PACKET, DISSECT_CODE(dissector_postgresql));\n return NULL;\n }\n snprintf((char*)conn_status->password, length+1, \"%s\", (char*)(ptr + 5));\n DISSECT_MSG(\"PostgreSQL credentials:%s-%d:%s:%s\\n\", ip_addr_ntoa(&PACKET->L3.dst, tmp), ntohs(PACKET->L4.dst), conn_status->user, conn_status->password);\n dissect_wipe_session(PACKET, DISSECT_CODE(dissector_postgresql));\n }\n }\n }\n } else { \/* Packets coming from the server *\/\n if (PACKET->DATA.len < 9)\n return NULL;\n dissect_create_ident(&ident, PACKET, DISSECT_CODE(dissector_postgresql));\n\n if (session_get(&s, ident, DISSECT_IDENT_LEN) == ESUCCESS) {\n conn_status = (struct postgresql_status *) s->data;\n if (conn_status->status == WAIT_AUTH &&\n ptr[0] == 'R' && !memcmp(ptr + 1, \"\\x00\\x00\\x00\\x0c\", 4) &&\n !memcmp(ptr + 5, \"\\x00\\x00\\x00\\x05\", 4)) {\n\n conn_status->status = WAIT_RESPONSE;\n\n conn_status->type = MD5;\n DEBUG_MSG(\"\\tDissector_postgresql AUTH type is MD5\");\n hex_encode(ptr + 9, 4, conn_status->salt); \/* save salt *\/\n }\n else if (conn_status->status == WAIT_AUTH &&\n ptr[0] == 'R' && !memcmp(ptr + 1, \"\\x00\\x00\\x00\\x08\", 4) &&\n !memcmp(ptr + 5, \"\\x00\\x00\\x00\\x03\", 4)) {\n conn_status->status = WAIT_RESPONSE;\n conn_status->type = CT;\n DEBUG_MSG(\"\\tDissector_postgresql AUTH type is clear-text!\");\n }\n }\n }\n\n SAFE_FREE(ident);\n return NULL;\n}","target":0,"code_token_length":1252,"total_token_length":1583,"max_tokens_setting":2048} +{"idx":348152,"func":"ks_http_fetch (ctrl_t ctrl, const char *url, unsigned int flags,\n estream_t *r_fp)\n{\n gpg_error_t err;\n http_session_t session = NULL;\n unsigned int session_flags;\n http_t http = NULL;\n int redirects_left = MAX_REDIRECTS;\n estream_t fp = NULL;\n char *request_buffer = NULL;\n parsed_uri_t uri = NULL;\n int is_onion, is_https;\n\n err = http_parse_uri (&uri, url, 0);\n if (err)\n goto leave;\n is_onion = uri->onion;\n is_https = uri->use_tls;\n\n \/* By default we only use the system provided certificates with this\n * fetch command. *\/\n session_flags = HTTP_FLAG_TRUST_SYS;\n if ((flags & KS_HTTP_FETCH_NO_CRL) || ctrl->http_no_crl)\n session_flags |= HTTP_FLAG_NO_CRL;\n if ((flags & KS_HTTP_FETCH_TRUST_CFG))\n session_flags |= HTTP_FLAG_TRUST_CFG;\n\n once_more:\n err = http_session_new (&session, NULL, session_flags,\n gnupg_http_tls_verify_cb, ctrl);\n if (err)\n goto leave;\n http_session_set_log_cb (session, cert_log_cb);\n http_session_set_timeout (session, ctrl->timeout);\n\n *r_fp = NULL;\n err = http_open (&http,\n HTTP_REQ_GET,\n url,\n \/* httphost *\/ NULL,\n \/* fixme: AUTH *\/ NULL,\n ((opt.honor_http_proxy? HTTP_FLAG_TRY_PROXY:0)\n | (DBG_LOOKUP? HTTP_FLAG_LOG_RESP:0)\n | (dirmngr_use_tor ()? HTTP_FLAG_FORCE_TOR:0)\n | (opt.disable_ipv4? HTTP_FLAG_IGNORE_IPv4 : 0)\n | (opt.disable_ipv6? HTTP_FLAG_IGNORE_IPv6 : 0)),\n ctrl->http_proxy,\n session,\n NULL,\n \/*FIXME curl->srvtag*\/NULL);\n if (!err)\n {\n fp = http_get_write_ptr (http);\n \/* Avoid caches to get the most recent copy of the key. We set\n * both the Pragma and Cache-Control versions of the header, so\n * we're good with both HTTP 1.0 and 1.1. *\/\n if ((flags & KS_HTTP_FETCH_NOCACHE))\n es_fputs (\"Pragma: no-cache\\r\\n\"\n \"Cache-Control: no-cache\\r\\n\", fp);\n http_start_data (http);\n if (es_ferror (fp))\n err = gpg_error_from_syserror ();\n }\n if (err)\n {\n \/* Fixme: After a redirection we show the old host name. *\/\n log_error (_(\"error connecting to '%s': %s\\n\"),\n url, gpg_strerror (err));\n goto leave;\n }\n\n \/* Wait for the response. *\/\n dirmngr_tick (ctrl);\n err = http_wait_response (http);\n if (err)\n {\n log_error (_(\"error reading HTTP response for '%s': %s\\n\"),\n url, gpg_strerror (err));\n goto leave;\n }\n\n switch (http_get_status_code (http))\n {\n case 200:\n err = 0;\n break; \/* Success. *\/\n\n case 301:\n case 302:\n case 307:\n {\n const char *s = http_get_header (http, \"Location\");\n\n log_info (_(\"URL '%s' redirected to '%s' (%u)\\n\"),\n url, s?s:\"[none]\", http_get_status_code (http));\n if (s && *s && redirects_left-- )\n {\n if (is_onion || is_https)\n {\n \/* Make sure that an onion address only redirects to\n * another onion address, or that a https address\n * only redirects to a https address. *\/\n http_release_parsed_uri (uri);\n uri = NULL;\n err = http_parse_uri (&uri, s, 0);\n if (err)\n goto leave;\n\n if (is_onion && !uri->onion)\n {\n err = gpg_error (GPG_ERR_FORBIDDEN);\n goto leave;\n }\n if (!(flags & KS_HTTP_FETCH_ALLOW_DOWNGRADE)\n && is_https && !uri->use_tls)\n {\n err = gpg_error (GPG_ERR_FORBIDDEN);\n goto leave;\n }\n }\n\n xfree (request_buffer);\n request_buffer = xtrystrdup (s);\n if (request_buffer)\n {\n url = request_buffer;\n http_close (http, 0);\n http = NULL;\n http_session_release (session);\n goto once_more;\n }\n err = gpg_error_from_syserror ();\n }\n else\n err = gpg_error (GPG_ERR_NO_DATA);\n log_error (_(\"too many redirections\\n\"));\n }\n goto leave;\n\n default:\n log_error (_(\"error accessing '%s': http status %u\\n\"),\n url, http_get_status_code (http));\n err = gpg_error (GPG_ERR_NO_DATA);\n goto leave;\n }\n\n fp = http_get_read_ptr (http);\n if (!fp)\n {\n err = gpg_error (GPG_ERR_BUG);\n goto leave;\n }\n\n \/* Return the read stream and close the HTTP context. *\/\n *r_fp = fp;\n http_close (http, 1);\n http = NULL;\n\n leave:\n http_close (http, 0);\n http_session_release (session);\n xfree (request_buffer);\n http_release_parsed_uri (uri);\n return err;\n}","target":1,"code_token_length":1232,"total_token_length":1563,"max_tokens_setting":2048} +{"idx":63838,"func":"static int jit_subprogs(struct bpf_verifier_env *env)\n{\n\tstruct bpf_prog *prog = env->prog, **func, *tmp;\n\tint i, j, subprog_start, subprog_end = 0, len, subprog;\n\tstruct bpf_insn *insn;\n\tvoid *old_bpf_func;\n\tint err = -ENOMEM;\n\n\tif (env->subprog_cnt <= 1)\n\t\treturn 0;\n\n\tfor (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {\n\t\tif (insn->code != (BPF_JMP | BPF_CALL) ||\n\t\t insn->src_reg != BPF_PSEUDO_CALL)\n\t\t\tcontinue;\n\t\t\/* Upon error here we cannot fall back to interpreter but\n\t\t * need a hard reject of the program. Thus -EFAULT is\n\t\t * propagated in any case.\n\t\t *\/\n\t\tsubprog = find_subprog(env, i + insn->imm + 1);\n\t\tif (subprog < 0) {\n\t\t\tWARN_ONCE(1, \"verifier bug. No program starts at insn %d\\n\",\n\t\t\t\t i + insn->imm + 1);\n\t\t\treturn -EFAULT;\n\t\t}\n\t\t\/* temporarily remember subprog id inside insn instead of\n\t\t * aux_data, since next loop will split up all insns into funcs\n\t\t *\/\n\t\tinsn->off = subprog;\n\t\t\/* remember original imm in case JIT fails and fallback\n\t\t * to interpreter will be needed\n\t\t *\/\n\t\tenv->insn_aux_data[i].call_imm = insn->imm;\n\t\t\/* point imm to __bpf_call_base+1 from JITs point of view *\/\n\t\tinsn->imm = 1;\n\t}\n\n\tfunc = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL);\n\tif (!func)\n\t\tgoto out_undo_insn;\n\n\tfor (i = 0; i < env->subprog_cnt; i++) {\n\t\tsubprog_start = subprog_end;\n\t\tsubprog_end = env->subprog_info[i + 1].start;\n\n\t\tlen = subprog_end - subprog_start;\n\t\tfunc[i] = bpf_prog_alloc(bpf_prog_size(len), GFP_USER);\n\t\tif (!func[i])\n\t\t\tgoto out_free;\n\t\tmemcpy(func[i]->insnsi, &prog->insnsi[subprog_start],\n\t\t len * sizeof(struct bpf_insn));\n\t\tfunc[i]->type = prog->type;\n\t\tfunc[i]->len = len;\n\t\tif (bpf_prog_calc_tag(func[i]))\n\t\t\tgoto out_free;\n\t\tfunc[i]->is_func = 1;\n\t\t\/* Use bpf_prog_F_tag to indicate functions in stack traces.\n\t\t * Long term would need debug info to populate names\n\t\t *\/\n\t\tfunc[i]->aux->name[0] = 'F';\n\t\tfunc[i]->aux->stack_depth = env->subprog_info[i].stack_depth;\n\t\tfunc[i]->jit_requested = 1;\n\t\tfunc[i] = bpf_int_jit_compile(func[i]);\n\t\tif (!func[i]->jited) {\n\t\t\terr = -ENOTSUPP;\n\t\t\tgoto out_free;\n\t\t}\n\t\tcond_resched();\n\t}\n\t\/* at this point all bpf functions were successfully JITed\n\t * now populate all bpf_calls with correct addresses and\n\t * run last pass of JIT\n\t *\/\n\tfor (i = 0; i < env->subprog_cnt; i++) {\n\t\tinsn = func[i]->insnsi;\n\t\tfor (j = 0; j < func[i]->len; j++, insn++) {\n\t\t\tif (insn->code != (BPF_JMP | BPF_CALL) ||\n\t\t\t insn->src_reg != BPF_PSEUDO_CALL)\n\t\t\t\tcontinue;\n\t\t\tsubprog = insn->off;\n\t\t\tinsn->imm = (u64 (*)(u64, u64, u64, u64, u64))\n\t\t\t\tfunc[subprog]->bpf_func -\n\t\t\t\t__bpf_call_base;\n\t\t}\n\n\t\t\/* we use the aux data to keep a list of the start addresses\n\t\t * of the JITed images for each function in the program\n\t\t *\n\t\t * for some architectures, such as powerpc64, the imm field\n\t\t * might not be large enough to hold the offset of the start\n\t\t * address of the callee's JITed image from __bpf_call_base\n\t\t *\n\t\t * in such cases, we can lookup the start address of a callee\n\t\t * by using its subprog id, available from the off field of\n\t\t * the call instruction, as an index for this list\n\t\t *\/\n\t\tfunc[i]->aux->func = func;\n\t\tfunc[i]->aux->func_cnt = env->subprog_cnt;\n\t}\n\tfor (i = 0; i < env->subprog_cnt; i++) {\n\t\told_bpf_func = func[i]->bpf_func;\n\t\ttmp = bpf_int_jit_compile(func[i]);\n\t\tif (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {\n\t\t\tverbose(env, \"JIT doesn't support bpf-to-bpf calls\\n\");\n\t\t\terr = -ENOTSUPP;\n\t\t\tgoto out_free;\n\t\t}\n\t\tcond_resched();\n\t}\n\n\t\/* finally lock prog and jit images for all functions and\n\t * populate kallsysm\n\t *\/\n\tfor (i = 0; i < env->subprog_cnt; i++) {\n\t\tbpf_prog_lock_ro(func[i]);\n\t\tbpf_prog_kallsyms_add(func[i]);\n\t}\n\n\t\/* Last step: make now unused interpreter insns from main\n\t * prog consistent for later dump requests, so they can\n\t * later look the same as if they were interpreted only.\n\t *\/\n\tfor (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {\n\t\tif (insn->code != (BPF_JMP | BPF_CALL) ||\n\t\t insn->src_reg != BPF_PSEUDO_CALL)\n\t\t\tcontinue;\n\t\tinsn->off = env->insn_aux_data[i].call_imm;\n\t\tsubprog = find_subprog(env, i + insn->off + 1);\n\t\tinsn->imm = subprog;\n\t}\n\n\tprog->jited = 1;\n\tprog->bpf_func = func[0]->bpf_func;\n\tprog->aux->func = func;\n\tprog->aux->func_cnt = env->subprog_cnt;\n\treturn 0;\nout_free:\n\tfor (i = 0; i < env->subprog_cnt; i++)\n\t\tif (func[i])\n\t\t\tbpf_jit_free(func[i]);\n\tkfree(func);\nout_undo_insn:\n\t\/* cleanup main prog to be interpreted *\/\n\tprog->jit_requested = 0;\n\tfor (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {\n\t\tif (insn->code != (BPF_JMP | BPF_CALL) ||\n\t\t insn->src_reg != BPF_PSEUDO_CALL)\n\t\t\tcontinue;\n\t\tinsn->off = 0;\n\t\tinsn->imm = env->insn_aux_data[i].call_imm;\n\t}\n\treturn err;\n}","target":0,"code_token_length":1528,"total_token_length":1859,"max_tokens_setting":2048} +{"idx":440225,"func":"add_ctype_to_cc(CClassNode* cc, int ctype, int not, ScanEnv* env)\n{\n#define ASCII_LIMIT 127\n\n int c, r;\n int ascii_mode;\n int is_single;\n const OnigCodePoint *ranges;\n OnigCodePoint limit;\n OnigCodePoint sb_out;\n OnigEncoding enc = env->enc;\n\n ascii_mode = IS_ASCII_MODE_CTYPE_OPTION(ctype, env->options);\n\n r = ONIGENC_GET_CTYPE_CODE_RANGE(enc, ctype, &sb_out, &ranges);\n if (r == 0) {\n if (ascii_mode == 0)\n r = add_ctype_to_cc_by_range(cc, ctype, not, env->enc, sb_out, ranges);\n else\n r = add_ctype_to_cc_by_range_limit(cc, ctype, not, env->enc, sb_out,\n ranges, ASCII_LIMIT);\n return r;\n }\n else if (r != ONIG_NO_SUPPORT_CONFIG) {\n return r;\n }\n\n r = 0;\n is_single = ONIGENC_IS_SINGLEBYTE(enc);\n limit = ascii_mode ? ASCII_LIMIT : SINGLE_BYTE_SIZE;\n\n switch (ctype) {\n case ONIGENC_CTYPE_ALPHA:\n case ONIGENC_CTYPE_BLANK:\n case ONIGENC_CTYPE_CNTRL:\n case ONIGENC_CTYPE_DIGIT:\n case ONIGENC_CTYPE_LOWER:\n case ONIGENC_CTYPE_PUNCT:\n case ONIGENC_CTYPE_SPACE:\n case ONIGENC_CTYPE_UPPER:\n case ONIGENC_CTYPE_XDIGIT:\n case ONIGENC_CTYPE_ASCII:\n case ONIGENC_CTYPE_ALNUM:\n if (not != 0) {\n for (c = 0; c < (int )limit; c++) {\n if (is_single != 0 || ONIGENC_CODE_TO_MBCLEN(enc, c) == 1) {\n if (! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype))\n BITSET_SET_BIT(cc->bs, c);\n }\n }\n for (c = limit; c < SINGLE_BYTE_SIZE; c++) {\n if (is_single != 0 || ONIGENC_CODE_TO_MBCLEN(enc, c) == 1)\n BITSET_SET_BIT(cc->bs, c);\n }\n\n if (is_single == 0)\n ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf);\n }\n else {\n for (c = 0; c < (int )limit; c++) {\n if (is_single != 0 || ONIGENC_CODE_TO_MBCLEN(enc, c) == 1) {\n if (ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype))\n BITSET_SET_BIT(cc->bs, c);\n }\n }\n }\n break;\n\n case ONIGENC_CTYPE_GRAPH:\n case ONIGENC_CTYPE_PRINT:\n case ONIGENC_CTYPE_WORD:\n if (not != 0) {\n for (c = 0; c < (int )limit; c++) {\n \/* check invalid code point *\/\n if ((is_single != 0 || ONIGENC_CODE_TO_MBCLEN(enc, c) == 1)\n && ! ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype))\n BITSET_SET_BIT(cc->bs, c);\n }\n for (c = limit; c < SINGLE_BYTE_SIZE; c++) {\n if (is_single != 0 || ONIGENC_CODE_TO_MBCLEN(enc, c) == 1)\n BITSET_SET_BIT(cc->bs, c);\n }\n if (ascii_mode != 0 && is_single == 0)\n ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf);\n }\n else {\n for (c = 0; c < (int )limit; c++) {\n if ((is_single != 0 || ONIGENC_CODE_TO_MBCLEN(enc, c) == 1)\n && ONIGENC_IS_CODE_CTYPE(enc, (OnigCodePoint )c, ctype))\n BITSET_SET_BIT(cc->bs, c);\n }\n if (ascii_mode == 0 && is_single == 0)\n ADD_ALL_MULTI_BYTE_RANGE(enc, cc->mbuf);\n }\n break;\n\n default:\n return ONIGERR_PARSER_BUG;\n break;\n }\n\n return r;\n}","target":0,"code_token_length":963,"total_token_length":1294,"max_tokens_setting":2048} +{"idx":413579,"func":"static void _rpc_prolog(slurm_msg_t *msg)\n{\n\tint rc = SLURM_SUCCESS;\n\tprolog_launch_msg_t *req = (prolog_launch_msg_t *)msg->data;\n\tjob_env_t job_env;\n\tbool first_job_run;\n\tuid_t req_uid;\n\n\tif (req == NULL)\n\t\treturn;\n\n\treq_uid = g_slurm_auth_get_uid(msg->auth_cred, conf->auth_info);\n\tif (!_slurm_authorized_user(req_uid)) {\n\t\terror(\"REQUEST_LAUNCH_PROLOG request from uid %u\",\n\t\t (unsigned int) req_uid);\n\t\treturn;\n\t}\n\n\tif (!req->user_name)\n\t\treq->user_name = uid_to_string(req->uid);\n\n\tif (slurm_send_rc_msg(msg, rc) < 0) {\n\t\terror(\"Error starting prolog: %m\");\n\t}\n\tif (rc) {\n\t\tint term_sig, exit_status;\n\t\tif (WIFSIGNALED(rc)) {\n\t\t\texit_status = 0;\n\t\t\tterm_sig = WTERMSIG(rc);\n\t\t} else {\n\t\t\texit_status = WEXITSTATUS(rc);\n\t\t\tterm_sig = 0;\n\t\t}\n\t\terror(\"[job %u] prolog start failed status=%d:%d\",\n\t\t req->job_id, exit_status, term_sig);\n\t\trc = ESLURMD_PROLOG_FAILED;\n\t}\n\n\tslurm_mutex_lock(&prolog_mutex);\n\tfirst_job_run = !slurm_cred_jobid_cached(conf->vctx, req->job_id);\n\tif (first_job_run) {\n\t\tif (slurmctld_conf.prolog_flags & PROLOG_FLAG_CONTAIN)\n\t\t\t_make_prolog_mem_container(msg);\n\n\t\tif (container_g_create(req->job_id))\n\t\t\terror(\"container_g_create(%u): %m\", req->job_id);\n\n\t\tslurm_cred_insert_jobid(conf->vctx, req->job_id);\n\t\t_add_job_running_prolog(req->job_id);\n\t\tslurm_mutex_unlock(&prolog_mutex);\n\n\t\tmemset(&job_env, 0, sizeof(job_env_t));\n\n\t\tjob_env.jobid = req->job_id;\n\t\tjob_env.step_id = 0;\t\/* not available *\/\n\t\tjob_env.node_list = req->nodes;\n\t\tjob_env.partition = req->partition;\n\t\tjob_env.spank_job_env = req->spank_job_env;\n\t\tjob_env.spank_job_env_size = req->spank_job_env_size;\n\t\tjob_env.uid = req->uid;\n\t\tjob_env.user_name = req->user_name;\n#if defined(HAVE_BG)\n\t\tselect_g_select_jobinfo_get(req->select_jobinfo,\n\t\t\t\t\t SELECT_JOBDATA_BLOCK_ID,\n\t\t\t\t\t &job_env.resv_id);\n#elif defined(HAVE_ALPS_CRAY)\n\t\tjob_env.resv_id = select_g_select_jobinfo_xstrdup(\n\t\t\treq->select_jobinfo, SELECT_PRINT_RESV_ID);\n#endif\n\t\trc = _run_prolog(&job_env, req->cred);\n\n\t\tif (rc) {\n\t\t\tint term_sig, exit_status;\n\t\t\tif (WIFSIGNALED(rc)) {\n\t\t\t\texit_status = 0;\n\t\t\t\tterm_sig = WTERMSIG(rc);\n\t\t\t} else {\n\t\t\t\texit_status = WEXITSTATUS(rc);\n\t\t\t\tterm_sig = 0;\n\t\t\t}\n\t\t\terror(\"[job %u] prolog failed status=%d:%d\",\n\t\t\t req->job_id, exit_status, term_sig);\n\t\t\trc = ESLURMD_PROLOG_FAILED;\n\t\t}\n\t} else\n\t\tslurm_mutex_unlock(&prolog_mutex);\n\n\tif (!(slurmctld_conf.prolog_flags & PROLOG_FLAG_NOHOLD))\n\t\t_notify_slurmctld_prolog_fini(req->job_id, rc);\n\n\tif (rc == SLURM_SUCCESS) {\n\t\tif (slurmctld_conf.prolog_flags & PROLOG_FLAG_CONTAIN)\n\t\t\t_spawn_prolog_stepd(msg);\n\t} else {\n\t\t_launch_job_fail(req->job_id, rc);\n\t\tsend_registration_msg(rc, false);\n\t}\n}","target":0,"code_token_length":843,"total_token_length":1174,"max_tokens_setting":2048} +{"idx":10246,"func":" tt_cmap14_validate( FT_Byte* table,\n FT_Validator valid )\n {\n FT_Byte* p;\n FT_ULong length;\n FT_ULong num_selectors;\n\n\n if ( table + 2 + 4 + 4 > valid->limit )\n FT_INVALID_TOO_SHORT;\n\n p = table + 2;\n length = TT_NEXT_ULONG( p );\n num_selectors = TT_NEXT_ULONG( p );\n\n if ( length > (FT_ULong)( valid->limit - table ) ||\n \/* length < 10 + 11 * num_selectors ? *\/\n length < 10 ||\n ( length - 10 ) \/ 11 < num_selectors )\n FT_INVALID_TOO_SHORT;\n\n \/* check selectors, they must be in increasing order *\/\n {\n \/* we start lastVarSel at 1 because a variant selector value of 0\n * isn't valid.\n *\/\n FT_ULong n, lastVarSel = 1;\n\n\n for ( n = 0; n < num_selectors; n++ )\n {\n FT_ULong varSel = TT_NEXT_UINT24( p );\n FT_ULong defOff = TT_NEXT_ULONG( p );\n FT_ULong nondefOff = TT_NEXT_ULONG( p );\n\n\n if ( defOff >= length || nondefOff >= length )\n FT_INVALID_TOO_SHORT;\n\n if ( varSel < lastVarSel )\n FT_INVALID_DATA;\n\n lastVarSel = varSel + 1;\n\n \/* check the default table (these glyphs should be reached *\/\n \/* through the normal Unicode cmap, no GIDs, just check order) *\/\n if ( defOff != 0 )\n {\n FT_Byte* defp = table + defOff;\n FT_ULong numRanges = TT_NEXT_ULONG( defp );\n FT_ULong i;\n FT_ULong lastBase = 0;\n \n \n \/* defp + numRanges * 4 > valid->limit ? *\/\n if ( numRanges > (FT_ULong)( valid->limit - defp ) \/ 4 )\n FT_INVALID_TOO_SHORT;\n\n\n if ( base + cnt >= 0x110000UL ) \/* end of Unicode *\/\n FT_INVALID_DATA;\n\n if ( base < lastBase )\n FT_INVALID_DATA;\n\n lastBase = base + cnt + 1U;\n }\n }\n\n \/* and the non-default table (these glyphs are specified here) *\/\n if ( nondefOff != 0 )\n {\n FT_Byte* ndp = table + nondefOff;\n FT_ULong numMappings = TT_NEXT_ULONG( ndp );\n \/* and the non-default table (these glyphs are specified here) *\/\n if ( nondefOff != 0 )\n {\n FT_Byte* ndp = table + nondefOff;\n FT_ULong numMappings = TT_NEXT_ULONG( ndp );\n FT_ULong i, lastUni = 0;\n \n \n \/* numMappings * 4 > (FT_ULong)( valid->limit - ndp ) ? *\/\n if ( numMappings > ( (FT_ULong)( valid->limit - ndp ) ) \/ 4 )\n FT_INVALID_TOO_SHORT;\n \n for ( i = 0; i < numMappings; ++i )\n\n lastUni = uni + 1U;\n\n if ( valid->level >= FT_VALIDATE_TIGHT &&\n gid >= TT_VALID_GLYPH_COUNT( valid ) )\n FT_INVALID_GLYPH_ID;\n }\n }\n }\n }\n","target":1,"code_token_length":789,"total_token_length":1120,"max_tokens_setting":2048} +{"idx":425054,"func":"void acquire_daemonlock(int closeflag) {\n\tstatic int fd = -1;\n\tchar buf[3 * MAX_FNAME];\n\tconst char *pidfile;\n\tchar *ep;\n\tlong otherpid = -1;\n\tssize_t num, len;\n\tpid_t pid = getpid();\n\n\tif (closeflag) {\n\t\t\/* close stashed fd for child so we don't leak it. *\/\n\t\tif (fd != -1) {\n\t\t\tclose(fd);\n\t\t\tfd = -1;\n\t\t}\n\t\t\/* and restore default sig handlers so we don't remove pid file if killed *\/\n\t\tsignal(SIGINT,SIG_DFL);\n\t\tsignal(SIGTERM,SIG_DFL);\n\t\treturn;\n\t}\n\n\tif (NoFork == 1)\n\t\treturn; \/\/move along, nothing to do here...\n\n\tif (fd == -1) {\n\t\tpidfile = _PATH_CRON_PID;\n\t\t\/* Initial mode is 0600 to prevent flock() race\/DoS. *\/\n\t\tif ((fd = open(pidfile, O_RDWR | O_CREAT, 0600)) == -1) {\n\t\t\tint save_errno = errno;\n\t\t\tsprintf(buf, \"can't open or create %s\", pidfile);\n\t\t\tfprintf(stderr, \"%s: %s: %s\\n\", ProgramName, buf,\n\t\t\t\tstrerror(save_errno));\n\t\t\tlog_it(\"CRON\", pid, \"DEATH\", buf, save_errno);\n\t\t\texit(ERROR_EXIT);\n\t\t}\n\n\t\tif (trylock_file(fd) < OK) {\n\t\t\tint save_errno = errno;\n\n\t\t\tmemset(buf, 0, sizeof (buf));\n\t\t\tif ((num = read(fd, buf, sizeof (buf) - 1)) > 0 &&\n\t\t\t\t(otherpid = strtol(buf, &ep, 10)) > 0 &&\n\t\t\t\tep != buf && *ep == '\\n' && otherpid != LONG_MAX) {\n\t\t\t\tsnprintf(buf, sizeof (buf),\n\t\t\t\t\t\"can't lock %s, otherpid may be %ld\", pidfile, otherpid);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tsnprintf(buf, sizeof (buf),\n\t\t\t\t\t\"can't lock %s, otherpid unknown\", pidfile);\n\t\t\t}\n\t\t\tfprintf(stderr, \"%s: %s: %s\\n\", ProgramName, buf,\n\t\t\t\tstrerror(save_errno));\n\t\t\tlog_it(\"CRON\", pid, \"DEATH\", buf, save_errno);\n\t\t\texit(ERROR_EXIT);\n\t\t}\n\t\t(void) fchmod(fd, 0644);\n\t\t(void) fcntl(fd, F_SETFD, 1);\n\t}\n#if !defined(HAVE_FLOCK)\n\telse {\n\t\t\/* Racy but better than nothing, just hope the parent exits *\/\n\t\tsleep(0);\n\t\ttrylock_file(fd);\t\n\t}\n#endif\n\n\tsprintf(buf, \"%ld\\n\", (long) pid);\n\t(void) lseek(fd, (off_t) 0, SEEK_SET);\n\tlen = (ssize_t)strlen(buf);\n\tif ((num = write(fd, buf, (size_t)len)) != len)\n\t\tlog_it(\"CRON\", pid, \"ERROR\", \"write() failed\", errno);\n\telse {\n\t\tif (ftruncate(fd, num) == -1)\n\t\t\tlog_it(\"CRON\", pid, \"ERROR\", \"ftruncate() failed\", errno);\n\t}\n\n\t\/* abandon fd even though the file is open. we need to keep\n\t * it open and locked, but we don't need the handles elsewhere.\n\t *\/\n}","target":0,"code_token_length":727,"total_token_length":1058,"max_tokens_setting":2048} +{"idx":365332,"func":"str_gsub(argc, argv, str, bang)\n int argc;\n VALUE *argv;\n VALUE str;\n int bang;\n{\n VALUE pat, val, repl, match, dest;\n struct re_registers *regs;\n long beg, n;\n long offset, blen, slen, len;\n int iter = 0;\n char *buf, *bp, *sp, *cp;\n int tainted = 0;\n\n if (argc == 1) {\n RETURN_ENUMERATOR(str, argc, argv);\n\titer = 1;\n }\n else if (argc == 2) {\n\trepl = argv[1];\n\tStringValue(repl);\n\tif (OBJ_TAINTED(repl)) tainted = 1;\n }\n else {\n\trb_raise(rb_eArgError, \"wrong number of arguments (%d for 2)\", argc);\n }\n\n pat = get_pat(argv[0], 1);\n offset=0; n=0;\n beg = rb_reg_search(pat, str, 0, 0);\n if (beg < 0) {\n\tif (bang) return Qnil;\t\/* no match, no substitution *\/\n\treturn rb_str_dup(str);\n }\n\n blen = RSTRING(str)->len + 30; \/* len + margin *\/\n dest = str_new(0, 0, blen);\n buf = RSTRING(dest)->ptr;\n bp = buf;\n sp = cp = RSTRING(str)->ptr;\n slen = RSTRING(str)->len;\n\n rb_str_locktmp(dest);\n while (beg >= 0) {\n\tn++;\n\tmatch = rb_backref_get();\n\tregs = RMATCH(match)->regs;\n\tif (iter) {\n\t rb_match_busy(match);\n\t val = rb_obj_as_string(rb_yield(rb_reg_nth_match(0, match)));\n\t str_mod_check(str, sp, slen);\n\t if (bang) str_frozen_check(str);\n\t if (val == dest) { \/* paranoid chack [ruby-dev:24827] *\/\n\t\trb_raise(rb_eRuntimeError, \"block should not cheat\");\n\t }\n\t rb_backref_set(match);\n\t}\n\telse {\n\t val = rb_reg_regsub(repl, str, regs);\n\t}\n\tif (OBJ_TAINTED(val)) tainted = 1;\n\tlen = (bp - buf) + (beg - offset) + RSTRING(val)->len + 3;\n\tif (blen < len) {\n\t while (blen < len) blen *= 2;\n\t len = bp - buf;\n\t RESIZE_CAPA(dest, blen);\n\t RSTRING(dest)->len = blen;\n\t buf = RSTRING(dest)->ptr;\n\t bp = buf + len;\n\t}\n\tlen = beg - offset;\t\/* copy pre-match substr *\/\n\tmemcpy(bp, cp, len);\n\tbp += len;\n\tmemcpy(bp, RSTRING(val)->ptr, RSTRING(val)->len);\n\tbp += RSTRING(val)->len;\n\toffset = END(0);\n\tif (BEG(0) == END(0)) {\n\t \/*\n\t * Always consume at least one character of the input string\n\t * in order to prevent infinite loops.\n\t *\/\n\t if (RSTRING(str)->len <= END(0)) break;\n\t len = mbclen2(RSTRING(str)->ptr[END(0)], pat);\n\t memcpy(bp, RSTRING(str)->ptr+END(0), len);\n\t bp += len;\n\t offset = END(0) + len;\n\t}\n\tcp = RSTRING(str)->ptr + offset;\n\tif (offset > RSTRING(str)->len) break;\n\tbeg = rb_reg_search(pat, str, offset, 0);\n }\n if (RSTRING(str)->len > offset) {\n\tlen = bp - buf;\n\tif (blen - len < RSTRING(str)->len - offset) {\n\t blen = len + RSTRING(str)->len - offset;\n\t RESIZE_CAPA(dest, blen);\n\t buf = RSTRING(dest)->ptr;\n\t bp = buf + len;\n\t}\n\tmemcpy(bp, cp, RSTRING(str)->len - offset);\n\tbp += RSTRING(str)->len - offset;\n }\n rb_backref_set(match);\n *bp = '\\0';\n rb_str_unlocktmp(dest);\n if (bang) {\n\tif (str_independent(str)) {\n\t free(RSTRING(str)->ptr);\n\t}\n\tFL_UNSET(str, STR_NOCAPA);\n\tRSTRING(str)->ptr = buf;\n\tRSTRING(str)->aux.capa = blen;\n\tRSTRING(dest)->ptr = 0;\n\tRSTRING(dest)->len = 0;\n }\n else {\n\tRBASIC(dest)->klass = rb_obj_class(str);\n\tOBJ_INFECT(dest, str);\n\tstr = dest;\n }\n RSTRING(str)->len = bp - buf;\n\n if (tainted) OBJ_TAINT(str);\n return str;\n}","target":0,"code_token_length":1031,"total_token_length":1362,"max_tokens_setting":2048} +{"idx":87898,"func":"int __kvm_set_memory_region(struct kvm *kvm,\n\t\t\t const struct kvm_userspace_memory_region *mem)\n{\n\tint r;\n\tgfn_t base_gfn;\n\tunsigned long npages;\n\tstruct kvm_memory_slot *slot;\n\tstruct kvm_memory_slot old, new;\n\tstruct kvm_memslots *slots = NULL, *old_memslots;\n\tint as_id, id;\n\tenum kvm_mr_change change;\n\n\tr = check_memory_region_flags(mem);\n\tif (r)\n\t\tgoto out;\n\n\tr = -EINVAL;\n\tas_id = mem->slot >> 16;\n\tid = (u16)mem->slot;\n\n\t\/* General sanity checks *\/\n\tif (mem->memory_size & (PAGE_SIZE - 1))\n\t\tgoto out;\n\tif (mem->guest_phys_addr & (PAGE_SIZE - 1))\n\t\tgoto out;\n\t\/* We can read the guest memory with __xxx_user() later on. *\/\n\tif ((id < KVM_USER_MEM_SLOTS) &&\n\t ((mem->userspace_addr & (PAGE_SIZE - 1)) ||\n\t !access_ok((void __user *)(unsigned long)mem->userspace_addr,\n\t\t\tmem->memory_size)))\n\t\tgoto out;\n\tif (as_id >= KVM_ADDRESS_SPACE_NUM || id >= KVM_MEM_SLOTS_NUM)\n\t\tgoto out;\n\tif (mem->guest_phys_addr + mem->memory_size < mem->guest_phys_addr)\n\t\tgoto out;\n\n\tslot = id_to_memslot(__kvm_memslots(kvm, as_id), id);\n\tbase_gfn = mem->guest_phys_addr >> PAGE_SHIFT;\n\tnpages = mem->memory_size >> PAGE_SHIFT;\n\n\tif (npages > KVM_MEM_MAX_NR_PAGES)\n\t\tgoto out;\n\n\tnew = old = *slot;\n\n\tnew.id = id;\n\tnew.base_gfn = base_gfn;\n\tnew.npages = npages;\n\tnew.flags = mem->flags;\n\n\tif (npages) {\n\t\tif (!old.npages)\n\t\t\tchange = KVM_MR_CREATE;\n\t\telse { \/* Modify an existing slot. *\/\n\t\t\tif ((mem->userspace_addr != old.userspace_addr) ||\n\t\t\t (npages != old.npages) ||\n\t\t\t ((new.flags ^ old.flags) & KVM_MEM_READONLY))\n\t\t\t\tgoto out;\n\n\t\t\tif (base_gfn != old.base_gfn)\n\t\t\t\tchange = KVM_MR_MOVE;\n\t\t\telse if (new.flags != old.flags)\n\t\t\t\tchange = KVM_MR_FLAGS_ONLY;\n\t\t\telse { \/* Nothing to change. *\/\n\t\t\t\tr = 0;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif (!old.npages)\n\t\t\tgoto out;\n\n\t\tchange = KVM_MR_DELETE;\n\t\tnew.base_gfn = 0;\n\t\tnew.flags = 0;\n\t}\n\n\tif ((change == KVM_MR_CREATE) || (change == KVM_MR_MOVE)) {\n\t\t\/* Check for overlaps *\/\n\t\tr = -EEXIST;\n\t\tkvm_for_each_memslot(slot, __kvm_memslots(kvm, as_id)) {\n\t\t\tif (slot->id == id)\n\t\t\t\tcontinue;\n\t\t\tif (!((base_gfn + npages <= slot->base_gfn) ||\n\t\t\t (base_gfn >= slot->base_gfn + slot->npages)))\n\t\t\t\tgoto out;\n\t\t}\n\t}\n\n\t\/* Free page dirty bitmap if unneeded *\/\n\tif (!(new.flags & KVM_MEM_LOG_DIRTY_PAGES))\n\t\tnew.dirty_bitmap = NULL;\n\n\tr = -ENOMEM;\n\tif (change == KVM_MR_CREATE) {\n\t\tnew.userspace_addr = mem->userspace_addr;\n\n\t\tif (kvm_arch_create_memslot(kvm, &new, npages))\n\t\t\tgoto out_free;\n\t}\n\n\t\/* Allocate page dirty bitmap if needed *\/\n\tif ((new.flags & KVM_MEM_LOG_DIRTY_PAGES) && !new.dirty_bitmap) {\n\t\tif (kvm_create_dirty_bitmap(&new) < 0)\n\t\t\tgoto out_free;\n\t}\n\n\tslots = kvzalloc(sizeof(struct kvm_memslots), GFP_KERNEL);\n\tif (!slots)\n\t\tgoto out_free;\n\tmemcpy(slots, __kvm_memslots(kvm, as_id), sizeof(struct kvm_memslots));\n\n\tif ((change == KVM_MR_DELETE) || (change == KVM_MR_MOVE)) {\n\t\tslot = id_to_memslot(slots, id);\n\t\tslot->flags |= KVM_MEMSLOT_INVALID;\n\n\t\told_memslots = install_new_memslots(kvm, as_id, slots);\n\n\t\t\/* From this point no new shadow pages pointing to a deleted,\n\t\t * or moved, memslot will be created.\n\t\t *\n\t\t * validation of sp->gfn happens in:\n\t\t *\t- gfn_to_hva (kvm_read_guest, gfn_to_pfn)\n\t\t *\t- kvm_is_visible_gfn (mmu_check_roots)\n\t\t *\/\n\t\tkvm_arch_flush_shadow_memslot(kvm, slot);\n\n\t\t\/*\n\t\t * We can re-use the old_memslots from above, the only difference\n\t\t * from the currently installed memslots is the invalid flag. This\n\t\t * will get overwritten by update_memslots anyway.\n\t\t *\/\n\t\tslots = old_memslots;\n\t}\n\n\tr = kvm_arch_prepare_memory_region(kvm, &new, mem, change);\n\tif (r)\n\t\tgoto out_slots;\n\n\t\/* actual memory is freed via old in kvm_free_memslot below *\/\n\tif (change == KVM_MR_DELETE) {\n\t\tnew.dirty_bitmap = NULL;\n\t\tmemset(&new.arch, 0, sizeof(new.arch));\n\t}\n\n\tupdate_memslots(slots, &new, change);\n\told_memslots = install_new_memslots(kvm, as_id, slots);\n\n\tkvm_arch_commit_memory_region(kvm, mem, &old, &new, change);\n\n\tkvm_free_memslot(kvm, &old, &new);\n\tkvfree(old_memslots);\n\treturn 0;\n\nout_slots:\n\tkvfree(slots);\nout_free:\n\tkvm_free_memslot(kvm, &new, &old);\nout:\n\treturn r;\n}","target":0,"code_token_length":1235,"total_token_length":1566,"max_tokens_setting":2048} +{"idx":445873,"func":"exif_data_load_data_content (ExifData *data, ExifIfd ifd,\n\t\t\t const unsigned char *d,\n\t\t\t unsigned int ds, unsigned int offset, unsigned int recursion_cost)\n{\n\tExifLong o, thumbnail_offset = 0, thumbnail_length = 0;\n\tExifShort n;\n\tExifEntry *entry;\n\tunsigned int i;\n\tExifTag tag;\n\n\tif (!data || !data->priv) \n\t\treturn;\n\n\t\/* check for valid ExifIfd enum range *\/\n\tif ((((int)ifd) < 0) || ( ((int)ifd) >= EXIF_IFD_COUNT))\n\t return;\n\n\tif (recursion_cost > 170) {\n\t\t\/*\n\t\t * recursion_cost is a logarithmic-scale indicator of how expensive this\n\t\t * recursive call might end up being. It is an indicator of the depth of\n\t\t * recursion as well as the potential for worst-case future recursive\n\t\t * calls. Since it's difficult to tell ahead of time how often recursion\n\t\t * will occur, this assumes the worst by assuming every tag could end up\n\t\t * causing recursion.\n\t\t * The value of 170 was chosen to limit typical EXIF structures to a\n\t\t * recursive depth of about 6, but pathological ones (those with very\n\t\t * many tags) to only 2.\n\t\t *\/\n\t\texif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, \"ExifData\",\n\t\t\t \"Deep\/expensive recursion detected!\");\n\t\treturn;\n\t}\n\n\t\/* Read the number of entries *\/\n\tif (CHECKOVERFLOW(offset, ds, 2)) {\n\t\texif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, \"ExifData\",\n\t\t\t \"Tag data past end of buffer (%u+2 > %u)\", offset, ds);\n\t\treturn;\n\t}\n\tn = exif_get_short (d + offset, data->priv->order);\n\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\",\n\t \"Loading %hu entries...\", n);\n\toffset += 2;\n\n\t\/* Check if we have enough data. *\/\n\tif (CHECKOVERFLOW(offset, ds, 12*n)) {\n\t\tn = (ds - offset) \/ 12;\n\t\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\",\n\t\t\t\t \"Short data; only loading %hu entries...\", n);\n\t}\n\n\tfor (i = 0; i < n; i++) {\n\n\t\ttag = exif_get_short (d + offset + 12 * i, data->priv->order);\n\t\tswitch (tag) {\n\t\tcase EXIF_TAG_EXIF_IFD_POINTER:\n\t\tcase EXIF_TAG_GPS_INFO_IFD_POINTER:\n\t\tcase EXIF_TAG_INTEROPERABILITY_IFD_POINTER:\n\t\tcase EXIF_TAG_JPEG_INTERCHANGE_FORMAT_LENGTH:\n\t\tcase EXIF_TAG_JPEG_INTERCHANGE_FORMAT:\n\t\t\to = exif_get_long (d + offset + 12 * i + 8,\n\t\t\t\t\t data->priv->order);\n\t\t\tif (o >= ds) {\n\t\t\t\texif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, \"ExifData\",\n\t\t\t\t\t \"Tag data past end of buffer (%u > %u)\", offset+2, ds);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\/* FIXME: IFD_POINTER tags aren't marked as being in a\n\t\t\t * specific IFD, so exif_tag_get_name_in_ifd won't work\n\t\t\t *\/\n\t\t\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\",\n\t\t\t\t \"Sub-IFD entry 0x%x ('%s') at %u.\", tag,\n\t\t\t\t exif_tag_get_name(tag), o);\n\t\t\tswitch (tag) {\n\t\t\tcase EXIF_TAG_EXIF_IFD_POINTER:\n\t\t\t\tCHECK_REC (EXIF_IFD_EXIF);\n\t\t\t\texif_data_load_data_content (data, EXIF_IFD_EXIF, d, ds, o,\n\t\t\t\t\trecursion_cost + level_cost(n));\n\t\t\t\tbreak;\n\t\t\tcase EXIF_TAG_GPS_INFO_IFD_POINTER:\n\t\t\t\tCHECK_REC (EXIF_IFD_GPS);\n\t\t\t\texif_data_load_data_content (data, EXIF_IFD_GPS, d, ds, o,\n\t\t\t\t\trecursion_cost + level_cost(n));\n\t\t\t\tbreak;\n\t\t\tcase EXIF_TAG_INTEROPERABILITY_IFD_POINTER:\n\t\t\t\tCHECK_REC (EXIF_IFD_INTEROPERABILITY);\n\t\t\t\texif_data_load_data_content (data, EXIF_IFD_INTEROPERABILITY, d, ds, o,\n\t\t\t\t\trecursion_cost + level_cost(n));\n\t\t\t\tbreak;\n\t\t\tcase EXIF_TAG_JPEG_INTERCHANGE_FORMAT:\n\t\t\t\tthumbnail_offset = o;\n\t\t\t\tif (thumbnail_offset && thumbnail_length)\n\t\t\t\t\texif_data_load_data_thumbnail (data, d,\n\t\t\t\t\t\t\t\t ds, thumbnail_offset,\n\t\t\t\t\t\t\t\t thumbnail_length);\n\t\t\t\tbreak;\n\t\t\tcase EXIF_TAG_JPEG_INTERCHANGE_FORMAT_LENGTH:\n\t\t\t\tthumbnail_length = o;\n\t\t\t\tif (thumbnail_offset && thumbnail_length)\n\t\t\t\t\texif_data_load_data_thumbnail (data, d,\n\t\t\t\t\t\t\t\t ds, thumbnail_offset,\n\t\t\t\t\t\t\t\t thumbnail_length);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault:\n\n\t\t\t\/*\n\t\t\t * If we don't know the tag, don't fail. It could be that new \n\t\t\t * versions of the standard have defined additional tags. Note that\n\t\t\t * 0 is a valid tag in the GPS IFD.\n\t\t\t *\/\n\t\t\tif (!exif_tag_get_name_in_ifd (tag, ifd)) {\n\n\t\t\t\t\/*\n\t\t\t\t * Special case: Tag and format 0. That's against specification\n\t\t\t\t * (at least up to 2.2). But Photoshop writes it anyways.\n\t\t\t\t *\/\n\t\t\t\tif (!memcmp (d + offset + 12 * i, \"\\0\\0\\0\\0\", 4)) {\n\t\t\t\t\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\",\n\t\t\t\t\t\t \"Skipping empty entry at position %u in '%s'.\", i, \n\t\t\t\t\t\t exif_ifd_get_name (ifd));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\texif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, \"ExifData\",\n\t\t\t\t\t \"Unknown tag 0x%04x (entry %u in '%s'). Please report this tag \"\n\t\t\t\t\t \"to .\", tag, i,\n\t\t\t\t\t exif_ifd_get_name (ifd));\n\t\t\t\tif (data->priv->options & EXIF_DATA_OPTION_IGNORE_UNKNOWN_TAGS)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tentry = exif_entry_new_mem (data->priv->mem);\n\t\t\tif (!entry) {\n\t\t\t\t exif_log (data->priv->log, EXIF_LOG_CODE_NO_MEMORY, \"ExifData\",\n \"Could not allocate memory\");\n\t\t\t\t return;\n\t\t\t}\n\t\t\tif (exif_data_load_data_entry (data, entry, d, ds,\n\t\t\t\t\t\t offset + 12 * i))\n\t\t\t\texif_content_add_entry (data->ifd[ifd], entry);\n\t\t\texif_entry_unref (entry);\n\t\t\tbreak;\n\t\t}\n\t}\n}","target":0,"code_token_length":1515,"total_token_length":1846,"max_tokens_setting":2048} +{"idx":264354,"func":"int libevt_record_values_read_end_of_file(\n libevt_record_values_t *record_values,\n uint8_t *record_data,\n size_t record_data_size,\n libcerror_error_t **error )\n{\n\tstatic char *function = \"libevt_record_values_read_end_of_file\";\n\tuint32_t size = 0;\n\tuint32_t size_copy = 0;\n\n#if defined( HAVE_DEBUG_OUTPUT )\n\tuint32_t value_32bit = 0;\n#endif\n\n\tif( record_values == NULL )\n\t{\n\t\tlibcerror_error_set(\n\t\t error,\n\t\t LIBCERROR_ERROR_DOMAIN_ARGUMENTS,\n\t\t LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,\n\t\t \"%s: invalid record values.\",\n\t\t function );\n\n\t\treturn( -1 );\n\t}\n\tif( record_data == NULL )\n\t{\n\t\tlibcerror_error_set(\n\t\t error,\n\t\t LIBCERROR_ERROR_DOMAIN_ARGUMENTS,\n\t\t LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,\n\t\t \"%s: invalid record data.\",\n\t\t function );\n\n\t\treturn( -1 );\n\t}\n\tif( record_data_size > (size_t) SSIZE_MAX )\n\t{\n\t\tlibcerror_error_set(\n\t\t error,\n\t\t LIBCERROR_ERROR_DOMAIN_ARGUMENTS,\n\t\t LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM,\n\t\t \"%s: invalid record data size value exceeds maximum.\",\n\t\t function );\n\n\t\treturn( -1 );\n\t}\n\tif( record_data_size < sizeof( evt_record_end_of_file_t ) )\n\t{\n\t\tlibcerror_error_set(\n\t\t error,\n\t\t LIBCERROR_ERROR_DOMAIN_RUNTIME,\n\t\t LIBCERROR_RUNTIME_ERROR_VALUE_OUT_OF_BOUNDS,\n\t\t \"%s: record data size value out of bounds.\",\n\t\t function );\n\n\t\treturn( -1 );\n\t}\n\tbyte_stream_copy_to_uint32_little_endian(\n\t ( (evt_record_end_of_file_t *) record_data )->size,\n\t size );\n\n\tbyte_stream_copy_to_uint32_little_endian(\n\t ( (evt_record_end_of_file_t *) record_data )->size_copy,\n\t size_copy );\n\n#if defined( HAVE_DEBUG_OUTPUT )\n\tif( libcnotify_verbose != 0 )\n\t{\n\t\tlibcnotify_printf(\n\t\t \"%s: size\\t\\t\\t\\t: %\" PRIu32 \"\\n\",\n\t\t function,\n\t\t size );\n\n\t\tbyte_stream_copy_to_uint32_little_endian(\n\t\t ( (evt_record_end_of_file_t *) record_data )->signature1,\n\t\t value_32bit );\n\t\tlibcnotify_printf(\n\t\t \"%s: signature1\\t\\t\\t: 0x%08\" PRIx32 \"\\n\",\n\t\t function,\n\t\t value_32bit );\n\n\t\tbyte_stream_copy_to_uint32_little_endian(\n\t\t ( (evt_record_end_of_file_t *) record_data )->signature2,\n\t\t value_32bit );\n\t\tlibcnotify_printf(\n\t\t \"%s: signature2\\t\\t\\t: 0x%08\" PRIx32 \"\\n\",\n\t\t function,\n\t\t value_32bit );\n\n\t\tbyte_stream_copy_to_uint32_little_endian(\n\t\t ( (evt_record_end_of_file_t *) record_data )->signature3,\n\t\t value_32bit );\n\t\tlibcnotify_printf(\n\t\t \"%s: signature3\\t\\t\\t: 0x%08\" PRIx32 \"\\n\",\n\t\t function,\n\t\t value_32bit );\n\n\t\tbyte_stream_copy_to_uint32_little_endian(\n\t\t ( (evt_record_end_of_file_t *) record_data )->signature4,\n\t\t value_32bit );\n\t\tlibcnotify_printf(\n\t\t \"%s: signature4\\t\\t\\t: 0x%08\" PRIx32 \"\\n\",\n\t\t function,\n\t\t value_32bit );\n\n\t\tbyte_stream_copy_to_uint32_little_endian(\n\t\t ( (evt_record_end_of_file_t *) record_data )->first_record_offset,\n\t\t value_32bit );\n\t\tlibcnotify_printf(\n\t\t \"%s: first record offset\\t\\t: 0x%08\" PRIx32 \"\\n\",\n\t\t function,\n\t\t value_32bit );\n\n\t\tbyte_stream_copy_to_uint32_little_endian(\n\t\t ( (evt_record_end_of_file_t *) record_data )->end_of_file_record_offset,\n\t\t value_32bit );\n\t\tlibcnotify_printf(\n\t\t \"%s: end of file record offset\\t: 0x%08\" PRIx32 \"\\n\",\n\t\t function,\n\t\t value_32bit );\n\n\t\tbyte_stream_copy_to_uint32_little_endian(\n\t\t ( (evt_record_end_of_file_t *) record_data )->last_record_number,\n\t\t value_32bit );\n\t\tlibcnotify_printf(\n\t\t \"%s: last record number\\t\\t: %\" PRIu32 \"\\n\",\n\t\t function,\n\t\t value_32bit );\n\n\t\tbyte_stream_copy_to_uint32_little_endian(\n\t\t ( (evt_record_end_of_file_t *) record_data )->first_record_number,\n\t\t value_32bit );\n\t\tlibcnotify_printf(\n\t\t \"%s: first record number\\t\\t: %\" PRIu32 \"\\n\",\n\t\t function,\n\t\t value_32bit );\n\n\t\tlibcnotify_printf(\n\t\t \"%s: size copy\\t\\t\\t: %\" PRIu32 \"\\n\",\n\t\t function,\n\t\t size_copy );\n\n\t\tlibcnotify_printf(\n\t\t \"\\n\" );\n\t}\n#endif\n\tif( size != size_copy )\n\t{\n\t\tlibcerror_error_set(\n\t\t error,\n\t\t LIBCERROR_ERROR_DOMAIN_INPUT,\n\t\t LIBCERROR_INPUT_ERROR_VALUE_MISMATCH,\n\t\t \"%s: value mismatch for size and size copy.\",\n\t\t function );\n\n\t\treturn( -1 );\n\t}\n\tif( record_data_size != (size_t) size )\n\t{\n\t\tlibcerror_error_set(\n\t\t error,\n\t\t LIBCERROR_ERROR_DOMAIN_INPUT,\n\t\t LIBCERROR_INPUT_ERROR_VALUE_MISMATCH,\n\t\t \"%s: value mismatch for record data size and size.\",\n\t\t function );\n\n\t\treturn( -1 );\n\t}\n\/* TODO correct values in IO handle if necessary *\/\n\n\treturn( 1 );\n}","target":0,"code_token_length":1247,"total_token_length":1578,"max_tokens_setting":2048} +{"idx":271143,"func":"int BlackPreservingSampler(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void* Cargo)\n{\n int i;\n cmsFloat32Number Inf[4], Outf[4];\n cmsFloat32Number LabK[4];\n cmsFloat64Number SumCMY, SumCMYK, Error, Ratio;\n cmsCIELab ColorimetricLab, BlackPreservingLab;\n PreserveKPlaneParams* bp = (PreserveKPlaneParams*) Cargo;\n\n \/\/ Convert from 16 bits to floating point\n for (i=0; i < 4; i++)\n Inf[i] = (cmsFloat32Number) (In[i] \/ 65535.0);\n\n \/\/ Get the K across Tone curve\n LabK[3] = cmsEvalToneCurveFloat(bp ->KTone, Inf[3]);\n\n \/\/ If going across black only, keep black only\n if (In[0] == 0 && In[1] == 0 && In[2] == 0) {\n\n Out[0] = Out[1] = Out[2] = 0;\n Out[3] = _cmsQuickSaturateWord(LabK[3] * 65535.0);\n return TRUE;\n }\n\n \/\/ Try the original transform,\n cmsPipelineEvalFloat( Inf, Outf, bp ->cmyk2cmyk);\n\n \/\/ Store a copy of the floating point result into 16-bit\n for (i=0; i < 4; i++)\n Out[i] = _cmsQuickSaturateWord(Outf[i] * 65535.0);\n\n \/\/ Maybe K is already ok (mostly on K=0)\n if ( fabs(Outf[3] - LabK[3]) < (3.0 \/ 65535.0) ) {\n return TRUE;\n }\n\n \/\/ K differ, mesure and keep Lab measurement for further usage\n \/\/ this is done in relative colorimetric intent\n cmsDoTransform(bp->hProofOutput, Out, &ColorimetricLab, 1);\n\n \/\/ Is not black only and the transform doesn't keep black.\n \/\/ Obtain the Lab of output CMYK. After that we have Lab + K\n cmsDoTransform(bp ->cmyk2Lab, Outf, LabK, 1);\n\n \/\/ Obtain the corresponding CMY using reverse interpolation\n \/\/ (K is fixed in LabK[3])\n if (!cmsPipelineEvalReverseFloat(LabK, Outf, Outf, bp ->LabK2cmyk)) {\n\n \/\/ Cannot find a suitable value, so use colorimetric xform\n \/\/ which is already stored in Out[]\n return TRUE;\n }\n\n \/\/ Make sure to pass thru K (which now is fixed)\n Outf[3] = LabK[3];\n\n \/\/ Apply TAC if needed\n SumCMY = Outf[0] + Outf[1] + Outf[2];\n SumCMYK = SumCMY + Outf[3];\n\n if (SumCMYK > bp ->MaxTAC) {\n\n Ratio = 1 - ((SumCMYK - bp->MaxTAC) \/ SumCMY);\n if (Ratio < 0)\n Ratio = 0;\n }\n else\n Ratio = 1.0;\n\n Out[0] = _cmsQuickSaturateWord(Outf[0] * Ratio * 65535.0); \/\/ C\n Out[1] = _cmsQuickSaturateWord(Outf[1] * Ratio * 65535.0); \/\/ M\n Out[2] = _cmsQuickSaturateWord(Outf[2] * Ratio * 65535.0); \/\/ Y\n Out[3] = _cmsQuickSaturateWord(Outf[3] * 65535.0);\n\n \/\/ Estimate the error (this goes 16 bits to Lab DBL)\n cmsDoTransform(bp->hProofOutput, Out, &BlackPreservingLab, 1);\n Error = cmsDeltaE(&ColorimetricLab, &BlackPreservingLab);\n if (Error > bp -> MaxError)\n bp->MaxError = Error;\n\n return TRUE;\n}","target":0,"code_token_length":960,"total_token_length":1291,"max_tokens_setting":2048} +{"idx":381539,"func":"HttpTransact::HandleCacheOpenReadHitFreshness(State* s)\n{\n CacheHTTPInfo *&obj = s->cache_info.object_read;\n\n ink_release_assert((s->request_sent_time == UNDEFINED_TIME) && (s->response_received_time == UNDEFINED_TIME));\n DebugTxn(\"http_seq\", \"[HttpTransact::HandleCacheOpenReadHitFreshness] Hit in cache\");\n\n if (delete_all_document_alternates_and_return(s, true)) {\n DebugTxn(\"http_trans\", \"[HandleCacheOpenReadHitFreshness] Delete and return\");\n s->cache_info.action = CACHE_DO_DELETE;\n s->next_action = HttpTransact::SM_ACTION_INTERNAL_CACHE_DELETE;\n return;\n }\n\n s->request_sent_time = obj->request_sent_time_get();\n s->response_received_time = obj->response_received_time_get();\n\n \/\/ There may be clock skew if one of the machines\n \/\/ went down and we do not have the correct delta\n \/\/ for it. this is just to deal with the effects\n \/\/ of the skew by setting minimum and maximum times\n \/\/ so that ages are not negative, etc.\n s->request_sent_time = min(s->client_request_time, s->request_sent_time);\n s->response_received_time = min(s->client_request_time, s->response_received_time);\n\n ink_assert(s->request_sent_time <= s->response_received_time);\n\n DebugTxn(\"http_trans\", \"[HandleCacheOpenReadHitFreshness] request_sent_time : %\" PRId64,\n (int64_t)s->request_sent_time);\n DebugTxn(\"http_trans\", \"[HandleCacheOpenReadHitFreshness] response_received_time : %\" PRId64,\n (int64_t)s->response_received_time);\n \/\/ if the plugin has already decided the freshness, we don't need to\n \/\/ do it again\n if (s->cache_lookup_result == HttpTransact::CACHE_LOOKUP_NONE) {\n \/\/ is the document still fresh enough to be served back to\n \/\/ the client without revalidation?\n Freshness_t freshness = what_is_document_freshness(s, &s->hdr_info.client_request, obj->response_get());\n switch (freshness) {\n case FRESHNESS_FRESH:\n DebugTxn(\"http_seq\", \"[HttpTransact::HandleCacheOpenReadHitFreshness] \" \"Fresh copy\");\n s->cache_lookup_result = HttpTransact::CACHE_LOOKUP_HIT_FRESH;\n break;\n case FRESHNESS_WARNING:\n DebugTxn(\"http_seq\", \"[HttpTransact::HandleCacheOpenReadHitFreshness] \" \"Heuristic-based Fresh copy\");\n s->cache_lookup_result = HttpTransact::CACHE_LOOKUP_HIT_WARNING;\n break;\n case FRESHNESS_STALE:\n DebugTxn(\"http_seq\", \"[HttpTransact::HandleCacheOpenReadHitFreshness] \" \"Stale in cache\");\n s->cache_lookup_result = HttpTransact::CACHE_LOOKUP_HIT_STALE;\n s->is_revalidation_necessary = true; \/\/ to identify a revalidation occurrence\n break;\n default:\n ink_assert(!(\"what_is_document_freshness has returned unsupported code.\"));\n break;\n }\n }\n\n ink_assert(s->cache_lookup_result != HttpTransact::CACHE_LOOKUP_MISS);\n if (s->cache_lookup_result == HttpTransact::CACHE_LOOKUP_HIT_STALE)\n SET_VIA_STRING(VIA_DETAIL_CACHE_LOOKUP, VIA_DETAIL_MISS_EXPIRED);\n\n if (!s->force_dns) { \/\/ If DNS is not performed before\n if (need_to_revalidate(s)) {\n TRANSACT_RETURN(SM_ACTION_API_CACHE_LOOKUP_COMPLETE, CallOSDNSLookup); \/\/ content needs to be revalidated and we did not perform a dns ....calling DNS lookup\n } else { \/\/ document can be served can cache\n TRANSACT_RETURN(SM_ACTION_API_CACHE_LOOKUP_COMPLETE, HttpTransact::HandleCacheOpenReadHit);\n }\n } else { \/\/ we have done dns . Its up to HandleCacheOpenReadHit to decide to go OS or serve from cache\n TRANSACT_RETURN(SM_ACTION_API_CACHE_LOOKUP_COMPLETE, HttpTransact::HandleCacheOpenReadHit);\n }\n}","target":0,"code_token_length":892,"total_token_length":1223,"max_tokens_setting":2048} +{"idx":84644,"func":"xfs_inode_from_disk(\n\tstruct xfs_inode\t*ip,\n\tstruct xfs_dinode\t*from)\n{\n\tstruct xfs_icdinode\t*to = &ip->i_d;\n\tstruct inode\t\t*inode = VFS_I(ip);\n\n\n\t\/*\n\t * Convert v1 inodes immediately to v2 inode format as this is the\n\t * minimum inode version format we support in the rest of the code.\n\t *\/\n\tto->di_version = from->di_version;\n\tif (to->di_version == 1) {\n\t\tset_nlink(inode, be16_to_cpu(from->di_onlink));\n\t\tto->di_projid_lo = 0;\n\t\tto->di_projid_hi = 0;\n\t\tto->di_version = 2;\n\t} else {\n\t\tset_nlink(inode, be32_to_cpu(from->di_nlink));\n\t\tto->di_projid_lo = be16_to_cpu(from->di_projid_lo);\n\t\tto->di_projid_hi = be16_to_cpu(from->di_projid_hi);\n\t}\n\n\tto->di_format = from->di_format;\n\tto->di_uid = be32_to_cpu(from->di_uid);\n\tto->di_gid = be32_to_cpu(from->di_gid);\n\tto->di_flushiter = be16_to_cpu(from->di_flushiter);\n\n\t\/*\n\t * Time is signed, so need to convert to signed 32 bit before\n\t * storing in inode timestamp which may be 64 bit. Otherwise\n\t * a time before epoch is converted to a time long after epoch\n\t * on 64 bit systems.\n\t *\/\n\tinode->i_atime.tv_sec = (int)be32_to_cpu(from->di_atime.t_sec);\n\tinode->i_atime.tv_nsec = (int)be32_to_cpu(from->di_atime.t_nsec);\n\tinode->i_mtime.tv_sec = (int)be32_to_cpu(from->di_mtime.t_sec);\n\tinode->i_mtime.tv_nsec = (int)be32_to_cpu(from->di_mtime.t_nsec);\n\tinode->i_ctime.tv_sec = (int)be32_to_cpu(from->di_ctime.t_sec);\n\tinode->i_ctime.tv_nsec = (int)be32_to_cpu(from->di_ctime.t_nsec);\n\tinode->i_generation = be32_to_cpu(from->di_gen);\n\tinode->i_mode = be16_to_cpu(from->di_mode);\n\n\tto->di_size = be64_to_cpu(from->di_size);\n\tto->di_nblocks = be64_to_cpu(from->di_nblocks);\n\tto->di_extsize = be32_to_cpu(from->di_extsize);\n\tto->di_nextents = be32_to_cpu(from->di_nextents);\n\tto->di_anextents = be16_to_cpu(from->di_anextents);\n\tto->di_forkoff = from->di_forkoff;\n\tto->di_aformat\t= from->di_aformat;\n\tto->di_dmevmask\t= be32_to_cpu(from->di_dmevmask);\n\tto->di_dmstate\t= be16_to_cpu(from->di_dmstate);\n\tto->di_flags\t= be16_to_cpu(from->di_flags);\n\n\tif (to->di_version == 3) {\n\t\tinode_set_iversion_queried(inode,\n\t\t\t\t\t be64_to_cpu(from->di_changecount));\n\t\tto->di_crtime.t_sec = be32_to_cpu(from->di_crtime.t_sec);\n\t\tto->di_crtime.t_nsec = be32_to_cpu(from->di_crtime.t_nsec);\n\t\tto->di_flags2 = be64_to_cpu(from->di_flags2);\n\t\tto->di_cowextsize = be32_to_cpu(from->di_cowextsize);\n\t}\n}","target":0,"code_token_length":810,"total_token_length":1141,"max_tokens_setting":2048} +{"idx":386913,"func":"do_move (GVfsBackend *backend,\n GVfsJobMove *job,\n const char *source,\n const char *destination,\n GFileCopyFlags flags,\n GFileProgressCallback progress_callback,\n gpointer progress_callback_data)\n{\n SoupMessage *msg;\n SoupURI *source_uri;\n SoupURI *target_uri;\n guint status;\n GFileType source_ft, target_ft;\n GError *error = NULL;\n gboolean res;\n\n if (flags & G_FILE_COPY_BACKUP)\n {\n if (flags & G_FILE_COPY_NO_FALLBACK_FOR_MOVE)\n {\n g_vfs_job_failed_literal (G_VFS_JOB (job),\n G_IO_ERROR,\n G_IO_ERROR_CANT_CREATE_BACKUP,\n _(\"Backups not supported\"));\n }\n else\n {\n \/* Return G_IO_ERROR_NOT_SUPPORTED instead of G_IO_ERROR_CANT_CREATE_BACKUP\n * to be proceeded with copy and delete fallback (see g_file_move). *\/\n g_vfs_job_failed_literal (G_VFS_JOB (job),\n G_IO_ERROR,\n G_IO_ERROR_NOT_SUPPORTED,\n \"Operation not supported\");\n }\n\n return;\n }\n\n source_uri = g_vfs_backend_dav_uri_for_path (backend, source, FALSE);\n msg = soup_message_new_from_uri (SOUP_METHOD_MOVE, source_uri);\n target_uri = g_vfs_backend_dav_uri_for_path (backend, destination, FALSE);\n\n res = stat_location (backend, target_uri, &target_ft, NULL, &error);\n if (!res && !g_error_matches (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND))\n {\n g_vfs_job_failed_from_error (G_VFS_JOB (job), error);\n g_error_free (error);\n return;\n }\n\n if (res)\n {\n if (flags & G_FILE_COPY_OVERWRITE)\n {\n res = stat_location (backend, source_uri, &source_ft, NULL, &error);\n if (res)\n {\n if (target_ft == G_FILE_TYPE_DIRECTORY)\n {\n if (source_ft == G_FILE_TYPE_DIRECTORY)\n g_vfs_job_failed_literal (G_VFS_JOB(job),\n G_IO_ERROR,\n G_IO_ERROR_WOULD_MERGE,\n _(\"Can't move directory over directory\"));\n else\n g_vfs_job_failed_literal (G_VFS_JOB(job),\n G_IO_ERROR,\n G_IO_ERROR_IS_DIRECTORY,\n _(\"Can't move over directory\"));\n return;\n }\n else if (source_ft == G_FILE_TYPE_DIRECTORY)\n {\n \/* Overwriting a file with a directory, first remove the\n * file *\/\n SoupMessage *msg;\n\n msg = soup_message_new_from_uri (SOUP_METHOD_DELETE,\n target_uri);\n status = g_vfs_backend_dav_send_message (backend, msg);\n\n if (!SOUP_STATUS_IS_SUCCESSFUL (status))\n {\n http_job_failed (G_VFS_JOB (job), msg);\n g_object_unref (msg);\n return;\n }\n g_object_unref (msg);\n }\n }\n else\n {\n g_vfs_job_failed_from_error (G_VFS_JOB (job), error);\n g_error_free (error);\n return;\n }\n }\n else\n {\n g_vfs_job_failed_literal (G_VFS_JOB(job),\n G_IO_ERROR,\n G_IO_ERROR_EXISTS,\n _(\"Target file exists\"));\n }\n }\n\n message_add_destination_header (msg, target_uri);\n message_add_overwrite_header (msg, flags & G_FILE_COPY_OVERWRITE);\n\n status = g_vfs_backend_dav_send_message (backend, msg);\n\n \/*\n * The precondition of SOUP_STATUS_PRECONDITION_FAILED (412) in\n * this case was triggered by the \"Overwrite: F\" header which\n * means that the target already exists.\n * Also if we get a REDIRECTION it means that there was no\n * \"Location\" header, since otherwise that would have triggered\n * our redirection handler. This probably means we are dealing\n * with an web dav implementation (like mod_dav) that also sends\n * redirects for the destionaion (i.e. \"Destination: \/foo\" header)\n * which very likely means that the target also exists (and is a\n * directory). That or the webdav server is broken.\n * We could find out by doing another stat and but I think this is\n * such a corner case that we are totally fine with returning\n * G_IO_ERROR_EXISTS.\n * *\/\n\n if (SOUP_STATUS_IS_SUCCESSFUL (status))\n {\n g_vfs_job_succeeded (G_VFS_JOB (job));\n }\n else if (status == SOUP_STATUS_PRECONDITION_FAILED ||\n SOUP_STATUS_IS_REDIRECTION (status))\n g_vfs_job_failed (G_VFS_JOB (job), G_IO_ERROR,\n G_IO_ERROR_EXISTS,\n _(\"Target file already exists\"));\n else\n http_job_failed (G_VFS_JOB (job), msg);\n\n g_object_unref (msg);\n soup_uri_free (source_uri);\n soup_uri_free (target_uri);\n}","target":0,"code_token_length":1094,"total_token_length":1425,"max_tokens_setting":2048} +{"idx":403020,"func":"ptp_unpack_OI (PTPParams *params, unsigned char* data, PTPObjectInfo *oi, unsigned int len)\n{\n\tuint8_t filenamelen;\n\tuint8_t capturedatelen;\n\tchar *capture_date;\n\n\tif (len < PTP_oi_SequenceNumber)\n\t\treturn;\n\n\toi->Filename = oi->Keywords = NULL;\n\n\t\/* FIXME: also handle length with all the strings at the end *\/\n\toi->StorageID=dtoh32a(&data[PTP_oi_StorageID]);\n\toi->ObjectFormat=dtoh16a(&data[PTP_oi_ObjectFormat]);\n\toi->ProtectionStatus=dtoh16a(&data[PTP_oi_ProtectionStatus]);\n\toi->ObjectCompressedSize=dtoh32a(&data[PTP_oi_ObjectCompressedSize]);\n\n\t\/* Stupid Samsung Galaxy developers emit a 64bit objectcompressedsize *\/\n\tif ((data[PTP_oi_filenamelen] == 0) && (data[PTP_oi_filenamelen+4] != 0)) {\n\t\tparams->ocs64 = 1;\n\t\tdata += 4;\n\t}\n\toi->ThumbFormat=dtoh16a(&data[PTP_oi_ThumbFormat]);\n\toi->ThumbCompressedSize=dtoh32a(&data[PTP_oi_ThumbCompressedSize]);\n\toi->ThumbPixWidth=dtoh32a(&data[PTP_oi_ThumbPixWidth]);\n\toi->ThumbPixHeight=dtoh32a(&data[PTP_oi_ThumbPixHeight]);\n\toi->ImagePixWidth=dtoh32a(&data[PTP_oi_ImagePixWidth]);\n\toi->ImagePixHeight=dtoh32a(&data[PTP_oi_ImagePixHeight]);\n\toi->ImageBitDepth=dtoh32a(&data[PTP_oi_ImageBitDepth]);\n\toi->ParentObject=dtoh32a(&data[PTP_oi_ParentObject]);\n\toi->AssociationType=dtoh16a(&data[PTP_oi_AssociationType]);\n\toi->AssociationDesc=dtoh32a(&data[PTP_oi_AssociationDesc]);\n\toi->SequenceNumber=dtoh32a(&data[PTP_oi_SequenceNumber]);\n\n\toi->Filename= ptp_unpack_string(params, data, PTP_oi_filenamelen, len, &filenamelen);\n\n\tcapture_date = ptp_unpack_string(params, data,\n\t\tPTP_oi_filenamelen+filenamelen*2+1, len, &capturedatelen);\n\t\/* subset of ISO 8601, without '.s' tenths of second and \n\t * time zone\n\t *\/\n\toi->CaptureDate = ptp_unpack_PTPTIME(capture_date);\n\tfree(capture_date);\n\n\t\/* now the modification date ... *\/\n\tcapture_date = ptp_unpack_string(params, data,\n\t\tPTP_oi_filenamelen+filenamelen*2\n\t\t+capturedatelen*2+2, len, &capturedatelen);\n\toi->ModificationDate = ptp_unpack_PTPTIME(capture_date);\n\tfree(capture_date);\n}","target":0,"code_token_length":708,"total_token_length":1039,"max_tokens_setting":2048} +{"idx":84907,"func":"ex_align(exarg_T *eap)\n{\n pos_T\tsave_curpos;\n int\t\tlen;\n int\t\tindent = 0;\n int\t\tnew_indent;\n int\t\thas_tab;\n int\t\twidth;\n\n#ifdef FEAT_RIGHTLEFT\n if (curwin->w_p_rl)\n {\n\t\/* switch left and right aligning *\/\n\tif (eap->cmdidx == CMD_right)\n\t eap->cmdidx = CMD_left;\n\telse if (eap->cmdidx == CMD_left)\n\t eap->cmdidx = CMD_right;\n }\n#endif\n\n width = atoi((char *)eap->arg);\n save_curpos = curwin->w_cursor;\n if (eap->cmdidx == CMD_left) \/* width is used for new indent *\/\n {\n\tif (width >= 0)\n\t indent = width;\n }\n else\n {\n\t\/*\n\t * if 'textwidth' set, use it\n\t * else if 'wrapmargin' set, use it\n\t * if invalid value, use 80\n\t *\/\n\tif (width <= 0)\n\t width = curbuf->b_p_tw;\n\tif (width == 0 && curbuf->b_p_wm > 0)\n\t width = curwin->w_width - curbuf->b_p_wm;\n\tif (width <= 0)\n\t width = 80;\n }\n\n if (u_save((linenr_T)(eap->line1 - 1), (linenr_T)(eap->line2 + 1)) == FAIL)\n\treturn;\n\n for (curwin->w_cursor.lnum = eap->line1;\n\t\t curwin->w_cursor.lnum <= eap->line2; ++curwin->w_cursor.lnum)\n {\n\tif (eap->cmdidx == CMD_left)\t\t\/* left align *\/\n\t new_indent = indent;\n\telse\n\t{\n\t has_tab = FALSE;\t\/* avoid uninit warnings *\/\n\t len = linelen(eap->cmdidx == CMD_right ? &has_tab\n\t\t\t\t\t\t : NULL) - get_indent();\n\n\t if (len <= 0)\t\t\t\/* skip blank lines *\/\n\t\tcontinue;\n\n\t if (eap->cmdidx == CMD_center)\n\t\tnew_indent = (width - len) \/ 2;\n\t else\n\t {\n\t\tnew_indent = width - len;\t\/* right align *\/\n\n\t\t\/*\n\t\t * Make sure that embedded TABs don't make the text go too far\n\t\t * to the right.\n\t\t *\/\n\t\tif (has_tab)\n\t\t while (new_indent > 0)\n\t\t {\n\t\t\t(void)set_indent(new_indent, 0);\n\t\t\tif (linelen(NULL) <= width)\n\t\t\t{\n\t\t\t \/*\n\t\t\t * Now try to move the line as much as possible to\n\t\t\t * the right. Stop when it moves too far.\n\t\t\t *\/\n\t\t\t do\n\t\t\t\t(void)set_indent(++new_indent, 0);\n\t\t\t while (linelen(NULL) <= width);\n\t\t\t --new_indent;\n\t\t\t break;\n\t\t\t}\n\t\t\t--new_indent;\n\t\t }\n\t }\n\t}\n\tif (new_indent < 0)\n\t new_indent = 0;\n\t(void)set_indent(new_indent, 0);\t\t\/* set indent *\/\n }\n changed_lines(eap->line1, 0, eap->line2 + 1, 0L);\n curwin->w_cursor = save_curpos;\n beginline(BL_WHITE | BL_FIX);\n}","target":0,"code_token_length":734,"total_token_length":1065,"max_tokens_setting":2048} +{"idx":99759,"func":"SMB2_read(const unsigned int xid, struct cifs_io_parms *io_parms,\n\t unsigned int *nbytes, char **buf, int *buf_type)\n{\n\tstruct smb_rqst rqst;\n\tint resp_buftype, rc = -EACCES;\n\tstruct smb2_read_plain_req *req = NULL;\n\tstruct smb2_read_rsp *rsp = NULL;\n\tstruct kvec iov[1];\n\tstruct kvec rsp_iov;\n\tunsigned int total_len;\n\tint flags = CIFS_LOG_ERROR;\n\tstruct cifs_ses *ses = io_parms->tcon->ses;\n\n\t*nbytes = 0;\n\trc = smb2_new_read_req((void **)&req, &total_len, io_parms, NULL, 0, 0);\n\tif (rc)\n\t\treturn rc;\n\n\tif (smb3_encryption_required(io_parms->tcon))\n\t\tflags |= CIFS_TRANSFORM_REQ;\n\n\tiov[0].iov_base = (char *)req;\n\tiov[0].iov_len = total_len;\n\n\tmemset(&rqst, 0, sizeof(struct smb_rqst));\n\trqst.rq_iov = iov;\n\trqst.rq_nvec = 1;\n\n\trc = cifs_send_recv(xid, ses, &rqst, &resp_buftype, flags, &rsp_iov);\n\trsp = (struct smb2_read_rsp *)rsp_iov.iov_base;\n\n\tif (rc) {\n\t\tif (rc != -ENODATA) {\n\t\t\tcifs_stats_fail_inc(io_parms->tcon, SMB2_READ_HE);\n\t\t\tcifs_dbg(VFS, \"Send error in read = %d\\n\", rc);\n\t\t\ttrace_smb3_read_err(xid, req->PersistentFileId,\n\t\t\t\t\t io_parms->tcon->tid, ses->Suid,\n\t\t\t\t\t io_parms->offset, io_parms->length,\n\t\t\t\t\t rc);\n\t\t} else\n\t\t\ttrace_smb3_read_done(xid, req->PersistentFileId,\n\t\t\t\t io_parms->tcon->tid, ses->Suid,\n\t\t\t\t io_parms->offset, 0);\n\t\tfree_rsp_buf(resp_buftype, rsp_iov.iov_base);\n\t\treturn rc == -ENODATA ? 0 : rc;\n\t} else\n\t\ttrace_smb3_read_done(xid, req->PersistentFileId,\n\t\t\t\t io_parms->tcon->tid, ses->Suid,\n\t\t\t\t io_parms->offset, io_parms->length);\n\n\tcifs_small_buf_release(req);\n\n\t*nbytes = le32_to_cpu(rsp->DataLength);\n\tif ((*nbytes > CIFS_MAX_MSGSIZE) ||\n\t (*nbytes > io_parms->length)) {\n\t\tcifs_dbg(FYI, \"bad length %d for count %d\\n\",\n\t\t\t *nbytes, io_parms->length);\n\t\trc = -EIO;\n\t\t*nbytes = 0;\n\t}\n\n\tif (*buf) {\n\t\tmemcpy(*buf, (char *)rsp + rsp->DataOffset, *nbytes);\n\t\tfree_rsp_buf(resp_buftype, rsp_iov.iov_base);\n\t} else if (resp_buftype != CIFS_NO_BUFFER) {\n\t\t*buf = rsp_iov.iov_base;\n\t\tif (resp_buftype == CIFS_SMALL_BUFFER)\n\t\t\t*buf_type = CIFS_SMALL_BUFFER;\n\t\telse if (resp_buftype == CIFS_LARGE_BUFFER)\n\t\t\t*buf_type = CIFS_LARGE_BUFFER;\n\t}\n\treturn rc;\n}","target":0,"code_token_length":718,"total_token_length":1049,"max_tokens_setting":2048} +{"idx":344374,"func":"add_account (GoaProvider *provider,\n GoaClient *client,\n GtkDialog *dialog,\n GtkBox *vbox,\n GError **error)\n{\n AddAccountData data;\n GVariantBuilder credentials;\n GVariantBuilder details;\n GoaEwsClient *ews_client;\n GoaObject *ret;\n const gchar *email_address;\n const gchar *server;\n const gchar *password;\n const gchar *username;\n const gchar *provider_type;\n gint response;\n\n ews_client = NULL;\n ret = NULL;\n\n memset (&data, 0, sizeof (AddAccountData));\n data.loop = g_main_loop_new (NULL, FALSE);\n data.dialog = dialog;\n data.error = NULL;\n\n create_account_details_ui (provider, dialog, vbox, TRUE, &data);\n gtk_widget_show_all (GTK_WIDGET (vbox));\n\n ews_client = goa_ews_client_new ();\n\n ews_again:\n response = gtk_dialog_run (dialog);\n if (response != GTK_RESPONSE_OK)\n {\n g_set_error (&data.error,\n GOA_ERROR,\n GOA_ERROR_DIALOG_DISMISSED,\n _(\"Dialog was dismissed\"));\n goto out;\n }\n\n email_address = gtk_entry_get_text (GTK_ENTRY (data.email_address));\n password = gtk_entry_get_text (GTK_ENTRY (data.password));\n username = gtk_entry_get_text (GTK_ENTRY (data.username));\n server = gtk_entry_get_text (GTK_ENTRY (data.server));\n\n \/* See if there's already an account of this type with the\n * given identity\n *\/\n provider_type = goa_provider_get_provider_type (provider);\n if (!goa_utils_check_duplicate (client,\n username,\n provider_type,\n (GoaPeekInterfaceFunc) goa_object_peek_password_based,\n &data.error))\n goto out;\n\n goa_ews_client_autodiscover (ews_client,\n email_address,\n password,\n username,\n server,\n NULL,\n autodiscover_cb,\n &data);\n goa_spinner_button_start (GOA_SPINNER_BUTTON (data.spinner_button));\n g_main_loop_run (data.loop);\n\n if (data.error != NULL)\n {\n gchar *markup;\n\n markup = g_strdup_printf (\"%s:<\/b> %s\",\n _(\"Error connecting to Microsoft Exchange server\"),\n data.error->message);\n g_clear_error (&data.error);\n\n gtk_label_set_markup (GTK_LABEL (data.cluebar_label), markup);\n g_free (markup);\n\n goa_spinner_button_set_label (GOA_SPINNER_BUTTON (data.spinner_button), _(\"_Try Again\"));\n gtk_expander_set_expanded (GTK_EXPANDER (data.expander), TRUE);\n gtk_widget_set_no_show_all (data.cluebar, FALSE);\n gtk_widget_show_all (data.cluebar);\n goto ews_again;\n }\n\n gtk_widget_hide (GTK_WIDGET (dialog));\n\n g_variant_builder_init (&credentials, G_VARIANT_TYPE_VARDICT);\n g_variant_builder_add (&credentials, \"{sv}\", \"password\", g_variant_new_string (password));\n\n g_variant_builder_init (&details, G_VARIANT_TYPE (\"a{ss}\"));\n g_variant_builder_add (&details, \"{ss}\", \"MailEnabled\", \"true\");\n g_variant_builder_add (&details, \"{ss}\", \"CalendarEnabled\", \"true\");\n g_variant_builder_add (&details, \"{ss}\", \"ContactsEnabled\", \"true\");\n g_variant_builder_add (&details, \"{ss}\", \"Host\", server);\n\n \/* OK, everything is dandy, add the account *\/\n \/* we want the GoaClient to update before this method returns (so it\n * can create a proxy for the new object) so run the mainloop while\n * waiting for this to complete\n *\/\n goa_manager_call_add_account (goa_client_get_manager (client),\n goa_provider_get_provider_type (provider),\n username,\n email_address,\n g_variant_builder_end (&credentials),\n g_variant_builder_end (&details),\n NULL, \/* GCancellable* *\/\n (GAsyncReadyCallback) add_account_cb,\n &data);\n g_main_loop_run (data.loop);\n if (data.error != NULL)\n goto out;\n\n ret = GOA_OBJECT (g_dbus_object_manager_get_object (goa_client_get_object_manager (client),\n data.account_object_path));\n\n out:\n \/* We might have an object even when data.error is set.\n * eg., if we failed to store the credentials in the keyring.\n *\/\n if (data.error != NULL)\n g_propagate_error (error, data.error);\n else\n g_assert (ret != NULL);\n\n g_free (data.account_object_path);\n if (data.loop != NULL)\n g_main_loop_unref (data.loop);\n if (ews_client != NULL)\n g_object_unref (ews_client);\n return ret;\n}","target":1,"code_token_length":1045,"total_token_length":1376,"max_tokens_setting":2048} +{"idx":298258,"func":"void CreateStatusBar(void)\n{\n\tSIZE sz = {0, 0};\n\tRECT rect;\n\tLONG x, y, width, height;\n\tint edge[3];\n\tTBBUTTON tbbStatusToolbarButtons[1];\n\tTBBUTTONINFO tbi;\n\tHFONT hFont;\n\tHDC hDC;\n\n\t\/\/ Create the status bar (WS_CLIPSIBLINGS since we have an overlapping button)\n\thStatus = CreateWindowExW(0, STATUSCLASSNAME, NULL, WS_CHILD | WS_VISIBLE | SBARS_TOOLTIPS | WS_CLIPSIBLINGS,\n\t\tCW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, hMainDialog,\n\t\t(HMENU)IDC_STATUS, hMainInstance, NULL);\n\n\t\/\/ Keep track of the status bar height\n\tGetClientRect(hStatus, &rect);\n\theight = rect.bottom;\n\n\t\/\/ Set the font we'll use to display the '#' sign in the toolbar button\n\thFont = CreateFontA(-MulDiv(10, GetDeviceCaps(GetDC(hMainDialog), LOGPIXELSY), 72),\n\t\t0, 0, 0, FW_MEDIUM, FALSE, FALSE, FALSE, DEFAULT_CHARSET,\n\t\t0, 0, PROOF_QUALITY, 0, (nWindowsVersion >= WINDOWS_VISTA)?\"Segoe UI\":\"Arial Unicode MS\");\n\n\t\/\/ Find the width of our hash sign\n\thDC = GetDC(hMainDialog);\n\tSelectObject(hDC, hFont);\n\tGetTextExtentPoint32W(hDC, L\"#\", 1, &sz);\n\tif (hDC != NULL)\n\t\tReleaseDC(hMainDialog, hDC);\n\n\t\/\/ Create 3 status areas\n\tGetClientRect(hMainDialog, &rect);\n\tedge[1] = rect.right - (int)(SB_TIMER_SECTION_SIZE * fScale);\n\tedge[0] = edge[1] - (8 + sz.cx + 8 + 1); \/\/ There's 8 absolute pixels on right and left of the text\n\tedge[2] = rect.right;\n\tSendMessage(hStatus, SB_SETPARTS, (WPARAM)ARRAYSIZE(edge), (LPARAM)&edge);\n\n\t\/\/ NB: To add an icon on the status bar, you can use something like this:\n\t\/\/\tSendMessage(hStatus, SB_SETICON, (WPARAM) 1, (LPARAM)LoadImage(GetLibraryHandle(\"rasdlg\"),\n\t\/\/\t\tMAKEINTRESOURCE(50), IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR | LR_SHARED));\n\n\t\/\/ This is supposed to create a toolips for a statusbar section (when SBARS_TOOLTIPS is in use)... but doesn't :(\n\t\/\/\tSendMessageLU(hStatus, SB_SETTIPTEXT, (WPARAM)2, (LPARAM)\"HELLO\");\n\n\t\/\/ Compute the dimensions for the hash button\n\tx = edge[0];\n\tif (nWindowsVersion <= WINDOWS_XP) {\n\t\tx -= 1;\n\t\theight -= 2;\n\t}\n\ty = rect.bottom - height + 1;\n\twidth = edge[1] - edge[0] - 1;\n\t\/\/ How I wish there was a way to figure out how to make Windows controls look good\n\t\/\/ at all scales, without adding all these crappy empirical adjustments...\n\tif ((fScale > 1.20f) && (fScale <2.40f))\n\t\theight -= 1;\n\tif (nWindowsVersion <= WINDOWS_7)\n\t\theight += 1;\n\n\t\/\/ Create the status toolbar\n\thStatusToolbar = CreateWindowExW(WS_EX_TRANSPARENT, TOOLBARCLASSNAME, NULL, WS_CHILD | WS_TABSTOP | WS_DISABLED |\n\t\tTBSTYLE_LIST | CCS_NOPARENTALIGN | CCS_NODIVIDER | CCS_NORESIZE,\n\t\tx, y, width, height, hMainDialog, (HMENU)IDC_STATUS_TOOLBAR, hMainInstance, NULL);\n\n\t\/\/ Set the button properties\n\tSendMessage(hStatusToolbar, WM_SETFONT, (WPARAM)hFont, TRUE);\n\tSendMessage(hStatusToolbar, TB_SETEXTENDEDSTYLE, 0, (LPARAM)TBSTYLE_EX_MIXEDBUTTONS);\n\tSendMessage(hStatusToolbar, TB_SETIMAGELIST, 0, (LPARAM)NULL);\n\tSendMessage(hStatusToolbar, TB_SETDISABLEDIMAGELIST, 0, (LPARAM)NULL);\n\tSendMessage(hStatusToolbar, TB_SETBITMAPSIZE, 0, MAKELONG(0,0));\n\n\t\/\/ Set our text\n\tmemset(tbbStatusToolbarButtons, 0, sizeof(TBBUTTON));\n\ttbbStatusToolbarButtons[0].idCommand = IDC_HASH;\n\ttbbStatusToolbarButtons[0].fsStyle = BTNS_SHOWTEXT;\n\ttbbStatusToolbarButtons[0].fsState = TBSTATE_ENABLED;\n\ttbbStatusToolbarButtons[0].iString = (INT_PTR)L\"#\";\n\tSendMessage(hStatusToolbar, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0);\n\tSendMessage(hStatusToolbar, TB_ADDBUTTONS, (WPARAM)1, (LPARAM)&tbbStatusToolbarButtons);\n\n\tSendMessage(hStatusToolbar, TB_SETBUTTONSIZE, 0, MAKELPARAM(width, height - 1));\n\t\/\/ Yeah, you'd think that TB_SETBUTTONSIZE would work for the width... but you'd be wrong.\n\t\/\/ The only working method that actually enforces the requested width is TB_SETBUTTONINFO\n\ttbi.cbSize = sizeof(tbi);\n\ttbi.dwMask = TBIF_SIZE | TBIF_COMMAND;\n\ttbi.cx = (WORD)width;\n\ttbi.idCommand = IDC_HASH;\n\tSendMessage(hStatusToolbar, TB_SETBUTTONINFO, (WPARAM)IDC_HASH, (LPARAM)&tbi);\n\n\t\/\/ Need to resend the positioning for the toolbar to become active... One of Windows' mysteries\n\t\/\/ Also use this opportunity to set our Z-order for tab stop\n\tSetWindowPos(hStatusToolbar, GetDlgItem(hMainDialog, IDCANCEL), x, y, width, height, 0);\n\tShowWindow(hStatusToolbar, SW_SHOWNORMAL);\n}","target":0,"code_token_length":1292,"total_token_length":1623,"max_tokens_setting":2048} +{"idx":394631,"func":"wb_set_offset(struct archive_write *a, int64_t off)\n{\n\tstruct iso9660 *iso9660 = (struct iso9660 *)a->format_data;\n\tint64_t used, ext_bytes;\n\n\tif (iso9660->wbuff_type != WB_TO_TEMP) {\n\t\tarchive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,\n\t\t \"Internal Programing error: iso9660:wb_set_offset()\");\n\t\treturn (ARCHIVE_FATAL);\n\t}\n\n\tused = sizeof(iso9660->wbuff) - iso9660->wbuff_remaining;\n\tif (iso9660->wbuff_offset + used > iso9660->wbuff_tail)\n\t\tiso9660->wbuff_tail = iso9660->wbuff_offset + used;\n\tif (iso9660->wbuff_offset < iso9660->wbuff_written) {\n\t\tif (used > 0 &&\n\t\t write_to_temp(a, iso9660->wbuff, (size_t)used) != ARCHIVE_OK)\n\t\t\treturn (ARCHIVE_FATAL);\n\t\tiso9660->wbuff_offset = iso9660->wbuff_written;\n\t\tlseek(iso9660->temp_fd, iso9660->wbuff_offset, SEEK_SET);\n\t\tiso9660->wbuff_remaining = sizeof(iso9660->wbuff);\n\t\tused = 0;\n\t}\n\tif (off < iso9660->wbuff_offset) {\n\t\t\/*\n\t\t * Write out waiting data.\n\t\t *\/\n\t\tif (used > 0) {\n\t\t\tif (wb_write_out(a) != ARCHIVE_OK)\n\t\t\t\treturn (ARCHIVE_FATAL);\n\t\t}\n\t\tlseek(iso9660->temp_fd, off, SEEK_SET);\n\t\tiso9660->wbuff_offset = off;\n\t\tiso9660->wbuff_remaining = sizeof(iso9660->wbuff);\n\t} else if (off <= iso9660->wbuff_tail) {\n\t\tiso9660->wbuff_remaining = (size_t)\n\t\t (sizeof(iso9660->wbuff) - (off - iso9660->wbuff_offset));\n\t} else {\n\t\text_bytes = off - iso9660->wbuff_tail;\n\t\tiso9660->wbuff_remaining = (size_t)(sizeof(iso9660->wbuff)\n\t\t - (iso9660->wbuff_tail - iso9660->wbuff_offset));\n\t\twhile (ext_bytes >= (int64_t)iso9660->wbuff_remaining) {\n\t\t\tif (write_null(a, (size_t)iso9660->wbuff_remaining)\n\t\t\t != ARCHIVE_OK)\n\t\t\t\treturn (ARCHIVE_FATAL);\n\t\t\text_bytes -= iso9660->wbuff_remaining;\n\t\t}\n\t\tif (ext_bytes > 0) {\n\t\t\tif (write_null(a, (size_t)ext_bytes) != ARCHIVE_OK)\n\t\t\t\treturn (ARCHIVE_FATAL);\n\t\t}\n\t}\n\treturn (ARCHIVE_OK);\n}","target":0,"code_token_length":695,"total_token_length":1026,"max_tokens_setting":2048} +{"idx":36873,"func":"static int pfkey_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type,\n\t\t\t const struct xfrm_migrate *m, int num_bundles,\n\t\t\t const struct xfrm_kmaddress *k)\n{\n\tint i;\n\tint sasize_sel;\n\tint size = 0;\n\tint size_pol = 0;\n\tstruct sk_buff *skb;\n\tstruct sadb_msg *hdr;\n\tstruct sadb_x_policy *pol;\n\tconst struct xfrm_migrate *mp;\n\n\tif (type != XFRM_POLICY_TYPE_MAIN)\n\t\treturn 0;\n\n\tif (num_bundles <= 0 || num_bundles > XFRM_MAX_DEPTH)\n\t\treturn -EINVAL;\n\n\tif (k != NULL) {\n\t\t\/* addresses for KM *\/\n\t\tsize += PFKEY_ALIGN8(sizeof(struct sadb_x_kmaddress) +\n\t\t\t\t pfkey_sockaddr_pair_size(k->family));\n\t}\n\n\t\/* selector *\/\n\tsasize_sel = pfkey_sockaddr_size(sel->family);\n\tif (!sasize_sel)\n\t\treturn -EINVAL;\n\tsize += (sizeof(struct sadb_address) + sasize_sel) * 2;\n\n\t\/* policy info *\/\n\tsize_pol += sizeof(struct sadb_x_policy);\n\n\t\/* ipsecrequests *\/\n\tfor (i = 0, mp = m; i < num_bundles; i++, mp++) {\n\t\t\/* old locator pair *\/\n\t\tsize_pol += sizeof(struct sadb_x_ipsecrequest) +\n\t\t\t pfkey_sockaddr_pair_size(mp->old_family);\n\t\t\/* new locator pair *\/\n\t\tsize_pol += sizeof(struct sadb_x_ipsecrequest) +\n\t\t\t pfkey_sockaddr_pair_size(mp->new_family);\n\t}\n\n\tsize += sizeof(struct sadb_msg) + size_pol;\n\n\t\/* alloc buffer *\/\n\tskb = alloc_skb(size, GFP_ATOMIC);\n\tif (skb == NULL)\n\t\treturn -ENOMEM;\n\n\thdr = (struct sadb_msg *)skb_put(skb, sizeof(struct sadb_msg));\n\thdr->sadb_msg_version = PF_KEY_V2;\n\thdr->sadb_msg_type = SADB_X_MIGRATE;\n\thdr->sadb_msg_satype = pfkey_proto2satype(m->proto);\n\thdr->sadb_msg_len = size \/ 8;\n\thdr->sadb_msg_errno = 0;\n\thdr->sadb_msg_reserved = 0;\n\thdr->sadb_msg_seq = 0;\n\thdr->sadb_msg_pid = 0;\n\n\t\/* Addresses to be used by KM for negotiation, if ext is available *\/\n\tif (k != NULL && (set_sadb_kmaddress(skb, k) < 0))\n\t\tgoto err;\n\n\t\/* selector src *\/\n\tset_sadb_address(skb, sasize_sel, SADB_EXT_ADDRESS_SRC, sel);\n\n\t\/* selector dst *\/\n\tset_sadb_address(skb, sasize_sel, SADB_EXT_ADDRESS_DST, sel);\n\n\t\/* policy information *\/\n\tpol = (struct sadb_x_policy *)skb_put(skb, sizeof(struct sadb_x_policy));\n\tpol->sadb_x_policy_len = size_pol \/ 8;\n\tpol->sadb_x_policy_exttype = SADB_X_EXT_POLICY;\n\tpol->sadb_x_policy_type = IPSEC_POLICY_IPSEC;\n\tpol->sadb_x_policy_dir = dir + 1;\n\tpol->sadb_x_policy_id = 0;\n\tpol->sadb_x_policy_priority = 0;\n\n\tfor (i = 0, mp = m; i < num_bundles; i++, mp++) {\n\t\t\/* old ipsecrequest *\/\n\t\tint mode = pfkey_mode_from_xfrm(mp->mode);\n\t\tif (mode < 0)\n\t\t\tgoto err;\n\t\tif (set_ipsecrequest(skb, mp->proto, mode,\n\t\t\t\t (mp->reqid ? IPSEC_LEVEL_UNIQUE : IPSEC_LEVEL_REQUIRE),\n\t\t\t\t mp->reqid, mp->old_family,\n\t\t\t\t &mp->old_saddr, &mp->old_daddr) < 0)\n\t\t\tgoto err;\n\n\t\t\/* new ipsecrequest *\/\n\t\tif (set_ipsecrequest(skb, mp->proto, mode,\n\t\t\t\t (mp->reqid ? IPSEC_LEVEL_UNIQUE : IPSEC_LEVEL_REQUIRE),\n\t\t\t\t mp->reqid, mp->new_family,\n\t\t\t\t &mp->new_saddr, &mp->new_daddr) < 0)\n\t\t\tgoto err;\n\t}\n\n\t\/* broadcast migrate message to sockets *\/\n\tpfkey_broadcast(skb, GFP_ATOMIC, BROADCAST_ALL, NULL, &init_net);\n\n\treturn 0;\n\nerr:\n\tkfree_skb(skb);\n\treturn -EINVAL;\n}","target":0,"code_token_length":952,"total_token_length":1283,"max_tokens_setting":2048} +{"idx":30164,"func":"void bn_sqr_comba8 ( BN_ULONG * r , const BN_ULONG * a ) {\n BN_ULONG c1 , c2 , c3 ;\n c1 = 0 ;\n c2 = 0 ;\n c3 = 0 ;\n sqr_add_c ( a , 0 , c1 , c2 , c3 ) ;\n r [ 0 ] = c1 ;\n c1 = 0 ;\n sqr_add_c2 ( a , 1 , 0 , c2 , c3 , c1 ) ;\n r [ 1 ] = c2 ;\n c2 = 0 ;\n sqr_add_c ( a , 1 , c3 , c1 , c2 ) ;\n sqr_add_c2 ( a , 2 , 0 , c3 , c1 , c2 ) ;\n r [ 2 ] = c3 ;\n c3 = 0 ;\n sqr_add_c2 ( a , 3 , 0 , c1 , c2 , c3 ) ;\n sqr_add_c2 ( a , 2 , 1 , c1 , c2 , c3 ) ;\n r [ 3 ] = c1 ;\n c1 = 0 ;\n sqr_add_c ( a , 2 , c2 , c3 , c1 ) ;\n sqr_add_c2 ( a , 3 , 1 , c2 , c3 , c1 ) ;\n sqr_add_c2 ( a , 4 , 0 , c2 , c3 , c1 ) ;\n r [ 4 ] = c2 ;\n c2 = 0 ;\n sqr_add_c2 ( a , 5 , 0 , c3 , c1 , c2 ) ;\n sqr_add_c2 ( a , 4 , 1 , c3 , c1 , c2 ) ;\n sqr_add_c2 ( a , 3 , 2 , c3 , c1 , c2 ) ;\n r [ 5 ] = c3 ;\n c3 = 0 ;\n sqr_add_c ( a , 3 , c1 , c2 , c3 ) ;\n sqr_add_c2 ( a , 4 , 2 , c1 , c2 , c3 ) ;\n sqr_add_c2 ( a , 5 , 1 , c1 , c2 , c3 ) ;\n sqr_add_c2 ( a , 6 , 0 , c1 , c2 , c3 ) ;\n r [ 6 ] = c1 ;\n c1 = 0 ;\n sqr_add_c2 ( a , 7 , 0 , c2 , c3 , c1 ) ;\n sqr_add_c2 ( a , 6 , 1 , c2 , c3 , c1 ) ;\n sqr_add_c2 ( a , 5 , 2 , c2 , c3 , c1 ) ;\n sqr_add_c2 ( a , 4 , 3 , c2 , c3 , c1 ) ;\n r [ 7 ] = c2 ;\n c2 = 0 ;\n sqr_add_c ( a , 4 , c3 , c1 , c2 ) ;\n sqr_add_c2 ( a , 5 , 3 , c3 , c1 , c2 ) ;\n sqr_add_c2 ( a , 6 , 2 , c3 , c1 , c2 ) ;\n sqr_add_c2 ( a , 7 , 1 , c3 , c1 , c2 ) ;\n r [ 8 ] = c3 ;\n c3 = 0 ;\n sqr_add_c2 ( a , 7 , 2 , c1 , c2 , c3 ) ;\n sqr_add_c2 ( a , 6 , 3 , c1 , c2 , c3 ) ;\n sqr_add_c2 ( a , 5 , 4 , c1 , c2 , c3 ) ;\n r [ 9 ] = c1 ;\n c1 = 0 ;\n sqr_add_c ( a , 5 , c2 , c3 , c1 ) ;\n sqr_add_c2 ( a , 6 , 4 , c2 , c3 , c1 ) ;\n sqr_add_c2 ( a , 7 , 3 , c2 , c3 , c1 ) ;\n r [ 10 ] = c2 ;\n c2 = 0 ;\n sqr_add_c2 ( a , 7 , 4 , c3 , c1 , c2 ) ;\n sqr_add_c2 ( a , 6 , 5 , c3 , c1 , c2 ) ;\n r [ 11 ] = c3 ;\n c3 = 0 ;\n sqr_add_c ( a , 6 , c1 , c2 , c3 ) ;\n sqr_add_c2 ( a , 7 , 5 , c1 , c2 , c3 ) ;\n r [ 12 ] = c1 ;\n c1 = 0 ;\n sqr_add_c2 ( a , 7 , 6 , c2 , c3 , c1 ) ;\n r [ 13 ] = c2 ;\n c2 = 0 ;\n sqr_add_c ( a , 7 , c3 , c1 , c2 ) ;\n r [ 14 ] = c3 ;\n r [ 15 ] = c1 ;\n }","target":0,"code_token_length":1084,"total_token_length":1415,"max_tokens_setting":2048} +{"idx":220657,"func":"CoreEnterLeaveEvent(DeviceIntPtr mouse,\n int type,\n int mode, int detail, WindowPtr pWin, Window child)\n{\n xEvent event = {\n .u.u.type = type,\n .u.u.detail = detail\n };\n WindowPtr focus;\n DeviceIntPtr keybd;\n GrabPtr grab = mouse->deviceGrab.grab;\n Mask mask;\n\n keybd = GetMaster(mouse, KEYBOARD_OR_FLOAT);\n\n if ((pWin == mouse->valuator->motionHintWindow) &&\n (detail != NotifyInferior))\n mouse->valuator->motionHintWindow = NullWindow;\n if (grab) {\n mask = (pWin == grab->window) ? grab->eventMask : 0;\n if (grab->ownerEvents)\n mask |= EventMaskForClient(pWin, rClient(grab));\n }\n else {\n mask = pWin->eventMask | wOtherEventMasks(pWin);\n }\n\n event.u.enterLeave.time = currentTime.milliseconds;\n event.u.enterLeave.rootX = mouse->spriteInfo->sprite->hot.x;\n event.u.enterLeave.rootY = mouse->spriteInfo->sprite->hot.y;\n \/* Counts on the same initial structure of crossing & button events! *\/\n FixUpEventFromWindow(mouse->spriteInfo->sprite, &event, pWin, None, FALSE);\n \/* Enter\/Leave events always set child *\/\n event.u.enterLeave.child = child;\n event.u.enterLeave.flags = event.u.keyButtonPointer.sameScreen ?\n ELFlagSameScreen : 0;\n event.u.enterLeave.state =\n mouse->button ? (mouse->button->state & 0x1f00) : 0;\n if (keybd)\n event.u.enterLeave.state |=\n XkbGrabStateFromRec(&keybd->key->xkbInfo->state);\n event.u.enterLeave.mode = mode;\n focus = (keybd) ? keybd->focus->win : None;\n if ((focus != NoneWin) &&\n ((pWin == focus) || (focus == PointerRootWin) || IsParent(focus, pWin)))\n event.u.enterLeave.flags |= ELFlagFocus;\n\n if ((mask & GetEventFilter(mouse, &event))) {\n if (grab)\n TryClientEvents(rClient(grab), mouse, &event, 1, mask,\n GetEventFilter(mouse, &event), grab);\n else\n DeliverEventsToWindow(mouse, pWin, &event, 1,\n GetEventFilter(mouse, &event), NullGrab);\n }\n\n if ((type == EnterNotify) && (mask & KeymapStateMask)) {\n xKeymapEvent ke = {\n .type = KeymapNotify\n };\n ClientPtr client = grab ? rClient(grab) : wClient(pWin);\n int rc;\n\n rc = XaceHook(XACE_DEVICE_ACCESS, client, keybd, DixReadAccess);\n if (rc == Success)\n memcpy((char *) &ke.map[0], (char *) &keybd->key->down[1], 31);\n\n if (grab)\n TryClientEvents(rClient(grab), keybd, (xEvent *) &ke, 1,\n mask, KeymapStateMask, grab);\n else\n DeliverEventsToWindow(mouse, pWin, (xEvent *) &ke, 1,\n KeymapStateMask, NullGrab);\n }\n}\n","target":0,"code_token_length":731,"total_token_length":1062,"max_tokens_setting":2048} +{"idx":392389,"func":"xmlBufAttrSerializeTxtContent(xmlBufPtr buf, xmlDocPtr doc,\n xmlAttrPtr attr, const xmlChar * string)\n{\n xmlChar *base, *cur;\n\n if (string == NULL)\n return;\n base = cur = (xmlChar *) string;\n while (*cur != 0) {\n if (*cur == '\\n') {\n if (base != cur)\n xmlBufAdd(buf, base, cur - base);\n xmlBufAdd(buf, BAD_CAST \" \", 5);\n cur++;\n base = cur;\n } else if (*cur == '\\r') {\n if (base != cur)\n xmlBufAdd(buf, base, cur - base);\n xmlBufAdd(buf, BAD_CAST \" \", 5);\n cur++;\n base = cur;\n } else if (*cur == '\\t') {\n if (base != cur)\n xmlBufAdd(buf, base, cur - base);\n xmlBufAdd(buf, BAD_CAST \" \", 4);\n cur++;\n base = cur;\n } else if (*cur == '\"') {\n if (base != cur)\n xmlBufAdd(buf, base, cur - base);\n xmlBufAdd(buf, BAD_CAST \""\", 6);\n cur++;\n base = cur;\n } else if (*cur == '<') {\n if (base != cur)\n xmlBufAdd(buf, base, cur - base);\n xmlBufAdd(buf, BAD_CAST \"<\", 4);\n cur++;\n base = cur;\n } else if (*cur == '>') {\n if (base != cur)\n xmlBufAdd(buf, base, cur - base);\n xmlBufAdd(buf, BAD_CAST \">\", 4);\n cur++;\n base = cur;\n } else if (*cur == '&') {\n if (base != cur)\n xmlBufAdd(buf, base, cur - base);\n xmlBufAdd(buf, BAD_CAST \"&\", 5);\n cur++;\n base = cur;\n } else if ((*cur >= 0x80) && (cur[1] != 0) &&\n\t ((doc == NULL) || (doc->encoding == NULL))) {\n \/*\n * We assume we have UTF-8 content.\n *\/\n unsigned char tmp[12];\n int val = 0, l = 1;\n\n if (base != cur)\n xmlBufAdd(buf, base, cur - base);\n if (*cur < 0xC0) {\n xmlSaveErr(XML_SAVE_NOT_UTF8, (xmlNodePtr) attr, NULL);\n if (doc != NULL)\n doc->encoding = xmlStrdup(BAD_CAST \"ISO-8859-1\");\n\t\txmlSerializeHexCharRef(tmp, *cur);\n xmlBufAdd(buf, (xmlChar *) tmp, -1);\n cur++;\n base = cur;\n continue;\n } else if (*cur < 0xE0) {\n val = (cur[0]) & 0x1F;\n val <<= 6;\n val |= (cur[1]) & 0x3F;\n l = 2;\n } else if ((*cur < 0xF0) && (cur [2] != 0)) {\n val = (cur[0]) & 0x0F;\n val <<= 6;\n val |= (cur[1]) & 0x3F;\n val <<= 6;\n val |= (cur[2]) & 0x3F;\n l = 3;\n } else if ((*cur < 0xF8) && (cur [2] != 0) && (cur[3] != 0)) {\n val = (cur[0]) & 0x07;\n val <<= 6;\n val |= (cur[1]) & 0x3F;\n val <<= 6;\n val |= (cur[2]) & 0x3F;\n val <<= 6;\n val |= (cur[3]) & 0x3F;\n l = 4;\n }\n if ((l == 1) || (!IS_CHAR(val))) {\n xmlSaveErr(XML_SAVE_CHAR_INVALID, (xmlNodePtr) attr, NULL);\n if (doc != NULL)\n doc->encoding = xmlStrdup(BAD_CAST \"ISO-8859-1\");\n\n\t\txmlSerializeHexCharRef(tmp, *cur);\n xmlBufAdd(buf, (xmlChar *) tmp, -1);\n cur++;\n base = cur;\n continue;\n }\n \/*\n * We could do multiple things here. Just save\n * as a char ref\n *\/\n\t xmlSerializeHexCharRef(tmp, val);\n xmlBufAdd(buf, (xmlChar *) tmp, -1);\n cur += l;\n base = cur;\n } else {\n cur++;\n }\n }\n if (base != cur)\n xmlBufAdd(buf, base, cur - base);\n}","target":0,"code_token_length":1065,"total_token_length":1396,"max_tokens_setting":2048} +{"idx":3185,"func":"static void get_over(struct SYMBOL *s)\n{\n\tstruct VOICE_S *p_voice, *p_voice2, *p_voice3;\n\tint range, voice, voice2, voice3;\nstatic char tx_wrong_dur[] = \"Wrong duration in voice overlay\";\nstatic char txt_no_note[] = \"No note in voice overlay\";\n\n\t\/* treat the end of overlay *\/\n\tp_voice = curvoice;\n\tif (p_voice->ignore)\n\t\treturn;\n\tif (s->abc_type == ABC_T_BAR\n\t || s->u.v_over.type == V_OVER_E) {\n\t\tif (!p_voice->last_sym) {\n\t\t\terror(1, s, txt_no_note);\n\t\t\treturn;\n\t\t}\n\t\tp_voice->last_sym->sflags |= S_BEAM_END;\n\t\tover_bar = 0;\n\t\tif (over_time < 0) {\n\t\t\terror(1, s, \"Erroneous end of voice overlap\");\n\t\t\treturn;\n\t\t}\n\t\tif (p_voice->time != over_mxtime)\n\t\t\terror(1, s, tx_wrong_dur);\n\t\tcurvoice = &voice_tb[over_voice];\n\t\tover_mxtime = 0;\n\t\tover_voice = -1;\n\t\tover_time = -1;\n\t\treturn;\n\t}\n\n\t\/* treat the full overlay start *\/\n\tif (s->u.v_over.type == V_OVER_S) {\n\t\tover_voice = p_voice - voice_tb;\n\t\tover_time = p_voice->time;\n\t\treturn;\n\t}\n\n\t\/* (here is treated a new overlay - '&') *\/\n\t\/* create the extra voice if not done yet *\/\n\tif (!p_voice->last_sym) {\n\t\terror(1, s, txt_no_note);\n\t\treturn;\n\t}\n\tp_voice->last_sym->sflags |= S_BEAM_END;\n\tvoice2 = s->u.v_over.voice;\n\tp_voice2 = &voice_tb[voice2];\n\tif (parsys->voice[voice2].range < 0) {\n\t\tint clone;\n\n\t\tif (cfmt.abc2pscompat) {\n\t\t\terror(1, s, \"Cannot have %%%%abc2pscompat\");\n\t\t\tcfmt.abc2pscompat = 0;\n\t\t}\n\t\tclone = p_voice->clone >= 0;\n\t\tp_voice2->id[0] = '&';\n\t\tp_voice2->id[1] = '\\0';\n\t\tp_voice2->second = 1;\n\t\tparsys->voice[voice2].second = 1;\n\t\tp_voice2->scale = p_voice->scale;\n\t\tp_voice2->octave = p_voice->octave;\n\t\tp_voice2->transpose = p_voice->transpose;\n\t\tmemcpy(&p_voice2->key, &p_voice->key,\n\t\t\t\t\tsizeof p_voice2->key);\n\t\tmemcpy(&p_voice2->ckey, &p_voice->ckey,\n\t\t\t\t\tsizeof p_voice2->ckey);\n\t\tmemcpy(&p_voice2->okey, &p_voice->okey,\n\t\t\t\t\tsizeof p_voice2->okey);\n\t\tp_voice2->posit = p_voice->posit;\n\t\tp_voice2->staff = p_voice->staff;\n\t\tp_voice2->cstaff = p_voice->cstaff;\n\t\tp_voice2->color = p_voice->color;\n\t\tp_voice2->map_name = p_voice->map_name;\n\t\trange = parsys->voice[p_voice - voice_tb].range;\n\t\tfor (voice = 0; voice < MAXVOICE; voice++) {\n\t\t\tif (parsys->voice[voice].range > range)\n\t\t\t\tparsys->voice[voice].range += clone + 1;\n\t\t}\n\t\tparsys->voice[voice2].range = range + 1;\n\t\tvoice_link(p_voice2);\n\t\tif (clone) {\n\t\t\tfor (voice3 = MAXVOICE; --voice3 >= 0; ) {\n\t\t\t\tif (parsys->voice[voice3].range < 0)\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (voice3 > 0) {\n\t\t\t\tp_voice3 = &voice_tb[voice3];\n\t\t\t\tstrcpy(p_voice3->id, p_voice2->id);\n\t\t\t\tp_voice3->second = 1;\n\t\t\t\tparsys->voice[voice3].second = 1;\n\t\t\t\tp_voice3->scale = voice_tb[p_voice->clone].scale;\n\t\t\t\tparsys->voice[voice3].range = range + 2;\n\t\t\t\tvoice_link(p_voice3);\n\t\t\t\tp_voice2->clone = voice3;\n\t\t\t} else {\n\t\t\t\terror(1, s,\n\t\t\t\t \"Too many voices for overlay cloning\");\n\t\t\t}\n\t\t}\n\t}\n\tvoice = p_voice - voice_tb;\n\/\/\tp_voice2->cstaff = p_voice2->staff = parsys->voice[voice2].staff\n\/\/\t\t\t= parsys->voice[voice].staff;\n\/\/\tif ((voice3 = p_voice2->clone) >= 0) {\n\/\/\t\tp_voice3 = &voice_tb[voice3];\n\/\/\t\tp_voice3->cstaff = p_voice3->staff\n\/\/\t\t\t\t= parsys->voice[voice3].staff\n\/\/\t\t\t\t= parsys->voice[p_voice->clone].staff;\n\/\/\t}\n\n\tif (over_time < 0) {\t\t\t\/* first '&' in a measure *\/\n\t\tint time;\n\n\t\tover_bar = 1;\n\t\tover_mxtime = p_voice->time;\n\t\tover_voice = voice;\n\t\ttime = p_voice2->time;\n\t\tfor (s = p_voice->last_sym; \/*s*\/; s = s->prev) {\n\t\t\tif (s->type == BAR\n\t\t\t || s->time <= time)\t\/* (if start of tune) *\/\n\t\t\t\tbreak;\n\t\t}\n\t\tover_time = s->time;\n\t} else {\n\t\tif (over_mxtime == 0)\n\t\t\tover_mxtime = p_voice->time;\n\t\telse if (p_voice->time != over_mxtime)\n\t\t\terror(1, s, tx_wrong_dur);\n\t}\n\tp_voice2->time = over_time;\n\tcurvoice = p_voice2;\n}","target":1,"code_token_length":1287,"total_token_length":1618,"max_tokens_setting":2048} +{"idx":81835,"func":"MagickExport MagickBooleanType LevelImage(Image *image,const double black_point,\n const double white_point,const double gamma,ExceptionInfo *exception)\n{\n#define LevelImageTag \"Level\/Image\"\n\n CacheView\n *image_view;\n\n MagickBooleanType\n status;\n\n MagickOffsetType\n progress;\n\n register ssize_t\n i;\n\n ssize_t\n y;\n\n \/*\n Allocate and initialize levels map.\n *\/\n assert(image != (Image *) NULL);\n assert(image->signature == MagickCoreSignature);\n if (image->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",image->filename);\n if (image->storage_class == PseudoClass)\n for (i=0; i < (ssize_t) image->colors; i++)\n {\n \/*\n Level colormap.\n *\/\n if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0)\n image->colormap[i].red=(double) ClampToQuantum(LevelPixel(black_point,\n white_point,gamma,image->colormap[i].red));\n if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0)\n image->colormap[i].green=(double) ClampToQuantum(LevelPixel(black_point,\n white_point,gamma,image->colormap[i].green));\n if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0)\n image->colormap[i].blue=(double) ClampToQuantum(LevelPixel(black_point,\n white_point,gamma,image->colormap[i].blue));\n if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0)\n image->colormap[i].alpha=(double) ClampToQuantum(LevelPixel(black_point,\n white_point,gamma,image->colormap[i].alpha));\n }\n \/*\n Level image.\n *\/\n status=MagickTrue;\n progress=0;\n image_view=AcquireAuthenticCacheView(image,exception);\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp parallel for schedule(static,4) shared(progress,status) \\\n magick_threads(image,image,image->rows,1)\n#endif\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register Quantum\n *magick_restrict q;\n\n register ssize_t\n x;\n\n if (status == MagickFalse)\n continue;\n q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);\n if (q == (Quantum *) NULL)\n {\n status=MagickFalse;\n continue;\n }\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n register ssize_t\n j;\n\n if (GetPixelReadMask(image,q) == 0)\n {\n q+=GetPixelChannels(image);\n continue;\n }\n for (j=0; j < (ssize_t) GetPixelChannels(image); j++)\n {\n PixelChannel channel=GetPixelChannelChannel(image,j);\n PixelTrait traits=GetPixelChannelTraits(image,channel);\n if ((traits & UpdatePixelTrait) == 0)\n continue;\n q[j]=ClampToQuantum(LevelPixel(black_point,white_point,gamma,\n (double) q[j]));\n }\n q+=GetPixelChannels(image);\n }\n if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)\n status=MagickFalse;\n if (image->progress_monitor != (MagickProgressMonitor) NULL)\n {\n MagickBooleanType\n proceed;\n\n#if defined(MAGICKCORE_OPENMP_SUPPORT)\n #pragma omp critical (MagickCore_LevelImage)\n#endif\n proceed=SetImageProgress(image,LevelImageTag,progress++,image->rows);\n if (proceed == MagickFalse)\n status=MagickFalse;\n }\n }\n image_view=DestroyCacheView(image_view);\n (void) ClampImage(image,exception);\n return(status);\n}","target":0,"code_token_length":866,"total_token_length":1197,"max_tokens_setting":2048} +{"idx":484980,"func":"static Image *ReadGROUP4Image(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n char\n filename[MagickPathExtent];\n\n FILE\n *file;\n\n Image\n *image;\n\n ImageInfo\n *read_info;\n\n int\n c,\n unique_file;\n\n MagickBooleanType\n status;\n\n size_t\n length;\n\n ssize_t\n offset,\n strip_offset;\n\n \/*\n Open image file.\n *\/\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickCoreSignature);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickCoreSignature);\n if (IsEventLogging() != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n image=AcquireImage(image_info,exception);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n \/*\n Write raw CCITT Group 4 wrapped as a TIFF image file.\n *\/\n file=(FILE *) NULL;\n unique_file=AcquireUniqueFileResource(filename);\n if (unique_file != -1)\n file=fdopen(unique_file,\"wb\");\n if ((unique_file == -1) || (file == (FILE *) NULL))\n ThrowImageException(FileOpenError,\"UnableToCreateTemporaryFile\");\n length=fwrite(\"\\111\\111\\052\\000\\010\\000\\000\\000\\016\\000\",1,10,file);\n if (length != 10)\n ThrowReaderException(CorruptImageError,\"UnexpectedEndOfFile\");\n length=fwrite(\"\\376\\000\\003\\000\\001\\000\\000\\000\\000\\000\\000\\000\",1,12,file);\n length=fwrite(\"\\000\\001\\004\\000\\001\\000\\000\\000\",1,8,file);\n length=WriteLSBLong(file,(unsigned int) image->columns);\n length=fwrite(\"\\001\\001\\004\\000\\001\\000\\000\\000\",1,8,file);\n length=WriteLSBLong(file,(unsigned int) image->rows);\n length=fwrite(\"\\002\\001\\003\\000\\001\\000\\000\\000\\001\\000\\000\\000\",1,12,file);\n length=fwrite(\"\\003\\001\\003\\000\\001\\000\\000\\000\\004\\000\\000\\000\",1,12,file);\n length=fwrite(\"\\006\\001\\003\\000\\001\\000\\000\\000\\000\\000\\000\\000\",1,12,file);\n length=fwrite(\"\\021\\001\\003\\000\\001\\000\\000\\000\",1,8,file);\n strip_offset=10+(12*14)+4+8;\n length=WriteLSBLong(file,(unsigned int) strip_offset);\n length=fwrite(\"\\022\\001\\003\\000\\001\\000\\000\\000\",1,8,file);\n length=WriteLSBLong(file,(unsigned int) image_info->orientation);\n length=fwrite(\"\\025\\001\\003\\000\\001\\000\\000\\000\\001\\000\\000\\000\",1,12,file);\n length=fwrite(\"\\026\\001\\004\\000\\001\\000\\000\\000\",1,8,file);\n length=WriteLSBLong(file,(unsigned int) image->rows);\n length=fwrite(\"\\027\\001\\004\\000\\001\\000\\000\\000\\000\\000\\000\\000\",1,12,file);\n offset=(ssize_t) ftell(file)-4;\n length=fwrite(\"\\032\\001\\005\\000\\001\\000\\000\\000\",1,8,file);\n length=WriteLSBLong(file,(unsigned int) (strip_offset-8));\n length=fwrite(\"\\033\\001\\005\\000\\001\\000\\000\\000\",1,8,file);\n length=WriteLSBLong(file,(unsigned int) (strip_offset-8));\n length=fwrite(\"\\050\\001\\003\\000\\001\\000\\000\\000\\002\\000\\000\\000\",1,12,file);\n length=fwrite(\"\\000\\000\\000\\000\",1,4,file);\n length=WriteLSBLong(file,(unsigned int) image->resolution.x);\n length=WriteLSBLong(file,1);\n status=MagickTrue;\n for (length=0; (c=ReadBlobByte(image)) != EOF; length++)\n if (fputc(c,file) != c)\n status=MagickFalse;\n offset=(ssize_t) fseek(file,(off_t) offset,SEEK_SET);\n length=WriteLSBLong(file,(unsigned int) length);\n if (ferror(file) != 0)\n {\n (void) fclose(file);\n ThrowImageException(FileOpenError,\"UnableToCreateTemporaryFile\");\n }\n (void) fclose(file);\n (void) CloseBlob(image);\n image=DestroyImage(image);\n \/*\n Read TIFF image.\n *\/\n read_info=CloneImageInfo((ImageInfo *) NULL);\n (void) FormatLocaleString(read_info->filename,MagickPathExtent,\"%s\",filename);\n image=ReadTIFFImage(read_info,exception);\n read_info=DestroyImageInfo(read_info);\n if (image != (Image *) NULL)\n {\n (void) CopyMagickString(image->filename,image_info->filename,\n MagickPathExtent);\n (void) CopyMagickString(image->magick_filename,image_info->filename,\n MagickPathExtent);\n (void) CopyMagickString(image->magick,\"GROUP4\",MagickPathExtent);\n }\n (void) RelinquishUniqueFileResource(filename);\n if (status == MagickFalse)\n image=DestroyImage(image);\n return(image);\n}","target":0,"code_token_length":1614,"total_token_length":1945,"max_tokens_setting":2048} +{"idx":383858,"func":"PHP_METHOD(Phar, extractTo)\n{\n\tchar *error = NULL;\n\tphp_stream *fp;\n\tphp_stream_statbuf ssb;\n\tphar_entry_info *entry;\n\tchar *pathto, *filename, *actual;\n\tint pathto_len, filename_len;\n\tint ret, i;\n\tint nelems;\n\tzval *zval_files = NULL;\n\tzend_bool overwrite = 0;\n\n\tPHAR_ARCHIVE_OBJECT();\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s|z!b\", &pathto, &pathto_len, &zval_files, &overwrite) == FAILURE) {\n\t\treturn;\n\t}\n\n\tfp = php_stream_open_wrapper(phar_obj->arc.archive->fname, \"rb\", IGNORE_URL|STREAM_MUST_SEEK, &actual);\n\n\tif (!fp) {\n\t\tzend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC,\n\t\t\t\"Invalid argument, %s cannot be found\", phar_obj->arc.archive->fname);\n\t\treturn;\n\t}\n\n\tefree(actual);\n\tphp_stream_close(fp);\n\n\tif (pathto_len < 1) {\n\t\tzend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC,\n\t\t\t\"Invalid argument, extraction path must be non-zero length\");\n\t\treturn;\n\t}\n\n\tif (pathto_len >= MAXPATHLEN) {\n\t\tchar *tmp = estrndup(pathto, 50);\n\t\t\/* truncate for error message *\/\n\t\tzend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC, \"Cannot extract to \\\"%s...\\\", destination directory is too long for filesystem\", tmp);\n\t\tefree(tmp);\n\t\treturn;\n\t}\n\n\tif (php_stream_stat_path(pathto, &ssb) < 0) {\n\t\tret = php_stream_mkdir(pathto, 0777, PHP_STREAM_MKDIR_RECURSIVE, NULL);\n\t\tif (!ret) {\n\t\t\tzend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC,\n\t\t\t\t\"Unable to create path \\\"%s\\\" for extraction\", pathto);\n\t\t\treturn;\n\t\t}\n\t} else if (!(ssb.sb.st_mode & S_IFDIR)) {\n\t\tzend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC,\n\t\t\t\"Unable to use path \\\"%s\\\" for extraction, it is a file, must be a directory\", pathto);\n\t\treturn;\n\t}\n\n\tif (zval_files) {\n\t\tswitch (Z_TYPE_P(zval_files)) {\n\t\t\tcase IS_NULL:\n\t\t\t\tgoto all_files;\n\t\t\tcase IS_STRING:\n\t\t\t\tfilename = Z_STRVAL_P(zval_files);\n\t\t\t\tfilename_len = Z_STRLEN_P(zval_files);\n\t\t\t\tbreak;\n\t\t\tcase IS_ARRAY:\n\t\t\t\tnelems = zend_hash_num_elements(Z_ARRVAL_P(zval_files));\n\t\t\t\tif (nelems == 0 ) {\n\t\t\t\t\tRETURN_FALSE;\n\t\t\t\t}\n\t\t\t\tfor (i = 0; i < nelems; i++) {\n\t\t\t\t\tzval **zval_file;\n\t\t\t\t\tif (zend_hash_index_find(Z_ARRVAL_P(zval_files), i, (void **) &zval_file) == SUCCESS) {\n\t\t\t\t\t\tswitch (Z_TYPE_PP(zval_file)) {\n\t\t\t\t\t\t\tcase IS_STRING:\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tzend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC,\n\t\t\t\t\t\t\t\t\t\"Invalid argument, array of filenames to extract contains non-string value\");\n\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (FAILURE == zend_hash_find(&phar_obj->arc.archive->manifest, Z_STRVAL_PP(zval_file), Z_STRLEN_PP(zval_file), (void **)&entry)) {\n\t\t\t\t\t\t\tzend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC,\n\t\t\t\t\t\t\t\t\"Phar Error: attempted to extract non-existent file \\\"%s\\\" from phar \\\"%s\\\"\", Z_STRVAL_PP(zval_file), phar_obj->arc.archive->fname);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error TSRMLS_CC)) {\n\t\t\t\t\t\t\tzend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC,\n\t\t\t\t\t\t\t\t\"Extraction from phar \\\"%s\\\" failed: %s\", phar_obj->arc.archive->fname, error);\n\t\t\t\t\t\t\tefree(error);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tRETURN_TRUE;\n\t\t\tdefault:\n\t\t\t\tzend_throw_exception_ex(spl_ce_InvalidArgumentException, 0 TSRMLS_CC,\n\t\t\t\t\t\"Invalid argument, expected a filename (string) or array of filenames\");\n\t\t\t\treturn;\n\t\t}\n\n\t\tif (FAILURE == zend_hash_find(&phar_obj->arc.archive->manifest, filename, filename_len, (void **)&entry)) {\n\t\t\tzend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC,\n\t\t\t\t\"Phar Error: attempted to extract non-existent file \\\"%s\\\" from phar \\\"%s\\\"\", filename, phar_obj->arc.archive->fname);\n\t\t\treturn;\n\t\t}\n\n\t\tif (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error TSRMLS_CC)) {\n\t\t\tzend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC,\n\t\t\t\t\"Extraction from phar \\\"%s\\\" failed: %s\", phar_obj->arc.archive->fname, error);\n\t\t\tefree(error);\n\t\t\treturn;\n\t\t}\n\t} else {\n\t\tphar_archive_data *phar;\nall_files:\n\t\tphar = phar_obj->arc.archive;\n\t\t\/* Extract all files *\/\n\t\tif (!zend_hash_num_elements(&(phar->manifest))) {\n\t\t\tRETURN_TRUE;\n\t\t}\n\n\t\tfor (zend_hash_internal_pointer_reset(&phar->manifest);\n\t\tzend_hash_has_more_elements(&phar->manifest) == SUCCESS;\n\t\tzend_hash_move_forward(&phar->manifest)) {\n\n\t\t\tif (zend_hash_get_current_data(&phar->manifest, (void **)&entry) == FAILURE) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (FAILURE == phar_extract_file(overwrite, entry, pathto, pathto_len, &error TSRMLS_CC)) {\n\t\t\t\tzend_throw_exception_ex(phar_ce_PharException, 0 TSRMLS_CC,\n\t\t\t\t\t\"Extraction from phar \\\"%s\\\" failed: %s\", phar->fname, error);\n\t\t\t\tefree(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t}\n\tRETURN_TRUE;\n}","target":0,"code_token_length":1361,"total_token_length":1692,"max_tokens_setting":2048} +{"idx":509560,"func":"static int tls_construct_cke_gost(SSL *s, unsigned char **p, int *len, int *al)\n{\n#ifndef OPENSSL_NO_GOST\n \/* GOST key exchange message creation *\/\n EVP_PKEY_CTX *pkey_ctx = NULL;\n X509 *peer_cert;\n size_t msglen;\n unsigned int md_len;\n unsigned char shared_ukm[32], tmp[256];\n EVP_MD_CTX *ukm_hash = NULL;\n int dgst_nid = NID_id_GostR3411_94;\n unsigned char *pms = NULL;\n size_t pmslen = 0;\n\n if ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aGOST12) != 0)\n dgst_nid = NID_id_GostR3411_2012_256;\n\n \/*\n * Get server sertificate PKEY and create ctx from it\n *\/\n peer_cert = s->session->peer;\n if (!peer_cert) {\n *al = SSL_AD_HANDSHAKE_FAILURE;\n SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST,\n SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);\n return 0;\n }\n\n pkey_ctx = EVP_PKEY_CTX_new(X509_get0_pubkey(peer_cert), NULL);\n if (pkey_ctx == NULL) {\n *al = SSL_AD_INTERNAL_ERROR;\n SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_MALLOC_FAILURE);\n return 0;\n }\n \/*\n * If we have send a certificate, and certificate key\n * parameters match those of server certificate, use\n * certificate key for key exchange\n *\/\n\n \/* Otherwise, generate ephemeral key pair *\/\n pmslen = 32;\n pms = OPENSSL_malloc(pmslen);\n if (pms == NULL) {\n *al = SSL_AD_INTERNAL_ERROR;\n SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_MALLOC_FAILURE);\n goto err;\n }\n\n if (EVP_PKEY_encrypt_init(pkey_ctx) <= 0\n \/* Generate session key *\/\n || RAND_bytes(pms, pmslen) <= 0) {\n *al = SSL_AD_INTERNAL_ERROR;\n SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_INTERNAL_ERROR);\n goto err;\n };\n \/*\n * Compute shared IV and store it in algorithm-specific context\n * data\n *\/\n ukm_hash = EVP_MD_CTX_new();\n if (ukm_hash == NULL\n || EVP_DigestInit(ukm_hash, EVP_get_digestbynid(dgst_nid)) <= 0\n || EVP_DigestUpdate(ukm_hash, s->s3->client_random,\n SSL3_RANDOM_SIZE) <= 0\n || EVP_DigestUpdate(ukm_hash, s->s3->server_random,\n SSL3_RANDOM_SIZE) <= 0\n || EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len) <= 0) {\n *al = SSL_AD_INTERNAL_ERROR;\n SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_INTERNAL_ERROR);\n goto err;\n }\n EVP_MD_CTX_free(ukm_hash);\n ukm_hash = NULL;\n if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,\n EVP_PKEY_CTRL_SET_IV, 8, shared_ukm) < 0) {\n *al = SSL_AD_INTERNAL_ERROR;\n SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, SSL_R_LIBRARY_BUG);\n goto err;\n }\n \/* Make GOST keytransport blob message *\/\n \/*\n * Encapsulate it into sequence\n *\/\n *((*p)++) = V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED;\n msglen = 255;\n if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, pms, pmslen) <= 0) {\n *al = SSL_AD_INTERNAL_ERROR;\n SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, SSL_R_LIBRARY_BUG);\n goto err;\n }\n if (msglen >= 0x80) {\n *((*p)++) = 0x81;\n *((*p)++) = msglen & 0xff;\n *len = msglen + 3;\n } else {\n *((*p)++) = msglen & 0xff;\n *len = msglen + 2;\n }\n memcpy(*p, tmp, msglen);\n\n EVP_PKEY_CTX_free(pkey_ctx);\n s->s3->tmp.pms = pms;\n s->s3->tmp.pmslen = pmslen;\n\n return 1;\n err:\n EVP_PKEY_CTX_free(pkey_ctx);\n OPENSSL_clear_free(pms, pmslen);\n EVP_MD_CTX_free(ukm_hash);\n return 0;\n#else\n SSLerr(SSL_F_TLS_CONSTRUCT_CKE_GOST, ERR_R_INTERNAL_ERROR);\n *al = SSL_AD_INTERNAL_ERROR;\n return 0;\n#endif\n}","target":0,"code_token_length":1133,"total_token_length":1464,"max_tokens_setting":2048} +{"idx":446500,"func":"virDomainHostdevSubsysSCSIHostDefParseXML(xmlNodePtr sourcenode,\n virDomainHostdevSubsysSCSIPtr scsisrc)\n{\n bool got_address = false, got_adapter = false;\n xmlNodePtr cur;\n virDomainHostdevSubsysSCSIHostPtr scsihostsrc = &scsisrc->u.host;\n g_autofree char *bus = NULL;\n g_autofree char *target = NULL;\n g_autofree char *unit = NULL;\n\n cur = sourcenode->children;\n while (cur != NULL) {\n if (cur->type == XML_ELEMENT_NODE) {\n if (virXMLNodeNameEqual(cur, \"address\")) {\n if (got_address) {\n virReportError(VIR_ERR_XML_ERROR, \"%s\",\n _(\"more than one source addresses is \"\n \"specified for scsi hostdev\"));\n return -1;\n }\n\n if (!(bus = virXMLPropString(cur, \"bus\")) ||\n !(target = virXMLPropString(cur, \"target\")) ||\n !(unit = virXMLPropString(cur, \"unit\"))) {\n virReportError(VIR_ERR_XML_ERROR, \"%s\",\n _(\"'bus', 'target', and 'unit' must be specified \"\n \"for scsi hostdev source address\"));\n return -1;\n }\n\n if (virStrToLong_uip(bus, NULL, 0, &scsihostsrc->bus) < 0) {\n virReportError(VIR_ERR_INTERNAL_ERROR,\n _(\"cannot parse bus '%s'\"), bus);\n return -1;\n }\n\n if (virStrToLong_uip(target, NULL, 0,\n &scsihostsrc->target) < 0) {\n virReportError(VIR_ERR_INTERNAL_ERROR,\n _(\"cannot parse target '%s'\"), target);\n return -1;\n }\n\n if (virStrToLong_ullp(unit, NULL, 0, &scsihostsrc->unit) < 0) {\n virReportError(VIR_ERR_INTERNAL_ERROR,\n _(\"cannot parse unit '%s'\"), unit);\n return -1;\n }\n\n got_address = true;\n } else if (virXMLNodeNameEqual(cur, \"adapter\")) {\n if (got_adapter) {\n virReportError(VIR_ERR_XML_ERROR, \"%s\",\n _(\"more than one adapters is specified \"\n \"for scsi hostdev source\"));\n return -1;\n }\n if (!(scsihostsrc->adapter = virXMLPropString(cur, \"name\"))) {\n virReportError(VIR_ERR_XML_ERROR, \"%s\",\n _(\"'adapter' must be specified for scsi hostdev source\"));\n return -1;\n }\n\n got_adapter = true;\n } else {\n virReportError(VIR_ERR_XML_ERROR,\n _(\"unsupported element '%s' of scsi hostdev source\"),\n cur->name);\n return -1;\n }\n }\n cur = cur->next;\n }\n\n if (!got_address || !got_adapter) {\n virReportError(VIR_ERR_XML_ERROR, \"%s\",\n _(\"'adapter' and 'address' must be specified for scsi \"\n \"hostdev source\"));\n return -1;\n }\n\n return 0;\n}","target":0,"code_token_length":699,"total_token_length":1030,"max_tokens_setting":2048} +{"idx":493241,"func":"transformIndexConstraints(CreateStmtContext *cxt)\n{\n\tIndexStmt *index;\n\tList\t *indexlist = NIL;\n\tList\t *finalindexlist = NIL;\n\tListCell *lc;\n\n\t\/*\n\t * Run through the constraints that need to generate an index. For PRIMARY\n\t * KEY, mark each column as NOT NULL and create an index. For UNIQUE or\n\t * EXCLUDE, create an index as for PRIMARY KEY, but do not insist on NOT\n\t * NULL.\n\t *\/\n\tforeach(lc, cxt->ixconstraints)\n\t{\n\t\tConstraint *constraint = lfirst_node(Constraint, lc);\n\n\t\tAssert(constraint->contype == CONSTR_PRIMARY ||\n\t\t\t constraint->contype == CONSTR_UNIQUE ||\n\t\t\t constraint->contype == CONSTR_EXCLUSION);\n\n\t\tindex = transformIndexConstraint(constraint, cxt);\n\n\t\tindexlist = lappend(indexlist, index);\n\t}\n\n\t\/*\n\t * Scan the index list and remove any redundant index specifications. This\n\t * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A\n\t * strict reading of SQL would suggest raising an error instead, but that\n\t * strikes me as too anal-retentive. - tgl 2001-02-14\n\t *\n\t * XXX in ALTER TABLE case, it'd be nice to look for duplicate\n\t * pre-existing indexes, too.\n\t *\/\n\tif (cxt->pkey != NULL)\n\t{\n\t\t\/* Make sure we keep the PKEY index in preference to others... *\/\n\t\tfinalindexlist = list_make1(cxt->pkey);\n\t}\n\n\tforeach(lc, indexlist)\n\t{\n\t\tbool\t\tkeep = true;\n\t\tListCell *k;\n\n\t\tindex = lfirst(lc);\n\n\t\t\/* if it's pkey, it's already in finalindexlist *\/\n\t\tif (index == cxt->pkey)\n\t\t\tcontinue;\n\n\t\tforeach(k, finalindexlist)\n\t\t{\n\t\t\tIndexStmt *priorindex = lfirst(k);\n\n\t\t\tif (equal(index->indexParams, priorindex->indexParams) &&\n\t\t\t\tequal(index->indexIncludingParams, priorindex->indexIncludingParams) &&\n\t\t\t\tequal(index->whereClause, priorindex->whereClause) &&\n\t\t\t\tequal(index->excludeOpNames, priorindex->excludeOpNames) &&\n\t\t\t\tstrcmp(index->accessMethod, priorindex->accessMethod) == 0 &&\n\t\t\t\tindex->deferrable == priorindex->deferrable &&\n\t\t\t\tindex->initdeferred == priorindex->initdeferred)\n\t\t\t{\n\t\t\t\tpriorindex->unique |= index->unique;\n\n\t\t\t\t\/*\n\t\t\t\t * If the prior index is as yet unnamed, and this one is\n\t\t\t\t * named, then transfer the name to the prior index. This\n\t\t\t\t * ensures that if we have named and unnamed constraints,\n\t\t\t\t * we'll use (at least one of) the names for the index.\n\t\t\t\t *\/\n\t\t\t\tif (priorindex->idxname == NULL)\n\t\t\t\t\tpriorindex->idxname = index->idxname;\n\t\t\t\tkeep = false;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (keep)\n\t\t\tfinalindexlist = lappend(finalindexlist, index);\n\t}\n\n\t\/*\n\t * Now append all the IndexStmts to cxt->alist. If we generated an ALTER\n\t * TABLE SET NOT NULL statement to support a primary key, it's already in\n\t * cxt->alist.\n\t *\/\n\tcxt->alist = list_concat(cxt->alist, finalindexlist);\n}","target":0,"code_token_length":744,"total_token_length":1075,"max_tokens_setting":2048} +{"idx":376904,"func":"static int check_refcounts_l2(BlockDriverState *bs, BdrvCheckResult *res,\n uint16_t *refcount_table, int refcount_table_size, int64_t l2_offset,\n int flags)\n{\n BDRVQcowState *s = bs->opaque;\n uint64_t *l2_table, l2_entry;\n uint64_t next_contiguous_offset = 0;\n int i, l2_size, nb_csectors;\n\n \/* Read L2 table from disk *\/\n l2_size = s->l2_size * sizeof(uint64_t);\n l2_table = g_malloc(l2_size);\n\n if (bdrv_pread(bs->file, l2_offset, l2_table, l2_size) != l2_size)\n goto fail;\n\n \/* Do the actual checks *\/\n for(i = 0; i < s->l2_size; i++) {\n l2_entry = be64_to_cpu(l2_table[i]);\n\n switch (qcow2_get_cluster_type(l2_entry)) {\n case QCOW2_CLUSTER_COMPRESSED:\n \/* Compressed clusters don't have QCOW_OFLAG_COPIED *\/\n if (l2_entry & QCOW_OFLAG_COPIED) {\n fprintf(stderr, \"ERROR: cluster %\" PRId64 \": \"\n \"copied flag must never be set for compressed \"\n \"clusters\\n\", l2_entry >> s->cluster_bits);\n l2_entry &= ~QCOW_OFLAG_COPIED;\n res->corruptions++;\n }\n\n \/* Mark cluster as used *\/\n nb_csectors = ((l2_entry >> s->csize_shift) &\n s->csize_mask) + 1;\n l2_entry &= s->cluster_offset_mask;\n inc_refcounts(bs, res, refcount_table, refcount_table_size,\n l2_entry & ~511, nb_csectors * 512);\n\n if (flags & CHECK_FRAG_INFO) {\n res->bfi.allocated_clusters++;\n res->bfi.compressed_clusters++;\n\n \/* Compressed clusters are fragmented by nature. Since they\n * take up sub-sector space but we only have sector granularity\n * I\/O we need to re-read the same sectors even for adjacent\n * compressed clusters.\n *\/\n res->bfi.fragmented_clusters++;\n }\n break;\n\n case QCOW2_CLUSTER_ZERO:\n if ((l2_entry & L2E_OFFSET_MASK) == 0) {\n break;\n }\n \/* fall through *\/\n\n case QCOW2_CLUSTER_NORMAL:\n {\n uint64_t offset = l2_entry & L2E_OFFSET_MASK;\n\n if (flags & CHECK_FRAG_INFO) {\n res->bfi.allocated_clusters++;\n if (next_contiguous_offset &&\n offset != next_contiguous_offset) {\n res->bfi.fragmented_clusters++;\n }\n next_contiguous_offset = offset + s->cluster_size;\n }\n\n \/* Mark cluster as used *\/\n inc_refcounts(bs, res, refcount_table,refcount_table_size,\n offset, s->cluster_size);\n\n \/* Correct offsets are cluster aligned *\/\n if (offset_into_cluster(s, offset)) {\n fprintf(stderr, \"ERROR offset=%\" PRIx64 \": Cluster is not \"\n \"properly aligned; L2 entry corrupted.\\n\", offset);\n res->corruptions++;\n }\n break;\n }\n\n case QCOW2_CLUSTER_UNALLOCATED:\n break;\n\n default:\n abort();\n }\n }\n\n g_free(l2_table);\n return 0;\n\nfail:\n fprintf(stderr, \"ERROR: I\/O error in check_refcounts_l2\\n\");\n g_free(l2_table);\n return -EIO;\n}","target":0,"code_token_length":800,"total_token_length":1131,"max_tokens_setting":2048} +{"idx":336788,"func":"static av_cold int alac_encode_init(AVCodecContext *avctx)\n\n{\n\n AlacEncodeContext *s = avctx->priv_data;\n\n int ret;\n\n uint8_t *alac_extradata;\n\n\n\n avctx->frame_size = s->frame_size = DEFAULT_FRAME_SIZE;\n\n\n\n if (avctx->sample_fmt != AV_SAMPLE_FMT_S16) {\n\n av_log(avctx, AV_LOG_ERROR, \"only pcm_s16 input samples are supported\\n\");\n\n return -1;\n\n }\n\n\n\n \/* TODO: Correctly implement multi-channel ALAC.\n\n It is similar to multi-channel AAC, in that it has a series of\n\n single-channel (SCE), channel-pair (CPE), and LFE elements. *\/\n\n if (avctx->channels > 2) {\n\n av_log(avctx, AV_LOG_ERROR, \"only mono or stereo input is currently supported\\n\");\n\n return AVERROR_PATCHWELCOME;\n\n }\n\n\n\n \/\/ Set default compression level\n\n if (avctx->compression_level == FF_COMPRESSION_DEFAULT)\n\n s->compression_level = 2;\n\n else\n\n s->compression_level = av_clip(avctx->compression_level, 0, 2);\n\n\n\n \/\/ Initialize default Rice parameters\n\n s->rc.history_mult = 40;\n\n s->rc.initial_history = 10;\n\n s->rc.k_modifier = 14;\n\n s->rc.rice_modifier = 4;\n\n\n\n s->max_coded_frame_size = get_max_frame_size(avctx->frame_size,\n\n avctx->channels,\n\n DEFAULT_SAMPLE_SIZE);\n\n\n\n \/\/ FIXME: consider wasted_bytes\n\n s->write_sample_size = DEFAULT_SAMPLE_SIZE + avctx->channels - 1;\n\n\n\n avctx->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + FF_INPUT_BUFFER_PADDING_SIZE);\n\n if (!avctx->extradata) {\n\n ret = AVERROR(ENOMEM);\n\n goto error;\n\n }\n\n avctx->extradata_size = ALAC_EXTRADATA_SIZE;\n\n\n\n alac_extradata = avctx->extradata;\n\n AV_WB32(alac_extradata, ALAC_EXTRADATA_SIZE);\n\n AV_WB32(alac_extradata+4, MKBETAG('a','l','a','c'));\n\n AV_WB32(alac_extradata+12, avctx->frame_size);\n\n AV_WB8 (alac_extradata+17, DEFAULT_SAMPLE_SIZE);\n\n AV_WB8 (alac_extradata+21, avctx->channels);\n\n AV_WB32(alac_extradata+24, s->max_coded_frame_size);\n\n AV_WB32(alac_extradata+28,\n\n avctx->sample_rate * avctx->channels * DEFAULT_SAMPLE_SIZE); \/\/ average bitrate\n\n AV_WB32(alac_extradata+32, avctx->sample_rate);\n\n\n\n \/\/ Set relevant extradata fields\n\n if (s->compression_level > 0) {\n\n AV_WB8(alac_extradata+18, s->rc.history_mult);\n\n AV_WB8(alac_extradata+19, s->rc.initial_history);\n\n AV_WB8(alac_extradata+20, s->rc.k_modifier);\n\n }\n\n\n\n s->min_prediction_order = DEFAULT_MIN_PRED_ORDER;\n\n if (avctx->min_prediction_order >= 0) {\n\n if (avctx->min_prediction_order < MIN_LPC_ORDER ||\n\n avctx->min_prediction_order > ALAC_MAX_LPC_ORDER) {\n\n av_log(avctx, AV_LOG_ERROR, \"invalid min prediction order: %d\\n\",\n\n avctx->min_prediction_order);\n\n ret = AVERROR(EINVAL);\n\n goto error;\n\n }\n\n\n\n s->min_prediction_order = avctx->min_prediction_order;\n\n }\n\n\n\n s->max_prediction_order = DEFAULT_MAX_PRED_ORDER;\n\n if (avctx->max_prediction_order >= 0) {\n\n if (avctx->max_prediction_order < MIN_LPC_ORDER ||\n\n avctx->max_prediction_order > ALAC_MAX_LPC_ORDER) {\n\n av_log(avctx, AV_LOG_ERROR, \"invalid max prediction order: %d\\n\",\n\n avctx->max_prediction_order);\n\n ret = AVERROR(EINVAL);\n\n goto error;\n\n }\n\n\n\n s->max_prediction_order = avctx->max_prediction_order;\n\n }\n\n\n\n if (s->max_prediction_order < s->min_prediction_order) {\n\n av_log(avctx, AV_LOG_ERROR,\n\n \"invalid prediction orders: min=%d max=%d\\n\",\n\n s->min_prediction_order, s->max_prediction_order);\n\n ret = AVERROR(EINVAL);\n\n goto error;\n\n }\n\n\n\n avctx->coded_frame = avcodec_alloc_frame();\n\n if (!avctx->coded_frame) {\n\n ret = AVERROR(ENOMEM);\n\n goto error;\n\n }\n\n\n\n s->avctx = avctx;\n\n\n\n if ((ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,\n\n s->max_prediction_order,\n\n FF_LPC_TYPE_LEVINSON)) < 0) {\n\n goto error;\n\n }\n\n\n\n return 0;\n\nerror:\n\n alac_encode_close(avctx);\n\n return ret;\n\n}\n","target":0,"code_token_length":1124,"total_token_length":1455,"max_tokens_setting":2048} +{"idx":335003,"func":"static void rpza_decode_stream(RpzaContext *s)\n\n{\n\n int width = s->avctx->width;\n\n int stride = s->frame.linesize[0] \/ 2;\n\n int row_inc = stride - 4;\n\n int stream_ptr = 0;\n\n int chunk_size;\n\n unsigned char opcode;\n\n int n_blocks;\n\n unsigned short colorA = 0, colorB;\n\n unsigned short color4[4];\n\n unsigned char index, idx;\n\n unsigned short ta, tb;\n\n unsigned short *pixels = (unsigned short *)s->frame.data[0];\n\n\n\n int row_ptr = 0;\n\n int pixel_ptr = 0;\n\n int block_ptr;\n\n int pixel_x, pixel_y;\n\n int total_blocks;\n\n\n\n \/* First byte is always 0xe1. Warn if it's different *\/\n\n if (s->buf[stream_ptr] != 0xe1)\n\n av_log(s->avctx, AV_LOG_ERROR, \"First chunk byte is 0x%02x instead of 0xe1\\n\",\n\n s->buf[stream_ptr]);\n\n\n\n \/* Get chunk size, ingnoring first byte *\/\n\n chunk_size = AV_RB32(&s->buf[stream_ptr]) & 0x00FFFFFF;\n\n stream_ptr += 4;\n\n\n\n \/* If length mismatch use size from MOV file and try to decode anyway *\/\n\n if (chunk_size != s->size)\n\n av_log(s->avctx, AV_LOG_ERROR, \"MOV chunk size != encoded chunk size; using MOV chunk size\\n\");\n\n\n\n chunk_size = s->size;\n\n\n\n \/* Number of 4x4 blocks in frame. *\/\n\n total_blocks = ((s->avctx->width + 3) \/ 4) * ((s->avctx->height + 3) \/ 4);\n\n\n\n \/* Process chunk data *\/\n\n while (stream_ptr < chunk_size) {\n\n opcode = s->buf[stream_ptr++]; \/* Get opcode *\/\n\n\n\n n_blocks = (opcode & 0x1f) + 1; \/* Extract block counter from opcode *\/\n\n\n\n \/* If opcode MSbit is 0, we need more data to decide what to do *\/\n\n if ((opcode & 0x80) == 0) {\n\n colorA = (opcode << 8) | (s->buf[stream_ptr++]);\n\n opcode = 0;\n\n if ((s->buf[stream_ptr] & 0x80) != 0) {\n\n \/* Must behave as opcode 110xxxxx, using colorA computed\n\n * above. Use fake opcode 0x20 to enter switch block at\n\n * the right place *\/\n\n opcode = 0x20;\n\n n_blocks = 1;\n\n }\n\n }\n\n\n\n switch (opcode & 0xe0) {\n\n\n\n \/* Skip blocks *\/\n\n case 0x80:\n\n while (n_blocks--) {\n\n ADVANCE_BLOCK();\n\n }\n\n break;\n\n\n\n \/* Fill blocks with one color *\/\n\n case 0xa0:\n\n colorA = AV_RB16 (&s->buf[stream_ptr]);\n\n stream_ptr += 2;\n\n while (n_blocks--) {\n\n block_ptr = row_ptr + pixel_ptr;\n\n for (pixel_y = 0; pixel_y < 4; pixel_y++) {\n\n for (pixel_x = 0; pixel_x < 4; pixel_x++){\n\n pixels[block_ptr] = colorA;\n\n block_ptr++;\n\n }\n\n block_ptr += row_inc;\n\n }\n\n ADVANCE_BLOCK();\n\n }\n\n break;\n\n\n\n \/* Fill blocks with 4 colors *\/\n\n case 0xc0:\n\n colorA = AV_RB16 (&s->buf[stream_ptr]);\n\n stream_ptr += 2;\n\n case 0x20:\n\n colorB = AV_RB16 (&s->buf[stream_ptr]);\n\n stream_ptr += 2;\n\n\n\n \/* sort out the colors *\/\n\n color4[0] = colorB;\n\n color4[1] = 0;\n\n color4[2] = 0;\n\n color4[3] = colorA;\n\n\n\n \/* red components *\/\n\n ta = (colorA >> 10) & 0x1F;\n\n tb = (colorB >> 10) & 0x1F;\n\n color4[1] |= ((11 * ta + 21 * tb) >> 5) << 10;\n\n color4[2] |= ((21 * ta + 11 * tb) >> 5) << 10;\n\n\n\n \/* green components *\/\n\n ta = (colorA >> 5) & 0x1F;\n\n tb = (colorB >> 5) & 0x1F;\n\n color4[1] |= ((11 * ta + 21 * tb) >> 5) << 5;\n\n color4[2] |= ((21 * ta + 11 * tb) >> 5) << 5;\n\n\n\n \/* blue components *\/\n\n ta = colorA & 0x1F;\n\n tb = colorB & 0x1F;\n\n color4[1] |= ((11 * ta + 21 * tb) >> 5);\n\n color4[2] |= ((21 * ta + 11 * tb) >> 5);\n\n\n\n\n\n while (n_blocks--) {\n\n block_ptr = row_ptr + pixel_ptr;\n\n for (pixel_y = 0; pixel_y < 4; pixel_y++) {\n\n index = s->buf[stream_ptr++];\n\n for (pixel_x = 0; pixel_x < 4; pixel_x++){\n\n idx = (index >> (2 * (3 - pixel_x))) & 0x03;\n\n pixels[block_ptr] = color4[idx];\n\n block_ptr++;\n\n }\n\n block_ptr += row_inc;\n\n }\n\n ADVANCE_BLOCK();\n\n }\n\n break;\n\n\n\n \/* Fill block with 16 colors *\/\n\n case 0x00:\n\n if (s->size - stream_ptr < 16)\n\n\n block_ptr = row_ptr + pixel_ptr;\n\n for (pixel_y = 0; pixel_y < 4; pixel_y++) {\n\n for (pixel_x = 0; pixel_x < 4; pixel_x++){\n\n \/* We already have color of upper left pixel *\/\n\n if ((pixel_y != 0) || (pixel_x !=0)) {\n\n colorA = AV_RB16 (&s->buf[stream_ptr]);\n\n stream_ptr += 2;\n\n }\n\n pixels[block_ptr] = colorA;\n\n block_ptr++;\n\n }\n\n block_ptr += row_inc;\n\n }\n\n ADVANCE_BLOCK();\n\n break;\n\n\n\n \/* Unknown opcode *\/\n\n default:\n\n av_log(s->avctx, AV_LOG_ERROR, \"Unknown opcode %d in rpza chunk.\"\n\n \" Skip remaining %d bytes of chunk data.\\n\", opcode,\n\n chunk_size - stream_ptr);\n\n\n } \/* Opcode switch *\/\n\n }\n\n}","target":1,"code_token_length":1486,"total_token_length":1817,"max_tokens_setting":2048} +{"idx":28877,"func":"static void truespeech_read_frame ( TSContext * dec , const uint8_t * input ) {\n GetBitContext gb ;\n dec -> dsp . bswap_buf ( ( uint32_t * ) dec -> buffer , ( const uint32_t * ) input , 8 ) ;\n init_get_bits ( & gb , dec -> buffer , 32 * 8 ) ;\n dec -> vector [ 7 ] = ts_codebook [ 7 ] [ get_bits ( & gb , 3 ) ] ;\n dec -> vector [ 6 ] = ts_codebook [ 6 ] [ get_bits ( & gb , 3 ) ] ;\n dec -> vector [ 5 ] = ts_codebook [ 5 ] [ get_bits ( & gb , 3 ) ] ;\n dec -> vector [ 4 ] = ts_codebook [ 4 ] [ get_bits ( & gb , 4 ) ] ;\n dec -> vector [ 3 ] = ts_codebook [ 3 ] [ get_bits ( & gb , 4 ) ] ;\n dec -> vector [ 2 ] = ts_codebook [ 2 ] [ get_bits ( & gb , 4 ) ] ;\n dec -> vector [ 1 ] = ts_codebook [ 1 ] [ get_bits ( & gb , 5 ) ] ;\n dec -> vector [ 0 ] = ts_codebook [ 0 ] [ get_bits ( & gb , 5 ) ] ;\n dec -> flag = get_bits1 ( & gb ) ;\n dec -> offset1 [ 0 ] = get_bits ( & gb , 4 ) << 4 ;\n dec -> offset2 [ 3 ] = get_bits ( & gb , 7 ) ;\n dec -> offset2 [ 2 ] = get_bits ( & gb , 7 ) ;\n dec -> offset2 [ 1 ] = get_bits ( & gb , 7 ) ;\n dec -> offset2 [ 0 ] = get_bits ( & gb , 7 ) ;\n dec -> offset1 [ 1 ] = get_bits ( & gb , 4 ) ;\n dec -> pulseval [ 1 ] = get_bits ( & gb , 14 ) ;\n dec -> pulseval [ 0 ] = get_bits ( & gb , 14 ) ;\n dec -> offset1 [ 1 ] |= get_bits ( & gb , 4 ) << 4 ;\n dec -> pulseval [ 3 ] = get_bits ( & gb , 14 ) ;\n dec -> pulseval [ 2 ] = get_bits ( & gb , 14 ) ;\n dec -> offset1 [ 0 ] |= get_bits1 ( & gb ) ;\n dec -> pulsepos [ 0 ] = get_bits_long ( & gb , 27 ) ;\n dec -> pulseoff [ 0 ] = get_bits ( & gb , 4 ) ;\n dec -> offset1 [ 0 ] |= get_bits1 ( & gb ) << 1 ;\n dec -> pulsepos [ 1 ] = get_bits_long ( & gb , 27 ) ;\n dec -> pulseoff [ 1 ] = get_bits ( & gb , 4 ) ;\n dec -> offset1 [ 0 ] |= get_bits1 ( & gb ) << 2 ;\n dec -> pulsepos [ 2 ] = get_bits_long ( & gb , 27 ) ;\n dec -> pulseoff [ 2 ] = get_bits ( & gb , 4 ) ;\n dec -> offset1 [ 0 ] |= get_bits1 ( & gb ) << 3 ;\n dec -> pulsepos [ 3 ] = get_bits_long ( & gb , 27 ) ;\n dec -> pulseoff [ 3 ] = get_bits ( & gb , 4 ) ;\n }","target":0,"code_token_length":764,"total_token_length":1095,"max_tokens_setting":2048} +{"idx":271205,"func":"int mainloop(CLIENT *client) {\n\tstruct nbd_request request;\n\tstruct nbd_reply reply;\n\tgboolean go_on=TRUE;\n#ifdef DODBG\n\tint i = 0;\n#endif\n\tnegotiate(client->net, client, NULL, client->modern ? NEG_MODERN : (NEG_OLD | NEG_INIT));\n\tDEBUG(\"Entering request loop!\\n\");\n\treply.magic = htonl(NBD_REPLY_MAGIC);\n\treply.error = 0;\n\twhile (go_on) {\n\t\tchar buf[BUFSIZE];\n\t\tchar* p;\n\t\tsize_t len;\n\t\tsize_t currlen;\n\t\tsize_t writelen;\n\t\tuint16_t command;\n#ifdef DODBG\n\t\ti++;\n\t\tprintf(\"%d: \", i);\n#endif\n\t\treadit(client->net, &request, sizeof(request));\n\t\tif (client->transactionlogfd != -1)\n\t\t\twriteit(client->transactionlogfd, &request, sizeof(request));\n\n\t\trequest.from = ntohll(request.from);\n\t\trequest.type = ntohl(request.type);\n\t\tcommand = request.type & NBD_CMD_MASK_COMMAND;\n\t\tlen = ntohl(request.len);\n\n\t\tDEBUG(\"%s from %llu (%llu) len %u, \", getcommandname(command),\n\t\t\t\t(unsigned long long)request.from,\n\t\t\t\t(unsigned long long)request.from \/ 512, len);\n\n\t\tif (request.magic != htonl(NBD_REQUEST_MAGIC))\n\t\t\terr(\"Not enough magic.\");\n\n\t\tmemcpy(reply.handle, request.handle, sizeof(reply.handle));\n\n\t\tif ((command==NBD_CMD_WRITE) || (command==NBD_CMD_READ)) {\n\t\t\tif (request.from + len < request.from) { \/\/ 64 bit overflow!!\n\t\t\t\tDEBUG(\"[Number too large!]\");\n\t\t\t\tERROR(client, reply, EINVAL);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (((off_t)request.from + len) > client->exportsize) {\n\t\t\t\tDEBUG(\"[RANGE!]\");\n\t\t\t\tERROR(client, reply, EINVAL);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tcurrlen = len;\n\t\t\tif (currlen > BUFSIZE - sizeof(struct nbd_reply)) {\n\t\t\t\tcurrlen = BUFSIZE - sizeof(struct nbd_reply);\n\t\t\t\tif(!logged_oversized) {\n\t\t\t\t\tmsg(LOG_DEBUG, \"oversized request (this is not a problem)\");\n\t\t\t\t\tlogged_oversized = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tswitch (command) {\n\n\t\tcase NBD_CMD_DISC:\n\t\t\tmsg(LOG_INFO, \"Disconnect request received.\");\n \tif (client->server->flags & F_COPYONWRITE) { \n\t\t\t\tif (client->difmap) g_free(client->difmap) ;\n \t\tclose(client->difffile);\n\t\t\t\tunlink(client->difffilename);\n\t\t\t\tfree(client->difffilename);\n\t\t\t}\n\t\t\tgo_on=FALSE;\n\t\t\tcontinue;\n\n\t\tcase NBD_CMD_WRITE:\n\t\t\tDEBUG(\"wr: net->buf, \");\n\t\t\twhile(len > 0) {\n\t\t\t\treadit(client->net, buf, currlen);\n\t\t\t\tDEBUG(\"buf->exp, \");\n\t\t\t\tif ((client->server->flags & F_READONLY) ||\n\t\t\t\t (client->server->flags & F_AUTOREADONLY)) {\n\t\t\t\t\tDEBUG(\"[WRITE to READONLY!]\");\n\t\t\t\t\tERROR(client, reply, EPERM);\n\t\t\t\t\tconsume(client->net, buf, len-currlen, BUFSIZE);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (expwrite(request.from, buf, currlen, client,\n\t\t\t\t\t request.type & NBD_CMD_FLAG_FUA)) {\n\t\t\t\t\tDEBUG(\"Write failed: %m\" );\n\t\t\t\t\tERROR(client, reply, errno);\n\t\t\t\t\tconsume(client->net, buf, len-currlen, BUFSIZE);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tlen -= currlen;\n\t\t\t\trequest.from += currlen;\n\t\t\t\tcurrlen = (len < BUFSIZE) ? len : BUFSIZE;\n\t\t\t}\n\t\t\tSEND(client->net, reply);\n\t\t\tDEBUG(\"OK!\\n\");\n\t\t\tcontinue;\n\n\t\tcase NBD_CMD_FLUSH:\n\t\t\tDEBUG(\"fl: \");\n\t\t\tif (expflush(client)) {\n\t\t\t\tDEBUG(\"Flush failed: %m\");\n\t\t\t\tERROR(client, reply, errno);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tSEND(client->net, reply);\n\t\t\tDEBUG(\"OK!\\n\");\n\t\t\tcontinue;\n\n\t\tcase NBD_CMD_READ:\n\t\t\tDEBUG(\"exp->buf, \");\n\t\t\tif (client->transactionlogfd != -1)\n\t\t\t\twriteit(client->transactionlogfd, &reply, sizeof(reply));\n\t\t\twriteit(client->net, &reply, sizeof(reply));\n\t\t\tp = buf;\n\t\t\twritelen = currlen;\n\t\t\twhile(len > 0) {\n\t\t\t\tif (expread(request.from, p, currlen, client)) {\n\t\t\t\t\tDEBUG(\"Read failed: %m\");\n\t\t\t\t\tERROR(client, reply, errno);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tDEBUG(\"buf->net, \");\n\t\t\t\twriteit(client->net, buf, writelen);\n\t\t\t\tlen -= currlen;\n\t\t\t\trequest.from += currlen;\n\t\t\t\tcurrlen = (len < BUFSIZE) ? len : BUFSIZE;\n\t\t\t\tp = buf;\n\t\t\t\twritelen = currlen;\n\t\t\t}\n\t\t\tDEBUG(\"OK!\\n\");\n\t\t\tcontinue;\n\n\t\tcase NBD_CMD_TRIM:\n\t\t\t\/* The kernel module sets discard_zeroes_data == 0,\n\t\t\t * so it is okay to do nothing. *\/\n\t\t\tif (exptrim(&request, client)) {\n\t\t\t\tDEBUG(\"Trim failed: %m\");\n\t\t\t\tERROR(client, reply, errno);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tSEND(client->net, reply);\n\t\t\tcontinue;\n\n\t\tdefault:\n\t\t\tDEBUG (\"Ignoring unknown command\\n\");\n\t\t\tcontinue;\n\t\t}\n\t}\n\treturn 0;\n}","target":0,"code_token_length":1169,"total_token_length":1500,"max_tokens_setting":2048} +{"idx":284659,"func":"static int AppLayerProtoDetectTest06(void)\n{\n AppLayerProtoDetectUnittestCtxBackup();\n AppLayerProtoDetectSetup();\n\n uint8_t l7data[] = \"220 Welcome to the OISF FTP server\\r\\n\";\n const char *buf;\n int r = 0;\n Flow f;\n AppProto pm_results[ALPROTO_MAX];\n AppLayerProtoDetectThreadCtx *alpd_tctx;\n\n memset(&f, 0x00, sizeof(f));\n f.protomap = FlowGetProtoMapping(IPPROTO_TCP);\n\n buf = \"HTTP\";\n AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_HTTP, buf, 4, 0, STREAM_TOCLIENT);\n buf = \"220 \";\n AppLayerProtoDetectPMRegisterPatternCS(IPPROTO_TCP, ALPROTO_FTP, buf, 4, 0, STREAM_TOCLIENT);\n\n AppLayerProtoDetectPrepareState();\n \/* AppLayerProtoDetectGetCtxThread() should be called post AppLayerProtoDetectPrepareState(), since\n * it sets internal structures which depends on the above function. *\/\n alpd_tctx = AppLayerProtoDetectGetCtxThread();\n\n if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0) {\n printf(\"alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].max_pat_id != 0\\n\");\n goto end;\n }\n if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2) {\n printf(\"alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].max_pat_id != 2\\n\");\n goto end;\n }\n\n if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL) {\n printf(\"alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[0].map != NULL\\n\");\n goto end;\n }\n if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map == NULL) {\n printf(\"alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map != NULL\\n\");\n goto end;\n }\n\n if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0]->alproto != ALPROTO_FTP) {\n printf(\"alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[0].alproto != ALPROTO_FTP\\n\");\n goto end;\n }\n if (alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1]->alproto != ALPROTO_HTTP) {\n printf(\"alpd_ctx.ctx_ipp[FLOW_PROTO_TCP].ctx_pm[1].map[1].alproto != ALPROTO_HTTP\\n\");\n goto end;\n }\n\n uint32_t cnt = AppLayerProtoDetectPMGetProto(alpd_tctx,\n &f,\n l7data, sizeof(l7data),\n STREAM_TOCLIENT,\n IPPROTO_TCP,\n pm_results);\n if (cnt != 1 && pm_results[0] != ALPROTO_FTP) {\n printf(\"cnt != 1 && pm_results[0] != AlPROTO_FTP\\n\");\n goto end;\n }\n\n r = 1;\n\n end:\n if (alpd_tctx != NULL)\n AppLayerProtoDetectDestroyCtxThread(alpd_tctx);\n AppLayerProtoDetectDeSetup();\n AppLayerProtoDetectUnittestCtxRestore();\n return r;\n}\n","target":0,"code_token_length":765,"total_token_length":1096,"max_tokens_setting":2048} +{"idx":164220,"func":"static void pcnet_transmit(PCNetState *s)\n{\n hwaddr xmit_cxda = 0;\n int count = CSR_XMTRL(s)-1;\n int add_crc = 0;\n int bcnt;\n s->xmit_pos = -1;\n\n if (!CSR_TXON(s)) {\n s->csr[0] &= ~0x0008;\n return;\n }\n\n s->tx_busy = 1;\n\n txagain:\n if (pcnet_tdte_poll(s)) {\n struct pcnet_TMD tmd;\n\n TMDLOAD(&tmd, PHYSADDR(s,CSR_CXDA(s)));\n\n#ifdef PCNET_DEBUG_TMD\n printf(\" TMDLOAD 0x%08x\\n\", PHYSADDR(s,CSR_CXDA(s)));\n PRINT_TMD(&tmd);\n#endif\n if (GET_FIELD(tmd.status, TMDS, STP)) {\n s->xmit_pos = 0;\n xmit_cxda = PHYSADDR(s,CSR_CXDA(s));\n if (BCR_SWSTYLE(s) != 1)\n add_crc = GET_FIELD(tmd.status, TMDS, ADDFCS);\n }\n if (s->lnkst == 0 &&\n (!CSR_LOOP(s) || (!CSR_INTL(s) && !BCR_TMAULOOP(s)))) {\n SET_FIELD(&tmd.misc, TMDM, LCAR, 1);\n SET_FIELD(&tmd.status, TMDS, ERR, 1);\n SET_FIELD(&tmd.status, TMDS, OWN, 0);\n s->csr[0] |= 0xa000; \/* ERR | CERR *\/\n s->xmit_pos = -1;\n goto txdone;\n }\n\n if (s->xmit_pos < 0) {\n goto txdone;\n }\n\n bcnt = 4096 - GET_FIELD(tmd.length, TMDL, BCNT);\n\n \/* if multi-tmd packet outsizes s->buffer then skip it silently.\n * Note: this is not what real hw does.\n * Last four bytes of s->buffer are used to store CRC FCS code.\n *\/\n if (s->xmit_pos + bcnt > sizeof(s->buffer) - 4) {\n s->xmit_pos = -1;\n goto txdone;\n }\n\n s->phys_mem_read(s->dma_opaque, PHYSADDR(s, tmd.tbadr),\n s->buffer + s->xmit_pos, bcnt, CSR_BSWP(s));\n s->xmit_pos += bcnt;\n \n if (!GET_FIELD(tmd.status, TMDS, ENP)) {\n goto txdone;\n }\n\n#ifdef PCNET_DEBUG\n printf(\"pcnet_transmit size=%d\\n\", s->xmit_pos);\n#endif\n if (CSR_LOOP(s)) {\n if (BCR_SWSTYLE(s) == 1)\n add_crc = !GET_FIELD(tmd.status, TMDS, NOFCS);\n s->looptest = add_crc ? PCNET_LOOPTEST_CRC : PCNET_LOOPTEST_NOCRC;\n pcnet_receive(qemu_get_queue(s->nic), s->buffer, s->xmit_pos);\n s->looptest = 0;\n } else {\n if (s->nic) {\n qemu_send_packet(qemu_get_queue(s->nic), s->buffer,\n s->xmit_pos);\n }\n }\n\n s->csr[0] &= ~0x0008; \/* clear TDMD *\/\n s->csr[4] |= 0x0004; \/* set TXSTRT *\/\n s->xmit_pos = -1;\n\n txdone:\n SET_FIELD(&tmd.status, TMDS, OWN, 0);\n TMDSTORE(&tmd, PHYSADDR(s,CSR_CXDA(s)));\n if (!CSR_TOKINTD(s) || (CSR_LTINTEN(s) && GET_FIELD(tmd.status, TMDS, LTINT)))\n s->csr[0] |= 0x0200; \/* set TINT *\/\n\n if (CSR_XMTRC(s)<=1)\n CSR_XMTRC(s) = CSR_XMTRL(s);\n else\n CSR_XMTRC(s)--;\n if (count--)\n goto txagain;\n\n } else\n if (s->xmit_pos >= 0) {\n struct pcnet_TMD tmd;\n TMDLOAD(&tmd, xmit_cxda);\n SET_FIELD(&tmd.misc, TMDM, BUFF, 1);\n SET_FIELD(&tmd.misc, TMDM, UFLO, 1);\n SET_FIELD(&tmd.status, TMDS, ERR, 1);\n SET_FIELD(&tmd.status, TMDS, OWN, 0);\n TMDSTORE(&tmd, xmit_cxda);\n s->csr[0] |= 0x0200; \/* set TINT *\/\n if (!CSR_DXSUFLO(s)) {\n s->csr[0] &= ~0x0010;\n } else\n if (count--)\n goto txagain;\n }\n\n s->tx_busy = 0;\n}\n","target":0,"code_token_length":1142,"total_token_length":1473,"max_tokens_setting":2048} +{"idx":385553,"func":"PHP_METHOD(SoapServer, addFunction)\n{\n\tsoapServicePtr service;\n\tzval *function_name, *function_copy;\n\tHashPosition pos;\n\n\tSOAP_SERVER_BEGIN_CODE();\n\n\tFETCH_THIS_SERVICE(service);\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"z\", &function_name) == FAILURE) {\n\t\treturn;\n\t}\n\n\t\/* TODO: could use zend_is_callable here *\/\n\n\tif (function_name->type == IS_ARRAY) {\n\t\tif (service->type == SOAP_FUNCTIONS) {\n\t\t\tzval **tmp_function, *function_copy;\n\n\t\t\tif (service->soap_functions.ft == NULL) {\n\t\t\t\tservice->soap_functions.functions_all = FALSE;\n\t\t\t\tservice->soap_functions.ft = emalloc(sizeof(HashTable));\n\t\t\t\tzend_hash_init(service->soap_functions.ft, zend_hash_num_elements(Z_ARRVAL_P(function_name)), NULL, ZVAL_PTR_DTOR, 0);\n\t\t\t}\n\n\t\t\tzend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(function_name), &pos);\n\t\t\twhile (zend_hash_get_current_data_ex(Z_ARRVAL_P(function_name), (void **)&tmp_function, &pos) != FAILURE) {\n\t\t\t\tchar *key;\n\t\t\t\tint key_len;\n\t\t\t\tzend_function *f;\n\n\t\t\t\tif (Z_TYPE_PP(tmp_function) != IS_STRING) {\n\t\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Tried to add a function that isn't a string\");\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tkey_len = Z_STRLEN_PP(tmp_function);\n\t\t\t\tkey = emalloc(key_len + 1);\n\t\t\t\tzend_str_tolower_copy(key, Z_STRVAL_PP(tmp_function), key_len);\n\n\t\t\t\tif (zend_hash_find(EG(function_table), key, key_len+1, (void**)&f) == FAILURE) {\n\t\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Tried to add a non existent function '%s'\", Z_STRVAL_PP(tmp_function));\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tMAKE_STD_ZVAL(function_copy);\n\t\t\t\tZVAL_STRING(function_copy, f->common.function_name, 1);\n\t\t\t\tzend_hash_update(service->soap_functions.ft, key, key_len+1, &function_copy, sizeof(zval *), NULL);\n\n\t\t\t\tefree(key);\n\t\t\t\tzend_hash_move_forward_ex(Z_ARRVAL_P(function_name), &pos);\n\t\t\t}\n\t\t}\n\t} else if (function_name->type == IS_STRING) {\n\t\tchar *key;\n\t\tint key_len;\n\t\tzend_function *f;\n\n\t\tkey_len = Z_STRLEN_P(function_name);\n\t\tkey = emalloc(key_len + 1);\n\t\tzend_str_tolower_copy(key, Z_STRVAL_P(function_name), key_len);\n\n\t\tif (zend_hash_find(EG(function_table), key, key_len+1, (void**)&f) == FAILURE) {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Tried to add a non existent function '%s'\", Z_STRVAL_P(function_name));\n\t\t\treturn;\n\t\t}\n\t\tif (service->soap_functions.ft == NULL) {\n\t\t\tservice->soap_functions.functions_all = FALSE;\n\t\t\tservice->soap_functions.ft = emalloc(sizeof(HashTable));\n\t\t\tzend_hash_init(service->soap_functions.ft, 0, NULL, ZVAL_PTR_DTOR, 0);\n\t\t}\n\n\t\tMAKE_STD_ZVAL(function_copy);\n\t\tZVAL_STRING(function_copy, f->common.function_name, 1);\n\t\tzend_hash_update(service->soap_functions.ft, key, key_len+1, &function_copy, sizeof(zval *), NULL);\n\t\tefree(key);\n\t} else if (function_name->type == IS_LONG) {\n\t\tif (Z_LVAL_P(function_name) == SOAP_FUNCTIONS_ALL) {\n\t\t\tif (service->soap_functions.ft != NULL) {\n\t\t\t\tzend_hash_destroy(service->soap_functions.ft);\n\t\t\t\tefree(service->soap_functions.ft);\n\t\t\t\tservice->soap_functions.ft = NULL;\n\t\t\t}\n\t\t\tservice->soap_functions.functions_all = TRUE;\n\t\t} else {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Invalid value passed\");\n\t\t\treturn;\n\t\t}\n\t}\n\n\tSOAP_SERVER_END_CODE();\n}","target":0,"code_token_length":877,"total_token_length":1208,"max_tokens_setting":2048} +{"idx":128454,"func":"static int net_slirp_init(NetClientState *peer, const char *model,\n\n const char *name, int restricted,\n\n const char *vnetwork, const char *vhost,\n\n const char *vhostname, const char *tftp_export,\n\n const char *bootfile, const char *vdhcp_start,\n\n const char *vnameserver, const char *smb_export,\n\n const char *vsmbserver, const char **dnssearch)\n\n{\n\n \/* default settings according to historic slirp *\/\n\n struct in_addr net = { .s_addr = htonl(0x0a000200) }; \/* 10.0.2.0 *\/\n\n struct in_addr mask = { .s_addr = htonl(0xffffff00) }; \/* 255.255.255.0 *\/\n\n struct in_addr host = { .s_addr = htonl(0x0a000202) }; \/* 10.0.2.2 *\/\n\n struct in_addr dhcp = { .s_addr = htonl(0x0a00020f) }; \/* 10.0.2.15 *\/\n\n struct in_addr dns = { .s_addr = htonl(0x0a000203) }; \/* 10.0.2.3 *\/\n\n#ifndef _WIN32\n\n struct in_addr smbsrv = { .s_addr = 0 };\n\n#endif\n\n NetClientState *nc;\n\n SlirpState *s;\n\n char buf[20];\n\n uint32_t addr;\n\n int shift;\n\n char *end;\n\n struct slirp_config_str *config;\n\n\n\n if (!tftp_export) {\n\n tftp_export = legacy_tftp_prefix;\n\n }\n\n if (!bootfile) {\n\n bootfile = legacy_bootp_filename;\n\n }\n\n\n\n if (vnetwork) {\n\n if (get_str_sep(buf, sizeof(buf), &vnetwork, '\/') < 0) {\n\n if (!inet_aton(vnetwork, &net)) {\n\n return -1;\n\n }\n\n addr = ntohl(net.s_addr);\n\n if (!(addr & 0x80000000)) {\n\n mask.s_addr = htonl(0xff000000); \/* class A *\/\n\n } else if ((addr & 0xfff00000) == 0xac100000) {\n\n mask.s_addr = htonl(0xfff00000); \/* priv. 172.16.0.0\/12 *\/\n\n } else if ((addr & 0xc0000000) == 0x80000000) {\n\n mask.s_addr = htonl(0xffff0000); \/* class B *\/\n\n } else if ((addr & 0xffff0000) == 0xc0a80000) {\n\n mask.s_addr = htonl(0xffff0000); \/* priv. 192.168.0.0\/16 *\/\n\n } else if ((addr & 0xffff0000) == 0xc6120000) {\n\n mask.s_addr = htonl(0xfffe0000); \/* tests 198.18.0.0\/15 *\/\n\n } else if ((addr & 0xe0000000) == 0xe0000000) {\n\n mask.s_addr = htonl(0xffffff00); \/* class C *\/\n\n } else {\n\n mask.s_addr = htonl(0xfffffff0); \/* multicast\/reserved *\/\n\n }\n\n } else {\n\n if (!inet_aton(buf, &net)) {\n\n return -1;\n\n }\n\n shift = strtol(vnetwork, &end, 10);\n\n if (*end != '\\0') {\n\n if (!inet_aton(vnetwork, &mask)) {\n\n return -1;\n\n }\n\n } else if (shift < 4 || shift > 32) {\n\n return -1;\n\n } else {\n\n mask.s_addr = htonl(0xffffffff << (32 - shift));\n\n }\n\n }\n\n net.s_addr &= mask.s_addr;\n\n host.s_addr = net.s_addr | (htonl(0x0202) & ~mask.s_addr);\n\n dhcp.s_addr = net.s_addr | (htonl(0x020f) & ~mask.s_addr);\n\n dns.s_addr = net.s_addr | (htonl(0x0203) & ~mask.s_addr);\n\n }\n\n\n\n if (vhost && !inet_aton(vhost, &host)) {\n\n return -1;\n\n }\n\n if ((host.s_addr & mask.s_addr) != net.s_addr) {\n\n return -1;\n\n }\n\n\n\n if (vdhcp_start && !inet_aton(vdhcp_start, &dhcp)) {\n\n return -1;\n\n }\n\n if ((dhcp.s_addr & mask.s_addr) != net.s_addr ||\n\n dhcp.s_addr == host.s_addr || dhcp.s_addr == dns.s_addr) {\n\n return -1;\n\n }\n\n\n\n if (vnameserver && !inet_aton(vnameserver, &dns)) {\n\n return -1;\n\n }\n\n if ((dns.s_addr & mask.s_addr) != net.s_addr ||\n\n dns.s_addr == host.s_addr) {\n\n return -1;\n\n }\n\n\n\n#ifndef _WIN32\n\n if (vsmbserver && !inet_aton(vsmbserver, &smbsrv)) {\n\n return -1;\n\n }\n\n#endif\n\n\n\n nc = qemu_new_net_client(&net_slirp_info, peer, model, name);\n\n\n\n snprintf(nc->info_str, sizeof(nc->info_str),\n\n \"net=%s,restrict=%s\", inet_ntoa(net),\n\n restricted ? \"on\" : \"off\");\n\n\n\n s = DO_UPCAST(SlirpState, nc, nc);\n\n\n\n s->slirp = slirp_init(restricted, net, mask, host, vhostname,\n\n tftp_export, bootfile, dhcp, dns, dnssearch, s);\n\n QTAILQ_INSERT_TAIL(&slirp_stacks, s, entry);\n\n\n\n for (config = slirp_configs; config; config = config->next) {\n\n if (config->flags & SLIRP_CFG_HOSTFWD) {\n\n if (slirp_hostfwd(s, config->str,\n\n config->flags & SLIRP_CFG_LEGACY) < 0)\n\n goto error;\n\n } else {\n\n if (slirp_guestfwd(s, config->str,\n\n config->flags & SLIRP_CFG_LEGACY) < 0)\n\n goto error;\n\n }\n\n }\n\n#ifndef _WIN32\n\n if (!smb_export) {\n\n smb_export = legacy_smb_export;\n\n }\n\n if (smb_export) {\n\n if (slirp_smb(s, smb_export, smbsrv) < 0)\n\n goto error;\n\n }\n\n#endif\n\n\n\n return 0;\n\n\n\nerror:\n\n qemu_del_net_client(nc);\n\n return -1;\n\n}\n","target":0,"code_token_length":1542,"total_token_length":1873,"max_tokens_setting":2048} +{"idx":428001,"func":"static int imip_send(icalcomponent *ical)\n{\n icalcomponent *comp;\n icalproperty *prop;\n icalproperty_method meth;\n icalcomponent_kind kind;\n const char *argv[8], *originator, *subject;\n FILE *sm;\n pid_t pid;\n int r;\n time_t t = time(NULL);\n char datestr[80];\n static unsigned send_count = 0;\n icalproperty_kind recip_kind;\n const char *(*get_recipient)(const icalproperty *);\n\n meth = icalcomponent_get_method(ical);\n comp = icalcomponent_get_first_real_component(ical);\n kind = icalcomponent_isa(comp);\n\n \/* Determine Originator and Recipient(s) based on methond and component *\/\n if (meth == ICAL_METHOD_REPLY) {\n\trecip_kind = ICAL_ORGANIZER_PROPERTY;\n\tget_recipient = &icalproperty_get_organizer;\n\n\tif (kind == ICAL_VPOLL_COMPONENT) {\n\t prop = icalcomponent_get_first_property(comp, ICAL_VOTER_PROPERTY);\n\t originator = icalproperty_get_voter(prop) + 7;\n\t}\n\telse {\n\t prop =\n\t\ticalcomponent_get_first_property(comp, ICAL_ATTENDEE_PROPERTY);\n\t originator = icalproperty_get_attendee(prop) + 7;\n\t}\n }\n else {\n\tprop = icalcomponent_get_first_property(comp, ICAL_ORGANIZER_PROPERTY);\n\toriginator = icalproperty_get_organizer(prop) + 7;\n\n\tif (kind == ICAL_VPOLL_COMPONENT) {\n\t recip_kind = ICAL_VOTER_PROPERTY;\n\t get_recipient = &icalproperty_get_voter;\n\t}\n\telse {\n\t recip_kind = ICAL_ATTENDEE_PROPERTY;\n\t get_recipient = &icalproperty_get_attendee;\n\t}\n }\n\n argv[0] = \"sendmail\";\n argv[1] = \"-f\";\n argv[2] = originator;\n argv[3] = \"-i\";\n argv[4] = \"-N\";\n argv[5] = \"failure,delay\";\n argv[6] = \"-t\";\n argv[7] = NULL;\n pid = open_sendmail(argv, &sm);\n\n if (sm == NULL) return HTTP_UNAVAILABLE;\n\n \/* Create iMIP message *\/\n fprintf(sm, \"From: %s\\r\\n\", originator);\n\n for (prop = icalcomponent_get_first_property(comp, recip_kind);\n\t prop;\n\t prop = icalcomponent_get_next_property(comp, recip_kind)) {\n\tfprintf(sm, \"To: %s\\r\\n\", get_recipient(prop) + 7);\n }\n\n subject = icalcomponent_get_summary(comp);\n if (!subject) {\n\tfprintf(sm, \"Subject: %s %s\\r\\n\", icalcomponent_kind_to_string(kind),\n\t\ticalproperty_method_to_string(meth));\n }\n else fprintf(sm, \"Subject: %s\\r\\n\", subject);\n\n time_to_rfc822(t, datestr, sizeof(datestr));\n fprintf(sm, \"Date: %s\\r\\n\", datestr);\n\n fprintf(sm, \"Message-ID: \\r\\n\",\n\t getpid(), t, send_count++, config_servername);\n\n fprintf(sm, \"Content-Type: text\/calendar; charset=utf-8\");\n fprintf(sm, \"; method=%s; component=%s \\r\\n\",\n\t icalproperty_method_to_string(meth),\n\t icalcomponent_kind_to_string(kind));\n\n fputs(\"Content-Disposition: inline\\r\\n\", sm);\n\n fputs(\"MIME-Version: 1.0\\r\\n\", sm);\n fputs(\"\\r\\n\", sm);\n\n fputs(icalcomponent_as_ical_string(ical), sm);\n\n fclose(sm);\n\n while (waitpid(pid, &r, 0) < 0);\n\n return r;\n}","target":0,"code_token_length":834,"total_token_length":1165,"max_tokens_setting":2048} +{"idx":52009,"func":"int lzo1x_decompress_safe(const unsigned char *in, size_t in_len,\n\t\t\t unsigned char *out, size_t *out_len)\n{\n\tunsigned char *op;\n\tconst unsigned char *ip;\n\tsize_t t, next;\n\tsize_t state = 0;\n\tconst unsigned char *m_pos;\n\tconst unsigned char * const ip_end = in + in_len;\n\tunsigned char * const op_end = out + *out_len;\n\n\top = out;\n\tip = in;\n\n\tif (unlikely(in_len < 3))\n\t\tgoto input_overrun;\n\tif (*ip > 17) {\n\t\tt = *ip++ - 17;\n\t\tif (t < 4) {\n\t\t\tnext = t;\n\t\t\tgoto match_next;\n\t\t}\n\t\tgoto copy_literal_run;\n\t}\n\n\tfor (;;) {\n\t\tt = *ip++;\n\t\tif (t < 16) {\n\t\t\tif (likely(state == 0)) {\n\t\t\t\tif (unlikely(t == 0)) {\n\t\t\t\t\twhile (unlikely(*ip == 0)) {\n\t\t\t\t\t\tt += 255;\n\t\t\t\t\t\tip++;\n\t\t\t\t\t\tNEED_IP(1, 0);\n\t\t\t\t\t}\n\t\t\t\t\tt += 15 + *ip++;\n\t\t\t\t}\n\t\t\t\tt += 3;\ncopy_literal_run:\n#if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)\n\t\t\t\tif (likely(HAVE_IP(t, 15) && HAVE_OP(t, 15))) {\n\t\t\t\t\tconst unsigned char *ie = ip + t;\n\t\t\t\t\tunsigned char *oe = op + t;\n\t\t\t\t\tdo {\n\t\t\t\t\t\tCOPY8(op, ip);\n\t\t\t\t\t\top += 8;\n\t\t\t\t\t\tip += 8;\n\t\t\t\t\t\tCOPY8(op, ip);\n\t\t\t\t\t\top += 8;\n\t\t\t\t\t\tip += 8;\n\t\t\t\t\t} while (ip < ie);\n\t\t\t\t\tip = ie;\n\t\t\t\t\top = oe;\n\t\t\t\t} else\n#endif\n\t\t\t\t{\n\t\t\t\t\tNEED_OP(t, 0);\n\t\t\t\t\tNEED_IP(t, 3);\n\t\t\t\t\tdo {\n\t\t\t\t\t\t*op++ = *ip++;\n\t\t\t\t\t} while (--t > 0);\n\t\t\t\t}\n\t\t\t\tstate = 4;\n\t\t\t\tcontinue;\n\t\t\t} else if (state != 4) {\n\t\t\t\tnext = t & 3;\n\t\t\t\tm_pos = op - 1;\n\t\t\t\tm_pos -= t >> 2;\n\t\t\t\tm_pos -= *ip++ << 2;\n\t\t\t\tTEST_LB(m_pos);\n\t\t\t\tNEED_OP(2, 0);\n\t\t\t\top[0] = m_pos[0];\n\t\t\t\top[1] = m_pos[1];\n\t\t\t\top += 2;\n\t\t\t\tgoto match_next;\n\t\t\t} else {\n\t\t\t\tnext = t & 3;\n\t\t\t\tm_pos = op - (1 + M2_MAX_OFFSET);\n\t\t\t\tm_pos -= t >> 2;\n\t\t\t\tm_pos -= *ip++ << 2;\n\t\t\t\tt = 3;\n\t\t\t}\n\t\t} else if (t >= 64) {\n\t\t\tnext = t & 3;\n\t\t\tm_pos = op - 1;\n\t\t\tm_pos -= (t >> 2) & 7;\n\t\t\tm_pos -= *ip++ << 3;\n\t\t\tt = (t >> 5) - 1 + (3 - 1);\n\t\t} else if (t >= 32) {\n\t\t\tt = (t & 31) + (3 - 1);\n\t\t\tif (unlikely(t == 2)) {\n\t\t\t\twhile (unlikely(*ip == 0)) {\n\t\t\t\t\tt += 255;\n\t\t\t\t\tip++;\n\t\t\t\t\tNEED_IP(1, 0);\n\t\t\t\t}\n\t\t\t\tt += 31 + *ip++;\n\t\t\t\tNEED_IP(2, 0);\n\t\t\t}\n\t\t\tm_pos = op - 1;\n\t\t\tnext = get_unaligned_le16(ip);\n\t\t\tip += 2;\n\t\t\tm_pos -= next >> 2;\n\t\t\tnext &= 3;\n\t\t} else {\n\t\t\tm_pos = op;\n\t\t\tm_pos -= (t & 8) << 11;\n\t\t\tt = (t & 7) + (3 - 1);\n\t\t\tif (unlikely(t == 2)) {\n\t\t\t\twhile (unlikely(*ip == 0)) {\n\t\t\t\t\tt += 255;\n\t\t\t\t\tip++;\n\t\t\t\t\tNEED_IP(1, 0);\n\t\t\t\t}\n\t\t\t\tt += 7 + *ip++;\n\t\t\t\tNEED_IP(2, 0);\n\t\t\t}\n\t\t\tnext = get_unaligned_le16(ip);\n\t\t\tip += 2;\n\t\t\tm_pos -= next >> 2;\n\t\t\tnext &= 3;\n\t\t\tif (m_pos == op)\n\t\t\t\tgoto eof_found;\n\t\t\tm_pos -= 0x4000;\n\t\t}\n\t\tTEST_LB(m_pos);\n#if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)\n\t\tif (op - m_pos >= 8) {\n\t\t\tunsigned char *oe = op + t;\n\t\t\tif (likely(HAVE_OP(t, 15))) {\n\t\t\t\tdo {\n\t\t\t\t\tCOPY8(op, m_pos);\n\t\t\t\t\top += 8;\n\t\t\t\t\tm_pos += 8;\n\t\t\t\t\tCOPY8(op, m_pos);\n\t\t\t\t\top += 8;\n\t\t\t\t\tm_pos += 8;\n\t\t\t\t} while (op < oe);\n\t\t\t\top = oe;\n\t\t\t\tif (HAVE_IP(6, 0)) {\n\t\t\t\t\tstate = next;\n\t\t\t\t\tCOPY4(op, ip);\n\t\t\t\t\top += next;\n\t\t\t\t\tip += next;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tNEED_OP(t, 0);\n\t\t\t\tdo {\n\t\t\t\t\t*op++ = *m_pos++;\n\t\t\t\t} while (op < oe);\n\t\t\t}\n\t\t} else\n#endif\n\t\t{\n\t\t\tunsigned char *oe = op + t;\n\t\t\tNEED_OP(t, 0);\n\t\t\top[0] = m_pos[0];\n\t\t\top[1] = m_pos[1];\n\t\t\top += 2;\n\t\t\tm_pos += 2;\n\t\t\tdo {\n\t\t\t\t*op++ = *m_pos++;\n\t\t\t} while (op < oe);\n\t\t}\nmatch_next:\n\t\tstate = next;\n\t\tt = next;\n#if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)\n\t\tif (likely(HAVE_IP(6, 0) && HAVE_OP(4, 0))) {\n\t\t\tCOPY4(op, ip);\n\t\t\top += t;\n\t\t\tip += t;\n\t\t} else\n#endif\n\t\t{\n\t\t\tNEED_IP(t, 3);\n\t\t\tNEED_OP(t, 0);\n\t\t\twhile (t > 0) {\n\t\t\t\t*op++ = *ip++;\n\t\t\t\tt--;\n\t\t\t}\n\t\t}\n\t}\n\neof_found:\n\t*out_len = op - out;\n\treturn (t != 3 ? LZO_E_ERROR :\n\t\tip == ip_end ? LZO_E_OK :\n\t\tip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN);\n\ninput_overrun:\n\t*out_len = op - out;\n\treturn LZO_E_INPUT_OVERRUN;\n\noutput_overrun:\n\t*out_len = op - out;\n\treturn LZO_E_OUTPUT_OVERRUN;\n\nlookbehind_overrun:\n\t*out_len = op - out;\n\treturn LZO_E_LOOKBEHIND_OVERRUN;\n}","target":0,"code_token_length":1525,"total_token_length":1856,"max_tokens_setting":2048} +{"idx":275387,"func":"static int zend_parse_va_args(int num_args, const char *type_spec, va_list *va, int flags TSRMLS_DC) \/* {{{ *\/\n{\n\tconst char *spec_walk;\n\tint c, i;\n\tint min_num_args = -1;\n\tint max_num_args = 0;\n\tint post_varargs = 0;\n\tzval **arg;\n\tint arg_count;\n\tint quiet = flags & ZEND_PARSE_PARAMS_QUIET;\n\tzend_bool have_varargs = 0;\n\tzval ****varargs = NULL;\n\tint *n_varargs = NULL;\n\n\tfor (spec_walk = type_spec; *spec_walk; spec_walk++) {\n\t\tc = *spec_walk;\n\t\tswitch (c) {\n\t\t\tcase 'l': case 'd':\n\t\t\tcase 's': case 'b':\n\t\t\tcase 'r': case 'a':\n\t\t\tcase 'o': case 'O':\n\t\t\tcase 'z': case 'Z':\n\t\t\tcase 'C': case 'h':\n\t\t\tcase 'f': case 'A':\n\t\t\tcase 'H': case 'p':\n\t\t\t\tmax_num_args++;\n\t\t\t\tbreak;\n\n\t\t\tcase '|':\n\t\t\t\tmin_num_args = max_num_args;\n\t\t\t\tbreak;\n\n\t\t\tcase '\/':\n\t\t\tcase '!':\n\t\t\t\t\/* Pass *\/\n\t\t\t\tbreak;\n\n\t\t\tcase '*':\n\t\t\tcase '+':\n\t\t\t\tif (have_varargs) {\n\t\t\t\t\tif (!quiet) {\n\t\t\t\t\t\tzend_function *active_function = EG(current_execute_data)->function_state.function;\n\t\t\t\t\t\tconst char *class_name = active_function->common.scope ? active_function->common.scope->name : \"\";\n\t\t\t\t\t\tzend_error(E_WARNING, \"%s%s%s(): only one varargs specifier (* or +) is permitted\",\n\t\t\t\t\t\t\t\tclass_name,\n\t\t\t\t\t\t\t\tclass_name[0] ? \"::\" : \"\",\n\t\t\t\t\t\t\t\tactive_function->common.function_name);\n\t\t\t\t\t}\n\t\t\t\t\treturn FAILURE;\n\t\t\t\t}\n\t\t\t\thave_varargs = 1;\n\t\t\t\t\/* we expect at least one parameter in varargs *\/\n\t\t\t\tif (c == '+') {\n\t\t\t\t\tmax_num_args++;\n\t\t\t\t}\n\t\t\t\t\/* mark the beginning of varargs *\/\n\t\t\t\tpost_varargs = max_num_args;\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tif (!quiet) {\n\t\t\t\t\tzend_function *active_function = EG(current_execute_data)->function_state.function;\n\t\t\t\t\tconst char *class_name = active_function->common.scope ? active_function->common.scope->name : \"\";\n\t\t\t\t\tzend_error(E_WARNING, \"%s%s%s(): bad type specifier while parsing parameters\",\n\t\t\t\t\t\t\tclass_name,\n\t\t\t\t\t\t\tclass_name[0] ? \"::\" : \"\",\n\t\t\t\t\t\t\tactive_function->common.function_name);\n\t\t\t\t}\n\t\t\t\treturn FAILURE;\n\t\t}\n\t}\n\n\tif (min_num_args < 0) {\n\t\tmin_num_args = max_num_args;\n\t}\n\n\tif (have_varargs) {\n\t\t\/* calculate how many required args are at the end of the specifier list *\/\n\t\tpost_varargs = max_num_args - post_varargs;\n\t\tmax_num_args = -1;\n\t}\n\n\tif (num_args < min_num_args || (num_args > max_num_args && max_num_args > 0)) {\n\t\tif (!quiet) {\n\t\t\tzend_function *active_function = EG(current_execute_data)->function_state.function;\n\t\t\tconst char *class_name = active_function->common.scope ? active_function->common.scope->name : \"\";\n\t\t\tzend_error(E_WARNING, \"%s%s%s() expects %s %d parameter%s, %d given\",\n\t\t\t\t\tclass_name,\n\t\t\t\t\tclass_name[0] ? \"::\" : \"\",\n\t\t\t\t\tactive_function->common.function_name,\n\t\t\t\t\tmin_num_args == max_num_args ? \"exactly\" : num_args < min_num_args ? \"at least\" : \"at most\",\n\t\t\t\t\tnum_args < min_num_args ? min_num_args : max_num_args,\n\t\t\t\t\t(num_args < min_num_args ? min_num_args : max_num_args) == 1 ? \"\" : \"s\",\n\t\t\t\t\tnum_args);\n\t\t}\n\t\treturn FAILURE;\n\t}\n\n\targ_count = (int)(zend_uintptr_t) *(zend_vm_stack_top(TSRMLS_C) - 1);\n\n\tif (num_args > arg_count) {\n\t\tzend_error(E_WARNING, \"%s(): could not obtain parameters for parsing\",\n\t\t\tget_active_function_name(TSRMLS_C));\n\t\treturn FAILURE;\n\t}\n\n\ti = 0;\n\twhile (num_args-- > 0) {\n\t\tif (*type_spec == '|') {\n\t\t\ttype_spec++;\n\t\t}\n\n\t\tif (*type_spec == '*' || *type_spec == '+') {\n\t\t\tint num_varargs = num_args + 1 - post_varargs;\n\n\t\t\t\/* eat up the passed in storage even if it won't be filled in with varargs *\/\n\t\t\tvarargs = va_arg(*va, zval ****);\n\t\t\tn_varargs = va_arg(*va, int *);\n\t\t\ttype_spec++;\n\n\t\t\tif (num_varargs > 0) {\n\t\t\t\tint iv = 0;\n\t\t\t\tzval **p = (zval **) (zend_vm_stack_top(TSRMLS_C) - 1 - (arg_count - i));\n\n\t\t\t\t*n_varargs = num_varargs;\n\n\t\t\t\t\/* allocate space for array and store args *\/\n\t\t\t\t*varargs = safe_emalloc(num_varargs, sizeof(zval **), 0);\n\t\t\t\twhile (num_varargs-- > 0) {\n\t\t\t\t\t(*varargs)[iv++] = p++;\n\t\t\t\t}\n\n\t\t\t\t\/* adjust how many args we have left and restart loop *\/\n\t\t\t\tnum_args = num_args + 1 - iv;\n\t\t\t\ti += iv;\n\t\t\t\tcontinue;\n\t\t\t} else {\n\t\t\t\t*varargs = NULL;\n\t\t\t\t*n_varargs = 0;\n\t\t\t}\n\t\t}\n\n\t\targ = (zval **) (zend_vm_stack_top(TSRMLS_C) - 1 - (arg_count-i));\n\n\t\tif (zend_parse_arg(i+1, arg, va, &type_spec, quiet TSRMLS_CC) == FAILURE) {\n\t\t\t\/* clean up varargs array if it was used *\/\n\t\t\tif (varargs && *varargs) {\n\t\t\t\tefree(*varargs);\n\t\t\t\t*varargs = NULL;\n\t\t\t}\n\t\t\treturn FAILURE;\n\t\t}\n\t\ti++;\n\t}\n\n\treturn SUCCESS;\n}\n\/* }}} *\/\n","target":0,"code_token_length":1276,"total_token_length":1607,"max_tokens_setting":2048} +{"idx":341462,"func":"static int parse_presentation_segment(AVCodecContext *avctx,\n const uint8_t *buf, int buf_size,\n int64_t pts)\n{\n PGSSubContext *ctx = avctx->priv_data;\n int i, state, ret;\n const uint8_t *buf_end = buf + buf_size;\n \/\/ Video descriptor\n int w = bytestream_get_be16(&buf);\n int h = bytestream_get_be16(&buf);\n uint16_t object_index;\n ctx->presentation.pts = pts;\n av_dlog(avctx, \"Video Dimensions %dx%d\\n\",\n w, h);\n ret = ff_set_dimensions(avctx, w, h);\n if (ret < 0)\n return ret;\n \/* Skip 1 bytes of unknown, frame rate *\/\n buf++;\n \/\/ Composition descriptor\n ctx->presentation.id_number = bytestream_get_be16(&buf);\n \/*\n * state is a 2 bit field that defines pgs epoch boundaries\n * 00 - Normal, previously defined objects and palettes are still valid\n * 01 - Acquisition point, previous objects and palettes can be released\n * 10 - Epoch start, previous objects and palettes can be released\n * 11 - Epoch continue, previous objects and palettes can be released\n *\n * reserved 6 bits discarded\n *\/\n state = bytestream_get_byte(&buf) >> 6;\n if (state != 0) {\n flush_cache(avctx);\n \/*\n * skip palette_update_flag (0x80),\n *\/\n buf += 1;\n ctx->presentation.palette_id = bytestream_get_byte(&buf);\n ctx->presentation.object_count = bytestream_get_byte(&buf);\n if (ctx->presentation.object_count > MAX_OBJECT_REFS) {\n av_log(avctx, AV_LOG_ERROR,\n \"Invalid number of presentation objects %d\\n\",\n ctx->presentation.object_count);\n ctx->presentation.object_count = 2;\n if (avctx->err_recognition & AV_EF_EXPLODE) {\n for (i = 0; i < ctx->presentation.object_count; i++)\n {\n ctx->presentation.objects[i].id = bytestream_get_be16(&buf);\n ctx->presentation.objects[i].window_id = bytestream_get_byte(&buf);\n ctx->presentation.objects[i].composition_flag = bytestream_get_byte(&buf);\n ctx->presentation.objects[i].x = bytestream_get_be16(&buf);\n ctx->presentation.objects[i].y = bytestream_get_be16(&buf);\n \/\/ If cropping\n if (ctx->presentation.objects[i].composition_flag & 0x80) {\n ctx->presentation.objects[i].crop_x = bytestream_get_be16(&buf);\n ctx->presentation.objects[i].crop_y = bytestream_get_be16(&buf);\n ctx->presentation.objects[i].crop_w = bytestream_get_be16(&buf);\n ctx->presentation.objects[i].crop_h = bytestream_get_be16(&buf);\n av_dlog(avctx, \"Subtitle Placement x=%d, y=%d\\n\",\n ctx->presentation.objects[i].x, ctx->presentation.objects[i].y);\n if (ctx->presentation.objects[i].x > avctx->width ||\n ctx->presentation.objects[i].y > avctx->height) {\n av_log(avctx, AV_LOG_ERROR, \"Subtitle out of video bounds. x = %d, y = %d, video width = %d, video height = %d.\\n\",\n ctx->presentation.objects[i].x,\n ctx->presentation.objects[i].y,\n avctx->width, avctx->height);\n ctx->presentation.objects[i].x = 0;\n ctx->presentation.objects[i].y = 0;\n if (avctx->err_recognition & AV_EF_EXPLODE) {\n return 0;","target":1,"code_token_length":859,"total_token_length":1190,"max_tokens_setting":2048} +{"idx":438169,"func":"long long Segment::CreateInstance(IMkvReader* pReader, long long pos,\n Segment*& pSegment) {\n if (pReader == NULL || pos < 0)\n return E_PARSE_FAILED;\n\n pSegment = NULL;\n\n long long total, available;\n\n const long status = pReader->Length(&total, &available);\n\n if (status < 0) \/\/ error\n return status;\n\n if (available < 0)\n return -1;\n\n if ((total >= 0) && (available > total))\n return -1;\n\n \/\/ I would assume that in practice this loop would execute\n \/\/ exactly once, but we allow for other elements (e.g. Void)\n \/\/ to immediately follow the EBML header. This is fine for\n \/\/ the source filter case (since the entire file is available),\n \/\/ but in the splitter case over a network we should probably\n \/\/ just give up early. We could for example decide only to\n \/\/ execute this loop a maximum of, say, 10 times.\n \/\/ TODO:\n \/\/ There is an implied \"give up early\" by only parsing up\n \/\/ to the available limit. We do do that, but only if the\n \/\/ total file size is unknown. We could decide to always\n \/\/ use what's available as our limit (irrespective of whether\n \/\/ we happen to know the total file length). This would have\n \/\/ as its sense \"parse this much of the file before giving up\",\n \/\/ which a slightly different sense from \"try to parse up to\n \/\/ 10 EMBL elements before giving up\".\n\n for (;;) {\n if ((total >= 0) && (pos >= total))\n return E_FILE_FORMAT_INVALID;\n\n \/\/ Read ID\n long len;\n long long result = GetUIntLength(pReader, pos, len);\n\n if (result) \/\/ error, or too few available bytes\n return result;\n\n if ((total >= 0) && ((pos + len) > total))\n return E_FILE_FORMAT_INVALID;\n\n if ((pos + len) > available)\n return pos + len;\n\n const long long idpos = pos;\n const long long id = ReadID(pReader, pos, len);\n\n if (id < 0)\n return E_FILE_FORMAT_INVALID;\n\n pos += len; \/\/ consume ID\n\n \/\/ Read Size\n\n result = GetUIntLength(pReader, pos, len);\n\n if (result) \/\/ error, or too few available bytes\n return result;\n\n if ((total >= 0) && ((pos + len) > total))\n return E_FILE_FORMAT_INVALID;\n\n if ((pos + len) > available)\n return pos + len;\n\n long long size = ReadUInt(pReader, pos, len);\n\n if (size < 0) \/\/ error\n return size;\n\n pos += len; \/\/ consume length of size of element\n\n \/\/ Pos now points to start of payload\n\n \/\/ Handle \"unknown size\" for live streaming of webm files.\n const long long unknown_size = (1LL << (7 * len)) - 1;\n\n if (id == libwebm::kMkvSegment) {\n if (size == unknown_size)\n size = -1;\n\n else if (total < 0)\n size = -1;\n\n else if ((pos + size) > total)\n size = -1;\n\n pSegment = new (std::nothrow) Segment(pReader, idpos, pos, size);\n if (pSegment == NULL)\n return E_PARSE_FAILED;\n\n return 0; \/\/ success\n }\n\n if (size == unknown_size)\n return E_FILE_FORMAT_INVALID;\n\n if ((total >= 0) && ((pos + size) > total))\n return E_FILE_FORMAT_INVALID;\n\n if ((pos + size) > available)\n return pos + size;\n\n pos += size; \/\/ consume payload\n }\n}","target":0,"code_token_length":853,"total_token_length":1184,"max_tokens_setting":2048} +{"idx":496535,"func":" bool operator() (SFace_handle sf1, SFace_handle sf2) const {\n CGAL_NEF_TRACEN(\"sort sfaces\");\n if(&*sf1 == &*sf2) return false;\n\n sort_vertices SORT(*this->sncp());\n\n CGAL_NEF_TRACEN(\" vertices \" << sf1->center_vertex()->point() << \" , \" << sf2->center_vertex()->point());\n if(sf1->center_vertex() != sf2->center_vertex())\n return SORT(sf1->center_vertex(), sf2->center_vertex());\n\n \/\/ sort_sface_cycle_entries sort_cycles((Base) *this);\n \/\/ return sort_cycles(*sf1->sface_cycles_begin(), *sf2->sface_cycles_begin());\n\n SM_decorator SD(&*sf1->center_vertex());\n moreLeft ml((Base) *this);\n Vector_3 plus(1,0,0);\n\n SFace_cycle_iterator fc;\n\n CGAL_NEF_TRACEN(\" sface 1\");\n\n SHalfedge_handle se1;\n SHalfloop_handle sl1;\n CGAL_forall_sface_cycles_of(fc,sf1) {\n if(fc.is_shalfedge()) {\n SHalfedge_handle se(fc);\n SHalfedge_around_sface_circulator ec(se),ee(se);\n CGAL_For_all(ec,ee) {\n CGAL_NEF_TRACEN(\" \" << ec->source()->point() <<\n \" | \" << ec->circle().orthogonal_vector());\n if(ml(ec, se1) == -1)\n se1 = ec;\n }\n }\n else if(fc.is_shalfloop())\n sl1 = SHalfloop_handle(fc);\n else\n CGAL_assertion(fc.is_svertex());\n }\n\n CGAL_NEF_TRACEN(\" sface 2\");\n\n SHalfedge_handle se2;\n SHalfloop_handle sl2;\n CGAL_forall_sface_cycles_of(fc,sf2) {\n if(fc.is_shalfedge()) {\n SHalfedge_handle se(fc);\n SHalfedge_around_sface_circulator ec(se),ee(se);\n CGAL_For_all(ec,ee) {\n CGAL_NEF_TRACEN(\" \" << ec->source()->point() <<\n \" | \" << ec->circle().orthogonal_vector());\n if(ml(ec, se2) == -1)\n se2 = ec;\n }\n }\n else if(fc.is_shalfloop())\n sl2 = SHalfloop_handle(fc);\n else\n CGAL_assertion(fc.is_svertex());\n }\n\n CGAL_NEF_TRACEN(\" sedge cycles existing? \" << (se1 != SHalfedge_handle())\n << \" , \" << (se2 != SHalfedge_handle()));\n\n if(se1 != SHalfedge_handle() && se2 == SHalfedge_handle())\n return true;\n if(se1 == SHalfedge_handle() && se2 != SHalfedge_handle())\n return false;\n\n if(se1 == SHalfedge_handle() && se2 == SHalfedge_handle()) {\n Vector_3 vec1 = sl1->circle().orthogonal_vector();\n Vector_3 vec2 = sl2->circle().orthogonal_vector();\n CGAL_NEF_TRACEN(\" sloops \" << vec1 << \" , \" << vec2);\n if(vec1.x() != vec2.x())\n return vec1.x() < vec2.x();\n else if(vec1.y() != vec2.y())\n return vec1.y() < vec2.y();\n else if(vec1.z() != vec2.z())\n return vec1.z() < vec2.z();\n }\n\n CGAL_assertion(se1 != SHalfedge_handle() && se2 != SHalfedge_handle());\n\n CGAL_NEF_TRACEN(\" minimal sedge in sface 1:\" << se1->source()->point() <<\n \" , \" << se1->circle().orthogonal_vector());\n CGAL_NEF_TRACEN(\" minimal sedge in sface 2:\" << se2->source()->point() <<\n \" , \" << se2->circle().orthogonal_vector());\n CGAL_NEF_TRACEN(\"result \" << ml(se1,se2));\n switch(ml(se1, se2)) {\n case -1: return true;\n case 1: return false;\n }\n sort_sface_cycle_entries SORTSFC(*this->sncp());\n return SORTSFC(*sf1->sface_cycles_begin(), *sf2->sface_cycles_begin());\n }","target":0,"code_token_length":996,"total_token_length":1327,"max_tokens_setting":2048} +{"idx":259543,"func":"static int setup_netdev(struct lxc_netdev *netdev)\n{\n\tchar ifname[IFNAMSIZ];\n\tchar *current_ifname = ifname;\n\tint err;\n\n\t\/* empty network namespace *\/\n\tif (!netdev->ifindex) {\n\t\tif (netdev->flags & IFF_UP) {\n\t\t\terr = lxc_netdev_up(\"lo\");\n\t\t\tif (err) {\n\t\t\t\tERROR(\"failed to set the loopback up : %s\",\n\t\t\t\t strerror(-err));\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\tif (netdev->type != LXC_NET_VETH)\n\t\t\treturn 0;\n\t\tnetdev->ifindex = if_nametoindex(netdev->name);\n\t}\n\n\t\/* get the new ifindex in case of physical netdev *\/\n\tif (netdev->type == LXC_NET_PHYS) {\n\t\tif (!(netdev->ifindex = if_nametoindex(netdev->link))) {\n\t\t\tERROR(\"failed to get ifindex for %s\",\n\t\t\t\tnetdev->link);\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\t\/* retrieve the name of the interface *\/\n\tif (!if_indextoname(netdev->ifindex, current_ifname)) {\n\t\tERROR(\"no interface corresponding to index '%d'\",\n\t\t netdev->ifindex);\n\t\treturn -1;\n\t}\n\n\t\/* default: let the system to choose one interface name *\/\n\tif (!netdev->name)\n\t\tnetdev->name = netdev->type == LXC_NET_PHYS ?\n\t\t\tnetdev->link : \"eth%d\";\n\n\t\/* rename the interface name *\/\n\tif (strcmp(ifname, netdev->name) != 0) {\n\t\terr = lxc_netdev_rename_by_name(ifname, netdev->name);\n\t\tif (err) {\n\t\t\tERROR(\"failed to rename %s->%s : %s\", ifname, netdev->name,\n\t\t\t strerror(-err));\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\t\/* Re-read the name of the interface because its name has changed\n\t * and would be automatically allocated by the system\n\t *\/\n\tif (!if_indextoname(netdev->ifindex, current_ifname)) {\n\t\tERROR(\"no interface corresponding to index '%d'\",\n\t\t netdev->ifindex);\n\t\treturn -1;\n\t}\n\n\t\/* set a mac address *\/\n\tif (netdev->hwaddr) {\n\t\tif (setup_hw_addr(netdev->hwaddr, current_ifname)) {\n\t\t\tERROR(\"failed to setup hw address for '%s'\",\n\t\t\t current_ifname);\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\t\/* setup ipv4 addresses on the interface *\/\n\tif (setup_ipv4_addr(&netdev->ipv4, netdev->ifindex)) {\n\t\tERROR(\"failed to setup ip addresses for '%s'\",\n\t\t\t ifname);\n\t\treturn -1;\n\t}\n\n\t\/* setup ipv6 addresses on the interface *\/\n\tif (setup_ipv6_addr(&netdev->ipv6, netdev->ifindex)) {\n\t\tERROR(\"failed to setup ipv6 addresses for '%s'\",\n\t\t\t ifname);\n\t\treturn -1;\n\t}\n\n\t\/* set the network device up *\/\n\tif (netdev->flags & IFF_UP) {\n\t\tint err;\n\n\t\terr = lxc_netdev_up(current_ifname);\n\t\tif (err) {\n\t\t\tERROR(\"failed to set '%s' up : %s\", current_ifname,\n\t\t\t strerror(-err));\n\t\t\treturn -1;\n\t\t}\n\n\t\t\/* the network is up, make the loopback up too *\/\n\t\terr = lxc_netdev_up(\"lo\");\n\t\tif (err) {\n\t\t\tERROR(\"failed to set the loopback up : %s\",\n\t\t\t strerror(-err));\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\t\/* We can only set up the default routes after bringing\n\t * up the interface, sine bringing up the interface adds\n\t * the link-local routes and we can't add a default\n\t * route if the gateway is not reachable. *\/\n\n\t\/* setup ipv4 gateway on the interface *\/\n\tif (netdev->ipv4_gateway) {\n\t\tif (!(netdev->flags & IFF_UP)) {\n\t\t\tERROR(\"Cannot add ipv4 gateway for %s when not bringing up the interface\", ifname);\n\t\t\treturn -1;\n\t\t}\n\n\t\tif (lxc_list_empty(&netdev->ipv4)) {\n\t\t\tERROR(\"Cannot add ipv4 gateway for %s when not assigning an address\", ifname);\n\t\t\treturn -1;\n\t\t}\n\n\t\terr = lxc_ipv4_gateway_add(netdev->ifindex, netdev->ipv4_gateway);\n\t\tif (err) {\n\t\t\terr = lxc_ipv4_dest_add(netdev->ifindex, netdev->ipv4_gateway);\n\t\t\tif (err) {\n\t\t\t\tERROR(\"failed to add ipv4 dest for '%s': %s\",\n\t\t\t\t\t ifname, strerror(-err));\n\t\t\t}\n\n\t\t\terr = lxc_ipv4_gateway_add(netdev->ifindex, netdev->ipv4_gateway);\n\t\t\tif (err) {\n\t\t\t\tERROR(\"failed to setup ipv4 gateway for '%s': %s\",\n\t\t\t\t\t ifname, strerror(-err));\n\t\t\t\tif (netdev->ipv4_gateway_auto) {\n\t\t\t\t\tchar buf[INET_ADDRSTRLEN];\n\t\t\t\t\tinet_ntop(AF_INET, netdev->ipv4_gateway, buf, sizeof(buf));\n\t\t\t\t\tERROR(\"tried to set autodetected ipv4 gateway '%s'\", buf);\n\t\t\t\t}\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/* setup ipv6 gateway on the interface *\/\n\tif (netdev->ipv6_gateway) {\n\t\tif (!(netdev->flags & IFF_UP)) {\n\t\t\tERROR(\"Cannot add ipv6 gateway for %s when not bringing up the interface\", ifname);\n\t\t\treturn -1;\n\t\t}\n\n\t\tif (lxc_list_empty(&netdev->ipv6) && !IN6_IS_ADDR_LINKLOCAL(netdev->ipv6_gateway)) {\n\t\t\tERROR(\"Cannot add ipv6 gateway for %s when not assigning an address\", ifname);\n\t\t\treturn -1;\n\t\t}\n\n\t\terr = lxc_ipv6_gateway_add(netdev->ifindex, netdev->ipv6_gateway);\n\t\tif (err) {\n\t\t\terr = lxc_ipv6_dest_add(netdev->ifindex, netdev->ipv6_gateway);\n\t\t\tif (err) {\n\t\t\t\tERROR(\"failed to add ipv6 dest for '%s': %s\",\n\t\t\t\t ifname, strerror(-err));\n\t\t\t}\n\n\t\t\terr = lxc_ipv6_gateway_add(netdev->ifindex, netdev->ipv6_gateway);\n\t\t\tif (err) {\n\t\t\t\tERROR(\"failed to setup ipv6 gateway for '%s': %s\",\n\t\t\t\t\t ifname, strerror(-err));\n\t\t\t\tif (netdev->ipv6_gateway_auto) {\n\t\t\t\t\tchar buf[INET6_ADDRSTRLEN];\n\t\t\t\t\tinet_ntop(AF_INET6, netdev->ipv6_gateway, buf, sizeof(buf));\n\t\t\t\t\tERROR(\"tried to set autodetected ipv6 gateway '%s'\", buf);\n\t\t\t\t}\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t}\n\n\tDEBUG(\"'%s' has been setup\", current_ifname);\n\n\treturn 0;\n}","target":0,"code_token_length":1498,"total_token_length":1829,"max_tokens_setting":2048} +{"idx":43294,"func":"do_open_lookup(struct svc_rqst *rqstp, struct nfsd4_compound_state *cstate, struct nfsd4_open *open, struct svc_fh **resfh)\n{\n\tstruct svc_fh *current_fh = &cstate->current_fh;\n\tint accmode;\n\t__be32 status;\n\n\t*resfh = kmalloc(sizeof(struct svc_fh), GFP_KERNEL);\n\tif (!*resfh)\n\t\treturn nfserr_jukebox;\n\tfh_init(*resfh, NFS4_FHSIZE);\n\topen->op_truncate = 0;\n\n\tif (open->op_create) {\n\t\t\/* FIXME: check session persistence and pnfs flags.\n\t\t * The nfsv4.1 spec requires the following semantics:\n\t\t *\n\t\t * Persistent | pNFS | Server REQUIRED | Client Allowed\n\t\t * Reply Cache | server | |\n\t\t * -------------+--------+-----------------+--------------------\n\t\t * no | no | EXCLUSIVE4_1 | EXCLUSIVE4_1\n\t\t * | | | (SHOULD)\n\t\t * | | and EXCLUSIVE4 | or EXCLUSIVE4\n\t\t * | | | (SHOULD NOT)\n\t\t * no | yes | EXCLUSIVE4_1 | EXCLUSIVE4_1\n\t\t * yes | no | GUARDED4 | GUARDED4\n\t\t * yes | yes | GUARDED4 | GUARDED4\n\t\t *\/\n\n\t\t\/*\n\t\t * Note: create modes (UNCHECKED,GUARDED...) are the same\n\t\t * in NFSv4 as in v3 except EXCLUSIVE4_1.\n\t\t *\/\n\t\tstatus = do_nfsd_create(rqstp, current_fh, open->op_fname.data,\n\t\t\t\t\topen->op_fname.len, &open->op_iattr,\n\t\t\t\t\t*resfh, open->op_createmode,\n\t\t\t\t\t(u32 *)open->op_verf.data,\n\t\t\t\t\t&open->op_truncate, &open->op_created);\n\n\t\tif (!status && open->op_label.len)\n\t\t\tnfsd4_security_inode_setsecctx(*resfh, &open->op_label, open->op_bmval);\n\n\t\t\/*\n\t\t * Following rfc 3530 14.2.16, and rfc 5661 18.16.4\n\t\t * use the returned bitmask to indicate which attributes\n\t\t * we used to store the verifier:\n\t\t *\/\n\t\tif (nfsd_create_is_exclusive(open->op_createmode) && status == 0)\n\t\t\topen->op_bmval[1] |= (FATTR4_WORD1_TIME_ACCESS |\n\t\t\t\t\t\tFATTR4_WORD1_TIME_MODIFY);\n\t} else\n\t\t\/*\n\t\t * Note this may exit with the parent still locked.\n\t\t * We will hold the lock until nfsd4_open's final\n\t\t * lookup, to prevent renames or unlinks until we've had\n\t\t * a chance to an acquire a delegation if appropriate.\n\t\t *\/\n\t\tstatus = nfsd_lookup(rqstp, current_fh,\n\t\t\t\t open->op_fname.data, open->op_fname.len, *resfh);\n\tif (status)\n\t\tgoto out;\n\tstatus = nfsd_check_obj_isreg(*resfh);\n\tif (status)\n\t\tgoto out;\n\n\tif (is_create_with_attrs(open) && open->op_acl != NULL)\n\t\tdo_set_nfs4_acl(rqstp, *resfh, open->op_acl, open->op_bmval);\n\n\tnfsd4_set_open_owner_reply_cache(cstate, open, *resfh);\n\taccmode = NFSD_MAY_NOP;\n\tif (open->op_created ||\n\t\t\topen->op_claim_type == NFS4_OPEN_CLAIM_DELEGATE_CUR)\n\t\taccmode |= NFSD_MAY_OWNER_OVERRIDE;\n\tstatus = do_open_permission(rqstp, *resfh, open, accmode);\n\tset_change_info(&open->op_cinfo, current_fh);\nout:\n\treturn status;\n}","target":0,"code_token_length":843,"total_token_length":1174,"max_tokens_setting":2048} +{"idx":440910,"func":"vnc_display_setup_auth(int *auth,\n int *subauth,\n QCryptoTLSCreds *tlscreds,\n bool password,\n bool sasl,\n bool websocket,\n Error **errp)\n{\n \/*\n * We have a choice of 3 authentication options\n *\n * 1. none\n * 2. vnc\n * 3. sasl\n *\n * The channel can be run in 2 modes\n *\n * 1. clear\n * 2. tls\n *\n * And TLS can use 2 types of credentials\n *\n * 1. anon\n * 2. x509\n *\n * We thus have 9 possible logical combinations\n *\n * 1. clear + none\n * 2. clear + vnc\n * 3. clear + sasl\n * 4. tls + anon + none\n * 5. tls + anon + vnc\n * 6. tls + anon + sasl\n * 7. tls + x509 + none\n * 8. tls + x509 + vnc\n * 9. tls + x509 + sasl\n *\n * These need to be mapped into the VNC auth schemes\n * in an appropriate manner. In regular VNC, all the\n * TLS options get mapped into VNC_AUTH_VENCRYPT\n * sub-auth types.\n *\n * In websockets, the https:\/\/ protocol already provides\n * TLS support, so there is no need to make use of the\n * VeNCrypt extension. Furthermore, websockets browser\n * clients could not use VeNCrypt even if they wanted to,\n * as they cannot control when the TLS handshake takes\n * place. Thus there is no option but to rely on https:\/\/,\n * meaning combinations 4->6 and 7->9 will be mapped to\n * VNC auth schemes in the same way as combos 1->3.\n *\n * Regardless of fact that we have a different mapping to\n * VNC auth mechs for plain VNC vs websockets VNC, the end\n * result has the same security characteristics.\n *\/\n if (websocket || !tlscreds) {\n if (password) {\n VNC_DEBUG(\"Initializing VNC server with password auth\\n\");\n *auth = VNC_AUTH_VNC;\n } else if (sasl) {\n VNC_DEBUG(\"Initializing VNC server with SASL auth\\n\");\n *auth = VNC_AUTH_SASL;\n } else {\n VNC_DEBUG(\"Initializing VNC server with no auth\\n\");\n *auth = VNC_AUTH_NONE;\n }\n *subauth = VNC_AUTH_INVALID;\n } else {\n bool is_x509 = object_dynamic_cast(OBJECT(tlscreds),\n TYPE_QCRYPTO_TLS_CREDS_X509) != NULL;\n bool is_anon = object_dynamic_cast(OBJECT(tlscreds),\n TYPE_QCRYPTO_TLS_CREDS_ANON) != NULL;\n\n if (!is_x509 && !is_anon) {\n error_setg(errp,\n \"Unsupported TLS cred type %s\",\n object_get_typename(OBJECT(tlscreds)));\n return -1;\n }\n *auth = VNC_AUTH_VENCRYPT;\n if (password) {\n if (is_x509) {\n VNC_DEBUG(\"Initializing VNC server with x509 password auth\\n\");\n *subauth = VNC_AUTH_VENCRYPT_X509VNC;\n } else {\n VNC_DEBUG(\"Initializing VNC server with TLS password auth\\n\");\n *subauth = VNC_AUTH_VENCRYPT_TLSVNC;\n }\n\n } else if (sasl) {\n if (is_x509) {\n VNC_DEBUG(\"Initializing VNC server with x509 SASL auth\\n\");\n *subauth = VNC_AUTH_VENCRYPT_X509SASL;\n } else {\n VNC_DEBUG(\"Initializing VNC server with TLS SASL auth\\n\");\n *subauth = VNC_AUTH_VENCRYPT_TLSSASL;\n }\n } else {\n if (is_x509) {\n VNC_DEBUG(\"Initializing VNC server with x509 no auth\\n\");\n *subauth = VNC_AUTH_VENCRYPT_X509NONE;\n } else {\n VNC_DEBUG(\"Initializing VNC server with TLS no auth\\n\");\n *subauth = VNC_AUTH_VENCRYPT_TLSNONE;\n }\n }\n }\n return 0;\n}","target":0,"code_token_length":1024,"total_token_length":1355,"max_tokens_setting":2048} +{"idx":114919,"func":"Status ConstantFolding::MaterializeBroadcastGradientArgs(\n const NodeDef& node, const GraphProperties& properties) {\n const NodeDef* shape_node1 = node_map_->GetNode(node.input(0));\n const NodeDef* shape_node2 = node_map_->GetNode(node.input(1));\n if (shape_node1 == nullptr ||\n (shape_node1->op() != \"Shape\" && !IsReallyConstant(*shape_node1)) ||\n shape_node2 == nullptr ||\n (shape_node2->op() != \"Shape\" && !IsReallyConstant(*shape_node2))) {\n return Status::OK();\n }\n\n \/\/ Don't optimize this again if it was already optimized and folded.\n if (OptimizedNodeExists(node, \"-folded-1\") ||\n OptimizedNodeExists(node, \"-folded-2\")) {\n return Status::OK();\n }\n int64_t min_id = 0;\n BCast::Vec shape1;\n if (!ExtractShape(*shape_node1, properties, &shape1, &min_id)) {\n return Status::OK();\n }\n BCast::Vec shape2;\n if (!ExtractShape(*shape_node2, properties, &shape2, &min_id)) {\n return Status::OK();\n }\n \/\/ A value of -1 means we don't known anything about the dimension. Replace\n \/\/ the -1 values with unique dimension ids since we don't want two '-1'\n \/\/ dimensions to be considered equal.\n for (auto& id : shape1) {\n if (id == -1) {\n id = --min_id;\n }\n }\n for (auto& id : shape2) {\n if (id == -1) {\n id = --min_id;\n }\n }\n\n \/\/ Beware: the reduction dimensions computed by the BCast class are valid iff\n \/\/ we assume that two distinct symbolic dimensions can't be equal and a\n \/\/ symbolic dimension can't be equal to 1. This is often but not always true,\n \/\/ so to make this optimization safe we filter out these cases.\n const int common_dims = std::min(shape1.size(), shape2.size());\n for (int i = 0; i < common_dims; ++i) {\n if (shape1[i] >= 0 && shape2[i] >= 0) {\n continue;\n }\n if (shape1[i] != shape2[i]) {\n \/\/ We're either dealing with 2 different symbolic dimensions or a symbolic\n \/\/ and a know dimensions. We can't be sure whether both are equal or not,\n \/\/ so we can't be sure whether we'll be broadcasting or not.\n return Status::OK();\n }\n }\n \/\/ These extra dims could be equal to 1, in which case there is no\n \/\/ broadcasting. It could also be greater than 1, in which case there would\n \/\/ be broadcasting. Since we don't know, we'll just punt.\n for (int i = common_dims, end = shape1.size(); i < end; ++i) {\n if (shape1[i] < 0) {\n return Status::OK();\n }\n }\n for (int i = common_dims, end = shape2.size(); i < end; ++i) {\n if (shape2[i] < 0) {\n return Status::OK();\n }\n }\n\n BCast bcast(shape1, shape2);\n if (!bcast.IsValid()) {\n return Status::OK();\n }\n\n BCast::Vec reduce_dims[2];\n reduce_dims[0] = bcast.grad_x_reduce_idx();\n reduce_dims[1] = bcast.grad_y_reduce_idx();\n\n TF_RETURN_IF_ERROR(CheckAttrExists(node, \"T\"));\n const DataType type = node.attr().at(\"T\").type();\n NodeDef* out[2];\n for (int j = 0; j < 2; ++j) {\n int reduction_indices = reduce_dims[j].size();\n Tensor value(type, TensorShape({reduction_indices}));\n for (int i = 0; i < reduction_indices; ++i) {\n if (type == DT_INT32) {\n value.vec()(i) = reduce_dims[j][i];\n } else {\n value.vec()(i) = reduce_dims[j][i];\n }\n }\n string const_name =\n OptimizedNodeName(node, strings::StrCat(\"-bcastargs-\", j));\n out[j] = node_map_->GetNode(const_name);\n if (out[j] == nullptr) {\n out[j] = graph_->add_node();\n TF_RETURN_IF_ERROR(\n CreateNodeDef(const_name, TensorValue(&value), out[j]));\n out[j]->set_device(node.device());\n node_map_->AddNode(const_name, out[j]);\n string ctrl_dep =\n AddControlDependency(node.name(), graph_, node_map_.get());\n *out[j]->add_input() = ctrl_dep;\n node_map_->AddOutput(NodeName(ctrl_dep), const_name);\n }\n }\n\n \/\/ We make a copy here since we might mutate the set.\n const auto outputs = node_map_->GetOutputs(node.name());\n for (NodeDef* output : outputs) {\n for (int k = 0; k < output->input_size(); ++k) {\n int port;\n string node_name = ParseNodeName(output->input(k), &port);\n if (node_name == node.name() && port >= 0 && port < 2 && out[port]) {\n *output->mutable_input(k) = out[port]->name();\n node_map_->UpdateInput(output->name(), node_name, out[port]->name());\n }\n }\n }\n\n return Status::OK();\n}","target":0,"code_token_length":1234,"total_token_length":1565,"max_tokens_setting":2048} +{"idx":441424,"func":"void RGWPostObj_ObjStore_S3::send_response()\n{\n if (op_ret == 0 && parts.count(\"success_action_redirect\")) {\n string redirect;\n\n part_str(parts, \"success_action_redirect\", &redirect);\n\n string tenant;\n string bucket;\n string key;\n string etag_str = \"\\\"\";\n\n etag_str.append(etag);\n etag_str.append(\"\\\"\");\n\n string etag_url;\n\n url_encode(s->bucket_tenant, tenant); \/* surely overkill, but cheap *\/\n url_encode(s->bucket_name, bucket);\n url_encode(s->object.name, key);\n url_encode(etag_str, etag_url);\n\n if (!s->bucket_tenant.empty()) {\n \/*\n * What we really would like is to quaily the bucket name, so\n * that the client could simply copy it and paste into next request.\n * Unfortunately, in S3 we cannot know if the client will decide\n * to come through DNS, with \"bucket.tenant\" sytanx, or through\n * URL with \"tenant\\bucket\" syntax. Therefore, we provide the\n * tenant separately.\n *\/\n redirect.append(\"?tenant=\");\n redirect.append(tenant);\n redirect.append(\"&bucket=\");\n redirect.append(bucket);\n } else {\n redirect.append(\"?bucket=\");\n redirect.append(bucket);\n }\n redirect.append(\"&key=\");\n redirect.append(key);\n redirect.append(\"&etag=\");\n redirect.append(etag_url);\n\n int r = check_utf8(redirect.c_str(), redirect.size());\n if (r < 0) {\n op_ret = r;\n goto done;\n }\n dump_redirect(s, redirect);\n op_ret = STATUS_REDIRECT;\n } else if (op_ret == 0 && parts.count(\"success_action_status\")) {\n string status_string;\n uint32_t status_int;\n\n part_str(parts, \"success_action_status\", &status_string);\n\n int r = stringtoul(status_string, &status_int);\n if (r < 0) {\n op_ret = r;\n goto done;\n }\n\n switch (status_int) {\n case 200:\n\tbreak;\n case 201:\n\top_ret = STATUS_CREATED;\n\tbreak;\n default:\n\top_ret = STATUS_NO_CONTENT;\n\tbreak;\n }\n } else if (! op_ret) {\n op_ret = STATUS_NO_CONTENT;\n }\n\ndone:\n if (op_ret == STATUS_CREATED) {\n for (auto &it : crypt_http_responses)\n dump_header(s, it.first, it.second);\n s->formatter->open_object_section(\"PostResponse\");\n if (g_conf->rgw_dns_name.length())\n s->formatter->dump_format(\"Location\", \"%s\/%s\",\n\t\t\t\ts->info.script_uri.c_str(),\n\t\t\t\ts->object.name.c_str());\n if (!s->bucket_tenant.empty())\n s->formatter->dump_string(\"Tenant\", s->bucket_tenant);\n s->formatter->dump_string(\"Bucket\", s->bucket_name);\n s->formatter->dump_string(\"Key\", s->object.name);\n s->formatter->close_section();\n }\n s->err.message = err_msg;\n set_req_state_err(s, op_ret);\n dump_errno(s);\n if (op_ret >= 0) {\n dump_content_length(s, s->formatter->get_len());\n }\n end_header(s, this);\n if (op_ret != STATUS_CREATED)\n return;\n\n rgw_flush_formatter_and_reset(s, s->formatter);\n}","target":0,"code_token_length":742,"total_token_length":1073,"max_tokens_setting":2048} +{"idx":378811,"func":"static SC_HTMLState sc_html_parse_tag(SC_HTMLParser *parser)\n{\n\tgchar buf[SC_HTMLBUFSIZE];\n\tSC_HTMLTag *tag;\n\n\tsc_html_get_parenthesis(parser, buf, sizeof(buf));\n\n\ttag = sc_html_get_tag(buf);\n\n\tparser->state = SC_HTML_UNKNOWN;\n\tif (!tag) return SC_HTML_UNKNOWN;\n\n\tif (!strcmp(tag->name, \"br\")) {\n\t\tparser->space = FALSE;\n\t\tsc_html_append_char(parser, '\\n');\n\t\tparser->state = SC_HTML_BR;\n\t} else if (!strcmp(tag->name, \"a\")) {\n\t\tGList *cur;\n\t\tfor (cur = tag->attr; cur != NULL; cur = cur->next) {\n\t\t\tif (cur->data && !strcmp(((SC_HTMLAttr *)cur->data)->name, \"href\")) {\n\t\t\t\tg_free(parser->href);\n\t\t\t\tparser->href = g_strdup(((SC_HTMLAttr *)cur->data)->value);\n\t\t\t\tdecode_href(parser);\n\t\t\t\tparser->state = SC_HTML_HREF_BEG;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} else if (!strcmp(tag->name, \"\/a\")) {\n\t\tparser->state = SC_HTML_HREF;\n\t} else if (!strcmp(tag->name, \"p\")) {\n\t\tparser->space = FALSE;\n\t\tif (!parser->empty_line) {\n\t\t\tparser->space = FALSE;\n\t\t\tif (!parser->newline) sc_html_append_char(parser, '\\n');\n\t\t\tsc_html_append_char(parser, '\\n');\n\t\t}\n\t\tparser->state = SC_HTML_PAR;\n\t} else if (!strcmp(tag->name, \"pre\")) {\n\t\tparser->pre = TRUE;\n\t\tparser->state = SC_HTML_PRE;\n\t} else if (!strcmp(tag->name, \"\/pre\")) {\n\t\tparser->pre = FALSE;\n\t\tparser->state = SC_HTML_NORMAL;\n\t} else if (!strcmp(tag->name, \"hr\")) {\n\t\tif (!parser->newline) {\n\t\t\tparser->space = FALSE;\n\t\t\tsc_html_append_char(parser, '\\n');\n\t\t}\n\t\tsc_html_append_str(parser, HR_STR \"\\n\", -1);\n\t\tparser->state = SC_HTML_HR;\n\t} else if (!strcmp(tag->name, \"div\") ||\n\t\t !strcmp(tag->name, \"ul\") ||\n\t\t !strcmp(tag->name, \"li\") ||\n\t\t !strcmp(tag->name, \"table\") ||\n\t\t !strcmp(tag->name, \"tr\") ||\n\t\t (tag->name[0] == 'h' && g_ascii_isdigit(tag->name[1]))) {\n\t\tif (!parser->newline) {\n\t\t\tparser->space = FALSE;\n\t\t\tsc_html_append_char(parser, '\\n');\n\t\t}\n\t\tparser->state = SC_HTML_NORMAL;\n\t} else if (!strcmp(tag->name, \"\/table\") ||\n\t\t (tag->name[0] == '\/' &&\n\t\t tag->name[1] == 'h' &&\n\t\t g_ascii_isdigit(tag->name[1]))) {\n\t\tif (!parser->empty_line) {\n\t\t\tparser->space = FALSE;\n\t\t\tif (!parser->newline) sc_html_append_char(parser, '\\n');\n\t\t\tsc_html_append_char(parser, '\\n');\n\t\t}\n\t\tparser->state = SC_HTML_NORMAL;\n\t} else if (!strcmp(tag->name, \"\/div\") ||\n\t\t !strcmp(tag->name, \"\/ul\") ||\n\t\t !strcmp(tag->name, \"\/li\")) {\n\t\tif (!parser->newline) {\n\t\t\tparser->space = FALSE;\n\t\t\tsc_html_append_char(parser, '\\n');\n\t\t}\n\t\tparser->state = SC_HTML_NORMAL;\n\t\t\t}\n\n\tsc_html_free_tag(tag);\n\n\treturn parser->state;\n}","target":0,"code_token_length":765,"total_token_length":1096,"max_tokens_setting":2048} +{"idx":123886,"func":"static void ov518_configure(struct gspca_dev *gspca_dev)\n{\n\tstruct sd *sd = (struct sd *) gspca_dev;\n\n\t\/* For 518 and 518+ *\/\n\tstatic const struct ov_regvals init_518[] = {\n\t\t{ R51x_SYS_RESET,\t0x40 },\n\t\t{ R51x_SYS_INIT,\t0xe1 },\n\t\t{ R51x_SYS_RESET,\t0x3e },\n\t\t{ R51x_SYS_INIT,\t0xe1 },\n\t\t{ R51x_SYS_RESET,\t0x00 },\n\t\t{ R51x_SYS_INIT,\t0xe1 },\n\t\t{ 0x46,\t\t\t0x00 },\n\t\t{ 0x5d,\t\t\t0x03 },\n\t};\n\n\tstatic const struct ov_regvals norm_518[] = {\n\t\t{ R51x_SYS_SNAP,\t0x02 }, \/* Reset *\/\n\t\t{ R51x_SYS_SNAP,\t0x01 }, \/* Enable *\/\n\t\t{ 0x31,\t\t\t0x0f },\n\t\t{ 0x5d,\t\t\t0x03 },\n\t\t{ 0x24,\t\t\t0x9f },\n\t\t{ 0x25,\t\t\t0x90 },\n\t\t{ 0x20,\t\t\t0x00 },\n\t\t{ 0x51,\t\t\t0x04 },\n\t\t{ 0x71,\t\t\t0x19 },\n\t\t{ 0x2f,\t\t\t0x80 },\n\t};\n\n\tstatic const struct ov_regvals norm_518_p[] = {\n\t\t{ R51x_SYS_SNAP,\t0x02 }, \/* Reset *\/\n\t\t{ R51x_SYS_SNAP,\t0x01 }, \/* Enable *\/\n\t\t{ 0x31,\t\t\t0x0f },\n\t\t{ 0x5d,\t\t\t0x03 },\n\t\t{ 0x24,\t\t\t0x9f },\n\t\t{ 0x25,\t\t\t0x90 },\n\t\t{ 0x20,\t\t\t0x60 },\n\t\t{ 0x51,\t\t\t0x02 },\n\t\t{ 0x71,\t\t\t0x19 },\n\t\t{ 0x40,\t\t\t0xff },\n\t\t{ 0x41,\t\t\t0x42 },\n\t\t{ 0x46,\t\t\t0x00 },\n\t\t{ 0x33,\t\t\t0x04 },\n\t\t{ 0x21,\t\t\t0x19 },\n\t\t{ 0x3f,\t\t\t0x10 },\n\t\t{ 0x2f,\t\t\t0x80 },\n\t};\n\n\t\/* First 5 bits of custom ID reg are a revision ID on OV518 *\/\n\tsd->revision = reg_r(sd, R51x_SYS_CUST_ID) & 0x1f;\n\tgspca_dbg(gspca_dev, D_PROBE, \"Device revision %d\\n\", sd->revision);\n\n\twrite_regvals(sd, init_518, ARRAY_SIZE(init_518));\n\n\t\/* Set LED GPIO pin to output mode *\/\n\treg_w_mask(sd, R518_GPIO_CTL, 0x00, 0x02);\n\n\tswitch (sd->bridge) {\n\tcase BRIDGE_OV518:\n\t\twrite_regvals(sd, norm_518, ARRAY_SIZE(norm_518));\n\t\tbreak;\n\tcase BRIDGE_OV518PLUS:\n\t\twrite_regvals(sd, norm_518_p, ARRAY_SIZE(norm_518_p));\n\t\tbreak;\n\t}\n\n\tov51x_upload_quan_tables(sd);\n\n\treg_w(sd, 0x2f, 0x80);\n}","target":0,"code_token_length":877,"total_token_length":1208,"max_tokens_setting":2048} +{"idx":412022,"func":"relpTcpSetRemHost(relpTcp_t *pThis, struct sockaddr *pAddr)\n{\n\trelpEngine_t *pEngine;\n\tint error;\n\tunsigned char szIP[NI_MAXHOST] = \"\";\n\tunsigned char szHname[NI_MAXHOST] = \"\";\n\tstruct addrinfo hints, *res;\n\tsize_t len;\n\t\n\tENTER_RELPFUNC;\n\tRELPOBJ_assert(pThis, Tcp);\n\tpEngine = pThis->pEngine;\n\tassert(pAddr != NULL);\n\n\terror = getnameinfo(pAddr, SALEN(pAddr), (char*)szIP, sizeof(szIP), NULL, 0, NI_NUMERICHOST);\n\tif(error) {\n\t\tpThis->pEngine->dbgprint(\"Malformed from address %s\\n\", gai_strerror(error));\n\t\tstrcpy((char*)szHname, \"???\");\n\t\tstrcpy((char*)szIP, \"???\");\n\t\tABORT_FINALIZE(RELP_RET_INVALID_HNAME);\n\t}\n\n\tif(pEngine->bEnableDns) {\n\t\terror = getnameinfo(pAddr, SALEN(pAddr), (char*)szHname, sizeof(szHname), NULL, 0, NI_NAMEREQD);\n\t\tif(error == 0) {\n\t\t\tmemset (&hints, 0, sizeof (struct addrinfo));\n\t\t\thints.ai_flags = AI_NUMERICHOST;\n\t\t\thints.ai_socktype = SOCK_STREAM;\n\t\t\t\/* we now do a lookup once again. This one should fail,\n\t\t\t * because we should not have obtained a non-numeric address. If\n\t\t\t * we got a numeric one, someone messed with DNS!\n\t\t\t *\/\n\t\t\tif(getaddrinfo((char*)szHname, NULL, &hints, &res) == 0) {\n\t\t\t\tfreeaddrinfo (res);\n\t\t\t\t\/* OK, we know we have evil, so let's indicate this to our caller *\/\n\t\t\t\tsnprintf((char*)szHname, NI_MAXHOST, \"[MALICIOUS:IP=%s]\", szIP);\n\t\t\t\tpEngine->dbgprint(\"Malicious PTR record, IP = \\\"%s\\\" HOST = \\\"%s\\\"\", szIP, szHname);\n\t\t\t\tiRet = RELP_RET_MALICIOUS_HNAME;\n\t\t\t}\n\t\t} else {\n\t\t\tstrcpy((char*)szHname, (char*)szIP);\n\t\t}\n\t} else {\n\t\tstrcpy((char*)szHname, (char*)szIP);\n\t}\n\n\t\/* We now have the names, so now let's allocate memory and store them permanently.\n\t * (side note: we may hold on to these values for quite a while, thus we trim their\n\t * memory consumption)\n\t *\/\n\tlen = strlen((char*)szIP) + 1; \/* +1 for \\0 byte *\/\n\tif((pThis->pRemHostIP = malloc(len)) == NULL)\n\t\tABORT_FINALIZE(RELP_RET_OUT_OF_MEMORY);\n\tmemcpy(pThis->pRemHostIP, szIP, len);\n\n\tlen = strlen((char*)szHname) + 1; \/* +1 for \\0 byte *\/\n\tif((pThis->pRemHostName = malloc(len)) == NULL) {\n\t\tfree(pThis->pRemHostIP); \/* prevent leak *\/\n\t\tpThis->pRemHostIP = NULL;\n\t\tABORT_FINALIZE(RELP_RET_OUT_OF_MEMORY);\n\t}\n\tmemcpy(pThis->pRemHostName, szHname, len);\n\nfinalize_it:\n\tLEAVE_RELPFUNC;\n}","target":0,"code_token_length":718,"total_token_length":1049,"max_tokens_setting":2048} +{"idx":301874,"func":"static int dn_accept(struct socket *sock, struct socket *newsock, int flags)\n{\n\tstruct sock *sk = sock->sk, *newsk;\n\tstruct sk_buff *skb = NULL;\n\tstruct dn_skb_cb *cb;\n\tunsigned char menuver;\n\tint err = 0;\n\tunsigned char type;\n\tlong timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);\n\tstruct dst_entry *dst;\n\n\tlock_sock(sk);\n\n\tif (sk->sk_state != TCP_LISTEN || DN_SK(sk)->state != DN_O) {\n\t\trelease_sock(sk);\n\t\treturn -EINVAL;\n\t}\n\n\tskb = skb_dequeue(&sk->sk_receive_queue);\n\tif (skb == NULL) {\n\t\tskb = dn_wait_for_connect(sk, &timeo);\n\t\tif (IS_ERR(skb)) {\n\t\t\trelease_sock(sk);\n\t\t\treturn PTR_ERR(skb);\n\t\t}\n\t}\n\n\tcb = DN_SKB_CB(skb);\n\tsk->sk_ack_backlog--;\n\tnewsk = dn_alloc_sock(sock_net(sk), newsock, sk->sk_allocation, 0);\n\tif (newsk == NULL) {\n\t\trelease_sock(sk);\n\t\tkfree_skb(skb);\n\t\treturn -ENOBUFS;\n\t}\n\trelease_sock(sk);\n\n\tdst = skb_dst(skb);\n\tsk_dst_set(newsk, dst);\n\tskb_dst_set(skb, NULL);\n\n\tDN_SK(newsk)->state = DN_CR;\n\tDN_SK(newsk)->addrrem = cb->src_port;\n\tDN_SK(newsk)->services_rem = cb->services;\n\tDN_SK(newsk)->info_rem = cb->info;\n\tDN_SK(newsk)->segsize_rem = cb->segsize;\n\tDN_SK(newsk)->accept_mode = DN_SK(sk)->accept_mode;\n\n\tif (DN_SK(newsk)->segsize_rem < 230)\n\t\tDN_SK(newsk)->segsize_rem = 230;\n\n\tif ((DN_SK(newsk)->services_rem & NSP_FC_MASK) == NSP_FC_NONE)\n\t\tDN_SK(newsk)->max_window = decnet_no_fc_max_cwnd;\n\n\tnewsk->sk_state = TCP_LISTEN;\n\tmemcpy(&(DN_SK(newsk)->addr), &(DN_SK(sk)->addr), sizeof(struct sockaddr_dn));\n\n\t\/*\n\t * If we are listening on a wild socket, we don't want\n\t * the newly created socket on the wrong hash queue.\n\t *\/\n\tDN_SK(newsk)->addr.sdn_flags &= ~SDF_WILD;\n\n\tskb_pull(skb, dn_username2sockaddr(skb->data, skb->len, &(DN_SK(newsk)->addr), &type));\n\tskb_pull(skb, dn_username2sockaddr(skb->data, skb->len, &(DN_SK(newsk)->peer), &type));\n\t*(__le16 *)(DN_SK(newsk)->peer.sdn_add.a_addr) = cb->src;\n\t*(__le16 *)(DN_SK(newsk)->addr.sdn_add.a_addr) = cb->dst;\n\n\tmenuver = *skb->data;\n\tskb_pull(skb, 1);\n\n\tif (menuver & DN_MENUVER_ACC)\n\t\tdn_access_copy(skb, &(DN_SK(newsk)->accessdata));\n\n\tif (menuver & DN_MENUVER_USR)\n\t\tdn_user_copy(skb, &(DN_SK(newsk)->conndata_in));\n\n\tif (menuver & DN_MENUVER_PRX)\n\t\tDN_SK(newsk)->peer.sdn_flags |= SDF_PROXY;\n\n\tif (menuver & DN_MENUVER_UIC)\n\t\tDN_SK(newsk)->peer.sdn_flags |= SDF_UICPROXY;\n\n\tkfree_skb(skb);\n\n\tmemcpy(&(DN_SK(newsk)->conndata_out), &(DN_SK(sk)->conndata_out),\n\t\tsizeof(struct optdata_dn));\n\tmemcpy(&(DN_SK(newsk)->discdata_out), &(DN_SK(sk)->discdata_out),\n\t\tsizeof(struct optdata_dn));\n\n\tlock_sock(newsk);\n\terr = dn_hash_sock(newsk);\n\tif (err == 0) {\n\t\tsock_reset_flag(newsk, SOCK_ZAPPED);\n\t\tdn_send_conn_ack(newsk);\n\n\t\t\/*\n\t\t * Here we use sk->sk_allocation since although the conn conf is\n\t\t * for the newsk, the context is the old socket.\n\t\t *\/\n\t\tif (DN_SK(newsk)->accept_mode == ACC_IMMED)\n\t\t\terr = dn_confirm_accept(newsk, &timeo,\n\t\t\t\t\t\tsk->sk_allocation);\n\t}\n\trelease_sock(newsk);\n\treturn err;\n}","target":0,"code_token_length":929,"total_token_length":1260,"max_tokens_setting":2048} +{"idx":344376,"func":"goa_ews_client_autodiscover (GoaEwsClient *client,\n const gchar *email,\n const gchar *password,\n const gchar *username,\n const gchar *server,\n gboolean accept_ssl_errors,\n GCancellable *cancellable,\n GAsyncReadyCallback callback,\n gpointer user_data)\n{\n AutodiscoverData *data;\n AutodiscoverAuthData *auth;\n gchar *url1;\n gchar *url2;\n xmlDoc *doc;\n xmlOutputBuffer *buf;\n\n g_return_if_fail (GOA_IS_EWS_CLIENT (client));\n g_return_if_fail (email != NULL || email[0] != '\\0');\n g_return_if_fail (password != NULL || password[0] != '\\0');\n g_return_if_fail (username != NULL || username[0] != '\\0');\n g_return_if_fail (server != NULL || server[0] != '\\0');\n g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));\n\n doc = ews_client_create_autodiscover_xml (email);\n buf = xmlAllocOutputBuffer (NULL);\n xmlNodeDumpOutput (buf, doc, xmlDocGetRootElement (doc), 0, 1, NULL);\n xmlOutputBufferFlush (buf);\n\n url1 = g_strdup_printf (\"https:\/\/%s\/autodiscover\/autodiscover.xml\", server);\n url2 = g_strdup_printf (\"https:\/\/autodiscover.%s\/autodiscover\/autodiscover.xml\", server);\n\n \/* http:\/\/msdn.microsoft.com\/en-us\/library\/ee332364.aspx says we are\n * supposed to try $domain and then autodiscover.$domain. But some\n * people have broken firewalls on the former which drop packets\n * instead of rejecting connections, and make the request take ages\n * to time out. So run both queries in parallel and let the fastest\n * (successful) one win.\n *\/\n data = g_slice_new0 (AutodiscoverData);\n data->buf = buf;\n data->res = g_simple_async_result_new (G_OBJECT (client), callback, user_data, goa_ews_client_autodiscover);\n data->msgs[0] = ews_client_create_msg_for_url (url1, buf);\n data->msgs[1] = ews_client_create_msg_for_url (url2, buf);\n data->session = soup_session_async_new_with_options (SOUP_SESSION_SSL_USE_SYSTEM_CA_FILE, TRUE,\n SOUP_SESSION_SSL_STRICT, FALSE,\n SOUP_SESSION_USE_NTLM, TRUE,\n SOUP_SESSION_USE_THREAD_CONTEXT, TRUE,\n NULL);\n data->accept_ssl_errors = accept_ssl_errors;\n\n if (cancellable != NULL)\n {\n data->cancellable = g_object_ref (cancellable);\n data->cancellable_id = g_cancellable_connect (data->cancellable,\n G_CALLBACK (ews_client_autodiscover_cancelled_cb),\n data,\n NULL);\n g_simple_async_result_set_check_cancellable (data->res, data->cancellable);\n }\n\n auth = g_slice_new0 (AutodiscoverAuthData);\n auth->username = g_strdup (username);\n auth->password = g_strdup (password);\n g_signal_connect_data (data->session,\n \"authenticate\",\n G_CALLBACK (ews_client_authenticate),\n auth,\n ews_client_autodiscover_auth_data_free,\n 0);\n\n soup_session_queue_message (data->session, data->msgs[0], ews_client_autodiscover_response_cb, data);\n soup_session_queue_message (data->session, data->msgs[1], ews_client_autodiscover_response_cb, data);\n\n g_free (url2);\n g_free (url1);\n xmlFreeDoc (doc);\n}","target":1,"code_token_length":836,"total_token_length":1167,"max_tokens_setting":2048} +{"idx":126373,"func":"static int fr_ioctl(struct net_device *dev, struct ifreq *ifr)\n{\n\tfr_proto __user *fr_s = ifr->ifr_settings.ifs_ifsu.fr;\n\tconst size_t size = sizeof(fr_proto);\n\tfr_proto new_settings;\n\thdlc_device *hdlc = dev_to_hdlc(dev);\n\tfr_proto_pvc pvc;\n\tint result;\n\n\tswitch (ifr->ifr_settings.type) {\n\tcase IF_GET_PROTO:\n\t\tif (dev_to_hdlc(dev)->proto != &proto) \/* Different proto *\/\n\t\t\treturn -EINVAL;\n\t\tifr->ifr_settings.type = IF_PROTO_FR;\n\t\tif (ifr->ifr_settings.size < size) {\n\t\t\tifr->ifr_settings.size = size; \/* data size wanted *\/\n\t\t\treturn -ENOBUFS;\n\t\t}\n\t\tif (copy_to_user(fr_s, &state(hdlc)->settings, size))\n\t\t\treturn -EFAULT;\n\t\treturn 0;\n\n\tcase IF_PROTO_FR:\n\t\tif (!capable(CAP_NET_ADMIN))\n\t\t\treturn -EPERM;\n\n\t\tif (dev->flags & IFF_UP)\n\t\t\treturn -EBUSY;\n\n\t\tif (copy_from_user(&new_settings, fr_s, size))\n\t\t\treturn -EFAULT;\n\n\t\tif (new_settings.lmi == LMI_DEFAULT)\n\t\t\tnew_settings.lmi = LMI_ANSI;\n\n\t\tif ((new_settings.lmi != LMI_NONE &&\n\t\t new_settings.lmi != LMI_ANSI &&\n\t\t new_settings.lmi != LMI_CCITT &&\n\t\t new_settings.lmi != LMI_CISCO) ||\n\t\t new_settings.t391 < 1 ||\n\t\t new_settings.t392 < 2 ||\n\t\t new_settings.n391 < 1 ||\n\t\t new_settings.n392 < 1 ||\n\t\t new_settings.n393 < new_settings.n392 ||\n\t\t new_settings.n393 > 32 ||\n\t\t (new_settings.dce != 0 &&\n\t\t new_settings.dce != 1))\n\t\t\treturn -EINVAL;\n\n\t\tresult=hdlc->attach(dev, ENCODING_NRZ,PARITY_CRC16_PR1_CCITT);\n\t\tif (result)\n\t\t\treturn result;\n\n\t\tif (dev_to_hdlc(dev)->proto != &proto) { \/* Different proto *\/\n\t\t\tresult = attach_hdlc_protocol(dev, &proto,\n\t\t\t\t\t\t sizeof(struct frad_state));\n\t\t\tif (result)\n\t\t\t\treturn result;\n\t\t\tstate(hdlc)->first_pvc = NULL;\n\t\t\tstate(hdlc)->dce_pvc_count = 0;\n\t\t}\n\t\tmemcpy(&state(hdlc)->settings, &new_settings, size);\n\t\tdev->type = ARPHRD_FRAD;\n\t\treturn 0;\n\n\tcase IF_PROTO_FR_ADD_PVC:\n\tcase IF_PROTO_FR_DEL_PVC:\n\tcase IF_PROTO_FR_ADD_ETH_PVC:\n\tcase IF_PROTO_FR_DEL_ETH_PVC:\n\t\tif (dev_to_hdlc(dev)->proto != &proto) \/* Different proto *\/\n\t\t\treturn -EINVAL;\n\n\t\tif (!capable(CAP_NET_ADMIN))\n\t\t\treturn -EPERM;\n\n\t\tif (copy_from_user(&pvc, ifr->ifr_settings.ifs_ifsu.fr_pvc,\n\t\t\t\t sizeof(fr_proto_pvc)))\n\t\t\treturn -EFAULT;\n\n\t\tif (pvc.dlci <= 0 || pvc.dlci >= 1024)\n\t\t\treturn -EINVAL;\t\/* Only 10 bits, DLCI 0 reserved *\/\n\n\t\tif (ifr->ifr_settings.type == IF_PROTO_FR_ADD_ETH_PVC ||\n\t\t ifr->ifr_settings.type == IF_PROTO_FR_DEL_ETH_PVC)\n\t\t\tresult = ARPHRD_ETHER; \/* bridged Ethernet device *\/\n\t\telse\n\t\t\tresult = ARPHRD_DLCI;\n\n\t\tif (ifr->ifr_settings.type == IF_PROTO_FR_ADD_PVC ||\n\t\t ifr->ifr_settings.type == IF_PROTO_FR_ADD_ETH_PVC)\n\t\t\treturn fr_add_pvc(dev, pvc.dlci, result);\n\t\telse\n\t\t\treturn fr_del_pvc(hdlc, pvc.dlci, result);\n\t}\n\n\treturn -EINVAL;\n}","target":0,"code_token_length":845,"total_token_length":1176,"max_tokens_setting":2048} +{"idx":345969,"func":"SMBC_attr_server(TALLOC_CTX *ctx,\n SMBCCTX *context,\n const char *server,\n uint16_t port,\n const char *share,\n char **pp_workgroup,\n char **pp_username,\n char **pp_password)\n{\n int flags;\n\tstruct cli_state *ipc_cli = NULL;\n\tstruct rpc_pipe_client *pipe_hnd = NULL;\n NTSTATUS nt_status;\n\tSMBCSRV *srv=NULL;\n\tSMBCSRV *ipc_srv=NULL;\n\n\t\/*\n\t * Use srv->cli->desthost and srv->cli->share instead of\n\t * server and share below to connect to the actual share,\n\t * i.e., a normal share or a referred share from\n\t * 'msdfs proxy' share.\n\t *\/\n\tsrv = SMBC_server(ctx, context, true, server, port, share,\n\t\t\tpp_workgroup, pp_username, pp_password);\n\tif (!srv) {\n\t\treturn NULL;\n\t}\n\tserver = smbXcli_conn_remote_name(srv->cli->conn);\n\tshare = srv->cli->share;\n\n \/*\n * See if we've already created this special connection. Reference\n * our \"special\" share name '*IPC$', which is an impossible real share\n * name due to the leading asterisk.\n *\/\n ipc_srv = SMBC_find_server(ctx, context, server, \"*IPC$\",\n pp_workgroup, pp_username, pp_password);\n if (!ipc_srv) {\n\n \/* We didn't find a cached connection. Get the password *\/\n\t\tif (!*pp_password || (*pp_password)[0] == '\\0') {\n \/* ... then retrieve it now. *\/\n\t\t\tSMBC_call_auth_fn(ctx, context, server, share,\n pp_workgroup,\n pp_username,\n pp_password);\n\t\t\tif (!*pp_workgroup || !*pp_username || !*pp_password) {\n\t\t\t\terrno = ENOMEM;\n\t\t\t\treturn NULL;\n\t\t\t}\n }\n\n flags = 0;\n if (smbc_getOptionUseKerberos(context)) {\n flags |= CLI_FULL_CONNECTION_USE_KERBEROS;\n }\n if (smbc_getOptionUseCCache(context)) {\n flags |= CLI_FULL_CONNECTION_USE_CCACHE;\n }\n\n nt_status = cli_full_connection(&ipc_cli,\n\t\t\t\t\t\tlp_netbios_name(), server,\n\t\t\t\t\t\tNULL, 0, \"IPC$\", \"?????\",\n\t\t\t\t\t\t*pp_username,\n\t\t\t\t\t\t*pp_workgroup,\n\t\t\t\t\t\t*pp_password,\n\t\t\t\t\t\tflags,\n\t\t\t\t\t\tSMB_SIGNING_DEFAULT);\n if (! NT_STATUS_IS_OK(nt_status)) {\n DEBUG(1,(\"cli_full_connection failed! (%s)\\n\",\n nt_errstr(nt_status)));\n errno = ENOTSUP;\n return NULL;\n }\n\n\t\tif (context->internal->smb_encryption_level) {\n\t\t\t\/* Attempt UNIX smb encryption. *\/\n\t\t\tif (!NT_STATUS_IS_OK(cli_force_encryption(ipc_cli,\n *pp_username,\n *pp_password,\n *pp_workgroup))) {\n\n\t\t\t\t\/*\n\t\t\t\t * context->smb_encryption_level ==\n\t\t\t\t * 1 means don't fail if encryption can't be\n\t\t\t\t * negotiated, == 2 means fail if encryption\n\t\t\t\t * can't be negotiated.\n\t\t\t\t *\/\n\n\t\t\t\tDEBUG(4,(\" SMB encrypt failed on IPC$\\n\"));\n\n\t\t\t\tif (context->internal->smb_encryption_level == 2) {\n\t\t cli_shutdown(ipc_cli);\n\t\t\t\t\terrno = EPERM;\n\t\t\t\t\treturn NULL;\n\t\t\t\t}\n\t\t\t}\n\t\t\tDEBUG(4,(\" SMB encrypt ok on IPC$\\n\"));\n\t\t}\n\n ipc_srv = SMB_MALLOC_P(SMBCSRV);\n if (!ipc_srv) {\n errno = ENOMEM;\n cli_shutdown(ipc_cli);\n return NULL;\n }\n\n ZERO_STRUCTP(ipc_srv);\n ipc_srv->cli = ipc_cli;\n\n nt_status = cli_rpc_pipe_open_noauth(\n\t\t\tipc_srv->cli, &ndr_table_lsarpc, &pipe_hnd);\n if (!NT_STATUS_IS_OK(nt_status)) {\n DEBUG(1, (\"cli_nt_session_open fail!\\n\"));\n errno = ENOTSUP;\n cli_shutdown(ipc_srv->cli);\n free(ipc_srv);\n return NULL;\n }\n\n \/*\n * Some systems don't support\n * SEC_FLAG_MAXIMUM_ALLOWED, but NT sends 0x2000000\n * so we might as well do it too.\n *\/\n\n nt_status = rpccli_lsa_open_policy(\n pipe_hnd,\n talloc_tos(),\n True,\n GENERIC_EXECUTE_ACCESS,\n &ipc_srv->pol);\n\n if (!NT_STATUS_IS_OK(nt_status)) {\n errno = SMBC_errno(context, ipc_srv->cli);\n cli_shutdown(ipc_srv->cli);\n free(ipc_srv);\n return NULL;\n }\n\n \/* now add it to the cache (internal or external) *\/\n\n errno = 0; \/* let cache function set errno if it likes *\/\n if (smbc_getFunctionAddCachedServer(context)(context, ipc_srv,\n server,\n \"*IPC$\",\n *pp_workgroup,\n *pp_username)) {\n DEBUG(3, (\" Failed to add server to cache\\n\"));\n if (errno == 0) {\n errno = ENOMEM;\n }\n cli_shutdown(ipc_srv->cli);\n free(ipc_srv);\n return NULL;\n }\n\n DLIST_ADD(context->internal->servers, ipc_srv);\n }\n\n return ipc_srv;\n}","target":1,"code_token_length":1168,"total_token_length":1499,"max_tokens_setting":2048} +{"idx":514190,"func":"span_renderer_init (cairo_abstract_span_renderer_t\t*_r,\n\t\t const cairo_composite_rectangles_t *composite,\n\t\t cairo_antialias_t\t\t\t antialias,\n\t\t cairo_bool_t\t\t\t needs_clip)\n{\n cairo_image_span_renderer_t *r = (cairo_image_span_renderer_t *)_r;\n cairo_image_surface_t *dst = (cairo_image_surface_t *)composite->surface;\n const cairo_pattern_t *source = &composite->source_pattern.base;\n cairo_operator_t op = composite->op;\n cairo_int_status_t status;\n\n TRACE ((stderr, \"%s: antialias=%d, needs_clip=%d\\n\", __FUNCTION__,\n\t antialias, needs_clip));\n\n if (needs_clip)\n\treturn CAIRO_INT_STATUS_UNSUPPORTED;\n\n r->composite = composite;\n r->mask = NULL;\n r->src = NULL;\n r->base.finish = NULL;\n\n status = mono_renderer_init (r, composite, antialias, needs_clip);\n if (status != CAIRO_INT_STATUS_UNSUPPORTED)\n\treturn status;\n\n status = inplace_renderer_init (r, composite, antialias, needs_clip);\n if (status != CAIRO_INT_STATUS_UNSUPPORTED)\n\treturn status;\n\n r->bpp = 0;\n\n if (op == CAIRO_OPERATOR_CLEAR) {\n#if PIXMAN_HAS_OP_LERP\n\top = PIXMAN_OP_LERP_CLEAR;\n#else\n\tsource = &_cairo_pattern_white.base;\n\top = PIXMAN_OP_OUT_REVERSE;\n#endif\n } else if (dst->base.is_clear &&\n\t (op == CAIRO_OPERATOR_SOURCE ||\n\t\top == CAIRO_OPERATOR_OVER ||\n\t\top == CAIRO_OPERATOR_ADD)) {\n\top = PIXMAN_OP_SRC;\n } else if (op == CAIRO_OPERATOR_SOURCE) {\n\tif (_cairo_pattern_is_opaque (&composite->source_pattern.base,\n\t\t\t\t &composite->source_sample_area))\n\t{\n\t op = PIXMAN_OP_OVER;\n\t}\n\telse\n\t{\n#if PIXMAN_HAS_OP_LERP\n\t op = PIXMAN_OP_LERP_SRC;\n#else\n\t return CAIRO_INT_STATUS_UNSUPPORTED;\n#endif\n\t}\n } else {\n\top = _pixman_operator (op);\n }\n r->op = op;\n\n r->src = _pixman_image_for_pattern (dst, source, FALSE,\n\t\t\t\t\t&composite->unbounded,\n\t\t\t\t\t&composite->source_sample_area,\n\t\t\t\t\t&r->u.mask.src_x, &r->u.mask.src_y);\n if (unlikely (r->src == NULL))\n\treturn _cairo_error (CAIRO_STATUS_NO_MEMORY);\n\n r->opacity = 1.0;\n if (composite->mask_pattern.base.type == CAIRO_PATTERN_TYPE_SOLID) {\n\tr->opacity = composite->mask_pattern.solid.color.alpha;\n } else {\n\tpixman_image_t *mask;\n\tint mask_x, mask_y;\n\n\tmask = _pixman_image_for_pattern (dst,\n\t\t\t\t\t &composite->mask_pattern.base,\n\t\t\t\t\t TRUE,\n\t\t\t\t\t &composite->unbounded,\n\t\t\t\t\t &composite->mask_sample_area,\n\t\t\t\t\t &mask_x, &mask_y);\n\tif (unlikely (mask == NULL))\n\t return _cairo_error (CAIRO_STATUS_NO_MEMORY);\n\n\t\/* XXX Component-alpha? *\/\n\tif ((dst->base.content & CAIRO_CONTENT_COLOR) == 0 &&\n\t _cairo_pattern_is_opaque (source, &composite->source_sample_area))\n\t{\n\t pixman_image_unref (r->src);\n\t r->src = mask;\n\t r->u.mask.src_x = mask_x;\n\t r->u.mask.src_y = mask_y;\n\t mask = NULL;\n\t}\n\n\tif (mask) {\n\t pixman_image_unref (mask);\n\t return CAIRO_INT_STATUS_UNSUPPORTED;\n\t}\n }\n\n r->u.mask.extents = composite->unbounded;\n r->u.mask.stride = (r->u.mask.extents.width + 3) & ~3;\n if (r->u.mask.extents.height * r->u.mask.stride > SZ_BUF) {\n\tr->mask = pixman_image_create_bits (PIXMAN_a8,\n\t\t\t\t\t r->u.mask.extents.width,\n\t\t\t\t\t r->u.mask.extents.height,\n\t\t\t\t\t NULL, 0);\n\n\tr->base.render_rows = _cairo_image_spans;\n\tr->base.finish = NULL;\n } else {\n\tr->mask = pixman_image_create_bits (PIXMAN_a8,\n\t\t\t\t\t r->u.mask.extents.width,\n\t\t\t\t\t r->u.mask.extents.height,\n\t\t\t\t\t (uint32_t *)r->_buf, r->u.mask.stride);\n\n\tr->base.render_rows = _cairo_image_spans_and_zero;\n\tr->base.finish = _cairo_image_finish_spans_and_zero;\n }\n if (unlikely (r->mask == NULL))\n\treturn _cairo_error (CAIRO_STATUS_NO_MEMORY);\n\n r->u.mask.data = (uint8_t *) pixman_image_get_data (r->mask);\n r->u.mask.stride = pixman_image_get_stride (r->mask);\n\n r->u.mask.extents.height += r->u.mask.extents.y;\n return CAIRO_STATUS_SUCCESS;\n}","target":0,"code_token_length":1049,"total_token_length":1380,"max_tokens_setting":2048} +{"idx":489427,"func":"GF_Err nhmldump_process(GF_Filter *filter)\n{\n\tGF_NHMLDumpCtx *ctx = gf_filter_get_udta(filter);\n\tGF_FilterPacket *pck;\n\tchar *data;\n\tu32 pck_size;\n\n\tif (!ctx->side_streams_config) {\n\t\treturn nhmldump_config_side_stream(filter, ctx);\n\t}\n\n\tpck = gf_filter_pid_get_packet(ctx->ipid);\n\tif (!pck) {\n\t\tif (gf_filter_pid_is_eos(ctx->ipid)) {\n\t\t\tif (ctx->bs_w && ctx->szRootName) {\n\t\t\t\tchar nhml[1024];\n\t\t\t\tu32 size;\n\t\t\t\tgf_bs_reassign_buffer(ctx->bs_w, ctx->nhml_buffer, ctx->nhml_buffer_size);\n\t\t\t\tsprintf(nhml, \"<\/%s>\\n\", ctx->szRootName);\n\t\t\t\tgf_bs_write_data(ctx->bs_w, nhml, (u32) strlen(nhml));\n\n\t\t\t\tgf_bs_get_content_no_truncate(ctx->bs_w, &ctx->nhml_buffer, &size, &ctx->nhml_buffer_size);\n\n\t\t\t\tif (ctx->filep) {\n\t\t\t\t\tgf_fwrite(ctx->nhml_buffer, size, ctx->filep);\n\t\t\t\t} else {\n\t\t\t\t\tGF_FilterPacket *dst_pck;\n\t\t\t\t\tu8 *output;\n\t\t\t\t\tdst_pck = gf_filter_pck_new_alloc(ctx->opid_nhml, size, &output);\n\t\t\t\t\tif (dst_pck) {\n\t\t\t\t\t\tmemcpy(output, ctx->nhml_buffer, size);\n\t\t\t\t\t\tgf_filter_pck_set_framing(dst_pck, GF_FALSE, GF_TRUE);\n\t\t\t\t\t\tgf_filter_pck_send(dst_pck);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tctx->szRootName = NULL;\n\t\t\t}\n\t\t\tif (ctx->opid_nhml) gf_filter_pid_set_eos(ctx->opid_nhml);\n\t\t\tif (ctx->opid_mdia) gf_filter_pid_set_eos(ctx->opid_mdia);\n\t\t\tif (ctx->opid_info) gf_filter_pid_set_eos(ctx->opid_info);\n\t\t\treturn GF_EOS;\n\t\t}\n\t\treturn GF_OK;\n\t}\n\n\tif (!ctx->bs_w) ctx->bs_w = gf_bs_new(NULL, 0, GF_BITSTREAM_WRITE);\n\telse gf_bs_reassign_buffer(ctx->bs_w, ctx->nhml_buffer, ctx->nhml_buffer_size);\n\n\tif (ctx->first) {\n\t\tnhmldump_send_header(ctx);\n\t\tgf_bs_reassign_buffer(ctx->bs_w, ctx->nhml_buffer, ctx->nhml_buffer_size);\n\t}\n\n\t\/\/get media data\n\tdata = (char *) gf_filter_pck_get_data(pck, &pck_size);\n\n\t\/\/send data\n\tif (ctx->is_dims) {\n\t\tnhmldump_send_dims(ctx, data, pck_size, pck);\n\t} else {\n\t\tnhmldump_send_frame(ctx, data, pck_size, pck);\n\t}\n\tctx->first = GF_FALSE;\n\n\n\tif (ctx->exporter) {\n\t\tu32 timescale = gf_filter_pck_get_timescale(pck);\n\t\tu64 ts = gf_filter_pck_get_cts(pck);\n\t\tgf_set_progress(\"Exporting\", ts*ctx->duration.den, ctx->duration.num*timescale);\n\t}\n\n\tgf_filter_pid_drop_packet(ctx->ipid);\n\n\treturn GF_OK;\n}","target":0,"code_token_length":724,"total_token_length":1055,"max_tokens_setting":2048} +{"idx":94283,"func":"SYSCALL_DEFINE5(keyctl, int, option, unsigned long, arg2, unsigned long, arg3,\n\t\tunsigned long, arg4, unsigned long, arg5)\n{\n\tswitch (option) {\n\tcase KEYCTL_GET_KEYRING_ID:\n\t\treturn keyctl_get_keyring_ID((key_serial_t) arg2,\n\t\t\t\t\t (int) arg3);\n\n\tcase KEYCTL_JOIN_SESSION_KEYRING:\n\t\treturn keyctl_join_session_keyring((const char __user *) arg2);\n\n\tcase KEYCTL_UPDATE:\n\t\treturn keyctl_update_key((key_serial_t) arg2,\n\t\t\t\t\t (const void __user *) arg3,\n\t\t\t\t\t (size_t) arg4);\n\n\tcase KEYCTL_REVOKE:\n\t\treturn keyctl_revoke_key((key_serial_t) arg2);\n\n\tcase KEYCTL_DESCRIBE:\n\t\treturn keyctl_describe_key((key_serial_t) arg2,\n\t\t\t\t\t (char __user *) arg3,\n\t\t\t\t\t (unsigned) arg4);\n\n\tcase KEYCTL_CLEAR:\n\t\treturn keyctl_keyring_clear((key_serial_t) arg2);\n\n\tcase KEYCTL_LINK:\n\t\treturn keyctl_keyring_link((key_serial_t) arg2,\n\t\t\t\t\t (key_serial_t) arg3);\n\n\tcase KEYCTL_UNLINK:\n\t\treturn keyctl_keyring_unlink((key_serial_t) arg2,\n\t\t\t\t\t (key_serial_t) arg3);\n\n\tcase KEYCTL_SEARCH:\n\t\treturn keyctl_keyring_search((key_serial_t) arg2,\n\t\t\t\t\t (const char __user *) arg3,\n\t\t\t\t\t (const char __user *) arg4,\n\t\t\t\t\t (key_serial_t) arg5);\n\n\tcase KEYCTL_READ:\n\t\treturn keyctl_read_key((key_serial_t) arg2,\n\t\t\t\t (char __user *) arg3,\n\t\t\t\t (size_t) arg4);\n\n\tcase KEYCTL_CHOWN:\n\t\treturn keyctl_chown_key((key_serial_t) arg2,\n\t\t\t\t\t(uid_t) arg3,\n\t\t\t\t\t(gid_t) arg4);\n\n\tcase KEYCTL_SETPERM:\n\t\treturn keyctl_setperm_key((key_serial_t) arg2,\n\t\t\t\t\t (key_perm_t) arg3);\n\n\tcase KEYCTL_INSTANTIATE:\n\t\treturn keyctl_instantiate_key((key_serial_t) arg2,\n\t\t\t\t\t (const void __user *) arg3,\n\t\t\t\t\t (size_t) arg4,\n\t\t\t\t\t (key_serial_t) arg5);\n\n\tcase KEYCTL_NEGATE:\n\t\treturn keyctl_negate_key((key_serial_t) arg2,\n\t\t\t\t\t (unsigned) arg3,\n\t\t\t\t\t (key_serial_t) arg4);\n\n\tcase KEYCTL_SET_REQKEY_KEYRING:\n\t\treturn keyctl_set_reqkey_keyring(arg2);\n\n\tcase KEYCTL_SET_TIMEOUT:\n\t\treturn keyctl_set_timeout((key_serial_t) arg2,\n\t\t\t\t\t (unsigned) arg3);\n\n\tcase KEYCTL_ASSUME_AUTHORITY:\n\t\treturn keyctl_assume_authority((key_serial_t) arg2);\n\n\tcase KEYCTL_GET_SECURITY:\n\t\treturn keyctl_get_security((key_serial_t) arg2,\n\t\t\t\t\t (char __user *) arg3,\n\t\t\t\t\t (size_t) arg4);\n\n\tcase KEYCTL_SESSION_TO_PARENT:\n\t\treturn keyctl_session_to_parent();\n\n\tcase KEYCTL_REJECT:\n\t\treturn keyctl_reject_key((key_serial_t) arg2,\n\t\t\t\t\t (unsigned) arg3,\n\t\t\t\t\t (unsigned) arg4,\n\t\t\t\t\t (key_serial_t) arg5);\n\n\tcase KEYCTL_INSTANTIATE_IOV:\n\t\treturn keyctl_instantiate_key_iov(\n\t\t\t(key_serial_t) arg2,\n\t\t\t(const struct iovec __user *) arg3,\n\t\t\t(unsigned) arg4,\n\t\t\t(key_serial_t) arg5);\n\n\tcase KEYCTL_INVALIDATE:\n\t\treturn keyctl_invalidate_key((key_serial_t) arg2);\n\n\tcase KEYCTL_GET_PERSISTENT:\n\t\treturn keyctl_get_persistent((uid_t)arg2, (key_serial_t)arg3);\n\n\tcase KEYCTL_DH_COMPUTE:\n\t\treturn keyctl_dh_compute((struct keyctl_dh_params __user *) arg2,\n\t\t\t\t\t (char __user *) arg3, (size_t) arg4,\n\t\t\t\t\t (void __user *) arg5);\n\n\tdefault:\n\t\treturn -EOPNOTSUPP;\n\t}\n}","target":0,"code_token_length":854,"total_token_length":1185,"max_tokens_setting":2048} +{"idx":160948,"func":"node_char_len1(Node* node, regex_t* reg, MinMaxCharLen* ci, ScanEnv* env,\n int level)\n{\n MinMaxCharLen tci;\n int r = CHAR_LEN_NORMAL;\n\n level++;\n\n switch (NODE_TYPE(node)) {\n case NODE_LIST:\n {\n int first = TRUE;\n do {\n r = node_char_len1(NODE_CAR(node), reg, &tci, env, level);\n if (r < 0) break;\n if (first == TRUE) {\n *ci = tci;\n first = FALSE;\n }\n else\n mmcl_add(ci, &tci);\n } while (IS_NOT_NULL(node = NODE_CDR(node)));\n }\n break;\n\n case NODE_ALT:\n {\n int fixed;\n\n r = node_char_len1(NODE_CAR(node), reg, ci, env, level);\n if (r < 0) break;\n\n fixed = TRUE;\n while (IS_NOT_NULL(node = NODE_CDR(node))) {\n r = node_char_len1(NODE_CAR(node), reg, &tci, env, level);\n if (r < 0) break;\n if (! mmcl_fixed(&tci))\n fixed = FALSE;\n mmcl_alt_merge(ci, &tci);\n }\n if (r < 0) break;\n\n r = CHAR_LEN_NORMAL;\n if (mmcl_fixed(ci)) break;\n\n if (fixed == TRUE && level == 1) {\n r = CHAR_LEN_TOP_ALT_FIXED;\n }\n }\n break;\n\n case NODE_STRING:\n {\n OnigLen clen;\n StrNode* sn = STR_(node);\n UChar *s = sn->s;\n\n if (NODE_IS_IGNORECASE(node) && ! NODE_STRING_IS_CRUDE(node)) {\n \/* Such a case is possible.\n ex. \/(?i)(?<=\\1)(a)\/\n Backref node refer to capture group, but it doesn't tune yet.\n *\/\n r = ONIGERR_INVALID_LOOK_BEHIND_PATTERN;\n break;\n }\n\n clen = 0;\n while (s < sn->end) {\n s += enclen(reg->enc, s);\n clen = distance_add(clen, 1);\n }\n mmcl_set(ci, clen);\n }\n break;\n\n case NODE_QUANT:\n {\n QuantNode* qn = QUANT_(node);\n\n if (qn->lower == qn->upper) {\n if (qn->upper == 0) {\n mmcl_set(ci, 0);\n }\n else {\n r = node_char_len1(NODE_BODY(node), reg, ci, env, level);\n if (r < 0) break;\n mmcl_multiply(ci, qn->lower);\n }\n }\n else {\n r = node_char_len1(NODE_BODY(node), reg, ci, env, level);\n if (r < 0) break;\n mmcl_repeat_range_multiply(ci, qn->lower, qn->upper);\n }\n }\n break;\n\n#ifdef USE_CALL\n case NODE_CALL:\n if (NODE_IS_RECURSION(node))\n mmcl_set_min_max(ci, 0, INFINITE_LEN, FALSE);\n else\n r = node_char_len1(NODE_BODY(node), reg, ci, env, level);\n break;\n#endif\n\n case NODE_CTYPE:\n case NODE_CCLASS:\n mmcl_set(ci, 1);\n break;\n\n case NODE_BAG:\n {\n BagNode* en = BAG_(node);\n\n switch (en->type) {\n case BAG_MEMORY:\n if (NODE_IS_FIXED_CLEN(node)) {\n mmcl_set_min_max(ci, en->min_char_len, en->max_char_len,\n NODE_IS_FIXED_CLEN_MIN_SURE(node));\n }\n else {\n if (NODE_IS_MARK1(node)) {\n mmcl_set_min_max(ci, 0, INFINITE_LEN, FALSE);\n }\n else {\n NODE_STATUS_ADD(node, MARK1);\n r = node_char_len1(NODE_BODY(node), reg, ci, env, level);\n NODE_STATUS_REMOVE(node, MARK1);\n if (r < 0) break;\n\n en->min_char_len = ci->min;\n en->max_char_len = ci->max;\n NODE_STATUS_ADD(node, FIXED_CLEN);\n if (ci->min_is_sure != FALSE)\n NODE_STATUS_ADD(node, FIXED_CLEN_MIN_SURE);\n }\n }\n \/* can't optimize look-behind if capture exists. *\/\n ci->min_is_sure = FALSE;\n break;\n case BAG_OPTION:\n case BAG_STOP_BACKTRACK:\n r = node_char_len1(NODE_BODY(node), reg, ci, env, level);\n break;\n case BAG_IF_ELSE:\n {\n MinMaxCharLen eci;\n\n r = node_char_len1(NODE_BODY(node), reg, ci, env, level);\n if (r < 0) break;\n\n if (IS_NOT_NULL(en->te.Then)) {\n r = node_char_len1(en->te.Then, reg, &tci, env, level);\n if (r < 0) break;\n mmcl_add(ci, &tci);\n }\n\n if (IS_NOT_NULL(en->te.Else)) {\n r = node_char_len1(en->te.Else, reg, &eci, env, level);\n if (r < 0) break;\n }\n else {\n mmcl_set(&eci, 0);\n }\n\n mmcl_alt_merge(ci, &eci);\n }\n break;\n default: \/* never come here *\/\n r = ONIGERR_PARSER_BUG;\n break;\n }\n }\n break;\n\n case NODE_GIMMICK:\n mmcl_set(ci, 0);\n break;\n\n case NODE_ANCHOR:\n zero:\n mmcl_set(ci, 0);\n \/* can't optimize look-behind if anchor exists. *\/\n ci->min_is_sure = FALSE;\n break;\n\n case NODE_BACKREF:\n if (NODE_IS_CHECKER(node))\n goto zero;\n\n if (NODE_IS_RECURSION(node)) {\n#ifdef USE_BACKREF_WITH_LEVEL\n if (NODE_IS_NEST_LEVEL(node)) {\n mmcl_set_min_max(ci, 0, INFINITE_LEN, FALSE);\n break;\n }\n#endif\n\n mmcl_set_min_max(ci, 0, 0, FALSE);\n break;\n }\n\n {\n int i;\n int* backs;\n MemEnv* mem_env = SCANENV_MEMENV(env);\n BackRefNode* br = BACKREF_(node);\n\n backs = BACKREFS_P(br);\n r = node_char_len1(mem_env[backs[0]].mem_node, reg, ci, env, level);\n if (r < 0) break;\n if (! mmcl_fixed(ci)) ci->min_is_sure = FALSE;\n\n for (i = 1; i < br->back_num; i++) {\n r = node_char_len1(mem_env[backs[i]].mem_node, reg, &tci, env, level);\n if (r < 0) break;\n if (! mmcl_fixed(&tci)) tci.min_is_sure = FALSE;\n mmcl_alt_merge(ci, &tci);\n }\n }\n break;\n\n default: \/* never come here *\/\n r = ONIGERR_PARSER_BUG;\n break;\n }\n\n return r;\n}","target":0,"code_token_length":1618,"total_token_length":1949,"max_tokens_setting":2048} +{"idx":294354,"func":"decompress_R2004_section (Bit_Chain *restrict dat, BITCODE_RC *restrict decomp,\n uint32_t decomp_data_size, uint32_t comp_data_size)\n{\n unsigned int i, lit_length;\n uint32_t comp_offset, comp_bytes, bytes_left;\n unsigned char opcode1 = 0, opcode2;\n long unsigned int start_byte = dat->byte;\n BITCODE_RC *src, *dst = decomp;\n BITCODE_RC *maxdst = decomp + decomp_data_size;\n\n bytes_left = decomp_data_size; \/\/ to write to\n if (comp_data_size > dat->size - start_byte) \/\/ bytes left to read from\n {\n LOG_WARN (\"Invalid comp_data_size %lu > %lu bytes left\",\n (unsigned long)bytes_left, dat->size - dat->byte)\n return DWG_ERR_VALUEOUTOFBOUNDS;\n }\n \/\/ length of the first sequence of uncompressed or literal data.\n lit_length = read_literal_length (dat, &opcode1);\n if (lit_length > bytes_left)\n {\n LOG_ERROR (\"Invalid literal_length %u > %u bytes left\",\n lit_length, (unsigned)decomp_data_size)\n return DWG_ERR_VALUEOUTOFBOUNDS;\n }\n bit_read_fixed (dat, decomp, lit_length);\n dst += lit_length;\n bytes_left -= lit_length;\n\n opcode1 = 0x00;\n while (dat->byte - start_byte < comp_data_size)\n {\n LOG_INSANE (\"-O %x \", opcode1)\n if (opcode1 == 0x00)\n {\n opcode1 = bit_read_RC (dat);\n LOG_INSANE (\"= 0x40)\n {\n comp_bytes = ((opcode1 & 0xF0) >> 4) - 1;\n opcode2 = bit_read_RC (dat);\n LOG_INSANE (\"> 2);\n\n if (opcode1 & 0x03)\n {\n lit_length = (opcode1 & 0x03);\n opcode1 = 0x00;\n }\n else\n lit_length = read_literal_length (dat, &opcode1);\n }\n else if (opcode1 >= 0x21\n && opcode1 <= 0x3F) \/\/ lgtm [cpp\/constant-comparison]\n {\n comp_bytes = opcode1 - 0x1E;\n comp_offset = read_two_byte_offset (dat, &lit_length);\n\n if (lit_length != 0)\n opcode1 = 0x00;\n else\n lit_length = read_literal_length (dat, &opcode1);\n }\n else if (opcode1 == 0x20)\n {\n comp_bytes = read_long_compression_offset (dat) + 0x21;\n comp_offset = read_two_byte_offset (dat, &lit_length);\n\n if (lit_length != 0)\n opcode1 = 0x00;\n else\n lit_length = read_literal_length (dat, &opcode1);\n }\n else if (opcode1 >= 0x12 && opcode1 <= 0x1F)\n {\n comp_bytes = (opcode1 & 0x0F) + 2;\n comp_offset = read_two_byte_offset (dat, &lit_length) + 0x3FFF;\n\n if (lit_length != 0)\n opcode1 = 0x00;\n else\n lit_length = read_literal_length (dat, &opcode1);\n }\n else if (opcode1 == 0x10)\n {\n comp_bytes = read_long_compression_offset (dat) + 9;\n comp_offset = read_two_byte_offset (dat, &lit_length) + 0x3FFF;\n\n if (lit_length != 0)\n opcode1 = 0x00;\n else\n lit_length = read_literal_length (dat, &opcode1);\n }\n else if (opcode1 == 0x11)\n break; \/\/ Terminates the input stream, everything is ok\n else\n {\n LOG_ERROR (\"Invalid opcode 0x%x in input stream at pos %lu\", opcode1,\n dat->byte);\n return DWG_ERR_INTERNALERROR; \/\/ error in input stream\n }\n\n src = dst - comp_offset - 1;\n if (src < decomp) \/\/ was assert (src >= decomp);\n {\n LOG_ERROR (\"decompress_R2004_section: src offset underflow\");\n return DWG_ERR_INTERNALERROR;\n }\n if (comp_bytes)\n {\n LOG_INSANE (\" bytes_left || \/\/ bytes left to write\n dst + comp_bytes > maxdst)\n {\n LOG_ERROR (\"Invalid comp_bytes %lu > %lu bytes left\",\n (unsigned long)comp_bytes, (unsigned long)bytes_left)\n return DWG_ERR_VALUEOUTOFBOUNDS;\n }\n for (i = 0; i < comp_bytes; ++i)\n *dst++ = *src++;\n bytes_left -= comp_bytes;\n }\n \/\/ copy \"literal data\"\n LOG_INSANE (\" bytes_left) \/\/ bytes left to write\n || dst + lit_length > maxdst) \/\/ dst overflow\n {\n LOG_ERROR (\"Invalid lit_length %u > %lu bytes left\",\n lit_length, (unsigned long)bytes_left)\n return DWG_ERR_VALUEOUTOFBOUNDS;\n }\n for (i = 0; i < lit_length; ++i)\n *dst++ = bit_read_RC (dat);\n }\n }\n\n return 0; \/\/ Success\n}","target":0,"code_token_length":1315,"total_token_length":1646,"max_tokens_setting":2048} +{"idx":502448,"func":"struct winsdb_addr **winsdb_addr_list_add(struct winsdb_handle *h, const struct winsdb_record *rec,\n\t\t\t\t\t struct winsdb_addr **addresses, const char *address,\n\t\t\t\t\t const char *wins_owner, time_t expire_time,\n\t\t\t\t\t bool is_name_registration)\n{\n\tstruct winsdb_addr *old_addr = NULL;\n\tsize_t len = 0;\n\tsize_t i;\n\tbool found_old_replica = false;\n\n\t\/*\n\t * count the addresses and maybe\n\t * find an old entry for the new address\n\t *\/\n\tfor (i=0; addresses[i]; i++) {\n\t\tif (old_addr) continue;\n\t\tif (strcmp(addresses[i]->address, address) == 0) {\n\t\t\told_addr = addresses[i];\n\t\t}\n\t}\n\tlen = i;\n\n\t\/*\n\t * the address is already there\n\t * and we can replace it\n\t *\/\n\tif (old_addr) {\n\t\tgoto remove_old_addr;\n\t}\n\n\t\/*\n\t * if we don't have 25 addresses already,\n\t * we can just add the new address\n\t *\/\n\tif (len < 25) {\n\t\tgoto add_new_addr;\n\t}\n\n\t\/*\n\t * if we haven't found the address,\n\t * and we have already have 25 addresses\n\t * if so then we need to do the following:\n\t * - if it isn't a name registration, then just ignore the new address\n\t * - if it is a name registration, then first search for \n\t * the oldest replica and if there's no replica address\n\t * search the oldest owned address\n\t *\/\n\tif (!is_name_registration) {\n\t\treturn addresses;\n\t}\n\n\t\/*\n\t * find the oldest replica address, if there's no replica\n\t * record at all, find the oldest owned address\n\t *\/\n\tfor (i=0; addresses[i]; i++) {\n\t\tbool cur_is_replica = false;\n\t\t\/* find out if the current address is a replica *\/\n\t\tif (strcmp(addresses[i]->wins_owner, h->local_owner) != 0) {\n\t\t\tcur_is_replica = true;\n\t\t}\n\n\t\t\/*\n\t\t * if we already found a replica address and the current address\n\t\t * is not a replica, then skip it\n\t\t *\/\n\t\tif (found_old_replica && !cur_is_replica) continue;\n\n\t\t\/*\n\t\t * if we found the first replica address, reset the address\n\t\t * that would be replaced\n\t\t *\/\n\t\tif (!found_old_replica && cur_is_replica) {\n\t\t\tfound_old_replica = true;\n\t\t\told_addr = addresses[i];\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/*\n\t\t * if the first address isn't a replica, just start with \n\t\t * the first one\n\t\t *\/\n\t\tif (!old_addr) {\n\t\t\told_addr = addresses[i];\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/*\n\t\t * see if we find an older address\n\t\t *\/\n\t\tif (addresses[i]->expire_time < old_addr->expire_time) {\n\t\t\told_addr = addresses[i];\n\t\t\tcontinue;\n\t\t}\n\t}\n\nremove_old_addr:\n\twinsdb_addr_list_remove(addresses, old_addr->address);\n\tlen --;\n\nadd_new_addr:\n\taddresses = talloc_realloc(addresses, addresses, struct winsdb_addr *, len + 2);\n\tif (!addresses) return NULL;\n\n\taddresses[len] = talloc(addresses, struct winsdb_addr);\n\tif (!addresses[len]) {\n\t\ttalloc_free(addresses);\n\t\treturn NULL;\n\t}\n\n\taddresses[len]->address = talloc_strdup(addresses[len], address);\n\tif (!addresses[len]->address) {\n\t\ttalloc_free(addresses);\n\t\treturn NULL;\n\t}\n\n\taddresses[len]->wins_owner = talloc_strdup(addresses[len], wins_owner);\n\tif (!addresses[len]->wins_owner) {\n\t\ttalloc_free(addresses);\n\t\treturn NULL;\n\t}\n\n\taddresses[len]->expire_time = expire_time;\n\n\taddresses[len+1] = NULL;\n\n\tLDB_TYPESAFE_QSORT(addresses, len+1, h, winsdb_addr_sort_list);\n\n\treturn addresses;\n}","target":0,"code_token_length":850,"total_token_length":1181,"max_tokens_setting":2048} +{"idx":290325,"func":"int main ( int argc , char * * argv ) {\n int option_idx = 0 ;\n int result ;\n const char * adb_server_ip = NULL ;\n unsigned short * adb_server_tcp_port = NULL ;\n unsigned int logcat_text = 0 ;\n const char * default_adb_server_ip = \"127.0.0.1\" ;\n unsigned short default_adb_server_tcp_port = 5037 ;\n unsigned short local_adb_server_tcp_port ;\n unsigned short local_bt_server_tcp_port ;\n unsigned short local_bt_local_tcp_port ;\n unsigned short * bt_server_tcp_port = NULL ;\n unsigned int bt_forward_socket = 0 ;\n const char * bt_local_ip = NULL ;\n unsigned short * bt_local_tcp_port = NULL ;\n unsigned short default_bt_server_tcp_port = 4330 ;\n const char * default_bt_local_ip = \"127.0.0.1\" ;\n unsigned short default_bt_local_tcp_port = 4330 ;\n extcap_parameters * extcap_conf = NULL ;\n # ifdef _WIN32 WSADATA wsaData ;\n attach_parent_console ( ) ;\n # endif opterr = 0 ;\n optind = 0 ;\n if ( argc == 1 ) {\n help ( ) ;\n return EXIT_CODE_SUCCESS ;\n }\n extcap_conf = g_new0 ( extcap_parameters , 1 ) ;\n extcap_base_set_util_info ( extcap_conf , ANDROIDDUMP_VERSION_MAJOR , ANDROIDDUMP_VERSION_MINOR , ANDROIDDUMP_VERSION_RELEASE , NULL ) ;\n while ( ( result = getopt_long ( argc , argv , \"\" , longopts , & option_idx ) ) != - 1 ) {\n switch ( result ) {\n case OPT_VERSION : printf ( \"%s.%s.%s\\n\" , ANDROIDDUMP_VERSION_MAJOR , ANDROIDDUMP_VERSION_MINOR , ANDROIDDUMP_VERSION_RELEASE ) ;\n return EXIT_CODE_SUCCESS ;\n case OPT_VERBOSE : if ( optarg ) verbose = ( g_ascii_strncasecmp ( optarg , \"TRUE\" , 4 ) == 0 ) ;\n else verbose = 1 ;\n {\n int j = 0 ;\n verbose_print ( \"VERBOSE: Command line: \" ) ;\n while ( j < argc ) {\n verbose_print ( \"%s \" , argv [ j ] ) ;\n j += 1 ;\n }\n verbose_print ( \"\\n\" ) ;\n }\n break ;\n case OPT_HELP : help ( ) ;\n return EXIT_CODE_SUCCESS ;\n case OPT_CONFIG_ADB_SERVER_IP : adb_server_ip = optarg ;\n break ;\n case OPT_CONFIG_ADB_SERVER_TCP_PORT : adb_server_tcp_port = & local_adb_server_tcp_port ;\n if ( ! optarg ) {\n errmsg_print ( \"ERROR: Impossible exception. Parameter required argument, but there is no it right now.\" ) ;\n return EXIT_CODE_GENERIC ;\n }\n * adb_server_tcp_port = ( unsigned short ) g_ascii_strtoull ( optarg , NULL , 10 ) ;\n break ;\n case OPT_CONFIG_LOGCAT_TEXT : logcat_text = ( g_ascii_strncasecmp ( optarg , \"TRUE\" , 4 ) == 0 ) ;\n break ;\n case OPT_CONFIG_BT_SERVER_TCP_PORT : bt_server_tcp_port = & local_bt_server_tcp_port ;\n if ( ! optarg ) {\n errmsg_print ( \"ERROR: Impossible exception. Parameter required argument, but there is no it right now.\" ) ;\n return EXIT_CODE_GENERIC ;\n }\n * bt_server_tcp_port = ( unsigned short ) g_ascii_strtoull ( optarg , NULL , 10 ) ;\n break ;\n case OPT_CONFIG_BT_FORWARD_SOCKET : bt_forward_socket = ( g_ascii_strncasecmp ( optarg , \"TRUE\" , 4 ) == 0 ) ;\n break ;\n case OPT_CONFIG_BT_LOCAL_IP : bt_local_ip = optarg ;\n break ;\n case OPT_CONFIG_BT_LOCAL_TCP_PORT : bt_local_tcp_port = & local_bt_local_tcp_port ;\n if ( ! optarg ) {\n errmsg_print ( \"ERROR: Impossible exception. Parameter required argument, but there is no it right now.\" ) ;\n return EXIT_CODE_GENERIC ;\n }\n * bt_local_tcp_port = ( unsigned short ) g_ascii_strtoull ( optarg , NULL , 10 ) ;\n break ;\n default : if ( ! extcap_base_parse_options ( extcap_conf , result - EXTCAP_OPT_LIST_INTERFACES , optarg ) ) {\n printf ( \"Invalid argument <%s>. Try --help.\\n\" , argv [ optind - 1 ] ) ;\n return EXIT_CODE_GENERIC ;\n }\n }\n }\n if ( ! adb_server_ip ) adb_server_ip = default_adb_server_ip ;\n if ( ! adb_server_tcp_port ) adb_server_tcp_port = & default_adb_server_tcp_port ;\n if ( ! bt_server_tcp_port ) bt_server_tcp_port = & default_bt_server_tcp_port ;\n if ( ! bt_local_ip ) bt_local_ip = default_bt_local_ip ;\n if ( ! bt_local_tcp_port ) bt_local_tcp_port = & default_bt_local_tcp_port ;\n # ifdef _WIN32 result = WSAStartup ( MAKEWORD ( 1 , 1 ) , & wsaData ) ;\n if ( result != 0 ) {\n errmsg_print ( \"ERROR: WSAStartup failed with error: %d\" , result ) ;\n return EXIT_CODE_GENERIC ;\n }\n # endif if ( extcap_conf -> do_list_interfaces ) register_interfaces ( extcap_conf , adb_server_ip , adb_server_tcp_port ) ;\n if ( extcap_base_handle_interface ( extcap_conf ) ) return EXIT_CODE_SUCCESS ;\n if ( extcap_conf -> show_config ) return list_config ( extcap_conf -> interface ) ;\n if ( extcap_conf -> capture ) {\n if ( extcap_conf -> interface && ( is_specified_interface ( extcap_conf -> interface , INTERFACE_ANDROID_LOGCAT_MAIN ) || is_specified_interface ( extcap_conf -> interface , INTERFACE_ANDROID_LOGCAT_SYSTEM ) || is_specified_interface ( extcap_conf -> interface , INTERFACE_ANDROID_LOGCAT_RADIO ) || is_specified_interface ( extcap_conf -> interface , INTERFACE_ANDROID_LOGCAT_EVENTS ) ) ) if ( logcat_text ) return capture_android_logcat_text ( extcap_conf -> interface , extcap_conf -> fifo , adb_server_ip , adb_server_tcp_port ) ;\n else return capture_android_logcat ( extcap_conf -> interface , extcap_conf -> fifo , adb_server_ip , adb_server_tcp_port ) ;\n else if ( extcap_conf -> interface && ( is_specified_interface ( extcap_conf -> interface , INTERFACE_ANDROID_LOGCAT_TEXT_MAIN ) || is_specified_interface ( extcap_conf -> interface , INTERFACE_ANDROID_LOGCAT_TEXT_SYSTEM ) || is_specified_interface ( extcap_conf -> interface , INTERFACE_ANDROID_LOGCAT_TEXT_RADIO ) || is_specified_interface ( extcap_conf -> interface , INTERFACE_ANDROID_LOGCAT_TEXT_EVENTS ) || ( is_specified_interface ( extcap_conf -> interface , INTERFACE_ANDROID_LOGCAT_TEXT_CRASH ) ) ) ) return capture_android_logcat_text ( extcap_conf -> interface , extcap_conf -> fifo , adb_server_ip , adb_server_tcp_port ) ;\n else if ( extcap_conf -> interface && is_specified_interface ( extcap_conf -> interface , INTERFACE_ANDROID_BLUETOOTH_HCIDUMP ) ) return capture_android_bluetooth_hcidump ( extcap_conf -> interface , extcap_conf -> fifo , adb_server_ip , adb_server_tcp_port ) ;\n else if ( extcap_conf -> interface && is_specified_interface ( extcap_conf -> interface , INTERFACE_ANDROID_BLUETOOTH_EXTERNAL_PARSER ) ) return capture_android_bluetooth_external_parser ( extcap_conf -> interface , extcap_conf -> fifo , adb_server_ip , adb_server_tcp_port , bt_server_tcp_port , bt_forward_socket , bt_local_ip , bt_local_tcp_port ) ;\n else if ( extcap_conf -> interface && ( is_specified_interface ( extcap_conf -> interface , INTERFACE_ANDROID_BLUETOOTH_BTSNOOP_NET ) ) ) return capture_android_bluetooth_btsnoop_net ( extcap_conf -> interface , extcap_conf -> fifo , adb_server_ip , adb_server_tcp_port ) ;\n else if ( extcap_conf -> interface && ( is_specified_interface ( extcap_conf -> interface , INTERFACE_ANDROID_WIFI_TCPDUMP ) ) ) return capture_android_wifi_tcpdump ( extcap_conf -> interface , extcap_conf -> fifo , adb_server_ip , adb_server_tcp_port ) ;\n else return EXIT_CODE_GENERIC ;\n }\n extcap_base_cleanup ( & extcap_conf ) ;\n return EXIT_CODE_SUCCESS ;\n }","target":0,"code_token_length":1712,"total_token_length":2043,"max_tokens_setting":2048} +{"idx":382560,"func":"my_regcomp(preg, pattern, cflags, charset)\nmy_regex_t *preg;\nconst char *pattern;\nint cflags;\nCHARSET_INFO *charset;\n{\n\tstruct parse pa;\n\tregister struct re_guts *g;\n\tregister struct parse *p = &pa;\n\tregister int i;\n\tregister size_t len;\n#ifdef REDEBUG\n#\tdefine\tGOODFLAGS(f)\t(f)\n#else\n#\tdefine\tGOODFLAGS(f)\t((f)&~REG_DUMP)\n#endif\n\n\tmy_regex_init(charset, NULL);\t\/* Init cclass if neaded *\/\n\tpreg->charset=charset;\n\tcflags = GOODFLAGS(cflags);\n\tif ((cflags®_EXTENDED) && (cflags®_NOSPEC))\n\t\treturn(REG_INVARG);\n\n\tif (cflags®_PEND) {\n\t\tif (preg->re_endp < pattern)\n\t\t\treturn(REG_INVARG);\n\t\tlen = preg->re_endp - pattern;\n\t} else\n\t\tlen = strlen((char *)pattern);\n\n\t\/*\n\t Find the maximum len we can safely process\n\t without a rollover and a mis-malloc.\n\t p->ssize is a sopno is a long (32+ bit signed);\n\t size_t is 16+ bit unsigned.\n\t*\/\n\t{\n\t size_t new_ssize = len \/ (size_t)2 * (size_t)3 + (size_t)1; \/* ugh *\/\n\t if ((new_ssize < len) ||\t\/* size_t rolled over *\/\n\t ((SIZE_T_MAX \/ sizeof(sop)) < new_ssize) ||\t\/* malloc arg *\/\n\t (new_ssize > LONG_MAX))\t\/* won't fit in ssize *\/\n\t\treturn(REG_ESPACE);\t\/* MY_REG_ESPACE or MY_REG_INVARG *\/\n\t p->ssize = new_ssize;\n\t}\n\n\t\/* do the mallocs early so failure handling is easy *\/\n\tg = (struct re_guts *)malloc(sizeof(struct re_guts) +\n\t\t\t\t\t\t\t(NC-1)*sizeof(cat_t));\n\tif (g == NULL)\n\t\treturn(REG_ESPACE);\n\tp->strip = (sop *)malloc(p->ssize * sizeof(sop));\n\tp->slen = 0;\n\tif (p->strip == NULL) {\n\t\tfree((char *)g);\n\t\treturn(REG_ESPACE);\n\t}\n\n\t\/* set things up *\/\n\tp->g = g;\n\tp->next = (char *)pattern;\t\/* convenience; we do not modify it *\/\n\tp->end = p->next + len;\n\tp->error = 0;\n\tp->ncsalloc = 0;\n\tp->charset = preg->charset;\n\tfor (i = 0; i < NPAREN; i++) {\n\t\tp->pbegin[i] = 0;\n\t\tp->pend[i] = 0;\n\t}\n\tg->csetsize = NC;\n\tg->sets = NULL;\n\tg->setbits = NULL;\n\tg->ncsets = 0;\n\tg->cflags = cflags;\n\tg->iflags = 0;\n\tg->nbol = 0;\n\tg->neol = 0;\n\tg->must = NULL;\n\tg->mlen = 0;\n\tg->nsub = 0;\n\tg->ncategories = 1;\t\/* category 0 is \"everything else\" *\/\n\tg->categories = &g->catspace[-(CHAR_MIN)];\n\t(void) memset((char *)g->catspace, 0, NC*sizeof(cat_t));\n\tg->backrefs = 0;\n\n\t\/* do it *\/\n\tEMIT(OEND, 0);\n\tg->firststate = THERE();\n\tif (cflags®_EXTENDED)\n\t\tp_ere(p, OUT);\n\telse if (cflags®_NOSPEC)\n\t\tp_str(p);\n\telse\n\t\tp_bre(p, OUT, OUT);\n\tEMIT(OEND, 0);\n\tg->laststate = THERE();\n\n\t\/* tidy up loose ends and fill things in *\/\n\tcategorize(p, g);\n\tstripsnug(p, g);\n\tfindmust(p, g);\n\tg->nplus = pluscount(p, g);\n\tg->magic = MAGIC2;\n\tpreg->re_nsub = g->nsub;\n\tpreg->re_g = g;\n\tpreg->re_magic = MAGIC1;\n#ifndef REDEBUG\n\t\/* not debugging, so can't rely on the assert() in regexec() *\/\n\tif (g->iflags&BAD)\n\t\tSETERROR(REG_ASSERT);\n#endif\n\n\t\/* win or lose, we're done *\/\n\tif (p->error != 0)\t\/* lose *\/\n\t\tmy_regfree(preg);\n\treturn(p->error);\n}","target":0,"code_token_length":958,"total_token_length":1289,"max_tokens_setting":2048} +{"idx":348572,"func":"void JPXStream::init()\n{\n Object oLen, cspace, smaskInData;\n if (getDict()) {\n oLen = getDict()->lookup(\"Length\");\n cspace = getDict()->lookup(\"ColorSpace\");\n smaskInData = getDict()->lookup(\"SMaskInData\");\n }\n\n int bufSize = BUFFER_INITIAL_SIZE;\n if (oLen.isInt()) bufSize = oLen.getInt();\n\n bool indexed = false;\n if (cspace.isArray() && cspace.arrayGetLength() > 0) {\n const Object cstype = cspace.arrayGet(0);\n if (cstype.isName(\"Indexed\")) indexed = true;\n }\n\n priv->smaskInData = 0;\n if (smaskInData.isInt()) priv->smaskInData = smaskInData.getInt();\n\n int length = 0;\n unsigned char *buf = str->toUnsignedChars(&length, bufSize);\n priv->init2(OPJ_CODEC_JP2, buf, length, indexed);\n gfree(buf);\n\n if (priv->image) {\n int numComps = (priv->image) ? priv->image->numcomps : 1;\n int alpha = 0;\n if (priv->image) {\n if (priv->image->color_space == OPJ_CLRSPC_SRGB && numComps == 4) { numComps = 3; alpha = 1; }\n else if (priv->image->color_space == OPJ_CLRSPC_SYCC && numComps == 4) { numComps = 3; alpha = 1; }\n else if (numComps == 2) { numComps = 1; alpha = 1; }\n else if (numComps > 4) { numComps = 4; alpha = 1; }\n else { alpha = 0; }\n }\n priv->npixels = priv->image->comps[0].w * priv->image->comps[0].h;\n priv->ncomps = priv->image->numcomps;\n if (alpha == 1 && priv->smaskInData == 0) priv->ncomps--;\n for (int component = 0; component < priv->ncomps; component++) {\n if (priv->image->comps[component].data == nullptr) {\n close();\n break;\n }\n unsigned char *cdata = (unsigned char *)priv->image->comps[component].data;\n int adjust = 0;\n int depth = priv->image->comps[component].prec;\n if (priv->image->comps[component].prec > 8)\n\tadjust = priv->image->comps[component].prec - 8;\n int sgndcorr = 0;\n if (priv->image->comps[component].sgnd)\n\tsgndcorr = 1 << (priv->image->comps[0].prec - 1);\n for (int i = 0; i < priv->npixels; i++) {\n\tint r = priv->image->comps[component].data[i];\n\t*(cdata++) = adjustComp(r, adjust, depth, sgndcorr, indexed);\n }\n }\n } else {\n priv->npixels = 0;\n }\n\n priv->counter = 0;\n priv->ccounter = 0;\n priv->inited = true;\n}","target":1,"code_token_length":751,"total_token_length":1082,"max_tokens_setting":2048} +{"idx":237683,"func":"FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)\n{\n\tFLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;\n\n if(\n#if FLAC__HAS_OGG\n \/* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC *\/\n !decoder->private_->is_ogg &&\n#endif\n\t\tdecoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)\n ) {\n *bytes = 0;\n\t\tdecoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;\n return false;\n }\n else if(*bytes > 0) {\n \/* While seeking, it is possible for our seek to land in the\n\t\t * middle of audio data that looks exactly like a frame header\n\t\t * from a future version of an encoder. When that happens, our\n\t\t * error callback will get an\n\t\t * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its\n\t\t * unparseable_frame_count. But there is a remote possibility\n\t\t * that it is properly synced at such a \"future-codec frame\",\n\t\t * so to make sure, we wait to see many \"unparseable\" errors in\n\t\t * a row before bailing out.\n\t\t *\/\n if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {\n\t\t\tdecoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;\n return false;\n }\n else {\n const FLAC__StreamDecoderReadStatus status =\n#if FLAC__HAS_OGG\n\t\t\t\tdecoder->private_->is_ogg?\n\t\t\t\tread_callback_ogg_aspect_(decoder, buffer, bytes) :\n#endif\n\t\t\t\tdecoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)\n ;\n if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {\n\t\t\t\tdecoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;\n return false;\n }\n else if(*bytes == 0) {\n if(\n\t\t\t\t\tstatus == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||\n (\n#if FLAC__HAS_OGG\n \/* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC *\/\n !decoder->private_->is_ogg &&\n#endif\n\t\t\t\t\t\tdecoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)\n )\n ) {\n\t\t\t\t\tdecoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;\n return false;\n }\n else\n return true;\n }\n else\n return true;\n }\n }\n else {\n \/* abort to avoid a deadlock *\/\n\t\tdecoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;\n return false;\n }\n \/* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around\n\t * for Ogg FLAC. This is because the ogg decoder aspect can lose sync\n\t * and at the same time hit the end of the stream (for example, seeking\n\t * to a point that is after the beginning of the last Ogg page). There\n\t * is no way to report an Ogg sync loss through the callbacks (see note\n\t * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.\n\t * So to keep the decoder from stopping at this point we gate the call\n\t * to the eof_callback and let the Ogg decoder aspect set the\n\t * end-of-stream state when it is needed.\n\t *\/\n}\n","target":0,"code_token_length":759,"total_token_length":1090,"max_tokens_setting":2048} +{"idx":88854,"func":"decode(message *m, const char *in, unsigned char *out, unsigned char (*decoder)(char), bool isFast)\n{\n\tunsigned char b1, b2, b3, b4;\n\tunsigned char cb1, cb2, cb3;\t\/* carried over from last line *\/\n\n\t\/*cli_dbgmsg(\"decode %s (len %d isFast %d base64chars %d)\\n\", in,\n\t\tin ? strlen(in) : 0,\n\t\tisFast, m->base64chars);*\/\n\n\tcb1 = cb2 = cb3 = '\\0';\n\n\tswitch(m->base64chars) {\n\t\tcase 3:\n\t\t\tcb3 = m->base64_3;\n\t\t\t\/* FALLTHROUGH *\/\n\t\tcase 2:\n\t\t\tcb2 = m->base64_2;\n\t\t\t\/* FALLTHROUGH *\/\n\t\tcase 1:\n\t\t\tcb1 = m->base64_1;\n\t\t\tisFast = FALSE;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tassert(m->base64chars <= 3);\n\t}\n\n\tif(isFast)\n\t\t\/* Fast decoding if not last line *\/\n\t\twhile(*in) {\n\t\t\tb1 = (*decoder)(*in++);\n\t\t\tb2 = (*decoder)(*in++);\n\t\t\tb3 = (*decoder)(*in++);\n\t\t\t\/*\n\t\t\t * Put this line here to help on some compilers which\n\t\t\t * can make use of some architecure's ability to\n\t\t\t * multiprocess when different variables can be\n\t\t\t * updated at the same time - here b3 is used in\n\t\t\t * one line, b1\/b2 in the next and b4 in the next after\n\t\t\t * that, b3 and b4 rely on in but b1\/b2 don't\n\t\t\t *\/\n\t\t\t*out++ = (b1 << 2) | ((b2 >> 4) & 0x3);\n\t\t\tb4 = (*decoder)(*in++);\n\t\t\t*out++ = (b2 << 4) | ((b3 >> 2) & 0xF);\n\t\t\t*out++ = (b3 << 6) | (b4 & 0x3F);\n\t\t}\n\telse if(in == NULL) {\t\/* flush *\/\n\t\tint nbytes;\n\n\t\tif(m->base64chars == 0)\n\t\t\treturn out;\n\n\t\tcli_dbgmsg(\"base64chars = %d (%c %c %c)\\n\", m->base64chars,\n\t\t\tisalnum(cb1) ? cb1 : '@',\n\t\t\tisalnum(cb2) ? cb2 : '@',\n\t\t\tisalnum(cb3) ? cb3 : '@');\n\n\t\tm->base64chars--;\n\t\tb1 = cb1;\n\t\tnbytes = 1;\n\n\t\tif(m->base64chars) {\n\t\t\tm->base64chars--;\n\t\t\tb2 = cb2;\n\n\t\t\tif(m->base64chars) {\n\t\t\t\tnbytes = 2;\n\t\t\t\tm->base64chars--;\n\t\t\t\tb3 = cb3;\n\t\t\t\tnbytes = 3;\n\t\t\t} else if(b2)\n\t\t\t\tnbytes = 2;\n\t\t}\n\n\t\tswitch(nbytes) {\n\t\t\tcase 3:\n\t\t\t\tb4 = '\\0';\n\t\t\t\t\/* fall through *\/\n\t\t\tcase 4:\n\t\t\t\t*out++ = (b1 << 2) | ((b2 >> 4) & 0x3);\n\t\t\t\t*out++ = (b2 << 4) | ((b3 >> 2) & 0xF);\n\t\t\t\tif((nbytes == 4) || (b3&0x3))\n\t\t\t\t\t*out++ = (b3 << 6) | (b4 & 0x3F);\n\t\t\t\tbreak;\n\t\t\tcase 2:\n\t\t\t\t*out++ = (b1 << 2) | ((b2 >> 4) & 0x3);\n\t\t\t\tif((b2 << 4) & 0xFF)\n\t\t\t\t\t*out++ = b2 << 4;\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\t\t\t\t*out++ = b1 << 2;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tassert(0);\n\t\t}\n\t} else while(*in) {\n\t\tint nbytes;\n\n\t\tif(m->base64chars) {\n\t\t\tm->base64chars--;\n\t\t\tb1 = cb1;\n\t\t} else\n\t\t\tb1 = (*decoder)(*in++);\n\n\t\tif(*in == '\\0') {\n\t\t\tb2 = '\\0';\n\t\t\tnbytes = 1;\n\t\t} else {\n\t\t\tif(m->base64chars) {\n\t\t\t\tm->base64chars--;\n\t\t\t\tb2 = cb2;\n\t\t\t} else\n\t\t\t\tb2 = (*decoder)(*in++);\n\n\t\t\tif(*in == '\\0') {\n\t\t\t\tb3 = '\\0';\n\t\t\t\tnbytes = 2;\n\t\t\t} else {\n\t\t\t\tif(m->base64chars) {\n\t\t\t\t\tm->base64chars--;\n\t\t\t\t\tb3 = cb3;\n\t\t\t\t} else\n\t\t\t\t\tb3 = (*decoder)(*in++);\n\n\t\t\t\tif(*in == '\\0') {\n\t\t\t\t\tb4 = '\\0';\n\t\t\t\t\tnbytes = 3;\n\t\t\t\t} else {\n\t\t\t\t\tb4 = (*decoder)(*in++);\n\t\t\t\t\tnbytes = 4;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tswitch(nbytes) {\n\t\t\tcase 4:\n\t\t\t\t*out++ = (b1 << 2) | ((b2 >> 4) & 0x3);\n\t\t\t\t*out++ = (b2 << 4) | ((b3 >> 2) & 0xF);\n\t\t\t\t*out++ = (b3 << 6) | (b4 & 0x3F);\n\t\t\t\tcontinue;\n\t\t\tcase 3:\n\t\t\t\tm->base64_3 = b3;\n\t\t\tcase 2:\n\t\t\t\tm->base64_2 = b2;\n\t\t\tcase 1:\n\t\t\t\tm->base64_1 = b1;\n\t\t\t\tm->base64chars = nbytes;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tassert(0);\n\t\t}\n\t\tbreak;\t\/* nbytes != 4 => EOL *\/\n\t}\n\treturn out;\n}","target":0,"code_token_length":1289,"total_token_length":1620,"max_tokens_setting":2048} +{"idx":238561,"func":"void UiSceneCreator::CreateBackground() {\n auto background =\n Create(k2dBrowsingTexturedBackground, kPhaseBackground);\n background->SetVisible(false);\n background->AddBinding(base::MakeUnique>(\n base::BindRepeating(\n [](Model* m) {\n return m->background_available && m->background_loaded;\n },\n base::Unretained(model_)),\n base::BindRepeating([](UiElement* e, const bool& v) { e->SetVisible(v); },\n base::Unretained(background.get()))));\n scene_->AddUiElement(k2dBrowsingBackground, std::move(background));\n\n auto element = Create(k2dBrowsingDefaultBackground, kPhaseNone);\n element->set_hit_testable(false);\n element->AddBinding(base::MakeUnique>(\n base::BindRepeating([](Model* m) { return !m->background_available; },\n base::Unretained(model_)),\n base::BindRepeating([](UiElement* e, const bool& v) { e->SetVisible(v); },\n base::Unretained(element.get()))));\n scene_->AddUiElement(k2dBrowsingBackground, std::move(element));\n\n struct Panel {\n UiElementName name;\n int x_offset;\n int y_offset;\n int z_offset;\n int x_rotation;\n int y_rotation;\n int angle;\n };\n const std::vector panels = {\n {kBackgroundFront, 0, 0, -1, 0, 1, 0},\n {kBackgroundLeft, -1, 0, 0, 0, 1, 1},\n {kBackgroundBack, 0, 0, 1, 0, 1, 2},\n {kBackgroundRight, 1, 0, 0, 0, 1, 3},\n {kBackgroundTop, 0, 1, 0, 1, 0, 1},\n {kBackgroundBottom, 0, -1, 0, 1, 0, -1},\n };\n for (auto& panel : panels) {\n auto panel_element = Create(panel.name, kPhaseBackground);\n panel_element->SetSize(kSceneSize, kSceneSize);\n panel_element->SetTranslate(panel.x_offset * kSceneSize \/ 2,\n panel.y_offset * kSceneSize \/ 2,\n panel.z_offset * kSceneSize \/ 2);\n panel_element->SetRotate(panel.x_rotation, panel.y_rotation, 0,\n base::kPiFloat \/ 2 * panel.angle);\n panel_element->set_hit_testable(false);\n BindColor(model_, panel_element.get(), &ColorScheme::world_background,\n &Rect::SetColor);\n panel_element->AddBinding(\n VR_BIND_FUNC(bool, Model, model_, should_render_web_vr() == false,\n UiElement, panel_element.get(), SetVisible));\n scene_->AddUiElement(k2dBrowsingDefaultBackground,\n std::move(panel_element));\n }\n\n auto floor = Create(kFloor, kPhaseFloorCeiling);\n floor->SetSize(kSceneSize, kSceneSize);\n floor->SetTranslate(0.0, -kSceneHeight \/ 2, 0.0);\n floor->SetRotate(1, 0, 0, -base::kPiFloat \/ 2);\n floor->set_gridline_count(kFloorGridlineCount);\n floor->set_focusable(false);\n BindColor(model_, floor.get(), &ColorScheme::floor, &Grid::SetCenterColor);\n BindColor(model_, floor.get(), &ColorScheme::world_background,\n &Grid::SetEdgeColor);\n BindColor(model_, floor.get(), &ColorScheme::floor_grid, &Grid::SetGridColor);\n scene_->AddUiElement(k2dBrowsingDefaultBackground, std::move(floor));\n\n auto ceiling = Create(kCeiling, kPhaseFloorCeiling);\n ceiling->set_focusable(false);\n ceiling->SetSize(kSceneSize, kSceneSize);\n ceiling->SetTranslate(0.0, kSceneHeight \/ 2, 0.0);\n ceiling->SetRotate(1, 0, 0, base::kPiFloat \/ 2);\n BindColor(model_, ceiling.get(), &ColorScheme::ceiling,\n &Rect::SetCenterColor);\n BindColor(model_, ceiling.get(), &ColorScheme::world_background,\n &Rect::SetEdgeColor);\n scene_->AddUiElement(k2dBrowsingDefaultBackground, std::move(ceiling));\n}\n","target":0,"code_token_length":999,"total_token_length":1330,"max_tokens_setting":2048} +{"idx":289098,"func":"TEST_F ( ExtensionServiceSyncTest , ProcessSyncDataSettings ) {\n InitializeEmptyExtensionService ( ) ;\n extension_sync_service ( ) -> MergeDataAndStartSyncing ( syncer : : EXTENSIONS , syncer : : SyncDataList ( ) , base : : MakeUnique < syncer : : FakeSyncChangeProcessor > ( ) , base : : MakeUnique < syncer : : SyncErrorFactoryMock > ( ) ) ;\n InstallCRX ( data_dir ( ) . AppendASCII ( \"good.crx\" ) , INSTALL_NEW ) ;\n EXPECT_TRUE ( service ( ) -> IsExtensionEnabled ( good_crx ) ) ;\n EXPECT_FALSE ( extensions : : util : : IsIncognitoEnabled ( good_crx , profile ( ) ) ) ;\n auto get_permissions_modifier = [ this ] ( ) {\n const Extension * extension = registry ( ) -> GetExtensionById ( good_crx , extensions : : ExtensionRegistry : : EVERYTHING ) ;\n return base : : MakeUnique < ScriptingPermissionsModifier > ( profile ( ) , extension ) ;\n }\n ;\n EXPECT_FALSE ( get_permissions_modifier ( ) -> HasSetAllowedOnAllUrls ( ) ) ;\n const bool kDefaultAllowedScripting = ScriptingPermissionsModifier : : DefaultAllowedOnAllUrls ( ) ;\n EXPECT_EQ ( kDefaultAllowedScripting , get_permissions_modifier ( ) -> IsAllowedOnAllUrls ( ) ) ;\n sync_pb : : EntitySpecifics specifics ;\n sync_pb : : ExtensionSpecifics * ext_specifics = specifics . mutable_extension ( ) ;\n ext_specifics -> set_id ( good_crx ) ;\n ext_specifics -> set_version ( service ( ) -> GetInstalledExtension ( good_crx ) -> version ( ) -> GetString ( ) ) ;\n ext_specifics -> set_enabled ( false ) ;\n {\n SyncChangeList list = MakeSyncChangeList ( good_crx , specifics , SyncChange : : ACTION_UPDATE ) ;\n extension_sync_service ( ) -> ProcessSyncChanges ( FROM_HERE , list ) ;\n EXPECT_FALSE ( service ( ) -> IsExtensionEnabled ( good_crx ) ) ;\n EXPECT_FALSE ( extensions : : util : : IsIncognitoEnabled ( good_crx , profile ( ) ) ) ;\n EXPECT_FALSE ( get_permissions_modifier ( ) -> HasSetAllowedOnAllUrls ( ) ) ;\n EXPECT_EQ ( kDefaultAllowedScripting , get_permissions_modifier ( ) -> IsAllowedOnAllUrls ( ) ) ;\n }\n {\n ext_specifics -> set_enabled ( true ) ;\n ext_specifics -> set_incognito_enabled ( true ) ;\n SyncChangeList list = MakeSyncChangeList ( good_crx , specifics , SyncChange : : ACTION_UPDATE ) ;\n extension_sync_service ( ) -> ProcessSyncChanges ( FROM_HERE , list ) ;\n EXPECT_TRUE ( service ( ) -> IsExtensionEnabled ( good_crx ) ) ;\n EXPECT_TRUE ( extensions : : util : : IsIncognitoEnabled ( good_crx , profile ( ) ) ) ;\n }\n {\n ext_specifics -> set_enabled ( false ) ;\n ext_specifics -> set_incognito_enabled ( true ) ;\n SyncChangeList list = MakeSyncChangeList ( good_crx , specifics , SyncChange : : ACTION_UPDATE ) ;\n extension_sync_service ( ) -> ProcessSyncChanges ( FROM_HERE , list ) ;\n EXPECT_FALSE ( service ( ) -> IsExtensionEnabled ( good_crx ) ) ;\n EXPECT_TRUE ( extensions : : util : : IsIncognitoEnabled ( good_crx , profile ( ) ) ) ;\n }\n {\n ext_specifics -> set_enabled ( true ) ;\n ext_specifics -> set_all_urls_enabled ( ! kDefaultAllowedScripting ) ;\n SyncChangeList list = MakeSyncChangeList ( good_crx , specifics , SyncChange : : ACTION_UPDATE ) ;\n extension_sync_service ( ) -> ProcessSyncChanges ( FROM_HERE , list ) ;\n EXPECT_TRUE ( service ( ) -> IsExtensionEnabled ( good_crx ) ) ;\n EXPECT_TRUE ( get_permissions_modifier ( ) -> HasSetAllowedOnAllUrls ( ) ) ;\n EXPECT_EQ ( ! kDefaultAllowedScripting , get_permissions_modifier ( ) -> IsAllowedOnAllUrls ( ) ) ;\n }\n {\n ext_specifics -> set_all_urls_enabled ( kDefaultAllowedScripting ) ;\n SyncChangeList list = MakeSyncChangeList ( good_crx , specifics , SyncChange : : ACTION_UPDATE ) ;\n extension_sync_service ( ) -> ProcessSyncChanges ( FROM_HERE , list ) ;\n EXPECT_TRUE ( service ( ) -> IsExtensionEnabled ( good_crx ) ) ;\n EXPECT_TRUE ( get_permissions_modifier ( ) -> HasSetAllowedOnAllUrls ( ) ) ;\n EXPECT_EQ ( kDefaultAllowedScripting , get_permissions_modifier ( ) -> IsAllowedOnAllUrls ( ) ) ;\n }\n EXPECT_FALSE ( service ( ) -> pending_extension_manager ( ) -> IsIdPending ( good_crx ) ) ;\n }","target":0,"code_token_length":966,"total_token_length":1297,"max_tokens_setting":2048} +{"idx":392563,"func":"static void pcpu_balance_workfn(struct work_struct *work)\n{\n\tLIST_HEAD(to_free);\n\tstruct list_head *free_head = &pcpu_slot[pcpu_nr_slots - 1];\n\tstruct pcpu_chunk *chunk, *next;\n\tint slot, nr_to_pop, ret;\n\n\t\/*\n\t * There's no reason to keep around multiple unused chunks and VM\n\t * areas can be scarce. Destroy all free chunks except for one.\n\t *\/\n\tmutex_lock(&pcpu_alloc_mutex);\n\tspin_lock_irq(&pcpu_lock);\n\n\tlist_for_each_entry_safe(chunk, next, free_head, list) {\n\t\tWARN_ON(chunk->immutable);\n\n\t\t\/* spare the first one *\/\n\t\tif (chunk == list_first_entry(free_head, struct pcpu_chunk, list))\n\t\t\tcontinue;\n\n\t\tlist_del_init(&chunk->map_extend_list);\n\t\tlist_move(&chunk->list, &to_free);\n\t}\n\n\tspin_unlock_irq(&pcpu_lock);\n\n\tlist_for_each_entry_safe(chunk, next, &to_free, list) {\n\t\tint rs, re;\n\n\t\tpcpu_for_each_pop_region(chunk, rs, re, 0, pcpu_unit_pages) {\n\t\t\tpcpu_depopulate_chunk(chunk, rs, re);\n\t\t\tspin_lock_irq(&pcpu_lock);\n\t\t\tpcpu_chunk_depopulated(chunk, rs, re);\n\t\t\tspin_unlock_irq(&pcpu_lock);\n\t\t}\n\t\tpcpu_destroy_chunk(chunk);\n\t}\n\n\t\/* service chunks which requested async area map extension *\/\n\tdo {\n\t\tint new_alloc = 0;\n\n\t\tspin_lock_irq(&pcpu_lock);\n\n\t\tchunk = list_first_entry_or_null(&pcpu_map_extend_chunks,\n\t\t\t\t\tstruct pcpu_chunk, map_extend_list);\n\t\tif (chunk) {\n\t\t\tlist_del_init(&chunk->map_extend_list);\n\t\t\tnew_alloc = pcpu_need_to_extend(chunk, false);\n\t\t}\n\n\t\tspin_unlock_irq(&pcpu_lock);\n\n\t\tif (new_alloc)\n\t\t\tpcpu_extend_area_map(chunk, new_alloc);\n\t} while (chunk);\n\n\t\/*\n\t * Ensure there are certain number of free populated pages for\n\t * atomic allocs. Fill up from the most packed so that atomic\n\t * allocs don't increase fragmentation. If atomic allocation\n\t * failed previously, always populate the maximum amount. This\n\t * should prevent atomic allocs larger than PAGE_SIZE from keeping\n\t * failing indefinitely; however, large atomic allocs are not\n\t * something we support properly and can be highly unreliable and\n\t * inefficient.\n\t *\/\nretry_pop:\n\tif (pcpu_atomic_alloc_failed) {\n\t\tnr_to_pop = PCPU_EMPTY_POP_PAGES_HIGH;\n\t\t\/* best effort anyway, don't worry about synchronization *\/\n\t\tpcpu_atomic_alloc_failed = false;\n\t} else {\n\t\tnr_to_pop = clamp(PCPU_EMPTY_POP_PAGES_HIGH -\n\t\t\t\t pcpu_nr_empty_pop_pages,\n\t\t\t\t 0, PCPU_EMPTY_POP_PAGES_HIGH);\n\t}\n\n\tfor (slot = pcpu_size_to_slot(PAGE_SIZE); slot < pcpu_nr_slots; slot++) {\n\t\tint nr_unpop = 0, rs, re;\n\n\t\tif (!nr_to_pop)\n\t\t\tbreak;\n\n\t\tspin_lock_irq(&pcpu_lock);\n\t\tlist_for_each_entry(chunk, &pcpu_slot[slot], list) {\n\t\t\tnr_unpop = pcpu_unit_pages - chunk->nr_populated;\n\t\t\tif (nr_unpop)\n\t\t\t\tbreak;\n\t\t}\n\t\tspin_unlock_irq(&pcpu_lock);\n\n\t\tif (!nr_unpop)\n\t\t\tcontinue;\n\n\t\t\/* @chunk can't go away while pcpu_alloc_mutex is held *\/\n\t\tpcpu_for_each_unpop_region(chunk, rs, re, 0, pcpu_unit_pages) {\n\t\t\tint nr = min(re - rs, nr_to_pop);\n\n\t\t\tret = pcpu_populate_chunk(chunk, rs, rs + nr);\n\t\t\tif (!ret) {\n\t\t\t\tnr_to_pop -= nr;\n\t\t\t\tspin_lock_irq(&pcpu_lock);\n\t\t\t\tpcpu_chunk_populated(chunk, rs, rs + nr);\n\t\t\t\tspin_unlock_irq(&pcpu_lock);\n\t\t\t} else {\n\t\t\t\tnr_to_pop = 0;\n\t\t\t}\n\n\t\t\tif (!nr_to_pop)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (nr_to_pop) {\n\t\t\/* ran out of chunks to populate, create a new one and retry *\/\n\t\tchunk = pcpu_create_chunk();\n\t\tif (chunk) {\n\t\t\tspin_lock_irq(&pcpu_lock);\n\t\t\tpcpu_chunk_relocate(chunk, -1);\n\t\t\tspin_unlock_irq(&pcpu_lock);\n\t\t\tgoto retry_pop;\n\t\t}\n\t}\n\n\tmutex_unlock(&pcpu_alloc_mutex);\n}","target":0,"code_token_length":964,"total_token_length":1295,"max_tokens_setting":2048} +{"idx":419826,"func":"void server_process_syslog_message(\n Server *s,\n const char *buf,\n size_t raw_len,\n const struct ucred *ucred,\n const struct timeval *tv,\n const char *label,\n size_t label_len) {\n\n char *t, syslog_priority[sizeof(\"PRIORITY=\") + DECIMAL_STR_MAX(int)],\n syslog_facility[sizeof(\"SYSLOG_FACILITY=\") + DECIMAL_STR_MAX(int)];\n const char *msg, *syslog_ts, *a;\n _cleanup_free_ char *identifier = NULL, *pid = NULL,\n *dummy = NULL, *msg_msg = NULL, *msg_raw = NULL;\n int priority = LOG_USER | LOG_INFO, r;\n ClientContext *context = NULL;\n struct iovec *iovec;\n size_t n = 0, m, i, leading_ws, syslog_ts_len;\n bool store_raw;\n\n assert(s);\n assert(buf);\n \/* The message cannot be empty. *\/\n assert(raw_len > 0);\n \/* The buffer NUL-terminated and can be used a string. raw_len is the length\n * without the terminating NUL byte, the buffer is actually one bigger. *\/\n assert(buf[raw_len] == '\\0');\n\n if (ucred && pid_is_valid(ucred->pid)) {\n r = client_context_get(s, ucred->pid, ucred, label, label_len, NULL, &context);\n if (r < 0)\n log_warning_errno(r, \"Failed to retrieve credentials for PID \" PID_FMT \", ignoring: %m\", ucred->pid);\n }\n\n \/* We are creating a copy of the message because we want to forward the original message\n verbatim to the legacy syslog implementation *\/\n for (i = raw_len; i > 0; i--)\n if (!strchr(WHITESPACE, buf[i-1]))\n break;\n\n leading_ws = strspn(buf, WHITESPACE);\n\n if (i == 0)\n \/* The message contains only whitespaces *\/\n msg = buf + raw_len;\n else if (i == raw_len)\n \/* Nice! No need to strip anything on the end, let's optimize this a bit *\/\n msg = buf + leading_ws;\n else {\n msg = dummy = new(char, i - leading_ws + 1);\n if (!dummy) {\n log_oom();\n return;\n }\n\n memcpy(dummy, buf + leading_ws, i - leading_ws);\n dummy[i - leading_ws] = 0;\n }\n\n \/* We will add the SYSLOG_RAW= field when we stripped anything\n * _or_ if the input message contained NUL bytes. *\/\n store_raw = msg != buf || strlen(msg) != raw_len;\n\n syslog_parse_priority(&msg, &priority, true);\n\n if (!client_context_test_priority(context, priority))\n return;\n\n syslog_ts = msg;\n syslog_ts_len = syslog_skip_timestamp(&msg);\n if (syslog_ts_len == 0)\n \/* We failed to parse the full timestamp, store the raw message too *\/\n store_raw = true;\n\n syslog_parse_identifier(&msg, &identifier, &pid);\n\n if (s->forward_to_syslog)\n forward_syslog_raw(s, priority, buf, raw_len, ucred, tv);\n\n if (s->forward_to_kmsg)\n server_forward_kmsg(s, priority, identifier, msg, ucred);\n\n if (s->forward_to_console)\n server_forward_console(s, priority, identifier, msg, ucred);\n\n if (s->forward_to_wall)\n server_forward_wall(s, priority, identifier, msg, ucred);\n\n m = N_IOVEC_META_FIELDS + 8 + client_context_extra_fields_n_iovec(context);\n iovec = newa(struct iovec, m);\n\n iovec[n++] = IOVEC_MAKE_STRING(\"_TRANSPORT=syslog\");\n\n xsprintf(syslog_priority, \"PRIORITY=%i\", priority & LOG_PRIMASK);\n iovec[n++] = IOVEC_MAKE_STRING(syslog_priority);\n\n if (priority & LOG_FACMASK) {\n xsprintf(syslog_facility, \"SYSLOG_FACILITY=%i\", LOG_FAC(priority));\n iovec[n++] = IOVEC_MAKE_STRING(syslog_facility);\n }\n\n if (identifier) {\n a = strjoina(\"SYSLOG_IDENTIFIER=\", identifier);\n iovec[n++] = IOVEC_MAKE_STRING(a);\n }\n\n if (pid) {\n a = strjoina(\"SYSLOG_PID=\", pid);\n iovec[n++] = IOVEC_MAKE_STRING(a);\n }\n\n if (syslog_ts_len > 0) {\n const size_t hlen = strlen(\"SYSLOG_TIMESTAMP=\");\n\n t = newa(char, hlen + syslog_ts_len);\n memcpy(t, \"SYSLOG_TIMESTAMP=\", hlen);\n memcpy(t + hlen, syslog_ts, syslog_ts_len);\n\n iovec[n++] = IOVEC_MAKE(t, hlen + syslog_ts_len);\n }\n\n msg_msg = strjoin(\"MESSAGE=\", msg);\n if (!msg_msg) {\n log_oom();\n return;\n }\n iovec[n++] = IOVEC_MAKE_STRING(msg_msg);\n\n if (store_raw) {\n const size_t hlen = strlen(\"SYSLOG_RAW=\");\n\n msg_raw = new(char, hlen + raw_len);\n if (!msg_raw) {\n log_oom();\n return;\n }\n\n memcpy(msg_raw, \"SYSLOG_RAW=\", hlen);\n memcpy(msg_raw + hlen, buf, raw_len);\n\n iovec[n++] = IOVEC_MAKE(msg_raw, hlen + raw_len);\n }\n\n server_dispatch_message(s, iovec, n, m, context, tv, priority, 0);\n}","target":0,"code_token_length":1240,"total_token_length":1571,"max_tokens_setting":2048} +{"idx":414217,"func":"contact_list_uids_handler (LDAPOp *op,\n LDAPMessage *res)\n{\n\tLDAPGetContactListUIDsOp *contact_list_uids_op = (LDAPGetContactListUIDsOp *) op;\n\tEBookBackendLDAP *bl = E_BOOK_BACKEND_LDAP (op->backend);\n\tLDAPMessage *e;\n\tgint msg_type;\n\tGTimeVal start, end;\n\tgulong diff;\n\n\tif (enable_debug) {\n\t\tprintf (\"contact_list_uids_handler ...\\n\");\n\t\tg_get_current_time (&start);\n\t}\n\n\tg_rec_mutex_lock (&eds_ldap_handler_lock);\n\tif (!bl->priv->ldap) {\n\t\tg_rec_mutex_unlock (&eds_ldap_handler_lock);\n\t\te_data_book_respond_get_contact_list_uids (op->book, op->opid, EDB_ERROR_NOT_CONNECTED (), NULL);\n\t\tldap_op_finished (op);\n\t\tif (enable_debug)\n\t\t\tprintf (\"contact_list_uids_handler ... ldap handler is NULL \\n\");\n\t\treturn;\n\t}\n\tg_rec_mutex_unlock (&eds_ldap_handler_lock);\n\n\tmsg_type = ldap_msgtype (res);\n\tif (msg_type == LDAP_RES_SEARCH_ENTRY) {\n\t\tg_rec_mutex_lock (&eds_ldap_handler_lock);\n\t\tif (bl->priv->ldap)\n\t\t\te = ldap_first_entry (bl->priv->ldap, res);\n\t\telse\n\t\t\te = NULL;\n\t\tg_rec_mutex_unlock (&eds_ldap_handler_lock);\n\n\t\twhile (NULL != e) {\n\t\t\tEContact *contact;\n\t\t\tgchar *uid = NULL;\n\n\t\t\tcontact = build_contact_from_entry (bl, e, NULL, &uid);\n\t\t\tg_clear_object (&contact);\n\n\t\t\tif (enable_debug)\n\t\t\t\tprintf (\"uid = %s\\n\", uid ? uid : \"(null)\");\n\n\t\t\tif (uid)\n\t\t\t\tcontact_list_uids_op->uids = g_slist_append (contact_list_uids_op->uids, uid);\n\n\t\t\tg_rec_mutex_lock (&eds_ldap_handler_lock);\n\t\t\tif (bl->priv->ldap)\n\t\t\t\te = ldap_next_entry (bl->priv->ldap, e);\n\t\t\telse\n\t\t\t\te = NULL;\n\t\t\tg_rec_mutex_unlock (&eds_ldap_handler_lock);\n\t\t}\n\t} else if (msg_type == LDAP_RES_SEARCH_REFERENCE) {\n\t\t\/* ignore references *\/\n\t} else if (msg_type == LDAP_RES_SEARCH_RESULT) {\n\t\tgchar *ldap_error_msg = NULL;\n\t\tgint ldap_error;\n\n\t\tg_rec_mutex_lock (&eds_ldap_handler_lock);\n\t\tif (bl->priv->ldap) {\n\t\t\tldap_parse_result (\n\t\t\t\tbl->priv->ldap, res, &ldap_error,\n\t\t\t\tNULL, &ldap_error_msg, NULL, NULL, 0);\n\t\t} else {\n\t\t\tldap_error = LDAP_SERVER_DOWN;\n\t\t}\n\t\tg_rec_mutex_unlock (&eds_ldap_handler_lock);\n\t\tif (ldap_error != LDAP_SUCCESS) {\n\t\t\tg_warning (\n\t\t\t\t\"contact_list_uids_handler: %02X (%s), additional info: %s\",\n\t\t\t\tldap_error,\n\t\t\t\tldap_err2string (ldap_error), ldap_error_msg);\n\t\t}\n\t\tif (ldap_error_msg)\n\t\t\tldap_memfree (ldap_error_msg);\n\n\t\tg_warning (\"search returned %d\\n\", ldap_error);\n\n\t\tif (ldap_error == LDAP_TIMELIMIT_EXCEEDED)\n\t\t\te_data_book_respond_get_contact_list_uids (\n\t\t\t\top->book, op->opid,\n\t\t\t\tEDB_ERROR (SEARCH_TIME_LIMIT_EXCEEDED),\n\t\t\t\tcontact_list_uids_op->uids);\n\t\telse if (ldap_error == LDAP_SIZELIMIT_EXCEEDED)\n\t\t\te_data_book_respond_get_contact_list_uids (\n\t\t\t\top->book, op->opid,\n\t\t\t\tEDB_ERROR (SEARCH_SIZE_LIMIT_EXCEEDED),\n\t\t\t\tcontact_list_uids_op->uids);\n\t\telse if (ldap_error == LDAP_SUCCESS)\n\t\t\te_data_book_respond_get_contact_list_uids (\n\t\t\t\top->book, op->opid,\n\t\t\t\tEDB_ERROR (SUCCESS),\n\t\t\t\tcontact_list_uids_op->uids);\n\t\telse\n\t\t\te_data_book_respond_get_contact_list_uids (\n\t\t\t\top->book, op->opid,\n\t\t\t\tldap_error_to_response (ldap_error),\n\t\t\t\tcontact_list_uids_op->uids);\n\n\t\tldap_op_finished (op);\n\t\tif (enable_debug) {\n\t\t\tprintf (\"contact_list_uids_handler success \");\n\t\t\tg_get_current_time (&end);\n\t\t\tdiff = end.tv_sec * 1000 + end.tv_usec \/ 1000;\n\t\t\tdiff -= start.tv_sec * 1000 + start.tv_usec \/ 1000;\n\t\t\tprintf (\"and took %ld.%03ld seconds\\n\", diff \/ 1000, diff % 1000);\n\t\t}\n\t}\n\telse {\n\t\tg_warning (\"unhandled search result type %d returned\", msg_type);\n\t\te_data_book_respond_get_contact_list_uids (\n\t\t\top->book, op->opid,\n\t\t\te_data_book_create_error_fmt (E_DATA_BOOK_STATUS_OTHER_ERROR,\n\t\t\t_(\"%s: Unhandled search result type %d returned\"), G_STRFUNC, msg_type),\n\t\t\tNULL);\n\t\tldap_op_finished (op);\n\t}\n}","target":0,"code_token_length":1093,"total_token_length":1424,"max_tokens_setting":2048} +{"idx":151709,"func":"CConfig CUser::ToConfig() const {\n CConfig config;\n CConfig passConfig;\n\n CString sHash;\n switch (m_eHashType) {\n case HASH_NONE:\n sHash = \"Plain\";\n break;\n case HASH_MD5:\n sHash = \"MD5\";\n break;\n case HASH_SHA256:\n sHash = \"SHA256\";\n break;\n }\n passConfig.AddKeyValuePair(\"Salt\", m_sPassSalt);\n passConfig.AddKeyValuePair(\"Method\", sHash);\n passConfig.AddKeyValuePair(\"Hash\", GetPass());\n config.AddSubConfig(\"Pass\", \"password\", passConfig);\n\n config.AddKeyValuePair(\"Nick\", GetNick());\n config.AddKeyValuePair(\"AltNick\", GetAltNick());\n config.AddKeyValuePair(\"Ident\", GetIdent());\n config.AddKeyValuePair(\"RealName\", GetRealName());\n config.AddKeyValuePair(\"BindHost\", GetBindHost());\n config.AddKeyValuePair(\"DCCBindHost\", GetDCCBindHost());\n config.AddKeyValuePair(\"QuitMsg\", GetQuitMsg());\n if (CZNC::Get().GetStatusPrefix() != GetStatusPrefix())\n config.AddKeyValuePair(\"StatusPrefix\", GetStatusPrefix());\n config.AddKeyValuePair(\"Skin\", GetSkinName());\n config.AddKeyValuePair(\"ChanModes\", GetDefaultChanModes());\n config.AddKeyValuePair(\"ChanBufferSize\", CString(GetChanBufferSize()));\n config.AddKeyValuePair(\"QueryBufferSize\", CString(GetQueryBufferSize()));\n config.AddKeyValuePair(\"AutoClearChanBuffer\",\n CString(AutoClearChanBuffer()));\n config.AddKeyValuePair(\"AutoClearQueryBuffer\",\n CString(AutoClearQueryBuffer()));\n config.AddKeyValuePair(\"MultiClients\", CString(MultiClients()));\n config.AddKeyValuePair(\"DenyLoadMod\", CString(DenyLoadMod()));\n config.AddKeyValuePair(\"Admin\", CString(IsAdmin()));\n config.AddKeyValuePair(\"DenySetBindHost\", CString(DenySetBindHost()));\n config.AddKeyValuePair(\"TimestampFormat\", GetTimestampFormat());\n config.AddKeyValuePair(\"AppendTimestamp\", CString(GetTimestampAppend()));\n config.AddKeyValuePair(\"PrependTimestamp\", CString(GetTimestampPrepend()));\n config.AddKeyValuePair(\"AuthOnlyViaModule\", CString(AuthOnlyViaModule()));\n config.AddKeyValuePair(\"Timezone\", m_sTimezone);\n config.AddKeyValuePair(\"JoinTries\", CString(m_uMaxJoinTries));\n config.AddKeyValuePair(\"MaxNetworks\", CString(m_uMaxNetworks));\n config.AddKeyValuePair(\"MaxQueryBuffers\", CString(m_uMaxQueryBuffers));\n config.AddKeyValuePair(\"MaxJoins\", CString(m_uMaxJoins));\n config.AddKeyValuePair(\"ClientEncoding\", GetClientEncoding());\n config.AddKeyValuePair(\"Language\", GetLanguage());\n config.AddKeyValuePair(\"NoTrafficTimeout\", CString(GetNoTrafficTimeout()));\n\n \/\/ Allow Hosts\n if (!m_ssAllowedHosts.empty()) {\n for (const CString& sHost : m_ssAllowedHosts) {\n config.AddKeyValuePair(\"Allow\", sHost);\n }\n }\n\n \/\/ CTCP Replies\n if (!m_mssCTCPReplies.empty()) {\n for (const auto& itb : m_mssCTCPReplies) {\n config.AddKeyValuePair(\"CTCPReply\",\n itb.first.AsUpper() + \" \" + itb.second);\n }\n }\n\n \/\/ Modules\n const CModules& Mods = GetModules();\n\n if (!Mods.empty()) {\n for (CModule* pMod : Mods) {\n CString sArgs = pMod->GetArgs();\n\n if (!sArgs.empty()) {\n sArgs = \" \" + sArgs;\n }\n\n config.AddKeyValuePair(\"LoadModule\", pMod->GetModName() + sArgs);\n }\n }\n\n \/\/ Networks\n for (CIRCNetwork* pNetwork : m_vIRCNetworks) {\n config.AddSubConfig(\"Network\", pNetwork->GetName(),\n pNetwork->ToConfig());\n }\n\n return config;\n}","target":0,"code_token_length":816,"total_token_length":1147,"max_tokens_setting":2048} +{"idx":18464,"func":"static int mpeg_decode_postinit ( AVCodecContext * avctx ) {\n Mpeg1Context * s1 = avctx -> priv_data ;\n MpegEncContext * s = & s1 -> mpeg_enc_ctx ;\n uint8_t old_permutation [ 64 ] ;\n if ( ( s1 -> mpeg_enc_ctx_allocated == 0 ) || avctx -> coded_width != s -> width || avctx -> coded_height != s -> height || s1 -> save_width != s -> width || s1 -> save_height != s -> height || s1 -> save_aspect_info != s -> aspect_ratio_info || s1 -> save_progressive_seq != s -> progressive_sequence || 0 ) {\n if ( s1 -> mpeg_enc_ctx_allocated ) {\n ParseContext pc = s -> parse_context ;\n s -> parse_context . buffer = 0 ;\n ff_MPV_common_end ( s ) ;\n s -> parse_context = pc ;\n }\n if ( ( s -> width == 0 ) || ( s -> height == 0 ) ) return - 2 ;\n avcodec_set_dimensions ( avctx , s -> width , s -> height ) ;\n avctx -> bit_rate = s -> bit_rate ;\n s1 -> save_aspect_info = s -> aspect_ratio_info ;\n s1 -> save_width = s -> width ;\n s1 -> save_height = s -> height ;\n s1 -> save_progressive_seq = s -> progressive_sequence ;\n avctx -> has_b_frames = ! s -> low_delay ;\n if ( avctx -> codec_id == AV_CODEC_ID_MPEG1VIDEO ) {\n avctx -> time_base . den = ff_mpeg12_frame_rate_tab [ s -> frame_rate_index ] . num ;\n avctx -> time_base . num = ff_mpeg12_frame_rate_tab [ s -> frame_rate_index ] . den ;\n avctx -> sample_aspect_ratio = av_d2q ( 1.0 \/ ff_mpeg1_aspect [ s -> aspect_ratio_info ] , 255 ) ;\n avctx -> ticks_per_frame = 1 ;\n }\n else {\n av_reduce ( & s -> avctx -> time_base . den , & s -> avctx -> time_base . num , ff_mpeg12_frame_rate_tab [ s -> frame_rate_index ] . num * s1 -> frame_rate_ext . num * 2 , ff_mpeg12_frame_rate_tab [ s -> frame_rate_index ] . den * s1 -> frame_rate_ext . den , 1 << 30 ) ;\n avctx -> ticks_per_frame = 2 ;\n if ( s -> aspect_ratio_info > 1 ) {\n AVRational dar = av_mul_q ( av_div_q ( ff_mpeg2_aspect [ s -> aspect_ratio_info ] , ( AVRational ) {\n s1 -> pan_scan . width , s1 -> pan_scan . height }\n ) , ( AVRational ) {\n s -> width , s -> height }\n ) ;\n if ( ( s1 -> pan_scan . width == 0 ) || ( s1 -> pan_scan . height == 0 ) || ( av_cmp_q ( dar , ( AVRational ) {\n 4 , 3 }\n ) && av_cmp_q ( dar , ( AVRational ) {\n 16 , 9 }\n ) ) ) {\n s -> avctx -> sample_aspect_ratio = av_div_q ( ff_mpeg2_aspect [ s -> aspect_ratio_info ] , ( AVRational ) {\n s -> width , s -> height }\n ) ;\n }\n else {\n s -> avctx -> sample_aspect_ratio = av_div_q ( ff_mpeg2_aspect [ s -> aspect_ratio_info ] , ( AVRational ) {\n s1 -> pan_scan . width , s1 -> pan_scan . height }\n ) ;\n av_dlog ( avctx , \"A %d\/%d\\n\" , ff_mpeg2_aspect [ s -> aspect_ratio_info ] . num , ff_mpeg2_aspect [ s -> aspect_ratio_info ] . den ) ;\n av_dlog ( avctx , \"B %d\/%d\\n\" , s -> avctx -> sample_aspect_ratio . num , s -> avctx -> sample_aspect_ratio . den ) ;\n }\n }\n else {\n s -> avctx -> sample_aspect_ratio = ff_mpeg2_aspect [ s -> aspect_ratio_info ] ;\n }\n }\n avctx -> pix_fmt = mpeg_get_pixelformat ( avctx ) ;\n avctx -> hwaccel = ff_find_hwaccel ( avctx -> codec -> id , avctx -> pix_fmt ) ;\n if ( avctx -> pix_fmt == AV_PIX_FMT_XVMC_MPEG2_IDCT || avctx -> hwaccel || s -> avctx -> codec -> capabilities & CODEC_CAP_HWACCEL_VDPAU ) if ( avctx -> idct_algo == FF_IDCT_AUTO ) avctx -> idct_algo = FF_IDCT_SIMPLE ;\n memcpy ( old_permutation , s -> dsp . idct_permutation , 64 * sizeof ( uint8_t ) ) ;\n if ( ff_MPV_common_init ( s ) < 0 ) return - 2 ;\n quant_matrix_rebuild ( s -> intra_matrix , old_permutation , s -> dsp . idct_permutation ) ;\n quant_matrix_rebuild ( s -> inter_matrix , old_permutation , s -> dsp . idct_permutation ) ;\n quant_matrix_rebuild ( s -> chroma_intra_matrix , old_permutation , s -> dsp . idct_permutation ) ;\n quant_matrix_rebuild ( s -> chroma_inter_matrix , old_permutation , s -> dsp . idct_permutation ) ;\n s1 -> mpeg_enc_ctx_allocated = 1 ;\n }\n return 0 ;\n }","target":0,"code_token_length":1155,"total_token_length":1486,"max_tokens_setting":2048} +{"idx":414613,"func":"static int __mb_check_buddy(struct ext4_buddy *e4b, char *file,\n\t\t\t\tconst char *function, int line)\n{\n\tstruct super_block *sb = e4b->bd_sb;\n\tint order = e4b->bd_blkbits + 1;\n\tint max;\n\tint max2;\n\tint i;\n\tint j;\n\tint k;\n\tint count;\n\tstruct ext4_group_info *grp;\n\tint fragments = 0;\n\tint fstart;\n\tstruct list_head *cur;\n\tvoid *buddy;\n\tvoid *buddy2;\n\n\t{\n\t\tstatic int mb_check_counter;\n\t\tif (mb_check_counter++ % 100 != 0)\n\t\t\treturn 0;\n\t}\n\n\twhile (order > 1) {\n\t\tbuddy = mb_find_buddy(e4b, order, &max);\n\t\tMB_CHECK_ASSERT(buddy);\n\t\tbuddy2 = mb_find_buddy(e4b, order - 1, &max2);\n\t\tMB_CHECK_ASSERT(buddy2);\n\t\tMB_CHECK_ASSERT(buddy != buddy2);\n\t\tMB_CHECK_ASSERT(max * 2 == max2);\n\n\t\tcount = 0;\n\t\tfor (i = 0; i < max; i++) {\n\n\t\t\tif (mb_test_bit(i, buddy)) {\n\t\t\t\t\/* only single bit in buddy2 may be 1 *\/\n\t\t\t\tif (!mb_test_bit(i << 1, buddy2)) {\n\t\t\t\t\tMB_CHECK_ASSERT(\n\t\t\t\t\t\tmb_test_bit((i<<1)+1, buddy2));\n\t\t\t\t} else if (!mb_test_bit((i << 1) + 1, buddy2)) {\n\t\t\t\t\tMB_CHECK_ASSERT(\n\t\t\t\t\t\tmb_test_bit(i << 1, buddy2));\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t\/* both bits in buddy2 must be 1 *\/\n\t\t\tMB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));\n\t\t\tMB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));\n\n\t\t\tfor (j = 0; j < (1 << order); j++) {\n\t\t\t\tk = (i * (1 << order)) + j;\n\t\t\t\tMB_CHECK_ASSERT(\n\t\t\t\t\t!mb_test_bit(k, e4b->bd_bitmap));\n\t\t\t}\n\t\t\tcount++;\n\t\t}\n\t\tMB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);\n\t\torder--;\n\t}\n\n\tfstart = -1;\n\tbuddy = mb_find_buddy(e4b, 0, &max);\n\tfor (i = 0; i < max; i++) {\n\t\tif (!mb_test_bit(i, buddy)) {\n\t\t\tMB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);\n\t\t\tif (fstart == -1) {\n\t\t\t\tfragments++;\n\t\t\t\tfstart = i;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tfstart = -1;\n\t\t\/* check used bits only *\/\n\t\tfor (j = 0; j < e4b->bd_blkbits + 1; j++) {\n\t\t\tbuddy2 = mb_find_buddy(e4b, j, &max2);\n\t\t\tk = i >> j;\n\t\t\tMB_CHECK_ASSERT(k < max2);\n\t\t\tMB_CHECK_ASSERT(mb_test_bit(k, buddy2));\n\t\t}\n\t}\n\tMB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));\n\tMB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);\n\n\tgrp = ext4_get_group_info(sb, e4b->bd_group);\n\tlist_for_each(cur, &grp->bb_prealloc_list) {\n\t\text4_group_t groupnr;\n\t\tstruct ext4_prealloc_space *pa;\n\t\tpa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);\n\t\text4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);\n\t\tMB_CHECK_ASSERT(groupnr == e4b->bd_group);\n\t\tfor (i = 0; i < pa->pa_len; i++)\n\t\t\tMB_CHECK_ASSERT(mb_test_bit(k + i, buddy));\n\t}\n\treturn 0;\n}","target":0,"code_token_length":870,"total_token_length":1201,"max_tokens_setting":2048} +{"idx":144435,"func":"COMPS_HSList* comps_mrtree_keys(COMPS_MRTree * rt) {\n COMPS_HSList *tmplist, *tmp_subnodes, *ret;\n COMPS_HSListItem *it;\n struct Pair {\n COMPS_HSList * subnodes;\n char * key;\n char added;\n } *pair, *parent_pair;\n\n pair = malloc(sizeof(struct Pair));\n pair->subnodes = rt->subnodes;\n pair->key = NULL;\n pair->added = 0;\n\n tmplist = comps_hslist_create();\n comps_hslist_init(tmplist, NULL, NULL, &free);\n ret = comps_hslist_create();\n comps_hslist_init(ret, NULL, NULL, &free);\n comps_hslist_append(tmplist, pair, 0);\n\n while (tmplist->first != NULL) {\n it = tmplist->first;\n comps_hslist_remove(tmplist, tmplist->first);\n tmp_subnodes = ((struct Pair*)it->data)->subnodes;\n parent_pair = (struct Pair*) it->data;\n free(it);\n\n for (it = tmp_subnodes->first; it != NULL; it=it->next) {\n pair = malloc(sizeof(struct Pair));\n pair->subnodes = ((COMPS_MRTreeData*)it->data)->subnodes;\n pair->added = 0;\n\n if (parent_pair->key != NULL) {\n pair->key =\n malloc(sizeof(char)\n * (strlen(((COMPS_MRTreeData*)it->data)->key)\n + strlen(parent_pair->key) + 1));\n memcpy(pair->key, parent_pair->key,\n sizeof(char) * strlen(parent_pair->key));\n memcpy(pair->key+strlen(parent_pair->key),\n ((COMPS_MRTreeData*)it->data)->key,\n sizeof(char)*(strlen(((COMPS_MRTreeData*)it->data)->key)+1));\n } else {\n pair->key = malloc(sizeof(char)*\n (strlen(((COMPS_MRTreeData*)it->data)->key) +\n 1));\n memcpy(pair->key, ((COMPS_MRTreeData*)it->data)->key,\n sizeof(char)*(strlen(((COMPS_MRTreeData*)it->data)->key)+1));\n }\n \/* current node has data *\/\n if (((COMPS_MRTreeData*)it->data)->data->first != NULL) {\n \/\/printf(\"data not null for |%s|\\n\", pair->key);\n comps_hslist_append(ret, pair->key, 0);\n pair->added = 1;\n if (((COMPS_MRTreeData*)it->data)->subnodes->first != NULL) {\n\/\/ printf(\"subnodes found\\b\");\n comps_hslist_append(tmplist, pair, 0);\n } else {\n free(pair);\n }\n \/* current node hasn't data *\/\n } else {\n if (((COMPS_MRTreeData*)it->data)->subnodes->first) {\n comps_hslist_append(tmplist, pair, 0);\n } else {\n free(pair->key);\n free(pair);\n }\n }\n }\n if (parent_pair->added == 0)\n free(parent_pair->key);\n free(parent_pair);\n }\n comps_hslist_destroy(&tmplist);\n return ret;\n}","target":0,"code_token_length":718,"total_token_length":1049,"max_tokens_setting":2048} +{"idx":340773,"func":"static int mov_write_packet(AVFormatContext *s, AVPacket *pkt)\n\n{\n\n MOVContext *mov = s->priv_data;\n\n ByteIOContext *pb = s->pb;\n\n MOVTrack *trk = &mov->tracks[pkt->stream_index];\n\n AVCodecContext *enc = trk->enc;\n\n unsigned int samplesInChunk = 0;\n\n int size= pkt->size;\n\n\n\n if (url_is_streamed(s->pb)) return 0; \/* Can't handle that *\/\n\n if (!size) return 0; \/* Discard 0 sized packets *\/\n\n\n\n if (enc->codec_id == CODEC_ID_AMR_NB) {\n\n \/* We must find out how many AMR blocks there are in one packet *\/\n\n static uint16_t packed_size[16] =\n\n {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 0};\n\n int len = 0;\n\n\n\n while (len < size && samplesInChunk < 100) {\n\n len += packed_size[(pkt->data[len] >> 3) & 0x0F];\n\n samplesInChunk++;\n\n }\n\n if(samplesInChunk > 1){\n\n av_log(s, AV_LOG_ERROR, \"fatal error, input is not a single packet, implement a AVParser for it\\n\");\n\n return -1;\n\n }\n\n } else if (trk->sampleSize)\n\n samplesInChunk = size\/trk->sampleSize;\n\n else\n\n samplesInChunk = 1;\n\n\n\n \/* copy extradata if it exists *\/\n\n if (trk->vosLen == 0 && enc->extradata_size > 0) {\n\n trk->vosLen = enc->extradata_size;\n\n trk->vosData = av_malloc(trk->vosLen);\n\n memcpy(trk->vosData, enc->extradata, trk->vosLen);\n\n }\n\n\n\n if (enc->codec_id == CODEC_ID_H264 && trk->vosLen > 0 && *(uint8_t *)trk->vosData != 1) {\n\n \/* from x264 or from bytestream h264 *\/\n\n \/* nal reformating needed *\/\n\n int ret = ff_avc_parse_nal_units(pkt->data, &pkt->data, &pkt->size);\n\n if (ret < 0)\n\n return ret;\n\n assert(pkt->size);\n\n size = pkt->size;\n\n } else if (enc->codec_id == CODEC_ID_DNXHD && !trk->vosLen) {\n\n \/* copy frame header to create needed atoms *\/\n\n if (size < 640)\n\n return -1;\n\n trk->vosLen = 640;\n\n trk->vosData = av_malloc(trk->vosLen);\n\n memcpy(trk->vosData, pkt->data, 640);\n\n }\n\n\n\n if (!(trk->entry % MOV_INDEX_CLUSTER_SIZE)) {\n\n trk->cluster = av_realloc(trk->cluster, (trk->entry + MOV_INDEX_CLUSTER_SIZE) * sizeof(*trk->cluster));\n\n if (!trk->cluster)\n\n return -1;\n\n }\n\n\n\n trk->cluster[trk->entry].pos = url_ftell(pb);\n\n trk->cluster[trk->entry].samplesInChunk = samplesInChunk;\n\n trk->cluster[trk->entry].size = size;\n\n trk->cluster[trk->entry].entries = samplesInChunk;\n\n trk->cluster[trk->entry].dts = pkt->dts;\n\n trk->trackDuration = pkt->dts - trk->cluster[0].dts + pkt->duration;\n\n\n\n if(enc->codec_type == CODEC_TYPE_VIDEO) {\n\n if (pkt->dts != pkt->pts)\n\n trk->hasBframes = 1;\n\n trk->cluster[trk->entry].cts = pkt->pts - pkt->dts;\n\n trk->cluster[trk->entry].key_frame = !!(pkt->flags & PKT_FLAG_KEY);\n\n if(trk->cluster[trk->entry].key_frame)\n\n trk->hasKeyframes++;\n\n }\n\n trk->entry++;\n\n trk->sampleCount += samplesInChunk;\n\n mov->mdat_size += size;\n\n\n\n put_buffer(pb, pkt->data, size);\n\n\n\n put_flush_packet(pb);\n\n return 0;\n\n}\n","target":0,"code_token_length":982,"total_token_length":1313,"max_tokens_setting":2048} +{"idx":288646,"func":"int SRP_VBASE_init ( SRP_VBASE * vb , char * verifier_file ) {\n int error_code ;\n STACK_OF ( SRP_gN ) * SRP_gN_tab = sk_SRP_gN_new_null ( ) ;\n char * last_index = NULL ;\n int i ;\n char * * pp ;\n SRP_gN * gN = NULL ;\n SRP_user_pwd * user_pwd = NULL ;\n TXT_DB * tmpdb = NULL ;\n BIO * in = BIO_new ( BIO_s_file ( ) ) ;\n error_code = SRP_ERR_OPEN_FILE ;\n if ( in == NULL || BIO_read_filename ( in , verifier_file ) <= 0 ) goto err ;\n error_code = SRP_ERR_VBASE_INCOMPLETE_FILE ;\n if ( ( tmpdb = TXT_DB_read ( in , DB_NUMBER ) ) == NULL ) goto err ;\n error_code = SRP_ERR_MEMORY ;\n if ( vb -> seed_key ) {\n last_index = SRP_get_default_gN ( NULL ) -> id ;\n }\n for ( i = 0 ;\n i < sk_OPENSSL_PSTRING_num ( tmpdb -> data ) ;\n i ++ ) {\n pp = sk_OPENSSL_PSTRING_value ( tmpdb -> data , i ) ;\n if ( pp [ DB_srptype ] [ 0 ] == DB_SRP_INDEX ) {\n if ( ( gN = ( SRP_gN * ) OPENSSL_malloc ( sizeof ( SRP_gN ) ) ) == NULL ) goto err ;\n if ( ! ( gN -> id = BUF_strdup ( pp [ DB_srpid ] ) ) || ! ( gN -> N = SRP_gN_place_bn ( vb -> gN_cache , pp [ DB_srpverifier ] ) ) || ! ( gN -> g = SRP_gN_place_bn ( vb -> gN_cache , pp [ DB_srpsalt ] ) ) || sk_SRP_gN_insert ( SRP_gN_tab , gN , 0 ) == 0 ) goto err ;\n gN = NULL ;\n if ( vb -> seed_key != NULL ) {\n last_index = pp [ DB_srpid ] ;\n }\n }\n else if ( pp [ DB_srptype ] [ 0 ] == DB_SRP_VALID ) {\n SRP_gN * lgN ;\n if ( ( lgN = SRP_get_gN_by_id ( pp [ DB_srpgN ] , SRP_gN_tab ) ) != NULL ) {\n error_code = SRP_ERR_MEMORY ;\n if ( ( user_pwd = SRP_user_pwd_new ( ) ) == NULL ) goto err ;\n SRP_user_pwd_set_gN ( user_pwd , lgN -> g , lgN -> N ) ;\n if ( ! SRP_user_pwd_set_ids ( user_pwd , pp [ DB_srpid ] , pp [ DB_srpinfo ] ) ) goto err ;\n error_code = SRP_ERR_VBASE_BN_LIB ;\n if ( ! SRP_user_pwd_set_sv ( user_pwd , pp [ DB_srpsalt ] , pp [ DB_srpverifier ] ) ) goto err ;\n if ( sk_SRP_user_pwd_insert ( vb -> users_pwd , user_pwd , 0 ) == 0 ) goto err ;\n user_pwd = NULL ;\n }\n }\n }\n if ( last_index != NULL ) {\n if ( ( ( gN = SRP_get_gN_by_id ( last_index , SRP_gN_tab ) ) == NULL ) ) {\n error_code = SRP_ERR_VBASE_BN_LIB ;\n goto err ;\n }\n vb -> default_g = gN -> g ;\n vb -> default_N = gN -> N ;\n gN = NULL ;\n }\n error_code = SRP_NO_ERROR ;\n err : if ( gN != NULL ) {\n OPENSSL_free ( gN -> id ) ;\n OPENSSL_free ( gN ) ;\n }\n SRP_user_pwd_free ( user_pwd ) ;\n if ( tmpdb ) TXT_DB_free ( tmpdb ) ;\n if ( in ) BIO_free_all ( in ) ;\n sk_SRP_gN_free ( SRP_gN_tab ) ;\n return error_code ;\n }","target":0,"code_token_length":827,"total_token_length":1158,"max_tokens_setting":2048} +{"idx":446548,"func":"virDomainVcpuParse(virDomainDefPtr def,\n xmlXPathContextPtr ctxt,\n virDomainXMLOptionPtr xmlopt)\n{\n int n;\n xmlNodePtr vcpuNode;\n size_t i;\n unsigned int maxvcpus;\n unsigned int vcpus;\n g_autofree char *tmp = NULL;\n g_autofree xmlNodePtr *nodes = NULL;\n\n vcpus = maxvcpus = 1;\n\n if ((vcpuNode = virXPathNode(\".\/vcpu[1]\", ctxt))) {\n if ((tmp = virXMLNodeContentString(vcpuNode))) {\n if (virStrToLong_ui(tmp, NULL, 10, &maxvcpus) < 0) {\n virReportError(VIR_ERR_XML_ERROR, \"%s\",\n _(\"maximum vcpus count must be an integer\"));\n return -1;\n }\n VIR_FREE(tmp);\n }\n\n if ((tmp = virXMLPropString(vcpuNode, \"current\"))) {\n if (virStrToLong_ui(tmp, NULL, 10, &vcpus) < 0) {\n virReportError(VIR_ERR_XML_ERROR, \"%s\",\n _(\"current vcpus count must be an integer\"));\n return -1;\n }\n VIR_FREE(tmp);\n } else {\n vcpus = maxvcpus;\n }\n\n tmp = virXMLPropString(vcpuNode, \"placement\");\n if (tmp) {\n if ((def->placement_mode =\n virDomainCpuPlacementModeTypeFromString(tmp)) < 0) {\n virReportError(VIR_ERR_CONFIG_UNSUPPORTED,\n _(\"Unsupported CPU placement mode '%s'\"),\n tmp);\n return -1;\n }\n VIR_FREE(tmp);\n } else {\n def->placement_mode = VIR_DOMAIN_CPU_PLACEMENT_MODE_STATIC;\n }\n\n if (def->placement_mode != VIR_DOMAIN_CPU_PLACEMENT_MODE_AUTO) {\n tmp = virXMLPropString(vcpuNode, \"cpuset\");\n if (tmp) {\n if (virBitmapParse(tmp, &def->cpumask, VIR_DOMAIN_CPUMASK_LEN) < 0)\n return -1;\n\n if (virBitmapIsAllClear(def->cpumask)) {\n virReportError(VIR_ERR_CONFIG_UNSUPPORTED,\n _(\"Invalid value of 'cpuset': %s\"), tmp);\n return -1;\n }\n\n VIR_FREE(tmp);\n }\n }\n }\n\n if (virDomainDefSetVcpusMax(def, maxvcpus, xmlopt) < 0)\n return -1;\n\n if ((n = virXPathNodeSet(\".\/vcpus\/vcpu\", ctxt, &nodes)) < 0)\n return -1;\n\n if (n) {\n \/* if individual vcpu states are provided take them as master *\/\n def->individualvcpus = true;\n\n for (i = 0; i < n; i++) {\n virDomainVcpuDefPtr vcpu;\n int state;\n unsigned int id;\n unsigned int order;\n\n if (!(tmp = virXMLPropString(nodes[i], \"id\")) ||\n virStrToLong_uip(tmp, NULL, 10, &id) < 0) {\n virReportError(VIR_ERR_XML_ERROR, \"%s\",\n _(\"missing or invalid vcpu id\"));\n return -1;\n }\n\n VIR_FREE(tmp);\n\n if (id >= def->maxvcpus) {\n virReportError(VIR_ERR_XML_ERROR,\n _(\"vcpu id '%u' is out of range of maximum \"\n \"vcpu count\"), id);\n return -1;\n }\n\n vcpu = virDomainDefGetVcpu(def, id);\n\n if (!(tmp = virXMLPropString(nodes[i], \"enabled\"))) {\n virReportError(VIR_ERR_XML_ERROR, \"%s\",\n _(\"missing vcpu enabled state\"));\n return -1;\n }\n\n if ((state = virTristateBoolTypeFromString(tmp)) < 0) {\n virReportError(VIR_ERR_XML_ERROR,\n _(\"invalid vcpu 'enabled' value '%s'\"), tmp);\n return -1;\n }\n VIR_FREE(tmp);\n\n vcpu->online = state == VIR_TRISTATE_BOOL_YES;\n\n if ((tmp = virXMLPropString(nodes[i], \"hotpluggable\"))) {\n int hotpluggable;\n if ((hotpluggable = virTristateBoolTypeFromString(tmp)) < 0) {\n virReportError(VIR_ERR_XML_ERROR,\n _(\"invalid vcpu 'hotpluggable' value '%s'\"), tmp);\n return -1;\n }\n vcpu->hotpluggable = hotpluggable;\n VIR_FREE(tmp);\n }\n\n if ((tmp = virXMLPropString(nodes[i], \"order\"))) {\n if (virStrToLong_uip(tmp, NULL, 10, &order) < 0) {\n virReportError(VIR_ERR_XML_ERROR, \"%s\",\n _(\"invalid vcpu order\"));\n return -1;\n }\n vcpu->order = order;\n VIR_FREE(tmp);\n }\n }\n } else {\n if (virDomainDefSetVcpus(def, vcpus) < 0)\n return -1;\n }\n\n return 0;\n}","target":0,"code_token_length":1133,"total_token_length":1464,"max_tokens_setting":2048} +{"idx":63037,"func":"WriteCompressedType(mat_t *mat,matvar_t *matvar,z_streamp z)\n{\n int err;\n mat_uint32_t comp_buf[512];\n mat_uint32_t uncomp_buf[512] = {0,};\n size_t byteswritten = 0, nelems = 1;\n\n if ( MAT_C_EMPTY == matvar->class_type ) {\n \/* exit early if this is an empty data *\/\n return byteswritten;\n }\n\n err = SafeMulDims(matvar, &nelems);\n if ( err ) {\n Mat_Critical(\"Integer multiplication overflow\");\n return byteswritten;\n }\n\n switch ( matvar->class_type ) {\n case MAT_C_DOUBLE:\n case MAT_C_SINGLE:\n case MAT_C_INT64:\n case MAT_C_UINT64:\n case MAT_C_INT32:\n case MAT_C_UINT32:\n case MAT_C_INT16:\n case MAT_C_UINT16:\n case MAT_C_INT8:\n case MAT_C_UINT8:\n {\n \/* WriteCompressedData makes sure uncompressed data is aligned\n * on an 8-byte boundary *\/\n if ( matvar->isComplex ) {\n mat_complex_split_t *complex_data = (mat_complex_split_t*)matvar->data;\n\n if ( NULL == matvar->data )\n complex_data = &null_complex_data;\n\n byteswritten += WriteCompressedData(mat,z,\n complex_data->Re,nelems,matvar->data_type);\n byteswritten += WriteCompressedData(mat,z,\n complex_data->Im,nelems,matvar->data_type);\n } else {\n byteswritten += WriteCompressedData(mat,z,\n matvar->data,nelems,matvar->data_type);\n }\n break;\n }\n case MAT_C_CHAR:\n {\n byteswritten += WriteCompressedCharData(mat,z,matvar->data,\n nelems,matvar->data_type);\n break;\n }\n case MAT_C_CELL:\n {\n size_t i;\n matvar_t **cells = (matvar_t **)matvar->data;\n\n \/* Check for an empty cell array *\/\n if ( matvar->nbytes == 0 || matvar->data_size == 0 ||\n matvar->data == NULL )\n break;\n nelems = matvar->nbytes \/ matvar->data_size;\n for ( i = 0; i < nelems; i++ )\n WriteCompressedCellArrayField(mat,cells[i],z);\n break;\n }\n case MAT_C_STRUCT:\n {\n int buf_size = 512;\n mat_int16_t fieldname_type = MAT_T_INT32;\n mat_int16_t fieldname_data_size = 4;\n unsigned char *padzero;\n int fieldname_size;\n size_t maxlen = 0, nfields, i, nelems_x_nfields;\n mat_int32_t array_name_type = MAT_T_INT8;\n matvar_t **fields = (matvar_t **)matvar->data;\n\n nfields = matvar->internal->num_fields;\n \/* Check for a structure with no fields *\/\n if ( nfields < 1 ) {\n fieldname_size = 1;\n uncomp_buf[0] = (fieldname_data_size << 16) | fieldname_type;\n uncomp_buf[1] = fieldname_size;\n uncomp_buf[2] = array_name_type;\n uncomp_buf[3] = 0;\n z->next_in = ZLIB_BYTE_PTR(uncomp_buf);\n z->avail_in = 16;\n do {\n z->next_out = ZLIB_BYTE_PTR(comp_buf);\n z->avail_out = buf_size*sizeof(*comp_buf);\n deflate(z,Z_NO_FLUSH);\n byteswritten += fwrite(comp_buf,1,buf_size*\n sizeof(*comp_buf)-z->avail_out,(FILE*)mat->fp);\n } while ( z->avail_out == 0 );\n break;\n }\n\n for ( i = 0; i < nfields; i++ ) {\n size_t len = strlen(matvar->internal->fieldnames[i]);\n if ( len > maxlen )\n maxlen = len;\n }\n maxlen++;\n fieldname_size = maxlen;\n while ( nfields*fieldname_size % 8 != 0 )\n fieldname_size++;\n uncomp_buf[0] = (fieldname_data_size << 16) | fieldname_type;\n uncomp_buf[1] = fieldname_size;\n uncomp_buf[2] = array_name_type;\n uncomp_buf[3] = nfields*fieldname_size;\n\n padzero = (unsigned char*)calloc(fieldname_size,1);\n z->next_in = ZLIB_BYTE_PTR(uncomp_buf);\n z->avail_in = 16;\n do {\n z->next_out = ZLIB_BYTE_PTR(comp_buf);\n z->avail_out = buf_size*sizeof(*comp_buf);\n deflate(z,Z_NO_FLUSH);\n byteswritten += fwrite(comp_buf,1,\n buf_size*sizeof(*comp_buf)-z->avail_out,(FILE*)mat->fp);\n } while ( z->avail_out == 0 );\n for ( i = 0; i < nfields; i++ ) {\n size_t len = strlen(matvar->internal->fieldnames[i]);\n memset(padzero,'\\0',fieldname_size);\n memcpy(padzero,matvar->internal->fieldnames[i],len);\n z->next_in = ZLIB_BYTE_PTR(padzero);\n z->avail_in = fieldname_size;\n do {\n z->next_out = ZLIB_BYTE_PTR(comp_buf);\n z->avail_out = buf_size*sizeof(*comp_buf);\n deflate(z,Z_NO_FLUSH);\n byteswritten += fwrite(comp_buf,1,\n buf_size*sizeof(*comp_buf)-z->avail_out,(FILE*)mat->fp);\n } while ( z->avail_out == 0 );\n }\n free(padzero);\n err = SafeMul(&nelems_x_nfields, nelems, nfields);\n if ( err ) {\n Mat_Critical(\"Integer multiplication overflow\");\n return byteswritten;\n }\n for ( i = 0; i < nelems_x_nfields; i++ )\n byteswritten += WriteCompressedStructField(mat,fields[i],z);\n break;\n }\n case MAT_C_SPARSE:\n {\n mat_sparse_t *sparse = (mat_sparse_t*)matvar->data;\n\n byteswritten += WriteCompressedData(mat,z,sparse->ir,\n sparse->nir,MAT_T_INT32);\n byteswritten += WriteCompressedData(mat,z,sparse->jc,\n sparse->njc,MAT_T_INT32);\n if ( matvar->isComplex ) {\n mat_complex_split_t *complex_data = (mat_complex_split_t*)sparse->data;\n byteswritten += WriteCompressedData(mat,z,\n complex_data->Re,sparse->ndata,matvar->data_type);\n byteswritten += WriteCompressedData(mat,z,\n complex_data->Im,sparse->ndata,matvar->data_type);\n } else {\n byteswritten += WriteCompressedData(mat,z,\n sparse->data,sparse->ndata,matvar->data_type);\n }\n break;\n }\n case MAT_C_FUNCTION:\n case MAT_C_OBJECT:\n case MAT_C_EMPTY:\n case MAT_C_OPAQUE:\n break;\n }\n\n return byteswritten;\n}","target":0,"code_token_length":1596,"total_token_length":1927,"max_tokens_setting":2048} +{"idx":497128,"func":"static int decode_ics_info(AACContext *ac, IndividualChannelStream *ics,\n GetBitContext *gb)\n{\n int aot = ac->oc[1].m4ac.object_type;\n if (aot != AOT_ER_AAC_ELD) {\n if (get_bits1(gb)) {\n av_log(ac->avctx, AV_LOG_ERROR, \"Reserved bit set.\\n\");\n return AVERROR_INVALIDDATA;\n }\n ics->window_sequence[1] = ics->window_sequence[0];\n ics->window_sequence[0] = get_bits(gb, 2);\n if (aot == AOT_ER_AAC_LD &&\n ics->window_sequence[0] != ONLY_LONG_SEQUENCE) {\n av_log(ac->avctx, AV_LOG_ERROR,\n \"AAC LD is only defined for ONLY_LONG_SEQUENCE but \"\n \"window sequence %d found.\\n\", ics->window_sequence[0]);\n ics->window_sequence[0] = ONLY_LONG_SEQUENCE;\n return AVERROR_INVALIDDATA;\n }\n ics->use_kb_window[1] = ics->use_kb_window[0];\n ics->use_kb_window[0] = get_bits1(gb);\n }\n ics->num_window_groups = 1;\n ics->group_len[0] = 1;\n if (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) {\n int i;\n ics->max_sfb = get_bits(gb, 4);\n for (i = 0; i < 7; i++) {\n if (get_bits1(gb)) {\n ics->group_len[ics->num_window_groups - 1]++;\n } else {\n ics->num_window_groups++;\n ics->group_len[ics->num_window_groups - 1] = 1;\n }\n }\n ics->num_windows = 8;\n ics->swb_offset = ff_swb_offset_128[ac->oc[1].m4ac.sampling_index];\n ics->num_swb = ff_aac_num_swb_128[ac->oc[1].m4ac.sampling_index];\n ics->tns_max_bands = ff_tns_max_bands_128[ac->oc[1].m4ac.sampling_index];\n ics->predictor_present = 0;\n } else {\n ics->max_sfb = get_bits(gb, 6);\n ics->num_windows = 1;\n if (aot == AOT_ER_AAC_LD || aot == AOT_ER_AAC_ELD) {\n ics->swb_offset = ff_swb_offset_512[ac->oc[1].m4ac.sampling_index];\n ics->num_swb = ff_aac_num_swb_512[ac->oc[1].m4ac.sampling_index];\n ics->tns_max_bands = ff_tns_max_bands_512[ac->oc[1].m4ac.sampling_index];\n if (!ics->num_swb || !ics->swb_offset)\n return AVERROR_BUG;\n } else {\n ics->swb_offset = ff_swb_offset_1024[ac->oc[1].m4ac.sampling_index];\n ics->num_swb = ff_aac_num_swb_1024[ac->oc[1].m4ac.sampling_index];\n ics->tns_max_bands = ff_tns_max_bands_1024[ac->oc[1].m4ac.sampling_index];\n }\n if (aot != AOT_ER_AAC_ELD) {\n ics->predictor_present = get_bits1(gb);\n ics->predictor_reset_group = 0;\n }\n if (ics->predictor_present) {\n if (aot == AOT_AAC_MAIN) {\n if (decode_prediction(ac, ics, gb)) {\n goto fail;\n }\n } else if (aot == AOT_AAC_LC ||\n aot == AOT_ER_AAC_LC) {\n av_log(ac->avctx, AV_LOG_ERROR,\n \"Prediction is not allowed in AAC-LC.\\n\");\n goto fail;\n } else {\n if (aot == AOT_ER_AAC_LD) {\n av_log(ac->avctx, AV_LOG_ERROR,\n \"LTP in ER AAC LD not yet implemented.\\n\");\n return AVERROR_PATCHWELCOME;\n }\n if ((ics->ltp.present = get_bits(gb, 1)))\n decode_ltp(&ics->ltp, gb, ics->max_sfb);\n }\n }\n }\n\n if (ics->max_sfb > ics->num_swb) {\n av_log(ac->avctx, AV_LOG_ERROR,\n \"Number of scalefactor bands in group (%d) \"\n \"exceeds limit (%d).\\n\",\n ics->max_sfb, ics->num_swb);\n goto fail;\n }\n\n return 0;\nfail:\n ics->max_sfb = 0;\n return AVERROR_INVALIDDATA;\n}","target":0,"code_token_length":1163,"total_token_length":1494,"max_tokens_setting":2048} +{"idx":117013,"func":"void CLASS phase_one_load_raw_c()\n{\n static const int length[] = {8, 7, 6, 9, 11, 10, 5, 12, 14, 13};\n int *offset, len[2], pred[2], row, col, i, j;\n ushort *pixel;\n short(*c_black)[2], (*r_black)[2];\n#ifdef LIBRAW_LIBRARY_BUILD\n if (ph1.format == 6)\n throw LIBRAW_EXCEPTION_IO_CORRUPT;\n#endif\n\n pixel = (ushort *)calloc(raw_width * 3 + raw_height * 4, 2);\n merror(pixel, \"phase_one_load_raw_c()\");\n offset = (int *)(pixel + raw_width);\n fseek(ifp, strip_offset, SEEK_SET);\n for (row = 0; row < raw_height; row++)\n offset[row] = get4();\n c_black = (short(*)[2])(offset + raw_height);\n fseek(ifp, ph1.black_col, SEEK_SET);\n if (ph1.black_col)\n read_shorts((ushort *)c_black[0], raw_height * 2);\n r_black = c_black + raw_height;\n fseek(ifp, ph1.black_row, SEEK_SET);\n if (ph1.black_row)\n read_shorts((ushort *)r_black[0], raw_width * 2);\n\n#ifdef LIBRAW_LIBRARY_BUILD\n \/\/ Copy data to internal copy (ever if not read)\n if (ph1.black_col || ph1.black_row)\n {\n imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height * 2, sizeof(ushort));\n merror(imgdata.rawdata.ph1_cblack, \"phase_one_load_raw_c()\");\n memmove(imgdata.rawdata.ph1_cblack, (ushort *)c_black[0], raw_height * 2 * sizeof(ushort));\n imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width * 2, sizeof(ushort));\n merror(imgdata.rawdata.ph1_rblack, \"phase_one_load_raw_c()\");\n memmove(imgdata.rawdata.ph1_rblack, (ushort *)r_black[0], raw_width * 2 * sizeof(ushort));\n }\n#endif\n\n for (i = 0; i < 256; i++)\n curve[i] = i * i \/ 3.969 + 0.5;\n#ifdef LIBRAW_LIBRARY_BUILD\n try\n {\n#endif\n for (row = 0; row < raw_height; row++)\n {\n#ifdef LIBRAW_LIBRARY_BUILD\n checkCancel();\n#endif\n fseek(ifp, data_offset + offset[row], SEEK_SET);\n ph1_bits(-1);\n pred[0] = pred[1] = 0;\n for (col = 0; col < raw_width; col++)\n {\n if (col >= (raw_width & -8))\n len[0] = len[1] = 14;\n else if ((col & 7) == 0)\n for (i = 0; i < 2; i++)\n {\n for (j = 0; j < 5 && !ph1_bits(1); j++)\n ;\n if (j--)\n len[i] = length[j * 2 + ph1_bits(1)];\n }\n if ((i = len[col & 1]) == 14)\n pixel[col] = pred[col & 1] = ph1_bits(16);\n else\n pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1));\n if (pred[col & 1] >> 16)\n derror();\n if (ph1.format == 5 && pixel[col] < 256)\n pixel[col] = curve[pixel[col]];\n }\n#ifndef LIBRAW_LIBRARY_BUILD\n for (col = 0; col < raw_width; col++)\n {\n int shift = ph1.format == 8 ? 0 : 2;\n i = (pixel[col] << shift) - ph1.t_black + c_black[row][col >= ph1.split_col] +\n r_black[col][row >= ph1.split_row];\n if (i > 0)\n RAW(row, col) = i;\n }\n#else\n if (ph1.format == 8)\n memmove(&RAW(row, 0), &pixel[0], raw_width * 2);\n else\n for (col = 0; col < raw_width; col++)\n RAW(row, col) = pixel[col] << 2;\n#endif\n }\n#ifdef LIBRAW_LIBRARY_BUILD\n }\n catch (...)\n {\n free(pixel);\n throw;\n }\n#endif\n free(pixel);\n maximum = 0xfffc - ph1.t_black;\n}","target":0,"code_token_length":1057,"total_token_length":1388,"max_tokens_setting":2048} +{"idx":325653,"func":"int coroutine_fn bdrv_co_flush(BlockDriverState *bs)\n{\n int ret;\n BdrvTrackedRequest req;\n if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs) ||\n bdrv_is_sg(bs)) {\n return 0;\n }\n tracked_request_begin(&req, bs, 0, 0, BDRV_TRACKED_FLUSH);\n int current_gen = bs->write_gen;\n \/* Wait until any previous flushes are completed *\/\n while (bs->flush_started_gen != bs->flushed_gen) {\n qemu_co_queue_wait(&bs->flush_queue);\n }\n bs->flush_started_gen = current_gen;\n \/* Write back all layers by calling one driver function *\/\n if (bs->drv->bdrv_co_flush) {\n ret = bs->drv->bdrv_co_flush(bs);\n goto out;\n }\n \/* Write back cached data to the OS even with cache=unsafe *\/\n BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);\n if (bs->drv->bdrv_co_flush_to_os) {\n ret = bs->drv->bdrv_co_flush_to_os(bs);\n if (ret < 0) {\n goto out;\n }\n }\n \/* But don't actually force it to the disk with cache=unsafe *\/\n if (bs->open_flags & BDRV_O_NO_FLUSH) {\n goto flush_parent;\n }\n \/* Check if we really need to flush anything *\/\n if (bs->flushed_gen == current_gen) {\n goto flush_parent;\n }\n BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);\n if (bs->drv->bdrv_co_flush_to_disk) {\n ret = bs->drv->bdrv_co_flush_to_disk(bs);\n } else if (bs->drv->bdrv_aio_flush) {\n BlockAIOCB *acb;\n CoroutineIOCompletion co = {\n .coroutine = qemu_coroutine_self(),\n };\n acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);\n if (acb == NULL) {\n ret = -EIO;\n } else {\n qemu_coroutine_yield();\n ret = co.ret;\n }\n } else {\n \/*\n * Some block drivers always operate in either writethrough or unsafe\n * mode and don't support bdrv_flush therefore. Usually qemu doesn't\n * know how the server works (because the behaviour is hardcoded or\n * depends on server-side configuration), so we can't ensure that\n * everything is safe on disk. Returning an error doesn't work because\n * that would break guests even if the server operates in writethrough\n * mode.\n *\n * Let's hope the user knows what he's doing.\n *\/\n ret = 0;\n }\n if (ret < 0) {\n goto out;\n }\n \/* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH\n * in the case of cache=unsafe, so there are no useless flushes.\n *\/\nflush_parent:\n ret = bs->file ? bdrv_co_flush(bs->file->bs) : 0;\nout:\n \/* Notify any pending flushes that we have completed *\/\n bs->flushed_gen = current_gen;\n qemu_co_queue_restart_all(&bs->flush_queue);\n tracked_request_end(&req);\n return ret;\n}","target":1,"code_token_length":738,"total_token_length":1069,"max_tokens_setting":2048} +{"idx":8020,"func":"static int xar_get_toc_data_values(xmlTextReaderPtr reader, long *length, long *offset, long *size, int *encoding,\n unsigned char ** a_cksum, int * a_hash, unsigned char ** e_cksum, int * e_hash)\n{\n const xmlChar *name;\n int indata = 0, inea = 0;\n int rc, gotoffset=0, gotlength=0, gotsize=0;\n\n *a_cksum = NULL;\n *a_hash = XAR_CKSUM_NONE;\n *e_cksum = NULL;\n *e_hash = XAR_CKSUM_NONE;\n *encoding = CL_TYPE_ANY;\n\n rc = xmlTextReaderRead(reader);\n while (rc == 1) {\n name = xmlTextReaderConstLocalName(reader);\n if (indata || inea) {\n \/* cli_dbgmsg(\"cli_scanxar: xmlTextReaderRead read %s\\n\", name); *\/\n if (xmlStrEqual(name, (const xmlChar *)\"offset\") && \n xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {\n if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, offset))\n gotoffset=1;\n\n } else if (xmlStrEqual(name, (const xmlChar *)\"length\") &&\n xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {\n if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, length))\n gotlength=1;\n\n } else if (xmlStrEqual(name, (const xmlChar *)\"size\") &&\n xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {\n if (CL_SUCCESS == xar_get_numeric_from_xml_element(reader, size))\n gotsize=1;\n\n } else if (xmlStrEqual(name, (const xmlChar *)\"archived-checksum\") &&\n xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {\n cli_dbgmsg(\"cli_scanxar: :\\n\");\n xar_get_checksum_values(reader, a_cksum, a_hash);\n \n } else if ((xmlStrEqual(name, (const xmlChar *)\"extracted-checksum\") ||\n xmlStrEqual(name, (const xmlChar *)\"unarchived-checksum\")) &&\n xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {\n cli_dbgmsg(\"cli_scanxar: :\\n\");\n xar_get_checksum_values(reader, e_cksum, e_hash);\n\n } else if (xmlStrEqual(name, (const xmlChar *)\"encoding\") &&\n xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {\n xmlChar * style = xmlTextReaderGetAttribute(reader, (const xmlChar *)\"style\");\n if (style == NULL) {\n cli_dbgmsg(\"cli_scaxar: xmlTextReaderGetAttribute no style attribute \"\n \"for encoding element\\n\");\n *encoding = CL_TYPE_ANY;\n } else if (xmlStrEqual(style, (const xmlChar *)\"application\/x-gzip\")) {\n cli_dbgmsg(\"cli_scanxar: encoding = application\/x-gzip.\\n\");\n *encoding = CL_TYPE_GZ; \n } else if (xmlStrEqual(style, (const xmlChar *)\"application\/octet-stream\")) {\n cli_dbgmsg(\"cli_scanxar: encoding = application\/octet-stream.\\n\");\n *encoding = CL_TYPE_ANY; \n } else if (xmlStrEqual(style, (const xmlChar *)\"application\/x-bzip2\")) {\n cli_dbgmsg(\"cli_scanxar: encoding = application\/x-bzip2.\\n\");\n *encoding = CL_TYPE_BZ;\n } else if (xmlStrEqual(style, (const xmlChar *)\"application\/x-lzma\")) {\n cli_dbgmsg(\"cli_scanxar: encoding = application\/x-lzma.\\n\");\n *encoding = CL_TYPE_7Z;\n } else if (xmlStrEqual(style, (const xmlChar *)\"application\/x-xz\")) {\n cli_dbgmsg(\"cli_scanxar: encoding = application\/x-xz.\\n\");\n *encoding = CL_TYPE_XZ;\n } else {\n cli_dbgmsg(\"cli_scaxar: unknown style value=%s for encoding element\\n\", style);\n *encoding = CL_TYPE_ANY;\n }\n if (style != NULL)\n xmlFree(style);\n\n } else if (indata && xmlStrEqual(name, (const xmlChar *)\"data\") &&\n xmlTextReaderNodeType(reader) == XML_READER_TYPE_END_ELEMENT) {\n break;\n\n } else if (inea && xmlStrEqual(name, (const xmlChar *)\"ea\") &&\n xmlTextReaderNodeType(reader) == XML_READER_TYPE_END_ELEMENT) {\n break;\n }\n \n } else {\n if (xmlTextReaderNodeType(reader) == XML_READER_TYPE_ELEMENT) {\n if (xmlStrEqual(name, (const xmlChar *)\"data\")) {\n cli_dbgmsg(\"cli_scanxar: xmlTextReaderRead read \\n\");\n indata = 1;\n } else if (xmlStrEqual(name, (const xmlChar *)\"ea\")) {\n cli_dbgmsg(\"cli_scanxar: xmlTextReaderRead read \\n\");\n inea = 1;\n }\n } else if ((xmlTextReaderNodeType(reader) == XML_READER_TYPE_END_ELEMENT) &&\n xmlStrEqual(name, (const xmlChar *)\"xar\")) {\n cli_dbgmsg(\"cli_scanxar: finished parsing xar TOC.\\n\"); \n break;\n }\n }\n rc = xmlTextReaderRead(reader);\n }\n \n if (gotoffset && gotlength && gotsize) {\n rc = CL_SUCCESS;\n }\n else if (0 == gotoffset + gotlength + gotsize)\n rc = CL_BREAK;\n else\n rc = CL_EFORMAT;\n\n return rc;\n}","target":1,"code_token_length":1251,"total_token_length":1582,"max_tokens_setting":2048} +{"idx":162455,"func":"void WebGLRenderingContextBase::TexImageHelperHTMLVideoElement(\n const SecurityOrigin* security_origin,\n TexImageFunctionID function_id,\n GLenum target,\n GLint level,\n GLint internalformat,\n GLenum format,\n GLenum type,\n GLint xoffset,\n GLint yoffset,\n GLint zoffset,\n HTMLVideoElement* video,\n const IntRect& source_image_rect,\n GLsizei depth,\n GLint unpack_image_height,\n ExceptionState& exception_state) {\n const char* func_name = GetTexImageFunctionName(function_id);\n if (isContextLost())\n return;\n\n if (!ValidateHTMLVideoElement(security_origin, func_name, video,\n exception_state))\n return;\n WebGLTexture* texture =\n ValidateTexImageBinding(func_name, function_id, target);\n if (!texture)\n return;\n TexImageFunctionType function_type;\n if (function_id == kTexImage2D || function_id == kTexImage3D)\n function_type = kTexImage;\n else\n function_type = kTexSubImage;\n if (!ValidateTexFunc(func_name, function_type, kSourceHTMLVideoElement,\n target, level, internalformat, video->videoWidth(),\n video->videoHeight(), 1, 0, format, type, xoffset,\n yoffset, zoffset))\n return;\n\n WebMediaPlayer::VideoFrameUploadMetadata frame_metadata = {};\n int already_uploaded_id = -1;\n WebMediaPlayer::VideoFrameUploadMetadata* frame_metadata_ptr = nullptr;\n if (RuntimeEnabledFeatures::ExperimentalCanvasFeaturesEnabled()) {\n already_uploaded_id = texture->GetLastUploadedVideoFrameId();\n frame_metadata_ptr = &frame_metadata;\n }\n \n if (!source_image_rect.IsValid()) {\n SynthesizeGLError(GL_INVALID_OPERATION, func_name,\n \"source sub-rectangle specified via pixel unpack \"\n \"parameters is invalid\");\n return;\n }\n bool source_image_rect_is_default =\n source_image_rect == SentinelEmptyRect() ||\n source_image_rect ==\n IntRect(0, 0, video->videoWidth(), video->videoHeight());\n const bool use_copyTextureCHROMIUM = function_id == kTexImage2D &&\n source_image_rect_is_default &&\n depth == 1 && GL_TEXTURE_2D == target &&\n CanUseTexImageByGPU(format, type);\n if (use_copyTextureCHROMIUM) {\n DCHECK_EQ(xoffset, 0);\n DCHECK_EQ(yoffset, 0);\n DCHECK_EQ(zoffset, 0);\n\n if (video->CopyVideoTextureToPlatformTexture(\n ContextGL(), target, texture->Object(), internalformat, format,\n type, level, unpack_premultiply_alpha_, unpack_flip_y_,\n already_uploaded_id, frame_metadata_ptr)) {\n texture->UpdateLastUploadedFrame(frame_metadata);\n return;\n }\n }\n\n if (source_image_rect_is_default) {\n ScopedUnpackParametersResetRestore(\n this, unpack_flip_y_ || unpack_premultiply_alpha_);\n if (video->TexImageImpl(\n static_cast(function_id),\n target, ContextGL(), texture->Object(), level,\n ConvertTexInternalFormat(internalformat, type), format, type,\n xoffset, yoffset, zoffset, unpack_flip_y_,\n unpack_premultiply_alpha_ &&\n unpack_colorspace_conversion_ == GL_NONE)) {\n texture->ClearLastUploadedFrame();\n return;\n }\n }\n\n if (use_copyTextureCHROMIUM) {\n std::unique_ptr surface =\n WTF::WrapUnique(new AcceleratedImageBufferSurface(\n IntSize(video->videoWidth(), video->videoHeight())));\n if (surface->IsValid()) {\n std::unique_ptr image_buffer(\n ImageBuffer::Create(std::move(surface)));\n if (image_buffer) {\n video->PaintCurrentFrame(\n image_buffer->Canvas(),\n IntRect(0, 0, video->videoWidth(), video->videoHeight()), nullptr,\n already_uploaded_id, frame_metadata_ptr);\n\n\n TexImage2DBase(target, level, internalformat, video->videoWidth(),\n video->videoHeight(), 0, format, type, nullptr);\n\n if (image_buffer->CopyToPlatformTexture(\n FunctionIDToSnapshotReason(function_id), ContextGL(), target,\n texture->Object(), unpack_premultiply_alpha_, unpack_flip_y_,\n IntPoint(0, 0),\n IntRect(0, 0, video->videoWidth(), video->videoHeight()))) {\n texture->UpdateLastUploadedFrame(frame_metadata);\n return;\n }\n }\n }\n }\n\n scoped_refptr image =\n VideoFrameToImage(video, already_uploaded_id, frame_metadata_ptr);\n if (!image)\n return;\n TexImageImpl(function_id, target, level, internalformat, xoffset, yoffset,\n zoffset, format, type, image.get(),\n WebGLImageConversion::kHtmlDomVideo, unpack_flip_y_,\n unpack_premultiply_alpha_, source_image_rect, depth,\n unpack_image_height);\n texture->UpdateLastUploadedFrame(frame_metadata);\n}\n","target":0,"code_token_length":1077,"total_token_length":1408,"max_tokens_setting":2048} +{"idx":109276,"func":"static int ext2_remount (struct super_block * sb, int * flags, char * data)\n{\n\tstruct ext2_sb_info * sbi = EXT2_SB(sb);\n\tstruct ext2_super_block * es;\n\tstruct ext2_mount_options old_opts;\n\tunsigned long old_sb_flags;\n\tint err;\n\n\tsync_filesystem(sb);\n\tspin_lock(&sbi->s_lock);\n\n\t\/* Store the old options *\/\n\told_sb_flags = sb->s_flags;\n\told_opts.s_mount_opt = sbi->s_mount_opt;\n\told_opts.s_resuid = sbi->s_resuid;\n\told_opts.s_resgid = sbi->s_resgid;\n\n\t\/*\n\t * Allow the \"check\" option to be passed as a remount option.\n\t *\/\n\tif (!parse_options(data, sb)) {\n\t\terr = -EINVAL;\n\t\tgoto restore_opts;\n\t}\n\n\tsb->s_flags = (sb->s_flags & ~MS_POSIXACL) |\n\t\t((sbi->s_mount_opt & EXT2_MOUNT_POSIX_ACL) ? MS_POSIXACL : 0);\n\n\tes = sbi->s_es;\n\tif ((sbi->s_mount_opt ^ old_opts.s_mount_opt) & EXT2_MOUNT_DAX) {\n\t\text2_msg(sb, KERN_WARNING, \"warning: refusing change of \"\n\t\t\t \"dax flag with busy inodes while remounting\");\n\t\tsbi->s_mount_opt ^= EXT2_MOUNT_DAX;\n\t}\n\tif ((*flags & MS_RDONLY) == (sb->s_flags & MS_RDONLY)) {\n\t\tspin_unlock(&sbi->s_lock);\n\t\treturn 0;\n\t}\n\tif (*flags & MS_RDONLY) {\n\t\tif (le16_to_cpu(es->s_state) & EXT2_VALID_FS ||\n\t\t !(sbi->s_mount_state & EXT2_VALID_FS)) {\n\t\t\tspin_unlock(&sbi->s_lock);\n\t\t\treturn 0;\n\t\t}\n\n\t\t\/*\n\t\t * OK, we are remounting a valid rw partition rdonly, so set\n\t\t * the rdonly flag and then mark the partition as valid again.\n\t\t *\/\n\t\tes->s_state = cpu_to_le16(sbi->s_mount_state);\n\t\tes->s_mtime = cpu_to_le32(get_seconds());\n\t\tspin_unlock(&sbi->s_lock);\n\n\t\terr = dquot_suspend(sb, -1);\n\t\tif (err < 0) {\n\t\t\tspin_lock(&sbi->s_lock);\n\t\t\tgoto restore_opts;\n\t\t}\n\n\t\text2_sync_super(sb, es, 1);\n\t} else {\n\t\t__le32 ret = EXT2_HAS_RO_COMPAT_FEATURE(sb,\n\t\t\t\t\t ~EXT2_FEATURE_RO_COMPAT_SUPP);\n\t\tif (ret) {\n\t\t\text2_msg(sb, KERN_WARNING,\n\t\t\t\t\"warning: couldn't remount RDWR because of \"\n\t\t\t\t\"unsupported optional features (%x).\",\n\t\t\t\tle32_to_cpu(ret));\n\t\t\terr = -EROFS;\n\t\t\tgoto restore_opts;\n\t\t}\n\t\t\/*\n\t\t * Mounting a RDONLY partition read-write, so reread and\n\t\t * store the current valid flag. (It may have been changed\n\t\t * by e2fsck since we originally mounted the partition.)\n\t\t *\/\n\t\tsbi->s_mount_state = le16_to_cpu(es->s_state);\n\t\tif (!ext2_setup_super (sb, es, 0))\n\t\t\tsb->s_flags &= ~MS_RDONLY;\n\t\tspin_unlock(&sbi->s_lock);\n\n\t\text2_write_super(sb);\n\n\t\tdquot_resume(sb, -1);\n\t}\n\n\treturn 0;\nrestore_opts:\n\tsbi->s_mount_opt = old_opts.s_mount_opt;\n\tsbi->s_resuid = old_opts.s_resuid;\n\tsbi->s_resgid = old_opts.s_resgid;\n\tsb->s_flags = old_sb_flags;\n\tspin_unlock(&sbi->s_lock);\n\treturn err;\n}","target":0,"code_token_length":808,"total_token_length":1139,"max_tokens_setting":2048} +{"idx":378387,"func":"static void sdap_get_initgr_done(struct tevent_req *subreq)\n{\n struct tevent_req *req = tevent_req_callback_data(subreq,\n struct tevent_req);\n struct sdap_get_initgr_state *state = tevent_req_data(req,\n struct sdap_get_initgr_state);\n int ret;\n TALLOC_CTX *tmp_ctx;\n gid_t primary_gid;\n char *gid;\n char *sid_str;\n char *dom_sid_str;\n char *group_sid_str;\n struct sdap_options *opts = state->opts;\n\n DEBUG(SSSDBG_TRACE_ALL, \"Initgroups done\\n\");\n\n tmp_ctx = talloc_new(NULL);\n if (!tmp_ctx) {\n tevent_req_error(req, ENOMEM);\n return;\n }\n\n switch (state->opts->schema_type) {\n case SDAP_SCHEMA_RFC2307:\n ret = sdap_initgr_rfc2307_recv(subreq);\n break;\n\n case SDAP_SCHEMA_RFC2307BIS:\n case SDAP_SCHEMA_AD:\n if (state->opts->dc_functional_level >= DS_BEHAVIOR_WIN2003\n && dp_opt_get_bool(state->opts->basic, SDAP_AD_USE_TOKENGROUPS)) {\n\n ret = sdap_ad_tokengroups_initgroups_recv(subreq);\n }\n else if (state->opts->support_matching_rule\n && dp_opt_get_bool(state->opts->basic,\n SDAP_AD_MATCHING_RULE_INITGROUPS)) {\n ret = sdap_get_ad_match_rule_initgroups_recv(subreq);\n } else {\n ret = sdap_initgr_rfc2307bis_recv(subreq);\n }\n break;\n\n case SDAP_SCHEMA_IPA_V1:\n ret = sdap_initgr_nested_recv(subreq);\n break;\n\n default:\n\n ret = EINVAL;\n break;\n }\n\n talloc_zfree(subreq);\n if (ret) {\n DEBUG(SSSDBG_TRACE_ALL, \"Error in initgroups: [%d][%s]\\n\",\n ret, strerror(ret));\n goto fail;\n }\n\n \/* We also need to update the user's primary group, since\n * the user may not be an explicit member of that group\n *\/\n\n if (state->use_id_mapping) {\n DEBUG(SSSDBG_TRACE_LIBS,\n \"Mapping primary group to unix ID\\n\");\n\n \/* The primary group ID is just the RID part of the objectSID\n * of the group. Generate the GID by adding this to the domain\n * SID value.\n *\/\n\n \/* Get the user SID so we can extract the domain SID\n * from it.\n *\/\n ret = sdap_attrs_get_sid_str(\n tmp_ctx, opts->idmap_ctx, state->orig_user,\n opts->user_map[SDAP_AT_USER_OBJECTSID].sys_name,\n &sid_str);\n if (ret != EOK) goto fail;\n\n \/* Get the domain SID from the user SID *\/\n ret = sdap_idmap_get_dom_sid_from_object(tmp_ctx, sid_str,\n &dom_sid_str);\n if (ret != EOK) {\n DEBUG(SSSDBG_MINOR_FAILURE,\n \"Could not parse domain SID from [%s]\\n\", sid_str);\n goto fail;\n }\n\n ret = sysdb_attrs_get_uint32_t(\n state->orig_user,\n opts->user_map[SDAP_AT_USER_PRIMARY_GROUP].sys_name,\n &primary_gid);\n if (ret != EOK) {\n DEBUG(SSSDBG_MINOR_FAILURE,\n \"no primary group ID provided\\n\");\n ret = EINVAL;\n goto fail;\n }\n\n \/* Add the RID to the end *\/\n group_sid_str = talloc_asprintf(tmp_ctx, \"%s-%lu\",\n dom_sid_str,\n (unsigned long)primary_gid);\n if (!group_sid_str) {\n ret = ENOMEM;\n goto fail;\n }\n\n \/* Convert the SID into a UNIX group ID *\/\n ret = sdap_idmap_sid_to_unix(opts->idmap_ctx, group_sid_str,\n &primary_gid);\n if (ret != EOK) goto fail;\n } else {\n ret = sysdb_attrs_get_uint32_t(state->orig_user, SYSDB_GIDNUM,\n &primary_gid);\n if (ret != EOK) {\n DEBUG(SSSDBG_TRACE_FUNC, \"Could not find user's primary GID\\n\");\n goto fail;\n }\n }\n\n gid = talloc_asprintf(state, \"%lu\", (unsigned long)primary_gid);\n if (gid == NULL) {\n ret = ENOMEM;\n goto fail;\n }\n\n subreq = groups_get_send(req, state->ev, state->id_ctx,\n state->id_ctx->opts->sdom, state->conn,\n gid, BE_FILTER_IDNUM, BE_ATTR_ALL, NULL);\n if (!subreq) {\n ret = ENOMEM;\n goto fail;\n }\n tevent_req_set_callback(subreq, sdap_get_initgr_pgid, req);\n\n talloc_free(tmp_ctx);\n return;\n\nfail:\n talloc_free(tmp_ctx);\n tevent_req_error(req, ret);\n return;\n}","target":0,"code_token_length":1111,"total_token_length":1442,"max_tokens_setting":2048} +{"idx":509694,"func":"static void test_store_result()\n{\n MYSQL_STMT *stmt;\n int rc;\n int32 nData;\n char szData[100];\n MYSQL_BIND my_bind[2];\n ulong length, length1;\n my_bool is_null[2];\n\n myheader(\"test_store_result\");\n\n rc= mysql_query(mysql, \"DROP TABLE IF EXISTS test_store_result\");\n myquery(rc);\n\n rc= mysql_query(mysql, \"CREATE TABLE test_store_result(col1 int , col2 varchar(50))\");\n myquery(rc);\n\n rc= mysql_query(mysql, \"INSERT INTO test_store_result VALUES(10, 'venu'), (20, 'mysql')\");\n myquery(rc);\n\n rc= mysql_query(mysql, \"INSERT INTO test_store_result(col2) VALUES('monty')\");\n myquery(rc);\n\n rc= mysql_commit(mysql);\n myquery(rc);\n\n \/* fetch *\/\n bzero((char*) my_bind, sizeof(my_bind));\n my_bind[0].buffer_type= MYSQL_TYPE_LONG;\n my_bind[0].buffer= (void *) &nData; \/* integer data *\/\n my_bind[0].length= &length;\n my_bind[0].is_null= &is_null[0];\n\n length= 0;\n my_bind[1].buffer_type= MYSQL_TYPE_STRING;\n my_bind[1].buffer= szData; \/* string data *\/\n my_bind[1].buffer_length= sizeof(szData);\n my_bind[1].length= &length1;\n my_bind[1].is_null= &is_null[1];\n length1= 0;\n\n stmt= mysql_simple_prepare(mysql, \"SELECT * FROM test_store_result\");\n check_stmt(stmt);\n\n rc= mysql_stmt_bind_result(stmt, my_bind);\n check_execute(stmt, rc);\n\n rc= mysql_stmt_execute(stmt);\n check_execute(stmt, rc);\n\n rc= mysql_stmt_store_result(stmt);\n check_execute(stmt, rc);\n\n rc= mysql_stmt_fetch(stmt);\n check_execute(stmt, rc);\n\n if (!opt_silent)\n fprintf(stdout, \"\\n row 1: %ld, %s(%lu)\", (long) nData, szData, length1);\n DIE_UNLESS(nData == 10);\n DIE_UNLESS(strcmp(szData, \"venu\") == 0);\n DIE_UNLESS(length1 == 4);\n\n rc= mysql_stmt_fetch(stmt);\n check_execute(stmt, rc);\n\n if (!opt_silent)\n fprintf(stdout, \"\\n row 2: %ld, %s(%lu)\", (long) nData, szData, length1);\n DIE_UNLESS(nData == 20);\n DIE_UNLESS(strcmp(szData, \"mysql\") == 0);\n DIE_UNLESS(length1 == 5);\n\n length= 99;\n rc= mysql_stmt_fetch(stmt);\n check_execute(stmt, rc);\n\n if (!opt_silent && is_null[0])\n fprintf(stdout, \"\\n row 3: NULL, %s(%lu)\", szData, length1);\n DIE_UNLESS(is_null[0]);\n DIE_UNLESS(strcmp(szData, \"monty\") == 0);\n DIE_UNLESS(length1 == 5);\n\n rc= mysql_stmt_fetch(stmt);\n DIE_UNLESS(rc == MYSQL_NO_DATA);\n\n rc= mysql_stmt_execute(stmt);\n check_execute(stmt, rc);\n\n rc= mysql_stmt_store_result(stmt);\n check_execute(stmt, rc);\n\n rc= mysql_stmt_fetch(stmt);\n check_execute(stmt, rc);\n\n if (!opt_silent)\n fprintf(stdout, \"\\n row 1: %ld, %s(%lu)\", (long) nData, szData, length1);\n DIE_UNLESS(nData == 10);\n DIE_UNLESS(strcmp(szData, \"venu\") == 0);\n DIE_UNLESS(length1 == 4);\n\n rc= mysql_stmt_fetch(stmt);\n check_execute(stmt, rc);\n\n if (!opt_silent)\n fprintf(stdout, \"\\n row 2: %ld, %s(%lu)\", (long) nData, szData, length1);\n DIE_UNLESS(nData == 20);\n DIE_UNLESS(strcmp(szData, \"mysql\") == 0);\n DIE_UNLESS(length1 == 5);\n\n length= 99;\n rc= mysql_stmt_fetch(stmt);\n check_execute(stmt, rc);\n\n if (!opt_silent && is_null[0])\n fprintf(stdout, \"\\n row 3: NULL, %s(%lu)\", szData, length1);\n DIE_UNLESS(is_null[0]);\n DIE_UNLESS(strcmp(szData, \"monty\") == 0);\n DIE_UNLESS(length1 == 5);\n\n rc= mysql_stmt_fetch(stmt);\n DIE_UNLESS(rc == MYSQL_NO_DATA);\n\n mysql_stmt_close(stmt);\n}","target":0,"code_token_length":1034,"total_token_length":1365,"max_tokens_setting":2048} +{"idx":119337,"func":"static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env)\n{\n\tstruct bpf_insn *insn = env->prog->insnsi;\n\tint insn_cnt = env->prog->len;\n\tint i, j, err;\n\n\terr = bpf_prog_calc_tag(env->prog);\n\tif (err)\n\t\treturn err;\n\n\tfor (i = 0; i < insn_cnt; i++, insn++) {\n\t\tif (BPF_CLASS(insn->code) == BPF_LDX &&\n\t\t (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) {\n\t\t\tverbose(\"BPF_LDX uses reserved fields\\n\");\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tif (BPF_CLASS(insn->code) == BPF_STX &&\n\t\t ((BPF_MODE(insn->code) != BPF_MEM &&\n\t\t BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) {\n\t\t\tverbose(\"BPF_STX uses reserved fields\\n\");\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tif (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {\n\t\t\tstruct bpf_map *map;\n\t\t\tstruct fd f;\n\n\t\t\tif (i == insn_cnt - 1 || insn[1].code != 0 ||\n\t\t\t insn[1].dst_reg != 0 || insn[1].src_reg != 0 ||\n\t\t\t insn[1].off != 0) {\n\t\t\t\tverbose(\"invalid bpf_ld_imm64 insn\\n\");\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\n\t\t\tif (insn->src_reg == 0)\n\t\t\t\t\/* valid generic load 64-bit imm *\/\n\t\t\t\tgoto next_insn;\n\n\t\t\tif (insn->src_reg != BPF_PSEUDO_MAP_FD) {\n\t\t\t\tverbose(\"unrecognized bpf_ld_imm64 insn\\n\");\n\t\t\t\treturn -EINVAL;\n\t\t\t}\n\n\t\t\tf = fdget(insn->imm);\n\t\t\tmap = __bpf_map_get(f);\n\t\t\tif (IS_ERR(map)) {\n\t\t\t\tverbose(\"fd %d is not pointing to valid bpf_map\\n\",\n\t\t\t\t\tinsn->imm);\n\t\t\t\treturn PTR_ERR(map);\n\t\t\t}\n\n\t\t\terr = check_map_prog_compatibility(map, env->prog);\n\t\t\tif (err) {\n\t\t\t\tfdput(f);\n\t\t\t\treturn err;\n\t\t\t}\n\n\t\t\t\/* store map pointer inside BPF_LD_IMM64 instruction *\/\n\t\t\tinsn[0].imm = (u32) (unsigned long) map;\n\t\t\tinsn[1].imm = ((u64) (unsigned long) map) >> 32;\n\n\t\t\t\/* check whether we recorded this map already *\/\n\t\t\tfor (j = 0; j < env->used_map_cnt; j++)\n\t\t\t\tif (env->used_maps[j] == map) {\n\t\t\t\t\tfdput(f);\n\t\t\t\t\tgoto next_insn;\n\t\t\t\t}\n\n\t\t\tif (env->used_map_cnt >= MAX_USED_MAPS) {\n\t\t\t\tfdput(f);\n\t\t\t\treturn -E2BIG;\n\t\t\t}\n\n\t\t\t\/* hold the map. If the program is rejected by verifier,\n\t\t\t * the map will be released by release_maps() or it\n\t\t\t * will be used by the valid program until it's unloaded\n\t\t\t * and all maps are released in free_bpf_prog_info()\n\t\t\t *\/\n\t\t\tmap = bpf_map_inc(map, false);\n\t\t\tif (IS_ERR(map)) {\n\t\t\t\tfdput(f);\n\t\t\t\treturn PTR_ERR(map);\n\t\t\t}\n\t\t\tenv->used_maps[env->used_map_cnt++] = map;\n\n\t\t\tfdput(f);\nnext_insn:\n\t\t\tinsn++;\n\t\t\ti++;\n\t\t}\n\t}\n\n\t\/* now all pseudo BPF_LD_IMM64 instructions load valid\n\t * 'struct bpf_map *' into a register instead of user map_fd.\n\t * These pointers will be used later by verifier to validate map access.\n\t *\/\n\treturn 0;\n}","target":0,"code_token_length":821,"total_token_length":1152,"max_tokens_setting":2048} +{"idx":431786,"func":" bool run(OperationContext* txn,\n const string& dbname,\n BSONObj& cmdObj,\n int options,\n string& errmsg,\n BSONObjBuilder& result) {\n RoleName roleName;\n PrivilegeVector privilegesToRemove;\n Status status = auth::parseAndValidateRolePrivilegeManipulationCommands(\n cmdObj, \"revokePrivilegesFromRole\", dbname, &roleName, &privilegesToRemove);\n if (!status.isOK()) {\n return appendCommandStatus(result, status);\n }\n\n ServiceContext* serviceContext = txn->getClient()->getServiceContext();\n stdx::lock_guard lk(getAuthzDataMutex(serviceContext));\n\n AuthorizationManager* authzManager = AuthorizationManager::get(serviceContext);\n status = requireAuthSchemaVersion26Final(txn, authzManager);\n if (!status.isOK()) {\n return appendCommandStatus(result, status);\n }\n\n if (RoleGraph::isBuiltinRole(roleName)) {\n return appendCommandStatus(\n result,\n Status(ErrorCodes::InvalidRoleModification,\n str::stream() << roleName.getFullName()\n << \" is a built-in role and cannot be modified.\"));\n }\n\n BSONObj roleDoc;\n status = authzManager->getRoleDescription(\n txn, roleName, PrivilegeFormat::kShowSeparate, &roleDoc);\n if (!status.isOK()) {\n return appendCommandStatus(result, status);\n }\n\n PrivilegeVector privileges;\n status = auth::parseAndValidatePrivilegeArray(BSONArray(roleDoc[\"privileges\"].Obj()),\n &privileges);\n if (!status.isOK()) {\n return appendCommandStatus(result, status);\n }\n\n for (PrivilegeVector::iterator itToRm = privilegesToRemove.begin();\n itToRm != privilegesToRemove.end();\n ++itToRm) {\n for (PrivilegeVector::iterator curIt = privileges.begin(); curIt != privileges.end();\n ++curIt) {\n if (curIt->getResourcePattern() == itToRm->getResourcePattern()) {\n curIt->removeActions(itToRm->getActions());\n if (curIt->getActions().empty()) {\n privileges.erase(curIt);\n }\n break;\n }\n }\n }\n\n \/\/ Build up update modifier object to $set privileges.\n mutablebson::Document updateObj;\n mutablebson::Element setElement = updateObj.makeElementObject(\"$set\");\n status = updateObj.root().pushBack(setElement);\n if (!status.isOK()) {\n return appendCommandStatus(result, status);\n }\n mutablebson::Element privilegesElement = updateObj.makeElementArray(\"privileges\");\n status = setElement.pushBack(privilegesElement);\n if (!status.isOK()) {\n return appendCommandStatus(result, status);\n }\n status = authzManager->getBSONForPrivileges(privileges, privilegesElement);\n if (!status.isOK()) {\n return appendCommandStatus(result, status);\n }\n\n audit::logRevokePrivilegesFromRole(Client::getCurrent(), roleName, privilegesToRemove);\n\n BSONObjBuilder updateBSONBuilder;\n updateObj.writeTo(&updateBSONBuilder);\n status = updateRoleDocument(txn, roleName, updateBSONBuilder.done());\n \/\/ Must invalidate even on bad status - what if the write succeeded but the GLE failed?\n authzManager->invalidateUserCache();\n return appendCommandStatus(result, status);\n }","target":0,"code_token_length":728,"total_token_length":1059,"max_tokens_setting":2048} +{"idx":18315,"func":"static ossl_inline t2 * sk_ ## t1 ## _shift ( STACK_OF ( t1 ) * sk ) {\n return ( t2 * ) OPENSSL_sk_shift ( ( OPENSSL_STACK * ) sk ) ;\n }\n static ossl_inline void sk_ ## t1 ## _pop_free ( STACK_OF ( t1 ) * sk , sk_ ## t1 ## _freefunc freefunc ) {\n OPENSSL_sk_pop_free ( ( OPENSSL_STACK * ) sk , ( OPENSSL_sk_freefunc ) freefunc ) ;\n }\n static ossl_inline int sk_ ## t1 ## _insert ( STACK_OF ( t1 ) * sk , t2 * ptr , int idx ) {\n return OPENSSL_sk_insert ( ( OPENSSL_STACK * ) sk , ( const void * ) ptr , idx ) ;\n }\n static ossl_inline t2 * sk_ ## t1 ## _set ( STACK_OF ( t1 ) * sk , int idx , t2 * ptr ) {\n return ( t2 * ) OPENSSL_sk_set ( ( OPENSSL_STACK * ) sk , idx , ( const void * ) ptr ) ;\n }\n static ossl_inline int sk_ ## t1 ## _find ( STACK_OF ( t1 ) * sk , t2 * ptr ) {\n return OPENSSL_sk_find ( ( OPENSSL_STACK * ) sk , ( const void * ) ptr ) ;\n }\n static ossl_inline int sk_ ## t1 ## _find_ex ( STACK_OF ( t1 ) * sk , t2 * ptr ) {\n return OPENSSL_sk_find_ex ( ( OPENSSL_STACK * ) sk , ( const void * ) ptr ) ;\n }\n static ossl_inline void sk_ ## t1 ## _sort ( STACK_OF ( t1 ) * sk ) {\n OPENSSL_sk_sort ( ( OPENSSL_STACK * ) sk ) ;\n }\n static ossl_inline int sk_ ## t1 ## _is_sorted ( const STACK_OF ( t1 ) * sk ) {\n return OPENSSL_sk_is_sorted ( ( const OPENSSL_STACK * ) sk ) ;\n }\n static ossl_inline STACK_OF ( t1 ) * sk_ ## t1 ## _dup ( const STACK_OF ( t1 ) * sk ) {\n return ( STACK_OF ( t1 ) * ) OPENSSL_sk_dup ( ( const OPENSSL_STACK * ) sk ) ;\n }\n static ossl_inline STACK_OF ( t1 ) * sk_ ## t1 ## _deep_copy ( const STACK_OF ( t1 ) * sk , sk_ ## t1 ## _copyfunc copyfunc , sk_ ## t1 ## _freefunc freefunc ) {\n return ( STACK_OF ( t1 ) * ) OPENSSL_sk_deep_copy ( ( const OPENSSL_STACK * ) sk , ( OPENSSL_sk_copyfunc ) copyfunc , ( OPENSSL_sk_freefunc ) freefunc ) ;\n }\n static ossl_inline sk_ ## t1 ## _compfunc sk_ ## t1 ## _set_cmp_func ( STACK_OF ( t1 ) * sk , sk_ ## t1 ## _compfunc compare ) {\n return ( sk_ ## t1 ## _compfunc ) OPENSSL_sk_set_cmp_func ( ( OPENSSL_STACK * ) sk , ( OPENSSL_sk_compfunc ) compare ) ;\n }\n # define DEFINE_SPECIAL_STACK_OF ( t1 , t2 ) SKM_DEFINE_STACK_OF ( t1 , t2 , t2 ) # define DEFINE_STACK_OF ( t ) SKM_DEFINE_STACK_OF ( t , t , t ) # define DEFINE_SPECIAL_STACK_OF_CONST ( t1 , t2 ) SKM_DEFINE_STACK_OF ( t1 , const t2 , t2 ) # define DEFINE_STACK_OF_CONST ( t ) SKM_DEFINE_STACK_OF ( t , const t , t ) typedef char * OPENSSL_STRING ;\n typedef const char * OPENSSL_CSTRING ;\n DEFINE_SPECIAL_STACK_OF ( OPENSSL_STRING , char )","target":0,"code_token_length":791,"total_token_length":1122,"max_tokens_setting":2048} +{"idx":292726,"func":"Variant HHVM_FUNCTION(imageloadfont, const String& \/*file*\/) {\n \/\/ TODO: ind = 5 + zend_list_insert(font, le_gd_font);\n throw_not_supported(__func__, \"NYI\");\n#ifdef NEVER\n Variant stream;\n zval **file;\n int hdr_size = sizeof(gdFont) - sizeof(char *);\n int ind, body_size, n = 0, b, i, body_size_check;\n gdFontPtr font;\n php_stream *stream;\n\n\n stream = File::Open(file, \"rb\");\n if (!stream) {\n raise_warning(\"failed to open file: %s\", file.c_str());\n return false;\n }\n\n \/* Only supports a architecture-dependent binary dump format\n * at the moment.\n * The file format is like this on machines with 32-byte integers:\n *\n * byte 0-3: (int) number of characters in the font\n * byte 4-7: (int) value of first character in the font (often 32, space)\n * byte 8-11: (int) pixel width of each character\n * byte 12-15: (int) pixel height of each character\n * bytes 16-: (char) array with character data, one byte per pixel\n * in each character, for a total of\n * (nchars*width*height) bytes.\n *\/\n font = (gdFontPtr) IM_MALLOC(sizeof(gdFont));\n CHECK_ALLOC_R(font, sizeof(gdFont), false);\n b = 0;\n String hdr = stream->read(hdr_size);\n if (hdr.length() < hdr_size) {\n IM_FREE(font);\n if (stream->eof()) {\n raise_warning(\"End of file while reading header\");\n } else {\n raise_warning(\"Error while reading header\");\n }\n stream->close();\n return false;\n }\n memcpy((void*)font, hdr.c_str(), hdr.length());\n i = int64_t(f_tell(stream));\n stream->seek(0, SEEK_END);\n body_size_check = int64_t(f_tell(stream)) - hdr_size;\n stream->seek(i, SEEK_SET);\n\n body_size = font->w * font->h * font->nchars;\n if (body_size != body_size_check) {\n font->w = FLIPWORD(font->w);\n font->h = FLIPWORD(font->h);\n font->nchars = FLIPWORD(font->nchars);\n body_size = font->w * font->h * font->nchars;\n }\n\n if (font->nchars <= 0 ||\n font->h <= 0 ||\n font->nchars >= INT_MAX || font->h >= INT_MAX) {\n raise_warning(\"Error reading font, invalid font header\");\n IM_FREE(font);\n stream->close();\n return false;\n }\n\n if ((font->nchars * font->h) <= 0 ||\n font->w <= 0 ||\n (font->nchars * font->h) >= INT_MAX || font->w >= INT_MAX) {\n raise_warning(\"Error reading font, invalid font header\");\n IM_FREE(font);\n stream->close();\n return false;\n }\n\n if (body_size != body_size_check) {\n raise_warning(\"Error reading font\");\n IM_FREE(font);\n stream->close();\n return false;\n }\n\n String body = stream->read(body_size);\n if (body.length() < body_size) {\n IM_FREE(font);\n if (stream->eof()) {\n raise_warning(\"End of file while reading body\");\n } else {\n raise_warning(\"Error while reading body\");\n }\n stream->close();\n return false;\n }\n font->data = IM_MALLOC(body_size);\n CHECK_ALLOC_R(font->data, body_size, false);\n memcpy((void*)font->data, body.c_str(), body.length());\n stream->close();\n\n \/* Adding 5 to the font index so we will never have font indices\n * that overlap with the old fonts (with indices 1-5). The first\n * list index given out is always 1.\n *\/\n \/\/ ind = 5 + zend_list_insert(font, le_gd_font);\n\n return ind;\n#endif\n}","target":0,"code_token_length":929,"total_token_length":1260,"max_tokens_setting":2048} +{"idx":7875,"func":"static char *create_output_name(unsigned char *fname, unsigned char *dir,\n\t\t\t int lower, int isunix, int utf8)\n{\n unsigned char *p, *name, c, *fe, sep, slash;\n unsigned int x;\n\n sep = (isunix) ? '\/' : '\\\\'; \/* the path-seperator *\/\n slash = (isunix) ? '\\\\' : '\/'; \/* the other slash *\/\n\n \/* length of filename *\/\n x = strlen((char *) fname);\n \/* UTF8 worst case scenario: tolower() expands all chars from 1 to 3 bytes *\/\n if (utf8) x *= 3;\n \/* length of output directory *\/\n if (dir) x += strlen((char *) dir);\n\n if (!(name = (unsigned char *) malloc(x + 2))) {\n fprintf(stderr, \"out of memory!\\n\");\n return NULL;\n }\n \n \/* start with blank name *\/\n *name = '\\0';\n\n \/* add output directory if needed *\/\n if (dir) {\n strcpy((char *) name, (char *) dir);\n strcat((char *) name, \"\/\");\n }\n\n \/* remove leading slashes *\/\n while (*fname == sep) fname++;\n\n \/* copy from fi->filename to new name, converting MS-DOS slashes to UNIX\n * slashes as we go. Also lowercases characters if needed.\n *\/\n p = &name[strlen((char *)name)];\n fe = &fname[strlen((char *)fname)];\n\n if (utf8) {\n \/* UTF8 translates two-byte unicode characters into 1, 2 or 3 bytes.\n * %000000000xxxxxxx -> %0xxxxxxx\n * %00000xxxxxyyyyyy -> %110xxxxx %10yyyyyy\n * %xxxxyyyyyyzzzzzz -> %1110xxxx %10yyyyyy %10zzzzzz\n *\n * Therefore, the inverse is as follows:\n * First char:\n * 0x00 - 0x7F = one byte char\n * 0x80 - 0xBF = invalid\n * 0xC0 - 0xDF = 2 byte char (next char only 0x80-0xBF is valid)\n * 0xE0 - 0xEF = 3 byte char (next 2 chars only 0x80-0xBF is valid)\n * 0xF0 - 0xFF = invalid\n *\/\n do {\n if (fname >= fe) {\n\tfree(name);\n\treturn NULL;\n }\n\n \/* get next UTF8 char *\/\n if ((c = *fname++) < 0x80) x = c;\n else {\n\tif ((c >= 0xC0) && (c < 0xE0)) {\n\t x = (c & 0x1F) << 6;\n\t x |= *fname++ & 0x3F;\n\t}\n\telse if ((c >= 0xE0) && (c < 0xF0)) {\n\t x = (c & 0xF) << 12;\n\t x |= (*fname++ & 0x3F) << 6;\n\t x |= *fname++ & 0x3F;\n\t}\n\telse x = '?';\n }\n\n \/* whatever is the path seperator -> '\/'\n * whatever is the other slash -> '\\\\'\n * otherwise, if lower is set, the lowercase version *\/\n if (x == sep) x = '\/';\n else if (x == slash) x = '\\\\';\n else if (lower) x = (unsigned int) tolower((int) x);\n\n \/* integer back to UTF8 *\/\n if (x < 0x80) {\n\t*p++ = (unsigned char) x;\n }\n else if (x < 0x800) {\n\t*p++ = 0xC0 | (x >> 6); \n\t*p++ = 0x80 | (x & 0x3F);\n }\n else {\n\t*p++ = 0xE0 | (x >> 12);\n\t*p++ = 0x80 | ((x >> 6) & 0x3F);\n\t*p++ = 0x80 | (x & 0x3F);\n }\n } while (x);\n }\n else {\n \/* regular non-utf8 version *\/\n do {\n c = *fname++;\n if (c == sep) c = '\/';\n else if (c == slash) c = '\\\\';\n else if (lower) c = (unsigned char) tolower((int) c);\n } while ((*p++ = c));\n }\n return (char *) name;\n}","target":1,"code_token_length":1036,"total_token_length":1367,"max_tokens_setting":2048} +{"idx":411329,"func":" }\n\n \/\/! Unserialize a CImg serialized buffer into a CImgList list.\n template\n static CImgList get_unserialize(const CImg& buffer) {\n#ifdef cimg_use_zlib\n#define _cimgz_unserialize_case(Tss) { \\\n Bytef *cbuf = 0; \\\n if (sizeof(t)!=1 || cimg::type::string()==cimg::type::string()) { \\\n cbuf = new Bytef[csiz]; Bytef *_cbuf = cbuf; \\\n for (ulongT i = 0; i::get_unserialize(): Unable to unserialize compressed data \" \\\n \"unless zlib is enabled.\", \\\n pixel_type());\n#endif\n\n#define _cimg_unserialize_case(Ts,Tss) \\\n if (!loaded && !cimg::strcasecmp(Ts,str_pixeltype)) { \\\n for (unsigned int l = 0; l::unserialize(): Invalid specified size (%u,%u,%u,%u) for \" \\\n \"image #%u in serialized buffer.\", \\\n pixel_type(),W,H,D,C,l); \\\n if (W*H*D*C>0) { \\\n CImg raw; \\\n CImg &img = res._data[l]; \\\n if (err==5) _cimgz_unserialize_case(Tss) \\\n else if (sizeof(Tss)==sizeof(t) && cimg::type::is_float()==cimg::type::is_float()) { \\\n raw.assign((Tss*)stream,W,H,D,C,true); \\\n stream+=raw.size(); \\\n } else { \\\n raw.assign(W,H,D,C); \\\n CImg _raw((unsigned char*)raw._data,W*sizeof(Tss),H,D,C,true); \\\n cimg_for(_raw,p,unsigned char) *p = (unsigned char)*(stream++); \\\n } \\\n if (endian!=cimg::endianness()) cimg::invert_endianness(raw._data,raw.size()); \\\n raw.move_to(img); \\\n } \\\n } \\\n loaded = true; \\\n }\n\n if (buffer.is_empty())\n throw CImgArgumentException(\"CImgList<%s>::get_unserialize(): Specified serialized buffer is (null).\",\n pixel_type());\n CImgList res;\n const t *stream = buffer._data, *const estream = buffer._data + buffer.size();\n bool loaded = false, endian = cimg::endianness(), is_bytef = false;\n CImg tmp(256), str_pixeltype(256), str_endian(256);\n *tmp = *str_pixeltype = *str_endian = 0;\n unsigned int j, N = 0, W, H, D, C;\n uint64T csiz;\n int i, err;\n cimg::unused(is_bytef);\n do {\n j = 0; while ((i=(int)*stream)!='\\n' && stream::get_unserialize(): CImg header not found in serialized buffer.\",\n pixel_type());\n if (!cimg::strncasecmp(\"little\",str_endian,6)) endian = false;\n else if (!cimg::strncasecmp(\"big\",str_endian,3)) endian = true;\n res.assign(N);\n _cimg_unserialize_case(\"bool\",bool);\n _cimg_unserialize_case(\"unsigned_char\",unsigned char);\n _cimg_unserialize_case(\"uchar\",unsigned char);\n _cimg_unserialize_case(\"char\",char);\n _cimg_unserialize_case(\"unsigned_short\",unsigned short);\n _cimg_unserialize_case(\"ushort\",unsigned short);\n _cimg_unserialize_case(\"short\",short);\n _cimg_unserialize_case(\"unsigned_int\",unsigned int);\n _cimg_unserialize_case(\"uint\",unsigned int);\n _cimg_unserialize_case(\"int\",int);\n _cimg_unserialize_case(\"unsigned_int64\",uint64T);\n _cimg_unserialize_case(\"uint64\",uint64T);\n _cimg_unserialize_case(\"int64\",int64T);\n _cimg_unserialize_case(\"float\",float);\n _cimg_unserialize_case(\"double\",double);\n if (!loaded)\n throw CImgArgumentException(\"CImgList<%s>::get_unserialize(): Unsupported pixel type '%s' defined \"","target":0,"code_token_length":1354,"total_token_length":1685,"max_tokens_setting":2048} +{"idx":266102,"func":"void shutdown_executor(void) \/* {{{ *\/\n{\n\tzend_function *func;\n\tzend_class_entry *ce;\n\n\tzend_try {\n\n\/* Removed because this can not be safely done, e.g. in this situation:\n Object 1 creates object 2\n Object 3 holds reference to object 2.\n Now when 1 and 2 are destroyed, 3 can still access 2 in its destructor, with\n very problematic results *\/\n\/* \t\tzend_objects_store_call_destructors(&EG(objects_store)); *\/\n\n\/* Moved after symbol table cleaners, because some of the cleaners can call\n destructors, which would use EG(symtable_cache_ptr) and thus leave leaks *\/\n\/*\t\twhile (EG(symtable_cache_ptr)>=EG(symtable_cache)) {\n\t\t\tzend_hash_destroy(*EG(symtable_cache_ptr));\n\t\t\tefree(*EG(symtable_cache_ptr));\n\t\t\tEG(symtable_cache_ptr)--;\n\t\t}\n*\/\n\t\tzend_llist_apply(&zend_extensions, (llist_apply_func_t) zend_extension_deactivator);\n\n\t\tif (CG(unclean_shutdown)) {\n\t\t\tEG(symbol_table).pDestructor = zend_unclean_zval_ptr_dtor;\n\t\t}\n\t\tzend_hash_graceful_reverse_destroy(&EG(symbol_table));\n\t} zend_end_try();\n\tEG(valid_symbol_table) = 0;\n\n\tzend_try {\n\t\tzval *zeh;\n\t\t\/* remove error handlers before destroying classes and functions,\n\t\t * so that if handler used some class, crash would not happen *\/\n\t\tif (Z_TYPE(EG(user_error_handler)) != IS_UNDEF) {\n\t\t\tzeh = &EG(user_error_handler);\n\t\t\tzval_ptr_dtor(zeh);\n\t\t\tZVAL_UNDEF(&EG(user_error_handler));\n\t\t}\n\n\t\tif (Z_TYPE(EG(user_exception_handler)) != IS_UNDEF) {\n\t\t\tzeh = &EG(user_exception_handler);\n\t\t\tzval_ptr_dtor(zeh);\n\t\t\tZVAL_UNDEF(&EG(user_exception_handler));\n\t\t}\n\n\t\tzend_stack_clean(&EG(user_error_handlers_error_reporting), NULL, 1);\n\t\tzend_stack_clean(&EG(user_error_handlers), (void (*)(void *))ZVAL_DESTRUCTOR, 1);\n\t\tzend_stack_clean(&EG(user_exception_handlers), (void (*)(void *))ZVAL_DESTRUCTOR, 1);\n\t} zend_end_try();\n\n\tzend_try {\n\t\t\/* Cleanup static data for functions and arrays.\n\t\t * We need a separate cleanup stage because of the following problem:\n\t\t * Suppose we destroy class X, which destroys the class's function table,\n\t\t * and in the function table we have function foo() that has static $bar.\n\t\t * Now if an object of class X is assigned to $bar, its destructor will be\n\t\t * called and will fail since X's function table is in mid-destruction.\n\t\t * So we want first of all to clean up all data and then move to tables destruction.\n\t\t * Note that only run-time accessed data need to be cleaned up, pre-defined data can\n\t\t * not contain objects and thus are not probelmatic *\/\n\t\tif (EG(full_tables_cleanup)) {\n\t\t\tZEND_HASH_FOREACH_PTR(EG(function_table), func) {\n\t\t\t\tif (func->type == ZEND_USER_FUNCTION) {\n\t\t\t\t\tzend_cleanup_op_array_data((zend_op_array *) func);\n\t\t\t\t}\n\t\t\t} ZEND_HASH_FOREACH_END();\n\t\t\tZEND_HASH_REVERSE_FOREACH_PTR(EG(class_table), ce) {\n\t\t\t\tif (ce->type == ZEND_USER_CLASS) {\n\t\t\t\t\tzend_cleanup_user_class_data(ce);\n\t\t\t\t} else {\n\t\t\t\t\tzend_cleanup_internal_class_data(ce);\n\t\t\t\t}\n\t\t\t} ZEND_HASH_FOREACH_END();\n\t\t} else {\n\t\t\tZEND_HASH_REVERSE_FOREACH_PTR(EG(function_table), func) {\n\t\t\t\tif (func->type != ZEND_USER_FUNCTION) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tzend_cleanup_op_array_data((zend_op_array *) func);\n\t\t\t} ZEND_HASH_FOREACH_END();\n\t\t\tZEND_HASH_REVERSE_FOREACH_PTR(EG(class_table), ce) {\n\t\t\t\tif (ce->type != ZEND_USER_CLASS) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tzend_cleanup_user_class_data(ce);\n\t\t\t} ZEND_HASH_FOREACH_END();\n\t\t\tzend_cleanup_internal_classes();\n\t\t}\n\t} zend_end_try();\n\n\tzend_try {\n\t\tzend_llist_destroy(&CG(open_files));\n\t} zend_end_try();\n\n\tzend_try {\n\t\tzend_close_rsrc_list(&EG(regular_list));\n\t} zend_end_try();\n\n#if ZEND_DEBUG\n\tif (GC_G(gc_enabled) && !CG(unclean_shutdown)) {\n\t\tgc_collect_cycles();\n\t}\n#endif\n\n\tzend_try {\n\t\tzend_objects_store_free_object_storage(&EG(objects_store));\n\n\t\tzend_vm_stack_destroy();\n\n\t\t\/* Destroy all op arrays *\/\n\t\tif (EG(full_tables_cleanup)) {\n\t\t\tzend_hash_reverse_apply(EG(function_table), clean_non_persistent_function_full);\n\t\t\tzend_hash_reverse_apply(EG(class_table), clean_non_persistent_class_full);\n\t\t} else {\n\t\t\tzend_hash_reverse_apply(EG(function_table), clean_non_persistent_function);\n\t\t\tzend_hash_reverse_apply(EG(class_table), clean_non_persistent_class);\n\t\t}\n\n\t\twhile (EG(symtable_cache_ptr)>=EG(symtable_cache)) {\n\t\t\tzend_hash_destroy(*EG(symtable_cache_ptr));\n\t\t\tFREE_HASHTABLE(*EG(symtable_cache_ptr));\n\t\t\tEG(symtable_cache_ptr)--;\n\t\t}\n\t} zend_end_try();\n\n\tzend_try {\n\t\tclean_non_persistent_constants();\n\t} zend_end_try();\n\n\tzend_try {\n#if 0&&ZEND_DEBUG\n\tsignal(SIGSEGV, original_sigsegv_handler);\n#endif\n\n\t\tzend_hash_destroy(&EG(included_files));\n\n\t\tzend_stack_destroy(&EG(user_error_handlers_error_reporting));\n\t\tzend_stack_destroy(&EG(user_error_handlers));\n\t\tzend_stack_destroy(&EG(user_exception_handlers));\n\t\tzend_objects_store_destroy(&EG(objects_store));\n\t\tif (EG(in_autoload)) {\n\t\t\tzend_hash_destroy(EG(in_autoload));\n\t\t\tFREE_HASHTABLE(EG(in_autoload));\n\t\t}\n\t} zend_end_try();\n\n\tzend_shutdown_fpu();\n\n\tEG(ht_iterators_used) = 0;\n\tif (EG(ht_iterators) != EG(ht_iterators_slots)) {\n\t\tefree(EG(ht_iterators));\n\t}\n\n\tEG(active) = 0;\n}","target":0,"code_token_length":1335,"total_token_length":1666,"max_tokens_setting":2048} +{"idx":468612,"func":"ClientRequestContext::clientRedirectDone(const Helper::Reply &reply)\n{\n HttpRequest *old_request = http->request;\n debugs(85, 5, HERE << \"'\" << http->uri << \"' result=\" << reply);\n assert(redirect_state == REDIRECT_PENDING);\n redirect_state = REDIRECT_DONE;\n\n \/\/ Put helper response Notes into the transaction state record (ALE) eventually\n \/\/ do it early to ensure that no matter what the outcome the notes are present.\n if (http->al)\n http->al->syncNotes(old_request);\n\n UpdateRequestNotes(http->getConn(), *old_request, reply.notes);\n\n switch (reply.result) {\n case Helper::TimedOut:\n if (Config.onUrlRewriteTimeout.action != toutActBypass) {\n static const auto d = MakeNamedErrorDetail(\"REDIRECTOR_TIMEDOUT\");\n http->calloutsError(ERR_GATEWAY_FAILURE, d);\n debugs(85, DBG_IMPORTANT, \"ERROR: URL rewrite helper: Timedout\");\n }\n break;\n\n case Helper::Unknown:\n case Helper::TT:\n \/\/ Handler in redirect.cc should have already mapped Unknown\n \/\/ IF it contained valid entry for the old URL-rewrite helper protocol\n debugs(85, DBG_IMPORTANT, \"ERROR: URL rewrite helper returned invalid result code. Wrong helper? \" << reply);\n break;\n\n case Helper::BrokenHelper:\n debugs(85, DBG_IMPORTANT, \"ERROR: URL rewrite helper: \" << reply);\n break;\n\n case Helper::Error:\n \/\/ no change to be done.\n break;\n\n case Helper::Okay: {\n \/\/ #1: redirect with a specific status code OK status=NNN url=\"...\"\n \/\/ #2: redirect with a default status code OK url=\"...\"\n \/\/ #3: re-write the URL OK rewrite-url=\"...\"\n\n const char *statusNote = reply.notes.findFirst(\"status\");\n const char *urlNote = reply.notes.findFirst(\"url\");\n\n if (urlNote != NULL) {\n \/\/ HTTP protocol redirect to be done.\n\n \/\/ TODO: change default redirect status for appropriate requests\n \/\/ Squid defaults to 302 status for now for better compatibility with old clients.\n \/\/ HTTP\/1.0 client should get 302 (Http::scFound)\n \/\/ HTTP\/1.1 client contacting reverse-proxy should get 307 (Http::scTemporaryRedirect)\n \/\/ HTTP\/1.1 client being diverted by forward-proxy should get 303 (Http::scSeeOther)\n Http::StatusCode status = Http::scFound;\n if (statusNote != NULL) {\n const char * result = statusNote;\n status = static_cast(atoi(result));\n }\n\n if (status == Http::scMovedPermanently\n || status == Http::scFound\n || status == Http::scSeeOther\n || status == Http::scPermanentRedirect\n || status == Http::scTemporaryRedirect) {\n http->redirect.status = status;\n http->redirect.location = xstrdup(urlNote);\n \/\/ TODO: validate the URL produced here is RFC 2616 compliant absolute URI\n } else {\n debugs(85, DBG_CRITICAL, \"ERROR: URL-rewrite produces invalid \" << status << \" redirect Location: \" << urlNote);\n }\n } else {\n \/\/ URL-rewrite wanted. Ew.\n urlNote = reply.notes.findFirst(\"rewrite-url\");\n\n \/\/ prevent broken helpers causing too much damage. If old URL == new URL skip the re-write.\n if (urlNote != NULL && strcmp(urlNote, http->uri)) {\n AnyP::Uri tmpUrl;\n if (tmpUrl.parse(old_request->method, SBuf(urlNote))) {\n HttpRequest *new_request = old_request->clone();\n new_request->url = tmpUrl;\n debugs(61, 2, \"URL-rewriter diverts URL from \" << old_request->effectiveRequestUri() << \" to \" << new_request->effectiveRequestUri());\n\n \/\/ update the new request to flag the re-writing was done on it\n new_request->flags.redirected = true;\n\n \/\/ unlink bodypipe from the old request. Not needed there any longer.\n if (old_request->body_pipe != NULL) {\n old_request->body_pipe = NULL;\n debugs(61,2, HERE << \"URL-rewriter diverts body_pipe \" << new_request->body_pipe <<\n \" from request \" << old_request << \" to \" << new_request);\n }\n\n http->resetRequest(new_request);\n old_request = nullptr;\n } else {\n debugs(85, DBG_CRITICAL, \"ERROR: URL-rewrite produces invalid request: \" <<\n old_request->method << \" \" << urlNote << \" \" << old_request->http_ver);\n }\n }\n }\n }\n break;\n }\n\n \/* XXX PIPELINE: This is inaccurate during pipelining *\/\n\n if (http->getConn() != NULL && Comm::IsConnOpen(http->getConn()->clientConnection))\n fd_note(http->getConn()->clientConnection->fd, http->uri);\n\n assert(http->uri);\n\n http->doCallouts();\n}","target":0,"code_token_length":1127,"total_token_length":1458,"max_tokens_setting":2048} +{"idx":324753,"func":"static void bamboo_init(MachineState *machine)\n\n{\n\n ram_addr_t ram_size = machine->ram_size;\n\n const char *kernel_filename = machine->kernel_filename;\n\n const char *kernel_cmdline = machine->kernel_cmdline;\n\n const char *initrd_filename = machine->initrd_filename;\n\n unsigned int pci_irq_nrs[4] = { 28, 27, 26, 25 };\n\n MemoryRegion *address_space_mem = get_system_memory();\n\n MemoryRegion *isa = g_new(MemoryRegion, 1);\n\n MemoryRegion *ram_memories\n\n = g_malloc(PPC440EP_SDRAM_NR_BANKS * sizeof(*ram_memories));\n\n hwaddr ram_bases[PPC440EP_SDRAM_NR_BANKS];\n\n hwaddr ram_sizes[PPC440EP_SDRAM_NR_BANKS];\n\n qemu_irq *pic;\n\n qemu_irq *irqs;\n\n PCIBus *pcibus;\n\n PowerPCCPU *cpu;\n\n CPUPPCState *env;\n\n uint64_t elf_entry;\n\n uint64_t elf_lowaddr;\n\n hwaddr loadaddr = 0;\n\n target_long initrd_size = 0;\n\n DeviceState *dev;\n\n int success;\n\n int i;\n\n\n\n \/* Setup CPU. *\/\n\n if (machine->cpu_model == NULL) {\n\n machine->cpu_model = \"440EP\";\n\n }\n\n cpu = POWERPC_CPU(cpu_generic_init(TYPE_POWERPC_CPU, machine->cpu_model));\n\n if (cpu == NULL) {\n\n fprintf(stderr, \"Unable to initialize CPU!\\n\");\n\n exit(1);\n\n }\n\n env = &cpu->env;\n\n\n\n if (env->mmu_model != POWERPC_MMU_BOOKE) {\n\n fprintf(stderr, \"MMU model %i not supported by this machine.\\n\",\n\n env->mmu_model);\n\n exit(1);\n\n }\n\n\n\n qemu_register_reset(main_cpu_reset, cpu);\n\n ppc_booke_timers_init(cpu, 400000000, 0);\n\n ppc_dcr_init(env, NULL, NULL);\n\n\n\n \/* interrupt controller *\/\n\n irqs = g_malloc0(sizeof(qemu_irq) * PPCUIC_OUTPUT_NB);\n\n irqs[PPCUIC_OUTPUT_INT] = ((qemu_irq *)env->irq_inputs)[PPC40x_INPUT_INT];\n\n irqs[PPCUIC_OUTPUT_CINT] = ((qemu_irq *)env->irq_inputs)[PPC40x_INPUT_CINT];\n\n pic = ppcuic_init(env, irqs, 0x0C0, 0, 1);\n\n\n\n \/* SDRAM controller *\/\n\n memset(ram_bases, 0, sizeof(ram_bases));\n\n memset(ram_sizes, 0, sizeof(ram_sizes));\n\n ram_size = ppc4xx_sdram_adjust(ram_size, PPC440EP_SDRAM_NR_BANKS,\n\n ram_memories,\n\n ram_bases, ram_sizes,\n\n ppc440ep_sdram_bank_sizes);\n\n \/* XXX 440EP's ECC interrupts are on UIC1, but we've only created UIC0. *\/\n\n ppc4xx_sdram_init(env, pic[14], PPC440EP_SDRAM_NR_BANKS, ram_memories,\n\n ram_bases, ram_sizes, 1);\n\n\n\n \/* PCI *\/\n\n dev = sysbus_create_varargs(TYPE_PPC4xx_PCI_HOST_BRIDGE,\n\n PPC440EP_PCI_CONFIG,\n\n pic[pci_irq_nrs[0]], pic[pci_irq_nrs[1]],\n\n pic[pci_irq_nrs[2]], pic[pci_irq_nrs[3]],\n\n NULL);\n\n pcibus = (PCIBus *)qdev_get_child_bus(dev, \"pci.0\");\n\n if (!pcibus) {\n\n fprintf(stderr, \"couldn't create PCI controller!\\n\");\n\n exit(1);\n\n }\n\n\n\n memory_region_init_alias(isa, NULL, \"isa_mmio\",\n\n get_system_io(), 0, PPC440EP_PCI_IOLEN);\n\n memory_region_add_subregion(get_system_memory(), PPC440EP_PCI_IO, isa);\n\n\n\n if (serial_hds[0] != NULL) {\n\n serial_mm_init(address_space_mem, 0xef600300, 0, pic[0],\n\n PPC_SERIAL_MM_BAUDBASE, serial_hds[0],\n\n DEVICE_BIG_ENDIAN);\n\n }\n\n if (serial_hds[1] != NULL) {\n\n serial_mm_init(address_space_mem, 0xef600400, 0, pic[1],\n\n PPC_SERIAL_MM_BAUDBASE, serial_hds[1],\n\n DEVICE_BIG_ENDIAN);\n\n }\n\n\n\n if (pcibus) {\n\n \/* Register network interfaces. *\/\n\n for (i = 0; i < nb_nics; i++) {\n\n \/* There are no PCI NICs on the Bamboo board, but there are\n\n * PCI slots, so we can pick whatever default model we want. *\/\n\n pci_nic_init_nofail(&nd_table[i], pcibus, \"e1000\", NULL);\n\n }\n\n }\n\n\n\n \/* Load kernel. *\/\n\n if (kernel_filename) {\n\n success = load_uimage(kernel_filename, &entry, &loadaddr, NULL,\n\n NULL, NULL);\n\n if (success < 0) {\n\n success = load_elf(kernel_filename, NULL, NULL, &elf_entry,\n\n &elf_lowaddr, NULL, 1, PPC_ELF_MACHINE,\n\n 0, 0);\n\n entry = elf_entry;\n\n loadaddr = elf_lowaddr;\n\n }\n\n \/* XXX try again as binary *\/\n\n if (success < 0) {\n\n fprintf(stderr, \"qemu: could not load kernel '%s'\\n\",\n\n kernel_filename);\n\n exit(1);\n\n }\n\n }\n\n\n\n \/* Load initrd. *\/\n\n if (initrd_filename) {\n\n initrd_size = load_image_targphys(initrd_filename, RAMDISK_ADDR,\n\n ram_size - RAMDISK_ADDR);\n\n\n\n if (initrd_size < 0) {\n\n fprintf(stderr, \"qemu: could not load ram disk '%s' at %x\\n\",\n\n initrd_filename, RAMDISK_ADDR);\n\n exit(1);\n\n }\n\n }\n\n\n\n \/* If we're loading a kernel directly, we must load the device tree too. *\/\n\n if (kernel_filename) {\n\n if (bamboo_load_device_tree(FDT_ADDR, ram_size, RAMDISK_ADDR,\n\n initrd_size, kernel_cmdline) < 0) {\n\n fprintf(stderr, \"couldn't load device tree\\n\");\n\n exit(1);\n\n }\n\n }\n\n}\n","target":1,"code_token_length":1426,"total_token_length":1757,"max_tokens_setting":2048} +{"idx":322157,"func":"static void dec_bit(DisasContext *dc)\n\n{\n\n TCGv t0, t1;\n\n unsigned int op;\n\n int mem_index = cpu_mmu_index(dc->env);\n\n\n\n op = dc->ir & ((1 << 9) - 1);\n\n switch (op) {\n\n case 0x21:\n\n \/* src. *\/\n\n t0 = tcg_temp_new();\n\n\n\n LOG_DIS(\"src r%d r%d\\n\", dc->rd, dc->ra);\n\n tcg_gen_andi_tl(t0, cpu_R[dc->ra], 1);\n\n if (dc->rd) {\n\n t1 = tcg_temp_new();\n\n read_carry(dc, t1);\n\n tcg_gen_shli_tl(t1, t1, 31);\n\n\n\n tcg_gen_shri_tl(cpu_R[dc->rd], cpu_R[dc->ra], 1);\n\n tcg_gen_or_tl(cpu_R[dc->rd], cpu_R[dc->rd], t1);\n\n tcg_temp_free(t1);\n\n }\n\n\n\n \/* Update carry. *\/\n\n write_carry(dc, t0);\n\n tcg_temp_free(t0);\n\n break;\n\n\n\n case 0x1:\n\n case 0x41:\n\n \/* srl. *\/\n\n t0 = tcg_temp_new();\n\n LOG_DIS(\"srl r%d r%d\\n\", dc->rd, dc->ra);\n\n\n\n \/* Update carry. *\/\n\n tcg_gen_andi_tl(t0, cpu_R[dc->ra], 1);\n\n write_carry(dc, t0);\n\n tcg_temp_free(t0);\n\n if (dc->rd) {\n\n if (op == 0x41)\n\n tcg_gen_shri_tl(cpu_R[dc->rd], cpu_R[dc->ra], 1);\n\n else\n\n tcg_gen_sari_tl(cpu_R[dc->rd], cpu_R[dc->ra], 1);\n\n }\n\n break;\n\n case 0x60:\n\n LOG_DIS(\"ext8s r%d r%d\\n\", dc->rd, dc->ra);\n\n tcg_gen_ext8s_i32(cpu_R[dc->rd], cpu_R[dc->ra]);\n\n break;\n\n case 0x61:\n\n LOG_DIS(\"ext16s r%d r%d\\n\", dc->rd, dc->ra);\n\n tcg_gen_ext16s_i32(cpu_R[dc->rd], cpu_R[dc->ra]);\n\n break;\n\n case 0x64:\n\n case 0x66:\n\n case 0x74:\n\n case 0x76:\n\n \/* wdc. *\/\n\n LOG_DIS(\"wdc r%d\\n\", dc->ra);\n\n if ((dc->tb_flags & MSR_EE_FLAG)\n\n && mem_index == MMU_USER_IDX) {\n\n tcg_gen_movi_tl(cpu_SR[SR_ESR], ESR_EC_PRIVINSN);\n\n t_gen_raise_exception(dc, EXCP_HW_EXCP);\n\n return;\n\n }\n\n break;\n\n case 0x68:\n\n \/* wic. *\/\n\n LOG_DIS(\"wic r%d\\n\", dc->ra);\n\n if ((dc->tb_flags & MSR_EE_FLAG)\n\n && mem_index == MMU_USER_IDX) {\n\n tcg_gen_movi_tl(cpu_SR[SR_ESR], ESR_EC_PRIVINSN);\n\n t_gen_raise_exception(dc, EXCP_HW_EXCP);\n\n return;\n\n }\n\n break;\n\n case 0xe0:\n\n if ((dc->tb_flags & MSR_EE_FLAG)\n\n && (dc->env->pvr.regs[2] & PVR2_ILL_OPCODE_EXC_MASK)\n\n && !((dc->env->pvr.regs[2] & PVR2_USE_PCMP_INSTR))) {\n\n tcg_gen_movi_tl(cpu_SR[SR_ESR], ESR_EC_ILLEGAL_OP);\n\n t_gen_raise_exception(dc, EXCP_HW_EXCP);\n\n }\n\n if (dc->env->pvr.regs[2] & PVR2_USE_PCMP_INSTR) {\n\n gen_helper_clz(cpu_R[dc->rd], cpu_R[dc->ra]);\n\n }\n\n break;\n\n case 0x1e0:\n\n \/* swapb *\/\n\n LOG_DIS(\"swapb r%d r%d\\n\", dc->rd, dc->ra);\n\n tcg_gen_bswap32_i32(cpu_R[dc->rd], cpu_R[dc->ra]);\n\n break;\n\n case 0x1e2:\n\n \/*swaph *\/\n\n LOG_DIS(\"swaph r%d r%d\\n\", dc->rd, dc->ra);\n\n tcg_gen_rotri_i32(cpu_R[dc->rd], cpu_R[dc->ra], 16);\n\n break;\n\n default:\n\n cpu_abort(dc->env, \"unknown bit oc=%x op=%x rd=%d ra=%d rb=%d\\n\",\n\n dc->pc, op, dc->rd, dc->ra, dc->rb);\n\n break;\n\n }\n\n}\n","target":0,"code_token_length":1088,"total_token_length":1419,"max_tokens_setting":2048} +{"idx":488986,"func":"static int dns_transaction_requires_rrsig(DnsTransaction *t, DnsResourceRecord *rr) {\n int r;\n\n assert(t);\n assert(rr);\n\n \/* Checks if the RR we are looking for must be signed with an\n * RRSIG. This is used for positive responses. *\/\n\n if (t->scope->dnssec_mode == DNSSEC_NO)\n return false;\n\n if (dns_type_is_pseudo(rr->key->type))\n return -EINVAL;\n\n r = dns_transaction_negative_trust_anchor_lookup(t, dns_resource_key_name(rr->key));\n if (r < 0)\n return r;\n if (r > 0)\n return false;\n\n switch (rr->key->type) {\n\n case DNS_TYPE_RRSIG:\n \/* RRSIGs are the signatures themselves, they need no signing. *\/\n return false;\n\n case DNS_TYPE_SOA:\n case DNS_TYPE_NS: {\n DnsTransaction *dt;\n Iterator i;\n\n \/* For SOA or NS RRs we look for a matching DS transaction *\/\n\n SET_FOREACH(dt, t->dnssec_transactions, i) {\n\n if (dt->key->class != rr->key->class)\n continue;\n if (dt->key->type != DNS_TYPE_DS)\n continue;\n\n r = dns_name_equal(dns_resource_key_name(dt->key), dns_resource_key_name(rr->key));\n if (r < 0)\n return r;\n if (r == 0)\n continue;\n\n \/* We found a DS transactions for the SOA\/NS\n * RRs we are looking at. If it discovered signed DS\n * RRs, then we need to be signed, too. *\/\n\n if (!dt->answer_authenticated)\n return false;\n\n return dns_answer_match_key(dt->answer, dt->key, NULL);\n }\n\n \/* We found nothing that proves this is safe to leave\n * this unauthenticated, hence ask inist on\n * authentication. *\/\n return true;\n }\n\n case DNS_TYPE_DS:\n case DNS_TYPE_CNAME:\n case DNS_TYPE_DNAME: {\n const char *parent = NULL;\n DnsTransaction *dt;\n Iterator i;\n\n \/*\n * CNAME\/DNAME RRs cannot be located at a zone apex, hence look directly for the parent SOA.\n *\n * DS RRs are signed if the parent is signed, hence also look at the parent SOA\n *\/\n\n SET_FOREACH(dt, t->dnssec_transactions, i) {\n\n if (dt->key->class != rr->key->class)\n continue;\n if (dt->key->type != DNS_TYPE_SOA)\n continue;\n\n if (!parent) {\n parent = dns_resource_key_name(rr->key);\n r = dns_name_parent(&parent);\n if (r < 0)\n return r;\n if (r == 0) {\n if (rr->key->type == DNS_TYPE_DS)\n return true;\n\n \/* A CNAME\/DNAME without a parent? That's sooo weird. *\/\n return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),\n \"Transaction %\" PRIu16 \" claims CNAME\/DNAME at root. Refusing.\", t->id);\n }\n }\n\n r = dns_name_equal(dns_resource_key_name(dt->key), parent);\n if (r < 0)\n return r;\n if (r == 0)\n continue;\n\n return t->answer_authenticated;\n }\n\n return true;\n }\n\n default: {\n DnsTransaction *dt;\n Iterator i;\n\n \/* Any other kind of RR (including DNSKEY\/NSEC\/NSEC3). Let's see if our SOA lookup was authenticated *\/\n\n SET_FOREACH(dt, t->dnssec_transactions, i) {\n\n if (dt->key->class != rr->key->class)\n continue;\n if (dt->key->type != DNS_TYPE_SOA)\n continue;\n\n r = dns_name_equal(dns_resource_key_name(dt->key), dns_resource_key_name(rr->key));\n if (r < 0)\n return r;\n if (r == 0)\n continue;\n\n \/* We found the transaction that was supposed to find\n * the SOA RR for us. It was successful, but found no\n * RR for us. This means we are not at a zone cut. In\n * this case, we require authentication if the SOA\n * lookup was authenticated too. *\/\n return t->answer_authenticated;\n }\n\n return true;\n }}\n}","target":0,"code_token_length":977,"total_token_length":1308,"max_tokens_setting":2048} +{"idx":11224,"func":"long Cluster::ParseBlockGroup(long long payload_size, long long& pos,\n long& len) {\n const long long payload_start = pos;\n const long long payload_stop = pos + payload_size;\n\n IMkvReader* const pReader = m_pSegment->m_pReader;\n\n long long total, avail;\n\n long status = pReader->Length(&total, &avail);\n\n if (status < 0) \/\/ error\n return status;\n\n assert((total < 0) || (avail <= total));\n\n if ((total >= 0) && (payload_stop > total))\n return E_FILE_FORMAT_INVALID;\n\n if (payload_stop > avail) {\n len = static_cast(payload_size);\n return E_BUFFER_NOT_FULL;\n }\n\n long long discard_padding = 0;\n\n while (pos < payload_stop) {\n\n if ((pos + 1) > avail) {\n len = 1;\n return E_BUFFER_NOT_FULL;\n }\n\n long long result = GetUIntLength(pReader, pos, len);\n\n if (result < 0) \/\/ error\n return static_cast(result);\n\n if (result > 0) \/\/ weird\n return E_BUFFER_NOT_FULL;\n\n if ((pos + len) > payload_stop)\n return E_FILE_FORMAT_INVALID;\n\n if ((pos + len) > avail)\n return E_BUFFER_NOT_FULL;\n\n const long long id = ReadUInt(pReader, pos, len);\n\n if (id < 0) \/\/ error\n return static_cast(id);\n\n if (id == 0) \/\/ not a value ID\n return E_FILE_FORMAT_INVALID;\n\n pos += len; \/\/ consume ID field\n\n\n if ((pos + 1) > avail) {\n len = 1;\n return E_BUFFER_NOT_FULL;\n }\n\n result = GetUIntLength(pReader, pos, len);\n\n if (result < 0) \/\/ error\n return static_cast(result);\n\n if (result > 0) \/\/ weird\n return E_BUFFER_NOT_FULL;\n\n if ((pos + len) > payload_stop)\n return E_FILE_FORMAT_INVALID;\n\n if ((pos + len) > avail)\n return E_BUFFER_NOT_FULL;\n\n const long long size = ReadUInt(pReader, pos, len);\n\n if (size < 0) \/\/ error\n return static_cast(size);\n\n pos += len; \/\/ consume size field\n\n\n if (pos > payload_stop)\n return E_FILE_FORMAT_INVALID;\n\n if (size == 0) \/\/ weird\n continue;\n\n const long long unknown_size = (1LL << (7 * len)) - 1;\n\n if (size == unknown_size)\n return E_FILE_FORMAT_INVALID;\n\n if (id == 0x35A2) { \/\/ DiscardPadding\n status = UnserializeInt(pReader, pos, size, discard_padding);\n\n if (status < 0) \/\/ error\n return status;\n }\n\n if (id != 0x21) { \/\/ sub-part of BlockGroup is not a Block\n pos += size; \/\/ consume sub-part of block group\n\n if (pos > payload_stop)\n return E_FILE_FORMAT_INVALID;\n\n continue;\n }\n\n const long long block_stop = pos + size;\n\n if (block_stop > payload_stop)\n return E_FILE_FORMAT_INVALID;\n\n\n if ((pos + 1) > avail) {\n len = 1;\n return E_BUFFER_NOT_FULL;\n }\n\n result = GetUIntLength(pReader, pos, len);\n\n if (result < 0) \/\/ error\n return static_cast(result);\n\n if (result > 0) \/\/ weird\n return E_BUFFER_NOT_FULL;\n\n if ((pos + len) > block_stop)\n return E_FILE_FORMAT_INVALID;\n\n if ((pos + len) > avail)\n return E_BUFFER_NOT_FULL;\n\n const long long track = ReadUInt(pReader, pos, len);\n\n if (track < 0) \/\/ error\n return static_cast(track);\n\n\n if (track == 0)\n return E_FILE_FORMAT_INVALID;\n \n#if 0\n const Tracks* const pTracks = m_pSegment->GetTracks();\n assert(pTracks);\n const long tn = static_cast(track);\n const Track* const pTrack = pTracks->GetTrackByNumber(tn);\n if (pTrack == NULL)\n return E_FILE_FORMAT_INVALID;\n#endif\n pos += len; \/\/ consume track number\n \n if ((pos + 2) > block_stop)\n return E_FILE_FORMAT_INVALID;\n\n if ((pos + 2) > avail) {\n len = 2;\n return E_BUFFER_NOT_FULL;\n }\n\n pos += 2; \/\/ consume timecode\n\n if ((pos + 1) > block_stop)\n return E_FILE_FORMAT_INVALID;\n\n if ((pos + 1) > avail) {\n len = 1;\n return E_BUFFER_NOT_FULL;\n }\n\n unsigned char flags;\n\n status = pReader->Read(pos, 1, &flags);\n\n if (status < 0) { \/\/ error or underflow\n len = 1;\n return status;\n }\n\n ++pos; \/\/ consume flags byte\n assert(pos <= avail);\n\n if (pos >= block_stop)\n return E_FILE_FORMAT_INVALID;\n\n const int lacing = int(flags & 0x06) >> 1;\n\n if ((lacing != 0) && (block_stop > avail)) {\n len = static_cast(block_stop - pos);\n return E_BUFFER_NOT_FULL;\n\n }\n \n pos = block_stop; \/\/ consume block-part of block group\n assert(pos <= payload_stop);\n }\n \n assert(pos == payload_stop);\n \n status = CreateBlock(0x20, \/\/ BlockGroup ID\n payload_start, payload_size, discard_padding);\n if (status != 0)\n return status;\n\n m_pos = payload_stop;\n\n return 0; \/\/ success\n}\n","target":1,"code_token_length":1181,"total_token_length":1512,"max_tokens_setting":2048} +{"idx":143,"func":"guint16 de_mid ( tvbuff_t * tvb , proto_tree * tree , packet_info * pinfo , guint32 offset , guint len , gchar * add_string , int string_len ) {\n guint8 oct ;\n guint32 curr_offset ;\n guint32 value ;\n gboolean odd ;\n const gchar * digit_str ;\n proto_item * ti ;\n curr_offset = offset ;\n oct = tvb_get_guint8 ( tvb , curr_offset ) ;\n switch ( oct & 0x07 ) {\n case 0 : proto_tree_add_item ( tree , hf_gsm_a_unused , tvb , curr_offset , 1 , ENC_BIG_ENDIAN ) ;\n proto_tree_add_item ( tree , hf_gsm_a_odd_even_ind , tvb , curr_offset , 1 , ENC_BIG_ENDIAN ) ;\n proto_tree_add_item ( tree , hf_gsm_a_mobile_identity_type , tvb , curr_offset , 1 , ENC_BIG_ENDIAN ) ;\n if ( add_string ) g_snprintf ( add_string , string_len , \" - No Identity Code\" ) ;\n curr_offset ++ ;\n if ( len > 1 ) {\n expert_add_info ( pinfo , tree , & ei_gsm_a_format_not_supported ) ;\n }\n curr_offset += len - 1 ;\n break ;\n case 3 : case 1 : odd = oct & 0x08 ;\n proto_tree_add_item ( tree , hf_gsm_a_id_dig_1 , tvb , curr_offset , 1 , ENC_BIG_ENDIAN ) ;\n proto_tree_add_item ( tree , hf_gsm_a_odd_even_ind , tvb , curr_offset , 1 , ENC_BIG_ENDIAN ) ;\n proto_tree_add_item ( tree , hf_gsm_a_mobile_identity_type , tvb , curr_offset , 1 , ENC_BIG_ENDIAN ) ;\n if ( ( oct & 0x07 ) == 3 ) {\n digit_str = tvb_bcd_dig_to_wmem_packet_str ( tvb , curr_offset , len - ( curr_offset - offset ) , NULL , TRUE ) ;\n proto_tree_add_string_format ( tree , hf_gsm_a_imeisv , tvb , curr_offset , len - ( curr_offset - offset ) , digit_str , \"BCD Digits: %s\" , digit_str ) ;\n }\n else {\n digit_str = dissect_e212_imsi ( tvb , pinfo , tree , curr_offset , len - ( curr_offset - offset ) , TRUE ) ;\n }\n if ( sccp_assoc && ! sccp_assoc -> calling_party ) {\n sccp_assoc -> calling_party = wmem_strdup_printf ( wmem_file_scope ( ) , ( ( oct & 0x07 ) == 3 ) ? \"IMEISV: %s\" : \"IMSI: %s\" , digit_str ) ;\n }\n if ( add_string ) g_snprintf ( add_string , string_len , \" - %s (%s)\" , ( ( oct & 0x07 ) == 3 ) ? \"IMEISV\" : \"IMSI\" , digit_str ) ;\n curr_offset += len - ( curr_offset - offset ) ;\n if ( ! odd ) {\n proto_tree_add_item ( tree , hf_gsm_a_filler , tvb , curr_offset - 1 , 1 , ENC_NA ) ;\n }\n break ;\n case 2 : proto_tree_add_uint_format_value ( tree , hf_gsm_a_identity_digit1 , tvb , curr_offset , 1 , oct , \"%c\" , Dgt1_9_bcd . out [ ( oct & 0xf0 ) >> 4 ] ) ;\n proto_tree_add_item ( tree , hf_gsm_a_odd_even_ind , tvb , curr_offset , 1 , ENC_BIG_ENDIAN ) ;\n proto_tree_add_item ( tree , hf_gsm_a_mobile_identity_type , tvb , curr_offset , 1 , ENC_BIG_ENDIAN ) ;\n curr_offset ++ ;\n if ( curr_offset - offset >= len ) return ( curr_offset - offset ) ;\n digit_str = tvb_bcd_dig_to_wmem_packet_str ( tvb , curr_offset , len - ( curr_offset - offset ) , NULL , FALSE ) ;\n proto_tree_add_string_format ( tree , hf_gsm_a_imei , tvb , curr_offset , len - ( curr_offset - offset ) , digit_str , \"BCD Digits: %s\" , digit_str ) ;\n if ( add_string ) g_snprintf ( add_string , string_len , \" - IMEI (%s)\" , digit_str ) ;\n curr_offset += len - ( curr_offset - offset ) ;\n break ;\n case 4 : proto_tree_add_item ( tree , hf_gsm_a_unused , tvb , curr_offset , 1 , ENC_BIG_ENDIAN ) ;\n proto_tree_add_item ( tree , hf_gsm_a_odd_even_ind , tvb , curr_offset , 1 , ENC_BIG_ENDIAN ) ;\n proto_tree_add_item ( tree , hf_gsm_a_mobile_identity_type , tvb , curr_offset , 1 , ENC_BIG_ENDIAN ) ;\n curr_offset ++ ;\n value = tvb_get_ntohl ( tvb , curr_offset ) ;\n proto_tree_add_uint ( tree , hf_gsm_a_tmsi , tvb , curr_offset , 4 , value ) ;\n if ( add_string ) g_snprintf ( add_string , string_len , \" - TMSI\/P-TMSI (0x%04x)\" , value ) ;\n curr_offset += 4 ;\n break ;\n case 5 : proto_tree_add_bits_item ( tree , hf_gsm_a_spare_bits , tvb , curr_offset << 3 , 2 , ENC_BIG_ENDIAN ) ;\n proto_tree_add_item ( tree , hf_gsm_a_mbs_ses_id_ind , tvb , curr_offset , 1 , ENC_BIG_ENDIAN ) ;\n proto_tree_add_item ( tree , hf_gsm_a_tmgi_mcc_mnc_ind , tvb , curr_offset , 1 , ENC_BIG_ENDIAN ) ;\n proto_tree_add_item ( tree , hf_gsm_a_odd_even_ind , tvb , curr_offset , 1 , ENC_BIG_ENDIAN ) ;\n proto_tree_add_item ( tree , hf_gsm_a_mobile_identity_type , tvb , curr_offset , 1 , ENC_BIG_ENDIAN ) ;\n curr_offset ++ ;\n proto_tree_add_item ( tree , hf_gsm_a_mbs_service_id , tvb , curr_offset , 3 , ENC_BIG_ENDIAN ) ;\n curr_offset += 3 ;\n if ( ( oct & 0x10 ) == 0x10 ) {\n curr_offset = dissect_e212_mcc_mnc ( tvb , pinfo , tree , curr_offset , E212_NONE , TRUE ) ;\n }\n if ( ( oct & 0x20 ) == 0x20 ) {\n proto_tree_add_item ( tree , hf_gsm_a_mbs_session_id , tvb , curr_offset , 1 , ENC_BIG_ENDIAN ) ;\n curr_offset ++ ;\n }\n break ;\n default : proto_tree_add_item ( tree , hf_gsm_a_odd_even_ind , tvb , curr_offset , 1 , ENC_BIG_ENDIAN ) ;\n ti = proto_tree_add_item ( tree , hf_gsm_a_mobile_identity_type , tvb , curr_offset , 1 , ENC_BIG_ENDIAN ) ;\n expert_add_info_format ( pinfo , ti , & ei_gsm_a_mobile_identity_type , \"Unknown format %u\" , ( oct & 0x07 ) ) ;\n if ( add_string ) g_snprintf ( add_string , string_len , \" - Format Unknown\" ) ;\n curr_offset += len ;\n break ;\n }\n EXTRANEOUS_DATA_CHECK ( len , curr_offset - offset , pinfo , & ei_gsm_a_extraneous_data ) ;\n return ( curr_offset - offset ) ;\n }","target":1,"code_token_length":1564,"total_token_length":1895,"max_tokens_setting":2048} +{"idx":447668,"func":"static bool net_tx_pkt_parse_headers(struct NetTxPkt *pkt)\n{\n struct iovec *l2_hdr, *l3_hdr;\n size_t bytes_read;\n size_t full_ip6hdr_len;\n uint16_t l3_proto;\n\n assert(pkt);\n\n l2_hdr = &pkt->vec[NET_TX_PKT_L2HDR_FRAG];\n l3_hdr = &pkt->vec[NET_TX_PKT_L3HDR_FRAG];\n\n bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, 0, l2_hdr->iov_base,\n ETH_MAX_L2_HDR_LEN);\n if (bytes_read < sizeof(struct eth_header)) {\n l2_hdr->iov_len = 0;\n return false;\n }\n\n l2_hdr->iov_len = sizeof(struct eth_header);\n switch (be16_to_cpu(PKT_GET_ETH_HDR(l2_hdr->iov_base)->h_proto)) {\n case ETH_P_VLAN:\n l2_hdr->iov_len += sizeof(struct vlan_header);\n break;\n case ETH_P_DVLAN:\n l2_hdr->iov_len += 2 * sizeof(struct vlan_header);\n break;\n }\n\n if (bytes_read < l2_hdr->iov_len) {\n l2_hdr->iov_len = 0;\n l3_hdr->iov_len = 0;\n pkt->packet_type = ETH_PKT_UCAST;\n return false;\n } else {\n l2_hdr->iov_len = ETH_MAX_L2_HDR_LEN;\n l2_hdr->iov_len = eth_get_l2_hdr_length(l2_hdr->iov_base);\n pkt->packet_type = get_eth_packet_type(l2_hdr->iov_base);\n }\n\n l3_proto = eth_get_l3_proto(l2_hdr, 1, l2_hdr->iov_len);\n\n switch (l3_proto) {\n case ETH_P_IP:\n bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,\n l3_hdr->iov_base, sizeof(struct ip_header));\n\n if (bytes_read < sizeof(struct ip_header)) {\n l3_hdr->iov_len = 0;\n return false;\n }\n\n l3_hdr->iov_len = IP_HDR_GET_LEN(l3_hdr->iov_base);\n\n if (l3_hdr->iov_len < sizeof(struct ip_header)) {\n l3_hdr->iov_len = 0;\n return false;\n }\n\n pkt->l4proto = IP_HDR_GET_P(l3_hdr->iov_base);\n\n if (IP_HDR_GET_LEN(l3_hdr->iov_base) != sizeof(struct ip_header)) {\n \/* copy optional IPv4 header data if any*\/\n bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags,\n l2_hdr->iov_len + sizeof(struct ip_header),\n l3_hdr->iov_base + sizeof(struct ip_header),\n l3_hdr->iov_len - sizeof(struct ip_header));\n if (bytes_read < l3_hdr->iov_len - sizeof(struct ip_header)) {\n l3_hdr->iov_len = 0;\n return false;\n }\n }\n\n break;\n\n case ETH_P_IPV6:\n {\n eth_ip6_hdr_info hdrinfo;\n\n if (!eth_parse_ipv6_hdr(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,\n &hdrinfo)) {\n l3_hdr->iov_len = 0;\n return false;\n }\n\n pkt->l4proto = hdrinfo.l4proto;\n full_ip6hdr_len = hdrinfo.full_hdr_len;\n\n if (full_ip6hdr_len > ETH_MAX_IP_DGRAM_LEN) {\n l3_hdr->iov_len = 0;\n return false;\n }\n\n bytes_read = iov_to_buf(pkt->raw, pkt->raw_frags, l2_hdr->iov_len,\n l3_hdr->iov_base, full_ip6hdr_len);\n\n if (bytes_read < full_ip6hdr_len) {\n l3_hdr->iov_len = 0;\n return false;\n } else {\n l3_hdr->iov_len = full_ip6hdr_len;\n }\n break;\n }\n default:\n l3_hdr->iov_len = 0;\n break;\n }\n\n net_tx_pkt_calculate_hdr_len(pkt);\n return true;\n}","target":0,"code_token_length":913,"total_token_length":1244,"max_tokens_setting":2048} +{"idx":192978,"func":"_dbus_strerror (int error_number)\n{\n#ifdef DBUS_WINCE\n return \"unknown\";\n#else\n const char *msg;\n\n switch (error_number)\n {\n case WSAEINTR:\n return \"Interrupted function call\";\n case WSAEACCES:\n return \"Permission denied\";\n case WSAEFAULT:\n return \"Bad address\";\n case WSAEINVAL:\n return \"Invalid argument\";\n case WSAEMFILE:\n return \"Too many open files\";\n case WSAEWOULDBLOCK:\n return \"Resource temporarily unavailable\";\n case WSAEINPROGRESS:\n return \"Operation now in progress\";\n case WSAEALREADY:\n return \"Operation already in progress\";\n case WSAENOTSOCK:\n return \"Socket operation on nonsocket\";\n case WSAEDESTADDRREQ:\n return \"Destination address required\";\n case WSAEMSGSIZE:\n return \"Message too long\";\n case WSAEPROTOTYPE:\n return \"Protocol wrong type for socket\";\n case WSAENOPROTOOPT:\n return \"Bad protocol option\";\n case WSAEPROTONOSUPPORT:\n return \"Protocol not supported\";\n case WSAESOCKTNOSUPPORT:\n return \"Socket type not supported\";\n case WSAEOPNOTSUPP:\n return \"Operation not supported\";\n case WSAEPFNOSUPPORT:\n return \"Protocol family not supported\";\n case WSAEAFNOSUPPORT:\n return \"Address family not supported by protocol family\";\n case WSAEADDRINUSE:\n return \"Address already in use\";\n case WSAEADDRNOTAVAIL:\n return \"Cannot assign requested address\";\n case WSAENETDOWN:\n return \"Network is down\";\n case WSAENETUNREACH:\n return \"Network is unreachable\";\n case WSAENETRESET:\n return \"Network dropped connection on reset\";\n case WSAECONNABORTED:\n return \"Software caused connection abort\";\n case WSAECONNRESET:\n return \"Connection reset by peer\";\n case WSAENOBUFS:\n return \"No buffer space available\";\n case WSAEISCONN:\n return \"Socket is already connected\";\n case WSAENOTCONN:\n return \"Socket is not connected\";\n case WSAESHUTDOWN:\n return \"Cannot send after socket shutdown\";\n case WSAETIMEDOUT:\n return \"Connection timed out\";\n case WSAECONNREFUSED:\n return \"Connection refused\";\n case WSAEHOSTDOWN:\n return \"Host is down\";\n case WSAEHOSTUNREACH:\n return \"No route to host\";\n case WSAEPROCLIM:\n return \"Too many processes\";\n case WSAEDISCON:\n return \"Graceful shutdown in progress\";\n case WSATYPE_NOT_FOUND:\n return \"Class type not found\";\n case WSAHOST_NOT_FOUND:\n return \"Host not found\";\n case WSATRY_AGAIN:\n return \"Nonauthoritative host not found\";\n case WSANO_RECOVERY:\n return \"This is a nonrecoverable error\";\n case WSANO_DATA:\n return \"Valid name, no data record of requested type\";\n case WSA_INVALID_HANDLE:\n return \"Specified event object handle is invalid\";\n case WSA_INVALID_PARAMETER:\n return \"One or more parameters are invalid\";\n case WSA_IO_INCOMPLETE:\n return \"Overlapped I\/O event object not in signaled state\";\n case WSA_IO_PENDING:\n return \"Overlapped operations will complete later\";\n case WSA_NOT_ENOUGH_MEMORY:\n return \"Insufficient memory available\";\n case WSA_OPERATION_ABORTED:\n return \"Overlapped operation aborted\";\n#ifdef WSAINVALIDPROCTABLE\n\n case WSAINVALIDPROCTABLE:\n return \"Invalid procedure table from service provider\";\n#endif\n#ifdef WSAINVALIDPROVIDER\n\n case WSAINVALIDPROVIDER:\n return \"Invalid service provider version number\";\n#endif\n#ifdef WSAPROVIDERFAILEDINIT\n\n case WSAPROVIDERFAILEDINIT:\n return \"Unable to initialize a service provider\";\n#endif\n\n case WSASYSCALLFAILURE:\n return \"System call failure\";\n }\n msg = strerror (error_number);\n if (msg == NULL)\n msg = \"unknown\";\n\n return msg;\n#endif \/\/DBUS_WINCE\n}\n","target":0,"code_token_length":938,"total_token_length":1269,"max_tokens_setting":2048} +{"idx":836,"func":"static void _LMBCSToUnicodeWithOffsets ( UConverterToUnicodeArgs * args , UErrorCode * err ) {\n char LMBCS [ ULMBCS_CHARSIZE_MAX ] ;\n UChar uniChar ;\n const char * saveSource ;\n const char * pStartLMBCS = args -> source ;\n const char * errSource = NULL ;\n int8_t savebytes = 0 ;\n while ( U_SUCCESS ( * err ) && args -> sourceLimit > args -> source && args -> targetLimit > args -> target ) {\n saveSource = args -> source ;\n if ( args -> converter -> toULength ) {\n const char * saveSourceLimit ;\n size_t size_old = args -> converter -> toULength ;\n size_t size_new_maybe_1 = sizeof ( LMBCS ) - size_old ;\n size_t size_new_maybe_2 = args -> sourceLimit - args -> source ;\n size_t size_new = ( size_new_maybe_1 < size_new_maybe_2 ) ? size_new_maybe_1 : size_new_maybe_2 ;\n uprv_memcpy ( LMBCS , args -> converter -> toUBytes , size_old ) ;\n uprv_memcpy ( LMBCS + size_old , args -> source , size_new ) ;\n saveSourceLimit = args -> sourceLimit ;\n args -> source = errSource = LMBCS ;\n args -> sourceLimit = LMBCS + size_old + size_new ;\n savebytes = ( int8_t ) ( size_old + size_new ) ;\n uniChar = ( UChar ) _LMBCSGetNextUCharWorker ( args , err ) ;\n args -> source = saveSource + ( ( args -> source - LMBCS ) - size_old ) ;\n args -> sourceLimit = saveSourceLimit ;\n if ( * err == U_TRUNCATED_CHAR_FOUND ) {\n args -> converter -> toULength = savebytes ;\n uprv_memcpy ( args -> converter -> toUBytes , LMBCS , savebytes ) ;\n args -> source = args -> sourceLimit ;\n * err = U_ZERO_ERROR ;\n return ;\n }\n else {\n args -> converter -> toULength = 0 ;\n }\n }\n else {\n errSource = saveSource ;\n uniChar = ( UChar ) _LMBCSGetNextUCharWorker ( args , err ) ;\n savebytes = ( int8_t ) ( args -> source - saveSource ) ;\n }\n if ( U_SUCCESS ( * err ) ) {\n if ( uniChar < 0xfffe ) {\n * ( args -> target ) ++ = uniChar ;\n if ( args -> offsets ) {\n * ( args -> offsets ) ++ = ( int32_t ) ( saveSource - pStartLMBCS ) ;\n }\n }\n else if ( uniChar == 0xfffe ) {\n * err = U_INVALID_CHAR_FOUND ;\n }\n else {\n * err = U_ILLEGAL_CHAR_FOUND ;\n }\n }\n }\n if ( U_SUCCESS ( * err ) && args -> sourceLimit > args -> source && args -> targetLimit <= args -> target ) {\n * err = U_BUFFER_OVERFLOW_ERROR ;\n }\n else if ( U_FAILURE ( * err ) ) {\n args -> converter -> toULength = savebytes ;\n if ( savebytes > 0 ) {\n uprv_memcpy ( args -> converter -> toUBytes , errSource , savebytes ) ;\n }\n if ( * err == U_TRUNCATED_CHAR_FOUND ) {\n * err = U_ZERO_ERROR ;\n }\n }\n }","target":1,"code_token_length":698,"total_token_length":1029,"max_tokens_setting":2048} +{"idx":407959,"func":"static int setcharset(unsigned char **p, unsigned char *charset)\n{\n setcharset_state state = CURLFNM_SCHS_DEFAULT;\n unsigned char rangestart = 0;\n unsigned char lastchar = 0;\n bool something_found = FALSE;\n unsigned char c;\n for(;;) {\n c = **p;\n if(!c)\n return SETCHARSET_FAIL;\n\n switch(state) {\n case CURLFNM_SCHS_DEFAULT:\n if(ISALNUM(c)) { \/* ASCII value *\/\n rangestart = c;\n charset[c] = 1;\n (*p)++;\n state = CURLFNM_SCHS_MAYRANGE;\n something_found = TRUE;\n }\n else if(c == ']') {\n if(something_found)\n return SETCHARSET_OK;\n something_found = TRUE;\n state = CURLFNM_SCHS_RIGHTBR;\n charset[c] = 1;\n (*p)++;\n }\n else if(c == '[') {\n char c2 = *((*p) + 1);\n if(c2 == ':') { \/* there has to be a keyword *\/\n (*p) += 2;\n if(parsekeyword(p, charset)) {\n state = CURLFNM_SCHS_DEFAULT;\n }\n else\n return SETCHARSET_FAIL;\n }\n else {\n charset[c] = 1;\n (*p)++;\n }\n something_found = TRUE;\n }\n else if(c == '?' || c == '*') {\n something_found = TRUE;\n charset[c] = 1;\n (*p)++;\n }\n else if(c == '^' || c == '!') {\n if(!something_found) {\n if(charset[CURLFNM_NEGATE]) {\n charset[c] = 1;\n something_found = TRUE;\n }\n else\n charset[CURLFNM_NEGATE] = 1; \/* negate charset *\/\n }\n else\n charset[c] = 1;\n (*p)++;\n }\n else if(c == '\\\\') {\n c = *(++(*p));\n if(ISPRINT((c))) {\n something_found = TRUE;\n state = CURLFNM_SCHS_MAYRANGE;\n charset[c] = 1;\n rangestart = c;\n (*p)++;\n }\n else\n return SETCHARSET_FAIL;\n }\n else {\n charset[c] = 1;\n (*p)++;\n something_found = TRUE;\n }\n break;\n case CURLFNM_SCHS_MAYRANGE:\n if(c == '-') {\n charset[c] = 1;\n (*p)++;\n lastchar = '-';\n state = CURLFNM_SCHS_MAYRANGE2;\n }\n else if(c == '[') {\n state = CURLFNM_SCHS_DEFAULT;\n }\n else if(ISALNUM(c)) {\n charset[c] = 1;\n (*p)++;\n }\n else if(c == '\\\\') {\n c = *(++(*p));\n if(ISPRINT(c)) {\n charset[c] = 1;\n (*p)++;\n }\n else\n return SETCHARSET_FAIL;\n }\n else if(c == ']') {\n return SETCHARSET_OK;\n }\n else\n return SETCHARSET_FAIL;\n break;\n case CURLFNM_SCHS_MAYRANGE2:\n if(c == ']') {\n return SETCHARSET_OK;\n }\n else if(c == '\\\\') {\n c = *(++(*p));\n if(ISPRINT(c)) {\n charset[c] = 1;\n state = CURLFNM_SCHS_DEFAULT;\n (*p)++;\n }\n else\n return SETCHARSET_FAIL;\n }\n else if(c >= rangestart) {\n if((ISLOWER(c) && ISLOWER(rangestart)) ||\n (ISDIGIT(c) && ISDIGIT(rangestart)) ||\n (ISUPPER(c) && ISUPPER(rangestart))) {\n charset[lastchar] = 0;\n rangestart++;\n while(rangestart++ <= c)\n charset[rangestart-1] = 1;\n (*p)++;\n state = CURLFNM_SCHS_DEFAULT;\n }\n else\n return SETCHARSET_FAIL;\n }\n else\n return SETCHARSET_FAIL;\n break;\n case CURLFNM_SCHS_RIGHTBR:\n if(c == '[') {\n state = CURLFNM_SCHS_RIGHTBRLEFTBR;\n charset[c] = 1;\n (*p)++;\n }\n else if(c == ']') {\n return SETCHARSET_OK;\n }\n else if(ISPRINT(c)) {\n charset[c] = 1;\n (*p)++;\n state = CURLFNM_SCHS_DEFAULT;\n }\n else\n \/* used 'goto fail' instead of 'return SETCHARSET_FAIL' to avoid a\n * nonsense warning 'statement not reached' at end of the fnc when\n * compiling on Solaris *\/\n goto fail;\n break;\n case CURLFNM_SCHS_RIGHTBRLEFTBR:\n if(c == ']') {\n return SETCHARSET_OK;\n }\n else {\n state = CURLFNM_SCHS_DEFAULT;\n charset[c] = 1;\n (*p)++;\n }\n break;\n }\n }\nfail:\n return SETCHARSET_FAIL;\n}","target":0,"code_token_length":1158,"total_token_length":1489,"max_tokens_setting":2048} +{"idx":25764,"func":"static void std_conv_pixmap ( fz_context * ctx , fz_pixmap * dst , fz_pixmap * src , fz_colorspace * prf , const fz_default_colorspaces * default_cs , const fz_color_params * color_params , int copy_spots ) {\n float srcv [ FZ_MAX_COLORS ] ;\n float dstv [ FZ_MAX_COLORS ] ;\n int srcn , dstn ;\n int k , i ;\n size_t w = src -> w ;\n int h = src -> h ;\n ptrdiff_t d_line_inc = dst -> stride - w * dst -> n ;\n ptrdiff_t s_line_inc = src -> stride - w * src -> n ;\n int da = dst -> alpha ;\n int sa = src -> alpha ;\n fz_colorspace * ss = src -> colorspace ;\n fz_colorspace * ds = dst -> colorspace ;\n unsigned char * s = src -> samples ;\n unsigned char * d = dst -> samples ;\n if ( ( int ) w < 0 || h < 0 ) return ;\n if ( color_params == NULL ) color_params = fz_default_color_params ( ctx ) ;\n srcn = ss -> n ;\n dstn = ds -> n ;\n assert ( src -> w == dst -> w && src -> h == dst -> h ) ;\n assert ( src -> n == srcn + sa ) ;\n assert ( dst -> n == dstn + da ) ;\n if ( d_line_inc == 0 && s_line_inc == 0 ) {\n w *= h ;\n h = 1 ;\n }\n if ( ( fz_colorspace_is_lab ( ctx , ss ) || fz_colorspace_is_lab_icc ( ctx , ss ) ) && srcn == 3 ) {\n fz_color_converter cc ;\n fz_find_color_converter ( ctx , & cc , NULL , ds , ss , color_params ) ;\n while ( h -- ) {\n size_t ww = w ;\n while ( ww -- ) {\n srcv [ 0 ] = * s ++ \/ 255.0f * 100 ;\n srcv [ 1 ] = * s ++ - 128 ;\n srcv [ 2 ] = * s ++ - 128 ;\n cc . convert ( ctx , & cc , dstv , srcv ) ;\n for ( k = 0 ;\n k < dstn ;\n k ++ ) * d ++ = dstv [ k ] * 255 ;\n if ( da ) * d ++ = ( sa ? * s : 255 ) ;\n s += sa ;\n }\n d += d_line_inc ;\n s += s_line_inc ;\n }\n fz_drop_color_converter ( ctx , & cc ) ;\n }\n else if ( w * h < 256 ) {\n fz_color_converter cc ;\n fz_find_color_converter ( ctx , & cc , NULL , ds , ss , color_params ) ;\n while ( h -- ) {\n size_t ww = w ;\n while ( ww -- ) {\n for ( k = 0 ;\n k < srcn ;\n k ++ ) srcv [ k ] = * s ++ \/ 255.0f ;\n cc . convert ( ctx , & cc , dstv , srcv ) ;\n for ( k = 0 ;\n k < dstn ;\n k ++ ) * d ++ = dstv [ k ] * 255 ;\n if ( da ) * d ++ = ( sa ? * s : 255 ) ;\n s += sa ;\n }\n d += d_line_inc ;\n s += s_line_inc ;\n }\n fz_drop_color_converter ( ctx , & cc ) ;\n }\n else if ( srcn == 1 ) {\n unsigned char lookup [ FZ_MAX_COLORS * 256 ] ;\n fz_color_converter cc ;\n fz_find_color_converter ( ctx , & cc , NULL , ds , ss , color_params ) ;\n for ( i = 0 ;\n i < 256 ;\n i ++ ) {\n srcv [ 0 ] = i \/ 255.0f ;\n cc . convert ( ctx , & cc , dstv , srcv ) ;\n for ( k = 0 ;\n k < dstn ;\n k ++ ) lookup [ i * dstn + k ] = dstv [ k ] * 255 ;\n }\n fz_drop_color_converter ( ctx , & cc ) ;\n while ( h -- ) {\n size_t ww = w ;\n while ( ww -- ) {\n i = * s ++ ;\n for ( k = 0 ;\n k < dstn ;\n k ++ ) * d ++ = lookup [ i * dstn + k ] ;\n if ( da ) * d ++ = ( sa ? * s : 255 ) ;\n s += sa ;\n }\n d += d_line_inc ;\n s += s_line_inc ;\n }\n }\n else {\n fz_hash_table * lookup ;\n unsigned char * color ;\n unsigned char dummy = s [ 0 ] ^ 255 ;\n unsigned char * sold = & dummy ;\n unsigned char * dold ;\n fz_color_converter cc ;\n lookup = fz_new_hash_table ( ctx , 509 , srcn , - 1 , NULL ) ;\n fz_find_color_converter ( ctx , & cc , NULL , ds , ss , color_params ) ;\n fz_try ( ctx ) {\n while ( h -- ) {\n size_t ww = w ;\n while ( ww -- ) {\n if ( * s == * sold && memcmp ( sold , s , srcn ) == 0 ) {\n sold = s ;\n memcpy ( d , dold , dstn ) ;\n d += dstn ;\n s += srcn ;\n if ( da ) * d ++ = ( sa ? * s : 255 ) ;\n s += sa ;\n }\n else {\n sold = s ;\n dold = d ;\n color = fz_hash_find ( ctx , lookup , s ) ;\n if ( color ) {\n memcpy ( d , color , dstn ) ;\n s += srcn ;\n d += dstn ;\n if ( da ) * d ++ = ( sa ? * s : 255 ) ;\n s += sa ;\n }\n else {\n for ( k = 0 ;\n k < srcn ;\n k ++ ) srcv [ k ] = * s ++ \/ 255.0f ;\n cc . convert ( ctx , & cc , dstv , srcv ) ;\n for ( k = 0 ;\n k < dstn ;\n k ++ ) * d ++ = dstv [ k ] * 255 ;\n fz_hash_insert ( ctx , lookup , s - srcn , d - dstn ) ;\n if ( da ) * d ++ = ( sa ? * s : 255 ) ;\n s += sa ;\n }\n }\n }\n d += d_line_inc ;\n s += s_line_inc ;\n }\n }\n fz_always ( ctx ) fz_drop_color_converter ( ctx , & cc ) ;\n fz_catch ( ctx ) fz_rethrow ( ctx ) ;\n fz_drop_hash_table ( ctx , lookup ) ;\n }\n }","target":0,"code_token_length":1409,"total_token_length":1740,"max_tokens_setting":2048} +{"idx":136573,"func":"PHP_FUNCTION(imageloadfont)\n{\n\tchar *file;\n\tint file_name, hdr_size = sizeof(gdFont) - sizeof(char *);\n\tint ind, body_size, n = 0, b, i, body_size_check;\n\tgdFontPtr font;\n\tphp_stream *stream;\n\n\tif (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"p\", &file, &file_name) == FAILURE) {\n\t\treturn;\n\t}\n\n\tstream = php_stream_open_wrapper(file, \"rb\", IGNORE_PATH | IGNORE_URL_WIN | REPORT_ERRORS, NULL);\n\tif (stream == NULL) {\n\t\tRETURN_FALSE;\n\t}\n\n\t\/* Only supports a architecture-dependent binary dump format\n\t * at the moment.\n\t * The file format is like this on machines with 32-byte integers:\n\t *\n\t * byte 0-3: (int) number of characters in the font\n\t * byte 4-7: (int) value of first character in the font (often 32, space)\n\t * byte 8-11: (int) pixel width of each character\n\t * byte 12-15: (int) pixel height of each character\n\t * bytes 16-: (char) array with character data, one byte per pixel\n\t * in each character, for a total of\n\t * (nchars*width*height) bytes.\n\t *\/\n\tfont = (gdFontPtr) emalloc(sizeof(gdFont));\n\tb = 0;\n\twhile (b < hdr_size && (n = php_stream_read(stream, (char*)&font[b], hdr_size - b))) {\n\t\tb += n;\n\t}\n\n\tif (!n) {\n\t\tefree(font);\n\t\tif (php_stream_eof(stream)) {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"End of file while reading header\");\n\t\t} else {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Error while reading header\");\n\t\t}\n\t\tphp_stream_close(stream);\n\t\tRETURN_FALSE;\n\t}\n\ti = php_stream_tell(stream);\n\tphp_stream_seek(stream, 0, SEEK_END);\n\tbody_size_check = php_stream_tell(stream) - hdr_size;\n\tphp_stream_seek(stream, i, SEEK_SET);\n\n\tbody_size = font->w * font->h * font->nchars;\n\tif (body_size != body_size_check) {\n\t\tfont->w = FLIPWORD(font->w);\n\t\tfont->h = FLIPWORD(font->h);\n\t\tfont->nchars = FLIPWORD(font->nchars);\n\t\tbody_size = font->w * font->h * font->nchars;\n\t}\n\n\tif (overflow2(font->nchars, font->h) || overflow2(font->nchars * font->h, font->w )) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Error reading font, invalid font header\");\n\t\tefree(font);\n\t\tphp_stream_close(stream);\n\t\tRETURN_FALSE;\n\t}\n\n\tif (body_size != body_size_check) {\n\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Error reading font\");\n\t\tefree(font);\n\t\tphp_stream_close(stream);\n\t\tRETURN_FALSE;\n\t}\n\n\tfont->data = emalloc(body_size);\n\tb = 0;\n\twhile (b < body_size && (n = php_stream_read(stream, &font->data[b], body_size - b))) {\n\t\tb += n;\n\t}\n\n\tif (!n) {\n\t\tefree(font->data);\n\t\tefree(font);\n\t\tif (php_stream_eof(stream)) {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"End of file while reading body\");\n\t\t} else {\n\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Error while reading body\");\n\t\t}\n\t\tphp_stream_close(stream);\n\t\tRETURN_FALSE;\n\t}\n\tphp_stream_close(stream);\n\n\t\/* Adding 5 to the font index so we will never have font indices\n\t * that overlap with the old fonts (with indices 1-5). The first\n\t * list index given out is always 1.\n\t *\/\n\tind = 5 + zend_list_insert(font, le_gd_font TSRMLS_CC);\n\n\tRETURN_LONG(ind);\n}","target":0,"code_token_length":892,"total_token_length":1223,"max_tokens_setting":2048} +{"idx":71040,"func":"rtl8xxxu_bss_info_changed(struct ieee80211_hw *hw, struct ieee80211_vif *vif,\n\t\t\t struct ieee80211_bss_conf *bss_conf, u32 changed)\n{\n\tstruct rtl8xxxu_priv *priv = hw->priv;\n\tstruct device *dev = &priv->udev->dev;\n\tstruct ieee80211_sta *sta;\n\tu32 val32;\n\tu8 val8;\n\n\tif (changed & BSS_CHANGED_ASSOC) {\n\t\tdev_dbg(dev, \"Changed ASSOC: %i!\\n\", bss_conf->assoc);\n\n\t\trtl8xxxu_set_linktype(priv, vif->type);\n\n\t\tif (bss_conf->assoc) {\n\t\t\tu32 ramask;\n\t\t\tint sgi = 0;\n\n\t\t\trcu_read_lock();\n\t\t\tsta = ieee80211_find_sta(vif, bss_conf->bssid);\n\t\t\tif (!sta) {\n\t\t\t\tdev_info(dev, \"%s: ASSOC no sta found\\n\",\n\t\t\t\t\t __func__);\n\t\t\t\trcu_read_unlock();\n\t\t\t\tgoto error;\n\t\t\t}\n\n\t\t\tif (sta->ht_cap.ht_supported)\n\t\t\t\tdev_info(dev, \"%s: HT supported\\n\", __func__);\n\t\t\tif (sta->vht_cap.vht_supported)\n\t\t\t\tdev_info(dev, \"%s: VHT supported\\n\", __func__);\n\n\t\t\t\/* TODO: Set bits 28-31 for rate adaptive id *\/\n\t\t\tramask = (sta->supp_rates[0] & 0xfff) |\n\t\t\t\tsta->ht_cap.mcs.rx_mask[0] << 12 |\n\t\t\t\tsta->ht_cap.mcs.rx_mask[1] << 20;\n\t\t\tif (sta->ht_cap.cap &\n\t\t\t (IEEE80211_HT_CAP_SGI_40 | IEEE80211_HT_CAP_SGI_20))\n\t\t\t\tsgi = 1;\n\t\t\trcu_read_unlock();\n\n\t\t\tpriv->fops->update_rate_mask(priv, ramask, sgi);\n\n\t\t\trtl8xxxu_write8(priv, REG_BCN_MAX_ERR, 0xff);\n\n\t\t\trtl8xxxu_stop_tx_beacon(priv);\n\n\t\t\t\/* joinbss sequence *\/\n\t\t\trtl8xxxu_write16(priv, REG_BCN_PSR_RPT,\n\t\t\t\t\t 0xc000 | bss_conf->aid);\n\n\t\t\tpriv->fops->report_connect(priv, 0, true);\n\t\t} else {\n\t\t\tval8 = rtl8xxxu_read8(priv, REG_BEACON_CTRL);\n\t\t\tval8 |= BEACON_DISABLE_TSF_UPDATE;\n\t\t\trtl8xxxu_write8(priv, REG_BEACON_CTRL, val8);\n\n\t\t\tpriv->fops->report_connect(priv, 0, false);\n\t\t}\n\t}\n\n\tif (changed & BSS_CHANGED_ERP_PREAMBLE) {\n\t\tdev_dbg(dev, \"Changed ERP_PREAMBLE: Use short preamble %i\\n\",\n\t\t\tbss_conf->use_short_preamble);\n\t\tval32 = rtl8xxxu_read32(priv, REG_RESPONSE_RATE_SET);\n\t\tif (bss_conf->use_short_preamble)\n\t\t\tval32 |= RSR_ACK_SHORT_PREAMBLE;\n\t\telse\n\t\t\tval32 &= ~RSR_ACK_SHORT_PREAMBLE;\n\t\trtl8xxxu_write32(priv, REG_RESPONSE_RATE_SET, val32);\n\t}\n\n\tif (changed & BSS_CHANGED_ERP_SLOT) {\n\t\tdev_dbg(dev, \"Changed ERP_SLOT: short_slot_time %i\\n\",\n\t\t\tbss_conf->use_short_slot);\n\n\t\tif (bss_conf->use_short_slot)\n\t\t\tval8 = 9;\n\t\telse\n\t\t\tval8 = 20;\n\t\trtl8xxxu_write8(priv, REG_SLOT, val8);\n\t}\n\n\tif (changed & BSS_CHANGED_BSSID) {\n\t\tdev_dbg(dev, \"Changed BSSID!\\n\");\n\t\trtl8xxxu_set_bssid(priv, bss_conf->bssid);\n\t}\n\n\tif (changed & BSS_CHANGED_BASIC_RATES) {\n\t\tdev_dbg(dev, \"Changed BASIC_RATES!\\n\");\n\t\trtl8xxxu_set_basic_rates(priv, bss_conf->basic_rates);\n\t}\nerror:\n\treturn;\n}","target":0,"code_token_length":904,"total_token_length":1235,"max_tokens_setting":2048} +{"idx":70160,"func":"bool Unpack::UnpackLargeBlock(UnpackThreadData &D)\n{\n if (!D.TableRead)\n {\n D.TableRead=true;\n if (!ReadTables(D.Inp,D.BlockHeader,D.BlockTables))\n {\n D.DamagedData=true;\n return false;\n }\n }\n\n if (D.Inp.InAddr>D.BlockHeader.HeaderSize+D.BlockHeader.BlockSize)\n {\n D.DamagedData=true;\n return false;\n }\n \n int BlockBorder=D.BlockHeader.BlockStart+D.BlockHeader.BlockSize-1;\n\n \/\/ Reserve enough space even for filter entry.\n int DataBorder=D.DataSize-16;\n int ReadBorder=Min(BlockBorder,DataBorder);\n\n while (true)\n {\n UnpPtr&=MaxWinMask;\n if (D.Inp.InAddr>=ReadBorder)\n {\n if (D.Inp.InAddr>BlockBorder || D.Inp.InAddr==BlockBorder && \n D.Inp.InBit>=D.BlockHeader.BlockBitSize)\n break;\n\n \/\/ If we do not have any more data in file to read, we must process\n \/\/ what we have until last byte. Otherwise we can return and append\n \/\/ more data to unprocessed few bytes.\n if ((D.Inp.InAddr>=DataBorder) && !D.NoDataLeft || D.Inp.InAddr>=D.DataSize)\n {\n D.Incomplete=true;\n break;\n }\n }\n if (((WriteBorder-UnpPtr) & MaxWinMask)DestUnpSize)\n return false;\n }\n\n uint MainSlot=DecodeNumber(D.Inp,&D.BlockTables.LD);\n if (MainSlot<256)\n {\n Window[UnpPtr++]=(byte)MainSlot;\n continue;\n }\n if (MainSlot>=262)\n {\n uint Length=SlotToLength(D.Inp,MainSlot-262);\n\n uint DBits,Distance=1,DistSlot=DecodeNumber(D.Inp,&D.BlockTables.DD);\n if (DistSlot<4)\n {\n DBits=0;\n Distance+=DistSlot;\n }\n else\n {\n DBits=DistSlot\/2 - 1;\n Distance+=(2 | (DistSlot & 1)) << DBits;\n }\n\n if (DBits>0)\n {\n if (DBits>=4)\n {\n if (DBits>4)\n {\n Distance+=((D.Inp.getbits32()>>(36-DBits))<<4);\n D.Inp.addbits(DBits-4);\n }\n uint LowDist=DecodeNumber(D.Inp,&D.BlockTables.LDD);\n Distance+=LowDist;\n }\n else\n {\n Distance+=D.Inp.getbits32()>>(32-DBits);\n D.Inp.addbits(DBits);\n }\n }\n\n if (Distance>0x100)\n {\n Length++;\n if (Distance>0x2000)\n {\n Length++;\n if (Distance>0x40000)\n Length++;\n }\n }\n\n InsertOldDist(Distance);\n LastLength=Length;\n CopyString(Length,Distance);\n continue;\n }\n if (MainSlot==256)\n {\n UnpackFilter Filter;\n if (!ReadFilter(D.Inp,Filter) || !AddFilter(Filter))\n break;\n continue;\n }\n if (MainSlot==257)\n {\n if (LastLength!=0)\n CopyString(LastLength,OldDist[0]);\n continue;\n }\n if (MainSlot<262)\n {\n uint DistNum=MainSlot-258;\n uint Distance=OldDist[DistNum];\n for (uint I=DistNum;I>0;I--)\n OldDist[I]=OldDist[I-1];\n OldDist[0]=Distance;\n\n uint LengthSlot=DecodeNumber(D.Inp,&D.BlockTables.RD);\n uint Length=SlotToLength(D.Inp,LengthSlot);\n LastLength=Length;\n CopyString(Length,Distance);\n continue;\n }\n }\n return true;\n}","target":0,"code_token_length":932,"total_token_length":1263,"max_tokens_setting":2048} +{"idx":68224,"func":"int nntp_open_connection(struct NntpAccountData *adata)\n{\n struct Connection *conn = adata->conn;\n char buf[256];\n int cap;\n bool posting = false, auth = true;\n\n if (adata->status == NNTP_OK)\n return 0;\n if (adata->status == NNTP_BYE)\n return -1;\n adata->status = NNTP_NONE;\n\n if (mutt_socket_open(conn) < 0)\n return -1;\n\n if (mutt_socket_readln(buf, sizeof(buf), conn) < 0)\n return nntp_connect_error(adata);\n\n if (mutt_str_startswith(buf, \"200\", CASE_MATCH))\n posting = true;\n else if (!mutt_str_startswith(buf, \"201\", CASE_MATCH))\n {\n mutt_socket_close(conn);\n mutt_str_remove_trailing_ws(buf);\n mutt_error(\"%s\", buf);\n return -1;\n }\n\n \/* get initial capabilities *\/\n cap = nntp_capabilities(adata);\n if (cap < 0)\n return -1;\n\n \/* tell news server to switch to mode reader if it isn't so *\/\n if (cap > 0)\n {\n if ((mutt_socket_send(conn, \"MODE READER\\r\\n\") < 0) ||\n (mutt_socket_readln(buf, sizeof(buf), conn) < 0))\n {\n return nntp_connect_error(adata);\n }\n\n if (mutt_str_startswith(buf, \"200\", CASE_MATCH))\n posting = true;\n else if (mutt_str_startswith(buf, \"201\", CASE_MATCH))\n posting = false;\n \/* error if has capabilities, ignore result if no capabilities *\/\n else if (adata->hasCAPABILITIES)\n {\n mutt_socket_close(conn);\n mutt_error(_(\"Could not switch to reader mode\"));\n return -1;\n }\n\n \/* recheck capabilities after MODE READER *\/\n if (adata->hasCAPABILITIES)\n {\n cap = nntp_capabilities(adata);\n if (cap < 0)\n return -1;\n }\n }\n\n mutt_message(_(\"Connected to %s. %s\"), conn->account.host,\n posting ? _(\"Posting is ok\") : _(\"Posting is NOT ok\"));\n mutt_sleep(1);\n\n#ifdef USE_SSL\n \/* Attempt STARTTLS if available and desired. *\/\n if ((adata->use_tls != 1) && (adata->hasSTARTTLS || C_SslForceTls))\n {\n if (adata->use_tls == 0)\n {\n adata->use_tls =\n C_SslForceTls || query_quadoption(C_SslStarttls,\n _(\"Secure connection with TLS?\")) == MUTT_YES ?\n 2 :\n 1;\n }\n if (adata->use_tls == 2)\n {\n if ((mutt_socket_send(conn, \"STARTTLS\\r\\n\") < 0) ||\n (mutt_socket_readln(buf, sizeof(buf), conn) < 0))\n {\n return nntp_connect_error(adata);\n }\n \/\/ Clear any data after the STARTTLS acknowledgement\n mutt_socket_empty(conn);\n if (!mutt_str_startswith(buf, \"382\", CASE_MATCH))\n {\n adata->use_tls = 0;\n mutt_error(\"STARTTLS: %s\", buf);\n }\n else if (mutt_ssl_starttls(conn))\n {\n adata->use_tls = 0;\n adata->status = NNTP_NONE;\n mutt_socket_close(adata->conn);\n mutt_error(_(\"Could not negotiate TLS connection\"));\n return -1;\n }\n else\n {\n \/* recheck capabilities after STARTTLS *\/\n cap = nntp_capabilities(adata);\n if (cap < 0)\n return -1;\n }\n }\n }\n#endif\n\n \/* authentication required? *\/\n if (conn->account.flags & MUTT_ACCT_USER)\n {\n if (!conn->account.user[0])\n auth = false;\n }\n else\n {\n if ((mutt_socket_send(conn, \"STAT\\r\\n\") < 0) ||\n (mutt_socket_readln(buf, sizeof(buf), conn) < 0))\n {\n return nntp_connect_error(adata);\n }\n if (!mutt_str_startswith(buf, \"480\", CASE_MATCH))\n auth = false;\n }\n\n \/* authenticate *\/\n if (auth && (nntp_auth(adata) < 0))\n return -1;\n\n \/* get final capabilities after authentication *\/\n if (adata->hasCAPABILITIES && (auth || (cap > 0)))\n {\n cap = nntp_capabilities(adata);\n if (cap < 0)\n return -1;\n if (cap > 0)\n {\n mutt_socket_close(conn);\n mutt_error(_(\"Could not switch to reader mode\"));\n return -1;\n }\n }\n\n \/* attempt features *\/\n if (nntp_attempt_features(adata) < 0)\n return -1;\n\n adata->status = NNTP_OK;\n return 0;\n}","target":0,"code_token_length":1115,"total_token_length":1446,"max_tokens_setting":2048} +{"idx":67661,"func":"TEST_F(HttpConnectionManagerImplTest, TestSrdsCrossScopeReroute) {\n setup(false, \"\", true, true);\n\n std::shared_ptr route_config1 =\n std::make_shared>();\n std::shared_ptr route_config2 =\n std::make_shared>();\n std::shared_ptr route1 = std::make_shared>();\n std::shared_ptr route2 = std::make_shared>();\n EXPECT_CALL(*route_config1, route(_, _)).WillRepeatedly(Return(route1));\n EXPECT_CALL(*route_config2, route(_, _)).WillRepeatedly(Return(route2));\n EXPECT_CALL(*static_cast(\n scopedRouteConfigProvider()->config().get()),\n getRouteConfig(_))\n \/\/ 1. Snap scoped route config;\n \/\/ 2. refreshCachedRoute (both in decodeHeaders(headers,end_stream);\n \/\/ 3. then refreshCachedRoute triggered by decoder_filters_[1]->callbacks_->route().\n .Times(3)\n .WillRepeatedly(Invoke([&](const HeaderMap& headers) -> Router::ConfigConstSharedPtr {\n auto& test_headers = static_cast(headers);\n if (test_headers.get_(\"scope_key\") == \"foo\") {\n return route_config1;\n }\n return route_config2;\n }));\n EXPECT_CALL(*codec_, dispatch(_)).WillOnce(Invoke([&](Buffer::Instance& data) -> void {\n StreamDecoder* decoder = &conn_manager_->newStream(response_encoder_);\n HeaderMapPtr headers{new TestHeaderMapImpl{\n {\":authority\", \"host\"}, {\":method\", \"GET\"}, {\"scope_key\", \"foo\"}, {\":path\", \"\/foo\"}}};\n decoder->decodeHeaders(std::move(headers), false);\n data.drain(4);\n }));\n setupFilterChain(2, 0);\n EXPECT_CALL(*decoder_filters_[0], decodeHeaders(_, false))\n .WillOnce(Invoke([&](Http::HeaderMap& headers, bool) -> FilterHeadersStatus {\n EXPECT_EQ(route1, decoder_filters_[0]->callbacks_->route());\n auto& test_headers = static_cast(headers);\n \/\/ Clear cached route and change scope key to \"bar\".\n decoder_filters_[0]->callbacks_->clearRouteCache();\n test_headers.remove(\"scope_key\");\n test_headers.addCopy(\"scope_key\", \"bar\");\n return FilterHeadersStatus::Continue;\n }));\n EXPECT_CALL(*decoder_filters_[1], decodeHeaders(_, false))\n .WillOnce(Invoke([&](Http::HeaderMap& headers, bool) -> FilterHeadersStatus {\n auto& test_headers = static_cast(headers);\n EXPECT_EQ(test_headers.get_(\"scope_key\"), \"bar\");\n \/\/ Route now switched to route2 as header \"scope_key\" has changed.\n EXPECT_EQ(route2, decoder_filters_[1]->callbacks_->route());\n EXPECT_EQ(route2->routeEntry(), decoder_filters_[1]->callbacks_->streamInfo().routeEntry());\n return FilterHeadersStatus::StopIteration;\n }));\n\n Buffer::OwnedImpl fake_input(\"1234\");\n conn_manager_->onData(fake_input, false);\n}","target":0,"code_token_length":725,"total_token_length":1056,"max_tokens_setting":2048} +{"idx":382400,"func":"pg_stat_get_wal_senders(PG_FUNCTION_ARGS)\n{\n#define PG_STAT_GET_WAL_SENDERS_COLS\t8\n\tReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;\n\tTupleDesc\ttupdesc;\n\tTuplestorestate *tupstore;\n\tMemoryContext per_query_ctx;\n\tMemoryContext oldcontext;\n\tWalSnd\t *sync_standby;\n\tint\t\t\ti;\n\n\t\/* check to see if caller supports us returning a tuplestore *\/\n\tif (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t errmsg(\"set-valued function called in context that cannot accept a set\")));\n\tif (!(rsinfo->allowedModes & SFRM_Materialize))\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n\t\t\t\t errmsg(\"materialize mode required, but it is not \" \\\n\t\t\t\t\t\t\"allowed in this context\")));\n\n\t\/* Build a tuple descriptor for our result type *\/\n\tif (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)\n\t\telog(ERROR, \"return type must be a row type\");\n\n\tper_query_ctx = rsinfo->econtext->ecxt_per_query_memory;\n\toldcontext = MemoryContextSwitchTo(per_query_ctx);\n\n\ttupstore = tuplestore_begin_heap(true, false, work_mem);\n\trsinfo->returnMode = SFRM_Materialize;\n\trsinfo->setResult = tupstore;\n\trsinfo->setDesc = tupdesc;\n\n\tMemoryContextSwitchTo(oldcontext);\n\n\t\/*\n\t * Get the currently active synchronous standby.\n\t *\/\n\tLWLockAcquire(SyncRepLock, LW_SHARED);\n\tsync_standby = SyncRepGetSynchronousStandby();\n\tLWLockRelease(SyncRepLock);\n\n\tfor (i = 0; i < max_wal_senders; i++)\n\t{\n\t\t\/* use volatile pointer to prevent code rearrangement *\/\n\t\tvolatile WalSnd *walsnd = &WalSndCtl->walsnds[i];\n\t\tXLogRecPtr\tsentPtr;\n\t\tXLogRecPtr\twrite;\n\t\tXLogRecPtr\tflush;\n\t\tXLogRecPtr\tapply;\n\t\tint\t\t\tpriority;\n\t\tWalSndState state;\n\t\tDatum\t\tvalues[PG_STAT_GET_WAL_SENDERS_COLS];\n\t\tbool\t\tnulls[PG_STAT_GET_WAL_SENDERS_COLS];\n\n\t\tif (walsnd->pid == 0)\n\t\t\tcontinue;\n\n\t\tSpinLockAcquire(&walsnd->mutex);\n\t\tsentPtr = walsnd->sentPtr;\n\t\tstate = walsnd->state;\n\t\twrite = walsnd->write;\n\t\tflush = walsnd->flush;\n\t\tapply = walsnd->apply;\n\t\tpriority = walsnd->sync_standby_priority;\n\t\tSpinLockRelease(&walsnd->mutex);\n\n\t\tmemset(nulls, 0, sizeof(nulls));\n\t\tvalues[0] = Int32GetDatum(walsnd->pid);\n\n\t\tif (!superuser())\n\t\t{\n\t\t\t\/*\n\t\t\t * Only superusers can see details. Other users only get the pid\n\t\t\t * value to know it's a walsender, but no details.\n\t\t\t *\/\n\t\t\tMemSet(&nulls[1], true, PG_STAT_GET_WAL_SENDERS_COLS - 1);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvalues[1] = CStringGetTextDatum(WalSndGetStateString(state));\n\t\t\tvalues[2] = LSNGetDatum(sentPtr);\n\n\t\t\tif (write == 0)\n\t\t\t\tnulls[3] = true;\n\t\t\tvalues[3] = LSNGetDatum(write);\n\n\t\t\tif (flush == 0)\n\t\t\t\tnulls[4] = true;\n\t\t\tvalues[4] = LSNGetDatum(flush);\n\n\t\t\tif (apply == 0)\n\t\t\t\tnulls[5] = true;\n\t\t\tvalues[5] = LSNGetDatum(apply);\n\n\t\t\t\/*\n\t\t\t * Treat a standby such as a pg_basebackup background process\n\t\t\t * which always returns an invalid flush location, as an\n\t\t\t * asynchronous standby.\n\t\t\t *\/\n\t\t\tpriority = XLogRecPtrIsInvalid(walsnd->flush) ? 0 : priority;\n\n\t\t\tvalues[6] = Int32GetDatum(priority);\n\n\t\t\t\/*\n\t\t\t * More easily understood version of standby state. This is purely\n\t\t\t * informational, not different from priority.\n\t\t\t *\/\n\t\t\tif (priority == 0)\n\t\t\t\tvalues[7] = CStringGetTextDatum(\"async\");\n\t\t\telse if (walsnd == sync_standby)\n\t\t\t\tvalues[7] = CStringGetTextDatum(\"sync\");\n\t\t\telse\n\t\t\t\tvalues[7] = CStringGetTextDatum(\"potential\");\n\t\t}\n\n\t\ttuplestore_putvalues(tupstore, tupdesc, values, nulls);\n\t}\n\n\t\/* clean up and return the tuplestore *\/\n\ttuplestore_donestoring(tupstore);\n\n\treturn (Datum) 0;\n}","target":0,"code_token_length":1053,"total_token_length":1384,"max_tokens_setting":2048} +{"idx":17081,"func":"TEST_F ( ShortcutsBackendTest , DeleteShortcuts ) {\n InitBackend ( ) ;\n ShortcutsDatabase : : Shortcut shortcut1 ( \"BD85DBA2-8C29-49F9-84AE-48E1E90880DF\" , base : : ASCIIToUTF16 ( \"goog\" ) , MatchCoreForTesting ( \"http:\/\/www.google.com\" ) , base : : Time : : Now ( ) , 100 ) ;\n EXPECT_TRUE ( AddShortcut ( shortcut1 ) ) ;\n ShortcutsDatabase : : Shortcut shortcut2 ( \"BD85DBA2-8C29-49F9-84AE-48E1E90880E0\" , base : : ASCIIToUTF16 ( \"gle\" ) , MatchCoreForTesting ( \"http:\/\/www.google.com\" ) , base : : Time : : Now ( ) , 100 ) ;\n EXPECT_TRUE ( AddShortcut ( shortcut2 ) ) ;\n ShortcutsDatabase : : Shortcut shortcut3 ( \"BD85DBA2-8C29-49F9-84AE-48E1E90880E1\" , base : : ASCIIToUTF16 ( \"sp\" ) , MatchCoreForTesting ( \"http:\/\/www.sport.com\" ) , base : : Time : : Now ( ) , 10 ) ;\n EXPECT_TRUE ( AddShortcut ( shortcut3 ) ) ;\n ShortcutsDatabase : : Shortcut shortcut4 ( \"BD85DBA2-8C29-49F9-84AE-48E1E90880E2\" , base : : ASCIIToUTF16 ( \"mov\" ) , MatchCoreForTesting ( \"http:\/\/www.film.com\" ) , base : : Time : : Now ( ) , 10 ) ;\n EXPECT_TRUE ( AddShortcut ( shortcut4 ) ) ;\n ASSERT_EQ ( 4U , shortcuts_map ( ) . size ( ) ) ;\n EXPECT_EQ ( shortcut1 . id , shortcuts_map ( ) . find ( shortcut1 . text ) -> second . id ) ;\n EXPECT_EQ ( shortcut2 . id , shortcuts_map ( ) . find ( shortcut2 . text ) -> second . id ) ;\n EXPECT_EQ ( shortcut3 . id , shortcuts_map ( ) . find ( shortcut3 . text ) -> second . id ) ;\n EXPECT_EQ ( shortcut4 . id , shortcuts_map ( ) . find ( shortcut4 . text ) -> second . id ) ;\n EXPECT_TRUE ( DeleteShortcutsWithURL ( shortcut1 . match_core . destination_url ) ) ;\n ASSERT_EQ ( 2U , shortcuts_map ( ) . size ( ) ) ;\n EXPECT_EQ ( 0U , shortcuts_map ( ) . count ( shortcut1 . text ) ) ;\n EXPECT_EQ ( 0U , shortcuts_map ( ) . count ( shortcut2 . text ) ) ;\n const ShortcutsBackend : : ShortcutMap : : const_iterator shortcut3_iter ( shortcuts_map ( ) . find ( shortcut3 . text ) ) ;\n ASSERT_TRUE ( shortcut3_iter != shortcuts_map ( ) . end ( ) ) ;\n EXPECT_EQ ( shortcut3 . id , shortcut3_iter -> second . id ) ;\n const ShortcutsBackend : : ShortcutMap : : const_iterator shortcut4_iter ( shortcuts_map ( ) . find ( shortcut4 . text ) ) ;\n ASSERT_TRUE ( shortcut4_iter != shortcuts_map ( ) . end ( ) ) ;\n EXPECT_EQ ( shortcut4 . id , shortcut4_iter -> second . id ) ;\n ShortcutsDatabase : : ShortcutIDs deleted_ids ;\n deleted_ids . push_back ( shortcut3 . id ) ;\n deleted_ids . push_back ( shortcut4 . id ) ;\n EXPECT_TRUE ( DeleteShortcutsWithIDs ( deleted_ids ) ) ;\n ASSERT_EQ ( 0U , shortcuts_map ( ) . size ( ) ) ;\n }","target":0,"code_token_length":819,"total_token_length":1150,"max_tokens_setting":2048} +{"idx":143691,"func":"static void WritePixels(struct ngiflib_img * i, struct ngiflib_decode_context * context, const u8 * pixels, u16 n) {\n\tu16 tocopy;\t\n\tstruct ngiflib_gif * p = i->parent;\n\n\twhile(n > 0) {\n\t\ttocopy = (context->Xtogo < n) ? context->Xtogo : n;\n\t\tif(!i->gce.transparent_flag) {\n#ifndef NGIFLIB_INDEXED_ONLY\n\t\t\tif(p->mode & NGIFLIB_MODE_INDEXED) {\n#endif \/* NGIFLIB_INDEXED_ONLY *\/\n\t\t\t\tngiflib_memcpy(context->frbuff_p.p8, pixels, tocopy);\n\t\t\t\tpixels += tocopy;\n\t\t\t\tcontext->frbuff_p.p8 += tocopy;\n#ifndef NGIFLIB_INDEXED_ONLY\n\t\t\t} else {\n\t\t\t\tint j;\n\t\t\t\tfor(j = (int)tocopy; j > 0; j--) {\n\t\t\t\t\t*(context->frbuff_p.p32++) =\n\t\t\t\t\t GifIndexToTrueColor(i->palette, *pixels++);\n\t\t\t\t}\n\t\t\t}\n#endif \/* NGIFLIB_INDEXED_ONLY *\/\n\t\t} else {\n\t\t\tint j;\n#ifndef NGIFLIB_INDEXED_ONLY\n\t\t\tif(p->mode & NGIFLIB_MODE_INDEXED) {\n#endif \/* NGIFLIB_INDEXED_ONLY *\/\n\t\t\t\tfor(j = (int)tocopy; j > 0; j--) {\n\t\t\t\t\tif(*pixels != i->gce.transparent_color) *context->frbuff_p.p8 = *pixels;\n\t\t\t\t\tpixels++;\n\t\t\t\t\tcontext->frbuff_p.p8++;\n\t\t\t\t}\n#ifndef NGIFLIB_INDEXED_ONLY\n\t\t\t} else {\n\t\t\t\tfor(j = (int)tocopy; j > 0; j--) {\n\t\t\t\t\tif(*pixels != i->gce.transparent_color) {\n\t\t\t\t\t\t*context->frbuff_p.p32 = GifIndexToTrueColor(i->palette, *pixels);\n\t\t\t\t\t}\n\t\t\t\t\tpixels++;\n\t\t\t\t\tcontext->frbuff_p.p32++;\n\t\t\t\t}\n\t\t\t}\n#endif \/* NGIFLIB_INDEXED_ONLY *\/\n\t\t}\n\t\tcontext->Xtogo -= tocopy;\n\t\tif(context->Xtogo == 0) {\n\t\t\t#ifdef NGIFLIB_ENABLE_CALLBACKS\n\t\t\tif(p->line_cb) p->line_cb(p, context->line_p, context->curY);\n\t\t\t#endif \/* NGIFLIB_ENABLE_CALLBACKS *\/\n\t\t\tcontext->Xtogo = i->width;\n\t\t\tswitch(context->pass) {\n\t\t\tcase 0:\n\t\t\t\tcontext->curY++;\n\t\t\t\tbreak;\n\t\t\tcase 1:\t\/* 1st pass : every eighth row starting from 0 *\/\n\t\t\t\tcontext->curY += 8;\n\t\t\t\tbreak;\n\t\t\tcase 2:\t\/* 2nd pass : every eighth row starting from 4 *\/\n\t\t\t\tcontext->curY += 8;\n\t\t\t\tbreak;\n\t\t\tcase 3:\t\/* 3rd pass : every fourth row starting from 2 *\/\n\t\t\t\tcontext->curY += 4;\n\t\t\t\tbreak;\n\t\t\tcase 4:\t\/* 4th pass : every odd row *\/\n\t\t\t\tcontext->curY += 2;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\twhile(context->pass > 0 && context->pass < 4 &&\n\t\t\t context->curY >= p->height) {\n\t\t\t\tswitch(++context->pass) {\n\t\t\t\tcase 2:\t\/* 2nd pass : every eighth row starting from 4 *\/\n\t\t\t\t\tcontext->curY = i->posY + 4;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 3:\t\/* 3rd pass : every fourth row starting from 2 *\/\n\t\t\t\t\tcontext->curY = i->posY + 2;\n\t\t\t\t\tbreak;\n\t\t\t\tcase 4:\t\/* 4th pass : every odd row *\/\n\t\t\t\t\tcontext->curY = i->posY + 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n#ifndef NGIFLIB_INDEXED_ONLY\n\t\t\tif(p->mode & NGIFLIB_MODE_INDEXED) {\n#endif \/* NGIFLIB_INDEXED_ONLY *\/\n\t\t\t\t#ifdef NGIFLIB_ENABLE_CALLBACKS\n\t\t\t\tcontext->line_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width;\n\t\t\t\tcontext->frbuff_p.p8 = context->line_p.p8 + i->posX;\n\t\t\t\t#else\n\t\t\t\tcontext->frbuff_p.p8 = p->frbuff.p8 + (u32)context->curY*p->width + i->posX;\n\t\t\t\t#endif \/* NGIFLIB_ENABLE_CALLBACKS *\/\n#ifndef NGIFLIB_INDEXED_ONLY\n\t\t\t} else {\n\t\t\t\t#ifdef NGIFLIB_ENABLE_CALLBACKS\n\t\t\t\tcontext->line_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width;\n\t\t\t\tcontext->frbuff_p.p32 = context->line_p.p32 + i->posX;\n\t\t\t\t#else\n\t\t\t\tcontext->frbuff_p.p32 = p->frbuff.p32 + (u32)context->curY*p->width + i->posX;\n\t\t\t\t#endif \/* NGIFLIB_ENABLE_CALLBACKS *\/\n\t\t\t}\n#endif \/* NGIFLIB_INDEXED_ONLY *\/\n\t\t}\n\t\tn -= tocopy;\n\t}\n}","target":0,"code_token_length":1106,"total_token_length":1437,"max_tokens_setting":2048} +{"idx":145,"func":"static void _UTF16LEFromUnicodeWithOffsets ( UConverterFromUnicodeArgs * pArgs , UErrorCode * pErrorCode ) {\n UConverter * cnv ;\n const UChar * source ;\n char * target ;\n int32_t * offsets ;\n uint32_t targetCapacity , length , sourceIndex ;\n UChar c , trail ;\n char overflow [ 4 ] ;\n source = pArgs -> source ;\n length = ( int32_t ) ( pArgs -> sourceLimit - source ) ;\n if ( length <= 0 ) {\n return ;\n }\n cnv = pArgs -> converter ;\n if ( cnv -> fromUnicodeStatus == UCNV_NEED_TO_WRITE_BOM ) {\n static const char bom [ ] = {\n ( char ) 0xff , ( char ) 0xfe }\n ;\n ucnv_fromUWriteBytes ( cnv , bom , 2 , & pArgs -> target , pArgs -> targetLimit , & pArgs -> offsets , - 1 , pErrorCode ) ;\n cnv -> fromUnicodeStatus = 0 ;\n }\n target = pArgs -> target ;\n if ( target >= pArgs -> targetLimit ) {\n * pErrorCode = U_BUFFER_OVERFLOW_ERROR ;\n return ;\n }\n targetCapacity = ( uint32_t ) ( pArgs -> targetLimit - pArgs -> target ) ;\n offsets = pArgs -> offsets ;\n sourceIndex = 0 ;\n if ( ( c = ( UChar ) cnv -> fromUChar32 ) != 0 && U16_IS_TRAIL ( trail = * source ) && targetCapacity >= 4 ) {\n ++ source ;\n -- length ;\n target [ 0 ] = ( uint8_t ) c ;\n target [ 1 ] = ( uint8_t ) ( c >> 8 ) ;\n target [ 2 ] = ( uint8_t ) trail ;\n target [ 3 ] = ( uint8_t ) ( trail >> 8 ) ;\n target += 4 ;\n targetCapacity -= 4 ;\n if ( offsets != NULL ) {\n * offsets ++ = - 1 ;\n * offsets ++ = - 1 ;\n * offsets ++ = - 1 ;\n * offsets ++ = - 1 ;\n }\n sourceIndex = 1 ;\n cnv -> fromUChar32 = c = 0 ;\n }\n if ( c == 0 ) {\n uint32_t count = 2 * length ;\n if ( count > targetCapacity ) {\n count = targetCapacity & ~ 1 ;\n }\n targetCapacity -= count ;\n count >>= 1 ;\n length -= count ;\n if ( offsets == NULL ) {\n while ( count > 0 ) {\n c = * source ++ ;\n if ( U16_IS_SINGLE ( c ) ) {\n target [ 0 ] = ( uint8_t ) c ;\n target [ 1 ] = ( uint8_t ) ( c >> 8 ) ;\n target += 2 ;\n }\n else if ( U16_IS_SURROGATE_LEAD ( c ) && count >= 2 && U16_IS_TRAIL ( trail = * source ) ) {\n ++ source ;\n -- count ;\n target [ 0 ] = ( uint8_t ) c ;\n target [ 1 ] = ( uint8_t ) ( c >> 8 ) ;\n target [ 2 ] = ( uint8_t ) trail ;\n target [ 3 ] = ( uint8_t ) ( trail >> 8 ) ;\n target += 4 ;\n }\n else {\n break ;\n }\n -- count ;\n }\n }\n else {\n while ( count > 0 ) {\n c = * source ++ ;\n if ( U16_IS_SINGLE ( c ) ) {\n target [ 0 ] = ( uint8_t ) c ;\n target [ 1 ] = ( uint8_t ) ( c >> 8 ) ;\n target += 2 ;\n * offsets ++ = sourceIndex ;\n * offsets ++ = sourceIndex ++ ;\n }\n else if ( U16_IS_SURROGATE_LEAD ( c ) && count >= 2 && U16_IS_TRAIL ( trail = * source ) ) {\n ++ source ;\n -- count ;\n target [ 0 ] = ( uint8_t ) c ;\n target [ 1 ] = ( uint8_t ) ( c >> 8 ) ;\n target [ 2 ] = ( uint8_t ) trail ;\n target [ 3 ] = ( uint8_t ) ( trail >> 8 ) ;\n target += 4 ;\n * offsets ++ = sourceIndex ;\n * offsets ++ = sourceIndex ;\n * offsets ++ = sourceIndex ;\n * offsets ++ = sourceIndex ;\n sourceIndex += 2 ;\n }\n else {\n break ;\n }\n -- count ;\n }\n }\n if ( count == 0 ) {\n if ( length > 0 && targetCapacity > 0 ) {\n if ( U16_IS_SINGLE ( c = * source ++ ) ) {\n overflow [ 0 ] = ( char ) c ;\n overflow [ 1 ] = ( char ) ( c >> 8 ) ;\n length = 2 ;\n c = 0 ;\n }\n }\n else {\n length = 0 ;\n c = 0 ;\n }\n }\n else {\n targetCapacity += 2 * count ;\n }\n }\n else {\n length = 0 ;\n }\n if ( c != 0 ) {\n length = 0 ;\n if ( U16_IS_SURROGATE_LEAD ( c ) ) {\n if ( source < pArgs -> sourceLimit ) {\n if ( U16_IS_TRAIL ( trail = * source ) ) {\n ++ source ;\n overflow [ 0 ] = ( char ) c ;\n overflow [ 1 ] = ( char ) ( c >> 8 ) ;\n overflow [ 2 ] = ( char ) trail ;\n overflow [ 3 ] = ( char ) ( trail >> 8 ) ;\n length = 4 ;\n c = 0 ;\n }\n else {\n * pErrorCode = U_ILLEGAL_CHAR_FOUND ;\n }\n }\n else {\n }\n }\n else {\n * pErrorCode = U_ILLEGAL_CHAR_FOUND ;\n }\n cnv -> fromUChar32 = c ;\n }\n if ( length > 0 ) {\n ucnv_fromUWriteBytes ( cnv , overflow , length , & target , pArgs -> targetLimit , & offsets , sourceIndex , pErrorCode ) ;\n targetCapacity = ( uint32_t ) ( pArgs -> targetLimit - ( char * ) target ) ;\n }\n if ( U_SUCCESS ( * pErrorCode ) && source < pArgs -> sourceLimit && targetCapacity == 0 ) {\n * pErrorCode = U_BUFFER_OVERFLOW_ERROR ;\n }\n pArgs -> source = source ;\n pArgs -> target = target ;\n pArgs -> offsets = offsets ;\n }","target":1,"code_token_length":1340,"total_token_length":1671,"max_tokens_setting":2048} +{"idx":264431,"func":"replace_param(char *buf, size_t max_len, char **multiline_ptr_ptr)\n{\n\tchar *cur_pos = buf;\n\tsize_t len_used = strlen(buf);\n\tdef_t *def;\n\tchar *s, *d, *e;\n\tssize_t i;\n\tsize_t extra_braces;\n\tsize_t replacing_len;\n\tchar *next_ptr = NULL;\n\tbool found_defn = false;\n\tchar *multiline_ptr = *multiline_ptr_ptr;\n\n\twhile ((cur_pos = strchr(cur_pos, '$')) && cur_pos[1] != '\\0') {\n\t\tif ((def = find_definition(cur_pos + 1, 0, false))) {\n\t\t\tfound_defn = true;\n\t\t\textra_braces = cur_pos[1] == BOB[0] ? 2 : 0;\n\t\t\tnext_ptr = multiline_ptr;\n\n\t\t\t\/* We are in a multiline expansion, and now have another\n\t\t\t * one, so save the previous state on the multiline stack *\/\n\t\t\tif (def->multiline && multiline_ptr) {\n\t\t\t\tif (!LIST_EXISTS(multiline_stack))\n\t\t\t\t\tmultiline_stack = alloc_list(NULL, NULL);\n\t\t\t\tlist_add(multiline_stack, multiline_ptr);\n\t\t\t}\n\n\t\t\tif (def->fn) {\n\t\t\t\t\/* This is a standard definition that uses a function for the replacement text *\/\n\t\t\t\tif (def->value)\n\t\t\t\t\tFREE(def->value);\n\t\t\t\tdef->value = (*def->fn)();\n\t\t\t\tdef->value_len = strlen(def->value);\n\t\t\t}\n\n\t\t\t\/* Ensure there is enough room to replace $PARAM or ${PARAM} with value *\/\n\t\t\tif (def->multiline) {\n\t\t\t\treplacing_len = strcspn(def->value, DEF_LINE_END);\n\t\t\t\tnext_ptr = def->value + replacing_len + 1;\n\t\t\t\tmultiline_ptr = next_ptr;\n\t\t\t}\n\t\t\telse\n\t\t\t\treplacing_len = def->value_len;\n\n\t\t\tif (len_used + replacing_len - (def->name_len + 1 + extra_braces) >= max_len) {\n\t\t\t\tlog_message(LOG_INFO, \"Parameter substitution on line '%s' would exceed maximum line length\", buf);\n\t\t\t\treturn NULL;\n\t\t\t}\n\n\t\t\tif (def->name_len + 1 + extra_braces != replacing_len) {\n\t\t\t\t\/* We need to move the existing text *\/\n\t\t\t\tif (def->name_len + 1 + extra_braces < replacing_len) {\n\t\t\t\t\t\/* We are lengthening the buf text *\/\n\t\t\t\t\ts = cur_pos + strlen(cur_pos);\n\t\t\t\t\td = s - (def->name_len + 1 + extra_braces) + replacing_len;\n\t\t\t\t\te = cur_pos;\n\t\t\t\t\ti = -1;\n\t\t\t\t} else {\n\t\t\t\t\t\/* We are shortening the buf text *\/\n\t\t\t\t\ts = cur_pos + (def->name_len + 1 + extra_braces) - replacing_len;\n\t\t\t\t\td = cur_pos;\n\t\t\t\t\te = cur_pos + strlen(cur_pos);\n\t\t\t\t\ti = 1;\n\t\t\t\t}\n\n\t\t\t\tdo {\n\t\t\t\t\t*d = *s;\n\t\t\t\t\tif (s == e)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\td += i;\n\t\t\t\t\ts += i;\n\t\t\t\t} while (true);\n\n\t\t\t\tlen_used = len_used + replacing_len - (def->name_len + 1 + extra_braces);\n\t\t\t}\n\n\t\t\t\/* Now copy the replacement text *\/\n\t\t\tstrncpy(cur_pos, def->value, replacing_len);\n\n\t\t\tif (def->value[strspn(def->value, \" \\t\")] == '~')\n\t\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t\tcur_pos++;\n\t}\n\n\t\/* If we did a replacement, update the multiline_ptr *\/\n\tif (found_defn)\n\t\t*multiline_ptr_ptr = next_ptr;\n\n\treturn found_defn;\n}","target":0,"code_token_length":768,"total_token_length":1099,"max_tokens_setting":2048} +{"idx":381396,"func":"static struct connectdata *allocate_conn(struct SessionHandle *data)\n{\n struct connectdata *conn = calloc(1, sizeof(struct connectdata));\n if(!conn)\n return NULL;\n\n conn->handler = &Curl_handler_dummy; \/* Be sure we have a handler defined\n already from start to avoid NULL\n situations and checks *\/\n\n \/* and we setup a few fields in case we end up actually using this struct *\/\n\n conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD; \/* no file descriptor *\/\n conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; \/* no file descriptor *\/\n conn->tempsock[0] = CURL_SOCKET_BAD; \/* no file descriptor *\/\n conn->tempsock[1] = CURL_SOCKET_BAD; \/* no file descriptor *\/\n conn->connection_id = -1; \/* no ID *\/\n conn->port = -1; \/* unknown at this point *\/\n conn->remote_port = -1; \/* unknown *\/\n\n \/* Default protocol-independent behavior doesn't support persistent\n connections, so we set this to force-close. Protocols that support\n this need to set this to FALSE in their \"curl_do\" functions. *\/\n connclose(conn, \"Default to force-close\");\n\n \/* Store creation time to help future close decision making *\/\n conn->created = Curl_tvnow();\n\n conn->data = data; \/* Setup the association between this connection\n and the SessionHandle *\/\n\n conn->proxytype = data->set.proxytype; \/* type *\/\n\n#ifdef CURL_DISABLE_PROXY\n\n conn->bits.proxy = FALSE;\n conn->bits.httpproxy = FALSE;\n conn->bits.proxy_user_passwd = FALSE;\n conn->bits.tunnel_proxy = FALSE;\n\n#else \/* CURL_DISABLE_PROXY *\/\n\n \/* note that these two proxy bits are now just on what looks to be\n requested, they may be altered down the road *\/\n conn->bits.proxy = (data->set.str[STRING_PROXY] &&\n *data->set.str[STRING_PROXY])?TRUE:FALSE;\n conn->bits.httpproxy = (conn->bits.proxy &&\n (conn->proxytype == CURLPROXY_HTTP ||\n conn->proxytype == CURLPROXY_HTTP_1_0))?TRUE:FALSE;\n conn->bits.proxy_user_passwd =\n (NULL != data->set.str[STRING_PROXYUSERNAME])?TRUE:FALSE;\n conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy;\n\n#endif \/* CURL_DISABLE_PROXY *\/\n\n conn->bits.user_passwd = (NULL != data->set.str[STRING_USERNAME])?TRUE:FALSE;\n conn->bits.ftp_use_epsv = data->set.ftp_use_epsv;\n conn->bits.ftp_use_eprt = data->set.ftp_use_eprt;\n\n conn->verifypeer = data->set.ssl.verifypeer;\n conn->verifyhost = data->set.ssl.verifyhost;\n\n conn->ip_version = data->set.ipver;\n\n#if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \\\n defined(NTLM_WB_ENABLED)\n conn->ntlm_auth_hlpr_socket = CURL_SOCKET_BAD;\n conn->ntlm_auth_hlpr_pid = 0;\n conn->challenge_header = NULL;\n conn->response_header = NULL;\n#endif\n\n if(Curl_multi_pipeline_enabled(data->multi) &&\n !conn->master_buffer) {\n \/* Allocate master_buffer to be used for pipelining *\/\n conn->master_buffer = calloc(BUFSIZE, sizeof (char));\n if(!conn->master_buffer)\n goto error;\n }\n\n \/* Initialize the pipeline lists *\/\n conn->send_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);\n conn->recv_pipe = Curl_llist_alloc((curl_llist_dtor) llist_dtor);\n if(!conn->send_pipe || !conn->recv_pipe)\n goto error;\n\n#ifdef HAVE_GSSAPI\n conn->data_prot = PROT_CLEAR;\n#endif\n\n \/* Store the local bind parameters that will be used for this connection *\/\n if(data->set.str[STRING_DEVICE]) {\n conn->localdev = strdup(data->set.str[STRING_DEVICE]);\n if(!conn->localdev)\n goto error;\n }\n conn->localportrange = data->set.localportrange;\n conn->localport = data->set.localport;\n\n \/* the close socket stuff needs to be copied to the connection struct as\n it may live on without (this specific) SessionHandle *\/\n conn->fclosesocket = data->set.fclosesocket;\n conn->closesocket_client = data->set.closesocket_client;\n\n return conn;\n error:\n\n Curl_llist_destroy(conn->send_pipe, NULL);\n Curl_llist_destroy(conn->recv_pipe, NULL);\n\n conn->send_pipe = NULL;\n conn->recv_pipe = NULL;\n\n Curl_safefree(conn->master_buffer);\n Curl_safefree(conn->localdev);\n Curl_safefree(conn);\n return NULL;\n}","target":0,"code_token_length":1077,"total_token_length":1408,"max_tokens_setting":2048} +{"idx":470288,"func":"static void textview_write_line(TextView *textview, const gchar *str,\n\t\t\t\tCodeConverter *conv, gboolean do_quote_folding)\n{\n\tGtkTextView *text;\n\tGtkTextBuffer *buffer;\n\tGtkTextIter iter;\n\tgchar buf[BUFFSIZE];\n\tgchar *fg_color;\n\tgint quotelevel = -1, real_quotelevel = -1;\n\tgchar quote_tag_str[10];\n\n\ttext = GTK_TEXT_VIEW(textview->text);\n\tbuffer = gtk_text_view_get_buffer(text);\n\tgtk_text_buffer_get_end_iter(buffer, &iter);\n\n\tif (!conv)\n\t\tstrncpy2(buf, str, sizeof(buf));\n\telse if (conv_convert(conv, buf, sizeof(buf), str) < 0)\n\t\tconv_localetodisp(buf, sizeof(buf), str);\n\t\t\n\tstrcrchomp(buf);\n\tfg_color = NULL;\n\n\t\/* change color of quotation\n\t >, foo>, _> ... ok, , foo bar>, foo-> ... ng\n\t Up to 3 levels of quotations are detected, and each\n\t level is colored using a different color. *\/\n\tif (prefs_common.enable_color\n\t && !textview->is_attachment\n\t && line_has_quote_char(buf, prefs_common.quote_chars)) {\n\t\treal_quotelevel = get_quote_level(buf, prefs_common.quote_chars);\n\t\tquotelevel = real_quotelevel;\n\t\t\/* set up the correct foreground color *\/\n\t\tif (quotelevel > 2) {\n\t\t\t\/* recycle colors *\/\n\t\t\tif (prefs_common.recycle_quote_colors)\n\t\t\t\tquotelevel %= 3;\n\t\t\telse\n\t\t\t\tquotelevel = 2;\n\t\t}\n\t}\n\n\tif (quotelevel == -1)\n\t\tfg_color = NULL;\n\telse {\n\t\tg_snprintf(quote_tag_str, sizeof(quote_tag_str),\n\t\t\t \"quote%d\", quotelevel);\n\t\tfg_color = quote_tag_str;\n\t}\n\n\tif (prefs_common.enable_color) {\n\t\tif (textview->is_diff || textview->is_in_git_patch) {\n\t\t\tif (strncmp(buf, \"+++ \", 4) == 0)\n\t\t\t\tfg_color = \"diff-add-file\";\n\t\t\telse if (buf[0] == '+')\n\t\t\t\tfg_color = \"diff-add\";\n\t\t\telse if (strncmp(buf, \"--- \", 4) == 0)\n\t\t\t\tfg_color = \"diff-del-file\";\n\t\t\telse if (buf[0] == '-')\n\t\t\t\tfg_color = \"diff-del\";\n\t\t\telse if (strncmp(buf, \"@@ \", 3) == 0 &&\n\t\t\t\t strstr(&buf[3], \" @@\"))\n\t\t\t\tfg_color = \"diff-hunk\";\n\n\t\t\tif (account_sigsep_matchlist_nchar_found(buf, \"%s\\n\")) {\n\t\t\t\ttextview->is_in_git_patch = FALSE;\n\t\t\t\ttextview->is_in_signature = TRUE;\n\t\t\t\tfg_color = \"signature\";\n\t\t\t}\n\t\t} else if (account_sigsep_matchlist_str_found(buf, \"%s\\n\")\n\t\t\t\t|| account_sigsep_matchlist_str_found(buf, \"- %s\\n\")\n\t\t\t\t|| textview->is_in_signature) {\n\t\t\tfg_color = \"signature\";\n\t\t\ttextview->is_in_signature = TRUE;\n\t\t} else if (strncmp(buf, \"diff --git \", 11) == 0) {\n\t\t\ttextview->is_in_git_patch = TRUE;\n\t\t}\n\t}\n\n\tif (!textview->is_attachment && real_quotelevel > -1 && do_quote_folding) {\n\t\tif (!g_utf8_validate(buf, -1, NULL)) {\n\t\t\tgchar *utf8buf = NULL;\n\t\t\tutf8buf = g_malloc(BUFFSIZE);\n\t\t\tconv_localetodisp(utf8buf, BUFFSIZE, buf);\n\t\t\tstrncpy2(buf, utf8buf, BUFFSIZE-1);\n\t\t\tg_free(utf8buf);\n\t\t}\ndo_quote:\n\t\tif ( textview->prev_quote_level != real_quotelevel ) {\n\t\t\tClickableText *uri;\n\t\t\turi = g_new0(ClickableText, 1);\n\t\t\turi->uri = g_strdup(\"\");\n\t\t\turi->data = g_strdup(buf);\n\t\t\turi->data_len = strlen(uri->data);\n\t\t\turi->start = gtk_text_iter_get_offset(&iter);\n\t\t\turi->is_quote = TRUE;\n\t\t\turi->quote_level = real_quotelevel;\n\t\t\turi->fg_color = g_strdup(fg_color);\n\n\t\t\tgtk_text_buffer_insert_with_tags_by_name\n\t\t\t\t\t(buffer, &iter, \" [...]\", -1,\n\t\t\t\t\t \"qlink\", fg_color, NULL);\n\t\t\turi->end = gtk_text_iter_get_offset(&iter);\n\t\t\tgtk_text_buffer_insert(buffer, &iter, \" \\n\", -1);\n\t\t\t\n\t\t\turi->filename = NULL;\n\t\t\ttextview->uri_list =\n\t\t\t\tg_slist_prepend(textview->uri_list, uri);\n\t\t\n\t\t\ttextview->prev_quote_level = real_quotelevel;\n\t\t} else {\n\t\t\tGSList *last = textview->uri_list;\n\t\t\tClickableText *lasturi = NULL;\n\t\t\tgint e_len = 0, n_len = 0;\n\t\t\t\n\t\t\tif (textview->uri_list) {\n\t\t\t\tlasturi = (ClickableText *)last->data;\n\t\t\t} else {\n\t\t\t\tg_print(\"oops (%d %d)\\n\",\n\t\t\t\t\treal_quotelevel, textview->prev_quote_level);\n\t\t\t}\t\n\t\t\tif (lasturi) {\t\n\t\t\t\tif (lasturi->is_quote == FALSE) {\n\t\t\t\t\ttextview->prev_quote_level = -1;\n\t\t\t\t\tgoto do_quote;\n\t\t\t\t}\n\t\t\t\te_len = lasturi->data ? lasturi->data_len:0;\n\t\t\t\tn_len = strlen(buf);\n\t\t\t\tlasturi->data = g_realloc((gchar *)lasturi->data, e_len + n_len + 1);\n\t\t\t\tstrcpy((gchar *)lasturi->data + e_len, buf);\n\t\t\t\t*((gchar *)lasturi->data + e_len + n_len) = '\\0';\n\t\t\t\tlasturi->data_len += n_len;\n\t\t\t}\n\t\t}\n\t} else {\n\t\ttextview_make_clickable_parts(textview, fg_color, \"link\", buf, FALSE);\n\t\ttextview->prev_quote_level = -1;\n\t}\n}","target":0,"code_token_length":1302,"total_token_length":1633,"max_tokens_setting":2048} +{"idx":494453,"func":"flushupdates(struct interface *ifp)\n{\n babel_interface_nfo *babel_ifp = NULL;\n struct xroute *xroute;\n struct babel_route *route;\n const unsigned char *last_prefix = NULL;\n unsigned char last_plen = 0xFF;\n int i;\n\n if(ifp == NULL) {\n\tstruct vrf *vrf = vrf_lookup_by_id(VRF_DEFAULT);\n struct interface *ifp_aux;\n FOR_ALL_INTERFACES(vrf, ifp_aux)\n flushupdates(ifp_aux);\n return;\n }\n\n babel_ifp = babel_get_if_nfo(ifp);\n if(babel_ifp->num_buffered_updates > 0) {\n struct buffered_update *b = babel_ifp->buffered_updates;\n int n = babel_ifp->num_buffered_updates;\n\n babel_ifp->buffered_updates = NULL;\n babel_ifp->update_bufsize = 0;\n babel_ifp->num_buffered_updates = 0;\n\n if(!if_up(ifp))\n goto done;\n\n debugf(BABEL_DEBUG_COMMON,\" (flushing %d buffered updates on %s (%d))\",\n n, ifp->name, ifp->ifindex);\n\n \/* In order to send fewer update messages, we want to send updates\n with the same router-id together, with IPv6 going out before IPv4. *\/\n\n for(i = 0; i < n; i++) {\n route = find_installed_route(b[i].prefix, b[i].plen);\n if(route)\n memcpy(b[i].id, route->src->id, 8);\n else\n memcpy(b[i].id, myid, 8);\n }\n\n qsort(b, n, sizeof(struct buffered_update), compare_buffered_updates);\n\n for(i = 0; i < n; i++) {\n \/* The same update may be scheduled multiple times before it is\n sent out. Since our buffer is now sorted, it is enough to\n compare with the previous update. *\/\n\n if(last_prefix) {\n if(b[i].plen == last_plen &&\n memcmp(b[i].prefix, last_prefix, 16) == 0)\n continue;\n }\n\n xroute = find_xroute(b[i].prefix, b[i].plen);\n route = find_installed_route(b[i].prefix, b[i].plen);\n\n if(xroute && (!route || xroute->metric <= kernel_metric)) {\n really_send_update(ifp, myid,\n xroute->prefix, xroute->plen,\n myseqno, xroute->metric,\n NULL, 0);\n last_prefix = xroute->prefix;\n last_plen = xroute->plen;\n } else if(route) {\n unsigned char channels[DIVERSITY_HOPS];\n int chlen;\n struct interface *route_ifp = route->neigh->ifp;\n struct babel_interface *babel_route_ifp = NULL;\n unsigned short metric;\n unsigned short seqno;\n\n seqno = route->seqno;\n metric =\n route_interferes(route, ifp) ?\n route_metric(route) :\n route_metric_noninterfering(route);\n\n if(metric < INFINITY)\n satisfy_request(route->src->prefix, route->src->plen,\n seqno, route->src->id, ifp);\n if((babel_ifp->flags & BABEL_IF_SPLIT_HORIZON) &&\n route->neigh->ifp == ifp)\n continue;\n\n babel_route_ifp = babel_get_if_nfo(route_ifp);\n if(babel_route_ifp->channel ==BABEL_IF_CHANNEL_NONINTERFERING) {\n memcpy(channels, route->channels, DIVERSITY_HOPS);\n } else {\n if(babel_route_ifp->channel == BABEL_IF_CHANNEL_UNKNOWN)\n channels[0] = BABEL_IF_CHANNEL_INTERFERING;\n else {\n assert(babel_route_ifp->channel > 0 &&\n babel_route_ifp->channel <= 255);\n channels[0] = babel_route_ifp->channel;\n }\n memcpy(channels + 1, route->channels, DIVERSITY_HOPS - 1);\n }\n\n chlen = channels_len(channels);\n really_send_update(ifp, route->src->id,\n route->src->prefix,\n route->src->plen,\n seqno, metric,\n channels, chlen);\n update_source(route->src, seqno, metric);\n last_prefix = route->src->prefix;\n last_plen = route->src->plen;\n } else {\n \/* There's no route for this prefix. This can happen shortly\n after an xroute has been retracted, so send a retraction. *\/\n really_send_update(ifp, myid, b[i].prefix, b[i].plen,\n myseqno, INFINITY, NULL, -1);\n }\n }\n schedule_flush_now(ifp);\n done:\n free(b);\n }\n babel_ifp->update_flush_timeout.tv_sec = 0;\n babel_ifp->update_flush_timeout.tv_usec = 0;\n}","target":0,"code_token_length":1097,"total_token_length":1428,"max_tokens_setting":2048} +{"idx":434975,"func":"DLLEXPORT int tjDecompressToYUV2(tjhandle handle, const unsigned char *jpegBuf,\n unsigned long jpegSize, unsigned char *dstBuf,\n int width, int pad, int height, int flags)\n{\n unsigned char *dstPlanes[3];\n int pw0, ph0, strides[3], retval = -1, jpegSubsamp = -1;\n int i, jpegwidth, jpegheight, scaledw, scaledh;\n\n GET_DINSTANCE(handle);\n this->jerr.stopOnWarning = (flags & TJFLAG_STOPONWARNING) ? TRUE : FALSE;\n\n if (jpegBuf == NULL || jpegSize <= 0 || dstBuf == NULL || width < 0 ||\n pad < 1 || !IS_POW2(pad) || height < 0)\n THROW(\"tjDecompressToYUV2(): Invalid argument\");\n\n if (setjmp(this->jerr.setjmp_buffer)) {\n \/* If we get here, the JPEG code has signaled an error. *\/\n return -1;\n }\n\n jpeg_mem_src_tj(dinfo, jpegBuf, jpegSize);\n jpeg_read_header(dinfo, TRUE);\n jpegSubsamp = getSubsamp(dinfo);\n if (jpegSubsamp < 0)\n THROW(\"tjDecompressToYUV2(): Could not determine subsampling type for JPEG image\");\n\n jpegwidth = dinfo->image_width; jpegheight = dinfo->image_height;\n if (width == 0) width = jpegwidth;\n if (height == 0) height = jpegheight;\n\n for (i = 0; i < NUMSF; i++) {\n scaledw = TJSCALED(jpegwidth, sf[i]);\n scaledh = TJSCALED(jpegheight, sf[i]);\n if (scaledw <= width && scaledh <= height)\n break;\n }\n if (i >= NUMSF)\n THROW(\"tjDecompressToYUV2(): Could not scale down to desired image dimensions\");\n\n pw0 = tjPlaneWidth(0, width, jpegSubsamp);\n ph0 = tjPlaneHeight(0, height, jpegSubsamp);\n dstPlanes[0] = dstBuf;\n strides[0] = PAD(pw0, pad);\n if (jpegSubsamp == TJSAMP_GRAY) {\n strides[1] = strides[2] = 0;\n dstPlanes[1] = dstPlanes[2] = NULL;\n } else {\n int pw1 = tjPlaneWidth(1, width, jpegSubsamp);\n int ph1 = tjPlaneHeight(1, height, jpegSubsamp);\n\n strides[1] = strides[2] = PAD(pw1, pad);\n dstPlanes[1] = dstPlanes[0] + strides[0] * ph0;\n dstPlanes[2] = dstPlanes[1] + strides[1] * ph1;\n }\n\n this->headerRead = 1;\n return tjDecompressToYUVPlanes(handle, jpegBuf, jpegSize, dstPlanes, width,\n strides, height, flags);\n\nbailout:\n this->jerr.stopOnWarning = FALSE;\n return retval;\n}","target":0,"code_token_length":699,"total_token_length":1030,"max_tokens_setting":2048} +{"idx":328202,"func":"static int vpc_create(const char *filename, QEMUOptionParameter *options)\n\n{\n\n uint8_t buf[1024];\n\n struct vhd_footer *footer = (struct vhd_footer *) buf;\n\n QEMUOptionParameter *disk_type_param;\n\n int fd, i;\n\n uint16_t cyls = 0;\n\n uint8_t heads = 0;\n\n uint8_t secs_per_cyl = 0;\n\n int64_t total_sectors;\n\n int64_t total_size;\n\n int disk_type;\n\n int ret = -EIO;\n\n\n\n \/* Read out options *\/\n\n total_size = get_option_parameter(options, BLOCK_OPT_SIZE)->value.n;\n\n\n\n disk_type_param = get_option_parameter(options, BLOCK_OPT_SUBFMT);\n\n if (disk_type_param && disk_type_param->value.s) {\n\n if (!strcmp(disk_type_param->value.s, \"dynamic\")) {\n\n disk_type = VHD_DYNAMIC;\n\n } else if (!strcmp(disk_type_param->value.s, \"fixed\")) {\n\n disk_type = VHD_FIXED;\n\n } else {\n\n return -EINVAL;\n\n }\n\n } else {\n\n disk_type = VHD_DYNAMIC;\n\n }\n\n\n\n \/* Create the file *\/\n\n fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);\n\n if (fd < 0) {\n\n return -EIO;\n\n }\n\n\n\n \/*\n\n * Calculate matching total_size and geometry. Increase the number of\n\n * sectors requested until we get enough (or fail). This ensures that\n\n * qemu-img convert doesn't truncate images, but rather rounds up.\n\n *\/\n\n total_sectors = total_size \/ BDRV_SECTOR_SIZE;\n\n for (i = 0; total_sectors > (int64_t)cyls * heads * secs_per_cyl; i++) {\n\n if (calculate_geometry(total_sectors + i, &cyls, &heads,\n\n &secs_per_cyl))\n\n {\n\n ret = -EFBIG;\n\n goto fail;\n\n }\n\n }\n\n\n\n total_sectors = (int64_t) cyls * heads * secs_per_cyl;\n\n\n\n \/* Prepare the Hard Disk Footer *\/\n\n memset(buf, 0, 1024);\n\n\n\n memcpy(footer->creator, \"conectix\", 8);\n\n \/* TODO Check if \"qemu\" creator_app is ok for VPC *\/\n\n memcpy(footer->creator_app, \"qemu\", 4);\n\n memcpy(footer->creator_os, \"Wi2k\", 4);\n\n\n\n footer->features = be32_to_cpu(0x02);\n\n footer->version = be32_to_cpu(0x00010000);\n\n if (disk_type == VHD_DYNAMIC) {\n\n footer->data_offset = be64_to_cpu(HEADER_SIZE);\n\n } else {\n\n footer->data_offset = be64_to_cpu(0xFFFFFFFFFFFFFFFFULL);\n\n }\n\n footer->timestamp = be32_to_cpu(time(NULL) - VHD_TIMESTAMP_BASE);\n\n\n\n \/* Version of Virtual PC 2007 *\/\n\n footer->major = be16_to_cpu(0x0005);\n\n footer->minor = be16_to_cpu(0x0003);\n\n if (disk_type == VHD_DYNAMIC) {\n\n footer->orig_size = be64_to_cpu(total_sectors * 512);\n\n footer->size = be64_to_cpu(total_sectors * 512);\n\n } else {\n\n footer->orig_size = be64_to_cpu(total_size);\n\n footer->size = be64_to_cpu(total_size);\n\n }\n\n footer->cyls = be16_to_cpu(cyls);\n\n footer->heads = heads;\n\n footer->secs_per_cyl = secs_per_cyl;\n\n\n\n footer->type = be32_to_cpu(disk_type);\n\n\n\n \/* TODO uuid is missing *\/\n\n\n\n footer->checksum = be32_to_cpu(vpc_checksum(buf, HEADER_SIZE));\n\n\n\n if (disk_type == VHD_DYNAMIC) {\n\n ret = create_dynamic_disk(fd, buf, total_sectors);\n\n } else {\n\n ret = create_fixed_disk(fd, buf, total_size);\n\n }\n\n\n\n fail:\n\n qemu_close(fd);\n\n return ret;\n\n}\n","target":0,"code_token_length":912,"total_token_length":1243,"max_tokens_setting":2048} +{"idx":118845,"func":"GF_Err video_sample_entry_on_child_box(GF_Box *s, GF_Box *a)\n{\n\tGF_MPEGVisualSampleEntryBox *ptr = (GF_MPEGVisualSampleEntryBox *)s;\n\tswitch (a->type) {\n\tcase GF_ISOM_BOX_TYPE_ESDS:\n\t\tif (ptr->esd) ERROR_ON_DUPLICATED_BOX(a, ptr)\n\t\tptr->esd = (GF_ESDBox *)a;\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_RINF:\n\t\tif (ptr->rinf) ERROR_ON_DUPLICATED_BOX(a, ptr)\n\t\tptr->rinf = (GF_RestrictedSchemeInfoBox *) a;\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_AVCC:\n\t\tif (ptr->avc_config) ERROR_ON_DUPLICATED_BOX(a, ptr)\n\t\tptr->avc_config = (GF_AVCConfigurationBox *)a;\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_HVCC:\n\t\tif (ptr->hevc_config) ERROR_ON_DUPLICATED_BOX(a, ptr)\n\t\tptr->hevc_config = (GF_HEVCConfigurationBox *)a;\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_SVCC:\n\t\tif (ptr->svc_config) ERROR_ON_DUPLICATED_BOX(a, ptr)\n\t\tptr->svc_config = (GF_AVCConfigurationBox *)a;\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_MVCC:\n\t\tif (ptr->mvc_config) ERROR_ON_DUPLICATED_BOX(a, ptr)\n\t\tptr->mvc_config = (GF_AVCConfigurationBox *)a;\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_LHVC:\n\t\tif (ptr->lhvc_config) ERROR_ON_DUPLICATED_BOX(a, ptr)\n\t\tptr->lhvc_config = (GF_HEVCConfigurationBox *)a;\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_AV1C:\n\t\tif (ptr->av1_config) ERROR_ON_DUPLICATED_BOX(a, ptr)\n\t\tptr->av1_config = (GF_AV1ConfigurationBox *)a;\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_VPCC:\n\t\tif (ptr->vp_config) ERROR_ON_DUPLICATED_BOX(a, ptr)\n\t\tptr->vp_config = (GF_VPConfigurationBox *)a;\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_DVCC:\n\t\tif (ptr->dovi_config) ERROR_ON_DUPLICATED_BOX(a, ptr)\n\t\tptr->dovi_config = (GF_DOVIConfigurationBox*)a;\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_UUID:\n\t\tif (! memcmp(((GF_UnknownUUIDBox*)a)->uuid, GF_ISOM_IPOD_EXT, 16)) {\n\t\t\tif (ptr->ipod_ext) ERROR_ON_DUPLICATED_BOX(a, ptr)\n\t\t\tptr->ipod_ext = (GF_UnknownUUIDBox *)a;\n\t\t} else {\n\t\t\treturn GF_OK;\n\t\t}\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_D263:\n\t\tif (ptr->cfg_3gpp) ERROR_ON_DUPLICATED_BOX(a, ptr)\n\t\tptr->cfg_3gpp = (GF_3GPPConfigBox *)a;\n\t\t\/*for 3GP config, remember sample entry type in config*\/\n\t\tptr->cfg_3gpp->cfg.type = ptr->type;\n\t\tbreak;\n\n\tcase GF_ISOM_BOX_TYPE_JP2H:\n\t\tif (ptr->jp2h) ERROR_ON_DUPLICATED_BOX(a, ptr)\n\t\tptr->jp2h = (GF_J2KHeaderBox *)a;\n\t\treturn GF_OK;\n\n\tcase GF_ISOM_BOX_TYPE_PASP:\n\tcase GF_ISOM_BOX_TYPE_CLAP:\n\tcase GF_ISOM_BOX_TYPE_COLR:\n\tcase GF_ISOM_BOX_TYPE_MDCV:\n\tcase GF_ISOM_BOX_TYPE_CLLI:\n\tcase GF_ISOM_BOX_TYPE_CCST:\n\tcase GF_ISOM_BOX_TYPE_AUXI:\n\tcase GF_ISOM_BOX_TYPE_RVCC:\n\tcase GF_ISOM_BOX_TYPE_M4DS:\n\t\tif (!gf_isom_box_check_unique(s->child_boxes, a)) {\n\t\t\tERROR_ON_DUPLICATED_BOX(a, ptr)\n\t\t}\n\t\treturn GF_OK;\n\t}\n\treturn GF_OK;\n}","target":0,"code_token_length":872,"total_token_length":1203,"max_tokens_setting":2048} +{"idx":486069,"func":"check_special_mountprog(const char *spec, const char *node, const char *type, int flags,\n\t\t\tchar *extra_opts, int *status) {\n\tchar search_path[] = FS_SEARCH_PATH;\n\tchar *path, mountprog[150];\n\tstruct stat statbuf;\n\tint res;\n\n\tif (!external_allowed)\n\t\treturn 0;\n\n\tif (type == NULL || strcmp(type, \"none\") == 0)\n\t\treturn 0;\n\n\tpath = strtok(search_path, \":\");\n\twhile (path) {\n\t\tint type_opt = 0;\n\n\t\tres = snprintf(mountprog, sizeof(mountprog), \"%s\/mount.%s\",\n\t\t\t path, type);\n\t\tpath = strtok(NULL, \":\");\n\t\tif (res >= sizeof(mountprog) || res < 0)\n\t\t\tcontinue;\n\n\t\tres = stat(mountprog, &statbuf);\n\t\tif (res == -1 && errno == ENOENT && strchr(type, '.')) {\n\t\t\t\/* If type ends with \".subtype\" try without it *\/\n\t\t\t*strrchr(mountprog, '.') = '\\0';\n\t\t\ttype_opt = 1;\n\t\t\tres = stat(mountprog, &statbuf);\n\t\t}\n\t\tif (res)\n\t\t\tcontinue;\n\n\t\tif (verbose)\n\t\t\tfflush(stdout);\n\n\t\tswitch (fork()) {\n\t\tcase 0: { \/* child *\/\n\t\t\tchar *oo, *mountargs[12];\n\t\t\tint i = 0;\n\n\t\t\tif (setgid(getgid()) < 0)\n\t\t\t\tdie(EX_FAIL, _(\"mount: cannot set group id: %s\"), strerror(errno));\n\n\t\t\tif (setuid(getuid()) < 0)\n\t\t\t\tdie(EX_FAIL, _(\"mount: cannot set user id: %s\"), strerror(errno));\n\n\t\t\too = fix_opts_string (flags, extra_opts, NULL);\n\t\t\tmountargs[i++] = mountprog;\t\t\t\/* 1 *\/\n\t\t\tmountargs[i++] = (char *) spec;\t\t\t\/* 2 *\/\n\t\t\tmountargs[i++] = (char *) node;\t\t\t\/* 3 *\/\n\t\t\tif (sloppy && strncmp(type, \"nfs\", 3) == 0)\n\t\t\t\tmountargs[i++] = \"-s\";\t\t\t\/* 4 *\/\n\t\t\tif (fake)\n\t\t\t\tmountargs[i++] = \"-f\";\t\t\t\/* 5 *\/\n\t\t\tif (nomtab)\n\t\t\t\tmountargs[i++] = \"-n\";\t\t\t\/* 6 *\/\n\t\t\tif (verbose)\n\t\t\t\tmountargs[i++] = \"-v\";\t\t\t\/* 7 *\/\n\t\t\tif (oo && *oo) {\n\t\t\t\tmountargs[i++] = \"-o\";\t\t\t\/* 8 *\/\n\t\t\t\tmountargs[i++] = oo;\t\t\t\/* 9 *\/\n\t\t\t}\n\t\t\tif (type_opt) {\n\t\t\t\tmountargs[i++] = \"-t\";\t\t\t\/* 10 *\/\n\t\t\t\tmountargs[i++] = (char *) type;\t\t\/* 11 *\/\n\t\t\t}\n\t\t\tmountargs[i] = NULL;\t\t\t\t\/* 12 *\/\n\n\t\t\tif (verbose > 2) {\n\t\t\t\ti = 0;\n\t\t\t\twhile (mountargs[i]) {\n\t\t\t\t\tprintf(\"mount: external mount: argv[%d] = \\\"%s\\\"\\n\",\n\t\t\t\t\t\ti, mountargs[i]);\n\t\t\t\t\ti++;\n\t\t\t\t}\n\t\t\t\tfflush(stdout);\n\t\t\t}\n\n\t\t\texecv(mountprog, mountargs);\n\t\t\texit(1);\t\/* exec failed *\/\n\t\t}\n\n\t\tdefault: { \/* parent *\/\n\t\t\tint st;\n\t\t\twait(&st);\n\t\t\t*status = (WIFEXITED(st) ? WEXITSTATUS(st) : EX_SYSERR);\n\t\t\treturn 1;\n\t\t}\n\n\t\tcase -1: { \/* error *\/\n\t\t\tint errsv = errno;\n\t\t\terror(_(\"mount: cannot fork: %s\"), strerror(errsv));\n\t\t}\n\t\t}\n\t}\n\n\treturn 0;\n}","target":0,"code_token_length":810,"total_token_length":1141,"max_tokens_setting":2048} +{"idx":30309,"func":"static int hls_read_packet(AVFormatContext *s, AVPacket *pkt)\n\n{\n\n HLSContext *c = s->priv_data;\n\n int ret, i, minvariant = -1;\n\n\n\n if (c->first_packet) {\n\n recheck_discard_flags(s, 1);\n\n c->first_packet = 0;\n\n }\n\n\n\nstart:\n\n c->end_of_segment = 0;\n\n for (i = 0; i < c->n_variants; i++) {\n\n struct variant *var = c->variants[i];\n\n \/* Make sure we've got one buffered packet from each open variant\n\n * stream *\/\n\n if (var->needed && !var->pkt.data) {\n\n while (1) {\n\n int64_t ts_diff;\n\n AVStream *st;\n\n ret = av_read_frame(var->ctx, &var->pkt);\n\n if (ret < 0) {\n\n if (!var->pb.eof_reached)\n\n return ret;\n\n\n break;\n\n } else {\n\n if (c->first_timestamp == AV_NOPTS_VALUE &&\n\n var->pkt.dts != AV_NOPTS_VALUE)\n\n c->first_timestamp = av_rescale_q(var->pkt.dts,\n\n var->ctx->streams[var->pkt.stream_index]->time_base,\n\n AV_TIME_BASE_Q);\n\n }\n\n\n\n if (c->seek_timestamp == AV_NOPTS_VALUE)\n\n break;\n\n\n\n if (var->pkt.dts == AV_NOPTS_VALUE) {\n\n c->seek_timestamp = AV_NOPTS_VALUE;\n\n break;\n\n }\n\n\n\n st = var->ctx->streams[var->pkt.stream_index];\n\n ts_diff = av_rescale_rnd(var->pkt.dts, AV_TIME_BASE,\n\n st->time_base.den, AV_ROUND_DOWN) -\n\n c->seek_timestamp;\n\n if (ts_diff >= 0 && (c->seek_flags & AVSEEK_FLAG_ANY ||\n\n var->pkt.flags & AV_PKT_FLAG_KEY)) {\n\n c->seek_timestamp = AV_NOPTS_VALUE;\n\n break;\n\n }\n\n\n\n }\n\n }\n\n \/* Check if this stream still is on an earlier segment number, or\n\n * has the packet with the lowest dts *\/\n\n if (var->pkt.data) {\n\n struct variant *minvar = c->variants[minvariant];\n\n if (minvariant < 0 || var->cur_seq_no < minvar->cur_seq_no) {\n\n minvariant = i;\n\n } else if (var->cur_seq_no == minvar->cur_seq_no) {\n\n int64_t dts = var->pkt.dts;\n\n int64_t mindts = minvar->pkt.dts;\n\n AVStream *st = var->ctx->streams[var->pkt.stream_index];\n\n AVStream *minst = minvar->ctx->streams[minvar->pkt.stream_index];\n\n\n\n if (dts == AV_NOPTS_VALUE) {\n\n minvariant = i;\n\n } else if (mindts != AV_NOPTS_VALUE) {\n\n if (st->start_time != AV_NOPTS_VALUE)\n\n dts -= st->start_time;\n\n if (minst->start_time != AV_NOPTS_VALUE)\n\n mindts -= minst->start_time;\n\n\n\n if (av_compare_ts(dts, st->time_base,\n\n mindts, minst->time_base) < 0)\n\n minvariant = i;\n\n }\n\n }\n\n }\n\n }\n\n if (c->end_of_segment) {\n\n if (recheck_discard_flags(s, 0))\n\n goto start;\n\n }\n\n \/* If we got a packet, return it *\/\n\n if (minvariant >= 0) {\n\n *pkt = c->variants[minvariant]->pkt;\n\n pkt->stream_index += c->variants[minvariant]->stream_offset;\n\n reset_packet(&c->variants[minvariant]->pkt);\n\n return 0;\n\n }\n\n return AVERROR_EOF;\n\n}","target":1,"code_token_length":827,"total_token_length":1158,"max_tokens_setting":2048} +{"idx":155813,"func":"pixOctcubeQuantMixedWithGray(PIX *pixs,\n l_int32 depth,\n l_int32 graylevels,\n l_int32 delta)\n{\nl_int32 w, h, wpls, wpld, i, j, size, octlevels;\nl_int32 rval, gval, bval, del, val, midval;\nl_int32 *carray, *rarray, *garray, *barray;\nl_int32 *tabval;\nl_uint32 octindex;\nl_uint32 *rtab, *gtab, *btab;\nl_uint32 *lines, *lined, *datas, *datad;\nPIX *pixd;\nPIXCMAP *cmap;\n\n PROCNAME(\"pixOctcubeQuantMixedWithGray\");\n\n if (!pixs)\n return (PIX *)ERROR_PTR(\"pixs not defined\", procName, NULL);\n if (pixGetDepth(pixs) != 32)\n return (PIX *)ERROR_PTR(\"pixs not 32 bpp\", procName, NULL);\n if (graylevels < 2)\n return (PIX *)ERROR_PTR(\"invalid graylevels\", procName, NULL);\n if (depth == 4) {\n octlevels = 1;\n size = 8; \/* 2 ** 3 *\/\n if (graylevels > 8)\n return (PIX *)ERROR_PTR(\"max 8 gray levels\", procName, NULL);\n } else if (depth == 8) {\n octlevels = 2;\n size = 64; \/* 2 ** 6 *\/\n if (graylevels > 192)\n return (PIX *)ERROR_PTR(\"max 192 gray levels\", procName, NULL);\n } else {\n return (PIX *)ERROR_PTR(\"output depth not 4 or 8 bpp\", procName, NULL);\n }\n\n pixd = NULL;\n\n \/* Make octcube index tables *\/\n rtab = gtab = btab = NULL;\n makeRGBToIndexTables(octlevels, &rtab, >ab, &btab);\n\n \/* Make octcube arrays for storing points in each cube *\/\n carray = (l_int32 *)LEPT_CALLOC(size, sizeof(l_int32));\n rarray = (l_int32 *)LEPT_CALLOC(size, sizeof(l_int32));\n garray = (l_int32 *)LEPT_CALLOC(size, sizeof(l_int32));\n barray = (l_int32 *)LEPT_CALLOC(size, sizeof(l_int32));\n\n \/* Make lookup table, using computed thresholds *\/\n tabval = makeGrayQuantIndexTable(graylevels);\n if (!rtab || !gtab || !btab ||\n !carray || !rarray || !garray || !barray || !tabval) {\n L_ERROR(\"calloc fail for an array\\n\", procName);\n goto array_cleanup;\n }\n\n \/* Make colormapped output pixd *\/\n pixGetDimensions(pixs, &w, &h, NULL);\n if ((pixd = pixCreate(w, h, depth)) == NULL) {\n L_ERROR(\"pixd not made\\n\", procName);\n goto array_cleanup;\n }\n pixCopyResolution(pixd, pixs);\n pixCopyInputFormat(pixd, pixs);\n cmap = pixcmapCreate(depth);\n for (j = 0; j < size; j++) \/* reserve octcube colors *\/\n pixcmapAddColor(cmap, 1, 1, 1); \/* a color that won't be used *\/\n for (j = 0; j < graylevels; j++) { \/* set grayscale colors *\/\n val = (255 * j) \/ (graylevels - 1);\n pixcmapAddColor(cmap, val, val, val);\n }\n pixSetColormap(pixd, cmap);\n wpld = pixGetWpl(pixd);\n datad = pixGetData(pixd);\n\n \/* Go through src image: assign dest pixels to colormap values\n * and compute average colors in each occupied octcube *\/\n datas = pixGetData(pixs);\n wpls = pixGetWpl(pixs);\n for (i = 0; i < h; i++) {\n lines = datas + i * wpls;\n lined = datad + i * wpld;\n for (j = 0; j < w; j++) {\n extractRGBValues(lines[j], &rval, &gval, &bval);\n if (rval > gval) {\n if (gval > bval) { \/* r > g > b *\/\n del = rval - bval;\n midval = gval;\n } else if (rval > bval) { \/* r > b > g *\/\n del = rval - gval;\n midval = bval;\n } else { \/* b > r > g *\/\n del = bval - gval;\n midval = rval;\n }\n } else { \/* gval >= rval *\/\n if (rval > bval) { \/* g > r > b *\/\n del = gval - bval;\n midval = rval;\n } else if (gval > bval) { \/* g > b > r *\/\n del = gval - rval;\n midval = bval;\n } else { \/* b > g > r *\/\n del = bval - rval;\n midval = gval;\n }\n }\n if (del > delta) { \/* assign to color *\/\n octindex = rtab[rval] | gtab[gval] | btab[bval];\n carray[octindex]++;\n rarray[octindex] += rval;\n garray[octindex] += gval;\n barray[octindex] += bval;\n if (depth == 4)\n SET_DATA_QBIT(lined, j, octindex);\n else \/* depth == 8 *\/\n SET_DATA_BYTE(lined, j, octindex);\n } else { \/* assign to grayscale *\/\n val = size + tabval[midval];\n if (depth == 4)\n SET_DATA_QBIT(lined, j, val);\n else \/* depth == 8 *\/\n SET_DATA_BYTE(lined, j, val);\n }\n }\n }\n\n \/* Average the colors in each bin and reset the colormap *\/\n for (i = 0; i < size; i++) {\n if (carray[i] > 0) {\n rarray[i] \/= carray[i];\n garray[i] \/= carray[i];\n barray[i] \/= carray[i];\n pixcmapResetColor(cmap, i, rarray[i], garray[i], barray[i]);\n }\n }\n\narray_cleanup:\n LEPT_FREE(carray);\n LEPT_FREE(rarray);\n LEPT_FREE(garray);\n LEPT_FREE(barray);\n LEPT_FREE(rtab);\n LEPT_FREE(gtab);\n LEPT_FREE(btab);\n LEPT_FREE(tabval);\n\n return pixd;\n}","target":0,"code_token_length":1567,"total_token_length":1898,"max_tokens_setting":2048} +{"idx":522816,"func":"static COND* substitute_for_best_equal_field(THD *thd, JOIN_TAB *context_tab,\n COND *cond,\n COND_EQUAL *cond_equal,\n void *table_join_idx,\n bool do_substitution)\n{\n Item_equal *item_equal;\n COND *org_cond= cond; \/\/ Return this in case of fatal error\n\n if (cond->type() == Item::COND_ITEM)\n {\n List *cond_list= ((Item_cond*) cond)->argument_list();\n\n bool and_level= ((Item_cond*) cond)->functype() ==\n Item_func::COND_AND_FUNC;\n if (and_level)\n {\n cond_equal= &((Item_cond_and *) cond)->m_cond_equal;\n cond_list->disjoin((List *) &cond_equal->current_level);\/* remove Item_equal objects from the AND. *\/\n\n List_iterator_fast it(cond_equal->current_level); \n while ((item_equal= it++))\n {\n item_equal->sort(&compare_fields_by_table_order, table_join_idx);\n }\n }\n \n List_iterator li(*cond_list);\n Item *item;\n while ((item= li++))\n {\n Item *new_item= substitute_for_best_equal_field(thd, context_tab,\n item, cond_equal,\n table_join_idx,\n do_substitution);\n \/*\n This works OK with PS\/SP re-execution as changes are made to\n the arguments of AND\/OR items only\n *\/\n if (new_item && new_item != item)\n li.replace(new_item);\n }\n\n if (and_level)\n {\n COND *eq_cond= 0;\n List_iterator_fast it(cond_equal->current_level);\n bool false_eq_cond= FALSE;\n bool all_deleted= true;\n while ((item_equal= it++))\n {\n if (item_equal->get_extraction_flag() == DELETION_FL)\n continue;\n all_deleted= false;\n eq_cond= eliminate_item_equal(thd, eq_cond, cond_equal->upper_levels,\n item_equal);\n if (!eq_cond)\n\t{\n eq_cond= 0;\n break;\n }\n else if (eq_cond->is_bool_literal() && !eq_cond->val_bool())\n\t{\n \/*\n This occurs when eliminate_item_equal() founds that cond is\n always false and substitutes it with Item_int 0.\n Due to this, value of item_equal will be 0, so just return it.\n\t *\/\n cond= eq_cond;\n false_eq_cond= TRUE;\n break;\n }\n }\n if (eq_cond && !false_eq_cond)\n {\n \/* Insert the generated equalities before all other conditions *\/\n if (eq_cond->type() == Item::COND_ITEM)\n ((Item_cond *) cond)->add_at_head(\n ((Item_cond *) eq_cond)->argument_list());\n else\n\t{\n if (cond_list->is_empty())\n cond= eq_cond;\n else\n\t {\n \/* Do not add an equality condition if it's always true *\/ \n if (!eq_cond->is_bool_literal() &&\n cond_list->push_front(eq_cond, thd->mem_root))\n eq_cond= 0;\n }\n\t}\n }\n if (!eq_cond && !all_deleted)\n {\n \/* \n We are out of memory doing the transformation.\n This is a fatal error now. However we bail out by returning the\n original condition that we had before we started the transformation. \n\t*\/\n\tcond_list->append((List *) &cond_equal->current_level);\n }\n }\t \n }\n else if (cond->type() == Item::FUNC_ITEM && \n ((Item_func*) cond)->functype() == Item_func::MULT_EQUAL_FUNC)\n {\n item_equal= (Item_equal *) cond;\n item_equal->sort(&compare_fields_by_table_order, table_join_idx);\n cond_equal= item_equal->upper_levels;\n if (cond_equal && cond_equal->current_level.head() == item_equal)\n cond_equal= cond_equal->upper_levels;\n if (item_equal->get_extraction_flag() == DELETION_FL)\n return 0;\n cond= eliminate_item_equal(thd, 0, cond_equal, item_equal);\n return cond ? cond : org_cond;\n }\n else if (do_substitution)\n {\n while (cond_equal)\n {\n List_iterator_fast it(cond_equal->current_level);\n while((item_equal= it++))\n {\n REPLACE_EQUAL_FIELD_ARG arg= {item_equal, context_tab};\n if (!(cond= cond->transform(thd, &Item::replace_equal_field,\n (uchar *) &arg)))\n return 0;\n }\n cond_equal= cond_equal->upper_levels;\n }\n }\n return cond;\n}","target":0,"code_token_length":1030,"total_token_length":1361,"max_tokens_setting":2048} +{"idx":360703,"func":"int do_print(const char *path_p, const struct stat *st, int walk_flags, void *unused)\n{\n\tconst char *default_prefix = NULL;\n\tacl_t acl = NULL, default_acl = NULL;\n\tint error = 0;\n\n\tif (walk_flags & WALK_TREE_FAILED) {\n\t\tfprintf(stderr, \"%s: %s: %s\\n\", progname, xquote(path_p, \"\\n\\r\"),\n\t\t\tstrerror(errno));\n\t\treturn 1;\n\t}\n\n\t\/*\n\t * Symlinks can never have ACLs, so when doing a physical walk, we\n\t * skip symlinks altogether, and when doing a half-logical walk, we\n\t * skip all non-toplevel symlinks. \n\t *\/\n\tif ((walk_flags & WALK_TREE_SYMLINK) &&\n\t ((walk_flags & WALK_TREE_PHYSICAL) ||\n\t !(walk_flags & (WALK_TREE_TOPLEVEL | WALK_TREE_LOGICAL))))\n\t\treturn 0;\n\n\tif (opt_print_acl) {\n\t\tacl = acl_get_file(path_p, ACL_TYPE_ACCESS);\n\t\tif (acl == NULL && (errno == ENOSYS || errno == ENOTSUP))\n\t\t\tacl = acl_get_file_mode(path_p);\n\t\tif (acl == NULL)\n\t\t\tgoto fail;\n\t}\n\n\tif (opt_print_default_acl && S_ISDIR(st->st_mode)) {\n\t\tdefault_acl = acl_get_file(path_p, ACL_TYPE_DEFAULT);\n\t\tif (default_acl == NULL) {\n\t\t\tif (errno != ENOSYS && errno != ENOTSUP)\n\t\t\t\tgoto fail;\n\t\t} else if (acl_entries(default_acl) == 0) {\n\t\t\tacl_free(default_acl);\n\t\t\tdefault_acl = NULL;\n\t\t}\n\t}\n\n\tif (opt_skip_base &&\n\t (!acl || acl_equiv_mode(acl, NULL) == 0) && !default_acl)\n\t\treturn 0;\n\n\tif (opt_print_acl && opt_print_default_acl)\n\t\tdefault_prefix = \"default:\";\n\n\tif (opt_strip_leading_slash) {\n\t\tif (*path_p == '\/') {\n\t\t\tif (!absolute_warning) {\n\t\t\t\tfprintf(stderr, _(\"%s: Removing leading \"\n\t\t\t\t\t\"'\/' from absolute path names\\n\"),\n\t\t\t\t progname);\n\t\t\t\tabsolute_warning = 1;\n\t\t\t}\n\t\t\twhile (*path_p == '\/')\n\t\t\t\tpath_p++;\n\t\t} else if (*path_p == '.' && *(path_p+1) == '\/')\n\t\t\twhile (*++path_p == '\/')\n\t\t\t\t\/* nothing *\/ ;\n\t\tif (*path_p == '\\0')\n\t\t\tpath_p = \".\";\n\t}\n\n\tif (opt_tabular) {\n\t\tif (do_show(stdout, path_p, st, acl, default_acl) != 0)\n\t\t\tgoto fail;\n\t} else {\n\t\tif (opt_comments) {\n\t\t\tprintf(\"# file: %s\\n\", xquote(path_p, \"\\n\\r\"));\n\t\t\tprintf(\"# owner: %s\\n\",\n\t\t\t xquote(user_name(st->st_uid, opt_numeric), \" \\t\\n\\r\"));\n\t\t\tprintf(\"# group: %s\\n\",\n\t\t\t xquote(group_name(st->st_gid, opt_numeric), \" \\t\\n\\r\"));\n\t\t}\n\t\tif (acl != NULL) {\n\t\t\tchar *acl_text = acl_to_any_text(acl, NULL, '\\n',\n\t\t\t\t\t\t\t print_options);\n\t\t\tif (!acl_text)\n\t\t\t\tgoto fail;\n\t\t\tif (puts(acl_text) < 0) {\n\t\t\t\tacl_free(acl_text);\n\t\t\t\tgoto fail;\n\t\t\t}\n\t\t\tacl_free(acl_text);\n\t\t}\n\t\tif (default_acl != NULL) {\n\t\t\tchar *acl_text = acl_to_any_text(default_acl, \n\t\t\t\t\t\t\t default_prefix, '\\n',\n\t\t\t\t\t\t\t print_options);\n\t\t\tif (!acl_text)\n\t\t\t\tgoto fail;\n\t\t\tif (puts(acl_text) < 0) {\n\t\t\t\tacl_free(acl_text);\n\t\t\t\tgoto fail;\n\t\t\t}\n\t\t\tacl_free(acl_text);\n\t\t}\n\t}\n\tif (acl || default_acl || opt_comments)\n\t\tprintf(\"\\n\");\n\ncleanup:\n\tif (acl)\n\t\tacl_free(acl);\n\tif (default_acl)\n\t\tacl_free(default_acl);\n\treturn error;\n\nfail:\n\tfprintf(stderr, \"%s: %s: %s\\n\", progname, xquote(path_p, \"\\n\\r\"),\n\t\tstrerror(errno));\n\terror = -1;\n\tgoto cleanup;\n}","target":0,"code_token_length":901,"total_token_length":1232,"max_tokens_setting":2048} +{"idx":323642,"func":"static void vc1_inv_trans_4x8_c(uint8_t *dest, int linesize, DCTELEM *block)\n\n{\n\n int i;\n\n register int t1,t2,t3,t4,t5,t6,t7,t8;\n\n DCTELEM *src, *dst;\n\n const uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;\n\n\n\n src = block;\n\n dst = block;\n\n for(i = 0; i < 8; i++){\n\n t1 = 17 * (src[0] + src[2]) + 4;\n\n t2 = 17 * (src[0] - src[2]) + 4;\n\n t3 = 22 * src[1] + 10 * src[3];\n\n t4 = 22 * src[3] - 10 * src[1];\n\n\n\n dst[0] = (t1 + t3) >> 3;\n\n dst[1] = (t2 - t4) >> 3;\n\n dst[2] = (t2 + t4) >> 3;\n\n dst[3] = (t1 - t3) >> 3;\n\n\n\n src += 8;\n\n dst += 8;\n\n }\n\n\n\n src = block;\n\n for(i = 0; i < 4; i++){\n\n t1 = 12 * (src[ 0] + src[32]) + 64;\n\n t2 = 12 * (src[ 0] - src[32]) + 64;\n\n t3 = 16 * src[16] + 6 * src[48];\n\n t4 = 6 * src[16] - 16 * src[48];\n\n\n\n t5 = t1 + t3;\n\n t6 = t2 + t4;\n\n t7 = t2 - t4;\n\n t8 = t1 - t3;\n\n\n\n t1 = 16 * src[ 8] + 15 * src[24] + 9 * src[40] + 4 * src[56];\n\n t2 = 15 * src[ 8] - 4 * src[24] - 16 * src[40] - 9 * src[56];\n\n t3 = 9 * src[ 8] - 16 * src[24] + 4 * src[40] + 15 * src[56];\n\n t4 = 4 * src[ 8] - 9 * src[24] + 15 * src[40] - 16 * src[56];\n\n\n\n dest[0*linesize] = cm[dest[0*linesize] + ((t5 + t1) >> 7)];\n\n dest[1*linesize] = cm[dest[1*linesize] + ((t6 + t2) >> 7)];\n\n dest[2*linesize] = cm[dest[2*linesize] + ((t7 + t3) >> 7)];\n\n dest[3*linesize] = cm[dest[3*linesize] + ((t8 + t4) >> 7)];\n\n dest[4*linesize] = cm[dest[4*linesize] + ((t8 - t4 + 1) >> 7)];\n\n dest[5*linesize] = cm[dest[5*linesize] + ((t7 - t3 + 1) >> 7)];\n\n dest[6*linesize] = cm[dest[6*linesize] + ((t6 - t2 + 1) >> 7)];\n\n dest[7*linesize] = cm[dest[7*linesize] + ((t5 - t1 + 1) >> 7)];\n\n\n\n src ++;\n\n dest++;\n\n }\n\n}\n","target":0,"code_token_length":867,"total_token_length":1198,"max_tokens_setting":2048} +{"idx":68942,"func":"int udpv6_recvmsg(struct sock *sk, struct msghdr *msg, size_t len,\n\t\t int noblock, int flags, int *addr_len)\n{\n\tstruct ipv6_pinfo *np = inet6_sk(sk);\n\tstruct inet_sock *inet = inet_sk(sk);\n\tstruct sk_buff *skb;\n\tunsigned int ulen, copied;\n\tint peeked, off = 0;\n\tint err;\n\tint is_udplite = IS_UDPLITE(sk);\n\tbool checksum_valid = false;\n\tint is_udp4;\n\tbool slow;\n\n\tif (flags & MSG_ERRQUEUE)\n\t\treturn ipv6_recv_error(sk, msg, len, addr_len);\n\n\tif (np->rxpmtu && np->rxopt.bits.rxpmtu)\n\t\treturn ipv6_recv_rxpmtu(sk, msg, len, addr_len);\n\ntry_again:\n\tskb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),\n\t\t\t\t &peeked, &off, &err);\n\tif (!skb)\n\t\tgoto out;\n\n\tulen = skb->len - sizeof(struct udphdr);\n\tcopied = len;\n\tif (copied > ulen)\n\t\tcopied = ulen;\n\telse if (copied < ulen)\n\t\tmsg->msg_flags |= MSG_TRUNC;\n\n\tis_udp4 = (skb->protocol == htons(ETH_P_IP));\n\n\t\/*\n\t * If checksum is needed at all, try to do it while copying the\n\t * data. If the data is truncated, or if we only want a partial\n\t * coverage checksum (UDP-Lite), do it before the copy.\n\t *\/\n\n\tif (copied < ulen || UDP_SKB_CB(skb)->partial_cov) {\n\t\tchecksum_valid = !udp_lib_checksum_complete(skb);\n\t\tif (!checksum_valid)\n\t\t\tgoto csum_copy_err;\n\t}\n\n\tif (checksum_valid || skb_csum_unnecessary(skb))\n\t\terr = skb_copy_datagram_msg(skb, sizeof(struct udphdr),\n\t\t\t\t\t msg, copied);\n\telse {\n\t\terr = skb_copy_and_csum_datagram_msg(skb, sizeof(struct udphdr), msg);\n\t\tif (err == -EINVAL)\n\t\t\tgoto csum_copy_err;\n\t}\n\tif (unlikely(err)) {\n\t\ttrace_kfree_skb(skb, udpv6_recvmsg);\n\t\tif (!peeked) {\n\t\t\tatomic_inc(&sk->sk_drops);\n\t\t\tif (is_udp4)\n\t\t\t\tUDP_INC_STATS_USER(sock_net(sk),\n\t\t\t\t\t\t UDP_MIB_INERRORS,\n\t\t\t\t\t\t is_udplite);\n\t\t\telse\n\t\t\t\tUDP6_INC_STATS_USER(sock_net(sk),\n\t\t\t\t\t\t UDP_MIB_INERRORS,\n\t\t\t\t\t\t is_udplite);\n\t\t}\n\t\tgoto out_free;\n\t}\n\tif (!peeked) {\n\t\tif (is_udp4)\n\t\t\tUDP_INC_STATS_USER(sock_net(sk),\n\t\t\t\t\tUDP_MIB_INDATAGRAMS, is_udplite);\n\t\telse\n\t\t\tUDP6_INC_STATS_USER(sock_net(sk),\n\t\t\t\t\tUDP_MIB_INDATAGRAMS, is_udplite);\n\t}\n\n\tsock_recv_ts_and_drops(msg, sk, skb);\n\n\t\/* Copy the address. *\/\n\tif (msg->msg_name) {\n\t\tDECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);\n\t\tsin6->sin6_family = AF_INET6;\n\t\tsin6->sin6_port = udp_hdr(skb)->source;\n\t\tsin6->sin6_flowinfo = 0;\n\n\t\tif (is_udp4) {\n\t\t\tipv6_addr_set_v4mapped(ip_hdr(skb)->saddr,\n\t\t\t\t\t &sin6->sin6_addr);\n\t\t\tsin6->sin6_scope_id = 0;\n\t\t} else {\n\t\t\tsin6->sin6_addr = ipv6_hdr(skb)->saddr;\n\t\t\tsin6->sin6_scope_id =\n\t\t\t\tipv6_iface_scope_id(&sin6->sin6_addr,\n\t\t\t\t\t\t inet6_iif(skb));\n\t\t}\n\t\t*addr_len = sizeof(*sin6);\n\t}\n\n\tif (np->rxopt.all)\n\t\tip6_datagram_recv_common_ctl(sk, msg, skb);\n\n\tif (is_udp4) {\n\t\tif (inet->cmsg_flags)\n\t\t\tip_cmsg_recv(msg, skb);\n\t} else {\n\t\tif (np->rxopt.all)\n\t\t\tip6_datagram_recv_specific_ctl(sk, msg, skb);\n\t}\n\n\terr = copied;\n\tif (flags & MSG_TRUNC)\n\t\terr = ulen;\n\nout_free:\n\tskb_free_datagram_locked(sk, skb);\nout:\n\treturn err;\n\ncsum_copy_err:\n\tslow = lock_sock_fast(sk);\n\tif (!skb_kill_datagram(sk, skb, flags)) {\n\t\tif (is_udp4) {\n\t\t\tUDP_INC_STATS_USER(sock_net(sk),\n\t\t\t\t\tUDP_MIB_CSUMERRORS, is_udplite);\n\t\t\tUDP_INC_STATS_USER(sock_net(sk),\n\t\t\t\t\tUDP_MIB_INERRORS, is_udplite);\n\t\t} else {\n\t\t\tUDP6_INC_STATS_USER(sock_net(sk),\n\t\t\t\t\tUDP_MIB_CSUMERRORS, is_udplite);\n\t\t\tUDP6_INC_STATS_USER(sock_net(sk),\n\t\t\t\t\tUDP_MIB_INERRORS, is_udplite);\n\t\t}\n\t}\n\tunlock_sock_fast(sk, slow);\n\n\t\/* starting over for a new packet, but check if we need to yield *\/\n\tcond_resched();\n\tmsg->msg_flags &= ~MSG_TRUNC;\n\tgoto try_again;\n}","target":0,"code_token_length":1135,"total_token_length":1466,"max_tokens_setting":2048} +{"idx":217910,"func":"gst_qtdemux_do_seek (GstQTDemux * qtdemux, GstPad * pad, GstEvent * event)\n{\n gdouble rate;\n GstFormat format;\n GstSeekFlags flags;\n GstSeekType cur_type, stop_type;\n gint64 cur, stop;\n gboolean flush;\n gboolean res;\n gboolean update;\n GstSegment seeksegment;\n int i;\n\n if (event) {\n GST_DEBUG_OBJECT (qtdemux, \"doing seek with event\");\n\n gst_event_parse_seek (event, &rate, &format, &flags,\n &cur_type, &cur, &stop_type, &stop);\n\n \/* we have to have a format as the segment format. Try to convert\n * if not. *\/\n if (format != GST_FORMAT_TIME) {\n GstFormat fmt;\n\n fmt = GST_FORMAT_TIME;\n res = TRUE;\n if (cur_type != GST_SEEK_TYPE_NONE)\n res = gst_pad_query_convert (pad, format, cur, &fmt, &cur);\n if (res && stop_type != GST_SEEK_TYPE_NONE)\n res = gst_pad_query_convert (pad, format, stop, &fmt, &stop);\n if (!res)\n goto no_format;\n\n format = fmt;\n }\n } else {\n GST_DEBUG_OBJECT (qtdemux, \"doing seek without event\");\n flags = 0;\n }\n\n flush = flags & GST_SEEK_FLAG_FLUSH;\n\n GST_DEBUG_OBJECT (qtdemux, \"seek format %d\", format);\n\n \/* stop streaming, either by flushing or by pausing the task *\/\n if (flush) {\n \/* unlock upstream pull_range *\/\n gst_pad_push_event (qtdemux->sinkpad, gst_event_new_flush_start ());\n \/* make sure out loop function exits *\/\n gst_qtdemux_push_event (qtdemux, gst_event_new_flush_start ());\n } else {\n \/* non flushing seek, pause the task *\/\n gst_pad_pause_task (qtdemux->sinkpad);\n }\n\n \/* wait for streaming to finish *\/\n GST_PAD_STREAM_LOCK (qtdemux->sinkpad);\n\n \/* copy segment, we need this because we still need the old\n * segment when we close the current segment. *\/\n memcpy (&seeksegment, &qtdemux->segment, sizeof (GstSegment));\n\n if (event) {\n \/* configure the segment with the seek variables *\/\n GST_DEBUG_OBJECT (qtdemux, \"configuring seek\");\n gst_segment_set_seek (&seeksegment, rate, format, flags,\n cur_type, cur, stop_type, stop, &update);\n }\n\n \/* now do the seek, this actually never returns FALSE *\/\n res = gst_qtdemux_perform_seek (qtdemux, &seeksegment);\n\n \/* prepare for streaming again *\/\n if (flush) {\n gst_pad_push_event (qtdemux->sinkpad, gst_event_new_flush_stop ());\n gst_qtdemux_push_event (qtdemux, gst_event_new_flush_stop ());\n } else if (qtdemux->segment_running) {\n \/* we are running the current segment and doing a non-flushing seek,\n * close the segment first based on the last_stop. *\/\n GST_DEBUG_OBJECT (qtdemux, \"closing running segment %\" G_GINT64_FORMAT\n \" to %\" G_GINT64_FORMAT, qtdemux->segment.start,\n qtdemux->segment.last_stop);\n\n if (qtdemux->segment.rate >= 0) {\n \/* FIXME, rate is the product of the global rate and the (quicktime)\n * segment rate. *\/\n qtdemux->pending_newsegment = gst_event_new_new_segment (TRUE,\n qtdemux->segment.rate, qtdemux->segment.format,\n qtdemux->segment.start, qtdemux->segment.last_stop,\n qtdemux->segment.time);\n } else { \/* For Reverse Playback *\/\n guint64 stop;\n\n if ((stop = qtdemux->segment.stop) == -1)\n stop = qtdemux->segment.duration;\n \/* for reverse playback, we played from stop to last_stop. *\/\n qtdemux->pending_newsegment = gst_event_new_new_segment (TRUE,\n qtdemux->segment.rate, qtdemux->segment.format,\n qtdemux->segment.last_stop, stop, qtdemux->segment.last_stop);\n }\n }\n\n \/* commit the new segment *\/\n memcpy (&qtdemux->segment, &seeksegment, sizeof (GstSegment));\n\n if (qtdemux->segment.flags & GST_SEEK_FLAG_SEGMENT) {\n gst_element_post_message (GST_ELEMENT_CAST (qtdemux),\n gst_message_new_segment_start (GST_OBJECT_CAST (qtdemux),\n qtdemux->segment.format, qtdemux->segment.last_stop));\n }\n\n \/* restart streaming, NEWSEGMENT will be sent from the streaming\n * thread. *\/\n qtdemux->segment_running = TRUE;\n for (i = 0; i < qtdemux->n_streams; i++)\n qtdemux->streams[i]->last_ret = GST_FLOW_OK;\n\n gst_pad_start_task (qtdemux->sinkpad, (GstTaskFunction) gst_qtdemux_loop,\n qtdemux->sinkpad);\n\n GST_PAD_STREAM_UNLOCK (qtdemux->sinkpad);\n\n return TRUE;\n\n \/* ERRORS *\/\nno_format:\n {\n GST_DEBUG_OBJECT (qtdemux, \"unsupported format given, seek aborted.\");\n return FALSE;\n }\n}\n","target":0,"code_token_length":1222,"total_token_length":1553,"max_tokens_setting":2048} +{"idx":347885,"func":"nf_ct_frag6_reasm(struct frag_queue *fq, struct sk_buff *prev, struct net_device *dev)\n{\n\tstruct sk_buff *fp, *head = fq->q.fragments;\n\tint payload_len;\n\tu8 ecn;\n\n\tinet_frag_kill(&fq->q);\n\n\tWARN_ON(head == NULL);\n\tWARN_ON(head->ip_defrag_offset != 0);\n\n\tecn = ip_frag_ecn_table[fq->ecn];\n\tif (unlikely(ecn == 0xff))\n\t\treturn false;\n\n\t\/* Unfragmented part is taken from the first segment. *\/\n\tpayload_len = ((head->data - skb_network_header(head)) -\n\t\t sizeof(struct ipv6hdr) + fq->q.len -\n\t\t sizeof(struct frag_hdr));\n\tif (payload_len > IPV6_MAXPLEN) {\n\t\tnet_dbg_ratelimited(\"nf_ct_frag6_reasm: payload len = %d\\n\",\n\t\t\t\t payload_len);\n\t\treturn false;\n\t}\n\n\t\/* Head of list must not be cloned. *\/\n\tif (skb_unclone(head, GFP_ATOMIC))\n\t\treturn false;\n\n\t\/* If the first fragment is fragmented itself, we split\n\t * it to two chunks: the first with data and paged part\n\t * and the second, holding only fragments. *\/\n\tif (skb_has_frag_list(head)) {\n\t\tstruct sk_buff *clone;\n\t\tint i, plen = 0;\n\n\t\tclone = alloc_skb(0, GFP_ATOMIC);\n\t\tif (clone == NULL)\n\t\t\treturn false;\n\n\t\tclone->next = head->next;\n\t\thead->next = clone;\n\t\tskb_shinfo(clone)->frag_list = skb_shinfo(head)->frag_list;\n\t\tskb_frag_list_init(head);\n\t\tfor (i = 0; i < skb_shinfo(head)->nr_frags; i++)\n\t\t\tplen += skb_frag_size(&skb_shinfo(head)->frags[i]);\n\t\tclone->len = clone->data_len = head->data_len - plen;\n\t\thead->data_len -= clone->len;\n\t\thead->len -= clone->len;\n\t\tclone->csum = 0;\n\t\tclone->ip_summed = head->ip_summed;\n\n\t\tadd_frag_mem_limit(fq->q.net, clone->truesize);\n\t}\n\n\t\/* morph head into last received skb: prev.\n\t *\n\t * This allows callers of ipv6 conntrack defrag to continue\n\t * to use the last skb(frag) passed into the reasm engine.\n\t * The last skb frag 'silently' turns into the full reassembled skb.\n\t *\n\t * Since prev is also part of q->fragments we have to clone it first.\n\t *\/\n\tif (head != prev) {\n\t\tstruct sk_buff *iter;\n\n\t\tfp = skb_clone(prev, GFP_ATOMIC);\n\t\tif (!fp)\n\t\t\treturn false;\n\n\t\tfp->next = prev->next;\n\n\t\titer = head;\n\t\twhile (iter) {\n\t\t\tif (iter->next == prev) {\n\t\t\t\titer->next = fp;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\titer = iter->next;\n\t\t}\n\n\t\tskb_morph(prev, head);\n\t\tprev->next = head->next;\n\t\tconsume_skb(head);\n\t\thead = prev;\n\t}\n\n\t\/* We have to remove fragment header from datagram and to relocate\n\t * header in order to calculate ICV correctly. *\/\n\tskb_network_header(head)[fq->nhoffset] = skb_transport_header(head)[0];\n\tmemmove(head->head + sizeof(struct frag_hdr), head->head,\n\t\t(head->data - head->head) - sizeof(struct frag_hdr));\n\thead->mac_header += sizeof(struct frag_hdr);\n\thead->network_header += sizeof(struct frag_hdr);\n\n\tskb_shinfo(head)->frag_list = head->next;\n\tskb_reset_transport_header(head);\n\tskb_push(head, head->data - skb_network_header(head));\n\n\tfor (fp = head->next; fp; fp = fp->next) {\n\t\thead->data_len += fp->len;\n\t\thead->len += fp->len;\n\t\tif (head->ip_summed != fp->ip_summed)\n\t\t\thead->ip_summed = CHECKSUM_NONE;\n\t\telse if (head->ip_summed == CHECKSUM_COMPLETE)\n\t\t\thead->csum = csum_add(head->csum, fp->csum);\n\t\thead->truesize += fp->truesize;\n\t}\n\tsub_frag_mem_limit(fq->q.net, head->truesize);\n\n\thead->ignore_df = 1;\n\thead->next = NULL;\n\thead->dev = dev;\n\thead->tstamp = fq->q.stamp;\n\tipv6_hdr(head)->payload_len = htons(payload_len);\n\tipv6_change_dsfield(ipv6_hdr(head), 0xff, ecn);\n\tIP6CB(head)->frag_max_size = sizeof(struct ipv6hdr) + fq->q.max_size;\n\n\t\/* Yes, and fold redundant checksum back. 8) *\/\n\tif (head->ip_summed == CHECKSUM_COMPLETE)\n\t\thead->csum = csum_partial(skb_network_header(head),\n\t\t\t\t\t skb_network_header_len(head),\n\t\t\t\t\t head->csum);\n\n\tfq->q.fragments = NULL;\n\tfq->q.rb_fragments = RB_ROOT;\n\tfq->q.fragments_tail = NULL;\n\n\treturn true;\n}","target":1,"code_token_length":1104,"total_token_length":1435,"max_tokens_setting":2048} +{"idx":218844,"func":"AccessibilityRole AXNodeObject::nativeAccessibilityRoleIgnoringAria() const {\n if (!getNode())\n return UnknownRole;\n\n if (getNode()->isLink())\n return LinkRole;\n\n if (isHTMLAnchorElement(*getNode())) {\n if (isClickable())\n return LinkRole;\n return AnchorRole;\n }\n\n if (isHTMLButtonElement(*getNode()))\n return buttonRoleType();\n\n if (isHTMLDetailsElement(*getNode()))\n return DetailsRole;\n\n if (isHTMLSummaryElement(*getNode())) {\n ContainerNode* parent = FlatTreeTraversal::parent(*getNode());\n if (parent && isHTMLDetailsElement(parent))\n return DisclosureTriangleRole;\n return UnknownRole;\n }\n\n if (isHTMLInputElement(*getNode())) {\n HTMLInputElement& input = toHTMLInputElement(*getNode());\n const AtomicString& type = input.type();\n if (input.dataList())\n return ComboBoxRole;\n if (type == InputTypeNames::button) {\n if ((getNode()->parentNode() &&\n isHTMLMenuElement(getNode()->parentNode())) ||\n (parentObject() && parentObject()->roleValue() == MenuRole))\n return MenuItemRole;\n return buttonRoleType();\n }\n if (type == InputTypeNames::checkbox) {\n if ((getNode()->parentNode() &&\n isHTMLMenuElement(getNode()->parentNode())) ||\n (parentObject() && parentObject()->roleValue() == MenuRole))\n return MenuItemCheckBoxRole;\n return CheckBoxRole;\n }\n if (type == InputTypeNames::date)\n return DateRole;\n if (type == InputTypeNames::datetime ||\n type == InputTypeNames::datetime_local ||\n type == InputTypeNames::month || type == InputTypeNames::week)\n return DateTimeRole;\n if (type == InputTypeNames::file)\n return ButtonRole;\n if (type == InputTypeNames::radio) {\n if ((getNode()->parentNode() &&\n isHTMLMenuElement(getNode()->parentNode())) ||\n (parentObject() && parentObject()->roleValue() == MenuRole))\n return MenuItemRadioRole;\n return RadioButtonRole;\n }\n if (type == InputTypeNames::number)\n return SpinButtonRole;\n if (input.isTextButton())\n return buttonRoleType();\n if (type == InputTypeNames::range)\n return SliderRole;\n if (type == InputTypeNames::color)\n return ColorWellRole;\n if (type == InputTypeNames::time)\n return InputTimeRole;\n return TextFieldRole;\n }\n\n if (isHTMLSelectElement(*getNode())) {\n HTMLSelectElement& selectElement = toHTMLSelectElement(*getNode());\n return selectElement.isMultiple() ? ListBoxRole : PopUpButtonRole;\n }\n\n if (isHTMLTextAreaElement(*getNode()))\n return TextFieldRole;\n\n if (headingLevel())\n return HeadingRole;\n\n if (isHTMLDivElement(*getNode()))\n return DivRole;\n\n if (isHTMLMeterElement(*getNode()))\n return MeterRole;\n\n if (isHTMLOutputElement(*getNode()))\n return StatusRole;\n\n if (isHTMLParagraphElement(*getNode()))\n return ParagraphRole;\n\n if (isHTMLLabelElement(*getNode()))\n return LabelRole;\n\n if (isHTMLLegendElement(*getNode()))\n return LegendRole;\n\n if (isHTMLRubyElement(*getNode()))\n return RubyRole;\n\n if (isHTMLDListElement(*getNode()))\n return DescriptionListRole;\n\n if (isHTMLAudioElement(*getNode()))\n return AudioRole;\n if (isHTMLVideoElement(*getNode()))\n return VideoRole;\n\n if (getNode()->hasTagName(ddTag))\n return DescriptionListDetailRole;\n\n if (getNode()->hasTagName(dtTag))\n return DescriptionListTermRole;\n\n if (getNode()->nodeName() == \"math\")\n return MathRole;\n\n if (getNode()->hasTagName(rpTag) || getNode()->hasTagName(rtTag))\n return AnnotationRole;\n\n if (isHTMLFormElement(*getNode()))\n return FormRole;\n\n if (getNode()->hasTagName(abbrTag))\n return AbbrRole;\n\n if (getNode()->hasTagName(articleTag))\n return ArticleRole;\n\n if (getNode()->hasTagName(mainTag))\n return MainRole;\n\n if (getNode()->hasTagName(markTag))\n return MarkRole;\n\n if (getNode()->hasTagName(navTag))\n return NavigationRole;\n\n if (getNode()->hasTagName(asideTag))\n return ComplementaryRole;\n\n if (getNode()->hasTagName(preTag))\n return PreRole;\n\n if (getNode()->hasTagName(sectionTag))\n return RegionRole;\n\n if (getNode()->hasTagName(addressTag))\n return ContentInfoRole;\n\n if (isHTMLDialogElement(*getNode()))\n return DialogRole;\n\n if (isHTMLHtmlElement(*getNode()))\n return IgnoredRole;\n\n if (isHTMLIFrameElement(*getNode())) {\n const AtomicString& ariaRole =\n getAOMPropertyOrARIAAttribute(AOMStringProperty::kRole);\n if (ariaRole == \"none\" || ariaRole == \"presentation\")\n return IframePresentationalRole;\n return IframeRole;\n }\n\n if (getNode()->hasTagName(headerTag)) {\n if (isDescendantOfElementType(getLandmarkRolesNotAllowed()))\n return GroupRole;\n return BannerRole;\n }\n\n if (getNode()->hasTagName(footerTag)) {\n if (isDescendantOfElementType(getLandmarkRolesNotAllowed()))\n return GroupRole;\n return FooterRole;\n }\n\n if (getNode()->hasTagName(blockquoteTag))\n return BlockquoteRole;\n\n if (getNode()->hasTagName(captionTag))\n return CaptionRole;\n\n if (getNode()->hasTagName(figcaptionTag))\n return FigcaptionRole;\n\n if (getNode()->hasTagName(figureTag))\n return FigureRole;\n\n if (getNode()->nodeName() == \"TIME\")\n return TimeRole;\n\n if (isEmbeddedObject())\n return EmbeddedObjectRole;\n\n if (isHTMLHRElement(*getNode()))\n return SplitterRole;\n\n if (isFieldset())\n return GroupRole;\n\n return UnknownRole;\n}\n","target":0,"code_token_length":1292,"total_token_length":1623,"max_tokens_setting":2048} +{"idx":236987,"func":"void RenderFrameHostManager::CommitPending() {\n TRACE_EVENT1(\"navigation\", \"RenderFrameHostManager::CommitPending\",\n \"FrameTreeNode id\", frame_tree_node_->frame_tree_node_id());\n DCHECK(pending_render_frame_host_ || speculative_render_frame_host_);\n\n bool is_main_frame = frame_tree_node_->IsMainFrame();\n\n bool will_focus_location_bar =\n is_main_frame && delegate_->FocusLocationBarByDefault();\n\n bool focus_render_view = !will_focus_location_bar &&\n render_frame_host_->GetView() &&\n render_frame_host_->GetView()->HasFocus();\n\n frame_tree_node_->ResetForNewProcess();\n\n std::unique_ptr old_render_frame_host;\n if (!IsBrowserSideNavigationEnabled()) {\n DCHECK(!speculative_render_frame_host_);\n old_render_frame_host =\n SetRenderFrameHost(std::move(pending_render_frame_host_));\n } else {\n DCHECK(speculative_render_frame_host_);\n old_render_frame_host =\n SetRenderFrameHost(std::move(speculative_render_frame_host_));\n }\n\n SkColor old_background_color = SK_ColorWHITE;\n bool has_old_background_color = false;\n if (old_render_frame_host->GetView()) {\n has_old_background_color = true;\n old_background_color = old_render_frame_host->GetView()->background_color();\n }\n\n bool new_rfh_has_view = !!render_frame_host_->GetView();\n if (!delegate_->IsHidden() && new_rfh_has_view) {\n render_frame_host_->GetView()->Show();\n }\n render_frame_host_->GetProcess()->RemovePendingView();\n\n if (!new_rfh_has_view) {\n DCHECK(!render_frame_host_->IsRenderFrameLive());\n DCHECK(!render_frame_host_->render_view_host()->IsRenderViewLive());\n render_frame_host_->ResetLoadingState();\n delegate_->RenderProcessGoneFromRenderManager(\n render_frame_host_->render_view_host());\n }\n\n if (is_main_frame &&\n old_render_frame_host->render_view_host()->GetWidget()->GetView()) {\n old_render_frame_host->render_view_host()->GetWidget()->GetView()->Hide();\n }\n\n delegate_->UpdateRenderViewSizeForRenderManager();\n\n if (will_focus_location_bar) {\n delegate_->SetFocusToLocationBar(false);\n } else if (focus_render_view && render_frame_host_->GetView()) {\n if (is_main_frame) {\n render_frame_host_->GetView()->Focus();\n } else {\n frame_tree_node_->frame_tree()->SetPageFocus(\n render_frame_host_->GetSiteInstance(), true);\n }\n }\n\n delegate_->NotifySwappedFromRenderManager(\n old_render_frame_host.get(), render_frame_host_.get(), is_main_frame);\n\n if (has_old_background_color && render_frame_host_->GetView())\n render_frame_host_->GetView()->SetBackgroundColor(old_background_color);\n\n if (is_main_frame) {\n RenderViewHostImpl* rvh = render_frame_host_->render_view_host();\n rvh->set_main_frame_routing_id(render_frame_host_->routing_id());\n\n if (!rvh->is_active())\n rvh->PostRenderViewReady();\n\n rvh->set_is_active(true);\n rvh->set_is_swapped_out(false);\n old_render_frame_host->render_view_host()->set_main_frame_routing_id(\n MSG_ROUTING_NONE);\n }\n\n SwapOutOldFrame(std::move(old_render_frame_host));\n\n DeleteRenderFrameProxyHost(render_frame_host_->GetSiteInstance());\n\n RenderFrameProxyHost* proxy_to_parent = GetProxyToParent();\n if (proxy_to_parent) {\n CHECK(SiteIsolationPolicy::AreCrossProcessFramesPossible());\n proxy_to_parent->SetChildRWHView(render_frame_host_->GetView());\n }\n\n CHECK(!GetRenderFrameProxyHost(render_frame_host_->GetSiteInstance()));\n}\n","target":0,"code_token_length":802,"total_token_length":1133,"max_tokens_setting":2048} +{"idx":516180,"func":"int ssl_verify_cert_chain(SSL *s, STACK_OF(X509) *sk)\n{\n X509 *x;\n int i = 0;\n X509_STORE *verify_store;\n X509_STORE_CTX *ctx = NULL;\n X509_VERIFY_PARAM *param;\n\n if ((sk == NULL) || (sk_X509_num(sk) == 0))\n return 0;\n\n if (s->cert->verify_store)\n verify_store = s->cert->verify_store;\n else\n verify_store = s->ctx->cert_store;\n\n ctx = X509_STORE_CTX_new_ex(s->ctx->libctx, s->ctx->propq);\n if (ctx == NULL) {\n ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);\n return 0;\n }\n\n x = sk_X509_value(sk, 0);\n if (!X509_STORE_CTX_init(ctx, verify_store, x, sk)) {\n ERR_raise(ERR_LIB_SSL, ERR_R_X509_LIB);\n goto end;\n }\n param = X509_STORE_CTX_get0_param(ctx);\n \/*\n * XXX: Separate @AUTHSECLEVEL and @TLSSECLEVEL would be useful at some\n * point, for now a single @SECLEVEL sets the same policy for TLS crypto\n * and PKI authentication.\n *\/\n X509_VERIFY_PARAM_set_auth_level(param, SSL_get_security_level(s));\n\n \/* Set suite B flags if needed *\/\n X509_STORE_CTX_set_flags(ctx, tls1_suiteb(s));\n if (!X509_STORE_CTX_set_ex_data\n (ctx, SSL_get_ex_data_X509_STORE_CTX_idx(), s)) {\n goto end;\n }\n\n \/* Verify via DANE if enabled *\/\n if (DANETLS_ENABLED(&s->dane))\n X509_STORE_CTX_set0_dane(ctx, &s->dane);\n\n \/*\n * We need to inherit the verify parameters. These can be determined by\n * the context: if its a server it will verify SSL client certificates or\n * vice versa.\n *\/\n\n X509_STORE_CTX_set_default(ctx, s->server ? \"ssl_client\" : \"ssl_server\");\n \/*\n * Anything non-default in \"s->param\" should overwrite anything in the ctx.\n *\/\n X509_VERIFY_PARAM_set1(param, s->param);\n\n if (s->verify_callback)\n X509_STORE_CTX_set_verify_cb(ctx, s->verify_callback);\n\n if (s->ctx->app_verify_callback != NULL) {\n i = s->ctx->app_verify_callback(ctx, s->ctx->app_verify_arg);\n } else {\n i = X509_verify_cert(ctx);\n \/* We treat an error in the same way as a failure to verify *\/\n if (i < 0)\n i = 0;\n }\n\n s->verify_result = X509_STORE_CTX_get_error(ctx);\n sk_X509_pop_free(s->verified_chain, X509_free);\n s->verified_chain = NULL;\n if (X509_STORE_CTX_get0_chain(ctx) != NULL) {\n s->verified_chain = X509_STORE_CTX_get1_chain(ctx);\n if (s->verified_chain == NULL) {\n ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);\n i = 0;\n }\n }\n\n \/* Move peername from the store context params to the SSL handle's *\/\n X509_VERIFY_PARAM_move_peername(s->param, param);\n\n end:\n X509_STORE_CTX_free(ctx);\n return i;\n}","target":0,"code_token_length":794,"total_token_length":1125,"max_tokens_setting":2048} +{"idx":57987,"func":"_rdpdr_check_fds(fd_set * rfds, fd_set * wfds, RD_BOOL timed_out)\n{\n\tRD_NTSTATUS status;\n\tuint32 result = 0;\n\tDEVICE_FNS *fns;\n\tstruct async_iorequest *iorq;\n\tstruct async_iorequest *prev;\n\tuint32 req_size = 0;\n\tuint32 buffer_len;\n\tstruct stream out;\n\tuint8 *buffer = NULL;\n\n\n\tif (timed_out)\n\t{\n\t\t\/* check serial iv_timeout *\/\n\n\t\tiorq = g_iorequest;\n\t\tprev = NULL;\n\t\twhile (iorq != NULL)\n\t\t{\n\t\t\tif (iorq->fd == g_min_timeout_fd)\n\t\t\t{\n\t\t\t\tif ((iorq->partial_len > 0) &&\n\t\t\t\t (g_rdpdr_device[iorq->device].device_type ==\n\t\t\t\t DEVICE_TYPE_SERIAL))\n\t\t\t\t{\n\n\t\t\t\t\t\/* iv_timeout between 2 chars, send partial_len *\/\n\t\t\t\t\t\/*printf(\"RDPDR: IVT total %u bytes read of %u\\n\", iorq->partial_len, iorq->length); *\/\n\t\t\t\t\trdpdr_send_completion(iorq->device,\n\t\t\t\t\t\t\t iorq->id, RD_STATUS_SUCCESS,\n\t\t\t\t\t\t\t iorq->partial_len,\n\t\t\t\t\t\t\t iorq->buffer, iorq->partial_len);\n\t\t\t\t\tiorq = rdpdr_remove_iorequest(prev, iorq);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tbreak;\n\t\t\t}\n\n\n\t\t\tprev = iorq;\n\t\t\tif (iorq)\n\t\t\t\tiorq = iorq->next;\n\n\t\t}\n\n\t\trdpdr_abort_io(g_min_timeout_fd, 0, RD_STATUS_TIMEOUT);\n\t\treturn;\n\t}\n\n\tiorq = g_iorequest;\n\tprev = NULL;\n\twhile (iorq != NULL)\n\t{\n\t\tif (iorq->fd != 0)\n\t\t{\n\t\t\tswitch (iorq->major)\n\t\t\t{\n\t\t\t\tcase IRP_MJ_READ:\n\t\t\t\t\tif (FD_ISSET(iorq->fd, rfds))\n\t\t\t\t\t{\n\t\t\t\t\t\t\/* Read the data *\/\n\t\t\t\t\t\tfns = iorq->fns;\n\n\t\t\t\t\t\treq_size =\n\t\t\t\t\t\t\t(iorq->length - iorq->partial_len) >\n\t\t\t\t\t\t\t8192 ? 8192 : (iorq->length -\n\t\t\t\t\t\t\t\t iorq->partial_len);\n\t\t\t\t\t\t\/* never read larger chunks than 8k - chances are that it will block *\/\n\t\t\t\t\t\tstatus = fns->read(iorq->fd,\n\t\t\t\t\t\t\t\t iorq->buffer + iorq->partial_len,\n\t\t\t\t\t\t\t\t req_size, iorq->offset, &result);\n\n\t\t\t\t\t\tif ((long) result > 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tiorq->partial_len += result;\n\t\t\t\t\t\t\tiorq->offset += result;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlogger(Protocol, Debug,\n\t\t\t\t\t\t \"_rdpdr_check_fds(), %d bytes of data read\",\n\t\t\t\t\t\t result);\n\n\t\t\t\t\t\t\/* only delete link if all data has been transfered *\/\n\t\t\t\t\t\t\/* or if result was 0 and status success - EOF *\/\n\t\t\t\t\t\tif ((iorq->partial_len == iorq->length) ||\n\t\t\t\t\t\t (result == 0))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlogger(Protocol, Debug,\n\t\t\t\t\t\t\t \"_rdpdr_check_fds(), AIO total %u bytes read of %u\",\n\t\t\t\t\t\t\t iorq->partial_len, iorq->length);\n\t\t\t\t\t\t\trdpdr_send_completion(iorq->device,\n\t\t\t\t\t\t\t\t\t iorq->id, status,\n\t\t\t\t\t\t\t\t\t iorq->partial_len,\n\t\t\t\t\t\t\t\t\t iorq->buffer,\n\t\t\t\t\t\t\t\t\t iorq->partial_len);\n\t\t\t\t\t\t\tiorq = rdpdr_remove_iorequest(prev, iorq);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase IRP_MJ_WRITE:\n\t\t\t\t\tif (FD_ISSET(iorq->fd, wfds))\n\t\t\t\t\t{\n\t\t\t\t\t\t\/* Write data. *\/\n\t\t\t\t\t\tfns = iorq->fns;\n\n\t\t\t\t\t\treq_size =\n\t\t\t\t\t\t\t(iorq->length - iorq->partial_len) >\n\t\t\t\t\t\t\t8192 ? 8192 : (iorq->length -\n\t\t\t\t\t\t\t\t iorq->partial_len);\n\n\t\t\t\t\t\t\/* never write larger chunks than 8k - chances are that it will block *\/\n\t\t\t\t\t\tstatus = fns->write(iorq->fd,\n\t\t\t\t\t\t\t\t iorq->buffer +\n\t\t\t\t\t\t\t\t iorq->partial_len, req_size,\n\t\t\t\t\t\t\t\t iorq->offset, &result);\n\n\t\t\t\t\t\tif ((long) result > 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tiorq->partial_len += result;\n\t\t\t\t\t\t\tiorq->offset += result;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tlogger(Protocol, Debug,\n\t\t\t\t\t\t \"_rdpdr_check_fds(), %d bytes of data written\",\n\t\t\t\t\t\t result);\n\n\t\t\t\t\t\t\/* only delete link if all data has been transfered *\/\n\t\t\t\t\t\t\/* or we couldn't write *\/\n\t\t\t\t\t\tif ((iorq->partial_len == iorq->length)\n\t\t\t\t\t\t || (result == 0))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tlogger(Protocol, Debug,\n\t\t\t\t\t\t\t \"_rdpdr_check_fds(), AIO total %u bytes written of %u\",\n\t\t\t\t\t\t\t iorq->partial_len, iorq->length);\n\t\t\t\t\t\t\trdpdr_send_completion(iorq->device,\n\t\t\t\t\t\t\t\t\t iorq->id, status,\n\t\t\t\t\t\t\t\t\t iorq->partial_len,\n\t\t\t\t\t\t\t\t\t (uint8 *) \"\", 1);\n\n\t\t\t\t\t\t\tiorq = rdpdr_remove_iorequest(prev, iorq);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase IRP_MJ_DEVICE_CONTROL:\n\t\t\t\t\tif (serial_get_event(iorq->fd, &result))\n\t\t\t\t\t{\n\t\t\t\t\t\tbuffer = (uint8 *) xrealloc((void *) buffer, 0x14);\n\t\t\t\t\t\tout.data = out.p = buffer;\n\t\t\t\t\t\tout.size = sizeof(buffer);\n\t\t\t\t\t\tout_uint32_le(&out, result);\n\t\t\t\t\t\tresult = buffer_len = out.p - out.data;\n\t\t\t\t\t\tstatus = RD_STATUS_SUCCESS;\n\t\t\t\t\t\trdpdr_send_completion(iorq->device, iorq->id,\n\t\t\t\t\t\t\t\t status, result, buffer,\n\t\t\t\t\t\t\t\t buffer_len);\n\t\t\t\t\t\txfree(buffer);\n\t\t\t\t\t\tiorq = rdpdr_remove_iorequest(prev, iorq);\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t}\n\t\tprev = iorq;\n\t\tif (iorq)\n\t\t\tiorq = iorq->next;\n\t}\n\n\t\/* Check notify *\/\n\tiorq = g_iorequest;\n\tprev = NULL;\n\twhile (iorq != NULL)\n\t{\n\t\tif (iorq->fd != 0)\n\t\t{\n\t\t\tswitch (iorq->major)\n\t\t\t{\n\n\t\t\t\tcase IRP_MJ_DIRECTORY_CONTROL:\n\t\t\t\t\tif (g_rdpdr_device[iorq->device].device_type ==\n\t\t\t\t\t DEVICE_TYPE_DISK)\n\t\t\t\t\t{\n\n\t\t\t\t\t\tif (g_notify_stamp)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tg_notify_stamp = False;\n\t\t\t\t\t\t\tstatus = disk_check_notify(iorq->fd);\n\t\t\t\t\t\t\tif (status != RD_STATUS_PENDING)\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\trdpdr_send_completion(iorq->device,\n\t\t\t\t\t\t\t\t\t\t iorq->id,\n\t\t\t\t\t\t\t\t\t\t status, 0,\n\t\t\t\t\t\t\t\t\t\t NULL, 0);\n\t\t\t\t\t\t\t\tiorq = rdpdr_remove_iorequest(prev,\n\t\t\t\t\t\t\t\t\t\t\t iorq);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\n\n\n\t\t\t}\n\t\t}\n\n\t\tprev = iorq;\n\t\tif (iorq)\n\t\t\tiorq = iorq->next;\n\t}\n\n}","target":0,"code_token_length":1603,"total_token_length":1934,"max_tokens_setting":2048} +{"idx":347162,"func":"static int jpc_dec_process_siz(jpc_dec_t *dec, jpc_ms_t *ms)\n{\n\tjpc_siz_t *siz = &ms->parms.siz;\n\tint compno;\n\tint tileno;\n\tjpc_dec_tile_t *tile;\n\tjpc_dec_tcomp_t *tcomp;\n\tint htileno;\n\tint vtileno;\n\tjpc_dec_cmpt_t *cmpt;\n\tsize_t size;\n\tsize_t num_samples;\n\tsize_t num_samples_delta;\n\n\tsize_t tile_samples;\n\tif (!jas_safe_size_mul(siz->tilewidth, siz->tileheight, &tile_samples) ||\n\t (dec->max_samples > 0 && tile_samples > dec->max_samples)) {\n\t\tjas_eprintf(\"tile too large\\n\");\n\t\treturn -1;\n\t}\n\n\tdec->xstart = siz->xoff;\n\tdec->ystart = siz->yoff;\n\tdec->xend = siz->width;\n\tdec->yend = siz->height;\n\tdec->tilewidth = siz->tilewidth;\n\tdec->tileheight = siz->tileheight;\n\tdec->tilexoff = siz->tilexoff;\n\tdec->tileyoff = siz->tileyoff;\n\tdec->numcomps = siz->numcomps;\n\n\tif (!(dec->cp = jpc_dec_cp_create(dec->numcomps))) {\n\t\treturn -1;\n\t}\n\n\tif (!(dec->cmpts = jas_alloc2(dec->numcomps, sizeof(jpc_dec_cmpt_t)))) {\n\t\treturn -1;\n\t}\n\n\tnum_samples = 0;\n\tfor (compno = 0, cmpt = dec->cmpts; compno < dec->numcomps; ++compno,\n\t ++cmpt) {\n\t\tcmpt->prec = siz->comps[compno].prec;\n\t\tcmpt->sgnd = siz->comps[compno].sgnd;\n\t\tcmpt->hstep = siz->comps[compno].hsamp;\n\t\tcmpt->vstep = siz->comps[compno].vsamp;\n\t\tcmpt->width = JPC_CEILDIV(dec->xend, cmpt->hstep) -\n\t\t JPC_CEILDIV(dec->xstart, cmpt->hstep);\n\t\tcmpt->height = JPC_CEILDIV(dec->yend, cmpt->vstep) -\n\t\t JPC_CEILDIV(dec->ystart, cmpt->vstep);\n\t\tcmpt->hsubstep = 0;\n\t\tcmpt->vsubstep = 0;\n\n\t\tif (!jas_safe_size_mul(cmpt->width, cmpt->height, &num_samples_delta)) {\n\t\t\tjas_eprintf(\"image too large\\n\");\n\t\t\treturn -1;\n\t\t}\n\t\tif (!jas_safe_size_add(num_samples, num_samples_delta, &num_samples)) {\n\t\t\tjas_eprintf(\"image too large\\n\");\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tif (dec->max_samples > 0 && num_samples > dec->max_samples) {\n\t\tjas_eprintf(\"maximum number of samples exceeded (%zu > %zu)\\n\",\n\t\t num_samples, dec->max_samples);\n\t\treturn -1;\n\t}\n\n\tdec->image = 0;\n\n\tdec->numhtiles = JPC_CEILDIV(dec->xend - dec->tilexoff, dec->tilewidth);\n\tdec->numvtiles = JPC_CEILDIV(dec->yend - dec->tileyoff, dec->tileheight);\n\tassert(dec->numhtiles >= 0);\n\tassert(dec->numvtiles >= 0);\n\tif (!jas_safe_size_mul(dec->numhtiles, dec->numvtiles, &size) ||\n\t size > INT_MAX) {\n\t\treturn -1;\n\t}\n\tif (dec->max_samples > 0 && size > dec->max_samples \/ 16 \/ 16) {\n\t\t\/* avoid Denial of Service by a malicious input file\n\t\t with millions of tiny tiles; if max_samples is\n\t\t configured, then assume the tiles are at least\n\t\t 16x16, and don't allow more than this number of\n\t\t tiles *\/\n\t\treturn -1;\n\t}\n\tif (dec->max_samples > 0 && size > dec->max_samples \/ dec->numcomps \/ 16) {\n\t\t\/* another DoS check: since each tile allocates an\n\t\t array of components, this check attempts to catch\n\t\t excessive tile*component numbers *\/\n\t\treturn -1;\n\t}\n\tdec->numtiles = size;\n\tJAS_DBGLOG(10, (\"numtiles = %d; numhtiles = %d; numvtiles = %d;\\n\",\n\t dec->numtiles, dec->numhtiles, dec->numvtiles));\n\tif (!(dec->tiles = jas_alloc2(dec->numtiles, sizeof(jpc_dec_tile_t)))) {\n\t\treturn -1;\n\t}\n\n\tfor (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,\n\t ++tile) {\n\t\t\/* initialize all tiles with JPC_TILE_DONE so\n\t\t jpc_dec_destroy() knows which ones need a\n\t\t jpc_dec_tilefini() call; they are not actually\n\t\t \"done\", of course *\/\n\t\ttile->state = JPC_TILE_DONE;\n\t}\n\n\tfor (tileno = 0, tile = dec->tiles; tileno < dec->numtiles; ++tileno,\n\t ++tile) {\n\t\thtileno = tileno % dec->numhtiles;\n\t\tvtileno = tileno \/ dec->numhtiles;\n\t\ttile->realmode = 0;\n\t\ttile->state = JPC_TILE_INIT;\n\t\ttile->xstart = JAS_MAX(dec->tilexoff + htileno * dec->tilewidth,\n\t\t dec->xstart);\n\t\ttile->ystart = JAS_MAX(dec->tileyoff + vtileno * dec->tileheight,\n\t\t dec->ystart);\n\t\ttile->xend = JAS_MIN(dec->tilexoff + (htileno + 1) *\n\t\t dec->tilewidth, dec->xend);\n\t\ttile->yend = JAS_MIN(dec->tileyoff + (vtileno + 1) *\n\t\t dec->tileheight, dec->yend);\n\t\ttile->numparts = 0;\n\t\ttile->partno = 0;\n\t\ttile->pkthdrstream = 0;\n\t\ttile->pkthdrstreampos = 0;\n\t\ttile->pptstab = 0;\n\t\ttile->cp = 0;\n\t\ttile->pi = 0;\n\t\tif (!(tile->tcomps = jas_alloc2(dec->numcomps,\n\t\t sizeof(jpc_dec_tcomp_t)))) {\n\t\t\treturn -1;\n\t\t}\n\t\tfor (compno = 0, cmpt = dec->cmpts, tcomp = tile->tcomps;\n\t\t compno < dec->numcomps; ++compno, ++cmpt, ++tcomp) {\n\t\t\ttcomp->rlvls = 0;\n\t\t\ttcomp->numrlvls = 0;\n\t\t\ttcomp->data = 0;\n\t\t\ttcomp->xstart = JPC_CEILDIV(tile->xstart, cmpt->hstep);\n\t\t\ttcomp->ystart = JPC_CEILDIV(tile->ystart, cmpt->vstep);\n\t\t\ttcomp->xend = JPC_CEILDIV(tile->xend, cmpt->hstep);\n\t\t\ttcomp->yend = JPC_CEILDIV(tile->yend, cmpt->vstep);\n\t\t\ttcomp->tsfb = 0;\n\t\t}\n\t}\n\n\tdec->pkthdrstreams = 0;\n\n\t\/* We should expect to encounter other main header marker segments\n\t or an SOT marker segment next. *\/\n\tdec->state = JPC_MH;\n\n\treturn 0;\n}","target":1,"code_token_length":1681,"total_token_length":2012,"max_tokens_setting":2048} +{"idx":364820,"func":"_parse_env_file(pam_handle_t *pamh, int ctrl, const char *file)\n{\n int retval=PAM_SUCCESS, i, t;\n char buffer[BUF_SIZE], *key, *mark;\n FILE *conf;\n\n D((\"Env file name is: %s\", file));\n\n if ((conf = fopen(file,\"r\")) == NULL) {\n pam_syslog(pamh, LOG_ERR, \"Unable to open env file: %s: %m\", file);\n return PAM_IGNORE;\n }\n\n while (_assemble_line(conf, buffer, BUF_SIZE) > 0) {\n\tD((\"Read line: %s\", buffer));\n\tkey = buffer;\n\n\t\/* skip leading white space *\/\n\tkey += strspn(key, \" \\n\\t\");\n\n\t\/* skip blanks lines and comments *\/\n\tif (key[0] == '#')\n\t continue;\n\n\t\/* skip over \"export \" if present so we can be compat with\n\t bash type declarations *\/\n\tif (strncmp(key, \"export \", (size_t) 7) == 0)\n\t key += 7;\n\n\t\/* now find the end of value *\/\n\tmark = key;\n\twhile(mark[0] != '\\n' && mark[0] != '#' && mark[0] != '\\0')\n\t mark++;\n\tif (mark[0] != '\\0')\n\t mark[0] = '\\0';\n\n \/*\n\t* sanity check, the key must be alpha-numeric\n\t*\/\n\n\tfor ( i = 0 ; key[i] != '=' && key[i] != '\\0' ; i++ )\n\t if (!isalnum(key[i]) && key[i] != '_') {\n\t\tpam_syslog(pamh, LOG_ERR,\n\t\t \"non-alphanumeric key '%s' in %s', ignoring\",\n\t\t key, file);\n\t\tbreak;\n\t }\n\t\/* non-alphanumeric key, ignore this line *\/\n\tif (key[i] != '=' && key[i] != '\\0')\n\t continue;\n\n\t\/* now we try to be smart about quotes around the value,\n\t but not too smart, we can't get all fancy with escaped\n\t values like bash *\/\n\tif (key[i] == '=' && (key[++i] == '\\\"' || key[i] == '\\'')) {\n\t for ( t = i+1 ; key[t] != '\\0' ; t++)\n\t\tif (key[t] != '\\\"' && key[t] != '\\'')\n\t\t key[i++] = key[t];\n\t\telse if (key[t+1] != '\\0')\n\t\t key[i++] = key[t];\n\t key[i] = '\\0';\n\t}\n\n\t\/* if this is a request to delete a variable, check that it's\n\t actually set first, so we don't get a vague error back from\n\t pam_putenv() *\/\n\tfor (i = 0; key[i] != '=' && key[i] != '\\0'; i++);\n\n\tif (key[i] == '\\0' && !pam_getenv(pamh,key))\n\t continue;\n\n\t\/* set the env var, if it fails, we break out of the loop *\/\n\tretval = pam_putenv(pamh, key);\n\tif (retval != PAM_SUCCESS) {\n\t D((\"error setting env \\\"%s\\\"\", key));\n\t break;\n\t} else if (ctrl & PAM_DEBUG_ARG) {\n\t pam_syslog(pamh, LOG_DEBUG,\n\t\t \"pam_putenv(\\\"%s\\\")\", key);\n\t}\n }\n\n (void) fclose(conf);\n\n \/* tidy up *\/\n D((\"Exit.\"));\n return retval;\n}","target":0,"code_token_length":746,"total_token_length":1077,"max_tokens_setting":2048} +{"idx":30750,"func":"static void write_crash_report ( const char * err ) {\n char * loc = git_pathdup ( \"fast_import_crash_%\" PRIuMAX , ( uintmax_t ) getpid ( ) ) ;\n FILE * rpt = fopen ( loc , \"w\" ) ;\n struct branch * b ;\n unsigned long lu ;\n struct recent_command * rc ;\n if ( ! rpt ) {\n error ( \"can't write crash report %s: %s\" , loc , strerror ( errno ) ) ;\n free ( loc ) ;\n return ;\n }\n fprintf ( stderr , \"fast-import: dumping crash report to %s\\n\" , loc ) ;\n fprintf ( rpt , \"fast-import crash report:\\n\" ) ;\n fprintf ( rpt , \" fast-import process: %\" PRIuMAX \"\\n\" , ( uintmax_t ) getpid ( ) ) ;\n fprintf ( rpt , \" parent process : %\" PRIuMAX \"\\n\" , ( uintmax_t ) getppid ( ) ) ;\n fprintf ( rpt , \" at %s\\n\" , show_date ( time ( NULL ) , 0 , DATE_MODE ( LOCAL ) ) ) ;\n fputc ( '\\n' , rpt ) ;\n fputs ( \"fatal: \" , rpt ) ;\n fputs ( err , rpt ) ;\n fputc ( '\\n' , rpt ) ;\n fputc ( '\\n' , rpt ) ;\n fputs ( \"Most Recent Commands Before Crash\\n\" , rpt ) ;\n fputs ( \"---------------------------------\\n\" , rpt ) ;\n for ( rc = cmd_hist . next ;\n rc != & cmd_hist ;\n rc = rc -> next ) {\n if ( rc -> next == & cmd_hist ) fputs ( \"* \" , rpt ) ;\n else fputs ( \" \" , rpt ) ;\n fputs ( rc -> buf , rpt ) ;\n fputc ( '\\n' , rpt ) ;\n }\n fputc ( '\\n' , rpt ) ;\n fputs ( \"Active Branch LRU\\n\" , rpt ) ;\n fputs ( \"-----------------\\n\" , rpt ) ;\n fprintf ( rpt , \" active_branches = %lu cur, %lu max\\n\" , cur_active_branches , max_active_branches ) ;\n fputc ( '\\n' , rpt ) ;\n fputs ( \" pos clock name\\n\" , rpt ) ;\n fputs ( \" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\\n\" , rpt ) ;\n for ( b = active_branches , lu = 0 ;\n b ;\n b = b -> active_next_branch ) fprintf ( rpt , \" %2lu) %6\" PRIuMAX \" %s\\n\" , ++ lu , b -> last_commit , b -> name ) ;\n fputc ( '\\n' , rpt ) ;\n fputs ( \"Inactive Branches\\n\" , rpt ) ;\n fputs ( \"-----------------\\n\" , rpt ) ;\n for ( lu = 0 ;\n lu < branch_table_sz ;\n lu ++ ) {\n for ( b = branch_table [ lu ] ;\n b ;\n b = b -> table_next_branch ) write_branch_report ( rpt , b ) ;\n }\n if ( first_tag ) {\n struct tag * tg ;\n fputc ( '\\n' , rpt ) ;\n fputs ( \"Annotated Tags\\n\" , rpt ) ;\n fputs ( \"--------------\\n\" , rpt ) ;\n for ( tg = first_tag ;\n tg ;\n tg = tg -> next_tag ) {\n fputs ( sha1_to_hex ( tg -> sha1 ) , rpt ) ;\n fputc ( ' ' , rpt ) ;\n fputs ( tg -> name , rpt ) ;\n fputc ( '\\n' , rpt ) ;\n }\n }\n fputc ( '\\n' , rpt ) ;\n fputs ( \"Marks\\n\" , rpt ) ;\n fputs ( \"-----\\n\" , rpt ) ;\n if ( export_marks_file ) fprintf ( rpt , \" exported to %s\\n\" , export_marks_file ) ;\n else dump_marks_helper ( rpt , 0 , marks ) ;\n fputc ( '\\n' , rpt ) ;\n fputs ( \"-------------------\\n\" , rpt ) ;\n fputs ( \"END OF CRASH REPORT\\n\" , rpt ) ;\n fclose ( rpt ) ;\n free ( loc ) ;\n }","target":0,"code_token_length":826,"total_token_length":1157,"max_tokens_setting":2048} +{"idx":164066,"func":"void _php_curl_verify_handlers(php_curl *ch, int reporterror) \/* {{{ *\/\n{\n\tphp_stream *stream;\n\tif (!ch || !ch->handlers) {\n\t\treturn;\n\t}\n\n\tif (!Z_ISUNDEF(ch->handlers->std_err)) {\n\t\tstream = zend_fetch_resource(&ch->handlers->std_err, -1, NULL, NULL, 2, php_file_le_stream(), php_file_le_pstream());\n\t\tif (stream == NULL) {\n\t\t\tif (reporterror) {\n\t\t\t\tphp_error_docref(NULL, E_WARNING, \"CURLOPT_STDERR resource has gone away, resetting to stderr\");\n\t\t\t}\n\t\t\tzval_ptr_dtor(&ch->handlers->std_err);\n\t\t\tZVAL_UNDEF(&ch->handlers->std_err);\n\n\t\t\tcurl_easy_setopt(ch->cp, CURLOPT_STDERR, stderr);\n\t\t}\n\t}\n\tif (ch->handlers->read && !Z_ISUNDEF(ch->handlers->read->stream)) {\n\t\tstream = zend_fetch_resource(&ch->handlers->read->stream, -1, NULL, NULL, 2, php_file_le_stream(), php_file_le_pstream());\n\t\tif (stream == NULL) {\n\t\t\tif (reporterror) {\n\t\t\t\tphp_error_docref(NULL, E_WARNING, \"CURLOPT_INFILE resource has gone away, resetting to default\");\n\t\t\t}\n\t\t\tzval_ptr_dtor(&ch->handlers->read->stream);\n\t\t\tZVAL_UNDEF(&ch->handlers->read->stream);\n\t\t\tch->handlers->read->res = NULL;\n\t\t\tch->handlers->read->fp = 0;\n\n\t\t\tcurl_easy_setopt(ch->cp, CURLOPT_INFILE, (void *) ch);\n\t\t}\n\t}\n\tif (ch->handlers->write_header && !Z_ISUNDEF(ch->handlers->write_header->stream)) {\n\t\tstream = zend_fetch_resource(&ch->handlers->write_header->stream, -1, NULL, NULL, 2, php_file_le_stream(), php_file_le_pstream());\n\t\tif (stream == NULL) {\n\t\t\tif (reporterror) {\n\t\t\t\tphp_error_docref(NULL, E_WARNING, \"CURLOPT_WRITEHEADER resource has gone away, resetting to default\");\n\t\t\t}\n\t\t\tzval_ptr_dtor(&ch->handlers->write_header->stream);\n\t\t\tZVAL_UNDEF(&ch->handlers->write_header->stream);\n\t\t\tch->handlers->write_header->fp = 0;\n\n\t\t\tch->handlers->write_header->method = PHP_CURL_IGNORE;\n\t\t\tcurl_easy_setopt(ch->cp, CURLOPT_WRITEHEADER, (void *) ch);\n\t\t}\n\t}\n\tif (ch->handlers->write && !Z_ISUNDEF(ch->handlers->write->stream)) {\n\t\tstream = zend_fetch_resource(&ch->handlers->write->stream, -1, NULL, NULL, 2, php_file_le_stream(), php_file_le_pstream());\n\t\tif (stream == NULL) {\n\t\t\tif (reporterror) {\n\t\t\t\tphp_error_docref(NULL, E_WARNING, \"CURLOPT_FILE resource has gone away, resetting to default\");\n\t\t\t}\n\t\t\tzval_ptr_dtor(&ch->handlers->write->stream);\n\t\t\tZVAL_UNDEF(&ch->handlers->write->stream);\n\t\t\tch->handlers->write->fp = 0;\n\n\t\t\tch->handlers->write->method = PHP_CURL_STDOUT;\n\t\t\tcurl_easy_setopt(ch->cp, CURLOPT_FILE, (void *) ch);\n\t\t}\n\t}\n\treturn ;\n}\n\/* }}} *\/\n","target":0,"code_token_length":721,"total_token_length":1052,"max_tokens_setting":2048} +{"idx":321575,"func":"void do_interrupt(CPUARMState *env)\n\n{\n\n uint32_t addr;\n\n uint32_t mask;\n\n int new_mode;\n\n uint32_t offset;\n\n\n\n if (IS_M(env)) {\n\n do_interrupt_v7m(env);\n\n return;\n\n }\n\n \/* TODO: Vectored interrupt controller. *\/\n\n switch (env->exception_index) {\n\n case EXCP_UDEF:\n\n new_mode = ARM_CPU_MODE_UND;\n\n addr = 0x04;\n\n mask = CPSR_I;\n\n if (env->thumb)\n\n offset = 2;\n\n else\n\n offset = 4;\n\n break;\n\n case EXCP_SWI:\n\n if (semihosting_enabled) {\n\n \/* Check for semihosting interrupt. *\/\n\n if (env->thumb) {\n\n mask = lduw_code(env->regs[15] - 2) & 0xff;\n\n } else {\n\n mask = ldl_code(env->regs[15] - 4) & 0xffffff;\n\n }\n\n \/* Only intercept calls from privileged modes, to provide some\n\n semblance of security. *\/\n\n if (((mask == 0x123456 && !env->thumb)\n\n || (mask == 0xab && env->thumb))\n\n && (env->uncached_cpsr & CPSR_M) != ARM_CPU_MODE_USR) {\n\n env->regs[0] = do_arm_semihosting(env);\n\n return;\n\n }\n\n }\n\n new_mode = ARM_CPU_MODE_SVC;\n\n addr = 0x08;\n\n mask = CPSR_I;\n\n \/* The PC already points to the next instruction. *\/\n\n offset = 0;\n\n break;\n\n case EXCP_BKPT:\n\n \/* See if this is a semihosting syscall. *\/\n\n if (env->thumb && semihosting_enabled) {\n\n mask = lduw_code(env->regs[15]) & 0xff;\n\n if (mask == 0xab\n\n && (env->uncached_cpsr & CPSR_M) != ARM_CPU_MODE_USR) {\n\n env->regs[15] += 2;\n\n env->regs[0] = do_arm_semihosting(env);\n\n return;\n\n }\n\n }\n\n env->cp15.c5_insn = 2;\n\n \/* Fall through to prefetch abort. *\/\n\n case EXCP_PREFETCH_ABORT:\n\n new_mode = ARM_CPU_MODE_ABT;\n\n addr = 0x0c;\n\n mask = CPSR_A | CPSR_I;\n\n offset = 4;\n\n break;\n\n case EXCP_DATA_ABORT:\n\n new_mode = ARM_CPU_MODE_ABT;\n\n addr = 0x10;\n\n mask = CPSR_A | CPSR_I;\n\n offset = 8;\n\n break;\n\n case EXCP_IRQ:\n\n new_mode = ARM_CPU_MODE_IRQ;\n\n addr = 0x18;\n\n \/* Disable IRQ and imprecise data aborts. *\/\n\n mask = CPSR_A | CPSR_I;\n\n offset = 4;\n\n break;\n\n case EXCP_FIQ:\n\n new_mode = ARM_CPU_MODE_FIQ;\n\n addr = 0x1c;\n\n \/* Disable FIQ, IRQ and imprecise data aborts. *\/\n\n mask = CPSR_A | CPSR_I | CPSR_F;\n\n offset = 4;\n\n break;\n\n default:\n\n cpu_abort(env, \"Unhandled exception 0x%x\\n\", env->exception_index);\n\n return; \/* Never happens. Keep compiler happy. *\/\n\n }\n\n \/* High vectors. *\/\n\n if (env->cp15.c1_sys & (1 << 13)) {\n\n addr += 0xffff0000;\n\n }\n\n switch_mode (env, new_mode);\n\n env->spsr = cpsr_read(env);\n\n \/* Clear IT bits. *\/\n\n env->condexec_bits = 0;\n\n \/* Switch to the new mode, and to the correct instruction set. *\/\n\n env->uncached_cpsr = (env->uncached_cpsr & ~CPSR_M) | new_mode;\n\n env->uncached_cpsr |= mask;\n\n \/* this is a lie, as the was no c1_sys on V4T\/V5, but who cares\n\n * and we should just guard the thumb mode on V4 *\/\n\n if (arm_feature(env, ARM_FEATURE_V4T)) {\n\n env->thumb = (env->cp15.c1_sys & (1 << 30)) != 0;\n\n }\n\n env->regs[14] = env->regs[15] + offset;\n\n env->regs[15] = addr;\n\n env->interrupt_request |= CPU_INTERRUPT_EXITTB;\n\n}\n","target":1,"code_token_length":1029,"total_token_length":1360,"max_tokens_setting":2048} +{"idx":346260,"func":"static inline void Process_ipfix_option_templates(exporter_ipfix_domain_t *exporter, void *option_template_flowset, FlowSource_t *fs) {\nvoid\t\t*DataPtr;\nuint32_t\tsize_left, size_required, i;\n\/\/ uint32_t nr_scopes, nr_options;\nuint16_t\tid, field_count, scope_field_count, offset, sampler_id_length;\nuint16_t\toffset_sampler_id, offset_sampler_mode, offset_sampler_interval, found_sampler;\nuint16_t\toffset_std_sampler_interval, offset_std_sampler_algorithm, found_std_sampling;\n\n\ti = 0;\t\/\/ keep compiler happy\n\tsize_left \t\t = GET_FLOWSET_LENGTH(option_template_flowset) - 4; \/\/ -4 for flowset header -> id and length\n\tif ( size_left < 6 ) {\n\t\tsyslog(LOG_ERR, \"Process_ipfix: [%u] option template length error: size left %u too small for an options template\", \n\t\t\texporter->info.id, size_left);\n\t\treturn;\n\t}\n\n\tDataPtr \t\t = option_template_flowset + 4;\n\tid \t \t\t\t = GET_OPTION_TEMPLATE_ID(DataPtr); \n\tfield_count \t = GET_OPTION_TEMPLATE_FIELD_COUNT(DataPtr);\n\tscope_field_count = GET_OPTION_TEMPLATE_SCOPE_FIELD_COUNT(DataPtr);\n\tDataPtr += 6;\n\tsize_left -= 6;\n\n\tif ( scope_field_count == 0 ) {\n\t\tsyslog(LOG_ERR, \"Process_ipfx: [%u] scope field count error: length must not be zero\", \n\t\t\texporter->info.id);\n\t\tdbg_printf(\"scope field count error: length must not be zero\\n\");\n\t\treturn;\n\t}\n\n\tsize_required = field_count * 2 * sizeof(uint16_t);\n\tdbg_printf(\"Size left: %u, size required: %u\\n\", size_left, size_required);\n\tif ( size_left < size_required ) {\n\t\tsyslog(LOG_ERR, \"Process_ipfix: [%u] option template length error: size left %u too small for %u scopes length and %u options length\", \n\t\t\texporter->info.id, size_left, field_count, scope_field_count);\n\t\tdbg_printf(\"option template length error: size left %u too small for field_count %u\\n\", \n\t\t\tsize_left, field_count);\n\t\treturn;\n\t}\n\n\tdbg_printf(\"Decode Option Template. id: %u, field count: %u, scope field count: %u\\n\",\n\t\tid, field_count, scope_field_count);\n\n\tif ( scope_field_count == 0 ) {\n\t\tsyslog(LOG_ERR, \"Process_ipfxi: [%u] scope field count error: length must not be zero\", \n\t\t\texporter->info.id);\n\t\treturn;\n\t}\n\n\tfor ( i=0; iinfo.id, size_left, field_count, scope_field_count);\n\t\t\t\tdbg_printf(\"option template length error: size left %u too small for field_count %u\\n\", \n\t\t\t\t\tsize_left, field_count);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tenterprise_value = Get_val32(DataPtr);\n\t\t\tDataPtr += 4;\n\t\t\tdbg_printf(\" [%i] Enterprise: 1, scope id: %u, scope length %u enterprise value: %u\\n\", \n\t\t\t\ti, id, length, enterprise_value);\n\t\t} else {\n\t\t\tdbg_printf(\" [%i] Enterprise: 0, scope id: %u, scope length %u\\n\", i, id, length);\n\t\t}\n\t}\n\tfor ( ;iinfo.id, size_left, field_count, scope_field_count);\n\t\t\t\tdbg_printf(\"option template length error: size left %u too small for field_count %u\\n\", \n\t\t\t\t\tsize_left, field_count);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tenterprise_value = Get_val32(DataPtr);\n\t\t\tDataPtr += 4;\n\t\t\tdbg_printf(\" [%i] Enterprise: 1, option id: %u, option length %u enterprise value: %u\\n\", \n\t\t\t\ti, id, length, enterprise_value);\n\t\t} else {\n\t\t\tdbg_printf(\" [%i] Enterprise: 0, option id: %u, option length %u\\n\", i, id, length);\n\t\t}\n\t}\n\n\tsampler_id_length\t\t\t = 0;\n\toffset_sampler_id \t\t\t = 0;\n\toffset_sampler_mode \t\t = 0;\n\toffset_sampler_interval \t = 0;\n\toffset_std_sampler_interval = 0;\n\toffset_std_sampler_algorithm = 0;\n\tfound_sampler\t\t\t\t = 0;\n\tfound_std_sampling\t\t\t = 0;\n\toffset = 0;\n\n\/* XXX\n XXX Sampling for IPFIX not yet implemented due to lack of data and information\n\t\tswitch (type) {\n\t\t\t\/\/ general sampling\n\t\t\tcase NF9_SAMPLING_INTERVAL:\n\t\t\t\toffset_std_sampler_interval = offset;\n\t\t\t\tfound_std_sampling++;\n\t\t\t\tbreak;\n\t\t\tcase NF9_SAMPLING_ALGORITHM:\n\t\t\t\toffset_std_sampler_algorithm = offset;\n\t\t\t\tfound_std_sampling++;\n\t\t\t\tbreak;\n\n\t\t\t\/\/ individual samplers\n\t\t\tcase NF9_FLOW_SAMPLER_ID:\n\t\t\t\toffset_sampler_id = offset;\n\t\t\t\tsampler_id_length = length;\n\t\t\t\tfound_sampler++;\n\t\t\t\tbreak;\n\t\t\tcase FLOW_SAMPLER_MODE:\n\t\t\t\toffset_sampler_mode = offset;\n\t\t\t\tfound_sampler++;\n\t\t\t\tbreak;\n\t\t\tcase NF9_FLOW_SAMPLER_RANDOM_INTERVAL:\n\t\t\t\toffset_sampler_interval = offset;\n\t\t\t\tfound_sampler++;\n\t\t\t\tbreak;\n\t\t}\n\t\toffset += length;\n\tif ( found_sampler == 3 ) { \/\/ need all three tags\n\t\tdbg_printf(\"[%u] Sampling information found\\n\", exporter->info.id);\n\t\tInsertSamplerOffset(fs, id, offset_sampler_id, sampler_id_length, offset_sampler_mode, offset_sampler_interval);\n\t} else if ( found_std_sampling == 2 ) { \/\/ need all two tags\n\t\tdbg_printf(\"[%u] Std sampling information found\\n\", exporter->info.id);\n\t\tInsertStdSamplerOffset(fs, id, offset_std_sampler_interval, offset_std_sampler_algorithm);\n\t} else {\n\t\tdbg_printf(\"[%u] No Sampling information found\\n\", exporter->info.id);\n\t}\n*\/\n\tdbg_printf(\"\\n\");\n\tprocessed_records++;\n\n} \/\/ End of Process_ipfix_option_templates","target":1,"code_token_length":1632,"total_token_length":1963,"max_tokens_setting":2048} +{"idx":31753,"func":"static int ext4_alloc_file_blocks(struct file *file, ext4_lblk_t offset,\n\t\t\t\t ext4_lblk_t len, loff_t new_size,\n\t\t\t\t int flags, int mode)\n{\n\tstruct inode *inode = file_inode(file);\n\thandle_t *handle;\n\tint ret = 0;\n\tint ret2 = 0;\n\tint retries = 0;\n\tint depth = 0;\n\tstruct ext4_map_blocks map;\n\tunsigned int credits;\n\tloff_t epos;\n\n\tmap.m_lblk = offset;\n\tmap.m_len = len;\n\t\/*\n\t * Don't normalize the request if it can fit in one extent so\n\t * that it doesn't get unnecessarily split into multiple\n\t * extents.\n\t *\/\n\tif (len <= EXT_UNWRITTEN_MAX_LEN)\n\t\tflags |= EXT4_GET_BLOCKS_NO_NORMALIZE;\n\n\t\/* Wait all existing dio workers, newcomers will block on i_mutex *\/\n\text4_inode_block_unlocked_dio(inode);\n\tinode_dio_wait(inode);\n\n\t\/*\n\t * credits to insert 1 extent into extent tree\n\t *\/\n\tcredits = ext4_chunk_trans_blocks(inode, len);\n\t\/*\n\t * We can only call ext_depth() on extent based inodes\n\t *\/\n\tif (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))\n\t\tdepth = ext_depth(inode);\n\telse\n\t\tdepth = -1;\n\nretry:\n\twhile (ret >= 0 && len) {\n\t\t\/*\n\t\t * Recalculate credits when extent tree depth changes.\n\t\t *\/\n\t\tif (depth >= 0 && depth != ext_depth(inode)) {\n\t\t\tcredits = ext4_chunk_trans_blocks(inode, len);\n\t\t\tdepth = ext_depth(inode);\n\t\t}\n\n\t\thandle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS,\n\t\t\t\t\t credits);\n\t\tif (IS_ERR(handle)) {\n\t\t\tret = PTR_ERR(handle);\n\t\t\tbreak;\n\t\t}\n\t\tret = ext4_map_blocks(handle, inode, &map, flags);\n\t\tif (ret <= 0) {\n\t\t\text4_debug(\"inode #%lu: block %u: len %u: \"\n\t\t\t\t \"ext4_ext_map_blocks returned %d\",\n\t\t\t\t inode->i_ino, map.m_lblk,\n\t\t\t\t map.m_len, ret);\n\t\t\text4_mark_inode_dirty(handle, inode);\n\t\t\tret2 = ext4_journal_stop(handle);\n\t\t\tbreak;\n\t\t}\n\t\tmap.m_lblk += ret;\n\t\tmap.m_len = len = len - ret;\n\t\tepos = (loff_t)map.m_lblk << inode->i_blkbits;\n\t\tinode->i_ctime = ext4_current_time(inode);\n\t\tif (new_size) {\n\t\t\tif (epos > new_size)\n\t\t\t\tepos = new_size;\n\t\t\tif (ext4_update_inode_size(inode, epos) & 0x1)\n\t\t\t\tinode->i_mtime = inode->i_ctime;\n\t\t} else {\n\t\t\tif (epos > inode->i_size)\n\t\t\t\text4_set_inode_flag(inode,\n\t\t\t\t\t\t EXT4_INODE_EOFBLOCKS);\n\t\t}\n\t\text4_mark_inode_dirty(handle, inode);\n\t\tret2 = ext4_journal_stop(handle);\n\t\tif (ret2)\n\t\t\tbreak;\n\t}\n\tif (ret == -ENOSPC &&\n\t\t\text4_should_retry_alloc(inode->i_sb, &retries)) {\n\t\tret = 0;\n\t\tgoto retry;\n\t}\n\n\text4_inode_resume_unlocked_dio(inode);\n\n\treturn ret > 0 ? ret2 : ret;\n}","target":0,"code_token_length":720,"total_token_length":1051,"max_tokens_setting":2048} +{"idx":458124,"func":"static OPJ_BOOL opj_j2k_write_all_tile_parts(opj_j2k_t *p_j2k,\n OPJ_BYTE * p_data,\n OPJ_UINT32 * p_data_written,\n OPJ_UINT32 total_data_size,\n opj_stream_private_t *p_stream,\n struct opj_event_mgr * p_manager\n )\n{\n OPJ_UINT32 tilepartno = 0;\n OPJ_UINT32 l_nb_bytes_written = 0;\n OPJ_UINT32 l_current_nb_bytes_written;\n OPJ_UINT32 l_part_tile_size;\n OPJ_UINT32 tot_num_tp;\n OPJ_UINT32 pino;\n\n OPJ_BYTE * l_begin_data;\n opj_tcp_t *l_tcp = 00;\n opj_tcd_t * l_tcd = 00;\n opj_cp_t * l_cp = 00;\n\n l_tcd = p_j2k->m_tcd;\n l_cp = &(p_j2k->m_cp);\n l_tcp = l_cp->tcps + p_j2k->m_current_tile_number;\n\n \/*Get number of tile parts*\/\n tot_num_tp = opj_j2k_get_num_tp(l_cp, 0, p_j2k->m_current_tile_number);\n\n \/* start writing remaining tile parts *\/\n ++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;\n for (tilepartno = 1; tilepartno < tot_num_tp ; ++tilepartno) {\n p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = tilepartno;\n l_current_nb_bytes_written = 0;\n l_part_tile_size = 0;\n l_begin_data = p_data;\n\n if (! opj_j2k_write_sot(p_j2k, p_data,\n total_data_size,\n &l_current_nb_bytes_written,\n p_stream,\n p_manager)) {\n return OPJ_FALSE;\n }\n\n l_nb_bytes_written += l_current_nb_bytes_written;\n p_data += l_current_nb_bytes_written;\n total_data_size -= l_current_nb_bytes_written;\n l_part_tile_size += l_current_nb_bytes_written;\n\n l_current_nb_bytes_written = 0;\n if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written,\n total_data_size, p_stream, p_manager)) {\n return OPJ_FALSE;\n }\n\n p_data += l_current_nb_bytes_written;\n l_nb_bytes_written += l_current_nb_bytes_written;\n total_data_size -= l_current_nb_bytes_written;\n l_part_tile_size += l_current_nb_bytes_written;\n\n \/* Writing Psot in SOT marker *\/\n opj_write_bytes(l_begin_data + 6, l_part_tile_size,\n 4); \/* PSOT *\/\n\n if (OPJ_IS_CINEMA(l_cp->rsiz) || OPJ_IS_IMF(l_cp->rsiz)) {\n opj_j2k_update_tlm(p_j2k, l_part_tile_size);\n }\n\n ++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;\n }\n\n for (pino = 1; pino <= l_tcp->numpocs; ++pino) {\n l_tcd->cur_pino = pino;\n\n \/*Get number of tile parts*\/\n tot_num_tp = opj_j2k_get_num_tp(l_cp, pino, p_j2k->m_current_tile_number);\n for (tilepartno = 0; tilepartno < tot_num_tp ; ++tilepartno) {\n p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = tilepartno;\n l_current_nb_bytes_written = 0;\n l_part_tile_size = 0;\n l_begin_data = p_data;\n\n if (! opj_j2k_write_sot(p_j2k, p_data,\n total_data_size,\n &l_current_nb_bytes_written, p_stream,\n p_manager)) {\n return OPJ_FALSE;\n }\n\n l_nb_bytes_written += l_current_nb_bytes_written;\n p_data += l_current_nb_bytes_written;\n total_data_size -= l_current_nb_bytes_written;\n l_part_tile_size += l_current_nb_bytes_written;\n\n l_current_nb_bytes_written = 0;\n\n if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written,\n total_data_size, p_stream, p_manager)) {\n return OPJ_FALSE;\n }\n\n l_nb_bytes_written += l_current_nb_bytes_written;\n p_data += l_current_nb_bytes_written;\n total_data_size -= l_current_nb_bytes_written;\n l_part_tile_size += l_current_nb_bytes_written;\n\n \/* Writing Psot in SOT marker *\/\n opj_write_bytes(l_begin_data + 6, l_part_tile_size,\n 4); \/* PSOT *\/\n\n if (OPJ_IS_CINEMA(l_cp->rsiz) || OPJ_IS_IMF(l_cp->rsiz)) {\n opj_j2k_update_tlm(p_j2k, l_part_tile_size);\n }\n\n ++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;\n }\n }\n\n *p_data_written = l_nb_bytes_written;\n\n return OPJ_TRUE;\n}","target":0,"code_token_length":1155,"total_token_length":1486,"max_tokens_setting":2048} +{"idx":402821,"func":"poolGrow(STRING_POOL *pool)\n{\n if (pool->freeBlocks) {\n if (pool->start == 0) {\n pool->blocks = pool->freeBlocks;\n pool->freeBlocks = pool->freeBlocks->next;\n pool->blocks->next = NULL;\n pool->start = pool->blocks->s;\n pool->end = pool->start + pool->blocks->size;\n pool->ptr = pool->start;\n return XML_TRUE;\n }\n if (pool->end - pool->start < pool->freeBlocks->size) {\n BLOCK *tem = pool->freeBlocks->next;\n pool->freeBlocks->next = pool->blocks;\n pool->blocks = pool->freeBlocks;\n pool->freeBlocks = tem;\n memcpy(pool->blocks->s, pool->start,\n (pool->end - pool->start) * sizeof(XML_Char));\n pool->ptr = pool->blocks->s + (pool->ptr - pool->start);\n pool->start = pool->blocks->s;\n pool->end = pool->start + pool->blocks->size;\n return XML_TRUE;\n }\n }\n if (pool->blocks && pool->start == pool->blocks->s) {\n BLOCK *temp;\n int blockSize = (int)((unsigned)(pool->end - pool->start)*2U);\n size_t bytesToAllocate;\n\n if (blockSize < 0)\n return XML_FALSE;\n\n bytesToAllocate = poolBytesToAllocateFor(blockSize);\n if (bytesToAllocate == 0)\n return XML_FALSE;\n\n temp = (BLOCK *)\n pool->mem->realloc_fcn(pool->blocks, (unsigned)bytesToAllocate);\n if (temp == NULL)\n return XML_FALSE;\n pool->blocks = temp;\n pool->blocks->size = blockSize;\n pool->ptr = pool->blocks->s + (pool->ptr - pool->start);\n pool->start = pool->blocks->s;\n pool->end = pool->start + blockSize;\n }\n else {\n BLOCK *tem;\n int blockSize = (int)(pool->end - pool->start);\n size_t bytesToAllocate;\n\n if (blockSize < 0)\n return XML_FALSE;\n\n if (blockSize < INIT_BLOCK_SIZE)\n blockSize = INIT_BLOCK_SIZE;\n else {\n \/* Detect overflow, avoiding _signed_ overflow undefined behavior *\/\n if ((int)((unsigned)blockSize * 2U) < 0) {\n return XML_FALSE;\n }\n blockSize *= 2;\n }\n\n bytesToAllocate = poolBytesToAllocateFor(blockSize);\n if (bytesToAllocate == 0)\n return XML_FALSE;\n\n tem = (BLOCK *)pool->mem->malloc_fcn(bytesToAllocate);\n if (!tem)\n return XML_FALSE;\n tem->size = blockSize;\n tem->next = pool->blocks;\n pool->blocks = tem;\n if (pool->ptr != pool->start)\n memcpy(tem->s, pool->start,\n (pool->ptr - pool->start) * sizeof(XML_Char));\n pool->ptr = tem->s + (pool->ptr - pool->start);\n pool->start = tem->s;\n pool->end = tem->s + blockSize;\n }\n return XML_TRUE;\n}","target":0,"code_token_length":708,"total_token_length":1039,"max_tokens_setting":2048} +{"idx":43352,"func":"static pj_status_t parse_rr(pj_dns_parsed_rr *rr, pj_pool_t *pool,\n\t\t\t const pj_uint8_t *pkt,\n\t\t\t const pj_uint8_t *start, const pj_uint8_t *max,\n\t\t\t int *parsed_len)\n{\n const pj_uint8_t *p = start;\n int name_len, name_part_len;\n pj_status_t status;\n\n \/* Get the length of the name *\/\n status = get_name_len(0, pkt, start, max, &name_part_len, &name_len);\n if (status != PJ_SUCCESS)\n\treturn status;\n\n \/* Allocate memory for the name *\/\n rr->name.ptr = (char*) pj_pool_alloc(pool, name_len+4);\n rr->name.slen = 0;\n\n \/* Get the name *\/\n status = get_name(0, pkt, start, max, &rr->name);\n if (status != PJ_SUCCESS)\n\treturn status;\n\n p = (start + name_part_len);\n\n \/* Check the size can accomodate next few fields. *\/\n if (p+10 > max)\n\treturn PJLIB_UTIL_EDNSINSIZE;\n\n \/* Get the type *\/\n pj_memcpy(&rr->type, p, 2);\n rr->type = pj_ntohs(rr->type);\n p += 2;\n \n \/* Get the class *\/\n pj_memcpy(&rr->dnsclass, p, 2);\n rr->dnsclass = pj_ntohs(rr->dnsclass);\n p += 2;\n\n \/* Class MUST be IN *\/\n if (rr->dnsclass != 1) {\n\t\/* Class is not IN, return error only if type is known (see #1889) *\/\n\tif (rr->type == PJ_DNS_TYPE_A || rr->type == PJ_DNS_TYPE_AAAA ||\n\t rr->type == PJ_DNS_TYPE_CNAME || rr->type == PJ_DNS_TYPE_NS ||\n\t rr->type == PJ_DNS_TYPE_PTR || rr->type == PJ_DNS_TYPE_SRV)\n\t{\n\t return PJLIB_UTIL_EDNSINCLASS;\n\t}\n }\n\n \/* Get TTL *\/\n pj_memcpy(&rr->ttl, p, 4);\n rr->ttl = pj_ntohl(rr->ttl);\n p += 4;\n\n \/* Get rdlength *\/\n pj_memcpy(&rr->rdlength, p, 2);\n rr->rdlength = pj_ntohs(rr->rdlength);\n p += 2;\n\n \/* Check that length is valid *\/\n if (p + rr->rdlength > max)\n\treturn PJLIB_UTIL_EDNSINSIZE;\n\n \/* Parse some well known records *\/\n if (rr->type == PJ_DNS_TYPE_A) {\n\tpj_memcpy(&rr->rdata.a.ip_addr, p, 4);\n\tp += 4;\n\n } else if (rr->type == PJ_DNS_TYPE_AAAA) {\n\tpj_memcpy(&rr->rdata.aaaa.ip_addr, p, 16);\n\tp += 16;\n\n } else if (rr->type == PJ_DNS_TYPE_CNAME ||\n\t rr->type == PJ_DNS_TYPE_NS ||\n\t rr->type == PJ_DNS_TYPE_PTR) \n {\n\n\t\/* Get the length of the target name *\/\n\tstatus = get_name_len(0, pkt, p, max, &name_part_len, &name_len);\n\tif (status != PJ_SUCCESS)\n\t return status;\n\n\t\/* Allocate memory for the name *\/\n\trr->rdata.cname.name.ptr = (char*) pj_pool_alloc(pool, name_len);\n\trr->rdata.cname.name.slen = 0;\n\n\t\/* Get the name *\/\n\tstatus = get_name(0, pkt, p, max, &rr->rdata.cname.name);\n\tif (status != PJ_SUCCESS)\n\t return status;\n\n\tp += name_part_len;\n\n } else if (rr->type == PJ_DNS_TYPE_SRV) {\n\n\t\/* Priority *\/\n\tpj_memcpy(&rr->rdata.srv.prio, p, 2);\n\trr->rdata.srv.prio = pj_ntohs(rr->rdata.srv.prio);\n\tp += 2;\n\n\t\/* Weight *\/\n\tpj_memcpy(&rr->rdata.srv.weight, p, 2);\n\trr->rdata.srv.weight = pj_ntohs(rr->rdata.srv.weight);\n\tp += 2;\n\n\t\/* Port *\/\n\tpj_memcpy(&rr->rdata.srv.port, p, 2);\n\trr->rdata.srv.port = pj_ntohs(rr->rdata.srv.port);\n\tp += 2;\n\t\n\t\/* Get the length of the target name *\/\n\tstatus = get_name_len(0, pkt, p, max, &name_part_len, &name_len);\n\tif (status != PJ_SUCCESS)\n\t return status;\n\n\t\/* Allocate memory for the name *\/\n\trr->rdata.srv.target.ptr = (char*) pj_pool_alloc(pool, name_len);\n\trr->rdata.srv.target.slen = 0;\n\n\t\/* Get the name *\/\n\tstatus = get_name(0, pkt, p, max, &rr->rdata.srv.target);\n\tif (status != PJ_SUCCESS)\n\t return status;\n\tp += name_part_len;\n\n } else {\n\t\/* Copy the raw data *\/\n\trr->data = pj_pool_alloc(pool, rr->rdlength);\n\tpj_memcpy(rr->data, p, rr->rdlength);\n\n\tp += rr->rdlength;\n }\n\n *parsed_len = (int)(p - start);\n return PJ_SUCCESS;\n}","target":0,"code_token_length":1172,"total_token_length":1503,"max_tokens_setting":2048} +{"idx":23667,"func":"err_status_t srtp_unprotect_rtcp ( srtp_t ctx , void * srtcp_hdr , int * pkt_octet_len ) {\n srtcp_hdr_t * hdr = ( srtcp_hdr_t * ) srtcp_hdr ;\n uint32_t * enc_start ;\n uint32_t * auth_start ;\n uint32_t * trailer ;\n unsigned int enc_octet_len = 0 ;\n uint8_t * auth_tag = NULL ;\n uint8_t tmp_tag [ SRTP_MAX_TAG_LEN ] ;\n uint8_t tag_copy [ SRTP_MAX_TAG_LEN ] ;\n err_status_t status ;\n unsigned int auth_len ;\n int tag_len ;\n srtp_stream_ctx_t * stream ;\n int prefix_len ;\n uint32_t seq_num ;\n int e_bit_in_packet ;\n int sec_serv_confidentiality ;\n if ( * pkt_octet_len < octets_in_rtcp_header + sizeof ( srtcp_trailer_t ) ) return err_status_bad_param ;\n stream = srtp_get_stream ( ctx , hdr -> ssrc ) ;\n if ( stream == NULL ) {\n if ( ctx -> stream_template != NULL ) {\n stream = ctx -> stream_template ;\n if ( stream -> ekt != NULL ) {\n status = srtp_stream_init_from_ekt ( stream , srtcp_hdr , * pkt_octet_len ) ;\n if ( status ) return status ;\n }\n debug_print ( mod_srtp , \"srtcp using provisional stream (SSRC: 0x%08x)\" , hdr -> ssrc ) ;\n }\n else {\n return err_status_no_ctx ;\n }\n }\n tag_len = auth_get_tag_length ( stream -> rtcp_auth ) ;\n if ( * pkt_octet_len < ( int ) ( octets_in_rtcp_header + tag_len + sizeof ( srtcp_trailer_t ) ) ) {\n return err_status_bad_param ;\n }\n if ( stream -> rtp_cipher -> algorithm == AES_128_GCM || stream -> rtp_cipher -> algorithm == AES_256_GCM ) {\n return srtp_unprotect_rtcp_aead ( ctx , stream , srtcp_hdr , ( unsigned int * ) pkt_octet_len ) ;\n }\n sec_serv_confidentiality = stream -> rtcp_services == sec_serv_conf || stream -> rtcp_services == sec_serv_conf_and_auth ;\n enc_octet_len = * pkt_octet_len - ( octets_in_rtcp_header + tag_len + sizeof ( srtcp_trailer_t ) ) ;\n trailer = ( uint32_t * ) ( ( char * ) hdr + * pkt_octet_len - ( tag_len + sizeof ( srtcp_trailer_t ) ) ) ;\n e_bit_in_packet = ( * ( ( unsigned char * ) trailer ) & SRTCP_E_BYTE_BIT ) == SRTCP_E_BYTE_BIT ;\n if ( e_bit_in_packet != sec_serv_confidentiality ) {\n return err_status_cant_check ;\n }\n if ( sec_serv_confidentiality ) {\n enc_start = ( uint32_t * ) hdr + uint32s_in_rtcp_header ;\n }\n else {\n enc_octet_len = 0 ;\n enc_start = NULL ;\n }\n auth_start = ( uint32_t * ) hdr ;\n auth_len = * pkt_octet_len - tag_len ;\n auth_tag = ( uint8_t * ) hdr + auth_len ;\n if ( stream -> ekt ) {\n auth_tag -= ekt_octets_after_base_tag ( stream -> ekt ) ;\n memcpy ( tag_copy , auth_tag , tag_len ) ;\n octet_string_set_to_zero ( auth_tag , tag_len ) ;\n auth_tag = tag_copy ;\n auth_len += tag_len ;\n }\n seq_num = ntohl ( * trailer ) & SRTCP_INDEX_MASK ;\n debug_print ( mod_srtp , \"srtcp index: %x\" , seq_num ) ;\n status = rdb_check ( & stream -> rtcp_rdb , seq_num ) ;\n if ( status ) return status ;\n if ( stream -> rtcp_cipher -> type -> id == AES_ICM ) {\n v128_t iv ;\n iv . v32 [ 0 ] = 0 ;\n iv . v32 [ 1 ] = hdr -> ssrc ;\n iv . v32 [ 2 ] = htonl ( seq_num >> 16 ) ;\n iv . v32 [ 3 ] = htonl ( seq_num << 16 ) ;\n status = cipher_set_iv ( stream -> rtcp_cipher , & iv , direction_decrypt ) ;\n }\n else {\n v128_t iv ;\n iv . v32 [ 0 ] = 0 ;\n iv . v32 [ 1 ] = 0 ;\n iv . v32 [ 2 ] = 0 ;\n iv . v32 [ 3 ] = htonl ( seq_num ) ;\n status = cipher_set_iv ( stream -> rtcp_cipher , & iv , direction_decrypt ) ;\n }\n if ( status ) return err_status_cipher_fail ;\n auth_start ( stream -> rtcp_auth ) ;\n status = auth_compute ( stream -> rtcp_auth , ( uint8_t * ) auth_start , auth_len , tmp_tag ) ;\n debug_print ( mod_srtp , \"srtcp computed tag: %s\" , octet_string_hex_string ( tmp_tag , tag_len ) ) ;\n if ( status ) return err_status_auth_fail ;\n debug_print ( mod_srtp , \"srtcp tag from packet: %s\" , octet_string_hex_string ( auth_tag , tag_len ) ) ;\n if ( octet_string_is_eq ( tmp_tag , auth_tag , tag_len ) ) return err_status_auth_fail ;\n prefix_len = auth_get_prefix_length ( stream -> rtcp_auth ) ;\n if ( prefix_len ) {\n status = cipher_output ( stream -> rtcp_cipher , auth_tag , prefix_len ) ;\n debug_print ( mod_srtp , \"keystream prefix: %s\" , octet_string_hex_string ( auth_tag , prefix_len ) ) ;\n if ( status ) return err_status_cipher_fail ;\n }\n if ( enc_start ) {\n status = cipher_decrypt ( stream -> rtcp_cipher , ( uint8_t * ) enc_start , & enc_octet_len ) ;\n if ( status ) return err_status_cipher_fail ;\n }\n * pkt_octet_len -= ( tag_len + sizeof ( srtcp_trailer_t ) ) ;\n * pkt_octet_len -= ekt_octets_after_base_tag ( stream -> ekt ) ;\n if ( stream -> direction != dir_srtp_receiver ) {\n if ( stream -> direction == dir_unknown ) {\n stream -> direction = dir_srtp_receiver ;\n }\n else {\n srtp_handle_event ( ctx , stream , event_ssrc_collision ) ;\n }\n }\n if ( stream == ctx -> stream_template ) {\n srtp_stream_ctx_t * new_stream ;\n status = srtp_stream_clone ( ctx -> stream_template , hdr -> ssrc , & new_stream ) ;\n if ( status ) return status ;\n new_stream -> next = ctx -> stream_list ;\n ctx -> stream_list = new_stream ;\n stream = new_stream ;\n }\n rdb_add_index ( & stream -> rtcp_rdb , seq_num ) ;\n return err_status_ok ;\n }","target":0,"code_token_length":1461,"total_token_length":1792,"max_tokens_setting":2048} +{"idx":129982,"func":"static ssize_t _hostsock_recvmsg(\n oe_fd_t* sock_,\n struct oe_msghdr* msg,\n int flags)\n{\n ssize_t ret = -1;\n sock_t* sock = _cast_sock(sock_);\n oe_errno = 0;\n void* buf = NULL;\n size_t buf_size = 0;\n size_t data_size = 0;\n oe_socklen_t namelen_out = 0;\n size_t controllen_out = 0;\n\n \/* Check the parameters. *\/\n if (!sock || !msg || (msg->msg_iovlen && !msg->msg_iov))\n OE_RAISE_ERRNO(OE_EINVAL);\n\n \/* Flatten the IO vector into contiguous heap memory. *\/\n if (oe_iov_pack(\n msg->msg_iov, (int)msg->msg_iovlen, &buf, &buf_size, &data_size) !=\n 0)\n OE_RAISE_ERRNO(OE_ENOMEM);\n\n \/*\n * According to the POSIX specification, when the data_size is greater\n * than SSIZE_MAX, the result is implementation-defined. OE raises an\n * error in this case.\n * Refer to\n * https:\/\/pubs.opengroup.org\/onlinepubs\/9699919799\/functions\/recvmsg.html\n * for more detail.\n *\/\n if (data_size > OE_SSIZE_MAX)\n OE_RAISE_ERRNO(OE_EINVAL);\n\n \/* Call the host. *\/\n {\n if (oe_syscall_recvmsg_ocall(\n &ret,\n sock->host_fd,\n msg->msg_name,\n msg->msg_namelen,\n &namelen_out,\n buf,\n msg->msg_iovlen,\n buf_size,\n msg->msg_control,\n msg->msg_controllen,\n &controllen_out,\n flags) != OE_OK)\n {\n OE_RAISE_ERRNO(OE_EINVAL);\n }\n\n if (ret == -1)\n OE_RAISE_ERRNO(oe_errno);\n }\n\n if (!msg->msg_name)\n msg->msg_namelen = 0;\n else\n {\n \/*\n * Error out the case if the namelen_out is greater than the size\n * of sockaddr_storage.\n *\/\n if (namelen_out > sizeof(struct oe_sockaddr_storage))\n OE_RAISE_ERRNO(OE_EINVAL);\n\n \/*\n * Note that the returned value can still exceed the supplied one,\n * which indicates a truncation.\n *\/\n if (msg->msg_namelen >= namelen_out)\n msg->msg_namelen = namelen_out;\n }\n\n if (!msg->msg_control)\n msg->msg_controllen = 0;\n else\n {\n \/*\n * Update the msg_controllen only if the supplied value is greater than\n * or equal to the returned value. Otherwise, keep the msg_controllen\n * unchanged, which indicates a truncation. In addition, explicitly\n * setting the MSG_CTRUNC flag when the truncation occurs.\n *\/\n if (msg->msg_controllen >= controllen_out)\n msg->msg_controllen = controllen_out;\n else\n msg->msg_flags |= OE_MSG_CTRUNC;\n }\n\n \/*\n * Guard the special case that a host sets an arbitrarily large value.\n * The return value should not exceed data_size.\n *\/\n if (ret > (ssize_t)data_size)\n {\n ret = -1;\n OE_RAISE_ERRNO(OE_EINVAL);\n }\n\n \/* Synchronize data read with IO vector. *\/\n if (oe_iov_sync(msg->msg_iov, (int)msg->msg_iovlen, buf, buf_size) != 0)\n OE_RAISE_ERRNO(OE_EINVAL);\n\ndone:\n\n if (buf)\n oe_free(buf);\n\n return ret;\n}","target":0,"code_token_length":845,"total_token_length":1176,"max_tokens_setting":2048} +{"idx":88241,"func":"int openssl_push_general_name(lua_State*L, const GENERAL_NAME* general_name)\n{\n if (general_name == NULL)\n {\n lua_pushnil(L);\n return 1;\n }\n lua_newtable(L);\n\n switch (general_name->type)\n {\n case GEN_OTHERNAME:\n {\n OTHERNAME *otherName = general_name->d.otherName;\n lua_newtable(L);\n openssl_push_asn1object(L, otherName->type_id);\n PUSH_ASN1_STRING(L, otherName->value->value.asn1_string);\n lua_settable(L, -3);\n lua_setfield(L, -2, \"otherName\");\n\n lua_pushstring(L, \"otherName\");\n lua_setfield(L, -2, \"type\");\n break;\n }\n case GEN_EMAIL:\n PUSH_ASN1_STRING(L, general_name->d.rfc822Name);\n lua_setfield(L, -2, \"rfc822Name\");\n\n lua_pushstring(L, \"rfc822Name\");\n lua_setfield(L, -2, \"type\");\n break;\n case GEN_DNS:\n PUSH_ASN1_STRING(L, general_name->d.dNSName);\n lua_setfield(L, -2, \"dNSName\");\n lua_pushstring(L, \"dNSName\");\n lua_setfield(L, -2, \"type\");\n break;\n case GEN_X400:\n openssl_push_asn1type(L, general_name->d.x400Address);\n lua_setfield(L, -2, \"x400Address\");\n lua_pushstring(L, \"x400Address\");\n lua_setfield(L, -2, \"type\");\n break;\n case GEN_DIRNAME:\n {\n X509_NAME* xn = general_name->d.directoryName;\n openssl_push_xname_asobject(L, xn);\n lua_setfield(L, -2, \"directoryName\");\n lua_pushstring(L, \"directoryName\");\n lua_setfield(L, -2, \"type\");\n }\n break;\n case GEN_URI:\n PUSH_ASN1_STRING(L, general_name->d.uniformResourceIdentifier);\n lua_setfield(L, -2, \"uniformResourceIdentifier\");\n lua_pushstring(L, \"uniformResourceIdentifier\");\n lua_setfield(L, -2, \"type\");\n break;\n case GEN_IPADD:\n lua_newtable(L);\n PUSH_ASN1_OCTET_STRING(L, general_name->d.iPAddress);\n lua_setfield(L, -2, \"iPAddress\");\n lua_pushstring(L, \"iPAddress\");\n lua_setfield(L, -2, \"type\");\n break;\n case GEN_EDIPARTY:\n lua_newtable(L);\n PUSH_ASN1_STRING(L, general_name->d.ediPartyName->nameAssigner);\n lua_setfield(L, -2, \"nameAssigner\");\n PUSH_ASN1_STRING(L, general_name->d.ediPartyName->partyName);\n lua_setfield(L, -2, \"partyName\");\n lua_setfield(L, -2, \"ediPartyName\");\n\n lua_pushstring(L, \"ediPartyName\");\n lua_setfield(L, -2, \"type\");\n break;\n case GEN_RID:\n lua_newtable(L);\n openssl_push_asn1object(L, general_name->d.registeredID);\n lua_setfield(L, -2, \"registeredID\");\n lua_pushstring(L, \"registeredID\");\n lua_setfield(L, -2, \"type\");\n break;\n default:\n lua_pushstring(L, \"unsupport\");\n lua_setfield(L, -2, \"type\");\n }\n return 1;\n};","target":0,"code_token_length":800,"total_token_length":1131,"max_tokens_setting":2048} +{"idx":483915,"func":"static int really_probe(struct device *dev, struct device_driver *drv)\n{\n\tint ret = -EPROBE_DEFER;\n\tint local_trigger_count = atomic_read(&deferred_trigger_count);\n\tbool test_remove = IS_ENABLED(CONFIG_DEBUG_TEST_DRIVER_REMOVE) &&\n\t\t\t !drv->suppress_bind_attrs;\n\n\tif (defer_all_probes) {\n\t\t\/*\n\t\t * Value of defer_all_probes can be set only by\n\t\t * device_block_probing() which, in turn, will call\n\t\t * wait_for_device_probe() right after that to avoid any races.\n\t\t *\/\n\t\tdev_dbg(dev, \"Driver %s force probe deferral\\n\", drv->name);\n\t\tdriver_deferred_probe_add(dev);\n\t\treturn ret;\n\t}\n\n\tret = device_links_check_suppliers(dev);\n\tif (ret == -EPROBE_DEFER)\n\t\tdriver_deferred_probe_add_trigger(dev, local_trigger_count);\n\tif (ret)\n\t\treturn ret;\n\n\tatomic_inc(&probe_count);\n\tpr_debug(\"bus: '%s': %s: probing driver %s with device %s\\n\",\n\t\t drv->bus->name, __func__, drv->name, dev_name(dev));\n\tif (!list_empty(&dev->devres_head)) {\n\t\tdev_crit(dev, \"Resources present before probing\\n\");\n\t\tret = -EBUSY;\n\t\tgoto done;\n\t}\n\nre_probe:\n\tdev->driver = drv;\n\n\t\/* If using pinctrl, bind pins now before probing *\/\n\tret = pinctrl_bind_pins(dev);\n\tif (ret)\n\t\tgoto pinctrl_bind_failed;\n\n\tif (dev->bus->dma_configure) {\n\t\tret = dev->bus->dma_configure(dev);\n\t\tif (ret)\n\t\t\tgoto probe_failed;\n\t}\n\n\tif (driver_sysfs_add(dev)) {\n\t\tpr_err(\"%s: driver_sysfs_add(%s) failed\\n\",\n\t\t __func__, dev_name(dev));\n\t\tgoto probe_failed;\n\t}\n\n\tif (dev->pm_domain && dev->pm_domain->activate) {\n\t\tret = dev->pm_domain->activate(dev);\n\t\tif (ret)\n\t\t\tgoto probe_failed;\n\t}\n\n\tif (dev->bus->probe) {\n\t\tret = dev->bus->probe(dev);\n\t\tif (ret)\n\t\t\tgoto probe_failed;\n\t} else if (drv->probe) {\n\t\tret = drv->probe(dev);\n\t\tif (ret)\n\t\t\tgoto probe_failed;\n\t}\n\n\tif (device_add_groups(dev, drv->dev_groups)) {\n\t\tdev_err(dev, \"device_add_groups() failed\\n\");\n\t\tgoto dev_groups_failed;\n\t}\n\n\tif (dev_has_sync_state(dev) &&\n\t device_create_file(dev, &dev_attr_state_synced)) {\n\t\tdev_err(dev, \"state_synced sysfs add failed\\n\");\n\t\tgoto dev_sysfs_state_synced_failed;\n\t}\n\n\tif (test_remove) {\n\t\ttest_remove = false;\n\n\t\tdevice_remove_file(dev, &dev_attr_state_synced);\n\t\tdevice_remove_groups(dev, drv->dev_groups);\n\n\t\tif (dev->bus->remove)\n\t\t\tdev->bus->remove(dev);\n\t\telse if (drv->remove)\n\t\t\tdrv->remove(dev);\n\n\t\tdevres_release_all(dev);\n\t\tdriver_sysfs_remove(dev);\n\t\tdev->driver = NULL;\n\t\tdev_set_drvdata(dev, NULL);\n\t\tif (dev->pm_domain && dev->pm_domain->dismiss)\n\t\t\tdev->pm_domain->dismiss(dev);\n\t\tpm_runtime_reinit(dev);\n\n\t\tgoto re_probe;\n\t}\n\n\tpinctrl_init_done(dev);\n\n\tif (dev->pm_domain && dev->pm_domain->sync)\n\t\tdev->pm_domain->sync(dev);\n\n\tdriver_bound(dev);\n\tret = 1;\n\tpr_debug(\"bus: '%s': %s: bound device %s to driver %s\\n\",\n\t\t drv->bus->name, __func__, dev_name(dev), drv->name);\n\tgoto done;\n\ndev_sysfs_state_synced_failed:\n\tdevice_remove_groups(dev, drv->dev_groups);\ndev_groups_failed:\n\tif (dev->bus->remove)\n\t\tdev->bus->remove(dev);\n\telse if (drv->remove)\n\t\tdrv->remove(dev);\nprobe_failed:\n\tif (dev->bus)\n\t\tblocking_notifier_call_chain(&dev->bus->p->bus_notifier,\n\t\t\t\t\t BUS_NOTIFY_DRIVER_NOT_BOUND, dev);\npinctrl_bind_failed:\n\tdevice_links_no_driver(dev);\n\tdevres_release_all(dev);\n\tarch_teardown_dma_ops(dev);\n\tdriver_sysfs_remove(dev);\n\tdev->driver = NULL;\n\tdev_set_drvdata(dev, NULL);\n\tif (dev->pm_domain && dev->pm_domain->dismiss)\n\t\tdev->pm_domain->dismiss(dev);\n\tpm_runtime_reinit(dev);\n\tdev_pm_set_driver_flags(dev, 0);\n\n\tswitch (ret) {\n\tcase -EPROBE_DEFER:\n\t\t\/* Driver requested deferred probing *\/\n\t\tdev_dbg(dev, \"Driver %s requests probe deferral\\n\", drv->name);\n\t\tdriver_deferred_probe_add_trigger(dev, local_trigger_count);\n\t\tbreak;\n\tcase -ENODEV:\n\tcase -ENXIO:\n\t\tpr_debug(\"%s: probe of %s rejects match %d\\n\",\n\t\t\t drv->name, dev_name(dev), ret);\n\t\tbreak;\n\tdefault:\n\t\t\/* driver matched but the probe failed *\/\n\t\tpr_warn(\"%s: probe of %s failed with error %d\\n\",\n\t\t\tdrv->name, dev_name(dev), ret);\n\t}\n\t\/*\n\t * Ignore errors returned by ->probe so that the next driver can try\n\t * its luck.\n\t *\/\n\tret = 0;\ndone:\n\tatomic_dec(&probe_count);\n\twake_up_all(&probe_waitqueue);\n\treturn ret;\n}","target":0,"code_token_length":1153,"total_token_length":1484,"max_tokens_setting":2048} +{"idx":346847,"func":"int main(int argc, char **argv)\n{\n MYSQL mysql;\n option_string *eptr;\n\n MY_INIT(argv[0]);\n\n if (load_defaults(\"my\",load_default_groups,&argc,&argv))\n {\n my_end(0);\n exit(1);\n }\n defaults_argv=argv;\n if (get_options(&argc,&argv))\n {\n free_defaults(defaults_argv);\n my_end(0);\n exit(1);\n }\n\n \/* Seed the random number generator if we will be using it. *\/\n if (auto_generate_sql)\n srandom((uint)time(NULL));\n\n \/* globals? Yes, so we only have to run strlen once *\/\n delimiter_length= strlen(delimiter);\n\n if (argc > 2)\n {\n fprintf(stderr,\"%s: Too many arguments\\n\",my_progname);\n free_defaults(defaults_argv);\n my_end(0);\n exit(1);\n }\n mysql_init(&mysql);\n if (opt_compress)\n mysql_options(&mysql,MYSQL_OPT_COMPRESS,NullS);\n#ifdef HAVE_OPENSSL\n if (opt_use_ssl)\n mysql_ssl_set(&mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,\n opt_ssl_capath, opt_ssl_cipher);\n#endif\n if (opt_protocol)\n mysql_options(&mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);\n#ifdef HAVE_SMEM\n if (shared_memory_base_name)\n mysql_options(&mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);\n#endif\n mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, default_charset);\n\n if (opt_plugin_dir && *opt_plugin_dir)\n mysql_options(&mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir);\n\n if (opt_default_auth && *opt_default_auth)\n mysql_options(&mysql, MYSQL_DEFAULT_AUTH, opt_default_auth);\n\n if (using_opt_enable_cleartext_plugin)\n mysql_options(&mysql, MYSQL_ENABLE_CLEARTEXT_PLUGIN, \n (char*) &opt_enable_cleartext_plugin);\n if (!opt_only_print) \n {\n if (!(mysql_connect_ssl_check(&mysql, host, user, opt_password,\n NULL, opt_mysql_port, opt_mysql_unix_port,\n connect_flags, opt_ssl_required)))\n {\n fprintf(stderr,\"%s: Error when connecting to server: %s\\n\",\n my_progname,mysql_error(&mysql));\n free_defaults(defaults_argv);\n my_end(0);\n exit(1);\n }\n }\n\n pthread_mutex_init(&counter_mutex, NULL);\n pthread_cond_init(&count_threshhold, NULL);\n pthread_mutex_init(&sleeper_mutex, NULL);\n pthread_cond_init(&sleep_threshhold, NULL);\n\n \/* Main iterations loop *\/\n eptr= engine_options;\n do\n {\n \/* For the final stage we run whatever queries we were asked to run *\/\n uint *current;\n\n if (verbose >= 2)\n printf(\"Starting Concurrency Test\\n\");\n\n if (*concurrency)\n {\n for (current= concurrency; current && *current; current++)\n concurrency_loop(&mysql, *current, eptr);\n }\n else\n {\n uint infinite= 1;\n do {\n concurrency_loop(&mysql, infinite, eptr);\n }\n while (infinite++);\n }\n\n if (!opt_preserve)\n drop_schema(&mysql, create_schema_string);\n\n } while (eptr ? (eptr= eptr->next) : 0);\n\n pthread_mutex_destroy(&counter_mutex);\n pthread_cond_destroy(&count_threshhold);\n pthread_mutex_destroy(&sleeper_mutex);\n pthread_cond_destroy(&sleep_threshhold);\n\n if (!opt_only_print) \n mysql_close(&mysql); \/* Close & free connection *\/\n\n \/* now free all the strings we created *\/\n my_free(opt_password);\n my_free(concurrency);\n\n statement_cleanup(create_statements);\n statement_cleanup(query_statements);\n statement_cleanup(pre_statements);\n statement_cleanup(post_statements);\n option_cleanup(engine_options);\n\n#ifdef HAVE_SMEM\n my_free(shared_memory_base_name);\n#endif\n free_defaults(defaults_argv);\n my_end(my_end_arg);\n\n return 0;\n}","target":1,"code_token_length":876,"total_token_length":1207,"max_tokens_setting":2048} +{"idx":519747,"func":"void prepare_frm_header(THD *thd, uint reclength, uchar *fileinfo,\n HA_CREATE_INFO *create_info, uint keys, KEY *key_info)\n{\n ulong key_comment_total_bytes= 0;\n uint i;\n DBUG_ENTER(\"prepare_frm_header\");\n\n \/* Fix this when we have new .frm files; Current limit is 4G rows (TODO) *\/\n if (create_info->max_rows > UINT_MAX32)\n create_info->max_rows= UINT_MAX32;\n if (create_info->min_rows > UINT_MAX32)\n create_info->min_rows= UINT_MAX32;\n\n uint key_length, tmp_key_length, tmp, csid;\n bzero((char*) fileinfo, FRM_HEADER_SIZE);\n \/* header *\/\n fileinfo[0]=(uchar) 254;\n fileinfo[1]= 1;\n fileinfo[2]= (create_info->expression_length == 0 ? FRM_VER_TRUE_VARCHAR :\n FRM_VER_EXPRESSSIONS);\n\n DBUG_ASSERT(ha_storage_engine_is_enabled(create_info->db_type));\n fileinfo[3]= (uchar) ha_legacy_type(create_info->db_type);\n\n \/*\n Keep in sync with pack_keys() in unireg.cc\n For each key:\n 8 bytes for the key header\n 9 bytes for each key-part (MAX_REF_PARTS)\n NAME_LEN bytes for the name\n 1 byte for the NAMES_SEP_CHAR (before the name)\n For all keys:\n 6 bytes for the header\n 1 byte for the NAMES_SEP_CHAR (after the last name)\n 9 extra bytes (padding for safety? alignment?)\n *\/\n for (i= 0; i < keys; i++)\n {\n DBUG_ASSERT(MY_TEST(key_info[i].flags & HA_USES_COMMENT) ==\n (key_info[i].comment.length > 0));\n if (key_info[i].flags & HA_USES_COMMENT)\n key_comment_total_bytes += 2 + key_info[i].comment.length;\n }\n\n key_length= keys * (8 + MAX_REF_PARTS * 9 + NAME_LEN + 1) + 16\n + key_comment_total_bytes;\n\n int2store(fileinfo+8,1);\n tmp_key_length= (key_length < 0xffff) ? key_length : 0xffff;\n int2store(fileinfo+14,tmp_key_length);\n int2store(fileinfo+16,reclength);\n int4store(fileinfo+18,create_info->max_rows);\n int4store(fileinfo+22,create_info->min_rows);\n \/* fileinfo[26] is set in mysql_create_frm() *\/\n fileinfo[27]=2;\t\t\t\t\/\/ Use long pack-fields\n \/* fileinfo[28 & 29] is set to key_info_length in mysql_create_frm() *\/\n create_info->table_options|=HA_OPTION_LONG_BLOB_PTR; \/\/ Use portable blob pointers\n int2store(fileinfo+30,create_info->table_options);\n fileinfo[32]=0;\t\t\t\t\/\/ No filename anymore\n fileinfo[33]=5; \/\/ Mark for 5.0 frm file\n int4store(fileinfo+34,create_info->avg_row_length);\n csid= (create_info->default_table_charset ?\n create_info->default_table_charset->number : 0);\n fileinfo[38]= (uchar) csid;\n fileinfo[39]= (uchar) ((uint) create_info->transactional |\n ((uint) create_info->page_checksum << 2));\n fileinfo[40]= (uchar) create_info->row_type;\n \/* Bytes 41-46 were for RAID support; now reused for other purposes *\/\n fileinfo[41]= (uchar) (csid >> 8);\n int2store(fileinfo+42, create_info->stats_sample_pages & 0xffff);\n fileinfo[44]= (uchar) create_info->stats_auto_recalc;\n int2store(fileinfo+45, (create_info->check_constraint_list->elements+\n create_info->field_check_constraints));\n int4store(fileinfo+47, key_length);\n tmp= MYSQL_VERSION_ID; \/\/ Store to avoid warning from int4store\n int4store(fileinfo+51, tmp);\n int4store(fileinfo+55, create_info->extra_size);\n \/*\n 59-60 is unused since 10.2.4\n 61 for default_part_db_type\n *\/\n int2store(fileinfo+62, create_info->key_block_size);\n DBUG_VOID_RETURN;\n} \/* prepare_fileinfo *\/","target":0,"code_token_length":1026,"total_token_length":1357,"max_tokens_setting":2048} +{"idx":318491,"func":"static inline void RENAME(yuvPlanartouyvy)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,\n\n long width, long height,\n\n long lumStride, long chromStride, long dstStride, long vertLumPerChroma)\n\n{\n\n long y;\n\n const x86_reg chromWidth= width>>1;\n\n for (y=0; yyuy2\n\n\n\n#if HAVE_FAST_64BIT\n\n int i;\n\n uint64_t *ldst = (uint64_t *) dst;\n\n const uint8_t *yc = ysrc, *uc = usrc, *vc = vsrc;\n\n for (i = 0; i < chromWidth; i += 2) {\n\n uint64_t k, l;\n\n k = uc[0] + (yc[0] << 8) +\n\n (vc[0] << 16) + (yc[1] << 24);\n\n l = uc[1] + (yc[2] << 8) +\n\n (vc[1] << 16) + (yc[3] << 24);\n\n *ldst++ = k + (l << 32);\n\n yc += 4;\n\n uc += 2;\n\n vc += 2;\n\n }\n\n\n\n#else\n\n int i, *idst = (int32_t *) dst;\n\n const uint8_t *yc = ysrc, *uc = usrc, *vc = vsrc;\n\n for (i = 0; i < chromWidth; i++) {\n\n#if HAVE_BIGENDIAN\n\n *idst++ = (uc[0] << 24)+ (yc[0] << 16) +\n\n (vc[0] << 8) + (yc[1] << 0);\n\n#else\n\n *idst++ = uc[0] + (yc[0] << 8) +\n\n (vc[0] << 16) + (yc[1] << 24);\n\n#endif\n\n yc += 2;\n\n uc++;\n\n vc++;\n\n }\n\n#endif\n\n#endif\n\n if ((y&(vertLumPerChroma-1)) == vertLumPerChroma-1) {\n\n usrc += chromStride;\n\n vsrc += chromStride;\n\n }\n\n ysrc += lumStride;\n\n dst += dstStride;\n\n }\n\n#if COMPILE_TEMPLATE_MMX\n\n __asm__(EMMS\" \\n\\t\"\n\n SFENCE\" \\n\\t\"\n\n :::\"memory\");\n\n#endif\n\n}\n","target":0,"code_token_length":1286,"total_token_length":1617,"max_tokens_setting":2048} +{"idx":8065,"func":"static int jpc_pi_nextpcrl(register jpc_pi_t *pi)\n{\n\tint rlvlno;\n\tjpc_pirlvl_t *pirlvl;\n\tjpc_pchg_t *pchg;\n\tint prchind;\n\tint prcvind;\n\tint *prclyrno;\n\tint compno;\n\tjpc_picomp_t *picomp;\n\tint xstep;\n\tint ystep;\n\tuint_fast32_t trx0;\n\tuint_fast32_t try0;\n\tuint_fast32_t r;\n\tuint_fast32_t rpx;\n\tuint_fast32_t rpy;\n\n\tpchg = pi->pchg;\n\tif (!pi->prgvolfirst) {\n\t\tgoto skip;\n\t} else {\n\t\tpi->xstep = 0;\n\t\tpi->ystep = 0;\n\t\tfor (compno = 0, picomp = pi->picomps; compno < pi->numcomps;\n\t\t ++compno, ++picomp) {\n\t\t\tfor (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno <\n\t\t\t picomp->numrlvls; ++rlvlno, ++pirlvl) {\n\t\t\t\txstep = picomp->hsamp * (1 <<\n\t\t\t\t (pirlvl->prcwidthexpn + picomp->numrlvls -\n\t\t\t\t rlvlno - 1));\n\t\t\t\tystep = picomp->vsamp * (1 <<\n\t\t\t\t (pirlvl->prcheightexpn + picomp->numrlvls -\n\t\t\t\t rlvlno - 1));\n\t\t\t\tpi->xstep = (!pi->xstep) ? xstep :\n\t\t\t\t JAS_MIN(pi->xstep, xstep);\n\t\t\t\tpi->ystep = (!pi->ystep) ? ystep :\n\t\t\t\t JAS_MIN(pi->ystep, ystep);\n\t\t\t}\n\t\t}\n\t\tpi->prgvolfirst = 0;\n\t}\n\n\tfor (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep -\n\t (pi->y % pi->ystep)) {\n\t\tfor (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep -\n\t\t (pi->x % pi->xstep)) {\n\t\t\tfor (pi->compno = pchg->compnostart, pi->picomp =\n\t\t\t &pi->picomps[pi->compno]; pi->compno < pi->numcomps\n\t\t\t && pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno,\n\t\t\t ++pi->picomp) {\n\t\t\t\tfor (pi->rlvlno = pchg->rlvlnostart,\n\t\t\t\t pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno];\n\t\t\t\t pi->rlvlno < pi->picomp->numrlvls &&\n\t\t\t\t pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno,\n\t\t\t\t ++pi->pirlvl) {\n\t\t\t\t\tif (pi->pirlvl->numprcs == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tr = pi->picomp->numrlvls - 1 - pi->rlvlno;\n\t\t\t\t\ttrx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r);\n\t\t\t\t\ttry0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r);\n\t\t\t\t\trpx = r + pi->pirlvl->prcwidthexpn;\n\t\t\t\t\trpy = r + pi->pirlvl->prcheightexpn;\n\t\t\t\t\tif (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) ||\n\t\t\t\t\t !(pi->x % (pi->picomp->hsamp << rpx))) &&\n\t\t\t\t\t ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) ||\n\t\t\t\t\t !(pi->y % (pi->picomp->vsamp << rpy)))) {\n\t\t\t\t\t\tprchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp\n\t\t\t\t\t\t << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0,\n\t\t\t\t\t\t pi->pirlvl->prcwidthexpn);\n\t\t\t\t\t\tprcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp\n\t\t\t\t\t\t << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0,\n\t\t\t\t\t\t pi->pirlvl->prcheightexpn);\n\t\t\t\t\t\tpi->prcno = prcvind * pi->pirlvl->numhprcs + prchind;\n\t\t\t\t\t\tassert(pi->prcno < pi->pirlvl->numprcs);\n\t\t\t\t\t\tfor (pi->lyrno = 0; pi->lyrno < pi->numlyrs &&\n\t\t\t\t\t\t pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) {\n\t\t\t\t\t\t\tprclyrno = &pi->pirlvl->prclyrnos[pi->prcno];\n\t\t\t\t\t\t\tif (pi->lyrno >= *prclyrno) {\n\t\t\t\t\t\t\t\t++(*prclyrno);\n\t\t\t\t\t\t\t\treturn 0;\n\t\t\t\t\t\t\t}\nskip:\n\t\t\t\t\t\t\t;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 1;\n}","target":1,"code_token_length":1208,"total_token_length":1539,"max_tokens_setting":2048} +{"idx":350397,"func":"int cancel_extop( Operation *op, SlapReply *rs )\n{\n\tOperation *o;\n\tint rc;\n\tint opid;\n\tBerElementBuffer berbuf;\n\tBerElement *ber = (BerElement *)&berbuf;\n\n\tassert( ber_bvcmp( &slap_EXOP_CANCEL, &op->ore_reqoid ) == 0 );\n\n\tif ( op->ore_reqdata == NULL ) {\n\t\trs->sr_text = \"no message ID supplied\";\n\t\treturn LDAP_PROTOCOL_ERROR;\n\t}\n\n\tif ( op->ore_reqdata->bv_len == 0 ) {\n\t\trs->sr_text = \"empty request data field\";\n\t\treturn LDAP_PROTOCOL_ERROR;\n\t}\n\n\t\/* ber_init2 uses reqdata directly, doesn't allocate new buffers *\/\n\tber_init2( ber, op->ore_reqdata, 0 );\n\n\tif ( ber_scanf( ber, \"{i}\", &opid ) == LBER_ERROR ) {\n\t\trs->sr_text = \"message ID parse failed\";\n\t\treturn LDAP_PROTOCOL_ERROR;\n\t}\n\n\tStatslog( LDAP_DEBUG_STATS, \"%s CANCEL msg=%d\\n\",\n\t\top->o_log_prefix, opid, 0, 0, 0 );\n\n\tif ( opid < 0 ) {\n\t\trs->sr_text = \"message ID invalid\";\n\t\treturn LDAP_PROTOCOL_ERROR;\n\t}\n\n\tldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );\n\n\tif ( op->o_abandon ) {\n\t\t\/* FIXME: Should instead reject the cancel\/abandon of this op, but\n\t\t * it seems unsafe to reset op->o_abandon once it is set. ITS#6138.\n\t\t *\/\n\t\trc = LDAP_OPERATIONS_ERROR;\n\t\trs->sr_text = \"tried to abandon or cancel this operation\";\n\t\tgoto out;\n\t}\n\n\tLDAP_STAILQ_FOREACH( o, &op->o_conn->c_pending_ops, o_next ) {\n\t\tif ( o->o_msgid == opid ) {\n\t\t\t\/* TODO: We could instead remove the cancelled operation\n\t\t\t * from c_pending_ops like Abandon does, and send its\n\t\t\t * response here. Not if it is pending because of a\n\t\t\t * congested connection though.\n\t\t\t *\/\n\t\t\trc = LDAP_CANNOT_CANCEL;\n\t\t\trs->sr_text = \"too busy for Cancel, try Abandon instead\";\n\t\t\tgoto out;\n\t\t}\n\t}\n\n\tLDAP_STAILQ_FOREACH( o, &op->o_conn->c_ops, o_next ) {\n\t\tif ( o->o_msgid == opid ) {\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif ( o == NULL ) {\n\t \trc = LDAP_NO_SUCH_OPERATION;\n\t\trs->sr_text = \"message ID not found\";\n\n\t} else if ( o->o_tag == LDAP_REQ_BIND\n\t\t\t|| o->o_tag == LDAP_REQ_UNBIND\n\t\t\t|| o->o_tag == LDAP_REQ_ABANDON ) {\n\t\trc = LDAP_CANNOT_CANCEL;\n\n\t} else if ( o->o_cancel != SLAP_CANCEL_NONE ) {\n\t\trc = LDAP_OPERATIONS_ERROR;\n\t\trs->sr_text = \"message ID already being cancelled\";\n\n#if 0\n\t} else if ( o->o_abandon ) {\n\t\t\/* TODO: Would this break something when\n\t\t * o_abandon=\"suppress response\"? (ITS#6138)\n\t\t *\/\n\t\trc = LDAP_TOO_LATE;\n#endif\n\n\t} else {\n\t\trc = LDAP_SUCCESS;\n\t\to->o_cancel = SLAP_CANCEL_REQ;\n\t\to->o_abandon = 1;\n\t}\n\n out:\n\tldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );\n\n\tif ( rc == LDAP_SUCCESS ) {\n\t\tLDAP_STAILQ_FOREACH( op->o_bd, &backendDB, be_next ) {\n\t\t\tif( !op->o_bd->be_cancel ) continue;\n\n\t\t\top->oq_cancel.rs_msgid = opid;\n\t\t\tif ( op->o_bd->be_cancel( op, rs ) == LDAP_SUCCESS ) {\n\t\t\t\treturn LDAP_SUCCESS;\n\t\t\t}\n\t\t}\n\n\t\tdo {\n\t\t\t\/* Fake a cond_wait with thread_yield, then\n\t\t\t * verify the result properly mutex-protected.\n\t\t\t *\/\n\t\t\twhile ( o->o_cancel == SLAP_CANCEL_REQ )\n\t\t\t\tldap_pvt_thread_yield();\n\t\t\tldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );\n\t\t\trc = o->o_cancel;\n\t\t\tldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );\n\t\t} while ( rc == SLAP_CANCEL_REQ );\n\n\t\tif ( rc == SLAP_CANCEL_ACK ) {\n\t\t\trc = LDAP_SUCCESS;\n\t\t}\n\n\t\to->o_cancel = SLAP_CANCEL_DONE;\n\t}\n\n\treturn rc;\n}","target":1,"code_token_length":993,"total_token_length":1324,"max_tokens_setting":2048} +{"idx":438904,"func":"static int ieee80211_set_csa_beacon(struct ieee80211_sub_if_data *sdata,\n\t\t\t\t struct cfg80211_csa_settings *params,\n\t\t\t\t u32 *changed)\n{\n\tstruct ieee80211_csa_settings csa = {};\n\tint err;\n\n\tswitch (sdata->vif.type) {\n\tcase NL80211_IFTYPE_AP:\n\t\tsdata->u.ap.next_beacon =\n\t\t\tcfg80211_beacon_dup(¶ms->beacon_after);\n\t\tif (!sdata->u.ap.next_beacon)\n\t\t\treturn -ENOMEM;\n\n\t\t\/*\n\t\t * With a count of 0, we don't have to wait for any\n\t\t * TBTT before switching, so complete the CSA\n\t\t * immediately. In theory, with a count == 1 we\n\t\t * should delay the switch until just before the next\n\t\t * TBTT, but that would complicate things so we switch\n\t\t * immediately too. If we would delay the switch\n\t\t * until the next TBTT, we would have to set the probe\n\t\t * response here.\n\t\t *\n\t\t * TODO: A channel switch with count <= 1 without\n\t\t * sending a CSA action frame is kind of useless,\n\t\t * because the clients won't know we're changing\n\t\t * channels. The action frame must be implemented\n\t\t * either here or in the userspace.\n\t\t *\/\n\t\tif (params->count <= 1)\n\t\t\tbreak;\n\n\t\tif ((params->n_counter_offsets_beacon >\n\t\t IEEE80211_MAX_CSA_COUNTERS_NUM) ||\n\t\t (params->n_counter_offsets_presp >\n\t\t IEEE80211_MAX_CSA_COUNTERS_NUM))\n\t\t\treturn -EINVAL;\n\n\t\tcsa.counter_offsets_beacon = params->counter_offsets_beacon;\n\t\tcsa.counter_offsets_presp = params->counter_offsets_presp;\n\t\tcsa.n_counter_offsets_beacon = params->n_counter_offsets_beacon;\n\t\tcsa.n_counter_offsets_presp = params->n_counter_offsets_presp;\n\t\tcsa.count = params->count;\n\n\t\terr = ieee80211_assign_beacon(sdata, ¶ms->beacon_csa, &csa);\n\t\tif (err < 0) {\n\t\t\tkfree(sdata->u.ap.next_beacon);\n\t\t\treturn err;\n\t\t}\n\t\t*changed |= err;\n\n\t\tbreak;\n\tcase NL80211_IFTYPE_ADHOC:\n\t\tif (!sdata->vif.bss_conf.ibss_joined)\n\t\t\treturn -EINVAL;\n\n\t\tif (params->chandef.width != sdata->u.ibss.chandef.width)\n\t\t\treturn -EINVAL;\n\n\t\tswitch (params->chandef.width) {\n\t\tcase NL80211_CHAN_WIDTH_40:\n\t\t\tif (cfg80211_get_chandef_type(¶ms->chandef) !=\n\t\t\t cfg80211_get_chandef_type(&sdata->u.ibss.chandef))\n\t\t\t\treturn -EINVAL;\n\t\tcase NL80211_CHAN_WIDTH_5:\n\t\tcase NL80211_CHAN_WIDTH_10:\n\t\tcase NL80211_CHAN_WIDTH_20_NOHT:\n\t\tcase NL80211_CHAN_WIDTH_20:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\t\/* changes into another band are not supported *\/\n\t\tif (sdata->u.ibss.chandef.chan->band !=\n\t\t params->chandef.chan->band)\n\t\t\treturn -EINVAL;\n\n\t\t\/* see comments in the NL80211_IFTYPE_AP block *\/\n\t\tif (params->count > 1) {\n\t\t\terr = ieee80211_ibss_csa_beacon(sdata, params);\n\t\t\tif (err < 0)\n\t\t\t\treturn err;\n\t\t\t*changed |= err;\n\t\t}\n\n\t\tieee80211_send_action_csa(sdata, params);\n\n\t\tbreak;\n#ifdef CONFIG_MAC80211_MESH\n\tcase NL80211_IFTYPE_MESH_POINT: {\n\t\tstruct ieee80211_if_mesh *ifmsh = &sdata->u.mesh;\n\n\t\tif (params->chandef.width != sdata->vif.bss_conf.chandef.width)\n\t\t\treturn -EINVAL;\n\n\t\t\/* changes into another band are not supported *\/\n\t\tif (sdata->vif.bss_conf.chandef.chan->band !=\n\t\t params->chandef.chan->band)\n\t\t\treturn -EINVAL;\n\n\t\tif (ifmsh->csa_role == IEEE80211_MESH_CSA_ROLE_NONE) {\n\t\t\tifmsh->csa_role = IEEE80211_MESH_CSA_ROLE_INIT;\n\t\t\tif (!ifmsh->pre_value)\n\t\t\t\tifmsh->pre_value = 1;\n\t\t\telse\n\t\t\t\tifmsh->pre_value++;\n\t\t}\n\n\t\t\/* see comments in the NL80211_IFTYPE_AP block *\/\n\t\tif (params->count > 1) {\n\t\t\terr = ieee80211_mesh_csa_beacon(sdata, params);\n\t\t\tif (err < 0) {\n\t\t\t\tifmsh->csa_role = IEEE80211_MESH_CSA_ROLE_NONE;\n\t\t\t\treturn err;\n\t\t\t}\n\t\t\t*changed |= err;\n\t\t}\n\n\t\tif (ifmsh->csa_role == IEEE80211_MESH_CSA_ROLE_INIT)\n\t\t\tieee80211_send_action_csa(sdata, params);\n\n\t\tbreak;\n\t\t}\n#endif\n\tdefault:\n\t\treturn -EOPNOTSUPP;\n\t}\n\n\treturn 0;\n}","target":0,"code_token_length":1225,"total_token_length":1556,"max_tokens_setting":2048} +{"idx":353738,"func":"static int aes_gcm_ctrl(EVP_CIPHER_CTX *c, int type, int arg, void *ptr)\n{\n EVP_AES_GCM_CTX *gctx = c->cipher_data;\n switch (type) {\n case EVP_CTRL_INIT:\n gctx->key_set = 0;\n gctx->iv_set = 0;\n gctx->ivlen = c->cipher->iv_len;\n gctx->iv = c->iv;\n gctx->taglen = -1;\n gctx->iv_gen = 0;\n gctx->tls_aad_len = -1;\n return 1;\n\n case EVP_CTRL_GCM_SET_IVLEN:\n if (arg <= 0)\n return 0;\n \/* Allocate memory for IV if needed *\/\n if ((arg > EVP_MAX_IV_LENGTH) && (arg > gctx->ivlen)) {\n if (gctx->iv != c->iv)\n OPENSSL_free(gctx->iv);\n gctx->iv = OPENSSL_malloc(arg);\n if (!gctx->iv)\n return 0;\n }\n gctx->ivlen = arg;\n return 1;\n\n case EVP_CTRL_GCM_SET_TAG:\n if (arg <= 0 || arg > 16 || c->encrypt)\n return 0;\n memcpy(c->buf, ptr, arg);\n gctx->taglen = arg;\n return 1;\n\n case EVP_CTRL_GCM_GET_TAG:\n if (arg <= 0 || arg > 16 || !c->encrypt || gctx->taglen < 0)\n return 0;\n memcpy(ptr, c->buf, arg);\n return 1;\n\n case EVP_CTRL_GCM_SET_IV_FIXED:\n \/* Special case: -1 length restores whole IV *\/\n if (arg == -1) {\n memcpy(gctx->iv, ptr, gctx->ivlen);\n gctx->iv_gen = 1;\n return 1;\n }\n \/*\n * Fixed field must be at least 4 bytes and invocation field at least\n * 8.\n *\/\n if ((arg < 4) || (gctx->ivlen - arg) < 8)\n return 0;\n if (arg)\n memcpy(gctx->iv, ptr, arg);\n if (c->encrypt && RAND_bytes(gctx->iv + arg, gctx->ivlen - arg) <= 0)\n return 0;\n gctx->iv_gen = 1;\n return 1;\n\n case EVP_CTRL_GCM_IV_GEN:\n if (gctx->iv_gen == 0 || gctx->key_set == 0)\n return 0;\n CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen);\n if (arg <= 0 || arg > gctx->ivlen)\n arg = gctx->ivlen;\n memcpy(ptr, gctx->iv + gctx->ivlen - arg, arg);\n \/*\n * Invocation field will be at least 8 bytes in size and so no need\n * to check wrap around or increment more than last 8 bytes.\n *\/\n ctr64_inc(gctx->iv + gctx->ivlen - 8);\n gctx->iv_set = 1;\n return 1;\n\n case EVP_CTRL_GCM_SET_IV_INV:\n if (gctx->iv_gen == 0 || gctx->key_set == 0 || c->encrypt)\n return 0;\n memcpy(gctx->iv + gctx->ivlen - arg, ptr, arg);\n CRYPTO_gcm128_setiv(&gctx->gcm, gctx->iv, gctx->ivlen);\n gctx->iv_set = 1;\n return 1;\n\n case EVP_CTRL_AEAD_TLS1_AAD:\n \/* Save the AAD for later use *\/\n if (arg != 13)\n return 0;\n memcpy(c->buf, ptr, arg);\n gctx->tls_aad_len = arg;\n {\n unsigned int len = c->buf[arg - 2] << 8 | c->buf[arg - 1];\n \/* Correct length for explicit IV *\/\n len -= EVP_GCM_TLS_EXPLICIT_IV_LEN;\n \/* If decrypting correct for tag too *\/\n if (!c->encrypt)\n len -= EVP_GCM_TLS_TAG_LEN;\n c->buf[arg - 2] = len >> 8;\n c->buf[arg - 1] = len & 0xff;\n }\n \/* Extra padding: tag appended to record *\/\n return EVP_GCM_TLS_TAG_LEN;\n\n case EVP_CTRL_COPY:\n {\n EVP_CIPHER_CTX *out = ptr;\n EVP_AES_GCM_CTX *gctx_out = out->cipher_data;\n if (gctx->gcm.key) {\n if (gctx->gcm.key != &gctx->ks)\n return 0;\n gctx_out->gcm.key = &gctx_out->ks;\n }\n if (gctx->iv == c->iv)\n gctx_out->iv = out->iv;\n else {\n gctx_out->iv = OPENSSL_malloc(gctx->ivlen);\n if (!gctx_out->iv)\n return 0;\n memcpy(gctx_out->iv, gctx->iv, gctx->ivlen);\n }\n return 1;\n }\n\n default:\n return -1;\n\n }\n}","target":1,"code_token_length":1181,"total_token_length":1512,"max_tokens_setting":2048} +{"idx":23396,"func":"static ssize_t virtio_net_receive ( VLANClientState * nc , const uint8_t * buf , size_t size ) {\n VirtIONet * n = DO_UPCAST ( NICState , nc , nc ) -> opaque ;\n struct virtio_net_hdr_mrg_rxbuf * mhdr = NULL ;\n size_t guest_hdr_len , offset , i , host_hdr_len ;\n if ( ! virtio_net_can_receive ( & n -> nic -> nc ) ) return - 1 ;\n guest_hdr_len = n -> mergeable_rx_bufs ? sizeof ( struct virtio_net_hdr_mrg_rxbuf ) : sizeof ( struct virtio_net_hdr ) ;\n host_hdr_len = n -> has_vnet_hdr ? sizeof ( struct virtio_net_hdr ) : 0 ;\n if ( ! virtio_net_has_buffers ( n , size + guest_hdr_len - host_hdr_len ) ) return 0 ;\n if ( ! receive_filter ( n , buf , size ) ) return size ;\n offset = i = 0 ;\n while ( offset < size ) {\n VirtQueueElement elem ;\n int len , total ;\n struct iovec sg [ VIRTQUEUE_MAX_SIZE ] ;\n total = 0 ;\n if ( virtqueue_pop ( n -> rx_vq , & elem ) == 0 ) {\n if ( i == 0 ) return - 1 ;\n error_report ( \"virtio-net unexpected empty queue: \" \"i %zd mergeable %d offset %zd, size %zd, \" \"guest hdr len %zd, host hdr len %zd guest features 0x%x\" , i , n -> mergeable_rx_bufs , offset , size , guest_hdr_len , host_hdr_len , n -> vdev . guest_features ) ;\n exit ( 1 ) ;\n }\n if ( elem . in_num < 1 ) {\n error_report ( \"virtio-net receive queue contains no in buffers\" ) ;\n exit ( 1 ) ;\n }\n if ( ! n -> mergeable_rx_bufs && elem . in_sg [ 0 ] . iov_len != guest_hdr_len ) {\n error_report ( \"virtio-net header not in first element\" ) ;\n exit ( 1 ) ;\n }\n memcpy ( & sg , & elem . in_sg [ 0 ] , sizeof ( sg [ 0 ] ) * elem . in_num ) ;\n if ( i == 0 ) {\n if ( n -> mergeable_rx_bufs ) mhdr = ( struct virtio_net_hdr_mrg_rxbuf * ) sg [ 0 ] . iov_base ;\n offset += receive_header ( n , sg , elem . in_num , buf + offset , size - offset , guest_hdr_len ) ;\n total += guest_hdr_len ;\n }\n len = iov_from_buf ( sg , elem . in_num , 0 , buf + offset , size - offset ) ;\n total += len ;\n offset += len ;\n if ( ! n -> mergeable_rx_bufs && offset < size ) {\n # if 0 error_report ( \"virtio-net truncated non-mergeable packet: \" \"i %zd mergeable %d offset %zd, size %zd, \" \"guest hdr len %zd, host hdr len %zd\" , i , n -> mergeable_rx_bufs , offset , size , guest_hdr_len , host_hdr_len ) ;\n # endif return size ;\n }\n virtqueue_fill ( n -> rx_vq , & elem , total , i ++ ) ;\n }\n if ( mhdr ) {\n stw_p ( & mhdr -> num_buffers , i ) ;\n }\n virtqueue_flush ( n -> rx_vq , i ) ;\n virtio_notify ( & n -> vdev , n -> rx_vq ) ;\n return size ;\n }","target":0,"code_token_length":751,"total_token_length":1082,"max_tokens_setting":2048} +{"idx":468655,"func":"ClientRequestContext::clientAccessCheckDone(const Acl::Answer &answer)\n{\n acl_checklist = NULL;\n err_type page_id;\n Http::StatusCode status;\n debugs(85, 2, \"The request \" << http->request->method << ' ' <<\n http->uri << \" is \" << answer <<\n \"; last ACL checked: \" << (AclMatchedName ? AclMatchedName : \"[none]\"));\n\n#if USE_AUTH\n char const *proxy_auth_msg = \"\";\n if (http->getConn() != NULL && http->getConn()->getAuth() != NULL)\n proxy_auth_msg = http->getConn()->getAuth()->denyMessage(\"\");\n else if (http->request->auth_user_request != NULL)\n proxy_auth_msg = http->request->auth_user_request->denyMessage(\"\");\n#endif\n\n if (!answer.allowed()) {\n \/\/ auth has a grace period where credentials can be expired but okay not to challenge.\n\n \/* Send an auth challenge or error *\/\n \/\/ XXX: do we still need aclIsProxyAuth() ?\n bool auth_challenge = (answer == ACCESS_AUTH_REQUIRED || aclIsProxyAuth(AclMatchedName));\n debugs(85, 5, \"Access Denied: \" << http->uri);\n debugs(85, 5, \"AclMatchedName = \" << (AclMatchedName ? AclMatchedName : \"\"));\n#if USE_AUTH\n if (auth_challenge)\n debugs(33, 5, \"Proxy Auth Message = \" << (proxy_auth_msg ? proxy_auth_msg : \"\"));\n#endif\n\n \/*\n * NOTE: get page_id here, based on AclMatchedName because if\n * USE_DELAY_POOLS is enabled, then AclMatchedName gets clobbered in\n * the clientCreateStoreEntry() call just below. Pedro Ribeiro\n * \n *\/\n page_id = aclGetDenyInfoPage(&Config.denyInfoList, AclMatchedName, answer != ACCESS_AUTH_REQUIRED);\n\n http->logType.update(LOG_TCP_DENIED);\n\n if (auth_challenge) {\n#if USE_AUTH\n if (http->request->flags.sslBumped) {\n \/*SSL Bumped request, authentication is not possible*\/\n status = Http::scForbidden;\n } else if (!http->flags.accel) {\n \/* Proxy authorisation needed *\/\n status = Http::scProxyAuthenticationRequired;\n } else {\n \/* WWW authorisation needed *\/\n status = Http::scUnauthorized;\n }\n#else\n \/\/ need auth, but not possible to do.\n status = Http::scForbidden;\n#endif\n if (page_id == ERR_NONE)\n page_id = ERR_CACHE_ACCESS_DENIED;\n } else {\n status = Http::scForbidden;\n\n if (page_id == ERR_NONE)\n page_id = ERR_ACCESS_DENIED;\n }\n\n Ip::Address tmpnoaddr;\n tmpnoaddr.setNoAddr();\n error = clientBuildError(page_id, status,\n NULL,\n http->getConn() != NULL ? http->getConn()->clientConnection->remote : tmpnoaddr,\n http->request, http->al\n );\n\n#if USE_AUTH\n error->auth_user_request =\n http->getConn() != NULL && http->getConn()->getAuth() != NULL ?\n http->getConn()->getAuth() : http->request->auth_user_request;\n#endif\n\n readNextRequest = true;\n }\n\n \/* ACCESS_ALLOWED continues here ... *\/\n xfree(http->uri);\n http->uri = SBufToCstring(http->request->effectiveRequestUri());\n http->doCallouts();\n}","target":0,"code_token_length":795,"total_token_length":1126,"max_tokens_setting":2048} +{"idx":129318,"func":"cherokee_validator_ldap_configure (cherokee_config_node_t *conf, cherokee_server_t *srv, cherokee_module_props_t **_props)\n{\n\tret_t ret;\n\tcherokee_list_t *i;\n\tcherokee_validator_ldap_props_t *props;\n\n\tUNUSED(srv);\n\n\tif (*_props == NULL) {\n\t\tCHEROKEE_NEW_STRUCT (n, validator_ldap_props);\n\n\t\tcherokee_validator_props_init_base (VALIDATOR_PROPS(n), MODULE_PROPS_FREE(props_free));\n\n\t\tn->port = LDAP_DEFAULT_PORT;\n\t\tn->tls = false;\n\n\t\tcherokee_buffer_init (&n->server);\n\t\tcherokee_buffer_init (&n->binddn);\n\t\tcherokee_buffer_init (&n->bindpw);\n\t\tcherokee_buffer_init (&n->basedn);\n\t\tcherokee_buffer_init (&n->filter);\n\t\tcherokee_buffer_init (&n->ca_file);\n\n\t\t*_props = MODULE_PROPS(n);\n\t}\n\n\tprops = PROP_LDAP(*_props);\n\n\tcherokee_config_node_foreach (i, conf) {\n\t\tcherokee_config_node_t *subconf = CONFIG_NODE(i);\n\n\t\tif (equal_buf_str (&subconf->key, \"server\")) {\n\t\t\tcherokee_buffer_add_buffer (&props->server, &subconf->val);\n\n\t\t} else if (equal_buf_str (&subconf->key, \"port\")) {\n\t\t\tret = cherokee_atoi (subconf->val.buf, &props->port);\n\t\t\tif (ret != ret_ok) return ret_error;\n\n\t\t} else if (equal_buf_str (&subconf->key, \"bind_dn\")) {\n\t\t\tcherokee_buffer_add_buffer (&props->binddn, &subconf->val);\n\n\t\t} else if (equal_buf_str (&subconf->key, \"bind_pw\")) {\n\t\t\tcherokee_buffer_add_buffer (&props->bindpw, &subconf->val);\n\n\t\t} else if (equal_buf_str (&subconf->key, \"base_dn\")) {\n\t\t\tcherokee_buffer_add_buffer (&props->basedn, &subconf->val);\n\n\t\t} else if (equal_buf_str (&subconf->key, \"filter\")) {\n\t\t\tcherokee_buffer_add_buffer (&props->filter, &subconf->val);\n\n\t\t} else if (equal_buf_str (&subconf->key, \"tls\")) {\n\t\t\tret = cherokee_atob (subconf->val.buf, &props->tls);\n\t\t\tif (ret != ret_ok) return ret_error;\n\n\t\t} else if (equal_buf_str (&subconf->key, \"ca_file\")) {\n\t\t\tcherokee_buffer_add_buffer (&props->ca_file, &subconf->val);\n\n\t\t} else if (equal_buf_str (&subconf->key, \"methods\") ||\n\t\t equal_buf_str (&subconf->key, \"realm\") ||\n\t\t equal_buf_str (&subconf->key, \"users\")) {\n\t\t\t\/* Handled in validator.c\n\t\t\t *\/\n\t\t} else {\n\t\t\tLOG_WARNING (CHEROKEE_ERROR_VALIDATOR_LDAP_KEY, subconf->key.buf);\n\t\t}\n\t}\n\n\t\/* Checks\n\t *\/\n\tif (cherokee_buffer_is_empty (&props->basedn)) {\n\t\tLOG_ERROR (CHEROKEE_ERROR_VALIDATOR_LDAP_PROPERTY, \"base_dn\");\n\t\treturn ret_error;\n\t}\n\n\tif (cherokee_buffer_is_empty (&props->server)) {\n\t\tLOG_ERROR (CHEROKEE_ERROR_VALIDATOR_LDAP_PROPERTY, \"server\");\n\t\treturn ret_error;\n\t}\n\n\tif ((cherokee_buffer_is_empty (&props->bindpw) &&\n\t (! cherokee_buffer_is_empty (&props->basedn))))\n\t{\n\t\tLOG_ERROR_S (CHEROKEE_ERROR_VALIDATOR_LDAP_SECURITY);\n\t\treturn ret_error;\n\t}\n\n\treturn ret_ok;\n}","target":0,"code_token_length":788,"total_token_length":1119,"max_tokens_setting":2048} +{"idx":201642,"func":"status_t BnHDCP::onTransact(\n uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) {\n switch (code) {\n case HDCP_SET_OBSERVER:\n {\n CHECK_INTERFACE(IHDCP, data, reply);\n\n sp observer =\n interface_cast(data.readStrongBinder());\n\n reply->writeInt32(setObserver(observer));\n return OK;\n }\n\n case HDCP_INIT_ASYNC:\n {\n CHECK_INTERFACE(IHDCP, data, reply);\n\n const char *host = data.readCString();\n unsigned port = data.readInt32();\n\n reply->writeInt32(initAsync(host, port));\n return OK;\n }\n\n case HDCP_SHUTDOWN_ASYNC:\n {\n CHECK_INTERFACE(IHDCP, data, reply);\n\n reply->writeInt32(shutdownAsync());\n return OK;\n }\n\n case HDCP_GET_CAPS:\n {\n CHECK_INTERFACE(IHDCP, data, reply);\n\n reply->writeInt32(getCaps());\n return OK;\n }\n\n\n case HDCP_ENCRYPT:\n {\n size_t size = data.readInt32();\n \/\/ watch out for overflow\n if (size <= SIZE_MAX \/ 2) {\n inData = malloc(2 * size);\n }\n if (inData == NULL) {\n reply->writeInt32(ERROR_OUT_OF_RANGE);\n return OK;\n }\n\n \n void *outData = (uint8_t *)inData + size;\n \n status_t err = data.read(inData, size);\n if (err != OK) {\n free(inData);\n reply->writeInt32(err);\n return OK;\n }\n \n uint32_t streamCTR = data.readInt32();\n uint64_t inputCTR;\n err = encrypt(inData, size, streamCTR, &inputCTR, outData);\n \n reply->writeInt32(err);\n \n if (err == OK) {\n reply->writeInt64(inputCTR);\n reply->write(outData, size);\n }\n\n free(inData);\n inData = outData = NULL;\n\n return OK;\n }\n\n case HDCP_ENCRYPT_NATIVE:\n {\n CHECK_INTERFACE(IHDCP, data, reply);\n\n sp graphicBuffer = new GraphicBuffer();\n data.read(*graphicBuffer);\n size_t offset = data.readInt32();\n size_t size = data.readInt32();\n uint32_t streamCTR = data.readInt32();\n void *outData = malloc(size);\n uint64_t inputCTR;\n\n status_t err = encryptNative(graphicBuffer, offset, size,\n streamCTR, &inputCTR, outData);\n\n reply->writeInt32(err);\n\n if (err == OK) {\n reply->writeInt64(inputCTR);\n reply->write(outData, size);\n }\n\n free(outData);\n outData = NULL;\n\n return OK;\n }\n\n case HDCP_DECRYPT:\n {\n size_t size = data.readInt32();\n size_t bufSize = 2 * size;\n\n void *inData = NULL;\n if (bufSize > size) {\n inData = malloc(bufSize);\n }\n\n if (inData == NULL) {\n reply->writeInt32(ERROR_OUT_OF_RANGE);\n return OK;\n }\n\n void *outData = (uint8_t *)inData + size;\n\n data.read(inData, size);\n\n uint32_t streamCTR = data.readInt32();\n uint64_t inputCTR = data.readInt64();\n status_t err = decrypt(inData, size, streamCTR, inputCTR, outData);\n\n reply->writeInt32(err);\n\n if (err == OK) {\n reply->write(outData, size);\n }\n\n free(inData);\n inData = outData = NULL;\n\n return OK;\n }\n\n default:\n return BBinder::onTransact(code, data, reply, flags);\n }\n}\n","target":0,"code_token_length":818,"total_token_length":1149,"max_tokens_setting":2048} +{"idx":505484,"func":"int tls1_mac(SSL *ssl, unsigned char *md, int send)\n\t{\n\tSSL3_RECORD *rec;\n\tunsigned char *mac_sec,*seq;\n\tconst EVP_MD *hash;\n\tsize_t md_size;\n\tint i;\n\tHMAC_CTX hmac;\n\tunsigned char header[13];\n\n\tif (send)\n\t\t{\n\t\trec= &(ssl->s3->wrec);\n\t\tmac_sec= &(ssl->s3->write_mac_secret[0]);\n\t\tseq= &(ssl->s3->write_sequence[0]);\n\t\thash=ssl->write_hash;\n\t\t}\n\telse\n\t\t{\n\t\trec= &(ssl->s3->rrec);\n\t\tmac_sec= &(ssl->s3->read_mac_secret[0]);\n\t\tseq= &(ssl->s3->read_sequence[0]);\n\t\thash=ssl->read_hash;\n\t\t}\n\n\tmd_size=EVP_MD_size(hash);\n\n\t\/* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX *\/\n\tHMAC_CTX_init(&hmac);\n\tHMAC_Init_ex(&hmac,mac_sec,EVP_MD_size(hash),hash,NULL);\n\n\tif (ssl->version == DTLS1_BAD_VER ||\n\t (ssl->version == DTLS1_VERSION && ssl->client_version != DTLS1_BAD_VER))\n\t\t{\n\t\tunsigned char dtlsseq[8],*p=dtlsseq;\n\t\ts2n(send?ssl->d1->w_epoch:ssl->d1->r_epoch, p);\n\t\tmemcpy (p,&seq[2],6);\n\n\t\tmemcpy(header, dtlsseq, 8);\n\t\t}\n\telse\n\t\tmemcpy(header, seq, 8);\n\n\theader[8]=rec->type;\n\theader[9]=(unsigned char)(ssl->version>>8);\n\theader[10]=(unsigned char)(ssl->version);\n\theader[11]=(rec->length)>>8;\n\theader[12]=(rec->length)&0xff;\n\n\tif (!send &&\n\t EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&\n\t ssl3_cbc_record_digest_supported(hash))\n\t\t{\n\t\t\/* This is a CBC-encrypted record. We must avoid leaking any\n\t\t * timing-side channel information about how many blocks of\n\t\t * data we are hashing because that gives an attacker a\n\t\t * timing-oracle. *\/\n\t\tssl3_cbc_digest_record(\n\t\t hash,\n\t\t\tmd, &md_size,\n\t\t\theader, rec->input,\n\t\t\trec->length + md_size, rec->orig_len,\n\t\t\tssl->s3->read_mac_secret,\n\t\t\tEVP_MD_size(ssl->read_hash),\n\t\t\t0 \/* not SSLv3 *\/);\n\t\t}\n\telse\n\t\t{\n\t\tunsigned mds;\n\n\t\tHMAC_Update(&hmac,header,sizeof(header));\n\t\tHMAC_Update(&hmac,rec->input,rec->length);\n\t\tHMAC_Final(&hmac,md,&mds);\n\t\tmd_size = mds;\n#ifdef OPENSSL_FIPS\n\t\tif (!send && FIPS_mode())\n\t\t\ttls_fips_digest_extra(\n\t \t\t\t\tssl->enc_read_ctx,\n\t\t\t\t\thash,\n\t\t\t\t\t&hmac, rec->input,\n\t\t\t\t\trec->length, rec->orig_len);\n#endif\n\t\t}\n\t\t\n\tHMAC_CTX_cleanup(&hmac);\n#ifdef TLS_DEBUG\nprintf(\"sec=\");\n{unsigned int z; for (z=0; zlength; z++) printf(\"%02X \",buf[z]); printf(\"\\n\"); }\n#endif\n\n\tif ( SSL_version(ssl) != DTLS1_VERSION && SSL_version(ssl) != DTLS1_BAD_VER)\n\t\t{\n\t\tfor (i=7; i>=0; i--)\n\t\t\t{\n\t\t\t++seq[i];\n\t\t\tif (seq[i] != 0) break; \n\t\t\t}\n\t\t}\n\n#ifdef TLS_DEBUG\n{unsigned int z; for (z=0; z404 Not Found<\/body><\/html>\\n\");\n http_response_send(res);\n exit(0);\n }\n\n if (!strcmp(page, \"Changes\"))\n {\n wiki_show_changes_page(res);\n }\n else if (!strcmp(page, \"ChangesRss\"))\n {\n wiki_show_changes_page_rss(res);\n }\n else if (!strcmp(page, \"Search\"))\n {\n wiki_show_search_results_page(res, http_request_param_get(req, \"expr\"));\n }\n else if (!strcmp(page, \"Create\"))\n {\n if ( (wikitext = http_request_param_get(req, \"title\")) != NULL)\n\t{\n\t \/* create page and redirect *\/\n\t wiki_redirect(res, http_request_param_get(req, \"title\"));\n\t}\n else\n\t{\n\t \/* show create page form *\/\n\t wiki_show_create_page(res);\n\t}\n }\n else\n {\n \/* TODO: dont blindly write wikitext data to disk *\/\n if ( (wikitext = http_request_param_get(req, \"wikitext\")) != NULL)\n\t{\n\t file_write(page, wikitext);\t \n\t}\n\n if (access(page, R_OK) == 0) \t\/* page exists *\/\n\t{\n\t wikitext = file_read(page);\n\t \n\t if (!strcmp(command, \"edit\"))\n\t {\n\t \/* print edit page *\/\n\t wiki_show_edit_page(res, wikitext, page);\n\t }\n\t else\n\t {\n\t wiki_show_page(res, wikitext, page);\n\t }\n\t}\n else\n\t{\n\t if (!strcmp(command, \"create\"))\n\t {\n\t wiki_show_edit_page(res, NULL, page);\n\t }\n\t else\n\t {\n\t char buf[1024];\n\t snprintf(buf, 1024, \"%s?create\", page);\n\t wiki_redirect(res, buf);\n\t }\n\t}\n }\n\n}","target":0,"code_token_length":796,"total_token_length":1127,"max_tokens_setting":2048} +{"idx":471827,"func":"int zsetAdd(robj *zobj, double score, sds ele, int *flags, double *newscore) {\n \/* Turn options into simple to check vars. *\/\n int incr = (*flags & ZADD_INCR) != 0;\n int nx = (*flags & ZADD_NX) != 0;\n int xx = (*flags & ZADD_XX) != 0;\n *flags = 0; \/* We'll return our response flags. *\/\n double curscore;\n\n \/* NaN as input is an error regardless of all the other parameters. *\/\n if (isnan(score)) {\n *flags = ZADD_NAN;\n return 0;\n }\n\n \/* Update the sorted set according to its encoding. *\/\n if (zobj->encoding == OBJ_ENCODING_ZIPLIST) {\n unsigned char *eptr;\n\n if ((eptr = zzlFind(zobj->ptr,ele,&curscore)) != NULL) {\n \/* NX? Return, same element already exists. *\/\n if (nx) {\n *flags |= ZADD_NOP;\n return 1;\n }\n\n \/* Prepare the score for the increment if needed. *\/\n if (incr) {\n score += curscore;\n if (isnan(score)) {\n *flags |= ZADD_NAN;\n return 0;\n }\n if (newscore) *newscore = score;\n }\n\n \/* Remove and re-insert when score changed. *\/\n if (score != curscore) {\n zobj->ptr = zzlDelete(zobj->ptr,eptr);\n zobj->ptr = zzlInsert(zobj->ptr,ele,score);\n *flags |= ZADD_UPDATED;\n }\n return 1;\n } else if (!xx) {\n \/* check if the element is too large or the list\n * becomes too long *before* executing zzlInsert. *\/\n if (zzlLength(zobj->ptr)+1 > server.zset_max_ziplist_entries ||\n sdslen(ele) > server.zset_max_ziplist_value ||\n !ziplistSafeToAdd(zobj->ptr, sdslen(ele)))\n {\n zsetConvert(zobj,OBJ_ENCODING_SKIPLIST);\n } else {\n zobj->ptr = zzlInsert(zobj->ptr,ele,score);\n if (newscore) *newscore = score;\n *flags |= ZADD_ADDED;\n return 1;\n }\n } else {\n *flags |= ZADD_NOP;\n return 1;\n }\n }\n\n \/* Note that the above block handling ziplist would have either returned or\n * converted the key to skiplist. *\/\n if (zobj->encoding == OBJ_ENCODING_SKIPLIST) {\n zset *zs = zobj->ptr;\n zskiplistNode *znode;\n dictEntry *de;\n\n de = dictFind(zs->dict,ele);\n if (de != NULL) {\n \/* NX? Return, same element already exists. *\/\n if (nx) {\n *flags |= ZADD_NOP;\n return 1;\n }\n curscore = *(double*)dictGetVal(de);\n\n \/* Prepare the score for the increment if needed. *\/\n if (incr) {\n score += curscore;\n if (isnan(score)) {\n *flags |= ZADD_NAN;\n return 0;\n }\n if (newscore) *newscore = score;\n }\n\n \/* Remove and re-insert when score changes. *\/\n if (score != curscore) {\n znode = zslUpdateScore(zs->zsl,curscore,ele,score);\n \/* Note that we did not removed the original element from\n * the hash table representing the sorted set, so we just\n * update the score. *\/\n dictGetVal(de) = &znode->score; \/* Update score ptr. *\/\n *flags |= ZADD_UPDATED;\n }\n return 1;\n } else if (!xx) {\n ele = sdsdup(ele);\n znode = zslInsert(zs->zsl,score,ele);\n serverAssert(dictAdd(zs->dict,ele,&znode->score) == DICT_OK);\n *flags |= ZADD_ADDED;\n if (newscore) *newscore = score;\n return 1;\n } else {\n *flags |= ZADD_NOP;\n return 1;\n }\n } else {\n serverPanic(\"Unknown sorted set encoding\");\n }\n return 0; \/* Never reached. *\/\n}","target":0,"code_token_length":979,"total_token_length":1310,"max_tokens_setting":2048} +{"idx":499900,"func":"unsigned int rijndaelSetupEncrypt(u32 *rk, const u8 *key, size_t keybits)\n{\n int i = 0;\n u32 temp;\n\n rk[0] = GETU32(key );\n rk[1] = GETU32(key + 4);\n rk[2] = GETU32(key + 8);\n rk[3] = GETU32(key + 12);\n if (keybits == 128)\n {\n for (;;)\n {\n temp = rk[3];\n rk[4] = rk[0] ^\n (Te4[(temp >> 16) & 0xff] & 0xff000000) ^\n (Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^\n (Te4[(temp ) & 0xff] & 0x0000ff00) ^\n (Te4[(temp >> 24) ] & 0x000000ff) ^\n rcon[i];\n rk[5] = rk[1] ^ rk[4];\n rk[6] = rk[2] ^ rk[5];\n rk[7] = rk[3] ^ rk[6];\n if (++i == 10)\n return 10;\n rk += 4;\n }\n }\n rk[4] = GETU32(key + 16);\n rk[5] = GETU32(key + 20);\n if (keybits == 192)\n {\n for (;;)\n {\n temp = rk[ 5];\n rk[ 6] = rk[ 0] ^\n (Te4[(temp >> 16) & 0xff] & 0xff000000) ^\n (Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^\n (Te4[(temp ) & 0xff] & 0x0000ff00) ^\n (Te4[(temp >> 24) ] & 0x000000ff) ^\n rcon[i];\n rk[ 7] = rk[ 1] ^ rk[ 6];\n rk[ 8] = rk[ 2] ^ rk[ 7];\n rk[ 9] = rk[ 3] ^ rk[ 8];\n if (++i == 8)\n return 12;\n rk[10] = rk[ 4] ^ rk[ 9];\n rk[11] = rk[ 5] ^ rk[10];\n rk += 6;\n }\n }\n rk[6] = GETU32(key + 24);\n rk[7] = GETU32(key + 28);\n if (keybits == 256)\n {\n for (;;)\n {\n temp = rk[ 7];\n rk[ 8] = rk[ 0] ^\n (Te4[(temp >> 16) & 0xff] & 0xff000000) ^\n (Te4[(temp >> 8) & 0xff] & 0x00ff0000) ^\n (Te4[(temp ) & 0xff] & 0x0000ff00) ^\n (Te4[(temp >> 24) ] & 0x000000ff) ^\n rcon[i];\n rk[ 9] = rk[ 1] ^ rk[ 8];\n rk[10] = rk[ 2] ^ rk[ 9];\n rk[11] = rk[ 3] ^ rk[10];\n if (++i == 7)\n return 14;\n temp = rk[11];\n rk[12] = rk[ 4] ^\n (Te4[(temp >> 24) ] & 0xff000000) ^\n (Te4[(temp >> 16) & 0xff] & 0x00ff0000) ^\n (Te4[(temp >> 8) & 0xff] & 0x0000ff00) ^\n (Te4[(temp ) & 0xff] & 0x000000ff);\n rk[13] = rk[ 5] ^ rk[12];\n rk[14] = rk[ 6] ^ rk[13];\n rk[15] = rk[ 7] ^ rk[14];\n rk += 8;\n }\n }\n return 0;\n}","target":0,"code_token_length":1075,"total_token_length":1406,"max_tokens_setting":2048} +{"idx":340895,"func":"static int mov_text_decode_frame(AVCodecContext *avctx,\n\n void *data, int *got_sub_ptr, AVPacket *avpkt)\n\n{\n\n AVSubtitle *sub = data;\n\n int ret, ts_start, ts_end;\n\n AVBPrint buf;\n\n char *ptr = avpkt->data;\n\n char *end;\n\n \/\/char *ptr_temp;\n\n int text_length, tsmb_type, style_entries, tsmb_size;\n\n int **style_start = {0,};\n\n int **style_end = {0,};\n\n int **style_flags = {0,};\n\n const uint8_t *tsmb;\n\n int index, i;\n\n int *flag;\n\n int *style_pos;\n\n\n\n if (!ptr || avpkt->size < 2)\n\n return AVERROR_INVALIDDATA;\n\n\n\n \/*\n\n * A packet of size two with value zero is an empty subtitle\n\n * used to mark the end of the previous non-empty subtitle.\n\n * We can just drop them here as we have duration information\n\n * already. If the value is non-zero, then it's technically a\n\n * bad packet.\n\n *\/\n\n if (avpkt->size == 2)\n\n return AV_RB16(ptr) == 0 ? 0 : AVERROR_INVALIDDATA;\n\n\n\n \/*\n\n * The first two bytes of the packet are the length of the text string\n\n * In complex cases, there are style descriptors appended to the string\n\n * so we can't just assume the packet size is the string size.\n\n *\/\n\n text_length = AV_RB16(ptr);\n\n end = ptr + FFMIN(2 + text_length, avpkt->size);\n\n ptr += 2;\n\n\n\n ts_start = av_rescale_q(avpkt->pts,\n\n avctx->time_base,\n\n (AVRational){1,100});\n\n ts_end = av_rescale_q(avpkt->pts + avpkt->duration,\n\n avctx->time_base,\n\n (AVRational){1,100});\n\n\n\n tsmb_size = 0;\n\n \/\/ Note that the spec recommends lines be no longer than 2048 characters.\n\n av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);\n\n if (text_length + 2 != avpkt->size) {\n\n while (text_length + 2 + tsmb_size < avpkt->size) {\n\n tsmb = ptr + text_length + tsmb_size;\n\n tsmb_size = AV_RB32(tsmb);\n\n tsmb += 4;\n\n tsmb_type = AV_RB32(tsmb);\n\n tsmb += 4;\n\n\n\n if (tsmb_type == MKBETAG('s','t','y','l')) {\n\n style_entries = AV_RB16(tsmb);\n\n tsmb += 2;\n\n\n\n for(i = 0; i < style_entries; i++) {\n\n style_pos = av_malloc(4);\n\n *style_pos = AV_RB16(tsmb);\n\n index = i;\n\n av_dynarray_add(&style_start, &index, style_pos);\n\n tsmb += 2;\n\n style_pos = av_malloc(4);\n\n *style_pos = AV_RB16(tsmb);\n\n index = i;\n\n av_dynarray_add(&style_end, &index, style_pos);\n\n tsmb += 2;\n\n \/\/ fontID = AV_RB16(tsmb);\n\n tsmb += 2;\n\n flag = av_malloc(4);\n\n *flag = AV_RB8(tsmb);\n\n index = i;\n\n av_dynarray_add(&style_flags, &index, flag);\n\n \/\/fontsize=AV_RB8(tsmb);\n\n tsmb += 2;\n\n \/\/ text-color-rgba\n\n tsmb += 4;\n\n }\n\n text_to_ass(&buf, ptr, end, style_start, style_end, style_flags, style_entries);\n\n av_freep(&style_start);\n\n av_freep(&style_end);\n\n av_freep(&style_flags);\n\n }\n\n }\n\n } else\n\n text_to_ass(&buf, ptr, end, NULL, NULL, 0, 0);\n\n\n\n ret = ff_ass_add_rect_bprint(sub, &buf, ts_start, ts_end - ts_start);\n\n av_bprint_finalize(&buf, NULL);\n\n if (ret < 0)\n\n return ret;\n\n *got_sub_ptr = sub->num_rects > 0;\n\n return avpkt->size;\n\n}\n","target":1,"code_token_length":944,"total_token_length":1275,"max_tokens_setting":2048} +{"idx":38603,"func":"static int megasas_get_ld_vf_affiliation_12(struct megasas_instance *instance,\n\t\t\t\t\t int initial)\n{\n\tstruct megasas_cmd *cmd;\n\tstruct megasas_dcmd_frame *dcmd;\n\tstruct MR_LD_VF_AFFILIATION *new_affiliation = NULL;\n\tstruct MR_LD_VF_MAP *newmap = NULL, *savedmap = NULL;\n\tdma_addr_t new_affiliation_h;\n\tint i, j, retval = 0, found = 0, doscan = 0;\n\tu8 thisVf;\n\n\tcmd = megasas_get_cmd(instance);\n\n\tif (!cmd) {\n\t\tdev_printk(KERN_DEBUG, &instance->pdev->dev, \"megasas_get_ld_vf_affiliation12: \"\n\t\t \"Failed to get cmd for scsi%d\\n\",\n\t\t instance->host->host_no);\n\t\treturn -ENOMEM;\n\t}\n\n\tdcmd = &cmd->frame->dcmd;\n\n\tif (!instance->vf_affiliation) {\n\t\tdev_warn(&instance->pdev->dev, \"SR-IOV: Couldn't get LD\/VF \"\n\t\t \"affiliation for scsi%d\\n\", instance->host->host_no);\n\t\tmegasas_return_cmd(instance, cmd);\n\t\treturn -ENOMEM;\n\t}\n\n\tif (initial)\n\t\tmemset(instance->vf_affiliation, 0, (MAX_LOGICAL_DRIVES + 1) *\n\t\t sizeof(struct MR_LD_VF_AFFILIATION));\n\telse {\n\t\tnew_affiliation =\n\t\t\tdma_zalloc_coherent(&instance->pdev->dev,\n\t\t\t\t\t (MAX_LOGICAL_DRIVES + 1) *\n\t\t\t\t\t sizeof(struct MR_LD_VF_AFFILIATION),\n\t\t\t\t\t &new_affiliation_h, GFP_KERNEL);\n\t\tif (!new_affiliation) {\n\t\t\tdev_printk(KERN_DEBUG, &instance->pdev->dev, \"SR-IOV: Couldn't allocate \"\n\t\t\t \"memory for new affiliation for scsi%d\\n\",\n\t\t\t instance->host->host_no);\n\t\t\tmegasas_return_cmd(instance, cmd);\n\t\t\treturn -ENOMEM;\n\t\t}\n\t}\n\n\tmemset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);\n\n\tdcmd->cmd = MFI_CMD_DCMD;\n\tdcmd->cmd_status = MFI_STAT_INVALID_STATUS;\n\tdcmd->sge_count = 1;\n\tdcmd->flags = cpu_to_le16(MFI_FRAME_DIR_BOTH);\n\tdcmd->timeout = 0;\n\tdcmd->pad_0 = 0;\n\tdcmd->data_xfer_len = cpu_to_le32((MAX_LOGICAL_DRIVES + 1) *\n\t\tsizeof(struct MR_LD_VF_AFFILIATION));\n\tdcmd->opcode = cpu_to_le32(MR_DCMD_LD_VF_MAP_GET_ALL_LDS);\n\n\tif (initial)\n\t\tdcmd->sgl.sge32[0].phys_addr =\n\t\t\tcpu_to_le32(instance->vf_affiliation_h);\n\telse\n\t\tdcmd->sgl.sge32[0].phys_addr =\n\t\t\tcpu_to_le32(new_affiliation_h);\n\n\tdcmd->sgl.sge32[0].length = cpu_to_le32((MAX_LOGICAL_DRIVES + 1) *\n\t\tsizeof(struct MR_LD_VF_AFFILIATION));\n\n\tdev_warn(&instance->pdev->dev, \"SR-IOV: Getting LD\/VF affiliation for \"\n\t \"scsi%d\\n\", instance->host->host_no);\n\n\n\tif (megasas_issue_blocked_cmd(instance, cmd, 0) != DCMD_SUCCESS) {\n\t\tdev_warn(&instance->pdev->dev, \"SR-IOV: LD\/VF affiliation DCMD\"\n\t\t \" failed with status 0x%x for scsi%d\\n\",\n\t\t dcmd->cmd_status, instance->host->host_no);\n\t\tretval = 1; \/* Do a scan if we couldn't get affiliation *\/\n\t\tgoto out;\n\t}\n\n\tif (!initial) {\n\t\tif (!new_affiliation->ldCount) {\n\t\t\tdev_warn(&instance->pdev->dev, \"SR-IOV: Got new LD\/VF \"\n\t\t\t \"affiliation for passive path for scsi%d\\n\",\n\t\t\t instance->host->host_no);\n\t\t\tretval = 1;\n\t\t\tgoto out;\n\t\t}\n\t\tnewmap = new_affiliation->map;\n\t\tsavedmap = instance->vf_affiliation->map;\n\t\tthisVf = new_affiliation->thisVf;\n\t\tfor (i = 0 ; i < new_affiliation->ldCount; i++) {\n\t\t\tfound = 0;\n\t\t\tfor (j = 0; j < instance->vf_affiliation->ldCount;\n\t\t\t j++) {\n\t\t\t\tif (newmap->ref.targetId ==\n\t\t\t\t savedmap->ref.targetId) {\n\t\t\t\t\tfound = 1;\n\t\t\t\t\tif (newmap->policy[thisVf] !=\n\t\t\t\t\t savedmap->policy[thisVf]) {\n\t\t\t\t\t\tdoscan = 1;\n\t\t\t\t\t\tgoto out;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tsavedmap = (struct MR_LD_VF_MAP *)\n\t\t\t\t\t((unsigned char *)savedmap +\n\t\t\t\t\t savedmap->size);\n\t\t\t}\n\t\t\tif (!found && newmap->policy[thisVf] !=\n\t\t\t MR_LD_ACCESS_HIDDEN) {\n\t\t\t\tdoscan = 1;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tnewmap = (struct MR_LD_VF_MAP *)\n\t\t\t\t((unsigned char *)newmap + newmap->size);\n\t\t}\n\n\t\tnewmap = new_affiliation->map;\n\t\tsavedmap = instance->vf_affiliation->map;\n\n\t\tfor (i = 0 ; i < instance->vf_affiliation->ldCount; i++) {\n\t\t\tfound = 0;\n\t\t\tfor (j = 0 ; j < new_affiliation->ldCount; j++) {\n\t\t\t\tif (savedmap->ref.targetId ==\n\t\t\t\t newmap->ref.targetId) {\n\t\t\t\t\tfound = 1;\n\t\t\t\t\tif (savedmap->policy[thisVf] !=\n\t\t\t\t\t newmap->policy[thisVf]) {\n\t\t\t\t\t\tdoscan = 1;\n\t\t\t\t\t\tgoto out;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tnewmap = (struct MR_LD_VF_MAP *)\n\t\t\t\t\t((unsigned char *)newmap +\n\t\t\t\t\t newmap->size);\n\t\t\t}\n\t\t\tif (!found && savedmap->policy[thisVf] !=\n\t\t\t MR_LD_ACCESS_HIDDEN) {\n\t\t\t\tdoscan = 1;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tsavedmap = (struct MR_LD_VF_MAP *)\n\t\t\t\t((unsigned char *)savedmap +\n\t\t\t\t savedmap->size);\n\t\t}\n\t}\nout:\n\tif (doscan) {\n\t\tdev_warn(&instance->pdev->dev, \"SR-IOV: Got new LD\/VF \"\n\t\t \"affiliation for scsi%d\\n\", instance->host->host_no);\n\t\tmemcpy(instance->vf_affiliation, new_affiliation,\n\t\t new_affiliation->size);\n\t\tretval = 1;\n\t}\n\n\tif (new_affiliation)\n\t\tdma_free_coherent(&instance->pdev->dev,\n\t\t\t\t (MAX_LOGICAL_DRIVES + 1) *\n\t\t\t\t sizeof(struct MR_LD_VF_AFFILIATION),\n\t\t\t\t new_affiliation, new_affiliation_h);\n\tmegasas_return_cmd(instance, cmd);\n\n\treturn retval;\n}","target":0,"code_token_length":1488,"total_token_length":1819,"max_tokens_setting":2048} +{"idx":250378,"func":" static int _make_words(char *l,long n,ogg_uint32_t *r,long quantvals,\n codebook *b, oggpack_buffer *opb,int maptype){\n long i,j,count=0;\n long top=0;\n ogg_uint32_t marker[MARKER_SIZE];\n\n if (n<1)\n return 1;\n\n if(n<2){\n r[0]=0x80000000;\n }else{\n memset(marker,0,sizeof(marker));\n\n for(i=0;i= MARKER_SIZE) {\n\n ALOGE(\"b\/23881715\");\n return 1;\n }\n ogg_uint32_t entry=marker[length];\n long chase=0;\n if(count && !entry)return -1; \/* overpopulated tree! *\/\n \n \/* chase the tree as far as it's already populated, fill in past *\/\n for(j=0;j>(length-j-1))&1;\n if(chase>=top){\n if (chase < 0 || chase >= n) return 1;\n top++;\n r[chase*2]=top;\n r[chase*2+1]=0;\n }else\n if (chase < 0 || chase >= n || chase*2+bit > n*2+1) return 1;\n if(!r[chase*2+bit])\n r[chase*2+bit]=top;\n chase=r[chase*2+bit];\n if (chase < 0 || chase >= n) return 1;\n }\n {\n int bit=(entry>>(length-j-1))&1;\n if(chase>=top){\n top++;\n r[chase*2+1]=0;\n }\n r[chase*2+bit]= decpack(i,count++,quantvals,b,opb,maptype) |\n 0x80000000;\n }\n \n \/* Look to see if the next shorter marker points to the node\n above. if so, update it and repeat. *\/\n for(j=length;j>0;j--){\n if(marker[j]&1){\n marker[j]=marker[j-1]<<1;\n break;\n }\n marker[j]++;\n }\n \n \/* prune the tree; the implicit invariant says all the longer\n markers were dangling from our just-taken node. Dangle them\n from our *new* node. *\/\n for(j=length+1;j>1) == entry){\n entry=marker[j];\n marker[j]=marker[j-1]<<1;\n }else\n break;\n }\n }\n }\n\n \/* sanity check the huffman tree; an underpopulated tree must be\n rejected. The only exception is the one-node pseudo-nil tree,\n which appears to be underpopulated because the tree doesn't\n really exist; there's only one possible 'codeword' or zero bits,\n but the above tree-gen code doesn't mark that. *\/\n if(b->used_entries != 1){\n for(i=1;i>(32-i))){\n return 1;\n }\n }\n\n\n return 0;\n\n }\n","target":0,"code_token_length":731,"total_token_length":1062,"max_tokens_setting":2048} +{"idx":287216,"func":"static void parse_class(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c,\n\t\t\t int class_index, int *methods, int *sym_count) {\n\tstruct r_bin_t *rbin = binfile->rbin;\n\n\tchar *class_name;\n\tint z;\n\tconst ut8 *p, *p_end;\n\n\tif (!c) {\n\t\treturn;\n\t}\n\n\tclass_name = dex_class_name (bin, c);\n\tclass_name = r_str_replace (class_name, \";\", \"\", 0); \/\/TODO: move to func\n\n\tif (!class_name || !*class_name) {\n\t\treturn;\n\t}\n\n\tRBinClass *cls = R_NEW0 (RBinClass);\n\tif (!cls) {\n\t\treturn;\n\t}\n\tcls->name = class_name;\n\tcls->index = class_index;\n\tcls->addr = bin->header.class_offset + class_index * DEX_CLASS_SIZE;\n\tcls->methods = r_list_new ();\n\tif (!cls->methods) {\n\t\tfree (cls);\n\t\treturn;\n\t}\n\tcls->fields = r_list_new ();\n\tif (!cls->fields) {\n\t\tr_list_free (cls->methods);\n\t\tfree (cls);\n\t\treturn;\n\t}\n\tr_list_append (bin->classes_list, cls);\n\tif (dexdump) {\n\t\trbin->cb_printf (\" Class descriptor : '%s;'\\n\", class_name);\n\t\trbin->cb_printf (\n\t\t\t\" Access flags : 0x%04x (%s)\\n\", c->access_flags,\n\t\t\tcreateAccessFlagStr (c->access_flags, kAccessForClass));\n\t\trbin->cb_printf (\" Superclass : '%s'\\n\",\n\t\t\t\t dex_class_super_name (bin, c));\n\t\trbin->cb_printf (\" Interfaces -\\n\");\n\t}\n\n\tif (c->interfaces_offset > 0 &&\n\t bin->header.data_offset < c->interfaces_offset &&\n\t c->interfaces_offset <\n\t\t bin->header.data_offset + bin->header.data_size) {\n\t\tp = r_buf_get_at (binfile->buf, c->interfaces_offset, NULL);\n\t\tint types_list_size = r_read_le32(p);\n\t\tif (types_list_size < 0 || types_list_size >= bin->header.types_size ) {\n\t\t\treturn;\n\t\t}\n\t\tfor (z = 0; z < types_list_size; z++) {\n\t\t\tint t = r_read_le16 (p + 4 + z * 2);\n\t\t\tif (t > 0 && t < bin->header.types_size ) {\n\t\t\t\tint tid = bin->types[t].descriptor_id;\n\t\t\t\tif (dexdump) {\n\t\t\t\t\trbin->cb_printf (\n\t\t\t\t\t\t\" #%d : '%s'\\n\",\n\t\t\t\t\t\tz, getstr (bin, tid));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ TODO: this is quite ugly\n\tif (!c || !c->class_data_offset) {\n\t\tif (dexdump) {\n\t\t\trbin->cb_printf (\n\t\t\t\t\" Static fields -\\n Instance fields \"\n\t\t\t\t\"-\\n Direct methods -\\n Virtual methods \"\n\t\t\t\t\"-\\n\");\n\t\t}\n\t} else {\n\t\t\/\/ TODO: move to func, def or inline\n\t\t\/\/ class_data_offset => [class_offset, class_defs_off+class_defs_size*32]\n\t\tif (bin->header.class_offset > c->class_data_offset ||\n\t\t c->class_data_offset <\n\t\t\t bin->header.class_offset +\n\t\t\t\t bin->header.class_size * DEX_CLASS_SIZE) {\n\t\t\treturn;\n\t\t}\n\n\t\tp = r_buf_get_at (binfile->buf, c->class_data_offset, NULL);\n\t\tp_end = p + binfile->buf->length - c->class_data_offset;\n\t\t\/\/XXX check for NULL!!\n\t\tc->class_data = (struct dex_class_data_item_t *)malloc (\n\t\t\tsizeof (struct dex_class_data_item_t));\n\t\tp = r_uleb128 (p, p_end - p, &c->class_data->static_fields_size);\n\t\tp = r_uleb128 (p, p_end - p, &c->class_data->instance_fields_size);\n\t\tp = r_uleb128 (p, p_end - p, &c->class_data->direct_methods_size);\n\t\tp = r_uleb128 (p, p_end - p, &c->class_data->virtual_methods_size);\n\n\t\tif (dexdump) { \n\t\t\trbin->cb_printf (\" Static fields -\\n\"); \n\t\t}\n\t\tp = parse_dex_class_fields (\n\t\t\tbinfile, bin, c, cls, p, p_end, sym_count,\n\t\t\tc->class_data->static_fields_size, true);\n\n\t\tif (dexdump) { \n\t\t\trbin->cb_printf (\" Instance fields -\\n\");\n\t\t}\n\t\tp = parse_dex_class_fields (\n\t\t\tbinfile, bin, c, cls, p, p_end, sym_count,\n\t\t\tc->class_data->instance_fields_size, false);\n\n\t\tif (dexdump) { \n\t\t\trbin->cb_printf (\" Direct methods -\\n\");\n\t\t}\n\t\tp = parse_dex_class_method (\n\t\t\tbinfile, bin, c, cls, p, p_end, sym_count,\n\t\t\tc->class_data->direct_methods_size, methods, true);\n\n\t\tif (dexdump) { \n\t\t\trbin->cb_printf (\" Virtual methods -\\n\");\n\t\t}\n\t\tp = parse_dex_class_method (\n\t\t\tbinfile, bin, c, cls, p, p_end, sym_count,\n\t\t\tc->class_data->virtual_methods_size, methods, false);\n\t}\n\n\tif (dexdump) { \n\t\tchar *source_file = getstr (bin, c->source_file);\n\t\tif (!source_file) {\n\t\t\trbin->cb_printf (\n\t\t\t\t\" source_file_idx : %d (unknown)\\n\\n\",\n\t\t\t\tc->source_file);\n\t\t} else {\n\t\t\trbin->cb_printf (\" source_file_idx : %d (%s)\\n\\n\",\n\t\t\t\t\t c->source_file, source_file);\n\t\t}\n\t}\n\t\/\/ TODO:!!!!\n\t\/\/ FIX: FREE BEFORE ALLOCATE!!!\n\t\/\/free (class_name);\n}","target":1,"code_token_length":1340,"total_token_length":1671,"max_tokens_setting":2048} +{"idx":507108,"func":"int ssl3_client_hello(SSL *s)\n\t{\n\tunsigned char *buf;\n\tunsigned char *p,*d;\n\tint i;\n\tunsigned long l;\n#ifndef OPENSSL_NO_COMP\n\tint j;\n\tSSL_COMP *comp;\n#endif\n\n\tbuf=(unsigned char *)s->init_buf->data;\n\tif (s->state == SSL3_ST_CW_CLNT_HELLO_A)\n\t\t{\n\t\tSSL_SESSION *sess = s->session;\n\t\tif ((sess == NULL) ||\n\t\t\t(sess->ssl_version != s->version) ||\n\t\t\t!sess->session_id_length ||\n\t\t\t(sess->not_resumable))\n\t\t\t{\n\t\t\tif (!ssl_get_new_session(s,0))\n\t\t\t\tgoto err;\n\t\t\t}\n\t\t\/* else use the pre-loaded session *\/\n\n\t\tp=s->s3->client_random;\n\n\t\tif (ssl_fill_hello_random(s, 0, p, SSL3_RANDOM_SIZE) <= 0)\n\t\t\tgoto err;\n\n\t\t\/* Do the message type and length last *\/\n\t\td=p= &(buf[4]);\n\n\t\t\/* version indicates the negotiated version: for example from\n\t\t * an SSLv2\/v3 compatible client hello). The client_version\n\t\t * field is the maximum version we permit and it is also\n\t\t * used in RSA encrypted premaster secrets. Some servers can\n\t\t * choke if we initially report a higher version then\n\t\t * renegotiate to a lower one in the premaster secret. This\n\t\t * didn't happen with TLS 1.0 as most servers supported it\n\t\t * but it can with TLS 1.1 or later if the server only supports\n\t\t * 1.0.\n\t\t *\n\t\t * Possible scenario with previous logic:\n\t\t * \t1. Client hello indicates TLS 1.2\n\t\t * \t2. Server hello says TLS 1.0\n\t\t *\t3. RSA encrypted premaster secret uses 1.2.\n\t\t * \t4. Handhaked proceeds using TLS 1.0.\n\t\t *\t5. Server sends hello request to renegotiate.\n\t\t *\t6. Client hello indicates TLS v1.0 as we now\n\t\t *\t know that is maximum server supports.\n\t\t *\t7. Server chokes on RSA encrypted premaster secret\n\t\t *\t containing version 1.0.\n\t\t *\n\t\t * For interoperability it should be OK to always use the\n\t\t * maximum version we support in client hello and then rely\n\t\t * on the checking of version to ensure the servers isn't\n\t\t * being inconsistent: for example initially negotiating with\n\t\t * TLS 1.0 and renegotiating with TLS 1.2. We do this by using\n\t\t * client_version in client hello and not resetting it to\n\t\t * the negotiated version.\n\t\t *\/\n#if 0\n\t\t*(p++)=s->version>>8;\n\t\t*(p++)=s->version&0xff;\n\t\ts->client_version=s->version;\n#else\n\t\t*(p++)=s->client_version>>8;\n\t\t*(p++)=s->client_version&0xff;\n#endif\n\n\t\t\/* Random stuff *\/\n\t\tmemcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE);\n\t\tp+=SSL3_RANDOM_SIZE;\n\n\t\t\/* Session ID *\/\n\t\tif (s->new_session)\n\t\t\ti=0;\n\t\telse\n\t\t\ti=s->session->session_id_length;\n\t\t*(p++)=i;\n\t\tif (i != 0)\n\t\t\t{\n\t\t\tif (i > (int)sizeof(s->session->session_id))\n\t\t\t\t{\n\t\t\t\tSSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);\n\t\t\t\tgoto err;\n\t\t\t\t}\n\t\t\tmemcpy(p,s->session->session_id,i);\n\t\t\tp+=i;\n\t\t\t}\n\t\t\n\t\t\/* Ciphers supported *\/\n\t\ti=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0);\n\t\tif (i == 0)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE);\n\t\t\tgoto err;\n\t\t\t}\n#ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH\n\t\t\t\/* Some servers hang if client hello > 256 bytes\n\t\t\t * as hack workaround chop number of supported ciphers\n\t\t\t * to keep it well below this if we use TLS v1.2\n\t\t\t *\/\n\t\t\tif (TLS1_get_version(s) >= TLS1_2_VERSION\n\t\t\t\t&& i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH)\n\t\t\t\ti = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;\n#endif\n\t\ts2n(i,p);\n\t\tp+=i;\n\n\t\t\/* COMPRESSION *\/\n#ifdef OPENSSL_NO_COMP\n\t\t*(p++)=1;\n#else\n\n\t\tif ((s->options & SSL_OP_NO_COMPRESSION)\n\t\t\t\t\t|| !s->ctx->comp_methods)\n\t\t\tj=0;\n\t\telse\n\t\t\tj=sk_SSL_COMP_num(s->ctx->comp_methods);\n\t\t*(p++)=1+j;\n\t\tfor (i=0; ictx->comp_methods,i);\n\t\t\t*(p++)=comp->id;\n\t\t\t}\n#endif\n\t\t*(p++)=0; \/* Add the NULL method *\/\n\n#ifndef OPENSSL_NO_TLSEXT\n\t\t\/* TLS extensions*\/\n\t\tif (ssl_prepare_clienthello_tlsext(s) <= 0)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_CLIENTHELLO_TLSEXT);\n\t\t\tgoto err;\n\t\t\t}\n\t\tif ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)\n\t\t\t{\n\t\t\tSSLerr(SSL_F_SSL3_CLIENT_HELLO,ERR_R_INTERNAL_ERROR);\n\t\t\tgoto err;\n\t\t\t}\n#endif\n\t\t\n\t\tl=(p-d);\n\t\td=buf;\n\t\t*(d++)=SSL3_MT_CLIENT_HELLO;\n\t\tl2n3(l,d);\n\n\t\ts->state=SSL3_ST_CW_CLNT_HELLO_B;\n\t\t\/* number of bytes to write *\/\n\t\ts->init_num=p-buf;\n\t\ts->init_off=0;\n\t\t}\n\n\t\/* SSL3_ST_CW_CLNT_HELLO_B *\/\n\treturn(ssl3_do_write(s,SSL3_RT_HANDSHAKE));\nerr:\n\treturn(-1);\n\t}","target":0,"code_token_length":1356,"total_token_length":1687,"max_tokens_setting":2048} +{"idx":108635,"func":"GF_Err audio_sample_entry_on_child_box(GF_Box *s, GF_Box *a)\n{\n\tGF_UnknownBox *wave = NULL;\n\tBool drop_wave=GF_FALSE;\n\tGF_MPEGAudioSampleEntryBox *ptr = (GF_MPEGAudioSampleEntryBox *)s;\n\n\tswitch (a->type) {\n\tcase GF_ISOM_BOX_TYPE_ESDS:\n\t\tif (ptr->esd) ERROR_ON_DUPLICATED_BOX(a, ptr)\n\t\tptr->esd = (GF_ESDBox *)a;\n\t\tptr->qtff_mode = GF_ISOM_AUDIO_QTFF_NONE;\n\t\tbreak;\n\n\tcase GF_ISOM_BOX_TYPE_DAMR:\n\tcase GF_ISOM_BOX_TYPE_DEVC:\n\tcase GF_ISOM_BOX_TYPE_DQCP:\n\tcase GF_ISOM_BOX_TYPE_DSMV:\n\t\tif (ptr->cfg_3gpp) ERROR_ON_DUPLICATED_BOX(a, ptr)\n\t\tptr->cfg_3gpp = (GF_3GPPConfigBox *) a;\n\t\t\/*for 3GP config, remember sample entry type in config*\/\n\t\tptr->cfg_3gpp->cfg.type = ptr->type;\n\t\tptr->qtff_mode = GF_ISOM_AUDIO_QTFF_NONE;\n\t\tbreak;\n\n\tcase GF_ISOM_BOX_TYPE_DOPS:\n\t\tif (ptr->cfg_opus) ERROR_ON_DUPLICATED_BOX(a, ptr)\n\t\tptr->cfg_opus = (GF_OpusSpecificBox *)a;\n\t\tptr->qtff_mode = GF_ISOM_AUDIO_QTFF_NONE;\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_DAC3:\n\t\tif (ptr->cfg_ac3) ERROR_ON_DUPLICATED_BOX(a, ptr)\n\t\tptr->cfg_ac3 = (GF_AC3ConfigBox *) a;\n\t\tptr->qtff_mode = GF_ISOM_AUDIO_QTFF_NONE;\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_DEC3:\n\t\tif (ptr->cfg_ac3) ERROR_ON_DUPLICATED_BOX(a, ptr)\n\t\tptr->cfg_ac3 = (GF_AC3ConfigBox *) a;\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_MHAC:\n\t\tif (ptr->cfg_mha) ERROR_ON_DUPLICATED_BOX(a, ptr)\n\t\tptr->cfg_mha = (GF_MHAConfigBox *) a;\n\t\tptr->qtff_mode = GF_ISOM_AUDIO_QTFF_NONE;\n\t\tbreak;\n\tcase GF_ISOM_BOX_TYPE_DFLA:\n\t\tif (ptr->cfg_flac) ERROR_ON_DUPLICATED_BOX(a, ptr)\n\t\tptr->cfg_flac = (GF_FLACConfigBox *) a;\n\t\tptr->qtff_mode = GF_ISOM_AUDIO_QTFF_NONE;\n\t\tbreak;\n\n\tcase GF_ISOM_BOX_TYPE_UNKNOWN:\n\t\twave = (GF_UnknownBox *)a;\n\t\t\/*HACK for QT files: get the esds box from the track*\/\n\t\tif (s->type == GF_ISOM_BOX_TYPE_MP4A) {\n\t\t\tif (ptr->esd) ERROR_ON_DUPLICATED_BOX(a, ptr)\n\n\t\t\t\/\/wave subboxes may have been properly parsed\n \t\t\tif ((wave->original_4cc == GF_QT_BOX_TYPE_WAVE) && gf_list_count(wave->child_boxes)) {\n \t\t\t\tu32 i;\n for (i =0; ichild_boxes); i++) {\n GF_Box *inner_box = (GF_Box *)gf_list_get(wave->child_boxes, i);\n if (inner_box->type == GF_ISOM_BOX_TYPE_ESDS) {\n ptr->esd = (GF_ESDBox *)inner_box;\n \t\t\t\t\t\tif (ptr->qtff_mode & GF_ISOM_AUDIO_QTFF_CONVERT_FLAG) {\n \tgf_list_rem(a->child_boxes, i);\n \tdrop_wave=GF_TRUE;\n \tptr->compression_id = 0;\n \tgf_list_add(ptr->child_boxes, inner_box);\n\t\t\t\t\t\t}\n }\n }\n\t\t\t\tif (drop_wave) {\n\t\t\t\t\tgf_isom_box_del_parent(&ptr->child_boxes, a);\n \tptr->qtff_mode = GF_ISOM_AUDIO_QTFF_NONE;\n\t\t\t\t\tptr->version = 0;\n\t\t\t\t\treturn GF_OK;\n\t\t\t\t}\n ptr->qtff_mode = GF_ISOM_AUDIO_QTFF_ON_EXT_VALID;\n return GF_OK;\n }\n gf_isom_box_del_parent(&ptr->child_boxes, a);\n return GF_ISOM_INVALID_MEDIA;\n\n\t\t}\n \t\tptr->qtff_mode &= ~GF_ISOM_AUDIO_QTFF_CONVERT_FLAG;\n\n \t\tif ((wave->original_4cc == GF_QT_BOX_TYPE_WAVE) && gf_list_count(wave->child_boxes)) {\n\t\t\tptr->qtff_mode = GF_ISOM_AUDIO_QTFF_ON_NOEXT;\n\t\t}\n\t\treturn GF_OK;\n\tcase GF_QT_BOX_TYPE_WAVE:\n\t{\n\t\tu32 subtype = 0;\n\t\tGF_Box **cfg_ptr = NULL;\n\t\tif (s->type == GF_ISOM_BOX_TYPE_MP4A) {\n\t\t\tcfg_ptr = (GF_Box **) &ptr->esd;\n\t\t\tsubtype = GF_ISOM_BOX_TYPE_ESDS;\n\t\t}\n\t\telse if (s->type == GF_ISOM_BOX_TYPE_AC3) {\n\t\t\tcfg_ptr = (GF_Box **) &ptr->cfg_ac3;\n\t\t\tsubtype = GF_ISOM_BOX_TYPE_DAC3;\n\t\t}\n\t\telse if (s->type == GF_ISOM_BOX_TYPE_EC3) {\n\t\t\tcfg_ptr = (GF_Box **) &ptr->cfg_ac3;\n\t\t\tsubtype = GF_ISOM_BOX_TYPE_DEC3;\n\t\t}\n\t\telse if (s->type == GF_ISOM_BOX_TYPE_OPUS) {\n\t\t\tcfg_ptr = (GF_Box **) &ptr->cfg_opus;\n\t\t\tsubtype = GF_ISOM_BOX_TYPE_DOPS;\n\t\t}\n\t\telse if ((s->type == GF_ISOM_BOX_TYPE_MHA1)\n\t\t\t|| (s->type == GF_ISOM_BOX_TYPE_MHA2)\n\t\t\t|| (s->type == GF_ISOM_BOX_TYPE_MHM1)\n\t\t\t|| (s->type == GF_ISOM_BOX_TYPE_MHM2)\n\t\t) {\n\t\t\tcfg_ptr = (GF_Box **) &ptr->cfg_mha;\n\t\t\tsubtype = GF_ISOM_BOX_TYPE_MHAC;\n\t\t}\n\n\t\tif (cfg_ptr) {\n\t\t\tif (*cfg_ptr) ERROR_ON_DUPLICATED_BOX(a, ptr)\n\n\t\t\t\/\/wave subboxes may have been properly parsed\n \t\t\tif (gf_list_count(a->child_boxes)) {\n \t\t\t\tu32 i;\n for (i =0; ichild_boxes); i++) {\n GF_Box *inner_box = (GF_Box *)gf_list_get(a->child_boxes, i);\n if (inner_box->type == subtype) {\n *cfg_ptr = inner_box;\n \t\t\t\t\t\tif (ptr->qtff_mode & GF_ISOM_AUDIO_QTFF_CONVERT_FLAG) {\n \tgf_list_rem(a->child_boxes, i);\n \tdrop_wave=GF_TRUE;\n \tgf_list_add(ptr->child_boxes, inner_box);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n }\n }\n\t\t\t\tif (drop_wave) {\n\t\t\t\t\tgf_isom_box_del_parent(&ptr->child_boxes, a);\n \tptr->qtff_mode = GF_ISOM_AUDIO_QTFF_NONE;\n\t\t\t\t\tptr->compression_id = 0;\n\t\t\t\t\tptr->version = 0;\n\t\t\t\t\treturn GF_OK;\n\t\t\t\t}\n ptr->qtff_mode = GF_ISOM_AUDIO_QTFF_ON_EXT_VALID;\n return GF_OK;\n }\n\t\t}\n\t}\n \t\tptr->qtff_mode = GF_ISOM_AUDIO_QTFF_ON_EXT_VALID;\n\t\treturn GF_OK;\n\t}\n\treturn GF_OK;\n}","target":0,"code_token_length":1623,"total_token_length":1954,"max_tokens_setting":2048} +{"idx":325684,"func":"POWERPC_FAMILY(POWER8E)(ObjectClass *oc, void *data)\n\n{\n\n DeviceClass *dc = DEVICE_CLASS(oc);\n\n PowerPCCPUClass *pcc = POWERPC_CPU_CLASS(oc);\n\n\n\n dc->fw_name = \"PowerPC,POWER8\";\n\n dc->desc = \"POWER8E\";\n\n dc->props = powerpc_servercpu_properties;\n\n pcc->pvr_match = ppc_pvr_match_power8;\n\n pcc->pcr_mask = PCR_COMPAT_2_05 | PCR_COMPAT_2_06;\n\n pcc->init_proc = init_proc_POWER8;\n\n pcc->check_pow = check_pow_nocheck;\n\n pcc->insns_flags = PPC_INSNS_BASE | PPC_ISEL | PPC_STRING | PPC_MFTB |\n\n PPC_FLOAT | PPC_FLOAT_FSEL | PPC_FLOAT_FRES |\n\n PPC_FLOAT_FSQRT | PPC_FLOAT_FRSQRTE |\n\n PPC_FLOAT_FRSQRTES |\n\n PPC_FLOAT_STFIWX |\n\n PPC_FLOAT_EXT |\n\n PPC_CACHE | PPC_CACHE_ICBI | PPC_CACHE_DCBZ |\n\n PPC_MEM_SYNC | PPC_MEM_EIEIO |\n\n PPC_MEM_TLBIE | PPC_MEM_TLBSYNC |\n\n PPC_64B | PPC_64BX | PPC_ALTIVEC |\n\n PPC_SEGMENT_64B | PPC_SLBI |\n\n PPC_POPCNTB | PPC_POPCNTWD;\n\n pcc->insns_flags2 = PPC2_VSX | PPC2_VSX207 | PPC2_DFP | PPC2_DBRX |\n\n PPC2_PERM_ISA206 | PPC2_DIVE_ISA206 |\n\n PPC2_ATOMIC_ISA206 | PPC2_FP_CVT_ISA206 |\n\n PPC2_FP_TST_ISA206 | PPC2_BCTAR_ISA207 |\n\n PPC2_LSQ_ISA207 | PPC2_ALTIVEC_207 |\n\n PPC2_ISA205 | PPC2_ISA207S;\n\n pcc->msr_mask = (1ull << MSR_SF) |\n\n (1ull << MSR_TM) |\n\n (1ull << MSR_VR) |\n\n (1ull << MSR_VSX) |\n\n (1ull << MSR_EE) |\n\n (1ull << MSR_PR) |\n\n (1ull << MSR_FP) |\n\n (1ull << MSR_ME) |\n\n (1ull << MSR_FE0) |\n\n (1ull << MSR_SE) |\n\n (1ull << MSR_DE) |\n\n (1ull << MSR_FE1) |\n\n (1ull << MSR_IR) |\n\n (1ull << MSR_DR) |\n\n (1ull << MSR_PMM) |\n\n (1ull << MSR_RI) |\n\n (1ull << MSR_LE);\n\n pcc->mmu_model = POWERPC_MMU_2_06;\n\n#if defined(CONFIG_SOFTMMU)\n\n pcc->handle_mmu_fault = ppc_hash64_handle_mmu_fault;\n\n#endif\n\n pcc->excp_model = POWERPC_EXCP_POWER7;\n\n pcc->bus_model = PPC_FLAGS_INPUT_POWER7;\n\n pcc->bfd_mach = bfd_mach_ppc64;\n\n pcc->flags = POWERPC_FLAG_VRE | POWERPC_FLAG_SE |\n\n POWERPC_FLAG_BE | POWERPC_FLAG_PMM |\n\n POWERPC_FLAG_BUS_CLK | POWERPC_FLAG_CFAR |\n\n POWERPC_FLAG_VSX;\n\n pcc->l1_dcache_size = 0x8000;\n\n pcc->l1_icache_size = 0x8000;\n\n pcc->interrupts_big_endian = ppc_cpu_interrupts_big_endian_lpcr;\n\n}\n","target":0,"code_token_length":799,"total_token_length":1130,"max_tokens_setting":2048} +{"idx":153986,"func":"su_main (int argc, char **argv, int mode)\n{\n int optc;\n const char *new_user = DEFAULT_USER, *runuser_user = NULL;\n char *command = NULL;\n int request_same_session = 0;\n char *shell = NULL;\n struct passwd *pw;\n struct passwd pw_copy;\n\n gid_t *groups = NULL;\n size_t ngroups = 0;\n bool use_supp = false;\n bool use_gid = false;\n gid_t gid = 0;\n\n static const struct option longopts[] = {\n {\"command\", required_argument, NULL, 'c'},\n {\"session-command\", required_argument, NULL, 'C'},\n {\"fast\", no_argument, NULL, 'f'},\n {\"login\", no_argument, NULL, 'l'},\n {\"preserve-environment\", no_argument, NULL, 'p'},\n {\"shell\", required_argument, NULL, 's'},\n {\"group\", required_argument, NULL, 'g'},\n {\"supp-group\", required_argument, NULL, 'G'},\n {\"user\", required_argument, NULL, 'u'},\t\t\/* runuser only *\/\n {\"help\", no_argument, 0, 'h'},\n {\"version\", no_argument, 0, 'V'},\n {NULL, 0, NULL, 0}\n };\n\n setlocale (LC_ALL, \"\");\n bindtextdomain (PACKAGE, LOCALEDIR);\n textdomain (PACKAGE);\n atexit(close_stdout);\n\n su_mode = mode;\n fast_startup = false;\n simulate_login = false;\n change_environment = true;\n\n while ((optc = getopt_long (argc, argv, \"c:fg:G:lmps:u:hV\", longopts, NULL)) != -1)\n {\n switch (optc)\n\t{\n\tcase 'c':\n\t command = optarg;\n\t break;\n\n case 'C':\n command = optarg;\n request_same_session = 1;\n break;\n\n\tcase 'f':\n\t fast_startup = true;\n\t break;\n\n\tcase 'g':\n\t use_gid = true;\n\t gid = add_supp_group(optarg, &groups, &ngroups);\n\t break;\n\n\tcase 'G':\n\t use_supp = true;\n\t add_supp_group(optarg, &groups, &ngroups);\n\t break;\n\n\tcase 'l':\n\t simulate_login = true;\n\t break;\n\n\tcase 'm':\n\tcase 'p':\n\t change_environment = false;\n\t break;\n\n\tcase 's':\n\t shell = optarg;\n\t break;\n\n\tcase 'u':\n\t if (su_mode != RUNUSER_MODE)\n\t usage (EXIT_FAILURE);\n\t runuser_user = optarg;\n\t break;\n\n\tcase 'h':\n\t usage(0);\n\n\tcase 'V':\n\t printf(UTIL_LINUX_VERSION);\n\t exit(EXIT_SUCCESS);\n\n\tdefault:\n\t errtryhelp(EXIT_FAILURE);\n\t}\n }\n\n restricted = evaluate_uid ();\n\n if (optind < argc && !strcmp (argv[optind], \"-\"))\n {\n simulate_login = true;\n ++optind;\n }\n\n if (simulate_login && !change_environment) {\n warnx(_(\"ignoring --preserve-environment, it's mutually exclusive with --login\"));\n change_environment = true;\n }\n\n switch (su_mode) {\n case RUNUSER_MODE:\n if (runuser_user) {\n \/* runuser -u *\/\n new_user = runuser_user;\n if (shell || fast_startup || command || simulate_login) {\n errx(EXIT_FAILURE,\n\t _(\"options --{shell,fast,command,session-command,login} and \"\n\t \"--user are mutually exclusive\"));\n }\n if (optind == argc)\n errx(EXIT_FAILURE, _(\"no command was specified\"));\n\n break;\n }\n \/* fallthrough if -u is not specified, then follow\n * traditional su(1) behavior\n *\/\n case SU_MODE:\n if (optind < argc)\n new_user = argv[optind++];\n break;\n }\n\n if ((use_supp || use_gid) && restricted)\n errx(EXIT_FAILURE, _(\"only root can specify alternative groups\"));\n\n logindefs_load_defaults = load_config;\n\n pw = getpwnam (new_user);\n if (! (pw && pw->pw_name && pw->pw_name[0] && pw->pw_dir && pw->pw_dir[0]\n\t && pw->pw_passwd))\n errx (EXIT_FAILURE, _(\"user %s does not exist\"), new_user);\n\n \/* Make a copy of the password information and point pw at the local\n copy instead. Otherwise, some systems (e.g. Linux) would clobber\n the static data through the getlogin call from log_su.\n Also, make sure pw->pw_shell is a nonempty string.\n It may be NULL when NEW_USER is a username that is retrieved via NIS (YP),\n but that doesn't have a default shell listed. *\/\n pw_copy = *pw;\n pw = &pw_copy;\n pw->pw_name = xstrdup (pw->pw_name);\n pw->pw_passwd = xstrdup (pw->pw_passwd);\n pw->pw_dir = xstrdup (pw->pw_dir);\n pw->pw_shell = xstrdup (pw->pw_shell && pw->pw_shell[0]\n\t\t\t ? pw->pw_shell\n\t\t\t : DEFAULT_SHELL);\n endpwent ();\n\n if (use_supp && !use_gid)\n pw->pw_gid = groups[0];\n else if (use_gid)\n pw->pw_gid = gid;\n\n authenticate (pw);\n\n if (request_same_session || !command || !pw->pw_uid)\n same_session = 1;\n\n \/* initialize shell variable only if \"-u \" not specified *\/\n if (runuser_user) {\n shell = NULL;\n } else {\n if (!shell && !change_environment)\n shell = getenv (\"SHELL\");\n if (shell && getuid () != 0 && restricted_shell (pw->pw_shell))\n {\n\t\/* The user being su'd to has a nonstandard shell, and so is\n\t probably a uucp account or has restricted access. Don't\n\t compromise the account by allowing access with a standard\n\t shell. *\/\n\twarnx (_(\"using restricted shell %s\"), pw->pw_shell);\n\tshell = NULL;\n }\n shell = xstrdup (shell ? shell : pw->pw_shell);\n }\n\n init_groups (pw, groups, ngroups);\n\n if (!simulate_login || command)\n suppress_pam_info = 1;\t\t\/* don't print PAM info messages *\/\n\n create_watching_parent ();\n \/* Now we're in the child. *\/\n\n change_identity (pw);\n if (!same_session)\n setsid ();\n\n \/* Set environment after pam_open_session, which may put KRB5CCNAME\n into the pam_env, etc. *\/\n\n modify_environment (pw, shell);\n\n if (simulate_login && chdir (pw->pw_dir) != 0)\n warn (_(\"warning: cannot change directory to %s\"), pw->pw_dir);\n\n if (shell)\n run_shell (shell, command, argv + optind, max (0, argc - optind));\n else {\n execvp(argv[optind], &argv[optind]);\n err(EXIT_FAILURE, _(\"failed to execute %s\"), argv[optind]);\n }\n}","target":0,"code_token_length":1562,"total_token_length":1893,"max_tokens_setting":2048} +{"idx":302366,"func":"EditorButton(XtermWidget xw, XButtonEvent *event)\n{\n TScreen *screen = TScreenOf(xw);\n int pty = screen->respond;\n int mouse_limit = MouseLimit(screen);\n Char line[32];\n Char final = 'M';\n int row, col;\n int button;\n unsigned count = 0;\n Boolean changed = True;\n\n \/* If button event, get button # adjusted for DEC compatibility *\/\n button = (int) (event->button - 1);\n if (button >= 3)\n\tbutton++;\n\n \/* Ignore buttons that cannot be encoded *\/\n if (screen->send_mouse_pos == X10_MOUSE) {\n\tif (button > 3)\n\t return;\n } else if (screen->extend_coords == SET_SGR_EXT_MODE_MOUSE\n\t || screen->extend_coords == SET_URXVT_EXT_MODE_MOUSE\n\t || screen->extend_coords == SET_PIXEL_POSITION_MOUSE) {\n\tif (button > 15) {\n\t return;\n\t}\n } else {\n\tif (button > 11) {\n\t return;\n\t}\n }\n\n if (screen->extend_coords == SET_PIXEL_POSITION_MOUSE) {\n\trow = event->y - OriginY(screen);\n\tcol = event->x - OriginX(screen);\n } else {\n\t\/* Compute character position of mouse pointer *\/\n\trow = (event->y - screen->border) \/ FontHeight(screen);\n\tcol = (event->x - OriginX(screen)) \/ FontWidth(screen);\n\n\t\/* Limit to screen dimensions *\/\n\tif (row < 0)\n\t row = 0;\n\telse if (row > screen->max_row)\n\t row = screen->max_row;\n\n\tif (col < 0)\n\t col = 0;\n\telse if (col > screen->max_col)\n\t col = screen->max_col;\n\n\tif (mouse_limit > 0) {\n\t \/* Limit to representable mouse dimensions *\/\n\t if (row > mouse_limit)\n\t\trow = mouse_limit;\n\t if (col > mouse_limit)\n\t\tcol = mouse_limit;\n\t}\n }\n\n \/* Build key sequence starting with \\E[M *\/\n if (screen->control_eight_bits) {\n\tline[count++] = ANSI_CSI;\n } else {\n\tline[count++] = ANSI_ESC;\n\tline[count++] = '[';\n }\n switch (screen->extend_coords) {\n case 0:\n case SET_EXT_MODE_MOUSE:\n#if OPT_SCO_FUNC_KEYS\n\tif (xw->keyboard.type == keyboardIsSCO) {\n\t \/*\n\t * SCO function key F1 is \\E[M, which would conflict with xterm's\n\t * normal kmous.\n\t *\/\n\t line[count++] = '>';\n\t}\n#endif\n\tline[count++] = final;\n\tbreak;\n case SET_SGR_EXT_MODE_MOUSE:\n case SET_PIXEL_POSITION_MOUSE:\n\tline[count++] = '<';\n\tbreak;\n }\n\n \/* Add event code to key sequence *\/\n if (okSendMousePos(xw) == X10_MOUSE) {\n\tcount = EMIT_BUTTON(button);\n } else {\n\t\/* Button-Motion events *\/\n\tswitch (event->type) {\n\tcase ButtonPress:\n\t screen->mouse_button |= ButtonBit(button);\n\t count = EMIT_BUTTON(button);\n\t break;\n\tcase ButtonRelease:\n\t \/*\n\t * The (vertical) wheel mouse interface generates release-events\n\t * for buttons 4 and 5.\n\t *\n\t * The X10\/X11 xterm protocol maps the release for buttons 1..3 to\n\t * a -1, which will be later mapped into a \"0\" (some button was\n\t * released), At this point, buttons 1..3 are encoded 0..2 (the\n\t * code 3 is unused).\n\t *\n\t * The SGR (extended) xterm mouse protocol keeps the button number\n\t * and uses a \"m\" to indicate button release.\n\t *\n\t * The behavior for mice with more buttons is unclear, and may be\n\t * revised -TD\n\t *\/\n\t screen->mouse_button &= ~ButtonBit(button);\n\t if (button < 3 || button > 5) {\n\t\tswitch (screen->extend_coords) {\n\t\tcase SET_SGR_EXT_MODE_MOUSE:\n\t\tcase SET_PIXEL_POSITION_MOUSE:\n\t\t final = 'm';\n\t\t break;\n\t\tdefault:\n\t\t button = -1;\n\t\t break;\n\t\t}\n\t }\n\t count = EMIT_BUTTON(button);\n\t break;\n\tcase MotionNotify:\n\t \/* BTN_EVENT_MOUSE and ANY_EVENT_MOUSE modes send motion\n\t * events only if character cell has changed.\n\t *\/\n\t if ((row == screen->mouse_row)\n\t\t&& (col == screen->mouse_col)) {\n\t\tchanged = False;\n\t } else {\n\t\tcount = EMIT_BUTTON(FirstBitN(screen->mouse_button));\n\t }\n\t break;\n\tdefault:\n\t changed = False;\n\t break;\n\t}\n }\n\n if (changed) {\n\tscreen->mouse_row = row;\n\tscreen->mouse_col = col;\n\n\tTRACE((\"mouse at %d,%d button+mask = %#x\\n\", row, col, line[count - 1]));\n\n\t\/* Add pointer position to key sequence *\/\n\tcount = EmitMousePositionSeparator(screen, line, count);\n\tcount = EmitMousePosition(screen, line, count, col);\n\tcount = EmitMousePositionSeparator(screen, line, count);\n\tcount = EmitMousePosition(screen, line, count, row);\n\n\tswitch (screen->extend_coords) {\n\tcase SET_SGR_EXT_MODE_MOUSE:\n\tcase SET_URXVT_EXT_MODE_MOUSE:\n\tcase SET_PIXEL_POSITION_MOUSE:\n\t line[count++] = final;\n\t break;\n\t}\n\n\t\/* Transmit key sequence to process running under xterm *\/\n\tTRACE((\"EditorButton -> %s\\n\", visibleChars(line, count)));\n\tv_write(pty, line, count);\n }\n return;\n}","target":0,"code_token_length":1212,"total_token_length":1543,"max_tokens_setting":2048} +{"idx":219029,"func":"void Document::InitSecurityContext(const DocumentInit& initializer) {\n DCHECK(!GetSecurityOrigin());\n\n if (!initializer.HasSecurityContext()) {\n cookie_url_ = KURL(g_empty_string);\n SetSecurityOrigin(SecurityOrigin::CreateUniqueOpaque());\n InitContentSecurityPolicy();\n ApplyFeaturePolicy({});\n return;\n }\n\n SandboxFlags sandbox_flags = initializer.GetSandboxFlags();\n if (fetcher_->Archive()) {\n sandbox_flags |=\n kSandboxAll &\n ~(kSandboxPopups | kSandboxPropagatesToAuxiliaryBrowsingContexts);\n }\n EnforceSandboxFlags(sandbox_flags);\n SetInsecureRequestPolicy(initializer.GetInsecureRequestPolicy());\n if (initializer.InsecureNavigationsToUpgrade()) {\n for (auto to_upgrade : *initializer.InsecureNavigationsToUpgrade())\n AddInsecureNavigationUpgrade(to_upgrade);\n }\n\n ContentSecurityPolicy* policy_to_inherit = nullptr;\n\n if (IsSandboxed(kSandboxOrigin)) {\n cookie_url_ = url_;\n scoped_refptr security_origin =\n SecurityOrigin::CreateUniqueOpaque();\n Document* owner = initializer.OwnerDocument();\n if (owner) {\n if (owner->GetSecurityOrigin()->IsPotentiallyTrustworthy())\n security_origin->SetOpaqueOriginIsPotentiallyTrustworthy(true);\n if (owner->GetSecurityOrigin()->CanLoadLocalResources())\n security_origin->GrantLoadLocalResources();\n policy_to_inherit = owner->GetContentSecurityPolicy();\n }\n SetSecurityOrigin(std::move(security_origin));\n } else if (Document* owner = initializer.OwnerDocument()) {\n cookie_url_ = owner->CookieURL();\n SetSecurityOrigin(owner->GetMutableSecurityOrigin());\n policy_to_inherit = owner->GetContentSecurityPolicy();\n } else {\n cookie_url_ = url_;\n SetSecurityOrigin(SecurityOrigin::Create(url_));\n }\n\n if (initializer.IsHostedInReservedIPRange()) {\n SetAddressSpace(GetSecurityOrigin()->IsLocalhost()\n ? mojom::IPAddressSpace::kLocal\n : mojom::IPAddressSpace::kPrivate);\n } else if (GetSecurityOrigin()->IsLocal()) {\n SetAddressSpace(mojom::IPAddressSpace::kLocal);\n } else {\n SetAddressSpace(mojom::IPAddressSpace::kPublic);\n }\n\n if (ImportsController()) {\n SetContentSecurityPolicy(\n ImportsController()->Master()->GetContentSecurityPolicy());\n } else {\n InitContentSecurityPolicy(nullptr, policy_to_inherit);\n }\n\n if (Settings* settings = initializer.GetSettings()) {\n if (!settings->GetWebSecurityEnabled()) {\n GetMutableSecurityOrigin()->GrantUniversalAccess();\n } else if (GetSecurityOrigin()->IsLocal()) {\n if (settings->GetAllowUniversalAccessFromFileURLs()) {\n GetMutableSecurityOrigin()->GrantUniversalAccess();\n } else if (!settings->GetAllowFileAccessFromFileURLs()) {\n GetMutableSecurityOrigin()->BlockLocalAccessFromLocalOrigin();\n }\n }\n }\n\n if (GetSecurityOrigin()->IsOpaque() &&\n SecurityOrigin::Create(url_)->IsPotentiallyTrustworthy())\n GetMutableSecurityOrigin()->SetOpaqueOriginIsPotentiallyTrustworthy(true);\n\n ApplyFeaturePolicy({});\n\n InitSecureContextState();\n}\n","target":0,"code_token_length":698,"total_token_length":1029,"max_tokens_setting":2048} +{"idx":104806,"func":"char * get_fru_area_str(uint8_t * data, uint32_t * offset)\n{\n\tstatic const char bcd_plus[] = \"0123456789 -.:,_\";\n\tchar * str;\n\tint len, off, size, i, j, k, typecode, char_idx;\n\tunion {\n\t\tuint32_t bits;\n\t\tchar chars[4];\n\t} u;\n\n\tsize = 0;\n\toff = *offset;\n\n\t\/* bits 6:7 contain format *\/\n\ttypecode = ((data[off] & 0xC0) >> 6);\n\n\t\/\/ printf(\"Typecode:%i\\n\", typecode);\n\t\/* bits 0:5 contain length *\/\n\tlen = data[off++];\n\tlen &= 0x3f;\n\n\tswitch (typecode) {\n\tcase 0: \/* 00b: binary\/unspecified *\/\n\tcase 1: \/* 01b: BCD plus *\/\n\t\t\/* hex dump or BCD -> 2x length *\/\n\t\tsize = (len * 2);\n\t\tbreak;\n\tcase 2: \/* 10b: 6-bit ASCII *\/\n\t\t\/* 4 chars per group of 1-3 bytes *\/\n\t\tsize = (((len * 4 + 2) \/ 3) & ~3);\n\t\tbreak;\n\tcase 3: \/* 11b: 8-bit ASCII *\/\n\t\t\/* no length adjustment *\/\n\t\tsize = len;\n\t\tbreak;\n\t}\n\n\tif (size < 1) {\n\t\t*offset = off;\n\t\treturn NULL;\n\t}\n\tstr = malloc(size+1);\n\tif (!str)\n\t\treturn NULL;\n\tmemset(str, 0, size+1);\n\n\tif (size == 0) {\n\t\tstr[0] = '\\0';\n\t\t*offset = off;\n\t\treturn str;\n\t}\n\n\tswitch (typecode) {\n\tcase 0: \/* Binary *\/\n\t\tstrncpy(str, buf2str(&data[off], len), size);\n\t\tbreak;\n\n\tcase 1: \/* BCD plus *\/\n\t\tfor (k = 0; k < size; k++)\n\t\t\tstr[k] = bcd_plus[((data[off + k \/ 2] >> ((k % 2) ? 0 : 4)) & 0x0f)];\n\t\tstr[k] = '\\0';\n\t\tbreak;\n\n\tcase 2: \/* 6-bit ASCII *\/\n\t\tfor (i = j = 0; i < len; i += 3) {\n\t\t\tu.bits = 0;\n\t\t\tk = ((len - i) < 3 ? (len - i) : 3);\n#if WORDS_BIGENDIAN\n\t\t\tu.chars[3] = data[off+i];\n\t\t\tu.chars[2] = (k > 1 ? data[off+i+1] : 0);\n\t\t\tu.chars[1] = (k > 2 ? data[off+i+2] : 0);\n\t\t\tchar_idx = 3;\n#else\n\t\t\tmemcpy((void *)&u.bits, &data[off+i], k);\n\t\t\tchar_idx = 0;\n#endif\n\t\t\tfor (k=0; k<4; k++) {\n\t\t\t\tstr[j++] = ((u.chars[char_idx] & 0x3f) + 0x20);\n\t\t\t\tu.bits >>= 6;\n\t\t\t}\n\t\t}\n\t\tstr[j] = '\\0';\n\t\tbreak;\n\n\tcase 3:\n\t\tmemcpy(str, &data[off], size);\n\t\tstr[size] = '\\0';\n\t\tbreak;\n\t}\n\n\toff += len;\n\t*offset = off;\n\n\treturn str;\n}","target":0,"code_token_length":761,"total_token_length":1092,"max_tokens_setting":2048} +{"idx":327170,"func":"int qcow2_update_header(BlockDriverState *bs)\n\n\n BDRVQcowState *s = bs->opaque;\n\n QCowHeader *header;\n\n char *buf;\n\n size_t buflen = s->cluster_size;\n\n int ret;\n\n uint64_t total_size;\n\n uint32_t refcount_table_clusters;\n\n size_t header_length;\n\n Qcow2UnknownHeaderExtension *uext;\n\n\n\n buf = qemu_blockalign(bs, buflen);\n\n\n\n \/* Header structure *\/\n\n header = (QCowHeader*) buf;\n\n\n\n if (buflen < sizeof(*header)) {\n\n ret = -ENOSPC;\n\n goto fail;\n\n }\n\n\n\n header_length = sizeof(*header) + s->unknown_header_fields_size;\n\n total_size = bs->total_sectors * BDRV_SECTOR_SIZE;\n\n refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);\n\n\n\n *header = (QCowHeader) {\n\n \/* Version 2 fields *\/\n\n .magic = cpu_to_be32(QCOW_MAGIC),\n\n .version = cpu_to_be32(s->qcow_version),\n\n .backing_file_offset = 0,\n\n .backing_file_size = 0,\n\n .cluster_bits = cpu_to_be32(s->cluster_bits),\n\n .size = cpu_to_be64(total_size),\n\n .crypt_method = cpu_to_be32(s->crypt_method_header),\n\n .l1_size = cpu_to_be32(s->l1_size),\n\n .l1_table_offset = cpu_to_be64(s->l1_table_offset),\n\n .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),\n\n .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),\n\n .nb_snapshots = cpu_to_be32(s->nb_snapshots),\n\n .snapshots_offset = cpu_to_be64(s->snapshots_offset),\n\n\n\n \/* Version 3 fields *\/\n\n .incompatible_features = cpu_to_be64(s->incompatible_features),\n\n .compatible_features = cpu_to_be64(s->compatible_features),\n\n .autoclear_features = cpu_to_be64(s->autoclear_features),\n\n .refcount_order = cpu_to_be32(3 + REFCOUNT_SHIFT),\n\n .header_length = cpu_to_be32(header_length),\n\n };\n\n\n\n \/* For older versions, write a shorter header *\/\n\n switch (s->qcow_version) {\n\n case 2:\n\n ret = offsetof(QCowHeader, incompatible_features);\n\n break;\n\n case 3:\n\n ret = sizeof(*header);\n\n break;\n\n default:\n\n ret = -EINVAL;\n\n goto fail;\n\n }\n\n\n\n buf += ret;\n\n buflen -= ret;\n\n memset(buf, 0, buflen);\n\n\n\n \/* Preserve any unknown field in the header *\/\n\n if (s->unknown_header_fields_size) {\n\n if (buflen < s->unknown_header_fields_size) {\n\n ret = -ENOSPC;\n\n goto fail;\n\n }\n\n\n\n memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);\n\n buf += s->unknown_header_fields_size;\n\n buflen -= s->unknown_header_fields_size;\n\n }\n\n\n\n \/* Backing file format header extension *\/\n\n if (*bs->backing_format) {\n\n ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,\n\n bs->backing_format, strlen(bs->backing_format),\n\n buflen);\n\n if (ret < 0) {\n\n goto fail;\n\n }\n\n\n\n buf += ret;\n\n buflen -= ret;\n\n }\n\n\n\n \/* Feature table *\/\n\n Qcow2Feature features[] = {\n\n\n\n .bit = QCOW2_INCOMPAT_DIRTY_BITNR,\n\n .name = \"dirty bit\",\n\n\n\n\n\n\n\n\n .type = QCOW2_FEAT_TYPE_COMPATIBLE,\n\n .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,\n\n .name = \"lazy refcounts\",\n\n\n };\n\n\n\n ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,\n\n features, sizeof(features), buflen);\n\n if (ret < 0) {\n\n goto fail;\n\n }\n\n buf += ret;\n\n buflen -= ret;\n\n\n\n \/* Keep unknown header extensions *\/\n\n QLIST_FOREACH(uext, &s->unknown_header_ext, next) {\n\n ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);\n\n if (ret < 0) {\n\n goto fail;\n\n }\n\n\n\n buf += ret;\n\n buflen -= ret;\n\n }\n\n\n\n \/* End of header extensions *\/\n\n ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);\n\n if (ret < 0) {\n\n goto fail;\n\n }\n\n\n\n buf += ret;\n\n buflen -= ret;\n\n\n\n \/* Backing file name *\/\n\n if (*bs->backing_file) {\n\n size_t backing_file_len = strlen(bs->backing_file);\n\n\n\n if (buflen < backing_file_len) {\n\n ret = -ENOSPC;\n\n goto fail;\n\n }\n\n\n\n \/* Using strncpy is ok here, since buf is not NUL-terminated. *\/\n\n strncpy(buf, bs->backing_file, buflen);\n\n\n\n header->backing_file_offset = cpu_to_be64(buf - ((char*) header));\n\n header->backing_file_size = cpu_to_be32(backing_file_len);\n\n }\n\n\n\n \/* Write the new header *\/\n\n ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);\n\n if (ret < 0) {\n\n goto fail;\n\n }\n\n\n\n ret = 0;\n\nfail:\n\n qemu_vfree(header);\n\n return ret;\n\n}","target":1,"code_token_length":1225,"total_token_length":1556,"max_tokens_setting":2048} +{"idx":509880,"func":"com_status(String *buffer __attribute__((unused)),\n\t char *line __attribute__((unused)))\n{\n const char *status_str;\n char buff[40];\n ulonglong id;\n MYSQL_RES *result;\n LINT_INIT(result);\n\n if (mysql_real_query_for_lazy(\n C_STRING_WITH_LEN(\"select DATABASE(), USER() limit 1\")))\n return 0;\n\n tee_puts(\"--------------\", stdout);\n usage(1);\t\t\t\t\t\/* Print version *\/\n tee_fprintf(stdout, \"\\nConnection id:\\t\\t%lu\\n\",mysql_thread_id(&mysql));\n \/*\n Don't remove \"limit 1\",\n it is protection againts SQL_SELECT_LIMIT=0\n *\/\n if (!mysql_store_result_for_lazy(&result))\n {\n MYSQL_ROW cur=mysql_fetch_row(result);\n if (cur)\n {\n tee_fprintf(stdout, \"Current database:\\t%s\\n\", cur[0] ? cur[0] : \"\");\n tee_fprintf(stdout, \"Current user:\\t\\t%s\\n\", cur[1]);\n }\n mysql_free_result(result);\n }\n\n#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)\n if ((status_str= mysql_get_ssl_cipher(&mysql)))\n tee_fprintf(stdout, \"SSL:\\t\\t\\tCipher in use is %s\\n\",\n status_str);\n else\n#endif \/* HAVE_OPENSSL && !EMBEDDED_LIBRARY *\/\n tee_puts(\"SSL:\\t\\t\\tNot in use\", stdout);\n\n if (skip_updates)\n {\n my_vidattr(A_BOLD);\n tee_fprintf(stdout, \"\\nAll updates ignored to this database\\n\");\n my_vidattr(A_NORMAL);\n }\n#ifdef USE_POPEN\n tee_fprintf(stdout, \"Current pager:\\t\\t%s\\n\", pager);\n tee_fprintf(stdout, \"Using outfile:\\t\\t'%s'\\n\", opt_outfile ? outfile : \"\");\n#endif\n tee_fprintf(stdout, \"Using delimiter:\\t%s\\n\", delimiter);\n tee_fprintf(stdout, \"Server:\\t\\t\\t%s\\n\", mysql_get_server_name(&mysql));\n tee_fprintf(stdout, \"Server version:\\t\\t%s\\n\", server_version_string(&mysql));\n tee_fprintf(stdout, \"Protocol version:\\t%d\\n\", mysql_get_proto_info(&mysql));\n tee_fprintf(stdout, \"Connection:\\t\\t%s\\n\", mysql_get_host_info(&mysql));\n if ((id= mysql_insert_id(&mysql)))\n tee_fprintf(stdout, \"Insert id:\\t\\t%s\\n\", llstr(id, buff));\n\n \/* \"limit 1\" is protection against SQL_SELECT_LIMIT=0 *\/\n if (mysql_real_query_for_lazy(C_STRING_WITH_LEN(\n \"select @@character_set_client, @@character_set_connection, \"\n \"@@character_set_server, @@character_set_database limit 1\")))\n {\n if (mysql_errno(&mysql) == CR_SERVER_GONE_ERROR)\n return 0;\n }\n if (!mysql_store_result_for_lazy(&result))\n {\n MYSQL_ROW cur=mysql_fetch_row(result);\n if (cur)\n {\n tee_fprintf(stdout, \"Server characterset:\\t%s\\n\", cur[2] ? cur[2] : \"\");\n tee_fprintf(stdout, \"Db characterset:\\t%s\\n\", cur[3] ? cur[3] : \"\");\n tee_fprintf(stdout, \"Client characterset:\\t%s\\n\", cur[0] ? cur[0] : \"\");\n tee_fprintf(stdout, \"Conn. characterset:\\t%s\\n\", cur[1] ? cur[1] : \"\");\n }\n mysql_free_result(result);\n }\n else\n {\n \/* Probably pre-4.1 server *\/\n tee_fprintf(stdout, \"Client characterset:\\t%s\\n\", charset_info->csname);\n tee_fprintf(stdout, \"Server characterset:\\t%s\\n\", mysql.charset->csname);\n }\n\n#ifndef EMBEDDED_LIBRARY\n if (strstr(mysql_get_host_info(&mysql),\"TCP\/IP\") || ! mysql.unix_socket)\n tee_fprintf(stdout, \"TCP port:\\t\\t%d\\n\", mysql.port);\n else\n tee_fprintf(stdout, \"UNIX socket:\\t\\t%s\\n\", mysql.unix_socket);\n if (mysql.net.compress)\n tee_fprintf(stdout, \"Protocol:\\t\\tCompressed\\n\");\n#endif\n\n if ((status_str= mysql_stat(&mysql)) && !mysql_error(&mysql)[0])\n {\n ulong sec;\n const char *pos= strchr(status_str,' ');\n \/* print label *\/\n tee_fprintf(stdout, \"%.*s\\t\\t\\t\", (int) (pos-status_str), status_str);\n if ((status_str= str2int(pos,10,0,LONG_MAX,(long*) &sec)))\n {\n nice_time((double) sec,buff,0);\n tee_puts(buff, stdout);\t\t\t\/* print nice time *\/\n while (*status_str == ' ')\n status_str++; \/* to next info *\/\n tee_putc('\\n', stdout);\n tee_puts(status_str, stdout);\n }\n }\n if (safe_updates)\n {\n my_vidattr(A_BOLD);\n tee_fprintf(stdout, \"\\nNote that you are running in safe_update_mode:\\n\");\n my_vidattr(A_NORMAL);\n tee_fprintf(stdout, \"\\\nUPDATEs and DELETEs that don't use a key in the WHERE clause are not allowed.\\n\\\n(One can force an UPDATE\/DELETE by adding LIMIT # at the end of the command.)\\n\\\nSELECT has an automatic 'LIMIT %lu' if LIMIT is not used.\\n\\\nMax number of examined row combination in a join is set to: %lu\\n\\n\",\nselect_limit, max_join_size);\n }\n tee_puts(\"--------------\\n\", stdout);\n return 0;\n}","target":0,"code_token_length":1224,"total_token_length":1555,"max_tokens_setting":2048} +{"idx":226139,"func":"void DisplayItemList::commitNewDisplayItems(GraphicsLayer* graphicsLayer)\n{\n TRACE_EVENT2(\"blink,benchmark\", \"DisplayItemList::commitNewDisplayItems\", \"current_display_list_size\", (int)m_currentDisplayItems.size(),\n \"num_non_cached_new_items\", (int)m_newDisplayItems.size() - m_numCachedItems);\n\n if (RuntimeEnabledFeatures::slimmingPaintSynchronizedPaintingEnabled()) {\n for (const auto& invalidation : m_invalidations)\n graphicsLayer->setNeedsDisplayInRect(invalidation.rect, invalidation.invalidationReason);\n m_invalidations.clear();\n }\n\n ASSERT(m_scopeStack.isEmpty());\n m_scopeStack.clear();\n m_nextScope = 1;\n ASSERT(!skippingCache());\n#if ENABLE(ASSERT)\n m_newDisplayItemIndicesByClient.clear();\n#endif\n\n if (m_currentDisplayItems.isEmpty()) {\n#if ENABLE(ASSERT)\n for (const auto& item : m_newDisplayItems)\n ASSERT(!item.isCached());\n #endif\n m_currentDisplayItems.swap(m_newDisplayItems);\n m_currentPaintChunks = m_newPaintChunks.releasePaintChunks();\n m_validlyCachedClientsDirty = true;\n m_numCachedItems = 0;\n return;\n }\n\n updateValidlyCachedClientsIfNeeded();\n\n OutOfOrderIndexContext outOfOrderIndexContext(m_currentDisplayItems.begin());\n \n DisplayItems updatedList(std::max(m_currentDisplayItems.usedCapacityInBytes(), m_newDisplayItems.usedCapacityInBytes()));\n Vector updatedPaintChunks;\n DisplayItems::iterator currentIt = m_currentDisplayItems.begin();\n DisplayItems::iterator currentEnd = m_currentDisplayItems.end();\n for (DisplayItems::iterator newIt = m_newDisplayItems.begin(); newIt != m_newDisplayItems.end(); ++newIt) {\n const DisplayItem& newDisplayItem = *newIt;\n const DisplayItem::Id newDisplayItemId = newDisplayItem.nonCachedId();\n bool newDisplayItemHasCachedType = newDisplayItem.type() != newDisplayItemId.type;\n\n bool isSynchronized = currentIt != currentEnd && newDisplayItemId.matches(*currentIt);\n\n if (newDisplayItemHasCachedType) {\n ASSERT(newDisplayItem.isCached());\n ASSERT(clientCacheIsValid(newDisplayItem.client()) || (RuntimeEnabledFeatures::slimmingPaintOffsetCachingEnabled() && !paintOffsetWasInvalidated(newDisplayItem.client())));\n if (!isSynchronized) {\n currentIt = findOutOfOrderCachedItem(newDisplayItemId, outOfOrderIndexContext);\n\n if (currentIt == currentEnd) {\n#ifndef NDEBUG\n showDebugData();\n WTFLogAlways(\"%s not found in m_currentDisplayItems\\n\", newDisplayItem.asDebugString().utf8().data());\n#endif\n ASSERT_NOT_REACHED();\n continue;\n }\n }\n#if ENABLE(ASSERT)\n if (RuntimeEnabledFeatures::slimmingPaintUnderInvalidationCheckingEnabled()) {\n DisplayItems::iterator temp = currentIt;\n checkUnderInvalidation(newIt, temp);\n }\n#endif\n if (newDisplayItem.isCachedDrawing()) {\n updatedList.appendByMoving(*currentIt);\n ++currentIt;\n } else {\n ASSERT(newDisplayItem.isCachedSubsequence());\n copyCachedSubsequence(currentIt, updatedList);\n ASSERT(updatedList.last().isEndSubsequence());\n }\n } else {\n ASSERT(!newDisplayItem.isDrawing()\n || newDisplayItem.skippedCache()\n || !clientCacheIsValid(newDisplayItem.client())\n || (RuntimeEnabledFeatures::slimmingPaintOffsetCachingEnabled() && paintOffsetWasInvalidated(newDisplayItem.client())));\n\n updatedList.appendByMoving(*newIt);\n\n if (isSynchronized)\n ++currentIt;\n }\n if (currentIt - outOfOrderIndexContext.nextItemToIndex > 0)\n outOfOrderIndexContext.nextItemToIndex = currentIt;\n }\n\n#if ENABLE(ASSERT)\n if (RuntimeEnabledFeatures::slimmingPaintUnderInvalidationCheckingEnabled())\n checkNoRemainingCachedDisplayItems();\n #endif \/\/ ENABLE(ASSERT)\n \n \/\/ TODO(jbroman): When subsequence caching applies to SPv2, we'll need to\n \/\/ merge the paint chunks as well.\n m_currentPaintChunks = m_newPaintChunks.releasePaintChunks();\n\n m_newDisplayItems.clear();\n m_validlyCachedClientsDirty = true;\n m_currentDisplayItems.swap(updatedList);\n m_numCachedItems = 0;\n\n#if ENABLE(ASSERT)\n m_clientsWithPaintOffsetInvalidations.clear();\n#endif\n}\n","target":0,"code_token_length":955,"total_token_length":1286,"max_tokens_setting":2048} +{"idx":13309,"func":"int main(int argc, char **argv)\n{\n\n u8 *byteStrmStart;\n u8 *byteStrm;\n u32 strmLen;\n u32 picSize;\n H264SwDecInst decInst;\n H264SwDecRet ret;\n H264SwDecInput decInput;\n H264SwDecOutput decOutput;\n H264SwDecPicture decPicture;\n H264SwDecInfo decInfo;\n u32 picNumber;\n\n FILE *finput;\n FILE *foutput;\n\n \/* Check that enough command line arguments given, if not -> print usage\n * information out *\/\n if (argc < 2)\n {\n printf( \"Usage: %s file.h264\\n\", argv[0]);\n return -1;\n }\n\n \/* open output file for writing, output file named out.yuv. If file open\n * fails -> exit *\/\n foutput = fopen(\"out.yuv\", \"wb\");\n if (foutput == NULL)\n {\n printf(\"UNABLE TO OPEN OUTPUT FILE\\n\");\n return -1;\n }\n\n \/* open input file for reading, file name given by user. If file open\n * fails -> exit *\/\n finput = fopen(argv[argc-1], \"rb\");\n if (finput == NULL)\n {\n printf(\"UNABLE TO OPEN INPUT FILE\\n\");\n return -1;\n }\n\n \/* check size of the input file -> length of the stream in bytes *\/\n fseek(finput, 0L, SEEK_END);\n strmLen = (u32)ftell(finput);\n\n rewind(finput);\n \n \/* allocate memory for stream buffer, exit if unsuccessful *\/\n byteStrm = byteStrmStart = (u8 *)H264SwDecMalloc(sizeof(u8)*strmLen);\n if (byteStrm == NULL)\n {\n printf(\"UNABLE TO ALLOCATE MEMORY\\n\");\n return -1;\n }\n\n \/* read input stream from file to buffer and close input file *\/\n fread(byteStrm, sizeof(u8), strmLen, finput);\n fclose(finput);\n\n \/* initialize decoder. If unsuccessful -> exit *\/\n ret = H264SwDecInit(&decInst, 0);\n if (ret != H264SWDEC_OK)\n {\n printf(\"DECODER INITIALIZATION FAILED\\n\");\n return -1;\n }\n\n \/* initialize H264SwDecDecode() input structure *\/\n decInput.pStream = byteStrmStart;\n decInput.dataLen = strmLen;\n decInput.intraConcealmentMethod = 0;\n\n picNumber = 0;\n\n \/* For performance measurements, read the start time (in seconds) here.\n * The decoding time should be measured over several frames and after\n * that average fps (frames\/second) can be calculated.\n *\n * startTime = GetTime();\n *\n * To prevent calculating file I\/O latensies as a decoding time,\n * comment out WriteOutput function call. Also prints to stdout might\n * consume considerable amount of cycles during measurement *\/\n\n \/* main decoding loop *\/\n do\n {\n \/* call API function to perform decoding *\/\n ret = H264SwDecDecode(decInst, &decInput, &decOutput);\n\n switch(ret)\n {\n\n case H264SWDEC_HDRS_RDY_BUFF_NOT_EMPTY:\n\n \/* picture dimensions are available for query now *\/\n ret = H264SwDecGetInfo(decInst, &decInfo);\n if (ret != H264SWDEC_OK)\n return -1;\n\n \/* picture size in pixels *\/\n picSize = decInfo.picWidth * decInfo.picHeight;\n \/* memory needed for YCbCr 4:2:0 picture in bytes *\/\n picSize = (3 * picSize)\/2;\n \/* memory needed for 16-bit RGB picture in bytes\n * picSize = (decInfo.picWidth * decInfo.picHeight) * 2; *\/\n\n printf(\"Width %d Height %d\\n\",\n decInfo.picWidth, decInfo.picHeight);\n\n \/* update H264SwDecDecode() input structure, number of bytes\n * \"consumed\" is computed as difference between the new stream\n * pointer and old stream pointer *\/\n decInput.dataLen -=\n (u32)(decOutput.pStrmCurrPos - decInput.pStream);\n decInput.pStream = decOutput.pStrmCurrPos;\n break;\n\n case H264SWDEC_PIC_RDY_BUFF_NOT_EMPTY:\n case H264SWDEC_PIC_RDY:\n\n \/* update H264SwDecDecode() input structure, number of bytes\n * \"consumed\" is computed as difference between the new stream\n * pointer and old stream pointer *\/\n decInput.dataLen -=\n (u32)(decOutput.pStrmCurrPos - decInput.pStream);\n decInput.pStream = decOutput.pStrmCurrPos;\n\n \/* use function H264SwDecNextPicture() to obtain next picture\n * in display order. Function is called until no more images\n * are ready for display *\/\n while (H264SwDecNextPicture(decInst, &decPicture, 0) ==\n H264SWDEC_PIC_RDY) { picNumber++;\n\n printf(\"PIC %d, type %s, concealed %d\\n\", picNumber,\n decPicture.isIdrPicture ? \"IDR\" : \"NON-IDR\",\n decPicture.nbrOfErrMBs);\n fflush(stdout);\n\n \/* Do color conversion if needed to get display image\n * in RGB-format\n *\n * YuvToRgb( decPicture.pOutputPicture, pRgbPicture ); *\/\n\n \/* write next display image to output file *\/\n WriteOutput(foutput, (u8*)decPicture.pOutputPicture,\n picSize);\n }\n\n break;\n\n case H264SWDEC_EVALUATION_LIMIT_EXCEEDED:\n \/* evaluation version of the decoder has limited decoding\n * capabilities *\/\n printf(\"EVALUATION LIMIT REACHED\\n\");\n goto end;\n\n default:\n printf(\"UNRECOVERABLE ERROR\\n\");\n return -1;\n }\n \/* keep decoding until all data from input stream buffer consumed *\/\n } while (decInput.dataLen > 0);\n\nend:\n\n \/* if output in display order is preferred, the decoder shall be forced\n * to output pictures remaining in decoded picture buffer. Use function\n * H264SwDecNextPicture() to obtain next picture in display order. Function\n * is called until no more images are ready for display. Second parameter\n * for the function is set to '1' to indicate that this is end of the\n * stream and all pictures shall be output *\/\n while (H264SwDecNextPicture(decInst, &decPicture, 1) ==\n H264SWDEC_PIC_RDY) {\n\n picNumber++;\n\n printf(\"PIC %d, type %s, concealed %d\\n\", picNumber,\n decPicture.isIdrPicture ? \"IDR\" : \"NON-IDR\",\n decPicture.nbrOfErrMBs);\n fflush(stdout);\n\n \/* Do color conversion if needed to get display image\n * in RGB-format\n *\n * YuvToRgb( decPicture.pOutputPicture, pRgbPicture ); *\/\n\n \/* write next display image to output file *\/\n WriteOutput(foutput, (u8*)decPicture.pOutputPicture, picSize);\n }\n\n \/* For performance measurements, read the end time (in seconds) here.\n *\n * endTime = GetTime();\n *\n * Now the performance can be calculated as frames per second:\n * fps = picNumber \/ (endTime - startTime); *\/\n\n\n \/* release decoder instance *\/\n H264SwDecRelease(decInst);\n\n \/* close output file *\/\n fclose(foutput);\n\n \/* free byte stream buffer *\/\n free(byteStrmStart);\n\n return 0;\n\n}\n","target":1,"code_token_length":1669,"total_token_length":2000,"max_tokens_setting":2048} +{"idx":274799,"func":"void WebContents::Print(gin_helper::Arguments* args) {\n gin_helper::Dictionary options =\n gin::Dictionary::CreateEmpty(args->isolate());\n base::Value settings(base::Value::Type::DICTIONARY);\n\n if (args->Length() >= 1 && !args->GetNext(&options)) {\n args->ThrowError(\"webContents.print(): Invalid print settings specified.\");\n return;\n }\n\n printing::CompletionCallback callback;\n if (args->Length() == 2 && !args->GetNext(&callback)) {\n args->ThrowError(\n \"webContents.print(): Invalid optional callback provided.\");\n return;\n }\n\n \/\/ Set optional silent printing\n bool silent = false;\n options.Get(\"silent\", &silent);\n\n bool print_background = false;\n options.Get(\"printBackground\", &print_background);\n settings.SetBoolKey(printing::kSettingShouldPrintBackgrounds,\n print_background);\n\n \/\/ Set custom margin settings\n gin_helper::Dictionary margins =\n gin::Dictionary::CreateEmpty(args->isolate());\n if (options.Get(\"margins\", &margins)) {\n printing::MarginType margin_type = printing::DEFAULT_MARGINS;\n margins.Get(\"marginType\", &margin_type);\n settings.SetIntKey(printing::kSettingMarginsType, margin_type);\n\n if (margin_type == printing::CUSTOM_MARGINS) {\n base::Value custom_margins(base::Value::Type::DICTIONARY);\n int top = 0;\n margins.Get(\"top\", &top);\n custom_margins.SetIntKey(printing::kSettingMarginTop, top);\n int bottom = 0;\n margins.Get(\"bottom\", &bottom);\n custom_margins.SetIntKey(printing::kSettingMarginBottom, bottom);\n int left = 0;\n margins.Get(\"left\", &left);\n custom_margins.SetIntKey(printing::kSettingMarginLeft, left);\n int right = 0;\n margins.Get(\"right\", &right);\n custom_margins.SetIntKey(printing::kSettingMarginRight, right);\n settings.SetPath(printing::kSettingMarginsCustom,\n std::move(custom_margins));\n }\n } else {\n settings.SetIntKey(printing::kSettingMarginsType,\n printing::DEFAULT_MARGINS);\n }\n\n \/\/ Set whether to print color or greyscale\n bool print_color = true;\n options.Get(\"color\", &print_color);\n int color_setting = print_color ? printing::COLOR : printing::GRAY;\n settings.SetIntKey(printing::kSettingColor, color_setting);\n\n \/\/ Is the orientation landscape or portrait.\n bool landscape = false;\n options.Get(\"landscape\", &landscape);\n settings.SetBoolKey(printing::kSettingLandscape, landscape);\n\n \/\/ We set the default to the system's default printer and only update\n \/\/ if at the Chromium level if the user overrides.\n \/\/ Printer device name as opened by the OS.\n base::string16 device_name;\n options.Get(\"deviceName\", &device_name);\n if (!device_name.empty() && !IsDeviceNameValid(device_name)) {\n args->ThrowError(\"webContents.print(): Invalid deviceName provided.\");\n return;\n }\n\n int scale_factor = 100;\n options.Get(\"scaleFactor\", &scale_factor);\n settings.SetIntKey(printing::kSettingScaleFactor, scale_factor);\n\n int pages_per_sheet = 1;\n options.Get(\"pagesPerSheet\", &pages_per_sheet);\n settings.SetIntKey(printing::kSettingPagesPerSheet, pages_per_sheet);\n\n \/\/ True if the user wants to print with collate.\n bool collate = true;\n options.Get(\"collate\", &collate);\n settings.SetBoolKey(printing::kSettingCollate, collate);\n\n \/\/ The number of individual copies to print\n int copies = 1;\n options.Get(\"copies\", &copies);\n settings.SetIntKey(printing::kSettingCopies, copies);\n\n \/\/ Strings to be printed as headers and footers if requested by the user.\n std::string header;\n options.Get(\"header\", &header);\n std::string footer;\n options.Get(\"footer\", &footer);\n\n if (!(header.empty() && footer.empty())) {\n settings.SetBoolKey(printing::kSettingHeaderFooterEnabled, true);\n\n settings.SetStringKey(printing::kSettingHeaderFooterTitle, header);\n settings.SetStringKey(printing::kSettingHeaderFooterURL, footer);\n } else {\n settings.SetBoolKey(printing::kSettingHeaderFooterEnabled, false);\n }\n\n \/\/ We don't want to allow the user to enable these settings\n \/\/ but we need to set them or a CHECK is hit.\n settings.SetIntKey(printing::kSettingPrinterType,\n static_cast(printing::PrinterType::kLocal));\n settings.SetBoolKey(printing::kSettingShouldPrintSelectionOnly, false);\n settings.SetBoolKey(printing::kSettingRasterizePdf, false);\n\n \/\/ Set custom page ranges to print\n std::vector page_ranges;\n if (options.Get(\"pageRanges\", &page_ranges)) {\n base::Value page_range_list(base::Value::Type::LIST);\n for (auto& range : page_ranges) {\n int from, to;\n if (range.Get(\"from\", &from) && range.Get(\"to\", &to)) {\n base::Value range(base::Value::Type::DICTIONARY);\n range.SetIntKey(printing::kSettingPageRangeFrom, from);\n range.SetIntKey(printing::kSettingPageRangeTo, to);\n page_range_list.Append(std::move(range));\n } else {\n continue;\n }\n }\n if (page_range_list.GetList().size() > 0)\n settings.SetPath(printing::kSettingPageRange, std::move(page_range_list));\n }\n\n \/\/ Duplex type user wants to use.\n printing::mojom::DuplexMode duplex_mode =\n printing::mojom::DuplexMode::kSimplex;\n options.Get(\"duplexMode\", &duplex_mode);\n settings.SetIntKey(printing::kSettingDuplexMode,\n static_cast(duplex_mode));\n\n \/\/ We've already done necessary parameter sanitization at the\n \/\/ JS level, so we can simply pass this through.\n base::Value media_size(base::Value::Type::DICTIONARY);\n if (options.Get(\"mediaSize\", &media_size))\n settings.SetKey(printing::kSettingMediaSize, std::move(media_size));\n\n \/\/ Set custom dots per inch (dpi)\n gin_helper::Dictionary dpi_settings;\n int dpi = 72;\n if (options.Get(\"dpi\", &dpi_settings)) {\n int horizontal = 72;\n dpi_settings.Get(\"horizontal\", &horizontal);\n settings.SetIntKey(printing::kSettingDpiHorizontal, horizontal);\n int vertical = 72;\n dpi_settings.Get(\"vertical\", &vertical);\n settings.SetIntKey(printing::kSettingDpiVertical, vertical);\n } else {\n settings.SetIntKey(printing::kSettingDpiHorizontal, dpi);\n settings.SetIntKey(printing::kSettingDpiVertical, dpi);\n }\n\n base::ThreadPool::PostTaskAndReplyWithResult(\n FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING},\n base::BindOnce(&GetDefaultPrinterAsync),\n base::BindOnce(&WebContents::OnGetDefaultPrinter,\n weak_factory_.GetWeakPtr(), std::move(settings),\n std::move(callback), device_name, silent));\n}","target":0,"code_token_length":1601,"total_token_length":1932,"max_tokens_setting":2048} +{"idx":237457,"func":"gs_main_finit(gs_main_instance * minst, int exit_status, int code)\n{\n i_ctx_t *i_ctx_p = minst->i_ctx_p;\n gs_dual_memory_t dmem = {0};\n int exit_code;\n ref error_object;\n char *tempnames;\n\n \/* NB: need to free gs_name_table\n *\/\n\n \/*\n * Previous versions of this code closed the devices in the\n * device list here. Since these devices are now prototypes,\n * they cannot be opened, so they do not need to be closed;\n * alloc_restore_all will close dynamically allocated devices.\n *\/\n tempnames = gs_main_tempnames(minst);\n\n \/* by the time we get here, we *must* avoid any random redefinitions of\n * operators etc, so we push systemdict onto the top of the dict stack.\n * We do this in C to avoid running into any other re-defininitions in the\n * Postscript world.\n *\/\n gs_finit_push_systemdict(i_ctx_p);\n\n \/* We have to disable BGPrint before we call interp_reclaim() to prevent the\n * parent rendering thread initialising for the next page, whilst we are\n * removing objects it may want to access - for example, the I\/O device table.\n * We also have to mess with the BeginPage\/EndPage procs so that we don't\n * trigger a spurious extra page to be emitted.\n *\/\n if (minst->init_done >= 2) {\n gs_main_run_string(minst,\n \"\/BGPrint \/GetDeviceParam .special_op \\\n {{ <<\/BeginPage {pop} \/EndPage {pop pop \/\/false } \\\n \/BGPrint false \/NumRenderingThreads 0>> setpagedevice} if} if \\\n serverdict \/.jobsavelevel get 0 eq {\/quit} {\/stop} ifelse \\\n .systemvar exec\",\n 0 , &exit_code, &error_object);\n }\n\n \/*\n * Close the \"main\" device, because it may need to write out\n * data before destruction. pdfwrite needs so.\n *\/\n if (minst->init_done >= 2) {\n int code = 0;\n\n if (idmemory->reclaim != 0) {\n code = interp_reclaim(&minst->i_ctx_p, avm_global);\n\n if (code < 0) {\n ref error_name;\n if (tempnames)\n free(tempnames);\n\n if (gs_errorname(i_ctx_p, code, &error_name) >= 0) {\n char err_str[32] = {0};\n name_string_ref(imemory, &error_name, &error_name);\n memcpy(err_str, error_name.value.const_bytes, r_size(&error_name));\n emprintf2(imemory, \"ERROR: %s (%d) reclaiming the memory while the interpreter finalization.\\n\", err_str, code);\n }\n else {\n emprintf1(imemory, \"UNKNOWN ERROR %d reclaiming the memory while the interpreter finalization.\\n\", code);\n }\n#ifdef MEMENTO_SQUEEZE_BUILD\n if (code != gs_error_VMerror ) return gs_error_Fatal;\n#else\n return gs_error_Fatal;\n#endif\n }\n i_ctx_p = minst->i_ctx_p; \/* interp_reclaim could change it. *\/\n }\n \n if (i_ctx_p->pgs != NULL && i_ctx_p->pgs->device != NULL &&\n gx_device_is_null(i_ctx_p->pgs->device)) {\n \/* if the job replaced the device with the nulldevice, we we need to grestore\n away that device, so the block below can properly dispense\n with the default device.\n *\/\n int code = gs_grestoreall(i_ctx_p->pgs);\n if (code < 0) return_error(gs_error_Fatal);\n }\n\n if (i_ctx_p->pgs != NULL && i_ctx_p->pgs->device != NULL) {\n gx_device *pdev = i_ctx_p->pgs->device;\n const char * dname = pdev->dname;\n if (code < 0) {\n ref error_name;\n if (gs_errorname(i_ctx_p, code, &error_name) >= 0) {\n char err_str[32] = {0};\n name_string_ref(imemory, &error_name, &error_name);\n memcpy(err_str, error_name.value.const_bytes, r_size(&error_name));\n emprintf3(imemory, \"ERROR: %s (%d) on closing %s device.\\n\", err_str, code, dname);\n }\n else {\n emprintf2(imemory, \"UNKNOWN ERROR %d closing %s device.\\n\", code, dname);\n }\n }\n rc_decrement(pdev, \"gs_main_finit\"); \/* device might be freed *\/\n if (exit_status == 0 || exit_status == gs_error_Quit)\n exit_status = code;\n }\n\n \/* Flush stdout and stderr *\/\n gs_main_run_string(minst,\n \"(%stdout) (w) file closefile (%stderr) (w) file closefile \\\n serverdict \/.jobsavelevel get 0 eq {\/quit} {\/stop} ifelse .systemexec \\\n systemdict \/savedinitialgstate .forceundef\",\n 0 , &exit_code, &error_object);\n }\n gp_readline_finit(minst->readline_data);\n i_ctx_p = minst->i_ctx_p;\t\t\/* get current interp context *\/\n if (gs_debug_c(':')) {\n print_resource_usage(minst, &gs_imemory, \"Final\");\n dmprintf1(minst->heap, \"%% Exiting instance 0x%p\\n\", minst);\n }\n \/* Do the equivalent of a restore \"past the bottom\". *\/\n \/* This will release all memory, close all open files, etc. *\/\n if (minst->init_done >= 1) {\n gs_memory_t *mem_raw = i_ctx_p->memory.current->non_gc_memory;\n i_plugin_holder *h = i_ctx_p->plugin_list;\n\n dmem = *idmemory;\n code = alloc_restore_all(i_ctx_p);\n if (code < 0)\n emprintf1(mem_raw,\n \"ERROR %d while the final restore. See gs\/psi\/ierrors.h for code explanation.\\n\",\n code);\n i_iodev_finit(&dmem);\n i_plugin_finit(mem_raw, h);\n }\n\n \/* clean up redirected stdout *\/\n if (minst->heap->gs_lib_ctx->fstdout2\n && (minst->heap->gs_lib_ctx->fstdout2 != minst->heap->gs_lib_ctx->fstdout)\n && (minst->heap->gs_lib_ctx->fstdout2 != minst->heap->gs_lib_ctx->fstderr)) {\n fclose(minst->heap->gs_lib_ctx->fstdout2);\n minst->heap->gs_lib_ctx->fstdout2 = (FILE *)NULL;\n }\n\n minst->heap->gs_lib_ctx->stdout_is_redirected = 0;\n minst->heap->gs_lib_ctx->stdout_to_stderr = 0;\n \/* remove any temporary files, after ghostscript has closed files *\/\n if (tempnames) {\n char *p = tempnames;\n while (*p) {\n unlink(p);\n p += strlen(p) + 1;\n }\n free(tempnames);\n }\n gs_lib_finit(exit_status, code, minst->heap);\n\n gs_free_object(minst->heap, minst->lib_path.container.value.refs, \"lib_path array\");\n ialloc_finit(&dmem);\n return exit_status;\n}\n","target":0,"code_token_length":1667,"total_token_length":1998,"max_tokens_setting":2048} +{"idx":206289,"func":"String DOMWindow::CrossDomainAccessErrorMessage(\n const LocalDOMWindow* calling_window) const {\n if (!calling_window || !calling_window->document() || !GetFrame())\n return String();\n\n const KURL& calling_window_url = calling_window->document()->Url();\n if (calling_window_url.IsNull())\n return String();\n\n const SecurityOrigin* active_origin =\n calling_window->document()->GetSecurityOrigin();\n const SecurityOrigin* target_origin =\n GetFrame()->GetSecurityContext()->GetSecurityOrigin();\n DCHECK(GetFrame()->IsRemoteFrame() ||\n !active_origin->CanAccess(target_origin));\n\n String message = \"Blocked a frame with origin \\\"\" +\n active_origin->ToString() +\n \"\\\" from accessing a frame with origin \\\"\" +\n target_origin->ToString() + \"\\\". \";\n\n KURL active_url = calling_window->document()->Url();\n KURL target_url = IsLocalDOMWindow()\n ? blink::ToLocalDOMWindow(this)->document()->Url()\n : KURL(NullURL(), target_origin->ToString());\n if (GetFrame()->GetSecurityContext()->IsSandboxed(kSandboxOrigin) ||\n calling_window->document()->IsSandboxed(kSandboxOrigin)) {\n message = \"Blocked a frame at \\\"\" +\n SecurityOrigin::Create(active_url)->ToString() +\n \"\\\" from accessing a frame at \\\"\" +\n SecurityOrigin::Create(target_url)->ToString() + \"\\\". \";\n if (GetFrame()->GetSecurityContext()->IsSandboxed(kSandboxOrigin) &&\n calling_window->document()->IsSandboxed(kSandboxOrigin))\n return \"Sandbox access violation: \" + message +\n \" Both frames are sandboxed and lack the \\\"allow-same-origin\\\" \"\n \"flag.\";\n if (GetFrame()->GetSecurityContext()->IsSandboxed(kSandboxOrigin))\n return \"Sandbox access violation: \" + message +\n \" The frame being accessed is sandboxed and lacks the \"\n \"\\\"allow-same-origin\\\" flag.\";\n return \"Sandbox access violation: \" + message +\n \" The frame requesting access is sandboxed and lacks the \"\n \"\\\"allow-same-origin\\\" flag.\";\n }\n\n if (target_origin->Protocol() != active_origin->Protocol())\n return message + \" The frame requesting access has a protocol of \\\"\" +\n active_url.Protocol() +\n \"\\\", the frame being accessed has a protocol of \\\"\" +\n target_url.Protocol() + \"\\\". Protocols must match.\\n\";\n\n if (target_origin->DomainWasSetInDOM() && active_origin->DomainWasSetInDOM())\n return message +\n \"The frame requesting access set \\\"document.domain\\\" to \\\"\" +\n active_origin->Domain() +\n \"\\\", the frame being accessed set it to \\\"\" +\n target_origin->Domain() +\n \"\\\". Both must set \\\"document.domain\\\" to the same value to allow \"\n \"access.\";\n if (active_origin->DomainWasSetInDOM())\n return message +\n \"The frame requesting access set \\\"document.domain\\\" to \\\"\" +\n active_origin->Domain() +\n \"\\\", but the frame being accessed did not. Both must set \"\n \"\\\"document.domain\\\" to the same value to allow access.\";\n if (target_origin->DomainWasSetInDOM())\n return message + \"The frame being accessed set \\\"document.domain\\\" to \\\"\" +\n target_origin->Domain() +\n \"\\\", but the frame requesting access did not. Both must set \"\n \"\\\"document.domain\\\" to the same value to allow access.\";\n\n return message + \"Protocols, domains, and ports must match.\";\n}\n","target":0,"code_token_length":745,"total_token_length":1076,"max_tokens_setting":2048} +{"idx":324094,"func":"static void decode_clnpass(Jpeg2000DecoderContext *s, Jpeg2000T1Context *t1,\n\n int width, int height, int bpno, int bandno,\n\n int seg_symbols, int vert_causal_ctx_csty_symbol)\n\n{\n\n int mask = 3 << (bpno - 1), y0, x, y, runlen, dec;\n\n\n\n for (y0 = 0; y0 < height; y0 += 4) {\n\n for (x = 0; x < width; x++) {\n\n int flags_mask = -1;\n\n if (vert_causal_ctx_csty_symbol)\n\n flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S);\n\n if (y0 + 3 < height &&\n\n !((t1->flags[y0 + 1][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||\n\n (t1->flags[y0 + 2][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||\n\n (t1->flags[y0 + 3][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG)) ||\n\n (t1->flags[y0 + 4][x + 1] & (JPEG2000_T1_SIG_NB | JPEG2000_T1_VIS | JPEG2000_T1_SIG) & flags_mask))) {\n\n if (!ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_RL))\n\n continue;\n\n runlen = ff_mqc_decode(&t1->mqc,\n\n t1->mqc.cx_states + MQC_CX_UNI);\n\n runlen = (runlen << 1) | ff_mqc_decode(&t1->mqc,\n\n t1->mqc.cx_states +\n\n MQC_CX_UNI);\n\n dec = 1;\n\n } else {\n\n runlen = 0;\n\n dec = 0;\n\n }\n\n\n\n for (y = y0 + runlen; y < y0 + 4 && y < height; y++) {\n\n int flags_mask = -1;\n\n if (vert_causal_ctx_csty_symbol && y == y0 + 3)\n\n flags_mask &= ~(JPEG2000_T1_SIG_S | JPEG2000_T1_SIG_SW | JPEG2000_T1_SIG_SE | JPEG2000_T1_SGN_S);\n\n if (!dec) {\n\n if (!(t1->flags[y+1][x+1] & (JPEG2000_T1_SIG | JPEG2000_T1_VIS))) {\n\n dec = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + ff_jpeg2000_getsigctxno(t1->flags[y+1][x+1] & flags_mask,\n\n bandno));\n\n }\n\n }\n\n if (dec) {\n\n int xorbit;\n\n int ctxno = ff_jpeg2000_getsgnctxno(t1->flags[y + 1][x + 1] & flags_mask,\n\n &xorbit);\n\n t1->data[y][x] = (ff_mqc_decode(&t1->mqc,\n\n t1->mqc.cx_states + ctxno) ^\n\n xorbit)\n\n ? -mask : mask;\n\n ff_jpeg2000_set_significance(t1, x, y, t1->data[y][x] < 0);\n\n }\n\n dec = 0;\n\n t1->flags[y + 1][x + 1] &= ~JPEG2000_T1_VIS;\n\n }\n\n }\n\n }\n\n if (seg_symbols) {\n\n int val;\n\n val = ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);\n\n val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);\n\n val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);\n\n val = (val << 1) + ff_mqc_decode(&t1->mqc, t1->mqc.cx_states + MQC_CX_UNI);\n\n if (val != 0xa)\n\n av_log(s->avctx, AV_LOG_ERROR,\n\n \"Segmentation symbol value incorrect\\n\");\n\n }\n\n}\n","target":0,"code_token_length":1077,"total_token_length":1408,"max_tokens_setting":2048} +{"idx":489902,"func":"static int asepcos_build_pin_apdu(sc_card_t *card, sc_apdu_t *apdu,\n\tstruct sc_pin_cmd_data *data, u8 *buf, size_t buf_len,\n\tunsigned int cmd, int is_puk)\n{\n\tint r, fileid;\n\tu8 *p = buf;\n\tsc_cardctl_asepcos_akn2fileid_t st;\n\n\tswitch (cmd) {\n\tcase SC_PIN_CMD_VERIFY:\n\t\tst.akn = data->pin_reference;\n\t\tr = asepcos_akn_to_fileid(card, &st);\n\t\tif (r != SC_SUCCESS)\n\t\t\treturn r;\n\t\tfileid = st.fileid;\n\t\t\/* the fileid of the puk is the fileid of the pin + 1 *\/\n\t\tif (is_puk != 0)\n\t\t\tfileid++;\n\t\tsc_format_apdu(card, apdu, SC_APDU_CASE_3_SHORT, 0x20, 0x02, 0x80);\n\t\t*p++ = (fileid >> 24) & 0xff;\n\t\t*p++ = (fileid >> 16) & 0xff;\n\t\t*p++ = (fileid >> 8 ) & 0xff;\n\t\t*p++ = fileid & 0xff;\n\t\tmemcpy(p, data->pin1.data, data->pin1.len);\n\t\tp += data->pin1.len;\n\t\tapdu->lc = p - buf;\n\t\tapdu->datalen = p - buf;\n\t\tapdu->data = buf;\n\t\tbreak;\n\tcase SC_PIN_CMD_CHANGE:\n\t\t\/* build the CHANGE KEY apdu. Note: the PIN file is implicitly\n\t\t * selected by its SFID *\/\n\t\t*p++ = 0x81;\n\t\t*p++ = data->pin2.len & 0xff;\n\t\tmemcpy(p, data->pin2.data, data->pin2.len);\n\t\tp += data->pin2.len;\n\t\tst.akn = data->pin_reference;\n\t\tr = asepcos_akn_to_fileid(card, &st);\n\t\tif (r != SC_SUCCESS)\n\t\t\treturn r;\n\t\tfileid = 0x80 | (st.fileid & 0x1f);\n\t\tsc_format_apdu(card, apdu, SC_APDU_CASE_3_SHORT, 0x24, 0x01, fileid);\n\t\tapdu->lc = p - buf;\n\t\tapdu->datalen = p - buf;\n\t\tapdu->data = buf;\n\t\tbreak;\n\tcase SC_PIN_CMD_UNBLOCK:\n\t\t\/* build the UNBLOCK KEY apdu. The PIN file is implicitly \n\t\t * selected by its SFID. The new PIN is provided in the\n\t\t * data field of the UNBLOCK KEY command. *\/\n\t\t*p++ = 0x81;\n\t\t*p++ = data->pin2.len & 0xff;\n\t\tmemcpy(p, data->pin2.data, data->pin2.len);\n\t\tp += data->pin2.len;\n\t\tst.akn = data->pin_reference;\n\t\tr = asepcos_akn_to_fileid(card, &st);\n\t\tif (r != SC_SUCCESS)\n\t\t\treturn r;\n\t\tfileid = 0x80 | (st.fileid & 0x1f);\n\t\tsc_format_apdu(card, apdu, SC_APDU_CASE_3_SHORT, 0x2C, 0x02, fileid);\n\t\tapdu->lc = p - buf;\n\t\tapdu->datalen = p - buf;\n\t\tapdu->data = buf;\n\t\tbreak;\n\tdefault:\n\t\treturn SC_ERROR_NOT_SUPPORTED;\n\t}\n\treturn SC_SUCCESS;\n}","target":0,"code_token_length":796,"total_token_length":1127,"max_tokens_setting":2048} +{"idx":137848,"func":"hybiReadHeader(ws_ctx_t *wsctx, int *sockRet, int *nPayload)\n{\n int ret;\n char *headerDst = wsctx->codeBufDecode + wsctx->header.nRead;\n int n = ((uint64_t)WSHLENMAX) - wsctx->header.nRead;\n\n\n ws_dbg(\"header_read to %p with len=%d\\n\", headerDst, n);\n ret = wsctx->ctxInfo.readFunc(wsctx->ctxInfo.ctxPtr, headerDst, n);\n ws_dbg(\"read %d bytes from socket\\n\", ret);\n if (ret <= 0) {\n if (-1 == ret) {\n \/* save errno because rfbErr() will tamper it *\/\n int olderrno = errno;\n rfbErr(\"%s: read; %s\\n\", __func__, strerror(errno));\n errno = olderrno;\n goto err_cleanup_state;\n } else {\n *sockRet = 0;\n goto err_cleanup_state_sock_closed;\n }\n }\n\n wsctx->header.nRead += ret;\n if (wsctx->header.nRead < 2) {\n \/* cannot decode header with less than two bytes *\/\n goto ret_header_pending;\n }\n\n \/* first two header bytes received; interpret header data and get rest *\/\n wsctx->header.data = (ws_header_t *)wsctx->codeBufDecode;\n\n wsctx->header.opcode = wsctx->header.data->b0 & 0x0f;\n wsctx->header.fin = (wsctx->header.data->b0 & 0x80) >> 7;\n if (isControlFrame(wsctx)) {\n ws_dbg(\"is control frame\\n\");\n \/* is a control frame, leave remembered continuation opcode unchanged;\n * just check if there is a wrong fragmentation *\/\n if (wsctx->header.fin == 0) {\n\n \/* we only accept text\/binary continuation frames; RFC6455:\n * Control frames (see Section 5.5) MAY be injected in the middle of\n * a fragmented message. Control frames themselves MUST NOT be\n * fragmented. *\/\n rfbErr(\"control frame with FIN bit cleared received, aborting\\n\");\n errno = EPROTO;\n goto err_cleanup_state;\n }\n } else {\n ws_dbg(\"not a control frame\\n\");\n \/* not a control frame, check for continuation opcode *\/\n if (wsctx->header.opcode == WS_OPCODE_CONTINUATION) {\n ws_dbg(\"cont_frame\\n\");\n \/* do we have state (i.e., opcode) for continuation frame? *\/\n if (wsctx->continuation_opcode == WS_OPCODE_INVALID) {\n rfbErr(\"no continuation state\\n\");\n errno = EPROTO;\n goto err_cleanup_state;\n }\n\n \/* otherwise, set opcode = continuation_opcode *\/\n wsctx->header.opcode = wsctx->continuation_opcode;\n ws_dbg(\"set opcode to continuation_opcode: %d\\n\", wsctx->header.opcode);\n } else {\n if (wsctx->header.fin == 0) {\n wsctx->continuation_opcode = wsctx->header.opcode;\n } else {\n wsctx->continuation_opcode = WS_OPCODE_INVALID;\n }\n ws_dbg(\"set continuation_opcode to %d\\n\", wsctx->continuation_opcode);\n }\n }\n\n wsctx->header.payloadLen = (uint64_t)(wsctx->header.data->b1 & 0x7f);\n ws_dbg(\"first header bytes received; opcode=%d lenbyte=%d fin=%d\\n\", wsctx->header.opcode, wsctx->header.payloadLen, wsctx->header.fin);\n\n \/*\n * 4.3. Client-to-Server Masking\n *\n * The client MUST mask all frames sent to the server. A server MUST\n * close the connection upon receiving a frame with the MASK bit set to 0.\n **\/\n if (!(wsctx->header.data->b1 & 0x80)) {\n rfbErr(\"%s: got frame without mask; ret=%d\\n\", __func__, ret);\n errno = EPROTO;\n goto err_cleanup_state;\n }\n\n\n if (wsctx->header.payloadLen < 126 && wsctx->header.nRead >= 6) {\n wsctx->header.headerLen = WS_HYBI_HEADER_LEN_SHORT;\n wsctx->header.mask = wsctx->header.data->u.m;\n } else if (wsctx->header.payloadLen == 126 && 8 <= wsctx->header.nRead) {\n wsctx->header.headerLen = WS_HYBI_HEADER_LEN_EXTENDED;\n wsctx->header.payloadLen = WS_NTOH16(wsctx->header.data->u.s16.l16);\n wsctx->header.mask = wsctx->header.data->u.s16.m16;\n } else if (wsctx->header.payloadLen == 127 && 14 <= wsctx->header.nRead) {\n wsctx->header.headerLen = WS_HYBI_HEADER_LEN_LONG;\n wsctx->header.payloadLen = WS_NTOH64(wsctx->header.data->u.s64.l64);\n wsctx->header.mask = wsctx->header.data->u.s64.m64;\n } else {\n \/* Incomplete frame header, try again *\/\n rfbErr(\"%s: incomplete frame header; ret=%d\\n\", __func__, ret);\n goto ret_header_pending;\n }\n\n char *h = wsctx->codeBufDecode;\n int i;\n ws_dbg(\"Header:\\n\");\n for (i=0; i <10; i++) {\n ws_dbg(\"0x%02X\\n\", (unsigned char)h[i]);\n }\n ws_dbg(\"\\n\");\n\n \/* while RFC 6455 mandates that lengths MUST be encoded with the minimum\n * number of bytes, it does not specify for the server how to react on\n * 'wrongly' encoded frames --- this implementation rejects them*\/\n if ((wsctx->header.headerLen > WS_HYBI_HEADER_LEN_SHORT\n && wsctx->header.payloadLen < (uint64_t)126)\n || (wsctx->header.headerLen > WS_HYBI_HEADER_LEN_EXTENDED\n && wsctx->header.payloadLen < (uint64_t)65536)) {\n rfbErr(\"%s: invalid length field; headerLen=%d payloadLen=%llu\\n\", __func__, wsctx->header.headerLen, wsctx->header.payloadLen);\n errno = EPROTO;\n goto err_cleanup_state;\n }\n\n \/* update write position for next bytes *\/\n wsctx->writePos = wsctx->codeBufDecode + wsctx->header.nRead;\n\n \/* set payload pointer just after header *\/\n wsctx->readPos = (unsigned char *)(wsctx->codeBufDecode + wsctx->header.headerLen);\n\n *nPayload = wsctx->header.nRead - wsctx->header.headerLen;\n wsctx->nReadPayload = *nPayload;\n\n ws_dbg(\"header complete: state=%d headerlen=%d payloadlen=%llu writeTo=%p nPayload=%d\\n\", wsctx->hybiDecodeState, wsctx->header.headerLen, wsctx->header.payloadLen, wsctx->writePos, *nPayload);\n\n return WS_HYBI_STATE_DATA_NEEDED;\n\nret_header_pending:\n errno = EAGAIN;\n *sockRet = -1;\n return WS_HYBI_STATE_HEADER_PENDING;\n\nerr_cleanup_state:\n *sockRet = -1;\nerr_cleanup_state_sock_closed:\n hybiDecodeCleanupComplete(wsctx);\n return WS_HYBI_STATE_ERR;\n}","target":0,"code_token_length":1661,"total_token_length":1992,"max_tokens_setting":2048} +{"idx":109570,"func":"static int create_uaxx_quirk(struct snd_usb_audio *chip,\n\t\t\t struct usb_interface *iface,\n\t\t\t struct usb_driver *driver,\n\t\t\t const struct snd_usb_audio_quirk *quirk)\n{\n\tstatic const struct audioformat ua_format = {\n\t\t.formats = SNDRV_PCM_FMTBIT_S24_3LE,\n\t\t.channels = 2,\n\t\t.fmt_type = UAC_FORMAT_TYPE_I,\n\t\t.altsetting = 1,\n\t\t.altset_idx = 1,\n\t\t.rates = SNDRV_PCM_RATE_CONTINUOUS,\n\t};\n\tstruct usb_host_interface *alts;\n\tstruct usb_interface_descriptor *altsd;\n\tstruct audioformat *fp;\n\tint stream, err;\n\n\t\/* both PCM and MIDI interfaces have 2 or more altsettings *\/\n\tif (iface->num_altsetting < 2)\n\t\treturn -ENXIO;\n\talts = &iface->altsetting[1];\n\taltsd = get_iface_desc(alts);\n\n\tif (altsd->bNumEndpoints == 2) {\n\t\tstatic const struct snd_usb_midi_endpoint_info ua700_ep = {\n\t\t\t.out_cables = 0x0003,\n\t\t\t.in_cables = 0x0003\n\t\t};\n\t\tstatic const struct snd_usb_audio_quirk ua700_quirk = {\n\t\t\t.type = QUIRK_MIDI_FIXED_ENDPOINT,\n\t\t\t.data = &ua700_ep\n\t\t};\n\t\tstatic const struct snd_usb_midi_endpoint_info uaxx_ep = {\n\t\t\t.out_cables = 0x0001,\n\t\t\t.in_cables = 0x0001\n\t\t};\n\t\tstatic const struct snd_usb_audio_quirk uaxx_quirk = {\n\t\t\t.type = QUIRK_MIDI_FIXED_ENDPOINT,\n\t\t\t.data = &uaxx_ep\n\t\t};\n\t\tconst struct snd_usb_audio_quirk *quirk =\n\t\t\tchip->usb_id == USB_ID(0x0582, 0x002b)\n\t\t\t? &ua700_quirk : &uaxx_quirk;\n\t\treturn __snd_usbmidi_create(chip->card, iface,\n\t\t\t\t\t &chip->midi_list, quirk,\n\t\t\t\t\t chip->usb_id);\n\t}\n\n\tif (altsd->bNumEndpoints != 1)\n\t\treturn -ENXIO;\n\n\tfp = kmemdup(&ua_format, sizeof(*fp), GFP_KERNEL);\n\tif (!fp)\n\t\treturn -ENOMEM;\n\n\tfp->iface = altsd->bInterfaceNumber;\n\tfp->endpoint = get_endpoint(alts, 0)->bEndpointAddress;\n\tfp->ep_attr = get_endpoint(alts, 0)->bmAttributes;\n\tfp->datainterval = 0;\n\tfp->maxpacksize = le16_to_cpu(get_endpoint(alts, 0)->wMaxPacketSize);\n\n\tswitch (fp->maxpacksize) {\n\tcase 0x120:\n\t\tfp->rate_max = fp->rate_min = 44100;\n\t\tbreak;\n\tcase 0x138:\n\tcase 0x140:\n\t\tfp->rate_max = fp->rate_min = 48000;\n\t\tbreak;\n\tcase 0x258:\n\tcase 0x260:\n\t\tfp->rate_max = fp->rate_min = 96000;\n\t\tbreak;\n\tdefault:\n\t\tusb_audio_err(chip, \"unknown sample rate\\n\");\n\t\tkfree(fp);\n\t\treturn -ENXIO;\n\t}\n\n\tstream = (fp->endpoint & USB_DIR_IN)\n\t\t? SNDRV_PCM_STREAM_CAPTURE : SNDRV_PCM_STREAM_PLAYBACK;\n\terr = snd_usb_add_audio_stream(chip, stream, fp);\n\tif (err < 0) {\n\t\tkfree(fp);\n\t\treturn err;\n\t}\n\tusb_set_interface(chip->dev, fp->iface, 0);\n\treturn 0;\n}","target":0,"code_token_length":821,"total_token_length":1152,"max_tokens_setting":2048} +{"idx":44311,"func":"static void unpack_14(const uint8_t b[14], uint16_t s[16])\n{\n unsigned short shift = (b[ 2] >> 2) & 15;\n unsigned short bias = (0x20 << shift);\n int i;\n\n s[ 0] = (b[0] << 8) | b[1];\n\n s[ 4] = s[ 0] + ((((b[ 2] << 4) | (b[ 3] >> 4)) & 0x3f) << shift) - bias;\n s[ 8] = s[ 4] + ((((b[ 3] << 2) | (b[ 4] >> 6)) & 0x3f) << shift) - bias;\n s[12] = s[ 8] + ((b[ 4] & 0x3f) << shift) - bias;\n\n s[ 1] = s[ 0] + ((b[ 5] >> 2) << shift) - bias;\n s[ 5] = s[ 4] + ((((b[ 5] << 4) | (b[ 6] >> 4)) & 0x3f) << shift) - bias;\n s[ 9] = s[ 8] + ((((b[ 6] << 2) | (b[ 7] >> 6)) & 0x3f) << shift) - bias;\n s[13] = s[12] + ((b[ 7] & 0x3f) << shift) - bias;\n\n s[ 2] = s[ 1] + ((b[ 8] >> 2) << shift) - bias;\n s[ 6] = s[ 5] + ((((b[ 8] << 4) | (b[ 9] >> 4)) & 0x3f) << shift) - bias;\n s[10] = s[ 9] + ((((b[ 9] << 2) | (b[10] >> 6)) & 0x3f) << shift) - bias;\n s[14] = s[13] + ((b[10] & 0x3f) << shift) - bias;\n\n s[ 3] = s[ 2] + ((b[11] >> 2) << shift) - bias;\n s[ 7] = s[ 6] + ((((b[11] << 4) | (b[12] >> 4)) & 0x3f) << shift) - bias;\n s[11] = s[10] + ((((b[12] << 2) | (b[13] >> 6)) & 0x3f) << shift) - bias;\n s[15] = s[14] + ((b[13] & 0x3f) << shift) - bias;\n\n for (i = 0; i < 16; ++i) {\n if (s[i] & 0x8000)\n s[i] &= 0x7fff;\n else\n s[i] = ~s[i];\n }\n}","target":0,"code_token_length":748,"total_token_length":1079,"max_tokens_setting":2048} +{"idx":92507,"func":"njs_generate_try_left(njs_vm_t *vm, njs_generator_t *generator,\n njs_parser_node_t *node)\n{\n njs_int_t ret;\n njs_index_t exit_index, catch_index;\n njs_jump_off_t try_end_offset;\n njs_variable_t *var;\n njs_vmcode_catch_t *catch;\n njs_vmcode_try_end_t *try_end;\n njs_generator_block_t *try_block;\n njs_generator_try_ctx_t *ctx;\n njs_vmcode_try_trampoline_t *try_break, *try_continue;\n\n ctx = generator->context;\n\n try_block = ctx->try_block;\n exit_index = try_block->index;\n\n njs_generate_code(generator, njs_vmcode_try_end_t, try_end,\n NJS_VMCODE_TRY_END, 0, NULL);\n try_end_offset = njs_code_offset(generator, try_end);\n\n if (try_block->exit != NULL) {\n ctx->try_exit_label = try_block->exit->label;\n\n njs_debug_generator(vm, \"TRY CTX %p EXIT LABEL %V\", ctx,\n &ctx->try_exit_label);\n\n njs_generate_patch_block(vm, generator, try_block,\n NJS_GENERATOR_EXIT);\n\n njs_generate_code(generator, njs_vmcode_try_trampoline_t, try_break,\n NJS_VMCODE_TRY_BREAK, 1, NULL);\n try_break->exit_value = exit_index;\n\n try_break->offset = -sizeof(njs_vmcode_try_end_t);\n\n } else {\n try_break = NULL;\n }\n\n if (try_block->continuation != NULL) {\n ctx->try_cont_label = try_block->continuation->label;\n\n njs_generate_patch_block(vm, generator, try_block,\n NJS_GENERATOR_CONTINUATION);\n\n njs_generate_code(generator, njs_vmcode_try_trampoline_t, try_continue,\n NJS_VMCODE_TRY_CONTINUE, 1, NULL);\n try_continue->exit_value = exit_index;\n\n try_continue->offset = -sizeof(njs_vmcode_try_end_t);\n\n if (try_break != NULL) {\n try_continue->offset -= sizeof(njs_vmcode_try_trampoline_t);\n }\n }\n\n njs_debug_generator(vm, \"EXIT %s %p\",\n njs_block_type(generator->block->type),\n generator->block);\n\n generator->block = try_block->next;\n\n njs_code_set_jump_offset(generator, njs_vmcode_try_start_t,\n ctx->try_offset);\n ctx->try_offset = try_end_offset;\n\n node = node->right;\n\n if (node->token_type == NJS_TOKEN_CATCH) {\n \/* A \"try\/catch\" case. *\/\n\n var = njs_variable_reference(vm, node->left);\n if (njs_slow_path(var == NULL)) {\n return NJS_ERROR;\n }\n\n catch_index = node->left->index;\n\n njs_generate_code_catch(generator, catch, catch_index, node);\n\n njs_generator_next(generator, njs_generate, node->right);\n\n return njs_generator_after(vm, generator,\n njs_queue_first(&generator->stack), node,\n njs_generate_try_catch, ctx, 0);\n }\n\n if (node->left != NULL) {\n \/* A try\/catch\/finally case. *\/\n\n var = njs_variable_reference(vm, node->left->left);\n if (njs_slow_path(var == NULL)) {\n return NJS_ERROR;\n }\n\n catch_index = node->left->left->index;\n\n njs_generate_code_catch(generator, catch, catch_index, node);\n ctx->catch_offset = njs_code_offset(generator, catch);\n\n ret = njs_generate_start_block(vm, generator, NJS_GENERATOR_TRY,\n &no_label);\n if (njs_slow_path(ret != NJS_OK)) {\n return ret;\n }\n\n ctx->catch_block = generator->block;\n ctx->catch_block->index = exit_index;\n\n njs_generator_next(generator, njs_generate, node->left->right);\n\n return njs_generator_after(vm, generator,\n njs_queue_first(&generator->stack), node,\n njs_generate_try_finally, ctx, 0);\n }\n\n \/* A try\/finally case. *\/\n\n njs_generate_code_catch(generator, catch, ctx->exception_index, NULL);\n\n ctx->catch_block = NULL;\n\n njs_code_set_jump_offset(generator, njs_vmcode_try_end_t,\n ctx->try_offset);\n\n njs_generator_next(generator, njs_generate, node->right);\n\n return njs_generator_after(vm, generator,\n njs_queue_first(&generator->stack), node,\n njs_generate_try_end, ctx, 0);\n}","target":0,"code_token_length":1027,"total_token_length":1358,"max_tokens_setting":2048} +{"idx":289081,"func":"static struct remote_lock * lock_remote ( const char * path , long timeout ) {\n struct active_request_slot * slot ;\n struct slot_results results ;\n struct buffer out_buffer = {\n STRBUF_INIT , 0 }\n ;\n struct strbuf in_buffer = STRBUF_INIT ;\n char * url ;\n char * ep ;\n char timeout_header [ 25 ] ;\n struct remote_lock * lock = NULL ;\n struct curl_slist * dav_headers = NULL ;\n struct xml_ctx ctx ;\n char * escaped ;\n url = xstrfmt ( \"%s%s\" , repo -> url , path ) ;\n ep = strchr ( url + strlen ( repo -> url ) + 1 , '\/' ) ;\n while ( ep ) {\n char saved_character = ep [ 1 ] ;\n ep [ 1 ] = '\\0' ;\n slot = get_active_slot ( ) ;\n slot -> results = & results ;\n curl_setup_http_get ( slot -> curl , url , DAV_MKCOL ) ;\n if ( start_active_slot ( slot ) ) {\n run_active_slot ( slot ) ;\n if ( results . curl_result != CURLE_OK && results . http_code != 405 ) {\n fprintf ( stderr , \"Unable to create branch path %s\\n\" , url ) ;\n free ( url ) ;\n return NULL ;\n }\n }\n else {\n fprintf ( stderr , \"Unable to start MKCOL request\\n\" ) ;\n free ( url ) ;\n return NULL ;\n }\n ep [ 1 ] = saved_character ;\n ep = strchr ( ep + 1 , '\/' ) ;\n }\n escaped = xml_entities ( ident_default_email ( ) ) ;\n strbuf_addf ( & out_buffer . buf , LOCK_REQUEST , escaped ) ;\n free ( escaped ) ;\n xsnprintf ( timeout_header , sizeof ( timeout_header ) , \"Timeout: Second-%ld\" , timeout ) ;\n dav_headers = curl_slist_append ( dav_headers , timeout_header ) ;\n dav_headers = curl_slist_append ( dav_headers , \"Content-Type: text\/xml\" ) ;\n slot = get_active_slot ( ) ;\n slot -> results = & results ;\n curl_setup_http ( slot -> curl , url , DAV_LOCK , & out_buffer , fwrite_buffer ) ;\n curl_easy_setopt ( slot -> curl , CURLOPT_HTTPHEADER , dav_headers ) ;\n curl_easy_setopt ( slot -> curl , CURLOPT_FILE , & in_buffer ) ;\n lock = xcalloc ( 1 , sizeof ( * lock ) ) ;\n lock -> timeout = - 1 ;\n if ( start_active_slot ( slot ) ) {\n run_active_slot ( slot ) ;\n if ( results . curl_result == CURLE_OK ) {\n XML_Parser parser = XML_ParserCreate ( NULL ) ;\n enum XML_Status result ;\n ctx . name = xcalloc ( 10 , 1 ) ;\n ctx . len = 0 ;\n ctx . cdata = NULL ;\n ctx . userFunc = handle_new_lock_ctx ;\n ctx . userData = lock ;\n XML_SetUserData ( parser , & ctx ) ;\n XML_SetElementHandler ( parser , xml_start_tag , xml_end_tag ) ;\n XML_SetCharacterDataHandler ( parser , xml_cdata ) ;\n result = XML_Parse ( parser , in_buffer . buf , in_buffer . len , 1 ) ;\n free ( ctx . name ) ;\n if ( result != XML_STATUS_OK ) {\n fprintf ( stderr , \"XML error: %s\\n\" , XML_ErrorString ( XML_GetErrorCode ( parser ) ) ) ;\n lock -> timeout = - 1 ;\n }\n XML_ParserFree ( parser ) ;\n }\n }\n else {\n fprintf ( stderr , \"Unable to start LOCK request\\n\" ) ;\n }\n curl_slist_free_all ( dav_headers ) ;\n strbuf_release ( & out_buffer . buf ) ;\n strbuf_release ( & in_buffer ) ;\n if ( lock -> token == NULL || lock -> timeout <= 0 ) {\n free ( lock -> token ) ;\n free ( lock -> owner ) ;\n free ( url ) ;\n free ( lock ) ;\n lock = NULL ;\n }\n else {\n lock -> url = url ;\n lock -> start_time = time ( NULL ) ;\n lock -> next = repo -> locks ;\n repo -> locks = lock ;\n }\n return lock ;\n }","target":0,"code_token_length":835,"total_token_length":1166,"max_tokens_setting":2048} +{"idx":473779,"func":"static u32 ieee80211_handle_pwr_constr(struct ieee80211_sub_if_data *sdata,\n\t\t\t\t struct ieee80211_channel *channel,\n\t\t\t\t struct ieee80211_mgmt *mgmt,\n\t\t\t\t const u8 *country_ie, u8 country_ie_len,\n\t\t\t\t const u8 *pwr_constr_ie,\n\t\t\t\t const u8 *cisco_dtpc_ie)\n{\n\tbool has_80211h_pwr = false, has_cisco_pwr = false;\n\tint chan_pwr = 0, pwr_reduction_80211h = 0;\n\tint pwr_level_cisco, pwr_level_80211h;\n\tint new_ap_level;\n\t__le16 capab = mgmt->u.probe_resp.capab_info;\n\n\tif (country_ie &&\n\t (capab & cpu_to_le16(WLAN_CAPABILITY_SPECTRUM_MGMT) ||\n\t capab & cpu_to_le16(WLAN_CAPABILITY_RADIO_MEASURE))) {\n\t\thas_80211h_pwr = ieee80211_find_80211h_pwr_constr(\n\t\t\tsdata, channel, country_ie, country_ie_len,\n\t\t\tpwr_constr_ie, &chan_pwr, &pwr_reduction_80211h);\n\t\tpwr_level_80211h =\n\t\t\tmax_t(int, 0, chan_pwr - pwr_reduction_80211h);\n\t}\n\n\tif (cisco_dtpc_ie) {\n\t\tieee80211_find_cisco_dtpc(\n\t\t\tsdata, channel, cisco_dtpc_ie, &pwr_level_cisco);\n\t\thas_cisco_pwr = true;\n\t}\n\n\tif (!has_80211h_pwr && !has_cisco_pwr)\n\t\treturn 0;\n\n\t\/* If we have both 802.11h and Cisco DTPC, apply both limits\n\t * by picking the smallest of the two power levels advertised.\n\t *\/\n\tif (has_80211h_pwr &&\n\t (!has_cisco_pwr || pwr_level_80211h <= pwr_level_cisco)) {\n\t\tnew_ap_level = pwr_level_80211h;\n\n\t\tif (sdata->ap_power_level == new_ap_level)\n\t\t\treturn 0;\n\n\t\tsdata_dbg(sdata,\n\t\t\t \"Limiting TX power to %d (%d - %d) dBm as advertised by %pM\\n\",\n\t\t\t pwr_level_80211h, chan_pwr, pwr_reduction_80211h,\n\t\t\t sdata->u.mgd.bssid);\n\t} else { \/* has_cisco_pwr is always true here. *\/\n\t\tnew_ap_level = pwr_level_cisco;\n\n\t\tif (sdata->ap_power_level == new_ap_level)\n\t\t\treturn 0;\n\n\t\tsdata_dbg(sdata,\n\t\t\t \"Limiting TX power to %d dBm as advertised by %pM\\n\",\n\t\t\t pwr_level_cisco, sdata->u.mgd.bssid);\n\t}\n\n\tsdata->ap_power_level = new_ap_level;\n\tif (__ieee80211_recalc_txpower(sdata))\n\t\treturn BSS_CHANGED_TXPOWER;\n\treturn 0;\n}","target":0,"code_token_length":722,"total_token_length":1053,"max_tokens_setting":2048} +{"idx":496303,"func":"static bool ad_convert_xattr(vfs_handle_struct *handle,\n\t\t\t struct adouble *ad,\n\t\t\t const struct smb_filename *smb_fname,\n\t\t\t const char *catia_mappings,\n\t\t\t bool *converted_xattr)\n{\n\tstatic struct char_mappings **string_replace_cmaps = NULL;\n\tuint16_t i;\n\tint saved_errno = 0;\n\tNTSTATUS status;\n\tint rc;\n\tbool ok;\n\n\t*converted_xattr = false;\n\n\tif (ad_getentrylen(ad, ADEID_FINDERI) == ADEDLEN_FINDERI) {\n\t\treturn true;\n\t}\n\n\tif (string_replace_cmaps == NULL) {\n\t\tconst char **mappings = NULL;\n\n\t\tmappings = str_list_make_v3_const(\n\t\t\ttalloc_tos(), catia_mappings, NULL);\n\t\tif (mappings == NULL) {\n\t\t\treturn false;\n\t\t}\n\t\tstring_replace_cmaps = string_replace_init_map(\n\t\t\thandle->conn->sconn, mappings);\n\t\tTALLOC_FREE(mappings);\n\t}\n\n\tfor (i = 0; i < ad->adx_header.adx_num_attrs; i++) {\n\t\tstruct ad_xattr_entry *e = &ad->adx_entries[i];\n\t\tchar *mapped_name = NULL;\n\t\tchar *tmp = NULL;\n\t\tstruct smb_filename *stream_name = NULL;\n\t\tfiles_struct *fsp = NULL;\n\t\tssize_t nwritten;\n\n\t\tstatus = string_replace_allocate(handle->conn,\n\t\t\t\t\t\t e->adx_name,\n\t\t\t\t\t\t string_replace_cmaps,\n\t\t\t\t\t\t talloc_tos(),\n\t\t\t\t\t\t &mapped_name,\n\t\t\t\t\t\t vfs_translate_to_windows);\n\t\tif (!NT_STATUS_IS_OK(status) &&\n\t\t !NT_STATUS_EQUAL(status, NT_STATUS_NONE_MAPPED))\n\t\t{\n\t\t\tDBG_ERR(\"string_replace_allocate failed\\n\");\n\t\t\tok = false;\n\t\t\tgoto fail;\n\t\t}\n\n\t\ttmp = mapped_name;\n\t\tmapped_name = talloc_asprintf(talloc_tos(), \":%s\", tmp);\n\t\tTALLOC_FREE(tmp);\n\t\tif (mapped_name == NULL) {\n\t\t\tok = false;\n\t\t\tgoto fail;\n\t\t}\n\n\t\tstream_name = synthetic_smb_fname(talloc_tos(),\n\t\t\t\t\t\t smb_fname->base_name,\n\t\t\t\t\t\t mapped_name,\n\t\t\t\t\t\t NULL,\n\t\t\t\t\t\t smb_fname->twrp,\n\t\t\t\t\t\t smb_fname->flags);\n\t\tTALLOC_FREE(mapped_name);\n\t\tif (stream_name == NULL) {\n\t\t\tDBG_ERR(\"synthetic_smb_fname failed\\n\");\n\t\t\tok = false;\n\t\t\tgoto fail;\n\t\t}\n\n\t\tDBG_DEBUG(\"stream_name: %s\\n\", smb_fname_str_dbg(stream_name));\n\n\t\trc = vfs_stat(handle->conn, stream_name);\n\t\tif (rc == -1 && errno != ENOENT) {\n\t\t\tok = false;\n\t\t\tgoto fail;\n\t\t}\n\n\t\tstatus = openat_pathref_fsp(handle->conn->cwd_fsp, stream_name);\n\t\tif (!NT_STATUS_IS_OK(status) &&\n\t\t !NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND))\n\t\t{\n\t\t\tok = false;\n\t\t\tgoto fail;\n\t\t}\n\n\t\tstatus = SMB_VFS_CREATE_FILE(\n\t\t\thandle->conn,\t\t\t\/* conn *\/\n\t\t\tNULL,\t\t\t\t\/* req *\/\n\t\t\tstream_name,\t\t\t\/* fname *\/\n\t\t\tFILE_GENERIC_WRITE,\t\t\/* access_mask *\/\n\t\t\tFILE_SHARE_READ | FILE_SHARE_WRITE, \/* share_access *\/\n\t\t\tFILE_OPEN_IF,\t\t\t\/* create_disposition *\/\n\t\t\t0,\t\t\t\t\/* create_options *\/\n\t\t\t0,\t\t\t\t\/* file_attributes *\/\n\t\t\tINTERNAL_OPEN_ONLY,\t\t\/* oplock_request *\/\n\t\t\tNULL,\t\t\t\t\/* lease *\/\n\t\t\t0,\t\t\t\t\/* allocation_size *\/\n\t\t\t0,\t\t\t\t\/* private_flags *\/\n\t\t\tNULL,\t\t\t\t\/* sd *\/\n\t\t\tNULL,\t\t\t\t\/* ea_list *\/\n\t\t\t&fsp,\t\t\t\t\/* result *\/\n\t\t\tNULL,\t\t\t\t\/* psbuf *\/\n\t\t\tNULL, NULL);\t\t\t\/* create context *\/\n\t\tTALLOC_FREE(stream_name);\n\t\tif (!NT_STATUS_IS_OK(status)) {\n\t\t\tDBG_ERR(\"SMB_VFS_CREATE_FILE failed\\n\");\n\t\t\tok = false;\n\t\t\tgoto fail;\n\t\t}\n\n\t\tnwritten = SMB_VFS_PWRITE(fsp,\n\t\t\t\t\t ad->ad_data + e->adx_offset,\n\t\t\t\t\t e->adx_length,\n\t\t\t\t\t 0);\n\t\tif (nwritten == -1) {\n\t\t\tDBG_ERR(\"SMB_VFS_PWRITE failed\\n\");\n\t\t\tsaved_errno = errno;\n\t\t\tclose_file(NULL, fsp, ERROR_CLOSE);\n\t\t\terrno = saved_errno;\n\t\t\tok = false;\n\t\t\tgoto fail;\n\t\t}\n\n\t\tstatus = close_file(NULL, fsp, NORMAL_CLOSE);\n\t\tif (!NT_STATUS_IS_OK(status)) {\n\t\t\tok = false;\n\t\t\tgoto fail;\n\t\t}\n\t\tfsp = NULL;\n\t}\n\n\tad->adx_header.adx_num_attrs = 0;\n\tTALLOC_FREE(ad->adx_entries);\n\n\tad_setentrylen(ad, ADEID_FINDERI, ADEDLEN_FINDERI);\n\n\trc = ad_fset(handle, ad, ad->ad_fsp);\n\tif (rc != 0) {\n\t\tDBG_ERR(\"ad_fset on [%s] failed: %s\\n\",\n\t\t\tfsp_str_dbg(ad->ad_fsp), strerror(errno));\n\t\tok = false;\n\t\tgoto fail;\n\t}\n\n\tok = ad_convert_move_reso(handle, ad, smb_fname);\n\tif (!ok) {\n\t\tgoto fail;\n\t}\n\n\t*converted_xattr = true;\n\tok = true;\n\nfail:\n\treturn ok;\n}","target":0,"code_token_length":1127,"total_token_length":1458,"max_tokens_setting":2048} +{"idx":72988,"func":"static OPJ_BOOL opj_tcd_mct_decode(opj_tcd_t *p_tcd, opj_event_mgr_t *p_manager)\n{\n opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;\n opj_tcp_t * l_tcp = p_tcd->tcp;\n opj_tcd_tilecomp_t * l_tile_comp = l_tile->comps;\n OPJ_UINT32 l_samples, i;\n\n if (! l_tcp->mct) {\n return OPJ_TRUE;\n }\n\n l_samples = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) *\n (l_tile_comp->y1 - l_tile_comp->y0));\n\n if (l_tile->numcomps >= 3) {\n \/* testcase 1336.pdf.asan.47.376 *\/\n if ((l_tile->comps[0].x1 - l_tile->comps[0].x0) * (l_tile->comps[0].y1 -\n l_tile->comps[0].y0) < (OPJ_INT32)l_samples ||\n (l_tile->comps[1].x1 - l_tile->comps[1].x0) * (l_tile->comps[1].y1 -\n l_tile->comps[1].y0) < (OPJ_INT32)l_samples ||\n (l_tile->comps[2].x1 - l_tile->comps[2].x0) * (l_tile->comps[2].y1 -\n l_tile->comps[2].y0) < (OPJ_INT32)l_samples) {\n opj_event_msg(p_manager, EVT_ERROR,\n \"Tiles don't all have the same dimension. Skip the MCT step.\\n\");\n return OPJ_FALSE;\n } else if (l_tcp->mct == 2) {\n OPJ_BYTE ** l_data;\n\n if (! l_tcp->m_mct_decoding_matrix) {\n return OPJ_TRUE;\n }\n\n l_data = (OPJ_BYTE **) opj_malloc(l_tile->numcomps * sizeof(OPJ_BYTE*));\n if (! l_data) {\n return OPJ_FALSE;\n }\n\n for (i = 0; i < l_tile->numcomps; ++i) {\n l_data[i] = (OPJ_BYTE*) l_tile_comp->data;\n ++l_tile_comp;\n }\n\n if (! opj_mct_decode_custom(\/* MCT data *\/\n (OPJ_BYTE*) l_tcp->m_mct_decoding_matrix,\n \/* size of components *\/\n l_samples,\n \/* components *\/\n l_data,\n \/* nb of components (i.e. size of pData) *\/\n l_tile->numcomps,\n \/* tells if the data is signed *\/\n p_tcd->image->comps->sgnd)) {\n opj_free(l_data);\n return OPJ_FALSE;\n }\n\n opj_free(l_data);\n } else {\n if (l_tcp->tccps->qmfbid == 1) {\n opj_mct_decode(l_tile->comps[0].data,\n l_tile->comps[1].data,\n l_tile->comps[2].data,\n l_samples);\n } else {\n opj_mct_decode_real((OPJ_FLOAT32*)l_tile->comps[0].data,\n (OPJ_FLOAT32*)l_tile->comps[1].data,\n (OPJ_FLOAT32*)l_tile->comps[2].data,\n l_samples);\n }\n }\n } else {\n opj_event_msg(p_manager, EVT_ERROR,\n \"Number of components (%d) is inconsistent with a MCT. Skip the MCT step.\\n\",\n l_tile->numcomps);\n }\n\n return OPJ_TRUE;\n}","target":0,"code_token_length":846,"total_token_length":1177,"max_tokens_setting":2048} +{"idx":361559,"func":"static connection_struct *switch_message(uint8 type, struct smb_request *req, int size)\n{\n\tint flags;\n\tuint16 session_tag;\n\tconnection_struct *conn = NULL;\n\tstruct smbd_server_connection *sconn = smbd_server_conn;\n\n\terrno = 0;\n\n\t\/* Make sure this is an SMB packet. smb_size contains NetBIOS header\n\t * so subtract 4 from it. *\/\n\tif (!valid_smb_header(req->inbuf)\n\t || (size < (smb_size - 4))) {\n\t\tDEBUG(2,(\"Non-SMB packet of length %d. Terminating server\\n\",\n\t\t\t smb_len(req->inbuf)));\n\t\texit_server_cleanly(\"Non-SMB packet\");\n\t}\n\n\tif (smb_messages[type].fn == NULL) {\n\t\tDEBUG(0,(\"Unknown message type %d!\\n\",type));\n\t\tsmb_dump(\"Unknown\", 1, (char *)req->inbuf, size);\n\t\treply_unknown_new(req, type);\n\t\treturn NULL;\n\t}\n\n\tflags = smb_messages[type].flags;\n\n\t\/* In share mode security we must ignore the vuid. *\/\n\tsession_tag = (lp_security() == SEC_SHARE)\n\t\t? UID_FIELD_INVALID : req->vuid;\n\tconn = req->conn;\n\n\tDEBUG(3,(\"switch message %s (pid %d) conn 0x%lx\\n\", smb_fn_name(type),\n\t\t (int)sys_getpid(), (unsigned long)conn));\n\n\tsmb_dump(smb_fn_name(type), 1, (char *)req->inbuf, size);\n\n\t\/* Ensure this value is replaced in the incoming packet. *\/\n\tSSVAL(req->inbuf,smb_uid,session_tag);\n\n\t\/*\n\t * Ensure the correct username is in current_user_info. This is a\n\t * really ugly bugfix for problems with multiple session_setup_and_X's\n\t * being done and allowing %U and %G substitutions to work correctly.\n\t * There is a reason this code is done here, don't move it unless you\n\t * know what you're doing... :-).\n\t * JRA.\n\t *\/\n\n\tif (session_tag != sconn->smb1.sessions.last_session_tag) {\n\t\tuser_struct *vuser = NULL;\n\n\t\tsconn->smb1.sessions.last_session_tag = session_tag;\n\t\tif(session_tag != UID_FIELD_INVALID) {\n\t\t\tvuser = get_valid_user_struct(sconn, session_tag);\n\t\t\tif (vuser) {\n\t\t\t\tset_current_user_info(\n\t\t\t\t\tvuser->server_info->sanitized_username,\n\t\t\t\t\tvuser->server_info->unix_name,\n\t\t\t\t\tpdb_get_domain(vuser->server_info\n\t\t\t\t\t\t ->sam_account));\n\t\t\t}\n\t\t}\n\t}\n\n\t\/* Does this call need to be run as the connected user? *\/\n\tif (flags & AS_USER) {\n\n\t\t\/* Does this call need a valid tree connection? *\/\n\t\tif (!conn) {\n\t\t\t\/*\n\t\t\t * Amazingly, the error code depends on the command\n\t\t\t * (from Samba4).\n\t\t\t *\/\n\t\t\tif (type == SMBntcreateX) {\n\t\t\t\treply_nterror(req, NT_STATUS_INVALID_HANDLE);\n\t\t\t} else {\n\t\t\t\treply_nterror(req, NT_STATUS_NETWORK_NAME_DELETED);\n\t\t\t}\n\t\t\treturn NULL;\n\t\t}\n\n\t\tif (!change_to_user(conn,session_tag)) {\n\t\t\tDEBUG(0, (\"Error: Could not change to user. Removing \"\n\t\t\t \"deferred open, mid=%d.\\n\", req->mid));\n\t\t\treply_force_doserror(req, ERRSRV, ERRbaduid);\n\t\t\treturn conn;\n\t\t}\n\n\t\t\/* All NEED_WRITE and CAN_IPC flags must also have AS_USER. *\/\n\n\t\t\/* Does it need write permission? *\/\n\t\tif ((flags & NEED_WRITE) && !CAN_WRITE(conn)) {\n\t\t\treply_nterror(req, NT_STATUS_MEDIA_WRITE_PROTECTED);\n\t\t\treturn conn;\n\t\t}\n\n\t\t\/* IPC services are limited *\/\n\t\tif (IS_IPC(conn) && !(flags & CAN_IPC)) {\n\t\t\treply_nterror(req, NT_STATUS_ACCESS_DENIED);\n\t\t\treturn conn;\n\t\t}\n\t} else {\n\t\t\/* This call needs to be run as root *\/\n\t\tchange_to_root_user();\n\t}\n\n\t\/* load service specific parameters *\/\n\tif (conn) {\n\t\tif (req->encrypted) {\n\t\t\tconn->encrypted_tid = true;\n\t\t\t\/* encrypted required from now on. *\/\n\t\t\tconn->encrypt_level = Required;\n\t\t} else if (ENCRYPTION_REQUIRED(conn)) {\n\t\t\tif (req->cmd != SMBtrans2 && req->cmd != SMBtranss2) {\n\t\t\t\texit_server_cleanly(\"encryption required \"\n\t\t\t\t\t\"on connection\");\n\t\t\t\treturn conn;\n\t\t\t}\n\t\t}\n\n\t\tif (!set_current_service(conn,SVAL(req->inbuf,smb_flg),\n\t\t\t\t\t (flags & (AS_USER|DO_CHDIR)\n\t\t\t\t\t ?True:False))) {\n\t\t\treply_nterror(req, NT_STATUS_ACCESS_DENIED);\n\t\t\treturn conn;\n\t\t}\n\t\tconn->num_smb_operations++;\n\t}\n\n\t\/* does this protocol need to be run as guest? *\/\n\tif ((flags & AS_GUEST)\n\t && (!change_to_guest() ||\n\t\t!check_access(smbd_server_fd(), lp_hostsallow(-1),\n\t\t\t lp_hostsdeny(-1)))) {\n\t\treply_nterror(req, NT_STATUS_ACCESS_DENIED);\n\t\treturn conn;\n\t}\n\n\tsmb_messages[type].fn(req);\n\treturn req->conn;\n}","target":0,"code_token_length":1133,"total_token_length":1464,"max_tokens_setting":2048} +{"idx":298237,"func":"void sctp_assoc_update(struct sctp_association *asoc,\n\t\t struct sctp_association *new)\n{\n\tstruct sctp_transport *trans;\n\tstruct list_head *pos, *temp;\n\n\t\/* Copy in new parameters of peer. *\/\n\tasoc->c = new->c;\n\tasoc->peer.rwnd = new->peer.rwnd;\n\tasoc->peer.sack_needed = new->peer.sack_needed;\n\tasoc->peer.auth_capable = new->peer.auth_capable;\n\tasoc->peer.i = new->peer.i;\n\tsctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL,\n\t\t\t asoc->peer.i.initial_tsn, GFP_ATOMIC);\n\n\t\/* Remove any peer addresses not present in the new association. *\/\n\tlist_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {\n\t\ttrans = list_entry(pos, struct sctp_transport, transports);\n\t\tif (!sctp_assoc_lookup_paddr(new, &trans->ipaddr)) {\n\t\t\tsctp_assoc_rm_peer(asoc, trans);\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (asoc->state >= SCTP_STATE_ESTABLISHED)\n\t\t\tsctp_transport_reset(trans);\n\t}\n\n\t\/* If the case is A (association restart), use\n\t * initial_tsn as next_tsn. If the case is B, use\n\t * current next_tsn in case data sent to peer\n\t * has been discarded and needs retransmission.\n\t *\/\n\tif (asoc->state >= SCTP_STATE_ESTABLISHED) {\n\t\tasoc->next_tsn = new->next_tsn;\n\t\tasoc->ctsn_ack_point = new->ctsn_ack_point;\n\t\tasoc->adv_peer_ack_point = new->adv_peer_ack_point;\n\n\t\t\/* Reinitialize SSN for both local streams\n\t\t * and peer's streams.\n\t\t *\/\n\t\tsctp_ssnmap_clear(asoc->ssnmap);\n\n\t\t\/* Flush the ULP reassembly and ordered queue.\n\t\t * Any data there will now be stale and will\n\t\t * cause problems.\n\t\t *\/\n\t\tsctp_ulpq_flush(&asoc->ulpq);\n\n\t\t\/* reset the overall association error count so\n\t\t * that the restarted association doesn't get torn\n\t\t * down on the next retransmission timer.\n\t\t *\/\n\t\tasoc->overall_error_count = 0;\n\n\t} else {\n\t\t\/* Add any peer addresses from the new association. *\/\n\t\tlist_for_each_entry(trans, &new->peer.transport_addr_list,\n\t\t\t\ttransports) {\n\t\t\tif (!sctp_assoc_lookup_paddr(asoc, &trans->ipaddr))\n\t\t\t\tsctp_assoc_add_peer(asoc, &trans->ipaddr,\n\t\t\t\t\t\t GFP_ATOMIC, trans->state);\n\t\t}\n\n\t\tasoc->ctsn_ack_point = asoc->next_tsn - 1;\n\t\tasoc->adv_peer_ack_point = asoc->ctsn_ack_point;\n\t\tif (!asoc->ssnmap) {\n\t\t\t\/* Move the ssnmap. *\/\n\t\t\tasoc->ssnmap = new->ssnmap;\n\t\t\tnew->ssnmap = NULL;\n\t\t}\n\n\t\tif (!asoc->assoc_id) {\n\t\t\t\/* get a new association id since we don't have one\n\t\t\t * yet.\n\t\t\t *\/\n\t\t\tsctp_assoc_set_id(asoc, GFP_ATOMIC);\n\t\t}\n\t}\n\n\t\/* SCTP-AUTH: Save the peer parameters from the new associations\n\t * and also move the association shared keys over\n\t *\/\n\tkfree(asoc->peer.peer_random);\n\tasoc->peer.peer_random = new->peer.peer_random;\n\tnew->peer.peer_random = NULL;\n\n\tkfree(asoc->peer.peer_chunks);\n\tasoc->peer.peer_chunks = new->peer.peer_chunks;\n\tnew->peer.peer_chunks = NULL;\n\n\tkfree(asoc->peer.peer_hmacs);\n\tasoc->peer.peer_hmacs = new->peer.peer_hmacs;\n\tnew->peer.peer_hmacs = NULL;\n\n\tsctp_auth_asoc_init_active_key(asoc, GFP_ATOMIC);\n}","target":0,"code_token_length":850,"total_token_length":1181,"max_tokens_setting":2048} +{"idx":303116,"func":"void vp8_mc_chroma(VP8Context *s, VP8ThreadData *td, uint8_t *dst1,\n uint8_t *dst2, ThreadFrame *ref, const VP56mv *mv,\n int x_off, int y_off, int block_w, int block_h,\n int width, int height, ptrdiff_t linesize,\n vp8_mc_func mc_func[3][3])\n{\n uint8_t *src1 = ref->f->data[1], *src2 = ref->f->data[2];\n\n if (AV_RN32A(mv)) {\n int mx = mv->x & 7, mx_idx = subpel_idx[0][mx];\n int my = mv->y & 7, my_idx = subpel_idx[0][my];\n\n x_off += mv->x >> 3;\n y_off += mv->y >> 3;\n\n \/\/ edge emulation\n src1 += y_off * linesize + x_off;\n src2 += y_off * linesize + x_off;\n ff_thread_await_progress(ref, (3 + y_off + block_h + subpel_idx[2][my]) >> 3, 0);\n if (x_off < mx_idx || x_off >= width - block_w - subpel_idx[2][mx] ||\n y_off < my_idx || y_off >= height - block_h - subpel_idx[2][my]) {\n s->vdsp.emulated_edge_mc(td->edge_emu_buffer,\n src1 - my_idx * linesize - mx_idx,\n EDGE_EMU_LINESIZE, linesize,\n block_w + subpel_idx[1][mx],\n block_h + subpel_idx[1][my],\n x_off - mx_idx, y_off - my_idx, width, height);\n src1 = td->edge_emu_buffer + mx_idx + EDGE_EMU_LINESIZE * my_idx;\n mc_func[my_idx][mx_idx](dst1, linesize, src1, EDGE_EMU_LINESIZE, block_h, mx, my);\n\n s->vdsp.emulated_edge_mc(td->edge_emu_buffer,\n src2 - my_idx * linesize - mx_idx,\n EDGE_EMU_LINESIZE, linesize,\n block_w + subpel_idx[1][mx],\n block_h + subpel_idx[1][my],\n x_off - mx_idx, y_off - my_idx, width, height);\n src2 = td->edge_emu_buffer + mx_idx + EDGE_EMU_LINESIZE * my_idx;\n mc_func[my_idx][mx_idx](dst2, linesize, src2, EDGE_EMU_LINESIZE, block_h, mx, my);\n } else {\n mc_func[my_idx][mx_idx](dst1, linesize, src1, linesize, block_h, mx, my);\n mc_func[my_idx][mx_idx](dst2, linesize, src2, linesize, block_h, mx, my);\n }\n } else {\n ff_thread_await_progress(ref, (3 + y_off + block_h) >> 3, 0);\n mc_func[0][0](dst1, linesize, src1 + y_off * linesize + x_off, linesize, block_h, 0, 0);\n mc_func[0][0](dst2, linesize, src2 + y_off * linesize + x_off, linesize, block_h, 0, 0);\n }\n}","target":0,"code_token_length":754,"total_token_length":1085,"max_tokens_setting":2048} +{"idx":357676,"func":"long do_fork(unsigned long clone_flags,\n\t unsigned long stack_start,\n\t struct pt_regs *regs,\n\t unsigned long stack_size,\n\t int __user *parent_tidptr,\n\t int __user *child_tidptr)\n{\n\tstruct task_struct *p;\n\tint trace = 0;\n\tlong nr;\n\n\t\/*\n\t * Do some preliminary argument and permissions checking before we\n\t * actually start allocating stuff\n\t *\/\n\tif (clone_flags & CLONE_NEWUSER) {\n\t\tif (clone_flags & CLONE_THREAD)\n\t\t\treturn -EINVAL;\n\t\t\/* hopefully this check will go away when userns support is\n\t\t * complete\n\t\t *\/\n\t\tif (!capable(CAP_SYS_ADMIN) || !capable(CAP_SETUID) ||\n\t\t\t\t!capable(CAP_SETGID))\n\t\t\treturn -EPERM;\n\t}\n\n\t\/*\n\t * We hope to recycle these flags after 2.6.26\n\t *\/\n\tif (unlikely(clone_flags & CLONE_STOPPED)) {\n\t\tstatic int __read_mostly count = 100;\n\n\t\tif (count > 0 && printk_ratelimit()) {\n\t\t\tchar comm[TASK_COMM_LEN];\n\n\t\t\tcount--;\n\t\t\tprintk(KERN_INFO \"fork(): process `%s' used deprecated \"\n\t\t\t\t\t\"clone flags 0x%lx\\n\",\n\t\t\t\tget_task_comm(comm, current),\n\t\t\t\tclone_flags & CLONE_STOPPED);\n\t\t}\n\t}\n\n\t\/*\n\t * When called from kernel_thread, don't do user tracing stuff.\n\t *\/\n\tif (likely(user_mode(regs)))\n\t\ttrace = tracehook_prepare_clone(clone_flags);\n\n\tp = copy_process(clone_flags, stack_start, regs, stack_size,\n\t\t\t child_tidptr, NULL, trace);\n\t\/*\n\t * Do this prior waking up the new thread - the thread pointer\n\t * might get invalid after that point, if the thread exits quickly.\n\t *\/\n\tif (!IS_ERR(p)) {\n\t\tstruct completion vfork;\n\n\t\ttrace_sched_process_fork(current, p);\n\n\t\tnr = task_pid_vnr(p);\n\n\t\tif (clone_flags & CLONE_PARENT_SETTID)\n\t\t\tput_user(nr, parent_tidptr);\n\n\t\tif (clone_flags & CLONE_VFORK) {\n\t\t\tp->vfork_done = &vfork;\n\t\t\tinit_completion(&vfork);\n\t\t}\n\n\t\taudit_finish_fork(p);\n\t\ttracehook_report_clone(trace, regs, clone_flags, nr, p);\n\n\t\t\/*\n\t\t * We set PF_STARTING at creation in case tracing wants to\n\t\t * use this to distinguish a fully live task from one that\n\t\t * hasn't gotten to tracehook_report_clone() yet. Now we\n\t\t * clear it and set the child going.\n\t\t *\/\n\t\tp->flags &= ~PF_STARTING;\n\n\t\tif (unlikely(clone_flags & CLONE_STOPPED)) {\n\t\t\t\/*\n\t\t\t * We'll start up with an immediate SIGSTOP.\n\t\t\t *\/\n\t\t\tsigaddset(&p->pending.signal, SIGSTOP);\n\t\t\tset_tsk_thread_flag(p, TIF_SIGPENDING);\n\t\t\t__set_task_state(p, TASK_STOPPED);\n\t\t} else {\n\t\t\twake_up_new_task(p, clone_flags);\n\t\t}\n\n\t\ttracehook_report_clone_complete(trace, regs,\n\t\t\t\t\t\tclone_flags, nr, p);\n\n\t\tif (clone_flags & CLONE_VFORK) {\n\t\t\tfreezer_do_not_count();\n\t\t\twait_for_completion(&vfork);\n\t\t\tfreezer_count();\n\t\t\ttracehook_report_vfork_done(p, nr);\n\t\t}\n\t} else {\n\t\tnr = PTR_ERR(p);\n\t}\n\treturn nr;\n}","target":0,"code_token_length":742,"total_token_length":1073,"max_tokens_setting":2048} +{"idx":447571,"func":"static cl_error_t egg_parse_archive_headers(egg_handle* handle)\n{\n cl_error_t status = CL_EPARSE;\n cl_error_t retval;\n\n egg_header* eggHeader = NULL;\n uint32_t magic = 0;\n const uint8_t* index = 0;\n\n if (!handle) {\n cli_errmsg(\"egg_parse_archive_headers: Invalid args!\\n\");\n return CL_EARG;\n }\n\n if (CL_SUCCESS != EGG_VALIDATE_HANDLE(handle)) {\n cli_errmsg(\"egg_parse_archive_headers: Invalid handle values!\\n\");\n status = CL_EARG;\n goto done;\n }\n\n \/*\n * 1st:\n * Archive headers begins with the egg_header.\n *\/\n\n index = (const uint8_t*)fmap_need_off_once(handle->map, handle->offset, sizeof(egg_header));\n if (!index) {\n cli_dbgmsg(\"egg_parse_archive_headers: File buffer too small to contain egg_header.\\n\");\n goto done;\n }\n\n eggHeader = (egg_header*)index;\n\n if (EGG_HEADER_MAGIC != le32_to_host(eggHeader->magic)) {\n cli_dbgmsg(\"egg_parse_archive_headers: Invalid egg header magic: %08x.\\n\", le32_to_host(eggHeader->magic));\n goto done;\n }\n\n cli_dbgmsg(\"egg_parse_archive_headers: egg_header->magic: %08x (%s)\\n\", le32_to_host(eggHeader->magic), getMagicHeaderName(le32_to_host(eggHeader->magic)));\n cli_dbgmsg(\"egg_parse_archive_headers: egg_header->version: %04x\\n\", le16_to_host(eggHeader->version));\n cli_dbgmsg(\"egg_parse_archive_headers: egg_header->header_id: %08x\\n\", le32_to_host(eggHeader->header_id));\n cli_dbgmsg(\"egg_parse_archive_headers: egg_header->reserved: %08x\\n\", le32_to_host(eggHeader->reserved));\n\n if (EGG_HEADER_VERSION != le16_to_host(eggHeader->version)) {\n cli_dbgmsg(\"egg_parse_archive_headers: Unexpected EGG archive version #: %04x.\\n\",\n le16_to_host(eggHeader->version));\n }\n\n handle->offset += sizeof(egg_header);\n\n \/*\n * 2nd:\n * Egg Header may be followed by:\n * a) split_compression header and\/or\n * b) solid_compression\n * c) global encryption header\n * d) EOFARC\n *\/\n\n while (handle->map->len > handle->offset) {\n\n \/* Get the next magic32_t *\/\n index = (const uint8_t*)fmap_need_off_once(handle->map, handle->offset, sizeof(magic32_t));\n if (!index) {\n cli_dbgmsg(\"egg_parse_archive_headers: File buffer too small to contain end of archive magic bytes.\\n\");\n goto done;\n }\n\n magic = le32_to_host(*((uint32_t*)index));\n\n if (EOFARC == magic) {\n \/*\n * Archive headers should conclude with EOFARC magic bytes.\n *\/\n handle->offset += sizeof(magic32_t);\n\n cli_dbgmsg(\"egg_parse_archive_headers: End of archive headers.\\n\");\n break; \/* Break out of the loop *\/\n } else {\n \/*\n * Parse extra fields.\n *\/\n retval = egg_parse_archive_extra_field(handle);\n if (CL_SUCCESS != retval) {\n cli_dbgmsg(\"egg_parse_archive_headers: Failed to parse archive header, magic: %08x (%s)\\n\", magic, getMagicHeaderName(magic));\n break; \/* Break out of the loop *\/\n }\n }\n }\n\n status = CL_SUCCESS;\n\ndone:\n return status;\n}","target":0,"code_token_length":830,"total_token_length":1161,"max_tokens_setting":2048} +{"idx":6872,"func":"static int string_scan_range(RList *list, const ut8 *buf, int min,\n\t\t\t const ut64 from, const ut64 to, int type) {\n\tut8 tmp[R_STRING_SCAN_BUFFER_SIZE];\n\tut64 str_start, needle = from;\n\tint count = 0, i, rc, runes;\n\tint str_type = R_STRING_TYPE_DETECT;\n\n\tif (type == -1) {\n\t\ttype = R_STRING_TYPE_DETECT;\n\t}\n\tif (!buf || !min) {\n\t\treturn -1;\n\t}\n\twhile (needle < to) {\n\t\trc = r_utf8_decode (buf + needle, to - needle, NULL);\n\t\tif (!rc) {\n\t\t\tneedle++;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (type == R_STRING_TYPE_DETECT) {\n\t\t\tchar *w = (char *)buf + needle + rc;\n\t\t\tif ((to - needle) > 4) {\n\t\t\t\tbool is_wide32 = needle + rc + 2 < to && !w[0] && !w[1] && !w[2] && w[3] && !w[4];\n\t\t\t\tif (is_wide32) {\n\t\t\t\t\tstr_type = R_STRING_TYPE_WIDE32;\n\t\t\t\t} else {\n\t\t\t\t\tbool is_wide = needle + rc + 2 < to && !w[0] && w[1] && !w[2];\n\t\t\t\t\tstr_type = is_wide? R_STRING_TYPE_WIDE: R_STRING_TYPE_ASCII;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tstr_type = R_STRING_TYPE_ASCII;\n\t\t\t}\n\t\t} else {\n\t\t\tstr_type = type;\n\t\t}\n\n\n\t\trunes = 0;\n\t\tstr_start = needle;\n\n\t\t\/* Eat a whole C string *\/\n\t\tfor (rc = i = 0; i < sizeof (tmp) - 3 && needle < to; i += rc) {\n\t\t\tRRune r = {0};\n\n\t\t\tif (str_type == R_STRING_TYPE_WIDE32) {\n\t\t\t\trc = r_utf32le_decode (buf + needle, to - needle, &r);\n\t\t\t\tif (rc) {\n\t\t\t\t\trc = 4;\n\t\t\t\t}\n\t\t\t} else if (str_type == R_STRING_TYPE_WIDE) {\n\t\t\t\trc = r_utf16le_decode (buf + needle, to - needle, &r);\n\t\t\t\tif (rc == 1) {\n\t\t\t\t\trc = 2;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trc = r_utf8_decode (buf + needle, to - needle, &r);\n\t\t\t\tif (rc > 1) {\n\t\t\t\t\tstr_type = R_STRING_TYPE_UTF8;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/* Invalid sequence detected *\/\n\t\t\tif (!rc) {\n\t\t\t\tneedle++;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tneedle += rc;\n\n\t\t\tif (r_isprint (r)) {\n\t\t\t\tif (str_type == R_STRING_TYPE_WIDE32) {\n\t\t\t\t\tif (r == 0xff) {\n\t\t\t\t\t\tr = 0;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\trc = r_utf8_encode (&tmp[i], r);\n\t\t\t\trunes++;\n\t\t\t\t\/* Print the escape code *\/\n\t\t\t} else if (r && r < 0x100 && strchr (\"\\b\\v\\f\\n\\r\\t\\a\\e\", (char)r)) {\n\t\t\t\tif ((i + 32) < sizeof (tmp) && r < 28) {\n\t\t\t\t\ttmp[i + 0] = '\\\\';\n\t\t\t\t\ttmp[i + 1] = \" abtnvfr e\"[r];\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ string too long\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\trc = 2;\n\t\t\t\trunes++;\n\t\t\t} else {\n\t\t\t\t\/* \\0 marks the end of C-strings *\/\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\ttmp[i++] = '\\0';\n\n\t\tif (runes >= min) {\n\t\t\tif (str_type == R_STRING_TYPE_ASCII) {\n\t\t\t\t\/\/ reduce false positives\n\t\t\t\tint j;\n\t\t\t\tfor (j = 0; j < i; j++) {\n\t\t\t\t\tchar ch = tmp[j];\n\t\t\t\t\tif (ch != '\\n' && ch != '\\r' && ch != '\\t') {\n\t\t\t\t\t\tif (!IS_PRINTABLE (tmp[j])) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (list) {\n\t\t\t\tRBinString *new = R_NEW0 (RBinString);\n\t\t\t\tif (!new) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tnew->type = str_type;\n\t\t\t\tnew->length = runes;\n\t\t\t\tnew->size = needle - str_start;\n\t\t\t\tnew->ordinal = count++;\n\t\t\t\t\/\/ TODO: move into adjust_offset\n\t\t\t\tswitch (str_type) {\n\t\t\t\tcase R_STRING_TYPE_WIDE:\n\t\t\t\t\t{\n\t\t\t\t\t\tconst ut8 *p = buf + str_start - 2;\n\t\t\t\t\t\tif (p[0] == 0xff && p[1] == 0xfe) {\n\t\t\t\t\t\t\tstr_start -= 2; \/\/ \\xff\\xfe\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase R_STRING_TYPE_WIDE32:\n\t\t\t\t\t{\n\t\t\t\t\t\tconst ut8 *p = buf + str_start - 4;\n\t\t\t\t\t\tif (p[0] == 0xff && p[1] == 0xfe) {\n\t\t\t\t\t\t\tstr_start -= 4; \/\/ \\xff\\xfe\\x00\\x00\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tnew->paddr = new->vaddr = str_start;\n\t\t\t\tnew->string = r_str_ndup ((const char *)tmp, i);\n\t\t\t\tr_list_append (list, new);\n\t\t\t} else {\n\t\t\t\t\/\/ DUMP TO STDOUT. raw dumping for rabin2 -zzz\n\t\t\t\tprintf (\"0x%08\" PFMT64x \" %s\\n\", str_start, tmp);\n\t\t\t}\n\t\t}\n\t}\n\treturn count;\n}","target":1,"code_token_length":1244,"total_token_length":1575,"max_tokens_setting":2048} +{"idx":331286,"func":"static int local_symlink(FsContext *fs_ctx, const char *oldpath,\n\n V9fsPath *dir_path, const char *name, FsCred *credp)\n\n{\n\n int err = -1;\n\n int serrno = 0;\n\n char *newpath;\n\n V9fsString fullname;\n\n char *buffer;\n\n\n\n v9fs_string_init(&fullname);\n\n v9fs_string_sprintf(&fullname, \"%s\/%s\", dir_path->data, name);\n\n newpath = fullname.data;\n\n\n\n \/* Determine the security model *\/\n\n if (fs_ctx->export_flags & V9FS_SM_MAPPED) {\n\n int fd;\n\n ssize_t oldpath_size, write_size;\n\n buffer = rpath(fs_ctx, newpath);\n\n fd = open(buffer, O_CREAT|O_EXCL|O_RDWR|O_NOFOLLOW, SM_LOCAL_MODE_BITS);\n\n if (fd == -1) {\n\n g_free(buffer);\n\n err = fd;\n\n goto out;\n\n }\n\n \/* Write the oldpath (target) to the file. *\/\n\n oldpath_size = strlen(oldpath);\n\n do {\n\n write_size = write(fd, (void *)oldpath, oldpath_size);\n\n } while (write_size == -1 && errno == EINTR);\n\n\n\n if (write_size != oldpath_size) {\n\n serrno = errno;\n\n close(fd);\n\n err = -1;\n\n goto err_end;\n\n }\n\n close(fd);\n\n \/* Set cleint credentials in symlink's xattr *\/\n\n credp->fc_mode = credp->fc_mode|S_IFLNK;\n\n err = local_set_xattr(buffer, credp);\n\n if (err == -1) {\n\n serrno = errno;\n\n goto err_end;\n\n }\n\n } else if (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE) {\n\n int fd;\n\n ssize_t oldpath_size, write_size;\n\n buffer = rpath(fs_ctx, newpath);\n\n fd = open(buffer, O_CREAT|O_EXCL|O_RDWR|O_NOFOLLOW, SM_LOCAL_MODE_BITS);\n\n if (fd == -1) {\n\n g_free(buffer);\n\n err = fd;\n\n goto out;\n\n }\n\n \/* Write the oldpath (target) to the file. *\/\n\n oldpath_size = strlen(oldpath);\n\n do {\n\n write_size = write(fd, (void *)oldpath, oldpath_size);\n\n } while (write_size == -1 && errno == EINTR);\n\n\n\n if (write_size != oldpath_size) {\n\n serrno = errno;\n\n close(fd);\n\n err = -1;\n\n goto err_end;\n\n }\n\n close(fd);\n\n \/* Set cleint credentials in symlink's xattr *\/\n\n credp->fc_mode = credp->fc_mode|S_IFLNK;\n\n err = local_set_mapped_file_attr(fs_ctx, newpath, credp);\n\n if (err == -1) {\n\n serrno = errno;\n\n goto err_end;\n\n }\n\n } else if ((fs_ctx->export_flags & V9FS_SM_PASSTHROUGH) ||\n\n (fs_ctx->export_flags & V9FS_SM_NONE)) {\n\n buffer = rpath(fs_ctx, newpath);\n\n err = symlink(oldpath, buffer);\n\n if (err) {\n\n g_free(buffer);\n\n goto out;\n\n }\n\n err = lchown(buffer, credp->fc_uid, credp->fc_gid);\n\n if (err == -1) {\n\n \/*\n\n * If we fail to change ownership and if we are\n\n * using security model none. Ignore the error\n\n *\/\n\n if ((fs_ctx->export_flags & V9FS_SEC_MASK) != V9FS_SM_NONE) {\n\n serrno = errno;\n\n goto err_end;\n\n } else\n\n err = 0;\n\n }\n\n }\n\n goto out;\n\n\n\nerr_end:\n\n remove(buffer);\n\n errno = serrno;\n\n g_free(buffer);\n\nout:\n\n v9fs_string_free(&fullname);\n\n return err;\n\n}\n","target":1,"code_token_length":852,"total_token_length":1183,"max_tokens_setting":2048} +{"idx":298120,"func":"static void resolve_stun_entry(pjsua_stun_resolve *sess)\n{\n pj_status_t status = PJ_EUNKNOWN;\n\n \/* Loop while we have entry to try *\/\n for (; sess->idx < sess->count;\n \t (pjsua_var.ua_cfg.stun_try_ipv6 && sess->af == pj_AF_INET())?\n\t sess->af = pj_AF_INET6(): (++sess->idx, sess->af = pj_AF_INET()))\n {\n\tint af;\n\tchar target[64];\n\tpj_str_t hostpart;\n\tpj_uint16_t port;\n\tpj_stun_sock_cb stun_sock_cb;\n\t\n\tpj_assert(sess->idx < sess->count);\n\n\tif (pjsua_var.ua_cfg.stun_try_ipv6 &&\n\t pjsua_var.stun_opt != PJSUA_NAT64_DISABLED &&\n\t sess->af == pj_AF_INET())\n\t{\n\t \/* Skip IPv4 STUN resolution if NAT64 is not disabled. *\/\n\t PJ_LOG(4,(THIS_FILE, \"Skipping IPv4 resolution of STUN server \"\n\t \t\t\t \"%s (%d of %d)\", target,\n\t \t\t\t sess->idx+1, sess->count));\t \n\t continue;\n\t}\n\n\tpj_ansi_snprintf(target, sizeof(target), \"%.*s\",\n\t\t\t (int)sess->srv[sess->idx].slen,\n\t\t\t sess->srv[sess->idx].ptr);\n\n\t\/* Parse the server entry into host:port *\/\n\tstatus = pj_sockaddr_parse2(pj_AF_UNSPEC(), 0, &sess->srv[sess->idx],\n\t\t\t\t &hostpart, &port, &af);\n\tif (status != PJ_SUCCESS) {\n \t PJ_LOG(2,(THIS_FILE, \"Invalid STUN server entry %s\", target));\n\t continue;\n\t}\n\t\n\t\/* Use default port if not specified *\/\n\tif (port == 0)\n\t port = PJ_STUN_PORT;\n\n\tpj_assert(sess->stun_sock == NULL);\n\n\tPJ_LOG(4,(THIS_FILE, \"Trying STUN server %s %s (%d of %d)..\",\n\t\t target, (sess->af == pj_AF_INET()? \"IPv4\": \"IPv6\"),\n\t\t sess->idx+1, sess->count));\n\n\t\/* Use STUN_sock to test this entry *\/\n\tpj_bzero(&stun_sock_cb, sizeof(stun_sock_cb));\n\tstun_sock_cb.on_status = &test_stun_on_status;\n\tsess->async_wait = PJ_FALSE;\n\tstatus = pj_stun_sock_create(&pjsua_var.stun_cfg, \"stunresolve\",\n\t\t\t\t sess->af, &stun_sock_cb,\n\t\t\t\t NULL, sess, &sess->stun_sock);\n\tif (status != PJ_SUCCESS) {\n\t char errmsg[PJ_ERR_MSG_SIZE];\n\t pj_strerror(status, errmsg, sizeof(errmsg));\n\t PJ_LOG(4,(THIS_FILE, \n\t\t \"Error creating STUN socket for %s: %s\",\n\t\t target, errmsg));\n\n\t continue;\n\t}\n\n\tstatus = pj_stun_sock_start(sess->stun_sock, &hostpart, port,\n\t\t\t\t pjsua_var.resolver);\n\tif (status != PJ_SUCCESS) {\n\t char errmsg[PJ_ERR_MSG_SIZE];\n\t pj_strerror(status, errmsg, sizeof(errmsg));\n\t PJ_LOG(4,(THIS_FILE, \n\t\t \"Error starting STUN socket for %s: %s\",\n\t\t target, errmsg));\n\n\t if (sess->stun_sock) {\n\t\tpj_stun_sock_destroy(sess->stun_sock);\n\t\tsess->stun_sock = NULL;\n\t }\n\t continue;\n\t}\n\n\t\/* Done for now, testing will resume\/complete asynchronously in\n\t * stun_sock_cb()\n\t *\/\n\tsess->async_wait = PJ_TRUE;\n\treturn;\n }\n\n if (sess->idx >= sess->count) {\n\t\/* No more entries to try *\/\n\tstun_resolve_add_ref(sess);\n\tpj_assert(status != PJ_SUCCESS || sess->status != PJ_EPENDING);\n if (sess->status == PJ_EPENDING)\n sess->status = status;\n\tstun_resolve_complete(sess);\n\tstun_resolve_dec_ref(sess);\n }\n}","target":0,"code_token_length":854,"total_token_length":1185,"max_tokens_setting":2048} +{"idx":277832,"func":"static Image *ReadWEBPImage(const ImageInfo *image_info,\n ExceptionInfo *exception)\n{\n Image\n *image;\n\n int\n webp_status;\n\n MagickBooleanType\n status;\n\n register unsigned char\n *p;\n\n size_t\n length;\n\n ssize_t\n count,\n y;\n\n unsigned char\n header[12],\n *stream;\n\n WebPDecoderConfig\n configure;\n\n WebPDecBuffer\n *restrict webp_image = &configure.output;\n\n WebPBitstreamFeatures\n *restrict features = &configure.input;\n\n \/*\n Open image file.\n *\/\n assert(image_info != (const ImageInfo *) NULL);\n assert(image_info->signature == MagickSignature);\n if (image_info->debug != MagickFalse)\n (void) LogMagickEvent(TraceEvent,GetMagickModule(),\"%s\",\n image_info->filename);\n assert(exception != (ExceptionInfo *) NULL);\n assert(exception->signature == MagickSignature);\n image=AcquireImage(image_info);\n status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);\n if (status == MagickFalse)\n {\n image=DestroyImageList(image);\n return((Image *) NULL);\n }\n if (WebPInitDecoderConfig(&configure) == 0)\n ThrowReaderException(ResourceLimitError,\"UnableToDecodeImageFile\");\n webp_image->colorspace=MODE_RGBA;\n count=ReadBlob(image,12,header);\n if (count != 12)\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n status=IsWEBP(header,count);\n if (status == MagickFalse)\n ThrowReaderException(CorruptImageError,\"CorruptImage\");\n length=(size_t) (ReadWebPLSBWord(header+4)+8);\n if (length < 12)\n ThrowReaderException(CorruptImageError,\"CorruptImage\");\n stream=(unsigned char *) AcquireQuantumMemory(length,sizeof(*stream));\n if (stream == (unsigned char *) NULL)\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n (void) memcpy(stream,header,12);\n count=ReadBlob(image,length-12,stream+12);\n if (count != (ssize_t) (length-12))\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n webp_status=WebPGetFeatures(stream,length,features);\n if (webp_status == VP8_STATUS_OK)\n {\n image->columns=(size_t) features->width;\n image->rows=(size_t) features->height;\n image->depth=8;\n image->matte=features->has_alpha != 0 ? MagickTrue : MagickFalse;\n if (IsWEBPImageLossless(stream,length) != MagickFalse)\n image->quality=100;\n if (image_info->ping != MagickFalse)\n {\n stream=(unsigned char*) RelinquishMagickMemory(stream);\n (void) CloseBlob(image);\n return(GetFirstImageInList(image));\n }\n status=SetImageExtent(image,image->columns,image->rows);\n if (status == MagickFalse)\n {\n InheritException(exception,&image->exception);\n return(DestroyImageList(image));\n }\n webp_status=WebPDecode(stream,length,&configure);\n }\n if (webp_status != VP8_STATUS_OK)\n {\n stream=(unsigned char*) RelinquishMagickMemory(stream);\n switch (webp_status)\n {\n case VP8_STATUS_OUT_OF_MEMORY:\n {\n ThrowReaderException(ResourceLimitError,\"MemoryAllocationFailed\");\n break;\n }\n case VP8_STATUS_INVALID_PARAM:\n {\n ThrowReaderException(CorruptImageError,\"invalid parameter\");\n break;\n }\n case VP8_STATUS_BITSTREAM_ERROR:\n {\n ThrowReaderException(CorruptImageError,\"CorruptImage\");\n break;\n }\n case VP8_STATUS_UNSUPPORTED_FEATURE:\n {\n ThrowReaderException(CoderError,\"DataEncodingSchemeIsNotSupported\");\n break;\n }\n case VP8_STATUS_SUSPENDED:\n {\n ThrowReaderException(CorruptImageError,\"decoder suspended\");\n break;\n }\n case VP8_STATUS_USER_ABORT:\n {\n ThrowReaderException(CorruptImageError,\"user abort\");\n break;\n }\n case VP8_STATUS_NOT_ENOUGH_DATA:\n {\n ThrowReaderException(CorruptImageError,\"InsufficientImageDataInFile\");\n break;\n }\n default:\n ThrowReaderException(CorruptImageError,\"CorruptImage\");\n }\n }\n p=(unsigned char *) webp_image->u.RGBA.rgba;\n for (y=0; y < (ssize_t) image->rows; y++)\n {\n register PixelPacket\n *q;\n\n register ssize_t\n x;\n\n q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);\n if (q == (PixelPacket *) NULL)\n break;\n for (x=0; x < (ssize_t) image->columns; x++)\n {\n SetPixelRed(q,ScaleCharToQuantum(*p++));\n SetPixelGreen(q,ScaleCharToQuantum(*p++));\n SetPixelBlue(q,ScaleCharToQuantum(*p++));\n SetPixelAlpha(q,ScaleCharToQuantum(*p++));\n q++;\n }\n if (SyncAuthenticPixels(image,exception) == MagickFalse)\n break;\n status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,\n image->rows);\n if (status == MagickFalse)\n break;\n }\n WebPFreeDecBuffer(webp_image);\n stream=(unsigned char*) RelinquishMagickMemory(stream);\n return(image);\n}\n","target":0,"code_token_length":1243,"total_token_length":1574,"max_tokens_setting":2048} +{"idx":37997,"func":"static int h264_decode_frame(AVCodecContext *avctx, void *data,\n int *got_frame, AVPacket *avpkt)\n{\n const uint8_t *buf = avpkt->data;\n int buf_size = avpkt->size;\n H264Context *h = avctx->priv_data;\n AVFrame *pict = data;\n int buf_index = 0;\n H264Picture *out;\n int i, out_idx;\n int ret;\n\n h->flags = avctx->flags;\n \/* reset data partitioning here, to ensure GetBitContexts from previous\n * packets do not get used. *\/\n h->data_partitioning = 0;\n\n \/* end of stream, output what is still in the buffers *\/\n if (buf_size == 0) {\n out:\n\n h->cur_pic_ptr = NULL;\n h->first_field = 0;\n\n \/\/ FIXME factorize this with the output code below\n out = h->delayed_pic[0];\n out_idx = 0;\n for (i = 1;\n h->delayed_pic[i] &&\n !h->delayed_pic[i]->f.key_frame &&\n !h->delayed_pic[i]->mmco_reset;\n i++)\n if (h->delayed_pic[i]->poc < out->poc) {\n out = h->delayed_pic[i];\n out_idx = i;\n }\n\n for (i = out_idx; h->delayed_pic[i]; i++)\n h->delayed_pic[i] = h->delayed_pic[i + 1];\n\n if (out) {\n out->reference &= ~DELAYED_PIC_REF;\n ret = output_frame(h, pict, out);\n if (ret < 0)\n return ret;\n *got_frame = 1;\n }\n\n return buf_index;\n }\n if (h->is_avc && av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, NULL)) {\n int side_size;\n uint8_t *side = av_packet_get_side_data(avpkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);\n if (is_extra(side, side_size))\n ff_h264_decode_extradata(h, side, side_size);\n }\n if(h->is_avc && buf_size >= 9 && buf[0]==1 && buf[2]==0 && (buf[4]&0xFC)==0xFC && (buf[5]&0x1F) && buf[8]==0x67){\n if (is_extra(buf, buf_size))\n return ff_h264_decode_extradata(h, buf, buf_size);\n }\n\n buf_index = decode_nal_units(h, buf, buf_size, 0);\n if (buf_index < 0)\n return AVERROR_INVALIDDATA;\n\n if (!h->cur_pic_ptr && h->nal_unit_type == NAL_END_SEQUENCE) {\n av_assert0(buf_index <= buf_size);\n goto out;\n }\n\n if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) && !h->cur_pic_ptr) {\n if (avctx->skip_frame >= AVDISCARD_NONREF ||\n buf_size >= 4 && !memcmp(\"Q264\", buf, 4))\n return buf_size;\n av_log(avctx, AV_LOG_ERROR, \"no frame!\\n\");\n return AVERROR_INVALIDDATA;\n }\n\n if (!(avctx->flags2 & CODEC_FLAG2_CHUNKS) ||\n (h->mb_y >= h->mb_height && h->mb_height)) {\n if (avctx->flags2 & CODEC_FLAG2_CHUNKS)\n decode_postinit(h, 1);\n\n ff_h264_field_end(h, 0);\n\n \/* Wait for second field. *\/\n *got_frame = 0;\n if (h->next_output_pic && (\n h->next_output_pic->recovered)) {\n if (!h->next_output_pic->recovered)\n h->next_output_pic->f.flags |= AV_FRAME_FLAG_CORRUPT;\n\n ret = output_frame(h, pict, h->next_output_pic);\n if (ret < 0)\n return ret;\n *got_frame = 1;\n if (CONFIG_MPEGVIDEO) {\n ff_print_debug_info2(h->avctx, pict, h->er.mbskip_table,\n h->next_output_pic->mb_type,\n h->next_output_pic->qscale_table,\n h->next_output_pic->motion_val,\n &h->low_delay,\n h->mb_width, h->mb_height, h->mb_stride, 1);\n }\n }\n }\n\n assert(pict->buf[0] || !*got_frame);\n\n return get_consumed_bytes(buf_index, buf_size);\n}","target":0,"code_token_length":1044,"total_token_length":1375,"max_tokens_setting":2048} +{"idx":371706,"func":"_archive_entry_copy_file_info (struct archive_entry *entry,\n\t\t\t GFileInfo *info,\n\t\t\t SaveData *save_data)\n{\n\tint filetype;\n\tchar *username;\n\tchar *groupname;\n\tgint64 id;\n\n\tswitch (g_file_info_get_file_type (info)) {\n\tcase G_FILE_TYPE_REGULAR:\n\t\tfiletype = AE_IFREG;\n\t\tbreak;\n\tcase G_FILE_TYPE_DIRECTORY:\n\t\tfiletype = AE_IFDIR;\n\t\tbreak;\n\tcase G_FILE_TYPE_SYMBOLIC_LINK:\n\t\tfiletype = AE_IFLNK;\n\t\tbreak;\n\tdefault:\n\t\treturn FALSE;\n\t\tbreak;\n\t}\n\tarchive_entry_set_filetype (entry, filetype);\n\n\tarchive_entry_set_atime (entry,\n\t\t\t\t g_file_info_get_attribute_uint64 (info, G_FILE_ATTRIBUTE_TIME_ACCESS),\n\t\t\t\t g_file_info_get_attribute_uint32 (info, G_FILE_ATTRIBUTE_TIME_ACCESS_USEC) * 1000);\n\tarchive_entry_set_ctime (entry,\n\t\t\t\t g_file_info_get_attribute_uint64 (info, G_FILE_ATTRIBUTE_TIME_CREATED),\n\t\t\t\t g_file_info_get_attribute_uint32 (info, G_FILE_ATTRIBUTE_TIME_CREATED_USEC) * 1000);\n\tarchive_entry_set_mtime (entry,\n\t\t\t\t g_file_info_get_attribute_uint64 (info, G_FILE_ATTRIBUTE_TIME_MODIFIED),\n\t\t\t\t g_file_info_get_attribute_uint32 (info, G_FILE_ATTRIBUTE_TIME_MODIFIED_USEC) * 1000);\n\tarchive_entry_unset_birthtime (entry);\n\tarchive_entry_set_dev (entry, g_file_info_get_attribute_uint32 (info, G_FILE_ATTRIBUTE_UNIX_DEVICE));\n\tarchive_entry_set_gid (entry, g_file_info_get_attribute_uint32 (info, G_FILE_ATTRIBUTE_UNIX_GID));\n\tarchive_entry_set_uid (entry, g_file_info_get_attribute_uint32 (info, G_FILE_ATTRIBUTE_UNIX_UID));\n\tarchive_entry_set_ino64 (entry, g_file_info_get_attribute_uint64 (info, G_FILE_ATTRIBUTE_UNIX_INODE));\n\tarchive_entry_set_mode (entry, g_file_info_get_attribute_uint32 (info, G_FILE_ATTRIBUTE_UNIX_MODE));\n\tarchive_entry_set_nlink (entry, g_file_info_get_attribute_uint32 (info, G_FILE_ATTRIBUTE_UNIX_NLINK));\n\tarchive_entry_set_rdev (entry, g_file_info_get_attribute_uint32 (info, G_FILE_ATTRIBUTE_UNIX_RDEV));\n\tarchive_entry_set_size (entry, g_file_info_get_attribute_uint64 (info, G_FILE_ATTRIBUTE_STANDARD_SIZE));\n\tif (filetype == AE_IFLNK)\n\t\tarchive_entry_set_symlink (entry, g_file_info_get_attribute_byte_string (info, G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET));\n\n\t\/* username *\/\n\n\tid = archive_entry_uid (entry);\n\tusername = g_hash_table_lookup (save_data->usernames, &id);\n\tif (username == NULL) {\n\t\tstruct passwd *pwd = getpwuid (id);\n\t\tif (pwd != NULL) {\n\t\t\tusername = g_strdup (pwd->pw_name);\n\t\t\tg_hash_table_insert (save_data->usernames, _g_int64_pointer_new (id), username);\n\t\t}\n\t}\n\tif (username != NULL)\n\t\tarchive_entry_set_uname (entry, username);\n\n\t\/* groupname *\/\n\n\tid = archive_entry_gid (entry);\n\tgroupname = g_hash_table_lookup (save_data->groupnames, &id);\n\tif (groupname == NULL) {\n\t\tstruct group *grp = getgrgid (id);\n\t\tif (grp != NULL) {\n\t\t\tgroupname = g_strdup (grp->gr_name);\n\t\t\tg_hash_table_insert (save_data->groupnames, _g_int64_pointer_new (id), groupname);\n\t\t}\n\t}\n\tif (groupname != NULL)\n\t\tarchive_entry_set_gname (entry, groupname);\n\n\treturn TRUE;\n}","target":0,"code_token_length":795,"total_token_length":1126,"max_tokens_setting":2048} +{"idx":419550,"func":"int sa_open_read_magic(int *fd, char *dfile, struct file_magic *file_magic,\n\t\t int ignore, int *endian_mismatch, int do_swap)\n{\n\tint n;\n\tunsigned int fm_types_nr[] = {FILE_MAGIC_ULL_NR, FILE_MAGIC_UL_NR, FILE_MAGIC_U_NR};\n\n\t\/* Open sa data file *\/\n\tif ((*fd = open(dfile, O_RDONLY)) < 0) {\n\t\tint saved_errno = errno;\n\n\t\tfprintf(stderr, _(\"Cannot open %s: %s\\n\"), dfile, strerror(errno));\n\n\t\tif ((saved_errno == ENOENT) && default_file_used) {\n\t\t\tfprintf(stderr, _(\"Please check if data collecting is enabled\\n\"));\n\t\t}\n\t\texit(2);\n\t}\n\n\t\/* Read file magic data *\/\n\tn = read(*fd, file_magic, FILE_MAGIC_SIZE);\n\n\tif ((n != FILE_MAGIC_SIZE) ||\n\t ((file_magic->sysstat_magic != SYSSTAT_MAGIC) && (file_magic->sysstat_magic != SYSSTAT_MAGIC_SWAPPED)) ||\n\t ((file_magic->format_magic != FORMAT_MAGIC) && (file_magic->format_magic != FORMAT_MAGIC_SWAPPED) && !ignore)) {\n#ifdef DEBUG\n\t\tfprintf(stderr, \"%s: Bytes read=%d sysstat_magic=%x format_magic=%x\\n\",\n\t\t\t__FUNCTION__, n, file_magic->sysstat_magic, file_magic->format_magic);\n#endif\n\t\t\/* Display error message and exit *\/\n\t\thandle_invalid_sa_file(*fd, file_magic, dfile, n);\n\t}\n\n\t*endian_mismatch = (file_magic->sysstat_magic != SYSSTAT_MAGIC);\n\tif (*endian_mismatch) {\n\t\tif (do_swap) {\n\t\t\t\/* Swap bytes for file_magic fields *\/\n\t\t\tfile_magic->sysstat_magic = SYSSTAT_MAGIC;\n\t\t\tfile_magic->format_magic = __builtin_bswap16(file_magic->format_magic);\n\t\t}\n\t\t\/*\n\t\t * Start swapping at field \"header_size\" position.\n\t\t * May not exist for older versions but in this case, it won't be used.\n\t\t *\/\n\t\tswap_struct(fm_types_nr, &file_magic->header_size, 0);\n\t}\n\n\tif ((file_magic->sysstat_version > 10) ||\n\t ((file_magic->sysstat_version == 10) && (file_magic->sysstat_patchlevel >= 3))) {\n\t\t\/* header_size field exists only for sysstat versions 10.3.1 and later *\/\n\t\tif ((file_magic->header_size <= MIN_FILE_HEADER_SIZE) ||\n\t\t (file_magic->header_size > MAX_FILE_HEADER_SIZE) ||\n\t\t ((file_magic->header_size < FILE_HEADER_SIZE) && !ignore)) {\n#ifdef DEBUG\n\t\t\tfprintf(stderr, \"%s: header_size=%u\\n\",\n\t\t\t\t__FUNCTION__, file_magic->header_size);\n#endif\n\t\t\t\/* Display error message and exit *\/\n\t\t\thandle_invalid_sa_file(*fd, file_magic, dfile, n);\n\t\t}\n\t}\n\tif ((file_magic->sysstat_version > 11) ||\n\t ((file_magic->sysstat_version == 11) && (file_magic->sysstat_patchlevel >= 7))) {\n\t\t\/* hdr_types_nr field exists only for sysstat versions 11.7.1 and later *\/\n\t\tif (MAP_SIZE(file_magic->hdr_types_nr) > file_magic->header_size) {\n#ifdef DEBUG\n\t\t\tfprintf(stderr, \"%s: map_size=%u header_size=%u\\n\",\n\t\t\t\t__FUNCTION__, MAP_SIZE(file_magic->hdr_types_nr), file_magic->header_size);\n#endif\n\t\t\thandle_invalid_sa_file(*fd, file_magic, dfile, n);\n\t\t}\n\t}\n\n\tif ((file_magic->format_magic != FORMAT_MAGIC) &&\n\t (file_magic->format_magic != FORMAT_MAGIC_SWAPPED))\n\t\t\/*\n\t\t * This is an old (or new) sa datafile format to\n\t\t * be read by sadf (since @ignore was set to TRUE).\n\t\t *\/\n\t\treturn -1;\n\n\treturn 0;\n}","target":0,"code_token_length":837,"total_token_length":1168,"max_tokens_setting":2048} +{"idx":7914,"func":"static PyObject *__pyx_pw_17clickhouse_driver_6varint_1write_varint(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {\n Py_ssize_t __pyx_v_number;\n PyObject *__pyx_v_buf = 0;\n PyObject *__pyx_r = 0;\n __Pyx_RefNannyDeclarations\n __Pyx_RefNannySetupContext(\"write_varint (wrapper)\", 0);\n {\n static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_number,&__pyx_n_s_buf,0};\n PyObject* values[2] = {0,0};\n if (unlikely(__pyx_kwds)) {\n Py_ssize_t kw_args;\n const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args);\n switch (pos_args) {\n case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);\n CYTHON_FALLTHROUGH;\n case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);\n CYTHON_FALLTHROUGH;\n case 0: break;\n default: goto __pyx_L5_argtuple_error;\n }\n kw_args = PyDict_Size(__pyx_kwds);\n switch (pos_args) {\n case 0:\n if (likely((values[0] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_number)) != 0)) kw_args--;\n else goto __pyx_L5_argtuple_error;\n CYTHON_FALLTHROUGH;\n case 1:\n if (likely((values[1] = __Pyx_PyDict_GetItemStr(__pyx_kwds, __pyx_n_s_buf)) != 0)) kw_args--;\n else {\n __Pyx_RaiseArgtupleInvalid(\"write_varint\", 1, 2, 2, 1); __PYX_ERR(0, 4, __pyx_L3_error)\n }\n }\n if (unlikely(kw_args > 0)) {\n if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, \"write_varint\") < 0)) __PYX_ERR(0, 4, __pyx_L3_error)\n }\n } else if (PyTuple_GET_SIZE(__pyx_args) != 2) {\n goto __pyx_L5_argtuple_error;\n } else {\n values[0] = PyTuple_GET_ITEM(__pyx_args, 0);\n values[1] = PyTuple_GET_ITEM(__pyx_args, 1);\n }\n __pyx_v_number = __Pyx_PyIndex_AsSsize_t(values[0]); if (unlikely((__pyx_v_number == (Py_ssize_t)-1) && PyErr_Occurred())) __PYX_ERR(0, 4, __pyx_L3_error)\n __pyx_v_buf = values[1];\n }\n goto __pyx_L4_argument_unpacking_done;\n __pyx_L5_argtuple_error:;\n __Pyx_RaiseArgtupleInvalid(\"write_varint\", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 4, __pyx_L3_error)\n __pyx_L3_error:;\n __Pyx_AddTraceback(\"clickhouse_driver.varint.write_varint\", __pyx_clineno, __pyx_lineno, __pyx_filename);\n __Pyx_RefNannyFinishContext();\n return NULL;\n __pyx_L4_argument_unpacking_done:;\n __pyx_r = __pyx_pf_17clickhouse_driver_6varint_write_varint(__pyx_self, __pyx_v_number, __pyx_v_buf);\n\n \/* function exit code *\/\n __Pyx_RefNannyFinishContext();\n return __pyx_r;\n}","target":1,"code_token_length":819,"total_token_length":1150,"max_tokens_setting":2048} +{"idx":414405,"func":"static void findHotKeys(void) {\n redisReply *keys, *reply;\n unsigned long long counters[HOTKEYS_SAMPLE] = {0};\n sds hotkeys[HOTKEYS_SAMPLE] = {NULL};\n unsigned long long sampled = 0, total_keys, *freqs = NULL, it = 0;\n unsigned int arrsize = 0, i, k;\n double pct;\n\n \/* Total keys pre scanning *\/\n total_keys = getDbSize();\n\n \/* Status message *\/\n printf(\"\\n# Scanning the entire keyspace to find hot keys as well as\\n\");\n printf(\"# average sizes per key type. You can use -i 0.1 to sleep 0.1 sec\\n\");\n printf(\"# per 100 SCAN commands (not usually needed).\\n\\n\");\n\n \/* SCAN loop *\/\n do {\n \/* Calculate approximate percentage completion *\/\n pct = 100 * (double)sampled\/total_keys;\n\n \/* Grab some keys and point to the keys array *\/\n reply = sendScan(&it);\n keys = reply->element[1];\n\n \/* Reallocate our freqs array if we need to *\/\n if(keys->elements > arrsize) {\n freqs = zrealloc(freqs, sizeof(unsigned long long)*keys->elements);\n\n if(!freqs) {\n fprintf(stderr, \"Failed to allocate storage for keys!\\n\");\n exit(1);\n }\n\n arrsize = keys->elements;\n }\n\n getKeyFreqs(keys, freqs);\n\n \/* Now update our stats *\/\n for(i=0;ielements;i++) {\n sampled++;\n \/* Update overall progress *\/\n if(sampled % 1000000 == 0) {\n printf(\"[%05.2f%%] Sampled %llu keys so far\\n\", pct, sampled);\n }\n\n \/* Use eviction pool here *\/\n k = 0;\n while (k < HOTKEYS_SAMPLE && freqs[i] > counters[k]) k++;\n if (k == 0) continue;\n k--;\n if (k == 0 || counters[k] == 0) {\n sdsfree(hotkeys[k]);\n } else {\n sdsfree(hotkeys[0]);\n memmove(counters,counters+1,sizeof(counters[0])*k);\n memmove(hotkeys,hotkeys+1,sizeof(hotkeys[0])*k);\n }\n counters[k] = freqs[i];\n hotkeys[k] = sdsnew(keys->element[i]->str);\n printf(\n \"[%05.2f%%] Hot key '%s' found so far with counter %llu\\n\",\n pct, keys->element[i]->str, freqs[i]);\n }\n\n \/* Sleep if we've been directed to do so *\/\n if(sampled && (sampled %100) == 0 && config.interval) {\n usleep(config.interval);\n }\n\n freeReplyObject(reply);\n } while(it != 0);\n\n if (freqs) zfree(freqs);\n\n \/* We're done *\/\n printf(\"\\n-------- summary -------\\n\\n\");\n\n printf(\"Sampled %llu keys in the keyspace!\\n\", sampled);\n\n for (i=1; i<= HOTKEYS_SAMPLE; i++) {\n k = HOTKEYS_SAMPLE - i;\n if(counters[k]>0) {\n printf(\"hot key found with counter: %llu\\tkeyname: %s\\n\", counters[k], hotkeys[k]);\n sdsfree(hotkeys[k]);\n }\n }\n\n exit(0);\n}","target":0,"code_token_length":767,"total_token_length":1098,"max_tokens_setting":2048} +{"idx":331308,"func":"static void rtsp_cmd_setup(HTTPContext *c, const char *url,\n\n RTSPHeader *h)\n\n{\n\n FFStream *stream;\n\n int stream_index, port;\n\n char buf[1024];\n\n char path1[1024];\n\n const char *path;\n\n HTTPContext *rtp_c;\n\n RTSPTransportField *th;\n\n struct sockaddr_in dest_addr;\n\n RTSPActionServerSetup setup;\n\n\n\n \/* find which url is asked *\/\n\n url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);\n\n path = path1;\n\n if (*path == '\/')\n\n path++;\n\n\n\n \/* now check each stream *\/\n\n for(stream = first_stream; stream != NULL; stream = stream->next) {\n\n if (!stream->is_feed && !strcmp(stream->fmt->name, \"rtp\")) {\n\n \/* accept aggregate filenames only if single stream *\/\n\n if (!strcmp(path, stream->filename)) {\n\n if (stream->nb_streams != 1) {\n\n rtsp_reply_error(c, RTSP_STATUS_AGGREGATE);\n\n return;\n\n }\n\n stream_index = 0;\n\n goto found;\n\n }\n\n\n\n for(stream_index = 0; stream_index < stream->nb_streams;\n\n stream_index++) {\n\n snprintf(buf, sizeof(buf), \"%s\/streamid=%d\",\n\n stream->filename, stream_index);\n\n if (!strcmp(path, buf))\n\n goto found;\n\n }\n\n }\n\n }\n\n \/* no stream found *\/\n\n rtsp_reply_error(c, RTSP_STATUS_SERVICE); \/* XXX: right error ? *\/\n\n return;\n\n found:\n\n\n\n \/* generate session id if needed *\/\n\n if (h->session_id[0] == '\\0')\n\n snprintf(h->session_id, sizeof(h->session_id), \"%08x%08x\",\n\n av_random(&random_state), av_random(&random_state));\n\n\n\n \/* find rtp session, and create it if none found *\/\n\n rtp_c = find_rtp_session(h->session_id);\n\n if (!rtp_c) {\n\n \/* always prefer UDP *\/\n\n th = find_transport(h, RTSP_PROTOCOL_RTP_UDP);\n\n if (!th) {\n\n th = find_transport(h, RTSP_PROTOCOL_RTP_TCP);\n\n if (!th) {\n\n rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);\n\n return;\n\n }\n\n }\n\n\n\n rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id,\n\n th->protocol);\n\n if (!rtp_c) {\n\n rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH);\n\n return;\n\n }\n\n\n\n \/* open input stream *\/\n\n if (open_input_stream(rtp_c, \"\") < 0) {\n\n rtsp_reply_error(c, RTSP_STATUS_INTERNAL);\n\n return;\n\n }\n\n }\n\n\n\n \/* test if stream is OK (test needed because several SETUP needs\n\n to be done for a given file) *\/\n\n if (rtp_c->stream != stream) {\n\n rtsp_reply_error(c, RTSP_STATUS_SERVICE);\n\n return;\n\n }\n\n\n\n \/* test if stream is already set up *\/\n\n if (rtp_c->rtp_ctx[stream_index]) {\n\n rtsp_reply_error(c, RTSP_STATUS_STATE);\n\n return;\n\n }\n\n\n\n \/* check transport *\/\n\n th = find_transport(h, rtp_c->rtp_protocol);\n\n if (!th || (th->protocol == RTSP_PROTOCOL_RTP_UDP &&\n\n th->client_port_min <= 0)) {\n\n rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);\n\n return;\n\n }\n\n\n\n \/* setup default options *\/\n\n setup.transport_option[0] = '\\0';\n\n dest_addr = rtp_c->from_addr;\n\n dest_addr.sin_port = htons(th->client_port_min);\n\n\n\n \/* setup stream *\/\n\n if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) {\n\n rtsp_reply_error(c, RTSP_STATUS_TRANSPORT);\n\n return;\n\n }\n\n\n\n \/* now everything is OK, so we can send the connection parameters *\/\n\n rtsp_reply_header(c, RTSP_STATUS_OK);\n\n \/* session ID *\/\n\n url_fprintf(c->pb, \"Session: %s\\r\\n\", rtp_c->session_id);\n\n\n\n switch(rtp_c->rtp_protocol) {\n\n case RTSP_PROTOCOL_RTP_UDP:\n\n port = rtp_get_local_port(rtp_c->rtp_handles[stream_index]);\n\n url_fprintf(c->pb, \"Transport: RTP\/AVP\/UDP;unicast;\"\n\n \"client_port=%d-%d;server_port=%d-%d\",\n\n th->client_port_min, th->client_port_min + 1,\n\n port, port + 1);\n\n break;\n\n case RTSP_PROTOCOL_RTP_TCP:\n\n url_fprintf(c->pb, \"Transport: RTP\/AVP\/TCP;interleaved=%d-%d\",\n\n stream_index * 2, stream_index * 2 + 1);\n\n break;\n\n default:\n\n break;\n\n }\n\n if (setup.transport_option[0] != '\\0')\n\n url_fprintf(c->pb, \";%s\", setup.transport_option);\n\n url_fprintf(c->pb, \"\\r\\n\");\n\n\n\n\n\n url_fprintf(c->pb, \"\\r\\n\");\n\n}\n","target":1,"code_token_length":1134,"total_token_length":1465,"max_tokens_setting":2048} +{"idx":338151,"func":"static void process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eof)\n\n{\n\n int i;\n\n int repeating = 0;\n\n AVPacket avpkt;\n\n\n\n if (ist->next_dts == AV_NOPTS_VALUE)\n\n ist->next_dts = ist->last_dts;\n\n\n\n if (!pkt) {\n\n \/* EOF handling *\/\n\n av_init_packet(&avpkt);\n\n avpkt.data = NULL;\n\n avpkt.size = 0;\n\n } else {\n\n avpkt = *pkt;\n\n }\n\n\n\n if (pkt && pkt->dts != AV_NOPTS_VALUE)\n\n ist->next_dts = ist->last_dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);\n\n\n\n \/\/ while we have more to decode or while the decoder did output something on EOF\n\n while (ist->decoding_needed && (!pkt || avpkt.size > 0)) {\n\n int ret = 0;\n\n int got_output = 0;\n\n\n\n if (!repeating)\n\n ist->last_dts = ist->next_dts;\n\n\n\n switch (ist->dec_ctx->codec_type) {\n\n case AVMEDIA_TYPE_AUDIO:\n\n ret = decode_audio (ist, repeating ? NULL : &avpkt, &got_output);\n\n break;\n\n case AVMEDIA_TYPE_VIDEO:\n\n ret = decode_video (ist, repeating ? NULL : &avpkt, &got_output);\n\n if (repeating && !got_output)\n\n ;\n\n else if (pkt && pkt->duration)\n\n ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);\n\n else if (ist->st->avg_frame_rate.num)\n\n ist->next_dts += av_rescale_q(1, av_inv_q(ist->st->avg_frame_rate),\n\n AV_TIME_BASE_Q);\n\n else if (ist->dec_ctx->framerate.num != 0) {\n\n int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 :\n\n ist->dec_ctx->ticks_per_frame;\n\n ist->next_dts += av_rescale_q(ticks, ist->dec_ctx->framerate, AV_TIME_BASE_Q);\n\n }\n\n break;\n\n case AVMEDIA_TYPE_SUBTITLE:\n\n if (repeating)\n\n break;\n\n ret = transcode_subtitles(ist, &avpkt, &got_output);\n\n break;\n\n default:\n\n return;\n\n }\n\n\n\n if (ret < 0) {\n\n av_log(NULL, AV_LOG_ERROR, \"Error while decoding stream #%d:%d\\n\",\n\n ist->file_index, ist->st->index);\n\n if (exit_on_error)\n\n exit_program(1);\n\n break;\n\n }\n\n\n\n if (!got_output)\n\n break;\n\n\n\n repeating = 1;\n\n }\n\n\n\n \/* after flushing, send an EOF on all the filter inputs attached to the stream *\/\n\n \/* except when looping we need to flush but not to send an EOF *\/\n\n if (!pkt && ist->decoding_needed && !no_eof) {\n\n int ret = send_filter_eof(ist);\n\n if (ret < 0) {\n\n av_log(NULL, AV_LOG_FATAL, \"Error marking filters as finished\\n\");\n\n exit_program(1);\n\n }\n\n }\n\n\n\n \/* handle stream copy *\/\n\n if (!ist->decoding_needed) {\n\n ist->last_dts = ist->next_dts;\n\n switch (ist->dec_ctx->codec_type) {\n\n case AVMEDIA_TYPE_AUDIO:\n\n ist->next_dts += ((int64_t)AV_TIME_BASE * ist->dec_ctx->frame_size) \/\n\n ist->dec_ctx->sample_rate;\n\n break;\n\n case AVMEDIA_TYPE_VIDEO:\n\n if (ist->dec_ctx->framerate.num != 0) {\n\n int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->dec_ctx->ticks_per_frame;\n\n ist->next_dts += ((int64_t)AV_TIME_BASE *\n\n ist->dec_ctx->framerate.den * ticks) \/\n\n ist->dec_ctx->framerate.num;\n\n }\n\n break;\n\n }\n\n }\n\n for (i = 0; pkt && i < nb_output_streams; i++) {\n\n OutputStream *ost = output_streams[i];\n\n\n\n if (!check_output_constraints(ist, ost) || ost->encoding_needed)\n\n continue;\n\n\n\n do_streamcopy(ist, ost, pkt);\n\n }\n\n\n\n return;\n\n}\n","target":1,"code_token_length":960,"total_token_length":1291,"max_tokens_setting":2048} +{"idx":362880,"func":"int sock_getsockopt(struct socket *sock, int level, int optname,\n\t\t char __user *optval, int __user *optlen)\n{\n\tstruct sock *sk = sock->sk;\n\n\tunion {\n\t\tint val;\n\t\tstruct linger ling;\n\t\tstruct timeval tm;\n\t} v;\n\n\tint lv = sizeof(int);\n\tint len;\n\n\tif (get_user(len, optlen))\n\t\treturn -EFAULT;\n\tif (len < 0)\n\t\treturn -EINVAL;\n\n\tmemset(&v, 0, sizeof(v));\n\n\tswitch (optname) {\n\tcase SO_DEBUG:\n\t\tv.val = sock_flag(sk, SOCK_DBG);\n\t\tbreak;\n\n\tcase SO_DONTROUTE:\n\t\tv.val = sock_flag(sk, SOCK_LOCALROUTE);\n\t\tbreak;\n\n\tcase SO_BROADCAST:\n\t\tv.val = !!sock_flag(sk, SOCK_BROADCAST);\n\t\tbreak;\n\n\tcase SO_SNDBUF:\n\t\tv.val = sk->sk_sndbuf;\n\t\tbreak;\n\n\tcase SO_RCVBUF:\n\t\tv.val = sk->sk_rcvbuf;\n\t\tbreak;\n\n\tcase SO_REUSEADDR:\n\t\tv.val = sk->sk_reuse;\n\t\tbreak;\n\n\tcase SO_KEEPALIVE:\n\t\tv.val = !!sock_flag(sk, SOCK_KEEPOPEN);\n\t\tbreak;\n\n\tcase SO_TYPE:\n\t\tv.val = sk->sk_type;\n\t\tbreak;\n\n\tcase SO_PROTOCOL:\n\t\tv.val = sk->sk_protocol;\n\t\tbreak;\n\n\tcase SO_DOMAIN:\n\t\tv.val = sk->sk_family;\n\t\tbreak;\n\n\tcase SO_ERROR:\n\t\tv.val = -sock_error(sk);\n\t\tif (v.val == 0)\n\t\t\tv.val = xchg(&sk->sk_err_soft, 0);\n\t\tbreak;\n\n\tcase SO_OOBINLINE:\n\t\tv.val = !!sock_flag(sk, SOCK_URGINLINE);\n\t\tbreak;\n\n\tcase SO_NO_CHECK:\n\t\tv.val = sk->sk_no_check;\n\t\tbreak;\n\n\tcase SO_PRIORITY:\n\t\tv.val = sk->sk_priority;\n\t\tbreak;\n\n\tcase SO_LINGER:\n\t\tlv\t\t= sizeof(v.ling);\n\t\tv.ling.l_onoff\t= !!sock_flag(sk, SOCK_LINGER);\n\t\tv.ling.l_linger\t= sk->sk_lingertime \/ HZ;\n\t\tbreak;\n\n\tcase SO_BSDCOMPAT:\n\t\tsock_warn_obsolete_bsdism(\"getsockopt\");\n\t\tbreak;\n\n\tcase SO_TIMESTAMP:\n\t\tv.val = sock_flag(sk, SOCK_RCVTSTAMP) &&\n\t\t\t\t!sock_flag(sk, SOCK_RCVTSTAMPNS);\n\t\tbreak;\n\n\tcase SO_TIMESTAMPNS:\n\t\tv.val = sock_flag(sk, SOCK_RCVTSTAMPNS);\n\t\tbreak;\n\n\tcase SO_TIMESTAMPING:\n\t\tv.val = 0;\n\t\tif (sock_flag(sk, SOCK_TIMESTAMPING_TX_HARDWARE))\n\t\t\tv.val |= SOF_TIMESTAMPING_TX_HARDWARE;\n\t\tif (sock_flag(sk, SOCK_TIMESTAMPING_TX_SOFTWARE))\n\t\t\tv.val |= SOF_TIMESTAMPING_TX_SOFTWARE;\n\t\tif (sock_flag(sk, SOCK_TIMESTAMPING_RX_HARDWARE))\n\t\t\tv.val |= SOF_TIMESTAMPING_RX_HARDWARE;\n\t\tif (sock_flag(sk, SOCK_TIMESTAMPING_RX_SOFTWARE))\n\t\t\tv.val |= SOF_TIMESTAMPING_RX_SOFTWARE;\n\t\tif (sock_flag(sk, SOCK_TIMESTAMPING_SOFTWARE))\n\t\t\tv.val |= SOF_TIMESTAMPING_SOFTWARE;\n\t\tif (sock_flag(sk, SOCK_TIMESTAMPING_SYS_HARDWARE))\n\t\t\tv.val |= SOF_TIMESTAMPING_SYS_HARDWARE;\n\t\tif (sock_flag(sk, SOCK_TIMESTAMPING_RAW_HARDWARE))\n\t\t\tv.val |= SOF_TIMESTAMPING_RAW_HARDWARE;\n\t\tbreak;\n\n\tcase SO_RCVTIMEO:\n\t\tlv = sizeof(struct timeval);\n\t\tif (sk->sk_rcvtimeo == MAX_SCHEDULE_TIMEOUT) {\n\t\t\tv.tm.tv_sec = 0;\n\t\t\tv.tm.tv_usec = 0;\n\t\t} else {\n\t\t\tv.tm.tv_sec = sk->sk_rcvtimeo \/ HZ;\n\t\t\tv.tm.tv_usec = ((sk->sk_rcvtimeo % HZ) * 1000000) \/ HZ;\n\t\t}\n\t\tbreak;\n\n\tcase SO_SNDTIMEO:\n\t\tlv = sizeof(struct timeval);\n\t\tif (sk->sk_sndtimeo == MAX_SCHEDULE_TIMEOUT) {\n\t\t\tv.tm.tv_sec = 0;\n\t\t\tv.tm.tv_usec = 0;\n\t\t} else {\n\t\t\tv.tm.tv_sec = sk->sk_sndtimeo \/ HZ;\n\t\t\tv.tm.tv_usec = ((sk->sk_sndtimeo % HZ) * 1000000) \/ HZ;\n\t\t}\n\t\tbreak;\n\n\tcase SO_RCVLOWAT:\n\t\tv.val = sk->sk_rcvlowat;\n\t\tbreak;\n\n\tcase SO_SNDLOWAT:\n\t\tv.val = 1;\n\t\tbreak;\n\n\tcase SO_PASSCRED:\n\t\tv.val = test_bit(SOCK_PASSCRED, &sock->flags) ? 1 : 0;\n\t\tbreak;\n\n\tcase SO_PEERCRED:\n\t\tif (len > sizeof(sk->sk_peercred))\n\t\t\tlen = sizeof(sk->sk_peercred);\n\t\tif (copy_to_user(optval, &sk->sk_peercred, len))\n\t\t\treturn -EFAULT;\n\t\tgoto lenout;\n\n\tcase SO_PEERNAME:\n\t{\n\t\tchar address[128];\n\n\t\tif (sock->ops->getname(sock, (struct sockaddr *)address, &lv, 2))\n\t\t\treturn -ENOTCONN;\n\t\tif (lv < len)\n\t\t\treturn -EINVAL;\n\t\tif (copy_to_user(optval, address, len))\n\t\t\treturn -EFAULT;\n\t\tgoto lenout;\n\t}\n\n\t\/* Dubious BSD thing... Probably nobody even uses it, but\n\t * the UNIX standard wants it for whatever reason... -DaveM\n\t *\/\n\tcase SO_ACCEPTCONN:\n\t\tv.val = sk->sk_state == TCP_LISTEN;\n\t\tbreak;\n\n\tcase SO_PASSSEC:\n\t\tv.val = test_bit(SOCK_PASSSEC, &sock->flags) ? 1 : 0;\n\t\tbreak;\n\n\tcase SO_PEERSEC:\n\t\treturn security_socket_getpeersec_stream(sock, optval, optlen, len);\n\n\tcase SO_MARK:\n\t\tv.val = sk->sk_mark;\n\t\tbreak;\n\n\tcase SO_RXQ_OVFL:\n\t\tv.val = !!sock_flag(sk, SOCK_RXQ_OVFL);\n\t\tbreak;\n\n\tdefault:\n\t\treturn -ENOPROTOOPT;\n\t}\n\n\tif (len > lv)\n\t\tlen = lv;\n\tif (copy_to_user(optval, &v, len))\n\t\treturn -EFAULT;\nlenout:\n\tif (put_user(len, optlen))\n\t\treturn -EFAULT;\n\treturn 0;\n}","target":0,"code_token_length":1375,"total_token_length":1706,"max_tokens_setting":2048} +{"idx":516195,"func":"MSG_PROCESS_RETURN tls_process_certificate_request(SSL *s, PACKET *pkt)\n{\n size_t i;\n\n \/* Clear certificate validity flags *\/\n for (i = 0; i < SSL_PKEY_NUM; i++)\n s->s3.tmp.valid_flags[i] = 0;\n\n if (SSL_IS_TLS13(s)) {\n PACKET reqctx, extensions;\n RAW_EXTENSION *rawexts = NULL;\n\n if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {\n \/*\n * We already sent close_notify. This can only happen in TLSv1.3\n * post-handshake messages. We can't reasonably respond to this, so\n * we just ignore it\n *\/\n return MSG_PROCESS_FINISHED_READING;\n }\n\n \/* Free and zero certificate types: it is not present in TLS 1.3 *\/\n OPENSSL_free(s->s3.tmp.ctype);\n s->s3.tmp.ctype = NULL;\n s->s3.tmp.ctype_len = 0;\n OPENSSL_free(s->pha_context);\n s->pha_context = NULL;\n s->pha_context_len = 0;\n\n if (!PACKET_get_length_prefixed_1(pkt, &reqctx) ||\n !PACKET_memdup(&reqctx, &s->pha_context, &s->pha_context_len)) {\n SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);\n return MSG_PROCESS_ERROR;\n }\n\n if (!PACKET_get_length_prefixed_2(pkt, &extensions)) {\n SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);\n return MSG_PROCESS_ERROR;\n }\n if (!tls_collect_extensions(s, &extensions,\n SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,\n &rawexts, NULL, 1)\n || !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,\n rawexts, NULL, 0, 1)) {\n \/* SSLfatal() already called *\/\n OPENSSL_free(rawexts);\n return MSG_PROCESS_ERROR;\n }\n OPENSSL_free(rawexts);\n if (!tls1_process_sigalgs(s)) {\n SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);\n return MSG_PROCESS_ERROR;\n }\n } else {\n PACKET ctypes;\n\n \/* get the certificate types *\/\n if (!PACKET_get_length_prefixed_1(pkt, &ctypes)) {\n SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);\n return MSG_PROCESS_ERROR;\n }\n\n if (!PACKET_memdup(&ctypes, &s->s3.tmp.ctype, &s->s3.tmp.ctype_len)) {\n SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);\n return MSG_PROCESS_ERROR;\n }\n\n if (SSL_USE_SIGALGS(s)) {\n PACKET sigalgs;\n\n if (!PACKET_get_length_prefixed_2(pkt, &sigalgs)) {\n SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);\n return MSG_PROCESS_ERROR;\n }\n\n \/*\n * Despite this being for certificates, preserve compatibility\n * with pre-TLS 1.3 and use the regular sigalgs field.\n *\/\n if (!tls1_save_sigalgs(s, &sigalgs, 0)) {\n SSLfatal(s, SSL_AD_INTERNAL_ERROR,\n SSL_R_SIGNATURE_ALGORITHMS_ERROR);\n return MSG_PROCESS_ERROR;\n }\n if (!tls1_process_sigalgs(s)) {\n SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);\n return MSG_PROCESS_ERROR;\n }\n }\n\n \/* get the CA RDNs *\/\n if (!parse_ca_names(s, pkt)) {\n \/* SSLfatal() already called *\/\n return MSG_PROCESS_ERROR;\n }\n }\n\n if (PACKET_remaining(pkt) != 0) {\n SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);\n return MSG_PROCESS_ERROR;\n }\n\n \/* we should setup a certificate to return.... *\/\n s->s3.tmp.cert_req = 1;\n\n \/*\n * In TLSv1.3 we don't prepare the client certificate yet. We wait until\n * after the CertificateVerify message has been received. This is because\n * in TLSv1.3 the CertificateRequest arrives before the Certificate message\n * but in TLSv1.2 it is the other way around. We want to make sure that\n * SSL_get1_peer_certificate() returns something sensible in\n * client_cert_cb.\n *\/\n if (SSL_IS_TLS13(s) && s->post_handshake_auth != SSL_PHA_REQUESTED)\n return MSG_PROCESS_CONTINUE_READING;\n\n return MSG_PROCESS_CONTINUE_PROCESSING;\n}","target":0,"code_token_length":1017,"total_token_length":1348,"max_tokens_setting":2048} +{"idx":63891,"func":"bool sql_slave_killed(THD* thd, Relay_log_info* rli)\n{\n bool ret= FALSE;\n bool is_parallel_warn= FALSE;\n\n DBUG_ENTER(\"sql_slave_killed\");\n\n DBUG_ASSERT(rli->info_thd == thd);\n DBUG_ASSERT(rli->slave_running == 1);\n if (abort_loop || thd->killed || rli->abort_slave)\n {\n is_parallel_warn= (rli->is_parallel_exec() && \n (rli->is_mts_in_group() || thd->killed));\n \/*\n Slave can execute stop being in one of two MTS or Single-Threaded mode.\n The modes define different criteria to accept the stop.\n In particular that relates to the concept of groupping.\n Killed Coordinator thread expects the worst so it warns on\n possible consistency issue.\n *\/\n if (is_parallel_warn ||\n (!rli->is_parallel_exec() &&\n thd->transaction.all.cannot_safely_rollback() && rli->is_in_group()))\n {\n char msg_stopped[]=\n \"... Slave SQL Thread stopped with incomplete event group \"\n \"having non-transactional changes. \"\n \"If the group consists solely of row-based events, you can try \"\n \"to restart the slave with --slave-exec-mode=IDEMPOTENT, which \"\n \"ignores duplicate key, key not found, and similar errors (see \"\n \"documentation for details).\";\n char msg_stopped_mts[]=\n \"... The slave coordinator and worker threads are stopped, possibly \"\n \"leaving data in inconsistent state. A restart should \"\n \"restore consistency automatically, although using non-transactional \"\n \"storage for data or info tables or DDL queries could lead to problems. \"\n \"In such cases you have to examine your data (see documentation for \"\n \"details).\";\n\n ret= TRUE;\n if (rli->abort_slave)\n {\n DBUG_PRINT(\"info\", (\"Request to stop slave SQL Thread received while \"\n \"applying an MTS group or a group that \"\n \"has non-transactional \"\n \"changes; waiting for completion of the group ... \"));\n\n \/*\n Slave sql thread shutdown in face of unfinished group modified \n Non-trans table is handled via a timer. The slave may eventually\n give out to complete the current group and in that case there\n might be issues at consequent slave restart, see the error message.\n WL#2975 offers a robust solution requiring to store the last exectuted\n event's coordinates along with the group's coordianates\n instead of waiting with @c last_event_start_time the timer.\n *\/\n\n if (rli->last_event_start_time == 0)\n rli->last_event_start_time= my_time(0);\n ret= difftime(my_time(0), rli->last_event_start_time) <=\n SLAVE_WAIT_GROUP_DONE ? FALSE : TRUE;\n\n DBUG_EXECUTE_IF(\"stop_slave_middle_group\", \n DBUG_EXECUTE_IF(\"incomplete_group_in_relay_log\",\n ret= TRUE;);); \/\/ time is over\n\n if (!ret && !rli->reported_unsafe_warning)\n {\n rli->report(WARNING_LEVEL, 0,\n !is_parallel_warn ?\n \"Request to stop slave SQL Thread received while \"\n \"applying a group that has non-transactional \"\n \"changes; waiting for completion of the group ... \"\n :\n \"Coordinator thread of multi-threaded slave is being \"\n \"stopped in the middle of assigning a group of events; \"\n \"deferring to exit until the group completion ... \");\n rli->reported_unsafe_warning= true;\n }\n }\n if (ret)\n {\n if (is_parallel_warn)\n rli->report(!rli->is_error() ? ERROR_LEVEL :\n WARNING_LEVEL, \/\/ an error was reported by Worker\n ER_MTS_INCONSISTENT_DATA,\n ER(ER_MTS_INCONSISTENT_DATA),\n msg_stopped_mts);\n else\n rli->report(ERROR_LEVEL, ER_SLAVE_FATAL_ERROR,\n ER(ER_SLAVE_FATAL_ERROR), msg_stopped);\n }\n }\n else\n {\n ret= TRUE;\n }\n }\n if (ret)\n {\n rli->last_event_start_time= 0;\n if (rli->mts_group_status == Relay_log_info::MTS_IN_GROUP)\n {\n rli->mts_group_status= Relay_log_info::MTS_KILLED_GROUP;\n }\n }\n \n DBUG_RETURN(ret);\n}","target":0,"code_token_length":987,"total_token_length":1318,"max_tokens_setting":2048} +{"idx":301178,"func":"do_core_note(struct magic_set *ms, unsigned char *nbuf, uint32_t type,\n int swap, uint32_t namesz, uint32_t descsz,\n size_t noff, size_t doff, int *flags, size_t size, int clazz)\n{\n#ifdef ELFCORE\n\tint os_style = -1;\n\t\/*\n\t * Sigh. The 2.0.36 kernel in Debian 2.1, at\n\t * least, doesn't correctly implement name\n\t * sections, in core dumps, as specified by\n\t * the \"Program Linking\" section of \"UNIX(R) System\n\t * V Release 4 Programmer's Guide: ANSI C and\n\t * Programming Support Tools\", because my copy\n\t * clearly says \"The first 'namesz' bytes in 'name'\n\t * contain a *null-terminated* [emphasis mine]\n\t * character representation of the entry's owner\n\t * or originator\", but the 2.0.36 kernel code\n\t * doesn't include the terminating null in the\n\t * name....\n\t *\/\n\tif ((namesz == 4 && strncmp((char *)&nbuf[noff], \"CORE\", 4) == 0) ||\n\t (namesz == 5 && strcmp((char *)&nbuf[noff], \"CORE\") == 0)) {\n\t\tos_style = OS_STYLE_SVR4;\n\t} \n\n\tif ((namesz == 8 && strcmp((char *)&nbuf[noff], \"FreeBSD\") == 0)) {\n\t\tos_style = OS_STYLE_FREEBSD;\n\t}\n\n\tif ((namesz >= 11 && strncmp((char *)&nbuf[noff], \"NetBSD-CORE\", 11)\n\t == 0)) {\n\t\tos_style = OS_STYLE_NETBSD;\n\t}\n\n\tif (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {\n\t\tif (file_printf(ms, \", %s-style\", os_style_names[os_style])\n\t\t == -1)\n\t\t\treturn 1;\n\t\t*flags |= FLAGS_DID_CORE_STYLE;\n\t\t*flags |= os_style;\n\t}\n\n\tswitch (os_style) {\n\tcase OS_STYLE_NETBSD:\n\t\tif (type == NT_NETBSD_CORE_PROCINFO) {\n\t\t\tchar sbuf[512];\n\t\t\tstruct NetBSD_elfcore_procinfo pi;\n\t\t\tmemset(&pi, 0, sizeof(pi));\n\t\t\tmemcpy(&pi, nbuf + doff, descsz);\n\n\t\t\tif (file_printf(ms, \", from '%.31s', pid=%u, uid=%u, \"\n\t\t\t \"gid=%u, nlwps=%u, lwp=%u (signal %u\/code %u)\",\n\t\t\t file_printable(sbuf, sizeof(sbuf),\n\t\t\t CAST(char *, pi.cpi_name)),\n\t\t\t elf_getu32(swap, pi.cpi_pid),\n\t\t\t elf_getu32(swap, pi.cpi_euid),\n\t\t\t elf_getu32(swap, pi.cpi_egid),\n\t\t\t elf_getu32(swap, pi.cpi_nlwps),\n\t\t\t elf_getu32(swap, pi.cpi_siglwp),\n\t\t\t elf_getu32(swap, pi.cpi_signo),\n\t\t\t elf_getu32(swap, pi.cpi_sigcode)) == -1)\n\t\t\t\treturn 1;\n\n\t\t\t*flags |= FLAGS_DID_CORE;\n\t\t\treturn 1;\n\t\t}\n\t\tbreak;\n\n\tdefault:\n\t\tif (type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {\n\t\t\tsize_t i, j;\n\t\t\tunsigned char c;\n\t\t\t\/*\n\t\t\t * Extract the program name. We assume\n\t\t\t * it to be 16 characters (that's what it\n\t\t\t * is in SunOS 5.x and Linux).\n\t\t\t *\n\t\t\t * Unfortunately, it's at a different offset\n\t\t\t * in various OSes, so try multiple offsets.\n\t\t\t * If the characters aren't all printable,\n\t\t\t * reject it.\n\t\t\t *\/\n\t\t\tfor (i = 0; i < NOFFSETS; i++) {\n\t\t\t\tunsigned char *cname, *cp;\n\t\t\t\tsize_t reloffset = prpsoffsets(i);\n\t\t\t\tsize_t noffset = doff + reloffset;\n\t\t\t\tsize_t k;\n\t\t\t\tfor (j = 0; j < 16; j++, noffset++,\n\t\t\t\t reloffset++) {\n\t\t\t\t\t\/*\n\t\t\t\t\t * Make sure we're not past\n\t\t\t\t\t * the end of the buffer; if\n\t\t\t\t\t * we are, just give up.\n\t\t\t\t\t *\/\n\t\t\t\t\tif (noffset >= size)\n\t\t\t\t\t\tgoto tryanother;\n\n\t\t\t\t\t\/*\n\t\t\t\t\t * Make sure we're not past\n\t\t\t\t\t * the end of the contents;\n\t\t\t\t\t * if we are, this obviously\n\t\t\t\t\t * isn't the right offset.\n\t\t\t\t\t *\/\n\t\t\t\t\tif (reloffset >= descsz)\n\t\t\t\t\t\tgoto tryanother;\n\n\t\t\t\t\tc = nbuf[noffset];\n\t\t\t\t\tif (c == '\\0') {\n\t\t\t\t\t\t\/*\n\t\t\t\t\t\t * A '\\0' at the\n\t\t\t\t\t\t * beginning is\n\t\t\t\t\t\t * obviously wrong.\n\t\t\t\t\t\t * Any other '\\0'\n\t\t\t\t\t\t * means we're done.\n\t\t\t\t\t\t *\/\n\t\t\t\t\t\tif (j == 0)\n\t\t\t\t\t\t\tgoto tryanother;\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t\/*\n\t\t\t\t\t\t * A nonprintable\n\t\t\t\t\t\t * character is also\n\t\t\t\t\t\t * wrong.\n\t\t\t\t\t\t *\/\n\t\t\t\t\t\tif (!isprint(c) || isquote(c))\n\t\t\t\t\t\t\tgoto tryanother;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\/*\n\t\t\t\t * Well, that worked.\n\t\t\t\t *\/\n\n\t\t\t\t\/*\n\t\t\t\t * Try next offsets, in case this match is\n\t\t\t\t * in the middle of a string.\n\t\t\t\t *\/\n\t\t\t\tfor (k = i + 1 ; k < NOFFSETS; k++) {\n\t\t\t\t\tsize_t no;\n\t\t\t\t\tint adjust = 1;\n\t\t\t\t\tif (prpsoffsets(k) >= prpsoffsets(i))\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tfor (no = doff + prpsoffsets(k);\n\t\t\t\t\t no < doff + prpsoffsets(i); no++)\n\t\t\t\t\t\tadjust = adjust\n\t\t\t\t\t\t && isprint(nbuf[no]);\n\t\t\t\t\tif (adjust)\n\t\t\t\t\t\ti = k;\n\t\t\t\t}\n\n\t\t\t\tcname = (unsigned char *)\n\t\t\t\t &nbuf[doff + prpsoffsets(i)];\n\t\t\t\tfor (cp = cname; *cp && isprint(*cp); cp++)\n\t\t\t\t\tcontinue;\n\t\t\t\t\/*\n\t\t\t\t * Linux apparently appends a space at the end\n\t\t\t\t * of the command line: remove it.\n\t\t\t\t *\/\n\t\t\t\twhile (cp > cname && isspace(cp[-1]))\n\t\t\t\t\tcp--;\n\t\t\t\tif (file_printf(ms, \", from '%.*s'\",\n\t\t\t\t (int)(cp - cname), cname) == -1)\n\t\t\t\t\treturn 1;\n\t\t\t\t*flags |= FLAGS_DID_CORE;\n\t\t\t\treturn 1;\n\n\t\t\ttryanother:\n\t\t\t\t;\n\t\t\t}\n\t\t}\n\t\tbreak;\n\t}\n#endif\n\treturn 0;\n}","target":0,"code_token_length":1463,"total_token_length":1794,"max_tokens_setting":2048} +{"idx":363347,"func":"xsltSystemPropertyFunction(xmlXPathParserContextPtr ctxt, int nargs){\n xmlXPathObjectPtr obj;\n xmlChar *prefix, *name;\n const xmlChar *nsURI = NULL;\n\n if (nargs != 1) {\n\txsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL,\n\t\t\"system-property() : expects one string arg\\n\");\n\tctxt->error = XPATH_INVALID_ARITY;\n\treturn;\n }\n if ((ctxt->value == NULL) || (ctxt->value->type != XPATH_STRING)) {\n\txsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL,\n\t \"system-property() : invalid arg expecting a string\\n\");\n\tctxt->error = XPATH_INVALID_TYPE;\n\treturn;\n }\n obj = valuePop(ctxt);\n if (obj->stringval == NULL) {\n\tvaluePush(ctxt, xmlXPathNewString((const xmlChar *)\"\"));\n } else {\n\tname = xmlSplitQName2(obj->stringval, &prefix);\n\tif (name == NULL) {\n\t name = xmlStrdup(obj->stringval);\n\t} else {\n\t nsURI = xmlXPathNsLookup(ctxt->context, prefix);\n\t if (nsURI == NULL) {\n\t\txsltTransformError(xsltXPathGetTransformContext(ctxt), NULL, NULL,\n\t\t \"system-property() : prefix %s is not bound\\n\", prefix);\n\t }\n\t}\n\n\tif (xmlStrEqual(nsURI, XSLT_NAMESPACE)) {\n#ifdef DOCBOOK_XSL_HACK\n\t if (xmlStrEqual(name, (const xmlChar *)\"vendor\")) {\n\t\txsltStylesheetPtr sheet;\n\t\txsltTransformContextPtr tctxt;\n\n\t\ttctxt = xsltXPathGetTransformContext(ctxt);\n\t\tif ((tctxt != NULL) && (tctxt->inst != NULL) &&\n\t\t (xmlStrEqual(tctxt->inst->name, BAD_CAST \"variable\")) &&\n\t\t (tctxt->inst->parent != NULL) &&\n\t\t (xmlStrEqual(tctxt->inst->parent->name,\n\t\t\t\t BAD_CAST \"template\")))\n\t\t sheet = tctxt->style;\n\t\telse\n\t\t sheet = NULL;\n\t\tif ((sheet != NULL) && (sheet->doc != NULL) &&\n\t\t (sheet->doc->URL != NULL) &&\n\t\t (xmlStrstr(sheet->doc->URL,\n\t\t\t (const xmlChar *)\"chunk\") != NULL)) {\n\t\t valuePush(ctxt, xmlXPathNewString(\n\t\t\t(const xmlChar *)\"libxslt (SAXON 6.2 compatible)\"));\n\n\t\t} else {\n\t\t valuePush(ctxt, xmlXPathNewString(\n\t\t\t(const xmlChar *)XSLT_DEFAULT_VENDOR));\n\t\t}\n\t } else\n#else\n\t if (xmlStrEqual(name, (const xmlChar *)\"vendor\")) {\n\t\tvaluePush(ctxt, xmlXPathNewString(\n\t\t\t (const xmlChar *)XSLT_DEFAULT_VENDOR));\n\t } else\n#endif\n\t if (xmlStrEqual(name, (const xmlChar *)\"version\")) {\n\t\tvaluePush(ctxt, xmlXPathNewString(\n\t\t (const xmlChar *)XSLT_DEFAULT_VERSION));\n\t } else if (xmlStrEqual(name, (const xmlChar *)\"vendor-url\")) {\n\t\tvaluePush(ctxt, xmlXPathNewString(\n\t\t (const xmlChar *)XSLT_DEFAULT_URL));\n\t } else {\n\t\tvaluePush(ctxt, xmlXPathNewString((const xmlChar *)\"\"));\n\t }\n\t}\n\tif (name != NULL)\n\t xmlFree(name);\n\tif (prefix != NULL)\n\t xmlFree(prefix);\n }\n xmlXPathFreeObject(obj);\n}","target":0,"code_token_length":752,"total_token_length":1083,"max_tokens_setting":2048} +{"idx":352168,"func":"static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn)\n{\n\tstruct bpf_insn_aux_data *aux = cur_aux(env);\n\tstruct bpf_reg_state *regs = cur_regs(env);\n\tstruct bpf_reg_state *dst_reg;\n\tstruct bpf_map *map;\n\tint err;\n\n\tif (BPF_SIZE(insn->code) != BPF_DW) {\n\t\tverbose(env, \"invalid BPF_LD_IMM insn\\n\");\n\t\treturn -EINVAL;\n\t}\n\tif (insn->off != 0) {\n\t\tverbose(env, \"BPF_LD_IMM64 uses reserved fields\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\terr = check_reg_arg(env, insn->dst_reg, DST_OP);\n\tif (err)\n\t\treturn err;\n\n\tdst_reg = ®s[insn->dst_reg];\n\tif (insn->src_reg == 0) {\n\t\tu64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm;\n\n\t\tdst_reg->type = SCALAR_VALUE;\n\t\t__mark_reg_known(®s[insn->dst_reg], imm);\n\t\treturn 0;\n\t}\n\n\tif (insn->src_reg == BPF_PSEUDO_BTF_ID) {\n\t\tmark_reg_known_zero(env, regs, insn->dst_reg);\n\n\t\tdst_reg->type = aux->btf_var.reg_type;\n\t\tswitch (dst_reg->type) {\n\t\tcase PTR_TO_MEM:\n\t\t\tdst_reg->mem_size = aux->btf_var.mem_size;\n\t\t\tbreak;\n\t\tcase PTR_TO_BTF_ID:\n\t\tcase PTR_TO_PERCPU_BTF_ID:\n\t\t\tdst_reg->btf = aux->btf_var.btf;\n\t\t\tdst_reg->btf_id = aux->btf_var.btf_id;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tverbose(env, \"bpf verifier is misconfigured\\n\");\n\t\t\treturn -EFAULT;\n\t\t}\n\t\treturn 0;\n\t}\n\n\tif (insn->src_reg == BPF_PSEUDO_FUNC) {\n\t\tstruct bpf_prog_aux *aux = env->prog->aux;\n\t\tu32 subprogno = find_subprog(env,\n\t\t\t\t\t env->insn_idx + insn->imm + 1);\n\n\t\tif (!aux->func_info) {\n\t\t\tverbose(env, \"missing btf func_info\\n\");\n\t\t\treturn -EINVAL;\n\t\t}\n\t\tif (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) {\n\t\t\tverbose(env, \"callback function not static\\n\");\n\t\t\treturn -EINVAL;\n\t\t}\n\n\t\tdst_reg->type = PTR_TO_FUNC;\n\t\tdst_reg->subprogno = subprogno;\n\t\treturn 0;\n\t}\n\n\tmap = env->used_maps[aux->map_index];\n\tmark_reg_known_zero(env, regs, insn->dst_reg);\n\tdst_reg->map_ptr = map;\n\n\tif (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||\n\t insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) {\n\t\tdst_reg->type = PTR_TO_MAP_VALUE;\n\t\tdst_reg->off = aux->map_off;\n\t\tif (map_value_has_spin_lock(map))\n\t\t\tdst_reg->id = ++env->id_gen;\n\t} else if (insn->src_reg == BPF_PSEUDO_MAP_FD ||\n\t\t insn->src_reg == BPF_PSEUDO_MAP_IDX) {\n\t\tdst_reg->type = CONST_PTR_TO_MAP;\n\t} else {\n\t\tverbose(env, \"bpf verifier is misconfigured\\n\");\n\t\treturn -EINVAL;\n\t}\n\n\treturn 0;\n}","target":1,"code_token_length":752,"total_token_length":1083,"max_tokens_setting":2048} +{"idx":339429,"func":"MAKE_ACCESSORS(AVVDPAUContext, vdpau_hwaccel, AVVDPAU_Render2, render2)\n\n\n\nint ff_vdpau_common_init(AVCodecContext *avctx, VdpDecoderProfile profile,\n\n int level)\n\n{\n\n VDPAUHWContext *hwctx = avctx->hwaccel_context;\n\n VDPAUContext *vdctx = avctx->internal->hwaccel_priv_data;\n\n VdpVideoSurfaceQueryCapabilities *surface_query_caps;\n\n VdpDecoderQueryCapabilities *decoder_query_caps;\n\n VdpDecoderCreate *create;\n\n void *func;\n\n VdpStatus status;\n\n VdpBool supported;\n\n uint32_t max_level, max_mb, max_width, max_height;\n\n \/* See vdpau\/vdpau.h for alignment constraints. *\/\n\n uint32_t width = (avctx->coded_width + 1) & ~1;\n\n uint32_t height = (avctx->coded_height + 3) & ~3;\n\n\n\n vdctx->width = UINT32_MAX;\n\n vdctx->height = UINT32_MAX;\n\n hwctx->reset = 0;\n\n\n\n if (!hwctx) {\n\n vdctx->device = VDP_INVALID_HANDLE;\n\n av_log(avctx, AV_LOG_WARNING, \"hwaccel_context has not been setup by the user application, cannot initialize\\n\");\n\n return 0;\n\n }\n\n\n\n if (hwctx->context.decoder != VDP_INVALID_HANDLE) {\n\n vdctx->decoder = hwctx->context.decoder;\n\n vdctx->render = hwctx->context.render;\n\n vdctx->device = VDP_INVALID_HANDLE;\n\n return 0; \/* Decoder created by user *\/\n\n }\n\n\n\n vdctx->device = hwctx->device;\n\n vdctx->get_proc_address = hwctx->get_proc_address;\n\n\n\n if (level < 0)\n\n return AVERROR(ENOTSUP);\n\n\n\n status = vdctx->get_proc_address(vdctx->device,\n\n VDP_FUNC_ID_VIDEO_SURFACE_QUERY_CAPABILITIES,\n\n &func);\n\n if (status != VDP_STATUS_OK)\n\n return vdpau_error(status);\n\n else\n\n surface_query_caps = func;\n\n\n\n status = surface_query_caps(vdctx->device, VDP_CHROMA_TYPE_420, &supported,\n\n &max_width, &max_height);\n\n if (status != VDP_STATUS_OK)\n\n return vdpau_error(status);\n\n if (supported != VDP_TRUE ||\n\n max_width < width || max_height < height)\n\n return AVERROR(ENOTSUP);\n\n\n\n status = vdctx->get_proc_address(vdctx->device,\n\n VDP_FUNC_ID_DECODER_QUERY_CAPABILITIES,\n\n &func);\n\n if (status != VDP_STATUS_OK)\n\n return vdpau_error(status);\n\n else\n\n decoder_query_caps = func;\n\n\n\n status = decoder_query_caps(vdctx->device, profile, &supported, &max_level,\n\n &max_mb, &max_width, &max_height);\n\n if (status != VDP_STATUS_OK)\n\n return vdpau_error(status);\n\n\n\n if (supported != VDP_TRUE || max_level < level ||\n\n max_width < width || max_height < height)\n\n return AVERROR(ENOTSUP);\n\n\n\n status = vdctx->get_proc_address(vdctx->device, VDP_FUNC_ID_DECODER_CREATE,\n\n &func);\n\n if (status != VDP_STATUS_OK)\n\n return vdpau_error(status);\n\n else\n\n create = func;\n\n\n\n status = vdctx->get_proc_address(vdctx->device, VDP_FUNC_ID_DECODER_RENDER,\n\n &func);\n\n if (status != VDP_STATUS_OK)\n\n return vdpau_error(status);\n\n else\n\n vdctx->render = func;\n\n\n\n status = create(vdctx->device, profile, width, height, avctx->refs,\n\n &vdctx->decoder);\n\n if (status == VDP_STATUS_OK) {\n\n vdctx->width = avctx->coded_width;\n\n vdctx->height = avctx->coded_height;\n\n }\n\n\n\n return vdpau_error(status);\n\n}\n","target":0,"code_token_length":885,"total_token_length":1216,"max_tokens_setting":2048} +{"idx":428018,"func":"EXPORTED void write_body(long code, struct transaction_t *txn,\n\t\tconst char *buf, unsigned len)\n{\n unsigned is_dynamic = code ? (txn->flags.te & TE_CHUNKED) : 1;\n unsigned outlen = len, offset = 0;\n int do_md5 = config_getswitch(IMAPOPT_HTTPCONTENTMD5);\n static MD5_CTX ctx;\n static unsigned char md5[MD5_DIGEST_LENGTH];\n\n if (!is_dynamic && len < GZIP_MIN_LEN) {\n\t\/* Don't compress small static content *\/\n\ttxn->resp_body.enc = CE_IDENTITY;\n\ttxn->flags.te = TE_NONE;\n }\n\n \/* Compress data *\/\n if (txn->resp_body.enc || txn->flags.te & ~TE_CHUNKED) {\n#ifdef HAVE_ZLIB\n\t\/* Only flush for static content or on last (zero-length) chunk *\/\n\tunsigned flush = (is_dynamic && len) ? Z_NO_FLUSH : Z_FINISH;\n\n\tif (code) deflateReset(&txn->zstrm);\n\n\ttxn->zstrm.next_in = (Bytef *) buf;\n\ttxn->zstrm.avail_in = len;\n\tbuf_reset(&txn->zbuf);\n\n\tdo {\n\t buf_ensure(&txn->zbuf,\n\t\t deflateBound(&txn->zstrm, txn->zstrm.avail_in));\n\n\t txn->zstrm.next_out = (Bytef *) txn->zbuf.s + txn->zbuf.len;\n\t txn->zstrm.avail_out = txn->zbuf.alloc - txn->zbuf.len;\n\n\t deflate(&txn->zstrm, flush);\n\t txn->zbuf.len = txn->zbuf.alloc - txn->zstrm.avail_out;\n\n\t} while (!txn->zstrm.avail_out);\n\n\tbuf = txn->zbuf.s;\n\toutlen = txn->zbuf.len;\n#else\n\t\/* XXX should never get here *\/\n\tfatal(\"Compression requested, but no zlib\", EC_SOFTWARE);\n#endif \/* HAVE_ZLIB *\/\n }\n\n if (code) {\n\t\/* Initial call - prepare response header based on CE, TE and version *\/\n\tif (do_md5) MD5Init(&ctx);\n\n\tif (txn->flags.te & ~TE_CHUNKED) {\n\t \/* Transfer-Encoded content MUST be chunked *\/\n\t txn->flags.te |= TE_CHUNKED;\n\n\t if (!is_dynamic) {\n\t\t\/* Handle static content as last chunk *\/\n\t\tlen = 0;\n\t }\n\t}\n\n\tif (!(txn->flags.te & TE_CHUNKED)) {\n\t \/* Full\/partial body (no encoding).\n\t *\n\t * In all cases, 'resp_body.len' is used to specify complete-length\n\t * In the case of a 206 or 416 response, Content-Length will be\n\t * set accordingly in response_header().\n\t *\/\n\t txn->resp_body.len = outlen;\n\n\t if (code == HTTP_PARTIAL) {\n\t\t\/* check_precond() tells us that this is a range request *\/\n\t\tcode = parse_ranges(*spool_getheader(txn->req_hdrs, \"Range\"),\n\t\t\t\t outlen, &txn->resp_body.range);\n\n\t\tswitch (code) {\n\t\tcase HTTP_OK:\n\t\t \/* Full body (unknown range-unit) *\/\n\t\t break;\n\n\t\tcase HTTP_PARTIAL:\n\t\t \/* One or more range request(s) *\/\n\t\t txn->resp_body.len = outlen;\n\n\t\t if (txn->resp_body.range->next) {\n\t\t\t\/* Multiple ranges *\/\n\t\t\tmultipart_byteranges(txn, buf);\n\t\t\treturn;\n\t\t }\n\t\t else {\n\t\t\t\/* Single range - set data parameters accordingly *\/\n\t\t\toffset += txn->resp_body.range->first;\n\t\t\toutlen = txn->resp_body.range->last -\n\t\t\t txn->resp_body.range->first + 1;\n\t\t }\n\t\t break;\n\n\t\tcase HTTP_UNSAT_RANGE:\n\t\t \/* No valid ranges *\/\n\t\t outlen = 0;\n\t\t break;\n\t\t}\n\t }\n\n\t if (outlen && do_md5) {\n\t\tMD5Update(&ctx, buf+offset, outlen);\n\t\tMD5Final(md5, &ctx);\n\t\ttxn->resp_body.md5 = md5;\n\t }\n\t}\n\telse if (txn->flags.ver1_0) {\n\t \/* HTTP\/1.0 doesn't support chunked - close-delimit the body *\/\n\t txn->flags.conn = CONN_CLOSE;\n\t}\n\telse if (do_md5) txn->flags.trailer = TRAILER_CMD5;\n\n\tresponse_header(code, txn);\n\n\t\/* MUST NOT send a body for 1xx\/204\/304 response or any HEAD response *\/\n\tswitch (code) {\n\tcase HTTP_CONTINUE:\n\tcase HTTP_SWITCH_PROT:\n\tcase HTTP_PROCESSING:\n\tcase HTTP_NO_CONTENT:\n\tcase HTTP_NOT_MODIFIED:\n\t return;\n\n\tdefault:\n\t if (txn->meth == METH_HEAD) return;\n\t}\n }\n\n \/* Output data *\/\n if ((txn->flags.te & TE_CHUNKED) && !txn->flags.ver1_0) {\n\t\/* HTTP\/1.1 chunk *\/\n\tif (outlen) {\n\t prot_printf(httpd_out, \"%x\\r\\n\", outlen);\n\t prot_write(httpd_out, buf, outlen);\n\t prot_puts(httpd_out, \"\\r\\n\");\n\n\t if (do_md5) MD5Update(&ctx, buf, outlen);\t \n\t}\n\tif (!len) {\n\t \/* Terminate the HTTP\/1.1 body with a zero-length chunk *\/\n\t prot_puts(httpd_out, \"0\\r\\n\");\n\n\t \/* Trailer *\/\n\t if (do_md5) {\n\t\tMD5Final(md5, &ctx);\n\t\tContent_MD5(md5);\n\t }\n\n\t prot_puts(httpd_out, \"\\r\\n\");\n\t}\n }\n else {\n\t\/* Full body or HTTP\/1.0 close-delimited body *\/\n\tprot_write(httpd_out, buf + offset, outlen);\n }\n}","target":0,"code_token_length":1239,"total_token_length":1570,"max_tokens_setting":2048} +{"idx":433818,"func":"ec_mulm_25519 (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v, mpi_ec_t ctx)\n{\n mpi_ptr_t wp, up, vp;\n mpi_size_t wsize = LIMB_SIZE_25519;\n mpi_limb_t n[LIMB_SIZE_25519*2];\n mpi_limb_t m[LIMB_SIZE_25519+1];\n mpi_limb_t cy;\n int msb;\n\n (void)ctx;\n if (w->nlimbs != wsize || u->nlimbs != wsize || v->nlimbs != wsize)\n log_bug (\"mulm_25519: different sizes\\n\");\n\n up = u->d;\n vp = v->d;\n wp = w->d;\n\n _gcry_mpih_mul_n (n, up, vp, wsize);\n memcpy (wp, n, wsize * BYTES_PER_MPI_LIMB);\n wp[LIMB_SIZE_25519-1] &= ~((mpi_limb_t)1 << (255 % BITS_PER_MPI_LIMB));\n\n memcpy (m, n+LIMB_SIZE_25519-1, (wsize+1) * BYTES_PER_MPI_LIMB);\n _gcry_mpih_rshift (m, m, LIMB_SIZE_25519+1, (255 % BITS_PER_MPI_LIMB));\n\n memcpy (n, m, wsize * BYTES_PER_MPI_LIMB);\n cy = _gcry_mpih_lshift (m, m, LIMB_SIZE_25519, 4);\n m[LIMB_SIZE_25519] = cy;\n cy = _gcry_mpih_add_n (m, m, n, wsize);\n m[LIMB_SIZE_25519] += cy;\n cy = _gcry_mpih_add_n (m, m, n, wsize);\n m[LIMB_SIZE_25519] += cy;\n cy = _gcry_mpih_add_n (m, m, n, wsize);\n m[LIMB_SIZE_25519] += cy;\n\n cy = _gcry_mpih_add_n (wp, wp, m, wsize);\n m[LIMB_SIZE_25519] += cy;\n\n memset (m, 0, wsize * BYTES_PER_MPI_LIMB);\n msb = (wp[LIMB_SIZE_25519-1] >> (255 % BITS_PER_MPI_LIMB));\n m[0] = (m[LIMB_SIZE_25519] * 2 + msb) * 19;\n wp[LIMB_SIZE_25519-1] &= ~((mpi_limb_t)1 << (255 % BITS_PER_MPI_LIMB));\n _gcry_mpih_add_n (wp, wp, m, wsize);\n\n m[0] = 0;\n cy = _gcry_mpih_sub_n (wp, wp, ctx->p->d, wsize);\n mpih_set_cond (m, ctx->p->d, wsize, (cy != 0UL));\n _gcry_mpih_add_n (wp, wp, m, wsize);\n}","target":0,"code_token_length":753,"total_token_length":1084,"max_tokens_setting":2048} +{"idx":393872,"func":"dissect_80211n_mac(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree, int offset, int data_len, gboolean add_subtree, guint32 *n_mac_flags, guint32 *ampdu_id, struct ieee_802_11_phdr *phdr)\n{\n proto_tree *ftree = tree;\n ptvcursor_t *csr;\n int subtree_off = add_subtree ? 4 : 0;\n guint32 flags;\n\n phdr->phy = PHDR_802_11_PHY_11N;\n\n *n_mac_flags = tvb_get_letohl(tvb, offset + subtree_off);\n *ampdu_id = tvb_get_letohl(tvb, offset + 4 + subtree_off);\n\n if (add_subtree) {\n ftree = proto_tree_add_subtree(tree, tvb, offset, data_len, ett_dot11n_mac, NULL, \"802.11n MAC\");\n add_ppi_field_header(tvb, ftree, &offset);\n data_len -= 4; \/* Subtract field header length *\/\n }\n\n if (data_len != PPI_80211N_MAC_LEN) {\n proto_tree_add_expert_format(ftree, pinfo, &ei_ppi_invalid_length, tvb, offset, data_len, \"Invalid length: %u\", data_len);\n THROW(ReportedBoundsError);\n }\n\n csr = ptvcursor_new(ftree, tvb, offset);\n\n flags = tvb_get_letohl(tvb, ptvcursor_current_offset(csr));\n phdr->phy_info.info_11n.presence_flags = PHDR_802_11N_HAS_SHORT_GI|PHDR_802_11N_HAS_GREENFIELD;\n phdr->phy_info.info_11n.short_gi = ((flags & DOT11N_FLAG_SHORT_GI) != 0);\n phdr->phy_info.info_11n.greenfield = ((flags & DOT11N_FLAG_GREENFIELD) != 0);\n ptvcursor_add_with_subtree(csr, hf_80211n_mac_flags, 4, ENC_LITTLE_ENDIAN,\n ett_dot11n_mac_flags);\n ptvcursor_add_no_advance(csr, hf_80211n_mac_flags_greenfield, 4, ENC_LITTLE_ENDIAN);\n ptvcursor_add_no_advance(csr, hf_80211n_mac_flags_ht20_40, 4, ENC_LITTLE_ENDIAN);\n ptvcursor_add_no_advance(csr, hf_80211n_mac_flags_rx_guard_interval, 4, ENC_LITTLE_ENDIAN);\n ptvcursor_add_no_advance(csr, hf_80211n_mac_flags_duplicate_rx, 4, ENC_LITTLE_ENDIAN);\n ptvcursor_add_no_advance(csr, hf_80211n_mac_flags_aggregate, 4, ENC_LITTLE_ENDIAN);\n ptvcursor_add_no_advance(csr, hf_80211n_mac_flags_more_aggregates, 4, ENC_LITTLE_ENDIAN);\n ptvcursor_add(csr, hf_80211n_mac_flags_delimiter_crc_after, 4, ENC_LITTLE_ENDIAN); \/* Last *\/\n ptvcursor_pop_subtree(csr);\n\n ptvcursor_add(csr, hf_80211n_mac_ampdu_id, 4, ENC_LITTLE_ENDIAN);\n ptvcursor_add(csr, hf_80211n_mac_num_delimiters, 1, ENC_LITTLE_ENDIAN);\n\n if (add_subtree) {\n ptvcursor_add(csr, hf_80211n_mac_reserved, 3, ENC_LITTLE_ENDIAN);\n }\n\n ptvcursor_free(csr);\n}","target":0,"code_token_length":837,"total_token_length":1168,"max_tokens_setting":2048} +{"idx":398569,"func":"static plist_t parse_bin_node(struct bplist_data *bplist, const char** object)\n{\n uint16_t type = 0;\n uint64_t size = 0;\n\n if (!object)\n return NULL;\n\n type = (**object) & BPLIST_MASK;\n size = (**object) & BPLIST_FILL;\n (*object)++;\n\n switch (type)\n {\n\n case BPLIST_NULL:\n switch (size)\n {\n\n case BPLIST_TRUE:\n {\n plist_data_t data = plist_new_plist_data();\n data->type = PLIST_BOOLEAN;\n data->boolval = TRUE;\n data->length = 1;\n return node_create(NULL, data);\n }\n\n case BPLIST_FALSE:\n {\n plist_data_t data = plist_new_plist_data();\n data->type = PLIST_BOOLEAN;\n data->boolval = FALSE;\n data->length = 1;\n return node_create(NULL, data);\n }\n\n case BPLIST_NULL:\n default:\n return NULL;\n }\n\n case BPLIST_UINT:\n if (*object - bplist->data + (uint64_t)(1 << size) >= bplist->size)\n return NULL;\n return parse_uint_node(object, size);\n\n case BPLIST_REAL:\n if (*object - bplist->data + (uint64_t)(1 << size) >= bplist->size)\n return NULL;\n return parse_real_node(object, size);\n\n case BPLIST_DATE:\n if (3 != size)\n return NULL;\n if (*object - bplist->data + (uint64_t)(1 << size) >= bplist->size)\n return NULL;\n return parse_date_node(object, size);\n\n case BPLIST_DATA:\n if (BPLIST_FILL == size) {\n uint8_t next_size = **object & BPLIST_FILL;\n if ((**object & BPLIST_MASK) != BPLIST_UINT)\n return NULL;\n (*object)++;\n size = UINT_TO_HOST(*object, (1 << next_size));\n (*object) += (1 << next_size);\n }\n\n if (*object - bplist->data + size >= bplist->size)\n return NULL;\n return parse_data_node(object, size);\n\n case BPLIST_STRING:\n if (BPLIST_FILL == size) {\n uint8_t next_size = **object & BPLIST_FILL;\n if ((**object & BPLIST_MASK) != BPLIST_UINT)\n return NULL;\n (*object)++;\n size = UINT_TO_HOST(*object, (1 << next_size));\n (*object) += (1 << next_size);\n }\n\n if (*object - bplist->data + size >= bplist->size)\n return NULL;\n return parse_string_node(object, size);\n\n case BPLIST_UNICODE:\n if (BPLIST_FILL == size) {\n uint8_t next_size = **object & BPLIST_FILL;\n if ((**object & BPLIST_MASK) != BPLIST_UINT)\n return NULL;\n (*object)++;\n size = UINT_TO_HOST(*object, (1 << next_size));\n (*object) += (1 << next_size);\n }\n\n if (*object - bplist->data + size * 2 >= bplist->size)\n return NULL;\n return parse_unicode_node(object, size);\n\n case BPLIST_SET:\n case BPLIST_ARRAY:\n if (BPLIST_FILL == size) {\n uint8_t next_size = **object & BPLIST_FILL;\n if ((**object & BPLIST_MASK) != BPLIST_UINT)\n return NULL;\n (*object)++;\n size = UINT_TO_HOST(*object, (1 << next_size));\n (*object) += (1 << next_size);\n }\n\n if (*object - bplist->data + size >= bplist->size)\n return NULL;\n return parse_array_node(bplist, object, size);\n\n case BPLIST_UID:\n return parse_uid_node(object, size);\n\n case BPLIST_DICT:\n if (BPLIST_FILL == size) {\n\t uint8_t next_size = **object & BPLIST_FILL;\n if ((**object & BPLIST_MASK) != BPLIST_UINT)\n return NULL;\n (*object)++;\n size = UINT_TO_HOST(*object, (1 << next_size));\n (*object) += (1 << next_size);\n }\n\n if (*object - bplist->data + size >= bplist->size)\n return NULL;\n return parse_dict_node(bplist, object, size);\n default:\n return NULL;\n }\n return NULL;\n}","target":0,"code_token_length":1003,"total_token_length":1334,"max_tokens_setting":2048} +{"idx":509588,"func":"static void test_fetch_column()\n{\n MYSQL_STMT *stmt;\n MYSQL_BIND my_bind[2];\n char c2[20], bc2[20];\n ulong l1, l2, bl1, bl2;\n int rc, c1, bc1;\n\n myheader(\"test_fetch_column\");\n\n rc= mysql_query(mysql, \"drop table if exists t1\");\n myquery(rc);\n\n rc= mysql_query(mysql, \"create table t1(c1 int primary key auto_increment, c2 char(10))\");\n myquery(rc);\n\n rc= mysql_query(mysql, \"insert into t1(c2) values('venu'), ('mysql')\");\n myquery(rc);\n\n stmt= mysql_simple_prepare(mysql, \"select * from t1 order by c2 desc\");\n check_stmt(stmt);\n\n bzero((char*) my_bind, sizeof(my_bind));\n my_bind[0].buffer_type= MYSQL_TYPE_LONG;\n my_bind[0].buffer= (void *)&bc1;\n my_bind[0].buffer_length= 0;\n my_bind[0].is_null= 0;\n my_bind[0].length= &bl1;\n my_bind[1].buffer_type= MYSQL_TYPE_STRING;\n my_bind[1].buffer= (void *)bc2;\n my_bind[1].buffer_length= 7;\n my_bind[1].is_null= 0;\n my_bind[1].length= &bl2;\n\n rc= mysql_stmt_execute(stmt);\n check_execute(stmt, rc);\n\n rc= mysql_stmt_bind_result(stmt, my_bind);\n check_execute(stmt, rc);\n\n rc= mysql_stmt_store_result(stmt);\n check_execute(stmt, rc);\n\n rc= mysql_stmt_fetch_column(stmt, my_bind, 1, 0); \/* No-op at this point *\/\n check_execute_r(stmt, rc);\n\n rc= mysql_stmt_fetch(stmt);\n check_execute(stmt, rc);\n\n if (!opt_silent)\n fprintf(stdout, \"\\n row 0: %d, %s\", bc1, bc2);\n\n c2[0]= '\\0'; l2= 0;\n my_bind[0].buffer_type= MYSQL_TYPE_STRING;\n my_bind[0].buffer= (void *)c2;\n my_bind[0].buffer_length= 7;\n my_bind[0].is_null= 0;\n my_bind[0].length= &l2;\n\n rc= mysql_stmt_fetch_column(stmt, my_bind, 1, 0);\n check_execute(stmt, rc);\n if (!opt_silent)\n fprintf(stdout, \"\\n col 1: %s(%ld)\", c2, l2);\n DIE_UNLESS(strncmp(c2, \"venu\", 4) == 0 && l2 == 4);\n\n c2[0]= '\\0'; l2= 0;\n rc= mysql_stmt_fetch_column(stmt, my_bind, 1, 0);\n check_execute(stmt, rc);\n if (!opt_silent)\n fprintf(stdout, \"\\n col 1: %s(%ld)\", c2, l2);\n DIE_UNLESS(strcmp(c2, \"venu\") == 0 && l2 == 4);\n\n c1= 0;\n my_bind[0].buffer_type= MYSQL_TYPE_LONG;\n my_bind[0].buffer= (void *)&c1;\n my_bind[0].buffer_length= 0;\n my_bind[0].is_null= 0;\n my_bind[0].length= &l1;\n\n rc= mysql_stmt_fetch_column(stmt, my_bind, 0, 0);\n check_execute(stmt, rc);\n if (!opt_silent)\n fprintf(stdout, \"\\n col 0: %d(%ld)\", c1, l1);\n DIE_UNLESS(c1 == 1 && l1 == 4);\n\n rc= mysql_stmt_fetch(stmt);\n check_execute(stmt, rc);\n\n if (!opt_silent)\n fprintf(stdout, \"\\n row 1: %d, %s\", bc1, bc2);\n\n c2[0]= '\\0'; l2= 0;\n my_bind[0].buffer_type= MYSQL_TYPE_STRING;\n my_bind[0].buffer= (void *)c2;\n my_bind[0].buffer_length= 7;\n my_bind[0].is_null= 0;\n my_bind[0].length= &l2;\n\n rc= mysql_stmt_fetch_column(stmt, my_bind, 1, 0);\n check_execute(stmt, rc);\n if (!opt_silent)\n fprintf(stdout, \"\\n col 1: %s(%ld)\", c2, l2);\n DIE_UNLESS(strncmp(c2, \"mysq\", 4) == 0 && l2 == 5);\n\n c2[0]= '\\0'; l2= 0;\n rc= mysql_stmt_fetch_column(stmt, my_bind, 1, 0);\n check_execute(stmt, rc);\n if (!opt_silent)\n fprintf(stdout, \"\\n col 1: %si(%ld)\", c2, l2);\n DIE_UNLESS(strcmp(c2, \"mysql\") == 0 && l2 == 5);\n\n c1= 0;\n my_bind[0].buffer_type= MYSQL_TYPE_LONG;\n my_bind[0].buffer= (void *)&c1;\n my_bind[0].buffer_length= 0;\n my_bind[0].is_null= 0;\n my_bind[0].length= &l1;\n\n rc= mysql_stmt_fetch_column(stmt, my_bind, 0, 0);\n check_execute(stmt, rc);\n if (!opt_silent)\n fprintf(stdout, \"\\n col 0: %d(%ld)\", c1, l1);\n DIE_UNLESS(c1 == 2 && l1 == 4);\n\n rc= mysql_stmt_fetch(stmt);\n DIE_UNLESS(rc == MYSQL_NO_DATA);\n\n rc= mysql_stmt_fetch_column(stmt, my_bind, 1, 0);\n check_execute_r(stmt, rc);\n\n mysql_stmt_close(stmt);\n myquery(mysql_query(mysql, \"drop table t1\"));\n}","target":0,"code_token_length":1322,"total_token_length":1653,"max_tokens_setting":2048} +{"idx":327400,"func":"static void create_gic(VirtBoardInfo *vbi, qemu_irq *pic, int type, bool secure)\n\n{\n\n \/* We create a standalone GIC *\/\n\n DeviceState *gicdev;\n\n SysBusDevice *gicbusdev;\n\n const char *gictype;\n\n int i;\n\n\n\n gictype = (type == 3) ? gicv3_class_name() : gic_class_name();\n\n\n\n gicdev = qdev_create(NULL, gictype);\n\n qdev_prop_set_uint32(gicdev, \"revision\", type);\n\n qdev_prop_set_uint32(gicdev, \"num-cpu\", smp_cpus);\n\n \/* Note that the num-irq property counts both internal and external\n\n * interrupts; there are always 32 of the former (mandated by GIC spec).\n\n *\/\n\n qdev_prop_set_uint32(gicdev, \"num-irq\", NUM_IRQS + 32);\n\n if (!kvm_irqchip_in_kernel()) {\n\n qdev_prop_set_bit(gicdev, \"has-security-extensions\", secure);\n\n }\n\n qdev_init_nofail(gicdev);\n\n gicbusdev = SYS_BUS_DEVICE(gicdev);\n\n sysbus_mmio_map(gicbusdev, 0, vbi->memmap[VIRT_GIC_DIST].base);\n\n if (type == 3) {\n\n sysbus_mmio_map(gicbusdev, 1, vbi->memmap[VIRT_GIC_REDIST].base);\n\n } else {\n\n sysbus_mmio_map(gicbusdev, 1, vbi->memmap[VIRT_GIC_CPU].base);\n\n }\n\n\n\n \/* Wire the outputs from each CPU's generic timer to the\n\n * appropriate GIC PPI inputs, and the GIC's IRQ output to\n\n * the CPU's IRQ input.\n\n *\/\n\n for (i = 0; i < smp_cpus; i++) {\n\n DeviceState *cpudev = DEVICE(qemu_get_cpu(i));\n\n int ppibase = NUM_IRQS + i * GIC_INTERNAL + GIC_NR_SGIS;\n\n int irq;\n\n \/* Mapping from the output timer irq lines from the CPU to the\n\n * GIC PPI inputs we use for the virt board.\n\n *\/\n\n const int timer_irq[] = {\n\n [GTIMER_PHYS] = ARCH_TIMER_NS_EL1_IRQ,\n\n [GTIMER_VIRT] = ARCH_TIMER_VIRT_IRQ,\n\n [GTIMER_HYP] = ARCH_TIMER_NS_EL2_IRQ,\n\n [GTIMER_SEC] = ARCH_TIMER_S_EL1_IRQ,\n\n };\n\n\n\n for (irq = 0; irq < ARRAY_SIZE(timer_irq); irq++) {\n\n qdev_connect_gpio_out(cpudev, irq,\n\n qdev_get_gpio_in(gicdev,\n\n ppibase + timer_irq[irq]));\n\n }\n\n\n\n sysbus_connect_irq(gicbusdev, i, qdev_get_gpio_in(cpudev, ARM_CPU_IRQ));\n\n sysbus_connect_irq(gicbusdev, i + smp_cpus,\n\n qdev_get_gpio_in(cpudev, ARM_CPU_FIQ));\n\n }\n\n\n\n for (i = 0; i < NUM_IRQS; i++) {\n\n pic[i] = qdev_get_gpio_in(gicdev, i);\n\n }\n\n\n\n fdt_add_gic_node(vbi, type);\n\n\n\n if (type == 3) {\n\n create_its(vbi, gicdev);\n\n } else {\n\n create_v2m(vbi, pic);\n\n }\n\n}\n","target":0,"code_token_length":746,"total_token_length":1077,"max_tokens_setting":2048} +{"idx":72081,"func":"static int _sx_sasl_gsasl_callback(Gsasl *gsasl_ctx, Gsasl_session *sd, Gsasl_property prop) {\n _sx_sasl_sess_t sctx = gsasl_session_hook_get(sd);\n _sx_sasl_t ctx = NULL;\n struct sx_sasl_creds_st creds = {NULL, NULL, NULL, NULL};\n char *value, *node, *host;\n int len, i;\n\n \/*\n * session hook data is not always available while its being set up,\n * also not needed in many of the cases below.\n *\/\n if(sctx != NULL) {\n ctx = sctx->ctx;\n }\n\n _sx_debug(ZONE, \"in _sx_sasl_gsasl_callback, property: %d\", prop);\n\n switch(prop) {\n case GSASL_PASSWORD:\n \/* GSASL_AUTHID, GSASL_AUTHZID, GSASL_REALM *\/\n assert(ctx);\n assert(ctx->cb);\n creds.authnid = gsasl_property_fast(sd, GSASL_AUTHID);\n creds.realm = gsasl_property_fast(sd, GSASL_REALM);\n if(!creds.authnid) return GSASL_NO_AUTHID;\n if(!creds.realm) return GSASL_NO_AUTHZID;\n if((ctx->cb)(sx_sasl_cb_GET_PASS, &creds, (void **)&value, sctx->s, ctx->cbarg) == sx_sasl_ret_OK) {\n gsasl_property_set(sd, GSASL_PASSWORD, value);\n }\n return GSASL_NEEDS_MORE;\n\n case GSASL_SERVICE:\n gsasl_property_set(sd, GSASL_SERVICE, \"xmpp\");\n return GSASL_OK;\n\n case GSASL_HOSTNAME:\n {\n char hostname[256];\n \/* get hostname *\/\n hostname[0] = '\\0';\n gethostname(hostname, 256);\n hostname[255] = '\\0';\n\n gsasl_property_set(sd, GSASL_HOSTNAME, hostname);\n }\n return GSASL_OK;\n\n case GSASL_VALIDATE_SIMPLE:\n \/* GSASL_AUTHID, GSASL_AUTHZID, GSASL_PASSWORD *\/\n assert(ctx);\n assert(ctx->cb);\n creds.authnid = gsasl_property_fast(sd, GSASL_AUTHID);\n creds.realm = gsasl_property_fast(sd, GSASL_REALM);\n creds.pass = gsasl_property_fast(sd, GSASL_PASSWORD);\n if(!creds.authnid) return GSASL_NO_AUTHID;\n if(!creds.realm) return GSASL_NO_AUTHZID;\n if(!creds.pass) return GSASL_NO_PASSWORD;\n if((ctx->cb)(sx_sasl_cb_CHECK_PASS, &creds, NULL, sctx->s, ctx->cbarg) == sx_sasl_ret_OK)\n return GSASL_OK;\n else\n return GSASL_AUTHENTICATION_ERROR;\n\n case GSASL_VALIDATE_GSSAPI:\n \/* GSASL_AUTHZID, GSASL_GSSAPI_DISPLAY_NAME *\/\n creds.authnid = gsasl_property_fast(sd, GSASL_GSSAPI_DISPLAY_NAME);\n if(!creds.authnid) return GSASL_NO_AUTHID;\n creds.authzid = gsasl_property_fast(sd, GSASL_AUTHZID);\n if(!creds.authzid) return GSASL_NO_AUTHZID;\n gsasl_property_set(sd, GSASL_AUTHID, creds.authnid);\n return GSASL_OK;\n\n case GSASL_VALIDATE_ANONYMOUS:\n \/* GSASL_ANONYMOUS_TOKEN *\/\n creds.authnid = gsasl_property_fast(sd, GSASL_ANONYMOUS_TOKEN);\n if(!creds.authnid) return GSASL_NO_ANONYMOUS_TOKEN;\n \/* set token as authid for later use *\/\n gsasl_property_set(sd, GSASL_AUTHID, creds.authnid);\n return GSASL_OK;\n\n case GSASL_VALIDATE_EXTERNAL:\n \/* GSASL_AUTHID *\/\n assert(ctx);\n assert(ctx->ext_id);\n creds.authzid = gsasl_property_fast(sd, GSASL_AUTHZID);\n _sx_debug(ZONE, \"sasl external\");\n _sx_debug(ZONE, \"sasl creds.authzid is '%s'\", creds.authzid);\n\n for (i = 0; i < SX_CONN_EXTERNAL_ID_MAX_COUNT; i++) {\n if (ctx->ext_id[i] == NULL)\n break;\n _sx_debug(ZONE, \"sasl ext_id(%d) is '%s'\", i, ctx->ext_id[i]);\n \/* XXX hackish.. detect c2s by existance of @ *\/\n value = strstr(ctx->ext_id[i], \"@\");\n\n if(value == NULL && creds.authzid != NULL && strcmp(ctx->ext_id[i], creds.authzid) == 0) {\n \/\/ s2s connection and it's valid\n \/* TODO Handle wildcards and other thigs from XEP-0178 *\/\n _sx_debug(ZONE, \"sasl ctx->ext_id doesn't have '@' in it. Assuming s2s\");\n return GSASL_OK;\n }\n if(value != NULL &&\n ((creds.authzid != NULL && strcmp(ctx->ext_id[i], creds.authzid) == 0) ||\n (creds.authzid == NULL)) ) {\n \/\/ c2s connection\n \/\/ creds.authzid == NULL condition is from XEP-0178 '=' auth reply\n\n \/\/ This should be freed by gsasl_finish() but I'm not sure\n \/\/ node = authnid\n len = value - ctx->ext_id[i];\n node = (char *) malloc(sizeof(char) * (len + 1)); \/\/ + null termination\n strncpy(node, ctx->ext_id[i], len);\n node[len] = '\\0'; \/\/ null terminate the string\n \/\/ host = realm\n len = strlen(value) - 1 + 1; \/\/ - the @ + null termination\n host = (char *) malloc(sizeof(char) * (len));\n strcpy(host, value + 1); \/\/ skip the @\n gsasl_property_set(sd, GSASL_AUTHID, node);\n gsasl_property_set(sd, GSASL_REALM, host);\n return GSASL_OK;\n }\n\n }\n return GSASL_AUTHENTICATION_ERROR;\n\n default:\n break;\n }\n\n return GSASL_NO_CALLBACK;\n}","target":0,"code_token_length":1396,"total_token_length":1727,"max_tokens_setting":2048} +{"idx":70633,"func":"static int b44_uncompress(EXRContext *s, const uint8_t *src, int compressed_size,\n int uncompressed_size, EXRThreadData *td) {\n const int8_t *sr = src;\n int stay_to_uncompress = compressed_size;\n int nb_b44_block_w, nb_b44_block_h;\n int index_tl_x, index_tl_y, index_out, index_tmp;\n uint16_t tmp_buffer[16]; \/* B44 use 4x4 half float pixel *\/\n int c, iY, iX, y, x;\n int target_channel_offset = 0;\n\n \/* calc B44 block count *\/\n nb_b44_block_w = td->xsize \/ 4;\n if ((td->xsize % 4) != 0)\n nb_b44_block_w++;\n\n nb_b44_block_h = td->ysize \/ 4;\n if ((td->ysize % 4) != 0)\n nb_b44_block_h++;\n\n for (c = 0; c < s->nb_channels; c++) {\n if (s->channels[c].pixel_type == EXR_HALF) {\/* B44 only compress half float data *\/\n for (iY = 0; iY < nb_b44_block_h; iY++) {\n for (iX = 0; iX < nb_b44_block_w; iX++) {\/* For each B44 block *\/\n if (stay_to_uncompress < 3) {\n av_log(s, AV_LOG_ERROR, \"Not enough data for B44A block: %d\", stay_to_uncompress);\n return AVERROR_INVALIDDATA;\n }\n\n if (src[compressed_size - stay_to_uncompress + 2] == 0xfc) { \/* B44A block *\/\n unpack_3(sr, tmp_buffer);\n sr += 3;\n stay_to_uncompress -= 3;\n } else {\/* B44 Block *\/\n if (stay_to_uncompress < 14) {\n av_log(s, AV_LOG_ERROR, \"Not enough data for B44 block: %d\", stay_to_uncompress);\n return AVERROR_INVALIDDATA;\n }\n unpack_14(sr, tmp_buffer);\n sr += 14;\n stay_to_uncompress -= 14;\n }\n\n \/* copy data to uncompress buffer (B44 block can exceed target resolution)*\/\n index_tl_x = iX * 4;\n index_tl_y = iY * 4;\n\n for (y = index_tl_y; y < FFMIN(index_tl_y + 4, td->ysize); y++) {\n for (x = index_tl_x; x < FFMIN(index_tl_x + 4, td->xsize); x++) {\n index_out = target_channel_offset * td->xsize + y * td->channel_line_size + 2 * x;\n index_tmp = (y-index_tl_y) * 4 + (x-index_tl_x);\n td->uncompressed_data[index_out] = tmp_buffer[index_tmp] & 0xff;\n td->uncompressed_data[index_out + 1] = tmp_buffer[index_tmp] >> 8;\n }\n }\n }\n }\n target_channel_offset += 2;\n } else {\/* Float or UINT 32 channel *\/\n if (stay_to_uncompress < td->ysize * td->xsize * 4) {\n av_log(s, AV_LOG_ERROR, \"Not enough data for uncompress channel: %d\", stay_to_uncompress);\n return AVERROR_INVALIDDATA;\n }\n\n for (y = 0; y < td->ysize; y++) {\n index_out = target_channel_offset * td->xsize + y * td->channel_line_size;\n memcpy(&td->uncompressed_data[index_out], sr, td->xsize * 4);\n sr += td->xsize * 4;\n }\n target_channel_offset += 4;\n\n stay_to_uncompress -= td->ysize * td->xsize * 4;\n }\n }\n\n return 0;\n}","target":0,"code_token_length":883,"total_token_length":1214,"max_tokens_setting":2048} +{"idx":103065,"func":"void xmc4400EthInitGpio(NetInterface *interface)\n{\n uint32_t temp;\n\n \/\/Configure ETH0.TX_EN (P0.4)\n temp = PORT0->IOCR4;\n temp &= ~PORT0_IOCR4_PC4_Msk;\n temp |= (17UL << PORT0_IOCR4_PC4_Pos);\n PORT0->IOCR4 = temp;\n\n \/\/Configure ETH0.MDIO (P2.0), ETH0.RXD0A (P2.2) and ETH0.RXD1A (P2.3)\n temp = PORT2->IOCR0;\n temp &= ~(PORT2_IOCR0_PC0_Msk | PORT2_IOCR0_PC2_Msk | PORT2_IOCR0_PC3_Msk);\n temp |= (0UL << PORT2_IOCR0_PC0_Pos) | (0UL << PORT2_IOCR0_PC2_Pos) | (0UL << PORT2_IOCR0_PC3_Pos);\n PORT2->IOCR0 = temp;\n\n \/\/Configure ETH0.RXERA (P2.4)and ETH0.MDC (P2.7)\n temp = PORT2->IOCR4;\n temp &= ~(PORT2_IOCR4_PC4_Msk | PORT2_IOCR4_PC7_Msk);\n temp |= (0UL << PORT2_IOCR4_PC4_Pos) | (17UL << PORT2_IOCR4_PC7_Pos);\n PORT2->IOCR4 = temp;\n\n \/\/Configure ETH0.TXD0 (P2.8) and ETH0.TXD1 (P2.9)\n temp = PORT2->IOCR8;\n temp &= ~(PORT2_IOCR8_PC8_Msk | PORT2_IOCR8_PC9_Msk);\n temp |= (17UL << PORT2_IOCR8_PC8_Pos) | (17UL << PORT2_IOCR8_PC9_Pos);\n PORT2->IOCR8 = temp;\n\n \/\/Configure ETH0.CLK_RMIIC (P15.8) and ETH0.CRS_DVC (P15.9)\n temp = PORT15->IOCR8;\n temp &= ~(PORT15_IOCR8_PC8_Msk | PORT15_IOCR8_PC9_Msk);\n temp |= (0UL << PORT15_IOCR8_PC8_Pos) | (0UL << PORT15_IOCR8_PC9_Pos);\n PORT15->IOCR8 = temp;\n\n \/\/Assign ETH_MDIO (P2.0) to HW0\n temp = PORT2->HWSEL & ~PORT2_HWSEL_HW0_Msk;\n PORT2->HWSEL = temp | (1UL << PORT2_HWSEL_HW0_Pos);\n\n \/\/Select output driver strength for ETH0.TX_EN (P2.5)\n temp = PORT2->PDR0;\n temp &= ~PORT2_PDR0_PD5_Msk;\n temp |= (0UL << PORT2_PDR0_PD5_Pos);\n PORT2->PDR0 = temp;\n\n \/\/Select output driver strength for ETH0.TXD0 (P2.8) and ETH0.TXD1 (P2.9)\n temp = PORT2->PDR1;\n temp &= ~(PORT2_PDR1_PD8_Msk | PORT2_PDR1_PD9_Msk);\n temp |= (0UL << PORT2_PDR1_PD8_Pos) | (0UL << PORT2_PDR1_PD9_Pos);\n PORT2->PDR1 = temp;\n\n \/\/Use ETH0.CLK_RMIIC (P15.8) and ETH0.CRS_DVC (P15.9) as digital inputs\n PORT15->PDISC &= ~(PORT15_PDISC_PDIS8_Msk | PORT15_PDISC_PDIS9_Msk);\n\n \/\/Select RMII operation mode\n ETH0_CON->CON = ETH_CON_INFSEL_Msk | ETH_CON_MDIO_B | ETH_CON_RXER_A |\n ETH_CON_CRS_DV_C | ETH_CON_CLK_RMII_C | ETH_CON_RXD1_A | ETH_CON_RXD0_A;\n}","target":0,"code_token_length":886,"total_token_length":1217,"max_tokens_setting":2048} +{"idx":490438,"func":"static GFINLINE void check_filter_error(GF_Filter *filter, GF_Err e, Bool for_reconnection)\n{\n\tGF_Err out_e = e;\n\tBool kill_filter = GF_FALSE;\n\tif (e>GF_OK) e = GF_OK;\n\telse if (e==GF_IP_NETWORK_EMPTY) e = GF_OK;\n\n\tif (e) {\n\t\tu64 diff;\n\t\tfilter->session->last_process_error = e;\n\n\t\tfilter->nb_errors ++;\n\t\tif (!filter->nb_consecutive_errors) filter->time_at_first_error = gf_sys_clock_high_res();\n\n\t\tfilter->nb_consecutive_errors ++;\n\t\tif (filter->nb_pck_io && !filter->session->in_final_flush)\n\t\t\tfilter->nb_consecutive_errors = 0;\n\t\t\/\/give it at most one second\n\t\tdiff = gf_sys_clock_high_res() - filter->time_at_first_error;\n\t\tif (diff >= 1000000) {\n\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_FILTER, (\"[Filter] %s in error \/ not responding properly: %d consecutive errors in \"LLU\" us with no packet discarded or sent\\n\\tdiscarding all inputs and notifying end of stream on all outputs\\n\", filter->name, filter->nb_consecutive_errors, diff));\n\t\t\tkill_filter = GF_TRUE;\n\t\t}\n\t} else {\n\t\tif ((!filter->nb_pck_io && filter->pending_packets && (filter->nb_pids_playing>0) && !gf_filter_connections_pending(filter)) || for_reconnection) {\n\t\t\tif (!filter->nb_consecutive_errors)\n\t\t\t\tfilter->time_at_first_error = gf_sys_clock_high_res();\n\t\t\tfilter->nb_consecutive_errors++;\n\n\t\t\tout_e = GF_SERVICE_ERROR;\n\t\t\tif (filter->nb_consecutive_errors >= 100000) {\n\t\t\t\tif (for_reconnection) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_FILTER, (\"[Filter] %s not responding properly: %d consecutive attempts at reconfiguring\\n\\tdiscarding all inputs and notifying end of stream on all outputs\\n\", filter->name, filter->nb_consecutive_errors));\n\t\t\t\t} else if (!filter->session->in_final_flush) {\n\t\t\t\t\tGF_LOG(GF_LOG_ERROR, GF_LOG_FILTER, (\"[Filter] %s not responding properly: %d consecutive process with no packet discarded or sent, but %d packets pending\\n\\tdiscarding all inputs and notifying end of stream on all outputs\\n\", filter->name, filter->nb_consecutive_errors, filter->pending_packets));\n\t\t\t\t} else {\n\t\t\t\t\tout_e = GF_OK;\n\t\t\t\t}\n\t\t\t\tkill_filter = GF_TRUE;\n\t\t\t}\n\t\t} else {\n\t\t\tfilter->nb_consecutive_errors = 0;\n\t\t\tfilter->nb_pck_io = 0;\n\t\t}\n\t}\n\n\tif (kill_filter) {\n\t\tu32 i;\n\t\tgf_mx_p(filter->tasks_mx);\n\t\tfor (i=0; inum_input_pids; i++) {\n\t\t\tGF_FilterPidInst *pidi = gf_list_get(filter->input_pids, i);\n\t\t\tgf_filter_pid_set_discard((GF_FilterPid *)pidi, GF_TRUE);\n\t\t}\n\t\tfor (i=0; inum_output_pids; i++) {\n\t\t\tGF_FilterPid *pid = gf_list_get(filter->output_pids, i);\n\t\t\tgf_filter_pid_set_eos(pid);\n\t\t}\n\t\tgf_mx_v(filter->tasks_mx);\n\t\tfilter->session->last_process_error = out_e;\n\t\tfilter->disabled = GF_TRUE;\n\t}\n}","target":0,"code_token_length":763,"total_token_length":1094,"max_tokens_setting":2048} +{"idx":352943,"func":"static av_always_inline void add_yblock(SnowContext *s, int sliced, slice_buffer *sb, IDWTELEM *dst, uint8_t *dst8, const uint8_t *obmc, int src_x, int src_y, int b_w, int b_h, int w, int h, int dst_stride, int src_stride, int obmc_stride, int b_x, int b_y, int add, int offset_dst, int plane_index){\n const int b_width = s->b_width << s->block_max_depth;\n const int b_height= s->b_height << s->block_max_depth;\n const int b_stride= b_width;\n BlockNode *lt= &s->block[b_x + b_y*b_stride];\n BlockNode *rt= lt+1;\n BlockNode *lb= lt+b_stride;\n BlockNode *rb= lb+1;\n uint8_t *block[4];\n int tmp_step= src_stride >= 7*MB_SIZE ? MB_SIZE : MB_SIZE*src_stride;\n uint8_t *tmp = s->scratchbuf;\n uint8_t *ptmp;\n int x,y;\n\n if(b_x<0){\n lt= rt;\n lb= rb;\n }else if(b_x + 1 >= b_width){\n rt= lt;\n rb= lb;\n }\n if(b_y<0){\n lt= lb;\n rt= rb;\n }else if(b_y + 1 >= b_height){\n lb= lt;\n rb= rt;\n }\n\n if(src_x<0){ \/\/FIXME merge with prev & always round internal width up to *16\n obmc -= src_x;\n b_w += src_x;\n if(!sliced && !offset_dst)\n dst -= src_x;\n src_x=0;\n }else if(src_x + b_w > w){\n b_w = w - src_x;\n }\n if(src_y<0){\n obmc -= src_y*obmc_stride;\n b_h += src_y;\n if(!sliced && !offset_dst)\n dst -= src_y*dst_stride;\n src_y=0;\n }else if(src_y + b_h> h){\n b_h = h - src_y;\n }\n\n if(b_w<=0 || b_h<=0) return;\n\n av_assert2(src_stride > 2*MB_SIZE + 5);\n\n if(!sliced && offset_dst)\n dst += src_x + src_y*dst_stride;\n dst8+= src_x + src_y*src_stride;\n\/\/ src += src_x + src_y*src_stride;\n\n ptmp= tmp + 3*tmp_step;\n block[0]= ptmp;\n ptmp+=tmp_step;\n ff_snow_pred_block(s, block[0], tmp, src_stride, src_x, src_y, b_w, b_h, lt, plane_index, w, h);\n\n if(same_block(lt, rt)){\n block[1]= block[0];\n }else{\n block[1]= ptmp;\n ptmp+=tmp_step;\n ff_snow_pred_block(s, block[1], tmp, src_stride, src_x, src_y, b_w, b_h, rt, plane_index, w, h);\n }\n\n if(same_block(lt, lb)){\n block[2]= block[0];\n }else if(same_block(rt, lb)){\n block[2]= block[1];\n }else{\n block[2]= ptmp;\n ptmp+=tmp_step;\n ff_snow_pred_block(s, block[2], tmp, src_stride, src_x, src_y, b_w, b_h, lb, plane_index, w, h);\n }\n\n if(same_block(lt, rb) ){\n block[3]= block[0];\n }else if(same_block(rt, rb)){\n block[3]= block[1];\n }else if(same_block(lb, rb)){\n block[3]= block[2];\n }else{\n block[3]= ptmp;\n ff_snow_pred_block(s, block[3], tmp, src_stride, src_x, src_y, b_w, b_h, rb, plane_index, w, h);\n }\n if(sliced){\n s->dwt.inner_add_yblock(obmc, obmc_stride, block, b_w, b_h, src_x,src_y, src_stride, sb, add, dst8);\n }else{\n for(y=0; y>1);\n const uint8_t *obmc3= obmc1+ obmc_stride*(obmc_stride>>1);\n const uint8_t *obmc4= obmc3+ (obmc_stride>>1);\n for(x=0; x>= 8 - FRAC_BITS;\n }\n if(add){\n v += dst[x + y*dst_stride];\n v = (v + (1<<(FRAC_BITS-1))) >> FRAC_BITS;\n if(v&(~255)) v= ~(v>>31);\n dst8[x + y*src_stride] = v;\n }else{\n dst[x + y*dst_stride] -= v;\n }\n }\n }\n }\n}","target":1,"code_token_length":1291,"total_token_length":1622,"max_tokens_setting":2048} +{"idx":80526,"func":"static pj_bool_t ssock_on_accept_complete (pj_ssl_sock_t *ssock_parent,\n\t\t\t\t\t pj_sock_t newsock,\n\t\t\t\t\t void *newconn,\n\t\t\t\t\t const pj_sockaddr_t *src_addr,\n\t\t\t\t\t int src_addr_len,\n\t\t\t\t\t pj_status_t accept_status)\n{\n pj_ssl_sock_t *ssock;\n#ifndef SSL_SOCK_IMP_USE_OWN_NETWORK\n pj_activesock_cb asock_cb;\n#endif\n pj_activesock_cfg asock_cfg;\n unsigned i;\n pj_status_t status;\n\n#ifndef SSL_SOCK_IMP_USE_OWN_NETWORK\n PJ_UNUSED_ARG(newconn);\n#endif\n\n if (accept_status != PJ_SUCCESS) {\n\tif (ssock_parent->param.cb.on_accept_complete2) {\n\t (*ssock_parent->param.cb.on_accept_complete2)(ssock_parent, NULL,\n\t\t\t\t\t\t \t src_addr,\n\t\t\t\t\t\t \t src_addr_len,\n\t\t\t\t\t\t \t accept_status);\n\t}\n\treturn PJ_TRUE;\n }\n\n \/* Create new SSL socket instance *\/\n status = pj_ssl_sock_create(ssock_parent->pool,\n\t\t\t\t&ssock_parent->newsock_param, &ssock);\n if (status != PJ_SUCCESS)\n\tgoto on_return;\n\n \/* Set parent and add ref count (avoid parent destroy during handshake) *\/\n ssock->parent = ssock_parent;\n if (ssock->parent->param.grp_lock)\n\tpj_grp_lock_add_ref(ssock->parent->param.grp_lock);\n\n \/* Update new SSL socket attributes *\/\n ssock->sock = newsock;\n ssock->is_server = PJ_TRUE;\n if (ssock_parent->cert) {\n\tstatus = pj_ssl_sock_set_certificate(ssock, ssock->pool, \n\t\t\t\t\t ssock_parent->cert);\n\tif (status != PJ_SUCCESS)\n\t goto on_return;\n }\n\n \/* Set local address *\/\n ssock->addr_len = src_addr_len;\n pj_sockaddr_cp(&ssock->local_addr, &ssock_parent->local_addr);\n\n \/* Set remote address *\/\n pj_sockaddr_cp(&ssock->rem_addr, src_addr);\n\n \/* Create SSL context *\/\n status = ssl_create(ssock);\n if (status != PJ_SUCCESS)\n\tgoto on_return;\n\n \/* Prepare read buffer *\/\n ssock->asock_rbuf = (void**)pj_pool_calloc(ssock->pool, \n\t\t\t\t\t ssock->param.async_cnt,\n\t\t\t\t\t sizeof(void*));\n if (!ssock->asock_rbuf) {\n\tstatus = PJ_ENOMEM;\n\tgoto on_return;\n }\n\n for (i = 0; iparam.async_cnt; ++i) {\n\tssock->asock_rbuf[i] = (void*) pj_pool_alloc(\n\t\t\t\t\t ssock->pool, \n\t\t\t\t\t ssock->param.read_buffer_size + \n\t\t\t\t\t sizeof(read_data_t*));\n\tif (!ssock->asock_rbuf[i]) {\n\t status = PJ_ENOMEM;\n\t goto on_return;\n\t}\n }\n\n \/* If listener socket has group lock, automatically create group lock\n * for the new socket.\n *\/\n if (ssock_parent->param.grp_lock) {\n\tpj_grp_lock_t *glock;\n\n\tstatus = pj_grp_lock_create(ssock->pool, NULL, &glock);\n\tif (status != PJ_SUCCESS)\n\t goto on_return;\n\n\tpj_grp_lock_add_ref(glock);\n\tssock->param.grp_lock = glock;\n\tpj_grp_lock_add_handler(ssock->param.grp_lock, ssock->pool, ssock,\n\t\t\t\tssl_on_destroy);\n }\n\n#ifdef SSL_SOCK_IMP_USE_OWN_NETWORK\n status = network_setup_connection(ssock, newconn);\n if (status != PJ_SUCCESS)\n\tgoto on_return;\n\n#else\n \/* Apply QoS, if specified *\/\n status = pj_sock_apply_qos2(ssock->sock, ssock->param.qos_type,\n\t\t\t\t&ssock->param.qos_params, 1, \n\t\t\t\tssock->pool->obj_name, NULL);\n if (status != PJ_SUCCESS && !ssock->param.qos_ignore_error)\n\tgoto on_return;\n\n \/* Apply socket options, if specified *\/\n if (ssock->param.sockopt_params.cnt) {\n\tstatus = pj_sock_setsockopt_params(ssock->sock, \n\t\t\t\t\t &ssock->param.sockopt_params);\n\tif (status != PJ_SUCCESS && !ssock->param.sockopt_ignore_error)\n\t goto on_return;\n }\n\n \/* Create active socket *\/\n pj_activesock_cfg_default(&asock_cfg);\n asock_cfg.grp_lock = ssock->param.grp_lock;\n asock_cfg.async_cnt = ssock->param.async_cnt;\n asock_cfg.concurrency = ssock->param.concurrency;\n asock_cfg.whole_data = PJ_TRUE;\n\n pj_bzero(&asock_cb, sizeof(asock_cb));\n asock_cb.on_data_read = asock_on_data_read;\n asock_cb.on_data_sent = asock_on_data_sent;\n\n status = pj_activesock_create(ssock->pool,\n\t\t\t\t ssock->sock, \n\t\t\t\t ssock->param.sock_type,\n\t\t\t\t &asock_cfg,\n\t\t\t\t ssock->param.ioqueue, \n\t\t\t\t &asock_cb,\n\t\t\t\t ssock,\n\t\t\t\t &ssock->asock);\n\n if (status != PJ_SUCCESS)\n\tgoto on_return;\n\n \/* Start read *\/\n status = pj_activesock_start_read2(ssock->asock, ssock->pool, \n\t\t\t\t (unsigned)ssock->param.read_buffer_size,\n\t\t\t\t ssock->asock_rbuf,\n\t\t\t\t PJ_IOQUEUE_ALWAYS_ASYNC);\n if (status != PJ_SUCCESS)\n\tgoto on_return;\n#endif\n\n \/* Update local address *\/\n status = get_localaddr(ssock, &ssock->local_addr, &ssock->addr_len);\n if (status != PJ_SUCCESS) {\n\t\/* This fails on few envs, e.g: win IOCP, just tolerate this and\n\t * use parent local address instead.\n\t *\/\n\tpj_sockaddr_cp(&ssock->local_addr, &ssock_parent->local_addr);\n }\n\n \/* Prepare write\/send state *\/\n pj_assert(ssock->send_buf.max_len == 0);\n ssock->send_buf.buf = (char*)\n\t\t\t pj_pool_alloc(ssock->pool, \n\t\t\t\t\tssock->param.send_buffer_size);\n if (!ssock->send_buf.buf)\n return PJ_ENOMEM;\n\n ssock->send_buf.max_len = ssock->param.send_buffer_size;\n ssock->send_buf.start = ssock->send_buf.buf;\n ssock->send_buf.len = 0;\n\n \/* Start handshake timer *\/\n if (ssock->param.timer_heap && (ssock->param.timeout.sec != 0 ||\n\tssock->param.timeout.msec != 0))\n {\n\tpj_assert(ssock->timer.id == TIMER_NONE);\n\tstatus = pj_timer_heap_schedule_w_grp_lock(ssock->param.timer_heap, \n\t\t\t\t\t\t &ssock->timer,\n\t\t\t\t\t\t &ssock->param.timeout,\n\t\t\t\t\t\t TIMER_HANDSHAKE_TIMEOUT,\n\t\t\t\t\t\t ssock->param.grp_lock);\n\tif (status != PJ_SUCCESS) {\n\t ssock->timer.id = TIMER_NONE;\n\t status = PJ_SUCCESS;\n\t}\n }\n\n \/* Start SSL handshake *\/\n ssock->ssl_state = SSL_STATE_HANDSHAKING;\n ssl_set_state(ssock, PJ_TRUE);\n status = ssl_do_handshake(ssock);\n\non_return:\n if (ssock && status != PJ_EPENDING) {\n\ton_handshake_complete(ssock, status);\n }\n\n \/* Must return PJ_TRUE whatever happened, as we must continue listening *\/\n return PJ_TRUE;\n}","target":0,"code_token_length":1580,"total_token_length":1911,"max_tokens_setting":2048} +{"idx":265300,"func":"rfbBool rfbSendFileTransferChunk(rfbClientPtr cl)\n{\n \/* Allocate buffer for compression *\/\n char readBuf[sz_rfbBlockSize];\n int bytesRead=0;\n int retval=0;\n fd_set wfds;\n struct timeval tv;\n int n;\n#ifdef LIBVNCSERVER_HAVE_LIBZ\n unsigned char compBuf[sz_rfbBlockSize + 1024];\n unsigned long nMaxCompSize = sizeof(compBuf);\n int nRetC = 0;\n#endif\n\n \/*\n * Don't close the client if we get into this one because \n * it is called from many places to service file transfers.\n * Note that permitFileTransfer is checked first.\n *\/\n if (cl->screen->permitFileTransfer != TRUE ||\n (cl->screen->getFileTransferPermission != NULL\n && cl->screen->getFileTransferPermission(cl) != TRUE)) { \n\t\treturn TRUE;\n }\n\n \/* If not sending, or no file open... Return as if we sent something! *\/\n if ((cl->fileTransfer.fd!=-1) && (cl->fileTransfer.sending==1))\n {\n\tFD_ZERO(&wfds);\n FD_SET(cl->sock, &wfds);\n\n \/* return immediately *\/\n\ttv.tv_sec = 0; \n\ttv.tv_usec = 0;\n\tn = select(cl->sock + 1, NULL, &wfds, NULL, &tv);\n\n\tif (n<0) {\n#ifdef WIN32\n\t errno=WSAGetLastError();\n#endif\n rfbLog(\"rfbSendFileTransferChunk() select failed: %s\\n\", strerror(errno));\n\t}\n \/* We have space on the transmit queue *\/\n\tif (n > 0)\n\t{\n bytesRead = read(cl->fileTransfer.fd, readBuf, sz_rfbBlockSize);\n switch (bytesRead) {\n case 0:\n \/*\n rfbLog(\"rfbSendFileTransferChunk(): End-Of-File Encountered\\n\");\n *\/\n retval = rfbSendFileTransferMessage(cl, rfbEndOfFile, 0, 0, 0, NULL);\n close(cl->fileTransfer.fd);\n cl->fileTransfer.fd = -1;\n cl->fileTransfer.sending = 0;\n cl->fileTransfer.receiving = 0;\n return retval;\n case -1:\n \/* TODO : send an error msg to the client... *\/\n#ifdef WIN32\n\t errno=WSAGetLastError();\n#endif\n rfbLog(\"rfbSendFileTransferChunk(): %s\\n\",strerror(errno));\n retval = rfbSendFileTransferMessage(cl, rfbAbortFileTransfer, 0, 0, 0, NULL);\n close(cl->fileTransfer.fd);\n cl->fileTransfer.fd = -1;\n cl->fileTransfer.sending = 0;\n cl->fileTransfer.receiving = 0;\n return retval;\n default:\n \/*\n rfbLog(\"rfbSendFileTransferChunk(): Read %d bytes\\n\", bytesRead);\n *\/\n if (!cl->fileTransfer.compressionEnabled)\n return rfbSendFileTransferMessage(cl, rfbFilePacket, 0, 0, bytesRead, readBuf);\n else\n {\n#ifdef LIBVNCSERVER_HAVE_LIBZ\n nRetC = compress(compBuf, &nMaxCompSize, (unsigned char *)readBuf, bytesRead);\n \/*\n rfbLog(\"Compressed the packet from %d -> %d bytes\\n\", nMaxCompSize, bytesRead);\n *\/\n \n if ((nRetC==0) && (nMaxCompSize 5 && is_dir_sep(end[-5]) &&\n\t !strncmp(end - 4, \".git\", 4)) {\n\t\tend -= 5;\n\t\twhile (start < end && is_dir_sep(end[-1]))\n\t\t\tend--;\n\t}\n\n\t\/*\n\t * Strip trailing port number if we've got only a\n\t * hostname (that is, there is no dir separator but a\n\t * colon). This check is required such that we do not\n\t * strip URI's like '\/foo\/bar:2222.git', which should\n\t * result in a dir '2222' being guessed due to backwards\n\t * compatibility.\n\t *\/\n\tif (memchr(start, '\/', end - start) == NULL\n\t && memchr(start, ':', end - start) != NULL) {\n\t\tptr = end;\n\t\twhile (start < ptr && isdigit(ptr[-1]) && ptr[-1] != ':')\n\t\t\tptr--;\n\t\tif (start < ptr && ptr[-1] == ':')\n\t\t\tend = ptr - 1;\n\t}\n\n\t\/*\n\t * Find last component. To remain backwards compatible we\n\t * also regard colons as path separators, such that\n\t * cloning a repository 'foo:bar.git' would result in a\n\t * directory 'bar' being guessed.\n\t *\/\n\tptr = end;\n\twhile (start < ptr && !is_dir_sep(ptr[-1]) && ptr[-1] != ':')\n\t\tptr--;\n\tstart = ptr;\n\n\t\/*\n\t * Strip .{bundle,git}.\n\t *\/\n\tlen = end - start;\n\tstrip_suffix_mem(start, &len, is_bundle ? \".bundle\" : \".git\");\n\n\tif (!len || (len == 1 && *start == '\/'))\n\t\tdie(_(\"No directory name could be guessed.\\n\"\n\t\t \"Please specify a directory on the command line\"));\n\n\tif (is_bare)\n\t\tdir = xstrfmt(\"%.*s.git\", (int)len, start);\n\telse\n\t\tdir = xstrndup(start, len);\n\t\/*\n\t * Replace sequences of 'control' characters and whitespace\n\t * with one ascii space, remove leading and trailing spaces.\n\t *\/\n\tif (*dir) {\n\t\tchar *out = dir;\n\t\tint prev_space = 1 \/* strip leading whitespace *\/;\n\t\tfor (end = dir; *end; ++end) {\n\t\t\tchar ch = *end;\n\t\t\tif ((unsigned char)ch < '\\x20')\n\t\t\t\tch = '\\x20';\n\t\t\tif (isspace(ch)) {\n\t\t\t\tif (prev_space)\n\t\t\t\t\tcontinue;\n\t\t\t\tprev_space = 1;\n\t\t\t} else\n\t\t\t\tprev_space = 0;\n\t\t\t*out++ = ch;\n\t\t}\n\t\t*out = '\\0';\n\t\tif (out > dir && prev_space)\n\t\t\tout[-1] = '\\0';\n\t}\n\treturn dir;\n}","target":0,"code_token_length":795,"total_token_length":1126,"max_tokens_setting":2048} +{"idx":35420,"func":"static int cdxl_decode_frame(AVCodecContext *avctx, void *data,\n int *got_frame, AVPacket *pkt)\n{\n CDXLVideoContext *c = avctx->priv_data;\n AVFrame * const p = data;\n int ret, w, h, encoding, aligned_width, buf_size = pkt->size;\n const uint8_t *buf = pkt->data;\n\n if (buf_size < 32)\n return AVERROR_INVALIDDATA;\n encoding = buf[1] & 7;\n c->format = buf[1] & 0xE0;\n w = AV_RB16(&buf[14]);\n h = AV_RB16(&buf[16]);\n c->bpp = buf[19];\n c->palette_size = AV_RB16(&buf[20]);\n c->palette = buf + 32;\n c->video = c->palette + c->palette_size;\n c->video_size = buf_size - c->palette_size - 32;\n\n if (c->palette_size > 512)\n return AVERROR_INVALIDDATA;\n if (buf_size < c->palette_size + 32)\n return AVERROR_INVALIDDATA;\n if (c->bpp < 1)\n return AVERROR_INVALIDDATA;\n if (c->format != BIT_PLANAR && c->format != BIT_LINE && c->format != CHUNKY) {\n avpriv_request_sample(avctx, \"Pixel format 0x%0x\", c->format);\n return AVERROR_PATCHWELCOME;\n }\n\n if ((ret = ff_set_dimensions(avctx, w, h)) < 0)\n return ret;\n\n if (c->format == CHUNKY)\n aligned_width = avctx->width;\n else\n aligned_width = FFALIGN(c->avctx->width, 16);\n c->padded_bits = aligned_width - c->avctx->width;\n if (c->video_size < aligned_width * avctx->height * (int64_t)c->bpp \/ 8)\n return AVERROR_INVALIDDATA;\n if (!encoding && c->palette_size && c->bpp <= 8 && c->format != CHUNKY) {\n avctx->pix_fmt = AV_PIX_FMT_PAL8;\n } else if (encoding == 1 && (c->bpp == 6 || c->bpp == 8) && c->format != CHUNKY) {\n if (c->palette_size != (1 << (c->bpp - 1)))\n return AVERROR_INVALIDDATA;\n avctx->pix_fmt = AV_PIX_FMT_BGR24;\n } else if (!encoding && c->bpp == 24 && c->format == CHUNKY &&\n !c->palette_size) {\n avctx->pix_fmt = AV_PIX_FMT_RGB24;\n } else {\n avpriv_request_sample(avctx, \"Encoding %d, bpp %d and format 0x%x\",\n encoding, c->bpp, c->format);\n return AVERROR_PATCHWELCOME;\n }\n\n if ((ret = ff_get_buffer(avctx, p, 0)) < 0)\n return ret;\n p->pict_type = AV_PICTURE_TYPE_I;\n\n if (encoding) {\n av_fast_padded_malloc(&c->new_video, &c->new_video_size,\n h * w + AV_INPUT_BUFFER_PADDING_SIZE);\n if (!c->new_video)\n return AVERROR(ENOMEM);\n if (c->bpp == 8)\n cdxl_decode_ham8(c, p);\n else\n cdxl_decode_ham6(c, p);\n } else if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {\n cdxl_decode_rgb(c, p);\n } else {\n cdxl_decode_raw(c, p);\n }\n *got_frame = 1;\n\n return buf_size;\n}","target":0,"code_token_length":853,"total_token_length":1184,"max_tokens_setting":2048} +{"idx":55720,"func":"flatpak_pull_from_bundle (OstreeRepo *repo,\n GFile *file,\n const char *remote,\n const char *ref,\n gboolean require_gpg_signature,\n GCancellable *cancellable,\n GError **error)\n{\n gsize metadata_size = 0;\n g_autofree char *metadata_contents = NULL;\n g_autofree char *to_checksum = NULL;\n g_autoptr(GFile) root = NULL;\n g_autoptr(GFile) metadata_file = NULL;\n g_autoptr(GInputStream) in = NULL;\n g_autoptr(OstreeGpgVerifyResult) gpg_result = NULL;\n g_autoptr(GError) my_error = NULL;\n g_autoptr(GVariant) metadata = NULL;\n gboolean metadata_valid;\n g_autofree char *remote_collection_id = NULL;\n g_autofree char *collection_id = NULL;\n\n metadata = flatpak_bundle_load (file, &to_checksum, NULL, NULL, NULL, &metadata_contents, NULL, NULL, &collection_id, error);\n if (metadata == NULL)\n return FALSE;\n\n metadata_size = strlen (metadata_contents);\n\n if (!ostree_repo_get_remote_option (repo, remote, \"collection-id\", NULL,\n &remote_collection_id, NULL))\n remote_collection_id = NULL;\n\n if (remote_collection_id != NULL && collection_id != NULL &&\n strcmp (remote_collection_id, collection_id) != 0)\n return flatpak_fail_error (error, FLATPAK_ERROR_INVALID_DATA, _(\"Collection \u2018%s\u2019 of bundle doesn\u2019t match collection \u2018%s\u2019 of remote\"),\n collection_id, remote_collection_id);\n\n if (!ostree_repo_prepare_transaction (repo, NULL, cancellable, error))\n return FALSE;\n\n \/* Don\u2019t need to set the collection ID here, since the remote binds this ref to the collection. *\/\n ostree_repo_transaction_set_ref (repo, remote, ref, to_checksum);\n\n if (!ostree_repo_static_delta_execute_offline (repo,\n file,\n FALSE,\n cancellable,\n error))\n return FALSE;\n\n gpg_result = ostree_repo_verify_commit_ext (repo, to_checksum,\n NULL, NULL, cancellable, &my_error);\n if (gpg_result == NULL)\n {\n \/* no gpg signature, we ignore this *if* there is no gpg key\n * specified in the bundle or by the user *\/\n if (g_error_matches (my_error, OSTREE_GPG_ERROR, OSTREE_GPG_ERROR_NO_SIGNATURE) &&\n !require_gpg_signature)\n {\n g_clear_error (&my_error);\n }\n else\n {\n g_propagate_error (error, g_steal_pointer (&my_error));\n return FALSE;\n }\n }\n else\n {\n \/* If there is no valid gpg signature we fail, unless there is no gpg\n key specified (on the command line or in the file) because then we\n trust the source bundle. *\/\n if (ostree_gpg_verify_result_count_valid (gpg_result) == 0 &&\n require_gpg_signature)\n return flatpak_fail_error (error, FLATPAK_ERROR_UNTRUSTED, _(\"GPG signatures found, but none are in trusted keyring\"));\n }\n\n if (!ostree_repo_read_commit (repo, to_checksum, &root, NULL, NULL, error))\n return FALSE;\n\n if (!ostree_repo_commit_transaction (repo, NULL, cancellable, error))\n return FALSE;\n\n \/* We ensure that the actual installed metadata matches the one in the\n header, because you may have made decisions on whether to install it or not\n based on that data. *\/\n metadata_file = g_file_resolve_relative_path (root, \"metadata\");\n in = (GInputStream *) g_file_read (metadata_file, cancellable, NULL);\n if (in != NULL)\n {\n g_autoptr(GMemoryOutputStream) data_stream = (GMemoryOutputStream *) g_memory_output_stream_new_resizable ();\n\n if (g_output_stream_splice (G_OUTPUT_STREAM (data_stream), in,\n G_OUTPUT_STREAM_SPLICE_CLOSE_SOURCE,\n cancellable, error) < 0)\n return FALSE;\n\n metadata_valid =\n metadata_contents != NULL &&\n metadata_size == g_memory_output_stream_get_data_size (data_stream) &&\n memcmp (metadata_contents, g_memory_output_stream_get_data (data_stream), metadata_size) == 0;\n }\n else\n {\n metadata_valid = (metadata_contents == NULL);\n }\n\n if (!metadata_valid)\n {\n \/* Immediately remove this broken commit *\/\n ostree_repo_set_ref_immediate (repo, remote, ref, NULL, cancellable, error);\n return flatpak_fail_error (error, FLATPAK_ERROR_INVALID_DATA, _(\"Metadata in header and app are inconsistent\"));\n }\n\n return TRUE;\n}","target":0,"code_token_length":1049,"total_token_length":1380,"max_tokens_setting":2048} +{"idx":251496,"func":"ssh_set_newkeys(struct ssh *ssh, int mode)\n{\n\tstruct session_state *state = ssh->state;\n\tstruct sshenc *enc;\n\tstruct sshmac *mac;\n\tstruct sshcomp *comp;\n\tstruct sshcipher_ctx *cc;\n\tu_int64_t *max_blocks;\n\tconst char *wmsg;\n\tint r, crypt_type;\n\n\tdebug2(\"set_newkeys: mode %d\", mode);\n\n\tif (mode == MODE_OUT) {\n\t\tcc = &state->send_context;\n\t\tcrypt_type = CIPHER_ENCRYPT;\n\t\tstate->p_send.packets = state->p_send.blocks = 0;\n\t\tmax_blocks = &state->max_blocks_out;\n\t} else {\n\t\tcc = &state->receive_context;\n\t\tcrypt_type = CIPHER_DECRYPT;\n\t\tstate->p_read.packets = state->p_read.blocks = 0;\n\t\tmax_blocks = &state->max_blocks_in;\n\t}\n\tif (state->newkeys[mode] != NULL) {\n\t\tdebug(\"set_newkeys: rekeying\");\n\t\tif ((r = cipher_cleanup(cc)) != 0)\n\t\t\treturn r;\n\t\tenc = &state->newkeys[mode]->enc;\n\t\tmac = &state->newkeys[mode]->mac;\n\t\tcomp = &state->newkeys[mode]->comp;\n\t\tmac_clear(mac);\n\t\texplicit_bzero(enc->iv, enc->iv_len);\n\t\texplicit_bzero(enc->key, enc->key_len);\n\t\texplicit_bzero(mac->key, mac->key_len);\n\t\tfree(enc->name);\n\t\tfree(enc->iv);\n\t\tfree(enc->key);\n\t\tfree(mac->name);\n\t\tfree(mac->key);\n\t\tfree(comp->name);\n\t\tfree(state->newkeys[mode]);\n\t}\n\t\/* move newkeys from kex to state *\/\n\tif ((state->newkeys[mode] = ssh->kex->newkeys[mode]) == NULL)\n\t\treturn SSH_ERR_INTERNAL_ERROR;\n\tssh->kex->newkeys[mode] = NULL;\n\tenc = &state->newkeys[mode]->enc;\n\tmac = &state->newkeys[mode]->mac;\n\tcomp = &state->newkeys[mode]->comp;\n\tif (cipher_authlen(enc->cipher) == 0) {\n\t\tif ((r = mac_init(mac)) != 0)\n\t\t\treturn r;\n\t}\n\tmac->enabled = 1;\n\tDBG(debug(\"cipher_init_context: %d\", mode));\n\tif ((r = cipher_init(cc, enc->cipher, enc->key, enc->key_len,\n\t enc->iv, enc->iv_len, crypt_type)) != 0)\n\t\treturn r;\n\tif (!state->cipher_warning_done &&\n\t (wmsg = cipher_warning_message(cc)) != NULL) {\n\t\terror(\"Warning: %s\", wmsg);\n\t\tstate->cipher_warning_done = 1;\n\t}\n\t\/* Deleting the keys does not gain extra security *\/\n\t\/* explicit_bzero(enc->iv, enc->block_size);\n\t explicit_bzero(enc->key, enc->key_len);\n\t explicit_bzero(mac->key, mac->key_len); *\/\n\tif ((comp->type == COMP_ZLIB ||\n\t (comp->type == COMP_DELAYED &&\n\t state->after_authentication)) && comp->enabled == 0) {\n\t\tif ((r = ssh_packet_init_compression(ssh)) < 0)\n\t\t\treturn r;\n\t\tif (mode == MODE_OUT) {\n\t\t\tif ((r = start_compression_out(ssh, 6)) != 0)\n\t\t\t\treturn r;\n\t\t} else {\n\t\t\tif ((r = start_compression_in(ssh)) != 0)\n\t\t\t\treturn r;\n\t\t}\n\t\tcomp->enabled = 1;\n\t}\n\t\/*\n\t * The 2^(blocksize*2) limit is too expensive for 3DES,\n\t * blowfish, etc, so enforce a 1GB limit for small blocksizes.\n\t *\/\n\tif (enc->block_size >= 16)\n\t\t*max_blocks = (u_int64_t)1 << (enc->block_size*2);\n\telse\n\t\t*max_blocks = ((u_int64_t)1 << 30) \/ enc->block_size;\n\tif (state->rekey_limit)\n\t\t*max_blocks = MIN(*max_blocks,\n\t\t state->rekey_limit \/ enc->block_size);\n\treturn 0;\n}\n","target":0,"code_token_length":925,"total_token_length":1256,"max_tokens_setting":2048} +{"idx":507461,"func":"int TS_RESP_verify_signature(PKCS7 *token, STACK_OF(X509) *certs,\n\t\t\t X509_STORE *store, X509 **signer_out)\n\t{\n\tSTACK_OF(PKCS7_SIGNER_INFO) *sinfos = NULL;\n\tPKCS7_SIGNER_INFO *si;\n\tSTACK_OF(X509) *signers = NULL;\n\tX509\t*signer;\n\tSTACK_OF(X509) *chain = NULL;\n\tchar\tbuf[4096];\n\tint\ti, j = 0, ret = 0;\n\tBIO\t*p7bio = NULL;\n\n\t\/* Some sanity checks first. *\/\n\tif (!token)\n\t\t{\n\t\tTSerr(TS_F_TS_RESP_VERIFY_SIGNATURE, TS_R_INVALID_NULL_POINTER);\n\t\tgoto err;\n\t\t}\n\n\t\/* Check for the correct content type *\/\n\tif(!PKCS7_type_is_signed(token))\n\t\t{\n\t\tTSerr(TS_F_TS_RESP_VERIFY_SIGNATURE, TS_R_WRONG_CONTENT_TYPE);\n\t\tgoto err;\n\t\t}\n\n\t\/* Check if there is one and only one signer. *\/\n\tsinfos = PKCS7_get_signer_info(token);\n\tif (!sinfos || sk_PKCS7_SIGNER_INFO_num(sinfos) != 1)\n\t\t{\n\t\tTSerr(TS_F_TS_RESP_VERIFY_SIGNATURE,\n\t\t TS_R_THERE_MUST_BE_ONE_SIGNER);\n\t\tgoto err;\n\t\t}\n\tsi = sk_PKCS7_SIGNER_INFO_value(sinfos, 0);\n\n\t\/* Check for no content: no data to verify signature. *\/\n\tif (PKCS7_get_detached(token))\n\t\t{\n\t\tTSerr(TS_F_TS_RESP_VERIFY_SIGNATURE, TS_R_NO_CONTENT);\n\t\tgoto err;\n\t\t}\n\t\n\t\/* Get hold of the signer certificate, search only internal\n\t certificates if it was requested. *\/\n\tsigners = PKCS7_get0_signers(token, certs, 0);\n\tif (!signers || sk_X509_num(signers) != 1) goto err;\n\tsigner = sk_X509_value(signers, 0);\n\n\t\/* Now verify the certificate. *\/\n\tif (!TS_verify_cert(store, certs, signer, &chain)) goto err;\n\n\t\/* Check if the signer certificate is consistent with the\n\t ESS extension. *\/\n\tif (!TS_check_signing_certs(si, chain)) goto err;\n\n\t\/* Creating the message digest. *\/\n\tp7bio = PKCS7_dataInit(token, NULL);\n\n\t\/* We now have to 'read' from p7bio to calculate digests etc. *\/\n\twhile ((i = BIO_read(p7bio,buf,sizeof(buf))) > 0);\n\n\t\/* Verifying the signature. *\/\n\tj = PKCS7_signatureVerify(p7bio, token, si, signer);\n\tif (j <= 0)\n\t\t{\n\t\tTSerr(TS_F_TS_RESP_VERIFY_SIGNATURE, TS_R_SIGNATURE_FAILURE);\n\t\tgoto err;\n\t\t}\n\n\t\/* Return the signer certificate if needed. *\/\n\tif (signer_out)\n\t\t{\n\t\t*signer_out = signer;\n\t\tCRYPTO_add(&signer->references, 1, CRYPTO_LOCK_X509);\n\t\t}\n\n\tret = 1;\n\n err:\n\tBIO_free_all(p7bio);\n\tsk_X509_pop_free(chain, X509_free);\n\tsk_X509_free(signers);\n\n\treturn ret;\n\t}","target":0,"code_token_length":719,"total_token_length":1050,"max_tokens_setting":2048} +{"idx":7453,"func":"static int rose_parse_national(unsigned char *p, struct rose_facilities_struct *facilities, int len)\n{\n\tunsigned char *pt;\n\tunsigned char l, lg, n = 0;\n\tint fac_national_digis_received = 0;\n\n\tdo {\n\t\tswitch (*p & 0xC0) {\n\t\tcase 0x00:\n\t\t\tp += 2;\n\t\t\tn += 2;\n\t\t\tlen -= 2;\n\t\t\tbreak;\n\n\t\tcase 0x40:\n\t\t\tif (*p == FAC_NATIONAL_RAND)\n\t\t\t\tfacilities->rand = ((p[1] << 8) & 0xFF00) + ((p[2] << 0) & 0x00FF);\n\t\t\tp += 3;\n\t\t\tn += 3;\n\t\t\tlen -= 3;\n\t\t\tbreak;\n\n\t\tcase 0x80:\n\t\t\tp += 4;\n\t\t\tn += 4;\n\t\t\tlen -= 4;\n\t\t\tbreak;\n\n\t\tcase 0xC0:\n\t\t\tl = p[1];\n\t\t\tif (*p == FAC_NATIONAL_DEST_DIGI) {\n\t\t\t\tif (!fac_national_digis_received) {\n\t\t\t\t\tmemcpy(&facilities->source_digis[0], p + 2, AX25_ADDR_LEN);\n\t\t\t\t\tfacilities->source_ndigis = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (*p == FAC_NATIONAL_SRC_DIGI) {\n\t\t\t\tif (!fac_national_digis_received) {\n\t\t\t\t\tmemcpy(&facilities->dest_digis[0], p + 2, AX25_ADDR_LEN);\n\t\t\t\t\tfacilities->dest_ndigis = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if (*p == FAC_NATIONAL_FAIL_CALL) {\n\t\t\t\tmemcpy(&facilities->fail_call, p + 2, AX25_ADDR_LEN);\n\t\t\t}\n\t\t\telse if (*p == FAC_NATIONAL_FAIL_ADD) {\n\t\t\t\tmemcpy(&facilities->fail_addr, p + 3, ROSE_ADDR_LEN);\n\t\t\t}\n\t\t\telse if (*p == FAC_NATIONAL_DIGIS) {\n\t\t\t\tfac_national_digis_received = 1;\n\t\t\t\tfacilities->source_ndigis = 0;\n\t\t\t\tfacilities->dest_ndigis = 0;\n\t\t\t\tfor (pt = p + 2, lg = 0 ; lg < l ; pt += AX25_ADDR_LEN, lg += AX25_ADDR_LEN) {\n\t\t\t\t\tif (pt[6] & AX25_HBIT) {\n\t\t\t\t\t\tif (facilities->dest_ndigis >= ROSE_MAX_DIGIS)\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\tmemcpy(&facilities->dest_digis[facilities->dest_ndigis++], pt, AX25_ADDR_LEN);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (facilities->source_ndigis >= ROSE_MAX_DIGIS)\n\t\t\t\t\t\t\treturn -1;\n\t\t\t\t\t\tmemcpy(&facilities->source_digis[facilities->source_ndigis++], pt, AX25_ADDR_LEN);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tp += l + 2;\n\t\t\tn += l + 2;\n\t\t\tlen -= l + 2;\n\t\t\tbreak;\n\t\t}\n\t} while (*p != 0x00 && len > 0);\n\n\treturn n;\n}","target":1,"code_token_length":704,"total_token_length":1035,"max_tokens_setting":2048} +{"idx":152174,"func":"static int construct_alloc_key(struct keyring_search_context *ctx,\n\t\t\t struct key *dest_keyring,\n\t\t\t unsigned long flags,\n\t\t\t struct key_user *user,\n\t\t\t struct key **_key)\n{\n\tstruct assoc_array_edit *edit;\n\tstruct key *key;\n\tkey_perm_t perm;\n\tkey_ref_t key_ref;\n\tint ret;\n\n\tkenter(\"%s,%s,,,\",\n\t ctx->index_key.type->name, ctx->index_key.description);\n\n\t*_key = NULL;\n\tmutex_lock(&user->cons_lock);\n\n\tperm = KEY_POS_VIEW | KEY_POS_SEARCH | KEY_POS_LINK | KEY_POS_SETATTR;\n\tperm |= KEY_USR_VIEW;\n\tif (ctx->index_key.type->read)\n\t\tperm |= KEY_POS_READ;\n\tif (ctx->index_key.type == &key_type_keyring ||\n\t ctx->index_key.type->update)\n\t\tperm |= KEY_POS_WRITE;\n\n\tkey = key_alloc(ctx->index_key.type, ctx->index_key.description,\n\t\t\tctx->cred->fsuid, ctx->cred->fsgid, ctx->cred,\n\t\t\tperm, flags);\n\tif (IS_ERR(key))\n\t\tgoto alloc_failed;\n\n\tset_bit(KEY_FLAG_USER_CONSTRUCT, &key->flags);\n\n\tif (dest_keyring) {\n\t\tret = __key_link_begin(dest_keyring, &ctx->index_key, &edit);\n\t\tif (ret < 0)\n\t\t\tgoto link_prealloc_failed;\n\t}\n\n\t\/* attach the key to the destination keyring under lock, but we do need\n\t * to do another check just in case someone beat us to it whilst we\n\t * waited for locks *\/\n\tmutex_lock(&key_construction_mutex);\n\n\tkey_ref = search_process_keyrings(ctx);\n\tif (!IS_ERR(key_ref))\n\t\tgoto key_already_present;\n\n\tif (dest_keyring)\n\t\t__key_link(key, &edit);\n\n\tmutex_unlock(&key_construction_mutex);\n\tif (dest_keyring)\n\t\t__key_link_end(dest_keyring, &ctx->index_key, edit);\n\tmutex_unlock(&user->cons_lock);\n\t*_key = key;\n\tkleave(\" = 0 [%d]\", key_serial(key));\n\treturn 0;\n\n\t\/* the key is now present - we tell the caller that we found it by\n\t * returning -EINPROGRESS *\/\nkey_already_present:\n\tkey_put(key);\n\tmutex_unlock(&key_construction_mutex);\n\tkey = key_ref_to_ptr(key_ref);\n\tif (dest_keyring) {\n\t\tret = __key_link_check_live_key(dest_keyring, key);\n\t\tif (ret == 0)\n\t\t\t__key_link(key, &edit);\n\t\t__key_link_end(dest_keyring, &ctx->index_key, edit);\n\t\tif (ret < 0)\n\t\t\tgoto link_check_failed;\n\t}\n\tmutex_unlock(&user->cons_lock);\n\t*_key = key;\n\tkleave(\" = -EINPROGRESS [%d]\", key_serial(key));\n\treturn -EINPROGRESS;\n\nlink_check_failed:\n\tmutex_unlock(&user->cons_lock);\n\tkey_put(key);\n\tkleave(\" = %d [linkcheck]\", ret);\n\treturn ret;\n\nlink_prealloc_failed:\n\tmutex_unlock(&user->cons_lock);\n\tkleave(\" = %d [prelink]\", ret);\n\treturn ret;\n\nalloc_failed:\n\tmutex_unlock(&user->cons_lock);\n\tkleave(\" = %ld\", PTR_ERR(key));\n\treturn PTR_ERR(key);\n}","target":0,"code_token_length":694,"total_token_length":1025,"max_tokens_setting":2048} +{"idx":427369,"func":"static void init_qxl_rom(PCIQXLDevice *d)\n{\n QXLRom *rom = memory_region_get_ram_ptr(&d->rom_bar);\n QXLModes *modes = (QXLModes *)(rom + 1);\n uint32_t ram_header_size;\n uint32_t surface0_area_size;\n uint32_t num_pages;\n uint32_t fb;\n int i, n;\n\n memset(rom, 0, d->rom_size);\n\n rom->magic = cpu_to_le32(QXL_ROM_MAGIC);\n rom->id = cpu_to_le32(d->id);\n rom->log_level = cpu_to_le32(d->guestdebug);\n rom->modes_offset = cpu_to_le32(sizeof(QXLRom));\n\n rom->slot_gen_bits = MEMSLOT_GENERATION_BITS;\n rom->slot_id_bits = MEMSLOT_SLOT_BITS;\n rom->slots_start = 1;\n rom->slots_end = NUM_MEMSLOTS - 1;\n rom->n_surfaces = cpu_to_le32(d->ssd.num_surfaces);\n\n for (i = 0, n = 0; i < ARRAY_SIZE(qxl_modes); i++) {\n fb = qxl_modes[i].y_res * qxl_modes[i].stride;\n if (fb > d->vgamem_size) {\n continue;\n }\n modes->modes[n].id = cpu_to_le32(i);\n modes->modes[n].x_res = cpu_to_le32(qxl_modes[i].x_res);\n modes->modes[n].y_res = cpu_to_le32(qxl_modes[i].y_res);\n modes->modes[n].bits = cpu_to_le32(qxl_modes[i].bits);\n modes->modes[n].stride = cpu_to_le32(qxl_modes[i].stride);\n modes->modes[n].x_mili = cpu_to_le32(qxl_modes[i].x_mili);\n modes->modes[n].y_mili = cpu_to_le32(qxl_modes[i].y_mili);\n modes->modes[n].orientation = cpu_to_le32(qxl_modes[i].orientation);\n n++;\n }\n modes->n_modes = cpu_to_le32(n);\n\n ram_header_size = ALIGN(sizeof(QXLRam), 4096);\n surface0_area_size = ALIGN(d->vgamem_size, 4096);\n num_pages = d->vga.vram_size;\n num_pages -= ram_header_size;\n num_pages -= surface0_area_size;\n num_pages = num_pages \/ QXL_PAGE_SIZE;\n\n assert(ram_header_size + surface0_area_size <= d->vga.vram_size);\n\n rom->draw_area_offset = cpu_to_le32(0);\n rom->surface0_area_size = cpu_to_le32(surface0_area_size);\n rom->pages_offset = cpu_to_le32(surface0_area_size);\n rom->num_pages = cpu_to_le32(num_pages);\n rom->ram_header_offset = cpu_to_le32(d->vga.vram_size - ram_header_size);\n\n if (d->xres && d->yres) {\n \/* needs linux kernel 4.12+ to work *\/\n rom->client_monitors_config.count = 1;\n rom->client_monitors_config.heads[0].left = 0;\n rom->client_monitors_config.heads[0].top = 0;\n rom->client_monitors_config.heads[0].right = cpu_to_le32(d->xres);\n rom->client_monitors_config.heads[0].bottom = cpu_to_le32(d->yres);\n rom->client_monitors_config_crc = qxl_crc32(\n (const uint8_t *)&rom->client_monitors_config,\n sizeof(rom->client_monitors_config));\n }\n\n d->shadow_rom = *rom;\n d->rom = rom;\n d->modes = modes;\n}","target":0,"code_token_length":884,"total_token_length":1215,"max_tokens_setting":2048} +{"idx":397267,"func":"static void ehci_execute_complete(EHCIQueue *q)\n{\n EHCIPacket *p = QTAILQ_FIRST(&q->packets);\n uint32_t tbytes;\n\n assert(p != NULL);\n assert(p->qtdaddr == q->qtdaddr);\n assert(p->async == EHCI_ASYNC_INITIALIZED ||\n p->async == EHCI_ASYNC_FINISHED);\n\n DPRINTF(\"execute_complete: qhaddr 0x%x, next 0x%x, qtdaddr 0x%x, \"\n \"status %d, actual_length %d\\n\",\n q->qhaddr, q->qh.next, q->qtdaddr,\n p->packet.status, p->packet.actual_length);\n\n switch (p->packet.status) {\n case USB_RET_SUCCESS:\n break;\n case USB_RET_IOERROR:\n case USB_RET_NODEV:\n q->qh.token |= (QTD_TOKEN_HALT | QTD_TOKEN_XACTERR);\n set_field(&q->qh.token, 0, QTD_TOKEN_CERR);\n ehci_raise_irq(q->ehci, USBSTS_ERRINT);\n break;\n case USB_RET_STALL:\n q->qh.token |= QTD_TOKEN_HALT;\n ehci_raise_irq(q->ehci, USBSTS_ERRINT);\n break;\n case USB_RET_NAK:\n set_field(&q->qh.altnext_qtd, 0, QH_ALTNEXT_NAKCNT);\n return; \/* We're not done yet with this transaction *\/\n case USB_RET_BABBLE:\n q->qh.token |= (QTD_TOKEN_HALT | QTD_TOKEN_BABBLE);\n ehci_raise_irq(q->ehci, USBSTS_ERRINT);\n break;\n default:\n \/* should not be triggerable *\/\n fprintf(stderr, \"USB invalid response %d\\n\", p->packet.status);\n g_assert_not_reached();\n break;\n }\n\n \/* TODO check 4.12 for splits *\/\n tbytes = get_field(q->qh.token, QTD_TOKEN_TBYTES);\n if (tbytes && p->pid == USB_TOKEN_IN) {\n tbytes -= p->packet.actual_length;\n if (tbytes) {\n \/* 4.15.1.2 must raise int on a short input packet *\/\n ehci_raise_irq(q->ehci, USBSTS_INT);\n if (q->async) {\n q->ehci->int_req_by_async = true;\n }\n }\n } else {\n tbytes = 0;\n }\n DPRINTF(\"updating tbytes to %d\\n\", tbytes);\n set_field(&q->qh.token, tbytes, QTD_TOKEN_TBYTES);\n\n ehci_finish_transfer(q, p->packet.actual_length);\n usb_packet_unmap(&p->packet, &p->sgl);\n qemu_sglist_destroy(&p->sgl);\n p->async = EHCI_ASYNC_NONE;\n\n q->qh.token ^= QTD_TOKEN_DTOGGLE;\n q->qh.token &= ~QTD_TOKEN_ACTIVE;\n\n if (q->qh.token & QTD_TOKEN_IOC) {\n ehci_raise_irq(q->ehci, USBSTS_INT);\n if (q->async) {\n q->ehci->int_req_by_async = true;\n }\n }\n}","target":0,"code_token_length":705,"total_token_length":1036,"max_tokens_setting":2048} +{"idx":513514,"func":"reexec_in_user_namespace (int ready, char *pause_pid_file_path, char *file_to_read, int outputfd)\n{\n int ret;\n pid_t pid;\n char b;\n pid_t ppid = getpid ();\n char **argv;\n char uid[16];\n char gid[16];\n char *listen_fds = NULL;\n char *listen_pid = NULL;\n bool do_socket_activation = false;\n char *cwd = getcwd (NULL, 0);\n sigset_t sigset, oldsigset;\n\n if (cwd == NULL)\n {\n fprintf (stderr, \"error getting current working directory: %s\\n\", strerror (errno));\n _exit (EXIT_FAILURE);\n }\n\n listen_pid = getenv(\"LISTEN_PID\");\n listen_fds = getenv(\"LISTEN_FDS\");\n\n if (listen_pid != NULL && listen_fds != NULL)\n {\n if (strtol(listen_pid, NULL, 10) == getpid())\n do_socket_activation = true;\n }\n\n sprintf (uid, \"%d\", geteuid ());\n sprintf (gid, \"%d\", getegid ());\n\n pid = syscall_clone (CLONE_NEWUSER|CLONE_NEWNS|SIGCHLD, NULL);\n if (pid < 0)\n {\n fprintf (stderr, \"cannot clone: %s\\n\", strerror (errno));\n check_proc_sys_userns_file (_max_user_namespaces);\n check_proc_sys_userns_file (_unprivileged_user_namespaces);\n }\n if (pid)\n {\n if (do_socket_activation)\n {\n long num_fds;\n num_fds = strtol (listen_fds, NULL, 10);\n if (num_fds != LONG_MIN && num_fds != LONG_MAX)\n {\n int f;\n\n for (f = 3; f < num_fds + 3; f++)\n if (open_files_set == NULL || FD_ISSET (f % FD_SETSIZE, &(open_files_set[f \/ FD_SETSIZE])))\n close (f);\n }\n unsetenv (\"LISTEN_PID\");\n unsetenv (\"LISTEN_FDS\");\n unsetenv (\"LISTEN_FDNAMES\");\n }\n return pid;\n }\n\n if (sigfillset (&sigset) < 0)\n {\n fprintf (stderr, \"cannot fill sigset: %s\\n\", strerror (errno));\n _exit (EXIT_FAILURE);\n }\n if (sigdelset (&sigset, SIGCHLD) < 0)\n {\n fprintf (stderr, \"cannot sigdelset(SIGCHLD): %s\\n\", strerror (errno));\n _exit (EXIT_FAILURE);\n }\n if (sigdelset (&sigset, SIGTERM) < 0)\n {\n fprintf (stderr, \"cannot sigdelset(SIGTERM): %s\\n\", strerror (errno));\n _exit (EXIT_FAILURE);\n }\n if (sigprocmask (SIG_BLOCK, &sigset, &oldsigset) < 0)\n {\n fprintf (stderr, \"cannot block signals: %s\\n\", strerror (errno));\n _exit (EXIT_FAILURE);\n }\n\n argv = get_cmd_line_args (ppid);\n if (argv == NULL)\n {\n fprintf (stderr, \"cannot read argv: %s\\n\", strerror (errno));\n _exit (EXIT_FAILURE);\n }\n\n if (do_socket_activation)\n {\n char s[32];\n sprintf (s, \"%d\", getpid());\n setenv (\"LISTEN_PID\", s, true);\n }\n\n setenv (\"_CONTAINERS_USERNS_CONFIGURED\", \"init\", 1);\n setenv (\"_CONTAINERS_ROOTLESS_UID\", uid, 1);\n setenv (\"_CONTAINERS_ROOTLESS_GID\", gid, 1);\n\n ret = TEMP_FAILURE_RETRY (read (ready, &b, 1));\n if (ret < 0)\n {\n fprintf (stderr, \"cannot read from sync pipe: %s\\n\", strerror (errno));\n _exit (EXIT_FAILURE);\n }\n if (b != '0')\n _exit (EXIT_FAILURE);\n\n if (syscall_setresgid (0, 0, 0) < 0)\n {\n fprintf (stderr, \"cannot setresgid: %s\\n\", strerror (errno));\n TEMP_FAILURE_RETRY (write (ready, \"1\", 1));\n _exit (EXIT_FAILURE);\n }\n\n if (syscall_setresuid (0, 0, 0) < 0)\n {\n fprintf (stderr, \"cannot setresuid: %s\\n\", strerror (errno));\n TEMP_FAILURE_RETRY (write (ready, \"1\", 1));\n _exit (EXIT_FAILURE);\n }\n\n if (chdir (cwd) < 0)\n {\n fprintf (stderr, \"cannot chdir: %s\\n\", strerror (errno));\n TEMP_FAILURE_RETRY (write (ready, \"1\", 1));\n _exit (EXIT_FAILURE);\n }\n free (cwd);\n\n if (pause_pid_file_path && pause_pid_file_path[0] != '\\0')\n {\n if (create_pause_process (pause_pid_file_path, argv) < 0)\n {\n TEMP_FAILURE_RETRY (write (ready, \"2\", 1));\n _exit (EXIT_FAILURE);\n }\n }\n\n ret = TEMP_FAILURE_RETRY (write (ready, \"0\", 1));\n if (ret < 0)\n {\n\t fprintf (stderr, \"cannot write to ready pipe: %s\\n\", strerror (errno));\n\t _exit (EXIT_FAILURE);\n }\n close (ready);\n\n if (sigprocmask (SIG_SETMASK, &oldsigset, NULL) < 0)\n {\n fprintf (stderr, \"cannot block signals: %s\\n\", strerror (errno));\n _exit (EXIT_FAILURE);\n }\n\n if (file_to_read && file_to_read[0])\n {\n ret = copy_file_to_fd (file_to_read, outputfd);\n close (outputfd);\n _exit (ret == 0 ? EXIT_SUCCESS : EXIT_FAILURE);\n }\n\n execvp (argv[0], argv);\n\n _exit (EXIT_FAILURE);\n}","target":0,"code_token_length":1316,"total_token_length":1647,"max_tokens_setting":2048} +{"idx":398773,"func":"gst_qtdemux_chain (GstPad * sinkpad, GstObject * parent, GstBuffer * inbuf)\n{\n GstQTDemux *demux;\n\n demux = GST_QTDEMUX (parent);\n\n GST_DEBUG_OBJECT (demux,\n \"Received buffer pts:%\" GST_TIME_FORMAT \" dts:%\" GST_TIME_FORMAT\n \" offset:%\" G_GUINT64_FORMAT \" size:%\" G_GSIZE_FORMAT \" demux offset:%\"\n G_GUINT64_FORMAT, GST_TIME_ARGS (GST_BUFFER_PTS (inbuf)),\n GST_TIME_ARGS (GST_BUFFER_DTS (inbuf)), GST_BUFFER_OFFSET (inbuf),\n gst_buffer_get_size (inbuf), demux->offset);\n\n if (GST_BUFFER_FLAG_IS_SET (inbuf, GST_BUFFER_FLAG_DISCONT)) {\n gboolean is_gap_input = FALSE;\n gint i;\n\n GST_DEBUG_OBJECT (demux, \"Got DISCONT, marking all streams as DISCONT\");\n\n for (i = 0; i < demux->n_streams; i++) {\n demux->streams[i]->discont = TRUE;\n }\n\n \/* Check if we can land back on our feet in the case where upstream is\n * handling the seeking\/pushing of samples with gaps in between (like\n * in the case of trick-mode DASH for example) *\/\n if (demux->upstream_format_is_time\n && GST_BUFFER_OFFSET (inbuf) != GST_BUFFER_OFFSET_NONE) {\n gint i;\n for (i = 0; i < demux->n_streams; i++) {\n guint32 res;\n GST_LOG_OBJECT (demux,\n \"Stream #%d , checking if offset %\" G_GUINT64_FORMAT\n \" is a sample start\", i, GST_BUFFER_OFFSET (inbuf));\n res =\n gst_qtdemux_find_index_for_given_media_offset_linear (demux,\n demux->streams[i], GST_BUFFER_OFFSET (inbuf));\n if (res != -1) {\n QtDemuxSample *sample = &demux->streams[i]->samples[res];\n GST_LOG_OBJECT (demux,\n \"Checking if sample %d from stream %d is valid (offset:%\"\n G_GUINT64_FORMAT \" size:%\" G_GUINT32_FORMAT \")\", res, i,\n sample->offset, sample->size);\n if (sample->offset == GST_BUFFER_OFFSET (inbuf)) {\n GST_LOG_OBJECT (demux,\n \"new buffer corresponds to a valid sample : %\" G_GUINT32_FORMAT,\n res);\n is_gap_input = TRUE;\n \/* We can go back to standard playback mode *\/\n demux->state = QTDEMUX_STATE_MOVIE;\n \/* Remember which sample this stream is at *\/\n demux->streams[i]->sample_index = res;\n \/* Finally update all push-based values to the expected values *\/\n demux->neededbytes = demux->streams[i]->samples[res].size;\n demux->todrop = 0;\n demux->offset = GST_BUFFER_OFFSET (inbuf);\n }\n }\n }\n if (!is_gap_input) {\n \/* Reset state if it's a real discont *\/\n demux->neededbytes = 16;\n demux->state = QTDEMUX_STATE_INITIAL;\n demux->offset = GST_BUFFER_OFFSET (inbuf);\n }\n }\n \/* Reverse fragmented playback, need to flush all we have before\n * consuming a new fragment.\n * The samples array have the timestamps calculated by accumulating the\n * durations but this won't work for reverse playback of fragments as\n * the timestamps of a subsequent fragment should be smaller than the\n * previously received one. *\/\n if (!is_gap_input && demux->fragmented && demux->segment.rate < 0) {\n gst_qtdemux_process_adapter (demux, TRUE);\n for (i = 0; i < demux->n_streams; i++)\n gst_qtdemux_stream_flush_samples_data (demux, demux->streams[i]);\n }\n }\n\n gst_adapter_push (demux->adapter, inbuf);\n\n GST_DEBUG_OBJECT (demux,\n \"pushing in inbuf %p, neededbytes:%u, available:%\" G_GSIZE_FORMAT, inbuf,\n demux->neededbytes, gst_adapter_available (demux->adapter));\n\n return gst_qtdemux_process_adapter (demux, FALSE);\n}","target":0,"code_token_length":948,"total_token_length":1279,"max_tokens_setting":2048} +{"idx":1121,"func":"static ossl_inline t2 * sk_ ## t1 ## _pop ( STACK_OF ( t1 ) * sk ) {\n return ( t2 * ) OPENSSL_sk_pop ( ( OPENSSL_STACK * ) sk ) ;\n }\n static ossl_inline t2 * sk_ ## t1 ## _shift ( STACK_OF ( t1 ) * sk ) {\n return ( t2 * ) OPENSSL_sk_shift ( ( OPENSSL_STACK * ) sk ) ;\n }\n static ossl_inline void sk_ ## t1 ## _pop_free ( STACK_OF ( t1 ) * sk , sk_ ## t1 ## _freefunc freefunc ) {\n OPENSSL_sk_pop_free ( ( OPENSSL_STACK * ) sk , ( OPENSSL_sk_freefunc ) freefunc ) ;\n }\n static ossl_inline int sk_ ## t1 ## _insert ( STACK_OF ( t1 ) * sk , t2 * ptr , int idx ) {\n return OPENSSL_sk_insert ( ( OPENSSL_STACK * ) sk , ( const void * ) ptr , idx ) ;\n }\n static ossl_inline t2 * sk_ ## t1 ## _set ( STACK_OF ( t1 ) * sk , int idx , t2 * ptr ) {\n return ( t2 * ) OPENSSL_sk_set ( ( OPENSSL_STACK * ) sk , idx , ( const void * ) ptr ) ;\n }\n static ossl_inline int sk_ ## t1 ## _find ( STACK_OF ( t1 ) * sk , t2 * ptr ) {\n return OPENSSL_sk_find ( ( OPENSSL_STACK * ) sk , ( const void * ) ptr ) ;\n }\n static ossl_inline int sk_ ## t1 ## _find_ex ( STACK_OF ( t1 ) * sk , t2 * ptr ) {\n return OPENSSL_sk_find_ex ( ( OPENSSL_STACK * ) sk , ( const void * ) ptr ) ;\n }\n static ossl_inline void sk_ ## t1 ## _sort ( STACK_OF ( t1 ) * sk ) {\n OPENSSL_sk_sort ( ( OPENSSL_STACK * ) sk ) ;\n }\n static ossl_inline int sk_ ## t1 ## _is_sorted ( const STACK_OF ( t1 ) * sk ) {\n return OPENSSL_sk_is_sorted ( ( const OPENSSL_STACK * ) sk ) ;\n }\n static ossl_inline STACK_OF ( t1 ) * sk_ ## t1 ## _dup ( const STACK_OF ( t1 ) * sk ) {\n return ( STACK_OF ( t1 ) * ) OPENSSL_sk_dup ( ( const OPENSSL_STACK * ) sk ) ;\n }\n static ossl_inline STACK_OF ( t1 ) * sk_ ## t1 ## _deep_copy ( const STACK_OF ( t1 ) * sk , sk_ ## t1 ## _copyfunc copyfunc , sk_ ## t1 ## _freefunc freefunc ) {\n return ( STACK_OF ( t1 ) * ) OPENSSL_sk_deep_copy ( ( const OPENSSL_STACK * ) sk , ( OPENSSL_sk_copyfunc ) copyfunc , ( OPENSSL_sk_freefunc ) freefunc ) ;\n }\n static ossl_inline sk_ ## t1 ## _compfunc sk_ ## t1 ## _set_cmp_func ( STACK_OF ( t1 ) * sk , sk_ ## t1 ## _compfunc compare ) {\n return ( sk_ ## t1 ## _compfunc ) OPENSSL_sk_set_cmp_func ( ( OPENSSL_STACK * ) sk , ( OPENSSL_sk_compfunc ) compare ) ;\n }\n # define DEFINE_SPECIAL_STACK_OF ( t1 , t2 ) SKM_DEFINE_STACK_OF ( t1 , t2 , t2 ) # define DEFINE_STACK_OF ( t ) SKM_DEFINE_STACK_OF ( t , t , t ) # define DEFINE_SPECIAL_STACK_OF_CONST ( t1 , t2 ) SKM_DEFINE_STACK_OF ( t1 , const t2 , t2 ) # define DEFINE_STACK_OF_CONST ( t ) SKM_DEFINE_STACK_OF ( t , const t , t ) typedef char * OPENSSL_STRING ;\n typedef const char * OPENSSL_CSTRING ;\n DEFINE_SPECIAL_STACK_OF ( OPENSSL_STRING , char )","target":1,"code_token_length":838,"total_token_length":1169,"max_tokens_setting":2048} +{"idx":381470,"func":"build_key_sequence (gcry_mpi_t *kparms, int mode, size_t *r_length)\n{\n int rc, i;\n size_t needed, n;\n unsigned char *plain, *p;\n size_t plainlen;\n size_t outseqlen, oidseqlen, octstrlen, inseqlen;\n\n needed = 3; \/* The version integer with value 0. *\/\n for (i=0; kparms[i]; i++)\n {\n n = 0;\n rc = gcry_mpi_print (GCRYMPI_FMT_STD, NULL, 0, &n, kparms[i]);\n if (rc)\n {\n log_error (\"error formatting parameter: %s\\n\", gpg_strerror (rc));\n return NULL;\n }\n needed += n;\n n = compute_tag_length (n);\n if (!n)\n return NULL;\n needed += n;\n }\n if (i != 8)\n {\n log_error (\"invalid parameters for p12_build\\n\");\n return NULL;\n }\n \/* Now this all goes into a sequence. *\/\n inseqlen = needed;\n n = compute_tag_length (needed);\n if (!n)\n return NULL;\n needed += n;\n\n if (mode != 2)\n {\n \/* Encapsulate all into an octet string. *\/\n octstrlen = needed;\n n = compute_tag_length (needed);\n if (!n)\n return NULL;\n needed += n;\n \/* Prepend the object identifier sequence. *\/\n oidseqlen = 2 + DIM (oid_rsaEncryption) + 2;\n needed += 2 + oidseqlen;\n \/* The version number. *\/\n needed += 3;\n \/* And finally put the whole thing into a sequence. *\/\n outseqlen = needed;\n n = compute_tag_length (needed);\n if (!n)\n return NULL;\n needed += n;\n }\n\n \/* allocate 8 extra bytes for padding *\/\n plain = gcry_malloc_secure (needed+8);\n if (!plain)\n {\n log_error (\"error allocating encryption buffer\\n\");\n return NULL;\n }\n\n \/* And now fill the plaintext buffer. *\/\n p = plain;\n if (mode != 2)\n {\n p = store_tag_length (p, TAG_SEQUENCE, outseqlen);\n \/* Store version. *\/\n *p++ = TAG_INTEGER;\n *p++ = 1;\n *p++ = 0;\n \/* Store object identifier sequence. *\/\n p = store_tag_length (p, TAG_SEQUENCE, oidseqlen);\n p = store_tag_length (p, TAG_OBJECT_ID, DIM (oid_rsaEncryption));\n memcpy (p, oid_rsaEncryption, DIM (oid_rsaEncryption));\n p += DIM (oid_rsaEncryption);\n *p++ = TAG_NULL;\n *p++ = 0;\n \/* Start with the octet string. *\/\n p = store_tag_length (p, TAG_OCTET_STRING, octstrlen);\n }\n\n p = store_tag_length (p, TAG_SEQUENCE, inseqlen);\n \/* Store the key parameters. *\/\n *p++ = TAG_INTEGER;\n *p++ = 1;\n *p++ = 0;\n for (i=0; kparms[i]; i++)\n {\n n = 0;\n rc = gcry_mpi_print (GCRYMPI_FMT_STD, NULL, 0, &n, kparms[i]);\n if (rc)\n {\n log_error (\"oops: error formatting parameter: %s\\n\",\n gpg_strerror (rc));\n gcry_free (plain);\n return NULL;\n }\n p = store_tag_length (p, TAG_INTEGER, n);\n\n n = plain + needed - p;\n rc = gcry_mpi_print (GCRYMPI_FMT_STD, p, n, &n, kparms[i]);\n if (rc)\n {\n log_error (\"oops: error storing parameter: %s\\n\",\n gpg_strerror (rc));\n gcry_free (plain);\n return NULL;\n }\n p += n;\n }\n\n plainlen = p - plain;\n assert (needed == plainlen);\n\n if (!mode)\n {\n \/* Append some pad characters; we already allocated extra space. *\/\n n = 8 - plainlen % 8;\n for (i=0; i < n; i++, plainlen++)\n *p++ = n;\n }\n\n *r_length = plainlen;\n return plain;\n}","target":0,"code_token_length":966,"total_token_length":1297,"max_tokens_setting":2048} +{"idx":492978,"func":"static int ssl_ciphersuite_match( mbedtls_ssl_context *ssl, int suite_id,\n const mbedtls_ssl_ciphersuite_t **ciphersuite_info )\n{\n const mbedtls_ssl_ciphersuite_t *suite_info;\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \\\n defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)\n mbedtls_pk_type_t sig_type;\n#endif\n\n suite_info = mbedtls_ssl_ciphersuite_from_id( suite_id );\n if( suite_info == NULL )\n {\n MBEDTLS_SSL_DEBUG_MSG( 1, ( \"should never happen\" ) );\n return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );\n }\n\n MBEDTLS_SSL_DEBUG_MSG( 3, ( \"trying ciphersuite: %#04x (%s)\",\n (unsigned int) suite_id, suite_info->name ) );\n\n if( suite_info->min_minor_ver > ssl->minor_ver ||\n suite_info->max_minor_ver < ssl->minor_ver )\n {\n MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ciphersuite mismatch: version\" ) );\n return( 0 );\n }\n\n#if defined(MBEDTLS_SSL_PROTO_DTLS)\n if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&\n ( suite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) )\n return( 0 );\n#endif\n\n#if defined(MBEDTLS_ARC4_C)\n if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED &&\n suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )\n {\n MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ciphersuite mismatch: rc4\" ) );\n return( 0 );\n }\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)\n if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE &&\n ( ssl->handshake->cli_exts & MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK ) == 0 )\n {\n MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ciphersuite mismatch: ecjpake \"\n \"not configured or ext missing\" ) );\n return( 0 );\n }\n#endif\n\n\n#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)\n if( mbedtls_ssl_ciphersuite_uses_ec( suite_info ) &&\n ( ssl->handshake->curves == NULL ||\n ssl->handshake->curves[0] == NULL ) )\n {\n MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ciphersuite mismatch: \"\n \"no common elliptic curve\" ) );\n return( 0 );\n }\n#endif\n\n#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)\n \/* If the ciphersuite requires a pre-shared key and we don't\n * have one, skip it now rather than failing later *\/\n if( mbedtls_ssl_ciphersuite_uses_psk( suite_info ) &&\n ssl_conf_has_psk_or_cb( ssl->conf ) == 0 )\n {\n MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ciphersuite mismatch: no pre-shared key\" ) );\n return( 0 );\n }\n#endif\n\n#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \\\n defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)\n \/* If the ciphersuite requires signing, check whether\n * a suitable hash algorithm is present. *\/\n if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )\n {\n sig_type = mbedtls_ssl_get_ciphersuite_sig_alg( suite_info );\n if( sig_type != MBEDTLS_PK_NONE &&\n mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs, sig_type ) == MBEDTLS_MD_NONE )\n {\n MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ciphersuite mismatch: no suitable hash algorithm \"\n \"for signature algorithm %u\", (unsigned) sig_type ) );\n return( 0 );\n }\n }\n\n#endif \/* MBEDTLS_SSL_PROTO_TLS1_2 &&\n MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED *\/\n\n#if defined(MBEDTLS_X509_CRT_PARSE_C)\n \/*\n * Final check: if ciphersuite requires us to have a\n * certificate\/key of a particular type:\n * - select the appropriate certificate if we have one, or\n * - try the next ciphersuite if we don't\n * This must be done last since we modify the key_cert list.\n *\/\n if( ssl_pick_cert( ssl, suite_info ) != 0 )\n {\n MBEDTLS_SSL_DEBUG_MSG( 3, ( \"ciphersuite mismatch: \"\n \"no suitable certificate\" ) );\n return( 0 );\n }\n#endif\n\n *ciphersuite_info = suite_info;\n return( 0 );\n}","target":0,"code_token_length":1055,"total_token_length":1386,"max_tokens_setting":2048} +{"idx":433764,"func":"read_block(FILE *fp, pcap_t *p, struct block_cursor *cursor, char *errbuf)\n{\n\tstruct pcap_ng_sf *ps;\n\tint status;\n\tstruct block_header bhdr;\n\tstruct block_trailer *btrlr;\n\tu_char *bdata;\n\tsize_t data_remaining;\n\n\tps = p->priv;\n\n\tstatus = read_bytes(fp, &bhdr, sizeof(bhdr), 0, errbuf);\n\tif (status <= 0)\n\t\treturn (status);\t\/* error or EOF *\/\n\n\tif (p->swapped) {\n\t\tbhdr.block_type = SWAPLONG(bhdr.block_type);\n\t\tbhdr.total_length = SWAPLONG(bhdr.total_length);\n\t}\n\n\t\/*\n\t * Is this block \"too small\" - i.e., is it shorter than a block\n\t * header plus a block trailer?\n\t *\/\n\tif (bhdr.total_length < sizeof(struct block_header) +\n\t sizeof(struct block_trailer)) {\n\t\tpcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,\n\t\t \"block in pcapng dump file has a length of %u < %\" PRIsize,\n\t\t bhdr.total_length,\n\t\t sizeof(struct block_header) + sizeof(struct block_trailer));\n\t\treturn (-1);\n\t}\n\n\t\/*\n\t * Is the block total length a multiple of 4?\n\t *\/\n\tif ((bhdr.total_length % 4) != 0) {\n\t\t\/*\n\t\t * No. Report that as an error.\n\t\t *\/\n\t\tpcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,\n\t\t \"block in pcapng dump file has a length of %u that is not a multiple of 4\" PRIsize,\n\t\t bhdr.total_length);\n\t\treturn (-1);\n\t}\n\n\t\/*\n\t * Is the buffer big enough?\n\t *\/\n\tif (p->bufsize < bhdr.total_length) {\n\t\t\/*\n\t\t * No - make it big enough, unless it's too big, in\n\t\t * which case we fail.\n\t\t *\/\n\t\tvoid *bigger_buffer;\n\n\t\tif (bhdr.total_length > ps->max_blocksize) {\n\t\t\tpcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, \"pcapng block size %u > maximum %u\", bhdr.total_length,\n\t\t\t ps->max_blocksize);\n\t\t\treturn (-1);\n\t\t}\n\t\tbigger_buffer = realloc(p->buffer, bhdr.total_length);\n\t\tif (bigger_buffer == NULL) {\n\t\t\tpcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, \"out of memory\");\n\t\t\treturn (-1);\n\t\t}\n\t\tp->buffer = bigger_buffer;\n\t}\n\n\t\/*\n\t * Copy the stuff we've read to the buffer, and read the rest\n\t * of the block.\n\t *\/\n\tmemcpy(p->buffer, &bhdr, sizeof(bhdr));\n\tbdata = (u_char *)p->buffer + sizeof(bhdr);\n\tdata_remaining = bhdr.total_length - sizeof(bhdr);\n\tif (read_bytes(fp, bdata, data_remaining, 1, errbuf) == -1)\n\t\treturn (-1);\n\n\t\/*\n\t * Get the block size from the trailer.\n\t *\/\n\tbtrlr = (struct block_trailer *)(bdata + data_remaining - sizeof (struct block_trailer));\n\tif (p->swapped)\n\t\tbtrlr->total_length = SWAPLONG(btrlr->total_length);\n\n\t\/*\n\t * Is the total length from the trailer the same as the total\n\t * length from the header?\n\t *\/\n\tif (bhdr.total_length != btrlr->total_length) {\n\t\t\/*\n\t\t * No.\n\t\t *\/\n\t\tpcap_snprintf(errbuf, PCAP_ERRBUF_SIZE,\n\t\t \"block total length in header and trailer don't match\");\n\t\treturn (-1);\n\t}\n\n\t\/*\n\t * Initialize the cursor.\n\t *\/\n\tcursor->data = bdata;\n\tcursor->data_remaining = data_remaining - sizeof(struct block_trailer);\n\tcursor->block_type = bhdr.block_type;\n\treturn (1);\n}","target":0,"code_token_length":826,"total_token_length":1157,"max_tokens_setting":2048} +{"idx":255898,"func":"void PrintPreviewDataSource::Init() {\n AddLocalizedString(\"title\", IDS_PRINT_PREVIEW_TITLE);\n AddLocalizedString(\"loading\", IDS_PRINT_PREVIEW_LOADING);\n AddLocalizedString(\"noPlugin\", IDS_PRINT_PREVIEW_NO_PLUGIN);\n AddLocalizedString(\"launchNativeDialog\", IDS_PRINT_PREVIEW_NATIVE_DIALOG);\n AddLocalizedString(\"previewFailed\", IDS_PRINT_PREVIEW_FAILED);\n AddLocalizedString(\"invalidPrinterSettings\",\n IDS_PRINT_PREVIEW_INVALID_PRINTER_SETTINGS);\n AddLocalizedString(\"printButton\", IDS_PRINT_PREVIEW_PRINT_BUTTON);\n AddLocalizedString(\"saveButton\", IDS_PRINT_PREVIEW_SAVE_BUTTON);\n AddLocalizedString(\"cancelButton\", IDS_PRINT_PREVIEW_CANCEL_BUTTON);\n AddLocalizedString(\"printing\", IDS_PRINT_PREVIEW_PRINTING);\n AddLocalizedString(\"printingToPDFInProgress\",\n IDS_PRINT_PREVIEW_PRINTING_TO_PDF_IN_PROGRESS);\n#if defined(OS_MACOSX)\n AddLocalizedString(\"openingPDFInPreview\",\n IDS_PRINT_PREVIEW_OPENING_PDF_IN_PREVIEW);\n#endif\n AddLocalizedString(\"destinationLabel\", IDS_PRINT_PREVIEW_DESTINATION_LABEL);\n AddLocalizedString(\"copiesLabel\", IDS_PRINT_PREVIEW_COPIES_LABEL);\n AddLocalizedString(\"examplePageRangeText\",\n IDS_PRINT_PREVIEW_EXAMPLE_PAGE_RANGE_TEXT);\n AddLocalizedString(\"layoutLabel\", IDS_PRINT_PREVIEW_LAYOUT_LABEL);\n AddLocalizedString(\"optionAllPages\", IDS_PRINT_PREVIEW_OPTION_ALL_PAGES);\n AddLocalizedString(\"optionBw\", IDS_PRINT_PREVIEW_OPTION_BW);\n AddLocalizedString(\"optionCollate\", IDS_PRINT_PREVIEW_OPTION_COLLATE);\n AddLocalizedString(\"optionColor\", IDS_PRINT_PREVIEW_OPTION_COLOR);\n AddLocalizedString(\"optionLandscape\", IDS_PRINT_PREVIEW_OPTION_LANDSCAPE);\n AddLocalizedString(\"optionPortrait\", IDS_PRINT_PREVIEW_OPTION_PORTRAIT);\n AddLocalizedString(\"optionTwoSided\", IDS_PRINT_PREVIEW_OPTION_TWO_SIDED);\n AddLocalizedString(\"pagesLabel\", IDS_PRINT_PREVIEW_PAGES_LABEL);\n AddLocalizedString(\"pageRangeTextBox\", IDS_PRINT_PREVIEW_PAGE_RANGE_TEXT);\n AddLocalizedString(\"pageRangeRadio\", IDS_PRINT_PREVIEW_PAGE_RANGE_RADIO);\n AddLocalizedString(\"printToPDF\", IDS_PRINT_PREVIEW_PRINT_TO_PDF);\n AddLocalizedString(\"printPreviewTitleFormat\", IDS_PRINT_PREVIEW_TITLE_FORMAT);\n AddLocalizedString(\"printPreviewSummaryFormatShort\",\n IDS_PRINT_PREVIEW_SUMMARY_FORMAT_SHORT);\n AddLocalizedString(\"printPreviewSummaryFormatLong\",\n IDS_PRINT_PREVIEW_SUMMARY_FORMAT_LONG);\n AddLocalizedString(\"printPreviewSheetsLabelSingular\",\n IDS_PRINT_PREVIEW_SHEETS_LABEL_SINGULAR);\n AddLocalizedString(\"printPreviewSheetsLabelPlural\",\n IDS_PRINT_PREVIEW_SHEETS_LABEL_PLURAL);\n AddLocalizedString(\"printPreviewPageLabelSingular\",\n IDS_PRINT_PREVIEW_PAGE_LABEL_SINGULAR);\n AddLocalizedString(\"printPreviewPageLabelPlural\",\n IDS_PRINT_PREVIEW_PAGE_LABEL_PLURAL);\n const string16 shortcut_text(UTF8ToUTF16(kAdvancedPrintShortcut));\n#if defined(OS_CHROMEOS)\n AddString(\"cloudPrintDialogOption\", l10n_util::GetStringFUTF16(\n IDS_PRINT_PREVIEW_CLOUD_DIALOG_OPTION,\n l10n_util::GetStringUTF16(IDS_GOOGLE_CLOUD_PRINT),\n shortcut_text));\n AddLocalizedString(\"printWithCloudPrint\",\n IDS_PRINT_PREVIEW_MORE_PRINTERS);\n#else\n AddString(\"systemDialogOption\", l10n_util::GetStringFUTF16(\n IDS_PRINT_PREVIEW_SYSTEM_DIALOG_OPTION,\n shortcut_text));\n AddString(\"printWithCloudPrint\", l10n_util::GetStringFUTF16(\n IDS_PRINT_PREVIEW_PRINT_WITH_CLOUD_PRINT,\n l10n_util::GetStringUTF16(IDS_GOOGLE_CLOUD_PRINT)));\n#endif\n#if defined(OS_MACOSX)\n AddLocalizedString(\"openPdfInPreviewOption\",\n IDS_PRINT_PREVIEW_OPEN_PDF_IN_PREVIEW_APP);\n#endif\n AddString(\"printWithCloudPrintWait\", l10n_util::GetStringFUTF16(\n IDS_PRINT_PREVIEW_PRINT_WITH_CLOUD_PRINT_WAIT,\n l10n_util::GetStringUTF16(IDS_GOOGLE_CLOUD_PRINT)));\n AddLocalizedString(\"pageRangeInstruction\",\n IDS_PRINT_PREVIEW_PAGE_RANGE_INSTRUCTION);\n AddLocalizedString(\"copiesInstruction\", IDS_PRINT_PREVIEW_COPIES_INSTRUCTION);\n AddLocalizedString(\"signIn\", IDS_PRINT_PREVIEW_SIGN_IN);\n AddLocalizedString(\"managePrinters\", IDS_PRINT_PREVIEW_MANAGE_PRINTERS);\n AddLocalizedString(\"incrementTitle\", IDS_PRINT_PREVIEW_INCREMENT_TITLE);\n AddLocalizedString(\"decrementTitle\", IDS_PRINT_PREVIEW_DECREMENT_TITLE);\n AddLocalizedString(\"printPagesLabel\", IDS_PRINT_PREVIEW_PRINT_PAGES_LABEL);\n AddLocalizedString(\"optionsLabel\", IDS_PRINT_PREVIEW_OPTIONS_LABEL);\n AddLocalizedString(\"optionHeaderFooter\",\n IDS_PRINT_PREVIEW_OPTION_HEADER_FOOTER);\n AddLocalizedString(\"marginsLabel\", IDS_PRINT_PREVIEW_MARGINS_LABEL);\n AddLocalizedString(\"defaultMargins\", IDS_PRINT_PREVIEW_DEFAULT_MARGINS);\n AddLocalizedString(\"noMargins\", IDS_PRINT_PREVIEW_NO_MARGINS);\n AddLocalizedString(\"customMargins\", IDS_PRINT_PREVIEW_CUSTOM_MARGINS);\n AddLocalizedString(\"minimumMargins\", IDS_PRINT_PREVIEW_MINIMUM_MARGINS);\n AddLocalizedString(\"top\", IDS_PRINT_PREVIEW_TOP_MARGIN_LABEL);\n AddLocalizedString(\"bottom\", IDS_PRINT_PREVIEW_BOTTOM_MARGIN_LABEL);\n AddLocalizedString(\"left\", IDS_PRINT_PREVIEW_LEFT_MARGIN_LABEL);\n AddLocalizedString(\"right\", IDS_PRINT_PREVIEW_RIGHT_MARGIN_LABEL);\n\n set_json_path(\"strings.js\");\n add_resource_path(\"print_preview.js\", IDR_PRINT_PREVIEW_JS);\n set_default_resource(IDR_PRINT_PREVIEW_HTML);\n}\n","target":1,"code_token_length":1118,"total_token_length":1449,"max_tokens_setting":2048} +{"idx":23655,"func":"const char * http_hdr_reason_lookup ( unsigned status ) {\n # define HTTP_STATUS_ENTRY ( value , reason ) case value : return # reason switch ( status ) {\n HTTP_STATUS_ENTRY ( 0 , None ) ;\n HTTP_STATUS_ENTRY ( 100 , Continue ) ;\n HTTP_STATUS_ENTRY ( 101 , Switching Protocols ) ;\n HTTP_STATUS_ENTRY ( 102 , Processing ) ;\n HTTP_STATUS_ENTRY ( 103 , Early Hints ) ;\n HTTP_STATUS_ENTRY ( 200 , OK ) ;\n HTTP_STATUS_ENTRY ( 201 , Created ) ;\n HTTP_STATUS_ENTRY ( 202 , Accepted ) ;\n HTTP_STATUS_ENTRY ( 203 , Non - Authoritative Information ) ;\n HTTP_STATUS_ENTRY ( 204 , No Content ) ;\n HTTP_STATUS_ENTRY ( 205 , Reset Content ) ;\n HTTP_STATUS_ENTRY ( 206 , Partial Content ) ;\n HTTP_STATUS_ENTRY ( 207 , Multi - Status ) ;\n HTTP_STATUS_ENTRY ( 208 , Already Reported ) ;\n HTTP_STATUS_ENTRY ( 226 , IM Used ) ;\n HTTP_STATUS_ENTRY ( 300 , Multiple Choices ) ;\n HTTP_STATUS_ENTRY ( 301 , Moved Permanently ) ;\n HTTP_STATUS_ENTRY ( 302 , Found ) ;\n HTTP_STATUS_ENTRY ( 303 , See Other ) ;\n HTTP_STATUS_ENTRY ( 304 , Not Modified ) ;\n HTTP_STATUS_ENTRY ( 305 , Use Proxy ) ;\n HTTP_STATUS_ENTRY ( 307 , Temporary Redirect ) ;\n HTTP_STATUS_ENTRY ( 308 , Permanent Redirect ) ;\n HTTP_STATUS_ENTRY ( 400 , Bad Request ) ;\n HTTP_STATUS_ENTRY ( 401 , Unauthorized ) ;\n HTTP_STATUS_ENTRY ( 402 , Payment Required ) ;\n HTTP_STATUS_ENTRY ( 403 , Forbidden ) ;\n HTTP_STATUS_ENTRY ( 404 , Not Found ) ;\n HTTP_STATUS_ENTRY ( 405 , Method Not Allowed ) ;\n HTTP_STATUS_ENTRY ( 406 , Not Acceptable ) ;\n HTTP_STATUS_ENTRY ( 407 , Proxy Authentication Required ) ;\n HTTP_STATUS_ENTRY ( 408 , Request Timeout ) ;\n HTTP_STATUS_ENTRY ( 409 , Conflict ) ;\n HTTP_STATUS_ENTRY ( 410 , Gone ) ;\n HTTP_STATUS_ENTRY ( 411 , Length Required ) ;\n HTTP_STATUS_ENTRY ( 412 , Precondition Failed ) ;\n HTTP_STATUS_ENTRY ( 413 , Request Entity Too Large ) ;\n HTTP_STATUS_ENTRY ( 414 , Request - URI Too Long ) ;\n HTTP_STATUS_ENTRY ( 415 , Unsupported Media Type ) ;\n HTTP_STATUS_ENTRY ( 416 , Requested Range Not Satisfiable ) ;\n HTTP_STATUS_ENTRY ( 417 , Expectation Failed ) ;\n HTTP_STATUS_ENTRY ( 422 , Unprocessable Entity ) ;\n HTTP_STATUS_ENTRY ( 423 , Locked ) ;\n HTTP_STATUS_ENTRY ( 424 , Failed Dependency ) ;\n HTTP_STATUS_ENTRY ( 426 , Upgrade Required ) ;\n HTTP_STATUS_ENTRY ( 428 , Precondition Required ) ;\n HTTP_STATUS_ENTRY ( 429 , Too Many Requests ) ;\n HTTP_STATUS_ENTRY ( 431 , Request Header Fields Too Large ) ;\n HTTP_STATUS_ENTRY ( 500 , Internal Server Error ) ;\n HTTP_STATUS_ENTRY ( 501 , Not Implemented ) ;\n HTTP_STATUS_ENTRY ( 502 , Bad Gateway ) ;\n HTTP_STATUS_ENTRY ( 503 , Service Unavailable ) ;\n HTTP_STATUS_ENTRY ( 504 , Gateway Timeout ) ;\n HTTP_STATUS_ENTRY ( 505 , HTTP Version Not Supported ) ;\n HTTP_STATUS_ENTRY ( 506 , Variant Also Negotiates ) ;\n HTTP_STATUS_ENTRY ( 507 , Insufficient Storage ) ;\n HTTP_STATUS_ENTRY ( 508 , Loop Detected ) ;\n HTTP_STATUS_ENTRY ( 510 , Not Extended ) ;\n HTTP_STATUS_ENTRY ( 511 , Network Authentication Required ) ;\n }\n # undef HTTP_STATUS_ENTRY return nullptr ;\n }","target":0,"code_token_length":836,"total_token_length":1167,"max_tokens_setting":2048} +{"idx":423023,"func":"void __init tcp_init(void)\n{\n\tstruct sk_buff *skb = NULL;\n\tunsigned long limit;\n\tint max_rshare, max_wshare, cnt;\n\tunsigned int i;\n\n\tBUILD_BUG_ON(sizeof(struct tcp_skb_cb) > sizeof(skb->cb));\n\n\tpercpu_counter_init(&tcp_sockets_allocated, 0);\n\tpercpu_counter_init(&tcp_orphan_count, 0);\n\ttcp_hashinfo.bind_bucket_cachep =\n\t\tkmem_cache_create(\"tcp_bind_bucket\",\n\t\t\t\t sizeof(struct inet_bind_bucket), 0,\n\t\t\t\t SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);\n\n\t\/* Size and allocate the main established and bind bucket\n\t * hash tables.\n\t *\n\t * The methodology is similar to that of the buffer cache.\n\t *\/\n\ttcp_hashinfo.ehash =\n\t\talloc_large_system_hash(\"TCP established\",\n\t\t\t\t\tsizeof(struct inet_ehash_bucket),\n\t\t\t\t\tthash_entries,\n\t\t\t\t\t17, \/* one slot per 128 KB of memory *\/\n\t\t\t\t\t0,\n\t\t\t\t\tNULL,\n\t\t\t\t\t&tcp_hashinfo.ehash_mask,\n\t\t\t\t\t0,\n\t\t\t\t\tthash_entries ? 0 : 512 * 1024);\n\tfor (i = 0; i <= tcp_hashinfo.ehash_mask; i++)\n\t\tINIT_HLIST_NULLS_HEAD(&tcp_hashinfo.ehash[i].chain, i);\n\n\tif (inet_ehash_locks_alloc(&tcp_hashinfo))\n\t\tpanic(\"TCP: failed to alloc ehash_locks\");\n\ttcp_hashinfo.bhash =\n\t\talloc_large_system_hash(\"TCP bind\",\n\t\t\t\t\tsizeof(struct inet_bind_hashbucket),\n\t\t\t\t\ttcp_hashinfo.ehash_mask + 1,\n\t\t\t\t\t17, \/* one slot per 128 KB of memory *\/\n\t\t\t\t\t0,\n\t\t\t\t\t&tcp_hashinfo.bhash_size,\n\t\t\t\t\tNULL,\n\t\t\t\t\t0,\n\t\t\t\t\t64 * 1024);\n\ttcp_hashinfo.bhash_size = 1U << tcp_hashinfo.bhash_size;\n\tfor (i = 0; i < tcp_hashinfo.bhash_size; i++) {\n\t\tspin_lock_init(&tcp_hashinfo.bhash[i].lock);\n\t\tINIT_HLIST_HEAD(&tcp_hashinfo.bhash[i].chain);\n\t}\n\n\n\tcnt = tcp_hashinfo.ehash_mask + 1;\n\n\ttcp_death_row.sysctl_max_tw_buckets = cnt \/ 2;\n\tsysctl_tcp_max_orphans = cnt \/ 2;\n\tsysctl_max_syn_backlog = max(128, cnt \/ 256);\n\n\ttcp_init_mem();\n\t\/* Set per-socket limits to no more than 1\/128 the pressure threshold *\/\n\tlimit = nr_free_buffer_pages() << (PAGE_SHIFT - 7);\n\tmax_wshare = min(4UL*1024*1024, limit);\n\tmax_rshare = min(6UL*1024*1024, limit);\n\n\tsysctl_tcp_wmem[0] = SK_MEM_QUANTUM;\n\tsysctl_tcp_wmem[1] = 16*1024;\n\tsysctl_tcp_wmem[2] = max(64*1024, max_wshare);\n\n\tsysctl_tcp_rmem[0] = SK_MEM_QUANTUM;\n\tsysctl_tcp_rmem[1] = 87380;\n\tsysctl_tcp_rmem[2] = max(87380, max_rshare);\n\n\tpr_info(\"Hash tables configured (established %u bind %u)\\n\",\n\t\ttcp_hashinfo.ehash_mask + 1, tcp_hashinfo.bhash_size);\n\n\ttcp_metrics_init();\n\n\ttcp_register_congestion_control(&tcp_reno);\n\n\ttcp_tasklet_init();\n}","target":0,"code_token_length":779,"total_token_length":1110,"max_tokens_setting":2048} +{"idx":2511,"func":"static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,\n\t\t\t\t u64 chunk_offset, u64 devid,\n\t\t\t\t u64 physical_offset, u64 physical_len)\n{\n\tstruct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;\n\tstruct extent_map *em;\n\tstruct map_lookup *map;\n\tstruct btrfs_device *dev;\n\tu64 stripe_len;\n\tbool found = false;\n\tint ret = 0;\n\tint i;\n\n\tread_lock(&em_tree->lock);\n\tem = lookup_extent_mapping(em_tree, chunk_offset, 1);\n\tread_unlock(&em_tree->lock);\n\n\tif (!em) {\n\t\tbtrfs_err(fs_info,\n\"dev extent physical offset %llu on devid %llu doesn't have corresponding chunk\",\n\t\t\t physical_offset, devid);\n\t\tret = -EUCLEAN;\n\t\tgoto out;\n\t}\n\n\tmap = em->map_lookup;\n\tstripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);\n\tif (physical_len != stripe_len) {\n\t\tbtrfs_err(fs_info,\n\"dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu\",\n\t\t\t physical_offset, devid, em->start, physical_len,\n\t\t\t stripe_len);\n\t\tret = -EUCLEAN;\n\t\tgoto out;\n\t}\n\n\tfor (i = 0; i < map->num_stripes; i++) {\n\t\tif (map->stripes[i].dev->devid == devid &&\n\t\t map->stripes[i].physical == physical_offset) {\n\t\t\tfound = true;\n\t\t\tif (map->verified_stripes >= map->num_stripes) {\n\t\t\t\tbtrfs_err(fs_info,\n\t\t\t\t\"too many dev extents for chunk %llu found\",\n\t\t\t\t\t em->start);\n\t\t\t\tret = -EUCLEAN;\n\t\t\t\tgoto out;\n\t\t\t}\n\t\t\tmap->verified_stripes++;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (!found) {\n\t\tbtrfs_err(fs_info,\n\t\"dev extent physical offset %llu devid %llu has no corresponding chunk\",\n\t\t\tphysical_offset, devid);\n\t\tret = -EUCLEAN;\n\t}\n\n\t\/* Make sure no dev extent is beyond device bondary *\/\n\tdev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL);\n\tif (!dev) {\n\t\tbtrfs_err(fs_info, \"failed to find devid %llu\", devid);\n\t\tret = -EUCLEAN;\n\t\tgoto out;\n\t}\n\n\t\/* It's possible this device is a dummy for seed device *\/\n\tif (dev->disk_total_bytes == 0) {\n\t\tdev = find_device(fs_info->fs_devices->seed, devid, NULL);\n\t\tif (!dev) {\n\t\t\tbtrfs_err(fs_info, \"failed to find seed devid %llu\",\n\t\t\t\t devid);\n\t\t\tret = -EUCLEAN;\n\t\t\tgoto out;\n\t\t}\n\t}\n\n\tif (physical_offset + physical_len > dev->disk_total_bytes) {\n\t\tbtrfs_err(fs_info,\n\"dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu\",\n\t\t\t devid, physical_offset, physical_len,\n\t\t\t dev->disk_total_bytes);\n\t\tret = -EUCLEAN;\n\t\tgoto out;\n\t}\nout:\n\tfree_extent_map(em);\n\treturn ret;\n}","target":1,"code_token_length":698,"total_token_length":1029,"max_tokens_setting":2048} +{"idx":195511,"func":"static void ipa_device_begin(wmfAPI * API)\n{\n char\n comment[MaxTextExtent];\n\n wmf_magick_t\n *ddata = WMF_MAGICK_GetData(API);\n\n \/* Make SVG output happy *\/\n (void) PushDrawingWand(WmfDrawingWand);\n\n DrawSetViewbox(WmfDrawingWand, 0, 0, ddata->image->columns, ddata->image->rows );\n\n (void) FormatLocaleString(comment,MaxTextExtent,\"Created by ImageMagick %s\",\n GetMagickVersion((size_t *) NULL));\n DrawComment(WmfDrawingWand,comment);\n\n \/* Scale width and height to image *\/\n DrawScale(WmfDrawingWand, ddata->scale_x, ddata->scale_y);\n\n \/* Translate to TL corner of bounding box *\/\n DrawTranslate(WmfDrawingWand, ddata->translate_x, ddata->translate_y);\n\n \/* Apply rotation *\/\n DrawRotate(WmfDrawingWand, ddata->rotate);\n\n if (ddata->image_info->texture == NULL)\n {\n PixelWand\n *background_color;\n\n \/* Draw rectangle in background color *\/\n background_color=NewPixelWand();\n PixelSetQuantumColor(background_color,&ddata->image->background_color);\n DrawSetFillColor(WmfDrawingWand,background_color);\n background_color=DestroyPixelWand(background_color);\n DrawRectangle(WmfDrawingWand,\n XC(ddata->bbox.TL.x),YC(ddata->bbox.TL.y),\n XC(ddata->bbox.BR.x),YC(ddata->bbox.BR.y));\n }\n else\n {\n \/* Draw rectangle with texture image the SVG way *\/\n Image\n *image;\n\n ImageInfo\n *image_info;\n\n ExceptionInfo\n *exception;\n\n exception=AcquireExceptionInfo();\n\n image_info = CloneImageInfo((ImageInfo *) 0);\n (void) CopyMagickString(image_info->filename,ddata->image_info->texture,\n MaxTextExtent);\n if ( ddata->image_info->size )\n CloneString(&image_info->size,ddata->image_info->size);\n\n image = ReadImage(image_info,exception);\n image_info=DestroyImageInfo(image_info);\n if (image)\n {\n char\n pattern_id[30];\n\n MagickWand\n *magick_wand;\n\n (void) CopyMagickString(image->magick,\"MIFF\",MaxTextExtent);\n DrawPushDefs(WmfDrawingWand);\n draw_pattern_push(API,ddata->pattern_id,image->columns,image->rows);\n magick_wand=NewMagickWandFromImage(image);\n (void) DrawComposite(WmfDrawingWand,CopyCompositeOp,0,0,\n image->columns,image->rows,magick_wand);\n magick_wand=DestroyMagickWand(magick_wand);\n (void) DrawPopPattern(WmfDrawingWand);\n DrawPopDefs(WmfDrawingWand);\n (void) FormatLocaleString(pattern_id,MaxTextExtent,\"#brush_%lu\",\n ddata->pattern_id);\n (void) DrawSetFillPatternURL(WmfDrawingWand,pattern_id);\n ++ddata->pattern_id;\n\n DrawRectangle(WmfDrawingWand,\n XC(ddata->bbox.TL.x),YC(ddata->bbox.TL.y),\n XC(ddata->bbox.BR.x),YC(ddata->bbox.BR.y));\n image=DestroyImageList(image);\n }\n else\n {\n LogMagickEvent(CoderEvent,GetMagickModule(),\n \"reading texture image failed!\");\n InheritException(&ddata->image->exception,exception);\n }\n (void) DestroyExceptionInfo(exception);\n }\n\n DrawSetClipRule(WmfDrawingWand,EvenOddRule); \/* Default for WMF is ALTERNATE polygon fill mode *\/\n draw_fill_color_string(WmfDrawingWand,\"none\"); \/* Default brush is WHITE_BRUSH *\/\n draw_stroke_color_string(WmfDrawingWand,\"none\"); \/* Default pen is BLACK_PEN *\/\n DrawSetStrokeLineCap(WmfDrawingWand,ButtCap); \/* Default linecap is PS_ENDCAP_FLAT *\/\n DrawSetStrokeLineJoin(WmfDrawingWand,MiterJoin); \/* Default linejoin is PS_JOIN_MITER *\/\n draw_under_color_string(WmfDrawingWand,\"white\"); \/* Default text box is white *\/\n}\n","target":0,"code_token_length":958,"total_token_length":1289,"max_tokens_setting":2048} +{"idx":123442,"func":"void MSG_ReadDeltaPlayerstate (msg_t *msg, playerState_t *from, playerState_t *to ) {\n\tint\t\t\ti, lc;\n\tint\t\t\tbits;\n\tnetField_t\t*field;\n\tint\t\t\tnumFields;\n\tint\t\t\tstartBit, endBit;\n\tint\t\t\tprint;\n\tint\t\t\t*fromF, *toF;\n\tint\t\t\ttrunc;\n\tplayerState_t\tdummy;\n\n\tif ( !from ) {\n\t\tfrom = &dummy;\n\t\tCom_Memset( &dummy, 0, sizeof( dummy ) );\n\t}\n\t*to = *from;\n\n\tif ( msg->bit == 0 ) {\n\t\tstartBit = msg->readcount * 8 - GENTITYNUM_BITS;\n\t} else {\n\t\tstartBit = ( msg->readcount - 1 ) * 8 + msg->bit - GENTITYNUM_BITS;\n\t}\n\n\t\/\/ shownet 2\/3 will interleave with other printed info, -2 will\n\t\/\/ just print the delta records\n\tif ( cl_shownet && ( cl_shownet->integer >= 2 || cl_shownet->integer == -2 ) ) {\n\t\tprint = 1;\n\t\tCom_Printf( \"%3i: playerstate \", msg->readcount );\n\t} else {\n\t\tprint = 0;\n\t}\n\n\tnumFields = ARRAY_LEN( playerStateFields );\n\tlc = MSG_ReadByte(msg);\n\n\tif ( lc > numFields || lc < 0 ) {\n\t\tCom_Error( ERR_DROP, \"invalid playerState field count\" );\n\t}\n\n\tfor ( i = 0, field = playerStateFields ; i < lc ; i++, field++ ) {\n\t\tfromF = (int *)( (byte *)from + field->offset );\n\t\ttoF = (int *)( (byte *)to + field->offset );\n\n\t\tif ( ! MSG_ReadBits( msg, 1 ) ) {\n\t\t\t\/\/ no change\n\t\t\t*toF = *fromF;\n\t\t} else {\n\t\t\tif ( field->bits == 0 ) {\n\t\t\t\t\/\/ float\n\t\t\t\tif ( MSG_ReadBits( msg, 1 ) == 0 ) {\n\t\t\t\t\t\/\/ integral float\n\t\t\t\t\ttrunc = MSG_ReadBits( msg, FLOAT_INT_BITS );\n\t\t\t\t\t\/\/ bias to allow equal parts positive and negative\n\t\t\t\t\ttrunc -= FLOAT_INT_BIAS;\n\t\t\t\t\t*(float *)toF = trunc; \n\t\t\t\t\tif ( print ) {\n\t\t\t\t\t\tCom_Printf( \"%s:%i \", field->name, trunc );\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ full floating point value\n\t\t\t\t\t*toF = MSG_ReadBits( msg, 32 );\n\t\t\t\t\tif ( print ) {\n\t\t\t\t\t\tCom_Printf( \"%s:%f \", field->name, *(float *)toF );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t\/\/ integer\n\t\t\t\t*toF = MSG_ReadBits( msg, field->bits );\n\t\t\t\tif ( print ) {\n\t\t\t\t\tCom_Printf( \"%s:%i \", field->name, *toF );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfor ( i=lc,field = &playerStateFields[lc];ioffset );\n\t\ttoF = (int *)( (byte *)to + field->offset );\n\t\t\/\/ no change\n\t\t*toF = *fromF;\n\t}\n\n\n\t\/\/ read the arrays\n\tif (MSG_ReadBits( msg, 1 ) ) {\n\t\t\/\/ parse stats\n\t\tif ( MSG_ReadBits( msg, 1 ) ) {\n\t\t\tLOG(\"PS_STATS\");\n\t\t\tbits = MSG_ReadBits (msg, MAX_STATS);\n\t\t\tfor (i=0 ; istats[i] = MSG_ReadShort(msg);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ parse persistant stats\n\t\tif ( MSG_ReadBits( msg, 1 ) ) {\n\t\t\tLOG(\"PS_PERSISTANT\");\n\t\t\tbits = MSG_ReadBits (msg, MAX_PERSISTANT);\n\t\t\tfor (i=0 ; ipersistant[i] = MSG_ReadShort(msg);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ parse ammo\n\t\tif ( MSG_ReadBits( msg, 1 ) ) {\n\t\t\tLOG(\"PS_AMMO\");\n\t\t\tbits = MSG_ReadBits (msg, MAX_WEAPONS);\n\t\t\tfor (i=0 ; iammo[i] = MSG_ReadShort(msg);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t\/\/ parse powerups\n\t\tif ( MSG_ReadBits( msg, 1 ) ) {\n\t\t\tLOG(\"PS_POWERUPS\");\n\t\t\tbits = MSG_ReadBits (msg, MAX_POWERUPS);\n\t\t\tfor (i=0 ; ipowerups[i] = MSG_ReadLong(msg);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tif ( print ) {\n\t\tif ( msg->bit == 0 ) {\n\t\t\tendBit = msg->readcount * 8 - GENTITYNUM_BITS;\n\t\t} else {\n\t\t\tendBit = ( msg->readcount - 1 ) * 8 + msg->bit - GENTITYNUM_BITS;\n\t\t}\n\t\tCom_Printf( \" (%i bits)\\n\", endBit - startBit );\n\t}\n}","target":0,"code_token_length":1197,"total_token_length":1528,"max_tokens_setting":2048} +{"idx":407544,"func":"ldns_bget_token(ldns_buffer *b, char *token, const char *delim, size_t limit)\n{\n\tint c, lc;\n\tint p; \/* 0 -> no parenthese seen, >0 nr of ( seen *\/\n\tint com, quoted;\n\tchar *t;\n\tsize_t i;\n\tconst char *d;\n\tconst char *del;\n\n\t\/* standard delimiters *\/\n\tif (!delim) {\n\t\t\/* from isspace(3) *\/\n\t\tdel = LDNS_PARSE_NORMAL;\n\t} else {\n\t\tdel = delim;\n\t}\n\n\tp = 0;\n\ti = 0;\n\tcom = 0;\n\tquoted = 0;\n\tt = token;\n\tlc = 0;\n\tif (del[0] == '\"') {\n\t\tquoted = 1;\n\t}\n\n\twhile ((c = ldns_bgetc(b)) != EOF) {\n\t\tif (c == '\\r') \/* carriage return *\/\n\t\t\tc = ' ';\n\t\tif (c == '(' && lc != '\\\\' && !quoted) {\n\t\t\t\/* this only counts for non-comments *\/\n\t\t\tif (com == 0) {\n\t\t\t\tp++;\n\t\t\t}\n\t\t\tlc = c;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == ')' && lc != '\\\\' && !quoted) {\n\t\t\t\/* this only counts for non-comments *\/\n\t\t\tif (com == 0) {\n\t\t\t\tp--;\n\t\t\t}\n\t\t\tlc = c;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (p < 0) {\n\t\t\t\/* more ) then ( *\/\n\t\t\t*t = '\\0';\n\t\t\treturn 0;\n\t\t}\n\n\t\t\/* do something with comments ; *\/\n\t\tif (c == ';' && quoted == 0) {\n\t\t\tif (lc != '\\\\') {\n\t\t\t\tcom = 1;\n\t\t\t}\n\t\t}\n\t\tif (c == '\"' && com == 0 && lc != '\\\\') {\n\t\t\tquoted = 1 - quoted;\n\t\t}\n\n\t\tif (c == '\\n' && com != 0) {\n\t\t\t\/* comments *\/\n\t\t\tcom = 0;\n\t\t\t*t = ' ';\n\t\t\tlc = c;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (com == 1) {\n\t\t\t*t = ' ';\n\t\t\tlc = c;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (c == '\\n' && p != 0) {\n\t\t\t\/* in parentheses *\/\n\t\t\t*t++ = ' ';\n\t\t\tlc = c;\n\t\t\tcontinue;\n\t\t}\n\n\t\t\/* check if we hit the delim *\/\n\t\tfor (d = del; *d; d++) {\n if (c == *d && lc != '\\\\' && p == 0) {\n\t\t\t\tgoto tokenread;\n }\n\t\t}\n\n\t\ti++;\n\t\tif (limit > 0 && (i >= limit || (size_t)(t-token) >= limit)) {\n\t\t\t*t = '\\0';\n\t\t\treturn -1;\n\t\t}\n\t\t*t++ = c;\n\n\t\tif (c == '\\\\' && lc == '\\\\') {\n\t\t\tlc = 0;\n\t\t} else {\n\t\t\tlc = c;\n\t\t}\n\t}\n\t*t = '\\0';\n\tif (i == 0) {\n\t\t\/* nothing read *\/\n\t\treturn -1;\n\t}\n\tif (p != 0) {\n\t\treturn -1;\n\t}\n\treturn (ssize_t)i;\n\ntokenread:\n\tif(*del == '\"') \/* do not skip over quotes, they are significant *\/\n\t\tldns_bskipcs(b, del+1);\n\telse\tldns_bskipcs(b, del);\n\t*t = '\\0';\n\n\tif (p != 0) {\n\t\treturn -1;\n\t}\n\treturn (ssize_t)i;\n}","target":0,"code_token_length":769,"total_token_length":1100,"max_tokens_setting":2048} +{"idx":492682,"func":"static int check_return_code(struct bpf_verifier_env *env)\n{\n\tstruct tnum enforce_attach_type_range = tnum_unknown;\n\tconst struct bpf_prog *prog = env->prog;\n\tstruct bpf_reg_state *reg;\n\tstruct tnum range = tnum_range(0, 1);\n\tint err;\n\n\t\/* The struct_ops func-ptr's return type could be \"void\" *\/\n\tif (env->prog->type == BPF_PROG_TYPE_STRUCT_OPS &&\n\t !prog->aux->attach_func_proto->type)\n\t\treturn 0;\n\n\t\/* eBPF calling convetion is such that R0 is used\n\t * to return the value from eBPF program.\n\t * Make sure that it's readable at this time\n\t * of bpf_exit, which means that program wrote\n\t * something into it earlier\n\t *\/\n\terr = check_reg_arg(env, BPF_REG_0, SRC_OP);\n\tif (err)\n\t\treturn err;\n\n\tif (is_pointer_value(env, BPF_REG_0)) {\n\t\tverbose(env, \"R0 leaks addr as return value\\n\");\n\t\treturn -EACCES;\n\t}\n\n\tswitch (env->prog->type) {\n\tcase BPF_PROG_TYPE_CGROUP_SOCK_ADDR:\n\t\tif (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG ||\n\t\t env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG)\n\t\t\trange = tnum_range(1, 1);\n\t\tbreak;\n\tcase BPF_PROG_TYPE_CGROUP_SKB:\n\t\tif (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) {\n\t\t\trange = tnum_range(0, 3);\n\t\t\tenforce_attach_type_range = tnum_range(2, 3);\n\t\t}\n\t\tbreak;\n\tcase BPF_PROG_TYPE_CGROUP_SOCK:\n\tcase BPF_PROG_TYPE_SOCK_OPS:\n\tcase BPF_PROG_TYPE_CGROUP_DEVICE:\n\tcase BPF_PROG_TYPE_CGROUP_SYSCTL:\n\tcase BPF_PROG_TYPE_CGROUP_SOCKOPT:\n\t\tbreak;\n\tcase BPF_PROG_TYPE_RAW_TRACEPOINT:\n\t\tif (!env->prog->aux->attach_btf_id)\n\t\t\treturn 0;\n\t\trange = tnum_const(0);\n\t\tbreak;\n\tdefault:\n\t\treturn 0;\n\t}\n\n\treg = cur_regs(env) + BPF_REG_0;\n\tif (reg->type != SCALAR_VALUE) {\n\t\tverbose(env, \"At program exit the register R0 is not a known value (%s)\\n\",\n\t\t\treg_type_str[reg->type]);\n\t\treturn -EINVAL;\n\t}\n\n\tif (!tnum_in(range, reg->var_off)) {\n\t\tchar tn_buf[48];\n\n\t\tverbose(env, \"At program exit the register R0 \");\n\t\tif (!tnum_is_unknown(reg->var_off)) {\n\t\t\ttnum_strn(tn_buf, sizeof(tn_buf), reg->var_off);\n\t\t\tverbose(env, \"has value %s\", tn_buf);\n\t\t} else {\n\t\t\tverbose(env, \"has unknown scalar value\");\n\t\t}\n\t\ttnum_strn(tn_buf, sizeof(tn_buf), range);\n\t\tverbose(env, \" should have been in %s\\n\", tn_buf);\n\t\treturn -EINVAL;\n\t}\n\n\tif (!tnum_is_unknown(enforce_attach_type_range) &&\n\t tnum_in(enforce_attach_type_range, reg->var_off))\n\t\tenv->prog->enforce_expected_attach_type = 1;\n\treturn 0;\n}","target":0,"code_token_length":740,"total_token_length":1071,"max_tokens_setting":2048} +{"idx":412887,"func":"static void exif_iif_add_value(image_info_type *image_info, int section_index, char *name, int tag, int format, int length, void* value, int motorola_intel TSRMLS_DC)\n{\n\tsize_t idex;\n\tvoid *vptr;\n\timage_info_value *info_value;\n\timage_info_data *info_data;\n\timage_info_data *list;\n\n\tif (length < 0) {\n\t\treturn;\n\t}\n\n\tlist = safe_erealloc(image_info->info_list[section_index].list, (image_info->info_list[section_index].count+1), sizeof(image_info_data), 0);\n\timage_info->info_list[section_index].list = list;\n\n\tinfo_data = &image_info->info_list[section_index].list[image_info->info_list[section_index].count];\n\tmemset(info_data, 0, sizeof(image_info_data));\n\tinfo_data->tag = tag;\n\tinfo_data->format = format;\n\tinfo_data->length = length;\n\tinfo_data->name = estrdup(name);\n\tinfo_value = &info_data->value;\n\n\tswitch (format) {\n\t\tcase TAG_FMT_STRING:\n\t\t\tif (value) {\n\t\t\t\tlength = php_strnlen(value, length);\n\t\t\t\tinfo_value->s = estrndup(value, length);\n\t\t\t\tinfo_data->length = length;\n\t\t\t} else {\n\t\t\t\tinfo_data->length = 0;\n\t\t\t\tinfo_value->s = estrdup(\"\");\n\t\t\t}\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\t\/* Standard says more types possible but skip them...\n\t\t\t * but allow users to handle data if they know how to\n\t\t\t * So not return but use type UNDEFINED\n\t\t\t * return;\n\t\t\t *\/\n\t\t\tinfo_data->tag = TAG_FMT_UNDEFINED;\/* otherwise not freed from memory *\/\n\t\tcase TAG_FMT_SBYTE:\n\t\tcase TAG_FMT_BYTE:\n\t\t\/* in contrast to strings bytes do not need to allocate buffer for NULL if length==0 *\/\n\t\t\tif (!length)\n\t\t\t\tbreak;\n\t\tcase TAG_FMT_UNDEFINED:\n\t\t\tif (value) {\n\t\t\t\tif (tag == TAG_MAKER_NOTE) {\n\t\t\t\t\tlength = (int) php_strnlen(value, length);\n\t\t\t\t}\n\n\t\t\t\t\/* do not recompute length here *\/\n\t\t\t\tinfo_value->s = estrndup(value, length);\n\t\t\t\tinfo_data->length = length;\n\t\t\t} else {\n\t\t\t\tinfo_data->length = 0;\n\t\t\t\tinfo_value->s = estrdup(\"\");\n\t\t\t}\n\t\t\tbreak;\n\n\t\tcase TAG_FMT_USHORT:\n\t\tcase TAG_FMT_ULONG:\n\t\tcase TAG_FMT_URATIONAL:\n\t\tcase TAG_FMT_SSHORT:\n\t\tcase TAG_FMT_SLONG:\n\t\tcase TAG_FMT_SRATIONAL:\n\t\tcase TAG_FMT_SINGLE:\n\t\tcase TAG_FMT_DOUBLE:\n\t\t\tif (length==0) {\n\t\t\t\tbreak;\n\t\t\t} else\n\t\t\tif (length>1) {\n\t\t\t\tinfo_value->list = safe_emalloc(length, sizeof(image_info_value), 0);\n\t\t\t} else {\n\t\t\t\tinfo_value = &info_data->value;\n\t\t\t}\n\t\t\tfor (idex=0,vptr=value; idex<(size_t)length; idex++,vptr=(char *) vptr + php_tiff_bytes_per_format[format]) {\n\t\t\t\tif (length>1) {\n\t\t\t\t\tinfo_value = &info_data->value.list[idex];\n\t\t\t\t}\n\t\t\t\tswitch (format) {\n\t\t\t\t\tcase TAG_FMT_USHORT:\n\t\t\t\t\t\tinfo_value->u = php_ifd_get16u(vptr, motorola_intel);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase TAG_FMT_ULONG:\n\t\t\t\t\t\tinfo_value->u = php_ifd_get32u(vptr, motorola_intel);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase TAG_FMT_URATIONAL:\n\t\t\t\t\t\tinfo_value->ur.num = php_ifd_get32u(vptr, motorola_intel);\n\t\t\t\t\t\tinfo_value->ur.den = php_ifd_get32u(4+(char *)vptr, motorola_intel);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase TAG_FMT_SSHORT:\n\t\t\t\t\t\tinfo_value->i = php_ifd_get16s(vptr, motorola_intel);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase TAG_FMT_SLONG:\n\t\t\t\t\t\tinfo_value->i = php_ifd_get32s(vptr, motorola_intel);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase TAG_FMT_SRATIONAL:\n\t\t\t\t\t\tinfo_value->sr.num = php_ifd_get32u(vptr, motorola_intel);\n\t\t\t\t\t\tinfo_value->sr.den = php_ifd_get32u(4+(char *)vptr, motorola_intel);\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase TAG_FMT_SINGLE:\n#ifdef EXIF_DEBUG\n\t\t\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Found value of type single\");\n#endif\n\t\t\t\t\t\tinfo_value->f = *(float *)value;\n\n\t\t\t\t\tcase TAG_FMT_DOUBLE:\n#ifdef EXIF_DEBUG\n\t\t\t\t\t\tphp_error_docref(NULL TSRMLS_CC, E_WARNING, \"Found value of type double\");\n#endif\n\t\t\t\t\t\tinfo_value->d = *(double *)value;\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t}\n\timage_info->sections_found |= 1<info_list[section_index].count++;\n}","target":0,"code_token_length":1051,"total_token_length":1382,"max_tokens_setting":2048} +{"idx":354131,"func":"find_field_in_tables(THD *thd, Item_ident *item,\n TABLE_LIST *first_table, TABLE_LIST *last_table,\n\t\t Item **ref, find_item_error_report_type report_error,\n bool check_privileges, bool register_tree_change)\n{\n Field *found=0;\n const char *db= item->db_name;\n const char *table_name= item->table_name;\n const char *name= item->field_name;\n uint length=(uint) strlen(name);\n char name_buff[SAFE_NAME_LEN+1];\n TABLE_LIST *cur_table= first_table;\n TABLE_LIST *actual_table;\n bool allow_rowid;\n\n if (!table_name || !table_name[0])\n {\n table_name= 0; \/\/ For easier test\n db= 0;\n }\n\n allow_rowid= table_name || (cur_table && !cur_table->next_local);\n\n if (item->cached_table)\n {\n DBUG_PRINT(\"info\", (\"using cached table\"));\n \/*\n This shortcut is used by prepared statements. We assume that\n TABLE_LIST *first_table is not changed during query execution (which\n is true for all queries except RENAME but luckily RENAME doesn't\n use fields...) so we can rely on reusing pointer to its member.\n With this optimization we also miss case when addition of one more\n field makes some prepared query ambiguous and so erroneous, but we\n accept this trade off.\n *\/\n TABLE_LIST *table_ref= item->cached_table;\n \/*\n The condition (table_ref->view == NULL) ensures that we will call\n find_field_in_table even in the case of information schema tables\n when table_ref->field_translation != NULL.\n *\/\n if (table_ref->table && !table_ref->view &&\n (!table_ref->is_merged_derived() ||\n (!table_ref->is_multitable() && table_ref->merged_for_insert)))\n {\n\n found= find_field_in_table(thd, table_ref->table, name, length,\n TRUE, &(item->cached_field_index));\n#ifndef NO_EMBEDDED_ACCESS_CHECKS\n \/* Check if there are sufficient access rights to the found field. *\/\n if (found && check_privileges && !is_temporary_table(table_ref) &&\n check_column_grant_in_table_ref(thd, table_ref, name, length))\n found= WRONG_GRANT;\n#endif\n }\n else\n found= find_field_in_table_ref(thd, table_ref, name, length, item->name,\n NULL, NULL, ref, check_privileges,\n TRUE, &(item->cached_field_index),\n register_tree_change,\n &actual_table);\n if (found)\n {\n if (found == WRONG_GRANT)\n\treturn (Field*) 0;\n\n \/*\n Only views fields should be marked as dependent, not an underlying\n fields.\n *\/\n if (!table_ref->belong_to_view &&\n !table_ref->belong_to_derived)\n {\n SELECT_LEX *current_sel= item->context->select_lex;\n SELECT_LEX *last_select= table_ref->select_lex;\n bool all_merged= TRUE;\n for (SELECT_LEX *sl= current_sel; sl && sl!=last_select;\n sl=sl->outer_select())\n {\n Item *subs= sl->master_unit()->item;\n if (subs->type() == Item::SUBSELECT_ITEM && \n ((Item_subselect*)subs)->substype() == Item_subselect::IN_SUBS &&\n ((Item_in_subselect*)subs)->test_strategy(SUBS_SEMI_JOIN))\n {\n continue;\n }\n all_merged= FALSE;\n break;\n }\n \/*\n If the field was an outer referencee, mark all selects using this\n sub query as dependent on the outer query\n *\/\n if (!all_merged && current_sel != last_select)\n {\n mark_select_range_as_dependent(thd, last_select, current_sel,\n found, *ref, item, true);\n }\n }\n return found;\n }\n }\n else\n item->can_be_depended= TRUE;\n\n if (db && lower_case_table_names)\n {\n \/*\n convert database to lower case for comparison.\n We can't do this in Item_field as this would change the\n 'name' of the item which may be used in the select list\n *\/\n strmake_buf(name_buff, db);\n my_casedn_str(files_charset_info, name_buff);\n db= name_buff;\n }\n\n if (last_table)\n last_table= last_table->next_name_resolution_table;\n\n for (; cur_table != last_table ;\n cur_table= cur_table->next_name_resolution_table)\n {\n Field *cur_field= find_field_in_table_ref(thd, cur_table, name, length,\n item->name, db, table_name, ref,\n (thd->lex->sql_command ==\n SQLCOM_SHOW_FIELDS)\n ? false : check_privileges,\n allow_rowid,\n &(item->cached_field_index),\n register_tree_change,\n &actual_table);\n if (cur_field)\n {\n if (cur_field == WRONG_GRANT)\n {\n if (thd->lex->sql_command != SQLCOM_SHOW_FIELDS)\n return (Field*) 0;\n\n thd->clear_error();\n cur_field= find_field_in_table_ref(thd, cur_table, name, length,\n item->name, db, table_name, ref,\n false,\n allow_rowid,\n &(item->cached_field_index),\n register_tree_change,\n &actual_table);\n if (cur_field)\n {\n Field *nf=new Field_null(NULL,0,Field::NONE,\n cur_field->field_name,\n &my_charset_bin);\n nf->init(cur_table->table);\n cur_field= nf;\n }\n }\n\n \/*\n Store the original table of the field, which may be different from\n cur_table in the case of NATURAL\/USING join.\n *\/\n item->cached_table= (!actual_table->cacheable_table || found) ?\n 0 : actual_table;\n\n DBUG_ASSERT(thd->where);\n \/*\n If we found a fully qualified field we return it directly as it can't\n have duplicates.\n *\/\n if (db)\n return cur_field;\n \n if (found)\n {\n if (report_error == REPORT_ALL_ERRORS ||\n report_error == IGNORE_EXCEPT_NON_UNIQUE)\n my_error(ER_NON_UNIQ_ERROR, MYF(0),\n table_name ? item->full_name() : name, thd->where);\n return (Field*) 0;\n }\n found= cur_field;\n }\n }\n\n if (found)\n return found;\n \n \/*\n If the field was qualified and there were no tables to search, issue\n an error that an unknown table was given. The situation is detected\n as follows: if there were no tables we wouldn't go through the loop\n and cur_table wouldn't be updated by the loop increment part, so it\n will be equal to the first table.\n *\/\n if (table_name && (cur_table == first_table) &&\n (report_error == REPORT_ALL_ERRORS ||\n report_error == REPORT_EXCEPT_NON_UNIQUE))\n {\n char buff[SAFE_NAME_LEN*2 + 2];\n if (db && db[0])\n {\n strxnmov(buff,sizeof(buff)-1,db,\".\",table_name,NullS);\n table_name=buff;\n }\n my_error(ER_UNKNOWN_TABLE, MYF(0), table_name, thd->where);\n }\n else\n {\n if (report_error == REPORT_ALL_ERRORS ||\n report_error == REPORT_EXCEPT_NON_UNIQUE)\n my_error(ER_BAD_FIELD_ERROR, MYF(0), item->full_name(), thd->where);\n else\n found= not_found_field;\n }\n return found;\n}","target":1,"code_token_length":1696,"total_token_length":2027,"max_tokens_setting":2048} +{"idx":94289,"func":"static int decode_modrm(struct x86_emulate_ctxt *ctxt,\n\t\t\tstruct operand *op)\n{\n\tu8 sib;\n\tint index_reg = 0, base_reg = 0, scale;\n\tint rc = X86EMUL_CONTINUE;\n\tulong modrm_ea = 0;\n\n\tif (ctxt->rex_prefix) {\n\t\tctxt->modrm_reg = (ctxt->rex_prefix & 4) << 1;\t\/* REX.R *\/\n\t\tindex_reg = (ctxt->rex_prefix & 2) << 2; \/* REX.X *\/\n\t\tctxt->modrm_rm = base_reg = (ctxt->rex_prefix & 1) << 3; \/* REG.B *\/\n\t}\n\n\tctxt->modrm = insn_fetch(u8, ctxt);\n\tctxt->modrm_mod |= (ctxt->modrm & 0xc0) >> 6;\n\tctxt->modrm_reg |= (ctxt->modrm & 0x38) >> 3;\n\tctxt->modrm_rm |= (ctxt->modrm & 0x07);\n\tctxt->modrm_seg = VCPU_SREG_DS;\n\n\tif (ctxt->modrm_mod == 3) {\n\t\top->type = OP_REG;\n\t\top->bytes = (ctxt->d & ByteOp) ? 1 : ctxt->op_bytes;\n\t\top->addr.reg = decode_register(ctxt->modrm_rm,\n\t\t\t\t\t ctxt->regs, ctxt->d & ByteOp);\n\t\tif (ctxt->d & Sse) {\n\t\t\top->type = OP_XMM;\n\t\t\top->bytes = 16;\n\t\t\top->addr.xmm = ctxt->modrm_rm;\n\t\t\tread_sse_reg(ctxt, &op->vec_val, ctxt->modrm_rm);\n\t\t\treturn rc;\n\t\t}\n\t\tfetch_register_operand(op);\n\t\treturn rc;\n\t}\n\n\top->type = OP_MEM;\n\n\tif (ctxt->ad_bytes == 2) {\n\t\tunsigned bx = ctxt->regs[VCPU_REGS_RBX];\n\t\tunsigned bp = ctxt->regs[VCPU_REGS_RBP];\n\t\tunsigned si = ctxt->regs[VCPU_REGS_RSI];\n\t\tunsigned di = ctxt->regs[VCPU_REGS_RDI];\n\n\t\t\/* 16-bit ModR\/M decode. *\/\n\t\tswitch (ctxt->modrm_mod) {\n\t\tcase 0:\n\t\t\tif (ctxt->modrm_rm == 6)\n\t\t\t\tmodrm_ea += insn_fetch(u16, ctxt);\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tmodrm_ea += insn_fetch(s8, ctxt);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tmodrm_ea += insn_fetch(u16, ctxt);\n\t\t\tbreak;\n\t\t}\n\t\tswitch (ctxt->modrm_rm) {\n\t\tcase 0:\n\t\t\tmodrm_ea += bx + si;\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tmodrm_ea += bx + di;\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tmodrm_ea += bp + si;\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tmodrm_ea += bp + di;\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tmodrm_ea += si;\n\t\t\tbreak;\n\t\tcase 5:\n\t\t\tmodrm_ea += di;\n\t\t\tbreak;\n\t\tcase 6:\n\t\t\tif (ctxt->modrm_mod != 0)\n\t\t\t\tmodrm_ea += bp;\n\t\t\tbreak;\n\t\tcase 7:\n\t\t\tmodrm_ea += bx;\n\t\t\tbreak;\n\t\t}\n\t\tif (ctxt->modrm_rm == 2 || ctxt->modrm_rm == 3 ||\n\t\t (ctxt->modrm_rm == 6 && ctxt->modrm_mod != 0))\n\t\t\tctxt->modrm_seg = VCPU_SREG_SS;\n\t\tmodrm_ea = (u16)modrm_ea;\n\t} else {\n\t\t\/* 32\/64-bit ModR\/M decode. *\/\n\t\tif ((ctxt->modrm_rm & 7) == 4) {\n\t\t\tsib = insn_fetch(u8, ctxt);\n\t\t\tindex_reg |= (sib >> 3) & 7;\n\t\t\tbase_reg |= sib & 7;\n\t\t\tscale = sib >> 6;\n\n\t\t\tif ((base_reg & 7) == 5 && ctxt->modrm_mod == 0)\n\t\t\t\tmodrm_ea += insn_fetch(s32, ctxt);\n\t\t\telse\n\t\t\t\tmodrm_ea += ctxt->regs[base_reg];\n\t\t\tif (index_reg != 4)\n\t\t\t\tmodrm_ea += ctxt->regs[index_reg] << scale;\n\t\t} else if ((ctxt->modrm_rm & 7) == 5 && ctxt->modrm_mod == 0) {\n\t\t\tif (ctxt->mode == X86EMUL_MODE_PROT64)\n\t\t\t\tctxt->rip_relative = 1;\n\t\t} else\n\t\t\tmodrm_ea += ctxt->regs[ctxt->modrm_rm];\n\t\tswitch (ctxt->modrm_mod) {\n\t\tcase 0:\n\t\t\tif (ctxt->modrm_rm == 5)\n\t\t\t\tmodrm_ea += insn_fetch(s32, ctxt);\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tmodrm_ea += insn_fetch(s8, ctxt);\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tmodrm_ea += insn_fetch(s32, ctxt);\n\t\t\tbreak;\n\t\t}\n\t}\n\top->addr.mem.ea = modrm_ea;\ndone:\n\treturn rc;\n}","target":0,"code_token_length":1146,"total_token_length":1477,"max_tokens_setting":2048} +{"idx":6866,"func":"rename_principal_2_svc(rprinc_arg *arg, struct svc_req *rqstp)\n{\n static generic_ret ret;\n char *prime_arg1,\n *prime_arg2;\n gss_buffer_desc client_name,\n service_name;\n OM_uint32 minor_stat;\n kadm5_server_handle_t handle;\n restriction_t *rp;\n const char *errmsg = NULL;\n size_t tlen1, tlen2, clen, slen;\n char *tdots1, *tdots2, *cdots, *sdots;\n\n xdr_free(xdr_generic_ret, &ret);\n\n if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))\n goto exit_func;\n\n if ((ret.code = check_handle((void *)handle)))\n goto exit_func;\n\n if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {\n ret.code = KADM5_FAILURE;\n goto exit_func;\n }\n if (krb5_unparse_name(handle->context, arg->src, &prime_arg1) ||\n krb5_unparse_name(handle->context, arg->dest, &prime_arg2)) {\n ret.code = KADM5_BAD_PRINCIPAL;\n goto exit_func;\n }\n tlen1 = strlen(prime_arg1);\n trunc_name(&tlen1, &tdots1);\n tlen2 = strlen(prime_arg2);\n trunc_name(&tlen2, &tdots2);\n clen = client_name.length;\n trunc_name(&clen, &cdots);\n slen = service_name.length;\n trunc_name(&slen, &sdots);\n\n ret.code = KADM5_OK;\n if (! CHANGEPW_SERVICE(rqstp)) {\n if (!kadm5int_acl_check(handle->context, rqst2name(rqstp),\n ACL_DELETE, arg->src, NULL))\n ret.code = KADM5_AUTH_DELETE;\n \/* any restrictions at all on the ADD kills the RENAME *\/\n if (!kadm5int_acl_check(handle->context, rqst2name(rqstp),\n ACL_ADD, arg->dest, &rp) || rp) {\n if (ret.code == KADM5_AUTH_DELETE)\n ret.code = KADM5_AUTH_INSUFFICIENT;\n else\n ret.code = KADM5_AUTH_ADD;\n }\n } else\n ret.code = KADM5_AUTH_INSUFFICIENT;\n if (ret.code != KADM5_OK) {\n \/* okay to cast lengths to int because trunc_name limits max value *\/\n krb5_klog_syslog(LOG_NOTICE,\n _(\"Unauthorized request: kadm5_rename_principal, \"\n \"%.*s%s to %.*s%s, \"\n \"client=%.*s%s, service=%.*s%s, addr=%s\"),\n (int)tlen1, prime_arg1, tdots1,\n (int)tlen2, prime_arg2, tdots2,\n (int)clen, (char *)client_name.value, cdots,\n (int)slen, (char *)service_name.value, sdots,\n client_addr(rqstp->rq_xprt));\n } else {\n ret.code = kadm5_rename_principal((void *)handle, arg->src,\n arg->dest);\n if( ret.code != 0 )\n errmsg = krb5_get_error_message(handle->context, ret.code);\n\n \/* okay to cast lengths to int because trunc_name limits max value *\/\n krb5_klog_syslog(LOG_NOTICE,\n _(\"Request: kadm5_rename_principal, \"\n \"%.*s%s to %.*s%s, %s, \"\n \"client=%.*s%s, service=%.*s%s, addr=%s\"),\n (int)tlen1, prime_arg1, tdots1,\n (int)tlen2, prime_arg2, tdots2,\n errmsg ? errmsg : _(\"success\"),\n (int)clen, (char *)client_name.value, cdots,\n (int)slen, (char *)service_name.value, sdots,\n client_addr(rqstp->rq_xprt));\n\n if (errmsg != NULL)\n krb5_free_error_message(handle->context, errmsg);\n\n }\n free(prime_arg1);\n free(prime_arg2);\n gss_release_buffer(&minor_stat, &client_name);\n gss_release_buffer(&minor_stat, &service_name);\nexit_func:\n free_server_handle(handle);\n return &ret;\n}","target":1,"code_token_length":970,"total_token_length":1301,"max_tokens_setting":2048} +{"idx":39876,"func":"got_buffer_from_bus (FlatpakProxyClient *client, ProxySide *side, Buffer *buffer)\n{\n if (client->authenticated && client->proxy->filter)\n {\n g_autoptr(Header) header = NULL;;\n GDBusMessage *rewritten;\n FlatpakPolicy policy;\n ExpectedReplyType expected_reply;\n\n \/* Filter and rewrite incoming messages as needed *\/\n\n header = parse_header (buffer, 0, client->serial_offset, client->hello_serial);\n if (header == NULL)\n {\n g_warning (\"Invalid message header format\");\n buffer_unref (buffer);\n side_closed (side);\n return;\n }\n\n if (!update_socket_messages (side, buffer, header))\n return;\n\n if (client->proxy->log_messages)\n print_incoming_header (header);\n\n if (header->has_reply_serial)\n {\n expected_reply = steal_expected_reply (get_other_side (side), header->reply_serial);\n\n \/* We only allow replies we expect *\/\n if (expected_reply == EXPECTED_REPLY_NONE)\n {\n if (client->proxy->log_messages)\n g_print (\"*Unexpected reply*\\n\");\n buffer_unref (buffer);\n return;\n }\n\n switch (expected_reply)\n {\n case EXPECTED_REPLY_HELLO:\n \/* When we get the initial reply to Hello, allow all\n further communications to our own unique id. *\/\n if (header->type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN)\n {\n g_autofree char *my_id = get_arg0_string (buffer);\n flatpak_proxy_client_update_unique_id_policy (client, my_id, FLATPAK_POLICY_TALK);\n break;\n }\n\n case EXPECTED_REPLY_REWRITE:\n \/* Replace a roundtrip ping with the rewritten message *\/\n\n rewritten = g_hash_table_lookup (client->rewrite_reply,\n GINT_TO_POINTER (header->reply_serial));\n\n if (client->proxy->log_messages)\n g_print (\"*REWRITTEN*\\n\");\n\n g_dbus_message_set_serial (rewritten, header->serial);\n g_clear_pointer (&buffer, buffer_unref);\n buffer = message_to_buffer (rewritten);\n\n g_hash_table_remove (client->rewrite_reply,\n GINT_TO_POINTER (header->reply_serial));\n break;\n\n case EXPECTED_REPLY_FAKE_LIST_NAMES:\n \/* This is a reply from the bus to a fake ListNames\n request, request ownership of any name matching a\n wildcard policy *\/\n\n queue_wildcard_initial_name_ops (client, header, buffer);\n\n \/* Don't forward fake replies to the app *\/\n if (client->proxy->log_messages)\n g_print (\"*SKIPPED*\\n\");\n g_clear_pointer (&buffer, buffer_unref);\n\n \/* Start reading the clients requests now that we are done with the names *\/\n start_reading (&client->client_side);\n break;\n\n case EXPECTED_REPLY_FAKE_GET_NAME_OWNER:\n \/* This is a reply from the bus to a fake GetNameOwner\n request, update the policy for this unique name based on\n the policy *\/\n {\n char *requested_name = g_hash_table_lookup (client->get_owner_reply, GINT_TO_POINTER (header->reply_serial));\n\n if (header->type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN)\n {\n g_autofree char *owner = get_arg0_string (buffer);\n flatpak_proxy_client_update_unique_id_policy_from_name (client, owner, requested_name);\n }\n\n g_hash_table_remove (client->get_owner_reply, GINT_TO_POINTER (header->reply_serial));\n\n \/* Don't forward fake replies to the app *\/\n if (client->proxy->log_messages)\n g_print (\"*SKIPPED*\\n\");\n g_clear_pointer (&buffer, buffer_unref);\n break;\n }\n\n case EXPECTED_REPLY_FILTER:\n if (client->proxy->log_messages)\n g_print (\"*SKIPPED*\\n\");\n g_clear_pointer (&buffer, buffer_unref);\n break;\n\n case EXPECTED_REPLY_LIST_NAMES:\n \/* This is a reply from the bus to a ListNames request, filter\n it according to the policy *\/\n if (header->type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN)\n {\n Buffer *filtered_buffer;\n\n filtered_buffer = filter_names_list (client, buffer);\n g_clear_pointer (&buffer, buffer_unref);\n buffer = filtered_buffer;\n }\n\n break;\n\n case EXPECTED_REPLY_NORMAL:\n break;\n\n default:\n g_warning (\"Unexpected expected reply type %d\", expected_reply);\n }\n }\n else \/* Not reply *\/\n {\n\n \/* Don't allow reply types with no reply_serial *\/\n if (header->type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN ||\n header->type == G_DBUS_MESSAGE_TYPE_ERROR)\n {\n if (client->proxy->log_messages)\n g_print (\"*Invalid reply*\\n\");\n g_clear_pointer (&buffer, buffer_unref);\n }\n\n \/* We filter all NameOwnerChanged signal according to the policy *\/\n if (message_is_name_owner_changed (client, header))\n {\n if (should_filter_name_owner_changed (client, buffer))\n g_clear_pointer (&buffer, buffer_unref);\n }\n }\n\n \/* All incoming broadcast signals are filtered according to policy *\/\n if (header->type == G_DBUS_MESSAGE_TYPE_SIGNAL && header->destination == NULL)\n {\n policy = flatpak_proxy_client_get_policy (client, header->sender);\n if (policy < FLATPAK_POLICY_TALK)\n {\n if (client->proxy->log_messages)\n g_print (\"*FILTERED IN*\\n\");\n g_clear_pointer (&buffer, buffer_unref);\n }\n }\n\n \/* We received and forwarded a message from a trusted peer. Make the policy for\n this unique id SEE so that the client can track its lifetime. *\/\n if (buffer && header->sender && header->sender[0] == ':')\n flatpak_proxy_client_update_unique_id_policy (client, header->sender, FLATPAK_POLICY_SEE);\n\n if (buffer && client_message_generates_reply (header))\n queue_expected_reply (side, header->serial, EXPECTED_REPLY_NORMAL);\n }\n\n if (buffer)\n queue_outgoing_buffer (&client->client_side, buffer);\n}","target":0,"code_token_length":1324,"total_token_length":1655,"max_tokens_setting":2048} +{"idx":106460,"func":"PJ_DEF(pj_status_t) pjmedia_sdp_neg_modify_local_offer2(\n pj_pool_t *pool,\n\t\t\t\t pjmedia_sdp_neg *neg,\n unsigned flags,\n\t\t\t\t const pjmedia_sdp_session *local)\n{\n pjmedia_sdp_session *new_offer;\n pjmedia_sdp_session *old_offer;\n unsigned oi; \/* old offer media index *\/\n pj_status_t status;\n\n \/* Check arguments are valid. *\/\n PJ_ASSERT_RETURN(pool && neg && local, PJ_EINVAL);\n\n \/* Can only do this in STATE_DONE. *\/\n PJ_ASSERT_RETURN(neg->state == PJMEDIA_SDP_NEG_STATE_DONE, \n\t\t PJMEDIA_SDPNEG_EINSTATE);\n\n \/* Validate the new offer *\/\n status = pjmedia_sdp_validate(local);\n if (status != PJ_SUCCESS)\n\treturn status;\n\n \/* Change state to STATE_LOCAL_OFFER *\/\n neg->state = PJMEDIA_SDP_NEG_STATE_LOCAL_OFFER;\n\n \/* When there is no active local SDP in state PJMEDIA_SDP_NEG_STATE_DONE,\n * it means that the previous initial SDP nego must have been failed,\n * so we'll just set the local SDP offer here.\n *\/\n if (!neg->active_local_sdp) {\n\tneg->initial_sdp_tmp = NULL;\n\tneg->initial_sdp = pjmedia_sdp_session_clone(pool, local);\n\tneg->neg_local_sdp = pjmedia_sdp_session_clone(pool, local);\n\n\treturn PJ_SUCCESS;\n }\n\n \/* Init vars *\/\n old_offer = neg->active_local_sdp;\n new_offer = pjmedia_sdp_session_clone(pool, local);\n\n \/* RFC 3264 Section 8: When issuing an offer that modifies the session,\n * the \"o=\" line of the new SDP MUST be identical to that in the\n * previous SDP, except that the version in the origin field MUST\n * increment by one from the previous SDP.\n *\/\n pj_strdup(pool, &new_offer->origin.user, &old_offer->origin.user);\n new_offer->origin.id = old_offer->origin.id;\n\n pj_strdup(pool, &new_offer->origin.net_type, &old_offer->origin.net_type);\n pj_strdup(pool, &new_offer->origin.addr_type,&old_offer->origin.addr_type);\n pj_strdup(pool, &new_offer->origin.addr, &old_offer->origin.addr);\n\n if ((flags & PJMEDIA_SDP_NEG_ALLOW_MEDIA_CHANGE) == 0) {\n \/* Generating the new offer, in the case media lines doesn't match the\n * active SDP (e.g. current\/active SDP's have m=audio and m=video lines,\n * and the new offer only has m=audio line), the negotiator will fix \n * the new offer by reordering and adding the missing media line with \n * port number set to zero.\n *\/\n for (oi = 0; oi < old_offer->media_count; ++oi) {\n\t pjmedia_sdp_media *om;\n\t pjmedia_sdp_media *nm;\n\t unsigned ni; \/* new offer media index *\/\n\t pj_bool_t found = PJ_FALSE;\n\n\t om = old_offer->media[oi];\n\t for (ni = oi; ni < new_offer->media_count; ++ni) {\n\t nm = new_offer->media[ni];\n\t if (pj_strcmp(&nm->desc.media, &om->desc.media) == 0) {\n\t\t if (ni != oi) {\n\t\t \/* The same media found but the position unmatched to\n * the old offer, so let's put this media in the right\n * place, and keep the order of the rest.\n\t\t *\/\n\t\t pj_array_insert(\n new_offer->media,\t\t \/* array *\/\n\t\t\t sizeof(new_offer->media[0]), \/* elmt size*\/\n\t\t\t ni,\t\t\t\t \/* count *\/\n\t\t oi,\t\t\t\t \/* pos *\/\n\t\t\t &nm);\t\t\t \/* new elmt *\/\n\t\t }\n\t\t found = PJ_TRUE;\n\t\t break;\n\t }\n\t }\n\t if (!found) {\n\t pjmedia_sdp_media *m;\n\n\t m = sdp_media_clone_deactivate(pool, om, om, local);\n\n\t pj_array_insert(new_offer->media, sizeof(new_offer->media[0]),\n\t\t\t new_offer->media_count++, oi, &m);\n\t }\n }\n } else {\n \/* If media type change is allowed, the negotiator only needs to fix \n * the new offer by adding the missing media line(s) with port number\n * set to zero.\n *\/\n for (oi = new_offer->media_count; oi < old_offer->media_count; ++oi) {\n pjmedia_sdp_media *m;\n\n\t m = sdp_media_clone_deactivate(pool, old_offer->media[oi],\n old_offer->media[oi], local);\n\n\t pj_array_insert(new_offer->media, sizeof(new_offer->media[0]),\n\t new_offer->media_count++, oi, &m);\n\n }\n }\n\n \/* New_offer fixed *\/\n#if PJMEDIA_SDP_NEG_COMPARE_BEFORE_INC_VERSION\n new_offer->origin.version = old_offer->origin.version;\n\n if (pjmedia_sdp_session_cmp(new_offer, neg->initial_sdp, 0) != PJ_SUCCESS)\n {\n\t++new_offer->origin.version;\n } \n#else\n new_offer->origin.version = old_offer->origin.version + 1;\n#endif\n \n neg->initial_sdp_tmp = neg->initial_sdp;\n neg->initial_sdp = new_offer;\n neg->neg_local_sdp = pjmedia_sdp_session_clone(pool, new_offer);\n\n return PJ_SUCCESS;\n}","target":0,"code_token_length":1192,"total_token_length":1523,"max_tokens_setting":2048} +{"idx":27748,"func":"static int decode_bmv_frame ( const uint8_t * source , int src_len , uint8_t * frame , int frame_off ) {\n unsigned val , saved_val = 0 ;\n int tmplen = src_len ;\n const uint8_t * src , * source_end = source + src_len ;\n uint8_t * frame_end = frame + SCREEN_WIDE * SCREEN_HIGH ;\n uint8_t * dst , * dst_end ;\n int len , mask ;\n int forward = ( frame_off <= - SCREEN_WIDE ) || ( frame_off >= 0 ) ;\n int read_two_nibbles , flag ;\n int advance_mode ;\n int mode = 0 ;\n int i ;\n if ( src_len <= 0 ) return AVERROR_INVALIDDATA ;\n if ( forward ) {\n src = source ;\n dst = frame ;\n dst_end = frame_end ;\n }\n else {\n src = source + src_len - 1 ;\n dst = frame_end - 1 ;\n dst_end = frame - 1 ;\n }\n for ( ;\n ;\n ) {\n int shift = 0 ;\n flag = 0 ;\n if ( ! mode || ( tmplen == 4 ) ) {\n if ( src < source || src >= source_end ) return AVERROR_INVALIDDATA ;\n val = * src ;\n read_two_nibbles = 1 ;\n }\n else {\n val = saved_val ;\n read_two_nibbles = 0 ;\n }\n if ( ! ( val & 0xC ) ) {\n for ( ;\n ;\n ) {\n if ( ! read_two_nibbles ) {\n if ( src < source || src >= source_end ) return AVERROR_INVALIDDATA ;\n shift += 2 ;\n val |= * src << shift ;\n if ( * src & 0xC ) break ;\n }\n read_two_nibbles = 0 ;\n shift += 2 ;\n mask = ( 1 << shift ) - 1 ;\n val = ( ( val >> 2 ) & ~ mask ) | ( val & mask ) ;\n NEXT_BYTE ( src ) ;\n if ( ( val & ( 0xC << shift ) ) ) {\n flag = 1 ;\n break ;\n }\n }\n }\n else if ( mode ) {\n flag = tmplen != 4 ;\n }\n if ( flag ) {\n tmplen = 4 ;\n }\n else {\n saved_val = val >> ( 4 + shift ) ;\n tmplen = 0 ;\n val &= ( 1 << ( shift + 4 ) ) - 1 ;\n NEXT_BYTE ( src ) ;\n }\n advance_mode = val & 1 ;\n len = ( val >> 1 ) - 1 ;\n mode += 1 + advance_mode ;\n if ( mode >= 4 ) mode -= 3 ;\n if ( FFABS ( dst_end - dst ) < len ) return AVERROR_INVALIDDATA ;\n switch ( mode ) {\n case 1 : if ( forward ) {\n if ( dst - frame + SCREEN_WIDE < frame_off || dst - frame + SCREEN_WIDE + frame_off < 0 || frame_end - dst < frame_off + len || frame_end - dst < len ) return AVERROR_INVALIDDATA ;\n for ( i = 0 ;\n i < len ;\n i ++ ) dst [ i ] = dst [ frame_off + i ] ;\n dst += len ;\n }\n else {\n dst -= len ;\n if ( dst - frame + SCREEN_WIDE < frame_off || dst - frame + SCREEN_WIDE + frame_off < 0 || frame_end - dst < frame_off + len || frame_end - dst < len ) return AVERROR_INVALIDDATA ;\n for ( i = len - 1 ;\n i >= 0 ;\n i -- ) dst [ i ] = dst [ frame_off + i ] ;\n }\n break ;\n case 2 : if ( forward ) {\n if ( source + src_len - src < len ) return AVERROR_INVALIDDATA ;\n memcpy ( dst , src , len ) ;\n dst += len ;\n src += len ;\n }\n else {\n if ( src - source < len ) return AVERROR_INVALIDDATA ;\n dst -= len ;\n src -= len ;\n memcpy ( dst , src , len ) ;\n }\n break ;\n case 3 : val = forward ? dst [ - 1 ] : dst [ 1 ] ;\n if ( forward ) {\n memset ( dst , val , len ) ;\n dst += len ;\n }\n else {\n dst -= len ;\n memset ( dst , val , len ) ;\n }\n break ;\n default : break ;\n }\n if ( dst == dst_end ) return 0 ;\n }\n return 0 ;\n }","target":0,"code_token_length":900,"total_token_length":1231,"max_tokens_setting":2048} +{"idx":352150,"func":"ecma_date_to_string_format (ecma_number_t datetime_number, \/**< datetime *\/\n const char *format_p) \/**< format buffer *\/\n{\n const uint32_t date_buffer_length = 37;\n JERRY_VLA (lit_utf8_byte_t, date_buffer, date_buffer_length);\n\n lit_utf8_byte_t *dest_p = date_buffer;\n\n while (*format_p != LIT_CHAR_NULL)\n {\n if (*format_p != LIT_CHAR_DOLLAR_SIGN)\n {\n *dest_p++ = (lit_utf8_byte_t) *format_p++;\n continue;\n }\n\n format_p++;\n\n const char *str_p = NULL;\n int32_t number = 0;\n int32_t number_length = 0;\n\n switch (*format_p)\n {\n case LIT_CHAR_UPPERCASE_Y: \/* Year. *\/\n {\n number = ecma_date_year_from_time (datetime_number);\n\n if (number >= 100000 || number <= -100000)\n {\n number_length = 6;\n }\n else if (number >= 10000 || number <= -10000)\n {\n number_length = 5;\n }\n else\n {\n number_length = 4;\n }\n break;\n }\n case LIT_CHAR_LOWERCASE_Y: \/* ISO Year: -000001, 0000, 0001, 9999, +012345 *\/\n {\n number = ecma_date_year_from_time (datetime_number);\n if (0 <= number && number <= 9999)\n {\n number_length = 4;\n }\n else\n {\n number_length = 6;\n }\n break;\n }\n case LIT_CHAR_UPPERCASE_M: \/* Month. *\/\n {\n int32_t month = ecma_date_month_from_time (datetime_number);\n\n JERRY_ASSERT (month >= 0 && month <= 11);\n\n str_p = month_names_p[month];\n break;\n }\n case LIT_CHAR_UPPERCASE_O: \/* Month as number. *\/\n {\n \/* The 'ecma_date_month_from_time' (ECMA 262 v5, 15.9.1.4) returns a\n * number from 0 to 11, but we have to print the month from 1 to 12\n * for ISO 8601 standard (ECMA 262 v5, 15.9.1.15). *\/\n number = ecma_date_month_from_time (datetime_number) + 1;\n number_length = 2;\n break;\n }\n case LIT_CHAR_UPPERCASE_D: \/* Day. *\/\n {\n number = ecma_date_date_from_time (datetime_number);\n number_length = 2;\n break;\n }\n case LIT_CHAR_UPPERCASE_W: \/* Day of week. *\/\n {\n int32_t day = ecma_date_week_day (datetime_number);\n\n JERRY_ASSERT (day >= 0 && day <= 6);\n\n str_p = day_names_p[day];\n break;\n }\n case LIT_CHAR_LOWERCASE_H: \/* Hour. *\/\n {\n number = ecma_date_hour_from_time (datetime_number);\n number_length = 2;\n break;\n }\n case LIT_CHAR_LOWERCASE_M: \/* Minutes. *\/\n {\n number = ecma_date_min_from_time (datetime_number);\n number_length = 2;\n break;\n }\n case LIT_CHAR_LOWERCASE_S: \/* Seconds. *\/\n {\n number = ecma_date_sec_from_time (datetime_number);\n number_length = 2;\n break;\n }\n case LIT_CHAR_LOWERCASE_I: \/* Milliseconds. *\/\n {\n number = ecma_date_ms_from_time (datetime_number);\n number_length = 3;\n break;\n }\n case LIT_CHAR_LOWERCASE_Z: \/* Time zone hours part. *\/\n {\n int32_t time_zone = (int32_t) ecma_date_local_time_zone_adjustment (datetime_number);\n\n if (time_zone >= 0)\n {\n *dest_p++ = LIT_CHAR_PLUS;\n }\n else\n {\n *dest_p++ = LIT_CHAR_MINUS;\n time_zone = -time_zone;\n }\n\n number = time_zone \/ ECMA_DATE_MS_PER_HOUR;\n number_length = 2;\n break;\n }\n default:\n {\n JERRY_ASSERT (*format_p == LIT_CHAR_UPPERCASE_Z); \/* Time zone minutes part. *\/\n\n int32_t time_zone = (int32_t) ecma_date_local_time_zone_adjustment (datetime_number);\n\n if (time_zone < 0)\n {\n time_zone = -time_zone;\n }\n\n number = (time_zone % ECMA_DATE_MS_PER_HOUR) \/ ECMA_DATE_MS_PER_MINUTE;\n number_length = 2;\n break;\n }\n }\n\n format_p++;\n\n if (str_p != NULL)\n {\n \/* Print string values: month or day name which is always 3 characters *\/\n memcpy (dest_p, str_p, 3);\n dest_p += 3;\n continue;\n }\n\n \/* Print right aligned number values. *\/\n JERRY_ASSERT (number_length > 0);\n\n if (number < 0)\n {\n number = -number;\n *dest_p++ = '-';\n }\n else if (*(format_p - 1) == LIT_CHAR_LOWERCASE_Y && number_length == 6)\n {\n \/* positive sign is compulsory for extended years *\/\n *dest_p++ = '+';\n }\n\n dest_p += number_length;\n lit_utf8_byte_t *buffer_p = dest_p;\n\n do\n {\n buffer_p--;\n *buffer_p = (lit_utf8_byte_t) ((number % 10) + (int32_t) LIT_CHAR_0);\n number \/= 10;\n }\n while (--number_length);\n }\n\n JERRY_ASSERT (dest_p <= date_buffer + date_buffer_length);\n\n return ecma_make_string_value (ecma_new_ecma_string_from_utf8 (date_buffer,\n (lit_utf8_size_t) (dest_p - date_buffer)));\n} \/* ecma_date_to_string_format *\/","target":1,"code_token_length":1376,"total_token_length":1707,"max_tokens_setting":2048} +{"idx":224357,"func":"ScriptValue WebGL2RenderingContextBase::getParameter(ScriptState* script_state,\n GLenum pname) {\n if (isContextLost())\n return ScriptValue::CreateNull(script_state);\n switch (pname) {\n case GL_SHADING_LANGUAGE_VERSION: {\n return WebGLAny(\n script_state,\n \"WebGL GLSL ES 3.00 (\" +\n String(ContextGL()->GetString(GL_SHADING_LANGUAGE_VERSION)) +\n \")\");\n }\n case GL_VERSION:\n return WebGLAny(\n script_state,\n \"WebGL 2.0 (\" + String(ContextGL()->GetString(GL_VERSION)) + \")\");\n\n case GL_COPY_READ_BUFFER_BINDING:\n return WebGLAny(script_state, bound_copy_read_buffer_.Get());\n case GL_COPY_WRITE_BUFFER_BINDING:\n return WebGLAny(script_state, bound_copy_write_buffer_.Get());\n case GL_DRAW_FRAMEBUFFER_BINDING:\n return WebGLAny(script_state, framebuffer_binding_.Get());\n case GL_FRAGMENT_SHADER_DERIVATIVE_HINT:\n return GetUnsignedIntParameter(script_state, pname);\n case GL_MAX_3D_TEXTURE_SIZE:\n return GetIntParameter(script_state, pname);\n case GL_MAX_ARRAY_TEXTURE_LAYERS:\n return GetIntParameter(script_state, pname);\n case GC3D_MAX_CLIENT_WAIT_TIMEOUT_WEBGL:\n return WebGLAny(script_state, kMaxClientWaitTimeout);\n case GL_MAX_COLOR_ATTACHMENTS:\n return GetIntParameter(script_state, pname);\n case GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS:\n return GetInt64Parameter(script_state, pname);\n case GL_MAX_COMBINED_UNIFORM_BLOCKS:\n return GetIntParameter(script_state, pname);\n case GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS:\n return GetInt64Parameter(script_state, pname);\n case GL_MAX_DRAW_BUFFERS:\n return GetIntParameter(script_state, pname);\n case GL_MAX_ELEMENT_INDEX:\n return GetInt64Parameter(script_state, pname);\n case GL_MAX_ELEMENTS_INDICES:\n return GetIntParameter(script_state, pname);\n case GL_MAX_ELEMENTS_VERTICES:\n return GetIntParameter(script_state, pname);\n case GL_MAX_FRAGMENT_INPUT_COMPONENTS:\n return GetIntParameter(script_state, pname);\n case GL_MAX_FRAGMENT_UNIFORM_BLOCKS:\n return GetIntParameter(script_state, pname);\n case GL_MAX_FRAGMENT_UNIFORM_COMPONENTS:\n return GetIntParameter(script_state, pname);\n case GL_MAX_PROGRAM_TEXEL_OFFSET:\n return GetIntParameter(script_state, pname);\n case GL_MAX_SAMPLES:\n return GetIntParameter(script_state, pname);\n case GL_MAX_SERVER_WAIT_TIMEOUT:\n return GetInt64Parameter(script_state, pname);\n case GL_MAX_TEXTURE_LOD_BIAS:\n return GetFloatParameter(script_state, pname);\n case GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS:\n return GetIntParameter(script_state, pname);\n case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS:\n return GetIntParameter(script_state, pname);\n case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS:\n return GetIntParameter(script_state, pname);\n case GL_MAX_UNIFORM_BLOCK_SIZE:\n return GetInt64Parameter(script_state, pname);\n case GL_MAX_UNIFORM_BUFFER_BINDINGS:\n return GetIntParameter(script_state, pname);\n case GL_MAX_VARYING_COMPONENTS:\n return GetIntParameter(script_state, pname);\n case GL_MAX_VERTEX_OUTPUT_COMPONENTS:\n return GetIntParameter(script_state, pname);\n case GL_MAX_VERTEX_UNIFORM_BLOCKS:\n return GetIntParameter(script_state, pname);\n case GL_MAX_VERTEX_UNIFORM_COMPONENTS:\n return GetIntParameter(script_state, pname);\n case GL_MIN_PROGRAM_TEXEL_OFFSET:\n return GetIntParameter(script_state, pname);\n case GL_PACK_ROW_LENGTH:\n return GetIntParameter(script_state, pname);\n case GL_PACK_SKIP_PIXELS:\n return GetIntParameter(script_state, pname);\n case GL_PACK_SKIP_ROWS:\n return GetIntParameter(script_state, pname);\n case GL_PIXEL_PACK_BUFFER_BINDING:\n return WebGLAny(script_state, bound_pixel_pack_buffer_.Get());\n case GL_PIXEL_UNPACK_BUFFER_BINDING:\n return WebGLAny(script_state, bound_pixel_unpack_buffer_.Get());\n case GL_RASTERIZER_DISCARD:\n return GetBooleanParameter(script_state, pname);\n case GL_READ_BUFFER: {\n GLenum value = 0;\n if (!isContextLost()) {\n WebGLFramebuffer* read_framebuffer_binding =\n GetFramebufferBinding(GL_READ_FRAMEBUFFER);\n if (!read_framebuffer_binding)\n value = read_buffer_of_default_framebuffer_;\n else\n value = read_framebuffer_binding->GetReadBuffer();\n }\n return WebGLAny(script_state, value);\n }\n case GL_READ_FRAMEBUFFER_BINDING:\n return WebGLAny(script_state, read_framebuffer_binding_.Get());\n case GL_SAMPLER_BINDING:\n return WebGLAny(script_state, sampler_units_[active_texture_unit_].Get());\n case GL_TEXTURE_BINDING_2D_ARRAY:\n return WebGLAny(\n script_state,\n texture_units_[active_texture_unit_].texture2d_array_binding_.Get());\n case GL_TEXTURE_BINDING_3D:\n return WebGLAny(\n script_state,\n texture_units_[active_texture_unit_].texture3d_binding_.Get());\n case GL_TRANSFORM_FEEDBACK_ACTIVE:\n return GetBooleanParameter(script_state, pname);\n case GL_TRANSFORM_FEEDBACK_BUFFER_BINDING:\n return WebGLAny(\n script_state,\n transform_feedback_binding_->GetBoundTransformFeedbackBuffer());\n case GL_TRANSFORM_FEEDBACK_BINDING:\n if (!transform_feedback_binding_->IsDefaultObject()) {\n return WebGLAny(script_state, transform_feedback_binding_.Get());\n }\n return ScriptValue::CreateNull(script_state);\n case GL_TRANSFORM_FEEDBACK_PAUSED:\n return GetBooleanParameter(script_state, pname);\n case GL_UNIFORM_BUFFER_BINDING:\n return WebGLAny(script_state, bound_uniform_buffer_.Get());\n case GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT:\n return GetIntParameter(script_state, pname);\n case GL_UNPACK_IMAGE_HEIGHT:\n return GetIntParameter(script_state, pname);\n case GL_UNPACK_ROW_LENGTH:\n return GetIntParameter(script_state, pname);\n case GL_UNPACK_SKIP_IMAGES:\n return GetIntParameter(script_state, pname);\n case GL_UNPACK_SKIP_PIXELS:\n return GetIntParameter(script_state, pname);\n case GL_UNPACK_SKIP_ROWS:\n return GetIntParameter(script_state, pname);\n case GL_TIMESTAMP_EXT:\n if (ExtensionEnabled(kEXTDisjointTimerQueryWebGL2Name)) {\n return WebGLAny(script_state, 0);\n }\n SynthesizeGLError(GL_INVALID_ENUM, \"getParameter\",\n \"invalid parameter name, \"\n \"EXT_disjoint_timer_query_webgl2 not enabled\");\n return ScriptValue::CreateNull(script_state);\n case GL_GPU_DISJOINT_EXT:\n if (ExtensionEnabled(kEXTDisjointTimerQueryWebGL2Name)) {\n return GetBooleanParameter(script_state, GL_GPU_DISJOINT_EXT);\n }\n SynthesizeGLError(GL_INVALID_ENUM, \"getParameter\",\n \"invalid parameter name, \"\n \"EXT_disjoint_timer_query_webgl2 not enabled\");\n return ScriptValue::CreateNull(script_state);\n\n default:\n return WebGLRenderingContextBase::getParameter(script_state, pname);\n }\n}\n","target":0,"code_token_length":1507,"total_token_length":1838,"max_tokens_setting":2048} +{"idx":340039,"func":"static int h264_mp4toannexb_filter(AVBitStreamFilterContext *bsfc,\n\n AVCodecContext *avctx, const char *args,\n\n uint8_t **poutbuf, int *poutbuf_size,\n\n const uint8_t *buf, int buf_size,\n\n int keyframe) {\n\n H264BSFContext *ctx = bsfc->priv_data;\n\n uint8_t unit_type;\n\n uint32_t nal_size, cumul_size = 0;\n\n\n\n \/* nothing to filter *\/\n\n if (!avctx->extradata || avctx->extradata_size < 6) {\n\n *poutbuf = (uint8_t*) buf;\n\n *poutbuf_size = buf_size;\n\n return 0;\n\n }\n\n\n\n \/* retrieve sps and pps NAL units from extradata *\/\n\n if (!ctx->sps_pps_data) {\n\n uint16_t unit_size;\n\n uint32_t total_size = 0;\n\n uint8_t *out = NULL, unit_nb, sps_done = 0;\n\n const uint8_t *extradata = avctx->extradata+4;\n\n static const uint8_t nalu_header[4] = {0, 0, 0, 1};\n\n\n\n \/* retrieve length coded size *\/\n\n ctx->length_size = (*extradata++ & 0x3) + 1;\n\n if (ctx->length_size == 3)\n\n return AVERROR(EINVAL);\n\n\n\n \/* retrieve sps and pps unit(s) *\/\n\n unit_nb = *extradata++ & 0x1f; \/* number of sps unit(s) *\/\n\n if (!unit_nb) {\n\n unit_nb = *extradata++; \/* number of pps unit(s) *\/\n\n sps_done++;\n\n }\n\n while (unit_nb--) {\n\n unit_size = AV_RB16(extradata);\n\n total_size += unit_size+4;\n\n if (extradata+2+unit_size > avctx->extradata+avctx->extradata_size) {\n\n av_free(out);\n\n return AVERROR(EINVAL);\n\n }\n\n out = av_realloc(out, total_size);\n\n if (!out)\n\n return AVERROR(ENOMEM);\n\n memcpy(out+total_size-unit_size-4, nalu_header, 4);\n\n memcpy(out+total_size-unit_size, extradata+2, unit_size);\n\n extradata += 2+unit_size;\n\n\n\n if (!unit_nb && !sps_done++)\n\n unit_nb = *extradata++; \/* number of pps unit(s) *\/\n\n }\n\n\n\n ctx->sps_pps_data = out;\n\n ctx->size = total_size;\n\n ctx->first_idr = 1;\n\n }\n\n\n\n *poutbuf_size = 0;\n\n *poutbuf = NULL;\n\n do {\n\n if (ctx->length_size == 1)\n\n nal_size = buf[0];\n\n else if (ctx->length_size == 2)\n\n nal_size = AV_RB16(buf);\n\n else\n\n nal_size = AV_RB32(buf);\n\n\n\n buf += ctx->length_size;\n\n unit_type = *buf & 0x1f;\n\n\n\n \/* prepend only to the first type 5 NAL unit of an IDR picture *\/\n\n if (ctx->first_idr && unit_type == 5) {\n\n alloc_and_copy(poutbuf, poutbuf_size,\n\n ctx->sps_pps_data, ctx->size,\n\n buf, nal_size);\n\n ctx->first_idr = 0;\n\n }\n\n else {\n\n alloc_and_copy(poutbuf, poutbuf_size,\n\n NULL, 0,\n\n buf, nal_size);\n\n if (!ctx->first_idr && unit_type == 1)\n\n ctx->first_idr = 1;\n\n }\n\n\n\n buf += nal_size;\n\n cumul_size += nal_size + ctx->length_size;\n\n } while (cumul_size < buf_size);\n\n\n\n return 1;\n\n}\n","target":0,"code_token_length":850,"total_token_length":1181,"max_tokens_setting":2048} +{"idx":111509,"func":"static int initialize_context_compression(\n blosc2_context* context, const void* src, int32_t srcsize, void* dest,\n int32_t destsize, int clevel, uint8_t const *filters,\n uint8_t const *filters_meta, int32_t typesize, int compressor,\n int32_t blocksize, int new_nthreads, int nthreads, blosc2_schunk* schunk) {\n\n \/* Set parameters *\/\n context->do_compress = 1;\n context->src = (const uint8_t*)src;\n context->srcsize = srcsize;\n context->dest = (uint8_t*)dest;\n context->output_bytes = 0;\n context->destsize = destsize;\n context->sourcesize = srcsize;\n context->typesize = (int32_t)typesize;\n context->filter_flags = filters_to_flags(filters);\n for (int i = 0; i < BLOSC2_MAX_FILTERS; i++) {\n context->filters[i] = filters[i];\n context->filters_meta[i] = filters_meta[i];\n }\n context->compcode = compressor;\n context->nthreads = nthreads;\n context->new_nthreads = new_nthreads;\n context->end_threads = 0;\n context->clevel = clevel;\n context->schunk = schunk;\n\n \/* Tune some compression parameters *\/\n context->blocksize = (int32_t)blocksize;\n if (context->btune != NULL) {\n btune_next_cparams(context);\n } else {\n btune_next_blocksize(context);\n }\n\n char* envvar = getenv(\"BLOSC_WARN\");\n int warnlvl = 0;\n if (envvar != NULL) {\n warnlvl = strtol(envvar, NULL, 10);\n }\n\n \/* Check buffer size limits *\/\n if (srcsize > BLOSC_MAX_BUFFERSIZE) {\n if (warnlvl > 0) {\n fprintf(stderr, \"Input buffer size cannot exceed %d bytes\\n\",\n BLOSC_MAX_BUFFERSIZE);\n }\n return 0;\n }\n\n if (destsize < BLOSC_MAX_OVERHEAD) {\n if (warnlvl > 0) {\n fprintf(stderr, \"Output buffer size should be larger than %d bytes\\n\",\n BLOSC_MAX_OVERHEAD);\n }\n return 0;\n }\n\n if (destsize < BLOSC_MAX_OVERHEAD) {\n if (warnlvl > 0) {\n fprintf(stderr, \"Output buffer size should be larger than %d bytes\\n\",\n BLOSC_MAX_OVERHEAD);\n }\n return -2;\n }\n if (destsize < BLOSC_MAX_OVERHEAD) {\n fprintf(stderr, \"Output buffer size should be larger than %d bytes\\n\",\n BLOSC_MAX_OVERHEAD);\n return -1;\n }\n\n \/* Compression level *\/\n if (clevel < 0 || clevel > 9) {\n \/* If clevel not in 0..9, print an error *\/\n fprintf(stderr, \"`clevel` parameter must be between 0 and 9!\\n\");\n return -10;\n }\n\n \/* Check typesize limits *\/\n if (context->typesize > BLOSC_MAX_TYPESIZE) {\n \/* If typesize is too large, treat buffer as an 1-byte stream. *\/\n context->typesize = 1;\n }\n\n \/* Compute number of blocks in buffer *\/\n context->nblocks = context->sourcesize \/ context->blocksize;\n context->leftover = context->sourcesize % context->blocksize;\n context->nblocks = (context->leftover > 0) ?\n (context->nblocks + 1) : context->nblocks;\n\n return 1;\n}","target":0,"code_token_length":826,"total_token_length":1157,"max_tokens_setting":2048} +{"idx":272626,"func":"static void move_back(compiler_common *common, jump_list **backtracks, BOOL must_be_valid)\n{\n\/* Goes one character back. Affects STR_PTR and TMP1. If must_be_valid is TRUE,\nTMP2 is not used. Otherwise TMP2 must contain the start of the subject buffer,\nand it is destroyed. Does not modify STR_PTR for invalid character sequences. *\/\nDEFINE_COMPILER;\n\n#if defined SUPPORT_UNICODE && PCRE2_CODE_UNIT_WIDTH != 32\nstruct sljit_jump *jump;\n#endif\n\n#ifdef SUPPORT_UNICODE\n#if PCRE2_CODE_UNIT_WIDTH == 8\nstruct sljit_label *label;\n\nif (common->utf)\n {\n if (!must_be_valid && common->invalid_utf)\n {\n OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), -IN_UCHARS(1));\n OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1));\n jump = CMP(SLJIT_LESS, TMP1, 0, SLJIT_IMM, 0x80);\n add_jump(compiler, &common->utfmoveback_invalid, JUMP(SLJIT_FAST_CALL));\n if (backtracks != NULL)\n add_jump(compiler, backtracks, CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, 0));\n JUMPHERE(jump);\n return;\n }\n\n label = LABEL();\n OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), -IN_UCHARS(1));\n OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1));\n OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xc0);\n CMPTO(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, 0x80, label);\n return;\n }\n#elif PCRE2_CODE_UNIT_WIDTH == 16\nif (common->utf)\n {\n OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), -IN_UCHARS(1));\n OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1));\n\n if (!must_be_valid && common->invalid_utf)\n {\n OP2(SLJIT_SUB, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xd800);\n jump = CMP(SLJIT_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, 0xe000 - 0xd800);\n add_jump(compiler, &common->utfmoveback_invalid, JUMP(SLJIT_FAST_CALL));\n if (backtracks != NULL)\n add_jump(compiler, backtracks, CMP(SLJIT_EQUAL, TMP1, 0, SLJIT_IMM, 0));\n JUMPHERE(jump);\n return;\n }\n\n \/* Skip low surrogate if necessary. *\/\n OP2(SLJIT_AND, TMP1, 0, TMP1, 0, SLJIT_IMM, 0xfc00);\n OP2U(SLJIT_SUB | SLJIT_SET_Z, TMP1, 0, SLJIT_IMM, 0xdc00);\n OP_FLAGS(SLJIT_MOV, TMP1, 0, SLJIT_EQUAL);\n OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, UCHAR_SHIFT);\n OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, TMP1, 0);\n return;\n }\n#elif PCRE2_CODE_UNIT_WIDTH == 32\nif (common->invalid_utf && !must_be_valid)\n {\n OP1(MOV_UCHAR, TMP1, 0, SLJIT_MEM1(STR_PTR), -IN_UCHARS(1));\n if (backtracks != NULL)\n {\n add_jump(compiler, backtracks, CMP(SLJIT_GREATER_EQUAL, TMP1, 0, SLJIT_IMM, 0x110000));\n OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1));\n return;\n }\n\n OP2U(SLJIT_SUB | SLJIT_SET_LESS, TMP1, 0, SLJIT_IMM, 0x110000);\n OP_FLAGS(SLJIT_MOV, TMP1, 0, SLJIT_LESS);\n OP2(SLJIT_SHL, TMP1, 0, TMP1, 0, SLJIT_IMM, UCHAR_SHIFT);\n OP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, TMP1, 0);\n return;\n }\n#endif \/* PCRE2_CODE_UNIT_WIDTH == [8|16|32] *\/\n#endif \/* SUPPORT_UNICODE *\/\n\nSLJIT_UNUSED_ARG(backtracks);\nSLJIT_UNUSED_ARG(must_be_valid);\n\nOP2(SLJIT_SUB, STR_PTR, 0, STR_PTR, 0, SLJIT_IMM, IN_UCHARS(1));\n}","target":0,"code_token_length":1184,"total_token_length":1515,"max_tokens_setting":2048} +{"idx":173007,"func":"IHEVCD_ERROR_T ihevcd_get_tile_pos(pps_t *ps_pps,\n sps_t *ps_sps,\n WORD32 ctb_x,\n WORD32 ctb_y,\n WORD32 *pi4_ctb_tile_x,\n WORD32 *pi4_ctb_tile_y,\n WORD32 *pi4_tile_idx)\n{\n\n tile_t *ps_tile_tmp;\n WORD32 i;\n WORD32 tile_row, tile_col;\n\n if(ctb_x < 0 || ctb_y < 0)\n {\n *pi4_ctb_tile_x = 0;\n *pi4_ctb_tile_y = 0;\n *pi4_tile_idx = 0;\n\n return (IHEVCD_ERROR_T)IHEVCD_SUCCESS;\n }\n\n tile_row = 0;\n tile_col = 0;\n ps_tile_tmp = ps_pps->ps_tile;\n if(0 == ps_pps->i1_tiles_enabled_flag)\n {\n *pi4_ctb_tile_x = ctb_x;\n *pi4_ctb_tile_y = ctb_y;\n *pi4_tile_idx = 0;\n }\n else\n {\n for(i = 0; i < ps_pps->i1_num_tile_columns; i++)\n {\n WORD16 next_tile_ctb_x;\n ps_tile_tmp = ps_pps->ps_tile + i; \/\/* ps_pps->i1_num_tile_rows;\n if((ps_pps->i1_num_tile_columns - 1) == i)\n {\n next_tile_ctb_x = ps_sps->i2_pic_wd_in_ctb;\n }\n else\n {\n tile_t *ps_tile_next_tmp;\n ps_tile_next_tmp = ps_pps->ps_tile + i + 1;\n next_tile_ctb_x = ps_tile_next_tmp->u1_pos_x;\n }\n if((ctb_x >= ps_tile_tmp->u1_pos_x) && (ctb_x < next_tile_ctb_x))\n {\n tile_col = i;\n break;\n }\n }\n *pi4_ctb_tile_x = ctb_x - ps_tile_tmp->u1_pos_x;\n\n for(i = 0; i < ps_pps->i1_num_tile_rows; i++)\n {\n WORD16 next_tile_ctb_y;\n ps_tile_tmp = ps_pps->ps_tile + i * ps_pps->i1_num_tile_columns;\n if((ps_pps->i1_num_tile_rows - 1) == i)\n {\n next_tile_ctb_y = ps_sps->i2_pic_ht_in_ctb;\n }\n else\n {\n tile_t *ps_tile_next_tmp;\n ps_tile_next_tmp = ps_pps->ps_tile + ((i + 1) * ps_pps->i1_num_tile_columns);\n next_tile_ctb_y = ps_tile_next_tmp->u1_pos_y;\n }\n if((ctb_y >= ps_tile_tmp->u1_pos_y) && (ctb_y < next_tile_ctb_y))\n {\n tile_row = i;\n break;\n }\n\n }\n *pi4_ctb_tile_y = ctb_y - ps_tile_tmp->u1_pos_y;\n *pi4_tile_idx = tile_row * ps_pps->i1_num_tile_columns\n + tile_col;\n }\n return (IHEVCD_ERROR_T)IHEVCD_SUCCESS;\n}\n","target":0,"code_token_length":698,"total_token_length":1029,"max_tokens_setting":2048} +{"idx":318425,"func":"static int config_props(AVFilterLink *inlink)\n\n{\n\n AVFilterContext *ctx = inlink->dst;\n\n LutContext *lut = ctx->priv;\n\n const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[inlink->format];\n\n int min[4], max[4];\n\n int val, comp, ret;\n\n\n\n lut->hsub = desc->log2_chroma_w;\n\n lut->vsub = desc->log2_chroma_h;\n\n\n\n lut->var_values[VAR_W] = inlink->w;\n\n lut->var_values[VAR_H] = inlink->h;\n\n\n\n switch (inlink->format) {\n\n case PIX_FMT_YUV410P:\n\n case PIX_FMT_YUV411P:\n\n case PIX_FMT_YUV420P:\n\n case PIX_FMT_YUV422P:\n\n case PIX_FMT_YUV440P:\n\n case PIX_FMT_YUV444P:\n\n case PIX_FMT_YUVA420P:\n\n min[Y] = min[U] = min[V] = 16;\n\n max[Y] = 235;\n\n max[U] = max[V] = 240;\n\n min[A] = 0; max[A] = 255;\n\n break;\n\n default:\n\n min[0] = min[1] = min[2] = min[3] = 0;\n\n max[0] = max[1] = max[2] = max[3] = 255;\n\n }\n\n\n\n lut->is_yuv = lut->is_rgb = 0;\n\n if (ff_fmt_is_in(inlink->format, yuv_pix_fmts)) lut->is_yuv = 1;\n\n else if (ff_fmt_is_in(inlink->format, rgb_pix_fmts)) lut->is_rgb = 1;\n\n\n\n if (lut->is_rgb) {\n\n switch (inlink->format) {\n\n case PIX_FMT_ARGB: lut->rgba_map[A] = 0; lut->rgba_map[R] = 1; lut->rgba_map[G] = 2; lut->rgba_map[B] = 3; break;\n\n case PIX_FMT_ABGR: lut->rgba_map[A] = 0; lut->rgba_map[B] = 1; lut->rgba_map[G] = 2; lut->rgba_map[R] = 3; break;\n\n case PIX_FMT_RGBA:\n\n case PIX_FMT_RGB24: lut->rgba_map[R] = 0; lut->rgba_map[G] = 1; lut->rgba_map[B] = 2; lut->rgba_map[A] = 3; break;\n\n case PIX_FMT_BGRA:\n\n case PIX_FMT_BGR24: lut->rgba_map[B] = 0; lut->rgba_map[G] = 1; lut->rgba_map[R] = 2; lut->rgba_map[A] = 3; break;\n\n }\n\n lut->step = av_get_bits_per_pixel(desc) >> 3;\n\n }\n\n\n\n for (comp = 0; comp < desc->nb_components; comp++) {\n\n double res;\n\n\n\n \/* create the parsed expression *\/\n\n ret = av_expr_parse(&lut->comp_expr[comp], lut->comp_expr_str[comp],\n\n var_names, funcs1_names, funcs1, NULL, NULL, 0, ctx);\n\n if (ret < 0) {\n\n av_log(ctx, AV_LOG_ERROR,\n\n \"Error when parsing the expression '%s' for the component %d.\\n\",\n\n lut->comp_expr_str[comp], comp);\n\n return AVERROR(EINVAL);\n\n }\n\n\n\n \/* compute the lut *\/\n\n lut->var_values[VAR_MAXVAL] = max[comp];\n\n lut->var_values[VAR_MINVAL] = min[comp];\n\n\n\n for (val = 0; val < 256; val++) {\n\n lut->var_values[VAR_VAL] = val;\n\n lut->var_values[VAR_CLIPVAL] = av_clip(val, min[comp], max[comp]);\n\n lut->var_values[VAR_NEGVAL] =\n\n av_clip(min[comp] + max[comp] - lut->var_values[VAR_VAL],\n\n min[comp], max[comp]);\n\n\n\n res = av_expr_eval(lut->comp_expr[comp], lut->var_values, lut);\n\n if (isnan(res)) {\n\n av_log(ctx, AV_LOG_ERROR,\n\n \"Error when evaluating the expression '%s' for the value %d for the component #%d.\\n\",\n\n lut->comp_expr_str[comp], val, comp);\n\n return AVERROR(EINVAL);\n\n }\n\n lut->lut[comp][val] = av_clip((int)res, min[comp], max[comp]);\n\n av_log(ctx, AV_LOG_DEBUG, \"val[%d][%d] = %d\\n\", comp, val, lut->lut[comp][val]);\n\n }\n\n }\n\n\n\n return 0;\n\n}\n","target":0,"code_token_length":1060,"total_token_length":1391,"max_tokens_setting":2048} +{"idx":285048,"func":"static int __mem_cgroup_try_charge(struct mm_struct *mm,\n\t\t\t\t gfp_t gfp_mask,\n\t\t\t\t unsigned int nr_pages,\n\t\t\t\t struct mem_cgroup **ptr,\n\t\t\t\t bool oom)\n{\n\tunsigned int batch = max(CHARGE_BATCH, nr_pages);\n\tint nr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;\n\tstruct mem_cgroup *memcg = NULL;\n\tint ret;\n\n\t\/*\n\t * Unlike gloval-vm's OOM-kill, we're not in memory shortage\n\t * in system level. So, allow to go ahead dying process in addition to\n\t * MEMDIE process.\n\t *\/\n\tif (unlikely(test_thread_flag(TIF_MEMDIE)\n\t\t || fatal_signal_pending(current)))\n\t\tgoto bypass;\n\n\t\/*\n\t * We always charge the cgroup the mm_struct belongs to.\n\t * The mm_struct's mem_cgroup changes on task migration if the\n\t * thread group leader migrates. It's possible that mm is not\n\t * set, if so charge the init_mm (happens for pagecache usage).\n\t *\/\n\tif (!*ptr && !mm)\n\t\t*ptr = root_mem_cgroup;\nagain:\n\tif (*ptr) { \/* css should be a valid one *\/\n\t\tmemcg = *ptr;\n\t\tVM_BUG_ON(css_is_removed(&memcg->css));\n\t\tif (mem_cgroup_is_root(memcg))\n\t\t\tgoto done;\n\t\tif (nr_pages == 1 && consume_stock(memcg))\n\t\t\tgoto done;\n\t\tcss_get(&memcg->css);\n\t} else {\n\t\tstruct task_struct *p;\n\n\t\trcu_read_lock();\n\t\tp = rcu_dereference(mm->owner);\n\t\t\/*\n\t\t * Because we don't have task_lock(), \"p\" can exit.\n\t\t * In that case, \"memcg\" can point to root or p can be NULL with\n\t\t * race with swapoff. Then, we have small risk of mis-accouning.\n\t\t * But such kind of mis-account by race always happens because\n\t\t * we don't have cgroup_mutex(). It's overkill and we allo that\n\t\t * small race, here.\n\t\t * (*) swapoff at el will charge against mm-struct not against\n\t\t * task-struct. So, mm->owner can be NULL.\n\t\t *\/\n\t\tmemcg = mem_cgroup_from_task(p);\n\t\tif (!memcg)\n\t\t\tmemcg = root_mem_cgroup;\n\t\tif (mem_cgroup_is_root(memcg)) {\n\t\t\trcu_read_unlock();\n\t\t\tgoto done;\n\t\t}\n\t\tif (nr_pages == 1 && consume_stock(memcg)) {\n\t\t\t\/*\n\t\t\t * It seems dagerous to access memcg without css_get().\n\t\t\t * But considering how consume_stok works, it's not\n\t\t\t * necessary. If consume_stock success, some charges\n\t\t\t * from this memcg are cached on this cpu. So, we\n\t\t\t * don't need to call css_get()\/css_tryget() before\n\t\t\t * calling consume_stock().\n\t\t\t *\/\n\t\t\trcu_read_unlock();\n\t\t\tgoto done;\n\t\t}\n\t\t\/* after here, we may be blocked. we need to get refcnt *\/\n\t\tif (!css_tryget(&memcg->css)) {\n\t\t\trcu_read_unlock();\n\t\t\tgoto again;\n\t\t}\n\t\trcu_read_unlock();\n\t}\n\n\tdo {\n\t\tbool oom_check;\n\n\t\t\/* If killed, bypass charge *\/\n\t\tif (fatal_signal_pending(current)) {\n\t\t\tcss_put(&memcg->css);\n\t\t\tgoto bypass;\n\t\t}\n\n\t\toom_check = false;\n\t\tif (oom && !nr_oom_retries) {\n\t\t\toom_check = true;\n\t\t\tnr_oom_retries = MEM_CGROUP_RECLAIM_RETRIES;\n\t\t}\n\n\t\tret = mem_cgroup_do_charge(memcg, gfp_mask, batch, oom_check);\n\t\tswitch (ret) {\n\t\tcase CHARGE_OK:\n\t\t\tbreak;\n\t\tcase CHARGE_RETRY: \/* not in OOM situation but retry *\/\n\t\t\tbatch = nr_pages;\n\t\t\tcss_put(&memcg->css);\n\t\t\tmemcg = NULL;\n\t\t\tgoto again;\n\t\tcase CHARGE_WOULDBLOCK: \/* !__GFP_WAIT *\/\n\t\t\tcss_put(&memcg->css);\n\t\t\tgoto nomem;\n\t\tcase CHARGE_NOMEM: \/* OOM routine works *\/\n\t\t\tif (!oom) {\n\t\t\t\tcss_put(&memcg->css);\n\t\t\t\tgoto nomem;\n\t\t\t}\n\t\t\t\/* If oom, we never return -ENOMEM *\/\n\t\t\tnr_oom_retries--;\n\t\t\tbreak;\n\t\tcase CHARGE_OOM_DIE: \/* Killed by OOM Killer *\/\n\t\t\tcss_put(&memcg->css);\n\t\t\tgoto bypass;\n\t\t}\n\t} while (ret != CHARGE_OK);\n\n\tif (batch > nr_pages)\n\t\trefill_stock(memcg, batch - nr_pages);\n\tcss_put(&memcg->css);\ndone:\n\t*ptr = memcg;\n\treturn 0;\nnomem:\n\t*ptr = NULL;\n\treturn -ENOMEM;\nbypass:\n\t*ptr = root_mem_cgroup;\n\treturn -EINTR;\n}\n","target":0,"code_token_length":1074,"total_token_length":1405,"max_tokens_setting":2048} +{"idx":342478,"func":"static CURLState *curl_init_state(BlockDriverState *bs, BDRVCURLState *s)\n\n{\n\n CURLState *state = NULL;\n\n int i, j;\n\n\n\n do {\n\n for (i=0; istates[i].acb[j])\n\n continue;\n\n if (s->states[i].in_use)\n\n continue;\n\n\n\n state = &s->states[i];\n\n state->in_use = 1;\n\n break;\n\n }\n\n if (!state) {\n\n qemu_mutex_unlock(&s->mutex);\n\n aio_poll(bdrv_get_aio_context(bs), true);\n\n qemu_mutex_lock(&s->mutex);\n\n }\n\n } while(!state);\n\n\n\n if (!state->curl) {\n\n state->curl = curl_easy_init();\n\n if (!state->curl) {\n\n return NULL;\n\n }\n\n curl_easy_setopt(state->curl, CURLOPT_URL, s->url);\n\n curl_easy_setopt(state->curl, CURLOPT_SSL_VERIFYPEER,\n\n (long) s->sslverify);\n\n if (s->cookie) {\n\n curl_easy_setopt(state->curl, CURLOPT_COOKIE, s->cookie);\n\n }\n\n curl_easy_setopt(state->curl, CURLOPT_TIMEOUT, (long)s->timeout);\n\n curl_easy_setopt(state->curl, CURLOPT_WRITEFUNCTION,\n\n (void *)curl_read_cb);\n\n curl_easy_setopt(state->curl, CURLOPT_WRITEDATA, (void *)state);\n\n curl_easy_setopt(state->curl, CURLOPT_PRIVATE, (void *)state);\n\n curl_easy_setopt(state->curl, CURLOPT_AUTOREFERER, 1);\n\n curl_easy_setopt(state->curl, CURLOPT_FOLLOWLOCATION, 1);\n\n curl_easy_setopt(state->curl, CURLOPT_NOSIGNAL, 1);\n\n curl_easy_setopt(state->curl, CURLOPT_ERRORBUFFER, state->errmsg);\n\n curl_easy_setopt(state->curl, CURLOPT_FAILONERROR, 1);\n\n\n\n if (s->username) {\n\n curl_easy_setopt(state->curl, CURLOPT_USERNAME, s->username);\n\n }\n\n if (s->password) {\n\n curl_easy_setopt(state->curl, CURLOPT_PASSWORD, s->password);\n\n }\n\n if (s->proxyusername) {\n\n curl_easy_setopt(state->curl,\n\n CURLOPT_PROXYUSERNAME, s->proxyusername);\n\n }\n\n if (s->proxypassword) {\n\n curl_easy_setopt(state->curl,\n\n CURLOPT_PROXYPASSWORD, s->proxypassword);\n\n }\n\n\n\n \/* Restrict supported protocols to avoid security issues in the more\n\n * obscure protocols. For example, do not allow POP3\/SMTP\/IMAP see\n\n * CVE-2013-0249.\n\n *\n\n * Restricting protocols is only supported from 7.19.4 upwards.\n\n *\/\n\n#if LIBCURL_VERSION_NUM >= 0x071304\n\n curl_easy_setopt(state->curl, CURLOPT_PROTOCOLS, PROTOCOLS);\n\n curl_easy_setopt(state->curl, CURLOPT_REDIR_PROTOCOLS, PROTOCOLS);\n\n#endif\n\n\n\n#ifdef DEBUG_VERBOSE\n\n curl_easy_setopt(state->curl, CURLOPT_VERBOSE, 1);\n\n#endif\n\n }\n\n\n\n QLIST_INIT(&state->sockets);\n\n state->s = s;\n\n\n\n return state;\n\n}\n","target":1,"code_token_length":695,"total_token_length":1026,"max_tokens_setting":2048} +{"idx":154986,"func":"static int core_anal_graph_construct_edges(RCore *core, RAnalFunction *fcn, int opts, PJ *pj, Sdb *DB) {\n\tRAnalBlock *bbi;\n\tRListIter *iter;\n\tint is_keva = opts & R_CORE_ANAL_KEYVALUE;\n\tint is_star = opts & R_CORE_ANAL_STAR;\n\tint is_json = opts & R_CORE_ANAL_JSON;\n\tint is_html = r_cons_context ()->is_html;\n\tchar *pal_jump = palColorFor (\"graph.true\");\n\tchar *pal_fail = palColorFor (\"graph.false\");\n\tchar *pal_trfa = palColorFor (\"graph.trufae\");\n\tint nodes = 0;\n\tr_list_foreach (fcn->bbs, iter, bbi) {\n\t\tif (bbi->jump != UT64_MAX) {\n\t\t\tnodes++;\n\t\t\tif (is_keva) {\n\t\t\t\tchar key[128];\n\t\t\t\tchar val[128];\n\t\t\t\tsnprintf (key, sizeof (key), \"bb.0x%08\"PFMT64x\".to\", bbi->addr);\n\t\t\t\tif (bbi->fail != UT64_MAX) {\n\t\t\t\t\tsnprintf (val, sizeof (val), \"0x%08\"PFMT64x, bbi->jump);\n\t\t\t\t} else {\n\t\t\t\t\tsnprintf (val, sizeof (val), \"0x%08\"PFMT64x \",0x%08\"PFMT64x,\n\t\t\t\t\t\t\tbbi->jump, bbi->fail);\n\t\t\t\t}\n\t\t\t\t\/\/ bb..to=,\n\t\t\t\tsdb_set (DB, key, val, 0);\n\t\t\t} else if (is_html) {\n\t\t\t\tr_cons_printf (\"
\\n\"\n\t\t\t\t\t\t\" <\/div>\\n\",\n\t\t\t\t\t\tbbi->addr, bbi->jump);\n\t\t\t} else if (!is_json && !is_keva) {\n\t\t\t\tif (is_star) {\n\t\t\t\t\tchar *from = get_title (bbi->addr);\n\t\t\t\t\tchar *to = get_title (bbi->jump);\n\t\t\t\t\tr_cons_printf (\"age %s %s\\n\", from, to);\n\t\t\t\t\tfree (from);\n\t\t\t\t\tfree (to);\n\t\t\t\t} else {\n\t\t\t\t\tr_strf_buffer (128);\n\t\t\t\t\tconst char* edge_color = bbi->fail != -1 ? pal_jump : pal_trfa;\n\t\t\t\t\tif (sdb_const_get (core->sdb, r_strf (\"agraph.edge.0x%\"PFMT64x\"_0x%\"PFMT64x\".highlight\", bbi->addr, bbi->jump), 0)) {\n\t\t\t\t\t\tedge_color = \"cyan\";\n\t\t\t\t\t}\n\t\t\t\t\tr_cons_printf (\" \\\"0x%08\"PFMT64x\"\\\" -> \\\"0x%08\"PFMT64x\"\\\" \"\n\t\t\t\t\t\t\t\"[color=\\\"%s\\\"];\\n\", bbi->addr, bbi->jump, edge_color);\n\t\t\t\t\tcore_anal_color_curr_node (core, bbi);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (bbi->fail != -1) {\n\t\t\tnodes++;\n\t\t\tif (is_html) {\n\t\t\t\tr_cons_printf (\"
\\n\"\n\t\t\t\t\t\t\" <\/div>\\n\",\n\t\t\t\t\t\tbbi->addr, bbi->fail);\n\t\t\t} else if (!is_keva && !is_json) {\n\t\t\t\tif (is_star) {\n\t\t\t\t\tchar *from = get_title (bbi->addr);\n\t\t\t\t\tchar *to = get_title (bbi->fail);\n\t\t\t\t\tr_cons_printf (\"age %s %s\\n\", from, to);\n\t\t\t\t\tfree(from);\n\t\t\t\t\tfree(to);\n\t\t\t\t} else {\n\t\t\t\t\tr_cons_printf (\" \\\"0x%08\"PFMT64x\"\\\" -> \\\"0x%08\"PFMT64x\"\\\" \"\n\t\t\t\t\t\t\t\t\t\"[color=\\\"%s\\\"];\\n\", bbi->addr, bbi->fail, pal_fail);\n\t\t\t\t\tcore_anal_color_curr_node (core, bbi);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (bbi->switch_op) {\n\t\t\tRAnalCaseOp *caseop;\n\t\t\tRListIter *iter;\n\n\t\t\tif (bbi->fail != UT64_MAX) {\n\t\t\t\tif (is_html) {\n\t\t\t\t\tr_cons_printf (\"
\\n\"\n\t\t\t\t\t\t\t\" <\/div>\\n\",\n\t\t\t\t\t\t\tbbi->addr, bbi->fail);\n\t\t\t\t} else if (!is_keva && !is_json) {\n\t\t\t\t\tif (is_star) {\n\t\t\t\t\t\tchar *from = get_title (bbi->addr);\n\t\t\t\t\t\tchar *to = get_title (bbi->fail);\n\t\t\t\t\t\tr_cons_printf (\"age %s %s\\n\", from, to);\n\t\t\t\t\t\tfree(from);\n\t\t\t\t\t\tfree(to);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tr_cons_printf (\" \\\"0x%08\"PFMT64x\"\\\" -> \\\"0x%08\"PFMT64x\"\\\" \"\n\t\t\t\t\t\t\t\t\"[color=\\\"%s\\\"];\\n\", bbi->addr, bbi->fail, pal_fail);\n\t\t\t\t\t\tcore_anal_color_curr_node (core, bbi);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tr_list_foreach (bbi->switch_op->cases, iter, caseop) {\n\t\t\t\tnodes++;\n\t\t\t\tif (is_keva) {\n\t\t\t\t\tchar key[128];\n\t\t\t\t\tsnprintf (key, sizeof (key),\n\t\t\t\t\t\t\t\"bb.0x%08\"PFMT64x\".switch.%\"PFMT64d,\n\t\t\t\t\t\t\tbbi->addr, caseop->value);\n\t\t\t\t\tsdb_num_set (DB, key, caseop->jump, 0);\n\t\t\t\t\tsnprintf (key, sizeof (key),\n\t\t\t\t\t\t\t\"bb.0x%08\"PFMT64x\".switch\", bbi->addr);\n\t\t\t\t\t\t\tsdb_array_add_num (DB, key, caseop->value, 0);\n\t\t\t\t} else if (is_html) {\n\t\t\t\t\tr_cons_printf (\"
\\n\"\n\t\t\t\t\t\t\t\" <\/div>\\n\",\n\t\t\t\t\t\t\tbbi->addr, caseop->addr);\n\t\t\t\t} else if (!is_json && !is_keva) {\n\t\t\t\t\tif (is_star) {\n\t\t\t\t\t\tchar *from = get_title (bbi->addr);\n\t\t\t\t\t\tchar *to = get_title (caseop->addr);\n\t\t\t\t\t\tr_cons_printf (\"age %s %s\\n\", from ,to);\n\t\t\t\t\t\tfree (from);\n\t\t\t\t\t\tfree (to);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tr_cons_printf (\" \\\"0x%08\" PFMT64x \"\\\" -> \\\"0x%08\" PFMT64x \"\\\" \"\n\t\t\t\t\t\t\t\t\"[color=\\\"%s\\\"];\\n\",\n\t\t\t\t\t\t\t\tbbi->addr, caseop->addr, pal_trfa);\n\t\t\t\t\t\tcore_anal_color_curr_node (core, bbi);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tfree(pal_jump);\n\tfree(pal_fail);\n\tfree(pal_trfa);\n\treturn nodes;\n}","target":0,"code_token_length":1637,"total_token_length":1968,"max_tokens_setting":2048} +{"idx":3578,"func":"static int oidc_handle_session_management_iframe_rp(request_rec *r, oidc_cfg *c,\n\t\toidc_session_t *session, const char *client_id,\n\t\tconst char *check_session_iframe) {\n\n\toidc_debug(r, \"enter\");\n\n\tconst char *java_script =\n\t\t\t\"